Skip to content

Commit 1fc94eb

Browse files
committed
Bug fixing and documentation updates
1 parent 702e39e commit 1fc94eb

11 files changed

Lines changed: 1000 additions & 308 deletions

File tree

CLAUDE.md

Lines changed: 56 additions & 209 deletions
Original file line numberDiff line numberDiff line change
@@ -2,217 +2,64 @@
22

33
## Project Overview
44

5-
Megahub is an ESP32-based robotics experimentation platform that combines LEGO WeDo/Powered Up! device support with Lua scripting and Blockly visual programming. The project consists of:
5+
Megahub is an ESP32-based robotics experimentation platform combining LEGO WeDo/Powered Up! device support with Lua scripting and Blockly visual programming.
66

7-
- **Firmware**: C++ embedded code running on ESP32 (PlatformIO)
8-
- **Frontend**: Web-based IDE built with Vite, Blockly, and vanilla JavaScript
9-
- **Libraries**: Custom ESP32 libraries for Bluetooth, UART, IMU, etc.
7+
- **Firmware**: C++ on ESP32, built with PlatformIO
8+
- **Frontend**: Web-based IDE (Vite, Blockly, vanilla JS) embedded in firmware flash
9+
- **Libraries**: Custom ESP32 libs for BLE, UART, IMU, Lua, HTTP in `/lib/`
1010

1111
## Critical Rules
1212

1313
1. **ALWAYS use the `implement-review-loop` agent** for code changes
14-
2. **ALWAYS update README.md** when adding, removing, or changing:
15-
- Configuration options
16-
- User-facing behavior
17-
- Troubleshooting information
18-
3. **NEVER duplicate README content here** - this file is for development context only
19-
5. Always use Context7 MCP when I need library/API documentation, code generation, setup or configuration steps without me having to explicitly ask.
20-
21-
### Memory Management
22-
23-
**ESP32 memory is severely constrained. Always be mindful of:**
24-
25-
1. **Stack Usage**: The ESP32 has limited stack space (~8KB per task). Avoid large local arrays or deep recursion.
26-
2. **Heap Fragmentation**: Minimize dynamic allocations. Reuse buffers where possible.
27-
3. **PSRAM**: The board may have PSRAM, but don't assume it's always available.
28-
4. **String Operations**: Be careful with String class; prefer fixed buffers or std::string with reserve().
29-
5. **Lua VM Memory**: The Lua interpreter runs in constrained memory. Large scripts can cause crashes.
30-
31-
**Memory Best Practices:**
32-
- Use the already existing custom `INFO`, `ERROR` or `WARN` logging macros instead of excessive `Serial.print()`
33-
- Avoid creating temporary String objects in loops
34-
- Monitor free heap with `ESP.getFreeHeap()` during development
35-
- Use `const` and `PROGMEM` for large constant data
36-
37-
### Bluetooth BLE Connectivity
38-
39-
**Bluetooth is complex and fragile on ESP32. Follow these rules strictly:**
40-
41-
1. **Connection State Management**: Always track connection state properly. Don't assume connections persist.
42-
2. **MTU Negotiation**: Handle MTU size properly. Default is 23 bytes, negotiated up to 512.
43-
3. **Notification Callbacks**: BLE notifications are asynchronous. Handle them in a non-blocking manner.
44-
4. **Pairing & Bonding**: The Web Bluetooth API has specific pairing requirements.
45-
5. **Multiple Connections**: The ESP32 can handle multiple BLE connections, but each consumes memory.
46-
6. **Classic BT vs BLE**: The project uses both Classic Bluetooth (for HID gamepads) and BLE (for LEGO devices and Web Bluetooth API).
47-
48-
**Bluetooth Best Practices:**
49-
- Never block in BLE callbacks
50-
- Always implement proper error handling for disconnections
51-
- Test with actual devices, not just simulators
52-
- Be aware of Web Bluetooth API browser compatibility (Chrome/Edge/Opera only)
53-
- Handle reconnection scenarios gracefully
54-
- Monitor connection events and clean up resources on disconnect
55-
56-
### LEGO Device Communication
57-
58-
**LEGO Powered Up protocol specifics:**
59-
60-
1. **UART Protocol**: Uses custom UART communication at specific baud rates
61-
2. **Device Detection**: Devices send identification messages on connection
62-
3. **Command Timing**: Some devices require specific timing between commands
63-
4. **Power Management**: Devices can enter sleep mode; handle wake-up properly
64-
5. **Port Configuration**: Track which devices are on which ports (0-3)
65-
66-
**LEGO Best Practices:**
67-
- Implement proper device initialization sequences
68-
- Handle device disconnection/reconnection
69-
- Respect command rate limits to avoid overwhelming devices
70-
- Parse device responses correctly (byte order, message structure)
71-
72-
### Build System & Project Structure
73-
74-
**PlatformIO Configuration:**
75-
- Build environment: `esp-wrover-kit`
76-
- Framework: Arduino + ESP-IDF hybrid
77-
- Custom partition table: [custom_4mb_noota.csv](custom_4mb_noota.csv)
78-
- Pre-build scripts: [gitversion.py](gitversion.py), [buildfrontend.py](buildfrontend.py), [embedfiles.py](embedfiles.py)
79-
80-
**Directory Structure:**
81-
```
82-
/lib/ Custom ESP32 libraries
83-
/btremote/ Bluetooth BLE server & Classic BT HID host
84-
/commands/ Command processing system
85-
/configuration/ WiFi & system configuration
86-
/hubwebserver/ HTTP server (PsychicHttp)
87-
/imu/ MPU6050 IMU support
88-
/lpfuart/ LEGO Powered Up UART protocol
89-
/lua/ Lua 5.4 interpreter
90-
/megahub/ Main application library
91-
/portstatus/ Port status tracking
92-
/inputdevices/ Gamepad/input device support
93-
/statusmonitor/ System monitoring
94-
95-
/src/ Main application entry point
96-
main.cpp Arduino setup() and loop()
97-
98-
/frontend/ Web-based IDE
99-
/src/ JavaScript source files
100-
package.json NPM dependencies (Blockly, Vite)
101-
vite.config.js Vite build configuration
102-
```
103-
104-
**Build Process:**
105-
1. Pre-build scripts run (git version, frontend build, file embedding)
106-
2. Frontend is built and embedded into firmware as compressed files
107-
3. PlatformIO compiles C++ code
108-
4. Single binary is flashed to ESP32
109-
110-
### Frontend Development
111-
112-
**Frontend Tech Stack:**
113-
- **Vite**: Build tool and dev server
114-
- **Blockly**: Visual programming blocks
115-
- **Vanilla JS**: No framework (intentionally lightweight)
116-
- **Web Bluetooth API**: Browser-based BLE communication
117-
- **Prism.js**: Syntax highlighting for Lua code
118-
119-
**Frontend Build Modes:**
120-
- `dev`: Development mode with hot reload
121-
- `bt`: Bluetooth mode (Deployed as Megahub IDE on Github)
122-
- `web`: Web mode (WebServer is running on firmware)
123-
124-
**Frontend Best Practices:**
125-
- Keep bundle size small (embedded in ESP32 flash)
126-
- Minimize dependencies
127-
- Handle Web Bluetooth API errors gracefully
128-
- Test in supported browsers (Chrome, Edge, Opera)
129-
- Use compression (gzip) for embedded files
130-
131-
### Common Pitfalls to Avoid
132-
133-
1. **Bluetooth Race Conditions**: Always use proper synchronization when accessing BLE state from multiple tasks
134-
2. **Memory Leaks**: Every `new` or `malloc` must have corresponding `delete` or `free`
135-
3. **Stack Overflow**: Don't allocate large arrays on the stack; use heap or static storage
136-
4. **String Concatenation**: Avoid repeated `+=` operations on String objects
137-
5. **Blocking Operations**: Never block in BLE callbacks, ISRs, or FreeRTOS tasks without proper timeout
138-
6. **Lua Errors**: Always wrap Lua execution in error handlers to prevent firmware crashes
139-
7. **Frontend Bundle Size**: Keep JavaScript bundles small; the ESP32 flash is limited
140-
8. **Web Bluetooth Permissions**: User gesture required to trigger Bluetooth pairing
141-
9. **LEGO Device Timeouts**: Some LEGO devices timeout if no command is received within ~1 second
142-
10. **IMU Calibration**: MPU6050 requires proper initialization sequence; don't skip delays
143-
144-
### Testing & Debugging
145-
146-
**Serial Monitor:**
147-
- Baud rate: 115200
148-
- Use `pio device monitor` or VSCode PlatformIO extension
149-
- Log levels controlled by `CORE_DEBUG_LEVEL` (currently set to 2)
150-
151-
**Common Debugging Techniques:**
152-
- Monitor free heap: `ESP.getFreeHeap()`
153-
- Check task stack: `uxTaskGetStackHighWaterMark()`
154-
- Use ESP32 exception decoder for crash analysis
155-
- Web browser console for frontend debugging
156-
- Bluetooth HCI logs (enable in ESP-IDF menuconfig)
157-
158-
**Unit Testing:**
159-
- Framework: Unity (PlatformIO)
160-
- Test files should be in `/test` directory
161-
- Run with `pio test`
162-
163-
### Important Files Reference
164-
165-
- [platformio.ini](platformio.ini) - Build configuration
166-
- [src/main.cpp](src/main.cpp) - Application entry point
167-
- [lib/btremote/src/btremote.cpp](lib/btremote/src/btremote.cpp) - Bluetooth implementation
168-
- [lib/megahub/src/libluahub.cpp](lib/megahub/src/libluahub.cpp) - Lua bindings
169-
- [frontend/src/bleclient.js](frontend/src/bleclient.js) - Web Bluetooth client
170-
- [frontend/src/index.js](frontend/src/index.js) - Frontend main application
171-
172-
### Key Architecture Concepts
173-
174-
1. **Dual Mode Operation**: The device can operate in Bluetooth mode (default) or WiFi mode
175-
2. **Embedded Web Server**: Frontend files are embedded in firmware and served via PsychicHttp
176-
3. **Command Pattern**: All operations use a command pattern (see [lib/commands](lib/commands))
177-
4. **Port Abstraction**: Generic port interface supports both LEGO and standard devices
178-
5. **Lua Sandbox**: Lua scripts run in a controlled environment with custom bindings
179-
6. **Blockly Code Generation**: Blockly blocks generate Lua code which is then executed
180-
181-
### Performance Considerations
182-
183-
- **WiFi vs Bluetooth**: WiFi has better throughput but higher power consumption
184-
- **Lua Execution**: Lua is interpreted; performance-critical code should be in C++
185-
- **BLE MTU**: Larger MTU = better throughput but requires negotiation
186-
- **FastLED**: Can consume significant CPU time; use carefully in time-critical code
187-
- **I2C Bus Speed**: IMU and other I2C devices share a bus; consider timing
188-
189-
### Resources & Documentation
190-
191-
- [README.md](README.md) - User-facing documentation
192-
- [BLOCKS.md](BLOCKS.md) - Blockly blocks reference, automatically generated
193-
- ESP32 Documentation: https://docs.espressif.com/projects/esp-idf/
194-
- Web Bluetooth API: https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API
195-
- Lua 5.4 Reference: https://www.lua.org/manual/5.4/
196-
- Blockly Documentation: https://developers.google.com/blockly
197-
198-
## Quick Reference for Claude
199-
200-
**Before making changes:**
201-
1. Read relevant source files to understand current implementation
202-
2. Consider memory implications (heap, stack, flash)
203-
3. For Bluetooth code, review connection state management
204-
4. For LEGO code, verify protocol compliance
205-
5. Use implement-review-loop agent for significant changes
206-
207-
**When in doubt:**
208-
- Ask the user for clarification
209-
- Check existing code for patterns and conventions
210-
- Test on actual hardware when possible
211-
- Document assumptions and limitations
212-
213-
**Remember:**
214-
- ESP32 memory is limited - optimize aggressively
215-
- Bluetooth is fragile - handle errors gracefully
216-
- LEGO protocol is strict - follow specifications
217-
- Frontend must be lightweight - minimize bundle size
218-
- Always consider multi-threading implications (FreeRTOS)
14+
2. **ALWAYS update README.md** when adding, removing, or changing user-facing behavior, config options, or troubleshooting info
15+
3. **NEVER duplicate README content here** — this file is for development context only
16+
4. **Always use Context7 MCP** for library/API documentation without being asked
17+
18+
## Skill Files (auto-loaded when relevant)
19+
20+
Domain-specific context is in `.claude/skills/` and loads automatically:
21+
22+
| Skill | Triggers on |
23+
|-------|-------------|
24+
| `frontend` | Work in `/frontend/` — theme, UI, components, BLE client, build modes |
25+
| `blockly` | Blockly blocks — block definitions, Lua generators, toolbox, BLOCKS.md |
26+
| `firmware-core` | General firmware — PlatformIO, build scripts, library structure |
27+
| `ble` | Bluetooth — BLE GATT server, Classic BT HID, connection handling |
28+
| `lego-protocol` | LEGO devices — UART, device init, motor noise/corruption |
29+
| `memory-freertos` | Memory, heap, stack, FreeRTOS tasks, synchronization |
30+
| `lua-integration` | Lua scripting, bindings, error handling, Blockly→Lua pipeline |
31+
| `documentation` | Doc structure, README outline, style rules, what to update and when |
32+
33+
## Key Architecture
34+
35+
1. **Dual mode**: Bluetooth mode (default, Web Bluetooth API) or WiFi mode (embedded HTTP server)
36+
2. **Embedded frontend**: Built by Vite, gzipped, embedded in firmware as C arrays
37+
3. **Command pattern**: All device operations use a command pattern (`lib/commands/`)
38+
4. **Port abstraction**: Generic port interface supports both LEGO and standard devices
39+
5. **Lua sandbox**: Lua 5.4 scripts run in a controlled environment with custom bindings
40+
6. **Blockly → Lua**: Blockly blocks generate Lua code which is then executed on the device
41+
42+
## Important Files
43+
44+
| File | Purpose |
45+
|------|---------|
46+
| [platformio.ini](platformio.ini) | Build configuration |
47+
| [src/main.cpp](src/main.cpp) | Application entry point |
48+
| [lib/btremote/src/btremote.cpp](lib/btremote/src/btremote.cpp) | BLE server + Classic BT host |
49+
| [lib/megahub/src/libluahub.cpp](lib/megahub/src/libluahub.cpp) | Lua bindings |
50+
| [frontend/src/index.js](frontend/src/index.js) | Frontend app controller |
51+
| [frontend/src/bleclient.js](frontend/src/bleclient.js) | Web Bluetooth client |
52+
| [frontend/src/theme.css](frontend/src/theme.css) | VS Code theme CSS variables |
53+
| [frontend/src/styles.css](frontend/src/styles.css) | Global styles and all UI component CSS |
54+
| [README.md](README.md) | User-facing documentation |
55+
56+
## Quick Reference
57+
58+
**Before any change:**
59+
1. Read the relevant source files first — understand before modifying
60+
2. Load the appropriate skill file for domain context
61+
3. For firmware: consider memory (heap, stack, flash) implications
62+
4. For frontend: check the theme system and existing UI patterns
63+
5. Use the `implement-review-loop` agent for all significant changes
64+
65+
**When in doubt:** Ask. Never guess at protocol details, memory limits, or BLE behavior.

0 commit comments

Comments
 (0)