Python MQTT 连接到 Azure Iot Hub

标签 python azure mqtt azure-iot-hub

我想使用 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] 连接尝试失败,因为连接方在一段时间后没有正确响应,或者由于连接的主机未能响应而建立的连接失败

有人知道为什么我无法连接到物联网中心吗?

最佳答案

现在有一个官方的 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)

关于Python MQTT 连接到 Azure Iot Hub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35452072/

相关文章:

azure - 无法读取 Azure IoT 中心 MQTT 订阅消息数据

python - 当我尝试使用 pymysql 插入大 blob 时管道损坏

azure - 如何在微服务/无服务器架构中创建文件缓存层

azure - QueueTrigger 属性可见性超时

ssl - 带有 SSL/TLS 的 mosquitto MQTT 代理和 Java 客户端

Android AWS IoT 示例未更新影子

python - 当我在控制台中输入命令时,TypeError : a bytes-like object is required, 不是 'str'

python - 使用 DictReader 从 python 中的 csv 行 'as a list' 中读取列表

Python YAML 保留换行符而不添加额外的换行符

azure - 如何设置 Azure CNAME