1、新建publish.py
from paho.mqtt import client as mqtt_client
import random
import time
broker = 'broker.emqx.io'
port = 1883
topic = "/python/mqtt"
client_id = f'python-mqtt-{random.randint(0, 1000)}'
def connect_mqtt():
def on_connect(client, userdata, flags, reason_code, properties):
if reason_code == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", reason_code)
client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, client_id)
client.on_connect = on_connect
client.connect(broker, port, 60)
return client
def publish(client):
msg_count = 0
while True:
time.sleep(1)
msg = f"messages: {msg_count}"
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}")
msg_count += 1
def run():
client = connect_mqtt()
client.loop_start()
publish(client)
if __name__ == '__main__':
run()
2、新建subscribe.py
from paho.mqtt import client as mqtt_client
import random
import time
broker = 'broker.emqx.io'
port = 1883
topic = "/python/mqtt"
client_id = f'python-mqtt-{random.randint(0, 1000)}'
def connect_mqtt():
def on_connect(client, userdata, flags, reason_code, properties):
if reason_code == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", reason_code)
client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, client_id)
client.on_connect = on_connect
client.connect(broker, port, 60)
return client
def subscribe(client: mqtt_client):
def on_message(client, userdata, msg):
print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
client.subscribe(topic)
client.on_message = on_message
def run():
client = connect_mqtt()
subscribe(client)
client.loop_forever()
if __name__ == '__main__':
run()
3、服务器搭建mqtt服务
这里选用emqx搭建
输入ip:端口查看服务是否搭建成功
4、命令行操作
# 执行文件
./subscribe.py &
# 后台执行文件并输出日志
nohup python -u subscribe.py > subscribe.log 2>&1 &
# 查看是否在后台运行
ps -ef|grep subscribe
# 后台的程序 需要关闭时,需要kill命令停止
kill -9 进程ID
5、subscribe.py 升级
from paho.mqtt import client as mqtt_client
from utils import logging
import random
import json
broker = 'broker.emqx.io'
port = 1883
topics = ["connect", "start", "stop"]
client_id = f'python-mqtt-{random.randint(0, 1000)}'
class Subscribe:
def __init__(self):
self.client = mqtt_client.Client(
mqtt_client.CallbackAPIVersion.VERSION2,
client_id
)
self.is_initialized = False
self.setup_mqtt()
def setup_mqtt(self):
def on_connect(client, userdata, flags, reason_code, properties):
if reason_code == 0:
print("Connected to MQTT Broker!")
for topic in topics:
client.subscribe(topic)
else:
print(f"Failed to connect, return code {reason_code}\n")
self.client.on_connect = on_connect
self.client.connect(broker, port, 60)
def on_message(self, client, userdata, msg):
payload = msg.payload.decode('utf-8')
# 尝试解析为 JSON,并格式化输出
try:
json_data = json.loads(payload)
output = json.dumps(json_data, indent=2, ensure_ascii=False)
except json.JSONDecodeError:
output = payload # 如果不是 JSON,就原样显示
if msg.topic == "connect":
print("Handling CONNECT command...")
logging(msg.topic, output)
# 处理连接逻辑
elif msg.topic == "start":
print("Handling START command...")
logging(msg.topic, output)
# 处理启动逻辑
elif msg.topic == "stop":
print("Handling STOP command...")
logging(msg.topic, output)
# 处理停止逻辑
def start(self):
if not self.is_initialized:
self.client.on_message = self.on_message
self.is_initialized = True
self.client.loop_forever()
if __name__ == '__main__':
subscriber = Subscribe()
subscriber.start()