Files
bolar_1/main/protocols/websocket_protocol.h

71 lines
2.6 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#pragma once
#include "protocol.h"
#include <web_socket.h>
#include <freertos/FreeRTOS.h>
#include <freertos/event_groups.h>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include <cstdint>
#define WEBSOCKET_PROTOCOL_SERVER_HELLO_EVENT (1 << 0)
// 上行 Opus 批量:5 帧一包(~300ms),用于降低 ML307 MIPSEND 频率。
// 见 protocols/websocket_protocol.md "批量音频"。
static constexpr size_t kAudioBatchSize = 5;
class WebsocketProtocol : public Protocol {
public:
WebsocketProtocol();
~WebsocketProtocol() override;
bool Start() override;
bool SendAudio(std::unique_ptr<AudioStreamPacket> packet) override;
bool OpenAudioChannel() override;
void CloseAudioChannel() override;
bool IsAudioChannelOpened() const override;
bool SendHeartbeat() override;
bool HeartbeatTimedOut() const override;
private:
bool SendText(const std::string& text) override;
std::string GetHelloMessage();
void ParseServerHello(const cJSON* root);
// 批量上行:把累积的 Opus 帧打成一个 v3 二进制帧发出
// 由 SendAudio 在满 kAudioBatchSize 时触发,或由 SendText / CloseAudioChannel
// 在发非音频控制消息前主动 flush 以保证时序。
// 调用方持有 audio_batch_mutex_ 时调用此函数。
bool FlushAudioBatchLocked();
bool SendTraceMarkerLocked(const char* stage, uint64_t seq, size_t frames,
size_t bytes, uint64_t client_send_ms,
int64_t client_epoch_ms);
bool ShouldTraceAudioBatchLocked(uint64_t seq, size_t frames, size_t bytes,
uint64_t now_ms);
EventGroupHandle_t event_group_handle_;
std::unique_ptr<WebSocket> websocket_;
int version_ = 3;
std::string trace_id_;
uint64_t trace_connect_send_ms_ = 0;
int64_t trace_connect_epoch_ms_ = 0;
uint64_t trace_text_seq_ = 0;
uint64_t trace_audio_batch_seq_ = 0;
uint64_t trace_downlink_audio_seq_ = 0;
uint64_t last_trace_downlink_audio_ms_ = 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;
// Last time we successfully wrote to the socket (audio / control / ping).
// Combined with base-class last_incoming_time_, drives the idle-only
// heartbeat: ping only fires when both directions have been silent for ≥3s.
std::chrono::time_point<std::chrono::steady_clock> last_outgoing_time_;
std::mutex audio_batch_mutex_;
std::vector<std::vector<uint8_t>> audio_batch_; // pending opus frames
};