Add Meshtext Companion channel chat and automatic radio2 setup

This commit is contained in:
mikecarper committed 2026-10-11 02:08:02 -07:00
1 parent 1f1a499482
commit 05907f49e0
52 files changed
+7700 -128

No files matched your search

+202 -2
View File
@@ -48,6 +48,12 @@ void Dispatcher::setRadioAvailable(bool available) {
if (radio_available == available) return;
radio_available = available;
#if MESH_ENABLE_MESHTEXT_CHAT
if (!available && hasForeignRadioFrame()) {
if (foreign_radio_sending) _radio->onSendFinished();
finishForeignRadioFrame(false, foreign_radio_sending);
}
#endif
radio_nonrx_timer_armed = false;
if (!dispatcher_started || !radio_available) return;
@@ -68,6 +74,12 @@ void Dispatcher::setRadioAvailable(bool available) {
}
void Dispatcher::begin() {
#if MESH_ENABLE_MESHTEXT_CHAT
if (hasForeignRadioFrame()) {
if (foreign_radio_sending && radio_available) _radio->onSendFinished();
finishForeignRadioFrame(false, foreign_radio_sending);
}
#endif
n_sent_flood = n_sent_direct = 0;
n_recv_flood = n_recv_direct = 0;
last_meshcore_recv_millis = 0;
@@ -259,6 +271,154 @@ void Dispatcher::failOutboundTransmit() {
outbound_cancellation = OutboundCancellation::None;
}
#if MESH_ENABLE_MESHTEXT_CHAT
bool Dispatcher::isForeignRadioCurrent() const {
const auto* profiles = _radio->profiles();
return radio_available && _radio->supportsMeshtext() && profiles
&& allowForeignRadioTransmit()
&& foreign_radio_profile == 1 && profiles->enabled()
&& profiles->canTransmit(foreign_radio_profile)
&& profiles->params(foreign_radio_profile).protocol == RadioProfileProtocol::Meshtext
&& foreign_radio_generation == profiles->generation[foreign_radio_profile];
}
bool Dispatcher::queueForeignRadioFrame(const uint8_t* bytes, size_t length,
uint8_t profile, uint32_t generation) {
const auto* profiles = _radio->profiles();
if (!bytes || !length || length > sizeof(foreign_radio_bytes) || hasForeignRadioFrame()
|| !radio_available || !_radio->supportsMeshtext() || _radio->isCarrierWaveActive()
|| !allowForeignRadioTransmit()
|| !profiles || profile != 1 || !profiles->enabled() || !profiles->canTransmit(profile)
|| profiles->params(profile).protocol != RadioProfileProtocol::Meshtext
|| generation != profiles->generation[profile]) return false;
memcpy(foreign_radio_bytes, bytes, length);
foreign_radio_length = (uint16_t)length;
foreign_radio_profile = profile;
foreign_radio_generation = generation;
foreign_radio_retry_at = foreign_radio_prepare_deadline = 0;
foreign_radio_sending = false;
return true;
}
void Dispatcher::finishForeignRadioFrame(bool success, bool account_airtime) {
if (!hasForeignRadioFrame()) return;
if (account_airtime) {
const uint32_t elapsed = (uint32_t)_ms->getMillis() - foreign_radio_start;
total_air_time += elapsed;
updateTxBudget();
tx_budget_ms = elapsed >= tx_budget_ms ? 0 : tx_budget_ms - elapsed;
if (tx_budget_ms < MIN_TX_BUDGET_RESERVE_MS) {
const float duty_cycle = 1.0f / (1.0f + getAirtimeBudgetFactor());
next_tx_time = futureMillis((unsigned long)((MIN_TX_BUDGET_RESERVE_MS - tx_budget_ms) / duty_cycle));
} else next_tx_time = _ms->getMillis();
}
if (success && _radio->profiles()) ++_radio->profiles()->tx_packets[foreign_radio_profile];
// Release ownership before calling the application; it may submit another
// explicit user message. No retry is scheduled after any failure/timeout.
foreign_radio_length = 0;
foreign_radio_sending = false;
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);
}
bool Dispatcher::serviceForeignRadioFrame() {
if (!hasForeignRadioFrame()) return false;
if (!foreign_radio_sending) {
if (!isForeignRadioCurrent()) finishForeignRadioFrame(false, false);
return false;
}
if (_radio->isSendComplete()) {
const bool current = isForeignRadioCurrent();
_radio->onSendFinished();
finishForeignRadioFrame(current, true);
return false;
}
if (millisHasNowPassed(foreign_radio_expiry)) {
_radio->onSendFinished();
finishForeignRadioFrame(false, true);
_err_flags |= ERR_EVENT_RADIO_WATCHDOG;
_radio->recoverRadio(true);
return false;
}
return true;
}
bool Dispatcher::checkForeignRadioSend() {
if (!hasForeignRadioFrame() || outbound || foreign_radio_sending) return false;
if (!isForeignRadioCurrent()) {
finishForeignRadioFrame(false, false);
return false;
}
if (!restoreOutboundTxOverrides() || _radio->isCarrierWaveActive()) return false;
const uint32_t now = _ms->getMillis();
// 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) {
foreign_radio_yield_meshcore = false;
return false;
}
if (foreign_radio_retry_at && (int32_t)(now - foreign_radio_retry_at) < 0) return false;
updateTxBudget();
const uint32_t airtime = validPrepareBusyAirtime(
_radio->getProfileAirtime(foreign_radio_profile, foreign_radio_length));
if (!airtime) { finishForeignRadioFrame(false, false); return false; }
if (tx_budget_ms < airtime / MIN_TX_BUDGET_AIRTIME_DIV) {
const float duty_cycle = 1.0f / (1.0f + getAirtimeBudgetFactor());
next_tx_time = futureMillis((unsigned long)((airtime / MIN_TX_BUDGET_AIRTIME_DIV - tx_budget_ms) / duty_cycle));
return false;
}
if (!millisHasNowPassed(next_tx_time)) return false;
const auto prepared = _radio->prepareTransmitProfile(foreign_radio_profile);
if (prepared == RadioParamApplyResult::BUSY) {
if (!foreign_radio_prepare_deadline) {
uint32_t maximum = validPrepareBusyAirtime(_radio->getProfileAirtime(0, MAX_TRANS_UNIT));
const uint32_t other = validPrepareBusyAirtime(_radio->getProfileAirtime(1, MAX_TRANS_UNIT));
if (other > maximum) maximum = other;
foreign_radio_prepare_deadline = now + maximum * 3 / 2 + RADIO_PREPARE_BUSY_GRACE_MS;
if (!foreign_radio_prepare_deadline) foreign_radio_prepare_deadline = 1;
} else if (millisHasNowPassed(foreign_radio_prepare_deadline)) {
finishForeignRadioFrame(false, false);
_err_flags |= ERR_EVENT_RADIO_WATCHDOG;
_radio->recoverRadio(true);
return false;
}
foreign_radio_retry_at = now + 10;
return false;
}
foreign_radio_prepare_deadline = 0;
if (prepared != RadioParamApplyResult::APPLIED || !isForeignRadioCurrent()) {
finishForeignRadioFrame(false, false);
return false;
}
// CAD is the normal bounded pre-transmit check. Waiting does not retain the
// transceiver: MeshCore RX/TX and profile scanning continue in the meantime.
uint32_t& busy_since = profile_cad_busy[foreign_radio_profile];
if (_radio->isReceiving()) {
if (!busy_since) busy_since = now ? now : 1;
if ((uint32_t)(now - busy_since) <= getCADFailMaxDuration()) {
foreign_radio_retry_at = now + getCADFailRetryDelay();
return false;
}
_err_flags |= ERR_EVENT_CAD_TIMEOUT;
}
busy_since = 0;
foreign_radio_retry_at = 0;
foreign_radio_start = _ms->getMillis();
if (!_radio->startSendRaw(foreign_radio_bytes, foreign_radio_length)) {
// RadioLib owns failure cleanup (including the board's FEM). Unlike
// MeshCore reliable routing, foreign chat never retries autonomously.
finishForeignRadioFrame(false, false);
return false;
}
foreign_radio_sending = true;
foreign_radio_expiry = foreign_radio_start + airtime * 3 / 2 + 1000;
return true;
}
#endif
int Dispatcher::calcRxDelay(float score, uint32_t air_time) const {
return (int) ((powf(10.0f, 0.85f - score) - 1.0f) * air_time);
}
@@ -301,6 +461,9 @@ 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 (hasForeignRadioFrame()) { delay_millis = 0; return true; }
#endif
const uint32_t now = _ms->getMillis();
bool found = false;
uint32_t shortest_delay = 0;
@@ -371,6 +534,11 @@ 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
// 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;
#endif
const unsigned long now = _ms->getMillis();
if (!radio_nonrx_timer_armed) {
@@ -632,7 +800,11 @@ void Dispatcher::loop() {
}
#endif
}
#if MESH_ENABLE_MESHTEXT_CHAT
if (!checkForeignRadioSend()) checkSend();
#else
checkSend();
#endif
releaseDroppedOutbound();
}
@@ -728,6 +900,24 @@ void Dispatcher::checkRecv() {
snr = _radio->getLastSNR();
rssi = _radio->getLastRSSI();
const uint8_t profile = _radio->receiveProfile();
const auto* profiles = _radio->profiles();
// 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]) {
rx_air_time += _radio->getProfileAirtime(profile, len);
++_radio->profiles()->rx_packets[profile];
onForeignRadioFrame(raw, (size_t)len, profile, profiles->generation[profile], snr, rssi);
}
#endif
_radio->onReceiveProcessed();
return;
}
// 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
@@ -793,6 +983,7 @@ void Dispatcher::processRecvPacket(Packet* pkt) {
const auto* profiles = _radio->profiles();
if (profiles && (pkt->radio_profile > 1
|| (pkt->radio_profile == 1 && !profiles->enabled())
|| profiles->params(pkt->radio_profile).protocol != RadioProfileProtocol::MeshCore
|| pkt->radio_generation != profiles->generation[pkt->radio_profile])) {
releasePacket(pkt);
return;
@@ -1083,8 +1274,15 @@ uint8_t Dispatcher::getTransmitProfileMask(const Packet* packet) const {
uint8_t origin = packet->radio_profile;
if (policy == RADIO_TX_AUTO && packet->radio_local && packet->getPayloadType() == PAYLOAD_TYPE_OTA
&& profiles->secondary_temporary && !profiles->primary_temporary) origin = 1;
return policy == RADIO_TX_AUTO ? profiles->transmitMask(origin)
uint8_t mask = policy == RADIO_TX_AUTO ? profiles->transmitMask(origin)
: explicitRadioTxMask(policy, profiles->canTransmit(1, force));
// Explicit BOTH/secondary/reply-force policies cannot turn a MeshCore
// packet into foreign-network traffic. The raw API is its only TX path.
for (uint8_t profile = 0; profile < 2; ++profile) {
if (profiles->params(profile).protocol != RadioProfileProtocol::MeshCore)
mask &= (uint8_t)~(1U << profile);
}
return mask;
}
uint32_t Dispatcher::getTransmitAirtime(const Packet* packet) const {
@@ -1099,8 +1297,10 @@ uint32_t Dispatcher::getTransmitAirtime(const Packet* packet) const {
bool Dispatcher::isPacketRadioCurrent(const Packet* packet) const {
const auto* p = _radio->profiles();
if (!p || !packet->radio_bound) return true;
if (!p) return true;
const uint8_t target = packet->radio_profile;
if (target > 1 || p->params(target).protocol != RadioProfileProtocol::MeshCore) return false;
if (!packet->radio_bound) return true;
const uint8_t origin = packet->radio_origin;
const bool force = packet->radio_reply && packet->radio_reply_force;
return target < 2 && origin < 2 && p->canTransmit(target, force)
+33 -1
View File
@@ -5,6 +5,7 @@
#include <Packet.h>
#include <Utils.h>
#include <RadioProfiles.h>
#include <helpers/MeshtextConfig.h>
#ifndef RADIO_LIVENESS_SOFT_ONLY
#include <helpers/RadioLivenessTracker.h>
#endif
@@ -45,6 +46,7 @@ public:
virtual RadioProfiles* profiles() { return nullptr; }
virtual const RadioProfiles* profiles() const { return nullptr; }
virtual bool validateProfile(const RadioProfileParams&) const { return false; }
virtual bool supportsMeshtext() const { return false; }
virtual uint8_t receiveProfile() const { return 0; }
virtual uint32_t receiveProfileGeneration() const {
return profiles() ? profiles()->generation[receiveProfile()] : 0;
@@ -341,6 +343,21 @@ class Dispatcher {
uint32_t receive_context_generation = 0;
bool receive_context_active = false;
uint32_t profile_cad_busy[2] = {};
#if MESH_ENABLE_MESHTEXT_CHAT
// 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;
uint32_t foreign_radio_generation = 0;
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 serviceForeignRadioFrame();
bool checkForeignRadioSend();
void finishForeignRadioFrame(bool success, bool account_airtime);
#endif
void processRecvPacket(Packet* pkt);
void releaseDroppedOutbound();
@@ -423,6 +440,15 @@ protected:
virtual void onTracePacketQueuedForSend(Packet* packet) { }
virtual void onSendComplete(Packet* packet) { }
virtual void onSendFail(Packet* packet) { }
#if MESH_ENABLE_MESHTEXT_CHAT
// 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);
bool hasForeignRadioFrame() const { return foreign_radio_length != 0; }
#endif
virtual void onRadioProfileCopyQueued(Packet* packet, const Packet* original, uint8_t priority) { }
// Policy gate for the other profile only; same-profile TX remains eligible.
// Called before admitting copies (including bound retry packets) to a queue.
@@ -504,7 +530,13 @@ public:
// Raw radio reads, local sends, and statistics resets do not update this clock.
uint32_t getLastMeshCoreRecvMillis() const { return last_meshcore_recv_millis; }
uint16_t getErrFlags() const { return _err_flags; } // Get error flags
bool hasOutbound() const { return outbound != NULL; }
bool hasOutbound() const {
return outbound != NULL
#if MESH_ENABLE_MESHTEXT_CHAT
|| hasForeignRadioFrame()
#endif
;
}
bool isCurrentOutbound(const Packet* packet) const { return outbound == packet; }
void resetStats() {
n_sent_flood = n_sent_direct = n_recv_flood = n_recv_direct = 0;
+5 -1
View File
@@ -1061,6 +1061,10 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
return ACTION_RELEASE;
}
if ((pkt->getPayloadType() == PAYLOAD_TYPE_GRP_TXT
|| pkt->getPayloadType() == PAYLOAD_TYPE_GRP_DATA)
&& !allowGroupPacketOnRadio(pkt)) return ACTION_RELEASE;
if (pkt->isRouteDirect() && pkt->getPathHashCount() > 0) {
// check for 'early received' ACK
if (pkt->getPayloadType() == PAYLOAD_TYPE_ACK) {
@@ -1262,7 +1266,7 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
onGroupPacketRecv(pkt);
// scan channels DB, for all matching hashes of 'channel_hash' (max 4 matches supported ATM)
GroupChannel channels[4];
int num = searchChannelsByHash(&channel_hash, channels, 4);
int num = searchChannelsForPacket(pkt, &channel_hash, channels, 4);
// for each matching channel, try to decrypt data
for (int j = 0; j < num; j++) {
// decrypt, checking MAC is valid
+8
View File
@@ -578,6 +578,14 @@ protected:
*/
virtual int searchChannelsByHash(const uint8_t* hash, GroupChannel channels[], int max_matches);
// Use captured RX origin: queued packets can outlive a transceiver retune.
virtual int searchChannelsForPacket(const Packet* packet, const uint8_t* hash,
GroupChannel channels[], int max_matches) {
return searchChannelsByHash(hash, channels, max_matches);
}
// Known wrong-profile traffic must not poison global receive deduplication.
virtual bool allowGroupPacketOnRadio(Packet* packet) { return true; }
/**
* \brief A structurally valid encrypted group packet has been observed.
* Called once for each unseen packet before local channel matching and
+13 -3
View File
@@ -9,6 +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 };
// These are modulation profiles of ONE transceiver, never additional radios.
struct RadioProfileParams {
@@ -17,10 +18,11 @@ struct RadioProfileParams {
uint16_t preamble = 0; // 0 = automatic, otherwise symbols
uint8_t sf = 0;
uint8_t cr = 0;
RadioProfileProtocol protocol = RadioProfileProtocol::MeshCore;
bool operator==(const RadioProfileParams& other) const {
return freq == other.freq && bw == other.bw && sf == other.sf
&& cr == other.cr && preamble == other.preamble;
&& cr == other.cr && preamble == other.preamble && protocol == other.protocol;
}
bool operator!=(const RadioProfileParams& other) const { return !(*this == other); }
};
@@ -102,8 +104,9 @@ class RadioProfiles {
|| (reply_rx_override && secondary.mode == RadioProfileMode::Rx)));
}
bool canCross() const {
return cross == RadioCrossMode::On || (cross == RadioCrossMode::Auto
&& primary_temporary == secondary_temporary);
return primary.protocol == secondary.params.protocol
&& (cross == RadioCrossMode::On || (cross == RadioCrossMode::Auto
&& primary_temporary == secondary_temporary));
}
uint8_t transmitMask(uint8_t origin) const {
if (origin > 1) origin = 0;
@@ -117,6 +120,7 @@ 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.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};
@@ -219,6 +223,9 @@ class RadioProfiles {
}
uint16_t preamble(uint8_t profile, uint16_t single_profile_default) const {
const auto& p = params(profile);
// The foreign network's wire format has a fixed 16-symbol preamble;
// MeshCore's scan recommendations must never silently lengthen it.
if (p.protocol == RadioProfileProtocol::Meshtext) return 16;
if (p.preamble) return p.preamble;
if (!enabled()) return single_profile_default;
// Do not expose an unmeasured short preamble while the startup test runs.
@@ -235,6 +242,9 @@ class RadioProfiles {
}
// Recommendations over 128 are reported as unsafe, 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.
if (enabled() && primary.protocol != secondary.params.protocol) return true;
if (enabled()) {
const uint8_t slow = slowerProfile();
const double available = double(preamble(slow, 32)) / 2.0 * symbolUs(params(slow))
+11
View File
@@ -136,6 +136,17 @@ inline const char* terminalPasswordInput(const char* line) {
== TerminalArgumentCommandMatch::Valid) {
return password;
}
// `set mt.channel <slot> <name> <PSK>`: never echo private channel keys.
const char* channel = nullptr;
if (parseTerminalArgumentCommand(setting, "mt.channel", channel)
== TerminalArgumentCommandMatch::Valid) {
for (unsigned token = 0; token < 2; ++token) {
while (*channel && *channel != ' ' && *channel != '\t') ++channel;
channel = skipRecentRepeaterSpaces(channel);
if (!*channel) return nullptr;
}
return channel;
}
return nullptr;
}
+71
View File
@@ -0,0 +1,71 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
// Local labels, not part of a hashtag PSK. Keep the original app label/key.
enum class CompanionChannelKind : uint8_t { MeshCore, Radio2, Meshtext, Invalid };
struct CompanionChannelAlias {
CompanionChannelKind kind;
bool hashtag;
const char* tail;
};
inline CompanionChannelAlias parseCompanionChannelAlias(const char* name) {
if (name == nullptr) return {CompanionChannelKind::Invalid, false, ""};
const bool hashtag = name[0] == '#';
const char* tail = name + (hashtag ? 1 : 0);
CompanionChannelKind kind = CompanionChannelKind::MeshCore;
if (strncmp(tail, "r2-", 3) == 0) {
kind = CompanionChannelKind::Radio2;
tail += 3;
} else if (strncmp(tail, "mt-", 3) == 0) {
kind = CompanionChannelKind::Meshtext;
tail += 3;
}
if (kind != CompanionChannelKind::MeshCore
&& (tail[0] == 0 || tail[0] == '#' || strncmp(tail, "r2-", 3) == 0
|| strncmp(tail, "mt-", 3) == 0)) kind = CompanionChannelKind::Invalid;
return {kind, hashtag, tail};
}
inline bool companionChannelCanonicalName(const char* name, char* out, size_t size) {
if (out == nullptr) return false;
const auto alias = parseCompanionChannelAlias(name);
if (alias.kind == CompanionChannelKind::Invalid) return false;
const size_t offset = alias.hashtag ? 1 : 0;
const size_t length = strlen(alias.tail);
if (size <= offset + length) return false;
if (offset) out[0] = '#';
memcpy(out + offset, alias.tail, length + 1);
return true;
}
template <typename Hash>
bool resolveCompanionChannelKey(const char* name, uint8_t secret[32], Hash hash) {
const auto alias = parseCompanionChannelAlias(name);
if (alias.kind == CompanionChannelKind::Invalid) return false;
if (alias.kind == CompanionChannelKind::MeshCore || !alias.hashtag) return true;
for (size_t i = 16; i < 32; ++i) {
if (secret[i] != 0) return true; // Never rewrite an explicit 256-bit PSK.
}
uint8_t app_key[16];
hash(app_key, sizeof(app_key), reinterpret_cast<const uint8_t*>(name), strlen(name));
if (memcmp(secret, app_key, sizeof(app_key)) != 0) return true; // Custom PSK.
char canonical[32];
if (!companionChannelCanonicalName(name, canonical, sizeof(canonical))) return false;
hash(secret, 16, reinterpret_cast<const uint8_t*>(canonical), strlen(canonical));
return true;
}
inline int companionChannelReceivePriority(const char* name, uint8_t origin,
bool radio2_defined = true) {
const auto alias = parseCompanionChannelAlias(name);
if (alias.kind == CompanionChannelKind::Invalid) return -1;
if (radio2_defined) {
if (alias.kind == CompanionChannelKind::Meshtext) return -1;
if (alias.kind == CompanionChannelKind::Radio2) return origin == 1 ? 0 : -1;
}
return origin == 1 ? 1 : 0;
}
+97
View File
@@ -0,0 +1,97 @@
#pragma once
#include "CompanionChannelAlias.h"
#include "MeshtextChat.h"
#include <initializer_list>
namespace mesh { namespace mt {
struct Channel {
char name[12] = {};
uint8_t key[32] = {};
size_t key_length = 16;
Preset preset = Preset::LongFast;
bool named_preset = false;
};
// The app retains its original label and PSK. Only this volatile wire copy
// expands a recognized public preset alias into the Meshtext AQ== key.
// Explicit private keys, including 256-bit keys, must never become public.
template <typename Hash>
bool describeChannel(const char* name, const uint8_t secret[32], Channel& out, Hash hash) {
const auto alias = parseCompanionChannelAlias(name);
if (alias.kind != CompanionChannelKind::Meshtext || !secret) return false;
Channel result;
result.named_preset = parsePreset(alias.tail, result.preset);
const char* wire_name = result.named_preset ? presetName(result.preset) : alias.tail;
if (!wire_name || !*wire_name || strlen(wire_name) >= sizeof(result.name)) return false;
memcpy(result.name, wire_name, strlen(wire_name) + 1);
memcpy(result.key, secret, sizeof(result.key));
for (size_t i = 16; i < sizeof(result.key); ++i) {
if (result.key[i]) result.key_length = 32;
}
if (alias.hashtag && result.key_length == 16) {
uint8_t derived[16];
hash(derived, sizeof(derived), reinterpret_cast<const uint8_t*>(name), strlen(name));
char canonical[32];
if (!companionChannelCanonicalName(name, canonical, sizeof(canonical))) return false;
const bool app_derived = memcmp(derived, secret, sizeof(derived)) == 0;
hash(derived, sizeof(derived), reinterpret_cast<const uint8_t*>(canonical), strlen(canonical));
const bool canonical_derived = memcmp(derived, secret, sizeof(derived)) == 0;
if (app_derived || canonical_derived) {
if (result.named_preset) memcpy(result.key, DefaultPsk, sizeof(DefaultPsk));
else memcpy(result.key, derived, sizeof(derived));
}
}
bool nonzero = false;
for (size_t i = 0; i < result.key_length; ++i) nonzero |= result.key[i] != 0;
if (!nonzero) return false; // Never silently fall back to an open channel.
out = result;
return true;
}
// The 902-915 MHz portion is unambiguously US among supported plans; 915-928
// overlaps US and ANZ, so it requires an explicit region instead of guessing.
inline Region inferRegion(float primary_frequency) {
if (primary_frequency >= 902 && primary_frequency < 915) return Region::US;
if (primary_frequency >= 869.4f && primary_frequency <= 869.65f) return Region::EU868;
if (primary_frequency >= 433 && primary_frequency <= 434) return Region::EU433;
return Region::Unset;
}
inline const char* regionName(Region region) {
switch (region) {
case Region::US: return "us";
case Region::EU868: return "eu868";
case Region::EU433: return "eu433";
case Region::ANZ: return "anz";
default: return "auto";
}
}
inline bool parseRegion(const char* value, Region& region) {
if (!value) return false;
for (Region item : {Region::Unset, Region::US, Region::EU868, Region::EU433, Region::ANZ}) {
if (!strcmp(value, regionName(item))) { region = item; return true; }
}
return false;
}
inline bool sameModulation(const RadioProfileParams& a, const RadioProfileParams& b) {
return a.bw == b.bw && a.sf == b.sf && a.cr == b.cr;
}
inline bool frequencyInRegion(Region region, const RadioProfileParams& p) {
const float half_width = p.bw / 2000.0f;
float lower = 0, upper = 0;
switch (region) {
case Region::US: lower = 902; upper = 928; break;
case Region::ANZ: lower = 915; upper = 928; break;
case Region::EU868: lower = 869.4f; upper = 869.65f; break;
case Region::EU433: lower = 433; upper = 434; break;
default: return false;
}
return p.freq - half_width >= lower - 0.0001f && p.freq + half_width <= upper + 0.0001f;
}
} } // namespace mesh::mt
+368
View File
@@ -0,0 +1,368 @@
#include "MeshtextChat.h"
#if defined(MESH_ENABLE_MESHTEXT_CHAT) && MESH_ENABLE_MESHTEXT_CHAT
#include <AES.h>
#include <string.h>
// Adapted from esp-cpp/espp, Copyright (c) 2022 esp-cpp, MIT license.
// Pinned source and complete notice: licenses/ESPP-Meshtext-MIT.txt.
// No upstream GPL implementation or generated schema code is included.
namespace mesh {
namespace mt {
const uint8_t DefaultPsk[16] = {
0xd4, 0xf1, 0xbb, 0x3a, 0x20, 0x29, 0x07, 0x59,
0xf0, 0xbc, 0xff, 0xab, 0xcf, 0x4e, 0x69, 0x01
};
namespace {
static constexpr uint32_t Broadcast = 0xffffffffU;
struct PresetInfo {
Preset preset;
const char* name;
uint32_t bandwidth;
uint8_t sf, cr;
};
const PresetInfo Presets[] = {
{Preset::ShortTurbo, "ShortTurbo", 500000, 7, 5},
{Preset::ShortFast, "ShortFast", 250000, 7, 5},
{Preset::ShortSlow, "ShortSlow", 250000, 8, 5},
{Preset::MediumTurbo, "MediumTurbo", 500000, 9, 5},
{Preset::MediumFast, "MediumFast", 250000, 9, 5},
{Preset::MediumSlow, "MediumSlow", 250000, 10, 5},
{Preset::LongTurbo, "LongTurbo", 500000, 11, 8},
{Preset::LongFast, "LongFast", 250000, 11, 5},
{Preset::LongModerate, "LongMod", 125000, 11, 8},
{Preset::LongSlow, "LongSlow", 125000, 12, 8},
};
const PresetInfo* presetInfo(Preset preset) {
for (const auto& entry : Presets) if (entry.preset == preset) return &entry;
return nullptr;
}
uint32_t nameHash(const char* name) {
uint32_t hash = 5381;
while (*name) hash = hash * 33U + static_cast<uint8_t>(*name++);
return hash;
}
bool validName(const char* name) {
if (name == nullptr || name[0] == 0) return false;
for (size_t i = 1; i < 12; ++i) if (name[i] == 0) return true;
return false;
}
bool equalPresetName(const char* a, const char* b) {
while (*a && *b) {
uint8_t first = static_cast<uint8_t>(*a++), second = static_cast<uint8_t>(*b++);
if (first >= 'A' && first <= 'Z') first += 'a' - 'A';
if (second >= 'A' && second <= 'Z') second += 'a' - 'A';
if (first != second) return false;
}
return *a == *b;
}
uint8_t channelHash(const char* name, const uint8_t* key, size_t key_len) {
uint8_t hash = 0;
while (*name) hash ^= static_cast<uint8_t>(*name++);
for (size_t i = 0; i < key_len; ++i) hash ^= key[i];
return hash;
}
void put32(uint8_t* out, uint32_t value) {
for (unsigned i = 0; i < 4; ++i) out[i] = static_cast<uint8_t>(value >> (8 * i));
}
uint32_t get32(const uint8_t* in) {
return uint32_t(in[0]) | uint32_t(in[1]) << 8 | uint32_t(in[2]) << 16 | uint32_t(in[3]) << 24;
}
void erase(uint8_t* bytes, size_t size) {
volatile uint8_t* dest = bytes;
while (size--) *dest++ = 0;
}
bool validUtf8(const uint8_t* text, size_t length, size_t maximum, size_t* scalar_count = nullptr) {
if (text == nullptr || length > maximum) return false;
size_t scalars = 0;
// Full UTF-8 validation: no NUL, overlong encoding, surrogate or >U+10FFFF.
for (size_t i = 0; i < length;) {
const uint8_t first = text[i++];
++scalars;
if (first == 0) return false;
if (first < 0x80) continue;
unsigned continuation;
uint8_t second_min = 0x80, second_max = 0xbf;
if (first >= 0xc2 && first <= 0xdf) continuation = 1;
else if (first >= 0xe0 && first <= 0xef) {
continuation = 2;
if (first == 0xe0) second_min = 0xa0;
if (first == 0xed) second_max = 0x9f;
} else if (first >= 0xf0 && first <= 0xf4) {
continuation = 3;
if (first == 0xf0) second_min = 0x90;
if (first == 0xf4) second_max = 0x8f;
} else return false;
if (continuation > length - i || text[i] < second_min || text[i] > second_max) return false;
++i;
while (--continuation) {
if (text[i] < 0x80 || text[i] > 0xbf) return false;
++i;
}
}
if (scalar_count != nullptr) *scalar_count = scalars;
return true;
}
bool validText(const uint8_t* text, size_t length) {
return length != 0 && validUtf8(text, length, MaxTextSize);
}
template <class Cipher>
bool crypt(const uint8_t* key, size_t key_len, uint32_t id, uint32_t from,
uint8_t* data, size_t length) {
Cipher cipher;
if (!cipher.setKey(key, key_len)) return false;
// Initial counter is packet ID as LE64 followed by sender as LE64. The
// standard CTR counter increment is big-endian across the entire block.
uint8_t counter[16] = {}, stream[16];
put32(counter, id);
put32(counter + 8, from);
for (size_t offset = 0; offset < length;) {
cipher.encryptBlock(stream, counter);
for (int i = 15; i >= 0; --i) if (++counter[i] != 0) break;
size_t block = length - offset;
if (block > sizeof(stream)) block = sizeof(stream);
for (size_t i = 0; i < block; ++i) data[offset + i] ^= stream[i];
offset += block;
}
cipher.clear();
erase(counter, sizeof(counter));
erase(stream, sizeof(stream));
return true;
}
bool cryptPayload(const uint8_t* key, size_t key_len, uint32_t id, uint32_t from,
uint8_t* data, size_t length) {
if (key_len == 16) return crypt<AES128>(key, key_len, id, from, data, length);
if (key_len == 32) return crypt<AES256>(key, key_len, id, from, data, length);
return false;
}
size_t finishFrame(uint32_t from, uint32_t id, uint8_t hop_limit, const char* channel_name,
const uint8_t* key, size_t key_len, uint8_t* out, size_t data_size) {
if (!cryptPayload(key, key_len, id, from, out + HeaderSize, data_size)) return 0;
put32(out, Broadcast); put32(out + 4, from); put32(out + 8, id);
out[12] = hop_limit | (hop_limit << 5);
out[13] = channelHash(channel_name, key, key_len);
out[14] = out[15] = 0;
return HeaderSize + data_size;
}
struct Reader {
const uint8_t* data;
size_t size, pos = 0;
Reader(const uint8_t* input, size_t length) : data(input), size(length) {}
bool varint(uint64_t& value) {
value = 0;
for (unsigned i = 0; i < 10 && pos < size; ++i) {
const uint8_t byte = data[pos++];
if (i == 9 && (byte & 0xfe) != 0) return false;
value |= uint64_t(byte & 0x7f) << (7 * i);
if ((byte & 0x80) == 0) return i == 0 || byte != 0;
}
return false;
}
bool bytes(const uint8_t*& out, size_t& length) {
uint64_t count;
if (!varint(count) || count > size - pos) return false;
length = static_cast<size_t>(count); out = data + pos; pos += length;
return true;
}
bool fixed32(uint32_t& value) {
if (size - pos < 4) return false;
value = get32(data + pos); pos += 4; return true;
}
bool skip(uint8_t wire) {
uint64_t ignored;
const uint8_t* bytes_;
size_t count;
if (wire == 0) return varint(ignored);
if (wire == 2) return bytes(bytes_, count);
count = wire == 1 ? 8 : wire == 5 ? 4 : 0;
if (count == 0 || count > size - pos) return false;
pos += count; return true;
}
};
bool textData(const uint8_t* data, size_t size, const uint8_t*& text, size_t& text_len) {
Reader reader(data, size);
bool have_port = false, have_text = false;
while (reader.pos < reader.size) {
uint64_t tag, value;
if (!reader.varint(tag) || tag < 8 || tag > 0xffffffffULL) return false;
const uint32_t field = static_cast<uint32_t>(tag >> 3);
const uint8_t wire = tag & 7;
if (field == 1) {
if (have_port || wire != 0 || !reader.varint(value) || value != 1) return false;
have_port = true; // TEXT_MESSAGE_APP
} else if (field == 2) {
if (have_text || wire != 2 || !reader.bytes(text, text_len)) return false;
have_text = true;
} else if (field == 3) {
// A received request does not cause any response in this text-only engine.
if (wire != 0 || !reader.varint(value) || value > 1) return false;
} else if (field >= 4 && field <= 8) {
uint32_t fixed;
if (wire != 5 || !reader.fixed32(fixed)) return false;
if (field == 4 && fixed != 0 && fixed != Broadcast) return false;
} else if (!reader.skip(wire)) return false;
}
return have_port && have_text && validText(text, text_len);
}
} // namespace
bool parsePreset(const char* name, Preset& preset) {
if (name == nullptr) return false;
for (const auto& entry : Presets) {
if (equalPresetName(entry.name, name)) { preset = entry.preset; return true; }
}
if (equalPresetName(name, "LongModerate")) { preset = Preset::LongModerate; return true; }
return false;
}
const char* presetName(Preset preset) {
const auto info = presetInfo(preset);
return info == nullptr ? nullptr : info->name;
}
bool modemConfig(Region region, Preset preset, RadioProfileParams& params, uint32_t slot) {
const auto info = presetInfo(preset);
if (info == nullptr) return false;
uint32_t start, end;
switch (region) {
case Region::US: start = 902000000; end = 928000000; break;
case Region::EU868: start = 869400000; end = 869650000; break;
case Region::EU433: start = 433000000; end = 434000000; break;
case Region::ANZ: start = 915000000; end = 928000000; break;
default: return false;
}
if (info->bandwidth > end - start) return false;
const uint32_t slots = (end - start) / info->bandwidth;
if (slot > slots) return false;
const uint32_t index = slot == 0 ? nameHash(info->name) % slots : slot - 1;
RadioProfileParams result;
result.freq = (start + info->bandwidth / 2 + index * info->bandwidth) / 1000000.0f;
result.bw = info->bandwidth / 1000.0f;
result.sf = info->sf; result.cr = info->cr; result.preamble = 16;
result.protocol = RadioProfileProtocol::Meshtext;
params = result;
return true;
}
size_t encodeText(uint32_t from, uint32_t id, uint8_t hop_limit, const char* channel_name,
const uint8_t* key, size_t key_len, const char* text, size_t text_len,
uint8_t out[MaxFrameSize]) {
if (out == nullptr || key == nullptr || (key_len != 16 && key_len != 32)
|| !validName(channel_name) || from == 0 || from == Broadcast || id == 0 || hop_limit > 7
|| !validText(reinterpret_cast<const uint8_t*>(text), text_len)) return 0;
uint8_t* data = out + HeaderSize;
size_t count = 0;
data[count++] = 0x08; data[count++] = 1; // Data.portnum = TEXT_MESSAGE_APP
data[count++] = 0x12; // Data.payload
if (text_len >= 128) data[count++] = static_cast<uint8_t>(text_len) | 0x80;
data[count++] = static_cast<uint8_t>(text_len >> (text_len >= 128 ? 7 : 0));
memcpy(data + count, text, text_len); count += text_len;
return finishFrame(from, id, hop_limit, channel_name, key, key_len, out, count);
}
size_t encodeNodeInfo(uint32_t from, uint32_t id, uint8_t hop_limit, const char* channel_name,
const uint8_t* key, size_t key_len, const char* long_name, size_t long_name_len,
const char* short_name, size_t short_name_len, uint8_t out[MaxFrameSize]) {
size_t short_characters = 0;
if (out == nullptr || key == nullptr || (key_len != 16 && key_len != 32)
|| !validName(channel_name) || from <= 3 || from == Broadcast || id == 0 || hop_limit > 7
|| !validUtf8(reinterpret_cast<const uint8_t*>(long_name), long_name_len, MaxLongNameSize)
|| short_name_len == 0
|| !validUtf8(reinterpret_cast<const uint8_t*>(short_name), short_name_len,
MaxShortNameSize, &short_characters)
|| short_characters > MaxShortNameCharacters) return 0;
// Handwritten standard protobuf wire fields, not generated schema code.
// User: id=1, long_name=2, short_name=3, role=7, is_unmessagable=9.
// All individual strings and the complete User payload fit one-byte lengths.
static_assert(11 + 2 + MaxLongNameSize + 2 + MaxShortNameSize + 4 < 128,
"NodeInfo requires bounded one-byte protobuf lengths");
static const char Hex[] = "0123456789abcdef";
uint8_t* data = out + HeaderSize;
size_t count = 0;
data[count++] = 0x08; data[count++] = 4; // Data.portnum = NODEINFO_APP.
data[count++] = 0x12; data[count++] = 0; // Data.payload length set below.
data[count++] = 0x0a; data[count++] = 9; data[count++] = '!';
for (unsigned i = 0; i < 8; ++i) data[count++] = Hex[(from >> (28 - 4 * i)) & 15];
if (long_name_len != 0) {
data[count++] = 0x12; data[count++] = static_cast<uint8_t>(long_name_len);
memcpy(data + count, long_name, long_name_len); count += long_name_len;
}
data[count++] = 0x1a; data[count++] = static_cast<uint8_t>(short_name_len);
memcpy(data + count, short_name, short_name_len); count += short_name_len;
data[count++] = 0x38; data[count++] = 1; // Config.DeviceConfig.Role.CLIENT_MUTE.
data[count++] = 0x48; data[count++] = 1; // User.is_unmessagable explicitly true.
data[3] = static_cast<uint8_t>(count - 4);
return finishFrame(from, id, hop_limit, channel_name, key, key_len, out, count);
}
bool decodeText(const uint8_t* raw, size_t length, const char* channel_name,
const uint8_t* key, size_t key_len, uint32_t local_node, DecodedText& decoded) {
if (raw == nullptr || key == nullptr || (key_len != 16 && key_len != 32)
|| !validName(channel_name) || length <= HeaderSize || length > HeaderSize + MaxDataSize
|| get32(raw) != Broadcast || raw[13] != channelHash(channel_name, key, key_len)) return false;
const uint32_t from = get32(raw + 4), id = get32(raw + 8);
if (from == 0 || from == Broadcast || from == local_node || id == 0) return false;
uint8_t data[MaxDataSize];
const size_t data_size = length - HeaderSize;
memcpy(data, raw + HeaderSize, data_size);
if (!cryptPayload(key, key_len, id, from, data, data_size)) {
erase(data, data_size); return false;
}
const uint8_t* text = nullptr;
size_t text_len = 0;
const bool valid = textData(data, data_size, text, text_len);
if (valid) {
decoded.from = from; decoded.id = id;
decoded.hop_limit = raw[12] & 7; decoded.hop_start = raw[12] >> 5;
decoded.hops = decoded.hop_start >= decoded.hop_limit ? decoded.hop_start - decoded.hop_limit : 0;
decoded.text_len = static_cast<uint16_t>(text_len);
memcpy(decoded.text, text, text_len); decoded.text[text_len] = 0;
}
erase(data, data_size);
return valid;
}
bool SeenPackets::seen(uint32_t from, uint32_t id) const {
if (from == 0 || from == Broadcast || id == 0) return false;
for (const auto& entry : entries_) if (entry.from == from && entry.id == id) return true;
return false;
}
bool SeenPackets::remember(uint32_t from, uint32_t id) {
if (from == 0 || from == Broadcast || id == 0 || seen(from, id)) return false;
entries_[next_].from = from; entries_[next_].id = id;
next_ = (next_ + 1) % Capacity;
return true;
}
void SeenPackets::clear() {
for (auto& entry : entries_) { entry.from = 0; entry.id = 0; }
next_ = 0;
}
} // namespace mt
} // namespace mesh
#endif // MESH_ENABLE_MESHTEXT_CHAT
+82
View File
@@ -0,0 +1,82 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <RadioProfiles.h>
#include "MeshtextConfig.h"
// Bounded adaptation of MIT-licensed esp-cpp/espp wire helpers.
// See licenses/ESPP-Meshtext-MIT.txt for the pinned source and license.
// Meshtext is a bounded text interoperability component, not a peer firmware fork.
// NodeInfo may only be explicitly encoded; received NodeInfo stays ignored.
namespace mesh {
namespace mt {
enum class Region : uint8_t { Unset, US, EU868, EU433, ANZ };
enum class Preset : uint8_t {
ShortTurbo, ShortFast, ShortSlow, MediumTurbo, MediumFast, MediumSlow,
LongTurbo, LongFast, LongModerate, LongSlow
};
// ASCII case-insensitive alias parsing; wire/default names retain stock case.
bool parsePreset(const char* name, Preset& preset);
// The stock default channel name; LongModerate uses "LongMod".
const char* presetName(Preset preset);
// freq is MHz, bw is kHz; slot is 1-based, or 0 for the preset-name hash.
// Invalid regions/presets/slots are rejected, leaving params unchanged.
bool modemConfig(Region region, Preset preset, RadioProfileParams& params, uint32_t slot = 0);
static constexpr size_t HeaderSize = 16;
static constexpr size_t MaxFrameSize = 255;
static constexpr size_t MaxDataSize = 233;
static constexpr size_t MaxTextSize = 228; // Data port + payload tag/length overhead.
static constexpr size_t MaxLongNameSize = 24; // Current stock User.long_name bound.
static constexpr size_t MaxShortNameSize = 4; // Stock max_size:5 includes NUL.
static constexpr size_t MaxShortNameCharacters = 4; // Unicode scalar values.
extern const uint8_t DefaultPsk[16]; // Expanded AQ== public key; never a hashtag hash.
struct DecodedText {
uint32_t from = 0, id = 0;
uint8_t hops = 0, hop_limit = 0, hop_start = 0;
uint16_t text_len = 0;
char text[MaxTextSize + 1] = {};
};
// Expanded AES-128/256 PSK only. No unencrypted-key fallback. Names are exact,
// canonical peer channel names (<12 bytes), without local display markers.
// Returns 0 for invalid arguments, malformed UTF-8, embedded NUL or overflow.
size_t encodeText(uint32_t from, uint32_t id, uint8_t hop_limit, const char* channel_name,
const uint8_t* key, size_t key_len, const char* text, size_t text_len,
uint8_t out[MaxFrameSize]);
// Explicit broadcast NODEINFO_APP containing only User id, long/short names,
// CLIENT_MUTE (no forwarding), and is_unmessagable=true (no direct messages).
// Names use explicit UTF-8 byte lengths, without their terminating NUL. Long
// names may be empty; short names require 1..4 UTF-8 bytes (stock wire bound).
// This can hold four ASCII characters but fewer multi-byte characters. Longer
// names are rejected, not byte-truncated. No MAC, PSK, public key or MC identity
// is copied. No ACK/response is requested and no automatic send is performed.
size_t encodeNodeInfo(uint32_t from, uint32_t id, uint8_t hop_limit, const char* channel_name,
const uint8_t* key, size_t key_len, const char* long_name, size_t long_name_len,
const char* short_name, size_t short_name_len, uint8_t out[MaxFrameSize]);
// Only broadcast TEXT_MESSAGE_APP is delivered. No DMs, ACKs, administrative
// handling, relaying or automatic transmissions. AES-CTR is not authenticated;
// a successful parse is not a proof of sender identity or PSK authenticity.
// On failure, decoded is left unchanged. Caller records dedup only on success.
bool decodeText(const uint8_t* raw, size_t length, const char* channel_name,
const uint8_t* key, size_t key_len, uint32_t local_node, DecodedText& decoded);
// Shared across channel slots. Packet IDs must never be reused with one sender
// and PSK (CTR nonce reuse). Call remember only after valid RX or successful TX.
class SeenPackets {
public:
static constexpr size_t Capacity = 32;
bool seen(uint32_t from, uint32_t id) const;
bool remember(uint32_t from, uint32_t id); // false for duplicate/invalid pair
void clear();
private:
struct Entry { uint32_t from = 0, id = 0; } entries_[Capacity];
uint8_t next_ = 0;
};
} // namespace mt
} // namespace mesh
+22
View File
@@ -0,0 +1,22 @@
#pragma once
// Resolve the chip in every translation unit, including Dispatcher.cpp which
// includes this before Arduino.h. Otherwise different class layouts could be
// selected for the same build depending on include order.
#if !defined(MESH_ENABLE_MESHTEXT_CHAT) && defined(ESP32_PLATFORM) && defined(ARDUINO)
#include <sdkconfig.h>
#endif
// Channel chat is an optional Companion transport, never a bridge. Start with
// the roomy ESP32-S3 Full/SX1262 family; other builds retain every existing
// feature and do not acquire the codec or its bounded raw-frame queue. A new
// family must qualify its modem implementation, flash and runtime RAM first.
#ifndef MESH_ENABLE_MESHTEXT_CHAT
#if defined(ESP32_PLATFORM) && defined(CONFIG_IDF_TARGET_ESP32S3) \
&& defined(COMPANION_RADIO_FULL) && defined(USE_SX1262) \
&& !(defined(MESH_PRIMARY_ESPNOW) && MESH_PRIMARY_ESPNOW)
#define MESH_ENABLE_MESHTEXT_CHAT 1
#else
#define MESH_ENABLE_MESHTEXT_CHAT 0
#endif
#endif
+232 -18
View File
@@ -95,7 +95,7 @@ RadioProfileCLI::ImageReadResult RadioProfileCLI::readImage(
if (!read_complete) return ImageReadResult::Unreadable;
uint32_t stored;
memcpy(&stored, bytes + size - 4, 4);
return bytes[0] == 'R' && bytes[1] == '2' && bytes[2] == 1
return bytes[0] == 'R' && bytes[1] == '2' && (bytes[2] == 1 || bytes[2] == 2)
&& stored == checksum(bytes, size - 4)
? ImageReadResult::Valid : ImageReadResult::Invalid;
}
@@ -119,9 +119,10 @@ bool RadioProfileCLI::writeImage(const char* path, const uint8_t* bytes, size_t
&& memcmp(bytes, verify, size) == 0;
}
bool RadioProfileCLI::save(const RadioProfileConfig& config, uint16_t preamble, RadioCrossMode cross) {
bool RadioProfileCLI::save(const RadioProfileConfig& config, uint16_t preamble, RadioCrossMode cross,
int8_t manual_secondary) {
if (!discardCorruptSavedImagesForWrite()) return false;
return prepareSavedImage(TempPath, config, preamble, cross) && commitSavedImage(TempPath);
return prepareSavedImage(TempPath, config, preamble, cross, manual_secondary) && commitSavedImage(TempPath);
}
bool RadioProfileCLI::discardCorruptSavedImagesForWrite() {
@@ -143,9 +144,18 @@ bool RadioProfileCLI::discardCorruptSavedImagesForWrite() {
}
bool RadioProfileCLI::prepareSavedImage(const char* path, const RadioProfileConfig& config,
uint16_t preamble, RadioCrossMode cross) {
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
// 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;
const bool manual = manual_secondary < 0 ? manual_secondary_ : manual_secondary != 0;
if (manual || config.mode != RadioProfileMode::Off) image[3] |= 0x80;
#else
(void)manual_secondary;
#endif
memcpy(image + 4, &config.params.freq, 4);
memcpy(image + 8, &config.params.bw, 4);
image[12] = config.params.sf; image[13] = config.params.cr;
@@ -176,6 +186,12 @@ void RadioProfileCLI::begin(FILESYSTEM* fs, Radio* radio, RTCClock* rtc, bool in
fs_ = fs; radio_ = radio; rtc_ = rtc; last_ms_ = millis();
hold_ = false;
recoverable_corrupt_store_ = false;
manual_secondary_ = false;
secondary_intent_generation_ = 0;
#if MESH_ENABLE_MESHTEXT_CHAT
auto_secondary_requested_ = secondary_protocol_overlay_ = false;
owns_secondary_runtime_ = external_secondary_override_ = false;
#endif
infrastructure_replies_ = infrastructure_replies;
if (radio_ && radio_->profiles()) {
radio_->profiles()->reply_tx = infrastructure_replies ? RADIO_TX_BOTH : RADIO_TX_AUTO;
@@ -206,7 +222,10 @@ void RadioProfileCLI::begin(FILESYSTEM* fs, Radio* radio, RTCClock* rtc, bool in
|| backup_image == ImageReadResult::Invalid);
return;
}
saved_.mode = (RadioProfileMode)bytes[3];
// Legacy Off is ambiguous: preserve it as deliberate manual intent rather
// than allowing a newly installed automatic feature to turn the radio on.
manual_secondary_ = bytes[2] == 1 || (bytes[3] & 0x80) != 0;
saved_.mode = (RadioProfileMode)(bytes[2] == 2 ? bytes[3] & 0x7F : bytes[3]);
memcpy(&saved_.params.freq, bytes + 4, 4);
memcpy(&saved_.params.bw, bytes + 8, 4);
saved_.params.sf = bytes[12]; saved_.params.cr = bytes[13];
@@ -215,6 +234,7 @@ void RadioProfileCLI::begin(FILESYSTEM* fs, Radio* radio, RTCClock* rtc, bool in
cross_ = (RadioCrossMode)bytes[18];
reply_setting_ = validReplySetting(bytes[19]) ? bytes[19] : 0;
if ((uint8_t)saved_.mode > 2 || (uint8_t)cross_ > 2
|| (bytes[2] == 2 && saved_.mode != RadioProfileMode::Off && !manual_secondary_)
|| (saved_.mode != RadioProfileMode::Off && !radio_->validateProfile(saved_.params))
|| (primary_preamble_ && (primary_preamble_ < 8 || primary_preamble_ > RadioProfiles::MaxPreamble))) {
// A CRC-valid image can still be semantically stale (for example, after
@@ -257,9 +277,160 @@ 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
protectExternalSecondary();
if (external_secondary_override_) return;
#endif
if (publish_pending_ && (int32_t)(millis() - publish_after_ms_) < 0) return;
#if MESH_ENABLE_MESHTEXT_CHAT
// 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;
radio_->profiles()->setSecondary(temp_active_ ? temporary_ : saved_, temp_active_);
RadioProfileConfig config = temp_active_ ? temporary_ : saved_;
#if MESH_ENABLE_MESHTEXT_CHAT
if (auto_secondary_requested_ && canAutoSecondary()) config = auto_secondary_;
else if (secondary_protocol_overlay_ && manualSecondaryConfigured() && !secondaryRuntimeBusy()) {
config.params.protocol = secondary_protocol_;
if (secondary_protocol_ == RadioProfileProtocol::Meshtext) config.params.preamble = 16;
}
#endif
radio_->profiles()->setSecondary(config, temp_active_);
#if MESH_ENABLE_MESHTEXT_CHAT
owns_secondary_runtime_ = auto_secondary_requested_ || secondary_protocol_overlay_;
if (owns_secondary_runtime_) {
owned_secondary_snapshot_ = config;
owned_secondary_generation_ = radio_->profiles()->generation[1];
}
#endif
}
#if MESH_ENABLE_MESHTEXT_CHAT
bool RadioProfileCLI::runtimeSecondaryUnchanged() const {
if (!owns_secondary_runtime_ || !radio_ || !radio_->profiles()) return true;
const auto* profiles = radio_->profiles();
return profiles->generation[1] == owned_secondary_generation_
&& profiles->secondary.mode == owned_secondary_snapshot_.mode
&& profiles->secondary.params == owned_secondary_snapshot_.params;
}
void RadioProfileCLI::protectExternalSecondary() {
if (runtimeSecondaryUnchanged()) return;
// Another owner changed the running tuple without a CLI mutation. Relinquish
// our RAM layer without restoring Off over that owner's settings, now or on
// later loop publications. An explicit CLI change can claim ownership back.
external_secondary_override_ = true;
owns_secondary_runtime_ = auto_secondary_requested_ = secondary_protocol_overlay_ = false;
}
#endif
bool RadioProfileCLI::hasSecondarySchedule() const {
for (const auto& schedule : schedules_) if (schedule.active) return true;
return false;
}
bool RadioProfileCLI::secondaryRuntimeBusy() const {
#if MESH_ENABLE_MESHTEXT_CHAT
if (external_secondary_override_ || !runtimeSecondaryUnchanged()) return true;
#endif
return !fs_ || !radio_ || !radio_->profiles() || hold_ || temp_pending_ || temp_active_
|| publish_pending_ || hasReplyMutation() || hasSecondarySchedule()
|| radio_->profiles()->primary_temporary || radio_->profiles()->secondary_temporary;
}
void RadioProfileCLI::noteSecondaryManualChange() {
++secondary_intent_generation_;
#if MESH_ENABLE_MESHTEXT_CHAT
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 (manual_secondary_ || saved_.mode != RadioProfileMode::Off || secondaryRuntimeBusy()) return false;
const auto& current = radio_->profiles()->secondary;
return current.mode == RadioProfileMode::Off || (auto_secondary_requested_
&& current.mode == auto_secondary_.mode && current.params == auto_secondary_.params);
#else
return false;
#endif
}
bool RadioProfileCLI::requestAutoSecondary(const RadioProfileConfig& config) {
#if MESH_ENABLE_MESHTEXT_CHAT
if (!canAutoSecondary() || config.mode == RadioProfileMode::Off
|| (uint8_t)config.mode > (uint8_t)RadioProfileMode::RxTx
|| !radio_->validateProfile(config.params)) return false;
if (auto_secondary_requested_ && (config.mode != auto_secondary_.mode
|| config.params != auto_secondary_.params)) return false;
auto preview = *radio_->profiles();
preview.setSecondary(config, false);
if (!preview.automaticPreambleFits()) return false;
auto_secondary_ = config;
auto_secondary_requested_ = true;
publish();
return autoSecondaryActive();
#else
(void)config;
return false;
#endif
}
void RadioProfileCLI::clearAutoSecondary() {
#if MESH_ENABLE_MESHTEXT_CHAT
if (!auto_secondary_requested_) return;
protectExternalSecondary();
auto_secondary_requested_ = false;
owns_secondary_runtime_ = secondary_protocol_overlay_;
publish();
#endif
}
bool RadioProfileCLI::autoSecondaryActive() const {
#if MESH_ENABLE_MESHTEXT_CHAT
if (!auto_secondary_requested_ || !canAutoSecondary()) return false;
const auto& current = radio_->profiles()->secondary;
return !radio_->profiles()->secondary_temporary && current.mode == auto_secondary_.mode
&& current.params == auto_secondary_.params;
#else
return false;
#endif
}
bool RadioProfileCLI::useSecondaryProtocol(RadioProfileProtocol protocol) {
#if MESH_ENABLE_MESHTEXT_CHAT
if (protocol == RadioProfileProtocol::MeshCore) {
clearSecondaryProtocol();
return true;
}
if (protocol != RadioProfileProtocol::Meshtext || !manualSecondaryConfigured()
|| secondaryRuntimeBusy()) return false;
auto preview = *radio_->profiles();
auto config = saved_;
config.params.protocol = protocol;
config.params.preamble = 16;
preview.setSecondary(config, false);
if (!radio_->validateProfile(config.params) || !preview.automaticPreambleFits()) return false;
secondary_protocol_ = protocol;
secondary_protocol_overlay_ = true;
publish();
return true;
#else
(void)protocol;
return false;
#endif
}
void RadioProfileCLI::clearSecondaryProtocol() {
#if MESH_ENABLE_MESHTEXT_CHAT
if (!secondary_protocol_overlay_) return;
protectExternalSecondary();
secondary_protocol_overlay_ = false;
owns_secondary_runtime_ = auto_secondary_requested_;
publish();
#endif
}
bool RadioProfileCLI::stageRemoteMutation(RemoteMutation kind, const RadioProfileConfig& config,
@@ -308,6 +479,7 @@ bool RadioProfileCLI::applyReplyMutation() {
remote_mutation_ = RemoteMutation::None;
remote_delivered_ = false;
if (kind == RemoteMutation::None) return true;
noteSecondaryManualChange();
if (kind == RemoteMutation::Temporary) {
pending_temporary_ = remote_config_;
pending_duration_ms_ = remote_duration_ms_;
@@ -315,6 +487,7 @@ bool RadioProfileCLI::applyReplyMutation() {
temp_pending_ = true;
} else if (kind == RemoteMutation::Saved) {
saved_ = remote_config_;
manual_secondary_ = true;
publish_pending_ = true; publish_after_ms_ = millis();
#if MESH_ENABLE_FLEET_CONTROL
} else if (kind == RemoteMutation::AddSavedSchedule
@@ -348,7 +521,7 @@ bool RadioProfileCLI::applyReplyMutation() {
schedule_retry_ms_ = 0;
#endif
} else {
if (kind == RemoteMutation::Off) { saved_ = {}; schedule_retry_ms_ = 0; }
if (kind == RemoteMutation::Off) { saved_ = {}; manual_secondary_ = true; schedule_retry_ms_ = 0; }
temp_pending_ = temp_active_ = false; temp_remaining_ms_ = 0;
for (auto& s : schedules_) if (kind == RemoteMutation::Off || s.temporary) s = {};
}
@@ -393,13 +566,13 @@ void RadioProfileCLI::loop() {
if (s.active && !s.temporary && epoch >= s.start && (!next || s.start < next->start)) next = &s;
}
if (!next) break;
if (!save(next->config, primary_preamble_, cross_)) {
if (!save(next->config, primary_preamble_, cross_, true)) {
// Keep the requested time and order intact. A failed earlier entry must
// not be retried after a later one and overwrite the newer settings.
schedule_retry_ms_ = 60000;
break;
}
saved_ = next->config; *next = {};
saved_ = next->config; manual_secondary_ = true; noteSecondaryManualChange(); *next = {};
}
for (auto& s : schedules_) {
if (!s.active || !s.temporary || s.started || epoch < s.start || temp_active_ || temp_pending_ || hasReplyMutation()) continue;
@@ -487,14 +660,14 @@ void RadioProfileCLI::appendChirpWarning(char* reply, size_t capacity, const Rad
}
void RadioProfileCLI::formatConfig(char* reply, size_t capacity, const RadioProfileConfig& config,
bool temporary, uint32_t remaining) const {
bool temporary, uint32_t remaining, bool automatic) const {
if (config.mode == RadioProfileMode::Off) { snprintf(reply, capacity, "> off"); return; }
RadioProfiles preview = *radio_->profiles();
preview.setSecondary(config, temporary);
uint16_t preamble = preview.preamble(1, 32);
snprintf(reply, capacity, "> %.3f,%.3f,%u,%u,%s,%u%s", config.params.freq, config.params.bw,
snprintf(reply, capacity, "> %.3f,%.3f,%u,%u,%s,%u%s%s", config.params.freq, config.params.bw,
config.params.sf, config.params.cr, modeName(config.mode), preamble,
config.params.preamble ? "" : " (auto)");
config.params.preamble ? "" : " (auto)", automatic ? "; auto-owned" : "");
if (temporary) {
uint32_t minutes = (remaining + 59999UL) / 60000UL;
const size_t used = strlen(reply);
@@ -643,14 +816,45 @@ 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 (base && autoSecondaryActive()) {
formatConfig(reply, capacity, auto_secondary_, false, 0, true);
return true;
}
if (base && saved_.mode == RadioProfileMode::Off) {
snprintf(reply, capacity, "> off (%s)", manual_secondary_ ? "manual" : "automatic allowed");
return true;
}
#endif
if (temporary && !temp_active_ && !temp_pending_) snprintf(reply, capacity, "> off");
else formatConfig(reply, capacity, temporary ? (temp_pending_ ? pending_temporary_ : temporary_) : saved_,
temporary, temp_pending_ ? pending_duration_ms_ : temp_remaining_ms_);
return true;
}
#if MESH_ENABLE_MESHTEXT_CHAT
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.
if (remote_command_ || temp_pending_ || temp_active_ || hasSecondarySchedule()
|| hasReplyMutation() || publish_pending_ || radio_->profiles()->primary_temporary
|| radio_->profiles()->secondary_temporary) {
snprintf(reply, capacity, "Error: automatic radio2 requires no pending change, lease or schedule");
return true;
}
if (!save({}, primary_preamble_, cross_, 0)) {
snprintf(reply, capacity, "Error: settings could not be saved"); return true;
}
noteSecondaryManualChange();
saved_ = {}; manual_secondary_ = false;
publish_pending_ = true; publish_after_ms_ = millis() + 2000;
publish();
snprintf(reply, capacity, "OK - automatic radio2 permitted in 2s");
return true;
}
#endif
if ((base || temporary) && verb == Set && !strcmp(args, "off")) {
if (base && !(remote_command_ ? prepareSavedImage(ReplyPath, {}, primary_preamble_, cross_)
: save({}, primary_preamble_, cross_))) {
if (base && !(remote_command_ ? prepareSavedImage(ReplyPath, {}, primary_preamble_, cross_, true)
: save({}, primary_preamble_, cross_, true))) {
snprintf(reply, capacity, "Error: settings could not be saved"); return true;
}
if (remote_command_) {
@@ -659,7 +863,8 @@ bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity,
? "saved radio2 restored" : "single radio");
return true;
}
if (base) { saved_ = {}; schedule_retry_ms_ = 0; }
noteSecondaryManualChange();
if (base) { saved_ = {}; manual_secondary_ = true; schedule_retry_ms_ = 0; }
temp_pending_ = temp_active_ = false; temp_remaining_ms_ = 0;
for (auto& s : schedules_) if (base || s.temporary) s = {};
publish_pending_ = true; publish_after_ms_ = millis() + 2000;
@@ -691,6 +896,7 @@ bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity,
}
schedules_[first+i] = {};
}
noteSecondaryManualChange();
publish(); snprintf(reply, capacity, "OK"); return true;
}
if (!index) {
@@ -767,7 +973,9 @@ bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity,
if (!stageRemoteSchedule(i, s)) {
snprintf(reply, capacity, "Error: radio acknowledgement pending"); return true;
}
} else schedules_[first+i] = s;
} else { schedules_[first+i] = s; noteSecondaryManualChange(); publish(); }
#else
noteSecondaryManualChange(); publish();
#endif
snprintf(reply, capacity, "OK - %s %u queued, preamble=%u", key, i+1, preview.preamble(1, 32));
appendChirpWarning(reply, capacity, preview); return true;
@@ -780,18 +988,24 @@ bool RadioProfileCLI::handle(const char* command, char* reply, size_t capacity,
}
if (remote_command_) stageRemoteMutation(RemoteMutation::Temporary, config, minutes * 60000UL);
else {
noteSecondaryManualChange();
pending_temporary_ = config; pending_duration_ms_ = minutes * 60000UL;
temp_start_ms_ = millis() + 2000; temp_pending_ = true;
#if MESH_ENABLE_MESHTEXT_CHAT
publish_pending_ = true; publish_after_ms_ = temp_start_ms_;
#endif
}
// An existing session remains active until the new request can take over.
snprintf(reply, capacity, "OK - tempradio2 %lud%luh%lum (%lu min); preamble=%u",
(unsigned long)(minutes/1440), (unsigned long)(minutes/60%24),
(unsigned long)(minutes%60), (unsigned long)minutes, preview.preamble(1, 32));
} else if (remote_command_ ? prepareSavedImage(ReplyPath, config, primary_preamble_, cross_)
: save(config, primary_preamble_, cross_)) {
} else if (remote_command_ ? prepareSavedImage(ReplyPath, config, primary_preamble_, cross_, true)
: save(config, primary_preamble_, cross_, true)) {
if (remote_command_) stageRemoteMutation(RemoteMutation::Saved, config);
else {
noteSecondaryManualChange();
saved_ = config;
manual_secondary_ = true;
publish_pending_ = true; publish_after_ms_ = millis() + 2000;
publish();
}
+35 -3
View File
@@ -4,6 +4,7 @@
#include <helpers/IdentityStore.h>
#include <helpers/CLICommandUtils.h>
#include <helpers/FleetControlConfig.h>
#include <helpers/MeshtextConfig.h>
namespace mesh {
@@ -28,6 +29,20 @@ class RadioProfileCLI {
RadioCrossMode cross_ = RadioCrossMode::Auto;
uint8_t reply_setting_ = 0; // reserved image byte: 0 = role default
bool infrastructure_replies_ = false;
// 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
RadioProfileConfig auto_secondary_;
bool auto_secondary_requested_ = false;
bool secondary_protocol_overlay_ = false;
RadioProfileProtocol secondary_protocol_ = RadioProfileProtocol::MeshCore;
RadioProfileConfig owned_secondary_snapshot_;
uint32_t owned_secondary_generation_ = 0;
bool owns_secondary_runtime_ = false, external_secondary_override_ = false;
bool runtimeSecondaryUnchanged() const;
void protectExternalSecondary();
#endif
Schedule schedules_[8];
uint32_t temp_remaining_ms_ = 0;
uint32_t temp_start_ms_ = 0;
@@ -63,17 +78,21 @@ class RadioProfileCLI {
#if MESH_ENABLE_FLEET_CONTROL
bool stageRemoteSchedule(unsigned slot, const Schedule& schedule);
#endif
bool save(const RadioProfileConfig& config, uint16_t preamble, RadioCrossMode cross);
bool save(const RadioProfileConfig& config, uint16_t preamble, RadioCrossMode cross,
int8_t manual_secondary = -1);
bool prepareSavedImage(const char* path, const RadioProfileConfig& config,
uint16_t preamble, RadioCrossMode cross);
uint16_t preamble, RadioCrossMode cross, int8_t manual_secondary = -1);
bool commitSavedImage(const char* path);
bool discardCorruptSavedImagesForWrite();
bool applyReplyMutation();
ImageReadResult readImage(const char* path, uint8_t* bytes, size_t size);
bool writeImage(const char* path, const uint8_t* bytes, size_t size);
void publish();
bool hasSecondarySchedule() const;
bool secondaryRuntimeBusy() const;
void noteSecondaryManualChange();
void formatConfig(char* reply, size_t capacity, const RadioProfileConfig& config,
bool temporary, uint32_t remaining_ms) const;
bool temporary, uint32_t remaining_ms, bool automatic = false) const;
public:
void begin(FILESYSTEM* fs, Radio* radio, RTCClock* rtc, bool infrastructure_replies = false);
void loop();
@@ -85,6 +104,19 @@ class RadioProfileCLI {
bool hasReplyMutation() const { return remote_mutation_ != RemoteMutation::None; }
uint32_t replyMutationGeneration() const { return remote_generation_; }
bool finishReplyMutation(bool delivered);
// Channel-derived RF settings are RAM-only and never replace explicit saved
// settings (including Off). Repeated identical requests do not retune.
bool requestAutoSecondary(const RadioProfileConfig& config);
void clearAutoSecondary();
bool autoSecondaryActive() const;
bool canAutoSecondary() const;
// 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);
void clearSecondaryProtocol();
bool manualSecondaryConfigured() const { return manual_secondary_ && saved_.mode != RadioProfileMode::Off; }
const RadioProfileConfig& savedSecondaryConfig() const { return saved_; }
uint32_t secondaryIntentGeneration() const { return secondary_intent_generation_; }
uint16_t primaryPreamble() const { return primary_preamble_; }
// Infrastructure owns a newer, atomic primary tuple in /com_prefs. Adopting
// its committed value changes saved intent only, never the running radio.
+31
View File
@@ -155,6 +155,37 @@ class CustomSX1262 : public SX1262 {
return SX1262::invertIQ(enable);
}
// MeshCore and Meshtext share CRC-on, explicit-header, normal-IQ LoRa
// packet settings. Only an acknowledged owned RX-to-RX hop may stage
// these fields: startReceive() then commits one complete packet tuple,
// including RadioLib's fixInvertedIQ register workaround, before SetRx.
// Ordinary setup/TX/CAD/sleep/recovery retains the normal setter path.
int16_t setProfileProtocol(uint8_t syncWord) {
const bool stage = _profileSwitch.canResumeFast();
const int16_t rc = SX1262::setSyncWord(syncWord);
if (rc != RADIOLIB_ERR_NONE) {
_profileSwitch.packetResult(rc, preambleLengthLoRa, crcTypeLoRa,
implicitLen, headerType, invertIQEnabled);
return rc;
}
if (!stage) {
int16_t state = setCRC(1);
if (state == RADIOLIB_ERR_NONE) state = explicitHeader();
if (state == RADIOLIB_ERR_NONE) state = invertIQ(false);
return state;
}
crcTypeLoRa = RADIOLIB_SX126X_LORA_CRC_ON;
implicitLen = 0xff; // RadioLib explicitHeader() default receive length.
headerType = RADIOLIB_SX126X_LORA_HEADER_EXPLICIT;
invertIQEnabled = RADIOLIB_SX126X_LORA_IQ_STANDARD;
// Even an unchanged software tuple must be acknowledged once after the
// protocol write. Failed packet/IQ-workaround/SetRx commands revoke the
// owned context; the wrapper restores the old protocol with full setup.
_profileSwitch.invalidatePacket();
return RADIOLIB_ERR_NONE;
}
// Ordinary setters can change hardware or leave RadioLib's fields updated
// after a failed write. They cannot preserve our acknowledged hop tuple.
int16_t setBandwidth(float bw) override {
@@ -38,8 +38,20 @@ public:
~CustomSX1262Wrapper() { unregisterInterruptAction(); }
CustomSX1262Wrapper(CustomSX1262& radio, mesh::MainBoard& board) : RadioLibWrapper(radio, board) { }
bool supportsCarrierWave() const override { return true; }
#if MESH_ENABLE_MESHTEXT_CHAT
bool supportsMeshtext() const override { return true; }
#endif
protected:
#if MESH_ENABLE_MESHTEXT_CHAT
bool applyProtocol(mesh::RadioProfileProtocol protocol) override {
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;
}
#endif
int16_t applyCachedTxPower(int8_t dbm) override {
#ifdef SX126X_PA_RAMP_TIME
// External-PA boards such as the T-Beam 1W require a slower PA ramp. Use
+35
View File
@@ -298,6 +298,9 @@ bool RadioLibWrapper::restoreAfterDeepInit() {
restored = _radio->setPreambleLength(currentPreambleLength())
== RADIOLIB_ERR_NONE;
}
#if MESH_ENABLE_MESHTEXT_CHAT
restored = restored && applyProtocol(_physical_protocol);
#endif
if (_dbm_valid) {
restored = applyCachedTxPower(_cur_dbm) == RADIOLIB_ERR_NONE && restored;
}
@@ -323,6 +326,9 @@ 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_CHAT
const auto previous_protocol = _physical_protocol;
#endif
const uint8_t previous_profile = _active_profile;
const uint32_t previous_generation = _profile_generation;
const bool previous_refresh = _profile_refresh_required;
@@ -337,6 +343,10 @@ mesh::RadioParamApplyResult RadioLibWrapper::trySetParams(float freq, float bw,
_physical_preamble = profilePreamble(0);
bool success = applyParams(freq, bw, sf, cr);
#if MESH_ENABLE_MESHTEXT_CHAT
success = success && applyProtocol(requested.protocol);
if (success) _physical_protocol = requested.protocol;
#endif
if (success) {
cacheParams(freq, bw, sf, cr);
_active_profile = 0;
@@ -367,6 +377,9 @@ 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_CHAT
_physical_protocol = previous_protocol;
#endif
_rx_ps_enabled = previous_rxps;
_profile_saved_rxps = previous_saved_rxps;
_rx_ps_continuous_fallback = previous_fallback;
@@ -375,6 +388,9 @@ 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_CHAT
restored = restored && applyProtocol(previous_protocol);
#endif
if (!restored) restored = restoreAfterDeepInit();
if (restored) endReconfigure(resume_rx);
@@ -391,6 +407,7 @@ 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 defined(USE_SX1276)
return p.freq >= 137 && p.freq <= 1020 && p.sf >= 7 && p.bw <= 500;
#elif defined(USE_SX1272)
@@ -432,8 +449,19 @@ 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_CHAT
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_CHAT
// 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)) {
applied = applyProtocol(p.protocol);
}
if (applied) _physical_protocol = p.protocol;
#endif
if (applied) {
cacheParams(p.freq, p.bw, p.sf, p.cr);
_active_profile = profile;
@@ -456,8 +484,14 @@ mesh::RadioParamApplyResult RadioLibWrapper::tuneProfile(uint8_t profile) {
_profile_generation = old_generation;
_profile_refresh_required = old_refresh;
_physical_preamble = old_preamble;
#if MESH_ENABLE_MESHTEXT_CHAT
_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_CHAT
restored = restored && applyProtocol(old_protocol);
#endif
if (!restored) restored = restoreAfterDeepInit();
if (restored) endReconfigure(resume);
if (!restored || (resume && !isInRecvMode())) _profile_refresh_required = true;
@@ -631,6 +665,7 @@ mesh::RadioParamApplyResult RadioLibWrapper::trySetPrimaryParams(const mesh::Rad
const bool was_temp = _profiles.primary_temporary;
const uint32_t generation = _profiles.generation[0];
_profiles.primary.preamble = p.preamble;
_profiles.primary.protocol = p.protocol;
_profiles.primary_temporary = temporary;
const auto result = trySetParams(p.freq, p.bw, p.sf, p.cr, timings);
if (result != mesh::RadioParamApplyResult::APPLIED) {
+8
View File
@@ -89,6 +89,14 @@ protected:
mesh::RadioProfiles _profiles;
uint8_t _active_profile = 0;
uint16_t _physical_preamble = 0;
#if MESH_ENABLE_MESHTEXT_CHAT
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.
virtual bool applyProtocol(mesh::RadioProfileProtocol protocol) {
return protocol == mesh::RadioProfileProtocol::MeshCore;
}
#endif
uint32_t _profile_generation = 0;
uint32_t _profile_scan_generation[2] = {};
uint32_t _profile_visit_stamp = 0;