Fix: Virtual console scrambled output when the output came from different contexts

This commit is contained in:
Thomas Basler 2023-08-03 22:16:29 +02:00
parent 10ba10d792
commit 43cba67531
2 changed files with 18 additions and 18 deletions

View File

@ -4,14 +4,15 @@
#include <AsyncWebSocket.h>
#include <HardwareSerial.h>
#include <Stream.h>
#include <mutex>
#define BUFFER_SIZE 500
class MessageOutputClass : public Print {
public:
MessageOutputClass();
void loop();
size_t write(uint8_t c);
size_t write(uint8_t c) override;
size_t write(const uint8_t *buffer, size_t size) override;
void register_ws_output(AsyncWebSocket* output);
private:
@ -21,7 +22,7 @@ private:
uint32_t _lastSend = 0;
bool _forceSend = false;
SemaphoreHandle_t _lock;
std::mutex _msgLock;
};
extern MessageOutputClass MessageOutput;

View File

@ -8,17 +8,6 @@
MessageOutputClass MessageOutput;
#define MSG_LOCK() \
do { \
} while (xSemaphoreTake(_lock, portMAX_DELAY) != pdPASS)
#define MSG_UNLOCK() xSemaphoreGive(_lock)
MessageOutputClass::MessageOutputClass()
{
_lock = xSemaphoreCreateMutex();
MSG_UNLOCK();
}
void MessageOutputClass::register_ws_output(AsyncWebSocket* output)
{
_ws = output;
@ -27,10 +16,9 @@ void MessageOutputClass::register_ws_output(AsyncWebSocket* output)
size_t MessageOutputClass::write(uint8_t c)
{
if (_buff_pos < BUFFER_SIZE) {
MSG_LOCK();
std::lock_guard<std::mutex> lock(_msgLock);
_buffer[_buff_pos] = c;
_buff_pos++;
MSG_UNLOCK();
} else {
_forceSend = true;
}
@ -38,11 +26,23 @@ size_t MessageOutputClass::write(uint8_t c)
return Serial.write(c);
}
size_t MessageOutputClass::write(const uint8_t* buffer, size_t size)
{
std::lock_guard<std::mutex> lock(_msgLock);
if (_buff_pos + size < BUFFER_SIZE) {
memcpy(&_buffer[_buff_pos], buffer, size);
_buff_pos += size;
}
_forceSend = true;
return Serial.write(buffer, size);
}
void MessageOutputClass::loop()
{
// Send data via websocket if either time is over or buffer is full
if (_forceSend || (millis() - _lastSend > 1000)) {
MSG_LOCK();
std::lock_guard<std::mutex> lock(_msgLock);
if (_ws && _buff_pos > 0) {
_ws->textAll(_buffer, _buff_pos);
_buff_pos = 0;
@ -50,7 +50,6 @@ void MessageOutputClass::loop()
if (_forceSend) {
_buff_pos = 0;
}
MSG_UNLOCK();
_forceSend = false;
}
}