与Azure Iot Hub的Python MQTT连接

时间:2016-02-17 09:03:55

标签: python azure mqtt azure-iot-hub

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

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

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吗?

4 个答案:

答案 0 :(得分:3)

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

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

基本上,这是它的工作原理:

  1. 创建设备客户端并为协议指定MQTT
  2. 设置收到邮件时将调用的回调
  3. 使用send_event_async将消息发送到Azure IoT Hub实例。
  4. 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)
    

答案 1 :(得分:2)

正如@FarukCelik所说,没有适用于Python的Azure IoT SDK。

但是,根据我的经验,我认为在Python中使用现有的SDK for IoTHub有四种可行的方法。

  1. 使用Azure IoT SDK for C扩展Python,您可以尝试引用https://docs.python.org/2/extending/extending.html来实现它。
  2. 使用Azure IoT SDK for Java作为导入的Jython包,您可以尝试引用http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html以了解如何执行此操作。
  3. 类似于第二种方式,将IronPython与用于C#/ .Net的Azure IoT SDK集成,请参阅http://ironpython.net/documentation/dotnet/
  4. 用于NodeJS的Azure IoT SDK通过JavaScript Client的同一个Eclipse项目Paho支持MQTT,因此我认为您可以尝试引用Azure NodeJS IoT SDK on GitHub的源代码来了解如何正确使用{ {3}}用于Azure IoTHub。
  5. 与此同时,GitHub上有一个用于Azure IoTHub设备的非官方Python库paho Python client。您可以关注这个项目存储库,但它现在还处于开发阶段。

    希望它有所帮助。最诚挚的问候。

答案 2 :(得分:0)

以下是如何使用paho(mosquitto)通过标准MQTT连接到Azure IoT Hub:

from paho.mqtt import client as mqtt


def on_connect(client, userdata, flags, rc):
    print "Connected with result code: %s" % rc
    client.subscribe("devices/<YOUR DEVICE ID>/messages/devicebound/#")


def on_disconnect(client, userdata, rc):
    print "Disconnected with result code: %s" % rc


def on_message(client, userdata, msg):
    print " - ".join((msg.topic, str(msg.payload)))
    # Do this only if you want to send a reply message every time you receive one
    client.publish("devices/<YOUR DEVICE ID>/messages/events", "REPLY", qos=1)


def on_publish(client, userdata, mid):
    print "Sent message"


client = mqtt.Client(cleint_id=<YOUR DEVICE ID>, protocol=mqtt.MQTTv311)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
client.on_publish = on_publish
client.username_pw_set(username="<YOUR NAMESPACE>.azure-devices.net/<YOUR DEVICE ID>",
                       password="<YOUR SHARED ACCESS SIGNATURE FOR THE DEVICE>")
client.tls_insecure_set(True) # You can also set the proper certificate using client.tls_set()
client.connect("<YOUR NAMESPACE>.azure-devices.net", port=8883)
client.loop_forever()

答案 3 :(得分:-1)