Python使用MQTT举例
HDUZN

关于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库

1
pip install 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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import paho.mqtt.client as mqtt_client
import time, json, random

# MQTT连接
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)
# Set Connecting Client ID
client = mqtt_client.Client(client_id)
client.on_connect = on_connect
client.connect(broker, port)
return client

# 发布消息
def publish(client, topic, msg):
# msg = f"messages: {msg_count}"
result = client.publish(topic, msg)
# result: [0, 1]
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()
# 发布消息
# stus = {"Tempeature":30.1,"Humidity":40.2,"Hours":12, "Minutes":15}
# res2 = json.dumps(stus) # 先把字典转成json
# client.publish('python/mqtt', payload=res2, qos=0)
# client.publish('emqtt', payload='Hello World', qos=0)
for i in range(100):
# 循环发布消息
publish(client, "mqtt/guangdu", i)
time.sleep(1)

# 建立连接
# MQTT Broker连接参数
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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
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

# MQTT Broker连接参数
broker = 'broker-cn.emqx.io'
port = 1883
client_id = f'python-mqtt-{random.randint(0, 1000)}'

client.connect(broker, port, 600) # 600为keepalive的时间间隔
client.subscribe("mqtt/guangdu", qos=0) # subscribe 订阅

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都行。

  • 本文标题:Python使用MQTT举例
  • 本文作者:HDUZN
  • 创建时间:2022-11-13 19:15:51
  • 本文链接:http://hduzn.cn/2022/11/13/Python使用MQTT举例/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论