From fcfda6636513bb75a61f6498f4762d6f042d9255 Mon Sep 17 00:00:00 2001 From: Chad Attermann Date: Wed, 14 Aug 2024 21:59:23 -0600 Subject: [PATCH] WIP: General improvements in persistence efficiency --- .../test/{Filesystem.cpp => FileSystem.cpp} | 238 ++++++++---- examples/test/FileSystem.h | 184 +++++++++ examples/test/Filesystem.h | 27 -- examples/test/Test.cpp | 2 +- examples/test/Test.h | 2 +- examples/test/TestBytes.cpp | 25 +- examples/test/TestCrypto.cpp | 129 ++++++- examples/test/TestFilesystem.cpp | 187 +++++++-- examples/test/TestOS.cpp | 22 ++ examples/test/TestPersistence.cpp | 144 +++++-- examples/test/TestReticulum.cpp | 69 +--- examples/test/main.cpp | 15 +- examples/test/platformio.ini | 29 +- examples/test/test_destination_table | 2 +- platformio.ini | 1 + src/Bytes.cpp | 29 +- src/Bytes.h | 21 +- src/FileStream.h | 144 +++++++ src/FileSystem.h | 125 +++++++ src/Filesystem.h | 142 ------- src/Identity.cpp | 3 +- src/Interface.cpp | 51 +-- src/Interface.h | 217 +++++------ src/Transport.cpp | 92 +++-- src/Transport.h | 3 +- src/Type.h | 14 +- src/Utilities/Crc.cpp | 16 + src/Utilities/Crc.h | 17 + src/Utilities/OS.cpp | 106 +----- src/Utilities/OS.h | 116 +++++- src/Utilities/Persistence.h | 332 ++++++++++++++-- src/Utilities/Print.cpp | 354 ++++++++++++++++++ src/Utilities/Print.h | 114 ++++++ src/Utilities/Stream.cpp | 339 +++++++++++++++++ src/Utilities/Stream.h | 143 +++++++ test/Test.cpp | 90 ----- 36 files changed, 2754 insertions(+), 790 deletions(-) rename examples/test/{Filesystem.cpp => FileSystem.cpp} (64%) create mode 100644 examples/test/FileSystem.h delete mode 100644 examples/test/Filesystem.h create mode 100644 src/FileStream.h create mode 100644 src/FileSystem.h delete mode 100644 src/Filesystem.h create mode 100644 src/Utilities/Crc.cpp create mode 100644 src/Utilities/Crc.h create mode 100644 src/Utilities/Print.cpp create mode 100644 src/Utilities/Print.h create mode 100644 src/Utilities/Stream.cpp create mode 100644 src/Utilities/Stream.h delete mode 100644 test/Test.cpp diff --git a/examples/test/Filesystem.cpp b/examples/test/FileSystem.cpp similarity index 64% rename from examples/test/Filesystem.cpp rename to examples/test/FileSystem.cpp index e3a5574..ecc741d 100644 --- a/examples/test/Filesystem.cpp +++ b/examples/test/FileSystem.cpp @@ -1,26 +1,49 @@ -#include "Filesystem.h" +#include "FileSystem.h" #include #include -#ifdef ARDUINO -#ifdef BOARD_ESP32 -//#include -#include -#elif BOARD_NRF52 -//#include -#include -using namespace Adafruit_LittleFS_Namespace; -#endif -#else -#include -#include -#include -#include -#endif +bool FileSystem::init() { + TRACE("FileSystem initializing..."); #ifdef ARDUINO -void Filesystem::listDir(const char* dir) { +#ifdef BOARD_ESP32 + // Setup FileSystem + INFO("SPIFFS mounting FileSystem"); + if (!SPIFFS.begin(true, "")){ + ERROR("SPIFFS FileSystem mount failed"); + return false; + } + 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 + RNS::Bytes test("test"); + if (write_file("/test", test) < 4) { + INFO("SPIFFS FileSystem is being formatted, please wait..."); + SPIFFS.format(); + } + else { + remove_file("/test"); + } + DEBUG("SPIFFS FileSystem is ready"); +#elif BOARD_NRF52 + // Initialize Internal File System + INFO("InternalFS mounting FileSystem"); + InternalFS.begin(); + INFO("InternalFS FileSystem is ready"); +#endif +#endif + return true; +} + +#ifdef ARDUINO +void FileSystem::listDir(const char* dir) { Serial.print("DIR: "); Serial.println(dir); #ifdef BOARD_ESP32 @@ -64,50 +87,11 @@ void Filesystem::listDir(const char* dir) { #endif } #else -void Filesystem::listDir(const char* dir) { +void FileSystem::listDir(const char* dir) { } #endif -bool Filesystem::init() { - TRACE("Filesystem initializing..."); - -#ifdef ARDUINO -#ifdef BOARD_ESP32 - // Setup filesystem - INFO("SPIFFS mounting filesystem"); - if (!SPIFFS.begin(true, "")){ - ERROR("SPIFFS filesystem mount failed"); - return false; - } - 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 - RNS::Bytes test("test"); - if (write_file("/test", test) < 4) { - INFO("SPIFFS filesystem is being formatted, please wait..."); - SPIFFS.format(); - } - else { - remove_file("/test"); - } - DEBUG("SPIFFS filesystem is ready"); -#elif BOARD_NRF52 - // Initialize Internal File System - INFO("InternalFS mounting filesystem"); - InternalFS.begin(); - INFO("InternalFS filesystem is ready"); -#endif -#endif - return true; -} - -/*virtual*/ bool Filesystem::file_exists(const char* file_path) { +/*virtual*/ bool FileSystem::file_exists(const char* file_path) { #ifdef ARDUINO #ifdef BOARD_ESP32 File file = SPIFFS.open(file_path, FILE_READ); @@ -142,7 +126,7 @@ bool Filesystem::init() { } } -/*virtual*/ size_t Filesystem::read_file(const char* file_path, RNS::Bytes& data) { +/*virtual*/ size_t FileSystem::read_file(const char* file_path, RNS::Bytes& data) { size_t read = 0; #ifdef ARDUINO #ifdef BOARD_ESP32 @@ -151,8 +135,10 @@ bool Filesystem::init() { size_t size = file.size(); read = file.readBytes((char*)data.writable(size), size); #elif BOARD_NRF52 - File file(InternalFS); - if (file.open(file_path, FILE_O_READ)) { + //File file(InternalFS); + //if (file.open(file_path, FILE_O_READ)) { + File file = InternalFS.open(file_path, FILE_O_READ); + if (file) { size_t size = file.size(); read = file.readBytes((char*)data.writable(size), size); #else @@ -167,7 +153,7 @@ bool Filesystem::init() { 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); + read = fread(data.writable(size), 1, size, file); #endif TRACE("read_file: read " + std::to_string(read) + " bytes from file " + std::string(file_path)); if (read != size) { @@ -192,7 +178,7 @@ bool Filesystem::init() { return read; } -/*virtual*/ size_t Filesystem::write_file(const char* file_path, const RNS::Bytes& data) { +/*virtual*/ size_t FileSystem::write_file(const char* file_path, const RNS::Bytes& data) { // CBA TODO Replace remove with working truncation remove_file(file_path); size_t wrote = 0; @@ -213,7 +199,7 @@ bool Filesystem::init() { 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); + wrote = fwrite(data.data(), 1, data.size(), file); #endif TRACE("write_file: wrote " + std::to_string(wrote) + " bytes to file " + std::string(file_path)); if (wrote < data.size()) { @@ -237,7 +223,101 @@ bool Filesystem::init() { return wrote; } -/*virtual*/ bool Filesystem::remove_file(const char* file_path) { +/*virtual*/ RNS::FileStream FileSystem::open_file(const char* file_path, RNS::FileStream::MODE file_mode) { + TRACEF("open_file: opening file %s", file_path); +#ifdef ARDUINO +#ifdef BOARD_ESP32 + const char* mode; + if (file_mode == RNS::FileStream::MODE_READ) { + mode = FILE_READ; + } + else if (file_mode == RNS::FileStream::MODE_WRITE) { + mode = FILE_WRITE; + } + else if (file_mode == RNS::FileStream::MODE_APPEND) { + mode = FILE_APPEND; + } + else { + ERRORF("open_file: unsupported mode %d", file_mode); + return {RNS::Type::NONE}; + } + TRACEF("open_file: opening file %s in mode %s", file_path, mode); + //// Using copy constructor to create a File* instead of local + //File file = SPIFFS.open(file_path, mode); + //if (!file) { + File* file = new File(SPIFFS.open(file_path, mode)); + if (file == null || !(*file)) { + ERRORF("open_file: failed to open output file %s", file_path); + return {RNS::Type::NONE}; + } + TRACEF("open_file: successfully opened file %s", file_path); + return RNS::FileStream(new FileStreamImpl(file)); +#elif BOARD_NRF52 + //File file = File(InternalFS); + File* file = new File(InternalFS); + int mode; + if (file_mode == RNS::FileStream::MODE_READ) { + mode = FILE_O_READ; + } + else if (file_mode == RNS::FileStream::MODE_WRITE) { + mode = FILE_O_WRITE; + // CBA TODO Replace remove with working truncation + if (InternalFS.exists(file_path)) { + InternalFS.remove(file_path); + } + } + else if (file_mode == RNS::FileStream::MODE_APPEND) { + // CBA This is the default write mode for nrf52 littlefs + mode = FILE_O_WRITE; + } + else { + ERRORF("open_file: unsupported mode %d", file_mode); + return {RNS::Type::NONE}; + } + if (!file->open(file_path, mode)) { + ERRORF("open_file: failed to open output file %s", file_path); + return {RNS::Type::NONE}; + } + + // Seek to beginning to overwrite (this is failing on nrf52) + //if (file_mode == RNS::FileStream::MODE_WRITE) { + // file->seek(0); + // file->truncate(0); + //} + TRACEF("open_file: successfully opened file %s", file_path); + return RNS::FileStream(new FileStreamImpl(file)); +#else + #warning("unsuppoprted"); + return RNS::FileStream(RNS::Type::NONE); +#endif +#else // ARDUINO + // Native + const char* mode; + if (file_mode == RNS::FileStream::MODE_READ) { + mode = "r"; + } + else if (file_mode == RNS::FileStream::MODE_WRITE) { + mode = "w"; + } + else if (file_mode == RNS::FileStream::MODE_APPEND) { + mode = "a"; + } + else { + ERRORF("open_file: unsupported mode %d", file_mode); + return {RNS::Type::NONE}; + } + TRACEF("open_file: opening file %s in mode %s", file_path, mode); + FILE* file = fopen(file_path, mode); + if (file == nullptr) { + ERRORF("open_file: failed to open output file %s", file_path); + return {RNS::Type::NONE}; + } + TRACEF("open_file: successfully opened file %s", file_path); + return RNS::FileStream(new FileStreamImpl(file)); +#endif +} + +/*virtual*/ bool FileSystem::remove_file(const char* file_path) { #ifdef ARDUINO #ifdef BOARD_ESP32 return SPIFFS.remove(file_path); @@ -252,7 +332,7 @@ bool Filesystem::init() { #endif } -/*virtual*/ bool Filesystem::rename_file(const char* from_file_path, const char* to_file_path) { +/*virtual*/ bool FileSystem::rename_file(const char* from_file_path, const char* to_file_path) { #ifdef ARDUINO #ifdef BOARD_ESP32 return SPIFFS.rename(from_file_path, to_file_path); @@ -267,7 +347,7 @@ bool Filesystem::init() { #endif } -/*virtua*/ bool Filesystem::directory_exists(const char* directory_path) { +/*virtua*/ bool FileSystem::directory_exists(const char* directory_path) { TRACE("directory_exists: checking for existence of directory " + std::string(directory_path)); #ifdef ARDUINO #ifdef BOARD_ESP32 @@ -298,7 +378,7 @@ bool Filesystem::init() { #endif } -/*virtual*/ bool Filesystem::create_directory(const char* directory_path) { +/*virtual*/ bool FileSystem::create_directory(const char* directory_path) { #ifdef ARDUINO #ifdef BOARD_ESP32 if (!SPIFFS.mkdir(directory_path)) { @@ -325,7 +405,7 @@ bool Filesystem::init() { #endif } -/*virtua*/ bool Filesystem::remove_directory(const char* directory_path) { +/*virtua*/ bool FileSystem::remove_directory(const char* directory_path) { TRACE("remove_directory: removing directory " + std::string(directory_path)); #ifdef ARDUINO #ifdef BOARD_ESP32 @@ -350,7 +430,7 @@ bool Filesystem::init() { #endif } -/*virtua*/ std::list Filesystem::list_directory(const char* directory_path) { +/*virtua*/ std::list FileSystem::list_directory(const char* directory_path) { TRACE("list_directory: listing directory " + std::string(directory_path)); std::list files; #ifdef ARDUINO @@ -387,11 +467,11 @@ bool Filesystem::init() { #ifdef BOARD_ESP32 -/*virtual*/ size_t Filesystem::storage_size() { +/*virtual*/ size_t FileSystem::storage_size() { return SPIFFS.totalBytes(); } -/*virtual*/ size_t Filesystem::storage_available() { +/*virtual*/ size_t FileSystem::storage_available() { return (SPIFFS.totalBytes() - SPIFFS.usedBytes()); } @@ -420,23 +500,25 @@ static int usedBytes() { return config->block_size * usedBlockCount; } -/*virtual*/ size_t Filesystem::storage_size() { - return totalBytes(); +/*virtual*/ size_t FileSystem::storage_size() { + //return totalBytes(); + return InternalFS.totalBytes(); } -/*virtual*/ size_t Filesystem::storage_available() { - return (totalBytes() - usedBytes()); +/*virtual*/ size_t FileSystem::storage_available() { + //return (totalBytes() - usedBytes()); + return (InternalFS.totalBytes() - InternalFS.usedBytes()); } #endif #else -/*virtual*/ size_t Filesystem::storage_size() { +/*virtual*/ size_t FileSystem::storage_size() { return 0; } -/*virtual*/ size_t Filesystem::storage_available() { +/*virtual*/ size_t FileSystem::storage_available() { return 0; } diff --git a/examples/test/FileSystem.h b/examples/test/FileSystem.h new file mode 100644 index 0000000..b696371 --- /dev/null +++ b/examples/test/FileSystem.h @@ -0,0 +1,184 @@ +#pragma once + +#include +#include +#include + +#ifdef ARDUINO +#ifdef BOARD_ESP32 +//#include +#include +#elif BOARD_NRF52 +//#include +#include +using namespace Adafruit_LittleFS_Namespace; +#endif +#else +#include +#include +#include +#include +#include +#include +#endif + +class FileSystem : public RNS::FileSystemImpl { + +public: + FileSystem() {} + + bool init(); + +public: + static void listDir(const char* dir); + +public: + virtual bool file_exists(const char* file_path); + virtual size_t read_file(const char* file_path, RNS::Bytes& data); + virtual size_t write_file(const char* file_path, const RNS::Bytes& data); + virtual RNS::FileStream open_file(const char* file_path, RNS::FileStream::MODE file_mode); + virtual bool remove_file(const char* file_path); + virtual bool rename_file(const char* from_file_path, const char* to_file_path); + virtual bool directory_exists(const char* directory_path); + virtual bool create_directory(const char* directory_path); + virtual bool remove_directory(const char* directory_path); + virtual std::list list_directory(const char* directory_path); + virtual size_t storage_size(); + virtual size_t storage_available(); + +protected: + +#if defined(BOARD_ESP32) || defined(BOARD_NRF52) + class FileStreamImpl : public RNS::FileStreamImpl { + + private: + std::unique_ptr _file; + bool _closed = false; + + public: + FileStreamImpl(File* file) : RNS::FileStreamImpl(), _file(file) {} + virtual ~FileStreamImpl() { if (!_closed) close(); } + + public: + inline virtual const char* name() { return _file->name(); } + inline virtual size_t size() { return _file->size(); } + inline virtual void close() { _closed = true; _file->close(); } + + // Print overrides + inline virtual size_t write(uint8_t byte) { return _file->write(byte); } + inline virtual size_t write(const uint8_t *buffer, size_t size) { return _file->write(buffer, size); } + + // Stream overrides + inline virtual int available() { return _file->available(); } + inline virtual int read() { return _file->read(); } + inline virtual int peek() { return _file->peek(); } + inline virtual void flush() { _file->flush(); } + + }; +#else + class FileStreamImpl : public RNS::FileStreamImpl { + + private: + FILE* _file = nullptr; + bool _closed = false; + size_t _available = 0; + char _filename[1024]; + + public: + FileStreamImpl(FILE* file) : RNS::FileStreamImpl(), _file(file) { + _available = size(); + } + virtual ~FileStreamImpl() { if (!_closed) close(); } + + public: + inline virtual const char* name() { + assert(_file); +#if 0 + char proclnk[1024]; + snprintf(proclnk, sizeof(proclnk), "/proc/self/fd/%d", fileno(_file)); + int r = readlink(proclnk, _filename, sizeof(_filename)); + if (r < 0) { + return nullptr); + } + _filename[r] = '\0'; + return _filename; +#elif 0 + if (fcntl(fd, F_GETPATH, _filename) < 0) { + rerturn nullptr; + } + return _filename; +#else + return nullptr; +#endif + } + inline virtual size_t size() { + assert(_file); + struct stat st; + fstat(fileno(_file), &st); + return st.st_size; + } + inline virtual void close() { + assert(_file); + _closed = true; + fclose(_file); + _file = nullptr; + } + + // Print overrides + inline virtual size_t write(uint8_t byte) { + assert(_file); + int ch = fputc(byte, _file); + if (ch == EOF) { + return 0; + } + ++_available; + return 1; + } + inline virtual size_t write(const uint8_t *buffer, size_t size) { + assert(_file); + size_t wrote = fwrite(buffer, sizeof(uint8_t), size, _file); + _available += wrote; + return wrote; + } + + // Stream overrides + inline virtual int available() { +#if 0 + assert(_file); + int size = 0; + ioctl(fileno(_file), FIONREAD, &size); + TRACEF("FileStream::available: %d", size); + return size; +#else + return _available; +#endif + } + inline virtual int read() { + if (_available <= 0) { + return EOF; + } + assert(_file); + int ch = fgetc(_file); + TRACEF("FileStream::read: %c", ch); + return ch; + } + inline virtual int peek() { + if (_available <= 0) { + return EOF; + } + assert(_file); + int ch = fgetc(_file); + ungetc(ch, _file); + TRACEF("FileStream::peek: %c", ch); + return ch; + } + inline virtual void flush() { + assert(_file); + fflush(_file); + TRACE("FileStream::flush"); + } + + }; +#endif + +}; diff --git a/examples/test/Filesystem.h b/examples/test/Filesystem.h deleted file mode 100644 index b877708..0000000 --- a/examples/test/Filesystem.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include -#include - -class Filesystem : public RNS::Filesystem { - -public: - bool init(); - -public: - static void listDir(const char* dir); - -protected: - virtual bool file_exists(const char* file_path); - virtual size_t read_file(const char* file_path, RNS::Bytes& data); - virtual size_t write_file(const char* file_path, const RNS::Bytes& data); - virtual bool remove_file(const char* file_path); - virtual bool rename_file(const char* from_file_path, const char* to_file_path); - virtual bool directory_exists(const char* directory_path); - virtual bool create_directory(const char* directory_path); - virtual bool remove_directory(const char* directory_path); - virtual std::list list_directory(const char* directory_path); - virtual size_t storage_size(); - virtual size_t storage_available(); - -}; diff --git a/examples/test/Test.cpp b/examples/test/Test.cpp index 16bcb93..bb6aa1a 100644 --- a/examples/test/Test.cpp +++ b/examples/test/Test.cpp @@ -8,7 +8,7 @@ void test() { testReference(); testCrypto(); testPersistence(); - testFilesystem(); + testFileSystem(); testReticulum(); } diff --git a/examples/test/Test.h b/examples/test/Test.h index 34a631f..36fb73c 100644 --- a/examples/test/Test.h +++ b/examples/test/Test.h @@ -7,5 +7,5 @@ void testCollections(); void testReference(); void testCrypto(); void testPersistence(); -void testFilesystem(); +void testFileSystem(); void testReticulum(); diff --git a/examples/test/TestBytes.cpp b/examples/test/TestBytes.cpp index 96ae45b..a784e40 100644 --- a/examples/test/TestBytes.cpp +++ b/examples/test/TestBytes.cpp @@ -433,6 +433,18 @@ void testBytesReserve() { } +void testFind() { + RNS::Bytes src("Hello"); + assert(0 == src.find("H")); + assert(-1 == src.find(1, "H")); + assert(2 == src.find("ll")); + assert(2 == src.find(1, "ll")); + assert(2 == src.find(2, "ll")); + assert(-1 == src.find(3, "ll")); + assert(-1 == src.find(32, "ll")); + assert(-1 == src.find("foo")); +} + void testBytes() { HEAD("Running testBytes...", RNS::LOG_TRACE); @@ -441,12 +453,13 @@ void testBytes() { size_t pre_memory = RNS::Utilities::OS::heap_available(); TRACEF("testBytes: pre-mem: %u", pre_memory); - //testBytesMain(); - //testCowBytes(); - //testBytesConversion(); - //testBytesResize(); - //testBytesStream(); + testBytesMain(); + testCowBytes(); + testBytesConversion(); + testBytesResize(); + testBytesStream(); testBytesReserve(); + testFind(); size_t post_memory = RNS::Utilities::OS::heap_available(); size_t diff_memory = (int)pre_memory - (int)post_memory; @@ -454,7 +467,9 @@ void testBytes() { TRACEF("testBytes: diff-mem: %u", diff_memory); assert(diff_memory == 0); +#if defined(RNS_USE_ALLOCATOR) RNS::Utilities::OS::dump_allocator_stats(); +#endif RNS::Utilities::OS::dump_heap_stats(); } diff --git a/examples/test/TestCrypto.cpp b/examples/test/TestCrypto.cpp index 24a641f..ff4dce2 100644 --- a/examples/test/TestCrypto.cpp +++ b/examples/test/TestCrypto.cpp @@ -6,13 +6,20 @@ #include "Packet.h" #include "Bytes.h" #include "Log.h" +#include "Utilities/Crc.h" #include "Cryptography/HMAC.h" #include "Cryptography/PKCS7.h" #include +// Imported from Crypto.cpp +// Computes CRC-8/HITAG checksum +// CBA Doesn't appeart to support incremental checksum building +extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); + void testCryptoMain() { + HEAD("testCryptoMain", RNS::LOG_TRACE); RNS::Reticulum reticulum_crypto; assert(reticulum_crypto); @@ -30,6 +37,7 @@ void testCryptoMain() { } void testHMAC() { + HEAD("testHMAC", RNS::LOG_TRACE); { const char keystr[] = "key"; @@ -43,16 +51,17 @@ void testHMAC() { RNS::Bytes key(keystr); RNS::Bytes data(datastr); RNS::Bytes hash(hasharr, sizeof(hasharr)); - TRACE("expected hash: " + hash.toHex()); + TRACEF("expected hash: %s", hash.toHex().c_str()); RNS::Cryptography::HMAC hmac(key, data); RNS::Bytes result = hmac.digest(); - TRACE("result hash: " + result.toHex()); + TRACEF("result hash: %s", result.toHex().c_str()); assert(memcmp(hash.data(), result.data(), result.size()) == 0); } } void testPKCS7() { - + HEAD("testPKCS7", RNS::LOG_TRACE); + const uint8_t str[] = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; // test buffer of half blocksize @@ -128,11 +137,123 @@ void testPKCS7() { } } +void testCrc8() { + HEAD("testCrc8", RNS::LOG_TRACE); + + char data[16]; + uint8_t crc; + + strcpy(data, "foo"); + crc = crypto_crc8(0, data, strlen(data)); + TRACEF("crc1: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0x48, crc); + assert(0x48 == crc); + + strcpy(data, "bar"); + crc = crypto_crc8(0, data, strlen(data)); + TRACEF("crc2: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0xED, crc); + assert(0xED == crc); + + strcpy(data, "foo"); + crc = crypto_crc8(0, data, strlen(data)); + TRACEF("crc3: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0x48, crc); + assert(0x48 == crc); + + strcpy(data, "foobarfoo"); + crc = crypto_crc8(0, data, strlen(data)); + TRACEF("crc4: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0x00, crc); + assert(0x00 == crc); +} + +void testCrc32() { + HEAD("testCrc32", RNS::LOG_TRACE); + + char data[16]; + uint32_t crc; + + strcpy(data, "foo"); + crc = RNS::Utilities::Crc::crc32(0, data); + TRACEF("crc1: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0x8C736521, crc); + assert(0x8C736521 == crc); + + strcpy(data, "bar"); + crc = RNS::Utilities::Crc::crc32(0, data); + TRACEF("crc2: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0x76FF8CAA, crc); + assert(0x76FF8CAA == crc); + + strcpy(data, "foo"); + crc = RNS::Utilities::Crc::crc32(0, data); + TRACEF("crc3: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0x8C736521, crc); + assert(0x8C736521 == crc); + + strcpy(data, "foobarfoo"); + crc = RNS::Utilities::Crc::crc32(0, data); + TRACEF("crc4: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0xEE2F4613, crc); + assert(0xEE2F4613 == crc); +} + +void testIncrementalCrc32() { + HEAD("testIncrementalCrc32", RNS::LOG_TRACE); + + char data[16]; + uint32_t crc; + + strcpy(data, "foo"); + crc = RNS::Utilities::Crc::crc32(0, data); + TRACEF("crc1: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0x8C736521, crc); + assert(0x8C736521 == crc); + + strcpy(data, "bar"); + crc = RNS::Utilities::Crc::crc32(crc, data); + TRACEF("crc1: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0x9EF61F95, crc); + assert(0x9EF61F95 == crc); + + strcpy(data, "foo"); + crc = RNS::Utilities::Crc::crc32(crc, data); + TRACEF("crc3: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0xEE2F4613, crc); + assert(0xEE2F4613 == crc); + + strcpy(data, "foobarfoo"); + crc = RNS::Utilities::Crc::crc32(0, data); + TRACEF("crc: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0xEE2F4613, crc); + assert(0xEE2F4613 == crc); +} + +void testByteCrc32() { + HEAD("testByteCrc32", RNS::LOG_TRACE); + + char data[16]; + strcpy(data, "foobarfoo"); + + uint32_t crc = 0; + for (int i = 0; i < strlen(data); i++) { + crc = RNS::Utilities::Crc::crc32(crc, data[i]); + } + TRACEF("crc: 0x%X", crc); + //TEST_ASSERT_EQUAL_UINT8(0xEE2F4613, crc); + assert(0xEE2F4613 == crc); +} + void testCrypto() { HEAD("Running testCrypto...", RNS::LOG_TRACE); - testCryptoMain(); + //testCryptoMain(); testHMAC(); testPKCS7(); + testCrc8(); + testCrc32(); + testIncrementalCrc32(); + testByteCrc32(); } /* diff --git a/examples/test/TestFilesystem.cpp b/examples/test/TestFilesystem.cpp index 0b5a3db..d6afa30 100644 --- a/examples/test/TestFilesystem.cpp +++ b/examples/test/TestFilesystem.cpp @@ -1,13 +1,17 @@ //#include -#include "Filesystem.h" +#include "FileSystem.h" #include -#include "Log.h" +#include +#include #include +#include +#include +#include -Filesystem test_filesystem; +RNS::FileSystem test_filesystem(RNS::Type::NONE); void testListDirectory() { @@ -39,7 +43,7 @@ void testWriteFile(const char* file_path) { { RNS::Bytes data("test"); size_t wrote = RNS::Utilities::OS::write_file(file_path, data); - //assert(wrote == 4); + assert(wrote == 4); } size_t post_memory = RNS::Utilities::OS::heap_available(); @@ -59,6 +63,7 @@ void testReadFile(const char* file_path) { RNS::Bytes data; size_t read = RNS::Utilities::OS::read_file(file_path, data); assert(read == 4); + assert(data.toString().compare("test") == 0); } size_t post_memory = RNS::Utilities::OS::heap_available(); @@ -69,6 +74,34 @@ void testReadFile(const char* file_path) { } +void testOverwriteFile(const char* file_path) { + + size_t pre_memory = RNS::Utilities::OS::heap_available(); + TRACEF("testOverwriteFile: pre-mem: %u", pre_memory); + + // overwrite + { + RNS::Bytes data("test"); + size_t wrote = RNS::Utilities::OS::write_file(file_path, data); + assert(wrote == 4); + } + + // read + { + RNS::Bytes data; + size_t read = RNS::Utilities::OS::read_file(file_path, data); + assert(read == 4); + assert(data.toString().compare("test") == 0); + } + + size_t post_memory = RNS::Utilities::OS::heap_available(); + size_t diff_memory = (int)pre_memory - (int)post_memory; + TRACEF("testOverwriteFile: post-mem: %u", post_memory); + TRACEF("testOverwriteFile: diff-mem: %u", diff_memory); + assert(diff_memory == 0); + +} + void testRemoveFile(const char* file_path) { size_t pre_memory = RNS::Utilities::OS::heap_available(); @@ -91,7 +124,7 @@ void testReadNonexistantFile() { { RNS::Bytes data; - size_t read = RNS::Utilities::OS::read_file("/foo", data); + size_t read = RNS::Utilities::OS::read_file("./foo", data); assert(read == 0); } @@ -122,47 +155,139 @@ void testWriteFail() { } -void testFilesystem() { - HEAD("Running testFilesystem...", RNS::LOG_TRACE); - - test_filesystem.init(); - test_filesystem.listDir("/"); - test_filesystem.listDir("/cache"); - RNS::Utilities::OS::register_filesystem(test_filesystem); - +void testWriteFileStream(const char* file_path) { size_t pre_memory = RNS::Utilities::OS::heap_available(); - TRACEF("testFilesystem: pre-mem: %u", pre_memory); + TRACEF("testWriteFileStream: pre-mem: %u", pre_memory); - // CBA Seems that first call to write_file allocates some memory (at least with NRF52 LittleFS) so get that out of the way first { - RNS::Bytes data("foo"); - RNS::Utilities::OS::write_file("/foo", data); - RNS::Utilities::OS::remove_file("/foo"); + RNS::Bytes data("stream"); + RNS::FileStream stream = RNS::Utilities::OS::open_file(file_path, RNS::FileStream::MODE_WRITE); + assert(stream); + TRACE("testWriteFileStream: writing to file..."); + size_t wrote = stream.write(data.data(), data.size()); + TRACEF("testWriteFileStream: wrote: %u", wrote); + // Auto-closes + //stream.close(); + assert(wrote == 6); + uint32_t crc = RNS::Utilities::Crc::crc32(0, data.data(), data.size()); + TRACEF("testWriteFileStream: crc: 0x%X", crc); + TRACEF("testWriteFileStream: stream crc: 0x%X", stream.crc()); + assert(crc == stream.crc()); } size_t post_memory = RNS::Utilities::OS::heap_available(); size_t diff_memory = (int)pre_memory - (int)post_memory; - TRACEF("testFilesystem: post-mem: %u", post_memory); - TRACEF("testFilesystem: diff-mem: %u", diff_memory); + TRACEF("testWriteFileStream: post-mem: %u", post_memory); + TRACEF("testWriteFileStream: diff-mem: %u", diff_memory); + assert(diff_memory == 0); +} - testListDirectory(); - testWriteFile("/test1"); - testReadFile("/test1"); - //testRemoveFile("/test1"); - testReadNonexistantFile(); - //testWriteFail(); +void testReadFileStream(const char* file_path) { + + size_t pre_memory = RNS::Utilities::OS::heap_available(); + TRACEF("testReadFileStream: pre-mem: %u", pre_memory); + + { + RNS::Bytes data; + RNS::FileStream stream = RNS::Utilities::OS::open_file(file_path, RNS::FileStream::MODE_READ); + assert(stream); + size_t size = stream.size(); + TRACEF("testReadFileStream: size: %u", size); + TRACE("testReadFileStream: reading from file..."); + size_t read = stream.readBytes(data.writable(size), size); + TRACEF("testReadFileStream: read: %u", read); + // Auto-closes + //stream.close(); + assert(read == 6); + assert(data.compare("stream") == 0); + uint32_t crc = RNS::Utilities::Crc::crc32(0, data.data(), data.size()); + TRACEF("testWriteFileStream: crc: 0x%X", crc); + TRACEF("testWriteFileStream: stream crc: 0x%X", stream.crc()); + assert(crc == stream.crc()); + } + + size_t post_memory = RNS::Utilities::OS::heap_available(); + size_t diff_memory = (int)pre_memory - (int)post_memory; + TRACEF("testReadFileStream: post-mem: %u", post_memory); + TRACEF("testReadFileStream: diff-mem: %u", diff_memory); + assert(diff_memory == 0); + +} + +void testStdStream() { + std::ofstream file("./stream"); + if(file.is_open()) { + file << "Hello world!" << std::endl; + file.flush(); + file.close(); + } + assert(RNS::Utilities::OS::file_exists("./stream")); + RNS::Utilities::OS::remove_file("./stream"); +} + +void testCacheWrite() { // CBA Attempt to reproduce failure to open file for write that is leaking mmeory if (!RNS::Utilities::OS::directory_exists("/cache")) { RNS::Utilities::OS::create_directory("/cache"); } - testWriteFile("/cache/test"); - testWriteFile("/cache/45c50662af11f1b26889efaab547942b"); - testWriteFile("/cache/40fe4ab8105b591cca1ef159d476a7b4"); - testWriteFile("/cache/c755609f4d0ab75b5119905a032eeb33"); - testWriteFile("/cache/426f66f9aadf866933358b71295f59d0"); + testWriteFile("./cache/test"); + testWriteFile("./cache/45c50662af11f1b26889efaab547942b45c50662af11f1b26889efaab547942b"); + testWriteFile("./cache/40fe4ab8105b591cca1ef159d476a7b440fe4ab8105b591cca1ef159d476a7b4"); + testWriteFile("./cache/c755609f4d0ab75b5119905a032eeb33c755609f4d0ab75b5119905a032eeb33"); + testWriteFile("./cache/426f66f9aadf866933358b71295f59d0426f66f9aadf866933358b71295f59d0"); + +} + +void testFilesystemSize() { + + TRACEF("testFilesystemSize: size: %u", test_filesystem.storage_size()); + TRACEF("testFilesystemSize: available: %u", test_filesystem.storage_available()); + +} + + +void testFileSystem() { + HEAD("Running testFileSystem...", RNS::LOG_TRACE); + + test_filesystem = new FileSystem(); + ((FileSystem*)test_filesystem.get())->init(); + FileSystem::listDir("/"); + FileSystem::listDir("/cache"); + RNS::Utilities::OS::register_filesystem(test_filesystem); + + + size_t pre_memory = RNS::Utilities::OS::heap_available(); + TRACEF("testFileSystem: pre-mem: %u", pre_memory); + + // CBA Seems that first call to write_file allocates some memory (at least with NRF52 LittleFS) so get that out of the way first + { + RNS::Bytes data("foo"); + RNS::Utilities::OS::write_file("./foo", data); + RNS::Utilities::OS::remove_file("./foo"); + } + + size_t post_memory = RNS::Utilities::OS::heap_available(); + size_t diff_memory = (int)pre_memory - (int)post_memory; + TRACEF("testFileSystem: post-mem: %u", post_memory); + TRACEF("testFileSystem: diff-mem: %u", diff_memory); + + + testListDirectory(); + testWriteFile("./test1"); + testReadFile("./test1"); + testOverwriteFile("./test1"); + testRemoveFile("./test1"); + testReadNonexistantFile(); + //testWriteFail(); + testWriteFileStream("./stream1"); + testReadFileStream("./stream1"); + testRemoveFile("./stream1"); + //testStdStream(); + //testCacheWrite(); + testFilesystemSize(); RNS::Utilities::OS::deregister_filesystem(); diff --git a/examples/test/TestOS.cpp b/examples/test/TestOS.cpp index 8e13c63..74806b0 100644 --- a/examples/test/TestOS.cpp +++ b/examples/test/TestOS.cpp @@ -33,9 +33,31 @@ void testTime() } +void testConvert() { + //uint64_t time = ltime(); + //printf("time: %lld\n", time); + + uint64_t num = 1234567890; + //TEST_ASSERT_EQUAL_UINT64(1234567890, num); + assert(1234567890 == num); + + char str[16]; + snprintf(str, 16, "%lld", num); + //TEST_ASSERT_EQUAL_STRING("1234567890", str); + assert(strncmp("1234567890", str, sizeof(str)) == 0); + + char* buf = (char*)# + + //uint64_t newnum = (uint64_t)(*buf); + uint64_t newnum = *(uint64_t*)buf; + //TEST_ASSERT_EQUAL_UINT64(1234567890, newnum); + assert(1234567890 == newnum); +} + void testOS() { HEAD("Running testOS...", RNS::LOG_TRACE); testTime(); + testConvert(); } /* diff --git a/examples/test/TestPersistence.cpp b/examples/test/TestPersistence.cpp index 9488e6d..e1ac1cd 100644 --- a/examples/test/TestPersistence.cpp +++ b/examples/test/TestPersistence.cpp @@ -1,13 +1,12 @@ //#include -#include "Filesystem.h" +#include "FileSystem.h" #include "Interface.h" #include "Transport.h" #include "Log.h" #include "Bytes.h" #include "Utilities/OS.h" - #include "Utilities/Persistence.h" //#include @@ -19,24 +18,21 @@ #include #include -Filesystem persistence_filesystem; +RNS::FileSystem persistence_filesystem(RNS::Type::NONE); -class TestInterface : public RNS::Interface { +class TestInterface : public RNS::InterfaceImpl { public: - TestInterface(const char* name = "TestInterface") : Interface(name) {} + TestInterface(const char* name = "TestInterface") : InterfaceImpl(name) {} virtual ~TestInterface() {} - virtual inline std::string toString() const { return "TestInterface[" + name() + "]"; } - private: - virtual void on_incoming(const RNS::Bytes& data) { - DEBUG(toString() + ".on_incoming: data: " + data.toHex()); - Interface::on_incoming(data); + virtual void handle_incoming(const RNS::Bytes& data) { + DEBUG("TestInterface.handle_incoming: data: " + data.toHex()); } - virtual void on_outgoing(const RNS::Bytes& data) { - DEBUG(toString() + ".on_outgoing: data: " + data.toHex()); - Interface::on_outgoing(data); + virtual void send_outgoing(const RNS::Bytes& data) { + DEBUG("TestInterface.send_outgoing: data: " + data.toHex()); + InterfaceImpl::send_outgoing(data); } }; @@ -166,7 +162,7 @@ void testDeserializeObject() { } } else { - TRACE("failed to deserialize"); + TRACE("testDeserializeObject: failed to deserialize"); assert(false); } //assert(RNS::Utilities::OS::remove_file(test_object_path)); @@ -231,7 +227,7 @@ void testDeserializeObject() { TRACE("testDeserializeObject: test: " + test.toString()); } else { - TRACE("failed to deserialize"); + TRACE("testDeserializeObject: failed to deserialize"); assert(false); } //assert(RNS::Utilities::OS::remove_file(test_object_path)); @@ -351,7 +347,6 @@ void testDeserializeVector() { } - #ifdef ARDUINO const char test_set_path[] = "/test_set"; #else @@ -548,7 +543,7 @@ void testSerializeDestinationTable() { //RNS::Bytes empty; //std::set blobs; //RNS::Interface interface({RNS::Type::NONE}); - TestInterface test_interface; + RNS::Interface test_interface(new TestInterface()); //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) : @@ -648,12 +643,13 @@ void testDeserializeDestinationTable() { RNS::Bytes data; if (RNS::Utilities::OS::read_file(test_destination_table_path, data) > 0) { + TRACE("testDeserializeDestinationTable: read: " + std::to_string(data.size()) + " bytes"); //StaticJsonDocument<8192> doc; //DynamicJsonDocument doc(1024); - int calcsize = data.size() * 1.5; + int calcsize = data.size() * 2.0; + TRACE("testDeserializeDestinationTable: calcsize " + std::to_string(calcsize) + " bytes"); DynamicJsonDocument doc(calcsize); - TRACE("testDeserializeDestinationTable: read: " + std::to_string(data.size()) + " bytes"); //TRACE("testDeserializeVector: data: " + data.toString()); DeserializationError error = deserializeJson(doc, data.data()); //DeserializationError error = deserializeMsgPack(doc, data.data()); @@ -686,6 +682,99 @@ void testDeserializeDestinationTable() { } +void testPersistenceSerializeDestinationTable() { + HEAD("testPersistenceSerializeDestinationTable", RNS::LOG_TRACE); + + //RNS::Bytes empty; + //std::set blobs; + //RNS::Interface interface({RNS::Type::NONE}); + RNS::Interface test_interface(new TestInterface()); + //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) : + //RNS::Transport::DestinationEntry entry_one(1.0, empty, 1, 0.0, blobs, interface, packet); + RNS::Bytes received; + received.assignHex("deadbeef"); + RNS::Bytes blob; + blob.assignHex("b10bb10b"); + std::set blobs({received, blob}); + RNS::Transport::DestinationEntry entry_one; + entry_one._timestamp = 1.0; + entry_one._received_from = received; + entry_one._receiving_interface = test_interface.get_hash(); + entry_one._random_blobs = blobs; + RNS::Bytes one; + one.assignHex("1111111111111111"); + map.insert({one, entry_one}); + //RNS::Transport::DestinationEntry entry_two(2.0, empty, 1, 0.0, blobs, interface, packet); + RNS::Transport::DestinationEntry entry_two; + entry_two._timestamp = 2.0; + entry_two._received_from = received; + entry_two._receiving_interface = test_interface.get_hash(); + entry_two._random_blobs = blobs; + RNS::Bytes two; + two.assignHex("2222222222222222"); + map.insert({two, entry_two}); + + for (int n = 0; n < 20; n++) { + RNS::Transport::DestinationEntry entry; + entry._timestamp = 1.0; + entry._received_from = received; + entry._receiving_interface = test_interface.get_hash(); + entry._random_blobs = blobs; + RNS::Bytes hash; + hash.assign(std::to_string(1000000000000001 + n).c_str()); + map.insert({hash, entry}); + } + + TRACEF("testPersistenceSerializeDestinationTable: map contains %d entries", map.size()); + assert(22 == map.size()); + for (auto& [hash, test] : map) { + TRACEF("testPersistenceSerializeDestinationTable: entry: %s = %s", hash.toHex().c_str(), test.debugString().c_str()); + } + + uint32_t stream_crc; + size_t wrote = RNS::Persistence::serialize(map, test_destination_table_path, stream_crc); + TRACEF("testPersistenceSerializeDestinationTable: wrote: %d bytes", wrote); + if (wrote == 0) { + TRACE("testPersistenceSerializeDestinationTable: write failed"); + assert(false); + } + + uint32_t crc = RNS::Persistence::crc(map); + TRACEF("testPersistenceSerializeDestinationTable: crc: 0x%X", crc); + TRACEF("testPersistenceSerializeDestinationTable: stream crc: 0x%X", stream_crc); + assert(0xFC979601 == crc); + assert(0xFC979601 == stream_crc); + +} + +void testPersistenceDeserializeDestinationTable() { + HEAD("testPersistenceDeserializeDestinationTable", RNS::LOG_TRACE); + + std::map map; + uint32_t stream_crc; + size_t read = RNS::Persistence::deserialize(map, test_destination_table_path, stream_crc); + TRACEF("testPersistenceDeserializeDestinationTable: deserialized %d bytes", read); + if (read == 0) { + TRACE("testPersistenceDeserializeDestinationTable: failed to deserialize"); + assert(false); + } + + TRACEF("testPersistenceDeserializeDestinationTable: map contains %d entries", map.size()); + assert(22 == map.size()); + for (auto& [hash, test] : map) { + TRACEF("testPersistenceDeserializeDestinationTable: entry: %s = %s", hash.toHex().c_str(), test.debugString().c_str()); + } + + uint32_t crc = RNS::Persistence::crc(map); + TRACEF("testPersistenceDeserializeDestinationTable: crc: 0x%X", crc); + TRACEF("testPersistenceDeserializeDestinationTable: stream crc: 0x%X", stream_crc); + assert(0xFC979601 == crc); + assert(0xFC979601 == stream_crc); + +} + void testSerializeTimeOffset() { uint64_t offset = RNS::Utilities::OS::ltime(); TRACEF("Writing time offset of %llu to file /time_offset", offset); @@ -697,9 +786,11 @@ void testSerializeTimeOffset() { void testPersistence() { HEAD("Running testPersistence...", RNS::LOG_TRACE); - persistence_filesystem.init(); + persistence_filesystem = new FileSystem(); + ((FileSystem*)persistence_filesystem.get())->init(); RNS::Utilities::OS::register_filesystem(persistence_filesystem); +/* testWrite(); testRead(); testSerializeObject(); @@ -710,10 +801,19 @@ void testPersistence() { testDeserializeSet(); testSerializeMap(); testDeserializeMap(); - //testSerializeDestinationTable(); - //testDeserializeDestinationTable(); +*/ + testSerializeTimeOffset(); + testSerializeDestinationTable(); + testDeserializeDestinationTable(); + + // CBA Following not currently working on native + testPersistenceSerializeDestinationTable(); + + // CBA Following not currently working on native + testPersistenceDeserializeDestinationTable(); + RNS::Utilities::OS::deregister_filesystem(); } diff --git a/examples/test/TestReticulum.cpp b/examples/test/TestReticulum.cpp index 62b0395..0b765de 100644 --- a/examples/test/TestReticulum.cpp +++ b/examples/test/TestReticulum.cpp @@ -6,67 +6,36 @@ #include -class TestInterface : public RNS::Interface { - +class InInterface : public RNS::InterfaceImpl { 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 InInterface : public RNS::Interface { -public: - InInterface() : RNS::Interface("InInterface") { - OUT(false); - IN(true); - } - InInterface(const char *name) : RNS::Interface(name) { - OUT(false); - IN(true); + InInterface(const char *name = "InInterface") : RNS::InterfaceImpl(name) { + _OUT = false; + _IN = true; } virtual ~InInterface() { - name("(deleted)"); + _name = "(deleted)"; } - virtual void on_incoming(const RNS::Bytes &data) { - HEAD("InInterface.on_incoming: data: " + data.toHex(), RNS::LOG_TRACE); - RNS::Interface::on_incoming(data); + virtual void handle_incoming(const RNS::Bytes &data) { + HEAD("InInterface.handle_incoming: data: " + data.toHex(), RNS::LOG_TRACE); } - virtual inline std::string toString() const { return "InInterface[" + name() + "]"; } }; -class OutInterface : public RNS::Interface { +class OutInterface : public RNS::InterfaceImpl { public: - OutInterface(InInterface& in_interface) : RNS::Interface("OutInterface"), _in_interface(in_interface) { - OUT(true); - IN(false); - } - OutInterface(InInterface& in_interface, const char *name) : RNS::Interface(name), _in_interface(in_interface) { - OUT(true); - IN(false); + OutInterface(RNS::Interface& in_interface, const char *name = "OutInterface") : RNS::InterfaceImpl(name), _in_interface(in_interface) { + _OUT = true; + _IN = false; } virtual ~OutInterface() { - name("(deleted)"); + _name = "(deleted)"; } - virtual void on_outgoing(const RNS::Bytes &data) { - HEAD("OutInterface.on_outgoing: data: " + data.toHex(), RNS::LOG_TRACE); - _in_interface.on_incoming(data); - RNS::Interface::on_outgoing(data); + virtual void send_outgoing(const RNS::Bytes &data) { + HEAD("OutInterface.send_outgoing: data: " + data.toHex(), RNS::LOG_TRACE); + _in_interface.handle_incoming(data); + InterfaceImpl::send_outgoing(data); } - virtual inline std::string toString() const { return "OutInterface[" + name() + "]"; } private: - InInterface& _in_interface; + RNS::Interface& _in_interface; }; // Test AnnounceHandler @@ -114,8 +83,8 @@ void onPingPacket(const RNS::Bytes& data, const RNS::Packet& packet) { RNS::Reticulum reticulum({RNS::Type::NONE}); RNS::Identity identity({RNS::Type::NONE}); RNS::Destination destination({RNS::Type::NONE}); -InInterface in_interface; -OutInterface out_interface(in_interface); +RNS::Interface in_interface(new InInterface()); +RNS::Interface out_interface(new OutInterface(in_interface)); void testReticulum() { HEAD("Running testReticulum...", RNS::LOG_TRACE); diff --git a/examples/test/main.cpp b/examples/test/main.cpp index 08ddf20..942af43 100644 --- a/examples/test/main.cpp +++ b/examples/test/main.cpp @@ -29,6 +29,7 @@ void setup() { break; } Serial.print("Hello from T-Beam on PlatformIO!\n"); + delay(2000); #endif RNS::loglevel(RNS::LOG_TRACE); @@ -42,20 +43,26 @@ void setup() { RNS::loglevel(RNS::LOG_TRACE); //RNS::loglevel(RNS::LOG_MEM); + //UNITY_BEGIN(); + + //RUN_TEST(test_request); + + //UNITY_END(); + // all tests //test(); // individiual tests //testReference(); //testCrypto(); - testBytes(); - //testFilesystem(); + //testBytes(); + testFileSystem(); //testPersistence(); //testReticulum(); + HEAD("All tests successful!", RNS::LOG_TRACE); + RNS::loglevel(loglevel); - TRACE("Finished running tests"); - //return; } catch (std::exception& e) { ERRORF("!!! Exception in test: %s", e.what()); diff --git a/examples/test/platformio.ini b/examples/test/platformio.ini index cce9058..f66174b 100644 --- a/examples/test/platformio.ini +++ b/examples/test/platformio.ini @@ -19,10 +19,16 @@ src_dir = . monitor_speed = 115200 upload_speed = 921600 build_type = debug +build_flags = + -DRNS_USE_ALLOCATOR=1 + -DRNS_USE_TLSF=1 +lib_deps = [env:native] platform = native +monitor_port = none build_flags = + ${env.build_flags} -std=c++11 -g3 -ggdb @@ -34,6 +40,7 @@ build_flags = -I. -DNATIVE lib_deps = + ${env.lib_deps} ArduinoJson@^6.21.3 https://github.com/attermann/arduinolibs.git microReticulum=symlink://../.. @@ -47,6 +54,7 @@ lib_compat_mode = off platform = native build_unflags = -std=gnu++11 build_flags = + ${env.build_flags} -std=c++17 -g3 -ggdb @@ -58,6 +66,7 @@ build_flags = -I. -DNATIVE lib_deps = + ${env.lib_deps} ArduinoJson@^6.21.3 https://github.com/attermann/arduinolibs.git microReticulum=symlink://../.. @@ -70,6 +79,7 @@ platform = heltec-cubecell board = cubecell_gps ;build_flags = -Wl,-Map,output.map build_flags = + ${env.build_flags} -std=c++11 -Wall -Wextra @@ -78,6 +88,7 @@ build_flags = -I. -DCUBECELL lib_deps = + ${env.lib_deps} ArduinoJson@^6.21.3 https://github.com/attermann/arduinolibs.git microReticulum=symlink://../.. @@ -91,6 +102,7 @@ upload_protocol = esp-builtin ;board_build.partitions = no_ota.csv ;board_build.partitions = huge_app.csv build_flags = + ${env.build_flags} -Wall -Wextra -Wno-missing-field-initializers @@ -99,6 +111,7 @@ build_flags = -I. -DBOARD_ESP32 lib_deps = + ${env.lib_deps} lovyan03/LovyanGFX@^1.1.8 ArduinoJson@^6.21.3 https://github.com/attermann/arduinolibs.git @@ -111,6 +124,7 @@ board = ttgo-lora32-v21 upload_speed = 460800 board_build.partitions = no_ota.csv build_flags = + ${env.build_flags} -Wall -Wextra -Wno-missing-field-initializers @@ -118,6 +132,7 @@ build_flags = -I. -DBOARD_ESP32 lib_deps = + ${env.lib_deps} ArduinoJson@^6.21.3 https://github.com/attermann/arduinolibs.git microReticulum=symlink://../.. @@ -130,6 +145,7 @@ board = ttgo-t-beam board_build.partitions = no_ota.csv ;board_build.partitions = huge_app.csv build_flags = + ${env.build_flags} -Wall -Wextra -Wno-missing-field-initializers @@ -137,6 +153,7 @@ build_flags = -I. -DBOARD_ESP32 lib_deps = + ${env.lib_deps} ArduinoJson@^6.21.3 https://github.com/attermann/arduinolibs.git microReticulum=symlink://../.. @@ -147,8 +164,9 @@ framework = arduino platform = nordicnrf52 board = wiscore_rak4631 board_build.partitions = no_ota.csv -board_build.filesystem = littlefs +board_build.FileSystem = littlefs build_flags = + ${env.build_flags} -fexceptions -Wall ;-Wextra @@ -159,6 +177,7 @@ build_flags = -DRNS_USE_TLSF=1 build_unflags = -fno-exceptions lib_deps = + ${env.lib_deps} ArduinoJson@^6.21.3 https://github.com/attermann/arduinolibs.git microReticulum=symlink://../.. @@ -168,10 +187,18 @@ framework = arduino platform = nordicnrf52 board = nrf52840_dk_adafruit monitor_speed = 115200 +build_flags = + ${env.build_flags} +lib_deps = + ${env.lib_deps} [env:nrf52_dk] framework = arduino ;framework = zephyr platform = nordicnrf52 board = nrf52_dk +build_flags = + ${env.build_flags} +lib_deps = + ${env.lib_deps} diff --git a/examples/test/test_destination_table b/examples/test/test_destination_table index 8e11eab..ac5809e 100644 --- a/examples/test/test_destination_table +++ b/examples/test/test_destination_table @@ -1 +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},"31303030303030303030303030303031":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303032":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303033":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303034":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303035":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303036":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303037":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303038":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303039":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303130":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303131":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303132":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303133":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303134":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303135":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303136":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303137":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303138":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303139":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"receiving_interface_hash":"aa6c2640df3ddc1c2194a3de35e784587191b82da5feeb50c1082ca9b45ecc95","packet_hash":null},"31303030303030303030303030303230":{"timestamp":1,"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 +{"1111111111111111":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"2222222222222222":{"timestamp":2,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303031":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303032":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303033":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303034":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303035":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303036":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303037":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303038":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303039":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303130":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303131":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303132":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303133":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303134":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303135":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303136":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303137":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303138":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303139":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303230":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},} \ No newline at end of file diff --git a/platformio.ini b/platformio.ini index edd7e89..4ffbf14 100644 --- a/platformio.ini +++ b/platformio.ini @@ -20,6 +20,7 @@ build_flags = -Wno-format -Wno-unused-parameter -Isrc + -DLIBRARY_TEST ;-DNDEBUG -DRNS_USE_FS -DRNS_PERSIST_PATHS diff --git a/src/Bytes.cpp b/src/Bytes.cpp index 1c3a6c2..e889d9f 100644 --- a/src/Bytes.cpp +++ b/src/Bytes.cpp @@ -81,7 +81,7 @@ MEM("exclusiveData: Created new empty data"); } } -int8_t Bytes::compare(const Bytes& bytes) const { +int Bytes::compare(const Bytes& bytes) const { if (_data == bytes._data) { return 0; } @@ -102,14 +102,30 @@ int8_t Bytes::compare(const Bytes& bytes) const { } } -void Bytes::assignHex(const char* hex) { +int Bytes::compare(const uint8_t* buf, size_t size) const { + if (!_data && size == 0) { + return 0; + } + else if (!_data) { + return -1; + } + int cmp = memcmp(_data->data(), buf, (_data->size() < size) ? _data->size() : size); + if (cmp == 0 && _data->size() < size) { + return -1; + } + else if (cmp == 0 && _data->size() > size) { + return 1; + } + return cmp; +} + +void Bytes::assignHex(const uint8_t* hex, size_t hex_size) { // if assignment is empty then clear data and don't bother creating new - if (hex == nullptr || hex[0] == 0) { + if (hex == nullptr || hex_size <= 0) { _data = nullptr; _exclusive = true; return; } - size_t hex_size = strlen(hex); exclusiveData(false, hex_size / 2); // need to clear data since we're appending below _data->clear(); @@ -119,12 +135,11 @@ void Bytes::assignHex(const char* hex) { } } -void Bytes::appendHex(const char* hex) { +void Bytes::appendHex(const uint8_t* hex, size_t hex_size) { // if append is empty then do nothing - if (hex == nullptr || hex[0] == 0) { + if (hex == nullptr || hex_size <= 0) { return; } - size_t hex_size = strlen(hex); exclusiveData(true, size() + (hex_size / 2)); for (size_t i = 0; i < hex_size; i += 2) { uint8_t byte = (hex[i] % 32 + 9) % 25 * 16 + (hex[i+1] % 32 + 9) % 25; diff --git a/src/Bytes.h b/src/Bytes.h index d380187..a52d18a 100644 --- a/src/Bytes.h +++ b/src/Bytes.h @@ -144,7 +144,8 @@ namespace RNS { } //inline void assign(const std::string& string) { assign(string.c_str()); } inline void assign(const std::string& string) { assign((uint8_t*)string.c_str(), string.length()); } - void assignHex(const char* hex); + void assignHex(const uint8_t* hex, size_t hex_size); + inline void assignHex(const char* hex) { assignHex((uint8_t*)hex, strlen(hex)); } inline void append(const Bytes& bytes) { // if append is empty then do nothing @@ -177,7 +178,8 @@ namespace RNS { } //inline void append(const std::string& string) { append(string.c_str()); } inline void append(const std::string& string) { append((uint8_t*)string.c_str(), string.length()); } - void appendHex(const char* hex); + void appendHex(const uint8_t* hex, size_t hex_size); + inline void appendHex(const char* hex) { appendHex((uint8_t*)hex, strlen(hex)); } inline uint8_t* writable(size_t size) { if (size > 0) { @@ -211,7 +213,9 @@ namespace RNS { } public: - int8_t compare(const Bytes& bytes) const; + int compare(const Bytes& bytes) const; + int compare(const uint8_t* buf, size_t size) const; + inline int compare(const char* str) const { return compare((const uint8_t*)str, strlen(str)); } inline size_t size() const { if (!_data) return 0; return _data->size(); } inline bool empty() const { if (!_data) return true; return _data->empty(); } inline size_t capacity() const { if (!_data) return 0; return _data->capacity(); } @@ -224,6 +228,17 @@ namespace RNS { Bytes mid(size_t beginpos) const; inline Bytes left(size_t len) const { if (!_data) return NONE; if (len > size()) len = size(); return {data(), len}; } inline Bytes right(size_t len) const { if (!_data) return NONE; if (len > size()) len = size(); return {data() + (size() - len), len}; } + inline int find(int pos, const char* str) { + if (!_data || _data->data() == nullptr || pos >= _data->size()) { + return -1; + } + const char* ptr = strnstr((const char*)(_data->data() + pos), str, (_data->size() - pos)); + if (ptr == nullptr) { + return -1; + } + return (int)((uint8_t*)ptr - _data->data()); + } + inline int find(const char* str) { return find(0, str); } // Python array indexing // [8:16] diff --git a/src/FileStream.h b/src/FileStream.h new file mode 100644 index 0000000..58ff406 --- /dev/null +++ b/src/FileStream.h @@ -0,0 +1,144 @@ +#pragma once + +#include "Utilities/Crc.h" +#include "Log.h" +#include "Bytes.h" +#include "Type.h" + +#ifdef ARDUINO +#include +#else +#include "Utilities/Stream.h" +#endif + +#include +#include +#include +#include + +namespace RNS { + + class FileStreamImpl { + + protected: + FileStreamImpl() { MEMF("FileStreamImpl object created, this: 0x%X", this); } + public: + virtual ~FileStreamImpl() { MEMF("FileStreamImpl object destroyed, this: 0x%X", this); } + + protected: + // CBA TODO Can these be pure-virtual??? + virtual const char* name() = 0; + virtual size_t size() = 0; + virtual void close() = 0; + + // Print overrides + virtual size_t write(uint8_t byte) = 0; + virtual size_t write(const uint8_t *buffer, size_t size) = 0; + + // Stream overrides + virtual int available() = 0; + virtual int read() = 0; + virtual int peek() = 0; + virtual void flush() = 0; + + friend class FileStream; + }; + + class FileStream : public Stream { + + public: + enum MODE { + MODE_READ, + MODE_WRITE, + MODE_APPEND, + }; + + public: + FileStream(Type::NoneConstructor none) { + MEMF("FileStream object NONE created, this: 0x%X, data: 0x%X", this, _impl.get()); + } + FileStream(const FileStream& obj) : _impl(obj._impl), _crc(obj._crc) { + MEMF("FileStream object copy created, this: 0x%X, data: 0x%X", this, _impl.get()); + } + FileStream(FileStreamImpl* impl) : _impl(impl) { + MEMF("FileStream object impl created, this: 0x%X, data: 0x%X", this, _impl.get()); + } + virtual ~FileStream() { + MEMF("FileStream object destroyed, this: 0x%X, data: 0x%X", this, _impl.get()); + } + + inline virtual FileStream& operator = (const FileStream& obj) { + _impl = obj._impl; + _crc = obj._crc; + MEMF("FileStream object copy created by assignment, this: 0x%X, data: 0x%X", this, _impl.get()); + return *this; + } + inline FileStream& operator = (FileStreamImpl* impl) { + _impl.reset(impl); + MEMF("FileStream object copy created by impl assignment, this: 0x%X, data: 0x%X", this, _impl.get()); + return *this; + } + inline operator bool() const { + MEMF("FileStream object bool, this: 0x%X, data: 0x%X", this, _impl.get()); + return _impl.get() != nullptr; + } + inline bool operator < (const FileStream& obj) const { + MEMF("FileStream object <, this: 0x%X, data: 0x%X", this, _impl.get()); + return _impl.get() < obj._impl.get(); + } + inline bool operator > (const FileStream& obj) const { + MEMF("FileStream object <, this: 0x%X, data: 0x%X", this, _impl.get()); + return _impl.get() > obj._impl.get(); + } + inline bool operator == (const FileStream& obj) const { + MEMF("FileStream object ==, this: 0x%X, data: 0x%X", this, _impl.get()); + return _impl.get() == obj._impl.get(); + } + inline bool operator != (const FileStream& obj) const { + MEMF("FileStream object !=, this: 0x%X, data: 0x%X", this, _impl.get()); + return _impl.get() != obj._impl.get(); + } + inline FileStreamImpl* get() { + return _impl.get(); + } + inline void clear() { + _impl.reset(); + } + + public: + inline uint32_t crc() { return _crc; } + inline size_t write(const char* str) { return write((const uint8_t*)str, strlen(str)); } + + // File overrides + inline const char* name() { assert(_impl); return _impl->name(); } + inline size_t size() { assert(_impl); return _impl->size(); } + inline void close() { assert(_impl); _impl->close(); } + + // Print overrides + inline size_t write(uint8_t byte) { assert(_impl); _crc = Utilities::Crc::crc32(_crc, byte); return _impl->write(byte); } + inline size_t write(const uint8_t *buffer, size_t size) { assert(_impl); _crc = Utilities::Crc::crc32(_crc, buffer, size); return _impl->write(buffer, size); } + + // Stream overrides + inline int available() { assert(_impl); return _impl->available(); } + inline int read() { assert(_impl); if (_impl->available() <= 0) return EOF; int ch = _impl->read(); uint8_t byte = (uint8_t)ch; _crc = Utilities::Crc::crc32(_crc, byte); return ch; } + inline int peek() { assert(_impl); return _impl->peek(); } + inline void flush() { assert(_impl); _impl->flush(); } + + // getters/setters + protected: + public: + +#ifndef NDEBUG + inline std::string debugString() const { + std::string dump; + dump = "FileStream object, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get()); + return dump; + } +#endif + + protected: + std::shared_ptr _impl; + uint32_t _crc = 0; + }; + +} diff --git a/src/FileSystem.h b/src/FileSystem.h new file mode 100644 index 0000000..951ac6b --- /dev/null +++ b/src/FileSystem.h @@ -0,0 +1,125 @@ +#pragma once + +#include "FileStream.h" +#include "Log.h" +#include "Bytes.h" +#include "Type.h" + +#include +#include +#include +#include + +namespace RNS { + + class FileSystemImpl { + + protected: + FileSystemImpl() { MEMF("FileSystem::FileSystemImpl object created, this: 0x%X", this); } + public: + virtual ~FileSystemImpl() { MEMF("FileSystem::FileSystemImpl object destroyed, this: 0x%X", this); } + + protected: + virtual bool file_exists(const char* file_path) = 0; + virtual size_t read_file(const char* file_path, Bytes& data) = 0; + virtual size_t write_file(const char* file_path, const Bytes& data) = 0; + virtual FileStream open_file(const char* file_path, FileStream::MODE file_mode) = 0; + virtual bool remove_file(const char* file_path) = 0; + virtual bool rename_file(const char* from_file_path, const char* to_file_path) = 0; + virtual bool directory_exists(const char* directory_path) = 0; + virtual bool create_directory(const char* directory_path) = 0; + virtual bool remove_directory(const char* directory_path) = 0; + virtual std::list list_directory(const char* directory_path) = 0; + virtual size_t storage_size() = 0; + virtual size_t storage_available() = 0; + + friend class FileSystem; + }; + + class FileSystem { + + public: + FileSystem(Type::NoneConstructor none) { + MEMF("FileSystem object NONE created, this: 0x%X, data: 0x%X", this, _impl.get()); + } + FileSystem(const FileSystem& obj) : _impl(obj._impl) { + MEMF("FileSystem object copy created, this: 0x%X, data: 0x%X", this, _impl.get()); + } + FileSystem(FileSystemImpl* impl) : _impl(impl) { + MEMF("FileSystem object impl created, this: 0x%X, data: 0x%X", this, _impl.get()); + } + virtual ~FileSystem() { + MEMF("FileSystem object destroyed, this: 0x%X, data: 0x%X", this, _impl.get()); + } + + inline FileSystem& operator = (const FileSystem& obj) { + _impl = obj._impl; + MEMF("FileSystem object copy created by assignment, this: 0x%X, data: 0x%X", this, _impl.get()); + return *this; + } + inline FileSystem& operator = (FileSystemImpl* impl) { + _impl.reset(impl); + MEMF("FileSystem object copy created by impl assignment, this: 0x%X, data: 0x%X", this, _impl.get()); + return *this; + } + inline operator bool() const { + MEMF("FileSystem object bool, this: 0x%X, data: 0x%X", this, _impl.get()); + return _impl.get() != nullptr; + } + inline bool operator < (const FileSystem& obj) const { + MEMF("FileSystem object <, this: 0x%X, data: 0x%X", this, _impl.get()); + return _impl.get() < obj._impl.get(); + } + inline bool operator > (const FileSystem& obj) const { + MEMF("FileSystem object <, this: 0x%X, data: 0x%X", this, _impl.get()); + return _impl.get() > obj._impl.get(); + } + inline bool operator == (const FileSystem& obj) const { + MEMF("FileSystem object ==, this: 0x%X, data: 0x%X", this, _impl.get()); + return _impl.get() == obj._impl.get(); + } + inline bool operator != (const FileSystem& obj) const { + MEMF("FileSystem object !=, this: 0x%X, data: 0x%X", this, _impl.get()); + return _impl.get() != obj._impl.get(); + } + inline FileSystemImpl* get() { + return _impl.get(); + } + inline void clear() { + _impl.reset(); + } + + public: + inline bool file_exists(const char* file_path) { assert(_impl); return _impl->file_exists(file_path); } + inline size_t read_file(const char* file_path, Bytes& data) { assert(_impl); return _impl->read_file(file_path, data); } + inline size_t write_file(const char* file_path, const Bytes& data) { assert(_impl); return _impl->write_file(file_path, data); } + inline FileStream open_file(const char* file_path, FileStream::MODE file_mode) { return _impl->open_file(file_path, file_mode); } + inline bool remove_file(const char* file_path) { assert(_impl); return _impl->remove_file(file_path); } + inline bool rename_file(const char* from_file_path, const char* to_file_path) { assert(_impl); return _impl->rename_file(from_file_path, to_file_path); } + inline bool directory_exists(const char* directory_path) { assert(_impl); return _impl->directory_exists(directory_path); } + inline bool create_directory(const char* directory_path) { assert(_impl); return _impl->create_directory(directory_path); } + inline bool remove_directory(const char* directory_path) { assert(_impl); return _impl->remove_directory(directory_path); } + inline std::list list_directory(const char* directory_path) { assert(_impl); return _impl->list_directory(directory_path); } + inline size_t storage_size() { assert(_impl); return _impl->storage_size(); } + inline size_t storage_available() { assert(_impl); return _impl->storage_available(); } + + private: + std::list _empty; + + // 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)_impl.get()); + return dump; + } +#endif + + protected: + std::shared_ptr _impl; + }; + +} diff --git a/src/Filesystem.h b/src/Filesystem.h deleted file mode 100644 index 0de6216..0000000 --- a/src/Filesystem.h +++ /dev/null @@ -1,142 +0,0 @@ -#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 size_t read_file(const char* file_path, Bytes& data) { return 0; } - virtual size_t write_file(const char* file_path, const Bytes& data) { return 0; } - 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 directory_exists(const char* directory_path) { return false; } - virtual bool create_directory(const char* directory_path) { return false; } - virtual bool remove_directory(const char* directory_path) { return false; } - virtual std::list list_directory(const char* directory_path) { TRACE("list_directory: empty"); return _empty; } - virtual size_t storage_size() { return 0; } - virtual size_t storage_available() { return 0; } - - public: - inline bool do_file_exists(const char* file_path) { assert(_object); return _object->do_file_exists(file_path); } - inline size_t do_read_file(const char* file_path, Bytes& data) { assert(_object); return _object->do_read_file(file_path, data); } - inline size_t do_write_file(const char* file_path, const Bytes& data) { assert(_object); return _object->do_write_file(file_path, data); } - 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_directory_exists(const char* directory_path) { assert(_object); return _object->do_directory_exists(directory_path); } - inline bool do_create_directory(const char* directory_path) { assert(_object); return _object->do_create_directory(directory_path); } - inline bool do_remove_directory(const char* directory_path) { assert(_object); return _object->do_remove_directory(directory_path); } - inline std::list do_list_directory(const char* directory_path) { assert(_object); return _object->do_list_directory(directory_path); } - inline size_t do_storage_size() { assert(_object); return _object->do_storage_size(); } - inline size_t do_storage_available() { assert(_object); return _object->do_storage_available(); } - - private: - std::list _empty; - - // 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: - inline bool do_file_exists(const char* file_path) { if (_parent == nullptr) return false; return _parent->file_exists(file_path); } - inline size_t do_read_file(const char* file_path, Bytes& data) { if (_parent == nullptr) return {Bytes::NONE}; return _parent->read_file(file_path, data); } - inline size_t do_write_file(const char* file_path, const Bytes& data) { if (_parent == nullptr) return false; return _parent->write_file(file_path, data); } - inline bool do_remove_file(const char* file_path) { if (_parent == nullptr) return false; return _parent->remove_file(file_path); } - 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); } - inline bool do_directory_exists(const char* directory_path) { if (_parent == nullptr) return false; return _parent->directory_exists(directory_path); } - inline bool do_create_directory(const char* directory_path) { if (_parent == nullptr) return false; return _parent->create_directory(directory_path); } - inline bool do_remove_directory(const char* directory_path) { if (_parent == nullptr) return false; return _parent->remove_directory(directory_path); } - inline std::list do_list_directory(const char* directory_path) { if (_parent == nullptr) return _empty; return _parent->list_directory(directory_path); } - inline size_t do_storage_size() { if (_parent == nullptr) return false; return _parent->storage_size(); } - inline size_t do_storage_available() { if (_parent == nullptr) return false; return _parent->storage_available(); } - private: - Filesystem* _parent = nullptr; - std::list _empty; - friend class Filesystem; - }; - - private: - std::shared_ptr _object; - bool _creator = false; - - friend class OS; - }; - -} diff --git a/src/Identity.cpp b/src/Identity.cpp index 884fc1c..89f8ae7 100644 --- a/src/Identity.cpp +++ b/src/Identity.cpp @@ -22,8 +22,9 @@ using namespace RNS::Utilities; /*static*/ std::map Identity::_known_destinations; /*static*/ bool Identity::_saving_known_destinations = false; // CBA +// CBA ACCUMULATES /*static*/ //uint16_t Identity::_known_destinations_maxsize = 100; -/*static*/ uint16_t Identity::_known_destinations_maxsize = 20; +/*static*/ uint16_t Identity::_known_destinations_maxsize = 100; Identity::Identity(bool create_keys /*= true*/) : _object(new Object()) { if (create_keys) { diff --git a/src/Interface.cpp b/src/Interface.cpp index 0226ae2..acb72b7 100644 --- a/src/Interface.cpp +++ b/src/Interface.cpp @@ -8,40 +8,23 @@ using namespace RNS::Type::Interface; /*static*/ uint8_t Interface::DISCOVER_PATHS_FOR = MODE_ACCESS_POINT | MODE_GATEWAY; -Interface::Interface() : _object(new Object(this)), _creator(true) { - // CBA MCU SHORTER HASH - _object->_hash = Identity::full_hash({toString()}); - //_object->_hash = Identity::truncated_hash({toString()}); - MEM("Interface object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); +/*virtual*/ void InterfaceImpl::send_outgoing(const Bytes& data) { + //TRACE("InterfaceImpl.send_outgoing: data: " + data.toHex()); + TRACE("InterfaceImpl.send_outgoing"); + _txb += data.size(); } -Interface::Interface(const char* name) : _object(new Object(this, name)), _creator(true) { - // CBA MCU SHORTER HASH - _object->_hash = Identity::full_hash({toString()}); - //_object->_hash = Identity::truncated_hash({toString()}); - MEM("Interface object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); -} - -/*virtual*/ inline void Interface::on_incoming(const Bytes& data) { - //TRACE("Interface.on_incoming: data: " + data.toHex()); - TRACE("Interface.on_incoming"); - assert(_object); - _object->_rxb += data.size(); +/*virtual*/ //void InterfaceImpl::handle_incoming(const Bytes& data) { +void Interface::handle_incoming(const Bytes& data) { + //TRACE("Interface.handle_incoming: data: " + data.toHex()); + TRACE("Interface.handle_incoming"); + assert(_impl); + _impl->_rxb += data.size(); // CBA TODO implement concept of owner or a callback mechanism for incoming data - //_object->_owner.inbound(data, *this); + //_impl->_owner.inbound(data, *this); Transport::inbound(data, *this); -} - -/*virtual*/ inline void Interface::on_outgoing(const Bytes& data) { - //TRACE("Interface.on_outgoing: data: " + data.toHex()); - TRACE("Interface.on_outgoing"); - assert(_object); - _object->_txb += data.size(); -} - -const Bytes Interface::get_hash() const { - assert(_object); - return _object->_hash; + // CBA This is no good because it frees impl when Interface is destroyed at end of inbound() + //Transport::inbound(data, Interface(this)); } void Interface::process_announce_queue() { @@ -69,11 +52,11 @@ void Interface::process_announce_queue() { double now = OS::time(); uint32_t wait_time = 0; - if (_object->_bitrate > 0 && _object->_announce_cap > 0) { - uint32_t tx_time = (len(selected["raw"])*8) / _object->_bitrate; - wait_time = (tx_time / _object->_announce_cap); + if (_impl->_bitrate > 0 && _impl->_announce_cap > 0) { + uint32_t tx_time = (len(selected["raw"])*8) / _impl->_bitrate; + wait_time = (tx_time / _impl->_announce_cap); } - _object->_announce_allowed_at = now + wait_time; + _impl->_announce_allowed_at = now + wait_time; self.on_outgoing(selected["raw"]) diff --git a/src/Interface.h b/src/Interface.h index c4b687e..c22c40c 100644 --- a/src/Interface.h +++ b/src/Interface.h @@ -13,9 +13,9 @@ namespace RNS { - class Interface { + class Interface; + using HInterface = std::shared_ptr; - public: class AnnounceEntry { public: AnnounceEntry() {} @@ -33,8 +33,46 @@ namespace RNS { Bytes _raw; }; + class InterfaceImpl { + protected: - using HInterface = std::shared_ptr; + InterfaceImpl() { MEM("Interface::Data object created, this: " + std::to_string((uintptr_t)this)); } + InterfaceImpl(const char* name) : _name(name) { MEM("Interface::Data object created, this: " + std::to_string((uintptr_t)this)); } + public: + virtual ~InterfaceImpl() { MEM("Interface::Data object destroyed, this: " + std::to_string((uintptr_t)this)); } + + protected: + // CBA send data out on interface + virtual void send_outgoing(const Bytes& data); + // CBA handle data coming in on interface + //virtual void handle_incoming(const Bytes& data); + + protected: + Interface* _parent = nullptr; + bool _IN = false; + bool _OUT = false; + bool _FWD = false; + bool _RPT = false; + std::string _name; + size_t _rxb = 0; + size_t _txb = 0; + bool _online = false; + Bytes _ifac_identity; + Type::Interface::modes _mode = Type::Interface::MODE_NONE; + uint32_t _bitrate = 0; + double _announce_allowed_at = 0; + float _announce_cap = 0.0; + std::list _announce_queue; + bool _is_connected_to_shared_instance = false; + bool _is_local_shared_instance = false; + Bytes _hash; + HInterface _parent_interface; + //Transport& _owner; + + friend class Interface; + }; + + class Interface { public: // Which interface modes a Transport Node @@ -43,142 +81,109 @@ namespace RNS { public: Interface(Type::NoneConstructor none) { - MEM("Interface object NONE created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + MEM("Interface object NONE created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); } - Interface(const Interface& interface) : _object(interface._object) { - MEM("Interface object copy created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + Interface(const Interface& obj) : _impl(obj._impl) { + MEM("Interface object copy created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + } + Interface(InterfaceImpl* impl) : _impl(impl) { + MEM("Interface object impl created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); } - Interface(); - Interface(const char* name); virtual ~Interface() { - if (_creator) { - MEM("Interface 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("Interface object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); + MEM("Interface object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); } - inline Interface& operator = (const Interface& interface) { - _object = interface._object; - MEM("Interface object copy created by assignment, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); - if (_creator) { - MEM("Interface object clearing creator flag, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); - _creator = false; - } + inline Interface& operator = (const Interface& obj) { + _impl = obj._impl; + MEM("Interface object copy created by assignment, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + return *this; + } + inline Interface& operator = (InterfaceImpl* impl) { + _impl.reset(impl); + MEM("Interface object copy created by assignment, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); return *this; } inline operator bool() const { - MEM("Interface object bool, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); - return _object.get() != nullptr; + MEM("Interface object bool, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + return _impl.get() != nullptr; } - inline bool operator < (const Interface& interface) const { - MEM("Interface object <, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); - return _object.get() < interface._object.get(); + inline bool operator < (const Interface& obj) const { + MEM("Interface object <, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + return _impl.get() < obj._impl.get(); } - inline bool operator > (const Interface& interface) const { - MEM("Interface object <, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); - return _object.get() > interface._object.get(); + inline bool operator > (const Interface& obj) const { + MEM("Interface object <, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + return _impl.get() > obj._impl.get(); } - inline bool operator == (const Interface& interface) const { - MEM("Interface object ==, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); - return _object.get() == interface._object.get(); + inline bool operator == (const Interface& obj) const { + MEM("Interface object ==, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + return _impl.get() == obj._impl.get(); } - inline bool operator != (const Interface& interface) const { - MEM("Interface object !=, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); - return _object.get() != interface._object.get(); + inline bool operator != (const Interface& obj) const { + MEM("Interface object !=, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + return _impl.get() != obj._impl.get(); + } + inline InterfaceImpl* get() { + return _impl.get(); + } + inline void clear() { + _impl.reset(); } public: - const Bytes get_hash() const; + inline const Bytes get_hash() const { assert(_impl); return _impl->_hash; } void process_announce_queue(); - inline void detach() {} // CBA ACCUMULATES - inline void add_announce(AnnounceEntry& entry) { assert(_object); _object->_announce_queue.push_back(entry); } + inline void add_announce(AnnounceEntry& entry) { assert(_impl); _impl->_announce_queue.push_back(entry); } protected: - // 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); - - private: - //inline void process_incoming(const Bytes& data) { assert(_object); _object->process_incoming(data); } - inline void process_outgoing(const Bytes& data) { assert(_object); _object->process_outgoing(data); } + inline void send_outgoing(const Bytes& data) { assert(_impl); _impl->send_outgoing(data); } + public: + //inline void handle_incoming(const Bytes& data) { assert(_impl); _impl->handle_incoming(data); } + // CBA handle data coming in on interface + void handle_incoming(const Bytes& data); // getters/setters protected: - inline void IN(bool IN) { assert(_object); _object->_IN = IN; } - inline void OUT(bool OUT) { assert(_object); _object->_OUT = OUT; } - inline void FWD(bool FWD) { assert(_object); _object->_FWD = FWD; } - inline void RPT(bool RPT) { assert(_object); _object->_RPT = RPT; } - inline void name(const char* name) { assert(_object); _object->_name = name; } - inline void bitrate(uint32_t bitrate) { assert(_object); _object->_bitrate = bitrate; } - inline void online(bool online) { assert(_object); _object->_online = online; } - inline void announce_allowed_at(double announce_allowed_at) { assert(_object); _object->_announce_allowed_at = announce_allowed_at; } + inline void IN(bool IN) { assert(_impl); _impl->_IN = IN; } + inline void OUT(bool OUT) { assert(_impl); _impl->_OUT = OUT; } + inline void FWD(bool FWD) { assert(_impl); _impl->_FWD = FWD; } + inline void RPT(bool RPT) { assert(_impl); _impl->_RPT = RPT; } + inline void name(const char* name) { assert(_impl); _impl->_name = name; } + inline void bitrate(uint32_t bitrate) { assert(_impl); _impl->_bitrate = bitrate; } + inline void online(bool online) { assert(_impl); _impl->_online = online; } + inline void announce_allowed_at(double announce_allowed_at) { assert(_impl); _impl->_announce_allowed_at = announce_allowed_at; } public: - inline bool IN() const { assert(_object); return _object->_IN; } - inline bool OUT() const { assert(_object); return _object->_OUT; } - inline bool FWD() const { assert(_object); return _object->_FWD; } - inline bool RPT() const { assert(_object); return _object->_RPT; } - inline bool online() const { assert(_object); return _object->_online; } - inline std::string name() const { assert(_object); return _object->_name; } - inline const Bytes& ifac_identity() const { assert(_object); return _object->_ifac_identity; } - inline Type::Interface::modes mode() const { assert(_object); return _object->_mode; } - inline void mode(Type::Interface::modes mode) { assert(_object); _object->_mode = mode; } - inline uint32_t bitrate() const { assert(_object); return _object->_bitrate; } - inline double announce_allowed_at() const { assert(_object); return _object->_announce_allowed_at; } - inline float announce_cap() const { assert(_object); return _object->_announce_cap; } - inline std::list& announce_queue() const { assert(_object); return _object->_announce_queue; } - inline bool is_connected_to_shared_instance() const { assert(_object); return _object->_is_connected_to_shared_instance; } - inline bool is_local_shared_instance() const { assert(_object); return _object->_is_local_shared_instance; } - inline HInterface parent_interface() const { assert(_object); return _object->_parent_interface; } + inline bool IN() const { assert(_impl); return _impl->_IN; } + inline bool OUT() const { assert(_impl); return _impl->_OUT; } + inline bool FWD() const { assert(_impl); return _impl->_FWD; } + inline bool RPT() const { assert(_impl); return _impl->_RPT; } + inline bool online() const { assert(_impl); return _impl->_online; } + inline std::string name() const { assert(_impl); return _impl->_name; } + inline const Bytes& ifac_identity() const { assert(_impl); return _impl->_ifac_identity; } + inline Type::Interface::modes mode() const { assert(_impl); return _impl->_mode; } + inline void mode(Type::Interface::modes mode) { assert(_impl); _impl->_mode = mode; } + inline uint32_t bitrate() const { assert(_impl); return _impl->_bitrate; } + inline double announce_allowed_at() const { assert(_impl); return _impl->_announce_allowed_at; } + inline float announce_cap() const { assert(_impl); return _impl->_announce_cap; } + inline std::list& announce_queue() const { assert(_impl); return _impl->_announce_queue; } + inline bool is_connected_to_shared_instance() const { assert(_impl); return _impl->_is_connected_to_shared_instance; } + inline bool is_local_shared_instance() const { assert(_impl); return _impl->_is_local_shared_instance; } + inline HInterface parent_interface() const { assert(_impl); return _impl->_parent_interface; } - virtual inline std::string toString() const { if (!_object) return ""; return "Interface[" + _object->_name + "]"; } + virtual inline std::string toString() const { if (!_impl) return ""; return "Interface[" + _impl->_name + "]"; } #ifndef NDEBUG inline std::string debugString() const { std::string dump; - dump = "Interface object, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()); + dump = "Interface object, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get()); return dump; } #endif - private: - class Object { - public: - Object(Interface* parent) : _parent(parent) { MEM("Interface::Data object created, this: " + std::to_string((uintptr_t)this)); } - Object(Interface* parent, const char* name) : _parent(parent), _name(name) { MEM("Interface::Data object created, this: " + std::to_string((uintptr_t)this)); } - virtual ~Object() { MEM("Interface::Data object destroyed, this: " + std::to_string((uintptr_t)this)); } - private: - //virtual inline void process_incoming(const Bytes& data) { if (_parent != nullptr) { _parent->on_incoming(data); } } - virtual inline void process_outgoing(const Bytes& data) { if (_parent != nullptr) { _parent->on_outgoing(data); } } - private: - Interface* _parent = nullptr; - bool _IN = false; - bool _OUT = false; - bool _FWD = false; - bool _RPT = false; - std::string _name; - size_t _rxb = 0; - size_t _txb = 0; - bool _online = false; - Bytes _ifac_identity; - Type::Interface::modes _mode = Type::Interface::MODE_NONE; - uint32_t _bitrate = 0; - double _announce_allowed_at = 0; - float _announce_cap = 0.0; - std::list _announce_queue; - bool _is_connected_to_shared_instance = false; - bool _is_local_shared_instance = false; - Bytes _hash; - HInterface _parent_interface; - //Transport& _owner; - friend class Interface; - }; - std::shared_ptr _object; - bool _creator = false; + protected: + std::shared_ptr _impl; friend class Transport; }; diff --git a/src/Transport.cpp b/src/Transport.cpp index 2ba45c7..91643c9 100644 --- a/src/Transport.cpp +++ b/src/Transport.cpp @@ -18,9 +18,6 @@ using namespace RNS; using namespace RNS::Type::Transport; using namespace RNS::Utilities; -// Imported from Crypto.cpp -extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); - #if defined(INTERFACES_SET) ///*static*/ std::set, std::less> Transport::_interfaces; /*static*/ std::set, std::less> Transport::_interfaces; @@ -80,20 +77,24 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); /*static*/ //float Transport::_tables_cull_interval = 5.0; /*static*/ float Transport::_tables_cull_interval = 60.0; /*static*/ bool Transport::_saving_path_table = false; +// CBA ACCUMULATES // CBA MCU /*static*/ //uint16_t Transport::_hashlist_maxsize = 1000000; /*static*/ //uint16_t Transport::_hashlist_maxsize = 100; -/*static*/ uint16_t Transport::_hashlist_maxsize = 20; +/*static*/ uint16_t Transport::_hashlist_maxsize = 100; +// CBA ACCUMULATES // CBA MCU /*static*/ //uint16_t Transport::_max_pr_tags = 32000; /*static*/ uint16_t Transport::_max_pr_tags = 32; // CBA -/*static*/ uint16_t Transport::_path_table_maxsize = 20; -/*static*/ uint16_t Transport::_path_table_maxpersist = 20; +// CBA ACCUMULATES +/*static*/ uint16_t Transport::_path_table_maxsize = 100; +// CBA ACCUMULATES +/*static*/ uint16_t Transport::_path_table_maxpersist = 100; /*static*/ double Transport::_last_saved = 0.0; /*static*/ float Transport::_save_interval = 3600.0; -/*static*/ uint8_t Transport::_destination_table_crc = 0; +/*static*/ uint32_t Transport::_destination_table_crc = 0; /*static*/ Reticulum Transport::_owner({Type::NONE}); /*static*/ Identity Transport::_identity({Type::NONE}); @@ -708,8 +709,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); */ } else { - //interface.on_outgoing(raw); - interface.process_outgoing(raw); + interface.send_outgoing(raw); } } catch (std::exception& e) { @@ -1000,7 +1000,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); } } if (should_queue) { - Interface::AnnounceEntry entry( + RNS::AnnounceEntry entry( packet.destination_hash(), outbound_time, packet.hops(), @@ -2634,7 +2634,7 @@ Deregisters an announce handler. try { char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE]; snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, packet.get_hash().toHex().c_str()); - return Persistence::serialize(packet, packet_cache_path); + return (Persistence::serialize(packet, packet_cache_path) > 0); } catch (std::exception& e) { ERROR("Error writing packet to cache. The contained exception was: " + std::string(e.what())); @@ -2670,9 +2670,8 @@ Deregisters an announce handler. */ char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE]; snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, packet_hash.toHex().c_str()); - //return Persistence::deserialize(packet_cache_path.c_str()); Packet packet({Type::NONE}); - if (Persistence::deserialize(packet, packet_cache_path)) { + if (Persistence::deserialize(packet, packet_cache_path) > 0) { packet.update_hash(); } return packet; @@ -3330,6 +3329,8 @@ will announce it. #endif } +//#define CUSTOM 1 + /*static*/ bool Transport::read_path_table() { DEBUG("Transport::read_path_table"); #if defined(RNS_USE_FS) && defined(RNS_PERSIST_PATHS) @@ -3373,13 +3374,14 @@ will announce it. */ try { -TRACE("Transport::start: buffer capacity " + std::to_string(Persistence::_buffer.capacity()) + " bytes"); +#if CUSTOM +TRACEF("Transport::start: buffer capacity %d bytes", Persistence::_buffer.capacity()); if (RNS::Utilities::OS::read_file(destination_table_path, Persistence::_buffer) > 0) { - TRACE("Transport::start: read: " + std::to_string(Persistence::_buffer.size()) + " bytes"); + TRACEF("Transport::start: read: %d bytes", Persistence::_buffer.size()); #ifndef NDEBUG // CBA DEBUG Dump path table -TRACE("Transport::start: buffer addr: " + std::to_string((long)Persistence::_buffer.data())); -TRACE("Transport::start: buffer size " + std::to_string(Persistence::_buffer.size()) + " bytes"); +TRACEF("Transport::start: buffer addr: 0x%X", Persistence::_buffer.data()); +TRACEF("Transport::start: buffer size %d bytes", Persistence::_buffer.size()); //TRACE("SERIALIZED: destination_table"); //TRACE(Persistence::_buffer.toString()); #endif @@ -3388,27 +3390,32 @@ TRACE("Transport::start: buffer size " + std::to_string(Persistence::_buffer.siz #else DeserializationError error = deserializeJson(Persistence::_document, Persistence::_buffer.data()); #endif - TRACE("Transport::start: doc size: " + std::to_string(Persistence::_buffer.size()) + " bytes"); + TRACEF("Transport::start: doc size: %d bytes", Persistence::_buffer.size()); if (!error) { - _destination_table = Persistence::_document.as>(); - TRACE("Transport::start: successfully deserialized path table with " + std::to_string(_destination_table.size()) + " entries"); // Calculate crc for dirty-checking before write - _destination_table_crc = crypto_crc8(0, Persistence::_buffer.data(), Persistence::_buffer.size()); + _destination_table_crc = Crc::crc32(0, Persistence::_buffer.data(), Persistence::_buffer.size()); + _destination_table = Persistence::_document.as>(); +#else // CUSTOM + // Calculate crc for dirty-checking before write + if (Persistence::deserialize(_destination_table, destination_table_path, _destination_table_crc) > 0) { +#endif // CUSTOM + + TRACEF("Transport::start: successfully deserialized path table with %d entries", _destination_table.size()); std::vector invalid_paths; for (auto& [destination_hash, destination_entry] : _destination_table) { #ifndef NDEBUG - TRACE("Transport::start: entry: " + destination_hash.toHex() + " = " + destination_entry.debugString()); + TRACEF("Transport::start: entry: %s = %s", destination_hash.toHex().c_str(), destination_entry.debugString().c_str()); #endif // CBA If announce packet load fails then remove destination entry (it's useless without announce packet) if (!destination_entry.announce_packet()) { // remove destination - WARNING("Transport::start: removing invalid path to " + destination_hash.toHex() + " due to missing announce packet"); + WARNINGF("Transport::start: removing invalid path to %s due to missing announce packet", destination_hash.toHex().c_str()); invalid_paths.push_back(destination_hash); } // CBA If receiving interface is not found then remove destination entry (it's useless without interface) if (!destination_entry.receiving_interface()) { // remove destination - WARNING("Transport::start: removing invalid path to " + destination_hash.toHex() + " due to missing receiving interface"); + WARNINGF("Transport::start: removing invalid path to %s due to missing receiving interface", destination_hash.toHex().c_str()); invalid_paths.push_back(destination_hash); } } @@ -3420,11 +3427,15 @@ TRACE("Transport::start: buffer size " + std::to_string(Persistence::_buffer.siz else { TRACE("Transport::start: failed to deserialize"); } +#if CUSTOM } else { TRACE("Transport::start: destination table read failed"); } - VERBOSE("Loaded " + std::to_string(_destination_table.size()) + " valid path table entries from storage"); +#else // CUSTOM +#endif // CUSTOM + + VERBOSEF("Loaded %d valid path table entries from storage", _destination_table.size()); } catch (std::exception& e) { @@ -3437,7 +3448,6 @@ TRACE("Transport::start: buffer size " + std::to_string(Persistence::_buffer.siz /*static*/ bool Transport::write_path_table() { DEBUG("Transport::write_path_table"); -//return false; if (Transport::_owner.is_connected_to_shared_instance()) { return true; @@ -3461,7 +3471,7 @@ TRACE("Transport::start: buffer size " + std::to_string(Persistence::_buffer.siz try { _saving_path_table = true; double save_start = OS::time(); - DEBUG("Saving " + std::to_string(_destination_table.size()) + " path table entries to storage..."); + DEBUGF("Saving %d path table entries to storage...", _destination_table.size()); /*p serialised_destinations = [] @@ -3504,9 +3514,10 @@ TRACE("Transport::start: buffer size " + std::to_string(Persistence::_buffer.siz file.close() */ +#if CUSTOM { Persistence::_document.set(_destination_table); - TRACE("Transport::write_path_table: doc size " + std::to_string(Persistence::_document.memoryUsage()) + " bytes"); + TRACEF("Transport::write_path_table: doc size %d bytes", Persistence::_document.memoryUsage()); //size_t size = 8192; size_t size = Persistence::_buffer.capacity(); @@ -3518,7 +3529,7 @@ TRACE("Transport::write_path_table: buffer addr: " + std::to_string((long)buffer #else size_t length = serializeJson(Persistence::_document, buffer, size); #endif - TRACE("Transport::write_path_table: serialized " + std::to_string(length) + " bytes"); + TRACEF("Transport::write_path_table: serialized %d bytes", length); if (length < size) { Persistence::_buffer.resize(length); } @@ -3534,12 +3545,12 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence:: //TRACE(Persistence::_buffer.toString()); #endif // Check crc to see if data has changed before writing - uint8_t crc = crypto_crc8(0, Persistence::_buffer.data(), Persistence::_buffer.size()); + uint32_t crc = Crc::crc32(0, Persistence::_buffer.data(), Persistence::_buffer.size()); if (_destination_table_crc > 0 && crc == _destination_table_crc) { TRACE("Transport::write_path_table: no change detected, skipping write"); } else if (RNS::Utilities::OS::write_file(destination_table_path, Persistence::_buffer) == Persistence::_buffer.size()) { - TRACE("Transport::write_path_table: wrote " + std::to_string(_destination_table.size()) + " entries, " + std::to_string(Persistence::_buffer.size()) + " bytes"); + TRACEF("Transport::write_path_table: wrote %d entries, %d bytes", _destination_table.size(), Persistence::_buffer.size()); _destination_table_crc = crc; success = true; @@ -3558,16 +3569,31 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence:: else { TRACE("Transport::write_path_table: failed to serialize"); } +#else // CUSTOM + uint32_t crc = Persistence::crc(_destination_table); + if (_destination_table_crc > 0 && crc == _destination_table_crc) { + TRACE("Transport::write_path_table: no change detected, skipping write"); + } + else { + TRACE("Transport::write_path_table: change detected, writing..."); + char destination_table_path[Type::Reticulum::FILEPATH_MAXSIZE]; + snprintf(destination_table_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/destination_table", Reticulum::_storagepath); + if (Persistence::serialize(_destination_table, destination_table_path, _destination_table_crc) > 0) { + TRACEF("Transport::write_path_table: wrote %d entries, %d bytes", _destination_table.size(), Persistence::_buffer.size()); + success = true; + } + } +#endif // CUSTOM if (success) { double save_time = OS::time() - save_start; if (save_time < 1.0) { //DEBUG("Saved " + std::to_string(_destination_table.size()) + " path table entries in " + std::to_string(OS::round(save_time * 1000, 1)) + " ms"); - DEBUG("Saved " + std::to_string(_destination_table.size()) + " path table entries in " + std::to_string((int)(save_time*1000)) + " ms"); + DEBUGF("Saved %d path table entries in %d ms", _destination_table.size(), (int)(save_time*1000)); } else { //DEBUG("Saved " + std::to_string(_destination_table.size()) + " path table entries in " + std::to_string(OS::round(save_time, 1)) + " s"); - DEBUG("Saved " + std::to_string(_destination_table.size()) + " path table entries in " + std::to_string(save_time) + " s"); + DEBUGF("Saved %d path table entries in %d s", _destination_table.size(), save_time); } } } diff --git a/src/Transport.h b/src/Transport.h index 3e092d1..8f506da 100644 --- a/src/Transport.h +++ b/src/Transport.h @@ -440,7 +440,7 @@ namespace RNS { static uint16_t _path_table_maxpersist; static double _last_saved; static float _save_interval; - static uint8_t _destination_table_crc; + static uint32_t _destination_table_crc; static Reticulum _owner; static Identity _identity; @@ -469,5 +469,4 @@ namespace RNS { s.push_back(*it); } } - } diff --git a/src/Type.h b/src/Type.h index ec222e1..13cb048 100644 --- a/src/Type.h +++ b/src/Type.h @@ -14,7 +14,9 @@ namespace RNS { namespace Type { namespace Persistence { + //static const uint16_t DOCUMENT_MAXSIZE = 1024; static const uint16_t DOCUMENT_MAXSIZE = 8192; + //static const uint16_t DOCUMENT_MAXSIZE = 16384; static const uint16_t BUFFER_MAXSIZE = Persistence::DOCUMENT_MAXSIZE * 1.5; // Json write buffer of 1.5 times document seems to be sufficient } @@ -80,16 +82,16 @@ namespace RNS { namespace Type { static const uint32_t RESOURCE_CACHE = 60*60*24; // CBA TEST - static const uint16_t JOB_INTERVAL = 60*5; - //static const uint16_t JOB_INTERVAL = 60; + //static const uint16_t JOB_INTERVAL = 60*5; + static const uint16_t JOB_INTERVAL = 60; // CBA TEST - static const uint16_t CLEAN_INTERVAL = 60*15; - //static const uint16_t CLEAN_INTERVAL = 60; + //static const uint16_t CLEAN_INTERVAL = 60*15; + static const uint16_t CLEAN_INTERVAL = 60; // CBA MCU //static const uint16_t PERSIST_INTERVAL = 60*60*12; // CBA TEST - static const uint16_t PERSIST_INTERVAL = 60*60; - //static const uint16_t PERSIST_INTERVAL = 60; + //static const uint16_t PERSIST_INTERVAL = 60*60; + static const uint16_t PERSIST_INTERVAL = 60; static const uint16_t GRACIOUS_PERSIST_INTERVAL = 60*5; static const uint8_t DESTINATION_LENGTH = TRUNCATED_HASHLENGTH/8; // In bytes diff --git a/src/Utilities/Crc.cpp b/src/Utilities/Crc.cpp new file mode 100644 index 0000000..9798546 --- /dev/null +++ b/src/Utilities/Crc.cpp @@ -0,0 +1,16 @@ +#include "Crc.h" + +using namespace RNS::Utilities; + +/*static*/ uint32_t Crc::crc32(uint32_t crc, const uint8_t* buf, size_t size) { + const unsigned char *data = (const unsigned char *)buf; + if (data == NULL) + return 0; + crc ^= 0xffffffff; + while (size--) { + crc ^= *data++; + for (unsigned k = 0; k < 8; k++) + crc = crc & 1 ? (crc >> 1) ^ 0xedb88320 : crc >> 1; + } + return crc ^ 0xffffffff; +} diff --git a/src/Utilities/Crc.h b/src/Utilities/Crc.h new file mode 100644 index 0000000..968f340 --- /dev/null +++ b/src/Utilities/Crc.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include + +namespace RNS { namespace Utilities { + + class Crc { + + public: + static uint32_t crc32(uint32_t crc, const uint8_t* buffer, size_t size); + static inline uint32_t crc32(uint32_t crc, uint8_t byte) { return crc32(crc, &byte, sizeof(byte)); } + static inline uint32_t crc32(uint32_t crc, const char* str) { return crc32(crc, (const uint8_t*)str, strlen(str)); } + + }; + +} } diff --git a/src/Utilities/OS.cpp b/src/Utilities/OS.cpp index 8bac919..c46c322 100644 --- a/src/Utilities/OS.cpp +++ b/src/Utilities/OS.cpp @@ -1,5 +1,6 @@ #include "OS.h" +#include "../Type.h" #include "../Log.h" using namespace RNS; @@ -10,14 +11,19 @@ using namespace RNS::Utilities; #if defined(RNS_USE_TLSF) #if defined(ESP32) - #define BUFFER_SIZE 1024 * 80 + //#define BUFFER_SIZE 1024 * 80 + #define BUFFER_SIZE 0 #define BUFFER_FRACTION 0.8 #elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT) - #define BUFFER_SIZE 1024 * 80 + //#define BUFFER_SIZE 1024 * 80 + #define BUFFER_SIZE 0 #define BUFFER_FRACTION 0.8 +#else + #define BUFFER_SIZE 1024 * 1000 + #define BUFFER_FRACTION 0 #endif -boolean tlsf_init = false; +bool tlsf_init = false; size_t _buffer_size = BUFFER_SIZE; size_t _contiguous_size = 0; @@ -47,7 +53,9 @@ void* operator new(size_t size) { #endif TRACEF("contiguous_size: %u", _contiguous_size); - _buffer_size = (size_t)((_contiguous_size * BUFFER_FRACTION) / 1024) * 1024; + if (_buffer_size == 0) { + _buffer_size = (size_t)((_contiguous_size * BUFFER_FRACTION) / 1024) * 1024; + } TRACEF("buffer_size: %u", _buffer_size); //void* raw_buffer = malloc(BUFFER_SIZE); @@ -206,97 +214,9 @@ size_t maxContiguousAllocation() { return (block_count - 1) * block_size; } -/*static*/ Filesystem OS::_filesystem = {Type::NONE}; +/*static*/ FileSystem OS::_filesystem = {Type::NONE}; /*static*/ uint64_t OS::_time_offset = 0; -/*static*/ void OS::register_filesystem(Filesystem& filesystem) { - TRACE("Registering filesystem..."); - OS::_filesystem = filesystem; -} - -/*static*/ void OS::deregister_filesystem() { - TRACE("Deregistering filesystem..."); - OS::_filesystem = {Type::NONE}; -} - -/*static*/ bool OS::file_exists(const char* file_path) { - 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*/ size_t OS::read_file(const char* file_path, Bytes& data) { - if (!_filesystem) { - throw std::runtime_error("Filesystem has not been registered"); - } - return _filesystem.do_read_file(file_path, data); -} - -/*static*/ size_t OS::write_file(const char* file_path, const Bytes& data) { - if (!_filesystem) { - throw std::runtime_error("Filesystem has not been registered"); - } - return _filesystem.do_write_file(file_path, data); -} - -/*static*/ bool OS::remove_file(const char* file_path) { - 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) { - 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::directory_exists(const char* directory_path) { - if (!_filesystem) { - throw std::runtime_error("Filesystem has not been registered"); - } - return _filesystem.do_directory_exists(directory_path); -} - -/*static*/ bool OS::create_directory(const char* directory_path) { - if (!_filesystem) { - throw std::runtime_error("Filesystem has not been registered"); - } - return _filesystem.do_create_directory(directory_path); -} - -/*static*/ bool OS::remove_directory(const char* directory_path) { - if (!_filesystem) { - throw std::runtime_error("Filesystem has not been registered"); - } - return _filesystem.do_remove_directory(directory_path); -} - -/*static*/ std::list OS::list_directory(const char* directory_path) { - if (!_filesystem) { - throw std::runtime_error("Filesystem has not been registered"); - } - return _filesystem.do_list_directory(directory_path); -} - -/*static*/ size_t OS::storage_size() { - if (!_filesystem) { - throw std::runtime_error("Filesystem has not been registered"); - } - return _filesystem.do_storage_size(); -} - -/*static*/ size_t OS::storage_available() { - if (!_filesystem) { - throw std::runtime_error("Filesystem has not been registered"); - } - return _filesystem.do_storage_available(); -} - /*static*/ size_t OS::heap_size() { #if defined(ESP32) return ESP.getHeapSize(); diff --git a/src/Utilities/OS.h b/src/Utilities/OS.h index 1304c56..59c1042 100644 --- a/src/Utilities/OS.h +++ b/src/Utilities/OS.h @@ -1,6 +1,7 @@ #pragma once -#include "../Filesystem.h" +#include "../FileSystem.h" +#include "../FileStream.h" #include "../Bytes.h" #include "tlsf.h" @@ -22,7 +23,7 @@ namespace RNS { namespace Utilities { class OS { private: - static Filesystem _filesystem; + static FileSystem _filesystem; static uint64_t _time_offset; public: @@ -73,20 +74,105 @@ namespace RNS { namespace Utilities { static void dump_allocator_stats(); #endif - static void register_filesystem(Filesystem& filesystem); - static void deregister_filesystem(); + inline static void register_filesystem(FileSystem& filesystem) { + TRACE("Registering filesystem..."); + _filesystem = filesystem; + } - static bool file_exists(const char* file_path); - static size_t read_file(const char* file_path, RNS::Bytes& data); - static size_t write_file(const char* file_path, const RNS::Bytes& data); - static bool remove_file(const char* file_path); - static bool rename_file(const char* from_file_path, const char* to_file_path); - static bool directory_exists(const char* directory_path); - static bool create_directory(const char* directory_path); - static bool remove_directory(const char* directory_path); - static std::list list_directory(const char* directory_path); - static size_t storage_size(); - static size_t storage_available(); + inline static void register_filesystem(FileSystemImpl* filesystemimpl) { + TRACE("Registering filesystem..."); + _filesystem = filesystemimpl; + } + + inline static void deregister_filesystem() { + TRACE("Deregistering filesystem..."); + _filesystem = {Type::NONE}; + } + + inline static bool file_exists(const char* file_path) { + if (!_filesystem) { + WARNING("file_exists: filesystem not registered"); + throw std::runtime_error("FileSystem has not been registered"); + } + return _filesystem.file_exists(file_path); + } + + inline static size_t read_file(const char* file_path, Bytes& data) { + if (!_filesystem) { + throw std::runtime_error("FileSystem has not been registered"); + } + return _filesystem.read_file(file_path, data); + } + + inline static size_t write_file(const char* file_path, const Bytes& data) { + if (!_filesystem) { + throw std::runtime_error("FileSystem has not been registered"); + } + return _filesystem.write_file(file_path, data); + } + + inline static FileStream open_file(const char* file_path, RNS::FileStream::MODE file_mode) { + if (!_filesystem) { + throw std::runtime_error("FileSystem has not been registered"); + } + return _filesystem.open_file(file_path, file_mode); + } + + inline static bool remove_file(const char* file_path) { + if (!_filesystem) { + throw std::runtime_error("FileSystem has not been registered"); + } + return _filesystem.remove_file(file_path); + } + + inline static bool rename_file(const char* from_file_path, const char* to_file_path) { + if (!_filesystem) { + throw std::runtime_error("FileSystem has not been registered"); + } + return _filesystem.rename_file(from_file_path, to_file_path); + } + + inline static bool directory_exists(const char* directory_path) { + if (!_filesystem) { + throw std::runtime_error("FileSystem has not been registered"); + } + return _filesystem.directory_exists(directory_path); + } + + inline static bool create_directory(const char* directory_path) { + if (!_filesystem) { + throw std::runtime_error("FileSystem has not been registered"); + } + return _filesystem.create_directory(directory_path); + } + + inline static bool remove_directory(const char* directory_path) { + if (!_filesystem) { + throw std::runtime_error("FileSystem has not been registered"); + } + return _filesystem.remove_directory(directory_path); + } + + inline static std::list list_directory(const char* directory_path) { + if (!_filesystem) { + throw std::runtime_error("FileSystem has not been registered"); + } + return _filesystem.list_directory(directory_path); + } + + inline static size_t storage_size() { + if (!_filesystem) { + throw std::runtime_error("FileSystem has not been registered"); + } + return _filesystem.storage_size(); + } + + inline static size_t storage_available() { + if (!_filesystem) { + throw std::runtime_error("FileSystem has not been registered"); + } + return _filesystem.storage_available(); + } static size_t heap_size(); static size_t heap_available(); diff --git a/src/Utilities/Persistence.h b/src/Utilities/Persistence.h index 30fe254..615ca70 100644 --- a/src/Utilities/Persistence.h +++ b/src/Utilities/Persistence.h @@ -122,15 +122,15 @@ namespace ArduinoJson { if (!src) { return dst.set(nullptr); } - TRACE("<<< Serializing interface hash " + src.get_hash().toHex()); + //TRACE("<<< Serializing interface hash " + src.get_hash().toHex()); return dst.set(src.get_hash().toHex()); } static RNS::Interface fromJson(JsonVariantConst src) { if (!src.isNull()) { RNS::Bytes hash; hash.assignHex(src.as()); - TRACE(">>> Deserialized interface hash " + hash.toHex()); - TRACE(">>> Querying transport for interface"); + //TRACE(">>> Deserialized interface hash " + hash.toHex()); + //TRACE(">>> Querying transport for interface"); // Query transport for matching interface return RNS::Transport::find_interface_from_hash(hash); } @@ -152,7 +152,7 @@ namespace ArduinoJson { if (!src) { return dst.set(nullptr); } - TRACE("<<< Serializing packet hash " + src.get_hash().toHex()); + //TRACE("<<< Serializing packet hash " + src.get_hash().toHex()); // Whenever a reference to a packet is serialized we must ensure that packet itself also gets serialized separately RNS::Transport::cache_packet(src, true); return dst.set(src.get_hash().toHex()); @@ -161,8 +161,8 @@ namespace ArduinoJson { if (!src.isNull()) { RNS::Bytes hash; hash.assignHex(src.as()); - TRACE(">>> Deserialized packet hash " + hash.toHex()); - TRACE(">>> Querying transport for cached packet"); + //TRACE(">>> Deserialized packet hash " + hash.toHex()); + //TRACE(">>> Querying transport for cached packet"); // Query transport for matching packet return RNS::Transport::get_cached_packet(hash); } @@ -179,16 +179,16 @@ namespace ArduinoJson { template <> struct Converter { static bool toJson(const RNS::Packet& src, JsonVariant dst) { - TRACE("<<< Serializing Packet"); + //TRACE("<<< Serializing Packet"); //dst["hash"] = src.get_hash(); dst["raw"] = src.raw(); dst["sent_at"] = src.sent_at(); dst["destination_hash"] = src.get_hash(); - TRACE("<<< Finished serializing Packet"); + //TRACE("<<< Finished serializing Packet"); return true; } static RNS::Packet fromJson(JsonVariantConst src) { - TRACE(">>> Deserializing Packet"); + //TRACE(">>> Deserializing Packet"); RNS::Bytes raw = src["raw"]; RNS::Packet packet( {RNS::Type::NONE}, @@ -199,7 +199,7 @@ namespace ArduinoJson { RNS::Bytes destination_hash = src["destination_hash"]; // set cached flag since pcket was read from cache packet.cached(true); - TRACE(">>> Finished deserializing Packet"); + //TRACE(">>> Finished deserializing Packet"); return packet; } static bool checkJson(JsonVariantConst src) { @@ -215,16 +215,16 @@ namespace ArduinoJson { template <> struct Converter { static bool toJson(const RNS::Transport::PacketEntry& src, JsonVariant dst) { - TRACE("<<< Serializing Transport::PacketEntry"); + //TRACE("<<< Serializing Transport::PacketEntry"); //dst["hash"] = src._hash; dst["raw"] = src._raw; dst["sent_at"] = src._sent_at; dst["destination_hash"] = src._destination_hash; - TRACE("<<< Finished serializing Transport::PacketEntry"); + //TRACE("<<< Finished serializing Transport::PacketEntry"); return true; } static RNS::Transport::PacketEntry fromJson(JsonVariantConst src) { - TRACE(">>> Deserializing Transport::PacketEntry"); + //TRACE(">>> Deserializing Transport::PacketEntry"); RNS::Transport::PacketEntry dst; //dst._hash = src["hash"]; dst._raw = src["raw"]; @@ -232,7 +232,7 @@ namespace ArduinoJson { dst._destination_hash = src["destination_hash"]; // set cached flag since pcket was read from cache dst._cached = true; - TRACE(">>> Finished deserializing Transport::PacketEntry"); + //TRACE(">>> Finished deserializing Transport::PacketEntry"); return dst; } static bool checkJson(JsonVariantConst src) { @@ -244,11 +244,12 @@ namespace ArduinoJson { } }; +#if 1 // ArduinoJSON serialization support for RNS::Transport::DestinationEntry template <> struct Converter { static bool toJson(const RNS::Transport::DestinationEntry& src, JsonVariant dst) { - TRACE("<<< Serializing Transport::DestinationEntry"); + //TRACE("<<< Serializing Transport::DestinationEntry"); dst["timestamp"] = src._timestamp; dst["received_from"] = src._received_from; dst["announce_hops"] = src._hops; @@ -284,11 +285,11 @@ namespace ArduinoJson { */ dst["interface_hash"] = src._receiving_interface; dst["packet_hash"] = src._announce_packet; - TRACE("<<< Finished Serializing Transport::DestinationEntry"); + //TRACE("<<< Finished Serializing Transport::DestinationEntry"); return true; } static RNS::Transport::DestinationEntry fromJson(JsonVariantConst src) { - TRACE(">>> Deserializing Transport::DestinationEntry"); + //TRACE(">>> Deserializing Transport::DestinationEntry"); RNS::Transport::DestinationEntry dst; dst._timestamp = src["timestamp"]; dst._received_from = src["received_from"]; @@ -323,7 +324,7 @@ namespace ArduinoJson { src["packet"].as() ); */ - TRACE(">>> Finished Deserializing Transport::DestinationEntry"); + //TRACE(">>> Finished Deserializing Transport::DestinationEntry"); return dst; } static bool checkJson(JsonVariantConst src) { @@ -337,15 +338,113 @@ namespace ArduinoJson { src["packet_hash"].is(); } }; +#endif } +#if 0 +namespace RNS { + + inline bool convertToJson(const Transport::DestinationEntry& src, JsonVariant dst) { + //TRACE("<<< NEW Serializing Transport::DestinationEntry"); + dst["timestamp"] = src._timestamp; + dst["received_from"] = src._received_from; + dst["announce_hops"] = src._hops; + dst["expires"] = src._expires; + dst["random_blobs"] = src._random_blobs; +/* + //dst["interface_hash"] = src._receiving_interface; + if (src._receiving_interface) { + dst["interface_hash"] = src._receiving_interface.get_hash(); + } + else { + dst["interface_hash"] = nullptr; + } + // CBA TODO Move packet serialization to *after* destination table serialization since packets are useless + // anyway if there's no space to left to write destination table. + // Whenever a reference to a packet is serialized we must ensure that packet itself also gets serialized separately + //dst["packet"] = src._announce_packet; + if (src._announce_packet) { + dst["packet_hash"] = src._announce_packet.get_hash(); + // Only cache packet if not already cached + if (!src._announce_packet.cached()) { + if (RNS::Transport::cache_packet(src._announce_packet, true)) { + const_cast(src._announce_packet).cached(true); + } + } + else { + TRACE("Destination announce packet " + src._announce_packet.get_hash().toHex() + " is already cached"); + } + } + else { + dst["packet_hash"] = nullptr; + } +*/ + dst["interface_hash"] = src._receiving_interface; + dst["packet_hash"] = src._announce_packet; + //TRACE("<<< Finished Serializing Transport::DestinationEntry"); + return true; + } + + inline void convertFromJson(JsonVariantConst src, Transport::DestinationEntry& dst) { + //TRACE(">>> NEW Deserializing Transport::DestinationEntry"); + dst._timestamp = src["timestamp"]; + dst._received_from = src["received_from"]; + dst._hops = src["announce_hops"]; + dst._expires = src["expires"]; + dst._random_blobs = src["random_blobs"].as>(); +/* + //dst._receiving_interface = src["interface_hash"]; + RNS::Bytes interface_hash = src["interface_hash"]; + if (interface_hash) { + // Query transport for matching interface + dst._receiving_interface = RNS::Transport::find_interface_from_hash(interface_hash); + } + //dst._announce_packet = src["packet"]; + RNS::Bytes packet_hash = src["packet_hash"]; + if (packet_hash) { + // Query transport for matching packet + dst._announce_packet = RNS::Transport::get_cached_packet(packet_hash); + } +*/ + dst._receiving_interface = src["interface_hash"]; + dst._announce_packet = src["packet_hash"]; +/* + //RNS::Transport::DestinationEntry dst(src["timestamp"], src["received_from"], src["announce_hops"], src["expires"], src["random_blobs"], src["receiving_interface"], src["packet"]); + RNS::Transport::DestinationEntry dst( + src["timestamp"].as(), + src["received_from"].as(), + src["announce_hops"].as(), + src["expires"].as(), + src["random_blobs"].as>(), + src["receiving_interface"].as(), + src["packet"].as() + ); +*/ + //TRACE(">>> Finished Deserializing Transport::DestinationEntry"); + } + + inline bool canConvertFromJson(JsonVariantConst src, const Transport::DestinationEntry&) { + TRACE("=== NEW Checking Transport::DestinationEntry"); + return + src["timestamp"].is() && + src["received_from"].is() && + src["announce_hops"].is() && + src["expires"].is() && + src["random_blobs"].is>() && + src["interface_hash"].is() && + src["packet_hash"].is(); + } +} +#endif + namespace RNS { namespace Persistence { static DynamicJsonDocument _document(Type::Persistence::DOCUMENT_MAXSIZE); static Bytes _buffer(Type::Persistence::BUFFER_MAXSIZE); - template bool serialize(const T& obj, const char* file_path) { + template size_t crc(const T& obj) { + TRACE("Persistence::crc"); _document.set(obj); size_t size = _buffer.capacity(); #ifdef USE_MSGPACK @@ -356,26 +455,46 @@ namespace RNS { namespace Persistence { if (length < size) { _buffer.resize(length); } - TRACE("Persistence::serialize: serialized " + std::to_string(length) + " bytes"); + TRACEF("Persistence::crc: serialized %d bytes", length); + return Utilities::Crc::crc32(0, _buffer.data(), _buffer.size()); + } + + template size_t serialize(const T& obj, const char* file_path) { + TRACE("Persistence::serialize"); + _document.set(obj); + size_t size = _buffer.capacity(); +#ifdef USE_MSGPACK + size_t length = serializeMsgPack(_document, _buffer.writable(size), size); +#else + size_t length = serializeJson(_document, _buffer.writable(size), size); +#endif + if (length < size) { + _buffer.resize(length); + } + TRACEF("Persistence::serialize: serialized %d bytes", length); + size_t wrote = 0; if (length > 0) { - if (RNS::Utilities::OS::write_file(file_path, _buffer) == _buffer.size()) { - TRACE("Persistence::serialize: wrote " + std::to_string(_buffer.size()) + " bytes"); + wrote = RNS::Utilities::OS::write_file(file_path, _buffer); + if (wrote == _buffer.size()) { + TRACEF("Persistence::serialize: wrote %d bytes", _buffer.size()); } else { TRACE("Persistence::serialize: write failed"); - return false; + return 0; } } else { TRACE("Persistence::serialize: failed to serialize"); - return false; + return 0; } - return true; + return wrote; } - template bool deserialize(T& obj, const char* file_path) { - if (RNS::Utilities::OS::read_file(file_path, _buffer) > 0) { - TRACE("Persistence::deserialize: read: " + std::to_string(_buffer.size()) + " bytes"); + template size_t deserialize(T& obj, const char* file_path) { + TRACE("Persistence::deserialize"); + size_t read = RNS::Utilities::OS::read_file(file_path, _buffer); + if (read > 0) { + TRACEF("Persistence::deserialize: read: %d bytes", _buffer.size()); //TRACE("testDeserializeVector: data: " + _buffer.toString()); #ifdef USE_MSGPACK DeserializationError error = deserializeMsgPack(_document, _buffer.data()); @@ -383,11 +502,12 @@ namespace RNS { namespace Persistence { DeserializationError error = deserializeJson(_document, _buffer.data()); #endif if (!error) { - TRACE("Persistence::deserialize: successfully deserialized"); + TRACE("Persistence::deserialize: successfully deserialized document"); obj = _document.as(); - if (obj) { - return true; - } + // CBA Following obj check doesn't work when T is a collection + //if (obj) { + return read; + //} TRACE("Persistence::deserialize: failed to compose object"); } else { @@ -397,7 +517,153 @@ namespace RNS { namespace Persistence { else { TRACE("Persistence::deserialize: read failed"); } - return false;; + return 0; } +#if 1 + template size_t crc(std::map& map) { + TRACE("Persistence::crc>"); + + uint32_t crc = 0; + crc = Utilities::Crc::crc32(crc, '{'); + for (const auto& [key, value] : map) { + crc = Utilities::Crc::crc32(crc, '"'); + std::string hex = key.toHex(); + crc = Utilities::Crc::crc32(crc, hex.c_str()); + crc = Utilities::Crc::crc32(crc, '"'); + crc = Utilities::Crc::crc32(crc, ':'); + + _document.set(value); + size_t size = _buffer.capacity(); +#ifdef USE_MSGPACK + size_t length = serializeMsgPack(_document, _buffer.writable(size), size); +#else + size_t length = serializeJson(_document, _buffer.writable(size), size); +#endif + if (length < size) { + _buffer.resize(length); + } + TRACEF("Persistence::crc: serialized entry %d bytes", length); + + if (length > 0) { + crc = Utilities::Crc::crc32(crc, _buffer.data(), _buffer.size()); + } + else { + // if failed to serialize entry then write empty entry + crc = Utilities::Crc::crc32(crc, "{}"); + } + crc = Utilities::Crc::crc32(crc, ','); + } + return Utilities::Crc::crc32(crc, '}'); + } + + template size_t serialize(std::map& map, const char* file_path, uint32_t& crc) { + TRACE("Persistence::serialize>"); + + // CBA TODO: Use stream here instead to avoid having to buffer entire structure + RNS::FileStream stream = RNS::Utilities::OS::open_file(file_path, RNS::FileStream::MODE_WRITE); + if (!stream) { + TRACE("Persistence::serialize: failed to open write stream"); + return 0; + } + + stream.write('{'); + for (const auto& [key, value] : map) { + stream.write('"'); + std::string hex = key.toHex(); + stream.write(hex.c_str()); + stream.write('"'); + stream.write(':'); + + _document.set(value); +#ifdef USE_MSGPACK + size_t length = serializeMsgPack(_document, stream); +#else + size_t length = serializeJson(_document, stream); +#endif + TRACEF("Persistence::serialize: serialized entry %d bytes", length); + + if (length == 0) { + // if failed to serialize entry then write empty entry + stream.write("{}"); + } + stream.write(','); + } + stream.write('}'); + TRACEF("Persistence::serialize: stream size: %d bytes", stream.size()); + crc = stream.crc(); + return stream.size(); + } + + template size_t serialize(std::map& map, const char* file_path) { + uint32_t crc; + return serialize(map, file_path, crc); + } + + template size_t deserialize(std::map& map, const char* file_path, uint32_t& crc) { + TRACE("Persistence::deserialize>"); + + // CBA TODO: Use stream here instead to avoid having to buffer entire structure + RNS::FileStream stream = RNS::Utilities::OS::open_file(file_path, RNS::FileStream::MODE_READ); + if (!stream) { + TRACE("Persistence::deserialize: failed to open read stream"); + return 0; + } + TRACEF("Persistence::deserialize: size: %d bytes", stream.size()); + + map.clear(); + + // find opening brace + if (stream.find('{')) { + char key_str[RNS::Type::Reticulum::DESTINATION_LENGTH*2+1] = ""; + do { + key_str[0] = 0; + // find map key opening quote + if (stream.find('"')) { + if (stream.readBytesUntil('"', key_str, sizeof(key_str)) > 0) { + Bytes key; + key.assignHex(key_str); + TRACEF("Persistence::deserialize: key: %s", key.toHex().c_str()); + if (stream.find(':')) { +#ifdef USE_MSGPACK + //DeserializationError error = deserializeMsgPack(_document, _buffer.data()); + DeserializationError error = deserializeMsgPack(_document, stream); +#else + //DeserializationError error = deserializeJson(_document, _buffer.data()); + DeserializationError error = deserializeJson(_document, stream); +#endif + if (!error) { + TRACE("Persistence::deserialize: successfully deserialized entry"); + T obj = _document.as(); + // CBA Following obj check doesn't work when T is a collection + //if (obj) { + // TRACE("Persistence::deserialize: failed to compose object"); + // break; + //} + map.insert({key, obj}); + } + else { + TRACE("Persistence::deserialize: failed to deserialize entry"); + //break; + } + + if (!stream.find(',')) { + break; + } + + } + } + } + } while (key_str[0] != 0); + } + crc = stream.crc(); + return stream.size(); + } + + template size_t deserialize(std::map& map, const char* file_path) { + uint32_t crc; + return deserialize(map, file_path, crc); + } +#endif + } } diff --git a/src/Utilities/Print.cpp b/src/Utilities/Print.cpp new file mode 100644 index 0000000..7c2566d --- /dev/null +++ b/src/Utilities/Print.cpp @@ -0,0 +1,354 @@ +/* + Print.cpp - Base class that provides print() and println() + Copyright (c) 2008 David A. Mellis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Modified 23 November 2006 by David A. Mellis + Modified December 2014 by Ivan Grokhotkov + Modified May 2015 by Michael C. Miller - ESP31B progmem support + */ + +#ifndef ARDUINO + +#include +#include +#include +#include +#include + +#include "Print.h" +extern "C" { + #include "time.h" +} + +// Public Methods ////////////////////////////////////////////////////////////// + +/* default implementation: may be overridden */ +size_t Print::write(const uint8_t *buffer, size_t size) +{ + size_t n = 0; + while(size--) { + n += write(*buffer++); + } + return n; +} + +size_t Print::printf(const char *format, ...) +{ + char loc_buf[64]; + char * temp = loc_buf; + va_list arg; + va_list copy; + va_start(arg, format); + va_copy(copy, arg); + int len = vsnprintf(temp, sizeof(loc_buf), format, copy); + va_end(copy); + if(len < 0) { + va_end(arg); + return 0; + } + if(len >= (int)sizeof(loc_buf)){ // comparation of same sign type for the compiler + temp = (char*) malloc(len+1); + if(temp == NULL) { + va_end(arg); + return 0; + } + len = vsnprintf(temp, len+1, format, arg); + } + va_end(arg); + len = write((uint8_t*)temp, len); + if(temp != loc_buf){ + free(temp); + } + return len; +} + +size_t Print::print(const std::string &s) +{ + return write(s.c_str(), s.length()); +} + +size_t Print::print(const char str[]) +{ + return write(str); +} + +size_t Print::print(char c) +{ + return write(c); +} + +size_t Print::print(unsigned char b, int base) +{ + return print((unsigned long) b, base); +} + +size_t Print::print(int n, int base) +{ + return print((long) n, base); +} + +size_t Print::print(unsigned int n, int base) +{ + return print((unsigned long) n, base); +} + +size_t Print::print(long n, int base) +{ + int t = 0; + if (base == 10 && n < 0) { + t = print('-'); + n = -n; + } + return printNumber(static_cast(n), base) + t; +} + +size_t Print::print(unsigned long n, int base) +{ + if(base == 0) { + return write(n); + } else { + return printNumber(n, base); + } +} + +size_t Print::print(long long n, int base) +{ + int t = 0; + if (base == 10 && n < 0) { + t = print('-'); + n = -n; + } + return printNumber(static_cast(n), base) + t; +} + +size_t Print::print(unsigned long long n, int base) +{ + if (base == 0) { + return write(n); + } else { + return printNumber(n, base); + } +} + +size_t Print::print(double n, int digits) +{ + return printFloat(n, digits); +} + +size_t Print::print(struct tm * timeinfo, const char * format) +{ + const char * f = format; + if(!f){ + f = "%c"; + } + char buf[64]; + size_t written = strftime(buf, 64, f, timeinfo); + if(written == 0){ + return written; + } + return print(buf); +} + +size_t Print::println(void) +{ + return print("\r\n"); +} + +size_t Print::println(const std::string &s) +{ + size_t n = print(s); + n += println(); + return n; +} + +size_t Print::println(const char c[]) +{ + size_t n = print(c); + n += println(); + return n; +} + +size_t Print::println(char c) +{ + size_t n = print(c); + n += println(); + return n; +} + +size_t Print::println(unsigned char b, int base) +{ + size_t n = print(b, base); + n += println(); + return n; +} + +size_t Print::println(int num, int base) +{ + size_t n = print(num, base); + n += println(); + return n; +} + +size_t Print::println(unsigned int num, int base) +{ + size_t n = print(num, base); + n += println(); + return n; +} + +size_t Print::println(long num, int base) +{ + size_t n = print(num, base); + n += println(); + return n; +} + +size_t Print::println(unsigned long num, int base) +{ + size_t n = print(num, base); + n += println(); + return n; +} + +size_t Print::println(long long num, int base) +{ + size_t n = print(num, base); + n += println(); + return n; +} + +size_t Print::println(unsigned long long num, int base) +{ + size_t n = print(num, base); + n += println(); + return n; +} + +size_t Print::println(double num, int digits) +{ + size_t n = print(num, digits); + n += println(); + return n; +} + +size_t Print::println(struct tm * timeinfo, const char * format) +{ + size_t n = print(timeinfo, format); + n += println(); + return n; +} + +// Private Methods ///////////////////////////////////////////////////////////// + +size_t Print::printNumber(unsigned long n, uint8_t base) +{ + char buf[8 * sizeof(n) + 1]; // Assumes 8-bit chars plus zero byte. + char *str = &buf[sizeof(buf) - 1]; + + *str = '\0'; + + // prevent crash if called with base == 1 + if(base < 2) { + base = 10; + } + + do { + char c = n % base; + n /= base; + + *--str = c < 10 ? c + '0' : c + 'A' - 10; + } while (n); + + return write(str); +} + +size_t Print::printNumber(unsigned long long n, uint8_t base) +{ + char buf[8 * sizeof(n) + 1]; // Assumes 8-bit chars plus zero byte. + char* str = &buf[sizeof(buf) - 1]; + + *str = '\0'; + + // prevent crash if called with base == 1 + if (base < 2) { + base = 10; + } + + do { + auto m = n; + n /= base; + char c = m - base * n; + + *--str = c < 10 ? c + '0' : c + 'A' - 10; + } while (n); + + return write(str); +} + +size_t Print::printFloat(double number, uint8_t digits) +{ + size_t n = 0; + + if(isnan(number)) { + return print("nan"); + } + if(isinf(number)) { + return print("inf"); + } + if(number > 4294967040.0) { + return print("ovf"); // constant determined empirically + } + if(number < -4294967040.0) { + return print("ovf"); // constant determined empirically + } + + // Handle negative numbers + if(number < 0.0) { + n += print('-'); + number = -number; + } + + // Round correctly so that print(1.999, 2) prints as "2.00" + double rounding = 0.5; + for(uint8_t i = 0; i < digits; ++i) { + rounding /= 10.0; + } + + number += rounding; + + // Extract the integer part of the number and print it + unsigned long int_part = (unsigned long) number; + double remainder = number - (double) int_part; + n += print(int_part); + + // Print the decimal point, but only if there are digits beyond + if(digits > 0) { + n += print("."); + } + + // Extract digits from the remainder one at a time + while(digits-- > 0) { + remainder *= 10.0; + int toPrint = int(remainder); + n += print(toPrint); + remainder -= toPrint; + } + + return n; +} + +#endif diff --git a/src/Utilities/Print.h b/src/Utilities/Print.h new file mode 100644 index 0000000..ee3b1b7 --- /dev/null +++ b/src/Utilities/Print.h @@ -0,0 +1,114 @@ +/* + Print.h - Base class that provides print() and println() + Copyright (c) 2008 David A. Mellis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef ARDUINO + +#ifndef Print_h +#define Print_h + +#include +#include +#include + +#define DEC 10 +#define HEX 16 +#define OCT 8 +#define BIN 2 + +class Print +{ +private: + int write_error; + size_t printNumber(unsigned long, uint8_t); + size_t printNumber(unsigned long long, uint8_t); + size_t printFloat(double, uint8_t); +protected: + void setWriteError(int err = 1) + { + write_error = err; + } +public: + Print() : + write_error(0) + { + } + virtual ~Print() {} + int getWriteError() + { + return write_error; + } + void clearWriteError() + { + setWriteError(0); + } + + virtual size_t write(uint8_t) = 0; + size_t write(const char *str) + { + if(str == NULL) { + return 0; + } + return write((const uint8_t *) str, strlen(str)); + } + virtual size_t write(const uint8_t *buffer, size_t size); + size_t write(const char *buffer, size_t size) + { + return write((const uint8_t *) buffer, size); + } + + size_t printf(const char * format, ...) __attribute__ ((format (printf, 2, 3))); + + // add availableForWrite to make compatible with Arduino Print.h + // default to zero, meaning "a single write may block" + // should be overriden by subclasses with buffering + virtual int availableForWrite() { return 0; } + size_t print(const std::string &); + size_t print(const char[]); + size_t print(char); + size_t print(unsigned char, int = DEC); + size_t print(int, int = DEC); + size_t print(unsigned int, int = DEC); + size_t print(long, int = DEC); + size_t print(unsigned long, int = DEC); + size_t print(long long, int = DEC); + size_t print(unsigned long long, int = DEC); + size_t print(double, int = 2); + size_t print(struct tm * timeinfo, const char * format = NULL); + + size_t println(const std::string &s); + size_t println(const char[]); + size_t println(char); + size_t println(unsigned char, int = DEC); + size_t println(int, int = DEC); + size_t println(unsigned int, int = DEC); + size_t println(long, int = DEC); + size_t println(unsigned long, int = DEC); + size_t println(long long, int = DEC); + size_t println(unsigned long long, int = DEC); + size_t println(double, int = 2); + size_t println(struct tm * timeinfo, const char * format = NULL); + size_t println(void); + + virtual void flush() { /* Empty implementation for backward compatibility */ } + +}; + +#endif + +#endif diff --git a/src/Utilities/Stream.cpp b/src/Utilities/Stream.cpp new file mode 100644 index 0000000..56fc2a6 --- /dev/null +++ b/src/Utilities/Stream.cpp @@ -0,0 +1,339 @@ +/* + Stream.cpp - adds parsing methods to Stream class + Copyright (c) 2008 David A. Mellis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + Created July 2011 + parsing functions based on TextFinder library by Michael Margolis + */ + +#ifndef ARDUINO + +#include "Stream.h" +#include "OS.h" + +#define PARSE_TIMEOUT 1000 // default number of milli-seconds to wait +#define NO_SKIP_CHAR 1 // a magic char not found in a valid ASCII numeric field + +// private method to read stream with timeout +int Stream::timedRead() +{ + int c; + _startMillis = RNS::Utilities::OS::ltime(); + do { + c = read(); + if(c >= 0) { + return c; + } + } while(RNS::Utilities::OS::ltime() - _startMillis < _timeout); + return -1; // -1 indicates timeout +} + +// private method to peek stream with timeout +int Stream::timedPeek() +{ + int c; + _startMillis = RNS::Utilities::OS::ltime(); + do { + c = peek(); + if(c >= 0) { + return c; + } + } while(RNS::Utilities::OS::ltime() - _startMillis < _timeout); + return -1; // -1 indicates timeout +} + +// returns peek of the next digit in the stream or -1 if timeout +// discards non-numeric characters +int Stream::peekNextDigit() +{ + int c; + while(1) { + c = timedPeek(); + if(c < 0) { + return c; // timeout + } + if(c == '-') { + return c; + } + if(c >= '0' && c <= '9') { + return c; + } + read(); // discard non-numeric + } +} + +// Public Methods +////////////////////////////////////////////////////////////// + +void Stream::setTimeout(unsigned long timeout) // sets the maximum number of milliseconds to wait +{ + _timeout = timeout; +} +unsigned long Stream::getTimeout(void) { + return _timeout; +} + +// find returns true if the target string is found +bool Stream::find(const char *target) +{ + return findUntil(target, strlen(target), NULL, 0); +} + +// reads data from the stream until the target string of given length is found +// returns true if target string is found, false if timed out +bool Stream::find(const char *target, size_t length) +{ + return findUntil(target, length, NULL, 0); +} + +// as find but search ends if the terminator string is found +bool Stream::findUntil(const char *target, const char *terminator) +{ + return findUntil(target, strlen(target), terminator, strlen(terminator)); +} + +// reads data from the stream until the target string of the given length is found +// search terminated if the terminator string is found +// returns true if target string is found, false if terminated or timed out +bool Stream::findUntil(const char *target, size_t targetLen, const char *terminator, size_t termLen) +{ + if (terminator == NULL) { + MultiTarget t[1] = {{target, targetLen, 0}}; + return findMulti(t, 1) == 0 ? true : false; + } else { + MultiTarget t[2] = {{target, targetLen, 0}, {terminator, termLen, 0}}; + return findMulti(t, 2) == 0 ? true : false; + } +} + +int Stream::findMulti( struct Stream::MultiTarget *targets, int tCount) { + // any zero length target string automatically matches and would make + // a mess of the rest of the algorithm. + for (struct MultiTarget *t = targets; t < targets+tCount; ++t) { + if (t->len <= 0) + return t - targets; + } + + while (1) { + int c = timedRead(); + if (c < 0) + return -1; + + for (struct MultiTarget *t = targets; t < targets+tCount; ++t) { + // the simple case is if we match, deal with that first. + if (c == t->str[t->index]) { + if (++t->index == t->len) + return t - targets; + else + continue; + } + + // if not we need to walk back and see if we could have matched further + // down the stream (ie '1112' doesn't match the first position in '11112' + // but it will match the second position so we can't just reset the current + // index to 0 when we find a mismatch. + if (t->index == 0) + continue; + + int origIndex = t->index; + do { + --t->index; + // first check if current char works against the new current index + if (c != t->str[t->index]) + continue; + + // if it's the only char then we're good, nothing more to check + if (t->index == 0) { + t->index++; + break; + } + + // otherwise we need to check the rest of the found string + int diff = origIndex - t->index; + size_t i; + for (i = 0; i < t->index; ++i) { + if (t->str[i] != t->str[i + diff]) + break; + } + + // if we successfully got through the previous loop then our current + // index is good. + if (i == t->index) { + t->index++; + break; + } + + // otherwise we just try the next index + } while (t->index); + } + } + // unreachable + return -1; +} + +// returns the first valid (long) integer value from the current position. +// initial characters that are not digits (or the minus sign) are skipped +// function is terminated by the first character that is not a digit. +long Stream::parseInt() +{ + return parseInt(NO_SKIP_CHAR); // terminate on first non-digit character (or timeout) +} + +// as above but a given skipChar is ignored +// this allows format characters (typically commas) in values to be ignored +long Stream::parseInt(char skipChar) +{ + bool isNegative = false; + long value = 0; + int c; + + c = peekNextDigit(); + // ignore non numeric leading characters + if(c < 0) { + return 0; // zero returned if timeout + } + + do { + if(c == skipChar) { + } // ignore this charactor + else if(c == '-') { + isNegative = true; + } else if(c >= '0' && c <= '9') { // is c a digit? + value = value * 10 + c - '0'; + } + read(); // consume the character we got with peek + c = timedPeek(); + } while((c >= '0' && c <= '9') || c == skipChar); + + if(isNegative) { + value = -value; + } + return value; +} + +// as parseInt but returns a floating point value +float Stream::parseFloat() +{ + return parseFloat(NO_SKIP_CHAR); +} + +// as above but the given skipChar is ignored +// this allows format characters (typically commas) in values to be ignored +float Stream::parseFloat(char skipChar) +{ + bool isNegative = false; + bool isFraction = false; + long value = 0; + int c; + float fraction = 1.0; + + c = peekNextDigit(); + // ignore non numeric leading characters + if(c < 0) { + return 0; // zero returned if timeout + } + + do { + if(c == skipChar) { + } // ignore + else if(c == '-') { + isNegative = true; + } else if(c == '.') { + isFraction = true; + } else if(c >= '0' && c <= '9') { // is c a digit? + value = value * 10 + c - '0'; + if(isFraction) { + fraction *= 0.1f; + } + } + read(); // consume the character we got with peek + c = timedPeek(); + } while((c >= '0' && c <= '9') || c == '.' || c == skipChar); + + if(isNegative) { + value = -value; + } + if(isFraction) { + return value * fraction; + } else { + return value; + } +} + +// read characters from stream into buffer +// terminates if length characters have been read, or timeout (see setTimeout) +// returns the number of characters placed in the buffer +// the buffer is NOT null terminated. +// +size_t Stream::readBytes(char *buffer, size_t length) +{ + size_t count = 0; + while(count < length) { + int c = timedRead(); + if(c < 0) { + break; + } + *buffer++ = (char) c; + count++; + } + return count; +} + +// as readBytes with terminator character +// terminates if length characters have been read, timeout, or if the terminator character detected +// returns the number of characters placed in the buffer (0 means no valid data found) + +size_t Stream::readBytesUntil(char terminator, char *buffer, size_t length) +{ + if(length < 1) { + return 0; + } + size_t index = 0; + while(index < length) { + int c = timedRead(); + if(c < 0 || c == terminator) { + break; + } + *buffer++ = (char) c; + index++; + } + return index; // return number of characters, not including null terminator +} + +std::string Stream::readString() +{ + std::string ret; + int c = timedRead(); + while(c >= 0) { + ret += (char) c; + c = timedRead(); + } + return ret; +} + +std::string Stream::readStringUntil(char terminator) +{ + std::string ret; + int c = timedRead(); + while(c >= 0 && c != terminator) { + ret += (char) c; + c = timedRead(); + } + return ret; +} + +#endif diff --git a/src/Utilities/Stream.h b/src/Utilities/Stream.h new file mode 100644 index 0000000..c3c7a70 --- /dev/null +++ b/src/Utilities/Stream.h @@ -0,0 +1,143 @@ +/* + Stream.h - base class for character-based streams. + Copyright (c) 2010 David A. Mellis. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + parsing functions based on TextFinder library by Michael Margolis + */ + +#ifndef ARDUINO + +#ifndef Stream_h +#define Stream_h + +#include +#include "Print.h" + +// compatability macros for testing +/* + #define getInt() parseInt() + #define getInt(skipChar) parseInt(skipchar) + #define getFloat() parseFloat() + #define getFloat(skipChar) parseFloat(skipChar) + #define getString( pre_string, post_string, buffer, length) + readBytesBetween( pre_string, terminator, buffer, length) + */ + +class Stream: public Print +{ +protected: + unsigned long _timeout; // number of milliseconds to wait for the next char before aborting timed read + unsigned long _startMillis; // used for timeout measurement + int timedRead(); // private method to read stream with timeout + int timedPeek(); // private method to peek stream with timeout + int peekNextDigit(); // returns the next numeric digit in the stream or -1 if timeout + +public: + virtual int available() = 0; + virtual int read() = 0; + virtual int peek() = 0; + + Stream():_startMillis(0) + { + _timeout = 1000; + } + virtual ~Stream() {} + +// parsing methods + + void setTimeout(unsigned long timeout); // sets maximum milliseconds to wait for stream data, default is 1 second + unsigned long getTimeout(void); + + bool find(const char *target); // reads data from the stream until the target string is found + bool find(uint8_t *target) + { + return find((char *) target); + } + // returns true if target string is found, false if timed out (see setTimeout) + + bool find(const char *target, size_t length); // reads data from the stream until the target string of given length is found + bool find(const uint8_t *target, size_t length) + { + return find((char *) target, length); + } + // returns true if target string is found, false if timed out + + bool find(char target) + { + return find (&target, 1); + } + + bool findUntil(const char *target, const char *terminator); // as find but search ends if the terminator string is found + bool findUntil(const uint8_t *target, const char *terminator) + { + return findUntil((char *) target, terminator); + } + + bool findUntil(const char *target, size_t targetLen, const char *terminate, size_t termLen); // as above but search ends if the terminate string is found + bool findUntil(const uint8_t *target, size_t targetLen, const char *terminate, size_t termLen) + { + return findUntil((char *) target, targetLen, terminate, termLen); + } + + long parseInt(); // returns the first valid (long) integer value from the current position. + // initial characters that are not digits (or the minus sign) are skipped + // integer is terminated by the first character that is not a digit. + + float parseFloat(); // float version of parseInt + + virtual size_t readBytes(char *buffer, size_t length); // read chars from stream into buffer + virtual size_t readBytes(uint8_t *buffer, size_t length) + { + return readBytes((char *) buffer, length); + } + // terminates if length characters have been read or timeout (see setTimeout) + // returns the number of characters placed in the buffer (0 means no valid data found) + + size_t readBytesUntil(char terminator, char *buffer, size_t length); // as readBytes with terminator character + size_t readBytesUntil(char terminator, uint8_t *buffer, size_t length) + { + return readBytesUntil(terminator, (char *) buffer, length); + } + // terminates if length characters have been read, timeout, or if the terminator character detected + // returns the number of characters placed in the buffer (0 means no valid data found) + + // Arduino String functions to be added here + virtual std::string readString(); + std::string readStringUntil(char terminator); + +protected: + long parseInt(char skipChar); // as above but the given skipChar is ignored + // as above but the given skipChar is ignored + // this allows format characters (typically commas) in values to be ignored + + float parseFloat(char skipChar); // as above but the given skipChar is ignored + + struct MultiTarget { + const char *str; // string you're searching for + size_t len; // length of string you're searching for + size_t index; // index used by the search routine. + }; + + // This allows you to search for an arbitrary number of strings. + // Returns index of the target that is found first or -1 if timeout occurs. + int findMulti(struct MultiTarget *targets, int tCount); + +}; + +#endif + +#endif diff --git a/test/Test.cpp b/test/Test.cpp deleted file mode 100644 index dff1cd2..0000000 --- a/test/Test.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include - -#include -#include -#include -#include -#include -#include -#include - -// Imported from Crypto.cpp -extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); - -void testCrc() { - char data[32]; - uint8_t crc; - strcpy(data, "foo"); - crc = crypto_crc8(0, data, sizeof(data)); - TEST_ASSERT_EQUAL_UINT8(174, crc); - strcpy(data, "bar"); - crc = crypto_crc8(0, data, sizeof(data)); - TEST_ASSERT_EQUAL_UINT8(63, crc); - strcpy(data, "foo"); - crc = crypto_crc8(0, data, sizeof(data)); - TEST_ASSERT_EQUAL_UINT8(174, crc); -} - -#ifndef ARDUINO -unsigned long millis() { - timeval time; - ::gettimeofday(&time, NULL); - return (uint64_t)(time.tv_sec * 1000) + (uint64_t)(time.tv_usec / 1000); - return 0; -} -#endif - -#ifdef ARDUINO -void testsleep(float seconds) { delay((uint32_t)(seconds * 1000)); } -#else -void testsleep(float seconds) { timespec time; time.tv_sec = (time_t)(seconds); time.tv_nsec = (seconds - (float)time.tv_sec) * 1000000000; ::nanosleep(&time, nullptr); } -#endif - -uint64_t timeOffset = 0; - -uint64_t ltime() { - // handle roll-over of 32-bit millis (approx. 49 days) - static uint32_t low32, high32; - uint32_t new_low32 = millis(); - if (new_low32 < low32) high32++; - low32 = new_low32; - return ((uint64_t)high32 << 32 | low32) + timeOffset; -} - -void testTime() { - //uint64_t start = RNS::Utilities::OS::ltime(); - //RNS::Utilities::OS::sleep(0.1); - //TEST_ASSERT_TRUE((RNS::Utilities::OS::ltime() - start) > 100); - uint64_t start = ltime(); - testsleep(0.1); - uint64_t end = ltime(); - TEST_ASSERT_TRUE((end - start) > 50); - TEST_ASSERT_TRUE((end - start) < 200); -} - -void testConvert() { - //uint64_t time = ltime(); - //printf("time: %lld\n", time); - - uint64_t num = 1234567890; - TEST_ASSERT_EQUAL_UINT64(1234567890, num); - - char str[16]; - snprintf(str, 16, "%lld", num); - TEST_ASSERT_EQUAL_STRING("1234567890", str); - - char* buf = (char*)# - - //uint64_t newnum = (uint64_t)(*buf); - uint64_t newnum = *(uint64_t*)buf; - TEST_ASSERT_EQUAL_UINT64(1234567890, newnum); -} - -int main(void) -{ - UNITY_BEGIN(); - //RUN_TEST(testCrc); - //RUN_TEST(testTime); - RUN_TEST(testConvert); - return UNITY_END(); -}