How read All the IOT HUB devices C2D messages in python

Atif Sayeedi 1 Reputation point
2021-09-30T10:37:04.783+00:00

In azure IOT Hub, I have multiple IoT Edge devices and I want to read all the cloud to device messages in python. I am unable to find the way how to read all the devices messages from cloud to device. I have tried paho.mqtt and azure.iot.device.aio, it works perfect for the one device.

Please suggest how to achieve this in Azure using Python.

Azure IoT Edge
Azure IoT Edge
An Azure service that is used to deploy cloud workloads to run on internet of things (IoT) edge devices via standard containers.
585 questions
Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,226 questions
Azure IoT SDK
Azure IoT SDK
An Azure software development kit that facilitates building applications that connect to Azure IoT services.
226 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Sander van de Velde | MVP 34,281 Reputation points MVP
    2021-10-13T13:20:11.507+00:00

    Hello @Atif Sayeedi ,

    Normally, each device sends its own telemetry and receives its own C2D commands or messages.

    So, each device has its own credentials and makes contact with the IoT Hub (eg. using the Azure IoT Device SDK).

    I checked the samples for Python and found this example in GitHub.

    It's event-based so the code is waiting for incoming C2D messages while other work is done.

    Here I send a message:

    140216-image.png

    Here it is received:

    140217-image.png

    See how the "Press Q to quit" is already executed while the code waits for the message to be received.

    So you can either start creating multiple 'threads' running next to each other in your python code, each with its own device client. They all wait for their own incoming messages. So multiple clients run in parallel.

    Or you can try to loop through the list of devices, create a temporary device client which shuts down just after disconnecting the Message Handler. So in the end, only one device client is running, in a serial manner.

    Messsages stay on the IoT Hub up to 48 hours before these are removed while not being picked up or accepted by the device client.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.