【发布时间】:2018-05-18 19:08:21
【问题描述】:
当某些数据发布到 MQTT 主题 devices/device_id/messages/events/ 时,我正在尝试从 IoT 中心接收“通知”。为了接收数据,我使用了以下主题:devices/device_id/messages/devicebound/。我的订阅代码如下(Python):
import paho.mqtt.client as mqtt
import ssl, random
from time import sleep
root_ca = "./certs/digicertbaltimoreroot.pem"
public_crt = './certs/rsa_cert.pem'
private_key = './certs/rsa_private.pem'
iothub_name = "myhub"
device_id = "mydevice"
mqtt_url = "{}.azure-devices.net".format(iothub_name)
mqtt_port = 8883
topic = "devices/{}/messages/devicebound/#".format(device_id)
def error_str(rc):
return "Some error occurred. {}: {}".format(rc, mqtt.error_string(rc))
def on_disconnect(unused_client, unused_userdata, rc):
print("on_disconnect", error_str(rc))
def on_connect(client, userdata, flags, response_code):
print("Connected with status: {0}".format(response_code))
client.subscribe(topic, 1)
def on_subscribe(client, userdata, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos))
def on_message(client, userdata, msg):
print("Topic: {0} -- Payload: {1}".format(msg.topic, str(msg.payload)))
if __name__ == "__main__":
client = mqtt.Client(device_id, protocol=mqtt.MQTTv311)
client.tls_set(root_ca,
certfile = public_crt,
keyfile = private_key,
cert_reqs = ssl.CERT_REQUIRED,
tls_version = ssl.PROTOCOL_TLSv1_2,
ciphers = None)
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
print("Connecting to Azure IoT Hub...")
client.connect(mqtt_url, mqtt_port, keepalive=60)
client.loop_forever()
当我运行时,我得到以下输出:
正在连接到 Azure IoT 中心...
已连接状态:3
('on_disconnect', '发生了一些错误。5: 连接被拒绝。')
已连接状态:3
('on_disconnect', '发生了一些错误。5: 连接被拒绝。')
谁能建议我缺少什么?
【问题讨论】:
-
也许这个文档可能会有所帮助:docs.microsoft.com/en-us/azure/iot-hub/…
-
你好,@juunas。在我在这里发布我的问题之前,我已经读过了。这对发布过程很有帮助。 “订阅”部分(接收云到设备的消息)不够好。
标签: azure iot publish-subscribe azure-iot-hub subscribe