#include "Telemetry.hpp" #define TAG "Telemetry" #include #include void Telemetry::begin() { resetReason = esp_reset_reason(); LOG_INFO(TAG, "Reset reason: %s%s", getResetReasonString().c_str(), isFaultReset() ? " (FAULT)" : ""); initBootTracking(); captureCrashReport(); // Always consume (it clears RTC memory), but only keep it for a fault // reset — after a clean reset/OTA the previous boot's snapshot is noise. PreCrashSnapshot crumbs = CrashBreadcrumbs::consume(); if (isFaultReset() && crumbs.available) { preCrash = crumbs; LOG_WARNING(TAG, "Pre-crash state: uptime %lu ms, free heap %lu, largest block %lu, min free %lu", preCrash.uptimeMs, preCrash.freeHeap, preCrash.largestBlock, preCrash.minFreeHeap); if (preCrash.abortMsg[0] != '') { LOG_WARNING(TAG, "Abort reason: %s", preCrash.abortMsg); } } CrashBreadcrumbs::updateSnapshot(); for (uint8_t i = 0; i < 16; i++) { strikeCounters[i] = 0; bellLoad[i] = 0; bellMaxLoad[i] = 500; } coolingActive = false; guardEnabled = true; sessionStartMs = millis(); lastRuntimeFlushMs = millis(); loadStrikeCounters(); loadMetrics(); // 8192: flushRuntimeToSD() nests ArduinoJson serialization + SD write + LOG_DEBUG // (512B format buffer + MQTT publish String + AsyncMqttClient::publish()) on this // task's own stack. 4096 overflowed the canary in production — see stack-audit notes. xTaskCreatePinnedToCore(telemetryTask, "TelemetryTask", 8192, this, 2, &telemetryTaskHandle, 1); registerTaskForStackMonitoring("TelemetryTask", telemetryTaskHandle); LOG_INFO(TAG, "Telemetry initialized"); } bool Telemetry::isFaultReset() const { switch (resetReason) { case ESP_RST_PANIC: case ESP_RST_INT_WDT: case ESP_RST_TASK_WDT: case ESP_RST_WDT: case ESP_RST_BROWNOUT: return true; default: return false; } } String Telemetry::getResetReasonString() const { switch (resetReason) { case ESP_RST_UNKNOWN: return "UNKNOWN"; case ESP_RST_POWERON: return "POWERON"; case ESP_RST_EXT: return "EXTERNAL_PIN"; case ESP_RST_SW: return "SOFTWARE"; case ESP_RST_PANIC: return "PANIC"; case ESP_RST_INT_WDT: return "INTERRUPT_WATCHDOG"; case ESP_RST_TASK_WDT: return "TASK_WATCHDOG"; case ESP_RST_WDT: return "OTHER_WATCHDOG"; case ESP_RST_DEEPSLEEP: return "DEEPSLEEP_WAKE"; case ESP_RST_BROWNOUT: return "BROWNOUT"; case ESP_RST_SDIO: return "SDIO"; default: return "UNKNOWN"; } } // ════════════════════════════════════════════════════════════════════════════ // BOOT TRACKING — lifetime counter + crash coredump summary // ════════════════════════════════════════════════════════════════════════════ void Telemetry::initBootTracking() { // Separate NVS namespace from FirmwareValidator's "fw_validator" — this // counter tracks the device's whole lifetime, not boots-since-this-firmware- // image-was-flashed, so it must not share storage or reset semantics. esp_err_t err = nvs_open("vesper_boot", NVS_READWRITE, &_bootNvsHandle); if (err != ESP_OK) { LOG_ERROR(TAG, "Failed to open boot-tracking NVS namespace: %s", esp_err_to_name(err)); return; } uint32_t count = 0; nvs_get_u32(_bootNvsHandle, "lifetime_boots", &count); // defaults to 0 if key absent count++; nvs_set_u32(_bootNvsHandle, "lifetime_boots", count); nvs_commit(_bootNvsHandle); lifetimeBootCount = count; LOG_INFO(TAG, "Lifetime boot count: %lu", lifetimeBootCount); } void Telemetry::captureCrashReport() { if (esp_core_dump_image_check() != ESP_OK) { return; // no coredump present — expected on a non-crash reset } esp_core_dump_summary_t summary; if (esp_core_dump_get_summary(&summary) != ESP_OK) { LOG_WARNING(TAG, "Coredump present but summary read failed"); esp_core_dump_image_erase(); // don't leave a dump we can't parse sitting in flash return; } crashReport.available = true; strncpy(crashReport.taskName, summary.exc_task, sizeof(crashReport.taskName) - 1); crashReport.taskName[sizeof(crashReport.taskName) - 1] = '\0'; crashReport.pc = summary.exc_pc; crashReport.excCause = summary.ex_info.exc_cause; crashReport.excVaddr = summary.ex_info.exc_vaddr; uint32_t depth = summary.exc_bt_info.depth; if (depth > 16) depth = 16; for (uint32_t i = 0; i < depth; i++) crashReport.backtrace[i] = summary.exc_bt_info.bt[i]; crashReport.backtraceDepth = depth; crashReport.backtraceCorrupted = summary.exc_bt_info.corrupted; strncpy(crashReport.elfSha, (const char*)summary.app_elf_sha256, sizeof(crashReport.elfSha) - 1); crashReport.elfSha[sizeof(crashReport.elfSha) - 1] = ''; LOG_WARNING(TAG, "Crash coredump found — task '%s', PC 0x%08lX, cause %lu, vaddr 0x%08lX", crashReport.taskName, crashReport.pc, crashReport.excCause, crashReport.excVaddr); // Same format as the serial panic output, so it can be pasted straight // into addr2line / the ESP exception decoder. char bt[16 * 11 + 1]; size_t pos = 0; for (uint8_t i = 0; i < crashReport.backtraceDepth; i++) { pos += snprintf(bt + pos, sizeof(bt) - pos, " 0x%08lX", (unsigned long)crashReport.backtrace[i]); } bt[pos] = ''; LOG_WARNING(TAG, "Crash backtrace (ELF %s)%s:%s", crashReport.elfSha, crashReport.backtraceCorrupted ? " [CORRUPTED]" : "", bt); // Erase immediately after reading — this is a one-shot report. Without this, // the same coredump would be re-reported on every subsequent boot until the // next crash overwrites it. esp_core_dump_image_erase(); } void Telemetry::writeCrashJson(JsonObject out) const { out["task"] = crashReport.taskName; out["pc"] = crashReport.pc; out["exc_cause"] = crashReport.excCause; out["exc_vaddr"] = crashReport.excVaddr; JsonArray bt = out["backtrace"].to(); for (uint8_t i = 0; i < crashReport.backtraceDepth; i++) bt.add(crashReport.backtrace[i]); out["backtrace_corrupted"] = crashReport.backtraceCorrupted; out["elf_sha256"] = crashReport.elfSha; } void Telemetry::writePreCrashJson(JsonObject out) const { out["uptime_ms"] = preCrash.uptimeMs; out["free_heap"] = preCrash.freeHeap; out["largest_block"] = preCrash.largestBlock; out["min_free_heap"] = preCrash.minFreeHeap; if (preCrash.abortMsg[0] != '') out["abort_msg"] = preCrash.abortMsg; } void Telemetry::setPlayerReference(bool* isPlayingPtr) { playerIsPlayingPtr = isPlayingPtr; LOG_DEBUG(TAG, "Player reference set"); } void Telemetry::setFileManager(FileManager* fm) { fileManager = fm; LOG_DEBUG(TAG, "FileManager reference set"); } void Telemetry::setForceStopCallback(void (*callback)()) { forceStopCallback = callback; LOG_DEBUG(TAG, "Force stop callback set"); } void Telemetry::recordBellStrike(uint8_t bellIndex) { if (bellIndex >= 16) { LOG_ERROR(TAG, "Invalid bell index: %d", bellIndex); return; } // Critical section - matches your original code portENTER_CRITICAL(&telemetrySpinlock); strikeCounters[bellIndex]++; // Count strikes per bell (warranty) bellLoad[bellIndex]++; // Load per bell (heat simulation) coolingActive = true; // System needs cooling portEXIT_CRITICAL(&telemetrySpinlock); } uint32_t Telemetry::getStrikeCount(uint8_t bellIndex) { if (bellIndex >= 16) { LOG_ERROR(TAG, "Invalid bell index: %d", bellIndex); return 0; } return strikeCounters[bellIndex]; } void Telemetry::resetStrikeCounters() { portENTER_CRITICAL(&telemetrySpinlock); for (uint8_t i = 0; i < 16; i++) { strikeCounters[i] = 0; } portEXIT_CRITICAL(&telemetrySpinlock); saveStrikeCounters(); LOG_WARNING(TAG, "Strike counters reset by user"); } uint16_t Telemetry::getBellLoad(uint8_t bellIndex) { if (bellIndex >= 16) { LOG_ERROR(TAG, "Invalid bell index: %d", bellIndex); return 0; } 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); return; } bellMaxLoad[bellIndex] = maxLoad; LOG_INFO(TAG, "Bell %d max load set to %d", bellIndex, maxLoad); } bool Telemetry::isOverloaded(uint8_t bellIndex) { if (bellIndex >= 16) { LOG_ERROR(TAG, "Invalid bell index: %d", bellIndex); return false; } return bellLoad[bellIndex] > bellMaxLoad[bellIndex]; } bool Telemetry::isCoolingActive() { return coolingActive; } void Telemetry::logTemperature(float temperature) { // Future implementation for temperature logging LOG_INFO(TAG, "Temperature: %.2f°C", temperature); } void Telemetry::logVibration(float vibration) { // Future implementation for vibration logging LOG_INFO(TAG, "Vibration: %.2f", vibration); } // ════════════════════════════════════════════════════════════════════════════ // DIAGNOSTICS REPORT — local temperature sampling + stack high-water registry // ════════════════════════════════════════════════════════════════════════════ void Telemetry::sampleDiagnosticsIfDue() { uint32_t now = millis(); if (now - lastDiagnosticsSampleMs < DIAGNOSTICS_SAMPLE_INTERVAL_MS) return; lastDiagnosticsSampleMs = now; // ESP32's built-in die temperature sensor (temperatureRead(), Arduino-ESP32 // core). Coarse and reads die temp rather than ambient — useful as a "is // this thing running hot" trend signal, not a calibrated instrument. float tempC = temperatureRead(); temperatureStats.addSample(tempC); } // Fixed-size registry — matches this codebase's avoid-dynamic-allocation // style elsewhere (e.g. strikeCounters[16]). 8 slots comfortably covers every // task with a stored TaskHandle_t today (TelemetryTask, HealthMonitor, // TimeKeeper, OutputManager, FirmwareValidator, Logging, BellEngine, // InputManager) with room to spare; short-lived fire-and-forget tasks like // mqttRecon/netRecon don't keep a handle at all and can't be monitored this way. namespace { struct StackMonitorEntry { const char* name = nullptr; TaskHandle_t handle = nullptr; }; constexpr size_t MAX_STACK_MONITOR_ENTRIES = 8; StackMonitorEntry stackMonitorRegistry[MAX_STACK_MONITOR_ENTRIES]; size_t stackMonitorCount = 0; } void Telemetry::registerTaskForStackMonitoring(const char* name, TaskHandle_t handle) { if (handle == nullptr) return; if (stackMonitorCount >= MAX_STACK_MONITOR_ENTRIES) { LOG_WARNING(TAG, "Stack monitor registry full — '%s' not registered", name); return; } stackMonitorRegistry[stackMonitorCount++] = { name, handle }; } void Telemetry::writeStackHighWaterMarks(JsonObject& out) { for (size_t i = 0; i < stackMonitorCount; i++) { const auto& entry = stackMonitorRegistry[i]; UBaseType_t wordsFree = uxTaskGetStackHighWaterMark(entry.handle); out[entry.name] = (uint32_t)(wordsFree * sizeof(StackType_t)); } } void Telemetry::writeTemperatureStats(JsonDocument& doc) const { if (temperatureStats.count == 0) return; JsonObject tempObj = doc["cpu_temp"].to(); tempObj["avg"] = temperatureStats.average(); tempObj["min"] = temperatureStats.min; tempObj["max"] = temperatureStats.max; tempObj["samples"] = temperatureStats.count; } 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 std::vector criticalBells; std::vector criticalLoads; std::vector warningBells; std::vector warningLoads; bool anyOverload = false; for (uint8_t i = 0; i < 16; i++) { if (bellLoad[i] > 0) { bellLoad[i]--; coolingActive = true; // Still has heat left } // Check for critical overload (90% of max load) uint16_t criticalThreshold = (bellMaxLoad[i] * 90) / 100; // Check for warning overload (60% of max load) uint16_t warningThreshold = (bellMaxLoad[i] * 60) / 100; // Critical overload - protection kicks in if (bellLoad[i] > bellMaxLoad[i]) { LOG_ERROR(TAG, "Bell %d OVERLOADED! load=%d max=%d", i, bellLoad[i], bellMaxLoad[i]); criticalBells.push_back(i); criticalLoads.push_back(bellLoad[i]); anyOverload = true; } else if (bellLoad[i] > criticalThreshold) { // Critical warning - approaching overload LOG_WARNING(TAG, "Bell %d approaching overload! load=%d (critical threshold=%d)", i, bellLoad[i], criticalThreshold); criticalBells.push_back(i); criticalLoads.push_back(bellLoad[i]); } else if (bellLoad[i] > warningThreshold) { // Warning - moderate load LOG_INFO(TAG, "Bell %d moderate load warning! load=%d (warning threshold=%d)", i, bellLoad[i], warningThreshold); warningBells.push_back(i); warningLoads.push_back(bellLoad[i]); } } // Note: Notifications now handled by BellEngine which has Communication reference // BellEngine monitors telemetry and sends notifications when overloads detected // Trigger force stop if any bell is actually overloaded if (anyOverload && forceStopCallback != nullptr) { forceStopCallback(); } } void Telemetry::telemetryTask(void* parameter) { Telemetry* telemetry = static_cast(parameter); LOG_INFO(TAG, "Telemetry task started"); while(1) { if (!telemetry->isPaused) { 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; } // Diagnostics: local temperature sampling (own throttle, ~15s) telemetry->sampleDiagnosticsIfDue(); } // Outside the pause check — an OTA-freeze crash needs context too. CrashBreadcrumbs::updateSnapshot(); 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"); } // ════════════════════════════════════════════════════════════════════════════ // BOOT DATA RESET — clears the lifetime boot counter (NVS) and the SD-side // boot history log. Deliberately separate from FirmwareValidator's own NVS // namespace ("fw_validator") — that one is live rollback-safety state, not // "history," and must never be touched by this. See docs/features/ // feature-catalog.md's boot-tracking table for why the two are kept distinct. // ════════════════════════════════════════════════════════════════════════════ bool Telemetry::resetBootData() { bool nvsOk = true; if (_bootNvsHandle != 0) { esp_err_t err = nvs_set_u32(_bootNvsHandle, "lifetime_boots", 0); if (err == ESP_OK) err = nvs_commit(_bootNvsHandle); if (err != ESP_OK) { LOG_ERROR(TAG, "Failed to reset lifetime boot count in NVS: %s", esp_err_to_name(err)); nvsOk = false; } } else { nvsOk = false; } portENTER_CRITICAL(&telemetrySpinlock); lifetimeBootCount = 0; portEXIT_CRITICAL(&telemetrySpinlock); // SD boot log — best-effort. Absent SD/FileManager isn't a failure of the // NVS reset (which is the authoritative counter); deleteFile() returning // false because the file never existed yet is also not an error worth // surfacing. if (fileManager) { fileManager->deleteFile("/telemetry_boot_log.json"); } LOG_WARNING(TAG, "Boot data reset by user (lifetime count + SD boot log)"); return nvsOk; } // ════════════════════════════════════════════════════════════════════════════ // 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; // Heap-allocated — boot log can be large (up to 200 entries). // StaticJsonDocument on a task stack would overflow; JsonDocument uses heap. JsonDocument doc; fileManager->readJsonFile("/telemetry_boot_log.json", doc); JsonArray entries = doc["boots"].is() ? doc["boots"].as() : doc["boots"].to(); // Rotate: keep only the last BOOT_LOG_MAX_ENTRIES - 1 entries before adding while (entries.size() >= BOOT_LOG_MAX_ENTRIES) { JsonDocument tmp; JsonArray fresh = tmp["boots"].to(); for (size_t i = 1; i < entries.size(); i++) fresh.add(entries[i]); doc["boots"] = fresh; entries = doc["boots"].as(); } // "boot" is the same lifetime_boot_count reported over MQTT (boot_report, // telemetry.get_metrics, etc.) — NOT a locally-tallied total_boots. The two // used to be separate counters that could silently drift apart (this file // previously only advanced its own counter here, gated on NTP success, // while the NVS counter increments on every boot regardless of network). // See docs/features/feature-catalog.md F-053. JsonObject entry = entries.add(); entry["ts"] = bootTimestamp; entry["boot"] = lifetimeBootCount; entry["reason"] = getResetReasonString(); if (crashReport.available) writeCrashJson(entry["crash"].to()); if (preCrash.available) writePreCrashJson(entry["pre_crash"].to()); if (!fileManager->writeJsonFile("/telemetry_boot_log.json", doc)) { LOG_WARNING(TAG, "Failed to write boot log"); } else { LOG_INFO(TAG, "Boot #%lu logged at timestamp %u", lifetimeBootCount, bootTimestamp); } } bool Telemetry::getBootHistory(JsonDocument& outEntries, uint16_t maxEntries) { if (!fileManager) return false; JsonDocument doc; if (!fileManager->readJsonFile("/telemetry_boot_log.json", doc)) { return false; // no SD, or file doesn't exist yet (e.g. NTP never synced) } JsonArray entries = doc["boots"].as(); if (entries.isNull()) return false; JsonArray out = outEntries["boots"].to(); size_t total = entries.size(); size_t start = (total > maxEntries) ? (total - maxEntries) : 0; for (size_t i = start; i < total; i++) { out.add(entries[i]); } outEntries["count"] = out.size(); return true; } 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 // ════════════════════════════════════════════════════════════════════════════ void Telemetry::saveStrikeCounters() { if (!fileManager) { LOG_WARNING(TAG, "Cannot save strike counters: FileManager not set"); return; } StaticJsonDocument<512> doc; JsonArray counters = doc.createNestedArray("strikeCounters"); // Thread-safe read of strike counters portENTER_CRITICAL(&telemetrySpinlock); for (uint8_t i = 0; i < 16; i++) { counters.add(strikeCounters[i]); } portEXIT_CRITICAL(&telemetrySpinlock); if (fileManager->writeJsonFile("/telemetry_data.json", doc)) { LOG_INFO(TAG, "Strike counters saved to SD card"); } else { LOG_ERROR(TAG, "Failed to save strike counters to SD card"); } } void Telemetry::loadStrikeCounters() { if (!fileManager) { LOG_WARNING(TAG, "Cannot load strike counters: FileManager not set"); return; } StaticJsonDocument<512> doc; if (!fileManager->readJsonFile("/telemetry_data.json", doc)) { LOG_INFO(TAG, "No previous strike counter data found, starting fresh"); return; } JsonArray counters = doc["strikeCounters"]; if (counters.isNull()) { LOG_WARNING(TAG, "Invalid telemetry data format"); return; } // Thread-safe write of strike counters portENTER_CRITICAL(&telemetrySpinlock); for (uint8_t i = 0; i < 16 && i < counters.size(); i++) { strikeCounters[i] = counters[i].as(); } portEXIT_CRITICAL(&telemetrySpinlock); LOG_INFO(TAG, "Strike counters loaded from SD card"); } // ════════════════════════════════════════════════════════════════════════════ // HEALTH CHECK IMPLEMENTATION // ════════════════════════════════════════════════════════════════════════════ bool Telemetry::isHealthy() const { // Check if telemetry task is created and running if (telemetryTaskHandle == NULL) { LOG_DEBUG(TAG, "Telemetry: Unhealthy - Task not created"); return false; } // Check if task is still alive eTaskState taskState = eTaskGetState(telemetryTaskHandle); if (taskState == eDeleted || taskState == eInvalid) { LOG_DEBUG(TAG, "Telemetry: Unhealthy - Task deleted or invalid"); return false; } // Check if player reference is set if (playerIsPlayingPtr == nullptr) { LOG_DEBUG(TAG, "Telemetry: Unhealthy - Player reference not set"); return false; } // Check for any critical overloads that would indicate system stress bool hasCriticalOverload = false; for (uint8_t i = 0; i < 16; i++) { if (bellLoad[i] > bellMaxLoad[i]) { hasCriticalOverload = true; break; } } if (hasCriticalOverload) { LOG_DEBUG(TAG, "Telemetry: Unhealthy - Critical bell overload detected"); return false; } return true; }