feat(comms): bidirectional device control — bells master switch, guard toggle, runtime tracking, system aggregate commands
Adds full bidirectional remote control across all major subsystems, establishing the device as the single source of truth for all settings. New firmware features (F-029 to F-037): - bells.enable / bells.disable: master ON/OFF for all playback and clock alerts (relay.test_output intentionally unaffected) - telemetry.set_guard_enabled: enable/disable thermal protection at runtime without touching thresholds - telemetry.set_max_loads: set bellMaxLoad per-bell or globally via command - Device runtime tracking: lifetime seconds flushed to SD every 10 min, boot log (up to 200 entries, rotating) written after first NTP sync - Total playback counter persisted to SD, increments on every play() - telemetry.get_metrics / telemetry.reset_metrics: new aggregate read + reset - system.get_config (replaces system.get_settings, old name still accepted), system.get_all (everything in one call), system.get_telemetry - log.get_config, mqtt.get_config, bells.get_config: new getters for previously write-only subsystems - network.status now includes ssid, mac, hostname - BellsHandler: new handler registered on CommandBus - LegacyAdapter updated with all new command mappings Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -38,6 +38,15 @@ Every feature — user-facing or significant internal mechanism — is listed he
|
||||
| F-026 | V2 playback `mode` field (`single` / `timed` / `interval` / `infinite`) | v2.0.4 | Stable |
|
||||
| F-027 | FileManager HTTPS removed — melody downloads over plain HTTP only | v2.0.4 | Stable |
|
||||
| F-028 | Logging level calibration — sane defaults + per-subsystem MQTT caps | v2.0.5 | Stable |
|
||||
| F-029 | Bell mechanism master ON/OFF switch (`bells.enable` / `bells.disable`) | v2.1.0 | Stable |
|
||||
| F-030 | Bell load guard ON/OFF switch (`telemetry.set_guard_enabled`) | v2.1.0 | Stable |
|
||||
| F-031 | Bell load guard threshold control per-bell (`telemetry.set_max_loads`) | v2.1.0 | Stable |
|
||||
| F-032 | Device runtime + boot tracking (SD-persisted, 10-min flush, boot log) | v2.1.0 | Stable |
|
||||
| F-033 | Total playback counter (SD-persisted lifetime count) | v2.1.0 | Stable |
|
||||
| F-034 | Telemetry aggregate commands (`telemetry.get_metrics`, `telemetry.reset_metrics`) | v2.1.0 | Stable |
|
||||
| F-035 | System aggregate commands (`system.get_config`, `system.get_all`, `system.get_telemetry`) | v2.1.0 | Stable |
|
||||
| F-036 | Per-subsystem config getters (`log.get_config`, `mqtt.get_config`, `bells.get_config`) | v2.1.0 | Stable |
|
||||
| F-037 | Network status extended (SSID + MAC in `network.status`) | v2.1.0 | Stable |
|
||||
|
||||
---
|
||||
|
||||
@@ -366,3 +375,120 @@ Subsystem: `src/ConfigManager/ConfigManager.hpp`, `src/Communication/Communicati
|
||||
`bellMaxLoad[i]` initialised to `500` (was `200`). This is the denominator used to calculate bell load percentage in telemetry reports. The old value caused false "overload" warnings on normal use patterns.
|
||||
|
||||
Subsystem: `src/Telemetry/Telemetry.cpp:begin()`
|
||||
|
||||
---
|
||||
|
||||
### F-029 — Bell mechanism master ON/OFF switch
|
||||
|
||||
A new `bellsEnabled` boolean in `GeneralConfig` (default `true`) gates all bell firing at the mechanism level. When disabled:
|
||||
- `BellEngine::start()` returns immediately without activating any relay outputs.
|
||||
- `Timekeeper::checkClockAlerts()` returns immediately without firing hour/half/quarter bells.
|
||||
- Manual relay tests (`relay.test_output`) are **not** affected — the guard is at the playback/alert layer, not the hardware layer.
|
||||
|
||||
Persisted to `settings/generalConfig.json` via `saveGeneralConfig()`.
|
||||
|
||||
Commands: `bells.enable` / `bells.disable` / `bells.get_config`
|
||||
Subsystems: `src/ConfigManager/ConfigManager.hpp`, `src/BellEngine/BellEngine.cpp`, `src/TimeKeeper/TimeKeeper.cpp`, `src/Communication/Handlers/BellsHandler/`
|
||||
|
||||
---
|
||||
|
||||
### F-030 — Bell load guard ON/OFF switch
|
||||
|
||||
`Telemetry::guardEnabled` (default `true`) allows the thermal protection system to be disabled at runtime via command without touching the thresholds. When disabled, load decay still runs for accurate reporting, but `forceStopCallback` is never triggered regardless of load levels.
|
||||
|
||||
Command: `telemetry.set_guard_enabled` `{ "enabled": true|false }`
|
||||
Not persisted — resets to `true` on reboot (deliberate: guard is a safety feature).
|
||||
Subsystem: `src/Telemetry/Telemetry.hpp`, `src/Telemetry/Telemetry.cpp`
|
||||
|
||||
---
|
||||
|
||||
### F-031 — Bell load guard threshold control
|
||||
|
||||
`telemetry.set_max_loads` allows setting `bellMaxLoad[i]` per-bell or globally via command at runtime. Two forms:
|
||||
- `{ "all": 500 }` — sets all 16 bells to the same threshold.
|
||||
- `{ "loads": { "0": 300, "3": 700 } }` — sets specific bells individually.
|
||||
|
||||
`telemetry.get_loads` now also returns `max_loads` and `guard_enabled` alongside the existing `loads`, `cooling_active`, `overloaded` fields.
|
||||
|
||||
Subsystem: `src/Telemetry/Telemetry.cpp`, `src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp`
|
||||
|
||||
---
|
||||
|
||||
### F-032 — Device runtime and boot tracking
|
||||
|
||||
Three types of persistent records written to SD:
|
||||
|
||||
**Runtime (`/telemetry_runtime.json`):**
|
||||
- `lifetime_seconds`: cumulative powered-on time across all boots. Loaded at boot, flushed every 10 minutes. If the device reboots before 10 minutes, that session's contribution is lost (accepted trade-off to avoid SD wear).
|
||||
|
||||
**Boot log (`/telemetry_boot_log.json`):**
|
||||
- Rotating array of up to 200 boot entries, each with `ts` (Unix timestamp) and `boot` (sequential boot count).
|
||||
- Written after first NTP sync so the timestamp is real. Offline boots without NTP produce no entry.
|
||||
- Useful for diagnosing crash/reboot loops: a device that rebooted 25 times on one day is instantly visible.
|
||||
|
||||
Runtime flush is done inside `TelemetryTask` on a 10-minute timer (`RUNTIME_FLUSH_INTERVAL_MS`). Boot log is written from `ntpSyncTask` in `main.cpp`.
|
||||
|
||||
Subsystem: `src/Telemetry/Telemetry.hpp`, `src/Telemetry/Telemetry.cpp`, `src/main.cpp`
|
||||
|
||||
---
|
||||
|
||||
### F-033 — Total playback counter
|
||||
|
||||
`Telemetry::totalPlaybackCount` (uint32_t) increments on every call to `Player::play()`. Persisted in `telemetry_runtime.json` alongside lifetime runtime. Readable via `telemetry.get_metrics` and `system.get_telemetry`. Resettable via `telemetry.reset_metrics` (also resets lifetime runtime).
|
||||
|
||||
Subsystem: `src/Telemetry/Telemetry.cpp`, `src/Player/Player.cpp`
|
||||
|
||||
---
|
||||
|
||||
### F-034 — Telemetry aggregate commands
|
||||
|
||||
New commands added to `TelemetryHandler`:
|
||||
|
||||
| Command | Description |
|
||||
|---|---|
|
||||
| `telemetry.get_metrics` | Returns `lifetime_runtime_seconds`, `session_runtime_seconds`, `total_playbacks`, `guard_enabled` |
|
||||
| `telemetry.reset_metrics` | Resets lifetime runtime and playback count to zero (persisted) |
|
||||
|
||||
Subsystem: `src/Communication/Handlers/TelemetryHandler/`
|
||||
|
||||
---
|
||||
|
||||
### F-035 — System aggregate commands
|
||||
|
||||
`system.get_settings` renamed to `system.get_config` (old name still accepted as backward-compat alias). Two new aggregate commands:
|
||||
|
||||
| Command | Returns |
|
||||
|---|---|
|
||||
| `system.get_config` | All user-configurable settings (full config dump) + `general` block with `bells_enabled`, `mqtt_enabled`, `ota_channel`, log levels |
|
||||
| `system.get_telemetry` | Strike counters, loads, max_loads, cooling, guard, runtime metrics, uptime, free heap — all in one call |
|
||||
| `system.get_all` | Everything: device identity + full config + telemetry snapshot + player status |
|
||||
|
||||
Reduces initialization round-trips from 8+ commands to 1.
|
||||
|
||||
Subsystem: `src/Communication/Handlers/SystemHandler/SystemHandler.cpp`
|
||||
|
||||
---
|
||||
|
||||
### F-036 — Per-subsystem config getters
|
||||
|
||||
Three new getter commands that were previously write-only:
|
||||
|
||||
| Command | Returns |
|
||||
|---|---|
|
||||
| `log.get_config` | `serial_level`, `sd_level`, `mqtt_level` |
|
||||
| `mqtt.get_config` | `enabled`, `host`, `port`, `user`, `use_ssl` |
|
||||
| `bells.get_config` | `bells_enabled`, `durations[16]`, `outputs[16]` |
|
||||
|
||||
Subsystem: `src/Communication/Handlers/LoggingHandler/`, `src/Communication/Handlers/MQTTHandler/`, `src/Communication/Handlers/BellsHandler/`
|
||||
|
||||
---
|
||||
|
||||
### F-037 — Network status extended
|
||||
|
||||
`network.status` now returns three additional fields alongside the existing `connected`, `ip`, `ap_mode`, `rssi`, `state`, `type`:
|
||||
|
||||
- `ssid`: currently connected WiFi network name (`WiFi.SSID()`)
|
||||
- `mac`: device MAC address (`WiFi.macAddress()`)
|
||||
- `hostname`: device hostname from `NetworkConfig`
|
||||
|
||||
Subsystem: `src/Communication/Handlers/NetworkHandler/NetworkHandler.cpp`
|
||||
|
||||
@@ -116,15 +116,18 @@ void BellEngine::setCommunicationManager(CommunicationRouter* commManager) {
|
||||
* @note Will log error and return if no melody data is available
|
||||
*/
|
||||
void BellEngine::start() {
|
||||
// Validate that melody data is ready before starting
|
||||
if (!_configManager.getBellsEnabled()) {
|
||||
LOG_WARNING(TAG, "BellEngine: start() rejected — bell mechanism is disabled");
|
||||
return;
|
||||
}
|
||||
if (!_melodyDataReady.load()) {
|
||||
LOG_ERROR(TAG, "Cannot start BellEngine: No melody data loaded");
|
||||
return; // ⛔ Early exit if no melody data
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "🚀 BellEngine Ignition - Starting precision playback");
|
||||
_emergencyStop.store(false); // ✅ Clear any emergency stop state
|
||||
_engineRunning.store(true); // ✅ Activate the engine atomically
|
||||
_emergencyStop.store(false);
|
||||
_engineRunning.store(true);
|
||||
}
|
||||
|
||||
void BellEngine::stop() {
|
||||
|
||||
@@ -45,10 +45,17 @@ static const ActionEntry ACTION_MAP[] = {
|
||||
{ "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", "get_full_settings", "system.get_config" },
|
||||
{ "system_info", "get_all_settings", "system.get_all" },
|
||||
{ "system_info", "get_telemetry", "system.get_telemetry" },
|
||||
// sync_time_to_lcd retired — LCD now uses request/response model
|
||||
{ "system_info", "sync_time_to_lcd", "system.get_time" },
|
||||
|
||||
// bells
|
||||
{ "bells", "enable", "bells.enable" },
|
||||
{ "bells", "disable", "bells.disable" },
|
||||
{ "bells", "get_config", "bells.get_config" },
|
||||
|
||||
// system
|
||||
{ "system", "status", "system.status" },
|
||||
{ "system", "reset_defaults", "system.factory_reset" },
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
#include "../Handlers/LoggingHandler/LoggingHandler.hpp"
|
||||
#include "../Handlers/TelemetryHandler/TelemetryHandler.hpp"
|
||||
#include "../Handlers/MQTTHandler/MQTTHandler.hpp"
|
||||
#include "../Handlers/BellsHandler/BellsHandler.hpp"
|
||||
#if HAS_RF
|
||||
#include "../../RFRemote/RFRemoteHandler.hpp"
|
||||
#endif
|
||||
@@ -288,9 +289,12 @@ void CommunicationRouter::registerHandlers() {
|
||||
_bus.registerHandler(std::make_unique<TelemetryHandler>(*_telemetry));
|
||||
}
|
||||
|
||||
// MQTT control (enable / disable)
|
||||
// MQTT control (enable / disable / get_config)
|
||||
_bus.registerHandler(std::make_unique<MQTTHandler>(_configManager, _mqttClient));
|
||||
|
||||
// Bell mechanism master switch
|
||||
_bus.registerHandler(std::make_unique<BellsHandler>(_configManager));
|
||||
|
||||
#if HAS_RF
|
||||
// RF remote control
|
||||
if (_rfRemote) {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
#include "BellsHandler.hpp"
|
||||
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||
#include "../../../Logging/Logging.hpp"
|
||||
|
||||
#define TAG "BellsHandler"
|
||||
|
||||
BellsHandler::BellsHandler(ConfigManager& configManager)
|
||||
: _configManager(configManager) {}
|
||||
|
||||
std::vector<String> BellsHandler::commands() const {
|
||||
return { "bells.enable", "bells.disable", "bells.get_config" };
|
||||
}
|
||||
|
||||
CommandResult BellsHandler::execute(const CommandEnvelope& envelope) {
|
||||
if (envelope.command == "bells.enable") return handleEnable(envelope);
|
||||
if (envelope.command == "bells.disable") return handleDisable(envelope);
|
||||
if (envelope.command == "bells.get_config") return handleGetConfig(envelope);
|
||||
return CommandResult::err(envelope.command, "Unknown bells command");
|
||||
}
|
||||
|
||||
CommandResult BellsHandler::handleEnable(const CommandEnvelope& e) {
|
||||
_configManager.setBellsEnabled(true);
|
||||
if (!_configManager.saveGeneralConfig()) {
|
||||
return CommandResult::err("bells.enable", "Bell mechanism enabled but failed to save to SD");
|
||||
}
|
||||
LOG_WARNING(TAG, "Bell mechanism enabled by command");
|
||||
return CommandResult::ok("bells.enable", "Bell mechanism enabled and saved");
|
||||
}
|
||||
|
||||
CommandResult BellsHandler::handleDisable(const CommandEnvelope& e) {
|
||||
_configManager.setBellsEnabled(false);
|
||||
if (!_configManager.saveGeneralConfig()) {
|
||||
return CommandResult::err("bells.disable", "Bell mechanism disabled but failed to save to SD");
|
||||
}
|
||||
LOG_WARNING(TAG, "Bell mechanism disabled by command");
|
||||
return CommandResult::ok("bells.disable", "Bell mechanism disabled and saved");
|
||||
}
|
||||
|
||||
CommandResult BellsHandler::handleGetConfig(const CommandEnvelope& e) {
|
||||
const auto& bellConfig = _configManager.getBellConfig();
|
||||
JsonDocument doc;
|
||||
doc["bells_enabled"] = _configManager.getBellsEnabled();
|
||||
|
||||
JsonObject durations = doc["durations"].to<JsonObject>();
|
||||
JsonObject outputs = doc["outputs"].to<JsonObject>();
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
durations[String(i)] = bellConfig.durations[i];
|
||||
outputs[String(i)] = bellConfig.outputs[i];
|
||||
}
|
||||
return CommandResult::ok("bells.get_config", doc);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include "../ICommandHandler.hpp"
|
||||
|
||||
class ConfigManager;
|
||||
|
||||
class BellsHandler : public ICommandHandler {
|
||||
public:
|
||||
explicit BellsHandler(ConfigManager& configManager);
|
||||
|
||||
std::vector<String> commands() const override;
|
||||
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||
|
||||
private:
|
||||
ConfigManager& _configManager;
|
||||
|
||||
CommandResult handleEnable(const CommandEnvelope& e);
|
||||
CommandResult handleDisable(const CommandEnvelope& e);
|
||||
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||
};
|
||||
@@ -8,13 +8,14 @@ LoggingHandler::LoggingHandler(ConfigManager& configManager)
|
||||
: _configManager(configManager) {}
|
||||
|
||||
std::vector<String> LoggingHandler::commands() const {
|
||||
return { "log.set_serial", "log.set_sd", "log.set_mqtt" };
|
||||
return { "log.set_serial", "log.set_sd", "log.set_mqtt", "log.get_config" };
|
||||
}
|
||||
|
||||
CommandResult LoggingHandler::execute(const CommandEnvelope& envelope) {
|
||||
if (envelope.command == "log.set_serial") return handleSetLevel(envelope, "serial");
|
||||
if (envelope.command == "log.set_sd") return handleSetLevel(envelope, "sd");
|
||||
if (envelope.command == "log.set_mqtt") return handleSetLevel(envelope, "mqtt");
|
||||
if (envelope.command == "log.get_config") return handleGetConfig(envelope);
|
||||
return CommandResult::err(envelope.command, "Unknown log command");
|
||||
}
|
||||
|
||||
@@ -51,3 +52,11 @@ CommandResult LoggingHandler::handleSetLevel(const CommandEnvelope& e, const Str
|
||||
return CommandResult::ok("log.set_" + channel,
|
||||
channel + " log level set to " + String(level) + " and saved");
|
||||
}
|
||||
|
||||
CommandResult LoggingHandler::handleGetConfig(const CommandEnvelope& e) {
|
||||
JsonDocument doc;
|
||||
doc["serial_level"] = _configManager.getSerialLogLevel();
|
||||
doc["sd_level"] = _configManager.getSdLogLevel();
|
||||
doc["mqtt_level"] = _configManager.getMqttLogLevel();
|
||||
return CommandResult::ok("log.get_config", doc);
|
||||
}
|
||||
|
||||
@@ -16,4 +16,5 @@ private:
|
||||
ConfigManager& _configManager;
|
||||
|
||||
CommandResult handleSetLevel(const CommandEnvelope& e, const String& channel);
|
||||
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||
};
|
||||
|
||||
@@ -9,10 +9,12 @@ MQTTHandler::MQTTHandler(ConfigManager& configManager, MQTTDriver& mqttClient)
|
||||
: _configManager(configManager), _mqttClient(mqttClient) {}
|
||||
|
||||
std::vector<String> MQTTHandler::commands() const {
|
||||
return { "mqtt.enable", "mqtt.disable" };
|
||||
return { "mqtt.enable", "mqtt.disable", "mqtt.get_config" };
|
||||
}
|
||||
|
||||
CommandResult MQTTHandler::execute(const CommandEnvelope& envelope) {
|
||||
if (envelope.command == "mqtt.get_config") return handleGetConfig(envelope);
|
||||
|
||||
bool enable = (envelope.command == "mqtt.enable");
|
||||
|
||||
_configManager.setMqttEnabled(enable);
|
||||
@@ -31,3 +33,14 @@ CommandResult MQTTHandler::execute(const CommandEnvelope& envelope) {
|
||||
return CommandResult::ok(envelope.command,
|
||||
String("MQTT ") + (enable ? "enabled" : "disabled") + " and saved");
|
||||
}
|
||||
|
||||
CommandResult MQTTHandler::handleGetConfig(const CommandEnvelope& e) {
|
||||
const auto& mqttCfg = _configManager.getMqttConfig();
|
||||
JsonDocument doc;
|
||||
doc["enabled"] = _configManager.getMqttEnabled();
|
||||
doc["host"] = mqttCfg.host.toString();
|
||||
doc["port"] = mqttCfg.port;
|
||||
doc["user"] = mqttCfg.user;
|
||||
doc["use_ssl"] = mqttCfg.useSSL;
|
||||
return CommandResult::ok("mqtt.get_config", doc);
|
||||
}
|
||||
|
||||
@@ -18,4 +18,6 @@ public:
|
||||
private:
|
||||
ConfigManager& _configManager;
|
||||
MQTTDriver& _mqttClient;
|
||||
|
||||
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||
};
|
||||
|
||||
@@ -34,6 +34,9 @@ CommandResult NetworkHandler::handleStatus(const CommandEnvelope& e) {
|
||||
doc["ip"] = _networking.getLocalIP();
|
||||
doc["ap_mode"] = _networking.isInAPMode();
|
||||
doc["rssi"] = WiFi.RSSI();
|
||||
doc["ssid"] = WiFi.SSID();
|
||||
doc["mac"] = WiFi.macAddress();
|
||||
doc["hostname"] = _configManager.getNetworkConfig().hostname;
|
||||
|
||||
const char* stateStr = "UNKNOWN";
|
||||
switch (_networking.getState()) {
|
||||
|
||||
@@ -24,22 +24,28 @@ SystemHandler::SystemHandler(ConfigManager& configManager, Player& player,
|
||||
std::vector<String> SystemHandler::commands() const {
|
||||
return {
|
||||
"ping", "identify",
|
||||
"system.status", "system.get_time", "system.get_settings",
|
||||
"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_settings") return handleGetSettings(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.factory_reset") return handleFactoryReset(envelope);
|
||||
if (envelope.command == "system.restart") return handleRestart(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");
|
||||
}
|
||||
|
||||
@@ -132,15 +138,109 @@ CommandResult SystemHandler::handleGetTime(const CommandEnvelope& e) {
|
||||
return CommandResult::ok("system.get_time", doc);
|
||||
}
|
||||
|
||||
CommandResult SystemHandler::handleGetSettings(const CommandEnvelope& e) {
|
||||
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_settings", "Failed to serialize settings");
|
||||
return CommandResult::err("system.get_config", "Failed to serialize settings");
|
||||
}
|
||||
return CommandResult::ok("system.get_settings", doc);
|
||||
// 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();
|
||||
|
||||
// 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();
|
||||
|
||||
// ── 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) {
|
||||
|
||||
@@ -33,9 +33,11 @@ private:
|
||||
CommandResult handleIdentify(const CommandEnvelope& e);
|
||||
CommandResult handleStatus(const CommandEnvelope& e);
|
||||
CommandResult handleGetTime(const CommandEnvelope& e);
|
||||
CommandResult handleGetSettings(const CommandEnvelope& e);
|
||||
CommandResult handleGetConfig(const CommandEnvelope& e);
|
||||
CommandResult handleGetDeviceInfo(const CommandEnvelope& e);
|
||||
CommandResult handleHealth(const CommandEnvelope& e);
|
||||
CommandResult handleGetAll(const CommandEnvelope& e);
|
||||
CommandResult handleGetTelemetry(const CommandEnvelope& e);
|
||||
CommandResult handleFactoryReset(const CommandEnvelope& e);
|
||||
CommandResult handleRestart(const CommandEnvelope& e);
|
||||
};
|
||||
|
||||
@@ -7,13 +7,21 @@
|
||||
TelemetryHandler::TelemetryHandler(Telemetry& telemetry) : _telemetry(telemetry) {}
|
||||
|
||||
std::vector<String> TelemetryHandler::commands() const {
|
||||
return { "telemetry.get_strikes", "telemetry.reset_strikes", "telemetry.get_loads" };
|
||||
return {
|
||||
"telemetry.get_strikes", "telemetry.reset_strikes", "telemetry.get_loads",
|
||||
"telemetry.set_max_loads", "telemetry.set_guard_enabled",
|
||||
"telemetry.get_metrics", "telemetry.reset_metrics"
|
||||
};
|
||||
}
|
||||
|
||||
CommandResult TelemetryHandler::execute(const CommandEnvelope& envelope) {
|
||||
if (envelope.command == "telemetry.get_strikes") return handleGetStrikes(envelope);
|
||||
if (envelope.command == "telemetry.reset_strikes") return handleResetStrikes(envelope);
|
||||
if (envelope.command == "telemetry.get_loads") return handleGetLoads(envelope);
|
||||
if (envelope.command == "telemetry.get_strikes") return handleGetStrikes(envelope);
|
||||
if (envelope.command == "telemetry.reset_strikes") return handleResetStrikes(envelope);
|
||||
if (envelope.command == "telemetry.get_loads") return handleGetLoads(envelope);
|
||||
if (envelope.command == "telemetry.set_max_loads") return handleSetMaxLoads(envelope);
|
||||
if (envelope.command == "telemetry.set_guard_enabled") return handleSetGuardEnabled(envelope);
|
||||
if (envelope.command == "telemetry.get_metrics") return handleGetMetrics(envelope);
|
||||
if (envelope.command == "telemetry.reset_metrics") return handleResetMetrics(envelope);
|
||||
return CommandResult::err(envelope.command, "Unknown telemetry command");
|
||||
}
|
||||
|
||||
@@ -36,11 +44,14 @@ CommandResult TelemetryHandler::handleResetStrikes(const CommandEnvelope& e) {
|
||||
|
||||
CommandResult TelemetryHandler::handleGetLoads(const CommandEnvelope& e) {
|
||||
JsonDocument doc;
|
||||
JsonObject loads = doc["loads"].to<JsonObject>();
|
||||
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);
|
||||
loads[String(i)] = _telemetry.getBellLoad(i);
|
||||
maxLoads[String(i)] = _telemetry.getBellMaxLoad(i);
|
||||
}
|
||||
doc["cooling_active"] = _telemetry.isCoolingActive();
|
||||
doc["guard_enabled"] = _telemetry.isGuardEnabled();
|
||||
|
||||
JsonArray overloaded = doc["overloaded"].to<JsonArray>();
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
@@ -49,3 +60,50 @@ CommandResult TelemetryHandler::handleGetLoads(const CommandEnvelope& e) {
|
||||
|
||||
return CommandResult::ok("telemetry.get_loads", doc);
|
||||
}
|
||||
|
||||
CommandResult TelemetryHandler::handleSetMaxLoads(const CommandEnvelope& e) {
|
||||
// Accepts either: { "all": 500 } OR { "loads": { "0": 300, "3": 700 } }
|
||||
if (e.contents["all"].is<uint16_t>()) {
|
||||
uint16_t val = e.contents["all"].as<uint16_t>();
|
||||
if (val == 0) return CommandResult::err("telemetry.set_max_loads", "max_load must be > 0");
|
||||
for (uint8_t i = 0; i < 16; i++) _telemetry.setBellMaxLoad(i, val);
|
||||
LOG_INFO(TAG, "All bell max loads set to %u", val);
|
||||
return CommandResult::ok("telemetry.set_max_loads", "All bell max loads updated");
|
||||
}
|
||||
if (e.contents["loads"].is<JsonObject>()) {
|
||||
JsonObjectConst loads = e.contents["loads"].as<JsonObjectConst>();
|
||||
for (JsonPairConst kv : loads) {
|
||||
uint8_t idx = (uint8_t)String(kv.key().c_str()).toInt();
|
||||
uint16_t val = kv.value().as<uint16_t>();
|
||||
if (idx < 16 && val > 0) _telemetry.setBellMaxLoad(idx, val);
|
||||
}
|
||||
return CommandResult::ok("telemetry.set_max_loads", "Bell max loads updated");
|
||||
}
|
||||
return CommandResult::err("telemetry.set_max_loads", "Provide 'all' (uint16) or 'loads' (object)");
|
||||
}
|
||||
|
||||
CommandResult TelemetryHandler::handleSetGuardEnabled(const CommandEnvelope& e) {
|
||||
if (!e.contents["enabled"].is<bool>()) {
|
||||
return CommandResult::err("telemetry.set_guard_enabled", "Missing required field: enabled (bool)");
|
||||
}
|
||||
bool enabled = e.contents["enabled"].as<bool>();
|
||||
_telemetry.setGuardEnabled(enabled);
|
||||
LOG_WARNING(TAG, "Bell guard %s by command", enabled ? "enabled" : "disabled");
|
||||
return CommandResult::ok("telemetry.set_guard_enabled",
|
||||
String("Bell guard ") + (enabled ? "enabled" : "disabled"));
|
||||
}
|
||||
|
||||
CommandResult TelemetryHandler::handleGetMetrics(const CommandEnvelope& e) {
|
||||
JsonDocument doc;
|
||||
doc["lifetime_runtime_seconds"] = _telemetry.getLifetimeRuntimeSeconds();
|
||||
doc["session_runtime_seconds"] = _telemetry.getCurrentSessionSeconds();
|
||||
doc["total_playbacks"] = _telemetry.getTotalPlaybackCount();
|
||||
doc["guard_enabled"] = _telemetry.isGuardEnabled();
|
||||
return CommandResult::ok("telemetry.get_metrics", doc);
|
||||
}
|
||||
|
||||
CommandResult TelemetryHandler::handleResetMetrics(const CommandEnvelope& e) {
|
||||
_telemetry.resetMetrics();
|
||||
LOG_WARNING(TAG, "Telemetry metrics reset by command");
|
||||
return CommandResult::ok("telemetry.reset_metrics", "Lifetime runtime and playback count reset to zero");
|
||||
}
|
||||
|
||||
@@ -18,4 +18,8 @@ private:
|
||||
CommandResult handleGetStrikes(const CommandEnvelope& e);
|
||||
CommandResult handleResetStrikes(const CommandEnvelope& e);
|
||||
CommandResult handleGetLoads(const CommandEnvelope& e);
|
||||
CommandResult handleSetMaxLoads(const CommandEnvelope& e);
|
||||
CommandResult handleSetGuardEnabled(const CommandEnvelope& e);
|
||||
CommandResult handleGetMetrics(const CommandEnvelope& e);
|
||||
CommandResult handleResetMetrics(const CommandEnvelope& e);
|
||||
};
|
||||
|
||||
@@ -1413,15 +1413,20 @@ bool ConfigManager::loadGeneralConfig() {
|
||||
}
|
||||
if (doc.containsKey("mqttEnabled")) {
|
||||
generalConfig.mqttEnabled = doc["mqttEnabled"].as<bool>();
|
||||
mqttConfig.enabled = generalConfig.mqttEnabled; // Sync with mqttConfig
|
||||
mqttConfig.enabled = generalConfig.mqttEnabled;
|
||||
}
|
||||
if (doc.containsKey("bellsEnabled")) {
|
||||
generalConfig.bellsEnabled = doc["bellsEnabled"].as<bool>();
|
||||
}
|
||||
if (doc.containsKey("otaChannel")) {
|
||||
generalConfig.otaChannel = doc["otaChannel"].as<String>();
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "ConfigManager - General config loaded - Serial log level: %d, SD log level: %d, MQTT log level: %d, MQTT enabled: %s, OTA channel: %s",
|
||||
generalConfig.serialLogLevel, generalConfig.sdLogLevel, generalConfig.mqttLogLevel,
|
||||
generalConfig.mqttEnabled ? "true" : "false", generalConfig.otaChannel.c_str());
|
||||
LOG_DEBUG(TAG, "ConfigManager - General config loaded - serialLog: %d, mqttEnabled: %s, bellsEnabled: %s, otaChannel: %s",
|
||||
generalConfig.serialLogLevel,
|
||||
generalConfig.mqttEnabled ? "true" : "false",
|
||||
generalConfig.bellsEnabled ? "true" : "false",
|
||||
generalConfig.otaChannel.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1433,10 +1438,11 @@ bool ConfigManager::saveGeneralConfig() {
|
||||
|
||||
StaticJsonDocument<256> doc;
|
||||
doc["serialLogLevel"] = generalConfig.serialLogLevel;
|
||||
doc["sdLogLevel"] = generalConfig.sdLogLevel;
|
||||
doc["mqttLogLevel"] = generalConfig.mqttLogLevel;
|
||||
doc["mqttEnabled"] = generalConfig.mqttEnabled;
|
||||
doc["otaChannel"] = generalConfig.otaChannel;
|
||||
doc["sdLogLevel"] = generalConfig.sdLogLevel;
|
||||
doc["mqttLogLevel"] = generalConfig.mqttLogLevel;
|
||||
doc["mqttEnabled"] = generalConfig.mqttEnabled;
|
||||
doc["bellsEnabled"] = generalConfig.bellsEnabled;
|
||||
doc["otaChannel"] = generalConfig.otaChannel;
|
||||
|
||||
char buffer[256];
|
||||
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
||||
|
||||
@@ -217,10 +217,11 @@ public:
|
||||
* All clock settings are loaded from SD card at startup.
|
||||
*/
|
||||
struct GeneralConfig {
|
||||
uint8_t serialLogLevel = 3; // INFO
|
||||
uint8_t sdLogLevel = 2; // WARNING (inactive until SD callback is wired)
|
||||
uint8_t mqttLogLevel = 2; // WARNING
|
||||
uint8_t serialLogLevel = 3; // INFO
|
||||
uint8_t sdLogLevel = 2; // WARNING (inactive until SD callback is wired)
|
||||
uint8_t mqttLogLevel = 2; // WARNING
|
||||
bool mqttEnabled = true; // MQTT enabled by default
|
||||
bool bellsEnabled = true; // Master bell mechanism ON/OFF (blocks playback + clock alerts)
|
||||
String otaChannel = "stable"; // OTA release channel: "stable" | "beta" | "development"
|
||||
};
|
||||
|
||||
@@ -441,6 +442,8 @@ public:
|
||||
uint8_t getMqttLogLevel() const { return generalConfig.mqttLogLevel; }
|
||||
void setMqttEnabled(bool enabled) { generalConfig.mqttEnabled = enabled; mqttConfig.enabled = enabled; }
|
||||
bool getMqttEnabled() const { return generalConfig.mqttEnabled; }
|
||||
void setBellsEnabled(bool enabled) { generalConfig.bellsEnabled = enabled; }
|
||||
bool getBellsEnabled() const { return generalConfig.bellsEnabled; }
|
||||
String getOtaChannel() const { return generalConfig.otaChannel; }
|
||||
void setOtaChannel(const String& channel) { generalConfig.otaChannel = channel; }
|
||||
bool loadGeneralConfig();
|
||||
|
||||
@@ -142,7 +142,8 @@ void Player::play() {
|
||||
isPlaying = true;
|
||||
hardStop = false;
|
||||
startTime = segmentStartTime = millis();
|
||||
setStatus(PlayerStatus::PLAYING); // Update status and notify clients
|
||||
setStatus(PlayerStatus::PLAYING);
|
||||
if (_telemetry) _telemetry->recordPlayback();
|
||||
LOG_DEBUG(TAG, "Plbck: PLAY");
|
||||
}
|
||||
|
||||
|
||||
+128
-11
@@ -4,21 +4,20 @@
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
void Telemetry::begin() {
|
||||
// Initialize arrays
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
strikeCounters[i] = 0;
|
||||
bellLoad[i] = 0;
|
||||
bellMaxLoad[i] = 500; // Default max load
|
||||
bellMaxLoad[i] = 500;
|
||||
}
|
||||
|
||||
coolingActive = false;
|
||||
guardEnabled = true;
|
||||
sessionStartMs = millis();
|
||||
lastRuntimeFlushMs = millis();
|
||||
|
||||
// Load strike counters from SD if available
|
||||
loadStrikeCounters();
|
||||
loadMetrics();
|
||||
|
||||
// Create the telemetry task
|
||||
xTaskCreatePinnedToCore(telemetryTask, "TelemetryTask", 4096, this, 2, &telemetryTaskHandle, 1);
|
||||
|
||||
LOG_INFO(TAG, "Telemetry initialized");
|
||||
}
|
||||
|
||||
@@ -66,7 +65,7 @@ void Telemetry::resetStrikeCounters() {
|
||||
strikeCounters[i] = 0;
|
||||
}
|
||||
portEXIT_CRITICAL(&telemetrySpinlock);
|
||||
|
||||
saveStrikeCounters();
|
||||
LOG_WARNING(TAG, "Strike counters reset by user");
|
||||
}
|
||||
|
||||
@@ -78,6 +77,11 @@ uint16_t Telemetry::getBellLoad(uint8_t bellIndex) {
|
||||
return bellLoad[bellIndex];
|
||||
}
|
||||
|
||||
uint16_t Telemetry::getBellMaxLoad(uint8_t bellIndex) {
|
||||
if (bellIndex >= 16) return 0;
|
||||
return bellMaxLoad[bellIndex];
|
||||
}
|
||||
|
||||
void Telemetry::setBellMaxLoad(uint8_t bellIndex, uint16_t maxLoad) {
|
||||
if (bellIndex >= 16) {
|
||||
LOG_ERROR(TAG, "Invalid bell index: %d", bellIndex);
|
||||
@@ -111,6 +115,15 @@ void Telemetry::logVibration(float vibration) {
|
||||
}
|
||||
|
||||
void Telemetry::checkBellLoads() {
|
||||
if (!guardEnabled) {
|
||||
// Guard disabled — still decay loads for accurate reporting, but never force-stop
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
if (bellLoad[i] > 0) bellLoad[i]--;
|
||||
}
|
||||
coolingActive = false;
|
||||
return;
|
||||
}
|
||||
|
||||
coolingActive = false; // Reset cooling flag
|
||||
|
||||
// Collect overloaded bells for batch notification
|
||||
@@ -170,25 +183,129 @@ void Telemetry::checkBellLoads() {
|
||||
|
||||
void Telemetry::telemetryTask(void* parameter) {
|
||||
Telemetry* telemetry = static_cast<Telemetry*>(parameter);
|
||||
|
||||
LOG_INFO(TAG, "Telemetry task started");
|
||||
|
||||
while(1) {
|
||||
// Skip processing if paused (OTA freeze mode)
|
||||
if (!telemetry->isPaused) {
|
||||
// Only run if player is playing OR we're still cooling
|
||||
bool isPlaying = (telemetry->playerIsPlayingPtr != nullptr) ?
|
||||
*(telemetry->playerIsPlayingPtr) : false;
|
||||
|
||||
if (isPlaying || telemetry->coolingActive) {
|
||||
telemetry->checkBellLoads();
|
||||
}
|
||||
|
||||
// Flush lifetime runtime to SD every 10 minutes
|
||||
uint32_t now = millis();
|
||||
if (now - telemetry->lastRuntimeFlushMs >= RUNTIME_FLUSH_INTERVAL_MS) {
|
||||
telemetry->flushRuntimeToSD();
|
||||
telemetry->lastRuntimeFlushMs = now;
|
||||
}
|
||||
}
|
||||
|
||||
vTaskDelay(pdMS_TO_TICKS(1000)); // Run every 1s
|
||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// PLAYBACK COUNTER
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Telemetry::recordPlayback() {
|
||||
portENTER_CRITICAL(&telemetrySpinlock);
|
||||
totalPlaybackCount++;
|
||||
portEXIT_CRITICAL(&telemetrySpinlock);
|
||||
saveMetrics();
|
||||
}
|
||||
|
||||
void Telemetry::resetMetrics() {
|
||||
portENTER_CRITICAL(&telemetrySpinlock);
|
||||
totalPlaybackCount = 0;
|
||||
lifetimeRuntimeSeconds = 0;
|
||||
portEXIT_CRITICAL(&telemetrySpinlock);
|
||||
saveMetrics();
|
||||
LOG_WARNING(TAG, "Telemetry metrics reset by user");
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// RUNTIME PERSISTENCE
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Telemetry::flushRuntimeToSD() {
|
||||
if (!fileManager) return;
|
||||
|
||||
uint32_t sessionSecs = (millis() - sessionStartMs) / 1000;
|
||||
uint32_t total = lifetimeRuntimeSeconds + sessionSecs;
|
||||
|
||||
StaticJsonDocument<256> doc;
|
||||
doc["lifetime_seconds"] = total;
|
||||
doc["total_playbacks"] = totalPlaybackCount;
|
||||
|
||||
if (fileManager->writeJsonFile("/telemetry_runtime.json", doc)) {
|
||||
LOG_DEBUG(TAG, "Runtime flushed: %lu lifetime seconds, %lu playbacks", total, totalPlaybackCount);
|
||||
} else {
|
||||
LOG_WARNING(TAG, "Failed to flush runtime to SD");
|
||||
}
|
||||
}
|
||||
|
||||
void Telemetry::logBootEvent(uint32_t bootTimestamp) {
|
||||
if (!fileManager) return;
|
||||
|
||||
// Read existing boot log (or create fresh)
|
||||
StaticJsonDocument<8192> doc;
|
||||
fileManager->readJsonFile("/telemetry_boot_log.json", doc);
|
||||
|
||||
JsonArray entries = doc["boots"].is<JsonArray>()
|
||||
? doc["boots"].as<JsonArray>()
|
||||
: doc["boots"].to<JsonArray>();
|
||||
|
||||
// Rotate: keep only the last BOOT_LOG_MAX_ENTRIES - 1 entries
|
||||
while (entries.size() >= BOOT_LOG_MAX_ENTRIES) {
|
||||
// Remove oldest (index 0) by rebuilding — ArduinoJson doesn't support remove(0) on array
|
||||
JsonDocument tmp;
|
||||
JsonArray fresh = tmp["boots"].to<JsonArray>();
|
||||
for (size_t i = 1; i < entries.size(); i++) fresh.add(entries[i]);
|
||||
doc["boots"] = fresh;
|
||||
entries = doc["boots"].as<JsonArray>();
|
||||
}
|
||||
|
||||
JsonObject entry = entries.add<JsonObject>();
|
||||
entry["ts"] = bootTimestamp;
|
||||
entry["boot"] = (uint32_t)(doc["total_boots"] | 0) + 1;
|
||||
doc["total_boots"] = (uint32_t)(doc["total_boots"] | 0) + 1;
|
||||
|
||||
if (!fileManager->writeJsonFile("/telemetry_boot_log.json", doc)) {
|
||||
LOG_WARNING(TAG, "Failed to write boot log");
|
||||
} else {
|
||||
LOG_INFO(TAG, "Boot #%u logged at timestamp %u", (uint32_t)doc["total_boots"], bootTimestamp);
|
||||
}
|
||||
}
|
||||
|
||||
void Telemetry::loadMetrics() {
|
||||
if (!fileManager) return;
|
||||
|
||||
StaticJsonDocument<256> doc;
|
||||
if (!fileManager->readJsonFile("/telemetry_runtime.json", doc)) {
|
||||
LOG_INFO(TAG, "No runtime metrics found, starting fresh");
|
||||
return;
|
||||
}
|
||||
|
||||
lifetimeRuntimeSeconds = doc["lifetime_seconds"] | 0;
|
||||
totalPlaybackCount = doc["total_playbacks"] | 0;
|
||||
LOG_INFO(TAG, "Metrics loaded: %lu lifetime seconds, %lu playbacks",
|
||||
lifetimeRuntimeSeconds, totalPlaybackCount);
|
||||
}
|
||||
|
||||
void Telemetry::saveMetrics() {
|
||||
if (!fileManager) return;
|
||||
|
||||
uint32_t sessionSecs = (millis() - sessionStartMs) / 1000;
|
||||
StaticJsonDocument<256> doc;
|
||||
doc["lifetime_seconds"] = lifetimeRuntimeSeconds + sessionSecs;
|
||||
doc["total_playbacks"] = totalPlaybackCount;
|
||||
|
||||
fileManager->writeJsonFile("/telemetry_runtime.json", doc);
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// STRIKE COUNTER PERSISTENCE
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -59,6 +59,11 @@
|
||||
#include "../Logging/Logging.hpp"
|
||||
#include "../FileManager/FileManager.hpp"
|
||||
|
||||
// Maximum number of boot log entries retained on SD (rotating)
|
||||
static constexpr uint16_t BOOT_LOG_MAX_ENTRIES = 200;
|
||||
// Runtime flush interval in milliseconds (10 minutes)
|
||||
static constexpr uint32_t RUNTIME_FLUSH_INTERVAL_MS = 10 * 60 * 1000UL;
|
||||
|
||||
class Telemetry {
|
||||
private:
|
||||
// Bell tracking
|
||||
@@ -66,6 +71,13 @@ private:
|
||||
uint16_t bellLoad[16] = {0}; // Current heat load per bell
|
||||
uint16_t bellMaxLoad[16] = {60}; // Max load threshold per bell
|
||||
bool coolingActive = false; // System-wide cooling flag
|
||||
bool guardEnabled = true; // Bell load guard enable/disable
|
||||
|
||||
// Runtime tracking
|
||||
uint32_t lifetimeRuntimeSeconds = 0; // Cumulative powered-on seconds (loaded from SD)
|
||||
uint32_t sessionStartMs = 0; // millis() at boot — used to compute current session
|
||||
uint32_t lastRuntimeFlushMs = 0; // Last time runtime was flushed to SD
|
||||
uint32_t totalPlaybackCount = 0; // Total melodies played (lifetime, persisted)
|
||||
|
||||
// Task handle
|
||||
TaskHandle_t telemetryTaskHandle = NULL;
|
||||
@@ -93,7 +105,7 @@ public:
|
||||
|
||||
// Strike counter management (warranty tracking)
|
||||
uint32_t getStrikeCount(uint8_t bellIndex);
|
||||
void resetStrikeCounters(); // User-requested reset
|
||||
void resetStrikeCounters(); // User-requested reset (per bell or all)
|
||||
|
||||
// Persistence methods
|
||||
void saveStrikeCounters();
|
||||
@@ -101,10 +113,28 @@ public:
|
||||
|
||||
// Bell load management
|
||||
uint16_t getBellLoad(uint8_t bellIndex);
|
||||
uint16_t getBellMaxLoad(uint8_t bellIndex);
|
||||
void setBellMaxLoad(uint8_t bellIndex, uint16_t maxLoad);
|
||||
bool isOverloaded(uint8_t bellIndex);
|
||||
bool isCoolingActive(); // Check if system needs cooling
|
||||
|
||||
// Bell guard enable/disable
|
||||
bool isGuardEnabled() const { return guardEnabled; }
|
||||
void setGuardEnabled(bool enabled) { guardEnabled = enabled; }
|
||||
|
||||
// Playback counter
|
||||
void recordPlayback();
|
||||
uint32_t getTotalPlaybackCount() const { return totalPlaybackCount; }
|
||||
void resetMetrics();
|
||||
|
||||
// Runtime metrics
|
||||
uint32_t getLifetimeRuntimeSeconds() const { return lifetimeRuntimeSeconds; }
|
||||
uint32_t getCurrentSessionSeconds() const { return (millis() - sessionStartMs) / 1000; }
|
||||
void flushRuntimeToSD();
|
||||
|
||||
// Boot log
|
||||
void logBootEvent(uint32_t bootTimestamp);
|
||||
|
||||
// Data collection (future expansion)
|
||||
void logTemperature(float temperature);
|
||||
void logVibration(float vibration);
|
||||
@@ -116,11 +146,6 @@ public:
|
||||
void pause() { isPaused = true; }
|
||||
void resume() { isPaused = false; }
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK METHOD
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Check if Telemetry is in healthy state */
|
||||
bool isHealthy() const;
|
||||
|
||||
// Static task function
|
||||
@@ -129,6 +154,8 @@ public:
|
||||
private:
|
||||
void (*forceStopCallback)() = nullptr;
|
||||
void checkBellLoads();
|
||||
void loadMetrics();
|
||||
void saveMetrics();
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -557,9 +557,12 @@ void Timekeeper::loadNextDayEvents() {
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Timekeeper::checkClockAlerts() {
|
||||
// Check if clock is enabled in config
|
||||
if (!_configManager || !_configManager->getClockEnabled()) {
|
||||
return; // Clock is disabled - skip all alert functionality
|
||||
return;
|
||||
}
|
||||
// Bell mechanism master switch — alerts fire bells, so respect it
|
||||
if (!_configManager->getBellsEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we have required dependencies
|
||||
|
||||
@@ -451,6 +451,8 @@ static void ntpSyncTask(void* param) {
|
||||
LOG_DEBUG(TAG, "Network stabilization complete - starting NTP sync");
|
||||
if (!networking.isInAPMode()) {
|
||||
timekeeper.syncTimeWithNTP();
|
||||
// Log boot event now that we have a real timestamp
|
||||
telemetry.logBootEvent((uint32_t)timekeeper.getTime());
|
||||
}
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user