Files
bolar_2/main/protocol/realtime_protocol.cc
2026-11-27 16:38:11 +08:00

1547 lines
48 KiB
C++

#include "protocol/realtime_protocol.h"
#include "connectivity/wifi_types.h"
#include "core/psram_object.h"
#include "diagnostics/device_log_formatter.h"
#include "diagnostics/trace_context.h"
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <new>
#include <esp_heap_caps.h>
#include <esp_log.h>
#include <esp_random.h>
#include <freertos/task.h>
#include <sys/time.h>
namespace borla {
namespace {
constexpr const char* kTag = "RealtimeProtocol2";
constexpr const char* kConversationTag = "ConversationText2";
// Conversation lines are what a human actually reads when watching a session,
// and they used to be indistinguishable from the surrounding state-machine
// chatter. These wrap them in colour and a direction marker.
//
// The escapes are emitted directly rather than through ESP_LOG's own colouring
// because CONFIG_LOG_COLORS is off in this build — IDF adds nothing, so there
// is nothing to compose with. Set the three constants to "" if the log ever has
// to be piped somewhere that cannot handle ANSI.
constexpr const char* kUserColor = "\033[1;36m"; // bright cyan
constexpr const char* kDeviceColor = "\033[1;32m"; // bright green
constexpr const char* kEmotionColor = "\033[0;35m"; // magenta
constexpr const char* kColorReset = "\033[0m";
constexpr uint32_t kHelloBuildError = 3301;
constexpr uint32_t kHelloTimeoutError = 3302;
constexpr uint32_t kHeartbeatTimeoutError = 3303;
constexpr uint32_t kTransportSendError = 3304;
constexpr uint32_t kInvalidServerHelloError = 3305;
constexpr uint32_t kMissingCallIdError = 3390;
constexpr char kHeartbeatPingMessage[] = "{\"type\":\"ping\"}";
// ClientHello needs a ~2 KB memory snapshot plus a ~2.5 KB text buffer. Both
// used to be stack locals, which put a ~4.7 KB frame on the WebSocket task
// right underneath the TLS write. Keep the pair in PSRAM instead.
struct HelloScratch {
MemorySnapshot memory{};
std::array<char, kBinaryAudioMaximumPacketBytes> message{};
};
const char* ProtocolPromptGroup(LocalPrompt prompt)
{
if (prompt == LocalPrompt::kActivationDevice) {
return "activation_prompt";
}
if (prompt == LocalPrompt::kProvisioning) {
return "wifi_config";
}
return ToString(prompt);
}
class MutexGuard final {
public:
explicit MutexGuard(SemaphoreHandle_t mutex)
: mutex_(mutex)
{
if (mutex_ != nullptr) {
xSemaphoreTake(mutex_, portMAX_DELAY);
}
}
~MutexGuard()
{
if (mutex_ != nullptr) {
xSemaphoreGive(mutex_);
}
}
private:
SemaphoreHandle_t mutex_;
};
} // namespace
RealtimeProtocol::RealtimeProtocol(
IWebsocketTransport& transport,
IRealtimeConfigStore& config_store)
: transport_(transport),
config_store_(config_store),
reconnect_backoff_(ReconnectBackoffConfig{
1000,
kProtocolRetryMaximumMs,
2,
20,
})
{
}
RealtimeProtocol::~RealtimeProtocol()
{
if (incoming_command_ != nullptr) {
incoming_command_->~ServerCommand();
heap_caps_free(incoming_command_);
incoming_command_ = nullptr;
}
}
bool RealtimeProtocol::Initialize(const DeviceIdentity& identity)
{
if (initialized_) {
return true;
}
mutex_ = xSemaphoreCreateMutexStatic(&mutex_storage_);
if (mutex_ == nullptr || !config_store_.Load(&config_)) {
ESP_LOGE(kTag, "configuration initialization failed");
return false;
}
if (incoming_command_ == nullptr) {
incoming_command_ = static_cast<ServerCommand*>(heap_caps_malloc(
sizeof(ServerCommand),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
if (incoming_command_ == nullptr) {
ESP_LOGE(kTag, "incoming command PSRAM allocation failed");
return false;
}
new (incoming_command_) ServerCommand();
}
std::snprintf(
config_.transport.device_id.data(),
config_.transport.device_id.size(),
"%s",
identity.mac);
std::snprintf(
config_.transport.firmware_version.data(),
config_.transport.firmware_version.size(),
"%s",
identity.app_version);
if (!transport_.Initialize()) {
ESP_LOGE(kTag, "transport initialization failed");
return false;
}
const esp_timer_create_args_t timer_args = {
.callback = &RealtimeProtocol::TimerCallback,
.arg = this,
.dispatch_method = ESP_TIMER_TASK,
.name = "realtime_tick2",
.skip_unhandled_events = true,
};
if (esp_timer_create(&timer_args, &timer_) != ESP_OK) {
timer_ = nullptr;
ESP_LOGE(kTag, "lifecycle timer creation failed");
return false;
}
if (esp_timer_start_periodic(timer_, 1000ULL * 1000ULL) != ESP_OK) {
esp_timer_delete(timer_);
timer_ = nullptr;
ESP_LOGE(kTag, "lifecycle timer start failed");
return false;
}
initialized_ = true;
ESP_LOGI(kTag, "initialized hello_timeout=%lu heartbeat=%lu/%lu ms",
static_cast<unsigned long>(config_.hello_timeout_ms),
static_cast<unsigned long>(config_.heartbeat_interval_ms),
static_cast<unsigned long>(config_.heartbeat_timeout_ms));
return true;
}
void RealtimeProtocol::Open()
{
if (!initialized_) {
ESP_LOGE(kTag, "open ignored before initialization");
return;
}
bool open_now = false;
{
MutexGuard lock(mutex_);
intentional_close_ = false;
disconnect_reported_ = false;
if (phase_ == RealtimeConnectionPhase::kConnecting ||
phase_ == RealtimeConnectionPhase::kAwaitingHello ||
phase_ == RealtimeConnectionPhase::kOpen ||
phase_ == RealtimeConnectionPhase::kClosingAfterError) {
return;
}
const uint64_t now = NowMs();
if (reconnect_at_ms_ != 0 && now < reconnect_at_ms_) {
pending_open_ = true;
ESP_LOGI(kTag, "open deferred for %llu ms",
static_cast<unsigned long long>(
reconnect_at_ms_ - now));
return;
}
phase_ = RealtimeConnectionPhase::kConnecting;
diagnostics_.phase = phase_;
pending_open_ = false;
open_now = true;
}
if (open_now && !transport_.Open(config_.transport, *this)) {
OnWebsocketDisconnected(kTransportSendError);
}
}
void RealtimeProtocol::Close()
{
if (!initialized_) {
return;
}
{
MutexGuard lock(mutex_);
intentional_close_ = true;
pending_open_ = false;
disconnect_reported_ = true;
phase_ = RealtimeConnectionPhase::kClosed;
active_tts_session_ = 0;
playback_text_[0] = '\0';
ClearCallLocked();
listening_uplink_enabled_ = false;
barge_in_enabled_ = false;
tts_tail_uplink_enabled_ = false;
call_uplink_enabled_ = false;
audio_batch_.Reset();
diagnostics_.phase = phase_;
diagnostics_.active_tts_session = 0;
reconnect_at_ms_ = 0;
reconnect_backoff_.Reset();
}
transport_.Close();
}
void RealtimeProtocol::SendStartListening()
{
std::array<char, kMessageCapacity> message{};
size_t size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!builder_.BuildStartListening(
diagnostics_.session_id.data(),
message.data(),
message.size(),
&size)) {
return;
}
listening_uplink_enabled_ = true;
// A new turn begins here; the id ties the uplink audio, the ASR text
// and the reply back together across device/server logs.
TraceContext::RefreshTrace("turn");
// tts:stop only closes the producer. Reaching listen:start means the
// local playback queue has physically drained, so normal batched
// listening can replace the single-frame TTS-tail uplink.
tts_tail_uplink_enabled_ = false;
}
SendBuiltMessage(message.data(), size);
}
void RealtimeProtocol::SendStopListening()
{
std::array<char, kMessageCapacity> message{};
size_t size = 0;
size_t audio_size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!builder_.BuildStopListening(
diagnostics_.session_id.data(),
message.data(),
message.size(),
&size)) {
return;
}
listening_uplink_enabled_ = false;
TakeAudioBatchLocked(&audio_size);
}
if (audio_size != 0 &&
!transport_.SendBinary(audio_packet_.data(), audio_size)) {
RequestErrorClose(kTransportSendError);
return;
}
SendBuiltMessage(message.data(), size);
}
void RealtimeProtocol::SendAbortSpeaking(
ConversationInterruptSource source)
{
std::array<char, kMessageCapacity> message{};
size_t size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!builder_.BuildAbort(
diagnostics_.session_id.data(),
source,
playback_text_.data(),
message.data(),
message.size(),
&size)) {
return;
}
playback_text_[0] = '\0';
active_tts_session_ = 0;
tts_tail_uplink_enabled_ = false;
diagnostics_.active_tts_session = 0;
if (!UplinkEnabledLocked()) {
audio_batch_.Reset();
}
}
ESP_LOGI(kTag, "abort requested source=%s", ToString(source));
SendBuiltMessage(message.data(), size);
}
bool RealtimeProtocol::SubmitEncodedAudio(
const uint8_t* data,
size_t size)
{
size_t packet_size = 0;
bool low_latency_barge_in = false;
size_t batch_frames = 0;
uint64_t trace_sequence = 0;
uint64_t trace_send_ms = 0;
bool trace_due = false;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!UplinkEnabledLocked()) {
return false;
}
low_latency_barge_in =
barge_in_enabled_ &&
(active_tts_session_ != 0 || tts_tail_uplink_enabled_) &&
!listening_uplink_enabled_ && !call_uplink_enabled_;
if (low_latency_barge_in) {
// A TTS session starts only after the normal listen path has
// flushed. Do not carry a stale partial batch into the low-latency
// barge-in window.
audio_batch_.Reset();
if (!BuildBinaryAudioSingleFrame(
data,
size,
audio_packet_.data(),
audio_packet_.size(),
&packet_size)) {
return false;
}
} else if (!audio_batch_.Push(data, size)) {
return false;
}
if (low_latency_barge_in) {
// Send below without waiting for the normal five-frame batch.
batch_frames = 1;
} else if (!audio_batch_.Full()) {
return true;
} else {
// Read the count before TakeAudioBatchLocked resets the builder.
batch_frames = audio_batch_.FrameCount();
if (!TakeAudioBatchLocked(&packet_size)) {
return false;
}
}
trace_sequence = ++trace_audio_batch_sequence_;
trace_send_ms = NowMs();
trace_due = ShouldTraceAudioBatchLocked(
trace_sequence, batch_frames, packet_size, trace_send_ms);
}
if (!transport_.SendBinary(
audio_packet_.data(), packet_size)) {
return false;
}
if (trace_due) {
// After the audio, so the marker can never delay the frames it
// describes, and outside the lock because SendBuiltMessage takes it.
SendAudioBatchTrace(
trace_sequence, batch_frames, packet_size, trace_send_ms);
}
return true;
}
int64_t RealtimeProtocol::EpochMs()
{
struct timeval now {};
if (gettimeofday(&now, nullptr) != 0) {
return 0;
}
// Before NTP lands the clock reads 1970. Reporting that as an epoch would
// make the server compute a 56-year skew, so say "unknown" instead.
if (now.tv_sec < 1700000000) {
return 0;
}
return static_cast<int64_t>(now.tv_sec) * 1000 +
now.tv_usec / 1000;
}
bool RealtimeProtocol::ShouldTraceAudioBatchLocked(
uint64_t sequence,
size_t frames,
size_t bytes,
uint64_t now_ms)
{
if (last_trace_audio_batch_ms_ == 0 || sequence == 1) {
last_trace_audio_batch_ms_ = now_ms;
last_trace_audio_batch_frames_ = frames;
last_trace_audio_batch_bytes_ = bytes;
return true;
}
const size_t previous_bytes =
last_trace_audio_batch_bytes_ != 0
? last_trace_audio_batch_bytes_
: 1;
const size_t byte_delta =
bytes > last_trace_audio_batch_bytes_
? bytes - last_trace_audio_batch_bytes_
: last_trace_audio_batch_bytes_ - bytes;
const bool frames_changed =
frames != last_trace_audio_batch_frames_;
const bool bytes_changed =
byte_delta >= kAudioTraceMinimumByteDelta &&
static_cast<float>(byte_delta) /
static_cast<float>(previous_bytes) >=
kAudioTraceRelativeChange;
const bool heartbeat =
now_ms >= last_trace_audio_batch_ms_ &&
now_ms - last_trace_audio_batch_ms_ >=
kAudioTraceHeartbeatMs;
if (!frames_changed && !bytes_changed && !heartbeat) {
return false;
}
last_trace_audio_batch_ms_ = now_ms;
last_trace_audio_batch_frames_ = frames;
last_trace_audio_batch_bytes_ = bytes;
return true;
}
void RealtimeProtocol::SendAudioBatchTrace(
uint64_t sequence,
size_t frames,
size_t bytes,
uint64_t client_send_ms)
{
std::array<char, kTraceMarkerCapacity> marker{};
size_t size = 0;
if (!builder_.BuildTraceMarker(
TraceContext::TraceId(),
"ws.audio_batch.send",
sequence,
frames,
bytes,
client_send_ms,
EpochMs(),
marker.data(),
marker.size(),
&size)) {
return;
}
SendBuiltMessage(marker.data(), size);
}
void RealtimeProtocol::FlushEncodedAudio()
{
size_t packet_size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!TakeAudioBatchLocked(&packet_size)) {
return;
}
}
if (!transport_.SendBinary(
audio_packet_.data(), packet_size)) {
ESP_LOGW(kTag, "audio batch flush dropped by transport");
}
}
bool RealtimeProtocol::SendSensorMessage(
const char* data,
size_t size)
{
if (data == nullptr || size == 0 ||
size >= kMessageCapacity) {
return false;
}
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen) {
return false;
}
}
return transport_.SendTelemetryText(data, size);
}
bool RealtimeProtocol::SendAlarmFired(
int32_t alarm_id,
int64_t fired_at_epoch)
{
std::array<char, kMessageCapacity> message{};
size_t size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!builder_.BuildAlarmFired(
alarm_id,
fired_at_epoch,
message.data(),
message.size(),
&size)) {
return false;
}
}
return SendBuiltMessage(message.data(), size);
}
void RealtimeProtocol::SendAcceptCall()
{
std::array<char, kMessageCapacity> message{};
size_t size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!builder_.BuildCallAction(
"accept",
active_call_id_.data(),
message.data(),
message.size(),
&size)) {
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError,
kMissingCallIdError));
return;
}
}
SendBuiltMessage(message.data(), size);
}
void RealtimeProtocol::SendHangupCall()
{
std::array<char, kMessageCapacity> message{};
size_t size = 0;
size_t audio_size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!builder_.BuildCallAction(
"hangup",
active_call_id_.data(),
message.data(),
message.size(),
&size)) {
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError,
kMissingCallIdError));
return;
}
call_uplink_enabled_ = false;
TakeAudioBatchLocked(&audio_size);
}
if (audio_size != 0 &&
!transport_.SendBinary(audio_packet_.data(), audio_size)) {
RequestErrorClose(kTransportSendError);
return;
}
SendBuiltMessage(message.data(), size);
}
void RealtimeProtocol::SendButtonClick(uint8_t click_count)
{
std::array<char, kMessageCapacity> message{};
size_t size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!builder_.BuildButton(
click_count,
message.data(),
message.size(),
&size)) {
return;
}
}
SendBuiltMessage(message.data(), size);
}
void RealtimeProtocol::SendGoodbye()
{
std::array<char, kMessageCapacity> message{};
size_t size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!builder_.BuildGoodbye(
message.data(), message.size(), &size)) {
return;
}
}
SendBuiltMessage(message.data(), size);
}
void RealtimeProtocol::SendLocalPlaybackState(
LocalPrompt prompt,
bool started)
{
std::array<char, kMessageCapacity> message{};
size_t size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!builder_.BuildLocalPlaybackState(
ProtocolPromptGroup(prompt),
started,
message.data(),
message.size(),
&size)) {
return;
}
}
SendBuiltMessage(message.data(), size);
}
bool RealtimeProtocol::SendFriendAdd(
const char* local_mac,
const char* local_name,
const char* remote_mac,
const char* remote_name)
{
std::array<char, kMessageCapacity> message{};
size_t size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!builder_.BuildFriendAdd(
local_mac,
local_name,
remote_mac,
remote_name,
message.data(),
message.size(),
&size)) {
return false;
}
}
return SendBuiltMessage(message.data(), size);
}
bool RealtimeProtocol::SendOtaNotify(
const char* text,
bool optional)
{
std::array<char, kMessageCapacity> message{};
size_t size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!builder_.BuildOtaNotify(
text,
optional,
message.data(),
message.size(),
&size)) {
return false;
}
}
return SendBuiltMessage(message.data(), size);
}
void RealtimeProtocol::RequestConnectionErrorPrompt()
{
if (remote_behavior_config_ == nullptr) {
return;
}
Publish(AppEvent::Make(
AppEventType::kLocalPromptRequested,
0,
static_cast<int32_t>(
remote_behavior_config_->ServerUnreachablePrompt()),
static_cast<uint32_t>(PlaybackPriority::kSystem)));
}
RealtimeDiagnostics RealtimeProtocol::GetDiagnostics() const
{
MutexGuard lock(mutex_);
return diagnostics_;
}
uint32_t RealtimeProtocol::ActiveTtsSession() const
{
MutexGuard lock(mutex_);
return active_tts_session_;
}
void RealtimeProtocol::OnWebsocketConnected()
{
auto scratch = MakePsramObject<HelloScratch>();
if (!scratch) {
ESP_LOGE(kTag, "ClientHello scratch allocation failed");
RequestErrorClose(kHelloBuildError);
return;
}
std::array<char, kMessageCapacity>& hello = scratch->message;
size_t hello_size = 0;
bool close_immediately = false;
MemorySnapshot& memory = scratch->memory;
if (memory_cache_ != nullptr) {
memory_cache_->CopySnapshot(&memory);
}
const bool has_memory =
memory_cache_ != nullptr && memory.HasData();
{
MutexGuard lock(mutex_);
if (intentional_close_) {
close_immediately = true;
} else {
const uint64_t now = NowMs();
disconnect_reported_ = false;
phase_ = RealtimeConnectionPhase::kAwaitingHello;
diagnostics_.phase = phase_;
hello_deadline_ms_ = now + config_.hello_timeout_ms;
last_incoming_ms_ = now;
last_ping_ms_ = now;
last_status_ms_ = now;
diagnostics_.last_incoming_ms = now;
bool built = builder_.BuildHello(
config_.transport.protocol_version,
has_memory ? &memory : nullptr,
hello.data(),
hello.size(),
&hello_size);
if (!built && has_memory) {
ESP_LOGW(kTag,
"memory cache omitted because hello exceeds capacity");
built = builder_.BuildHello(
config_.transport.protocol_version,
hello.data(),
hello.size(),
&hello_size);
}
if (!built) {
phase_ = RealtimeConnectionPhase::kClosingAfterError;
diagnostics_.phase = phase_;
}
}
}
if (close_immediately) {
transport_.Close();
return;
}
if (hello_size == 0) {
RequestErrorClose(kHelloBuildError);
return;
}
if (!SendBuiltMessage(hello.data(), hello_size)) {
RequestErrorClose(kTransportSendError);
return;
}
ESP_LOGI(kTag,
"ClientHello queued stack_free_bytes=%u",
static_cast<unsigned>(
uxTaskGetStackHighWaterMark(nullptr)));
}
void RealtimeProtocol::OnWebsocketDisconnected(int error_code)
{
bool publish_disconnected = false;
bool server_was_reachable = false;
{
MutexGuard lock(mutex_);
if (intentional_close_) {
phase_ = RealtimeConnectionPhase::kClosed;
diagnostics_.phase = phase_;
return;
}
if (!disconnect_reported_) {
publish_disconnected = true;
disconnect_reported_ = true;
}
server_was_reachable =
phase_ == RealtimeConnectionPhase::kOpen;
phase_ = RealtimeConnectionPhase::kClosed;
active_tts_session_ = 0;
playback_text_[0] = '\0';
ClearCallLocked();
listening_uplink_enabled_ = false;
barge_in_enabled_ = false;
tts_tail_uplink_enabled_ = false;
call_uplink_enabled_ = false;
audio_batch_.Reset();
diagnostics_.phase = phase_;
diagnostics_.active_tts_session = 0;
diagnostics_.transport_error_count++;
ScheduleReconnectLocked(NowMs());
}
// Heap snapshot on the same line: every disconnect so far has been an
// internal-RAM starvation symptom (esp-aes alloc, select() ENOMEM), and
// the periodic diagnostics line is too sparse to catch the trough.
ESP_LOGW(kTag,
"transport disconnected error=%d internal_free=%u largest=%u",
error_code,
static_cast<unsigned>(
heap_caps_get_free_size(MALLOC_CAP_INTERNAL)),
static_cast<unsigned>(
heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)));
if (publish_disconnected) {
Publish(AppEvent::Make(
AppEventType::kRealtimeDisconnected,
static_cast<uint32_t>(
error_code < 0 ? -error_code : error_code)));
if (!server_was_reachable &&
remote_behavior_config_ != nullptr) {
Publish(AppEvent::Make(
AppEventType::kLocalPromptRequested,
0,
static_cast<int32_t>(
remote_behavior_config_->
ServerUnreachablePrompt()),
static_cast<uint32_t>(
PlaybackPriority::kSystem)));
}
}
}
void RealtimeProtocol::OnWebsocketText(
const char* data,
size_t size)
{
if (incoming_command_ == nullptr ||
!dispatcher_.ParseInto(data, size, incoming_command_)) {
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError, 3101));
return;
}
const ServerCommand& command = *incoming_command_;
if (command.type == ServerCommandType::kHello) {
ESP_LOGI(kTag,
"ServerHello parsed stack_free_bytes=%u",
static_cast<unsigned>(
uxTaskGetStackHighWaterMark(nullptr)));
}
{
MutexGuard lock(mutex_);
last_incoming_ms_ = NowMs();
diagnostics_.last_incoming_ms = last_incoming_ms_;
diagnostics_.received_text_count++;
if (command.type == ServerCommandType::kInvalid) {
diagnostics_.invalid_message_count++;
} else if (
command.type == ServerCommandType::kUnsupported) {
diagnostics_.unsupported_message_count++;
}
}
HandleCommand(command);
}
void RealtimeProtocol::OnWebsocketBinary(
const uint8_t* data,
size_t size)
{
IRealtimeBinarySink* sink = nullptr;
uint32_t session_id = 0;
{
MutexGuard lock(mutex_);
last_incoming_ms_ = NowMs();
diagnostics_.last_incoming_ms = last_incoming_ms_;
diagnostics_.received_binary_count++;
sink = binary_sink_;
session_id = active_call_session_ != 0
? active_call_session_
: active_tts_session_;
}
if (sink == nullptr || session_id == 0) {
ESP_LOGD(kTag,
"binary frame ignored without sink/session size=%u",
static_cast<unsigned>(size));
return;
}
class PlaybackVisitor final : public IBinaryAudioFrameVisitor {
public:
PlaybackVisitor(
IRealtimeBinarySink& sink,
uint32_t session_id)
: sink_(sink), session_id_(session_id)
{
}
bool OnOpusFrame(
const uint8_t* frame,
size_t frame_size) override
{
sink_.OnRealtimeBinary(
frame, frame_size, session_id_);
return true;
}
private:
IRealtimeBinarySink& sink_;
uint32_t session_id_;
};
PlaybackVisitor visitor(*sink, session_id);
size_t frames = 0;
if (!VisitBinaryAudioPacket(
data, size, visitor, &frames)) {
{
MutexGuard lock(mutex_);
diagnostics_.invalid_message_count++;
}
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError, 3201));
}
}
void RealtimeProtocol::TimerCallback(void* context)
{
static_cast<RealtimeProtocol*>(context)->OnTimer();
}
void RealtimeProtocol::OnTimer()
{
bool open_transport = false;
bool send_ping = false;
bool send_status = false;
uint32_t close_error = 0;
{
MutexGuard lock(mutex_);
const uint64_t now = NowMs();
if (!intentional_close_ &&
pending_open_ &&
phase_ == RealtimeConnectionPhase::kClosed &&
now >= reconnect_at_ms_) {
pending_open_ = false;
phase_ = RealtimeConnectionPhase::kConnecting;
diagnostics_.phase = phase_;
open_transport = true;
} else if (
phase_ == RealtimeConnectionPhase::kAwaitingHello &&
now >= hello_deadline_ms_) {
phase_ = RealtimeConnectionPhase::kClosingAfterError;
diagnostics_.phase = phase_;
close_error = kHelloTimeoutError;
} else if (phase_ == RealtimeConnectionPhase::kOpen) {
if (now - last_incoming_ms_ >=
config_.heartbeat_timeout_ms) {
phase_ = RealtimeConnectionPhase::kClosingAfterError;
diagnostics_.phase = phase_;
close_error = kHeartbeatTimeoutError;
} else if (
now - last_ping_ms_ >=
config_.heartbeat_interval_ms) {
last_ping_ms_ = now;
send_ping = true;
}
if (now - last_status_ms_ >= kStatusIntervalMs) {
// Stamp here so a suppressed send (invalid battery sample)
// still paces the next attempt one interval out.
last_status_ms_ = now;
send_status = true;
}
}
}
if (open_transport &&
!transport_.Open(config_.transport, *this)) {
OnWebsocketDisconnected(kTransportSendError);
}
if (send_ping && !SendBuiltMessage(
kHeartbeatPingMessage,
sizeof(kHeartbeatPingMessage) - 1)) {
close_error = kTransportSendError;
}
if (send_status && close_error == 0) {
SendStatusSnapshot();
}
if (close_error != 0) {
RequestErrorClose(close_error);
}
}
void RealtimeProtocol::HandleCommand(
const ServerCommand& command)
{
switch (command.type) {
case ServerCommandType::kInvalid: {
bool invalid_hello = false;
{
MutexGuard lock(mutex_);
invalid_hello =
phase_ == RealtimeConnectionPhase::kAwaitingHello;
}
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError,
command.error_id));
if (invalid_hello) {
RequestErrorClose(kInvalidServerHelloError);
}
return;
}
case ServerCommandType::kUnsupported:
ESP_LOGD(kTag, "unsupported server message ignored");
return;
case ServerCommandType::kHello:
HandleHello(command);
return;
case ServerCommandType::kPing: {
std::array<char, kHeartbeatMessageCapacity> pong{};
size_t size = 0;
if (builder_.BuildPong(
pong.data(), pong.size(), &size)) {
SendBuiltMessage(pong.data(), size);
}
return;
}
case ServerCommandType::kPong:
case ServerCommandType::kTtsSentenceEnd:
return;
case ServerCommandType::kSttText:
ESP_LOGI(
kConversationTag,
"%s>>> 用户 | %s%s",
kUserColor,
command.conversation_text.data(),
kColorReset);
return;
case ServerCommandType::kLlmEmotion:
ESP_LOGI(
kConversationTag,
"%s .. 情绪 | %s%s",
kEmotionColor,
command.conversation_text[0] == '\0'
? "-"
: command.conversation_text.data(),
kColorReset);
return;
case ServerCommandType::kTtsSentenceStart: {
ESP_LOGI(
kConversationTag,
"%s<<< 播乐 | %s%s",
kDeviceColor,
command.conversation_text.data(),
kColorReset);
// Remember what the speaker is about to say, so an abort mid-sentence
// can tell the server where the child stopped listening.
MutexGuard lock(mutex_);
// std::strncpy(
// playback_text_.data(),
// command.conversation_text.data(),
// playback_text_.size() - 1);
strlcpy(playback_text_.data(),command.conversation_text.data(),playback_text_.size());
playback_text_[playback_text_.size() - 1] = '\0';
return;
}
case ServerCommandType::kBargeIn:
switch (command.barge_in_state) {
case BargeInDecisionState::kCandidate:
Publish(AppEvent::Make(
AppEventType::kBargeInCandidate));
return;
case BargeInDecisionState::kRejected:
Publish(AppEvent::Make(
AppEventType::kBargeInRejected));
return;
case BargeInDecisionState::kConfirmed:
{
MutexGuard lock(mutex_);
active_tts_session_ = 0;
playback_text_[0] = '\0';
tts_tail_uplink_enabled_ = false;
diagnostics_.active_tts_session = 0;
audio_batch_.Reset();
}
Publish(AppEvent::Make(
AppEventType::kBargeInConfirmed));
return;
case BargeInDecisionState::kNone:
return;
}
return;
case ServerCommandType::kControl: {
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen) {
return;
}
if (command.control_action ==
RemoteControlAction::kBargeIn) {
barge_in_enabled_ = command.control_value != 0;
if (!barge_in_enabled_) {
tts_tail_uplink_enabled_ = false;
}
if (!UplinkEnabledLocked()) {
audio_batch_.Reset();
}
}
}
switch (command.control_action) {
case RemoteControlAction::kVolume:
Publish(AppEvent::Make(
AppEventType::kAudioVolumeRequested,
0,
command.control_value));
return;
case RemoteControlAction::kWakeWord:
Publish(AppEvent::Make(
AppEventType::kWakeWordControlRequested,
0,
command.control_value));
return;
case RemoteControlAction::kBargeIn:
Publish(AppEvent::Make(
AppEventType::kBargeInControlRequested,
0,
command.control_value));
return;
case RemoteControlAction::kLightSleep:
Publish(AppEvent::Make(
AppEventType::kRemoteIdleSleepRequested));
return;
case RemoteControlAction::kLedAlert:
Publish(AppEvent::Make(
AppEventType::kLedAlertRequested,
0,
command.control_value));
return;
case RemoteControlAction::kNone:
return;
}
return;
}
case ServerCommandType::kTtsStart: {
uint32_t session_id = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen) {
return;
}
session_id = AllocateTtsSessionLocked();
active_tts_session_ = session_id;
tts_tail_uplink_enabled_ = false;
diagnostics_.active_tts_session = session_id;
}
Publish(AppEvent::Make(
AppEventType::kTtsStarted, session_id));
return;
}
case ServerCommandType::kTtsStop: {
uint32_t session_id = 0;
bool tail_uplink = false;
{
MutexGuard lock(mutex_);
session_id = active_tts_session_;
active_tts_session_ = 0;
// The sentence finished on its own — a later abort must not report
// it as still playing.
playback_text_[0] = '\0';
// Keep the microphone/AEC path open while queued speaker frames
// are still draining. SendStartListening() closes this tail lane
// when playback is physically empty.
tts_tail_uplink_enabled_ =
session_id != 0 && barge_in_enabled_;
tail_uplink = tts_tail_uplink_enabled_;
diagnostics_.active_tts_session = 0;
if (!UplinkEnabledLocked()) {
audio_batch_.Reset();
}
}
if (session_id != 0) {
ESP_LOGI(
kTag,
"tts producer stopped session=%lu tail_uplink=%d",
static_cast<unsigned long>(session_id),
tail_uplink ? 1 : 0);
Publish(AppEvent::Make(
AppEventType::kTtsStreamEnded, session_id));
}
return;
}
case ServerCommandType::kPlayLocal:
if (command.soft_off_after_playback) {
Publish(AppEvent::Make(
AppEventType::kShutdownPromptRequested));
} else {
Publish(AppEvent::Make(
AppEventType::kLocalPromptRequested,
command.prompt_index < 0
? 0
: static_cast<uint32_t>(
command.prompt_index) + 1U,
static_cast<int32_t>(command.local_prompt),
static_cast<uint32_t>(
command.playback_priority)));
}
return;
case ServerCommandType::kPlayLocalSequence:
if (local_sequence_handler_ == nullptr ||
!local_sequence_handler_->StartLocalSequence(
command.local_sequence)) {
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError, 3113));
}
return;
case ServerCommandType::kMemorySync:
if (memory_cache_ == nullptr ||
!memory_cache_->Update(command.memory)) {
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError, 3114));
}
return;
case ServerCommandType::kSetTimer:
if (schedule_handler_ == nullptr ||
!schedule_handler_->AddReminder(
command.duration_seconds)) {
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError, 3110));
}
return;
case ServerCommandType::kCancelTimer:
if (schedule_handler_ != nullptr) {
schedule_handler_->CancelReminder(
command.timer_cancel_scope);
}
return;
case ServerCommandType::kSetAlarm:
if (schedule_handler_ == nullptr ||
!schedule_handler_->SetAlarm(command.alarm)) {
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError, 3111));
}
return;
case ServerCommandType::kDeleteAlarm:
if (schedule_handler_ != nullptr) {
schedule_handler_->DeleteAlarm(command.alarm_id);
}
return;
case ServerCommandType::kSyncAlarms:
if (schedule_handler_ == nullptr ||
!schedule_handler_->SyncAlarms(command.alarms)) {
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError, 3112));
}
return;
case ServerCommandType::kAlarmConfig:
if (schedule_handler_ != nullptr) {
schedule_handler_->SetAlarmToneIndices(
command.set_tone_index,
command.wake_tone_index);
}
return;
case ServerCommandType::kCall: {
uint32_t session_id = 0;
AppEventType event_type = AppEventType::kCallEnded;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen) {
return;
}
const bool same_call =
active_call_id_[0] != '\0' &&
std::strcmp(
active_call_id_.data(),
command.call_id.data()) == 0;
if (command.call_state == CallSignalState::kRing ||
command.call_state == CallSignalState::kInvite) {
active_call_id_ = command.call_id;
active_call_session_ = AllocateCallSessionLocked();
diagnostics_.active_call_session =
active_call_session_;
active_tts_session_ = 0;
playback_text_[0] = '\0';
tts_tail_uplink_enabled_ = false;
diagnostics_.active_tts_session = 0;
listening_uplink_enabled_ = false;
call_uplink_enabled_ = false;
audio_batch_.Reset();
session_id = active_call_session_;
event_type =
command.call_state == CallSignalState::kInvite
? AppEventType::kIncomingCall
: AppEventType::kOutgoingCall;
} else if (
command.call_state == CallSignalState::kConnected &&
same_call) {
session_id = active_call_session_;
call_uplink_enabled_ = true;
event_type = AppEventType::kCallConnected;
} else if (
(command.call_state == CallSignalState::kEnded ||
command.call_state == CallSignalState::kMissed) &&
same_call) {
session_id = active_call_session_;
ClearCallLocked();
audio_batch_.Reset();
event_type = AppEventType::kCallEnded;
} else {
return;
}
}
Publish(AppEvent::Make(event_type, session_id));
return;
}
case ServerCommandType::kEnterProvisioning:
Publish(AppEvent::Make(
AppEventType::kProvisioningRequested));
return;
case ServerCommandType::kError:
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError,
command.error_id));
return;
}
}
void RealtimeProtocol::HandleHello(const ServerCommand& command)
{
bool accepted = false;
{
MutexGuard lock(mutex_);
if (phase_ == RealtimeConnectionPhase::kAwaitingHello) {
diagnostics_.session_id = command.session_id;
phase_ = RealtimeConnectionPhase::kOpen;
diagnostics_.phase = phase_;
reconnect_backoff_.Reset();
reconnect_at_ms_ = 0;
pending_open_ = false;
accepted = true;
}
}
if (!accepted) {
ESP_LOGW(kTag, "unexpected duplicate ServerHello ignored");
return;
}
// Correlation scopes: the server owns the session id, the device opens a
// new turn scope for everything that follows this hello.
TraceContext::SetSession(command.session_id.data());
TraceContext::RefreshTrace("ws");
SyncClock(command);
if (device_profile_sink_ != nullptr &&
command.device_name[0] != '\0') {
device_profile_sink_->SetDeviceName(
command.device_name.data());
}
if (remote_behavior_config_ != nullptr) {
const bool button_saved =
remote_behavior_config_->UpdateButtonActions(
command.triple_click_action,
command.quadruple_click_action);
const bool prompts_saved =
remote_behavior_config_->UpdateConnectionPrompts(
command.has_server_unreachable_prompt,
command.server_unreachable_prompt,
command.has_no_network_prompt,
command.no_network_prompt);
if (!button_saved || !prompts_saved) {
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError, 3115));
}
}
ESP_LOGI(kTag,
"ServerHello accepted session=%s output=%luHz frame=%ums",
command.session_id.data(),
static_cast<unsigned long>(command.output_sample_rate),
static_cast<unsigned>(command.frame_duration_ms));
Publish(AppEvent::Make(AppEventType::kRealtimeConnected));
SendStatusSnapshot();
}
void RealtimeProtocol::SendStatusSnapshot()
{
if (battery_ == nullptr) {
return;
}
const BatteryStatus status = battery_->GetBatteryStatus();
if (!status.valid) {
// Suppress rather than report a bogus 0%: the battery task may not
// have produced its first plausible sample yet.
return;
}
const int16_t volume_percent =
volume_ != nullptr
? static_cast<int16_t>(volume_->OutputVolumePercent())
: static_cast<int16_t>(-1);
std::array<char, kStatusMessageCapacity> message{};
size_t size = 0;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kOpen ||
!builder_.BuildStatus(
status.percent,
status.millivolts,
status.charging,
config_.transport.firmware_version.data(),
volume_percent,
message.data(),
message.size(),
&size)) {
return;
}
last_status_ms_ = NowMs();
}
SendBuiltMessage(message.data(), size);
}
void RealtimeProtocol::RequestErrorClose(uint32_t error_id)
{
bool should_close = false;
{
MutexGuard lock(mutex_);
if (phase_ != RealtimeConnectionPhase::kClosed &&
phase_ != RealtimeConnectionPhase::kClosingAfterError) {
phase_ = RealtimeConnectionPhase::kClosingAfterError;
diagnostics_.phase = phase_;
should_close = true;
} else if (
phase_ == RealtimeConnectionPhase::kClosingAfterError) {
should_close = true;
}
}
if (!should_close) {
return;
}
Publish(AppEvent::Make(
AppEventType::kRealtimeProtocolError, error_id));
transport_.Close();
}
void RealtimeProtocol::ScheduleReconnectLocked(uint64_t now_ms)
{
const uint32_t delay =
reconnect_backoff_.NextDelayMs(esp_random());
reconnect_at_ms_ = now_ms + delay;
pending_open_ = true;
diagnostics_.reconnect_attempt_count =
reconnect_backoff_.attempt_count();
ESP_LOGI(kTag, "reconnect gate delay=%lu ms attempt=%lu",
static_cast<unsigned long>(delay),
static_cast<unsigned long>(
diagnostics_.reconnect_attempt_count));
}
void RealtimeProtocol::Publish(const AppEvent& event)
{
if (publisher_ == nullptr || !publisher_->Publish(event)) {
ESP_LOGE(kTag, "failed to publish event=%s",
ToString(event.type));
}
}
bool RealtimeProtocol::SendBuiltMessage(
const char* data,
size_t size)
{
if (!transport_.SendText(data, size)) {
return false;
}
MutexGuard lock(mutex_);
diagnostics_.sent_text_count++;
return true;
}
bool RealtimeProtocol::TakeAudioBatchLocked(size_t* packet_size)
{
if (packet_size == nullptr || audio_batch_.Empty()) {
return false;
}
const bool built = audio_batch_.Build(
audio_packet_.data(),
audio_packet_.size(),
packet_size);
audio_batch_.Reset();
return built;
}
bool RealtimeProtocol::UplinkEnabledLocked() const
{
return listening_uplink_enabled_ ||
call_uplink_enabled_ ||
(barge_in_enabled_ &&
(active_tts_session_ != 0 || tts_tail_uplink_enabled_));
}
uint32_t RealtimeProtocol::AllocateTtsSessionLocked()
{
uint32_t result = next_tts_session_++;
if (result == 0 || result >= 0x80000000U) {
next_tts_session_ = 2;
result = 1;
}
return result;
}
uint32_t RealtimeProtocol::AllocateCallSessionLocked()
{
uint32_t result = next_call_session_++;
if (result < 0x80000000U || result == 0xFFFFFFFFU) {
next_call_session_ = 0x80000002U;
result = 0x80000001U;
}
return result;
}
void RealtimeProtocol::ClearCallLocked()
{
active_call_id_.fill('\0');
active_call_session_ = 0;
call_uplink_enabled_ = false;
diagnostics_.active_call_session = 0;
}
void RealtimeProtocol::SyncClock(const ServerCommand& command)
{
if (command.server_time_seconds < 1700000000LL) {
return;
}
timeval time_value{};
time_value.tv_sec =
static_cast<time_t>(command.server_time_seconds);
settimeofday(&time_value, nullptr);
if (command.timezone_offset_seconds >= -43200 &&
command.timezone_offset_seconds <= 50400) {
const int offset_hours =
command.timezone_offset_seconds / 3600;
char timezone[20]{};
std::snprintf(
timezone, sizeof(timezone), "UTC%+d", -offset_hours);
setenv("TZ", timezone, 1);
tzset();
}
DeviceLogFormatter::MarkClockSynchronized();
}
uint64_t RealtimeProtocol::NowMs() const
{
return static_cast<uint64_t>(
esp_timer_get_time() / 1000ULL);
}
} // namespace borla