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

    proxy_opts = ProxyOptions(
        proxy_type=socks.HTTP,
        proxy_addr="127.0.0.1",
        proxy_port=8888  # localhost
    )

    # The client object is used to interact with your Azure IoT hub.
    device_client = IoTHubDeviceClient.create_from_connection_string(
        conn_str, websockets=True, proxy_options=proxy_opts)

    # Connect the client.
    await device_client.connect()

    async def send_test_message(i):
        print("sending message #" + str(i))
        msg = Message("test wind speed " + str(i))
        msg.message_id = uuid.uuid4()
        msg.correlation_id = "correlation-1234"
        msg.custom_properties["tornado-warning"] = "yes"
        await device_client.send_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()
Beispiel #2
0
async def main():

    with open("private.json", "r") as read_file:
        config = json.load(read_file)

    device_client = IoTHubDeviceClient.create_from_connection_string(config["connection-string"])
    await device_client.connect()

    last_temp = ""

    done = False
    sample_count = 0
    max_samples = 64

    while not (done):
        temp = "{0:0.1f}".format(get_temp())
        print("data", temp)

        if temp != last_temp:
            last_temp = temp;

            data = {}
            data['sample'] = temp
            json_body = json.dumps(data)
            print("Sending message: ", json_body)
            sample_count += 1
            await device_client.send_message(json_body)

        done = (sample_count > max_samples)

        time.sleep(30)

    await device_client.disconnect()
def create_client():
    # Create an IoT Hub client
    client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)

    # Define a method request handler
    async def method_request_handler(method_request):
        if method_request.name == "SetTelemetryInterval":
            try:
                global INTERVAL
                INTERVAL = int(method_request.payload)
            except ValueError:
                response_payload = {"Response": "Invalid parameter"}
                response_status = 400
            else:
                response_payload = {"Response": "Executed direct method {}".format(method_request.name)}
                response_status = 200
        else:
            response_payload = {"Response": "Direct method {} not defined".format(method_request.name)}
            response_status = 404

        method_response = MethodResponse.create_from_method_request(method_request, response_status, response_payload)
        await client.send_method_response(method_response)

    try:
        # Attach the method request handler
        client.on_method_request_received = method_request_handler
    except:
        # Clean up in the event of failure
        client.shutdown()
        raise

    return client
Beispiel #4
0
async def main():

    conn_str = "HostName=5G-IoT-System-For-Emergency-Responders.azure-devices.net;DeviceId=application_device1;SharedAccessKey=x84oYfc8Wm4lL7nfMzNm87X7YmFbC+TtHX4ny+bV8ck="
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    # Connect the device client.
    await device_client.connect()

    # Send a few messages
    count = 0
    tempFile = open("/sys/class/thermal/thermal_zone0/temp", "r")
    while count < 5:
        cpu_temp = tempFile.read()
        cpu_temp_float = float(cpu_temp)
        tempFile.seek(0)
        print("Sending message to Azure IoT...")
        msg = Message("Environment sensor")
        msg.message_id = uuid.uuid4()
        msg.custom_properties["Temperature"] = cpu_temp_float
        await device_client.send_message(msg)
        print("Message successfully sent:")
        print(msg.custom_properties)
        count = count + 1
        time.sleep(10)

    # finally, disconnect
    await device_client.disconnect()
    sys.exit(0)
Beispiel #5
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()
async def main():
    # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here.
    # NOTE:  connection string must contain ;GatewayHostName=<hostname of your iot edge device>
    # make sure your IoT Edge box is setup as a 'transparent gateway' per the IOT Edge documentation
    conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
    # path to the root ca cert used on your iot edge device (must copy the pem file to this downstream device)
    # example:   /home/azureuser/edge_certs/azure-iot-test-only.root.ca.cert.pem
    ca_cert = os.getenv("IOTEDGE_ROOT_CA_CERT_PATH")

    certfile = open(ca_cert)
    root_ca_cert = certfile.read()

    # The client object is used to interact with your Azure IoT Edge device.
    device_client = IoTHubDeviceClient.create_from_connection_string(
        connection_string=conn_str, server_verification_cert=root_ca_cert
    )

    # Connect the client.
    await device_client.connect()

    async def send_test_message(i):
        print("sending message #" + str(i))
        msg = Message("test wind speed " + str(i))
        msg.message_id = uuid.uuid4()
        msg.correlation_id = "correlation-1234"
        msg.custom_properties["tornado-warning"] = "yes"
        await device_client.send_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()
async def main():

    conn_str = "<Your device connection string goes here>"
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)
    await device_client.connect()

    last_temp = ""

    while True:
        temp = "{0:0.1f}".format(get_temp())
        print("Temperature", temp)

        if temp != last_temp:
            last_temp = temp;

            data = {}
            data['temperature'] = temp
            json_body = json.dumps(data)
            print("Sending message: ", json_body)
            await device_client.send_message(json_body)

        twin = await device_client.get_twin()
        handle_twin(twin)

        time.sleep(1)

    await device_client.disconnect()
    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 main():

    # Get the data list from our library
    dataList = fileparser.get_data_list_from_wisdm('WISDM_ar_v1.1\\WISDM_ar_v1.1_raw.txt')

    # Fetch the connection string from an enviornment variable
    conn_str = "HostName=berlinHub.azure-devices.net;DeviceId=subject_33;SharedAccessKey=wMVcHCziLXiH6CQRf/uz8uUnHIiQjkF1yAPKQ9t5iHU="

    # Create instance of the device client using the connection string
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    # Connect the device client.
    await device_client.connect()

    # Loop through the data and send to IoT Hub
    for data in dataList:
        msg_txt_formatted = MSG_TXT.format(user=data.user, activity=data.activity, timestamp=data.timestamp, x=data.x, y=data.y, z=data.z)
        message = Message(msg_txt_formatted)

        print( "Sending message: {}".format(message) )
        await device_client.send_message(message)
        print ( "Message successfully sent" )
        time.sleep(MSG_INTERVAL)

    await device_client.shutdown()
    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
Beispiel #11
0
 async def connect(self):
     deviceClient = IoTHubDeviceClient.create_from_connection_string(
         self.connectionString)  # iz librarya konstruktor
     await deviceClient.connect(
     )  # await -> ceka do kad se klijent ne spoji na azure
     self.device = deviceClient  # device klijent spremimo u varijablu da se moze koristiti u cijeloj klasi
     self.device.on_message_received = self.azureMessageCallback  # callback metoda izjednacena s onom iz libraria (kad prime oni poruku, primimo i mi u svojoj)
async def main():
    # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here.
    conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")

    # The client object is used to interact with your Azure IoT hub.
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    # 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()
Beispiel #13
0
async def main():
    connection_string = os.getenv("DEVICE_CONNECTION_STRING")
    device_client = IoTHubDeviceClient.create_from_connection_string(
        connection_string)
    await device_client.connect()

    try:
        values = list(map(float, sys.argv[1:])) or [42]
        payload = []
        for value in values:
            print("Collecting value:", value)
            payload.append({
                "DeviceId":
                "microsoft-sphere-device",
                "ValueId":
                "Temperature",
                "Value":
                value,
                "TimeStamp":
                datetime.datetime.now(datetime.timezone.utc)
            })
            await asyncio.sleep(1)

        message = json.dumps(payload, default=serialize_datetime)
        print("Sending message:", message)
        await device_client.send_message(message)
    finally:
        await device_client.disconnect()
async def main():
    # Scenario based values
    keep_alive = 15

    conn_str = "HostName=localhost;DeviceId=devicemtr;SharedAccessKey=Zm9vYmFy"
    device_client = IoTHubDeviceClient.create_from_connection_string(
        conn_str, keep_alive=keep_alive)

    await device_client.connect()

    send_message_task = asyncio.create_task(send_test_message(device_client))

    # Run the listener in the event loop
    # This can be a STDIN listener as well for user to indicate quitting.
    loop = asyncio.get_running_loop()
    finished_loops = loop.run_in_executor(None, quitting_listener)

    # Wait for count times to reach a certain number indicative of completion
    await finished_loops

    print(elapsed_times)

    try:
        send_message_task.cancel()
    except asyncio.CancelledError:
        print("send message task is cancelled now")

    await device_client.disconnect()
Beispiel #15
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
Beispiel #16
0
async def main():
    # The connection string for a device should never be stored in code. For the sake of simplicity we're using an environment variable here.
    conn_str = os.getenv("IOTHUB_DEVICE_CONNECTION_STRING")
    # The client object is used to interact with your Azure IoT hub.
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    # connect the client.
    await device_client.connect()

    # define behavior for receiving a twin patch
    # NOTE: this could be a function or a coroutine
    def twin_patch_handler(patch):
        print("the data in the desired properties patch was: {}".format(patch))

    # set the twin patch handler on the client
    device_client.on_twin_desired_properties_patch_received = twin_patch_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()
Beispiel #17
0
async def receive_cloud_message():
    device_client = IoTHubDeviceClient.create_from_connection_string(
        DEVICE_CONN_STRING)

    await device_client.connect()

    async def message_listener(device_client):
        while True:
            message = await device_client.receive_message()
            print("the data in the message received was ")
            print(message.data)
            await analyze_msg(message.data)

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

    asyncio.create_task(message_listener(device_client))

    loop = asyncio.get_running_loop()
    user_finished = loop.run_in_executor(None, stdin_listener)

    await user_finished

    await device_client.disconnect()
Beispiel #18
0
async def main():
    device_client = IoTHubDeviceClient.create_from_connection_string(
        "HostName=YOURAZUREACCOUNT.azure-devices.net;DeviceId=Pi_Envirnoment;SharedAccessKey=YOURSHAREDACCESSKEY"
    )

    await device_client.connect()

    async def twin_patch_listener(device_client):
        while True:
            patch = await device_client.receive_twin_desired_properties_patch(
            )  # blocking call
            print("the data in the desired properties patch was: {}".format(
                patch))

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

    asyncio.create_task(twin_patch_listener(device_client))

    loop = asyncio.get_running_loop()
    user_finished = loop.run_in_executor(None, quit_listener)

    await user_finished

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

    # The client object is used to interact with your Azure IoT hub.
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    # Connect the client.
    await device_client.connect()

    node = cellulariot.CellularIoTApp()
    node.setupGPIO()

    node.disable()
    time.sleep(1)
    node.enable()

    async def sensor_data():
        msg = Message("Acceleration: "+str(node.readAccel())+"; "+"Humidity: " + str(node.readHum())+"; "+"Temperature: " + str(node.readTemp())+"; "+"Lux: " + str(node.readLux())+"; "+"ADC1: " + str(node.readAdc(0))+"; "+"ADC2: " + str(node.readAdc(1))+"; "+"ADC3: " + str(node.readAdc(2))+"; "+"ADC4: " + str(node.readAdc(3)))
        msg.message_id = uuid.uuid4()
        msg.correlation_id = "correlation-1234"
        await device_client.send_message(msg)
    
    count = 0
    while(True):
        await sensor_data()
        print("#"+str(count)+" sent data")
        count = count+1
        time.sleep(1)
Beispiel #20
0
 def connect(self, transport_type, connection_string, cert):
     print("connecting using " + transport_type)
     auth_provider = auth.from_connection_string(connection_string)
     if "GatewayHostName" in connection_string:
         auth_provider.ca_cert = cert
     self.client = IoTHubDeviceClient.from_authentication_provider(
         auth_provider, transport_type)
     async_helper.run_coroutine_sync(self.client.connect())
Beispiel #21
0
async def main():
    # provision the device
    async def register_device():
        provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
            provisioning_host='global.azure-devices-provisioning.net',
            registration_id=device_id,
            id_scope=id_scope,
            symmetric_key=primary_key,
        )

        return await provisioning_device_client.register()

    results = await asyncio.gather(register_device())
    registration_result = results[0]

    # build the connection string
    conn_str='HostName=' + registration_result.registration_state.assigned_hub + \
                ';DeviceId=' + device_id + \
                ';SharedAccessKey=' + primary_key

    # The client object is used to interact with your Azure IoT Central.
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    # connect the client.
    print('Connecting')
    await device_client.connect()
    print('Connected')

    # listen for commands
    async def command_listener(device_client):
        global mode
        while True:
            method_request = await device_client.receive_method_request()
            payload = {'result': True, 'data': method_request.name}
            method_response = MethodResponse.create_from_method_request(
                method_request, 200, payload
            )
            await device_client.send_method_response(method_response)

    # async loop that controls the lights
    async def main_loop():
        while True:            
            telemetry = getTelemetryData()
            print(telemetry)

            await device_client.send_message(telemetry)
            await asyncio.sleep(1)

    listeners = asyncio.gather(command_listener(device_client))

    await main_loop()

    # Cancel listening
    listeners.cancel()

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

    # The client object is used to interact with your Azure IoT hub.
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    # connect the client.
    await device_client.connect()

    # Define behavior for handling methods
    async def method_request_handler(method_request):
        # Determine how to respond to the method request based on the method name
        if method_request.name == "method1":
            payload = {
                "result": True,
                "data": "some data"
            }  # set response payload
            status = 200  # set return status code
            print("executed method1")
        elif method_request.name == "method2":
            payload = {"result": True, "data": 1234}  # set response payload
            status = 200  # set return status code
            print("executed method2")
        else:
            payload = {
                "result": False,
                "data": "unknown method"
            }  # set response payload
            status = 400  # set return status code
            print("executed unknown method: " + method_request.name)

        # Send the response
        method_response = MethodResponse.create_from_method_request(
            method_request, status, payload)
        await device_client.send_method_response(method_response)

    # Set the method request handler on the client
    device_client.on_method_request_received = method_request_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 method calls
    await user_finished

    # Finally, shut down the client
    await device_client.shutdown()
Beispiel #23
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()
Beispiel #24
0
async def send_single_message(message_body):
    device_client = IoTHubDeviceClient.create_from_connection_string(
        DEVICE_CONN_STRING)
    await device_client.connect()

    message = Message(json.dumps(message_body),
                      content_type='application/json')
    await device_client.send_message(message)

    await device_client.disconnect()
Beispiel #25
0
async def InitIoTHubClient():
    # Fetch the connection string from an enviornment variable
    conn_str = "HostName=sameerIOTHub.azure-devices.net;DeviceId=RaspberryPi;SharedAccessKey=UBPpcMu5Hwb79ZfhnLBLz5vAF01NlndzR9OFH+/CfeA="

    # Create instance of the device client using the authentication provider
    global device_client
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    # Connect the device client.
    await device_client.connect()
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
Beispiel #27
0
async def write_to_hub(source_path, list_of_files, counter, limit,
                       container_name, dest_folder):
    conn_str = env.IOT_HUB_CONN_STRING

    # The client object is used to interact with your Azure IoT hub.
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    # Connect the client.
    await device_client.connect()

    async def send_spectrogram(counter):
        sleep_interval = 5
        while True:
            for f in list_of_files:
                payload = json.dumps({
                    'capturedate': time.time(),
                    'filename': f,
                    'finished': 'False'
                })
                azure_interface = AzureInterface(container_name)
                azure_interface.send_to_azure(join_paths([source_path, f]),
                                              dest_folder,
                                              f,
                                              media_file=True)
                msg = build_message(payload)
                await device_client.send_message(msg)
                logger.info("done sending file " + str(f))
                counter['count'] += 1
                logger.info(counter['count'])
                await asyncio.sleep(sleep_interval)

    # Define behavior for halting the application
    def stdin_listener(counter, limit):
        while True:
            try:
                if counter['count'] == limit:
                    logger.info('Quitting...')
                    logger.info('File limit reached %s', str(limit))
                    break
            except EOFError as e:
                time.sleep(10000)

    tasks = asyncio.gather(send_spectrogram(counter))

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

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

    # Cancel tasks
    tasks.add_done_callback(lambda r: r.exception())
    tasks.cancel()
    await device_client.disconnect()
Beispiel #28
0
async def main():
    # Connect to IoT Central and request the connection details for the device
    provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
        provisioning_host="global.azure-devices-provisioning.net",
        registration_id=device_id,
        id_scope=id_scope,
        symmetric_key=primary_key)
    registration_result = await provisioning_device_client.register()

    # Build the connection string - this is used to connect to IoT Central
    conn_str="HostName=" + registration_result.registration_state.assigned_hub + \
                ";DeviceId=" + device_id + \
                ";SharedAccessKey=" + primary_key

    # The client object is used to interact with Azure IoT Central.
    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    # Connect the client.
    timestamp = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M %S'), '%Y-%m-%d %H:%M %S')
    print(timestamp, end='')
    print(" Connecting ...")
    await device_client.connect()
    timestamp = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M %S'), '%Y-%m-%d %H:%M %S')
    print(timestamp, end='')
    print(" Connected!")

    # Start the command listener
    timestamp = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M %S'), '%Y-%m-%d %H:%M %S')
    print(timestamp, end='')
    print(" Start Listening ...")
    listener1 = asyncio.gather(light_listener(device_client))
    listener2 = asyncio.gather(temp_listener(device_client))
    # async loop
    async def main_loop():
        while True:
            await asyncio.sleep(60)
            listener1 = asyncio.gather(light_listener(device_client))
            listener2 = asyncio.gather(temp_listener(device_client))

    # Run the async main loop forever
    try:
        await main_loop()

    except KeyboardInterrupt:
        # Cancel listening
        listener1.cancel()
        listener2.cancel()

    finally:
        # Finally, disconnect
        await device_client.disconnect()
        timestamp = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M %S'), '%Y-%m-%d %H:%M %S')
        print(timestamp, end='')
        print(" Disconnected!")
        GPIO.cleanup()
Beispiel #29
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()
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()])