Files
project-vesper/src/Communication/Handlers/SystemHandler/SystemHandler.cpp
T
bonaminandClaude Sonnet 5 64a8bc2b88 feat(SystemHandler,ConfigManager): add system.set_identity sysadmin command (F-060)
Device identity (serial/hw_family/hw_revision) has been read-only from
production firmware since NVS provisioning — serial derives the MQTT
password and hw_family/hw_revision select the OTA channel, so an
uncontrolled write path could desync MQTT auth or brick OTA to the
wrong hardware. This adds one narrow, deliberate exception: an
MQTT-only system.set_identity command for correcting a
mis-provisioned unit or reassigning a serial after a board swap,
without a USB/serial reflash.

Rejected over WebSocket/HTTP/UART by design (same pattern as
identify's WebSocket-only check); requires all three fields together
to avoid partial-identity states; forces a reboot after a successful
write since MQTT credentials/hostname/AP SSID are derived from serial
only once at boot. Firmware does not update the backend device record
itself — that's the caller's (console's) responsibility in the same
operation.

Also includes docs/README.md's rule 6 (console API reference sync
requirement) from an earlier uncommitted session, which this change
follows.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-20 20:09:39 +03:00

362 lines
16 KiB
C++

#if HAS_RTC
#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_config", // replaces system.get_settings (kept as alias below)
"system.get_settings", // backward-compat alias — routes to handleGetConfig
"system.get_device_info", "system.health",
"system.get_all", "system.get_telemetry",
"system.factory_reset", "system.restart",
"system.set_identity"
};
}
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_config" ||
envelope.command == "system.get_settings") return handleGetConfig(envelope);
if (envelope.command == "system.get_device_info") return handleGetDeviceInfo(envelope);
if (envelope.command == "system.health") return handleHealth(envelope);
if (envelope.command == "system.get_all") return handleGetAll(envelope);
if (envelope.command == "system.get_telemetry") return handleGetTelemetry(envelope);
if (envelope.command == "system.factory_reset") return handleFactoryReset(envelope);
if (envelope.command == "system.restart") return handleRestart(envelope);
if (envelope.command == "system.set_identity") return handleSetIdentity(envelope);
return CommandResult::err(envelope.command, "Unknown system command");
}
// ---------------------------------------------------------------------------
CommandResult SystemHandler::handlePing(const CommandEnvelope& e) {
JsonDocument doc;
doc["type"] = "pong";
// Echo caller's timestamp back unchanged so the caller can compute RTT
// as (time_received - contents.ts) without needing symmetric clocks.
// uint64_t: epoch-millis (e.g. 1752600000123) overflows uint32_t.
if (e.contents["ts"].is<uint64_t>()) {
doc["ts"] = e.contents["ts"];
}
doc["device_uptime_ms"] = millis();
return CommandResult::ok("pong", doc);
}
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::handleGetConfig(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_config", "Failed to serialize settings");
}
// Add bells_enabled which is not in getAllSettingsAsJson yet
doc["general"]["bells_enabled"] = _configManager.getBellsEnabled();
doc["general"]["mqtt_enabled"] = _configManager.getMqttEnabled();
doc["general"]["ota_channel"] = _configManager.getOtaChannel();
doc["general"]["serial_log"] = _configManager.getSerialLogLevel();
doc["general"]["sd_log"] = _configManager.getSdLogLevel();
doc["general"]["mqtt_log"] = _configManager.getMqttLogLevel();
return CommandResult::ok("system.get_config", doc);
}
CommandResult SystemHandler::handleGetTelemetry(const CommandEnvelope& e) {
JsonDocument doc;
// Strike counters
JsonObject strikes = doc["strikes"].to<JsonObject>();
for (uint8_t i = 0; i < 16; i++) strikes[String(i)] = _telemetry.getStrikeCount(i);
// Bell loads
JsonObject loads = doc["loads"].to<JsonObject>();
JsonObject maxLoads = doc["max_loads"].to<JsonObject>();
for (uint8_t i = 0; i < 16; i++) {
loads[String(i)] = _telemetry.getBellLoad(i);
maxLoads[String(i)] = _telemetry.getBellMaxLoad(i);
}
doc["cooling_active"] = _telemetry.isCoolingActive();
doc["guard_enabled"] = _telemetry.isGuardEnabled();
// Runtime metrics
doc["lifetime_runtime_seconds"] = _telemetry.getLifetimeRuntimeSeconds();
doc["session_runtime_seconds"] = _telemetry.getCurrentSessionSeconds();
doc["total_playbacks"] = _telemetry.getTotalPlaybackCount();
doc["lifetime_boot_count"] = _telemetry.getLifetimeBootCount();
// Device uptime
doc["uptime_ms"] = millis();
doc["free_heap"] = (uint32_t)ESP.getFreeHeap();
return CommandResult::ok("system.get_telemetry", doc);
}
CommandResult SystemHandler::handleGetAll(const CommandEnvelope& e) {
JsonDocument doc;
// ── Device identity ────────────────────────────────────────────────────
JsonObject device = doc["device"].to<JsonObject>();
device["serial"] = _configManager.getSerial();
device["hw_family"] = _configManager.getHwFamily();
device["hw_revision"] = _configManager.getHwRevision();
device["fw_version"] = _configManager.getFwVersion();
device["uptime_ms"] = millis();
device["free_heap"] = (uint32_t)ESP.getFreeHeap();
// ── Full config (reuse getAllSettingsAsJson) ────────────────────────────
{
String settingsJson = _configManager.getAllSettingsAsJson();
JsonDocument cfg;
if (!deserializeJson(cfg, settingsJson)) {
doc["config"] = cfg;
}
}
doc["config"]["general"]["bells_enabled"] = _configManager.getBellsEnabled();
doc["config"]["general"]["mqtt_enabled"] = _configManager.getMqttEnabled();
doc["config"]["general"]["ota_channel"] = _configManager.getOtaChannel();
doc["config"]["general"]["serial_log"] = _configManager.getSerialLogLevel();
doc["config"]["general"]["sd_log"] = _configManager.getSdLogLevel();
doc["config"]["general"]["mqtt_log"] = _configManager.getMqttLogLevel();
// ── Telemetry snapshot ─────────────────────────────────────────────────
JsonObject telemetry = doc["telemetry"].to<JsonObject>();
JsonObject strikes = telemetry["strikes"].to<JsonObject>();
JsonObject loads = telemetry["loads"].to<JsonObject>();
JsonObject maxLoads = telemetry["max_loads"].to<JsonObject>();
for (uint8_t i = 0; i < 16; i++) {
strikes[String(i)] = _telemetry.getStrikeCount(i);
loads[String(i)] = _telemetry.getBellLoad(i);
maxLoads[String(i)] = _telemetry.getBellMaxLoad(i);
}
telemetry["cooling_active"] = _telemetry.isCoolingActive();
telemetry["guard_enabled"] = _telemetry.isGuardEnabled();
telemetry["lifetime_runtime_seconds"] = _telemetry.getLifetimeRuntimeSeconds();
telemetry["session_runtime_seconds"] = _telemetry.getCurrentSessionSeconds();
telemetry["total_playbacks"] = _telemetry.getTotalPlaybackCount();
telemetry["lifetime_boot_count"] = _telemetry.getLifetimeBootCount();
// ── Player status ──────────────────────────────────────────────────────
JsonObject player = doc["player"].to<JsonObject>();
PlayerStatus ps = _player.getStatus();
const char* psStr = "STOPPED";
switch (ps) {
case PlayerStatus::PLAYING: psStr = "PLAYING"; break;
case PlayerStatus::PAUSED: psStr = "PAUSED"; break;
case PlayerStatus::STOPPING: psStr = "STOPPING"; break;
default: break;
}
player["status"] = psStr;
return CommandResult::ok("system.get_all", 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");
}
CommandResult SystemHandler::handleSetIdentity(const CommandEnvelope& e) {
// Sysadmin-only override of factory-set device identity. Restricted to MQTT so it can
// only be triggered from the backend/console, which is expected to update its own
// device record (and re-derive the MQTT password from the new serial) in lockstep —
// see ConfigManager::saveDeviceIdentityToNVS() for the full rationale.
if (e.transport != CommandEnvelope::Transport::MQTT) {
return CommandResult::err("system.set_identity", "system.set_identity is only available via MQTT");
}
if (!e.contents["serial"].is<const char*>() ||
!e.contents["hw_family"].is<const char*>() ||
!e.contents["hw_revision"].is<const char*>()) {
return CommandResult::err("system.set_identity",
"Missing required fields: serial, hw_family, hw_revision (all required)");
}
String serial = e.contents["serial"].as<String>();
String hwFamily = e.contents["hw_family"].as<String>();
String hwRevision = e.contents["hw_revision"].as<String>();
if (serial.isEmpty() || hwFamily.isEmpty() || hwRevision.isEmpty()) {
return CommandResult::err("system.set_identity",
"serial, hw_family and hw_revision must be non-empty");
}
LOG_WARNING(TAG, "Device identity override requested via MQTT command");
bool ok = _configManager.saveDeviceIdentityToNVS(serial, hwFamily, hwRevision);
if (!ok) {
return CommandResult::err("system.set_identity",
"Failed to persist new identity to NVS — device identity unchanged");
}
// MQTT credentials, hostname and AP SSID were derived from the OLD serial at boot
// and won't recompute without a restart, so force one after the reply goes out.
xTaskCreate([](void*) {
vTaskDelay(pdMS_TO_TICKS(2000));
ESP.restart();
}, "setIdentityRebootTask", 1024, nullptr, 1, nullptr);
return CommandResult::ok("system.set_identity",
"Device identity updated. Restarting in 2 seconds to apply.");
}
#endif // HAS_RTC