架构图
服务与程序
用docker启动mqtt broker(服务器)
访问:http://192.168.88.173:18083/#/dashboard/overview
用户名:admin 密码:***
消息发布者(查找sop的url地址,发布出去)
修改url,重新发布消息
import random
from paho.mqtt import client as mqtt_clientbroker = '192.168.88.173'
port = 1883
topic = "/python/mqtt"client_id = f'python-mqtt-{random.randint(0, 1000)}'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)raise Exception("连接MQTT 服务失败!")client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION1,client_id) # 创建客户端client.on_connect = on_connect # 指定回调函数client.connect(broker, port) # 开始连接return clientdef publish(client):msg = "http://hhy201904.x3322.net:8070/web"msg = "http://www.baidu.com"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():client = connect_mqtt()client.loop_start() # 开启一个独立的循环通讯线程publish(client)if __name__ == '__main__':run()
消息订阅者(订阅topic主题)
获取订阅消息,启动浏览器
import random
import os
from paho.mqtt import client as mqtt_client
import webbrowserbroker = '192.168.88.173'
port = 1883
topic = "/python/mqtt"client_id = f'python-mqtt-{random.randint(0, 100)}'def connect_mqtt() -> mqtt_client: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(mqtt_client.CallbackAPIVersion.VERSION1,client_id)client.on_connect = on_connectclient.connect(broker, port)return clientdef subscribe(client: mqtt_client):def on_message(client, userdata, msg): # 回调函数print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")url = msg.payloadwebbrowser.open(url, 1)os.system("start /max edge")client.subscribe(topic)client.on_message = on_messagedef run():client = connect_mqtt()subscribe(client)client.loop_forever()if __name__ == '__main__':run()
树莓派设置
python开机自启动(打开订阅者服务)
目录:/home/tx/.config/autostart/my.desktop
[Desktop Entry]
Type=Application
Exec=lxterminal -e python3 -i /home/pi/example.py && chromium-browser --disable-popup-blocking --no-first-run --disable-desktop-notifications --kiosk "http://www.baidu.com"
****