/** * serial_lock.h * * A single global mutex that serializes writes to the USB-CDC `Serial` port. * * Multiple FreeRTOS tasks (CAN raw logger, UART task, main loop heartbeat, ...) * write to the same serial output. Without coordination their writes interleave * and splice mid-line, corrupting the CANRAW capture stream. Every frequent * writer takes this lock around its full line so lines never interleave. * * Usage: * SerialLock::lock(); * Serial.write(...); // or ESP_LOGx(...) * SerialLock::unlock(); * * Call SerialLock::init() once early in setup(), before any task starts. Before * init (or if creation fails) lock()/unlock() are safe no-ops. */ #ifndef _SERIAL_LOCK_H #define _SERIAL_LOCK_H #include #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" namespace SerialLock { /** Create the mutex. Idempotent; call once in setup() before tasks start. */ void init(); /** * Acquire the serial lock. * @param timeout ticks to wait (default: wait forever) * @return true if acquired (also true if the lock isn't initialized yet) */ bool lock(TickType_t timeout = portMAX_DELAY); /** Release the serial lock (no-op if not held / not initialized). */ void unlock(); } #endif // _SERIAL_LOCK_H