Add latency simulation to uart_mock for USB UART test

Add inject_to_rx_buffer_delayed() to uart_mock which stages bytes
that aren't visible to available() until the delay elapses. This
simulates USB packet delivery latency.

The test uses a 40ms delay which is:
- Greater than the old ~2ms timeout (fails without fix)
- Less than the new 50ms fallback timeout (passes with fix)
This commit is contained in:
J. Nick Koston
2026-03-07 18:07:18 -10:00
parent ab08aa7553
commit 5319b8593b
5 changed files with 52 additions and 8 deletions
@@ -53,6 +53,14 @@ void MockUartComponent::loop() {
}
}
// Process staged RX - deliver bytes whose delay has elapsed
while (!this->staged_rx_.empty() && millis() >= this->staged_rx_.front().available_at_ms) {
auto &staged = this->staged_rx_.front();
ESP_LOGD(TAG, "Delivering %zu staged RX bytes", staged.data.size());
this->inject_to_rx_buffer(staged.data);
this->staged_rx_.pop_front();
}
// Process delayed responses
for (auto &response : this->responses_) {
if (response.delay_ms > 0 && response.last_match_ms > 0 && now - response.last_match_ms >= response.delay_ms) {
@@ -208,4 +216,15 @@ void MockUartComponent::inject_to_rx_buffer(const std::vector<uint8_t> &data) {
}
}
void MockUartComponent::inject_to_rx_buffer_delayed(const std::vector<uint8_t> &data, uint32_t delay_ms) {
if (!data.empty() && data.size() <= 64) {
char hex_buf[format_hex_pretty_size(64)];
ESP_LOGD(TAG, "Staging %zu RX bytes with %ums delay: %s", data.size(), delay_ms,
format_hex_pretty_to(hex_buf, sizeof(hex_buf), data.data(), data.size()));
} else if (data.size() > 64) {
ESP_LOGD(TAG, "Staging %zu RX bytes with %ums delay (too large to log inline)", data.size(), delay_ms);
}
this->staged_rx_.push_back({data, millis() + delay_ms});
}
} // namespace esphome::uart_mock