python - 如何在 python 中读取所有 IOT HUB 设备 C2D 消息
问题描述
在 azure IOT Hub 中,我有多个 IoT Edge 设备,我想在 python 中读取所有云到设备消息。我无法找到如何从云端读取所有设备消息到设备的方法。我已经尝试过 paho.mqtt 和 azure.iot.device.aio,它非常适合一个设备。
请建议如何使用 Python 在 Azure 中实现这一点。
解决方案
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消息的更多信息
推荐阅读
- jquery - 在 HTML 中图像的右侧插入一个包含 2 行 4 列的表格
- xamarin.forms - XamarinForms Shell 导航与上一页的 TabBar 项
- youtube-livestreaming-api - 创建默认广播的问题(POST https://www.googleapis.com/youtube/v3/liveBroadcasts)
- php - android studio添加记录和更新问题
- javascript - Form 的 App Script 无法准确替换模板中的字段
- mysql - 用事务处理 findAll 查询并使用限制和抵消它的不工作
- json - 将 json 数据从烧瓶 api 解析到颤振列表
- ios - 在已失效的会话中创建的任务
- git - git 在拉取请求之前与上游同步分叉历史
- informatica - 如何从 informatica 云调用 teradata 上的存储过程/宏?