ESP32 007 MicroPython 适用于 Python 和 MicroPython 的小型 Web 框架库 Microdot

发布于:2025-06-28 ⋅ 阅读:(20) ⋅ 点赞:(0)

MicroPython 安装 Microdot

  • 目录结构如下:
/
├── main.py
├── lib/
│   └── microdot/  文件夹地址链接 https://github.com/miguelgrinberg/microdot/tree/main/src/microdot
│       └── __init__.py   
│       └──microdot.py
  • 则导入方式:
from lib.microdot import Microdot

在这里插入图片描述

简单试用 Microdot

  • 文件结构如下
/
├── main.py
├── lib/
│   └── microdot/
│       └── __init__.py   
│       └──microdot.py

wifi_config.json 网络配置

{
  "ssid": "******",
  "password": "********",
  "use_static_ip": true,
  "ip": "192.168.1.123",
  "subnet": "255.255.255.0",
  "gateway": "192.168.1.1",
  "dns": "8.8.8.8"
}

wifi.py : 负责加载网络配置并连接 Wi-Fi,支持静态 IP:

# wifi.py
import network
import time
import ujson

def load_wifi_config(filename='wifi_config.json'):
    try:
        with open(filename, 'r') as f:
            config = ujson.load(f)
            return config
    except Exception as e:
        print("读取 Wi-Fi 配置失败:", e)
        return None

def connect_wifi():
    config = load_wifi_config()
    if not config:
        print("配置无效")
        return None

    ssid = config.get('ssid')
    password = config.get('password')

    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)

    if config.get('use_static_ip'):
        ip = config.get('ip')
        subnet = config.get('subnet')
        gateway = config.get('gateway')
        dns = config.get('dns')
        if ip and subnet and gateway and dns:
            wlan.ifconfig((ip, subnet, gateway, dns))
            print("⚙️ 使用固定 IP:", ip)
        else:
            print("⚠️ 静态 IP 参数不完整,使用 DHCP")

    if not wlan.isconnected():
        print(f'连接 Wi-Fi: {ssid} ...')
        wlan.connect(ssid, password)
        timeout = 10
        while not wlan.isconnected() and timeout > 0:
            time.sleep(1)
            timeout -= 1

    if wlan.isconnected():
        print('✅ Wi-Fi 连接成功,IP 地址:', wlan.ifconfig()[0])
    else:
        print('❌ Wi-Fi 连接失败')
    return wlan

main.py

from lib.microdot import Microdot
from wifi import connect_wifi  # 导入你的 Wi-Fi 模块

# === 启动 Wi-Fi ===
connect_wifi()

# === 启动 Web 服务 ===
app = Microdot()

@app.route('/')
def index(req):
    return 'ESP32 Microdot Web 服务运行中,固定 IP 已启用!'

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

支持从 SD 卡读取 HTML 文件

项目结构

  • HTML 文件(例如 index.html)放在 SD 卡的 /www 目录下,文件结构如下:
/
├── main.py
└── wifi_config.json
├── lib/
│   └── wifi.py
│   └── scard.py // [SD卡库的试用](https://blog.csdn.net/ResumeProject/article/details/148798245)
│   └── microdot/
│       └── __init__.py   
│       └──microdot.py
(sd卡根目录)
└── www/
    ├── index.html
    ├── about.html
    └── style.css

在这里插入图片描述

修改 main.py 代码

from lib.microdot import Microdot, Response
from wifi import connect_wifi
from scard import SDCard
from machine import SPI, Pin
import os

def mount_sd():
    try:
        spi = SPI(2, baudrate=1_000_000,
                  sck=Pin(5),
                  mosi=Pin(6),
                  miso=Pin(7))
        cs = Pin(4, Pin.OUT)
        sd = SDCard(spi, cs)
        os.mount(sd, '/sd')
        print("✅ SD 卡挂载成功:", os.listdir('/sd'))
        return True
    except Exception as e:
        print("❌ SD 卡挂载失败:", e)
        return False

# 初始化
connect_wifi()
mount_sd()

Response.default_content_type = 'text/html'
app = Microdot()

@app.route('/')
def index(req):
    try:
        with open('/sd/www/index.html') as f:
            return f.read()
    except Exception as e:
        return f"<h1>无法加载页面</h1><p>{e}</p>", 500

@app.route('/<path:path>')
def serve_static(req, path):
    full_path = '/sd/www/' + path
    if os.path.isfile(full_path):
        try:
            with open(full_path) as f:
                return f.read()
        except:
            return '读取失败', 500
    return '404 Not Found', 404

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


index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>ESP32 Web</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>欢迎来到 ESP32</h1>
  <p>此页面从 SD 卡 /www/index.html 加载</p>
  <a href="about.html">关于</a>
</body>
</html>

界面效果

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到