关于MQTT的简介和服务器的搭建,之前已经写了笔记了:Docker搭建MQTT服务器
用来学习、研究,自己不搭MQTT服务器也行,EMQX有提供免费的在线 MQTT 服务器(还提供证书的下载):
官网:https://www.emqx.com/zh/mqtt/public-mqtt5-broker
1 2 3 4 5 6
| MQTT 服务器信息 Broker: broker-cn.emqx.io TCP 端口: 1883 WebSocket 端口: 8083 SSL/TLS 端口: 8883 WebSocket Secure 端口: 8084
|
Python使用MQTT的例子,主要就写2个python文件,一个用来publish(发布消息),一个用来subcribe(订阅消息),看看是不是都能接收到消息。(消息订阅后都能接收到,就可以存入自己建的本地数据库啦)
一、安装paho-mqtt库
安装了这个库就可以处理MQTT了,官方文档上也例子:https://pypi.org/project/paho-mqtt/#
二、publish发布消息(mqtt_publish.py)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
import paho.mqtt.client as mqtt_client import time, json, random
def connect_mqtt(): def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(client_id) client.on_connect = on_connect client.connect(broker, port) return client
def publish(client, topic, msg): result = client.publish(topic, msg) status = result[0] if status == 0: print(f"Send `{msg}` to topic `{topic}`") else: print(f"Failed to send message to topic {topic}")
def run_publish(): client = connect_mqtt() time.sleep(1) client.loop_start() for i in range(100): publish(client, "mqtt/guangdu", i) time.sleep(1)
broker = 'broker-cn.emqx.io' port = 1883 client_id = f'python-mqtt-{random.randint(0, 1000)}'
run_publish()
|
三、subcribe订阅消息(mqtt_subcribe.py)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
import paho.mqtt.client as mqtt import random
def on_connect(client, userdata, flags, rc): print("Connected with result code: " + str(rc))
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
broker = 'broker-cn.emqx.io' port = 1883 client_id = f'python-mqtt-{random.randint(0, 1000)}'
client.connect(broker, port, 600) client.subscribe("mqtt/guangdu", qos=0)
client.loop_forever()
|
四、测试
- 1.先把 mqtt_subcribe.py 运行起来(在VS Code)中
- 2.再把 mqtt_publish.py 在命令行或Windows PowerShell中运行起来
python .\mqtt_publish.py
就能看到效果啦。订阅消息的这边一直可以接收到发布出来的消息啦。
所以,在订阅消息的 on_message方法中,可以把消息的主题(msg.topic)和消息的内容(msg.payload)直接存进数据库啦,sqlite和mysql都行。