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 Application Boot

From Leeroopedia
Knowledge Sources
Domains System_Initialization, Embedded_Systems
Last Updated 2026-10-17 00:00 GMT

Overview

Concrete implementation of the staged device boot sequence provided by the XiaoZhi firmware, handling NVS initialization, board/audio setup, network callback wiring, and the main event loop.

Description

The Application singleton is the central coordinator of the XiaoZhi firmware. It owns the main event loop (Run()), the audio service, the protocol object, the OTA object, and the device state machine. The boot sequence is split across app_main(), Application::Initialize(), and Application::Run().

app_main() initializes NVS flash (erasing and reinitializing on corruption), then constructs the Application singleton via GetInstance() and calls Initialize() and Run().

Initialize() performs synchronous hardware setup (display, audio codec, audio service), wires audio service callbacks to event bits, registers the state change listener, starts the clock timer, and registers MCP tools. Network connection starts asynchronously via Board::StartNetwork().

Run() is the main event loop. It calls xEventGroupWaitBits() to block on any of 15 event bits, then dispatches to the appropriate handler. This function never returns.

Usage

Import or reference this implementation when:

  • Understanding the firmware entry point and initialization order
  • Tracing how event bits drive the main loop
  • Adding a new event bit or handler to the main loop
  • Understanding the relationship between app_main, Initialize, and Run

Code Reference

Source Location

  • Repository: XiaoZhi ESP32
  • Files: main/main.cc, main/application.cc, main/application.h

Signature

// main/main.cc
extern "C" void app_main(void);

// main/application.h
class Application {
public:
    static Application& GetInstance();
    void Initialize();
    void Run();
    bool SetDeviceState(DeviceState state);
    void Schedule(std::function<void()>&& callback);
    void Reboot();
    bool UpgradeFirmware(const std::string& url, const std::string& version = "");
    void PlaySound(const std::string_view& sound);
    AudioService& GetAudioService();
    void ResetProtocol();
    // ... see application.h for full API
private:
    void HandleNetworkConnectedEvent();
    void HandleActivationDoneEvent();
    void HandleWakeWordDetectedEvent();
    void HandleStateChangedEvent();
    void ActivationTask();
    void InitializeProtocol();
    // ...
};

Import

#include "application.h"
// app_main is the C entry point, not an import

I/O Contract

Inputs

Name Type Required Description
(none) — — app_main takes no arguments; Initialize/Run read state from the Application singleton

Outputs

Name Type Description
Initialize() Display UI shown; audio service started; MCP tools registered; network callback wired; clock timer running
Run() Main event loop dispatching 15 event bits to handlers
Schedule(callback) Callback enqueued on main_tasks_; executed on next main loop iteration
SetDeviceState(state) Returns true if transition was valid and accepted

Usage Examples

Boot Sequence

// main/main.cc — firmware entry point
extern "C" void app_main(void) {
    // 1. Initialize NVS (erase on corruption)
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        nvs_flash_erase();
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    // 2. Initialize and run the application
    auto& app = Application::GetInstance();
    app.Initialize();  // synchronous hardware setup
    app.Run();         // main event loop, never returns
}

Wiring Audio Callbacks to Event Bits

// In Application::Initialize()
AudioServiceCallbacks callbacks;
callbacks.on_send_queue_available = [this]() {
    xEventGroupSetBits(event_group_, MAIN_EVENT_SEND_AUDIO);
};
callbacks.on_wake_word_detected = [this](const std::string& wake_word) {
    xEventGroupSetBits(event_group_, MAIN_EVENT_WAKE_WORD_DETECTED);
};
callbacks.on_playback_drained = [this]() {
    xEventGroupSetBits(event_group_, MAIN_EVENT_PLAYBACK_DRAINED);
};
audio_service_.SetCallbacks(callbacks);

Scheduling State Mutation from a Callback

// In the OnIncomingJson dispatch lambda (runs on network task)
protocol_->OnIncomingJson([this](const cJSON* root) {
    const char* type = cJSON_GetObjectItem(root, "type")->valuestring;
    if (strcmp(type, "tts") == 0) {
        // Schedule state change on main task (thread-safe)
        Schedule([this]() {
            SetDeviceState(kDeviceStateSpeaking);
        });
    }
});

Related Pages

Implements Principle

Requires Environment

Page Connections

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