WIP: Continued work of persistence and refactoring

This commit is contained in:
attermann committed 2023-12-11 13:42:20 -07:00
1 parent f9a679ffc2
commit 162dcff6cd
25 files changed
+1026 -315

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
name=reticulum-cpp
version=0.1.1
author=Chad Attermann <attermann@gmail.com>
maintainer=Chad Attermann <attermann@gmail.com>
sentence=Port of Reticulum Network Stack to C++
paragraph=Port of Reticulum Network Stack to C++ specifically but not exclusively targeting 32-bit and better MCUs
category=Communication
url=https://github.com/attermann/reticulum-cpp
architectures=*
+20
View File
@@ -43,9 +43,29 @@ lib_deps =
rweather/Crypto@^0.4.0
lib_compat_mode = off
[env:cubecell_gps]
platform = heltec-cubecell
board = cubecell_gps
framework = arduino
monitor_speed = 115200
;build_flags = -Wl,-Map,output.map
build_flags =
-std=c++11
-Wall
-Wextra
-Wno-missing-field-initializers
-Wno-format
-Isrc
lib_deps =
ArduinoJson@^6.21.3
rweather/Crypto@^0.4.0
; CBA NOTE must undef min and max from Arduino.h
[env:ttgo-t-beam]
platform = espressif32
board = ttgo-t-beam
board_build.partitions = no_ota.csv
;board_build.partitions = huge_app.csv
framework = arduino
monitor_speed = 115200
build_flags =
+1 -1
View File
@@ -21,7 +21,7 @@
*/
#include "CBC.h"
#include "Crypto.h"
#include <Crypto.h>
#include <string.h>
/**
+2 -2
View File
@@ -23,8 +23,8 @@
#ifndef CRYPTO_CBC_h
#define CRYPTO_CBC_h
#include "Cipher.h"
#include "BlockCipher.h"
#include <Cipher.h>
#include <BlockCipher.h>
class CBCCommon : public Cipher
{
+1 -1
View File
@@ -25,7 +25,7 @@ namespace RNS { namespace Cryptography {
return randnum;
}
// return 32 bit random unigned int between 0 and specified value
// return 32 bit random unsigned int between 0 and specified value
inline uint32_t randomnum(uint32_t max) {
return randomnum() % max;
}
+1 -1
View File
@@ -86,7 +86,7 @@ Destination::Destination(const Identity& identity, const Type::Destination::dire
/*virtual*/ Destination::~Destination() {
mem("Destination object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
if (_object && _object.use_count() == 1) {
extreme("Destination object has last data reference");
mem("Destination object has last data reference");
// CBA Can't call deregister_destination here because it's possible (likely even) that Destination
// is being destructed from that same collection which will result in a llop and memory errors.
+1 -1
View File
@@ -173,7 +173,7 @@ namespace RNS {
inline const Callbacks& callbacks() const { assert(_object); return _object->_callbacks; }
inline const Identity& identity() const { assert(_object); return _object->_identity; }
inline std::string toString() const { assert(_object); return "{Destination:" + _object->_hash.toHex() + "}"; }
inline std::string toString() const { if (!_object) return ""; return "{Destination:" + _object->_hash.toHex() + "}"; }
private:
class Object {
+6
View File
@@ -249,6 +249,7 @@ Recall last heard app_data for a destination hash.
// simply overwrite on exit now that every local client
// disconnect triggers a data persist.
bool success = false;
try {
if (_saving_known_destinations) {
double wait_interval = 0.2;
@@ -304,12 +305,16 @@ Recall last heard app_data for a destination hash.
}
debug("Saved known destinations to storage in " + time_str);
success = true;
}
catch (std::exception& e) {
error("Error while saving known destinations to disk, the contained exception was: " + std::string(e.what()));
}
_saving_known_destinations = false;
return success;
}
/*static*/ void Identity::load_known_destinations() {
@@ -332,6 +337,7 @@ Recall last heard app_data for a destination hash.
else:
RNS.log("Destinations file does not exist, no known destinations loaded", RNS.LOG_VERBOSE)
*/
}
/*static*/ bool Identity::validate_announce(const Packet& packet) {
+1 -1
View File
@@ -153,7 +153,7 @@ namespace RNS {
//inline const Cryptography::X25519PrivateKey::Ptr prv() const { assert(_object); return _object->_prv; }
inline const Cryptography::X25519PublicKey::Ptr pub() const { assert(_object); return _object->_pub; }
inline std::string toString() const { assert(_object); return "{Identity:" + _object->_hash.toHex() + "}"; }
inline std::string toString() const { if (!_object) return ""; return "{Identity:" + _object->_hash.toHex() + "}"; }
private:
class Object {
+20 -1
View File
@@ -8,6 +8,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) {
_object->_hash = Identity::full_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) {
_object->_hash = Identity::full_hash({toString()});
mem("Interface object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
/*virtual*/ inline void Interface::on_incoming(const Bytes& data) {
extreme("Interface::on_incoming: data: " + data.toHex());
assert(_object);
@@ -24,7 +34,9 @@ using namespace RNS::Type::Interface;
}
const Bytes Interface::get_hash() const {
return Identity::full_hash({toString()});
assert(_object);
//return Identity::full_hash({toString()});
return _object->_hash;
}
void Interface::process_announce_queue() {
@@ -74,14 +86,21 @@ void Interface::process_announce_queue() {
*/
}
/*
void ArduinoJson::convertFromJson(JsonVariantConst src, RNS::Interface& dst) {
RNS::extreme(">>> Deserializing Interface");
RNS::extreme(">>> Interface pre: " + dst.debugString());
if (!src.isNull()) {
RNS::Bytes hash;
hash.assignHex(src.as<const char*>());
RNS::extreme(">>> Querying Transport for Interface hash " + hash.toHex());
// Query transport for matching interface
dst = Transport::find_interface_from_hash(hash);
RNS::extreme(">>> Interface post: " + dst.debugString());
}
else {
dst = {RNS::Type::NONE};
RNS::extreme(">>> Interface post: " + dst.debugString());
}
}
*/
+58 -18
View File
@@ -4,6 +4,8 @@
#include "Bytes.h"
#include "Type.h"
#include <ArduinoJson.h>
#include <list>
#include <memory>
#include <stdint.h>
@@ -45,17 +47,14 @@ namespace RNS {
Interface(const Interface& interface) : _object(interface._object) {
mem("Interface object copy created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
Interface() : _object(new Object(*this)) {
mem("Interface object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
Interface(const char* name) : _object(new Object(*this, name)), _creator(true) {
mem("Interface object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
Interface();
Interface(const char* name);
virtual ~Interface() {
if (_creator) {
mem("Interface object clearing parent reference, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
// clear reference to parent in object foir safety
assert(_object);
_object->_parent = {Type::NONE};
_object->_parent = nullptr;
}
mem("Interface object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
}
@@ -63,26 +62,30 @@ namespace RNS {
inline Interface& operator = (const Interface& interface) {
_object = interface._object;
mem("Interface object copy created by assignment, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
if (_creator) {
mem("Interface object clearing creator flag, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
_creator = false;
}
return *this;
}
inline operator bool() const {
extreme("Interface object bool, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
mem("Interface object bool, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
return _object.get() != nullptr;
}
inline bool operator < (const Interface& interface) const {
extreme("Interface object <, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
mem("Interface object <, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
return _object.get() < interface._object.get();
}
inline bool operator > (const Interface& interface) const {
extreme("Interface object <, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
mem("Interface object <, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
return _object.get() > interface._object.get();
}
inline bool operator == (const Interface& interface) const {
extreme("Interface object ==, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
mem("Interface object ==, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
return _object.get() == interface._object.get();
}
inline bool operator != (const Interface& interface) const {
extreme("Interface object !=, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
mem("Interface object !=, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
return _object.get() != interface._object.get();
}
@@ -130,25 +133,27 @@ namespace RNS {
inline bool is_local_shared_instance() const { assert(_object); return _object->_is_local_shared_instance; }
inline HInterface parent_interface() const { assert(_object); return _object->_parent_interface; }
virtual inline std::string toString() const { assert(_object); return "Interface[" + _object->_name + "]"; }
virtual inline std::string toString() const { if (!_object) return ""; return "Interface[" + _object->_name + "]"; }
#ifndef NDEBUG
inline std::string debugString() const {
std::string dump;
dump = "Interface object, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get());
return dump;
}
#endif
private:
class Object {
public:
Object(Interface& parent) : _parent(parent) { mem("Interface::Data object created, this: " + std::to_string((uintptr_t)this)); }
Object(Interface& parent, const char* name) : _parent(parent), _name(name) { mem("Interface::Data object created, this: " + std::to_string((uintptr_t)this)); }
Object(Interface* parent) : _parent(parent) { mem("Interface::Data object created, this: " + std::to_string((uintptr_t)this)); }
Object(Interface* parent, const char* name) : _parent(parent), _name(name) { mem("Interface::Data object created, this: " + std::to_string((uintptr_t)this)); }
virtual ~Object() { mem("Interface::Data object destroyed, this: " + std::to_string((uintptr_t)this)); }
private:
//virtual inline void process_incoming(const Bytes& data) { if (_parent) { _parent.on_incoming(data); } }
virtual inline void process_outgoing(const Bytes& data) { if (_parent) { _parent.on_outgoing(data); } }
//virtual inline void process_incoming(const Bytes& data) { if (_parent != nullptr) { _parent->on_incoming(data); } }
virtual inline void process_outgoing(const Bytes& data) { if (_parent != nullptr) { _parent->on_outgoing(data); } }
private:
Interface& _parent;
Interface* _parent = nullptr;
bool _IN = false;
bool _OUT = false;
bool _FWD = false;
@@ -165,6 +170,7 @@ namespace RNS {
std::list<AnnounceEntry> _announce_queue;
bool _is_connected_to_shared_instance = false;
bool _is_local_shared_instance = false;
Bytes _hash;
HInterface _parent_interface;
//Transport& _owner;
friend class Interface;
@@ -177,11 +183,14 @@ namespace RNS {
}
/*
namespace ArduinoJson {
inline bool convertToJson(const RNS::Interface& src, JsonVariant dst) {
RNS::extreme("<<< Serializing Interface");
if (!src) {
return dst.set(nullptr);
}
RNS::extreme("<<< Interface hash " + src.get_hash().toHex());
return dst.set(src.get_hash().toHex());
}
void convertFromJson(JsonVariantConst src, RNS::Interface& dst);
@@ -189,3 +198,34 @@ namespace ArduinoJson {
return src.is<const char*>() && strlen(src.as<const char*>()) == 64;
}
}
*/
/*
namespace ArduinoJson {
template <>
struct Converter<RNS::Interface> {
static bool toJson(const RNS::Interface& src, JsonVariant dst) {
if (!src) {
return dst.set(nullptr);
}
RNS::extreme("<<< Serializing interface hash " + src.get_hash().toHex());
return dst.set(src.get_hash().toHex());
}
static RNS::Interface fromJson(JsonVariantConst src) {
if (!src.isNull()) {
RNS::Bytes hash;
hash.assignHex(src.as<const char*>());
RNS::extreme(">>> Deserialized interface hash " + hash.toHex());
RNS::extreme(">>> Querying transport for interface");
// Query transport for matching interface
return RNS::Interface::find_interface_from_hash(hash);
}
else {
return {RNS::Type::NONE};
}
}
static bool checkJson(JsonVariantConst src) {
return src.is<const char*>() && strlen(src.as<const char*>()) == 64;
}
};
}
*/
+11
View File
@@ -83,6 +83,11 @@ void LoRaInterface::loop() {
Serial.println(available);
extreme("LoRaInterface: receiving bytes...");
// read header (for detecting split packets)
uint8_t header = LoRa.read();
// CBA TODO add support for split packets
// read packet
buffer.clear();
while (LoRa.available()) {
@@ -113,6 +118,12 @@ Serial.println(available);
LoRa.beginPacket(); // start packet
// write header (for detecting split packets)
uint8_t header = Cryptography::randomnum(256) & 0xF0;
LoRa.write(header);
// CBA TODO add support for split packets
// add payload
//LoRa.print((const char*)data.data());
for (size_t i = 0; i < data.size(); ++i) {
+2 -1
View File
@@ -52,7 +52,8 @@ namespace RNS {
inline const Bytes& hash() const { assert(_object); return _object->_hash; }
inline Type::Link::status status() const { assert(_object); return _object->_status; }
inline std::string toString() const { assert(_object); return "{Link: unknown}"; }
inline std::string toString() const { if (!_object) return "";
return "{Link: unknown}"; }
private:
class Object {
+10 -9
View File
@@ -9,15 +9,16 @@
namespace RNS {
enum LogLevel {
LOG_CRITICAL = 0,
LOG_ERROR = 1,
LOG_WARNING = 2,
LOG_NOTICE = 3,
LOG_INFO = 4,
LOG_VERBOSE = 5,
LOG_DEBUG = 6,
LOG_EXTREME = 7,
LOG_MEM = 8,
LOG_NONE = 0,
LOG_CRITICAL = 1,
LOG_ERROR = 2,
LOG_WARNING = 3,
LOG_NOTICE = 4,
LOG_INFO = 5,
LOG_VERBOSE = 6,
LOG_DEBUG = 7,
LOG_EXTREME = 8,
LOG_MEM = 9
};
void loglevel(LogLevel level);
+7
View File
@@ -496,7 +496,11 @@ const Bytes Packet::get_hashable_part() const {
//}
#ifndef NDEBUG
std::string Packet::debugString() const {
if (!_object) {
return "";
}
if (_object->_packed) {
//unpack();
}
@@ -534,6 +538,7 @@ std::string Packet::debugString() const {
dump += "--------------------\n";
return dump;
}
#endif
void PacketReceipt::check_timeout() {
assert(_object);
@@ -555,6 +560,7 @@ void PacketReceipt::check_timeout() {
}
}
/*
void ArduinoJson::convertFromJson(JsonVariantConst src, RNS::Packet& dst) {
if (!src.isNull()) {
RNS::Bytes hash;
@@ -566,3 +572,4 @@ void ArduinoJson::convertFromJson(JsonVariantConst src, RNS::Packet& dst) {
dst = {RNS::Type::NONE};
}
}
*/
+37 -1
View File
@@ -3,6 +3,7 @@
#include "Destination.h"
#include "Link.h"
#include "Interface.h"
#include "Bytes.h"
#include "Log.h"
#include "Type.h"
#include "Utilities/OS.h"
@@ -222,9 +223,11 @@ namespace RNS {
inline const Bytes& raw() const { assert(_object); return _object->_raw; }
inline const Bytes& data() const { assert(_object); return _object->_data; }
inline std::string toString() const { assert(_object); return "{Packet:" + _object->_packet_hash.toHex() + "}"; }
inline std::string toString() const { if (!_object) return ""; return "{Packet:" + _object->_packet_hash.toHex() + "}"; }
#ifndef NDEBUG
std::string debugString() const;
#endif
private:
class Object {
@@ -271,10 +274,12 @@ namespace RNS {
friend class Packet;
};
std::shared_ptr<Object> _object;
};
}
/*
namespace ArduinoJson {
inline bool convertToJson(const RNS::Packet& src, JsonVariant dst) {
if (!src) {
@@ -287,3 +292,34 @@ namespace ArduinoJson {
return src.is<const char*>() && strlen(src.as<const char*>()) == 64;
}
}
*/
/*
namespace ArduinoJson {
template <>
struct Converter<RNS::Packet> {
static bool toJson(const RNS::Packet& src, JsonVariant dst) {
if (!src) {
return dst.set(nullptr);
}
RNS::extreme("<<< Serializing packet hash " + src.get_hash().toHex());
return dst.set(src.get_hash().toHex());
}
static RNS::Packet fromJson(JsonVariantConst src) {
if (!src.isNull()) {
RNS::Bytes hash;
hash.assignHex(src.as<const char*>());
RNS::extreme(">>> Deserialized packet hash " + hash.toHex());
RNS::extreme(">>> Querying transport for cached packet");
// Query transport for matching interface
return RNS::Packet::get_cached_packet(hash);
}
else {
return {RNS::Type::NONE};
}
}
static bool checkJson(JsonVariantConst src) {
return src.is<const char*>() && strlen(src.as<const char*>()) == 64;
}
};
}
*/
+12 -7
View File
@@ -14,7 +14,8 @@
using namespace RNS;
using namespace RNS::Type::Reticulum;
/*static*/ std::string Reticulum::storagepath;
/*static*/ std::string Reticulum::_storagepath;
/*static*/ std::string Reticulum::_cachepath;
/*static*/ bool Reticulum::__transport_enabled = false;
/*static*/ bool Reticulum::__use_implicit_proof = true;
@@ -40,9 +41,6 @@ Reticulum::Reticulum() : _object(new Object()) {
// Initialkize random number generator
RNG.begin("Reticulum");
// CBA TEST Transport
__transport_enabled = true;
Utilities::OS::setup();
#ifdef ARDUINO
@@ -81,9 +79,11 @@ Reticulum::Reticulum() : _object(new Object()) {
*/
// CBA MOCK
#ifdef ARDUINO
storagepath = "";
_storagepath = "";
_cachepath = "";
#else
storagepath = ".";
_storagepath = ".";
_cachepath = ".";
#endif
/* TODO
@@ -148,7 +148,8 @@ Reticulum::Reticulum() : _object(new Object()) {
RNS.Identity.load_known_destinations()
*/
Transport::start(*this);
// CBA Moved to start() so Transport is not started until after interfaces are setup
//Transport::start(*this);
/*
self.rpc_addr = ("127.0.0.1", self.local_control_port)
@@ -169,6 +170,10 @@ Reticulum::Reticulum() : _object(new Object()) {
}
void Reticulum::start() {
Transport::start(*this);
}
void Reticulum::loop() {
assert(_object);
if (!_object->_is_connected_to_shared_instance) {
+4 -2
View File
@@ -23,8 +23,9 @@ namespace RNS {
//z configdir = None
//z configpath = ""
//p storagepath = ""
static std::string storagepath;
//z cachepath = ""
static std::string _storagepath;
//p cachepath = ""
static std::string _cachepath;
static bool __transport_enabled;
static bool __use_implicit_proof;
@@ -56,6 +57,7 @@ namespace RNS {
}
public:
void start();
void loop();
/*
+222 -45
View File
@@ -1,45 +1,50 @@
//#include <unity.h>
#include "Transport.h"
#include "Interfaces/LoRaInterface.h"
#include "Utilities/Persistence.h"
#include "Utilities/OS.h"
#include "Log.h"
#include "Bytes.h"
#include "Interfaces/LoRaInterface.h"
#include "Utilities/OS.h"
#include <ArduinoJson.h>
#include "Utilities/Persistence.h"
//#include <ArduinoJson.h>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <assert.h>
#include <stdio.h>
class Test {
class TestObject {
public:
Test() {}
Test(const char* foo, const char* fee) : _foo(foo), _fee(fee) {}
const std::string toString() { return std::string("Test(") + _foo + "," + _fee + ")"; }
std::string _foo;
std::string _fee;
TestObject() {}
TestObject(const char* str, std::vector<std::string>& vec) : _str(str), _vec(vec) {}
inline bool operator < (const TestObject& test) const { return _str < test._str; }
inline const std::string toString() const { return std::string("TestObject(") + _str + "," + std::to_string(_vec.size()) + ")"; }
std::string _str;
std::vector<std::string> _vec;
};
namespace ArduinoJson {
// ArduinoJSON serialization support for TestObject
template <>
struct Converter<Test> {
static bool toJson(const Test& src, JsonVariant dst) {
dst["foo"] = src._foo;
dst["fee"] = src._fee;
struct Converter<TestObject> {
static bool toJson(const TestObject& src, JsonVariant dst) {
dst["str"] = src._str;
dst["vec"] = src._vec;
return true;
}
static Test fromJson(JsonVariantConst src) {
return Test(src["foo"], src["fee"]);
static TestObject fromJson(JsonVariantConst src) {
TestObject dst;
dst._str = src["str"].as<std::string>();
dst._vec = src["vec"].as<std::vector<std::string>>();
return dst;
}
static bool checkJson(JsonVariantConst src) {
return src["foo"].is<std::string>() && src["fee"].is<std::string>();
return src["str"].is<std::string>() && src["vec"].is<std::vector<std::string>>();
}
};
}
@@ -85,18 +90,18 @@ const char test_object_path[] = "/test_object";
const char test_object_path[] = "test_object";
#endif
/*
void testSerializeObject() {
Test test("bar", "fum");
StaticJsonDocument<1024> doc;
doc["foo"] = test._foo;
doc["fee"] = test._fee;
doc = test;
RNS::Bytes data;
size_t size = 1024;
//size_t length = serializeJson(doc, data.writable(size), size);
size_t length = serializeMsgPack(doc, data.writable(size), size);
size_t length = serializeJson(doc, data.writable(size), size);
//size_t length = serializeMsgPack(doc, data.writable(size), size);
if (length < size) {
data.resize(length);
}
@@ -126,8 +131,8 @@ void testDeserializeObject() {
if (data) {
RNS::extreme("read: " + std::to_string(data.size()) + " bytes");
//RNS::extreme("data: " + data.toString());
//DeserializationError error = deserializeJson(doc, data.data());
DeserializationError error = deserializeMsgPack(doc, data.data());
DeserializationError error = deserializeJson(doc, data.data());
//DeserializationError error = deserializeMsgPack(doc, data.data());
if (!error) {
JsonObject root = doc.as<JsonObject>();
for (JsonPair kv : root) {
@@ -146,6 +151,71 @@ void testDeserializeObject() {
}
}
*/
void testSerializeObject() {
std::vector<std::string> vec({"one", "two"});
TestObject test("test", vec);
RNS::extreme("serializeObject: test: " + test.toString());
StaticJsonDocument<1024> doc;
doc = test;
RNS::Bytes data;
size_t size = 1024;
size_t length = serializeJson(doc, data.writable(size), size);
//size_t length = serializeMsgPack(doc, data.writable(size), size);
if (length < size) {
data.resize(length);
}
RNS::extreme("serialized " + std::to_string(length) + " bytes");
if (length > 0) {
if (RNS::Utilities::OS::write_file(data, test_object_path)) {
RNS::extreme("wrote: " + std::to_string(data.size()) + " bytes");
}
else {
RNS::extreme("write failed");
assert(false);
}
}
else {
RNS::extreme("failed to serialize");
assert(false);
}
}
void testDeserializeObject() {
//StaticJsonDocument<8192> doc;
DynamicJsonDocument doc(8192);
RNS::Bytes data = RNS::Utilities::OS::read_file(test_object_path);
if (data) {
RNS::extreme("read: " + std::to_string(data.size()) + " bytes");
//RNS::extreme("data: " + data.toString());
DeserializationError error = deserializeJson(doc, data.data());
//DeserializationError error = deserializeMsgPack(doc, data.data());
if (!error) {
//JsonObject root = doc.as<JsonObject>();
//for (JsonPair kv : root) {
// RNS::extreme("key: " + std::string(kv.key().c_str()) + " value: " + kv.value().as<const char*>());
//}
TestObject test = doc.as<TestObject>();
RNS::extreme("testDeserializeObject: test: " + test.toString());
}
else {
RNS::extreme("failed to deserialize");
assert(false);
}
//assert(RNS::Utilities::OS::remove_file(test_object_path));
}
else {
RNS::extreme("read failed");
assert(false);
}
}
#ifdef ARDUINO
@@ -156,12 +226,12 @@ const char test_vector_path[] = "test_vector";
void testSerializeVector() {
//std::vector<std::string> vector;
//vector.push_back("foo");
//vector.push_back("bar");
std::vector<Test> vector;
vector.push_back({"bar1", "fum1"});
vector.push_back({"bar2", "fum2"});
std::vector<std::string> tvec;
tvec.push_back("foo");
tvec.push_back("bar");
std::vector<TestObject> vector;
vector.push_back({"two", tvec});
vector.push_back({"one", tvec});
StaticJsonDocument<4096> doc;
//copyArray(vector, doc.createNestedArray("vector"));
@@ -169,6 +239,9 @@ void testSerializeVector() {
//copyArray(vector, doc);
doc = vector;
//JsonVariant dst;
//dst = vector;
/*
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
@@ -230,14 +303,14 @@ void testDeserializeVector() {
if (!error) {
RNS::extreme("testDeserializeVector: successfully deserialized");
std::vector<Test> vector = doc.as<std::vector<Test>>();
std::vector<TestObject> vector = doc.as<std::vector<TestObject>>();
for (auto& test : vector) {
RNS::extreme("testDeserializeVector: entry: " + test.toString());
}
//JsonArray arr = doc.as<JsonArray>();
//for (JsonVariant elem : arr) {
// RNS::extreme("testDeserializeVector: entry: " + elem.as<Test>().toString());
// RNS::extreme("testDeserializeVector: entry: " + elem.as<TestObject>().toString());
//}
}
else {
@@ -254,6 +327,103 @@ void testDeserializeVector() {
}
#ifdef ARDUINO
const char test_set_path[] = "/test_set";
#else
const char test_set_path[] = "test_set";
#endif
void testSerializeSet() {
std::vector<std::string> tvec;
tvec.push_back("foo");
tvec.push_back("bar");
std::set<TestObject> set;
set.insert({"two", tvec});
set.insert({"one", tvec});
StaticJsonDocument<4096> doc;
//copyArray(set, doc.createNestedArray("set"));
//doc["set"] = set;
//copyArray(set, doc);
//doc = set;
//std::string test;
//RNS::Bytes test;
//std::set<int> test;
std::set<RNS::Bytes> test;
//std::map<std::string, std::string> test;
JsonVariant dst;
dst["test"] = test;
RNS::Bytes data;
size_t size = 4096;
size_t length = serializeJson(doc, data.writable(size), size);
//size_t length = serializeMsgPack(doc, data.writable(size), size);
if (length < size) {
data.resize(length);
}
RNS::extreme("testSerializeSet: serialized " + std::to_string(length) + " bytes");
if (length > 0) {
if (RNS::Utilities::OS::write_file(data, test_set_path)) {
RNS::extreme("testSerializeSet: wrote: " + std::to_string(data.size()) + " bytes");
}
else {
RNS::extreme("testSerializeSet: write failed");
assert(false);
}
}
else {
RNS::extreme("testSerializeSet: failed to serialize");
assert(false);
}
}
void testDeserializeSet() {
// Compute the required size
const int capacity =
JSON_ARRAY_SIZE(2) +
2*JSON_OBJECT_SIZE(3) +
4*JSON_OBJECT_SIZE(1);
//StaticJsonDocument<8192> doc;
DynamicJsonDocument doc(8192);
RNS::Bytes data = RNS::Utilities::OS::read_file(test_set_path);
if (data) {
RNS::extreme("testDeserializeSet: read: " + std::to_string(data.size()) + " bytes");
//RNS::extreme("testDeserializeSet: data: " + data.toString());
DeserializationError error = deserializeJson(doc, data.data());
//DeserializationError error = deserializeMsgPack(doc, data.data());
if (!error) {
RNS::extreme("testDeserializeSet: successfully deserialized");
std::set<TestObject> set = doc.as<std::set<TestObject>>();
for (auto& test : set) {
RNS::extreme("testDeserializeSet: entry: " + test.toString());
}
//JsonArray arr = doc.as<JsonArray>();
//for (JsonVariant elem : arr) {
// RNS::extreme("testDeserializeSet: entry: " + elem.as<TestObject>().toString());
//}
}
else {
RNS::extreme("testDeserializeSet: failed to deserialize");
assert(false);
}
//assert(RNS::Utilities::OS::remove_file(test_set_path));
}
else {
RNS::extreme("testDeserializeSet: read failed");
assert(false);
}
}
#ifdef ARDUINO
const char test_map_path[] = "/test_map";
#else
@@ -262,12 +432,12 @@ const char test_map_path[] = "test_map";
void testSerializeMap() {
//std::map<std::string, std::string> map;
//map.insert({"foo", "bar"});
//map.insert({"fee", "fum"});
std::map<std::string, Test> map;
map.insert({"one", {"bar1", "fum1"}});
map.insert({"two", {"bar2", "fum2"}});
std::vector<std::string> tvec;
tvec.push_back("foo");
tvec.push_back("bar");
std::map<std::string, TestObject> map;
map.insert({"two", {"two", tvec}});
map.insert({"one", {"one", tvec}});
StaticJsonDocument<4096> doc;
//copyArray(map, doc.createNestedArray("map"));
@@ -319,14 +489,14 @@ void testDeserializeMap() {
if (!error) {
RNS::extreme("testDeserializeMap: successfully deserialized");
std::map<std::string, Test> map(doc.as<std::map<std::string, Test>>());
std::map<std::string, TestObject> map(doc.as<std::map<std::string, TestObject>>());
for (auto& [str, test] : map) {
RNS::extreme("testDeserializeMap: entry: " + str + " = " + test.toString());
}
//JsonObject root = doc.as<JsonObject>();
//for (JsonPair kv : root) {
// RNS::extreme("testDeserializeMap: entry: " + std::string(kv.key().c_str()) + " = " + kv.value().as<Test>().toString());
// RNS::extreme("testDeserializeMap: entry: " + std::string(kv.key().c_str()) + " = " + kv.value().as<TestObject>().toString());
//}
}
else {
@@ -336,7 +506,7 @@ void testDeserializeMap() {
//assert(RNS::Utilities::OS::remove_file(test_map_path));
}
else {
RNS::extreme("testDeserializeMap: testDeserializeVector: read failed");
RNS::extreme("testDeserializeMap: read failed");
assert(false);
}
@@ -360,10 +530,14 @@ void testSerializeDestinationTable() {
//RNS::Transport::DestinationEntry entry_one(1.0, empty, 1, 0.0, blobs, interface, packet);
RNS::Bytes received;
received.assignHex("deadbeef");
RNS::Bytes blob;
blob.assignHex("b10bb10b");
std::set<RNS::Bytes> blobs({received, blob});
RNS::Transport::DestinationEntry entry_one;
entry_one._timestamp = 1.0;
entry_one._received_from = received;
entry_one._receiving_interface = lora_interface;
entry_one._random_blobs = blobs;
RNS::Bytes one;
one.assignHex("1111111111111111");
map.insert({one, entry_one});
@@ -372,12 +546,13 @@ void testSerializeDestinationTable() {
entry_two._timestamp = 2.0;
entry_two._received_from = received;
entry_two._receiving_interface = lora_interface;
entry_two._random_blobs = blobs;
RNS::Bytes two;
two.assignHex("2222222222222222");
map.insert({two, entry_two});
for (auto& [hash, test] : map) {
RNS::extreme("testSerializeDestinationTable: entry: " + hash.toHex() + " = (" + std::to_string(test._timestamp) + "," + test._received_from.toHex() + ")");
RNS::extreme("testSerializeDestinationTable: entry: " + hash.toHex() + " = " + test.debugString());
}
StaticJsonDocument<4096> doc;
@@ -429,12 +604,12 @@ void testDeserializeDestinationTable() {
static std::map<RNS::Bytes, RNS::Transport::DestinationEntry> map(doc.as<std::map<RNS::Bytes, RNS::Transport::DestinationEntry>>());
for (auto& [hash, test] : map) {
RNS::extreme("testDeserializeDestinationTable: entry: " + hash.toHex() + " = (" + std::to_string(test._timestamp) + "," + test._received_from.toHex() + ")");
RNS::extreme("testDeserializeDestinationTable: entry: " + hash.toHex() + " = " + test.debugString());
}
//JsonObject root = doc.as<JsonObject>();
//for (JsonPair kv : root) {
// RNS::extreme("testDeserializeDestinationTable: entry: " + std::string(kv.key().c_str()) + " = " + kv.value().as<Test>().toString());
// RNS::extreme("testDeserializeDestinationTable: entry: " + std::string(kv.key().c_str()) + " = " + kv.value().as<TestObject>().toString());
//}
}
else {
@@ -459,6 +634,8 @@ void testPersistence() {
testDeserializeObject();
testSerializeVector();
testDeserializeVector();
testSerializeSet();
testDeserializeSet();
testSerializeMap();
testDeserializeMap();
testSerializeDestinationTable();
+207 -104
View File
@@ -8,6 +8,7 @@
#include "Log.h"
#include "Cryptography/Random.h"
#include "Utilities/OS.h"
#include "Utilities/Persistence.h"
#include <algorithm>
#include <unistd.h>
@@ -60,17 +61,22 @@ using namespace RNS::Utilities;
/*static*/ double Transport::_start_time = 0;
/*static*/ bool Transport::_jobs_locked = false;
/*static*/ bool Transport::_jobs_running = false;
/*static*/ uint32_t Transport::_job_interval = 0.250;
/*static*/ float Transport::_job_interval = 0.250;
/*static*/ double Transport::_jobs_last_run = 0;
/*static*/ double Transport::_links_last_checked = 0;
/*static*/ uint32_t Transport::_links_check_interval = 1.0;
/*static*/ float Transport::_links_check_interval = 1.0;
/*static*/ double Transport::_receipts_last_checked = 0;
/*static*/ uint32_t Transport::_receipts_check_interval = 1.0;
/*static*/ float Transport::_receipts_check_interval = 1.0;
/*static*/ double Transport::_announces_last_checked = 0;
/*static*/ uint32_t Transport::_announces_check_interval= 1.0;
/*static*/ uint32_t Transport::_hashlist_maxsize = 1000000;
/*static*/ float Transport::_announces_check_interval= 1.0;
/*static*/ double Transport::_tables_last_culled = 0;
/*static*/ uint32_t Transport::_tables_cull_interval = 5.0;
/*static*/ float Transport::_tables_cull_interval = 5.0;
/*static*/ bool Transport::_saving_path_table = false;
/*static*/ uint32_t Transport::_hashlist_maxsize = 1000000;
// CBA
/*static*/ double Transport::_last_saved = 0;
/*static*/ float Transport::_save_interval = 3600;
/*static*/ Reticulum Transport::_owner({Type::NONE});
/*static*/ Identity Transport::_identity({Type::NONE});
@@ -81,7 +87,7 @@ using namespace RNS::Utilities;
_owner = reticulum_instance;
if (!_identity) {
std::string transport_identity_path = Reticulum::storagepath + "/transport_identity";
std::string transport_identity_path = Reticulum::_storagepath + "/transport_identity";
// CBA TEST
//OS::remove_file(transport_identity_path.c_str());
if (OS::file_exists(transport_identity_path.c_str())) {
@@ -134,12 +140,11 @@ using namespace RNS::Utilities;
//p thread = threading.Thread(target=Transport.jobloop, daemon=True)
//p thread.start()
// TODO
/*
if RNS.Reticulum.transport_enabled():
if (Reticulum::transport_enabled()) {
destination_table_path = RNS.Reticulum.storagepath+"/destination_table"
if os.path.isfile(destination_table_path) and not Transport.owner.is_connected_to_shared_instance:
std::string destination_table_path = Reticulum::_storagepath + "/destination_table";
if (!_owner.is_connected_to_shared_instance() && OS::file_exists(destination_table_path.c_str())) {
/*p
serialised_destinations = []
try:
file = open(destination_table_path, "rb")
@@ -173,17 +178,44 @@ using namespace RNS::Utilities;
RNS.log("The announce packet could not be loaded from cache", RNS.LOG_DEBUG)
if receiving_interface == None:
RNS.log("The interface is no longer available", RNS.LOG_DEBUG)
*/
if len(Transport.destination_table) == 1:
specifier = "entry"
else:
specifier = "entries"
try {
//StaticJsonDocument<1024> doc;
DynamicJsonDocument doc(1024);
RNS.log("Loaded "+str(len(Transport.destination_table))+" path table "+specifier+" from storage", RNS.LOG_VERBOSE)
RNS::Bytes data = RNS::Utilities::OS::read_file(destination_table_path.c_str());
if (data) {
RNS::extreme("Transport::start: read: " + std::to_string(data.size()) + " bytes");
//RNS::extreme("testDeserializeVector: data: " + data.toString());
DeserializationError error = deserializeJson(doc, data.data());
//DeserializationError error = deserializeMsgPack(doc, data.data());
if (!error) {
_destination_table = doc.as<std::map<Bytes, DestinationEntry>>();
RNS::extreme("Transport::start: successfully deserialized");
#ifndef NDEBUG
for (auto& [hash, entry] : _destination_table) {
RNS::extreme("Transport::start: entry: " + hash.toHex() + " = " + entry.debugString());
}
#endif
}
else {
RNS::extreme("Transport::start: failed to deserialize");
}
}
else {
RNS::extreme("Transport::start: read failed");
}
verbose("Loaded " + std::to_string(_destination_table.size()) + " path table entries from storage");
except Exception as e:
RNS.log("Could not load destination table from storage, the contained exception was: "+str(e), RNS.LOG_ERROR)
}
catch (std::exception& e) {
error("Could not load destination table from storage, the contained exception was: " + std::string(e.what()));
}
}
// TODO
/*
tunnel_table_path = RNS.Reticulum.storagepath+"/tunnels"
if os.path.isfile(tunnel_table_path) and not Transport.owner.is_connected_to_shared_instance:
serialised_tunnels = []
@@ -241,10 +273,14 @@ using namespace RNS::Utilities;
RNS.log("Transport Instance will respond to probe requests on "+str(Transport.probe_destination), RNS.LOG_NOTICE)
else:
Transport.probe_destination = None
*/
RNS.log("Transport instance "+str(Transport.identity)+" started", RNS.LOG_VERBOSE)
Transport.start_time = time.time()
verbose("Transport instance " + _identity.toString() + " started");
_start_time = OS::time();
}
// TODO
/*
// Synthesize tunnels for any interfaces wanting it
for interface in Transport.interfaces:
interface.tunnel_id = None
@@ -628,6 +664,12 @@ using namespace RNS::Utilities;
Transport.tables_last_culled = time.time()
*/
// Periodically persist data
if (OS::time() > (_last_saved + _save_interval)) {
persist_data();
_last_saved = OS::time();
}
}
else {
// Transport jobs were locked, do nothing
@@ -2053,7 +2095,7 @@ using namespace RNS::Utilities;
}
}
else {
debug("Transport::inbound: Packet destination " + packet.destination_hash().toHex() + " not found, ignoring");
debug("Transport::inbound: Packet destination " + packet.destination_hash().toHex() + " not found, not handling locally");
}
}
}
@@ -2259,7 +2301,7 @@ using namespace RNS::Utilities;
}
/*static*/ void Transport::register_interface(Interface& interface) {
extreme("Transport: Registering interface " + interface.toString());
extreme("Transport: Registering interface " + interface.get_hash().toHex() + " " + interface.toString());
#if defined(INTERFACES_SET)
_interfaces.insert(interface);
#elif defined(INTERFACES_LIST)
@@ -2335,7 +2377,7 @@ using namespace RNS::Utilities;
}
}
else {
extreme("Transport:register_destination: Skipping registraion (not direction IN) of destination " + destination.toString());
extreme("Transport:register_destination: Skipping registration (not direction IN) of destination " + destination.toString());
}
/*
@@ -2461,36 +2503,42 @@ Deregisters an announce handler.
// means that they have not had their hop count
// increased yet! Take note of this when reading from
// the packet cache.
/*static*/ void Transport::cache(const Packet& packet, bool force_cache /*= false*/) {
// TODO
/*
/*static*/ bool Transport::cache(const Packet& packet, bool force_cache /*= false*/) {
extreme("Conditionally saving packet " + packet.get_hash().toHex() + " to storage");
if (should_cache(packet) || force_cache) {
extreme("Saving packet " + packet.get_hash().toHex() + " to storage");
try {
//packet_hash = RNS.hexrep(packet.get_hash(), delimit=False)
Bytes packet_hash = packet.get_hash().toHex();
//interface_reference = None
std::string interface_reference;
if (packet.receiving_interface()) {
interface_reference = packet.receiving_interface().toString();
}
/*p
packet_hash = RNS.hexrep(packet.get_hash(), delimit=False)
interface_reference = None
if packet.receiving_interface != None:
interface_reference = str(packet.receiving_interface)
file = open(RNS.Reticulum.cachepath+"/"+packet_hash, "wb")
file.write(umsgpack.packb([packet.raw, interface_reference]))
file.close()
*/
std::string packet_cache_path = Reticulum::_cachepath + "/" + packet.get_hash().toHex();
// CBA remporarily disabled until CachedPacket is implemented
/*
DynamicJsonDocument doc(1024);
doc.set(packet);
return Persistence::serialize(doc, packet_cache_path.c_str(), 1024);
*/
return Persistence::serialize(packet, packet_cache_path.c_str(), 1024);
}
catch (std::exception& e) {
error("Error writing packet to cache. The contained exception was: " + e.what());
error("Error writing packet to cache. The contained exception was: " + std::string(e.what()));
}
}
*/
return false;
}
/*static*/ Packet Transport::get_cached_packet(const Bytes& packet_hash) {
// TODO
/*
extreme("Loading packet " + packet_hash.toHex() + " to storage");
try {
//packet_hash = RNS.hexrep(packet_hash, delimit=False)
Bytes packet_hash = packet_hash.toHex();
/*p
packet_hash = RNS.hexrep(packet_hash, delimit=False)
path = RNS.Reticulum.cachepath+"/"+packet_hash
if os.path.isfile(path):
@@ -2508,13 +2556,25 @@ Deregisters an announce handler.
return packet
else:
return None
*/
std::string packet_cache_path = Reticulum::_cachepath + "/" + packet_hash.toHex();
// CBA remporarily disabled until CachedPacket is implemented since this results in recursive calls
// due to Packet deserializer calling get_cached_packet()
/*
DynamicJsonDocument doc(1024);
if (Persistence::deserialize(doc, packet_cache_path.c_str())) {
return doc.as<Packet>();
}
*/
//return Persistence::deserialize(packet_cache_path.c_str());
Packet packet({Type::NONE});
Persistence::deserialize(packet, packet_cache_path.c_str());
return packet;
}
catch (std::exception& e) {
error("Exception occurred while getting cached packet.");
error("The contained exception was: " + e.what());
error("The contained exception was: " + std::string(e.what()));
}
*/
// MOCK
return {Type::NONE};
}
@@ -3114,76 +3174,118 @@ will announce it.
*/
}
/*static*/ void Transport::save_path_table() {
// TODO
/*
if not Transport.owner.is_connected_to_shared_instance:
if hasattr(Transport, "saving_path_table"):
wait_interval = 0.2
wait_timeout = 5
wait_start = time.time()
while Transport.saving_path_table:
time.sleep(wait_interval)
if time.time() > wait_start+wait_timeout:
RNS.log("Could not save path table to storage, waiting for previous save operation timed out.", RNS.LOG_ERROR)
return False
/*static*/ bool Transport::save_path_table() {
debug("Transport::save_path_table");
try:
Transport.saving_path_table = True
save_start = time.time()
RNS.log("Saving path table to storage...", RNS.LOG_DEBUG)
if (Transport::_owner.is_connected_to_shared_instance()) {
return true;
}
serialised_destinations = []
for destination_hash in Transport.destination_table:
bool success = false;
if (_saving_path_table) {
double wait_interval = 0.2;
double wait_timeout = 5;
double wait_start = OS::time();
while (_saving_path_table) {
OS::sleep(wait_interval);
if (OS::time() > (wait_start + wait_timeout)) {
error("Could not save path table to storage, waiting for previous save operation timed out.");
return false;
}
}
}
try {
_saving_path_table = true;
double save_start = OS::time();
debug("Saving " + std::to_string(_destination_table.size()) + " path table entries to storage...");
/*p
serialised_destinations = []
for destination_hash in Transport.destination_table:
// Get the destination entry from the destination table
de = Transport.destination_table[destination_hash]
interface_hash = de[5].get_hash()
// Only store destination table entry if the associated
// interface is still active
interface = Transport.find_interface_from_hash(interface_hash)
if interface != None:
// Get the destination entry from the destination table
de = Transport.destination_table[destination_hash]
interface_hash = de[5].get_hash()
timestamp = de[0]
received_from = de[1]
hops = de[2]
expires = de[3]
random_blobs = de[4]
packet_hash = de[6].get_hash()
// Only store destination table entry if the associated
// interface is still active
interface = Transport.find_interface_from_hash(interface_hash)
if interface != None:
// Get the destination entry from the destination table
de = Transport.destination_table[destination_hash]
timestamp = de[0]
received_from = de[1]
hops = de[2]
expires = de[3]
random_blobs = de[4]
packet_hash = de[6].get_hash()
serialised_entry = [
destination_hash,
timestamp,
received_from,
hops,
expires,
random_blobs,
interface_hash,
packet_hash
]
serialised_entry = [
destination_hash,
timestamp,
received_from,
hops,
expires,
random_blobs,
interface_hash,
packet_hash
]
serialised_destinations.append(serialised_entry)
serialised_destinations.append(serialised_entry)
Transport.cache(de[6], force_cache=True)
Transport.cache(de[6], force_cache=True)
destination_table_path = RNS.Reticulum.storagepath+"/destination_table"
file = open(destination_table_path, "wb")
file.write(umsgpack.packb(serialised_destinations))
file.close()
save_time = time.time() - save_start
if save_time < 1:
time_str = str(round(save_time*1000,2))+"ms"
else:
time_str = str(round(save_time,2))+"s"
RNS.log("Saved "+str(len(serialised_destinations))+" path table entries in "+time_str, RNS.LOG_DEBUG)
except Exception as e:
RNS.log("Could not save path table to storage, the contained exception was: "+str(e), RNS.LOG_ERROR)
Transport.saving_path_table = False
destination_table_path = RNS.Reticulum.storagepath+"/destination_table"
file = open(destination_table_path, "wb")
file.write(umsgpack.packb(serialised_destinations))
file.close()
*/
std::string destination_table_path = Reticulum::_storagepath + "/destination_table";
//StaticJsonDocument<1024> doc;
//doc = _destination_table;
DynamicJsonDocument doc(1024);
doc.set(_destination_table);
RNS::Bytes data;
size_t size = 4096;
size_t length = serializeJson(doc, data.writable(size), size);
//size_t length = serializeMsgPack(doc, data.writable(size), size);
if (length < size) {
data.resize(length);
}
RNS::extreme("Transport::save_path_table: serialized " + std::to_string(length) + " bytes");
if (length > 0) {
if (RNS::Utilities::OS::write_file(data, destination_table_path.c_str())) {
RNS::extreme("Transport::save_path_table: wrote: " + std::to_string(data.size()) + " bytes");
}
else {
RNS::extreme("Transport::save_path_table: write failed");
}
}
else {
RNS::extreme("Transport::save_path_table: failed to serialize");
}
double save_time = OS::time() - save_start;
std::string time_str;
if (save_time < 1) {
time_str = std::to_string(OS::round(save_time * 1000, 2)) + "ms";
}
else {
time_str = std::to_string(OS::round(save_time, 2)) + "s";
}
debug("Saved " + std::to_string(_destination_table.size()) + " path table entries in " + time_str);
success = true;
}
catch (std::exception& e) {
error("Could not save path table to storage, the contained exception was: " + std::string(e.what()));
}
_saving_path_table = false;
return success;
}
/*static*/ void Transport::save_tunnel_table() {
@@ -3266,6 +3368,7 @@ will announce it.
}
/*static*/ void Transport::persist_data() {
extreme("Transport::persist_data()");
save_packet_hashlist();
save_path_table();
save_tunnel_table();
+38 -67
View File
@@ -4,13 +4,12 @@
#include "Bytes.h"
#include "Type.h"
#include <ArduinoJson.h>
#include <memory>
#include <map>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <array>
#include <memory>
#include <functional>
#include <stdint.h>
@@ -62,8 +61,8 @@ namespace RNS {
class DestinationEntry {
public:
DestinationEntry() {}
DestinationEntry(double time, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set<Bytes>& random_blobs, Interface& receiving_interface, const Packet& packet) :
_timestamp(time),
DestinationEntry(double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set<Bytes>& random_blobs, Interface& receiving_interface, const Packet& packet) :
_timestamp(timestamp),
_received_from(received_from),
_hops(announce_hops),
_expires(expires),
@@ -77,11 +76,29 @@ namespace RNS {
Bytes _received_from;
uint8_t _hops = 0;
double _expires = 0;
const std::set<Bytes> _random_blobs;
std::set<Bytes> _random_blobs;
// CBA TODO does this need to be a reference in order for virtual method callbacks to work?
Interface _receiving_interface = {Type::NONE};
//const Packet& _announce_packet;
const Packet _announce_packet = {Type::NONE};
Packet _announce_packet = {Type::NONE};
#ifndef NDEBUG
inline std::string debugString() const {
std::string dump;
dump = "DestinationEntry: timestamp=" + std::to_string(_timestamp) +
" received_from=" + _received_from.toHex() +
" hops=" + std::to_string(_hops) +
" expires=" + std::to_string(_expires) +
//" random_blobs=" + _random_blobs +
" receiving_interface=" + _receiving_interface.toString() +
" announce_packet=" + _announce_packet.toString();
dump += " random_blobs=(";
for (auto& blob : _random_blobs) {
dump += blob.toHex() + ",";
}
dump += ")";
return dump;
}
#endif
};
// CBA TODO Analyze safety of using Inrerface references here
@@ -208,7 +225,7 @@ namespace RNS {
static void deregister_announce_handler(HAnnounceHandler handler);
static Interface find_interface_from_hash(const Bytes& interface_hash);
static bool should_cache(const Packet& packet);
static void cache(const Packet& packet, bool force_cache = false);
static bool cache(const Packet& packet, bool force_cache = false);
static Packet get_cached_packet(const Bytes& packet_hash);
static bool cache_request_packet(const Packet& packet);
static void cache_request(const Bytes& packet_hash, const Destination& destination);
@@ -231,7 +248,7 @@ namespace RNS {
static void drop_announce_queues();
static bool announce_emitted(const Packet& packet);
static void save_packet_hashlist();
static void save_path_table();
static bool save_path_table();
static void save_tunnel_table();
static void persist_data();
static void exit_handler();
@@ -299,71 +316,25 @@ namespace RNS {
static double _start_time;
static bool _jobs_locked;
static bool _jobs_running;
static uint32_t _job_interval;
static float _job_interval;
static double _jobs_last_run;
static double _links_last_checked;
static uint32_t _links_check_interval;
static float _links_check_interval;
static double _receipts_last_checked;
static uint32_t _receipts_check_interval;
static float _receipts_check_interval;
static double _announces_last_checked;
static uint32_t _announces_check_interval;
static uint32_t _hashlist_maxsize;
static float _announces_check_interval;
static double _tables_last_culled;
static uint32_t _tables_cull_interval;
static float _tables_cull_interval;
static bool _saving_path_table;
static uint32_t _hashlist_maxsize;
// CBA
static double _last_saved;
static float _save_interval;
static Reticulum _owner;
static Identity _identity;
};
}
namespace ArduinoJson {
// ArduinoJSON serialization support for RNS::Transport::DestinationEntry
template <>
struct Converter<RNS::Transport::DestinationEntry> {
static bool toJson(const RNS::Transport::DestinationEntry& src, JsonVariant dst) {
dst["timestamp"] = src._timestamp;
dst["received_from"] = src._received_from;
dst["announce_hops"] = src._hops;
dst["expires"] = src._expires;
//dst["random_blobs"] = src._random_blobs;
dst["receiving_interface"] = src._receiving_interface;
dst["packet"] = src._announce_packet;
return true;
}
static RNS::Transport::DestinationEntry fromJson(JsonVariantConst src) {
/**/
RNS::Transport::DestinationEntry dst;
dst._timestamp = src["timestamp"];
dst._received_from = src["received_from"];
dst._hops = src["announce_hops"];
dst._expires = src["expires"];
//dst._random_blobs = src["random_blobs"];
dst._receiving_interface = src["receiving_interface"];
//dst._announce_packet = src["packet"];
/**/
/*
//RNS::Transport::DestinationEntry dst(src["timestamp"], src["received_from"], src["announce_hops"], src["expires"], src["random_blobs"], src["receiving_interface"], src["packet"]);
RNS::Transport::DestinationEntry dst(
src["timestamp"].as<double>(),
src["received_from"].as<RNS::Bytes>(),
src["announce_hops"].as<int>(),
src["expires"].as<double>(),
src["random_blobs"].as<std::set<RNS::Bytes>>(),
src["receiving_interface"].as<RNS::Interface>(),
src["packet"].as<RNS::Packet>()
);
*/
return dst;
}
static bool checkJson(JsonVariantConst src) {
return
src["timestamp"].is<double>() &&
src["received_from"].is<RNS::Bytes>() &&
src["announce_hops"].is<int>() &&
src["expires"].is<double>();
}
};
}
+43 -21
View File
@@ -4,7 +4,7 @@
#ifdef ARDUINO
#include <FS.h>
#include <LittleFS.h>
#include <SPIFFS.h>
#else
#include <stdio.h>
#include <sys/types.h>
@@ -15,27 +15,44 @@
using namespace RNS;
using namespace RNS::Utilities;
#ifdef ARDUINO
void listDir(char * dir){
Serial.print("DIR: ");
Serial.println(dir);
File root = SPIFFS.open(dir);
File file = root.openNextFile();
while(file){
Serial.print(" FILE: ");
Serial.println(file.name());
file = root.openNextFile();
}
}
#endif
/*static*/ void OS::setup() {
#ifdef ARDUINO
// Setup filesystem
if (!LittleFS.begin(true)){
Serial.println("LittleFS Mount Failed");
return;
}
if (!SPIFFS.begin(true, "")){
error("SPIFFS filesystem mount failed");
}
else {
listDir("/");
debug("SPIFFS filesystem is ready");
}
#endif
}
/*static*/ bool OS::file_exists(const char* file_path) {
#ifdef ARDUINO
File file = LittleFS.open(file_path, FILE_READ);
File file = SPIFFS.open(file_path, FILE_READ);
if (file) {
#else
FILE* file = fopen(file_path, "r");
if (file != nullptr) {
#endif
//RNS::extreme("file_exists: file exists, closing file");
//extreme("file_exists: file exists, closing file");
#ifdef ARDUINO
file.close();
#else
@@ -44,7 +61,7 @@ using namespace RNS::Utilities;
return true;
}
else {
RNS::extreme("file_exists: failed to open file " + std::string(file_path));
error("file_exists: failed to open file " + std::string(file_path));
return false;
}
}
@@ -52,7 +69,7 @@ using namespace RNS::Utilities;
/*static*/ const Bytes OS::read_file(const char* file_path) {
Bytes data;
#ifdef ARDUINO
File file = LittleFS.open(file_path, FILE_READ);
File file = SPIFFS.open(file_path, FILE_READ);
if (file) {
size_t size = file.size();
size_t read = file.readBytes((char*)data.writable(size), size);
@@ -65,12 +82,12 @@ using namespace RNS::Utilities;
//size_t read = fread(data.writable(size), size, 1, file);
size_t read = fread(data.writable(size), 1, size, file);
#endif
RNS::extreme("read_file: read " + std::to_string(read) + " bytes from file " + std::string(file_path));
extreme("read_file: read " + std::to_string(read) + " bytes from file " + std::string(file_path));
if (read != size) {
RNS::extreme("read_file: failed to read file " + std::string(file_path));
error("read_file: failed to read file " + std::string(file_path));
data.clear();
}
//RNS::extreme("read_file: closing input file");
//extreme("read_file: closing input file");
#ifdef ARDUINO
file.close();
#else
@@ -78,7 +95,7 @@ using namespace RNS::Utilities;
#endif
}
else {
RNS::extreme("read_file: failed to open input file " + std::string(file_path));
error("read_file: failed to open input file " + std::string(file_path));
}
return data;
}
@@ -86,7 +103,7 @@ using namespace RNS::Utilities;
/*static*/ bool OS::write_file(const Bytes& data, const char* file_path) {
bool success = false;
#ifdef ARDUINO
File file = LittleFS.open(file_path, FILE_WRITE);
File file = SPIFFS.open(file_path, FILE_WRITE);
if (file) {
size_t wrote = file.write(data.data(), data.size());
#else
@@ -95,14 +112,14 @@ using namespace RNS::Utilities;
//size_t wrote = fwrite(data.data(), data.size(), 1, file);
size_t wrote = fwrite(data.data(), 1, data.size(), file);
#endif
RNS::extreme("write_file: wrote " + std::to_string(wrote) + " bytes to file " + std::string(file_path));
extreme("write_file: wrote " + std::to_string(wrote) + " bytes to file " + std::string(file_path));
if (wrote == data.size()) {
success = true;
}
else {
RNS::extreme("write_file: failed to write file " + std::string(file_path));
error("write_file: failed to write file " + std::string(file_path));
}
//RNS::extreme("write_file: closing output file");
//extreme("write_file: closing output file");
#ifdef ARDUINO
file.close();
#else
@@ -110,14 +127,14 @@ using namespace RNS::Utilities;
#endif
}
else {
RNS::extreme("write_file: failed to open output file " + std::string(file_path));
error("write_file: failed to open output file " + std::string(file_path));
}
return success;
}
/*static*/ bool OS::remove_file(const char* file_path) {
#ifdef ARDUINO
return LittleFS.remove(file_path);
return SPIFFS.remove(file_path);
#else
return (remove(file_path) == 0);
#endif
@@ -125,7 +142,7 @@ using namespace RNS::Utilities;
/*static*/ bool OS::rename_file(const char* from_file_path, const char* to_file_path) {
#ifdef ARDUINO
return LittleFS.rename(from_file_path, to_file_path);
return SPIFFS.rename(from_file_path, to_file_path);
#else
return (rename(from_file_path, to_file_path) == 0);
#endif
@@ -133,7 +150,12 @@ using namespace RNS::Utilities;
/*static*/ bool OS::create_directory(const char* directory_path) {
#ifdef ARDUINO
return LittleFS.mkdir(directory_path);
if (SPIFFS.mkdir(directory_path)) {
return true;
}
else {
error("create_directory: failed to create directorty " + std::string(directory_path));
}
#else
struct stat st = {0};
if (stat(directory_path, &st) == 0) {
+1 -1
View File
@@ -9,7 +9,7 @@
#include <sys/time.h>
#ifdef ARDUINO
#include "Arduino.h"
#include <Arduino.h>
#endif
namespace RNS { namespace Utilities {
+278 -20
View File
@@ -1,78 +1,105 @@
#pragma once
#include "Bytes.h"
// CBA NOTE If headers for classes referenced in this file are not included here,
// then they MUST be included BEFORE this header is included.
#include "Transport.h"
#include <ArduinoJson.h>
#include <map>
#include <vector>
#include <set>
#include <string>
#include <ArduinoJson.h>
namespace ArduinoJson {
// ArduinoJSON serialization support for std::vector<T>
template <typename T>
struct Converter<std::vector<T> > {
struct Converter<std::vector<T>> {
static void toJson(const std::vector<T>& src, JsonVariant dst) {
JsonArray array = dst.to<JsonArray>();
for (T item : src)
array.add(item);
array.add(item);
}
static std::vector<T> fromJson(JsonVariantConst src) {
std::vector<T> dst;
for (T item : src.as<JsonArrayConst>())
dst.push_back(item);
dst.push_back(item);
return dst;
}
static bool checkJson(JsonVariantConst src) {
JsonArrayConst array = src;
bool result = array;
for (JsonVariantConst item : array)
result &= item.is<T>();
result &= item.is<T>();
return result;
}
};
// ArduinoJSON serialization support for std::set<T>
template <typename T>
struct Converter<std::set<T>> {
static void toJson(const std::set<T>& src, JsonVariant dst) {
JsonArray array = dst.to<JsonArray>();
for (T item : src)
array.add(item);
}
static std::set<T> fromJson(JsonVariantConst src) {
std::set<T> dst;
for (T item : src.as<JsonArrayConst>())
dst.insert(item);
return dst;
}
static bool checkJson(JsonVariantConst src) {
JsonArrayConst array = src;
bool result = array;
for (JsonVariantConst item : array)
result &= item.is<T>();
return result;
}
};
// ArduinoJSON serialization support for std::map<std::string, T>
template <typename T>
struct Converter<std::map<std::string, T> > {
struct Converter<std::map<std::string, T>> {
static void toJson(const std::map<std::string, T>& src, JsonVariant dst) {
JsonObject obj = dst.to<JsonObject>();
for (const auto& item : src)
obj[item.first] = item.second;
obj[item.first] = item.second;
}
static std::map<std::string, T> fromJson(JsonVariantConst src) {
std::map<std::string, T> dst;
for (JsonPairConst item : src.as<JsonObjectConst>())
dst[item.key().c_str()] = item.value().as<T>();
dst[item.key().c_str()] = item.value().as<T>();
return dst;
}
static bool checkJson(JsonVariantConst src) {
JsonObjectConst obj = src;
bool result = obj;
for (JsonPairConst item : obj)
result &= item.value().is<T>();
result &= item.value().is<T>();
return result;
}
};
// ArduinoJSON serialization support for std::map<Bytes, T>
template <typename T>
struct Converter<std::map<RNS::Bytes, T> > {
struct Converter<std::map<RNS::Bytes, T>> {
static void toJson(const std::map<RNS::Bytes, T>& src, JsonVariant dst) {
JsonObject obj = dst.to<JsonObject>();
for (const auto& item : src) {
//obj[item.first] = item.second;
obj[item.first.toHex()] = item.second;
//obj[item.first] = item.second;
obj[item.first.toHex()] = item.second;
}
}
static std::map<RNS::Bytes, T> fromJson(JsonVariantConst src) {
std::map<RNS::Bytes, T> dst;
for (JsonPairConst item : src.as<JsonObjectConst>()) {
//dst[item.key().c_str()] = item.value().as<T>();
RNS::Bytes key;
key.assignHex(item.key().c_str());
//dst[key] = item.value().as<T>();
dst.insert({key, item.value().as<T>()});
//dst[item.key().c_str()] = item.value().as<T>();
RNS::Bytes key;
key.assignHex(item.key().c_str());
//dst[key] = item.value().as<T>();
dst.insert({key, item.value().as<T>()});
}
return dst;
}
@@ -80,10 +107,241 @@ namespace ArduinoJson {
JsonObjectConst obj = src;
bool result = obj;
for (JsonPairConst item : obj) {
result &= item.value().is<T>();
result &= item.value().is<T>();
}
return result;
}
};
/*
// ArduinoJSON serialization support for RNS::Interface
template <>
struct Converter<RNS::Interface> {
static bool toJson(const RNS::Interface& src, JsonVariant dst) {
if (!src) {
return dst.set(nullptr);
}
RNS::extreme("<<< Serializing interface hash " + src.get_hash().toHex());
return dst.set(src.get_hash().toHex());
}
static RNS::Interface fromJson(JsonVariantConst src) {
if (!src.isNull()) {
RNS::Bytes hash;
hash.assignHex(src.as<const char*>());
RNS::extreme(">>> Deserialized interface hash " + hash.toHex());
RNS::extreme(">>> Querying transport for interface");
// Query transport for matching interface
return RNS::Transport::find_interface_from_hash(hash);
}
else {
return {RNS::Type::NONE};
}
}
static bool checkJson(JsonVariantConst src) {
return src.is<const char*>() && strlen(src.as<const char*>()) == 64;
}
};
*/
/*
// ArduinoJSON serialization support for RNS::Packet
template <>
struct Converter<RNS::Packet> {
static bool toJson(const RNS::Packet& src, JsonVariant dst) {
if (!src) {
return dst.set(nullptr);
}
RNS::extreme("<<< Serializing packet hash " + src.get_hash().toHex());
// Whenever a reference to a packet is serilized we must ensure that packet itself also gets serialized separately
RNS::Transport::cache(src, true);
return dst.set(src.get_hash().toHex());
}
static RNS::Packet fromJson(JsonVariantConst src) {
if (!src.isNull()) {
RNS::Bytes hash;
hash.assignHex(src.as<const char*>());
RNS::extreme(">>> Deserialized packet hash " + hash.toHex());
RNS::extreme(">>> Querying transport for cached packet");
// Query transport for matching packet
return RNS::Transport::get_cached_packet(hash);
}
else {
return {RNS::Type::NONE};
}
}
static bool checkJson(JsonVariantConst src) {
return src.is<const char*>() && strlen(src.as<const char*>()) == 64;
}
};
*/
// ArduinoJSON serialization support for RNS::Packet
template <>
struct Converter<RNS::Packet> {
static bool toJson(const RNS::Packet& src, JsonVariant dst) {
RNS::extreme("<<< Serializing packet");
dst["hash"] = src.get_hash();
dst["raw"] = src.raw();
dst["sent_at"] = src.sent_at();
dst["destination_hash"] = src.get_hash();
RNS::extreme("<<< Finished serializing packet");
return true;
}
static RNS::Packet fromJson(JsonVariantConst src) {
RNS::extreme(">>> Deserializing packet");
/*
RNS::Packet packet;
//packet.set_hash(src["hash"]);
packet.sent_at(src["sent_at"]);
RNS::Bytes destination_hash = src["destination_hash"];
*/
/**/
RNS::Bytes raw = src["raw"];
RNS::Packet packet(
{RNS::Type::NONE},
raw
);
//packet.set_hash(src["hash"]);
packet.sent_at(src["sent_at"]);
RNS::Bytes destination_hash = src["destination_hash"];
/**/
RNS::extreme(">>> Finished deserializing packet");
return packet;
}
static bool checkJson(JsonVariantConst src) {
return
src["hash"].is<RNS::Bytes>() &&
src["raw"].is<RNS::Bytes>() &&
src["sent_at"].is<double>() &&
src["destination_hash"].is<RNS::Bytes>();
}
};
// ArduinoJSON serialization support for RNS::Transport::DestinationEntry
template <>
struct Converter<RNS::Transport::DestinationEntry> {
static bool toJson(const RNS::Transport::DestinationEntry& src, JsonVariant dst) {
RNS::extreme("<<< Serializing Transport::DestinationEntry");
dst["timestamp"] = src._timestamp;
dst["received_from"] = src._received_from;
dst["announce_hops"] = src._hops;
dst["expires"] = src._expires;
dst["random_blobs"] = src._random_blobs;
//dst["receiving_interface"] = src._receiving_interface;
if (src._receiving_interface) {
dst["receiving_interface_hash"] = src._receiving_interface.get_hash();
}
else {
dst["receiving_interface_hash"] = nullptr;
}
//dst["packet"] = src._announce_packet;
if (src._announce_packet) {
dst["packet_hash"] = src._announce_packet.get_hash();
// Whenever a reference to a packet is serilized we must ensure that packet itself also gets serialized separately
RNS::Transport::cache(src._announce_packet, true);
}
else {
dst["packet_hash"] = nullptr;
}
RNS::extreme("<<< Finished Serializing Transport::DestinationEntry");
return true;
}
static RNS::Transport::DestinationEntry fromJson(JsonVariantConst src) {
RNS::extreme(">>> Deserializing Transport::DestinationEntry");
/**/
RNS::Transport::DestinationEntry dst;
dst._timestamp = src["timestamp"];
dst._received_from = src["received_from"];
dst._hops = src["announce_hops"];
dst._expires = src["expires"];
dst._random_blobs = src["random_blobs"].as<std::set<RNS::Bytes>>();
//dst._receiving_interface = src["receiving_interface"];
RNS::Bytes interface_hash = src["receiving_interface_hash"];
if (interface_hash)
// Query transport for matching interface
dst._receiving_interface = RNS::Transport::find_interface_from_hash(interface_hash);
//dst._announce_packet = src["packet"];
RNS::Bytes packet_hash = src["packet_hash"];
if (packet_hash)
// Query transport for matching packet
dst._announce_packet = RNS::Transport::get_cached_packet(packet_hash);
/**/
/*
//RNS::Transport::DestinationEntry dst(src["timestamp"], src["received_from"], src["announce_hops"], src["expires"], src["random_blobs"], src["receiving_interface"], src["packet"]);
RNS::Transport::DestinationEntry dst(
src["timestamp"].as<double>(),
src["received_from"].as<RNS::Bytes>(),
src["announce_hops"].as<int>(),
src["expires"].as<double>(),
src["random_blobs"].as<std::set<RNS::Bytes>>(),
src["receiving_interface"].as<RNS::Interface>(),
src["packet"].as<RNS::Packet>()
);
*/
RNS::extreme(">>> Finished Deserializing Transport::DestinationEntry");
return dst;
}
static bool checkJson(JsonVariantConst src) {
return
src["timestamp"].is<double>() &&
src["received_from"].is<RNS::Bytes>() &&
src["announce_hops"].is<int>() &&
src["expires"].is<double>() &&
src["random_blobs"].is<std::set<RNS::Bytes>>() &&
src["receiving_interface_hash"].is<RNS::Bytes>() &&
src["packet_hash"].is<RNS::Bytes>();
}
};
}
namespace RNS { namespace Persistence {
template <typename T> bool serialize(const T& obj, const char* file_path, size_t max_size) {
DynamicJsonDocument doc(1024);
doc.set(obj);
RNS::Bytes data;
size_t length = serializeJson(doc, data.writable(max_size), max_size);
//size_t length = serializeMsgPack(doc, data.writable(max_size), max_size);
if (length < max_size) {
data.resize(length);
}
RNS::extreme("Persistence::serialize: serialized " + std::to_string(length) + " bytes");
if (length > 0) {
if (RNS::Utilities::OS::write_file(data, file_path)) {
RNS::extreme("Persistence::serialize: wrote: " + std::to_string(data.size()) + " bytes");
}
else {
RNS::extreme("Persistence::serialize: write failed");
return false;
}
}
else {
RNS::extreme("Persistence::serialize: failed to serialize");
return false;
}
return true;
}
template <typename T> bool deserialize(T& obj, const char* file_path) {
DynamicJsonDocument doc(1024);
RNS::Bytes data = RNS::Utilities::OS::read_file(file_path);
if (data) {
RNS::extreme("Persistence::deserialize: read: " + std::to_string(data.size()) + " bytes");
//RNS::extreme("testDeserializeVector: data: " + data.toString());
DeserializationError error = deserializeJson(doc, data.data());
//DeserializationError error = deserializeMsgPack(doc, data.data());
if (!error) {
RNS::extreme("Persistence::deserialize: successfully deserialized");
obj = doc.as<T>();
return true;
}
else {
RNS::extreme("Persistence::deserialize: failed to deserialize");
}
}
else {
RNS::extreme("Persistence::deserialize: read failed");
}
return false;;
}
} }
+34 -11
View File
@@ -1,4 +1,4 @@
//#define NDEBUG
#define NDEBUG
#include "Test/Test.h"
@@ -17,6 +17,7 @@
#ifdef ARDUINO
#include <Arduino.h>
#include <SPIFFS.h>
#else
#include <termios.h>
#include <fcntl.h>
@@ -33,11 +34,11 @@
#ifndef NDEBUG
//#define RUN_TESTS
#define RUN_TESTS
#endif
#define RUN_RETICULUM
#define UDP_INTERFACE
//#define UDP_INTERFACE
#define LORA_INTERFACE
//#define RETICULUM_PACKET_TEST
@@ -160,12 +161,6 @@ void reticulum_setup() {
// 21.8% baseline here with serial
RNS::head("Creating Reticulum instance...", RNS::LOG_EXTREME);
//RNS::Reticulum reticulum;
reticulum = RNS::Reticulum();
//return;
// 21.9% (+0.1%)
RNS::head("Registering Interface instances with Transport...", RNS::LOG_EXTREME);
#ifdef UDP_INTERFACE
udp_interface.mode(RNS::Type::Interface::MODE_GATEWAY);
@@ -178,7 +173,8 @@ void reticulum_setup() {
#ifdef UDP_INTERFACE
RNS::head("Starting UDPInterface...", RNS::LOG_EXTREME);
udp_interface.start("some_ssid", "some_password");
//udp_interface.start("wifi_ssid", "wifi_password", 4242);
udp_interface.start("broadmind-guest", "brcguest", 4242);
#endif
#ifdef LORA_INTERFACE
@@ -186,6 +182,14 @@ void reticulum_setup() {
lora_interface.start();
#endif
RNS::head("Creating Reticulum instance...", RNS::LOG_EXTREME);
//RNS::Reticulum reticulum;
reticulum = RNS::Reticulum();
reticulum.transport_enabled(true);
reticulum.start();
//return;
// 21.9% (+0.1%)
RNS::head("Creating Identity instance...", RNS::LOG_EXTREME);
// new identity
//RNS::Identity identity;
@@ -207,12 +211,13 @@ void reticulum_setup() {
destination = RNS::Destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "app", "aspects");
// 23.0% (+0.4%)
// test data receive packet
// Register DATA packet callback
RNS::head("Registering packet callback with Destination...", RNS::LOG_EXTREME);
destination.set_packet_callback(onPacket);
destination.set_proof_strategy(RNS::Type::Destination::PROVE_ALL);
{
// Register PING packet callback
RNS::head("Creating PING Destination instance...", RNS::LOG_EXTREME);
RNS::Destination ping_destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "example_utilities", "echo.request");
@@ -241,12 +246,16 @@ void reticulum_setup() {
RNS::head("Sending send packet...", RNS::LOG_EXTREME);
send_packet.pack();
#ifndef NDEBUG
RNS::extreme("Test send_packet: " + send_packet.debugString());
#endif
RNS::head("Creating recv packet...", RNS::LOG_EXTREME);
RNS::Packet recv_packet({RNS::Type::NONE}, send_packet.raw());
recv_packet.unpack();
#ifndef NDEBUG
RNS::extreme("Test recv_packet: " + recv_packet.debugString());
#endif
RNS::head("Spoofing recv packet to destination...", RNS::LOG_EXTREME);
destination.receive(recv_packet);
@@ -262,6 +271,8 @@ void reticulum_setup() {
void reticulum_teardown() {
RNS::info("Tearing down Reticulum...");
RNS::Transport::save_path_table();
try {
RNS::head("Deregistering announce handler with Transport...", RNS::LOG_EXTREME);
@@ -302,6 +313,14 @@ void setup() {
// Setup user button
pinMode(USER_BUTTON_PIN, INPUT);
attachInterrupt(USER_BUTTON_PIN, userKey, FALLING);
// Setup filesystem
if (!SPIFFS.begin(true, "")){
RNS::error("SPIFFS filesystem mount failed");
}
else {
RNS::debug("SPIFFS filesystem is ready");
}
#endif
RNS::loglevel(RNS::LOG_EXTREME);
@@ -394,6 +413,10 @@ int main(void) {
RNS::Utilities::OS::sleep(0.01);
}
#if defined(RUN_RETICULUM)
reticulum_teardown();
#endif
printf("Goodbye from Native on PlatformIO!\n");
}
#endif