mirror of
https://github.com/esphome/esphome.git
synced 2026-10-19 12:42:50 +00:00
[uart] Add discard_available to drop stale receive bytes (#21029)
This commit is contained in:
@@ -33,6 +33,13 @@ void UARTDevice::check_uart_settings(uint32_t baud_rate, uint8_t stop_bits, UART
|
||||
}
|
||||
}
|
||||
|
||||
void UARTDevice::discard_available() {
|
||||
UARTComponent *parent = this->parent_;
|
||||
uint8_t byte;
|
||||
while (parent->available() && parent->read_byte(&byte)) {
|
||||
}
|
||||
}
|
||||
|
||||
const LogString *parity_to_str(UARTParityOptions parity) {
|
||||
return UARTParityStrings::get_log_str(static_cast<uint8_t>(parity), UARTParityStrings::LAST_INDEX);
|
||||
}
|
||||
|
||||
@@ -90,6 +90,9 @@ class UARTDevice {
|
||||
count);
|
||||
}
|
||||
|
||||
/// Read and drop every byte waiting in the receive buffer.
|
||||
void discard_available();
|
||||
|
||||
UARTFlushResult flush() { return this->parent_->flush(); }
|
||||
|
||||
// Compat APIs
|
||||
|
||||
@@ -141,4 +141,42 @@ TEST(UARTReadAvailableTest, ChunksWithCountStopEarly) {
|
||||
EXPECT_EQ(uart.remaining(), 14u);
|
||||
}
|
||||
|
||||
TEST(UARTReadAvailableTest, DiscardDropsEveryWaitingByte) {
|
||||
::testing::NiceMock<FakeRxUART> uart(make_bytes(5));
|
||||
UARTDevice dev(&uart);
|
||||
dev.discard_available();
|
||||
EXPECT_EQ(uart.remaining(), 0u);
|
||||
}
|
||||
|
||||
TEST(UARTReadAvailableTest, DiscardWithNothingAvailableDoesNotRead) {
|
||||
::testing::NiceMock<FakeRxUART> uart(std::vector<uint8_t>{});
|
||||
UARTDevice dev(&uart);
|
||||
dev.discard_available();
|
||||
EXPECT_TRUE(uart.read_sizes.empty());
|
||||
}
|
||||
|
||||
TEST(UARTReadAvailableTest, DiscardDropsBytesThatArriveWhileDraining) {
|
||||
::testing::NiceMock<FakeRxUART> uart(std::vector<uint8_t>{1, 2});
|
||||
bool appended = false;
|
||||
ON_CALL(uart, available()).WillByDefault(Invoke([&]() -> size_t {
|
||||
if (!appended && uart.read_sizes.size() == 1) {
|
||||
uart.append({9, 9});
|
||||
appended = true;
|
||||
}
|
||||
return uart.remaining();
|
||||
}));
|
||||
UARTDevice dev(&uart);
|
||||
dev.discard_available();
|
||||
EXPECT_TRUE(appended);
|
||||
EXPECT_EQ(uart.remaining(), 0u);
|
||||
}
|
||||
|
||||
TEST(UARTReadAvailableTest, DiscardStopsOnReadFailure) {
|
||||
::testing::NiceMock<FakeRxUART> uart(make_bytes(5));
|
||||
uart.fail_after_reads = 2;
|
||||
UARTDevice dev(&uart);
|
||||
dev.discard_available();
|
||||
EXPECT_EQ(uart.read_sizes.size(), 3u);
|
||||
}
|
||||
|
||||
} // namespace esphome::uart::testing
|
||||
|
||||
Reference in New Issue
Block a user