Skip to main content
 首页 » 编程设计

与 Azure Iot Hub 的 Python MQTT 连接

2025年05月04日25mate10pro

我想使用 Python MQTT 连接到 Azure Iot Hub。

Iot Hub 需要用户名和 SAS token 。这是我的代码:

import paho.mqtt.client as mqtt 
 
def on_connect(client, userdata, flags, rc): 
    print("Connected with result code "+str(rc)) 
    client.subscribe("$SYS/#") 
 
def on_message(client, userdata, msg): 
    print(msg.topic+" "+str(msg.payload)) 
 
client = mqtt.Client() 
client.on_connect = on_connect 
client.on_message = on_message 
 
client.username_pw_set("myHub.azure-devices.net/device1", "mySASToken") 
 
client.connect("myHub.azure-devices.net", 1883, 60) 
 
client.loop_forever() 

但是运行一段时间后,抛出了这个异常:

TimeoutError: [WinError 10060] 连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机没有响应

有人知道为什么我无法连接到 Iot Hub 吗?

请您参考如下方法:

现在有一个官方 Python SDK 可以将设备连接到 Azure IoT 中心: https://github.com/Azure/azure-iot-sdks/tree/master/python/device

This sample演示了如何使用 MQTT 协议(protocol)进行连接。

基本上,它是这样工作的:

  1. 创 build 备客户端并为协议(protocol)指定 MQTT
  2. 设置收到消息时调用的回调
  3. 使用 send_event_async 将消息发送到您的 Azure IoT 中心实例。
from iothub_client import * 
 
def send_confirmation_callback(message, result, userContext): 
    print "Confirmation[%d] received for message with result = %s" % (userContext, result) 
 
def receive_message_callback(message, counter): 
    buffer = message.get_bytearray() 
    size = len(buffer) 
    print "Received Message" 
    print "    Data: <<<%s>>> & Size=%d" % (buffer[:size], size) 
    return IoTHubMessageDispositionResult.ACCEPTED 
 
iotHubClient = IoTHubClient(connectionString, IoTHubTransportProvider.MQTT) 
iotHubClient.set_message_callback(receive_message_callback, 0) 
iotHubClient.send_event_async(message, send_confirmation_callback, 0)