Requested by the console-side agent building a device Health tab (RSSI, ping latency, free heap, restart timeline graphs). Both changes are additive and backward-compatible. publishHeartbeat() now includes free_heap (ESP.getFreeHeap()) on the existing 30s heartbeat, alongside rssi — previously free heap was only visible once per boot via boot_report, a single point rather than a trend. handlePing() previously built a JsonDocument and never used it — ping was a pure ack. It now echoes back an optional caller-supplied "ts" (epoch-millis) unchanged, plus device_uptime_ms, so the caller can compute round-trip latency as (time of receipt) - ts without needing synchronized clocks. ts is optional on both request and response, so existing callers doing a plain liveness check are unaffected. Left the existing #if HAS_RTC scoping on SystemHandler.cpp untouched, per the request — ping remains RTC-variant-only. Verified: pio run on vesper-std-v1 and agnus-v1 (confirms the HAS_RTC scoping around SystemHandler.cpp wasn't disturbed). Documented in feature-catalog.md F-054, MQTTDriver/README.md, and Communication/Handlers/README.md. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
317 lines
14 KiB
C++
317 lines
14 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"
|
|
};
|
|
}
|
|
|
|
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);
|
|
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");
|
|
}
|
|
|
|
#endif // HAS_RTC
|