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

Principle:78 Xiaozhi esp32 Server Message Dispatch

From Leeroopedia
Knowledge Sources
Domains Software_Architecture, Message_Processing
Last Updated 2026-10-17 00:00 GMT

Overview

A message dispatch pattern that routes incoming JSON messages from a server to the appropriate handler based on a type field, scheduling side effects on the main task to ensure thread-safe mutation of application state from callbacks that may run on network or protocol tasks.

Description

Server message dispatch is the mechanism by which the XiaoZhi firmware processes incoming JSON messages from the voice assistant server. Messages arrive over WebSocket (text frames) or MQTT and are parsed as cJSON objects. A dispatch lambda registered via Protocol::OnIncomingJson() examines the type field and routes to the appropriate handler.

Supported message types:

  • tts: Text-to-speech control. Sub-states: start (enter speaking), stop (end speaking), sentence_start (display subtitle + optional glyph payload).
  • stt: Speech-to-text result. Contains recognized text displayed as chat message.
  • llm: LLM metadata. Contains emotion for display avatar.
  • mcp: MCP (Model Context Protocol) tool call/result. Parsed by McpServer::ParseMessage().
  • system: System commands. reboot triggers device restart.
  • notify: Notification audio playback. Contains audio URL and subtitles.
  • alert: Alert display with status, message, emotion.
  • custom: Custom board-specific message. Handled by Board::GetBoardJson() dispatch.

Critical thread-safety rule: The OnIncomingJson callback runs in the network/protocol task context, not the main task. All mutations to application state (display updates, state transitions, audio control) must be scheduled via Application::Schedule() or signaled via event bits. Direct mutation from the callback would race with the main event loop.

Usage

Use this principle when:

  • A server sends typed JSON messages that must be routed to different handlers
  • Message callbacks run on a non-main task and must not directly mutate shared state
  • The device must display TTS subtitles, emotions, and MCP tool results in real-time
  • Thread-safe state mutation is required in a single-threaded event loop architecture

Theoretical Basis

The dispatch uses a type-based router pattern:

OnIncomingJson(cJSON* root):
  type = root["type"]
  switch type:
    "tts":
      state = root["state"]
      if state == "start":  Schedule(SetDeviceState(Speaking))
      if state == "stop":   Schedule(HandleTtsStop)
      if state == "sentence_start":
        Schedule(display.SetChatMessage(text))
        if has_glyphs: Schedule(display.AddTextGlyphs(payload))
    "stt":  Schedule(display.SetChatMessage(root["text"]))
    "llm":  Schedule(display.SetEmotion(root["emotion"]))
    "mcp":  McpServer.ParseMessage(root["payload"])
    "system":
      if root["command"] == "reboot": Schedule(Reboot)
    ...

The thread-safety contract:

Network Task                Main Task
─────────────               ─────────
OnIncomingJson()            Run() event loop
  → read JSON               → Schedule() callbacks
  → Schedule(update)    →     → mutate state
  → return (no mutation)     → update display/audio

Application::Schedule(std::function<void()>&& callback) enqueues the callback onto main_tasks_ and sets MAIN_EVENT_SCHEDULE. The main loop executes all scheduled callbacks before processing other events.

Practical Guide

When implementing server message dispatch:

  • Never mutate state directly in the callback: use Schedule() or event bits.
  • Parse cJSON defensively: check for null fields before accessing.
  • Preserve cJSON ownership: the cJSON* is owned by the caller; do not free it in the handler.
  • Handle all message types: log unknown types for debugging.
  • Use cjson_utils.h RAII wrappers: for scoped cJSON management.

Related Pages

Implemented By

Page Connections

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