我正在尝试使用 MQTT 连接 Azure IoT-Hub 并发送和接收消息。
我正在关注此处给出的官方文档
但它总是与结果代码断开连接:1,尽管它永远不会进入 on_connect 函数。但是,如果我尝试在函数之外发布它(连接字符串后注释掉的行),它会进入 on_publish 方法。
我在这里使用的设备是我在 Azure IoT Suite 中创建的模拟设备
这是我正在使用的代码
from paho.mqtt import client as mqtt
def on_connect(client, userdata, flags, rc):
print "Connected with result code: %s" % rc
client.subscribe("devices/MyTestDevice02/messages/devicebound/#")
client.publish("devices/MyTestDevice02/messages/events", "Hello World!")
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)))
client.publish("devices/MyTestDevice02/messages/events", "REPLY", qos=1)
def on_publish(client, userdata, mid):
print "Sent message"
client = mqtt.Client("MyTestDevice02", 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="USERNAME.azure-devices.net/MyTestDevice02",
password="SharedAccessSignature=SharedAccessSignature sr=USERNAME.azure-devices.net%2fdevices%2fMyTestDevice02&sig=xxxxxx5rRr7c%3d&se=1492318301")
client.tls_insecure_set(True) # You can also set the proper certificate using client.tls_set()
client.connect("USERNAME.azure-devices.net", port=8883)
#client.publish("devices/MyTestDevice02/messages/events", "Hello World!")
client.loop_forever()
任何帮助表示赞赏。而且我不想使用 sdk,这就是我尝试直接发布它的原因。