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

254 lines
8.8 KiB
C++

#pragma once
#include "connectivity/reconnect_backoff.h"
#include "audio/encoded_audio_sink.h"
#include "ports/battery_status_provider.h"
#include "ports/device_platform.h"
#include "ports/device_profile_sink.h"
#include "ports/event_publisher.h"
#include "ports/local_sequence_handler.h"
#include "ports/memory_cache.h"
#include "ports/remote_behavior_config.h"
#include "ports/realtime_protocol.h"
#include "ports/sensor_message_sink.h"
#include "ports/volume_status_provider.h"
#include "protocol/protocol_message_builder.h"
#include "protocol/binary_audio_protocol.h"
#include "protocol/realtime_config.h"
#include "protocol/server_message_dispatcher.h"
#include "protocol/realtime_binary_sink.h"
#include "protocol/websocket_transport.h"
#include "schedule/schedule_types.h"
#include <array>
#include <cstddef>
#include <cstdint>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
namespace borla {
enum class RealtimeConnectionPhase : uint8_t {
kClosed,
kConnecting,
kAwaitingHello,
kOpen,
kClosingAfterError,
};
struct RealtimeDiagnostics {
RealtimeConnectionPhase phase = RealtimeConnectionPhase::kClosed;
uint32_t reconnect_attempt_count = 0;
uint32_t invalid_message_count = 0;
uint32_t unsupported_message_count = 0;
uint32_t received_text_count = 0;
uint32_t received_binary_count = 0;
uint32_t sent_text_count = 0;
uint32_t transport_error_count = 0;
uint32_t active_tts_session = 0;
uint32_t active_call_session = 0;
uint64_t last_incoming_ms = 0;
std::array<char, kRealtimeSessionIdCapacity> session_id{};
};
class RealtimeProtocol final
: public IRealtimeProtocol,
public IEncodedAudioSink,
public ISensorMessageSink,
public IScheduleEventSink,
public IWebsocketTransportObserver {
public:
RealtimeProtocol(
IWebsocketTransport& transport,
IRealtimeConfigStore& config_store);
~RealtimeProtocol();
bool Initialize(const DeviceIdentity& identity);
void SetEventPublisher(IEventPublisher* publisher)
{
publisher_ = publisher;
}
void SetBinarySink(IRealtimeBinarySink* sink) { binary_sink_ = sink; }
void SetScheduleCommandHandler(IScheduleCommandHandler* handler)
{
schedule_handler_ = handler;
}
void SetBatteryStatusProvider(IBatteryStatusProvider* provider)
{
battery_ = provider;
}
void SetVolumeStatusProvider(IVolumeStatusProvider* provider)
{
volume_ = provider;
}
void SetDeviceProfileSink(IDeviceProfileSink* sink)
{
device_profile_sink_ = sink;
}
void SetLocalSequenceHandler(ILocalSequenceHandler* handler)
{
local_sequence_handler_ = handler;
}
void SetMemoryCache(IMemoryCache* cache)
{
memory_cache_ = cache;
}
void SetRemoteBehaviorConfig(IRemoteBehaviorConfig* config)
{
remote_behavior_config_ = config;
}
void Open() override;
void Close() override;
void SendStartListening() override;
void SendStopListening() override;
void SendAbortSpeaking(
ConversationInterruptSource source) override;
void SendGoodbye() override;
void SendAcceptCall() override;
void SendHangupCall() override;
void SendButtonClick(uint8_t click_count) override;
void SendLocalPlaybackState(
LocalPrompt prompt,
bool started) override;
bool SendFriendAdd(
const char* local_mac,
const char* local_name,
const char* remote_mac,
const char* remote_name) override;
bool SendOtaNotify(
const char* text,
bool optional) override;
void RequestConnectionErrorPrompt() override;
bool SubmitEncodedAudio(
const uint8_t* data,
size_t size) override;
void FlushEncodedAudio() override;
bool SendSensorMessage(
const char* data,
size_t size) override;
bool SendAlarmFired(
int32_t alarm_id,
int64_t fired_at_epoch) override;
RealtimeDiagnostics GetDiagnostics() const;
uint32_t ActiveTtsSession() const;
void OnWebsocketConnected() override;
void OnWebsocketDisconnected(int error_code) override;
void OnWebsocketText(const char* data, size_t size) override;
void OnWebsocketBinary(
const uint8_t* data,
size_t size) override;
private:
static constexpr size_t kMessageCapacity =
kBinaryAudioMaximumPacketBytes;
static constexpr size_t kHeartbeatMessageCapacity = 128;
// Status is built on the esp_timer task, whose stack is a few KB. Size the
// buffer for the message (~150 bytes) instead of reusing the 2.5 KB
// audio-packet capacity the other builders share.
static constexpr size_t kStatusMessageCapacity = 256;
static constexpr uint32_t kProtocolRetryMaximumMs = 30000;
static constexpr uint32_t kStatusIntervalMs = 60000;
static constexpr size_t kTraceMarkerCapacity = 256;
static constexpr uint64_t kAudioTraceHeartbeatMs = 5000;
static constexpr float kAudioTraceRelativeChange = 0.20F;
static constexpr size_t kAudioTraceMinimumByteDelta = 160;
static void TimerCallback(void* context);
void OnTimer();
void HandleCommand(const ServerCommand& command);
void HandleHello(const ServerCommand& command);
void RequestErrorClose(uint32_t error_id);
void ScheduleReconnectLocked(uint64_t now_ms);
void Publish(const AppEvent& event);
bool SendBuiltMessage(const char* data, size_t size);
bool TakeAudioBatchLocked(size_t* packet_size);
// One uplink batch leaves every 300 ms, and a marker per batch would be
// pure noise. Emit one when the batch shape actually changes — first batch,
// a different frame count, or a byte size that moved by both an absolute
// and a relative margin — plus a slow heartbeat so a steady stream still
// reports a clock sample. Same policy as the previous firmware.
bool ShouldTraceAudioBatchLocked(
uint64_t sequence,
size_t frames,
size_t bytes,
uint64_t now_ms);
void SendAudioBatchTrace(
uint64_t sequence,
size_t frames,
size_t bytes,
uint64_t client_send_ms);
static int64_t EpochMs();
bool UplinkEnabledLocked() const;
uint32_t AllocateTtsSessionLocked();
uint32_t AllocateCallSessionLocked();
void ClearCallLocked();
void SyncClock(const ServerCommand& command);
void SendStatusSnapshot();
uint64_t NowMs() const;
IWebsocketTransport& transport_;
IRealtimeConfigStore& config_store_;
IEventPublisher* publisher_ = nullptr;
IRealtimeBinarySink* binary_sink_ = nullptr;
IScheduleCommandHandler* schedule_handler_ = nullptr;
IBatteryStatusProvider* battery_ = nullptr;
IVolumeStatusProvider* volume_ = nullptr;
IDeviceProfileSink* device_profile_sink_ = nullptr;
ILocalSequenceHandler* local_sequence_handler_ = nullptr;
IMemoryCache* memory_cache_ = nullptr;
IRemoteBehaviorConfig* remote_behavior_config_ = nullptr;
RealtimeConfig config_{};
ServerMessageDispatcher dispatcher_;
ServerCommand* incoming_command_ = nullptr;
ProtocolMessageBuilder builder_;
ReconnectBackoff reconnect_backoff_;
mutable StaticSemaphore_t mutex_storage_{};
SemaphoreHandle_t mutex_ = nullptr;
esp_timer_handle_t timer_ = nullptr;
bool initialized_ = false;
bool intentional_close_ = true;
bool pending_open_ = false;
bool disconnect_reported_ = false;
RealtimeConnectionPhase phase_ = RealtimeConnectionPhase::kClosed;
uint64_t hello_deadline_ms_ = 0;
uint64_t reconnect_at_ms_ = 0;
uint64_t last_incoming_ms_ = 0;
uint64_t last_ping_ms_ = 0;
uint64_t last_status_ms_ = 0;
uint32_t next_tts_session_ = 1;
uint32_t active_tts_session_ = 0;
uint32_t next_call_session_ = 0x80000001U;
uint32_t active_call_session_ = 0;
std::array<char, kCallIdCapacity> active_call_id_{};
// The sentence currently coming out of the speaker, reported to the server
// on abort so it knows how much of its reply the child actually heard.
// Only the leading bytes are kept — the abort builder caps the field anyway,
// and holding a full sentence per connection is not worth the RAM.
std::array<
char,
ProtocolMessageBuilder::kPlaybackTextBytes + 1>
playback_text_{};
uint64_t trace_audio_batch_sequence_ = 0;
uint64_t last_trace_audio_batch_ms_ = 0;
size_t last_trace_audio_batch_frames_ = 0;
size_t last_trace_audio_batch_bytes_ = 0;
bool listening_uplink_enabled_ = false;
bool barge_in_enabled_ = false;
bool tts_tail_uplink_enabled_ = false;
bool call_uplink_enabled_ = false;
BinaryAudioBatchBuilder audio_batch_;
std::array<
uint8_t,
kBinaryAudioMaximumPacketBytes>
audio_packet_{};
RealtimeDiagnostics diagnostics_{};
};
} // namespace borla