refactor: Fixed the file hierarchy and switched to platform.io
This commit is contained in:
+13
-8
@@ -1,16 +1,21 @@
|
||||
.vscode/
|
||||
docs/
|
||||
html/
|
||||
vesper/build/
|
||||
vesper/sd_settings/
|
||||
vesper/CLAUDE.md
|
||||
vesper/flutter/
|
||||
vesper/docs_manual/
|
||||
build/
|
||||
sd_settings/
|
||||
CLAUDE.md
|
||||
flutter/
|
||||
docs_manual/
|
||||
Doxyfile
|
||||
vesper/.claude/
|
||||
.claude/
|
||||
|
||||
# PlatformIO — build output and downloaded libraries (never commit these)
|
||||
vesper/.pio/
|
||||
.pio/
|
||||
|
||||
# Local PlatformIO overrides (contains secrets — never commit)
|
||||
platformio.ini.local
|
||||
|
||||
# Per-device NVS binaries (generated, never commit)
|
||||
provisioning/*.bin
|
||||
|
||||
# Claude Code memory/session files
|
||||
.claude/
|
||||
@@ -0,0 +1,841 @@
|
||||
# Communication Subsystem — Complete Refactor Plan
|
||||
|
||||
> Written: 2026-02-27
|
||||
> Status: **Planning** — Not yet implemented
|
||||
> Related: MQTT refactor, Logging refactor (separate plans)
|
||||
|
||||
---
|
||||
|
||||
## Current State Assessment
|
||||
|
||||
### What works well
|
||||
- Unified JSON command format across all protocols — worth keeping
|
||||
- CommunicationRouter as the central hub — right architectural instinct
|
||||
- Non-blocking async design — correct
|
||||
- ResponseBuilder consistency — good
|
||||
|
||||
### What's broken architecturally
|
||||
- `CommandHandler.cpp` is ~700+ lines of a single giant `if/else if` chain — classic "God Class" anti-pattern
|
||||
- HTTP is a second-class citizen, faking a WebSocket context with `clientId=0xFFFFFFFF` — no proper identity
|
||||
- `MessageSource` has no `HTTP` value — HTTP is disguised as WebSocket throughout the code
|
||||
- CommandHandler has 8 injected dependencies via raw pointers + setters — tightly coupled to everything
|
||||
- Sub-commands (`relay_setup → set_timings`) are a second level of `if/else` inside the first — inconsistent
|
||||
- No protocol versioning — adding the 4th transport requires touching CommandHandler again
|
||||
- `SettingsWebServer` bypasses the command system entirely
|
||||
|
||||
---
|
||||
|
||||
## Architectural Philosophy
|
||||
|
||||
**Target pattern:** A transport-agnostic command bus with registered handlers.
|
||||
|
||||
- **Transport Layer** — MQTT, WebSocket, HTTP, UART, future WebServer — each just delivers a `CommandEnvelope` to the bus
|
||||
- **Command Bus** — receives envelopes, dispatches to the right handler by command name
|
||||
- **Command Handlers** — small, focused classes, one per domain (Playback, Clock, Relay, System, etc.)
|
||||
- **Response** — returned to the bus, which delivers it back through the originating transport
|
||||
|
||||
Pattern: **Command Pattern + Message Bus** (standard embedded system architecture)
|
||||
|
||||
---
|
||||
|
||||
## New Directory Structure
|
||||
|
||||
```
|
||||
src/Communication/
|
||||
├── Transport/
|
||||
│ ├── ITransport.hpp ← Interface all transports implement
|
||||
│ ├── MQTTTransport/
|
||||
│ │ ├── MQTTTransport.hpp
|
||||
│ │ └── MQTTTransport.cpp
|
||||
│ ├── WebSocketTransport/
|
||||
│ │ ├── WebSocketTransport.hpp
|
||||
│ │ └── WebSocketTransport.cpp
|
||||
│ ├── HTTPTransport/
|
||||
│ │ ├── HTTPTransport.hpp
|
||||
│ │ └── HTTPTransport.cpp
|
||||
│ ├── UARTTransport/
|
||||
│ │ ├── UARTTransport.hpp
|
||||
│ │ └── UARTTransport.cpp
|
||||
│ └── WebServerTransport/ ← Future 4th transport, slot ready
|
||||
│ └── (placeholder)
|
||||
│
|
||||
├── CommandBus/
|
||||
│ ├── CommandBus.hpp ← Registry + dispatcher
|
||||
│ ├── CommandBus.cpp
|
||||
│ ├── CommandEnvelope.hpp ← Universal message wrapper
|
||||
│ ├── CommandResult.hpp ← Standardized return type
|
||||
│ └── LegacyAdapter.hpp/cpp ← Optional: v1 legacy shim (deletable)
|
||||
│
|
||||
├── Handlers/
|
||||
│ ├── ICommandHandler.hpp ← Handler interface
|
||||
│ ├── PlaybackHandler/
|
||||
│ ├── FileHandler/
|
||||
│ ├── RelayHandler/
|
||||
│ ├── ClockHandler/
|
||||
│ ├── SystemHandler/
|
||||
│ ├── FirmwareHandler/
|
||||
│ ├── NetworkHandler/
|
||||
│ └── LoggingHandler/
|
||||
│
|
||||
├── ResponseBuilder/ ← Keep as-is, add fromResult() factory
|
||||
│ ├── ResponseBuilder.hpp
|
||||
│ └── ResponseBuilder.cpp
|
||||
│
|
||||
└── CommunicationRouter/ ← Keeps coordinating role, simplified
|
||||
├── CommunicationRouter.hpp
|
||||
└── CommunicationRouter.cpp
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Core Data Structures
|
||||
|
||||
### CommandEnvelope
|
||||
Replaces `JsonDocument + MessageContext`.
|
||||
|
||||
```cpp
|
||||
// CommandBus/CommandEnvelope.hpp
|
||||
struct CommandEnvelope {
|
||||
// Protocol version — enables forward compatibility
|
||||
uint8_t version; // 2 = new, 1 = legacy (default 2)
|
||||
|
||||
enum class Transport {
|
||||
MQTT,
|
||||
WEBSOCKET,
|
||||
HTTP,
|
||||
UART
|
||||
} transport;
|
||||
|
||||
uint32_t clientId; // WS client ID, 0 for others
|
||||
|
||||
String command; // e.g. "playback", "relay_setup"
|
||||
JsonDocument contents; // The "contents" object
|
||||
|
||||
// Reply callback injected by the transport
|
||||
std::function<void(const CommandResult&)> reply;
|
||||
};
|
||||
```
|
||||
|
||||
### CommandResult
|
||||
Replaces ad-hoc string building in handler methods.
|
||||
|
||||
```cpp
|
||||
// CommandBus/CommandResult.hpp
|
||||
struct CommandResult {
|
||||
enum class Status { SUCCESS, ERROR, INFO };
|
||||
|
||||
Status status;
|
||||
String type; // command type echo
|
||||
String payload; // string payload
|
||||
JsonDocument data; // structured data payload (optional)
|
||||
bool hasData = false;
|
||||
|
||||
// Factory methods
|
||||
static CommandResult ok(const String& type, const String& msg = "");
|
||||
static CommandResult ok(const String& type, const JsonDocument& data);
|
||||
static CommandResult err(const String& type, const String& msg);
|
||||
};
|
||||
```
|
||||
|
||||
### ICommandHandler
|
||||
Interface every domain handler implements.
|
||||
|
||||
```cpp
|
||||
// Handlers/ICommandHandler.hpp
|
||||
class ICommandHandler {
|
||||
public:
|
||||
virtual ~ICommandHandler() = default;
|
||||
|
||||
// Returns the command name(s) this handler owns
|
||||
virtual std::vector<String> commands() const = 0;
|
||||
|
||||
// Execute the command, return result
|
||||
virtual CommandResult execute(const CommandEnvelope& envelope) = 0;
|
||||
};
|
||||
```
|
||||
|
||||
### ITransport
|
||||
Interface every transport implements.
|
||||
|
||||
```cpp
|
||||
// Transport/ITransport.hpp
|
||||
class ITransport {
|
||||
public:
|
||||
virtual ~ITransport() = default;
|
||||
|
||||
virtual void begin() = 0;
|
||||
virtual void loop() = 0;
|
||||
virtual bool isHealthy() const = 0;
|
||||
virtual String name() const = 0;
|
||||
|
||||
// Broadcast to all clients of this transport
|
||||
virtual void broadcast(const String& message) = 0;
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## The CommandBus
|
||||
|
||||
Replaces the giant `if/else` chain. The entire dispatcher is ~10 lines.
|
||||
|
||||
```cpp
|
||||
// CommandBus/CommandBus.hpp
|
||||
class CommandBus {
|
||||
public:
|
||||
void registerHandler(std::unique_ptr<ICommandHandler> handler);
|
||||
void dispatch(CommandEnvelope& envelope);
|
||||
void broadcast(const CommandResult& result);
|
||||
void addTransport(ITransport* transport);
|
||||
|
||||
private:
|
||||
std::unordered_map<String, ICommandHandler*> _registry;
|
||||
std::vector<std::unique_ptr<ICommandHandler>> _handlers;
|
||||
std::vector<ITransport*> _transports;
|
||||
};
|
||||
|
||||
// CommandBus/CommandBus.cpp
|
||||
void CommandBus::dispatch(CommandEnvelope& envelope) {
|
||||
auto it = _registry.find(envelope.command);
|
||||
if (it == _registry.end()) {
|
||||
envelope.reply(CommandResult::err("unknown", "Unknown command: " + envelope.command));
|
||||
return;
|
||||
}
|
||||
CommandResult result = it->second->execute(envelope);
|
||||
envelope.reply(result);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Per-Domain Handler Pattern
|
||||
|
||||
Each handler: ~50–100 lines, focused, one dependency set, independently testable.
|
||||
|
||||
```cpp
|
||||
// Handlers/PlaybackHandler/PlaybackHandler.hpp
|
||||
class PlaybackHandler : public ICommandHandler {
|
||||
public:
|
||||
explicit PlaybackHandler(Player& player);
|
||||
std::vector<String> commands() const override;
|
||||
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||
private:
|
||||
Player& _player;
|
||||
};
|
||||
|
||||
// Handlers/PlaybackHandler/PlaybackHandler.cpp
|
||||
std::vector<String> PlaybackHandler::commands() const {
|
||||
return { "playback" };
|
||||
}
|
||||
|
||||
CommandResult PlaybackHandler::execute(const CommandEnvelope& envelope) {
|
||||
bool ok = _player.command(envelope.contents.as<JsonVariant>());
|
||||
if (ok) return CommandResult::ok("playback", "Command executed");
|
||||
return CommandResult::err("playback", "Player rejected command");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Transport Layer Pattern
|
||||
|
||||
Each transport parses raw input, builds a `CommandEnvelope` with a reply lambda, and dispatches.
|
||||
|
||||
```cpp
|
||||
// WebSocketTransport — on message received:
|
||||
void WebSocketTransport::onMessage(uint32_t clientId, const String& raw) {
|
||||
JsonDocument doc;
|
||||
if (deserializeJson(doc, raw) != DeserializationError::Ok) {
|
||||
sendToClient(clientId, ResponseBuilder::error("parse", "Invalid JSON"));
|
||||
return;
|
||||
}
|
||||
|
||||
CommandEnvelope envelope;
|
||||
envelope.transport = CommandEnvelope::Transport::WEBSOCKET;
|
||||
envelope.clientId = clientId;
|
||||
envelope.command = doc["cmd"].as<String>();
|
||||
envelope.contents = doc["contents"];
|
||||
envelope.version = doc["v"] | 2;
|
||||
|
||||
envelope.reply = [this, clientId](const CommandResult& result) {
|
||||
sendToClient(clientId, ResponseBuilder::fromResult(result));
|
||||
};
|
||||
|
||||
_commandBus.dispatch(envelope);
|
||||
}
|
||||
```
|
||||
|
||||
HTTP is now a proper first-class transport — no more `0xFFFFFFFF` hack:
|
||||
|
||||
```cpp
|
||||
// HTTPTransport — on POST /api/command:
|
||||
envelope.transport = CommandEnvelope::Transport::HTTP;
|
||||
envelope.reply = [request](const CommandResult& result) {
|
||||
request->send(200, "application/json", ResponseBuilder::fromResult(result));
|
||||
};
|
||||
```
|
||||
|
||||
UART keeps its whitelist — lives inside `UARTTransport`, not in the bus:
|
||||
|
||||
```cpp
|
||||
// UARTTransport — before dispatch:
|
||||
if (!isWhitelisted(envelope.command)) {
|
||||
// silently ignore (prevent feedback loops)
|
||||
return;
|
||||
}
|
||||
_commandBus.dispatch(envelope);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Simplified CommunicationRouter
|
||||
|
||||
```cpp
|
||||
class CommunicationRouter {
|
||||
public:
|
||||
CommunicationRouter(/* core dependencies */);
|
||||
|
||||
void begin();
|
||||
void loop();
|
||||
bool isHealthy() const;
|
||||
|
||||
// For subsystems pushing events (telemetry, bell strikes, etc.)
|
||||
void broadcast(const CommandResult& event);
|
||||
void broadcastToMasters(const String& message);
|
||||
|
||||
private:
|
||||
CommandBus _commandBus;
|
||||
|
||||
MQTTTransport _mqtt;
|
||||
WebSocketTransport _ws;
|
||||
HTTPTransport _http;
|
||||
UARTTransport _uart;
|
||||
|
||||
void registerHandlers(); // Replaces all setXxxReference() calls
|
||||
};
|
||||
|
||||
// All handler wiring in one place:
|
||||
void CommunicationRouter::registerHandlers() {
|
||||
_commandBus.registerHandler(std::make_unique<PlaybackHandler>(_player));
|
||||
_commandBus.registerHandler(std::make_unique<RelayHandler>(_configManager));
|
||||
_commandBus.registerHandler(std::make_unique<ClockHandler>(_configManager, _timeKeeper));
|
||||
_commandBus.registerHandler(std::make_unique<FileHandler>(_fileManager));
|
||||
_commandBus.registerHandler(std::make_unique<SystemHandler>(_configManager, _networking));
|
||||
_commandBus.registerHandler(std::make_unique<FirmwareHandler>(_firmwareValidator, _otaManager));
|
||||
_commandBus.registerHandler(std::make_unique<NetworkHandler>(_configManager, _networking));
|
||||
_commandBus.registerHandler(std::make_unique<LoggingHandler>(_logging));
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sub-Command Strategy
|
||||
|
||||
Two options — pick one:
|
||||
|
||||
### Option A — Flatten (Recommended for new protocol)
|
||||
Register `relay.set_timings` and `relay.set_outputs` as separate top-level commands. Removes nested `if/else` entirely.
|
||||
```json
|
||||
{ "cmd": "relay.set_timings", "v": 2, "contents": { ... } }
|
||||
```
|
||||
|
||||
### Option B — Keep Nesting (Recommended for wire compatibility)
|
||||
Keep `relay_setup` as the command. `RelayHandler` switches on `contents["action"]` internally. Still clean because it's isolated in one small class.
|
||||
```json
|
||||
{ "cmd": "relay_setup", "contents": { "action": "set_timings", ... } }
|
||||
```
|
||||
|
||||
**Decision:** Option B is safer if FlutterFlow app rollout is staggered. Wire format stays identical.
|
||||
|
||||
---
|
||||
|
||||
## Protocol Versioning / Legacy Compatibility
|
||||
|
||||
`CommandEnvelope.version` enables a clean cutover:
|
||||
|
||||
- Client sends `"v": 1` (or omits `v`) → treated as legacy
|
||||
- Client sends `"v": 2` → goes straight through
|
||||
|
||||
```cpp
|
||||
// CommandBus/LegacyAdapter.hpp / .cpp
|
||||
// Maps old command names / content shapes to new ones
|
||||
// Completely deletable in one PR when legacy support ends
|
||||
|
||||
static const std::unordered_map<String, String> LEGACY_COMMAND_MAP = {
|
||||
// Add entries here only if command names change in v2
|
||||
// If names stay the same, this file may not be needed at all
|
||||
};
|
||||
|
||||
void translateLegacyEnvelope(CommandEnvelope& env) {
|
||||
auto it = LEGACY_COMMAND_MAP.find(env.command);
|
||||
if (it != LEGACY_COMMAND_MAP.end()) {
|
||||
env.command = it->second;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Recommendation:** If command names stay identical between v1 and v2, skip the legacy adapter entirely and just force-update the FlutterFlow app.
|
||||
|
||||
---
|
||||
|
||||
## The 4th Transport — On-Board Web Server
|
||||
|
||||
With this architecture, adding it costs almost nothing:
|
||||
1. Create `WebServerTransport` implementing `ITransport`
|
||||
2. HTML routes POST to CommandBus via synthetic `CommandEnvelope`
|
||||
3. Register it in `CommunicationRouter::begin()`
|
||||
4. `SettingsWebServer` absorbs into this transport (fixes the current bypass of the command system)
|
||||
|
||||
---
|
||||
|
||||
## What Stays the Same
|
||||
|
||||
| Component | Action |
|
||||
|---|---|
|
||||
| `ResponseBuilder` | Keep — add `fromResult(CommandResult)` factory method |
|
||||
| `ClientManager` | Keep — used by `WebSocketTransport` |
|
||||
| Wire protocol format | Keep — `{ "cmd": "...", "contents": { ... } }` unchanged |
|
||||
| MQTT topics | Keep — no change |
|
||||
| MQTT auth system | Keep — no change |
|
||||
| UART whitelist | Keep — move into `UARTTransport` |
|
||||
|
||||
---
|
||||
|
||||
## Implementation Stages
|
||||
|
||||
### Stage 1 — Core Scaffolding ✅ / ⬜ TODO
|
||||
> No behavior change. Zero risk. Headers only.
|
||||
|
||||
- [ ] Define `CommandEnvelope.hpp`
|
||||
- [ ] Define `CommandResult.hpp`
|
||||
- [ ] Define `ICommandHandler.hpp`
|
||||
- [ ] Define `ITransport.hpp`
|
||||
- [ ] Create `CommandBus` skeleton (register + dispatch, no handlers yet)
|
||||
- [ ] Old `CommandHandler` stays untouched
|
||||
|
||||
### Stage 2 — Migrate Handlers One Domain at a Time
|
||||
> Write new handler → register on bus → comment out old if/else branch → test
|
||||
|
||||
- [ ] `PlaybackHandler` (simplest — one dependency)
|
||||
- [ ] `SystemHandler`
|
||||
- [ ] `FirmwareHandler`
|
||||
- [ ] `LoggingHandler`
|
||||
- [ ] `RelayHandler` (complex — multiple sub-commands)
|
||||
- [ ] `ClockHandler` (most complex — many sub-commands)
|
||||
- [ ] `FileHandler`
|
||||
- [ ] `NetworkHandler`
|
||||
|
||||
### Stage 3 — Transport Layer Refactor
|
||||
- [ ] Refactor `MQTTAsyncClient` → `MQTTTransport` (implement `ITransport`)
|
||||
- [ ] Refactor `WebSocketServer` → `WebSocketTransport` (implement `ITransport`)
|
||||
- [ ] Promote `HTTPRequestHandler` → `HTTPTransport` (proper HTTP identity, no more 0xFFFFFFFF)
|
||||
- [ ] Refactor `UARTCommandHandler` → `UARTTransport` (whitelist lives here)
|
||||
|
||||
### Stage 4 — CommunicationRouter Simplification
|
||||
- [ ] Replace router internals with `CommandBus` + transport array
|
||||
- [ ] Implement `registerHandlers()` — replaces all `setXxxReference()` calls
|
||||
- [ ] Delete old `CommandHandler` once all handlers migrated and tested
|
||||
|
||||
### Stage 5 — Legacy Adapter (optional)
|
||||
- [ ] Add `LegacyAdapter.cpp` if needed for staggered FlutterFlow rollout
|
||||
- [ ] Test with FlutterFlow app sending `"v": 1`
|
||||
- [ ] Set cutover date — delete adapter in one clean PR
|
||||
|
||||
### Stage 6 — SettingsWebServer Integration (4th Transport)
|
||||
- [ ] Create `WebServerTransport` skeleton
|
||||
- [ ] Absorb `SettingsWebServer` into `WebServerTransport`
|
||||
- [ ] Settings page form POSTs route through `CommandBus`
|
||||
- [ ] All 4 transports share single command pipeline
|
||||
|
||||
---
|
||||
|
||||
## Before / After Comparison
|
||||
|
||||
| Concern | Current | New |
|
||||
|---|---|---|
|
||||
| Command dispatch | 700-line `if/else` | Hash map, O(1) lookup |
|
||||
| Adding a command | Edit giant `CommandHandler` | Add a new ~50-line class |
|
||||
| HTTP identity | Fake WebSocket (`0xFFFFFFFF`) | Proper `HTTPTransport` |
|
||||
| Adding a transport | Touch `CommandHandler` | Implement `ITransport`, register |
|
||||
| Handler dependencies | 8 setter injections on one class | Explicit constructor per handler |
|
||||
| Sub-commands | Nested `if/else` inside `if/else` | Internal to focused handler class |
|
||||
| Legacy support | N/A | Isolated `LegacyAdapter`, deletable in one PR |
|
||||
| On-board WebServer | Bypasses command system | `WebServerTransport`, full integration |
|
||||
|
||||
---
|
||||
|
||||
## ESP32 Memory Notes
|
||||
|
||||
- `std::unordered_map` is fine on ESP32-D0WD for a ~10-entry registry (trivial footprint)
|
||||
- `std::unique_ptr` for handler ownership — no raw pointer leaks
|
||||
- `std::function` reply lambdas — small captures (one pointer + one uint32)
|
||||
- If memory gets tight: replace `unordered_map` with sorted static array + binary search — zero impact on handler code
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
# Command System Redesign
|
||||
|
||||
> This section documents the complete v2 command API — what changes, what's removed, what's new, and the full canonical command table.
|
||||
|
||||
---
|
||||
|
||||
## What's Wrong With the Current Commands
|
||||
|
||||
### Problem 1 — Two umbrella commands doing the same job
|
||||
`system` and `system_info` are both grab-bags. Two commands even overlap directly:
|
||||
- `system → status` duplicates `system_info → report_status`
|
||||
- `system → get_firmware_status` duplicates `system_info → get_firmware_status`
|
||||
|
||||
### Problem 2 — Wrong grouping
|
||||
- `set_network_config` is buried inside `system` instead of being in a `network` namespace
|
||||
- Log level commands are inside `system` instead of a `log` namespace
|
||||
- `set_mqtt_enabled` controls a transport but lives in `system`
|
||||
- `get_device_time` and `get_clock_time` are in `system_info` but logically belong in `clock` and `system` respectively
|
||||
|
||||
### Problem 3 — Internal command exposed publicly
|
||||
- `sync_time_to_lcd` is a UART push that the device sends to its own LCD slave board. It is not a client command — a FlutterFlow app should never need to call this. It should be an internal method, not a public API endpoint.
|
||||
|
||||
### Problem 4 — Entire subsystems have zero command coverage
|
||||
- `HealthMonitor` — no commands at all
|
||||
- `Telemetry` — no commands at all
|
||||
- `OutputManager` — no direct control (relay fire/extinguish only reachable via Player)
|
||||
- `BuiltInMelodies` — list never exposed, clients can't see what's available without downloading
|
||||
|
||||
### Problem 5 — Naming inconsistency
|
||||
- `set_timings` on relay means "bell strike durations" — ambiguous
|
||||
- `restart` and `reboot` are aliases doing the same thing — pick one
|
||||
- `reset_defaults` is unclear — `factory_reset` is universally understood
|
||||
|
||||
---
|
||||
|
||||
## Handler Input Contract (Design Principle)
|
||||
|
||||
This rule applies to **every single handler** without exception. It must be enforced during implementation.
|
||||
|
||||
```
|
||||
Extra fields in contents? → Ignore silently. Never crash on unknown keys.
|
||||
Missing optional fields? → Use defaults or skip that part of the operation.
|
||||
Missing required fields? → Return ERROR with a clear message. Do nothing else.
|
||||
Wrong type / bad format? → Return ERROR with a clear message. Do nothing else.
|
||||
No contents at all? → If the command needs none, proceed. If it needs some, return ERROR.
|
||||
```
|
||||
|
||||
Concretely: if a client sends `relay.set_durations` with only bell `"0"`, update bell 0 and leave all others unchanged. Do not require all 6 bells to be present. If a client sends `relay.test_output` with no `output` field, return an error — that field is required. If a client sends `relay.test_output` with `output`, `duration_ms`, and an extra unknown field `foo`, ignore `foo` and proceed.
|
||||
|
||||
This applies to ALL multi-field commands: relay durations, relay outputs, clock outputs, clock alerts, network config, etc.
|
||||
|
||||
---
|
||||
|
||||
## Command Decisions: Keep / Change / Remove / Add
|
||||
|
||||
### KEEP (as-is or renamed)
|
||||
| Old command | Decision | Reason |
|
||||
|---|---|---|
|
||||
| `ping` | Keep → `ping` | Simple, universally understood utility |
|
||||
| `identify` | Keep → `identify` | WebSocket client-type registration, needed |
|
||||
| `playback` | Keep → `playback` | Already flat and well-structured |
|
||||
| `relay_setup → set_outputs` | Keep → `relay.set_outputs` | Correct grouping, just flatten |
|
||||
| `clock_setup → set_outputs` | Keep → `clock.set_outputs` | Correct grouping |
|
||||
| `clock_setup → set_alerts` | Keep → `clock.set_alerts` | Correct grouping |
|
||||
| `clock_setup → set_backlight` | Keep → `clock.set_backlight` | Correct grouping |
|
||||
| `clock_setup → set_silence` | Keep → `clock.set_silence` | Correct grouping |
|
||||
| `clock_setup → set_rtc_time` | Keep → `clock.set_time` | Shorter, clearer |
|
||||
| `clock_setup → set_physical_clock_time` | Keep → `clock.set_face` | "Face" = analog clock face position |
|
||||
| `clock_setup → pause_clock_updates` | Keep → `clock.pause` | Fine |
|
||||
| `clock_setup → resume_clock_updates` | Keep → `clock.resume` | Fine |
|
||||
| `system_info → get_full_settings` | Keep → `system.get_settings` | Useful, correct namespace |
|
||||
| `system_info → network_info` | Keep → `network.info` | Move to correct namespace |
|
||||
| `system → reset_defaults` | Keep → `system.factory_reset` | Rename: clearer intent |
|
||||
| `system → commit_firmware` | Keep → `firmware.commit` | Correct namespace |
|
||||
| `system → rollback_firmware` | Keep → `firmware.rollback` | Correct namespace |
|
||||
| `system → get_firmware_status` | Keep → `firmware.status` | Deduplicated, correct namespace |
|
||||
| `system → set_network_config` | Keep → `network.set_config` | Move to correct namespace |
|
||||
| `system → set_serial_log_level` | Keep → `log.set_serial` | Correct namespace |
|
||||
| `system → set_sd_log_level` | Keep → `log.set_sd` | Correct namespace |
|
||||
| `system → set_mqtt_log_level` | Keep → `log.set_mqtt` | Correct namespace |
|
||||
| `system → restart` | Keep → `system.restart` | Collapse `reboot` alias, one canonical name |
|
||||
| `system → force_update` | Keep → `ota.update` | Correct namespace |
|
||||
| `system → custom_update` | Keep → `ota.custom` | Correct namespace |
|
||||
| `file_manager → list_melodies` | Keep → `files.list` | Flat, cleaner — melodies only (SD card) |
|
||||
| `file_manager → download_melody` | Keep → `files.download` | Fine |
|
||||
| `file_manager → delete_melody` | Keep → `files.delete` | Fine |
|
||||
|
||||
### CHANGE (same function, fixed grouping or naming)
|
||||
| Old command | New command | What changes |
|
||||
|---|---|---|
|
||||
| `relay_setup → set_timings` | `relay.set_durations` | Renamed: "timings" is vague, "durations" is what it actually sets (ms per strike) |
|
||||
| `clock_setup → set_timings` | `clock.set_timings` | Keep name, but note: currently calls `updateClockOutputs()` — **bug in original code**, fix during migration |
|
||||
| `clock_setup → set_enabled` | Split into `clock.enable` / `clock.disable` | No boolean needed — intent is unambiguous, cleaner in logs and app code |
|
||||
| `system → set_mqtt_enabled` | Split into `mqtt.enable` / `mqtt.disable` | Same reasoning as clock enable/disable |
|
||||
| `system_info → report_status` | `system.status` | Moved out of umbrella, deduplicated with `system → status` |
|
||||
| `system_info → get_device_time` | `system.get_time` | Moved: this is system-level RTC time, not clock-face time |
|
||||
| `system_info → get_clock_time` | `clock.get_face` | Moved to `clock` namespace — returns analog face position |
|
||||
| `telemetry.reset_strikes` | `telemetry.reset_strikes` + optional `{ "bell": N }` | Omit `bell` → reset all. Include `bell` → reset only that channel. Enables per-bell reset when a striker is replaced. |
|
||||
| `relay.test_output` | `relay.test_output` with required `duration_ms` | No default duration — caller must be explicit. Forces operator intentionality. 85–140ms is typical; 200ms is too long for sensitive strikers. Both `output` and `duration_ms` are required fields. |
|
||||
|
||||
### REMOVE
|
||||
| Old command | Reason |
|
||||
|---|---|
|
||||
| `system → status` | Duplicate of `system_info → report_status`. One survives as `system.status`. |
|
||||
| `system → get_firmware_status` (under `system`) | Duplicate. Survives as `firmware.status`. |
|
||||
| `system_info → get_firmware_status` (under `system_info`) | Duplicate. Same as above. |
|
||||
| `system → reboot` | Alias for `restart`. Removed. `system.restart` is the one. |
|
||||
| `system_info → sync_time_to_lcd` | **Removed as a public push command.** The LCD slave is a proper bidirectional UART client — it requests time with `system.get_time` and gets a response. The old model (master pushing time unsolicited) caused infinite loop bugs when responses were corrupted. The new model is clean request/response. |
|
||||
|
||||
### ADD (new commands, previously uncovered functionality)
|
||||
| New command | Handler | What it does | Why |
|
||||
|---|---|---|---|
|
||||
| `system.get_device_info` | SystemHandler | Returns device UID, hw_type, hw_version, fw_version, uptime, free heap | Currently buried in `get_full_settings` — needs its own fast endpoint |
|
||||
| `system.health` | SystemHandler | Returns full `HealthMonitor` report — all subsystem states, warnings, critical failures | `HealthMonitor` has zero command coverage today |
|
||||
| `clock.set_timezone` | ClockHandler | Sets GMT offset + DST offset + optional timezone name, saves to SD | Timezone is currently piggybacked onto `clock.set_time` — can't change timezone without resending a timestamp |
|
||||
| `clock.get_timezone` | ClockHandler | Returns current GMT offset, DST offset, timezone name | No read command for timezone today |
|
||||
| `clock.sync_ntp` | ClockHandler | Forces an immediate NTP sync via `TimeKeeper::syncTimeWithNTP()` | No on-demand NTP sync exists today |
|
||||
| `telemetry.get_strikes` | TelemetryHandler | Returns strike counts per bell channel | Currently only returned as part of `system.status` |
|
||||
| `telemetry.reset_strikes` | TelemetryHandler | Resets strike counters — all channels, or a single channel via `{ "bell": N }` | No command exists today; per-bell reset is critical for striker replacement |
|
||||
| `telemetry.get_loads` | TelemetryHandler | Returns current heat load per bell channel, cooling status, overload flags | No command exists today |
|
||||
| `files.list_builtin` | FileHandler | Returns list of all built-in melodies (name + UID) from `BuiltInMelodies::getBuiltInMelodiesJSON()` | Currently impossible for a client to know what built-ins exist without trying to play them |
|
||||
| `ota.status` | FirmwareHandler | Returns OTAManager status: current version, available version, update channel, last check time, update progress | No status query exists today |
|
||||
| `ota.check` | FirmwareHandler | Triggers `OTAManager::checkForUpdates()` and returns result immediately | No on-demand check exists today |
|
||||
| `relay.get_config` | RelayHandler | Returns current bell durations + output assignments as JSON | No read command for relay config today — only write |
|
||||
| `clock.get_config` | ClockHandler | Returns full clock configuration (outputs, timings, alerts, backlight, silence, enabled state) | No read command for clock config today — only write |
|
||||
| `network.status` | NetworkHandler | Returns connection state, IP, RSSI, AP mode flag | `network.info` only returns IP/gateway/DNS — no connection state or signal strength |
|
||||
| `relay.test_output` | RelayHandler | Fires a specific relay for a caller-specified duration. Both `output` and `duration_ms` required. Safety-gated: only works when Player is stopped | Diagnostic/commissioning — currently impossible without a full playback command |
|
||||
|
||||
---
|
||||
|
||||
## Complete v2 Command Table
|
||||
|
||||
The canonical reference. Every command in the new system.
|
||||
|
||||
### `ping`
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| Handler | SystemHandler |
|
||||
| Transport restriction | None (all transports) |
|
||||
| Contents | *(none)* |
|
||||
| Returns | `{ "status": "SUCCESS", "type": "pong" }` |
|
||||
|
||||
### `identify`
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| Handler | SystemHandler |
|
||||
| Transport restriction | WebSocket only |
|
||||
| Contents | `{ "device_type": "master" \| "secondary" }` — required |
|
||||
| Returns | Success/error |
|
||||
|
||||
### `playback`
|
||||
| Field | Value |
|
||||
|---|---|
|
||||
| Handler | PlaybackHandler |
|
||||
| Transport restriction | None |
|
||||
| Contents | `{ "action": "play" \| "stop" \| "pause" \| "unpause", ...melody attributes }` — `action` required |
|
||||
| Returns | Success/error |
|
||||
|
||||
---
|
||||
|
||||
### Relay namespace — `RelayHandler`
|
||||
|
||||
| Command | Required fields | Optional fields | Returns |
|
||||
|---|---|---|---|
|
||||
| `relay.set_durations` | *(at least one bell)* | `{ "bells": { "0": 95, "2": 110, ... } }` — partial updates accepted | Success/error |
|
||||
| `relay.set_outputs` | *(at least one bell)* | `{ "bells": { "0": 2, "1": 3, ... } }` — partial updates accepted | Success/error |
|
||||
| `relay.get_config` | *(none)* | — | `{ "durations": {...}, "outputs": {...} }` |
|
||||
| `relay.test_output` | `output`, `duration_ms` | — | Success/error — **player must be stopped** |
|
||||
|
||||
---
|
||||
|
||||
### Clock namespace — `ClockHandler`
|
||||
|
||||
| Command | Required fields | Optional fields | Returns |
|
||||
|---|---|---|---|
|
||||
| `clock.set_outputs` | *(at least one of c1, c2)* | `{ "c1": 4, "c2": 5 }` — partial OK | Success/error |
|
||||
| `clock.set_timings` | *(at least one timing field)* | timing config fields — partial OK | Success/error |
|
||||
| `clock.set_alerts` | *(at least one alert field)* | alert config fields — partial OK | Success/error |
|
||||
| `clock.set_backlight` | *(at least one field)* | backlight config fields — partial OK | Success/error |
|
||||
| `clock.set_silence` | *(at least one field)* | silence period fields — partial OK | Success/error |
|
||||
| `clock.set_time` | `timestamp` | `timezone_offset`, `dst_offset` | Success/error |
|
||||
| `clock.set_face` | `hour`, `minute` | — | Success/error |
|
||||
| `clock.set_timezone` | `gmt_offset_sec` | `dst_offset_sec`, `timezone_name` | Success/error |
|
||||
| `clock.get_timezone` | *(none)* | — | `{ gmt_offset_sec, dst_offset_sec, timezone_name }` |
|
||||
| `clock.sync_ntp` | *(none)* | — | Success/error |
|
||||
| `clock.enable` | *(none)* | — | Success/error |
|
||||
| `clock.disable` | *(none)* | — | Success/error |
|
||||
| `clock.pause` | *(none)* | — | Success/error |
|
||||
| `clock.resume` | *(none)* | — | Success/error |
|
||||
| `clock.get_face` | *(none)* | — | `{ clock_hour, clock_minute, last_sync_time, next_output_is_c1 }` |
|
||||
| `clock.get_config` | *(none)* | — | Full clock config object |
|
||||
|
||||
---
|
||||
|
||||
### System namespace — `SystemHandler`
|
||||
|
||||
| Command | Required fields | Optional fields | Returns |
|
||||
|---|---|---|---|
|
||||
| `system.status` | *(none)* | — | Player state, strike counters, projected run time |
|
||||
| `system.get_time` | *(none)* | — | `{ local_timestamp, utc_timestamp, year, month, day, hour, minute, second, rtc_available }` |
|
||||
| `system.get_settings` | *(none)* | — | Full ConfigManager JSON dump |
|
||||
| `system.get_device_info` | *(none)* | — | `{ uid, hw_type, hw_version, fw_version, uptime_ms, free_heap, min_free_heap }` |
|
||||
| `system.health` | *(none)* | — | Full HealthMonitor report — subsystem states, warnings, critical count |
|
||||
| `system.factory_reset` | *(none)* | — | Success/error |
|
||||
| `system.restart` | *(none)* | — | Sends response, then reboots after 2s |
|
||||
|
||||
---
|
||||
|
||||
### Firmware namespace — `FirmwareHandler`
|
||||
|
||||
| Command | Required fields | Returns |
|
||||
|---|---|---|
|
||||
| `firmware.status` | *(none)* | Validation state, version, boot count, can_commit, can_rollback |
|
||||
| `firmware.commit` | *(none)* | Success/error |
|
||||
| `firmware.rollback` | *(none)* | Success/error — device reboots |
|
||||
|
||||
---
|
||||
|
||||
### OTA namespace — `FirmwareHandler`
|
||||
|
||||
| Command | Required fields | Optional fields | Returns |
|
||||
|---|---|---|---|
|
||||
| `ota.status` | *(none)* | — | `{ current_version, available_version, channel, update_available, last_check, progress }` |
|
||||
| `ota.check` | *(none)* | `channel` (default: "stable") | Update availability result |
|
||||
| `ota.update` | *(none)* | `channel` (default: "stable") | Success/error — device may reboot |
|
||||
| `ota.custom` | `firmware_url` | `checksum`, `file_size`, `version` | Success/error — device may reboot |
|
||||
|
||||
---
|
||||
|
||||
### Network namespace — `NetworkHandler`
|
||||
|
||||
| Command | Required fields | Optional fields | Returns |
|
||||
|---|---|---|---|
|
||||
| `network.info` | *(none)* | — | `{ ip, gateway, dns }` |
|
||||
| `network.status` | *(none)* | — | `{ connected, state, type, ip, rssi, ap_mode }` |
|
||||
| `network.set_config` | *(at least one field)* | `hostname`, `useStaticIP`, `ip`, `gateway`, `subnet`, `dns1`, `dns2` — partial OK; static IP requires ip+gateway+subnet together | Success/error + restart_required flag |
|
||||
|
||||
---
|
||||
|
||||
### Files namespace — `FileHandler`
|
||||
|
||||
| Command | Required fields | Returns |
|
||||
|---|---|---|
|
||||
| `files.list` | *(none)* | Array of melody files on SD card (melodies only) |
|
||||
| `files.list_builtin` | *(none)* | Array of built-in melodies `[{ name, uid }, ...]` |
|
||||
| `files.download` | `melodys_uid` | Success/error |
|
||||
| `files.delete` | `name` | Success/error |
|
||||
|
||||
> `files.list` returns SD card melodies only. Built-in melodies have their own endpoint. Future: add `type` filter for other file categories (schedules, etc.)
|
||||
|
||||
---
|
||||
|
||||
### Log namespace — `LoggingHandler`
|
||||
|
||||
| Command | Required fields | Returns |
|
||||
|---|---|---|
|
||||
| `log.set_serial` | `level` (0–5) | Success/error |
|
||||
| `log.set_sd` | `level` (0–5) | Success/error |
|
||||
| `log.set_mqtt` | `level` (0–5) | Success/error |
|
||||
|
||||
---
|
||||
|
||||
### MQTT namespace — `MQTTHandler`
|
||||
|
||||
| Command | Required fields | Returns |
|
||||
|---|---|---|
|
||||
| `mqtt.enable` | *(none)* | Success/error |
|
||||
| `mqtt.disable` | *(none)* | Success/error |
|
||||
|
||||
---
|
||||
|
||||
### Telemetry namespace — `TelemetryHandler` *(new — zero coverage today)*
|
||||
|
||||
| Command | Required fields | Optional fields | Returns |
|
||||
|---|---|---|---|
|
||||
| `telemetry.get_strikes` | *(none)* | — | `{ "strikes": { "0": 1234, "1": 567, ... } }` |
|
||||
| `telemetry.reset_strikes` | *(none)* | `bell` (int) — omit to reset all, include to reset one channel | Success/error |
|
||||
| `telemetry.get_loads` | *(none)* | — | `{ "loads": { "0": 42.5, ... }, "cooling_active": false, "overloaded": [2, 5] }` |
|
||||
|
||||
---
|
||||
|
||||
## Handler → Dependency Map
|
||||
|
||||
| Handler | Dependencies |
|
||||
|---|---|
|
||||
| `PlaybackHandler` | `Player` |
|
||||
| `RelayHandler` | `ConfigManager`, `OutputManager`, `Player` (for safety gate) |
|
||||
| `ClockHandler` | `ConfigManager`, `TimeKeeper` |
|
||||
| `SystemHandler` | `ConfigManager`, `Player`, `Telemetry`, `HealthMonitor` |
|
||||
| `FirmwareHandler` | `FirmwareValidator`, `OTAManager`, `Player` |
|
||||
| `NetworkHandler` | `ConfigManager`, `Networking` |
|
||||
| `FileHandler` | `FileManager` |
|
||||
| `LoggingHandler` | `ConfigManager` |
|
||||
| `TelemetryHandler` | `Telemetry` |
|
||||
| `MQTTHandler` | `ConfigManager`, `MQTTTransport` (direct reference) |
|
||||
|
||||
---
|
||||
|
||||
## UART Whitelist (v2)
|
||||
|
||||
The UART transport only allows commands that make sense for a slave LCD/button board. All others are silently dropped to prevent feedback loops.
|
||||
|
||||
The LCD is a proper bidirectional client in v2 — it can send requests and receive responses. The old push model (`sync_time_to_lcd`) is retired. The LCD requests `system.get_time` and the response is a normal command reply — no loop possible because replies are not commands.
|
||||
|
||||
```
|
||||
Allowed via UART (whitelist):
|
||||
- ping (connection check)
|
||||
- playback (play/stop from physical buttons)
|
||||
- clock.pause (button-triggered pause)
|
||||
- clock.resume (button-triggered resume)
|
||||
- system.get_time (LCD requests current time — replaces old push model)
|
||||
```
|
||||
|
||||
All other commands are silently dropped by `UARTTransport` before reaching the bus.
|
||||
|
||||
---
|
||||
|
||||
## v1 → v2 Legacy Mapping (LegacyAdapter)
|
||||
|
||||
Full translation table for `LegacyAdapter.cpp`. When a client sends `"v": 1` (or omits `v`), this runs first. The adapter extracts `contents["action"]`, combines it with `cmd` to produce the flat v2 command, and strips `action` from contents before dispatch.
|
||||
|
||||
| v1 `cmd` | v1 `action` | v2 `cmd` |
|
||||
|---|---|---|
|
||||
| `ping` | — | `ping` |
|
||||
| `identify` | — | `identify` |
|
||||
| `playback` | — | `playback` |
|
||||
| `file_manager` | `list_melodies` | `files.list` |
|
||||
| `file_manager` | `download_melody` | `files.download` |
|
||||
| `file_manager` | `delete_melody` | `files.delete` |
|
||||
| `relay_setup` | `set_timings` | `relay.set_durations` |
|
||||
| `relay_setup` | `set_outputs` | `relay.set_outputs` |
|
||||
| `clock_setup` | `set_outputs` | `clock.set_outputs` |
|
||||
| `clock_setup` | `set_timings` | `clock.set_timings` |
|
||||
| `clock_setup` | `set_alerts` | `clock.set_alerts` |
|
||||
| `clock_setup` | `set_backlight` | `clock.set_backlight` |
|
||||
| `clock_setup` | `set_silence` | `clock.set_silence` |
|
||||
| `clock_setup` | `set_rtc_time` | `clock.set_time` |
|
||||
| `clock_setup` | `set_physical_clock_time` | `clock.set_face` |
|
||||
| `clock_setup` | `pause_clock_updates` | `clock.pause` |
|
||||
| `clock_setup` | `resume_clock_updates` | `clock.resume` |
|
||||
| `clock_setup` | `set_enabled` + `enabled=true` | `clock.enable` |
|
||||
| `clock_setup` | `set_enabled` + `enabled=false` | `clock.disable` |
|
||||
| `system_info` | `report_status` | `system.status` |
|
||||
| `system_info` | `get_device_time` | `system.get_time` |
|
||||
| `system_info` | `get_clock_time` | `clock.get_face` |
|
||||
| `system_info` | `get_firmware_status` | `firmware.status` |
|
||||
| `system_info` | `network_info` | `network.info` |
|
||||
| `system_info` | `get_full_settings` | `system.get_settings` |
|
||||
| `system_info` | `sync_time_to_lcd` | `system.get_time` *(remapped — LCD now uses request/response model)* |
|
||||
| `system` | `status` | `system.status` |
|
||||
| `system` | `reset_defaults` | `system.factory_reset` |
|
||||
| `system` | `commit_firmware` | `firmware.commit` |
|
||||
| `system` | `rollback_firmware` | `firmware.rollback` |
|
||||
| `system` | `get_firmware_status` | `firmware.status` |
|
||||
| `system` | `set_network_config` | `network.set_config` |
|
||||
| `system` | `set_serial_log_level` | `log.set_serial` |
|
||||
| `system` | `set_sd_log_level` | `log.set_sd` |
|
||||
| `system` | `set_mqtt_log_level` | `log.set_mqtt` |
|
||||
| `system` | `set_mqtt_enabled` + `enabled=true` | `mqtt.enable` |
|
||||
| `system` | `set_mqtt_enabled` + `enabled=false` | `mqtt.disable` |
|
||||
| `system` | `restart` | `system.restart` |
|
||||
| `system` | `reboot` | `system.restart` |
|
||||
| `system` | `force_update` | `ota.update` |
|
||||
| `system` | `custom_update` | `ota.custom` |
|
||||
@@ -0,0 +1,178 @@
|
||||
# Firmware Variants — Project Vesper
|
||||
|
||||
> Reference for all PlatformIO build environments defined in `vesper/platformio.ini`.
|
||||
|
||||
---
|
||||
|
||||
## Active Environments
|
||||
|
||||
### `vesper-v1` — Vesper (VS)
|
||||
|
||||
| Property | Value |
|
||||
|---|---|
|
||||
| Board | Kincony KC868-A6 |
|
||||
| MCU | ESP32-D0WD-V3 (rev 3.1) |
|
||||
| PlatformIO board target | `esp32dev` |
|
||||
| Flash size | 4 MB |
|
||||
| Partition table | `min_spiffs.csv` |
|
||||
| Board type code | `VS` |
|
||||
| Board version | `01` |
|
||||
| PSRAM | No |
|
||||
| RF remote | No |
|
||||
| Onboard LCD | No |
|
||||
|
||||
**Partition layout (`min_spiffs.csv`):**
|
||||
|
||||
| Partition | Address | Size |
|
||||
|---|---|---|
|
||||
| nvs | `0x9000` | 20 KB (0x5000) |
|
||||
| app0 (active) | `0x10000` | ~1.8 MB |
|
||||
| app1 (OTA) | `0x1F0000` | ~1.8 MB |
|
||||
| spiffs | `0x3D0000` | 128 KB |
|
||||
|
||||
**Build:**
|
||||
```bash
|
||||
# From repo root
|
||||
pio run -e vesper-v1
|
||||
# Output: vesper/.pio/build/vesper-v1/firmware.bin
|
||||
```
|
||||
|
||||
**Full erase + upload:**
|
||||
```bash
|
||||
pio run -e vesper-v1 --target upload --upload-port COM8
|
||||
```
|
||||
|
||||
**Flash NVS after full upload** (NVS is wiped by full erase — must reflash separately):
|
||||
```bash
|
||||
C:/Users/espi_/.espressif/python_env/idf5.4_py3.11_env/Scripts/python.exe \
|
||||
-m esptool --chip esp32 --port COM8 --baud 921600 \
|
||||
write_flash 0x9000 vesper/provisioning/nvs_lab_device.bin
|
||||
```
|
||||
|
||||
**Serial monitor:**
|
||||
```bash
|
||||
pio device monitor # 115200 baud
|
||||
```
|
||||
|
||||
**OTA URL pattern (VPS NGINX):**
|
||||
```
|
||||
http://72.61.191.197/ota/vs/stable/firmware.bin
|
||||
http://72.61.191.197/ota/vs/{channel}/firmware.bin
|
||||
```
|
||||
Channels: `stable`, `beta`
|
||||
|
||||
**Key build flags:**
|
||||
```ini
|
||||
-DBOARD_TYPE="VS"
|
||||
-DBOARD_VERSION="01"
|
||||
-DBOARD_NAME="Vesper"
|
||||
-DPSRAM_ENABLED=0
|
||||
-DHAS_RF=0
|
||||
-DHAS_LCD=0
|
||||
-DMQTT_SECRET="<set-locally-not-committed>"
|
||||
```
|
||||
|
||||
> **Important:** `MQTT_SECRET` must match the `MQTT_SECRET` in the backend `.env` on the VPS.
|
||||
> Never commit the real secret. Override locally via a `platformio.ini.local` file (gitignored):
|
||||
> ```ini
|
||||
> [env:vesper-v1]
|
||||
> build_flags =
|
||||
> ... (copy existing flags) ...
|
||||
> -DMQTT_SECRET=\"your_actual_secret\"
|
||||
> ```
|
||||
|
||||
---
|
||||
|
||||
## Planned Environments (Not Yet Active)
|
||||
|
||||
### `vesper-plus-v1` — Vesper+ (VP)
|
||||
|
||||
| Property | Value |
|
||||
|---|---|
|
||||
| Board target | `esp32dev` |
|
||||
| Board type code | `VP` |
|
||||
| RF remote | **Yes** (`HAS_RF=1`) |
|
||||
| Onboard LCD | No |
|
||||
| Status | Commented out in `platformio.ini` |
|
||||
|
||||
**When activated, upload command:**
|
||||
```bash
|
||||
pio run -e vesper-plus-v1 --target upload --upload-port <PORT>
|
||||
```
|
||||
|
||||
**OTA URL pattern:**
|
||||
```
|
||||
http://72.61.191.197/ota/vp/stable/firmware.bin
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### `vesper-pro-v1` — Vesper Pro (VX)
|
||||
|
||||
| Property | Value |
|
||||
|---|---|
|
||||
| Board target | `esp32dev` |
|
||||
| Board type code | `VX` |
|
||||
| RF remote | No |
|
||||
| Onboard LCD | **Yes** (`HAS_LCD=1`) |
|
||||
| Status | Commented out in `platformio.ini` |
|
||||
|
||||
**When activated, upload command:**
|
||||
```bash
|
||||
pio run -e vesper-pro-v1 --target upload --upload-port <PORT>
|
||||
```
|
||||
|
||||
**OTA URL pattern:**
|
||||
```
|
||||
http://72.61.191.197/ota/vx/stable/firmware.bin
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## NVS Identity (All Variants)
|
||||
|
||||
Each device has a pre-flashed NVS partition at `0x9000` containing:
|
||||
|
||||
| NVS namespace | Key | Example |
|
||||
|---|---|---|
|
||||
| `device_id` | `device_uid` | `PV-26B18-VS01R-X7KQA` |
|
||||
| `device_id` | `hw_type` | `VS` |
|
||||
| `device_id` | `hw_version` | `01` |
|
||||
|
||||
NVS binaries are generated by the admin console at:
|
||||
```
|
||||
GET /api/manufacturing/devices/{sn}/nvs.bin
|
||||
```
|
||||
|
||||
The lab device NVS CSV and binary live at:
|
||||
```
|
||||
vesper/provisioning/nvs_lab_device.csv
|
||||
vesper/provisioning/nvs_lab_device.bin
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Shared Library Dependencies
|
||||
|
||||
All variants share the same `lib_deps` (defined in `[common]`):
|
||||
|
||||
| Library | Purpose |
|
||||
|---|---|
|
||||
| `tzapu/WiFiManager` | WiFi provisioning captive portal |
|
||||
| `me-no-dev/ESPAsyncWebServer` | Async HTTP server + WebSocket |
|
||||
| `me-no-dev/AsyncTCP` | Async TCP (required by above) |
|
||||
| `bblanchon/ArduinoJson` | JSON parsing (v7) |
|
||||
| `adafruit/Adafruit PCF8574` | I2C GPIO expander (relay control) |
|
||||
| `adafruit/RTClib` | Real-time clock |
|
||||
| `marvinroger/async-mqtt-client` | Async MQTT client |
|
||||
|
||||
---
|
||||
|
||||
## Adding a New Variant
|
||||
|
||||
1. Copy a `[env:vesper-*]` block in `vesper/platformio.ini` and uncomment it.
|
||||
2. Set the correct `BOARD_TYPE`, `BOARD_VERSION`, `HAS_RF`, `HAS_LCD` flags.
|
||||
3. Add the new `BoardType` value to `backend/manufacturing/models.py` (`BoardType` enum and `BOARD_TYPE_LABELS`).
|
||||
4. Add the NVS gen path for the new `hw_type` in `backend/utils/nvs_generator.py` if needed.
|
||||
5. Create the NGINX OTA directory on the VPS: `/srv/ota/{new_type}/stable/`.
|
||||
6. Upload a firmware binary and update the firmware manager entry.
|
||||
@@ -1,37 +1,15 @@
|
||||
Features:
|
||||
|
||||
// Board Naming Schema:
|
||||
|
||||
eg. PV25K07BC01R01
|
||||
|
||||
PV 25 K 07 BC 01 R 01
|
||||
PV [Y] [M] [D] [BT] [RV] R [BC]
|
||||
|
||||
// SERBIA_OLD: PV25K07BC01R01
|
||||
// SERBIA_NEW: PV26A28BC01R01
|
||||
|
||||
// XRISTIANIKH_ELPIS: PV26B02BP01R01
|
||||
|
||||
|
||||
PV25L22BP01R01
|
||||
|
||||
|
||||
Y: (Year) 2 Digit Year. eg 25 for 2025
|
||||
M: (Month) 1 Letter as Coded Month. eg B for February
|
||||
D: (Day) 2 Digit Date. eg 17 for 17th of the Month
|
||||
BT: (Board Type) 2 letter/digit board Type (custom) eg BC for BellCore
|
||||
RV: (Revision) 2 letter/digit board revision code
|
||||
R: Now, just an R for "Revision" but can change later
|
||||
BC: (Batch Code) 2 digit SerialNumber starting from 01
|
||||
|
||||
|
||||
// mqtt topics:
|
||||
|
||||
vesper/<DEVID>/data // Data sent from the controller
|
||||
vesper/<DEVID>/control // Commands sent to the controller
|
||||
vesper/<DEVID>/kiosk/event // Kiosk Mode Events
|
||||
vesper/<DEVID>/kiosk/info // Kiosk Mode General Info
|
||||
|
||||
// WiFi Local AP
|
||||
BellSystemsInfra
|
||||
v3sp3r_8998!
|
||||
|
||||
|
||||
|
||||
- WiFi Manager (captive portal with hotspot)
|
||||
@@ -3,7 +3,7 @@
|
||||
; ═══════════════════════════════════════════════════════════════════════════════
|
||||
;
|
||||
; Hardware Variants:
|
||||
; vesper-v1 — Kincony KC868-A6 (ESP32-S3, 4MB flash) — current production board
|
||||
; vesper-v1 — Kincony KC868-A6 (ESP32-D0WD-V3, 4MB flash) — current production board
|
||||
;
|
||||
; Future variants (not yet active):
|
||||
; vesper-plus-v1 — Vesper+ with RF remote support
|
||||
@@ -51,13 +51,13 @@ build_flags_common =
|
||||
-DCONFIG_ASYNC_TCP_RUNNING_CORE=0
|
||||
|
||||
; ───────────────────────────────────────────────────────────────────────────────
|
||||
; VESPER v1 — Kincony KC868-A6 (ESP32-S3, 4MB Flash)
|
||||
; VESPER v1 — Kincony KC868-A6 (ESP32-D0WD-V3, 4MB Flash)
|
||||
; Current production board
|
||||
; ───────────────────────────────────────────────────────────────────────────────
|
||||
[env:vesper-v1]
|
||||
platform = ${common.platform}
|
||||
framework = ${common.framework}
|
||||
board = esp32-s3-devkitc-1
|
||||
board = esp32dev
|
||||
|
||||
; Serial monitor
|
||||
monitor_speed = ${common.monitor_speed}
|
||||
@@ -66,11 +66,20 @@ monitor_speed = ${common.monitor_speed}
|
||||
upload_speed = 921600
|
||||
upload_protocol = esptool
|
||||
|
||||
; Partition table — default 4MB with OTA support
|
||||
; Provides: 1.8MB app slot + 1.8MB OTA slot + 64KB NVS + SPIFFS
|
||||
board_build.partitions = default_8MB.csv
|
||||
; Partition table — 4MB with OTA support, larger app slots
|
||||
; min_spiffs.csv: ~1.8MB app + ~1.8MB OTA + 64KB NVS + 128KB SPIFFS
|
||||
board_build.partitions = min_spiffs.csv
|
||||
|
||||
; FreeRTOS timer service task stack — default 2048 is too small when timer callbacks
|
||||
; do LOG formatting, MQTT connect(), NTP sync, etc. Increase to 4096.
|
||||
board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
|
||||
|
||||
; Build flags for this variant
|
||||
; IMPORTANT: MQTT_SECRET must match the MQTT_SECRET in the backend .env file exactly.
|
||||
; Do NOT commit the real secret value to git.
|
||||
; To override locally without modifying this file, use a platformio.ini.local file:
|
||||
; [env:vesper-v1]
|
||||
; build_flags = ... -DMQTT_SECRET=\"your_actual_secret\"
|
||||
build_flags =
|
||||
${common.build_flags_common}
|
||||
-DBOARD_TYPE=\"VS\"
|
||||
@@ -79,6 +88,8 @@ build_flags =
|
||||
-DPSRAM_ENABLED=0
|
||||
-DHAS_RF=0
|
||||
-DHAS_LCD=0
|
||||
-DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\"
|
||||
|
||||
|
||||
lib_deps = ${common.lib_deps}
|
||||
|
||||
@@ -89,7 +100,7 @@ lib_deps = ${common.lib_deps}
|
||||
; [env:vesper-plus-v1]
|
||||
; platform = ${common.platform}
|
||||
; framework = ${common.framework}
|
||||
; board = esp32-s3-devkitc-1
|
||||
; board = esp32dev
|
||||
; monitor_speed = ${common.monitor_speed}
|
||||
; build_flags =
|
||||
; ${common.build_flags_common}
|
||||
@@ -108,7 +119,7 @@ lib_deps = ${common.lib_deps}
|
||||
; [env:vesper-pro-v1]
|
||||
; platform = ${common.platform}
|
||||
; framework = ${common.framework}
|
||||
; board = esp32-s3-devkitc-1
|
||||
; board = esp32dev
|
||||
; monitor_speed = ${common.monitor_speed}
|
||||
; build_flags =
|
||||
; ${common.build_flags_common}
|
||||
@@ -0,0 +1,5 @@
|
||||
key,type,encoding,value
|
||||
device_id,namespace,,
|
||||
device_uid,data,string,PV000000000000
|
||||
hw_type,data,string,VS
|
||||
hw_version,data,string,01
|
||||
|
+31
-7
@@ -18,6 +18,7 @@ MQTTAsyncClient::MQTTAsyncClient(ConfigManager& configManager, Networking& netwo
|
||||
, _mqttReconnectTimer(nullptr)
|
||||
, _networkStabilizationTimer(nullptr)
|
||||
, _heartbeatTimer(nullptr)
|
||||
, _heartbeatTaskHandle(nullptr)
|
||||
, _reconnectAttempts(0)
|
||||
, _lastConnectionAttempt(0) {
|
||||
|
||||
@@ -317,13 +318,15 @@ void MQTTAsyncClient::attemptReconnection() {
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::mqttReconnectTimerCallback(TimerHandle_t xTimer) {
|
||||
// Get the MQTT instance from the timer's ID (set during timer creation)
|
||||
// For now, we'll use a static instance pointer (similar to Networking)
|
||||
// You'll need to add: static MQTTAsyncClient* _instance; to header
|
||||
void MQTTAsyncClient::mqttReconnectTaskFn(void* param) {
|
||||
MQTTAsyncClient* client = static_cast<MQTTAsyncClient*>(param);
|
||||
client->attemptReconnection();
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::mqttReconnectTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTAsyncClient::_instance) {
|
||||
MQTTAsyncClient::_instance->attemptReconnection();
|
||||
xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 3072, MQTTAsyncClient::_instance, 5, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,6 +349,7 @@ void MQTTAsyncClient::startHeartbeat() {
|
||||
void MQTTAsyncClient::stopHeartbeat() {
|
||||
if (_heartbeatTimer) {
|
||||
xTimerStop(_heartbeatTimer, 0);
|
||||
_heartbeatTaskHandle = nullptr;
|
||||
LOG_INFO(TAG, "❤️ Stopped MQTT heartbeat");
|
||||
}
|
||||
}
|
||||
@@ -406,9 +410,21 @@ void MQTTAsyncClient::publishHeartbeat() {
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::mqttHeartbeatTaskFn(void* param) {
|
||||
MQTTAsyncClient* client = static_cast<MQTTAsyncClient*>(param);
|
||||
client->publishHeartbeat();
|
||||
client->_heartbeatTaskHandle = nullptr;
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::heartbeatTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTAsyncClient::_instance) {
|
||||
MQTTAsyncClient::_instance->publishHeartbeat();
|
||||
// Guard: skip if previous heartbeat task is still running
|
||||
if (MQTTAsyncClient::_instance->_heartbeatTaskHandle != nullptr) {
|
||||
return;
|
||||
}
|
||||
xTaskCreate(mqttHeartbeatTaskFn, "mqttHB", 3072, MQTTAsyncClient::_instance, 3,
|
||||
&MQTTAsyncClient::_instance->_heartbeatTaskHandle);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,9 +437,17 @@ void MQTTAsyncClient::connectAfterStabilization() {
|
||||
connect();
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::mqttConnectTaskFn(void* param) {
|
||||
// Runs in its own task so LOG calls don't overflow the Tmr Svc stack
|
||||
MQTTAsyncClient* client = static_cast<MQTTAsyncClient*>(param);
|
||||
client->connectAfterStabilization();
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::networkStabilizationTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTAsyncClient::_instance) {
|
||||
MQTTAsyncClient::_instance->connectAfterStabilization();
|
||||
// Defer to a task — timer callbacks run in Tmr Svc (2KB stack), not enough for connect()
|
||||
xTaskCreate(mqttConnectTaskFn, "mqttConnect", 3072, MQTTAsyncClient::_instance, 5, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
+4
@@ -117,6 +117,7 @@ private:
|
||||
unsigned long _lastConnectionAttempt; // Track last attempt time
|
||||
void attemptReconnection();
|
||||
static void mqttReconnectTimerCallback(TimerHandle_t xTimer);
|
||||
static void mqttReconnectTaskFn(void* param);
|
||||
unsigned long getReconnectDelay(); // Calculate backoff delay
|
||||
|
||||
// Network Stabilization Timer (non-blocking replacement for delay)
|
||||
@@ -124,12 +125,15 @@ private:
|
||||
static const unsigned long NETWORK_STABILIZATION_DELAY = 2000; // 2 seconds
|
||||
void connectAfterStabilization();
|
||||
static void networkStabilizationTimerCallback(TimerHandle_t xTimer);
|
||||
static void mqttConnectTaskFn(void* param);
|
||||
|
||||
// Heartbeat Timer (30 seconds)
|
||||
TimerHandle_t _heartbeatTimer;
|
||||
static const unsigned long HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
||||
TaskHandle_t _heartbeatTaskHandle; // Guard: only one heartbeat task at a time
|
||||
void publishHeartbeat();
|
||||
static void heartbeatTimerCallback(TimerHandle_t xTimer);
|
||||
static void mqttHeartbeatTaskFn(void* param);
|
||||
void startHeartbeat();
|
||||
void stopHeartbeat();
|
||||
};
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <WiFi.h> // For MAC address generation
|
||||
#include <time.h> // For timestamp generation
|
||||
#include <algorithm> // For std::sort
|
||||
#include "mbedtls/md.h" // For HMAC-SHA256 password derivation
|
||||
|
||||
// NVS namespace for device identity storage
|
||||
const char* ConfigManager::NVS_NAMESPACE = "device_id";
|
||||
@@ -29,6 +30,14 @@ void ConfigManager::initializeCleanDefaults() {
|
||||
// Set MQTT user to deviceUID for unique identification
|
||||
mqttConfig.user = deviceConfig.deviceUID;
|
||||
|
||||
// Derive MQTT password from deviceUID using HMAC-SHA256
|
||||
// MQTT_SECRET is compiled in via build flag -DMQTT_SECRET="..."
|
||||
// Must match the MQTT_SECRET in the backend .env exactly.
|
||||
mqttConfig.password = computeMqttPassword(deviceConfig.deviceUID);
|
||||
|
||||
LOG_INFO(TAG, "🔑 MQTT auth — user: %s, password: %s", mqttConfig.user.c_str(), mqttConfig.password.c_str());
|
||||
LOG_INFO(TAG, "🔑 MQTT_SECRET prefix: %.8s...", MQTT_SECRET);
|
||||
|
||||
LOG_DEBUG(TAG, "ConfigManager - Clean defaults initialized with auto-generated identifiers");
|
||||
}
|
||||
|
||||
@@ -1301,3 +1310,39 @@ bool ConfigManager::saveGeneralConfig() {
|
||||
LOG_DEBUG(TAG, "ConfigManager - General config saved (MQTT enabled: %s)", generalConfig.mqttEnabled ? "true" : "false");
|
||||
return true;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// HMAC-SHA256 MQTT password derivation
|
||||
// Password = HMAC-SHA256(MQTT_SECRET, deviceUID), first 16 bytes as hex (32 chars)
|
||||
// Matches backend: hmac.new(secret, uid, sha256).hexdigest()[:32]
|
||||
// MQTT_SECRET is injected at compile time via -DMQTT_SECRET="..." in platformio.ini
|
||||
// =============================================================================
|
||||
String ConfigManager::computeMqttPassword(const String& uid) {
|
||||
const char* secret = MQTT_SECRET;
|
||||
const uint8_t* key = (const uint8_t*)secret;
|
||||
size_t keyLen = strlen(secret);
|
||||
|
||||
const uint8_t* msg = (const uint8_t*)uid.c_str();
|
||||
size_t msgLen = uid.length();
|
||||
|
||||
uint8_t hmacResult[32]; // SHA-256 produces 32 bytes
|
||||
|
||||
mbedtls_md_context_t ctx;
|
||||
const mbedtls_md_info_t* info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
|
||||
|
||||
mbedtls_md_init(&ctx);
|
||||
mbedtls_md_setup(&ctx, info, 1); // 1 = HMAC mode
|
||||
mbedtls_md_hmac_starts(&ctx, key, keyLen);
|
||||
mbedtls_md_hmac_update(&ctx, msg, msgLen);
|
||||
mbedtls_md_hmac_finish(&ctx, hmacResult);
|
||||
mbedtls_md_free(&ctx);
|
||||
|
||||
// Convert first 16 bytes (32 hex chars) — matches backend [:32]
|
||||
char hexStr[33];
|
||||
for (int i = 0; i < 16; i++) {
|
||||
snprintf(&hexStr[i * 2], 3, "%02x", hmacResult[i]);
|
||||
}
|
||||
hexStr[32] = '\0';
|
||||
|
||||
return String(hexStr);
|
||||
}
|
||||
@@ -84,7 +84,7 @@ public:
|
||||
IPAddress host = IPAddress(72,61,191,197); // 📡 MQTT broker (default cloud broker)
|
||||
int port = 1883; // 🔌 Standard MQTT port (non-SSL)
|
||||
String user; // 👤 Auto-set to deviceUID
|
||||
String password = "vesper"; // 🔑 Default password
|
||||
String password; // 🔑 Derived at runtime via computeMqttPassword()
|
||||
bool useSSL = false; // 🔒 SSL disabled for local broker
|
||||
bool enabled = true; // 🔘 MQTT enabled by default (can be toggled via command)
|
||||
};
|
||||
@@ -274,6 +274,8 @@ private:
|
||||
String readNVSString(const char* key, const String& defaultValue);
|
||||
// REMOVED: saveDeviceIdentityToNVS() and writeNVSString() - Production firmware is READ-ONLY
|
||||
|
||||
String computeMqttPassword(const String& uid);
|
||||
|
||||
public:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PUBLIC INTERFACE - Clean deployment-ready API
|
||||
@@ -322,63 +322,18 @@ bool FileManager::readJsonFile(const String& filePath, JsonDocument& doc) {
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool FileManager::isHealthy() const {
|
||||
// Check if ConfigManager is available
|
||||
if (!configManager) {
|
||||
LOG_DEBUG(TAG, "FileManager: Unhealthy - ConfigManager not available");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if SD card can be initialized
|
||||
uint8_t sdPin = configManager->getHardwareConfig().sdChipSelect;
|
||||
if (!SD.begin(sdPin)) {
|
||||
// Use SD.cardType() as a lightweight presence check — avoids calling SD.begin()
|
||||
// on every health poll (which is expensive and crashes without a card inserted).
|
||||
if (SD.cardType() == CARD_NONE) {
|
||||
LOG_DEBUG(TAG, "FileManager: Unhealthy - SD Card initialization failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if we can read from SD card (test with root directory)
|
||||
File root = SD.open("/");
|
||||
if (!root) {
|
||||
LOG_DEBUG(TAG, "FileManager: Unhealthy - Cannot access SD root directory");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!root.isDirectory()) {
|
||||
LOG_DEBUG(TAG, "FileManager: Unhealthy - SD root is not a directory");
|
||||
root.close();
|
||||
return false;
|
||||
}
|
||||
|
||||
root.close();
|
||||
|
||||
// Check if we can write to SD card (create/delete a test file)
|
||||
String testFile = "/health_test.tmp";
|
||||
File file = SD.open(testFile.c_str(), FILE_WRITE);
|
||||
if (!file) {
|
||||
LOG_DEBUG(TAG, "FileManager: Unhealthy - Cannot write to SD card");
|
||||
return false;
|
||||
}
|
||||
|
||||
file.print("health_check");
|
||||
file.close();
|
||||
|
||||
// Verify we can read the test file
|
||||
file = SD.open(testFile.c_str(), FILE_READ);
|
||||
if (!file) {
|
||||
LOG_DEBUG(TAG, "FileManager: Unhealthy - Cannot read test file from SD card");
|
||||
return false;
|
||||
}
|
||||
|
||||
String content = file.readString();
|
||||
file.close();
|
||||
|
||||
// Clean up test file
|
||||
SD.remove(testFile.c_str());
|
||||
|
||||
if (content != "health_check") {
|
||||
LOG_DEBUG(TAG, "FileManager: Unhealthy - SD card read/write test failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
+15
-9
@@ -368,20 +368,18 @@ bool FirmwareValidator::performBasicHealthCheck() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check critical subsystems only
|
||||
// Check hardware-critical subsystems only.
|
||||
// SD-dependent systems (ConfigManager, FileManager) are excluded: SD absence
|
||||
// means config defaults are used, but hardware is still functional.
|
||||
bool bellEngineOk = (_healthMonitor->checkSubsystemHealth("BellEngine") == HealthStatus::HEALTHY);
|
||||
bool outputManagerOk = (_healthMonitor->checkSubsystemHealth("OutputManager") == HealthStatus::HEALTHY);
|
||||
bool configManagerOk = (_healthMonitor->checkSubsystemHealth("ConfigManager") == HealthStatus::HEALTHY);
|
||||
bool fileManagerOk = (_healthMonitor->checkSubsystemHealth("FileManager") == HealthStatus::HEALTHY);
|
||||
|
||||
bool basicHealthOk = bellEngineOk && outputManagerOk && configManagerOk && fileManagerOk;
|
||||
bool basicHealthOk = bellEngineOk && outputManagerOk;
|
||||
|
||||
if (!basicHealthOk) {
|
||||
LOG_ERROR(TAG, "❌ Basic health check failed:");
|
||||
if (!bellEngineOk) LOG_ERROR(TAG, " - BellEngine: FAILED");
|
||||
if (!outputManagerOk) LOG_ERROR(TAG, " - OutputManager: FAILED");
|
||||
if (!configManagerOk) LOG_ERROR(TAG, " - ConfigManager: FAILED");
|
||||
if (!fileManagerOk) LOG_ERROR(TAG, " - FileManager: FAILED");
|
||||
} else {
|
||||
LOG_VERBOSE(TAG, "✅ Basic health check passed");
|
||||
}
|
||||
@@ -415,10 +413,10 @@ bool FirmwareValidator::performRuntimeHealthCheck() {
|
||||
}
|
||||
|
||||
void FirmwareValidator::validationTimerCallback(TimerHandle_t timer) {
|
||||
// This runs in the FreeRTOS timer service task (Tmr Svc) which has a small stack.
|
||||
// Do NOT call commitFirmware() here — just set a flag and let the monitoring task commit.
|
||||
FirmwareValidator* validator = static_cast<FirmwareValidator*>(pvTimerGetTimerID(timer));
|
||||
|
||||
LOG_INFO(TAG, "⏰ Runtime validation timeout reached - committing firmware");
|
||||
validator->handleValidationSuccess();
|
||||
validator->_commitPending = true;
|
||||
}
|
||||
|
||||
void FirmwareValidator::monitoringTaskFunction(void* parameter) {
|
||||
@@ -434,6 +432,14 @@ void FirmwareValidator::monitoringTaskFunction(void* parameter) {
|
||||
|
||||
void FirmwareValidator::monitoringLoop() {
|
||||
while (_validationState == FirmwareValidationState::RUNTIME_TESTING) {
|
||||
// Check if the validation timer fired — commit from here (not from Tmr Svc callback)
|
||||
if (_commitPending) {
|
||||
_commitPending = false;
|
||||
LOG_INFO(TAG, "⏰ Runtime validation timeout reached - committing firmware");
|
||||
handleValidationSuccess();
|
||||
return;
|
||||
}
|
||||
|
||||
// Feed watchdog if enabled
|
||||
if (_config.enableWatchdog) {
|
||||
feedWatchdog();
|
||||
+2
@@ -282,6 +282,8 @@ private:
|
||||
uint8_t _runtimeFailureCount = 0;
|
||||
TimerHandle_t _validationTimer = nullptr;
|
||||
TaskHandle_t _monitoringTask = nullptr;
|
||||
// Flag set by timer callback (Tmr Svc context) — actual commit done in monitoring task
|
||||
volatile bool _commitPending = false;
|
||||
|
||||
// NVS handles for persistent storage
|
||||
nvs_handle_t _nvsHandle = 0;
|
||||
@@ -209,20 +209,20 @@ HealthStatus HealthMonitor::performFullHealthCheck() {
|
||||
checkedSystems++;
|
||||
}
|
||||
|
||||
// Check ConfigManager
|
||||
// Check ConfigManager — SD absence is non-critical (device runs on defaults)
|
||||
if (_configManager) {
|
||||
bool healthy = _configManager->isHealthy();
|
||||
updateSubsystemHealth("ConfigManager",
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::CRITICAL,
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::WARNING,
|
||||
healthy ? "" : "ConfigManager health check failed");
|
||||
checkedSystems++;
|
||||
}
|
||||
|
||||
// Check FileManager
|
||||
// Check FileManager — SD absence is non-critical (device runs on defaults)
|
||||
if (_fileManager) {
|
||||
bool healthy = _fileManager->isHealthy();
|
||||
updateSubsystemHealth("FileManager",
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::CRITICAL,
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::WARNING,
|
||||
healthy ? "" : "FileManager health check failed");
|
||||
checkedSystems++;
|
||||
}
|
||||
@@ -52,9 +52,9 @@ Networking::~Networking() {
|
||||
void Networking::begin() {
|
||||
LOG_INFO(TAG, "Initializing Networking System");
|
||||
|
||||
// Create reconnection timer
|
||||
// Create reconnection timer (one-shot — restarted manually only when still disconnected)
|
||||
_reconnectionTimer = xTimerCreate("reconnectionTimer", pdMS_TO_TICKS(RECONNECTION_INTERVAL),
|
||||
pdTRUE, (void*)0, reconnectionTimerCallback);
|
||||
pdFALSE, (void*)0, reconnectionTimerCallback);
|
||||
|
||||
// Setup network event handler
|
||||
WiFi.onEvent(networkEventHandler);
|
||||
@@ -202,7 +202,7 @@ void Networking::startWiFiPortal() {
|
||||
|
||||
void Networking::handleReconnection() {
|
||||
if (_state == NetworkState::CONNECTED_ETHERNET || _state == NetworkState::CONNECTED_WIFI) {
|
||||
return; // Already connected
|
||||
return; // Already connected — timer is stopped in onWiFiConnected(), nothing to do
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "Attempting reconnection...");
|
||||
@@ -243,25 +243,30 @@ void Networking::handleReconnection() {
|
||||
_wifiConnectionFailures = 3;
|
||||
}
|
||||
_lastConnectionAttempt = now;
|
||||
startWiFiConnection(); // startWiFiConnection re-arms the timer
|
||||
}
|
||||
} else {
|
||||
// Retry WiFi connection — startWiFiConnection re-arms the timer
|
||||
startWiFiConnection();
|
||||
}
|
||||
} else {
|
||||
// Retry WiFi connection
|
||||
startWiFiConnection();
|
||||
// Still within timeout window — re-arm timer to check again later
|
||||
xTimerStart(_reconnectionTimer, 0);
|
||||
}
|
||||
}
|
||||
return; // Still waiting for WiFi
|
||||
return;
|
||||
}
|
||||
|
||||
// State is DISCONNECTED - WiFi only mode (Ethernet disabled)
|
||||
LOG_INFO(TAG, "Disconnected - trying WiFi");
|
||||
if (hasValidWiFiCredentials()) {
|
||||
startWiFiConnection();
|
||||
startWiFiConnection(); // re-arms timer
|
||||
} else if (!_bootSequenceComplete) {
|
||||
// No credentials during boot - start portal
|
||||
startWiFiPortal();
|
||||
} else {
|
||||
LOG_WARNING(TAG, "No WiFi credentials and boot sequence complete - waiting");
|
||||
// Re-arm so we keep checking in case credentials arrive
|
||||
xTimerStart(_reconnectionTimer, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -533,9 +538,15 @@ void Networking::networkEventHandler(arduino_event_id_t event, arduino_event_inf
|
||||
}
|
||||
}
|
||||
|
||||
void Networking::networkReconnectTaskFn(void* param) {
|
||||
Networking* net = static_cast<Networking*>(param);
|
||||
net->handleReconnection();
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void Networking::reconnectionTimerCallback(TimerHandle_t xTimer) {
|
||||
if (_instance) {
|
||||
_instance->handleReconnection();
|
||||
xTaskCreate(networkReconnectTaskFn, "netRecon", 3072, _instance, 5, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,8 +159,9 @@ private:
|
||||
void applyNetworkConfig(bool ethernet = false);
|
||||
bool hasValidWiFiCredentials();
|
||||
|
||||
// Timer callback
|
||||
// Timer callback and its task function
|
||||
static void reconnectionTimerCallback(TimerHandle_t xTimer);
|
||||
static void networkReconnectTaskFn(void* param);
|
||||
|
||||
// Constants
|
||||
static const unsigned long RECONNECTION_INTERVAL = 5000; // 5 seconds
|
||||
@@ -201,12 +201,18 @@ void handleFactoryReset() {
|
||||
}
|
||||
}
|
||||
|
||||
// Non-blocking NTP sync timer callback
|
||||
void ntpSyncTimerCallback(TimerHandle_t xTimer) {
|
||||
// One-shot task to perform NTP sync outside the Tmr Svc context
|
||||
static void ntpSyncTask(void* param) {
|
||||
LOG_DEBUG(TAG, "Network stabilization complete - starting NTP sync");
|
||||
if (!networking.isInAPMode()) {
|
||||
timekeeper.syncTimeWithNTP();
|
||||
}
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
// Non-blocking NTP sync timer callback — defers work to a task (Tmr Svc stack is only 2KB)
|
||||
void ntpSyncTimerCallback(TimerHandle_t xTimer) {
|
||||
xTaskCreate(ntpSyncTask, "ntpSync", 3072, NULL, 5, NULL);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
Device Setup Process:
|
||||
|
||||
1. Build device with peripherals.
|
||||
2. Flash Base Firmware
|
||||
3. Set Device Credentials (UID/HWID/Rev) via WebServer on device
|
||||
4. Add Device to BellCloud
|
||||
5. Add Device Credentials to Mosquitto
|
||||
6. Reboot Device to Pull Stable Production Firmware
|
||||
7. Sell the device.
|
||||
- User will bind it to their account
|
||||
- Factory can install App and bind user for convenience
|
||||
@@ -1,139 +0,0 @@
|
||||
# 💓 MQTT Heartbeat Feature
|
||||
|
||||
## Overview
|
||||
Implemented a **retained MQTT heartbeat** system that sends periodic status updates every 30 seconds when the controller is connected to MQTT.
|
||||
|
||||
## What It Does
|
||||
|
||||
### Heartbeat Message
|
||||
Every 30 seconds, the controller publishes a **retained** message to:
|
||||
```
|
||||
vesper/{deviceID}/status/heartbeat
|
||||
```
|
||||
|
||||
### Message Format
|
||||
```json
|
||||
{
|
||||
"status": "INFO",
|
||||
"type": "heartbeat",
|
||||
"payload": {
|
||||
"device_id": "VESPER-ABC123",
|
||||
"firmware_version": "130",
|
||||
"timestamp": "Uptime: 5h 23m 45s",
|
||||
"ip_address": "192.168.1.100",
|
||||
"gateway": "192.168.1.1",
|
||||
"uptime_ms": 19425000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Key Features
|
||||
✅ **Retained Message** - Only the LAST heartbeat stays on the broker
|
||||
✅ **Auto-Start** - Begins when MQTT connects
|
||||
✅ **Auto-Stop** - Stops when MQTT disconnects
|
||||
✅ **30-Second Interval** - Periodic updates
|
||||
✅ **First Beat Immediate** - Sends first heartbeat right after connecting
|
||||
✅ **QoS 1** - Reliable delivery
|
||||
|
||||
## Why This is Awesome
|
||||
|
||||
### For Your Flutter App
|
||||
1. **Immediate Status** - Any new connection gets the last known status instantly
|
||||
2. **Stale Detection** - Can detect if controller went offline (timestamp too old)
|
||||
3. **Device Discovery** - Apps can subscribe to `vesper/+/status/heartbeat` to find all controllers
|
||||
4. **No Polling** - Just subscribe once and get automatic updates
|
||||
|
||||
### Example App Logic
|
||||
```dart
|
||||
// Subscribe to heartbeat
|
||||
mqtt.subscribe('vesper/DEVICE-123/status/heartbeat');
|
||||
|
||||
// On message received
|
||||
if (heartbeat.uptime_ms > lastSeen.uptime_ms + 120000) {
|
||||
// No heartbeat for 2+ minutes = controller offline
|
||||
showOfflineWarning();
|
||||
}
|
||||
```
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### Files Modified
|
||||
1. **MQTTAsyncClient.hpp** - Added heartbeat timer and methods
|
||||
2. **MQTTAsyncClient.cpp** - Implemented heartbeat logic
|
||||
3. **Networking.hpp** - Added `getGateway()` method
|
||||
4. **Networking.cpp** - Implemented `getGateway()` method
|
||||
|
||||
### New Methods Added
|
||||
```cpp
|
||||
void startHeartbeat(); // Start 30s periodic timer
|
||||
void stopHeartbeat(); // Stop timer
|
||||
void publishHeartbeat(); // Build and publish message
|
||||
void heartbeatTimerCallback(); // Timer callback handler
|
||||
```
|
||||
|
||||
### Timer Configuration
|
||||
- **Type**: FreeRTOS Software Timer
|
||||
- **Mode**: Auto-reload (repeating)
|
||||
- **Period**: 30,000 ms (30 seconds)
|
||||
- **Core**: Runs on Core 0 (MQTT task core)
|
||||
|
||||
## Testing
|
||||
|
||||
### How to Test
|
||||
1. Flash the firmware
|
||||
2. Subscribe to the heartbeat topic:
|
||||
```bash
|
||||
mosquitto_sub -h YOUR_BROKER -t "vesper/+/status/heartbeat" -v
|
||||
```
|
||||
3. You should see heartbeats every 30 seconds
|
||||
4. Disconnect the controller - the last message stays retained
|
||||
5. Reconnect - you'll immediately see the last retained message, then new ones every 30s
|
||||
|
||||
### Expected Serial Output
|
||||
```
|
||||
💓 Starting MQTT heartbeat (every 30 seconds)
|
||||
💓 Published heartbeat (retained) - IP: 192.168.1.100, Uptime: 45000ms
|
||||
💓 Published heartbeat (retained) - IP: 192.168.1.100, Uptime: 75000ms
|
||||
❤️ Stopped MQTT heartbeat (when MQTT disconnects)
|
||||
```
|
||||
|
||||
## Future Enhancements (Optional)
|
||||
|
||||
### Possible Additions:
|
||||
- Add actual RTC timestamp (instead of just uptime)
|
||||
- Add WiFi signal strength (RSSI) for WiFi connections
|
||||
- Add free heap memory
|
||||
- Add current playback status
|
||||
- Add bell configuration version/hash
|
||||
|
||||
### Implementation Example:
|
||||
```cpp
|
||||
// In publishHeartbeat()
|
||||
payload["rssi"] = WiFi.RSSI(); // WiFi signal strength
|
||||
payload["free_heap"] = ESP.getFreeHeap();
|
||||
payload["playback_active"] = player.isPlaying;
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Current Settings (can be changed in MQTTAsyncClient.hpp):
|
||||
```cpp
|
||||
static const unsigned long HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
||||
```
|
||||
|
||||
To change interval to 60 seconds:
|
||||
```cpp
|
||||
static const unsigned long HEARTBEAT_INTERVAL = 60000; // 60 seconds
|
||||
```
|
||||
|
||||
## Notes
|
||||
- Message is published with **QoS 1** (at least once delivery)
|
||||
- Message is **retained** (broker keeps last message)
|
||||
- Timer starts automatically when MQTT connects
|
||||
- Timer stops automatically when MQTT disconnects
|
||||
- First heartbeat is sent immediately upon connection (no 30s wait)
|
||||
|
||||
---
|
||||
**Feature Implemented**: January 2025
|
||||
**Version**: Firmware v130+
|
||||
**Status**: ✅ Production Ready
|
||||
@@ -1,463 +0,0 @@
|
||||
# Project Vesper — Manufacturing Automation Master Plan
|
||||
|
||||
> **How to use this document:** Work through each Phase in order. Each Phase has self-contained tasks you can hand directly to Claude Code. Phases 1–3 are foundational; don't skip ahead. Phases 4–6 build on top of them.
|
||||
|
||||
---
|
||||
|
||||
## Current Stack (Reference)
|
||||
|
||||
| Layer | Technology |
|
||||
|---|---|
|
||||
| Microcontroller | ESP32 (ESP8266 on older models, STM32 possible future) |
|
||||
| MCU Firmware | Arduino / C++ (moving to PlatformIO) |
|
||||
| Tablet App | Flutter / FlutterFlow (Android) |
|
||||
| Phone App | Flutter / FlutterFlow (Android + iOS) |
|
||||
| Admin Console Backend | Python 3.11+ / FastAPI |
|
||||
| Admin Console Frontend | React + Tailwind CSS |
|
||||
| Primary Database | Firebase Firestore (via Admin SDK) |
|
||||
| Secondary Database | Local SQLite (MQTT logs, etc.) |
|
||||
| File Storage | Firebase Storage |
|
||||
| MQTT Broker | Mosquitto on VPS |
|
||||
| Web Server | NGINX on VPS (OTA files, reverse proxy) |
|
||||
| Deployment | Gitea → git pull on VPS, Docker Compose locally |
|
||||
|
||||
---
|
||||
|
||||
## Serial Number Format (Locked In)
|
||||
|
||||
```
|
||||
PV-YYMMM-BBTTR-XXXXX
|
||||
|
||||
PV = Project Vesper prefix
|
||||
YY = 2-digit year (e.g. 26)
|
||||
MMM = 3-char date block = 2-digit month letter + 2-digit day (e.g. A18 = Jan 18)
|
||||
BB = Board Type code (e.g. BC = BellCore, BP = BellPRO)
|
||||
TT = Board Type revision (e.g. 02)
|
||||
R = Literal "R"
|
||||
XXXXX = 5-char random suffix (A-Z, 0-9, excluding 0/O/1/I for label clarity)
|
||||
|
||||
Example: PV-26A18-BC02R-X7KQA
|
||||
```
|
||||
|
||||
**Month Letter Codes:**
|
||||
A=Jan, B=Feb, C=Mar, D=Apr, E=May, F=Jun, G=Jul, H=Aug, I=Sep, J=Oct, K=Nov, L=Dec
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — PlatformIO Migration (Firmware Side)
|
||||
|
||||
> **Goal:** Replace Arduino IDE with PlatformIO. All future firmware work happens here. This unlocks scripted builds and the ability to produce `.bin` files on demand.
|
||||
>
|
||||
> **Tell Claude Code:** *"Help me migrate my existing Arduino IDE ESP32 project to PlatformIO with multiple board environments."*
|
||||
|
||||
### Tasks
|
||||
|
||||
- [ ] Install PlatformIO extension in VS Code
|
||||
- [ ] Create `platformio.ini` with one `[env]` block per hardware variant. Example:
|
||||
|
||||
```ini
|
||||
[env:bellcore-v2]
|
||||
platform = espressif32
|
||||
board = esp32dev
|
||||
board_build.partitions = partitions/custom_4mb.csv
|
||||
board_build.flash_mode = dio
|
||||
board_upload.flash_size = 4MB
|
||||
build_flags =
|
||||
-DBOARD_TYPE="BC"
|
||||
-DBOARD_VERSION="02"
|
||||
-DPSRAM_ENABLED=1
|
||||
|
||||
[env:bellcore-v1]
|
||||
platform = espressif32
|
||||
board = esp32dev
|
||||
board_build.partitions = partitions/custom_2mb.csv
|
||||
board_build.flash_mode = dout
|
||||
board_upload.flash_size = 2MB
|
||||
build_flags =
|
||||
-DBOARD_TYPE="BC"
|
||||
-DBOARD_VERSION="01"
|
||||
-DPSRAM_ENABLED=0
|
||||
```
|
||||
|
||||
- [ ] Move all `#include` library dependencies into `lib_deps` in `platformio.ini` (no more manual library manager)
|
||||
- [ ] Verify `pio run -e bellcore-v2` compiles clean
|
||||
- [ ] Confirm `.pio/build/bellcore-v2/firmware.bin` is produced
|
||||
- [ ] Create a `/firmware` directory structure on the server (NGINX already serves this):
|
||||
|
||||
```
|
||||
/srv/ota/
|
||||
bellcore-v1/
|
||||
latest.bin
|
||||
v1.0.0.bin
|
||||
v1.0.1.bin
|
||||
bellcore-v2/
|
||||
latest.bin
|
||||
...
|
||||
```
|
||||
|
||||
- [ ] Update your OTA logic in firmware to pull from `/ota/{board_type}/latest.bin`
|
||||
- [ ] Add a `scripts/build_and_upload.sh` that compiles + copies the new `.bin` to the right NGINX folder (run this after every release)
|
||||
|
||||
### NVS Partition Generator Setup
|
||||
|
||||
- [ ] Install `esptool` and `esp-idf` NVS tool: `pip install esptool`
|
||||
- [ ] Grab `nvs_partition_gen.py` from ESP-IDF tools (or install via `idf-component-manager`)
|
||||
- [ ] Test generating a `.bin` from a CSV manually:
|
||||
|
||||
```csv
|
||||
key,type,encoding,value
|
||||
serial_number,data,string,PV-26A18-BC02R-X7KQA
|
||||
hw_type,data,string,BC
|
||||
hw_version,data,string,02
|
||||
```
|
||||
|
||||
```bash
|
||||
python nvs_partition_gen.py generate nvs_data.csv nvs_data.bin 0x6000
|
||||
```
|
||||
|
||||
- [ ] Confirm the ESP32 reads NVS values correctly on boot with this pre-flashed partition
|
||||
- [ ] Note the NVS partition address for your board (check your partition table CSV — typically `0x9000`)
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — MQTT Dynamic Auth (Backend Side)
|
||||
|
||||
> **Goal:** Replace `mosquitto_passwd` manual SSH with automatic credential management. New devices are live on MQTT the moment they exist in your database. Per-device topic isolation enforced automatically.
|
||||
>
|
||||
> **Tell Claude Code:** *"Help me set up mosquitto-go-auth on my VPS with a FastAPI backend for dynamic MQTT authentication and ACL enforcement."*
|
||||
|
||||
### Tasks
|
||||
|
||||
#### 2a. Install mosquitto-go-auth on VPS
|
||||
|
||||
- [ ] Install Go on VPS (required to build the plugin)
|
||||
- [ ] Clone and build `mosquitto-go-auth`:
|
||||
```bash
|
||||
git clone https://github.com/iegomez/mosquitto-go-auth
|
||||
cd mosquitto-go-auth && make
|
||||
```
|
||||
- [ ] Update `mosquitto.conf` to load the plugin:
|
||||
```
|
||||
auth_plugin /path/to/go-auth.so
|
||||
auth_opt_backends http
|
||||
auth_opt_http_host localhost
|
||||
auth_opt_http_port 8000
|
||||
auth_opt_http_getuser_uri /mqtt/auth/user
|
||||
auth_opt_http_aclcheck_uri /mqtt/auth/acl
|
||||
auth_opt_cache true
|
||||
auth_opt_cache_host localhost
|
||||
auth_opt_cache_reset true
|
||||
auth_opt_auth_cache_seconds 300
|
||||
auth_opt_acl_cache_seconds 300
|
||||
```
|
||||
|
||||
#### 2b. Add MQTT Auth Endpoints to FastAPI
|
||||
|
||||
- [ ] Create `/mqtt/auth/user` endpoint — Mosquitto calls this on CONNECT:
|
||||
- Receives: `username` (= device SN), `password`
|
||||
- Checks Firestore/SQLite for device record + hashed password
|
||||
- Returns: `200` (allow) or `403` (deny)
|
||||
|
||||
- [ ] Create `/mqtt/auth/acl` endpoint — Mosquitto calls this on SUBSCRIBE/PUBLISH:
|
||||
- Receives: `username`, `topic`, `acc` (1=sub, 2=pub)
|
||||
- Rule: username must match the SN segment in the topic
|
||||
- Topic pattern: `/vesper/{SN}/data` or `/vesper/{SN}/control`
|
||||
- Extract `{SN}` from topic, compare to `username`
|
||||
- Returns: `200` or `403`
|
||||
|
||||
- [ ] **For user phone app clients:** Add a separate user auth flow
|
||||
- Users authenticate with their Firebase UID as MQTT username
|
||||
- ACL check: look up which devices this UID owns in Firestore, permit only those SNs in topics
|
||||
|
||||
#### 2c. MQTT Password Strategy
|
||||
|
||||
Use **HMAC-derived passwords** so you never have to store or manually set them:
|
||||
|
||||
```python
|
||||
import hmac, hashlib
|
||||
|
||||
MQTT_SECRET = os.getenv("MQTT_SECRET") # Keep in .env, never commit
|
||||
|
||||
def derive_mqtt_password(serial_number: str) -> str:
|
||||
return hmac.new(
|
||||
MQTT_SECRET.encode(),
|
||||
serial_number.encode(),
|
||||
hashlib.sha256
|
||||
).hexdigest()[:32]
|
||||
```
|
||||
|
||||
- Device SN is known → password is deterministic → firmware can compute it at boot
|
||||
- No password storage needed in DB (just re-derive on auth check)
|
||||
- Changing `MQTT_SECRET` rotates all passwords at once if ever needed
|
||||
|
||||
- [ ] Add `MQTT_SECRET` to your `.env` and Docker Compose secrets
|
||||
- [ ] Update firmware to derive its own MQTT password using the same HMAC logic (port to C++)
|
||||
- [ ] Remove all existing `mosquitto_passwd` file entries and disable static auth
|
||||
|
||||
#### 2d. Test
|
||||
|
||||
- [ ] New device connects with correct SN + derived password → allowed
|
||||
- [ ] Device tries to sub/pub on another device's topic → denied (403)
|
||||
- [ ] Wrong password → denied
|
||||
- [ ] Confirm cache is working (check logs, only 1-2 auth calls per session)
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Serial Number & Batch Management in Admin Console
|
||||
|
||||
> **Goal:** SN generation, DB registration, and MQTT credential provisioning all happen in one flow in the React Console. The Flutter admin app is retired.
|
||||
>
|
||||
> **Tell Claude Code:** *"Add a Manufacturing / Batch Management section to our React+FastAPI admin console with the following features..."*
|
||||
|
||||
### Tasks
|
||||
|
||||
#### 3a. Backend — New API Routes in FastAPI
|
||||
|
||||
- [ ] `POST /manufacturing/batch` — Create a new batch:
|
||||
- Input: `board_type`, `board_version`, `quantity`, `subscription_plan`, `available_outputs`
|
||||
- Generate N serial numbers using the `PV-YYMMM-BBTTR-XXXXX` format
|
||||
- Check Firestore for collisions, regenerate if collision found
|
||||
- Write N device documents to Firestore collection `devices`:
|
||||
```json
|
||||
{
|
||||
"serial_number": "PV-26A18-BC02R-X7KQA",
|
||||
"hw_type": "BC",
|
||||
"hw_version": "02",
|
||||
"status": "manufactured",
|
||||
"subscription_plan": "standard",
|
||||
"available_outputs": 8,
|
||||
"created_at": "...",
|
||||
"owner": null,
|
||||
"users_list": []
|
||||
}
|
||||
```
|
||||
- Returns: list of created SNs
|
||||
|
||||
- [ ] `GET /manufacturing/batch/{batch_id}` — List devices in a batch with status
|
||||
- [ ] `GET /manufacturing/devices` — List all devices with filters (status, hw_type, date range)
|
||||
- [ ] `POST /manufacturing/devices/{sn}/assign` — Pre-assign device to a customer email
|
||||
- [ ] `GET /manufacturing/firmware/{hw_type}/{hw_version}` — Return download URL for the correct `.bin`
|
||||
|
||||
#### 3b. SN Generator Utility (Python)
|
||||
|
||||
```python
|
||||
# utils/serial_number.py
|
||||
import random, string
|
||||
from datetime import datetime
|
||||
|
||||
MONTH_CODES = "ABCDEFGHIJKL"
|
||||
SAFE_CHARS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # No 0,O,1,I
|
||||
|
||||
def generate_serial(board_type: str, board_version: str) -> str:
|
||||
now = datetime.utcnow()
|
||||
year = now.strftime("%y")
|
||||
month = MONTH_CODES[now.month - 1]
|
||||
day = now.strftime("%d")
|
||||
random_suffix = "".join(random.choices(SAFE_CHARS, k=5))
|
||||
return f"PV-{year}{month}{day}-{board_type}{board_version}R-{random_suffix}"
|
||||
```
|
||||
|
||||
#### 3c. NVS Binary Generation in FastAPI
|
||||
|
||||
- [ ] Copy `nvs_partition_gen.py` into your FastAPI project
|
||||
- [ ] Add endpoint `GET /manufacturing/devices/{sn}/nvs.bin`:
|
||||
- Generates a temp CSV for this SN
|
||||
- Runs `nvs_partition_gen.py` to produce the `.bin`
|
||||
- Returns the binary file as a download
|
||||
- [ ] Add endpoint `GET /manufacturing/devices/{sn}/firmware.bin`:
|
||||
- Looks up device's `hw_type` and `hw_version` from Firestore
|
||||
- Returns the correct firmware `.bin` from the NGINX folder (or redirects to NGINX URL)
|
||||
|
||||
#### 3d. Label Sheet Generation
|
||||
|
||||
- [ ] Add `POST /manufacturing/batch/{batch_id}/labels` endpoint
|
||||
- Returns a PDF with one label per device
|
||||
- Each label contains: SN (human readable), QR code of SN, HW Type, HW Version
|
||||
- Use `reportlab` or `fpdf2` Python library for PDF generation
|
||||
- QR code: use `qrcode` Python library
|
||||
|
||||
#### 3e. Frontend — Manufacturing Section in React Console
|
||||
|
||||
- [ ] New route: `/manufacturing`
|
||||
- [ ] **Batch Creator:** Form with board type selector, quantity, subscription plan → calls `POST /manufacturing/batch` → shows created SNs + download label PDF button
|
||||
- [ ] **Device List:** Filterable table of all devices with status badges (manufactured / sold / claimed / active)
|
||||
- [ ] **Device Detail Page:** Shows all fields, allows status update, shows assignment history
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — Browser-Based Flashing (The Provisioning Wizard)
|
||||
|
||||
> **Goal:** A single browser tab handles the entire provisioning flow. Plug in ESP32, click through wizard, done. No Arduino IDE, no esptool CLI, no SSH.
|
||||
>
|
||||
> **Tell Claude Code:** *"Add a Device Provisioning Wizard to our React admin console using esptool-js and the Web Serial API."*
|
||||
>
|
||||
> **Browser requirement:** Chrome or Edge only (Web Serial API). Firefox not supported. This is fine for an internal manufacturing tool.
|
||||
|
||||
### Tasks
|
||||
|
||||
#### 4a. Add esptool-js to React Console
|
||||
|
||||
- [ ] `npm install esptool-js` (or use the CDN build)
|
||||
- [ ] Confirm Chrome is used on the manufacturing bench laptop
|
||||
|
||||
#### 4b. Provisioning Wizard UI (React Component)
|
||||
|
||||
Build a step-by-step wizard. Steps:
|
||||
|
||||
**Step 1 — Select or Create Device**
|
||||
- Search existing unprovisioned device by SN, OR
|
||||
- Quick-create single device (calls `POST /manufacturing/batch` with qty=1)
|
||||
- Displays SN, HW Type, HW Version
|
||||
|
||||
**Step 2 — Flash Device**
|
||||
- "Connect Device" button → triggers Web Serial port picker
|
||||
- Fetches `nvs.bin` and `firmware.bin` from your FastAPI backend for this SN
|
||||
- Shows two progress bars: NVS partition flash + Firmware flash
|
||||
- Flash addresses (example for standard ESP32):
|
||||
- NVS: `0x9000` (verify against your partition table)
|
||||
- Firmware: `0x10000`
|
||||
- On completion: updates device status to `flashed` in Firestore via API call
|
||||
|
||||
**Step 3 — Verify**
|
||||
- Prompt: "Power cycle device and wait for it to connect"
|
||||
- Poll Firestore (or MQTT) for first heartbeat/connection from this SN
|
||||
- Show green checkmark when device phone home
|
||||
- Updates status to `provisioned`
|
||||
|
||||
**Step 4 — Done**
|
||||
- Show summary
|
||||
- Option: "Provision next device" (loops back to Step 1 with same batch settings)
|
||||
- Option: "Print label" (downloads single-device PDF label)
|
||||
|
||||
#### 4c. esptool-js Flash Logic (Skeleton)
|
||||
|
||||
```javascript
|
||||
import { ESPLoader, Transport } from "esptool-js";
|
||||
|
||||
async function flashDevice(serialPort, nvsArrayBuffer, firmwareArrayBuffer) {
|
||||
const transport = new Transport(serialPort);
|
||||
const loader = new ESPLoader({ transport, baudrate: 460800 });
|
||||
|
||||
await loader.main_fn();
|
||||
await loader.flash_id();
|
||||
|
||||
await loader.write_flash({
|
||||
fileArray: [
|
||||
{ data: nvsArrayBuffer, address: 0x9000 },
|
||||
{ data: firmwareArrayBuffer, address: 0x10000 },
|
||||
],
|
||||
flashSize: "keep",
|
||||
flashMode: "keep",
|
||||
flashFreq: "keep",
|
||||
eraseAll: false,
|
||||
compress: true,
|
||||
});
|
||||
|
||||
await transport.disconnect();
|
||||
}
|
||||
```
|
||||
|
||||
#### 4d. NGINX CORS Headers
|
||||
|
||||
Add to your NGINX config so the browser can fetch `.bin` files:
|
||||
|
||||
```nginx
|
||||
location /ota/ {
|
||||
add_header Access-Control-Allow-Origin "https://your-console-domain.com";
|
||||
add_header Access-Control-Allow-Methods "GET";
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — Email Notifications
|
||||
|
||||
> **Goal:** Admin Console can send transactional emails (device assignment invites, alerts, etc.)
|
||||
>
|
||||
> **Tell Claude Code:** *"Add email sending capability to our FastAPI backend using Resend (or SMTP)."*
|
||||
|
||||
### Tasks
|
||||
|
||||
- [ ] Sign up for [Resend](https://resend.com) (free tier: 3000 emails/month, 100/day)
|
||||
- [ ] Add `RESEND_API_KEY` to `.env`
|
||||
- [ ] Install: `pip install resend`
|
||||
- [ ] Create `utils/email.py`:
|
||||
|
||||
```python
|
||||
import resend
|
||||
import os
|
||||
|
||||
resend.api_key = os.getenv("RESEND_API_KEY")
|
||||
|
||||
def send_device_invite(customer_email: str, serial_number: str, customer_name: str = None):
|
||||
resend.Emails.send({
|
||||
"from": "noreply@yourcompany.com",
|
||||
"to": customer_email,
|
||||
"subject": "Your Vesper device is ready",
|
||||
"html": f"""
|
||||
<h2>Your device has been registered</h2>
|
||||
<p>Serial Number: <strong>{serial_number}</strong></p>
|
||||
<p>Open the Vesper app and enter this serial number to get started.</p>
|
||||
"""
|
||||
})
|
||||
```
|
||||
|
||||
- [ ] Hook into `POST /manufacturing/devices/{sn}/assign` to send invite automatically
|
||||
- [ ] Add basic email templates for: device assignment, welcome, error alerts
|
||||
|
||||
---
|
||||
|
||||
## Phase 6 — Polish & Retire Legacy Tools
|
||||
|
||||
> **Goal:** Clean up. Everything lives in the Console. Nothing is done manually.
|
||||
|
||||
### Tasks
|
||||
|
||||
- [ ] **Retire Flutter admin app** — confirm every function it had is now in the React Console
|
||||
- [ ] **Remove static mosquitto password file** — all auth is dynamic now
|
||||
- [ ] **Add device status dashboard** to Console home: counts by status, recent provisioning activity
|
||||
- [ ] **Add audit log** — every manufacturing action (batch created, device flashed, device assigned) logged to SQLite with timestamp and admin user
|
||||
- [ ] **Document your `platformio.ini` environments** — add a `FIRMWARE_VARIANTS.md` to the firmware repo
|
||||
- [ ] **Set up Gitea webhook** → on push to `main`, VPS auto-pulls and restarts Docker containers (replaces manual `git pull`)
|
||||
|
||||
---
|
||||
|
||||
## Gitea / Docker Compose Deployment Note
|
||||
|
||||
Your local Docker Compose setup and VPS production setup are the same codebase — this is correct and will continue to work fine. A few tips:
|
||||
|
||||
- Use a `.env.production` and `.env.development` file, never commit either
|
||||
- Your `docker-compose.yml` should reference `${ENV_VAR}` from the env file
|
||||
- The Gitea webhook for auto-deploy is a simple shell script triggered by the webhook:
|
||||
```bash
|
||||
#!/bin/bash
|
||||
cd /path/to/project
|
||||
git pull origin main
|
||||
docker compose up -d --build
|
||||
```
|
||||
- Protect this webhook endpoint with a secret token
|
||||
|
||||
---
|
||||
|
||||
## Summary — What Gets Killed
|
||||
|
||||
| Old Way | Replaced By |
|
||||
|---|---|
|
||||
| Arduino IDE | PlatformIO (VS Code) |
|
||||
| Manual `mosquitto_passwd` via SSH | FastAPI dynamic auth endpoints |
|
||||
| Flutter admin app | React Admin Console |
|
||||
| Manual SN generation | Console batch creator |
|
||||
| Manual DB entry per device | Auto-provisioned on batch creation |
|
||||
| Manual firmware flash + config page | Browser provisioning wizard (esptool-js) |
|
||||
| Manual NVS entry via HTTP config page | Pre-flashed NVS partition |
|
||||
|
||||
## Estimated Time Per Device (After All Phases Complete)
|
||||
|
||||
| Task | Time |
|
||||
|---|---|
|
||||
| Generate 15-device batch + print labels | ~2 min |
|
||||
| Flash each device (plug in, click Flash, done) | ~3 min each (parallelizable) |
|
||||
| Devices self-verify on lab WiFi | passive, ~1 min each |
|
||||
| **Total for 15 devices** | **~20-25 min** |
|
||||
|
||||
vs. current ~20 min per device = ~5 hours for 15.
|
||||
@@ -1,534 +0,0 @@
|
||||
/*
|
||||
|
||||
█████ █████ ██████████ █████████ ███████████ ██████████ ███████████
|
||||
▒▒███ ▒▒███ ▒▒███▒▒▒▒▒█ ███▒▒▒▒▒███▒▒███▒▒▒▒▒███▒▒███▒▒▒▒▒█▒▒███▒▒▒▒▒███
|
||||
▒███ ▒███ ▒███ █ ▒ ▒███ ▒▒▒ ▒███ ▒███ ▒███ █ ▒ ▒███ ▒███
|
||||
▒███ ▒███ ▒██████ ▒▒█████████ ▒██████████ ▒██████ ▒██████████
|
||||
▒▒███ ███ ▒███▒▒█ ▒▒▒▒▒▒▒▒███ ▒███▒▒▒▒▒▒ ▒███▒▒█ ▒███▒▒▒▒▒███
|
||||
▒▒▒█████▒ ▒███ ▒ █ ███ ▒███ ▒███ ▒███ ▒ █ ▒███ ▒███
|
||||
▒▒███ ██████████▒▒█████████ █████ ██████████ █████ █████
|
||||
▒▒▒ ▒▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒▒
|
||||
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* Project VESPER - BELL AUTOMATION SYSTEM - Main Firmware Entry Point
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🔔 DESCRIPTION:
|
||||
* High-precision automated bell control system with multi-protocol communication,
|
||||
* real-time telemetry, OTA updates, and modular hardware abstraction.
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* Clean modular design with dependency injection and proper separation of concerns.
|
||||
* Each major system is encapsulated in its own class with well-defined interfaces.
|
||||
*
|
||||
* 🎯 KEY FEATURES:
|
||||
* ✅ Microsecond-precision bell timing (BellEngine)
|
||||
* ✅ Multi-hardware support (PCF8574, GPIO, Mock)
|
||||
* ✅ Dual network connectivity (Ethernet + WiFi + Permanent AP Mode)
|
||||
* ✅ Multi-protocol communication (MQTT + WebSocket + HTTP REST API)
|
||||
* ✅ Web settings interface for network mode switching
|
||||
* ✅ Real-time telemetry and load monitoring
|
||||
* ✅ Over-the-air firmware updates
|
||||
* ✅ SD card configuration and file management
|
||||
* ✅ NTP time synchronization
|
||||
* ✅ Comprehensive logging system
|
||||
*
|
||||
* 📡 COMMUNICATION PROTOCOLS:
|
||||
* • MQTT (SSL/TLS via AsyncMqttClient on Core 0)
|
||||
* • WebSocket (Real-time web interface)
|
||||
* • HTTP REST API (Command execution via HTTP)
|
||||
* • UDP Discovery (Auto-discovery service)
|
||||
* • HTTP/HTTPS (OTA updates)
|
||||
*
|
||||
* 🔧 HARDWARE ABSTRACTION:
|
||||
* OutputManager provides clean interface for different relay systems:
|
||||
* - PCF8574OutputManager: I2C GPIO expander (8 outputs, 6 on Kincony A6 Board)
|
||||
* - GPIOOutputManager: Direct ESP32 pins (for DIY projects)
|
||||
* - MockOutputManager: Testing without hardware
|
||||
*
|
||||
* ⚡ PERFORMANCE:
|
||||
* High-priority FreeRTOS tasks ensure microsecond timing precision.
|
||||
* Core 1 dedicated to BellEngine for maximum performance.
|
||||
*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* 📋 VERSION CONFIGURATION
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* 📅 DATE: 2025-10-10
|
||||
* 👨💻 AUTHOR: BellSystems bonamin
|
||||
*/
|
||||
|
||||
#define FW_VERSION "154"
|
||||
|
||||
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* 📅 VERSION HISTORY:
|
||||
* NOTE: Versions are now stored as integers (v1.3 = 130)
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* v0.1 (100) - Vesper Launch Beta
|
||||
* v1.2 (120) - Added Log Level Configuration via App/MQTT
|
||||
* v1.3 (130) - Added Telemetry Reports to App, Various Playback Fixes
|
||||
* v137 - Made OTA and MQTT delays Async
|
||||
* v138 - Removed Ethernet, added default WiFi creds (Mikrotik AP) and fixed various Clock issues
|
||||
* v140 - Changed FW Updates to Direct-to-Flash and added manual update functionality with version check
|
||||
* v151 - Fixed Clock Alerts not running properly
|
||||
* v152 - Fix RTC Time Reports, added sync_time_to_LCD functionality
|
||||
* v153 - Fix Infinite Loop Bug and Melody Download crashes.
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// SYSTEM LIBRARIES - Core ESP32 and Arduino functionality
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
#include <SD.h> // SD card file system operations
|
||||
#include <FS.h> // File system base class
|
||||
#include <ETH.h> // Ethernet connectivity (W5500 support)
|
||||
#include <SPI.h> // SPI communication protocol
|
||||
#include <Arduino.h> // Arduino core framework
|
||||
#include <WiFi.h> // WiFi connectivity management
|
||||
#include <HTTPClient.h> // HTTP client for OTA updates
|
||||
#include <Update.h> // Firmware update utilities
|
||||
#include <Wire.h> // I2C communication protocol
|
||||
#include <esp_task_wdt.h> // Task watchdog timer
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// NETWORKING LIBRARIES - Advanced networking and communication
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
#include <WiFiManager.h> // WiFi configuration portal
|
||||
#include <ESPAsyncWebServer.h> // Async web server for WebSocket support
|
||||
#include <AsyncUDP.h> // UDP for discovery service
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// DATA PROCESSING LIBRARIES - JSON parsing and data structures
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
#include <ArduinoJson.h> // Efficient JSON processing
|
||||
#include <string> // STL string support
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// HARDWARE LIBRARIES - Peripheral device control
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
#include <Adafruit_PCF8574.h> // I2C GPIO expander for relay control
|
||||
#include <RTClib.h> // Real-time clock functionality
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// CUSTOM CLASSES - Include Custom Classes and Functions
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
#include "src/SDCardMutex/SDCardMutex.hpp" // ⚠️ MUST be included before any SD-using classes
|
||||
#include "src/ConfigManager/ConfigManager.hpp"
|
||||
#include "src/FileManager/FileManager.hpp"
|
||||
#include "src/TimeKeeper/TimeKeeper.hpp"
|
||||
#include "src/Logging/Logging.hpp"
|
||||
#include "src/Telemetry/Telemetry.hpp"
|
||||
#include "src/OTAManager/OTAManager.hpp"
|
||||
#include "src/Networking/Networking.hpp"
|
||||
#include "src/Communication/CommunicationRouter/CommunicationRouter.hpp"
|
||||
#include "src/ClientManager/ClientManager.hpp"
|
||||
#include "src/Communication/ResponseBuilder/ResponseBuilder.hpp"
|
||||
#include "src/Player/Player.hpp"
|
||||
#include "src/BellEngine/BellEngine.hpp"
|
||||
#include "src/OutputManager/OutputManager.hpp"
|
||||
#include "src/HealthMonitor/HealthMonitor.hpp"
|
||||
#include "src/FirmwareValidator/FirmwareValidator.hpp"
|
||||
#include "src/InputManager/InputManager.hpp"
|
||||
|
||||
// Class Constructors
|
||||
ConfigManager configManager;
|
||||
FileManager fileManager(&configManager);
|
||||
Timekeeper timekeeper;
|
||||
Telemetry telemetry;
|
||||
OTAManager otaManager(configManager);
|
||||
Player player;
|
||||
AsyncWebServer server(80);
|
||||
AsyncWebSocket ws("/ws");
|
||||
AsyncUDP udp;
|
||||
Networking networking(configManager);
|
||||
CommunicationRouter communication(configManager, otaManager, networking, server, ws, udp);
|
||||
HealthMonitor healthMonitor;
|
||||
FirmwareValidator firmwareValidator;
|
||||
InputManager inputManager;
|
||||
|
||||
|
||||
// 🔥 OUTPUT SYSTEM - PCF8574/PCF8575 I2C Expanders Configuration
|
||||
// Choose one of the following configurations (with active output counts):
|
||||
|
||||
// Option 1: Single PCF8574 (6 active outputs out of 8 max)
|
||||
PCF8574OutputManager outputManager(0x24, ChipType::PCF8574, 6);
|
||||
|
||||
// Option 2: Single PCF8575 (8 active outputs out of 16 max)
|
||||
//PCF8574OutputManager outputManager(0x24, ChipType::PCF8575, 8);
|
||||
|
||||
// Option 3: PCF8574 + PCF8575 (6 + 8 = 14 total virtual outputs)
|
||||
//PCF8574OutputManager outputManager(0x24, ChipType::PCF8574, 6, 0x21, ChipType::PCF8575, 8);
|
||||
|
||||
// Option 4: Dual PCF8575 (8 + 8 = 16 total virtual outputs)
|
||||
//PCF8574OutputManager outputManager(0x24, ChipType::PCF8575, 8, 0x21, ChipType::PCF8575, 8);
|
||||
|
||||
// Virtual Output Mapping Examples:
|
||||
// Option 1: Virtual outputs 0-5 → PCF8574[0x20] pins 0-5
|
||||
// Option 3: Virtual outputs 0-5 → PCF8574[0x20] pins 0-5, Virtual outputs 6-13 → PCF8575[0x21] pins 0-7
|
||||
// Option 4: Virtual outputs 0-7 → PCF8575[0x20] pins 0-7, Virtual outputs 8-15 → PCF8575[0x21] pins 0-7
|
||||
|
||||
// Legacy backward-compatible (defaults to 8 active outputs):
|
||||
//PCF8574OutputManager outputManager(0x20, ChipType::PCF8574); // 8/8 active outputs
|
||||
|
||||
BellEngine bellEngine(player, configManager, telemetry, outputManager); // 🔥 THE ULTIMATE BEAST!
|
||||
|
||||
TaskHandle_t bellEngineHandle = NULL; // Legacy - will be removed
|
||||
TimerHandle_t schedulerTimer;
|
||||
TimerHandle_t ntpSyncTimer; // Non-blocking delayed NTP sync timer
|
||||
|
||||
|
||||
|
||||
void handleFactoryReset() {
|
||||
if (configManager.resetAllToDefaults()) {
|
||||
delay(3000);
|
||||
ESP.restart();
|
||||
}
|
||||
}
|
||||
|
||||
// Non-blocking NTP sync timer callback
|
||||
void ntpSyncTimerCallback(TimerHandle_t xTimer) {
|
||||
LOG_DEBUG("Network stabilization complete - starting NTP sync");
|
||||
if (!networking.isInAPMode()) {
|
||||
timekeeper.syncTimeWithNTP();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
void setup()
|
||||
{
|
||||
// Initialize Serial Communications (for debugging) & I2C Bus (for Hardware Control)
|
||||
Serial.begin(115200);
|
||||
Serial.print("VESPER System Booting UP! - Version ");
|
||||
Serial.println(FW_VERSION);
|
||||
Wire.begin(4,15);
|
||||
auto& hwConfig = configManager.getHardwareConfig();
|
||||
SPI.begin(hwConfig.ethSpiSck, hwConfig.ethSpiMiso, hwConfig.ethSpiMosi);
|
||||
delay(50);
|
||||
|
||||
// 🔒 CRITICAL: Initialize SD Card Mutex BEFORE any SD operations
|
||||
// This prevents concurrent SD access from multiple FreeRTOS tasks
|
||||
if (!SDCardMutex::getInstance().begin()) {
|
||||
Serial.println("❌ FATAL: Failed to initialize SD card mutex!");
|
||||
Serial.println(" System cannot continue safely - entering infinite loop");
|
||||
while(1) { delay(1000); } // Halt system - unsafe to proceed
|
||||
}
|
||||
Serial.println("✅ SD card mutex initialized");
|
||||
|
||||
// Initialize Configuration (loads factory identity from NVS + user settings from SD)
|
||||
configManager.begin();
|
||||
|
||||
// Apply log level from config (loaded from SD)
|
||||
uint8_t logLevel = configManager.getGeneralConfig().serialLogLevel;
|
||||
Logging::setLevel((Logging::LogLevel)logLevel);
|
||||
LOG_INFO("Log level set to %d from configuration", logLevel);
|
||||
|
||||
inputManager.begin();
|
||||
inputManager.setFactoryResetLongPressCallback(handleFactoryReset);
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// REMOVED: Manual device identity setters
|
||||
// Device identity (UID, hwType, hwVersion) is now READ-ONLY in production firmware
|
||||
// These values are set by factory firmware and stored permanently in NVS
|
||||
// Production firmware loads them once at boot and keeps them in RAM
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
// Update firmware version (this is the ONLY identity field that can be set)
|
||||
|
||||
// 🔥 MIGRATION: Convert old float-style version to integer format
|
||||
String currentVersion = configManager.getFwVersion();
|
||||
if (currentVersion.indexOf('.') != -1) {
|
||||
// Old format detected (e.g., "1.3"), convert to integer ("130")
|
||||
float versionFloat = currentVersion.toFloat();
|
||||
uint16_t versionInt = (uint16_t)(versionFloat * 100.0f);
|
||||
configManager.setFwVersion(String(versionInt));
|
||||
configManager.saveDeviceConfig();
|
||||
LOG_INFO("⚠️ Migrated version format: %s -> %u", currentVersion.c_str(), versionInt);
|
||||
}
|
||||
|
||||
configManager.setFwVersion(FW_VERSION);
|
||||
LOG_INFO("Firmware version: %s", FW_VERSION);
|
||||
|
||||
|
||||
// Display device information after configuration is loaded
|
||||
Serial.println("\n=== DEVICE IDENTITY ===");
|
||||
Serial.printf("Device UID: %s\n", configManager.getDeviceUID().c_str());
|
||||
Serial.printf("Hardware Type: %s\n", configManager.getHwType().c_str());
|
||||
Serial.printf("Hardware Version: %s\n", configManager.getHwVersion().c_str());
|
||||
Serial.printf("Firmware Version: %s\n", configManager.getFwVersion().c_str());
|
||||
Serial.printf("AP SSID: %s\n", configManager.getAPSSID().c_str());
|
||||
Serial.println("=====================\n");
|
||||
|
||||
// 🔥 CRITICAL: Initialize Health Monitor FIRST (required for firmware validation)
|
||||
healthMonitor.begin();
|
||||
// Register all subsystems with health monitor for continuous monitoring
|
||||
healthMonitor.setConfigManager(&configManager);
|
||||
healthMonitor.setFileManager(&fileManager);
|
||||
|
||||
// Initialize Output Manager - 🔥 THE NEW WAY!
|
||||
outputManager.setConfigManager(&configManager);
|
||||
if (!outputManager.initialize()) {
|
||||
LOG_ERROR("Failed to initialize OutputManager!");
|
||||
// Continue anyway for now
|
||||
}
|
||||
// Register OutputManager with health monitor
|
||||
healthMonitor.setOutputManager(&outputManager);
|
||||
|
||||
// Initialize BellEngine early for health validation
|
||||
bellEngine.begin();
|
||||
healthMonitor.setBellEngine(&bellEngine);
|
||||
|
||||
delay(100);
|
||||
|
||||
// 🔥 BULLETPROOF: Initialize Firmware Validator and perform startup validation
|
||||
firmwareValidator.begin(&healthMonitor, &configManager);
|
||||
delay(100);
|
||||
|
||||
// 💀 CRITICAL SAFETY CHECK: Perform startup validation
|
||||
// This MUST happen early before initializing other subsystems
|
||||
if (!firmwareValidator.performStartupValidation()) {
|
||||
// If we reach here, startup validation failed and rollback was triggered
|
||||
// The system should reboot automatically to the previous firmware
|
||||
LOG_ERROR("💀 STARTUP VALIDATION FAILED - SYSTEM HALTED");
|
||||
while(1) { delay(1000); } // Should not reach here
|
||||
}
|
||||
|
||||
LOG_INFO("✅ Firmware startup validation PASSED - proceeding with initialization");
|
||||
|
||||
// Initialize remaining subsystems...
|
||||
|
||||
// SD Card initialization is now handled by ConfigManager
|
||||
|
||||
// Initialize timekeeper with NO clock outputs
|
||||
timekeeper.begin(); // No parameters needed
|
||||
// Connect the timekeeper to dependencies (CLEAN!)
|
||||
timekeeper.setOutputManager(&outputManager);
|
||||
timekeeper.setConfigManager(&configManager);
|
||||
timekeeper.setNetworking(&networking);
|
||||
timekeeper.setPlayer(&player); // 🔥 Connect for playback coordination
|
||||
// Clock outputs now configured via ConfigManager/Communication commands
|
||||
|
||||
// Register TimeKeeper with health monitor
|
||||
healthMonitor.setTimeKeeper(&timekeeper);
|
||||
|
||||
// Initialize Telemetry
|
||||
telemetry.setPlayerReference(&player.isPlaying);
|
||||
// 🚑 CRITICAL: Connect force stop callback for overload protection!
|
||||
telemetry.setForceStopCallback([]() { player.forceStop(); });
|
||||
telemetry.setFileManager(&fileManager);
|
||||
telemetry.begin();
|
||||
|
||||
// Register Telemetry with health monitor
|
||||
healthMonitor.setTelemetry(&telemetry);
|
||||
|
||||
|
||||
// Initialize Networking (handles everything automatically)
|
||||
networking.begin();
|
||||
|
||||
// Register Networking with health monitor
|
||||
healthMonitor.setNetworking(&networking);
|
||||
|
||||
// Initialize Player
|
||||
player.begin();
|
||||
|
||||
// Register Player with health monitor
|
||||
healthMonitor.setPlayer(&player);
|
||||
|
||||
// BellEngine already initialized and registered earlier for health validation
|
||||
|
||||
// Initialize Communication Manager (now with PubSubClient MQTT)
|
||||
communication.begin();
|
||||
communication.setPlayerReference(&player);
|
||||
communication.setFileManagerReference(&fileManager);
|
||||
communication.setTimeKeeperReference(&timekeeper);
|
||||
communication.setFirmwareValidatorReference(&firmwareValidator);
|
||||
communication.setTelemetryReference(&telemetry);
|
||||
|
||||
player.setDependencies(&communication, &fileManager);
|
||||
player.setBellEngine(&bellEngine); // Connect the beast!
|
||||
player.setTelemetry(&telemetry);
|
||||
player.setTimekeeper(&timekeeper); // 🔥 Connect for alert coordination
|
||||
|
||||
// Register Communication with health monitor
|
||||
healthMonitor.setCommunication(&communication);
|
||||
|
||||
// 🔔 CONNECT BELLENGINE TO COMMUNICATION FOR DING NOTIFICATIONS!
|
||||
bellEngine.setCommunicationManager(&communication);
|
||||
|
||||
// Track if AsyncWebServer has been started to prevent duplicates
|
||||
static bool webServerStarted = false;
|
||||
|
||||
// Create NTP sync timer (one-shot, 3 second delay for network stabilization)
|
||||
ntpSyncTimer = xTimerCreate(
|
||||
"NTPSync", // Timer name
|
||||
pdMS_TO_TICKS(3000), // 3 second delay (network stabilization)
|
||||
pdFALSE, // One-shot timer (not auto-reload)
|
||||
NULL, // Timer ID (not used)
|
||||
ntpSyncTimerCallback // Callback function
|
||||
);
|
||||
|
||||
// Set up network callbacks
|
||||
networking.setNetworkCallbacks(
|
||||
[&webServerStarted]() {
|
||||
communication.onNetworkConnected();
|
||||
|
||||
// Schedule non-blocking NTP sync after 3s network stabilization (like MQTT)
|
||||
// Skip NTP sync in AP mode (no internet connection)
|
||||
if (!networking.isInAPMode() && ntpSyncTimer) {
|
||||
LOG_DEBUG("Network connected - scheduling NTP sync after 3s stabilization (non-blocking)");
|
||||
xTimerStart(ntpSyncTimer, 0);
|
||||
}
|
||||
|
||||
// Start AsyncWebServer when network becomes available (only once!)
|
||||
if (!webServerStarted && networking.getState() != NetworkState::WIFI_PORTAL_MODE) {
|
||||
LOG_INFO("🚀 Starting AsyncWebServer on port 80...");
|
||||
server.begin();
|
||||
LOG_INFO("✅ AsyncWebServer started on http://%s", networking.getLocalIP().c_str());
|
||||
webServerStarted = true;
|
||||
}
|
||||
}, // onConnected
|
||||
[]() { communication.onNetworkDisconnected(); } // onDisconnected
|
||||
);
|
||||
|
||||
// If already connected, trigger MQTT connection and setup manually
|
||||
if (networking.isConnected()) {
|
||||
LOG_INFO("Network already connected - initializing services");
|
||||
communication.onNetworkConnected();
|
||||
|
||||
// Schedule non-blocking NTP sync after 3s network stabilization (like MQTT)
|
||||
// Skip NTP sync in AP mode (no internet connection)
|
||||
if (!networking.isInAPMode() && ntpSyncTimer) {
|
||||
LOG_DEBUG("Network already connected - scheduling NTP sync after 3s stabilization (non-blocking)");
|
||||
xTimerStart(ntpSyncTimer, 0);
|
||||
}
|
||||
|
||||
// 🔥 CRITICAL: Start AsyncWebServer ONLY when network is ready
|
||||
// Do NOT start if WiFiManager portal is active (port 80 conflict!)
|
||||
if (!webServerStarted && networking.getState() != NetworkState::WIFI_PORTAL_MODE) {
|
||||
LOG_INFO("🚀 Starting AsyncWebServer on port 80...");
|
||||
server.begin();
|
||||
LOG_INFO("✅ AsyncWebServer started on http://%s", networking.getLocalIP().c_str());
|
||||
webServerStarted = true;
|
||||
}
|
||||
} else {
|
||||
LOG_WARNING("⚠️ Network not ready - services will start after connection");
|
||||
}
|
||||
|
||||
// Initialize OTA Manager
|
||||
otaManager.begin();
|
||||
otaManager.setFileManager(&fileManager);
|
||||
otaManager.setPlayer(&player); // Set player reference for idle check
|
||||
otaManager.setTimeKeeper(&timekeeper); // Set timekeeper reference for freeze mode
|
||||
otaManager.setTelemetry(&telemetry); // Set telemetry reference for freeze mode
|
||||
|
||||
// 🔥 FIX: OTA check will happen asynchronously via scheduled timer (no blocking delay)
|
||||
// UDP discovery setup can happen immediately without conflicts
|
||||
communication.setupUdpDiscovery();
|
||||
|
||||
// Register OTA Manager with health monitor
|
||||
healthMonitor.setOTAManager(&otaManager);
|
||||
|
||||
// Note: AsyncWebServer will be started by network callbacks when connection is ready
|
||||
// This avoids port 80 conflicts with WiFiManager's captive portal
|
||||
|
||||
|
||||
// 🔥 START RUNTIME VALIDATION: All subsystems are now initialized
|
||||
// Begin extended runtime validation if we're in testing mode
|
||||
if (firmwareValidator.isInTestingMode()) {
|
||||
LOG_INFO("🏃 Starting runtime validation - firmware will be tested for %lu seconds",
|
||||
firmwareValidator.getValidationConfig().runtimeTimeoutMs / 1000);
|
||||
firmwareValidator.startRuntimeValidation();
|
||||
} else {
|
||||
LOG_INFO("✅ Firmware already validated - normal operation mode");
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// INITIALIZATION COMPLETE
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// ✅ All automatic task creation handled by individual components:
|
||||
// • BellEngine creates high-priority timing task on Core 1
|
||||
// • Telemetry creates monitoring task for load tracking
|
||||
// • Player creates duration timer for playback control
|
||||
// • Communication creates MQTT task on Core 0 with PubSubClient
|
||||
// • Networking creates connection management timers
|
||||
// ✅ Bell configuration automatically loaded by ConfigManager
|
||||
// ✅ System ready for MQTT commands, WebSocket connections, and UDP discovery
|
||||
}
|
||||
|
||||
// ███████████████████████████████████████████████████████████████████████████████████
|
||||
// █ MAIN LOOP █
|
||||
// ███████████████████████████████████████████████████████████████████████████████████
|
||||
// The main loop is intentionally kept minimal in this architecture. All critical
|
||||
// functionality runs in dedicated FreeRTOS tasks for optimal performance and timing.
|
||||
// This ensures the main loop doesn't interfere with precision bell timing.
|
||||
|
||||
/**
|
||||
* @brief Main execution loop - Minimal by design
|
||||
*
|
||||
* In the new modular architecture, all heavy lifting is done by dedicated tasks:
|
||||
* • BellEngine: High-priority task on Core 1 for microsecond timing
|
||||
* • Telemetry: Background monitoring task for system health
|
||||
* • Player: Timer-based duration control for melody playback
|
||||
* • Communication: MQTT task on Core 0 + Event-driven WebSocket
|
||||
* • Networking: Automatic connection management
|
||||
*
|
||||
* The main loop only handles lightweight operations that don't require
|
||||
* precise timing or could benefit from running on Core 0.
|
||||
*
|
||||
* @note This loop runs on Core 0 and should remain lightweight to avoid
|
||||
* interfering with the precision timing on Core 1.
|
||||
*/
|
||||
void loop()
|
||||
{
|
||||
// Feed watchdog only during firmware validation
|
||||
if (firmwareValidator.isInTestingMode()) {
|
||||
esp_task_wdt_reset();
|
||||
} else {
|
||||
// Remove task from watchdog if validation completed
|
||||
static bool taskRemoved = false;
|
||||
if (!taskRemoved) {
|
||||
esp_task_wdt_delete(NULL); // Remove current task
|
||||
taskRemoved = true;
|
||||
}
|
||||
}
|
||||
|
||||
// 🔥 CRITICAL: Clean up dead WebSocket connections every 2 seconds
|
||||
// This prevents ghost connections from blocking new clients
|
||||
static unsigned long lastWsCleanup = 0;
|
||||
if (millis() - lastWsCleanup > 2000) {
|
||||
ws.cleanupClients();
|
||||
lastWsCleanup = millis();
|
||||
}
|
||||
|
||||
// Process UART command input from external devices (LCD panel, buttons)
|
||||
communication.loop();
|
||||
|
||||
// 🔥 DEBUG: Log every 10 seconds to verify we're still running
|
||||
static unsigned long lastLog = 0;
|
||||
if (millis() - lastLog > 10000) {
|
||||
LOG_DEBUG("❤️ Loop alive | Free heap: %d bytes (%.1f KB) | Min free: %d | Largest block: %d",
|
||||
ESP.getFreeHeap(),
|
||||
ESP.getFreeHeap() / 1024.0,
|
||||
ESP.getMinFreeHeap(),
|
||||
ESP.getMaxAllocHeap());
|
||||
lastLog = millis();
|
||||
}
|
||||
|
||||
// Keep the loop responsive but not busy
|
||||
delay(100); // ⏱️ 100ms delay to prevent busy waiting
|
||||
}
|
||||
Reference in New Issue
Block a user