Files
meshcore-tth/examples/simple_repeater/MyMesh.cpp
T

1969 lines
79 KiB
C++

#include "MyMesh.h"
#include <algorithm>
/* ------------------------------ Config -------------------------------- */
#ifndef LORA_FREQ
#define LORA_FREQ 915.0
#endif
#ifndef LORA_BW
#define LORA_BW 250
#endif
#ifndef LORA_SF
#define LORA_SF 10
#endif
#ifndef LORA_CR
#define LORA_CR 5
#endif
#ifndef LORA_TX_POWER
#define LORA_TX_POWER 20
#endif
#ifndef ADVERT_NAME
#define ADVERT_NAME "repeater"
#endif
#ifndef ADVERT_LAT
#define ADVERT_LAT 0.0
#endif
#ifndef ADVERT_LON
#define ADVERT_LON 0.0
#endif
#ifndef ADMIN_PASSWORD
#define ADMIN_PASSWORD "password"
#endif
#ifndef SERVER_RESPONSE_DELAY
#define SERVER_RESPONSE_DELAY 300
#endif
#ifndef TXT_ACK_DELAY
#define TXT_ACK_DELAY 200
#endif
#define FIRMWARE_VER_LEVEL 2
#define REQ_TYPE_GET_STATUS 0x01 // same as _GET_STATS
#define REQ_TYPE_KEEP_ALIVE 0x02
#define REQ_TYPE_GET_TELEMETRY_DATA 0x03
#define REQ_TYPE_GET_ACCESS_LIST 0x05
#define REQ_TYPE_GET_NEIGHBOURS 0x06
#define REQ_TYPE_GET_OWNER_INFO 0x07 // FIRMWARE_VER_LEVEL >= 2
#define RESP_SERVER_LOGIN_OK 0 // response to ANON_REQ
#define ANON_REQ_TYPE_REGIONS 0x01
#define ANON_REQ_TYPE_OWNER 0x02
#define ANON_REQ_TYPE_BASIC 0x03 // just remote clock
#define CLI_REPLY_DELAY_MILLIS 600
#define LAZY_CONTACTS_WRITE_DELAY 5000
void MyMesh::putNeighbour(const mesh::Identity &id, uint32_t timestamp, float snr) {
#if MAX_NEIGHBOURS // check if neighbours enabled
// find existing neighbour, else use least recently updated
uint32_t oldest_timestamp = 0xFFFFFFFF;
NeighbourInfo *neighbour = &neighbours[0];
for (int i = 0; i < MAX_NEIGHBOURS; i++) {
// if neighbour already known, we should update it
if (id.matches(neighbours[i].id)) {
neighbour = &neighbours[i];
break;
}
// otherwise we should update the least recently updated neighbour
if (neighbours[i].heard_timestamp < oldest_timestamp) {
neighbour = &neighbours[i];
oldest_timestamp = neighbour->heard_timestamp;
}
}
// update neighbour info
neighbour->id = id;
neighbour->advert_timestamp = timestamp;
neighbour->heard_timestamp = getRTCClock()->getCurrentTime();
neighbour->snr = (int8_t)(snr * 4);
#endif
}
#if MAX_HEARD_NODES || RXLOG_SIZE
// Cheap deterministic frame id: FNV-1a over (type || payload). Same value for
// every copy of one advert/packet regardless of the path it took (path is not
// hashed), so it GROUPS the copies that arrived via different paths -> the bridge
// joins nodes<->rxlog on it to reconstruct multi-path. NOT the SHA packet-hash
// (the mesh already computes that once per frame in hasSeen(); a second SHA on
// the radio hot path would be wasted work).
static uint32_t analyzer_frame_id(const mesh::Packet* pkt) {
uint32_t h = 2166136261u;
uint8_t t = pkt->getPayloadType();
h = (h ^ t) * 16777619u;
for (uint16_t k = 0; k < pkt->payload_len; k++) h = (h ^ pkt->payload[k]) * 16777619u;
return h;
}
// Render a stored path as COLON-separated per-hop hashes. The path-hash width is
// uniform per packet (1/2/3 B, top 2 bits of path_len) but not otherwise visible
// in the hex, so delimit the hops: each token between ':' is one hop-hash and its
// byte width is (token length / 2). 1-byte -> "36:2F:EC", 2-byte -> "362F:ECBD".
// out must hold ANALYZER_PATH_LEN*3+1 bytes.
static void analyzer_path_hex(char* out, const uint8_t* path, uint8_t path_len) {
static const char hexd[] = "0123456789ABCDEF";
uint8_t cnt = path_len & 63;
uint8_t sz = (path_len >> 6) + 1;
char* p = out;
uint8_t off = 0;
for (uint8_t h = 0; h < cnt && off + sz <= ANALYZER_PATH_LEN; h++) {
if (h) *p++ = ':';
for (uint8_t b = 0; b < sz; b++, off++) {
*p++ = hexd[path[off] >> 4];
*p++ = hexd[path[off] & 0x0F];
}
}
*p = 0;
}
#endif
#if MAX_HEARD_NODES
// CUSTOM (TeTeHacko): record/update one heard node in the analyzer registry.
void MyMesh::putHeardNode(const mesh::Identity& id, uint32_t advert_timestamp, uint8_t type,
int32_t lat, int32_t lon, const char* name,
int8_t snr, int8_t rssi, const mesh::Packet* pkt) {
uint32_t now = getRTCClock()->getCurrentTime();
bool is_direct = (pkt->getPathHashCount() == 0); // 0-hop = heard directly
uint32_t oldest = 0xFFFFFFFF;
HeardNode* slot = &heard_nodes[0];
bool existing = false;
for (int i = 0; i < MAX_HEARD_NODES; i++) {
HeardNode* n = &heard_nodes[i];
if (n->heard_timestamp > 0 && memcmp(n->pub_prefix, id.pub_key, HEARD_NODE_PREFIX) == 0) {
slot = n; existing = true; break; // update existing entry
}
if (n->heard_timestamp < oldest) { oldest = n->heard_timestamp; slot = n; } // else evict LRU
}
if (!existing) *slot = HeardNode(); // reused/evicted slot -> clear stale fields (direct_heard!)
// latest identity / position / name always win
memcpy(slot->pub_prefix, id.pub_key, HEARD_NODE_PREFIX);
slot->advert_timestamp = advert_timestamp;
slot->heard_timestamp = now;
slot->type = type;
slot->lat = lat;
slot->lon = lon;
StrHelper::strncpy(slot->name, name ? name : "", sizeof(slot->name));
slot->pkt_hash = analyzer_frame_id(pkt); // join key -> rxlog copies (= every path this advert took)
// Representative path + link quality. A DIRECT (0-hop) advert is the key edge
// (us <-> node). Because all copies of one advert share a hash, dedup means
// onAdvertRecv only fires for whichever copy arrives first -- often a stronger
// relayed one -- so a plain last-write keeps overwriting a direct link with a
// relayed path. Prefer the direct observation for HEARD_DIRECT_TTL_SECS. (Full
// multi-path is reconstructed on the bridge via the pkt_hash join to rxlog.)
bool direct_recent = slot->direct_heard != 0 && (now - slot->direct_heard) < HEARD_DIRECT_TTL_SECS;
if (is_direct) {
slot->direct_heard = now;
slot->snr = snr; slot->rssi = rssi;
slot->path_len = 0; // empty path = direct
memset(slot->path, 0, sizeof(slot->path));
} else if (!direct_recent) {
slot->snr = snr; slot->rssi = rssi;
slot->path_len = (uint8_t) pkt->path_len;
uint8_t pb = pkt->getPathByteLen();
if (pb > ANALYZER_PATH_LEN) pb = ANALYZER_PATH_LEN;
memset(slot->path, 0, sizeof(slot->path));
if (pb) memcpy(slot->path, pkt->path, pb);
}
// else: relayed advert but heard direct recently -> keep the direct path/SNR
}
// `nodes [offset]` -> paged dump of the heard-node registry (newest first).
// One text line per node: N,<prefix-hex>,<type>,<lat*1e6>,<lon*1e6>,<snr*4>,<rssi>,<secs_ago>,<pkthash-hex>,<path-hex>,<name>
// <pkthash> = join key: group `rxlog` records by it to get EVERY path this
// node's advert arrived by (multi-path). <path> is a single representative
// (direct/0-hop preferred). Trailer line: E,<next_offset>,<total>
void MyMesh::formatNodesReply(char* reply, int max_len, uint16_t offset) {
char* dp = reply;
int total = 0;
static HeardNode* sorted[MAX_HEARD_NODES]; // BSS, ne stack (128 ptrů; volá se jen z loop tasku)
for (int i = 0; i < MAX_HEARD_NODES; i++) {
if (heard_nodes[i].heard_timestamp > 0) sorted[total++] = &heard_nodes[i];
}
std::sort(sorted, sorted + total, [](const HeardNode* a, const HeardNode* b) {
return a->heard_timestamp > b->heard_timestamp; // newest first
});
uint32_t now = getRTCClock()->getCurrentTime();
int i = offset;
char line[160];
for (; i < total; i++) {
HeardNode* n = sorted[i];
char prefix[HEARD_NODE_PREFIX * 2 + 1];
mesh::Utils::toHex(prefix, n->pub_prefix, HEARD_NODE_PREFIX);
char pathhex[ANALYZER_PATH_LEN * 3 + 1];
analyzer_path_hex(pathhex, n->path, n->path_len); // colon-separated hops (width self-describing)
snprintf(line, sizeof(line), "N,%s,%u,%ld,%ld,%d,%d,%lu,%08lX,%s,%s\n",
prefix, (unsigned)n->type, (long)n->lat, (long)n->lon,
(int)n->snr, (int)n->rssi, (unsigned long)(now - n->heard_timestamp),
(unsigned long)n->pkt_hash, pathhex, n->name);
int ll = strlen(line);
if (i > offset && (dp - reply) + ll + 24 > max_len) break; // room for trailer; always emit >=1
memcpy(dp, line, ll); dp += ll;
}
dp += sprintf(dp, "E,%d,%d", i, total);
*dp = 0;
}
#endif
#if RXLOG_SIZE
// CUSTOM (TeTeHacko): append one heard frame to the analyzer firehose ring.
void MyMesh::captureRx(const mesh::Packet* pkt) {
RxLogRec* r = &rxlog_ring[rxlog_head];
rxlog_head = (rxlog_head + 1) % RXLOG_SIZE;
r->seq = rxlog_next_seq++;
if (rxlog_next_seq == 0) rxlog_next_seq = 1; // wrap guard (seq 0 reserved for empty)
r->when = getRTCClock()->getCurrentTime();
r->pkt_hash = analyzer_frame_id(pkt); // same key across all copies -> groups the paths a frame took
r->snr = pkt->_snr;
r->rssi = (int8_t) pkt->getRSSI();
r->header = pkt->header;
r->path_len = (uint8_t) pkt->path_len;
uint8_t pb = pkt->getPathByteLen();
if (pb > ANALYZER_PATH_LEN) pb = ANALYZER_PATH_LEN;
memset(r->path, 0, sizeof(r->path));
if (pb) memcpy(r->path, pkt->path, pb);
}
// `rxlog [cursor]` -> paged dump of frames with seq > cursor (oldest first).
// One text line per record: R,<seq>,<when>,<pkthash-hex>,<hdr-hex>,<snr*4>,<rssi>,<path-hex>
// Trailer line: E,<last_returned_seq>,<oldest_seq_in_ring>,<newest_seq>
void MyMesh::formatRxLogReply(char* reply, int max_len, uint32_t cursor) {
char* dp = reply;
static RxLogRec* recs[RXLOG_SIZE]; // BSS, ne stack (512 ptrů = 2 KB; volá se jen z loop tasku)
int n = 0;
uint32_t oldest = 0, newest = 0;
for (int i = 0; i < RXLOG_SIZE; i++) {
RxLogRec* r = &rxlog_ring[i];
if (r->seq == 0) continue;
if (oldest == 0 || r->seq < oldest) oldest = r->seq;
if (r->seq > newest) newest = r->seq;
if (r->seq > cursor) recs[n++] = r;
}
std::sort(recs, recs + n, [](const RxLogRec* a, const RxLogRec* b) {
return a->seq < b->seq; // oldest unread first
});
uint32_t last = cursor;
char line[128];
for (int i = 0; i < n; i++) {
RxLogRec* r = recs[i];
char pathhex[ANALYZER_PATH_LEN * 3 + 1];
analyzer_path_hex(pathhex, r->path, r->path_len); // colon-separated hops (width self-describing)
snprintf(line, sizeof(line), "R,%lu,%lu,%08lX,%02X,%d,%d,%s\n",
(unsigned long)r->seq, (unsigned long)r->when,
(unsigned long)r->pkt_hash, (unsigned)r->header,
(int)r->snr, (int)r->rssi, pathhex);
int ll = strlen(line);
if (i > 0 && (dp - reply) + ll + 40 > max_len) break; // room for trailer; always emit >=1
memcpy(dp, line, ll); dp += ll;
last = r->seq;
}
dp += sprintf(dp, "E,%lu,%lu,%lu", (unsigned long)last, (unsigned long)oldest, (unsigned long)newest);
*dp = 0;
}
#endif
#if PKTFEED_SIZE
// CUSTOM (TeTeHacko): observer feed -- rxlog's sibling ring that keeps the FULL
// raw frame so the bridge can publish meshcoretomqtt-compatible packets (the
// SHA256 packet hash and type/route/payload decode all happen bridge-side).
void MyMesh::stagePktFeed(const uint8_t raw[], int len) {
if (len <= 0 || len > MAX_TRANS_UNIT) {
pktfeed_stage_len = 0;
return;
}
memcpy(pktfeed_stage, raw, len);
pktfeed_stage_len = (uint8_t) len;
}
void MyMesh::commitPktFeed(const mesh::Packet* pkt) {
// stage/commit must be the same frame: both run in order inside one
// Dispatcher::checkRecv pass, but a parse-failed frame leaves a stale stage
// behind -- the length check discards such a mismatched pairing
if (pktfeed_stage_len == 0 || pktfeed_stage_len != pkt->getRawLength()) {
pktfeed_stage_len = 0;
return;
}
PktFeedRec* r = &pktfeed_ring[pktfeed_head];
pktfeed_head = (pktfeed_head + 1) % PKTFEED_SIZE;
r->seq = pktfeed_next_seq++;
if (pktfeed_next_seq == 0) pktfeed_next_seq = 1; // wrap guard (seq 0 reserved for empty)
r->when = getRTCClock()->getCurrentTime();
r->snr = pkt->_snr;
r->rssi = (int8_t) pkt->getRSSI();
r->len = pktfeed_stage_len;
memcpy(r->raw, pktfeed_stage, pktfeed_stage_len);
pktfeed_stage_len = 0;
}
// `pktlog [cursor]` -> paged dump of raw frames with seq > cursor (oldest first).
// One text line per record: P,<seq>,<when>,<snr*4>,<rssi>,<raw-hex>
// Trailer line: E,<last_returned_seq>,<oldest_seq_in_ring>,<newest_seq>
void MyMesh::formatPktFeedReply(char* reply, int max_len, uint32_t cursor) {
char* dp = reply;
PktFeedRec* recs[PKTFEED_SIZE]; // small ring -> stack is fine (32 ptrs)
int n = 0;
uint32_t oldest = 0, newest = 0;
for (int i = 0; i < PKTFEED_SIZE; i++) {
PktFeedRec* r = &pktfeed_ring[i];
if (r->seq == 0) continue;
if (oldest == 0 || r->seq < oldest) oldest = r->seq;
if (r->seq > newest) newest = r->seq;
if (r->seq > cursor) recs[n++] = r;
}
std::sort(recs, recs + n, [](const PktFeedRec* a, const PktFeedRec* b) {
return a->seq < b->seq; // oldest unread first
});
uint32_t last = cursor;
static char line[40 + MAX_TRANS_UNIT * 2]; // BSS, ne stack (~550 B; volá se jen z loop tasku)
for (int i = 0; i < n; i++) {
PktFeedRec* r = recs[i];
int ll = snprintf(line, sizeof(line), "P,%lu,%lu,%d,%d,",
(unsigned long)r->seq, (unsigned long)r->when,
(int)r->snr, (int)r->rssi);
for (int b = 0; b < r->len; b++) {
ll += sprintf(line + ll, "%02X", r->raw[b]);
}
line[ll++] = '\n';
line[ll] = 0;
// Unlike rxlog there is NO "always emit >=1" here: a full-size record line
// (~550 B) exceeds the mesh admin CLI's 150 B budget and would overflow its
// reply buffer. There the reply degrades to a bare trailer (paging stalls);
// the intended consumer is the local console's ~1000 B pages, which always
// fit at least one record.
if ((dp - reply) + ll + 40 > max_len) break; // room for trailer
memcpy(dp, line, ll); dp += ll;
last = r->seq;
}
dp += sprintf(dp, "E,%lu,%lu,%lu", (unsigned long)last, (unsigned long)oldest, (unsigned long)newest);
*dp = 0;
}
#endif
uint8_t MyMesh::handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood) {
ClientInfo* client = NULL;
if (data[0] == 0) { // blank password, just check if sender is in ACL
client = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
if (client == NULL) {
#if MESH_DEBUG
MESH_DEBUG_PRINTLN("Login, sender not in ACL");
#endif
}
}
if (client == NULL) {
uint8_t perms;
if (strcmp((char *)data, _prefs.password) == 0) { // check for valid admin password
perms = PERM_ACL_ADMIN;
} else if (strcmp((char *)data, _prefs.guest_password) == 0) { // check guest password
perms = PERM_ACL_GUEST;
} else {
#if MESH_DEBUG
MESH_DEBUG_PRINTLN("Invalid password: %s", data);
#endif
return 0;
}
client = acl.putClient(sender, 0); // add to contacts (if not already known)
if (sender_timestamp <= client->last_timestamp) {
MESH_DEBUG_PRINTLN("Possible login replay attack!");
return 0; // FATAL: client table is full -OR- replay attack
}
MESH_DEBUG_PRINTLN("Login success!");
client->last_timestamp = sender_timestamp;
client->last_activity = getRTCClock()->getCurrentTime();
client->permissions &= ~0x03;
client->permissions |= perms;
memcpy(client->shared_secret, secret, PUB_KEY_SIZE);
if (perms != PERM_ACL_GUEST) { // keep number of FS writes to a minimum
dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY);
}
}
if (is_flood) {
client->out_path_len = OUT_PATH_UNKNOWN; // need to rediscover out_path
}
uint32_t now = getRTCClock()->getCurrentTimeUnique();
memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
reply_data[4] = RESP_SERVER_LOGIN_OK;
reply_data[5] = 0; // Legacy: was recommended keep-alive interval (secs / 16)
reply_data[6] = client->isAdmin() ? 1 : 0;
reply_data[7] = client->permissions;
getRNG()->random(&reply_data[8], 4); // random blob to help packet-hash uniqueness
reply_data[12] = FIRMWARE_VER_LEVEL; // New field
return 13; // reply length
}
uint8_t MyMesh::handleAnonRegionsReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) {
if (anon_limiter.allow(rtc_clock.getCurrentTime())) {
// request data has: {reply-path-len}{reply-path}
reply_path_len = *data++;
if (!mesh::Packet::isValidPathLen(reply_path_len)) return 0; // reject - bad encoding
mesh::Packet::writePath(reply_path, data, reply_path_len);
// data += (uint8_t)reply_path_len * reply_path_hash_size;
memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag
uint32_t now = getRTCClock()->getCurrentTime();
memcpy(&reply_data[4], &now, 4); // include our clock (for easy clock sync, and packet hash uniqueness)
return 8 + region_map.exportNamesTo((char *) &reply_data[8], sizeof(reply_data) - 12, REGION_DENY_FLOOD); // reply length
}
return 0;
}
uint8_t MyMesh::handleAnonOwnerReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) {
if (anon_limiter.allow(rtc_clock.getCurrentTime())) {
// request data has: {reply-path-len}{reply-path}
reply_path_len = *data++;
if (!mesh::Packet::isValidPathLen(reply_path_len)) return 0; // reject - bad encoding
mesh::Packet::writePath(reply_path, data, reply_path_len);
// data += (uint8_t)reply_path_len * reply_path_hash_size;
memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag
uint32_t now = getRTCClock()->getCurrentTime();
memcpy(&reply_data[4], &now, 4); // include our clock (for easy clock sync, and packet hash uniqueness)
sprintf((char *) &reply_data[8], "%s\n%s", _prefs.node_name, _prefs.owner_info);
return 8 + strlen((char *) &reply_data[8]); // reply length
}
return 0;
}
uint8_t MyMesh::handleAnonClockReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data) {
if (anon_limiter.allow(rtc_clock.getCurrentTime())) {
// request data has: {reply-path-len}{reply-path}
reply_path_len = *data++;
if (!mesh::Packet::isValidPathLen(reply_path_len)) return 0; // reject - bad encoding
mesh::Packet::writePath(reply_path, data, reply_path_len);
// data += (uint8_t)reply_path_len * reply_path_hash_size;
memcpy(reply_data, &sender_timestamp, 4); // prefix with sender_timestamp, like a tag
uint32_t now = getRTCClock()->getCurrentTime();
memcpy(&reply_data[4], &now, 4); // include our clock (for easy clock sync, and packet hash uniqueness)
reply_data[8] = 0; // features
#ifdef WITH_RS232_BRIDGE
reply_data[8] |= 0x01; // is bridge, type UART
#elif WITH_ESPNOW_BRIDGE
reply_data[8] |= 0x03; // is bridge, type ESP-NOW
#endif
if (_prefs.disable_fwd) { // is this repeater currently disabled
reply_data[8] |= 0x80; // is disabled
}
// TODO: add some kind of moving-window utilisation metric, so can query 'how busy' is this repeater
return 9; // reply length
}
return 0;
}
int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t *payload, size_t payload_len) {
// uint32_t now = getRTCClock()->getCurrentTimeUnique();
// memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
memcpy(reply_data, &sender_timestamp, 4); // reflect sender_timestamp back in response packet (kind of like a 'tag')
if (payload[0] == REQ_TYPE_GET_STATUS) { // guests can also access this now
RepeaterStats stats;
stats.batt_milli_volts = board.getBattMilliVolts();
stats.curr_tx_queue_len = _mgr->getOutboundTotal();
stats.noise_floor = (int16_t)_radio->getNoiseFloor();
stats.last_rssi = (int16_t)radio_driver.getLastRSSI();
stats.n_packets_recv = radio_driver.getPacketsRecv();
stats.n_packets_sent = radio_driver.getPacketsSent();
stats.total_air_time_secs = getTotalAirTime() / 1000;
stats.total_up_time_secs = uptime_millis / 1000;
stats.n_sent_flood = getNumSentFlood();
stats.n_sent_direct = getNumSentDirect();
stats.n_recv_flood = getNumRecvFlood();
stats.n_recv_direct = getNumRecvDirect();
stats.err_events = _err_flags;
stats.last_snr = (int16_t)(radio_driver.getLastSNR() * 4);
stats.n_direct_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumDirectDups(), 0xFFFF);
stats.n_flood_dups = std::min<uint32_t>(((SimpleMeshTables *)getTables())->getNumFloodDups(), 0xFFFF);
stats.total_rx_air_time_secs = getReceiveAirTime() / 1000;
stats.n_recv_errors = radio_driver.getPacketsRecvErrors();
stats.n_tx_start_fail = getNumTxStartFail(); // CUSTOM (TeTeHacko)
stats.n_tx_timeout = getNumTxTimeout(); // CUSTOM (TeTeHacko)
memcpy(&reply_data[4], &stats, sizeof(stats));
return 4 + sizeof(stats); // reply_len
}
if (payload[0] == REQ_TYPE_GET_TELEMETRY_DATA) {
uint8_t perm_mask = ~(payload[1]); // NEW: first reserved byte (of 4), is now inverse mask to apply to permissions
telemetry.reset();
telemetry.addVoltage(TELEM_CHANNEL_SELF, (float)board.getBattMilliVolts() / 1000.0f);
// query other sensors -- target specific
if ((sender->permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_GUEST) {
perm_mask = 0x00; // just base telemetry allowed
}
sensors.querySensors(perm_mask, telemetry);
// This default temperature will be overridden by external sensors (if any)
float temperature = board.getMCUTemperature();
if(!isnan(temperature)) { // Supported boards with built-in temperature sensor. ESP32-C3 may return NAN
telemetry.addTemperature(TELEM_CHANNEL_SELF, temperature); // Built-in MCU Temperature
}
uint8_t tlen = telemetry.getSize();
memcpy(&reply_data[4], telemetry.getBuffer(), tlen);
return 4 + tlen; // reply_len
}
if (payload[0] == REQ_TYPE_GET_ACCESS_LIST && sender->isAdmin()) {
uint8_t res1 = payload[1]; // reserved for future (extra query params)
uint8_t res2 = payload[2];
if (res1 == 0 && res2 == 0) {
uint8_t ofs = 4;
for (int i = 0; i < acl.getNumClients() && ofs + 7 <= sizeof(reply_data) - 4; i++) {
auto c = acl.getClientByIdx(i);
if (c->permissions == 0) continue; // skip deleted entries
memcpy(&reply_data[ofs], c->id.pub_key, 6); ofs += 6; // just 6-byte pub_key prefix
reply_data[ofs++] = c->permissions;
}
return ofs;
}
}
if (payload[0] == REQ_TYPE_GET_NEIGHBOURS) {
uint8_t request_version = payload[1];
if (request_version == 0) {
// reply data offset (after response sender_timestamp/tag)
int reply_offset = 4;
// get request params
uint8_t count = payload[2]; // how many neighbours to fetch (0-255)
uint16_t offset;
memcpy(&offset, &payload[3], 2); // offset from start of neighbours list (0-65535)
uint8_t order_by = payload[5]; // how to order neighbours. 0=newest_to_oldest, 1=oldest_to_newest, 2=strongest_to_weakest, 3=weakest_to_strongest
uint8_t pubkey_prefix_length = payload[6]; // how many bytes of neighbour pub key we want
// we also send a 4 byte random blob in payload[7...10] to help packet uniqueness
MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS count=%d, offset=%d, order_by=%d, pubkey_prefix_length=%d", count, offset, order_by, pubkey_prefix_length);
// clamp pub key prefix length to max pub key length
if(pubkey_prefix_length > PUB_KEY_SIZE){
pubkey_prefix_length = PUB_KEY_SIZE;
MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS invalid pubkey_prefix_length=%d clamping to %d", pubkey_prefix_length, PUB_KEY_SIZE);
}
// create copy of neighbours list, skipping empty entries so we can sort it separately from main list
int16_t neighbours_count = 0;
#if MAX_NEIGHBOURS
NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
for (int i = 0; i < MAX_NEIGHBOURS; i++) {
auto neighbour = &neighbours[i];
if (neighbour->heard_timestamp > 0) {
sorted_neighbours[neighbours_count] = neighbour;
neighbours_count++;
}
}
// sort neighbours based on order
if (order_by == 0) {
// sort by newest to oldest
MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting newest to oldest");
std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
return a->heard_timestamp > b->heard_timestamp; // desc
});
} else if (order_by == 1) {
// sort by oldest to newest
MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting oldest to newest");
std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
return a->heard_timestamp < b->heard_timestamp; // asc
});
} else if (order_by == 2) {
// sort by strongest to weakest
MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting strongest to weakest");
std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
return a->snr > b->snr; // desc
});
} else if (order_by == 3) {
// sort by weakest to strongest
MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS sorting weakest to strongest");
std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
return a->snr < b->snr; // asc
});
}
#endif
// build results buffer
int results_count = 0;
int results_offset = 0;
uint8_t results_buffer[130];
for(int index = 0; index < count && index + offset < neighbours_count; index++){
// stop if we can't fit another entry in results
int entry_size = pubkey_prefix_length + 4 + 1;
if(results_offset + entry_size > sizeof(results_buffer)){
MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS no more entries can fit in results buffer");
break;
}
#if MAX_NEIGHBOURS
// add next neighbour to results
auto neighbour = sorted_neighbours[index + offset];
uint32_t heard_seconds_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
memcpy(&results_buffer[results_offset], neighbour->id.pub_key, pubkey_prefix_length); results_offset += pubkey_prefix_length;
memcpy(&results_buffer[results_offset], &heard_seconds_ago, 4); results_offset += 4;
memcpy(&results_buffer[results_offset], &neighbour->snr, 1); results_offset += 1;
results_count++;
#endif
}
// build reply
MESH_DEBUG_PRINTLN("REQ_TYPE_GET_NEIGHBOURS neighbours_count=%d results_count=%d", neighbours_count, results_count);
memcpy(&reply_data[reply_offset], &neighbours_count, 2); reply_offset += 2;
memcpy(&reply_data[reply_offset], &results_count, 2); reply_offset += 2;
memcpy(&reply_data[reply_offset], &results_buffer, results_offset); reply_offset += results_offset;
return reply_offset;
}
} else if (payload[0] == REQ_TYPE_GET_OWNER_INFO) {
sprintf((char *) &reply_data[4], "%s\n%s\n%s", FIRMWARE_VERSION, _prefs.node_name, _prefs.owner_info);
return 4 + strlen((char *) &reply_data[4]);
}
return 0; // unknown command
}
mesh::Packet *MyMesh::createSelfAdvert() {
uint8_t app_data[MAX_ADVERT_DATA_SIZE];
uint8_t app_data_len = _cli.buildAdvertData(ADV_TYPE_REPEATER, app_data);
return createAdvert(self_id, app_data, app_data_len);
}
File MyMesh::openAppend(const char *fname) {
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
return _fs->open(fname, FILE_O_WRITE);
#elif defined(RP2040_PLATFORM)
return _fs->open(fname, "a");
#else
return _fs->open(fname, "a", true);
#endif
}
static uint8_t max_loop_minimal[] = { 0, /* 1-byte */ 4, /* 2-byte */ 2, /* 3-byte */ 1 };
static uint8_t max_loop_moderate[] = { 0, /* 1-byte */ 2, /* 2-byte */ 1, /* 3-byte */ 1 };
static uint8_t max_loop_strict[] = { 0, /* 1-byte */ 1, /* 2-byte */ 1, /* 3-byte */ 1 };
bool MyMesh::isLooped(const mesh::Packet* packet, const uint8_t max_counters[]) {
uint8_t hash_size = packet->getPathHashSize();
uint8_t hash_count = packet->getPathHashCount();
uint8_t n = 0;
const uint8_t* path = packet->path;
while (hash_count > 0) { // count how many times this node is already in the path
if (self_id.isHashMatch(path, hash_size)) n++;
hash_count--;
path += hash_size;
}
return n >= max_counters[hash_size];
}
void MyMesh::sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size) {
TransportKey req_scope;
bool is_wildcard = recv_pkt_region != NULL && recv_pkt_region->isWildcard();
bool req_scope_known = recv_pkt_region != NULL && !is_wildcard
&& region_map.getTransportKeysFor(*recv_pkt_region, &req_scope, 1) > 0;
switch (mesh::chooseReplyScope(req_scope_known, is_wildcard, !default_scope.isNull())) {
case mesh::REPLY_SCOPE_REQUEST:
sendFloodScoped(req_scope, packet, delay_millis, path_hash_size); // reply with same scope as request
break;
case mesh::REPLY_SCOPE_DEFAULT:
// requester's scope is unknown: DIRECT request (no transport codes), or code matched no Region.
// un-scoped would be dropped at hop 0 by repeaters running flood.max.unscoped=0
sendFloodScoped(default_scope, packet, delay_millis, path_hash_size);
break;
case mesh::REPLY_SCOPE_NONE:
sendFlood(packet, delay_millis, path_hash_size); // send un-scoped
break;
}
}
bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
if (_prefs.disable_fwd) return false;
if (packet->isRouteFlood()
&& mesh::isFloodHopLimitExceeded(packet, _prefs.flood_max, _prefs.flood_max_unscoped, _prefs.flood_max_advert)) {
return false;
}
if (packet->isRouteFlood() && recv_pkt_region == NULL) {
MESH_DEBUG_PRINTLN("allowPacketForward: unknown transport code, or wildcard not allowed for FLOOD packet");
return false;
}
if (packet->isRouteFlood() && _prefs.loop_detect != LOOP_DETECT_OFF) {
const uint8_t* maximums;
if (_prefs.loop_detect == LOOP_DETECT_MINIMAL) {
maximums = max_loop_minimal;
} else if (_prefs.loop_detect == LOOP_DETECT_MODERATE) {
maximums = max_loop_moderate;
} else {
maximums = max_loop_strict;
}
if (isLooped(packet, maximums)) {
MESH_DEBUG_PRINTLN("allowPacketForward: FLOOD packet loop detected!");
return false;
}
}
// CUSTOM (TeTeHacko): keyless channel-hash deny list / throttle (`filter hash`).
// LAST of the checks here, so a throttle pass is only spent on a packet that
// would otherwise go out; and before takeForwardingRateLimit() in
// routeRecvPacket(), so a vetoed packet does not eat FairnessLimiter tokens.
if (filterHashDenied(packet)) {
MESH_DEBUG_PRINTLN("allowPacketForward: channel hash %02X on deny list", packet->payload[0]);
return false;
}
return true;
}
// CUSTOM (TeTeHacko): `fairness` -- denied-forward stats + current caps;
// `fairness on|off` -- runtime kill switch (persisted).
// `fairness grid` -- busiest deny buckets per category (what we shed).
// `fairness cap <group> <sender> <advert>` -- burst caps, 0 = default.
// `fairness refill <group_s> <sender_s> <advert_s>` -- refill interval secs, 0 = default.
// `fairness advert [<hours>|clear]` -- per-origin advert window (0 = off).
// `fairness dryrun [on|off]` -- count verdicts, forward anyway.
// `fairness air` -- estimated airtime shed per reason.
// All tuning is persisted, so a mast reboot keeps it.
bool MyMesh::fairnessHandleCommand(const char *command, char *reply, int reply_max) {
if (memcmp(command, "fairness", 8) != 0 || (command[8] != 0 && command[8] != ' ')) return false;
const char *arg = (command[8] == ' ') ? &command[9] : "";
if (strcmp(arg, "on") == 0 || strcmp(arg, "off") == 0) {
_prefs.fairness_enabled = (arg[1] == 'n') ? 1 : 0;
fairness_limiter.setBucketsEnabled(_prefs.fairness_enabled);
savePrefs();
snprintf(reply, reply_max, "OK - fairness %s", _prefs.fairness_enabled ? "on" : "off");
return true;
}
if (strcmp(arg, "dryrun") == 0 || strcmp(arg, "dryrun on") == 0 || strcmp(arg, "dryrun off") == 0) {
if (arg[6] == ' ') {
_prefs.fair_dry_run = (arg[8] == 'n') ? 1 : 0;
fairness_limiter.setDryRun(_prefs.fair_dry_run);
savePrefs();
}
snprintf(reply, reply_max, "%sfairness dry-run %s", arg[6] == ' ' ? "OK - " : "",
fairness_limiter.dryRun() ? "on" : "off");
return true;
}
if (strcmp(arg, "advert") == 0 || strncmp(arg, "advert ", 7) == 0) {
AdvertWindow& w = fairness_limiter.advertWindow();
if (strcmp(arg, "advert clear") == 0) {
w.clear();
} else if (arg[6] == ' ') {
char* end = NULL;
long h = strtol(arg + 7, &end, 10);
if (end == arg + 7 || *end != 0 || h < 0 || h > ADVERT_WINDOW_MAX_HOURS) {
snprintf(reply, reply_max, "Err - fairness advert <0-%d hours>|clear", ADVERT_WINDOW_MAX_HOURS);
return true;
}
_prefs.fair_advert_hours = (uint16_t)h;
w.setHours(_prefs.fair_advert_hours);
savePrefs();
}
snprintf(reply, reply_max, "advert window %uh%s, held %u (%us air), cache %d/%d, evicted %u",
(uint32_t)w.hours(), fairness_limiter.dryRun() ? " DRY-RUN" : "", fairness_limiter.deniedWindow(),
fairness_limiter.shedAirtimeMs(FAIR_SHED_WINDOW) / 1000, w.count(), w.capacity(), w.evicted());
return true;
}
if (strcmp(arg, "air") == 0) {
snprintf(reply, reply_max, "shed air%s: group %us sender %us advert %us window %us",
fairness_limiter.dryRun() ? " (dry-run, would be)" : "",
fairness_limiter.shedAirtimeMs(FAIR_SHED_GROUP) / 1000,
fairness_limiter.shedAirtimeMs(FAIR_SHED_SENDER) / 1000,
fairness_limiter.shedAirtimeMs(FAIR_SHED_ADVERT) / 1000,
fairness_limiter.shedAirtimeMs(FAIR_SHED_WINDOW) / 1000);
return true;
}
if (strcmp(arg, "grid") == 0) {
char grid[180];
fairness_limiter.formatGrid(grid, sizeof(grid));
snprintf(reply, reply_max, "%s", grid);
return true;
}
// strncmp, not memcmp: for the bare `fairness` command arg is the 1-byte ""
// literal, and memcmp(arg, "cap ", 4) would over-read it (UB, trips ASAN).
if (strncmp(arg, "cap ", 4) == 0) {
int g = 0, s = 0, a = 0;
if (sscanf(arg + 4, "%d %d %d", &g, &s, &a) != 3 || g < 0 || s < 0 || a < 0 || g > 255 || s > 255 || a > 255) {
strcpy(reply, "Err - fairness cap <group> <sender> <advert> (0=default)");
return true;
}
_prefs.fair_group_cap = (uint8_t)g;
_prefs.fair_sender_cap = (uint8_t)s;
_prefs.fair_advert_cap = (uint8_t)a;
fairness_limiter.setGroupCap(_prefs.fair_group_cap);
fairness_limiter.setSenderNormalCap(_prefs.fair_sender_cap);
fairness_limiter.setSenderLowCap(_prefs.fair_advert_cap);
savePrefs();
snprintf(reply, reply_max, "OK - cap group %u sender %u advert %u",
(uint32_t)fairness_limiter.groupCap(), (uint32_t)fairness_limiter.senderNormalCap(),
(uint32_t)fairness_limiter.senderLowCap());
return true;
}
if (strncmp(arg, "refill ", 7) == 0) {
int g = 0, s = 0, a = 0;
if (sscanf(arg + 7, "%d %d %d", &g, &s, &a) != 3 || g < 0 || s < 0 || a < 0 || g > 65535 || s > 65535 || a > 65535) {
strcpy(reply, "Err - fairness refill <group_s> <sender_s> <advert_s> (0=default)");
return true;
}
_prefs.fair_group_refill_s = (uint16_t)g;
_prefs.fair_sender_refill_s = (uint16_t)s;
_prefs.fair_advert_refill_s = (uint16_t)a;
// reschedule so the new interval takes effect from now
next_fair_group_refill = futureMillis(fairGroupRefillMs());
next_fair_sender_normal_refill = futureMillis(fairSenderRefillMs());
next_fair_sender_low_refill = futureMillis(fairAdvertRefillMs());
savePrefs();
snprintf(reply, reply_max, "OK - refill group %us sender %us advert %us",
(uint32_t)(fairGroupRefillMs() / 1000), (uint32_t)(fairSenderRefillMs() / 1000),
(uint32_t)(fairAdvertRefillMs() / 1000));
return true;
}
if (arg[0] != 0) {
strcpy(reply, "Err - fairness [on|off|grid|cap|refill|advert|dryrun|air]");
return true;
}
// bare `fairness` -- stats + current caps/refills
snprintf(reply, reply_max,
"fairness: %s%s, denied group %u/sender %u/advert %u/window %u; cap %u/%u/%u; refill %u/%u/%us",
_prefs.fairness_enabled ? "on" : "OFF", fairness_limiter.dryRun() ? " DRY-RUN" : "",
fairness_limiter.deniedGroup(), fairness_limiter.deniedSenderNormal(),
fairness_limiter.deniedSenderLow(), fairness_limiter.deniedWindow(),
(uint32_t)fairness_limiter.groupCap(), (uint32_t)fairness_limiter.senderNormalCap(),
(uint32_t)fairness_limiter.senderLowCap(),
(uint32_t)(fairGroupRefillMs() / 1000), (uint32_t)(fairSenderRefillMs() / 1000),
(uint32_t)(fairAdvertRefillMs() / 1000));
return true;
}
const char *MyMesh::getLogDateTime() {
static char tmp[32];
uint32_t now = getRTCClock()->getCurrentTime();
DateTime dt = DateTime(now);
sprintf(tmp, "%02d:%02d:%02d - %d/%d/%d U", dt.hour(), dt.minute(), dt.second(), dt.day(), dt.month(),
dt.year());
return tmp;
}
void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
#if PKTFEED_SIZE
// observer feed: raw bytes only exist here (pre-parse); committed in logRx
stagePktFeed(raw, len);
#endif
#if MESH_PACKET_LOGGING
Serial.print(getLogDateTime());
Serial.print(" RAW: ");
mesh::Utils::printHex(Serial, raw, len);
Serial.println();
#endif
}
void MyMesh::logRx(mesh::Packet *pkt, int len, float score) {
#if RXLOG_SIZE
// analyzer firehose: every parsed frame we hear. Called synchronously from
// Dispatcher::checkRecv (before any score-delay queueing), so getRSSI()/SNR
// on the packet still belong to THIS frame.
captureRx(pkt);
#endif
#if PKTFEED_SIZE
// observer feed: pair the staged raw bytes (from logRxRaw) with this frame
commitPktFeed(pkt);
#endif
#ifdef WITH_BRIDGE
if (_prefs.bridge_pkt_src == 1) {
bridge.sendPacket(pkt);
}
#endif
if (_logging) {
File f = openAppend(PACKET_LOG_FILE);
if (f) {
f.print(getLogDateTime());
f.printf(": RX, len=%d (type=%d, route=%s, payload_len=%d) SNR=%d RSSI=%d score=%d", len,
pkt->getPayloadType(), pkt->isRouteDirect() ? "D" : "F", pkt->payload_len,
(int)_radio->getLastSNR(), (int)_radio->getLastRSSI(), (int)(score * 1000));
if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
} else {
f.printf("\n");
}
f.close();
}
}
}
void MyMesh::logTx(mesh::Packet *pkt, int len) {
#ifdef WITH_BRIDGE
if (_prefs.bridge_pkt_src == 0) {
bridge.sendPacket(pkt);
}
#endif
if (_logging) {
File f = openAppend(PACKET_LOG_FILE);
if (f) {
f.print(getLogDateTime());
f.printf(": TX, len=%d (type=%d, route=%s, payload_len=%d)", len, pkt->getPayloadType(),
pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
if (pkt->getPayloadType() == PAYLOAD_TYPE_PATH || pkt->getPayloadType() == PAYLOAD_TYPE_REQ ||
pkt->getPayloadType() == PAYLOAD_TYPE_RESPONSE || pkt->getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
f.printf(" [%02X -> %02X]\n", (uint32_t)pkt->payload[1], (uint32_t)pkt->payload[0]);
} else {
f.printf("\n");
}
f.close();
}
}
}
void MyMesh::logTxFail(mesh::Packet *pkt, int len) {
if (_logging) {
File f = openAppend(PACKET_LOG_FILE);
if (f) {
f.print(getLogDateTime());
f.printf(": TX FAIL!, len=%d (type=%d, route=%s, payload_len=%d)\n", len, pkt->getPayloadType(),
pkt->isRouteDirect() ? "D" : "F", pkt->payload_len);
f.close();
}
}
}
int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
if (_prefs.rx_delay_base <= 0.0f) return 0;
return (int)((pow(_prefs.rx_delay_base, 0.85f - score) - 1.0) * air_time);
}
uint32_t MyMesh::getRetransmitDelay(const mesh::Packet *packet) {
uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.tx_delay_factor);
return getRNG()->nextInt(0, 5*t + 1);
}
uint32_t MyMesh::getDirectRetransmitDelay(const mesh::Packet *packet) {
uint32_t t = (_radio->getEstAirtimeFor(packet->getPathByteLen() + packet->payload_len + 2) * _prefs.direct_tx_delay_factor);
return getRNG()->nextInt(0, 5*t + 1);
}
mesh::DispatcherAction MyMesh::onRecvPacket(mesh::Packet* pkt) {
if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD);
} else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) {
if (region_map.getWildcard().flags & REGION_DENY_FLOOD) {
recv_pkt_region = NULL;
} else {
recv_pkt_region = &region_map.getWildcard();
}
} else {
recv_pkt_region = NULL;
}
return Mesh::onRecvPacket(pkt);
}
void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
uint8_t *data, size_t len) {
if (packet->getPayloadType() == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin
// client (unknown at this stage)
uint32_t timestamp;
memcpy(&timestamp, data, 4);
data[len] = 0; // ensure null terminator
uint8_t reply_len;
reply_path_len = 0xFF;
if (data[4] == 0 || data[4] >= ' ') { // is password, ie. a login request
reply_len = handleLoginReq(sender, secret, timestamp, &data[4], packet->isRouteFlood());
} else if (data[4] == ANON_REQ_TYPE_REGIONS && packet->isRouteDirect()) {
reply_len = handleAnonRegionsReq(sender, timestamp, &data[5]);
} else if (data[4] == ANON_REQ_TYPE_OWNER && packet->isRouteDirect()) {
reply_len = handleAnonOwnerReq(sender, timestamp, &data[5]);
} else if (data[4] == ANON_REQ_TYPE_BASIC && packet->isRouteDirect()) {
reply_len = handleAnonClockReq(sender, timestamp, &data[5]);
} else {
reply_len = 0; // unknown/invalid request type
}
if (reply_len == 0) return; // invalid request
// a DIRECT login can reply via the stored out_path, as onPeerDataRecv() does for REQ
ClientInfo* client = acl.getClient(sender.pub_key, PUB_KEY_SIZE);
bool have_out_path = client != NULL && client->out_path_len != OUT_PATH_UNKNOWN;
auto route = mesh::chooseReplyRoute(packet->isRouteFlood(), reply_path_len != 0xFF, have_out_path);
if (route == mesh::REPLY_ROUTE_PATH_RETURN) {
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
mesh::Packet* path = createPathReturn(sender, secret, packet->path, packet->path_len,
PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
return;
}
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, secret, reply_data, reply_len);
if (reply == NULL) return;
if (route == mesh::REPLY_ROUTE_DIRECT_SUPPLIED) {
sendDirect(reply, reply_path, reply_path_len, SERVER_RESPONSE_DELAY);
} else if (route == mesh::REPLY_ROUTE_DIRECT_OUT_PATH) {
sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
} else {
sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
}
}
}
int MyMesh::searchPeersByHash(const uint8_t *hash) {
int n = 0;
for (int i = 0; i < acl.getNumClients(); i++) {
if (acl.getClientByIdx(i)->id.isHashMatch(hash)) {
matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
}
}
return n;
}
void MyMesh::getPeerSharedSecret(uint8_t *dest_secret, int peer_idx) {
int i = matching_peer_indexes[peer_idx];
if (i >= 0 && i < acl.getNumClients()) {
// lookup pre-calculated shared_secret
memcpy(dest_secret, acl.getClientByIdx(i)->shared_secret, PUB_KEY_SIZE);
} else {
MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
}
}
static bool isShare(const mesh::Packet *packet) {
if (packet->hasTransportCodes()) {
return packet->transport_codes[0] == 0 && packet->transport_codes[1] == 0; // codes { 0, 0 } means 'send to nowhere'
}
return false;
}
void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32_t timestamp,
const uint8_t *app_data, size_t app_data_len) {
mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl
AdvertDataParser parser(app_data, app_data_len);
// if this a zero hop advert (and not via 'Share'), add it to neighbours
if (packet->getPathHashCount() == 0 && !isShare(packet)) {
if (parser.isValid() && parser.getType() == ADV_TYPE_REPEATER) { // just keep neigbouring Repeaters
putNeighbour(id, timestamp, packet->getSNR());
}
}
#if MAX_HEARD_NODES
// analyzer: record infrastructure nodes only -- REPEATERS and ROOM SERVERS,
// any hop count. Chat clients (and sensors) are deliberately NOT recorded:
// they are personal/mobile devices, so mapping them is a privacy concern and
// just churns the registry. The signature is already verified upstream
// (mesh::Mesh::onAdvertRecv only reaches here for valid adverts), so the
// identities/positions kept here are trustworthy.
uint8_t adv_type = parser.getType();
if (parser.isValid() && !isShare(packet)
&& (adv_type == ADV_TYPE_REPEATER || adv_type == ADV_TYPE_ROOM)) {
putHeardNode(id, timestamp, adv_type,
parser.hasLatLon() ? parser.getIntLat() : 0,
parser.hasLatLon() ? parser.getIntLon() : 0,
parser.hasName() ? parser.getName() : "",
packet->_snr, (int8_t)packet->getRSSI(), packet);
}
#endif
}
void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx, const uint8_t *secret,
uint8_t *data, size_t len) {
int i = matching_peer_indexes[sender_idx];
if (i < 0 || i >= acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
return;
}
ClientInfo* client = acl.getClientByIdx(i);
if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
uint32_t timestamp;
memcpy(&timestamp, data, 4);
if (timestamp > client->last_timestamp) { // prevent replay attacks
int reply_len = handleRequest(client, timestamp, &data[4], len - 4);
if (reply_len == 0) return; // invalid command
client->last_timestamp = timestamp;
client->last_activity = getRTCClock()->getCurrentTime();
if (packet->isRouteFlood()) {
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
mesh::Packet *path = createPathReturn(client->id, secret, packet->path, packet->path_len,
PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
if (path) sendFloodReply(path, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
} else {
mesh::Packet *reply =
createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, secret, reply_data, reply_len);
if (reply) {
if (client->out_path_len != OUT_PATH_UNKNOWN) { // we have an out_path, so send DIRECT
sendDirect(reply, client->out_path, client->out_path_len, SERVER_RESPONSE_DELAY);
} else {
sendFloodReply(reply, SERVER_RESPONSE_DELAY, packet->getPathHashSize());
}
}
}
} else {
MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
}
} else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5 && client->isAdmin()) { // a CLI command
uint32_t sender_timestamp;
memcpy(&sender_timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
uint8_t flags = (data[4] >> 2); // message attempt number, and other flags
if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA || flags == TXT_TYPE_CLI_COMMAND)) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported text type received: flags=%02x", (uint32_t)flags);
} else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks
bool is_retry = (sender_timestamp == client->last_timestamp);
client->last_timestamp = sender_timestamp;
client->last_activity = getRTCClock()->getCurrentTime();
// len can be > original length, but 'text' will be padded with zeroes
data[len] = 0; // need to make a C string again, with null terminator
if (flags == TXT_TYPE_PLAIN) { // for legacy CLI, send Acks
uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove
// to sender that we got it
mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
PUB_KEY_SIZE);
mesh::Packet *ack = createAck(ack_hash);
if (ack) {
if (client->out_path_len == OUT_PATH_UNKNOWN) {
sendFloodReply(ack, TXT_ACK_DELAY, packet->getPathHashSize());
} else {
sendDirect(ack, client->out_path, client->out_path_len, TXT_ACK_DELAY);
}
}
}
uint8_t temp[166];
char *command = (char *)&data[5];
char *reply = (char *)&temp[5];
if (is_retry) {
*reply = 0;
} else {
handleCommand(sender_timestamp, command, reply);
}
int text_len = strlen(reply);
if (text_len > 0) {
uint32_t timestamp = getRTCClock()->getCurrentTimeUnique();
if (timestamp == sender_timestamp) {
// WORKAROUND: the two timestamps need to be different, in the CLI view
timestamp++;
}
memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
temp[4] = (TXT_TYPE_CLI_DATA << 2); // NOTE: legacy was: TXT_TYPE_PLAIN
auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
if (reply) {
if (client->out_path_len == OUT_PATH_UNKNOWN) {
sendFloodReply(reply, CLI_REPLY_DELAY_MILLIS, packet->getPathHashSize());
} else {
sendDirect(reply, client->out_path, client->out_path_len, CLI_REPLY_DELAY_MILLIS);
}
}
}
} else {
MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
}
}
}
bool MyMesh::onPeerPathRecv(mesh::Packet *packet, int sender_idx, const uint8_t *secret, uint8_t *path,
uint8_t path_len, uint8_t extra_type, uint8_t *extra, uint8_t extra_len) {
// TODO: prevent replay attacks
int i = matching_peer_indexes[sender_idx];
if (i >= 0 && i < acl.getNumClients()) { // get from our known_clients table (sender SHOULD already be known in this context)
MESH_DEBUG_PRINTLN("PATH to client, path_len=%d", (uint32_t)path_len);
auto client = acl.getClientByIdx(i);
// store a copy of path, for sendDirect()
client->out_path_len = mesh::Packet::copyPath(client->out_path, path, path_len);
client->last_activity = getRTCClock()->getCurrentTime();
} else {
MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
}
// NOTE: no reciprocal path send!!
return false;
}
#define CTL_TYPE_NODE_DISCOVER_REQ 0x80
#define CTL_TYPE_NODE_DISCOVER_RESP 0x90
void MyMesh::onControlDataRecv(mesh::Packet* packet) {
uint8_t type = packet->payload[0] & 0xF0; // just test upper 4 bits
if (type == CTL_TYPE_NODE_DISCOVER_REQ && packet->payload_len >= 6
&& !_prefs.disable_fwd && discover_limiter.allow(rtc_clock.getCurrentTime())
&& !isHiddenNode() // this node wishes to NOT be discoverable
) {
int i = 1;
uint8_t filter = packet->payload[i++];
uint32_t tag;
memcpy(&tag, &packet->payload[i], 4); i += 4;
uint32_t since;
if (packet->payload_len >= i+4) { // optional since field
memcpy(&since, &packet->payload[i], 4); i += 4;
} else {
since = 0;
}
if ((filter & (1 << ADV_TYPE_REPEATER)) != 0 && _prefs.discovery_mod_timestamp >= since) {
bool prefix_only = packet->payload[0] & 1;
uint8_t data[6 + PUB_KEY_SIZE];
data[0] = CTL_TYPE_NODE_DISCOVER_RESP | ADV_TYPE_REPEATER; // low 4-bits for node type
data[1] = packet->_snr; // let sender know the inbound SNR ( x 4)
memcpy(&data[2], &tag, 4); // include tag from request, for client to match to
memcpy(&data[6], self_id.pub_key, PUB_KEY_SIZE);
auto resp = createControlData(data, prefix_only ? 6 + 8 : 6 + PUB_KEY_SIZE);
if (resp) {
sendZeroHop(resp, getRetransmitDelay(resp)*4, _prefs.path_hash_mode + 1); // apply random delay (widened x4), as multiple nodes can respond to this
}
}
} else if (type == CTL_TYPE_NODE_DISCOVER_RESP && packet->payload_len >= 6) {
uint8_t node_type = packet->payload[0] & 0x0F;
if (node_type != ADV_TYPE_REPEATER) {
return;
}
if (packet->payload_len < 6 + PUB_KEY_SIZE) {
MESH_DEBUG_PRINTLN("onControlDataRecv: DISCOVER_RESP pubkey too short: %d", (uint32_t)packet->payload_len);
return;
}
if (pending_discover_tag == 0 || millisHasNowPassed(pending_discover_until)) {
pending_discover_tag = 0;
return;
}
uint32_t tag;
memcpy(&tag, &packet->payload[2], 4);
if (tag != pending_discover_tag) {
return;
}
mesh::Identity id(&packet->payload[6]);
if (id.matches(self_id)) {
return;
}
putNeighbour(id, rtc_clock.getCurrentTime(), packet->getSNR());
}
}
void MyMesh::sendNodeDiscoverReq() {
uint8_t data[10];
data[0] = CTL_TYPE_NODE_DISCOVER_REQ; // prefix_only=0
data[1] = (1 << ADV_TYPE_REPEATER);
getRNG()->random(&data[2], 4); // tag
memcpy(&pending_discover_tag, &data[2], 4);
pending_discover_until = futureMillis(60000);
uint32_t since = 0;
memcpy(&data[6], &since, 4);
auto pkt = createControlData(data, sizeof(data));
if (pkt) {
sendZeroHop(pkt, (uint32_t)0, _prefs.path_hash_mode + 1); // přetypování nutné: holá 0 je i null pointer pro transport_codes přetížení
}
}
MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondClock &ms, mesh::RNG &rng,
mesh::RTCClock &rtc, mesh::MeshTables &tables)
: mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32), tables),
region_map(key_store), temp_map(key_store),
_cli(board, rtc, sensors, region_map, acl, &_prefs, this),
telemetry(MAX_PACKET_PAYLOAD - 4),
discover_limiter(4, 120), // max 4 every 2 minutes
anon_limiter(4, 180) // max 4 every 3 minutes
#if defined(WITH_RS232_BRIDGE)
, bridge(&_prefs, WITH_RS232_BRIDGE, _mgr, &rtc)
#endif
#if defined(WITH_ESPNOW_BRIDGE)
, bridge(&_prefs, _mgr, &rtc)
#endif
{
last_millis = 0;
uptime_millis = 0;
next_local_advert = next_flood_advert = 0;
next_fair_sender_normal_refill = next_fair_sender_low_refill = next_fair_group_refill = 0;
dirty_contacts_expiry = 0;
set_radio_at = revert_radio_at = 0;
_logging = false;
region_load_active = false;
recv_pkt_region = NULL;
#if MAX_NEIGHBOURS
memset(neighbours, 0, sizeof(neighbours));
#endif
#if MAX_HEARD_NODES
memset(heard_nodes, 0, sizeof(heard_nodes));
#endif
#if RXLOG_SIZE
memset(rxlog_ring, 0, sizeof(rxlog_ring));
rxlog_head = 0;
rxlog_next_seq = 1; // seq 0 is reserved for "empty slot" / initial cursor
#endif
#if PKTFEED_SIZE
memset(pktfeed_ring, 0, sizeof(pktfeed_ring));
pktfeed_head = 0;
pktfeed_next_seq = 1; // seq 0 is reserved for "empty slot" / initial cursor
pktfeed_stage_len = 0;
#endif
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
channelsInit(); // registers the bot channel and/or the filter channels
#endif
// defaults
_prefs.airtime_factor = 1.0;
#ifdef AIRTIME_FACTOR_DEFAULT // CUSTOM (TeTeHacko): e.g. 9 = 10 % duty cycle (meshcore.cz)
_prefs.airtime_factor = AIRTIME_FACTOR_DEFAULT;
#endif
_prefs.rx_delay_base = 0.0f; // turn off by default, was 10.0;
_prefs.tx_delay_factor = 0.5f; // was 0.25f
_prefs.direct_tx_delay_factor = 0.3f; // was 0.2
StrHelper::strncpy(_prefs.node_name, ADVERT_NAME, sizeof(_prefs.node_name));
_prefs.node_lat = ADVERT_LAT;
_prefs.node_lon = ADVERT_LON;
StrHelper::strncpy(_prefs.password, ADMIN_PASSWORD, sizeof(_prefs.password));
_prefs.freq = LORA_FREQ;
_prefs.sf = LORA_SF;
_prefs.bw = LORA_BW;
_prefs.cr = LORA_CR;
_prefs.tx_power_dbm = LORA_TX_POWER;
// CUSTOM (TeTeHacko): 2-byte path hashes by default. Upstream leaves this
// field unset, so a fresh node came up at mode 0 = 1 byte per hop -- which
// nobody on the CZ mesh runs any more, and every new install then needed a
// manual `set path.hash.mode 1`.
//
// NOTE this is the PATH hash, not PATH_HASH_SIZE. It is used as
// sendFlood(..., path_hash_mode + 1), i.e. bytes each hop appends to the path
// while flooding, and the size travels in the packet: Packet.h:85 packs it
// into the top 2 bits of path_len and Mesh.cpp:93 matches with
// getPathHashSize(), so mixed-mode nodes still route for each other.
// PATH_HASH_SIZE (1) is a different field -- the destination and channel hash
// in Mesh.cpp:458/548 -- and changing THAT would break the wire format
// against every other node in the mesh.
#ifndef PATH_HASH_MODE_DEFAULT
#define PATH_HASH_MODE_DEFAULT 1 // 1 = 2 bytes per hop
#endif
_prefs.path_hash_mode = PATH_HASH_MODE_DEFAULT;
// CUSTOM (TeTeHacko): overridable so a node can be built to SHIP SILENT.
// ENABLE_ADVERT_ON_BOOT only suppresses the advert at boot, not the periodic
// timer -- with the upstream defaults an `erase`d node starts advertising
// within 2 minutes. For a repeater that is going somewhere unreachable that
// is the wrong way round: it must stay quiet until somebody deliberately
// turns it on, and a reboot on the mast must not undo that.
// Set both to 0 in the deployment envs; 0 = off (CommonCLI.cpp:615-630).
#ifndef ADVERT_INTERVAL_DEFAULT
#define ADVERT_INTERVAL_DEFAULT 1 // *2 = 2 minutes, upstream default
#endif
#ifndef FLOOD_ADVERT_INTERVAL_DEFAULT
#define FLOOD_ADVERT_INTERVAL_DEFAULT 47 // hours
#endif
#ifndef DISABLE_FWD_DEFAULT
#define DISABLE_FWD_DEFAULT 0 // 0 = repeat on
#endif
_prefs.advert_interval = ADVERT_INTERVAL_DEFAULT;
_prefs.flood_advert_interval = FLOOD_ADVERT_INTERVAL_DEFAULT;
_prefs.disable_fwd = DISABLE_FWD_DEFAULT;
_prefs.flood_max = 64;
_prefs.flood_max_unscoped = 64;
_prefs.flood_max_advert = 8;
// CUSTOM (TeTeHacko): FairnessLimiter on by default; `fairness off` is the
// runtime kill switch (persisted, so it survives a reboot on the mast).
#ifndef FAIRNESS_ENABLED_DEFAULT
#define FAIRNESS_ENABLED_DEFAULT 1
#endif
_prefs.fairness_enabled = FAIRNESS_ENABLED_DEFAULT;
filter_hash_dropped = 0;
filter_hash_passed = 0;
_prefs.interference_threshold = 0; // disabled
_prefs.cad_enabled = 0; // hardware CAD before TX (off by default; 'set cad on')
_prefs.loop_detect = LOOP_DETECT_MINIMAL;
// bridge defaults
_prefs.bridge_enabled = 1; // enabled
_prefs.bridge_delay = 500; // milliseconds
_prefs.bridge_pkt_src = 0; // logTx
_prefs.bridge_baud = 115200; // baud rate
_prefs.bridge_channel = 1; // channel 1
StrHelper::strncpy(_prefs.bridge_secret, "LVSITANOS", sizeof(_prefs.bridge_secret));
// GPS defaults
_prefs.gps_enabled = 0;
_prefs.gps_interval = 0;
_prefs.advert_loc_policy = ADVERT_LOC_PREFS;
_prefs.adc_multiplier = 0.0f; // 0.0f means use default board multiplier
#if defined(USE_SX1262) || defined(USE_SX1268)
#ifdef SX126X_RX_BOOSTED_GAIN
_prefs.rx_boosted_gain = SX126X_RX_BOOSTED_GAIN;
#else
_prefs.rx_boosted_gain = 1; // enabled by default;
#endif
#endif
_prefs.radio_fem_rxgain = 1;
_prefs.radio_fem_txgain = 0;
pending_discover_tag = 0;
pending_discover_until = 0;
memset(default_scope.key, 0, sizeof(default_scope.key));
}
void MyMesh::begin(FILESYSTEM *fs) {
mesh::Mesh::begin();
_fs = fs;
// load persisted prefs
_cli.loadPrefs(_fs);
acl.load(_fs, self_id);
// Apply any persisted runtime cap tuning (0 = build default). Do this before
// the first refill so the initial token respects a raised cap.
fairness_limiter.setGroupCap(_prefs.fair_group_cap);
fairness_limiter.setSenderNormalCap(_prefs.fair_sender_cap);
fairness_limiter.setSenderLowCap(_prefs.fair_advert_cap);
fairness_limiter.setBucketsEnabled(_prefs.fairness_enabled);
fairness_limiter.setDryRun(_prefs.fair_dry_run);
fairness_limiter.advertWindow().setHours(_prefs.fair_advert_hours);
// Fairness buckets start with just ONE token (not the full cap): a repeater
// stuck in a crash loop must not hand out a fresh burst on every boot.
fairness_limiter.refillSenderNormal();
fairness_limiter.refillSenderLow();
fairness_limiter.refillGroup();
next_fair_sender_normal_refill = futureMillis(fairSenderRefillMs());
next_fair_sender_low_refill = futureMillis(fairAdvertRefillMs());
next_fair_group_refill = futureMillis(fairGroupRefillMs());
// TODO: key_store.begin();
#ifdef DEFAULT_REGIONS
// CUSTOM (TeTeHacko): a node that never saved regions gets DEFAULT_REGIONS
// (e.g. "cz,cs", meshcore.cz/regiony) -- as if `region put` each + `region
// save`. Once /regions2 exists the operator's list wins, removals included.
bool regions_saved = _fs->exists("/regions2");
#endif
region_map.load(_fs);
#ifdef DEFAULT_REGIONS
if (!regions_saved && region_map.putDefaults(DEFAULT_REGIONS) > 0) {
region_map.save(_fs);
}
#endif
// establish default-scope
{
RegionEntry* r = region_map.getDefaultRegion();
if (r) {
region_map.getTransportKeysFor(*r, &default_scope, 1);
} else {
#ifdef DEFAULT_FLOOD_SCOPE_NAME
r = region_map.findByName(DEFAULT_FLOOD_SCOPE_NAME);
if (r == NULL) {
r = region_map.putRegion(DEFAULT_FLOOD_SCOPE_NAME, 0); // auto-create the default scope region
if (r) { r->flags = 0; } // Allow-flood
}
if (r) {
region_map.setDefaultRegion(r);
region_map.getTransportKeysFor(*r, &default_scope, 1);
}
#endif
}
}
#if defined(WITH_BRIDGE)
if (_prefs.bridge_enabled) {
bridge.begin();
}
#endif
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
radio_driver.setTxPower(_prefs.tx_power_dbm);
radio_driver.setRxBoostedGainMode(_prefs.rx_boosted_gain);
MESH_DEBUG_PRINTLN("RX Boosted Gain Mode: %s",
radio_driver.getRxBoostedGainMode() ? "Enabled" : "Disabled");
board.attachDynamicPrefs(_prefs.getCustom());
updateAdvertTimer();
updateFloodAdvertTimer();
board.setAdcMultiplier(_prefs.adc_multiplier);
#if ENV_INCLUDE_GPS == 1
applyGpsPrefs();
#endif
}
void MyMesh::sendFloodScoped(const TransportKey& scope, mesh::Packet* pkt, uint32_t delay_millis, uint8_t path_hash_size) {
if (scope.isNull()) {
sendFlood(pkt, delay_millis, path_hash_size);
} else {
uint16_t codes[2];
codes[0] = scope.calcTransportCode(pkt);
codes[1] = 0; // REVISIT: set to 'home' Region, for sender/return region?
sendFlood(pkt, codes, delay_millis, path_hash_size);
}
}
void MyMesh::applyTempRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, int timeout_mins) {
set_radio_at = futureMillis(2000); // give CLI reply some time to be sent back, before applying temp radio params
pending_freq = freq;
pending_bw = bw;
pending_sf = sf;
pending_cr = cr;
revert_radio_at = futureMillis(2000 + timeout_mins * 60 * 1000); // schedule when to revert radio params
}
bool MyMesh::formatFileSystem() {
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
return InternalFS.format();
#elif defined(RP2040_PLATFORM)
return LittleFS.format();
#elif defined(ESP32)
return SPIFFS.format();
#else
#error "need to implement file system erase"
return false;
#endif
}
void MyMesh::sendSelfAdvertisement(int delay_millis, bool flood) {
mesh::Packet *pkt = createSelfAdvert();
if (pkt) {
if (flood) {
sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
} else {
sendZeroHop(pkt, delay_millis, _prefs.path_hash_mode + 1);
}
} else {
MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
}
}
void MyMesh::updateAdvertTimer() {
if (_prefs.advert_interval > 0) { // schedule local advert timer
next_local_advert = futureMillis(((uint32_t)_prefs.advert_interval) * 2 * 60 * 1000);
} else {
next_local_advert = 0; // stop the timer
}
}
void MyMesh::updateFloodAdvertTimer() {
if (_prefs.flood_advert_interval > 0) { // schedule flood advert timer
next_flood_advert = futureMillis(((uint32_t)_prefs.flood_advert_interval) * 60 * 60 * 1000);
} else {
next_flood_advert = 0; // stop the timer
}
}
void MyMesh::dumpLogFile() {
#if defined(RP2040_PLATFORM)
File f = _fs->open(PACKET_LOG_FILE, "r");
#else
File f = _fs->open(PACKET_LOG_FILE);
#endif
if (f) {
while (f.available()) {
int c = f.read();
if (c < 0) break;
Serial.print((char)c);
}
f.close();
}
}
void MyMesh::setTxPower(int8_t power_dbm) {
radio_driver.setTxPower(power_dbm);
}
bool MyMesh::setRxBoostedGain(bool enable) {
return radio_driver.setRxBoostedGainMode(enable);
}
#if defined(USE_LR2021)
bool MyMesh::configSideDetectors(const uint8_t sideDetSFs[], uint8_t num, float bw) {
return radio_driver.configSideDetectors(sideDetSFs, num, bw);
}
#endif
void MyMesh::formatNeighborsReply(char *reply) {
char *dp = reply;
#if MAX_NEIGHBOURS
// create copy of neighbours list, skipping empty entries so we can sort it separately from main list
int16_t neighbours_count = 0;
NeighbourInfo* sorted_neighbours[MAX_NEIGHBOURS];
for (int i = 0; i < MAX_NEIGHBOURS; i++) {
auto neighbour = &neighbours[i];
if (neighbour->heard_timestamp > 0) {
sorted_neighbours[neighbours_count] = neighbour;
neighbours_count++;
}
}
// sort neighbours newest to oldest
std::sort(sorted_neighbours, sorted_neighbours + neighbours_count, [](const NeighbourInfo* a, const NeighbourInfo* b) {
return a->heard_timestamp > b->heard_timestamp; // desc
});
for (int i = 0; i < neighbours_count && dp - reply < 134; i++) {
NeighbourInfo *neighbour = sorted_neighbours[i];
// add new line if not first item
if (i > 0) *dp++ = '\n';
char hex[10];
// get 4 bytes of neighbour id as hex
mesh::Utils::toHex(hex, neighbour->id.pub_key, 4);
// add next neighbour
uint32_t secs_ago = getRTCClock()->getCurrentTime() - neighbour->heard_timestamp;
sprintf(dp, "%s:%d:%d", hex, secs_ago, neighbour->snr);
while (*dp)
dp++; // find end of string
}
#endif
if (dp == reply) { // no neighbours, need empty response
strcpy(dp, "-none-");
dp += 6;
}
*dp = 0; // null terminator
}
void MyMesh::removeNeighbor(const uint8_t *pubkey, int key_len) {
#if MAX_NEIGHBOURS
for (int i = 0; i < MAX_NEIGHBOURS; i++) {
NeighbourInfo *neighbour = &neighbours[i];
if (memcmp(neighbour->id.pub_key, pubkey, key_len) == 0) {
neighbours[i] = NeighbourInfo(); // clear neighbour entry
}
}
#endif
}
void MyMesh::startRegionsLoad() {
temp_map.resetFrom(region_map); // rebuild regions in a temp instance
memset(load_stack, 0, sizeof(load_stack));
load_stack[0] = &temp_map.getWildcard();
region_load_active = true;
}
bool MyMesh::saveRegions() {
return region_map.save(_fs);
}
void MyMesh::onDefaultRegionChanged(const RegionEntry* r) {
if (r) {
region_map.getTransportKeysFor(*r, &default_scope, 1);
} else {
memset(default_scope.key, 0, sizeof(default_scope.key));
}
}
void MyMesh::formatStatsReply(char *reply) {
StatsFormatHelper::formatCoreStats(reply, board, *_ms, _err_flags, _mgr);
}
void MyMesh::formatRadioStatsReply(char *reply) {
StatsFormatHelper::formatRadioStats(reply, _radio, radio_driver, getTotalAirTime(), getReceiveAirTime());
}
void MyMesh::formatPacketStatsReply(char *reply) {
StatsFormatHelper::formatPacketStats(reply, radio_driver, getNumSentFlood(), getNumSentDirect(),
getNumRecvFlood(), getNumRecvDirect(),
getNumTxStartFail(), getNumTxTimeout());
}
void MyMesh::saveIdentity(const mesh::LocalIdentity &new_id) {
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
IdentityStore store(*_fs, "");
#elif defined(ESP32)
IdentityStore store(*_fs, "/identity");
#elif defined(RP2040_PLATFORM)
IdentityStore store(*_fs, "/identity");
#else
#error "need to define saveIdentity()"
#endif
store.save("_main", new_id);
}
void MyMesh::clearStats() {
radio_driver.resetStats();
resetStats();
((SimpleMeshTables *)getTables())->resetStats();
}
void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply, int reply_max) {
if (region_load_active) {
if (StrHelper::isBlank(command)) { // empty/blank line, signal to terminate 'load' operation
region_map = temp_map; // copy over the temp instance as new current map
region_load_active = false;
sprintf(reply, "OK - loaded %d regions", region_map.getCount());
} else {
char *np = command;
while (*np == ' ') np++; // skip indent
int indent = np - command;
char *ep = np;
while (RegionMap::is_name_char(*ep)) ep++;
if (*ep) { *ep++ = 0; } // set null terminator for end of name
while (*ep && *ep != 'F') ep++; // look for (optional) flags
if (indent > 0 && indent < 8 && strlen(np) > 0) {
auto parent = load_stack[indent - 1];
if (parent) {
auto old = region_map.findByName(np);
auto nw = temp_map.putRegion(np, parent->id, old ? old->id : 0); // carry-over the current ID (if name already exists)
if (nw) {
nw->flags = old ? old->flags : (*ep == 'F' ? 0 : REGION_DENY_FLOOD); // carry-over flags from curr
load_stack[indent] = nw; // keep pointers to parent regions, to resolve parent_id's
}
}
}
reply[0] = 0;
}
return;
}
while (*command == ' ') command++; // skip leading spaces
#ifdef BENCH_FAULT_CMD
// Bench builds only (PLATFORMIO_BUILD_FLAGS=-D BENCH_FAULT_CMD): crash on
// purpose, to prove the hardfault record survives the reset and gets printed.
if (strcmp(command, "hardfault") == 0) {
__builtin_trap(); // UDF -> UsageFault, escalates to HardFault
}
#endif
if (strlen(command) > 4 && command[2] == '|') { // optional prefix (for companion radio CLI)
memcpy(reply, command, 3); // reflect the prefix back
reply += 3;
command += 3;
}
// handle ACL related commands
if (memcmp(command, "setperm ", 8) == 0) { // format: setperm {pubkey-hex} {permissions-int8}
char* hex = &command[8];
char* sp = strchr(hex, ' '); // look for separator char
if (sp == NULL) {
strcpy(reply, "Err - bad params");
} else {
*sp++ = 0; // replace space with null terminator
uint8_t pubkey[PUB_KEY_SIZE];
int hex_len = min(sp - hex, PUB_KEY_SIZE*2);
if (mesh::Utils::fromHex(pubkey, hex_len / 2, hex)) {
uint8_t perms = atoi(sp);
if (acl.applyPermissions(self_id, pubkey, hex_len / 2, perms)) {
dirty_contacts_expiry = futureMillis(LAZY_CONTACTS_WRITE_DELAY); // trigger acl.save()
strcpy(reply, "OK");
} else {
strcpy(reply, "Err - invalid params");
}
} else {
strcpy(reply, "Err - bad pubkey");
}
}
} else if (sender_timestamp == 0 && strcmp(command, "get acl") == 0) {
Serial.println("ACL:");
for (int i = 0; i < acl.getNumClients(); i++) {
auto c = acl.getClientByIdx(i);
if (c->permissions == 0) continue; // skip deleted (or guest) entries
Serial.printf("%02X ", c->permissions);
mesh::Utils::printHex(Serial, c->id.pub_key, PUB_KEY_SIZE);
Serial.printf("\n");
}
reply[0] = 0;
} else if (memcmp(command, "discover.neighbors", 18) == 0) {
const char* sub = command + 18;
while (*sub == ' ') sub++;
if (*sub != 0) {
strcpy(reply, "Err - discover.neighbors has no options");
} else {
sendNodeDiscoverReq();
strcpy(reply, "OK - Discover sent");
}
#if MAX_HEARD_NODES
} else if (memcmp(command, "nodes", 5) == 0 && (command[5] == 0 || command[5] == ' ')) {
// analyzer: paged dump of heard repeaters/room servers (for a map/bridge).
// Page size = caller's reply capacity: local console passes ~1000 (fewer BLE
// round trips), the mesh admin CLI keeps the default 150 (one LoRa packet).
uint16_t offset = (command[5] == ' ') ? (uint16_t) atoi(&command[6]) : 0;
formatNodesReply(reply, reply_max, offset);
#endif
#if RXLOG_SIZE
} else if (memcmp(command, "rxlog", 5) == 0 && (command[5] == 0 || command[5] == ' ')) {
// analyzer: paged firehose of every frame heard, since <cursor> (0 = all)
uint32_t cursor = (command[5] == ' ') ? (uint32_t) strtoul(&command[6], NULL, 10) : 0;
formatRxLogReply(reply, reply_max, cursor);
#endif
#if PKTFEED_SIZE
} else if (memcmp(command, "pktlog", 6) == 0 && (command[6] == 0 || command[6] == ' ')) {
// observer feed: paged raw frames heard, since <cursor> (0 = all)
uint32_t cursor = (command[6] == ' ') ? (uint32_t) strtoul(&command[7], NULL, 10) : 0;
formatPktFeedReply(reply, reply_max, cursor);
#endif
} else{
#ifdef BOT_CHANNEL_PSK
// CUSTOM (TeTeHacko): `bot` — read-only channel bot diagnostics. See ChannelBot.h.
if (botHandleCommand(command, reply)) return;
#endif
// CUSTOM (TeTeHacko): `filter hash [add|del <hex>|clear]` — keyless channel-hash
// deny list. Before filterHandleCommand(), which would claim any `filter ...`.
if (filterHashHandleCommand(command, reply, reply_max)) return;
// CUSTOM (TeTeHacko): `filter dryrun [on|off]`, `filter age [<min>|off]`. Also
// before filterHandleCommand(), which would take `dryrun`/`age` for names.
if (filterMiscHandleCommand(command, reply, reply_max)) return;
#ifdef FILTER_CHANNEL_PSKS
// CUSTOM (TeTeHacko): `filter add|del|list|clear` — runtime deny list for
// channel messages this repeater refuses to forward. See ChannelFilter.h.
if (filterHandleCommand(command, reply, reply_max)) return;
#endif
// CUSTOM (TeTeHacko): `fairness [on|off|grid|cap ...|refill ...]` — rate limiter.
if (fairnessHandleCommand(command, reply, reply_max)) return;
// CUSTOM (TeTeHacko): `blink [n]` — flash the LED to identify this board.
// Outside the BLE guard on purpose: a USB-only build needs it just as much,
// since a board with no data cable and no BLE cannot be identified at all.
extern bool identHandleCommand(const char* command, char* reply);
if (identHandleCommand(command, reply)) return;
// CUSTOM (TeTeHacko): `dfu [uf2|serial|ota]` — deterministic reboot into the
// bootloader (GPREGRET magic, same as the core's enterUf2Dfu). Local only.
extern bool dfuHandleCommand(uint32_t sender_timestamp, const char* command, char* reply);
if (dfuHandleCommand(sender_timestamp, command, reply)) return;
// CUSTOM (TeTeHacko): `txpwr [dBm]` — set output power and report RadioLib's
// verdict, which `set tx` swallows. See main.cpp.
extern bool txPwrHandleCommand(const char* command, char* reply);
if (txPwrHandleCommand(command, reply)) return;
#ifdef RADIO_DIAG
// CUSTOM (TeTeHacko): `radiostat` / `radiokick` -- see main.cpp.
extern bool radioDiagHandleCommand(const char* command, char* reply);
if (radioDiagHandleCommand(command, reply)) return;
#endif
#ifdef PIN_DIAG
// CUSTOM (TeTeHacko): `dio1` — is the DIO1 IRQ line alive, and if not, which
// END of it is broken? Salvage diagnostics, see main.cpp.
extern bool pinDiagHandleCommand(const char* command, char* reply);
if (pinDiagHandleCommand(command, reply)) return;
#endif
#if defined(BLE_PIN_CODE) && defined(NRF52_PLATFORM)
// CUSTOM (TeTeHacko): `ble on|off|ble` — implemented in main.cpp (BLE console).
// Available from serial, the BLE console and remotely via MC (admin remote CLI).
extern bool bleConsoleHandleCommand(const char* command, char* reply);
if (bleConsoleHandleCommand(command, reply)) return;
#endif
_cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
}
}
void MyMesh::loop() {
#ifdef WITH_BRIDGE
bridge.loop();
#endif
mesh::Mesh::loop();
// Fairness limiter refilling. The `else if` chain keeps the three timers from
// aligning on one loop pass; each adds ONE token per bucket per interval.
if (next_fair_sender_normal_refill && millisHasNowPassed(next_fair_sender_normal_refill)) {
fairness_limiter.refillSenderNormal();
next_fair_sender_normal_refill = futureMillis(fairSenderRefillMs());
} else if (next_fair_sender_low_refill && millisHasNowPassed(next_fair_sender_low_refill)) {
fairness_limiter.refillSenderLow();
next_fair_sender_low_refill = futureMillis(fairAdvertRefillMs());
} else if (next_fair_group_refill && millisHasNowPassed(next_fair_group_refill)) {
fairness_limiter.refillGroup();
next_fair_group_refill = futureMillis(fairGroupRefillMs());
}
if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
mesh::Packet *pkt = createSelfAdvert();
uint32_t delay_millis = 0;
if (pkt) sendFloodScoped(default_scope, pkt, delay_millis, _prefs.path_hash_mode + 1);
updateFloodAdvertTimer(); // schedule next flood advert
updateAdvertTimer(); // also schedule local advert (so they don't overlap)
} else if (next_local_advert && millisHasNowPassed(next_local_advert)) {
// Šířku předat i tady: tenhle periodický advert NEJDE přes
// sendSelfAdvertisement(), takže by ji jinak minul — a je to přesně on, kdo
// se každé `advert.interval` minuty hlásil na jeden bajt.
mesh::Packet *pkt = createSelfAdvert();
if (pkt) sendZeroHop(pkt, (uint32_t)0, _prefs.path_hash_mode + 1); // (uint32_t) viz výš
updateAdvertTimer(); // schedule next local advert
}
if (set_radio_at && millisHasNowPassed(set_radio_at)) { // apply pending (temporary) radio params
set_radio_at = 0; // clear timer
radio_driver.setParams(pending_freq, pending_bw, pending_sf, pending_cr);
MESH_DEBUG_PRINTLN("Temp radio params");
}
if (revert_radio_at && millisHasNowPassed(revert_radio_at)) { // revert radio params to orig
revert_radio_at = 0; // clear timer
radio_driver.setParams(_prefs.freq, _prefs.bw, _prefs.sf, _prefs.cr);
MESH_DEBUG_PRINTLN("Radio params restored");
}
// is pending dirty contacts write needed?
if (dirty_contacts_expiry && millisHasNowPassed(dirty_contacts_expiry)) {
acl.save(_fs);
dirty_contacts_expiry = 0;
}
// update uptime
uint32_t now = millis();
uptime_millis += now - last_millis;
last_millis = now;
}
// CUSTOM (TeTeHacko): channel module method bodies. Included here, at the very
// bottom, so they see the complete MyMesh definition (same convention the Solo
// firmware uses for its own bot). Order matters: ChannelCommon.h defines the
// helpers (chan_list_has, channelAddFromPsk) the other two use.
#include "ChannelCommon.h"
#include "ChannelFilter.h"
#include "ChannelBot.h"
// To check if there is pending work
bool MyMesh::hasPendingWork() const {
#if defined(WITH_BRIDGE)
if (bridge.isRunning()) return true; // bridge needs WiFi radio, can't sleep
#endif
return _mgr->getOutboundTotal() > 0;
}