Console requested four more Health-tab metrics beyond F-054's free_heap/ping work. None needed 30s heartbeat freshness, so this adds a separate low-frequency report instead of growing the heartbeat further: published every 5 min to status/info (diagnostics_report) and queryable on-demand via a new telemetry.get_diagnostics command. Only CPU temperature needs local sampling (15s, via a min/max/avg RunningStats accumulator on Telemetry) — a thermal spike could occur and subside entirely within a 5-minute gap. The other three fields are monotonic/self-tracking (WiFi reconnect counter, FreeRTOS's own stack high-water mark, rarely-changing OTA state) so a single read at report time loses no information. Verified: pio run on all four board variants.
1441 lines
54 KiB
C++
1441 lines
54 KiB
C++
#include "OTAManager.hpp"
|
|
|
|
#define TAG "OTAManager"
|
|
#include "../ConfigManager/ConfigManager.hpp"
|
|
#include "../Logging/Logging.hpp"
|
|
#include "../Player/Player.hpp"
|
|
#include "../SDCardMutex/SDCardMutex.hpp"
|
|
#include <nvs_flash.h>
|
|
#include <nvs.h>
|
|
#include <esp_task_wdt.h>
|
|
|
|
const char* OTAManager::errorCodeToString(ErrorCode code) {
|
|
switch (code) {
|
|
case ErrorCode::NONE: return "NONE";
|
|
case ErrorCode::HTTP_ERROR: return "HTTP_ERROR";
|
|
case ErrorCode::VERSION_CHECK_FAILED: return "VERSION_CHECK_FAILED";
|
|
case ErrorCode::DOWNLOAD_FAILED: return "DOWNLOAD_FAILED";
|
|
case ErrorCode::INSUFFICIENT_SPACE: return "INSUFFICIENT_SPACE";
|
|
case ErrorCode::WRITE_FAILED: return "WRITE_FAILED";
|
|
case ErrorCode::VERIFICATION_FAILED: return "VERIFICATION_FAILED";
|
|
case ErrorCode::CHECKSUM_MISMATCH: return "CHECKSUM_MISMATCH";
|
|
case ErrorCode::METADATA_PARSE_FAILED: return "METADATA_PARSE_FAILED";
|
|
case ErrorCode::SIZE_MISMATCH: return "SIZE_MISMATCH";
|
|
case ErrorCode::VERSION_TOO_LOW: return "VERSION_TOO_LOW";
|
|
case ErrorCode::CHANNEL_MISMATCH: return "CHANNEL_MISMATCH";
|
|
case ErrorCode::PLAYER_ACTIVE: return "PLAYER_ACTIVE";
|
|
default: return "UNKNOWN";
|
|
}
|
|
}
|
|
|
|
OTAManager::OTAManager(ConfigManager& configManager)
|
|
: _configManager(configManager)
|
|
, _fileManager(nullptr)
|
|
, _player(nullptr)
|
|
#if HAS_RTC
|
|
, _timeKeeper(nullptr)
|
|
#endif
|
|
, _telemetry(nullptr)
|
|
, _status(Status::IDLE)
|
|
, _lastError(ErrorCode::NONE)
|
|
, _availableVersion({0, 0, 0})
|
|
, _minVersion({0, 0, 0})
|
|
, _expectedFileSize(0)
|
|
, _updateAvailable(false)
|
|
, _availableChecksum("")
|
|
, _updateChannel("stable")
|
|
, _isMandatory(false)
|
|
, _isEmergency(false)
|
|
, _progressCallback(nullptr)
|
|
, _statusCallback(nullptr)
|
|
, _scheduledCheckTimer(NULL)
|
|
, _initialCheckTimer(NULL)
|
|
, _otaWorkerTask(NULL)
|
|
, _otaWorkSignal(NULL)
|
|
, _pendingWork(OTAWorkType::NONE) {
|
|
}
|
|
|
|
OTAManager::~OTAManager() {
|
|
// Clean up worker task and semaphore
|
|
if (_otaWorkerTask != NULL) {
|
|
vTaskDelete(_otaWorkerTask);
|
|
_otaWorkerTask = NULL;
|
|
}
|
|
if (_otaWorkSignal != NULL) {
|
|
vSemaphoreDelete(_otaWorkSignal);
|
|
_otaWorkSignal = NULL;
|
|
}
|
|
|
|
if (_scheduledCheckTimer != NULL) {
|
|
xTimerStop(_scheduledCheckTimer, 0);
|
|
xTimerDelete(_scheduledCheckTimer, portMAX_DELAY);
|
|
_scheduledCheckTimer = NULL;
|
|
}
|
|
if (_initialCheckTimer != NULL) {
|
|
xTimerStop(_initialCheckTimer, 0);
|
|
xTimerDelete(_initialCheckTimer, portMAX_DELAY);
|
|
_initialCheckTimer = NULL;
|
|
}
|
|
}
|
|
|
|
void OTAManager::begin() {
|
|
LOG_INFO(TAG, "OTA Manager initialized");
|
|
setStatus(Status::IDLE);
|
|
|
|
// Create semaphore for worker task signaling
|
|
_otaWorkSignal = xSemaphoreCreateBinary();
|
|
if (_otaWorkSignal == NULL) {
|
|
LOG_ERROR(TAG, "Failed to create OTA work semaphore!");
|
|
return;
|
|
}
|
|
|
|
// Create dedicated worker task with 16KB stack.
|
|
// Update.write() + HTTPClient + TLS frames + call depth during flash requires ~12-14KB;
|
|
// 8KB was silently overflowing during the stream-write phase.
|
|
BaseType_t taskCreated = xTaskCreatePinnedToCore(
|
|
otaWorkerTaskFunction,
|
|
"OTA_Worker",
|
|
16384, // 16KB stack - required for Update.write() + HTTP during flash
|
|
this, // Pass OTAManager instance
|
|
2, // Priority 2 (lower than critical tasks)
|
|
&_otaWorkerTask,
|
|
1 // Core 1 — TLS/HTTPS requires Core 1; lwip runs on Core 0 and deadlocks blocking TLS on the same core
|
|
);
|
|
|
|
if (taskCreated != pdPASS) {
|
|
LOG_ERROR(TAG, "Failed to create OTA worker task!");
|
|
vSemaphoreDelete(_otaWorkSignal);
|
|
_otaWorkSignal = NULL;
|
|
return;
|
|
}
|
|
|
|
LOG_INFO(TAG, "OTA worker task created with 16KB stack on Core 1");
|
|
|
|
// Create timer for scheduled checks (checks every minute if it's 3:00 AM)
|
|
_scheduledCheckTimer = xTimerCreate(
|
|
"OTA_Schedule",
|
|
pdMS_TO_TICKS(60000), // Check every minute
|
|
pdTRUE, // Auto-reload (periodic)
|
|
this, // Timer ID (pass OTAManager instance)
|
|
scheduledCheckCallback
|
|
);
|
|
|
|
if (_scheduledCheckTimer != NULL) {
|
|
xTimerStart(_scheduledCheckTimer, 0);
|
|
LOG_INFO(TAG, "OTA scheduled check timer started (will check at 3:00 AM)");
|
|
} else {
|
|
LOG_ERROR(TAG, "Failed to create OTA scheduled check timer!");
|
|
}
|
|
|
|
// 🔥 NEW: Create one-shot timer for initial boot check (5 seconds after boot)
|
|
// This prevents blocking during critical connection phase
|
|
_initialCheckTimer = xTimerCreate(
|
|
"OTA_InitCheck",
|
|
pdMS_TO_TICKS(5000), // 5 seconds delay
|
|
pdFALSE, // One-shot timer
|
|
this, // Timer ID (pass OTAManager instance)
|
|
initialCheckCallback
|
|
);
|
|
|
|
if (_initialCheckTimer != NULL) {
|
|
xTimerStart(_initialCheckTimer, 0);
|
|
LOG_INFO(TAG, "OTA initial check scheduled for 5 seconds after boot (non-blocking)");
|
|
} else {
|
|
LOG_ERROR(TAG, "Failed to create OTA initial check timer!");
|
|
}
|
|
}
|
|
|
|
void OTAManager::setFileManager(FileManager* fm) {
|
|
_fileManager = fm;
|
|
}
|
|
|
|
void OTAManager::setPlayer(Player* player) {
|
|
_player = player;
|
|
}
|
|
|
|
#if HAS_RTC
|
|
void OTAManager::setTimeKeeper(Timekeeper* tk) {
|
|
_timeKeeper = tk;
|
|
}
|
|
#endif
|
|
|
|
void OTAManager::setTelemetry(Telemetry* telemetry) {
|
|
_telemetry = telemetry;
|
|
}
|
|
|
|
// ✅ NEW: Static timer callback for initial boot check
|
|
// CRITICAL: Timer callbacks run in Timer Service task with limited stack!
|
|
// We ONLY set a flag here - actual work is done by dedicated worker task
|
|
void OTAManager::initialCheckCallback(TimerHandle_t xTimer) {
|
|
OTAManager* ota = static_cast<OTAManager*>(pvTimerGetTimerID(xTimer));
|
|
if (ota && ota->_otaWorkSignal) {
|
|
// Signal worker task to perform initial check
|
|
ota->_pendingWork = OTAWorkType::INITIAL_CHECK;
|
|
xSemaphoreGive(ota->_otaWorkSignal);
|
|
}
|
|
}
|
|
|
|
// ✅ NEW: Perform initial OTA check (async, non-blocking)
|
|
void OTAManager::performInitialCheck() {
|
|
// This runs asynchronously in worker task, won't block WebSocket/UDP/MQTT
|
|
checkForUpdates();
|
|
}
|
|
|
|
// ✅ NEW: Static timer callback for scheduled checks
|
|
// CRITICAL: Timer callbacks run in Timer Service task with limited stack!
|
|
// We ONLY set a flag here - actual work is done by dedicated worker task
|
|
void OTAManager::scheduledCheckCallback(TimerHandle_t xTimer) {
|
|
OTAManager* ota = static_cast<OTAManager*>(pvTimerGetTimerID(xTimer));
|
|
|
|
// Get current time
|
|
time_t now = time(nullptr);
|
|
struct tm* timeinfo = localtime(&now);
|
|
|
|
// Only proceed if it's exactly 3:00 AM
|
|
if (timeinfo->tm_hour == 3 && timeinfo->tm_min == 0) {
|
|
// Check if player is idle before signaling worker
|
|
if (!ota->isPlayerActive() && ota->_otaWorkSignal) {
|
|
// Signal worker task to perform scheduled check
|
|
ota->_pendingWork = OTAWorkType::SCHEDULED_CHECK;
|
|
xSemaphoreGive(ota->_otaWorkSignal);
|
|
} else if (ota->isPlayerActive()) {
|
|
LOG_WARNING(TAG, "⚠️ Player is active - skipping scheduled update check");
|
|
}
|
|
}
|
|
}
|
|
|
|
// ✅ NEW: Check for emergency updates only (called by scheduled timer)
|
|
void OTAManager::checkForEmergencyUpdates() {
|
|
if (_status != Status::IDLE) {
|
|
LOG_WARNING(TAG, "OTA check already in progress");
|
|
return;
|
|
}
|
|
|
|
String channel = _configManager.getOtaChannel();
|
|
LOG_INFO(TAG, "Checking for EMERGENCY updates on channel '%s'...", channel.c_str());
|
|
checkForUpdates(channel);
|
|
|
|
// Only proceed if emergency flag is set
|
|
if (_updateAvailable && _isEmergency) {
|
|
LOG_INFO(TAG, "🚨 EMERGENCY update detected during scheduled check - updating immediately");
|
|
update(channel);
|
|
} else if (_updateAvailable && _isMandatory) {
|
|
LOG_INFO(TAG, "⚠️ Mandatory update available, but will wait for next boot");
|
|
} else {
|
|
LOG_INFO(TAG, "✅ No emergency updates available");
|
|
}
|
|
}
|
|
|
|
void OTAManager::checkForUpdates() {
|
|
// Use the device's persisted OTA channel (default "stable")
|
|
checkForUpdates(_configManager.getOtaChannel());
|
|
}
|
|
|
|
void OTAManager::checkForUpdates(const String& channel) {
|
|
if (_status != Status::IDLE) {
|
|
LOG_WARNING(TAG, "OTA check already in progress");
|
|
return;
|
|
}
|
|
|
|
// 🔥 CRITICAL: Check network connectivity before attempting HTTP requests
|
|
if (WiFi.status() != WL_CONNECTED) { // ETHERNET DISABLED - WiFi only
|
|
LOG_WARNING(TAG, "OTA check skipped - no network connectivity");
|
|
return;
|
|
}
|
|
|
|
setStatus(Status::CHECKING_VERSION);
|
|
_lastCheckUptimeMs = millis();
|
|
LOG_INFO(TAG, "Checking for firmware updates in %s channel for %s...",
|
|
channel.c_str(), _configManager.getHardwareVariant().c_str());
|
|
|
|
if (checkVersion(channel)) {
|
|
SemVer currentVersion = getCurrentVersion();
|
|
LOG_INFO(TAG, "Current version: %s, Available version: %s (Channel: %s)",
|
|
currentVersion.toString().c_str(), _availableVersion.toString().c_str(), channel.c_str());
|
|
|
|
if (_availableVersion > currentVersion) {
|
|
_updateAvailable = true;
|
|
LOG_INFO(TAG, "New version available! Mandatory: %s, Emergency: %s",
|
|
_isMandatory ? "YES" : "NO", _isEmergency ? "YES" : "NO");
|
|
setStatus(Status::IDLE);
|
|
|
|
// Auto-update for emergency or mandatory updates.
|
|
// Emergency: apply immediately regardless of channel.
|
|
// Mandatory: apply on this boot check (any channel).
|
|
// Optional: do nothing — wait for user/MQTT trigger.
|
|
if (_isEmergency || _isMandatory) {
|
|
LOG_INFO(TAG, "OTA: %s update detected on channel '%s' — starting automatic update",
|
|
_isEmergency ? "Emergency" : "Mandatory", channel.c_str());
|
|
update(channel);
|
|
}
|
|
} else {
|
|
_updateAvailable = false;
|
|
LOG_INFO(TAG, "No new version available");
|
|
setStatus(Status::IDLE);
|
|
}
|
|
} else {
|
|
_updateAvailable = false;
|
|
setStatus(Status::FAILED, _lastError);
|
|
}
|
|
}
|
|
|
|
void OTAManager::update() {
|
|
update("stable"); // Default to stable channel
|
|
}
|
|
|
|
void OTAManager::update(const String& channel) {
|
|
if (_status != Status::IDLE) {
|
|
LOG_WARNING(TAG, "OTA update already in progress");
|
|
return;
|
|
}
|
|
|
|
if (!_updateAvailable) {
|
|
LOG_WARNING(TAG, "No update available for channel: %s", channel.c_str());
|
|
return;
|
|
}
|
|
|
|
LOG_INFO(TAG, "Starting OTA update from %s channel...", channel.c_str());
|
|
setStatus(Status::DOWNLOADING);
|
|
|
|
if (downloadAndInstall(channel)) {
|
|
setStatus(Status::SUCCESS);
|
|
LOG_INFO(TAG, "Update successfully finished. Rebooting...");
|
|
delay(1000);
|
|
ESP.restart();
|
|
} else {
|
|
setStatus(Status::FAILED, _lastError);
|
|
}
|
|
}
|
|
|
|
SemVer OTAManager::getCurrentVersion() const {
|
|
return SemVer::parse(FW_VERSION);
|
|
}
|
|
|
|
void OTAManager::setStatus(Status status, ErrorCode error) {
|
|
_status = status;
|
|
_lastError = error;
|
|
|
|
if (_statusCallback) {
|
|
_statusCallback(status, error);
|
|
}
|
|
}
|
|
|
|
void OTAManager::notifyProgress(size_t current, size_t total) {
|
|
if (_progressCallback) {
|
|
_progressCallback(current, total);
|
|
}
|
|
}
|
|
|
|
// Version checking against new FastAPI backend
|
|
// API: GET {baseUrl}/api/firmware/{hw_type}/{channel}/latest
|
|
// Response: { "version": "1.2.3", "min_fw_version": "1.0.0", "sha256": "abc...",
|
|
// "size": 123456, "update_type": "stable", "mandatory": true, "emergency": false }
|
|
bool OTAManager::checkVersion(const String& channel) {
|
|
std::vector<String> servers = _configManager.getUpdateServers();
|
|
auto& updateConfig = _configManager.getUpdateConfig();
|
|
String hwType = _configManager.getHardwareVariant();
|
|
|
|
for (size_t serverIndex = 0; serverIndex < servers.size(); serverIndex++) {
|
|
String baseUrl = servers[serverIndex];
|
|
String metadataUrl = buildLatestUrl(baseUrl, hwType, channel);
|
|
|
|
LOG_INFO(TAG, "OTA: Trying server %d/%d: %s", serverIndex + 1, servers.size(), metadataUrl.c_str());
|
|
|
|
String jsonStr;
|
|
int httpCode = -1;
|
|
|
|
for (int retryCount = 0; retryCount < updateConfig.retries; retryCount++) {
|
|
if (retryCount > 0) {
|
|
LOG_INFO(TAG, "OTA: Retry %d/%d for server %d", retryCount + 1, updateConfig.retries, serverIndex + 1);
|
|
delay(1000 * retryCount); // Exponential backoff
|
|
}
|
|
|
|
HTTPClient http;
|
|
http.setTimeout(updateConfig.timeout);
|
|
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
|
|
http.begin(metadataUrl);
|
|
|
|
httpCode = http.GET();
|
|
|
|
if (httpCode == HTTP_CODE_OK) {
|
|
jsonStr = http.getString();
|
|
}
|
|
http.end();
|
|
|
|
if (httpCode == HTTP_CODE_OK) break;
|
|
}
|
|
|
|
if (httpCode != HTTP_CODE_OK) {
|
|
LOG_ERROR(TAG, "OTA: Server %d failed after %d retries. HTTP code: %d",
|
|
serverIndex + 1, updateConfig.retries, httpCode);
|
|
continue;
|
|
}
|
|
|
|
{
|
|
DynamicJsonDocument doc(1024);
|
|
DeserializationError error = deserializeJson(doc, jsonStr);
|
|
if (error) {
|
|
LOG_ERROR(TAG, "OTA: Failed to parse metadata JSON from server %d: %s", serverIndex + 1, error.c_str());
|
|
continue;
|
|
}
|
|
|
|
// FastAPI response fields
|
|
const char* versionStr = doc["version"] | "";
|
|
if (strlen(versionStr) == 0) {
|
|
LOG_ERROR(TAG, "OTA: Missing 'version' field in metadata from server %d", serverIndex + 1);
|
|
continue;
|
|
}
|
|
_availableVersion = SemVer::parse(String(versionStr));
|
|
|
|
const char* minVersionStr = doc["min_fw_version"] | "";
|
|
_minVersion = (strlen(minVersionStr) > 0) ? SemVer::parse(String(minVersionStr)) : SemVer{0, 0, 0};
|
|
|
|
_availableChecksum = doc["sha256"] | "";
|
|
_expectedFileSize = doc["size"] | (size_t)0;
|
|
_availableDownloadPath = doc["download_url"] | "";
|
|
|
|
// update_type: "optional" | "mandatory" | "emergency"
|
|
_isMandatory = doc["mandatory"] | false;
|
|
_isEmergency = doc["emergency"] | false;
|
|
_updateChannel = channel;
|
|
|
|
// Validate the server actually responded for the channel we asked for.
|
|
const char* serverChannel = doc["channel"] | "";
|
|
if (strlen(serverChannel) > 0 && String(serverChannel) != channel) {
|
|
LOG_ERROR(TAG, "OTA: Channel mismatch! Requested: %s, Got: %s", channel.c_str(), serverChannel);
|
|
_lastError = ErrorCode::CHANNEL_MISMATCH;
|
|
continue;
|
|
}
|
|
|
|
if (_availableVersion.isZero()) {
|
|
LOG_ERROR(TAG, "OTA: Invalid version string '%s' from server %d", versionStr, serverIndex + 1);
|
|
continue;
|
|
}
|
|
|
|
if (_availableChecksum.length() != 64) {
|
|
LOG_ERROR(TAG, "OTA: Invalid sha256 length (%d) from server %d", _availableChecksum.length(), serverIndex + 1);
|
|
continue;
|
|
}
|
|
|
|
SemVer currentVersion = getCurrentVersion();
|
|
if (!_minVersion.isZero() && currentVersion < _minVersion) {
|
|
LOG_WARNING(TAG, "OTA: Server returned version %s with min_fw_version %s — server is handling upgrade chain",
|
|
versionStr, _minVersion.toString().c_str());
|
|
}
|
|
|
|
LOG_INFO(TAG, "OTA: Metadata OK from server %d — version=%s, size=%u, mandatory=%s, emergency=%s",
|
|
serverIndex + 1, versionStr, _expectedFileSize,
|
|
_isMandatory ? "YES" : "NO", _isEmergency ? "YES" : "NO");
|
|
return true;
|
|
}
|
|
}
|
|
|
|
LOG_ERROR(TAG, "OTA: All %d servers failed to provide metadata", servers.size());
|
|
_lastError = ErrorCode::HTTP_ERROR;
|
|
return false;
|
|
}
|
|
|
|
// Download and install firmware from new FastAPI backend
|
|
// API: GET {baseUrl}/api/firmware/{hw_type}/{channel}/{version}/firmware.bin
|
|
bool OTAManager::downloadAndInstall(const String& channel) {
|
|
std::vector<String> servers = _configManager.getUpdateServers();
|
|
String hwType = _configManager.getHardwareVariant();
|
|
String toVersion = _availableVersion.toString();
|
|
|
|
for (size_t serverIndex = 0; serverIndex < servers.size(); serverIndex++) {
|
|
String baseUrl = servers[serverIndex];
|
|
|
|
// Prefer the download_url returned by the server (relative path prepended with baseUrl).
|
|
// Fall back to constructing the URL locally if the server didn't return one.
|
|
String firmwareUrl;
|
|
if (_availableDownloadPath.length() > 0) {
|
|
firmwareUrl = baseUrl + _availableDownloadPath;
|
|
} else {
|
|
firmwareUrl = buildFirmwareUrl(baseUrl, hwType, channel, toVersion);
|
|
}
|
|
|
|
LOG_INFO(TAG, "OTA: Trying firmware download from server %d/%d: %s",
|
|
serverIndex + 1, servers.size(), firmwareUrl.c_str());
|
|
|
|
String fromVersion = getCurrentVersion().toString();
|
|
if (downloadDirectToFlash(firmwareUrl, _expectedFileSize, fromVersion, toVersion, channel)) {
|
|
LOG_INFO(TAG, "OTA: Firmware download and flash successful from server %d", serverIndex + 1);
|
|
return true;
|
|
} else {
|
|
LOG_WARNING(TAG, "OTA: Firmware download failed from server %d, trying next", serverIndex + 1);
|
|
}
|
|
}
|
|
|
|
LOG_ERROR(TAG, "OTA: All %d servers failed to provide firmware", servers.size());
|
|
return false;
|
|
}
|
|
|
|
// 🔥 NEW: Download directly to flash memory, bypassing SD card
|
|
bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize, const String& fromVersion, const String& toVersion, const String& channel) {
|
|
LOG_INFO(TAG, "OTA: Starting direct-to-flash download (bypassing SD card)");
|
|
|
|
HTTPClient http;
|
|
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
|
|
http.begin(url); // Let HTTPClient manage TLS internally (same as bootOtaCheck)
|
|
http.setTimeout(60000); // 60 seconds for a ~1.4MB binary
|
|
|
|
int httpCode = http.GET();
|
|
|
|
if (httpCode != HTTP_CODE_OK) {
|
|
LOG_ERROR(TAG, "Download HTTP error code: %d", httpCode);
|
|
setStatus(Status::FAILED, ErrorCode::HTTP_ERROR);
|
|
http.end();
|
|
return false;
|
|
}
|
|
|
|
int contentLength = http.getSize();
|
|
|
|
LOG_INFO(TAG, "OTA: HTTP Response Code: %d", httpCode);
|
|
LOG_INFO(TAG, "OTA: Content-Length: %d bytes", contentLength);
|
|
|
|
if (contentLength <= 0) {
|
|
LOG_ERROR(TAG, "Invalid content length");
|
|
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
|
|
http.end();
|
|
return false;
|
|
}
|
|
|
|
// Validate file size
|
|
if (expectedSize > 0 && (size_t)contentLength != expectedSize) {
|
|
LOG_ERROR(TAG, "OTA: File size mismatch! Expected: %u, Got: %d", expectedSize, contentLength);
|
|
setStatus(Status::FAILED, ErrorCode::SIZE_MISMATCH);
|
|
http.end();
|
|
return false;
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// ENTER OTA FREEZE MODE - Pause all non-critical systems
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
LOG_INFO(TAG, "OTA: Entering freeze mode - pausing TimeKeeper and Telemetry");
|
|
|
|
#if HAS_RTC
|
|
if (_timeKeeper) {
|
|
_timeKeeper->pauseClockUpdates();
|
|
}
|
|
#endif
|
|
|
|
if (_telemetry) {
|
|
_telemetry->pause();
|
|
}
|
|
|
|
// Begin OTA update to flash with MD5 validation enabled
|
|
if (!Update.begin(contentLength)) {
|
|
LOG_ERROR(TAG, "Not enough space to begin OTA update");
|
|
setStatus(Status::FAILED, ErrorCode::INSUFFICIENT_SPACE);
|
|
http.end();
|
|
|
|
// Resume systems
|
|
#if HAS_RTC
|
|
if (_timeKeeper) _timeKeeper->resumeClockUpdates();
|
|
#endif
|
|
if (_telemetry) _telemetry->resume();
|
|
|
|
return false;
|
|
}
|
|
|
|
LOG_INFO(TAG, "OTA: Update partition ready, starting stream write...");
|
|
LOG_INFO(TAG, "OTA: Checksum validation will be performed by ESP32 bootloader");
|
|
setStatus(Status::INSTALLING);
|
|
|
|
// Stream directly to flash with periodic watchdog feeding
|
|
WiFiClient* stream = http.getStreamPtr();
|
|
static uint8_t buffer[4096]; // 4KB buffer — static to avoid blowing the 8KB task stack
|
|
size_t written = 0;
|
|
size_t lastLoggedPercent = 0;
|
|
unsigned long lastWatchdogReset = millis();
|
|
|
|
while (http.connected() && written < (size_t)contentLength) {
|
|
size_t available = stream->available();
|
|
if (available) {
|
|
size_t toRead = min(available, sizeof(buffer));
|
|
size_t bytesRead = stream->readBytes(buffer, toRead);
|
|
|
|
if (bytesRead > 0) {
|
|
// Write to flash
|
|
size_t bytesWritten = Update.write(buffer, bytesRead);
|
|
|
|
if (bytesWritten != bytesRead) {
|
|
LOG_ERROR(TAG, "OTA: Flash write failed at offset %u (%u/%u bytes written)",
|
|
written, bytesWritten, bytesRead);
|
|
http.end();
|
|
|
|
// Resume systems
|
|
#if HAS_RTC
|
|
if (_timeKeeper) _timeKeeper->resumeClockUpdates();
|
|
#endif
|
|
if (_telemetry) _telemetry->resume();
|
|
|
|
setStatus(Status::FAILED, ErrorCode::WRITE_FAILED);
|
|
return false;
|
|
}
|
|
|
|
written += bytesWritten;
|
|
|
|
// Log progress every 20%
|
|
size_t currentPercent = (written * 100) / contentLength;
|
|
if (currentPercent >= lastLoggedPercent + 20) {
|
|
LOG_INFO(TAG, "OTA: Flash write progress: %u%% (%u/%u bytes)",
|
|
currentPercent, written, contentLength);
|
|
lastLoggedPercent = currentPercent;
|
|
}
|
|
}
|
|
} else {
|
|
// No data available yet — block for 1ms so IDLE0 can run and reset its watchdog.
|
|
// yield()/vPortYield() is cooperative and doesn't release the CPU long enough;
|
|
// vTaskDelay(1) actually suspends this task for one tick (~1ms).
|
|
vTaskDelay(1);
|
|
}
|
|
|
|
// Feed watchdog every 500ms to prevent timeout
|
|
if (millis() - lastWatchdogReset > 500) {
|
|
esp_task_wdt_reset();
|
|
lastWatchdogReset = millis();
|
|
}
|
|
}
|
|
|
|
http.end();
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// EXIT OTA FREEZE MODE - Resume all paused systems
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
LOG_INFO(TAG, "OTA: Exiting freeze mode - resuming TimeKeeper and Telemetry");
|
|
|
|
#if HAS_RTC
|
|
if (_timeKeeper) {
|
|
_timeKeeper->resumeClockUpdates();
|
|
}
|
|
#endif
|
|
|
|
if (_telemetry) {
|
|
_telemetry->resume();
|
|
}
|
|
|
|
if (written == (size_t)contentLength) {
|
|
LOG_INFO(TAG, "OTA: Successfully written %u bytes to flash", written);
|
|
} else {
|
|
LOG_ERROR(TAG, "OTA: Written only %u/%d bytes", written, contentLength);
|
|
setStatus(Status::FAILED, ErrorCode::WRITE_FAILED);
|
|
return false;
|
|
}
|
|
|
|
// Binary is fully written to the staged partition — report download event
|
|
postDownloadTelemetry(fromVersion, toVersion, channel);
|
|
|
|
if (Update.end(true)) { // true = set new boot partition
|
|
LOG_INFO(TAG, "OTA: Update complete!");
|
|
if (Update.isFinished()) {
|
|
setStatus(Status::SUCCESS);
|
|
// Partition committed — report flash event before reboot
|
|
postFlashTelemetry(fromVersion, toVersion, channel);
|
|
LOG_INFO(TAG, "OTA: Firmware update successful. Rebooting...");
|
|
delay(1000);
|
|
ESP.restart();
|
|
return true;
|
|
} else {
|
|
LOG_ERROR(TAG, "OTA: Update not finished");
|
|
setStatus(Status::FAILED, ErrorCode::VERIFICATION_FAILED);
|
|
return false;
|
|
}
|
|
} else {
|
|
LOG_ERROR(TAG, "OTA: Update error: %s", Update.errorString());
|
|
setStatus(Status::FAILED, ErrorCode::VERIFICATION_FAILED);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
bool OTAManager::downloadToSD(const String& url, const String& expectedChecksum, size_t expectedSize) {
|
|
if (!_fileManager) {
|
|
LOG_ERROR(TAG, "FileManager not set!");
|
|
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
|
|
return false;
|
|
}
|
|
|
|
// Ensure firmware directory exists
|
|
_fileManager->createDirectory("/firmware");
|
|
|
|
// Download to temporary file
|
|
String tempPath = "/firmware/staged_update.bin";
|
|
|
|
HTTPClient http;
|
|
http.begin(url.c_str());
|
|
|
|
// Set timeout to prevent hanging
|
|
http.setTimeout(30000); // 30 seconds
|
|
|
|
int httpCode = http.GET();
|
|
|
|
if (httpCode != HTTP_CODE_OK) {
|
|
LOG_ERROR(TAG, "Download HTTP error code: %d", httpCode);
|
|
setStatus(Status::FAILED, ErrorCode::HTTP_ERROR);
|
|
http.end();
|
|
return false;
|
|
}
|
|
|
|
int contentLength = http.getSize();
|
|
|
|
// Log HTTP response headers for debugging
|
|
LOG_INFO(TAG, "OTA: HTTP Response Code: %d", httpCode);
|
|
LOG_INFO(TAG, "OTA: Content-Length header: %d bytes", contentLength);
|
|
if (contentLength <= 0) {
|
|
LOG_ERROR(TAG, "Invalid content length");
|
|
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
|
|
http.end();
|
|
return false;
|
|
}
|
|
|
|
// ✅ NEW: Validate file size against metadata
|
|
if (expectedSize > 0 && (size_t)contentLength != expectedSize) {
|
|
LOG_ERROR(TAG, "OTA: File size mismatch! Expected: %u, Got: %d", expectedSize, contentLength);
|
|
setStatus(Status::FAILED, ErrorCode::SIZE_MISMATCH);
|
|
http.end();
|
|
return false;
|
|
}
|
|
|
|
// ✅ NEW: Check available SD card space
|
|
if (!checkAvailableSpace(contentLength)) {
|
|
LOG_ERROR(TAG, "OTA: Insufficient SD card space for update");
|
|
setStatus(Status::FAILED, ErrorCode::INSUFFICIENT_SPACE);
|
|
http.end();
|
|
return false;
|
|
}
|
|
|
|
LOG_INFO(TAG, "OTA: Starting download of %d bytes...", contentLength);
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// ENTER OTA FREEZE MODE - Pause all non-critical systems to prevent SD contention
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
LOG_INFO(TAG, "OTA: Entering freeze mode - pausing TimeKeeper and Telemetry");
|
|
|
|
#if HAS_RTC
|
|
if (_timeKeeper) {
|
|
_timeKeeper->pauseClockUpdates();
|
|
}
|
|
#endif
|
|
|
|
if (_telemetry) {
|
|
_telemetry->pause();
|
|
}
|
|
|
|
// 🔒 ACQUIRE SD CARD MUTEX - Prevents concurrent SD access
|
|
LOG_INFO(TAG, "OTA: Acquiring SD card mutex for safe file operations");
|
|
if (!SDCardMutex::getInstance().lock(10000)) { // 10 second timeout
|
|
LOG_ERROR(TAG, "OTA: Failed to acquire SD card mutex!");
|
|
#if HAS_RTC
|
|
if (_timeKeeper) _timeKeeper->resumeClockUpdates();
|
|
#endif
|
|
if (_telemetry) _telemetry->resume();
|
|
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
|
|
http.end();
|
|
return false;
|
|
}
|
|
|
|
// Delete file if it exists, before opening
|
|
if (SD.exists(tempPath.c_str())) {
|
|
LOG_INFO(TAG, "OTA: Removing existing staged update file");
|
|
if (!SD.remove(tempPath.c_str())) {
|
|
LOG_ERROR(TAG, "OTA: Failed to remove existing file!");
|
|
}
|
|
delay(200); // Give SD card time to complete deletion
|
|
}
|
|
|
|
// Open file for writing
|
|
File file = SD.open(tempPath.c_str(), FILE_WRITE);
|
|
if (!file) {
|
|
LOG_ERROR(TAG, "Failed to create temporary update file");
|
|
|
|
// Release mutex and resume systems before returning
|
|
SDCardMutex::getInstance().unlock();
|
|
#if HAS_RTC
|
|
if (_timeKeeper) _timeKeeper->resumeClockUpdates();
|
|
#endif
|
|
if (_telemetry) _telemetry->resume();
|
|
|
|
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
|
|
http.end();
|
|
return false;
|
|
}
|
|
|
|
LOG_INFO(TAG, "OTA: File opened successfully for writing (mutex locked)");
|
|
|
|
WiFiClient* stream = http.getStreamPtr();
|
|
uint8_t buffer[4096]; // ✅ Increased to 4KB for better performance
|
|
size_t written = 0;
|
|
size_t lastLoggedPercent = 0;
|
|
unsigned long lastYield = millis();
|
|
int loopsWithoutData = 0;
|
|
|
|
while (http.connected() && written < (size_t)contentLength) {
|
|
size_t available = stream->available();
|
|
if (available) {
|
|
loopsWithoutData = 0; // Reset counter when we have data
|
|
size_t toRead = min(available, sizeof(buffer));
|
|
size_t bytesRead = stream->readBytes(buffer, toRead);
|
|
|
|
if (bytesRead > 0) {
|
|
// Write to SD card
|
|
size_t bytesWritten = file.write(buffer, bytesRead);
|
|
|
|
// Check if write succeeded
|
|
if (bytesWritten != bytesRead) {
|
|
LOG_ERROR(TAG, "SD write failed at offset %u (%u/%u bytes written)", written, bytesWritten, bytesRead);
|
|
file.close();
|
|
SDCardMutex::getInstance().unlock();
|
|
http.end();
|
|
|
|
#if HAS_RTC
|
|
if (_timeKeeper) _timeKeeper->resumeClockUpdates();
|
|
#endif
|
|
if (_telemetry) _telemetry->resume();
|
|
|
|
setStatus(Status::FAILED, ErrorCode::WRITE_FAILED);
|
|
return false;
|
|
}
|
|
|
|
written += bytesWritten;
|
|
|
|
// Progress reporting
|
|
notifyProgress(written, contentLength);
|
|
|
|
// Log progress every 20%
|
|
size_t currentPercent = (written * 100) / contentLength;
|
|
if (currentPercent >= lastLoggedPercent + 20) {
|
|
LOG_INFO(TAG, "OTA: Download progress: %u%% (%u/%u bytes)",
|
|
currentPercent, written, contentLength);
|
|
lastLoggedPercent = currentPercent;
|
|
}
|
|
}
|
|
} else {
|
|
// No data available - yield to prevent tight loop
|
|
loopsWithoutData++;
|
|
if (loopsWithoutData > 10) {
|
|
// If we've waited a while with no data, give longer yield
|
|
vTaskDelay(pdMS_TO_TICKS(1)); // 1ms delay
|
|
loopsWithoutData = 0;
|
|
}
|
|
}
|
|
|
|
// 🐕 Yield every 100ms to allow other tasks (including IDLE) to run
|
|
if (millis() - lastYield > 100) {
|
|
vTaskDelay(pdMS_TO_TICKS(1)); // Just 1ms is enough
|
|
lastYield = millis();
|
|
}
|
|
}
|
|
|
|
// 🔥 CRITICAL: Flush file buffer before closing to ensure all data is written
|
|
file.flush();
|
|
delay(100); // Brief delay to ensure SD card completes write
|
|
file.close();
|
|
|
|
// 🔓 RELEASE SD CARD MUTEX - Other tasks can now access SD
|
|
SDCardMutex::getInstance().unlock();
|
|
LOG_INFO(TAG, "OTA: SD card mutex released");
|
|
|
|
http.end();
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// EXIT OTA FREEZE MODE - Resume all paused systems
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
LOG_INFO(TAG, "OTA: Exiting freeze mode - resuming TimeKeeper and Telemetry");
|
|
|
|
#if HAS_RTC
|
|
if (_timeKeeper) {
|
|
_timeKeeper->resumeClockUpdates();
|
|
}
|
|
#endif
|
|
|
|
if (_telemetry) {
|
|
_telemetry->resume();
|
|
}
|
|
|
|
if (written != (size_t)contentLength) {
|
|
LOG_ERROR(TAG, "Download incomplete: %u/%d bytes", written, contentLength);
|
|
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
|
|
return false;
|
|
}
|
|
|
|
LOG_INFO(TAG, "Download complete (%u bytes)", written);
|
|
|
|
// 🔒 Acquire mutex for file verification operations
|
|
if (!SDCardMutex::getInstance().lock(5000)) {
|
|
LOG_ERROR(TAG, "OTA: Failed to acquire SD mutex for verification");
|
|
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
|
|
return false;
|
|
}
|
|
|
|
// 🔍 DEBUG: Check actual file size on SD card
|
|
size_t actualFileSize = _fileManager->getFileSize(tempPath);
|
|
LOG_INFO(TAG, "OTA: File size on SD card: %u bytes (expected: %u)", actualFileSize, written);
|
|
|
|
if (actualFileSize != written) {
|
|
LOG_ERROR(TAG, "OTA: FILE SIZE MISMATCH ON SD CARD! Expected %u, got %u", written, actualFileSize);
|
|
SDCardMutex::getInstance().unlock();
|
|
setStatus(Status::FAILED, ErrorCode::WRITE_FAILED);
|
|
return false;
|
|
}
|
|
|
|
// 🔍 DEBUG: Read first 32 bytes for inspection
|
|
File debugFile = SD.open(tempPath.c_str());
|
|
if (debugFile) {
|
|
uint8_t debugBuffer[32];
|
|
size_t debugRead = debugFile.readBytes((char*)debugBuffer, 32);
|
|
debugFile.close();
|
|
|
|
String hexDump = "OTA: First 32 bytes (hex): ";
|
|
for (size_t i = 0; i < debugRead && i < 32; i++) {
|
|
char hex[4];
|
|
sprintf(hex, "%02X ", debugBuffer[i]);
|
|
hexDump += hex;
|
|
}
|
|
LOG_INFO(TAG, "%s", hexDump.c_str());
|
|
}
|
|
|
|
SDCardMutex::getInstance().unlock(); // Release before checksum (checksum will acquire its own)
|
|
|
|
// Verify checksum (verifyChecksum acquires its own mutex)
|
|
if (!verifyChecksum(tempPath, expectedChecksum)) {
|
|
LOG_ERROR(TAG, "Checksum verification failed after download");
|
|
_fileManager->deleteFile(tempPath);
|
|
setStatus(Status::FAILED, ErrorCode::CHECKSUM_MISMATCH);
|
|
return false;
|
|
}
|
|
|
|
LOG_INFO(TAG, "Download and checksum verification successful");
|
|
return true;
|
|
}
|
|
|
|
bool OTAManager::verifyChecksum(const String& filePath, const String& expectedChecksum) {
|
|
String calculatedChecksum = calculateSHA256(filePath);
|
|
|
|
if (calculatedChecksum.isEmpty()) {
|
|
LOG_ERROR(TAG, "Failed to calculate checksum");
|
|
return false;
|
|
}
|
|
|
|
bool match = calculatedChecksum.equalsIgnoreCase(expectedChecksum);
|
|
|
|
if (match) {
|
|
LOG_INFO(TAG, "Checksum verification passed");
|
|
} else {
|
|
LOG_ERROR(TAG, "Checksum mismatch!");
|
|
LOG_ERROR(TAG, "Expected: %s", expectedChecksum.c_str());
|
|
LOG_ERROR(TAG, "Calculated: %s", calculatedChecksum.c_str());
|
|
}
|
|
|
|
return match;
|
|
}
|
|
|
|
String OTAManager::calculateSHA256(const String& filePath) {
|
|
// 🔒 Acquire SD mutex for file reading
|
|
if (!SDCardMutex::getInstance().lock(5000)) {
|
|
LOG_ERROR(TAG, "Failed to acquire SD mutex for checksum calculation");
|
|
return "";
|
|
}
|
|
|
|
File file = SD.open(filePath.c_str());
|
|
if (!file) {
|
|
LOG_ERROR(TAG, "Failed to open file for checksum calculation: %s", filePath.c_str());
|
|
SDCardMutex::getInstance().unlock();
|
|
return "";
|
|
}
|
|
|
|
mbedtls_md_context_t ctx;
|
|
mbedtls_md_type_t md_type = MBEDTLS_MD_SHA256;
|
|
|
|
mbedtls_md_init(&ctx);
|
|
mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0);
|
|
mbedtls_md_starts(&ctx);
|
|
|
|
uint8_t buffer[1024];
|
|
size_t bytesRead;
|
|
|
|
while ((bytesRead = file.readBytes((char*)buffer, sizeof(buffer))) > 0) {
|
|
mbedtls_md_update(&ctx, buffer, bytesRead);
|
|
}
|
|
|
|
uint8_t hash[32];
|
|
mbedtls_md_finish(&ctx, hash);
|
|
mbedtls_md_free(&ctx);
|
|
|
|
file.close();
|
|
|
|
// 🔓 Release SD mutex
|
|
SDCardMutex::getInstance().unlock();
|
|
|
|
// Convert to hex string
|
|
String hashString = "";
|
|
for (int i = 0; i < 32; i++) {
|
|
String hex = String(hash[i], HEX);
|
|
if (hex.length() == 1) {
|
|
hex = "0" + hex;
|
|
}
|
|
hashString += hex;
|
|
}
|
|
|
|
return hashString;
|
|
}
|
|
|
|
bool OTAManager::installFromSD(const String& filePath) {
|
|
// 🔒 Acquire SD mutex for file size check
|
|
if (!SDCardMutex::getInstance().lock(5000)) {
|
|
LOG_ERROR(TAG, "Failed to acquire SD mutex for installation");
|
|
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
|
|
return false;
|
|
}
|
|
|
|
size_t updateSize = _fileManager->getFileSize(filePath);
|
|
|
|
SDCardMutex::getInstance().unlock(); // Release after size check
|
|
|
|
if (updateSize == 0) {
|
|
LOG_ERROR(TAG, "Empty update file");
|
|
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
|
|
return false;
|
|
}
|
|
|
|
LOG_INFO(TAG, "Installing firmware from SD (%u bytes)...", updateSize);
|
|
setStatus(Status::INSTALLING);
|
|
|
|
if (!Update.begin(updateSize)) {
|
|
LOG_ERROR(TAG, "Not enough space to begin update");
|
|
setStatus(Status::FAILED, ErrorCode::INSUFFICIENT_SPACE);
|
|
return false;
|
|
}
|
|
|
|
// 🔒 Acquire SD mutex for file reading during flash
|
|
if (!SDCardMutex::getInstance().lock(30000)) { // 30 second timeout for flash operation
|
|
LOG_ERROR(TAG, "Failed to acquire SD mutex for firmware flash");
|
|
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
|
|
return false;
|
|
}
|
|
|
|
File updateBin = SD.open(filePath.c_str());
|
|
if (!updateBin) {
|
|
LOG_ERROR(TAG, "Failed to open update file: %s", filePath.c_str());
|
|
SDCardMutex::getInstance().unlock();
|
|
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
|
|
return false;
|
|
}
|
|
|
|
size_t written = Update.writeStream(updateBin);
|
|
updateBin.close();
|
|
|
|
// 🔓 Release SD mutex after reading file
|
|
SDCardMutex::getInstance().unlock();
|
|
|
|
if (written == updateSize) {
|
|
LOG_INFO(TAG, "Update written successfully (%u bytes)", written);
|
|
} else {
|
|
LOG_ERROR(TAG, "Written only %u/%u bytes", written, updateSize);
|
|
setStatus(Status::FAILED, ErrorCode::WRITE_FAILED);
|
|
return false;
|
|
}
|
|
|
|
if (Update.end(true)) { // true = set new boot partition
|
|
LOG_INFO(TAG, "Update finished!");
|
|
if (Update.isFinished()) {
|
|
setStatus(Status::SUCCESS);
|
|
LOG_INFO(TAG, "Update complete. Cleaning up and rebooting...");
|
|
|
|
// Clean up the update files
|
|
_fileManager->deleteFile(filePath);
|
|
_fileManager->deleteFile("/firmware/staged_update.sha256");
|
|
_fileManager->deleteFile("/firmware/update.sha256");
|
|
|
|
// Clear firmware validation state to force validation of new firmware
|
|
nvs_handle_t nvsHandle;
|
|
esp_err_t err = nvs_open("fw_validator", NVS_READWRITE, &nvsHandle);
|
|
if (err == ESP_OK) {
|
|
nvs_erase_key(nvsHandle, "val_state");
|
|
nvs_erase_key(nvsHandle, "retry_count");
|
|
nvs_erase_key(nvsHandle, "fail_count");
|
|
nvs_commit(nvsHandle);
|
|
nvs_close(nvsHandle);
|
|
LOG_INFO(TAG, "✅ OTA: Firmware validation state cleared - new firmware will be validated");
|
|
} else {
|
|
LOG_WARNING(TAG, "⚠️ OTA: Failed to clear validation state: %s", esp_err_to_name(err));
|
|
}
|
|
|
|
delay(1000);
|
|
ESP.restart();
|
|
return true;
|
|
} else {
|
|
LOG_ERROR(TAG, "Update not complete");
|
|
setStatus(Status::FAILED, ErrorCode::VERIFICATION_FAILED);
|
|
return false;
|
|
}
|
|
} else {
|
|
LOG_ERROR(TAG, "Update error: %s", Update.errorString());
|
|
setStatus(Status::FAILED, ErrorCode::VERIFICATION_FAILED);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
void OTAManager::checkFirmwareUpdateFromSD() {
|
|
if (!_fileManager) {
|
|
LOG_ERROR(TAG, "FileManager not set!");
|
|
return;
|
|
}
|
|
|
|
if (!_fileManager->fileExists("/firmware/update.bin")) {
|
|
LOG_DEBUG(TAG, "No update.bin found on SD card");
|
|
return;
|
|
}
|
|
|
|
// Check for checksum file
|
|
String checksumFile = "/firmware/update.sha256";
|
|
if (!_fileManager->fileExists(checksumFile)) {
|
|
LOG_WARNING(TAG, "No checksum file found, proceeding without verification");
|
|
installFromSD("/firmware/update.bin");
|
|
return;
|
|
}
|
|
|
|
// Read expected checksum
|
|
File checksumFileHandle = SD.open(checksumFile.c_str());
|
|
if (!checksumFileHandle) {
|
|
LOG_ERROR(TAG, "Failed to open checksum file");
|
|
return;
|
|
}
|
|
|
|
String expectedChecksum = checksumFileHandle.readString();
|
|
checksumFileHandle.close();
|
|
expectedChecksum.trim();
|
|
|
|
// Verify checksum
|
|
if (!verifyChecksum("/firmware/update.bin", expectedChecksum)) {
|
|
LOG_ERROR(TAG, "Checksum verification failed, aborting update");
|
|
setStatus(Status::FAILED, ErrorCode::CHECKSUM_MISMATCH);
|
|
return;
|
|
}
|
|
|
|
LOG_INFO(TAG, "Checksum verified, proceeding with update");
|
|
installFromSD("/firmware/update.bin");
|
|
}
|
|
|
|
bool OTAManager::performManualUpdate() {
|
|
return performManualUpdate("stable");
|
|
}
|
|
|
|
bool OTAManager::performManualUpdate(const String& channel) {
|
|
if (_status != Status::IDLE) {
|
|
LOG_WARNING(TAG, "OTA update already in progress");
|
|
return false;
|
|
}
|
|
|
|
// Check for updates in the specified channel first
|
|
checkForUpdates(channel);
|
|
|
|
if (!_updateAvailable) {
|
|
LOG_WARNING(TAG, "No update available in %s channel", channel.c_str());
|
|
return false;
|
|
}
|
|
|
|
LOG_INFO(TAG, "Starting manual OTA update from %s channel (direct-to-flash)...", channel.c_str());
|
|
setStatus(Status::DOWNLOADING);
|
|
|
|
std::vector<String> servers = _configManager.getUpdateServers();
|
|
String hwType = _configManager.getHardwareVariant();
|
|
String fromVersion = getCurrentVersion().toString();
|
|
String toVersion = _availableVersion.toString();
|
|
|
|
for (size_t i = 0; i < servers.size(); i++) {
|
|
String firmwareUrl = buildFirmwareUrl(servers[i], hwType, channel, toVersion);
|
|
if (downloadDirectToFlash(firmwareUrl, _expectedFileSize, fromVersion, toVersion, channel)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// CUSTOM FIRMWARE UPDATE
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
|
|
bool OTAManager::performCustomUpdate(const String& firmwareUrl, const String& checksum, size_t fileSize, const String& version) {
|
|
if (_status != Status::IDLE) {
|
|
LOG_WARNING(TAG, "OTA update already in progress");
|
|
return false;
|
|
}
|
|
|
|
// Check if player is active
|
|
if (isPlayerActive()) {
|
|
LOG_ERROR(TAG, "Cannot perform custom update: Player is active");
|
|
setStatus(Status::FAILED, ErrorCode::PLAYER_ACTIVE);
|
|
return false;
|
|
}
|
|
|
|
LOG_INFO(TAG, "🔥 Starting CUSTOM firmware update (direct-to-flash)...");
|
|
LOG_INFO(TAG, " URL: %s", firmwareUrl.c_str());
|
|
LOG_INFO(TAG, " File Size: %u bytes", fileSize);
|
|
|
|
if (!checksum.isEmpty()) {
|
|
LOG_INFO(TAG, " Checksum: %s (NOTE: ESP32 will validate after flash)", checksum.c_str());
|
|
}
|
|
|
|
if (!version.isEmpty()) {
|
|
LOG_INFO(TAG, " Target Version: %s", version.c_str());
|
|
}
|
|
|
|
setStatus(Status::DOWNLOADING);
|
|
|
|
String fromVersion = getCurrentVersion().toString();
|
|
bool result = downloadDirectToFlash(firmwareUrl, fileSize, fromVersion, version, "custom");
|
|
|
|
if (result) {
|
|
LOG_INFO(TAG, "🚀 Custom firmware installed - device will reboot");
|
|
} else {
|
|
LOG_ERROR(TAG, "❌ Custom firmware installation failed");
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
// Hardware variant management
|
|
String OTAManager::getHardwareVariant() const {
|
|
return _configManager.getHardwareVariant();
|
|
}
|
|
|
|
void OTAManager::setHardwareVariant(const String& variant) {
|
|
LOG_WARNING(TAG, "OTAManager::setHardwareVariant is deprecated. Use ConfigManager::setHardwareVariant instead");
|
|
}
|
|
|
|
// URL builders for FastAPI backend
|
|
// GET /api/firmware/{hw_type}/{channel}/latest?current_version={semver}
|
|
// Passing current_version lets the server resolve upgrade chains and return the
|
|
// correct next hop instead of the absolute latest.
|
|
String OTAManager::buildLatestUrl(const String& baseUrl, const String& hwType, const String& channel) const {
|
|
String currentVersion = getCurrentVersion().toString();
|
|
String hwVersion = _configManager.getHwVersion();
|
|
return baseUrl + "/api/firmware/" + hwType + "/" + channel + "/latest?hw_version=" + hwVersion + "¤t_version=" + currentVersion;
|
|
}
|
|
|
|
// GET /api/firmware/{hw_type}/{channel}/{version}/info
|
|
String OTAManager::buildVersionInfoUrl(const String& baseUrl, const String& hwType, const String& channel, const String& version) const {
|
|
return baseUrl + "/api/firmware/" + hwType + "/" + channel + "/" + version + "/info";
|
|
}
|
|
|
|
// GET /api/firmware/{hw_type}/{channel}/{version}/firmware.bin
|
|
String OTAManager::buildFirmwareUrl(const String& baseUrl, const String& hwType, const String& channel, const String& version) const {
|
|
return baseUrl + "/api/firmware/" + hwType + "/" + channel + "/" + version + "/firmware.bin";
|
|
}
|
|
|
|
// ═════════════════════════════════════════════════════════════════════════════
|
|
// OTA TELEMETRY - POST events to backend for fleet visibility
|
|
// ═════════════════════════════════════════════════════════════════════════════
|
|
|
|
// Called after the firmware binary has been fully downloaded and written to flash,
|
|
// but BEFORE Update.end() is called (i.e. the new partition is staged but not yet active).
|
|
// POST /api/ota/events/download
|
|
void OTAManager::postDownloadTelemetry(const String& fromVersion, const String& toVersion, const String& channel) {
|
|
if (WiFi.status() != WL_CONNECTED) return;
|
|
|
|
std::vector<String> servers = _configManager.getUpdateServers();
|
|
if (servers.empty()) return;
|
|
|
|
// Use primary server only — this is best-effort, not critical path
|
|
String url = servers[0] + "/api/ota/events/download";
|
|
|
|
DynamicJsonDocument doc(256);
|
|
doc["device_uid"] = _configManager.getDeviceUID();
|
|
doc["hw_type"] = _configManager.getHardwareVariant();
|
|
doc["hw_version"] = _configManager.getHwVersion();
|
|
doc["from_version"] = fromVersion;
|
|
doc["to_version"] = toVersion;
|
|
doc["channel"] = channel;
|
|
|
|
String body;
|
|
serializeJson(doc, body);
|
|
|
|
HTTPClient http;
|
|
http.begin(url.c_str());
|
|
http.addHeader("Content-Type", "application/json");
|
|
http.setTimeout(5000);
|
|
|
|
int code = http.POST(body);
|
|
if (code == HTTP_CODE_OK || code == HTTP_CODE_CREATED || code == 204) {
|
|
LOG_INFO(TAG, "OTA: Download event reported to backend (HTTP %d)", code);
|
|
} else {
|
|
LOG_WARNING(TAG, "OTA: Download event POST failed (HTTP %d) — non-critical, continuing", code);
|
|
}
|
|
http.end();
|
|
}
|
|
|
|
// Called immediately after Update.end() succeeds — the new firmware is committed
|
|
// to the boot partition and the device is about to restart.
|
|
// POST /api/ota/events/flash
|
|
void OTAManager::postFlashTelemetry(const String& fromVersion, const String& toVersion, const String& channel) {
|
|
if (WiFi.status() != WL_CONNECTED) return;
|
|
|
|
std::vector<String> servers = _configManager.getUpdateServers();
|
|
if (servers.empty()) return;
|
|
|
|
String url = servers[0] + "/api/ota/events/flash";
|
|
|
|
DynamicJsonDocument doc(256);
|
|
doc["device_uid"] = _configManager.getDeviceUID();
|
|
doc["hw_type"] = _configManager.getHardwareVariant();
|
|
doc["hw_version"] = _configManager.getHwVersion();
|
|
doc["from_version"] = fromVersion;
|
|
doc["to_version"] = toVersion;
|
|
doc["channel"] = channel;
|
|
doc["sha256"] = _availableChecksum;
|
|
|
|
String body;
|
|
serializeJson(doc, body);
|
|
|
|
HTTPClient http;
|
|
http.begin(url.c_str());
|
|
http.addHeader("Content-Type", "application/json");
|
|
http.setTimeout(5000);
|
|
|
|
int code = http.POST(body);
|
|
if (code == HTTP_CODE_OK || code == HTTP_CODE_CREATED || code == 204) {
|
|
LOG_INFO(TAG, "OTA: Flash event reported to backend (HTTP %d)", code);
|
|
} else {
|
|
LOG_WARNING(TAG, "OTA: Flash event POST failed (HTTP %d) — non-critical, continuing", code);
|
|
}
|
|
http.end();
|
|
}
|
|
|
|
// ✅ NEW: Check if player is currently active
|
|
bool OTAManager::isPlayerActive() const {
|
|
if (!_player) {
|
|
// If player reference not set, assume it's safe to update
|
|
return false;
|
|
}
|
|
|
|
// Player is active if it's playing or paused (not stopped)
|
|
return _player->isCurrentlyPlaying() || _player->isCurrentlyPaused();
|
|
}
|
|
|
|
// ✅ NEW: Check if SD card has enough free space
|
|
bool OTAManager::checkAvailableSpace(size_t requiredBytes) const {
|
|
if (!_fileManager) {
|
|
LOG_WARNING(TAG, "OTA: FileManager not set, cannot check available space");
|
|
return true; // Assume it's okay if we can't check
|
|
}
|
|
|
|
// Add 10% safety margin
|
|
size_t requiredWithMargin = requiredBytes + (requiredBytes / 10);
|
|
|
|
// Get SD card info
|
|
uint64_t totalBytes = SD.totalBytes();
|
|
uint64_t usedBytes = SD.usedBytes();
|
|
uint64_t freeBytes = totalBytes - usedBytes;
|
|
|
|
LOG_INFO(TAG, "OTA: SD card space - Total: %llu MB, Used: %llu MB, Free: %llu MB",
|
|
totalBytes / (1024 * 1024),
|
|
usedBytes / (1024 * 1024),
|
|
freeBytes / (1024 * 1024));
|
|
|
|
if (freeBytes < requiredWithMargin) {
|
|
LOG_ERROR(TAG, "OTA: Insufficient space! Required: %u bytes (+10%% margin), Available: %llu bytes",
|
|
requiredWithMargin, freeBytes);
|
|
return false;
|
|
}
|
|
|
|
LOG_INFO(TAG, "OTA: Sufficient space available for update");
|
|
return true;
|
|
}
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// HEALTH CHECK IMPLEMENTATION
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
|
|
bool OTAManager::isHealthy() const {
|
|
// Check if FileManager dependency is set
|
|
if (!_fileManager) {
|
|
LOG_DEBUG(TAG, "OTAManager: Unhealthy - FileManager not set");
|
|
return false;
|
|
}
|
|
|
|
// Check if we're not in a failed state
|
|
if (_status == Status::FAILED) {
|
|
LOG_DEBUG(TAG, "OTAManager: Unhealthy - In failed state");
|
|
return false;
|
|
}
|
|
|
|
// Check if ConfigManager has valid configuration
|
|
String hwVariant = _configManager.getHardwareVariant();
|
|
if (hwVariant.isEmpty() || hwVariant == "BellSystems") {
|
|
LOG_DEBUG(TAG, "OTAManager: Unhealthy - Invalid hardware variant: %s", hwVariant.c_str());
|
|
return false;
|
|
}
|
|
|
|
if (getCurrentVersion().isZero()) {
|
|
LOG_DEBUG(TAG, "OTAManager: Unhealthy - Firmware version is 0.0.0");
|
|
return false;
|
|
}
|
|
|
|
// Check if update servers are available
|
|
std::vector<String> servers = _configManager.getUpdateServers();
|
|
if (servers.empty()) {
|
|
LOG_DEBUG(TAG, "OTAManager: Unhealthy - No update servers configured");
|
|
return false;
|
|
}
|
|
|
|
// Check if FileManager is healthy (can access SD card)
|
|
if (!_fileManager->isHealthy()) {
|
|
LOG_DEBUG(TAG, "OTAManager: Unhealthy - FileManager is unhealthy");
|
|
return false;
|
|
}
|
|
|
|
// Check if scheduled timer is running
|
|
if (_scheduledCheckTimer == NULL || xTimerIsTimerActive(_scheduledCheckTimer) == pdFALSE) {
|
|
LOG_DEBUG(TAG, "OTAManager: Unhealthy - Scheduled check timer not running");
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// WORKER TASK IMPLEMENTATION
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
|
|
// Static entry point for worker task
|
|
void OTAManager::otaWorkerTaskFunction(void* parameter) {
|
|
OTAManager* ota = static_cast<OTAManager*>(parameter);
|
|
LOG_INFO(TAG, "🔧 OTA Worker task started on Core %d with 8KB stack", xPortGetCoreID());
|
|
|
|
// Run the worker loop
|
|
ota->otaWorkerLoop();
|
|
|
|
// Should not reach here
|
|
LOG_ERROR(TAG, "❌ OTA Worker task ended unexpectedly!");
|
|
vTaskDelete(NULL);
|
|
}
|
|
|
|
// Worker task loop - waits for signals and performs OTA operations
|
|
void OTAManager::otaWorkerLoop() {
|
|
while (true) {
|
|
// Wait for work signal (blocks until semaphore is given)
|
|
if (xSemaphoreTake(_otaWorkSignal, portMAX_DELAY) == pdTRUE) {
|
|
// Check what type of work to perform
|
|
switch (_pendingWork) {
|
|
case OTAWorkType::INITIAL_CHECK:
|
|
LOG_INFO(TAG, "🚀 Worker: Performing initial OTA check");
|
|
performInitialCheck();
|
|
break;
|
|
|
|
case OTAWorkType::SCHEDULED_CHECK:
|
|
LOG_INFO(TAG, "🕒 Worker: Performing scheduled emergency check");
|
|
checkForEmergencyUpdates();
|
|
break;
|
|
|
|
case OTAWorkType::NONE:
|
|
default:
|
|
LOG_WARNING(TAG, "⚠️ Worker: Received signal but no work pending");
|
|
break;
|
|
}
|
|
|
|
// Clear pending work
|
|
_pendingWork = OTAWorkType::NONE;
|
|
}
|
|
}
|
|
}
|