Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:78 Xiaozhi esp32 Ota

From Leeroopedia
Knowledge Sources
Domains Firmware_Update, Device_Identity, Security
Last Updated 2026-10-17 00:00 GMT

Overview

Concrete tool for OTA firmware version checking, device activation, and firmware flashing provided by the XiaoZhi firmware, implementing version comparison, HMAC-SHA256 challenge-response activation, and ESP-IDF partition-based firmware download and flash.

Description

The Ota class manages the firmware update lifecycle:

  • CheckVersion(): HTTP POST to the OTA server with system info (MAC, UUID, serial number, user-agent). Parses the JSON response for firmware version/URL, MQTT/WebSocket config, server time, and activation challenge. Persists connection config to NVS.
  • Activate(): If the server returned an activation challenge, computes HMAC-SHA256(HMAC_KEY0, challenge) using the ESP32 hardware HMAC peripheral and posts the result to /activate. Retries on 202 (pending) with backoff.
  • Upgrade(url, callback): Static method that downloads a firmware binary via HTTP, validates the image header, and streams it to the inactive OTA partition in 4KB chunks using esp_ota_write(). Reports progress via callback.
  • MarkCurrentVersionValid(): Called after a successful boot on new firmware to cancel rollback protection.
  • ParseVersion() / IsNewVersionAvailable(): Semantic version comparison using dotted numeric segments.

The constructor reads the serial number from eFuse USER_DATA block (32 bytes), validating it as printable ASCII.

Usage

Reference this implementation when:

  • Implementing firmware update checks
  • Understanding the HMAC challenge-response activation flow
  • Tracing the firmware download and flash process
  • Comparing firmware versions

Code Reference

Source Location

Signature

class Ota {
public:
    Ota();
    ~Ota();

    NetworkResult<> CheckVersion();
    esp_err_t Activate();
    bool HasActivationChallenge();
    bool HasNewVersion();
    bool HasMqttConfig();
    bool HasWebsocketConfig();
    bool HasActivationCode();
    bool HasServerTime();
    bool StartUpgrade(std::function<void(int progress, size_t speed)> callback);
    static bool Upgrade(const std::string& firmware_url,
                        std::function<void(int progress, size_t speed)> callback);
    void MarkCurrentVersionValid();

    const std::string& GetFirmwareVersion() const;
    const std::string& GetCurrentVersion() const;
    const std::string& GetFirmwareUrl() const;
    const std::string& GetActivationMessage() const;
    const std::string& GetActivationCode() const;
    std::string GetCheckVersionUrl();

private:
    std::expected<std::vector<int>, std::string> ParseVersion(const std::string& version);
    bool IsNewVersionAvailable(const std::string& currentVersion,
                                 const std::string& newVersion);
    std::string GetActivationPayload();
    std::unique_ptr<Http> SetupHttp();
    // ... state fields
};

Import

#include "ota.h"

I/O Contract

Inputs

Name Type Required Description
(none for CheckVersion) — Reads OTA URL from NVS or CONFIG_OTA_URL
firmware_url const std::string& HTTP URL of firmware binary
callback std::function<void(int, size_t)> Progress callback (percentage, bytes/sec)
challenge from server Random nonce from CheckVersion response

Outputs

Name Type Description
CheckVersion() Success/failure; populates has_new_version_, firmware_url_, mqtt/websocket config
Activate() ESP_OK on success, ESP_ERR_TIMEOUT on pending (202)
Upgrade() True if firmware flashed and boot partition set
HasNewVersion() True if server returned a newer firmware version
GetFirmwareUrl() Download URL for new firmware

Usage Examples

Version Check and Activation

// In Application::CheckNewVersion()
auto result = ota_->CheckVersion();
if (!result.success) {
    ESP_LOGE(TAG, "CheckVersion failed: %s", result.error.c_str());
    return;
}

if (ota_->HasActivationChallenge()) {
    // Activation loop: retry up to 10 times
    for (int i = 0; i < 10; i++) {
        esp_err_t err = ota_->Activate();
        if (err == ESP_OK) break;
        vTaskDelay(pdMS_TO_TICKS(3000 + i * 1000));
    }
}

if (ota_->HasNewVersion()) {
    // Optionally upgrade firmware
}

Firmware Download and Flash

// In Application::UpgradeFirmware()
bool success = Ota::Upgrade(firmware_url, [](int progress, size_t speed) {
    ESP_LOGI(TAG, "OTA progress: %d%%, speed: %zu B/s", progress, speed);
    // Update display with progress
});

if (success) {
    Ota::MarkCurrentVersionValid();
    Reboot();
}

Related Pages

Implements Principle

Requires Environment

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment