Skip to content

Commit

Permalink
ws: Add optional callback for received binary ws frames
Browse files Browse the repository at this point in the history
This is a bit of a hack and will be improved later.
We need it as a simple in-between solution to test a new
module that needs to receive binary data over wss
  • Loading branch information
borg42 committed Sep 30, 2024
1 parent 37035a3 commit 665baba
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
16 changes: 16 additions & 0 deletions software/src/modules/ws/web_sockets.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,11 @@ static esp_err_t ws_handler(httpd_req_t *req)
// If it was a TEXT message, print it
logger.printfln("Ignoring received packet with message: \"%s\" (web sockets are unidirectional for now)", ws_pkt.payload);
// FIXME: input handling
} else if (ws_pkt.type == HTTPD_WS_TYPE_BINARY) {
WebSockets *ws = (WebSockets *)req->user_ctx;
if (ws->on_binary_data_received_fn != nullptr) {
ws->on_binary_data_received_fn(httpd_req_to_sockfd(req), &ws_pkt);
}
} else if (ws_pkt.type == HTTPD_WS_TYPE_CLOSE) {
// If it was a CLOSE, remove it from the keep-alive list
WebSockets *ws = (WebSockets *)req->user_ctx;
Expand Down Expand Up @@ -606,3 +611,14 @@ void WebSockets::onConnect_HTTPThread(std::function<void(WebSocketsClient)> fn)
{
on_client_connect_fn = fn;
}

// TODO: In a perfect world this function would be part of the WebSocketsClient class.
// In the ws_handler it could then be called with just the websocket frame.
// Currently all callees of this function have to check the fd against all open connections and match it.
// If we would do this the other way around, the interfaces would be nicer.
// However, in WebSockets we would need to keep a list of all WebSocketsClient instances and
// and maintain it (remove closed connections etc). This is not necessary now.
void WebSockets::onBinaryDataReceived_HTTPThread(std::function<void(const int fd, httpd_ws_frame_t *ws_pkt)> fn)
{
on_binary_data_received_fn = fn;
}
3 changes: 3 additions & 0 deletions software/src/modules/ws/web_sockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ class WebSockets
bool queueFull();

void onConnect_HTTPThread(std::function<void(WebSocketsClient)> fn);
void onBinaryDataReceived_HTTPThread(std::function<void(const int fd, httpd_ws_frame_t *ws_pkt)> fn);

void triggerHttpThread();
bool haveWork(ws_work_item *item);
Expand All @@ -102,7 +103,9 @@ class WebSockets
uint32_t worker_poll_count = 0;

httpd_handle_t httpd;

std::function<void(WebSocketsClient)> on_client_connect_fn;
std::function<void(const int fd, httpd_ws_frame_t *ws_pkt)> on_binary_data_received_fn = nullptr;

ConfigRoot state;
};

0 comments on commit 665baba

Please sign in to comment.