这里写目录标题
物联网esp32、micropython、mosquitto、websocket、nginx、html、js、python实现wifi外网点灯(非局域网)阿里云服务器,保姆级教程
1、esp32的micropython连接wifi及mosquitto服务器
猪不喜欢多说废话(除非是母猪),上代码
import time
#点灯模块
from machine import Pin
#网络连接模块 WiFi模块
import network
import esp
esp.osdebug(None)
#连接mosquitto模块,这个要在esp32板子中安装,命令两条
#命令1:import upip
#命令2:upip.install('micropython-umqtt.simple')
from lib.umqtt.simple2 import MQTTClient
#垃圾回收
import gc
gc.collect()
#连接wifi ssid=你的wifi名称 password=你的wifi密码 要修改
ssid = '?????????'
password = '********'
#wlan网络模式
station = network.WLAN(network.STA_IF)
station.active(True)
#连接wifi
station.connect(ssid, password)
while station.isconnected() == False:
pass
#连接成功后打印成功及板子连接的IP信息
print('Connection successful')
print(station.ifconfig())
#定义板载led
led = Pin(22, Pin.OUT)
#收到消息后执行的函数
def sub_cb(topic, msg, retain, dup):
print((topic, msg, retain, dup))
#收到消息后将bytes转为str 此处decode的参数模式和python不一样,注意容易出错
rsmsg =str(msg.decode('UTF-8','strict'))
#修改灯的状态 value值 0 开 1 关
if rsmsg=='开':
print('准备打开led灯')
led.value(0)
print('灯已开')
elif rsmsg=='关':
print('准备关闭led灯')
led.value(1)
print('灯已关')
else:
print('消息无效无操作')
#连接mosquitto的函数
def main(server="localhost", blocking_method=False):
#MQTTClient 第一个参数,你以名:zhutou连接mosquitto,麻烦自己修改名
#MQTTClient 第二个参数,阿里云服务器的IP:13.14.52.02 麻烦自己修改IP
#另外记得阿里云安全组打开mosquitto1883默认端口 ,8080和9001 websocket端口,不然你连不上
c = MQTTClient("zhutou", '13.14.52.02')
c.set_callback(sub_cb)
c.connect()
#订阅消息b"paho/test/single"
c.subscribe(b"paho/test/single")
#保持一直等着收订阅的消息
while True:
if blocking_method:
# Blocking wait for message
c.wait_msg()
else:
# Non-blocking wait for message
c.check_msg()
# Then need to sleep to avoid 100% CPU usage (in a real
# app other useful actions would be performed instead)
time.sleep(1)
c.disconnect()
#调用连接函数main
main()
#下面这句话是废话我测试时候用的
print(cs.px)
2、网页端代码html+js
下不到paho-mqtt.js再找我
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>pxLED</title>
<!--paho-mqtt.js文件不好下,有时候网站打不开找我过墙好找一些github上有https://github.com/eclipse/paho.mqtt.javascript/blob/master/src/paho-mqtt.js这个网站下的不行的话M我-->
<script src="./2021-8-16/paho-mqtt.js" type="text/javascript"></script>
<!--<script type = "text/javascript" src = "./jquery-3.2.1min.js"></script>-->
</head>
<body>
<button onclick="changeio()">改变开关状态</button>
</body>
<script>
var io ='开';
//连接mosquitto xxxxxxx为你的服务器ip yyyyyy为端口 此处建议开mosquitto.conf中开8080 9001 websocket 阿里云安全组也开放此2个端口 以及默认的1883端口。还有个坑有些paho-mqtt.js不是不能用,是要改成clientmsq= new Paho.Client('xxxxxxx',yyyyyy,"/mqtt",'webclient-px');和 var sendmsg = new Paho.Message(io);
clientmsq= new Paho.MQTT.Client('xxxxxxx',yyyyyy,"/mqtt",'webclient-px');
//心跳包10秒,按需求修改
clientmsq.connect({keepAliveInterval:10});
//按钮改变等状态功能
function changeio() {
if (io =='关'){
io='开'
}else if(io=='开'){
io='关'
}
//请把连接代码放在外面,或者先执行连接延时一段时间后再发送消息,不让速度太快,还没连上你就发消息了,会报错。
// clientmsq= new Paho.MQTT.Client('39.106.39.98',8080,"/mqtt",'webclient-px');
// clientmsq.connect({
// invocationContext: {
// host: '13.14.52.02',//IP地址
// port: 8080,//端口号
// // path: client.path,
// clientId: 'webclient-px'//标识
// }});
// clientmsq.subscribe('paho/test/single');
// console.log(clientmsq.send);
//发送消息代码io为具体消息
var sendmsg = new Paho.MQTT.Message(io);
//发送的订阅频道'paho/test/single'自己修改 保证和你的板子订阅频道一致就好了
sendmsg.destinationName = 'paho/test/single';
sendmsg.retained = true ;
// clientmsq.send(topic='paho/test/single',payload=io,0,true);
//发送
clientmsq.send(sendmsg);
// clientmsq.disconnect();
}
</script>
</html>
3、mosquitto主持人(broker)在centos 7上安装配置
安装这一步太久了有点忘了
我好像直接yum install mosquitto
具体你们还是自己探索吧
启动:
1.默认启动(好像是只开了1883端口)进入主持人模式窗口、可以看见谁连进来了订阅了什么、谁出去了、地址什么的,ctrl+c退出并关闭mosquitto、想让他在后台运行你就把shell窗口关了,另开一个窗口,服务器本地连也是再开shell窗口。
mosquitto -v
2.按指定配置启动(一般路径是这个:/etc/mosquitto/mosquitto.conf)这个.conf 文件默认里面是没有内容的都是注释、开启端口模式见下面。
mosquitto -c /etc/mosquitto/mosquitto.conf -v
2.1mosquitto.conf开启端口(以下开启两个端口8080、9001并且都是websockets协议,每一个都要加,不然默认mqtt协议,你前端就连不上)
listener 8080
protocol websockets
listener 9001
protocol websockets
3其它-d什么的命令、用户名密码自己探究(实际应用你肯定得用上)
4、赠送py测试端发送和接收消息(都是东拼西凑的,仅仅能用而已)
4.1python 订阅端
import paho.mqtt.client as mqtt
# 一旦连接成功,回调此方法
def on_connect(mqttc, obj, flags, rc):
print("rc: " + str(rc)+'连接成功')
# 一旦订阅到消息,回调此方法
def on_message(mqttc, obj, msg):
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload)+'已收到消息')
print('\nmsg\n')
print(str(msg.payload.decode(encoding='UTF-8')))
# 一旦订阅成功,回调此方法
def on_subscribe(mqttc, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos)+'订阅成功')
# 一旦有log,回调此方法
def on_log(mqttc, obj, level, string):
print(string+'log')
# 新建mqtt客户端,默认没有clientid,clean_session=True, transport="tcp"
mqttc = mqtt.Client(client_id='PX')
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_log = on_log
# 连接broker,心跳时间为60s
a=mqttc.connect("39.106.39.98", 1883, 60)
print(a)
# 订阅该主题,QoS=0 这个是最低的发送标准 参数为1.2时会确认收到消息
mqttc.subscribe("paho/test/single", 0)
#保持持续连接
mqttc.loop_forever()
4.2python发送端
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import paho.mqtt.publish as publish
import time
t=time.localtime()
#这个是发送当前时间的被我注释了nowtime
# nowtime=str(t.tm_year) +'-'+ str(t.tm_mon)+'-'+str(t.tm_mday)+','+str(t.tm_hour)+':'+ str(t.tm_min)+':'+ str(t.tm_sec)
#给ESP32板子发送开灯指令 nowtime
nowtime='开'
#四个参数依次为1发布主题、2消息、3服务器地址(外网的)、4什么名字连接
publish.single("paho/test/single", nowtime, hostname="13.14.52.02",client_id='PXFB')
代码为东拼西凑修改的,实现了功能,感谢各位博客大佬
版权声明:本文为weixin_43798286原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。