#include "uart_mitm.h" #include "esphome/core/log.h" #include "esphome/core/helpers.h" #define RX_SUPPRESS_INTERVAL 50 // Time in ms to suppress rx after tx on same bus #define RX_BLOCK_INTERVAL 50 // Time in ms to block before preparing a message to ship. #define RX_BUF_LEN 64 // Time in ms to block before preparing a message to ship. namespace esphome { namespace serial { static const char *const TAG = "uart_mitm"; static uint32_t rx1_suppress_until = 0; static uint32_t rx2_suppress_until = 0; static uint32_t rx1_block_until = 0; static uint32_t rx2_block_until = 0; static uint8_t rx1_buffer_idx = 0; static uint8_t rx2_buffer_idx = 0; static uint8_t rx1_buffer[RX_BUF_LEN]; static uint8_t rx2_buffer[RX_BUF_LEN]; void UARTMITM::loop() { uint8_t c; while (this->uart1_->available()) { this->uart1_->read_byte(&c); if (rx1_block_until < millis()) { // current millis is after our blocking deadline; we can ship // ... so ship! std::string hexString = format_hex(rx1_buffer, rx1_buffer_idx + 1); ESP_LOGD(TAG, "RX1: %s", hexString.c_str()); rx1_buffer_idx = 0; } rx1_block_until = millis() + RX_BLOCK_INTERVAL; if (rx1_suppress_until < millis()) { rx1_buffer[rx1_buffer_idx++] = c; if (rx1_buffer_idx == RX_BUF_LEN) { ESP_LOGW(TAG, "RX1: Somehow ran out of buf space."); rx1_buffer_idx = 0; } this->uart2_->write_byte(c); rx2_suppress_until = millis() + RX_SUPPRESS_INTERVAL; } } while (this->uart2_->available()) { this->uart2_->read_byte(&c); if (rx2_block_until < millis()) { // current millis is after our blocking deadline; we can ship // ... so ship! std::string hexString = format_hex(rx2_buffer, rx2_buffer_idx + 1); ESP_LOGD(TAG, "RX2: %s", hexString.c_str()); rx2_buffer_idx = 0; } rx2_block_until = millis() + RX_BLOCK_INTERVAL; if (rx2_suppress_until < millis()) { rx2_buffer[rx2_buffer_idx++] = c; if (rx2_buffer_idx == RX_BUF_LEN) { ESP_LOGW(TAG, "RX2: Somehow ran out of buf space."); rx2_buffer_idx = 0; } this->uart1_->write_byte(c); rx1_suppress_until = millis() + RX_SUPPRESS_INTERVAL; } } } void UARTMITM::dump_config() { ESP_LOGCONFIG(TAG, "UART MITM"); } } // namespace serial } // namespace esphome