Skip to content

Commit

Permalink
tidy the main sketch
Browse files Browse the repository at this point in the history
  • Loading branch information
hoeken committed Aug 12, 2024
1 parent f715b0a commit c133738
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 72 deletions.
12 changes: 6 additions & 6 deletions examples/platformio/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ void setup()
server.onOpen([](PsychicClient* client) { Serial.printf("[http] connection #%u connected from %s\n", client->socket(), client->remoteIP().toString().c_str()); });

// example callback everytime a connection is closed
server.onClose([](PsychicClient* client) { Serial.printf("[http] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString().c_str()); });
server.onClose([](PsychicClient* client) { Serial.printf("[http] connection #%u closed\n", client->socket()); });

// api - json message passed in as post body
// curl -i -X POST -H "Content-Type: application/json" -d '{"foo":"bar"}' http://psychic.local/api
Expand Down Expand Up @@ -394,7 +394,7 @@ void setup()
PsychicWebHandler* connectionHandler = new PsychicWebHandler();
connectionHandler->onRequest([](PsychicRequest* request) { return request->reply("OK"); });
connectionHandler->onOpen([](PsychicClient* client) { Serial.printf("[handler] connection #%u connected from %s\n", client->socket(), client->remoteIP().toString().c_str()); });
connectionHandler->onClose([](PsychicClient* client) { Serial.printf("[handler] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString().c_str()); });
connectionHandler->onClose([](PsychicClient* client) { Serial.printf("[handler] connection #%u closed\n", client->socket()); });

// add it to our server
server.on("/handler", connectionHandler);
Expand Down Expand Up @@ -651,10 +651,10 @@ void setup()
client->sendMessage("Hello!");
});
websocketHandler.onFrame([](PsychicWebSocketRequest* request, httpd_ws_frame* frame) {
Serial.printf("[socket] #%d sent: %s\n", request->client()->socket(), (char*)frame->payload);
Serial.printf("[socket] #%d sent: %s\n", request->client()->socket(), String((char*)frame->payload, frame->len).c_str());
return request->reply(frame);
});
websocketHandler.onClose([](PsychicWebSocketClient* client) { Serial.printf("[socket] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString().c_str()); });
websocketHandler.onClose([](PsychicWebSocketClient* client) { Serial.printf("[socket] connection #%u closed\n", client->socket()); });
server.on("/ws", &websocketHandler);

// EventSource server
Expand All @@ -663,7 +663,7 @@ void setup()
Serial.printf("[eventsource] connection #%u connected from %s\n", client->socket(), client->remoteIP().toString().c_str());
client->send("Hello user!", NULL, millis(), 1000);
});
eventSource.onClose([](PsychicEventSourceClient* client) { Serial.printf("[eventsource] connection #%u closed from %s\n", client->socket(), client->remoteIP().toString().c_str()); });
eventSource.onClose([](PsychicEventSourceClient* client) { Serial.printf("[eventsource] connection #%u closed\n", client->socket()); });
server.on("/events", &eventSource);

// example of using POST data inside the filter
Expand All @@ -689,7 +689,7 @@ char output[60];

void loop()
{
if (millis() - lastUpdate > 2000) {
if (millis() - lastUpdate > 1000) {
sprintf(output, "Millis: %lu\n", millis());
websocketHandler.sendAll(output);

Expand Down
6 changes: 2 additions & 4 deletions src/PsychicClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ IPAddress PsychicClient::localIP()
struct sockaddr_in6 addr; // esp_http_server uses IPv6 addressing
socklen_t addr_size = sizeof(addr);

if (getsockname(_socket, (struct sockaddr*)&addr, &addr_size) < 0)
{
if (getsockname(_socket, (struct sockaddr*)&addr, &addr_size) < 0) {
ESP_LOGE(PH_TAG, "Error getting client IP");
return address;
}
Expand All @@ -62,8 +61,7 @@ IPAddress PsychicClient::remoteIP()
struct sockaddr_in6 addr; // esp_http_server uses IPv6 addressing
socklen_t addr_size = sizeof(addr);

if (getpeername(_socket, (struct sockaddr*)&addr, &addr_size) < 0)
{
if (getpeername(_socket, (struct sockaddr*)&addr, &addr_size) < 0) {
ESP_LOGE(PH_TAG, "Error getting client IP");
return address;
}
Expand Down
1 change: 1 addition & 0 deletions src/PsychicClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

class PsychicClient
{

protected:
httpd_handle_t _server;
int _socket;
Expand Down
31 changes: 10 additions & 21 deletions src/PsychicEndpoint.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,10 @@ String PsychicEndpoint::uri()
esp_err_t PsychicEndpoint::requestCallback(httpd_req_t* req)
{
#ifdef ENABLE_ASYNC
if (is_on_async_worker_thread() == false)
{
if (submit_async_req(req, PsychicEndpoint::requestCallback) == ESP_OK)
{
if (is_on_async_worker_thread() == false) {
if (submit_async_req(req, PsychicEndpoint::requestCallback) == ESP_OK) {
return ESP_OK;
}
else
{
} else {
httpd_resp_set_status(req, "503 Busy");
httpd_resp_sendstr(req, "No workers available. Server busy.</div>");
return ESP_OK;
Expand All @@ -63,10 +59,8 @@ esp_err_t PsychicEndpoint::requestCallback(httpd_req_t* req)
PsychicRequest request(self->_server, req);

// make sure we have a handler
if (handler != NULL)
{
if (handler->filter(&request) && handler->canHandle(&request))
{
if (handler != NULL) {
if (handler->filter(&request) && handler->canHandle(&request)) {
// check our credentials
if (handler->needsAuthentication(&request))
return handler->authenticate(&request);
Expand All @@ -76,9 +70,8 @@ esp_err_t PsychicEndpoint::requestCallback(httpd_req_t* req)
}
// pass it to our generic handlers
else
return PsychicHttpServer::notFoundHandler(req, HTTPD_500_INTERNAL_SERVER_ERROR);
}
else
return PsychicHttpServer::requestHandler(req);
} else
return request.reply(500, "text/html", "No handler registered.");
}

Expand All @@ -97,19 +90,15 @@ bool PsychicEndpoint::matches(const char* uri)
position = strlen(uri);

// do we have a per-endpoint match function
if (this->getURIMatchFunction() != NULL)
{
if (this->getURIMatchFunction() != NULL) {
// ESP_LOGD(PH_TAG, "Match? %s == %s (%d)", _uri.c_str(), uri, position);
return this->getURIMatchFunction()(_uri.c_str(), uri, (size_t)position);
}
// do we have a global match function
if (_server->getURIMatchFunction() != NULL)
{
if (_server->getURIMatchFunction() != NULL) {
// ESP_LOGD(PH_TAG, "Match? %s == %s (%d)", _uri.c_str(), uri, position);
return _server->getURIMatchFunction()(_uri.c_str(), uri, (size_t)position);
}
else
{
} else {
ESP_LOGE(PH_TAG, "No uri matching function set");
return false;
}
Expand Down
17 changes: 6 additions & 11 deletions src/PsychicHttpServer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -276,9 +276,9 @@ PsychicEndpoint* PsychicHttpServer::on(const char* uri, int method, PsychicHandl
// save it to our 'real' handlers for later.
_esp_idf_endpoints.push_back(my_uri);
}

// add it to our meta endpoints
else
_endpoints.push_back(endpoint);
_endpoints.push_back(endpoint);

return endpoint;
}
Expand Down Expand Up @@ -314,6 +314,7 @@ PsychicEndpoint* PsychicHttpServer::on(const char* uri, int method, PsychicJsonR
bool PsychicHttpServer::removeEndpoint(const char* uri, int method)
{
// some handlers (aka websockets) need actual endpoints in esp-idf http_server
// don't return from here, because its added to the _endpoints list too.
for (auto& endpoint : _esp_idf_endpoints) {
if (!strcmp(endpoint.uri, uri) && method == endpoint.method) {
ESP_LOGD(PH_TAG, "Unregistering endpoint %s | %s", endpoint.uri, http_method_str((http_method)endpoint.method));
Expand All @@ -322,8 +323,6 @@ bool PsychicHttpServer::removeEndpoint(const char* uri, int method)
esp_err_t ret = httpd_register_uri_handler(this->server, &endpoint);
if (ret != ESP_OK)
ESP_LOGE(PH_TAG, "Add endpoint failed (%s)", esp_err_to_name(ret));

return true;
}
}

Expand All @@ -332,6 +331,8 @@ bool PsychicHttpServer::removeEndpoint(const char* uri, int method)
if (endpoint->uri().equals(uri) && method == endpoint->_method)
return removeEndpoint(endpoint);
}

return false;
}

bool PsychicHttpServer::removeEndpoint(PsychicEndpoint* endpoint)
Expand Down Expand Up @@ -404,13 +405,7 @@ esp_err_t PsychicHttpServer::requestHandler(httpd_req_t* req)
}
}

// nothing found, give it to our defaultEndpoint
PsychicHandler* handler = server->defaultEndpoint->handler();
if (handler->filter(&request) && handler->canHandle(&request))
return handler->handleRequest(&request);

// not sure how we got this far.
return ESP_ERR_HTTPD_INVALID_REQ;
return PsychicHttpServer::notFoundHandler(req, HTTPD_404_NOT_FOUND);
}

esp_err_t PsychicHttpServer::notFoundHandler(httpd_req_t* req, httpd_err_code_t err)
Expand Down
73 changes: 43 additions & 30 deletions src/PsychicWebSocket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@ PsychicWebSocketClient::~PsychicWebSocketClient()

void PsychicWebSocketClient::_sendMessageCallback(esp_err_t err, int socket, void* arg)
{
// PsychicWebSocketClient* client = (PsychicWebSocketClient*)arg;
// free our frame.
httpd_ws_frame_t* ws_pkt = (httpd_ws_frame_t*)arg;
free(ws_pkt->payload);
free(ws_pkt);

if (err == ESP_OK)
return;
Expand All @@ -71,19 +74,40 @@ void PsychicWebSocketClient::_sendMessageCallback(esp_err_t err, int socket, voi

esp_err_t PsychicWebSocketClient::sendMessage(httpd_ws_frame_t* ws_pkt)
{
return httpd_ws_send_data_async(this->server(), this->socket(), ws_pkt, PsychicWebSocketClient::_sendMessageCallback, this);
return sendMessage(ws_pkt->type, ws_pkt->payload, ws_pkt->len);
}

esp_err_t PsychicWebSocketClient::sendMessage(httpd_ws_type_t op, const void* data, size_t len)
{
httpd_ws_frame_t ws_pkt;
memset(&ws_pkt, 0, sizeof(httpd_ws_frame_t));
// init our frame.
httpd_ws_frame_t* ws_pkt = (httpd_ws_frame_t*)malloc(sizeof(httpd_ws_frame_t));
if (ws_pkt == NULL) {
ESP_LOGE(PH_TAG, "Websocket: out of memory");
return ESP_ERR_NO_MEM;
}
memset(ws_pkt, 0, sizeof(httpd_ws_frame_t)); // zero the datastructure out

// allocate for event text
ws_pkt->payload = (uint8_t*)malloc(len);
if (ws_pkt->payload == NULL) {
ESP_LOGE(PH_TAG, "Websocket: out of memory");
free(ws_pkt); // free our other memory
return ESP_ERR_NO_MEM;
}
memcpy(ws_pkt->payload, data, len);

ws_pkt.payload = (uint8_t*)data;
ws_pkt.len = len;
ws_pkt.type = op;
ws_pkt->len = len;
ws_pkt->type = op;

esp_err_t err = httpd_ws_send_data_async(server(), socket(), ws_pkt, PsychicWebSocketClient::_sendMessageCallback, ws_pkt);

return this->sendMessage(&ws_pkt);
// take care of memory
if (err != ESP_OK) {
free(ws_pkt->payload);
free(ws_pkt);
}

return err;
}

esp_err_t PsychicWebSocketClient::sendMessage(const char* buf)
Expand All @@ -108,8 +132,7 @@ PsychicWebSocketClient* PsychicWebSocketHandler::getClient(int socket)
if (client == NULL)
return NULL;

if (client->_friend == NULL)
{
if (client->_friend == NULL) {
return NULL;
}

Expand Down Expand Up @@ -137,8 +160,7 @@ void PsychicWebSocketHandler::removeClient(PsychicClient* client)
void PsychicWebSocketHandler::openCallback(PsychicClient* client)
{
PsychicWebSocketClient* buddy = getClient(client);
if (buddy == NULL)
{
if (buddy == NULL) {
return;
}

Expand All @@ -149,8 +171,7 @@ void PsychicWebSocketHandler::openCallback(PsychicClient* client)
void PsychicWebSocketHandler::closeCallback(PsychicClient* client)
{
PsychicWebSocketClient* buddy = getClient(client);
if (buddy == NULL)
{
if (buddy == NULL) {
return;
}

Expand All @@ -166,8 +187,7 @@ esp_err_t PsychicWebSocketHandler::handleRequest(PsychicRequest* request)
PsychicClient* client = checkForNewClient(request->client());

// beginning of the ws URI handler and our onConnect hook
if (request->method() == HTTP_GET)
{
if (request->method() == HTTP_GET) {
if (client->isNew)
openCallback(client);

Expand All @@ -185,28 +205,24 @@ esp_err_t PsychicWebSocketHandler::handleRequest(PsychicRequest* request)

/* Set max_len = 0 to get the frame len */
esp_err_t ret = httpd_ws_recv_frame(wsRequest.request(), &ws_pkt, 0);
if (ret != ESP_OK)
{
if (ret != ESP_OK) {
ESP_LOGE(PH_TAG, "httpd_ws_recv_frame failed to get frame len with %s", esp_err_to_name(ret));
return ret;
}

// okay, now try to load the packet
// ESP_LOGD(PH_TAG, "frame len is %d", ws_pkt.len);
if (ws_pkt.len)
{
if (ws_pkt.len) {
/* ws_pkt.len + 1 is for NULL termination as we are expecting a string */
buf = (uint8_t*)calloc(1, ws_pkt.len + 1);
if (buf == NULL)
{
if (buf == NULL) {
ESP_LOGE(PH_TAG, "Failed to calloc memory for buf");
return ESP_ERR_NO_MEM;
}
ws_pkt.payload = buf;
/* Set max_len = ws_pkt.len to get the frame payload */
ret = httpd_ws_recv_frame(wsRequest.request(), &ws_pkt, ws_pkt.len);
if (ret != ESP_OK)
{
if (ret != ESP_OK) {
ESP_LOGE(PH_TAG, "httpd_ws_recv_frame failed with %s", esp_err_to_name(ret));
free(buf);
return ret;
Expand All @@ -215,8 +231,7 @@ esp_err_t PsychicWebSocketHandler::handleRequest(PsychicRequest* request)
}

// Text messages are our payload.
if (ws_pkt.type == HTTPD_WS_TYPE_TEXT || ws_pkt.type == HTTPD_WS_TYPE_BINARY)
{
if (ws_pkt.type == HTTPD_WS_TYPE_TEXT || ws_pkt.type == HTTPD_WS_TYPE_BINARY) {
if (this->_onFrame != NULL)
ret = this->_onFrame(&wsRequest, &ws_pkt);
}
Expand Down Expand Up @@ -255,12 +270,10 @@ PsychicWebSocketHandler* PsychicWebSocketHandler::onClose(PsychicWebSocketClient

void PsychicWebSocketHandler::sendAll(httpd_ws_frame_t* ws_pkt)
{
for (PsychicClient* client : _clients)
{
for (PsychicClient* client : _clients) {
// ESP_LOGD(PH_TAG, "Active client (fd=%d) -> sending async message", client->socket());

if (client->_friend == NULL)
{
if (client->_friend == NULL) {
return;
}

Expand Down

0 comments on commit c133738

Please sign in to comment.