本帖最后由 soon顺soon 于 2020-12-8 12:37 编辑
本文分享一种利用python搭建MQTT控制WIFI-IoT的红绿灯测试web页面的方法,实现按下 web页面按键后会发布topic为ledstatus,payload分别为RedLED、YellowLED、GreenLED的消息,如果刚好有兴趣的可以参考下。
WIFI-IoT上收到消息后反转对应LED 状态的相关代码,参阅
一、相关的软件和python库安装
ubuntu20.04中搭建MQTT Broker的指令如下
- sudo apt-get install mosquitto
- sudo apt-get install mosquitto-clients
- sudo apt-get install mosquitto-dev
Ubuntu下用python搭建web会用到的库安装指令如下
- pip3 install paho.mqtt
- pip3 install web.py
如果是在windows下mqtt的包安装要换成如下
- pip install web.py
- pip install paho-mqtt
二、用html写个简单的页面"key.html"如下
- Wifi-loT测试页面
- Soon-Wifi-loT
-
-
-
-
页面比较简洁只有标题和三个按键
三、Python相关代码如下
- import web
- import paho.mqtt.client
- import time
- HOSTNAME ="xxxxxx"#请填入你的Broker地址/可以是你局域网ubuntu虚拟机IP,或者云服务器地址
- MQTTPORT = 1883#默认1883 具体看你Broker配置
- USERNAME ="xxxxxx" #请填入用户名
- PASSWD="xxxxxx"#请填入用密码
- HTML_PAGE = "key.html"
- TOPICE = "ledstatus"
- mqtt = paho.mqtt.client
- urls = (
- '/RedLED', 'RedLED',
- '/YellowLED', 'YellowLED',
- '/GreenLED', 'GreenLED',
- '/(.*)', 'Wifi_lOT_home'
- )
- app = web.application(urls, globals())
- client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
- client = mqtt.Client(client_id) # ClientId不能重复,所以使用当前时间
- # publish 消息
- def on_publish(topic, payload, qos):
- client.username_pw_set(USERNAME, PASSWD) # 必须设置,否则会返回「Connected with result code 4」
- client.connect(HOSTNAME, MQTTPORT, 60)
- client.publish(topic, payload, qos)
- class Wifi_lOT_home:
- def GET(self, name):
- file = open(HTML_PAGE, "rb+")
- return file.read()
- def POST(self):
- print ("test soon")
-
- class RedLED:
- def POST(self):
- print ("RedLED POST")
- on_publish(TOPICE, "RedLED".encode(),0)
- file = open(HTML_PAGE, "rb+")
- return file.read()
- class YellowLED:
- def POST(self):
- print ("YellowLED POST")
- on_publish(TOPICE,"YellowLED".encode(),0)
- file = open(HTML_PAGE, "rb+")
- return file.read()
- class GreenLED:
- def POST(self):
- print ("GreenLED POST")
- on_publish(TOPICE,"GreenLED".encode(),0)
- file = open(HTML_PAGE, "rb+")
- return file.read()
- if __name__ == "__main__":
- app.run()
四、运行指令和效果
运行指令python3 -u xxxxxx.py 端口 ,如 python3 -u keyEvent.py 8080
然后在浏览器输入http://localhost:8080/ 或者http://(ubuntu IP/server IP):8080/ 就能看到以下页面
附相关代码