86 lines
2.6 KiB
C++
86 lines
2.6 KiB
C++
#ifndef WEBSOCKET_H
|
|
#define WEBSOCKET_H
|
|
|
|
#include <functional>
|
|
#include <string>
|
|
#include <map>
|
|
#include <memory>
|
|
#include <deque>
|
|
#include <mutex>
|
|
#include <freertos/FreeRTOS.h>
|
|
#include <freertos/event_groups.h>
|
|
#include <freertos/semphr.h>
|
|
#include <freertos/task.h>
|
|
|
|
#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<void()> callback);
|
|
void OnDisconnected(std::function<void()> callback);
|
|
void OnData(std::function<void(const char*, size_t, bool binary)> callback);
|
|
void OnError(std::function<void(int)> callback);
|
|
|
|
private:
|
|
NetworkInterface* network_;
|
|
int connect_id_;
|
|
std::unique_ptr<Tcp> 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<TxFrame> 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<std::string, std::string> headers_;
|
|
std::function<void(const char*, size_t, bool binary)> on_data_;
|
|
std::function<void(int)> on_error_;
|
|
std::function<void()> on_connected_;
|
|
std::function<void()> 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
|