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 WebsocketProtocol

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

Overview

Concrete tool for WebSocket-based voice assistant communication provided by the XiaoZhi firmware, implementing the Protocol interface over a persistent WebSocket connection with versioned binary audio framing.

Description

WebsocketProtocol implements the Protocol abstract interface over a WebSocket connection. It is the primary transport for WiFi-connected devices. Key behaviors:

  • Lazy connection: Start() does nothing; the WebSocket connection is established in OpenAudioChannel()
  • Hello handshake: OpenAudioChannel() reads WebSocket URL, token, and version from NVS Settings, connects, sends a hello JSON, and waits up to 10 seconds for the server hello (via WEBSOCKET_PROTOCOL_SERVER_HELLO_EVENT)
  • Binary audio framing: Supports three protocol versions selected during hello:
    • v1: raw Opus payload (no header)
    • v2: BinaryProtocol2 (16-byte header with timestamp, big-endian)
    • v3: BinaryProtocol3 (4-byte compact header)
  • Text/JSON framing: JSON messages sent as WebSocket text frames via SendText()
  • Event-driven receive: The WebSocket library calls data callbacks; text frames trigger OnIncomingJson, binary frames trigger OnIncomingAudio

Usage

Reference this implementation when:

  • Using WebSocket as the transport for voice communication
  • Understanding binary protocol versioning
  • Tracing the hello handshake and server parameter negotiation
  • Debugging audio frame encoding/decoding

Code Reference

Source Location

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

Signature

class WebsocketProtocol : public Protocol {
public:
    WebsocketProtocol();
    ~WebsocketProtocol();

    bool Start() override;
    bool SendAudio(std::unique_ptr<AudioStreamPacket> packet) override;
    bool OpenAudioChannel() override;
    void CloseAudioChannel(bool send_goodbye = true) override;
    bool IsAudioChannelOpened() const override;

private:
    EventGroupHandle_t event_group_handle_;
    std::shared_ptr<WebSocket> websocket_;
    int version_ = 1;

    void ParseServerHello(const cJSON* root);
    bool SendText(const std::string& text) override;
    std::string GetHelloMessage();
};

Import

#include "websocket_protocol.h"

I/O Contract

Inputs

Name Type Required Description
packet unique_ptr<AudioStreamPacket> Opus packet with timestamp and payload
websocket/url NVS String WebSocket server URL from activation
websocket/token NVS String Authentication token
websocket/version NVS Int Protocol version (1, 2, or 3)

Outputs

Name Type Description
SendAudio() Binary WebSocket frame sent (v1/v2/v3 format)
OpenAudioChannel() True if hello handshake completed within 10s
ParseServerHello() Sets server_sample_rate_, server_frame_duration_, session_id_, version_

Usage Examples

Opening an Audio Channel

// In Application::ContinueWakeWordInvoke()
auto protocol = std::make_unique<WebsocketProtocol>();
protocol->OnAudioChannelOpened([this]() {
    Schedule([this]() {
        SetDeviceState(kDeviceStateListening);
        Board::GetInstance().SetPowerSaveLevel(PowerSaveLevel::PERFORMANCE);
    });
});
protocol->OnIncomingJson([this](const cJSON* root) { /* dispatch */ });
protocol->OnIncomingAudio([this](std::unique_ptr<AudioStreamPacket> p) {
    audio_service_.PushPacketToDecodeQueue(std::move(p));
});

if (protocol->OpenAudioChannel()) {
    // Channel open, hello handshake done
    protocol_ = std::move(protocol);
}

Binary Audio Frame Encoding (v2)

// In WebsocketProtocol::SendAudio (version_ == 2)
std::string serialized;
serialized.resize(sizeof(BinaryProtocol2) + packet->payload.size());
auto bp2 = (BinaryProtocol2*)serialized.data();
bp2->version = htons(version_);
bp2->type = 0;  // OPUS
bp2->timestamp = htonl(packet->timestamp);
bp2->payload_size = htonl(packet->payload.size());
memcpy(bp2->payload, packet->payload.data(), packet->payload.size());
websocket_->Send(serialized.data(), serialized.size(), true);  // binary frame

Related Pages

Implements Principle

Requires Environment

Page Connections

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