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()
IoT集线器消息路由使用户能够将设备到云的消息路由到面向服务的端点。As消息路由使用户能够将不同的数据类型(即设备遥测消息、设备生命周期事件和设备双更改事件)路由到不同的端点
默认情况下,消息路由到与Event Hubs兼容的内置面向服务的端点(消息/事件)
使用Azure IoT HubToolkitVisual Studio代码,您可以轻松地从built-in endpoint读取设备到云的消息。如果您使用的是Visual Studio,那么还可以使用Cloud Explorer到monitor device-to-cloud messages.
请参阅blog以了解如何从所有设备获取来自Azure IoT Hub的消息
示例代码如下所示,可以在循环中设置,通过首先获取所有设备列表来获取所有设备消息
有关C2Dmessages的更多信息
相关问题 更多 >
编程相关推荐