From 4b70ee863df0b6711da561c4694f97c2e765716e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Br=C3=A1zio?= Date: Fri, 27 Jun 2025 19:55:17 +0100 Subject: [PATCH 1/6] Serial bridge implementation --- examples/simple_repeater/main.cpp | 18 +++- platformio.ini | 1 + src/Dispatcher.cpp | 24 ++++- src/Dispatcher.h | 5 ++ src/bridge/serial/Packet.h | 58 +++++++++++++ src/bridge/serial/PacketQueue.h | 113 ++++++++++++++++++++++++ src/bridge/serial/SerialBridge.cpp | 135 +++++++++++++++++++++++++++++ src/bridge/serial/SerialBridge.h | 73 ++++++++++++++++ 8 files changed, 422 insertions(+), 5 deletions(-) create mode 100644 src/bridge/serial/Packet.h create mode 100644 src/bridge/serial/PacketQueue.h create mode 100644 src/bridge/serial/SerialBridge.cpp create mode 100644 src/bridge/serial/SerialBridge.h diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index c33cadda..4edca23d 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -72,6 +72,11 @@ static UITask ui_task(display); #endif +#ifdef BRIDGE_OVER_SERIAL +#include "bridge/serial/SerialBridge.h" +bridge::SerialBridge *bridge_interface; +#endif + #define FIRMWARE_ROLE "repeater" #define PACKET_LOG_FILE "/packet_log" @@ -752,7 +757,14 @@ void setup() { } #endif - if (!radio_init()) { halt(); } +#ifdef BRIDGE_OVER_SERIAL + bridge_interface = new bridge::SerialBridge(); + bridge_interface->setup(); +#endif + + if (!radio_init()) { + halt(); + } fast_rng.begin(radio_get_rng_seed()); @@ -825,6 +837,10 @@ void loop() { command[0] = 0; // reset command buffer } +#ifdef BRIDGE_OVER_SERIAL + bridge_interface->loop(); +#endif + the_mesh.loop(); sensors.loop(); } diff --git a/platformio.ini b/platformio.ini index 90e7cfb0..36cdf760 100644 --- a/platformio.ini +++ b/platformio.ini @@ -32,6 +32,7 @@ build_flags = -w -DNDEBUG -DRADIOLIB_STATIC_ONLY=1 -DRADIOLIB_GODMODE=1 build_src_filter = +<*.cpp> + + + ; ----------------- ESP32 --------------------- diff --git a/src/Dispatcher.cpp b/src/Dispatcher.cpp index 7f39dc49..08cca61e 100644 --- a/src/Dispatcher.cpp +++ b/src/Dispatcher.cpp @@ -1,7 +1,7 @@ #include "Dispatcher.h" #if MESH_PACKET_LOGGING - #include +#include #endif #include @@ -104,6 +104,7 @@ void Dispatcher::loop() { processRecvPacket(pkt); } } + checkRecv(); checkSend(); } @@ -115,6 +116,18 @@ void Dispatcher::checkRecv() { { uint8_t raw[MAX_TRANS_UNIT+1]; int len = _radio->recvRaw(raw, MAX_TRANS_UNIT); + +#ifdef BRIDGE_OVER_SERIAL + // We are basically stamping metadata from the last RF packet into something that came from serial, + // it works for now. But long term the code on checkRecv() should be refactored to be able to deal + // with both use cases without dupeing the existing code. I've chosen [for now] not to dupe and just + // fake the metadata. + + if (len == 0) { + len = bridge_interface->getPacket(raw); + } +#endif + if (len > 0) { logRxRaw(_radio->getLastSNR(), _radio->getLastRSSI(), raw, len); @@ -280,7 +293,11 @@ void Dispatcher::checkSend() { } outbound_expiry = futureMillis(max_airtime); - #if MESH_PACKET_LOGGING +#ifdef BRIDGE_OVER_SERIAL + bridge_interface->sendPacket(outbound); +#endif + +#if MESH_PACKET_LOGGING Serial.print(getLogDateTime()); Serial.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, outbound->getPayloadType(), outbound->isRouteDirect() ? "D" : "F", outbound->payload_len); @@ -290,7 +307,7 @@ void Dispatcher::checkSend() { } else { Serial.printf("\n"); } - #endif +#endif } } } @@ -328,5 +345,4 @@ bool Dispatcher::millisHasNowPassed(unsigned long timestamp) const { unsigned long Dispatcher::futureMillis(int millis_from_now) const { return _ms->getMillis() + millis_from_now; } - } \ No newline at end of file diff --git a/src/Dispatcher.h b/src/Dispatcher.h index 2200f81b..98184b50 100644 --- a/src/Dispatcher.h +++ b/src/Dispatcher.h @@ -6,6 +6,11 @@ #include #include +#ifdef BRIDGE_OVER_SERIAL +#include "bridge/serial/SerialBridge.h" +extern bridge::SerialBridge *bridge_interface; +#endif + namespace mesh { /** diff --git a/src/bridge/serial/Packet.h b/src/bridge/serial/Packet.h new file mode 100644 index 00000000..fbb4155a --- /dev/null +++ b/src/bridge/serial/Packet.h @@ -0,0 +1,58 @@ +/** + * MeshCore - A new lightweight, hybrid routing mesh protocol for packet radios + * Copyright (c) 2025 Scott Powell / rippleradios.com + * + * This project is maintained by the contributors listed in + * https://github.com/ripplebiz/MeshCore/graphs/contributors + * + * MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ +#pragma once + +#include "MeshCore.h" + +#include + +namespace bridge { + +/* + * +----------------------------------------------------+ + * | SERIAL PACKET SPEC | + * +-----------+---------+------------------------------+ + * | TYPE | NAME | DESCRIPTION | + * +-----------+---------+------------------------------+ + * | uint16_t | MAGIC | The packet start marker | + * | uint16_t | LEN | Length of the payload | + * | uint16_t | CRC | Checksum for error checking | + * | uint8_t[] | PAYLOAD | Actual rf packet data | + * +-----------+---------+------------------------------+ + */ +#define SERIAL_PKT_MAGIC 0xdead + +struct Packet { + uint16_t magic, len, crc; + uint8_t payload[MAX_TRANS_UNIT]; + + Packet() : magic(SERIAL_PKT_MAGIC), len(0), crc(0) {} +}; + +} // namespace bridge \ No newline at end of file diff --git a/src/bridge/serial/PacketQueue.h b/src/bridge/serial/PacketQueue.h new file mode 100644 index 00000000..a83d8f2e --- /dev/null +++ b/src/bridge/serial/PacketQueue.h @@ -0,0 +1,113 @@ +/** + * MeshCore - A new lightweight, hybrid routing mesh protocol for packet radios + * Copyright (c) 2025 Scott Powell / rippleradios.com + * + * This project is maintained by the contributors listed in + * https://github.com/ripplebiz/MeshCore/graphs/contributors + * + * MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ +#pragma once + +#include "MeshCore.h" + +#include +#include + +#if MESH_PACKET_LOGGING +#include +#endif + +#ifndef MAX_QUEUE_SIZE +#define MAX_QUEUE_SIZE 8 +#endif + +namespace bridge { + +class PacketQueue { +private: + struct { + size_t len; + uint8_t bytes[MAX_TRANS_UNIT]; + } buffer[MAX_QUEUE_SIZE]; + +protected: + uint16_t head = 0, tail = 0; + +public: + size_t available() const { return (tail - head + MAX_QUEUE_SIZE) % MAX_QUEUE_SIZE; } + + size_t enqueue(const uint8_t *bytes, const uint8_t len) { + if (len == 0 || len > MAX_TRANS_UNIT) { +#if BRIDGE_DEBUG + Serial.printf("BRIDGE: enqueue() failed len=%d\n", len); +#endif + return 0; + } + + if ((tail + 1) % MAX_QUEUE_SIZE == head) { // Buffer full + head = (head + 1) % MAX_QUEUE_SIZE; // Overwrite oldest packet + } + + buffer[tail].len = len; + memcpy(buffer[tail].bytes, bytes, len); + +#if MESH_PACKET_LOGGING + Serial.printf("BRIDGE: enqueue() len=%d payload[5]=", len); + for (size_t i = 0; i < len && i < 5; ++i) { + Serial.printf("0x%02x ", buffer[tail].bytes[i]); + } + Serial.printf("\n"); +#endif + + tail = (tail + 1) % MAX_QUEUE_SIZE; + return len; + } + + size_t enqueue(const mesh::Packet *pkt) { + uint8_t bytes[MAX_TRANS_UNIT]; + const size_t len = pkt->writeTo(bytes); + return enqueue(bytes, len); + } + + size_t dequeue(uint8_t *bytes) { + if (head == tail) { // Buffer empty + return 0; + } + + const size_t len = buffer[head].len; + memcpy(bytes, buffer[head].bytes, len); + head = (head + 1) % MAX_QUEUE_SIZE; + +#if MESH_PACKET_LOGGING + Serial.printf("BRIDGE: dequeue() payload[5]="); + for (size_t i = 0; i < len && i < 5; ++i) { + Serial.printf("0x%02x ", bytes[i]); + } + Serial.printf("\n"); +#endif + + return len; + } +}; + +} // namespace bridge diff --git a/src/bridge/serial/SerialBridge.cpp b/src/bridge/serial/SerialBridge.cpp new file mode 100644 index 00000000..1e83f9e6 --- /dev/null +++ b/src/bridge/serial/SerialBridge.cpp @@ -0,0 +1,135 @@ +/** + * MeshCore - A new lightweight, hybrid routing mesh protocol for packet radios + * Copyright (c) 2025 Scott Powell / rippleradios.com + * + * This project is maintained by the contributors listed in + * https://github.com/ripplebiz/MeshCore/graphs/contributors + * + * MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ +#include "SerialBridge.h" + +#include "MeshCore.h" +#include "Packet.h" + +// Alternative for ESP32 +// Alternative for RP2040 +#include + +namespace bridge { +#ifdef BRIDGE_OVER_SERIAL + +#if !defined(BRIDGE_OVER_SERIAL_RX) || !defined(BRIDGE_OVER_SERIAL_TX) +#error You must define RX and TX pins +#endif + +void SerialBridge::setup() { +#if defined(ESP32) + BRIDGE_OVER_SERIAL.setPins(BRIDGE_OVER_SERIAL_RX, BRIDGE_OVER_SERIAL_TX); +#elif defined(RP2040_PLATFORM) + BRIDGE_OVER_SERIAL.setPinout(BRIDGE_OVER_SERIAL_TX, BRIDGE_OVER_SERIAL_RX); +#else +#error SerialBridge was not tested on the current platform +#endif + BRIDGE_OVER_SERIAL.begin(115200); + Serial.printf("Bridge over serial: enabled\n"); +} + +void SerialBridge::loop() { + readFromSerial(); + writeToSerial(); +} + +bool SerialBridge::shouldRetransmit(const mesh::Packet *pkt) { + if (pkt->isMarkedDoNotRetransmit()) { + return false; + } +} + +size_t SerialBridge::getPacket(uint8_t *bytes) { + return rx_queue.dequeue(bytes); +} + +size_t SerialBridge::sendPacket(const mesh::Packet *pkt) { + if (shouldRetransmit(pkt)) return 0; + const size_t len = tx_queue.enqueue(pkt); + return len; +} + +void SerialBridge::readFromSerial() { + static constexpr uint16_t size = sizeof(bridge::Packet) + 1; + static uint8_t buffer[size]; + static uint16_t tail = 0; + + while (BRIDGE_OVER_SERIAL.available()) { + buffer[tail] = (uint8_t)BRIDGE_OVER_SERIAL.read(); + tail = (tail + 1) % size; + +#if BRIDGE_OVER_SERIAL_DEBUG + Serial.printf("%02x ", buffer[(tail - 1 + size) % size]); +#endif + + // Check for complete packet by looking back to where the magic number should be + uint16_t head = (tail - sizeof(bridge::Packet) + size) % size; + const uint16_t magic = buffer[head] | (buffer[(head + 1) % size] << 8); + + if (magic == SERIAL_PKT_MAGIC) { + const uint16_t len = buffer[(head + 2) % size] | (buffer[(head + 3) % size] << 8); + const uint16_t crc = buffer[(head + 4) % size] | (buffer[(head + 5) % size] << 8); + + uint8_t payload[MAX_TRANS_UNIT]; + for (size_t i = 0; i < len; i++) { + payload[i] = buffer[(head + 6 + i) % size]; + } + + const bool valid = verifyCRC(payload, len, crc); + +#if MESH_PACKET_LOGGING + Serial.printf("BRIDGE: Read from serial len=%d crc=0x%04x\n", len, crc); +#endif + + if (verifyCRC(payload, len, crc)) { +#if MESH_PACKET_LOGGING + Serial.printf("BRIDGE: Received packet was validated\n"); +#endif + rx_queue.enqueue(payload, len); + } + } + } +} + +void SerialBridge::writeToSerial() { + bridge::Packet pkt; + if (!tx_queue.available()) return; + pkt.len = tx_queue.dequeue(pkt.payload); + + if (pkt.len > 0) { + pkt.crc = SerialBridge::calculateCRC(pkt.payload, pkt.len); + BRIDGE_OVER_SERIAL.write((uint8_t *)&pkt, sizeof(bridge::Packet)); +#if MESH_PACKET_LOGGING + Serial.printf("BRIDGE: Write to serial len=%d crc=0x%04x\n", pkt.len, pkt.crc); +#endif + } +} + +#endif +} // namespace bridge diff --git a/src/bridge/serial/SerialBridge.h b/src/bridge/serial/SerialBridge.h new file mode 100644 index 00000000..80bb2360 --- /dev/null +++ b/src/bridge/serial/SerialBridge.h @@ -0,0 +1,73 @@ +/** + * MeshCore - A new lightweight, hybrid routing mesh protocol for packet radios + * Copyright (c) 2025 Scott Powell / rippleradios.com + * + * This project is maintained by the contributors listed in + * https://github.com/ripplebiz/MeshCore/graphs/contributors + * + * MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ +#pragma once + +#include "Packet.h" +#include "PacketQueue.h" + +#include + +namespace bridge { + +class SerialBridge { +private: + PacketQueue rx_queue, tx_queue; + +protected: + bool shouldRetransmit(const mesh::Packet *); + +public: + void loop(); + void setup(); + void readFromSerial(); + void writeToSerial(); + + size_t getPacket(uint8_t *); + size_t sendPacket(const mesh::Packet *); + + static uint16_t calculateCRC(const uint8_t *bytes, size_t len) { + // Fletcher-16 + // https://en.wikipedia.org/wiki/Fletcher%27s_checksum + 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; + }; + + static bool verifyCRC(const uint8_t *bytes, size_t len, uint16_t crc) { + uint16_t computedChecksum = calculateCRC(bytes, len); + return (computedChecksum == crc); + } +}; + +} // namespace bridge From 2f77cef04b65f1d76a01e3b8c74086732d43a8e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Br=C3=A1zio?= Date: Sun, 29 Jun 2025 16:28:11 +0100 Subject: [PATCH 2/6] Add config flags to variants --- variants/heltec_v3/platformio.ini | 3 +++ variants/lilygo_tlora_v2_1/platformio.ini | 3 +++ variants/waveshare_rp2040_lora/platformio.ini | 3 +++ 3 files changed, 9 insertions(+) diff --git a/variants/heltec_v3/platformio.ini b/variants/heltec_v3/platformio.ini index 8f9b1a27..173be80c 100644 --- a/variants/heltec_v3/platformio.ini +++ b/variants/heltec_v3/platformio.ini @@ -47,6 +47,9 @@ build_flags = -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' -D MAX_NEIGHBOURS=8 +; -D BRIDGE_OVER_SERIAL=Serial2 +; -D BRIDGE_OVER_SERIAL_RX=5 +; -D BRIDGE_OVER_SERIAL_TX=6 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Heltec_lora32_v3.build_src_filter} diff --git a/variants/lilygo_tlora_v2_1/platformio.ini b/variants/lilygo_tlora_v2_1/platformio.ini index d9cecfc2..bd351c5a 100644 --- a/variants/lilygo_tlora_v2_1/platformio.ini +++ b/variants/lilygo_tlora_v2_1/platformio.ini @@ -44,6 +44,9 @@ build_flags = -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' -D MAX_NEIGHBOURS=8 +; -D BRIDGE_OVER_SERIAL=Serial2 +; -D BRIDGE_OVER_SERIAL_RX=34 +; -D BRIDGE_OVER_SERIAL_TX=25 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 ; -D CORE_DEBUG_LEVEL=3 diff --git a/variants/waveshare_rp2040_lora/platformio.ini b/variants/waveshare_rp2040_lora/platformio.ini index 2730734d..b1e4714a 100644 --- a/variants/waveshare_rp2040_lora/platformio.ini +++ b/variants/waveshare_rp2040_lora/platformio.ini @@ -35,6 +35,9 @@ build_flags = ${waveshare_rp2040_lora.build_flags} -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' -D MAX_NEIGHBOURS=8 +; -D BRIDGE_OVER_SERIAL=Serial2 +; -D BRIDGE_OVER_SERIAL_RX=9 +; -D BRIDGE_OVER_SERIAL_TX=8 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${waveshare_rp2040_lora.build_src_filter} From ac056fb0b98ecd9ce0da6cda8693f1cdffb97cb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Br=C3=A1zio?= Date: Tue, 8 Jul 2025 14:04:21 +0100 Subject: [PATCH 3/6] Remove serial bridge implementation and implement simplified version directly in the repeater source code. --- examples/simple_repeater/main.cpp | 121 +++++++++++++++++++++----- src/Dispatcher.cpp | 15 ---- src/Dispatcher.h | 5 -- src/bridge/serial/Packet.h | 58 ------------- src/bridge/serial/PacketQueue.h | 113 ------------------------ src/bridge/serial/SerialBridge.cpp | 135 ----------------------------- src/bridge/serial/SerialBridge.h | 73 ---------------- 7 files changed, 100 insertions(+), 420 deletions(-) delete mode 100644 src/bridge/serial/Packet.h delete mode 100644 src/bridge/serial/PacketQueue.h delete mode 100644 src/bridge/serial/SerialBridge.cpp delete mode 100644 src/bridge/serial/SerialBridge.h diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index 131dc496..96969f96 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -72,17 +72,35 @@ static UITask ui_task(display); #endif -#ifdef BRIDGE_OVER_SERIAL -#include "bridge/serial/SerialBridge.h" -bridge::SerialBridge *bridge_interface; -#endif - #define FIRMWARE_ROLE "repeater" #define PACKET_LOG_FILE "/packet_log" /* ------------------------------ Code -------------------------------- */ +#ifdef BRIDGE_OVER_SERIAL +#define SERIAL_PKT_MAGIC 0xbeef + +struct SerialPacket { + uint16_t magic, len, crc; + uint8_t payload[MAX_TRANS_UNIT]; + SerialPacket() : magic(SERIAL_PKT_MAGIC), len(0), crc(0) {} +}; + +// Fletcher-16 +// https://en.wikipedia.org/wiki/Fletcher%27s_checksum +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; +}; +#endif + #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS #define REQ_TYPE_KEEP_ALIVE 0x02 #define REQ_TYPE_GET_TELEMETRY_DATA 0x03 @@ -297,6 +315,20 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { } } void logTx(mesh::Packet* pkt, int len) override { +#ifdef BRIDGE_OVER_SERIAL + SerialPacket spkt; + spkt.len = pkt->writeTo(spkt.payload); + + if (spkt.len > 0) { + spkt.crc = fletcher16(spkt.payload, spkt.len); + BRIDGE_OVER_SERIAL.write((uint8_t *)&spkt, sizeof(SerialPacket)); + +#if MESH_PACKET_LOGGING + Serial.printf("BRIDGE: Write to serial len=%d crc=0x%04x\n", spkt.len, spkt.crc); +#endif + } +#endif + if (_logging) { File f = openAppend(PACKET_LOG_FILE); if (f) { @@ -358,9 +390,9 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { } else if (strcmp((char *) &data[4], _prefs.guest_password) == 0) { // check guest password is_admin = false; } else { - #if MESH_DEBUG +#if MESH_DEBUG MESH_DEBUG_PRINTLN("Invalid password: %s", &data[4]); - #endif +#endif return; } @@ -377,15 +409,15 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { uint32_t now = getRTCClock()->getCurrentTimeUnique(); memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp - #if 0 +#if 0 memcpy(&reply_data[4], "OK", 2); // legacy response - #else +#else reply_data[4] = RESP_SERVER_LOGIN_OK; reply_data[5] = 0; // NEW: recommended keep-alive interval (secs / 16) reply_data[6] = is_admin ? 1 : 0; reply_data[7] = 0; // FUTURE: reserved getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness - #endif +#endif if (packet->isRouteFlood()) { // let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response @@ -562,9 +594,9 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { next_local_advert = next_flood_advert = 0; _logging = false; - #if MAX_NEIGHBOURS +#if MAX_NEIGHBOURS memset(neighbours, 0, sizeof(neighbours)); - #endif +#endif // defaults memset(&_prefs, 0, sizeof(_prefs)); @@ -712,6 +744,44 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { } void loop() { +#ifdef BRIDGE_OVER_SERIAL + static constexpr uint16_t size = sizeof(SerialPacket) + 1; + static uint8_t buffer[size]; + static uint16_t tail = 0; + + while (BRIDGE_OVER_SERIAL.available()) { + buffer[tail] = (uint8_t)BRIDGE_OVER_SERIAL.read(); + MESH_DEBUG_PRINT("%02x ", buffer[tail]); + tail = (tail + 1) % size; + + // Check for complete packet by looking back to where the magic number should be + uint16_t head = (tail - sizeof(SerialPacket) + size) % size; + const uint16_t magic = buffer[head] | (buffer[(head + 1) % size] << 8); + + if (magic == SERIAL_PKT_MAGIC) { + uint8_t bytes[MAX_TRANS_UNIT]; + const uint16_t len = buffer[(head + 2) % size] | (buffer[(head + 3) % size] << 8); + const uint16_t crc = buffer[(head + 4) % size] | (buffer[(head + 5) % size] << 8); + + for (size_t i = 0; i < len; i++) { + bytes[i] = buffer[(head + 6 + i) % size]; + } + + uint16_t f16 = fletcher16(bytes, len); + +#if MESH_PACKET_LOGGING + Serial.printf("BRIDGE: Read from serial len=%d crc=0x%04x valid=%s\n", len, crc, (f16 == crc) ? "true" : "false"); +#endif + + if (f16 == crc) { + mesh::Packet *pkt = _mgr->allocNew(); + pkt->readFrom(bytes, len); + _mgr->queueInbound(pkt, millis()); + } + } + } +#endif + mesh::Mesh::loop(); if (next_flood_advert && millisHasNowPassed(next_flood_advert)) { @@ -745,6 +815,24 @@ static char command[80]; void setup() { Serial.begin(115200); + +#ifdef BRIDGE_OVER_SERIAL +#if defined(ESP32) + BRIDGE_OVER_SERIAL.setPins(BRIDGE_OVER_SERIAL_RX, BRIDGE_OVER_SERIAL_TX); +#elif defined(RP2040_PLATFORM) + BRIDGE_OVER_SERIAL.setRX(BRIDGE_OVER_SERIAL_RX); + BRIDGE_OVER_SERIAL.setTX(BRIDGE_OVER_SERIAL_TX); +#elif defined(STM32_PLATFORM) + BRIDGE_OVER_SERIAL.setRx(BRIDGE_OVER_SERIAL_RX); + BRIDGE_OVER_SERIAL.setTx(BRIDGE_OVER_SERIAL_TX); +#else +#error SerialBridge was not tested on the current platform +#endif + + BRIDGE_OVER_SERIAL.begin(115200); + MESH_DEBUG_PRINTLN("Bridge over serial: enabled"); +#endif + delay(1000); board.begin(); @@ -757,11 +845,6 @@ void setup() { } #endif -#ifdef BRIDGE_OVER_SERIAL - bridge_interface = new bridge::SerialBridge(); - bridge_interface->setup(); -#endif - if (!radio_init()) { halt(); } @@ -837,10 +920,6 @@ void loop() { command[0] = 0; // reset command buffer } -#ifdef BRIDGE_OVER_SERIAL - bridge_interface->loop(); -#endif - the_mesh.loop(); sensors.loop(); } diff --git a/src/Dispatcher.cpp b/src/Dispatcher.cpp index 08cca61e..1a6e833b 100644 --- a/src/Dispatcher.cpp +++ b/src/Dispatcher.cpp @@ -117,17 +117,6 @@ void Dispatcher::checkRecv() { uint8_t raw[MAX_TRANS_UNIT+1]; int len = _radio->recvRaw(raw, MAX_TRANS_UNIT); -#ifdef BRIDGE_OVER_SERIAL - // We are basically stamping metadata from the last RF packet into something that came from serial, - // it works for now. But long term the code on checkRecv() should be refactored to be able to deal - // with both use cases without dupeing the existing code. I've chosen [for now] not to dupe and just - // fake the metadata. - - if (len == 0) { - len = bridge_interface->getPacket(raw); - } -#endif - if (len > 0) { logRxRaw(_radio->getLastSNR(), _radio->getLastRSSI(), raw, len); @@ -293,10 +282,6 @@ void Dispatcher::checkSend() { } outbound_expiry = futureMillis(max_airtime); -#ifdef BRIDGE_OVER_SERIAL - bridge_interface->sendPacket(outbound); -#endif - #if MESH_PACKET_LOGGING Serial.print(getLogDateTime()); Serial.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", diff --git a/src/Dispatcher.h b/src/Dispatcher.h index 98184b50..2200f81b 100644 --- a/src/Dispatcher.h +++ b/src/Dispatcher.h @@ -6,11 +6,6 @@ #include #include -#ifdef BRIDGE_OVER_SERIAL -#include "bridge/serial/SerialBridge.h" -extern bridge::SerialBridge *bridge_interface; -#endif - namespace mesh { /** diff --git a/src/bridge/serial/Packet.h b/src/bridge/serial/Packet.h deleted file mode 100644 index fbb4155a..00000000 --- a/src/bridge/serial/Packet.h +++ /dev/null @@ -1,58 +0,0 @@ -/** - * MeshCore - A new lightweight, hybrid routing mesh protocol for packet radios - * Copyright (c) 2025 Scott Powell / rippleradios.com - * - * This project is maintained by the contributors listed in - * https://github.com/ripplebiz/MeshCore/graphs/contributors - * - * MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - * - */ -#pragma once - -#include "MeshCore.h" - -#include - -namespace bridge { - -/* - * +----------------------------------------------------+ - * | SERIAL PACKET SPEC | - * +-----------+---------+------------------------------+ - * | TYPE | NAME | DESCRIPTION | - * +-----------+---------+------------------------------+ - * | uint16_t | MAGIC | The packet start marker | - * | uint16_t | LEN | Length of the payload | - * | uint16_t | CRC | Checksum for error checking | - * | uint8_t[] | PAYLOAD | Actual rf packet data | - * +-----------+---------+------------------------------+ - */ -#define SERIAL_PKT_MAGIC 0xdead - -struct Packet { - uint16_t magic, len, crc; - uint8_t payload[MAX_TRANS_UNIT]; - - Packet() : magic(SERIAL_PKT_MAGIC), len(0), crc(0) {} -}; - -} // namespace bridge \ No newline at end of file diff --git a/src/bridge/serial/PacketQueue.h b/src/bridge/serial/PacketQueue.h deleted file mode 100644 index a83d8f2e..00000000 --- a/src/bridge/serial/PacketQueue.h +++ /dev/null @@ -1,113 +0,0 @@ -/** - * MeshCore - A new lightweight, hybrid routing mesh protocol for packet radios - * Copyright (c) 2025 Scott Powell / rippleradios.com - * - * This project is maintained by the contributors listed in - * https://github.com/ripplebiz/MeshCore/graphs/contributors - * - * MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - * - */ -#pragma once - -#include "MeshCore.h" - -#include -#include - -#if MESH_PACKET_LOGGING -#include -#endif - -#ifndef MAX_QUEUE_SIZE -#define MAX_QUEUE_SIZE 8 -#endif - -namespace bridge { - -class PacketQueue { -private: - struct { - size_t len; - uint8_t bytes[MAX_TRANS_UNIT]; - } buffer[MAX_QUEUE_SIZE]; - -protected: - uint16_t head = 0, tail = 0; - -public: - size_t available() const { return (tail - head + MAX_QUEUE_SIZE) % MAX_QUEUE_SIZE; } - - size_t enqueue(const uint8_t *bytes, const uint8_t len) { - if (len == 0 || len > MAX_TRANS_UNIT) { -#if BRIDGE_DEBUG - Serial.printf("BRIDGE: enqueue() failed len=%d\n", len); -#endif - return 0; - } - - if ((tail + 1) % MAX_QUEUE_SIZE == head) { // Buffer full - head = (head + 1) % MAX_QUEUE_SIZE; // Overwrite oldest packet - } - - buffer[tail].len = len; - memcpy(buffer[tail].bytes, bytes, len); - -#if MESH_PACKET_LOGGING - Serial.printf("BRIDGE: enqueue() len=%d payload[5]=", len); - for (size_t i = 0; i < len && i < 5; ++i) { - Serial.printf("0x%02x ", buffer[tail].bytes[i]); - } - Serial.printf("\n"); -#endif - - tail = (tail + 1) % MAX_QUEUE_SIZE; - return len; - } - - size_t enqueue(const mesh::Packet *pkt) { - uint8_t bytes[MAX_TRANS_UNIT]; - const size_t len = pkt->writeTo(bytes); - return enqueue(bytes, len); - } - - size_t dequeue(uint8_t *bytes) { - if (head == tail) { // Buffer empty - return 0; - } - - const size_t len = buffer[head].len; - memcpy(bytes, buffer[head].bytes, len); - head = (head + 1) % MAX_QUEUE_SIZE; - -#if MESH_PACKET_LOGGING - Serial.printf("BRIDGE: dequeue() payload[5]="); - for (size_t i = 0; i < len && i < 5; ++i) { - Serial.printf("0x%02x ", bytes[i]); - } - Serial.printf("\n"); -#endif - - return len; - } -}; - -} // namespace bridge diff --git a/src/bridge/serial/SerialBridge.cpp b/src/bridge/serial/SerialBridge.cpp deleted file mode 100644 index 1e83f9e6..00000000 --- a/src/bridge/serial/SerialBridge.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/** - * MeshCore - A new lightweight, hybrid routing mesh protocol for packet radios - * Copyright (c) 2025 Scott Powell / rippleradios.com - * - * This project is maintained by the contributors listed in - * https://github.com/ripplebiz/MeshCore/graphs/contributors - * - * MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - * - */ -#include "SerialBridge.h" - -#include "MeshCore.h" -#include "Packet.h" - -// Alternative for ESP32 -// Alternative for RP2040 -#include - -namespace bridge { -#ifdef BRIDGE_OVER_SERIAL - -#if !defined(BRIDGE_OVER_SERIAL_RX) || !defined(BRIDGE_OVER_SERIAL_TX) -#error You must define RX and TX pins -#endif - -void SerialBridge::setup() { -#if defined(ESP32) - BRIDGE_OVER_SERIAL.setPins(BRIDGE_OVER_SERIAL_RX, BRIDGE_OVER_SERIAL_TX); -#elif defined(RP2040_PLATFORM) - BRIDGE_OVER_SERIAL.setPinout(BRIDGE_OVER_SERIAL_TX, BRIDGE_OVER_SERIAL_RX); -#else -#error SerialBridge was not tested on the current platform -#endif - BRIDGE_OVER_SERIAL.begin(115200); - Serial.printf("Bridge over serial: enabled\n"); -} - -void SerialBridge::loop() { - readFromSerial(); - writeToSerial(); -} - -bool SerialBridge::shouldRetransmit(const mesh::Packet *pkt) { - if (pkt->isMarkedDoNotRetransmit()) { - return false; - } -} - -size_t SerialBridge::getPacket(uint8_t *bytes) { - return rx_queue.dequeue(bytes); -} - -size_t SerialBridge::sendPacket(const mesh::Packet *pkt) { - if (shouldRetransmit(pkt)) return 0; - const size_t len = tx_queue.enqueue(pkt); - return len; -} - -void SerialBridge::readFromSerial() { - static constexpr uint16_t size = sizeof(bridge::Packet) + 1; - static uint8_t buffer[size]; - static uint16_t tail = 0; - - while (BRIDGE_OVER_SERIAL.available()) { - buffer[tail] = (uint8_t)BRIDGE_OVER_SERIAL.read(); - tail = (tail + 1) % size; - -#if BRIDGE_OVER_SERIAL_DEBUG - Serial.printf("%02x ", buffer[(tail - 1 + size) % size]); -#endif - - // Check for complete packet by looking back to where the magic number should be - uint16_t head = (tail - sizeof(bridge::Packet) + size) % size; - const uint16_t magic = buffer[head] | (buffer[(head + 1) % size] << 8); - - if (magic == SERIAL_PKT_MAGIC) { - const uint16_t len = buffer[(head + 2) % size] | (buffer[(head + 3) % size] << 8); - const uint16_t crc = buffer[(head + 4) % size] | (buffer[(head + 5) % size] << 8); - - uint8_t payload[MAX_TRANS_UNIT]; - for (size_t i = 0; i < len; i++) { - payload[i] = buffer[(head + 6 + i) % size]; - } - - const bool valid = verifyCRC(payload, len, crc); - -#if MESH_PACKET_LOGGING - Serial.printf("BRIDGE: Read from serial len=%d crc=0x%04x\n", len, crc); -#endif - - if (verifyCRC(payload, len, crc)) { -#if MESH_PACKET_LOGGING - Serial.printf("BRIDGE: Received packet was validated\n"); -#endif - rx_queue.enqueue(payload, len); - } - } - } -} - -void SerialBridge::writeToSerial() { - bridge::Packet pkt; - if (!tx_queue.available()) return; - pkt.len = tx_queue.dequeue(pkt.payload); - - if (pkt.len > 0) { - pkt.crc = SerialBridge::calculateCRC(pkt.payload, pkt.len); - BRIDGE_OVER_SERIAL.write((uint8_t *)&pkt, sizeof(bridge::Packet)); -#if MESH_PACKET_LOGGING - Serial.printf("BRIDGE: Write to serial len=%d crc=0x%04x\n", pkt.len, pkt.crc); -#endif - } -} - -#endif -} // namespace bridge diff --git a/src/bridge/serial/SerialBridge.h b/src/bridge/serial/SerialBridge.h deleted file mode 100644 index 80bb2360..00000000 --- a/src/bridge/serial/SerialBridge.h +++ /dev/null @@ -1,73 +0,0 @@ -/** - * MeshCore - A new lightweight, hybrid routing mesh protocol for packet radios - * Copyright (c) 2025 Scott Powell / rippleradios.com - * - * This project is maintained by the contributors listed in - * https://github.com/ripplebiz/MeshCore/graphs/contributors - * - * MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - * - */ -#pragma once - -#include "Packet.h" -#include "PacketQueue.h" - -#include - -namespace bridge { - -class SerialBridge { -private: - PacketQueue rx_queue, tx_queue; - -protected: - bool shouldRetransmit(const mesh::Packet *); - -public: - void loop(); - void setup(); - void readFromSerial(); - void writeToSerial(); - - size_t getPacket(uint8_t *); - size_t sendPacket(const mesh::Packet *); - - static uint16_t calculateCRC(const uint8_t *bytes, size_t len) { - // Fletcher-16 - // https://en.wikipedia.org/wiki/Fletcher%27s_checksum - 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; - }; - - static bool verifyCRC(const uint8_t *bytes, size_t len, uint16_t crc) { - uint16_t computedChecksum = calculateCRC(bytes, len); - return (computedChecksum == crc); - } -}; - -} // namespace bridge From 92ee1820c42041dce922b8e5917eb46533f9e217 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Br=C3=A1zio?= Date: Tue, 8 Jul 2025 16:02:10 +0100 Subject: [PATCH 4/6] Add null check for packet allocation and clean up Dispatcher --- examples/simple_repeater/main.cpp | 13 ++++++++++--- src/Dispatcher.cpp | 9 ++++----- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index 96969f96..428e932f 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -774,9 +774,16 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { #endif if (f16 == crc) { - mesh::Packet *pkt = _mgr->allocNew(); - pkt->readFrom(bytes, len); - _mgr->queueInbound(pkt, millis()); + Packet *pkt = _mgr->allocNew(); + + if (pkt != NULL) { + pkt->readFrom(bytes, len); + _mgr->queueInbound(pkt, millis()); + } else { +#if MESH_PACKET_LOGGING + Serial.printf("BRIDGE: Unable to allocate new Packet *pkt"); +#endif + } } } } diff --git a/src/Dispatcher.cpp b/src/Dispatcher.cpp index 1a6e833b..7f39dc49 100644 --- a/src/Dispatcher.cpp +++ b/src/Dispatcher.cpp @@ -1,7 +1,7 @@ #include "Dispatcher.h" #if MESH_PACKET_LOGGING -#include + #include #endif #include @@ -104,7 +104,6 @@ void Dispatcher::loop() { processRecvPacket(pkt); } } - checkRecv(); checkSend(); } @@ -116,7 +115,6 @@ void Dispatcher::checkRecv() { { uint8_t raw[MAX_TRANS_UNIT+1]; int len = _radio->recvRaw(raw, MAX_TRANS_UNIT); - if (len > 0) { logRxRaw(_radio->getLastSNR(), _radio->getLastRSSI(), raw, len); @@ -282,7 +280,7 @@ void Dispatcher::checkSend() { } outbound_expiry = futureMillis(max_airtime); -#if MESH_PACKET_LOGGING + #if MESH_PACKET_LOGGING Serial.print(getLogDateTime()); Serial.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, outbound->getPayloadType(), outbound->isRouteDirect() ? "D" : "F", outbound->payload_len); @@ -292,7 +290,7 @@ void Dispatcher::checkSend() { } else { Serial.printf("\n"); } -#endif + #endif } } } @@ -330,4 +328,5 @@ bool Dispatcher::millisHasNowPassed(unsigned long timestamp) const { unsigned long Dispatcher::futureMillis(int millis_from_now) const { return _ms->getMillis() + millis_from_now; } + } \ No newline at end of file From 97b51900f8667515f4f1a6f9064f5d280a0b480f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Br=C3=A1zio?= Date: Tue, 8 Jul 2025 21:45:49 +0100 Subject: [PATCH 5/6] More robust handling of pkt len --- examples/simple_repeater/main.cpp | 45 ++++++++++++++++++------------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index 428e932f..fe065a33 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -79,7 +79,7 @@ /* ------------------------------ Code -------------------------------- */ #ifdef BRIDGE_OVER_SERIAL -#define SERIAL_PKT_MAGIC 0xbeef +#define SERIAL_PKT_MAGIC 0xcafe struct SerialPacket { uint16_t magic, len, crc; @@ -316,15 +316,17 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { } void logTx(mesh::Packet* pkt, int len) override { #ifdef BRIDGE_OVER_SERIAL - SerialPacket spkt; - spkt.len = pkt->writeTo(spkt.payload); + SerialPacket serialpkt; + size_t seriallen = pkt->writeTo(serialpkt.payload); - if (spkt.len > 0) { - spkt.crc = fletcher16(spkt.payload, spkt.len); - BRIDGE_OVER_SERIAL.write((uint8_t *)&spkt, sizeof(SerialPacket)); + if (seriallen - 1 < MAX_TRANS_UNIT - 1) { + serialpkt.len = seriallen; + serialpkt.crc = fletcher16(serialpkt.payload, serialpkt.len); + BRIDGE_OVER_SERIAL.write((uint8_t *)&serialpkt, sizeof(SerialPacket)); #if MESH_PACKET_LOGGING - Serial.printf("BRIDGE: Write to serial len=%d crc=0x%04x\n", spkt.len, spkt.crc); + Serial.print(getLogDateTime()); + Serial.printf(": BRIDGE: Write to serial len=%d crc=0x%04x\n", serialpkt.len, serialpkt.crc); #endif } #endif @@ -763,26 +765,31 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { const uint16_t len = buffer[(head + 2) % size] | (buffer[(head + 3) % size] << 8); const uint16_t crc = buffer[(head + 4) % size] | (buffer[(head + 5) % size] << 8); - for (size_t i = 0; i < len; i++) { - bytes[i] = buffer[(head + 6 + i) % size]; - } + if (len - 1 < MAX_TRANS_UNIT - 1) { + for (size_t i = 0; i < len; i++) { + bytes[i] = buffer[(head + 6 + i) % size]; + } - uint16_t f16 = fletcher16(bytes, len); + uint16_t f16 = fletcher16(bytes, len); #if MESH_PACKET_LOGGING - Serial.printf("BRIDGE: Read from serial len=%d crc=0x%04x valid=%s\n", len, crc, (f16 == crc) ? "true" : "false"); + Serial.print(getLogDateTime()); + Serial.printf(": BRIDGE: Read from serial len=%d crc=0x%04x valid=%s\n", len, crc, + (f16 == crc) ? "true" : "false"); #endif - if (f16 == crc) { - Packet *pkt = _mgr->allocNew(); + if (f16 == crc) { + mesh::Packet *pkt = _mgr->allocNew(); - if (pkt != NULL) { - pkt->readFrom(bytes, len); - _mgr->queueInbound(pkt, millis()); - } else { + if (pkt == NULL) { #if MESH_PACKET_LOGGING - Serial.printf("BRIDGE: Unable to allocate new Packet *pkt"); + Serial.print(getLogDateTime()); + Serial.printf(": BRIDGE: Unable to allocate new Packet *pkt\n"); #endif + } else { + pkt->readFrom(bytes, len); + _mgr->queueInbound(pkt, millis()); + } } } } From 04042e3ca0c1f0c52ddd110d589bdb446d5de4eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Br=C3=A1zio?= Date: Wed, 9 Jul 2025 11:03:35 +0100 Subject: [PATCH 6/6] Refactor serial bridge handling --- examples/simple_repeater/main.cpp | 170 +++++++++--------- platformio.ini | 1 - variants/heltec_v3/platformio.ini | 25 ++- variants/lilygo_tlora_v2_1/platformio.ini | 25 ++- variants/waveshare_rp2040_lora/platformio.ini | 19 +- 5 files changed, 147 insertions(+), 93 deletions(-) diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index fe065a33..e9683fd3 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -80,25 +80,6 @@ #ifdef BRIDGE_OVER_SERIAL #define SERIAL_PKT_MAGIC 0xcafe - -struct SerialPacket { - uint16_t magic, len, crc; - uint8_t payload[MAX_TRANS_UNIT]; - SerialPacket() : magic(SERIAL_PKT_MAGIC), len(0), crc(0) {} -}; - -// Fletcher-16 -// https://en.wikipedia.org/wiki/Fletcher%27s_checksum -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; -}; #endif #define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS @@ -267,6 +248,89 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { #endif } +#ifdef BRIDGE_OVER_SERIAL + struct SerialPacket { + uint16_t magic, len, crc; + uint8_t payload[MAX_TRANS_UNIT]; + SerialPacket() : magic(SERIAL_PKT_MAGIC), len(0), crc(0) {} + }; + + // Fletcher-16 + // https://en.wikipedia.org/wiki/Fletcher%27s_checksum + 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; + }; + + inline void serialBridgeSendPkt(const mesh::Packet *pkt) { + SerialPacket spkt; + spkt.len = pkt->writeTo(spkt.payload); + spkt.crc = fletcher16(spkt.payload, spkt.len); + BRIDGE_OVER_SERIAL.write((uint8_t *)&spkt, sizeof(SerialPacket)); + +#if MESH_PACKET_LOGGING + Serial.printf("%s: BRIDGE: TX, len=%d crc=0x%04x\n", getLogDateTime(), spkt.len, spkt.crc); +#endif + } + + inline void serialBridgeReceivePkt() { + static constexpr uint16_t size = sizeof(SerialPacket) + 1; + static uint8_t buffer[size]; + static uint16_t tail = 0; + + while (BRIDGE_OVER_SERIAL.available()) { + buffer[tail] = (uint8_t)BRIDGE_OVER_SERIAL.read(); + MESH_DEBUG_PRINT("%02x ", buffer[tail]); + tail = (tail + 1) % size; + + // Check for complete packet by looking back to where the magic number should be + const uint16_t head = (tail - sizeof(SerialPacket) + size) % size; + if ((buffer[head] | (buffer[(head + 1) % size] << 8)) != SERIAL_PKT_MAGIC) { + return; + } + + uint8_t bytes[MAX_TRANS_UNIT]; + const uint16_t len = buffer[(head + 2) % size] | (buffer[(head + 3) % size] << 8); + + if (len == 0 || len > sizeof(bytes)) { + MESH_DEBUG_PRINTLN("%s: BRIDGE: RX, invalid packet len", getLogDateTime()); + return; + } + + for (size_t i = 0; i < len; i++) { + bytes[i] = buffer[(head + 6 + i) % size]; + } + + const uint16_t crc = buffer[(head + 4) % size] | (buffer[(head + 5) % size] << 8); + const uint16_t f16 = fletcher16(bytes, len); + +#if MESH_PACKET_LOGGING + Serial.printf("%s: BRIDGE: RX, len=%d crc=0x%04x\n", getLogDateTime(), len, crc); +#endif + + if ((f16 != crc)) { + MESH_DEBUG_PRINTLN("%s: BRIDGE: RX, invalid packet checksum", getLogDateTime()); + return; + } + + mesh::Packet *pkt = _mgr->allocNew(); + if (pkt == NULL) { + MESH_DEBUG_PRINTLN("%s: BRIDGE: RX, no unused packets available", getLogDateTime()); + return; + } + + pkt->readFrom(bytes, len); + _mgr->queueInbound(pkt, futureMillis(0)); + } + } +#endif + protected: float getAirtimeBudgetFactor() const override { return _prefs.airtime_factor; @@ -316,21 +380,10 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { } void logTx(mesh::Packet* pkt, int len) override { #ifdef BRIDGE_OVER_SERIAL - SerialPacket serialpkt; - size_t seriallen = pkt->writeTo(serialpkt.payload); - - if (seriallen - 1 < MAX_TRANS_UNIT - 1) { - serialpkt.len = seriallen; - serialpkt.crc = fletcher16(serialpkt.payload, serialpkt.len); - BRIDGE_OVER_SERIAL.write((uint8_t *)&serialpkt, sizeof(SerialPacket)); - -#if MESH_PACKET_LOGGING - Serial.print(getLogDateTime()); - Serial.printf(": BRIDGE: Write to serial len=%d crc=0x%04x\n", serialpkt.len, serialpkt.crc); -#endif + if (!pkt->isMarkedDoNotRetransmit()) { + serialBridgeSendPkt(pkt); } #endif - if (_logging) { File f = openAppend(PACKET_LOG_FILE); if (f) { @@ -747,53 +800,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { void loop() { #ifdef BRIDGE_OVER_SERIAL - static constexpr uint16_t size = sizeof(SerialPacket) + 1; - static uint8_t buffer[size]; - static uint16_t tail = 0; - - while (BRIDGE_OVER_SERIAL.available()) { - buffer[tail] = (uint8_t)BRIDGE_OVER_SERIAL.read(); - MESH_DEBUG_PRINT("%02x ", buffer[tail]); - tail = (tail + 1) % size; - - // Check for complete packet by looking back to where the magic number should be - uint16_t head = (tail - sizeof(SerialPacket) + size) % size; - const uint16_t magic = buffer[head] | (buffer[(head + 1) % size] << 8); - - if (magic == SERIAL_PKT_MAGIC) { - uint8_t bytes[MAX_TRANS_UNIT]; - const uint16_t len = buffer[(head + 2) % size] | (buffer[(head + 3) % size] << 8); - const uint16_t crc = buffer[(head + 4) % size] | (buffer[(head + 5) % size] << 8); - - if (len - 1 < MAX_TRANS_UNIT - 1) { - for (size_t i = 0; i < len; i++) { - bytes[i] = buffer[(head + 6 + i) % size]; - } - - uint16_t f16 = fletcher16(bytes, len); - -#if MESH_PACKET_LOGGING - Serial.print(getLogDateTime()); - Serial.printf(": BRIDGE: Read from serial len=%d crc=0x%04x valid=%s\n", len, crc, - (f16 == crc) ? "true" : "false"); -#endif - - if (f16 == crc) { - mesh::Packet *pkt = _mgr->allocNew(); - - if (pkt == NULL) { -#if MESH_PACKET_LOGGING - Serial.print(getLogDateTime()); - Serial.printf(": BRIDGE: Unable to allocate new Packet *pkt\n"); -#endif - } else { - pkt->readFrom(bytes, len); - _mgr->queueInbound(pkt, millis()); - } - } - } - } - } + serialBridgeReceivePkt(); #endif mesh::Mesh::loop(); @@ -829,6 +836,7 @@ static char command[80]; void setup() { Serial.begin(115200); + delay(1000); #ifdef BRIDGE_OVER_SERIAL #if defined(ESP32) @@ -842,13 +850,9 @@ void setup() { #else #error SerialBridge was not tested on the current platform #endif - BRIDGE_OVER_SERIAL.begin(115200); - MESH_DEBUG_PRINTLN("Bridge over serial: enabled"); #endif - delay(1000); - board.begin(); #ifdef DISPLAY_CLASS diff --git a/platformio.ini b/platformio.ini index 36cdf760..90e7cfb0 100644 --- a/platformio.ini +++ b/platformio.ini @@ -32,7 +32,6 @@ build_flags = -w -DNDEBUG -DRADIOLIB_STATIC_ONLY=1 -DRADIOLIB_GODMODE=1 build_src_filter = +<*.cpp> + - + ; ----------------- ESP32 --------------------- diff --git a/variants/heltec_v3/platformio.ini b/variants/heltec_v3/platformio.ini index 704958d1..16e65bf2 100644 --- a/variants/heltec_v3/platformio.ini +++ b/variants/heltec_v3/platformio.ini @@ -49,9 +49,6 @@ build_flags = -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' -D MAX_NEIGHBOURS=8 -; -D BRIDGE_OVER_SERIAL=Serial2 -; -D BRIDGE_OVER_SERIAL_RX=5 -; -D BRIDGE_OVER_SERIAL_TX=6 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${Heltec_lora32_v3.build_src_filter} @@ -61,6 +58,28 @@ lib_deps = ${Heltec_lora32_v3.lib_deps} ${esp32_ota.lib_deps} +[env:Heltec_v3_Bridge] +extends = Heltec_lora32_v3 +build_flags = + ${Heltec_lora32_v3.build_flags} + -D DISPLAY_CLASS=SSD1306Display + -D ADVERT_NAME='"Heltec Bridge"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=8 + -D BRIDGE_OVER_SERIAL=Serial2 + -D BRIDGE_OVER_SERIAL_RX=5 + -D BRIDGE_OVER_SERIAL_TX=6 + -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${Heltec_lora32_v3.build_src_filter} + + + +<../examples/simple_repeater> +lib_deps = + ${Heltec_lora32_v3.lib_deps} + ${esp32_ota.lib_deps} + [env:Heltec_v3_room_server] extends = Heltec_lora32_v3 build_flags = diff --git a/variants/lilygo_tlora_v2_1/platformio.ini b/variants/lilygo_tlora_v2_1/platformio.ini index a2169f1f..adf4a7e4 100644 --- a/variants/lilygo_tlora_v2_1/platformio.ini +++ b/variants/lilygo_tlora_v2_1/platformio.ini @@ -57,9 +57,6 @@ build_flags = -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' -D MAX_NEIGHBOURS=8 -; -D BRIDGE_OVER_SERIAL=Serial2 -; -D BRIDGE_OVER_SERIAL_RX=34 -; -D BRIDGE_OVER_SERIAL_TX=25 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 ; -D CORE_DEBUG_LEVEL=3 @@ -67,6 +64,28 @@ lib_deps = ${LilyGo_TLora_V2_1_1_6.lib_deps} ${esp32_ota.lib_deps} +[env:LilyGo_TLora_V2_1_1_6_Bridge] +extends = LilyGo_TLora_V2_1_1_6 +build_src_filter = ${LilyGo_TLora_V2_1_1_6.build_src_filter} + + + +<../examples/simple_repeater> +build_flags = + ${LilyGo_TLora_V2_1_1_6.build_flags} + -D ADVERT_NAME='"TLora-V2.1-1.6 Bridge"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=8 + -D BRIDGE_OVER_SERIAL=Serial2 + -D BRIDGE_OVER_SERIAL_RX=34 + -D BRIDGE_OVER_SERIAL_TX=25 + -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +; -D CORE_DEBUG_LEVEL=3 +lib_deps = + ${LilyGo_TLora_V2_1_1_6.lib_deps} + ${esp32_ota.lib_deps} + [env:LilyGo_TLora_V2_1_1_6_terminal_chat] extends = LilyGo_TLora_V2_1_1_6 build_flags = diff --git a/variants/waveshare_rp2040_lora/platformio.ini b/variants/waveshare_rp2040_lora/platformio.ini index b1e4714a..515f7020 100644 --- a/variants/waveshare_rp2040_lora/platformio.ini +++ b/variants/waveshare_rp2040_lora/platformio.ini @@ -35,14 +35,27 @@ build_flags = ${waveshare_rp2040_lora.build_flags} -D ADVERT_LON=0.0 -D ADMIN_PASSWORD='"password"' -D MAX_NEIGHBOURS=8 -; -D BRIDGE_OVER_SERIAL=Serial2 -; -D BRIDGE_OVER_SERIAL_RX=9 -; -D BRIDGE_OVER_SERIAL_TX=8 ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${waveshare_rp2040_lora.build_src_filter} +<../examples/simple_repeater> +[env:waveshare_rp2040_lora_Bridge] +extends = waveshare_rp2040_lora +build_flags = ${waveshare_rp2040_lora.build_flags} + -D ADVERT_NAME='"RP2040-LoRa Bridge"' + -D ADVERT_LAT=0.0 + -D ADVERT_LON=0.0 + -D ADMIN_PASSWORD='"password"' + -D MAX_NEIGHBOURS=8 + -D BRIDGE_OVER_SERIAL=Serial2 + -D BRIDGE_OVER_SERIAL_RX=9 + -D BRIDGE_OVER_SERIAL_TX=8 + -D MESH_PACKET_LOGGING=1 +; -D MESH_DEBUG=1 +build_src_filter = ${waveshare_rp2040_lora.build_src_filter} + +<../examples/simple_repeater> + [env:waveshare_rp2040_lora_room_server] extends = waveshare_rp2040_lora build_flags = ${waveshare_rp2040_lora.build_flags}