diff --git a/main/app_serial.cpp b/main/app_serial.cpp index 344f567..c8e4a94 100644 --- a/main/app_serial.cpp +++ b/main/app_serial.cpp @@ -28,11 +28,16 @@ QueueHandle_t setupSerial(const uart_port_t uart) .source_clk = UART_SCLK_DEFAULT, }; - ESP_ERROR_CHECK(uart_driver_install(uart, 132, 128 * 2, 4, &s_uart_queue, 0)); + ESP_ERROR_CHECK(uart_driver_install(uart, 128 * 2, 128 * 2, 4, &s_uart_queue, 0)); ESP_ERROR_CHECK(uart_param_config(uart, &config)); ESP_ERROR_CHECK(uart_set_pin(uart, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE)); return s_uart_queue; } +void discardRxBuffer(const uart_port_t uart) +{ + ESP_ERROR_CHECK(uart_flush(uart)); +} + } diff --git a/main/app_serial.hpp b/main/app_serial.hpp index cd21bac..a3e4094 100644 --- a/main/app_serial.hpp +++ b/main/app_serial.hpp @@ -13,4 +13,6 @@ namespace Serial [[nodiscard]] QueueHandle_t setupSerial(const uart_port_t uart); +void discardRxBuffer(const uart_port_t uart); + } diff --git a/main/esp_tunnel.cpp b/main/esp_tunnel.cpp index ee47c11..d0c75b2 100644 --- a/main/esp_tunnel.cpp +++ b/main/esp_tunnel.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include "app_networking.hpp" #include "app_serial.hpp" @@ -26,13 +27,15 @@ QueueSetHandle_t s_queue_set = nullptr; QueueHandle_t s_esp_now_queue = nullptr; QueueHandle_t s_uart_queue = nullptr; -void s_sendUartData(const std::size_t len) +void s_sendUartData(std::size_t len) { + len = std::clamp(len, 1, 128); ESP_LOGD(LOG_TAG, "Sending %u bytes via UART.", len); std::array tx_buffer; uart_read_bytes(CONFIG_ESPTNL_UART, tx_buffer.data(), len, 0); + xTimerStop(s_timer, 0); Networking::sendData(tx_buffer, len); } @@ -54,7 +57,7 @@ std::size_t s_uartBytesWaiting() if (queue_select == s_esp_now_queue) { Networking::EspNowEvent event; - xQueueReceive(queue_select, &event, 0); + xQueueReceive(s_esp_now_queue, &event, 0); ESP_LOGD(LOG_TAG, "ESP-NOW event: %u, rx-length: %ull.", event.type, event.rx_length); @@ -81,7 +84,6 @@ std::size_t s_uartBytesWaiting() if (s_uartBytesWaiting() >= 128) { s_sendUartData(bytes_waiting); - xTimerStop(s_timer, 0); } } } @@ -94,11 +96,26 @@ std::size_t s_uartBytesWaiting() if (event.type == UART_DATA) { - if (event.size >= 128) - s_sendUartData(event.size); + const std::size_t recv_size = s_uartBytesWaiting(); + if (recv_size >= 128) + s_sendUartData(recv_size); else xTimerReset(s_timer, 0); } + else if (event.type == UART_BUFFER_FULL) + { + const std::size_t recv_size = s_uartBytesWaiting(); + s_sendUartData(recv_size); + } + else if (event.type == UART_FIFO_OVF) + { + ESP_LOGE(LOG_TAG, "UART FIFO overflow. Flushing."); + Serial::discardRxBuffer(CONFIG_ESPTNL_UART); + } + } + else + { + ESP_LOGW(LOG_TAG, "Unknown event type."); } } }