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 Protocol

From Leeroopedia
Knowledge Sources
Domains Network_Protocols, Audio_Streaming
Last Updated 2026-10-17 00:00 GMT

Overview

Concrete tool for transport-neutral voice assistant communication provided by the XiaoZhi firmware, defining the Protocol base class with shared JSON message semantics and callback registration for both WebSocket and MQTT/UDP transports.

Description

Protocol is the abstract base class defining the voice assistant's network communication contract. It provides:

  • Callback registration: OnIncomingJson(), OnIncomingAudio(), OnAudioChannelOpened(), OnAudioChannelClosed(), OnNetworkError(), OnConnected(), OnDisconnected()
  • Shared JSON message methods: SendWakeWordDetected(), SendStartListening(), SendStopListening(), SendAbortSpeaking(), SendMcpMessage() — these construct JSON strings and delegate to the pure virtual SendText()
  • Server parameters: server_sample_rate_, server_frame_duration_, session_id_ — set by the concrete transport during hello handshake
  • Timeout detection: IsTimeout() returns true if no incoming message for 120 seconds

The AudioStreamPacket struct and binary protocol structs (BinaryProtocol2, BinaryProtocol3) are defined alongside the Protocol class.

Two concrete subclasses: WebsocketProtocol (WebSocket transport) and MqttProtocol (MQTT for JSON + UDP for encrypted audio).

Usage

Reference this implementation when:

  • Understanding the shared message contract between device and server
  • Adding a new JSON message type
  • Implementing a new transport (subclass Protocol)
  • Tracing callback registration and dispatch

Code Reference

Source Location

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

Signature

struct AudioStreamPacket {
    int sample_rate = 0;
    int frame_duration = 0;
    uint32_t timestamp = 0;
    uint32_t playback_id = 0;
    uint32_t media_position_ms = 0;
    std::vector<uint8_t> payload;
};

enum ListeningMode { kListeningModeAutoStop, kListeningModeManualStop, kListeningModeRealtime };
enum AbortReason { kAbortReasonNone, kAbortReasonWakeWordDetected };

class Protocol {
public:
    virtual ~Protocol() = default;
    int server_sample_rate() const;
    int server_frame_duration() const;
    const std::string& session_id() const;

    void OnIncomingAudio(std::function<void(std::unique_ptr<AudioStreamPacket>)> callback);
    void OnIncomingJson(std::function<void(const cJSON* root)> callback);
    void OnAudioChannelOpened(std::function<void()> callback);
    void OnAudioChannelClosed(std::function<void()> callback);
    void OnNetworkError(std::function<void(const std::string&)> callback);
    void OnConnected(std::function<void()> callback);
    void OnDisconnected(std::function<void()> callback);

    virtual bool Start() = 0;
    virtual bool OpenAudioChannel() = 0;
    virtual void CloseAudioChannel(bool send_goodbye = true) = 0;
    virtual bool IsAudioChannelOpened() const = 0;
    virtual bool SendAudio(std::unique_ptr<AudioStreamPacket> packet) = 0;
    virtual void SendWakeWordDetected(const std::string& wake_word);
    virtual void SendStartListening(ListeningMode mode);
    virtual void SendStopListening();
    virtual void SendAbortSpeaking(AbortReason reason);
    virtual void SendMcpMessage(const std::string& message);

protected:
    virtual bool SendText(const std::string& text) = 0;
    virtual void SetError(const std::string& message);
    virtual bool IsTimeout() const;
    // ... server_sample_rate_, session_id_, etc.
};

Import

#include "protocol.h"
// For WebSocket transport:
#include "websocket_protocol.h"
// For MQTT transport:
#include "mqtt_protocol.h"

I/O Contract

Inputs

Name Type Required Description
packet unique_ptr<AudioStreamPacket> Opus audio packet to send
root (callback) const cJSON* Parsed JSON from server (ownership stays with Protocol)
wake_word const std::string& Detected wake word text
mode ListeningMode Listening mode: auto, manual, realtime

Outputs

Name Type Description
SendAudio() True if audio sent successfully
SendStartListening() Sends {"type":"listen","state":"start","mode":"..."}
SendStopListening() Sends {"type":"listen","state":"stop"}
SendAbortSpeaking() Sends {"type":"abort","reason":"..."}
OnIncomingJson callback Fires with parsed cJSON when JSON message arrives

Usage Examples

Registering Callbacks

protocol_->OnIncomingJson([this](const cJSON* root) {
    // Runs on network task — use Schedule() for state mutations
    const char* type = cJSON_GetObjectItem(root, "type")->valuestring;
    // ... dispatch by type
});
protocol_->OnIncomingAudio([this](std::unique_ptr<AudioStreamPacket> packet) {
    audio_service_.PushPacketToDecodeQueue(std::move(packet));
});
protocol_->OnAudioChannelOpened([this]() {
    Schedule([this]() { SetDeviceState(kDeviceStateListening); });
});

Sending Voice Assistant Messages

// After wake word detection
protocol_->SendWakeWordDetected("ni hao xiao zhi");

// Start listening in auto-stop mode
protocol_->SendStartListening(kListeningModeAutoStop);

// Stop listening (manual mode)
protocol_->SendStopListening();

// Abort TTS playback (user interrupted with wake word)
protocol_->SendAbortSpeaking(kAbortReasonWakeWordDetected);

// Send MCP tool result
protocol_->SendMcpMessage(payload_json);

Related Pages

Implements Principle

Requires Environment

Page Connections

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