我正在尝试从物联网设备获取消息,但出现以下错误:后台线程中捕获异常。无法处理。
['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()
该错误表示 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()
输出: