async def main():
    # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here.
    conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")

    # The "Authentication Provider" is the object in charge of creating authentication "tokens" for the device client.
    # TODO: open question: do we want async versions of from_connection_string and from_authentication_provider?
    auth_provider = auth.from_connection_string(conn_str)

    # For now, the SDK only supports MQTT as a protocol. the client object is used to interact with your Azure IoT hub.
    # It needs an Authentication Provider to secure the communication with the hub, using either tokens or x509 certificates
    device_client = DeviceClient.from_authentication_provider(
        auth_provider, "mqtt")

    # Connect the client.
    await device_client.connect()

    async def send_test_message(i):
        print("sending message #" + str(i))
        msg = Message("test wind speed " + str(i))
        msg.message_id = uuid.uuid4()
        msg.correlation_id = "correlation-1234"
        msg.custom_properties["tornado-warning"] = "yes"
        await device_client.send_event(msg)
        print("done sending message #" + str(i))

    # send `messages_to_send` messages in parallel
    await asyncio.gather(
        *[send_test_message(i) for i in range(1, messages_to_send + 1)])

    # finally, disconnect
    await device_client.disconnect()
async def create_environ_auth_provider():
    """
    This creates an authentication provider from the system's environment variables.
    """
    env_auth_provider = auth.from_environment()
    device_client_env = DeviceClient.from_authentication_provider(
        env_auth_provider, "mqtt")
    print("Authenticating from system environment...")
    await device_client_env.connect()
    print("Successfully authenticated!")
async def create_symmetric_key_auth_provider():
    """
    This creates an authentication provider from the connection string of the device or module
    """
    key_auth_provider = auth.from_connection_string(
        os.getenv("IOTHUB_DEVICE_CONNECTION_STRING"))
    device_client_key = DeviceClient.from_authentication_provider(
        key_auth_provider, "mqtt")
    print("Authenticating with Device Connection String...")
    await device_client_key.connect()
    print("Successfully authenticated!")
async def create_shared_access_sig_auth_provider():
    """
    This creates an authentication provider from the pre-generated shared access signature of the device or module
    """
    sas_auth_provider = auth.from_shared_access_signature(
        os.getenv("IOTHUB_DEVICE_SAS_STRING"))
    device_client_sas = DeviceClient.from_authentication_provider(
        sas_auth_provider, "mqtt")
    print("Authenticating with SharedAccessSignature string...")
    await device_client_sas.connect()
    print("Successfully authenticated!")
Beispiel #5
0
async def main():
    # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here.
    conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
    # The "Authentication Provider" is the object in charge of creating authentication "tokens" for the device client.
    auth_provider = auth.from_connection_string(conn_str)
    # For now, the SDK only supports MQTT as a protocol. the client object is used to interact with your Azure IoT hub.
    # It needs an Authentication Provider to secure the communication with the hub, using either tokens or x509 certificates
    device_client = DeviceClient.from_authentication_provider(
        auth_provider, "mqtt")

    # connect the client.
    await device_client.connect()

    # define behavior for receiving a C2D message
    async def c2d_listener(device_client):
        while True:
            c2d_message = await device_client.receive_c2d_message(
            )  # blocking call
            print("the data in the message received was ")
            print(c2d_message.data)
            print("custom properties are")
            print(c2d_message.custom_properties)

    # define behavior for halting the application
    def stdin_listener():
        while True:
            selection = input("Press Q to quit\n")
            if selection == "Q" or selection == "q":
                print("Quitting...")
                break

    # Schedule task for C2D Listener
    asyncio.create_task(c2d_listener(device_client))

    # Run the stdin listener in the event loop
    loop = asyncio.get_running_loop()
    user_finished = loop.run_in_executor(None, stdin_listener)

    # Wait for user to indicate they are done listening for messages
    await user_finished

    # Finally, disconnect
    await device_client.disconnect()
 async def client(self, transport):
     return DeviceClient(transport)
Beispiel #7
0
async def main():
    # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here.
    conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
    # The "Authentication Provider" is the object in charge of creating authentication "tokens" for the device client.
    auth_provider = from_connection_string(conn_str)
    # For now, the SDK only supports MQTT as a protocol. the client object is used to interact with your Azure IoT hub.
    # It needs an Authentication Provider to secure the communication with the hub, using either tokens or x509 certificates
    device_client = DeviceClient.from_authentication_provider(
        auth_provider, "mqtt")

    # connect the client.
    await device_client.connect()

    # define behavior for handling methods
    async def method1_listener(device_client):
        while True:
            method_request = await device_client.receive_method(
                "method1")  # Wait for method1 calls
            payload = json.dumps({
                "result": True,
                "data": "some data"
            })  # set response payload
            status = 200  # set return status code
            print("executed method1")
            await device_client.send_method_response(method_request, payload,
                                                     status)  # send response

    async def method2_listener(device_client):
        while True:
            method_request = await device_client.receive_method(
                "method2")  # Wait for method2 calls
            payload = json.dumps({
                "result": True,
                "data": 1234
            })  # set response payload
            status = 200  # set return status code
            print("executed method2")
            await device_client.send_method_response(method_request, payload,
                                                     status)  # send response

    async def generic_method_listener(device_client):
        while True:
            method_request = await device_client.receive_method(
            )  # Wait for unknown method calls
            payload = json.dumps({
                "result": False,
                "data": "unknown method"
            }  # set response payload
                                 )
            status = 400  # set return status code
            print("executed unknown method: " + method_request.name)
            await device_client.send_method_response(method_request, payload,
                                                     status)  # send response

    # define behavior for halting the application
    def stdin_listener():
        while True:
            selection = input("Press Q to quit\n")
            if selection == "Q" or selection == "q":
                print("Quitting...")
                break

    # Schedule tasks for Method Listener
    listeners = asyncio.gather(
        method1_listener(device_client),
        method2_listener(device_client),
        generic_method_listener(device_client),
    )

    # Run the stdin listener in the event loop
    loop = asyncio.get_running_loop()
    user_finished = loop.run_in_executor(None, stdin_listener)

    # Wait for user to indicate they are done listening for method calls
    await user_finished

    # Cancel listening
    listeners.cancel()

    # Finally, disconnect
    await device_client.disconnect()