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

Heuristic:78 Xiaozhi esp32 Event Group Synchronization

From Leeroopedia
Knowledge Sources
Domains Embedded, Concurrency
Last Updated 2026-10-17 00:00 GMT

Overview

FreeRTOS event groups coordinate multi-stage audio and device initialization across tasks without blocking the main event loop.

Description

The XiaoZhi firmware uses FreeRTOS event groups (`xEventGroupCreate` / `xEventGroupSetBits` / `xEventGroupWaitBits` / `xEventGroupClearBits`) as the primary cross-task synchronization mechanism. Event bits represent runtime states such as "wake word running", "audio processor running", "audio testing running", and "audio input stop request". Tasks wait on combinations of bits using `xEventGroupWaitBits` with `portMAX_DELAY`, which blocks the calling task without consuming CPU. The main event loop uses its own event group (`MAIN_EVENT_*` bits) to receive signals from audio, network, and OTA callbacks.

This pattern avoids polling and busy-waiting. It also decouples the signaling thread from the acting thread — a callback on an audio or transport task can set a bit, and the main task picks it up on its next `xEventGroupWaitBits` call.

Usage

Use this heuristic when designing any multi-task interaction in the firmware: audio pipeline stage coordination, wake word enable/disable, network state notifications, or scheduling main-task mutations from callback contexts. Never call `Application::SetDeviceState()` or manipulate UI directly from an audio/transport callback — set an event bit instead and handle it in the main loop.

The Insight (Rule of Thumb)

  • Action: Use `xEventGroupSetBits` / `xEventGroupClearBits` from callback tasks to signal state changes; use `xEventGroupWaitBits` in the consumer task to react.
  • Value: Each subsystem gets its own event group with `#define`-ed bit masks (e.g., `AS_EVENT_WAKE_WORD_RUNNING`, `MAIN_EVENT_SEND_AUDIO`). Wait on OR-combinations of bits.
  • Trade-off: Event groups are lightweight but carry no payload — use `Application::Schedule()` for callbacks that need to pass data.
  • Compatibility: FreeRTOS event groups are available on all ESP-IDF targets. Bits are 24-bit on ESP32/S3 and 8-bit on C3/C5/C6 — avoid exceeding the platform bit width.

Reasoning

On ESP32, the audio pipeline runs across 3+ FreeRTOS tasks (input, output, opus codec) plus the AFE processing task. The main application task owns the state machine and UI. Callbacks from the audio engine (wake word detected, VAD change) fire on the AFE task. Directly calling `SetDeviceState` from the AFE task would race the main loop. Event bits provide a lock-free, non-blocking signal: the callback sets a bit, and the main loop's `xEventGroupWaitBits` wakes on the next iteration. This is the idiomatic ESP-IDF pattern for "signal without payload" across tasks.

The `AudioService::AudioInputTask` demonstrates the canonical wait pattern — it blocks on `kAudioInputActiveBits | AS_EVENT_AUDIO_INPUT_STOP_REQUEST` with `portMAX_DELAY`, then branches on which bit was set.

Code Evidence

Main event bits from `main/application.h:25-39`:

#define MAIN_EVENT_SCHEDULE             (1 << 0)
#define MAIN_EVENT_SEND_AUDIO           (1 << 1)
#define MAIN_EVENT_WAKE_WORD_DETECTED   (1 << 2)
#define MAIN_EVENT_VAD_CHANGE           (1 << 3)
#define MAIN_EVENT_ERROR                (1 << 4)
#define MAIN_EVENT_ACTIVATION_DONE      (1 << 5)
#define MAIN_EVENT_CLOCK_TICK           (1 << 6)
#define MAIN_EVENT_NETWORK_CONNECTED    (1 << 7)
#define MAIN_EVENT_NETWORK_DISCONNECTED (1 << 8)
#define MAIN_EVENT_TOGGLE_CHAT          (1 << 9)
#define MAIN_EVENT_START_LISTENING      (1 << 10)
#define MAIN_EVENT_STOP_LISTENING       (1 << 11)
#define MAIN_EVENT_STATE_CHANGED        (1 << 12)
#define MAIN_EVENT_PLAYBACK_DRAINED     (1 << 13)
#define MAIN_EVENT_STARTUP_HINT_TIMEOUT (1 << 14)

AudioService event bits from `main/audio/audio_service.h:51-54`:

#define AS_EVENT_AUDIO_TESTING_RUNNING   (1 << 0)
#define AS_EVENT_WAKE_WORD_RUNNING        (1 << 1)
#define AS_EVENT_AUDIO_PROCESSOR_RUNNING  (1 << 2)
#define AS_EVENT_AUDIO_INPUT_STOP_REQUEST (1 << 4)

Input task wait pattern from `main/audio/audio_service.cc:242-250`:

void AudioService::AudioInputTask() {
    constexpr EventBits_t kAudioInputActiveBits = AS_EVENT_AUDIO_TESTING_RUNNING |
                                                  AS_EVENT_WAKE_WORD_RUNNING |
                                                  AS_EVENT_AUDIO_PROCESSOR_RUNNING;
    while (true) {
        EventBits_t bits = xEventGroupWaitBits(
            event_group_, kAudioInputActiveBits | AS_EVENT_AUDIO_INPUT_STOP_REQUEST, pdFALSE,
            pdFALSE, portMAX_DELAY);

Wake word callback signaling from `main/audio/audio_service.cc:96-99`:

    audio_engine_->OnWakeWordDetected([this](const std::string& wake_word) {
        xEventGroupClearBits(event_group_, AS_EVENT_WAKE_WORD_RUNNING);
        if (callbacks_.on_wake_word_detected) {
            callbacks_.on_wake_word_detected(wake_word);
        }
    });

Related Pages

Page Connections

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