#ifndef WEBSOCKET_H #define WEBSOCKET_H #include #include #include #include #include #include #include #include #include #include #include "tcp.h" class NetworkInterface; class WebSocket { public: WebSocket(NetworkInterface* network, int connect_id); ~WebSocket(); void SetHeader(const char* key, const char* value); void SetReceiveBufferSize(size_t size); bool IsConnected() const; bool Connect(const char* uri); bool Send(const std::string& data); bool Send(const void* data, size_t len, bool binary = false, bool fin = true); void Ping(); void Close(); void OnConnected(std::function callback); void OnDisconnected(std::function callback); void OnData(std::function callback); void OnError(std::function callback); private: NetworkInterface* network_; int connect_id_; std::unique_ptr tcp_; bool continuation_ = false; size_t receive_buffer_size_ = 2048; std::string receive_buffer_; bool handshake_completed_ = false; bool connected_ = false; EventGroupHandle_t handshake_event_group_; static const EventBits_t HANDSHAKE_SUCCESS_BIT = BIT0; static const EventBits_t HANDSHAKE_FAILED_BIT = BIT1; // === Async TX === // A dedicated task owns every socket write, so callers (notably the // single-threaded main event loop) only enqueue pre-framed bytes and // return at once — a stalled uplink can never freeze them. struct TxFrame { std::string bytes; bool droppable; // audio frames may be dropped under backpressure }; static constexpr size_t kTxQueueMaxFrames = 96; static const EventBits_t TX_TASK_EXIT_BIT = BIT0; std::deque tx_queue_; std::mutex tx_mutex_; SemaphoreHandle_t tx_sem_ = nullptr; EventGroupHandle_t tx_event_group_ = nullptr; TaskHandle_t tx_task_handle_ = nullptr; volatile bool tx_running_ = false; std::map headers_; std::function on_data_; std::function on_error_; std::function on_connected_; std::function on_disconnected_; void OnTcpData(const std::string& data); bool SendControlFrame(uint8_t opcode, const void* data, size_t len); bool EnqueueTx(std::string&& bytes, bool droppable); void StartTxTask(); void StopTxTask(); void TxTask(); }; #endif // WEBSOCKET_H