首页 > 解决方案 > 如何在 python 中读取所有 IOT HUB 设备 C2D 消息

问题描述

在 azure IOT Hub 中,我有多个 IoT Edge 设备,我想在 python 中读取所有云到设备消息。我无法找到如何从云端读取所有设备消息到设备的方法。我已经尝试过 paho.mqtt 和 azure.iot.device.aio,它非常适合一个设备。

请建议如何使用 Python 在 Azure 中实现这一点。

标签: pythonazureazure-iot-hub

解决方案


IoT 中心消息路由使用户能够将设备到云的消息路由到面向服务的端点。As Message 路由使用户能够将不同的数据类型(即设备遥测消息、设备生命周期事件和设备孪生更改事件)路由到各种端点。

默认情况下,消息被路由到与事件中心兼容的内置面向服务的终结点(消息/事件)

使用 Azure IoT Hub Toolkit Visual Studio Code,您可以轻松地从内置端点读取设备到云的消息。如果您使用的是 Visual Studio,您还可以使用Cloud Explorer监控设备到云的消息。

请参阅博客以了解我们如何从所有设备的 Azure IoT 中心获取消息。

示例代码如下,可以在循环中设置,通过首先获取所有设备列表来获取所有设备消息。

import os
import asyncio
from six.moves import input
import threading
from azure.iot.device.aio import IoTHubDeviceClient
 
 
async def main():
    conn_str = "HostName=***.azure-devices.net;DeviceId=MyRPi;SharedAccessKey=***"
    # 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 message
    async def message_listener(device_client):
        while True:
            message = await device_client.receive_message()  # blocking call
            print("the data in the message received was ")
            print(message.data)
            print("custom properties are")
            print(message.custom_properties)
 
    # define behavior for halting the application
    def stdin_listener():
        while True:
            selection = input("Press Q to quit\n")
            if selection == "Q" or selection == "q":
                print("Quitting...")
                break
 
    # Schedule task for message listener
    asyncio.create_task(message_listener(device_client))
 
    # Run the stdin listener in the event loop
    loop = asyncio.get_running_loop()
    user_finished = loop.run_in_executor(None, stdin_listener)
 
    # Wait for user to indicate they are done listening for messages
    await user_finished
 
    # Finally, disconnect
    await device_client.disconnect()
 
 
if __name__ == "__main__":
    asyncio.run(main())
 
    # If using Python 3.6 or below, use the following code instead of asyncio.run(main()):
    # loop = asyncio.get_event_loop()
    # loop.run_until_complete(main())
    # loop.close()

有关 C2D消息的更多信息


推荐阅读