async def connect(self):

        try:

            # load the secrets
            secrets = Secrets(self.logger)
            secrets.init()
            self.device_secrets = secrets.get_device_secrets(self.device_name)
            print("here secrets")
            print(self.device_secrets)

            self.device_client = IoTHubDeviceClient.create_from_symmetric_key(
                symmetric_key=self.device_secrets["Device"]["Secrets"]
                ["DeviceSymmetricKey"],
                hostname=self.device_secrets["Device"]["Secrets"]
                ["AssignedHub"],
                device_id=self.device_name,
                websockets=True)
            await self.device_client.connect()
            self.logger.info("[DEVICE CLIENT] %s" % self.device_client)

        except Exception as ex:
            self.logger.error("[ERROR] %s" % ex)
            self.logger.error(
                "[TERMINATING] We encountered an error creating and connecting the device in the Class::DeviceClient"
            )
            return None

        return
    async def connect(self):

        try:

            # Get the device secrets from the Secrets section for Devices, this
            # is captured and written during provisioning
            self.device_secrets = [
                x for x in self.secrets["Devices"]
                if x["Device"]["Name"] == self.device_name
            ]

            if len(self.device_secrets) > 0:

                self.device_client = IoTHubDeviceClient.create_from_symmetric_key(
                    symmetric_key=self.device_secrets[0]["Device"]["Secrets"]
                    ["DeviceSymmetricKey"],
                    hostname=self.device_secrets[0]["Device"]["Secrets"]
                    ["AssignedHub"],
                    device_id=self.device_name,
                    websockets=True)

            await self.device_client.connect()
            self.logger.info("[%s] %s" %
                             (self.class_name_map, self.device_client))

            return

        except Exception as ex:
            self.logger.error("[ERROR] %s" % ex)
            self.logger.error(
                "[TERMINATING] We encountered an error creating and connecting the device for %s"
                % self.class_name_map)
            return None
Ejemplo n.º 3
0
async def device_cloud_connection(device_symmetric_key, id_scope, device_id,
                                  provisioning_host):
    try:
        registration_result = await register_device(device_symmetric_key,
                                                    id_scope, device_id,
                                                    provisioning_host)
        logging.debug(
            f"registration result is: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! {registration_result}"
        )
        try:
            if registration_result.status == 'assigned':
                device_client = IoTHubDeviceClient.create_from_symmetric_key(
                    symmetric_key=device_symmetric_key,
                    hostname=registration_result.registration_state.
                    assigned_hub,
                    device_id=registration_result.registration_state.device_id,
                )
                logging.debug(f"Trying to connect")

                # Connect the client.
                await device_client.connect()
                logging.info('Device connected successfully')
                await device_client.disconnect()
                return device_client
            else:
                logging.debug(
                    f"returning cloud connection device client value : !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
                )
                return False
        except Exception as e:
            logging.warning(f"Error while registering device.. {e} ")

    except Exception as e:
        logging.error(f"Error connecting to Iot Hub..!!! {e}")
        return False
Ejemplo n.º 4
0
async def main():

    # provisions the device to IoT Central-- this uses the Device Provisioning Service behind the scenes
    provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
        provisioning_host=provisioning_host,
        registration_id=registration_id,
        id_scope=id_scope,
        symmetric_key=symmetric_key,
    )

    registration_result = await provisioning_device_client.register()

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

    if registration_result.status == "assigned":
        print(
            "Your device has been provisioned. It will now begin sending telemetry."
        )
        device_client = IoTHubDeviceClient.create_from_symmetric_key(
            symmetric_key=symmetric_key,
            hostname=registration_result.registration_state.assigned_hub,
            device_id=registration_result.registration_state.device_id,
        )

        # Connect the client.
        await device_client.connect()

    # Send the current temperature as a telemetry message
    async def send_telemetry():
        print("Sending telemetry for temperature")

        while True:
            current_temp = random.randrange(
                10, 50)  # Current temperature in Celsius (randomly generated)
            # Send a single temperature report message
            temperature_msg = {"temperature": current_temp}

            msg = Message(json.dumps(temperature_msg))
            msg.content_encoding = "utf-8"
            msg.content_type = "application/json"
            print("Sent message")
            await device_client.send_message(msg)
            await asyncio.sleep(8)

    send_telemetry_task = asyncio.create_task(send_telemetry())

    # 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

    send_telemetry_task.cancel()
    # Finally, shut down the client
    await device_client.disconnect()
async def main():
    async def register_device(registration_id):
        provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
            provisioning_host=provisioning_host,
            registration_id=registration_id,
            id_scope=id_scope,
            symmetric_key=device_ids_to_keys[registration_id],
        )

        return await provisioning_device_client.register()

    results = await asyncio.gather(register_device(device_id_1),
                                   register_device(device_id_2),
                                   register_device(device_id_3))

    clients_to_device_ids = {}

    for index in range(0, len(results)):
        registration_result = results[index]
        print("The complete state of registration result is")
        print(registration_result.registration_state)

        if registration_result.status == "assigned":
            device_id = registration_result.registration_state.device_id

            print(
                "Will send telemetry from the provisioned device with id {id}".
                format(id=device_id))
            device_client = IoTHubDeviceClient.create_from_symmetric_key(
                symmetric_key=device_ids_to_keys[device_id],
                hostname=registration_result.registration_state.assigned_hub,
                device_id=registration_result.registration_state.device_id,
            )
            # Assign the Id just for print statements
            device_client.id = device_id

            clients_to_device_ids[device_id] = device_client

        else:
            print("Can not send telemetry from the provisioned device")

    # connect all the clients
    await asyncio.gather(
        *[client.connect() for client in clients_to_device_ids.values()])

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

    # disconnect all the clients
    await asyncio.gather(
        *[client.disconnect() for client in clients_to_device_ids.values()])
async def connect_device(device_context):
    connection_retry_count = 1
    device_context["connected"] = False

    while (not device_context["connected"]) and (connection_retry_count < 3):
        device_context["device_symmetric_key"] = derive_device_key(
            device_context["device_id"], group_symmetric_key)

        provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
            provisioning_host=provisioning_host,
            registration_id=device_context["device_id"],
            id_scope=scope_id,
            symmetric_key=device_context["device_symmetric_key"],
            websockets=True)

        # DPS payload contains the model_id of the leaf device and the gateway identity to connect them to
        provisioning_device_client.provisioning_payload = (
            '{{"iotcModelId":"{}", "iotcGateway":{{"iotcGatewayId": "{}" }}}}'
        ).format(leaf_model_identity, gateway_id)
        device_context["registration_result"] = None
        try:
            device_context[
                "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")

        if device_context["registration_result"] != None:
            print("The complete registration result is {}".format(
                device_context["registration_result"].registration_state))
            if device_context["registration_result"].status == "assigned":
                device_context[
                    "device_client"] = IoTHubDeviceClient.create_from_symmetric_key(
                        symmetric_key=device_context["device_symmetric_key"],
                        hostname=device_context["registration_result"].
                        registration_state.assigned_hub,
                        device_id=device_context["device_id"],
                        websockets=True)

        # connect to IoT Hub
        try:
            await device_context["device_client"].connect()
            device_context["connected"] = True
        except:
            print("Connection failed, retry {} of 3".format(
                connection_retry_count))
            connection_retry_count = connection_retry_count + 1
Ejemplo n.º 7
0
 async def connect_device():
     device_client = None
     try:
       registration_result = await register_device()
       if registration_result.status == 'assigned':
         device_client = IoTHubDeviceClient.create_from_symmetric_key(
           symmetric_key=symmetric_key,
           hostname=registration_result.registration_state.assigned_hub,
           device_id=registration_result.registration_state.device_id,
         )
         # Connect the client.
         await device_client.connect()
         print('Device connected successfully')
     finally:
       return device_client
Ejemplo n.º 8
0
async def main():

    # This should ony be done once for every Device

    # vlaues from rest call - Create device
    provisioning_host = "global.azure-devices-provisioning.net"
    id_scope = "*************"
    deviceId = "*********************"
    primarykey = "*******************"

    # Provision device
    provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
        provisioning_host=provisioning_host,
        registration_id=deviceId,
        id_scope=id_scope,
        symmetric_key=primarykey,
    )

    registration_result = await provisioning_device_client.register()
    print(registration_result)

    # Creating a client for sending data
    if registration_result.status == "assigned":
        print("Provisioned the device")
        device_client = IoTHubDeviceClient.create_from_symmetric_key(
            symmetric_key=primarykey,
            hostname=registration_result.registration_state.assigned_hub,
            device_id=registration_result.registration_state.device_id,
        )

    # Connect the client.
    await device_client.connect()
    msgData = '{"PeriodFrom":"2020-10-16T07:49:00Z","PeriodTo":"2020-10-16T07:50:00Z","AveragePowerConsumptionInKW":0.0,"AveragePowerGenerationInKW":27.0}'
    msg = Message(msgData,
                  message_id=None,
                  content_encoding="utf-8",
                  content_type="application/json",
                  output_name=None)
    await device_client.send_message(msg)

    print("Send message to AssetHUB")

    await device_client.disconnect()
async def connect_iotc_device() -> IoTCClient:
    log: logging.Logger = app_logger.get_logger()
    device_client = None
    #asyncio.sleep(0)
    registration_result = await register_device()
    if registration_result.status == 'assigned':
        try:
            device_client = IoTHubDeviceClient.create_from_symmetric_key(
                symmetric_key=credentials.symmetric_key,
                hostname=registration_result.registration_state.assigned_hub,
                device_id=registration_result.registration_state.device_id,
            )
            #device_client = IoTCClient(credentials.device_id, credentials.id_scope, IOTCConnectType.IOTC_CONNECT_DEVICE_KEY, credentials.symmetric_key)
            await device_client.connect()
            log.info('Connected to IoTCentral')
        except Exception as e:
            s = e
            log.error("Error Connecting to IoTCentral: {e}")
        finally:
            return device_client
Ejemplo n.º 10
0
async def main():
    provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
        provisioning_host=provisioning_host,
        registration_id=registration_id,
        id_scope=id_scope,
        symmetric_key=symmetric_key,
    )

    properties = {"House": "Gryffindor", "Muggle-Born": "False"}
    wizard_a = Wizard("Harry", "Potter", properties)
    provisioning_device_client.provisioning_payload = wizard_a
    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_symmetric_key(
            symmetric_key=symmetric_key,
            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()
            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")
async def main():
    provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
        provisioning_host=provisioning_host,
        registration_id=registration_id,
        id_scope=id_scope,
        symmetric_key=symmetric_key,
    )

    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_symmetric_key(
            symmetric_key=symmetric_key,
            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")
Ejemplo n.º 12
0
async def main():
    provisioning_host = "global.azure-devices-provisioning.net"
    id_scope = os.getenv("IOTHUB_DEVICE_DPS_ID_SCOPE")
    registration_id = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_ID")
    symmetric_key = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_KEY")

    # Check to see if they have dps id_scope, dps device_key, and dps device_id
    # filled out correctly..
    if (id_scope is None or id_scope == '<Your Scope Here...>' or 
        symmetric_key is None or symmetric_key == '<Your Key Here...>' or
        registration_id is None or registration_id == '<Your Device ID Here...>'):
        raise ValueError(
            'Make sure you have your device environment variables setup correctly! ' 
            'See https://github.com/jamisonderek/waterconsumption#obtaining-your-device-values')

    registration_result = await provision_device(
        provisioning_host, id_scope, registration_id, symmetric_key, model_id
    )

    if registration_result.status == "assigned":
        print("Device was assigned")
        print(registration_result.registration_state.assigned_hub)
        print(registration_result.registration_state.device_id)

        device_client = IoTHubDeviceClient.create_from_symmetric_key(
            symmetric_key=symmetric_key,
            hostname=registration_result.registration_state.assigned_hub,
            device_id=registration_result.registration_state.device_id,
            product_info=model_id,
        )
    else:
        raise RuntimeError(
            "Could not provision device. Aborting Plug and Play device connection."
        )

    # Connect the client.
    await device_client.connect()

    iot_device = HybridDevice()
    iot_device.turn_valve_off()

    ################################################
    # Register callback and Handle command (reboot)

    print("Listening for command requests and property updates")
    command_listener = CommandListener(device_client, iot_device)

    ################################################
    # Send telemetry 

    async def send_telemetry():
        minute = datetime.now().minute

        while True:
            message = iot_device.get_telemetry()
            message.pop("Valve")
            await send_telemetry_from_smart_valve(device_client, message)

            # Delay, so we only send telemetry data once per minute.
            while datetime.now().minute == minute:
                await asyncio.sleep(2) # wait 2 seconds
            minute = datetime.now().minute            

    async def send_valve_telemetry():
        last_valve_data = None

        while True:
            valve = iot_device.get_valve()
            if valve != last_valve_data:
                last_valve_data = valve
                if (valve == ValveState.closed):
                    message = {"Valve": "ValveState.closed"}
                else:
                    message = {"Valve": "ValveState.open"}
                await send_telemetry_from_smart_valve(device_client, message)

            await asyncio.sleep(5) # Update the flow data every 5 seconds.

    async def twin_patch_handler(patch):
        print("the data in the desired properties patch was: {0}".format(patch))
        if "DeviceLocation" in patch:
            iot_device.set_location(patch["DeviceLocation"])
       
        ignore_keys = ["__t", "$version"]
        version = patch["$version"]
        prop_dict = {}

        for prop_name, prop_value in patch.items():
            if prop_name in ignore_keys:
                continue
            else:
                prop_dict[prop_name] = {
                    "ac": 200,
                    "ad": "Successfully executed patch",
                    "av": version,
                    "value": prop_value,
                }

        await device_client.patch_twin_reported_properties(prop_dict)

    device_client.on_twin_desired_properties_patch_received = twin_patch_handler

    twin = await device_client.get_twin()
    print("the twin was: {0}".format(twin))
    if "desired" in twin:
        twin = twin["desired"]
        if "DeviceLocation" in twin:
            iot_device.set_location(twin["DeviceLocation"])

    # Allow time for device to stablize before starting telemetry
    await asyncio.sleep(10) 
    send_telemetry_task = asyncio.create_task(send_telemetry())
    send_valve_telemetry_task = asyncio.create_task(send_valve_telemetry())

    # Run the stdin listener in the event loop
    loop = asyncio.get_running_loop()

    # Wait for user to indicate they are done listening for method calls
    user_finished = loop.run_in_executor(None, stdin_listener)
    await user_finished

    send_telemetry_task.cancel()
    send_valve_telemetry_task.cancel()

    # Finally, shut down the client
    await device_client.shutdown()
Ejemplo n.º 13
0
async def main():
    global pnp_client

    if not check_environment_variables():
        return 1

    symmeticKey = SYMMETRIC_KEY
    # Create the device_client.
    if SECURITY_TYPE == "DPS":
        registration_result = await provision_device(DPS_DEVICE_ENDPOINT_HOST,
                                                     ID_SCOPE, REGISTRATION_ID,
                                                     SYMMETRIC_KEY, MODEL_ID)

        if registration_result == None:
            symmeticKey = generate_device_key(REGISTRATION_ID, SYMMETRIC_KEY)

            registration_result = await provision_device(
                DPS_DEVICE_ENDPOINT_HOST, ID_SCOPE, REGISTRATION_ID,
                symmeticKey, MODEL_ID)

        if registration_result.status == "assigned":
            print("Device was assigned.")
            print(
                f'IoT Hub   : {registration_result.registration_state.assigned_hub}'
            )
            print(
                f'Device ID : {registration_result.registration_state.device_id}'
            )

            device_client = IoTHubDeviceClient.create_from_symmetric_key(
                symmetric_key=symmeticKey,
                hostname=registration_result.registration_state.assigned_hub,
                device_id=registration_result.registration_state.device_id,
                product_info=MODEL_ID,
            )
        else:
            print(
                "ERROR: Could not provision device. Aborting Plug and Play device connection.",
                file=sys.stderr)
            return 1

    elif SECURITY_TYPE == "connectionString":
        print(f"Connecting using Connection String {DEVICE_CONNECTION_STRING}")
        device_client = IoTHubDeviceClient.create_from_connection_string(
            DEVICE_CONNECTION_STRING, product_info=MODEL_ID)

    else:
        print(
            "ERROR: At least one choice needs to be made for complete functioning of this sample.",
            file=sys.stderr)
        return 1

    # Create the pnp client.
    pnp_client = MjClient()
    pnp_client.acceleration = MjCont.Telemetry()
    pnp_client.ambientLight = MjCont.Telemetry()
    pnp_client.f1Button = MjCont.Telemetry()
    pnp_client.f2Button = MjCont.Telemetry()
    pnp_client.f3Button = MjCont.Telemetry()
    pnp_client.oButton = MjCont.Telemetry()
    pnp_client.ringBuzzer = RingBuzzerCommand()
    pnp_client.ledStaGreen = StaLedGreenProperty()
    pnp_client.ledStaRed = StaLedRedProperty()
    pnp_client.usrLed = UsrLedProperty()
    pnp_client.firmwareVer = MjCont.ReadOnlyProperty()
    pnp_client.telemetryInterval = TelemetryIntervalProperty()

    pnp_client.firmwareVer.value = FIRMWARE_VERSION

    # Connect the client.
    pnp_client.set_iot_hub_device_client(device_client)
    await pnp_client.connect()

    # Assign acceleration and button events.
    accel_device = rt.get_acceleration_device()
    btn_device = rt.get_button_device()
    asyncio.ensure_future(accel_coroutine(accel_device))
    asyncio.ensure_future(btn_coroutine(btn_device))

    # Assign the send_telemetry_acceleration task.
    send_telemetry_acceleration_task = asyncio.create_task(
        send_telemetry_acceleration_loop())

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

    await device_client.disconnect()

    # Cleanup.
    send_telemetry_acceleration_task.cancel()
    await device_client.shutdown()

    return 0
Ejemplo n.º 14
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
Ejemplo n.º 15
0
async def main():
    switch = os.getenv("IOTHUB_DEVICE_SECURITY_TYPE")
    if switch == "DPS":
        provisioning_host = os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT")
        id_scope = os.getenv("IOTHUB_DEVICE_DPS_ID_SCOPE")
        registration_id = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_ID")
        symmetric_key = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_KEY")

        registration_result = await provision_device(
            provisioning_host, id_scope, registration_id, symmetric_key, model_id
        )

        if registration_result.status == "assigned":
            device_client = IoTHubDeviceClient.create_from_symmetric_key(
                symmetric_key=symmetric_key,
                hostname=registration_result.registration_state.assigned_hub,
                device_id=registration_result.registration_state.device_id,
            )
        else:
            raise RuntimeError("Could not provision device. Aborting PNP device connection.")
    else:
        conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
        print("Connecting using Connection String " + conn_str)
        device_client = IoTHubDeviceClient.create_from_connection_string(
            conn_str, product_info=model_id
        )

    # Connect the client.
    await device_client.connect()

    ################################################
    # Set and read desired property (target temperature)

    asyncio.create_task(
        device_client.patch_twin_reported_properties({"maxTempSinceLastReboot": maxTemp})
    )

    ################################################
    # Register callback and Handle command (reboot)
    print("Listening for command requests and property updates")

    async def execute_property_listener():
        ignore_keys = ["__t", "$version"]
        while True:
            patch = await device_client.receive_twin_desired_properties_patch()  # blocking call
            print("the data in the desired properties patch was: {}".format(patch))

            component_prefix = list(patch.keys())[0]
            values = patch[component_prefix]
            print("previous values")
            print(values)

            version = patch["$version"]
            inner_dict = {}

            for prop_name, prop_value in values.items():
                if prop_name in ignore_keys:
                    continue
                else:
                    inner_dict["ac"] = 200
                    inner_dict["ad"] = "Successfully executed patch"
                    inner_dict["av"] = version
                    inner_dict["value"] = prop_value
                    values[prop_name] = inner_dict

            iotin_dict = dict()
            if component_prefix:
                iotin_dict[component_prefix] = values
                # print(iotin_dict)
            else:
                iotin_dict = values

            await device_client.patch_twin_reported_properties(iotin_dict)

    listeners = asyncio.gather(
        execute_command_listener(
            device_client,
            method_name="reboot",
            user_command_handler=reboot_handler,
            create_user_response_handler=create_reboot_response,
        ),
        execute_command_listener(
            device_client,
            method_name="getMaxMinReport",
            user_command_handler=max_min_handler,
            create_user_response_handler=create_max_min_report_response,
        ),
        execute_property_listener(),
    )

    ################################################
    # Send telemetry (current temperature)

    async def send_telemetry():
        print("Sending telemetry for temperature")
        global maxTemp
        global minTemp
        currentAvgIdx = 0

        while True:
            currentTemp = random.randrange(10, 50)  # Current temperature in Celsius
            if not maxTemp:
                maxTemp = currentTemp
            elif currentTemp > maxTemp:
                maxTemp = currentTemp

            if not minTemp:
                minTemp = currentTemp
            elif currentTemp < minTemp:
                minTemp = currentTemp

            avgTempList[currentAvgIdx] = currentTemp
            currentAvgIdx = (currentAvgIdx + 1) % sizeOfMovingWindow

            temperature_msg1 = {"temperature": currentTemp}
            await send_telemetry_from_thermostat(device_client, temperature_msg1)
            await asyncio.sleep(8)

    send_telemetry_task = asyncio.create_task(send_telemetry())

    # 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

    if not listeners.done():
        listeners.set_result("DONE")

    listeners.cancel()

    send_telemetry_task.cancel()

    # finally, disconnect
    await device_client.disconnect()
Ejemplo n.º 16
0
async def main():
    provisioning_host = "global.azure-devices-provisioning.net"
    id_scope = os.getenv("IOTHUB_DEVICE_DPS_ID_SCOPE")
    registration_id = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_ID")
    symmetric_key = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_KEY")

    registration_result = await provision_device(
        provisioning_host, id_scope, registration_id, symmetric_key, model_id
    )

    if registration_result.status == "assigned":
        print("Device was assigned")
        print(registration_result.registration_state.assigned_hub)
        print(registration_result.registration_state.device_id)

        device_client = IoTHubDeviceClient.create_from_symmetric_key(
            symmetric_key=symmetric_key,
            hostname=registration_result.registration_state.assigned_hub,
            device_id=registration_result.registration_state.device_id,
            product_info=model_id,
        )
    else:
        raise RuntimeError(
            "Could not provision device. Aborting Plug and Play device connection."
        )


    # Connect the client.
    await device_client.connect()

    # TODO: Replace with real device.
    iot_device = SimulatedDevice()

    ################################################
    # Set and read desired property (target temperature)

    #await device_client.patch_twin_reported_properties({"maxTempSinceLastReboot": max_temp})

    ################################################
    # Register callback and Handle command (reboot)
    print("Listening for command requests and property updates")

    listeners = asyncio.gather(
        execute_command_listener(
            device_client,
            iot_device,
            method_name="turnValveOn",
            user_command_handler=turn_valve_on_handler,
            create_user_response_handler=turn_valve_on_response,
        ),
        execute_command_listener(
            device_client,
            iot_device,
            method_name="turnValveOff",
            user_command_handler=turn_valve_off_handler,
            create_user_response_handler=turn_valve_off_response,
        ),
        execute_property_listener(device_client),
    )

    ################################################
    # Send telemetry 

    async def send_telemetry():
        print("Sending telemetry for smart valve")
        sent_valve_data = False

        while True:
            await asyncio.sleep(15)
            message = iot_device.get_telemetry()
            if sent_valve_data:
                message.pop("Valve")  # Remove the Valve data, since we already sent that information.
            else:
                sent_valve_data = True
            await send_telemetry_from_smart_valve(device_client, message)

    send_telemetry_task = asyncio.create_task(send_telemetry())

    # Run the stdin listener in the event loop
    loop = asyncio.get_running_loop()

    # Wait for user to indicate they are done listening for method calls
    user_finished = loop.run_in_executor(None, stdin_listener)
    await user_finished

    if not listeners.done():
        listeners.set_result("DONE")

    listeners.cancel()

    send_telemetry_task.cancel()

    # Finally, shut down the client
    await device_client.shutdown()
async def main():
    switch = os.getenv("IOTHUB_DEVICE_SECURITY_TYPE")
    if switch == "DPS":
        provisioning_host = (os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT")
                             if os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT") else
                             "global.azure-devices-provisioning.net")
        id_scope = os.getenv("IOTHUB_DEVICE_DPS_ID_SCOPE")
        registration_id = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_ID")
        symmetric_key = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_KEY")

        registration_result = await provision_device(provisioning_host,
                                                     id_scope, registration_id,
                                                     symmetric_key, model_id)

        if registration_result.status == "assigned":
            print("Device was assigned")
            print(registration_result.registration_state.assigned_hub)
            print(registration_result.registration_state.device_id)

            device_client = IoTHubDeviceClient.create_from_symmetric_key(
                symmetric_key=symmetric_key,
                hostname=registration_result.registration_state.assigned_hub,
                device_id=registration_result.registration_state.device_id,
                product_info=model_id,
            )
        else:
            raise RuntimeError(
                "Could not provision device. Aborting Plug and Play device connection."
            )

    elif switch == "connectionString":
        conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
        ca_cert = os.getenv("IOTEDGE_ROOT_CA_CERT_PATH")
        certfile = open(ca_cert)
        root_ca_cert = certfile.read()
        print("Connecting using Connection String " + conn_str)
        device_client = IoTHubDeviceClient.create_from_connection_string(
            conn_str,
            product_info=model_id,
            server_verification_cert=root_ca_cert)
    else:
        raise RuntimeError(
            "At least one choice needs to be made for complete functioning of this sample."
        )

    # Connect the client.
    await device_client.connect()

    ################################################
    # Set and read desired property (target temperature)

    max_temp = 10.96  # Initial Max Temp otherwise will not pass certification
    await device_client.patch_twin_reported_properties(
        {"maxTempSinceLastReboot": max_temp})

    ################################################
    # Register callback and Handle command (reboot)
    print("Listening for command requests and property updates")

    listeners = asyncio.gather(
        execute_command_listener(
            device_client,
            method_name="reboot",
            user_command_handler=reboot_handler,
            create_user_response_handler=create_reboot_response,
        ),
        execute_command_listener(
            device_client,
            method_name="getMaxMinReport",
            user_command_handler=max_min_handler,
            create_user_response_handler=create_max_min_report_response,
        ),
        execute_property_listener(device_client),
    )

    ################################################
    # Send telemetry (current temperature)
    async def send_telemetry():
        print("Sending telemetry for temperature")
        global max_temp
        global min_temp
        current_avg_idx = 0

        while True:
            current_temp = random.randrange(
                10, 50)  # Current temperature in Celsius
            if not max_temp:
                max_temp = current_temp
            elif current_temp > max_temp:
                max_temp = current_temp

            if not min_temp:
                min_temp = current_temp
            elif current_temp < min_temp:
                min_temp = current_temp

            avg_temp_list[current_avg_idx] = current_temp
            current_avg_idx = (current_avg_idx + 1) % moving_window_size

            temperature_msg1 = {"temperature": current_temp}
            await send_telemetry_from_thermostat(device_client,
                                                 temperature_msg1)
            await asyncio.sleep(8)

    loop = asyncio.get_event_loop()
    send_telemetry_task = loop.create_task(send_telemetry())

    # 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

    if not listeners.done():
        listeners.set_result("DONE")

    listeners.cancel()

    send_telemetry_task.cancel()

    # Finally, shut down the client
    await device_client.shutdown()
Ejemplo n.º 18
0
async def main():
    print("HancomMDS Inc. Azure-IoT General Device")
    switch = os.getenv("IOTHUB_DEVICE_SECURITY_TYPE")
    switch = "DPS"
    if switch == "DPS":
        provisioning_host = (os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT")
                             if os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT") else
                             "global.azure-devices-provisioning.net")
        id_scope = os.getenv("IOTHUB_DEVICE_DPS_ID_SCOPE")
        registration_id = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_ID")
        symmetric_key = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_KEY")

        print(
            '[DEBUG] id_scope={id},\n > registration_id={rid}\n > symmetric_key={skey}'
            .format(id=id_scope, rid=registration_id, skey=symmetric_key))

        registration_result = await provision_device(provisioning_host,
                                                     id_scope, registration_id,
                                                     symmetric_key, model_id)

        if registration_result.status == "assigned":
            print("Device was assigned")
            print(registration_result.registration_state.assigned_hub)
            print(registration_result.registration_state.device_id)

            device_client = IoTHubDeviceClient.create_from_symmetric_key(
                symmetric_key=symmetric_key,
                hostname=registration_result.registration_state.assigned_hub,
                device_id=registration_result.registration_state.device_id,
                product_info=model_id,
            )
        else:
            raise RuntimeError(
                "Could not provision device. Aborting Plug and Play device connection."
            )

    elif switch == "connectionString":
        conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
        print("Connecting using Connection String " + conn_str)
        device_client = IoTHubDeviceClient.create_from_connection_string(
            conn_str, product_info=model_id)
    else:
        raise RuntimeError(
            "At least one choice needs to be made for complete functioning of this sample."
        )

    # Connect the client.
    await device_client.connect()

    OS_SYSTEM = platform.system()
    MACHINE = platform.machine()

    # Command Listener
    # For Multiple components
    if OS_SYSTEM == "Windows":
        listeners = asyncio.gather(
            execute_command_listener(
                device_client,
                windows_device_info_component_name,
                method_name="reboot",
                user_command_handler=reboot_handler,
                create_user_response_handler=create_reboot_response,
            ),
            execute_command_listener(
                device_client,
                windows_device_info_component_name,
                method_name="setperiod",
                user_command_handler=setperiod_handler,
                create_user_response_handler=create_setperiod_response,
            ),
        )
    elif OS_SYSTEM == "Linux":
        listeners = asyncio.gather(
            execute_command_listener(
                device_client,
                linux_device_info_component_name,
                method_name="reboot",
                user_command_handler=reboot_handler,
                create_user_response_handler=create_reboot_response,
            ),
            execute_command_listener(
                device_client,
                linux_device_info_component_name,
                method_name="setperiod",
                user_command_handler=setperiod_handler,
                create_user_response_handler=create_setperiod_response,
            ),
        )

    await property_update(device_client, OS_SYSTEM, MACHINE)
    telemetery_update_task = asyncio.create_task(
        telemetery_update(device_client, OS_SYSTEM, MACHINE))

    loop = asyncio.get_running_loop()
    end = loop.run_in_executor(None, end_listener)
    await end

    if not listeners.done():
        listeners.set_result("DONE")

    # For Multiple components
    if not property_updates.done():
        property_updates.set_result("DONE")

    listeners.cancel()
    # For Multiple components
    property_updates.cancel()

    telemetery_update_task.cancel()

    # finally, disconnect
    await device_client.disconnect()
Ejemplo n.º 19
0
async def main():
    switch = os.getenv("IOTHUB_DEVICE_SECURITY_TYPE")
    if switch == "DPS":
        provisioning_host = (os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT")
                             if os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT") else
                             "global.azure-devices-provisioning.net")
        id_scope = os.getenv("IOTHUB_DEVICE_DPS_ID_SCOPE")
        registration_id = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_ID")
        symmetric_key = os.getenv("IOTHUB_DEVICE_DPS_DEVICE_KEY")

        registration_result = await provision_device(provisioning_host,
                                                     id_scope, registration_id,
                                                     symmetric_key, model_id)

        if registration_result.status == "assigned":
            print("Device was assigned")
            print(registration_result.registration_state.assigned_hub)
            print(registration_result.registration_state.device_id)
            device_client = IoTHubDeviceClient.create_from_symmetric_key(
                symmetric_key=symmetric_key,
                hostname=registration_result.registration_state.assigned_hub,
                device_id=registration_result.registration_state.device_id,
                product_info=model_id,
            )
        else:
            raise RuntimeError(
                "Could not provision device. Aborting Plug and Play device connection."
            )

    elif switch == "connectionString":
        conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
        print("Connecting using Connection String " + conn_str)
        device_client = IoTHubDeviceClient.create_from_connection_string(
            conn_str, product_info=model_id)
    else:
        raise RuntimeError(
            "At least one choice needs to be made for complete functioning of this sample."
        )

    # Connect the client.
    await device_client.connect()

    ################################################
    # Update readable properties from various components

    properties_root = pnp_helper.create_reported_properties(
        serialNumber=serial_number)
    properties_thermostat1 = pnp_helper.create_reported_properties(
        thermostat_1_component_name, maxTempSinceLastReboot=98.34)
    properties_thermostat2 = pnp_helper.create_reported_properties(
        thermostat_2_component_name, maxTempSinceLastReboot=48.92)
    properties_device_info = pnp_helper.create_reported_properties(
        device_information_component_name,
        swVersion="5.5",
        manufacturer="Contoso Device Corporation",
        model="Contoso 4762B-turbo",
        osName="Mac Os",
        processorArchitecture="x86-64",
        processorManufacturer="Intel",
        totalStorage=1024,
        totalMemory=32,
    )

    property_updates = asyncio.gather(
        device_client.patch_twin_reported_properties(properties_root),
        device_client.patch_twin_reported_properties(properties_thermostat1),
        device_client.patch_twin_reported_properties(properties_thermostat2),
        device_client.patch_twin_reported_properties(properties_device_info),
    )

    ################################################
    # Get all the listeners running
    print("Listening for command requests and property updates")

    global THERMOSTAT_1
    global THERMOSTAT_2
    THERMOSTAT_1 = Thermostat(thermostat_1_component_name, 10)
    THERMOSTAT_2 = Thermostat(thermostat_2_component_name, 10)

    listeners = asyncio.gather(
        execute_command_listener(device_client,
                                 method_name="reboot",
                                 user_command_handler=reboot_handler),
        execute_command_listener(
            device_client,
            thermostat_1_component_name,
            method_name="getMaxMinReport",
            user_command_handler=max_min_handler,
            create_user_response_handler=create_max_min_report_response,
        ),
        execute_command_listener(
            device_client,
            thermostat_2_component_name,
            method_name="getMaxMinReport",
            user_command_handler=max_min_handler,
            create_user_response_handler=create_max_min_report_response,
        ),
        execute_property_listener(device_client),
    )

    ################################################
    # Function to send telemetry every 8 seconds
    async def send_telemetry():
        print("Sending telemetry from various components")

        while True:
            curr_temp_ext = random.randrange(10, 50)
            THERMOSTAT_1.record(curr_temp_ext)

            temperature_msg1 = {"temperature": curr_temp_ext}
            await send_telemetry_from_temp_controller(
                device_client, temperature_msg1, thermostat_1_component_name)

            curr_temp_int = random.randrange(
                10, 50)  # Current temperature in Celsius
            THERMOSTAT_2.record(curr_temp_int)

            temperature_msg2 = {"temperature": curr_temp_int}

            await send_telemetry_from_temp_controller(
                device_client, temperature_msg2, thermostat_2_component_name)

            workingset_msg3 = {"workingSet": random.randrange(1, 100)}
            await send_telemetry_from_temp_controller(device_client,
                                                      workingset_msg3)

    send_telemetry_task = asyncio.ensure_future(send_telemetry())

    # 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

    if not listeners.done():
        listeners.set_result("DONE")

    if not property_updates.done():
        property_updates.set_result("DONE")

    listeners.cancel()
    property_updates.cancel()

    send_telemetry_task.cancel()

    # Finally, shut down the client
    await device_client.shutdown()
Ejemplo n.º 20
0
async def main():

    # Connect using Device Provisioning Service (DPS)
    device_key = derive_device_key(
        registration_id, symmetric_key
    )  #Convert from original symmetric key to device key for further enrollment
    #print(device_key)
    provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
        provisioning_host=provisioning_host,
        registration_id=registration_id,
        id_scope=id_scope,
        symmetric_key=device_key)
    registration_result = await provisioning_device_client.register()
    print("The Provision Status is :", registration_result.status)
    print("The Provisioned ID is: ",
          registration_result.registration_state.device_id)
    print("The Assigned IoT Hub is: ",
          registration_result.registration_state.assigned_hub)
    print("The eTag is :", registration_result.registration_state.etag)

    if registration_result.status == "assigned":
        print(
            "Provisioning Sucessfully, will send telemetry from the provisioned device now!"
        )
        device_client = IoTHubDeviceClient.create_from_symmetric_key(
            symmetric_key=device_key,
            hostname=registration_result.registration_state.assigned_hub,
            device_id=registration_result.registration_state.device_id,
        )

        # Connect the client.
        await device_client.connect()

    # Update Device Information on Start
    await device_client.patch_twin_reported_properties(device_property)
    await device_client.patch_twin_reported_properties(location)

    # define method handler
    async def method_request_handler(method_request):
        if method_request.name == "SetTelementryInternal":
            global telemetry_interval
            print(
                str(datetime.datetime.now()),
                "Recevied Request \"SetTelementryInternal\", Setting Interval to: "
                + str(telemetry_interval))
            telemetry_interval = method_request.payload["Telemetry_Interval"]
            # set response payload
            payload = {
                "Time":
                str(datetime.datetime.now()),
                "CallbackStatus":
                "200 OK",
                "CallbackPayload":
                "The Interval is now: " + str(telemetry_interval)
            }
            status = 200  # set return status code
            print(
                str(datetime.datetime.now()),
                "Processing Request \"SetTelementryInternal\" and Report, The Interval is now: "
                + str(telemetry_interval))
            method_response = MethodResponse.create_from_method_request(
                method_request, status, payload)
            # send response
            await device_client.send_method_response(method_response)

            device_property_new_interval = {
                'Telemetry_Interval': telemetry_interval
            }
            await device_client.patch_twin_reported_properties(
                device_property_new_interval)

        elif method_request.name == "SetTelemetrySwitch":
            global send_data
            send_data = method_request.payload
            print(
                str(datetime.datetime.now()),
                "Recevied Request \"SetTelemetrySwitch\", Setting Send_Data Switch to: "
                + str(send_data))
            payload = {
                "Time": str(datetime.datetime.now()),
                "CommandStatus": "200 OK",
                "CommandCallback": "The Send Data Status is: " + str(send_data)
            }
            status = 200  # set return status code
            print(
                str(datetime.datetime.now()),
                "Processing Request \"SetTelemetrySwitch\" and Report, The Send_Data Status is "
                + str(send_data))
            method_response = MethodResponse.create_from_method_request(
                method_request, status, payload)
            # send response
            await device_client.send_method_response(method_response)

            device_property_new_switch = {'Telemetry_Switch': send_data}
            await device_client.patch_twin_reported_properties(
                device_property_new_switch)

        else:
            # set response payload
            payload = {"result": False, "data": "Unrecognized Method"}
            status = 400  # set return status code
            print(str(datetime.datetime.now()),
                  "Receiving Unknown Method: " + method_request.name)
            method_response = MethodResponse.create_from_method_request(
                method_request, status, payload)
            # send response
            await device_client.send_method_response(method_response)

    async def twin_patch_handler(data):
        global fw_info
        fw_info_new = data["Firmware_Info"]["value"]
        print(
            str(datetime.datetime.now()),
            "Received Firmware Upgrade Request: Version " + str(fw_info_new) +
            ", Initialiazing...")
        time.sleep(2)
        if fw_info >= fw_info_new:
            print(
                str(datetime.datetime.now()),
                "The Firmware Version is Latest, Firmware Upgrade Cancelled")

        if fw_info < fw_info_new:
            print(str(datetime.datetime.now()),
                  "Step 1: New Firmware Version " + str(fw_info_new),
                  "is Set, Firmware Downloading...")
            time.sleep(2)
            print(str(datetime.datetime.now()),
                  "Step 2: Downloading Success, Validation Firmware file...")
            time.sleep(2)
            print(
                str(datetime.datetime.now()),
                "Step 3: Firmware Validation Passed, Start Firmware Upgrading..."
            )
            time.sleep(2)
            print(str(datetime.datetime.now()),
                  "Step 4: Upgrading Sucessful, Rebooting Device...")
            time.sleep(2)
            print(str(datetime.datetime.now()),
                  "Step 5: Device Successful Reconnected !!!")
            fw_info = fw_info_new

            device_property_new_fw = {'Firmware_Info': fw_info}
            await device_client.patch_twin_reported_properties(
                device_property_new_fw)

    # define behavior for receiving a message
    async def message_receive_handler(device_client):
        while True:
            message = device_client.receive_message()  # blocking call
            print(str(datetime.datetime.now()), "Received Message:")
            print(message.data.decode())
            if len(message.custom_properties) > 0:
                print(str(datetime.datetime.now()), "With Custom Properties:")
                print(message.custom_properties)

    # define send message to iot hub
    async def send_telemetry(device_client):
        global telemetry_interval, send_data
        telemetry_data_raw = '{{"voltage": {voltage},"ampere": {ampere},"walt": {walt}}}'
        temp_telemetry_raw = '{{"Temperature": {temp},"Humidity": {humi}}}'
        while True:
            time.sleep(telemetry_interval)
            if send_data == True:
                voltageset = 220 + (random.random() * 10)
                ampereset = 10 + random.random()
                waltset = (voltageset * ampereset) / 1000
                device_telemetry_data_formatted = telemetry_data_raw.format(
                    voltage=voltageset, ampere=ampereset, walt=waltset)
                device_telemetry_data = Message(
                    device_telemetry_data_formatted)
                print(str(datetime.datetime.now()), "Sending Telemetry: ",
                      device_telemetry_data)

                Temperatureset = 20 + (random.random() * 3)
                Humidityset = 50 + (random.random() * 6)
                temp_telemetry_data_formatted = temp_telemetry_raw.format(
                    temp=Temperatureset, humi=Humidityset)
                temp_telemetry_data = Message(temp_telemetry_data_formatted)
                print(str(datetime.datetime.now()), "Sending Telemetry: ",
                      temp_telemetry_data)

                if waltset > 2.5:
                    alert_info = "Capacity Over 90%"
                    alert_msg_raw = '{{"Alert": "{alert}"}}'
                    alert_msg = Message(alert_msg_raw.format(alert=alert_info),
                                        content_encoding="utf-8",
                                        content_type="application/json")
                    alert_msg.custom_properties["Alert"] = "Capacity Over 90%"
                    alert_msg.message_id = uuid.uuid4()
                    await device_client.send_message(alert_msg)
                    print(str(datetime.datetime.now()), "Sending Telemetry: ",
                          alert_msg)

                await device_client.send_message(device_telemetry_data)
                await device_client.send_message(temp_telemetry_data)

    def send_telemetry_sync(device_client):
        loop = asyncio.new_event_loop()
        loop.run_until_complete(send_telemetry(device_client))

    def stdin_listener():
        while True:
            selection = input("Press Q to quit\n")
            if selection == "Q" or selection == "q":
                print("Quitting...")
                break

    # Set handlers to the client
    device_client.on_method_request_received = method_request_handler
    device_client.on_twin_desired_properties_patch_received = twin_patch_handler
    device_client.on_message_received = message_receive_handler

    send_telemetry_Thread = threading.Thread(target=send_telemetry_sync,
                                             args=(device_client, ))
    send_telemetry_Thread.daemon = True
    send_telemetry_Thread.start()

    # Run the stdin listener in the event loop
    loop = asyncio.get_event_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

    # Finally, disconnect
    await device_client.disconnect()
Ejemplo n.º 21
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()
Ejemplo n.º 22
0
async def main():
    switch = os.getenv("IOTHUB_DEVICE_SECURITY_TYPE")
    if switch == "DPS":
        provisioning_host = (os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT")
                             if os.getenv("IOTHUB_DEVICE_DPS_ENDPOINT") else
                             "global.azure-devices-provisioning.net")
        id_scope = os.getenv("DPS_IDSCOPE")
        registration_id = os.getenv("DPS_DEVICE_ID")
        symmetric_key = os.getenv("DPS_SYMMETRIC_KEY")

        registration_result = await provision_device(provisioning_host,
                                                     id_scope, registration_id,
                                                     symmetric_key, model_id)

        if registration_result.status == "assigned":
            print("Device was assigned")
            print(registration_result.registration_state.assigned_hub)
            print(registration_result.registration_state.device_id)
            device_client = IoTHubDeviceClient.create_from_symmetric_key(
                symmetric_key=symmetric_key,
                hostname=registration_result.registration_state.assigned_hub,
                device_id=registration_result.registration_state.device_id,
                product_info=model_id,
            )
        else:
            raise RuntimeError(
                "Could not provision device. Aborting Plug and Play device connection."
            )

    elif switch == "ConnectionString":
        conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
        print("Connecting using Connection String " + conn_str)
        device_client = IoTHubDeviceClient.create_from_connection_string(
            conn_str, product_info=model_id)
    else:
        raise RuntimeError(
            "At least one choice needs to be made for complete functioning of this sample."
        )

    # Connect the client.
    await device_client.connect()

    ################################################
    # Register callback and Handle command (reboot)
    print("Listening for command requests and property updates")

    listeners = asyncio.gather(
        execute_command_listener(
            device_client,
            method_name="show_text",
            user_command_handler=led_text_handler,
            create_user_response_handler=create_led_text_report_response,
        ), execute_property_listener(device_client))

    ################################################
    # Send telemetry
    async def send_telemetry():
        print("Sending telemetry for SenseHat")

        while True:
            temperature_hts221 = sense.get_temperature()
            humidity = sense.get_humidity()
            temperature_lps25h = (
                (sense.get_temperature_from_pressure() / 5) * 9) + 32
            pressure = sense.get_pressure()
            orientation_rad = sense.get_orientation_radians()
            lsm9ds1_accelerometer = sense.get_accelerometer_raw()
            lsm9ds1_gyroscope = sense.get_gyroscope_raw()
            lsm9ds1_compass = sense.get_compass_raw()
            imu_yaw = orientation_rad['yaw']
            imu_roll = orientation_rad['roll']
            imu_pitch = orientation_rad['pitch']
            lsm9ds1_compass_x = lsm9ds1_compass['x']
            lsm9ds1_compass_y = lsm9ds1_compass['y']
            lsm9ds1_compass_z = lsm9ds1_compass['z']
            lsm9ds1_gyroscope_x = lsm9ds1_gyroscope['x']
            lsm9ds1_gyroscope_y = lsm9ds1_gyroscope['y']
            lsm9ds1_gyroscope_z = lsm9ds1_gyroscope['z']
            lsm9ds1_accelerometer_x = lsm9ds1_accelerometer['x']
            lsm9ds1_accelerometer_y = lsm9ds1_accelerometer['y']
            lsm9ds1_accelerometer_z = lsm9ds1_accelerometer['z']
            ### For old model file ###     temperature_msg1 = {"temperature_hts221": temperature_hts221,"humidity": humidity,"temperature_lps25h": temperature_lps25h,"pressure": pressure,"imu": orientation_rad,"lsm9ds1_accelerometer": lsm9ds1_accelerometer,"lsm9ds1_gyroscope": lsm9ds1_gyroscope,"lsm9ds1_compass": lsm9ds1_compass}
            temperature_msg1 = {
                "temperature_hts221": temperature_hts221,
                "humidity": humidity,
                "temperature_lps25h": temperature_lps25h,
                "pressure": pressure,
                "imu_yaw": imu_yaw,
                "imu_roll": imu_roll,
                "imu_pitch": imu_pitch,
                "lsm9ds1_accelerometer_x": lsm9ds1_accelerometer_x,
                "lsm9ds1_accelerometer_y": lsm9ds1_accelerometer_y,
                "lsm9ds1_accelerometer_z": lsm9ds1_accelerometer_z,
                "lsm9ds1_gyroscope_x": lsm9ds1_gyroscope_x,
                "lsm9ds1_gyroscope_y": lsm9ds1_gyroscope_y,
                "lsm9ds1_gyroscope_z": lsm9ds1_gyroscope_z,
                "lsm9ds1_compass_x": lsm9ds1_compass_x,
                "lsm9ds1_compass_y": lsm9ds1_compass_y,
                "lsm9ds1_compass_z": lsm9ds1_compass_z
            }
            await send_telemetry_from_thermostat(device_client,
                                                 temperature_msg1)
            await device_client.patch_twin_reported_properties(
                {"manufacturer": "Pi Fundation"})
            await asyncio.sleep(8)

    send_telemetry_task = asyncio.create_task(send_telemetry())

    # 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

    if not listeners.done():
        listeners.set_result("DONE")

    listeners.cancel()

    send_telemetry_task.cancel()

    # finally, disconnect
    await device_client.disconnect()
Ejemplo n.º 23
0
async def main():
    global device_client

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

    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:
            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=symmetric_key,
                websockets=use_websockets
            )

            provisioning_device_client.provisioning_payload = '{"iotcModelId":"%s"}' % (model_identity)
            registration_result = await provisioning_device_client.register()

            dps_cache = (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:
            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
        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 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))

    #awit the tasks ending before exiting
    try:
        await asyncio.gather(twin_listener, direct_method_listener, telemetry_loop, reported_loop1, reported_loop2, reported_loop3) 
    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()
async def main():

    # Function for sending message
    async def send_test_message():
        print("Sending telemetry message from device " + device_id)
        body_dict = {}
        body_dict['Temperature'] = random.randrange(76, 80, 1)
        body_dict['Humidity'] = random.randrange(40, 60, 1)
        body_dict['Location'] = '28.424911, -81.468962'
        body_json = json.dumps(body_dict)
        print(body_json)
        msg = Message(body_json)
        msg.message_id = uuid.uuid4()
        msg.correlation_id = "correlation-1234"
        msg.contentEncoding = "utf-8",
        msg.contentType = "application/json",
        await device_client.send_message(msg)
        print("Done sending message")

    # update the reported properties
    async def update_device_twin(device_client, led_manager):
        reported_properties = {}
        for i in range(8):
            key = 'led' + str(i + 1) + '_status'
            reported_properties[key] = led_manager.leds[i].status
            key = 'led' + str(i + 1) + '_blink'
            reported_properties[key] = led_manager.leds[i].blink
            key = 'led' + str(i + 1) + '_r'
            reported_properties[key] = led_manager.leds[i].r
            key = 'led' + str(i + 1) + '_g'
            reported_properties[key] = led_manager.leds[i].g
            key = 'led' + str(i + 1) + '_b'
            reported_properties[key] = led_manager.leds[i].b
        await device_client.patch_twin_reported_properties(reported_properties)
        print("Updated Device Twin's reported properties:")
        printjson(reported_properties)

    # define behavior for receiving a twin patch
    async def twin_patch_listener(device_client, led_manager):
        while True:
            patch = await device_client.receive_twin_desired_properties_patch(
            )  # blocking call
            print("Received new device twin's desired properties:")
            printjson(patch)
            for i in range(8):
                led_status = led_manager.leds[i].status
                led_blink = led_manager.leds[i].blink
                led_r = led_manager.leds[i].r
                led_g = led_manager.leds[i].g
                led_b = led_manager.leds[i].b
                key = 'led' + str(i + 1) + '_status'
                if key in patch:
                    led_status = patch[key]
                key = 'led' + str(i + 1) + '_blink'
                if key in patch:
                    led_blink = patch[key]
                key = 'led' + str(i + 1) + '_r'
                if key in patch:
                    led_r = patch[key]
                key = 'led' + str(i + 1) + '_g'
                if key in patch:
                    led_g = patch[key]
                key = 'led' + str(i + 1) + '_b'
                if key in patch:
                    led_b = patch[key]
                led_manager.set_led(i, led_status, led_r, led_g, led_b,
                                    led_blink)
            await update_device_twin(device_client, led_manager)

    async def direct_methods_listener(device_client, led_manager):
        while True:
            method_request = (await device_client.receive_method_request()
                              )  # Wait for unknown method calls

            # Check which method was involked
            if (method_request.name == "TurnLedsOff"):
                # Turn all leds off
                led_manager.set_all_leds_off()
                response_payload = {
                    "result": True,
                    "data": "Leds are all off"
                }  # set response payload
                response_status = 200  # set return status code
                print("Executed method " + method_request.name)

            elif (method_request.name == "ScrollLeds"):
                # Set leds colors and start scrolling
                led_manager.set_all_leds_off()
                led_manager.set_all_leds_color(255, 255, 255)
                led_manager.start_scrolling()
                response_payload = {
                    "result": True,
                    "data": "Leds are now scrolling"
                }  # set response payload
                response_status = 200  # set return status code
                print("Executed method " + method_request.name)

            else:
                # Respond
                response_payload = {
                    "result": True,
                    "data": "unknown method"
                }  # set response payload
                response_status = 200  # set return status code
                print("Executed unknown method: " + method_request.name)

            method_response = MethodResponse.create_from_method_request(
                method_request, response_status, response_payload)
            await device_client.send_method_response(method_response
                                                     )  # send response

    # Schedule tasks for Methods and twins updates
    led_listeners = asyncio.gather(led_manager.scroll_leds_task(),
                                   led_manager.update_leds_task())

    # Thread pool Executor to execute async functions in sync task
    # pool = concurrent.futures.ThreadPoolExecutor()

    device_id = registration_id
    print("Connecting device " + device_id)

    # Connect the client.
    print("Provisioning device to Azure IoT...")
    led_manager.set_all_leds_color(0, 255, 0)
    led_manager.start_scrolling()

    # registration using DPS
    provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
        provisioning_host=provisioning_host,
        registration_id=registration_id,
        id_scope=id_scope,
        symmetric_key=symmetric_key)

    registration_result = await provisioning_device_client.register()

    led_manager.set_all_leds_off()

    if registration_result.status == "assigned":
        print("Device successfully registered. Creating device client")
        # Create device client from the above result
        device_client = IoTHubDeviceClient.create_from_symmetric_key(
            symmetric_key=symmetric_key,
            hostname=registration_result.registration_state.assigned_hub,
            device_id=registration_result.registration_state.device_id,
        )
    else:
        led_manager.set_led(0, true, 255, 0, 0, true)
        print("Provisioning of the device failed.")
        sys.exit()

    # Connect the client.
    print("Connecting to Azure IoT...")
    led_manager.set_all_leds_color(0, 0, 255)
    led_manager.start_scrolling()

    await device_client.connect()
    print("Device is connected to Azure IoT")
    led_manager.set_all_leds_off()

    # Update Device Twin reported properties
    await update_device_twin(device_client, led_manager)

    # Schedule tasks for Methods and twins updates
    iothub_listeners = asyncio.gather(
        direct_methods_listener(device_client, led_manager),
        twin_patch_listener(device_client, led_manager))

    # define behavior for halting the application
    def stdin_listener():
        pool = concurrent.futures.ThreadPoolExecutor()
        while True:
            print(
                "To control the leds from Azure IoT, you can send the following commands through Direct Methods: TurnLedsOff, ScrollLeds"
            )
            selection = input(
                "Commands: \n   Q: quit\n   S: Send a telemetry message\n")
            if selection == "Q" or selection == "q":
                print("Quitting...")
                break
            elif selection == "S" or selection == "s":
                # send 8 messages one after the other with a sleep
                result = pool.submit(asyncio.run, send_test_message()).result()

    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

    # Cancel listening
    led_listeners.cancel()
    iothub_listeners.cancel()

    # finally, disconnect
    await device_client.disconnect()
async def main():
    global client

    # calculate the device
    device_symmetric_key = derive_device_key(device_id, GROUP_SYMMETRIC_KEY)

    # create a provisioning client that uses a symmetric device key
    provisioning_client = ProvisioningDeviceClient.create_from_symmetric_key(
        provisioning_host=provisioning_host,
        registration_id=device_id,
        id_scope=SCOPE_ID,
        symmetric_key=device_symmetric_key,
        websockets=use_websockets
    )

    # register the device via DPS (with a specific device model) 
    # and obtain the hostname of the Azure IoT hub to connect to
    provisioning_client.provisioning_payload = f'{{"iotcModelId":"{model_id}"}}'
    registration_result = None
    try:
        registration_result = await provisioning_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:  # error if the device is blocked
        print('Client Error')
    except Exception:
        print('Unknown Exception')

    # create the IoT hub device client and connect
    client = IoTHubDeviceClient.create_from_symmetric_key(
        symmetric_key=device_symmetric_key,
        hostname=registration_result.registration_state.assigned_hub,
        device_id=device_id,
        websockets=use_websockets
    )

    await client.connect()

    # send the Raspberry Pi device information as a reported property
    pi_info = get_pi_model_info()
    reported_payload = {"pi_info": {
                            "cpu_architecture": pi_info['cpu_architecture'],
                            "cpu_model": pi_info['cpu_model'],
                            "cpu_revision": pi_info['cpu_revision'],
                            "estimated_mips": pi_info['estimated_mips'],
                            "hardware": pi_info['hardware'],
                            "hardware_revision": pi_info['hardware_revision'],
                            "ip_address": get_ip_address(),
                            "min_cpu_frequency": get_cpu_frequency_statistics()["min"],
                            "max_cpu_frequency": get_cpu_frequency_statistics()["max"],
                            "model": pi_info['model'],
                            "serial_number": pi_info['serial_number'],
                       }}
    try:
        await client.patch_twin_reported_properties(reported_payload)
    except Exception:
        print('Error: Unable to send the Raspberry Pi model information')

    # set up the cloud to device message listener
    client.on_message_received = c2d_message_handler

    # set up the direct method message listener
    client.on_method_request_received = direct_method_handler
    
    # set up the twin desired property patch message listener
    client.on_twin_desired_properties_patch_received = desired_property_handler

    # start the telemetry loop with a send frequency of 5 seconds
    telemetry_loop = asyncio.create_task(send_telemetry(5))

    # start the reported property loop with a send frequency of 20 seconds
    reported_loop = asyncio.create_task(send_reportedProperty(20))

    # start the keyboard monitor looking for Q to be pressed to clean exit
    loop = asyncio.get_running_loop()
    loop.run_in_executor(None, stdin_listener)

    # do not exit until the telemetry and reported property loops exit
    await asyncio.gather(telemetry_loop, reported_loop)

    # disconnect cleanly from the IoT hub
    await client.disconnect()