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

+27
View File
@@ -1116,6 +1116,8 @@ bool DataStore::loadPrefsInt(const char *filename,
loaded_prefs.usb_debug_enabled = 0;
// Old images cannot opt in using an unrelated runtime preference value.
loaded_prefs.lost_reply = 0;
loaded_prefs.tx_media = mesh::RADIO_TX_AUTO;
loaded_prefs.tx_ssh = mesh::RADIO_TX_AUTO;
#if defined(RAK_4631)
loaded_prefs.peripherals_shared = 0;
#endif
@@ -1201,6 +1203,16 @@ bool DataStore::loadPrefsInt(const char *filename,
333,
#else
236,
#endif
#ifdef TBEAM_1W
243 + mesh::companion::traffic::FooterSize,
#elif defined(RP2040_PLATFORM) && defined(ENABLE_WIFI_INTERFACE)
333 + mesh::companion::traffic::FooterSize,
#elif defined(RAK_4631)
236 + mesh::peripherals::FooterSize
+ mesh::companion::traffic::FooterSize,
#else
236 + mesh::companion::traffic::FooterSize,
#endif
};
const uint32_t prefs_size = file.size();
@@ -1378,6 +1390,16 @@ bool DataStore::loadPrefsInt(const char *filename,
#endif
#endif
// The compact STM32 table and the explicit readers both end at the
// unchanged historical prefix. Consume the common footer only afterward.
if (file.available() != 0) {
uint8_t traffic_footer[mesh::companion::traffic::FooterSize] = {};
success = success
&& file.read(traffic_footer, sizeof(traffic_footer)) == sizeof(traffic_footer)
&& mesh::companion::traffic::decodeFooter(traffic_footer,
sizeof(traffic_footer), loaded_prefs.tx_media, loaded_prefs.tx_ssh);
}
// Any bytes left over form only part of a historically appended field.
// Preserve the file and defaults rather than treating that tail as EOF.
success = success && file.available() == 0;
@@ -1582,6 +1604,11 @@ bool DataStore::savePrefs(const CompanionNodePrefs& _prefs, double node_lat, dou
&& file.write(image, sizeof(image)) == sizeof(image);
#endif
#endif
uint8_t traffic_footer[mesh::companion::traffic::FooterSize];
mesh::companion::traffic::encodeFooter(traffic_footer,
_prefs.tx_media, _prefs.tx_ssh);
success = success
&& file.write(traffic_footer, sizeof(traffic_footer)) == sizeof(traffic_footer);
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) || defined(ESP32_PLATFORM) || defined(RP2040_PLATFORM)
success = file.commit(success);
if (!success) MESH_DEBUG_PRINTLN("DataStore: atomic preferences write failed");
@@ -0,0 +1,240 @@
#include "MyMesh.h"
#if MESH_ENABLE_ETHERNET_TUNNEL
#include <Preferences.h>
#include <helpers/CLICommandUtils.h>
#include <helpers/CompanionChannelAlias.h>
void MyMesh::beginEthernetTunnel() {
_ethernet_settings = {};
_ethernet_settings_valid = false;
Preferences prefs;
if (!prefs.begin("mesh-eth", false)) { _ethernet_status = "settings unreadable"; return; }
const size_t length = prefs.getBytesLength("settings");
if (!length) _ethernet_settings_valid = true;
else {
uint8_t image[mesh::ethernet::SettingsSize];
_ethernet_settings_valid = length == sizeof(image)
&& prefs.getBytes("settings", image, sizeof(image)) == sizeof(image)
&& mesh::ethernet::decodeSettings(image, sizeof(image), _ethernet_settings);
}
prefs.end();
_ethernet_status = _ethernet_settings_valid ? "off" : "invalid settings; set ethernet.radio to repair";
}
bool MyMesh::ethernetChannelConflict() {
if (_ethernet_checked_channels == _ethernet_channel_generation) return _ethernet_channels_conflict;
_ethernet_checked_channels = _ethernet_channel_generation;
_ethernet_channels_conflict = false;
for (int i = 0; i < MAX_GROUP_CHANNELS; ++i) {
ChannelDetails channel;
if (!BaseChatMesh::getChannel(i, channel) || !channel.name[0]) continue;
if (parseCompanionChannelAlias(channel.name).kind != CompanionChannelKind::MeshCore) {
_ethernet_channels_conflict = true;
break;
}
}
return _ethernet_channels_conflict;
}
void MyMesh::releaseEthernetProfile() {
_ethernet_active = false;
_ethernet_kiss.loop(false);
discardQueuedForeignRadioFrame(mesh::RadioProfileProtocol::Ethernet);
const auto* profiles = _radio->profiles();
if (_ethernet_owned && profiles
&& profiles->secondary.params.protocol == mesh::RadioProfileProtocol::Ethernet) {
_radio_profiles.clearAutoSecondary();
_radio_profiles.clearSecondaryProtocol();
}
_ethernet_owned = false;
_ethernet_generation = 0;
}
bool MyMesh::saveEthernetSettings(const mesh::ethernet::Settings& settings) {
if (hasForeignRadioFrame() || !mesh::ethernet::validSettings(settings)) return false;
uint8_t image[mesh::ethernet::SettingsSize], verify[mesh::ethernet::SettingsSize];
mesh::ethernet::encodeSettings(image, settings);
Preferences prefs;
if (!prefs.begin("mesh-eth", false)) return false;
const bool ok = prefs.putBytes("settings", image, sizeof(image)) == sizeof(image)
&& prefs.getBytes("settings", verify, sizeof(verify)) == sizeof(verify)
&& !memcmp(image, verify, sizeof(image));
prefs.end();
releaseEthernetProfile();
if (!ok) {
// The write may have committed even if verification failed. Suspend
// instead of using a different network now than the next boot will load.
_ethernet_settings_valid = false;
_ethernet_status = "settings save failed; suspended";
return false;
}
_ethernet_settings = settings;
_ethernet_settings_valid = true;
if (settings.enabled && !ethernetChannelConflict()) {
// Removing the last MT channel can leave its RAM lease until the next
// loop. Release that unused owner only after this explicit enable saves.
const auto* profiles = _radio->profiles();
if (profiles && profiles->secondary.params.protocol == mesh::RadioProfileProtocol::Meshtext) {
_radio_profiles.clearAutoSecondary();
_radio_profiles.clearSecondaryProtocol();
}
}
_ethernet_status = settings.enabled ? "waiting for radio2" : "off";
return true;
}
bool MyMesh::eraseEthernetSettings() {
releaseEthernetProfile();
_ethernet_settings_valid = false;
_ethernet_settings.enabled = false;
Preferences prefs;
if (!prefs.begin("mesh-eth", false)) return false;
const bool ok = !prefs.getBytesLength("settings") || prefs.remove("settings");
prefs.end();
if (ok) { _ethernet_settings = {}; _ethernet_settings_valid = true; }
_ethernet_status = ok ? "off" : "settings erase failed";
return ok;
}
bool MyMesh::ethernetRadioConflict(const mesh::ethernet::Settings& settings) {
if (ethernetChannelConflict() || _radio_profiles.secondaryTemporary()) return true;
if (!_radio_profiles.manualSecondaryConfigured()) return !_radio_profiles.canAutoSecondary();
auto saved = _radio_profiles.savedSecondaryConfig();
saved.params.protocol = mesh::RadioProfileProtocol::Ethernet;
return saved.mode != mesh::RadioProfileMode::RxTx || saved.params != settings.radio;
}
bool MyMesh::handleEthernetTunnelCommand(const char* command, char* reply, size_t capacity) {
const bool status = !strcmp(command, "get ethernet") || !strcmp(command, "get ethernet.status");
const bool get_radio = !strcmp(command, "get ethernet.radio");
const bool set = !strncmp(command, "set ethernet", 12)
&& (command[12] == 0 || command[12] == ' ' || command[12] == '.');
if (!status && !get_radio && !set) return false;
if (status) {
const auto& server = _ethernet_kiss.status();
snprintf(reply, capacity, "> ethernet=%s; %s; TCP %u %s; RX=%lu TX=%lu fail=%lu; radio2 only",
_ethernet_settings.enabled ? "on" : "off", _ethernet_status,
mesh::ethernet::KissServer::Port, server.connected ? "connected" : server.listening ? "listening" : "stopped",
(unsigned long)_ethernet_received, (unsigned long)_ethernet_sent, (unsigned long)_ethernet_failed);
return true;
}
if (get_radio) {
const auto& p = _ethernet_settings.radio;
if (!_ethernet_settings.configured) snprintf(reply, capacity, "> unset; set ethernet.radio <MHz>,<kHz>,<SF>,<CR>[,<preamble>]");
else snprintf(reply, capacity, "> %.3f,%g,%u,%u,%u; sync=0x16; %s",
p.freq, p.bw, p.sf, p.cr, p.preamble, _ethernet_settings_valid ? "saved" : "invalid settings");
return true;
}
auto settings = _ethernet_settings_valid ? _ethernet_settings : mesh::ethernet::Settings{};
if (!strncmp(command, "set ethernet.radio ", 19)) {
char tuple[96]; uint16_t preamble;
if (!mesh::RadioProfileCLI::parseSuffix(command + 19, 4, tuple, sizeof(tuple), preamble)
|| !mesh::cli::parseRadioTupleStrict(tuple, settings.radio.freq, settings.radio.bw,
settings.radio.sf, settings.radio.cr)) {
snprintf(reply, capacity, "Error: use set ethernet.radio <MHz>,<kHz>,<SF>,<CR>[,<preamble>]"); return true;
}
settings.radio.preamble = preamble ? preamble : 32;
settings.configured = true;
if (!mesh::ethernet::validSettings(settings)
|| !_radio->supportsEthernetTunnel() || !_radio->validateProfile(settings.radio)) {
snprintf(reply, capacity, "Error: Ethernet modem/tuple unsupported"); return true;
}
// Editing a running tunnel must not silently evict someone else's lease.
// Disable the tunnel before changing to a conflicting RF tuple.
if (settings.enabled && ethernetRadioConflict(settings)) {
snprintf(reply, capacity, "Error: radio2 reserved/conflicting; set ethernet off first"); return true;
}
} else if (!strcmp(command, "set ethernet on")) {
if (!settings.configured || !settings.radio.freq) {
snprintf(reply, capacity, "Error: set ethernet.radio first; no automatic frequency"); return true;
}
if (!_radio->supportsEthernetTunnel() || ethernetRadioConflict(settings)) {
snprintf(reply, capacity, "Error: radio2 reserved/conflicting; remove r2-/mt- channels or match saved radio2"); return true;
}
settings.enabled = true;
} else if (!strcmp(command, "set ethernet off")) settings.enabled = false;
else { snprintf(reply, capacity, "Error: use set ethernet on|off or set ethernet.radio <MHz>,<kHz>,<SF>,<CR>[,<preamble>]"); return true; }
if (!saveEthernetSettings(settings)) snprintf(reply, capacity, "Error: Ethernet settings not saved (pending TX/storage failure)");
else snprintf(reply, capacity, "OK - ethernet %s saved; radio2 only; trusted-LAN KISS TCP %u", settings.enabled ? "on" : "off", mesh::ethernet::KissServer::Port);
return true;
}
void MyMesh::loopEthernetTunnel() {
const auto* current = _radio->profiles();
const bool lease_unchanged = _ethernet_active && _ethernet_owned && current
&& current->generation[1] == _ethernet_generation
&& _radio_profiles.secondaryIntentGeneration() == _ethernet_intent_generation
&& current->secondary.mode == mesh::RadioProfileMode::RxTx
&& current->secondary.params == _ethernet_settings.radio
&& _radio_profiles.secondaryRuntimeAvailable();
const char* blocked = nullptr;
if (!_ethernet_settings_valid) blocked = "invalid settings";
else if (!_ethernet_settings.enabled) blocked = "off";
else if (!_ethernet_settings.configured) blocked = "radio unset";
else if (!_radio_available || !_radio->supportsEthernetTunnel()) blocked = "modem unavailable";
else if (ethernetChannelConflict()) blocked = "conflicting r2-/mt- channel";
else if (_radio_profiles.secondaryTemporary()) blocked = "temporary radio2 owns modem";
// Validation/timing preview and profile publication happen only on an
// ownership/configuration edge, never on every RF polling pass.
if (!blocked && !lease_unchanged) {
if (_radio_profiles.manualSecondaryConfigured()) {
auto saved = _radio_profiles.savedSecondaryConfig();
saved.params.protocol = mesh::RadioProfileProtocol::Ethernet;
if (saved.mode != mesh::RadioProfileMode::RxTx || saved.params != _ethernet_settings.radio
|| !_radio_profiles.useSecondaryProtocol(mesh::RadioProfileProtocol::Ethernet)) blocked = "saved radio2 conflicts";
} else {
mesh::RadioProfileConfig config;
config.mode = mesh::RadioProfileMode::RxTx; config.params = _ethernet_settings.radio;
if (!_radio_profiles.requestAutoSecondary(config)) blocked = "radio2 reserved";
}
}
if (blocked) {
if (_ethernet_active || _ethernet_owned) releaseEthernetProfile();
else _ethernet_kiss.loop(false);
_ethernet_status = blocked;
return;
}
const auto* profiles = _radio->profiles();
if (!profiles || !profiles->enabled() || !profiles->canTransmit(1)
|| profiles->secondary.params.protocol != mesh::RadioProfileProtocol::Ethernet) {
releaseEthernetProfile(); _ethernet_status = "waiting for radio2"; return;
}
if (_ethernet_generation != profiles->generation[1]) _ethernet_kiss.resetPending();
_ethernet_generation = profiles->generation[1];
_ethernet_intent_generation = _radio_profiles.secondaryIntentGeneration();
_ethernet_owned = _ethernet_active = true;
const auto before = _ethernet_kiss.status().accepted + _ethernet_kiss.status().disconnects;
_ethernet_kiss.loop(true);
const auto after = _ethernet_kiss.status().accepted + _ethernet_kiss.status().disconnects;
if (before != after) discardQueuedForeignRadioFrame(mesh::RadioProfileProtocol::Ethernet);
_ethernet_status = _ethernet_kiss.status().listening ? "active (RX time-shared)" : "waiting for station WiFi";
const uint8_t* bytes; size_t length;
if (!hasForeignRadioFrame() && _ethernet_kiss.peekTransmit(bytes, length)
&& queueForeignRadioFrame(bytes, length, 1, profiles->generation[1], mesh::RadioProfileProtocol::Ethernet))
_ethernet_kiss.consumeTransmit();
}
bool MyMesh::onEthernetFrame(const uint8_t* bytes, size_t length, uint8_t profile, uint32_t generation) {
const auto* profiles = _radio->profiles();
if (!_ethernet_active || !profiles || profile != 1 || generation != profiles->generation[1]
|| profiles->secondary.params.protocol != mesh::RadioProfileProtocol::Ethernet) return false;
if (!_ethernet_kiss.queueReceive(bytes, length)) return false;
++_ethernet_received;
return true;
}
#if !MESH_ENABLE_MESHTEXT_CHAT
bool MyMesh::onForeignRadioFrame(const uint8_t* bytes, size_t length, uint8_t profile,
uint32_t generation, float snr, float rssi) {
(void)snr; (void)rssi;
return onEthernetFrame(bytes, length, profile, generation);
}
void MyMesh::onForeignRadioSendComplete(bool success) {
if (queuedForeignRadioProtocol() != mesh::RadioProfileProtocol::Ethernet) return;
if (success) ++_ethernet_sent;
else ++_ethernet_failed;
}
#endif
#endif
@@ -286,6 +286,16 @@ bool MyMesh::validateMeshtextChannelChange(int index, const ChannelDetails& cand
}
void MyMesh::refreshMeshtextProfile() {
#if MESH_ENABLE_ETHERNET_TUNNEL
// This owner must never revoke an Ethernet lease simply because it has
// no Meshtext channels. Explicit channel conflicts suspend Ethernet too.
if (_ethernet_settings.enabled) {
_mt_active = false;
_mt_status = "radio2 reserved for Ethernet";
_mt_profile_dirty = true;
return;
}
#endif
const auto* current_profiles = _radio->profiles();
const uint32_t primary_generation = current_profiles ? current_profiles->generation[0] : 0;
const uint32_t secondary_generation = current_profiles ? current_profiles->generation[1] : 0;
@@ -424,6 +434,12 @@ bool MyMesh::sendMeshtextNodeInfo(const ChannelDetails& channel) {
bool MyMesh::onForeignRadioFrame(const uint8_t* bytes, size_t length, uint8_t profile,
uint32_t generation, float snr, float rssi) {
#if MESH_ENABLE_ETHERNET_TUNNEL
const auto* receiving_profiles = _radio->profiles();
if (receiving_profiles && profile < 2
&& receiving_profiles->params(profile).protocol == mesh::RadioProfileProtocol::Ethernet)
return onEthernetFrame(bytes, length, profile, generation);
#endif
(void)rssi;
const auto* profiles = _radio->profiles();
if (!_mt_active || !profiles || profile != 1 || generation != profiles->generation[1]) return false;
@@ -454,6 +470,13 @@ bool MyMesh::onForeignRadioFrame(const uint8_t* bytes, size_t length, uint8_t pr
}
void MyMesh::onForeignRadioSendComplete(bool success) {
#if MESH_ENABLE_ETHERNET_TUNNEL
if (queuedForeignRadioProtocol() == mesh::RadioProfileProtocol::Ethernet) {
if (success) ++_ethernet_sent;
else ++_ethernet_failed;
return;
}
#endif
if (success) ++_mt_sent;
else ++_mt_failed;
}
+104 -9
View File
@@ -2,6 +2,9 @@
#include <helpers/BatteryChargeCLI.h>
#include <helpers/MorseCLI.h>
#include <helpers/MorseLoopPolicy.h>
#if defined(MESH_HIL_TX_FREQ_MHZ)
#include <helpers/radiolib/HilTxFrequencyGuard.h>
#endif
#if defined(RAK_4631)
#include <helpers/PeripheralModePrefs.h>
#endif
@@ -9,6 +12,7 @@
#include "NotificationSettingsFile.h"
#include "MyMesh.h"
#include <helpers/CompanionTxRoutingCLI.h>
#include <helpers/CompanionTrafficRouting.h>
#include <helpers/CompanionChannelAlias.h>
#include <helpers/FleetCommand.h>
#include "CompanionBluetooth.h"
@@ -1713,7 +1717,15 @@ bool MyMesh::getChannel(int channel_idx, ChannelDetails& channel) {
bool MyMesh::setChannel(int channel_idx, const ChannelDetails& channel) {
if (parseCompanionChannelAlias(channel.name).kind == CompanionChannelKind::Invalid) return false;
return BaseChatMesh::setChannel(channel_idx, channel);
#if MESH_ENABLE_ETHERNET_TUNNEL
if (_ethernet_settings.enabled && channel.name[0]
&& parseCompanionChannelAlias(channel.name).kind != CompanionChannelKind::MeshCore) return false;
#endif
const bool saved = BaseChatMesh::setChannel(channel_idx, channel);
#if MESH_ENABLE_ETHERNET_TUNNEL
if (saved) ++_ethernet_channel_generation;
#endif
return saved;
}
int MyMesh::searchChannelsForPacket(const mesh::Packet* packet, const uint8_t* hash,
@@ -3164,6 +3176,9 @@ void MyMesh::begin(bool has_display, bool radio_available,
#if MESH_ENABLE_TX_BEACONS
beginBeacons();
#endif
#if MESH_ENABLE_ETHERNET_TUNNEL
beginEthernetTunnel();
#endif
#if MESH_ENABLE_MESHTEXT_CHAT
beginMeshtext();
#endif
@@ -3566,6 +3581,58 @@ bool MyMesh::handleCadCommand(const char* command, char* reply,
return true;
}
bool MyMesh::handleTrafficRoutingCommand(const char* command, char* reply, size_t reply_size) {
if (!reply || !reply_size) return false;
const auto parsed = mesh::companion::parseTrafficRouteCommand(command);
if (!parsed.matched) return false;
const char* kind = parsed.kind == mesh::companion::TrafficKind::Media ? "media" : "ssh";
if (!parsed.valid) {
snprintf(reply, reply_size, "Error: use get tx.%s or set tx.%s auto|radio|radio2|both|off", kind, kind);
return true;
}
uint8_t& policy = parsed.kind == mesh::companion::TrafficKind::Media ? _prefs.tx_media : _prefs.tx_ssh;
if (parsed.set) {
const uint8_t previous = policy;
policy = parsed.policy;
// Even an unchanged value must have durable storage before we say saved.
if (!savePrefs()) {
policy = previous;
snprintf(reply, reply_size, "Error: tx.%s was not saved", kind);
return true;
}
}
const uint8_t mask = mesh::companion::trafficTransmitMask(policy, _radio->profiles());
snprintf(reply, reply_size, "%s tx.%s %s; active=%s%s", parsed.set ? "OK -" : ">", kind,
mesh::radioTxPolicyName(policy), policy == mesh::RADIO_TX_AUTO ? "channel/global"
: mask ? mesh::radioTxPolicyName(mask) : "off",
(policy == mesh::RADIO_TX_SECONDARY || policy == mesh::RADIO_TX_BOTH) && !(mask & 2)
? " (radio2 unavailable for TX)" : "");
return true;
}
bool MyMesh::sendClientGroupData(mesh::GroupChannel& channel, uint8_t* path, uint8_t path_len,
uint16_t data_type, const uint8_t* data, int data_len) {
if (data_len < 0 || data_len > MAX_GROUP_DATA_LENGTH || (data_len && !data)) return false;
const uint8_t policy = mesh::companion::trafficPolicy(mesh::companion::groupTrafficKind(data_type),
_prefs.tx_media, _prefs.tx_ssh);
if (policy == mesh::RADIO_TX_AUTO) return sendGroupData(channel, path, path_len, data_type, data, data_len);
// Override only this datagram, not the saved channel, PSK, alias or text route.
mesh::GroupChannel routed = channel;
routed.tx_radio = policy;
return sendGroupData(routed, path, path_len, data_type, data, data_len);
}
bool MyMesh::sendClientRawData(const uint8_t* data, size_t data_len, uint8_t* path, uint8_t path_len) {
if (!data || data_len < 4) return false;
auto pkt = createRawData(data, data_len);
if (!pkt) return false;
const uint8_t policy = mesh::companion::trafficPolicy(mesh::companion::rawTrafficKind(data, data_len),
_prefs.tx_media, _prefs.tx_ssh);
if (policy != mesh::RADIO_TX_AUTO) pkt->tx_radio = policy;
// sendDirect owns/releases the packet on either success or failure.
return sendDirect(pkt, path, path_len);
}
bool MyMesh::handleTxRoutingCommand(const char* command, char* reply, size_t reply_size) {
const auto parsed = mesh::companion::parseTxRouteCommand(command);
if (!parsed.matched) return false;
@@ -3672,6 +3739,9 @@ bool MyMesh::handleLocalControlCommand(const char* command, char* reply,
size_t reply_size) {
if (!command || !reply || reply_size == 0) return false;
while (*command == ' ') command++;
#if defined(MESH_HIL_TX_FREQ_MHZ)
if (mesh::handleHilTxFrequencyCommand(command, reply, reply_size)) return true;
#endif
#if defined(RAK_4631)
// This helper is also reached only after normal remote-admin admission.
if (mesh::peripherals::handleCommand(_prefs.peripherals_shared, command,
@@ -3693,6 +3763,10 @@ bool MyMesh::handleLocalControlCommand(const char* command, char* reply,
return true;
}
#if MESH_ENABLE_ETHERNET_TUNNEL
if (handleEthernetTunnelCommand(command, reply, reply_size)) return true;
#endif
if (handleTrafficRoutingCommand(command, reply, reply_size)) return true;
if (handleTxRoutingCommand(command, reply, reply_size)) return true;
#if MESH_ENABLE_TX_BEACONS
if (handleBeaconCommand(command, reply, reply_size)) return true;
@@ -6069,7 +6143,7 @@ void MyMesh::handleCmdFrame(size_t len) {
} else if (payload_len > MAX_GROUP_DATA_LENGTH) {
MESH_DEBUG_PRINTLN("CMD_SEND_CHANNEL_DATA payload too long: %d > %d", payload_len, MAX_GROUP_DATA_LENGTH);
writeErrFrame(ERR_CODE_ILLEGAL_ARG);
} else if (sendGroupData(channel.channel, path, path_len, data_type, payload, payload_len)) {
} else if (sendClientGroupData(channel.channel, path, path_len, data_type, payload, payload_len)) {
writeOKFrame();
} else {
writeErrFrame(ERR_CODE_TABLE_FULL);
@@ -6580,18 +6654,17 @@ void MyMesh::handleCmdFrame(size_t len) {
} else if (cmd_frame[0] == CMD_SEND_RAW_DATA && len >= 6) {
int i = 1;
uint8_t path_len = cmd_frame[i++];
if (path_len >= 0 && mesh::Packet::isValidPathLen(path_len)) {
if (mesh::Packet::isValidPathLen(path_len)) {
uint8_t path[MAX_PATH_SIZE];
i += mesh::Packet::writePath(path, &cmd_frame[i], path_len);
if (i + 4 > len) { // min payload 4 bytes
const size_t path_bytes = static_cast<size_t>(path_len & 63) * ((path_len >> 6) + 1);
if (static_cast<size_t>(i) + path_bytes + 4 > len) { // min payload 4 bytes, before reading path
writeErrFrame(ERR_CODE_ILLEGAL_ARG);
} else {
auto pkt = createRawData(&cmd_frame[i], len - i);
if (pkt) {
sendDirect(pkt, path, path_len);
i += mesh::Packet::writePath(path, &cmd_frame[i], path_len);
if (sendClientRawData(&cmd_frame[i], len - i, path, path_len)) {
writeOKFrame();
} else {
writeErrFrame(ERR_CODE_TABLE_FULL);
writeErrFrame(ERR_CODE_BAD_STATE);
}
}
} else {
@@ -10086,6 +10159,13 @@ void MyMesh::handleTerminalCommand(char* command, bool reader_prompt,
#endif
#if COMPANION_FEATURE_READER
terminalOutput().print(" get reader <chapter>[:<verse>[-<last>]] [page] (World English Bible, offline)\r\n");
#endif
terminalOutput().print(" get/set tx.media auto|radio|radio2|both|off (binary media)\r\n"
" get/set tx.ssh auto|radio|radio2|both|off (tagged tunnel data)\r\n");
#if MESH_ENABLE_ETHERNET_TUNNEL
terminalOutput().print(" get ethernet / get ethernet.radio\r\n"
" set ethernet.radio <MHz>,<kHz>,<SF>,<CR>[,<preamble>]\r\n"
" set ethernet on|off (saved; trusted-LAN KISS TCP 5003, radio2 only)\r\n");
#endif
terminalOutput().print(" get pwrmgt.bootreason\r\n");
#if COMPANION_FEATURE_MEMORY_DIAGNOSTICS
@@ -10354,6 +10434,12 @@ bool MyMesh::handleDirectCommand(const char* command, char* reply, size_t reply_
stopContactsIterator();
resetContacts();
mesh::resetLazyPersistenceAfterSuccess(dirty_contacts_expiry, dirty_contacts_failures);
#if MESH_ENABLE_ETHERNET_TUNNEL
if (!eraseEthernetSettings()) {
snprintf(reply, reply_size, "File system erased; Error: Ethernet settings erase failed");
return true;
}
#endif
#if MESH_ENABLE_MESHTEXT_CHAT
if (!eraseMeshtextSettings()) {
snprintf(reply, reply_size, "File system erased; Error: MT settings erase failed");
@@ -10916,6 +11002,12 @@ complete_line:
suspendBeacons();
#endif
bool success = _store->formatFileSystem();
#if MESH_ENABLE_ETHERNET_TUNNEL
if (success && !eraseEthernetSettings()) {
output.println(" Error: file system erased, but Ethernet settings erase failed");
return;
}
#endif
#if MESH_ENABLE_MESHTEXT_CHAT
if (success && !eraseMeshtextSettings()) {
output.println(" Error: file system erased, but MT settings erase failed");
@@ -11178,6 +11270,9 @@ void MyMesh::loop() {
#if MESH_ENABLE_MESHTEXT_CHAT
refreshMeshtextProfile();
#endif
#if MESH_ENABLE_ETHERNET_TUNNEL
if (!mesh::morseTimingActive(_radio)) loopEthernetTunnel();
#endif
#if defined(WITH_MQTT_BRIDGE) && defined(ESP32_PLATFORM) && defined(WIFI_SSID)
if (_mqtt_bridge) _mqtt_bridge->servicePendingClockCorrection();
#endif
+43 -6
View File
@@ -29,6 +29,10 @@
#include <helpers/RadioProfileCLI.h>
#include <helpers/MorseReplyHandoff.h>
#include <helpers/MeshtextConfig.h>
#if MESH_ENABLE_ETHERNET_TUNNEL
#include <helpers/EthernetTunnelSettings.h>
#include <helpers/esp32/EthernetKissServer.h>
#endif
namespace mesh { class BeaconManager; }
#if MESH_ENABLE_MESHTEXT_CHAT
#include <helpers/CompanionMeshtextChannel.h>
@@ -334,6 +338,10 @@ public:
void beginUsbLoggingReplyBarrier(BaseSerialInterface* route);
void endUsbLoggingReplyBarrier(bool reply_queued);
bool handleTxRoutingCommand(const char* command, char* reply, size_t reply_size);
bool handleTrafficRoutingCommand(const char* command, char* reply, size_t reply_size);
bool sendClientGroupData(mesh::GroupChannel& channel, uint8_t* path, uint8_t path_len,
uint16_t data_type, const uint8_t* data, int data_len);
bool sendClientRawData(const uint8_t* data, size_t data_len, uint8_t* path, uint8_t path_len);
int getRecentlyHeard(AdvertPath dest[], int max_num);
@@ -375,6 +383,41 @@ protected:
const mesh::GroupChannel& channel, uint8_t* data, size_t len) override;
bool isAliasRadio2Defined() const;
bool resolveChannelAlias(ChannelDetails& channel) const;
#if MESH_ENABLE_ETHERNET_TUNNEL
mesh::ethernet::Settings _ethernet_settings;
mesh::ethernet::KissServer _ethernet_kiss;
bool _ethernet_settings_valid = true, _ethernet_active = false, _ethernet_owned = false;
uint32_t _ethernet_generation = 0;
uint32_t _ethernet_intent_generation = 0, _ethernet_channel_generation = 0;
uint32_t _ethernet_checked_channels = UINT32_MAX;
bool _ethernet_channels_conflict = false;
uint32_t _ethernet_received = 0, _ethernet_sent = 0, _ethernet_failed = 0;
const char* _ethernet_status = "off";
void beginEthernetTunnel();
bool ethernetChannelConflict();
bool ethernetRadioConflict(const mesh::ethernet::Settings& settings);
void releaseEthernetProfile();
bool saveEthernetSettings(const mesh::ethernet::Settings& settings);
bool eraseEthernetSettings();
bool handleEthernetTunnelCommand(const char* command, char* reply, size_t capacity);
void loopEthernetTunnel();
bool onEthernetFrame(const uint8_t* bytes, size_t length, uint8_t profile, uint32_t generation);
#endif
#if MESH_ENABLE_FOREIGN_RADIO
bool onForeignRadioFrame(const uint8_t* bytes, size_t length, uint8_t profile,
uint32_t generation, float snr, float rssi) override;
void onForeignRadioSendComplete(bool success) override;
bool allowForeignRadioTransmit() const override {
return _radio_available && _scheduled_reboot_at == 0 && (
#if MESH_ENABLE_MESHTEXT_CHAT
_mt_active ||
#endif
#if MESH_ENABLE_ETHERNET_TUNNEL
_ethernet_active ||
#endif
false);
}
#endif
#if MESH_ENABLE_MESHTEXT_CHAT
void beginMeshtext();
void refreshMeshtextIdentity();
@@ -387,12 +430,6 @@ protected:
bool eraseMeshtextSettings();
bool sendMeshtextText(const ChannelDetails& channel, const char* text, size_t length);
bool sendMeshtextNodeInfo(const ChannelDetails& channel);
bool onForeignRadioFrame(const uint8_t* bytes, size_t length, uint8_t profile,
uint32_t generation, float snr, float rssi) override;
void onForeignRadioSendComplete(bool success) override;
bool allowForeignRadioTransmit() const override {
return _radio_available && _scheduled_reboot_at == 0 && _mt_active;
}
mesh::mt::Region meshtextRegion() const;
#endif
bool queueChannelText(uint8_t index, const uint8_t secret[32], float snr,
+11 -15
View File
@@ -10,6 +10,7 @@
#include <helpers/BluetoothMac.h>
#include <helpers/CommonRadioPrefs.h>
#include <helpers/DynamicConfigSerializer.h>
#include <helpers/CompanionTrafficPrefs.h>
#include "BluetoothName.h"
@@ -121,6 +122,9 @@ public:
// A checked footer follows every existing on-flash field, never an insertion.
uint8_t peripherals_shared = 0; // applied at boot, not on a live CLI save
#endif
// Checked footer after all previously published fields/board footers.
uint8_t tx_media = mesh::RADIO_TX_AUTO;
uint8_t tx_ssh = mesh::RADIO_TX_AUTO;
private:
class RadioPrefs : public CommonRadioPrefs {
@@ -259,31 +263,23 @@ public:
// untouched, and leave a normally constructed snapshot's adapters local.
bool copyPersistedValuesFrom(const CompanionNodePrefs& source) {
if (&source == this) return true;
#if defined(RAK_4631)
const auto& last_value = peripherals_shared;
#else
const auto& last_value = lost_reply;
#endif
static_assert(sizeof(lost_reply) == sizeof(uint8_t),
"The published lost reply preference is one byte");
const auto& last_value = tx_ssh;
static_assert(sizeof(tx_ssh) == sizeof(uint8_t),
"The last persisted traffic policy is one byte");
const uintptr_t first = reinterpret_cast<uintptr_t>(&airtime_factor);
const uintptr_t last = reinterpret_cast<uintptr_t>(&last_value);
if (last < first
|| last - first > sizeof(*this) - sizeof(lost_reply)) {
|| last - first > sizeof(*this) - sizeof(tx_ssh)) {
return false;
}
const size_t size = static_cast<size_t>(last - first)
+ sizeof(lost_reply);
+ sizeof(tx_ssh);
const auto bounded = [size](const CompanionNodePrefs& values) -> bool {
const uintptr_t object = reinterpret_cast<uintptr_t>(&values);
const uintptr_t begin =
reinterpret_cast<uintptr_t>(&values.airtime_factor);
const uintptr_t end = reinterpret_cast<uintptr_t>(
#if defined(RAK_4631)
&values.peripherals_shared
#else
&values.lost_reply
#endif
&values.tx_ssh
);
const uintptr_t radio_begin = reinterpret_cast<uintptr_t>(&values.radio);
const uintptr_t custom_begin = reinterpret_cast<uintptr_t>(&values.custom);
@@ -292,7 +288,7 @@ public:
return begin >= object && begin - object <= sizeof(values)
&& size <= sizeof(values) - static_cast<size_t>(begin - object)
&& end >= begin
&& end - begin == size - sizeof(values.lost_reply)
&& end - begin == size - sizeof(values.tx_ssh)
&& radio_begin >= begin && size <= radio_begin - begin
&& custom_begin >= begin && size <= custom_begin - begin;
};
+51 -6
View File
@@ -460,6 +460,29 @@ void KissModem::handleHardwareCommand(uint8_t sub_cmd, const uint8_t* data, uint
case HW_CMD_GET_TEMPRADIO2:
handleGetTempRadio2();
break;
case HW_CMD_SET_RADIO2_EXT:
handleSetRadio2(data, len, true);
break;
case HW_CMD_GET_RADIO2_EXT:
if (len != 0) writeHardwareError(HW_ERR_INVALID_LENGTH);
else handleGetRadio2(true);
break;
#if defined(MESH_HIL_TX_FREQ_MHZ)
case HW_CMD_GET_LAB_TX_GUARD: {
if (len != 0) {
writeHardwareError(HW_ERR_INVALID_LENGTH);
break;
}
// This same compile-time boundary guards startSendRaw(). Never infer
// bench safety from a host-requested profile or a generic version byte.
static_assert(MESH_HIL_TX_FREQ_MHZ >= 150 && MESH_HIL_TX_FREQ_MHZ <= 2500,
"HIL TX frequency must be an explicit valid MHz value");
uint8_t hz[4];
writeU32LE(hz, frequencyToHz(static_cast<float>(MESH_HIL_TX_FREQ_MHZ)));
writeHardwareFrame(HW_RESP(HW_CMD_GET_LAB_TX_GUARD), hz, sizeof(hz));
break;
}
#endif
default:
writeHardwareError(HW_ERR_UNKNOWN_CMD);
break;
@@ -821,8 +844,8 @@ void KissModem::handleGetRadio() {
writeHardwareFrame(HW_RESP(HW_CMD_GET_RADIO), buf, sizeof(buf));
}
void KissModem::handleSetRadio2(const uint8_t* data, uint16_t len) {
if (len != KISS_RADIO2_PARAMS_SIZE) {
void KissModem::handleSetRadio2(const uint8_t* data, uint16_t len, bool extended) {
if (len != (extended ? KISS_RADIO2_EXT_PARAMS_SIZE : KISS_RADIO2_PARAMS_SIZE)) {
writeHardwareError(HW_ERR_INVALID_LENGTH);
return;
}
@@ -833,7 +856,27 @@ void KissModem::handleSetRadio2(const uint8_t* data, uint16_t len) {
}
Radio2Config config;
if (!decodeRadio2Config(data, config) || !validateRadio2Config(config)) {
if (!decodeRadio2Config(data, config)) {
writeHardwareError(HW_ERR_INVALID_PARAM);
return;
}
if (extended) {
const uint8_t protocol = data[KISS_RADIO2_PARAMS_SIZE];
if (protocol != (uint8_t)mesh::RadioProfileProtocol::MeshCore
&& protocol != (uint8_t)mesh::RadioProfileProtocol::Ethernet) {
writeHardwareError(HW_ERR_INVALID_PARAM);
return;
}
config.profile.params.protocol = (mesh::RadioProfileProtocol)protocol;
// Reject unavailable wire support even for an off/zero tuple. The host
// must never mistake an accepted setting for a supported modem format.
if (config.profile.params.protocol == mesh::RadioProfileProtocol::Ethernet
&& !_radio.supportsEthernetTunnel()) {
writeHardwareError(HW_ERR_INVALID_PARAM);
return;
}
}
if (!validateRadio2Config(config)) {
writeHardwareError(HW_ERR_INVALID_PARAM);
return;
}
@@ -845,14 +888,16 @@ void KissModem::handleSetRadio2(const uint8_t* data, uint16_t len) {
writeHardwareFrame(HW_RESP_OK, nullptr, 0);
}
void KissModem::handleGetRadio2() {
void KissModem::handleGetRadio2(bool extended) {
if (!_radio.profiles()) {
writeHardwareError(HW_ERR_NO_CALLBACK);
return;
}
uint8_t buf[KISS_RADIO2_PARAMS_SIZE];
uint8_t buf[KISS_RADIO2_EXT_PARAMS_SIZE];
encodeRadio2Config(_saved_radio2, buf);
writeHardwareFrame(HW_RESP(HW_CMD_GET_RADIO2), buf, sizeof(buf));
if (extended) buf[KISS_RADIO2_PARAMS_SIZE] = (uint8_t)_saved_radio2.profile.params.protocol;
writeHardwareFrame(HW_RESP(extended ? HW_CMD_GET_RADIO2_EXT : HW_CMD_GET_RADIO2), buf,
extended ? KISS_RADIO2_EXT_PARAMS_SIZE : KISS_RADIO2_PARAMS_SIZE);
}
void KissModem::handleSetTempRadio2(const uint8_t* data, uint16_t len) {
+8 -3
View File
@@ -69,6 +69,9 @@
#define HW_CMD_GET_RADIO2 0x1C
#define HW_CMD_SET_TEMPRADIO2 0x1D
#define HW_CMD_GET_TEMPRADIO2 0x1E
#define HW_CMD_SET_RADIO2_EXT 0x1F
#define HW_CMD_GET_RADIO2_EXT 0x20
#define HW_CMD_GET_LAB_TX_GUARD 0x21
/* Response code = command code | 0x80. Generic / unsolicited use 0xF0+. */
#define HW_RESP(cmd) ((cmd) | 0x80)
@@ -91,10 +94,12 @@
#define KISS_RADIO_PARAMS_SIZE 10
#define KISS_RADIO2_PARAMS_SIZE 13
#define KISS_RADIO2_EXT_PARAMS_SIZE 14
#define KISS_TEMPRADIO2_PARAMS_SIZE 15
#define KISS_MAX_TEMPRADIO2_MINUTES 10080
/* Version 2 adds the logical secondary-radio KISS port and radio2 commands. */
/* Version 2 adds the logical secondary-radio KISS port and radio2 commands.
* Extended radio2 commands are additive; old firmware returns UnknownCmd. */
#define KISS_FIRMWARE_VERSION 2
typedef void (*SetRadioCallback)(float freq, float bw, uint8_t sf, uint8_t cr);
@@ -215,8 +220,8 @@ class KissModem {
void handleSetRadio(const uint8_t* data, uint16_t len);
void handleSetTxPower(const uint8_t* data, uint16_t len);
void handleGetRadio();
void handleSetRadio2(const uint8_t* data, uint16_t len);
void handleGetRadio2();
void handleSetRadio2(const uint8_t* data, uint16_t len, bool extended = false);
void handleGetRadio2(bool extended = false);
void handleSetTempRadio2(const uint8_t* data, uint16_t len);
void handleGetTempRadio2();
void handleGetTxPower();
+56 -1
View File
@@ -29,6 +29,18 @@
#define NOISE_FLOOR_CALIB_INTERVAL_MS 2000
#define AGC_RESET_INTERVAL_MS 30000
// Lab-only boot diagnostics must never contaminate a native-USB or dedicated
// UART KISS stream. Ordinary builds compile all stage calls away.
#if defined(ESP32) && defined(MESH_HIL_KISS_BOOT_TRACE) && MESH_HIL_KISS_BOOT_TRACE \
&& (!defined(ARDUINO_USB_CDC_ON_BOOT) || !ARDUINO_USB_CDC_ON_BOOT) \
&& !(defined(KISS_UART_RX) && defined(KISS_UART_TX))
#define KISS_UART_BOOT_TRACE 1
#define KISS_BOOT_STAGE(stage) do { Serial.print("KISS_BOOT "); Serial.println(stage); } while (0)
#else
#define KISS_UART_BOOT_TRACE 0
#define KISS_BOOT_STAGE(stage) ((void)0)
#endif
#if MESH_ESP32_HWCDC_SESSION_GUARD && !(defined(KISS_UART_RX) && defined(KISS_UART_TX))
#define KISS_HWCDC_TRANSPORT 1
#else
@@ -72,7 +84,6 @@ void loadOrCreateIdentity() {
InternalFS.begin();
IdentityStore store(InternalFS, "");
#elif defined(ESP32)
SPIFFS.begin(true);
IdentityStore store(SPIFFS, "/identity");
#elif defined(RP2040_PLATFORM)
LittleFS.begin();
@@ -98,21 +109,28 @@ void loadOrCreateIdentity() {
}
}
#else
KISS_BOOT_STAGE("identity.load.before");
const IdentityLoadResult identity_load = store.loadResult("_main", identity);
KISS_BOOT_STAGE("identity.load.after");
#endif
const bool needs_identity = identity_load == IdentityLoadResult::Missing
|| (identity_load == IdentityLoadResult::Loaded
&& mesh::hasReservedIdentityPrefix(identity));
bool identity_ready = identity_load != IdentityLoadResult::Unreadable;
if (needs_identity) {
KISS_BOOT_STAGE("identity.generate.before");
identity_ready = mesh::generateUsableLocalIdentity(identity, radio_new_identity);
KISS_BOOT_STAGE("identity.generate.after");
KISS_BOOT_STAGE("identity.save.before");
if (identity_ready) identity_ready = store.saveWithRetry("_main", identity);
KISS_BOOT_STAGE("identity.save.after");
}
#if defined(ESP32_PLATFORM)
mesh::discardESP32TrueRandom();
#endif
if (!identity_ready) {
KISS_BOOT_STAGE("identity.failed");
MESH_DEBUG_PRINTLN("Identity generation or persistence failed after retries; rebooting");
board.reboot();
halt(); // Never let setup continue if a platform's reboot returns.
@@ -144,13 +162,35 @@ void onGetStats(uint32_t* rx, uint32_t* tx, uint32_t* errors) {
}
void setup() {
#if KISS_UART_BOOT_TRACE
Serial.begin(115200);
KISS_BOOT_STAGE("setup.enter");
#endif
#if KISS_HWCDC_TRANSPORT
// KISS owns the entire serial byte stream, including gaps between chunks.
mesh::setUsbLoggingEnabled(false);
mesh::setUsbDebugEnabled(false);
#endif
KISS_BOOT_STAGE("board.before");
board.begin();
KISS_BOOT_STAGE("board.after");
#if defined(ESP32)
// Mount (and, on a virgin store, format) before radio interrupts start,
// matching the Companion startup order. Never generate a replacement
// identity when primary storage has failed to become available.
KISS_BOOT_STAGE("filesystem.before");
const bool filesystem_ready = SPIFFS.begin(true);
KISS_BOOT_STAGE("filesystem.after");
if (!filesystem_ready) {
KISS_BOOT_STAGE("filesystem.failed");
MESH_DEBUG_PRINTLN("SPIFFS initialization failed; rebooting");
board.reboot();
halt();
}
#endif
KISS_BOOT_STAGE("radio.before");
int radioinit_attempts = 0;
while (!radio_init()) {
++radioinit_attempts;
@@ -161,14 +201,24 @@ void setup() {
}
delay(500);
}
KISS_BOOT_STAGE("radio.after");
KISS_BOOT_STAGE("driver.before");
radio_driver.begin();
KISS_BOOT_STAGE("driver.after");
KISS_BOOT_STAGE("rng.before");
rng.begin(radio_driver.getRngSeed());
KISS_BOOT_STAGE("rng.after");
KISS_BOOT_STAGE("identity.before");
loadOrCreateIdentity();
KISS_BOOT_STAGE("identity.after");
KISS_BOOT_STAGE("sensors.before");
sensors.begin();
KISS_BOOT_STAGE("sensors.after");
KISS_BOOT_STAGE("serial.before");
#if defined(KISS_UART_RX) && defined(KISS_UART_TX)
#if defined(ESP32)
Serial1.setPins(KISS_UART_RX, KISS_UART_TX);
@@ -207,13 +257,18 @@ void setup() {
#endif
#endif
KISS_BOOT_STAGE("serial.after");
modem->setRadioCallback(onSetRadio);
modem->setTxPowerCallback(onSetTxPower);
modem->setGetCurrentRssiCallback(onGetCurrentRssi);
modem->setGetStatsCallback(onGetStats);
KISS_BOOT_STAGE("modem.before");
modem->begin();
KISS_BOOT_STAGE("modem.after");
KISS_BOOT_STAGE("boot_complete.before");
board.onBootComplete();
KISS_BOOT_STAGE("setup.complete");
}
void loop() {