Share radio2 raw transport for Ethernet and negotiated direct LoRa OTA

This commit is contained in:
mikecarper committed 2026-10-15 11:05:21 -07:00
1 parent e57ab1309f
commit 23c9648789
77 files changed
+7061 -260

No files matched your search

+119 -14
View File
@@ -1,5 +1,8 @@
#include "Dispatcher.h"
#include "helpers/ota/OtaTiming.h"
#if MESH_ENABLE_OTA_KISS_DIRECT
#include "helpers/ota/OtaDirectWire.h"
#endif
#if MESH_PACKET_LOGGING
#include <Arduino.h>
@@ -51,7 +54,7 @@ void Dispatcher::setRadioAvailable(bool available) {
if (!available) cancelBeaconRadioFrame();
#endif
radio_available = available;
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_FOREIGN_RADIO
if (!available && hasForeignRadioFrame()) {
if (foreign_radio_sending) _radio->onSendFinished();
finishForeignRadioFrame(false, foreign_radio_sending);
@@ -83,7 +86,7 @@ void Dispatcher::begin() {
cancelBeaconRadioFrame();
if (hasBeaconRadioFrame()) return; // restoration owns the peripheral
#endif
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_FOREIGN_RADIO
if (hasForeignRadioFrame()) {
if (foreign_radio_sending && radio_available) _radio->onSendFinished();
finishForeignRadioFrame(false, foreign_radio_sending);
@@ -279,32 +282,84 @@ void Dispatcher::failOutboundTransmit() {
outbound_cancellation = OutboundCancellation::None;
}
#if MESH_ENABLE_FOREIGN_RADIO
bool Dispatcher::supportsForeignRadioProtocol(RadioProfileProtocol protocol) const {
switch (protocol) {
#if MESH_ENABLE_MESHTEXT_CHAT
case RadioProfileProtocol::Meshtext: return _radio->supportsMeshtext();
#endif
#if MESH_ENABLE_ETHERNET_TUNNEL
case RadioProfileProtocol::Ethernet: return _radio->supportsEthernetTunnel();
#endif
default: return false;
}
}
bool Dispatcher::isForeignRadioCurrent() const {
const auto* profiles = _radio->profiles();
return radio_available && _radio->supportsMeshtext() && profiles
#if MESH_ENABLE_OTA_KISS_DIRECT
if (foreign_radio_protocol == RadioProfileProtocol::MeshCore) {
return radio_available && profiles && foreign_radio_profile < 2
&& profiles->canTransmit(foreign_radio_profile)
&& profiles->params(foreign_radio_profile).protocol == RadioProfileProtocol::MeshCore
&& foreign_radio_generation == profiles->generation[foreign_radio_profile]
&& foreign_radio_ota_epoch != 0 && foreign_radio_ota_epoch == directOtaEpoch()
&& allowDirectOtaTransmit(foreign_radio_profile, foreign_radio_generation);
}
#endif
return radio_available && supportsForeignRadioProtocol(foreign_radio_protocol) && profiles
&& allowForeignRadioTransmit()
&& foreign_radio_profile == 1 && profiles->enabled()
&& profiles->canTransmit(foreign_radio_profile)
&& profiles->params(foreign_radio_profile).protocol == RadioProfileProtocol::Meshtext
&& profiles->params(foreign_radio_profile).protocol == foreign_radio_protocol
&& foreign_radio_generation == profiles->generation[foreign_radio_profile];
}
#if MESH_ENABLE_OTA_KISS_DIRECT
bool Dispatcher::queueDirectOtaRadioFrame(const uint8_t* message, uint16_t length,
uint8_t profile, uint32_t generation) {
#if MESH_ENABLE_TX_BEACONS
if (hasBeaconRadioFrame()) return false;
#endif
const auto* profiles = _radio->profiles();
const uint32_t epoch = directOtaEpoch();
if (hasForeignRadioFrame() || !radio_available || _radio->isCarrierWaveActive()
|| !epoch
|| !profiles || profile >= 2 || !profiles->canTransmit(profile)
|| profiles->params(profile).protocol != RadioProfileProtocol::MeshCore
|| generation != profiles->generation[profile]
|| !allowDirectOtaTransmit(profile, generation)) return false;
const uint16_t encoded = ota::ota_direct_wire_encode(
foreign_radio_bytes, sizeof(foreign_radio_bytes), message, length);
if (!encoded) return false;
foreign_radio_length = encoded;
foreign_radio_profile = profile;
foreign_radio_protocol = RadioProfileProtocol::MeshCore;
foreign_radio_generation = generation;
foreign_radio_ota_epoch = epoch;
foreign_radio_retry_at = foreign_radio_prepare_deadline = 0;
foreign_radio_sending = false;
return true;
}
#endif
bool Dispatcher::queueForeignRadioFrame(const uint8_t* bytes, size_t length,
uint8_t profile, uint32_t generation) {
uint8_t profile, uint32_t generation,
RadioProfileProtocol protocol) {
#if MESH_ENABLE_TX_BEACONS
if (hasBeaconRadioFrame()) return false;
#endif
const auto* profiles = _radio->profiles();
if (!bytes || !length || length > sizeof(foreign_radio_bytes) || hasForeignRadioFrame()
|| !radio_available || !_radio->supportsMeshtext() || _radio->isCarrierWaveActive()
|| !radio_available || !supportsForeignRadioProtocol(protocol) || _radio->isCarrierWaveActive()
|| !allowForeignRadioTransmit()
|| !profiles || profile != 1 || !profiles->enabled() || !profiles->canTransmit(profile)
|| profiles->params(profile).protocol != RadioProfileProtocol::Meshtext
|| profiles->params(profile).protocol != protocol
|| generation != profiles->generation[profile]) return false;
memcpy(foreign_radio_bytes, bytes, length);
foreign_radio_length = (uint16_t)length;
foreign_radio_profile = profile;
foreign_radio_protocol = protocol;
foreign_radio_generation = generation;
foreign_radio_retry_at = foreign_radio_prepare_deadline = 0;
foreign_radio_sending = false;
@@ -313,9 +368,14 @@ bool Dispatcher::queueForeignRadioFrame(const uint8_t* bytes, size_t length,
void Dispatcher::finishForeignRadioFrame(bool success, bool account_airtime) {
if (!hasForeignRadioFrame()) return;
const bool direct_ota = foreign_radio_protocol == RadioProfileProtocol::MeshCore;
if (account_airtime) {
const uint32_t elapsed = (uint32_t)_ms->getMillis() - foreign_radio_start;
total_air_time += elapsed;
if (direct_ota) {
ota_tx_finished_at = _ms->getMillis();
ota_tx_airtime = elapsed;
}
updateTxBudget();
tx_budget_ms = elapsed >= tx_budget_ms ? 0 : tx_budget_ms - elapsed;
if (tx_budget_ms < MIN_TX_BUDGET_RESERVE_MS) {
@@ -328,11 +388,24 @@ void Dispatcher::finishForeignRadioFrame(bool success, bool account_airtime) {
// explicit user message. No retry is scheduled after any failure/timeout.
foreign_radio_length = 0;
foreign_radio_sending = false;
#if MESH_ENABLE_OTA_KISS_DIRECT
foreign_radio_ota_epoch = 0;
#endif
foreign_radio_yield_meshcore = true;
profile_cad_busy[foreign_radio_profile] = 0;
foreign_radio_retry_at = foreign_radio_prepare_deadline = 0;
radio_nonrx_start = _ms->getMillis();
onForeignRadioSendComplete(success);
// A direct OTA packet is not a Meshtext/Ethernet send, and must not change
// either transport's application counters or trigger its callbacks.
if (direct_ota) {
if (success) ++n_sent_direct;
} else onForeignRadioSendComplete(success);
}
bool Dispatcher::discardQueuedForeignRadioFrame(RadioProfileProtocol protocol) {
if (!hasForeignRadioFrame() || foreign_radio_sending || foreign_radio_protocol != protocol) return false;
finishForeignRadioFrame(false, false);
return true;
}
bool Dispatcher::serviceForeignRadioFrame() {
@@ -365,6 +438,11 @@ bool Dispatcher::checkForeignRadioSend() {
}
if (!restoreOutboundTxOverrides() || _radio->isCarrierWaveActive()) return false;
const uint32_t now = _ms->getMillis();
if (foreign_radio_protocol == RadioProfileProtocol::MeshCore && ota_tx_airtime) {
const uint32_t quiet = ota::packetQuietTime(ota_tx_airtime, getOtaPacketSpeedFactor());
if (now - ota_tx_finished_at < quiet) return false;
ota_tx_airtime = 0;
}
// Continuous explicit foreign chat must leave due MeshCore traffic a turn
// between messages; a blocked/absent MeshCore queue does not stall MT.
if (foreign_radio_yield_meshcore && _mgr->getOutboundCount(now) > 0) {
@@ -472,7 +550,7 @@ void Dispatcher::logPacketLine(const char* direction, const Packet* packet,
bool Dispatcher::getNextQueueWakeDelay(uint32_t& delay_millis) const {
if (isDualRadioActive()) { delay_millis = 0; return true; }
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_FOREIGN_RADIO
if (hasForeignRadioFrame()) { delay_millis = 0; return true; }
#endif
const uint32_t now = _ms->getMillis();
@@ -576,7 +654,7 @@ void Dispatcher::loop() {
// A maintenance carrier has no TxDone packet. Keep its deadline serviced,
// but leave queued packets and RX/AGC watchdogs alone until normal RX returns.
if (_radio->isCarrierWaveActive()) return;
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_FOREIGN_RADIO
// Use the same physical-radio owner and cleanup path as MeshCore TX. A
// foreign packet never enters the MeshCore retry/forwarding machinery.
if (serviceForeignRadioFrame()) return;
@@ -840,7 +918,7 @@ void Dispatcher::loop() {
#if MESH_ENABLE_TX_BEACONS
if (checkBeaconRadioSend()) { releaseDroppedOutbound(); return; }
#endif
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_FOREIGN_RADIO
if (!checkForeignRadioSend()) checkSend();
#else
checkSend();
@@ -942,13 +1020,23 @@ void Dispatcher::checkRecv() {
const uint8_t profile = _radio->receiveProfile();
const auto* profiles = _radio->profiles();
// A logical tuple may have been replaced while the physical modem was
// completing RX. Never reinterpret old Ethernet/Meshtext bytes under
// the new MeshCore tuple, even for raw logs or bridge hooks.
if (profiles && (profile >= 2
|| _radio->receiveProfileGeneration() != profiles->generation[profile])) {
_radio->onReceiveProcessed();
return;
}
// Protocol is selected by the receiving modem, never guessed from a
// payload byte. No foreign bytes may leak into MeshCore raw sinks,
// parsing, duplicate suppression, direct forwarding, or app counters.
if (profiles && profile < 2
&& profiles->params(profile).protocol == RadioProfileProtocol::Meshtext) {
#if MESH_ENABLE_MESHTEXT_CHAT
if (profiles->enabled() && _radio->receiveProfileGeneration() == profiles->generation[profile]) {
&& profiles->params(profile).protocol != RadioProfileProtocol::MeshCore) {
#if MESH_ENABLE_FOREIGN_RADIO
if (profile == 1 && profiles->enabled()
&& supportsForeignRadioProtocol(profiles->params(profile).protocol)
&& _radio->receiveProfileGeneration() == profiles->generation[profile]) {
rx_air_time += _radio->getProfileAirtime(profile, len);
++_radio->profiles()->rx_packets[profile];
onForeignRadioFrame(raw, (size_t)len, profile, profiles->generation[profile], snr, rssi);
@@ -958,6 +1046,23 @@ void Dispatcher::checkRecv() {
return;
}
#if MESH_ENABLE_OTA_KISS_DIRECT
// Consume the reserved direct extension before Packet allocation and
// before normal raw logs/bridges. Old firmware rejects its version.
// Malformed/unsolicited frames never become routed MeshCore traffic.
if (ota::ota_direct_wire_marker(raw, (size_t)len)) {
if (profiles && profile < 2
&& onDirectOtaRadioFrame(raw, (size_t)len, profile,
_radio->receiveProfileGeneration())) {
rx_air_time += _radio->getProfileAirtime(profile, len);
++_radio->profiles()->rx_packets[profile];
++n_recv_direct;
}
_radio->onReceiveProcessed();
return;
}
#endif
// TRACE and CONTROL are direct-only. Reject a flood framing before
// raw hooks can expose it to USB logs, MQTT, ESP-NOW, or another bridge.
// The header check is deliberate: it also holds when the packet pool is
+26 -4
View File
@@ -92,6 +92,7 @@ public:
virtual const RadioProfiles* profiles() const { return nullptr; }
virtual bool validateProfile(const RadioProfileParams&) const { return false; }
virtual bool supportsMeshtext() const { return false; }
virtual bool supportsEthernetTunnel() const { return false; }
#if MESH_ENABLE_TX_BEACONS
virtual RadioParamApplyResult prepareBeaconTransmit(const RadioProfileParams&, int8_t) {
return RadioParamApplyResult::FAILED;
@@ -395,17 +396,22 @@ class Dispatcher {
unsigned long tx_budget_ms;
unsigned long last_budget_update;
unsigned long duty_cycle_window_ms;
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_FOREIGN_RADIO
// One bounded user-send slot; never placed in the MeshCore packet pool.
uint8_t foreign_radio_bytes[MAX_TRANS_UNIT] = {};
uint16_t foreign_radio_length = 0;
uint8_t foreign_radio_profile = 0;
RadioProfileProtocol foreign_radio_protocol = RadioProfileProtocol::MeshCore;
uint32_t foreign_radio_generation = 0;
#if MESH_ENABLE_OTA_KISS_DIRECT
uint32_t foreign_radio_ota_epoch = 0;
#endif
uint32_t foreign_radio_retry_at = 0, foreign_radio_prepare_deadline = 0;
uint32_t foreign_radio_start = 0, foreign_radio_expiry = 0;
bool foreign_radio_sending = false;
bool foreign_radio_yield_meshcore = false;
bool isForeignRadioCurrent() const;
bool supportsForeignRadioProtocol(RadioProfileProtocol protocol) const;
bool serviceForeignRadioFrame();
bool checkForeignRadioSend();
void finishForeignRadioFrame(bool success, bool account_airtime);
@@ -490,13 +496,29 @@ protected:
virtual void onTracePacketQueuedForSend(Packet* packet) { }
virtual void onSendComplete(Packet* packet) { }
virtual void onSendFail(Packet* packet) { }
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_FOREIGN_RADIO
// Foreign RX is consumed here before MeshCore parsing or any raw bridge.
// Returning false drops the frame; it never falls through to MeshCore.
virtual bool onForeignRadioFrame(const uint8_t*, size_t, uint8_t, uint32_t, float, float) { return false; }
virtual void onForeignRadioSendComplete(bool) { }
virtual bool allowForeignRadioTransmit() const { return true; }
bool queueForeignRadioFrame(const uint8_t* bytes, size_t length, uint8_t profile, uint32_t generation);
#if MESH_ENABLE_OTA_KISS_DIRECT
// The KISS host framing is off-air. These are bounded, zero-hop OTA radio
// frames, never Packet objects and never a second physical TX owner.
virtual bool onDirectOtaRadioFrame(const uint8_t*, size_t, uint8_t, uint32_t) { return false; }
virtual bool allowDirectOtaTransmit(uint8_t, uint32_t) const { return false; }
// Captured when queued: abort, fallback and workspace replacement retire
// this token even when the physical temporary profile remains unchanged.
virtual uint32_t directOtaEpoch() const { return 0; }
bool queueDirectOtaRadioFrame(const uint8_t* message, uint16_t length,
uint8_t profile, uint32_t generation);
#endif
bool queueForeignRadioFrame(const uint8_t* bytes, size_t length, uint8_t profile, uint32_t generation,
RadioProfileProtocol protocol = RadioProfileProtocol::Meshtext);
RadioProfileProtocol queuedForeignRadioProtocol() const { return foreign_radio_protocol; }
// Cancel host work that has not reached RF. An in-flight frame cannot be
// unsent and retains normal completion/airtime accounting.
bool discardQueuedForeignRadioFrame(RadioProfileProtocol protocol);
bool hasForeignRadioFrame() const { return foreign_radio_length != 0; }
#endif
virtual void onRadioProfileCopyQueued(Packet* packet, const Packet* original, uint8_t priority) { }
@@ -597,7 +619,7 @@ public:
#if MESH_ENABLE_TX_BEACONS
|| hasBeaconRadioFrame()
#endif
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_FOREIGN_RADIO
|| hasForeignRadioFrame()
#endif
;
+77 -11
View File
@@ -7,6 +7,9 @@
#include "helpers/ota/OtaContext.h" // OTA mesh-integration is centralized here so every role gets it
#include "helpers/ota/OtaSpeedConfig.h"
#include "helpers/ota/OtaProtocol.h" // decode_adv -> the `ota neighbors` discovery table
#if MESH_ENABLE_OTA_KISS_DIRECT
#include "helpers/ota/OtaDirectWire.h"
#endif
#if !defined(OTA_SEEDER_ONLY)
#include "helpers/ota/OtaSelf.h" // ota_self_firmware -> auto-advertise our own image
#endif
@@ -196,6 +199,15 @@ static int queuedPacedOtaResponses(PacketManager* manager) {
bool Mesh::otaSendAdapter(void* ctx, const uint8_t* msg, uint16_t len, bool /*flood*/) {
Mesh* m = (Mesh*)ctx;
if (!m->isAnyTempRadioActive()) return false;
const auto* context = ota::ota_context_if_active();
const auto route = context ? context->manager.replyRoute() : ota::OtaReplyRoute{};
#if MESH_ENABLE_OTA_KISS_DIRECT
if (route.direct) {
// KISS/raw frames bypass the routed Packet pool entirely. The shared
// single-frame owner retains exact profile affinity until actual TxDone.
return m->queueDirectOtaRadioFrame(msg, len, route.profile, route.generation);
}
#endif
const bool paced = isPacedOtaResponse(msg, len);
const int queued = paced ? queuedPacedOtaResponses(m->_mgr) : 0;
// Routine OTA backpressure must not attempt an allocation, which would
@@ -205,16 +217,17 @@ bool Mesh::otaSendAdapter(void* ctx, const uint8_t* msg, uint16_t len, bool /*fl
Packet* p = m->createOtaPacket(msg, len);
if (!p) return false;
p->radio_reply = len && ota::ota_is_response_message(msg[0]);
if (p->radio_reply) {
if (const auto* context = ota::ota_context_if_active()) {
const auto route = context->manager.replyRoute();
if (route.profile < 2) {
// DATA, PROOF and MANIFEST are emitted after the RX call stack ends.
// Restore origin only; normal reply policy still decides one/both TX.
p->radio_profile = p->radio_origin = route.profile;
p->radio_generation = p->radio_origin_generation = route.generation;
p->radio_local = false;
}
if (route.profile < 2) {
// DATA, PROOF and MANIFEST are emitted after the RX call stack ends.
// Restore origin only; normal reply policy still decides one/both TX.
p->radio_profile = p->radio_origin = route.profile;
p->radio_generation = p->radio_origin_generation = route.generation;
p->radio_local = false;
// A direct negotiation fallback stays on its original physical
// session instead of silently moving onto a replacement profile.
if (!p->radio_reply) {
p->radio_bound = true;
p->tx_radio = route.profile == 0 ? RADIO_TX_PRIMARY : RADIO_TX_SECONDARY;
}
}
const uint8_t mask = m->getTransmitProfileMask(p);
@@ -233,6 +246,46 @@ bool Mesh::otaSendAdapter(void* ctx, const uint8_t* msg, uint16_t len, bool /*fl
// Runtime OTA flood reach (`ota config hops`, persisted in NodePrefs): accept packets up to N hops away and
// relay those still under N hops. 0 = direct only. Overridable per-role by subclassing.
uint8_t Mesh::getOtaHopLimit() const { return ota::ota_hop_limit(); }
#if MESH_ENABLE_OTA_KISS_DIRECT
uint32_t Mesh::directOtaEpoch() const {
const auto* context = ota::ota_context_if_active();
return context ? context->manager.directTransportEpoch() : 0;
}
bool Mesh::allowDirectOtaTransmit(uint8_t profile, uint32_t generation) const {
if (!isAnyTempRadioActive() || !allowPacketTransmit(nullptr)) return false;
const auto* profiles = _radio->profiles();
if (!profiles || profile >= 2 || generation != profiles->generation[profile]
|| profiles->params(profile).protocol != RadioProfileProtocol::MeshCore
|| !profiles->canTransmit(profile)) return false;
// Never infer a normal-channel TX opportunity from a temporary window on
// the other tuple. Explicit cross policy retains its existing meaning.
return (profile == 0 ? (isTempRadioActive() || profiles->primary_temporary)
: profiles->secondary_temporary)
|| profiles->cross == RadioCrossMode::On;
}
bool Mesh::onDirectOtaRadioFrame(const uint8_t* bytes, size_t length,
uint8_t profile, uint32_t generation) {
const uint8_t* message;
uint16_t message_len;
if (!allowDirectOtaTransmit(profile, generation)
|| !ota::ota_direct_wire_decode(bytes, length, message, message_len)) return false;
auto* context = ota::ota_context_if_active();
if (!context) return false; // unsolicited bytes cannot allocate an OTA arena
syncOtaTiming(context->manager);
context->manager.set_direct_transport_enabled(true);
context->manager.note_rx_path_hops(0);
ota::OtaReplyRoute route;
route.profile = profile;
route.generation = generation;
route.direct = true;
context->manager.on_message(message, message_len, route);
context->track_session(context->manager.fetchState(), _ms->getMillis());
return true;
}
#endif
#endif
void Mesh::begin() {
@@ -463,6 +516,9 @@ void __attribute__((noinline)) Mesh::serviceLoopMaintenance() {
if (!ota_active) {
if (_ota_temp_was_active) {
ota::ota_ctx().manager.clearPendingEgress();
#if MESH_ENABLE_OTA_KISS_DIRECT
discardQueuedForeignRadioFrame(RadioProfileProtocol::MeshCore);
#endif
resetOtaRelayBackoff();
}
_ota_temp_was_active = false;
@@ -485,7 +541,11 @@ void __attribute__((noinline)) Mesh::serviceLoopMaintenance() {
syncOtaTiming(ota::ota_ctx().manager);
ota::ota_ctx().manager.serviceEgress([](void* ctx, const ota::OtaReplyRoute& route) {
if (route.profile == 0xFF) return true;
const auto* profiles = static_cast<Mesh*>(ctx)->_radio->profiles();
const auto* mesh = static_cast<Mesh*>(ctx);
const auto* profiles = mesh->_radio->profiles();
#if MESH_ENABLE_OTA_KISS_DIRECT
if (route.direct) return mesh->allowDirectOtaTransmit(route.profile, route.generation);
#endif
// A completed/reconfigured temp session must not leak its retained replies
// onto the replacement channel, or pin a stale descriptor behind backpressure.
return route.profile < 2 && (!profiles ? route.profile == 0
@@ -1412,6 +1472,12 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
ota::OtaReplyRoute route;
route.profile = pkt->radio_profile;
route.generation = pkt->radio_generation;
#if MESH_ENABLE_OTA_KISS_DIRECT
if (!context->manager.directFetchActive()) {
context->manager.set_direct_transport_enabled(
allowDirectOtaTransmit(route.profile, route.generation));
}
#endif
terminal_ota = context->manager.on_message(pkt->payload, pkt->payload_len, route);
context->track_session(context->manager.fetchState(), _ms->getMillis());
onOtaRecv(pkt);
+6
View File
@@ -558,6 +558,12 @@ protected:
// OTA mesh-integration is centralized in Mesh::begin()/loop()/dispatch, so every role (repeater,
// companion, room, sensor, ...) gets fetch/serve/apply without per-example wiring.
static bool otaSendAdapter(void* ctx, const uint8_t* msg, uint16_t len, bool flood);
#if MESH_ENABLE_OTA_KISS_DIRECT
bool allowDirectOtaTransmit(uint8_t profile, uint32_t generation) const override;
uint32_t directOtaEpoch() const override;
bool onDirectOtaRadioFrame(const uint8_t* bytes, size_t length, uint8_t profile,
uint32_t generation) override;
#endif
void syncOtaTiming(ota::OtaManager& manager);
unsigned long _next_ota_tick = 0;
ota::LongTimer _ota_announce_timer; // supports long scaled intervals across millis rollovers
+5 -4
View File
@@ -9,7 +9,7 @@ namespace mesh {
enum class RadioProfileMode : uint8_t { Off = 0, Rx = 1, RxTx = 2 };
enum class RadioCrossMode : uint8_t { Auto = 0, On = 1, Off = 2 };
enum class RadioProfileProtocol : uint8_t { MeshCore = 0, Meshtext = 1 };
enum class RadioProfileProtocol : uint8_t { MeshCore = 0, Meshtext = 1, Ethernet = 2 };
// These are modulation profiles of ONE transceiver, never additional radios.
struct RadioProfileParams {
@@ -42,7 +42,7 @@ class RadioProfiles {
static constexpr double MinFastListenSymbols = MinListenSymbols;
static constexpr uint8_t AcquisitionSymbols = 8;
static constexpr uint16_t MaxPreamble = 65528;
static constexpr uint16_t MaxAutomaticPreamble = 128;
static constexpr uint16_t MaxAutomaticPreamble = 512;
// Successful RX-to-RX hops self-test the board-specific switch allowance.
// Packet receptions can extend a visit. No fixed loop allowance is added to
// the self-tested, guarded switch time in the idle-scan timing model.
@@ -120,7 +120,8 @@ class RadioProfiles {
static bool valid(const RadioProfileParams& p) {
if (!isfinite(p.freq) || !isfinite(p.bw) || p.freq < 150 || p.freq > 2500
|| p.sf < 5 || p.sf > 12 || p.cr < 5 || p.cr > 8
|| (p.protocol != RadioProfileProtocol::MeshCore && p.protocol != RadioProfileProtocol::Meshtext)
|| (p.protocol != RadioProfileProtocol::MeshCore && p.protocol != RadioProfileProtocol::Meshtext
&& p.protocol != RadioProfileProtocol::Ethernet)
|| (p.preamble != 0 && (p.preamble < 8 || p.preamble > MaxPreamble))) return false;
static constexpr float bandwidths[] = {7.8f, 10.4f, 15.6f, 20.8f, 31.25f, 41.7f,
62.5f, 125, 250, 500, 1000, 812.5f, 1625};
@@ -247,7 +248,7 @@ class RadioProfiles {
for (uint8_t i = 0; i < (enabled() ? 2 : 1); ++i) {
if (!valid(params(i)) || !safePreamble(params(i), preamble(i, 32))) return false;
}
// Recommendations over 128 are reported as unsafe, but the profile can
// Recommendations above the automatic cap remain visible, but the profile can
// still run at the cap when its physical preamble is legal.
// A foreign network fixes its own preamble and cannot advertise our scan
// cycle. Accept safe wire settings, but do not claim loss-free scanning.
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <RadioTxPolicy.h>
#include <stddef.h>
#include <stdint.h>
namespace mesh { namespace companion { namespace traffic {
// A checked append-only preference footer. The existing preference image and
// any board-specific footer retain their published positions.
static constexpr size_t FooterSize = 8;
inline uint16_t checksum(const uint8_t* bytes, size_t size) {
uint16_t crc = 0xffff;
for (size_t i = 0; i < size; ++i) {
crc ^= static_cast<uint16_t>(bytes[i]) << 8;
for (unsigned bit = 0; bit < 8; ++bit)
crc = (crc & 0x8000) ? static_cast<uint16_t>((crc << 1) ^ 0x1021)
: static_cast<uint16_t>(crc << 1);
}
return crc;
}
inline void encodeFooter(uint8_t out[FooterSize], uint8_t media, uint8_t ssh) {
out[0] = 'T'; out[1] = 'X'; out[2] = 'R'; out[3] = 1;
out[4] = encodeRadioTxPolicy(media);
out[5] = encodeRadioTxPolicy(ssh);
const uint16_t crc = checksum(out, 6);
out[6] = static_cast<uint8_t>(crc >> 8);
out[7] = static_cast<uint8_t>(crc);
}
inline bool validPolicyByte(uint8_t value) {
return value == 0 || (value >= 0xa1 && value <= 0xa4);
}
inline bool decodeFooter(const uint8_t* in, size_t size,
uint8_t& media, uint8_t& ssh) {
if (!in || size != FooterSize || in[0] != 'T' || in[1] != 'X'
|| in[2] != 'R' || in[3] != 1
|| !validPolicyByte(in[4]) || !validPolicyByte(in[5])
|| checksum(in, 6) != static_cast<uint16_t>((in[6] << 8) | in[7]))
return false;
media = decodeRadioTxPolicy(in[4]);
ssh = decodeRadioTxPolicy(in[5]);
return true;
}
} } } // namespace mesh::companion::traffic
+98
View File
@@ -0,0 +1,98 @@
#pragma once
#include <RadioProfiles.h>
#include <stddef.h>
#include <string.h>
namespace mesh { namespace companion {
enum class TrafficKind : uint8_t { Other, Media, Ssh };
// Channel application IDs, not new MeshCore packet types. SSH is an opt-in
// contract for tunnel clients, not a claim that opaque bytes can be inspected.
static constexpr uint16_t MEDIA_CHANNEL_DATA_TYPE = 0x5643; // Open TAK 'VC'
static constexpr uint16_t SSH_CHANNEL_DATA_TYPE = 0x5353; // 'SS'
inline TrafficKind groupTrafficKind(uint16_t data_type) {
return data_type == MEDIA_CHANNEL_DATA_TYPE ? TrafficKind::Media
: data_type == SSH_CHANNEL_DATA_TYPE ? TrafficKind::Ssh : TrafficKind::Other;
}
inline TrafficKind rawTrafficKind(const uint8_t* data, size_t length) {
if (!data || !length) return TrafficKind::Other;
// Open TAK's VE3/VOX binary clip packets also carry photos. Do not capture
// every RAW_CUSTOM application just because the media app uses that API.
if ((data[0] == 0x56 && length >= 7) || (data[0] == 0x57 && length >= 8))
return TrafficKind::Media;
if (data[0] == 0x72 && length >= 13) {
const uint8_t flags = data[5];
const size_t count = data[12];
if ((flags & ~7U) || (!(flags & 1) && count) || count > length - 13)
return TrafficKind::Other;
const size_t end = 13 + count;
if (!(flags & 4)) return length == end ? TrafficKind::Media : TrafficKind::Other;
if (length > end && data[end] <= 63 && length - end - 1 == data[end])
return TrafficKind::Media;
return TrafficKind::Other;
}
// Tunnel apps must opt in on EVERY packet, including their encrypted data,
// ACKs and retries: ['S']['S']['H'][version=1][application bytes...]. The
// envelope is passed through unchanged; it is not an SSH implementation.
if (length >= 5 && !memcmp(data, "SSH\x01", 4)) return TrafficKind::Ssh;
return TrafficKind::Other;
}
inline uint8_t trafficPolicy(TrafficKind kind, uint8_t media, uint8_t ssh) {
return kind == TrafficKind::Media ? media
: kind == TrafficKind::Ssh ? ssh : static_cast<uint8_t>(RADIO_TX_AUTO);
}
inline uint8_t trafficTransmitMask(uint8_t policy, const RadioProfiles* profiles) {
uint8_t mask = policy == RADIO_TX_AUTO ? (profiles ? profiles->transmitMask(0) : 1)
: explicitRadioTxMask(policy, profiles && profiles->canTransmit(1));
// Match Dispatcher: MeshCore datagrams cannot be sent on a Meshtext profile,
// even if that profile is configured rxtx.
if (profiles) {
for (uint8_t i = 0; i < 2; ++i) {
if (profiles->params(i).protocol != RadioProfileProtocol::MeshCore)
mask &= static_cast<uint8_t>(~(1U << i));
}
}
return mask;
}
struct TrafficRouteCommand {
bool matched = false;
bool valid = false;
bool set = false;
TrafficKind kind = TrafficKind::Other;
uint8_t policy = RADIO_TX_AUTO;
};
inline TrafficRouteCommand parseTrafficRouteCommand(const char* text) {
TrafficRouteCommand result;
if (!text) return result;
if (!strncmp(text, "get ", 4)) result.set = false;
else if (!strncmp(text, "set ", 4)) result.set = true;
else return result;
text += 4;
if (!strncmp(text, "tx.media", 8)) result.kind = TrafficKind::Media;
else if (!strncmp(text, "tx.ssh", 6)) result.kind = TrafficKind::Ssh;
else return result;
text += result.kind == TrafficKind::Media ? 8 : 6;
if (*text && *text != ' ' && *text != '\t') return result;
result.matched = true;
while (*text == ' ' || *text == '\t') ++text;
const char* end = text + strlen(text);
while (end > text && (end[-1] == ' ' || end[-1] == '\t')) --end;
if (!result.set) { result.valid = end == text; return result; }
char value[8];
const size_t length = end - text;
if (!length || length >= sizeof(value)) return result;
memcpy(value, text, length);
value[length] = 0;
result.valid = parseRadioTxPolicy(value, result.policy);
return result;
}
} } // namespace mesh::companion
+157
View File
@@ -0,0 +1,157 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace mesh { namespace ethernet {
static constexpr size_t MinimumFrameSize = 14;
static constexpr size_t MaxFrameSize = 255;
static constexpr size_t QueueDepth = 2;
static constexpr size_t MaxEncodedSize = 2 * MaxFrameSize + 3;
static constexpr uint8_t Fend = 0xc0;
static constexpr uint8_t Fesc = 0xdb;
static constexpr uint8_t Tfend = 0xdc;
static constexpr uint8_t Tfesc = 0xdd;
// Only standard port-0 DATA frames are accepted. Ethernet bytes are not
// interpreted, wrapped, padded or truncated here: ARP and all IP fragments
// must traverse the same link as the TCP connection they support.
class KissCodec {
struct Frame {
uint16_t length = 0;
uint8_t bytes[MaxFrameSize];
};
struct EncodedFrame {
uint16_t length = 0;
uint8_t bytes[MaxEncodedSize];
};
Frame _transmit[QueueDepth];
EncodedFrame _receive[QueueDepth];
uint8_t _transmitHead = 0, _transmitCount = 0;
uint8_t _receiveHead = 0, _receiveCount = 0;
uint16_t _outputOffset = 0;
uint8_t _input[MaxFrameSize];
uint16_t _inputLength = 0;
bool _framed = false, _command = false, _discard = false, _escaped = false;
uint32_t _receivedFrames = 0, _sentFrames = 0, _malformed = 0, _dropped = 0;
void rejectInput() {
if (!_discard) ++_malformed;
_discard = true;
}
public:
// Session resets deliberately preserve lifetime diagnostic counters.
void resetPending() {
_transmitHead = _transmitCount = _receiveHead = _receiveCount = 0;
_outputOffset = _inputLength = 0;
_framed = _command = _discard = _escaped = false;
}
bool canAcceptByte() const { return _transmitCount < QueueDepth; }
// False means the caller must retain this byte and apply TCP backpressure.
// The socket adapter checks canAcceptByte() BEFORE consuming a socket byte.
bool feed(uint8_t byte) {
if (!canAcceptByte()) return false;
if (byte == Fend) {
if (_framed && _command && !_discard) {
if (_escaped || (_inputLength && _inputLength < MinimumFrameSize)) {
rejectInput();
} else if (_inputLength >= MinimumFrameSize) {
Frame& frame = _transmit[(_transmitHead + _transmitCount) % QueueDepth];
memcpy(frame.bytes, _input, _inputLength);
frame.length = _inputLength;
++_transmitCount;
++_receivedFrames;
}
}
// One FEND can close the last frame and start the next one.
_framed = true;
_command = _discard = _escaped = false;
_inputLength = 0;
return true;
}
if (!_framed || _discard) return true;
if (!_command) {
_command = true;
// Other ports and control commands are ignored until the next boundary.
if (byte != 0) _discard = true;
return true;
}
if (_escaped) {
_escaped = false;
if (byte == Tfend) byte = Fend;
else if (byte == Tfesc) byte = Fesc;
else { rejectInput(); return true; }
} else if (byte == Fesc) {
_escaped = true;
return true;
}
if (_inputLength >= MaxFrameSize) { rejectInput(); return true; }
_input[_inputLength++] = byte;
return true;
}
bool peekTransmit(const uint8_t*& bytes, size_t& length) const {
if (!_transmitCount) { bytes = nullptr; length = 0; return false; }
bytes = _transmit[_transmitHead].bytes;
length = _transmit[_transmitHead].length;
return true;
}
void consumeTransmit() {
if (!_transmitCount) return;
_transmitHead = (_transmitHead + 1) % QueueDepth;
--_transmitCount;
}
bool queueReceive(const uint8_t* bytes, size_t length) {
if (!bytes || length < MinimumFrameSize || length > MaxFrameSize
|| _receiveCount >= QueueDepth) { ++_dropped; return false; }
EncodedFrame& frame = _receive[(_receiveHead + _receiveCount) % QueueDepth];
size_t at = 0;
frame.bytes[at++] = Fend;
frame.bytes[at++] = 0; // KISS port-0 DATA, never a companion binary frame.
for (size_t i = 0; i < length; ++i) {
const uint8_t byte = bytes[i];
if (byte == Fend || byte == Fesc) {
frame.bytes[at++] = Fesc;
frame.bytes[at++] = byte == Fend ? Tfend : Tfesc;
} else frame.bytes[at++] = byte;
}
frame.bytes[at++] = Fend;
frame.length = static_cast<uint16_t>(at);
++_receiveCount;
return true;
}
bool peekOutput(const uint8_t*& bytes, size_t& length) const {
if (!_receiveCount) { bytes = nullptr; length = 0; return false; }
bytes = _receive[_receiveHead].bytes + _outputOffset;
length = _receive[_receiveHead].length - _outputOffset;
return true;
}
void consumeOutput(size_t length) {
if (!_receiveCount) return;
const size_t remaining = _receive[_receiveHead].length - _outputOffset;
if (length >= remaining) {
_outputOffset = 0;
_receiveHead = (_receiveHead + 1) % QueueDepth;
--_receiveCount;
++_sentFrames;
} else _outputOffset += static_cast<uint16_t>(length);
}
uint8_t pendingTransmit() const { return _transmitCount; }
uint8_t pendingReceive() const { return _receiveCount; }
uint32_t receivedFrames() const { return _receivedFrames; }
uint32_t sentFrames() const { return _sentFrames; }
uint32_t malformedFrames() const { return _malformed; }
uint32_t droppedFrames() const { return _dropped; }
};
} } // namespace mesh::ethernet
+22
View File
@@ -0,0 +1,22 @@
#pragma once
// Ethernet tunnelling is a host-assisted ESP32 Full Companion transport.
// Deliberately independent of radio-chip macros: some Arduino variants reveal
// their chip only after this header is consumed in other translation units.
// A concrete driver must additionally advertise the wire capability.
#ifndef MESH_ENABLE_ETHERNET_TUNNEL
#if defined(ESP32_PLATFORM) && defined(COMPANION_RADIO_FULL) \
&& defined(WIFI_SSID) \
&& !(defined(MESH_PRIMARY_ESPNOW) && MESH_PRIMARY_ESPNOW)
#define MESH_ENABLE_ETHERNET_TUNNEL 1
#else
#define MESH_ENABLE_ETHERNET_TUNNEL 0
#endif
#endif
// Raw KISS modems may opt into the same LoRa wire format without including
// Companion ownership, its foreign-frame dispatcher slot, or a WiFi server.
// Keep this independent of board macros so every translation unit agrees.
#ifndef MESH_ENABLE_ETHERNET_WIRE
#define MESH_ENABLE_ETHERNET_WIRE MESH_ENABLE_ETHERNET_TUNNEL
#endif
+62
View File
@@ -0,0 +1,62 @@
#pragma once
#include <RadioProfiles.h>
#include <string.h>
namespace mesh { namespace ethernet {
struct Settings {
bool enabled = false;
bool configured = false;
RadioProfileParams radio;
Settings() { radio.protocol = RadioProfileProtocol::Ethernet; }
};
static constexpr size_t SettingsSize = 32;
inline uint32_t settingsChecksum(const uint8_t* bytes, size_t length) {
uint32_t crc = 0xffffffff;
while (length--) {
crc ^= *bytes++;
for (unsigned i = 0; i < 8; ++i) crc = (crc >> 1) ^ ((crc & 1) ? 0xedb88320U : 0);
}
return crc;
}
inline bool validSettings(const Settings& value) {
return (!value.enabled || value.configured)
&& (!value.configured || (value.radio.protocol == RadioProfileProtocol::Ethernet
&& RadioProfiles::valid(value.radio) && value.radio.preamble >= 8
&& RadioProfiles::safePreamble(value.radio, value.radio.preamble)));
}
inline void encodeSettings(uint8_t image[SettingsSize], const Settings& value) {
memset(image, 0, SettingsSize);
memcpy(image, "ETH1", 4);
image[4] = value.enabled; image[5] = value.configured;
image[6] = value.radio.sf; image[7] = value.radio.cr;
memcpy(image + 8, &value.radio.freq, 4);
memcpy(image + 12, &value.radio.bw, 4);
memcpy(image + 16, &value.radio.preamble, 2);
const uint32_t crc = settingsChecksum(image, SettingsSize - 4);
memcpy(image + SettingsSize - 4, &crc, 4);
}
inline bool decodeSettings(const uint8_t* image, size_t length, Settings& value) {
if (!image || length != SettingsSize || memcmp(image, "ETH1", 4)
|| image[4] > 1 || image[5] > 1) return false;
uint32_t crc;
memcpy(&crc, image + SettingsSize - 4, 4);
if (crc != settingsChecksum(image, SettingsSize - 4)) return false;
for (size_t i = 18; i < SettingsSize - 4; ++i) if (image[i]) return false;
Settings loaded;
loaded.enabled = image[4]; loaded.configured = image[5];
loaded.radio.sf = image[6]; loaded.radio.cr = image[7];
memcpy(&loaded.radio.freq, image + 8, 4);
memcpy(&loaded.radio.bw, image + 12, 4);
memcpy(&loaded.radio.preamble, image + 16, 2);
if (!validSettings(loaded)) return false;
value = loaded;
return true;
}
} } // namespace mesh::ethernet
+9
View File
@@ -1,6 +1,8 @@
#pragma once
#include "BeaconFeatureConfig.h"
#include "EthernetTunnelConfig.h"
#include "ota/OtaDirectConfig.h"
// Resolve the chip in every translation unit, including Dispatcher.cpp which
// includes this before Arduino.h. Otherwise different class layouts could be
@@ -40,3 +42,10 @@
#define MESH_ENABLE_MESHTEXT_WIRE 0
#endif
#endif
// Foreign transports and negotiated direct KISS OTA share one bounded raw
// dispatcher slot. Direct OTA retains its temporary MeshCore profile; foreign
// transports keep their existing radio2-only ownership.
#ifndef MESH_ENABLE_FOREIGN_RADIO
#define MESH_ENABLE_FOREIGN_RADIO (MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL || MESH_ENABLE_OTA_KISS_DIRECT)
#endif
+36 -21
View File
@@ -3,6 +3,7 @@
#include "RadioProfileCommandUtils.h"
#include "FilePresence.h"
#include "radiolib/RXPowerSaving.h"
#include "radiolib/HilTxFrequencyGuard.h"
#include <Arduino.h>
#include <stdio.h>
#include <string.h>
@@ -147,7 +148,7 @@ bool RadioProfileCLI::prepareSavedImage(const char* path, const RadioProfileConf
uint16_t preamble, RadioCrossMode cross, int8_t manual_secondary) {
if (!fs_ || hold_) return false;
uint8_t image[ImageSize] = {'R', '2', 1, (uint8_t)config.mode};
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
// Version 2 keeps the 24-byte layout and CRC; bit 7 records explicit radio2
// intent. Other settings can save an unused Off slot without claiming it.
image[2] = 2;
@@ -188,7 +189,7 @@ void RadioProfileCLI::begin(FILESYSTEM* fs, Radio* radio, RTCClock* rtc, bool in
recoverable_corrupt_store_ = false;
manual_secondary_ = false;
secondary_intent_generation_ = 0;
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
auto_secondary_requested_ = secondary_protocol_overlay_ = false;
owns_secondary_runtime_ = external_secondary_override_ = false;
#endif
@@ -277,19 +278,19 @@ void RadioProfileCLI::publish() {
? (validReplySetting(reply_setting_) ? reply_setting_ & 7 : RADIO_TX_BOTH) : RADIO_TX_AUTO;
radio_->profiles()->reply_force = infrastructure_replies_
&& validReplySetting(reply_setting_) && (reply_setting_ & 8);
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
protectExternalSecondary();
if (external_secondary_override_) return;
#endif
if (publish_pending_ && (int32_t)(millis() - publish_after_ms_) < 0) return;
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
// An accepted remote command owns the old RX generation until its reply has
// completed (or its atomic storage commit has succeeded).
if (hasReplyMutation()) return;
#endif
publish_pending_ = false;
RadioProfileConfig config = temp_active_ ? temporary_ : saved_;
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
if (auto_secondary_requested_ && canAutoSecondary()) config = auto_secondary_;
else if (secondary_protocol_overlay_ && manualSecondaryConfigured() && !secondaryRuntimeBusy()) {
config.params.protocol = secondary_protocol_;
@@ -297,7 +298,7 @@ void RadioProfileCLI::publish() {
}
#endif
radio_->profiles()->setSecondary(config, temp_active_);
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
owns_secondary_runtime_ = auto_secondary_requested_ || secondary_protocol_overlay_;
if (owns_secondary_runtime_) {
owned_secondary_snapshot_ = config;
@@ -306,7 +307,7 @@ void RadioProfileCLI::publish() {
#endif
}
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
bool RadioProfileCLI::runtimeSecondaryUnchanged() const {
if (!owns_secondary_runtime_ || !radio_ || !radio_->profiles()) return true;
const auto* profiles = radio_->profiles();
@@ -331,7 +332,7 @@ bool RadioProfileCLI::hasSecondarySchedule() const {
}
bool RadioProfileCLI::secondaryRuntimeBusy() const {
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
if (external_secondary_override_ || !runtimeSecondaryUnchanged()) return true;
#endif
return !fs_ || !radio_ || !radio_->profiles() || hold_ || temp_pending_ || temp_active_
@@ -341,14 +342,14 @@ bool RadioProfileCLI::secondaryRuntimeBusy() const {
void RadioProfileCLI::noteSecondaryManualChange() {
++secondary_intent_generation_;
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
auto_secondary_requested_ = secondary_protocol_overlay_ = false;
owns_secondary_runtime_ = external_secondary_override_ = false;
#endif
}
bool RadioProfileCLI::canAutoSecondary() const {
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
if (manual_secondary_ || saved_.mode != RadioProfileMode::Off || secondaryRuntimeBusy()) return false;
const auto& current = radio_->profiles()->secondary;
return current.mode == RadioProfileMode::Off || (auto_secondary_requested_
@@ -359,7 +360,7 @@ bool RadioProfileCLI::canAutoSecondary() const {
}
bool RadioProfileCLI::requestAutoSecondary(const RadioProfileConfig& config) {
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
if (!canAutoSecondary() || config.mode == RadioProfileMode::Off
|| (uint8_t)config.mode > (uint8_t)RadioProfileMode::RxTx
|| !radio_->validateProfile(config.params)) return false;
@@ -379,7 +380,7 @@ bool RadioProfileCLI::requestAutoSecondary(const RadioProfileConfig& config) {
}
void RadioProfileCLI::clearAutoSecondary() {
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
if (!auto_secondary_requested_) return;
protectExternalSecondary();
auto_secondary_requested_ = false;
@@ -389,7 +390,7 @@ void RadioProfileCLI::clearAutoSecondary() {
}
bool RadioProfileCLI::autoSecondaryActive() const {
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
if (!auto_secondary_requested_ || !canAutoSecondary()) return false;
const auto& current = radio_->profiles()->secondary;
return !radio_->profiles()->secondary_temporary && current.mode == auto_secondary_.mode
@@ -400,17 +401,27 @@ bool RadioProfileCLI::autoSecondaryActive() const {
}
bool RadioProfileCLI::useSecondaryProtocol(RadioProfileProtocol protocol) {
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
if (protocol == RadioProfileProtocol::MeshCore) {
clearSecondaryProtocol();
return true;
}
if (protocol != RadioProfileProtocol::Meshtext || !manualSecondaryConfigured()
const bool supported_protocol =
#if MESH_ENABLE_MESHTEXT_CHAT
protocol == RadioProfileProtocol::Meshtext ||
#endif
#if MESH_ENABLE_ETHERNET_TUNNEL
protocol == RadioProfileProtocol::Ethernet ||
#endif
false;
if (!supported_protocol || !manualSecondaryConfigured()
|| secondaryRuntimeBusy()) return false;
// Never silently replace another foreign owner's overlay.
if (secondary_protocol_overlay_ && secondary_protocol_ != protocol) return false;
auto preview = *radio_->profiles();
auto config = saved_;
config.params.protocol = protocol;
config.params.preamble = 16;
if (protocol == RadioProfileProtocol::Meshtext) config.params.preamble = 16;
preview.setSecondary(config, false);
if (!radio_->validateProfile(config.params) || !preview.automaticPreambleFits()) return false;
secondary_protocol_ = protocol;
@@ -424,7 +435,7 @@ bool RadioProfileCLI::useSecondaryProtocol(RadioProfileProtocol protocol) {
}
void RadioProfileCLI::clearSecondaryProtocol() {
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
if (!secondary_protocol_overlay_) return;
protectExternalSecondary();
secondary_protocol_overlay_ = false;
@@ -632,7 +643,8 @@ void RadioProfileCLI::appendChirpWarning(char* reply, size_t capacity, const Rad
const bool over_a = timing.preamble[0] > RadioProfiles::MaxAutomaticPreamble;
const bool over_b = timing.preamble[1] > RadioProfiles::MaxAutomaticPreamble;
if (used < capacity && (over_a || over_b))
snprintf(reply + used, capacity - used, "; WARN need >128: %s",
snprintf(reply + used, capacity - used, "; WARN need >%u: %s",
unsigned(RadioProfiles::MaxAutomaticPreamble),
over_a && over_b ? "radio,radio2" : over_a ? "radio" : "radio2");
used = strlen(reply);
const bool short_a = preview.primary.preamble && preview.primary.preamble < timing.preamble[0];
@@ -679,6 +691,9 @@ void RadioProfileCLI::formatConfig(char* reply, size_t capacity, const RadioProf
}
bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity, bool remote_origin) {
#if defined(MESH_HIL_TX_FREQ_MHZ)
if (handleHilTxFrequencyCommand(command, reply, capacity)) return true;
#endif
if (handleCarrierWaveCommand(radio_, command, reply, capacity)) return true;
const char* text = command;
enum { Get, Set, Delete } verb = Get;
@@ -816,7 +831,7 @@ bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity,
return true;
}
if ((base || temporary) && verb == Get && !*args) {
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
if (base && autoSecondaryActive()) {
formatConfig(reply, capacity, auto_secondary_, false, 0, true);
return true;
@@ -831,7 +846,7 @@ bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity,
temporary, temp_pending_ ? pending_duration_ms_ : temp_remaining_ms_);
return true;
}
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
if (base && verb == Set && !strcmp(args, "auto")) {
// This clears only saved permission, never an active/pending lease or a
// schedule. Remote acknowledgement staging must not weaken that contract.
@@ -991,7 +1006,7 @@ bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity,
noteSecondaryManualChange();
pending_temporary_ = config; pending_duration_ms_ = minutes * 60000UL;
temp_start_ms_ = millis() + 2000; temp_pending_ = true;
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
publish_pending_ = true; publish_after_ms_ = temp_start_ms_;
#endif
}
+2 -1
View File
@@ -32,7 +32,7 @@ class RadioProfileCLI {
// Saved Off can be an explicit veto, rather than an unused secondary slot.
bool manual_secondary_ = false;
uint32_t secondary_intent_generation_ = 0;
#if MESH_ENABLE_MESHTEXT_CHAT
#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL
RadioProfileConfig auto_secondary_;
bool auto_secondary_requested_ = false;
bool secondary_protocol_overlay_ = false;
@@ -110,6 +110,7 @@ class RadioProfileCLI {
void clearAutoSecondary();
bool autoSecondaryActive() const;
bool canAutoSecondary() const;
bool secondaryRuntimeAvailable() const { return !secondaryRuntimeBusy(); }
// Borrow a manually configured RF tuple without persisting its wire protocol
// or the foreign network's fixed preamble. Temporary sessions take priority.
bool useSecondaryProtocol(RadioProfileProtocol protocol);
+148
View File
@@ -0,0 +1,148 @@
#pragma once
#include <Arduino.h>
#include <WiFi.h>
#include <errno.h>
#include <lwip/sockets.h>
#include <helpers/EthernetKiss.h>
namespace mesh { namespace ethernet {
// Opt-in, unauthenticated KISS-over-TCP on a trusted station LAN only. This
// service never joins WiFi, opens an AP, selects an RF profile, or adds bytes
// to the Ethernet frame. The owner must explicitly enable and service RF.
class KissServer {
public:
// Full Companion already uses 5000/5001/5002 for binary, OTA and text.
static constexpr uint16_t Port = 5003;
static constexpr size_t ReadBudget = 128;
static constexpr size_t WriteBudget = 128;
struct Status {
bool enabled, listening, connected;
uint32_t accepted, rejected, disconnects, rxFrames, txFrames;
uint32_t malformed, dropped, listenFailures;
uint8_t pendingTransmit, pendingReceive;
};
private:
WiFiServer _server;
WiFiClient _client;
KissCodec _codec;
uint32_t _address = 0, _lastListenAttempt = 0;
bool _enabled = false, _listening = false, _connected = false;
bool _listenAttempted = false;
uint32_t _accepted = 0, _rejected = 0, _disconnects = 0, _listenFailures = 0;
void disconnect() {
if (_connected) ++_disconnects;
_connected = false;
_client.stop();
_codec.resetPending();
}
void stop() {
disconnect();
_server.end();
_listening = _listenAttempted = false;
_address = 0;
}
public:
KissServer() : _server(Port, 2) {}
// Closing the stream AND pending accepts discards unread SDK/socket bytes.
// Merely clearing the decoder would let pre-change work survive in a socket.
// The next enabled poll immediately rebinds to the same station address.
void resetPending() {
disconnect();
_server.end();
_listening = _listenAttempted = false;
}
void loop(bool enabled) {
_enabled = enabled;
const bool station = (WiFi.getMode() & WIFI_STA)
&& WiFi.status() == WL_CONNECTED;
const uint32_t address = station ? static_cast<uint32_t>(WiFi.localIP()) : 0;
if (!enabled || !address) {
if (_address || _listening || _connected) stop();
return;
}
if (_address != address) {
stop();
_address = address;
// Binding the station address prevents this unauthenticated service from
// appearing on a simultaneously enabled setup AP.
_server = WiFiServer(IPAddress(address), Port, 2);
}
const uint32_t now = static_cast<uint32_t>(millis());
if (_listening && !static_cast<bool>(_server)) {
_server.end();
_listening = _listenAttempted = false;
}
if (!_listening && (!_listenAttempted
|| static_cast<uint32_t>(now - _lastListenAttempt) >= 1000U)) {
_lastListenAttempt = now;
_listenAttempted = true;
_server.begin();
_listening = static_cast<bool>(_server);
if (!_listening) { ++_listenFailures; _server.end(); }
}
if (_connected && !_client.connected()) disconnect();
if (_listening) {
// Accept at most one queued connection per poll. An idle valid owner is
// never displaced by another host or by that host reconnecting early.
WiFiClient incoming = _server.available();
if (incoming) {
if (_connected) { incoming.stop(); ++_rejected; }
else {
_codec.resetPending();
_client = incoming;
_client.setNoDelay(true);
_connected = true;
++_accepted;
}
}
}
if (!_connected) return;
// WiFiClient::write may retry blocking select calls for seconds. One
// MSG_DONTWAIT send, with a fixed byte budget, leaves LoRa scanning runnable.
const uint8_t* bytes;
size_t length;
if (_codec.peekOutput(bytes, length)) {
if (length > WriteBudget) length = WriteBudget;
const int written = ::send(_client.fd(), bytes, length, MSG_DONTWAIT);
if (written > 0) _codec.consumeOutput(static_cast<size_t>(written));
else if (written < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
disconnect();
return;
}
}
for (size_t consumed = 0; consumed < ReadBudget && _codec.canAcceptByte(); ++consumed) {
uint8_t byte;
const int received = ::recv(_client.fd(), &byte, 1, MSG_DONTWAIT);
if (received == 1) _codec.feed(byte);
else {
if (received == 0 || (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR))
disconnect();
break;
}
}
}
bool peekTransmit(const uint8_t*& bytes, size_t& length) const {
return _codec.peekTransmit(bytes, length);
}
void consumeTransmit() { _codec.consumeTransmit(); }
bool queueReceive(const uint8_t* bytes, size_t length) {
return _connected && _codec.queueReceive(bytes, length);
}
Status status() const {
return {_enabled, _listening, _connected, _accepted, _rejected, _disconnects,
_codec.receivedFrames(), _codec.sentFrames(), _codec.malformedFrames(),
_codec.droppedFrames(), _listenFailures,
_codec.pendingTransmit(), _codec.pendingReceive()};
}
};
} } // namespace mesh::ethernet
+4 -1
View File
@@ -113,6 +113,7 @@ static const char* fetch_error_word(OtaManager::FetchError error) {
case OtaManager::FETCH_ERROR_INTEGRITY: return "integrity check";
case OtaManager::FETCH_ERROR_MANIFEST_TIMEOUT: return "manifest timeout";
case OtaManager::FETCH_ERROR_LEAVES_TIMEOUT: return "leaves timeout";
case OtaManager::FETCH_ERROR_RADIO_SESSION: return "radio session changed";
default: return "none";
}
}
@@ -178,7 +179,9 @@ static __attribute__((noinline)) bool handle_status(char* reply, OtaContext& c)
else
snprintf(dl, sizeof dl, "%sdownload: %s %u/%u (%u%%) id=%s %us",
c.manager.fetched_is_bootloader() ? "bootloader " : "",
state_word(fs), have, tot, pct, midhx, age);
fs == OtaManager::FETCHING && c.manager.directFetchActive() ?
(c.manager.directFetchConfirmed() ? "direct240" : "direct240 probe") : state_word(fs),
have, tot, pct, midhx, age);
}
const char* hw = (c.hw_id[0]) ? c.hw_id : "?";
#if OTA_TARGET_NAME_TABLE && OTA_TARGET_NAME_FRONT_CODED
+21
View File
@@ -0,0 +1,21 @@
#pragma once
// One bounded raw-radio slot, shared with the existing KISS/foreign scheduler.
// Normal Packet storage, routed OTA and non-OTA builds remain unchanged.
#ifndef MESH_ENABLE_OTA_KISS_DIRECT
#if defined(ENABLE_OTA) && !(defined(MESH_PRIMARY_ESPNOW) && MESH_PRIMARY_ESPNOW) \
&& !(defined(MESH_ENABLE_FOREIGN_RADIO) && !MESH_ENABLE_FOREIGN_RADIO)
#define MESH_ENABLE_OTA_KISS_DIRECT 1
#else
#define MESH_ENABLE_OTA_KISS_DIRECT 0
#endif
#endif
#if MESH_ENABLE_OTA_KISS_DIRECT != 0 && MESH_ENABLE_OTA_KISS_DIRECT != 1
#error "MESH_ENABLE_OTA_KISS_DIRECT must be 0 or 1"
#endif
#if MESH_ENABLE_OTA_KISS_DIRECT && !defined(ENABLE_OTA)
#error "direct KISS OTA requires ENABLE_OTA"
#endif
#if MESH_ENABLE_OTA_KISS_DIRECT && defined(MESH_ENABLE_FOREIGN_RADIO) && !MESH_ENABLE_FOREIGN_RADIO
#error "direct KISS OTA requires the shared raw-radio scheduler"
#endif
+51
View File
@@ -0,0 +1,51 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include "OtaFormat.h"
namespace mesh { namespace ota {
// KISS DATA carries these radio bytes unchanged. KISS escaping stays on the
// host cable, never on RF. The reserved MeshCore version makes old endpoints
// reject the frame before interpreting any OTA bytes; it is always zero-hop.
// This bypasses Packet's routed 184-byte payload, without enlarging its pool.
static constexpr uint8_t OTA_DIRECT_HEADER = 0xF2; // v4, OTA, DIRECT
static constexpr uint16_t OTA_DIRECT_RF_MAX = 255;
static constexpr uint16_t OTA_DIRECT_HEADER_BYTES = 2;
static constexpr uint16_t OTA_DIRECT_MESSAGE_MAX =
OTA_DIRECT_RF_MAX - OTA_DIRECT_HEADER_BYTES;
static constexpr uint16_t OTA_DIRECT_FRAG_DATA =
OTA_DIRECT_MESSAGE_MAX - 9 - 4; // OTA_DATA framing + v2 stream identity
inline bool ota_direct_wire_marker(const uint8_t* bytes, size_t length) {
return bytes && length && bytes[0] == OTA_DIRECT_HEADER;
}
inline bool ota_direct_wire_decode(const uint8_t* bytes, size_t length,
const uint8_t*& message, uint16_t& message_len) {
message = nullptr;
message_len = 0;
if (!ota_direct_wire_marker(bytes, length) || length < 3
|| length > OTA_DIRECT_RF_MAX || bytes[1] != 0
|| !ota_is_transfer_message(bytes[2])) return false;
message = bytes + OTA_DIRECT_HEADER_BYTES;
message_len = static_cast<uint16_t>(length - OTA_DIRECT_HEADER_BYTES);
return true;
}
inline uint16_t ota_direct_wire_encode(uint8_t* output, size_t capacity,
const uint8_t* message, uint16_t length) {
if (!output || !message || !length || length > OTA_DIRECT_MESSAGE_MAX
|| capacity < size_t(length) + OTA_DIRECT_HEADER_BYTES
|| !ota_is_transfer_message(message[0])) return 0;
output[0] = OTA_DIRECT_HEADER;
output[1] = 0; // no path, transport codes, forwarding or Ethernet overhead
memcpy(output + OTA_DIRECT_HEADER_BYTES, message, length);
return static_cast<uint16_t>(length + OTA_DIRECT_HEADER_BYTES);
}
static_assert(OTA_DIRECT_FRAG_DATA == 240, "direct KISS OTA payload budget");
} }
+142 -34
View File
@@ -10,6 +10,21 @@
namespace mesh {
namespace ota {
namespace {
// Construction and transfer state belong to the single mesh-loop owner. This
// process token outlives heap/shared context recreation, without another queue.
uint32_t direct_epoch = 0;
}
OtaManager::OtaManager() {
invalidateDirectTransport();
}
void OtaManager::invalidateDirectTransport() {
direct_epoch = ota_advance_direct_epoch(direct_epoch);
_direct_transport_epoch = direct_epoch;
}
OtaManager::~OtaManager() {
free(_catalog_heap);
free(_leaves_buf);
@@ -17,6 +32,12 @@ OtaManager::~OtaManager() {
free(_scratch);
}
void OtaManager::set_direct_transport_enabled(bool on) {
if (_direct_transport_enabled != on) invalidateDirectTransport();
_direct_transport_enabled = on;
if (!on && _direct_session) downgradeDirectTransport();
}
bool OtaManager::set_speed(float speed) {
if (!validSpeed(speed)) return false;
if (_speed == speed) return true;
@@ -124,6 +145,7 @@ void OtaManager::begin(uint32_t my_target_id, OtaSend send, void* ctx) {
_fstate = IDLE; _have = 0; _fbc = 0;
_paused_from = IDLE;
_fetch_error = FETCH_ERROR_NONE;
_direct_session = false; _direct_confirmed = false; _fetch_route = {};
_archive_fetch = false; _validate = false;
clearFetchIntent();
_resume_verify_idx = 0; _resume_invalidated = false;
@@ -598,6 +620,7 @@ uint32_t OtaManager::proofEgressGapMs() const {
}
void OtaManager::clearPendingEgress() {
invalidateDirectTransport();
_n_manifest_jobs = 0;
_n_serve_jobs = 0;
_serve_block_len = 0;
@@ -713,13 +736,8 @@ bool OtaManager::loadActiveServeBlock() {
if (bs == 0 || bs > OTA_MAX_BLOCK) return false;
uint32_t off = (uint32_t)job.block * bs;
uint32_t blen = (off + bs <= v->m.payload_size) ? bs : (v->m.payload_size - off);
if (v->read) {
if (!v->read(v->read_ctx, off, _serve_block, blen)) return false;
} else {
memcpy(_serve_block, v->m.payload + off, blen);
}
_serve_block_len = (uint16_t)blen;
_serve_wire_block = _serve_block;
_serve_wire_block = nullptr;
_serve_wire_len = _serve_block_len;
_serve_wire_deflated = false;
@@ -731,22 +749,40 @@ bool OtaManager::loadActiveServeBlock() {
v->scratch_sz = v->scratch ? OTA_MAX_BLOCK : 0;
}
_source_buffer_used_at = _now_ms;
if (job.wire_v2 && job.allow_deflate && v->scratch && v->scratch_sz >= blen) {
// A host-precompressed representation is enough to serve DATA: proofs use
// authenticated leaves. Do not pull the same raw block over BLE/USB first.
if (job.wire_v2 && job.allow_deflate && v->read_deflated &&
v->scratch && v->scratch_sz >= blen) {
uint16_t encoded_len = 0;
bool encoded = false;
if (v->read_deflated) {
encoded = v->read_deflated(v->deflate_ctx, job.block, v->scratch,
(uint16_t)blen, &encoded_len);
} else if (_deflate_encode) {
encoded = _deflate_encode(_deflate_encode_ctx, _serve_block, (uint16_t)blen,
v->scratch, (uint16_t)blen, &encoded_len);
}
const bool encoded = v->read_deflated(v->deflate_ctx, job.block, v->scratch,
(uint16_t)blen, &encoded_len);
if (encoded && encoded_len > 0 && encoded_len < blen) {
_serve_wire_block = v->scratch;
_serve_wire_len = encoded_len;
_serve_wire_deflated = true;
}
}
if (!_serve_wire_block) {
if (v->read) {
if (!v->read(v->read_ctx, off, _serve_block, blen)) return false;
} else {
memcpy(_serve_block, v->m.payload + off, blen);
}
_serve_wire_block = _serve_block;
// Device encoders need raw input; host codec failures retain the existing
// raw fallback instead of allocating another encoder workspace.
if (job.wire_v2 && job.allow_deflate && !v->read_deflated && _deflate_encode &&
v->scratch && v->scratch_sz >= blen) {
uint16_t encoded_len = 0;
if (_deflate_encode(_deflate_encode_ctx, _serve_block, (uint16_t)blen,
v->scratch, (uint16_t)blen, &encoded_len) &&
encoded_len > 0 && encoded_len < blen) {
_serve_wire_block = v->scratch;
_serve_wire_len = encoded_len;
_serve_wire_deflated = true;
}
}
}
mh4(_serve_wire_id, _serve_wire_block, _serve_wire_len);
_serve_block_loaded = true;
return true;
@@ -805,15 +841,16 @@ bool OtaManager::handleReq(const uint8_t* m, uint16_t n) {
const uint32_t off = idx * block_size;
if (off + blen > v->m.payload_size) blen = v->m.payload_size - off;
const bool wire_v2 = ota_req_is_v2(rq.items[i].want_mask);
if (_request_route.direct && !wire_v2) continue;
const bool allow_deflate = wire_v2 &&
(rq.items[i].want_mask & OTA_REQ_V2_ALLOW_DEFLATE) != 0;
const bool extended_length = wire_v2 &&
ota_req_v2_extended_length(rq.items[i].want_mask);
const bool block_requires_extended = v->m.block_size() > OTA_DATA_V2_LEGACY_MAX_ENCODED;
if (wire_v2 && extended_length != block_requires_extended) continue;
const uint16_t valid_mask = frag_full_mask((blen +
(wire_v2 ? OTA_FRAG_DATA_V2 : OTA_FRAG_DATA) - 1) /
(wire_v2 ? OTA_FRAG_DATA_V2 : OTA_FRAG_DATA));
const uint16_t fragment_data = _request_route.direct ? OTA_DIRECT_FRAG_DATA :
(wire_v2 ? OTA_FRAG_DATA_V2 : OTA_FRAG_DATA);
const uint16_t valid_mask = frag_full_mask((blen + fragment_data - 1) / fragment_data);
const uint16_t requested = wire_v2
? ota_req_v2_fragments(rq.items[i].want_mask) : rq.items[i].want_mask;
const uint16_t want = (uint16_t)(requested & valid_mask);
@@ -835,6 +872,10 @@ bool OtaManager::handleReqProof(const uint8_t* m, uint16_t n) {
}
void OtaManager::serviceEgress(OtaReplyRouteValid route_valid, void* route_ctx) {
if (_fstate == FETCHING && _fetch_route.profile < 2 && route_valid &&
!route_valid(route_ctx, _fetch_route)) {
failFetch(FETCH_ERROR_RADIO_SESSION);
}
// Metadata comes first so an older receiver gets every manifest fragment before its retry horizon. The
// send callback supplies radio-queue backpressure, and a rejected fragment remains in this descriptor.
if (serviceManifestEgress(route_valid, route_ctx)) return;
@@ -871,12 +912,13 @@ void OtaManager::serviceEgress(OtaReplyRouteValid route_valid, void* route_ctx)
popServeJob();
return;
}
const uint16_t fragment_data = job.wire_v2 ? OTA_FRAG_DATA_V2 : OTA_FRAG_DATA;
const uint16_t fragment_data = job.route.direct ? OTA_DIRECT_FRAG_DATA :
(job.wire_v2 ? OTA_FRAG_DATA_V2 : OTA_FRAG_DATA);
const uint16_t valid_mask = frag_full_mask(
(_serve_wire_len + fragment_data - 1u) / fragment_data);
job.pending_mask &= valid_mask;
if (job.pending_mask == 0) {
job.proof_ready_at = armedDeadline(_now_ms, proofEgressGapMs());
job.proof_ready_at = job.route.direct ? 0 : armedDeadline(_now_ms, proofEgressGapMs());
return;
}
uint8_t fragment = 0;
@@ -891,7 +933,7 @@ void OtaManager::serviceEgress(OtaReplyRouteValid route_valid, void* route_ctx)
DataMsg dm;
memcpy(dm.manifest_id, job.mid, 4);
dm.block_idx = job.block;
uint8_t v2_data[OTA_DATA_V2_STREAM_ID_BYTES + OTA_FRAG_DATA_V2];
uint8_t v2_data[OTA_DATA_V2_STREAM_ID_BYTES + OTA_DIRECT_FRAG_DATA];
if (job.wire_v2) {
const bool packed = job.extended_length
? ota_data_v2_pack_extended(fragment, _serve_wire_len, dm.frag_off)
@@ -909,7 +951,7 @@ void OtaManager::serviceEgress(OtaReplyRouteValid route_valid, void* route_ctx)
dm.data = _serve_block + frag_off;
dm.data_len = (uint16_t)frag_len;
}
uint8_t b[MAX_PACKET_PAYLOAD];
uint8_t b[OTA_DIRECT_MESSAGE_MAX];
if (emit(b, encode_data(b, sizeof(b), dm), false, &job.route)) {
const uint16_t bit = (uint16_t)(1u << fragment);
job.pending_mask &= (uint16_t)~bit;
@@ -919,7 +961,7 @@ void OtaManager::serviceEgress(OtaReplyRouteValid route_valid, void* route_ctx)
// proactive proof into the radio queue at the same instant: the two half-duplex transmissions would
// collide and force the receiver onto its multi-second retry tick. Include every response that the
// adapter can already have admitted ahead of this proof, then retain a bounded fast-link floor.
job.proof_ready_at = armedDeadline(_now_ms, proofEgressGapMs());
job.proof_ready_at = job.route.direct ? 0 : armedDeadline(_now_ms, proofEgressGapMs());
}
}
return;
@@ -1274,6 +1316,7 @@ bool OtaManager::anyWireDataReceived() const {
void OtaManager::downgradeWireToLegacy() {
if (!_wire_v2_session) return;
if (_direct_session) downgradeDirectTransport();
_wire_v2_session = false;
_wire_v2_confirmed = false;
_wire_allow_deflate = false;
@@ -1294,6 +1337,26 @@ void OtaManager::downgradeWireToLegacy() {
OTA_DBG("OTA: source uses legacy 160-byte DATA geometry\n");
}
void OtaManager::downgradeDirectTransport() {
if (!_direct_session) return;
invalidateDirectTransport();
_direct_session = false;
_direct_confirmed = false;
_fetch_route.direct = false; // keep the original physical session binding
_wire_v2_confirmed = false;
_wire_empty_stalls = 0;
for (uint8_t i = 0; i < OTA_FETCH_PIPELINE; ++i) {
const uint32_t block = _reasm[i].block;
clearReassemblySlot(i);
if (block == NO_BLOCK) continue;
_reasm[i].block = block;
const uint16_t fragment_data = fetchFragmentData();
_reasm[i].need = frag_full_mask((blockLen(block) + fragment_data - 1u) / fragment_data);
}
_flight_dirty = true;
OTA_DBG("OTA: direct source unavailable; retain blocks and use routed DATA geometry\n");
}
int OtaManager::findReassemblySlot(uint32_t block) const {
for (uint8_t slot = 0; slot < OTA_FETCH_PIPELINE; slot++) {
if (_reasm[slot].block == block) return slot;
@@ -1345,7 +1408,7 @@ uint32_t OtaManager::fetchRetryTimeoutMs() const {
: (uint32_t)count_mask_bits((uint16_t)(slot.need & ~slot.mask)) + 1u;
}
if (active == 0) {
const uint32_t fragment_data = _wire_v2_session ? OTA_FRAG_DATA_V2 : OTA_FRAG_DATA;
const uint32_t fragment_data = fetchFragmentData();
const uint32_t fragments = (_fbs + fragment_data - 1) / fragment_data;
packets += (fragments + 1) * _pipeline_width;
}
@@ -1429,6 +1492,7 @@ void OtaManager::clearFetchIntent() {
}
void OtaManager::failFetch(FetchError error) {
invalidateDirectTransport();
if (error == FETCH_ERROR_STORAGE && _fetch && _fetch->canReconnect()
&& pauseFetchForDisconnect()) return;
if (!_have_desired_mid && _desired_target == 0 && !_archive_fetch) {
@@ -1451,6 +1515,7 @@ void OtaManager::failFetch(FetchError error) {
}
void OtaManager::completeFetch() {
invalidateDirectTransport();
_auto_failure_delay = 0;
_fetch_error = FETCH_ERROR_NONE;
_fstate = COMPLETE;
@@ -1501,6 +1566,7 @@ OtaManager::PullResult OtaManager::startFetch(const uint8_t* mid, uint32_t targe
_wire_v2_confirmed = false;
_wire_allow_deflate = _wire_v2_session && _deflate_decode != nullptr;
_wire_empty_stalls = 0;
_direct_session = false; _direct_confirmed = false; _fetch_route = {};
_fexpected_target = target;
_validate = validate; // motatool folder-capture warm-start (seed leaf-diff)
// A validate pull is a FRESH seed capture, not a resume: the store already holds the seed's payload (not a
@@ -1526,6 +1592,7 @@ bool OtaManager::resumeStagedExplicit(const uint8_t* want_mid, uint32_t expected
_wire_v2_confirmed = false;
_wire_allow_deflate = _wire_v2_session && _deflate_decode != nullptr;
_wire_empty_stalls = 0;
_direct_session = false; _direct_confirmed = false; _fetch_route = {};
_validate = false;
_archive_fetch = false;
_desired_target = expected_target;
@@ -1539,6 +1606,7 @@ bool OtaManager::resumeStagedExplicit(const uint8_t* want_mid, uint32_t expected
bool OtaManager::pauseFetchForDisconnect() {
if (!fetchActive()) return false;
invalidateDirectTransport();
if (_fstate != PAUSED) _paused_from = _fstate;
_fetch_error = FETCH_ERROR_STORAGE;
_fstate = PAUSED;
@@ -1673,6 +1741,17 @@ void OtaManager::handleManifest(const uint8_t* m, uint16_t n) {
_fpoff = payload_off; _floff = leaves_off; _fpsize = payload_size; _fbc = bc; _fbs = bs;
_ftotal = total; _have = 0;
clearReassembly(); // fresh transfer: drop any prior per-block state
// The successful legacy manifest exchange proves a local source exists on
// this exact radio session. A new zero-hop request probes its direct codec;
// old sources drop the reserved wire version and receive a normal retry.
_direct_session = _direct_transport_enabled && _wire_v2_session &&
_max_hops == 0 && _observed_path_transmissions == 1 &&
_request_route.profile < 2 && !_request_route.direct;
_direct_confirmed = false;
if (_direct_session) {
_fetch_route = _request_route;
_fetch_route.direct = true;
}
// Warm-start (folder-capture): if requested and the image is small enough for the fixed leaves bitmap,
// bulk-fetch the target leaves and diff the seed already staged in the store; else just transfer normally.
if (_validate && beginLeafDiff()) {
@@ -1824,6 +1903,7 @@ bool OtaManager::resumeStagedFor(const uint8_t* want_mid, bool automatic_resume)
_wire_v2_confirmed = false;
_wire_allow_deflate = _wire_v2_session && _deflate_decode != nullptr;
_wire_empty_stalls = 0;
_direct_session = false; _direct_confirmed = false; _fetch_route = {};
memcpy(_fid, m.merkle_root, 4);
memcpy(_froot, m.merkle_root, 4);
_fflags = m.flags;
@@ -1945,6 +2025,11 @@ bool OtaManager::handleData(const uint8_t* m, uint16_t n) {
DataMsg dm;
if (!decode_data(m, n, dm) || !_fetch) return false;
if (_fstate != FETCHING || memcmp(dm.manifest_id, _fid, 4) != 0) return false;
if (_request_route.direct && (!_direct_session ||
!(_request_route == _fetch_route))) return false;
if (!_request_route.direct && _direct_session &&
(_direct_confirmed || _request_route.profile != _fetch_route.profile ||
_request_route.generation != _fetch_route.generation)) return false;
if (dm.block_idx >= _fbc) return false;
bool present;
if (!readBlockPresent(dm.block_idx, present)) {
@@ -1958,6 +2043,7 @@ bool OtaManager::handleData(const uint8_t* m, uint16_t n) {
uint32_t blen = blockLen(dm.block_idx);
if ((dm.frag_off & OTA_DATA_V2_MARK) == 0) {
if (_request_route.direct) return false; // direct wire is explicitly v2-only
if (dm.frag_off % OTA_FRAG_DATA != 0) return false; // canonical legacy-aligned slices only
if ((uint32_t)dm.frag_off + dm.data_len > blen) return false;
uint32_t expected_len = blen - dm.frag_off;
@@ -1965,6 +2051,7 @@ bool OtaManager::handleData(const uint8_t* m, uint16_t n) {
if (dm.data_len != expected_len) return false; // do not mark a short slice as complete
uint32_t kf = dm.frag_off / OTA_FRAG_DATA;
if (kf >= 16) return false;
if (_direct_session) downgradeDirectTransport(); // canonical old response, no geometry mixing
// A deployed source ignores the v2 request bits, masks them against its seven-fragment geometry, and
// responds here. Only a fully canonical legacy slice may select that profile; malformed matching-MID
// traffic must not force a session-wide downgrade. Never mix it with already accepted v2 bytes.
@@ -1989,11 +2076,13 @@ bool OtaManager::handleData(const uint8_t* m, uint16_t n) {
if (!unpacked) return false;
if (encoded_len > blen || (deflated ? encoded_len >= blen : encoded_len != blen)) return false;
const uint16_t fragment_len = (uint16_t)(dm.data_len - OTA_DATA_V2_STREAM_ID_BYTES);
const uint32_t fragment_off = (uint32_t)fragment * OTA_FRAG_DATA_V2;
const uint16_t fragment_data = _request_route.direct ? OTA_DIRECT_FRAG_DATA : OTA_FRAG_DATA_V2;
const uint32_t fragment_off = (uint32_t)fragment * fragment_data;
if (fragment_off >= encoded_len || fragment_off + fragment_len > encoded_len) return false;
uint32_t expected_len = encoded_len - fragment_off;
if (expected_len > OTA_FRAG_DATA_V2) expected_len = OTA_FRAG_DATA_V2;
if (expected_len > fragment_data) expected_len = fragment_data;
if (fragment_len != expected_len) return false;
if (_direct_session && !_request_route.direct) downgradeDirectTransport();
_wire_v2_confirmed = true;
const uint8_t* stream_id = dm.data;
@@ -2003,7 +2092,7 @@ bool OtaManager::handleData(const uint8_t* m, uint16_t n) {
slot.deflated = deflated;
memcpy(slot.stream_id, stream_id, sizeof(slot.stream_id));
slot.mask = 0;
slot.need = frag_full_mask((encoded_len + OTA_FRAG_DATA_V2 - 1) / OTA_FRAG_DATA_V2);
slot.need = frag_full_mask((encoded_len + fragment_data - 1) / fragment_data);
} else if (!slot.wire_v2 || slot.encoded_len != encoded_len || slot.deflated != deflated ||
memcmp(slot.stream_id, stream_id, sizeof(slot.stream_id)) != 0) {
return false; // another seeder's representation; never mix
@@ -2011,6 +2100,7 @@ bool OtaManager::handleData(const uint8_t* m, uint16_t n) {
_wire_empty_stalls = 0; // a valid v2 source is still serving this flight
const uint16_t bit = (uint16_t)(1u << fragment);
if (!(slot.need & bit)) return false;
if (_request_route.direct) _direct_confirmed = true;
if (slot.mask & bit) return true;
memcpy(slot.buf + fragment_off, dm.data + OTA_DATA_V2_STREAM_ID_BYTES, fragment_len);
slot.mask |= bit;
@@ -2044,7 +2134,8 @@ bool OtaManager::handleData(const uint8_t* m, uint16_t n) {
if (!decoded || decoded_len != blen) {
_wire_allow_deflate = false; // retry this/future blocks as raw v2
slot.mask = 0;
slot.need = frag_full_mask((blen + OTA_FRAG_DATA_V2 - 1) / OTA_FRAG_DATA_V2);
const uint16_t fragment_data = fetchFragmentData();
slot.need = frag_full_mask((blen + fragment_data - 1) / fragment_data);
slot.encoded_len = 0;
slot.wire_v2 = false;
slot.deflated = false;
@@ -2067,6 +2158,8 @@ bool OtaManager::handleProof(const uint8_t* m, uint16_t n) {
ProofMsg pm;
if (!decode_proof(m, n, pm) || !_fetch) return false;
if (_fstate != FETCHING || memcmp(pm.manifest_id, _fid, 4) != 0) return false;
if (_request_route.direct != _direct_session ||
(_request_route.direct && !(_request_route == _fetch_route))) return false;
if (pm.block_idx >= _fbc) return false;
int slot_index = findReassemblySlot(pm.block_idx);
if (slot_index < 0 || !_reasm[slot_index].awaiting_proof) {
@@ -2146,7 +2239,7 @@ bool OtaManager::requestSlot(uint8_t slot_index) {
if (slot.awaiting_proof) {
ReqProofMsg rp; memcpy(rp.manifest_id, _fid, 4); rp.block_idx = (uint16_t)slot.block;
uint8_t b[16];
bool sent = emit(b, encode_req_proof(b, sizeof(b), rp), false);
bool sent = emit(b, encode_req_proof(b, sizeof(b), rp), false, fetchReplyRoute());
if (sent) {
slot.proof_request_at = 0;
noteFetchActivity();
@@ -2162,7 +2255,7 @@ bool OtaManager::requestSlot(uint8_t slot_index) {
OTA_DBG("OTA: REQ block=%u want=%04x (have=%u/%u mask=%04x window=%u)\n",
(unsigned)slot.block, (unsigned)want, (unsigned)_have, (unsigned)_fbc,
(unsigned)slot.mask, (unsigned)_req_count);
bool sent = emit(b, encode_req(b, sizeof(b), rq), false);
bool sent = emit(b, encode_req(b, sizeof(b), rq), false, fetchReplyRoute());
if (sent) noteFetchActivity();
return sent;
}
@@ -2185,7 +2278,7 @@ bool OtaManager::requestFlight() {
OTA_DBG("OTA: REQ flight first=%u blocks=%u width=%u/%u\n",
(unsigned)_req_start, (unsigned)_req_count,
(unsigned)_pipeline_width, (unsigned)OTA_FETCH_PIPELINE);
bool sent = emit(b, encode_req_window(b, sizeof(b), request), false);
bool sent = emit(b, encode_req_window(b, sizeof(b), request), false, fetchReplyRoute());
_flight_request_pending = !sent;
if (sent) noteFetchActivity();
return sent;
@@ -2203,7 +2296,7 @@ bool OtaManager::fillPipeline() {
ReassemblySlot& slot = _reasm[slot_index];
slot.block = block;
slot.mask = 0;
const uint16_t fragment_data = _wire_v2_session ? OTA_FRAG_DATA_V2 : OTA_FRAG_DATA;
const uint16_t fragment_data = fetchFragmentData();
slot.need = frag_full_mask((blockLen(block) + fragment_data - 1) / fragment_data);
slot.awaiting_proof = false;
slot.proof_request_at = 0;
@@ -2222,6 +2315,18 @@ void OtaManager::requestMissing() {
// Keep the original flight and retry it before evaluating network loss.
if (_flight_request_pending) { requestFlight(); return; }
// An unanswered first probe must still reach old sources promptly. Once
// direct DATA has proved support, one lost request/burst is not evidence of
// a legacy source: use the sparse retry below before changing geometry. Its
// existing empty-flight counter advances only after local admission, and
// valid DATA resets it, so backpressure never consumes this one retry.
if (_direct_session && !anyWireDataReceived() &&
(!_direct_confirmed || _wire_empty_stalls >= 1)) {
downgradeDirectTransport();
requestFlight();
return;
}
// No v2 DATA at all means the request may have reached only deployed sources which ignored its profile
// bits (or the first response burst was lost). Retry once in the universal legacy profile instead of
// pinning the session to a feature it has not observed on air.
@@ -2255,7 +2360,7 @@ void OtaManager::requestMissing() {
const uint32_t block = reassembly.block;
clearReassemblySlot(slot);
reassembly.block = block;
const uint16_t fragment_data = _wire_v2_session ? OTA_FRAG_DATA_V2 : OTA_FRAG_DATA;
const uint16_t fragment_data = fetchFragmentData();
reassembly.need = frag_full_mask((blockLen(block) + fragment_data - 1u) / fragment_data);
}
const bool partial_v2 = _wire_v2_session && reassembly.wire_v2 && reassembly.mask != 0 &&
@@ -2264,7 +2369,8 @@ void OtaManager::requestMissing() {
// A v2 seeder may disappear after establishing a representation while only deployed legacy seeders
// remain. Keep one sparse retry, then fall back the whole flight to the universal profile. Clearing
// every slot prevents geometry/representation mixing and guarantees that old sources can take over.
downgradeWireToLegacy();
if (_direct_session) downgradeDirectTransport();
else downgradeWireToLegacy();
}
if (requestSlot(slot)) {
// Advance fallback evidence only when the sparse retry enters the
@@ -2376,6 +2482,8 @@ void OtaManager::loop() {
// ---------------- dispatch ----------------
bool OtaManager::on_message(const uint8_t* msg, uint16_t len, OtaReplyRoute route) {
if (route.direct && (!_direct_transport_enabled || route.profile >= 2 ||
len > OTA_DIRECT_MESSAGE_MAX)) return false;
const OtaReplyRoute previous = _request_route;
_request_route = route;
const bool consumed = dispatchMessage(msg, len);
+38 -4
View File
@@ -6,6 +6,7 @@
#include "OtaMemoryPolicy.h"
#include "OtaTiming.h"
#include "OtaProtocol.h"
#include "OtaDirectWire.h"
#include "OtaByteIO.h"
#include "OtaStore.h"
#include "MotaContainer.h"
@@ -35,12 +36,18 @@ typedef bool (*OtaSend)(void* ctx, const uint8_t* msg, uint16_t len, bool flood)
struct OtaReplyRoute {
uint32_t generation = 0;
uint8_t profile = 0xFF; // no radio affinity (portable callers)
bool direct = false; // negotiated zero-hop raw/KISS wire, not routed Packet data
bool operator==(const OtaReplyRoute& other) const {
return profile == other.profile && generation == other.generation;
return profile == other.profile && generation == other.generation && direct == other.direct;
}
};
static_assert(sizeof(OtaReplyRoute) == 8, "Direct OTA must use existing route padding");
typedef bool (*OtaReplyRouteValid)(void* ctx, const OtaReplyRoute& route);
inline constexpr uint32_t ota_advance_direct_epoch(uint32_t previous) {
return previous == UINT32_MAX ? 1u : previous + 1u;
}
// Device admission is separate from portable block transport. Signed-only
// automatic fetches must authenticate the manifest before touching staging.
typedef bool (*OtaManifestAdmit)(void* ctx, const MotaManifest& manifest);
@@ -260,7 +267,7 @@ static_assert(OTA_AUTOFETCH_FAILURE_BACKOFF_MS > 0u &&
class OtaManager {
public:
OtaManager() = default;
OtaManager();
~OtaManager();
OtaManager(const OtaManager&) = delete;
OtaManager& operator=(const OtaManager&) = delete;
@@ -292,7 +299,8 @@ public:
FETCH_ERROR_STORAGE,
FETCH_ERROR_INTEGRITY,
FETCH_ERROR_MANIFEST_TIMEOUT,
FETCH_ERROR_LEAVES_TIMEOUT
FETCH_ERROR_LEAVES_TIMEOUT,
FETCH_ERROR_RADIO_SESSION
};
// Sentinel for "no block" in the reassembly / peer-REQ / recently-served slots (a real block index is
@@ -385,6 +393,13 @@ public:
// Defaults on for moving-forward 171-byte transfers. This switch exists for qualification and emergency
// rollback; disabling it produces byte-for-byte legacy OTA_REQ/OTA_DATA behavior.
void set_wire_v2_enabled(bool on) { _wire_v2_enabled = on; }
// Explicit transport capability, never inferred from block size or a sender.
// A fetch probes only after a validated zero-hop manifest at max_hops=0.
void set_direct_transport_enabled(bool on);
bool directFetchActive() const { return _direct_session; }
bool directFetchConfirmed() const { return _direct_session && _direct_confirmed; }
OtaReplyRoute directFetchRoute() const { return _fetch_route; }
uint32_t directTransportEpoch() const { return _direct_transport_epoch; }
// Resume a fetch from a container already persisted in the store (after a reboot). want_mid=nullptr is
// automatic adoption and rechecks current autofetch/target/version policy; a non-null MID is an explicit
@@ -523,7 +538,10 @@ public:
// Max OTA flood reach in HOPS (runtime-tunable, persisted): a node accepts OTA from up to N hops away and
// relays packets still under N hops; 0 = direct only (accept path_count 0, never relay). Bounds duty-cycle
// when crossing repeaters. Default OTA_HOP_LIMIT_DEFAULT. Set via `ota config hops`.
void set_max_hops(uint8_t h) { _max_hops = h; }
void set_max_hops(uint8_t h) {
_max_hops = h;
if (h != 0 && _direct_session) downgradeDirectTransport();
}
uint8_t max_hops() const { return _max_hops; }
bool fetched_is_signed() const { return (_fflags & MFLAG_SIGNED) != 0; } // flags of the fetched manifest
bool fetched_is_bootloader() const { return (_fflags & MFLAG_BOOTLOADER) != 0; }
@@ -549,6 +567,7 @@ public:
// Drop the current fetch session back to IDLE so a fresh `ota pull` / advert starts a new one.
void reset_session() {
invalidateDirectTransport();
_fstate = IDLE; _have = 0; _fbc = 0; _ftotal = 0; _fflags = 0;
_paused_from = IDLE;
_req_count = 0; _mf_retries = 0;
@@ -562,6 +581,7 @@ public:
_resume_verify_idx = 0; _resume_invalidated = false;
_resume_merkle.reset();
_wire_empty_stalls = 0;
_direct_session = false; _direct_confirmed = false; _fetch_route = {};
}
FetchState fetchState() const { return _fstate; }
@@ -695,6 +715,15 @@ private:
uint16_t wireRequestMask(uint32_t block, uint16_t need, uint16_t received,
uint16_t encoded_len) const;
void downgradeWireToLegacy(); // old source answered/ignored the v2 request profile
void downgradeDirectTransport(); // preserve committed blocks; discard unverified geometry
void invalidateDirectTransport(); // retire already-admitted direct raw frames
uint16_t fetchFragmentData() const {
return _direct_session ? OTA_DIRECT_FRAG_DATA :
(_wire_v2_session ? OTA_FRAG_DATA_V2 : OTA_FRAG_DATA);
}
const OtaReplyRoute* fetchReplyRoute() const {
return _fetch_route.profile < 2 ? &_fetch_route : nullptr;
}
bool anyWireDataReceived() const;
uint32_t blockLen(uint32_t i) const;
@@ -808,6 +837,11 @@ private:
uint8_t _max_hops = OTA_HOP_LIMIT_DEFAULT; // OTA flood reach in hops; 0=direct only (persisted)
uint8_t _fflags = 0; // flags of the manifest currently being fetched
bool _wire_v2_enabled = true; // advertise v2 in OTA_REQ while retaining transparent fallback
bool _direct_transport_enabled = false;
bool _direct_session = false;
bool _direct_confirmed = false;
OtaReplyRoute _fetch_route;
uint32_t _direct_transport_epoch;
bool _wire_v2_session = true; // false after an old source responds or the first request stalls
bool _wire_v2_confirmed = false; // at least one structurally valid v2 DATA packet was observed
bool _wire_allow_deflate = false; // session may request compressed blocks only with a decoder
+18 -6
View File
@@ -44,6 +44,9 @@ public:
#if MESH_ENABLE_MESHTEXT_WIRE
bool supportsMeshtext() const override { return true; }
#endif
#if MESH_ENABLE_ETHERNET_WIRE
bool supportsEthernetTunnel() const override { return true; }
#endif
protected:
float morseReceiverBandwidthKHz() const override { return 4.8f; }
@@ -70,15 +73,24 @@ protected:
return restoreSX126xPacketRamp(static_cast<CustomSX1262*>(_radio)) == RADIOLIB_ERR_NONE
&& RadioLibWrapper::restoreCarrierWaveModem();
}
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
bool applyProtocol(mesh::RadioProfileProtocol protocol) override {
if (protocol != mesh::RadioProfileProtocol::MeshCore
&& protocol != mesh::RadioProfileProtocol::Meshtext) return false;
// Respect an explicitly disabled wire implementation, including builds
// that retain other beacon or Companion features.
uint8_t sync = 0x12;
if (protocol == mesh::RadioProfileProtocol::Meshtext) {
if (!supportsMeshtext()) return false;
sync = 0x2b;
#if MESH_ENABLE_ETHERNET_WIRE
} else if (protocol == mesh::RadioProfileProtocol::Ethernet) {
if (!supportsEthernetTunnel()) return false;
sync = 0x16;
#endif
} else if (protocol != mesh::RadioProfileProtocol::MeshCore) return false;
// No alternate wire implementation means no modem write is needed.
// Ethernet-only builds must still restore the MeshCore syncword.
#if !MESH_ENABLE_ETHERNET_WIRE
if (!supportsMeshtext()) return protocol == mesh::RadioProfileProtocol::MeshCore;
#endif
auto* radio = static_cast<CustomSX1262*>(_radio);
const uint8_t sync = protocol == mesh::RadioProfileProtocol::Meshtext ? 0x2b : 0x12;
// Stage shared packet invariants only in a proven owned RX hop; normal
// initialization/rollback still repairs the complete RadioLib state.
return radio->setProfileProtocol(sync) == RADIOLIB_ERR_NONE;
+14 -4
View File
@@ -16,6 +16,9 @@ public:
#if MESH_ENABLE_MESHTEXT_WIRE
bool supportsMeshtext() const override { return true; }
#endif
#if MESH_ENABLE_ETHERNET_WIRE
bool supportsEthernetTunnel() const override { return true; }
#endif
void powerOff() {
if (isCarrierWaveActive()) setCarrierWave(0, 0);
@@ -23,11 +26,18 @@ public:
}
protected:
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
bool applyProtocol(mesh::RadioProfileProtocol protocol) override {
if (protocol != mesh::RadioProfileProtocol::MeshCore
&& protocol != mesh::RadioProfileProtocol::Meshtext) return false;
const uint8_t sync = protocol == mesh::RadioProfileProtocol::Meshtext ? 0x2b : 0x12;
uint8_t sync = 0x12;
if (protocol == mesh::RadioProfileProtocol::Meshtext) {
if (!supportsMeshtext()) return false;
sync = 0x2b;
#if MESH_ENABLE_ETHERNET_WIRE
} else if (protocol == mesh::RadioProfileProtocol::Ethernet) {
if (!supportsEthernetTunnel()) return false;
sync = 0x16;
#endif
} else if (protocol != mesh::RadioProfileProtocol::MeshCore) return false;
return static_cast<CustomSX1276*>(_radio)->setProfileProtocol(sync) == RADIOLIB_ERR_NONE;
}
#endif
@@ -0,0 +1,41 @@
#pragma once
#include <math.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
namespace mesh {
// Opt-in bench safety boundary, not a user setting or production default.
// Receive profiles may use other frequencies; no transmitter may do so.
inline bool hilTransmitFrequencyAllowed(float frequency_mhz) {
#if defined(MESH_HIL_TX_FREQ_MHZ)
static_assert(MESH_HIL_TX_FREQ_MHZ >= 150 && MESH_HIL_TX_FREQ_MHZ <= 2500,
"HIL TX frequency must be an explicit valid MHz value");
return isfinite(frequency_mhz)
&& fabsf(frequency_mhz - static_cast<float>(MESH_HIL_TX_FREQ_MHZ)) <= 0.0001f;
#else
(void)frequency_mhz;
return true;
#endif
}
// Runtime preflight must identify the same compiled boundary as the RF gate.
// No setter exists, and ordinary production images expose no such command.
inline bool handleHilTxFrequencyCommand(const char* command, char* reply, size_t capacity) {
#if defined(MESH_HIL_TX_FREQ_MHZ)
if (!command || !reply || !capacity || strcmp(command, "get lab.tx") != 0) return false;
snprintf(reply, capacity,
"> HIL TX lock=%.3f MHz; off-frequency TX blocked; primary RX-only when off-frequency",
static_cast<double>(MESH_HIL_TX_FREQ_MHZ));
return true;
#else
(void)command;
(void)reply;
(void)capacity;
return false;
#endif
}
} // namespace mesh
+90 -13
View File
@@ -252,6 +252,10 @@ bool RadioLibWrapper::setTxPower(int8_t dbm) {
) && _cw_active) return false;
if (_cw_active) {
if (_cw_stopping) return false;
#if defined(MESH_HIL_TX_FREQ_MHZ)
if (!hilPacketTransmitAllowed() || _cw_profile != _active_profile
|| _cw_generation != _profile_generation) return false;
#endif
// Permit meter sweeps through the board's normal power/PA calibration.
// SX127x's power setter enters standby, so re-key without resetting the
// modem or extending the original CW deadline.
@@ -331,7 +335,7 @@ bool RadioLibWrapper::restoreAfterDeepInit() {
restored = _radio->setPreambleLength(currentPreambleLength())
== RADIOLIB_ERR_NONE;
}
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
restored = restored && applyProtocol(_physical_protocol);
#endif
if (_dbm_valid) {
@@ -359,7 +363,7 @@ mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw,
const uint8_t previous_sf = _cur_sf;
const uint8_t previous_cr = _cur_cr;
const uint16_t previous_preamble = _physical_preamble;
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
const auto previous_protocol = _physical_protocol;
#endif
const uint8_t previous_profile = _active_profile;
@@ -376,7 +380,7 @@ mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw,
_physical_preamble = profilePreamble(0);
bool success = applyParams(freq, bw, sf, cr);
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
success = success && applyProtocol(requested.protocol);
if (success) _physical_protocol = requested.protocol;
#endif
@@ -410,7 +414,7 @@ mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw,
_profile_generation = previous_generation;
_profile_refresh_required = previous_refresh;
_physical_preamble = previous_preamble;
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
_physical_protocol = previous_protocol;
#endif
_rx_ps_enabled = previous_rxps;
@@ -421,7 +425,7 @@ mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw,
bool restored = had_previous_params
&& _radio->standby() == RADIOLIB_ERR_NONE
&& applyParams(previous_freq, previous_bw, previous_sf, previous_cr);
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
restored = restored && applyProtocol(previous_protocol);
#endif
@@ -441,6 +445,11 @@ mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw,
bool RadioLibWrapper::validateProfile(const mesh::RadioProfileParams& p) const {
if (!mesh::RadioProfiles::valid(p)) return false;
if (p.protocol == mesh::RadioProfileProtocol::Meshtext && !supportsMeshtext()) return false;
#if MESH_ENABLE_ETHERNET_WIRE
if (p.protocol == mesh::RadioProfileProtocol::Ethernet && !supportsEthernetTunnel()) return false;
#else
if (p.protocol == mesh::RadioProfileProtocol::Ethernet) return false;
#endif
#if MESH_RADIO_PROFILE_CHIP == 1276
return p.freq >= 137 && p.freq <= 1020 && p.sf >= 7 && p.bw <= 500;
#elif MESH_RADIO_PROFILE_CHIP == 1272
@@ -485,12 +494,12 @@ mesh::RadioParamApplyResult RadioLibWrapper::tuneProfile(uint8_t profile) {
const bool old_refresh = _profile_refresh_required;
const bool old_params_valid = _params_valid;
const uint16_t old_preamble = _physical_preamble;
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
const auto old_protocol = _physical_protocol;
#endif
_physical_preamble = preamble;
bool applied = applyParams(p.freq, p.bw, p.sf, p.cr);
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
// Changing only the protocol still changes the sync word. Conversely a
// failed write must not publish the new generation or cached wire format.
if (applied && (_physical_protocol != p.protocol || _profile_refresh_required)) {
@@ -520,12 +529,12 @@ mesh::RadioParamApplyResult RadioLibWrapper::tuneProfile(uint8_t profile) {
_profile_generation = old_generation;
_profile_refresh_required = old_refresh;
_physical_preamble = old_preamble;
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
_physical_protocol = old_protocol;
#endif
bool restored = old_params_valid && _radio->standby() == RADIOLIB_ERR_NONE
&& applyParams(old_freq, old_bw, old_sf, old_cr);
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
restored = restored && applyProtocol(old_protocol);
#endif
if (!restored) restored = restoreAfterDeepInit();
@@ -573,7 +582,7 @@ void RadioLibWrapper::cacheBeaconRestoreParams() {
_active_profile = profile;
_profile_generation = _profiles.generation[profile];
_physical_preamble = profilePreamble(profile);
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
_physical_protocol = p.protocol;
#endif
_profile_refresh_required = true;
@@ -583,6 +592,10 @@ mesh::RadioParamApplyResult RadioLibWrapper::prepareBeaconTransmit(
const mesh::RadioProfileParams& p, int8_t power) {
using Result = mesh::RadioParamApplyResult;
if (_beacon_owned || _cw_active) return Result::BUSY;
#if defined(MESH_HIL_TX_FREQ_MHZ)
_hil_beacon_tx_frequency_mhz = 0;
if (!mesh::hilTransmitFrequencyAllowed(p.freq)) return Result::FAILED;
#endif
if (!_params_valid || !_dbm_valid || !getBeaconAirtime(p, MAX_TRANS_UNIT)) return Result::FAILED;
if (isCalibratingNoiseFloor()) return Result::BUSY;
@@ -602,7 +615,7 @@ mesh::RadioParamApplyResult RadioLibWrapper::prepareBeaconTransmit(
? 16 : (p.preamble ? p.preamble : 32);
bool applied = _radio->standby() == RADIOLIB_ERR_NONE
&& applyParams(p.freq, p.bw, p.sf, p.cr);
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
applied = applied && applyProtocol(p.protocol);
if (applied) _physical_protocol = p.protocol;
#endif
@@ -611,6 +624,9 @@ mesh::RadioParamApplyResult RadioLibWrapper::prepareBeaconTransmit(
_rx_hold_continuous = false;
state = STATE_IDLE;
// Do not startReceive: this is a TX-only excursion, not a third RX profile.
#if defined(MESH_HIL_TX_FREQ_MHZ)
if (applied) _hil_beacon_tx_frequency_mhz = p.freq;
#endif
return applied ? Result::APPLIED : Result::FAILED;
}
@@ -630,6 +646,9 @@ mesh::RadioParamApplyResult RadioLibWrapper::restoreBeaconReceive() {
using Result = mesh::RadioParamApplyResult;
if (!_beacon_owned) return Result::APPLIED;
if (state == STATE_TX_WAIT) return Result::BUSY;
#if defined(MESH_HIL_TX_FREQ_MHZ)
_hil_beacon_tx_frequency_mhz = 0;
#endif
const uint32_t now = millis();
if (_beacon_restore_at && static_cast<int32_t>(now - _beacon_restore_at) < 0) return Result::BUSY;
_beacon_restoring = true;
@@ -639,7 +658,7 @@ mesh::RadioParamApplyResult RadioLibWrapper::restoreBeaconReceive() {
&& _radio->standby() == RADIOLIB_ERR_NONE;
beginProfileRetune(false);
restored = restored && applyParams(p.freq, p.bw, p.sf, p.cr);
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
restored = restored && applyProtocol(p.protocol);
#endif
restored = restored && applyCachedTxPower(_cur_dbm) == RADIOLIB_ERR_NONE;
@@ -682,6 +701,10 @@ mesh::RadioParamApplyResult RadioLibWrapper::prepareTransmitProfile(uint8_t prof
}
mesh::RadioParamApplyResult RadioLibWrapper::prepareTransmitProfile(uint8_t profile, bool reply_rx_override) {
#if defined(MESH_HIL_TX_FREQ_MHZ)
if (profile > 1 || !mesh::hilTransmitFrequencyAllowed(_profiles.params(profile).freq))
return mesh::RadioParamApplyResult::FAILED;
#endif
#if MESH_ENABLE_TX_BEACONS
if (_beacon_owned) return mesh::RadioParamApplyResult::BUSY;
#endif
@@ -729,7 +752,7 @@ void RadioLibWrapper::serviceProfileScan() {
}
if (_profiles.enabled() && !_profiles.switchTestReady()) {
// A bounded startup self-test uses the real RX-to-RX retune path for the
// active pair. Keep the 128-symbol provisional preamble until four good
// active pair. Keep the maximum automatic provisional preamble until four good
// samples in each direction are available. A packet, TX, or BUSY radio
// defers the remaining hops without counting an invalid measurement.
for (uint8_t hops = 0; hops < 2 * mesh::RadioProfiles::SwitchTestSamplesPerDirection;
@@ -1221,6 +1244,9 @@ mesh::RadioParamApplyResult RadioLibWrapper::setCarrierWave(uint8_t profile, uin
if (!duration_ms) return !_cw_active || stopCarrierWave() ? Result::APPLIED : Result::FAILED;
if (profile > 1 || duration_ms > CarrierWaveMaxMillis || !_params_valid
|| !_profiles.canTransmit(profile)) return Result::FAILED;
#if defined(MESH_HIL_TX_FREQ_MHZ)
if (!mesh::hilTransmitFrequencyAllowed(_profiles.params(profile).freq)) return Result::FAILED;
#endif
if (_cw_active) {
if (_morse_owned
#if MESH_ENABLE_MORSE_RX
@@ -1243,6 +1269,12 @@ mesh::RadioParamApplyResult RadioLibWrapper::setCarrierWave(uint8_t profile, uin
startRecv();
return Result::FAILED;
}
#if defined(MESH_HIL_TX_FREQ_MHZ)
if (!hilPacketTransmitAllowed()) {
startRecv();
return Result::FAILED;
}
#endif
_radio->clearPacketReceivedAction();
state = STATE_IDLE;
_rx_ps_armed = false;
@@ -1277,6 +1309,9 @@ mesh::MorseTxResult RadioLibWrapper::startMorseTx(float frequency_mhz,
const Result valid_text = mesh::MorseTx::validate(text, wpm);
if (valid_text != Result::Started) return valid_text;
if (!_params_valid || !isfinite(frequency_mhz)) return Result::InvalidFrequency;
#if defined(MESH_HIL_TX_FREQ_MHZ)
if (!mesh::hilTransmitFrequencyAllowed(frequency_mhz)) return Result::InvalidFrequency;
#endif
// Only the carrier frequency matters here: existing LoRa SF/BW/protocol
// constraints must not accidentally limit an unmodulated transmission.
if (!validateMorseFrequency(frequency_mhz)) return Result::InvalidFrequency;
@@ -1338,6 +1373,12 @@ bool RadioLibWrapper::serviceMorseTx() {
if (static_cast<int32_t>(now - _cw_retry_at) >= 0) stopCarrierWave();
return true;
}
#if defined(MESH_HIL_TX_FREQ_MHZ)
if (!mesh::hilTransmitFrequencyAllowed(_morse_frequency)) {
stopCarrierWave();
return true;
}
#endif
if (_morse_generation[0] != _profiles.generation[0]
|| _morse_generation[1] != _profiles.generation[1]) {
stopCarrierWave();
@@ -1620,6 +1661,12 @@ bool RadioLibWrapper::serviceCarrierWave() {
#endif
if (serviceMorseTx()) return true;
if (_cw_active) {
#if defined(MESH_HIL_TX_FREQ_MHZ)
if (!hilPacketTransmitAllowed()) {
stopCarrierWave();
return true;
}
#endif
const uint32_t now = millis();
if ((_cw_stopping && static_cast<int32_t>(now - _cw_retry_at) >= 0)
|| (!_cw_stopping && (static_cast<int32_t>(now - _cw_until) >= 0
@@ -1996,7 +2043,37 @@ uint32_t RadioLibWrapper::getEstAirtimeFor(int len_bytes) {
return airtime_us / 1000;
}
#if defined(MESH_HIL_TX_FREQ_MHZ)
bool RadioLibWrapper::hilPacketTransmitAllowed() const {
#if MESH_ENABLE_TX_BEACONS
if (_beacon_owned) {
return !_beacon_restoring
&& mesh::hilTransmitFrequencyAllowed(_hil_beacon_tx_frequency_mhz);
}
#endif
// Check the committed physical cache, not only a requested profile. Failed
// retunes, stale generations, and an unresolved refresh never authorize RF.
if (!_params_valid || _profile_refresh_required || _active_profile > 1
|| (_active_profile == 1 && !_profiles.enabled())
|| _profile_generation != _profiles.generation[_active_profile]) return false;
const auto& p = _profiles.params(_active_profile);
return mesh::hilTransmitFrequencyAllowed(_cur_freq)
&& _cur_freq == p.freq && _cur_bw == p.bw && _cur_sf == p.sf && _cur_cr == p.cr
&& _physical_preamble == profilePreamble(_active_profile)
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
&& _physical_protocol == p.protocol
#endif
;
}
#endif
bool RadioLibWrapper::startSendRaw(const uint8_t* bytes, int len) {
#if defined(MESH_HIL_TX_FREQ_MHZ)
if (!hilPacketTransmitAllowed()) {
MESH_DEBUG_PRINTLN("HIL: packet TX blocked outside the proven allowed frequency");
return false;
}
#endif
if (_cw_active || hasPendingRadioInterrupt()) return false;
_rx_hold_continuous = false;
if (_rx_ps_armed) {
+10 -1
View File
@@ -8,6 +8,7 @@
#include "CadTiming.h"
#include "RadioAirtime.h"
#include "RXPowerSaving.h"
#include "HilTxFrequencyGuard.h"
// Fallback RX powersaving timings, only used until setRxPowerSaving() is called
// (begin() always applies the persisted values). The authoritative defaults live
@@ -89,7 +90,7 @@ protected:
mesh::RadioProfiles _profiles;
uint8_t _active_profile = 0;
uint16_t _physical_preamble = 0;
#if MESH_ENABLE_MESHTEXT_WIRE
#if MESH_ENABLE_MESHTEXT_WIRE || MESH_ENABLE_ETHERNET_WIRE
mesh::RadioProfileProtocol _physical_protocol = mesh::RadioProfileProtocol::MeshCore;
// Wire settings are a transaction with the modulation tuple. Unsupported
// wrappers decline rather than claiming a profile was applied.
@@ -104,6 +105,9 @@ protected:
bool _profile_rxps_suspended = false;
bool _profile_saved_rxps = false;
bool _profile_refresh_required = false;
#if defined(MESH_HIL_TX_FREQ_MHZ)
bool hilPacketTransmitAllowed() const;
#endif
#if MESH_ENABLE_TX_BEACONS
// The normal cache is never overwritten by a transmit-only excursion.
// Retain ownership through failed TX and restoration retries.
@@ -112,6 +116,11 @@ protected:
uint8_t _beacon_restore_profile = 0;
uint32_t _beacon_restore_at = 0;
uint32_t _beacon_cad_timeout = 0;
#if defined(MESH_HIL_TX_FREQ_MHZ)
// Beacon excursions deliberately leave the normal profile cache intact.
// Zero revokes TX proof until the complete physical setup has succeeded.
float _hil_beacon_tx_frequency_mhz = 0;
#endif
void cacheBeaconRestoreParams();
#endif
bool _cw_active = false;