WIP: Logging optimizations and memory management

Changed a few key logs to use printf-style instead of string
concatenation to avoid dynamic memory allocation. Still need to move
all remaining logging over to printf-style.

Added option (-DRNS_USE_ALLOCATOR=1) to override new/delete operators for
both allocation metrics and the ability to implement an alternate memory
allocator.

Added option (-DRNS_USE_TLSF=1) to use the alternate TLSF allocator
(must also define RNS_USE_ALLOCATOR). This allocator is well known for
reducing fragmentation and providing constant, O(1)-time allocation
and deallocation for real-time embedded systems.

This TLSF allocator appears to already be the default allocator for
ESP32 boards, but the allocator used by NRF52 is unknown at this time so
the TLSF allocator internal to microReticulum is only being used for
NRF52 boards at this time.

Future memory management improvements will include custom allocators for
long-lived structures like the path table that will segregate them from
the general pool of memory that is constantly cycling, thereby further
reducing fragmentation. It will also allow these structures to use
alternate memory like PSRAM present on T-Beam boards.
This commit is contained in:
Chad Attermann committed 2024-07-16 10:40:46 -06:00
1 parent 25741cf235
commit 3af5111606
30 files changed
+2428 -355

No files matched your search

+2 -2
View File
@@ -208,7 +208,7 @@ void reticulum_setup() {
HEAD("Ready!", RNS::LOG_TRACE);
}
catch (std::exception& e) {
ERROR(std::string("!!! Exception in reticulum_setup: ") + e.what() + " !!!");
ERRORF("!!! Exception in reticulum_setup: %s", e.what());
}
}
@@ -227,7 +227,7 @@ void reticulum_teardown() {
}
catch (std::exception& e) {
ERROR(std::string("!!! Exception in reticulum_teardown: ") + e.what() + " !!!");
ERRORF("!!! Exception in reticulum_teardown: %s", e.what());
}
}
+3 -3
View File
@@ -135,7 +135,7 @@ void run_tests() {
//return;
}
catch (std::exception& e) {
ERROR(std::string("!!! Exception in test: ") + e.what() + " !!!");
ERRORF("!!! Exception in test: %s", e.what());
}
}
@@ -275,7 +275,7 @@ void reticulum_setup() {
HEAD("Ready!", RNS::LOG_TRACE);
}
catch (std::exception& e) {
ERROR(std::string("!!! Exception in reticulum_setup: ") + e.what() + " !!!");
ERRORF("!!! Exception in reticulum_setup: %s", e.what());
}
}
@@ -302,7 +302,7 @@ void reticulum_teardown() {
}
catch (std::exception& e) {
ERROR(std::string("!!! Exception in reticulum_teardown: ") + e.what() + " !!!");
ERRORF("!!! Exception in reticulum_teardown: %s", e.what());
}
}
#endif
+24 -10
View File
@@ -20,7 +20,7 @@ using namespace Adafruit_LittleFS_Namespace;
#endif
#ifdef ARDUINO
void listDir(const char* dir){
void Filesystem::listDir(const char* dir) {
Serial.print("DIR: ");
Serial.println(dir);
#ifdef BOARD_ESP32
@@ -30,8 +30,13 @@ void listDir(const char* dir){
return;
}
File file = root.openNextFile();
while(file){
Serial.print(" FILE: ");
while (file) {
if (file.isDirectory()) {
Serial.print(" DIR: ");
}
else {
Serial.print(" FILE: ");
}
Serial.println(file.name());
file.close();
file = root.openNextFile();
@@ -44,8 +49,13 @@ void listDir(const char* dir){
return;
}
File file = root.openNextFile();
while(file){
Serial.print(" FILE: ");
while (file) {
if (file.isDirectory()) {
Serial.print(" DIR: ");
}
else {
Serial.print(" FILE: ");
}
Serial.println(file.name());
file.close();
file = root.openNextFile();
@@ -53,6 +63,9 @@ void listDir(const char* dir){
root.close();
#endif
}
#else
void Filesystem::listDir(const char* dir) {
}
#endif
bool Filesystem::init() {
@@ -75,8 +88,8 @@ bool Filesystem::init() {
Serial.print(used);
Serial.println(" MB");
// ensure filesystem is writable and format if not
RNS::Bytes test;
if (!write_file("/test", test)) {
RNS::Bytes test("test");
if (write_file("/test", test) < 4) {
INFO("SPIFFS filesystem is being formatted, please wait...");
SPIFFS.format();
}
@@ -90,7 +103,6 @@ bool Filesystem::init() {
InternalFS.begin();
INFO("InternalFS filesystem is ready");
#endif
listDir("/");
#endif
return true;
}
@@ -157,7 +169,7 @@ bool Filesystem::init() {
//size_t read = fread(data.writable(size), size, 1, file);
size_t read = fread(data.writable(size), 1, size, file);
#endif
TRACE("read_file: read " + std::to_string(read) + " RNS::Bytes from file " + std::string(file_path));
TRACE("read_file: read " + std::to_string(read) + " bytes from file " + std::string(file_path));
if (read != size) {
ERROR("read_file: failed to read file " + std::string(file_path));
data.clear();
@@ -181,6 +193,8 @@ bool Filesystem::init() {
}
/*virtual*/ size_t Filesystem::write_file(const char* file_path, const RNS::Bytes& data) {
// CBA TODO Replace remove with working truncation
remove_file(file_path);
size_t wrote = 0;
#ifdef ARDUINO
#ifdef BOARD_ESP32
@@ -201,7 +215,7 @@ bool Filesystem::init() {
//size_t wrote = fwrite(data.data(), data.size(), 1, file);
size_t wrote = fwrite(data.data(), 1, data.size(), file);
#endif
TRACE("write_file: wrote " + std::to_string(wrote) + " RNS::Bytes to file " + std::string(file_path));
TRACE("write_file: wrote " + std::to_string(wrote) + " bytes to file " + std::string(file_path));
if (wrote < data.size()) {
WARNING("write_file: not all data was written to file " + std::string(file_path));
}
+3
View File
@@ -8,6 +8,9 @@ class Filesystem : public RNS::Filesystem {
public:
bool init();
public:
static void listDir(const char* dir);
protected:
virtual bool file_exists(const char* file_path);
virtual size_t read_file(const char* file_path, RNS::Bytes& data);
+143 -64
View File
@@ -140,6 +140,7 @@ void testBytesMain() {
}
// test resize
HEAD("TestBytes: resize", RNS::LOG_TRACE);
{
RNS::Bytes shrink(bytes);
shrink.resize(5);
@@ -148,60 +149,6 @@ void testBytesMain() {
assert(memcmp(shrink.data(), "Hello", shrink.size()) == 0);
}
// stream into empty bytes
{
RNS::Bytes strmbuf;
strmbuf << prebuf << postbuf;
TRACE("stream prebuf: " + prebuf.toString());
TRACE("stream postbuf: " + postbuf.toString());
TRACE("stream strmbuf: " + strmbuf.toString());
assert(strmbuf.size() == 11);
assert(memcmp(strmbuf.data(), "Hello World", strmbuf.size()) == 0);
assert(prebuf.size() == 5);
assert(memcmp(prebuf.data(), "Hello", prebuf.size()) == 0);
assert(postbuf.size() == 6);
assert(memcmp(postbuf.data(), " World", postbuf.size()) == 0);
}
// stream into populated bytes
{
RNS::Bytes strmbuf("Stream ");
assert(strmbuf);
assert(strmbuf.size() == 7);
assert(memcmp(strmbuf.data(), "Stream ", strmbuf.size()) == 0);
strmbuf << prebuf << postbuf;
TRACE("stream prebuf: " + prebuf.toString());
TRACE("stream postbuf: " + postbuf.toString());
TRACE("stream strmbuf: " + strmbuf.toString());
assert(strmbuf.size() == 18);
assert(memcmp(strmbuf.data(), "Stream Hello World", strmbuf.size()) == 0);
assert(prebuf.size() == 5);
assert(memcmp(prebuf.data(), "Hello", prebuf.size()) == 0);
assert(postbuf.size() == 6);
assert(memcmp(postbuf.data(), " World", postbuf.size()) == 0);
}
// stream with assignment
// (side effect of also updating pre - this is a known and correct but perhaps unexpected and non-intuitive side-effect of assignment with stream)
{
// NOTE pre must be volatile in order for below stream with assignment to work (since it gets modified)
RNS::Bytes pre("Hello");
assert(pre.size() == 5);
const RNS::Bytes post(" World");
assert(post.size() == 6);
RNS::Bytes strmbuf = pre << post;
TRACE("stream pre: " + prebuf.toString());
TRACE("stream post: " + postbuf.toString());
TRACE("stream strmbuf: " + strmbuf.toString());
assert(strmbuf.size() == 11);
assert(memcmp(strmbuf.data(), "Hello World", strmbuf.size()) == 0);
assert(pre.size() == 11);
assert(memcmp(pre.data(), "Hello World", pre.size()) == 0);
assert(post.size() == 6);
assert(memcmp(post.data(), " World", post.size()) == 0);
}
// test creating bytes from default
{
RNS::Bytes bytes;
@@ -235,11 +182,11 @@ void testBytesMain() {
}
// function default argument
TRACE("TestBytes: function default argument");
HEAD("TestBytes: function default argument", RNS::LOG_TRACE);
testBytesDefault();
// function reference return
TRACE("TestBytes: function reference return");
HEAD("TestBytes: function reference return", RNS::LOG_TRACE);
{
RNS::Bytes test = testBytesReference();
TRACE("returned");
@@ -326,12 +273,14 @@ void testBytesConversion() {
assert(text.length() == 11);
assert(text.compare("Hello World") == 0);
// overwrite
bytes.assignHex(hex.c_str());
text = bytes.toString();
TRACE("hex: \"" + hex + "\" text: \"" + text + "\"");
assert(text.length() == 11);
assert(text.compare("Hello World") == 0);
// apend
bytes.appendHex(hex.c_str());
text = bytes.toString();
TRACE("hex: \"" + hex + "\" text: \"" + text + "\"");
@@ -362,22 +311,152 @@ void testBytesResize() {
assert(bytes.capacity() == 1024);
}
void testBytesStream() {
const uint8_t prestr[] = "Hello";
const uint8_t poststr[] = " World";
const RNS::Bytes prebuf(prestr, 5);
assert(prebuf);
assert(prebuf.size() == 5);
assert(memcmp(prebuf.data(), "Hello", prebuf.size()) == 0);
const RNS::Bytes postbuf(poststr, 6);
assert(postbuf);
assert(postbuf.size() == 6);
assert(memcmp(postbuf.data(), " World", postbuf.size()) == 0);
// stream into empty bytes
HEAD("TestBytes: stream into empty bytes", RNS::LOG_TRACE);
{
RNS::Bytes strmbuf;
strmbuf << prebuf << postbuf;
TRACE("Results:");
TRACEF("stream prebuf: %s", prebuf.toString().c_str());
TRACEF("stream postbuf: %s", postbuf.toString().c_str());
TRACEF("stream strmbuf: %s", strmbuf.toString().c_str());
assert(strmbuf.size() == 11);
assert(memcmp(strmbuf.data(), "Hello World", strmbuf.size()) == 0);
assert(prebuf.size() == 5);
assert(memcmp(prebuf.data(), "Hello", prebuf.size()) == 0);
assert(postbuf.size() == 6);
assert(memcmp(postbuf.data(), " World", postbuf.size()) == 0);
}
// stream into reserved empty bytes
HEAD("TestBytes: stream into reserved empty bytes", RNS::LOG_TRACE);
{
RNS::Bytes strmbuf(256);
//strmbuf << prebuf << postbuf;
strmbuf << prebuf;
strmbuf << postbuf;
TRACE("Results:");
//TRACEF("stream prebuf: %s", prebuf.toString().c_str());
//TRACEF("stream postbuf: %s", postbuf.toString().c_str());
//TRACEF("stream strmbuf: %s", strmbuf.toString().c_str());
assert(strmbuf.size() == 11);
assert(memcmp(strmbuf.data(), "Hello World", strmbuf.size()) == 0);
assert(prebuf.size() == 5);
assert(memcmp(prebuf.data(), "Hello", prebuf.size()) == 0);
assert(postbuf.size() == 6);
assert(memcmp(postbuf.data(), " World", postbuf.size()) == 0);
}
// stream into populated bytes
HEAD("TestBytes: stream into populated bytes", RNS::LOG_TRACE);
{
RNS::Bytes strmbuf("Stream ");
assert(strmbuf);
assert(strmbuf.size() == 7);
assert(memcmp(strmbuf.data(), "Stream ", strmbuf.size()) == 0);
strmbuf << prebuf << postbuf;
TRACE("Results:");
TRACEF("stream prebuf: %s", prebuf.toString().c_str());
TRACEF("stream postbuf: %s", postbuf.toString().c_str());
TRACEF("stream strmbuf: %s", strmbuf.toString().c_str());
assert(strmbuf.size() == 18);
assert(memcmp(strmbuf.data(), "Stream Hello World", strmbuf.size()) == 0);
assert(prebuf.size() == 5);
assert(memcmp(prebuf.data(), "Hello", prebuf.size()) == 0);
assert(postbuf.size() == 6);
assert(memcmp(postbuf.data(), " World", postbuf.size()) == 0);
}
// stream with assignment
HEAD("TestBytes: stream with assignment", RNS::LOG_TRACE);
// (side effect of also updating pre - this is a known and correct but perhaps unexpected and non-intuitive side-effect of assignment with stream)
{
// NOTE pre must be volatile in order for below stream with assignment to work (since it gets modified)
RNS::Bytes pre("Hello");
assert(pre.size() == 5);
const RNS::Bytes post(" World");
assert(post.size() == 6);
RNS::Bytes strmbuf = pre << post;
TRACE("Results:");
TRACEF("stream pre: %s", prebuf.toString().c_str());
TRACEF("stream post: %s", postbuf.toString().c_str());
TRACEF("stream strmbuf: %s", strmbuf.toString().c_str());
assert(strmbuf.size() == 11);
assert(memcmp(strmbuf.data(), "Hello World", strmbuf.size()) == 0);
assert(pre.size() == 11);
assert(memcmp(pre.data(), "Hello World", pre.size()) == 0);
assert(post.size() == 6);
assert(memcmp(post.data(), " World", post.size()) == 0);
}
}
void testBytesReserve() {
RNS::Bytes src("Hello");
uint8_t hops = 32;
{
RNS::Bytes dst = src.left(1);
dst << hops;
dst << src.mid(2);
TRACEF("non-reserve: %s", dst.toString().c_str());
assert(dst.size() == 5);
assert(memcmp(dst.data(), "H llo", dst.size()) == 0);
}
{
RNS::Bytes dst(512);
dst << src.left(1);
dst << hops;
dst << src.mid(2);
TRACEF("reserve: %s", dst.toString().c_str());
assert(dst.size() == 5);
assert(memcmp(dst.data(), "H llo", dst.size()) == 0);
}
}
void testBytes() {
HEAD("Running testBytes...", RNS::LOG_TRACE);
size_t pre_memory = RNS::Utilities::OS::heap_available();
TRACE("testBytes: pre-mem: " + std::to_string(pre_memory));
RNS::Utilities::OS::dump_heap_stats();
testBytesMain();
testCowBytes();
testBytesConversion();
testBytesResize();
size_t pre_memory = RNS::Utilities::OS::heap_available();
TRACEF("testBytes: pre-mem: %u", pre_memory);
//testBytesMain();
//testCowBytes();
//testBytesConversion();
//testBytesResize();
//testBytesStream();
testBytesReserve();
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t diff_memory = (int)pre_memory - (int)post_memory;
TRACE("testBytes: post-mem: " + std::to_string(post_memory));
TRACE("testBytes: diff-mem: " + std::to_string(diff_memory));
TRACEF("testBytes: post-mem: %u", post_memory);
TRACEF("testBytes: diff-mem: %u", diff_memory);
assert(diff_memory == 0);
RNS::Utilities::OS::dump_allocator_stats();
RNS::Utilities::OS::dump_heap_stats();
}
/*
+142 -9
View File
@@ -1,37 +1,170 @@
//#include <unity.h>
#include "Filesystem.h"
#include <Utilities/OS.h>
#include "Log.h"
#include <assert.h>
using namespace RNS;
using namespace RNS::Utilities;
Filesystem test_filesystem;
void testListDirectory() {
size_t pre_memory = OS::heap_available();
size_t pre_memory = RNS::Utilities::OS::heap_available();
INFO("testListDirectory: pre-mem: " + std::to_string(pre_memory));
for (int i = 0; i < 1; i++) {
std::list<std::string> files;
files = OS::list_directory("/");
for (auto& file : files) {
INFO("FILE: " + file);
{
for (int i = 0; i < 1; i++) {
std::list<std::string> files;
files = RNS::Utilities::OS::list_directory("/");
for (auto& file : files) {
INFO("FILE: " + file);
}
}
}
size_t post_memory = OS::heap_available();
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t diff_memory = (int)pre_memory - (int)post_memory;
INFO("testListDirectory: post-mem: " + std::to_string(post_memory));
INFO("testListDirectory: diff-mem: " + std::to_string(diff_memory));
assert(diff_memory == 0);
}
void testWriteFile(const char* file_path) {
size_t pre_memory = RNS::Utilities::OS::heap_available();
TRACEF("testWriteFile: pre-mem: %u", pre_memory);
{
RNS::Bytes data("test");
size_t wrote = RNS::Utilities::OS::write_file(file_path, data);
//assert(wrote == 4);
}
size_t post_memory = RNS::Utilities::OS::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);
assert(diff_memory == 0);
}
void testReadFile(const char* file_path) {
size_t pre_memory = RNS::Utilities::OS::heap_available();
TRACEF("testReadFile: pre-mem: %u", pre_memory);
{
RNS::Bytes data;
size_t read = RNS::Utilities::OS::read_file(file_path, data);
assert(read == 4);
}
size_t post_memory = RNS::Utilities::OS::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);
assert(diff_memory == 0);
}
void testRemoveFile(const char* file_path) {
size_t pre_memory = RNS::Utilities::OS::heap_available();
TRACEF("testRemoveFile: pre-mem: %u", pre_memory);
assert(RNS::Utilities::OS::remove_file(file_path));
size_t post_memory = RNS::Utilities::OS::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);
assert(diff_memory == 0);
}
void testReadNonexistantFile() {
size_t pre_memory = RNS::Utilities::OS::heap_available();
TRACEF("testReadNonexistantFile: pre-mem: %u", pre_memory);
{
RNS::Bytes data;
size_t read = RNS::Utilities::OS::read_file("/foo", data);
assert(read == 0);
}
size_t post_memory = RNS::Utilities::OS::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);
assert(diff_memory == 0);
}
void testWriteFail() {
size_t pre_memory = RNS::Utilities::OS::heap_available();
TRACEF("testWriteFail: pre-mem: %u", pre_memory);
{
RNS::Bytes data("test");
size_t wrote = RNS::Utilities::OS::write_file("", data);
assert(wrote == 4);
}
size_t post_memory = RNS::Utilities::OS::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);
assert(diff_memory == 0);
}
void testFilesystem() {
HEAD("Running testFilesystem...", RNS::LOG_TRACE);
test_filesystem.init();
test_filesystem.listDir("/");
test_filesystem.listDir("/cache");
RNS::Utilities::OS::register_filesystem(test_filesystem);
size_t pre_memory = RNS::Utilities::OS::heap_available();
TRACEF("testFilesystem: pre-mem: %u", pre_memory);
// CBA Seems that first call to write_file allocates some memory (at least with NRF52 LittleFS) so get that out of the way first
{
RNS::Bytes data("foo");
RNS::Utilities::OS::write_file("/foo", data);
RNS::Utilities::OS::remove_file("/foo");
}
size_t post_memory = RNS::Utilities::OS::heap_available();
size_t diff_memory = (int)pre_memory - (int)post_memory;
TRACEF("testFilesystem: post-mem: %u", post_memory);
TRACEF("testFilesystem: diff-mem: %u", diff_memory);
testListDirectory();
testWriteFile("/test1");
testReadFile("/test1");
//testRemoveFile("/test1");
testReadNonexistantFile();
//testWriteFail();
// CBA Attempt to reproduce failure to open file for write that is leaking mmeory
if (!RNS::Utilities::OS::directory_exists("/cache")) {
RNS::Utilities::OS::create_directory("/cache");
}
testWriteFile("/cache/test");
testWriteFile("/cache/45c50662af11f1b26889efaab547942b");
testWriteFile("/cache/40fe4ab8105b591cca1ef159d476a7b4");
testWriteFile("/cache/c755609f4d0ab75b5119905a032eeb33");
testWriteFile("/cache/426f66f9aadf866933358b71295f59d0");
RNS::Utilities::OS::deregister_filesystem();
}
+20 -3
View File
@@ -1,5 +1,7 @@
//#include <unity.h>
#include "Filesystem.h"
#include "Interface.h"
#include "Transport.h"
#include "Log.h"
@@ -17,6 +19,7 @@
#include <assert.h>
#include <stdio.h>
Filesystem persistence_filesystem;
class TestInterface : public RNS::Interface {
@@ -240,7 +243,6 @@ void testDeserializeObject() {
}
#ifdef ARDUINO
const char test_vector_path[] = "/test_vector";
#else
@@ -684,9 +686,20 @@ void testDeserializeDestinationTable() {
}
void testSerializeTimeOffset() {
uint64_t offset = RNS::Utilities::OS::ltime();
TRACEF("Writing time offset of %llu to file /time_offset", offset);
RNS::Bytes buf((uint8_t*)&offset, sizeof(offset));
RNS::Utilities::OS::write_file("/time_offset", buf);
}
void testPersistence() {
HEAD("Running testPersistence...", RNS::LOG_TRACE);
persistence_filesystem.init();
RNS::Utilities::OS::register_filesystem(persistence_filesystem);
testWrite();
testRead();
testSerializeObject();
@@ -697,8 +710,12 @@ void testPersistence() {
testDeserializeSet();
testSerializeMap();
testDeserializeMap();
testSerializeDestinationTable();
testDeserializeDestinationTable();
//testSerializeDestinationTable();
//testDeserializeDestinationTable();
testSerializeTimeOffset();
RNS::Utilities::OS::deregister_filesystem();
}
/*
+163 -3
View File
@@ -6,21 +6,181 @@
#include <assert.h>
RNS::Reticulum reticulum = {RNS::Type::NONE};
class TestInterface : public RNS::Interface {
void testDestinationTable() {
public:
TestInterface(const char* name = "TestInterface") : Interface(name) {}
virtual ~TestInterface() {}
virtual inline std::string toString() const { return "TestInterface[" + name() + "]"; }
private:
virtual void on_incoming(const RNS::Bytes& data) {
RNS::debug(toString() + ".on_incoming: data: " + data.toHex());
Interface::on_incoming(data);
}
virtual void on_outgoing(const RNS::Bytes& data) {
RNS::debug(toString() + ".on_outgoing: data: " + data.toHex());
Interface::on_outgoing(data);
}
};
class InInterface : public RNS::Interface {
public:
InInterface() : RNS::Interface("InInterface") {
OUT(false);
IN(true);
}
InInterface(const char *name) : RNS::Interface(name) {
OUT(false);
IN(true);
}
virtual ~InInterface() {
name("(deleted)");
}
virtual void on_incoming(const RNS::Bytes &data) {
HEAD("InInterface.on_incoming: data: " + data.toHex(), RNS::LOG_TRACE);
RNS::Interface::on_incoming(data);
}
virtual inline std::string toString() const { return "InInterface[" + name() + "]"; }
};
class OutInterface : public RNS::Interface {
public:
OutInterface(InInterface& in_interface) : RNS::Interface("OutInterface"), _in_interface(in_interface) {
OUT(true);
IN(false);
}
OutInterface(InInterface& in_interface, const char *name) : RNS::Interface(name), _in_interface(in_interface) {
OUT(true);
IN(false);
}
virtual ~OutInterface() {
name("(deleted)");
}
virtual void on_outgoing(const RNS::Bytes &data) {
HEAD("OutInterface.on_outgoing: data: " + data.toHex(), RNS::LOG_TRACE);
_in_interface.on_incoming(data);
RNS::Interface::on_outgoing(data);
}
virtual inline std::string toString() const { return "OutInterface[" + name() + "]"; }
private:
InInterface& _in_interface;
};
// Test AnnounceHandler
class ExampleAnnounceHandler : public RNS::AnnounceHandler {
public:
ExampleAnnounceHandler(const char* aspect_filter = nullptr) : AnnounceHandler(aspect_filter) {}
virtual ~ExampleAnnounceHandler() {}
virtual void received_announce(const RNS::Bytes& destination_hash, const RNS::Identity& announced_identity, const RNS::Bytes& app_data) {
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
INFO("ExampleAnnounceHandler: destination hash: " + destination_hash.toHex());
if (announced_identity) {
INFO("ExampleAnnounceHandler: announced identity hash: " + announced_identity.hash().toHex());
INFO("ExampleAnnounceHandler: announced identity app data: " + announced_identity.app_data().toHex());
}
if (app_data) {
INFO("ExampleAnnounceHandler: app data text: \"" + app_data.toString() + "\"");
}
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
};
//ExampleAnnounceHandler announce_handler((const char*)"example_utilities.announcesample.fruits");
//RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler("example_utilities.announcesample.fruits"));
RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler());
// Test packet receive callback
void onPacket(const RNS::Bytes& data, const RNS::Packet& packet) {
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
INFO("onPacket: data: " + data.toHex());
INFO("onPacket: text: \"" + data.toString() + "\"");
//TRACE("onPacket: " + packet.debugString());
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
// Ping packet receive callback
void onPingPacket(const RNS::Bytes& data, const RNS::Packet& packet) {
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
INFO("onPingPacket: data: " + data.toHex());
INFO("onPingPacket: text: \"" + data.toString() + "\"");
//TRACE("onPingPacket: " + packet.debugString());
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
RNS::Reticulum reticulum({RNS::Type::NONE});
RNS::Identity identity({RNS::Type::NONE});
RNS::Destination destination({RNS::Type::NONE});
InInterface in_interface;
OutInterface out_interface(in_interface);
void testReticulum() {
HEAD("Running testReticulum...", RNS::LOG_TRACE);
HEAD("Registering Interface instances with Transport...", RNS::LOG_TRACE);
RNS::Transport::register_interface(in_interface);
RNS::Transport::register_interface(out_interface);
RNS::Bytes transport_prv_bytes;
#ifdef ARDUINO
transport_prv_bytes.assignHex("CAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFECAFE");
#else
transport_prv_bytes.assignHex("BABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABE");
#endif
RNS::Identity transport_identity(false);
transport_identity.load_private_key(transport_prv_bytes);
RNS::Transport::identity(transport_identity);
HEAD("Creating Reticulum instance...", RNS::LOG_TRACE);
reticulum = RNS::Reticulum();
reticulum.transport_enabled(true);
reticulum.probe_destination_enabled(true);
reticulum.start();
testDestinationTable();
HEAD("Creating Identity instance...", RNS::LOG_TRACE);
// new identity
identity = RNS::Identity(false);
RNS::Bytes prv_bytes;
#ifdef ARDUINO
prv_bytes.assignHex("78E7D93E28D55871608FF13329A226CABC3903A357388A035B360162FF6321570B092E0583772AB80BC425F99791DF5CA2CA0A985FF0415DAB419BBC64DDFAE8");
#else
prv_bytes.assignHex("E0D43398EDC974EBA9F4A83463691A08F4D306D4E56BA6B275B8690A2FBD9852E9EBE7C03BC45CAEC9EF8E78C830037210BFB9986F6CA2DEE2B5C28D7B4DE6B0");
#endif
identity.load_private_key(prv_bytes);
// 22.6% (+0.7%)
HEAD("Creating Destination instance...", RNS::LOG_TRACE);
//RNS::Destination destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "app", "aspects");
destination = RNS::Destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "app", "aspects");
// 23.0% (+0.4%)
// Register DATA packet callback
HEAD("Registering packet callback with Destination...", RNS::LOG_TRACE);
destination.set_packet_callback(onPacket);
destination.set_proof_strategy(RNS::Type::Destination::PROVE_ALL);
{
// Register PING packet callback
HEAD("Creating PING Destination instance...", RNS::LOG_TRACE);
RNS::Destination ping_destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "example_utilities", "echo.request");
HEAD("Registering packet callback with PING Destination...", RNS::LOG_TRACE);
ping_destination.set_packet_callback(onPingPacket);
ping_destination.set_proof_strategy(RNS::Type::Destination::PROVE_ALL);
}
HEAD("Registering announce handler with Transport...", RNS::LOG_TRACE);
RNS::Transport::register_announce_handler(announce_handler);
HEAD("Announcing destination...", RNS::LOG_TRACE);
// test path
//destination.announce(RNS::bytesFromString("test"), true, nullptr, RNS::bytesFromString("test_tag"));
// test packet send
destination.announce(RNS::bytesFromString("test"));
// 23.9% (+0.8%)
reticulum = {RNS::Type::NONE};
}
+3 -12
View File
@@ -1,7 +1,5 @@
//#define NDEBUG
#include "Filesystem.h"
#include "Test.h"
#include "Log.h"
@@ -22,8 +20,6 @@
#include <map>
#include <functional>
Filesystem filesystem;
void setup() {
#ifdef ARDUINO
@@ -38,18 +34,13 @@ void setup() {
RNS::loglevel(RNS::LOG_TRACE);
//RNS::loglevel(RNS::LOG_MEM);
if (filesystem) {
INFO("Filesystem exists");
filesystem.init();
}
RNS::Utilities::OS::register_filesystem(filesystem);
try {
TRACE("Running tests...");
RNS::LogLevel loglevel = RNS::loglevel();
//RNS::loglevel(RNS::LOG_WARNING);
RNS::loglevel(RNS::LOG_TRACE);
//RNS::loglevel(RNS::LOG_MEM);
// all tests
//test();
@@ -57,9 +48,9 @@ void setup() {
// individiual tests
//testReference();
//testCrypto();
//testPersistence();
testBytes();
//testFilesystem();
//testPersistence();
//testReticulum();
RNS::loglevel(loglevel);
@@ -67,7 +58,7 @@ void setup() {
//return;
}
catch (std::exception& e) {
ERROR(std::string("!!! Exception in test: ") + e.what() + " !!!");
ERRORF("!!! Exception in test: %s", e.what());
}
#ifdef ARDUINO
+24 -1
View File
@@ -16,9 +16,9 @@ include_dir = .
src_dir = .
[env]
framework = arduino
monitor_speed = 115200
upload_speed = 921600
build_type = debug
[env:native]
platform = native
@@ -61,9 +61,11 @@ lib_deps =
ArduinoJson@^6.21.3
https://github.com/attermann/arduinolibs.git
microReticulum=symlink://../..
lib_extra_dirs = ../
lib_compat_mode = off
[env:cubecell-gps]
framework = arduino
platform = heltec-cubecell
board = cubecell_gps
;build_flags = -Wl,-Map,output.map
@@ -82,6 +84,7 @@ lib_deps =
; CBA NOTE must undef min and max from Arduino.h
[env:heltec-tracker]
framework = arduino
platform = espressif32
board = heltec_wireless_tracker
upload_protocol = esp-builtin
@@ -102,8 +105,10 @@ lib_deps =
microReticulum=symlink://../..
[env:ttgo-lora32-v21]
framework = arduino
platform = espressif32
board = ttgo-lora32-v21
upload_speed = 460800
board_build.partitions = no_ota.csv
build_flags =
-Wall
@@ -116,8 +121,10 @@ lib_deps =
ArduinoJson@^6.21.3
https://github.com/attermann/arduinolibs.git
microReticulum=symlink://../..
monitor_filters = esp32_exception_decoder
[env:ttgo-t-beam]
framework = arduino
platform = espressif32
board = ttgo-t-beam
board_build.partitions = no_ota.csv
@@ -133,8 +140,10 @@ lib_deps =
ArduinoJson@^6.21.3
https://github.com/attermann/arduinolibs.git
microReticulum=symlink://../..
monitor_filters = esp32_exception_decoder
[env:wiscore_rak4631]
framework = arduino
platform = nordicnrf52
board = wiscore_rak4631
board_build.partitions = no_ota.csv
@@ -147,8 +156,22 @@ build_flags =
-Wno-format
-I.
-DBOARD_NRF52
-DRNS_USE_TLSF=1
build_unflags = -fno-exceptions
lib_deps =
ArduinoJson@^6.21.3
https://github.com/attermann/arduinolibs.git
microReticulum=symlink://../..
[env:nrf52840_dk_adafruit]
framework = arduino
platform = nordicnrf52
board = nrf52840_dk_adafruit
monitor_speed = 115200
[env:nrf52_dk]
framework = arduino
;framework = zephyr
platform = nordicnrf52
board = nrf52_dk
+2 -2
View File
@@ -209,7 +209,7 @@ void reticulum_setup() {
HEAD("Ready!", RNS::LOG_TRACE);
}
catch (std::exception& e) {
ERROR(std::string("!!! Exception in reticulum_setup: ") + e.what() + " !!!");
ERRORF("!!! Exception in reticulum_setup: %s", e.what());
}
}
@@ -228,7 +228,7 @@ void reticulum_teardown() {
}
catch (std::exception& e) {
ERROR(std::string("!!! Exception in reticulum_teardown: ") + e.what() + " !!!");
ERRORF("!!! Exception in reticulum_teardown: %s", e.what());
}
}
+1
View File
@@ -132,6 +132,7 @@ build_flags =
-Wno-format
-Isrc
;-DNDEBUG
-DRNS_USE_TLSF=1
lib_deps =
ArduinoJson@^6.21.3
https://github.com/attermann/arduinolibs.git
+52 -37
View File
@@ -3,56 +3,67 @@
using namespace RNS;
// Creates new shared data for instance
// - If size is specified (>0) then create shared data with initial size
// - If size is not specified (<=0) then create empty shared data
void Bytes::newData(size_t size /*= 0*/) {
MEM("Bytes is creating its own data");
if (size > 0) {
// CBA Note that this method of construction creates vector with specified and initializes all eleemtnets with default values
Data* data = new Data(size);
if (data == nullptr) {
ERROR("Bytes failed to allocate data buffer");
throw std::runtime_error("Failed to allocate data buffer");
}
_data = SharedData(data);
// - If capacity is specified (>0) then create empty shared data with initial reserved capacity
// - If capacity is not specified (<=0) then create empty shared data with no initial capacity
void Bytes::newData(size_t capacity /*= 0*/) {
MEMF("Bytes is creating own data with capacity %u", capacity);
MEM("newData: Creating new data...");
Data* data = new Data();
if (data == nullptr) {
ERROR("Bytes failed to allocate empty data buffer");
throw std::runtime_error("Failed to allocate empty data buffer");
}
else {
Data* data = new Data();
if (data == nullptr) {
ERROR("Bytes failed to allocate empty data buffer");
throw std::runtime_error("Failed to allocate empty data buffer");
}
_data = SharedData(data);
MEM("newData: Created new data");
if (capacity > 0) {
MEM("newData: Reserving data capacity...");
data->reserve(capacity);
MEM("newData: Reserved data capacity");
}
MEM("newData: Assigning data to shared data pointer...");
_data = SharedData(data);
MEM("newData: Assigned data to shared data pointer");
_exclusive = true;
}
// Ensures that instance has exclusive shared data
// - If instance has no shared data then create new shared data
// - If instance does not have exclusive on shared data that is not empty then make a copy of shared data (if requests) and resize (if requested)
// - If instance does not have exclusive on shared data that is not empty then make a copy of shared data (if requests) and reserve capacity (if requested)
// - If instance does not have exclusive on shared data that is empty then then create new shared data
// - If instance already has exclusive on shared data then do nothing except resize (if requested)
void Bytes::exclusiveData(bool copy /*= true*/, size_t size /*= 0*/) {
// - If instance already has exclusive on shared data then do nothing except reserve capacity (if requested)
void Bytes::exclusiveData(bool copy /*= true*/, size_t capacity /*= 0*/) {
if (!_data) {
newData(size);
newData(capacity);
}
else if (!_exclusive) {
Data *data;
if (copy && !_data->empty()) {
//TRACE("Bytes is creating a writable copy of its shared data");
data = new Data(*_data.get());
//Data* data = new Data(*_data.get());
MEM("exclusiveData: Creating new data...");
Data* data = new Data();
if (data == nullptr) {
ERROR("Bytes failed to duplicate data buffer");
throw std::runtime_error("Failed to duplicate data buffer");
}
if (size > 0) {
data->resize(size);
MEM("exclusiveData: Created new data");
if (capacity > 0) {
MEM("exclusiveData: Reserving data capacity...");
// if requested capacity < existing size then reserve capacity for existing size instead
data->reserve((capacity > _data->size()) ? capacity : _data->size());
MEM("exclusiveData: Reserved data capacity");
}
else {
data->reserve(_data->size());
}
MEM("exclusiveData: Copying existing data...");
data->insert(data->begin(), _data->begin(), _data->end());
MEM("exclusiveData: Copied existing data");
MEM("exclusiveData: Assigning data to shared data pointer...");
_data = SharedData(data);
MEM("exclusiveData: Assigned data to shared data pointer");
_exclusive = true;
}
else {
//TRACE("Bytes is creating its own data because shared is empty");
//MEM("Bytes is creating its own data because shared is empty");
//data = new Data();
//if (data == nullptr) {
// ERROR("Bytes failed to allocate empty data buffer");
@@ -60,11 +71,13 @@ void Bytes::exclusiveData(bool copy /*= true*/, size_t size /*= 0*/) {
//}
//_data = SharedData(data);
//_exclusive = true;
newData(size);
MEM("exclusiveData: Creating new empty data...");
newData(capacity);
MEM("exclusiveData: Created new empty data");
}
}
else if (size > 0) {
_data->resize(size);
else if (capacity > 0 && capacity > size()) {
reserve(capacity);
}
}
@@ -96,9 +109,11 @@ void Bytes::assignHex(const char* hex) {
_exclusive = true;
return;
}
newData();
size_t len = strlen(hex);
for (size_t i = 0; i < len; i += 2) {
size_t hex_size = strlen(hex);
exclusiveData(false, hex_size / 2);
// need to clear data since we're appending below
_data->clear();
for (size_t i = 0; i < hex_size; i += 2) {
uint8_t byte = (hex[i] % 32 + 9) % 25 * 16 + (hex[i+1] % 32 + 9) % 25;
_data->push_back(byte);
}
@@ -109,9 +124,9 @@ void Bytes::appendHex(const char* hex) {
if (hex == nullptr || hex[0] == 0) {
return;
}
exclusiveData();
size_t len = strlen(hex);
for (size_t i = 0; i < len; i += 2) {
size_t hex_size = strlen(hex);
exclusiveData(true, size() + (hex_size / 2));
for (size_t i = 0; i < hex_size; i += 2) {
uint8_t byte = (hex[i] % 32 + 9) % 25 * 16 + (hex[i+1] % 32 + 9) % 25;
_data->push_back(byte);
}
+54 -35
View File
@@ -31,35 +31,34 @@ namespace RNS {
public:
Bytes() {
MEM("Bytes object created from default, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((unsigned long)_data.get()));
MEMF("Bytes object created from defaul, this: %lu, data: %lu", this, _data.get());
}
Bytes(const NoneConstructor none) {
MEM("Bytes object created from NONE, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((unsigned long)_data.get()));
MEMF("Bytes object created from NONE, this: %lu, data: %lu", this, _data.get());
}
Bytes(const Bytes& bytes) {
MEM("Bytes is using shared data");
assign(bytes);
MEM("Bytes object copy created from bytes \"" + toString() + "\", this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((unsigned long)_data.get()));
MEMF("Bytes object copy created from bytes \"%s\", this: %lu, data: %lu", toString().c_str(), this, _data.get());
}
Bytes(const uint8_t* chunk, size_t size) {
assign(chunk, size);
MEM(std::string("Bytes object created from chunk \"") + toString() + "\", this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((unsigned long)_data.get()));
MEMF("Bytes object created from chunk \"%s\", this: %lu, data: %lu", toString().c_str(), this, _data.get());
}
Bytes(const char* string) {
assign(string);
MEM(std::string("Bytes object created from string \"") + toString() + "\", this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((unsigned long)_data.get()));
MEMF("Bytes object created from string \"%s\", this: %lu, data: %lu", toString().c_str(), this, _data.get());
}
Bytes(const std::string& string) {
assign(string);
MEM(std::string("Bytes object created from std::string \"") + toString() + "\", this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((unsigned long)_data.get()));
MEMF("Bytes object created from std::string \"%s\", this: %lu, data: %lu", toString().c_str(), this, _data.get());
}
Bytes(size_t capacity) {
newData();
reserve(capacity);
MEM(std::string("Bytes object created with capacity ") + std::to_string(capacity) + ", this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((unsigned long)_data.get()));
newData(capacity);
MEMF("Bytes object created with capacity %u, this: %lu, data: %lu", capacity, this, _data.get());
}
virtual ~Bytes() {
MEM(std::string("Bytes object destroyed \"") + toString() + "\", this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((unsigned long)_data.get()));
MEMF("Bytes object destroyed \"%s\", this: %lu, data: %lu", toString().c_str(), this, _data.get());
}
inline const Bytes& operator = (const Bytes& bytes) {
@@ -98,8 +97,8 @@ namespace RNS {
_exclusive = false;
return _data;
}
void newData(size_t size = 0);
void exclusiveData(bool copy = true, size_t size = 0);
void newData(size_t capacity = 0);
void exclusiveData(bool copy = true, size_t capacity = 0);
public:
inline void clear() {
@@ -118,21 +117,19 @@ namespace RNS {
_exclusive = true;
return;
}
//newData();
exclusiveData(false);
exclusiveData(false, bytes._data->size());
_data->insert(_data->begin(), bytes._data->begin(), bytes._data->end());
#endif
}
inline void assign(const uint8_t* chunk, size_t size) {
inline void assign(const uint8_t* chunk, size_t chunk_size) {
// if assignment is empty then clear data and don't bother creating new
if (chunk == nullptr || size <= 0) {
if (chunk == nullptr || chunk_size <= 0) {
_data = nullptr;
_exclusive = true;
return;
}
//newData();
exclusiveData(false);
_data->insert(_data->begin(), chunk, chunk + size);
exclusiveData(false, chunk_size);
_data->insert(_data->begin(), chunk, chunk + chunk_size);
}
inline void assign(const char* string) {
// if assignment is empty then clear data and don't bother creating new
@@ -141,11 +138,12 @@ namespace RNS {
_exclusive = true;
return;
}
//newData();
exclusiveData(false);
_data->insert(_data->begin(), (uint8_t* )string, (uint8_t* )string + strlen(string));
size_t string_size = strlen(string);
exclusiveData(false, string_size);
_data->insert(_data->begin(), (uint8_t* )string, (uint8_t* )string + string_size);
}
inline void assign(const std::string& string) { assign(string.c_str()); }
//inline void assign(const std::string& string) { assign(string.c_str()); }
inline void assign(const std::string& string) { assign((uint8_t*)string.c_str(), string.length()); }
void assignHex(const char* hex);
inline void append(const Bytes& bytes) {
@@ -153,41 +151,48 @@ namespace RNS {
if (bytes.size() <= 0) {
return;
}
exclusiveData(true);
exclusiveData(true, size() + bytes.size());
_data->insert(_data->end(), bytes._data->begin(), bytes._data->end());
}
inline void append(const uint8_t* chunk, size_t size) {
inline void append(const uint8_t* chunk, size_t chunk_size) {
// if append is empty then do nothing
if (chunk == nullptr || size <= 0) {
if (chunk == nullptr || chunk_size <= 0) {
return;
}
exclusiveData(true);
_data->insert(_data->end(), chunk, chunk + size);
exclusiveData(true, size() + chunk_size);
_data->insert(_data->end(), chunk, chunk + chunk_size);
}
inline void append(const char* string) {
// if append is empty then do nothing
if (string == nullptr || string[0] == 0) {
return;
}
exclusiveData(true);
_data->insert(_data->end(), (uint8_t* )string, (uint8_t* )string + strlen(string));
size_t string_size = strlen(string);
exclusiveData(true, size() + string_size);
_data->insert(_data->end(), (uint8_t* )string, (uint8_t* )string + string_size);
}
inline void append(const std::string& string) { append(string.c_str()); }
inline void append(uint8_t byte) {
exclusiveData(true);
exclusiveData(true, size() + 1);
_data->push_back(byte);
}
//inline void append(const std::string& string) { append(string.c_str()); }
inline void append(const std::string& string) { append((uint8_t*)string.c_str(), string.length()); }
void appendHex(const char* hex);
inline uint8_t* writable(size_t size) {
if (size > 0) {
//newData(size);
// create exclusive data with reserved capacity
exclusiveData(false, size);
// actually expand data to requested size
resize(size);
return _data->data();
}
else if (_data) {
//newData(_data->size());
exclusiveData(false, _data->size());
size_t current_size = _data->size();
// create exclusive data with reserved capacity
exclusiveData(false, current_size);
// actually expand data to current size
resize(current_size);
return _data->data();
}
return nullptr;
@@ -198,6 +203,9 @@ namespace RNS {
if (newsize == size()) {
return;
}
// CBA TODO Determine whether or not to reserve capacity here since when size is shrunk the call to
// exclusive data may copy all data firt which will effectively grow the data again before being
// shrunk below (inefficient).
exclusiveData(true);
_data->resize(newsize);
}
@@ -260,12 +268,23 @@ namespace RNS {
}
inline RNS::Bytes& operator << (RNS::Bytes& lhbytes, const RNS::Bytes& rhbytes) {
MEM("Appending right-hand Bytes to left-hand Bytes");
lhbytes.append(rhbytes);
MEM("Returning left-hand Bytes");
return lhbytes;
}
inline RNS::Bytes& operator << (RNS::Bytes& lhbytes, uint8_t rhbyte) {
MEM("Appending right-hand byte to left-hand Bytes");
lhbytes.append(rhbyte);
MEM("Returning left-hand Bytes");
return lhbytes;
}
inline RNS::Bytes& operator << (RNS::Bytes& lhbytes, const char* rhstr) {
MEM("Appending right-hand str to left-hand Bytes");
lhbytes.append(rhstr);
MEM("Returning left-hand Bytes");
return lhbytes;
}
+6 -6
View File
@@ -96,7 +96,7 @@ bool Identity::load_private_key(const Bytes& prv_bytes) {
catch (std::exception& e) {
//p raise e
ERROR("Failed to load identity key");
ERROR("The contained exception was: " + std::string(e.what()));
ERRORF("The contained exception was: %s", e.what());
return false;
}
}
@@ -126,7 +126,7 @@ void Identity::load_public_key(const Bytes& pub_bytes) {
update_hashes();
}
catch (std::exception& e) {
ERROR("Error while loading public key, the contained exception was: " + std::string(e.what()));
ERRORF("Error while loading public key, the contained exception was: %s", e.what());
}
}
@@ -143,7 +143,7 @@ bool Identity::load(const char* path) {
}
catch (std::exception& e) {
ERROR("Error while loading identity from " + std::string(path));
ERROR("The contained exception was: " + std::string(e.what()));
ERRORF("The contained exception was: %s", e.what());
}
return false;
}
@@ -162,8 +162,8 @@ bool Identity::to_file(const char* path) {
return (OS::write_file(path, get_private_key()) == get_private_key().size());
}
catch (std::exception& e) {
ERROR("Error while saving identity to " + std::string(path));
ERROR("The contained exception was: " + std::string(e.what()));
ERRORF("Error while saving identity to %s", path);
ERRORF("The contained exception was: %s", e.what());
}
return false;
}
@@ -315,7 +315,7 @@ Recall last heard app_data for a destination hash.
success = true;
}
catch (std::exception& e) {
ERROR("Error while saving known destinations to disk, the contained exception was: " + std::string(e.what()));
ERRORF("Error while saving known destinations to disk, the contained exception was: %s", e.what());
}
_saving_known_destinations = false;
+6 -9
View File
@@ -9,16 +9,16 @@ using namespace RNS::Type::Interface;
/*static*/ uint8_t Interface::DISCOVER_PATHS_FOR = MODE_ACCESS_POINT | MODE_GATEWAY;
Interface::Interface() : _object(new Object(this)), _creator(true) {
// CBA MCU
//_object->_hash = Identity::full_hash({toString()});
_object->_hash = Identity::truncated_hash({toString()});
// CBA MCU SHORTER HASH
_object->_hash = Identity::full_hash({toString()});
//_object->_hash = Identity::truncated_hash({toString()});
MEM("Interface object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
Interface::Interface(const char* name) : _object(new Object(this, name)), _creator(true) {
// CBA MCU
//_object->_hash = Identity::full_hash({toString()});
_object->_hash = Identity::truncated_hash({toString()});
// CBA MCU SHORTER HASH
_object->_hash = Identity::full_hash({toString()});
//_object->_hash = Identity::truncated_hash({toString()});
MEM("Interface object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
@@ -41,9 +41,6 @@ Interface::Interface(const char* name) : _object(new Object(this, name)), _creat
const Bytes Interface::get_hash() const {
assert(_object);
// CBA MCU
////return Identity::full_hash({toString()});
//return Identity::truncated_hash({toString()});
return _object->_hash;
}
+3 -6
View File
@@ -59,7 +59,7 @@ const char* RNS::getTimeString() {
}
struct tm* tm = localtime(&tv.tv_sec);
size_t len = strftime(_datetime, sizeof(_datetime), "%Y-%m-%d %H:%M:%S", tm);
sprintf(_datetime+len, ".%03d", millis);
snprintf(_datetime+len, sizeof(_datetime)-len, ".%03d", millis);
return _datetime;
#endif
}
@@ -76,7 +76,7 @@ void RNS::setLogCallback(log_callback on_log /*= nullptr*/) {
_on_log = on_log;
}
void RNS::doLog(const char* msg, LogLevel level) {
void RNS::doLog(LogLevel level, const char* msg) {
if (level > _level) {
return;
}
@@ -105,8 +105,5 @@ void HEAD(const char* msg, LogLevel level) {
#else
printf("\n");
#endif
doLog(msg, level);
}
void RNS::doLog(LogLevel level, const char* msg, ...) {
doLog(level, msg);
}
+51 -25
View File
@@ -7,22 +7,37 @@
#include <string>
#define LOG(msg, level) (RNS::log(msg, level))
#define LOGF(level, msg, ...) (RNS::logf(level, msg, __VA_ARGS__))
#define HEAD(msg, level) (RNS::head(msg, level))
#define HEADF(level, msg, ...) (RNS::headf(level, msg, __VA_ARGS__))
#define CRITICAL(msg) (RNS::critical(msg))
#define CRITICALF(msg, ...) (RNS::criticalf(msg, __VA_ARGS__))
#define ERROR(msg) (RNS::error(msg))
#define ERRORF(msg, ...) (RNS::errorf(msg, __VA_ARGS__))
#define WARNING(msg) (RNS::warning(msg))
#define WARNINGF(msg, ...) (RNS::warningf(msg, __VA_ARGS__))
#define NOTICE(msg) (RNS::notice(msg))
#define NOTICEF(msg, ...) (RNS::noticef(msg, __VA_ARGS__))
#define INFO(msg) (RNS::info(msg))
#define INFOF(msg, ...) (RNS::infof(msg, __VA_ARGS__))
#define VERBOSE(msg) (RNS::verbose(msg))
#define VERBOSEF(msg, ...) (RNS::verbosef(msg, __VA_ARGS__))
#ifndef NDEBUG
#define DEBUG(msg) (RNS::debug(msg))
#define DEBUGF(msg, ...) (RNS::debugf(msg, __VA_ARGS__))
#define TRACE(msg) (RNS::trace(msg))
#define TRACEF(msg, ...) (RNS::tracef(msg, __VA_ARGS__))
//#define MEM(msg) (RNS::mem(msg))
#define MEM(ignore) ((void)0)
//#define MEMF(msg, ...) (RNS::memf(msg, __VA_ARGS__))
#define MEMF(...) ((void)0)
#else
#define DEBUG(ignore) ((void)0)
#define TRACE(ignore) ((void)0)
#define DEBUGF(...) ((void)0)
#define TRACE(...) ((void)0)
#define TRACEF(...) ((void)0)
#define MEM(ignore) ((void)0)
#define MEMF(...) ((void)0)
#endif
namespace RNS {
@@ -50,44 +65,55 @@ namespace RNS {
void setLogCallback(log_callback on_log = nullptr);
void doLog(const char* msg, LogLevel level);
void doLog(LogLevel level, const char* msg, ...);
void doLog(LogLevel level, const char* msg);
inline void doLog(LogLevel level, const char* msg, va_list vlist) { char buf[1024]; vsnprintf(buf, sizeof(buf), msg, vlist); doLog(level, buf); }
inline void log(const char* msg, LogLevel level = LOG_NOTICE) { doLog(msg, level); }
inline void log(const char* msg, LogLevel level = LOG_NOTICE) { doLog(level, msg); }
#ifdef ARDUINO
inline void log(const String& msg, LogLevel level = LOG_NOTICE) { doLog(msg.c_str(), level); }
inline void log(const StringSumHelper& msg, LogLevel level = LOG_NOTICE) { doLog(msg.c_str(), level); }
inline void log(const String& msg, LogLevel level = LOG_NOTICE) { doLog(level, msg.c_str()); }
inline void log(const StringSumHelper& msg, LogLevel level = LOG_NOTICE) { doLog(level, msg.c_str()); }
#endif
inline void log(const std::string& msg, LogLevel level = LOG_NOTICE) { doLog(msg.c_str(), level); }
inline void log(const std::string& msg, LogLevel level = LOG_NOTICE) { doLog(level, msg.c_str()); }
inline void logf(LogLevel level, const char* msg, ...) { va_list vlist; va_start(vlist, msg); doLog(level, msg, vlist); va_end(vlist); }
void head(const char* msg, LogLevel level = LOG_NOTICE);
inline void head(const std::string& msg, LogLevel level = LOG_NOTICE) { head(msg.c_str(), level); }
inline void headf(LogLevel level, const char* msg, ...) { va_list vlist; va_start(vlist, msg); doLog(level, msg, vlist); va_end(vlist); }
inline void critical(const char* msg) { doLog(msg, LOG_CRITICAL); }
inline void critical(const std::string& msg) { doLog(msg.c_str(), LOG_CRITICAL); }
inline void critical(const char* msg) { doLog(LOG_CRITICAL, msg); }
inline void critical(const std::string& msg) { doLog(LOG_CRITICAL, msg.c_str()); }
inline void criticalf(const char* msg, ...) { va_list vlist; va_start(vlist, msg); doLog(LOG_CRITICAL, msg, vlist); va_end(vlist); }
inline void error(const char* msg) { doLog(msg, LOG_ERROR); }
inline void error(const std::string& msg) { doLog(msg.c_str(), LOG_ERROR); }
inline void error(const char* msg) { doLog(LOG_ERROR, msg); }
inline void error(const std::string& msg) { doLog(LOG_ERROR, msg.c_str()); }
inline void errorf(const char* msg, ...) { va_list vlist; va_start(vlist, msg); doLog(LOG_ERROR, msg, vlist); va_end(vlist); }
inline void warning(const char* msg) { doLog(msg, LOG_WARNING); }
inline void warning(const std::string& msg) { doLog(msg.c_str(), LOG_WARNING); }
inline void warning(const char* msg) { doLog(LOG_WARNING, msg); }
inline void warning(const std::string& msg) { doLog(LOG_WARNING, msg.c_str()); }
inline void warningf(const char* msg, ...) { va_list vlist; va_start(vlist, msg); doLog(LOG_WARNING, msg, vlist); va_end(vlist); }
inline void notice(const char* msg) { doLog(msg, LOG_NOTICE); }
inline void notice(const std::string& msg) { doLog(msg.c_str(), LOG_NOTICE); }
inline void notice(const char* msg) { doLog(LOG_NOTICE, msg); }
inline void notice(const std::string& msg) { doLog(LOG_NOTICE, msg.c_str()); }
inline void noticef(const char* msg, ...) { va_list vlist; va_start(vlist, msg); doLog(LOG_NOTICE, msg, vlist); va_end(vlist); }
inline void info(const char* msg) { doLog(msg, LOG_INFO); }
inline void info(const std::string& msg) { doLog(msg.c_str(), LOG_INFO); }
inline void info(const char* msg) { doLog(LOG_INFO, msg); }
inline void info(const std::string& msg) { doLog(LOG_INFO, msg.c_str()); }
inline void infof(const char* msg, ...) { va_list vlist; va_start(vlist, msg); doLog(LOG_INFO, msg, vlist); va_end(vlist); }
inline void verbose(const char* msg) { doLog(msg, LOG_VERBOSE); }
inline void verbose(const std::string& msg) { doLog(msg.c_str(), LOG_VERBOSE); }
inline void verbose(const char* msg) { doLog(LOG_VERBOSE, msg); }
inline void verbose(const std::string& msg) { doLog(LOG_VERBOSE, msg.c_str()); }
inline void verbosef(const char* msg, ...) { va_list vlist; va_start(vlist, msg); doLog(LOG_VERBOSE, msg, vlist); va_end(vlist); }
inline void debug(const char* msg) { doLog(msg, LOG_DEBUG); }
inline void debug(const std::string& msg) { doLog(msg.c_str(), LOG_DEBUG); }
inline void debug(const char* msg) { doLog(LOG_DEBUG, msg); }
inline void debug(const std::string& msg) { doLog(LOG_DEBUG, msg.c_str()); }
inline void debugf(const char* msg, ...) { va_list vlist; va_start(vlist, msg); doLog(LOG_DEBUG, msg, vlist); va_end(vlist); }
inline void trace(const char* msg) { doLog(msg, LOG_TRACE); }
inline void trace(const std::string& msg) { doLog(msg.c_str(), LOG_TRACE); }
inline void trace(const char* msg) { doLog(LOG_TRACE, msg); }
inline void trace(const std::string& msg) { doLog(LOG_TRACE, msg.c_str()); }
inline void tracef(const char* msg, ...) { va_list vlist; va_start(vlist, msg); doLog(LOG_TRACE, msg, vlist); va_end(vlist); }
inline void mem(const char* msg) { doLog(msg, LOG_MEM); }
inline void mem(const std::string& msg) { doLog(msg.c_str(), LOG_MEM); }
inline void mem(const char* msg) { doLog(LOG_MEM, msg); }
inline void mem(const std::string& msg) { doLog(LOG_MEM, msg.c_str()); }
inline void memf(const char* msg, ...) { va_list vlist; va_start(vlist, msg); doLog(LOG_MEM, msg, vlist); va_end(vlist); }
}
+3 -3
View File
@@ -506,9 +506,9 @@ void Packet::update_hash() {
const Bytes Packet::get_hash() const {
assert(_object);
Bytes hashable_part = get_hashable_part();
// CBA MCU
//return Identity::full_hash(hashable_part);
return Identity::truncated_hash(hashable_part);
// CBA MCU SHORTER HASH
return Identity::full_hash(hashable_part);
//return Identity::truncated_hash(hashable_part);
}
const Bytes Packet::getTruncatedHash() const {
+1 -1
View File
@@ -225,7 +225,7 @@ namespace RNS {
inline uint8_t flags() const { assert(_object); return _object->_flags; }
inline uint8_t hops() const { assert(_object); return _object->_hops; }
inline void hops(uint8_t hops) { assert(_object); _object->_hops = hops; }
inline const bool cached() const { assert(_object); return _object->_cached; }
inline bool cached() const { assert(_object); return _object->_cached; }
inline void cached(bool cached) { assert(_object); _object->_cached = cached; }
inline const Bytes& packet_hash() const { assert(_object); return _object->_packet_hash; }
inline const Bytes& destination_hash() const { assert(_object); return _object->_destination_hash; }
+39 -26
View File
@@ -15,8 +15,10 @@ using namespace RNS;
using namespace RNS::Type::Reticulum;
using namespace RNS::Utilities;
/*static*/ std::string Reticulum::_storagepath;
/*static*/ std::string Reticulum::_cachepath;
/*static*/ //std::string Reticulum::_storagepath;
/*static*/ char Reticulum::_storagepath[FILEPATH_MAXSIZE];
/*static*/ //std::string Reticulum::_cachepath;
/*static*/ char Reticulum::_cachepath[FILEPATH_MAXSIZE];
/*static*/ bool Reticulum::__transport_enabled = false;
/*static*/ bool Reticulum::__use_implicit_proof = true;
@@ -77,20 +79,25 @@ Reticulum::Reticulum() : _object(new Object()) {
*/
// CBA TEST
#ifdef ARDUINO
_storagepath = "";
_cachepath = "/cache";
//_storagepath = "";
strncpy(_storagepath, "", FILEPATH_MAXSIZE);
//_cachepath = "/cache";
strncpy(_cachepath, "/cache", FILEPATH_MAXSIZE);
#else
_storagepath = ".";
_cachepath = "./cache";
//_storagepath = ".";
strncpy(_storagepath, ".", FILEPATH_MAXSIZE);
//_cachepath = "./cache";
strncpy(_cachepath, "./cache", FILEPATH_MAXSIZE);
#endif
#ifdef ARDUINO
// load time offset from file if it exists
try {
std::string time_offset_path = Reticulum::_storagepath + "/time_offset";
if (OS::file_exists(time_offset_path.c_str())) {
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.c_str(), buf) == 8) {
if (OS::read_file(time_offset_path, buf) == 8) {
uint64_t offset = *(uint64_t*)buf.data();
DEBUG("Read time offset of " + std::to_string(offset) + " from file");
OS::setTimeOffset(offset);
@@ -98,7 +105,7 @@ Reticulum::Reticulum() : _object(new Object()) {
}
}
catch (std::exception& e) {
ERROR("Failed to load time offset, the contained exception was: " + std::string(e.what()));
ERRORF("Failed to load time offset, the contained exception was: %s", e.what());
}
#endif
@@ -215,10 +222,11 @@ void Reticulum::jobs() {
double now = OS::time();
#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 (remaining <= 10) {
if (remaining <= 2) {
head("DETECTED LOW-MEMORY CONDITION (" + std::to_string(remaining) + "%), RESETTING!!!", LOG_CRITICAL);
persist_data();
#if defined(ESP32)
@@ -229,6 +237,7 @@ void Reticulum::jobs() {
#endif
}
}
#endif
if (now > _object->_last_cache_clean + CLEAN_INTERVAL) {
clean_caches();
@@ -254,14 +263,15 @@ void Reticulum::persist_data() {
#ifdef ARDUINO
// write time offset to file
try {
std::string time_offset_path = Reticulum::_storagepath + "/time_offset";
char time_offset_path[FILEPATH_MAXSIZE];
snprintf(time_offset_path, FILEPATH_MAXSIZE, "%s/time_offset", _storagepath);
uint64_t offset = OS::ltime();
DEBUG("Writing time offset of " + std::to_string(offset) + " to file");
DEBUGF("Writing time offset of %llu to file %s", offset, time_offset_path);
Bytes buf((uint8_t*)&offset, sizeof(offset));
OS::write_file(time_offset_path.c_str(), buf);
OS::write_file(time_offset_path, buf);
}
catch (std::exception& e) {
ERROR("Failed to write time offset, the contained exception was: " + std::string(e.what()));
ERRORF("Failed to write time offset, the contained exception was: %s", e.what());
}
#endif
@@ -277,7 +287,8 @@ void Reticulum::clean_caches() {
for (auto& filename : OS::list_directory(resourcepath) {
try {
if (filename.length() == (Type::Identity::HASHLENGTH//8)*2) {
std::string filepath = _resourcepath + "/" + filename;
char filepath[FILEPATH_MAXSIZE];
snprintf(filepath, FILEPATH_MAXSIZE, "%s/%s", _resourcepath, filename.c_str());
//p mtime = os.path.getmtime(filepath)
//p age = now - mtime
//p if (age > Types::Reticulum.RESOURCE_CACHE) {
@@ -286,7 +297,7 @@ void Reticulum::clean_caches() {
}
}
catch (std::exception& e) {
ERROR("Error while cleaning resources cache, the contained exception was: " + std::string(e.what()));
ERROR("Error while cleaning resources cache, the contained exception was: %s", e.what());
}
}
@@ -294,7 +305,8 @@ void Reticulum::clean_caches() {
for (auto& filename : OS::list_directory(_cachepath.c_str())) {
try {
if (filename.length() == (Type::Identity::HASHLENGTH/8)*2) {
std::string filepath = _cachepath + "/" + filename;
char filepath[FILEPATH_MAXSIZE];
snprintf(filepath, FILEPATH_MAXSIZE, "%s/%s", _cachepath, filename.c_str());
//p mtime = os.path.getmtime(filepath)
//p age = now - mtime
//p if (age > Types::Transport::DESTINATION_TIMEOUT) {
@@ -303,7 +315,7 @@ void Reticulum::clean_caches() {
}
}
catch (std::exception& e) {
ERROR("Error while cleaning packet cache, the contained exception was: " + std::string(e.what()));
ERROR("Error while cleaning packet cache, the contained exception was: %s", e.what());
}
}
*/
@@ -319,18 +331,19 @@ void Reticulum::clear_caches() {
TRACE("Clearing resource and packet caches...");
try {
std::string destination_table_path = _storagepath + "/destination_table";
OS::remove_file(destination_table_path.c_str());
char destination_table_path[FILEPATH_MAXSIZE];
snprintf(destination_table_path, FILEPATH_MAXSIZE, "%s/destination_table", _storagepath);
OS::remove_file(destination_table_path);
std::string packet_cache_path = _cachepath;
OS::remove_directory(packet_cache_path.c_str());
OS::remove_directory(_cachepath);
#ifdef ARDUINO
std::string time_offset_path = _storagepath + "/time_offset";
OS::remove_file(time_offset_path.c_str());
char time_offset_path[FILEPATH_MAXSIZE];
snprintf(time_offset_path, FILEPATH_MAXSIZE, "%s/time_offset", _storagepath);
OS::remove_file(time_offset_path);
#endif
}
catch (std::exception& e) {
ERROR("Failed to clear cache file(s), the contained exception was: " + std::string(e.what()));
ERRORF("Failed to clear cache file(s), the contained exception was: %s", e.what());
}
}
+4 -2
View File
@@ -25,9 +25,11 @@ namespace RNS {
//z configdir = None
//z configpath = ""
//p storagepath = ""
static std::string _storagepath;
//static std::string _storagepath;
static char _storagepath[Type::Reticulum::FILEPATH_MAXSIZE];
//p cachepath = ""
static std::string _cachepath;
//static std::string _cachepath;
static char _cachepath[Type::Reticulum::FILEPATH_MAXSIZE];
static bool __transport_enabled;
static bool __use_implicit_proof;
+76 -67
View File
@@ -122,30 +122,31 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
_last_saved = OS::time();
// ensure required directories exist
if (!OS::directory_exists(Reticulum::_cachepath.c_str())) {
if (!OS::directory_exists(Reticulum::_cachepath)) {
VERBOSE("No cache directory, creating...");
OS::create_directory(Reticulum::_cachepath.c_str());
OS::create_directory(Reticulum::_cachepath);
}
if (!_identity) {
std::string transport_identity_path = Reticulum::_storagepath + "/transport_identity";
char transport_identity_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(transport_identity_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/transport_identity", Reticulum::_storagepath);
DEBUG("Checking for transport identity...");
try {
if (OS::file_exists(transport_identity_path.c_str())) {
_identity = Identity::from_file(transport_identity_path.c_str());
if (OS::file_exists(transport_identity_path)) {
_identity = Identity::from_file(transport_identity_path);
}
if (!_identity) {
VERBOSE("No valid Transport Identity in storage, creating...");
_identity = Identity();
_identity.to_file(transport_identity_path.c_str());
_identity.to_file(transport_identity_path);
}
else {
VERBOSE("Loaded Transport Identity from storage");
}
}
catch (std::exception& e) {
ERROR("Failed to check for transport identity, the contained exception was: " + std::string(e.what()));
ERRORF("Failed to check for transport identity, the contained exception was: %s", e.what());
}
}
@@ -160,7 +161,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
file.close();
}
catch (std::exception& e) {
ERROR("Could not load packet hashlist from storage, the contained exception was: " + std::string(e.what()));
ERROR("Could not load packet hashlist from storage, the contained exception was: %s", e.what());
}
}
}
@@ -197,6 +198,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
// Read in path table and then write and clean in case any entries are invalid
read_path_table();
DEBUG("Writing path table and cleaning caches to clean-up any orphaned paths/files");
write_path_table();
clean_caches();
@@ -637,7 +639,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
}
catch (std::exception& e) {
ERROR("An exception occurred while running Transport jobs.");
ERROR("The contained exception was: " + std::string(e.what()));
ERRORF("The contained exception was: %s", e.what());
}
_jobs_running = false;
@@ -757,7 +759,9 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
// Insert packet into transport
//new_flags = (RNS.Packet.HEADER_2) << 6 | (Transport.TRANSPORT) << 4 | (packet.flags & 0b00001111)
uint8_t new_flags = (Type::Packet::HEADER_2) << 6 | (Type::Transport::TRANSPORT) << 4 | (packet.flags() & 0b00001111);
Bytes new_raw;
// CBA RESERVE
//Bytes new_raw;
Bytes new_raw(512);
//new_raw = struct.pack("!B", new_flags)
new_raw << new_flags;
//new_raw += packet.raw[1:2]
@@ -787,7 +791,9 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
// Insert packet into transport
//new_flags = (RNS.Packet.HEADER_2) << 6 | (Transport.TRANSPORT) << 4 | (packet.flags & 0b00001111)
uint8_t new_flags = (Type::Packet::HEADER_2) << 6 | (Type::Transport::TRANSPORT) << 4 | (packet.flags() & 0b00001111);
Bytes new_raw;
// CBA RESERVE
//Bytes new_raw;
Bytes new_raw(512);
//new_raw = struct.pack("!B", new_flags)
new_raw << new_flags;
//new_raw += packet.raw[1:2]
@@ -1468,7 +1474,9 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
Bytes next_hop = destination_entry._received_from;
uint8_t remaining_hops = destination_entry._hops;
Bytes new_raw;
// CBA RESERVE
//Bytes new_raw;
Bytes new_raw(512);
if (remaining_hops > 1) {
// Just increase hop count and transmit
//new_raw = packet.raw[0:1]
@@ -1596,7 +1604,9 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
if (outbound_interface) {
TRACE("Transport::inbound: Transmitting link transport packet");
Bytes new_raw;
// CBA RESERVE
//Bytes new_raw;
Bytes new_raw(512);
//new_raw = packet.raw[0:1]
new_raw << packet.raw().left(1);
//new_raw += struct.pack("!B", packet.hops)
@@ -2058,7 +2068,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
}
catch (std::exception& e) {
ERROR("Error while processing external announce callback.");
ERROR("The contained exception was: " + std::string(e.what()));
ERRORF("The contained exception was: %s", e.what());
}
}
}
@@ -2183,7 +2193,10 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
if (peer_identity.validate(signature, signed_data)) {
TRACE("Link request proof validated for transport via " + link_entry._receiving_interface.toString());
//p new_raw = packet.raw[0:1]
Bytes new_raw = packet.raw().left(1);
// CBA RESERVE
//Bytes new_raw = packet.raw().left(1);
Bytes new_raw(512);
new_raw << packet.raw().left(1);
//p new_raw += struct.pack("!B", packet.hops)
new_raw << packet.hops();
//p new_raw += packet.raw[2:]
@@ -2245,7 +2258,10 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size);
if (packet.receiving_interface() == reverse_entry._outbound_interface) {
TRACE("Proof received on correct interface, transporting it via " + reverse_entry._receiving_interface.toString());
//p new_raw = packet.raw[0:1]
Bytes new_raw = packet.raw().left(1);
// CBA RESERVE
//Bytes new_raw = packet.raw().left(1);
Bytes new_raw(512);
new_raw << packet.raw().left(1);
//p new_raw += struct.pack("!B", packet.hops)
new_raw << packet.hops();
//p new_raw += packet.raw[2:]
@@ -2615,8 +2631,9 @@ Deregisters an announce handler.
if (should_cache_packet(packet) || force_cache) {
TRACE("Saving packet " + packet.get_hash().toHex() + " to storage");
try {
std::string packet_cache_path = Reticulum::_cachepath + "/" + packet.get_hash().toHex();
return Persistence::serialize(packet, packet_cache_path.c_str());
char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, packet.get_hash().toHex().c_str());
return Persistence::serialize(packet, packet_cache_path);
}
catch (std::exception& e) {
ERROR("Error writing packet to cache. The contained exception was: " + std::string(e.what()));
@@ -2648,17 +2665,18 @@ Deregisters an announce handler.
else:
return None
*/
std::string packet_cache_path = Reticulum::_cachepath + "/" + packet_hash.toHex();
char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, packet_hash.toHex().c_str());
//return Persistence::deserialize(packet_cache_path.c_str());
Packet packet({Type::NONE});
if (Persistence::deserialize(packet, packet_cache_path.c_str())) {
if (Persistence::deserialize(packet, packet_cache_path)) {
packet.update_hash();
}
return packet;
}
catch (std::exception& e) {
ERROR("Exception occurred while getting cached packet.");
ERROR("The contained exception was: " + std::string(e.what()));
ERRORF("The contained exception was: %s", e.what());
}
return {Type::NONE};
}
@@ -2666,9 +2684,10 @@ Deregisters an announce handler.
/*static*/ bool Transport::clear_cached_packet(const Bytes& packet_hash) {
TRACE("Clearing packet " + packet_hash.toHex() + " from cache storage");
try {
std::string packet_cache_path = Reticulum::_cachepath + "/" + packet_hash.toHex();
char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, packet_hash.toHex().c_str());
double start_time = OS::time();
bool success = RNS::Utilities::OS::remove_file(packet_cache_path.c_str());
bool success = RNS::Utilities::OS::remove_file(packet_cache_path);
double diff_time = OS::time() - start_time;
if (diff_time < 1.0) {
DEBUG("Remove cached packet in " + std::to_string((int)(diff_time*1000)) + " ms");
@@ -2679,7 +2698,7 @@ Deregisters an announce handler.
}
catch (std::exception& e) {
ERROR("Exception occurred while clearing cached packet.");
ERROR("The contained exception was: " + std::string(e.what()));
ERRORF("The contained exception was: %s", e.what());
}
return false;
}
@@ -3032,7 +3051,6 @@ will announce it.
// rebroadcast locally. In such a case the actual announce
// is temporarily held, and then reinserted when the path
// request has been served to the peer.
const Packet& announce_packet = announce_packet;
auto announce_iter = _announce_table.find(announce_packet.destination_hash());
if (announce_iter != _announce_table.end()) {
AnnounceEntry& held_entry = (*announce_iter).second;
@@ -3306,8 +3324,9 @@ will announce it.
/*static*/ bool Transport::read_path_table() {
DEBUG("Transport::read_path_table");
std::string destination_table_path = Reticulum::_storagepath + "/destination_table";
if (!_owner.is_connected_to_shared_instance() && OS::file_exists(destination_table_path.c_str())) {
char destination_table_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(destination_table_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/destination_table", Reticulum::_storagepath);
if (!_owner.is_connected_to_shared_instance() && OS::file_exists(destination_table_path)) {
/*p
serialised_destinations = []
try:
@@ -3346,7 +3365,7 @@ will announce it.
try {
TRACE("Transport::start: buffer capacity " + std::to_string(Persistence::_buffer.capacity()) + " bytes");
if (RNS::Utilities::OS::read_file(destination_table_path.c_str(), Persistence::_buffer) > 0) {
if (RNS::Utilities::OS::read_file(destination_table_path, Persistence::_buffer) > 0) {
TRACE("Transport::start: read: " + std::to_string(Persistence::_buffer.size()) + " bytes");
#ifndef NDEBUG
// CBA DEBUG Dump path table
@@ -3400,7 +3419,7 @@ TRACE("Transport::start: buffer size " + std::to_string(Persistence::_buffer.siz
}
catch (std::exception& e) {
ERROR("Could not load destination table from storage, the contained exception was: " + std::string(e.what()));
ERRORF("Could not load destination table from storage, the contained exception was: %s", e.what());
}
}
return false;
@@ -3474,8 +3493,6 @@ TRACE("Transport::start: buffer size " + std::to_string(Persistence::_buffer.siz
file.close()
*/
std::string destination_table_path = Reticulum::_storagepath + "/destination_table";
{
Persistence::_document.set(_destination_table);
TRACE("Transport::write_path_table: doc size " + std::to_string(Persistence::_document.memoryUsage()) + " bytes");
@@ -3496,6 +3513,8 @@ TRACE("Transport::write_path_table: buffer addr: " + std::to_string((long)buffer
}
}
if (Persistence::_buffer.size() > 0) {
char destination_table_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(destination_table_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/destination_table", Reticulum::_storagepath);
#ifndef NDEBUG
// CBA DEBUG Dump path table
TRACE("Transport::write_path_table: buffer addr: " + std::to_string((long)Persistence::_buffer.data()));
@@ -3508,7 +3527,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence::
if (_destination_table_crc > 0 && crc == _destination_table_crc) {
TRACE("Transport::write_path_table: no change detected, skipping write");
}
else if (RNS::Utilities::OS::write_file(destination_table_path.c_str(), Persistence::_buffer) == Persistence::_buffer.size()) {
else if (RNS::Utilities::OS::write_file(destination_table_path, Persistence::_buffer) == Persistence::_buffer.size()) {
TRACE("Transport::write_path_table: wrote " + std::to_string(_destination_table.size()) + " entries, " + std::to_string(Persistence::_buffer.size()) + " bytes");
_destination_table_crc = crc;
success = true;
@@ -3542,7 +3561,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence::
}
}
catch (std::exception& e) {
ERROR("Could not save path table to storage, the contained exception was: " + std::string(e.what()));
ERRORF("Could not save path table to storage, the contained exception was: %s", e.what());
}
_saving_path_table = false;
@@ -3694,7 +3713,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence::
/*static*/ void Transport::clean_caches() {
TRACE("Transport::clean_caches()");
// CBA Remove cached packets no longer in path list
std::list<std::string> files = OS::list_directory(Reticulum::_cachepath.c_str());
std::list<std::string> files = OS::list_directory(Reticulum::_cachepath);
for (auto& file : files) {
TRACE("Transport::clean_caches: Checking for use of cached packet " + file);
bool found = false;
@@ -3705,29 +3724,17 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence::
}
}
if (!found) {
TRACE("Transport::clean_caches: Removing cached packet " + file);
std::string packet_cache_path = Reticulum::_cachepath + "/" + file;
OS::remove_file(packet_cache_path.c_str());
TRACE("Transport::clean_caches: No matching path found, removing cached packet " + file);
char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, file.c_str());
OS::remove_file(packet_cache_path);
}
}
}
/*static*/ void Transport::dump_stats() {
#if defined(ESP32)
TRACE("Psram size: " + std::to_string(ESP.getPsramSize()));
TRACE("Psram free: " + std::to_string(ESP.getFreePsram()));
TRACE("Psram min free: " + std::to_string(ESP.getMinFreePsram()));
TRACE("Psram max alloc: " + std::to_string(ESP.getMaxAllocPsram()));
TRACE("Heap size: " + std::to_string(ESP.getHeapSize()));
TRACE("Heap free: " + std::to_string(ESP.getFreeHeap()));
TRACE("Heap min free: " + std::to_string(ESP.getMinFreeHeap()));
TRACE("Heap max alloc: " + std::to_string(ESP.getMaxAllocHeap()));
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
if (loglevel() == LOG_TRACE) {
dbgMemInfo();
}
#endif
OS::dump_heap_stats();
size_t memory = OS::heap_available();
size_t flash = OS::storage_available();
@@ -3746,7 +3753,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence::
// _reverse_table
// _announce_table
// _held_announces
HEAD("mem: " + std::to_string(memory) + " (" + std::to_string((int)((double)memory / (double)OS::heap_size() * 100.0)) + "%) [" + std::to_string((int)memory - (int)_last_memory) + "] flash: " + std::to_string(flash) + " (" + std::to_string((int)((double)flash / (double)OS::storage_size() * 100.0)) + "%) [" + std::to_string((int)flash - (int)_last_flash) + "] paths: " + std::to_string(_destination_table.size()) + " dsts: " + std::to_string(_destinations.size()) + " revr: " + std::to_string(_reverse_table.size()) + " annc: " + std::to_string(_announce_table.size()) + " held: " + std::to_string(_held_announces.size()), LOG_VERBOSE);
HEADF(LOG_VERBOSE, "mem: %u (%u%%) [%d] flash: %u (%u%%) [%d] paths: %u dsts: %u revr: %u annc: %u held: %u", memory, (int)((double)memory / (double)OS::heap_size() * 100.0), memory - _last_memory, flash, (int)((double)flash / (double)OS::storage_size() * 100.0), flash - _last_flash, _destination_table.size(), _destinations.size(), _reverse_table.size(), _announce_table.size(), _held_announces.size());
// _path_requests
// _discovery_path_requests
@@ -3754,7 +3761,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence::
// _discovery_pr_tags
// _control_destinations
// _control_hashes
VERBOSE("preqs: " + std::to_string(_path_requests.size()) + " dpreqs: " + std::to_string(_discovery_path_requests.size()) + " ppreqs: " + std::to_string(_pending_local_path_requests.size()) + " dprt: " + std::to_string(_discovery_pr_tags.size()) + " cdsts: " + std::to_string(_control_destinations.size()) + " chshs: " + std::to_string(_control_hashes.size()));
VERBOSEF("preqs: %u dpreqs: %u ppreqs: %u dprt: %u cdsts: %u chshs: %u", _path_requests.size(), _discovery_path_requests.size(), _pending_local_path_requests.size(), _discovery_pr_tags.size(), _control_destinations.size(), _control_hashes.size());
// _packet_hashlist
// _receipts
@@ -3770,8 +3777,8 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence::
for (auto& [interface_hash, interface] : _interfaces) {
interface_announces += interface.announce_queue().size();
}
VERBOSE("phl: " + std::to_string(_packet_hashlist.size()) + " rcp: " + std::to_string(_receipts.size()) + " lt: " + std::to_string(_link_table.size()) + " pl: " + std::to_string(_pending_links.size()) + " al: " + std::to_string(_active_links.size()) + " tun: " + std::to_string(_tunnels.size()));
VERBOSE("pin: " + std::to_string(_packets_received) + " pout: " + std::to_string(_packets_sent) + " dadd: " + std::to_string(_destinations_added) + " dpr: " + std::to_string(destination_path_responses) + " ikd: " + std::to_string(Identity::_known_destinations.size()) + " ia: " + std::to_string(interface_announces) + "\r\n");
VERBOSEF("phl: %u rcp: %u lt: %u pl: %u al: %u tun: %u", _packet_hashlist.size(), _receipts.size(), _link_table.size(), _pending_links.size(), _active_links.size(), _tunnels.size());
VERBOSEF("pin: %u pout: %u padd: %u dpr: %u ikd: %u ia: %u\r\n", _packets_received, _packets_sent, _destinations_added, destination_path_responses, Identity::_known_destinations.size(), interface_announces);
_last_memory = memory;
_last_flash = flash;
@@ -3827,13 +3834,14 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence::
WARNING("Failed to remove destination " + announce_packet.destination_hash().toHex() + " from path table");
}
// Remove announce packet from packet table
if (_packet_table.erase(destination_entry._announce_packet) < 1) {
WARNING("Failed to remove packet " + destination_entry._announce_packet.toHex() + " from packet table");
}
//if (_packet_table.erase(destination_entry._announce_packet) < 1) {
// WARNING("Failed to remove packet " + destination_entry._announce_packet.toHex() + " from packet table");
//}
// Remove cached packet file
std::string packet_cache_path = Reticulum::_cachepath + "/" + destination_entry._announce_packet.toHex();
if (OS::file_exists(packet_cache_path.c_str())) {
OS::remove_file(packet_cache_path.c_str());
char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, destination_entry._announce_packet.toHex().c_str());
if (OS::file_exists(packet_cache_path)) {
OS::remove_file(packet_cache_path);
}
++count;
if (_destination_table.size() <= _path_table_maxsize) {
@@ -3860,13 +3868,14 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence::
WARNING("Failed to remove destination " + destination_hash.toHex() + " from path table");
}
// Remove announce packet from packet table
if (_packet_table.erase(destination_entry._announce_packet) < 1) {
WARNING("Failed to remove packet " + destination_entry._announce_packet.toHex() + " from packet table");
}
//if (_packet_table.erase(destination_entry._announce_packet) < 1) {
// WARNING("Failed to remove packet " + destination_entry._announce_packet.toHex() + " from packet table");
//}
// Remove cached packet file
std::string packet_cache_path = Reticulum::_cachepath + "/" + destination_entry._announce_packet.toHex();
if (OS::file_exists(packet_cache_path.c_str())) {
OS::remove_file(packet_cache_path.c_str());
char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, destination_entry._announce_packet.toHex().c_str());
if (OS::file_exists(packet_cache_path)) {
OS::remove_file(packet_cache_path);
}
++count;
if (_destination_table.size() <= _path_table_maxsize) {
+2
View File
@@ -355,6 +355,8 @@ namespace RNS {
inline static void path_table_maxsize(uint16_t path_table_maxsize) { _path_table_maxsize = path_table_maxsize; }
inline static uint16_t probe_destination_enabled() { 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; }
private:
// CBA MUST use references to interfaces here in order for virtul overrides for send/receive to work
+6 -1
View File
@@ -85,14 +85,19 @@ namespace RNS { namespace Type {
// CBA TEST
static const uint16_t CLEAN_INTERVAL = 60*15;
//static const uint16_t CLEAN_INTERVAL = 60;
// CBA TEST
// 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 GRACIOUS_PERSIST_INTERVAL = 60*5;
static const uint8_t DESTINATION_LENGTH = TRUNCATED_HASHLENGTH/8; // In bytes
// CBA MCU
//static const uint8_t FILEPATH_MAXSIZE = 64;
static const uint8_t FILEPATH_MAXSIZE = 96;
}
namespace Identity {
+225 -27
View File
@@ -2,19 +2,210 @@
#include "../Log.h"
//#ifdef ARDUINO
#if 0
#ifdef __arm__
// should use uinstd.h to define sbrk but Due causes a conflict
//extern "C" char* sbrk(int incr);
#else
extern char *__brkval;
#endif
#endif
using namespace RNS;
using namespace RNS::Utilities;
#if defined(RNS_USE_ALLOCATOR)
#if defined(RNS_USE_TLSF)
#if defined(ESP32)
#define BUFFER_SIZE 1024 * 80
#define BUFFER_FRACTION 0.8
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
#define BUFFER_SIZE 1024 * 80
#define BUFFER_FRACTION 0.8
#endif
boolean tlsf_init = false;
size_t _buffer_size = 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
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;
// 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) {
#if defined(RNS_USE_TLSF)
//if (OS::_tlsf == nullptr) {
if (!tlsf_init) {
tlsf_init = true;
#if defined(ESP32)
_contiguous_size = ESP.getMaxAllocHeap();
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
_contiguous_size = dbgHeapFree();
#endif
TRACEF("contiguous_size: %u", _contiguous_size);
_buffer_size = (size_t)((_contiguous_size * BUFFER_FRACTION) / 1024) * 1024;
TRACEF("buffer_size: %u", _buffer_size);
//void* raw_buffer = malloc(BUFFER_SIZE);
void* raw_buffer = malloc(_buffer_size);
if (raw_buffer == nullptr) {
ERROR("-- allocation for tlsf FAILED");
}
else {
#if 1
//OS::_tlsf = tlsf_create_with_pool(raw_buffer, BUFFER_SIZE);
OS::_tlsf = tlsf_create_with_pool(raw_buffer, _buffer_size);
#else
Serial.print("raw_buffer: ");
Serial.println((long)raw_buffer);
Serial.print("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("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("-- initialization of tlsf FAILED");
}
}
}
#endif
++_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) {
//TRACEF("--- allocating memory from tlsf (%u bytes)", size);
p = tlsf_malloc(OS::_tlsf, size);
//TRACEF("--- allocated memory from tlsf (%u bytes) (addr=%lx)", size, p);
}
else {
//TRACEF("--- allocating memory (%u bytes)", size);
p = malloc(size);
//TRACEF("--- allocated memory (%u bytes) (addr=%lx)", size, p);
++_new_fault;
}
#else
//TRACEF("--- allocating memory (%u bytes)", size);
p = malloc(size);
//TRACEF("--- allocated memory (%u bytes) (addr=%lx)", size, p);
#endif
return p;
}
// CBA Added attribute weak to avoid collision with new override on nrf52
void operator delete(void* p) {
//__attribute__((weak)) void operator delete(void* p) {
#if defined(RNS_USE_TLSF)
if (OS::_tlsf != nullptr) {
//TRACEF("--- freeing memory from tlsf (addr=%lx)", 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
++_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
}
#if defined(RNS_USE_TLSF)
uint32_t _tlsf_used_count = 0;
uint32_t _tlsf_used_size = 0;
uint32_t _tlsf_free_count = 0;
uint32_t _tlsf_free_size = 0;
uint32_t _tlsf_free_max_size = 0;
void tlsf_mem_walker(void* ptr, size_t size, int used, void* user)
{
if (used) {
_tlsf_used_count++;
_tlsf_used_size += size;
}
else {
_tlsf_free_count++;
_tlsf_free_size += size;
if (size > _tlsf_free_max_size) {
_tlsf_free_max_size = size;
}
}
}
void dump_tlsf_stats() {
_tlsf_used_count = 0;
_tlsf_used_size = 0;
_tlsf_free_count = 0;
_tlsf_free_size = 0;
_tlsf_free_max_size = 0;
tlsf_walk_pool(tlsf_get_pool(OS::_tlsf), tlsf_mem_walker, nullptr);
HEAD("TLSF Stats", LOG_TRACE);
TRACEF("Buffer Size: %u", _buffer_size);
TRACEF("Contiguous Size: %u", _contiguous_size);
TRACEF("Used Count: %u", _tlsf_used_count);
TRACEF("Used Size: %u (%u%% used)", _tlsf_used_size, (unsigned)((double)_tlsf_used_size / (double)_buffer_size * 100.0));
TRACEF("Free Count: %u", _tlsf_free_count);
TRACEF("Free Size: %u (%u%% free)", _tlsf_free_size, (unsigned)((double)_tlsf_free_size / (double)_buffer_size * 100.0));
TRACEF("Max Free Size: %u (%u%% fragmented)\n", _tlsf_free_max_size, (unsigned)(100.0 - (double)_tlsf_free_max_size / (double)_tlsf_free_size * 100.0));
}
#endif
/*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;
@@ -106,23 +297,6 @@ using namespace RNS::Utilities;
return _filesystem.do_storage_available();
}
/*
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 OS::heap_size() {
#if defined(ESP32)
return ESP.getHeapSize();
@@ -143,3 +317,27 @@ size_t maxContiguousAllocation() {
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
}
+11 -1
View File
@@ -3,6 +3,8 @@
#include "../Filesystem.h"
#include "../Bytes.h"
#include "tlsf.h"
#include <cmath>
#include <unistd.h>
#include <time.h>
@@ -23,6 +25,9 @@ namespace RNS { namespace Utilities {
static Filesystem _filesystem;
static uint64_t _time_offset;
public:
static tlsf_t _tlsf;
public:
static inline uint64_t getTimeOffset() { return _time_offset; }
static inline void setTimeOffset(uint64_t offset) { _time_offset = offset; }
@@ -64,6 +69,10 @@ namespace RNS { namespace Utilities {
//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; }
#if defined(RNS_USE_ALLOCATOR)
static void dump_allocator_stats();
#endif
static void register_filesystem(Filesystem& filesystem);
static void deregister_filesystem();
@@ -81,7 +90,8 @@ namespace RNS { namespace Utilities {
static size_t heap_size();
static size_t heap_available();
static void dump_heap_stats();
};
} }
+1
View File
@@ -372,6 +372,7 @@ namespace RNS { namespace Persistence {
}
return true;
}
template <typename T> bool deserialize(T& obj, const char* file_path) {
if (RNS::Utilities::OS::read_file(file_path, _buffer) > 0) {
TRACE("Persistence::deserialize: read: " + std::to_string(_buffer.size()) + " bytes");
+1268
View File
File diff suppressed because it is too large. Load diff
+90
View File
@@ -0,0 +1,90 @@
#ifndef INCLUDED_tlsf
#define INCLUDED_tlsf
/*
** Two Level Segregated Fit memory allocator, version 3.1.
** Written by Matthew Conte
** http://tlsf.baisoku.org
**
** Based on the original documentation by Miguel Masmano:
** http://www.gii.upv.es/tlsf/main/docs
**
** This implementation was written to the specification
** of the document, therefore no GPL restrictions apply.
**
** Copyright (c) 2006-2016, Matthew Conte
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the copyright holder nor the
** names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL MATTHEW CONTE BE LIABLE FOR ANY
** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stddef.h>
#if defined(__cplusplus)
extern "C" {
#endif
/* tlsf_t: a TLSF structure. Can contain 1 to N pools. */
/* pool_t: a block of memory that TLSF can manage. */
typedef void* tlsf_t;
typedef void* pool_t;
/* Create/destroy a memory pool. */
tlsf_t tlsf_create(void* mem);
tlsf_t tlsf_create_with_pool(void* mem, size_t bytes);
void tlsf_destroy(tlsf_t tlsf);
pool_t tlsf_get_pool(tlsf_t tlsf);
/* Add/remove memory pools. */
pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes);
void tlsf_remove_pool(tlsf_t tlsf, pool_t pool);
/* malloc/memalign/realloc/free replacements. */
void* tlsf_malloc(tlsf_t tlsf, size_t bytes);
void* tlsf_memalign(tlsf_t tlsf, size_t align, size_t bytes);
void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size);
void tlsf_free(tlsf_t tlsf, void* ptr);
/* Returns internal block size, not original request size */
size_t tlsf_block_size(void* ptr);
/* Overheads/limits of internal structures. */
size_t tlsf_size(void);
size_t tlsf_align_size(void);
size_t tlsf_block_size_min(void);
size_t tlsf_block_size_max(void);
size_t tlsf_pool_overhead(void);
size_t tlsf_alloc_overhead(void);
/* Debugging. */
typedef void (*tlsf_walker)(void* ptr, size_t size, int used, void* user);
void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void* user);
/* Returns nonzero if any internal consistency check fails. */
int tlsf_check(tlsf_t tlsf);
int tlsf_check_pool(pool_t pool);
#if defined(__cplusplus)
};
#endif
#endif