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 MqttProtocol

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

Overview

Concrete tool for MQTT/UDP-based voice assistant communication provided by the XiaoZhi firmware, implementing the Protocol interface using MQTT for JSON control messages and AES-CTR encrypted UDP for low-latency audio streaming.

Description

MqttProtocol implements the Protocol abstract interface for devices using cellular modems (ML307) or constrained networks where WebSocket is impractical. It uses a hybrid transport:

  • MQTT: Carries JSON control messages (hello, listen, abort, mcp) via publish/subscribe topics. MQTT provides reliable delivery for control plane.
  • UDP: Carries binary audio packets for lower latency than MQTT QoS 0. Audio is AES-CTR encrypted using a key negotiated during the hello handshake.

Key design aspects:

  • Reconnection: A 60-second reconnect timer (MQTT_RECONNECT_INTERVAL_MS) re-establishes the MQTT client on disconnection.
  • Ping interval: 90 seconds (MQTT_PING_INTERVAL_SECONDS) keeps the connection alive.
  • Alive flag: alive_ shared pointer prevents scheduled callbacks from running after destruction.
  • Channel mutex: channel_mutex_ guards the open/close state; udp_ is shared so SendAudio() can call Send() without holding the mutex (to avoid blocking AT response parsing).
  • Sequence numbers: local_sequence_ and remote_sequence_ track UDP packet ordering.

Usage

Reference this implementation when:

  • Using MQTT/UDP transport for voice communication (cellular boards)
  • Understanding AES-CTR audio encryption
  • Tracing MQTT reconnection logic
  • Comparing transport implementations

Code Reference

Source Location

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

Signature

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

    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:
    std::shared_ptr<std::atomic<bool>> alive_;
    EventGroupHandle_t event_group_handle_;
    std::string publish_topic_;
    mutable std::mutex channel_mutex_;
    std::mutex crypto_mutex_;
    std::unique_ptr<Mqtt> mqtt_;
    std::shared_ptr<Udp> udp_;
    psa_key_id_t aes_key_id_ = PSA_KEY_ID_NULL;
    std::string aes_nonce_;
    std::string udp_server_;
    int udp_port_;
    uint32_t local_sequence_;
    uint32_t remote_sequence_;
    esp_timer_handle_t reconnect_timer_;

    bool StartMqttClient(bool report_error = false);
    void ParseServerHello(const cJSON* root);
    bool DecodeHexString(const std::string& hex, std::string& decoded);
    bool CryptAesCtr(const uint8_t* input, size_t input_size,
                     const uint8_t* nonce, uint8_t* output);
    bool SendText(const std::string& text) override;
    std::string GetHelloMessage();
};

Import

#include "mqtt_protocol.h"

I/O Contract

Inputs

Name Type Required Description
packet unique_ptr<AudioStreamPacket> Opus packet to send over UDP
mqtt/host NVS String MQTT broker host from activation
mqtt/port NVS Int MQTT broker port
mqtt/client_id NVS String MQTT client ID
mqtt/username NVS String MQTT username (optional)
mqtt/password NVS String MQTT password (optional)
mqtt/publish_topic NVS String Topic for publishing messages
mqtt/udp_server NVS String UDP audio server address
mqtt/udp_port NVS Int UDP audio server port
mqtt/aes_key NVS String AES key (hex-encoded, 128-bit)
mqtt/aes_nonce NVS String AES nonce (hex-encoded)

Outputs

Name Type Description
SendAudio() AES-CTR encrypted UDP datagram sent
SendText() JSON published via MQTT
OpenAudioChannel() True if MQTT connected and hello handshake done

Usage Examples

Sending Encrypted Audio over UDP

// In MqttProtocol::SendAudio (simplified)
std::string encrypted;
encrypted.resize(packet->payload.size());
{
    std::lock_guard<std::mutex> lock(crypto_mutex_);
    CryptAesCtr(packet->payload.data(), packet->payload.size(),
                (const uint8_t*)aes_nonce_.data(),
                (uint8_t*)encrypted.data());
}
// Send encrypted audio as UDP datagram
udp_->Send(encrypted.data(), encrypted.size());

MQTT Reconnection Timer

// Reconnect timer fires after 60s on disconnect
esp_timer_start_once(reconnect_timer_, MQTT_RECONNECT_INTERVAL_MS * 1000);
// In timer callback:
if (*alive_ && !mqtt_->IsConnected()) {
    StartMqttClient();
}

Related Pages

Implements Principle

Requires Environment

Page Connections

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