Exemple #1
0
 def connect(self, transport_type, connection_string, cert):
     print("connecting using " + transport_type)
     auth_provider = auth.from_connection_string(connection_string)
     if "GatewayHostName" in connection_string:
         auth_provider.ca_cert = cert
     self.client = IoTHubDeviceClient.from_authentication_provider(
         auth_provider, transport_type)
     self.client.connect()
 def connect(self, transport_type, connection_string, cert):
     print("connecting using " + transport_type)
     auth_provider = auth.from_connection_string(connection_string)
     if "GatewayHostName" in connection_string:
         auth_provider.ca_cert = cert
     self.client = IoTHubModuleClient.from_authentication_provider(
         auth_provider, transport_type
     )
     async_helper.run_coroutine_sync(self.client.connect())
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 = IoTHubDeviceClient.from_authentication_provider(
        key_auth_provider, "mqtt")
    print("Authenticating with Device Connection String...")
    await device_client_key.connect()
    print("Successfully authenticated!")
Exemple #4
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 = IoTHubDeviceClient.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()
Exemple #5
0
# -------------------------------------------------------------------------
# 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.device import IoTHubDeviceClient, Message
from azure.iot.device 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 = IoTHubDeviceClient.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(1, 6):
    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"
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 = IoTHubDeviceClient.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_request(
                "method1")  # Wait for method1 calls
            payload = {
                "result": True,
                "data": "some data"
            }  # set response payload
            status = 200  # set return status code
            print("executed method1")
            method_response = MethodResponse.create_from_method_request(
                method_request, status, payload)
            await device_client.send_method_response(method_response
                                                     )  # send response

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

    async def generic_method_listener(device_client):
        while True:
            method_request = (await device_client.receive_method_request()
                              )  # Wait for unknown method calls
            payload = {
                "result": False,
                "data": "unknown method"
            }  # set response payload
            status = 400  # set return status code
            print("executed unknown method: " + method_request.name)
            method_response = MethodResponse.create_from_method_request(
                method_request, status, payload)
            await device_client.send_method_response(method_response
                                                     )  # 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()