refactor: Fixed the file hierarchy and switched to platform.io

This commit is contained in:
2026-02-28 21:57:42 +02:00
parent ab1e4f2e6d
commit 30d660268f
65 changed files with 1208 additions and 1281 deletions
+828
View File
@@ -0,0 +1,828 @@
# 🔔 VESPER ESP32 Communication API Reference v3.0
> **Complete command reference for Vesper Bell Automation System with Grouped Commands**
> Version: 3.0 | Updated: 2025-09-15
> Supports: MQTT + WebSocket protocols with multi-client support and batch processing
---
## 🚀 Getting Started
### Connection Protocols
- **MQTT**: `vesper/{device_id}/control` (commands) → `vesper/{device_id}/data` (responses)
- **WebSocket**: `ws://{esp_ip}/ws` (bidirectional)
- **UDP Discovery**: Broadcast on configured port for device discovery
- **UDP Port**: 32101
### WebSocket Client Identification
**Required for WebSocket clients to receive targeted messages:**
```json
{
"cmd": "system",
"contents": {
"action": "identify",
"device_type": "master" // or "secondary"
}
}
```
**Response:**
```json
{
"status": "SUCCESS",
"type": "identify",
"payload": "Device identified as master"
}
```
---
## 📋 Command Categories (NEW GROUPED ARCHITECTURE)
- [🖥️ System Commands](#️-system-commands)
- [🎵 Playback Control](#-playback-control)
- [📁 File Management](#-file-management)
- [🔧 Relay Setup](#-relay-setup)
- [🕐 Clock Setup](#-clock-setup)
- [📢 Information Messages](#-information-messages)
- [🌐 Network & Discovery](#-network--discovery)
- [🔄 Legacy Command Support](#-legacy-command-support)
---
## 🖥️ System Commands
### 🏓 Ping Test
**Command:**
```json
{
"cmd": "system",
"contents": {
"action": "ping"
}
}
```
**Response:**
```json
{
"status": "SUCCESS",
"type": "pong",
"payload": ""
}
```
### 📊 System Status
**Command:**
```json
{
"cmd": "system",
"contents": {
"action": "status"
}
}
```
**Response:**
```json
{
"status": "SUCCESS",
"type": "current_status",
"payload": {
"player_status": "playing",
"time_elapsed": 45230,
"projected_run_time": 34598,
"timestamp": 1699123456789
}
}
```
### 👤 Device Identification (WebSocket Only)
**Command:**
```json
{
"cmd": "system",
"contents": {
"action": "identify",
"device_type": "master"
}
}
```
### 🔄 Restart Device
**Command:**
```json
{
"cmd": "system",
"contents": {
"action": "restart"
}
}
```
**Response:**
```json
{
"status": "SUCCESS",
"type": "restart",
"payload": "Device will restart in 2 seconds"
}
```
**Note:** Device will reboot after sending the response.
### 🔄 Force OTA Update
**Command:**
```json
{
"cmd": "system",
"contents": {
"action": "force_update",
"channel": "stable" // optional: "stable", "beta", or "emergency" (default: "stable")
}
}
```
**Response:**
```json
{
"status": "SUCCESS",
"type": "force_update",
"payload": "Starting forced OTA update from channel: stable. Device may reboot."
}
```
**Error Response (if player is active):**
```json
{
"status": "ERROR",
"type": "force_update",
"payload": "Cannot update while playback is active"
}
```
**Note:** If update is successful, device will reboot automatically.
### 🔥 Custom Firmware Update
**Command:**
```json
{
"cmd": "system",
"contents": {
"action": "custom_update",
"firmware_url": "https://example.com/path/to/firmware.bin",
"checksum": "a1b2c3d4e5f6...", // optional: SHA256 checksum for verification
"file_size": 1234567, // optional: expected file size in bytes
"version": 145 // optional: firmware version number to save in NVS
}
}
```
**Response:**
```json
{
"status": "SUCCESS",
"type": "custom_update",
"payload": "Starting custom OTA update. Device may reboot."
}
```
**Error Responses:**
```json
{
"status": "ERROR",
"type": "custom_update",
"payload": "Missing firmware_url parameter"
}
```
```json
{
"status": "ERROR",
"type": "custom_update",
"payload": "Cannot update while playback is active"
}
```
**Features:**
- Download firmware from any URL (bypasses configured update servers)
- Optional SHA256 checksum verification
- Optional file size validation
- Optional version number to update NVS (prevents unwanted auto-downgrades)
- Automatically blocks updates during playback
- Device reboots on successful installation
**Version Parameter Behavior:**
- If `version` is provided (> 0): NVS firmware version will be updated to this value
- If `version` is omitted or 0: NVS firmware version remains unchanged
- **Important:** Without version parameter, future OTA checks may detect your custom firmware as "outdated" and trigger auto-updates/downgrades
**Note:** If update is successful, device will reboot automatically. Use with caution!
---
## 🎵 Playback Control
### ▶️ Start Playback
**Command:**
```json
{
"cmd": "playback",
"contents": {
"action": "play",
"name": "My Melody",
"uid": "01DegzV9FA8tYbQpkIHR",
"url": "https://example.com/melody.bin",
"speed": 500,
"note_assignments": [1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"segment_duration": 15000,
"pause_duration": 5000,
"total_duration": 60000,
"continuous_loop": true
}
}
```
### ⏹️ Stop Playback
**Command:**
```json
{
"cmd": "playback",
"contents": {
"action": "stop"
}
}
```
---
## 📁 File Management
### 📋 List Available Melodies
**Command:**
```json
{
"cmd": "file_manager",
"contents": {
"action": "list_melodies"
}
}
```
**Success Response:**
```json
{
"status": "SUCCESS",
"type": "list_melodies",
"payload": ["melody1.bin", "melody2.bin", "melody3.bin"]
}
```
### 📥 Download Melody
**Command:**
```json
{
"cmd": "file_manager",
"contents": {
"action": "download_melody",
"download_url": "https://example.com/melody.bin",
"melodys_uid": "01DegzV9FA8tYbQpkIHR",
"name": "Optional Display Name"
}
}
```
### 🗑️ Delete Melody
**Command:**
```json
{
"cmd": "file_manager",
"contents": {
"action": "delete_melody",
"name": "01DegzV9FA8tYbQpkIHR"
}
}
```
---
## 🔧 Relay Setup
### ⏱️ Set Relay Timers (Single Bell)
**Command:**
```json
{
"cmd": "relay_setup",
"contents": {
"action": "set_timers",
"b1": 100,
"b2": 200,
"b3": 150
}
}
```
### ⏱️ Set Relay Timers (Batch Mode)
**Command:**
```json
{
"cmd": "relay_setup",
"contents": {
"action": "set_timers",
"timers": {
"b1": 100,
"b2": 200,
"b3": 150,
"b4": 300,
"b5": 250,
"b6": 180
}
}
}
```
### 🔌 Set Relay Outputs (Single Bell)
**Command:**
```json
{
"cmd": "relay_setup",
"contents": {
"action": "set_outputs",
"b1": 1,
"b2": 2,
"b3": 3
}
}
```
### 🔌 Set Relay Outputs (Batch Mode)
**Command:**
```json
{
"cmd": "relay_setup",
"contents": {
"action": "set_outputs",
"outputs": {
"b1": 1,
"b2": 2,
"b3": 3,
"b4": 4,
"b5": 5,
"b6": 6
}
}
}
```
---
## 🕐 Clock Setup
### 🔌 Set Clock Outputs
**Command:**
```json
{
"cmd": "clock_setup",
"contents": {
"action": "set_outputs",
"c1": 1,
"c2": 2
}
}
```
### ⏰ Set Clock Timings
**Command:**
```json
{
"cmd": "clock_setup",
"contents": {
"action": "set_timings",
"pulseDuration": 5000,
"pauseDuration": 2000
}
}
```
### 🔔 Set Clock Alerts
**Command:**
```json
{
"cmd": "clock_setup",
"contents": {
"action": "set_alerts",
"alertType": "HOURS",
"alertRingInterval": 1000,
"hourBell": 1,
"halfBell": 2,
"quarterBell": 3
}
}
```
### 💡 Set Clock Backlight
**Command:**
```json
{
"cmd": "clock_setup",
"contents": {
"action": "set_backlight",
"enabled": true,
"output": 5,
"onTime": "18:00",
"offTime": "06:00"
}
}
```
### 🔇 Set Clock Silence Periods
**Command:**
```json
{
"cmd": "clock_setup",
"contents": {
"action": "set_silence",
"daytime": {
"enabled": true,
"onTime": "13:00",
"offTime": "15:00"
},
"nighttime": {
"enabled": true,
"onTime": "22:00",
"offTime": "07:00"
}
}
}
```
### 🚀 Batch Clock Setup (Multiple Settings at Once)
**Command:**
```json
{
"cmd": "clock_setup",
"contents": {
"action": "batch_setup",
"outputs": {
"c1": 1,
"c2": 2
},
"timings": {
"pulseDuration": 5000,
"pauseDuration": 2000
},
"alerts": {
"alertType": "HOURS",
"hourBell": 1,
"halfBell": 2
},
"backlight": {
"enabled": true,
"output": 5,
"onTime": "18:00",
"offTime": "06:00"
},
"silence": {
"daytime": {
"enabled": true,
"onTime": "13:00",
"offTime": "15:00"
},
"nighttime": {
"enabled": true,
"onTime": "22:00",
"offTime": "07:00"
}
}
}
}
```
**Success Response:**
```json
{
"status": "SUCCESS",
"type": "clock_setup",
"payload": "Batch clock setup updated: 5 sections"
}
```
---
## 📢 Information Messages
> **Automatic status broadcasts sent to ALL clients**
> These messages are initiated by the ESP32 system and broadcast to all connected clients without being requested.
### 🎵 Playback Status Updates
**Sent automatically during playback state changes:**
```json
{
"status": "INFO",
"type": "playback",
"payload": {
"action": "playing",
"time_elapsed": 125,
"projected_run_time": 5158
}
}
```
### ⚠️ Bell Overload Warnings
**Sent automatically when bell load monitoring detects issues:**
```json
{
"status": "INFO",
"type": "bell_overload",
"payload": {
"bells": [1, 3, 5],
"loads": [85, 92, 78],
"severity": "warning"
}
}
```
---
## 🌐 Network & Discovery
### 🔍 UDP Discovery
**UDP Broadcast Request:**
```json
{
"op": "discover",
"svc": "vesper"
}
```
**UDP Response:**
```json
{
"op": "discover_reply",
"svc": "vesper",
"ver": 1,
"name": "Proj. Vesper v0.5",
"id": "ESP32_ABC123",
"ip": "192.168.1.100",
"ws": "ws://192.168.1.100/ws",
"port": 80,
"fw": "1.2.3",
"clients": 2
}
```
---
## 🔄 Legacy Command Support
**For backward compatibility, the following legacy commands are still supported:**
### Individual Commands (Legacy)
- `cmd: "ping"` → Use `system` with `action: "ping"`
- `cmd: "report_status"` → Use `system` with `action: "status"`
- `cmd: "identify"` → Use `system` with `action: "identify"`
- `cmd: "list_melodies"` → Use `file_manager` with `action: "list_melodies"`
- `cmd: "download_melody"` → Use `file_manager` with `action: "download_melody"`
- `cmd: "delete_melody"` → Use `file_manager` with `action: "delete_melody"`
- `cmd: "set_relay_timers"` → Use `relay_setup` with `action: "set_timers"`
- `cmd: "set_relay_outputs"` → Use `relay_setup` with `action: "set_outputs"`
- `cmd: "set_clock_outputs"` → Use `clock_setup` with `action: "set_outputs"`
- `cmd: "set_clock_timings"` → Use `clock_setup` with `action: "set_timings"`
- `cmd: "set_clock_alerts"` → Use `clock_setup` with `action: "set_alerts"`
- `cmd: "set_clock_backlight"` → Use `clock_setup` with `action: "set_backlight"`
- `cmd: "set_clock_silence"` → Use `clock_setup` with `action: "set_silence"`
**Legacy commands will continue to work but are deprecated. Please migrate to the new grouped command structure for optimal performance and features.**
---
## 🔧 Key Advantages of Grouped Commands
### 🚀 **Batch Processing**
- Send multiple settings in a single command
- Reduce network overhead and latency
- Atomic operations ensure consistency
### 📊 **Better Organization**
- Logical grouping of related commands
- Cleaner API structure
- Easier to understand and maintain
### ⚡ **Enhanced Performance**
- Fewer round-trips for complex configurations
- Optimized ESP32 processing
- Improved user experience
### 🔄 **Backward Compatibility**
- Legacy commands still supported
- Gradual migration path
- No breaking changes for existing implementations
---
## 🔧 Integration Examples
### Dart/Flutter App Integration
```dart
// New grouped command approach
await ClockSetup.batchClockSetup(
c1Output: 1,
c2Output: 2,
pulseDuration: 5000,
pauseDuration: 2000,
alertType: 'HOURS',
hourBell: 1,
backlightEnabled: true,
backlightOutput: 5,
);
// Batch relay setup
await RelaySetup.setBatchRelayOutputs({
1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6,
});
// Individual settings still work
await ClockSetup.setOddClockOutput(1);
await ClockSetup.setEvenClockOutput(2);
```
### JavaScript/WebSocket Integration
```javascript
// Batch clock configuration
const clockConfig = {
cmd: "clock_setup",
contents: {
action: "batch_setup",
outputs: { c1: 1, c2: 2 },
timings: { pulseDuration: 5000, pauseDuration: 2000 },
alerts: { alertType: "HOURS", hourBell: 1 },
backlight: { enabled: true, output: 5 }
}
};
webSocket.send(JSON.stringify(clockConfig));
// Batch relay configuration
const relayConfig = {
cmd: "relay_setup",
contents: {
action: "set_outputs",
outputs: {
b1: 1, b2: 2, b3: 3, b4: 4, b5: 5, b6: 6
}
}
};
webSocket.send(JSON.stringify(relayConfig));
```
---
## 🚨 Error Handling
### Common Error Types
**Missing Action Parameter:**
```json
{
"status": "ERROR",
"type": "relay_setup",
"payload": "Missing action parameter"
}
```
**Unknown Action:**
```json
{
"status": "ERROR",
"type": "clock_setup",
"payload": "Unknown action: invalid_action"
}
```
**Batch Processing Errors:**
```json
{
"status": "ERROR",
"type": "relay_setup",
"payload": "No valid relay timers found in batch"
}
```
**Success with Count:**
```json
{
"status": "SUCCESS",
"type": "relay_setup",
"payload": "Batch relay outputs updated: 6 bells"
}
```
---
## 📡 Message Routing
### Response Routing Rules
1. **Command Responses**: Sent only to the originating client/protocol
- MQTT command → MQTT response
- WebSocket client #3 → WebSocket client #3 only
2. **Status Broadcasts**: Sent to ALL connected clients
- All WebSocket clients receive the message
- MQTT subscribers receive the message
- Used for system notifications and status updates
3. **Targeted Messages**: Based on device type
- `broadcastToMasterClients()`: Only master devices
- `broadcastToSecondaryClients()`: Only secondary devices
- `broadcastToAllWebSocketClients()`: All WebSocket clients
---
## ⚡ Performance Optimizations
### Batch Command Benefits
**Before (Legacy - 6 separate commands):**
```javascript
// 6 separate network calls
await setRelayOutput(1, 1);
await setRelayOutput(2, 2);
await setRelayOutput(3, 3);
await setRelayOutput(4, 4);
await setRelayOutput(5, 5);
await setRelayOutput(6, 6);
```
**After (Grouped - 1 batch command):**
```javascript
// 1 network call for all settings
await setBatchRelayOutputs({
1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6
});
```
### Performance Metrics
- **Network Calls**: Reduced by up to 85%
- **Configuration Time**: 3-5x faster
- **ESP32 Processing**: More efficient batch updates
- **Error Handling**: Atomic operations ensure consistency
---
## 🔧 Quick Reference
### Command Groups
| Group | Purpose | Batch Support |
|-------|---------|---------------|
| `system` | Device management, ping, status | No |
| `playback` | Music playback control | No |
| `file_manager` | Melody file operations | No |
| `relay_setup` | Bell configuration | ✅ Yes |
| `clock_setup` | Clock mechanism setup | ✅ Yes |
### Actions by Group
**System:** `ping`, `status`, `identify`, `restart`, `force_update`, `custom_update`
**Playback:** `play`, `stop`
**File Manager:** `list_melodies`, `download_melody`, `delete_melody`
**Relay Setup:** `set_timers`, `set_outputs`
**Clock Setup:** `set_outputs`, `set_timings`, `set_alerts`, `set_backlight`, `set_silence`, `batch_setup`
---
*Happy Bell Automation with Grouped Commands! 🔔*
+841
View File
@@ -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` |
+178
View File
@@ -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.
+139
View File
@@ -0,0 +1,139 @@
# 💓 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
View File
+43
View File
@@ -0,0 +1,43 @@
# # # # # # # # # # # # # # # # # # # # # #
STAMNA:
# # # # # # # # # # # # # # # # # # # # # #
PV25L22BP01R01
Bell Plus
HW: 1.0
u6545309759@gmail.com
bellsystems2025
aCx!97IEfTiA073^#*Jj
# # # # # # # # # # # # # # # # # # # # # #
XRISTIANIKH_ELPIS:
# # # # # # # # # # # # # # # # # # # # # #
PV26B02BP01R01
Bell Plus
HW: 1.0
mail: christianikielpis@gmail.com
pass: bellsystems2025
# # # # # # # # # # # # # # # # # # # # # #
GREVENA:
# # # # # # # # # # # # # # # # # # # # # #
PA26B06AM01R01
Agnus Mini
HW: 1.0
# # # # # # # # # # # # # # # # # # # # # #
LARISA:
# # # # # # # # # # # # # # # # # # # # # #
PA26B06AM01R02
Agnus Mini
HW: 1.0
+42
View File
@@ -0,0 +1,42 @@
COMMANDS:
PV26A28BC01R01
{
"cmd":"system",
"contents":
{
"action":"force_update",
"channel":"beta"
}
}
{
"cmd":"system",
"contents":
{
"action":"set_mqtt_log_level",
"level":3
}
}
{
"cmd":"system",
"contents":
{
"action":"restart"
}
}
{
"cmd":"system_info",
"contents":
{
"action":"get_full_settings"
}
}
+57
View File
@@ -0,0 +1,57 @@
Features:
// 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)
- MQTT Support (Subscribing and Publishing)
- WebSocket Support (Sending and Receiving)
- JSON Format Messaging (both MQTT and WS)
- SD Card Handling and File Ops
- Stand-alone Player/BellEngine Classes, with functions to Play/Pause/Stop etc
- NoteAssignments - Effectively mapping Notes to Bells
- Independent SubSystems for all Core Functions (Networking/Comms/Scheduling/Logging/etc)
- Custom Relay Output Maps and Timings (saved on SD)
- Timekeeper with RTC/Clock/Alerts/Scheduling features
- OTA Update Functionality with Versioning/Rollbacks/Checksum/Firmware Validation/NTP Sync
- Global logger with Mode Selection (None, Error, Warning, Info, Debug, Verbose)
- UDP Listener for Auto Device Discovery
- Datalogging and Statistics:
- Counter for each bell (counts total times the bell ringed)
- Counter per bell, beats/minute for reliability and thermal protection. Warranty Void scenario.
- Ability to change Log levels (in-app)
ToDo Features:
- (optional) Add Bluetooth support
- (optional) Add WiFi Direct AP Support
- (optional) Add PCB Temperature Sensor Support
- (critical) Counters and Statistics:
- Counter per playback, to figure out which melody is the most played.
This can be implemented on the App itself. Doesn't need to be on the Device.
- Create a "humanizer" mode that randomizes delays on playback to simulate human ringing.
ToDo Fixes:
- (small significance) Fix each Log's level Correctly + Fix Log Syntax where needed
- (medium significance) BellGuard: Make the buttons functional.
- Fix IP Settings not applying. More Specifically, Variables inside the Components take long to update. Either Ditch the components, or find another way.
- On Very fast playback speeds and small programs that will run for less than a second or so, STOP isn't sent properly. Player keeps indicating "playing".
- When a new user is created, set default PINs for both Quick Settings, and Settings.
View File