看了很多大佬写的给esp32 配网的教程,打算写一篇用esp32开启热点,然后用手机连接到热点接入web的方式来给esp32配置无线网络的方法。
首先我们要下载microdot的压缩包,地址:
GitHub - miguelgrinberg/microdot: The impossibly small web framework for Python and MicroPython.
将压缩包解压,并将里面的utemplate文件夹、templates文件夹、microdot.py、microdot_utemplate.py、microdot_websocket.py、microdot_jinja.py、microdot_session.py上传进入esp32.。
新建一个wificonfig.txt,写入:
wifissid=none
wifipassword=none
保存后,重命名为wificonfig.ini,上传入esp32。
将esp32的templates文件夹中的文件全都删除,新建一个index.html,写入以下代码:
<!doctype html>
<html lang="en">
<html>
<head>
<title>连接wifi</title>
<meta charset="UTF-8">
</head>
<body>
<h1>连接wifi</h1>
<p>请输入wifi名称和密码</p>
<form method="post" action="/submit_data">
<p>
wifi名称:
<input name="wifiname" id='wifiname' autofocus />
</p>
<p>
wifi密码:
<input name="wifipwd" autofocus />
</p>
<input name="submitBtn" id='submitBtn' type="submit" value="Submit" class="disabled" />
</form>
<style>
.disabled {
background-color: grey;
pointer-events: none; /* 防止按钮被点击 */
}
</style>
<script>
document.getElementById('wifiname').addEventListener('input', function() {
var inputField = document.getElementById('wifiname');
var submitBtn = document.getElementById('submitBtn');
if (inputField.value.trim() !== '') {
// 如果输入框中有内容,则启用按钮
submitBtn.classList.remove('disabled');
} else {
// 如果输入框中没有内容,则禁用按钮
submitBtn.classList.add('disabled');
}
});
</script>
</body>
</html>
将index.html保存,并上传入esp32的templates文件夹中。
在esp32中新建main.py,写入以下代码:
from microdot import Microdot, Response
from microdot_utemplate import render_template
import uos
import network
import utime
app = Microdot()
Response.default_content_type = 'text/html'
def write_ini_file(filename, config_dict):
with open(filename, 'w') as f:
for key, value in config_dict.items():
f.write(f'{key} = {value}\n')
def read_ini_file(filename):
config_dict = {}
with open(filename, 'r') as f:
for line in f:
line = line.strip() # 去除行尾的换行符和空格
if line and not line.startswith('#'): # 忽略空行和注释行(以 # 开头的行)
key, value = line.split('=') # 分割键和值
config_dict[key.strip()] = value.strip() # 将键和值添加到字典中,并去除前后的空格
return config_dict
def connect_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF) # 创建WLAN对象,STA模式表示Station模式,即客户端模式
wlan.active(True) # 激活接口
if not wlan.isconnected(): # 检查是否已经连接
wlan.scan()
print('connecting to network...')
wlan.connect(ssid, password) # 连接到指定的SSID和密码
while not wlan.isconnected(): # 等待连接成功
print('.', end='')
utime.sleep(1)
print('network config:', wlan.ifconfig()) # 打印网络配置信息
@app.route('/')
def index(req):
return render_template('index.html')
@app.post('/submit_data')
def submit_form(req):
wifiname = req.form.get('wifiname')
wifipwd = req.form.get('wifipwd')
print(wifiname,wifipwd)
config = {
'wifissid': wifiname,
'wifipassword': wifipwd
}
write_ini_file('wificonfig.ini', config)
return 'wifi信息已配置'
if __name__ == '__main__':
wlan = network.WLAN(network.STA_IF) # 创建WLAN对象,STA模式表示Station模式,即客户端模式
wlan.active(True) # 激活接口
while not wlan.isconnected():
config = read_ini_file('wificonfig.ini')
# 检查是否已经连接
print('connecting to network...')
print((config['wifissid'],config['wifipassword']))
# 连接到指定的SSID和密码
try:
wlan.connect(config['wifissid'],config['wifipassword'])
print('network config:', wlan.ifconfig())
except OSError as e:
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid='MyMicroPythonAP', password='mysecretpassword')
print('Network config:', ap.ifconfig())
app.run(debug=True)
print('wifi已连接')
至此,结束
版权归原作者 大初哥 所有, 如有侵权,请联系我们删除。