安装mqtt for python库
pip install paho-mqtt
一个简单的示例
import paho.mqtt.client as mqtt
import json
def on_connect(client, userdata, flags, reason_code, properties):
print(f"Connected with result code {reason_code}")
client.subscribe('TEST/#')
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
obj = json.loads(msg.payload)
print(f"parse json:{obj}")
for k, v in obj.items():
print(f"key = {k}, value = {v}")
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect('mqtt.eclipseprojects.io', 1883, 60)
print('mqtt client start loop......')
mqttc.loop_forever()
mqtt client start loop......
Connected with result code Success
TEST/CLIENTS/DATA b'{"adress":"123456","name":"null","type":"LCD_THERMOSTATE","t_01":"0.00","t_02":"0.00","t_03":"0.00","t_04":"0.00","h_01":"0","p_01":"0","co2":"0","ip":"192.168.0.100","mask":"255.255.255.0","mac":"F0-F5-BD-10-29-68","state":"offline"}'
parse json:{'adress': '123456', 'name': 'null', 'type': 'LCD_THERMOSTATE', 't_01': '0.00', 't_02': '0.00', 't_03': '0.00', 't_04': '0.00', 'h_01': '0', 'p_01': '0', 'co2': '0', 'ip': '192.168.0.100', 'mask': '255.255.255.0', 'mac': 'F0-F5-BD-10-29-68', 'state': 'offline'}
key = adress, value = 123456
key = name, value = null
key = type, value = LCD_THERMOSTATE
key = t_01, value = 0.00
key = t_02, value = 0.00
key = t_03, value = 0.00
key = t_04, value = 0.00
key = h_01, value = 0
key = p_01, value = 0
key = co2, value = 0
key = ip, value = 192.168.0.100
key = mask, value = 255.255.255.0
key = mac, value = F0-F5-BD-10-29-68
key = state, value = offline
关注我,了解更多
公众号:搏哥聊技术