5 Commits
Author SHA1 Message Date
Chad Attermann 23b285f3bf Initial implementation of Base64 support in Bytes 2026-03-08 12:25:36 -06:00
Chad Attermann 491fbd034e Fixed unit test failures in Linux. 2026-03-06 17:25:41 -07:00
Chad Attermann c69087ba40 Merge pull request #31 from attermann/psram_allocator
Introduces a flexible two-class allocator architecture (RNS_DEFAULT_ALLOCATOR and RNS_CONTAINER_ALLOCATOR) supporting heap, PSRAM, and TLSF pool variants for fine-grained control over embedded memory layout.

New Memory.h/cpp with ContainerAllocator, heap/PSRAM/pool allocator types, and heap stats reporting
IdentityTable and PathTable now use ContainerAllocator
Replaced RNS_USE_TLSF/RNS_USE_ALLOCATOR/RNS_USE_PSRAM flags with per-class allocator flags (RNS_DEFAULT_ALLOCATOR, RNS_CONTAINER_ALLOCATOR)
Added ESP32 PSRAM allocator support (RNS_PSRAM_ALLOCATOR, RNS_PSRAM_POOL_ALLOCATOR)
Added Transport::get_path()/remove_path() helpers
Added loop callback (set_loop_callback) to enable more responsive app during long operations (like clean_cache)
Aded guard against re-entrancy to clean_cache()
Added callback option to list_directory() to avoid heap allocation
Added OOM auto-restart (ESP.restart/NVIC_SystemReset) in Interface send/receive and Reticulum loop.
Renamed setLogCallback to set_log_callback
Made Link/Identity static members private
Added native14 env to CI and platformio.ini
Bumped version to 0.2.10
2026-03-06 17:10:37 -07:00
Chad Attermann 4d6f0b9de2 Added dual-class PSRAM/TLSF allocator system and refactored memory management
Introduces a flexible two-class allocator architecture (RNS_DEFAULT_ALLOCATOR and RNS_CONTAINER_ALLOCATOR) supporting heap, PSRAM, and TLSF pool variants for fine-grained control over embedded memory layout.

- New Memory.h/cpp with ContainerAllocator<T>, heap/PSRAM/pool allocator types, and heap stats reporting
- IdentityTable and PathTable now use ContainerAllocator
- Replaced RNS_USE_TLSF/RNS_USE_ALLOCATOR/RNS_USE_PSRAM flags with per-class allocator flags (RNS_DEFAULT_ALLOCATOR, RNS_CONTAINER_ALLOCATOR)
- Added ESP32 PSRAM allocator support (RNS_PSRAM_ALLOCATOR, RNS_PSRAM_POOL_ALLOCATOR)
- Added Transport::get_path()/remove_path() helpers
- Added loop callback (set_loop_callback) to enable more responsive app during long operations (like clean_cache)
- Aded guard against re-entrancy to clean_cache()
- Added callback option to list_directory() to avoid heap allocation
- Added OOM auto-restart (ESP.restart/NVIC_SystemReset) in Interface send/receive and Reticulum loop.
- Renamed setLogCallback to set_log_callback
- Made Link/Identity static members private
- Added native14 env to CI and platformio.ini
- Bumped version to 0.2.10
2026-03-06 16:43:04 -07:00
Chad Attermann 49ccbc2827 Major bug fixes and performance enhancements
- Fixed bug in path table loading from flash storage wherein the raw
(packed) announce packet associated with each path entry was not being
unpacked prior to use.
- Fixed bug in path table entry announce packet loading where critical
changes to the announce packet (like hops increment) was being
overwriteen each time packet was re-loaded from cache.
- Optimized path table entries to lazy-load both announce packet and
receive interface so that memory is consumed by these structures until
if/when the path is actually used.
- Updated several global timers and sizes to match new RNS 1.x values.
- Bumped version to 0.2.9
2026-03-03 17:53:06 -07:00
38 changed files with 1943 additions and 1234 deletions

No files matched your search

+1 -1
View File
@@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
env: [native, native17, native20]
env: [native, native14, native17, native20]
steps:
- uses: actions/checkout@v4
+27 -3
View File
@@ -18,9 +18,33 @@ This API is dependent on the following external libraries:
- `-DRNS_MEM_LOG` Used to enable logging of low-level memory operations for debug purposes
- `-DRNS_USE_FS` Used to enable use of file system by RNS for persistence
- `-DRNS_PERSIST_PATHS` Used to enable persistence of RNS paths in file system (also requires `-DRNS_USE_FS`)
- `-DRNS_USE_TLSF=1` Enables the use of the TLSF (Two-Level Segregate Fit) dynamic memory manager for efficient management of constrained MCU memory with minimal fragmentation. Currently only required on NRF52 boards (ESP32 already uses TLSF internally).
- `-RNS_TLSF_BUFFER_SIZ=N` Defines the TLSF memory pool buffer size (N bytes, default 0 which means dynamic)
- `-DRNS_USE_ALLOCATOR=1` Enables the replacement of default new/delete operators with custom implementations that take advantage of optimized memory managers (eg, TLSF). Currently only required on NRF52 boards (ESP32 already uses TLSF internally).
## Memory Management Build Options
Two classes of memory allocator are defined; the container allocator (`RNS_CONTAINER_ALLOCATOR`) which is used for certain long-lived STL containers (e.g. path table), and the default allocator (`RNS_DEFAULT_ALLOCATOR`) which is used for all other C++ memory allocation (new/delete).
Each class of allocator can be configured to use a separate type of allocator. Available memory allocators are:
- `RNS_HEAP_ALLOCATOR`: Basic allocator that uses default system HEAP.
- `RNS_HEAP_POOL_ALLOCATOR`: Optimized TLSF managed HEAP buffer
- `RNS_PSRAM_ALLOCATOR`: Basic allocator that uses PSRAM memory (if PSRAM is available)
- `RNS_PSRAM_POOL_ALLOCATOR`: Optimized TLSF managed PSRAM buffer (if PSRAM is available)
Each class of allocator pool can have a separate buffer size:
- `RNS_HEAP_POOL_BUFFER_SIZE=N` Defines the HEAP TLSF memory pool buffer size (N bytes, default 0 which means dynamic)
- `RNS_PSRAM_POOL_BUFFER_SIZE=N` Defines the PSRAM TLSF memory pool buffer size (N bytes, default 0 which means dynamic)
"POOL" allocators use TLSF (Two-Level Segregate Fit) for efficient management of constrained MCU memory with minimal fragmentation.
The allocator for each class can be configured using build flags in `platformio.ini, for example:
```
[env]
build_flags =
-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_ALLOCATOR
-DRNS_CONTAINER_ALLOCATOR=RNS_PSRAM_POOL_ALLOCATOR
```
NOTE: Currently `-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_POOL_ALLOCATOR` is only required on NRF52 boards since ESP32 already uses TLSF internally.
## Building
@@ -247,14 +247,13 @@ void UniversalFileSystem::listDir(const char* dir) {
//if (!file) {
File* file = new File(SPIFFS.open(file_path, mode));
if (file == nullptr || !(*file)) {
if (file != nullptr) delete 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 UniversalFileStream(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;
@@ -274,7 +273,10 @@ void UniversalFileSystem::listDir(const char* dir) {
ERRORF("open_file: unsupported mode %d", file_mode);
return {RNS::Type::NONE};
}
if (!file->open(file_path, mode)) {
//File file = File(InternalFS);
File* file = new File(InternalFS);
if (file == nullptr || !file->open(file_path, mode)) {
if (file != nullptr) delete file;
ERRORF("open_file: failed to open output file %s", file_path);
return {RNS::Type::NONE};
}
@@ -430,7 +432,7 @@ void UniversalFileSystem::listDir(const char* dir) {
#endif
}
/*virtua*/ std::list<std::string> UniversalFileSystem::list_directory(const char* directory_path) {
/*virtua*/ std::list<std::string> UniversalFileSystem::list_directory(const char* directory_path, Callbacks::DirectoryListing callback /*= nullptr*/) {
TRACEF("list_directory: listing directory %s", directory_path);
std::list<std::string> files;
#ifdef ARDUINO
@@ -447,7 +449,8 @@ void UniversalFileSystem::listDir(const char* dir) {
while (file) {
if (!file.isDirectory()) {
char* name = (char*)file.name();
files.push_back(name);
if (callback) callback(name);
else files.push_back(name);
}
// CBA Following close required to avoid leaking memory
file.close();
@@ -42,7 +42,7 @@ public:
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<std::string> list_directory(const char* directory_path);
virtual std::list<std::string> list_directory(const char* directory_path, Callbacks::DirectoryListing callback = nullptr);
virtual size_t storage_size();
virtual size_t storage_available();
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "microReticulum",
"version": "0.2.8",
"version": "0.2.10",
"description": "Port of Reticulum Network Stack to C++ specifically but not exclusively targeting 32-bit and better MCUs",
"keywords": "reticulum, rns, mesh, embedded, mcu, esp32, nrf52, native",
"repository":
+1 -1
View File
@@ -1,5 +1,5 @@
name=microReticulum
version=0.2.8
version=0.2.10
author=Chad Attermann <attermann@gmail.com>
maintainer=Chad Attermann <attermann@gmail.com>
sentence=Port of Reticulum Network Stack to C++
+52 -16
View File
@@ -22,6 +22,9 @@ build_flags =
-Wno-missing-field-initializers
-Wno-format
-Wno-unused-parameter
-Wno-unused-variable
-Wno-unused-but-set-variable
-Wno-unused-private-field
-Isrc
-DLIBRARY_TEST
;-DNDEBUG
@@ -45,6 +48,19 @@ lib_deps =
${env.lib_deps}
lib_compat_mode = off
[env:native14]
platform = native
build_unflags =
${env.build_unflags}
-std=gnu++11
build_flags =
${env.build_flags}
-std=gnu++14
-DNATIVE
lib_deps =
${env.lib_deps}
lib_compat_mode = off
[env:native17]
platform = native
build_unflags =
@@ -73,9 +89,13 @@ lib_compat_mode = off
[env:native_debug]
platform = native
build_unflags =
${env.build_unflags}
-std=gnu++11
build_flags =
${env.build_flags}
-std=gnu++11
;-std=gnu++11
-std=gnu++17
-DNATIVE
; CBA TEST
;-fsanitize=address
@@ -83,31 +103,40 @@ build_flags =
-g
;-O1
-O0
;-DRNS_MEM_LOG
-DRNS_USE_ALLOCATOR=1
-DRNS_USE_TLSF=1
-Wunused-parameter
-Wunused-variable
-Wunused-but-set-variable
-Wunused-private-field
;-DBOARD_HAS_PSRAM=1
;-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_ALLOCATOR
-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_POOL_ALLOCATOR
-DRNS_CONTAINER_ALLOCATOR=RNS_ALTHEAP_POOL_ALLOCATOR
;-DRNS_HEAP_POOL_BUFFER_SIZE=81920
;-DRNS_HEAP_POOL_BUFFER_SIZE=102400
-DRNS_HEAP_POOL_BUFFER_SIZE=204800
;-DRNS_HEAP_POOL_BUFFER_SIZE=307200
;-DRNS_HEAP_POOL_BUFFER_SIZE=409600
;-DRNS_HEAP_POOL_BUFFER_SIZE=512000
;-DRNS_HEAP_POOL_BUFFER_SIZE=614400
;-DRNS_HEAP_POOL_BUFFER_SIZE=1024000
-DRNS_ALTHEAP_POOL_BUFFER_SIZE=2048000
-DTLSF_DEBUG=1
;-DRNS_TLSF_BUFFER_SIZE=81920
;-DRNS_TLSF_BUFFER_SIZE=102400
-DRNS_TLSF_BUFFER_SIZE=204800
;-DRNS_TLSF_BUFFER_SIZE=307200
;-DRNS_TLSF_BUFFER_SIZE=409600
;-DRNS_TLSF_BUFFER_SIZE=512000
;-DRNS_TLSF_BUFFER_SIZE=614400
;-DRNS_TLSF_BUFFER_SIZE=1024000
;-DRNS_MEM_LOG
lib_deps =
${env.lib_deps}
lib_compat_mode = off
test_flags = -vvv
[env:embedded]
framework = arduino
upload_speed = 460800
build_unflags =
${env.build_unflags}
;-std=gnu++11
-std=gnu++11
;-fno-rtti
build_flags =
${env.build_flags}
;-std=gnu++17
-std=gnu++17
lib_deps =
${env.lib_deps}
@@ -168,6 +197,13 @@ build_flags =
-DBOARD_ESP32
-DMSGPACK_USE_BOOST=OFF
-DARDUINO_USB_CDC_ON_BOOT=1
; CBA TEST
-DBOARD_HAS_PSRAM=1
;-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_ALLOCATOR
-DRNS_DEFAULT_ALLOCATOR=RNS_PSRAM_ALLOCATOR
;-DRNS_CONTAINER_ALLOCATOR=RNS_PSRAM_ALLOCATOR
-DRNS_CONTAINER_ALLOCATOR=RNS_PSRAM_POOL_ALLOCATOR
-DRNS_PSRAM_POOL_BUFFER_SIZE=2048000
lib_deps =
${env:embedded.lib_deps}
monitor_filters = esp32_exception_decoder
@@ -184,8 +220,8 @@ build_flags =
-I variants/rak4630
-fexceptions
-DBOARD_NRF52
-DRNS_USE_ALLOCATOR=1
-DRNS_USE_TLSF=1
-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_POOL_ALLOCATOR
-DRNS_HEAP_POOL_BUFFER_SIZE=204800
-DMSGPACK_USE_BOOST=OFF
lib_deps =
${env:embedded.lib_deps}
+83
View File
@@ -162,6 +162,18 @@ void Bytes::appendHex(const uint8_t* hex, size_t hex_size) {
const char hex_upper_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
const char hex_lower_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
static const char base64_chars[65] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static int8_t b64_decode_char(uint8_t c) {
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return -1; // invalid / padding
}
std::string RNS::hexFromByte(uint8_t byte, bool upper /*= true*/) {
std::string hex;
if (upper) {
@@ -193,6 +205,77 @@ std::string Bytes::toHex(bool upper /*= false*/) const {
return hex;
}
std::string Bytes::toBase64() const {
if (!_data) {
return "";
}
const uint8_t* in = _data->data();
size_t in_size = _data->size();
std::string out;
out.reserve(((in_size + 2) / 3) * 4);
for (size_t i = 0; i < in_size; i += 3) {
uint8_t b0 = in[i];
uint8_t b1 = (i + 1 < in_size) ? in[i + 1] : 0;
uint8_t b2 = (i + 2 < in_size) ? in[i + 2] : 0;
out += base64_chars[(b0 >> 2) & 0x3F];
out += base64_chars[((b0 << 4) | (b1 >> 4)) & 0x3F];
out += (i + 1 < in_size) ? base64_chars[((b1 << 2) | (b2 >> 6)) & 0x3F] : '=';
out += (i + 2 < in_size) ? base64_chars[b2 & 0x3F] : '=';
}
return out;
}
void Bytes::assignBase64(const uint8_t* b64, size_t b64_size) {
if (b64 == nullptr || b64_size == 0) {
_data = nullptr;
_exclusive = true;
return;
}
// strip trailing padding
while (b64_size > 0 && b64[b64_size - 1] == '=') {
--b64_size;
}
size_t out_size = (b64_size * 3) / 4;
exclusiveData(false, out_size);
_data->clear();
for (size_t i = 0; i < b64_size; ) {
int8_t v0 = (i < b64_size) ? b64_decode_char(b64[i++]) : 0;
int8_t v1 = (i < b64_size) ? b64_decode_char(b64[i++]) : 0;
int8_t v2 = (i < b64_size) ? b64_decode_char(b64[i++]) : -1;
int8_t v3 = (i < b64_size) ? b64_decode_char(b64[i++]) : -1;
if (v0 < 0 || v1 < 0) break;
_data->push_back((uint8_t)((v0 << 2) | (v1 >> 4)));
if (v2 >= 0) _data->push_back((uint8_t)((v1 << 4) | (v2 >> 2)));
if (v3 >= 0) _data->push_back((uint8_t)((v2 << 6) | v3));
}
if (_data->empty()) {
_data = nullptr;
_exclusive = true;
}
}
void Bytes::appendBase64(const uint8_t* b64, size_t b64_size) {
if (b64 == nullptr || b64_size == 0) {
return;
}
// strip trailing padding
while (b64_size > 0 && b64[b64_size - 1] == '=') {
--b64_size;
}
size_t out_size = (b64_size * 3) / 4;
exclusiveData(true, size() + out_size);
for (size_t i = 0; i < b64_size; ) {
int8_t v0 = (i < b64_size) ? b64_decode_char(b64[i++]) : 0;
int8_t v1 = (i < b64_size) ? b64_decode_char(b64[i++]) : 0;
int8_t v2 = (i < b64_size) ? b64_decode_char(b64[i++]) : -1;
int8_t v3 = (i < b64_size) ? b64_decode_char(b64[i++]) : -1;
if (v0 < 0 || v1 < 0) break;
_data->push_back((uint8_t)((v0 << 2) | (v1 >> 4)));
if (v2 >= 0) _data->push_back((uint8_t)((v1 << 4) | (v2 >> 2)));
if (v3 >= 0) _data->push_back((uint8_t)((v2 << 6) | v3));
}
}
// mid
Bytes Bytes::mid(size_t beginpos, size_t len) const {
if (!_data || beginpos >= size()) {
+16 -5
View File
@@ -1,6 +1,7 @@
#pragma once
#include "Log.h"
#include "Utilities/Memory.h"
#include <ArduinoJson.h>
@@ -40,9 +41,9 @@ namespace RNS {
class Bytes {
private:
//typedef std::vector<uint8_t> Data;
using Data = std::vector<uint8_t>;
//typedef std::shared_ptr<Data> SharedData;
// CBA Need to fix msgpack serialize/deserialize before enabling ContainerAllocator
//using Data = std::vector<uint8_t, Utilities::Memory::ContainerAllocator<uint8_t>>;
using SharedData = std::shared_ptr<Data>;
public:
@@ -309,6 +310,13 @@ MEM("Creating from data-move...");
void appendHex(const uint8_t* hex, size_t hex_size);
inline void appendHex(const char* hex) { if (!hex) return; appendHex((uint8_t*)hex, strlen(hex)); }
void assignBase64(const uint8_t* b64, size_t b64_size);
inline void assignBase64(const char* b64) { if (!b64) return; assignBase64((uint8_t*)b64, strlen(b64)); }
void appendBase64(const uint8_t* b64, size_t b64_size);
inline void appendBase64(const char* b64) { if (!b64) return; appendBase64((uint8_t*)b64, strlen(b64)); }
inline uint8_t* writable(size_t size) {
if (size > 0) {
// create exclusive data with reserved capacity
@@ -353,6 +361,7 @@ MEM("Creating from data-move...");
inline std::string toString() const { if (!_data) return ""; return {(const char*)data(), size()}; }
std::string toHex(bool upper = false) const;
std::string toBase64() const;
Bytes mid(size_t beginpos, size_t len) const;
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}; }
@@ -408,6 +417,7 @@ MEM("Creating from data-move...");
inline std::string stringFromBytes(const Bytes& bytes) { return bytes.toString(); }
inline std::string hexFromBytes(const Bytes& bytes) { return bytes.toHex(); }
inline std::string base64FromBytes(const Bytes& bytes) { return bytes.toBase64(); }
std::string hexFromByte(uint8_t byte, bool upper = true);
}
@@ -433,15 +443,16 @@ inline RNS::Bytes& operator << (RNS::Bytes& lhbytes, const char* rhstr) {
return lhbytes;
}
//CBA TODO Standardize where custom object de/serialization lives
namespace ArduinoJson {
// Serialize
inline bool convertToJson(const RNS::Bytes& src, JsonVariant dst) {
return dst.set(src.toHex());
return dst.set(src.toBase64());
}
// Deserialize
inline void convertFromJson(JsonVariantConst src, RNS::Bytes& dst) {
const char* hex = src.as<const char*>();
if (hex) dst.assignHex(hex);
const char* b64 = src.as<const char*>();
if (b64) dst.assignBase64(b64);
}
inline bool canConvertFromJson(JsonVariantConst src, const RNS::Bytes&) {
return src.is<const char*>();
+3 -3
View File
@@ -289,7 +289,7 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In
_object->_path_responses.insert({tag, {OS::time(), announce_data}});
}
catch (const std::bad_alloc&) {
ERRORF("announce: bad_alloc - out of memory, path response not stored for %s", _object->_hash.toHex().c_str());
ERRORF("announce: bad_alloc - OUT OF MEMORY, path response not stored for %s", _object->_hash.toHex().c_str());
}
catch (const std::exception& e) {
ERRORF("announce: exception storing path response: %s", e.what());
@@ -317,7 +317,7 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In
}
}
catch (const std::bad_alloc&) {
ERRORF("announce: bad_alloc - out of memory, announce not sent for %s", _object->_hash.toHex().c_str());
ERRORF("announce: bad_alloc - OUT OF MEMORY, announce not sent for %s", _object->_hash.toHex().c_str());
return {Type::NONE};
}
catch (const std::exception& e) {
@@ -407,7 +407,7 @@ TRACE("***** Accepting link request");
_object->_links.insert(link);
}
catch (const std::bad_alloc&) {
ERROR("incoming_link_request: bad_alloc - out of memory, link not tracked");
ERROR("incoming_link_request: bad_alloc - OUT OF MEMORY, link not tracked");
}
catch (const std::exception& e) {
ERRORF("incoming_link_request: exception tracking link: %s", e.what());
+12 -2
View File
@@ -8,12 +8,19 @@
#include <list>
#include <memory>
#include <cassert>
#include <functional>
#include <stdint.h>
namespace RNS {
class FileSystemImpl {
public:
struct Callbacks {
//using DirectoryListing = void(*)(const char* file_name);
using DirectoryListing = std::function<void(const char*)>;
};
protected:
FileSystemImpl() { MEMF("FileSystem::FileSystemImpl object created, this: 0x%X", this); }
public:
@@ -31,7 +38,7 @@ namespace RNS {
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<std::string> list_directory(const char* directory_path) = 0;
virtual std::list<std::string> list_directory(const char* directory_path, Callbacks::DirectoryListing callback = nullptr) = 0;
virtual size_t storage_size() = 0;
virtual size_t storage_available() = 0;
@@ -40,6 +47,9 @@ namespace RNS {
class FileSystem {
public:
using Callbacks = FileSystemImpl::Callbacks;
public:
FileSystem(Type::NoneConstructor none) {
MEMF("FileSystem NONE object created, this: 0x%X, impl: 0x%X", this, _impl.get());
@@ -103,7 +113,7 @@ namespace RNS {
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<std::string> list_directory(const char* directory_path) { assert(_impl); return _impl->list_directory(directory_path); }
inline std::list<std::string> list_directory(const char* directory_path, Callbacks::DirectoryListing callback = nullptr) { assert(_impl); return _impl->list_directory(directory_path, callback); }
inline size_t storage_size() { assert(_impl); return _impl->storage_size(); }
inline size_t storage_available() { assert(_impl); return _impl->storage_available(); }
+4 -14
View File
@@ -23,7 +23,7 @@ using namespace RNS::Utilities;
#define RNS_KNOWN_DESTINATIONS_MAX 100
#endif
/*static*/ std::map<Bytes, Identity::IdentityEntry> Identity::_known_destinations;
/*static*/ Identity::IdentityTable Identity::_known_destinations;
/*static*/ bool Identity::_saving_known_destinations = false;
// CBA
// CBA ACCUMULATES
@@ -205,7 +205,7 @@ Can be used to load previously created and saved identities into Reticulum.
cull_known_destinations();
}
catch (const std::bad_alloc&) {
ERRORF("remember: bad_alloc - out of memory, identity not stored for %s", destination_hash.toHex().c_str());
ERRORF("remember: bad_alloc - OUT OF MEMORY, identity not stored for %s", destination_hash.toHex().c_str());
}
catch (const std::exception& e) {
ERRORF("remember: exception storing identity: %s", e.what());
@@ -319,19 +319,9 @@ Recall last heard app_data for a destination hash.
file = open(RNS.Reticulum.storagepath+"/known_destinations","wb")
umsgpack.dump(Identity.known_destinations, file)
file.close()
DEBUGF("Saved known destinations to storage in %.3f seconds", OS::round(OS::time() - save_start, 3));
*/
std::string time_str;
double save_time = OS::time() - save_start;
if (save_time < 1) {
time_str = std::to_string((int)(save_time*1000)) + " ms";
}
else {
time_str = std::to_string(OS::round(save_time, 1)) + " s";
}
DEBUGF("Saved known destinations to storage in %s", time_str.c_str());
success = true;
}
catch (std::exception& e) {
@@ -394,7 +384,7 @@ Recall last heard app_data for a destination hash.
DEBUGF("Removed %d path(s) from known destinations", count);
}
catch (const std::bad_alloc& e) {
ERROR("cull_known_destinations: bad_alloc - out of memory building sort index, falling back to single erase");
ERROR("cull_known_destinations: bad_alloc - OUT OF MEMORY building sort index, falling back to single erase");
// Fallback: std::min_element does no heap allocation — erase one oldest entry
auto oldest = std::min_element(
_known_destinations.begin(), _known_destinations.end(),
+7 -2
View File
@@ -7,6 +7,7 @@
#include "Cryptography/Ed25519.h"
#include "Cryptography/X25519.h"
#include "Cryptography/Token.h"
#include "Utilities/Memory.h"
#include <map>
#include <string>
@@ -36,9 +37,11 @@ namespace RNS {
Bytes _public_key;
Bytes _app_data;
};
//using IdentityTable = std::map<Bytes, IdentityEntry>;
using IdentityTable = std::map<Bytes, IdentityEntry, std::less<Bytes>, Utilities::Memory::ContainerAllocator<std::pair<const Bytes, IdentityEntry>>>;
public:
static std::map<Bytes, IdentityEntry> _known_destinations;
private:
static IdentityTable _known_destinations;
static bool _saving_known_destinations;
// CBA
static uint16_t _known_destinations_maxsize;
@@ -197,6 +200,8 @@ namespace RNS {
};
std::shared_ptr<Object> _object;
// CBA For access to private static members by Transport class
friend class Transport;
};
}
+41 -4
View File
@@ -25,16 +25,53 @@ void InterfaceImpl::handle_incoming(const Bytes& data) {
Transport::inbound(data, interface);
}
void Interface::handle_incoming(const Bytes& data) {
//TRACEF("Interface.handle_incoming: data: %s", data.toHex().c_str());
TRACE("Interface.handle_incoming");
void Interface::send_outgoing(const Bytes& data) {
assert(_impl);
//TRACEF("Interface.send_outgoing: data: %s", data.toHex().c_str());
//TRACE("Interface.send_outgoing");
// Catch exceptions from calls into Interface implementation
try {
_impl->send_outgoing(data);
}
catch (const std::bad_alloc&) {
ERROR("Interface::send_outgoing: bad_alloc - OUT OF MEMORY");
// Critical OOM, restarting
#if defined(ESP32)
ESP.restart();
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
NVIC_SystemReset();
#endif
}
catch (std::exception& e) {
ERRORF("Interface::send_outgoing: %s", e.what());
}
}
void Interface::handle_incoming(const Bytes& data) {
assert(_impl);
//TRACEF("Interface.handle_incoming: data: %s", data.toHex().c_str());
//TRACE("Interface.handle_incoming");
/*
_impl->_rxb += data.size();
// Pass data on to transport for handling
Transport::inbound(data, *this);
*/
_impl->handle_incoming(data);
// Catch exceptions from calls into Interface implementation
try {
_impl->handle_incoming(data);
}
catch (const std::bad_alloc&) {
ERROR("Interface::handle_incoming: bad_alloc - OUT OF MEMORY");
// Critical OOM, restarting
#if defined(ESP32)
ESP.restart();
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
NVIC_SystemReset();
#endif
}
catch (std::exception& e) {
ERRORF("Interface::handle_incoming: %s", e.what());
}
}
void Interface::process_announce_queue() {
+2 -2
View File
@@ -161,9 +161,9 @@ namespace RNS {
inline void add_announce(AnnounceEntry& entry) { assert(_impl); _impl->_announce_queue.push_back(entry); }
protected:
inline void send_outgoing(const Bytes& data) { assert(_impl); _impl->send_outgoing(data); }
// Internal method to handle data going out on interface and pass on to impl
void send_outgoing(const Bytes& data);
public:
//inline void handle_incoming(const Bytes& data) { assert(_impl); _impl->handle_incoming(data); }
// Public method to handle data coming in on interface and pass on to impl
void handle_incoming(const Bytes& data);
+3 -1
View File
@@ -130,7 +130,7 @@ namespace RNS {
friend class Link;
};
public:
private:
static uint8_t resource_strategies;
static std::set<RNS::Type::Link::link_mode> ENABLED_MODES;
static RNS::Type::Link::link_mode MODE_DEFAULT;
@@ -265,6 +265,8 @@ namespace RNS {
protected:
std::shared_ptr<LinkData> _object;
// CBA For access to private static members by LinkData class
friend class LinkData;
};
}
+1 -1
View File
@@ -72,7 +72,7 @@ LogLevel RNS::loglevel() {
return _level;
}
void RNS::setLogCallback(log_callback on_log /*= nullptr*/) {
void RNS::set_log_callback(log_callback on_log /*= nullptr*/) {
_on_log = on_log;
}
+1 -1
View File
@@ -75,7 +75,7 @@ namespace RNS {
void loglevel(LogLevel level);
LogLevel loglevel();
void setLogCallback(log_callback on_log = nullptr);
void set_log_callback(log_callback on_log = nullptr);
void doLog(LogLevel level, const char* msg);
inline void doLog(LogLevel level, const char* msg, va_list vlist) { char buf[RNS_LOG_BUFFER_SIZE]; vsnprintf(buf, sizeof(buf), msg, vlist); doLog(level, buf); }
+8 -7
View File
@@ -23,7 +23,7 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa
{
if (_object->_destination) {
TRACE("Creating packet with destination...");
//TRACE("Creating packet with destination...");
// CBA Should never see empty transport_type
//if (transport_type == NONE) {
// transport_type = Type::Transport::BROADCAST;
@@ -47,7 +47,7 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa
_object->_create_receipt = create_receipt;
}
else {
TRACE("Creating packet without destination...");
//TRACE("Creating packet without destination...");
// CBA NOTE: This variant is for creating a new packet from a received raw buffer
_object->_raw = data;
_object->_packed = true;
@@ -78,14 +78,14 @@ uint8_t Packet::get_packed_flags() {
assert(_object);
uint8_t packed_flags = 0;
if (_object->_context == LRPROOF) {
TRACE("***** Packing with LINK type");
//TRACE("***** Packing with LINK type");
packed_flags = (_object->_header_type << 6) | (_object->_context_flag << 5) | (_object->_transport_type << 4) | (Type::Destination::LINK << 2) | _object->_packet_type;
}
else {
if (!_object->_destination) {
throw std::logic_error("Packet destination is required");
}
TRACEF("***** Packing with %d type", _object->_destination.type());
//TRACEF("***** Packing with %d type", _object->_destination.type());
packed_flags = (_object->_header_type << 6) | (_object->_context_flag << 5) | (_object->_transport_type << 4) | (_object->_destination.type() << 2) | _object->_packet_type;
}
return packed_flags;
@@ -420,7 +420,7 @@ bool Packet::unpack() {
update_hash();
}
catch (const std::bad_alloc&) {
ERROR("Packet::unpack: bad_alloc - out of memory unpacking packet");
ERROR("Packet::unpack: bad_alloc - OUT OF MEMORY unpacking packet");
return false;
}
catch (std::exception& e) {
@@ -589,14 +589,15 @@ std::string Packet::debugString() const {
if (_object->_packed) {
//unpack();
}
std::string str = "ph=" + _object->_packet_hash.toHex();
str += " ht=" + std::to_string(_object->_header_type);
std::string str;
str = "ht=" + std::to_string(_object->_header_type);
str += " tt=" + std::to_string(_object->_transport_type);
str += " dt=" + std::to_string(_object->_destination_type);
str += " pt=" + std::to_string(_object->_packet_type);
str += " hp=" + std::to_string(_object->_hops);
str += " ti=" + _object->_transport_id.toHex();
str += " dh=" + _object->_destination_hash.toHex();
str += " ph=" + _object->_packet_hash.toHex();
return str;
}
std::string Packet::dumpString() const {
+2
View File
@@ -250,6 +250,8 @@ namespace RNS {
inline const Link& destination_link() const { assert(_object); return _object->_destination_link; }
//CBA Following method is only used by Resource to access decrypted resource advertisement form Link. Consider a better way.
inline const Bytes& plaintext() { assert(_object); return _object->_plaintext; }
inline bool packed() const { assert(_object); return _object->_packed; }
inline bool from_packed() const { assert(_object); return _object->_fromPacked; }
// setters
inline void destination(const Destination& destination) { assert(_object); _object->_destination = destination; }
+78 -58
View File
@@ -2,6 +2,7 @@
#include "Transport.h"
#include "Log.h"
#include "Utilities/Memory.h"
//#include <TransistorNoiseSource.h>
#include <RNG.h>
@@ -29,6 +30,9 @@ using namespace RNS::Utilities;
/*static*/ bool Reticulum::__allow_probes = false;
/*static*/ bool Reticulum::panic_on_interface_error = false;
/*static*/ uint16_t Reticulum::_persist_interval = PERSIST_INTERVAL;
/*static*/ uint16_t Reticulum::_clean_interval = CLEAN_INTERVAL;
#ifdef ARDUINO
// Noise source to seed the random number generator.
//TransistorNoiseSource noise(A1);
@@ -115,32 +119,6 @@ Reticulum::Reticulum() : _object(new Object()) {
strncpy(_cachepath, "./cache", FILEPATH_MAXSIZE);
#endif
#ifdef ARDUINO
#if defined(RNS_USE_FS)
// load time offset from file if it exists
try {
char time_offset_path[FILEPATH_MAXSIZE];
snprintf(time_offset_path, FILEPATH_MAXSIZE, "%s/time_offset", _storagepath);
if (OS::file_exists(time_offset_path)) {
Bytes buf;
if (OS::read_file(time_offset_path, buf) == 8) {
uint64_t offset = *(uint64_t*)buf.data();
DEBUGF("Read time offset of %llu from file", offset);
OS::setTimeOffset(offset);
}
}
}
catch (std::exception& e) {
ERRORF("Failed to load time offset, the contained exception was: %s", e.what());
}
#endif
#endif
// Initialize time-based variables *after* time offset update
_object->_last_data_persist = OS::time();
_object->_last_cache_clean = 0.0;
_object->_jobs_last_run = OS::time();
/*p TODO
if not os.path.isdir(Reticulum.storagepath):
os.makedirs(Reticulum.storagepath)
@@ -196,40 +174,80 @@ Reticulum::Reticulum() : _object(new Object()) {
void Reticulum::start() {
INFOF("Total memory: %zu", OS::heap_size());
INFOF("Total memory: %zu", Memory::heap_size());
INFOF("Total flash: %zu", OS::storage_size());
#ifdef ARDUINO
#if defined(RNS_USE_FS)
// load time offset from file if it exists
try {
char time_offset_path[FILEPATH_MAXSIZE];
snprintf(time_offset_path, FILEPATH_MAXSIZE, "%s/time_offset", _storagepath);
if (OS::file_exists(time_offset_path)) {
Bytes buf;
if (OS::read_file(time_offset_path, buf) == 8) {
uint64_t offset = *(uint64_t*)buf.data();
DEBUGF("Read time offset of %llu from file", offset);
OS::setTimeOffset(offset);
}
}
}
catch (std::exception& e) {
ERRORF("Failed to load time offset, the contained exception was: %s", e.what());
}
#endif
#endif
INFO("Starting Transport...");
Transport::start(*this);
// Initialize time-based variables *after* time offset update and Transport start
_object->_last_data_persist = OS::time();
_object->_last_cache_clean = OS::time();
_object->_jobs_last_run = OS::time();
}
void Reticulum::loop() {
assert(_object);
if (!_object->_is_connected_to_shared_instance) {
// Catch exceptions from loop work
try {
if (!_object->_is_connected_to_shared_instance) {
// Perform Reticulum housekeeping
if (OS::time() > (_object->_jobs_last_run + JOB_INTERVAL)) {
jobs();
_object->_jobs_last_run = OS::time();
// Perform Reticulum housekeeping
if (OS::time() > (_object->_jobs_last_run + JOB_INTERVAL)) {
jobs();
}
// Perform interface processing
for (auto& [hash, interface] : Transport::get_interfaces()) {
interface.loop();
}
// Perform Filesystem processing
FileSystem& filesystem = OS::get_filesystem();
if (filesystem) {
filesystem.loop();
}
// Perform Transport processing
RNS::Transport::loop();
}
// Perform interface processing
for (auto& [hash, interface] : Transport::get_interfaces()) {
interface.loop();
}
// Perform Filesystem processing
FileSystem& filesystem = OS::get_filesystem();
if (filesystem) {
filesystem.loop();
}
// Perform Transport processing
RNS::Transport::loop();
}
// Perform random number gnerator housekeeping
RNG.loop();
// Perform random number gnerator housekeeping
RNG.loop();
}
catch (const std::bad_alloc&) {
ERROR("Reticulum::loop: bad_alloc - OUT OF MEMORY");
// Critical OOM, restarting
#if defined(ESP32)
ESP.restart();
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
NVIC_SystemReset();
#endif
}
catch (std::exception& e) {
ERRORF("Reticulum::loop: %s", e.what());
}
}
void Reticulum::jobs() {
@@ -238,8 +256,8 @@ void Reticulum::jobs() {
#if 1
// CBA Detect low-memory condition and reset
if (OS::heap_size() > 0) {
uint8_t remaining = (uint8_t)((double)OS::heap_available() / (double)OS::heap_size() * 100.0);
if (Memory::heap_size() > 0) {
uint8_t remaining = (uint8_t)((double)Memory::heap_available() / (double)Memory::heap_size() * 100.0);
if (remaining <= 2) {
HEADF(LOG_CRITICAL, "DETECTED LOW-MEMORY CONDITION (%d%%), RESETTING!!!", remaining);
persist_data();
@@ -253,14 +271,15 @@ void Reticulum::jobs() {
}
#endif
if (now > _object->_last_cache_clean + CLEAN_INTERVAL) {
if (now > _object->_last_cache_clean + _clean_interval) {
clean_caches();
_object->_last_cache_clean = OS::time();
}
if (now > _object->_last_data_persist + PERSIST_INTERVAL) {
if (now > _object->_last_data_persist + _persist_interval) {
persist_data();
}
_object->_jobs_last_run = OS::time();
}
// CBA TODO
@@ -354,6 +373,7 @@ void Reticulum::clean_caches() {
Identity::cull_known_destinations();
#endif
_object->_last_cache_clean = OS::time();
}
void Reticulum::clear_caches() {
@@ -395,7 +415,7 @@ void Reticulum::get_interface_stats() const {
}
*/
const std::map<Bytes, Transport::DestinationEntry>& Reticulum::get_path_table() const {
const Transport::PathTable& Reticulum::get_path_table() const {
/*
path_table = []
for dst_hash in Transport::destination_table:
@@ -411,7 +431,7 @@ const std::map<Bytes, Transport::DestinationEntry>& Reticulum::get_path_table()
return path_table
*/
return Transport::get_destination_table();
return Transport::get_path_table();
}
const std::map<Bytes, Transport::RateEntry>& Reticulum::get_rate_table() const {
@@ -438,8 +458,8 @@ bool Reticulum::drop_path(const Bytes& destination) {
uint16_t Reticulum::drop_all_via(const Bytes& transport_hash) {
uint16_t dropped_count = 0;
//for (auto& destination_hash : Transport::get_destination_table()) {
for (const auto& [destination_hash, destination_entry] : Transport::get_destination_table()) {
//for (auto& destination_hash : Transport::get_path_table()) {
for (const auto& [destination_hash, destination_entry] : Transport::get_path_table()) {
if (destination_entry._received_from == transport_hash) {
Transport::expire_path(destination_hash);
++dropped_count;
+11 -2
View File
@@ -16,7 +16,7 @@ namespace RNS {
class Reticulum {
public:
private:
//z router = None
//z config = None
@@ -42,6 +42,9 @@ namespace RNS {
static bool __allow_probes;
static bool panic_on_interface_error;
static uint16_t _persist_interval;
static uint16_t _clean_interval;
public:
// Return the currently running Reticulum instance
inline static const Reticulum& get_instance() { return _instance; }
@@ -81,7 +84,7 @@ namespace RNS {
//void __create_default_config();
//void rpc_loop();
//void get_interface_stats() const;
const std::map<Bytes, Transport::DestinationEntry>& get_path_table() const;
const Transport::PathTable& get_path_table() const;
const std::map<Bytes, Transport::RateEntry>& get_rate_table() const;
bool drop_path(const Bytes& destination);
uint16_t drop_all_via(const Bytes& transport_hash);
@@ -144,6 +147,10 @@ namespace RNS {
// getters/setters
inline bool is_connected_to_shared_instance() const { assert(_object); return _object->_is_connected_to_shared_instance; }
inline static uint16_t persist_interval() { return _persist_interval; }
inline static void persist_interval(uint16_t persist_interval) { _persist_interval = persist_interval; }
inline static uint16_t clean_interval() { return _clean_interval; }
inline static void clean_interval(uint16_t clean_interval) { _clean_interval = clean_interval; }
private:
class Object {
@@ -177,6 +184,8 @@ namespace RNS {
};
std::shared_ptr<Object> _object;
// CBA For access to private static members by Transport class
friend class Transport;
};
}
+242 -438
View File
File diff suppressed because it is too large. Load diff
+130 -57
View File
@@ -3,6 +3,7 @@
#include "Packet.h"
#include "Bytes.h"
#include "Type.h"
#include "Utilities/Memory.h"
#include <map>
#include <vector>
@@ -13,12 +14,9 @@
#include <functional>
#include <stdint.h>
//#define INTERFACES_SET
//#define INTERFACES_LIST
#define INTERFACES_MAP
//#define DESTINATIONS_SET
#define DESTINATIONS_MAP
#ifndef RNS_LEAN_PATH_TABLE
#define RNS_LEAN_PATH_TABLE 1
#endif
namespace RNS {
@@ -56,6 +54,10 @@ namespace RNS {
class Transport {
public:
using InterfaceTable = std::map<Bytes, Interface&>;
using DestinationTable = std::map<Bytes, Destination>;
class Callbacks {
public:
using receive_packet = void(*)(const Bytes& raw, const Interface& interface);
@@ -68,8 +70,6 @@ namespace RNS {
friend class Transport;
};
public:
class PacketEntry {
public:
PacketEntry() {}
@@ -99,40 +99,110 @@ namespace RNS {
}
#endif
};
using PacketTable = std::map<Bytes, PacketEntry>;
// CBA TODO Analyze safety of using Inrerface references here
// CBA TODO Analyze safety of using Packet references here
class DestinationEntry {
public:
DestinationEntry() {}
DestinationEntry(double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set<Bytes>& random_blobs, const Bytes& receiving_interface, const Bytes& packet) :
DestinationEntry(double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set<Bytes>& random_blobs, const Interface& receiving_interface, const Packet& announce_packet) :
_timestamp(timestamp),
_received_from(received_from),
_hops(announce_hops),
_expires(expires),
_random_blobs(random_blobs),
#if RNS_LEAN_PATH_TABLE
_receiving_interface(receiving_interface)
#else
_receiving_interface(receiving_interface),
_announce_packet(packet)
_announce_packet(announce_packet)
#endif
{
if (receiving_interface) _receiving_interface_hash = receiving_interface.get_hash();
if (announce_packet) _announce_packet_hash = announce_packet.get_hash();
}
DestinationEntry(double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set<Bytes>& random_blobs, const Bytes& receiving_interface_hash, const Bytes& announce_packet_hash) :
_timestamp(timestamp),
_received_from(received_from),
_hops(announce_hops),
_expires(expires),
_random_blobs(random_blobs),
_receiving_interface_hash(receiving_interface_hash),
_announce_packet_hash(announce_packet_hash)
{
}
inline operator bool() const {
return (_receiving_interface_hash && _announce_packet_hash);
}
public:
inline Interface receiving_interface() const { return find_interface_from_hash(_receiving_interface); }
inline Packet announce_packet() const { return get_cached_packet(_announce_packet); }
// Lazy load receiving_interface and announce_packet
inline Interface& receiving_interface() {
if (!_receiving_interface) _receiving_interface = find_interface_from_hash(_receiving_interface_hash);
return _receiving_interface;
}
#if RNS_LEAN_PATH_TABLE
// Lazy load transient announce packet
inline Packet announce_packet() {
Packet announce_packet = get_cached_packet(_announce_packet_hash);
if (announce_packet) {
// Announce packet is cached in packed state
// so we need to unpack it before accessing.
announce_packet.unpack();
// We increase the hops, since reading a packet
// from cache is equivalent to receiving it again
// over an interface. It is cached with it's non-
// increased hop-count.
announce_packet.hops(announce_packet.hops() + 1);
}
return announce_packet;
}
#else
// Lazy load and cache announce packet
inline Packet& announce_packet() {
if (!_announce_packet) _announce_packet = get_cached_packet(_announce_packet_hash);
if (_announce_packet) {
// Announce packet is cached in packed state
// so we need to unpack it before accessing.
_announce_packet.unpack();
// We increase the hops, since reading a packet
// from cache is equivalent to receiving it again
// over an interface. It is cached with it's non-
// increased hop-count.
_announce_packet.hops(_announce_packet.hops() + 1);
}
return _announce_packet;
}
#endif
// Getters and setters for receiving_interface_hash and announce_packet_hash
inline Bytes receiving_interface_hash() const { if (_receiving_interface) return _receiving_interface.get_hash(); return _receiving_interface_hash; }
inline void receiving_interface_hash(const Bytes& hash) { if (hash == receiving_interface_hash()) return; _receiving_interface_hash = hash; _receiving_interface = {Type::NONE}; }
#if RNS_LEAN_PATH_TABLE
inline Bytes announce_packet_hash() const { return _announce_packet_hash; }
inline void announce_packet_hash(const Bytes& hash) { _announce_packet_hash = hash; }
#else
inline Bytes announce_packet_hash() const { if (_announce_packet) return _announce_packet.get_hash(); return _announce_packet_hash; }
inline void announce_packet_hash(const Bytes& hash) { if (hash == announce_packet_hash()) return; _announce_packet_hash = hash; _announce_packet = {Type::NONE}; }
#endif
public:
double _timestamp = 0;
Bytes _received_from;
uint8_t _hops = 0;
double _expires = 0;
std::set<Bytes> _random_blobs;
//Interface _receiving_interface = {Type::NONE};
Bytes _receiving_interface;
//const Packet& _announce_packet;
//Packet _announce_packet = {Type::NONE};
Bytes _announce_packet;
inline bool operator < (const DestinationEntry& entry) const {
// sort by ascending timestamp (oldest entries at the top)
return _timestamp < entry._timestamp;
}
private:
Interface _receiving_interface = {Type::NONE};
Bytes _receiving_interface_hash;
#if !RNS_LEAN_PATH_TABLE
//const Packet& _announce_packet;
Packet _announce_packet = {Type::NONE};
#endif
Bytes _announce_packet_hash;
public:
#ifndef NDEBUG
inline std::string debugString() const {
std::string dump;
@@ -141,8 +211,8 @@ namespace RNS {
" hops=" + std::to_string(_hops) +
" expires=" + std::to_string(_expires) +
//" random_blobs=" + _random_blobs +
" receiving_interface=" + _receiving_interface.toHex() +
" announce_packet=" + _announce_packet.toHex();
" receiving_interface=" + receiving_interface_hash().toHex() +
" announce_packet=" + announce_packet_hash().toHex();
dump += " random_blobs=(";
for (auto& blob : _random_blobs) {
dump += blob.toHex() + ",";
@@ -152,6 +222,8 @@ namespace RNS {
}
#endif
};
//using PathTable = std::map<Bytes, DestinationEntry>;
using PathTable = std::map<Bytes, DestinationEntry, std::less<Bytes>, Utilities::Memory::ContainerAllocator<std::pair<const Bytes, DestinationEntry>>>;
// CBA TODO Analyze safety of using Inrerface references here
// CBA TODO Analyze safety of using Packet references here
@@ -183,6 +255,8 @@ namespace RNS {
bool _block_rebroadcasts = false;
const Interface _attached_interface = {Type::NONE};
};
//using AnnounceTable = std::map<Bytes, AnnounceEntry>;
using AnnounceTable = std::map<Bytes, AnnounceEntry, std::less<Bytes>, Utilities::Memory::ContainerAllocator<std::pair<const Bytes, AnnounceEntry>>>;
// CBA TODO Analyze safety of using Inrerface references here
class LinkEntry {
@@ -210,6 +284,7 @@ namespace RNS {
bool _validated = false;
double _proof_timeout = 0;
};
using LinkTable = std::map<Bytes, LinkEntry>;
// CBA TODO Analyze safety of using Inrerface references here
class ReverseEntry {
@@ -225,6 +300,7 @@ namespace RNS {
const Interface _outbound_interface = {Type::NONE};
double _timestamp = 0;
};
using ReverseTable = std::map<Bytes, ReverseEntry>;
// CBA TODO Analyze safety of using Inrerface references here
class PathRequestEntry {
@@ -240,6 +316,7 @@ namespace RNS {
double _timeout = 0;
const Interface _requesting_interface = {Type::NONE};
};
using PathRequestTable = std::map<Bytes, PathRequestEntry>;
/*
// CBA TODO Analyze safety of using Inrerface references here
@@ -279,9 +356,10 @@ namespace RNS {
public:
const Bytes _tunnel_id;
const Bytes _interface_hash;
std::map<Bytes, DestinationEntry> _serialised_paths;
PathTable _serialised_paths;
double _expires = 0;
};
using TunnelTable = std::map<Bytes, TunnelEntry>;
class RateEntry {
public:
@@ -296,6 +374,7 @@ namespace RNS {
double _blocked_until = 0.0;
std::vector<double> _timestamps;
};
using RateTable = std::map<Bytes, RateEntry>;
public:
static void start(const Reticulum& reticulum_instance);
@@ -312,20 +391,23 @@ namespace RNS {
static void handle_tunnel(const Bytes& tunnel_id, const Interface& interface);
static void register_interface(Interface& interface);
static void deregister_interface(const Interface& interface);
inline static const std::map<Bytes, Interface&> get_interfaces() { return _interfaces; }
inline static const InterfaceTable& get_interfaces() { return _interfaces; }
static void register_destination(Destination& destination);
static void deregister_destination(const Destination& destination);
static void register_link(Link& link);
static void activate_link(Link& link);
static void register_announce_handler(HAnnounceHandler handler);
static void deregister_announce_handler(HAnnounceHandler handler);
static bool is_interface_from_hash(const Bytes& interface_hash);
static Interface find_interface_from_hash(const Bytes& interface_hash);
static bool should_cache_packet(const Packet& packet);
static bool cache_packet(const Packet& packet, bool force_cache = false);
static bool is_cached_packet(const Bytes& packet_hash);
static Packet get_cached_packet(const Bytes& packet_hash);
static bool clear_cached_packet(const Bytes& packet_hash);
static bool cache_request_packet(const Packet& packet);
static void cache_request(const Bytes& packet_hash, const Destination& destination);
static DestinationEntry& get_path(const Bytes& destination_hash);
static bool remove_path(const Bytes& destination_hash);
static bool has_path(const Bytes& destination_hash);
static uint8_t hops_to(const Bytes& destination_hash);
@@ -387,55 +469,42 @@ namespace RNS {
inline static void hashlist_maxsize(uint16_t hashlist_maxsize) { _hashlist_maxsize = hashlist_maxsize; }
inline static uint16_t max_pr_tags() { return _max_pr_tags; }
inline static void max_pr_tags(uint16_t max_pr_tags) { _max_pr_tags = max_pr_tags; }
inline static uint16_t probe_destination_enabled() { return _path_table_maxpersist; }
inline static uint16_t path_table_maxpersist() { return _path_table_maxpersist; }
inline static void path_table_maxpersist(uint16_t path_table_maxpersist) { _path_table_maxpersist = path_table_maxpersist; }
// CBA TEST
static inline void identity(Identity& identity) { _identity = identity; }
inline static const std::map<Bytes, DestinationEntry>& get_destination_table() { return _destination_table; }
inline static const std::map<Bytes, RateEntry>& get_announce_rate_table() { return _announce_rate_table; }
inline static const std::map<Bytes, LinkEntry>& get_link_table() { return _link_table; }
inline static const PathTable& get_path_table() { return _path_table; }
inline static const RateTable& get_announce_rate_table() { return _announce_rate_table; }
inline static const LinkTable& get_link_table() { return _link_table; }
private:
// CBA MUST use references to interfaces here in order for virtul overrides for send/receive to work
#if defined(INTERFACES_SET)
// set sorted, can use find
//static std::set<std::reference_wrapper<const Interface>, std::less<const Interface>> _interfaces; // All active interfaces
static std::set<std::reference_wrapper<Interface>, std::less<Interface>> _interfaces; // All active interfaces
#elif defined(INTERFACES_LIST)
// list is unsorted, can't use find
static std::list<std::reference_wrapper<Interface>> _interfaces; // All active interfaces
#elif defined(INTERFACES_MAP)
// map is sorted, can use find
static std::map<Bytes, Interface&> _interfaces; // All active interfaces
#endif
#if defined(DESTINATIONS_SET)
static std::set<Destination> _destinations; // All active destinations
#elif defined(DESTINATIONS_MAP)
static std::map<Bytes, Destination> _destinations; // All active destinations
#endif
static InterfaceTable _interfaces; // All active interfaces
static DestinationTable _destinations; // All active destinations
// CBA TODO: Reconsider using std::set for enforcing uniqueness. Maybe consider std::map keyed on hash instead
static std::set<Link> _pending_links; // Links that are being established
static std::set<Link> _active_links; // Links that are active
static std::set<Bytes> _packet_hashlist; // A list of packet hashes for duplicate detection
static std::list<PacketReceipt> _receipts; // Receipts of all outgoing packets for proof processing
static std::set<Link> _pending_links; // Links that are being established
static std::set<Link> _active_links; // Links that are active
static std::set<Bytes> _packet_hashlist; // A list of packet hashes for duplicate detection
static std::list<PacketReceipt> _receipts; // Receipts of all outgoing packets for proof processing
// TODO: "destination_table" should really be renamed to "path_table"
// Notes on memory usage: 1 megabyte of memory can store approximately
// 55.100 path table entries or approximately 22.300 link table entries.
static std::map<Bytes, AnnounceEntry> _announce_table; // A table for storing announces currently waiting to be retransmitted
static std::map<Bytes, DestinationEntry> _destination_table; // A lookup table containing the next hop to a given destination
static std::map<Bytes, ReverseEntry> _reverse_table; // A lookup table for storing packet hashes used to return proofs and replies
static std::map<Bytes, LinkEntry> _link_table; // A lookup table containing hops for links
static std::map<Bytes, AnnounceEntry> _held_announces; // A table containing temporarily held announce-table entries
static std::set<HAnnounceHandler> _announce_handlers; // A table storing externally registered announce handlers
static std::map<Bytes, TunnelEntry> _tunnels; // A table storing tunnels to other transport instances
static std::map<Bytes, RateEntry> _announce_rate_table; // A table for keeping track of announce rates
static std::map<Bytes, double> _path_requests; // A table for storing path request timestamps
static AnnounceTable _announce_table; // A table for storing announces currently waiting to be retransmitted
static PathTable _path_table; // A lookup table containing the next hop to a given destination
static ReverseTable _reverse_table; // A lookup table for storing packet hashes used to return proofs and replies
static LinkTable _link_table; // A lookup table containing hops for links
static AnnounceTable _held_announces; // A table containing temporarily held announce-table entries
static TunnelTable _tunnels; // A table storing tunnels to other transport instances
static RateTable _announce_rate_table; // A table for keeping track of announce rates
static std::set<HAnnounceHandler> _announce_handlers; // A table storing externally registered announce handlers
static std::map<Bytes, double> _path_requests; // A table for storing path request timestamps
static std::map<Bytes, PathRequestEntry> _discovery_path_requests; // A table for keeping track of path requests on behalf of other nodes
static std::set<Bytes> _discovery_pr_tags; // A table for keeping track of tagged path requests
static PathRequestTable _discovery_path_requests; // A table for keeping track of path requests on behalf of other nodes
static std::set<Bytes> _discovery_pr_tags; // A table for keeping track of tagged path requests
// Transport control destinations are used
// for control purposes like path requests
@@ -451,7 +520,7 @@ namespace RNS {
static std::map<Bytes, const Interface&> _pending_local_path_requests;
// CBA
static std::map<Bytes, PacketEntry> _packet_table; // A lookup table containing announce packets for known paths
static PacketTable _packet_table; // A lookup table containing announce packets for known paths
//z _local_client_rssi_cache = []
//z _local_client_snr_cache = []
@@ -479,7 +548,7 @@ namespace RNS {
static uint16_t _path_table_maxpersist;
static double _last_saved;
static float _save_interval;
static uint32_t _destination_table_crc;
static uint32_t _path_table_crc;
static uint16_t _announce_table_maxsize;
static Reticulum _owner;
@@ -493,7 +562,11 @@ namespace RNS {
static uint32_t _packets_received;
static uint32_t _destinations_added;
static size_t _last_memory;
static size_t _last_psram;
static size_t _last_flash;
// CBA Block re-entrance
static bool cleaning_caches;
};
template <typename M, typename S>
+6 -8
View File
@@ -104,7 +104,7 @@ namespace RNS { namespace Type {
but it can be configured individually on a per-interface basis.
*/
static const uint16_t MINIMUM_BITRATE = 500;
static const uint16_t MINIMUM_BITRATE = 5;
// TODO: To reach the 300bps level without unreasonably impacting
// performance on faster links, we need a mechanism for setting
@@ -130,13 +130,11 @@ namespace RNS { namespace Type {
//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;
// 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 GRACIOUS_PERSIST_INTERVAL = 60*5;
static const uint8_t DESTINATION_LENGTH = TRUNCATED_HASHLENGTH/8; // In bytes
@@ -235,7 +233,7 @@ namespace RNS { namespace Type {
static const float KEEPALIVE_MAX_RTT = 1.75;
static const uint8_t KEEPALIVE_TIMEOUT_FACTOR = 4;
// Grace period in seconds used in link timeout calculation.
static const uint8_t STALE_GRACE = 2;
static const uint8_t STALE_GRACE = 5;
// Interval for sending keep-alive packets on established links in seconds.
static const uint16_t KEEPALIVE = 360;
/*
@@ -442,12 +440,12 @@ namespace RNS { namespace Type {
static const uint8_t LOCAL_REBROADCASTS_MAX = 2; // How many local rebroadcasts of an announce is allowed
static const uint8_t PATH_REQUEST_TIMEOUT = 15; // Default timuout for client path requests in seconds
static constexpr const float PATH_REQUEST_GRACE = 0.35; // Grace time before a path announcement is made, allows directly reachable peers to respond first
static constexpr const float PATH_REQUEST_GRACE = 0.4; // Grace time before a path announcement is made, allows directly reachable peers to respond first
static const uint8_t PATH_REQUEST_RW = 2; // Path request random window
static const uint8_t PATH_REQUEST_MI = 5; // Minimum interval in seconds for automated path requests
static constexpr const float LINK_TIMEOUT = Link::STALE_TIME * 1.25;
static const uint16_t REVERSE_TIMEOUT = 30*60; // Reverse table entries are removed after 30 minutes
static const uint16_t REVERSE_TIMEOUT = 8*60; // Reverse table entries are removed after 8 minutes
// CBA MCU
static const uint16_t MAX_RECEIPTS = RNS_RECEIPTS_MAX; // Maximum number of receipts to keep track of
static const uint8_t MAX_RATE_TIMESTAMPS = RNS_RATE_TIMESTAMPS_MAX; // Maximum number of announce timestamps to keep per destination
+565
View File
@@ -0,0 +1,565 @@
#include "Memory.h"
#include <new>
using namespace RNS;
using namespace RNS::Utilities;
#ifndef RNS_DEFAULT_ALLOCATOR
#if defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
// Use TLSF on NRF52 boards by default since they don't embed their own advanced memory manager like ESP32 does
#define RNS_DEFAULT_ALLOCATOR RNS_HEAP_POOL_ALLOCATOR
#else
#define RNS_DEFAULT_ALLOCATOR RNS_HEAP_ALLOCATOR
#endif
#endif
#ifndef RNS_CONTAINER_ALLOCATOR
#if defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
// Use TLSF on NRF52 boards by default since they don't embed their own advanced memory manager like ESP32 does
#define RNS_CONTAINER_ALLOCATOR RNS_HEAP_POOL_ALLOCATOR
#else
#define RNS_CONTAINER_ALLOCATOR RNS_HEAP_ALLOCATOR
#endif
#endif
#ifndef RNS_HEAP_POOL_BUFFER_SIZE
#define RNS_HEAP_POOL_BUFFER_SIZE 1024 * 1000
#endif
#ifndef RNS_PSRAM_POOL_BUFFER_SIZE
#define RNS_PSRAM_POOL_BUFFER_SIZE 0
#endif
#ifndef RNS_ALTHEAP_POOL_BUFFER_SIZE
#define RNS_ALTHEAP_POOL_BUFFER_SIZE 0
#endif
#ifndef BUFFER_FRACTION
#define BUFFER_FRACTION 0.8
#endif
//char _tlsf_msg[256] = "";
/*static*/ Memory::pool_info Memory::heap_pool_info(RNS_HEAP_POOL_ALLOCATOR, RNS_HEAP_POOL_BUFFER_SIZE);
/*static*/ Memory::pool_info Memory::psram_pool_info(RNS_PSRAM_POOL_ALLOCATOR, RNS_PSRAM_POOL_BUFFER_SIZE);;
/*static*/ Memory::pool_info Memory::altheap_pool_info(RNS_ALTHEAP_POOL_ALLOCATOR, RNS_ALTHEAP_POOL_BUFFER_SIZE);;
/*static*/ Memory::allocator_info Memory::default_allocator_info;
/*static*/ Memory::allocator_info Memory::container_allocator_info;
/*static*/ void Memory::pool_init(Memory::pool_info& pool_info) {
if (pool_info.pool_init) {
return;
}
pool_info.pool_init = true;
printf("Initializing TLSF pool...\n");
#if defined(ESP32)
heap_pool_info.contiguous_size = ESP.getMaxAllocHeap();
psram_pool_info.contiguous_size = ESP.getMaxAllocPsram();
altheap_pool_info.contiguous_size = ESP.getMaxAllocHeap();
printf("TLSF: Heap contiguous_size: %u\n", ESP.getMaxAllocHeap());
printf("TLSF: PSRAM contiguous_size: %u\n", ESP.getMaxAllocPsram());
printf("TLSF: contiguous_size: %u\n", pool_info.contiguous_size);
if (pool_info.buffer_size == 0) {
// CBA NOTE Using fp mathhere somehow causes tlsf_create_with_pool() to fail.
//pool_info.buffer_size = (size_t)(pool_info.contiguous_size * BUFFER_FRACTION);
// Compute 80% exactly using integers
pool_info.buffer_size = (pool_info.contiguous_size * 4) / 5;
}
// Round DOWN to TLSF alignment
size_t align = tlsf_align_size();
pool_info.buffer_size &= ~(align - 1);
void* raw_buffer = nullptr;
// If pool type is PSRAM then allocate pool buffer from PSRAM
if (pool_info.type == RNS_PSRAM_POOL_ALLOCATOR) {
raw_buffer = (void*)ps_malloc(pool_info.buffer_size);
}
// Otherwise just allocate from heap
else {
raw_buffer = (void*)aligned_alloc(align, pool_info.buffer_size);
}
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
heap_pool_info.contiguous_size = dbgHeapFree();
altheap_pool_info.buffer_size = dbgHeapFree();
TRACEF("TLSF: contiguous_size: %u", pool_info.contiguous_size);
if (pool_info.buffer_size == 0) {
pool_info.buffer_size = (size_t)(pool_info.contiguous_size * BUFFER_FRACTION);
}
// For NRF52 round to kB
pool_info.buffer_size = (size_t)(pool_info.buffer_size / 1024) * 1024;
TRACEF("TLSF: buffer_size: %u", pool_info.buffer_size);
void* raw_buffer = malloc(pool_info.buffer_size);
#else
pool_info.buffer_size = (size_t)RNS_HEAP_POOL_BUFFER_SIZE;
TRACEF("TLSF: buffer_size: %u", pool_info.buffer_size);
void* raw_buffer = malloc(pool_info.buffer_size);
#endif
if (raw_buffer == nullptr) {
ERROR("-- TLSF: buffer allocation FAILED");
printf("TLSF buffer allocation FAILED!\n");
//strcpy(_tlsf_msg, "-- TLSF: buffer allocation FAILED!!!");
}
else {
#if 1
pool_info.tlsf = tlsf_create_with_pool(raw_buffer, pool_info.buffer_size);
if (pool_info.tlsf == nullptr) {
//sprintf(_tlsf_msg, "TLSF: initialization with align=%d, contiguous=%d, size=%d FAILED!!!", tlsf_align_size(), pool_info.contiguous_size, pool_info.buffer_size);
printf("TLSF: initialization with align=%d, contiguous=%d, size=%d FAILED!!!\n", tlsf_align_size(), pool_info.contiguous_size, pool_info.buffer_size);
}
else {
//sprintf(_tlsf_msg, "TLSF: initialization with align=%d, contiguous=%d, size=%d SUCCESSFUL!!!", tlsf_align_size(), pool_info.contiguous_size, pool_info.buffer_size);
printf("TLSF: initialization with align=%d, contiguous=%d, size=%d SUCCESSFUL!!!\n", tlsf_align_size(), pool_info.contiguous_size, pool_info.buffer_size);
}
#else
Serial.print("TLSF: raw_buffer: ");
Serial.println((long)raw_buffer);
Serial.print("TLSF: align_size: ");
Serial.println((long)tlsf_align_size());
void* aligned_buffer = (void*)(((size_t)raw_buffer + (tlsf_align_size() - 1)) & ~(tlsf_align_size() - 1));
Serial.print("TLSF: aligned_buffer: ");
Serial.println((long)aligned_buffer);
pool_info.tlsf = tlsf_create_with_pool(aligned_buffer, pool_info.buffer_size-(size_t)((uint32_t)aligned_buffer - (uint32_t)raw_buffer));
//tlfs = tlsf_create_with_pool(aligned_buffer, pool_info.buffer_size--(size_t)((uint32_t)aligned_buffer - (uint32_t)raw_buffer));
#endif
if (pool_info.tlsf == nullptr) {
ERROR("-- TLSF: initialization of FAILED");
}
}
}
/*static*/ void* Memory::pool_malloc(Memory::pool_info& pool_info, size_t size) {
if (size == 0) return nullptr;
//if (pool_info.tlsf == nullptr) {
if (!pool_info.pool_init) {
Memory::pool_init(pool_info);
}
void* p;
if (pool_info.tlsf != nullptr) {
//struct tlsf_stats stats;
//memset(&stats, 0, sizeof(stats));
//tlsf_walk_pool(tlsf_get_pool(pool_info.tlsf), tlsf_mem_walker, &stats);
//if (tlsf_check(pool_info.tlsf) != 0) {
// printf("--- HEAP CORRUPTION DETECTED!!!\n");
//}
//TRACEF("--- allocating memory from tlsf (%u bytes)", size);
//printf("--- allocating memory from tlsf (%u bytes) (%u free)\n", size, stats.free_size);
p = tlsf_malloc(pool_info.tlsf, size);
//TRACEF("--- allocated memory from tlsf (addr=%lx) (%u bytes)", p, size);
//printf("--- allocated memory from tlsf (addr=%lx) (%u bytes)\n", p, size);
}
else {
//TRACEF("--- allocating memory (%u bytes)", size);
p = malloc(size);
//TRACEF("--- allocated memory (addr=%lx) (%u bytes)", p, size);
++pool_info.alloc_fault;
}
return p;
}
/*static*/ void Memory::pool_free(Memory::pool_info& pool_info, void* p, size_t size /*= 0*/) noexcept {
if (p == nullptr) return;
if (pool_info.tlsf != nullptr) {
//TRACEF("--- freeing memory from tlsf (addr=%lx)", p);
//printf("--- freeing memory from tlsf (addr=%lx)\n", p);
tlsf_free(pool_info.tlsf, p);
}
else {
//TRACEF("--- freeing memory (addr=%lx)", p);
free(p);
++pool_info.free_fault;
}
/*
if (free_count == _alloc_count) {
TRACE("TLFS deinitializing");
dump_memory_stats();
tlsf_destroy(pool_info.tlsf);
pool_info.tlsf = nullptr;
}
*/
}
struct tlsf_stats {
uint32_t used_count = 0;
uint32_t used_size = 0;
uint32_t free_count = 0;
uint32_t free_size = 0;
uint32_t free_max_size = 0;
};
void tlsf_mem_walker(void* ptr, size_t size, int used, void* user)
{
if (!user) {
return;
}
struct tlsf_stats* stats = (struct tlsf_stats*)user;
if (used) {
stats->used_count++;
stats->used_size += size;
}
else {
stats->free_count++;
stats->free_size += size;
if (size > stats->free_max_size) {
stats->free_max_size = size;
}
}
}
/*static*/ void Memory::dump_pool_stats(Memory::pool_info& pool_info, const char* name /*= ""*/) {
//TRACEF("TLSF Message: %s", _tlsf_msg);
if (pool_info.tlsf == nullptr) {
return;
}
struct tlsf_stats stats;
memset(&stats, 0, sizeof(stats));
tlsf_walk_pool(tlsf_get_pool(pool_info.tlsf), tlsf_mem_walker, &stats);
HEADF(LOG_TRACE, "%sPool Stats", name);
TRACEF(" Buffer Size: %u", pool_info.buffer_size);
TRACEF(" Contiguous Size: %u", pool_info.contiguous_size);
TRACEF(" Used Count: %u", stats.used_count);
TRACEF(" Used Size: %u (%u%% used)", stats.used_size, (unsigned)((double)stats.used_size / (double)pool_info.buffer_size * 100.0));
TRACEF(" Free Count: %u", stats.free_count);
TRACEF(" Free Size: %u (%u%% free)", stats.free_size, (unsigned)((double)stats.free_size / (double)pool_info.buffer_size * 100.0));
TRACEF(" Max Free Size: %u (%u%% fragmented)", stats.free_max_size, (unsigned)(100.0 - (double)stats.free_max_size / (double)stats.free_size * 100.0));
//TRACEF(" alloc_count: %u", pool_info.alloc_count);
TRACEF(" alloc_fault: %u", pool_info.alloc_fault);
//TRACEF(" free_count: %u", pool_info.free_count);
TRACEF(" free_fault: %u", pool_info.free_fault);
}
/*static*/ void Memory::dump_basic_pool_stats() {
size_t heap_free = 0;
uint8_t heap_pct = 0;
if (heap_pool_info.tlsf != nullptr) {
struct tlsf_stats stats;
memset(&stats, 0, sizeof(stats));
tlsf_walk_pool(tlsf_get_pool(heap_pool_info.tlsf), tlsf_mem_walker, &stats);
heap_free = stats.free_size;
heap_pct = (uint8_t)((double)heap_free / (double)heap_pool_info.buffer_size * 100.0);
}
if (heap_pool_info.last_free == 0) {
heap_pool_info.last_free = heap_free;
}
size_t psram_free = 0;
uint8_t psram_pct = 0;
if (psram_pool_info.tlsf != nullptr) {
struct tlsf_stats stats;
memset(&stats, 0, sizeof(stats));
tlsf_walk_pool(tlsf_get_pool(psram_pool_info.tlsf), tlsf_mem_walker, &stats);
psram_free = stats.free_size;
psram_pct = (uint8_t)((double)psram_free / (double)psram_pool_info.buffer_size * 100.0);
}
if (psram_pool_info.last_free == 0) {
psram_pool_info.last_free = psram_free;
}
size_t altheap_free = 0;
uint8_t altheap_pct = 0;
if (altheap_pool_info.tlsf != nullptr) {
struct tlsf_stats stats;
memset(&stats, 0, sizeof(stats));
tlsf_walk_pool(tlsf_get_pool(altheap_pool_info.tlsf), tlsf_mem_walker, &stats);
altheap_free = stats.free_size;
altheap_pct = (uint8_t)((double)altheap_free / (double)altheap_pool_info.buffer_size * 100.0);
}
if (altheap_pool_info.last_free == 0) {
altheap_pool_info.last_free = altheap_free;
}
VERBOSEF("heap_pool: %u (%u%%) [%d] psram_pool: %u (%u%%) [%d] alt_pool: %u (%u%%) [%d]", heap_free, heap_pct, heap_free - heap_pool_info.last_free, psram_free, psram_pct, psram_free - psram_pool_info.last_free, altheap_free, altheap_pct, altheap_free - altheap_pool_info.last_free);
heap_pool_info.last_free = heap_free;
psram_pool_info.last_free = psram_free;
altheap_pool_info.last_free = altheap_free;
}
/*static*/ void Memory::dump_allocator_stats(Memory::allocator_info& allocator_info, const char* name /*= ""*/) {
HEADF(LOG_TRACE, "%sAllocator Stats", name);
TRACEF(" Active Count: %u", (allocator_info.alloc_count - allocator_info.free_count));
TRACEF(" Min Size: %u", allocator_info.min_alloc_size);
TRACEF(" Max Size: %u", allocator_info.max_alloc_size);
TRACEF(" Avg Size: %u", (size_t)((allocator_info.alloc_count > 0) ? (allocator_info.alloc_size / allocator_info.alloc_count) : 0));
TRACEF(" alloc_count: %u", allocator_info.alloc_count);
TRACEF(" alloc_fault: %u", allocator_info.alloc_fault);
TRACEF(" free_count: %u", allocator_info.free_count);
TRACEF(" free_fault: %u", allocator_info.free_fault);
}
/*static*/ void Memory::dump_basic_allocator_stats() {
int dflt_diff = 0;
// Increase in used memory, negative diff
if (default_allocator_info.alloc_size > default_allocator_info.last_size) {
dflt_diff = (int)(default_allocator_info.alloc_size - default_allocator_info.last_size) * -1;
}
// Decrease in used memory, positive diff
else {
dflt_diff = (int)(default_allocator_info.last_size - default_allocator_info.alloc_size);
}
//if (default_allocator_info.last_size == 0) {
// default_allocator_info.last_size = default_allocator_info.alloc_size;
//}
int cntr_diff = 0;
// Increase in used memory, negative diff
if (container_allocator_info.alloc_size > container_allocator_info.last_size) {
cntr_diff = (int)(container_allocator_info.alloc_size - container_allocator_info.last_size) * -1;
}
// Decrease in used memory, positive diff
else {
cntr_diff = (int)(container_allocator_info.last_size - container_allocator_info.alloc_size);
}
//if (container_allocator_info.last_size == 0) {
// container_allocator_info.last_size = container_allocator_info.alloc_size;
//}
VERBOSEF("dflt_alloc: %llu [%d] cntr_alloc: %llu [%d]", default_allocator_info.alloc_size, dflt_diff, container_allocator_info.alloc_size, cntr_diff);
default_allocator_info.last_size = default_allocator_info.alloc_size;
container_allocator_info.last_size = container_allocator_info.alloc_size;
}
size_t maxContiguousAllocation() {
// Brute-force determine maximum allocation size
//const size_t block_size = 256;
const size_t block_size = 32;
size_t block_count;
for (block_count = 1; ; block_count++) {
void* ptr = malloc(block_count * block_size);
if (ptr == nullptr) {
break;
}
free(ptr);
}
return (block_count - 1) * block_size;
}
/*static*/ size_t Memory::heap_size() {
#if defined(ESP32)
return ESP.getHeapSize();
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
return dbgHeapTotal();
#else
return 0;
#endif
}
/*static*/ size_t Memory::heap_available() {
#if defined(ESP32)
return ESP.getFreeHeap();
//return ESP.getMaxAllocHeap();
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
return dbgHeapFree();
#else
return 0;
#endif
}
/*static*/ void Memory::dump_heap_stats() {
#if defined(ESP32)
HEAD("Heap Stats", LOG_TRACE);
TRACEF(" Heap size: %u", ESP.getHeapSize());
TRACEF(" Heap free: %u (%u%% free)", ESP.getFreeHeap(), (unsigned)((double)ESP.getFreeHeap() / (double)ESP.getHeapSize() * 100.0));
//TRACEF(" Heap free: %u (%u%% free)", xPortGetFreeHeapSize(), (unsigned)((double)xPortGetFreeHeapSize() / (double)xPort * 100.0));
TRACEF(" Heap min free: %u", ESP.getMinFreeHeap());
//TRACEF(" Heap min free: %u", xPortGetMinimumEverFreeHeapSize());
TRACEF(" Heap max alloc: %u (%u%% fragmented)", ESP.getMaxAllocHeap(), (unsigned)(100.0 - (double)ESP.getMaxAllocHeap() / (double)ESP.getFreeHeap() * 100.0));
//TRACEF(" Heap max alloc: %u (%u%% fragmented)", ESP.getMaxAllocHeap(), (unsigned)(100.0 - (double)ESP.getMaxAllocHeap() / (double)xPortGetFreeHeapSize() * 100.0));
TRACEF(" PSRAM size: %u", ESP.getPsramSize());
TRACEF(" PSRAM free: %u (%u%% free)", ESP.getFreePsram(), (ESP.getPsramSize() > 0) ? (unsigned)((double)ESP.getFreePsram() / (double)ESP.getPsramSize() * 100.0) : 0);
TRACEF(" PSRAM min free: %u", ESP.getMinFreePsram());
TRACEF(" PSRAM max alloc: %u (%u%% fragmented)", ESP.getMaxAllocPsram(), (ESP.getFreePsram() > 0) ? (unsigned)(100.0 - (double)ESP.getMaxAllocPsram() / (double)ESP.getFreePsram() * 100.0) : 0);
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
HEAD("Heap Stats", LOG_TRACE);
if (loglevel() == LOG_TRACE) {
dbgMemInfo();
}
#endif
dump_allocator_stats(default_allocator_info, "Default ");
dump_allocator_stats(container_allocator_info, "Container ");
dump_pool_stats(heap_pool_info, "Heap ");
dump_pool_stats(psram_pool_info, "PSRAM ");
dump_pool_stats(altheap_pool_info, "AltHeap ");
dump_basic_pool_stats();
dump_basic_allocator_stats();
}
// Only override new/delete if RNS_DEFAULT_ALLOCATOR is not RNS_HEAP_ALLOCATOR
#if RNS_DEFAULT_ALLOCATOR != RNS_HEAP_ALLOCATOR
void* allocator_malloc(size_t size) {
if (size == 0) return nullptr;
++Memory::default_allocator_info.alloc_count;
Memory::default_allocator_info.alloc_size += size;
if (size < Memory::default_allocator_info.min_alloc_size || Memory::default_allocator_info.min_alloc_size == 0) {
Memory::default_allocator_info.min_alloc_size = size;
}
if (size > Memory::default_allocator_info.max_alloc_size) {
Memory::default_allocator_info.max_alloc_size = size;
}
#if RNS_DEFAULT_ALLOCATOR == RNS_HEAP_POOL_ALLOCATOR
return Memory::pool_malloc(Memory::heap_pool_info, size);
#elif RNS_DEFAULT_ALLOCATOR == RNS_PSRAM_ALLOCATOR
#if BOARD_HAS_PSRAM != 1
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
#endif
// CBA PSRAM may not be accessible early in startup, but since we use the same free() for both
// HEAP and PSRAM allocations, we canb simply fallback to HEAP allocation when PSRAM fails
void* p = ps_malloc(size);
if (p == nullptr) {
++Memory::default_allocator_info.alloc_fault;
p = malloc(size);
}
return p;
#elif RNS_DEFAULT_ALLOCATOR == RNS_PSRAM_POOL_ALLOCATOR
#error "RNS_DEFAULT_ALLOCATOR can not be set to RNS_PSRAM_POOL_ALLOCATOR because PSRAM isn't initialized early enough."
#if BOARD_HAS_PSRAM != 1
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
#endif
return Memory::pool_malloc(Memory::psram_pool_info, size);
#elif RNS_DEFAULT_ALLOCATOR == RNS_ALTHEAP_POOL_ALLOCATOR
return Memory::pool_malloc(Memory::altheap_pool_info, size);
#elif RNS_DEFAULT_ALLOCATOR == RNS_HEAP_ALLOCATOR
return ::operator new(n * sizeof(value_type));
#else
#error "Unknown or invalid allocator."
#endif
}
void allocator_free(void* p, size_t size = 0) noexcept {
if (p == nullptr) return;
++Memory::default_allocator_info.free_count;
Memory::default_allocator_info.alloc_size -= size;
#if RNS_DEFAULT_ALLOCATOR == RNS_HEAP_POOL_ALLOCATOR
Memory::pool_free(Memory::heap_pool_info, p, size);
#elif RNS_DEFAULT_ALLOCATOR == RNS_PSRAM_ALLOCATOR
#if BOARD_HAS_PSRAM != 1
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
#endif
free(p);
#elif RNS_DEFAULT_ALLOCATOR == RNS_PSRAM_POOL_ALLOCATOR
#error "RNS_DEFAULT_ALLOCATOR can not be set to RNS_PSRAM_POOL_ALLOCATOR because PSRAM isn't initialized early enough."
#if BOARD_HAS_PSRAM != 1
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
#endif
Memory::pool_free(Memory::psram_pool_info, p, size);
#elif RNS_DEFAULT_ALLOCATOR == RNS_ALTHEAP_POOL_ALLOCATOR
Memory::pool_free(Memory::altheap_pool_info, p, size);
#elif RNS_DEFAULT_ALLOCATOR == RNS_HEAP_ALLOCATOR
::operator delete(p);
#else
#error "Unknown or invalid allocator."
#endif
}
//--------------------------------------------------
// Standard allocation
//--------------------------------------------------
// CBA Added attribute weak to avoid collision with new override on nrf52
void* operator new(size_t size) {
//__attribute__((weak)) void* operator new(size_t size) {
//printf("--- new allocating memory from tlsf (%u bytes)\n", size);
void* p = allocator_malloc(size);
if (p == nullptr) {
throw std::bad_alloc();
}
return p;
}
void* operator new[](size_t size) {
//printf("--- new[] allocating memory from tlsf (%u bytes)\n", size);
void* p = allocator_malloc(size);
if (p == nullptr) {
throw std::bad_alloc();
}
return p;
}
//--------------------------------------------------
// Nothrow allocation
//--------------------------------------------------
void* operator new(size_t size, const std::nothrow_t&) noexcept {
//printf("--- new no-throw allocating memory from tlsf (%u bytes)\n", size);
return allocator_malloc(size);
}
void* operator new[](size_t size, const std::nothrow_t&) noexcept {
//printf("--- new[] no-throw allocating memory from tlsf (%u bytes)\n", size);
return allocator_malloc(size);
}
//--------------------------------------------------
// Standard delete
//--------------------------------------------------
// CBA Added attribute weak to avoid collision with new override on nrf52
void operator delete(void* p) noexcept {
//__attribute__((weak)) void operator delete(void* p) noexcept {
//printf("--- delete freeing memory from tlsf (addr=%lx)\n", p);
if (p != nullptr) allocator_free(p);
}
void operator delete[](void* p) noexcept {
//printf("--- delete[] freeing memory from tlsf (addr=%lx)\n", p);
if (p != nullptr) allocator_free(p);
}
//--------------------------------------------------
// Sized delete (C++14+)
//--------------------------------------------------
void operator delete(void* p, size_t size) noexcept { // sized delete
//printf("--- delete(size) freeing memory from tlsf (addr=%lx)\n", p);
if (p != nullptr) allocator_free(p, size);
}
void operator delete[](void* p, size_t size) noexcept {
//printf("--- delete[](size) freeing memory from tlsf (addr=%lx)\n", p);
if (p != nullptr) allocator_free(p, size);
}
//--------------------------------------------------
// Nothrow delete
//--------------------------------------------------
void operator delete(void* p, const std::nothrow_t&) noexcept {
//printf("--- delete no-throw freeing memory from tlsf (addr=%lx)\n", p);
if (p != nullptr) allocator_free(p);
}
void operator delete[](void* p, const std::nothrow_t&) noexcept {
//printf("--- delete[] no-throw freeing memory from tlsf (addr=%lx)\n", p);
if (p != nullptr) allocator_free(p);
}
//--------------------------------------------------
// Aligned allocation/delete (C++17+)
//--------------------------------------------------
#if __cplusplus >= 201703L
void* operator new(size_t size, std::align_val_t) {
//printf("--- new aligned allocating memory from tlsf (%u bytes)\n", size);
void* p = allocator_malloc(size);
if (p == nullptr) {
throw std::bad_alloc();
}
return p;
}
void operator delete(void* p, std::align_val_t) {
//printf("--- delete aligned freeing memory from tlsf (addr=%lx)\n", p);
if (p != nullptr) allocator_free(p);
}
#endif
#endif
+172
View File
@@ -0,0 +1,172 @@
#pragma once
#include "../Log.h"
#include "tlsf.h"
#include <memory>
#define RNS_HEAP_ALLOCATOR 0 // Use HEAP for allocator
#define RNS_HEAP_POOL_ALLOCATOR 1 // Use HEAP pool for allocator
#define RNS_PSRAM_ALLOCATOR 2 // Use PSRAM for allocator
#define RNS_PSRAM_POOL_ALLOCATOR 3 // Use PSRAM pool for allocator
#define RNS_ALTHEAP_POOL_ALLOCATOR 4 // Use alternate HEAP pool for allocator
namespace RNS { namespace Utilities {
class Memory {
private:
struct pool_info {
pool_info(uint8_t t, size_t s) : type(t), buffer_size(s) {}
uint8_t type = 0;
bool pool_init = false;
size_t buffer_size = 0;
size_t contiguous_size = 0;
tlsf_t tlsf = nullptr;
uint32_t alloc_fault = 0;
uint32_t free_fault = 0;
size_t last_free = 0;
};
struct allocator_info {
uint32_t alloc_count = 0;
uint32_t alloc_fault = 0;
uint32_t free_count = 0;
uint32_t free_fault = 0;
uint64_t alloc_size = 0;
size_t min_alloc_size = 0;
size_t max_alloc_size = 0;
uint64_t last_size = 0;
};
public:
static void pool_init(pool_info& pool_info);
static void* pool_malloc(pool_info& pool_info, size_t size);
static void pool_free(pool_info& pool_info, void* p, size_t size = 0) noexcept;
static void dump_pool_stats(pool_info& pool_info, const char* name = "");
static void dump_basic_pool_stats();
static void dump_allocator_stats(Memory::allocator_info& allocator_info, const char* name = "");
static void dump_basic_allocator_stats();
static size_t heap_size();
static size_t heap_available();
static void dump_heap_stats();
public:
static pool_info heap_pool_info;
static pool_info psram_pool_info;
static pool_info altheap_pool_info;
static allocator_info default_allocator_info;
static allocator_info container_allocator_info;
public:
template <typename T>
struct ContainerAllocator {
using value_type = T;
ContainerAllocator() noexcept {}
// Essential for std::map internal node allocation
template <class U>
ContainerAllocator(const ContainerAllocator<U>&) noexcept {}
/*
// Required for embedded toolchains (ESP32 Xtensa GCC) that don't synthesiz
// rebind automatically via std::allocator_traits
template<class U>
struct rebind {
using other = ContainerAllocator<U>;
};
*/
T* allocate(std::size_t n) {
if (n == 0) return nullptr;
size_t size = n * sizeof(value_type);
++container_allocator_info.alloc_count;
container_allocator_info.alloc_size += size;
if (size < container_allocator_info.min_alloc_size || container_allocator_info.min_alloc_size == 0) {
container_allocator_info.min_alloc_size = size;
}
if (size > container_allocator_info.max_alloc_size) {
container_allocator_info.max_alloc_size = size;
}
#if RNS_CONTAINER_ALLOCATOR == RNS_HEAP_POOL_ALLOCATOR
void* p = pool_malloc(heap_pool_info, size);
#elif RNS_CONTAINER_ALLOCATOR == RNS_PSRAM_ALLOCATOR
#if BOARD_HAS_PSRAM != 1
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
#endif
// CBA PSRAM may not be accessible early in startup, but since we use the same free() for both
// HEAP and PSRAM allocations, we canb simply fallback to HEAP allocation when PSRAM fails
void* p = ps_malloc(size);
if (p == nullptr) {
++container_allocator_info.alloc_fault;
p = malloc(size);
}
#elif RNS_CONTAINER_ALLOCATOR == RNS_PSRAM_POOL_ALLOCATOR
#if BOARD_HAS_PSRAM != 1
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
#endif
void* p = pool_malloc(psram_pool_info, size);
#elif RNS_CONTAINER_ALLOCATOR == RNS_ALTHEAP_POOL_ALLOCATOR
void* p = pool_malloc(altheap_pool_info, size);
#elif RNS_CONTAINER_ALLOCATOR == RNS_HEAP_ALLOCATOR
void* p = ::operator new(size);
#else
#error "Unknown or invalid allocator."
#endif
if (p == nullptr) {
ERRORF("--- ContainerAllocator failed to allocate memory (%u bytes)", size);
throw std::bad_alloc();
}
//TRACEF("--- ContainerAllocator allocated memory (addr=%lx) (%u bytes)", p, size);
return static_cast<T*>(p);
}
void deallocate(T* p, std::size_t n) noexcept {
if (p == nullptr) return;
size_t size = n * sizeof(value_type);
++default_allocator_info.free_count;
container_allocator_info.alloc_size -= size;
//TRACEF("--- ContainerAllocator freeing memory (addr=%lx) (%u bytes)", p, size);
#if RNS_CONTAINER_ALLOCATOR == RNS_HEAP_POOL_ALLOCATOR
pool_free(heap_pool_info, p, size);
#elif RNS_CONTAINER_ALLOCATOR == RNS_PSRAM_ALLOCATOR
#if BOARD_HAS_PSRAM != 1
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
#endif
free(p);
#elif RNS_CONTAINER_ALLOCATOR == RNS_PSRAM_POOL_ALLOCATOR
#if BOARD_HAS_PSRAM != 1
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
#endif
pool_free(psram_pool_info, p, size);
#elif RNS_CONTAINER_ALLOCATOR == RNS_ALTHEAP_POOL_ALLOCATOR
pool_free(altheap_pool_info, p, size);
#elif RNS_CONTAINER_ALLOCATOR == RNS_HEAP_ALLOCATOR
::operator delete(p);
#else
#error "Unknown or invalid allocator."
#endif
}
// Equality operators are required
bool operator==(const ContainerAllocator&) const noexcept { return true; }
bool operator!=(const ContainerAllocator&) const noexcept { return false; }
//template <class T, class U>
//bool operator==(const MyAllocator<T>&, const MyAllocator<U>&) { return true; }
//template <class T, class U>
//bool operator!=(const MyAllocator<T>&, const MyAllocator<U>&) { return false; }
};
};
} }
+1 -362
View File
@@ -8,367 +8,6 @@
using namespace RNS;
using namespace RNS::Utilities;
#if defined(RNS_USE_ALLOCATOR)
#if defined(RNS_USE_TLSF)
#if defined(ESP32)
#ifndef RNS_TLSF_BUFFER_SIZE
//#define RNS_TLSF_BUFFER_SIZE 1024 * 80
#define RNS_TLSF_BUFFER_SIZE 0
#endif
#ifndef BUFFER_FRACTION
#define BUFFER_FRACTION 0.8
#endif
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
#ifndef RNS_TLSF_BUFFER_SIZE
//#define RNS_TLSF_BUFFER_SIZE 1024 * 80
#define RNS_TLSF_BUFFER_SIZE 0
#endif
#ifndef BUFFER_FRACTION
#define BUFFER_FRACTION 0.8
#endif
#else
#ifndef RNS_TLSF_BUFFER_SIZE
#define RNS_TLSF_BUFFER_SIZE 1024 * 1000
#endif
#ifndef BUFFER_FRACTION
#define BUFFER_FRACTION 0
#endif
#endif
struct tlsf_stats {
uint32_t used_count = 0;
uint32_t used_size = 0;
uint32_t free_count = 0;
uint32_t free_size = 0;
uint32_t free_max_size = 0;
};
bool _pool_init = false;
//char _tlsf_msg[256] = "";
size_t _buffer_size = RNS_TLSF_BUFFER_SIZE;
size_t _contiguous_size = 0;
/*static*/ //tlsf_t OS::_tlsf = tlsf_create_with_pool(malloc(1024 * 1024), 1024 * 1024);
/*static*/ tlsf_t OS::_tlsf = nullptr;
#endif // RNS_USE_TLSF
uint32_t _new_count = 0;
uint32_t _new_fault = 0;
uint64_t _new_size = 0;
uint32_t _delete_count = 0;
uint32_t _delete_fault = 0;
size_t _min_size = 0;
size_t _max_size = 0;
void tlsf_mem_walker(void* ptr, size_t size, int used, void* user);
void dump_tlsf_stats();
#if defined(RNS_USE_TLSF)
inline void pool_init() {
#if defined(ESP32)
// CBA Still unknown why the call to tlsf_create_with_pool() is so flaky on ESP32 with calculated buffer size. Reuires more research and unit tests.
_contiguous_size = ESP.getMaxAllocHeap();
TRACEF("TLSF: contiguous_size: %u", _contiguous_size);
if (_buffer_size == 0) {
// CBA NOTE Using fp mathhere somehow causes tlsf_create_with_pool() to fail.
//_buffer_size = (size_t)(_contiguous_size * BUFFER_FRACTION);
// Compute 80% exactly using integers
_buffer_size = (_contiguous_size * 4) / 5;
}
// Round DOWN to TLSF alignment
size_t align = tlsf_align_size();
_buffer_size &= ~(align - 1);
void* raw_buffer = (void*)aligned_alloc(align, _buffer_size);
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
_contiguous_size = dbgHeapFree();
TRACEF("TLSF: contiguous_size: %u", _contiguous_size);
if (_buffer_size == 0) {
_buffer_size = (size_t)(_contiguous_size * BUFFER_FRACTION);
}
// For NRF52 round to kB
_buffer_size = (size_t)(_buffer_size / 1024) * 1024;
TRACEF("TLSF: buffer_size: %u", _buffer_size);
void* raw_buffer = malloc(_buffer_size);
#else
_buffer_size = (size_t)RNS_TLSF_BUFFER_SIZE;
TRACEF("TLSF: buffer_size: %u", _buffer_size);
void* raw_buffer = malloc(_buffer_size);
#endif
if (raw_buffer == nullptr) {
ERROR("-- TLSF: buffer allocation FAILED");
//strcpy(_tlsf_msg, "-- TLSF: buffer allocation FAILED!!!");
}
else {
#if 1
OS::_tlsf = tlsf_create_with_pool(raw_buffer, _buffer_size);
if (OS::_tlsf == nullptr) {
//sprintf(_tlsf_msg, "TLSF: initialization with align=%d, contiguous=%d, size=%d FAILED!!!", tlsf_align_size(), _contiguous_size, _buffer_size);
printf("TLSF: initialization with align=%d, contiguous=%d, size=%d FAILED!!!\n", tlsf_align_size(), _contiguous_size, _buffer_size);
}
else {
//sprintf(_tlsf_msg, "TLSF: initialization with align=%d, contiguous=%d, size=%d SUCCESSFUL!!!", tlsf_align_size(), _contiguous_size, _buffer_size);
printf("TLSF: initialization with align=%d, contiguous=%d, size=%d SUCCESSFUL!!!\n", tlsf_align_size(), _contiguous_size, _buffer_size);
}
#else
Serial.print("TLSF: raw_buffer: ");
Serial.println((long)raw_buffer);
Serial.print("TLSF: align_size: ");
Serial.println((long)tlsf_align_size());
void* aligned_buffer = (void*)(((size_t)raw_buffer + (tlsf_align_size() - 1)) & ~(tlsf_align_size() - 1));
Serial.print("TLSF: aligned_buffer: ");
Serial.println((long)aligned_buffer);
OS::_tlsf = tlsf_create_with_pool(aligned_buffer, _buffer_size-(size_t)((uint32_t)aligned_buffer - (uint32_t)raw_buffer));
//tlfs = tlsf_create_with_pool(aligned_buffer, buffer_size--(size_t)((uint32_t)aligned_buffer - (uint32_t)raw_buffer));
#endif
if (OS::_tlsf == nullptr) {
ERROR("-- TLSF: initialization of FAILED");
}
}
}
#endif // RNS_USE_TLSF
void* pool_malloc(std::size_t size) {
#if defined(RNS_USE_TLSF)
//if (OS::_tlsf == nullptr) {
if (!_pool_init) {
_pool_init = true;
printf("Initializing TLSF pool...\n");
pool_init();
}
#endif // RNS_USE_TLSF
++_new_count;
_new_size += size;
if (size < _min_size || _min_size == 0) {
_min_size = size;
}
//if (size > _max_size) {
if (size < 4192 && size > _max_size) {
_max_size = size;
}
void* p;
#if defined(RNS_USE_TLSF)
if (OS::_tlsf != nullptr) {
//struct tlsf_stats stats;
//memset(&stats, 0, sizeof(stats));
//tlsf_walk_pool(tlsf_get_pool(OS::_tlsf), tlsf_mem_walker, &stats);
//if (tlsf_check(OS::_tlsf) != 0) {
// printf("--- HEAP CORRUPTION DETECTED!!!\n");
//}
//TRACEF("--- allocating memory from tlsf (%u bytes)", size);
//printf("--- allocating memory from tlsf (%u bytes) (%u free)\n", size, stats.free_size);
p = tlsf_malloc(OS::_tlsf, size);
//TRACEF("--- allocated memory from tlsf (addr=%lx) (%u bytes)", p, size);
//printf("--- allocated memory from tlsf (addr=%lx) (%u bytes)\n", p, size);
}
else {
//TRACEF("--- allocating memory (%u bytes)", size);
p = malloc(size);
//TRACEF("--- allocated memory (addr=%lx) (%u bytes)", p, size);
++_new_fault;
}
#else
//TRACEF("--- allocating memory (%u bytes)", size);
p = malloc(size);
//TRACEF("--- allocated memory (addr=%lx) (%u bytes)", p, size);
#endif // RNS_USE_TLSF
return p;
}
void pool_free(void* p) noexcept {
#if defined(RNS_USE_TLSF)
if (OS::_tlsf != nullptr) {
//TRACEF("--- freeing memory from tlsf (addr=%lx)", p);
//printf("--- freeing memory from tlsf (addr=%lx)\n", p);
tlsf_free(OS::_tlsf, p);
}
else {
//TRACEF("--- freeing memory (addr=%lx)", p);
free(p);
++_delete_fault;
}
#else
//TRACEF("--- freeing memory (addr=%lx)", p);
//TRACE("--- freeing memory");
free(p);
#endif // RNS_USE_TLSF
++_delete_count;
#if defined(RNS_USE_TLSF)
//if (_delete_count == _new_count) {
// TRACE("TLFS deinitializing");
// OS::dump_memory_stats();
// tlsf_destroy(OS::_tlsf);
// OS::_tlsf = nullptr;
//}
#endif
}
// CBA Added attribute weak to avoid collision with new override on nrf52
void* operator new(std::size_t size) {
//__attribute__((weak)) void* operator new(std::size_t size) {
//printf("--- new allocating memory from tlsf (%u bytes)\n", size);
void* p = pool_malloc(size);
if (p == nullptr) {
throw std::bad_alloc();
}
return p;
}
// CBA Added attribute weak to avoid collision with new override on nrf52
void operator delete(void* p) noexcept {
//__attribute__((weak)) void operator delete(void* p) noexcept {
//printf("--- delete freeing memory from tlsf (addr=%lx)\n", p);
pool_free(p);
}
/**/
void* operator new[](std::size_t size) {
//printf("--- new[] allocating memory from tlsf (%u bytes)\n", size);
void* p = pool_malloc(size);
if (p == nullptr) {
throw std::bad_alloc();
}
return p;
}
void operator delete[](void* p) noexcept {
//printf("--- delete[] freeing memory from tlsf (addr=%lx)\n", p);
pool_free(p);
}
void operator delete(void* p, std::size_t size) noexcept { // sized delete
//printf("--- delete(size) freeing memory from tlsf (addr=%lx)\n", p);
pool_free(p);
}
void operator delete[](void* p, std::size_t size) noexcept {
//printf("--- delete[](size) freeing memory from tlsf (addr=%lx)\n", p);
pool_free(p);
}
/**/
#if defined(RNS_USE_TLSF)
void tlsf_mem_walker(void* ptr, size_t size, int used, void* user)
{
if (!user) {
return;
}
struct tlsf_stats* stats = (struct tlsf_stats*)user;
if (used) {
stats->used_count++;
stats->used_size += size;
}
else {
stats->free_count++;
stats->free_size += size;
if (size > stats->free_max_size) {
stats->free_max_size = size;
}
}
}
void dump_tlsf_stats() {
struct tlsf_stats stats;
memset(&stats, 0, sizeof(stats));
//TRACEF("TLSF Message: %s", _tlsf_msg);
if (OS::_tlsf == nullptr) {
return;
}
tlsf_walk_pool(tlsf_get_pool(OS::_tlsf), tlsf_mem_walker, &stats);
HEAD("TLSF Stats", LOG_TRACE);
TRACEF("Buffer Size: %u", _buffer_size);
TRACEF("Contiguous Size: %u", _contiguous_size);
TRACEF("Used Count: %u", stats.used_count);
TRACEF("Used Size: %u (%u%% used)", stats.used_size, (unsigned)((double)stats.used_size / (double)_buffer_size * 100.0));
TRACEF("Free Count: %u", stats.free_count);
TRACEF("Free Size: %u (%u%% free)", stats.free_size, (unsigned)((double)stats.free_size / (double)_buffer_size * 100.0));
TRACEF("Max Free Size: %u (%u%% fragmented)\n", stats.free_max_size, (unsigned)(100.0 - (double)stats.free_max_size / (double)stats.free_size * 100.0));
}
#endif // RNS_USE_TLSF
/*static*/ void OS::dump_allocator_stats() {
HEAD("Allocator Stats", LOG_TRACE);
TRACEF("New Count: %u", _new_count);
TRACEF("New Fault: %u", _new_fault);
TRACEF("Delete Count: %u", _delete_count);
TRACEF("Delete Fault: %u", _delete_fault);
TRACEF("Active Count: %u", (_new_count - _delete_count));
TRACEF("Min Size: %u", _min_size);
TRACEF("Max Size: %u", _max_size);
TRACEF("Avg Size: %u\n", (size_t)(_new_size / _new_count));
#if defined(RNS_USE_TLSF)
dump_tlsf_stats();
#endif
}
#endif // RNS_USE_ALLOCATOR
size_t maxContiguousAllocation() {
// Brute-force determine maximum allocation size
//const size_t block_size = 256;
const size_t block_size = 32;
size_t block_count;
for (block_count = 1; ; block_count++) {
void* ptr = malloc(block_count * block_size);
if (ptr == nullptr) {
break;
}
free(ptr);
}
return (block_count - 1) * block_size;
}
/*static*/ FileSystem OS::_filesystem = {Type::NONE};
/*static*/ uint64_t OS::_time_offset = 0;
/*static*/ size_t OS::heap_size() {
#if defined(ESP32)
return ESP.getHeapSize();
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
return dbgHeapTotal();
#else
return 0;
#endif
}
/*static*/ size_t OS::heap_available() {
#if defined(ESP32)
return ESP.getFreeHeap();
//return ESP.getMaxAllocHeap();
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
return dbgHeapFree();
#else
return 0;
#endif
}
/*static*/ void OS::dump_heap_stats() {
HEAD("Heap Stats", LOG_TRACE);
#if defined(ESP32)
TRACEF("Heap size: %u", ESP.getHeapSize());
TRACEF("Heap free: %u (%u%% free)", ESP.getFreeHeap(), (unsigned)((double)ESP.getFreeHeap() / (double)ESP.getHeapSize() * 100.0));
//TRACEF("Heap free: %u (%u%% free)", xPortGetFreeHeapSize(), (unsigned)((double)xPortGetFreeHeapSize() / (double)xPort * 100.0));
TRACEF("Heap min free: %u", ESP.getMinFreeHeap());
//TRACEF("Heap min free: %u", xPortGetMinimumEverFreeHeapSize());
TRACEF("Heap max alloc: %u (%u%% fragmented)", ESP.getMaxAllocHeap(), (unsigned)(100.0 - (double)ESP.getMaxAllocHeap() / (double)ESP.getFreeHeap() * 100.0));
//TRACEF("Heap max alloc: %u (%u%% fragmented)", ESP.getMaxAllocHeap(), (unsigned)(100.0 - (double)ESP.getMaxAllocHeap() / (double)xPortGetFreeHeapSize() * 100.0));
TRACEF("PSRAM size: %u", ESP.getPsramSize());
TRACEF("PSRAM free: %u (%u%% free)", ESP.getFreePsram(), (ESP.getPsramSize() > 0) ? (unsigned)((double)ESP.getFreePsram() / (double)ESP.getPsramSize() * 100.0) : 0);
TRACEF("PSRAM min free: %u", ESP.getMinFreePsram());
TRACEF("PSRAM max alloc: %u (%u%% fragmented)", ESP.getMaxAllocPsram(), (ESP.getFreePsram() > 0) ? (unsigned)(100.0 - (double)ESP.getMaxAllocPsram() / (double)ESP.getFreePsram() * 100.0) : 0);
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
if (loglevel() == LOG_TRACE) {
dbgMemInfo();
}
#endif
#if defined(RNS_USE_ALLOCATOR)
OS::dump_allocator_stats();
#endif
}
/*static*/ OS::LoopCallback OS::_on_loop = nullptr;
+49 -34
View File
@@ -4,9 +4,9 @@
#include "../FileStream.h"
#include "../Bytes.h"
#include "tlsf.h"
#include <cmath>
#include <memory>
#include <functional>
#include <unistd.h>
#include <time.h>
#include <stdint.h>
@@ -14,6 +14,9 @@
#ifdef ARDUINO
#include <Arduino.h>
#if defined(ESP32)
#include "esp_task_wdt.h"
#endif
#endif
#undef round
@@ -22,20 +25,22 @@ namespace RNS { namespace Utilities {
class OS {
public:
//using LoopCallback = void(*)();
using LoopCallback = std::function<void()>;
private:
static FileSystem _filesystem;
static uint64_t _time_offset;
static LoopCallback _on_loop;
public:
static tlsf_t _tlsf;
public:
static inline uint64_t getTimeOffset() { return _time_offset; }
static inline void setTimeOffset(uint64_t offset) { _time_offset = offset; }
inline static uint64_t getTimeOffset() { return _time_offset; }
inline static void setTimeOffset(uint64_t offset) { _time_offset = offset; }
#ifdef ARDUINO
// return current time in milliseconds since startup
static inline uint64_t ltime() {
inline static uint64_t ltime() {
// handle roll-over of 32-bit millis (approx. 49 days)
static uint32_t low32, high32;
uint32_t new_low32 = millis();
@@ -45,32 +50,32 @@ namespace RNS { namespace Utilities {
}
#else
// return current time in milliseconds since 00:00:00, January 1, 1970 (Unix Epoch)
static inline uint64_t ltime() { timeval time; ::gettimeofday(&time, NULL); return (uint64_t)(time.tv_sec * 1000) + (uint64_t)(time.tv_usec / 1000); }
inline static uint64_t ltime() { timeval time; ::gettimeofday(&time, NULL); return (uint64_t)(time.tv_sec * 1000) + (uint64_t)(time.tv_usec / 1000); }
#endif
#ifdef ARDUINO
// return current time in float seconds since startup
static inline double time() { return (double)(ltime() / 1000.0); }
inline static double time() { return (double)(ltime() / 1000.0); }
#else
// return current time in float seconds since 00:00:00, January 1, 1970 (Unix Epoch)
static inline double time() { timeval time; ::gettimeofday(&time, NULL); return (double)time.tv_sec + ((double)time.tv_usec / 1000000); }
inline static double time() { timeval time; ::gettimeofday(&time, NULL); return (double)time.tv_sec + ((double)time.tv_usec / 1000000); }
#endif
// sleep for specified milliseconds
//static inline void sleep(float seconds) { ::sleep(seconds); }
//inline static void sleep(float seconds) { ::sleep(seconds); }
#ifdef ARDUINO
static inline void sleep(float seconds) { delay((uint32_t)(seconds * 1000)); }
inline static void sleep(float seconds) { delay((uint32_t)(seconds * 1000)); }
#else
static inline void sleep(float seconds) { timespec time; time.tv_sec = (time_t)(seconds); time.tv_nsec = (seconds - (float)time.tv_sec) * 1000000000; ::nanosleep(&time, nullptr); }
inline static void sleep(float seconds) { timespec time; time.tv_sec = (time_t)(seconds); time.tv_nsec = (seconds - (float)time.tv_sec) * 1000000000; ::nanosleep(&time, nullptr); }
#endif
//static inline void sleep(uint32_t milliseconds) { ::sleep((float)milliseconds / 1000.0); }
//inline static void sleep(uint32_t milliseconds) { ::sleep((float)milliseconds / 1000.0); }
// round decimal number to specified precision
//static inline float round(float value, uint8_t precision) { return std::round(value / precision) * precision; }
//static inline double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
static inline double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
//inline static float round(float value, uint8_t precision) { return std::round(value / precision) * precision; }
//inline static double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
inline static double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
static inline uint64_t from_bytes_big_endian(const uint8_t* data, size_t len) {
inline static uint64_t from_bytes_big_endian(const uint8_t* data, size_t len) {
uint64_t result = 0;
for (size_t i = 0; i < len; ++i) {
result = (result << 8) | data[i];
@@ -79,17 +84,17 @@ namespace RNS { namespace Utilities {
}
// Detect endianness at runtime
static int is_big_endian(void) {
inline static int is_big_endian(void) {
uint16_t test = 0x0102;
return ((uint8_t*)&test)[0] == 0x01;
}
// Byte swap functions
static uint16_t swap16(uint16_t val) {
inline static uint16_t swap16(uint16_t val) {
return (val << 8) | (val >> 8);
}
static uint32_t swap32(uint32_t val) {
inline static uint32_t swap32(uint32_t val) {
return ((val << 24) & 0xFF000000) |
((val << 8) & 0x00FF0000) |
((val >> 8) & 0x0000FF00) |
@@ -98,25 +103,39 @@ namespace RNS { namespace Utilities {
// Platform-independent replacements
static uint16_t portable_htons(uint16_t val) {
inline static uint16_t portable_htons(uint16_t val) {
return is_big_endian() ? val : swap16(val);
}
static uint32_t portable_htonl(uint32_t val) {
inline static uint32_t portable_htonl(uint32_t val) {
return is_big_endian() ? val : swap32(val);
}
static uint16_t portable_ntohs(uint16_t val) {
inline static uint16_t portable_ntohs(uint16_t val) {
return is_big_endian() ? val : swap16(val);
}
static uint32_t portable_ntohl(uint32_t val) {
inline static uint32_t portable_ntohl(uint32_t val) {
return is_big_endian() ? val : swap32(val);
}
#if defined(RNS_USE_ALLOCATOR)
static void dump_allocator_stats();
inline static void reset_watchdog() {
#if defined(ESP32)
esp_task_wdt_reset();
#endif
}
inline static void set_loop_callback(LoopCallback on_loop = nullptr) { _on_loop = on_loop; }
inline static void run_loop() {
if (_on_loop) {
try {
_on_loop();
}
catch (const std::exception& e) {
ERRORF("run_loop: exception while looping: %s", e.what());
}
}
}
inline static void register_filesystem(FileSystem& filesystem) {
TRACE("Registering filesystem...");
@@ -204,11 +223,11 @@ namespace RNS { namespace Utilities {
return _filesystem.remove_directory(directory_path);
}
inline static std::list<std::string> list_directory(const char* directory_path) {
inline static std::list<std::string> list_directory(const char* directory_path, FileSystem::Callbacks::DirectoryListing callback = nullptr) {
if (!_filesystem) {
throw std::runtime_error("FileSystem has not been registered");
}
return _filesystem.list_directory(directory_path);
return _filesystem.list_directory(directory_path, callback);
}
inline static size_t storage_size() {
@@ -224,10 +243,6 @@ namespace RNS { namespace Utilities {
}
return _filesystem.storage_available();
}
static size_t heap_size();
static size_t heap_available();
static void dump_heap_stats();
};
+40 -29
View File
@@ -94,7 +94,7 @@ namespace ArduinoJson {
JsonObject obj = dst.to<JsonObject>();
for (const auto& item : src) {
//obj[item.first] = item.second;
obj[item.first.toHex()] = item.second;
obj[item.first.toBase64()] = item.second;
}
}
static std::map<RNS::Bytes, T> fromJson(JsonVariantConst src) {
@@ -102,7 +102,7 @@ namespace ArduinoJson {
for (JsonPairConst item : src.as<JsonObjectConst>()) {
//dst[item.key().c_str()] = item.value().as<T>();
RNS::Bytes key;
key.assignHex(item.key().c_str());
key.assignBase64(item.key().c_str());
//dst[key] = item.value().as<T>();
dst.insert({key, item.value().as<T>()});
}
@@ -209,7 +209,6 @@ namespace ArduinoJson {
//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");
return true;
}
@@ -220,8 +219,7 @@ namespace ArduinoJson {
RNS::Packet packet(RNS::Destination(RNS::Type::NONE), raw);
//packet.set_hash(src["hash"]);
packet.sent_at(src["sent_at"]);
RNS::Bytes destination_hash = src["destination_hash"];
// set cached flag since pcket was read from cache
// set cached flag since packet was read from cache
packet.cached(true);
//TRACE(">>> Finished deserializing Packet");
return packet;
@@ -230,8 +228,7 @@ namespace ArduinoJson {
return
//src["hash"].is<RNS::Bytes>() &&
src["raw"].is<RNS::Bytes>() &&
src["sent_at"].is<double>() &&
src["destination_hash"].is<RNS::Bytes>();
src["sent_at"].is<double>();
}
};
@@ -279,18 +276,21 @@ namespace ArduinoJson {
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;
}
*/
dst["interface_hash"] = src.receiving_interface_hash();
// 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.
// anyway if there's no space 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
@@ -307,8 +307,8 @@ namespace ArduinoJson {
dst["packet_hash"] = nullptr;
}
*/
dst["interface_hash"] = src._receiving_interface;
dst["packet_hash"] = src._announce_packet;
dst["packet_hash"] = src.announce_packet_hash();
//TRACE("<<< Finished Serializing Transport::DestinationEntry");
return true;
}
@@ -320,22 +320,25 @@ namespace ArduinoJson {
dst._hops = src["announce_hops"];
dst._expires = src["expires"];
dst._random_blobs = src["random_blobs"].as<std::set<RNS::Bytes>>();
/*
//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"];
*/
dst.receiving_interface_hash(src["interface_hash"]);
/*
RNS::Bytes packet_hash = src["packet_hash"];
if (packet_hash) {
// Query transport for matching packet
// Query transport for matching cached packet
dst._announce_packet = RNS::Transport::get_cached_packet(packet_hash);
}
*/
dst._receiving_interface = src["interface_hash"];
dst._announce_packet = src["packet_hash"];
dst.announce_packet_hash(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(
@@ -376,14 +379,18 @@ namespace RNS {
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;
}
*/
dst["interface_hash"] = src.receiving_interface_hash();
/*
// 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
@@ -404,8 +411,8 @@ namespace RNS {
dst["packet_hash"] = nullptr;
}
*/
dst["interface_hash"] = src._receiving_interface;
dst["packet_hash"] = src._announce_packet;
dst["packet_hash"] = src.announce_packet_hash();
//TRACE("<<< Finished Serializing Transport::DestinationEntry");
return true;
}
@@ -417,22 +424,25 @@ namespace RNS {
dst._hops = src["announce_hops"];
dst._expires = src["expires"];
dst._random_blobs = src["random_blobs"].as<std::set<RNS::Bytes>>();
/*
//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"];
*/
dst.receiving_interface_hash(src["interface_hash"]);
/*
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"];
dst.announce_packet_hash(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(
@@ -546,7 +556,7 @@ namespace RNS { namespace Persistence {
}
#if 1
template <typename T> uint32_t crc(std::map<Bytes, T>& map) {
template <typename T, typename Compare, typename Allocator> uint32_t crc(std::map<Bytes, T, Compare, Allocator>& map) {
//TRACE("Persistence::crc<map<Bytes, T>>");
uint32_t crc = 0;
@@ -582,7 +592,7 @@ namespace RNS { namespace Persistence {
return Utilities::Crc::crc32(crc, '}');
}
template <typename T> size_t serialize(std::map<Bytes, T>& map, const char* file_path, uint32_t& crc) {
template <typename T, typename Compare, typename Allocator> size_t serialize(std::map<Bytes, T, Compare, Allocator>& map, const char* file_path, uint32_t& crc) {
//TRACE("Persistence::serialize<map<Bytes,T>>");
// CBA TODO: Use stream here instead to avoid having to buffer entire structure
@@ -615,17 +625,18 @@ namespace RNS { namespace Persistence {
stream.write(',');
}
stream.write('}');
stream.flush();
TRACEF("Persistence::serialize: stream size: %d bytes", stream.size());
crc = stream.crc();
return stream.size();
}
template <typename T> size_t serialize(std::map<Bytes, T>& map, const char* file_path) {
template <typename T, typename Compare, typename Allocator> size_t serialize(std::map<Bytes, T, Compare, Allocator>& map, const char* file_path) {
uint32_t crc;
return serialize(map, file_path, crc);
}
template <typename T> size_t deserialize(std::map<Bytes, T>& map, const char* file_path, uint32_t& crc) {
template <typename T, typename Compare, typename Allocator> size_t deserialize(std::map<Bytes, T, Compare, Allocator>& map, const char* file_path, uint32_t& crc) {
//TRACE("Persistence::deserialize<map<Bytes,T>>");
// CBA TODO: Use stream here instead to avoid having to buffer entire structure
@@ -690,7 +701,7 @@ namespace RNS { namespace Persistence {
return stream.size();
}
template <typename T> size_t deserialize(std::map<Bytes, T>& map, const char* file_path) {
template <typename T, typename Compare, typename Allocator> size_t deserialize(std::map<Bytes, T, Compare, Allocator>& map, const char* file_path) {
uint32_t crc;
return deserialize(map, file_path, crc);
}
+114 -110
View File
@@ -33,8 +33,8 @@ public:
bool init() {
TRACE("FileSystem initializing...");
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
// Setup FileSystem
INFO("SPIFFS mounting FileSystem");
if (!SPIFFS.begin(true, "")){
@@ -59,22 +59,22 @@ public:
remove_file("/test");
}
DEBUG("SPIFFS FileSystem is ready");
#elif BOARD_NRF52
#elif BOARD_NRF52
// Initialize Internal File System
INFO("InternalFS mounting FileSystem");
InternalFS.begin();
INFO("InternalFS FileSystem is ready");
#endif
#endif
#endif
#endif
return true;
}
public:
static void listDir(const char* dir) {
#ifdef ARDUINO
#ifdef ARDUINO
Serial.print("DIR: ");
Serial.println(dir);
#ifdef BOARD_ESP32
#ifdef BOARD_ESP32
File root = SPIFFS.open(dir);
if (!root) {
Serial.println("Failed to opend directory");
@@ -93,7 +93,7 @@ public:
file = root.openNextFile();
}
root.close();
#elif BOARD_NRF52
#elif BOARD_NRF52
File root = InternalFS.open(dir);
if (!root) {
Serial.println("Failed to opend directory");
@@ -112,38 +112,38 @@ public:
file = root.openNextFile();
}
root.close();
#endif
#endif
#endif
#endif
}
public:
virtual bool file_exists(const char* file_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(file_path, FILE_READ);
if (file) {
#elif BOARD_NRF52
#elif BOARD_NRF52
File file(InternalFS);
if (file.open(file_path, FILE_O_READ)) {
#else
#else
if (false) {
#endif
#else
#endif
#else
// Native
FILE* file = fopen(file_path, "r");
if (file != nullptr) {
#endif
#endif
//TRACE("file_exists: file exists, closing file");
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
file.close();
#elif BOARD_NRF52
#elif BOARD_NRF52
file.close();
#endif
#else
#endif
#else
// Native
fclose(file);
#endif
#endif
return true;
}
else {
@@ -154,24 +154,24 @@ public:
virtual size_t read_file(const char* file_path, RNS::Bytes& data) {
size_t read = 0;
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(file_path, FILE_READ);
if (file) {
size_t size = file.size();
read = file.readBytes((char*)data.writable(size), size);
#elif BOARD_NRF52
#elif BOARD_NRF52
//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
#else
if (false) {
size_t size = 0;
#endif
#else
#endif
#else
// Native
FILE* file = fopen(file_path, "r");
if (file != nullptr) {
@@ -180,23 +180,23 @@ public:
rewind(file);
//size_t read = fread(data.writable(size), size, 1, file);
read = fread(data.writable(size), 1, size, file);
#endif
#endif
TRACEF("read_file: read %zu bytes from file %s", read, file_path);
if (read != size) {
ERRORF("read_file: failed to read file %s", file_path);
data.clear();
}
//TRACE("read_file: closing input file");
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
file.close();
#elif BOARD_NRF52
#elif BOARD_NRF52
file.close();
#endif
#else
#endif
#else
// Native
fclose(file);
#endif
#endif
}
else {
ERRORF("read_file: failed to open input file %s", file_path);
@@ -208,40 +208,40 @@ public:
// CBA TODO Replace remove with working truncation
remove_file(file_path);
size_t wrote = 0;
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(file_path, FILE_WRITE);
if (file) {
wrote = file.write(data.data(), data.size());
#elif BOARD_NRF52
#elif BOARD_NRF52
File file(InternalFS);
if (file.open(file_path, FILE_O_WRITE)) {
wrote = file.write(data.data(), data.size());
#else
#else
if (false) {
#endif
#else
#endif
#else
// Native
FILE* file = fopen(file_path, "w");
if (file != nullptr) {
//size_t wrote = fwrite(data.data(), data.size(), 1, file);
wrote = fwrite(data.data(), 1, data.size(), file);
#endif
#endif
TRACEF("write_file: wrote %zu bytes to file %s", wrote, file_path);
if (wrote < data.size()) {
WARNINGF("write_file: not all data was written to file %s", file_path);
}
//TRACE("write_file: closing output file");
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
file.close();
#elif BOARD_NRF52
#elif BOARD_NRF52
file.close();
#endif
#else
#endif
#else
// Native
fclose(file);
#endif
#endif
}
else {
ERRORF("write_file: failed to open output file %s", file_path);
@@ -251,8 +251,8 @@ public:
virtual RNS::FileStream open_file(const char* file_path, RNS::FileStream::MODE file_mode) {
TRACEF("open_file: opening file %s", file_path);
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
const char* mode;
if (file_mode == RNS::FileStream::MODE_READ) {
mode = FILE_READ;
@@ -273,14 +273,13 @@ public:
//if (!file) {
File* file = new File(SPIFFS.open(file_path, mode));
if (file == nullptr || !(*file)) {
if (file != nullptr) delete 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);
#elif BOARD_NRF52
int mode;
if (file_mode == RNS::FileStream::MODE_READ) {
mode = FILE_O_READ;
@@ -300,7 +299,10 @@ public:
ERRORF("open_file: unsupported mode %d", file_mode);
return {RNS::Type::NONE};
}
if (!file->open(file_path, mode)) {
//File file = File(InternalFS);
File* file = new File(InternalFS);
if (file == nullptr || !file->open(file_path, mode)) {
if (file != nullptr) delete file;
ERRORF("open_file: failed to open output file %s", file_path);
return {RNS::Type::NONE};
}
@@ -312,11 +314,11 @@ public:
//}
TRACEF("open_file: successfully opened file %s", file_path);
return RNS::FileStream(new FileStreamImpl(file));
#else
#warning("unsupported");
#else
#warning("unsupported");
return RNS::FileStream(RNS::Type::NONE);
#endif
#else // ARDUINO
#endif
#else // ARDUINO
// Native
const char* mode;
if (file_mode == RNS::FileStream::MODE_READ) {
@@ -340,136 +342,136 @@ public:
}
TRACEF("open_file: successfully opened file %s", file_path);
return RNS::FileStream(new FileStreamImpl(file));
#endif
#endif
}
virtual bool remove_file(const char* file_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
return SPIFFS.remove(file_path);
#elif BOARD_NRF52
#elif BOARD_NRF52
return InternalFS.remove(file_path);
#else
#else
return false;
#endif
#else
#endif
#else
// Native
return (remove(file_path) == 0);
#endif
#endif
}
virtual bool rename_file(const char* from_file_path, const char* to_file_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
return SPIFFS.rename(from_file_path, to_file_path);
#elif BOARD_NRF52
#elif BOARD_NRF52
return InternalFS.rename(from_file_path, to_file_path);
#else
#else
return false;
#endif
#else
#endif
#else
// Native
return (rename(from_file_path, to_file_path) == 0);
#endif
#endif
}
/*virtua*/ bool directory_exists(const char* directory_path) {
TRACEF("directory_exists: checking for existence of directory %s", directory_path);
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(directory_path, FILE_READ);
if (file) {
bool is_directory = file.isDirectory();
file.close();
return is_directory;
}
#elif BOARD_NRF52
#elif BOARD_NRF52
File file(InternalFS);
if (file.open(directory_path, FILE_O_READ)) {
bool is_directory = file.isDirectory();
file.close();
return is_directory;
}
#else
#else
if (false) {
return false;
}
#endif
#endif
else {
return false;
}
#else
#else
// Native
struct stat st = {0};
return (stat(directory_path, &st) == 0);
#endif
#endif
}
virtual bool create_directory(const char* directory_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
if (!SPIFFS.mkdir(directory_path)) {
ERRORF("create_directory: failed to create directorty %s", directory_path);
return false;
}
return true;
#elif BOARD_NRF52
#elif BOARD_NRF52
if (!InternalFS.mkdir(directory_path)) {
ERRORF("create_directory: failed to create directorty %s", directory_path);
return false;
}
return true;
#else
#else
return false;
#endif
#else
#endif
#else
// Native
struct stat st = {0};
if (stat(directory_path, &st) == 0) {
return true;
}
return (mkdir(directory_path, 0700) == 0);
#endif
#endif
}
/*virtua*/ bool remove_directory(const char* directory_path) {
TRACEF("remove_directory: removing directory %s", directory_path);
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
//if (!LittleFS.rmdir_r(directory_path)) {
if (!SPIFFS.rmdir(directory_path)) {
ERRORF("remove_directory: failed to remove directorty %s", directory_path);
return false;
}
return true;
#elif BOARD_NRF52
#elif BOARD_NRF52
if (!InternalFS.rmdir_r(directory_path)) {
ERRORF("remove_directory: failed to remove directory %s", directory_path);
return false;
}
return true;
#else
#else
return false;
#endif
#else
#endif
#else
// Native
if (rmdir(directory_path) == 0) {
ERRORF("remove_directory: failed to remove directory %s", directory_path);
return false;
}
return true;
#endif
#endif
}
/*virtua*/ std::list<std::string> list_directory(const char* directory_path) {
/*virtua*/ std::list<std::string> list_directory(const char* directory_path, Callbacks::DirectoryListing callback = nullptr) {
TRACEF("list_directory: listing directory %s", directory_path);
std::list<std::string> files;
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
File root = SPIFFS.open(directory_path);
#elif BOARD_NRF52
#elif BOARD_NRF52
File root = InternalFS.open(directory_path);
#endif
#endif
if (!root) {
ERRORF("list_directory: failed to open directory %s", directory_path);
return files;
@@ -478,7 +480,8 @@ public:
while (file) {
if (!file.isDirectory()) {
char* name = (char*)file.name();
files.push_back(name);
if (callback) callback(name);
else files.push_back(name);
}
// CBA Following close required to avoid leaking memory
file.close();
@@ -487,7 +490,7 @@ public:
TRACE("list_directory: returning directory listing");
root.close();
return files;
#else
#else
// Native
DIR *dir = opendir(directory_path);
if (dir == NULL) {
@@ -500,20 +503,21 @@ public:
continue;
}
char* name = entry->d_name;
files.push_back(name);
if (callback) callback(name);
else files.push_back(name);
}
if (closedir(dir) == -1) {
ERRORF("list_directory: failed to close directory %s", directory_path);
}
return files;
#endif
#endif
}
#ifdef ARDUINO
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef BOARD_ESP32
virtual size_t storage_size() {
return SPIFFS.totalBytes();
@@ -523,7 +527,7 @@ public:
return (SPIFFS.totalBytes() - SPIFFS.usedBytes());
}
#elif BOARD_NRF52
#elif BOARD_NRF52
static int _countLfsBlock(void *p, lfs_block_t block){
lfs_size_t *size = (lfs_size_t*) p;
@@ -558,9 +562,9 @@ public:
return (InternalFS.totalBytes() - InternalFS.usedBytes());
}
#endif
#endif
#else
#else
virtual size_t storage_size() {
return 0;
@@ -570,7 +574,7 @@ public:
return 0;
}
#endif
#endif
protected:
+142
View File
@@ -0,0 +1,142 @@
#include <unity.h>
#include <Bytes.h>
#include <Utilities/OS.h>
#include <Utilities/Memory.h>
#include <map>
#include <string>
#include <scoped_allocator>
//#define VECTOR_INTERNAL_CONTENT
//#define VECTOR_EXTERNAL_CONTENT
//#define BYTES_INTERNAL_CONTENT
#define BYTES_EXTERNAL_CONTENT
class TestObject {
public:
TestObject() {}
TestObject(const char* str, std::vector<std::string>& vec, RNS::Bytes& buf) : _str(str), _vec(vec), _external_buf(buf) {
#ifdef VECTOR_INTERNAL_CONTENT
// CBA The following vector entries use psram even though they're created internally (not part of base object)
_vec.push_back("fee");
_vec.push_back("fum");
#endif
#ifdef BYTES_INTERNAL_CONTENT
// CBA The following Bytes content use psram even though they're created internally (not part of base object)
_internal_buf.assign("This is a Bytes buffer allocated INSIDE of TestObject");
#endif
}
inline bool operator < (const TestObject& test) const { return _str < test._str; }
inline const std::string toString() const { return std::string("TestObject(") + _str + "," + std::to_string(_vec.size()) + "," + _internal_buf.toString() + "," + _external_buf.toString() + ")"; }
// CBA All of the following empty containers are included in the memory allocated for std::map and use psram
std::string _str;
std::vector<std::string> _vec;
RNS::Bytes _internal_buf;
RNS::Bytes _external_buf;
};
void test_map_allocator() {
// CBA TODO Figure out how to selectively use PSRAM for Bytes and Packet objects.
// Trigger creation of both heap and psram pool before starting
RNS::Utilities::Memory::pool_init(RNS::Utilities::Memory::heap_pool_info);
RNS::Utilities::Memory::pool_init(RNS::Utilities::Memory::altheap_pool_info);
//RNS::Utilities::Memory::dump_heap_stats();
HEAD("Initial Stats:", RNS::LOG_TRACE);
RNS::Utilities::Memory::dump_basic_pool_stats();
//RNS::Utilities::Memory::dump_basic_allocator_stats();
{
//using TestMap = std::map<Bytes, TestObject, std::less<Bytes>, RNS::Utilities::Memory::ContainerAllocator<std::pair<const Bytes, TestObject>>>;
using TestMap = std::map<std::string, TestObject, std::less<std::string>, RNS::Utilities::Memory::ContainerAllocator<std::pair<const std::string, TestObject>>>;
//using TestAlloc = RNS::Utilities::Memory::ContainerAllocator<std::pair<const std::string, TestObject>>;
//using TestStringAlloc = RNS::Utilities::Memory::ContainerAllocator<char>;
//using TestMap = std::map<std::string, TestObject, std::less<std::string>, std::scoped_allocator_adaptor<TestAlloc, TestStringAlloc>>;
HEAD("Post-map Stats:", RNS::LOG_TRACE);
RNS::Utilities::Memory::dump_basic_pool_stats();
//RNS::Utilities::Memory::dump_basic_allocator_stats();
// CBA The following empty vector object is included in the memory allocated for std::map and uses psram
std::vector<std::string> vec;
#ifdef VECTOR_EXTERNAL_CONTENT
// CBA The following vector entries use psram
vec.push_back("foo");
vec.push_back("bar");
#endif
// CBA The following empty Bytes object is included in the memory allocated for std::map and uses psram
RNS::Bytes buf;
#ifdef BYTES_EXTERNAL_CONTENT
// CBA The following Bytes content use psram
buf.assign("This is a Bytes buffer allocated OUTSIDE of TestObject");
#endif
TestMap map;
map.insert({"two", {"two", vec, buf}});
map.insert({"one", {"one", vec, buf}});
HEAD("Post-insert Stats:", RNS::LOG_TRACE);
RNS::Utilities::Memory::dump_basic_pool_stats();
//RNS::Utilities::Memory::dump_basic_allocator_stats();
TEST_ASSERT_EQUAL(2, map.size());
for (const auto& [key, entry] : map) {
TRACEF("key: %s, entry: %s", key.c_str(), entry.toString().c_str());
}
}
HEAD("Post-free Stats:", RNS::LOG_TRACE);
RNS::Utilities::Memory::dump_basic_pool_stats();
//RNS::Utilities::Memory::dump_basic_allocator_stats();
}
void setUp(void) {
// set stuff up here before each test
}
void tearDown(void) {
// clean stuff up here after each test
}
int runUnityTests(void) {
UNITY_BEGIN();
// Suite-level setup
// Run tests
RUN_TEST(test_map_allocator);
// Suite-level teardown
return UNITY_END();
}
// For native dev-platform or for some embedded frameworks
int main(void) {
return runUnityTests();
}
#ifdef ARDUINO
// For Arduino framework
void setup() {
// Wait ~2 seconds before the Unity test runner
// establishes connection with a board Serial interface
delay(2000);
runUnityTests();
}
void loop() {}
#endif
// For ESP-IDF framework
void app_main() {
runUnityTests();
}
+51 -3
View File
@@ -301,6 +301,53 @@ void testBytesConversion() {
}
void testBytesBase64() {
// encode "Hello World" → known base64 value
{
RNS::Bytes bytes("Hello World");
std::string b64 = bytes.toBase64();
TRACEF("text: \"%s\" base64: \"%s\"", bytes.toString().c_str(), b64.c_str());
TEST_ASSERT_EQUAL_STRING("SGVsbG8gV29ybGQ=", b64.c_str());
}
// decode known base64 string → "Hello World"
{
RNS::Bytes bytes;
bytes.assignBase64("SGVsbG8gV29ybGQ=");
std::string text = bytes.toString();
TRACEF("base64: \"SGVsbG8gV29ybGQ=\" text: \"%s\"", text.c_str());
TEST_ASSERT_EQUAL_size_t(11, text.length());
TEST_ASSERT_EQUAL_STRING("Hello World", text.c_str());
}
// round-trip stability
{
RNS::Bytes original("Hello World");
std::string b64 = original.toBase64();
RNS::Bytes restored;
restored.assignBase64(b64.c_str());
TEST_ASSERT_EQUAL_size_t(original.size(), restored.size());
TEST_ASSERT_EQUAL_MEMORY(original.data(), restored.data(), original.size());
}
// empty bytes → toBase64 returns ""
{
RNS::Bytes empty;
TEST_ASSERT_EQUAL_STRING("", empty.toBase64().c_str());
}
// assignBase64 then appendBase64 produces concatenated result
{
RNS::Bytes bytes;
bytes.assignBase64("SGVsbG8="); // "Hello"
bytes.appendBase64("IFdvcmxk"); // " World"
TEST_ASSERT_EQUAL_size_t(11, bytes.size());
TEST_ASSERT_EQUAL_MEMORY("Hello World", bytes.data(), bytes.size());
}
}
void testBytesResize() {
TRACE("Testing downsize of Bytes with initial capacity");
@@ -659,14 +706,15 @@ int runUnityTests(void) {
UNITY_BEGIN();
// Suite-level setup
RNS::Utilities::OS::dump_heap_stats();
size_t pre_memory = RNS::Utilities::OS::heap_available();
RNS::Utilities::Memory::dump_heap_stats();
size_t pre_memory = RNS::Utilities::Memory::heap_available();
TRACEF("testBytes: pre-mem: %u", pre_memory);
// Run tests
RUN_TEST(testBytesMain);
RUN_TEST(testCowBytes);
RUN_TEST(testBytesConversion);
RUN_TEST(testBytesBase64);
RUN_TEST(testBytesResize);
RUN_TEST(testBytesStream);
RUN_TEST(testBytesReserve);
@@ -686,7 +734,7 @@ int runUnityTests(void) {
RUN_TEST(test_mid_zero_size_bytes);
// Suite-level teardown
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t post_memory = RNS::Utilities::Memory::heap_available();
size_t diff_memory = (int)pre_memory - (int)post_memory;
TRACEF("testBytes: post-mem: %u", post_memory);
TRACEF("testBytes: diff-mem: %u", diff_memory);
+23 -27
View File
@@ -20,7 +20,7 @@ const char test_stream_path[] = "test_stream";
void writeFile(const char* file_path) {
size_t pre_memory = RNS::Utilities::OS::heap_available();
size_t pre_memory = RNS::Utilities::Memory::heap_available();
TRACEF("testWriteFile: pre-mem: %u", pre_memory);
{
@@ -29,7 +29,7 @@ void writeFile(const char* file_path) {
TEST_ASSERT_EQUAL_size_t(4, wrote);
}
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t post_memory = RNS::Utilities::Memory::heap_available();
size_t diff_memory = (int)pre_memory - (int)post_memory;
TRACEF("testWriteFile: post-mem: %u", post_memory);
TRACEF("testWriteFile: diff-mem: %u", diff_memory);
@@ -39,7 +39,7 @@ void writeFile(const char* file_path) {
void readFile(const char* file_path) {
size_t pre_memory = RNS::Utilities::OS::heap_available();
size_t pre_memory = RNS::Utilities::Memory::heap_available();
TRACEF("testReadFile: pre-mem: %u", pre_memory);
{
@@ -49,7 +49,7 @@ void readFile(const char* file_path) {
TEST_ASSERT_EQUAL_STRING("test", data.toString().c_str());
}
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t post_memory = RNS::Utilities::Memory::heap_available();
size_t diff_memory = (int)pre_memory - (int)post_memory;
TRACEF("testReadFile: post-mem: %u", post_memory);
TRACEF("testReadFile: diff-mem: %u", diff_memory);
@@ -59,7 +59,7 @@ void readFile(const char* file_path) {
void overwriteFile(const char* file_path) {
size_t pre_memory = RNS::Utilities::OS::heap_available();
size_t pre_memory = RNS::Utilities::Memory::heap_available();
TRACEF("testOverwriteFile: pre-mem: %u", pre_memory);
// overwrite
@@ -77,7 +77,7 @@ void overwriteFile(const char* file_path) {
TEST_ASSERT_EQUAL_STRING("test", data.toString().c_str());
}
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t post_memory = RNS::Utilities::Memory::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);
@@ -87,12 +87,12 @@ void overwriteFile(const char* file_path) {
void removeFile(const char* file_path) {
size_t pre_memory = RNS::Utilities::OS::heap_available();
size_t pre_memory = RNS::Utilities::Memory::heap_available();
TRACEF("testRemoveFile: pre-mem: %u", pre_memory);
TEST_ASSERT_TRUE(RNS::Utilities::OS::remove_file(file_path));
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t post_memory = RNS::Utilities::Memory::heap_available();
size_t diff_memory = (int)pre_memory - (int)post_memory;
TRACEF("testRemoveFile: post-mem: %u", post_memory);
TRACEF("testRemoveFile: diff-mem: %u", diff_memory);
@@ -102,7 +102,7 @@ void removeFile(const char* file_path) {
void writeFileStream(const char* file_path) {
size_t pre_memory = RNS::Utilities::OS::heap_available();
size_t pre_memory = RNS::Utilities::Memory::heap_available();
TRACEF("testWriteFileStream: pre-mem: %u", pre_memory);
{
@@ -121,7 +121,7 @@ void writeFileStream(const char* file_path) {
TEST_ASSERT_EQUAL_UINT32(crc, stream.crc());
}
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t post_memory = RNS::Utilities::Memory::heap_available();
size_t diff_memory = (int)pre_memory - (int)post_memory;
TRACEF("testWriteFileStream: post-mem: %u", post_memory);
TRACEF("testWriteFileStream: diff-mem: %u", diff_memory);
@@ -131,7 +131,7 @@ void writeFileStream(const char* file_path) {
void readFileStream(const char* file_path) {
size_t pre_memory = RNS::Utilities::OS::heap_available();
size_t pre_memory = RNS::Utilities::Memory::heap_available();
TRACEF("testReadFileStream: pre-mem: %u", pre_memory);
{
@@ -153,7 +153,7 @@ void readFileStream(const char* file_path) {
TEST_ASSERT_EQUAL_UINT32(crc, stream.crc());
}
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t post_memory = RNS::Utilities::Memory::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);
@@ -164,20 +164,16 @@ void readFileStream(const char* file_path) {
void testListDirectory() {
size_t pre_memory = RNS::Utilities::OS::heap_available();
size_t pre_memory = RNS::Utilities::Memory::heap_available();
INFOF("testListDirectory: pre-mem: %zu", pre_memory);
{
for (int i = 0; i < 1; i++) {
std::list<std::string> files;
files = RNS::Utilities::OS::list_directory("/");
for (auto& file : files) {
INFOF("FILE: %s", file.c_str());
}
}
RNS::Utilities::OS::list_directory("/", [](const char* file_path) {
INFOF("FILE: %s", file_path);
});
}
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t post_memory = RNS::Utilities::Memory::heap_available();
size_t diff_memory = (int)pre_memory - (int)post_memory;
INFOF("testListDirectory: post-mem: %zu", post_memory);
INFOF("testListDirectory: diff-mem: %zu", diff_memory);
@@ -202,7 +198,7 @@ void testRemoveFile(const char* file_path) {
void testReadNonexistantFile() {
size_t pre_memory = RNS::Utilities::OS::heap_available();
size_t pre_memory = RNS::Utilities::Memory::heap_available();
TRACEF("testReadNonexistantFile: pre-mem: %u", pre_memory);
{
@@ -211,7 +207,7 @@ void testReadNonexistantFile() {
TEST_ASSERT_EQUAL_size_t(0, read);
}
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t post_memory = RNS::Utilities::Memory::heap_available();
size_t diff_memory = (int)pre_memory - (int)post_memory;
TRACEF("testReadNonexistantFile: post-mem: %u", post_memory);
TRACEF("testReadNonexistantFile: diff-mem: %u", diff_memory);
@@ -221,7 +217,7 @@ void testReadNonexistantFile() {
void testWriteFail() {
size_t pre_memory = RNS::Utilities::OS::heap_available();
size_t pre_memory = RNS::Utilities::Memory::heap_available();
TRACEF("testWriteFail: pre-mem: %u", pre_memory);
{
@@ -230,7 +226,7 @@ void testWriteFail() {
TEST_ASSERT_EQUAL_size_t(4, wrote);
}
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t post_memory = RNS::Utilities::Memory::heap_available();
size_t diff_memory = (int)pre_memory - (int)post_memory;
TRACEF("testWriteFail: post-mem: %u", post_memory);
TRACEF("testWriteFail: diff-mem: %u", diff_memory);
@@ -290,7 +286,7 @@ int runUnityTests(void) {
FileSystem::listDir("/cache");
RNS::Utilities::OS::register_filesystem(test_filesystem);
size_t pre_memory = RNS::Utilities::OS::heap_available();
size_t pre_memory = RNS::Utilities::Memory::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
@@ -300,7 +296,7 @@ int runUnityTests(void) {
RNS::Utilities::OS::remove_file("./foo");
}
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t post_memory = RNS::Utilities::Memory::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);
+15 -15
View File
@@ -517,11 +517,11 @@ void testDeserializeMap() {
}
#ifdef ARDUINO
const char test_destination_table_path[] = "/test_destination_table";
const char test_empty_destination_table_path[] = "/test_empty_destination_table";
const char test_path_table_path[] = "/test_path_table";
const char test_empty_path_table_path[] = "/test_empty_path_table";
#else
const char test_destination_table_path[] = "test_destination_table";
const char test_empty_destination_table_path[] = "test_empty_destination_table";
const char test_path_table_path[] = "test_path_table";
const char test_empty_path_table_path[] = "test_empty_path_table";
#endif
void testSerializeDestinationTable() {
@@ -542,8 +542,8 @@ void testSerializeDestinationTable() {
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;
entry_one.receiving_interface_hash(test_interface.get_hash());
RNS::Bytes one;
one.assignHex("1111111111111111");
map.insert({one, entry_one});
@@ -551,8 +551,8 @@ void testSerializeDestinationTable() {
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;
entry_two.receiving_interface_hash(test_interface.get_hash());
RNS::Bytes two;
two.assignHex("2222222222222222");
map.insert({two, entry_two});
@@ -561,8 +561,8 @@ void testSerializeDestinationTable() {
RNS::Transport::DestinationEntry entry;
entry._timestamp = 1.0;
entry._received_from = received;
entry._receiving_interface = test_interface.get_hash();
entry._random_blobs = blobs;
entry.receiving_interface_hash(test_interface.get_hash());
RNS::Bytes hash;
hash.assign(std::to_string(1000000000000001 + n).c_str());
map.insert({hash, entry});
@@ -588,7 +588,7 @@ void testSerializeDestinationTable() {
TRACEF("testSerializeDestinationTable: serialized %zu bytes", length);
if (length > 0) {
TRACEF("testSerializeDestinationTable: json: %s", data.toString().c_str());
if (RNS::Utilities::OS::write_file(test_destination_table_path, data) == data.size()) {
if (RNS::Utilities::OS::write_file(test_path_table_path, data) == data.size()) {
TRACEF("testSerializeDestinationTable: wrote: %zu bytes", data.size());
}
else {
@@ -606,7 +606,7 @@ void testSerializeDestinationTable() {
void testDeserializeDestinationTable() {
RNS::Bytes data;
if (RNS::Utilities::OS::read_file(test_destination_table_path, data) > 0) {
if (RNS::Utilities::OS::read_file(test_path_table_path, data) > 0) {
TRACEF("testDeserializeDestinationTable: read: %zu bytes", data.size());
TRACEF("testDeserializeDestinationTable: json: %s", data.toString().c_str());
JsonDocument doc;
@@ -634,7 +634,7 @@ void testDeserializeDestinationTable() {
TRACEF("testDeserializeDestinationTable: failed to deserialize: %s", error.c_str());
TEST_FAIL();
}
//assert(RNS::Utilities::OS::remove_file(test_destination_table_path));
//assert(RNS::Utilities::OS::remove_file(test_path_table_path));
}
else {
TRACE("testDeserializeDestinationTable: read failed");
@@ -647,10 +647,10 @@ void testDeserializeEmptyDestinationTable() {
// Write empty JSON destination table
RNS::Bytes emptyData("{}");
TEST_ASSERT_EQUAL_size_t(2, RNS::Utilities::OS::write_file(test_empty_destination_table_path, emptyData));
TEST_ASSERT_EQUAL_size_t(2, RNS::Utilities::OS::write_file(test_empty_path_table_path, emptyData));
RNS::Bytes data;
if (RNS::Utilities::OS::read_file(test_empty_destination_table_path, data) > 0) {
if (RNS::Utilities::OS::read_file(test_empty_path_table_path, data) > 0) {
TRACEF("testDeserializeEmptyDestinationTable: read: %zu bytes", data.size());
JsonDocument doc;
@@ -677,7 +677,7 @@ void testDeserializeEmptyDestinationTable() {
TRACE("testDeserializeEmptyDestinationTable: failed to deserialize");
TEST_FAIL();
}
//assert(RNS::Utilities::OS::remove_file(test_empty_destination_table_path));
//assert(RNS::Utilities::OS::remove_file(test_empty_path_table_path));
}
else {
TRACE("testDeserializeEmptyDestinationTable: read failed");
@@ -1124,8 +1124,8 @@ int runUnityTests(void) {
RNS::Utilities::OS::remove_file(test_map_path);
RNS::Utilities::OS::remove_file(test_vector_path);
RNS::Utilities::OS::remove_file(test_set_path);
RNS::Utilities::OS::remove_file(test_destination_table_path);
RNS::Utilities::OS::remove_file(test_empty_destination_table_path);
RNS::Utilities::OS::remove_file(test_path_table_path);
RNS::Utilities::OS::remove_file(test_empty_path_table_path);
RNS::Utilities::OS::remove_file(test_array_path);
RNS::Utilities::OS::remove_file(test_series_path);
RNS::Utilities::OS::deregister_filesystem();
+11 -2
View File
@@ -3,7 +3,7 @@
#include "Reticulum.h"
#include "Bytes.h"
void testReference() {
void test_reticulum_reference() {
HEAD("Running testReference...", RNS::LOG_TRACE);
RNS::Reticulum reticulum_default;
@@ -115,6 +115,14 @@ void testReference() {
}
void test_destination_entry_reference() {
HEAD("Running testReference...", RNS::LOG_TRACE);
RNS::Transport::DestinationEntry destination_entry;
TEST_ASSERT_FALSE(destination_entry);
}
void setUp(void) {
// set stuff up here before each test
@@ -126,7 +134,8 @@ void tearDown(void) {
int runUnityTests(void) {
UNITY_BEGIN();
RUN_TEST(testReference);
RUN_TEST(test_reticulum_reference);
RUN_TEST(test_destination_entry_reference);
return UNITY_END();
}
+13 -13
View File
@@ -36,11 +36,11 @@ private:
};
#ifdef ARDUINO
const char test_destination_table_path[] = "/test_destination_table";
const char test_empty_destination_table_path[] = "/test_empty_destination_table";
const char test_path_table_path[] = "/test_path_table";
const char test_empty_path_table_path[] = "/test_empty_path_table";
#else
const char test_destination_table_path[] = "test_destination_table";
const char test_empty_destination_table_path[] = "test_empty_destination_table";
const char test_path_table_path[] = "test_path_table";
const char test_empty_path_table_path[] = "test_empty_path_table";
#endif
void testSerializeDestinationTable() {
@@ -62,7 +62,7 @@ void testSerializeDestinationTable() {
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.receiving_interface_hash(test_interface.get_hash());
entry_one._random_blobs = blobs;
RNS::Bytes one;
one.assignHex("1111111111111111");
@@ -71,7 +71,7 @@ void testSerializeDestinationTable() {
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.receiving_interface_hash(test_interface.get_hash());
entry_two._random_blobs = blobs;
RNS::Bytes two;
two.assignHex("2222222222222222");
@@ -81,7 +81,7 @@ void testSerializeDestinationTable() {
RNS::Transport::DestinationEntry entry;
entry._timestamp = 1.0;
entry._received_from = received;
entry._receiving_interface = test_interface.get_hash();
entry.receiving_interface_hash(test_interface.get_hash());
entry._random_blobs = blobs;
RNS::Bytes hash;
hash.assign(std::to_string(1000000000000001 + n).c_str());
@@ -95,7 +95,7 @@ void testSerializeDestinationTable() {
}
uint32_t stream_crc;
size_t wrote = RNS::Persistence::serialize(map, test_destination_table_path, stream_crc);
size_t wrote = RNS::Persistence::serialize(map, test_path_table_path, stream_crc);
TRACEF("testSerializeDestinationTable: wrote: %d bytes", wrote);
if (wrote == 0) {
TRACE("testSerializeDestinationTable: write failed");
@@ -115,7 +115,7 @@ void testDeserializeDestinationTable() {
std::map<RNS::Bytes, RNS::Transport::DestinationEntry> map;
uint32_t stream_crc;
size_t read = RNS::Persistence::deserialize(map, test_destination_table_path, stream_crc);
size_t read = RNS::Persistence::deserialize(map, test_path_table_path, stream_crc);
TRACEF("testDeserializeDestinationTable: deserialized %d bytes", read);
if (read == 0) {
TRACE("testDeserializeDestinationTable: failed to deserialize");
@@ -140,10 +140,10 @@ void testDeserializeEmptyDestinationTable() {
// Write empty JSON destination table
RNS::Bytes emptyData("{}");
TEST_ASSERT_EQUAL_size_t(2, RNS::Utilities::OS::write_file(test_empty_destination_table_path, emptyData));
TEST_ASSERT_EQUAL_size_t(2, RNS::Utilities::OS::write_file(test_empty_path_table_path, emptyData));
std::map<RNS::Bytes, RNS::Transport::DestinationEntry> destination_table;
RNS::Persistence::deserialize(destination_table, test_empty_destination_table_path);
RNS::Persistence::deserialize(destination_table, test_empty_path_table_path);
TEST_ASSERT_EQUAL_size_t(0, destination_table.size());
}
@@ -170,8 +170,8 @@ int runUnityTests(void) {
RUN_TEST(testDeserializeEmptyDestinationTable);
// Suite-level teardown
RNS::Utilities::OS::remove_file(test_destination_table_path);
RNS::Utilities::OS::remove_file(test_empty_destination_table_path);
RNS::Utilities::OS::remove_file(test_path_table_path);
RNS::Utilities::OS::remove_file(test_empty_path_table_path);
RNS::Utilities::OS::deregister_filesystem();
return UNITY_END();
+6 -6
View File
@@ -30,7 +30,7 @@ public:
InterfaceImpl::handle_incoming(data);
}
catch (const std::bad_alloc&) {
ERROR("handle_incoming: bad_alloc - out of memory");
ERROR("handle_incoming: bad_alloc - OUT OF MEMORY");
}
catch (const std::exception& e) {
ERRORF("handle_incoming: exception: %s", e.what());
@@ -52,7 +52,7 @@ public:
InterfaceImpl::handle_outgoing(data);
}
catch (const std::bad_alloc&) {
ERROR("handle_outgoing: bad_alloc - out of memory");
ERROR("handle_outgoing: bad_alloc - OUT OF MEMORY");
}
catch (const std::exception& e) {
ERRORF("handle_outgoing: exception: %s", e.what());
@@ -130,7 +130,7 @@ void initRNS() {
rns_initialized = true;
}
catch (const std::bad_alloc&) {
ERROR("initRNS: bad_alloc - out of memory");
ERROR("initRNS: bad_alloc - OUT OF MEMORY");
}
catch (const std::exception& e) {
ERRORF("initRNS: exception: %s", e.what());
@@ -427,7 +427,7 @@ void test_incoming_announce_limit() {
}
}
catch (const std::bad_alloc&) {
ERROR("test_incoming_announce_limit: bad_alloc - out of memory");
ERROR("test_incoming_announce_limit: bad_alloc - OUT OF MEMORY");
break;
}
catch (const std::exception& e) {
@@ -488,7 +488,7 @@ void test_incoming_announce_over_limit() {
}
}
catch (const std::bad_alloc&) {
ERROR("test_incoming_announce_over_limit: bad_alloc - out of memory");
ERROR("test_incoming_announce_over_limit: bad_alloc - OUT OF MEMORY");
break;
}
catch (const std::exception& e) {
@@ -554,7 +554,7 @@ void test_incoming_announce_stress() {
}
}
catch (const std::bad_alloc&) {
ERROR("test_incoming_announce_stress: bad_alloc - out of memory");
ERROR("test_incoming_announce_stress: bad_alloc - OUT OF MEMORY");
break;
}
catch (const std::exception& e) {