通过Claude Code进行AI驱动的ESP32 MicroPython开发
这是一个完整的模型上下文协议(MCP)桥接器,它使Claude Code能够通过浏览器中的WebSerial API在ESP32设备上开发、上传和管理MicroPython程序。
Claude Code ──► MCP客户端 ──► WebSocket ──► 浏览器 ──► WebSerial API ──► ESP32
▲ │
└───────── 响应 ────────┘
pip install -r requirements.txt
python esp32_bridge_server.py
服务器运行在 http://localhost:3000
导航至 http://localhost:3000 在Chrome或Edge中(需要WebSerial)
添加到你的Claude Code MCP配置中:
{
"mcpServers": {
"esp32-bridge": {
"command": "python",
"args": ["/workspace/mcp_client.py", "ws://localhost:3000"],
"env": {}
}
}
}
| 工具 | 描述 | 参数 |
|---|---|---|
upload_code | 将MicroPython代码上传到ESP32 | code (字符串), filename (可选) |
execute_command | 在REPL中执行命令 | command (字符串) |
read_console | 获取最近的控制台输出 | lines (可选,默认值:110) |
reset_device | 软重启ESP32 | 无 |
list_files | 列出文件系统文件 | 无 |
将这段LED闪烁代码上传到我的ESP32:
import time
from machine import Pin
led = Pin(2, Pin.OUT)
while True:
led.on()
time.sleep(0.5)
led.off()
time.sleep(0.5)
Claude Code将自动:
main.py上传# 运行所有测试
pytest tests/ -v
# 运行特定测试文件
pytest tests/test_mcp.py -v
# 使用覆盖率运行
pytest tests/ --cov=mcp_handler --cov-report=html
# 启动桥接服务器(终端1)
python esp32_bridge_server.py
# 启动模拟ESP32(终端2)
python tests/mock_esp32.py
# 运行集成测试(终端3)
pytest tests/test_integration.py -v
# 为开发启动模拟ESP32
python tests/mock_esp32.py --port 3001 --debug
# 使用curl测试
curl http://localhost:3001/health
esp32-webserial-bridge/
├── esp32_bridge_server.py # 主Flask WebSocket服务器
├── mcp_handler.py # MCP协议实现
├── mcp_client.py # Claude Code入口点
├── claude_code_config.json # MCP服务器配置
├── requirements.txt # Python依赖
├── templates/
│ └── esp32_bridge.html # 网络界面
├── tests/
│ ├── test_mcp.py # 单元测试
│ ├── test_integration.py # 集成测试
│ └── mock_esp32.py # 模拟ESP32服务器
└── README.md # 此文件
FLASK_DEBUG - 启用Flask调试模式WEBSOCKET_URL - WebSocket服务器URL(默认:ws://localhost:3000)MCP_TIMEOUT - MCP请求超时时间(秒,默认:30)mcp_handler.py的_handle_tools_list()中添加工具定义_handle_tools_call()中实现处理器templates/esp32_bridge.html🔧 检查当前MCP配置
# 列出所有已配置的MCP服务器
claude mcp list
# 获取关于esp32-bridge服务器的详细信息
claude mcp get esp32-bridge
🔧 更新MCP服务器端口 如果您的ESP32桥接器配置了错误的端口:
# 移除现有配置
claude mcp remove esp32-bridge -s local
# 使用正确的端口(3000)添加
claude mcp add esp32-bridge /workspace/venv/bin/python /workspace/mcp_client.py http://localhost:3000
🔧 MCP服务器状态
~/.claude.json(本地项目范围)🔴 WebSerial API不支持
🔴 ESP32未被检测到
🔴 WebSocket连接失败
🔴 MCP客户端无响应
# 启用调试日志
python mcp_client.py --debug ws://localhost:3000
# 检查服务器健康状况
curl http://localhost:3000/health
# 查看WebSocket连接
curl http://localhost:3000/api/connections
git checkout -b feature/awesome-featurepytest tests/ -vMIT许可证
为ESP32和AI开发社区制作 ❤️