日期 2024年4月 下的文章

ESP32 micropython web配网

目录结构:
libs
∟ microdot
static
∟ index.html
∟ jquery.js
boot.py
main.py
index.html代码

<html>
<head>
<title>ESP32 Web服务</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="static/jquery.js" type="text/javascript"></script>
<style>
body {
  background-color: black;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: white;
}
.tlable{
width:80px;
text-align:right;
display:inline-block;
margin-right:5px;
}
</style>
</head>
<h1>ESP32设置中心</h1>
<form action="wificonfig" method="post">
  <p><span class="tlable">SSID: </span><input type="text" name="ssid"></p>
  <p><span class="tlable">密码:</span> <input type="text" name="password"></p>
  <input type="submit" value="提交">
</form>
</body>
</html>

main.py代码

import machine
import network
import utime
from libs.microdot import Microdot
from libs.microdot import send_file
import json


# 保持配置文件
def save_config(config):
    """function to save the config dict to the JSON file"""
    with open("config.json", "w") as f:
        json.dump(config, f)
        
ap_mode = False
# 读取 WIFI 的账号密码
# load the config file from flash
ssid=''
password=''
with open("config.json") as f:
    config = json.load(f)
    print(config)
    ssid=config['ssid']
    password=config['password']
    if ssid=='':
        ap_mode = True
# 连接 WiFi
if ap_mode is False:
    wifi_connect_times = 0
    wlan = network.WLAN(network.STA_IF)
    wlan.active(False)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(ssid, password)
    for i in range(20):
        print('第{}次尝试连接WIFI'.format(i))
        if wlan.isconnected():
            break
        utime.sleep_ms(500) #一般睡个5-10秒,应该绰绰有余
    # WIFI连接失败后开启热点,通过WiFi热点配网  
    if not wlan.isconnected():
        wlan.active(False) #关掉连接
        print('wifi connection error, please reconnect')
        config['ssid']=''
        save_config(config)
        machine.reset()
    else:
        print('network config:', wlan.ifconfig())
# 开启热点
else:
    # 创建Wi-Fi接入点
    wlan = network.WLAN(network.AP_IF)
    # 启用接入点
    wlan.active(True)
    # 设置接入点参数
    wlan.config(essid='herokay', authmode=network.AUTH_WPA_WPA2_PSK, password='123123123')
    # 输出接入点IP地址
    print('AP IP address:', wlan.ifconfig()[0])
    
app = Microdot()

#提供静态文件访问功能
@app.route('/static/<path:path>')
def static(request, path):
    if '..' in path:
        # directory traversal is not allowed
        return 'Not found', 404
    return send_file('static/' + path, max_age=86400)

@app.route('/')
def hello(request):
    return send_file('/static/index.html')

@app.post('/wificonfig')
def shutdown(request):
    config['ssid']=request.form.get('ssid')
    config['password']=request.form.get('password')
    save_config(config)
    machine.reset()
    return 'WIFI:' + ssid + ":" + password

app.run(host='0.0.0.0', port=80, debug=False)