diff --git a/Firmware/lib/WebsocketCommunicator/WebsocketCommunicator.cpp b/Firmware/lib/WebsocketCommunicator/WebsocketCommunicator.cpp index 00fa93b..2925fca 100644 --- a/Firmware/lib/WebsocketCommunicator/WebsocketCommunicator.cpp +++ b/Firmware/lib/WebsocketCommunicator/WebsocketCommunicator.cpp @@ -22,7 +22,7 @@ WebsocketCommunicator::WebsocketCommunicator(AsyncWebSocket &socket, AsyncWebSer break; } }; - + msgRead = false; socket.onEvent(onEvent); server.addHandler(&socket); } @@ -41,11 +41,21 @@ void WebsocketCommunicator::sendMessage(const char message[]) char *WebsocketCommunicator::receiveMessage() { + msgRead = true; return getBuffer(); } +void WebsocketCommunicator::clearBufferSafely() +{ + if (msgRead) + { + clearBuffer(); + } +} + void WebsocketCommunicator::handleMessage(void *arg, uint8_t *data, size_t len) { + msgRead = false; int effectiveLen = len < bufferSize ? len : bufferSize; strncpy(messageBuffer, (char *)data, effectiveLen); } \ No newline at end of file diff --git a/Firmware/lib/WebsocketCommunicator/WebsocketCommunicator.h b/Firmware/lib/WebsocketCommunicator/WebsocketCommunicator.h index 1e6dbdd..b7b620d 100644 --- a/Firmware/lib/WebsocketCommunicator/WebsocketCommunicator.h +++ b/Firmware/lib/WebsocketCommunicator/WebsocketCommunicator.h @@ -5,6 +5,7 @@ class WebsocketCommunicator : public Communicator { private: void handleMessage(void *arg, uint8_t *data, size_t len); + bool msgRead; protected: AsyncWebSocket &socket; @@ -15,4 +16,5 @@ public: void sendMessage(int *values, __SIZE_TYPE__ numberOfValues) override; void sendMessage(const char message[]) override; char *receiveMessage() override; + void clearBufferSafely(); }; \ No newline at end of file diff --git a/Firmware/src/main.cpp b/Firmware/src/main.cpp index d07cc11..0cdfaa9 100644 --- a/Firmware/src/main.cpp +++ b/Firmware/src/main.cpp @@ -20,7 +20,7 @@ AsyncWebSocket ws("/ws"); Communicator *computer; Communicator *phone; -Communicator *websocket; +WebsocketCommunicator *websocket; LightController *light; void websocketTask(void *parameter) @@ -28,15 +28,13 @@ void websocketTask(void *parameter) while (true) { websocket->sendMessage(light->getBjtState(), light->getBjtCount()); - light->updateState(websocket->receiveMessage(), STEPS); - websocket->clearBuffer(); vTaskDelay(100 / portTICK_PERIOD_MS); } vTaskDelete(NULL); } -void registerTasks() +void registerWebSocketTask() { xTaskCreate(websocketTask, "websocketTask", 10000, NULL, 1, NULL); } @@ -79,7 +77,7 @@ void setup() connectWifi(WIFI_TIMEOUT); server.begin(); - registerTasks(); + registerWebSocketTask(); } void computerCycle() @@ -96,9 +94,16 @@ void phoneCycle() phone->clearBuffer(); } +void websocketCycle() +{ + light->updateState(websocket->receiveMessage(), STEPS); + websocket->clearBufferSafely(); +} + void loop() { computerCycle(); phoneCycle(); + websocketCycle(); ws.cleanupClients(); } \ No newline at end of file