2022-04-10 17:12:44 +02:00
|
|
|
#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;
|
|
|
|
}
|
|
|
|
};
|
2022-04-13 19:09:03 +02:00
|
|
|
msgRead = false;
|
2022-04-10 17:12:44 +02:00
|
|
|
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()
|
|
|
|
{
|
2022-04-13 19:09:03 +02:00
|
|
|
msgRead = true;
|
2022-04-10 17:12:44 +02:00
|
|
|
return getBuffer();
|
|
|
|
}
|
|
|
|
|
2022-04-13 19:09:03 +02:00
|
|
|
void WebsocketCommunicator::clearBufferSafely()
|
|
|
|
{
|
|
|
|
if (msgRead)
|
|
|
|
{
|
|
|
|
clearBuffer();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-10 17:12:44 +02:00
|
|
|
void WebsocketCommunicator::handleMessage(void *arg, uint8_t *data, size_t len)
|
|
|
|
{
|
2022-04-13 19:09:03 +02:00
|
|
|
msgRead = false;
|
2022-04-13 18:42:39 +02:00
|
|
|
int effectiveLen = len < bufferSize ? len : bufferSize;
|
|
|
|
strncpy(messageBuffer, (char *)data, effectiveLen);
|
2022-04-10 17:12:44 +02:00
|
|
|
}
|