如何在python中读取所有IOT集线器设备C2D消息

2024-05-17 05:26:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 方法消息deviceazureiotmqttpaho建议
1条回答
网友
1楼 · 发布于 2024-05-17 05:26:15

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

默认情况下,消息路由到与Event Hubs兼容的内置面向服务的端点(消息/事件)

使用Azure IoT HubToolkitVisual Studio代码,您可以轻松地从built-in endpoint读取设备到云的消息。如果您使用的是Visual Studio,那么还可以使用Cloud Explorermonitor device-to-cloud messages.

请参阅blog以了解如何从所有设备获取来自Azure IoT Hub的消息

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

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()

有关C2Dmessages的更多信息

相关问题 更多 >