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_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!")
Example #3
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()
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

import os
import time
import uuid
from azure.iot.hub.devicesdk import DeviceClient, Message
from azure.iot.hub.devicesdk import auth

# 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.
device_client.connect()

# send 5 messages with a 1 second pause between each message
for i in range(0, 5):
    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"