From 1b1beab4fafa0b1c6f0905888009128edfe503e2 Mon Sep 17 00:00:00 2001 From: Chad Attermann Date: Sun, 26 May 2024 17:28:51 -0600 Subject: [PATCH] WIP: Work toward removing platform-specifics Moved LoRa and UDP test code into `examples` folder. Moved `main.cpp` test app to `examples` folder. Removed platform-specific filesystem code and replaced with an interface to be implemeneted by the consumer. --- .../lora}/LoRaInterface.cpp | 4 +- .../lora}/LoRaInterface.h | 6 +- examples/lora/main.cpp | 341 +++++++++++++++++ {src => examples}/main.cpp | 0 examples/test/.gitignore | 5 + examples/test/.vscode/extensions.json | 10 + examples/test/.vscode/tasks.json | 29 ++ examples/test/TestFilesystem.cpp | 272 ++++++++++++++ examples/test/TestFilesystem.h | 20 + examples/test/main.cpp | 76 ++++ examples/test/platformio.ini | 150 ++++++++ examples/test/test_destination_table | 1 + examples/test/test_file | 1 + examples/test/test_map | 1 + examples/test/test_object | 1 + examples/test/test_set | 1 + examples/test/test_vector | 1 + .../udp}/UDPInterface.cpp | 2 +- .../udp}/UDPInterface.h | 6 +- examples/udp/main.cpp | 342 ++++++++++++++++++ library.json | 7 +- library.properties | 1 + platformio.ini | 35 +- src/Cryptography/HMAC.h | 1 + src/Destination.h | 1 + src/Filesystem.h | 121 +++++++ src/Identity.h | 1 + src/Interface.h | 3 +- src/Link.h | 1 + src/Packet.h | 1 + src/Reticulum.cpp | 2 - src/Reticulum.h | 1 + src/Test/TestPersistence.cpp | 30 +- src/Transport.cpp | 26 +- src/Utilities/OS.cpp | 181 ++------- src/Utilities/OS.h | 16 +- 36 files changed, 1501 insertions(+), 196 deletions(-) rename {src/Interfaces => examples/lora}/LoRaInterface.cpp (98%) rename {src/Interfaces => examples/lora}/LoRaInterface.h (94%) create mode 100644 examples/lora/main.cpp rename {src => examples}/main.cpp (100%) create mode 100644 examples/test/.gitignore create mode 100644 examples/test/.vscode/extensions.json create mode 100644 examples/test/.vscode/tasks.json create mode 100644 examples/test/TestFilesystem.cpp create mode 100644 examples/test/TestFilesystem.h create mode 100644 examples/test/main.cpp create mode 100644 examples/test/platformio.ini create mode 100644 examples/test/test_destination_table create mode 100644 examples/test/test_file create mode 100644 examples/test/test_map create mode 100644 examples/test/test_object create mode 100644 examples/test/test_set create mode 100644 examples/test/test_vector rename {src/Interfaces => examples/udp}/UDPInterface.cpp (99%) rename {src/Interfaces => examples/udp}/UDPInterface.h (95%) create mode 100644 examples/udp/main.cpp create mode 100644 src/Filesystem.h diff --git a/src/Interfaces/LoRaInterface.cpp b/examples/lora/LoRaInterface.cpp similarity index 98% rename from src/Interfaces/LoRaInterface.cpp rename to examples/lora/LoRaInterface.cpp index c46b49e..4e7908a 100644 --- a/src/Interfaces/LoRaInterface.cpp +++ b/examples/lora/LoRaInterface.cpp @@ -1,7 +1,7 @@ #include "LoRaInterface.h" -#include "../Log.h" -#include "../Utilities/OS.h" +#include "../src/Log.h" +#include "../src/Utilities/OS.h" #include diff --git a/src/Interfaces/LoRaInterface.h b/examples/lora/LoRaInterface.h similarity index 94% rename from src/Interfaces/LoRaInterface.h rename to examples/lora/LoRaInterface.h index a790bd9..b5fb4a3 100644 --- a/src/Interfaces/LoRaInterface.h +++ b/examples/lora/LoRaInterface.h @@ -1,8 +1,8 @@ #pragma once -#include "../Interface.h" -#include "../Bytes.h" -#include "../Type.h" +#include "../src/Interface.h" +#include "../src/Bytes.h" +#include "../src/Type.h" #ifdef ARDUINO #include diff --git a/examples/lora/main.cpp b/examples/lora/main.cpp new file mode 100644 index 0000000..163ad8b --- /dev/null +++ b/examples/lora/main.cpp @@ -0,0 +1,341 @@ +//#define NDEBUG + +#include "LoRaInterface.h" + +#include "Reticulum.h" +#include "Identity.h" +#include "Destination.h" +#include "Packet.h" +#include "Transport.h" +#include "Interface.h" +#include "Log.h" +#include "Bytes.h" +#include "Type.h" +#include "Utilities/OS.h" + +#ifdef ARDUINO +#include +#include +#else +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include + +//#define RETICULUM_PACKET_TEST + +#define BUTTON_PIN 38 +//#define BUTTON_PIN_MASK GPIO_SEL_38 + +// Let's define an app name. We'll use this for all +// destinations we create. Since this basic example +// is part of a range of example utilities, we'll put +// them all within the app namespace "example_utilities" +const char* APP_NAME = "example_utilities"; + +// We initialise two lists of strings to use as app_data +const char* fruits[] = {"Peach", "Quince", "Date", "Tangerine", "Pomelo", "Carambola", "Grape"}; +const char* noble_gases[] = {"Helium", "Neon", "Argon", "Krypton", "Xenon", "Radon", "Oganesson"}; + +double last_announce = 0.0; +bool send_announce = false; + +// Test AnnounceHandler +class ExampleAnnounceHandler : public RNS::AnnounceHandler { +public: + ExampleAnnounceHandler(const char* aspect_filter = nullptr) : AnnounceHandler(aspect_filter) {} + virtual ~ExampleAnnounceHandler() {} + virtual void received_announce(const RNS::Bytes& destination_hash, const RNS::Identity& announced_identity, const RNS::Bytes& app_data) { + RNS::info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); + RNS::info("ExampleAnnounceHandler: destination hash: " + destination_hash.toHex()); + if (announced_identity) { + RNS::info("ExampleAnnounceHandler: announced identity hash: " + announced_identity.hash().toHex()); + RNS::info("ExampleAnnounceHandler: announced identity app data: " + announced_identity.app_data().toHex()); + } + if (app_data) { + RNS::info("ExampleAnnounceHandler: app data text: \"" + app_data.toString() + "\""); + } + RNS::info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); + } +}; + +// Test packet receive callback +void onPacket(const RNS::Bytes& data, const RNS::Packet& packet) { + RNS::info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); + RNS::info("onPacket: data: " + data.toHex()); + RNS::info("onPacket: text: \"" + data.toString() + "\""); + //RNS::extreme("onPacket: " + packet.debugString()); + RNS::info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); +} + +// Ping packet receive callback +void onPingPacket(const RNS::Bytes& data, const RNS::Packet& packet) { + RNS::info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); + RNS::info("onPingPacket: data: " + data.toHex()); + RNS::info("onPingPacket: text: \"" + data.toString() + "\""); + //RNS::extreme("onPingPacket: " + packet.debugString()); + RNS::info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); +} + + +RNS::Reticulum reticulum({RNS::Type::NONE}); +RNS::Identity identity({RNS::Type::NONE}); +RNS::Destination destination({RNS::Type::NONE}); + +RNS::Interfaces::LoRaInterface lora_interface; + +//ExampleAnnounceHandler announce_handler((const char*)"example_utilities.announcesample.fruits"); +//RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler("example_utilities.announcesample.fruits")); +RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler()); + +void reticulum_announce() { + if (destination) { + RNS::head("Announcing destination...", RNS::LOG_EXTREME); + //destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7])); + // test path + //destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7]), true, nullptr, RNS::bytesFromString("test_tag")); + // test packet send + destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7])); + } +} + +void reticulum_setup() { + RNS::info("Setting up Reticulum..."); + + try { + + //std::stringstream test; + // !!! just adding this single stringstream alone (not even using it) adds a whopping 17.1% !!! + // !!! JUST SAY NO TO STRINGSTREAM !!! + + // 18.5% completely empty program + + // 21.8% baseline here with serial + + RNS::head("Registering Interface instances with Transport...", RNS::LOG_EXTREME); + lora_interface.mode(RNS::Type::Interface::MODE_GATEWAY); + RNS::Transport::register_interface(lora_interface); + + RNS::head("Starting LoRaInterface...", RNS::LOG_EXTREME); + lora_interface.start(); + + RNS::head("Creating Reticulum instance...", RNS::LOG_EXTREME); + //RNS::Reticulum reticulum; + reticulum = RNS::Reticulum(); + reticulum.transport_enabled(true); + reticulum.start(); + //return; + // 21.9% (+0.1%) + + RNS::head("Creating Identity instance...", RNS::LOG_EXTREME); + // new identity + //RNS::Identity identity; + //identity = RNS::Identity(); + // predefined identity + //RNS::Identity identity(false); + identity = RNS::Identity(false); + RNS::Bytes prv_bytes; +#ifdef ARDUINO + prv_bytes.assignHex("78E7D93E28D55871608FF13329A226CABC3903A357388A035B360162FF6321570B092E0583772AB80BC425F99791DF5CA2CA0A985FF0415DAB419BBC64DDFAE8"); +#else + prv_bytes.assignHex("E0D43398EDC974EBA9F4A83463691A08F4D306D4E56BA6B275B8690A2FBD9852E9EBE7C03BC45CAEC9EF8E78C830037210BFB9986F6CA2DEE2B5C28D7B4DE6B0"); +#endif + identity.load_private_key(prv_bytes); + // 22.6% (+0.7%) + + RNS::head("Creating Destination instance...", RNS::LOG_EXTREME); + //RNS::Destination destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "app", "aspects"); + destination = RNS::Destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "app", "aspects"); + // 23.0% (+0.4%) + + // Register DATA packet callback + RNS::head("Registering packet callback with Destination...", RNS::LOG_EXTREME); + destination.set_packet_callback(onPacket); + destination.set_proof_strategy(RNS::Type::Destination::PROVE_ALL); + + { + // Register PING packet callback + RNS::head("Creating PING Destination instance...", RNS::LOG_EXTREME); + RNS::Destination ping_destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "example_utilities", "echo.request"); + + RNS::head("Registering packet callback with PING Destination...", RNS::LOG_EXTREME); + ping_destination.set_packet_callback(onPingPacket); + ping_destination.set_proof_strategy(RNS::Type::Destination::PROVE_ALL); + } + + RNS::head("Registering announce handler with Transport...", RNS::LOG_EXTREME); + RNS::Transport::register_announce_handler(announce_handler); + +/* + RNS::head("Announcing destination...", RNS::LOG_EXTREME); + //destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7])); + // test path + //destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7]), true, nullptr, RNS::bytesFromString("test_tag")); + // test packet send + destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7])); + // 23.9% (+0.8%) +*/ + +#if defined (RETICULUM_PACKET_TEST) + // test data send packet + RNS::head("Creating send packet...", RNS::LOG_EXTREME); + RNS::Packet send_packet(destination, "The quick brown fox jumps over the lazy dog"); + + RNS::head("Sending send packet...", RNS::LOG_EXTREME); + send_packet.pack(); +#ifndef NDEBUG + RNS::extreme("Test send_packet: " + send_packet.debugString()); +#endif + + RNS::head("Creating recv packet...", RNS::LOG_EXTREME); + RNS::Packet recv_packet({RNS::Type::NONE}, send_packet.raw()); + recv_packet.unpack(); +#ifndef NDEBUG + RNS::extreme("Test recv_packet: " + recv_packet.debugString()); +#endif + + RNS::head("Spoofing recv packet to destination...", RNS::LOG_EXTREME); + destination.receive(recv_packet); +#endif + + RNS::head("Ready!", RNS::LOG_EXTREME); + } + catch (std::exception& e) { + RNS::error(std::string("!!! Exception in reticulum_setup: ") + e.what() + " !!!"); + } +} + +void reticulum_teardown() { + RNS::info("Tearing down Reticulum..."); + + RNS::Transport::save_path_table(); + + try { + + RNS::head("Deregistering announce handler with Transport...", RNS::LOG_EXTREME); + RNS::Transport::deregister_announce_handler(announce_handler); + + RNS::head("Deregistering Interface instances with Transport...", RNS::LOG_EXTREME); + RNS::Transport::deregister_interface(lora_interface); + + } + catch (std::exception& e) { + RNS::error(std::string("!!! Exception in reticulum_teardown: ") + e.what() + " !!!"); + } +} + +#ifdef ARDUINO +void userKey(void) +{ + //delay(10); + if (digitalRead(BUTTON_PIN) == LOW) { + //Serial.print("T-Beam USER button press\n"); + send_announce = true; + } +} +#endif + +void setup() { + +#ifdef ARDUINO + Serial.begin(115200); + Serial.print("Hello from T-Beam on PlatformIO!\n"); + + // Setup user button + pinMode(BUTTON_PIN, INPUT); + attachInterrupt(BUTTON_PIN, userKey, FALLING); + + // Setup filesystem + if (!SPIFFS.begin(true, "")){ + RNS::error("SPIFFS filesystem mount failed"); + } + else { + RNS::debug("SPIFFS filesystem is ready"); + } +#endif + + RNS::loglevel(RNS::LOG_EXTREME); + //RNS::loglevel(RNS::LOG_MEM); + +/* + { + //RNS::Reticulum reticulum_test; + RNS::Destination destination_test({RNS::Type::NONE}, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "test", "test"); + } +*/ + + reticulum_setup(); + +#ifdef ARDUINO + //Serial.print("Goodbye from T-Beam on PlatformIO!\n"); +#endif +} + +void loop() { + + reticulum.loop(); + lora_interface.loop(); + +#ifdef ARDUINO +/* + if ((RNS::Utilities::OS::time() - last_announce) > 10) { + reticulum_announce(); + last_announce = RNS::Utilities::OS::time(); + } +*/ +#endif + if (send_announce) { + reticulum_announce(); + send_announce = false; + } + +} + +#ifndef ARDUINO +int getch( ) { + termios oldt; + termios newt; + tcgetattr( STDIN_FILENO, &oldt ); + newt = oldt; + newt.c_lflag &= ~( ICANON | ECHO ); + tcsetattr( STDIN_FILENO, TCSANOW, &newt ); + fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL) | O_NONBLOCK); + int ch = getchar(); + tcsetattr( STDIN_FILENO, TCSANOW, &oldt ); + return ch; +} + +int main(void) { + printf("Hello from Native on PlatformIO!\n"); + + setup(); + + bool run = true; + while (run) { + loop(); + int ch = getch(); + if (ch > 0) { + switch (ch) { + case 'a': + reticulum_announce(); + break; + case 'q': + run = false; + break; + } + } + RNS::Utilities::OS::sleep(0.01); + } + + reticulum_teardown(); + + printf("Goodbye from Native on PlatformIO!\n"); +} +#endif diff --git a/src/main.cpp b/examples/main.cpp similarity index 100% rename from src/main.cpp rename to examples/main.cpp diff --git a/examples/test/.gitignore b/examples/test/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/examples/test/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/examples/test/.vscode/extensions.json b/examples/test/.vscode/extensions.json new file mode 100644 index 0000000..080e70d --- /dev/null +++ b/examples/test/.vscode/extensions.json @@ -0,0 +1,10 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ], + "unwantedRecommendations": [ + "ms-vscode.cpptools-extension-pack" + ] +} diff --git a/examples/test/.vscode/tasks.json b/examples/test/.vscode/tasks.json new file mode 100644 index 0000000..5318667 --- /dev/null +++ b/examples/test/.vscode/tasks.json @@ -0,0 +1,29 @@ +{ + "tasks": [ + { + "type": "cppbuild", + "label": "C/C++: clang++ build active file", + "command": "/usr/bin/clang++", + "args": [ + "-fcolor-diagnostics", + "-fansi-escape-codes", + "-g", + "${file}", + "-o", + "${fileDirname}/${fileBasenameNoExtension}" + ], + "options": { + "cwd": "${fileDirname}" + }, + "problemMatcher": [ + "$gcc" + ], + "group": { + "kind": "build", + "isDefault": true + }, + "detail": "Task generated by Debugger." + } + ], + "version": "2.0.0" +} \ No newline at end of file diff --git a/examples/test/TestFilesystem.cpp b/examples/test/TestFilesystem.cpp new file mode 100644 index 0000000..6559358 --- /dev/null +++ b/examples/test/TestFilesystem.cpp @@ -0,0 +1,272 @@ +#include "TestFilesystem.h" + +#include + +#ifdef ARDUINO +#ifdef ESP32 +#include +#include +#elif NRF52 +#include +#include +using namespace Adafruit_LittleFS_Namespace; +#endif +#else +#include +#include +#include +#include +#endif + +using namespace RNS; + +#ifdef ARDUINO +void listDir(char * dir){ + Serial.print("DIR: "); + Serial.println(dir); +#ifdef ESP32 + File root = SPIFFS.open(dir); + File file = root.openNextFile(); + while(file){ + Serial.print(" FILE: "); + Serial.println(file.name()); + file = root.openNextFile(); + } +#elif NRF52 + File root = InternalFS.open(dir); + File file = root.openNextFile(); + while(file){ + Serial.print(" FILE: "); + Serial.println(file.name()); + file = root.openNextFile(); + } +#endif +} +#endif + +TestFilesystem::TestFilesystem() : Filesystem() { + extreme("TestFilesystem initializing..."); + +#ifdef ARDUINO +#ifdef ESP32 + // Setup filesystem + info("SPIFFS mounting filesystem"); + if (!SPIFFS.begin(true, "")){ + error("SPIFFS filesystem mount failed"); + return; + } + uint32_t size = SPIFFS.totalBytes() / (1024 * 1024); + Serial.print("size: "); + Serial.print(size); + Serial.println(" MB"); + uint32_t used = SPIFFS.usedBytes() / (1024 * 1024); + Serial.print("used: "); + Serial.print(used); + Serial.println(" MB"); + // ensure filesystem is writable and format if not + Bytes test; + if (!OS::write_file(test, "/test")) { + info("SPIFFS filesystem is being formatted, please wait..."); + SPIFFS.format(); + } + else { + OS::remove_file("/test"); + } + debug("SPIFFS filesystem is ready"); +#elif NRF52 + // Initialize Internal File System + info("InternalFS mounting filesystem"); + InternalFS.begin(); + info("InternalFS filesystem is ready"); +#endif + listDir("/"); +#endif + +} + +/*virtual*/ TestFilesystem::~TestFilesystem() { +} + +/*virtual*/ bool TestFilesystem::file_exists(const char* file_path) { +#ifdef ARDUINO +#ifdef ESP32 + File file = SPIFFS.open(file_path, FILE_READ); + if (file) { +#elif NRF52 + File file(InternalFS); + file.open(file_path, FILE_O_READ); + if (file) { +#else + if (false) { +#endif +#else + FILE* file = fopen(file_path, "r"); + if (file != nullptr) { +#endif + //extreme("file_exists: file exists, closing file"); +#ifdef ARDUINO +#ifdef ESP32 + file.close(); +#elif NRF52 + file.close(); +#endif +#else + fclose(file); +#endif + return true; + } + else { + error("file_exists: failed to open file " + std::string(file_path)); + return false; + } +} + +/*virtual*/ const Bytes TestFilesystem::read_file(const char* file_path) { + Bytes data; +#ifdef ARDUINO +#ifdef ESP32 + File file = SPIFFS.open(file_path, FILE_READ); + if (file) { + size_t size = file.size(); + size_t read = file.readBytes((char*)data.writable(size), size); +#elif NRF52 + File file(InternalFS); + file.open(file_path, FILE_O_READ); + if (file) { + size_t size = file.size(); + size_t read = file.readBytes((char*)data.writable(size), size); +#else + if (false) { + size_t size = 0; + size_t read = 0; +#endif +#else + FILE* file = fopen(file_path, "r"); + if (file != nullptr) { + fseek(file, 0, SEEK_END); + size_t size = ftell(file); + rewind(file); + //size_t read = fread(data.writable(size), size, 1, file); + size_t read = fread(data.writable(size), 1, size, file); +#endif + extreme("read_file: read " + std::to_string(read) + " Bytes from file " + std::string(file_path)); + if (read != size) { + error("read_file: failed to read file " + std::string(file_path)); + data.clear(); + } + //extreme("read_file: closing input file"); +#ifdef ARDUINO +#ifdef ESP32 + file.close(); +#elif NRF52 + file.close(); +#endif +#else + fclose(file); +#endif + } + else { + error("read_file: failed to open input file " + std::string(file_path)); + } + return data; +} + +/*virtual*/ bool TestFilesystem::write_file(const Bytes& data, const char* file_path) { + bool success = false; +#ifdef ARDUINO +#ifdef ESP32 + File file = SPIFFS.open(file_path, FILE_WRITE); + if (file) { + size_t wrote = file.write(data.data(), data.size()); +#elif NRF52 + File file(InternalFS); + file.open(file_path, FILE_O_WRITE); + if (file) { + size_t wrote = file.write(data.data(), data.size()); +#else + if (false) { + size_t wrote = 0; +#endif +#else + FILE* file = fopen(file_path, "w"); + if (file != nullptr) { + //size_t wrote = fwrite(data.data(), data.size(), 1, file); + size_t wrote = fwrite(data.data(), 1, data.size(), file); +#endif + extreme("write_file: wrote " + std::to_string(wrote) + " Bytes to file " + std::string(file_path)); + if (wrote == data.size()) { + success = true; + } + else { + error("write_file: failed to write file " + std::string(file_path)); + } + //extreme("write_file: closing output file"); +#ifdef ARDUINO +#ifdef ESP32 + file.close(); +#elif NRF52 + file.close(); +#endif +#else + fclose(file); +#endif + } + else { + error("write_file: failed to open output file " + std::string(file_path)); + } + return success; +} + +/*virtual*/ bool TestFilesystem::remove_file(const char* file_path) { +#ifdef ARDUINO +#ifdef ESP32 + return SPIFFS.remove(file_path); +#elif NRF52 + return InternalFS.remove(file_path); +#else + return false; +#endif +#else + return (remove(file_path) == 0); +#endif +} + +/*virtual*/ bool TestFilesystem::rename_file(const char* from_file_path, const char* to_file_path) { +#ifdef ARDUINO +#ifdef ESP32 + return SPIFFS.rename(from_file_path, to_file_path); +#elif NRF52 + return InternalFS.rename(from_file_path, to_file_path); +#else + return false; +#endif +#else + return (rename(from_file_path, to_file_path) == 0); +#endif +} + +/*virtual*/ bool TestFilesystem::create_directory(const char* directory_path) { +#ifdef ARDUINO +#ifdef ESP32 + if (!SPIFFS.mkdir(directory_path)) { + error("create_directory: failed to create directorty " + std::string(directory_path)); + return false; + } + return true; +#elif NRF52 + if (!InternalFS.mkdir(directory_path)) { + error("create_directory: failed to create directorty " + std::string(directory_path)); + return false; + } + return true; +#else + return false; +#endif +#else + struct stat st = {0}; + if (stat(directory_path, &st) == 0) { + return true; + } + return (mkdir(directory_path, 0700) == 0); +#endif +} diff --git a/examples/test/TestFilesystem.h b/examples/test/TestFilesystem.h new file mode 100644 index 0000000..2b7fc33 --- /dev/null +++ b/examples/test/TestFilesystem.h @@ -0,0 +1,20 @@ +#pragma once + +#include +#include + +class TestFilesystem : public RNS::Filesystem { + +public: + TestFilesystem(); + virtual ~TestFilesystem(); + +protected: + virtual bool file_exists(const char* file_path); + virtual const RNS::Bytes read_file(const char* file_path); + virtual bool write_file(const RNS::Bytes& data, const char* file_path); + virtual bool remove_file(const char* file_path); + virtual bool rename_file(const char* from_file_path, const char* to_file_path); + virtual bool create_directory(const char* directory_path); + +}; diff --git a/examples/test/main.cpp b/examples/test/main.cpp new file mode 100644 index 0000000..172877d --- /dev/null +++ b/examples/test/main.cpp @@ -0,0 +1,76 @@ +//#define NDEBUG + +#include "TestFilesystem.h" + +#include + +#include "Log.h" +#include "Utilities/OS.h" + +#ifdef ARDUINO +#include +#else +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include + +TestFilesystem filesystem; + +void setup() { + +#ifdef ARDUINO + Serial.begin(115200); + Serial.print("Hello from T-Beam on PlatformIO!\n"); +#endif + + RNS::loglevel(RNS::LOG_EXTREME); + //RNS::loglevel(RNS::LOG_MEM); + + if (filesystem) { + RNS::info("TestFilesystem exists"); + } + RNS::Utilities::OS::register_filesystem(filesystem); + + try { + + RNS::extreme("Running tests..."); + RNS::LogLevel loglevel = RNS::loglevel(); + //RNS::loglevel(RNS::LOG_WARNING); + RNS::loglevel(RNS::LOG_EXTREME); + //test(); + //testReference(); + //testCrypto(); + testPersistence(); + RNS::loglevel(loglevel); + RNS::extreme("Finished running tests"); + //return; + } + catch (std::exception& e) { + RNS::error(std::string("!!! Exception in test: ") + e.what() + " !!!"); + } + +#ifdef ARDUINO + //Serial.print("Goodbye from T-Beam on PlatformIO!\n"); +#endif +} + +void loop() { +} + +#ifndef ARDUINO +int main(void) { + printf("Hello from Native on PlatformIO!\n"); + + setup(); + + printf("Goodbye from Native on PlatformIO!\n"); +} +#endif diff --git a/examples/test/platformio.ini b/examples/test/platformio.ini new file mode 100644 index 0000000..f5c3071 --- /dev/null +++ b/examples/test/platformio.ini @@ -0,0 +1,150 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[platformio] +;default_envs = native +;include_dir = ../../src +;src_dir = ../../src +include_dir = . +src_dir = . + +[env:native] +platform = native +build_flags = + -std=c++11 + -Wall + -Wextra + -Wno-missing-field-initializers + -Wno-format + -Wno-unused-parameter + -I. + -DNATIVE +lib_deps = + ArduinoJson@^6.21.3 + https://github.com/attermann/arduinolibs.git + microReticulum=symlink://../.. +lib_extra_dirs = ../ +lib_compat_mode = off + +[env:native17] +platform = native +build_unflags = -std=gnu++11 +build_flags = + -std=c++17 + -Wall + -Wextra + -Wno-missing-field-initializers + -Wno-format + -Wno-unused-parameter + -I. + -DNATIVE +lib_deps = + ArduinoJson@^6.21.3 + https://github.com/attermann/arduinolibs.git + microReticulum=symlink://../.. +lib_compat_mode = off + +[env:cubecell-gps] +platform = heltec-cubecell +board = cubecell_gps +framework = arduino +monitor_speed = 115200 +;build_flags = -Wl,-Map,output.map +build_flags = + -std=c++11 + -Wall + -Wextra + -Wno-missing-field-initializers + -Wno-format + -I. + -DCUBECELL +lib_deps = + ArduinoJson@^6.21.3 + https://github.com/attermann/arduinolibs.git + microReticulum=symlink://../.. +; CBA NOTE must undef min and max from Arduino.h + +[env:heltec-tracker] +platform = espressif32 +board = heltec_wireless_tracker +upload_protocol = esp-builtin +;board_build.partitions = no_ota.csv +;board_build.partitions = huge_app.csv +framework = arduino +monitor_speed = 115200 +build_flags = + -Wall + -Wextra + -Wno-missing-field-initializers + -Wno-format + -I variants/heltec_wireless_tracker + -I. + -DESP32 +lib_deps = + lovyan03/LovyanGFX@^1.1.8 + ArduinoJson@^6.21.3 + https://github.com/attermann/arduinolibs.git + microReticulum=symlink://../.. + +[env:ttgo-lora32-v21] +platform = espressif32 +board = ttgo-lora32-v21 +board_build.partitions = no_ota.csv +framework = arduino +monitor_speed = 115200 +build_flags = + -Wall + -Wextra + -Wno-missing-field-initializers + -Wno-format + -I. + -DESP32 +lib_deps = + ArduinoJson@^6.21.3 + https://github.com/attermann/arduinolibs.git + microReticulum=symlink://../.. + +[env:ttgo-t-beam] +platform = espressif32 +board = ttgo-t-beam +board_build.partitions = no_ota.csv +;board_build.partitions = huge_app.csv +framework = arduino +monitor_speed = 115200 +build_flags = + -Wall + -Wextra + -Wno-missing-field-initializers + -Wno-format + -I. + -DESP32 +lib_deps = + ArduinoJson@^6.21.3 + https://github.com/attermann/arduinolibs.git + microReticulum=symlink://../.. + +[env:wiscore_rak4631] +platform = nordicnrf52 +board = wiscore_rak4631 +board_build.partitions = no_ota.csv +framework = arduino +monitor_speed = 115200 +build_flags = + -fexceptions + -Wall + ;-Wextra + -Wno-missing-field-initializers + -Wno-format + -I. + ;-DNRF52 +lib_deps = + ArduinoJson@^6.21.3 + https://github.com/attermann/arduinolibs.git + microReticulum=symlink://../.. diff --git a/examples/test/test_destination_table b/examples/test/test_destination_table new file mode 100644 index 0000000..c8a4595 --- /dev/null +++ b/examples/test/test_destination_table @@ -0,0 +1 @@ +{"1111111111111111":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"2222222222222222":{"timestamp":2,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null}} \ No newline at end of file diff --git a/examples/test/test_file b/examples/test/test_file new file mode 100644 index 0000000..0aa6fb5 --- /dev/null +++ b/examples/test/test_file @@ -0,0 +1 @@ +test data \ No newline at end of file diff --git a/examples/test/test_map b/examples/test/test_map new file mode 100644 index 0000000..7f681b5 --- /dev/null +++ b/examples/test/test_map @@ -0,0 +1 @@ +{"one":{"str":"one","vec":["foo","bar"]},"two":{"str":"two","vec":["foo","bar"]}} \ No newline at end of file diff --git a/examples/test/test_object b/examples/test/test_object new file mode 100644 index 0000000..6204578 --- /dev/null +++ b/examples/test/test_object @@ -0,0 +1 @@ +{"str":"test","vec":["one","two"]} \ No newline at end of file diff --git a/examples/test/test_set b/examples/test/test_set new file mode 100644 index 0000000..ec747fa --- /dev/null +++ b/examples/test/test_set @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/examples/test/test_vector b/examples/test/test_vector new file mode 100644 index 0000000..b350935 --- /dev/null +++ b/examples/test/test_vector @@ -0,0 +1 @@ +[{"str":"two","vec":["foo","bar"]},{"str":"one","vec":["foo","bar"]}] \ No newline at end of file diff --git a/src/Interfaces/UDPInterface.cpp b/examples/udp/UDPInterface.cpp similarity index 99% rename from src/Interfaces/UDPInterface.cpp rename to examples/udp/UDPInterface.cpp index 6e23336..a8a4f0a 100644 --- a/src/Interfaces/UDPInterface.cpp +++ b/examples/udp/UDPInterface.cpp @@ -1,6 +1,6 @@ #include "UDPInterface.h" -#include "../Log.h" +#include "../src/Log.h" #include diff --git a/src/Interfaces/UDPInterface.h b/examples/udp/UDPInterface.h similarity index 95% rename from src/Interfaces/UDPInterface.h rename to examples/udp/UDPInterface.h index 41251cd..f7e698b 100644 --- a/src/Interfaces/UDPInterface.h +++ b/examples/udp/UDPInterface.h @@ -1,8 +1,8 @@ #pragma once -#include "../Interface.h" -#include "../Bytes.h" -#include "../Type.h" +#include "../src/Interface.h" +#include "../src/Bytes.h" +#include "../src/Type.h" #ifdef ARDUINO #include diff --git a/examples/udp/main.cpp b/examples/udp/main.cpp new file mode 100644 index 0000000..612490a --- /dev/null +++ b/examples/udp/main.cpp @@ -0,0 +1,342 @@ +//#define NDEBUG + +#include "UDPInterface.h" + +#include "Reticulum.h" +#include "Identity.h" +#include "Destination.h" +#include "Packet.h" +#include "Transport.h" +#include "Interface.h" +#include "Log.h" +#include "Bytes.h" +#include "Type.h" +#include "Utilities/OS.h" + +#ifdef ARDUINO +#include +#include +#else +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +//#include + +//#define RETICULUM_PACKET_TEST + +#define BUTTON_PIN 38 +//#define BUTTON_PIN_MASK GPIO_SEL_38 + +// Let's define an app name. We'll use this for all +// destinations we create. Since this basic example +// is part of a range of example utilities, we'll put +// them all within the app namespace "example_utilities" +const char* APP_NAME = "example_utilities"; + +// We initialise two lists of strings to use as app_data +const char* fruits[] = {"Peach", "Quince", "Date", "Tangerine", "Pomelo", "Carambola", "Grape"}; +const char* noble_gases[] = {"Helium", "Neon", "Argon", "Krypton", "Xenon", "Radon", "Oganesson"}; + +double last_announce = 0.0; +bool send_announce = false; + +// Test AnnounceHandler +class ExampleAnnounceHandler : public RNS::AnnounceHandler { +public: + ExampleAnnounceHandler(const char* aspect_filter = nullptr) : AnnounceHandler(aspect_filter) {} + virtual ~ExampleAnnounceHandler() {} + virtual void received_announce(const RNS::Bytes& destination_hash, const RNS::Identity& announced_identity, const RNS::Bytes& app_data) { + RNS::info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); + RNS::info("ExampleAnnounceHandler: destination hash: " + destination_hash.toHex()); + if (announced_identity) { + RNS::info("ExampleAnnounceHandler: announced identity hash: " + announced_identity.hash().toHex()); + RNS::info("ExampleAnnounceHandler: announced identity app data: " + announced_identity.app_data().toHex()); + } + if (app_data) { + RNS::info("ExampleAnnounceHandler: app data text: \"" + app_data.toString() + "\""); + } + RNS::info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); + } +}; + +// Test packet receive callback +void onPacket(const RNS::Bytes& data, const RNS::Packet& packet) { + RNS::info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); + RNS::info("onPacket: data: " + data.toHex()); + RNS::info("onPacket: text: \"" + data.toString() + "\""); + //RNS::extreme("onPacket: " + packet.debugString()); + RNS::info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); +} + +// Ping packet receive callback +void onPingPacket(const RNS::Bytes& data, const RNS::Packet& packet) { + RNS::info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); + RNS::info("onPingPacket: data: " + data.toHex()); + RNS::info("onPingPacket: text: \"" + data.toString() + "\""); + //RNS::extreme("onPingPacket: " + packet.debugString()); + RNS::info("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); +} + + +RNS::Reticulum reticulum({RNS::Type::NONE}); +RNS::Identity identity({RNS::Type::NONE}); +RNS::Destination destination({RNS::Type::NONE}); + +RNS::Interfaces::UDPInterface udp_interface("udp"); + +//ExampleAnnounceHandler announce_handler((const char*)"example_utilities.announcesample.fruits"); +//RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler("example_utilities.announcesample.fruits")); +RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler()); + +void reticulum_announce() { + if (destination) { + RNS::head("Announcing destination...", RNS::LOG_EXTREME); + //destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7])); + // test path + //destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7]), true, nullptr, RNS::bytesFromString("test_tag")); + // test packet send + destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7])); + } +} + +void reticulum_setup() { + RNS::info("Setting up Reticulum..."); + + try { + + //std::stringstream test; + // !!! just adding this single stringstream alone (not even using it) adds a whopping 17.1% !!! + // !!! JUST SAY NO TO STRINGSTREAM !!! + + // 18.5% completely empty program + + // 21.8% baseline here with serial + + RNS::head("Registering Interface instances with Transport...", RNS::LOG_EXTREME); + udp_interface.mode(RNS::Type::Interface::MODE_GATEWAY); + RNS::Transport::register_interface(udp_interface); + + RNS::head("Starting UDPInterface...", RNS::LOG_EXTREME); + udp_interface.start("wifi_ssid", "wifi_password", 4242); + + RNS::head("Creating Reticulum instance...", RNS::LOG_EXTREME); + //RNS::Reticulum reticulum; + reticulum = RNS::Reticulum(); + reticulum.transport_enabled(true); + reticulum.start(); + //return; + // 21.9% (+0.1%) + + RNS::head("Creating Identity instance...", RNS::LOG_EXTREME); + // new identity + //RNS::Identity identity; + //identity = RNS::Identity(); + // predefined identity + //RNS::Identity identity(false); + identity = RNS::Identity(false); + RNS::Bytes prv_bytes; +#ifdef ARDUINO + prv_bytes.assignHex("78E7D93E28D55871608FF13329A226CABC3903A357388A035B360162FF6321570B092E0583772AB80BC425F99791DF5CA2CA0A985FF0415DAB419BBC64DDFAE8"); +#else + prv_bytes.assignHex("E0D43398EDC974EBA9F4A83463691A08F4D306D4E56BA6B275B8690A2FBD9852E9EBE7C03BC45CAEC9EF8E78C830037210BFB9986F6CA2DEE2B5C28D7B4DE6B0"); +#endif + identity.load_private_key(prv_bytes); + // 22.6% (+0.7%) + + RNS::head("Creating Destination instance...", RNS::LOG_EXTREME); + //RNS::Destination destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "app", "aspects"); + destination = RNS::Destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "app", "aspects"); + // 23.0% (+0.4%) + + // Register DATA packet callback + RNS::head("Registering packet callback with Destination...", RNS::LOG_EXTREME); + destination.set_packet_callback(onPacket); + destination.set_proof_strategy(RNS::Type::Destination::PROVE_ALL); + + { + // Register PING packet callback + RNS::head("Creating PING Destination instance...", RNS::LOG_EXTREME); + RNS::Destination ping_destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "example_utilities", "echo.request"); + + RNS::head("Registering packet callback with PING Destination...", RNS::LOG_EXTREME); + ping_destination.set_packet_callback(onPingPacket); + ping_destination.set_proof_strategy(RNS::Type::Destination::PROVE_ALL); + } + + RNS::head("Registering announce handler with Transport...", RNS::LOG_EXTREME); + RNS::Transport::register_announce_handler(announce_handler); + +/* + RNS::head("Announcing destination...", RNS::LOG_EXTREME); + //destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7])); + // test path + //destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7]), true, nullptr, RNS::bytesFromString("test_tag")); + // test packet send + destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7])); + // 23.9% (+0.8%) +*/ + +#if defined (RETICULUM_PACKET_TEST) + // test data send packet + RNS::head("Creating send packet...", RNS::LOG_EXTREME); + RNS::Packet send_packet(destination, "The quick brown fox jumps over the lazy dog"); + + RNS::head("Sending send packet...", RNS::LOG_EXTREME); + send_packet.pack(); +#ifndef NDEBUG + RNS::extreme("Test send_packet: " + send_packet.debugString()); +#endif + + RNS::head("Creating recv packet...", RNS::LOG_EXTREME); + RNS::Packet recv_packet({RNS::Type::NONE}, send_packet.raw()); + recv_packet.unpack(); +#ifndef NDEBUG + RNS::extreme("Test recv_packet: " + recv_packet.debugString()); +#endif + + RNS::head("Spoofing recv packet to destination...", RNS::LOG_EXTREME); + destination.receive(recv_packet); +#endif + + RNS::head("Ready!", RNS::LOG_EXTREME); + } + catch (std::exception& e) { + RNS::error(std::string("!!! Exception in reticulum_setup: ") + e.what() + " !!!"); + } +} + +void reticulum_teardown() { + RNS::info("Tearing down Reticulum..."); + + RNS::Transport::save_path_table(); + + try { + + RNS::head("Deregistering announce handler with Transport...", RNS::LOG_EXTREME); + RNS::Transport::deregister_announce_handler(announce_handler); + + RNS::head("Deregistering Interface instances with Transport...", RNS::LOG_EXTREME); + RNS::Transport::deregister_interface(udp_interface); + + } + catch (std::exception& e) { + RNS::error(std::string("!!! Exception in reticulum_teardown: ") + e.what() + " !!!"); + } +} + +#ifdef ARDUINO +void userKey(void) +{ + //delay(10); + if (digitalRead(BUTTON_PIN) == LOW) { + //Serial.print("T-Beam USER button press\n"); + send_announce = true; + } +} +#endif + +void setup() { + +#ifdef ARDUINO + Serial.begin(115200); + Serial.print("Hello from T-Beam on PlatformIO!\n"); + + // Setup user button + pinMode(BUTTON_PIN, INPUT); + attachInterrupt(BUTTON_PIN, userKey, FALLING); + + // Setup filesystem + if (!SPIFFS.begin(true, "")){ + RNS::error("SPIFFS filesystem mount failed"); + } + else { + RNS::debug("SPIFFS filesystem is ready"); + } +#endif + + RNS::loglevel(RNS::LOG_EXTREME); + //RNS::loglevel(RNS::LOG_MEM); + +/* + { + //RNS::Reticulum reticulum_test; + RNS::Destination destination_test({RNS::Type::NONE}, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "test", "test"); + } +*/ + + reticulum_setup(); + +#ifdef ARDUINO + //Serial.print("Goodbye from T-Beam on PlatformIO!\n"); +#endif +} + +void loop() { + + reticulum.loop(); + udp_interface.loop(); + +#ifdef ARDUINO +/* + if ((RNS::Utilities::OS::time() - last_announce) > 10) { + reticulum_announce(); + last_announce = RNS::Utilities::OS::time(); + } +*/ +#endif + if (send_announce) { + reticulum_announce(); + send_announce = false; + } + +} + +#ifndef ARDUINO +int getch( ) { + termios oldt; + termios newt; + tcgetattr( STDIN_FILENO, &oldt ); + newt = oldt; + newt.c_lflag &= ~( ICANON | ECHO ); + tcsetattr( STDIN_FILENO, TCSANOW, &newt ); + fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL) | O_NONBLOCK); + int ch = getchar(); + tcsetattr( STDIN_FILENO, TCSANOW, &oldt ); + return ch; +} + +int main(void) { + printf("Hello from Native on PlatformIO!\n"); + + setup(); + + bool run = true; + while (run) { + loop(); + int ch = getch(); + if (ch > 0) { + switch (ch) { + case 'a': + reticulum_announce(); + break; + case 'q': + run = false; + break; + } + } + RNS::Utilities::OS::sleep(0.01); + } + + reticulum_teardown(); + + printf("Goodbye from Native on PlatformIO!\n"); +} +#endif diff --git a/library.json b/library.json index 19dce97..55728c0 100644 --- a/library.json +++ b/library.json @@ -20,15 +20,12 @@ "homepage": "https://reticulum.network/", "dependencies": { "ArduinoJson": "~6.21.3", - "rweather/Crypto": "~0.4.0", - "sandeepmistry/LoRa": "~0.8.0", - "WiFi": "~2.0.0" + "rweather/Crypto": "~0.4.0" }, "frameworks": "*", "platforms": "*", "export": {}, "exclude": [ - ".github", - "src/main.cpp" + ".github" ] } \ No newline at end of file diff --git a/library.properties b/library.properties index 72222cc..6e7d99c 100644 --- a/library.properties +++ b/library.properties @@ -7,3 +7,4 @@ paragraph=Port of Reticulum Network Stack to C++ specifically but not exclusivel category=Communication url=https://github.com/attermann/microReticulum.git architectures=* +depends=ArduinoJson,rweather/Crypto diff --git a/platformio.ini b/platformio.ini index 54b2b31..75d33a1 100644 --- a/platformio.ini +++ b/platformio.ini @@ -24,7 +24,7 @@ build_flags = -DNATIVE lib_deps = ArduinoJson@^6.21.3 - rweather/Crypto@^0.4.0 + https://github.com/attermann/arduinolibs.git lib_compat_mode = off [env:native17] @@ -40,7 +40,8 @@ build_flags = -Isrc -DNATIVE lib_deps = - rweather/Crypto@^0.4.0 + ArduinoJson@^6.21.3 + https://github.com/attermann/arduinolibs.git lib_compat_mode = off [env:cubecell-gps] @@ -58,7 +59,7 @@ build_flags = -Isrc lib_deps = ArduinoJson@^6.21.3 - rweather/Crypto@^0.4.0 + https://github.com/attermann/arduinolibs.git ; CBA NOTE must undef min and max from Arduino.h [env:heltec-tracker] @@ -77,10 +78,9 @@ build_flags = -I variants/heltec_wireless_tracker -Isrc lib_deps = - ArduinoJson@^6.21.3 - rweather/Crypto@^0.4.0 - sandeepmistry/LoRa@^0.8.0 lovyan03/LovyanGFX@^1.1.8 + ArduinoJson@^6.21.3 + https://github.com/attermann/arduinolibs.git [env:ttgo-lora32-v21] platform = espressif32 @@ -96,8 +96,7 @@ build_flags = -Isrc lib_deps = ArduinoJson@^6.21.3 - rweather/Crypto@^0.4.0 - sandeepmistry/LoRa@^0.8.0 + https://github.com/attermann/arduinolibs.git [env:ttgo-t-beam] platform = espressif32 @@ -114,5 +113,21 @@ build_flags = -Isrc lib_deps = ArduinoJson@^6.21.3 - rweather/Crypto@^0.4.0 - sandeepmistry/LoRa@^0.8.0 + https://github.com/attermann/arduinolibs.git + +[env:wiscore_rak4631] +platform = nordicnrf52 +board = wiscore_rak4631 +board_build.partitions = no_ota.csv +framework = arduino +monitor_speed = 115200 +build_flags = + -fexceptions + -Wall + -Wextra + -Wno-missing-field-initializers + -Wno-format + -Isrc +lib_deps = + ArduinoJson@^6.21.3 + https://github.com/attermann/arduinolibs.git diff --git a/src/Cryptography/HMAC.h b/src/Cryptography/HMAC.h index e5706b9..92a5bce 100644 --- a/src/Cryptography/HMAC.h +++ b/src/Cryptography/HMAC.h @@ -7,6 +7,7 @@ #include #include #include +#include namespace RNS { namespace Cryptography { diff --git a/src/Destination.h b/src/Destination.h index b5ae5f8..9fcbb9b 100644 --- a/src/Destination.h +++ b/src/Destination.h @@ -12,6 +12,7 @@ #include #include #include +#include #include namespace RNS { diff --git a/src/Filesystem.h b/src/Filesystem.h new file mode 100644 index 0000000..1c629f6 --- /dev/null +++ b/src/Filesystem.h @@ -0,0 +1,121 @@ +#pragma once + +#include "Log.h" +#include "Bytes.h" +#include "Type.h" + +#include +#include +#include +#include + +namespace RNS { + + class Filesystem { + + protected: + using HFilesystem = std::shared_ptr; + + public: + Filesystem(Type::NoneConstructor none) { + mem("Filesystem object NONE created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + } + Filesystem(const Filesystem& filesystem) : _object(filesystem._object) { + mem("Filesystem object copy created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + } + Filesystem() : _object(new Object(this)), _creator(true) { + mem("Filesystem object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + } + virtual ~Filesystem() { + if (_creator) { + mem("Filesystem object clearing parent reference, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + // clear reference to parent in object foir safety + assert(_object); + _object->_parent = nullptr; + } + mem("Filesystem object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + } + + inline Filesystem& operator = (const Filesystem& filesystem) { + _object = filesystem._object; + mem("Filesystem object copy created by assignment, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + if (_creator) { + mem("Filesystem object clearing creator flag, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + _creator = false; + } + return *this; + } + inline operator bool() const { + mem("Filesystem object bool, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + return _object.get() != nullptr; + } + inline bool operator < (const Filesystem& filesystem) const { + mem("Filesystem object <, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + return _object.get() < filesystem._object.get(); + } + inline bool operator > (const Filesystem& filesystem) const { + mem("Filesystem object <, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + return _object.get() > filesystem._object.get(); + } + inline bool operator == (const Filesystem& filesystem) const { + mem("Filesystem object ==, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + return _object.get() == filesystem._object.get(); + } + inline bool operator != (const Filesystem& filesystem) const { + mem("Filesystem object !=, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + return _object.get() != filesystem._object.get(); + } + + protected: + // CBA These should NOT be called internally, and should be protected (only to be overridden and called by Object) + virtual bool file_exists(const char* file_path) { return false; } + virtual const Bytes read_file(const char* file_path) { return {Bytes::NONE}; } + virtual bool write_file(const Bytes& data, const char* file_path) { return false; } + virtual bool remove_file(const char* file_path) { return false; } + virtual bool rename_file(const char* from_file_path, const char* to_file_path) { return false; } + virtual bool create_directory(const char* directory_path) { return false; } + + public: + inline bool do_file_exists(const char* file_path) { assert(_object); return _object->do_file_exists(file_path); } + inline const Bytes do_read_file(const char* file_path) { assert(_object); return _object->do_read_file(file_path); } + inline bool do_write_file(const Bytes& data, const char* file_path) { assert(_object); return _object->do_write_file(data, file_path); } + inline bool do_remove_file(const char* file_path) { assert(_object); return _object->do_remove_file(file_path); } + inline bool do_rename_file(const char* from_file_path, const char* to_file_path) { assert(_object); return _object->do_rename_file(from_file_path, to_file_path); } + inline bool do_create_directory(const char* directory_path) { assert(_object); return _object->do_create_directory(directory_path); } + + // getters/setters + protected: + public: + +#ifndef NDEBUG + inline std::string debugString() const { + std::string dump; + dump = "Filesystem object, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()); + return dump; + } +#endif + + private: + class Object { + public: + Object(Filesystem* parent) : _parent(parent) { mem("Filesystem::Data object created, this: " + std::to_string((uintptr_t)this)); } + Object(Filesystem* parent, const char* name) : _parent(parent) { mem("Filesystem::Data object created, this: " + std::to_string((uintptr_t)this)); } + virtual ~Object() { mem("Filesystem::Data object destroyed, this: " + std::to_string((uintptr_t)this)); } + private: + virtual inline bool do_file_exists(const char* file_path) { if (_parent == nullptr) return false; return _parent->file_exists(file_path); } + virtual inline const Bytes do_read_file(const char* file_path) { if (_parent == nullptr) return {Bytes::NONE}; return _parent->read_file(file_path); } + virtual inline bool do_write_file(const Bytes& data, const char* file_path) { if (_parent == nullptr) return false; return _parent->write_file(data, file_path); } + virtual inline bool do_remove_file(const char* file_path) { if (_parent == nullptr) return false; return _parent->remove_file(file_path); } + virtual inline bool do_rename_file(const char* from_file_path, const char* to_file_path) { if (_parent == nullptr) return false; return _parent->rename_file(from_file_path, to_file_path); } + virtual inline bool do_create_directory(const char* directory_path) { if (_parent == nullptr) return false; return _parent->create_directory(directory_path); } + private: + Filesystem* _parent = nullptr; + friend class Filesystem; + }; + std::shared_ptr _object; + bool _creator = false; + + friend class OS; + }; + +} diff --git a/src/Identity.h b/src/Identity.h index 3f9444a..6ff5f41 100644 --- a/src/Identity.h +++ b/src/Identity.h @@ -11,6 +11,7 @@ #include #include #include +#include namespace RNS { diff --git a/src/Interface.h b/src/Interface.h index 054204b..a79bea0 100644 --- a/src/Interface.h +++ b/src/Interface.h @@ -8,6 +8,7 @@ #include #include +#include #include namespace RNS { @@ -97,7 +98,7 @@ namespace RNS { inline void add_announce(AnnounceEntry& entry) { assert(_object); _object->_announce_queue.push_back(entry); } protected: - // CBA TODO these should NOT called internally, and should likely be protected (only to be overridden and called by Object) + // CBA These should NOT be called internally, and should be protected (only to be overridden and called by Object) virtual void on_incoming(const Bytes& data); virtual void on_outgoing(const Bytes& data); diff --git a/src/Link.h b/src/Link.h index a9fc80e..9edca37 100644 --- a/src/Link.h +++ b/src/Link.h @@ -5,6 +5,7 @@ #include "Type.h" #include +#include namespace RNS { diff --git a/src/Packet.h b/src/Packet.h index 9ab1324..5cd089b 100644 --- a/src/Packet.h +++ b/src/Packet.h @@ -9,6 +9,7 @@ #include "Utilities/OS.h" #include +#include #include #include diff --git a/src/Reticulum.cpp b/src/Reticulum.cpp index 6ce2619..299066c 100644 --- a/src/Reticulum.cpp +++ b/src/Reticulum.cpp @@ -41,8 +41,6 @@ Reticulum::Reticulum() : _object(new Object()) { // Initialkize random number generator RNG.begin("Reticulum"); - Utilities::OS::setup(); - #ifdef ARDUINO // Stir in the Ethernet MAC address. //byte mac[6]; diff --git a/src/Reticulum.h b/src/Reticulum.h index eed18b7..cfe12ab 100644 --- a/src/Reticulum.h +++ b/src/Reticulum.h @@ -6,6 +6,7 @@ #include #include #include +#include #include namespace RNS { diff --git a/src/Test/TestPersistence.cpp b/src/Test/TestPersistence.cpp index c560ea4..faf9320 100644 --- a/src/Test/TestPersistence.cpp +++ b/src/Test/TestPersistence.cpp @@ -1,9 +1,9 @@ //#include +#include "Interface.h" #include "Transport.h" #include "Log.h" #include "Bytes.h" -#include "Interfaces/LoRaInterface.h" #include "Utilities/OS.h" #include "Utilities/Persistence.h" @@ -18,6 +18,27 @@ #include +class TestInterface : public RNS::Interface { + +public: + TestInterface(const char* name = "TestInterface") : Interface(name) {} + virtual ~TestInterface() {} + + virtual inline std::string toString() const { return "TestInterface[" + name() + "]"; } + +private: + virtual void on_incoming(const RNS::Bytes& data) { + RNS::debug(toString() + ".on_incoming: data: " + data.toHex()); + Interface::on_incoming(data); + } + virtual void on_outgoing(const RNS::Bytes& data) { + RNS::debug(toString() + ".on_outgoing: data: " + data.toHex()); + Interface::on_outgoing(data); + } + +}; + + class TestObject { public: TestObject() {} @@ -28,6 +49,7 @@ public: std::vector _vec; }; + namespace ArduinoJson { // ArduinoJSON serialization support for TestObject template <> @@ -523,7 +545,7 @@ void testSerializeDestinationTable() { //RNS::Bytes empty; //std::set blobs; //RNS::Interface interface({RNS::Type::NONE}); - RNS::Interfaces::LoRaInterface lora_interface; + TestInterface test_interface; //RNS::Packet packet({RNS::Type::NONE}); static std::map map; //DestinationEntry(double time, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set& random_blobs, Interface& receiving_interface, const Packet& packet) : @@ -536,7 +558,7 @@ void testSerializeDestinationTable() { RNS::Transport::DestinationEntry entry_one; entry_one._timestamp = 1.0; entry_one._received_from = received; - entry_one._receiving_interface = lora_interface; + entry_one._receiving_interface = test_interface; entry_one._random_blobs = blobs; RNS::Bytes one; one.assignHex("1111111111111111"); @@ -545,7 +567,7 @@ void testSerializeDestinationTable() { RNS::Transport::DestinationEntry entry_two; entry_two._timestamp = 2.0; entry_two._received_from = received; - entry_two._receiving_interface = lora_interface; + entry_two._receiving_interface = test_interface; entry_two._random_blobs = blobs; RNS::Bytes two; two.assignHex("2222222222222222"); diff --git a/src/Transport.cpp b/src/Transport.cpp index 85eab95..bea7fd8 100644 --- a/src/Transport.cpp +++ b/src/Transport.cpp @@ -91,19 +91,25 @@ using namespace RNS::Utilities; if (!_identity) { std::string transport_identity_path = Reticulum::_storagepath + "/transport_identity"; + debug("Checking for transport identity..."); + try { // CBA TEST //OS::remove_file(transport_identity_path.c_str()); - if (OS::file_exists(transport_identity_path.c_str())) { - _identity = Identity::from_file(transport_identity_path.c_str()); - } + if (OS::file_exists(transport_identity_path.c_str())) { + _identity = Identity::from_file(transport_identity_path.c_str()); + } - if (!_identity) { - verbose("No valid Transport Identity in storage, creating..."); - _identity = Identity(); - _identity.to_file(transport_identity_path.c_str()); + if (!_identity) { + verbose("No valid Transport Identity in storage, creating..."); + _identity = Identity(); + _identity.to_file(transport_identity_path.c_str()); + } + else { + verbose("Loaded Transport Identity from storage"); + } } - else { - verbose("Loaded Transport Identity from storage"); + catch (std::exception& e) { + error("Failed to check for transport identity, the contained exception was: " + std::string(e.what())); } } @@ -118,7 +124,7 @@ using namespace RNS::Utilities; file.close(); } catch (std::exception& e) { - error("Could not load packet hashlist from storage, the contained exception was: " + e.what()); + error("Could not load packet hashlist from storage, the contained exception was: " + std::string(e.what())); } } } diff --git a/src/Utilities/OS.cpp b/src/Utilities/OS.cpp index 4fbef9c..9d4743e 100644 --- a/src/Utilities/OS.cpp +++ b/src/Utilities/OS.cpp @@ -2,182 +2,61 @@ #include "../Log.h" -#ifdef ARDUINO -#include -#include -#else -#include -#include -#include -#include -#endif - using namespace RNS; using namespace RNS::Utilities; -#ifdef ARDUINO -void listDir(char * dir){ - Serial.print("DIR: "); - Serial.println(dir); - File root = SPIFFS.open(dir); - File file = root.openNextFile(); - while(file){ - Serial.print(" FILE: "); - Serial.println(file.name()); - file = root.openNextFile(); - } +/*static*/ Filesystem OS::filesystem = {Type::NONE}; + +/*static*/ void OS::register_filesystem(Filesystem& filesystem) { + extreme("Registering filesystem......"); + OS::filesystem = filesystem; } -#endif - -/*static*/ void OS::setup() { - -#ifdef ARDUINO - // Setup filesystem - if (!SPIFFS.begin(true, "")){ - error("SPIFFS filesystem mount failed"); - } - else { - uint32_t size = SPIFFS.totalBytes() / (1024 * 1024); - Serial.print("size: "); - Serial.print(size); - Serial.println(" MB"); - uint32_t used = SPIFFS.usedBytes() / (1024 * 1024); - Serial.print("used: "); - Serial.print(used); - Serial.println(" MB"); - // ensure filesystem is writable and format if not - Bytes test; - if (!OS::write_file(test, "/test")) { - info("SPIFFS filesystem is being formatted, please wait..."); - SPIFFS.format(); - } - else { - OS::remove_file("/test"); - } - listDir("/"); - debug("SPIFFS filesystem is ready"); - } -#endif +/*static*/ void OS::deregister_filesystem() { + extreme("Deregistering filesystem......"); + OS::filesystem = {Type::NONE}; } /*static*/ bool OS::file_exists(const char* file_path) { -#ifdef ARDUINO - File file = SPIFFS.open(file_path, FILE_READ); - if (file) { -#else - FILE* file = fopen(file_path, "r"); - if (file != nullptr) { -#endif - //extreme("file_exists: file exists, closing file"); -#ifdef ARDUINO - file.close(); -#else - fclose(file); -#endif - return true; - } - else { - error("file_exists: failed to open file " + std::string(file_path)); - return false; + extreme("file_exists: checking for filesystem"); + if (!filesystem) { + warning("file_exists: filesystem not registered"); + throw std::runtime_error("Filesystem has not been registered"); } + return filesystem.do_file_exists(file_path); } /*static*/ const Bytes OS::read_file(const char* file_path) { - Bytes data; -#ifdef ARDUINO - File file = SPIFFS.open(file_path, FILE_READ); - if (file) { - size_t size = file.size(); - size_t read = file.readBytes((char*)data.writable(size), size); -#else - FILE* file = fopen(file_path, "r"); - if (file != nullptr) { - fseek(file, 0, SEEK_END); - size_t size = ftell(file); - rewind(file); - //size_t read = fread(data.writable(size), size, 1, file); - size_t read = fread(data.writable(size), 1, size, file); -#endif - extreme("read_file: read " + std::to_string(read) + " bytes from file " + std::string(file_path)); - if (read != size) { - error("read_file: failed to read file " + std::string(file_path)); - data.clear(); - } - //extreme("read_file: closing input file"); -#ifdef ARDUINO - file.close(); -#else - fclose(file); -#endif + if (!filesystem) { + throw std::runtime_error("Filesystem has not been registered"); } - else { - error("read_file: failed to open input file " + std::string(file_path)); - } - return data; + return filesystem.do_read_file(file_path); } /*static*/ bool OS::write_file(const Bytes& data, const char* file_path) { - bool success = false; -#ifdef ARDUINO - File file = SPIFFS.open(file_path, FILE_WRITE); - if (file) { - size_t wrote = file.write(data.data(), data.size()); -#else - FILE* file = fopen(file_path, "w"); - if (file != nullptr) { - //size_t wrote = fwrite(data.data(), data.size(), 1, file); - size_t wrote = fwrite(data.data(), 1, data.size(), file); -#endif - extreme("write_file: wrote " + std::to_string(wrote) + " bytes to file " + std::string(file_path)); - if (wrote == data.size()) { - success = true; - } - else { - error("write_file: failed to write file " + std::string(file_path)); - } - //extreme("write_file: closing output file"); -#ifdef ARDUINO - file.close(); -#else - fclose(file); -#endif + if (!filesystem) { + throw std::runtime_error("Filesystem has not been registered"); } - else { - error("write_file: failed to open output file " + std::string(file_path)); - } - return success; + return filesystem.do_write_file(data, file_path); } /*static*/ bool OS::remove_file(const char* file_path) { -#ifdef ARDUINO - return SPIFFS.remove(file_path); -#else - return (remove(file_path) == 0); -#endif + if (!filesystem) { + throw std::runtime_error("Filesystem has not been registered"); + } + return filesystem.do_remove_file(file_path); } /*static*/ bool OS::rename_file(const char* from_file_path, const char* to_file_path) { -#ifdef ARDUINO - return SPIFFS.rename(from_file_path, to_file_path); -#else - return (rename(from_file_path, to_file_path) == 0); -#endif + if (!filesystem) { + throw std::runtime_error("Filesystem has not been registered"); + } + return filesystem.do_rename_file(from_file_path, to_file_path); } /*static*/ bool OS::create_directory(const char* directory_path) { -#ifdef ARDUINO - if (SPIFFS.mkdir(directory_path)) { - return true; + if (!filesystem) { + throw std::runtime_error("Filesystem has not been registered"); } - else { - error("create_directory: failed to create directorty " + std::string(directory_path)); - } -#else - struct stat st = {0}; - if (stat(directory_path, &st) == 0) { - return true; - } - return (mkdir(directory_path, 0700) == 0); -#endif + return filesystem.do_create_directory(directory_path); } diff --git a/src/Utilities/OS.h b/src/Utilities/OS.h index f1dff16..cc38034 100644 --- a/src/Utilities/OS.h +++ b/src/Utilities/OS.h @@ -1,5 +1,6 @@ #pragma once +#include "../Filesystem.h" #include "../Bytes.h" #include @@ -12,13 +13,16 @@ #include #endif +#undef round + namespace RNS { namespace Utilities { class OS { - public: - static void setup(); + private: + static Filesystem filesystem; + public: // sleep for specified milliseconds //static inline void sleep(float seconds) { ::sleep(seconds); } #ifdef ARDUINO @@ -35,8 +39,12 @@ namespace RNS { namespace Utilities { static inline double time() { timeval time; ::gettimeofday(&time, NULL); return (double)time.tv_sec + ((double)time.tv_usec / 1000000); } // round decimal number to specified precision - //static inline float round(float value, uint8_t precision) { return std::round(value / precision) * precision; } - static inline double round(double value, uint8_t precision) { return std::round(value / precision) * precision; } + //static inline float round(float value, uint8_t precision) { return std::round(value / precision) * precision; } + //static inline double round(double value, uint8_t precision) { return std::round(value / precision) * precision; } + static inline double round(double value, uint8_t precision) { return std::round(value / precision) * precision; } + + static void register_filesystem(Filesystem& filesystem); + static void deregister_filesystem(); static bool file_exists(const char* file_path); static const RNS::Bytes read_file(const char* file_path);