如何从 python 读取来自 iothub azure 设备的消息?

问题描述 投票:0回答:1

我正在尝试从物联网设备获取消息,但出现以下错误:后台线程中捕获异常。无法处理。

['azure.iot.device.common.transport_exceptions.ConnectionDroppedError: Unexpected disconnection\n']

尝试了以下代码:

import time
from azure.iot.device import IoTHubDeviceClient

RECEIVED_MESSAGES = 0

connection_string = "="

def message_handler(message):
    global RECEIVED_MESSAGES
    RECEIVED_MESSAGES += 1
    print("")
    print("Message received:")

    # print data from both system and application (custom) properties
    for property in vars(message).items():
        print ("    {}".format(property))

    print("Total calls received: {}".format(RECEIVED_MESSAGES))

def main():
    print ("Starting the Python IoT Hub C2D Messaging device sample...")

    # Instantiate the client
    client = IoTHubDeviceClient.create_from_connection_string(connection_string) 

    print ("Waiting for C2D messages, press Ctrl-C to exit")
    try:
        # Attach the handler to the client
        client.on_message_received = message_handler

        while True:
            time.sleep(1000)
    except KeyboardInterrupt:
        print("IoT Hub C2D Messaging device sample stopped")
    finally:
        # Graceful exit
        print("Shutting down IoT Hub Client")
        client.shutdown()

if __name__ == '__main__':
    main()
python azure-iot-hub
1个回答
0
投票

该错误表示 Azure IoT 设备与 Azure IoT 中心意外断开连接。

代码:

import  time
from  azure.iot.device  import  IoTHubDeviceClient
# Replace with your IoT device connection string
connection_string = "HostName=sam.azure-devices.net;DeviceId=mytestdevice1;SharedAccessKey="
RECEIVED_MESSAGES = 0  # Initialize the received message count
def  message_handler(message):
global  RECEIVED_MESSAGES
RECEIVED_MESSAGES += 1
print("Message received:")
print(" Data: {}".format(message.data))
print("Total calls received: {}".format(RECEIVED_MESSAGES)) 
def  main():
print("Starting the Python IoT Hub C2D Messaging device sample...")
# Instantiate the client
client = IoTHubDeviceClient.create_from_connection_string(connection_string)
print("Waiting for C2D messages, press Ctrl-C to exit")
try:
# Attach the handler to the client
client.on_message_received = message_handler
# Connect to the IoT Hub
client.connect()
while  True:
time.sleep(1)  # Reduce the sleep duration
except  KeyboardInterrupt:
print("IoT Hub C2D Messaging device sample stopped")
finally:
# Graceful exit
print("Shutting down IoT Hub Client")
client.shutdown()
if  __name__ == '__main__':
main()

  • 从 Azure IoT 中心发送消息,如下所示:

enter image description here

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.