base-station/Firmware/lib/WebsocketCommunicator/WebsocketCommunicator.cpp

51 lines
1.6 KiB
C++
Raw Normal View History

#include <WebsocketCommunicator.h>
#include <ESPAsyncWebServer.h>
WebsocketCommunicator::WebsocketCommunicator(AsyncWebSocket &socket, AsyncWebServer &server, __SIZE_TYPE__ bufferSize) : Communicator(bufferSize), socket(socket), server(server)
{
AwsEventHandler onEvent = [this](AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
void *arg, uint8_t *data, size_t len)
{
switch (type)
{
case WS_EVT_CONNECT:
Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket client #%u disconnected\n", client->id());
break;
case WS_EVT_DATA:
handleMessage(arg, data, len);
break;
case WS_EVT_PONG:
case WS_EVT_ERROR:
break;
}
};
socket.onEvent(onEvent);
server.addHandler(&socket);
}
void WebsocketCommunicator::sendMessage(int *values, __SIZE_TYPE__ numberOfValues)
{
char message[calculateMessageOutSize(numberOfValues)];
parseIDs(values, numberOfValues, message);
sendMessage(message);
}
void WebsocketCommunicator::sendMessage(const char message[])
{
socket.textAll(message);
}
char *WebsocketCommunicator::receiveMessage()
{
return getBuffer();
}
void WebsocketCommunicator::handleMessage(void *arg, uint8_t *data, size_t len)
{
2022-04-13 18:42:39 +02:00
int effectiveLen = len < bufferSize ? len : bufferSize;
strncpy(messageBuffer, (char *)data, effectiveLen);
}