Refactor bridge implementations to inherit from BridgeBase

This commit is contained in:
João Brázio
2025-09-08 02:03:08 +01:00
parent 537449e6af
commit 0051ccef26
7 changed files with 282 additions and 155 deletions

View File

@@ -47,6 +47,7 @@ build_src_filter =
+<*.cpp>
+<helpers/*.cpp>
+<helpers/radiolib/*.cpp>
+<helpers/bridges/BridgeBase.cpp>
+<helpers/ui/MomentaryButton.cpp>
; ----------------- ESP32 ---------------------

View File

@@ -0,0 +1,34 @@
#include "BridgeBase.h"
const char *BridgeBase::getLogDateTime() {
static char tmp[32];
uint32_t now = _rtc->getCurrentTime();
DateTime dt = DateTime(now);
sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
dt.year());
return tmp;
}
uint16_t BridgeBase::fletcher16(const uint8_t *data, size_t len) {
uint8_t sum1 = 0, sum2 = 0;
for (size_t i = 0; i < len; i++) {
sum1 = (sum1 + data[i]) % 255;
sum2 = (sum2 + sum1) % 255;
}
return (sum2 << 8) | sum1;
}
bool BridgeBase::validateChecksum(const uint8_t *data, size_t len, uint16_t received_checksum) {
uint16_t calculated_checksum = fletcher16(data, len);
return received_checksum == calculated_checksum;
}
void BridgeBase::handleReceivedPacket(mesh::Packet *packet) {
if (!_seen_packets.hasSeen(packet)) {
_mgr->queueInbound(packet, 0);
} else {
_mgr->free(packet);
}
}

View File

@@ -0,0 +1,84 @@
#pragma once
#include "helpers/AbstractBridge.h"
#include "helpers/SimpleMeshTables.h"
#include <RTClib.h>
/**
* @brief Base class implementing common bridge functionality
*
* This class provides common functionality used by different bridge implementations
* like packet tracking, checksum calculation, timestamping, and duplicate detection.
*
* Features:
* - Fletcher-16 checksum calculation for data integrity
* - Packet duplicate detection using SimpleMeshTables
* - Common timestamp formatting for debug logging
* - Shared packet management and queuing logic
*/
class BridgeBase : public AbstractBridge {
public:
virtual ~BridgeBase() = default;
protected:
/** Packet manager for allocating and queuing mesh packets */
mesh::PacketManager *_mgr;
/** RTC clock for timestamping debug messages */
mesh::RTCClock *_rtc;
/** Tracks seen packets to prevent loops in broadcast communications */
SimpleMeshTables _seen_packets;
/**
* @brief Constructs a BridgeBase instance
*
* @param mgr PacketManager for allocating and queuing packets
* @param rtc RTCClock for timestamping debug messages
*/
BridgeBase(mesh::PacketManager *mgr, mesh::RTCClock *rtc) : _mgr(mgr), _rtc(rtc) {}
/**
* @brief Gets formatted date/time string for logging
*
* Format: "HH:MM:SS - DD/MM/YYYY U"
*
* @return Formatted date/time string
*/
const char *getLogDateTime();
/**
* @brief Calculate Fletcher-16 checksum
*
* Based on: https://en.wikipedia.org/wiki/Fletcher%27s_checksum
* Used to verify data integrity of received packets
*
* @param data Pointer to data to calculate checksum for
* @param len Length of data in bytes
* @return Calculated Fletcher-16 checksum
*/
static uint16_t fletcher16(const uint8_t *data, size_t len);
/**
* @brief Validate received checksum against calculated checksum
*
* @param data Pointer to data to validate
* @param len Length of data in bytes
* @param received_checksum Checksum received with data
* @return true if checksum is valid, false otherwise
*/
bool validateChecksum(const uint8_t *data, size_t len, uint16_t received_checksum);
/**
* @brief Common packet handling for received packets
*
* Implements the standard pattern used by all bridges:
* - Check if packet was seen before using _seen_packets.hasSeen()
* - Queue packet for mesh processing if not seen before
* - Free packet if already seen to prevent duplicates
*
* @param packet The received mesh packet
*/
void handleReceivedPacket(mesh::Packet *packet);
};

View File

@@ -1,6 +1,5 @@
#include "ESPNowBridge.h"
#include <RTClib.h>
#include <WiFi.h>
#include <esp_wifi.h>
@@ -22,21 +21,8 @@ void ESPNowBridge::send_cb(const uint8_t *mac, esp_now_send_status_t status) {
}
}
// Fletcher16 checksum calculation
static uint16_t fletcher16(const uint8_t *data, size_t len) {
uint16_t sum1 = 0;
uint16_t sum2 = 0;
while (len--) {
sum1 = (sum1 + *data++) % 255;
sum2 = (sum2 + sum1) % 255;
}
return (sum2 << 8) | sum1;
}
ESPNowBridge::ESPNowBridge(mesh::PacketManager *mgr, mesh::RTCClock *rtc)
: _mgr(mgr), _rtc(rtc), _rx_buffer_pos(0) {
: BridgeBase(mgr, rtc), _rx_buffer_pos(0) {
_instance = this;
}
@@ -115,13 +101,12 @@ void ESPNowBridge::onDataRecv(const uint8_t *mac, const uint8_t *data, int32_t l
// Validate checksum
uint16_t received_checksum = (decrypted[0] << 8) | decrypted[1];
const size_t payloadLen = encryptedDataLen - CHECKSUM_SIZE;
uint16_t calculated_checksum = fletcher16(decrypted + CHECKSUM_SIZE, payloadLen);
if (received_checksum != calculated_checksum) {
if (!validateChecksum(decrypted + CHECKSUM_SIZE, payloadLen, received_checksum)) {
// Failed to decrypt - likely from a different network
#if MESH_PACKET_LOGGING
Serial.printf("%s: ESPNOW BRIDGE: RX checksum mismatch, rcv=0x%04X calc=0x%04X\n", getLogDateTime(),
received_checksum, calculated_checksum);
Serial.printf("%s: ESPNOW BRIDGE: RX checksum mismatch, rcv=0x%04X\n", getLogDateTime(),
received_checksum);
#endif
return;
}
@@ -146,23 +131,19 @@ void ESPNowBridge::onDataSent(const uint8_t *mac_addr, esp_now_send_status_t sta
}
void ESPNowBridge::onPacketReceived(mesh::Packet *packet) {
if (!_seen_packets.hasSeen(packet)) {
_mgr->queueInbound(packet, 0);
} else {
_mgr->free(packet);
}
handleReceivedPacket(packet);
}
void ESPNowBridge::onPacketTransmitted(mesh::Packet *packet) {
if (!_seen_packets.hasSeen(packet)) {
// First validate the packet pointer
if (!packet) {
// First validate the packet pointer
if (!packet) {
#if MESH_PACKET_LOGGING
Serial.printf("%s: ESPNOW BRIDGE: TX invalid packet pointer\n", getLogDateTime());
Serial.printf("%s: ESPNOW BRIDGE: TX invalid packet pointer\n", getLogDateTime());
#endif
return;
}
return;
}
if (!_seen_packets.hasSeen(packet)) {
// Create a temporary buffer just for size calculation and reuse for actual writing
uint8_t sizingBuffer[MAX_PAYLOAD_SIZE];
@@ -212,13 +193,4 @@ void ESPNowBridge::onPacketTransmitted(mesh::Packet *packet) {
}
}
const char *ESPNowBridge::getLogDateTime() {
static char tmp[32];
uint32_t now = _rtc->getCurrentTime();
DateTime dt = DateTime(now);
sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
dt.year());
return tmp;
}
#endif

View File

@@ -2,8 +2,7 @@
#include "MeshCore.h"
#include "esp_now.h"
#include "helpers/AbstractBridge.h"
#include "helpers/SimpleMeshTables.h"
#include "helpers/bridges/BridgeBase.h"
#ifdef WITH_ESPNOW_BRIDGE
@@ -44,21 +43,12 @@
* WITH_ESPNOW_BRIDGE_SECRET values. Packets encrypted with a different key will
* fail the checksum validation and be discarded.
*/
class ESPNowBridge : public AbstractBridge {
class ESPNowBridge : public BridgeBase {
private:
static ESPNowBridge *_instance;
static void recv_cb(const uint8_t *mac, const uint8_t *data, int32_t len);
static void send_cb(const uint8_t *mac, esp_now_send_status_t status);
/** Packet manager for allocating and queuing mesh packets */
mesh::PacketManager *_mgr;
/** RTC clock for timestamping debug messages */
mesh::RTCClock *_rtc;
/** Tracks seen packets to prevent loops in broadcast communications */
SimpleMeshTables _seen_packets;
/**
* ESP-NOW Protocol Structure:
* - ESP-NOW header: 20 bytes (handled by ESP-NOW protocol)
@@ -168,14 +158,6 @@ public:
* @param packet The mesh packet to transmit
*/
void onPacketTransmitted(mesh::Packet *packet) override;
/**
* Gets formatted date/time string for logging
* Format: "HH:MM:SS - DD/MM/YYYY U"
*
* @return Formatted date/time string
*/
const char *getLogDateTime();
};
#endif

View File

@@ -1,32 +1,11 @@
#include "RS232Bridge.h"
#include <HardwareSerial.h>
#include <RTClib.h>
#ifdef WITH_RS232_BRIDGE
// Static Fletcher-16 checksum calculation
// Based on: https://en.wikipedia.org/wiki/Fletcher%27s_checksum
// Used to verify data integrity of received packets
inline static uint16_t fletcher16(const uint8_t *bytes, const size_t len) {
uint8_t sum1 = 0, sum2 = 0;
for (size_t i = 0; i < len; i++) {
sum1 = (sum1 + bytes[i]) % 255;
sum2 = (sum2 + sum1) % 255;
}
return (sum2 << 8) | sum1;
};
const char* RS232Bridge::getLogDateTime() {
static char tmp[32];
uint32_t now = _rtc->getCurrentTime();
DateTime dt = DateTime(now);
sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(), dt.year());
return tmp;
}
RS232Bridge::RS232Bridge(Stream& serial, mesh::PacketManager* mgr, mesh::RTCClock* rtc) : _serial(&serial), _mgr(mgr), _rtc(rtc) {}
RS232Bridge::RS232Bridge(Stream &serial, mesh::PacketManager *mgr, mesh::RTCClock *rtc)
: BridgeBase(mgr, rtc), _serial(&serial) {}
void RS232Bridge::begin() {
#if !defined(WITH_RS232_BRIDGE_RX) || !defined(WITH_RS232_BRIDGE_TX)
@@ -46,27 +25,48 @@ void RS232Bridge::begin() {
#else
#error RS232Bridge was not tested on the current platform
#endif
((HardwareSerial*)_serial)->begin(115200);
((HardwareSerial *)_serial)->begin(115200);
}
void RS232Bridge::onPacketTransmitted(mesh::Packet* packet) {
void RS232Bridge::onPacketTransmitted(mesh::Packet *packet) {
// First validate the packet pointer
if (!packet) {
#if MESH_PACKET_LOGGING
Serial.printf("%s: RS232 BRIDGE: TX invalid packet pointer\n", getLogDateTime());
#endif
return;
}
if (!_seen_packets.hasSeen(packet)) {
uint8_t buffer[MAX_SERIAL_PACKET_SIZE];
uint16_t len = packet->writeTo(buffer + 4);
buffer[0] = (SERIAL_PKT_MAGIC >> 8) & 0xFF;
buffer[1] = SERIAL_PKT_MAGIC & 0xFF;
buffer[2] = (len >> 8) & 0xFF;
buffer[3] = len & 0xFF;
// Check if packet fits within our maximum payload size
if (len > (MAX_TRANS_UNIT + 1)) {
#if MESH_PACKET_LOGGING
Serial.printf("%s: RS232 BRIDGE: TX packet too large (payload=%d, max=%d)\n", getLogDateTime(), len,
MAX_TRANS_UNIT + 1);
#endif
return;
}
// Build packet header
buffer[0] = (SERIAL_PKT_MAGIC >> 8) & 0xFF; // Magic high byte
buffer[1] = SERIAL_PKT_MAGIC & 0xFF; // Magic low byte
buffer[2] = (len >> 8) & 0xFF; // Length high byte
buffer[3] = len & 0xFF; // Length low byte
// Calculate checksum over the payload
uint16_t checksum = fletcher16(buffer + 4, len);
buffer[4 + len] = (checksum >> 8) & 0xFF;
buffer[5 + len] = checksum & 0xFF;
buffer[4 + len] = (checksum >> 8) & 0xFF; // Checksum high byte
buffer[5 + len] = checksum & 0xFF; // Checksum low byte
// Send complete packet
_serial->write(buffer, len + SERIAL_OVERHEAD);
#if MESH_PACKET_LOGGING
Serial.printf("%s: BRIDGE: TX, len=%d crc=0x%04x\n", getLogDateTime(), len, checksum);
Serial.printf("%s: RS232 BRIDGE: TX, len=%d crc=0x%04x\n", getLogDateTime(), len, checksum);
#endif
}
}
@@ -81,7 +81,12 @@ void RS232Bridge::loop() {
(_rx_buffer_pos == 1 && b == (SERIAL_PKT_MAGIC & 0xFF))) {
_rx_buffer[_rx_buffer_pos++] = b;
} else {
// Invalid magic byte, reset and start over
_rx_buffer_pos = 0;
// Check if this byte could be the start of a new magic word
if (b == ((SERIAL_PKT_MAGIC >> 8) & 0xFF)) {
_rx_buffer[_rx_buffer_pos++] = b;
}
}
} else {
// Reading length, payload, and checksum
@@ -89,22 +94,44 @@ void RS232Bridge::loop() {
if (_rx_buffer_pos >= 4) {
uint16_t len = (_rx_buffer[2] << 8) | _rx_buffer[3];
// Validate length field
if (len > (MAX_TRANS_UNIT + 1)) {
#if MESH_PACKET_LOGGING
Serial.printf("%s: RS232 BRIDGE: RX invalid length %d, resetting\n", getLogDateTime(), len);
#endif
_rx_buffer_pos = 0; // Invalid length, reset
return;
continue;
}
if (_rx_buffer_pos == len + SERIAL_OVERHEAD) { // Full packet received
uint16_t checksum = (_rx_buffer[4 + len] << 8) | _rx_buffer[5 + len];
if (checksum == fletcher16(_rx_buffer + 4, len)) {
uint16_t received_checksum = (_rx_buffer[4 + len] << 8) | _rx_buffer[5 + len];
if (validateChecksum(_rx_buffer + 4, len, received_checksum)) {
#if MESH_PACKET_LOGGING
Serial.printf("%s: BRIDGE: RX, len=%d crc=0x%04x\n", getLogDateTime(), len, checksum);
Serial.printf("%s: RS232 BRIDGE: RX, len=%d crc=0x%04x\n", getLogDateTime(), len,
received_checksum);
#endif
mesh::Packet* pkt = _mgr->allocNew();
mesh::Packet *pkt = _mgr->allocNew();
if (pkt) {
pkt->readFrom(_rx_buffer + 4, len);
onPacketReceived(pkt);
if (pkt->readFrom(_rx_buffer + 4, len)) {
onPacketReceived(pkt);
} else {
#if MESH_PACKET_LOGGING
Serial.printf("%s: RS232 BRIDGE: RX failed to parse packet\n", getLogDateTime());
#endif
_mgr->free(pkt);
}
} else {
#if MESH_PACKET_LOGGING
Serial.printf("%s: RS232 BRIDGE: RX failed to allocate packet\n", getLogDateTime());
#endif
}
} else {
#if MESH_PACKET_LOGGING
Serial.printf("%s: RS232 BRIDGE: RX checksum mismatch, rcv=0x%04x\n", getLogDateTime(),
received_checksum);
#endif
}
_rx_buffer_pos = 0; // Reset for next packet
}
@@ -113,12 +140,8 @@ void RS232Bridge::loop() {
}
}
void RS232Bridge::onPacketReceived(mesh::Packet* packet) {
if (!_seen_packets.hasSeen(packet)) {
_mgr->queueInbound(packet, 0);
} else {
_mgr->free(packet);
}
void RS232Bridge::onPacketReceived(mesh::Packet *packet) {
handleReceivedPacket(packet);
}
#endif

View File

@@ -1,7 +1,7 @@
#pragma once
#include "helpers/AbstractBridge.h"
#include "helpers/SimpleMeshTables.h"
#include "helpers/bridges/BridgeBase.h"
#include <Stream.h>
#ifdef WITH_RS232_BRIDGE
@@ -15,21 +15,22 @@
*
* Features:
* - Point-to-point communication over hardware UART
* - Fletcher-16 checksum for data integrity verification
* - Magic header for packet synchronization
* - Fletcher-16 checksum for data integrity verification
* - Magic header for packet synchronization and frame alignment
* - Duplicate packet detection using SimpleMeshTables tracking
* - Configurable RX/TX pins via build defines
* - Baud rate fixed at 115200
* - Fixed baud rate at 115200 for consistent timing
*
* Packet Structure:
* [2 bytes] Magic Header - Used to identify start of packet
* [2 bytes] Fletcher-16 checksum - Data integrity check
* [1 byte] Payload length
* [n bytes] Packet payload
* [2 bytes] Magic Header (0xC03E) - Used to identify start of RS232Bridge packets
* [2 bytes] Payload Length - Length of the mesh packet payload
* [n bytes] Mesh Packet Payload - The actual mesh packet data
* [2 bytes] Fletcher-16 Checksum - Calculated over the payload for integrity verification
*
* The Fletcher-16 checksum is used to validate packet integrity and detect
* corrupted or malformed packets. It provides error detection capabilities
* suitable for serial communication where noise or timing issues could
* corrupt data.
* The Fletcher-16 checksum is calculated over the mesh packet payload and provides
* error detection capabilities suitable for serial communication where electrical
* noise, timing issues, or hardware problems could corrupt data. The checksum
* validation ensures only valid packets are forwarded to the mesh.
*
* Configuration:
* - Define WITH_RS232_BRIDGE to enable this bridge
@@ -37,12 +38,13 @@
* - Define WITH_RS232_BRIDGE_TX with the TX pin number
*
* Platform Support:
* - ESP32 targets
* - NRF52 targets
* - RP2040 targets
* - STM32 targets
* Different platforms require different pin configuration methods:
* - ESP32: Uses HardwareSerial::setPins(rx, tx)
* - NRF52: Uses HardwareSerial::setPins(rx, tx)
* - RP2040: Uses SerialUART::setRX(rx) and SerialUART::setTX(tx)
* - STM32: Uses HardwareSerial::setRx(rx) and HardwareSerial::setTx(tx)
*/
class RS232Bridge : public AbstractBridge {
class RS232Bridge : public BridgeBase {
public:
/**
* @brief Constructs an RS232Bridge instance
@@ -51,69 +53,98 @@ public:
* @param mgr PacketManager for allocating and queuing packets
* @param rtc RTCClock for timestamping debug messages
*/
RS232Bridge(Stream& serial, mesh::PacketManager* mgr, mesh::RTCClock* rtc);
RS232Bridge(Stream &serial, mesh::PacketManager *mgr, mesh::RTCClock *rtc);
/**
* Initializes the RS232 bridge
*
* - Configures UART pins based on platform
* - Sets baud rate to 115200
*
* - Validates that RX/TX pins are defined
* - Configures UART pins based on target platform
* - Sets baud rate to 115200 for consistent communication
* - Platform-specific pin configuration methods are used
*/
void begin() override;
/**
* @brief Main loop handler
* Processes incoming serial data and builds packets
* @brief Main loop handler for processing incoming serial data
*
* Implements a state machine for packet reception:
* 1. Searches for magic header bytes for packet synchronization
* 2. Reads length field to determine expected packet size
* 3. Validates packet length against maximum allowed size
* 4. Receives complete packet payload and checksum
* 5. Validates Fletcher-16 checksum for data integrity
* 6. Creates mesh packet and forwards if valid
*/
void loop() override;
/**
* @brief Called when a packet needs to be transmitted over serial
* Formats and sends the packet with proper framing
*
* Formats the mesh packet with RS232 framing protocol:
* - Adds magic header for synchronization
* - Includes payload length field
* - Calculates Fletcher-16 checksum over payload
* - Transmits complete framed packet
* - Uses duplicate detection to prevent retransmission
*
* @param packet The mesh packet to transmit
*/
void onPacketTransmitted(mesh::Packet* packet) override;
void onPacketTransmitted(mesh::Packet *packet) override;
/**
* @brief Called when a complete packet has been received from serial
* Queues the packet for mesh processing if checksum is valid
*
* @param packet The received mesh packet
* @brief Called when a complete valid packet has been received from serial
*
* Forwards the received packet to the mesh for processing.
* The packet has already been validated for checksum integrity
* and parsed successfully at this point.
*
* @param packet The received mesh packet ready for processing
*/
void onPacketReceived(mesh::Packet* packet) override;
void onPacketReceived(mesh::Packet *packet) override;
private:
/** Helper function to get formatted timestamp for logging */
const char* getLogDateTime();
/**
* RS232 Protocol Structure:
* - Magic header: 2 bytes (packet identification)
* - Length field: 2 bytes (payload length)
* - Payload: variable bytes (mesh packet data)
* - Checksum: 2 bytes (Fletcher-16 over payload)
* Total overhead: 6 bytes
*/
/** Magic number to identify start of RS232 packets */
/** Magic number to identify start of RS232Bridge packets */
static constexpr uint16_t SERIAL_PKT_MAGIC = 0xC03E;
/**
* @brief The total overhead of the serial protocol in bytes.
* [MAGIC_WORD (2 bytes)] [LENGTH (2 bytes)] [PAYLOAD (variable)] [CHECKSUM (2 bytes)]
* Size constants for packet parsing and construction
*/
static constexpr uint16_t SERIAL_OVERHEAD = 6;
static constexpr uint16_t MAGIC_HEADER_SIZE = 2;
static constexpr uint16_t LENGTH_FIELD_SIZE = 2;
static constexpr uint16_t CHECKSUM_SIZE = 2;
/**
* @brief The maximum size of a packet on the serial line.
* @brief The total overhead of the serial protocol in bytes.
* Includes: MAGIC_WORD (2) + LENGTH (2) + CHECKSUM (2) = 6 bytes
*/
static constexpr uint16_t SERIAL_OVERHEAD = MAGIC_HEADER_SIZE + LENGTH_FIELD_SIZE + CHECKSUM_SIZE;
/**
* @brief The maximum size of a complete packet on the serial line.
*
* This is calculated as the sum of:
* - 1 byte for the packet header (from mesh::Packet)
* - 4 bytes for transport codes (from mesh::Packet)
* - 1 byte for the path length (from mesh::Packet)
* - MAX_PATH_SIZE for the path itself (from MeshCore.h)
* - MAX_PACKET_PAYLOAD for the payload (from MeshCore.h)
* - SERIAL_OVERHEAD for the serial framing
* - MAX_TRANS_UNIT + 1 for the maximum mesh packet size
* - SERIAL_OVERHEAD for the framing (magic + length + checksum)
*/
static constexpr uint16_t MAX_SERIAL_PACKET_SIZE = (MAX_TRANS_UNIT + 1) + SERIAL_OVERHEAD;
Stream* _serial;
mesh::PacketManager* _mgr;
mesh::RTCClock* _rtc;
SimpleMeshTables _seen_packets;
uint8_t _rx_buffer[MAX_SERIAL_PACKET_SIZE]; // Buffer for serial data
/** Hardware serial port interface */
Stream *_serial;
/** Buffer for building received packets */
uint8_t _rx_buffer[MAX_SERIAL_PACKET_SIZE];
/** Current position in the receive buffer */
uint16_t _rx_buffer_pos = 0;
};