Harden retry, power, and companion behavior
This commit is contained in:
1 parent
67cfc30588
commit
57cc977e58
23 files changed
+938
-115
No files matched your search
+1
-1
@@ -13,7 +13,7 @@ namespace mesh {
|
||||
#define MIN_TX_BUDGET_AIRTIME_DIV 2 // require at least 1/N of estimated airtime as budget before TX
|
||||
|
||||
#ifndef NOISE_FLOOR_CALIB_INTERVAL
|
||||
#define NOISE_FLOOR_CALIB_INTERVAL 30000 // request at most every 30 seconds
|
||||
#define NOISE_FLOOR_CALIB_INTERVAL 2000 // refresh every 2 seconds
|
||||
#endif
|
||||
|
||||
void Dispatcher::begin() {
|
||||
|
||||
+283
-62
@@ -29,6 +29,9 @@ static const uint8_t DIRECT_RETRY_MAX_ATTEMPTS_HARD_MAX = 21;
|
||||
static const uint8_t FLOOD_RETRY_MAX_ATTEMPTS_DEFAULT = 15;
|
||||
static const uint8_t FLOOD_RETRY_MAX_ATTEMPTS_HARD_MAX = 15;
|
||||
static const uint8_t FLOOD_RETRY_MAX_PATH_DEFAULT = 1;
|
||||
static const uint32_t ORIGIN_ADVERT_RETRY_EXTRA_DELAY_MS = 60UL * 1000UL;
|
||||
static const uint32_t RECENT_ADVERT_MAX_AGE_SECONDS = 6UL * 60UL * 60UL;
|
||||
static const uint32_t FORWARDED_ADVERT_ECHO_WATCH_MS = 5UL * 60UL * 1000UL;
|
||||
|
||||
static bool hasValidEncryptedPayloadLength(uint16_t payload_len, uint16_t clear_prefix_len) {
|
||||
const uint16_t overhead = clear_prefix_len + CIPHER_MAC_SIZE;
|
||||
@@ -150,6 +153,7 @@ void Mesh::begin() {
|
||||
_active_flood_retry_count = 0;
|
||||
_waiting_direct_retry_count = 0;
|
||||
_waiting_flood_retry_count = 0;
|
||||
_next_recent_advert_echo = 0;
|
||||
_next_direct_retry_timeout = 0;
|
||||
_next_flood_retry_timeout = 0;
|
||||
for (int i = 0; i < MAX_DIRECT_RETRY_SLOTS; i++) {
|
||||
@@ -183,10 +187,20 @@ void Mesh::begin() {
|
||||
memset(_flood_retries[i].retry_key, 0, sizeof(_flood_retries[i].retry_key));
|
||||
_flood_retries[i].priority = 0;
|
||||
_flood_retries[i].progress_marker = 0;
|
||||
_flood_retries[i].self_advert = false;
|
||||
_flood_retries[i].waiting_final_echo = false;
|
||||
_flood_retries[i].queued = false;
|
||||
_flood_retries[i].active = false;
|
||||
}
|
||||
for (int i = 0; i < MAX_RECENT_ADVERT_ECHOS; i++) {
|
||||
memset(_recent_advert_echoes[i].packet_hash, 0,
|
||||
sizeof(_recent_advert_echoes[i].packet_hash));
|
||||
_recent_advert_echoes[i].advert_timestamp = 0;
|
||||
_recent_advert_echoes[i].watch_started_at = 0;
|
||||
_recent_advert_echoes[i].progress_marker = 0;
|
||||
_recent_advert_echoes[i].confirmed = false;
|
||||
_recent_advert_echoes[i].valid = false;
|
||||
}
|
||||
Dispatcher::begin();
|
||||
#if defined(ENABLE_OTA)
|
||||
uint32_t my_tid = 0;
|
||||
@@ -327,12 +341,21 @@ void Mesh::loop() {
|
||||
|
||||
bool Mesh::allowPacketTransmit(const Packet* packet) const {
|
||||
#if defined(ENABLE_OTA)
|
||||
if (packet != NULL && packet->getPayloadType() == PAYLOAD_TYPE_OTA) {
|
||||
return isTempRadioActive();
|
||||
if (packet != NULL && packet->getPayloadType() == PAYLOAD_TYPE_OTA
|
||||
&& !isTempRadioActive()) {
|
||||
return false;
|
||||
}
|
||||
#else
|
||||
(void)packet;
|
||||
#endif
|
||||
if (packet != NULL && _active_flood_retry_count != 0) {
|
||||
for (int i = 0; i < MAX_FLOOD_RETRY_SLOTS; i++) {
|
||||
if (!_flood_retries[i].active || !_flood_retries[i].queued
|
||||
|| _flood_retries[i].packet != packet) {
|
||||
continue;
|
||||
}
|
||||
uint8_t max_attempts = getEligibleFloodRetryMaxAttempts(packet);
|
||||
return max_attempts > _flood_retries[i].retry_attempts_sent;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -392,6 +415,11 @@ bool Mesh::allowFloodRetry(const Packet* packet) const {
|
||||
(void)packet;
|
||||
return true;
|
||||
}
|
||||
bool Mesh::isSelfOriginAdvert(const Packet* packet) const {
|
||||
return packet != NULL && packet->getPayloadType() == PAYLOAD_TYPE_ADVERT
|
||||
&& packet->getPathHashCount() == 0 && packet->payload_len >= PUB_KEY_SIZE
|
||||
&& self_id.matches(packet->payload);
|
||||
}
|
||||
bool Mesh::hasFloodRetryTargetPrefix(const Packet* packet) const {
|
||||
(void)packet;
|
||||
return false;
|
||||
@@ -412,10 +440,54 @@ uint8_t Mesh::applyGroupDataFloodRetryPathGate(const Packet* packet,
|
||||
}
|
||||
return general_gate;
|
||||
}
|
||||
uint8_t Mesh::applyFloodRetryAttemptPolicy(const Packet* packet,
|
||||
uint8_t role_max_attempts) {
|
||||
uint8_t attempts = role_max_attempts > FLOOD_RETRY_MAX_ATTEMPTS_HARD_MAX
|
||||
? FLOOD_RETRY_MAX_ATTEMPTS_HARD_MAX
|
||||
: role_max_attempts;
|
||||
if (attempts == 0 || packet == NULL) {
|
||||
return attempts;
|
||||
}
|
||||
|
||||
switch (packet->getPayloadType()) {
|
||||
case PAYLOAD_TYPE_REQ:
|
||||
return 0;
|
||||
case PAYLOAD_TYPE_GRP_TXT:
|
||||
return attempts;
|
||||
case PAYLOAD_TYPE_RESPONSE:
|
||||
case PAYLOAD_TYPE_TXT_MSG:
|
||||
case PAYLOAD_TYPE_ANON_REQ:
|
||||
case PAYLOAD_TYPE_PATH:
|
||||
return packet->getPathHashCount() == 0 || attempts <= 2 ? attempts : 2;
|
||||
default:
|
||||
return attempts > 1 ? 1 : attempts;
|
||||
}
|
||||
}
|
||||
uint8_t Mesh::getFloodRetryMaxAttempts(const Packet* packet) const {
|
||||
(void)packet;
|
||||
return FLOOD_RETRY_MAX_ATTEMPTS_DEFAULT;
|
||||
}
|
||||
uint8_t Mesh::getEffectiveFloodRetryMaxAttempts(const Packet* packet) const {
|
||||
return applyFloodRetryAttemptPolicy(packet, getFloodRetryMaxAttempts(packet));
|
||||
}
|
||||
uint8_t Mesh::getEligibleFloodRetryMaxAttempts(const Packet* packet) const {
|
||||
if (packet == NULL || !packet->isRouteFlood()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint8_t max_attempts = getEffectiveFloodRetryMaxAttempts(packet);
|
||||
if (max_attempts == 0 || !allowFloodRetry(packet)
|
||||
|| hasFloodRetryTargetPrefix(packet)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint8_t max_path_len = getFloodRetryMaxPathLength(packet);
|
||||
if (max_path_len != FLOOD_RETRY_PATH_GATE_DISABLED
|
||||
&& packet->getPathHashCount() > max_path_len) {
|
||||
return 0;
|
||||
}
|
||||
return max_attempts;
|
||||
}
|
||||
uint32_t Mesh::getFloodRetryAttemptDelay(const Packet* packet, uint8_t attempt_idx) {
|
||||
(void)attempt_idx;
|
||||
if (packet == NULL) {
|
||||
@@ -426,13 +498,18 @@ uint32_t Mesh::getFloodRetryAttemptDelay(const Packet* packet, uint8_t attempt_i
|
||||
uint32_t packet_airtime = _radio->getEstAirtimeFor(packet->getRawLength());
|
||||
uint32_t jitter_percent = _rng->nextInt(0, 201);
|
||||
uint32_t jitter = (packet_airtime * jitter_percent) / 100UL;
|
||||
return max_packet_airtime + (20UL * packet_airtime) + jitter;
|
||||
uint32_t delay = max_packet_airtime + (20UL * packet_airtime) + jitter;
|
||||
if (isSelfOriginAdvert(packet)) {
|
||||
delay += ORIGIN_ADVERT_RETRY_EXTRA_DELAY_MS;
|
||||
}
|
||||
return delay;
|
||||
}
|
||||
uint8_t Mesh::getExtraAckTransmitCount() const {
|
||||
return 0;
|
||||
}
|
||||
|
||||
void Mesh::onSendComplete(Packet* packet) {
|
||||
watchForwardedAdvertEcho(packet);
|
||||
armDirectRetryOnSendComplete(packet);
|
||||
armFloodRetryOnSendComplete(packet);
|
||||
}
|
||||
@@ -459,6 +536,7 @@ int Mesh::searchChannelsByHash(const uint8_t* hash, GroupChannel channels[], int
|
||||
}
|
||||
|
||||
DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
observeForwardedAdvertEcho(pkt);
|
||||
if (pkt->isRouteDirect()) {
|
||||
cancelDirectRetryOnEcho(pkt);
|
||||
} else if (pkt->isRouteFlood()) {
|
||||
@@ -845,6 +923,10 @@ void Mesh::removePathPrefix(Packet* pkt, uint8_t prefix_count) {
|
||||
}
|
||||
|
||||
DispatcherAction Mesh::routeRecvPacket(Packet* packet) {
|
||||
if (shouldSuppressEchoedAdvertForward(packet)) {
|
||||
return ACTION_RELEASE;
|
||||
}
|
||||
|
||||
uint8_t n = packet->getPathHashCount();
|
||||
if (packet->isRouteFlood() && !packet->isMarkedDoNotRetransmit()
|
||||
&& (n + 1)*packet->getPathHashSize() <= MAX_PATH_SIZE && allowPacketForward(packet)) {
|
||||
@@ -1529,12 +1611,70 @@ void Mesh::clearFloodRetrySlot(int idx) {
|
||||
memset(_flood_retries[idx].retry_key, 0, sizeof(_flood_retries[idx].retry_key));
|
||||
_flood_retries[idx].priority = 0;
|
||||
_flood_retries[idx].progress_marker = 0;
|
||||
_flood_retries[idx].self_advert = false;
|
||||
_flood_retries[idx].waiting_final_echo = false;
|
||||
_flood_retries[idx].queued = false;
|
||||
_flood_retries[idx].active = false;
|
||||
if (rebuild_timeout) rebuildNextFloodRetryTimeout();
|
||||
}
|
||||
|
||||
void Mesh::retireFloodRetrySlot(int idx) {
|
||||
if (idx < 0 || idx >= MAX_FLOOD_RETRY_SLOTS || !_flood_retries[idx].active) {
|
||||
return;
|
||||
}
|
||||
|
||||
Packet* retry = _flood_retries[idx].queued ? _flood_retries[idx].packet : NULL;
|
||||
if (retry != NULL && retry != getOutboundInFlight()) {
|
||||
for (int j = 0; j < _mgr->getOutboundTotal(); j++) {
|
||||
if (_mgr->getOutboundByIdx(j) != retry) continue;
|
||||
Packet* pending = _mgr->removeOutboundByIdx(j);
|
||||
if (pending != NULL) {
|
||||
_flood_retries[idx].packet = NULL;
|
||||
releasePacket(pending);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
clearFloodRetrySlot(idx);
|
||||
}
|
||||
|
||||
void Mesh::replaceQueuedSelfAdvertRetries(const Packet* packet) {
|
||||
if (packet == NULL || !packet->isRouteFlood() || !isSelfOriginAdvert(packet)) {
|
||||
return;
|
||||
}
|
||||
|
||||
int replacement_slot = -1;
|
||||
bool found_prior = false;
|
||||
for (int i = 0; i < MAX_FLOOD_RETRY_SLOTS; i++) {
|
||||
if (!_flood_retries[i].active
|
||||
|| !_flood_retries[i].self_advert) {
|
||||
continue;
|
||||
}
|
||||
if (_flood_retries[i].trigger_packet == packet) {
|
||||
replacement_slot = i;
|
||||
} else {
|
||||
found_prior = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found_prior) return;
|
||||
|
||||
for (int i = 0; i < MAX_FLOOD_RETRY_SLOTS; i++) {
|
||||
if (i == replacement_slot || !_flood_retries[i].active
|
||||
|| !_flood_retries[i].self_advert) {
|
||||
continue;
|
||||
}
|
||||
retireFloodRetrySlot(i);
|
||||
}
|
||||
|
||||
// A full retry table or an identical retry key can prevent the new advert
|
||||
// from reserving a slot before it enters the outbound queue. Older advert
|
||||
// retries are gone now, so let the successfully queued advert take over.
|
||||
if (replacement_slot < 0) {
|
||||
maybeScheduleFloodRetry(packet, 3);
|
||||
}
|
||||
}
|
||||
|
||||
void Mesh::rebuildNextFloodRetryTimeout() {
|
||||
bool found = false;
|
||||
uint32_t shortest_delay = 0;
|
||||
@@ -1566,20 +1706,7 @@ void Mesh::cancelAllFloodRetries() {
|
||||
|
||||
for (int i = 0; i < MAX_FLOOD_RETRY_SLOTS; i++) {
|
||||
if (!_flood_retries[i].active) continue;
|
||||
|
||||
Packet* retry = _flood_retries[i].queued ? _flood_retries[i].packet : NULL;
|
||||
if (retry != NULL && retry != getOutboundInFlight()) {
|
||||
for (int j = 0; j < _mgr->getOutboundTotal(); j++) {
|
||||
if (_mgr->getOutboundByIdx(j) != retry) continue;
|
||||
Packet* pending = _mgr->removeOutboundByIdx(j);
|
||||
if (pending != NULL) {
|
||||
_flood_retries[i].packet = NULL;
|
||||
releasePacket(pending);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
clearFloodRetrySlot(i);
|
||||
retireFloodRetrySlot(i);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1607,20 +1734,7 @@ bool Mesh::cancelActiveRetries(const uint8_t retry_key[MAX_HASH_SIZE]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Packet* retry = _flood_retries[i].queued ? _flood_retries[i].packet : NULL;
|
||||
if (retry != NULL && retry != getOutboundInFlight()) {
|
||||
for (int j = 0; j < _mgr->getOutboundTotal(); j++) {
|
||||
if (_mgr->getOutboundByIdx(j) == retry) {
|
||||
Packet* pending = _mgr->removeOutboundByIdx(j);
|
||||
if (pending != NULL) {
|
||||
_flood_retries[i].packet = NULL;
|
||||
releasePacket(pending);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
clearFloodRetrySlot(i);
|
||||
retireFloodRetrySlot(i);
|
||||
cancelled = true;
|
||||
}
|
||||
|
||||
@@ -1677,6 +1791,121 @@ bool Mesh::isFloodRetryEchoTarget(const Packet* packet, uint8_t progress_marker)
|
||||
return packet->isRouteFlood() && packet->getPathHashCount() > progress_marker;
|
||||
}
|
||||
|
||||
bool Mesh::getRecentAdvertTimestamp(const Packet* packet, uint32_t& timestamp) const {
|
||||
if (packet == NULL || packet->getPayloadType() != PAYLOAD_TYPE_ADVERT
|
||||
|| packet->payload_len < PUB_KEY_SIZE + sizeof(timestamp) + SIGNATURE_SIZE) {
|
||||
return false;
|
||||
}
|
||||
memcpy(×tamp, &packet->payload[PUB_KEY_SIZE], sizeof(timestamp));
|
||||
return isRecentAdvertTimestamp(timestamp);
|
||||
}
|
||||
|
||||
bool Mesh::isRecentAdvertTimestamp(uint32_t timestamp) const {
|
||||
uint32_t now = _rtc->getCurrentTime();
|
||||
return now >= timestamp && now - timestamp < RECENT_ADVERT_MAX_AGE_SECONDS;
|
||||
}
|
||||
|
||||
void Mesh::watchForwardedAdvertEcho(const Packet* packet) {
|
||||
if (packet == NULL || !packet->isRouteFlood() || packet->getPathHashCount() == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t advert_timestamp;
|
||||
if (!getRecentAdvertTimestamp(packet, advert_timestamp)) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t packet_hash[MAX_HASH_SIZE];
|
||||
packet->calculatePacketHash(packet_hash);
|
||||
uint32_t now_millis = _ms->getMillis();
|
||||
int slot_idx = -1;
|
||||
for (int i = 0; i < MAX_RECENT_ADVERT_ECHOS; i++) {
|
||||
RecentAdvertEchoEntry& entry = _recent_advert_echoes[i];
|
||||
if (entry.valid && memcmp(entry.packet_hash, packet_hash, MAX_HASH_SIZE) == 0) {
|
||||
if (entry.confirmed) {
|
||||
return;
|
||||
}
|
||||
slot_idx = i;
|
||||
break;
|
||||
}
|
||||
bool expired = entry.valid
|
||||
&& ((entry.confirmed && !isRecentAdvertTimestamp(entry.advert_timestamp))
|
||||
|| (!entry.confirmed
|
||||
&& (uint32_t)(now_millis - entry.watch_started_at)
|
||||
> FORWARDED_ADVERT_ECHO_WATCH_MS));
|
||||
if (slot_idx < 0 && (!entry.valid || expired)) {
|
||||
slot_idx = i;
|
||||
}
|
||||
}
|
||||
if (slot_idx < 0) {
|
||||
slot_idx = _next_recent_advert_echo;
|
||||
}
|
||||
_next_recent_advert_echo = (slot_idx + 1) % MAX_RECENT_ADVERT_ECHOS;
|
||||
|
||||
RecentAdvertEchoEntry& entry = _recent_advert_echoes[slot_idx];
|
||||
memcpy(entry.packet_hash, packet_hash, sizeof(entry.packet_hash));
|
||||
entry.advert_timestamp = advert_timestamp;
|
||||
entry.watch_started_at = now_millis;
|
||||
entry.progress_marker = packet->getPathHashCount();
|
||||
entry.confirmed = false;
|
||||
entry.valid = true;
|
||||
}
|
||||
|
||||
void Mesh::observeForwardedAdvertEcho(const Packet* packet) {
|
||||
if (packet == NULL || !packet->isRouteFlood()) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t advert_timestamp;
|
||||
if (!getRecentAdvertTimestamp(packet, advert_timestamp)) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t packet_hash[MAX_HASH_SIZE];
|
||||
packet->calculatePacketHash(packet_hash);
|
||||
uint32_t now_millis = _ms->getMillis();
|
||||
for (int i = 0; i < MAX_RECENT_ADVERT_ECHOS; i++) {
|
||||
RecentAdvertEchoEntry& entry = _recent_advert_echoes[i];
|
||||
if (!entry.valid || entry.confirmed
|
||||
|| memcmp(entry.packet_hash, packet_hash, MAX_HASH_SIZE) != 0) {
|
||||
continue;
|
||||
}
|
||||
if ((uint32_t)(now_millis - entry.watch_started_at) > FORWARDED_ADVERT_ECHO_WATCH_MS) {
|
||||
entry.valid = false;
|
||||
continue;
|
||||
}
|
||||
// The exact advert payload is the identity. It may return through a
|
||||
// different branch; a longer path still proves a downstream copy exists.
|
||||
if (entry.advert_timestamp == advert_timestamp
|
||||
&& packet->getPathHashCount() > entry.progress_marker) {
|
||||
entry.confirmed = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool Mesh::shouldSuppressEchoedAdvertForward(const Packet* packet) const {
|
||||
if (packet == NULL || !packet->isRouteFlood()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint32_t advert_timestamp;
|
||||
if (!getRecentAdvertTimestamp(packet, advert_timestamp)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t packet_hash[MAX_HASH_SIZE];
|
||||
packet->calculatePacketHash(packet_hash);
|
||||
for (int i = 0; i < MAX_RECENT_ADVERT_ECHOS; i++) {
|
||||
const RecentAdvertEchoEntry& entry = _recent_advert_echoes[i];
|
||||
if (entry.valid && entry.confirmed && entry.advert_timestamp == advert_timestamp
|
||||
&& memcmp(entry.packet_hash, packet_hash, MAX_HASH_SIZE) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Mesh::cancelFloodRetryOnEcho(const Packet* packet) {
|
||||
if (_active_flood_retry_count == 0) return false;
|
||||
|
||||
@@ -1700,18 +1929,7 @@ bool Mesh::cancelFloodRetryOnEcho(const Packet* packet) {
|
||||
: _flood_retries[i].retry_attempts_sent + 1;
|
||||
onFloodRetryEvent("good", packet, echo_millis, retry_attempt);
|
||||
|
||||
if (_flood_retries[i].queued) {
|
||||
for (int j = 0; j < _mgr->getOutboundTotal(); j++) {
|
||||
if (_mgr->getOutboundByIdx(j) == _flood_retries[i].packet) {
|
||||
Packet* pending = _mgr->removeOutboundByIdx(j);
|
||||
if (pending) {
|
||||
releasePacket(pending);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
clearFloodRetrySlot(i);
|
||||
retireFloodRetrySlot(i);
|
||||
cleared = true;
|
||||
}
|
||||
|
||||
@@ -1737,11 +1955,10 @@ void Mesh::armFloodRetryOnSendComplete(const Packet* packet) {
|
||||
onFloodRetryEvent("resent", packet, elapsed_millis, _flood_retries[i].retry_attempts_sent + 1);
|
||||
_flood_retries[i].retry_attempts_sent++;
|
||||
|
||||
uint8_t max_attempts = getFloodRetryMaxAttempts(packet);
|
||||
if (max_attempts < 1) {
|
||||
max_attempts = 1;
|
||||
} else if (max_attempts > FLOOD_RETRY_MAX_ATTEMPTS_HARD_MAX) {
|
||||
max_attempts = FLOOD_RETRY_MAX_ATTEMPTS_HARD_MAX;
|
||||
uint8_t max_attempts = getEligibleFloodRetryMaxAttempts(packet);
|
||||
if (max_attempts == 0) {
|
||||
clearFloodRetrySlot(i);
|
||||
continue;
|
||||
}
|
||||
if (_flood_retries[i].retry_attempts_sent >= max_attempts) {
|
||||
// Dispatcher releases the transmitted packet after this hook. Keep only
|
||||
@@ -1789,6 +2006,11 @@ void Mesh::armFloodRetryOnSendComplete(const Packet* packet) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (getEligibleFloodRetryMaxAttempts(packet) == 0) {
|
||||
clearFloodRetrySlot(i);
|
||||
continue;
|
||||
}
|
||||
|
||||
Packet* retry = obtainNewPacket();
|
||||
if (retry == NULL) {
|
||||
onFloodRetryEvent("dropped_no_packet", packet, _flood_retries[i].retry_delay, 1);
|
||||
@@ -1847,15 +2069,9 @@ void Mesh::maybeScheduleFloodRetry(const Packet* packet, uint8_t priority) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check the inexpensive global kill switch before prefix/path eligibility.
|
||||
// This makes flood.retry.count=0 a genuinely cheap disabled state.
|
||||
uint8_t max_attempts = getFloodRetryMaxAttempts(packet);
|
||||
if (max_attempts == 0 || hasFloodRetryTargetPrefix(packet)) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t max_path_len = getFloodRetryMaxPathLength(packet);
|
||||
if (max_path_len != FLOOD_RETRY_PATH_GATE_DISABLED && packet->getPathHashCount() > max_path_len) {
|
||||
// Keep all count/type/path gates in one check, which is also reused when a
|
||||
// delayed retry reaches the radio so a newly disabled retry stays disabled.
|
||||
if (getEligibleFloodRetryMaxAttempts(packet) == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1881,7 +2097,7 @@ void Mesh::maybeScheduleFloodRetry(const Packet* packet, uint8_t priority) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!allowFloodRetry(packet)) {
|
||||
if (!prepareFloodRetry(packet)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1895,6 +2111,7 @@ void Mesh::maybeScheduleFloodRetry(const Packet* packet, uint8_t priority) {
|
||||
_flood_retries[slot_idx].retry_attempts_sent = 0;
|
||||
_flood_retries[slot_idx].priority = priority;
|
||||
_flood_retries[slot_idx].progress_marker = packet->getPathHashCount();
|
||||
_flood_retries[slot_idx].self_advert = isSelfOriginAdvert(packet);
|
||||
_flood_retries[slot_idx].waiting_final_echo = false;
|
||||
_flood_retries[slot_idx].queued = false;
|
||||
_flood_retries[slot_idx].active = true;
|
||||
@@ -2196,7 +2413,9 @@ bool Mesh::sendFlood(Packet* packet, uint32_t delay_millis, uint8_t path_hash_si
|
||||
pri = 1;
|
||||
}
|
||||
maybeScheduleFloodRetry(packet, pri);
|
||||
return sendPacket(packet, pri, delay_millis);
|
||||
bool queued = sendPacket(packet, pri, delay_millis);
|
||||
if (queued) replaceQueuedSelfAdvertRetries(packet);
|
||||
return queued;
|
||||
}
|
||||
|
||||
bool Mesh::sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_millis, uint8_t path_hash_size) {
|
||||
@@ -2228,7 +2447,9 @@ bool Mesh::sendFlood(Packet* packet, uint16_t* transport_codes, uint32_t delay_m
|
||||
pri = 1;
|
||||
}
|
||||
maybeScheduleFloodRetry(packet, pri);
|
||||
return sendPacket(packet, pri, delay_millis);
|
||||
bool queued = sendPacket(packet, pri, delay_millis);
|
||||
if (queued) replaceQueuedSelfAdvertRetries(packet);
|
||||
return queued;
|
||||
}
|
||||
|
||||
bool Mesh::sendDirect(Packet* packet, const uint8_t* path, uint8_t path_len, uint32_t delay_millis) {
|
||||
|
||||
+48
@@ -25,6 +25,13 @@ namespace mesh {
|
||||
#define MAX_FLOOD_RETRY_SLOTS 6
|
||||
#endif
|
||||
|
||||
#ifndef MAX_RECENT_ADVERT_ECHOS
|
||||
#define MAX_RECENT_ADVERT_ECHOS 8
|
||||
#endif
|
||||
#if MAX_RECENT_ADVERT_ECHOS < 1
|
||||
#error "MAX_RECENT_ADVERT_ECHOS must be at least 1"
|
||||
#endif
|
||||
|
||||
#ifndef FLOOD_RETRY_PATH_GATE_DISABLED
|
||||
#define FLOOD_RETRY_PATH_GATE_DISABLED 0xFF
|
||||
#endif
|
||||
@@ -83,20 +90,32 @@ class Mesh : public Dispatcher {
|
||||
uint8_t retry_key[MAX_HASH_SIZE];
|
||||
uint8_t priority;
|
||||
uint8_t progress_marker;
|
||||
bool self_advert;
|
||||
bool waiting_final_echo;
|
||||
bool queued;
|
||||
bool active;
|
||||
};
|
||||
|
||||
struct RecentAdvertEchoEntry {
|
||||
uint8_t packet_hash[MAX_HASH_SIZE];
|
||||
uint32_t advert_timestamp;
|
||||
uint32_t watch_started_at;
|
||||
uint8_t progress_marker;
|
||||
bool confirmed;
|
||||
bool valid;
|
||||
};
|
||||
|
||||
RTCClock* _rtc;
|
||||
RNG* _rng;
|
||||
MeshTables* _tables;
|
||||
DirectRetryEntry _direct_retries[MAX_DIRECT_RETRY_SLOTS];
|
||||
FloodRetryEntry _flood_retries[MAX_FLOOD_RETRY_SLOTS];
|
||||
RecentAdvertEchoEntry _recent_advert_echoes[MAX_RECENT_ADVERT_ECHOS];
|
||||
uint8_t _active_direct_retry_count;
|
||||
uint8_t _active_flood_retry_count;
|
||||
uint8_t _waiting_direct_retry_count;
|
||||
uint8_t _waiting_flood_retry_count;
|
||||
uint8_t _next_recent_advert_echo;
|
||||
unsigned long _next_direct_retry_timeout;
|
||||
unsigned long _next_flood_retry_timeout;
|
||||
|
||||
@@ -117,7 +136,16 @@ class Mesh : public Dispatcher {
|
||||
bool canDecodeDirectPayloadForSelf(const Packet* packet);
|
||||
void maybeScheduleDirectRetry(const Packet* packet, uint8_t priority, bool final_hop_retry = false);
|
||||
void clearFloodRetrySlot(int idx);
|
||||
void retireFloodRetrySlot(int idx);
|
||||
void replaceQueuedSelfAdvertRetries(const Packet* packet);
|
||||
bool cancelFloodRetryOnEcho(const Packet* packet);
|
||||
bool getRecentAdvertTimestamp(const Packet* packet, uint32_t& timestamp) const;
|
||||
bool isRecentAdvertTimestamp(uint32_t timestamp) const;
|
||||
void watchForwardedAdvertEcho(const Packet* packet);
|
||||
void observeForwardedAdvertEcho(const Packet* packet);
|
||||
bool shouldSuppressEchoedAdvertForward(const Packet* packet) const;
|
||||
uint8_t getEffectiveFloodRetryMaxAttempts(const Packet* packet) const;
|
||||
uint8_t getEligibleFloodRetryMaxAttempts(const Packet* packet) const;
|
||||
void armFloodRetryOnSendComplete(const Packet* packet);
|
||||
void clearPendingFloodRetryOnSendFail(const Packet* packet);
|
||||
void maybeScheduleFloodRetry(const Packet* packet, uint8_t priority);
|
||||
@@ -231,6 +259,20 @@ protected:
|
||||
*/
|
||||
virtual bool allowFloodRetry(const Packet* packet) const;
|
||||
|
||||
/**
|
||||
* \brief Reserve any role-specific state after a free flood retry slot is found.
|
||||
* \returns false if role-specific state could not be reserved.
|
||||
*/
|
||||
virtual bool prepareFloodRetry(const Packet* packet) const {
|
||||
(void)packet;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* \returns true only for a zero-hop advert carrying this node's public key.
|
||||
*/
|
||||
bool isSelfOriginAdvert(const Packet* packet) const;
|
||||
|
||||
/**
|
||||
* \brief Return true when this FLOOD packet already carries an application-defined target prefix.
|
||||
*/
|
||||
@@ -248,6 +290,12 @@ protected:
|
||||
uint8_t general_gate,
|
||||
uint8_t group_data_gate);
|
||||
|
||||
/**
|
||||
* \returns the shared payload/path cap applied after a role chooses its flood retry count.
|
||||
*/
|
||||
static uint8_t applyFloodRetryAttemptPolicy(const Packet* packet,
|
||||
uint8_t role_max_attempts);
|
||||
|
||||
/**
|
||||
* \returns maximum number of FLOOD retry transmissions after the initial TX.
|
||||
*/
|
||||
|
||||
@@ -21,6 +21,9 @@ public:
|
||||
// Backends whose busy methods are throttling/high-water signals should
|
||||
// override this with their actual queue state.
|
||||
virtual bool hasPendingIO() const { return isReadBusy() || isWriteBusy(); }
|
||||
// Returns true once for each pending Bluetooth pairing prompt. Non-BLE
|
||||
// transports keep the default implementation so UI code can poll safely.
|
||||
virtual bool takePairingRequest() { return false; }
|
||||
virtual size_t writeFrame(const uint8_t src[], size_t len) = 0;
|
||||
virtual size_t checkRecvFrame(uint8_t dest[]) = 0;
|
||||
};
|
||||
@@ -26,7 +26,9 @@ void SerialBLEInterface::begin(const char* prefix, char* name, uint32_t pin_code
|
||||
// Create the BLE Device
|
||||
BLEDevice::init(dev_name);
|
||||
BLEDevice::setSecurityCallbacks(this);
|
||||
BLEDevice::setMTU(MAX_FRAME_SIZE);
|
||||
// ATT notifications consume three bytes of the negotiated MTU. Reserve
|
||||
// that overhead so a MAX_FRAME_SIZE protocol frame fits without truncation.
|
||||
BLEDevice::setMTU(MAX_FRAME_SIZE + 3);
|
||||
|
||||
BLESecurity sec;
|
||||
sec.setStaticPIN(pin_code);
|
||||
@@ -44,7 +46,15 @@ void SerialBLEInterface::begin(const char* prefix, char* name, uint32_t pin_code
|
||||
// Create a BLE Characteristic
|
||||
pTxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
|
||||
pTxCharacteristic->setAccessPermissions(ESP_GATT_PERM_READ_ENC_MITM);
|
||||
pTxCharacteristic->addDescriptor(new BLE2902());
|
||||
pTxCharacteristic->setCallbacks(this);
|
||||
pTxDescriptor = new BLE2902();
|
||||
// Make notification setup start/finish pairing before the client begins its
|
||||
// short device-info request timeout. The RX and TX characteristics already
|
||||
// require the same MITM-encrypted link, so this does not add a new pairing
|
||||
// requirement; it only moves it earlier in the connection handshake.
|
||||
pTxDescriptor->setAccessPermissions(
|
||||
(esp_gatt_perm_t)(ESP_GATT_PERM_READ_ENC_MITM | ESP_GATT_PERM_WRITE_ENC_MITM));
|
||||
pTxCharacteristic->addDescriptor(pTxDescriptor);
|
||||
|
||||
BLECharacteristic * pRxCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);
|
||||
pRxCharacteristic->setAccessPermissions(ESP_GATT_PERM_WRITE_ENC_MITM);
|
||||
@@ -57,15 +67,18 @@ void SerialBLEInterface::begin(const char* prefix, char* name, uint32_t pin_code
|
||||
|
||||
uint32_t SerialBLEInterface::onPassKeyRequest() {
|
||||
BLE_DEBUG_PRINTLN("onPassKeyRequest()");
|
||||
_pairingRequestPending.store(true, std::memory_order_release);
|
||||
return _pin_code;
|
||||
}
|
||||
|
||||
void SerialBLEInterface::onPassKeyNotify(uint32_t pass_key) {
|
||||
BLE_DEBUG_PRINTLN("onPassKeyNotify(%u)", pass_key);
|
||||
_pairingRequestPending.store(true, std::memory_order_release);
|
||||
}
|
||||
|
||||
bool SerialBLEInterface::onConfirmPIN(uint32_t pass_key) {
|
||||
BLE_DEBUG_PRINTLN("onConfirmPIN(%u)", pass_key);
|
||||
_pairingRequestPending.store(true, std::memory_order_release);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -95,6 +108,9 @@ void SerialBLEInterface::onConnect(BLEServer* pServer) {
|
||||
void SerialBLEInterface::onConnect(BLEServer* pServer, esp_ble_gatts_cb_param_t *param) {
|
||||
BLE_DEBUG_PRINTLN("onConnect(), conn_id=%d, mtu=%d", param->connect.conn_id, pServer->getPeerMTU(param->connect.conn_id));
|
||||
last_conn_id = param->connect.conn_id;
|
||||
deviceConnected = false; // becomes usable only after authentication completes
|
||||
notifySucceeded = false;
|
||||
if (pTxDescriptor != NULL) pTxDescriptor->setNotifications(false);
|
||||
}
|
||||
|
||||
void SerialBLEInterface::onMtuChanged(BLEServer* pServer, esp_ble_gatts_cb_param_t* param) {
|
||||
@@ -103,6 +119,9 @@ void SerialBLEInterface::onMtuChanged(BLEServer* pServer, esp_ble_gatts_cb_param
|
||||
|
||||
void SerialBLEInterface::onDisconnect(BLEServer* pServer) {
|
||||
BLE_DEBUG_PRINTLN("onDisconnect()");
|
||||
deviceConnected = false;
|
||||
notifySucceeded = false;
|
||||
if (pTxDescriptor != NULL) pTxDescriptor->setNotifications(false);
|
||||
if (_isEnabled) {
|
||||
adv_restart_time = millis() + ADVERT_RESTART_DELAY;
|
||||
|
||||
@@ -127,6 +146,15 @@ void SerialBLEInterface::onWrite(BLECharacteristic* pCharacteristic, esp_ble_gat
|
||||
}
|
||||
}
|
||||
|
||||
void SerialBLEInterface::onStatus(BLECharacteristic* pCharacteristic, Status status, uint32_t code) {
|
||||
(void)pCharacteristic;
|
||||
notifySucceeded = status == SUCCESS_NOTIFY;
|
||||
if (!notifySucceeded) {
|
||||
BLE_DEBUG_PRINTLN("notify failed, status=%d, code=%u; retaining frame",
|
||||
(int)status, (unsigned)code);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- public methods
|
||||
|
||||
void SerialBLEInterface::enable() {
|
||||
@@ -194,19 +222,31 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
if (send_queue_len > 0 // first, check send queue
|
||||
&& millis() >= _last_write + BLE_WRITE_MIN_INTERVAL // space the writes apart
|
||||
) {
|
||||
_last_write = millis();
|
||||
pTxCharacteristic->setValue(send_queue[0].buf, send_queue[0].len);
|
||||
pTxCharacteristic->notify();
|
||||
const uint16_t peer_mtu = pServer->getPeerMTU(last_conn_id);
|
||||
const bool notifications_ready = pTxDescriptor != NULL && pTxDescriptor->getNotifications();
|
||||
const bool frame_fits = peer_mtu > 3 && send_queue[0].len <= peer_mtu - 3;
|
||||
|
||||
BLE_DEBUG_PRINTLN("writeBytes: sz=%d, hdr=%d", (uint32_t)send_queue[0].len, (uint32_t) send_queue[0].buf[0]);
|
||||
// A fresh pairing can deliver the app's first command before its CCCD
|
||||
// subscription or MTU exchange completes. Keep the response queued until
|
||||
// both are ready instead of silently dropping/truncating device info.
|
||||
if (notifications_ready && frame_fits) {
|
||||
_last_write = millis();
|
||||
notifySucceeded = false;
|
||||
pTxCharacteristic->setValue(send_queue[0].buf, send_queue[0].len);
|
||||
pTxCharacteristic->notify();
|
||||
|
||||
send_queue_len--;
|
||||
for (int i = 0; i < send_queue_len; i++) { // delete top item from queue
|
||||
send_queue[i] = send_queue[i + 1];
|
||||
if (notifySucceeded) {
|
||||
BLE_DEBUG_PRINTLN("writeBytes: sz=%d, hdr=%d", (uint32_t)send_queue[0].len, (uint32_t) send_queue[0].buf[0]);
|
||||
|
||||
send_queue_len--;
|
||||
for (int i = 0; i < send_queue_len; i++) { // delete top item from queue
|
||||
send_queue[i] = send_queue[i + 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (recv_queue_len > 0) { // check recv queue
|
||||
if (deviceConnected && recv_queue_len > 0) { // check recv queue after authentication
|
||||
size_t len = recv_queue[0].len; // take from top of queue
|
||||
memcpy(dest, recv_queue[0].buf, len);
|
||||
|
||||
@@ -219,8 +259,6 @@ size_t SerialBLEInterface::checkRecvFrame(uint8_t dest[]) {
|
||||
return len;
|
||||
}
|
||||
|
||||
if (pServer->getConnectedCount() == 0) deviceConnected = false;
|
||||
|
||||
if (deviceConnected != oldDeviceConnected) {
|
||||
if (!deviceConnected) { // disconnecting
|
||||
clearBuffers();
|
||||
|
||||
@@ -5,18 +5,22 @@
|
||||
#include <BLEServer.h>
|
||||
#include <BLEUtils.h>
|
||||
#include <BLE2902.h>
|
||||
#include <atomic>
|
||||
|
||||
class SerialBLEInterface : public BaseSerialInterface, BLESecurityCallbacks, BLEServerCallbacks, BLECharacteristicCallbacks {
|
||||
BLEServer *pServer;
|
||||
BLEService *pService;
|
||||
BLECharacteristic * pTxCharacteristic;
|
||||
BLE2902 *pTxDescriptor;
|
||||
bool deviceConnected;
|
||||
bool oldDeviceConnected;
|
||||
bool notifySucceeded;
|
||||
bool _isEnabled;
|
||||
uint16_t last_conn_id;
|
||||
uint32_t _pin_code;
|
||||
unsigned long _last_write;
|
||||
unsigned long adv_restart_time;
|
||||
std::atomic<bool> _pairingRequestPending{false};
|
||||
|
||||
struct Frame {
|
||||
uint8_t len;
|
||||
@@ -47,13 +51,17 @@ protected:
|
||||
|
||||
// BLECharacteristicCallbacks methods
|
||||
void onWrite(BLECharacteristic* pCharacteristic, esp_ble_gatts_cb_param_t* param) override;
|
||||
void onStatus(BLECharacteristic* pCharacteristic, Status status, uint32_t code) override;
|
||||
|
||||
public:
|
||||
SerialBLEInterface() {
|
||||
pServer = NULL;
|
||||
pService = NULL;
|
||||
pTxCharacteristic = NULL;
|
||||
pTxDescriptor = NULL;
|
||||
deviceConnected = false;
|
||||
oldDeviceConnected = false;
|
||||
notifySucceeded = false;
|
||||
adv_restart_time = 0;
|
||||
_isEnabled = false;
|
||||
_last_write = 0;
|
||||
@@ -79,6 +87,9 @@ public:
|
||||
bool isReadBusy() const override;
|
||||
bool isWriteBusy() const override;
|
||||
bool hasPendingIO() const override { return recv_queue_len > 0 || send_queue_len > 0; }
|
||||
bool takePairingRequest() override {
|
||||
return _pairingRequestPending.exchange(false, std::memory_order_acq_rel);
|
||||
}
|
||||
size_t writeFrame(const uint8_t src[], size_t len) override;
|
||||
size_t checkRecvFrame(uint8_t dest[]) override;
|
||||
};
|
||||
|
||||
@@ -8,16 +8,15 @@
|
||||
#define STATE_TX_DONE 4
|
||||
#define STATE_INT_READY 16
|
||||
|
||||
#define NUM_NOISE_FLOOR_SAMPLES 16
|
||||
#define NUM_NOISE_FLOOR_SAMPLES 64
|
||||
#define SAMPLING_THRESHOLD 14
|
||||
|
||||
// On-demand noise-floor calibration windows (RX duty-cycle powersaving only).
|
||||
// Requests are coalesced so retries cannot repeatedly force continuous RX.
|
||||
#define NF_CALIB_INTERVAL_MS 300000UL // no more than once every five minutes
|
||||
#define NF_CALIB_INTERVAL_MS 2000UL // match the original 2-second refresh cadence
|
||||
#define NF_CALIB_TIMEOUT_MS 5000UL // give up on the batch (busy channel)
|
||||
#define NF_CONTINUOUS_TIMEOUT_MS 1000UL // bound awake time without RX powersaving
|
||||
#define NF_CALIB_SETTLE_MS 20UL // frontend/AGC settle after RX entry
|
||||
#define NF_SAMPLE_INTERVAL_MS 20UL // avoid back-to-back SPI RSSI reads
|
||||
|
||||
static volatile uint8_t state = STATE_IDLE;
|
||||
|
||||
@@ -57,7 +56,6 @@ void RadioLibWrapper::begin() {
|
||||
// Arm the bounded sampling window only after the radio actually reaches RX.
|
||||
// Companion initialization can take longer than the window itself.
|
||||
_nf_calib_deadline = 0;
|
||||
_nf_next_sample_at = 0;
|
||||
}
|
||||
|
||||
uint32_t RadioLibWrapper::getRngSeed() {
|
||||
@@ -170,11 +168,10 @@ void RadioLibWrapper::idle() {
|
||||
|
||||
void RadioLibWrapper::triggerNoiseFloorCalibrate(int threshold) {
|
||||
_threshold = threshold;
|
||||
// With interference detection disabled, Dispatcher polling is a free flag
|
||||
// update: passive retries request a refresh themselves only when the cached
|
||||
// floor is stale. An enabled threshold keeps the floor periodically fresh;
|
||||
// an invalid startup floor is retried even when interference detection is off.
|
||||
if (threshold != 0 || !_noise_floor_valid) requestNoiseFloorRefresh();
|
||||
// Calibration is independent of interference detection. Callers such as the
|
||||
// Dispatcher and KISS modem use a zero threshold but still expect a fresh
|
||||
// floor measurement on every scheduled request.
|
||||
requestNoiseFloorRefresh();
|
||||
}
|
||||
|
||||
void RadioLibWrapper::requestNoiseFloorRefresh() {
|
||||
@@ -183,7 +180,6 @@ void RadioLibWrapper::requestNoiseFloorRefresh() {
|
||||
_num_floor_samples = 0;
|
||||
_floor_sample_sum = 0;
|
||||
_nf_calib_deadline = 0; // starts when continuous RX is actually available
|
||||
_nf_next_sample_at = 0;
|
||||
}
|
||||
|
||||
void RadioLibWrapper::doResetAGC() {
|
||||
@@ -211,7 +207,6 @@ void RadioLibWrapper::resetAGC() {
|
||||
_num_floor_samples = 0;
|
||||
_floor_sample_sum = 0;
|
||||
_nf_calib_deadline = 0; // starts after reset recovery reaches RX
|
||||
_nf_next_sample_at = 0;
|
||||
}
|
||||
|
||||
void RadioLibWrapper::rxPsWatchdogCheck() {
|
||||
@@ -311,7 +306,6 @@ void RadioLibWrapper::noiseFloorCalibCheck(unsigned long now) {
|
||||
_nf_calib_active = true;
|
||||
_nf_calib_deadline = now + NF_CALIB_TIMEOUT_MS;
|
||||
_nf_sample_from = now + NF_CALIB_SETTLE_MS;
|
||||
_nf_next_sample_at = _nf_sample_from;
|
||||
_num_floor_samples = 0; // start a fresh batch for this window
|
||||
_floor_sample_sum = 0;
|
||||
state = STATE_IDLE; // recvRaw() re-arms; startReceiveMode() sees the
|
||||
@@ -324,7 +318,6 @@ void RadioLibWrapper::endNoiseFloorCalib(unsigned long now) {
|
||||
_nf_refresh_requested = false;
|
||||
_nf_last_calib = now;
|
||||
_nf_calib_deadline = 0;
|
||||
_nf_next_sample_at = 0;
|
||||
// force a receive re-arm back into duty-cycle mode, but don't clobber a
|
||||
// completed-but-unread packet or an in-flight TX (recvRaw()/onSendFinished()
|
||||
// will re-arm right after those anyway; same guard style as setRxPowerSaving)
|
||||
@@ -349,16 +342,25 @@ void RadioLibWrapper::loop() {
|
||||
}
|
||||
if (_nf_refresh_requested && _num_floor_samples >= NUM_NOISE_FLOOR_SAMPLES
|
||||
&& _floor_sample_sum != 0) {
|
||||
_noise_floor = _floor_sample_sum / NUM_NOISE_FLOOR_SAMPLES;
|
||||
if (_noise_floor < -120) {
|
||||
_noise_floor = -120; // clamp to lower bound of -120dBi
|
||||
int16_t sampled_floor = _floor_sample_sum / NUM_NOISE_FLOOR_SAMPLES;
|
||||
if (sampled_floor < -120) {
|
||||
sampled_floor = -120; // clamp to lower bound of -120dBi
|
||||
}
|
||||
if (_noise_floor_valid) {
|
||||
// Favor the fresh high-rate batch while retaining a small amount of
|
||||
// history: 25% previous floor + 75% newly sampled floor. Round the
|
||||
// negative dBm result to the nearest integer instead of toward zero.
|
||||
int32_t weighted_floor = (int32_t)_noise_floor + 3L * sampled_floor;
|
||||
_noise_floor = weighted_floor < 0 ? (weighted_floor - 2) / 4
|
||||
: (weighted_floor + 2) / 4;
|
||||
} else {
|
||||
_noise_floor = sampled_floor;
|
||||
}
|
||||
_floor_sample_sum = 0;
|
||||
_noise_floor_valid = true;
|
||||
_nf_refresh_requested = false;
|
||||
_nf_last_calib = now;
|
||||
_nf_calib_deadline = 0;
|
||||
_nf_next_sample_at = 0;
|
||||
|
||||
MESH_DEBUG_PRINTLN("RadioLibWrapper: noise_floor = %d", (int)_noise_floor);
|
||||
|
||||
@@ -376,14 +378,12 @@ void RadioLibWrapper::loop() {
|
||||
_nf_refresh_requested = false;
|
||||
_nf_last_calib = now;
|
||||
_nf_calib_deadline = 0;
|
||||
_nf_next_sample_at = 0;
|
||||
_num_floor_samples = 0;
|
||||
_floor_sample_sum = 0;
|
||||
}
|
||||
|
||||
if (_nf_refresh_requested && state == STATE_RX
|
||||
&& _num_floor_samples < NUM_NOISE_FLOOR_SAMPLES
|
||||
&& (_nf_next_sample_at == 0 || (long)(now - _nf_next_sample_at) >= 0)) {
|
||||
&& _num_floor_samples < NUM_NOISE_FLOOR_SAMPLES) {
|
||||
// Noise floor is only sampled outside RX duty-cycle mode: continuously in
|
||||
// plain RX (powersaving off), or inside an on-demand calibration window
|
||||
// (powersaving on), skipping the first moments after RX entry there while
|
||||
@@ -392,7 +392,6 @@ void RadioLibWrapper::loop() {
|
||||
&& !(_nf_calib_active && (long)(now - _nf_sample_from) < 0)
|
||||
&& !isReceivingPacket()) {
|
||||
int rssi = getCurrentRSSI();
|
||||
_nf_next_sample_at = now + NF_SAMPLE_INTERVAL_MS;
|
||||
if (rssi < _noise_floor + SAMPLING_THRESHOLD) { // only consider samples below current floor + sampling THRESHOLD
|
||||
_num_floor_samples++;
|
||||
_floor_sample_sum += rssi;
|
||||
|
||||
@@ -61,7 +61,6 @@ protected:
|
||||
unsigned long _nf_last_calib; // millis of last completed/attempted window
|
||||
unsigned long _nf_calib_deadline; // abort window if the batch can't complete
|
||||
unsigned long _nf_sample_from; // no samples before this (RX entry settle)
|
||||
unsigned long _nf_next_sample_at; // pace SPI RSSI reads during a sample batch
|
||||
|
||||
void idle() override;
|
||||
void startRecv() override;
|
||||
@@ -99,8 +98,7 @@ public:
|
||||
_wd_stuck_thresh(0), _wd_observe_until(0), _wd_observe_ms(0),
|
||||
_cur_freq(0), _cur_bw(0), _cur_sf(0), _cur_cr(0), _cur_dbm(0),
|
||||
_cur_rx_boosted_gain(false), _params_valid(false), _dbm_valid(false), _rx_boosted_gain_valid(false),
|
||||
_nf_calib_active(false), _nf_last_calib(0), _nf_calib_deadline(0), _nf_sample_from(0),
|
||||
_nf_next_sample_at(0)
|
||||
_nf_calib_active(false), _nf_last_calib(0), _nf_calib_deadline(0), _nf_sample_from(0)
|
||||
{
|
||||
n_recv = n_sent = n_recv_errors = n_wd_soft = n_wd_hard = 0;
|
||||
last_recv_millis = 0;
|
||||
|
||||
Reference in new issue
Block a user