文章目录
前言
既然有了云服务器,可以搭建一个MQTT服务器,这样可以使用ESP32的micropython编程,实现物联网平台的构建。
一、通过宝塔面板登录服务器,拉取emqx/emqx镜像
二、使用宝塔远程工具后台运行镜像
docker run -dit --name emqx -p 18083:18083 -p 1883:1883 -p 8083:8083 -p 8084:8084 emqx/emqx:latest
docker exec -it emqx /bin/sh
三、访问emqt的web管理页面
可以把语音换成中文的。
http://你的云服务器公网IP:18083
账号: admin
密码: public
其他端口如下:如果发现某个端口访问不了,可以尝试去宝塔面板的安全位置去放行一下。
1883:MQTT 协议端口
8883:MQTT/SSL 端口
8083:MQTT/WebSocket 端口
8080:HTTP API 端口
18083:Dashboard 管理控制台端口
四、编写消息发布端和订阅端,python实现
我是用pycharm编写代码,编写之前,安装一下paho-mqtt这个包。也可以用pip3 install paho-mqtt
安装。
1.发布端publish
代码如下(示例):
from paho.mqtt import client as mqtt_client
import random
import time
broker = '0.0.0.0' #你的云服务器公网IP
port = 1883 #MQTT 协议端口
topic = "lmq"
#调用 Python random.randint 函数随机生成 MQTT 客户端 id
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)
client = mqtt_client.Client(client_id)
client.on_connect = on_connect
client.connect(broker, port)
return client
def publish(client):
msg_count = 0
while True:
time.sleep(1)
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}")
msg_count += 1
def run():
client = connect_mqtt()
client.loop_start()
publish(client)
if __name__ == '__main__':
run()
2.订阅端subscribe
代码如下(示例):
from paho.mqtt import client as mqtt_client
import random
broker = '0.0.0.0' #你的云服务器公网IP
port = 1883 #MQTT 协议端口
topic = "lmq"
# 调用 Python random.randint 函数随机生成 MQTT 客户端 id
client_id = f'python-mqtt-{random.randint(0, 1000)}'
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(client_id)
client.on_connect = on_connect
client.connect(broker, port)
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()
如果没错误,应该就是下图这样子。
总结
用最快的方法实现就好。后续可以用qt做一个软件界面,即可控制ESP32等能接入网络的硬件设备。