Principle:78 Xiaozhi esp32 Server Message Dispatch
| 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 recognizedtextdisplayed as chat message.llm: LLM metadata. Containsemotionfor display avatar.mcp: MCP (Model Context Protocol) tool call/result. Parsed byMcpServer::ParseMessage().system: System commands.reboottriggers device restart.notify: Notification audio playback. Contains audio URL and subtitles.alert: Alert display with status, message, emotion.custom: Custom board-specific message. Handled byBoard::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
cJSONdefensively: 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.hRAII wrappers: for scoped cJSON management.