From 2f78308de0efdbedf1414177e2d0fceb6b9287eb Mon Sep 17 00:00:00 2001 From: Igor Mammedov Date: Thu, 23 May 2019 18:45:06 +0200 Subject: [PATCH] uart: add drain() API it would allow to empty RX buffer when necessary Signed-off-by: Igor Mammedov --- esphome/components/uart/uart.cpp | 29 +++++++++++++++++++++++++++++ esphome/components/uart/uart.h | 5 +++++ 2 files changed, 34 insertions(+) diff --git a/esphome/components/uart/uart.cpp b/esphome/components/uart/uart.cpp index 56661b8aa7..ca74885393 100644 --- a/esphome/components/uart/uart.cpp +++ b/esphome/components/uart/uart.cpp @@ -98,6 +98,14 @@ void UARTComponent::flush() { ESP_LOGVV(TAG, " Flushing..."); this->hw_serial_->flush(); } + +void UARTComponent::drain() { + for (int i = 0; this->available(); i++) { + uint8_t junk; + this->read_byte(&junk); + ESP_LOGVV(TAG, "Draining RX[%d]: %0x", i, junk); + } +} #endif // ESP32 #ifdef ARDUINO_ARCH_ESP8266 @@ -235,6 +243,19 @@ void UARTComponent::flush() { } } +void UARTComponent::drain() { + if (this->hw_serial_ != nullptr) { + for (int i = 0; this->available(); i++) { + uint8_t junk; + this->read_byte(&junk); + ESP_LOGVV(TAG, "Draining RX[%d]: %0x", i, junk); + } + } else { + this->sw_serial_->drain(); + } +} + + void ESP8266SoftwareSerial::setup(int8_t tx_pin, int8_t rx_pin, uint32_t baud_rate) { this->bit_time_ = F_CPU / baud_rate; if (tx_pin != -1) { @@ -321,6 +342,14 @@ uint8_t ESP8266SoftwareSerial::peek_byte() { return this->rx_buffer_[this->rx_out_pos_]; } void ESP8266SoftwareSerial::flush() { this->rx_in_pos_ = this->rx_out_pos_ = 0; } + +void ESP8266SoftwareSerial::drain() { + for (int i = 0; this->available(); i++) { + uint8_t junk = this->read_byte(); + ESP_LOGVV(TAG, "Draining RX[%d]: %0x", i, junk); + } +} + int ESP8266SoftwareSerial::available() { int avail = int(this->rx_in_pos_) - int(this->rx_out_pos_); if (avail < 0) diff --git a/esphome/components/uart/uart.h b/esphome/components/uart/uart.h index 005536de4a..28cf7f69d0 100644 --- a/esphome/components/uart/uart.h +++ b/esphome/components/uart/uart.h @@ -16,6 +16,7 @@ class ESP8266SoftwareSerial { uint8_t peek_byte(); void flush(); + void drain(); void write_byte(uint8_t data); @@ -62,6 +63,8 @@ class UARTComponent : public Component, public Stream { void flush() override; + void drain(); + float get_setup_priority() const override { return setup_priority::BUS; } size_t write(uint8_t data) override; @@ -109,6 +112,8 @@ class UARTDevice : public Stream { void flush() override { return this->parent_->flush(); } + void drain() { return this->parent_->drain(); } + size_t write(uint8_t data) override { return this->parent_->write(data); } int read() override { return this->parent_->read(); } int peek() override { return this->parent_->peek(); }