试用百度 IoTHub MQTT 协议
演示代码依赖项:
- Python3
- Paho-mqtt (pip3 install paho-mqtt)
- 百度天工云(物联网IoTHub,前100万条免费)
试用使用如下代码(注意修改为自己的设备名与密码)
#!/usr/bin/env python3
# by Qige <[email protected]> since 20180402
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("/b1/event/")
client.subscribe("/b1/device/")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
# get mqtt instant, with right flags
client = mqtt.Client(client_id="qigez", clean_session=True, transport="tcp")
bmqtt_user = 'bmqtt/qigez'
bmqtt_passwd = 'QiGehfHBLNF5KOC3hYTMg9zfAXgZbUHJAXodSBdaAlo='
print('trying ' + bmqtt_user)
# "Connected with result code 4": wrong user or password
client.username_pw_set(bmqtt_user, bmqtt_passwd)
# callbacks
client.on_connect = on_connect
client.on_message = on_message
# enable logger
client.enable_logger()
# start MQTT
client.connect("bmqtt.mqtt.iot.bj.baidubce.com", 1883, 60)
# send DPS sample command
client.publish('/b1/cmd/','device=gw010001&cmd=list&filter=all')
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
发布主题会导致立即断开连接
原因是,发布的主题并不在配置的允许主题列表中。