feat(comms): Stage 2 — all 10 domain handlers implemented
Adds the complete set of v2 command handlers. Old CommandHandler is
untouched — handlers are standalone and not yet wired to anything.
Handlers added:
PlaybackHandler — playback (1 dependency)
LoggingHandler — log.set_serial/sd/mqtt
FileHandler — files.list/list_builtin/download/delete
TelemetryHandler — telemetry.get_strikes/reset_strikes/get_loads
RelayHandler — relay.set_durations/set_outputs/get_config/test_output
FirmwareHandler — firmware.status/commit/rollback + ota.update/custom
NetworkHandler — network.info/status/set_config
MQTTHandler — mqtt.enable/disable
SystemHandler — ping/identify + system.* commands (8 total)
ClockHandler — 16 clock.* commands
Notable fixes vs. original CommandHandler:
- clock.set_timings now sets pulseDuration/pauseDuration correctly
(original called updateClockOutputs — was a bug)
- system.restart uses a deferred FreeRTOS task (no blocking delay)
- relay.test_output safety-gated: player must be fully stopped
- Timekeeper class name (lowercase k) corrected throughout
Two compile-time fixes applied during build:
- JsonVariantConst → const_cast<JsonDocument&>().as<JsonVariant>()
(ConfigManager methods take non-const JsonVariant)
- class TimeKeeper → class Timekeeper (actual class name in header)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,204 @@
|
||||
#include "SystemHandler.hpp"
|
||||
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||
#include "../../../Player/Player.hpp"
|
||||
#include "../../../Telemetry/Telemetry.hpp"
|
||||
#include "../../../HealthMonitor/HealthMonitor.hpp"
|
||||
#include "../../../TimeKeeper/TimeKeeper.hpp"
|
||||
#include "../../../ClientManager/ClientManager.hpp"
|
||||
#include "../../../Logging/Logging.hpp"
|
||||
#include <Arduino.h>
|
||||
|
||||
#define TAG "SystemHandler"
|
||||
|
||||
SystemHandler::SystemHandler(ConfigManager& configManager, Player& player,
|
||||
Telemetry& telemetry, HealthMonitor& healthMonitor,
|
||||
Timekeeper& timeKeeper, ClientManager& clientManager)
|
||||
: _configManager(configManager)
|
||||
, _player(player)
|
||||
, _telemetry(telemetry)
|
||||
, _healthMonitor(healthMonitor)
|
||||
, _timeKeeper(timeKeeper)
|
||||
, _clientManager(clientManager) {}
|
||||
|
||||
std::vector<String> SystemHandler::commands() const {
|
||||
return {
|
||||
"ping", "identify",
|
||||
"system.status", "system.get_time", "system.get_settings",
|
||||
"system.get_device_info", "system.health",
|
||||
"system.factory_reset", "system.restart"
|
||||
};
|
||||
}
|
||||
|
||||
CommandResult SystemHandler::execute(const CommandEnvelope& envelope) {
|
||||
if (envelope.command == "ping") return handlePing(envelope);
|
||||
if (envelope.command == "identify") return handleIdentify(envelope);
|
||||
if (envelope.command == "system.status") return handleStatus(envelope);
|
||||
if (envelope.command == "system.get_time") return handleGetTime(envelope);
|
||||
if (envelope.command == "system.get_settings") return handleGetSettings(envelope);
|
||||
if (envelope.command == "system.get_device_info") return handleGetDeviceInfo(envelope);
|
||||
if (envelope.command == "system.health") return handleHealth(envelope);
|
||||
if (envelope.command == "system.factory_reset") return handleFactoryReset(envelope);
|
||||
if (envelope.command == "system.restart") return handleRestart(envelope);
|
||||
return CommandResult::err(envelope.command, "Unknown system command");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
CommandResult SystemHandler::handlePing(const CommandEnvelope& e) {
|
||||
JsonDocument doc;
|
||||
doc["type"] = "pong";
|
||||
return CommandResult::ok("pong");
|
||||
}
|
||||
|
||||
CommandResult SystemHandler::handleIdentify(const CommandEnvelope& e) {
|
||||
if (e.transport != CommandEnvelope::Transport::WEBSOCKET) {
|
||||
return CommandResult::err("identify", "identify is only available via WebSocket");
|
||||
}
|
||||
if (!e.contents["device_type"].is<const char*>()) {
|
||||
return CommandResult::err("identify", "Missing required field: device_type");
|
||||
}
|
||||
|
||||
String deviceTypeStr = e.contents["device_type"].as<String>();
|
||||
ClientManager::DeviceType deviceType = ClientManager::DeviceType::UNKNOWN;
|
||||
if (deviceTypeStr == "master") deviceType = ClientManager::DeviceType::MASTER;
|
||||
if (deviceTypeStr == "secondary") deviceType = ClientManager::DeviceType::SECONDARY;
|
||||
|
||||
if (deviceType == ClientManager::DeviceType::UNKNOWN) {
|
||||
return CommandResult::err("identify", "Invalid device_type. Use 'master' or 'secondary'");
|
||||
}
|
||||
|
||||
_clientManager.updateClientType(e.clientId, deviceType);
|
||||
LOG_INFO(TAG, "Client #%u identified as %s", e.clientId, deviceTypeStr.c_str());
|
||||
return CommandResult::ok("identify", "Device identified as " + deviceTypeStr);
|
||||
}
|
||||
|
||||
CommandResult SystemHandler::handleStatus(const CommandEnvelope& e) {
|
||||
PlayerStatus playerStatus = _player.getStatus();
|
||||
uint32_t timeElapsedMs = 0;
|
||||
uint64_t projectedRunTime = 0;
|
||||
|
||||
if (playerStatus == PlayerStatus::PLAYING ||
|
||||
playerStatus == PlayerStatus::PAUSED ||
|
||||
playerStatus == PlayerStatus::STOPPING) {
|
||||
timeElapsedMs = (uint32_t)(millis() - _player.startTime);
|
||||
}
|
||||
projectedRunTime = _player.calculateProjectedRunTime();
|
||||
|
||||
uint32_t strikeCounters[16] = {0};
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
strikeCounters[i] = _telemetry.getStrikeCount(i);
|
||||
}
|
||||
|
||||
// Delegate to ResponseBuilder which already handles this format
|
||||
// We build the result directly here to keep the handler self-contained
|
||||
JsonDocument doc;
|
||||
const char* statusStr = "STOPPED";
|
||||
switch (playerStatus) {
|
||||
case PlayerStatus::PLAYING: statusStr = "PLAYING"; break;
|
||||
case PlayerStatus::PAUSED: statusStr = "PAUSED"; break;
|
||||
case PlayerStatus::STOPPING: statusStr = "STOPPING"; break;
|
||||
default: break;
|
||||
}
|
||||
doc["player_status"] = statusStr;
|
||||
doc["time_elapsed_ms"] = timeElapsedMs;
|
||||
doc["projected_run_time"] = projectedRunTime;
|
||||
JsonObject strikes = doc["strike_counters"].to<JsonObject>();
|
||||
for (uint8_t i = 0; i < 16; i++) strikes[String(i)] = strikeCounters[i];
|
||||
|
||||
return CommandResult::ok("system.status", doc);
|
||||
}
|
||||
|
||||
CommandResult SystemHandler::handleGetTime(const CommandEnvelope& e) {
|
||||
unsigned long localTimestamp = _timeKeeper.getTime();
|
||||
const auto& timeConfig = _configManager.getTimeConfig();
|
||||
long totalOffset = timeConfig.gmtOffsetSec + timeConfig.daylightOffsetSec;
|
||||
unsigned long utcTimestamp = localTimestamp - totalOffset;
|
||||
|
||||
JsonDocument doc;
|
||||
doc["local_timestamp"] = localTimestamp;
|
||||
doc["utc_timestamp"] = utcTimestamp;
|
||||
doc["rtc_available"] = (localTimestamp > 0);
|
||||
|
||||
time_t rawTime = (time_t)localTimestamp;
|
||||
struct tm* ti = gmtime(&rawTime);
|
||||
doc["year"] = ti->tm_year + 1900;
|
||||
doc["month"] = ti->tm_mon + 1;
|
||||
doc["day"] = ti->tm_mday;
|
||||
doc["hour"] = ti->tm_hour;
|
||||
doc["minute"] = ti->tm_min;
|
||||
doc["second"] = ti->tm_sec;
|
||||
|
||||
return CommandResult::ok("system.get_time", doc);
|
||||
}
|
||||
|
||||
CommandResult SystemHandler::handleGetSettings(const CommandEnvelope& e) {
|
||||
String settingsJson = _configManager.getAllSettingsAsJson();
|
||||
JsonDocument doc;
|
||||
DeserializationError err = deserializeJson(doc, settingsJson);
|
||||
if (err) {
|
||||
LOG_ERROR(TAG, "Failed to parse settings JSON: %s", err.c_str());
|
||||
return CommandResult::err("system.get_settings", "Failed to serialize settings");
|
||||
}
|
||||
return CommandResult::ok("system.get_settings", doc);
|
||||
}
|
||||
|
||||
CommandResult SystemHandler::handleGetDeviceInfo(const CommandEnvelope& e) {
|
||||
JsonDocument doc;
|
||||
doc["uid"] = _configManager.getDeviceUID();
|
||||
doc["hw_type"] = _configManager.getHwType();
|
||||
doc["hw_version"] = _configManager.getHwVersion();
|
||||
doc["fw_version"] = _configManager.getFwVersion();
|
||||
doc["uptime_ms"] = millis();
|
||||
doc["free_heap"] = (uint32_t)ESP.getFreeHeap();
|
||||
doc["min_free_heap"] = (uint32_t)ESP.getMinFreeHeap();
|
||||
return CommandResult::ok("system.get_device_info", doc);
|
||||
}
|
||||
|
||||
CommandResult SystemHandler::handleHealth(const CommandEnvelope& e) {
|
||||
_healthMonitor.performFullHealthCheck();
|
||||
const auto& subsystems = _healthMonitor.getAllSubsystemHealth();
|
||||
|
||||
JsonDocument doc;
|
||||
doc["critical_count"] = _healthMonitor.getCriticalFailureCount();
|
||||
doc["warning_count"] = _healthMonitor.getWarningCount();
|
||||
doc["firmware_stable"] = _healthMonitor.isFirmwareStable();
|
||||
|
||||
JsonArray arr = doc["subsystems"].to<JsonArray>();
|
||||
for (const auto& pair : subsystems) {
|
||||
JsonObject obj = arr.add<JsonObject>();
|
||||
obj["name"] = pair.second.name;
|
||||
const char* s = "HEALTHY";
|
||||
switch (pair.second.status) {
|
||||
case HealthStatus::WARNING: s = "WARNING"; break;
|
||||
case HealthStatus::CRITICAL: s = "CRITICAL"; break;
|
||||
case HealthStatus::FAILED: s = "FAILED"; break;
|
||||
default: break;
|
||||
}
|
||||
obj["status"] = s;
|
||||
if (!pair.second.lastError.isEmpty()) obj["error"] = pair.second.lastError;
|
||||
}
|
||||
|
||||
return CommandResult::ok("system.health", doc);
|
||||
}
|
||||
|
||||
CommandResult SystemHandler::handleFactoryReset(const CommandEnvelope& e) {
|
||||
LOG_WARNING(TAG, "Factory reset requested");
|
||||
bool ok = _configManager.resetAllToDefaults();
|
||||
if (ok) {
|
||||
return CommandResult::ok("system.factory_reset",
|
||||
"Factory reset complete. Restart device to apply.");
|
||||
}
|
||||
return CommandResult::err("system.factory_reset",
|
||||
"Factory reset partially applied — some settings may not have saved");
|
||||
}
|
||||
|
||||
CommandResult SystemHandler::handleRestart(const CommandEnvelope& e) {
|
||||
LOG_WARNING(TAG, "Device restart requested via command");
|
||||
// Response is sent before restart via the reply lambda in the transport
|
||||
// We schedule the restart after a brief delay so the reply gets out first
|
||||
xTaskCreate([](void*) {
|
||||
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||
ESP.restart();
|
||||
}, "restartTask", 1024, nullptr, 1, nullptr);
|
||||
return CommandResult::ok("system.restart", "Device will restart in 2 seconds");
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include "../ICommandHandler.hpp"
|
||||
|
||||
class ConfigManager;
|
||||
class Player;
|
||||
class Telemetry;
|
||||
class HealthMonitor;
|
||||
class Timekeeper;
|
||||
class ClientManager;
|
||||
|
||||
class SystemHandler : public ICommandHandler {
|
||||
public:
|
||||
SystemHandler(ConfigManager& configManager, Player& player,
|
||||
Telemetry& telemetry, HealthMonitor& healthMonitor,
|
||||
Timekeeper& timeKeeper, ClientManager& clientManager);
|
||||
|
||||
std::vector<String> commands() const override;
|
||||
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||
|
||||
private:
|
||||
ConfigManager& _configManager;
|
||||
Player& _player;
|
||||
Telemetry& _telemetry;
|
||||
HealthMonitor& _healthMonitor;
|
||||
Timekeeper& _timeKeeper;
|
||||
ClientManager& _clientManager;
|
||||
|
||||
CommandResult handlePing(const CommandEnvelope& e);
|
||||
CommandResult handleIdentify(const CommandEnvelope& e);
|
||||
CommandResult handleStatus(const CommandEnvelope& e);
|
||||
CommandResult handleGetTime(const CommandEnvelope& e);
|
||||
CommandResult handleGetSettings(const CommandEnvelope& e);
|
||||
CommandResult handleGetDeviceInfo(const CommandEnvelope& e);
|
||||
CommandResult handleHealth(const CommandEnvelope& e);
|
||||
CommandResult handleFactoryReset(const CommandEnvelope& e);
|
||||
CommandResult handleRestart(const CommandEnvelope& e);
|
||||
};
|
||||
Reference in New Issue
Block a user