/* * UARTDRIVER.CPP - UART Protocol Driver Implementation */ #include "UARTDriver.hpp" #define TAG "UARTHandler" #include "../../../Logging/Logging.hpp" UARTDriver::UARTDriver(uint8_t txPin, uint8_t rxPin, uint32_t baudRate) : _serial(Serial2) , _txPin(txPin) , _rxPin(rxPin) , _baudRate(baudRate) , _ready(false) , _bufferIndex(0) , _messageCount(0) , _errorCount(0) , _callback(nullptr) { resetBuffer(); } UARTDriver::~UARTDriver() { _serial.end(); } void UARTDriver::begin() { LOG_INFO(TAG, "Initializing UART Command Handler"); LOG_INFO(TAG, " TX Pin: GPIO%d", _txPin); LOG_INFO(TAG, " RX Pin: GPIO%d", _rxPin); LOG_INFO(TAG, " Baud Rate: %u", _baudRate); // Initialize Serial2 with custom pins _serial.begin(_baudRate, SERIAL_8N1, _rxPin, _txPin); // Clear any garbage in the buffer while (_serial.available()) { _serial.read(); } _ready = true; LOG_INFO(TAG, "UART Command Handler ready"); } void UARTDriver::loop() { if (!_ready) return; // Process all available bytes while (_serial.available()) { char c = _serial.read(); // Check for message delimiter (newline) if (c == '\n' || c == '\r') { if (_bufferIndex > 0) { // Null-terminate and process _buffer[_bufferIndex] = '\0'; processLine(_buffer); resetBuffer(); } // Skip empty lines continue; } // Add character to buffer if (_bufferIndex < BUFFER_SIZE - 1) { _buffer[_bufferIndex++] = c; } else { // Buffer overflow - discard and reset LOG_ERROR(TAG, "UART buffer overflow, discarding message"); _errorCount++; resetBuffer(); } } } void UARTDriver::setCallback(MessageCallback callback) { _callback = callback; } void UARTDriver::send(const String& response) { if (!_ready) { LOG_ERROR(TAG, "UART not ready, cannot send response"); return; } _serial.print(response); _serial.print('\n'); // Newline delimiter _serial.flush(); // Ensure data is sent LOG_DEBUG(TAG, "UART TX: %s", response.c_str()); } void UARTDriver::processLine(const char* line) { LOG_DEBUG(TAG, "UART RX: %s", line); // Skip empty lines or whitespace-only if (strlen(line) == 0) return; // Parse JSON JsonDocument doc; DeserializationError error = deserializeJson(doc, line); if (error) { LOG_ERROR(TAG, "UART JSON parse error: %s", error.c_str()); _errorCount++; // Send error response back JsonDocument errorDoc; errorDoc["status"] = "ERROR"; errorDoc["type"] = "parse_error"; errorDoc["payload"] = error.c_str(); String errorResponse; serializeJson(errorDoc, errorResponse); send(errorResponse); return; } _messageCount++; // Invoke callback if set if (_callback) { _callback(doc); } else { LOG_WARNING(TAG, "UART message received but no callback set"); } } void UARTDriver::resetBuffer() { _bufferIndex = 0; memset(_buffer, 0, BUFFER_SIZE); }