From 124758ade2b8d9e94d91ff8ce1a6424e30dd66ee Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 30 Nov 2023 16:04:02 +0700 Subject: [PATCH] add availableForWrite() for uart --- cores/nRF5/HardwareSerial.h | 1 + cores/nRF5/RingBuffer.cpp | 8 ++++++++ cores/nRF5/RingBuffer.h | 13 +++++++------ cores/nRF5/Uart.cpp | 6 ++++++ cores/nRF5/Uart.h | 1 + 5 files changed, 23 insertions(+), 6 deletions(-) diff --git a/cores/nRF5/HardwareSerial.h b/cores/nRF5/HardwareSerial.h index 50bb338a8..602281eb5 100644 --- a/cores/nRF5/HardwareSerial.h +++ b/cores/nRF5/HardwareSerial.h @@ -70,6 +70,7 @@ class HardwareSerial : public Stream virtual void flush(void) = 0; virtual size_t write(uint8_t) = 0; virtual size_t write(const uint8_t *buffer, size_t size) = 0; + virtual int availableForWrite(void); using Print::write; // pull in write(str) from Print virtual operator bool() = 0; }; diff --git a/cores/nRF5/RingBuffer.cpp b/cores/nRF5/RingBuffer.cpp index d877a6e30..9437dbd3f 100644 --- a/cores/nRF5/RingBuffer.cpp +++ b/cores/nRF5/RingBuffer.cpp @@ -67,6 +67,14 @@ int RingBuffer::available() return delta; } +int RingBuffer::availableForStore() { + if (_iHead >= _iTail) { + return SERIAL_BUFFER_SIZE - 1 - _iHead + _iTail; + } else { + return _iTail - _iHead - 1; + } +} + int RingBuffer::peek() { if(_iTail == _iHead) diff --git a/cores/nRF5/RingBuffer.h b/cores/nRF5/RingBuffer.h index cf8f77d35..d35737fd7 100644 --- a/cores/nRF5/RingBuffer.h +++ b/cores/nRF5/RingBuffer.h @@ -39,14 +39,15 @@ class RingBuffer public: RingBuffer( void ) ; void store_char( uint8_t c ) ; - void clear(); - int read_char(); - int available(); - int peek(); - bool isFull(); + void clear(); + int read_char(); + int available(); + int availableForStore(); + int peek(); + bool isFull(); private: - int nextIndex(int index); + int nextIndex(int index); } ; #endif /* _RING_BUFFER_ */ diff --git a/cores/nRF5/Uart.cpp b/cores/nRF5/Uart.cpp index 9b598219b..874dcad14 100644 --- a/cores/nRF5/Uart.cpp +++ b/cores/nRF5/Uart.cpp @@ -253,6 +253,12 @@ size_t Uart::write(const uint8_t *buffer, size_t size) return sent; } +int Uart::availableForWrite(void) { + // UART does not use ring buffer for TX, therefore it is either busy or not + UBaseType_t available = uxSemaphoreGetCount(_end_tx_sem); + return available ? SERIAL_BUFFER_SIZE : 0; +} + //------------- Serial1 (or Serial in case of nRF52832) -------------// #ifdef NRF52832_XXAA Uart Serial( NRF_UARTE0, UARTE0_UART0_IRQn, PIN_SERIAL_RX, PIN_SERIAL_TX ); diff --git a/cores/nRF5/Uart.h b/cores/nRF5/Uart.h index 9aa78fceb..f21f3d1c2 100644 --- a/cores/nRF5/Uart.h +++ b/cores/nRF5/Uart.h @@ -39,6 +39,7 @@ class Uart : public HardwareSerial void begin(unsigned long baudrate, uint16_t config); void end(); int available(); + int availableForWrite(void); int peek(); int read(); void flush();