How read All the IOT HUB devices C2D messages in python

Atif Sayeedi 1 Reputation point

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.
427 questions
Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
796 questions
Azure IoT SDK
Azure IoT SDK
An Azure software development kit that facilitates building applications that connect to Azure IoT services.
173 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Sander van de Velde 17,936 Reputation points MVP

    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:


    Here it is received:


    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.