mirror of
https://github.com/ratspeak/microReticulum
synced 2026-11-22 23:10:38 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
23b285f3bf | ||
|
|
491fbd034e | ||
|
|
c69087ba40 | ||
|
|
4d6f0b9de2 | ||
|
|
49ccbc2827 | ||
|
|
a968fdfc64 | ||
|
|
9da37b29ac | ||
|
|
89dce2c73b | ||
|
|
e3a128ed2d | ||
|
|
9289da1a19 | ||
|
|
d670dd00d3 | ||
|
|
448695ca7a | ||
|
|
79b75bbd4e | ||
|
|
5864a3c6fc | ||
|
|
3babdc001d | ||
|
|
e86481e121 | ||
|
|
086aac87b5 | ||
|
|
c40adfb4ec | ||
|
|
b0681fe33f | ||
|
|
f5a23a5a56 | ||
|
|
20a7022241 | ||
|
|
6d31c9cd2b | ||
|
|
d76bfce7ce | ||
|
|
3c4978f294 | ||
|
|
3cc7c2a55d | ||
|
|
6a705bc582 | ||
|
|
b2dc394623 |
No files matched your search
@@ -11,7 +11,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
env: [native, native17, native20]
|
||||
env: [native, native14, native17, native20]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -51,6 +51,7 @@ jobs:
|
||||
|
||||
- name: Build Embedded Targets
|
||||
run: |
|
||||
pio run --environment ttgo-lora32-v21
|
||||
pio run --environment ttgo-t-beam
|
||||
# pio run --environment wiscore_rak4631 # Got UnknownBoard: Unknown board ID 'wiscore_rak4631'
|
||||
pio run --environment lilygo_tbeam_supreme
|
||||
pio run --environment ttgo-lora32-v21
|
||||
pio run --environment wiscore_rak4631
|
||||
@@ -18,8 +18,33 @@ This API is dependent on the following external libraries:
|
||||
- `-DRNS_MEM_LOG` Used to enable logging of low-level memory operations for debug purposes
|
||||
- `-DRNS_USE_FS` Used to enable use of file system by RNS for persistence
|
||||
- `-DRNS_PERSIST_PATHS` Used to enable persistence of RNS paths in file system (also requires `-DRNS_USE_FS`)
|
||||
- `-DRNS_USE_TLSF=1` Enables the use of the TLSF (Two-Level Segregate Fit) dynamic memory manager for efficient management of constrained MCU memory with minimal fragmentation. Currently only required on NRF52 boards (ESP32 already uses TLSF internally).
|
||||
- `-DRNS_USE_ALLOCATOR=1` Enables the replacement of default new/delete operators with custom implementations that take advantage of optimized memory managers (eg, TLSF). Currently only required on NRF52 boards (ESP32 already uses TLSF internally).
|
||||
|
||||
## Memory Management Build Options
|
||||
|
||||
Two classes of memory allocator are defined; the container allocator (`RNS_CONTAINER_ALLOCATOR`) which is used for certain long-lived STL containers (e.g. path table), and the default allocator (`RNS_DEFAULT_ALLOCATOR`) which is used for all other C++ memory allocation (new/delete).
|
||||
|
||||
Each class of allocator can be configured to use a separate type of allocator. Available memory allocators are:
|
||||
- `RNS_HEAP_ALLOCATOR`: Basic allocator that uses default system HEAP.
|
||||
- `RNS_HEAP_POOL_ALLOCATOR`: Optimized TLSF managed HEAP buffer
|
||||
- `RNS_PSRAM_ALLOCATOR`: Basic allocator that uses PSRAM memory (if PSRAM is available)
|
||||
- `RNS_PSRAM_POOL_ALLOCATOR`: Optimized TLSF managed PSRAM buffer (if PSRAM is available)
|
||||
|
||||
Each class of allocator pool can have a separate buffer size:
|
||||
- `RNS_HEAP_POOL_BUFFER_SIZE=N` Defines the HEAP TLSF memory pool buffer size (N bytes, default 0 which means dynamic)
|
||||
- `RNS_PSRAM_POOL_BUFFER_SIZE=N` Defines the PSRAM TLSF memory pool buffer size (N bytes, default 0 which means dynamic)
|
||||
|
||||
"POOL" allocators use TLSF (Two-Level Segregate Fit) for efficient management of constrained MCU memory with minimal fragmentation.
|
||||
|
||||
The allocator for each class can be configured using build flags in `platformio.ini, for example:
|
||||
|
||||
```
|
||||
[env]
|
||||
build_flags =
|
||||
-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_ALLOCATOR
|
||||
-DRNS_CONTAINER_ALLOCATOR=RNS_PSRAM_POOL_ALLOCATOR
|
||||
```
|
||||
|
||||
NOTE: Currently `-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_POOL_ALLOCATOR` is only required on NRF52 boards since ESP32 already uses TLSF internally.
|
||||
|
||||
## Building
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino":{
|
||||
"ldscript": "esp32_out.ld"
|
||||
},
|
||||
"core": "esp32",
|
||||
"extra_flags": "-DARDUINO_ESP32_DEV",
|
||||
"f_cpu": "240000000L",
|
||||
"f_flash": "40000000L",
|
||||
"flash_mode": "dio",
|
||||
"mcu": "esp32",
|
||||
"variant": "rak11200"
|
||||
},
|
||||
"connectivity": [
|
||||
"wifi",
|
||||
"bluetooth",
|
||||
"ethernet",
|
||||
"can"
|
||||
],
|
||||
"frameworks": [
|
||||
"arduino",
|
||||
"espidf"
|
||||
],
|
||||
"name": "WisCore RAK11200 Board",
|
||||
"upload": {
|
||||
"flash_size": "4MB",
|
||||
"maximum_ram_size": 327680,
|
||||
"maximum_size": 4194304,
|
||||
"protocols": [
|
||||
"esptool",
|
||||
"espota",
|
||||
"ftdi"
|
||||
],
|
||||
"require_upload_port": true,
|
||||
"speed": 460800
|
||||
},
|
||||
"url": "https://www.rakwireless.com",
|
||||
"vendor": "RAKwireless"
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"build": {
|
||||
"core": "arduino",
|
||||
"cpu": "cortex-m0plus",
|
||||
"extra_flags": "-D ARDUINO_RASPBERRY_PI_PICO -DARDUINO_ARCH_RP2040",
|
||||
"f_cpu": "133000000L",
|
||||
"hwids": [
|
||||
[
|
||||
"0x2E8A",
|
||||
"0x00C0"
|
||||
]
|
||||
],
|
||||
"mcu": "rp2040",
|
||||
"variant": "rak11300"
|
||||
},
|
||||
"debug": {
|
||||
"jlink_device": "RP2040_M0_0",
|
||||
"openocd_target": "rp2040.cfg",
|
||||
"svd_path": "rp2040.svd"
|
||||
},
|
||||
"frameworks": [
|
||||
"arduino"
|
||||
],
|
||||
"name": "WisBlock RAK11300",
|
||||
"upload": {
|
||||
"maximum_ram_size": 270336,
|
||||
"maximum_size": 2097152,
|
||||
"require_upload_port": true,
|
||||
"native_usb": true,
|
||||
"use_1200bps_touch": true,
|
||||
"wait_for_upload_port": false,
|
||||
"protocol": "picotool",
|
||||
"protocols": [
|
||||
"cmsis-dap",
|
||||
"jlink",
|
||||
"raspberrypi-swd",
|
||||
"picotool"
|
||||
]
|
||||
},
|
||||
"url": "https://docs.rakwireless.com/",
|
||||
"vendor": "RAKwireless"
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"ldscript": "esp32s3_out.ld",
|
||||
"memory_type": "qio_opi"
|
||||
},
|
||||
"core": "esp32",
|
||||
"extra_flags": [
|
||||
"-DRAK3112",
|
||||
"-DARDUINO_USB_CDC_ON_BOOT=1",
|
||||
"-DARDUINO_USB_MODE=1",
|
||||
"-DARDUINO_RUNNING_CORE=1",
|
||||
"-DARDUINO_EVENT_RUNNING_CORE=1",
|
||||
"-DBOARD_HAS_PSRAM"
|
||||
],
|
||||
"f_cpu": "240000000L",
|
||||
"f_flash": "80000000L",
|
||||
"flash_mode": "dio",
|
||||
"hwids": [
|
||||
[
|
||||
"0x303A",
|
||||
"0x1001"
|
||||
]
|
||||
],
|
||||
"mcu": "esp32s3",
|
||||
"variant": "rak3112"
|
||||
},
|
||||
"connectivity": [
|
||||
"wifi",
|
||||
"bluetooth"
|
||||
],
|
||||
"debug": {
|
||||
"openocd_target": "esp32s3.cfg"
|
||||
},
|
||||
"frameworks": [
|
||||
"arduino",
|
||||
"espidf"
|
||||
],
|
||||
"name": "RAKwireless RAK3112",
|
||||
"upload": {
|
||||
"flash_size": "16MB",
|
||||
"maximum_ram_size": 327680,
|
||||
"maximum_size": 16777216,
|
||||
"use_1200bps_touch": true,
|
||||
"wait_for_upload_port": false,
|
||||
"require_upload_port": true,
|
||||
"speed": 921600
|
||||
},
|
||||
"url": "http://www.rakwireless.com/",
|
||||
"vendor": "RAKwireless"
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"build": {
|
||||
"arduino": {
|
||||
"ldscript": "nrf52840_s140_v6.ld"
|
||||
},
|
||||
"core": "nRF5",
|
||||
"cpu": "cortex-m4",
|
||||
"extra_flags": "-DARDUINO_NRF52840_FEATHER -DNRF52840_XXAA",
|
||||
"f_cpu": "64000000L",
|
||||
"hwids": [
|
||||
[
|
||||
"0x239A",
|
||||
"0x8029"
|
||||
],
|
||||
[
|
||||
"0x239A",
|
||||
"0x0029"
|
||||
],
|
||||
[
|
||||
"0x239A",
|
||||
"0x002A"
|
||||
],
|
||||
[
|
||||
"0x239A",
|
||||
"0x802A"
|
||||
]
|
||||
],
|
||||
"usb_product": "WisCore RAK4631 Board",
|
||||
"mcu": "nrf52840",
|
||||
"variant": "rak4630",
|
||||
"bsp": {
|
||||
"name": "adafruit"
|
||||
},
|
||||
"softdevice": {
|
||||
"sd_flags": "-DS140",
|
||||
"sd_name": "s140",
|
||||
"sd_version": "6.1.1",
|
||||
"sd_fwid": "0x00B6"
|
||||
},
|
||||
"bootloader": {
|
||||
"settings_addr": "0xFF000"
|
||||
}
|
||||
},
|
||||
"connectivity": [
|
||||
"bluetooth"
|
||||
],
|
||||
"debug": {
|
||||
"jlink_device": "nRF52840_xxAA",
|
||||
"openocd_target": "nrf52840",
|
||||
"svd_path": "nrf52840.svd"
|
||||
},
|
||||
"frameworks": [
|
||||
"arduino"
|
||||
],
|
||||
"name": "WisCore RAK4631 Board",
|
||||
"upload": {
|
||||
"maximum_ram_size": 248832,
|
||||
"maximum_size": 815104,
|
||||
"speed": 115200,
|
||||
"protocol": "nrfutil",
|
||||
"protocols": [
|
||||
"jlink",
|
||||
"nrfjprog",
|
||||
"nrfutil",
|
||||
"stlink"
|
||||
],
|
||||
"use_1200bps_touch": true,
|
||||
"require_upload_port": true,
|
||||
"wait_for_upload_port": true
|
||||
},
|
||||
"url": "https://www.rakwireless.com",
|
||||
"vendor": "RAKwireless"
|
||||
}
|
||||
@@ -66,7 +66,7 @@ delay(1500);
|
||||
LoRa.setTxPower(power);
|
||||
|
||||
INFO("LoRa init succeeded.");
|
||||
TRACE("LoRa bandwidth is " + std::to_string(Utilities::OS::round(_bitrate/1000.0, 2)) + " Kbps");
|
||||
TRACEF("LoRa bandwidth is %.2f Kbps", Utilities::OS::round(_bitrate/1000.0, 2));
|
||||
#endif
|
||||
|
||||
_online = true;
|
||||
@@ -111,10 +111,10 @@ void LoRaInterface::loop() {
|
||||
}
|
||||
|
||||
/*virtual*/ void LoRaInterface::send_outgoing(const Bytes& data) {
|
||||
DEBUG(toString() + ".on_outgoing: data: " + data.toHex());
|
||||
DEBUGF("%s.on_outgoing: data: %s", toString().c_str(), data.toHex().c_str());
|
||||
try {
|
||||
if (_online) {
|
||||
TRACE("LoRaInterface: sending " + std::to_string(data.size()) + " bytes...");
|
||||
TRACEF("LoRaInterface: sending %zu bytes...", data.size());
|
||||
// Send packet
|
||||
#ifdef ARDUINO
|
||||
|
||||
@@ -142,12 +142,12 @@ void LoRaInterface::loop() {
|
||||
InterfaceImpl::handle_outgoing(data);
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERROR("Could not transmit on " + toString() + ". The contained exception was: " + e.what());
|
||||
ERRORF("Could not transmit on %s. The contained exception was: %s", toString().c_str(), e.what());
|
||||
}
|
||||
}
|
||||
|
||||
/*virtual*/ void LoRaInterface::on_incoming(const Bytes& data) {
|
||||
DEBUG(toString() + ".on_incoming: data: " + data.toHex());
|
||||
DEBUGF("%s.on_incoming: data: %s", toString().c_str(), data.toHex().c_str());
|
||||
// Pass received data on to transport
|
||||
InterfaceImpl::handle_incoming(data);
|
||||
}
|
||||
@@ -64,14 +64,14 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa
|
||||
}
|
||||
_local_port = port;
|
||||
_remote_port = port;
|
||||
TRACE("UDPInterface: local host: " + _local_host);
|
||||
TRACE("UDPInterface: local port: " + std::to_string(_local_port));
|
||||
TRACE("UDPInterface: remote host: " + _remote_host);
|
||||
TRACE("UDPInterface: remote port: " + std::to_string(_remote_port));
|
||||
TRACEF("UDPInterface: local host: %s", _local_host.c_str());
|
||||
TRACEF("UDPInterface: local port: %d", _local_port);
|
||||
TRACEF("UDPInterface: remote host: %s", _remote_host.c_str());
|
||||
TRACEF("UDPInterface: remote port: %d", _remote_port);
|
||||
|
||||
#ifdef ARDUINO
|
||||
TRACE("UDPInterface: wifi ssid: " + _wifi_ssid);
|
||||
TRACE("UDPInterface: wifi password: " + _wifi_password);
|
||||
TRACEF("UDPInterface: wifi ssid: %s", _wifi_ssid.c_str());
|
||||
TRACEF("UDPInterface: wifi password: %s", _wifi_password.c_str());
|
||||
|
||||
// Connect to the WiFi network
|
||||
WiFi.begin(_wifi_ssid.c_str(), _wifi_password.c_str());
|
||||
@@ -133,7 +133,7 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa
|
||||
if (inet_aton(_local_host.c_str(), &local_addr) == 0) {
|
||||
struct hostent* host_ent = gethostbyname(_local_host.c_str());
|
||||
if (host_ent == nullptr || host_ent->h_addr_list[0] == nullptr) {
|
||||
ERROR("Unable to resolve local host " + std::string(_local_host));
|
||||
ERRORF("Unable to resolve local host %s", _local_host.c_str());
|
||||
return false;
|
||||
}
|
||||
_local_address = *((in_addr_t*)(host_ent->h_addr_list[0]));
|
||||
@@ -147,7 +147,7 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa
|
||||
if (inet_aton(_remote_host.c_str(), &remote_addr) == 0) {
|
||||
struct hostent* host_ent = gethostbyname(_remote_host.c_str());
|
||||
if (host_ent == nullptr || host_ent->h_addr_list[0] == nullptr) {
|
||||
ERROR("Unable to resolve remote host " + std::string(_remote_host));
|
||||
ERRORF("Unable to resolve remote host %s", _remote_host.c_str());
|
||||
return false;
|
||||
}
|
||||
_remote_address = *((in_addr_t*)(host_ent->h_addr_list[0]));
|
||||
@@ -160,7 +160,7 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa
|
||||
TRACE("Opening UDP socket");
|
||||
_socket = socket( PF_INET, SOCK_DGRAM, 0 );
|
||||
if (_socket < 0) {
|
||||
ERROR("Unable to create socket with error " + std::to_string(errno));
|
||||
ERRORF("Unable to create socket with error %d", errno);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -176,7 +176,7 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa
|
||||
#endif
|
||||
|
||||
// bind to interface for listening
|
||||
INFO("Binding UDP socket " + std::to_string(_socket) + " to " + std::string(_local_host) + ":" + std::to_string(_local_port));
|
||||
INFOF("Binding UDP socket %d to %s:%d", _socket, _local_host.c_str(), _local_port);
|
||||
sockaddr_in bind_addr;
|
||||
bind_addr.sin_family = AF_INET;
|
||||
bind_addr.sin_addr.s_addr = _local_address;
|
||||
@@ -184,7 +184,7 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa
|
||||
if (bind(_socket, (struct sockaddr*)&bind_addr, sizeof(bind_addr)) == -1) {
|
||||
close(_socket);
|
||||
_socket = -1;
|
||||
ERROR("Unable to bind socket with error " + std::to_string(errno));
|
||||
ERRORF("Unable to bind socket with error %d", errno);
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
@@ -234,7 +234,7 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa
|
||||
}
|
||||
|
||||
/*virtual*/ void UDPInterface::send_outgoing(const Bytes& data) {
|
||||
DEBUG(toString() + ".on_outgoing: data: " + data.toHex());
|
||||
DEBUGF("%s.on_outgoing: data: %s", toString().c_str(), data.toHex().c_str());
|
||||
try {
|
||||
if (_online) {
|
||||
// Send packet
|
||||
@@ -243,13 +243,13 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa
|
||||
udp.write(data.data(), data.size());
|
||||
udp.endPacket();
|
||||
#else
|
||||
TRACE("Sending UDP packet to " + std::string(_remote_host) + ":" + std::to_string(_remote_port));
|
||||
TRACEF("Sending UDP packet to %s:%d", _remote_host.c_str(), _remote_port);
|
||||
sockaddr_in sock_addr;
|
||||
sock_addr.sin_family = AF_INET;
|
||||
sock_addr.sin_addr.s_addr = _remote_address;
|
||||
sock_addr.sin_port = htons(_remote_port);
|
||||
int sent = sendto(_socket, data.data(), data.size(), 0, (struct sockaddr*)&sock_addr, sizeof(sock_addr));
|
||||
TRACE("Sent " + std::to_string(sent) + " bytes to " + std::string(_remote_host) + ":" + std::to_string(_remote_port));
|
||||
TRACEF("Sent %d bytes to %s:%d", sent, _remote_host.c_str(), _remote_port);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -257,12 +257,12 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa
|
||||
InterfaceImpl::handle_outgoing(data);
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERROR("Could not transmit on " + toString() + ". The contained exception was: " + e.what());
|
||||
ERRORF("Could not transmit on %s. The contained exception was: %s", toString().c_str(), e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void UDPInterface::on_incoming(const Bytes& data) {
|
||||
DEBUG(toString() + ".on_incoming: data: " + data.toHex());
|
||||
DEBUGF("%s.on_incoming: data: %s", toString().c_str(), data.toHex().c_str());
|
||||
// Pass received data on to transport
|
||||
InterfaceImpl::handle_incoming(data);
|
||||
}
|
||||
@@ -121,7 +121,7 @@ void UniversalFileSystem::listDir(const char* dir) {
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
ERROR("file_exists: failed to open file " + std::string(file_path));
|
||||
ERRORF("file_exists: failed to open file %s", file_path);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -155,9 +155,9 @@ void UniversalFileSystem::listDir(const char* dir) {
|
||||
//size_t read = fread(data.writable(size), size, 1, file);
|
||||
read = fread(data.writable(size), 1, size, file);
|
||||
#endif
|
||||
TRACE("read_file: read " + std::to_string(read) + " bytes from file " + std::string(file_path));
|
||||
TRACEF("read_file: read %zu bytes from file %s", read, file_path);
|
||||
if (read != size) {
|
||||
ERROR("read_file: failed to read file " + std::string(file_path));
|
||||
ERRORF("read_file: failed to read file %s", file_path);
|
||||
data.clear();
|
||||
}
|
||||
//TRACE("read_file: closing input file");
|
||||
@@ -173,7 +173,7 @@ void UniversalFileSystem::listDir(const char* dir) {
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
ERROR("read_file: failed to open input file " + std::string(file_path));
|
||||
ERRORF("read_file: failed to open input file %s", file_path);
|
||||
}
|
||||
return read;
|
||||
}
|
||||
@@ -201,9 +201,9 @@ void UniversalFileSystem::listDir(const char* dir) {
|
||||
//size_t wrote = fwrite(data.data(), data.size(), 1, file);
|
||||
wrote = fwrite(data.data(), 1, data.size(), file);
|
||||
#endif
|
||||
TRACE("write_file: wrote " + std::to_string(wrote) + " bytes to file " + std::string(file_path));
|
||||
TRACEF("write_file: wrote %zu bytes to file %s", wrote, file_path);
|
||||
if (wrote < data.size()) {
|
||||
WARNING("write_file: not all data was written to file " + std::string(file_path));
|
||||
WARNINGF("write_file: not all data was written to file %s", file_path);
|
||||
}
|
||||
//TRACE("write_file: closing output file");
|
||||
#ifdef ARDUINO
|
||||
@@ -218,7 +218,7 @@ void UniversalFileSystem::listDir(const char* dir) {
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
ERROR("write_file: failed to open output file " + std::string(file_path));
|
||||
ERRORF("write_file: failed to open output file %s", file_path);
|
||||
}
|
||||
return wrote;
|
||||
}
|
||||
@@ -247,14 +247,13 @@ void UniversalFileSystem::listDir(const char* dir) {
|
||||
//if (!file) {
|
||||
File* file = new File(SPIFFS.open(file_path, mode));
|
||||
if (file == nullptr || !(*file)) {
|
||||
if (file != nullptr) delete file;
|
||||
ERRORF("open_file: failed to open output file %s", file_path);
|
||||
return {RNS::Type::NONE};
|
||||
}
|
||||
TRACEF("open_file: successfully opened file %s", file_path);
|
||||
return RNS::FileStream(new UniversalFileStream(file));
|
||||
#elif BOARD_NRF52
|
||||
//File file = File(InternalFS);
|
||||
File* file = new File(InternalFS);
|
||||
int mode;
|
||||
if (file_mode == RNS::FileStream::MODE_READ) {
|
||||
mode = FILE_O_READ;
|
||||
@@ -274,7 +273,10 @@ void UniversalFileSystem::listDir(const char* dir) {
|
||||
ERRORF("open_file: unsupported mode %d", file_mode);
|
||||
return {RNS::Type::NONE};
|
||||
}
|
||||
if (!file->open(file_path, mode)) {
|
||||
//File file = File(InternalFS);
|
||||
File* file = new File(InternalFS);
|
||||
if (file == nullptr || !file->open(file_path, mode)) {
|
||||
if (file != nullptr) delete file;
|
||||
ERRORF("open_file: failed to open output file %s", file_path);
|
||||
return {RNS::Type::NONE};
|
||||
}
|
||||
@@ -348,7 +350,7 @@ void UniversalFileSystem::listDir(const char* dir) {
|
||||
}
|
||||
|
||||
/*virtua*/ bool UniversalFileSystem::directory_exists(const char* directory_path) {
|
||||
TRACE("directory_exists: checking for existence of directory " + std::string(directory_path));
|
||||
TRACEF("directory_exists: checking for existence of directory %s", directory_path);
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
File file = SPIFFS.open(directory_path, FILE_READ);
|
||||
@@ -382,13 +384,13 @@ void UniversalFileSystem::listDir(const char* dir) {
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
if (!SPIFFS.mkdir(directory_path)) {
|
||||
ERROR("create_directory: failed to create directorty " + std::string(directory_path));
|
||||
ERRORF("create_directory: failed to create directorty %s", directory_path);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
#elif BOARD_NRF52
|
||||
if (!InternalFS.mkdir(directory_path)) {
|
||||
ERROR("create_directory: failed to create directorty " + std::string(directory_path));
|
||||
ERRORF("create_directory: failed to create directorty %s", directory_path);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -406,18 +408,18 @@ void UniversalFileSystem::listDir(const char* dir) {
|
||||
}
|
||||
|
||||
/*virtua*/ bool UniversalFileSystem::remove_directory(const char* directory_path) {
|
||||
TRACE("remove_directory: removing directory " + std::string(directory_path));
|
||||
TRACEF("remove_directory: removing directory %s", directory_path);
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
//if (!LittleFS.rmdir_r(directory_path)) {
|
||||
if (!SPIFFS.rmdir(directory_path)) {
|
||||
ERROR("remove_directory: failed to remove directorty " + std::string(directory_path));
|
||||
ERRORF("remove_directory: failed to remove directorty %s", directory_path);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
#elif BOARD_NRF52
|
||||
if (!InternalFS.rmdir_r(directory_path)) {
|
||||
ERROR("remove_directory: failed to remove directory " + std::string(directory_path));
|
||||
ERRORF("remove_directory: failed to remove directory %s", directory_path);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -430,8 +432,8 @@ void UniversalFileSystem::listDir(const char* dir) {
|
||||
#endif
|
||||
}
|
||||
|
||||
/*virtua*/ std::list<std::string> UniversalFileSystem::list_directory(const char* directory_path) {
|
||||
TRACE("list_directory: listing directory " + std::string(directory_path));
|
||||
/*virtua*/ std::list<std::string> UniversalFileSystem::list_directory(const char* directory_path, Callbacks::DirectoryListing callback /*= nullptr*/) {
|
||||
TRACEF("list_directory: listing directory %s", directory_path);
|
||||
std::list<std::string> files;
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
@@ -440,14 +442,15 @@ void UniversalFileSystem::listDir(const char* dir) {
|
||||
File root = InternalFS.open(directory_path);
|
||||
#endif
|
||||
if (!root) {
|
||||
ERROR("list_directory: failed to open directory " + std::string(directory_path));
|
||||
ERRORF("list_directory: failed to open directory %s", directory_path);
|
||||
return files;
|
||||
}
|
||||
File file = root.openNextFile();
|
||||
while (file) {
|
||||
if (!file.isDirectory()) {
|
||||
char* name = (char*)file.name();
|
||||
files.push_back(name);
|
||||
if (callback) callback(name);
|
||||
else files.push_back(name);
|
||||
}
|
||||
// CBA Following close required to avoid leaking memory
|
||||
file.close();
|
||||
|
||||
@@ -42,7 +42,7 @@ public:
|
||||
virtual bool directory_exists(const char* directory_path);
|
||||
virtual bool create_directory(const char* directory_path);
|
||||
virtual bool remove_directory(const char* directory_path);
|
||||
virtual std::list<std::string> list_directory(const char* directory_path);
|
||||
virtual std::list<std::string> list_directory(const char* directory_path, Callbacks::DirectoryListing callback = nullptr);
|
||||
virtual size_t storage_size();
|
||||
virtual size_t storage_available();
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
#include <termios.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <signal.h>
|
||||
#endif
|
||||
|
||||
#include <stdlib.h>
|
||||
@@ -34,6 +35,7 @@
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <functional>
|
||||
#include <algorithm>
|
||||
|
||||
// Let's define an app name. We'll use this for all
|
||||
// destinations we create. Since this echo example
|
||||
@@ -63,7 +65,7 @@ void server_packet_received(const RNS::Bytes& message, const RNS::Packet& packet
|
||||
// it will all be directed to the last client
|
||||
// that connected.
|
||||
std::string text = message.toString();
|
||||
RNS::log("Received data on the link: "+text);
|
||||
RNS::logf(RNS::LOG_NOTICE, "Received data on the link: %s", text.c_str());
|
||||
|
||||
std::string reply_text = "I received \""+text+"\" over the link";
|
||||
RNS::Bytes reply_data(reply_text);
|
||||
@@ -84,11 +86,7 @@ void client_connected(RNS::Link& link) {
|
||||
|
||||
void server_loop(RNS::Destination& destination) {
|
||||
// Let the user know that everything is ready
|
||||
RNS::log(
|
||||
"Link example <"+
|
||||
destination.hash().toHex()+
|
||||
"> running, waiting for a connection."
|
||||
);
|
||||
RNS::logf(RNS::LOG_NOTICE, "Link example <%s> running, waiting for a connection.", destination.hash().toHex().c_str());
|
||||
|
||||
RNS::log("Hit enter to manually send an announce (Ctrl-C to quit)");
|
||||
|
||||
@@ -103,7 +101,7 @@ void server_loop(RNS::Destination& destination) {
|
||||
while (read(STDIN_FILENO, &ch, 1) > 0) {
|
||||
if (ch == '\n') {
|
||||
destination.announce();
|
||||
RNS::log("Sent announce from "+destination.hash().toHex());
|
||||
RNS::logf(RNS::LOG_NOTICE, "Sent announce from %s", destination.hash().toHex().c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -180,7 +178,7 @@ void link_closed(RNS::Link& link) {
|
||||
// simply print out the data.
|
||||
void client_packet_received(const RNS::Bytes& message, const RNS::Packet& packet) {
|
||||
std::string text = message.toString();
|
||||
RNS::log("Received data on the link: "+text);
|
||||
RNS::logf(RNS::LOG_NOTICE, "Received data on the link: %s", text.c_str());
|
||||
printf("> ");
|
||||
fflush(stdout);
|
||||
}
|
||||
@@ -221,12 +219,7 @@ printf("(sending data: %s)\n", text.c_str());
|
||||
RNS::Packet(server_link, data).send();
|
||||
}
|
||||
else {
|
||||
RNS::log(
|
||||
"Cannot send this packet, the data size of "+
|
||||
std::to_string(data.size())+" bytes exceeds the link packet MDU of "+
|
||||
std::to_string(RNS::Type::Link::MDU)+" bytes",
|
||||
RNS::LOG_ERROR
|
||||
);
|
||||
RNS::logf(RNS::LOG_ERROR, "Cannot send this packet, the data size of %zu bytes exceeds the link packet MDU of %zu bytes", data.size(), (size_t)RNS::Type::Link::MDU);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,11 +321,27 @@ void cleanup_handler(int signum) {
|
||||
// starts up the desired program mode.
|
||||
int main(int argc, char *argv[]) {
|
||||
|
||||
bool log_trace = false;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
if (argv[i] && strcasecmp(argv[i], "--log_trace") == 0) {
|
||||
log_trace = true;
|
||||
for (int j = i; j < argc - 1; ++j) {
|
||||
argv[j] = argv[j + 1];
|
||||
}
|
||||
--argc;
|
||||
--i;
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(RNS_MEM_LOG)
|
||||
RNS::loglevel(RNS::LOG_MEM);
|
||||
#else
|
||||
RNS::loglevel(RNS::LOG_NOTICE);
|
||||
//RNS::loglevel(RNS::LOG_TRACE);
|
||||
if (log_trace) {
|
||||
RNS::loglevel(RNS::LOG_TRACE);
|
||||
}
|
||||
else {
|
||||
RNS::loglevel(RNS::LOG_NOTICE);
|
||||
}
|
||||
#endif
|
||||
|
||||
// Register the signal handler for SIGINT
|
||||
|
||||
@@ -18,8 +18,6 @@ monitor_speed = 115200
|
||||
upload_speed = 921600
|
||||
build_type = debug
|
||||
build_flags =
|
||||
-DRNS_USE_ALLOCATOR=1
|
||||
-DRNS_USE_TLSF=1
|
||||
;-DRNS_MEM_LOG
|
||||
lib_deps =
|
||||
ArduinoJson@^7.4.2
|
||||
|
||||
@@ -55,13 +55,13 @@ public:
|
||||
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());
|
||||
INFOF("ExampleAnnounceHandler: destination hash: %s", destination_hash.toHex().c_str());
|
||||
if (announced_identity) {
|
||||
INFO("ExampleAnnounceHandler: announced identity hash: " + announced_identity.hash().toHex());
|
||||
INFO("ExampleAnnounceHandler: announced identity app data: " + announced_identity.app_data().toHex());
|
||||
INFOF("ExampleAnnounceHandler: announced identity hash: %s", announced_identity.hash().toHex().c_str());
|
||||
INFOF("ExampleAnnounceHandler: announced identity app data: %s", announced_identity.app_data().toHex().c_str());
|
||||
}
|
||||
if (app_data) {
|
||||
INFO("ExampleAnnounceHandler: app data text: \"" + app_data.toString() + "\"");
|
||||
INFOF("ExampleAnnounceHandler: app data text: \"%s\"", app_data.toString().c_str());
|
||||
}
|
||||
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
|
||||
}
|
||||
@@ -70,18 +70,18 @@ public:
|
||||
// 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());
|
||||
INFOF("onPacket: data: %s", data.toHex().c_str());
|
||||
INFOF("onPacket: text: \"%s\"", data.toString().c_str());
|
||||
//TRACEF("onPacket: %s", packet.debugString().c_str());
|
||||
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());
|
||||
INFOF("onPingPacket: data: %s", data.toHex().c_str());
|
||||
INFOF("onPingPacket: text: \"%s\"", data.toString().c_str());
|
||||
//TRACEF("onPingPacket: %s", packet.debugString().c_str());
|
||||
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
|
||||
}
|
||||
|
||||
@@ -205,14 +205,14 @@ void reticulum_setup() {
|
||||
HEAD("Sending send packet...", RNS::LOG_TRACE);
|
||||
send_packet.pack();
|
||||
#ifndef NDEBUG
|
||||
TRACE("Test send_packet: " + send_packet.debugString());
|
||||
TRACEF("Test send_packet: %s", send_packet.debugString().c_str());
|
||||
#endif
|
||||
|
||||
HEAD("Creating recv packet...", RNS::LOG_TRACE);
|
||||
RNS::Packet recv_packet({RNS::Type::NONE}, send_packet.raw());
|
||||
recv_packet.unpack();
|
||||
#ifndef NDEBUG
|
||||
TRACE("Test recv_packet: " + recv_packet.debugString());
|
||||
TRACEF("Test recv_packet: %s", recv_packet.debugString().c_str());
|
||||
#endif
|
||||
|
||||
HEAD("Spoofing recv packet to destination...", RNS::LOG_TRACE);
|
||||
|
||||
@@ -80,11 +80,13 @@ monitor_filters = esp32_exception_decoder
|
||||
[env:wiscore_rak4631]
|
||||
framework = arduino
|
||||
platform = nordicnrf52
|
||||
board = wiscore_rak4631
|
||||
board = rak4630
|
||||
board_build.partitions = no_ota.csv
|
||||
board_build.FileSystem = littlefs
|
||||
build_src_filter = ${env.build_src_filter}+<../variants/rak4630>
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
-I variants/rak4630
|
||||
;-Wextra
|
||||
-fexceptions
|
||||
-DBOARD_NRF52
|
||||
|
||||
@@ -56,13 +56,13 @@ public:
|
||||
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());
|
||||
INFOF("ExampleAnnounceHandler: destination hash: %s", destination_hash.toHex().c_str());
|
||||
if (announced_identity) {
|
||||
INFO("ExampleAnnounceHandler: announced identity hash: " + announced_identity.hash().toHex());
|
||||
INFO("ExampleAnnounceHandler: announced identity app data: " + announced_identity.app_data().toHex());
|
||||
INFOF("ExampleAnnounceHandler: announced identity hash: %s", announced_identity.hash().toHex().c_str());
|
||||
INFOF("ExampleAnnounceHandler: announced identity app data: %s", announced_identity.app_data().toHex().c_str());
|
||||
}
|
||||
if (app_data) {
|
||||
INFO("ExampleAnnounceHandler: app data text: \"" + app_data.toString() + "\"");
|
||||
INFOF("ExampleAnnounceHandler: app data text: \"%s\"", app_data.toString().c_str());
|
||||
}
|
||||
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
|
||||
}
|
||||
@@ -71,18 +71,18 @@ public:
|
||||
// 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());
|
||||
INFOF("onPacket: data: %s", data.toHex().c_str());
|
||||
INFOF("onPacket: text: \"%s\"", data.toString().c_str());
|
||||
//TRACEF("onPacket: %s", packet.debugString().c_str());
|
||||
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());
|
||||
INFOF("onPingPacket: data: %s", data.toHex().c_str());
|
||||
INFOF("onPingPacket: text: \"%s\"", data.toString().c_str());
|
||||
//TRACEF("onPingPacket: %s", packet.debugString().c_str());
|
||||
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
|
||||
}
|
||||
|
||||
@@ -198,14 +198,14 @@ void reticulum_setup() {
|
||||
HEAD("Sending send packet...", RNS::LOG_TRACE);
|
||||
send_packet.pack();
|
||||
#ifndef NDEBUG
|
||||
TRACE("Test send_packet: " + send_packet.debugString());
|
||||
TRACEF("Test send_packet: %s", send_packet.debugString().c_str());
|
||||
#endif
|
||||
|
||||
HEAD("Creating recv packet...", RNS::LOG_TRACE);
|
||||
RNS::Packet recv_packet({RNS::Type::NONE}, send_packet.raw());
|
||||
recv_packet.unpack();
|
||||
#ifndef NDEBUG
|
||||
TRACE("Test recv_packet: " + recv_packet.debugString());
|
||||
TRACEF("Test recv_packet: %s", recv_packet.debugString().c_str());
|
||||
#endif
|
||||
|
||||
HEAD("Spoofing recv packet to destination...", RNS::LOG_TRACE);
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "microReticulum",
|
||||
"version": "0.2.3",
|
||||
"version": "0.2.10",
|
||||
"description": "Port of Reticulum Network Stack to C++ specifically but not exclusively targeting 32-bit and better MCUs",
|
||||
"keywords": "reticulum, rns, mesh, embedded, mcu, esp32, nrf52, native",
|
||||
"repository":
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
name=microReticulum
|
||||
version=0.2.3
|
||||
version=0.2.10
|
||||
author=Chad Attermann <attermann@gmail.com>
|
||||
maintainer=Chad Attermann <attermann@gmail.com>
|
||||
sentence=Port of Reticulum Network Stack to C++
|
||||
|
||||
+133
-27
@@ -9,15 +9,22 @@
|
||||
; https://docs.platformio.org/page/projectconf.html
|
||||
|
||||
[platformio]
|
||||
default_envs = native
|
||||
default_envs = native17
|
||||
|
||||
[env]
|
||||
monitor_speed = 115200
|
||||
build_unflags =
|
||||
-fno-exceptions
|
||||
build_flags =
|
||||
-fexceptions
|
||||
-Wall
|
||||
;-Wextra
|
||||
-Wno-missing-field-initializers
|
||||
-Wno-format
|
||||
-Wno-unused-parameter
|
||||
-Wno-unused-variable
|
||||
-Wno-unused-but-set-variable
|
||||
-Wno-unused-private-field
|
||||
-Isrc
|
||||
-DLIBRARY_TEST
|
||||
;-DNDEBUG
|
||||
@@ -35,18 +42,33 @@ test_build_src = true
|
||||
platform = native
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
-std=c++11
|
||||
-std=gnu++11
|
||||
-DNATIVE
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
lib_compat_mode = off
|
||||
|
||||
[env:native17]
|
||||
[env:native14]
|
||||
platform = native
|
||||
build_unflags = -std=gnu++11
|
||||
build_unflags =
|
||||
${env.build_unflags}
|
||||
-std=gnu++11
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
-std=c++17
|
||||
-std=gnu++14
|
||||
-DNATIVE
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
lib_compat_mode = off
|
||||
|
||||
[env:native17]
|
||||
platform = native
|
||||
build_unflags =
|
||||
${env.build_unflags}
|
||||
-std=gnu++11
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
-std=gnu++17
|
||||
-DNATIVE
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
@@ -54,76 +76,160 @@ lib_compat_mode = off
|
||||
|
||||
[env:native20]
|
||||
platform = native
|
||||
build_unflags = -std=gnu++11
|
||||
build_unflags =
|
||||
${env.build_unflags}
|
||||
-std=gnu++11
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
-std=c++20
|
||||
-std=gnu++20
|
||||
-DNATIVE
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
lib_compat_mode = off
|
||||
|
||||
[env:native_debug]
|
||||
platform = native
|
||||
build_unflags =
|
||||
${env.build_unflags}
|
||||
-std=gnu++11
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
;-std=gnu++11
|
||||
-std=gnu++17
|
||||
-DNATIVE
|
||||
; CBA TEST
|
||||
;-fsanitize=address
|
||||
-fno-omit-frame-pointer
|
||||
-g
|
||||
;-O1
|
||||
-O0
|
||||
-Wunused-parameter
|
||||
-Wunused-variable
|
||||
-Wunused-but-set-variable
|
||||
-Wunused-private-field
|
||||
;-DBOARD_HAS_PSRAM=1
|
||||
;-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_ALLOCATOR
|
||||
-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_POOL_ALLOCATOR
|
||||
-DRNS_CONTAINER_ALLOCATOR=RNS_ALTHEAP_POOL_ALLOCATOR
|
||||
;-DRNS_HEAP_POOL_BUFFER_SIZE=81920
|
||||
;-DRNS_HEAP_POOL_BUFFER_SIZE=102400
|
||||
-DRNS_HEAP_POOL_BUFFER_SIZE=204800
|
||||
;-DRNS_HEAP_POOL_BUFFER_SIZE=307200
|
||||
;-DRNS_HEAP_POOL_BUFFER_SIZE=409600
|
||||
;-DRNS_HEAP_POOL_BUFFER_SIZE=512000
|
||||
;-DRNS_HEAP_POOL_BUFFER_SIZE=614400
|
||||
;-DRNS_HEAP_POOL_BUFFER_SIZE=1024000
|
||||
-DRNS_ALTHEAP_POOL_BUFFER_SIZE=2048000
|
||||
-DTLSF_DEBUG=1
|
||||
;-DRNS_MEM_LOG
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
lib_compat_mode = off
|
||||
test_flags = -vvv
|
||||
|
||||
[env:embedded]
|
||||
framework = arduino
|
||||
upload_speed = 460800
|
||||
build_unflags =
|
||||
${env.build_unflags}
|
||||
-std=gnu++11
|
||||
;-fno-rtti
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
-std=gnu++17
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
|
||||
[env:ttgo-lora32-v21]
|
||||
extends = env:embedded
|
||||
platform = espressif32
|
||||
board = ttgo-lora32-v21
|
||||
board_build.partitions = no_ota.csv
|
||||
framework = arduino
|
||||
monitor_speed = 115200
|
||||
build_unflags =
|
||||
${env:embedded.build_unflags}
|
||||
-std=gnu++11
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
${env:embedded.build_flags}
|
||||
-std=gnu++17
|
||||
-DBOARD_ESP32
|
||||
-DMSGPACK_USE_BOOST=OFF
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
${env:embedded.lib_deps}
|
||||
monitor_filters = esp32_exception_decoder
|
||||
|
||||
[env:ttgo-t-beam]
|
||||
extends = env:embedded
|
||||
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 =
|
||||
${env.build_flags}
|
||||
${env:embedded.build_flags}
|
||||
-DBOARD_ESP32
|
||||
-DMSGPACK_USE_BOOST=OFF
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
${env:embedded.lib_deps}
|
||||
monitor_filters = esp32_exception_decoder
|
||||
|
||||
[env:lilygo_tbeam_supreme]
|
||||
extends = env:embedded
|
||||
platform = espressif32
|
||||
board = t-beams3-supreme
|
||||
board_build.partitions = no_ota.csv
|
||||
;board_build.partitions = huge_app.csv
|
||||
framework = arduino
|
||||
monitor_speed = 115200
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
${env:embedded.build_flags}
|
||||
-DBOARD_ESP32
|
||||
-DMSGPACK_USE_BOOST=OFF
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
${env:embedded.lib_deps}
|
||||
monitor_filters = esp32_exception_decoder
|
||||
|
||||
; also Heltec Wireless Tracker
|
||||
[env:heltec_wifi_lora_32_V4]
|
||||
extends = env:embedded
|
||||
platform = espressif32
|
||||
board = esp32-s3-devkitc-1
|
||||
board_build.partitions = no_ota.csv
|
||||
;board_build.partitions = huge_app.csv
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
-DBOARD_ESP32
|
||||
-DMSGPACK_USE_BOOST=OFF
|
||||
-DARDUINO_USB_CDC_ON_BOOT=1
|
||||
; CBA TEST
|
||||
-DBOARD_HAS_PSRAM=1
|
||||
;-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_ALLOCATOR
|
||||
-DRNS_DEFAULT_ALLOCATOR=RNS_PSRAM_ALLOCATOR
|
||||
;-DRNS_CONTAINER_ALLOCATOR=RNS_PSRAM_ALLOCATOR
|
||||
-DRNS_CONTAINER_ALLOCATOR=RNS_PSRAM_POOL_ALLOCATOR
|
||||
-DRNS_PSRAM_POOL_BUFFER_SIZE=2048000
|
||||
lib_deps =
|
||||
${env:embedded.lib_deps}
|
||||
monitor_filters = esp32_exception_decoder
|
||||
upload_speed = 921600
|
||||
|
||||
[env:wiscore_rak4631]
|
||||
extends = env:embedded
|
||||
platform = nordicnrf52
|
||||
board = wiscore_rak4631
|
||||
board = rak4630
|
||||
board_build.partitions = no_ota.csv
|
||||
framework = arduino
|
||||
monitor_speed = 115200
|
||||
build_src_filter = ${env:embedded.build_src_filter}+<../variants/rak4630>
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
${env:embedded.build_flags}
|
||||
-I variants/rak4630
|
||||
-fexceptions
|
||||
-DBOARD_NRF52
|
||||
-DRNS_USE_ALLOCATOR=1
|
||||
-DRNS_USE_TLSF=1
|
||||
-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_POOL_ALLOCATOR
|
||||
-DRNS_HEAP_POOL_BUFFER_SIZE=204800
|
||||
-DMSGPACK_USE_BOOST=OFF
|
||||
lib_deps =
|
||||
${env.lib_deps}
|
||||
${env:embedded.lib_deps}
|
||||
adafruit/Adafruit TinyUSB Library
|
||||
|
||||
; Overrides for specific tests (not working!)
|
||||
[test_env:test_objects]
|
||||
build_flags =
|
||||
${env.build_flags}
|
||||
${env:embedded.build_flags}
|
||||
;-DTEST_OBJECT_DATA=1
|
||||
-DTEST_OBJECT_IMPL=1
|
||||
+100
-4
@@ -126,6 +126,13 @@ void Bytes::assignHex(const uint8_t* hex, size_t hex_size) {
|
||||
_exclusive = true;
|
||||
return;
|
||||
}
|
||||
// Truncate to even length (hex bytes come in pairs)
|
||||
hex_size &= ~(size_t)1;
|
||||
if (hex_size == 0) {
|
||||
_data = nullptr;
|
||||
_exclusive = true;
|
||||
return;
|
||||
}
|
||||
exclusiveData(false, hex_size / 2);
|
||||
// need to clear data since we're appending below
|
||||
_data->clear();
|
||||
@@ -140,6 +147,11 @@ void Bytes::appendHex(const uint8_t* hex, size_t hex_size) {
|
||||
if (hex == nullptr || hex_size <= 0) {
|
||||
return;
|
||||
}
|
||||
// Truncate to even length (hex bytes come in pairs)
|
||||
hex_size &= ~(size_t)1;
|
||||
if (hex_size == 0) {
|
||||
return;
|
||||
}
|
||||
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;
|
||||
@@ -150,6 +162,18 @@ void Bytes::appendHex(const uint8_t* hex, size_t hex_size) {
|
||||
const char hex_upper_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
|
||||
const char hex_lower_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
|
||||
|
||||
static const char base64_chars[65] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
static int8_t b64_decode_char(uint8_t c) {
|
||||
if (c >= 'A' && c <= 'Z') return c - 'A';
|
||||
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
|
||||
if (c >= '0' && c <= '9') return c - '0' + 52;
|
||||
if (c == '+') return 62;
|
||||
if (c == '/') return 63;
|
||||
return -1; // invalid / padding
|
||||
}
|
||||
|
||||
std::string RNS::hexFromByte(uint8_t byte, bool upper /*= true*/) {
|
||||
std::string hex;
|
||||
if (upper) {
|
||||
@@ -181,15 +205,87 @@ std::string Bytes::toHex(bool upper /*= false*/) const {
|
||||
return hex;
|
||||
}
|
||||
|
||||
std::string Bytes::toBase64() const {
|
||||
if (!_data) {
|
||||
return "";
|
||||
}
|
||||
const uint8_t* in = _data->data();
|
||||
size_t in_size = _data->size();
|
||||
std::string out;
|
||||
out.reserve(((in_size + 2) / 3) * 4);
|
||||
for (size_t i = 0; i < in_size; i += 3) {
|
||||
uint8_t b0 = in[i];
|
||||
uint8_t b1 = (i + 1 < in_size) ? in[i + 1] : 0;
|
||||
uint8_t b2 = (i + 2 < in_size) ? in[i + 2] : 0;
|
||||
out += base64_chars[(b0 >> 2) & 0x3F];
|
||||
out += base64_chars[((b0 << 4) | (b1 >> 4)) & 0x3F];
|
||||
out += (i + 1 < in_size) ? base64_chars[((b1 << 2) | (b2 >> 6)) & 0x3F] : '=';
|
||||
out += (i + 2 < in_size) ? base64_chars[b2 & 0x3F] : '=';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void Bytes::assignBase64(const uint8_t* b64, size_t b64_size) {
|
||||
if (b64 == nullptr || b64_size == 0) {
|
||||
_data = nullptr;
|
||||
_exclusive = true;
|
||||
return;
|
||||
}
|
||||
// strip trailing padding
|
||||
while (b64_size > 0 && b64[b64_size - 1] == '=') {
|
||||
--b64_size;
|
||||
}
|
||||
size_t out_size = (b64_size * 3) / 4;
|
||||
exclusiveData(false, out_size);
|
||||
_data->clear();
|
||||
for (size_t i = 0; i < b64_size; ) {
|
||||
int8_t v0 = (i < b64_size) ? b64_decode_char(b64[i++]) : 0;
|
||||
int8_t v1 = (i < b64_size) ? b64_decode_char(b64[i++]) : 0;
|
||||
int8_t v2 = (i < b64_size) ? b64_decode_char(b64[i++]) : -1;
|
||||
int8_t v3 = (i < b64_size) ? b64_decode_char(b64[i++]) : -1;
|
||||
if (v0 < 0 || v1 < 0) break;
|
||||
_data->push_back((uint8_t)((v0 << 2) | (v1 >> 4)));
|
||||
if (v2 >= 0) _data->push_back((uint8_t)((v1 << 4) | (v2 >> 2)));
|
||||
if (v3 >= 0) _data->push_back((uint8_t)((v2 << 6) | v3));
|
||||
}
|
||||
if (_data->empty()) {
|
||||
_data = nullptr;
|
||||
_exclusive = true;
|
||||
}
|
||||
}
|
||||
|
||||
void Bytes::appendBase64(const uint8_t* b64, size_t b64_size) {
|
||||
if (b64 == nullptr || b64_size == 0) {
|
||||
return;
|
||||
}
|
||||
// strip trailing padding
|
||||
while (b64_size > 0 && b64[b64_size - 1] == '=') {
|
||||
--b64_size;
|
||||
}
|
||||
size_t out_size = (b64_size * 3) / 4;
|
||||
exclusiveData(true, size() + out_size);
|
||||
for (size_t i = 0; i < b64_size; ) {
|
||||
int8_t v0 = (i < b64_size) ? b64_decode_char(b64[i++]) : 0;
|
||||
int8_t v1 = (i < b64_size) ? b64_decode_char(b64[i++]) : 0;
|
||||
int8_t v2 = (i < b64_size) ? b64_decode_char(b64[i++]) : -1;
|
||||
int8_t v3 = (i < b64_size) ? b64_decode_char(b64[i++]) : -1;
|
||||
if (v0 < 0 || v1 < 0) break;
|
||||
_data->push_back((uint8_t)((v0 << 2) | (v1 >> 4)));
|
||||
if (v2 >= 0) _data->push_back((uint8_t)((v1 << 4) | (v2 >> 2)));
|
||||
if (v3 >= 0) _data->push_back((uint8_t)((v2 << 6) | v3));
|
||||
}
|
||||
}
|
||||
|
||||
// mid
|
||||
Bytes Bytes::mid(size_t beginpos, size_t len) const {
|
||||
if (!_data || beginpos >= size()) {
|
||||
return NONE;
|
||||
}
|
||||
if ((beginpos + len) >= size()) {
|
||||
len = (size() - beginpos);
|
||||
}
|
||||
return {data() + beginpos, len};
|
||||
size_t remaining = size() - beginpos;
|
||||
if (len > remaining) {
|
||||
len = remaining;
|
||||
}
|
||||
return {data() + beginpos, len};
|
||||
}
|
||||
|
||||
// to end
|
||||
|
||||
+22
-9
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "Log.h"
|
||||
#include "Utilities/Memory.h"
|
||||
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
@@ -40,9 +41,9 @@ namespace RNS {
|
||||
class Bytes {
|
||||
|
||||
private:
|
||||
//typedef std::vector<uint8_t> Data;
|
||||
using Data = std::vector<uint8_t>;
|
||||
//typedef std::shared_ptr<Data> SharedData;
|
||||
// CBA Need to fix msgpack serialize/deserialize before enabling ContainerAllocator
|
||||
//using Data = std::vector<uint8_t, Utilities::Memory::ContainerAllocator<uint8_t>>;
|
||||
using SharedData = std::shared_ptr<Data>;
|
||||
|
||||
public:
|
||||
@@ -196,6 +197,7 @@ MEM("Creating from data-move...");
|
||||
|
||||
inline void assign(const Bytes& bytes) {
|
||||
#ifdef COW
|
||||
// shared_ptr copy only — O(1), no heap allocation
|
||||
_data = bytes.shareData();
|
||||
_exclusive = false;
|
||||
#else
|
||||
@@ -261,7 +263,7 @@ MEM("Creating from data-move...");
|
||||
//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 uint8_t* hex, size_t hex_size);
|
||||
inline void assignHex(const char* hex) { assignHex((uint8_t*)hex, strlen(hex)); }
|
||||
inline void assignHex(const char* hex) { if (!hex) return; assignHex((uint8_t*)hex, strlen(hex)); }
|
||||
|
||||
inline void append(const Bytes& bytes) {
|
||||
// if append is empty then do nothing
|
||||
@@ -306,7 +308,14 @@ MEM("Creating from data-move...");
|
||||
//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 uint8_t* hex, size_t hex_size);
|
||||
inline void appendHex(const char* hex) { appendHex((uint8_t*)hex, strlen(hex)); }
|
||||
inline void appendHex(const char* hex) { if (!hex) return; appendHex((uint8_t*)hex, strlen(hex)); }
|
||||
|
||||
void assignBase64(const uint8_t* b64, size_t b64_size);
|
||||
inline void assignBase64(const char* b64) { if (!b64) return; assignBase64((uint8_t*)b64, strlen(b64)); }
|
||||
|
||||
void appendBase64(const uint8_t* b64, size_t b64_size);
|
||||
inline void appendBase64(const char* b64) { if (!b64) return; appendBase64((uint8_t*)b64, strlen(b64)); }
|
||||
|
||||
|
||||
inline uint8_t* writable(size_t size) {
|
||||
if (size > 0) {
|
||||
@@ -342,7 +351,7 @@ MEM("Creating from data-move...");
|
||||
public:
|
||||
int compare(const Bytes& bytes) const;
|
||||
int compare(const uint8_t* buf, size_t size) const;
|
||||
inline int compare(const char* str) const { return compare((const uint8_t*)str, strlen(str)); }
|
||||
inline int compare(const char* str) const { if (!str) return empty() ? 0 : 1; return compare((const uint8_t*)str, strlen(str)); }
|
||||
inline size_t size() const { if (!_data) return 0; return _data->size(); }
|
||||
inline bool empty() const { if (!_data) return true; return _data->empty(); }
|
||||
inline size_t capacity() const { if (!_data) return 0; return _data->capacity(); }
|
||||
@@ -352,12 +361,13 @@ MEM("Creating from data-move...");
|
||||
|
||||
inline std::string toString() const { if (!_data) return ""; return {(const char*)data(), size()}; }
|
||||
std::string toHex(bool upper = false) const;
|
||||
std::string toBase64() const;
|
||||
Bytes mid(size_t beginpos, size_t len) const;
|
||||
Bytes mid(size_t beginpos) const;
|
||||
inline Bytes left(size_t len) const { if (!_data) return NONE; if (len > size()) len = size(); return {data(), len}; }
|
||||
inline Bytes right(size_t len) const { if (!_data) return NONE; if (len > size()) len = size(); return {data() + (size() - len), len}; }
|
||||
inline int find(int pos, const char* str) {
|
||||
if (!_data || _data->data() == nullptr || (size_t)pos >= _data->size()) {
|
||||
if (!str || !_data || _data->data() == nullptr || (size_t)pos >= _data->size()) {
|
||||
return -1;
|
||||
}
|
||||
//const char* ptr = strnstr((const char*)(_data->data() + pos), str, (_data->size() - pos));
|
||||
@@ -402,11 +412,12 @@ MEM("Creating from data-move...");
|
||||
//inline Bytes bytesFromChunk(const uint8_t* ptr, size_t len) { return Bytes(ptr, len); }
|
||||
inline Bytes bytesFromChunk(const uint8_t* ptr, size_t len) { return {ptr, len}; }
|
||||
//inline Bytes bytesFromString(const char* str) { return Bytes((uint8_t*)str, strlen(str)); }
|
||||
inline Bytes bytesFromString(const char* str) { return {(uint8_t*)str, strlen(str)}; }
|
||||
inline Bytes bytesFromString(const char* str) { if (!str) return {}; return {(uint8_t*)str, strlen(str)}; }
|
||||
//z inline Bytes bytesFromInt(const int) { return {(uint8_t*)str, strlen(str)}; }
|
||||
|
||||
inline std::string stringFromBytes(const Bytes& bytes) { return bytes.toString(); }
|
||||
inline std::string hexFromBytes(const Bytes& bytes) { return bytes.toHex(); }
|
||||
inline std::string base64FromBytes(const Bytes& bytes) { return bytes.toBase64(); }
|
||||
std::string hexFromByte(uint8_t byte, bool upper = true);
|
||||
|
||||
}
|
||||
@@ -432,14 +443,16 @@ inline RNS::Bytes& operator << (RNS::Bytes& lhbytes, const char* rhstr) {
|
||||
return lhbytes;
|
||||
}
|
||||
|
||||
//CBA TODO Standardize where custom object de/serialization lives
|
||||
namespace ArduinoJson {
|
||||
// Serialize
|
||||
inline bool convertToJson(const RNS::Bytes& src, JsonVariant dst) {
|
||||
return dst.set(src.toHex());
|
||||
return dst.set(src.toBase64());
|
||||
}
|
||||
// Deserialize
|
||||
inline void convertFromJson(JsonVariantConst src, RNS::Bytes& dst) {
|
||||
dst.assignHex(src.as<const char*>());
|
||||
const char* b64 = src.as<const char*>();
|
||||
if (b64) dst.assignBase64(b64);
|
||||
}
|
||||
inline bool canConvertFromJson(JsonVariantConst src, const RNS::Bytes&) {
|
||||
return src.is<const char*>();
|
||||
|
||||
+2
-2
@@ -39,8 +39,8 @@ namespace RNS {
|
||||
private:
|
||||
class Object {
|
||||
public:
|
||||
Object() { MEM("Channel::Data object created, this: " + std::to_string((uintptr_t)this)); }
|
||||
virtual ~Object() { MEM("Channel::Data object destroyed, this: " + std::to_string((uintptr_t)this)); }
|
||||
Object() { MEMF("Channel::Data object created, this: %p", (void*)this); }
|
||||
virtual ~Object() { MEMF("Channel::Data object destroyed, this: %p", (void*)this); }
|
||||
private:
|
||||
|
||||
friend class Channel;
|
||||
|
||||
+15
-15
@@ -41,44 +41,44 @@ bool Fernet::verify_hmac(const Bytes& token) {
|
||||
|
||||
//received_hmac = token[-32:]
|
||||
Bytes received_hmac = token.right(32);
|
||||
DEBUG("Fernet::verify_hmac: received_hmac: " + received_hmac.toHex());
|
||||
DEBUGF("Fernet::verify_hmac: received_hmac: %s", received_hmac.toHex().c_str());
|
||||
//expected_hmac = HMAC.new(self._signing_key, token[:-32]).digest()
|
||||
Bytes expected_hmac = HMAC::generate(_signing_key, token.left(token.size()-32))->digest();
|
||||
DEBUG("Fernet::verify_hmac: expected_hmac: " + expected_hmac.toHex());
|
||||
DEBUGF("Fernet::verify_hmac: expected_hmac: %s", expected_hmac.toHex().c_str());
|
||||
|
||||
return (received_hmac == expected_hmac);
|
||||
}
|
||||
|
||||
const Bytes Fernet::encrypt(const Bytes& data) {
|
||||
|
||||
DEBUG("Fernet::encrypt: plaintext length: " + std::to_string(data.size()));
|
||||
DEBUGF("Fernet::encrypt: plaintext length: %zu", data.size());
|
||||
Bytes iv = random(16);
|
||||
//double current_time = OS::time();
|
||||
TRACE("Fernet::encrypt: iv: " + iv.toHex());
|
||||
TRACEF("Fernet::encrypt: iv: %s", iv.toHex().c_str());
|
||||
|
||||
TRACE("Fernet::encrypt: plaintext: " + data.toHex());
|
||||
TRACEF("Fernet::encrypt: plaintext: %s", data.toHex().c_str());
|
||||
Bytes ciphertext = AES_128_CBC::encrypt(
|
||||
PKCS7::pad(data),
|
||||
_encryption_key,
|
||||
iv
|
||||
);
|
||||
DEBUG("Fernet::encrypt: padded ciphertext length: " + std::to_string(ciphertext.size()));
|
||||
TRACE("Fernet::encrypt: ciphertext: " + ciphertext.toHex());
|
||||
DEBUGF("Fernet::encrypt: padded ciphertext length: %zu", ciphertext.size());
|
||||
TRACEF("Fernet::encrypt: ciphertext: %s", ciphertext.toHex().c_str());
|
||||
|
||||
Bytes signed_parts = iv + ciphertext;
|
||||
|
||||
//return signed_parts + HMAC::generate(_signing_key, signed_parts)->digest();
|
||||
Bytes sig(HMAC::generate(_signing_key, signed_parts)->digest());
|
||||
TRACE("Fernet::encrypt: sig: " + sig.toHex());
|
||||
TRACEF("Fernet::encrypt: sig: %s", sig.toHex().c_str());
|
||||
Bytes token(signed_parts + sig);
|
||||
DEBUG("Fernet::encrypt: token length: " + std::to_string(token.size()));
|
||||
DEBUGF("Fernet::encrypt: token length: %zu", token.size());
|
||||
return token;
|
||||
}
|
||||
|
||||
|
||||
const Bytes Fernet::decrypt(const Bytes& token) {
|
||||
|
||||
DEBUG("Fernet::decrypt: token length: " + std::to_string(token.size()));
|
||||
DEBUGF("Fernet::decrypt: token length: %zu", token.size());
|
||||
if (token.size() < 48) {
|
||||
throw std::invalid_argument("Cannot decrypt token of only " + std::to_string(token.size()) + " bytes");
|
||||
}
|
||||
@@ -89,11 +89,11 @@ const Bytes Fernet::decrypt(const Bytes& token) {
|
||||
|
||||
//iv = token[:16]
|
||||
Bytes iv = token.left(16);
|
||||
TRACE("Fernet::decrypt: iv: " + iv.toHex());
|
||||
TRACEF("Fernet::decrypt: iv: %s", iv.toHex().c_str());
|
||||
|
||||
//ciphertext = token[16:-32]
|
||||
Bytes ciphertext = token.mid(16, token.size()-48);
|
||||
TRACE("Fernet::decrypt: ciphertext: " + ciphertext.toHex());
|
||||
TRACEF("Fernet::decrypt: ciphertext: %s", ciphertext.toHex().c_str());
|
||||
|
||||
try {
|
||||
Bytes plaintext = PKCS7::unpad(
|
||||
@@ -103,10 +103,10 @@ const Bytes Fernet::decrypt(const Bytes& token) {
|
||||
iv
|
||||
)
|
||||
);
|
||||
DEBUG("Fernet::encrypt: unpadded plaintext length: " + std::to_string(plaintext.size()));
|
||||
TRACE("Fernet::decrypt: plaintext: " + plaintext.toHex());
|
||||
DEBUGF("Fernet::encrypt: unpadded plaintext length: %zu", plaintext.size());
|
||||
TRACEF("Fernet::decrypt: plaintext: %s", plaintext.toHex().c_str());
|
||||
|
||||
DEBUG("Fernet::decrypt: plaintext length: " + std::to_string(plaintext.size()));
|
||||
DEBUGF("Fernet::decrypt: plaintext length: %zu", plaintext.size());
|
||||
return plaintext;
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
|
||||
@@ -15,13 +15,13 @@ calls in RNS end up here.
|
||||
*/
|
||||
|
||||
const Bytes RNS::Cryptography::sha256(const Bytes& data) {
|
||||
//TRACE("Cryptography::sha256: data: " + data.toHex() );
|
||||
//TRACEF("Cryptography::sha256: data: %s", data.toHex().c_str());
|
||||
SHA256 digest;
|
||||
digest.reset();
|
||||
digest.update(data.data(), data.size());
|
||||
Bytes hash;
|
||||
digest.finalize(hash.writable(32), 32);
|
||||
//TRACE("Cryptography::sha256: hash: " + hash.toHex() );
|
||||
//TRACEF("Cryptography::sha256: hash: %s", hash.toHex().c_str());
|
||||
return hash;
|
||||
}
|
||||
|
||||
@@ -31,6 +31,6 @@ const Bytes RNS::Cryptography::sha512(const Bytes& data) {
|
||||
digest.update(data.data(), data.size());
|
||||
Bytes hash;
|
||||
digest.finalize(hash.writable(64), 64);
|
||||
//TRACE("Cryptography::sha512: hash: " + hash.toHex() );
|
||||
//TRACEF("Cryptography::sha512: hash: %s", hash.toHex().c_str());
|
||||
return hash;
|
||||
}
|
||||
@@ -28,9 +28,9 @@ namespace RNS { namespace Cryptography {
|
||||
// updates passed buffer
|
||||
static inline void inplace_pad(Bytes& data, size_t bs = BLOCKSIZE) {
|
||||
size_t len = data.size();
|
||||
//DEBUG("PKCS7::pad: len: " + std::to_string(len));
|
||||
//DEBUGF("PKCS7::pad: len: %zu", len);
|
||||
size_t padlen = bs - (len % bs);
|
||||
//DEBUG("PKCS7::pad: pad len: " + std::to_string(padlen));
|
||||
//DEBUGF("PKCS7::pad: pad len: %zu", padlen);
|
||||
// create zero-filled byte padding array of size padlen
|
||||
//p v = bytes([padlen])
|
||||
//uint8_t pad[padlen] = {0};
|
||||
@@ -41,24 +41,24 @@ namespace RNS { namespace Cryptography {
|
||||
// concatenate data with padding
|
||||
//p return data+v*padlen
|
||||
data.append(pad, padlen);
|
||||
//DEBUG("PKCS7::pad: data size: " + std::to_string(data.size()));
|
||||
//DEBUGF("PKCS7::pad: data size: %zu", data.size());
|
||||
}
|
||||
|
||||
// updates passed buffer
|
||||
static inline void inplace_unpad(Bytes& data, size_t bs = BLOCKSIZE) {
|
||||
size_t len = data.size();
|
||||
//DEBUG("PKCS7::unpad: len: " + std::to_string(len));
|
||||
//DEBUGF("PKCS7::unpad: len: %zu", len);
|
||||
// read last byte which is pad length
|
||||
//pad = data[-1]
|
||||
size_t padlen = (size_t)data.data()[data.size()-1];
|
||||
//DEBUG("PKCS7::unpad: pad len: " + std::to_string(padlen));
|
||||
//DEBUGF("PKCS7::unpad: pad len: %zu", padlen);
|
||||
if (padlen > bs) {
|
||||
throw std::runtime_error("Cannot unpad, invalid padding length of " + std::to_string(padlen) + " bytes");
|
||||
}
|
||||
// truncate data to strip padding
|
||||
//return data[:len-padlen]
|
||||
data.resize(len - padlen);
|
||||
//DEBUG("PKCS7::unpad: data size: " + std::to_string(data.size()));
|
||||
//DEBUGF("PKCS7::unpad: data size: %zu", data.size());
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
+15
-15
@@ -56,22 +56,22 @@ bool Token::verify_hmac(const Bytes& token) {
|
||||
|
||||
//received_hmac = token[-32:]
|
||||
Bytes received_hmac = token.right(32);
|
||||
DEBUG("Token::verify_hmac: received_hmac: " + received_hmac.toHex());
|
||||
DEBUGF("Token::verify_hmac: received_hmac: %s", received_hmac.toHex().c_str());
|
||||
//expected_hmac = HMAC.new(self._signing_key, token[:-32]).digest()
|
||||
Bytes expected_hmac = HMAC::generate(_signing_key, token.left(token.size()-32))->digest();
|
||||
DEBUG("Token::verify_hmac: expected_hmac: " + expected_hmac.toHex());
|
||||
DEBUGF("Token::verify_hmac: expected_hmac: %s", expected_hmac.toHex().c_str());
|
||||
|
||||
return (received_hmac == expected_hmac);
|
||||
}
|
||||
|
||||
const Bytes Token::encrypt(const Bytes& data) {
|
||||
|
||||
DEBUG("Token::encrypt: plaintext length: " + std::to_string(data.size()));
|
||||
DEBUGF("Token::encrypt: plaintext length: %zu", data.size());
|
||||
Bytes iv = random(16);
|
||||
//double current_time = OS::time();
|
||||
TRACE("Token::encrypt: iv: " + iv.toHex());
|
||||
TRACEF("Token::encrypt: iv: %s", iv.toHex().c_str());
|
||||
|
||||
TRACE("Token::encrypt: plaintext: " + data.toHex());
|
||||
TRACEF("Token::encrypt: plaintext: %s", data.toHex().c_str());
|
||||
Bytes ciphertext;
|
||||
if (_mode == MODE_AES_128_CBC) {
|
||||
ciphertext = AES_128_CBC::encrypt(
|
||||
@@ -90,23 +90,23 @@ const Bytes Token::encrypt(const Bytes& data) {
|
||||
else {
|
||||
throw new std::invalid_argument("Invalid token mode "+std::to_string(_mode));
|
||||
}
|
||||
DEBUG("Token::encrypt: padded ciphertext length: " + std::to_string(ciphertext.size()));
|
||||
TRACE("Token::encrypt: ciphertext: " + ciphertext.toHex());
|
||||
DEBUGF("Token::encrypt: padded ciphertext length: %zu", ciphertext.size());
|
||||
TRACEF("Token::encrypt: ciphertext: %s", ciphertext.toHex().c_str());
|
||||
|
||||
Bytes signed_parts = iv + ciphertext;
|
||||
|
||||
//return signed_parts + HMAC::generate(_signing_key, signed_parts)->digest();
|
||||
Bytes sig(HMAC::generate(_signing_key, signed_parts)->digest());
|
||||
TRACE("Token::encrypt: sig: " + sig.toHex());
|
||||
TRACEF("Token::encrypt: sig: %s", sig.toHex().c_str());
|
||||
Bytes token(signed_parts + sig);
|
||||
DEBUG("Token::encrypt: token length: " + std::to_string(token.size()));
|
||||
DEBUGF("Token::encrypt: token length: %zu", token.size());
|
||||
return token;
|
||||
}
|
||||
|
||||
|
||||
const Bytes Token::decrypt(const Bytes& token) {
|
||||
|
||||
DEBUG("Token::decrypt: token length: " + std::to_string(token.size()));
|
||||
DEBUGF("Token::decrypt: token length: %zu", token.size());
|
||||
if (token.size() < 48) {
|
||||
throw std::invalid_argument("Cannot decrypt token of only " + std::to_string(token.size()) + " bytes");
|
||||
}
|
||||
@@ -117,11 +117,11 @@ const Bytes Token::decrypt(const Bytes& token) {
|
||||
|
||||
//iv = token[:16]
|
||||
Bytes iv = token.left(16);
|
||||
TRACE("Token::decrypt: iv: " + iv.toHex());
|
||||
TRACEF("Token::decrypt: iv: %s", iv.toHex().c_str());
|
||||
|
||||
//ciphertext = token[16:-32]
|
||||
Bytes ciphertext = token.mid(16, token.size()-48);
|
||||
TRACE("Token::decrypt: ciphertext: " + ciphertext.toHex());
|
||||
TRACEF("Token::decrypt: ciphertext: %s", ciphertext.toHex().c_str());
|
||||
|
||||
try {
|
||||
Bytes plaintext;
|
||||
@@ -146,10 +146,10 @@ const Bytes Token::decrypt(const Bytes& token) {
|
||||
else {
|
||||
throw new std::invalid_argument("Invalid token mode "+std::to_string(_mode));
|
||||
}
|
||||
DEBUG("Token::encrypt: unpadded plaintext length: " + std::to_string(plaintext.size()));
|
||||
TRACE("Token::decrypt: plaintext: " + plaintext.toHex());
|
||||
DEBUGF("Token::encrypt: unpadded plaintext length: %zu", plaintext.size());
|
||||
TRACEF("Token::decrypt: plaintext: %s", plaintext.toHex().c_str());
|
||||
|
||||
DEBUG("Token::decrypt: plaintext length: " + std::to_string(plaintext.size()));
|
||||
DEBUGF("Token::decrypt: plaintext length: %zu", plaintext.size());
|
||||
return plaintext;
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
|
||||
+10
-10
@@ -170,26 +170,26 @@ namespace RNS { namespace Cryptography {
|
||||
}
|
||||
*/
|
||||
inline const Bytes exchange(const Bytes& peer_public_key) {
|
||||
DEBUG("X25519PublicKey::exchange: public key: " + _publicKey.toHex());
|
||||
DEBUG("X25519PublicKey::exchange: peer public key: " + peer_public_key.toHex());
|
||||
DEBUG("X25519PublicKey::exchange: pre private key: " + _privateKey.toHex());
|
||||
DEBUGF("X25519PublicKey::exchange: public key: %s", _publicKey.toHex().c_str());
|
||||
DEBUGF("X25519PublicKey::exchange: peer public key: %s", peer_public_key.toHex().c_str());
|
||||
DEBUGF("X25519PublicKey::exchange: pre private key: %s", _privateKey.toHex().c_str());
|
||||
Bytes sharedKey;
|
||||
if (!Curve25519::eval(sharedKey.writable(32), _privateKey.data(), peer_public_key.data())) {
|
||||
throw std::runtime_error("Peer key is invalid");
|
||||
}
|
||||
DEBUG("X25519PublicKey::exchange: shared key: " + sharedKey.toHex());
|
||||
DEBUG("X25519PublicKey::exchange: post private key: " + _privateKey.toHex());
|
||||
DEBUGF("X25519PublicKey::exchange: shared key: %s", sharedKey.toHex().c_str());
|
||||
DEBUGF("X25519PublicKey::exchange: post private key: %s", _privateKey.toHex().c_str());
|
||||
return sharedKey;
|
||||
}
|
||||
|
||||
inline bool verify(const Bytes& peer_public_key) {
|
||||
DEBUG("X25519PublicKey::exchange: public key: " + _publicKey.toHex());
|
||||
DEBUG("X25519PublicKey::exchange: peer public key: " + peer_public_key.toHex());
|
||||
DEBUG("X25519PublicKey::exchange: pre private key: " + _privateKey.toHex());
|
||||
DEBUGF("X25519PublicKey::exchange: public key: %s", _publicKey.toHex().c_str());
|
||||
DEBUGF("X25519PublicKey::exchange: peer public key: %s", peer_public_key.toHex().c_str());
|
||||
DEBUGF("X25519PublicKey::exchange: pre private key: %s", _privateKey.toHex().c_str());
|
||||
Bytes sharedKey(peer_public_key);
|
||||
bool success = Curve25519::dh2(sharedKey.writable(32), _privateKey.writable(32));
|
||||
DEBUG("X25519PublicKey::exchange: shared key: " + sharedKey.toHex());
|
||||
DEBUG("X25519PublicKey::exchange: post private key: " + _privateKey.toHex());
|
||||
DEBUGF("X25519PublicKey::exchange: shared key: %s", sharedKey.toHex().c_str());
|
||||
DEBUGF("X25519PublicKey::exchange: post private key: %s", _privateKey.toHex().c_str());
|
||||
return success;
|
||||
}
|
||||
|
||||
|
||||
+136
-110
@@ -15,13 +15,13 @@ using namespace RNS::Utilities;
|
||||
|
||||
Destination::Destination(const Identity& identity, const directions direction, const types type, const char* app_name, const char* aspects) : _object(new Object(identity)) {
|
||||
assert(_object);
|
||||
MEM("Destination object creating..., this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Destination object creating..., this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
|
||||
// Check input values and build name string
|
||||
if (strchr(app_name, '.') != nullptr) {
|
||||
throw std::invalid_argument("Dots can't be used in app names");
|
||||
}
|
||||
//TRACE("Destination::Destination: app name: " + std::string(app_name));
|
||||
//TRACEF("Destination::Destination: app name: %s", app_name);
|
||||
|
||||
_object->_type = type;
|
||||
_object->_direction = direction;
|
||||
@@ -33,34 +33,34 @@ Destination::Destination(const Identity& identity, const directions direction, c
|
||||
// CBA TODO determine why identity.hexhash is added both here and by expand_name called below
|
||||
fullaspects += "." + _object->_identity.hexhash();
|
||||
}
|
||||
//TRACE("Destination::Destination: full aspects: " + fullaspects);
|
||||
//TRACEF("Destination::Destination: full aspects: %s", fullaspects.c_str());
|
||||
|
||||
if (_object->_identity && _object->_type == PLAIN) {
|
||||
throw std::invalid_argument("Selected destination type PLAIN cannot hold an identity");
|
||||
}
|
||||
|
||||
_object->_name = expand_name(_object->_identity, app_name, fullaspects.c_str());
|
||||
//TRACE("Destination::Destination: name: " + _object->_name);
|
||||
//TRACEF("Destination::Destination: name: %s", _object->_name.c_str());
|
||||
|
||||
// Generate the destination address hash
|
||||
//TRACE("Destination::Destination: creating hash...");
|
||||
_object->_hash = hash(_object->_identity, app_name, fullaspects.c_str());
|
||||
_object->_hexhash = _object->_hash.toHex();
|
||||
TRACE("Destination::Destination: hash: " + _object->_hash.toHex());
|
||||
TRACEF("Destination::Destination: hash: %s", _object->_hash.toHex().c_str());
|
||||
//TRACE("Destination::Destination: creating name hash...");
|
||||
//p self.name_hash = RNS.Identity.full_hash(self.expand_name(None, app_name, *aspects).encode("utf-8"))[:(RNS.Identity.NAME_HASH_LENGTH//8)]
|
||||
_object->_name_hash = name_hash(app_name, aspects);
|
||||
//TRACE("Destination::Destination: name hash: " + _object->_name_hash.toHex());
|
||||
//TRACEF("Destination::Destination: name hash: %s", _object->_name_hash.toHex().c_str());
|
||||
|
||||
//TRACE("Destination::Destination: calling register_destination");
|
||||
Transport::register_destination(*this);
|
||||
|
||||
MEM("Destination object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Destination object created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
|
||||
Destination::Destination(const Identity& identity, const Type::Destination::directions direction, const Type::Destination::types type, const Bytes& hash) : _object(new Object(identity)) {
|
||||
assert(_object);
|
||||
MEM("Destination object creating..., this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Destination object creating..., this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
|
||||
_object->_type = type;
|
||||
_object->_direction = direction;
|
||||
@@ -71,20 +71,20 @@ Destination::Destination(const Identity& identity, const Type::Destination::dire
|
||||
|
||||
_object->_hash = hash;
|
||||
_object->_hexhash = _object->_hash.toHex();
|
||||
TRACE("Destination::Destination: hash: " + _object->_hash.toHex());
|
||||
TRACEF("Destination::Destination: hash: %s", _object->_hash.toHex().c_str());
|
||||
//TRACE("Destination::Destination: creating name hash...");
|
||||
//p self.name_hash = RNS.Identity.full_hash(self.expand_name(None, app_name, *aspects).encode("utf-8"))[:(RNS.Identity.NAME_HASH_LENGTH//8)]
|
||||
_object->_name_hash = name_hash("unknown", "unknown");
|
||||
//TRACE("Destination::Destination: name hash: " + _object->_name_hash.toHex());
|
||||
//TRACEF("Destination::Destination: name hash: %s", _object->_name_hash.toHex().c_str());
|
||||
|
||||
//TRACE("Destination::Destination: calling register_destination");
|
||||
Transport::register_destination(*this);
|
||||
|
||||
MEM("Destination object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Destination object created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
|
||||
/*virtual*/ Destination::~Destination() {
|
||||
MEM("Destination object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Destination object destroyed, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
if (_object && _object.use_count() == 1) {
|
||||
MEM("Destination object has last data reference");
|
||||
|
||||
@@ -194,117 +194,135 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In
|
||||
throw std::invalid_argument("Only IN destination types can be announced");
|
||||
}
|
||||
|
||||
double now = OS::time();
|
||||
auto it = _object->_path_responses.begin();
|
||||
while (it != _object->_path_responses.end()) {
|
||||
// vector
|
||||
//Response& entry = *it;
|
||||
// map
|
||||
PathResponse& entry = (*it).second;
|
||||
if (now > (entry.first + PR_TAG_WINDOW)) {
|
||||
it = _object->_path_responses.erase(it);
|
||||
try {
|
||||
double now = OS::time();
|
||||
auto it = _object->_path_responses.begin();
|
||||
while (it != _object->_path_responses.end()) {
|
||||
// vector
|
||||
//Response& entry = *it;
|
||||
// map
|
||||
PathResponse& entry = (*it).second;
|
||||
if (now > (entry.first + PR_TAG_WINDOW)) {
|
||||
it = _object->_path_responses.erase(it);
|
||||
}
|
||||
else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
Bytes announce_data;
|
||||
Bytes announce_data;
|
||||
|
||||
/*
|
||||
// CBA TEST
|
||||
TRACE("Destination::announce: performing path test...");
|
||||
TRACE("Destination::announce: inserting path...");
|
||||
_object->_path_responses.insert({Bytes("foo_tag"), {0, Bytes("this is foo tag")}});
|
||||
TRACE("Destination::announce: inserting path...");
|
||||
_object->_path_responses.insert({Bytes("test_tag"), {0, Bytes("this is test tag")}});
|
||||
if (path_response) {
|
||||
TRACE("Destination::announce: path_response is true");
|
||||
}
|
||||
if (!tag.empty()) {
|
||||
TRACE("Destination::announce: tag is specified");
|
||||
std::string tagstr((const char*)tag.data(), tag.size());
|
||||
DEBUG(std::string("Destination::announce: tag: ") + tagstr);
|
||||
DEBUG(std::string("Destination::announce: tag len: ") + std::to_string(tag.size()));
|
||||
TRACE("Destination::announce: searching for tag...");
|
||||
if (_object->_path_responses.find(tag) != _object->_path_responses.end()) {
|
||||
TRACE("Destination::announce: found tag in _path_responses");
|
||||
DEBUG(std::string("Destination::announce: data: ") +_object->_path_responses[tag].second.toString());
|
||||
// CBA TEST
|
||||
TRACE("Destination::announce: performing path test...");
|
||||
TRACE("Destination::announce: inserting path...");
|
||||
_object->_path_responses.insert({Bytes("foo_tag"), {0, Bytes("this is foo tag")}});
|
||||
TRACE("Destination::announce: inserting path...");
|
||||
_object->_path_responses.insert({Bytes("test_tag"), {0, Bytes("this is test tag")}});
|
||||
if (path_response) {
|
||||
TRACE("Destination::announce: path_response is true");
|
||||
}
|
||||
else {
|
||||
TRACE("Destination::announce: tag not found in _path_responses");
|
||||
if (!tag.empty()) {
|
||||
TRACE("Destination::announce: tag is specified");
|
||||
std::string tagstr((const char*)tag.data(), tag.size());
|
||||
DEBUGF("Destination::announce: tag: %s", tagstr.c_str());
|
||||
DEBUGF("Destination::announce: tag len: %zu", tag.size());
|
||||
TRACE("Destination::announce: searching for tag...");
|
||||
if (_object->_path_responses.find(tag) != _object->_path_responses.end()) {
|
||||
TRACE("Destination::announce: found tag in _path_responses");
|
||||
DEBUGF("Destination::announce: data: %s", _object->_path_responses[tag].second.toString().c_str());
|
||||
}
|
||||
else {
|
||||
TRACE("Destination::announce: tag not found in _path_responses");
|
||||
}
|
||||
}
|
||||
}
|
||||
TRACE("Destination::announce: path test finished");
|
||||
TRACE("Destination::announce: path test finished");
|
||||
*/
|
||||
|
||||
if (path_response && !tag.empty() && _object->_path_responses.find(tag) != _object->_path_responses.end()) {
|
||||
// This code is currently not used, since Transport will block duplicate
|
||||
// path requests based on tags. When multi-path support is implemented in
|
||||
// Transport, this will allow Transport to detect redundant paths to the
|
||||
// same destination, and select the best one based on chosen criteria,
|
||||
// since it will be able to detect that a single emitted announce was
|
||||
// received via multiple paths. The difference in reception time will
|
||||
// potentially also be useful in determining characteristics of the
|
||||
// multiple available paths, and to choose the best one.
|
||||
//z TRACE("Using cached announce data for answering path request with tag "+RNS.prettyhexrep(tag));
|
||||
announce_data << _object->_path_responses[tag].second;
|
||||
}
|
||||
else {
|
||||
Bytes destination_hash = _object->_hash;
|
||||
//p random_hash = Identity::get_random_hash()[0:5] << int(time.time()).to_bytes(5, "big")
|
||||
// CBA TODO add in time to random hash
|
||||
Bytes random_hash = Cryptography::random(Type::Identity::RANDOM_HASH_LENGTH/8);
|
||||
if (path_response && !tag.empty() && _object->_path_responses.find(tag) != _object->_path_responses.end()) {
|
||||
// This code is currently not used, since Transport will block duplicate
|
||||
// path requests based on tags. When multi-path support is implemented in
|
||||
// Transport, this will allow Transport to detect redundant paths to the
|
||||
// same destination, and select the best one based on chosen criteria,
|
||||
// since it will be able to detect that a single emitted announce was
|
||||
// received via multiple paths. The difference in reception time will
|
||||
// potentially also be useful in determining characteristics of the
|
||||
// multiple available paths, and to choose the best one.
|
||||
//z TRACEF("Using cached announce data for answering path request with tag %s", RNS.prettyhexrep(tag).c_str());
|
||||
announce_data << _object->_path_responses[tag].second;
|
||||
}
|
||||
else {
|
||||
Bytes destination_hash = _object->_hash;
|
||||
//p random_hash = Identity::get_random_hash()[0:5] << int(time.time()).to_bytes(5, "big")
|
||||
// CBA TODO add in time to random hash
|
||||
Bytes random_hash = Cryptography::random(Type::Identity::RANDOM_HASH_LENGTH/8);
|
||||
|
||||
Bytes new_app_data(app_data);
|
||||
if (new_app_data.empty() && !_object->_default_app_data.empty()) {
|
||||
new_app_data = _object->_default_app_data;
|
||||
Bytes new_app_data(app_data);
|
||||
if (new_app_data.empty() && !_object->_default_app_data.empty()) {
|
||||
new_app_data = _object->_default_app_data;
|
||||
}
|
||||
|
||||
Bytes signed_data;
|
||||
//TRACEF("Destination::announce: hash: %s", _object->_hash.toHex().c_str());
|
||||
//TRACEF("Destination::announce: public key: %s", _object->_identity.get_public_key().toHex().c_str());
|
||||
//TRACEF("Destination::announce: name hash: %s", _object->_name_hash.toHex().c_str());
|
||||
//TRACEF("Destination::announce: random hash: %s", random_hash.toHex().c_str());
|
||||
//TRACEF("Destination::announce: app data: %s", new_app_data.toHex().c_str());
|
||||
//TRACEF("Destination::announce: app data text:%s", new_app_data.toString().c_str());
|
||||
signed_data << _object->_hash << _object->_identity.get_public_key() << _object->_name_hash << random_hash;
|
||||
if (new_app_data) {
|
||||
signed_data << new_app_data;
|
||||
}
|
||||
//TRACEF("Destination::announce: signed data: %s", signed_data.toHex().c_str());
|
||||
|
||||
Bytes signature(_object->_identity.sign(signed_data));
|
||||
//TRACEF("Destination::announce: signature: %s", signature.toHex().c_str());
|
||||
|
||||
announce_data << _object->_identity.get_public_key() << _object->_name_hash << random_hash << signature;
|
||||
|
||||
if (new_app_data) {
|
||||
announce_data << new_app_data;
|
||||
}
|
||||
|
||||
// CBA ACCUMULATES
|
||||
try {
|
||||
_object->_path_responses.insert({tag, {OS::time(), announce_data}});
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERRORF("announce: bad_alloc - OUT OF MEMORY, path response not stored for %s", _object->_hash.toHex().c_str());
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("announce: exception storing path response: %s", e.what());
|
||||
}
|
||||
}
|
||||
//TRACEF("Destination::announce: announce_data:%s", announce_data.toHex().c_str());
|
||||
|
||||
Type::Packet::context_types announce_context = Type::Packet::CONTEXT_NONE;
|
||||
if (path_response) {
|
||||
announce_context = Type::Packet::PATH_RESPONSE;
|
||||
}
|
||||
|
||||
Bytes signed_data;
|
||||
//TRACE("Destination::announce: hash: " + _object->_hash.toHex());
|
||||
//TRACE("Destination::announce: public key: " + _object->_identity.get_public_key().toHex());
|
||||
//TRACE("Destination::announce: name hash: " + _object->_name_hash.toHex());
|
||||
//TRACE("Destination::announce: random hash: " + random_hash.toHex());
|
||||
//TRACE("Destination::announce: app data: " + new_app_data.toHex());
|
||||
//TRACE("Destination::announce: app data text:" + new_app_data.toString());
|
||||
signed_data << _object->_hash << _object->_identity.get_public_key() << _object->_name_hash << random_hash;
|
||||
if (new_app_data) {
|
||||
signed_data << new_app_data;
|
||||
//TRACE("Destination::announce: creating announce packet...");
|
||||
//p announce_packet = RNS.Packet(self, announce_data, RNS.Packet.ANNOUNCE, context = announce_context, attached_interface = attached_interface)
|
||||
//Packet announce_packet(*this, announce_data, Type::Packet::ANNOUNCE, announce_context, Type::Transport::BROADCAST, Type::Packet::HEADER_1, nullptr, attached_interface);
|
||||
Packet announce_packet(*this, attached_interface, announce_data, Type::Packet::ANNOUNCE, announce_context, Type::Transport::BROADCAST, Type::Packet::HEADER_1);
|
||||
|
||||
if (send) {
|
||||
TRACE("Destination::announce: sending announce packet...");
|
||||
announce_packet.send();
|
||||
return {Type::NONE};
|
||||
}
|
||||
//TRACE("Destination::announce: signed data: " + signed_data.toHex());
|
||||
|
||||
Bytes signature(_object->_identity.sign(signed_data));
|
||||
//TRACE("Destination::announce: signature: " + signature.toHex());
|
||||
|
||||
announce_data << _object->_identity.get_public_key() << _object->_name_hash << random_hash << signature;
|
||||
|
||||
if (new_app_data) {
|
||||
announce_data << new_app_data;
|
||||
else {
|
||||
return announce_packet;
|
||||
}
|
||||
|
||||
// CBA ACCUMULATES
|
||||
_object->_path_responses.insert({tag, {OS::time(), announce_data}});
|
||||
}
|
||||
//TRACE("Destination::announce: announce_data:" + announce_data.toHex());
|
||||
|
||||
Type::Packet::context_types announce_context = Type::Packet::CONTEXT_NONE;
|
||||
if (path_response) {
|
||||
announce_context = Type::Packet::PATH_RESPONSE;
|
||||
}
|
||||
|
||||
//TRACE("Destination::announce: creating announce packet...");
|
||||
//p announce_packet = RNS.Packet(self, announce_data, RNS.Packet.ANNOUNCE, context = announce_context, attached_interface = attached_interface)
|
||||
//Packet announce_packet(*this, announce_data, Type::Packet::ANNOUNCE, announce_context, Type::Transport::BROADCAST, Type::Packet::HEADER_1, nullptr, attached_interface);
|
||||
Packet announce_packet(*this, attached_interface, announce_data, Type::Packet::ANNOUNCE, announce_context, Type::Transport::BROADCAST, Type::Packet::HEADER_1);
|
||||
|
||||
if (send) {
|
||||
TRACE("Destination::announce: sending announce packet...");
|
||||
announce_packet.send();
|
||||
catch (const std::bad_alloc&) {
|
||||
ERRORF("announce: bad_alloc - OUT OF MEMORY, announce not sent for %s", _object->_hash.toHex().c_str());
|
||||
return {Type::NONE};
|
||||
}
|
||||
else {
|
||||
return announce_packet;
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("announce: exception during announce: %s", e.what());
|
||||
return {Type::NONE};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,7 +381,7 @@ void Destination::receive(const Packet& packet) {
|
||||
else {
|
||||
// CBA TODO Why isn't the Packet decrypting itself?
|
||||
Bytes plaintext(decrypt(packet.data()));
|
||||
//TRACE("Destination::receive: decrypted data: " + plaintext.toHex());
|
||||
//TRACEF("Destination::receive: decrypted data: %s", plaintext.toHex().c_str());
|
||||
if (plaintext) {
|
||||
if (packet.packet_type() == Type::Packet::DATA) {
|
||||
if (_object->_callbacks._packet) {
|
||||
@@ -371,7 +389,7 @@ void Destination::receive(const Packet& packet) {
|
||||
_object->_callbacks._packet(plaintext, packet);
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
DEBUG("Error while executing receive callback from " + toString() + ". The contained exception was: " + e.what());
|
||||
DEBUGF("Error while executing receive callback from %s. The contained exception was: %s", toString().c_str(), e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -385,7 +403,15 @@ void Destination::incoming_link_request(const Bytes& data, const Packet& packet)
|
||||
TRACE("***** Accepting link request");
|
||||
RNS::Link link = Link::validate_request(*this, data, packet);
|
||||
if (link) {
|
||||
_object->_links.insert(link);
|
||||
try {
|
||||
_object->_links.insert(link);
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERROR("incoming_link_request: bad_alloc - OUT OF MEMORY, link not tracked");
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("incoming_link_request: exception tracking link: %s", e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+5
-5
@@ -73,10 +73,10 @@ namespace RNS {
|
||||
|
||||
public:
|
||||
Destination(Type::NoneConstructor none) {
|
||||
MEM("Destination NONE object created, this: " + std::to_string((uintptr_t)this));
|
||||
MEMF("Destination NONE object created, this: %p", (void*)this);
|
||||
}
|
||||
Destination(const Destination& destination) : _object(destination._object) {
|
||||
MEM("Destination object copy created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Destination object copy created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
Destination(
|
||||
const Identity& identity,
|
||||
@@ -95,7 +95,7 @@ namespace RNS {
|
||||
|
||||
inline Destination& operator = (const Destination& destination) {
|
||||
_object = destination._object;
|
||||
MEM("Destination object copy created by assignment, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Destination object copy created by assignment, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
return *this;
|
||||
}
|
||||
inline operator bool() const {
|
||||
@@ -212,8 +212,8 @@ namespace RNS {
|
||||
private:
|
||||
class Object {
|
||||
public:
|
||||
Object(const Identity& identity) : _identity(identity) { MEM("Destination::Data object created, this: " + std::to_string((uintptr_t)this)); }
|
||||
virtual ~Object() { MEM("Destination::Data object destroyed, this: " + std::to_string((uintptr_t)this)); }
|
||||
Object(const Identity& identity) : _identity(identity) { MEMF("Destination::Data object created, this: %p", (void*)this); }
|
||||
virtual ~Object() { MEMF("Destination::Data object destroyed, this: %p", (void*)this); }
|
||||
private:
|
||||
bool _accept_link_requests = true;
|
||||
Callbacks _callbacks;
|
||||
|
||||
+12
-2
@@ -8,12 +8,19 @@
|
||||
#include <list>
|
||||
#include <memory>
|
||||
#include <cassert>
|
||||
#include <functional>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace RNS {
|
||||
|
||||
class FileSystemImpl {
|
||||
|
||||
public:
|
||||
struct Callbacks {
|
||||
//using DirectoryListing = void(*)(const char* file_name);
|
||||
using DirectoryListing = std::function<void(const char*)>;
|
||||
};
|
||||
|
||||
protected:
|
||||
FileSystemImpl() { MEMF("FileSystem::FileSystemImpl object created, this: 0x%X", this); }
|
||||
public:
|
||||
@@ -31,7 +38,7 @@ namespace RNS {
|
||||
virtual bool directory_exists(const char* directory_path) = 0;
|
||||
virtual bool create_directory(const char* directory_path) = 0;
|
||||
virtual bool remove_directory(const char* directory_path) = 0;
|
||||
virtual std::list<std::string> list_directory(const char* directory_path) = 0;
|
||||
virtual std::list<std::string> list_directory(const char* directory_path, Callbacks::DirectoryListing callback = nullptr) = 0;
|
||||
virtual size_t storage_size() = 0;
|
||||
virtual size_t storage_available() = 0;
|
||||
|
||||
@@ -40,6 +47,9 @@ namespace RNS {
|
||||
|
||||
class FileSystem {
|
||||
|
||||
public:
|
||||
using Callbacks = FileSystemImpl::Callbacks;
|
||||
|
||||
public:
|
||||
FileSystem(Type::NoneConstructor none) {
|
||||
MEMF("FileSystem NONE object created, this: 0x%X, impl: 0x%X", this, _impl.get());
|
||||
@@ -103,7 +113,7 @@ namespace RNS {
|
||||
inline bool directory_exists(const char* directory_path) { assert(_impl); return _impl->directory_exists(directory_path); }
|
||||
inline bool create_directory(const char* directory_path) { assert(_impl); return _impl->create_directory(directory_path); }
|
||||
inline bool remove_directory(const char* directory_path) { assert(_impl); return _impl->remove_directory(directory_path); }
|
||||
inline std::list<std::string> list_directory(const char* directory_path) { assert(_impl); return _impl->list_directory(directory_path); }
|
||||
inline std::list<std::string> list_directory(const char* directory_path, Callbacks::DirectoryListing callback = nullptr) { assert(_impl); return _impl->list_directory(directory_path, callback); }
|
||||
inline size_t storage_size() { assert(_impl); return _impl->storage_size(); }
|
||||
inline size_t storage_available() { assert(_impl); return _impl->storage_available(); }
|
||||
|
||||
|
||||
+113
-91
@@ -19,18 +19,21 @@ using namespace RNS::Type::Identity;
|
||||
using namespace RNS::Cryptography;
|
||||
using namespace RNS::Utilities;
|
||||
|
||||
/*static*/ std::map<Bytes, Identity::IdentityEntry> Identity::_known_destinations;
|
||||
#ifndef RNS_KNOWN_DESTINATIONS_MAX
|
||||
#define RNS_KNOWN_DESTINATIONS_MAX 100
|
||||
#endif
|
||||
|
||||
/*static*/ Identity::IdentityTable Identity::_known_destinations;
|
||||
/*static*/ bool Identity::_saving_known_destinations = false;
|
||||
// CBA
|
||||
// CBA ACCUMULATES
|
||||
/*static*/ //uint16_t Identity::_known_destinations_maxsize = 100;
|
||||
/*static*/ uint16_t Identity::_known_destinations_maxsize = 100;
|
||||
/*static*/ uint16_t Identity::_known_destinations_maxsize = RNS_KNOWN_DESTINATIONS_MAX;
|
||||
|
||||
Identity::Identity(bool create_keys /*= true*/) : _object(new Object()) {
|
||||
if (create_keys) {
|
||||
createKeys();
|
||||
}
|
||||
MEM("Identity object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Identity object created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
|
||||
void Identity::createKeys() {
|
||||
@@ -39,26 +42,26 @@ void Identity::createKeys() {
|
||||
// CRYPTO: create encryption private keys
|
||||
_object->_prv = Cryptography::X25519PrivateKey::generate();
|
||||
_object->_prv_bytes = _object->_prv->private_bytes();
|
||||
//TRACE("Identity::createKeys: prv bytes: " + _object->_prv_bytes.toHex());
|
||||
//TRACEF("Identity::createKeys: prv bytes: %s", _object->_prv_bytes.toHex().c_str());
|
||||
|
||||
// CRYPTO: create signature private keys
|
||||
_object->_sig_prv = Cryptography::Ed25519PrivateKey::generate();
|
||||
_object->_sig_prv_bytes = _object->_sig_prv->private_bytes();
|
||||
//TRACE("Identity::createKeys: sig prv bytes: " + _object->_sig_prv_bytes.toHex());
|
||||
//TRACEF("Identity::createKeys: sig prv bytes: %s", _object->_sig_prv_bytes.toHex().c_str());
|
||||
|
||||
// CRYPTO: create encryption public keys
|
||||
_object->_pub = _object->_prv->public_key();
|
||||
_object->_pub_bytes = _object->_pub->public_bytes();
|
||||
//TRACE("Identity::createKeys: pub bytes: " + _object->_pub_bytes.toHex());
|
||||
//TRACEF("Identity::createKeys: pub bytes: %s", _object->_pub_bytes.toHex().c_str());
|
||||
|
||||
// CRYPTO: create signature public keys
|
||||
_object->_sig_pub = _object->_sig_prv->public_key();
|
||||
_object->_sig_pub_bytes = _object->_sig_pub->public_bytes();
|
||||
//TRACE("Identity::createKeys: sig pub bytes: " + _object->_sig_pub_bytes.toHex());
|
||||
//TRACEF("Identity::createKeys: sig pub bytes: %s", _object->_sig_pub_bytes.toHex().c_str());
|
||||
|
||||
update_hashes();
|
||||
|
||||
VERBOSE("Identity keys created for " + _object->_hash.toHex());
|
||||
VERBOSEF("Identity keys created for %s", _object->_hash.toHex().c_str());
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -75,20 +78,20 @@ bool Identity::load_private_key(const Bytes& prv_bytes) {
|
||||
//p self.prv_bytes = prv_bytes[:Identity.KEYSIZE//8//2]
|
||||
_object->_prv_bytes = prv_bytes.left(Type::Identity::KEYSIZE/8/2);
|
||||
_object->_prv = X25519PrivateKey::from_private_bytes(_object->_prv_bytes);
|
||||
//TRACE("Identity::load_private_key: prv bytes: " + _object->_prv_bytes.toHex());
|
||||
//TRACEF("Identity::load_private_key: prv bytes: %s", _object->_prv_bytes.toHex().c_str());
|
||||
|
||||
//p self.sig_prv_bytes = prv_bytes[Identity.KEYSIZE//8//2:]
|
||||
_object->_sig_prv_bytes = prv_bytes.mid(Type::Identity::KEYSIZE/8/2);
|
||||
_object->_sig_prv = Ed25519PrivateKey::from_private_bytes(_object->_sig_prv_bytes);
|
||||
//TRACE("Identity::load_private_key: sig prv bytes: " + _object->_sig_prv_bytes.toHex());
|
||||
//TRACEF("Identity::load_private_key: sig prv bytes: %s", _object->_sig_prv_bytes.toHex().c_str());
|
||||
|
||||
_object->_pub = _object->_prv->public_key();
|
||||
_object->_pub_bytes = _object->_pub->public_bytes();
|
||||
//TRACE("Identity::load_private_key: pub bytes: " + _object->_pub_bytes.toHex());
|
||||
//TRACEF("Identity::load_private_key: pub bytes: %s", _object->_pub_bytes.toHex().c_str());
|
||||
|
||||
_object->_sig_pub = _object->_sig_prv->public_key();
|
||||
_object->_sig_pub_bytes = _object->_sig_pub->public_bytes();
|
||||
//TRACE("Identity::load_private_key: sig pub bytes: " + _object->_sig_pub_bytes.toHex());
|
||||
//TRACEF("Identity::load_private_key: sig pub bytes: %s", _object->_sig_pub_bytes.toHex().c_str());
|
||||
|
||||
update_hashes();
|
||||
|
||||
@@ -115,11 +118,11 @@ void Identity::load_public_key(const Bytes& pub_bytes) {
|
||||
|
||||
//_pub_bytes = pub_bytes[:Identity.KEYSIZE//8//2]
|
||||
_object->_pub_bytes = pub_bytes.left(Type::Identity::KEYSIZE/8/2);
|
||||
//TRACE("Identity::load_public_key: pub bytes: " + _object->_pub_bytes.toHex());
|
||||
//TRACEF("Identity::load_public_key: pub bytes: ", _object->_pub_bytes.toHex().c_str());
|
||||
|
||||
//_sig_pub_bytes = pub_bytes[Identity.KEYSIZE//8//2:]
|
||||
_object->_sig_pub_bytes = pub_bytes.mid(Type::Identity::KEYSIZE/8/2);
|
||||
//TRACE("Identity::load_public_key: sig pub bytes: " + _object->_sig_pub_bytes.toHex());
|
||||
//TRACEF("Identity::load_public_key: sig pub bytes: ", _object->_sig_pub_bytes.toHex().c_str());
|
||||
|
||||
_object->_pub = X25519PublicKey::from_public_bytes(_object->_pub_bytes);
|
||||
_object->_sig_pub = Ed25519PublicKey::from_public_bytes(_object->_sig_pub_bytes);
|
||||
@@ -144,7 +147,7 @@ bool Identity::load(const char* path) {
|
||||
}
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERROR("Error while loading identity from " + std::string(path));
|
||||
ERRORF("Error while loading identity from %s", path);
|
||||
ERRORF("The contained exception was: %s", e.what());
|
||||
}
|
||||
#endif
|
||||
@@ -196,7 +199,17 @@ Can be used to load previously created and saved identities into Reticulum.
|
||||
else {
|
||||
//p _known_destinations[destination_hash] = {OS::time(), packet_hash, public_key, app_data};
|
||||
// CBA ACCUMULATES
|
||||
_known_destinations.insert({destination_hash, {OS::time(), packet_hash, public_key, app_data}});
|
||||
try {
|
||||
_known_destinations.insert({destination_hash, {OS::time(), packet_hash, public_key, app_data}});
|
||||
// CBA IMMEDIATE CULL
|
||||
cull_known_destinations();
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERRORF("remember: bad_alloc - OUT OF MEMORY, identity not stored for %s", destination_hash.toHex().c_str());
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("remember: exception storing identity: %s", e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,7 +223,7 @@ Recall identity for a destination hash.
|
||||
TRACE("Identity::recall...");
|
||||
auto iter = _known_destinations.find(destination_hash);
|
||||
if (iter != _known_destinations.end()) {
|
||||
TRACE("Identity::recall: Found identity entry for destination " + destination_hash.toHex());
|
||||
TRACEF("Identity::recall: Found identity entry for destination %s", destination_hash.toHex().c_str());
|
||||
const IdentityEntry& identity_data = (*iter).second;
|
||||
Identity identity(false);
|
||||
identity.load_public_key(identity_data._public_key);
|
||||
@@ -218,16 +231,16 @@ Recall identity for a destination hash.
|
||||
return identity;
|
||||
}
|
||||
else {
|
||||
TRACE("Identity::recall: Unable to find identity entry for destination " + destination_hash.toHex() + ", performing destination lookup...");
|
||||
TRACEF("Identity::recall: Unable to find identity entry for destination %s, performing destination lookup...", destination_hash.toHex().c_str());
|
||||
Destination registered_destination(Transport::find_destination_from_hash(destination_hash));
|
||||
if (registered_destination) {
|
||||
TRACE("Identity::recall: Found destination " + destination_hash.toHex());
|
||||
TRACEF("Identity::recall: Found destination %s", destination_hash.toHex().c_str());
|
||||
Identity identity(false);
|
||||
identity.load_public_key(registered_destination.identity().get_public_key());
|
||||
identity.app_data({Bytes::NONE});
|
||||
return identity;
|
||||
}
|
||||
TRACE("Identity::recall: Unable to find destination " + destination_hash.toHex());
|
||||
TRACEF("Identity::recall: Unable to find destination %s", destination_hash.toHex().c_str());
|
||||
return {Type::NONE};
|
||||
}
|
||||
}
|
||||
@@ -242,12 +255,12 @@ Recall last heard app_data for a destination hash.
|
||||
TRACE("Identity::recall_app_data...");
|
||||
auto iter = _known_destinations.find(destination_hash);
|
||||
if (iter != _known_destinations.end()) {
|
||||
TRACE("Identity::recall_app_data: Found identity entry for destination " + destination_hash.toHex());
|
||||
TRACEF("Identity::recall_app_data: Found identity entry for destination %s", destination_hash.toHex().c_str());
|
||||
const IdentityEntry& identity_data = (*iter).second;
|
||||
return identity_data._app_data;
|
||||
}
|
||||
else {
|
||||
TRACE("Identity::recall_app_data: Unable to find identity entry for destination " + destination_hash.toHex());
|
||||
TRACEF("Identity::recall_app_data: Unable to find identity entry for destination %s", destination_hash.toHex().c_str());
|
||||
return {Bytes::NONE};
|
||||
}
|
||||
}
|
||||
@@ -295,28 +308,20 @@ Recall last heard app_data for a destination hash.
|
||||
//_known_destinations[destination_hash] = identity_entry;
|
||||
// CBA ACCUMULATES
|
||||
_known_destinations.insert({destination_hash, identity_entry});
|
||||
// CBA IMMEDIATE CULL
|
||||
cull_known_destinations();
|
||||
}
|
||||
}
|
||||
|
||||
// TODO
|
||||
/*
|
||||
DEBUG("Saving " + std::to_string(_known_destinations.size()) + " known destinations to storage...");
|
||||
DEBUGF("Saving %zu known destinations to storage...", _known_destinations.size());
|
||||
file = open(RNS.Reticulum.storagepath+"/known_destinations","wb")
|
||||
umsgpack.dump(Identity.known_destinations, file)
|
||||
file.close()
|
||||
DEBUGF("Saved known destinations to storage in %.3f seconds", OS::round(OS::time() - save_start, 3));
|
||||
*/
|
||||
|
||||
std::string time_str;
|
||||
double save_time = OS::time() - save_start;
|
||||
if (save_time < 1) {
|
||||
time_str = std::to_string((int)(save_time*1000)) + " ms";
|
||||
}
|
||||
else {
|
||||
time_str = std::to_string(OS::round(save_time, 1)) + " s";
|
||||
}
|
||||
|
||||
DEBUG("Saved known destinations to storage in " + time_str);
|
||||
|
||||
success = true;
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
@@ -352,32 +357,49 @@ Recall last heard app_data for a destination hash.
|
||||
}
|
||||
|
||||
/*static*/ void Identity::cull_known_destinations() {
|
||||
TRACE("Transport::cull_path_table()");
|
||||
TRACE("Identity::cull_known_destinations()");
|
||||
if (_known_destinations.size() > _known_destinations_maxsize) {
|
||||
// prune by age
|
||||
uint16_t count = 0;
|
||||
std::vector<std::pair<Bytes, IdentityEntry>> sorted_pairs;
|
||||
// Copy key/value pairs from map into vector
|
||||
std::for_each(_known_destinations.begin(), _known_destinations.end(), [&](const std::pair<const Bytes, IdentityEntry>& ref) {
|
||||
sorted_pairs.push_back(ref);
|
||||
});
|
||||
// Sort vector using specified comparator
|
||||
std::sort(sorted_pairs.begin(), sorted_pairs.end(), [](const std::pair<Bytes, IdentityEntry> &left, const std::pair<Bytes, IdentityEntry> &right) {
|
||||
return left.second._timestamp < right.second._timestamp;
|
||||
});
|
||||
// Iterate vector of sorted values
|
||||
for (auto& [destination_hash, identity_entry] : sorted_pairs) {
|
||||
TRACE("Transport::cull_path_table: Removing destination " + destination_hash.toHex() + " from known destinations");
|
||||
// Remove destination from known destinations
|
||||
if (_known_destinations.erase(destination_hash) < 1) {
|
||||
WARNING("Failed to remove destination " + destination_hash.toHex() + " from known destinations");
|
||||
try {
|
||||
// Build lightweight (timestamp, key) index to avoid copying full IdentityEntry
|
||||
// objects — prevents OOM on heap-constrained devices when the table is full.
|
||||
std::vector<std::pair<double, Bytes>> sorted_keys;
|
||||
sorted_keys.reserve(_known_destinations.size());
|
||||
for (const auto& [key, entry] : _known_destinations) {
|
||||
sorted_keys.emplace_back(entry._timestamp, key);
|
||||
}
|
||||
++count;
|
||||
if (_known_destinations.size() <= _known_destinations_maxsize) {
|
||||
break;
|
||||
// Sort ascending by timestamp (oldest first)
|
||||
std::sort(sorted_keys.begin(), sorted_keys.end());
|
||||
|
||||
uint16_t count = 0;
|
||||
for (const auto& [timestamp, destination_hash] : sorted_keys) {
|
||||
TRACEF("Identity::cull_known_destinations: Removing destination %s from known destinations", destination_hash.toHex().c_str());
|
||||
if (_known_destinations.erase(destination_hash) < 1) {
|
||||
WARNINGF("Failed to remove destination %s from known destinations", destination_hash.toHex().c_str());
|
||||
}
|
||||
++count;
|
||||
if (_known_destinations.size() <= _known_destinations_maxsize) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
DEBUGF("Removed %d path(s) from known destinations", count);
|
||||
}
|
||||
catch (const std::bad_alloc& e) {
|
||||
ERROR("cull_known_destinations: bad_alloc - OUT OF MEMORY building sort index, falling back to single erase");
|
||||
// Fallback: std::min_element does no heap allocation — erase one oldest entry
|
||||
auto oldest = std::min_element(
|
||||
_known_destinations.begin(), _known_destinations.end(),
|
||||
[](const std::pair<const Bytes, IdentityEntry>& a,
|
||||
const std::pair<const Bytes, IdentityEntry>& b) {
|
||||
return a.second._timestamp < b.second._timestamp;
|
||||
}
|
||||
);
|
||||
if (oldest != _known_destinations.end()) {
|
||||
_known_destinations.erase(oldest);
|
||||
}
|
||||
}
|
||||
DEBUG("Removed " + std::to_string(count) + " path(s) from known destinations");
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("cull_known_destinations: exception: %s", e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,25 +407,25 @@ Recall last heard app_data for a destination hash.
|
||||
try {
|
||||
if (packet.packet_type() == Type::Packet::ANNOUNCE) {
|
||||
Bytes destination_hash = packet.destination_hash();
|
||||
//TRACE("Identity::validate_announce: destination_hash: " + packet.destination_hash().toHex());
|
||||
//TRACEF("Identity::validate_announce: destination_hash: %s", packet.destination_hash().toHex().c_str());
|
||||
Bytes public_key = packet.data().left(KEYSIZE/8);
|
||||
//TRACE("Identity::validate_announce: public_key: " + public_key.toHex());
|
||||
//TRACEF("Identity::validate_announce: public_key: %s", public_key.toHex().c_str());
|
||||
Bytes name_hash = packet.data().mid(KEYSIZE/8, NAME_HASH_LENGTH/8);
|
||||
//TRACE("Identity::validate_announce: name_hash: " + name_hash.toHex());
|
||||
//TRACEF("Identity::validate_announce: name_hash: %s", name_hash.toHex().c_str());
|
||||
Bytes random_hash = packet.data().mid(KEYSIZE/8 + NAME_HASH_LENGTH/8, RANDOM_HASH_LENGTH/8);
|
||||
//TRACE("Identity::validate_announce: random_hash: " + random_hash.toHex());
|
||||
//TRACEF("Identity::validate_announce: random_hash: %s", random_hash.toHex().c_str());
|
||||
Bytes signature = packet.data().mid(KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8, SIGLENGTH/8);
|
||||
//TRACE("Identity::validate_announce: signature: " + signature.toHex());
|
||||
//TRACEF("Identity::validate_announce: signature: %s", signature.toHex().c_str());
|
||||
Bytes app_data;
|
||||
if (packet.data().size() > (KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8 + SIGLENGTH/8)) {
|
||||
app_data = packet.data().mid(KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8 + SIGLENGTH/8);
|
||||
}
|
||||
//TRACE("Identity::validate_announce: app_data: " + app_data.toHex());
|
||||
//TRACE("Identity::validate_announce: app_data text: " + app_data.toString());
|
||||
//TRACEF("Identity::validate_announce: app_data: %s", app_data.toHex().c_str());
|
||||
//TRACEF("Identity::validate_announce: app_data text: %s", app_data.toString().c_str());
|
||||
|
||||
Bytes signed_data;
|
||||
signed_data << packet.destination_hash() << public_key << name_hash << random_hash+app_data;
|
||||
//TRACE("Identity::validate_announce: signed_data: " + signed_data.toHex());
|
||||
//TRACEF("Identity::validate_announce: signed_data: %s", signed_data.toHex().c_str());
|
||||
|
||||
if (packet.data().size() <= KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8 + SIGLENGTH/8) {
|
||||
app_data.clear();
|
||||
@@ -415,8 +437,8 @@ Recall last heard app_data for a destination hash.
|
||||
if (announced_identity.pub() && announced_identity.validate(signature, signed_data)) {
|
||||
Bytes hash_material = name_hash << announced_identity.hash();
|
||||
Bytes expected_hash = full_hash(hash_material).left(Type::Reticulum::TRUNCATED_HASHLENGTH/8);
|
||||
//TRACE("Identity::validate_announce: destination_hash: " + packet.destination_hash().toHex());
|
||||
//TRACE("Identity::validate_announce: expected_hash: " + expected_hash.toHex());
|
||||
//TRACEF("Identity::validate_announce: destination_hash: %s", packet.destination_hash().toHex().c_str());
|
||||
//TRACEF("Identity::validate_announce: expected_hash: %s", expected_hash.toHex().c_str());
|
||||
|
||||
if (packet.destination_hash() == expected_hash) {
|
||||
// Check if we already have a public key for this destination
|
||||
@@ -453,28 +475,28 @@ Recall last heard app_data for a destination hash.
|
||||
*/
|
||||
|
||||
if (packet.transport_id()) {
|
||||
TRACE("Valid announce for " + packet.destination_hash().toHex() + " " + std::to_string(packet.hops()) + " hops away, received via " + packet.transport_id().toHex() + " on " + packet.receiving_interface().toString() + signal_str);
|
||||
TRACEF("Valid announce for %s %d hops away, received via %s on %s%s", packet.destination_hash().toHex().c_str(), packet.hops(), packet.transport_id().toHex().c_str(), packet.receiving_interface().toString().c_str(), signal_str.c_str());
|
||||
}
|
||||
else {
|
||||
TRACE("Valid announce for " + packet.destination_hash().toHex() + " " + std::to_string(packet.hops()) + " hops away, received on " + packet.receiving_interface().toString() + signal_str);
|
||||
TRACEF("Valid announce for %s %d hops away, received on %s%s", packet.destination_hash().toHex().c_str(), packet.hops(), packet.receiving_interface().toString().c_str(), signal_str.c_str());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
DEBUG("Received invalid announce for " + packet.destination_hash().toHex() + ": Destination mismatch.");
|
||||
DEBUGF("Received invalid announce for %s: Destination mismatch.", packet.destination_hash().toHex().c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else {
|
||||
DEBUG("Received invalid announce for " + packet.destination_hash().toHex() + ": Invalid signature.");
|
||||
DEBUGF("Received invalid announce for %s: Invalid signature.", packet.destination_hash().toHex().c_str());
|
||||
//p del announced_identity
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERROR("Error occurred while validating announce. The contained exception was: " + std::string(e.what()));
|
||||
ERRORF("Error occurred while validating announce. The contained exception was: %s", e.what());
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
@@ -505,12 +527,12 @@ const Bytes Identity::encrypt(const Bytes& plaintext) const {
|
||||
}
|
||||
Cryptography::X25519PrivateKey::Ptr ephemeral_key = Cryptography::X25519PrivateKey::generate();
|
||||
Bytes ephemeral_pub_bytes = ephemeral_key->public_key()->public_bytes();
|
||||
TRACE("Identity::encrypt: ephemeral public key: " + ephemeral_pub_bytes.toHex());
|
||||
TRACEF("Identity::encrypt: ephemeral public key: %s", ephemeral_pub_bytes.toHex().c_str());
|
||||
|
||||
// CRYPTO: create shared key for key exchange using own public key
|
||||
//shared_key = ephemeral_key.exchange(self.pub)
|
||||
Bytes shared_key = ephemeral_key->exchange(_object->_pub_bytes);
|
||||
TRACE("Identity::encrypt: shared key: " + shared_key.toHex());
|
||||
TRACEF("Identity::encrypt: shared key: %s", shared_key.toHex().c_str());
|
||||
|
||||
Bytes derived_key = Cryptography::hkdf(
|
||||
DERIVED_KEY_LENGTH,
|
||||
@@ -518,13 +540,13 @@ const Bytes Identity::encrypt(const Bytes& plaintext) const {
|
||||
get_salt(),
|
||||
get_context()
|
||||
);
|
||||
TRACE("Identity::encrypt: derived key: " + derived_key.toHex());
|
||||
TRACEF("Identity::encrypt: derived key: %s", derived_key.toHex().c_str());
|
||||
|
||||
Cryptography::Token token(derived_key);
|
||||
TRACE("Identity::encrypt: Token encrypting data of length " + std::to_string(plaintext.size()));
|
||||
TRACE("Identity::encrypt: plaintext: " + plaintext.toHex());
|
||||
TRACEF("Identity::encrypt: Token encrypting data of length %zu", plaintext.size());
|
||||
TRACEF("Identity::encrypt: plaintext: %s", plaintext.toHex().c_str());
|
||||
Bytes ciphertext = token.encrypt(plaintext);
|
||||
TRACE("Identity::encrypt: ciphertext: " + ciphertext.toHex());
|
||||
TRACEF("Identity::encrypt: ciphertext: %s", ciphertext.toHex().c_str());
|
||||
|
||||
return ephemeral_pub_bytes + ciphertext;
|
||||
}
|
||||
@@ -544,7 +566,7 @@ const Bytes Identity::decrypt(const Bytes& ciphertext_token) const {
|
||||
throw std::runtime_error("Decryption failed because identity does not hold a private key");
|
||||
}
|
||||
if (ciphertext_token.size() <= Type::Identity::KEYSIZE/8/2) {
|
||||
DEBUG("Decryption failed because the token size " + std::to_string(ciphertext_token.size()) + " was invalid.");
|
||||
DEBUGF("Decryption failed because the token size %zu was invalid.", ciphertext_token.size());
|
||||
return {Bytes::NONE};
|
||||
}
|
||||
Bytes plaintext;
|
||||
@@ -553,12 +575,12 @@ const Bytes Identity::decrypt(const Bytes& ciphertext_token) const {
|
||||
Bytes peer_pub_bytes = ciphertext_token.left(Type::Identity::KEYSIZE/8/2);
|
||||
//peer_pub = X25519PublicKey.from_public_bytes(peer_pub_bytes)
|
||||
//Cryptography::X25519PublicKey::Ptr peer_pub = Cryptography::X25519PublicKey::from_public_bytes(peer_pub_bytes);
|
||||
TRACE("Identity::decrypt: peer public key: " + peer_pub_bytes.toHex());
|
||||
TRACEF("Identity::decrypt: peer public key: %s", peer_pub_bytes.toHex().c_str());
|
||||
|
||||
// CRYPTO: create shared key for key exchange using peer public key
|
||||
//shared_key = _object->_prv->exchange(peer_pub);
|
||||
Bytes shared_key = _object->_prv->exchange(peer_pub_bytes);
|
||||
TRACE("Identity::decrypt: shared key: " + shared_key.toHex());
|
||||
TRACEF("Identity::decrypt: shared key: %s", shared_key.toHex().c_str());
|
||||
|
||||
Bytes derived_key = Cryptography::hkdf(
|
||||
DERIVED_KEY_LENGTH,
|
||||
@@ -566,19 +588,19 @@ const Bytes Identity::decrypt(const Bytes& ciphertext_token) const {
|
||||
get_salt(),
|
||||
get_context()
|
||||
);
|
||||
TRACE("Identity::decrypt: derived key: " + derived_key.toHex());
|
||||
TRACEF("Identity::decrypt: derived key: %s", derived_key.toHex().c_str());
|
||||
|
||||
Cryptography::Token token(derived_key);
|
||||
//ciphertext = ciphertext_token[Identity.KEYSIZE//8//2:]
|
||||
Bytes ciphertext(ciphertext_token.mid(Type::Identity::KEYSIZE/8/2));
|
||||
TRACE("Identity::decrypt: Token decrypting data of length " + std::to_string(ciphertext.size()));
|
||||
TRACE("Identity::decrypt: ciphertext: " + ciphertext.toHex());
|
||||
TRACEF("Identity::decrypt: Token decrypting data of length %zu", ciphertext.size());
|
||||
TRACEF("Identity::decrypt: ciphertext: %s", ciphertext.toHex().c_str());
|
||||
plaintext = token.decrypt(ciphertext);
|
||||
TRACE("Identity::decrypt: plaintext: " + plaintext.toHex());
|
||||
//TRACE("Identity::decrypt: Token decrypted data of length " + std::to_string(plaintext.size()));
|
||||
TRACEF("Identity::decrypt: plaintext: %s", plaintext.toHex().c_str());
|
||||
//TRACEF("Identity::decrypt: Token decrypted data of length %zu", plaintext.size());
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
DEBUG("Decryption by " + toString() + " failed: " + e.what());
|
||||
DEBUGF("Decryption by %s failed: %s", toString().c_str(), e.what());
|
||||
}
|
||||
|
||||
return plaintext;
|
||||
@@ -600,7 +622,7 @@ const Bytes Identity::sign(const Bytes& message) const {
|
||||
return _object->_sig_prv->sign(message);
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERROR("The identity " + toString() + " could not sign the requested message. The contained exception was: " + e.what());
|
||||
ERRORF("The identity %s could not sign the requested message. The contained exception was: %s", toString().c_str(), e.what());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
@@ -617,7 +639,7 @@ bool Identity::validate(const Bytes& signature, const Bytes& message) const {
|
||||
assert(_object);
|
||||
if (_object->_pub) {
|
||||
try {
|
||||
TRACE("Identity::validate: Attempting to verify signature: " + signature.toHex() + " and message: " + message.toHex());
|
||||
TRACEF("Identity::validate: Attempting to verify signature: %s and message: %s", signature.toHex().c_str(), message.toHex().c_str());
|
||||
_object->_sig_pub->verify(signature, message);
|
||||
return true;
|
||||
}
|
||||
@@ -636,11 +658,11 @@ void Identity::prove(const Packet& packet, const Destination& destination /*= {T
|
||||
Bytes proof_data;
|
||||
if (RNS::Reticulum::should_use_implicit_proof()) {
|
||||
proof_data = signature;
|
||||
TRACE("Identity::prove: implicit proof data: " + proof_data.toHex());
|
||||
TRACEF("Identity::prove: implicit proof data: %s", proof_data.toHex().c_str());
|
||||
}
|
||||
else {
|
||||
proof_data = packet.packet_hash() + signature;
|
||||
TRACE("Identity::prove: explicit proof data: " + proof_data.toHex());
|
||||
TRACEF("Identity::prove: explicit proof data: %s", proof_data.toHex().c_str());
|
||||
}
|
||||
|
||||
if (!destination) {
|
||||
|
||||
+16
-9
@@ -7,6 +7,7 @@
|
||||
#include "Cryptography/Ed25519.h"
|
||||
#include "Cryptography/X25519.h"
|
||||
#include "Cryptography/Token.h"
|
||||
#include "Utilities/Memory.h"
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
@@ -36,9 +37,11 @@ namespace RNS {
|
||||
Bytes _public_key;
|
||||
Bytes _app_data;
|
||||
};
|
||||
//using IdentityTable = std::map<Bytes, IdentityEntry>;
|
||||
using IdentityTable = std::map<Bytes, IdentityEntry, std::less<Bytes>, Utilities::Memory::ContainerAllocator<std::pair<const Bytes, IdentityEntry>>>;
|
||||
|
||||
public:
|
||||
static std::map<Bytes, IdentityEntry> _known_destinations;
|
||||
private:
|
||||
static IdentityTable _known_destinations;
|
||||
static bool _saving_known_destinations;
|
||||
// CBA
|
||||
static uint16_t _known_destinations_maxsize;
|
||||
@@ -46,18 +49,18 @@ namespace RNS {
|
||||
public:
|
||||
Identity(bool create_keys = true);
|
||||
Identity(Type::NoneConstructor none) {
|
||||
MEM("Identity NONE object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Identity NONE object created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
Identity(const Identity& identity) : _object(identity._object) {
|
||||
MEM("Identity object copy created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Identity object copy created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
virtual ~Identity() {
|
||||
MEM("Identity object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Identity object destroyed, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
|
||||
inline Identity& operator = (const Identity& identity) {
|
||||
_object = identity._object;
|
||||
MEM("Identity object copy created by assignment, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Identity object copy created by assignment, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
return *this;
|
||||
}
|
||||
inline operator bool() const {
|
||||
@@ -89,7 +92,7 @@ namespace RNS {
|
||||
inline void update_hashes() {
|
||||
assert(_object);
|
||||
_object->_hash = truncated_hash(get_public_key());
|
||||
TRACE("Identity::update_hashes: hash: " + _object->_hash.toHex());
|
||||
TRACEF("Identity::update_hashes: hash: %s", _object->_hash.toHex().c_str());
|
||||
_object->_hexhash = _object->_hash.toHex();
|
||||
};
|
||||
bool load(const char* path);
|
||||
@@ -164,14 +167,16 @@ namespace RNS {
|
||||
inline const Cryptography::Ed25519PrivateKey::Ptr sig_prv() const { assert(_object); return _object->_sig_prv; }
|
||||
inline const Cryptography::X25519PublicKey::Ptr pub() const { assert(_object); return _object->_pub; }
|
||||
inline const Cryptography::Ed25519PublicKey::Ptr sig_pub() const { assert(_object); return _object->_sig_pub; }
|
||||
inline static uint16_t known_destinations_maxsize() { return _known_destinations_maxsize; }
|
||||
inline static void known_destinations_maxsize(uint16_t known_destinations_maxsize) { _known_destinations_maxsize = known_destinations_maxsize; }
|
||||
|
||||
inline std::string toString() const { if (!_object) return ""; return "{Identity:" + _object->_hash.toHex() + "}"; }
|
||||
|
||||
private:
|
||||
class Object {
|
||||
public:
|
||||
Object() { MEM("Identity::Data object created, this: " + std::to_string((uintptr_t)this)); }
|
||||
virtual ~Object() { MEM("Identity::Data object destroyed, this: " + std::to_string((uintptr_t)this)); }
|
||||
Object() { MEMF("Identity::Data object created, this: %p", (void*)this); }
|
||||
virtual ~Object() { MEMF("Identity::Data object destroyed, this: %p", (void*)this); }
|
||||
private:
|
||||
|
||||
Cryptography::X25519PrivateKey::Ptr _prv;
|
||||
@@ -195,6 +200,8 @@ namespace RNS {
|
||||
};
|
||||
std::shared_ptr<Object> _object;
|
||||
|
||||
// CBA For access to private static members by Transport class
|
||||
friend class Transport;
|
||||
};
|
||||
|
||||
}
|
||||
+47
-10
@@ -9,13 +9,13 @@ using namespace RNS::Type::Interface;
|
||||
/*static*/ uint8_t Interface::DISCOVER_PATHS_FOR = MODE_ACCESS_POINT | MODE_GATEWAY;
|
||||
|
||||
void InterfaceImpl::handle_outgoing(const Bytes& data) {
|
||||
//TRACE("InterfaceImpl.handle_outgoing: data: " + data.toHex());
|
||||
//TRACEF("InterfaceImpl.handle_outgoing: data: %s", data.toHex().c_str());
|
||||
TRACE("InterfaceImpl.handle_outgoing");
|
||||
_txb += data.size();
|
||||
}
|
||||
|
||||
void InterfaceImpl::handle_incoming(const Bytes& data) {
|
||||
//TRACE("InterfaceImpl.handle_incoming: data: " + data.toHex());
|
||||
//TRACEF("InterfaceImpl.handle_incoming: data: %s", data.toHex().c_str());
|
||||
TRACE("InterfaceImpl.handle_incoming");
|
||||
_rxb += data.size();
|
||||
// Create temporary Interface encapsulating our own shared impl
|
||||
@@ -25,16 +25,53 @@ void InterfaceImpl::handle_incoming(const Bytes& data) {
|
||||
Transport::inbound(data, interface);
|
||||
}
|
||||
|
||||
void Interface::handle_incoming(const Bytes& data) {
|
||||
//TRACE("Interface.handle_incoming: data: " + data.toHex());
|
||||
TRACE("Interface.handle_incoming");
|
||||
void Interface::send_outgoing(const Bytes& data) {
|
||||
assert(_impl);
|
||||
//TRACEF("Interface.send_outgoing: data: %s", data.toHex().c_str());
|
||||
//TRACE("Interface.send_outgoing");
|
||||
// Catch exceptions from calls into Interface implementation
|
||||
try {
|
||||
_impl->send_outgoing(data);
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERROR("Interface::send_outgoing: bad_alloc - OUT OF MEMORY");
|
||||
// Critical OOM, restarting
|
||||
#if defined(ESP32)
|
||||
ESP.restart();
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
NVIC_SystemReset();
|
||||
#endif
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERRORF("Interface::send_outgoing: %s", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void Interface::handle_incoming(const Bytes& data) {
|
||||
assert(_impl);
|
||||
//TRACEF("Interface.handle_incoming: data: %s", data.toHex().c_str());
|
||||
//TRACE("Interface.handle_incoming");
|
||||
/*
|
||||
_impl->_rxb += data.size();
|
||||
// Pass data on to transport for handling
|
||||
Transport::inbound(data, *this);
|
||||
*/
|
||||
_impl->handle_incoming(data);
|
||||
// Catch exceptions from calls into Interface implementation
|
||||
try {
|
||||
_impl->handle_incoming(data);
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERROR("Interface::handle_incoming: bad_alloc - OUT OF MEMORY");
|
||||
// Critical OOM, restarting
|
||||
#if defined(ESP32)
|
||||
ESP.restart();
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
NVIC_SystemReset();
|
||||
#endif
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERRORF("Interface::handle_incoming: %s", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void Interface::process_announce_queue() {
|
||||
@@ -87,18 +124,18 @@ void Interface::process_announce_queue() {
|
||||
/*
|
||||
void ArduinoJson::convertFromJson(JsonVariantConst src, RNS::Interface& dst) {
|
||||
TRACE(">>> Deserializing Interface");
|
||||
TRACE(">>> Interface pre: " + dst.debugString());
|
||||
TRACEF(">>> Interface pre: %s", dst.debugString().c_str());
|
||||
if (!src.isNull()) {
|
||||
RNS::Bytes hash;
|
||||
hash.assignHex(src.as<const char*>());
|
||||
TRACE(">>> Querying Transport for Interface hash " + hash.toHex());
|
||||
TRACEF(">>> Querying Transport for Interface hash %s", hash.toHex().c_str());
|
||||
// Query transport for matching interface
|
||||
dst = Transport::find_interface_from_hash(hash);
|
||||
TRACE(">>> Interface post: " + dst.debugString());
|
||||
TRACEF(">>> Interface post: %s", dst.debugString().c_str());
|
||||
}
|
||||
else {
|
||||
dst = {RNS::Type::NONE};
|
||||
TRACE(">>> Interface post: " + dst.debugString());
|
||||
TRACEF(">>> Interface post: %s", dst.debugString().c_str());
|
||||
}
|
||||
}
|
||||
*/
|
||||
+5
-5
@@ -161,9 +161,9 @@ namespace RNS {
|
||||
inline void add_announce(AnnounceEntry& entry) { assert(_impl); _impl->_announce_queue.push_back(entry); }
|
||||
|
||||
protected:
|
||||
inline void send_outgoing(const Bytes& data) { assert(_impl); _impl->send_outgoing(data); }
|
||||
// Internal method to handle data going out on interface and pass on to impl
|
||||
void send_outgoing(const Bytes& data);
|
||||
public:
|
||||
//inline void handle_incoming(const Bytes& data) { assert(_impl); _impl->handle_incoming(data); }
|
||||
// Public method to handle data coming in on interface and pass on to impl
|
||||
void handle_incoming(const Bytes& data);
|
||||
|
||||
@@ -224,7 +224,7 @@ namespace ArduinoJson {
|
||||
if (!src) {
|
||||
return dst.set(nullptr);
|
||||
}
|
||||
TRACE("<<< Interface hash " + src.get_hash().toHex());
|
||||
TRACEF("<<< Interface hash %s", src.get_hash().toHex().c_str());
|
||||
return dst.set(src.get_hash().toHex());
|
||||
}
|
||||
void convertFromJson(JsonVariantConst src, RNS::Interface& dst);
|
||||
@@ -241,14 +241,14 @@ namespace ArduinoJson {
|
||||
if (!src) {
|
||||
return dst.set(nullptr);
|
||||
}
|
||||
TRACE("<<< Serializing interface hash " + src.get_hash().toHex());
|
||||
TRACEF("<<< Serializing interface hash %s", src.get_hash().toHex().c_str());
|
||||
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*>());
|
||||
TRACE(">>> Deserialized interface hash " + hash.toHex());
|
||||
TRACEF(">>> Deserialized interface hash %s", hash.toHex().c_str());
|
||||
TRACE(">>> Querying transport for interface");
|
||||
// Query transport for matching interface
|
||||
return RNS::Interface::find_interface_from_hash(hash);
|
||||
|
||||
+39
-6
@@ -176,14 +176,34 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi
|
||||
}
|
||||
|
||||
/*static*/ Link Link::validate_request( const Destination& owner, const Bytes& data, const Packet& packet) {
|
||||
if (data.size() == ECPUBSIZE) {
|
||||
if (data.size() == ECPUBSIZE || data.size() == ECPUBSIZE + LINK_MTU_SIZE) {
|
||||
try {
|
||||
Link link({Type::NONE}, nullptr, nullptr, owner, data.left(ECPUBSIZE/2), data.mid(ECPUBSIZE/2, ECPUBSIZE/2));
|
||||
link.set_link_id(packet);
|
||||
|
||||
if (data.size() == ECPUBSIZE + LINK_MTU_SIZE) {
|
||||
DEBUG("Link request includes MTU signalling"); // TODO: Remove debug
|
||||
try {
|
||||
uint16_t mtu = mtu_from_lr_packet(packet);
|
||||
link.mtu((mtu != 0) ? mtu : Type::Reticulum::MTU);
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERRORF("An error ocurred while validating link request %s", link.link_id().toHex().c_str());
|
||||
link.mtu(Type::Reticulum::MTU);
|
||||
}
|
||||
}
|
||||
|
||||
link.mode(mode_from_lr_packet(packet));
|
||||
|
||||
// TODO: Remove debug
|
||||
DEBUGF("Incoming link request with mode %d", link.get_mode());
|
||||
|
||||
link.update_mdu();
|
||||
link.destination(packet.destination());
|
||||
link.establishment_timeout(ESTABLISHMENT_TIMEOUT_PER_HOP * std::max((uint8_t)1, packet.hops()) + KEEPALIVE);
|
||||
link.establishment_cost(link.establishment_cost() + packet.raw().size());
|
||||
VERBOSEF("Validating link request %s", link.link_id().toHex().c_str());
|
||||
TRACEF("Link MTU configured to %d", link.mtu());
|
||||
TRACEF("Establishment timeout is %f for incoming link request %s", link.establishment_timeout(), link.link_id().toHex().c_str());
|
||||
link.handshake();
|
||||
link.attached_interface(packet.receiving_interface());
|
||||
@@ -202,7 +222,7 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi
|
||||
}
|
||||
}
|
||||
else {
|
||||
DEBUG("Invalid link request payload size, dropping request");
|
||||
DEBUGF("Invalid link request payload size (%zu), dropping request", data.size());
|
||||
return {Type::NONE};
|
||||
}
|
||||
}
|
||||
@@ -256,10 +276,11 @@ void Link::handshake() {
|
||||
void Link::prove() {
|
||||
assert(_object);
|
||||
DEBUGF("Link %s requesting proof", link_id().toHex().c_str());
|
||||
Bytes signed_data =_object->_link_id + _object->_pub_bytes + _object->_sig_pub_bytes;
|
||||
Bytes signalling_bytes = Link::signalling_bytes(_object->_mtu, _object->_mode);
|
||||
Bytes signed_data = _object->_link_id + _object->_pub_bytes + _object->_sig_pub_bytes + signalling_bytes;
|
||||
const Bytes signature(_object->_owner.identity().sign(signed_data));
|
||||
|
||||
Bytes proof_data = signature + _object->_pub_bytes;
|
||||
Bytes proof_data = signature + _object->_pub_bytes + signalling_bytes;
|
||||
// CBA LINK
|
||||
// CBA TODO: Determine which approach is better, passing liunk to packet or passing _link_destination
|
||||
Packet proof(*this, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
|
||||
@@ -317,7 +338,7 @@ void Link::validate_proof(const Packet& packet) {
|
||||
handshake();
|
||||
|
||||
_object->_establishment_cost += packet.raw().size();
|
||||
Bytes signed_data = _object->_link_id + _object->_peer_pub_bytes + _object->_peer_sig_pub_bytes;
|
||||
Bytes signed_data = _object->_link_id + _object->_peer_pub_bytes + _object->_peer_sig_pub_bytes + signalling_bytes;
|
||||
const Bytes signature(packet_data.left(Type::Identity::SIGLENGTH/8));
|
||||
|
||||
TRACEF("Link %s validating identity", link_id().toHex().c_str());
|
||||
@@ -335,7 +356,7 @@ void Link::validate_proof(const Packet& packet) {
|
||||
_object->_activated_at = OS::time();
|
||||
_object->_last_proof = _object->_activated_at;
|
||||
Transport::activate_link(*this);
|
||||
VERBOSEF("Link %s established with %s, RTT is %f s", toString().c_str(), _object->_destination.toString().c_str(), OS::round(_object->_rtt, 3));
|
||||
VERBOSEF("Link %s established with %s, RTT is %.3f s", toString().c_str(), _object->_destination.toString().c_str(), OS::round(_object->_rtt, 3));
|
||||
|
||||
//p if _object->_rtt != None and _object->_establishment_cost != None and _object->_rtt > 0 and _object->_establishment_cost > 0:
|
||||
if (_object->_rtt != 0.0 && _object->_establishment_cost != 0 && _object->_rtt > 0 and _object->_establishment_cost > 0) {
|
||||
@@ -677,6 +698,7 @@ void Link::teardown_packet(const Packet& packet) {
|
||||
}
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERRORF("Error while decrypting teardown packet from %s. The contained exception was: %s", toString().c_str(), e.what());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1112,6 +1134,7 @@ void Link::receive(const Packet& packet) {
|
||||
if (!_object->_initiator) {
|
||||
rtt_packet(packet);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Type::Packet::LINKCLOSE:
|
||||
{
|
||||
@@ -1564,6 +1587,16 @@ void Link::status(Type::Link::status status) {
|
||||
_object->_status = status;
|
||||
}
|
||||
|
||||
void Link::mtu(uint16_t mtu) {
|
||||
assert(_object);
|
||||
_object->_mtu = mtu;
|
||||
}
|
||||
|
||||
void Link::mode(RNS::Type::Link::link_mode mode) {
|
||||
assert(_object);
|
||||
_object->_mode = mode;
|
||||
}
|
||||
|
||||
|
||||
//RequestReceipt::RequestReceipt(const Link& link, const PacketReceipt& packet_receipt /*= {Type::NONE}*/, const Resource& resource /*= {Type::NONE}*/, RequestReceipt::Callbacks::response response_callback /*= nullptr*/, RequestReceipt::Callbacks::failed failed_callback /*= nullptr*/, RequestReceipt::Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/, int request_size /*= 0*/) :
|
||||
RequestReceipt::RequestReceipt(const Link& link, const PacketReceipt& packet_receipt, const Resource& resource, RequestReceipt::Callbacks::response response_callback /*= nullptr*/, RequestReceipt::Callbacks::failed failed_callback /*= nullptr*/, RequestReceipt::Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/, int request_size /*= 0*/) :
|
||||
|
||||
+6
-2
@@ -130,7 +130,7 @@ namespace RNS {
|
||||
friend class Link;
|
||||
};
|
||||
|
||||
public:
|
||||
private:
|
||||
static uint8_t resource_strategies;
|
||||
static std::set<RNS::Type::Link::link_mode> ENABLED_MODES;
|
||||
static RNS::Type::Link::link_mode MODE_DEFAULT;
|
||||
@@ -198,7 +198,7 @@ namespace RNS {
|
||||
void teardown_packet(const Packet& packet);
|
||||
void link_closed();
|
||||
void start_watchdog();
|
||||
void __watchdog_job();
|
||||
void __watchdog_job();
|
||||
void send_keepalive();
|
||||
void handle_request(const Bytes& request_id, const ResourceRequest& unpacked_request);
|
||||
void handle_response(const Bytes& request_id, const Bytes& response_data, size_t response_size, size_t response_transfer_size);
|
||||
@@ -259,10 +259,14 @@ namespace RNS {
|
||||
void increment_tx();
|
||||
void increment_txbytes(uint16_t bytes);
|
||||
void status(Type::Link::status status);
|
||||
void mtu(uint16_t mtu);
|
||||
void mode(RNS::Type::Link::link_mode mode);
|
||||
|
||||
protected:
|
||||
std::shared_ptr<LinkData> _object;
|
||||
|
||||
// CBA For access to private static members by LinkData class
|
||||
friend class LinkData;
|
||||
};
|
||||
|
||||
}
|
||||
+7
-2
@@ -72,7 +72,7 @@ LogLevel RNS::loglevel() {
|
||||
return _level;
|
||||
}
|
||||
|
||||
void RNS::setLogCallback(log_callback on_log /*= nullptr*/) {
|
||||
void RNS::set_log_callback(log_callback on_log /*= nullptr*/) {
|
||||
_on_log = on_log;
|
||||
}
|
||||
|
||||
@@ -98,10 +98,15 @@ void RNS::doLog(LogLevel level, const char* msg) {
|
||||
#endif
|
||||
}
|
||||
|
||||
void HEAD(const char* msg, LogLevel level) {
|
||||
void RNS::doHeadLog(LogLevel level, const char* msg) {
|
||||
if (level > _level) {
|
||||
return;
|
||||
}
|
||||
if (_on_log != nullptr) {
|
||||
_on_log("", level);
|
||||
_on_log(msg, level);
|
||||
return;
|
||||
}
|
||||
#ifdef ARDUINO
|
||||
Serial.println("");
|
||||
#else
|
||||
|
||||
@@ -8,30 +8,35 @@
|
||||
|
||||
#include <string>
|
||||
|
||||
#ifndef ARDUINO
|
||||
#define msg (msg)
|
||||
#endif
|
||||
|
||||
#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__))
|
||||
|
||||
#define CRITICAL(msg) (RNS::log(msg, RNS::LOG_CRITICAL))
|
||||
#define CRITICALF(msg, ...) (RNS::logf(RNS::LOG_CRITICAL, msg, __VA_ARGS__))
|
||||
#define ERROR(msg) (RNS::log(msg, RNS::LOG_ERROR))
|
||||
#define ERRORF(msg, ...) (RNS::logf(RNS::LOG_ERROR, msg, __VA_ARGS__))
|
||||
#define WARNING(msg) (RNS::log(msg, RNS::LOG_WARNING))
|
||||
#define WARNINGF(msg, ...) (RNS::logf(RNS::LOG_WARNING, msg, __VA_ARGS__))
|
||||
#define NOTICE(msg) (RNS::log(msg, RNS::LOG_NOTICE))
|
||||
#define NOTICEF(msg, ...) (RNS::logf(RNS::LOG_NOTICE, msg, __VA_ARGS__))
|
||||
#define INFO(msg) (RNS::log(msg, RNS::LOG_INFO))
|
||||
#define INFOF(msg, ...) (RNS::logf(RNS::LOG_INFO, msg, __VA_ARGS__))
|
||||
#define VERBOSE(msg) (RNS::log(msg, RNS::LOG_VERBOSE))
|
||||
#define VERBOSEF(msg, ...) (RNS::logf(RNS::LOG_VERBOSE, 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 DEBUG(msg) (RNS::log(msg, RNS::LOG_DEBUG))
|
||||
#define DEBUGF(msg, ...) (RNS::logf(RNS::LOG_DEBUG, msg, __VA_ARGS__))
|
||||
#define TRACE(msg) (RNS::log(msg, RNS::LOG_TRACE))
|
||||
#define TRACEF(msg, ...) (RNS::logf(RNS::LOG_TRACE, msg, __VA_ARGS__))
|
||||
#if defined(RNS_MEM_LOG)
|
||||
#define MEM(msg) (RNS::mem(msg))
|
||||
#define MEMF(msg, ...) (RNS::memf(msg, __VA_ARGS__))
|
||||
#define MEM(msg) (RNS::log(msg, RNS::LOG_MEM))
|
||||
#define MEMF(msg, ...) (RNS::logf(RNS::LOG_MEM, msg, __VA_ARGS__))
|
||||
#else
|
||||
#define MEM(ignore) ((void)0)
|
||||
#define MEMF(...) ((void)0)
|
||||
@@ -39,12 +44,14 @@
|
||||
#else
|
||||
#define DEBUG(ignore) ((void)0)
|
||||
#define DEBUGF(...) ((void)0)
|
||||
#define TRACE(...) ((void)0)
|
||||
#define TRACE(ignore) ((void)0)
|
||||
#define TRACEF(...) ((void)0)
|
||||
#define MEM(ignore) ((void)0)
|
||||
#define MEMF(...) ((void)0)
|
||||
#endif
|
||||
|
||||
#define RNS_LOG_BUFFER_SIZE 1024
|
||||
|
||||
namespace RNS {
|
||||
|
||||
enum LogLevel {
|
||||
@@ -68,22 +75,41 @@ namespace RNS {
|
||||
void loglevel(LogLevel level);
|
||||
LogLevel loglevel();
|
||||
|
||||
void setLogCallback(log_callback on_log = nullptr);
|
||||
void set_log_callback(log_callback on_log = nullptr);
|
||||
|
||||
void doLog(LogLevel level, const char* msg);
|
||||
inline void doLog(LogLevel level, const char* msg, va_list vlist) { char buf[1024]; vsnprintf(buf, sizeof(buf), msg, vlist); doLog(level, buf); }
|
||||
inline void doLog(LogLevel level, const char* msg, va_list vlist) { char buf[RNS_LOG_BUFFER_SIZE]; vsnprintf(buf, sizeof(buf), msg, vlist); doLog(level, buf); }
|
||||
#ifdef ARDUINO
|
||||
//inline void doLog(LogLevel level, const __FlashStringHelper* msg) { char buf[RNS_LOG_BUFFER_SIZE]; strncpy_P(buf, (const char*)msg, sizeof(buf)); doLog(level, buf); }
|
||||
//inline void doLog(LogLevel level, const __FlashStringHelper* msg, va_list vlist) { char buf[RNS_LOG_BUFFER_SIZE]; vsnprintf_P(buf, sizeof(buf), (const char*)msg, vlist); doLog(level, buf); }
|
||||
#endif
|
||||
|
||||
void doHeadLog(LogLevel level, const char* msg);
|
||||
inline void doHeadLog(LogLevel level, const char* msg, va_list vlist) { char buf[RNS_LOG_BUFFER_SIZE]; vsnprintf(buf, sizeof(buf), msg, vlist); doHeadLog(level, buf); }
|
||||
#ifdef ARDUINO
|
||||
//inline void doHeadLog(LogLevel level, const __FlashStringHelper* msg) { char buf[RNS_LOG_BUFFER_SIZE]; strncpy_P(buf, (const char*)msg, sizeof(buf)); doHeadLog(level, buf); }
|
||||
//inline void doHeadLog(LogLevel level, const __FlashStringHelper* msg, va_list vlist) { char buf[RNS_LOG_BUFFER_SIZE]; vsnprintf_P(buf, sizeof(buf), (const char*)msg, vlist); doHeadLog(level, buf); }
|
||||
#endif
|
||||
|
||||
inline void log(const char* msg, LogLevel level = LOG_NOTICE) { doLog(level, msg); }
|
||||
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); }
|
||||
#ifdef ARDUINO
|
||||
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()); }
|
||||
//inline void log(const __FlashStringHelper* msg, LogLevel level = LOG_NOTICE) { doLog(level, msg); }
|
||||
//inline void logf(LogLevel level, const __FlashStringHelper* msg, ...) { va_list vlist; va_start(vlist, msg); doLog(level, msg, vlist); va_end(vlist); }
|
||||
#endif
|
||||
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 head(const char* msg, LogLevel level = LOG_NOTICE) { doHeadLog(level, msg); }
|
||||
inline void head(const std::string& msg, LogLevel level = LOG_NOTICE) { doHeadLog(level, msg.c_str()); }
|
||||
inline void headf(LogLevel level, const char* msg, ...) { va_list vlist; va_start(vlist, msg); doHeadLog(level, msg, vlist); va_end(vlist); }
|
||||
#ifdef ARDUINO
|
||||
inline void head(const String& msg, LogLevel level = LOG_NOTICE) { doHeadLog(level, msg.c_str()); }
|
||||
inline void head(const StringSumHelper& msg, LogLevel level = LOG_NOTICE) { doHeadLog(level, msg.c_str()); }
|
||||
//inline void head(const __FlashStringHelper* msg, LogLevel level = LOG_NOTICE) { doHeadLog(level, msg); }
|
||||
//inline void headf(LogLevel level, const __FlashStringHelper* msg, ...) { va_list vlist; va_start(vlist, msg); doHeadLog(level, msg, vlist); va_end(vlist); }
|
||||
#endif
|
||||
|
||||
inline void critical(const char* msg) { doLog(LOG_CRITICAL, msg); }
|
||||
inline void critical(const std::string& msg) { doLog(LOG_CRITICAL, msg.c_str()); }
|
||||
|
||||
+22
-17
@@ -23,7 +23,7 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa
|
||||
{
|
||||
|
||||
if (_object->_destination) {
|
||||
TRACE("Creating packet with destination...");
|
||||
//TRACE("Creating packet with destination...");
|
||||
// CBA Should never see empty transport_type
|
||||
//if (transport_type == NONE) {
|
||||
// transport_type = Type::Transport::BROADCAST;
|
||||
@@ -47,7 +47,7 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa
|
||||
_object->_create_receipt = create_receipt;
|
||||
}
|
||||
else {
|
||||
TRACE("Creating packet without destination...");
|
||||
//TRACE("Creating packet without destination...");
|
||||
// CBA NOTE: This variant is for creating a new packet from a received raw buffer
|
||||
_object->_raw = data;
|
||||
_object->_packed = true;
|
||||
@@ -55,7 +55,7 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa
|
||||
_object->_create_receipt = false;
|
||||
}
|
||||
|
||||
MEM("Packet object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Packet object created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
|
||||
// CBA LINK
|
||||
@@ -70,7 +70,7 @@ Packet::Packet(const Link& link, const Bytes& data, Type::Packet::types packet_t
|
||||
_object->_MTU = link.mtu();
|
||||
// CBA HACK: Need to re-build packed flags since Link was assigned
|
||||
_object->_flags = get_packed_flags();
|
||||
MEM("Packet link object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Packet link object created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
|
||||
|
||||
@@ -78,14 +78,14 @@ uint8_t Packet::get_packed_flags() {
|
||||
assert(_object);
|
||||
uint8_t packed_flags = 0;
|
||||
if (_object->_context == LRPROOF) {
|
||||
TRACE("***** Packing with LINK type");
|
||||
//TRACE("***** Packing with LINK type");
|
||||
packed_flags = (_object->_header_type << 6) | (_object->_context_flag << 5) | (_object->_transport_type << 4) | (Type::Destination::LINK << 2) | _object->_packet_type;
|
||||
}
|
||||
else {
|
||||
if (!_object->_destination) {
|
||||
throw std::logic_error("Packet destination is required");
|
||||
}
|
||||
TRACEF("***** Packing with %d type", _object->_destination.type());
|
||||
//TRACEF("***** Packing with %d type", _object->_destination.type());
|
||||
packed_flags = (_object->_header_type << 6) | (_object->_context_flag << 5) | (_object->_transport_type << 4) | (_object->_destination.type() << 2) | _object->_packet_type;
|
||||
}
|
||||
return packed_flags;
|
||||
@@ -283,13 +283,13 @@ void Packet::pack() {
|
||||
// CBA LINK
|
||||
if (_object->_context == LRPROOF) {
|
||||
if (!_object->_destination_link) throw std::invalid_argument("Packet is not associated with a Link");
|
||||
TRACE("Packet::pack: destination link id: " + _object->_destination_link.link_id().toHex() );
|
||||
TRACEF("Packet::pack: destination link id: %s", _object->_destination_link.link_id().toHex().c_str());
|
||||
_object->_header << _object->_destination_link.link_id();
|
||||
_object->_ciphertext = _object->_data;
|
||||
}
|
||||
else {
|
||||
if (_object->_header_type == HEADER_1) {
|
||||
TRACE("Packet::pack: destination hash: " + _object->_destination.hash().toHex() );
|
||||
TRACEF("Packet::pack: destination hash: %s", _object->_destination.hash().toHex().c_str());
|
||||
_object->_header << _object->_destination.hash();
|
||||
|
||||
if (_object->_packet_type == ANNOUNCE) {
|
||||
@@ -348,8 +348,8 @@ TRACEF("***** Destination Data: %s", _object->_ciphertext.toHex().c_str());
|
||||
if (!_object->_transport_id) {
|
||||
throw std::invalid_argument("Packet with header type 2 must have a transport ID");
|
||||
}
|
||||
TRACE("Packet::pack: transport id: " + _object->_transport_id.toHex() );
|
||||
TRACE("Packet::pack: destination hash: " + _object->_destination.hash().toHex() );
|
||||
TRACEF("Packet::pack: transport id: %s", _object->_transport_id.toHex().c_str());
|
||||
TRACEF("Packet::pack: destination hash: %s", _object->_destination.hash().toHex().c_str());
|
||||
_object->_header << _object->_transport_id;
|
||||
_object->_header << _object->_destination.hash();
|
||||
|
||||
@@ -419,8 +419,12 @@ bool Packet::unpack() {
|
||||
_object->_packed = false;
|
||||
update_hash();
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERROR("Packet::unpack: bad_alloc - OUT OF MEMORY unpacking packet");
|
||||
return false;
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERROR(std::string("Received malformed packet, dropping it. The contained exception was: ") + e.what());
|
||||
ERRORF("Received malformed packet, dropping it. The contained exception was: %s", e.what());
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -585,14 +589,15 @@ std::string Packet::debugString() const {
|
||||
if (_object->_packed) {
|
||||
//unpack();
|
||||
}
|
||||
std::string str = "ph=" + _object->_packet_hash.toHex();
|
||||
str += " ht=" + std::to_string(_object->_header_type);
|
||||
std::string str;
|
||||
str = "ht=" + std::to_string(_object->_header_type);
|
||||
str += " tt=" + std::to_string(_object->_transport_type);
|
||||
str += " dt=" + std::to_string(_object->_destination_type);
|
||||
str += " pt=" + std::to_string(_object->_packet_type);
|
||||
str += " hp=" + std::to_string(_object->_hops);
|
||||
str += " ti=" + _object->_transport_id.toHex();
|
||||
str += " dh=" + _object->_destination_hash.toHex();
|
||||
str += " ph=" + _object->_packet_hash.toHex();
|
||||
return str;
|
||||
}
|
||||
std::string Packet::dumpString() const {
|
||||
@@ -852,8 +857,8 @@ bool PacketReceipt::validate_link_proof(const Bytes& proof, const Link& link, co
|
||||
_object->_callbacks._delivery(*this);
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERROR("An error occurred while evaluating external delivery callback for " + link.toString());
|
||||
ERROR("The contained exception was: " + std::string(e.what()));
|
||||
ERRORF("An error occurred while evaluating external delivery callback for %s", link.toString().c_str());
|
||||
ERRORF("The contained exception was: %s", e.what());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -914,7 +919,7 @@ bool PacketReceipt::validate_proof(const Bytes& proof, const Packet& proof_packe
|
||||
_object->_callbacks._delivery(*this);
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERROR("Error while executing proof validated callback. The contained exception was: " + std::string(e.what()));
|
||||
ERRORF("Error while executing proof validated callback. The contained exception was: %s", e.what());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -945,7 +950,7 @@ bool PacketReceipt::validate_proof(const Bytes& proof, const Packet& proof_packe
|
||||
_object->_callbacks._delivery(*this);
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERROR("Error while executing proof validated callback. The contained exception was: " + std::string(e.what()));
|
||||
ERRORF("Error while executing proof validated callback. The contained exception was: %s", e.what());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
+12
-10
@@ -145,10 +145,10 @@ namespace RNS {
|
||||
|
||||
public:
|
||||
Packet(Type::NoneConstructor none) {
|
||||
MEM("Packet NONE object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Packet NONE object created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
Packet(const Packet& packet) : _object(packet._object) {
|
||||
MEM("Packet object copy created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Packet object copy created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
Packet(
|
||||
const Destination& destination,
|
||||
@@ -182,12 +182,12 @@ namespace RNS {
|
||||
Type::Packet::context_flags context_flag = Type::Packet::FLAG_UNSET
|
||||
);
|
||||
virtual ~Packet() {
|
||||
MEM("Packet object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Packet object destroyed, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
|
||||
inline Packet& operator = (const Packet& packet) {
|
||||
_object = packet._object;
|
||||
MEM("Packet object copy created by assignment, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Packet object copy created by assignment, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
return *this;
|
||||
}
|
||||
inline operator bool() const {
|
||||
@@ -250,6 +250,8 @@ namespace RNS {
|
||||
inline const Link& destination_link() const { assert(_object); return _object->_destination_link; }
|
||||
//CBA Following method is only used by Resource to access decrypted resource advertisement form Link. Consider a better way.
|
||||
inline const Bytes& plaintext() { assert(_object); return _object->_plaintext; }
|
||||
inline bool packed() const { assert(_object); return _object->_packed; }
|
||||
inline bool from_packed() const { assert(_object); return _object->_fromPacked; }
|
||||
|
||||
// setters
|
||||
inline void destination(const Destination& destination) { assert(_object); _object->_destination = destination; }
|
||||
@@ -272,11 +274,11 @@ namespace RNS {
|
||||
private:
|
||||
class Object {
|
||||
public:
|
||||
Object(const Destination& destination, const Interface& attached_interface) : _destination(destination), _attached_interface(attached_interface) { MEM("Packet::Data object created, this: " + std::to_string((uintptr_t)this)); }
|
||||
Object(const Destination& destination, const Interface& attached_interface) : _destination(destination), _attached_interface(attached_interface) { MEMF("Packet::Data object created, this: %p", (void*)this); }
|
||||
// CBA LINK
|
||||
//Object(const Destination& destination, const Link& destination_link) : _destination(destination), _destination_link(destination_link) { MEM("Packet::Data object created, this: " + std::to_string((uintptr_t)this)); }
|
||||
//Object(const Link& link) : _destination(link.destination()), _destination_link(link) { MEM("Packet::Data object created, this: " + std::to_string((uintptr_t)this)); }
|
||||
virtual ~Object() { MEM("Packet::Data object destroyed, this: " + std::to_string((uintptr_t)this)); }
|
||||
//Object(const Destination& destination, const Link& destination_link) : _destination(destination), _destination_link(destination_link) { MEMF("Packet::Data object created, this: %p", (void*)this); }
|
||||
//Object(const Link& link) : _destination(link.destination()), _destination_link(link) { MEMF("Packet::Data object created, this: %p", (void*)this); }
|
||||
virtual ~Object() { MEMF("Packet::Data object destroyed, this: %p", (void*)this); }
|
||||
private:
|
||||
Destination _destination = {Type::NONE};
|
||||
|
||||
@@ -358,14 +360,14 @@ namespace ArduinoJson {
|
||||
if (!src) {
|
||||
return dst.set(nullptr);
|
||||
}
|
||||
TRACE("<<< Serializing packet hash " + src.get_hash().toHex());
|
||||
TRACEF("<<< Serializing packet hash %s", src.get_hash().toHex().c_str());
|
||||
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*>());
|
||||
TRACE(">>> Deserialized packet hash " + hash.toHex());
|
||||
TRACEF(">>> Deserialized packet hash %s", hash.toHex().c_str());
|
||||
TRACE(">>> Querying transport for cached packet");
|
||||
// Query transport for matching interface
|
||||
return RNS::Packet::get_cached_packet(hash);
|
||||
|
||||
+83
-63
@@ -2,6 +2,7 @@
|
||||
|
||||
#include "Transport.h"
|
||||
#include "Log.h"
|
||||
#include "Utilities/Memory.h"
|
||||
|
||||
//#include <TransistorNoiseSource.h>
|
||||
#include <RNG.h>
|
||||
@@ -29,6 +30,9 @@ using namespace RNS::Utilities;
|
||||
/*static*/ bool Reticulum::__allow_probes = false;
|
||||
/*static*/ bool Reticulum::panic_on_interface_error = false;
|
||||
|
||||
/*static*/ uint16_t Reticulum::_persist_interval = PERSIST_INTERVAL;
|
||||
/*static*/ uint16_t Reticulum::_clean_interval = CLEAN_INTERVAL;
|
||||
|
||||
#ifdef ARDUINO
|
||||
// Noise source to seed the random number generator.
|
||||
//TransistorNoiseSource noise(A1);
|
||||
@@ -67,12 +71,12 @@ void Reticulum::sigterm_handler(signal, frame):
|
||||
|
||||
//def __init__(self,configdir=None, loglevel=None, logdest=None, verbosity=None):
|
||||
Reticulum::Reticulum() : _object(new Object()) {
|
||||
MEM("Reticulum default object creating..., this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Reticulum default object creating..., this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
|
||||
// Initialize random number generator
|
||||
TRACE("Initializing RNG...");
|
||||
RNG.begin("Reticulum");
|
||||
TRACE("RNG initial random value: " + std::to_string(Cryptography::randomnum()));
|
||||
TRACEF("RNG initial random value: %d", Cryptography::randomnum());
|
||||
|
||||
#ifdef ARDUINO
|
||||
// Add a noise source to the list of sources known to RNG.
|
||||
@@ -115,32 +119,6 @@ Reticulum::Reticulum() : _object(new Object()) {
|
||||
strncpy(_cachepath, "./cache", FILEPATH_MAXSIZE);
|
||||
#endif
|
||||
|
||||
#ifdef ARDUINO
|
||||
#if defined(RNS_USE_FS)
|
||||
// load time offset from file if it exists
|
||||
try {
|
||||
char time_offset_path[FILEPATH_MAXSIZE];
|
||||
snprintf(time_offset_path, FILEPATH_MAXSIZE, "%s/time_offset", _storagepath);
|
||||
if (OS::file_exists(time_offset_path)) {
|
||||
Bytes buf;
|
||||
if (OS::read_file(time_offset_path, buf) == 8) {
|
||||
uint64_t offset = *(uint64_t*)buf.data();
|
||||
DEBUG("Read time offset of " + std::to_string(offset) + " from file");
|
||||
OS::setTimeOffset(offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERRORF("Failed to load time offset, the contained exception was: %s", e.what());
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Initialize time-based variables *after* time offset update
|
||||
_object->_last_data_persist = OS::time();
|
||||
_object->_last_cache_clean = 0.0;
|
||||
_object->_jobs_last_run = OS::time();
|
||||
|
||||
/*p TODO
|
||||
if not os.path.isdir(Reticulum.storagepath):
|
||||
os.makedirs(Reticulum.storagepath)
|
||||
@@ -191,45 +169,85 @@ Reticulum::Reticulum() : _object(new Object()) {
|
||||
signal.signal(signal.SIGTERM, Reticulum.sigterm_handler)
|
||||
*/
|
||||
|
||||
MEM("Reticulum default object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Reticulum default object created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
|
||||
void Reticulum::start() {
|
||||
|
||||
INFO("Total memory: " + std::to_string(OS::heap_size()));
|
||||
INFO("Total flash: " + std::to_string(OS::storage_size()));
|
||||
INFOF("Total memory: %zu", Memory::heap_size());
|
||||
INFOF("Total flash: %zu", OS::storage_size());
|
||||
|
||||
#ifdef ARDUINO
|
||||
#if defined(RNS_USE_FS)
|
||||
// load time offset from file if it exists
|
||||
try {
|
||||
char time_offset_path[FILEPATH_MAXSIZE];
|
||||
snprintf(time_offset_path, FILEPATH_MAXSIZE, "%s/time_offset", _storagepath);
|
||||
if (OS::file_exists(time_offset_path)) {
|
||||
Bytes buf;
|
||||
if (OS::read_file(time_offset_path, buf) == 8) {
|
||||
uint64_t offset = *(uint64_t*)buf.data();
|
||||
DEBUGF("Read time offset of %llu from file", offset);
|
||||
OS::setTimeOffset(offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERRORF("Failed to load time offset, the contained exception was: %s", e.what());
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
INFO("Starting Transport...");
|
||||
Transport::start(*this);
|
||||
|
||||
// Initialize time-based variables *after* time offset update and Transport start
|
||||
_object->_last_data_persist = OS::time();
|
||||
_object->_last_cache_clean = OS::time();
|
||||
_object->_jobs_last_run = OS::time();
|
||||
}
|
||||
|
||||
void Reticulum::loop() {
|
||||
assert(_object);
|
||||
if (!_object->_is_connected_to_shared_instance) {
|
||||
// Catch exceptions from loop work
|
||||
try {
|
||||
if (!_object->_is_connected_to_shared_instance) {
|
||||
|
||||
// Perform Reticulum housekeeping
|
||||
if (OS::time() > (_object->_jobs_last_run + JOB_INTERVAL)) {
|
||||
jobs();
|
||||
_object->_jobs_last_run = OS::time();
|
||||
// Perform Reticulum housekeeping
|
||||
if (OS::time() > (_object->_jobs_last_run + JOB_INTERVAL)) {
|
||||
jobs();
|
||||
}
|
||||
|
||||
// Perform interface processing
|
||||
for (auto& [hash, interface] : Transport::get_interfaces()) {
|
||||
interface.loop();
|
||||
}
|
||||
|
||||
// Perform Filesystem processing
|
||||
FileSystem& filesystem = OS::get_filesystem();
|
||||
if (filesystem) {
|
||||
filesystem.loop();
|
||||
}
|
||||
|
||||
// Perform Transport processing
|
||||
RNS::Transport::loop();
|
||||
}
|
||||
|
||||
// Perform interface processing
|
||||
for (auto& [hash, interface] : Transport::get_interfaces()) {
|
||||
interface.loop();
|
||||
}
|
||||
|
||||
// Perform Filesystem processing
|
||||
FileSystem& filesystem = OS::get_filesystem();
|
||||
if (filesystem) {
|
||||
filesystem.loop();
|
||||
}
|
||||
|
||||
|
||||
// Perform Transport processing
|
||||
RNS::Transport::loop();
|
||||
}
|
||||
// Perform random number gnerator housekeeping
|
||||
RNG.loop();
|
||||
// Perform random number gnerator housekeeping
|
||||
RNG.loop();
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERROR("Reticulum::loop: bad_alloc - OUT OF MEMORY");
|
||||
// Critical OOM, restarting
|
||||
#if defined(ESP32)
|
||||
ESP.restart();
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
NVIC_SystemReset();
|
||||
#endif
|
||||
}
|
||||
catch (std::exception& e) {
|
||||
ERRORF("Reticulum::loop: %s", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
void Reticulum::jobs() {
|
||||
@@ -238,10 +256,10 @@ void Reticulum::jobs() {
|
||||
|
||||
#if 1
|
||||
// CBA Detect low-memory condition and reset
|
||||
if (OS::heap_size() > 0) {
|
||||
uint8_t remaining = (uint8_t)((double)OS::heap_available() / (double)OS::heap_size() * 100.0);
|
||||
if (Memory::heap_size() > 0) {
|
||||
uint8_t remaining = (uint8_t)((double)Memory::heap_available() / (double)Memory::heap_size() * 100.0);
|
||||
if (remaining <= 2) {
|
||||
head("DETECTED LOW-MEMORY CONDITION (" + std::to_string(remaining) + "%), RESETTING!!!", LOG_CRITICAL);
|
||||
HEADF(LOG_CRITICAL, "DETECTED LOW-MEMORY CONDITION (%d%%), RESETTING!!!", remaining);
|
||||
persist_data();
|
||||
#if defined(ESP32)
|
||||
ESP.restart();
|
||||
@@ -253,14 +271,15 @@ void Reticulum::jobs() {
|
||||
}
|
||||
#endif
|
||||
|
||||
if (now > _object->_last_cache_clean + CLEAN_INTERVAL) {
|
||||
if (now > _object->_last_cache_clean + _clean_interval) {
|
||||
clean_caches();
|
||||
_object->_last_cache_clean = OS::time();
|
||||
}
|
||||
|
||||
if (now > _object->_last_data_persist + PERSIST_INTERVAL) {
|
||||
if (now > _object->_last_data_persist + _persist_interval) {
|
||||
persist_data();
|
||||
}
|
||||
|
||||
_object->_jobs_last_run = OS::time();
|
||||
}
|
||||
|
||||
// CBA TODO
|
||||
@@ -354,6 +373,7 @@ void Reticulum::clean_caches() {
|
||||
Identity::cull_known_destinations();
|
||||
#endif
|
||||
|
||||
_object->_last_cache_clean = OS::time();
|
||||
}
|
||||
|
||||
void Reticulum::clear_caches() {
|
||||
@@ -395,7 +415,7 @@ void Reticulum::get_interface_stats() const {
|
||||
}
|
||||
*/
|
||||
|
||||
const std::map<Bytes, Transport::DestinationEntry>& Reticulum::get_path_table() const {
|
||||
const Transport::PathTable& Reticulum::get_path_table() const {
|
||||
/*
|
||||
path_table = []
|
||||
for dst_hash in Transport::destination_table:
|
||||
@@ -411,7 +431,7 @@ const std::map<Bytes, Transport::DestinationEntry>& Reticulum::get_path_table()
|
||||
|
||||
return path_table
|
||||
*/
|
||||
return Transport::get_destination_table();
|
||||
return Transport::get_path_table();
|
||||
}
|
||||
|
||||
const std::map<Bytes, Transport::RateEntry>& Reticulum::get_rate_table() const {
|
||||
@@ -438,8 +458,8 @@ bool Reticulum::drop_path(const Bytes& destination) {
|
||||
|
||||
uint16_t Reticulum::drop_all_via(const Bytes& transport_hash) {
|
||||
uint16_t dropped_count = 0;
|
||||
//for (auto& destination_hash : Transport::get_destination_table()) {
|
||||
for (const auto& [destination_hash, destination_entry] : Transport::get_destination_table()) {
|
||||
//for (auto& destination_hash : Transport::get_path_table()) {
|
||||
for (const auto& [destination_hash, destination_entry] : Transport::get_path_table()) {
|
||||
if (destination_entry._received_from == transport_hash) {
|
||||
Transport::expire_path(destination_hash);
|
||||
++dropped_count;
|
||||
|
||||
+17
-8
@@ -16,7 +16,7 @@ namespace RNS {
|
||||
|
||||
class Reticulum {
|
||||
|
||||
public:
|
||||
private:
|
||||
|
||||
//z router = None
|
||||
//z config = None
|
||||
@@ -42,6 +42,9 @@ namespace RNS {
|
||||
static bool __allow_probes;
|
||||
static bool panic_on_interface_error;
|
||||
|
||||
static uint16_t _persist_interval;
|
||||
static uint16_t _clean_interval;
|
||||
|
||||
public:
|
||||
// Return the currently running Reticulum instance
|
||||
inline static const Reticulum& get_instance() { return _instance; }
|
||||
@@ -49,18 +52,18 @@ namespace RNS {
|
||||
public:
|
||||
Reticulum();
|
||||
Reticulum(Type::NoneConstructor none) {
|
||||
MEM("Reticulum empty object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Reticulum empty object created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
Reticulum(const Reticulum& reticulum) : _object(reticulum._object) {
|
||||
MEM("Reticulum object copy created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Reticulum object copy created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
virtual ~Reticulum() {
|
||||
MEM("Reticulum object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Reticulum object destroyed, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
}
|
||||
|
||||
inline Reticulum& operator = (const Reticulum& reticulum) {
|
||||
_object = reticulum._object;
|
||||
MEM("Reticulum object copy created by assignment, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get()));
|
||||
MEMF("Reticulum object copy created by assignment, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||
return *this;
|
||||
}
|
||||
inline operator bool() const {
|
||||
@@ -81,7 +84,7 @@ namespace RNS {
|
||||
//void __create_default_config();
|
||||
//void rpc_loop();
|
||||
//void get_interface_stats() const;
|
||||
const std::map<Bytes, Transport::DestinationEntry>& get_path_table() const;
|
||||
const Transport::PathTable& get_path_table() const;
|
||||
const std::map<Bytes, Transport::RateEntry>& get_rate_table() const;
|
||||
bool drop_path(const Bytes& destination);
|
||||
uint16_t drop_all_via(const Bytes& transport_hash);
|
||||
@@ -144,15 +147,19 @@ namespace RNS {
|
||||
|
||||
// getters/setters
|
||||
inline bool is_connected_to_shared_instance() const { assert(_object); return _object->_is_connected_to_shared_instance; }
|
||||
inline static uint16_t persist_interval() { return _persist_interval; }
|
||||
inline static void persist_interval(uint16_t persist_interval) { _persist_interval = persist_interval; }
|
||||
inline static uint16_t clean_interval() { return _clean_interval; }
|
||||
inline static void clean_interval(uint16_t clean_interval) { _clean_interval = clean_interval; }
|
||||
|
||||
private:
|
||||
class Object {
|
||||
public:
|
||||
Object() {
|
||||
MEM("Reticulum data object created, this: " + std::to_string((uintptr_t)this));
|
||||
MEMF("Reticulum data object created, this: %p", (void*)this);
|
||||
}
|
||||
virtual ~Object() {
|
||||
MEM("Reticulum data object destroyed, this: " + std::to_string((uintptr_t)this));
|
||||
MEMF("Reticulum data object destroyed, this: %p", (void*)this);
|
||||
}
|
||||
private:
|
||||
|
||||
@@ -177,6 +184,8 @@ namespace RNS {
|
||||
};
|
||||
std::shared_ptr<Object> _object;
|
||||
|
||||
// CBA For access to private static members by Transport class
|
||||
friend class Transport;
|
||||
};
|
||||
|
||||
}
|
||||
+712
-739
File diff suppressed because it is too large.
Load diff
+138
-57
@@ -3,6 +3,7 @@
|
||||
#include "Packet.h"
|
||||
#include "Bytes.h"
|
||||
#include "Type.h"
|
||||
#include "Utilities/Memory.h"
|
||||
|
||||
#include <map>
|
||||
#include <vector>
|
||||
@@ -13,12 +14,9 @@
|
||||
#include <functional>
|
||||
#include <stdint.h>
|
||||
|
||||
//#define INTERFACES_SET
|
||||
//#define INTERFACES_LIST
|
||||
#define INTERFACES_MAP
|
||||
|
||||
//#define DESTINATIONS_SET
|
||||
#define DESTINATIONS_MAP
|
||||
#ifndef RNS_LEAN_PATH_TABLE
|
||||
#define RNS_LEAN_PATH_TABLE 1
|
||||
#endif
|
||||
|
||||
namespace RNS {
|
||||
|
||||
@@ -56,6 +54,10 @@ namespace RNS {
|
||||
class Transport {
|
||||
|
||||
public:
|
||||
|
||||
using InterfaceTable = std::map<Bytes, Interface&>;
|
||||
using DestinationTable = std::map<Bytes, Destination>;
|
||||
|
||||
class Callbacks {
|
||||
public:
|
||||
using receive_packet = void(*)(const Bytes& raw, const Interface& interface);
|
||||
@@ -68,8 +70,6 @@ namespace RNS {
|
||||
friend class Transport;
|
||||
};
|
||||
|
||||
public:
|
||||
|
||||
class PacketEntry {
|
||||
public:
|
||||
PacketEntry() {}
|
||||
@@ -99,40 +99,110 @@ namespace RNS {
|
||||
}
|
||||
#endif
|
||||
};
|
||||
using PacketTable = std::map<Bytes, PacketEntry>;
|
||||
|
||||
// CBA TODO Analyze safety of using Inrerface references here
|
||||
// CBA TODO Analyze safety of using Packet references here
|
||||
class DestinationEntry {
|
||||
public:
|
||||
DestinationEntry() {}
|
||||
DestinationEntry(double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set<Bytes>& random_blobs, const Bytes& receiving_interface, const Bytes& packet) :
|
||||
DestinationEntry(double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set<Bytes>& random_blobs, const Interface& receiving_interface, const Packet& announce_packet) :
|
||||
_timestamp(timestamp),
|
||||
_received_from(received_from),
|
||||
_hops(announce_hops),
|
||||
_expires(expires),
|
||||
_random_blobs(random_blobs),
|
||||
#if RNS_LEAN_PATH_TABLE
|
||||
_receiving_interface(receiving_interface)
|
||||
#else
|
||||
_receiving_interface(receiving_interface),
|
||||
_announce_packet(packet)
|
||||
_announce_packet(announce_packet)
|
||||
#endif
|
||||
{
|
||||
if (receiving_interface) _receiving_interface_hash = receiving_interface.get_hash();
|
||||
if (announce_packet) _announce_packet_hash = announce_packet.get_hash();
|
||||
}
|
||||
DestinationEntry(double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set<Bytes>& random_blobs, const Bytes& receiving_interface_hash, const Bytes& announce_packet_hash) :
|
||||
_timestamp(timestamp),
|
||||
_received_from(received_from),
|
||||
_hops(announce_hops),
|
||||
_expires(expires),
|
||||
_random_blobs(random_blobs),
|
||||
_receiving_interface_hash(receiving_interface_hash),
|
||||
_announce_packet_hash(announce_packet_hash)
|
||||
{
|
||||
}
|
||||
inline operator bool() const {
|
||||
return (_receiving_interface_hash && _announce_packet_hash);
|
||||
}
|
||||
public:
|
||||
inline Interface receiving_interface() const { return find_interface_from_hash(_receiving_interface); }
|
||||
inline Packet announce_packet() const { return get_cached_packet(_announce_packet); }
|
||||
// Lazy load receiving_interface and announce_packet
|
||||
inline Interface& receiving_interface() {
|
||||
if (!_receiving_interface) _receiving_interface = find_interface_from_hash(_receiving_interface_hash);
|
||||
return _receiving_interface;
|
||||
}
|
||||
#if RNS_LEAN_PATH_TABLE
|
||||
// Lazy load transient announce packet
|
||||
inline Packet announce_packet() {
|
||||
Packet announce_packet = get_cached_packet(_announce_packet_hash);
|
||||
if (announce_packet) {
|
||||
// Announce packet is cached in packed state
|
||||
// so we need to unpack it before accessing.
|
||||
announce_packet.unpack();
|
||||
// We increase the hops, since reading a packet
|
||||
// from cache is equivalent to receiving it again
|
||||
// over an interface. It is cached with it's non-
|
||||
// increased hop-count.
|
||||
announce_packet.hops(announce_packet.hops() + 1);
|
||||
}
|
||||
return announce_packet;
|
||||
}
|
||||
#else
|
||||
// Lazy load and cache announce packet
|
||||
inline Packet& announce_packet() {
|
||||
if (!_announce_packet) _announce_packet = get_cached_packet(_announce_packet_hash);
|
||||
if (_announce_packet) {
|
||||
// Announce packet is cached in packed state
|
||||
// so we need to unpack it before accessing.
|
||||
_announce_packet.unpack();
|
||||
// We increase the hops, since reading a packet
|
||||
// from cache is equivalent to receiving it again
|
||||
// over an interface. It is cached with it's non-
|
||||
// increased hop-count.
|
||||
_announce_packet.hops(_announce_packet.hops() + 1);
|
||||
}
|
||||
return _announce_packet;
|
||||
}
|
||||
#endif
|
||||
// Getters and setters for receiving_interface_hash and announce_packet_hash
|
||||
inline Bytes receiving_interface_hash() const { if (_receiving_interface) return _receiving_interface.get_hash(); return _receiving_interface_hash; }
|
||||
inline void receiving_interface_hash(const Bytes& hash) { if (hash == receiving_interface_hash()) return; _receiving_interface_hash = hash; _receiving_interface = {Type::NONE}; }
|
||||
#if RNS_LEAN_PATH_TABLE
|
||||
inline Bytes announce_packet_hash() const { return _announce_packet_hash; }
|
||||
inline void announce_packet_hash(const Bytes& hash) { _announce_packet_hash = hash; }
|
||||
#else
|
||||
inline Bytes announce_packet_hash() const { if (_announce_packet) return _announce_packet.get_hash(); return _announce_packet_hash; }
|
||||
inline void announce_packet_hash(const Bytes& hash) { if (hash == announce_packet_hash()) return; _announce_packet_hash = hash; _announce_packet = {Type::NONE}; }
|
||||
#endif
|
||||
public:
|
||||
double _timestamp = 0;
|
||||
Bytes _received_from;
|
||||
uint8_t _hops = 0;
|
||||
double _expires = 0;
|
||||
std::set<Bytes> _random_blobs;
|
||||
//Interface _receiving_interface = {Type::NONE};
|
||||
Bytes _receiving_interface;
|
||||
//const Packet& _announce_packet;
|
||||
//Packet _announce_packet = {Type::NONE};
|
||||
Bytes _announce_packet;
|
||||
inline bool operator < (const DestinationEntry& entry) const {
|
||||
// sort by ascending timestamp (oldest entries at the top)
|
||||
return _timestamp < entry._timestamp;
|
||||
}
|
||||
private:
|
||||
Interface _receiving_interface = {Type::NONE};
|
||||
Bytes _receiving_interface_hash;
|
||||
#if !RNS_LEAN_PATH_TABLE
|
||||
//const Packet& _announce_packet;
|
||||
Packet _announce_packet = {Type::NONE};
|
||||
#endif
|
||||
Bytes _announce_packet_hash;
|
||||
public:
|
||||
#ifndef NDEBUG
|
||||
inline std::string debugString() const {
|
||||
std::string dump;
|
||||
@@ -141,8 +211,8 @@ namespace RNS {
|
||||
" hops=" + std::to_string(_hops) +
|
||||
" expires=" + std::to_string(_expires) +
|
||||
//" random_blobs=" + _random_blobs +
|
||||
" receiving_interface=" + _receiving_interface.toHex() +
|
||||
" announce_packet=" + _announce_packet.toHex();
|
||||
" receiving_interface=" + receiving_interface_hash().toHex() +
|
||||
" announce_packet=" + announce_packet_hash().toHex();
|
||||
dump += " random_blobs=(";
|
||||
for (auto& blob : _random_blobs) {
|
||||
dump += blob.toHex() + ",";
|
||||
@@ -152,6 +222,8 @@ namespace RNS {
|
||||
}
|
||||
#endif
|
||||
};
|
||||
//using PathTable = std::map<Bytes, DestinationEntry>;
|
||||
using PathTable = std::map<Bytes, DestinationEntry, std::less<Bytes>, Utilities::Memory::ContainerAllocator<std::pair<const Bytes, DestinationEntry>>>;
|
||||
|
||||
// CBA TODO Analyze safety of using Inrerface references here
|
||||
// CBA TODO Analyze safety of using Packet references here
|
||||
@@ -183,6 +255,8 @@ namespace RNS {
|
||||
bool _block_rebroadcasts = false;
|
||||
const Interface _attached_interface = {Type::NONE};
|
||||
};
|
||||
//using AnnounceTable = std::map<Bytes, AnnounceEntry>;
|
||||
using AnnounceTable = std::map<Bytes, AnnounceEntry, std::less<Bytes>, Utilities::Memory::ContainerAllocator<std::pair<const Bytes, AnnounceEntry>>>;
|
||||
|
||||
// CBA TODO Analyze safety of using Inrerface references here
|
||||
class LinkEntry {
|
||||
@@ -210,6 +284,7 @@ namespace RNS {
|
||||
bool _validated = false;
|
||||
double _proof_timeout = 0;
|
||||
};
|
||||
using LinkTable = std::map<Bytes, LinkEntry>;
|
||||
|
||||
// CBA TODO Analyze safety of using Inrerface references here
|
||||
class ReverseEntry {
|
||||
@@ -225,6 +300,7 @@ namespace RNS {
|
||||
const Interface _outbound_interface = {Type::NONE};
|
||||
double _timestamp = 0;
|
||||
};
|
||||
using ReverseTable = std::map<Bytes, ReverseEntry>;
|
||||
|
||||
// CBA TODO Analyze safety of using Inrerface references here
|
||||
class PathRequestEntry {
|
||||
@@ -240,6 +316,7 @@ namespace RNS {
|
||||
double _timeout = 0;
|
||||
const Interface _requesting_interface = {Type::NONE};
|
||||
};
|
||||
using PathRequestTable = std::map<Bytes, PathRequestEntry>;
|
||||
|
||||
/*
|
||||
// CBA TODO Analyze safety of using Inrerface references here
|
||||
@@ -279,9 +356,10 @@ namespace RNS {
|
||||
public:
|
||||
const Bytes _tunnel_id;
|
||||
const Bytes _interface_hash;
|
||||
std::map<Bytes, DestinationEntry> _serialised_paths;
|
||||
PathTable _serialised_paths;
|
||||
double _expires = 0;
|
||||
};
|
||||
using TunnelTable = std::map<Bytes, TunnelEntry>;
|
||||
|
||||
class RateEntry {
|
||||
public:
|
||||
@@ -296,6 +374,7 @@ namespace RNS {
|
||||
double _blocked_until = 0.0;
|
||||
std::vector<double> _timestamps;
|
||||
};
|
||||
using RateTable = std::map<Bytes, RateEntry>;
|
||||
|
||||
public:
|
||||
static void start(const Reticulum& reticulum_instance);
|
||||
@@ -312,20 +391,23 @@ namespace RNS {
|
||||
static void handle_tunnel(const Bytes& tunnel_id, const Interface& interface);
|
||||
static void register_interface(Interface& interface);
|
||||
static void deregister_interface(const Interface& interface);
|
||||
inline static const std::map<Bytes, Interface&> get_interfaces() { return _interfaces; }
|
||||
inline static const InterfaceTable& get_interfaces() { return _interfaces; }
|
||||
static void register_destination(Destination& destination);
|
||||
static void deregister_destination(const Destination& destination);
|
||||
static void register_link(Link& link);
|
||||
static void activate_link(Link& link);
|
||||
static void register_announce_handler(HAnnounceHandler handler);
|
||||
static void deregister_announce_handler(HAnnounceHandler handler);
|
||||
static bool is_interface_from_hash(const Bytes& interface_hash);
|
||||
static Interface find_interface_from_hash(const Bytes& interface_hash);
|
||||
static bool should_cache_packet(const Packet& packet);
|
||||
static bool cache_packet(const Packet& packet, bool force_cache = false);
|
||||
static bool is_cached_packet(const Bytes& packet_hash);
|
||||
static Packet get_cached_packet(const Bytes& packet_hash);
|
||||
static bool clear_cached_packet(const Bytes& packet_hash);
|
||||
static bool cache_request_packet(const Packet& packet);
|
||||
static void cache_request(const Bytes& packet_hash, const Destination& destination);
|
||||
static DestinationEntry& get_path(const Bytes& destination_hash);
|
||||
static bool remove_path(const Bytes& destination_hash);
|
||||
static bool has_path(const Bytes& destination_hash);
|
||||
static uint8_t hops_to(const Bytes& destination_hash);
|
||||
@@ -371,6 +453,7 @@ namespace RNS {
|
||||
|
||||
// CBA
|
||||
static void cull_path_table();
|
||||
static void cull_announce_table();
|
||||
|
||||
// getters/setters
|
||||
static inline void set_receive_packet_callback(Callbacks::receive_packet callback) { _callbacks._receive_packet = callback; }
|
||||
@@ -380,55 +463,48 @@ namespace RNS {
|
||||
static inline const Identity& identity() { return _identity; }
|
||||
inline static uint16_t path_table_maxsize() { return _path_table_maxsize; }
|
||||
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 uint16_t announce_table_maxsize() { return _announce_table_maxsize; }
|
||||
inline static void announce_table_maxsize(uint16_t announce_table_maxsize) { _announce_table_maxsize = announce_table_maxsize; }
|
||||
inline static uint16_t hashlist_maxsize() { return _hashlist_maxsize; }
|
||||
inline static void hashlist_maxsize(uint16_t hashlist_maxsize) { _hashlist_maxsize = hashlist_maxsize; }
|
||||
inline static uint16_t max_pr_tags() { return _max_pr_tags; }
|
||||
inline static void max_pr_tags(uint16_t max_pr_tags) { _max_pr_tags = max_pr_tags; }
|
||||
inline static uint16_t path_table_maxpersist() { return _path_table_maxpersist; }
|
||||
inline static void path_table_maxpersist(uint16_t path_table_maxpersist) { _path_table_maxpersist = path_table_maxpersist; }
|
||||
// CBA TEST
|
||||
static inline void identity(Identity& identity) { _identity = identity; }
|
||||
|
||||
inline static const std::map<Bytes, DestinationEntry>& get_destination_table() { return _destination_table; }
|
||||
inline static const std::map<Bytes, RateEntry>& get_announce_rate_table() { return _announce_rate_table; }
|
||||
inline static const std::map<Bytes, LinkEntry>& get_link_table() { return _link_table; }
|
||||
inline static const PathTable& get_path_table() { return _path_table; }
|
||||
inline static const RateTable& get_announce_rate_table() { return _announce_rate_table; }
|
||||
inline static const LinkTable& get_link_table() { return _link_table; }
|
||||
|
||||
private:
|
||||
// CBA MUST use references to interfaces here in order for virtul overrides for send/receive to work
|
||||
#if defined(INTERFACES_SET)
|
||||
// set sorted, can use find
|
||||
//static std::set<std::reference_wrapper<const Interface>, std::less<const Interface>> _interfaces; // All active interfaces
|
||||
static std::set<std::reference_wrapper<Interface>, std::less<Interface>> _interfaces; // All active interfaces
|
||||
#elif defined(INTERFACES_LIST)
|
||||
// list is unsorted, can't use find
|
||||
static std::list<std::reference_wrapper<Interface>> _interfaces; // All active interfaces
|
||||
#elif defined(INTERFACES_MAP)
|
||||
// map is sorted, can use find
|
||||
static std::map<Bytes, Interface&> _interfaces; // All active interfaces
|
||||
#endif
|
||||
#if defined(DESTINATIONS_SET)
|
||||
static std::set<Destination> _destinations; // All active destinations
|
||||
#elif defined(DESTINATIONS_MAP)
|
||||
static std::map<Bytes, Destination> _destinations; // All active destinations
|
||||
#endif
|
||||
static InterfaceTable _interfaces; // All active interfaces
|
||||
static DestinationTable _destinations; // All active destinations
|
||||
// CBA TODO: Reconsider using std::set for enforcing uniqueness. Maybe consider std::map keyed on hash instead
|
||||
static std::set<Link> _pending_links; // Links that are being established
|
||||
static std::set<Link> _active_links; // Links that are active
|
||||
static std::set<Bytes> _packet_hashlist; // A list of packet hashes for duplicate detection
|
||||
static std::list<PacketReceipt> _receipts; // Receipts of all outgoing packets for proof processing
|
||||
static std::set<Link> _pending_links; // Links that are being established
|
||||
static std::set<Link> _active_links; // Links that are active
|
||||
static std::set<Bytes> _packet_hashlist; // A list of packet hashes for duplicate detection
|
||||
static std::list<PacketReceipt> _receipts; // Receipts of all outgoing packets for proof processing
|
||||
|
||||
// TODO: "destination_table" should really be renamed to "path_table"
|
||||
// Notes on memory usage: 1 megabyte of memory can store approximately
|
||||
// 55.100 path table entries or approximately 22.300 link table entries.
|
||||
|
||||
static std::map<Bytes, AnnounceEntry> _announce_table; // A table for storing announces currently waiting to be retransmitted
|
||||
static std::map<Bytes, DestinationEntry> _destination_table; // A lookup table containing the next hop to a given destination
|
||||
static std::map<Bytes, ReverseEntry> _reverse_table; // A lookup table for storing packet hashes used to return proofs and replies
|
||||
static std::map<Bytes, LinkEntry> _link_table; // A lookup table containing hops for links
|
||||
static std::map<Bytes, AnnounceEntry> _held_announces; // A table containing temporarily held announce-table entries
|
||||
static std::set<HAnnounceHandler> _announce_handlers; // A table storing externally registered announce handlers
|
||||
static std::map<Bytes, TunnelEntry> _tunnels; // A table storing tunnels to other transport instances
|
||||
static std::map<Bytes, RateEntry> _announce_rate_table; // A table for keeping track of announce rates
|
||||
static std::map<Bytes, double> _path_requests; // A table for storing path request timestamps
|
||||
static AnnounceTable _announce_table; // A table for storing announces currently waiting to be retransmitted
|
||||
static PathTable _path_table; // A lookup table containing the next hop to a given destination
|
||||
static ReverseTable _reverse_table; // A lookup table for storing packet hashes used to return proofs and replies
|
||||
static LinkTable _link_table; // A lookup table containing hops for links
|
||||
static AnnounceTable _held_announces; // A table containing temporarily held announce-table entries
|
||||
static TunnelTable _tunnels; // A table storing tunnels to other transport instances
|
||||
static RateTable _announce_rate_table; // A table for keeping track of announce rates
|
||||
static std::set<HAnnounceHandler> _announce_handlers; // A table storing externally registered announce handlers
|
||||
static std::map<Bytes, double> _path_requests; // A table for storing path request timestamps
|
||||
|
||||
static std::map<Bytes, PathRequestEntry> _discovery_path_requests; // A table for keeping track of path requests on behalf of other nodes
|
||||
static std::set<Bytes> _discovery_pr_tags; // A table for keeping track of tagged path requests
|
||||
static PathRequestTable _discovery_path_requests; // A table for keeping track of path requests on behalf of other nodes
|
||||
static std::set<Bytes> _discovery_pr_tags; // A table for keeping track of tagged path requests
|
||||
|
||||
// Transport control destinations are used
|
||||
// for control purposes like path requests
|
||||
@@ -444,7 +520,7 @@ namespace RNS {
|
||||
static std::map<Bytes, const Interface&> _pending_local_path_requests;
|
||||
|
||||
// CBA
|
||||
static std::map<Bytes, PacketEntry> _packet_table; // A lookup table containing announce packets for known paths
|
||||
static PacketTable _packet_table; // A lookup table containing announce packets for known paths
|
||||
|
||||
//z _local_client_rssi_cache = []
|
||||
//z _local_client_snr_cache = []
|
||||
@@ -472,7 +548,8 @@ namespace RNS {
|
||||
static uint16_t _path_table_maxpersist;
|
||||
static double _last_saved;
|
||||
static float _save_interval;
|
||||
static uint32_t _destination_table_crc;
|
||||
static uint32_t _path_table_crc;
|
||||
static uint16_t _announce_table_maxsize;
|
||||
|
||||
static Reticulum _owner;
|
||||
static Identity _identity;
|
||||
@@ -485,7 +562,11 @@ namespace RNS {
|
||||
static uint32_t _packets_received;
|
||||
static uint32_t _destinations_added;
|
||||
static size_t _last_memory;
|
||||
static size_t _last_psram;
|
||||
static size_t _last_flash;
|
||||
|
||||
// CBA Block re-entrance
|
||||
static bool cleaning_caches;
|
||||
};
|
||||
|
||||
template <typename M, typename S>
|
||||
|
||||
+33
-14
@@ -5,6 +5,28 @@
|
||||
#include <stdint.h>
|
||||
#include <math.h>
|
||||
|
||||
#ifndef RNS_QUEUED_ANNOUNCES_MAX
|
||||
#define RNS_QUEUED_ANNOUNCES_MAX 20
|
||||
#endif
|
||||
|
||||
#ifndef RNS_RECEIPTS_MAX
|
||||
#define RNS_RECEIPTS_MAX 20
|
||||
#endif
|
||||
|
||||
#ifndef RNS_RATE_TIMESTAMPS_MAX
|
||||
#define RNS_RATE_TIMESTAMPS_MAX 16
|
||||
#endif
|
||||
|
||||
#ifndef RNS_RANDOM_BLOBS_PERSIST_MAX
|
||||
//#define RNS_RANDOM_BLOBS_PERSIST_MAX 32
|
||||
#define RNS_RANDOM_BLOBS_PERSIST_MAX 16
|
||||
#endif
|
||||
|
||||
#ifndef RNS_RANDOM_BLOBS_MAX
|
||||
//#define RNS_RANDOM_BLOBS_MAX 64
|
||||
#define RNS_RANDOM_BLOBS_MAX 32
|
||||
#endif
|
||||
|
||||
|
||||
namespace RNS { namespace Type {
|
||||
|
||||
@@ -61,7 +83,7 @@ namespace RNS { namespace Type {
|
||||
*/
|
||||
static const bool LINK_MTU_DISCOVERY = true;
|
||||
|
||||
static const uint16_t MAX_QUEUED_ANNOUNCES = 16384;
|
||||
static const uint16_t MAX_QUEUED_ANNOUNCES = RNS_QUEUED_ANNOUNCES_MAX;
|
||||
static const uint32_t QUEUED_ANNOUNCE_LIFE = 60*60*24;
|
||||
|
||||
static const uint8_t ANNOUNCE_CAP = 2;
|
||||
@@ -82,7 +104,7 @@ namespace RNS { namespace Type {
|
||||
but it can be configured individually on a per-interface basis.
|
||||
*/
|
||||
|
||||
static const uint16_t MINIMUM_BITRATE = 500;
|
||||
static const uint16_t MINIMUM_BITRATE = 5;
|
||||
|
||||
// TODO: To reach the 300bps level without unreasonably impacting
|
||||
// performance on faster links, we need a mechanism for setting
|
||||
@@ -108,13 +130,11 @@ namespace RNS { namespace Type {
|
||||
//static const uint16_t JOB_INTERVAL = 60*5;
|
||||
static const uint16_t JOB_INTERVAL = 60;
|
||||
// CBA TEST
|
||||
//static const uint16_t CLEAN_INTERVAL = 60*15;
|
||||
static const uint16_t CLEAN_INTERVAL = 60;
|
||||
static const uint16_t CLEAN_INTERVAL = 60*15;
|
||||
// CBA MCU
|
||||
//static const uint16_t PERSIST_INTERVAL = 60*60*12;
|
||||
// CBA TEST
|
||||
//static const uint16_t PERSIST_INTERVAL = 60*60;
|
||||
static const uint16_t PERSIST_INTERVAL = 60;
|
||||
static const uint16_t PERSIST_INTERVAL = 60*60;
|
||||
static const uint16_t GRACIOUS_PERSIST_INTERVAL = 60*5;
|
||||
|
||||
static const uint8_t DESTINATION_LENGTH = TRUNCATED_HASHLENGTH/8; // In bytes
|
||||
@@ -213,7 +233,7 @@ namespace RNS { namespace Type {
|
||||
static const float KEEPALIVE_MAX_RTT = 1.75;
|
||||
static const uint8_t KEEPALIVE_TIMEOUT_FACTOR = 4;
|
||||
// Grace period in seconds used in link timeout calculation.
|
||||
static const uint8_t STALE_GRACE = 2;
|
||||
static const uint8_t STALE_GRACE = 5;
|
||||
// Interval for sending keep-alive packets on established links in seconds.
|
||||
static const uint16_t KEEPALIVE = 360;
|
||||
/*
|
||||
@@ -420,18 +440,17 @@ namespace RNS { namespace Type {
|
||||
static const uint8_t LOCAL_REBROADCASTS_MAX = 2; // How many local rebroadcasts of an announce is allowed
|
||||
|
||||
static const uint8_t PATH_REQUEST_TIMEOUT = 15; // Default timuout for client path requests in seconds
|
||||
static constexpr const float PATH_REQUEST_GRACE = 0.35; // Grace time before a path announcement is made, allows directly reachable peers to respond first
|
||||
static constexpr const float PATH_REQUEST_GRACE = 0.4; // Grace time before a path announcement is made, allows directly reachable peers to respond first
|
||||
static const uint8_t PATH_REQUEST_RW = 2; // Path request random window
|
||||
static const uint8_t PATH_REQUEST_MI = 5; // Minimum interval in seconds for automated path requests
|
||||
|
||||
static constexpr const float LINK_TIMEOUT = Link::STALE_TIME * 1.25;
|
||||
static const uint16_t REVERSE_TIMEOUT = 30*60; // Reverse table entries are removed after 30 minutes
|
||||
static const uint16_t REVERSE_TIMEOUT = 8*60; // Reverse table entries are removed after 8 minutes
|
||||
// CBA MCU
|
||||
//static const uint16_t MAX_RECEIPTS = 1024; // Maximum number of receipts to keep track of
|
||||
static const uint16_t MAX_RECEIPTS = 20; // Maximum number of receipts to keep track of
|
||||
static const uint8_t MAX_RATE_TIMESTAMPS = 16; // Maximum number of announce timestamps to keep per destination
|
||||
static const uint8_t PERSIST_RANDOM_BLOBS = 32; // Maximum number of random blobs per destination to persist to disk
|
||||
static const uint8_t MAX_RANDOM_BLOBS = 64; // Maximum number of random blobs per destination to keep in memory
|
||||
static const uint16_t MAX_RECEIPTS = RNS_RECEIPTS_MAX; // Maximum number of receipts to keep track of
|
||||
static const uint8_t MAX_RATE_TIMESTAMPS = RNS_RATE_TIMESTAMPS_MAX; // Maximum number of announce timestamps to keep per destination
|
||||
static const uint8_t PERSIST_RANDOM_BLOBS = RNS_RANDOM_BLOBS_PERSIST_MAX; // Maximum number of random blobs per destination to persist to disk
|
||||
static const uint8_t MAX_RANDOM_BLOBS = RNS_RANDOM_BLOBS_MAX; // Maximum number of random blobs per destination to keep in memory
|
||||
|
||||
// CBA MCU
|
||||
//static const uint32_t DESTINATION_TIMEOUT = 60*60*24*7; // Destination table entries are removed if unused for one week
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
#include "Memory.h"
|
||||
|
||||
#include <new>
|
||||
|
||||
using namespace RNS;
|
||||
using namespace RNS::Utilities;
|
||||
|
||||
#ifndef RNS_DEFAULT_ALLOCATOR
|
||||
#if defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
// Use TLSF on NRF52 boards by default since they don't embed their own advanced memory manager like ESP32 does
|
||||
#define RNS_DEFAULT_ALLOCATOR RNS_HEAP_POOL_ALLOCATOR
|
||||
#else
|
||||
#define RNS_DEFAULT_ALLOCATOR RNS_HEAP_ALLOCATOR
|
||||
#endif
|
||||
#endif
|
||||
#ifndef RNS_CONTAINER_ALLOCATOR
|
||||
#if defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
// Use TLSF on NRF52 boards by default since they don't embed their own advanced memory manager like ESP32 does
|
||||
#define RNS_CONTAINER_ALLOCATOR RNS_HEAP_POOL_ALLOCATOR
|
||||
#else
|
||||
#define RNS_CONTAINER_ALLOCATOR RNS_HEAP_ALLOCATOR
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef RNS_HEAP_POOL_BUFFER_SIZE
|
||||
#define RNS_HEAP_POOL_BUFFER_SIZE 1024 * 1000
|
||||
#endif
|
||||
#ifndef RNS_PSRAM_POOL_BUFFER_SIZE
|
||||
#define RNS_PSRAM_POOL_BUFFER_SIZE 0
|
||||
#endif
|
||||
#ifndef RNS_ALTHEAP_POOL_BUFFER_SIZE
|
||||
#define RNS_ALTHEAP_POOL_BUFFER_SIZE 0
|
||||
#endif
|
||||
#ifndef BUFFER_FRACTION
|
||||
#define BUFFER_FRACTION 0.8
|
||||
#endif
|
||||
|
||||
|
||||
//char _tlsf_msg[256] = "";
|
||||
|
||||
/*static*/ Memory::pool_info Memory::heap_pool_info(RNS_HEAP_POOL_ALLOCATOR, RNS_HEAP_POOL_BUFFER_SIZE);
|
||||
/*static*/ Memory::pool_info Memory::psram_pool_info(RNS_PSRAM_POOL_ALLOCATOR, RNS_PSRAM_POOL_BUFFER_SIZE);;
|
||||
/*static*/ Memory::pool_info Memory::altheap_pool_info(RNS_ALTHEAP_POOL_ALLOCATOR, RNS_ALTHEAP_POOL_BUFFER_SIZE);;
|
||||
/*static*/ Memory::allocator_info Memory::default_allocator_info;
|
||||
/*static*/ Memory::allocator_info Memory::container_allocator_info;
|
||||
|
||||
|
||||
/*static*/ void Memory::pool_init(Memory::pool_info& pool_info) {
|
||||
if (pool_info.pool_init) {
|
||||
return;
|
||||
}
|
||||
pool_info.pool_init = true;
|
||||
printf("Initializing TLSF pool...\n");
|
||||
|
||||
#if defined(ESP32)
|
||||
heap_pool_info.contiguous_size = ESP.getMaxAllocHeap();
|
||||
psram_pool_info.contiguous_size = ESP.getMaxAllocPsram();
|
||||
altheap_pool_info.contiguous_size = ESP.getMaxAllocHeap();
|
||||
printf("TLSF: Heap contiguous_size: %u\n", ESP.getMaxAllocHeap());
|
||||
printf("TLSF: PSRAM contiguous_size: %u\n", ESP.getMaxAllocPsram());
|
||||
printf("TLSF: contiguous_size: %u\n", pool_info.contiguous_size);
|
||||
if (pool_info.buffer_size == 0) {
|
||||
// CBA NOTE Using fp mathhere somehow causes tlsf_create_with_pool() to fail.
|
||||
//pool_info.buffer_size = (size_t)(pool_info.contiguous_size * BUFFER_FRACTION);
|
||||
// Compute 80% exactly using integers
|
||||
pool_info.buffer_size = (pool_info.contiguous_size * 4) / 5;
|
||||
}
|
||||
// Round DOWN to TLSF alignment
|
||||
size_t align = tlsf_align_size();
|
||||
pool_info.buffer_size &= ~(align - 1);
|
||||
void* raw_buffer = nullptr;
|
||||
// If pool type is PSRAM then allocate pool buffer from PSRAM
|
||||
if (pool_info.type == RNS_PSRAM_POOL_ALLOCATOR) {
|
||||
raw_buffer = (void*)ps_malloc(pool_info.buffer_size);
|
||||
}
|
||||
// Otherwise just allocate from heap
|
||||
else {
|
||||
raw_buffer = (void*)aligned_alloc(align, pool_info.buffer_size);
|
||||
}
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
heap_pool_info.contiguous_size = dbgHeapFree();
|
||||
altheap_pool_info.buffer_size = dbgHeapFree();
|
||||
TRACEF("TLSF: contiguous_size: %u", pool_info.contiguous_size);
|
||||
if (pool_info.buffer_size == 0) {
|
||||
pool_info.buffer_size = (size_t)(pool_info.contiguous_size * BUFFER_FRACTION);
|
||||
}
|
||||
// For NRF52 round to kB
|
||||
pool_info.buffer_size = (size_t)(pool_info.buffer_size / 1024) * 1024;
|
||||
TRACEF("TLSF: buffer_size: %u", pool_info.buffer_size);
|
||||
void* raw_buffer = malloc(pool_info.buffer_size);
|
||||
#else
|
||||
pool_info.buffer_size = (size_t)RNS_HEAP_POOL_BUFFER_SIZE;
|
||||
TRACEF("TLSF: buffer_size: %u", pool_info.buffer_size);
|
||||
void* raw_buffer = malloc(pool_info.buffer_size);
|
||||
#endif
|
||||
if (raw_buffer == nullptr) {
|
||||
ERROR("-- TLSF: buffer allocation FAILED");
|
||||
printf("TLSF buffer allocation FAILED!\n");
|
||||
//strcpy(_tlsf_msg, "-- TLSF: buffer allocation FAILED!!!");
|
||||
}
|
||||
else {
|
||||
#if 1
|
||||
pool_info.tlsf = tlsf_create_with_pool(raw_buffer, pool_info.buffer_size);
|
||||
if (pool_info.tlsf == nullptr) {
|
||||
//sprintf(_tlsf_msg, "TLSF: initialization with align=%d, contiguous=%d, size=%d FAILED!!!", tlsf_align_size(), pool_info.contiguous_size, pool_info.buffer_size);
|
||||
printf("TLSF: initialization with align=%d, contiguous=%d, size=%d FAILED!!!\n", tlsf_align_size(), pool_info.contiguous_size, pool_info.buffer_size);
|
||||
}
|
||||
else {
|
||||
//sprintf(_tlsf_msg, "TLSF: initialization with align=%d, contiguous=%d, size=%d SUCCESSFUL!!!", tlsf_align_size(), pool_info.contiguous_size, pool_info.buffer_size);
|
||||
printf("TLSF: initialization with align=%d, contiguous=%d, size=%d SUCCESSFUL!!!\n", tlsf_align_size(), pool_info.contiguous_size, pool_info.buffer_size);
|
||||
}
|
||||
#else
|
||||
Serial.print("TLSF: raw_buffer: ");
|
||||
Serial.println((long)raw_buffer);
|
||||
Serial.print("TLSF: align_size: ");
|
||||
Serial.println((long)tlsf_align_size());
|
||||
void* aligned_buffer = (void*)(((size_t)raw_buffer + (tlsf_align_size() - 1)) & ~(tlsf_align_size() - 1));
|
||||
Serial.print("TLSF: aligned_buffer: ");
|
||||
Serial.println((long)aligned_buffer);
|
||||
pool_info.tlsf = tlsf_create_with_pool(aligned_buffer, pool_info.buffer_size-(size_t)((uint32_t)aligned_buffer - (uint32_t)raw_buffer));
|
||||
//tlfs = tlsf_create_with_pool(aligned_buffer, pool_info.buffer_size--(size_t)((uint32_t)aligned_buffer - (uint32_t)raw_buffer));
|
||||
#endif
|
||||
if (pool_info.tlsf == nullptr) {
|
||||
ERROR("-- TLSF: initialization of FAILED");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/*static*/ void* Memory::pool_malloc(Memory::pool_info& pool_info, size_t size) {
|
||||
if (size == 0) return nullptr;
|
||||
//if (pool_info.tlsf == nullptr) {
|
||||
if (!pool_info.pool_init) {
|
||||
Memory::pool_init(pool_info);
|
||||
}
|
||||
void* p;
|
||||
if (pool_info.tlsf != nullptr) {
|
||||
//struct tlsf_stats stats;
|
||||
//memset(&stats, 0, sizeof(stats));
|
||||
//tlsf_walk_pool(tlsf_get_pool(pool_info.tlsf), tlsf_mem_walker, &stats);
|
||||
//if (tlsf_check(pool_info.tlsf) != 0) {
|
||||
// printf("--- HEAP CORRUPTION DETECTED!!!\n");
|
||||
//}
|
||||
//TRACEF("--- allocating memory from tlsf (%u bytes)", size);
|
||||
//printf("--- allocating memory from tlsf (%u bytes) (%u free)\n", size, stats.free_size);
|
||||
p = tlsf_malloc(pool_info.tlsf, size);
|
||||
//TRACEF("--- allocated memory from tlsf (addr=%lx) (%u bytes)", p, size);
|
||||
//printf("--- allocated memory from tlsf (addr=%lx) (%u bytes)\n", p, size);
|
||||
}
|
||||
else {
|
||||
//TRACEF("--- allocating memory (%u bytes)", size);
|
||||
p = malloc(size);
|
||||
//TRACEF("--- allocated memory (addr=%lx) (%u bytes)", p, size);
|
||||
++pool_info.alloc_fault;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/*static*/ void Memory::pool_free(Memory::pool_info& pool_info, void* p, size_t size /*= 0*/) noexcept {
|
||||
if (p == nullptr) return;
|
||||
if (pool_info.tlsf != nullptr) {
|
||||
//TRACEF("--- freeing memory from tlsf (addr=%lx)", p);
|
||||
//printf("--- freeing memory from tlsf (addr=%lx)\n", p);
|
||||
tlsf_free(pool_info.tlsf, p);
|
||||
}
|
||||
else {
|
||||
//TRACEF("--- freeing memory (addr=%lx)", p);
|
||||
free(p);
|
||||
++pool_info.free_fault;
|
||||
}
|
||||
/*
|
||||
if (free_count == _alloc_count) {
|
||||
TRACE("TLFS deinitializing");
|
||||
dump_memory_stats();
|
||||
tlsf_destroy(pool_info.tlsf);
|
||||
pool_info.tlsf = nullptr;
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
|
||||
struct tlsf_stats {
|
||||
uint32_t used_count = 0;
|
||||
uint32_t used_size = 0;
|
||||
uint32_t free_count = 0;
|
||||
uint32_t free_size = 0;
|
||||
uint32_t free_max_size = 0;
|
||||
};
|
||||
|
||||
void tlsf_mem_walker(void* ptr, size_t size, int used, void* user)
|
||||
{
|
||||
if (!user) {
|
||||
return;
|
||||
}
|
||||
struct tlsf_stats* stats = (struct tlsf_stats*)user;
|
||||
if (used) {
|
||||
stats->used_count++;
|
||||
stats->used_size += size;
|
||||
}
|
||||
else {
|
||||
stats->free_count++;
|
||||
stats->free_size += size;
|
||||
if (size > stats->free_max_size) {
|
||||
stats->free_max_size = size;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*static*/ void Memory::dump_pool_stats(Memory::pool_info& pool_info, const char* name /*= ""*/) {
|
||||
//TRACEF("TLSF Message: %s", _tlsf_msg);
|
||||
if (pool_info.tlsf == nullptr) {
|
||||
return;
|
||||
}
|
||||
struct tlsf_stats stats;
|
||||
memset(&stats, 0, sizeof(stats));
|
||||
tlsf_walk_pool(tlsf_get_pool(pool_info.tlsf), tlsf_mem_walker, &stats);
|
||||
HEADF(LOG_TRACE, "%sPool Stats", name);
|
||||
TRACEF(" Buffer Size: %u", pool_info.buffer_size);
|
||||
TRACEF(" Contiguous Size: %u", pool_info.contiguous_size);
|
||||
TRACEF(" Used Count: %u", stats.used_count);
|
||||
TRACEF(" Used Size: %u (%u%% used)", stats.used_size, (unsigned)((double)stats.used_size / (double)pool_info.buffer_size * 100.0));
|
||||
TRACEF(" Free Count: %u", stats.free_count);
|
||||
TRACEF(" Free Size: %u (%u%% free)", stats.free_size, (unsigned)((double)stats.free_size / (double)pool_info.buffer_size * 100.0));
|
||||
TRACEF(" Max Free Size: %u (%u%% fragmented)", stats.free_max_size, (unsigned)(100.0 - (double)stats.free_max_size / (double)stats.free_size * 100.0));
|
||||
//TRACEF(" alloc_count: %u", pool_info.alloc_count);
|
||||
TRACEF(" alloc_fault: %u", pool_info.alloc_fault);
|
||||
//TRACEF(" free_count: %u", pool_info.free_count);
|
||||
TRACEF(" free_fault: %u", pool_info.free_fault);
|
||||
}
|
||||
|
||||
/*static*/ void Memory::dump_basic_pool_stats() {
|
||||
|
||||
size_t heap_free = 0;
|
||||
uint8_t heap_pct = 0;
|
||||
if (heap_pool_info.tlsf != nullptr) {
|
||||
struct tlsf_stats stats;
|
||||
memset(&stats, 0, sizeof(stats));
|
||||
tlsf_walk_pool(tlsf_get_pool(heap_pool_info.tlsf), tlsf_mem_walker, &stats);
|
||||
heap_free = stats.free_size;
|
||||
heap_pct = (uint8_t)((double)heap_free / (double)heap_pool_info.buffer_size * 100.0);
|
||||
}
|
||||
if (heap_pool_info.last_free == 0) {
|
||||
heap_pool_info.last_free = heap_free;
|
||||
}
|
||||
|
||||
size_t psram_free = 0;
|
||||
uint8_t psram_pct = 0;
|
||||
if (psram_pool_info.tlsf != nullptr) {
|
||||
struct tlsf_stats stats;
|
||||
memset(&stats, 0, sizeof(stats));
|
||||
tlsf_walk_pool(tlsf_get_pool(psram_pool_info.tlsf), tlsf_mem_walker, &stats);
|
||||
psram_free = stats.free_size;
|
||||
psram_pct = (uint8_t)((double)psram_free / (double)psram_pool_info.buffer_size * 100.0);
|
||||
}
|
||||
if (psram_pool_info.last_free == 0) {
|
||||
psram_pool_info.last_free = psram_free;
|
||||
}
|
||||
|
||||
size_t altheap_free = 0;
|
||||
uint8_t altheap_pct = 0;
|
||||
if (altheap_pool_info.tlsf != nullptr) {
|
||||
struct tlsf_stats stats;
|
||||
memset(&stats, 0, sizeof(stats));
|
||||
tlsf_walk_pool(tlsf_get_pool(altheap_pool_info.tlsf), tlsf_mem_walker, &stats);
|
||||
altheap_free = stats.free_size;
|
||||
altheap_pct = (uint8_t)((double)altheap_free / (double)altheap_pool_info.buffer_size * 100.0);
|
||||
}
|
||||
if (altheap_pool_info.last_free == 0) {
|
||||
altheap_pool_info.last_free = altheap_free;
|
||||
}
|
||||
|
||||
VERBOSEF("heap_pool: %u (%u%%) [%d] psram_pool: %u (%u%%) [%d] alt_pool: %u (%u%%) [%d]", heap_free, heap_pct, heap_free - heap_pool_info.last_free, psram_free, psram_pct, psram_free - psram_pool_info.last_free, altheap_free, altheap_pct, altheap_free - altheap_pool_info.last_free);
|
||||
|
||||
heap_pool_info.last_free = heap_free;
|
||||
psram_pool_info.last_free = psram_free;
|
||||
altheap_pool_info.last_free = altheap_free;
|
||||
}
|
||||
|
||||
/*static*/ void Memory::dump_allocator_stats(Memory::allocator_info& allocator_info, const char* name /*= ""*/) {
|
||||
HEADF(LOG_TRACE, "%sAllocator Stats", name);
|
||||
TRACEF(" Active Count: %u", (allocator_info.alloc_count - allocator_info.free_count));
|
||||
TRACEF(" Min Size: %u", allocator_info.min_alloc_size);
|
||||
TRACEF(" Max Size: %u", allocator_info.max_alloc_size);
|
||||
TRACEF(" Avg Size: %u", (size_t)((allocator_info.alloc_count > 0) ? (allocator_info.alloc_size / allocator_info.alloc_count) : 0));
|
||||
TRACEF(" alloc_count: %u", allocator_info.alloc_count);
|
||||
TRACEF(" alloc_fault: %u", allocator_info.alloc_fault);
|
||||
TRACEF(" free_count: %u", allocator_info.free_count);
|
||||
TRACEF(" free_fault: %u", allocator_info.free_fault);
|
||||
}
|
||||
|
||||
/*static*/ void Memory::dump_basic_allocator_stats() {
|
||||
|
||||
int dflt_diff = 0;
|
||||
// Increase in used memory, negative diff
|
||||
if (default_allocator_info.alloc_size > default_allocator_info.last_size) {
|
||||
dflt_diff = (int)(default_allocator_info.alloc_size - default_allocator_info.last_size) * -1;
|
||||
}
|
||||
// Decrease in used memory, positive diff
|
||||
else {
|
||||
dflt_diff = (int)(default_allocator_info.last_size - default_allocator_info.alloc_size);
|
||||
}
|
||||
//if (default_allocator_info.last_size == 0) {
|
||||
// default_allocator_info.last_size = default_allocator_info.alloc_size;
|
||||
//}
|
||||
|
||||
int cntr_diff = 0;
|
||||
// Increase in used memory, negative diff
|
||||
if (container_allocator_info.alloc_size > container_allocator_info.last_size) {
|
||||
cntr_diff = (int)(container_allocator_info.alloc_size - container_allocator_info.last_size) * -1;
|
||||
}
|
||||
// Decrease in used memory, positive diff
|
||||
else {
|
||||
cntr_diff = (int)(container_allocator_info.last_size - container_allocator_info.alloc_size);
|
||||
}
|
||||
//if (container_allocator_info.last_size == 0) {
|
||||
// container_allocator_info.last_size = container_allocator_info.alloc_size;
|
||||
//}
|
||||
|
||||
VERBOSEF("dflt_alloc: %llu [%d] cntr_alloc: %llu [%d]", default_allocator_info.alloc_size, dflt_diff, container_allocator_info.alloc_size, cntr_diff);
|
||||
|
||||
default_allocator_info.last_size = default_allocator_info.alloc_size;
|
||||
container_allocator_info.last_size = container_allocator_info.alloc_size;
|
||||
}
|
||||
|
||||
|
||||
size_t maxContiguousAllocation() {
|
||||
// Brute-force determine maximum allocation size
|
||||
//const size_t block_size = 256;
|
||||
const size_t block_size = 32;
|
||||
size_t block_count;
|
||||
for (block_count = 1; ; block_count++) {
|
||||
void* ptr = malloc(block_count * block_size);
|
||||
if (ptr == nullptr) {
|
||||
break;
|
||||
}
|
||||
free(ptr);
|
||||
}
|
||||
return (block_count - 1) * block_size;
|
||||
}
|
||||
|
||||
/*static*/ size_t Memory::heap_size() {
|
||||
#if defined(ESP32)
|
||||
return ESP.getHeapSize();
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
return dbgHeapTotal();
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
/*static*/ size_t Memory::heap_available() {
|
||||
#if defined(ESP32)
|
||||
return ESP.getFreeHeap();
|
||||
//return ESP.getMaxAllocHeap();
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
return dbgHeapFree();
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
/*static*/ void Memory::dump_heap_stats() {
|
||||
#if defined(ESP32)
|
||||
HEAD("Heap Stats", LOG_TRACE);
|
||||
TRACEF(" Heap size: %u", ESP.getHeapSize());
|
||||
TRACEF(" Heap free: %u (%u%% free)", ESP.getFreeHeap(), (unsigned)((double)ESP.getFreeHeap() / (double)ESP.getHeapSize() * 100.0));
|
||||
//TRACEF(" Heap free: %u (%u%% free)", xPortGetFreeHeapSize(), (unsigned)((double)xPortGetFreeHeapSize() / (double)xPort * 100.0));
|
||||
TRACEF(" Heap min free: %u", ESP.getMinFreeHeap());
|
||||
//TRACEF(" Heap min free: %u", xPortGetMinimumEverFreeHeapSize());
|
||||
TRACEF(" Heap max alloc: %u (%u%% fragmented)", ESP.getMaxAllocHeap(), (unsigned)(100.0 - (double)ESP.getMaxAllocHeap() / (double)ESP.getFreeHeap() * 100.0));
|
||||
//TRACEF(" Heap max alloc: %u (%u%% fragmented)", ESP.getMaxAllocHeap(), (unsigned)(100.0 - (double)ESP.getMaxAllocHeap() / (double)xPortGetFreeHeapSize() * 100.0));
|
||||
TRACEF(" PSRAM size: %u", ESP.getPsramSize());
|
||||
TRACEF(" PSRAM free: %u (%u%% free)", ESP.getFreePsram(), (ESP.getPsramSize() > 0) ? (unsigned)((double)ESP.getFreePsram() / (double)ESP.getPsramSize() * 100.0) : 0);
|
||||
TRACEF(" PSRAM min free: %u", ESP.getMinFreePsram());
|
||||
TRACEF(" PSRAM max alloc: %u (%u%% fragmented)", ESP.getMaxAllocPsram(), (ESP.getFreePsram() > 0) ? (unsigned)(100.0 - (double)ESP.getMaxAllocPsram() / (double)ESP.getFreePsram() * 100.0) : 0);
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
HEAD("Heap Stats", LOG_TRACE);
|
||||
if (loglevel() == LOG_TRACE) {
|
||||
dbgMemInfo();
|
||||
}
|
||||
#endif
|
||||
|
||||
dump_allocator_stats(default_allocator_info, "Default ");
|
||||
dump_allocator_stats(container_allocator_info, "Container ");
|
||||
|
||||
dump_pool_stats(heap_pool_info, "Heap ");
|
||||
dump_pool_stats(psram_pool_info, "PSRAM ");
|
||||
dump_pool_stats(altheap_pool_info, "AltHeap ");
|
||||
dump_basic_pool_stats();
|
||||
dump_basic_allocator_stats();
|
||||
|
||||
}
|
||||
|
||||
|
||||
// Only override new/delete if RNS_DEFAULT_ALLOCATOR is not RNS_HEAP_ALLOCATOR
|
||||
#if RNS_DEFAULT_ALLOCATOR != RNS_HEAP_ALLOCATOR
|
||||
|
||||
void* allocator_malloc(size_t size) {
|
||||
if (size == 0) return nullptr;
|
||||
++Memory::default_allocator_info.alloc_count;
|
||||
Memory::default_allocator_info.alloc_size += size;
|
||||
if (size < Memory::default_allocator_info.min_alloc_size || Memory::default_allocator_info.min_alloc_size == 0) {
|
||||
Memory::default_allocator_info.min_alloc_size = size;
|
||||
}
|
||||
if (size > Memory::default_allocator_info.max_alloc_size) {
|
||||
Memory::default_allocator_info.max_alloc_size = size;
|
||||
}
|
||||
#if RNS_DEFAULT_ALLOCATOR == RNS_HEAP_POOL_ALLOCATOR
|
||||
return Memory::pool_malloc(Memory::heap_pool_info, size);
|
||||
#elif RNS_DEFAULT_ALLOCATOR == RNS_PSRAM_ALLOCATOR
|
||||
#if BOARD_HAS_PSRAM != 1
|
||||
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||
#endif
|
||||
// CBA PSRAM may not be accessible early in startup, but since we use the same free() for both
|
||||
// HEAP and PSRAM allocations, we canb simply fallback to HEAP allocation when PSRAM fails
|
||||
void* p = ps_malloc(size);
|
||||
if (p == nullptr) {
|
||||
++Memory::default_allocator_info.alloc_fault;
|
||||
p = malloc(size);
|
||||
}
|
||||
return p;
|
||||
#elif RNS_DEFAULT_ALLOCATOR == RNS_PSRAM_POOL_ALLOCATOR
|
||||
#error "RNS_DEFAULT_ALLOCATOR can not be set to RNS_PSRAM_POOL_ALLOCATOR because PSRAM isn't initialized early enough."
|
||||
#if BOARD_HAS_PSRAM != 1
|
||||
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||
#endif
|
||||
return Memory::pool_malloc(Memory::psram_pool_info, size);
|
||||
#elif RNS_DEFAULT_ALLOCATOR == RNS_ALTHEAP_POOL_ALLOCATOR
|
||||
return Memory::pool_malloc(Memory::altheap_pool_info, size);
|
||||
#elif RNS_DEFAULT_ALLOCATOR == RNS_HEAP_ALLOCATOR
|
||||
return ::operator new(n * sizeof(value_type));
|
||||
#else
|
||||
#error "Unknown or invalid allocator."
|
||||
#endif
|
||||
}
|
||||
|
||||
void allocator_free(void* p, size_t size = 0) noexcept {
|
||||
if (p == nullptr) return;
|
||||
++Memory::default_allocator_info.free_count;
|
||||
Memory::default_allocator_info.alloc_size -= size;
|
||||
#if RNS_DEFAULT_ALLOCATOR == RNS_HEAP_POOL_ALLOCATOR
|
||||
Memory::pool_free(Memory::heap_pool_info, p, size);
|
||||
#elif RNS_DEFAULT_ALLOCATOR == RNS_PSRAM_ALLOCATOR
|
||||
#if BOARD_HAS_PSRAM != 1
|
||||
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||
#endif
|
||||
free(p);
|
||||
#elif RNS_DEFAULT_ALLOCATOR == RNS_PSRAM_POOL_ALLOCATOR
|
||||
#error "RNS_DEFAULT_ALLOCATOR can not be set to RNS_PSRAM_POOL_ALLOCATOR because PSRAM isn't initialized early enough."
|
||||
#if BOARD_HAS_PSRAM != 1
|
||||
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||
#endif
|
||||
Memory::pool_free(Memory::psram_pool_info, p, size);
|
||||
#elif RNS_DEFAULT_ALLOCATOR == RNS_ALTHEAP_POOL_ALLOCATOR
|
||||
Memory::pool_free(Memory::altheap_pool_info, p, size);
|
||||
#elif RNS_DEFAULT_ALLOCATOR == RNS_HEAP_ALLOCATOR
|
||||
::operator delete(p);
|
||||
#else
|
||||
#error "Unknown or invalid allocator."
|
||||
#endif
|
||||
}
|
||||
|
||||
//--------------------------------------------------
|
||||
// Standard allocation
|
||||
//--------------------------------------------------
|
||||
|
||||
// CBA Added attribute weak to avoid collision with new override on nrf52
|
||||
void* operator new(size_t size) {
|
||||
//__attribute__((weak)) void* operator new(size_t size) {
|
||||
//printf("--- new allocating memory from tlsf (%u bytes)\n", size);
|
||||
void* p = allocator_malloc(size);
|
||||
if (p == nullptr) {
|
||||
throw std::bad_alloc();
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
void* operator new[](size_t size) {
|
||||
//printf("--- new[] allocating memory from tlsf (%u bytes)\n", size);
|
||||
void* p = allocator_malloc(size);
|
||||
if (p == nullptr) {
|
||||
throw std::bad_alloc();
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
//--------------------------------------------------
|
||||
// Nothrow allocation
|
||||
//--------------------------------------------------
|
||||
|
||||
void* operator new(size_t size, const std::nothrow_t&) noexcept {
|
||||
//printf("--- new no-throw allocating memory from tlsf (%u bytes)\n", size);
|
||||
return allocator_malloc(size);
|
||||
}
|
||||
|
||||
void* operator new[](size_t size, const std::nothrow_t&) noexcept {
|
||||
//printf("--- new[] no-throw allocating memory from tlsf (%u bytes)\n", size);
|
||||
return allocator_malloc(size);
|
||||
}
|
||||
|
||||
//--------------------------------------------------
|
||||
// Standard delete
|
||||
//--------------------------------------------------
|
||||
|
||||
// CBA Added attribute weak to avoid collision with new override on nrf52
|
||||
void operator delete(void* p) noexcept {
|
||||
//__attribute__((weak)) void operator delete(void* p) noexcept {
|
||||
//printf("--- delete freeing memory from tlsf (addr=%lx)\n", p);
|
||||
if (p != nullptr) allocator_free(p);
|
||||
}
|
||||
|
||||
void operator delete[](void* p) noexcept {
|
||||
//printf("--- delete[] freeing memory from tlsf (addr=%lx)\n", p);
|
||||
if (p != nullptr) allocator_free(p);
|
||||
}
|
||||
|
||||
//--------------------------------------------------
|
||||
// Sized delete (C++14+)
|
||||
//--------------------------------------------------
|
||||
|
||||
void operator delete(void* p, size_t size) noexcept { // sized delete
|
||||
//printf("--- delete(size) freeing memory from tlsf (addr=%lx)\n", p);
|
||||
if (p != nullptr) allocator_free(p, size);
|
||||
}
|
||||
|
||||
void operator delete[](void* p, size_t size) noexcept {
|
||||
//printf("--- delete[](size) freeing memory from tlsf (addr=%lx)\n", p);
|
||||
if (p != nullptr) allocator_free(p, size);
|
||||
}
|
||||
|
||||
//--------------------------------------------------
|
||||
// Nothrow delete
|
||||
//--------------------------------------------------
|
||||
|
||||
void operator delete(void* p, const std::nothrow_t&) noexcept {
|
||||
//printf("--- delete no-throw freeing memory from tlsf (addr=%lx)\n", p);
|
||||
if (p != nullptr) allocator_free(p);
|
||||
}
|
||||
|
||||
void operator delete[](void* p, const std::nothrow_t&) noexcept {
|
||||
//printf("--- delete[] no-throw freeing memory from tlsf (addr=%lx)\n", p);
|
||||
if (p != nullptr) allocator_free(p);
|
||||
}
|
||||
|
||||
//--------------------------------------------------
|
||||
// Aligned allocation/delete (C++17+)
|
||||
//--------------------------------------------------
|
||||
|
||||
#if __cplusplus >= 201703L
|
||||
void* operator new(size_t size, std::align_val_t) {
|
||||
//printf("--- new aligned allocating memory from tlsf (%u bytes)\n", size);
|
||||
void* p = allocator_malloc(size);
|
||||
if (p == nullptr) {
|
||||
throw std::bad_alloc();
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
void operator delete(void* p, std::align_val_t) {
|
||||
//printf("--- delete aligned freeing memory from tlsf (addr=%lx)\n", p);
|
||||
if (p != nullptr) allocator_free(p);
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,172 @@
|
||||
#pragma once
|
||||
|
||||
#include "../Log.h"
|
||||
|
||||
#include "tlsf.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
#define RNS_HEAP_ALLOCATOR 0 // Use HEAP for allocator
|
||||
#define RNS_HEAP_POOL_ALLOCATOR 1 // Use HEAP pool for allocator
|
||||
#define RNS_PSRAM_ALLOCATOR 2 // Use PSRAM for allocator
|
||||
#define RNS_PSRAM_POOL_ALLOCATOR 3 // Use PSRAM pool for allocator
|
||||
#define RNS_ALTHEAP_POOL_ALLOCATOR 4 // Use alternate HEAP pool for allocator
|
||||
|
||||
namespace RNS { namespace Utilities {
|
||||
|
||||
class Memory {
|
||||
|
||||
private:
|
||||
|
||||
struct pool_info {
|
||||
pool_info(uint8_t t, size_t s) : type(t), buffer_size(s) {}
|
||||
uint8_t type = 0;
|
||||
bool pool_init = false;
|
||||
size_t buffer_size = 0;
|
||||
size_t contiguous_size = 0;
|
||||
tlsf_t tlsf = nullptr;
|
||||
uint32_t alloc_fault = 0;
|
||||
uint32_t free_fault = 0;
|
||||
size_t last_free = 0;
|
||||
};
|
||||
|
||||
struct allocator_info {
|
||||
uint32_t alloc_count = 0;
|
||||
uint32_t alloc_fault = 0;
|
||||
uint32_t free_count = 0;
|
||||
uint32_t free_fault = 0;
|
||||
uint64_t alloc_size = 0;
|
||||
size_t min_alloc_size = 0;
|
||||
size_t max_alloc_size = 0;
|
||||
uint64_t last_size = 0;
|
||||
};
|
||||
|
||||
public:
|
||||
|
||||
static void pool_init(pool_info& pool_info);
|
||||
static void* pool_malloc(pool_info& pool_info, size_t size);
|
||||
static void pool_free(pool_info& pool_info, void* p, size_t size = 0) noexcept;
|
||||
|
||||
static void dump_pool_stats(pool_info& pool_info, const char* name = "");
|
||||
static void dump_basic_pool_stats();
|
||||
|
||||
static void dump_allocator_stats(Memory::allocator_info& allocator_info, const char* name = "");
|
||||
static void dump_basic_allocator_stats();
|
||||
|
||||
static size_t heap_size();
|
||||
static size_t heap_available();
|
||||
static void dump_heap_stats();
|
||||
|
||||
public:
|
||||
|
||||
static pool_info heap_pool_info;
|
||||
static pool_info psram_pool_info;
|
||||
static pool_info altheap_pool_info;
|
||||
|
||||
static allocator_info default_allocator_info;
|
||||
static allocator_info container_allocator_info;
|
||||
|
||||
public:
|
||||
|
||||
template <typename T>
|
||||
struct ContainerAllocator {
|
||||
using value_type = T;
|
||||
|
||||
ContainerAllocator() noexcept {}
|
||||
|
||||
// Essential for std::map internal node allocation
|
||||
template <class U>
|
||||
ContainerAllocator(const ContainerAllocator<U>&) noexcept {}
|
||||
|
||||
/*
|
||||
// Required for embedded toolchains (ESP32 Xtensa GCC) that don't synthesiz
|
||||
// rebind automatically via std::allocator_traits
|
||||
template<class U>
|
||||
struct rebind {
|
||||
using other = ContainerAllocator<U>;
|
||||
};
|
||||
*/
|
||||
|
||||
T* allocate(std::size_t n) {
|
||||
if (n == 0) return nullptr;
|
||||
size_t size = n * sizeof(value_type);
|
||||
++container_allocator_info.alloc_count;
|
||||
container_allocator_info.alloc_size += size;
|
||||
if (size < container_allocator_info.min_alloc_size || container_allocator_info.min_alloc_size == 0) {
|
||||
container_allocator_info.min_alloc_size = size;
|
||||
}
|
||||
if (size > container_allocator_info.max_alloc_size) {
|
||||
container_allocator_info.max_alloc_size = size;
|
||||
}
|
||||
#if RNS_CONTAINER_ALLOCATOR == RNS_HEAP_POOL_ALLOCATOR
|
||||
void* p = pool_malloc(heap_pool_info, size);
|
||||
#elif RNS_CONTAINER_ALLOCATOR == RNS_PSRAM_ALLOCATOR
|
||||
#if BOARD_HAS_PSRAM != 1
|
||||
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||
#endif
|
||||
// CBA PSRAM may not be accessible early in startup, but since we use the same free() for both
|
||||
// HEAP and PSRAM allocations, we canb simply fallback to HEAP allocation when PSRAM fails
|
||||
void* p = ps_malloc(size);
|
||||
if (p == nullptr) {
|
||||
++container_allocator_info.alloc_fault;
|
||||
p = malloc(size);
|
||||
}
|
||||
#elif RNS_CONTAINER_ALLOCATOR == RNS_PSRAM_POOL_ALLOCATOR
|
||||
#if BOARD_HAS_PSRAM != 1
|
||||
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||
#endif
|
||||
void* p = pool_malloc(psram_pool_info, size);
|
||||
#elif RNS_CONTAINER_ALLOCATOR == RNS_ALTHEAP_POOL_ALLOCATOR
|
||||
void* p = pool_malloc(altheap_pool_info, size);
|
||||
#elif RNS_CONTAINER_ALLOCATOR == RNS_HEAP_ALLOCATOR
|
||||
void* p = ::operator new(size);
|
||||
#else
|
||||
#error "Unknown or invalid allocator."
|
||||
#endif
|
||||
if (p == nullptr) {
|
||||
ERRORF("--- ContainerAllocator failed to allocate memory (%u bytes)", size);
|
||||
throw std::bad_alloc();
|
||||
}
|
||||
//TRACEF("--- ContainerAllocator allocated memory (addr=%lx) (%u bytes)", p, size);
|
||||
return static_cast<T*>(p);
|
||||
}
|
||||
|
||||
void deallocate(T* p, std::size_t n) noexcept {
|
||||
if (p == nullptr) return;
|
||||
size_t size = n * sizeof(value_type);
|
||||
++default_allocator_info.free_count;
|
||||
container_allocator_info.alloc_size -= size;
|
||||
//TRACEF("--- ContainerAllocator freeing memory (addr=%lx) (%u bytes)", p, size);
|
||||
#if RNS_CONTAINER_ALLOCATOR == RNS_HEAP_POOL_ALLOCATOR
|
||||
pool_free(heap_pool_info, p, size);
|
||||
#elif RNS_CONTAINER_ALLOCATOR == RNS_PSRAM_ALLOCATOR
|
||||
#if BOARD_HAS_PSRAM != 1
|
||||
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||
#endif
|
||||
free(p);
|
||||
#elif RNS_CONTAINER_ALLOCATOR == RNS_PSRAM_POOL_ALLOCATOR
|
||||
#if BOARD_HAS_PSRAM != 1
|
||||
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||
#endif
|
||||
pool_free(psram_pool_info, p, size);
|
||||
#elif RNS_CONTAINER_ALLOCATOR == RNS_ALTHEAP_POOL_ALLOCATOR
|
||||
pool_free(altheap_pool_info, p, size);
|
||||
#elif RNS_CONTAINER_ALLOCATOR == RNS_HEAP_ALLOCATOR
|
||||
::operator delete(p);
|
||||
#else
|
||||
#error "Unknown or invalid allocator."
|
||||
#endif
|
||||
}
|
||||
|
||||
// Equality operators are required
|
||||
bool operator==(const ContainerAllocator&) const noexcept { return true; }
|
||||
bool operator!=(const ContainerAllocator&) const noexcept { return false; }
|
||||
//template <class T, class U>
|
||||
//bool operator==(const MyAllocator<T>&, const MyAllocator<U>&) { return true; }
|
||||
//template <class T, class U>
|
||||
//bool operator!=(const MyAllocator<T>&, const MyAllocator<U>&) { return false; }
|
||||
};
|
||||
|
||||
};
|
||||
|
||||
} }
|
||||
+3
-275
@@ -3,283 +3,11 @@
|
||||
#include "../Type.h"
|
||||
#include "../Log.h"
|
||||
|
||||
#include <new>
|
||||
|
||||
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_SIZE 0
|
||||
#define BUFFER_FRACTION 0.8
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
//#define BUFFER_SIZE 1024 * 80
|
||||
#define BUFFER_SIZE 0
|
||||
#define BUFFER_FRACTION 0.8
|
||||
#else
|
||||
#define BUFFER_SIZE 1024 * 1000
|
||||
#define BUFFER_FRACTION 0
|
||||
#endif
|
||||
|
||||
bool _tlsf_init = false;
|
||||
//char _tlsf_msg[256] = "";
|
||||
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)
|
||||
// CBA Still unknown why the call to tlsf_create_with_pool() is so flaky on ESP32 with calculated buffer size. Reuires more research and unit tests.
|
||||
_contiguous_size = ESP.getMaxAllocHeap();
|
||||
TRACEF("contiguous_size: %u", _contiguous_size);
|
||||
if (_buffer_size == 0) {
|
||||
// CBA NOTE Using fp mathhere somehow causes tlsf_create_with_pool() to fail.
|
||||
//_buffer_size = (size_t)(_contiguous_size * BUFFER_FRACTION);
|
||||
// Compute 80% exactly using integers
|
||||
_buffer_size = (_contiguous_size * 4) / 5;
|
||||
}
|
||||
// Round DOWN to TLSF alignment
|
||||
size_t align = tlsf_align_size();
|
||||
_buffer_size &= ~(align - 1);
|
||||
void* raw_buffer = (void*)aligned_alloc(align, _buffer_size);
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
_contiguous_size = dbgHeapFree();
|
||||
TRACEF("contiguous_size: %u", _contiguous_size);
|
||||
if (_buffer_size == 0) {
|
||||
_buffer_size = (size_t)(_contiguous_size * BUFFER_FRACTION);
|
||||
}
|
||||
// For NRF52 round to kB
|
||||
_buffer_size = (size_t)(_buffer_size / 1024) * 1024;
|
||||
TRACEF("buffer_size: %u", _buffer_size);
|
||||
void* raw_buffer = malloc(_buffer_size);
|
||||
#endif
|
||||
if (raw_buffer == nullptr) {
|
||||
ERROR("-- allocation for tlsf FAILED");
|
||||
//strcpy(_tlsf_msg, "-- allocation for tlsf FAILED!!!");
|
||||
}
|
||||
else {
|
||||
#if 1
|
||||
OS::_tlsf = tlsf_create_with_pool(raw_buffer, _buffer_size);
|
||||
//if (OS::_tlsf == nullptr) {
|
||||
// sprintf(_tlsf_msg, "initialization of tlsf with align=%d, contiguous=%d, size=%d FAILED!!!", tlsf_align_size(), _contiguous_size, _buffer_size);
|
||||
//}
|
||||
//else {
|
||||
// sprintf(_tlsf_msg, "initialization of tlsf with align=%d, contiguous=%d, size=%d SUCCESSFUL!!!", tlsf_align_size(), _contiguous_size, _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;
|
||||
//TRACEF("TLSF Message: %s", _tlsf_msg);
|
||||
if (OS::_tlsf == nullptr) {
|
||||
return;
|
||||
}
|
||||
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;
|
||||
|
||||
/*static*/ size_t OS::heap_size() {
|
||||
#if defined(ESP32)
|
||||
return ESP.getHeapSize();
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
return dbgHeapTotal();
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
/*static*/ size_t OS::heap_available() {
|
||||
#if defined(ESP32)
|
||||
return ESP.getFreeHeap();
|
||||
//return ESP.getMaxAllocHeap();
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
return dbgHeapFree();
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
/*static*/ void OS::dump_heap_stats() {
|
||||
HEAD("Heap Stats", LOG_TRACE);
|
||||
#if defined(ESP32)
|
||||
TRACEF("Heap size: %u", ESP.getHeapSize());
|
||||
TRACEF("Heap free: %u (%u%% free)", ESP.getFreeHeap(), (unsigned)((double)ESP.getFreeHeap() / (double)ESP.getHeapSize() * 100.0));
|
||||
//TRACEF("Heap free: %u (%u%% free)", xPortGetFreeHeapSize(), (unsigned)((double)xPortGetFreeHeapSize() / (double)xPort * 100.0));
|
||||
TRACEF("Heap min free: %u", ESP.getMinFreeHeap());
|
||||
//TRACEF("Heap min free: %u", xPortGetMinimumEverFreeHeapSize());
|
||||
TRACEF("Heap max alloc: %u (%u%% fragmented)", ESP.getMaxAllocHeap(), (unsigned)(100.0 - (double)ESP.getMaxAllocHeap() / (double)ESP.getFreeHeap() * 100.0));
|
||||
//TRACEF("Heap max alloc: %u (%u%% fragmented)", ESP.getMaxAllocHeap(), (unsigned)(100.0 - (double)ESP.getMaxAllocHeap() / (double)xPortGetFreeHeapSize() * 100.0));
|
||||
TRACEF("PSRAM size: %u", ESP.getPsramSize());
|
||||
TRACEF("PSRAM free: %u (%u%% free)", ESP.getFreePsram(), (ESP.getPsramSize() > 0) ? (unsigned)((double)ESP.getFreePsram() / (double)ESP.getPsramSize() * 100.0) : 0);
|
||||
TRACEF("PSRAM min free: %u", ESP.getMinFreePsram());
|
||||
TRACEF("PSRAM max alloc: %u (%u%% fragmented)", ESP.getMaxAllocPsram(), (ESP.getFreePsram() > 0) ? (unsigned)(100.0 - (double)ESP.getMaxAllocPsram() / (double)ESP.getFreePsram() * 100.0) : 0);
|
||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||
if (loglevel() == LOG_TRACE) {
|
||||
dbgMemInfo();
|
||||
}
|
||||
#endif
|
||||
#if defined(RNS_USE_ALLOCATOR)
|
||||
OS::dump_allocator_stats();
|
||||
#endif
|
||||
}
|
||||
/*static*/ OS::LoopCallback OS::_on_loop = nullptr;
|
||||
+49
-34
@@ -4,9 +4,9 @@
|
||||
#include "../FileStream.h"
|
||||
#include "../Bytes.h"
|
||||
|
||||
#include "tlsf.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
#include <unistd.h>
|
||||
#include <time.h>
|
||||
#include <stdint.h>
|
||||
@@ -14,6 +14,9 @@
|
||||
|
||||
#ifdef ARDUINO
|
||||
#include <Arduino.h>
|
||||
#if defined(ESP32)
|
||||
#include "esp_task_wdt.h"
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#undef round
|
||||
@@ -22,20 +25,22 @@ namespace RNS { namespace Utilities {
|
||||
|
||||
class OS {
|
||||
|
||||
public:
|
||||
//using LoopCallback = void(*)();
|
||||
using LoopCallback = std::function<void()>;
|
||||
|
||||
private:
|
||||
static FileSystem _filesystem;
|
||||
static uint64_t _time_offset;
|
||||
static LoopCallback _on_loop;
|
||||
|
||||
public:
|
||||
static tlsf_t _tlsf;
|
||||
|
||||
public:
|
||||
static inline uint64_t getTimeOffset() { return _time_offset; }
|
||||
static inline void setTimeOffset(uint64_t offset) { _time_offset = offset; }
|
||||
inline static uint64_t getTimeOffset() { return _time_offset; }
|
||||
inline static void setTimeOffset(uint64_t offset) { _time_offset = offset; }
|
||||
|
||||
#ifdef ARDUINO
|
||||
// return current time in milliseconds since startup
|
||||
static inline uint64_t ltime() {
|
||||
inline static uint64_t ltime() {
|
||||
// handle roll-over of 32-bit millis (approx. 49 days)
|
||||
static uint32_t low32, high32;
|
||||
uint32_t new_low32 = millis();
|
||||
@@ -45,32 +50,32 @@ namespace RNS { namespace Utilities {
|
||||
}
|
||||
#else
|
||||
// return current time in milliseconds since 00:00:00, January 1, 1970 (Unix Epoch)
|
||||
static inline uint64_t ltime() { timeval time; ::gettimeofday(&time, NULL); return (uint64_t)(time.tv_sec * 1000) + (uint64_t)(time.tv_usec / 1000); }
|
||||
inline static uint64_t ltime() { timeval time; ::gettimeofday(&time, NULL); return (uint64_t)(time.tv_sec * 1000) + (uint64_t)(time.tv_usec / 1000); }
|
||||
#endif
|
||||
|
||||
#ifdef ARDUINO
|
||||
// return current time in float seconds since startup
|
||||
static inline double time() { return (double)(ltime() / 1000.0); }
|
||||
inline static double time() { return (double)(ltime() / 1000.0); }
|
||||
#else
|
||||
// return current time in float seconds since 00:00:00, January 1, 1970 (Unix Epoch)
|
||||
static inline double time() { timeval time; ::gettimeofday(&time, NULL); return (double)time.tv_sec + ((double)time.tv_usec / 1000000); }
|
||||
inline static double time() { timeval time; ::gettimeofday(&time, NULL); return (double)time.tv_sec + ((double)time.tv_usec / 1000000); }
|
||||
#endif
|
||||
|
||||
// sleep for specified milliseconds
|
||||
//static inline void sleep(float seconds) { ::sleep(seconds); }
|
||||
//inline static void sleep(float seconds) { ::sleep(seconds); }
|
||||
#ifdef ARDUINO
|
||||
static inline void sleep(float seconds) { delay((uint32_t)(seconds * 1000)); }
|
||||
inline static void sleep(float seconds) { delay((uint32_t)(seconds * 1000)); }
|
||||
#else
|
||||
static inline void sleep(float seconds) { timespec time; time.tv_sec = (time_t)(seconds); time.tv_nsec = (seconds - (float)time.tv_sec) * 1000000000; ::nanosleep(&time, nullptr); }
|
||||
inline static void sleep(float seconds) { timespec time; time.tv_sec = (time_t)(seconds); time.tv_nsec = (seconds - (float)time.tv_sec) * 1000000000; ::nanosleep(&time, nullptr); }
|
||||
#endif
|
||||
//static inline void sleep(uint32_t milliseconds) { ::sleep((float)milliseconds / 1000.0); }
|
||||
//inline static void sleep(uint32_t milliseconds) { ::sleep((float)milliseconds / 1000.0); }
|
||||
|
||||
// round decimal number to specified precision
|
||||
//static inline float round(float value, uint8_t precision) { return std::round(value / precision) * precision; }
|
||||
//static inline double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
|
||||
static inline double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
|
||||
//inline static float round(float value, uint8_t precision) { return std::round(value / precision) * precision; }
|
||||
//inline static double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
|
||||
inline static double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
|
||||
|
||||
static inline uint64_t from_bytes_big_endian(const uint8_t* data, size_t len) {
|
||||
inline static uint64_t from_bytes_big_endian(const uint8_t* data, size_t len) {
|
||||
uint64_t result = 0;
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
result = (result << 8) | data[i];
|
||||
@@ -79,17 +84,17 @@ namespace RNS { namespace Utilities {
|
||||
}
|
||||
|
||||
// Detect endianness at runtime
|
||||
static int is_big_endian(void) {
|
||||
inline static int is_big_endian(void) {
|
||||
uint16_t test = 0x0102;
|
||||
return ((uint8_t*)&test)[0] == 0x01;
|
||||
}
|
||||
|
||||
// Byte swap functions
|
||||
static uint16_t swap16(uint16_t val) {
|
||||
inline static uint16_t swap16(uint16_t val) {
|
||||
return (val << 8) | (val >> 8);
|
||||
}
|
||||
|
||||
static uint32_t swap32(uint32_t val) {
|
||||
inline static uint32_t swap32(uint32_t val) {
|
||||
return ((val << 24) & 0xFF000000) |
|
||||
((val << 8) & 0x00FF0000) |
|
||||
((val >> 8) & 0x0000FF00) |
|
||||
@@ -98,25 +103,39 @@ namespace RNS { namespace Utilities {
|
||||
|
||||
// Platform-independent replacements
|
||||
|
||||
static uint16_t portable_htons(uint16_t val) {
|
||||
inline static uint16_t portable_htons(uint16_t val) {
|
||||
return is_big_endian() ? val : swap16(val);
|
||||
}
|
||||
|
||||
static uint32_t portable_htonl(uint32_t val) {
|
||||
inline static uint32_t portable_htonl(uint32_t val) {
|
||||
return is_big_endian() ? val : swap32(val);
|
||||
}
|
||||
|
||||
static uint16_t portable_ntohs(uint16_t val) {
|
||||
inline static uint16_t portable_ntohs(uint16_t val) {
|
||||
return is_big_endian() ? val : swap16(val);
|
||||
}
|
||||
|
||||
static uint32_t portable_ntohl(uint32_t val) {
|
||||
inline static uint32_t portable_ntohl(uint32_t val) {
|
||||
return is_big_endian() ? val : swap32(val);
|
||||
}
|
||||
|
||||
#if defined(RNS_USE_ALLOCATOR)
|
||||
static void dump_allocator_stats();
|
||||
inline static void reset_watchdog() {
|
||||
#if defined(ESP32)
|
||||
esp_task_wdt_reset();
|
||||
#endif
|
||||
}
|
||||
|
||||
inline static void set_loop_callback(LoopCallback on_loop = nullptr) { _on_loop = on_loop; }
|
||||
inline static void run_loop() {
|
||||
if (_on_loop) {
|
||||
try {
|
||||
_on_loop();
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("run_loop: exception while looping: %s", e.what());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline static void register_filesystem(FileSystem& filesystem) {
|
||||
TRACE("Registering filesystem...");
|
||||
@@ -204,11 +223,11 @@ namespace RNS { namespace Utilities {
|
||||
return _filesystem.remove_directory(directory_path);
|
||||
}
|
||||
|
||||
inline static std::list<std::string> list_directory(const char* directory_path) {
|
||||
inline static std::list<std::string> list_directory(const char* directory_path, FileSystem::Callbacks::DirectoryListing callback = nullptr) {
|
||||
if (!_filesystem) {
|
||||
throw std::runtime_error("FileSystem has not been registered");
|
||||
}
|
||||
return _filesystem.list_directory(directory_path);
|
||||
return _filesystem.list_directory(directory_path, callback);
|
||||
}
|
||||
|
||||
inline static size_t storage_size() {
|
||||
@@ -224,10 +243,6 @@ namespace RNS { namespace Utilities {
|
||||
}
|
||||
return _filesystem.storage_available();
|
||||
}
|
||||
|
||||
static size_t heap_size();
|
||||
static size_t heap_available();
|
||||
static void dump_heap_stats();
|
||||
|
||||
};
|
||||
|
||||
|
||||
+50
-39
@@ -94,7 +94,7 @@ namespace ArduinoJson {
|
||||
JsonObject obj = dst.to<JsonObject>();
|
||||
for (const auto& item : src) {
|
||||
//obj[item.first] = item.second;
|
||||
obj[item.first.toHex()] = item.second;
|
||||
obj[item.first.toBase64()] = item.second;
|
||||
}
|
||||
}
|
||||
static std::map<RNS::Bytes, T> fromJson(JsonVariantConst src) {
|
||||
@@ -102,7 +102,7 @@ namespace ArduinoJson {
|
||||
for (JsonPairConst item : src.as<JsonObjectConst>()) {
|
||||
//dst[item.key().c_str()] = item.value().as<T>();
|
||||
RNS::Bytes key;
|
||||
key.assignHex(item.key().c_str());
|
||||
key.assignBase64(item.key().c_str());
|
||||
//dst[key] = item.value().as<T>();
|
||||
dst.insert({key, item.value().as<T>()});
|
||||
}
|
||||
@@ -148,14 +148,14 @@ namespace ArduinoJson {
|
||||
if (!src) {
|
||||
return dst.set(nullptr);
|
||||
}
|
||||
//TRACE("<<< Serializing interface hash " + src.get_hash().toHex());
|
||||
//TRACEF("<<< Serializing interface hash %s", src.get_hash().toHex().c_str());
|
||||
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*>());
|
||||
//TRACE(">>> Deserialized interface hash " + hash.toHex());
|
||||
//TRACEF(">>> Deserialized interface hash %s", hash.toHex().c_str());
|
||||
//TRACE(">>> Querying transport for interface");
|
||||
// Query transport for matching interface
|
||||
return RNS::Transport::find_interface_from_hash(hash);
|
||||
@@ -178,7 +178,7 @@ namespace ArduinoJson {
|
||||
if (!src) {
|
||||
return dst.set(nullptr);
|
||||
}
|
||||
//TRACE("<<< Serializing packet hash " + src.get_hash().toHex());
|
||||
//TRACEF("<<< Serializing packet hash %s", src.get_hash().toHex().c_str());
|
||||
// Whenever a reference to a packet is serialized we must ensure that packet itself also gets serialized separately
|
||||
RNS::Transport::cache_packet(src, true);
|
||||
return dst.set(src.get_hash().toHex());
|
||||
@@ -187,7 +187,7 @@ namespace ArduinoJson {
|
||||
if (!src.isNull()) {
|
||||
RNS::Bytes hash;
|
||||
hash.assignHex(src.as<const char*>());
|
||||
//TRACE(">>> Deserialized packet hash " + hash.toHex());
|
||||
//TRACEF(">>> Deserialized packet hash %s", hash.toHex().c_str());
|
||||
//TRACE(">>> Querying transport for cached packet");
|
||||
// Query transport for matching packet
|
||||
return RNS::Transport::get_cached_packet(hash);
|
||||
@@ -209,7 +209,6 @@ namespace ArduinoJson {
|
||||
//dst["hash"] = src.get_hash();
|
||||
dst["raw"] = src.raw();
|
||||
dst["sent_at"] = src.sent_at();
|
||||
dst["destination_hash"] = src.get_hash();
|
||||
//TRACE("<<< Finished serializing Packet");
|
||||
return true;
|
||||
}
|
||||
@@ -220,8 +219,7 @@ namespace ArduinoJson {
|
||||
RNS::Packet packet(RNS::Destination(RNS::Type::NONE), raw);
|
||||
//packet.set_hash(src["hash"]);
|
||||
packet.sent_at(src["sent_at"]);
|
||||
RNS::Bytes destination_hash = src["destination_hash"];
|
||||
// set cached flag since pcket was read from cache
|
||||
// set cached flag since packet was read from cache
|
||||
packet.cached(true);
|
||||
//TRACE(">>> Finished deserializing Packet");
|
||||
return packet;
|
||||
@@ -230,8 +228,7 @@ namespace ArduinoJson {
|
||||
return
|
||||
//src["hash"].is<RNS::Bytes>() &&
|
||||
src["raw"].is<RNS::Bytes>() &&
|
||||
src["sent_at"].is<double>() &&
|
||||
src["destination_hash"].is<RNS::Bytes>();
|
||||
src["sent_at"].is<double>();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -279,18 +276,21 @@ namespace ArduinoJson {
|
||||
dst["announce_hops"] = src._hops;
|
||||
dst["expires"] = src._expires;
|
||||
dst["random_blobs"] = src._random_blobs;
|
||||
|
||||
/*
|
||||
//dst["interface_hash"] = src._receiving_interface;
|
||||
if (src._receiving_interface) {
|
||||
dst["interface_hash"] = src._receiving_interface.get_hash();
|
||||
}
|
||||
else {
|
||||
dst["interface_hash"] = nullptr;
|
||||
}
|
||||
*/
|
||||
dst["interface_hash"] = src.receiving_interface_hash();
|
||||
|
||||
// CBA TODO Move packet serialization to *after* destination table serialization since packets are useless
|
||||
// anyway if there's no space to left to write destination table.
|
||||
// anyway if there's no space left to write destination table.
|
||||
// Whenever a reference to a packet is serialized we must ensure that packet itself also gets serialized separately
|
||||
//dst["packet"] = src._announce_packet;
|
||||
/*
|
||||
if (src._announce_packet) {
|
||||
dst["packet_hash"] = src._announce_packet.get_hash();
|
||||
// Only cache packet if not already cached
|
||||
@@ -300,15 +300,15 @@ namespace ArduinoJson {
|
||||
}
|
||||
}
|
||||
else {
|
||||
TRACE("Destination announce packet " + src._announce_packet.get_hash().toHex() + " is already cached");
|
||||
TRACEF("Destination announce packet %s is already cached", src._announce_packet.get_hash().toHex().c_str());
|
||||
}
|
||||
}
|
||||
else {
|
||||
dst["packet_hash"] = nullptr;
|
||||
}
|
||||
*/
|
||||
dst["interface_hash"] = src._receiving_interface;
|
||||
dst["packet_hash"] = src._announce_packet;
|
||||
dst["packet_hash"] = src.announce_packet_hash();
|
||||
|
||||
//TRACE("<<< Finished Serializing Transport::DestinationEntry");
|
||||
return true;
|
||||
}
|
||||
@@ -320,22 +320,25 @@ namespace ArduinoJson {
|
||||
dst._hops = src["announce_hops"];
|
||||
dst._expires = src["expires"];
|
||||
dst._random_blobs = src["random_blobs"].as<std::set<RNS::Bytes>>();
|
||||
|
||||
/*
|
||||
//dst._receiving_interface = src["interface_hash"];
|
||||
RNS::Bytes interface_hash = src["interface_hash"];
|
||||
if (interface_hash) {
|
||||
// Query transport for matching interface
|
||||
dst._receiving_interface = RNS::Transport::find_interface_from_hash(interface_hash);
|
||||
}
|
||||
//dst._announce_packet = src["packet"];
|
||||
*/
|
||||
dst.receiving_interface_hash(src["interface_hash"]);
|
||||
|
||||
/*
|
||||
RNS::Bytes packet_hash = src["packet_hash"];
|
||||
if (packet_hash) {
|
||||
// Query transport for matching packet
|
||||
// Query transport for matching cached packet
|
||||
dst._announce_packet = RNS::Transport::get_cached_packet(packet_hash);
|
||||
}
|
||||
*/
|
||||
dst._receiving_interface = src["interface_hash"];
|
||||
dst._announce_packet = src["packet_hash"];
|
||||
dst.announce_packet_hash(src["packet_hash"]);
|
||||
|
||||
/*
|
||||
//RNS::Transport::DestinationEntry dst(src["timestamp"], src["received_from"], src["announce_hops"], src["expires"], src["random_blobs"], src["receiving_interface"], src["packet"]);
|
||||
RNS::Transport::DestinationEntry dst(
|
||||
@@ -376,14 +379,18 @@ namespace RNS {
|
||||
dst["announce_hops"] = src._hops;
|
||||
dst["expires"] = src._expires;
|
||||
dst["random_blobs"] = src._random_blobs;
|
||||
|
||||
/*
|
||||
//dst["interface_hash"] = src._receiving_interface;
|
||||
if (src._receiving_interface) {
|
||||
dst["interface_hash"] = src._receiving_interface.get_hash();
|
||||
}
|
||||
else {
|
||||
dst["interface_hash"] = nullptr;
|
||||
}
|
||||
*/
|
||||
dst["interface_hash"] = src.receiving_interface_hash();
|
||||
|
||||
/*
|
||||
// CBA TODO Move packet serialization to *after* destination table serialization since packets are useless
|
||||
// anyway if there's no space to left to write destination table.
|
||||
// Whenever a reference to a packet is serialized we must ensure that packet itself also gets serialized separately
|
||||
@@ -397,15 +404,15 @@ namespace RNS {
|
||||
}
|
||||
}
|
||||
else {
|
||||
TRACE("Destination announce packet " + src._announce_packet.get_hash().toHex() + " is already cached");
|
||||
TRACEF("Destination announce packet %s is already cached", src._announce_packet.get_hash().toHex().c_str());
|
||||
}
|
||||
}
|
||||
else {
|
||||
dst["packet_hash"] = nullptr;
|
||||
}
|
||||
*/
|
||||
dst["interface_hash"] = src._receiving_interface;
|
||||
dst["packet_hash"] = src._announce_packet;
|
||||
dst["packet_hash"] = src.announce_packet_hash();
|
||||
|
||||
//TRACE("<<< Finished Serializing Transport::DestinationEntry");
|
||||
return true;
|
||||
}
|
||||
@@ -417,22 +424,25 @@ namespace RNS {
|
||||
dst._hops = src["announce_hops"];
|
||||
dst._expires = src["expires"];
|
||||
dst._random_blobs = src["random_blobs"].as<std::set<RNS::Bytes>>();
|
||||
|
||||
/*
|
||||
//dst._receiving_interface = src["interface_hash"];
|
||||
RNS::Bytes interface_hash = src["interface_hash"];
|
||||
if (interface_hash) {
|
||||
// Query transport for matching interface
|
||||
dst._receiving_interface = RNS::Transport::find_interface_from_hash(interface_hash);
|
||||
}
|
||||
//dst._announce_packet = src["packet"];
|
||||
*/
|
||||
dst.receiving_interface_hash(src["interface_hash"]);
|
||||
|
||||
/*
|
||||
RNS::Bytes packet_hash = src["packet_hash"];
|
||||
if (packet_hash) {
|
||||
// Query transport for matching packet
|
||||
dst._announce_packet = RNS::Transport::get_cached_packet(packet_hash);
|
||||
}
|
||||
*/
|
||||
dst._receiving_interface = src["interface_hash"];
|
||||
dst._announce_packet = src["packet_hash"];
|
||||
dst.announce_packet_hash(src["packet_hash"]);
|
||||
|
||||
/*
|
||||
//RNS::Transport::DestinationEntry dst(src["timestamp"], src["received_from"], src["announce_hops"], src["expires"], src["random_blobs"], src["receiving_interface"], src["packet"]);
|
||||
RNS::Transport::DestinationEntry dst(
|
||||
@@ -468,7 +478,7 @@ namespace RNS { namespace Persistence {
|
||||
static JsonDocument _document;
|
||||
static Bytes _buffer(Type::Persistence::BUFFER_MAXSIZE);
|
||||
|
||||
template <typename T> size_t crc(const T& obj) {
|
||||
template <typename T> uint32_t crc(const T& obj) {
|
||||
//TRACE("Persistence::crc<T>");
|
||||
_document.set(obj);
|
||||
size_t size = _buffer.capacity();
|
||||
@@ -480,7 +490,7 @@ namespace RNS { namespace Persistence {
|
||||
if (length < size) {
|
||||
_buffer.resize(length);
|
||||
}
|
||||
TRACEF("Persistence::crc: serialized %d bytes", length);
|
||||
//TRACEF("Persistence::crc: serialized %d bytes", length);
|
||||
return Utilities::Crc::crc32(0, _buffer.data(), _buffer.size());
|
||||
}
|
||||
|
||||
@@ -520,7 +530,7 @@ namespace RNS { namespace Persistence {
|
||||
size_t read = RNS::Utilities::OS::read_file(file_path, _buffer);
|
||||
if (read > 0) {
|
||||
TRACEF("Persistence::deserialize: read: %d bytes", _buffer.size());
|
||||
//TRACE("testDeserializeVector: data: " + _buffer.toString());
|
||||
//TRACEF("testDeserializeVector: data: %s", _buffer.toString().c_str());
|
||||
#ifdef USE_MSGPACK
|
||||
DeserializationError error = deserializeMsgPack(_document, _buffer.data());
|
||||
#else
|
||||
@@ -546,7 +556,7 @@ namespace RNS { namespace Persistence {
|
||||
}
|
||||
|
||||
#if 1
|
||||
template <typename T> size_t crc(std::map<Bytes, T>& map) {
|
||||
template <typename T, typename Compare, typename Allocator> uint32_t crc(std::map<Bytes, T, Compare, Allocator>& map) {
|
||||
//TRACE("Persistence::crc<map<Bytes, T>>");
|
||||
|
||||
uint32_t crc = 0;
|
||||
@@ -568,7 +578,7 @@ namespace RNS { namespace Persistence {
|
||||
if (length < size) {
|
||||
_buffer.resize(length);
|
||||
}
|
||||
TRACEF("Persistence::crc: serialized entry %d bytes", length);
|
||||
//TRACEF("Persistence::crc: serialized entry %d bytes", length);
|
||||
|
||||
if (length > 0) {
|
||||
crc = Utilities::Crc::crc32(crc, _buffer.data(), _buffer.size());
|
||||
@@ -582,7 +592,7 @@ namespace RNS { namespace Persistence {
|
||||
return Utilities::Crc::crc32(crc, '}');
|
||||
}
|
||||
|
||||
template <typename T> size_t serialize(std::map<Bytes, T>& map, const char* file_path, uint32_t& crc) {
|
||||
template <typename T, typename Compare, typename Allocator> size_t serialize(std::map<Bytes, T, Compare, Allocator>& map, const char* file_path, uint32_t& crc) {
|
||||
//TRACE("Persistence::serialize<map<Bytes,T>>");
|
||||
|
||||
// CBA TODO: Use stream here instead to avoid having to buffer entire structure
|
||||
@@ -615,17 +625,18 @@ namespace RNS { namespace Persistence {
|
||||
stream.write(',');
|
||||
}
|
||||
stream.write('}');
|
||||
stream.flush();
|
||||
TRACEF("Persistence::serialize: stream size: %d bytes", stream.size());
|
||||
crc = stream.crc();
|
||||
return stream.size();
|
||||
}
|
||||
|
||||
template <typename T> size_t serialize(std::map<Bytes, T>& map, const char* file_path) {
|
||||
template <typename T, typename Compare, typename Allocator> size_t serialize(std::map<Bytes, T, Compare, Allocator>& map, const char* file_path) {
|
||||
uint32_t crc;
|
||||
return serialize(map, file_path, crc);
|
||||
}
|
||||
|
||||
template <typename T> size_t deserialize(std::map<Bytes, T>& map, const char* file_path, uint32_t& crc) {
|
||||
template <typename T, typename Compare, typename Allocator> size_t deserialize(std::map<Bytes, T, Compare, Allocator>& map, const char* file_path, uint32_t& crc) {
|
||||
//TRACE("Persistence::deserialize<map<Bytes,T>>");
|
||||
|
||||
// CBA TODO: Use stream here instead to avoid having to buffer entire structure
|
||||
@@ -690,7 +701,7 @@ namespace RNS { namespace Persistence {
|
||||
return stream.size();
|
||||
}
|
||||
|
||||
template <typename T> size_t deserialize(std::map<Bytes, T>& map, const char* file_path) {
|
||||
template <typename T, typename Compare, typename Allocator> size_t deserialize(std::map<Bytes, T, Compare, Allocator>& map, const char* file_path) {
|
||||
uint32_t crc;
|
||||
return deserialize(map, file_path, crc);
|
||||
}
|
||||
|
||||
+153
-126
@@ -22,6 +22,7 @@ using namespace Adafruit_LittleFS_Namespace;
|
||||
#include <sys/stat.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <unistd.h>
|
||||
#include <dirent.h>
|
||||
#endif
|
||||
|
||||
class FileSystem : public RNS::FileSystemImpl {
|
||||
@@ -32,8 +33,8 @@ public:
|
||||
bool init() {
|
||||
TRACE("FileSystem initializing...");
|
||||
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
// Setup FileSystem
|
||||
INFO("SPIFFS mounting FileSystem");
|
||||
if (!SPIFFS.begin(true, "")){
|
||||
@@ -58,22 +59,22 @@ public:
|
||||
remove_file("/test");
|
||||
}
|
||||
DEBUG("SPIFFS FileSystem is ready");
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
// Initialize Internal File System
|
||||
INFO("InternalFS mounting FileSystem");
|
||||
InternalFS.begin();
|
||||
INFO("InternalFS FileSystem is ready");
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
public:
|
||||
static void listDir(const char* dir) {
|
||||
#ifdef ARDUINO
|
||||
#ifdef ARDUINO
|
||||
Serial.print("DIR: ");
|
||||
Serial.println(dir);
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef BOARD_ESP32
|
||||
File root = SPIFFS.open(dir);
|
||||
if (!root) {
|
||||
Serial.println("Failed to opend directory");
|
||||
@@ -92,7 +93,7 @@ public:
|
||||
file = root.openNextFile();
|
||||
}
|
||||
root.close();
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
File root = InternalFS.open(dir);
|
||||
if (!root) {
|
||||
Serial.println("Failed to opend directory");
|
||||
@@ -111,66 +112,66 @@ public:
|
||||
file = root.openNextFile();
|
||||
}
|
||||
root.close();
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
public:
|
||||
virtual bool file_exists(const char* file_path) {
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
File file = SPIFFS.open(file_path, FILE_READ);
|
||||
if (file) {
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
File file(InternalFS);
|
||||
if (file.open(file_path, FILE_O_READ)) {
|
||||
#else
|
||||
#else
|
||||
if (false) {
|
||||
#endif
|
||||
#else
|
||||
#endif
|
||||
#else
|
||||
// Native
|
||||
FILE* file = fopen(file_path, "r");
|
||||
if (file != nullptr) {
|
||||
#endif
|
||||
#endif
|
||||
//TRACE("file_exists: file exists, closing file");
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
file.close();
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
file.close();
|
||||
#endif
|
||||
#else
|
||||
#endif
|
||||
#else
|
||||
// Native
|
||||
fclose(file);
|
||||
#endif
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
ERROR("file_exists: failed to open file " + std::string(file_path));
|
||||
ERRORF("file_exists: failed to open file %s", file_path);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
virtual size_t read_file(const char* file_path, RNS::Bytes& data) {
|
||||
size_t read = 0;
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
File file = SPIFFS.open(file_path, FILE_READ);
|
||||
if (file) {
|
||||
size_t size = file.size();
|
||||
read = file.readBytes((char*)data.writable(size), size);
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
//File file(InternalFS);
|
||||
//if (file.open(file_path, FILE_O_READ)) {
|
||||
File file = InternalFS.open(file_path, FILE_O_READ);
|
||||
if (file) {
|
||||
size_t size = file.size();
|
||||
read = file.readBytes((char*)data.writable(size), size);
|
||||
#else
|
||||
#else
|
||||
if (false) {
|
||||
size_t size = 0;
|
||||
#endif
|
||||
#else
|
||||
#endif
|
||||
#else
|
||||
// Native
|
||||
FILE* file = fopen(file_path, "r");
|
||||
if (file != nullptr) {
|
||||
@@ -179,26 +180,26 @@ public:
|
||||
rewind(file);
|
||||
//size_t read = fread(data.writable(size), size, 1, file);
|
||||
read = fread(data.writable(size), 1, size, file);
|
||||
#endif
|
||||
TRACE("read_file: read " + std::to_string(read) + " bytes from file " + std::string(file_path));
|
||||
#endif
|
||||
TRACEF("read_file: read %zu bytes from file %s", read, file_path);
|
||||
if (read != size) {
|
||||
ERROR("read_file: failed to read file " + std::string(file_path));
|
||||
ERRORF("read_file: failed to read file %s", file_path);
|
||||
data.clear();
|
||||
}
|
||||
//TRACE("read_file: closing input file");
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
file.close();
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
file.close();
|
||||
#endif
|
||||
#else
|
||||
#endif
|
||||
#else
|
||||
// Native
|
||||
fclose(file);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
ERROR("read_file: failed to open input file " + std::string(file_path));
|
||||
ERRORF("read_file: failed to open input file %s", file_path);
|
||||
}
|
||||
return read;
|
||||
}
|
||||
@@ -207,51 +208,51 @@ public:
|
||||
// CBA TODO Replace remove with working truncation
|
||||
remove_file(file_path);
|
||||
size_t wrote = 0;
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
File file = SPIFFS.open(file_path, FILE_WRITE);
|
||||
if (file) {
|
||||
wrote = file.write(data.data(), data.size());
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
File file(InternalFS);
|
||||
if (file.open(file_path, FILE_O_WRITE)) {
|
||||
wrote = file.write(data.data(), data.size());
|
||||
#else
|
||||
#else
|
||||
if (false) {
|
||||
#endif
|
||||
#else
|
||||
#endif
|
||||
#else
|
||||
// Native
|
||||
FILE* file = fopen(file_path, "w");
|
||||
if (file != nullptr) {
|
||||
//size_t wrote = fwrite(data.data(), data.size(), 1, file);
|
||||
wrote = fwrite(data.data(), 1, data.size(), file);
|
||||
#endif
|
||||
TRACE("write_file: wrote " + std::to_string(wrote) + " bytes to file " + std::string(file_path));
|
||||
#endif
|
||||
TRACEF("write_file: wrote %zu bytes to file %s", wrote, file_path);
|
||||
if (wrote < data.size()) {
|
||||
WARNING("write_file: not all data was written to file " + std::string(file_path));
|
||||
WARNINGF("write_file: not all data was written to file %s", file_path);
|
||||
}
|
||||
//TRACE("write_file: closing output file");
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
file.close();
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
file.close();
|
||||
#endif
|
||||
#else
|
||||
#endif
|
||||
#else
|
||||
// Native
|
||||
fclose(file);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
ERROR("write_file: failed to open output file " + std::string(file_path));
|
||||
ERRORF("write_file: failed to open output file %s", file_path);
|
||||
}
|
||||
return wrote;
|
||||
}
|
||||
|
||||
virtual RNS::FileStream open_file(const char* file_path, RNS::FileStream::MODE file_mode) {
|
||||
TRACEF("open_file: opening file %s", file_path);
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
const char* mode;
|
||||
if (file_mode == RNS::FileStream::MODE_READ) {
|
||||
mode = FILE_READ;
|
||||
@@ -272,14 +273,13 @@ public:
|
||||
//if (!file) {
|
||||
File* file = new File(SPIFFS.open(file_path, mode));
|
||||
if (file == nullptr || !(*file)) {
|
||||
if (file != nullptr) delete file;
|
||||
ERRORF("open_file: failed to open output file %s", file_path);
|
||||
return {RNS::Type::NONE};
|
||||
}
|
||||
TRACEF("open_file: successfully opened file %s", file_path);
|
||||
return RNS::FileStream(new FileStreamImpl(file));
|
||||
#elif BOARD_NRF52
|
||||
//File file = File(InternalFS);
|
||||
File* file = new File(InternalFS);
|
||||
#elif BOARD_NRF52
|
||||
int mode;
|
||||
if (file_mode == RNS::FileStream::MODE_READ) {
|
||||
mode = FILE_O_READ;
|
||||
@@ -299,7 +299,10 @@ public:
|
||||
ERRORF("open_file: unsupported mode %d", file_mode);
|
||||
return {RNS::Type::NONE};
|
||||
}
|
||||
if (!file->open(file_path, mode)) {
|
||||
//File file = File(InternalFS);
|
||||
File* file = new File(InternalFS);
|
||||
if (file == nullptr || !file->open(file_path, mode)) {
|
||||
if (file != nullptr) delete file;
|
||||
ERRORF("open_file: failed to open output file %s", file_path);
|
||||
return {RNS::Type::NONE};
|
||||
}
|
||||
@@ -311,11 +314,11 @@ public:
|
||||
//}
|
||||
TRACEF("open_file: successfully opened file %s", file_path);
|
||||
return RNS::FileStream(new FileStreamImpl(file));
|
||||
#else
|
||||
#warning("unsupported");
|
||||
#else
|
||||
#warning("unsupported");
|
||||
return RNS::FileStream(RNS::Type::NONE);
|
||||
#endif
|
||||
#else // ARDUINO
|
||||
#endif
|
||||
#else // ARDUINO
|
||||
// Native
|
||||
const char* mode;
|
||||
if (file_mode == RNS::FileStream::MODE_READ) {
|
||||
@@ -339,140 +342,146 @@ public:
|
||||
}
|
||||
TRACEF("open_file: successfully opened file %s", file_path);
|
||||
return RNS::FileStream(new FileStreamImpl(file));
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
virtual bool remove_file(const char* file_path) {
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
return SPIFFS.remove(file_path);
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
return InternalFS.remove(file_path);
|
||||
#else
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
#else
|
||||
#endif
|
||||
#else
|
||||
// Native
|
||||
return (remove(file_path) == 0);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
virtual bool rename_file(const char* from_file_path, const char* to_file_path) {
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
return SPIFFS.rename(from_file_path, to_file_path);
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
return InternalFS.rename(from_file_path, to_file_path);
|
||||
#else
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
#else
|
||||
#endif
|
||||
#else
|
||||
// Native
|
||||
return (rename(from_file_path, to_file_path) == 0);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
/*virtua*/ bool directory_exists(const char* directory_path) {
|
||||
TRACE("directory_exists: checking for existence of directory " + std::string(directory_path));
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
TRACEF("directory_exists: checking for existence of directory %s", directory_path);
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
File file = SPIFFS.open(directory_path, FILE_READ);
|
||||
if (file) {
|
||||
bool is_directory = file.isDirectory();
|
||||
file.close();
|
||||
return is_directory;
|
||||
}
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
File file(InternalFS);
|
||||
if (file.open(directory_path, FILE_O_READ)) {
|
||||
bool is_directory = file.isDirectory();
|
||||
file.close();
|
||||
return is_directory;
|
||||
}
|
||||
#else
|
||||
#else
|
||||
if (false) {
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
#else
|
||||
#else
|
||||
// Native
|
||||
return false;
|
||||
#endif
|
||||
struct stat st = {0};
|
||||
return (stat(directory_path, &st) == 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
virtual bool create_directory(const char* directory_path) {
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
if (!SPIFFS.mkdir(directory_path)) {
|
||||
ERROR("create_directory: failed to create directorty " + std::string(directory_path));
|
||||
ERRORF("create_directory: failed to create directorty %s", directory_path);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
if (!InternalFS.mkdir(directory_path)) {
|
||||
ERROR("create_directory: failed to create directorty " + std::string(directory_path));
|
||||
ERRORF("create_directory: failed to create directorty %s", directory_path);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
#else
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
#else
|
||||
#endif
|
||||
#else
|
||||
// Native
|
||||
struct stat st = {0};
|
||||
if (stat(directory_path, &st) == 0) {
|
||||
return true;
|
||||
}
|
||||
return (mkdir(directory_path, 0700) == 0);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
/*virtua*/ bool remove_directory(const char* directory_path) {
|
||||
TRACE("remove_directory: removing directory " + std::string(directory_path));
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
TRACEF("remove_directory: removing directory %s", directory_path);
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
//if (!LittleFS.rmdir_r(directory_path)) {
|
||||
if (!SPIFFS.rmdir(directory_path)) {
|
||||
ERROR("remove_directory: failed to remove directorty " + std::string(directory_path));
|
||||
ERRORF("remove_directory: failed to remove directorty %s", directory_path);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
if (!InternalFS.rmdir_r(directory_path)) {
|
||||
ERROR("remove_directory: failed to remove directory " + std::string(directory_path));
|
||||
ERRORF("remove_directory: failed to remove directory %s", directory_path);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
#else
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
#else
|
||||
#endif
|
||||
#else
|
||||
// Native
|
||||
return false;
|
||||
#endif
|
||||
if (rmdir(directory_path) == 0) {
|
||||
ERRORF("remove_directory: failed to remove directory %s", directory_path);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
/*virtua*/ std::list<std::string> list_directory(const char* directory_path) {
|
||||
TRACE("list_directory: listing directory " + std::string(directory_path));
|
||||
/*virtua*/ std::list<std::string> list_directory(const char* directory_path, Callbacks::DirectoryListing callback = nullptr) {
|
||||
TRACEF("list_directory: listing directory %s", directory_path);
|
||||
std::list<std::string> files;
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef ARDUINO
|
||||
#ifdef BOARD_ESP32
|
||||
File root = SPIFFS.open(directory_path);
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
File root = InternalFS.open(directory_path);
|
||||
#endif
|
||||
#endif
|
||||
if (!root) {
|
||||
ERROR("list_directory: failed to open directory " + std::string(directory_path));
|
||||
ERRORF("list_directory: failed to open directory %s", directory_path);
|
||||
return files;
|
||||
}
|
||||
File file = root.openNextFile();
|
||||
while (file) {
|
||||
if (!file.isDirectory()) {
|
||||
char* name = (char*)file.name();
|
||||
files.push_back(name);
|
||||
if (callback) callback(name);
|
||||
else files.push_back(name);
|
||||
}
|
||||
// CBA Following close required to avoid leaking memory
|
||||
file.close();
|
||||
@@ -481,16 +490,34 @@ public:
|
||||
TRACE("list_directory: returning directory listing");
|
||||
root.close();
|
||||
return files;
|
||||
#else
|
||||
#else
|
||||
// Native
|
||||
DIR *dir = opendir(directory_path);
|
||||
if (dir == NULL) {
|
||||
ERRORF("list_directory: failed to open directory %s", directory_path);
|
||||
return files;
|
||||
}
|
||||
struct dirent *entry;
|
||||
while ((entry = readdir(dir)) != NULL) {
|
||||
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
|
||||
continue;
|
||||
}
|
||||
char* name = entry->d_name;
|
||||
if (callback) callback(name);
|
||||
else files.push_back(name);
|
||||
}
|
||||
if (closedir(dir) == -1) {
|
||||
ERRORF("list_directory: failed to close directory %s", directory_path);
|
||||
}
|
||||
|
||||
return files;
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
#ifdef ARDUINO
|
||||
#ifdef ARDUINO
|
||||
|
||||
#ifdef BOARD_ESP32
|
||||
#ifdef BOARD_ESP32
|
||||
|
||||
virtual size_t storage_size() {
|
||||
return SPIFFS.totalBytes();
|
||||
@@ -500,7 +527,7 @@ public:
|
||||
return (SPIFFS.totalBytes() - SPIFFS.usedBytes());
|
||||
}
|
||||
|
||||
#elif BOARD_NRF52
|
||||
#elif BOARD_NRF52
|
||||
|
||||
static int _countLfsBlock(void *p, lfs_block_t block){
|
||||
lfs_size_t *size = (lfs_size_t*) p;
|
||||
@@ -535,9 +562,9 @@ public:
|
||||
return (InternalFS.totalBytes() - InternalFS.usedBytes());
|
||||
}
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#else
|
||||
#else
|
||||
|
||||
virtual size_t storage_size() {
|
||||
return 0;
|
||||
@@ -547,7 +574,7 @@ public:
|
||||
return 0;
|
||||
}
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
protected:
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
#include <unity.h>
|
||||
|
||||
#include <Bytes.h>
|
||||
#include <Utilities/OS.h>
|
||||
#include <Utilities/Memory.h>
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <scoped_allocator>
|
||||
|
||||
//#define VECTOR_INTERNAL_CONTENT
|
||||
//#define VECTOR_EXTERNAL_CONTENT
|
||||
//#define BYTES_INTERNAL_CONTENT
|
||||
#define BYTES_EXTERNAL_CONTENT
|
||||
|
||||
class TestObject {
|
||||
public:
|
||||
TestObject() {}
|
||||
TestObject(const char* str, std::vector<std::string>& vec, RNS::Bytes& buf) : _str(str), _vec(vec), _external_buf(buf) {
|
||||
#ifdef VECTOR_INTERNAL_CONTENT
|
||||
// CBA The following vector entries use psram even though they're created internally (not part of base object)
|
||||
_vec.push_back("fee");
|
||||
_vec.push_back("fum");
|
||||
#endif
|
||||
#ifdef BYTES_INTERNAL_CONTENT
|
||||
// CBA The following Bytes content use psram even though they're created internally (not part of base object)
|
||||
_internal_buf.assign("This is a Bytes buffer allocated INSIDE of TestObject");
|
||||
#endif
|
||||
}
|
||||
inline bool operator < (const TestObject& test) const { return _str < test._str; }
|
||||
|
||||
inline const std::string toString() const { return std::string("TestObject(") + _str + "," + std::to_string(_vec.size()) + "," + _internal_buf.toString() + "," + _external_buf.toString() + ")"; }
|
||||
|
||||
// CBA All of the following empty containers are included in the memory allocated for std::map and use psram
|
||||
std::string _str;
|
||||
std::vector<std::string> _vec;
|
||||
RNS::Bytes _internal_buf;
|
||||
RNS::Bytes _external_buf;
|
||||
};
|
||||
|
||||
|
||||
void test_map_allocator() {
|
||||
|
||||
// CBA TODO Figure out how to selectively use PSRAM for Bytes and Packet objects.
|
||||
|
||||
// Trigger creation of both heap and psram pool before starting
|
||||
RNS::Utilities::Memory::pool_init(RNS::Utilities::Memory::heap_pool_info);
|
||||
RNS::Utilities::Memory::pool_init(RNS::Utilities::Memory::altheap_pool_info);
|
||||
//RNS::Utilities::Memory::dump_heap_stats();
|
||||
HEAD("Initial Stats:", RNS::LOG_TRACE);
|
||||
RNS::Utilities::Memory::dump_basic_pool_stats();
|
||||
//RNS::Utilities::Memory::dump_basic_allocator_stats();
|
||||
|
||||
{
|
||||
//using TestMap = std::map<Bytes, TestObject, std::less<Bytes>, RNS::Utilities::Memory::ContainerAllocator<std::pair<const Bytes, TestObject>>>;
|
||||
using TestMap = std::map<std::string, TestObject, std::less<std::string>, RNS::Utilities::Memory::ContainerAllocator<std::pair<const std::string, TestObject>>>;
|
||||
//using TestAlloc = RNS::Utilities::Memory::ContainerAllocator<std::pair<const std::string, TestObject>>;
|
||||
//using TestStringAlloc = RNS::Utilities::Memory::ContainerAllocator<char>;
|
||||
//using TestMap = std::map<std::string, TestObject, std::less<std::string>, std::scoped_allocator_adaptor<TestAlloc, TestStringAlloc>>;
|
||||
|
||||
HEAD("Post-map Stats:", RNS::LOG_TRACE);
|
||||
RNS::Utilities::Memory::dump_basic_pool_stats();
|
||||
//RNS::Utilities::Memory::dump_basic_allocator_stats();
|
||||
|
||||
// CBA The following empty vector object is included in the memory allocated for std::map and uses psram
|
||||
std::vector<std::string> vec;
|
||||
#ifdef VECTOR_EXTERNAL_CONTENT
|
||||
// CBA The following vector entries use psram
|
||||
vec.push_back("foo");
|
||||
vec.push_back("bar");
|
||||
#endif
|
||||
|
||||
// CBA The following empty Bytes object is included in the memory allocated for std::map and uses psram
|
||||
RNS::Bytes buf;
|
||||
#ifdef BYTES_EXTERNAL_CONTENT
|
||||
// CBA The following Bytes content use psram
|
||||
buf.assign("This is a Bytes buffer allocated OUTSIDE of TestObject");
|
||||
#endif
|
||||
|
||||
TestMap map;
|
||||
map.insert({"two", {"two", vec, buf}});
|
||||
map.insert({"one", {"one", vec, buf}});
|
||||
|
||||
HEAD("Post-insert Stats:", RNS::LOG_TRACE);
|
||||
RNS::Utilities::Memory::dump_basic_pool_stats();
|
||||
//RNS::Utilities::Memory::dump_basic_allocator_stats();
|
||||
|
||||
TEST_ASSERT_EQUAL(2, map.size());
|
||||
for (const auto& [key, entry] : map) {
|
||||
TRACEF("key: %s, entry: %s", key.c_str(), entry.toString().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
HEAD("Post-free Stats:", RNS::LOG_TRACE);
|
||||
RNS::Utilities::Memory::dump_basic_pool_stats();
|
||||
//RNS::Utilities::Memory::dump_basic_allocator_stats();
|
||||
|
||||
}
|
||||
|
||||
|
||||
void setUp(void) {
|
||||
// set stuff up here before each test
|
||||
}
|
||||
|
||||
void tearDown(void) {
|
||||
// clean stuff up here after each test
|
||||
}
|
||||
|
||||
int runUnityTests(void) {
|
||||
UNITY_BEGIN();
|
||||
|
||||
// Suite-level setup
|
||||
|
||||
// Run tests
|
||||
RUN_TEST(test_map_allocator);
|
||||
|
||||
// Suite-level teardown
|
||||
|
||||
return UNITY_END();
|
||||
}
|
||||
|
||||
// For native dev-platform or for some embedded frameworks
|
||||
int main(void) {
|
||||
return runUnityTests();
|
||||
}
|
||||
|
||||
#ifdef ARDUINO
|
||||
// For Arduino framework
|
||||
void setup() {
|
||||
// Wait ~2 seconds before the Unity test runner
|
||||
// establishes connection with a board Serial interface
|
||||
delay(2000);
|
||||
|
||||
runUnityTests();
|
||||
}
|
||||
void loop() {}
|
||||
#endif
|
||||
|
||||
// For ESP-IDF framework
|
||||
void app_main() {
|
||||
runUnityTests();
|
||||
}
|
||||
+164
-29
@@ -64,9 +64,9 @@ void testBytesMain() {
|
||||
bytes += prebuf + postbuf;
|
||||
TEST_ASSERT_EQUAL_size_t(14, bytes.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("FooHello World", bytes.data(), bytes.size());
|
||||
TRACE("assign bytes: " + bytes.toString());
|
||||
TRACE("assign prebuf: " + prebuf.toString());
|
||||
TRACE("assign postbuf: " + postbuf.toString());
|
||||
TRACEF("assign bytes: %s", bytes.toString().c_str());
|
||||
TRACEF("assign prebuf: %s", prebuf.toString().c_str());
|
||||
TRACEF("assign postbuf: %s", postbuf.toString().c_str());
|
||||
|
||||
// test string assignment with addition
|
||||
bytes = prebuf + postbuf;
|
||||
@@ -83,56 +83,56 @@ void testBytesMain() {
|
||||
// test left in range
|
||||
{
|
||||
RNS::Bytes left(bytes.left(5));
|
||||
TRACE("left: " + left.toString());
|
||||
TRACEF("left: %s", left.toString().c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(5, left.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("Hello", left.data(), left.size());
|
||||
}
|
||||
// test left oob
|
||||
{
|
||||
RNS::Bytes left(bytes.left(20));
|
||||
TRACE("oob left: " + left.toString());
|
||||
TRACEF("oob left: %s", left.toString().c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(11, left.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("Hello World", left.data(), left.size());
|
||||
}
|
||||
// test right in range
|
||||
{
|
||||
RNS::Bytes right(bytes.right(5));
|
||||
TRACE("right: " + right.toString());
|
||||
TRACEF("right: %s", right.toString().c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(5, right.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("World", right.data(), right.size());
|
||||
}
|
||||
// test right oob
|
||||
{
|
||||
RNS::Bytes right(bytes.right(20));
|
||||
TRACE("oob right: " + right.toString());
|
||||
TRACEF("oob right: %s", right.toString().c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(11, right.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("Hello World", right.data(), right.size());
|
||||
}
|
||||
// test mid in range
|
||||
{
|
||||
RNS::Bytes mid(bytes.mid(3, 5));
|
||||
TRACE("mid: " + mid.toString());
|
||||
TRACEF("mid: %s", mid.toString().c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(5, mid.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("lo Wo", mid.data(), mid.size());
|
||||
}
|
||||
// test mid oob pos
|
||||
{
|
||||
RNS::Bytes mid(bytes.mid(20, 5));
|
||||
TRACE("oob pos mid: " + mid.toString());
|
||||
TRACEF("oob pos mid: %s", mid.toString().c_str());
|
||||
TEST_ASSERT_FALSE(mid);
|
||||
TEST_ASSERT_EQUAL_size_t(0, mid.size());
|
||||
}
|
||||
// test mid oob pos
|
||||
{
|
||||
RNS::Bytes mid(bytes.mid(3, 20));
|
||||
TRACE("oob len mid: " + mid.toString());
|
||||
TRACEF("oob len mid: %s", mid.toString().c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(8, mid.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("lo World", mid.data(), mid.size());
|
||||
}
|
||||
// test mid to end variant
|
||||
{
|
||||
RNS::Bytes mid(bytes.mid(3));
|
||||
TRACE("end mid: " + mid.toString());
|
||||
TRACEF("end mid: %s", mid.toString().c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(8, mid.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("lo World", mid.data(), mid.size());
|
||||
}
|
||||
@@ -142,7 +142,7 @@ void testBytesMain() {
|
||||
{
|
||||
RNS::Bytes shrink(bytes);
|
||||
shrink.resize(5);
|
||||
TRACE("shrink: " + shrink.toString());
|
||||
TRACEF("shrink: %s", shrink.toString().c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(5, shrink.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("Hello", shrink.data(), shrink.size());
|
||||
}
|
||||
@@ -151,11 +151,11 @@ void testBytesMain() {
|
||||
HEAD("TestBytes: trim", RNS::LOG_TRACE);
|
||||
{
|
||||
RNS::Bytes bytes("Hello World");
|
||||
TRACE("orig: " + bytes.toString());
|
||||
TRACEF("orig: %s", bytes.toString().c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(11, bytes.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("Hello World", bytes.data(), bytes.size());
|
||||
bytes = bytes.left(5);
|
||||
TRACE("trim: " + bytes.toString());
|
||||
TRACEF("trim: %s", bytes.toString().c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(5, bytes.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("Hello", bytes.data(), bytes.size());
|
||||
}
|
||||
@@ -226,9 +226,9 @@ void testCowBytes() {
|
||||
TEST_ASSERT_EQUAL_MEMORY("1", bytes3.data(), bytes3.size());
|
||||
TEST_ASSERT_EQUAL_PTR(bytes2.data(), bytes3.data());
|
||||
|
||||
TRACE("pre bytes1 ptr: " + std::to_string((uintptr_t)bytes1.data()) + " data: " + bytes1.toString());
|
||||
TRACE("pre bytes2 ptr: " + std::to_string((uintptr_t)bytes2.data()) + " data: " + bytes2.toString());
|
||||
TRACE("pre bytes3 ptr: " + std::to_string((uintptr_t)bytes3.data()) + " data: " + bytes3.toString());
|
||||
TRACEF("pre bytes1 ptr: %p data: %s", (void*)bytes1.data(), bytes1.toString().c_str());
|
||||
TRACEF("pre bytes2 ptr: %p data: %s", (void*)bytes2.data(), bytes2.toString().c_str());
|
||||
TRACEF("pre bytes3 ptr: %p data: %s", (void*)bytes3.data(), bytes3.toString().c_str());
|
||||
|
||||
//bytes1.append("mississippi");
|
||||
//assert(bytes1.size() == 12);
|
||||
@@ -245,9 +245,9 @@ void testCowBytes() {
|
||||
TEST_ASSERT_EQUAL_MEMORY("mississippi", bytes3.data(), bytes3.size());
|
||||
TEST_ASSERT_NOT_EQUAL(bytes2.data(), bytes3.data());
|
||||
|
||||
TRACE("post bytes1 ptr: " + std::to_string((uintptr_t)bytes1.data()) + " data: " + bytes1.toString());
|
||||
TRACE("post bytes2 ptr: " + std::to_string((uintptr_t)bytes2.data()) + " data: " + bytes2.toString());
|
||||
TRACE("post bytes3 ptr: " + std::to_string((uintptr_t)bytes3.data()) + " data: " + bytes3.toString());
|
||||
TRACEF("post bytes1 ptr: %p data: %s", (void*)bytes1.data(), bytes1.toString().c_str());
|
||||
TRACEF("post bytes2 ptr: %p data: %s", (void*)bytes2.data(), bytes2.toString().c_str());
|
||||
TRACEF("post bytes3 ptr: %p data: %s", (void*)bytes3.data(), bytes3.toString().c_str());
|
||||
}
|
||||
|
||||
void testBytesConversion() {
|
||||
@@ -255,14 +255,14 @@ void testBytesConversion() {
|
||||
{
|
||||
RNS::Bytes bytes("Hello World");
|
||||
std::string hex = bytes.toHex(true);
|
||||
TRACE("text: \"" + bytes.toString() + "\" upper hex: \"" + hex + "\"");
|
||||
TRACEF("text: \"%s\" upper hex: \"%s\"", bytes.toString().c_str(), hex.c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(22, hex.length());
|
||||
TEST_ASSERT_EQUAL_STRING("48656C6C6F20576F726C64", hex.c_str());
|
||||
}
|
||||
{
|
||||
RNS::Bytes bytes("Hello World");
|
||||
std::string hex = bytes.toHex(false);
|
||||
TRACE("text: \"" + bytes.toString() + "\" lower hex: \"" + hex + "\"");
|
||||
TRACEF("text: \"%s\" lower hex: \"%s\"", bytes.toString().c_str(), hex.c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(22, hex.length());
|
||||
TEST_ASSERT_EQUAL_STRING("48656c6c6f20576f726c64", hex.c_str());
|
||||
}
|
||||
@@ -271,7 +271,7 @@ void testBytesConversion() {
|
||||
RNS::Bytes bytes;
|
||||
bytes.assignHex(hex.c_str());
|
||||
std::string text = bytes.toString();
|
||||
TRACE("hex: \"" + hex + "\" text: \"" + text + "\"");
|
||||
TRACEF("hex: \"%s\" text: \"%s\"", hex.c_str(), text.c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(11, text.length());
|
||||
TEST_ASSERT_EQUAL_STRING("Hello World", text.c_str());
|
||||
}
|
||||
@@ -280,27 +280,74 @@ void testBytesConversion() {
|
||||
RNS::Bytes bytes;
|
||||
bytes.assignHex(hex.c_str());
|
||||
std::string text = bytes.toString();
|
||||
TRACE("hex: \"" + hex + "\" text: \"" + text + "\"");
|
||||
TRACEF("hex: \"%s\" text: \"%s\"", hex.c_str(), text.c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(11, text.length());
|
||||
TEST_ASSERT_EQUAL_STRING("Hello World", text.c_str());
|
||||
|
||||
// overwrite
|
||||
bytes.assignHex(hex.c_str());
|
||||
text = bytes.toString();
|
||||
TRACE("hex: \"" + hex + "\" text: \"" + text + "\"");
|
||||
TRACEF("hex: \"%s\" text: \"%s\"", hex.c_str(), text.c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(11, text.length());
|
||||
TEST_ASSERT_EQUAL_STRING("Hello World", text.c_str());
|
||||
|
||||
// apend
|
||||
bytes.appendHex(hex.c_str());
|
||||
text = bytes.toString();
|
||||
TRACE("hex: \"" + hex + "\" text: \"" + text + "\"");
|
||||
TRACEF("hex: \"%s\" text: \"%s\"", hex.c_str(), text.c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(22, text.length());
|
||||
TEST_ASSERT_EQUAL_STRING("Hello WorldHello World", text.c_str());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void testBytesBase64() {
|
||||
|
||||
// encode "Hello World" → known base64 value
|
||||
{
|
||||
RNS::Bytes bytes("Hello World");
|
||||
std::string b64 = bytes.toBase64();
|
||||
TRACEF("text: \"%s\" base64: \"%s\"", bytes.toString().c_str(), b64.c_str());
|
||||
TEST_ASSERT_EQUAL_STRING("SGVsbG8gV29ybGQ=", b64.c_str());
|
||||
}
|
||||
|
||||
// decode known base64 string → "Hello World"
|
||||
{
|
||||
RNS::Bytes bytes;
|
||||
bytes.assignBase64("SGVsbG8gV29ybGQ=");
|
||||
std::string text = bytes.toString();
|
||||
TRACEF("base64: \"SGVsbG8gV29ybGQ=\" text: \"%s\"", text.c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(11, text.length());
|
||||
TEST_ASSERT_EQUAL_STRING("Hello World", text.c_str());
|
||||
}
|
||||
|
||||
// round-trip stability
|
||||
{
|
||||
RNS::Bytes original("Hello World");
|
||||
std::string b64 = original.toBase64();
|
||||
RNS::Bytes restored;
|
||||
restored.assignBase64(b64.c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(original.size(), restored.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY(original.data(), restored.data(), original.size());
|
||||
}
|
||||
|
||||
// empty bytes → toBase64 returns ""
|
||||
{
|
||||
RNS::Bytes empty;
|
||||
TEST_ASSERT_EQUAL_STRING("", empty.toBase64().c_str());
|
||||
}
|
||||
|
||||
// assignBase64 then appendBase64 produces concatenated result
|
||||
{
|
||||
RNS::Bytes bytes;
|
||||
bytes.assignBase64("SGVsbG8="); // "Hello"
|
||||
bytes.appendBase64("IFdvcmxk"); // " World"
|
||||
TEST_ASSERT_EQUAL_size_t(11, bytes.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("Hello World", bytes.data(), bytes.size());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void testBytesResize() {
|
||||
TRACE("Testing downsize of Bytes with initial capacity");
|
||||
|
||||
@@ -569,6 +616,83 @@ void testIndex() {
|
||||
TEST_ASSERT_EQUAL_UINT8('o', bytes[4]);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Bytes edge case tests
|
||||
// ============================================================================
|
||||
|
||||
void test_assignHex_even_length() {
|
||||
// Normal case: even-length hex string
|
||||
RNS::Bytes bytes;
|
||||
bytes.assignHex("48656C6C6F"); // "Hello"
|
||||
TEST_ASSERT_EQUAL_size_t(5, bytes.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("Hello", bytes.data(), 5);
|
||||
}
|
||||
|
||||
void test_assignHex_odd_length() {
|
||||
// Odd-length hex should be truncated to even (drop trailing nibble)
|
||||
RNS::Bytes bytes;
|
||||
bytes.assignHex("ABC"); // 3 chars - only "AB" should be decoded
|
||||
TEST_ASSERT_EQUAL_size_t(1, bytes.size());
|
||||
TEST_ASSERT_EQUAL_UINT8(0xAB, bytes.data()[0]);
|
||||
}
|
||||
|
||||
void test_assignHex_single_char() {
|
||||
// Single char hex can't form a complete byte - should produce empty
|
||||
RNS::Bytes bytes;
|
||||
bytes.assignHex("A");
|
||||
TEST_ASSERT_EQUAL_size_t(0, bytes.size());
|
||||
}
|
||||
|
||||
void test_assignHex_empty() {
|
||||
RNS::Bytes bytes;
|
||||
bytes.assignHex("");
|
||||
TEST_ASSERT_EQUAL_size_t(0, bytes.size());
|
||||
}
|
||||
|
||||
void test_appendHex_odd_length() {
|
||||
// appendHex with odd length should also truncate to even
|
||||
RNS::Bytes bytes;
|
||||
bytes.assignHex("4142"); // "AB"
|
||||
TEST_ASSERT_EQUAL_size_t(2, bytes.size());
|
||||
|
||||
bytes.appendHex("434"); // 3 chars - only "43" ('C') should be appended
|
||||
TEST_ASSERT_EQUAL_size_t(3, bytes.size());
|
||||
TEST_ASSERT_EQUAL_UINT8(0x43, bytes.data()[2]);
|
||||
}
|
||||
|
||||
void test_hex_roundtrip_stability() {
|
||||
// toHex always produces even length, so roundtrip should be safe
|
||||
RNS::Bytes original("Hello World");
|
||||
std::string hex = original.toHex();
|
||||
TEST_ASSERT_TRUE(hex.length() % 2 == 0); // Must be even
|
||||
|
||||
RNS::Bytes restored;
|
||||
restored.assignHex(hex.c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(original.size(), restored.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY(original.data(), restored.data(), original.size());
|
||||
}
|
||||
|
||||
void test_mid_large_len() {
|
||||
// mid() with len that extends past end should clamp
|
||||
RNS::Bytes bytes("Hello World");
|
||||
|
||||
RNS::Bytes mid = bytes.mid(3, 100);
|
||||
TEST_ASSERT_EQUAL_size_t(8, mid.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("lo World", mid.data(), 8);
|
||||
|
||||
// SIZE_MAX len should also clamp, not integer-overflow and crash
|
||||
RNS::Bytes mid2 = bytes.mid(3, SIZE_MAX);
|
||||
TEST_ASSERT_EQUAL_size_t(8, mid2.size());
|
||||
TEST_ASSERT_EQUAL_MEMORY("lo World", mid2.data(), 8);
|
||||
}
|
||||
|
||||
void test_mid_zero_size_bytes() {
|
||||
RNS::Bytes empty;
|
||||
RNS::Bytes mid = empty.mid(0, 5);
|
||||
TEST_ASSERT_FALSE(mid);
|
||||
TEST_ASSERT_EQUAL_size_t(0, mid.size());
|
||||
}
|
||||
|
||||
|
||||
void setUp(void) {
|
||||
// set stuff up here before each test
|
||||
@@ -582,14 +706,15 @@ int runUnityTests(void) {
|
||||
UNITY_BEGIN();
|
||||
|
||||
// Suite-level setup
|
||||
RNS::Utilities::OS::dump_heap_stats();
|
||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
||||
RNS::Utilities::Memory::dump_heap_stats();
|
||||
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||
TRACEF("testBytes: pre-mem: %u", pre_memory);
|
||||
|
||||
// Run tests
|
||||
RUN_TEST(testBytesMain);
|
||||
RUN_TEST(testCowBytes);
|
||||
RUN_TEST(testBytesConversion);
|
||||
RUN_TEST(testBytesBase64);
|
||||
RUN_TEST(testBytesResize);
|
||||
RUN_TEST(testBytesStream);
|
||||
RUN_TEST(testBytesReserve);
|
||||
@@ -598,8 +723,18 @@ int runUnityTests(void) {
|
||||
RUN_TEST(testConcat);
|
||||
RUN_TEST(testIndex);
|
||||
|
||||
// Bytes edge cases
|
||||
RUN_TEST(test_assignHex_even_length);
|
||||
RUN_TEST(test_assignHex_odd_length);
|
||||
RUN_TEST(test_assignHex_single_char);
|
||||
RUN_TEST(test_assignHex_empty);
|
||||
RUN_TEST(test_appendHex_odd_length);
|
||||
RUN_TEST(test_hex_roundtrip_stability);
|
||||
RUN_TEST(test_mid_large_len);
|
||||
RUN_TEST(test_mid_zero_size_bytes);
|
||||
|
||||
// Suite-level teardown
|
||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||
TRACEF("testBytes: post-mem: %u", post_memory);
|
||||
TRACEF("testBytes: diff-mem: %u", diff_memory);
|
||||
|
||||
@@ -28,14 +28,14 @@ void testBytesMap()
|
||||
TEST_ASSERT_NOT_EQUAL(map.end(), preit);
|
||||
TEST_ASSERT_EQUAL_STRING("hello", (*preit).second.c_str());
|
||||
if (preit != map.end()) {
|
||||
TRACE(std::string("found prebuf: ") + (*preit).second);
|
||||
TRACEF("found prebuf: %s", (*preit).second.c_str());
|
||||
}
|
||||
|
||||
auto postit = map.find(postbuf);
|
||||
TEST_ASSERT_NOT_EQUAL(map.end(), postit);
|
||||
TEST_ASSERT_EQUAL_STRING("world", (*postit).second.c_str());
|
||||
if (postit != map.end()) {
|
||||
TRACE(std::string("found postbuf: ") + (*postit).second);
|
||||
TRACEF("found postbuf: %s", (*postit).second.c_str());
|
||||
}
|
||||
|
||||
const uint8_t newstr[] = "World";
|
||||
@@ -46,7 +46,7 @@ void testBytesMap()
|
||||
TEST_ASSERT_NOT_EQUAL(map.end(), newit);
|
||||
TEST_ASSERT_EQUAL_STRING("world", (*newit).second.c_str());
|
||||
if (newit != map.end()) {
|
||||
TRACE(std::string("found newbuf: ") + (*newit).second);
|
||||
TRACEF("found newbuf: %s", (*newit).second.c_str());
|
||||
}
|
||||
|
||||
std::string str = map["World"];
|
||||
@@ -85,7 +85,7 @@ void testOldMap() {
|
||||
}
|
||||
}
|
||||
for (auto& pair : entries) {
|
||||
TRACE("entries: " + pair.second._hash.toString());
|
||||
TRACEF("entries: %s", pair.second._hash.toString().c_str());
|
||||
}
|
||||
TEST_ASSERT_EQUAL_size_t(2, entries.size());
|
||||
TEST_ASSERT_EQUAL_size_t(2, other_entries.size());
|
||||
@@ -113,7 +113,7 @@ void testNewMap() {
|
||||
}
|
||||
}
|
||||
for (auto& [hash, entry] : entries) {
|
||||
TRACE("entries: " + entry._hash.toString());
|
||||
TRACEF("entries: %s", entry._hash.toString().c_str());
|
||||
}
|
||||
TEST_ASSERT_EQUAL_size_t(2, entries.size());
|
||||
TEST_ASSERT_EQUAL_size_t(2, other_entries.size());
|
||||
|
||||
@@ -20,7 +20,7 @@ const char test_stream_path[] = "test_stream";
|
||||
|
||||
void writeFile(const char* file_path) {
|
||||
|
||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||
TRACEF("testWriteFile: pre-mem: %u", pre_memory);
|
||||
|
||||
{
|
||||
@@ -29,7 +29,7 @@ void writeFile(const char* file_path) {
|
||||
TEST_ASSERT_EQUAL_size_t(4, wrote);
|
||||
}
|
||||
|
||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||
TRACEF("testWriteFile: post-mem: %u", post_memory);
|
||||
TRACEF("testWriteFile: diff-mem: %u", diff_memory);
|
||||
@@ -39,7 +39,7 @@ void writeFile(const char* file_path) {
|
||||
|
||||
void readFile(const char* file_path) {
|
||||
|
||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||
TRACEF("testReadFile: pre-mem: %u", pre_memory);
|
||||
|
||||
{
|
||||
@@ -49,7 +49,7 @@ void readFile(const char* file_path) {
|
||||
TEST_ASSERT_EQUAL_STRING("test", data.toString().c_str());
|
||||
}
|
||||
|
||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||
TRACEF("testReadFile: post-mem: %u", post_memory);
|
||||
TRACEF("testReadFile: diff-mem: %u", diff_memory);
|
||||
@@ -59,7 +59,7 @@ void readFile(const char* file_path) {
|
||||
|
||||
void overwriteFile(const char* file_path) {
|
||||
|
||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||
TRACEF("testOverwriteFile: pre-mem: %u", pre_memory);
|
||||
|
||||
// overwrite
|
||||
@@ -77,7 +77,7 @@ void overwriteFile(const char* file_path) {
|
||||
TEST_ASSERT_EQUAL_STRING("test", data.toString().c_str());
|
||||
}
|
||||
|
||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||
TRACEF("testOverwriteFile: post-mem: %u", post_memory);
|
||||
TRACEF("testOverwriteFile: diff-mem: %u", diff_memory);
|
||||
@@ -87,12 +87,12 @@ void overwriteFile(const char* file_path) {
|
||||
|
||||
void removeFile(const char* file_path) {
|
||||
|
||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||
TRACEF("testRemoveFile: pre-mem: %u", pre_memory);
|
||||
|
||||
TEST_ASSERT_TRUE(RNS::Utilities::OS::remove_file(file_path));
|
||||
|
||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||
TRACEF("testRemoveFile: post-mem: %u", post_memory);
|
||||
TRACEF("testRemoveFile: diff-mem: %u", diff_memory);
|
||||
@@ -102,7 +102,7 @@ void removeFile(const char* file_path) {
|
||||
|
||||
void writeFileStream(const char* file_path) {
|
||||
|
||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||
TRACEF("testWriteFileStream: pre-mem: %u", pre_memory);
|
||||
|
||||
{
|
||||
@@ -121,7 +121,7 @@ void writeFileStream(const char* file_path) {
|
||||
TEST_ASSERT_EQUAL_UINT32(crc, stream.crc());
|
||||
}
|
||||
|
||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||
TRACEF("testWriteFileStream: post-mem: %u", post_memory);
|
||||
TRACEF("testWriteFileStream: diff-mem: %u", diff_memory);
|
||||
@@ -131,7 +131,7 @@ void writeFileStream(const char* file_path) {
|
||||
|
||||
void readFileStream(const char* file_path) {
|
||||
|
||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||
TRACEF("testReadFileStream: pre-mem: %u", pre_memory);
|
||||
|
||||
{
|
||||
@@ -153,7 +153,7 @@ void readFileStream(const char* file_path) {
|
||||
TEST_ASSERT_EQUAL_UINT32(crc, stream.crc());
|
||||
}
|
||||
|
||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||
TRACEF("testReadFileStream: post-mem: %u", post_memory);
|
||||
TRACEF("testReadFileStream: diff-mem: %u", diff_memory);
|
||||
@@ -164,23 +164,19 @@ void readFileStream(const char* file_path) {
|
||||
|
||||
void testListDirectory() {
|
||||
|
||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
||||
INFO("testListDirectory: pre-mem: " + std::to_string(pre_memory));
|
||||
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||
INFOF("testListDirectory: pre-mem: %zu", pre_memory);
|
||||
|
||||
{
|
||||
for (int i = 0; i < 1; i++) {
|
||||
std::list<std::string> files;
|
||||
files = RNS::Utilities::OS::list_directory("/");
|
||||
for (auto& file : files) {
|
||||
INFO("FILE: " + file);
|
||||
}
|
||||
}
|
||||
RNS::Utilities::OS::list_directory("/", [](const char* file_path) {
|
||||
INFOF("FILE: %s", file_path);
|
||||
});
|
||||
}
|
||||
|
||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||
INFO("testListDirectory: post-mem: " + std::to_string(post_memory));
|
||||
INFO("testListDirectory: diff-mem: " + std::to_string(diff_memory));
|
||||
INFOF("testListDirectory: post-mem: %zu", post_memory);
|
||||
INFOF("testListDirectory: diff-mem: %zu", diff_memory);
|
||||
TEST_ASSERT_EQUAL_size_t(0, diff_memory);
|
||||
}
|
||||
|
||||
@@ -202,7 +198,7 @@ void testRemoveFile(const char* file_path) {
|
||||
|
||||
void testReadNonexistantFile() {
|
||||
|
||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||
TRACEF("testReadNonexistantFile: pre-mem: %u", pre_memory);
|
||||
|
||||
{
|
||||
@@ -211,7 +207,7 @@ void testReadNonexistantFile() {
|
||||
TEST_ASSERT_EQUAL_size_t(0, read);
|
||||
}
|
||||
|
||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||
TRACEF("testReadNonexistantFile: post-mem: %u", post_memory);
|
||||
TRACEF("testReadNonexistantFile: diff-mem: %u", diff_memory);
|
||||
@@ -221,7 +217,7 @@ void testReadNonexistantFile() {
|
||||
|
||||
void testWriteFail() {
|
||||
|
||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||
TRACEF("testWriteFail: pre-mem: %u", pre_memory);
|
||||
|
||||
{
|
||||
@@ -230,7 +226,7 @@ void testWriteFail() {
|
||||
TEST_ASSERT_EQUAL_size_t(4, wrote);
|
||||
}
|
||||
|
||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||
TRACEF("testWriteFail: post-mem: %u", post_memory);
|
||||
TRACEF("testWriteFail: diff-mem: %u", diff_memory);
|
||||
@@ -290,7 +286,7 @@ int runUnityTests(void) {
|
||||
FileSystem::listDir("/cache");
|
||||
RNS::Utilities::OS::register_filesystem(test_filesystem);
|
||||
|
||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||
TRACEF("testFileSystem: pre-mem: %u", pre_memory);
|
||||
|
||||
// CBA Seems that first call to write_file allocates some memory (at least with NRF52 LittleFS) so get that out of the way first
|
||||
@@ -300,7 +296,7 @@ int runUnityTests(void) {
|
||||
RNS::Utilities::OS::remove_file("./foo");
|
||||
}
|
||||
|
||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
||||
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||
TRACEF("testFileSystem: post-mem: %u", post_memory);
|
||||
TRACEF("testFileSystem: diff-mem: %u", diff_memory);
|
||||
|
||||
@@ -20,12 +20,12 @@ void testTime()
|
||||
double diff_time;
|
||||
|
||||
diff_time = (double)(end_ltime - start_ltime) / 1000.0;
|
||||
TRACE(std::string("ltime diff: ") + std::to_string(diff_time));
|
||||
TRACEF("ltime diff: %f", diff_time);
|
||||
TEST_ASSERT_TRUE(diff_time > sleep_time * 0.99);
|
||||
TEST_ASSERT_TRUE(diff_time < sleep_time * 1.01);
|
||||
|
||||
diff_time = end_dtime - start_dtime;
|
||||
TRACE(std::string("dtime diff: ") + std::to_string(diff_time));
|
||||
TRACEF("dtime diff: %f", diff_time);
|
||||
TEST_ASSERT_TRUE(diff_time > sleep_time * 0.99);
|
||||
TEST_ASSERT_TRUE(diff_time < sleep_time * 1.01);
|
||||
|
||||
|
||||
@@ -26,12 +26,12 @@ public:
|
||||
|
||||
private:
|
||||
virtual void send_outgoing(const RNS::Bytes& data) {
|
||||
DEBUG("TestInterface.send_outgoing: data: " + data.toHex());
|
||||
DEBUGF("TestInterface.send_outgoing: data: %s", data.toHex().c_str());
|
||||
// Perform post-send housekeeping
|
||||
InterfaceImpl::handle_outgoing(data);
|
||||
}
|
||||
void on_incoming(const RNS::Bytes& data) {
|
||||
DEBUG("TestInterface.on_incoming: data: " + data.toHex());
|
||||
DEBUGF("TestInterface.on_incoming: data: %s", data.toHex().c_str());
|
||||
// Pass received data on to transport
|
||||
InterfaceImpl::handle_incoming(data);
|
||||
}
|
||||
@@ -82,7 +82,7 @@ const char test_file_data[] = "test data";
|
||||
void testWrite() {
|
||||
RNS::Bytes data(test_file_data);
|
||||
if (RNS::Utilities::OS::write_file(test_file_path, data) == data.size()) {
|
||||
TRACE("wrote: " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("wrote: %zu bytes", data.size());
|
||||
}
|
||||
else {
|
||||
TRACE("write failed");
|
||||
@@ -93,8 +93,8 @@ void testWrite() {
|
||||
void testRead() {
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_file_path, data) > 0) {
|
||||
TRACE("read: " + std::to_string(data.size()) + " bytes");
|
||||
TRACE("data: " + data.toString());
|
||||
TRACEF("read: %zu bytes", data.size());
|
||||
TRACEF("data: %s", data.toString().c_str());
|
||||
TEST_ASSERT_EQUAL_size_t(strlen(test_file_data), data.size());
|
||||
TEST_ASSERT_NOT_NULL(data.data());
|
||||
TEST_ASSERT_EQUAL_MEMORY(test_file_data, data.data(), strlen(test_file_data));
|
||||
@@ -132,10 +132,10 @@ void testSerializeObject() {
|
||||
if (length < size) {
|
||||
data.resize(length);
|
||||
}
|
||||
TRACE("serialized " + std::to_string(length) + " bytes");
|
||||
TRACEF("serialized %zu bytes", length);
|
||||
if (length > 0) {
|
||||
if (RNS::Utilities::OS::write_file(test_object_path, data) == data.size()) {
|
||||
TRACE("wrote: " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("wrote: %zu bytes", data.size());
|
||||
}
|
||||
else {
|
||||
TRACE("write failed");
|
||||
@@ -157,14 +157,14 @@ void testDeserializeObject() {
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_object_path, data) > 0) {
|
||||
if (data) {
|
||||
TRACE("read: " + std::to_string(data.size()) + " bytes");
|
||||
//TRACE("data: " + data.toString());
|
||||
TRACEF("read: %zu bytes", data.size());
|
||||
//TRACEF("data: %s", data.toString().c_str());
|
||||
DeserializationError error = deserializeJson(doc, data.data());
|
||||
//DeserializationError error = deserializeMsgPack(doc, data.data());
|
||||
if (!error) {
|
||||
JsonObject root = doc.as<JsonObject>();
|
||||
for (JsonPair kv : root) {
|
||||
TRACE("key: " + std::string(kv.key().c_str()) + " value: " + kv.value().as<const char*>());
|
||||
TRACEF("key: %s value: %s", kv.key().c_str(), kv.value().as<const char*>());
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -184,7 +184,7 @@ void testSerializeObject() {
|
||||
|
||||
std::vector<std::string> vec({"one", "two"});
|
||||
TestObject test("test", vec);
|
||||
TRACE("testSerializeObject: test: " + test.toString());
|
||||
TRACEF("testSerializeObject: test: %s", test.toString().c_str());
|
||||
|
||||
JsonDocument doc;
|
||||
doc.set(test);
|
||||
@@ -196,10 +196,10 @@ void testSerializeObject() {
|
||||
if (length < size) {
|
||||
data.resize(length);
|
||||
}
|
||||
TRACE("testSerializeObject: serialized " + std::to_string(length) + " bytes");
|
||||
TRACEF("testSerializeObject: serialized %zu bytes", length);
|
||||
if (length > 0) {
|
||||
if (RNS::Utilities::OS::write_file(test_object_path, data) == data.size()) {
|
||||
TRACE("testSerializeObject: wrote: " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("testSerializeObject: wrote: %zu bytes", data.size());
|
||||
}
|
||||
else {
|
||||
TRACE("testSerializeObject: write failed");
|
||||
@@ -219,17 +219,17 @@ void testDeserializeObject() {
|
||||
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_object_path, data) > 0) {
|
||||
TRACE("testDeserializeObject: read: " + std::to_string(data.size()) + " bytes");
|
||||
//TRACE("data: " + data.toString());
|
||||
TRACEF("testDeserializeObject: read: %zu bytes", data.size());
|
||||
//TRACEF("data: %s", data.toString().c_str());
|
||||
DeserializationError error = deserializeJson(doc, data.data());
|
||||
//DeserializationError error = deserializeMsgPack(doc, data.data());
|
||||
if (!error) {
|
||||
//JsonObject root = doc.as<JsonObject>();
|
||||
//for (JsonPair kv : root) {
|
||||
// TRACE("key: " + std::string(kv.key().c_str()) + " value: " + kv.value().as<const char*>());
|
||||
// TRACEF("key: %s value: %s", kv.key().c_str(), kv.value().as<const char*>());
|
||||
//}
|
||||
TestObject test = doc.as<TestObject>();
|
||||
TRACE("testDeserializeObject: test: " + test.toString());
|
||||
TRACEF("testDeserializeObject: test: %s", test.toString().c_str());
|
||||
}
|
||||
else {
|
||||
TRACE("testDeserializeObject: failed to deserialize");
|
||||
@@ -292,10 +292,10 @@ void testSerializeVector() {
|
||||
if (length < size) {
|
||||
data.resize(length);
|
||||
}
|
||||
TRACE("testSerializeVector: serialized " + std::to_string(length) + " bytes");
|
||||
TRACEF("testSerializeVector: serialized %zu bytes", length);
|
||||
if (length > 0) {
|
||||
if (RNS::Utilities::OS::write_file(test_vector_path, data) == data.size()) {
|
||||
TRACE("testSerializeVector: wrote: " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("testSerializeVector: wrote: %zu bytes", data.size());
|
||||
}
|
||||
else {
|
||||
TRACE("testSerializeVector: write failed");
|
||||
@@ -315,8 +315,8 @@ void testDeserializeVector() {
|
||||
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_vector_path, data) > 0) {
|
||||
TRACE("testDeserializeVector: read: " + std::to_string(data.size()) + " bytes");
|
||||
//TRACE("testDeserializeVector: data: " + data.toString());
|
||||
TRACEF("testDeserializeVector: read: %zu bytes", data.size());
|
||||
//TRACEF("testDeserializeVector: data: %s", data.toString().c_str());
|
||||
DeserializationError error = deserializeJson(doc, data.data());
|
||||
//DeserializationError error = deserializeMsgPack(doc, data.data());
|
||||
if (!error) {
|
||||
@@ -324,12 +324,12 @@ void testDeserializeVector() {
|
||||
|
||||
std::vector<TestObject> vector = doc.as<std::vector<TestObject>>();
|
||||
for (auto& test : vector) {
|
||||
TRACE("testDeserializeVector: entry: " + test.toString());
|
||||
TRACEF("testDeserializeVector: entry: %s", test.toString().c_str());
|
||||
}
|
||||
|
||||
//JsonArray arr = doc.as<JsonArray>();
|
||||
//for (JsonVariant elem : arr) {
|
||||
// TRACE("testDeserializeVector: entry: " + elem.as<TestObject>().toString());
|
||||
// TRACEF("testDeserializeVector: entry: %s", elem.as<TestObject>().toString().c_str());
|
||||
//}
|
||||
}
|
||||
else {
|
||||
@@ -381,10 +381,10 @@ void testSerializeSet() {
|
||||
if (length < size) {
|
||||
data.resize(length);
|
||||
}
|
||||
TRACE("testSerializeSet: serialized " + std::to_string(length) + " bytes");
|
||||
TRACEF("testSerializeSet: serialized %zu bytes", length);
|
||||
if (length > 0) {
|
||||
if (RNS::Utilities::OS::write_file(test_set_path, data) == data.size()) {
|
||||
TRACE("testSerializeSet: wrote: " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("testSerializeSet: wrote: %zu bytes", data.size());
|
||||
}
|
||||
else {
|
||||
TRACE("testSerializeSet: write failed");
|
||||
@@ -404,8 +404,8 @@ void testDeserializeSet() {
|
||||
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_set_path, data) > 0) {
|
||||
TRACE("testDeserializeSet: read: " + std::to_string(data.size()) + " bytes");
|
||||
//TRACE("testDeserializeSet: data: " + data.toString());
|
||||
TRACEF("testDeserializeSet: read: %zu bytes", data.size());
|
||||
//TRACEF("testDeserializeSet: data: %s", data.toString().c_str());
|
||||
DeserializationError error = deserializeJson(doc, data.data());
|
||||
//DeserializationError error = deserializeMsgPack(doc, data.data());
|
||||
if (!error) {
|
||||
@@ -413,12 +413,12 @@ void testDeserializeSet() {
|
||||
|
||||
std::set<TestObject> set = doc.as<std::set<TestObject>>();
|
||||
for (auto& test : set) {
|
||||
TRACE("testDeserializeSet: entry: " + test.toString());
|
||||
TRACEF("testDeserializeSet: entry: %s", test.toString().c_str());
|
||||
}
|
||||
|
||||
//JsonArray arr = doc.as<JsonArray>();
|
||||
//for (JsonVariant elem : arr) {
|
||||
// TRACE("testDeserializeSet: entry: " + elem.as<TestObject>().toString());
|
||||
// TRACEF("testDeserializeSet: entry: %s", elem.as<TestObject>().toString().c_str());
|
||||
//}
|
||||
}
|
||||
else {
|
||||
@@ -463,10 +463,10 @@ void testSerializeMap() {
|
||||
if (length < size) {
|
||||
data.resize(length);
|
||||
}
|
||||
TRACE("testSerializeMap: serialized " + std::to_string(length) + " bytes");
|
||||
TRACEF("testSerializeMap: serialized %zu bytes", length);
|
||||
if (length > 0) {
|
||||
if (RNS::Utilities::OS::write_file(test_map_path, data) == data.size()) {
|
||||
TRACE("testSerializeMap: wrote: " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("testSerializeMap: wrote: %zu bytes", data.size());
|
||||
}
|
||||
else {
|
||||
TRACE("testSerializeMap: write failed");
|
||||
@@ -486,8 +486,8 @@ void testDeserializeMap() {
|
||||
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_map_path, data) > 0) {
|
||||
TRACE("testDeserializeMap: read: " + std::to_string(data.size()) + " bytes");
|
||||
//TRACE("testDeserializeMap: data: " + data.toString());
|
||||
TRACEF("testDeserializeMap: read: %zu bytes", data.size());
|
||||
//TRACEF("testDeserializeMap: data: %s", data.toString().c_str());
|
||||
DeserializationError error = deserializeJson(doc, data.data());
|
||||
//DeserializationError error = deserializeMsgPack(doc, data.data());
|
||||
if (!error) {
|
||||
@@ -495,12 +495,12 @@ void testDeserializeMap() {
|
||||
|
||||
std::map<std::string, TestObject> map(doc.as<std::map<std::string, TestObject>>());
|
||||
for (auto& [str, test] : map) {
|
||||
TRACE("testDeserializeMap: entry: " + str + " = " + test.toString());
|
||||
TRACEF("testDeserializeMap: entry: %s = %s", str.c_str(), test.toString().c_str());
|
||||
}
|
||||
|
||||
//JsonObject root = doc.as<JsonObject>();
|
||||
//for (JsonPair kv : root) {
|
||||
// TRACE("testDeserializeMap: entry: " + std::string(kv.key().c_str()) + " = " + kv.value().as<TestObject>().toString());
|
||||
// TRACEF("testDeserializeMap: entry: %s = %s", kv.key().c_str(), kv.value().as<TestObject>().toString().c_str());
|
||||
//}
|
||||
}
|
||||
else {
|
||||
@@ -517,11 +517,11 @@ void testDeserializeMap() {
|
||||
}
|
||||
|
||||
#ifdef ARDUINO
|
||||
const char test_destination_table_path[] = "/test_destination_table";
|
||||
const char test_empty_destination_table_path[] = "/test_empty_destination_table";
|
||||
const char test_path_table_path[] = "/test_path_table";
|
||||
const char test_empty_path_table_path[] = "/test_empty_path_table";
|
||||
#else
|
||||
const char test_destination_table_path[] = "test_destination_table";
|
||||
const char test_empty_destination_table_path[] = "test_empty_destination_table";
|
||||
const char test_path_table_path[] = "test_path_table";
|
||||
const char test_empty_path_table_path[] = "test_empty_path_table";
|
||||
#endif
|
||||
|
||||
void testSerializeDestinationTable() {
|
||||
@@ -542,8 +542,8 @@ void testSerializeDestinationTable() {
|
||||
RNS::Transport::DestinationEntry entry_one;
|
||||
entry_one._timestamp = 1.0;
|
||||
entry_one._received_from = received;
|
||||
entry_one._receiving_interface = test_interface.get_hash();
|
||||
entry_one._random_blobs = blobs;
|
||||
entry_one.receiving_interface_hash(test_interface.get_hash());
|
||||
RNS::Bytes one;
|
||||
one.assignHex("1111111111111111");
|
||||
map.insert({one, entry_one});
|
||||
@@ -551,8 +551,8 @@ void testSerializeDestinationTable() {
|
||||
RNS::Transport::DestinationEntry entry_two;
|
||||
entry_two._timestamp = 2.0;
|
||||
entry_two._received_from = received;
|
||||
entry_two._receiving_interface = test_interface.get_hash();
|
||||
entry_two._random_blobs = blobs;
|
||||
entry_two.receiving_interface_hash(test_interface.get_hash());
|
||||
RNS::Bytes two;
|
||||
two.assignHex("2222222222222222");
|
||||
map.insert({two, entry_two});
|
||||
@@ -561,35 +561,35 @@ void testSerializeDestinationTable() {
|
||||
RNS::Transport::DestinationEntry entry;
|
||||
entry._timestamp = 1.0;
|
||||
entry._received_from = received;
|
||||
entry._receiving_interface = test_interface.get_hash();
|
||||
entry._random_blobs = blobs;
|
||||
entry.receiving_interface_hash(test_interface.get_hash());
|
||||
RNS::Bytes hash;
|
||||
hash.assign(std::to_string(1000000000000001 + n).c_str());
|
||||
map.insert({hash, entry});
|
||||
}
|
||||
|
||||
for (auto& [hash, test] : map) {
|
||||
TRACE("testSerializeDestinationTable: entry: " + hash.toHex() + " = " + test.debugString());
|
||||
TRACEF("testSerializeDestinationTable: entry: %s = %s", hash.toHex().c_str(), test.debugString().c_str());
|
||||
}
|
||||
|
||||
JsonDocument doc;
|
||||
doc.set(map);
|
||||
TRACE("testSerializeDestinationTable: doc size " + std::to_string(doc.size()));
|
||||
TRACEF("testSerializeDestinationTable: doc size %zu", doc.size());
|
||||
|
||||
RNS::Bytes data;
|
||||
size_t size = 32768;
|
||||
//size_t size = BUFFER_SIZE;
|
||||
TRACE("testSerializeDestinationTable: buffer size " + std::to_string(size) + " bytes");
|
||||
TRACEF("testSerializeDestinationTable: buffer size %zu bytes", 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);
|
||||
}
|
||||
TRACE("testSerializeDestinationTable: serialized " + std::to_string(length) + " bytes");
|
||||
TRACEF("testSerializeDestinationTable: serialized %zu bytes", length);
|
||||
if (length > 0) {
|
||||
TRACE("testSerializeDestinationTable: json: " + data.toString());
|
||||
if (RNS::Utilities::OS::write_file(test_destination_table_path, data) == data.size()) {
|
||||
TRACE("testSerializeDestinationTable: wrote: " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("testSerializeDestinationTable: json: %s", data.toString().c_str());
|
||||
if (RNS::Utilities::OS::write_file(test_path_table_path, data) == data.size()) {
|
||||
TRACEF("testSerializeDestinationTable: wrote: %zu bytes", data.size());
|
||||
}
|
||||
else {
|
||||
TRACE("testSerializeDestinationTable: write failed");
|
||||
@@ -606,35 +606,35 @@ void testSerializeDestinationTable() {
|
||||
void testDeserializeDestinationTable() {
|
||||
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_destination_table_path, data) > 0) {
|
||||
TRACE("testDeserializeDestinationTable: read: " + std::to_string(data.size()) + " bytes");
|
||||
TRACE("testDeserializeDestinationTable: json: " + data.toString());
|
||||
if (RNS::Utilities::OS::read_file(test_path_table_path, data) > 0) {
|
||||
TRACEF("testDeserializeDestinationTable: read: %zu bytes", data.size());
|
||||
TRACEF("testDeserializeDestinationTable: json: %s", data.toString().c_str());
|
||||
JsonDocument doc;
|
||||
|
||||
//TRACE("testDeserializeVector: data: " + data.toString());
|
||||
//TRACEF("testDeserializeVector: data: %s", data.toString().c_str());
|
||||
DeserializationError error = deserializeJson(doc, data.data());
|
||||
//DeserializationError error = deserializeMsgPack(doc, data.data());
|
||||
TRACE("testDeserializeDestinationTable: doc size " + std::to_string(doc.size()));
|
||||
TRACEF("testDeserializeDestinationTable: doc size %zu", doc.size());
|
||||
if (!error) {
|
||||
TRACE("testDeserializeDestinationTable: successfully deserialized " + std::to_string(data.size()) + " bytes");
|
||||
//TRACE("testDeserializeDestinationTable: json: " + data.toString());
|
||||
TRACEF("testDeserializeDestinationTable: successfully deserialized %zu bytes", data.size());
|
||||
//TRACEF("testDeserializeDestinationTable: json: %s", data.toString().c_str());
|
||||
|
||||
static std::map<RNS::Bytes, RNS::Transport::DestinationEntry> map(doc.as<std::map<RNS::Bytes, RNS::Transport::DestinationEntry>>());
|
||||
TEST_ASSERT_EQUAL_size_t(22, map.size());
|
||||
for (auto& [hash, test] : map) {
|
||||
TRACE("testDeserializeDestinationTable: entry: " + hash.toHex() + " = " + test.debugString());
|
||||
TRACEF("testDeserializeDestinationTable: entry: %s = %s", hash.toHex().c_str(), test.debugString().c_str());
|
||||
}
|
||||
|
||||
//JsonObject root = doc.as<JsonObject>();
|
||||
//for (JsonPair kv : root) {
|
||||
// TRACE("testDeserializeDestinationTable: entry: " + std::string(kv.key().c_str()) + " = " + kv.value().as<TestObject>().toString());
|
||||
// TRACEF("testDeserializeDestinationTable: entry: %s = %s", kv.key().c_str(), kv.value().as<TestObject>().toString().c_str());
|
||||
//}
|
||||
}
|
||||
else {
|
||||
TRACEF("testDeserializeDestinationTable: failed to deserialize: %s", error.c_str());
|
||||
TEST_FAIL();
|
||||
}
|
||||
//assert(RNS::Utilities::OS::remove_file(test_destination_table_path));
|
||||
//assert(RNS::Utilities::OS::remove_file(test_path_table_path));
|
||||
}
|
||||
else {
|
||||
TRACE("testDeserializeDestinationTable: read failed");
|
||||
@@ -647,37 +647,37 @@ void testDeserializeEmptyDestinationTable() {
|
||||
|
||||
// Write empty JSON destination table
|
||||
RNS::Bytes emptyData("{}");
|
||||
TEST_ASSERT_EQUAL_size_t(2, RNS::Utilities::OS::write_file(test_empty_destination_table_path, emptyData));
|
||||
TEST_ASSERT_EQUAL_size_t(2, RNS::Utilities::OS::write_file(test_empty_path_table_path, emptyData));
|
||||
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_empty_destination_table_path, data) > 0) {
|
||||
TRACE("testDeserializeEmptyDestinationTable: read: " + std::to_string(data.size()) + " bytes");
|
||||
if (RNS::Utilities::OS::read_file(test_empty_path_table_path, data) > 0) {
|
||||
TRACEF("testDeserializeEmptyDestinationTable: read: %zu bytes", data.size());
|
||||
JsonDocument doc;
|
||||
|
||||
//TRACE("testDeserializeVector: data: " + data.toString());
|
||||
//TRACEF("testDeserializeVector: data: %s", data.toString().c_str());
|
||||
DeserializationError error = deserializeJson(doc, data.data());
|
||||
//DeserializationError error = deserializeMsgPack(doc, data.data());
|
||||
TRACE("testDeserializeEmptyDestinationTable: doc size " + std::to_string(doc.size()));
|
||||
TRACEF("testDeserializeEmptyDestinationTable: doc size %zu", doc.size());
|
||||
if (!error) {
|
||||
TRACE("testDeserializeEmptyDestinationTable: successfully deserialized " + std::to_string(data.size()) + " bytes");
|
||||
TRACE("testDeserializeEmptyDestinationTable: json: " + data.toString());
|
||||
TRACEF("testDeserializeEmptyDestinationTable: successfully deserialized %zu bytes", data.size());
|
||||
TRACEF("testDeserializeEmptyDestinationTable: json: %s", data.toString().c_str());
|
||||
|
||||
static std::map<RNS::Bytes, RNS::Transport::DestinationEntry> map(doc.as<std::map<RNS::Bytes, RNS::Transport::DestinationEntry>>());
|
||||
TEST_ASSERT_EQUAL_size_t(0, map.size());
|
||||
for (auto& [hash, test] : map) {
|
||||
TRACE("testDeserializeEmptyDestinationTable: entry: " + hash.toHex() + " = " + test.debugString());
|
||||
TRACEF("testDeserializeEmptyDestinationTable: entry: %s = %s", hash.toHex().c_str(), test.debugString().c_str());
|
||||
}
|
||||
|
||||
//JsonObject root = doc.as<JsonObject>();
|
||||
//for (JsonPair kv : root) {
|
||||
// TRACE("testDeserializeEmptyDestinationTable: entry: " + std::string(kv.key().c_str()) + " = " + kv.value().as<TestObject>().toString());
|
||||
// TRACEF("testDeserializeEmptyDestinationTable: entry: %s = %s", kv.key().c_str(), kv.value().as<TestObject>().toString().c_str());
|
||||
//}
|
||||
}
|
||||
else {
|
||||
TRACE("testDeserializeEmptyDestinationTable: failed to deserialize");
|
||||
TEST_FAIL();
|
||||
}
|
||||
//assert(RNS::Utilities::OS::remove_file(test_empty_destination_table_path));
|
||||
//assert(RNS::Utilities::OS::remove_file(test_empty_path_table_path));
|
||||
}
|
||||
else {
|
||||
TRACE("testDeserializeEmptyDestinationTable: read failed");
|
||||
@@ -715,7 +715,7 @@ void testJsonMsgpackSerializeObject() {
|
||||
|
||||
std::vector<std::string> vec({"one", "two"});
|
||||
TestObject test("test", vec);
|
||||
TRACE("testJsonMsgpackSerializeObject: test: " + test.toString());
|
||||
TRACEF("testJsonMsgpackSerializeObject: test: %s", test.toString().c_str());
|
||||
|
||||
JsonDocument doc;
|
||||
doc.set(test);
|
||||
@@ -726,10 +726,10 @@ void testJsonMsgpackSerializeObject() {
|
||||
if (length < size) {
|
||||
data.resize(length);
|
||||
}
|
||||
TRACE("testJsonMsgpackSerializeObject: serialized " + std::to_string(length) + " bytes");
|
||||
TRACEF("testJsonMsgpackSerializeObject: serialized %zu bytes", length);
|
||||
if (length > 0) {
|
||||
if (RNS::Utilities::OS::write_file(test_object_path, data) == data.size()) {
|
||||
TRACE("testJsonMsgpackSerializeObject: wrote: " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("testJsonMsgpackSerializeObject: wrote: %zu bytes", data.size());
|
||||
}
|
||||
else {
|
||||
TRACE("testJsonMsgpackSerializeObject: write failed");
|
||||
@@ -749,16 +749,16 @@ void testJsonMsgpackDeserializeObject() {
|
||||
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_object_path, data) > 0) {
|
||||
TRACE("testJsonMsgpackDeserializeObject: read: " + std::to_string(data.size()) + " bytes");
|
||||
//TRACE("data: " + data.toString());
|
||||
TRACEF("testJsonMsgpackDeserializeObject: read: %zu bytes", data.size());
|
||||
//TRACEF("data: %s", data.toString().c_str());
|
||||
DeserializationError error = deserializeMsgPack(doc, data.data());
|
||||
if (!error) {
|
||||
//JsonObject root = doc.as<JsonObject>();
|
||||
//for (JsonPair kv : root) {
|
||||
// TRACE("key: " + std::string(kv.key().c_str()) + " value: " + kv.value().as<const char*>());
|
||||
// TRACEF("key: %s value: %s", kv.key().c_str(), kv.value().as<const char*>());
|
||||
//}
|
||||
TestObject test = doc.as<TestObject>();
|
||||
TRACE("testJsonMsgpackDeserializeObject: test: " + test.toString());
|
||||
TRACEF("testJsonMsgpackDeserializeObject: test: %s", test.toString().c_str());
|
||||
}
|
||||
else {
|
||||
TRACE("testJsonMsgpackDeserializeObject: failed to deserialize");
|
||||
@@ -809,10 +809,10 @@ void testJsonMsgpackSerializeArray() {
|
||||
if (length < size) {
|
||||
data.resize(length);
|
||||
}
|
||||
TRACE("testJsonMsgpackSerializeArray: serialized " + std::to_string(length) + " bytes");
|
||||
TRACEF("testJsonMsgpackSerializeArray: serialized %zu bytes", length);
|
||||
if (length > 0) {
|
||||
if (RNS::Utilities::OS::write_file(test_array_path, data) == data.size()) {
|
||||
TRACE("testJsonMsgpackSerializeArray: wrote: " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("testJsonMsgpackSerializeArray: wrote: %zu bytes", data.size());
|
||||
}
|
||||
else {
|
||||
TRACE("testJsonMsgpackSerializeArray: write failed");
|
||||
@@ -832,8 +832,8 @@ void testJsonMsgpackDeserializeArray() {
|
||||
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_array_path, data) > 0) {
|
||||
TRACE("testJsonMsgpackDeserializeArray: read: " + std::to_string(data.size()) + " bytes");
|
||||
//TRACE("data: " + data.toString());
|
||||
TRACEF("testJsonMsgpackDeserializeArray: read: %zu bytes", data.size());
|
||||
//TRACEF("data: %s", data.toString().c_str());
|
||||
DeserializationError error = deserializeMsgPack(doc, data.data(), data.size());
|
||||
if (!error) {
|
||||
JsonArray array = doc.as<JsonArray>();
|
||||
@@ -869,7 +869,7 @@ void testMsgpackSerializeObject() {
|
||||
|
||||
std::vector<std::string> vec({"one", "two"});
|
||||
TestObject test("test", vec);
|
||||
TRACE("testMsgpackSerializeObject: test: " + test.toString());
|
||||
TRACEF("testMsgpackSerializeObject: test: %s", test.toString().c_str());
|
||||
|
||||
JsonDocument doc;
|
||||
|
||||
@@ -879,10 +879,10 @@ void testMsgpackSerializeObject() {
|
||||
if (length < size) {
|
||||
data.resize(length);
|
||||
}
|
||||
TRACE("testMsgpackSerializeObject: serialized " + std::to_string(length) + " bytes");
|
||||
TRACEF("testMsgpackSerializeObject: serialized %zu bytes", length);
|
||||
if (length > 0) {
|
||||
if (RNS::Utilities::OS::write_file(test_object_path, data) == data.size()) {
|
||||
TRACE("testMsgpackSerializeObject: wrote: " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("testMsgpackSerializeObject: wrote: %zu bytes", data.size());
|
||||
}
|
||||
else {
|
||||
TRACE("testMsgpackSerializeObject: write failed");
|
||||
@@ -902,16 +902,16 @@ void testMsgpackDeserializeObject() {
|
||||
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_object_path, data) > 0) {
|
||||
TRACE("testMsgpackDeserializeObject: read: " + std::to_string(data.size()) + " bytes");
|
||||
//TRACE("data: " + data.toString());
|
||||
TRACEF("testMsgpackDeserializeObject: read: %zu bytes", data.size());
|
||||
//TRACEF("data: %s", data.toString().c_str());
|
||||
DeserializationError error = deserializeMsgPack(doc, data.data());
|
||||
if (!error) {
|
||||
//JsonObject root = doc.as<JsonObject>();
|
||||
//for (JsonPair kv : root) {
|
||||
// TRACE("key: " + std::string(kv.key().c_str()) + " value: " + kv.value().as<const char*>());
|
||||
// TRACEF("key: %s value: %s", kv.key().c_str(), kv.value().as<const char*>());
|
||||
//}
|
||||
TestObject test = doc.as<TestObject>();
|
||||
TRACE("testMsgpackDeserializeObject: test: " + test.toString());
|
||||
TRACEF("testMsgpackDeserializeObject: test: %s", test.toString().c_str());
|
||||
}
|
||||
else {
|
||||
TRACE("testMsgpackDeserializeObject: failed to deserialize");
|
||||
@@ -951,10 +951,10 @@ void testMsgpackSerializeArray() {
|
||||
//packer.to_array(time, one.collection(), two.collection());
|
||||
RNS::Bytes data(packer.data(), packer.size());
|
||||
|
||||
TRACE("testMsgpackSerializeArray: serialized " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("testMsgpackSerializeArray: serialized %zu bytes", data.size());
|
||||
if (packer.size() > 0) {
|
||||
if (RNS::Utilities::OS::write_file(test_array_path, data) == data.size()) {
|
||||
TRACE("testMsgpackSerializeArray: wrote: " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("testMsgpackSerializeArray: wrote: %zu bytes", data.size());
|
||||
}
|
||||
else {
|
||||
TRACE("testMsgpackSerializeArray: write failed");
|
||||
@@ -974,8 +974,8 @@ void testMsgpackDeserializeArray() {
|
||||
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_array_path, data) > 0) {
|
||||
TRACE("testMsgpackDeserializeArray: read: " + std::to_string(data.size()) + " bytes");
|
||||
//TRACE("data: " + data.toString());
|
||||
TRACEF("testMsgpackDeserializeArray: read: %zu bytes", data.size());
|
||||
//TRACEF("data: %s", data.toString().c_str());
|
||||
MsgPack::Unpacker unpacker;
|
||||
unpacker.feed(data.data(), data.size());
|
||||
double time;
|
||||
@@ -1018,10 +1018,10 @@ void testMsgpackSerializeSeries() {
|
||||
//packer.serialize(time, one.collection(), two.collection());
|
||||
RNS::Bytes data(packer.data(), packer.size());
|
||||
|
||||
TRACE("testMsgpackSerializeSeries: serialized " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("testMsgpackSerializeSeries: serialized %zu bytes", data.size());
|
||||
if (packer.size() > 0) {
|
||||
if (RNS::Utilities::OS::write_file(test_series_path, data) == data.size()) {
|
||||
TRACE("testMsgpackSerializeSeries: wrote: " + std::to_string(data.size()) + " bytes");
|
||||
TRACEF("testMsgpackSerializeSeries: wrote: %zu bytes", data.size());
|
||||
}
|
||||
else {
|
||||
TRACE("testMsgpackSerializeSeries: write failed");
|
||||
@@ -1041,8 +1041,8 @@ void testMsgpackDeserializeSeries() {
|
||||
|
||||
RNS::Bytes data;
|
||||
if (RNS::Utilities::OS::read_file(test_series_path, data) > 0) {
|
||||
TRACE("testMsgpackDeserializeSeries: read: " + std::to_string(data.size()) + " bytes");
|
||||
//TRACE("data: " + data.toString());
|
||||
TRACEF("testMsgpackDeserializeSeries: read: %zu bytes", data.size());
|
||||
//TRACEF("data: %s", data.toString().c_str());
|
||||
MsgPack::Unpacker unpacker;
|
||||
unpacker.feed(data.data(), data.size());
|
||||
double time;
|
||||
@@ -1124,8 +1124,8 @@ int runUnityTests(void) {
|
||||
RNS::Utilities::OS::remove_file(test_map_path);
|
||||
RNS::Utilities::OS::remove_file(test_vector_path);
|
||||
RNS::Utilities::OS::remove_file(test_set_path);
|
||||
RNS::Utilities::OS::remove_file(test_destination_table_path);
|
||||
RNS::Utilities::OS::remove_file(test_empty_destination_table_path);
|
||||
RNS::Utilities::OS::remove_file(test_path_table_path);
|
||||
RNS::Utilities::OS::remove_file(test_empty_path_table_path);
|
||||
RNS::Utilities::OS::remove_file(test_array_path);
|
||||
RNS::Utilities::OS::remove_file(test_series_path);
|
||||
RNS::Utilities::OS::deregister_filesystem();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
#include "Reticulum.h"
|
||||
#include "Bytes.h"
|
||||
|
||||
void testReference() {
|
||||
void test_reticulum_reference() {
|
||||
HEAD("Running testReference...", RNS::LOG_TRACE);
|
||||
|
||||
RNS::Reticulum reticulum_default;
|
||||
@@ -26,7 +26,7 @@ void testReference() {
|
||||
interfaces.insert(testinterface);
|
||||
for (auto iter = interfaces.begin(); iter != interfaces.end(); ++iter) {
|
||||
RNS::Interface& interface = (*iter);
|
||||
TRACE("Found interface: " + interface.toString());
|
||||
TRACEF("Found interface: %s", interface.toString().c_str());
|
||||
RNS::Bytes data;
|
||||
const_cast<RNS::Interface&>(interface).on_outgoing(data);
|
||||
}
|
||||
@@ -39,7 +39,7 @@ void testReference() {
|
||||
std::set<std::reference_wrapper<RNS::Interface>, std::less<RNS::Interface>> interfaces;
|
||||
interfaces.insert(testinterface);
|
||||
for (auto& interface : interfaces) {
|
||||
TRACE("Found interface: " + interface.toString());
|
||||
TRACEF("Found interface: %s", interface.toString().c_str());
|
||||
RNS::Bytes data;
|
||||
const_cast<RNS::Interface&>(interface).on_outgoing(data);
|
||||
}
|
||||
@@ -53,7 +53,7 @@ void testReference() {
|
||||
interfaces.push_back(testinterface);
|
||||
for (auto iter = interfaces.begin(); iter != interfaces.end(); ++iter) {
|
||||
RNS::Interface& interface = (*iter);
|
||||
TRACE("Found interface: " + interface.toString());
|
||||
TRACEF("Found interface: %s", interface.toString().c_str());
|
||||
RNS::Bytes data;
|
||||
const_cast<RNS::Interface&>(interface).on_outgoing(data);
|
||||
}
|
||||
@@ -67,7 +67,7 @@ void testReference() {
|
||||
interfaces.push_back(testinterface);
|
||||
//for (auto& interface : interfaces) {
|
||||
for (RNS::Interface& interface : interfaces) {
|
||||
TRACE("Found interface: " + interface.toString());
|
||||
TRACEF("Found interface: %s", interface.toString().c_str());
|
||||
RNS::Bytes data;
|
||||
const_cast<RNS::Interface&>(interface).on_outgoing(data);
|
||||
}
|
||||
@@ -81,14 +81,14 @@ void testReference() {
|
||||
interfaces.push_back(testinterface);
|
||||
for (auto iter = interfaces.begin(); iter != interfaces.end(); ++iter) {
|
||||
RNS::Interface& interface = (*iter);
|
||||
TRACE("1 Found interface: " + interface.toString());
|
||||
TRACEF("1 Found interface: %s", interface.toString().c_str());
|
||||
RNS::Bytes data;
|
||||
const_cast<RNS::Interface&>(interface).on_outgoing(data);
|
||||
}
|
||||
}
|
||||
for (auto iter = interfaces.begin(); iter != interfaces.end(); ++iter) {
|
||||
RNS::Interface& interface = (*iter);
|
||||
TRACE("2 Found interface: " + interface.toString());
|
||||
TRACEF("2 Found interface: %s", interface.toString().c_str());
|
||||
RNS::Bytes data;
|
||||
const_cast<RNS::Interface&>(interface).on_outgoing(data);
|
||||
}
|
||||
@@ -101,13 +101,13 @@ void testReference() {
|
||||
destinations.insert({destination.hash(), destination});
|
||||
//for (RNS::Destination& destination : destinations) {
|
||||
for (auto& [hash, destination] : destinations) {
|
||||
TRACE("Iterated destination: " + destination.toString());
|
||||
TRACEF("Iterated destination: %s", destination.toString().c_str());
|
||||
}
|
||||
RNS::Bytes hash = destination.hash();
|
||||
auto iter = destinations.find(hash);
|
||||
if (iter != destinations.end()) {
|
||||
RNS::Destination& destination = (*iter).second;
|
||||
TRACE("Found destination: " + destination.toString());
|
||||
TRACEF("Found destination: %s", destination.toString().c_str());
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -115,6 +115,14 @@ void testReference() {
|
||||
|
||||
}
|
||||
|
||||
void test_destination_entry_reference() {
|
||||
HEAD("Running testReference...", RNS::LOG_TRACE);
|
||||
|
||||
RNS::Transport::DestinationEntry destination_entry;
|
||||
TEST_ASSERT_FALSE(destination_entry);
|
||||
|
||||
}
|
||||
|
||||
|
||||
void setUp(void) {
|
||||
// set stuff up here before each test
|
||||
@@ -126,7 +134,8 @@ void tearDown(void) {
|
||||
|
||||
int runUnityTests(void) {
|
||||
UNITY_BEGIN();
|
||||
RUN_TEST(testReference);
|
||||
RUN_TEST(test_reticulum_reference);
|
||||
RUN_TEST(test_destination_entry_reference);
|
||||
return UNITY_END();
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ public:
|
||||
_name = "(deleted)";
|
||||
}
|
||||
virtual void send_outgoing(const RNS::Bytes &data) {
|
||||
HEAD("OutInterface.send_outgoing: data: " + data.toHex(), RNS::LOG_TRACE);
|
||||
HEADF(RNS::LOG_TRACE, "OutInterface.send_outgoing: data: %s", data.toHex().c_str());
|
||||
|
||||
// Loop data back to InInterface for testing
|
||||
// NOTE: This sends the incoming data directory to RNS::Interface (which relays to Transport)
|
||||
@@ -57,13 +57,13 @@ public:
|
||||
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());
|
||||
INFOF("ExampleAnnounceHandler: destination hash: %s", destination_hash.toHex().c_str());
|
||||
if (announced_identity) {
|
||||
INFO("ExampleAnnounceHandler: announced identity hash: " + announced_identity.hash().toHex());
|
||||
INFO("ExampleAnnounceHandler: announced identity app data: " + announced_identity.app_data().toHex());
|
||||
INFOF("ExampleAnnounceHandler: announced identity hash: %s", announced_identity.hash().toHex().c_str());
|
||||
INFOF("ExampleAnnounceHandler: announced identity app data: %s", announced_identity.app_data().toHex().c_str());
|
||||
}
|
||||
if (app_data) {
|
||||
INFO("ExampleAnnounceHandler: app data text: \"" + app_data.toString() + "\"");
|
||||
INFOF("ExampleAnnounceHandler: app data text: \"%s\"", app_data.toString().c_str());
|
||||
}
|
||||
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
|
||||
}
|
||||
@@ -77,9 +77,9 @@ RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler());
|
||||
//void(*)(const Bytes& data, const Packet& packet)
|
||||
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());
|
||||
INFOF("onPacket: data: %s", data.toHex().c_str());
|
||||
INFOF("onPacket: text: \"%s\"", data.toString().c_str());
|
||||
//TRACEF("onPacket: %s", packet.debugString().c_str());
|
||||
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
|
||||
}
|
||||
|
||||
@@ -87,9 +87,9 @@ void onPacket(const RNS::Bytes& data, const RNS::Packet& packet) {
|
||||
//void(*)(const Bytes& data, const Packet& packet)
|
||||
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());
|
||||
INFOF("onPingPacket: data: %s", data.toHex().c_str());
|
||||
INFOF("onPingPacket: text: \"%s\"", data.toString().c_str());
|
||||
//TRACEF("onPingPacket: %s", packet.debugString().c_str());
|
||||
INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
|
||||
}
|
||||
|
||||
|
||||
@@ -23,12 +23,12 @@ public:
|
||||
|
||||
private:
|
||||
virtual void send_outgoing(const RNS::Bytes& data) {
|
||||
DEBUG("TestInterface.send_outgoing: data: " + data.toHex());
|
||||
DEBUGF("TestInterface.send_outgoing: data: %s", data.toHex().c_str());
|
||||
// Perform post-send housekeeping
|
||||
InterfaceImpl::handle_outgoing(data);
|
||||
}
|
||||
void on_incoming(const RNS::Bytes& data) {
|
||||
DEBUG("TestInterface.on_incoming: data: " + data.toHex());
|
||||
DEBUGF("TestInterface.on_incoming: data: %s", data.toHex().c_str());
|
||||
// Pass received data on to transport
|
||||
InterfaceImpl::handle_incoming(data);
|
||||
}
|
||||
@@ -36,11 +36,11 @@ private:
|
||||
};
|
||||
|
||||
#ifdef ARDUINO
|
||||
const char test_destination_table_path[] = "/test_destination_table";
|
||||
const char test_empty_destination_table_path[] = "/test_empty_destination_table";
|
||||
const char test_path_table_path[] = "/test_path_table";
|
||||
const char test_empty_path_table_path[] = "/test_empty_path_table";
|
||||
#else
|
||||
const char test_destination_table_path[] = "test_destination_table";
|
||||
const char test_empty_destination_table_path[] = "test_empty_destination_table";
|
||||
const char test_path_table_path[] = "test_path_table";
|
||||
const char test_empty_path_table_path[] = "test_empty_path_table";
|
||||
#endif
|
||||
|
||||
void testSerializeDestinationTable() {
|
||||
@@ -62,7 +62,7 @@ void testSerializeDestinationTable() {
|
||||
RNS::Transport::DestinationEntry entry_one;
|
||||
entry_one._timestamp = 1.0;
|
||||
entry_one._received_from = received;
|
||||
entry_one._receiving_interface = test_interface.get_hash();
|
||||
entry_one.receiving_interface_hash(test_interface.get_hash());
|
||||
entry_one._random_blobs = blobs;
|
||||
RNS::Bytes one;
|
||||
one.assignHex("1111111111111111");
|
||||
@@ -71,7 +71,7 @@ void testSerializeDestinationTable() {
|
||||
RNS::Transport::DestinationEntry entry_two;
|
||||
entry_two._timestamp = 2.0;
|
||||
entry_two._received_from = received;
|
||||
entry_two._receiving_interface = test_interface.get_hash();
|
||||
entry_two.receiving_interface_hash(test_interface.get_hash());
|
||||
entry_two._random_blobs = blobs;
|
||||
RNS::Bytes two;
|
||||
two.assignHex("2222222222222222");
|
||||
@@ -81,7 +81,7 @@ void testSerializeDestinationTable() {
|
||||
RNS::Transport::DestinationEntry entry;
|
||||
entry._timestamp = 1.0;
|
||||
entry._received_from = received;
|
||||
entry._receiving_interface = test_interface.get_hash();
|
||||
entry.receiving_interface_hash(test_interface.get_hash());
|
||||
entry._random_blobs = blobs;
|
||||
RNS::Bytes hash;
|
||||
hash.assign(std::to_string(1000000000000001 + n).c_str());
|
||||
@@ -95,7 +95,7 @@ void testSerializeDestinationTable() {
|
||||
}
|
||||
|
||||
uint32_t stream_crc;
|
||||
size_t wrote = RNS::Persistence::serialize(map, test_destination_table_path, stream_crc);
|
||||
size_t wrote = RNS::Persistence::serialize(map, test_path_table_path, stream_crc);
|
||||
TRACEF("testSerializeDestinationTable: wrote: %d bytes", wrote);
|
||||
if (wrote == 0) {
|
||||
TRACE("testSerializeDestinationTable: write failed");
|
||||
@@ -115,7 +115,7 @@ void testDeserializeDestinationTable() {
|
||||
|
||||
std::map<RNS::Bytes, RNS::Transport::DestinationEntry> map;
|
||||
uint32_t stream_crc;
|
||||
size_t read = RNS::Persistence::deserialize(map, test_destination_table_path, stream_crc);
|
||||
size_t read = RNS::Persistence::deserialize(map, test_path_table_path, stream_crc);
|
||||
TRACEF("testDeserializeDestinationTable: deserialized %d bytes", read);
|
||||
if (read == 0) {
|
||||
TRACE("testDeserializeDestinationTable: failed to deserialize");
|
||||
@@ -140,10 +140,10 @@ void testDeserializeEmptyDestinationTable() {
|
||||
|
||||
// Write empty JSON destination table
|
||||
RNS::Bytes emptyData("{}");
|
||||
TEST_ASSERT_EQUAL_size_t(2, RNS::Utilities::OS::write_file(test_empty_destination_table_path, emptyData));
|
||||
TEST_ASSERT_EQUAL_size_t(2, RNS::Utilities::OS::write_file(test_empty_path_table_path, emptyData));
|
||||
|
||||
std::map<RNS::Bytes, RNS::Transport::DestinationEntry> destination_table;
|
||||
RNS::Persistence::deserialize(destination_table, test_empty_destination_table_path);
|
||||
RNS::Persistence::deserialize(destination_table, test_empty_path_table_path);
|
||||
TEST_ASSERT_EQUAL_size_t(0, destination_table.size());
|
||||
}
|
||||
|
||||
@@ -170,8 +170,8 @@ int runUnityTests(void) {
|
||||
RUN_TEST(testDeserializeEmptyDestinationTable);
|
||||
|
||||
// Suite-level teardown
|
||||
RNS::Utilities::OS::remove_file(test_destination_table_path);
|
||||
RNS::Utilities::OS::remove_file(test_empty_destination_table_path);
|
||||
RNS::Utilities::OS::remove_file(test_path_table_path);
|
||||
RNS::Utilities::OS::remove_file(test_empty_path_table_path);
|
||||
RNS::Utilities::OS::deregister_filesystem();
|
||||
|
||||
return UNITY_END();
|
||||
|
||||
@@ -0,0 +1,625 @@
|
||||
#include <unity.h>
|
||||
|
||||
#include "../common/filesystem/FileSystem.h"
|
||||
|
||||
#include <Reticulum.h>
|
||||
#include <Transport.h>
|
||||
#include <Identity.h>
|
||||
#include <Destination.h>
|
||||
#include <Packet.h>
|
||||
#include <Log.h>
|
||||
#include <Bytes.h>
|
||||
#include <Utilities/OS.h>
|
||||
|
||||
// ============================================================================
|
||||
// Test infrastructure - loopback interfaces
|
||||
// ============================================================================
|
||||
|
||||
static int packets_received = 0;
|
||||
|
||||
class InInterface : public RNS::InterfaceImpl {
|
||||
public:
|
||||
InInterface(const char *name = "InInterface") : RNS::InterfaceImpl(name) {
|
||||
_OUT = false;
|
||||
_IN = true;
|
||||
}
|
||||
virtual ~InInterface() { _name = "(deleted)"; }
|
||||
virtual void send_outgoing(const RNS::Bytes &data) {}
|
||||
virtual void handle_incoming(const RNS::Bytes &data) {
|
||||
try {
|
||||
InterfaceImpl::handle_incoming(data);
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERROR("handle_incoming: bad_alloc - OUT OF MEMORY");
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("handle_incoming: exception: %s", e.what());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class OutInterface : public RNS::InterfaceImpl {
|
||||
public:
|
||||
OutInterface(RNS::Interface& in_interface, const char *name = "OutInterface")
|
||||
: RNS::InterfaceImpl(name), _in_interface(in_interface) {
|
||||
_OUT = true;
|
||||
_IN = false;
|
||||
}
|
||||
virtual ~OutInterface() { _name = "(deleted)"; }
|
||||
virtual void send_outgoing(const RNS::Bytes &data) {
|
||||
_in_interface.handle_incoming(data);
|
||||
try {
|
||||
InterfaceImpl::handle_outgoing(data);
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERROR("handle_outgoing: bad_alloc - OUT OF MEMORY");
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("handle_outgoing: exception: %s", e.what());
|
||||
}
|
||||
}
|
||||
private:
|
||||
RNS::Interface& _in_interface;
|
||||
};
|
||||
|
||||
// Global test state
|
||||
RNS::Reticulum test_reticulum({RNS::Type::NONE});
|
||||
RNS::Identity test_identity({RNS::Type::NONE});
|
||||
RNS::Destination test_dest({RNS::Type::NONE});
|
||||
RNS::Interface in_interface(new InInterface());
|
||||
RNS::Interface out_interface(new OutInterface(in_interface));
|
||||
|
||||
void onTestPacket(const RNS::Bytes& data, const RNS::Packet& packet) {
|
||||
packets_received++;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Setup: Initialize Reticulum with loopback interfaces
|
||||
// ============================================================================
|
||||
|
||||
bool rns_initialized = false;
|
||||
|
||||
void initRNS() {
|
||||
if (rns_initialized) return;
|
||||
|
||||
#if defined(RNS_MEM_LOG)
|
||||
RNS::loglevel(RNS::LOG_MEM);
|
||||
#else
|
||||
RNS::loglevel(RNS::LOG_TRACE);
|
||||
#endif
|
||||
|
||||
try {
|
||||
// Set sane memory limits based on hardware-specific availability
|
||||
RNS::Transport::path_table_maxsize(50);
|
||||
RNS::Transport::announce_table_maxsize(50);
|
||||
RNS::Transport::hashlist_maxsize(50);
|
||||
RNS::Transport::max_pr_tags(32);
|
||||
RNS::Identity::known_destinations_maxsize(50);
|
||||
|
||||
RNS::FileSystem reticulum_filesystem = new FileSystem();
|
||||
((FileSystem*)reticulum_filesystem.get())->init();
|
||||
RNS::Utilities::OS::register_filesystem(reticulum_filesystem);
|
||||
|
||||
RNS::Transport::register_interface(in_interface);
|
||||
RNS::Transport::register_interface(out_interface);
|
||||
|
||||
RNS::Transport::dump_stats();
|
||||
|
||||
// Transport identity
|
||||
RNS::Bytes transport_prv;
|
||||
transport_prv.assignHex("BABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABEBABE");
|
||||
RNS::Identity transport_identity(false);
|
||||
transport_identity.load_private_key(transport_prv);
|
||||
RNS::Transport::identity(transport_identity);
|
||||
|
||||
test_reticulum = RNS::Reticulum();
|
||||
test_reticulum.transport_enabled(true);
|
||||
test_reticulum.start();
|
||||
|
||||
// Single identity and destination (same pattern as test_rns_loopback)
|
||||
test_identity = RNS::Identity(false);
|
||||
RNS::Bytes prv;
|
||||
prv.assignHex("E0D43398EDC974EBA9F4A83463691A08F4D306D4E56BA6B275B8690A2FBD9852E9EBE7C03BC45CAEC9EF8E78C830037210BFB9986F6CA2DEE2B5C28D7B4DE6B0");
|
||||
test_identity.load_private_key(prv);
|
||||
|
||||
test_dest = RNS::Destination(test_identity, RNS::Type::Destination::IN,
|
||||
RNS::Type::Destination::SINGLE, "test", "transport");
|
||||
test_dest.set_packet_callback(onTestPacket);
|
||||
test_dest.set_proof_strategy(RNS::Type::Destination::PROVE_ALL);
|
||||
|
||||
rns_initialized = true;
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERROR("initRNS: bad_alloc - OUT OF MEMORY");
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("initRNS: exception: %s", e.what());
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Transport receipt lifecycle tests
|
||||
// ============================================================================
|
||||
|
||||
void test_receipt_creation_and_culling() {
|
||||
// Send packets and verify the send path + receipt creation + culling doesn't crash.
|
||||
// Note: loopback only delivers announces, not data packets, so we test
|
||||
// the outbound path, receipt creation, and jobs() culling cycle.
|
||||
initRNS();
|
||||
|
||||
const int NUM_PACKETS = 10;
|
||||
for (int i = 0; i < NUM_PACKETS; i++) {
|
||||
RNS::Bytes payload("Test packet " + std::to_string(i));
|
||||
RNS::Packet packet(test_dest, payload);
|
||||
packet.send();
|
||||
}
|
||||
|
||||
// Run Transport jobs to process receipts (check interval = 1.0s)
|
||||
RNS::Utilities::OS::sleep(1.5);
|
||||
test_reticulum.loop();
|
||||
|
||||
// Run again to trigger receipt timeout and culling
|
||||
RNS::Utilities::OS::sleep(1.5);
|
||||
test_reticulum.loop();
|
||||
|
||||
TEST_ASSERT_TRUE_MESSAGE(true, "Receipt creation and culling did not crash");
|
||||
}
|
||||
|
||||
void test_receipt_rapid_fire() {
|
||||
// Simulate Maps-like behavior: send many packets in rapid succession.
|
||||
// This stresses Transport::outbound(), receipt list growth, and
|
||||
// the jobs() culling path.
|
||||
initRNS();
|
||||
|
||||
const int NUM_PACKETS = 50;
|
||||
for (int i = 0; i < NUM_PACKETS; i++) {
|
||||
std::string msg = "Tile request z=10 x=" + std::to_string(i) + " y=42";
|
||||
RNS::Bytes payload(msg.c_str());
|
||||
RNS::Packet packet(test_dest, payload);
|
||||
packet.send();
|
||||
}
|
||||
|
||||
// Run multiple job cycles to process and cull all receipts
|
||||
for (int cycle = 0; cycle < 5; cycle++) {
|
||||
RNS::Utilities::OS::sleep(1.5);
|
||||
test_reticulum.loop();
|
||||
}
|
||||
|
||||
TEST_ASSERT_TRUE_MESSAGE(true, "Rapid-fire send did not crash");
|
||||
}
|
||||
|
||||
void test_receipt_timeout_callback() {
|
||||
// Test that receipt timeout callbacks fire correctly
|
||||
initRNS();
|
||||
|
||||
static bool timeout_called = false;
|
||||
static bool delivery_called = false;
|
||||
|
||||
// Create a destination that we can't actually reach (no loopback for this one)
|
||||
RNS::Identity remote_id(true); // Random identity
|
||||
RNS::Destination unreachable_dest(remote_id, RNS::Type::Destination::OUT,
|
||||
RNS::Type::Destination::SINGLE, "test", "unreachable");
|
||||
|
||||
RNS::Bytes payload("This should timeout");
|
||||
RNS::Packet packet(unreachable_dest, payload);
|
||||
packet.send();
|
||||
RNS::PacketReceipt receipt = packet.receipt();
|
||||
receipt.set_timeout(1); // 1 second timeout
|
||||
receipt.set_timeout_callback([](const RNS::PacketReceipt& r) {
|
||||
timeout_called = true;
|
||||
});
|
||||
receipt.set_delivery_callback([](const RNS::PacketReceipt& r) {
|
||||
delivery_called = true;
|
||||
});
|
||||
|
||||
// Wait for timeout
|
||||
for (int i = 0; i < 5; i++) {
|
||||
RNS::Utilities::OS::sleep(0.5);
|
||||
test_reticulum.loop();
|
||||
}
|
||||
|
||||
TEST_ASSERT_TRUE_MESSAGE(timeout_called, "Timeout callback should have fired");
|
||||
TEST_ASSERT_FALSE_MESSAGE(delivery_called, "Delivery callback should NOT have fired");
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Transport hashlist tests
|
||||
// ============================================================================
|
||||
|
||||
void test_hashlist_basic() {
|
||||
// Send enough packets that the hashlist should grow
|
||||
initRNS();
|
||||
|
||||
const int NUM_PACKETS = 30;
|
||||
for (int i = 0; i < NUM_PACKETS; i++) {
|
||||
RNS::Bytes payload("Hash test " + std::to_string(i));
|
||||
RNS::Packet packet(test_dest, payload);
|
||||
packet.send();
|
||||
}
|
||||
|
||||
// Run jobs to process and potentially cull hashlist
|
||||
test_reticulum.loop();
|
||||
|
||||
TEST_ASSERT_TRUE_MESSAGE(true, "Hashlist operations did not crash");
|
||||
}
|
||||
|
||||
void test_hashlist_overflow() {
|
||||
// Send more packets than _hashlist_maxsize (100) to trigger culling
|
||||
initRNS();
|
||||
|
||||
const int NUM_PACKETS = 150; // > maxsize of 100
|
||||
for (int i = 0; i < NUM_PACKETS; i++) {
|
||||
RNS::Bytes payload("Overflow " + std::to_string(i) + " padding to make unique");
|
||||
RNS::Packet packet(test_dest, payload);
|
||||
packet.send();
|
||||
|
||||
// Periodically run jobs to trigger culling mid-stream
|
||||
if (i % 25 == 0) {
|
||||
test_reticulum.loop();
|
||||
}
|
||||
}
|
||||
|
||||
// Final jobs run
|
||||
test_reticulum.loop();
|
||||
RNS::Utilities::OS::sleep(1.5);
|
||||
test_reticulum.loop();
|
||||
|
||||
TEST_ASSERT_TRUE_MESSAGE(true, "Hashlist overflow and culling did not crash");
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Packet send/receive cycle stress test
|
||||
// ============================================================================
|
||||
|
||||
void test_send_receive_cycle() {
|
||||
// Single packet send through outbound path, then jobs cycle
|
||||
initRNS();
|
||||
|
||||
RNS::Bytes payload("Cycle test payload");
|
||||
RNS::Packet packet(test_dest, payload);
|
||||
packet.send();
|
||||
|
||||
test_reticulum.loop();
|
||||
RNS::Utilities::OS::sleep(1.5);
|
||||
test_reticulum.loop();
|
||||
|
||||
TEST_ASSERT_TRUE_MESSAGE(true, "Send/jobs cycle did not crash");
|
||||
}
|
||||
|
||||
void test_send_receive_stress() {
|
||||
// Stress test: 100 packets with periodic jobs() processing.
|
||||
// Tests that outbound + hashlist + receipt list handles volume.
|
||||
initRNS();
|
||||
|
||||
const int NUM_CYCLES = 100;
|
||||
for (int i = 0; i < NUM_CYCLES; i++) {
|
||||
std::string msg = "Stress " + std::to_string(i);
|
||||
RNS::Bytes payload(msg.c_str());
|
||||
RNS::Packet packet(test_dest, payload);
|
||||
packet.send();
|
||||
|
||||
// Run jobs every 10 packets
|
||||
if (i % 10 == 0) {
|
||||
test_reticulum.loop();
|
||||
}
|
||||
}
|
||||
|
||||
// Final processing - let receipts timeout and get culled
|
||||
for (int i = 0; i < 3; i++) {
|
||||
RNS::Utilities::OS::sleep(1.5);
|
||||
test_reticulum.loop();
|
||||
}
|
||||
|
||||
printf("[TEST] Sent %d packets without crash\n", NUM_CYCLES);
|
||||
TEST_ASSERT_TRUE_MESSAGE(true, "Stress test did not crash");
|
||||
}
|
||||
|
||||
void test_interleaved_send_and_jobs() {
|
||||
// Interleave packet sends with Transport::jobs() to stress the
|
||||
// _jobs_locked/_jobs_running coordination and receipt processing
|
||||
initRNS();
|
||||
|
||||
for (int round = 0; round < 20; round++) {
|
||||
// Send a burst of 5 packets
|
||||
for (int i = 0; i < 5; i++) {
|
||||
std::string msg = "Burst " + std::to_string(round) + "." + std::to_string(i);
|
||||
RNS::Bytes payload(msg.c_str());
|
||||
RNS::Packet packet(test_dest, payload);
|
||||
packet.send();
|
||||
}
|
||||
|
||||
// Immediately run jobs (tests state after outbound batch)
|
||||
test_reticulum.loop();
|
||||
}
|
||||
|
||||
// Let receipts settle and get culled
|
||||
for (int i = 0; i < 3; i++) {
|
||||
RNS::Utilities::OS::sleep(1.5);
|
||||
test_reticulum.loop();
|
||||
}
|
||||
|
||||
printf("[TEST] Burst test: 20 rounds x 5 packets completed\n");
|
||||
TEST_ASSERT_TRUE_MESSAGE(true, "Interleaved send/jobs did not crash");
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Identity/Destination lifecycle tests
|
||||
// ============================================================================
|
||||
|
||||
void test_identity_create_destroy_cycle() {
|
||||
// Rapidly create and destroy identities to stress crypto allocation
|
||||
for (int i = 0; i < 20; i++) {
|
||||
RNS::Identity id(true); // Generate new keypair
|
||||
TEST_ASSERT_TRUE(id);
|
||||
RNS::Bytes hash = id.hash();
|
||||
TEST_ASSERT_TRUE(hash.size() > 0);
|
||||
std::string hex = hash.toHex();
|
||||
TEST_ASSERT_TRUE(hex.length() > 0);
|
||||
}
|
||||
TEST_ASSERT_TRUE_MESSAGE(true, "Identity create/destroy cycle did not crash");
|
||||
}
|
||||
|
||||
void test_destination_packet_cycle() {
|
||||
// Create destinations, send packets, destroy - repeat
|
||||
initRNS();
|
||||
|
||||
for (int cycle = 0; cycle < 10; cycle++) {
|
||||
RNS::Identity temp_id(true);
|
||||
RNS::Destination temp_dest(temp_id, RNS::Type::Destination::IN,
|
||||
RNS::Type::Destination::SINGLE, "test", "temp");
|
||||
temp_dest.set_proof_strategy(RNS::Type::Destination::PROVE_ALL);
|
||||
|
||||
// Announce
|
||||
std::string app_data = "test_cycle_" + std::to_string(cycle);
|
||||
temp_dest.announce(RNS::bytesFromString(app_data.c_str()));
|
||||
|
||||
test_reticulum.loop();
|
||||
// temp_dest goes out of scope here
|
||||
}
|
||||
|
||||
TEST_ASSERT_TRUE_MESSAGE(true, "Destination lifecycle did not crash");
|
||||
}
|
||||
|
||||
|
||||
void test_incoming_announce_limit() {
|
||||
|
||||
printf("test_incoming_announce_max: BEGIN\n");
|
||||
|
||||
initRNS();
|
||||
|
||||
const int num_announces = 50;
|
||||
const int announces_period = 100;
|
||||
|
||||
int announce_count = 0;
|
||||
uint64_t start_time = RNS::Utilities::OS::ltime();
|
||||
uint64_t announce_time = 0;
|
||||
uint64_t log_time = 0;
|
||||
while (true) {
|
||||
// Loop for 10 seconds after last announce
|
||||
if ((RNS::Utilities::OS::ltime() - start_time) >= (num_announces * announces_period + 10000)) {
|
||||
break;
|
||||
}
|
||||
try {
|
||||
if (announce_count < num_announces && (RNS::Utilities::OS::ltime() - announce_time) >= announces_period) {
|
||||
printf("***** test_incoming_announce_limit: Sending announce #%d\n", announce_count + 1);
|
||||
RNS::Identity temp_id(true);
|
||||
RNS::Destination temp_dest(temp_id, RNS::Type::Destination::IN,
|
||||
RNS::Type::Destination::SINGLE, "test", "announce");
|
||||
temp_dest.set_proof_strategy(RNS::Type::Destination::PROVE_ALL);
|
||||
|
||||
// Announce
|
||||
std::string app_data = "test_announce_" + std::to_string(announce_count + 1);
|
||||
RNS::Packet announce_packet = temp_dest.announce(app_data, false, {RNS::Type::NONE}, {RNS::Type::NONE}, false);
|
||||
announce_packet.pack();
|
||||
|
||||
// Must deregister destination so that the ANNOUNCE appears to be from a remote node
|
||||
RNS::Transport::deregister_destination(temp_dest);
|
||||
|
||||
in_interface.handle_incoming(announce_packet.raw());
|
||||
|
||||
announce_time = RNS::Utilities::OS::ltime();
|
||||
++announce_count;
|
||||
}
|
||||
test_reticulum.loop();
|
||||
if ((RNS::Utilities::OS::ltime() - log_time) >= 5000) {
|
||||
RNS::Transport::dump_stats();
|
||||
log_time = RNS::Utilities::OS::ltime();
|
||||
}
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERROR("test_incoming_announce_limit: bad_alloc - OUT OF MEMORY");
|
||||
break;
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("test_incoming_announce_limit: exception: %s", e.what());
|
||||
break;
|
||||
}
|
||||
RNS::Utilities::OS::sleep(0.1);
|
||||
}
|
||||
RNS::Transport::persist_data();
|
||||
RNS::Transport::dump_stats();
|
||||
|
||||
printf("test_incoming_announce_limit: END\n");
|
||||
}
|
||||
|
||||
void test_incoming_announce_over_limit() {
|
||||
|
||||
printf("test_incoming_announce_over_limit: BEGIN\n");
|
||||
|
||||
initRNS();
|
||||
|
||||
const int num_announces = 100;
|
||||
const int announces_period = 100;
|
||||
|
||||
int announce_count = 0;
|
||||
uint64_t start_time = RNS::Utilities::OS::ltime();
|
||||
uint64_t announce_time = 0;
|
||||
uint64_t log_time = 0;
|
||||
while (true) {
|
||||
// Loop for 10 seconds after last announce
|
||||
if ((RNS::Utilities::OS::ltime() - start_time) >= (num_announces * announces_period + 10000)) {
|
||||
break;
|
||||
}
|
||||
try {
|
||||
if (announce_count < num_announces && (RNS::Utilities::OS::ltime() - announce_time) >= announces_period) {
|
||||
printf("***** test_incoming_announce_over_limit: Sending announce #%d\n", announce_count + 1);
|
||||
RNS::Identity temp_id(true);
|
||||
RNS::Destination temp_dest(temp_id, RNS::Type::Destination::IN,
|
||||
RNS::Type::Destination::SINGLE, "test", "announce");
|
||||
temp_dest.set_proof_strategy(RNS::Type::Destination::PROVE_ALL);
|
||||
|
||||
// Announce
|
||||
std::string app_data = "test_announce_" + std::to_string(announce_count + 1);
|
||||
RNS::Packet announce_packet = temp_dest.announce(app_data, false, {RNS::Type::NONE}, {RNS::Type::NONE}, false);
|
||||
announce_packet.pack();
|
||||
|
||||
// Must deregister destination so that the ANNOUNCE appears to be from a remote node
|
||||
RNS::Transport::deregister_destination(temp_dest);
|
||||
|
||||
in_interface.handle_incoming(announce_packet.raw());
|
||||
|
||||
announce_time = RNS::Utilities::OS::ltime();
|
||||
++announce_count;
|
||||
}
|
||||
test_reticulum.loop();
|
||||
if ((RNS::Utilities::OS::ltime() - log_time) >= 5000) {
|
||||
RNS::Transport::dump_stats();
|
||||
log_time = RNS::Utilities::OS::ltime();
|
||||
}
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERROR("test_incoming_announce_over_limit: bad_alloc - OUT OF MEMORY");
|
||||
break;
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("test_incoming_announce_over_limit: exception: %s", e.what());
|
||||
break;
|
||||
}
|
||||
RNS::Utilities::OS::sleep(0.1);
|
||||
}
|
||||
RNS::Transport::persist_data();
|
||||
RNS::Transport::dump_stats();
|
||||
|
||||
printf("test_incoming_announce_over_limit: END\n");
|
||||
}
|
||||
|
||||
void test_incoming_announce_stress() {
|
||||
|
||||
printf("test_incoming_announce_stress: BEGIN\n");
|
||||
|
||||
initRNS();
|
||||
|
||||
//const int num_announces = 0;
|
||||
//const int num_announces = 100;
|
||||
//const int num_announces = 1000;
|
||||
const int num_announces = 10000;
|
||||
//const int announces_period = 1000;
|
||||
const int announces_period = 100;
|
||||
|
||||
int announce_count = 0;
|
||||
uint64_t start_time = RNS::Utilities::OS::ltime();
|
||||
uint64_t announce_time = 0;
|
||||
uint64_t log_time = 0;
|
||||
while (true) {
|
||||
// Loop for 60 seconds after last announce
|
||||
if ((RNS::Utilities::OS::ltime() - start_time) >= (num_announces * announces_period + 60000)) {
|
||||
break;
|
||||
}
|
||||
try {
|
||||
if (announce_count < num_announces && (RNS::Utilities::OS::ltime() - announce_time) >= announces_period) {
|
||||
printf("***** test_incoming_announce_stress: Sending announce #%d\n", announce_count + 1);
|
||||
RNS::Identity temp_id(true);
|
||||
RNS::Destination temp_dest(temp_id, RNS::Type::Destination::IN,
|
||||
RNS::Type::Destination::SINGLE, "test", "announce");
|
||||
temp_dest.set_proof_strategy(RNS::Type::Destination::PROVE_ALL);
|
||||
|
||||
// Announce
|
||||
std::string app_data = "test_announce_" + std::to_string(announce_count + 1);
|
||||
RNS::Packet announce_packet = temp_dest.announce(app_data, false, {RNS::Type::NONE}, {RNS::Type::NONE}, false);
|
||||
announce_packet.pack();
|
||||
//printf("test_incoming_anounce: Sending packet with data: %s\n", announce_packet.raw().toHex().c_str());
|
||||
|
||||
// Must deregister destination so that the ANNOUNCE appears to be from a remote node
|
||||
RNS::Transport::deregister_destination(temp_dest);
|
||||
|
||||
in_interface.handle_incoming(announce_packet.raw());
|
||||
|
||||
announce_time = RNS::Utilities::OS::ltime();
|
||||
++announce_count;
|
||||
}
|
||||
test_reticulum.loop();
|
||||
if ((RNS::Utilities::OS::ltime() - log_time) >= 5000) {
|
||||
RNS::Transport::dump_stats();
|
||||
log_time = RNS::Utilities::OS::ltime();
|
||||
}
|
||||
}
|
||||
catch (const std::bad_alloc&) {
|
||||
ERROR("test_incoming_announce_stress: bad_alloc - OUT OF MEMORY");
|
||||
break;
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
ERRORF("test_incoming_announce_stress: exception: %s", e.what());
|
||||
break;
|
||||
}
|
||||
RNS::Utilities::OS::sleep(0.1);
|
||||
}
|
||||
RNS::Transport::persist_data();
|
||||
RNS::Transport::dump_stats();
|
||||
|
||||
printf("test_incoming_announce_stress: END\n");
|
||||
}
|
||||
|
||||
|
||||
// ============================================================================
|
||||
// Test runner
|
||||
// ============================================================================
|
||||
|
||||
void setUp(void) {}
|
||||
void tearDown(void) {}
|
||||
|
||||
int runUnityTests(void) {
|
||||
UNITY_BEGIN();
|
||||
|
||||
/*
|
||||
// Transport receipt lifecycle
|
||||
RUN_TEST(test_receipt_creation_and_culling);
|
||||
RUN_TEST(test_receipt_rapid_fire);
|
||||
// CBA Temporarily disabled while failing
|
||||
//RUN_TEST(test_receipt_timeout_callback);
|
||||
|
||||
// Transport hashlist
|
||||
RUN_TEST(test_hashlist_basic);
|
||||
RUN_TEST(test_hashlist_overflow);
|
||||
|
||||
// Packet send/receive
|
||||
RUN_TEST(test_send_receive_cycle);
|
||||
RUN_TEST(test_send_receive_stress);
|
||||
RUN_TEST(test_interleaved_send_and_jobs);
|
||||
|
||||
// Identity/Destination lifecycle
|
||||
RUN_TEST(test_identity_create_destroy_cycle);
|
||||
RUN_TEST(test_destination_packet_cycle);
|
||||
|
||||
//RUN_TEST(test_incoming_announce_limit);
|
||||
*/
|
||||
RUN_TEST(test_incoming_announce_over_limit);
|
||||
//RUN_TEST(test_incoming_announce_stress);
|
||||
|
||||
return UNITY_END();
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
return runUnityTests();
|
||||
}
|
||||
|
||||
#ifdef ARDUINO
|
||||
void setup() {
|
||||
delay(2000);
|
||||
runUnityTests();
|
||||
}
|
||||
void loop() {}
|
||||
#endif
|
||||
|
||||
void app_main() {
|
||||
runUnityTests();
|
||||
}
|
||||
Vendored
BIN
Binary file not shown.
@@ -0,0 +1,64 @@
|
||||
#ifndef Pins_Arduino_h
|
||||
#define Pins_Arduino_h
|
||||
|
||||
#ifndef _VARIANT_RAK11200_
|
||||
#define _VARIANT_RAK11200_
|
||||
#endif
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
// #ifndef EXTERNAL_NUM_INTERRUPTS
|
||||
// #define EXTERNAL_NUM_INTERRUPTS 16
|
||||
// #endif
|
||||
// #ifndef NUM_DIGITAL_PINS
|
||||
// #define NUM_DIGITAL_PINS 40
|
||||
// #endif
|
||||
// #ifndef NUM_ANALOG_INPUTS
|
||||
// #define NUM_ANALOG_INPUTS 16
|
||||
// #endif
|
||||
// #ifndef analogInputToDigitalPin
|
||||
// #define analogInputToDigitalPin(p) (((p) < 20) ? (esp32_adc2gpio[(p)]) : -1)
|
||||
// #endif
|
||||
// #ifndef digitalPinToInterrupt
|
||||
// #define digitalPinToInterrupt(p) (((p) < 40) ? (p) : -1)
|
||||
// #endif
|
||||
// #ifndef digitalPinHasPWM
|
||||
// #define digitalPinHasPWM(p) (p < 34)
|
||||
// #endif
|
||||
|
||||
#define LED_GREEN 12
|
||||
#define LED_BLUE 2
|
||||
|
||||
#ifdef LED_BUILTIN
|
||||
#undef LED_BUILTIN
|
||||
#endif
|
||||
#define LED_BUILTIN LED_GREEN
|
||||
|
||||
static const uint8_t TX = 1;
|
||||
static const uint8_t RX = 3;
|
||||
|
||||
#define TX1 21
|
||||
#define RX1 19
|
||||
|
||||
#define WB_IO1 14
|
||||
#define WB_IO2 27
|
||||
#define WB_IO3 26
|
||||
#define WB_IO4 23
|
||||
#define WB_IO5 13
|
||||
#define WB_IO6 22
|
||||
#define WB_SW1 34
|
||||
#define WB_A0 36
|
||||
#define WB_A1 39
|
||||
#define WB_CS 32
|
||||
#define WB_LED1 12
|
||||
#define WB_LED2 2
|
||||
|
||||
static const uint8_t SDA = 4;
|
||||
static const uint8_t SCL = 5;
|
||||
|
||||
static const uint8_t SS = 32;
|
||||
static const uint8_t MOSI = 25;
|
||||
static const uint8_t MISO = 35;
|
||||
static const uint8_t SCK = 33;
|
||||
|
||||
#endif /* Pins_Arduino_h */
|
||||
@@ -0,0 +1 @@
|
||||
// Just for consistency, for RAK11200 ESP32 Wrover all definitions are in the pins_arduino.h
|
||||
@@ -0,0 +1 @@
|
||||
#include "rak_variant.h"
|
||||
@@ -0,0 +1,6 @@
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#ifndef _VARIANT_RAK11300_
|
||||
#define _VARIANT_RAK11300_
|
||||
|
||||
#endif // #define _VARIANT_RAK11300_
|
||||
@@ -0,0 +1,2 @@
|
||||
// Just for consistency, for RAK11310 all definitions are in the pins_arduino.h
|
||||
#include "rak_variant.h"
|
||||
@@ -0,0 +1,97 @@
|
||||
#ifndef Pins_Arduino_h
|
||||
#define Pins_Arduino_h
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifndef _VARIANT_RAK3112_
|
||||
#define _VARIANT_RAK3112_
|
||||
#endif
|
||||
|
||||
#define USB_VID 0x303a
|
||||
#define USB_PID 0x1001
|
||||
|
||||
// GPIO's
|
||||
#define WB_IO1 21
|
||||
#define WB_IO2 2
|
||||
// #define WB_IO2 14
|
||||
#define WB_IO3 41
|
||||
#define WB_IO4 42
|
||||
#define WB_IO5 38
|
||||
#define WB_IO6 39
|
||||
// #define WB_SW1 35 NC
|
||||
#define WB_A0 1
|
||||
#define WB_A1 2
|
||||
#define WB_CS 12
|
||||
#define WB_LED1 46
|
||||
#define WB_LED2 45
|
||||
|
||||
// LEDs
|
||||
#define PIN_LED1 (46)
|
||||
#define PIN_LED2 (45)
|
||||
#define LED_BLUE PIN_LED2
|
||||
#define LED_GREEN PIN_LED1
|
||||
#define LED_BUILTIN LED_GREEN
|
||||
#define LED_CONN PIN_LED2
|
||||
#define LED_STATE_ON 1 // State when LED is litted
|
||||
|
||||
/*
|
||||
* Analog pins
|
||||
*/
|
||||
#define PIN_A0 (21)
|
||||
#define PIN_A1 (14)
|
||||
|
||||
/*
|
||||
* Serial interfaces
|
||||
*/
|
||||
// TXD1 RXD1 on Base Board
|
||||
#define PIN_SERIAL1_RX (44)
|
||||
#define PIN_SERIAL1_TX (43)
|
||||
|
||||
// TXD0 RXD0 on Base Board (NC due to large flash chip)
|
||||
// #define PIN_SERIAL2_RX (19)
|
||||
// #define PIN_SERIAL2_TX (20)
|
||||
|
||||
/*
|
||||
* SPI Interfaces
|
||||
*/
|
||||
#define SPI_INTERFACES_COUNT 1
|
||||
|
||||
#define PIN_SPI_MISO (10)
|
||||
#define PIN_SPI_MOSI (11)
|
||||
#define PIN_SPI_SCK (13)
|
||||
#define SPI_CS (12)
|
||||
|
||||
static const uint8_t SS = SPI_CS;
|
||||
static const uint8_t MOSI = PIN_SPI_MOSI;
|
||||
static const uint8_t MISO = PIN_SPI_MISO;
|
||||
static const uint8_t SCK = PIN_SPI_SCK;
|
||||
|
||||
// Internal SPI to LoRa transceiver
|
||||
#define LORA_SX126X_SCK 5
|
||||
#define LORA_SX126X_MISO 3
|
||||
#define LORA_SX126X_MOSI 6
|
||||
#define LORA_SX126X_CS 7
|
||||
#define LORA_SX126X_RESET 8
|
||||
#define LORA_SX126X_DIO1 47
|
||||
#define LORA_SX126X_BUSY 48
|
||||
#define LORA_SX126X_DIO2_AS_RF_SWITCH 1
|
||||
#define LORA_SX126X_DIO3_TCXO_VOLTAGE 1.8
|
||||
|
||||
/*
|
||||
* Wire Interfaces
|
||||
*/
|
||||
#define WIRE_INTERFACES_COUNT 2
|
||||
|
||||
#ifndef PIN_WIRE_SDA
|
||||
#define PIN_WIRE_SDA (9)
|
||||
#endif
|
||||
#ifndef PIN_WIRE_SCL
|
||||
#define PIN_WIRE_SCL (40)
|
||||
#endif
|
||||
#define SDA PIN_WIRE_SDA
|
||||
#define SCL PIN_WIRE_SCL
|
||||
|
||||
#define PIN_WIRE1_SDA (17)
|
||||
#define PIN_WIRE1_SCL (18)
|
||||
|
||||
#endif /* Pins_Arduino_h */
|
||||
@@ -0,0 +1,5 @@
|
||||
// Just for consistency, for RAK3112 ESP32-S3 all definitions are in the pins_arduino.h
|
||||
|
||||
#ifndef _VARIANT_RAK3112_
|
||||
#define _VARIANT_RAK3113_
|
||||
#endif
|
||||
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
Copyright (c) 2015 Arduino LLC. All right reserved.
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include <nrf.h>
|
||||
#include <nrf_soc.h>
|
||||
#include <nrf_sdm.h>
|
||||
#include <nrf_gpio.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
extern const uint32_t g_ADigitalPinMap[] ;
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
Copyright (c) 2014-2015 Arduino LLC. All right reserved.
|
||||
Copyright (c) 2016 Sandeep Mistry All right reserved.
|
||||
Copyright (c) 2018, Adafruit Industries (adafruit.com)
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#include "variant.h"
|
||||
#include "wiring_constants.h"
|
||||
#include "wiring_digital.h"
|
||||
#include "nrf.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif // __cplusplus
|
||||
|
||||
const uint32_t g_ADigitalPinMap[] =
|
||||
{
|
||||
// P0
|
||||
0, 1, 2, 3, 4, 5, 6, 7,
|
||||
8, 9, 10, 11, 12, 13, 14, 15,
|
||||
16, 17, 18, 19, 20, 21, 22, 23,
|
||||
24, 25, 26, 27, 28, 29, 30, 31,
|
||||
|
||||
// P1
|
||||
32, 33, 34, 35, 36, 37, 38, 39,
|
||||
40, 41, 42, 43, 44, 45, 46, 47};
|
||||
|
||||
void initVariant()
|
||||
{
|
||||
// LED1 & LED2
|
||||
pinMode(PIN_LED1, OUTPUT);
|
||||
ledOff(PIN_LED1);
|
||||
|
||||
pinMode(PIN_LED2, OUTPUT);
|
||||
ledOff(PIN_LED2);
|
||||
}
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
Copyright (c) 2014-2015 Arduino LLC. All right reserved.
|
||||
Copyright (c) 2016 Sandeep Mistry All right reserved.
|
||||
Copyright (c) 2018, Adafruit Industries (adafruit.com)
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the GNU Lesser General Public License for more details.
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifndef _VARIANT_RAK4630_
|
||||
#define _VARIANT_RAK4630_
|
||||
|
||||
#define RAK4630
|
||||
|
||||
/** Master clock frequency */
|
||||
#define VARIANT_MCK (64000000ul)
|
||||
|
||||
#define USE_LFXO // Board uses 32khz crystal for LF
|
||||
// define USE_LFRC // Board uses RC for LF
|
||||
|
||||
/*----------------------------------------------------------------------------
|
||||
* Headers
|
||||
*----------------------------------------------------------------------------*/
|
||||
#include <Arduino.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif // __cplusplus
|
||||
|
||||
/*
|
||||
* WisBlock Base GPIO definitions
|
||||
*/
|
||||
static const uint8_t WB_IO1 = 17; // SLOT_A SLOT_B
|
||||
static const uint8_t WB_IO2 = 34; // SLOT_A SLOT_B
|
||||
static const uint8_t WB_IO3 = 21; // SLOT_C
|
||||
static const uint8_t WB_IO4 = 4; // SLOT_C
|
||||
static const uint8_t WB_IO5 = 9; // SLOT_D
|
||||
static const uint8_t WB_IO6 = 10; // SLOT_D
|
||||
static const uint8_t WB_SW1 = 33; // IO_SLOT
|
||||
static const uint8_t WB_A0 = 5; // IO_SLOT
|
||||
static const uint8_t WB_A1 = 31; // IO_SLOT
|
||||
static const uint8_t WB_I2C1_SDA = 13; // SENSOR_SLOT IO_SLOT
|
||||
static const uint8_t WB_I2C1_SCL = 14; // SENSOR_SLOT IO_SLOT
|
||||
static const uint8_t WB_I2C2_SDA = 24; // IO_SLOT
|
||||
static const uint8_t WB_I2C2_SCL = 25; // IO_SLOT
|
||||
static const uint8_t WB_SPI_CS = 26; // IO_SLOT
|
||||
static const uint8_t WB_SPI_CLK = 3; // IO_SLOT
|
||||
static const uint8_t WB_SPI_MISO = 29; // IO_SLOT
|
||||
static const uint8_t WB_SPI_MOSI = 30; // IO_SLOT
|
||||
|
||||
// Number of pins defined in PinDescription array
|
||||
#define PINS_COUNT (48)
|
||||
#define NUM_DIGITAL_PINS (48)
|
||||
#define NUM_ANALOG_INPUTS (6)
|
||||
#define NUM_ANALOG_OUTPUTS (0)
|
||||
|
||||
// LEDs
|
||||
#define PIN_LED1 (35)
|
||||
#define PIN_LED2 (36)
|
||||
|
||||
#define LED_BUILTIN PIN_LED1
|
||||
#define LED_CONN PIN_LED2
|
||||
|
||||
#define LED_GREEN PIN_LED1
|
||||
#define LED_BLUE PIN_LED2
|
||||
|
||||
#define LED_STATE_ON 1 // State when LED is litted
|
||||
|
||||
/*
|
||||
* Analog pins
|
||||
*/
|
||||
#define PIN_A0 (5) //(3)
|
||||
#define PIN_A1 (31) //(4)
|
||||
#define PIN_A2 (28)
|
||||
#define PIN_A3 (29)
|
||||
#define PIN_A4 (30)
|
||||
#define PIN_A5 (31)
|
||||
#define PIN_A6 (0xff)
|
||||
#define PIN_A7 (0xff)
|
||||
|
||||
static const uint8_t A0 = PIN_A0;
|
||||
static const uint8_t A1 = PIN_A1;
|
||||
static const uint8_t A2 = PIN_A2;
|
||||
static const uint8_t A3 = PIN_A3;
|
||||
static const uint8_t A4 = PIN_A4;
|
||||
static const uint8_t A5 = PIN_A5;
|
||||
static const uint8_t A6 = PIN_A6;
|
||||
static const uint8_t A7 = PIN_A7;
|
||||
#define ADC_RESOLUTION 14
|
||||
|
||||
// Other pins
|
||||
#define PIN_AREF (2)
|
||||
#define PIN_NFC1 (9)
|
||||
#define PIN_NFC2 (10)
|
||||
|
||||
static const uint8_t AREF = PIN_AREF;
|
||||
|
||||
/*
|
||||
* Serial interfaces
|
||||
*/
|
||||
// TXD1 RXD1 on Base Board
|
||||
#define PIN_SERIAL1_RX (15)
|
||||
#define PIN_SERIAL1_TX (16)
|
||||
|
||||
// TXD0 RXD0 on Base Board
|
||||
#define PIN_SERIAL2_RX (19)
|
||||
#define PIN_SERIAL2_TX (20)
|
||||
|
||||
/*
|
||||
* SPI Interfaces
|
||||
*/
|
||||
#define SPI_INTERFACES_COUNT 1
|
||||
|
||||
#define PIN_SPI_MISO (29)
|
||||
#define PIN_SPI_MOSI (30)
|
||||
#define PIN_SPI_SCK (3)
|
||||
|
||||
static const uint8_t SS = 26;
|
||||
static const uint8_t MOSI = PIN_SPI_MOSI;
|
||||
static const uint8_t MISO = PIN_SPI_MISO;
|
||||
static const uint8_t SCK = PIN_SPI_SCK;
|
||||
|
||||
/*
|
||||
* Wire Interfaces
|
||||
*/
|
||||
#define WIRE_INTERFACES_COUNT 2
|
||||
|
||||
#define PIN_WIRE_SDA (13)
|
||||
#define PIN_WIRE_SCL (14)
|
||||
#define PIN_WIRE1_SDA (24)
|
||||
#define PIN_WIRE1_SCL (25)
|
||||
|
||||
// QSPI Pins
|
||||
#define PIN_QSPI_SCK 3 // 19
|
||||
#define PIN_QSPI_CS 26 // 17
|
||||
#define PIN_QSPI_IO0 30 // 20
|
||||
#define PIN_QSPI_IO1 29 // 21
|
||||
#define PIN_QSPI_IO2 28 // 22
|
||||
#define PIN_QSPI_IO3 2 // 23
|
||||
|
||||
// On-board QSPI Flash
|
||||
#define EXTERNAL_FLASH_DEVICES IS25LP080D
|
||||
#define EXTERNAL_FLASH_USE_QSPI
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
/*----------------------------------------------------------------------------
|
||||
* Arduino objects - C++ only
|
||||
*----------------------------------------------------------------------------*/
|
||||
|
||||
#endif
|
||||
Reference in new issue
Block a user