Exemplo n.º 1
0
async def main():
    hostname = os.getenv("HOSTNAME")
    # The device that has been created on the portal using X509 CA signing or Self signing capabilities
    device_id = os.getenv("DEVICE_ID")

    x509 = X509(
        cert_file=os.getenv("X509_CERT_FILE"),
        key_file=os.getenv("X509_KEY_FILE"),
        pass_phrase=os.getenv("X509_PASS_PHRASE"),
    )

    # The client object is used to interact with your Azure IoT hub.
    device_client = IoTHubDeviceClient.create_from_x509_certificate(
        hostname=hostname, device_id=device_id, x509=x509)

    # 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"
        msg.content_encoding = "utf-8"
        msg.content_type = "application/json"
        await device_client.send_message(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, shut down the client
    await device_client.shutdown()
Exemplo n.º 2
0
async def main():
    hostname = IOTHUB_HOSTNAME
    device_id = IOTHUB_DEVICE_ID
    x509 = X509(cert_file=X509_CERT_FILE,
                key_file=X509_KEY_FILE,
                pass_phrase=X509_PASS_PHRASE)

    # Create the Device Client.
    device_client = IoTHubDeviceClient.create_from_x509_certificate(
        hostname=hostname, device_id=device_id, x509=x509)

    # Connect the client.
    await device_client.connect()

    # get the Storage SAS information from IoT Hub.
    blob_name = "fakeBlobName12"
    storage_info = await device_client.get_storage_info_for_blob(blob_name)
    result = {"status_code": -1, "status_description": "N/A"}

    # Using the Storage Blob V12 API, perform the blob upload.
    try:
        upload_result = await upload_via_storage_blob(storage_info)
        if upload_result.error_code:
            result = {
                "status_code": upload_result.error_code,
                "status_description": "Storage Blob Upload Error",
            }
        else:
            result = {"status_code": 200, "status_description": ""}
    except ResourceExistsError as ex:
        if ex.status_code:
            result = {
                "status_code": ex.status_code,
                "status_description": ex.reason
            }
        else:
            print("Failed with Exception: {}", ex)
            result = {"status_code": 400, "status_description": ex.message}

    pp = pprint.PrettyPrinter(indent=4)
    pp.pprint(result)
    if result["status_code"] == 200:
        await device_client.notify_blob_upload_status(
            storage_info["correlationId"], True, result["status_code"],
            result["status_description"])
    else:
        await device_client.notify_blob_upload_status(
            storage_info["correlationId"],
            False,
            result["status_code"],
            result["status_description"],
        )

    # Finally, disconnect
    await device_client.disconnect()
Exemplo n.º 3
0
async def main():
    x509 = X509(
        cert_file=os.getenv("X509_CERT_FILE"),
        key_file=os.getenv("X509_KEY_FILE"),
        pass_phrase=os.getenv("PASS_PHRASE"),
    )

    provisioning_device_client = ProvisioningDeviceClient.create_from_x509_certificate(
        provisioning_host=provisioning_host,
        registration_id=registration_id,
        id_scope=id_scope,
        x509=x509,
    )

    registration_result = await provisioning_device_client.register()

    print("The complete registration result is")
    print(registration_result.registration_state)

    if registration_result.status == "assigned":
        print("Will send telemetry from the provisioned device")
        device_client = IoTHubDeviceClient.create_from_x509_certificate(
            x509=x509,
            hostname=registration_result.registration_state.assigned_hub,
            device_id=registration_result.registration_state.device_id,
        )

        # 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["count"] = i
            msg.custom_properties["tornado-warning"] = "yes"
            await device_client.send_message(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()
    else:
        print("Can not send telemetry from the provisioned device")
Exemplo n.º 4
0
async def main():
    hostname = os.getenv("HOSTNAME")
    # The device that has been created on the portal using X509 CA signing or Self signing capabilities
    device_id = os.getenv("DEVICE_ID")

    x509 = X509(
        cert_file=os.getenv("X509_CERT_FILE"),
        key_file=os.getenv("X509_KEY_FILE"),
        pass_phrase=os.getenv("PASS_PHRASE"),
    )

    # The client object is used to interact with your Azure IoT hub.
    device_client = IoTHubDeviceClient.create_from_x509_certificate(
        hostname=hostname, device_id=device_id, x509=x509
    )

    await device_client.connect()

    # Define behavior for receiving a message
    # NOTE: this could be a function or a coroutine
    def message_received_handler(message):
        print("the data in the message received was ")
        print(message.data)
        print("custom properties are")
        print(message.custom_properties)

    # Set the message received handler on the client
    device_client.on_message_received = message_received_handler

    # 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

    # 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()
Exemplo n.º 5
0
async def main():
    hostname = os.getenv("IOTHUB_HOSTNAME")
    device_id = os.getenv("IOTHUB_DEVICE_ID")
    x509 = X509(
        cert_file=os.getenv("X509_CERT_FILE"),
        key_file=os.getenv("X509_KEY_FILE"),
        pass_phrase=os.getenv("PASS_PHRASE"),
    )

    device_client = IoTHubDeviceClient.create_from_x509_certificate(
        hostname=hostname, device_id=device_id, x509=x509)
    # device_client = IoTHubModuleClient.create_from_connection_string(conn_str)

    # Connect the client.
    await device_client.connect()

    # await device_client.get_storage_info_for_blob("fake_device", "fake_method_params")

    # get the storage sas
    blob_name = "fakeBlobName12"
    storage_info = await device_client.get_storage_info_for_blob(blob_name)

    # upload to blob
    connection = http.client.HTTPSConnection(hostname)
    connection.connect()
    # notify iot hub of blob upload result
    # await device_client.notify_upload_result(storage_blob_result)
    storage_blob_result = await storage_blob(storage_info)
    pp = pprint.PrettyPrinter(indent=4)
    pp.pprint(storage_blob_result)
    connection.close()
    await device_client.notify_blob_upload_status(
        storage_info["correlationId"], True, 200, "fake status description")

    # Finally, disconnect
    await device_client.disconnect()
Exemplo n.º 6
0
async def main():
    hostname = os.getenv("HOSTNAME")
    # The device that has been created on the portal using X509 CA signing or Self signing capabilities
    device_id = os.getenv("DEVICE_ID")

    x509 = X509(
        cert_file=os.getenv("X509_CERT_FILE"),
        key_file=os.getenv("X509_KEY_FILE"),
        pass_phrase=os.getenv("PASS_PHRASE"),
    )

    # The client object is used to interact with your Azure IoT hub.
    device_client = IoTHubDeviceClient.create_from_x509_certificate(
        hostname=hostname, device_id=device_id, x509=x509)

    # define behavior for receiving a message
    async def message_listener(device_client):
        while True:
            message = await device_client.receive_message()  # blocking call
            print("the data in the message received was ")
            print(message.data)
            print("custom properties are")
            print(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 message listener
    asyncio.create_task(message_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()


# if __name__ == "__main__":
#     asyncio.run(main())
#
# CONNECTION_STRING = os.getenv("CONNECTION_STRING", "nostring")
# PATH_TO_FILE = r"[/pythoniot/azure.pdf]"
#
# try:
#    os.environ["CONNECTION_STRING"]
# except KeyError:
#    print ("Please set the connection string via docker environment")
#    sys.exit(1)
#
#
# async def store_blob(blob_info, file_name):
#     try:
#         sas_url = "https://{}/{}/{}{}".format(
#             blob_info["hostName"],
#             blob_info["containerName"],
#             blob_info["blobName"],
#             blob_info["sasToken"]
#         )
#
#         print("\nUploading file: {} to Azure Storage as blob: {} in container {}\n".format(file_name, blob_info["blobName"], blob_info["containerName"]))
#
#         # Upload the specified file
#         with BlobClient.from_blob_url(sas_url) as blob_client:
#             with open(file_name, "rb") as f:
#                 result = blob_client.upload_blob(f, overwrite=True)
#                 return (True, result)
#
#     except FileNotFoundError as ex:
#         # catch file not found and add an HTTP status code to return in notification to IoT Hub
#         ex.status_code = 404
#         return (False, ex)
#
#     except AzureError as ex:
#         # catch Azure errors that might result from the upload operation
#         return (False, ex)
#
# async def main():
#     try:
#         print ( "IoT Hub file upload sample, press Ctrl-C to exit" )
#
#         conn_str = CONNECTION_STRING
#         file_name = PATH_TO_FILE
#         blob_name = os.path.basename(file_name)
#
#         device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)
#
#         # Connect the client
#         await device_client.connect()
#
#         # Get the storage info for the blob
#         storage_info = await device_client.get_storage_info_for_blob(blob_name)
#
#         # Upload to blob
#         success, result = await store_blob(storage_info, file_name)
#
#         if success == True:
#             print("Upload succeeded. Result is: \n")
#             print(result)
#             print()
#
#             await device_client.notify_blob_upload_status(
#                 storage_info["correlationId"], True, 200, "OK: {}".format(file_name)
#             )
#
#         else :
#             # If the upload was not successful, the result is the exception object
#             print("Upload failed. Exception is: \n")
#             print(result)
#             print()
#
#             await device_client.notify_blob_upload_status(
#                 storage_info["correlationId"], False, result.status_code, str(result)
#             )
#
#     except Exception as ex:
#         print("\nException:")
#         print(ex)
#
#     except KeyboardInterrupt:
#         print ( "\nIoTHubDeviceClient sample stopped" )
#
#     finally:
#         # Finally, disconnect the client
#         await device_client.disconnect()
#
#
# if __name__ == "__main__":
#     asyncio.run(main())
#     #loop = asyncio.get_event_loop()
#     #loop.run_until_complete(main())
#     #loop.close()
Exemplo n.º 7
0
    async def auth_and_connect(self):
        if self._isConnected:
            return

        model_id  = self._modelDev.model_id()
        auth_conf = self._modelConfig.auth_props()

        if auth_conf.get(ModelConfigBase.IOTHUB_DEVICE_DPS_AUTH_MODE):
            print ("auth.mode", auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_AUTH_MODE] )
        if self._modelConfig.is_x509_mode():
            x509 = X509(
                cert_file=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_X509_CERT],
                key_file=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_X509_KEY],
                pass_phrase=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_X509_PASS],
            )
            provisioning_device_client = ProvisioningDeviceClient.create_from_x509_certificate(
                provisioning_host=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_ENDPOINT],
                registration_id=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_DEVICE_ID],
                id_scope=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_ID_SCOPE],
                x509=x509,
            )
        else:
            provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
                provisioning_host=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_ENDPOINT],
                registration_id=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_DEVICE_ID],
                id_scope=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_ID_SCOPE],
                symmetric_key=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_DEVICE_KEY]
            )
        provisioning_device_client.provisioning_payload = {
            "modelId": model_id
        }
        try:
            registration_result = await provisioning_device_client.register()
            if registration_result.status != "assigned":
                print("Could not provision device.")
                return ErrorCode.AuthenticationFailed
            else:
                print("Device was assigned")
        except:
            print("Connection error.")
            return ErrorCode.ConnectionFailed

        registration_state = registration_result.registration_state
        print(registration_state.assigned_hub)
        print(registration_state.device_id)
        if self._modelConfig.is_x509_mode():
            x509 = X509(
                cert_file=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_X509_CERT],
                key_file=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_X509_KEY],
                pass_phrase=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_X509_PASS],
            )
            device_client = IoTHubDeviceClient.create_from_x509_certificate(
                x509=x509,
                hostname=registration_state.assigned_hub,
                device_id=registration_state.device_id,
                product_info=model_id,
                connection_retry=False
            )
        else:
            device_client = IoTHubDeviceClient.create_from_symmetric_key(
                symmetric_key=auth_conf[ModelConfigBase.IOTHUB_DEVICE_DPS_DEVICE_KEY],
                hostname=registration_state.assigned_hub,
                device_id=registration_state.device_id,
                product_info=model_id,
                connection_retry=False
            )
        await device_client.connect()
        twin = await device_client.get_twin()
        if 'desired' in twin:
            desiredProps = twin['desired']
            del (desiredProps)['$version']
            for name in iter(desiredProps):
                self._modelDev.set_prop(name, desiredProps[name])
        del (twin['reported'])['$version']
        props = self._modelDev.props()
        if props != twin['reported']:
            await device_client.patch_twin_reported_properties(props)
        device_client.on_method_request_received = self._method_request_handler
        device_client.on_twin_desired_properties_patch_received = self._twin_patch_handler
        device_client.on__message_received = self._message_received_handler
        self._clientHandle = device_client
        self._isConnected  = True

        return ErrorCode.Success
Exemplo n.º 8
0
async def main():
    global device_client
    global device_symmetric_key

    random.seed()
    dps_registered = False
    connected = False
    connection_retry_count = 1
    x509 = None

    while (not connected):  # and (connection_retry_count < 3):
        if use_cached_credentials and os.path.exists('dpsCache.json'):
            dps_cache = read_dps_cache_from_file()
            if dps_cache[2] == device_id:
                dps_registered = True
            else:
                os.remove('dpsCache.json')
                continue
        else:
            if use_x509:  # register the device using the X509 certificate
                current_path = os.path.dirname(os.path.abspath(__file__))
                x509 = X509(cert_file=os.path.join(current_path,
                                                   x509_public_cert_file),
                            key_file=os.path.join(current_path,
                                                  x509_private_cert_file),
                            pass_phrase=x509_pass_phrase)
                provisioning_device_client = ProvisioningDeviceClient.create_from_x509_certificate(
                    provisioning_host=provisioning_host,
                    registration_id=device_id,
                    id_scope=id_scope,
                    x509=x509,
                    websockets=use_websockets)
            else:  # use symmetric key
                if use_group_symmetric_key:  # use group symmetric key to generate a device symmetric key
                    device_symmetric_key = derive_device_key(
                        device_id, group_symmetric_key)

                provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
                    provisioning_host=provisioning_host,
                    registration_id=device_id,
                    id_scope=id_scope,
                    symmetric_key=device_symmetric_key,
                    websockets=use_websockets)

            provisioning_device_client.provisioning_payload = '{"iotcModelId":"%s"}' % (
                model_identity)
            registration_result = None
            try:
                registration_result = await provisioning_device_client.register(
                )
            except exceptions.CredentialError:
                print("Credential Error")
            except exceptions.ConnectionFailedError:
                print("Connection Failed Error")
            except exceptions.ConnectionDroppedError:  # error if the key is wrong
                print("Connection Dropped Error")
            except exceptions.ClientError as inst:  # error if the device is blocked
                print("ClientError")
            except Exception:
                print("Unknown Exception")

            dps_cache = (device_symmetric_key,
                         registration_result.registration_state.assigned_hub,
                         registration_result.registration_state.device_id)
            if use_cached_credentials:
                write_dps_cache_to_file(dps_cache)

            print("The complete registration result is %s" %
                  (registration_result.registration_state))
            if registration_result.status == "assigned":
                dps_registered = True

        if dps_registered:
            if use_x509:  # create device client on IoT Hub using the X509 certificate
                device_client = IoTHubDeviceClient.create_from_x509_certificate(
                    x509=x509,
                    hostname=registration_result.registration_state.
                    assigned_hub,
                    device_id=registration_result.registration_state.device_id,
                )
            else:  # create device client on IoT Hub using a device symmetric key
                device_client = IoTHubDeviceClient.create_from_symmetric_key(
                    symmetric_key=dps_cache[0],
                    hostname=dps_cache[1],
                    device_id=dps_cache[2],
                    websockets=use_websockets)

        # connect to IoT Hub
        try:
            await device_client.connect()
            connected = True
        except:
            print("Connection failed, retry %d of 3" %
                  (connection_retry_count))
            if os.path.exists('dpsCache.json'):
                os.remove('dpsCache.json')
                dps_registered = False
            connection_retry_count = connection_retry_count + 1

    # add desired property listener
    twin_listener = asyncio.create_task(twin_patch_handler(device_client))

    # add direct method listener
    direct_method_listener = asyncio.create_task(
        direct_method_handler(device_client))

    # add C2D listener
    c2d_listener = asyncio.create_task(message_listener(device_client))

    # add tasks to send telemetry (every 5 seconds) and reported properties (every 20, 25, 30 seconds respectively)
    telemetry_loop = asyncio.create_task(send_telemetry(device_client, 5))
    reported_loop1 = asyncio.create_task(
        send_reportedProperty(device_client, "text", "string", 20))
    reported_loop2 = asyncio.create_task(
        send_reportedProperty(device_client, "boolean", "bool", 25))
    reported_loop3 = asyncio.create_task(
        send_reportedProperty(device_client, "number", "number", 30))
    keyboard_loop = asyncio.get_running_loop().run_in_executor(
        None, keyboard_monitor,
        [twin_listener, direct_method_listener, c2d_listener])

    #awit the tasks ending before exiting
    try:
        await asyncio.gather(twin_listener, c2d_listener,
                             direct_method_listener, telemetry_loop,
                             reported_loop1, reported_loop2, reported_loop3,
                             keyboard_loop)
    except asyncio.CancelledError:
        pass  # ignore the cancel actions on twin_listener and direct_method_listener

    # finally, disconnect
    print("Disconnecting from IoT Hub")
    await device_client.disconnect()