From 4573ca11a5334a800c59cc1d09a57d8eae27f2c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20J=C3=A4ger?= Date: Fri, 13 Jan 2023 21:22:21 +0100 Subject: [PATCH] ThingSet serial: Fix tx buffer mutex for consecutive messages If the device received a command before the previous one was processed, it could get stalled inside the ISR, as the rx fifo was never read and the interrupts kept firing, while processing (in lower priority thread) cannot happen. --- app/src/ext/serial.cpp | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/app/src/ext/serial.cpp b/app/src/ext/serial.cpp index 95ccab5..41e46a8 100644 --- a/app/src/ext/serial.cpp +++ b/app/src/ext/serial.cpp @@ -33,6 +33,7 @@ static char tx_buf[CONFIG_THINGSET_SERIAL_TX_BUF_SIZE]; static char rx_buf[CONFIG_THINGSET_SERIAL_RX_BUF_SIZE]; static volatile size_t rx_buf_pos = 0; +static bool discard_buffer; static struct k_sem command_flag; // used as an event to signal a received command static struct k_sem rx_buf_mutex; // binary semaphore used as mutex in ISR context @@ -83,10 +84,16 @@ void serial_cb(const struct device *dev, void *user_data) return; } - while (uart_irq_rx_ready(uart_dev) && k_sem_take(&rx_buf_mutex, K_NO_WAIT) == 0) { + while (uart_irq_rx_ready(uart_dev)) { uart_fifo_read(uart_dev, &c, 1); + if (k_sem_take(&rx_buf_mutex, K_NO_WAIT) != 0) { + // buffer not available: drop character + discard_buffer = true; + continue; + } + // \r\n and \n are markers for line end, i.e. command end // we accept this at any time, even if the buffer is 'full', since // there is always one last character left for the \0 @@ -97,8 +104,15 @@ void serial_cb(const struct device *dev, void *user_data) else { rx_buf[rx_buf_pos] = '\0'; } - // start processing command and keep the rx_buf_mutex locked - k_sem_give(&command_flag); + if (discard_buffer) { + rx_buf_pos = 0; + discard_buffer = false; + k_sem_give(&rx_buf_mutex); + } + else { + // start processing command and keep the rx_buf_mutex locked + k_sem_give(&command_flag); + } return; } // backspace allowed if there is something in the buffer already