Skip to content

Commit

Permalink
AP_HAL_ESP32: check UART thread ownership
Browse files Browse the repository at this point in the history
Signed-off-by: Rhys Mainwaring <[email protected]>
  • Loading branch information
srmainwaring committed Jan 4, 2025
1 parent 5f8a655 commit 19978df
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
26 changes: 22 additions & 4 deletions libraries/AP_HAL_ESP32/UARTDriver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ void UARTDriver::vprintf(const char *fmt, va_list ap)

void UARTDriver::_begin(uint32_t b, uint16_t rxS, uint16_t txS)
{
if (b == 0 && txS == 0 && rxS == 0 && _initialized) {
// the thread owning this port has changed
_uart_owner_thd = xTaskGetCurrentTaskHandle();
return;
}

if (uart_num < ARRAY_SIZE(uart_desc)) {
uart_port_t p = uart_desc[uart_num].port;
if (!_initialized) {
Expand All @@ -58,6 +64,7 @@ void UARTDriver::_begin(uint32_t b, uint16_t rxS, uint16_t txS)
uart_driver_install(p, 2*UART_HW_FIFO_LEN(p), 0, 0, nullptr, 0);
_readbuf.set_size(RX_BUF_SIZE);
_writebuf.set_size(TX_BUF_SIZE);
_uart_owner_thd = xTaskGetCurrentTaskHandle();

_initialized = true;
} else {
Expand Down Expand Up @@ -98,7 +105,7 @@ bool UARTDriver::tx_pending()

uint32_t UARTDriver::_available()
{
if (!_initialized) {
if (!_initialized || _uart_owner_thd != xTaskGetCurrentTaskHandle()) {
return 0;
}
return _readbuf.available();
Expand All @@ -117,6 +124,10 @@ uint32_t UARTDriver::txspace()

ssize_t IRAM_ATTR UARTDriver::_read(uint8_t *buffer, uint16_t count)
{
if (_uart_owner_thd != xTaskGetCurrentTaskHandle()) {
return -1;
}

if (!_initialized) {
return -1;
}
Expand Down Expand Up @@ -184,9 +195,16 @@ size_t IRAM_ATTR UARTDriver::_write(const uint8_t *buffer, size_t size)

bool UARTDriver::_discard_input()
{
//uart_port_t p = uart_desc[uart_num].port;
//return uart_flush_input(p) == ESP_OK;
return false;
if (_uart_owner_thd != xTaskGetCurrentTaskHandle()) {
return false;
}
if (!_initialized) {
return false;
}

_readbuf.clear();

return true;
}

// record timestamp of new incoming data
Expand Down
5 changes: 5 additions & 0 deletions libraries/AP_HAL_ESP32/UARTDriver.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
#include "driver/gpio.h"
#include "driver/uart.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

namespace ESP32
{

Expand Down Expand Up @@ -92,6 +95,8 @@ class UARTDriver : public AP_HAL::UARTDriver
uint8_t _receive_timestamp_idx;
uint32_t _baudrate;

const tskTaskControlBlock* _uart_owner_thd;

void _receive_timestamp_update(void);

protected:
Expand Down

0 comments on commit 19978df

Please sign in to comment.