diff --git a/docs/radio_profiles.md b/docs/radio_profiles.md index 36f8e6c4d..d1ce79a95 100644 --- a/docs/radio_profiles.md +++ b/docs/radio_profiles.md @@ -59,6 +59,19 @@ For the same profile at **125 kHz**, use: set radio2 mediamesh-range ``` +On Companions, adding `#r2-mediamesh` in the app also saves the `mediamesh` +profile; `#r2-mediamesh-range` selects `mediamesh-range`. Renaming another +channel to either alias does the same. Names without `#` also work. No extra +CLI command or forwarding-region setup is needed on a Companion. + +Re-saving the same preset alias, editing its key, or rebooting preserves any +later manual radio2 changes, including `set radio2 off`. Removing the channel +does not switch radio2 off. All `r2-` channels share one secondary profile, so +the most recently added or renamed MediaMesh preset chooses its RF settings. +Meshtext channels and an active foreign-protocol radio2 session cannot share +this setup. The supplied channel name and key retain the normal alias rules +[below](#companion-channel-name-routing-aliases). + The RF settings match the presets documented by [MeshCore Open TAK](https://github.com/jade-on-mesh/meshcore-open-tak/blob/main/documentation/media-mesh.md) and [Wadamesh TAK](https://github.com/jade-on-mesh/wadamesh-tak/blob/main/MEDIAMESH.md). diff --git a/examples/companion_radio/MyMesh.cpp b/examples/companion_radio/MyMesh.cpp index 7f81df74d..2ff0c856e 100644 --- a/examples/companion_radio/MyMesh.cpp +++ b/examples/companion_radio/MyMesh.cpp @@ -7491,10 +7491,45 @@ void MyMesh::handleCmdFrame(size_t len) { && !memcmp(wire_channel.channel.secret, previous_wire_channel.channel.secret, sizeof(channel.channel.secret))) { channel.channel.tx_radio = previous.channel.tx_radio; } + const char* preset = companionChannelRadio2Preset(channel.name); + const char* previous_preset = companionChannelRadio2Preset(previous.name); + // A join or rename selects the saved preset, just like set radio2. App + // replays/key edits must not undo a later manual Off or custom RF setting. + const bool setup_preset = have_previous && preset + && (!previous_preset || strcmp(preset, previous_preset)); + if (setup_preset) { +#if !MESH_ENABLE_MESHTEXT_CHAT + // Even without the foreign-protocol backend, do not turn old fallback + // mt- channels into inactive protocol requests as a hidden side effect. + for (int i = 0; i < MAX_GROUP_CHANNELS; ++i) { + ChannelDetails other; + if (i != channel_idx && BaseChatMesh::getChannel(i, other) + && parseCompanionChannelAlias(other.name).kind == CompanionChannelKind::Meshtext) { + writeErrFrame(ERR_CODE_BAD_STATE); + return; + } + } +#endif + if (!_radio_profiles.stageChannelPreset(preset)) { + writeErrFrame(ERR_CODE_BAD_STATE); + return; + } + } if (!have_previous || !setChannel(channel_idx, channel)) { + if (setup_preset) _radio_profiles.finishChannelPreset(false); writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx } else if (saveChannels()) { + if (setup_preset && !_radio_profiles.finishChannelPreset(true)) { + // Never report a complete setup when the RF image did not commit. + // Restore the channel when storage permits; report failure even if + // an indeterminate channels write has quarantined further saves. + setChannel(channel_idx, previous); + saveChannels(); + _radio_profiles.finishChannelPreset(false); + writeErrFrame(ERR_CODE_FILE_IO_ERROR); + return; + } #if MESH_ENABLE_MESHTEXT_CHAT _mt_seen.clear(); _mt_profile_dirty = true; @@ -7509,6 +7544,7 @@ void MyMesh::handleCmdFrame(size_t len) { // commit this update, and never acknowledge a change that will disappear // after reboot. setChannel(channel_idx, previous); + if (setup_preset) _radio_profiles.finishChannelPreset(false); writeErrFrame(ERR_CODE_FILE_IO_ERROR); } } else if (cmd_frame[0] == CMD_SIGN_START) { diff --git a/src/helpers/CompanionChannelAlias.h b/src/helpers/CompanionChannelAlias.h index af0f9846c..7c434b595 100644 --- a/src/helpers/CompanionChannelAlias.h +++ b/src/helpers/CompanionChannelAlias.h @@ -3,6 +3,7 @@ #include #include #include +#include // Local labels, not part of a hashtag PSK. Keep the original app label/key. enum class CompanionChannelKind : uint8_t { MeshCore, Radio2, Meshtext, Invalid }; @@ -30,6 +31,14 @@ inline CompanionChannelAlias parseCompanionChannelAlias(const char* name) { return {kind, hashtag, tail}; } +// Only exact named radio2 aliases request RF setup. Ordinary channels and +// arbitrary r2 labels keep the operator's existing profile. +inline const char* companionChannelRadio2Preset(const char* name) { + const auto alias = parseCompanionChannelAlias(name); + return alias.kind == CompanionChannelKind::Radio2 + && mesh::cli::radio2PresetTuple(alias.tail) ? alias.tail : nullptr; +} + inline bool companionChannelCanonicalName(const char* name, char* out, size_t size) { if (out == nullptr) return false; const auto alias = parseCompanionChannelAlias(name); diff --git a/src/helpers/RadioProfileCLI.cpp b/src/helpers/RadioProfileCLI.cpp index 4b790912b..60facf08a 100644 --- a/src/helpers/RadioProfileCLI.cpp +++ b/src/helpers/RadioProfileCLI.cpp @@ -746,6 +746,29 @@ bool RadioProfileCLI::finishReplyMutation(bool delivered) { || !fs_ || !fs_->exists(ReplyPath) || fs_->remove(ReplyPath); } +bool RadioProfileCLI::stageChannelPreset(const char* name) { + if (!name || !cli::radio2PresetTuple(name) || remote_command_ + || !secondaryRuntimeAvailable()) return false; + const auto& secondary = radio_->profiles()->secondary; + if (secondary.mode != RadioProfileMode::Off + && secondary.params.protocol != RadioProfileProtocol::MeshCore) return false; + char command[48], reply[160]; + snprintf(command, sizeof(command), "set radio2 %s", name); + beginReplyCommand(); + const bool handled = handle(command, reply, sizeof(reply)); + endReplyCommand(); + return handled && !strncmp(reply, "OK", 2) + && remote_mutation_ == RemoteMutation::Saved; +} + +bool RadioProfileCLI::finishChannelPreset(bool commit) { + if (remote_command_ || remote_mutation_ != RemoteMutation::Saved) return false; + if (!commit) return finishReplyMutation(false); + if (!applyReplyMutation()) return false; + publish_after_ms_ = millis() + 2000; + return true; +} + #if MESH_ENABLE_FLEET_CONTROL bool RadioProfileCLI::stageRemoteSchedule(unsigned slot, const Schedule& schedule) { if (slot >= 4 || !stageRemoteMutation(schedule.temporary diff --git a/src/helpers/RadioProfileCLI.h b/src/helpers/RadioProfileCLI.h index 5fe0bae40..2273d2701 100644 --- a/src/helpers/RadioProfileCLI.h +++ b/src/helpers/RadioProfileCLI.h @@ -163,7 +163,12 @@ 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 + // A channel join can stage a named preset before its channel save. Commit + // synchronously only after that save succeeds; cancellation leaves saved + // RF intent and the running modem unchanged. + bool stageChannelPreset(const char* name); + bool finishChannelPreset(bool commit); + // Passive RF borrowing is RAM-only and never replaces explicit saved // settings (including Off). Repeated identical requests do not retune. bool requestAutoSecondary(const RadioProfileConfig& config); void clearAutoSecondary(); diff --git a/test/fixtures/companion_meshtext.cpp b/test/fixtures/companion_meshtext.cpp index 2a14e8408..70103d83b 100644 --- a/test/fixtures/companion_meshtext.cpp +++ b/test/fixtures/companion_meshtext.cpp @@ -2,6 +2,7 @@ // production method bodies; all boundary substitutes are visible below. @FIXTURE@ #include +#include #include #include #include @@ -497,6 +498,99 @@ static void commands() { applySet(node,0,{}); assert(node.ok && !node._mt_active && !node.radio.p.enabled()); assertUntouched(node); puts("PASS commands"); } +static void assertMediaMeshConfig(const mesh::RadioProfileConfig& config,float bandwidth) { + assert(config.mode==mesh::RadioProfileMode::RxTx); + assert(std::fabs(config.params.freq-911.150f)<0.0001f && config.params.bw==bandwidth); + assert(config.params.sf==7 && config.params.cr==5 && !config.params.preamble); + assert(config.params.protocol==mesh::RadioProfileProtocol::MeshCore); +} +static void channelPresets() { + // These use the actual binary command branch and RadioProfileCLI image + // writer. Channel persistence itself remains this fixture's save boundary. + for(bool range:{false,true}) { + Preferences::reset(); MyMesh node; node.beginMeshtext(); + const auto primary=node.radio.p.primary; + const auto requested=channel(range?"r2-mediamesh-range":"#r2-mediamesh"); + applySet(node,0,requested); + assert(node.ok && node.error==-1 && !node.radio.p.enabled()); + assertMediaMeshConfig(node._radio_profiles.savedSecondaryConfig(),range?125:250); + assert(node._radio_profiles.manualSecondaryConfigured() && node.fs.files.count("/radio_profiles")); + assert(!node._radio_profiles.hasReplyMutation() && !node.fs.files.count("/radio_profiles.reply")); + ChannelDetails raw; assert(node.getChannelForSave(0,raw)); + assert(!strcmp(raw.name,requested.name) && !memcmp(raw.channel.secret,requested.channel.secret,32)); + node.advance(1999); assert(!node.radio.p.enabled()); + node.advance(1); assertMediaMeshConfig(node.radio.p.secondary,range?125:250); + assert(node.radio.p.primary==primary && node.radio.p.cross==mesh::RadioCrossMode::Off); + assert(!node.radio.p.secondary_temporary && !node._mt_active); + MyMesh reboot; reboot.fs=node.fs; reboot.stored[0]=raw; + reboot._radio_profiles.begin(&reboot.fs,&reboot.radio,&reboot.clock); reboot.beginMeshtext(); + assertMediaMeshConfig(reboot.radio.p.secondary,range?125:250); + assert(reboot._radio_profiles.manualSecondaryConfigured() && !reboot._mt_active); + assertUntouched(node); assertUntouched(reboot); + } + + Preferences::reset(); MyMesh node; node.beginMeshtext(); + applySet(node,0,channel("#r2-mediamesh")); assert(node.ok); node.advance(2000); + // The newest join/rename chooses the tuple, even with another named alias + // present. Names do not continuously force RF over later operator choices. + applySet(node,1,channel("#r2-mediamesh-range")); assert(node.ok); + assertMediaMeshConfig(node._radio_profiles.savedSecondaryConfig(),125); + assertMediaMeshConfig(node.radio.p.secondary,250); + node.advance(2000); assertMediaMeshConfig(node.radio.p.secondary,125); + auto renamed=channel("r2-mediamesh",16); + applySet(node,1,renamed); assert(node.ok); + assertMediaMeshConfig(node._radio_profiles.savedSecondaryConfig(),250); + assertMediaMeshConfig(node.radio.p.secondary,125); + node.advance(2000); assertMediaMeshConfig(node.radio.p.secondary,250); + for(const char* command:{"set radio2 off","set radio2 912.5,250,8,5,rx,80"}) { + node.cli(command); node.advance(2000); + const auto saved=node._radio_profiles.savedSecondaryConfig(); + const auto running=node.radio.p.secondary; + const auto disk=node.fs.files; + for(bool edit_key:{false,true}) { + if(edit_key) renamed.channel.secret[0]^=0x80; + applySet(node,1,renamed); assert(node.ok); + assert(node._radio_profiles.savedSecondaryConfig().mode==saved.mode + && node._radio_profiles.savedSecondaryConfig().params==saved.params); + node.advance(2000); + assert(node.radio.p.secondary.mode==running.mode && node.radio.p.secondary.params==running.params); + assert(node.fs.files==disk && !node._radio_profiles.hasReplyMutation()); + } + } + assertUntouched(node); + + for(bool fail_rf_commit:{false,true}) { + Preferences::reset(); MyMesh failed; failed.beginMeshtext(); + failed.cli("set radio2 912.5,250,8,5,rx,80"); failed.advance(2000); + failed.commit(0,channel("ordinary",16)); + const auto old_channel=failed.stored[0]; + const auto old_profile=failed.radio.p.secondary; + const auto old_disk=failed.fs.files; + if(fail_rf_commit) failed.fs.fail_rename_from={"/radio_profiles.reply"}; + else failed.save_result=false; + applySet(failed,0,channel("#r2-mediamesh")); + assert(!failed.ok && failed.error==ERR_CODE_FILE_IO_ERROR); + assert(!strcmp(failed.stored[0].name,old_channel.name) + && !memcmp(failed.stored[0].channel.secret,old_channel.channel.secret,32) + && failed.stored[0].channel.tx_radio==old_channel.channel.tx_radio); + assert(failed.fs.files==old_disk && !failed._radio_profiles.hasReplyMutation()); + assert(failed._radio_profiles.savedSecondaryConfig().mode==old_profile.mode + && failed._radio_profiles.savedSecondaryConfig().params==old_profile.params); + failed.advance(2000); + assert(failed.radio.p.secondary.mode==old_profile.mode && failed.radio.p.secondary.params==old_profile.params); + assertUntouched(failed); + } + Preferences::reset(); MyMesh conflicting; active(conflicting); + const auto old_profile=conflicting.radio.p.secondary; + const auto old_disk=conflicting.fs.files; + applySet(conflicting,1,channel("#r2-mediamesh")); + assert(!conflicting.ok && conflicting.error==ERR_CODE_BAD_STATE && !conflicting.stored[1].name[0]); + assert(conflicting.radio.p.secondary.mode==old_profile.mode + && conflicting.radio.p.secondary.params==old_profile.params); + assert(conflicting.fs.files==old_disk && conflicting._mt_active); + assert(!conflicting._radio_profiles.hasReplyMutation()); assertUntouched(conflicting); + puts("PASS channel-presets"); +} static void privateCLI() { Preferences::reset(); MyMesh node; node.beginMeshtext(); char reply[256]; const char* key128="0102030405060708090a0b0c0d0e0f10"; @@ -1646,6 +1740,7 @@ int main(int argc,char** argv) { else if(!strcmp(argv[1],"receive"))receive(); else if(!strcmp(argv[1],"transmit"))transmit(); else if(!strcmp(argv[1],"commands"))commands(); + else if(!strcmp(argv[1],"channel-presets"))channelPresets(); else if(!strcmp(argv[1],"cli"))privateCLI(); else if(!strcmp(argv[1],"hops"))hops(); else if(!strcmp(argv[1],"shortname"))shortname(); diff --git a/test/fixtures/radio_profiles/cli_test.cpp b/test/fixtures/radio_profiles/cli_test.cpp index 2d847332d..953cf35b5 100644 --- a/test/fixtures/radio_profiles/cli_test.cpp +++ b/test/fixtures/radio_profiles/cli_test.cpp @@ -548,6 +548,168 @@ static void mediaMeshPresets() { assert(!invalid.radio.p.enabled() && invalid.fs.files.empty()); } +static void channelPresetTransaction() { + for (bool range : {false, true}) { + Fixture f; + assert(f.cli.savePrimaryPreamble(48)); + f.cli.stagePrimary(48, false); + f.cmd("set radio2.cross on"); + f.cmd("set radio2 910.5,500,8,5,rxtx,80"); f.advance(2000); + const auto primary = f.radio.p.primary; + const auto previous = f.radio.p.secondary; + const auto previous_image = f.fs.files["/radio_profiles"]; + const uint32_t intent = f.cli.secondaryIntentGeneration(); + assert(f.cli.stageChannelPreset(range ? "mediamesh-range" : "mediamesh")); + assert(f.cli.hasReplyMutation() && f.fs.exists("/radio_profiles.reply")); + assert(f.fs.files["/radio_profiles"] == previous_image); + assert(f.cli.savedSecondaryConfig().params == previous.params); + assert(f.radio.p.secondary.params == previous.params); + f.advance(100); // A staged channel save has no permission to publish yet. + assert(f.radio.p.secondary.params == previous.params); + assert(f.cli.secondaryIntentGeneration() == intent); + assert(f.cli.finishChannelPreset(true)); + assert(!f.cli.hasReplyMutation() && !f.fs.exists("/radio_profiles.reply")); + assert(f.cli.secondaryIntentGeneration() == intent + 1); + const auto saved = f.cli.savedSecondaryConfig(); + assert(saved.mode == mesh::RadioProfileMode::RxTx); + assert(fabsf(saved.params.freq - 911.150f) < 0.0001f); + assert(saved.params.bw == (range ? 125 : 250)); + assert(saved.params.sf == 7 && saved.params.cr == 5 && !saved.params.preamble); + assert(saved.params.protocol == mesh::RadioProfileProtocol::MeshCore); + // The pair is durable before acknowledging the channel, while the radio + // retains the ordinary saved setter's two-second application delay. + Radio reboot; mesh::RadioProfileCLI restored; + restored.begin(&f.fs, &reboot, &f.clock); + assert(reboot.p.secondary.params == saved.params); + assert(reboot.p.secondary.mode == saved.mode); + assert(reboot.p.primary == primary && reboot.p.cross == mesh::RadioCrossMode::On); + f.advance(1999); + assert(f.radio.p.secondary.params == previous.params); + f.advance(1); + assert(f.radio.p.secondary.params == saved.params && f.radio.p.secondary.mode == saved.mode); + assert(f.radio.p.primary == primary && f.radio.p.cross == mesh::RadioCrossMode::On); + assert(!f.cli.finishChannelPreset(true) && !f.cli.finishChannelPreset(false)); + } + { + Fixture f; + f.cmd("set radio2 off"); f.advance(2000); + const auto before = f.fs.files; + const uint32_t intent = f.cli.secondaryIntentGeneration(); + assert(f.cli.stageChannelPreset("mediamesh")); + assert(f.cli.finishChannelPreset(false)); // The channel save failed. + assert(!f.cli.hasReplyMutation() && f.fs.files == before); + assert(f.cli.secondaryIntentGeneration() == intent); + f.advance(2000); + assert(!f.radio.p.enabled() && f.cli.savedSecondaryConfig().mode == mesh::RadioProfileMode::Off); + Radio reboot; mesh::RadioProfileCLI restored; + restored.begin(&f.fs, &reboot, &f.clock); + assert(!reboot.p.enabled()); + } + for (int fail_rename : {1, 2}) { + Fixture f; + f.cmd("set radio2 910.5,500,8,5,rx,80"); f.advance(2000); + const auto before = f.fs.files; + const auto previous = f.radio.p.secondary; + const uint32_t intent = f.cli.secondaryIntentGeneration(); + assert(f.cli.stageChannelPreset("mediamesh-range")); + f.fs.fail_rename = fail_rename; + assert(!f.cli.finishChannelPreset(true)); + assert(f.cli.hasReplyMutation()); + assert(f.radio.p.secondary.params == previous.params); + assert(f.cli.savedSecondaryConfig().params == previous.params); + assert(f.cli.secondaryIntentGeneration() == intent); + assert(f.cli.finishChannelPreset(false)); + assert(f.fs.files == before && !f.cli.hasReplyMutation()); + f.advance(2000); + assert(f.radio.p.secondary.params == previous.params); + Radio reboot; mesh::RadioProfileCLI restored; + restored.begin(&f.fs, &reboot, &f.clock); + assert(reboot.p.secondary.params == previous.params && reboot.p.secondary.mode == previous.mode); + } + { + Fixture f; + const char* invalid_names[] = {nullptr, "", "MediaMesh", "mediamesh-extra", + "mediamesh,32", "911.150,250,7,5,rxtx"}; + for (const char* name : invalid_names) { + assert(!f.cli.stageChannelPreset(name)); + assert(!f.cli.hasReplyMutation() && f.fs.files.empty()); + } + f.radio.minimum_frequency = 912; + assert(!f.cli.stageChannelPreset("mediamesh")); + assert(!f.cli.hasReplyMutation() && f.fs.files.empty()); + f.radio.minimum_frequency = 137; + f.fs.fail_write = true; + assert(!f.cli.stageChannelPreset("mediamesh")); + assert(!f.cli.hasReplyMutation() && !f.radio.p.enabled()); + assert(!f.fs.exists("/radio_profiles")); + } + { + Fixture f; + mesh::RadioProfileCLI unsupported; + unsupported.begin(&f.fs, nullptr, &f.clock); + assert(!unsupported.stageChannelPreset("mediamesh")); + assert(!unsupported.finishChannelPreset(true) && f.fs.files.empty()); + } + for (auto protocol : {mesh::RadioProfileProtocol::Meshtext, + mesh::RadioProfileProtocol::Kiss, mesh::RadioProfileProtocol::Ethernet}) { + Fixture f; + mesh::RadioProfileConfig foreign; + foreign.mode = mesh::RadioProfileMode::RxTx; + foreign.params.freq = 911.5; foreign.params.bw = 250; + foreign.params.sf = 7; foreign.params.cr = 5; foreign.params.protocol = protocol; + f.radio.p.setSecondary(foreign, false); + assert(!f.cli.stageChannelPreset("mediamesh")); + assert(!f.cli.hasReplyMutation() && f.fs.files.empty()); + assert(f.radio.p.secondary.params == foreign.params); + } +#if MESH_ENABLE_MESHTEXT_CHAT || MESH_ENABLE_ETHERNET_TUNNEL || MESH_ENABLE_HOST_KISS + { + Fixture f; + mesh::RadioProfileConfig foreign; + foreign.mode = mesh::RadioProfileMode::RxTx; + foreign.params.freq = 911.5; foreign.params.bw = 250; + foreign.params.sf = 7; foreign.params.cr = 5; + foreign.params.protocol = mesh::RadioProfileProtocol::Meshtext; + assert(f.cli.requestAutoSecondary(foreign)); + assert(!f.cli.stageChannelPreset("mediamesh")); + assert(f.cli.autoSecondaryActive() && f.fs.files.empty()); + // A separately leased MeshCore tuple must also remain protected after + // an automatic owner observes an external generation change. + foreign.params.protocol = mesh::RadioProfileProtocol::MeshCore; + f.radio.p.setSecondary(foreign, false); + assert(!f.cli.stageChannelPreset("mediamesh")); + assert(!f.cli.hasReplyMutation() && f.fs.files.empty()); + assert(f.radio.p.secondary.params == foreign.params); + } +#endif + for (unsigned busy = 0; busy < 5; ++busy) { + Fixture f; + if (busy == 0) f.radio.p.primary_temporary = true; + else if (busy == 1) f.cmd("set tempradio2 910.5,500,8,5,rx,1,80"); + else if (busy == 2) { f.cmd("set tempradio2 910.5,500,8,5,rx,1,80"); f.advance(2000); } + else if (busy == 3) f.cmd("set radioat2 910.5,500,8,5,rx,+1,80"); + else f.cmd("set radio2 910.5,500,8,5,rx,80"); + const auto before = f.fs.files; + assert(!f.cli.stageChannelPreset("mediamesh")); + assert(!f.cli.hasReplyMutation() && f.fs.files == before); + } + { + Fixture f; + f.cli.beginReplyCommand(); + assert(!f.cli.stageChannelPreset("mediamesh")); + f.cmd("set radio2 mediamesh-range"); + f.cli.endReplyCommand(); + const auto before = f.fs.files; + const uint32_t generation = f.cli.replyMutationGeneration(); + assert(!f.cli.stageChannelPreset("mediamesh")); + assert(!f.cli.stageChannelPreset("invalid")); + assert(f.cli.hasReplyMutation() && f.cli.replyMutationGeneration() == generation); + assert(f.fs.files == before); // Failed staging cannot cancel the remote ACK owner. + assert(f.cli.finishReplyMutation(true)); f.advance(1); + assert(!f.cli.hasReplyMutation() && f.radio.p.secondary.params.bw == 125); + } +} + struct MediaScope { bool available = true, fail_save = false, enabled = false, durable = false; unsigned checks = 0, commits = 0; @@ -731,6 +893,7 @@ int main(int argc, char** argv) { else if (!strcmp(argv[1], "relative_schedule")) relativeSchedules(); else if (!strcmp(argv[1], "spectrum_overlap")) spectrumOverlap(); else if (!strcmp(argv[1], "mediamesh")) mediaMeshPresets(); + else if (!strcmp(argv[1], "channel_preset")) channelPresetTransaction(); else if (!strcmp(argv[1], "media_scope")) mediaMeshScopeLifecycle(); else return 2; return 0; diff --git a/test/test_companion_channel_alias.py b/test/test_companion_channel_alias.py index dcfafe675..39acaf50c 100644 --- a/test/test_companion_channel_alias.py +++ b/test/test_companion_channel_alias.py @@ -17,6 +17,8 @@ HASH_NAMES = ( "#emergency", "#r2-emergency", "#mt-emergency", "#custom", "#r2-custom", "#mt-custom", "#EMERGENCY", "#Emergency", "emergency", "Emergency", "#emergency-test", + "#mediamesh", "#r2-mediamesh", "r2-mediamesh", + "#mediamesh-range", "#r2-mediamesh-range", "r2-mediamesh-range", ) HARNESS = r''' @@ -80,6 +82,18 @@ static void grammar() { "#r2-r2-room", "#r2-mt-room", "#mt-r2-room", "#mt-mt-room"}) { assert(parseCompanionChannelAlias(name).kind == CompanionChannelKind::Invalid); } + for (const char* name : {"#r2-mediamesh", "r2-mediamesh", + "#r2-mediamesh-range", "r2-mediamesh-range"}) { + const auto alias = parseCompanionChannelAlias(name); + assert(companionChannelRadio2Preset(name)); + assert(!strcmp(companionChannelRadio2Preset(name), alias.tail)); + } + for (const char* name : {"#mediamesh", "mediamesh", "#mt-mediamesh", + "#r2-MediaMesh", "#r2-mediamesh-extra", "#r2-mediamesh,32", + "#r2-mt-mediamesh", "#r2-", ""}) { + assert(!companionChannelRadio2Preset(name)); + } + assert(!companionChannelRadio2Preset(nullptr)); puts("PASS grammar"); } static void canonical() { @@ -391,6 +405,22 @@ struct Serial { COMMAND_MEMBERS = r''' Serial serial; Serial* _serial = &serial; + struct ProfileSetup { + bool stage_ok = true, commit_ok = true, pending = false; + unsigned stages = 0, commits = 0, cancels = 0; + char requested[32] = {}; + bool stageChannelPreset(const char* name) { + ++stages; + if (!stage_ok) return false; + strcpy(requested, name); pending = true; return true; + } + bool finishChannelPreset(bool commit) { + assert(pending); + if (commit) { ++commits; if (!commit_ok) return false; } + else ++cancels; + pending = false; return true; + } + } _radio_profiles; bool save_result = true, ok = false; int error = -1; unsigned save_calls = 0; bool saveChannels() { ++save_calls; return save_result; } void writeErrFrame(uint8_t code) { error = code; } @@ -985,7 +1015,7 @@ class CompanionChannelAliasTest(unittest.TestCase): "@KEY_VECTORS@", key_vectors).replace("@METHODS@", methods).replace("@SAVE_GETTER@", save_getter) self.run_native_program(source_text, "runtime") - def test_production_binary_get_set_raw_keys_and_rollback(self): + def binary_channel_program(self, cases=None): companion = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text(encoding="utf-8") header = (ROOT / "examples/companion_radio/MyMesh.h").read_text(encoding="utf-8") signatures = ("bool MyMesh::isAliasRadio2Defined(", "bool MyMesh::resolveChannelAlias(", @@ -1000,7 +1030,7 @@ class CompanionChannelAliasTest(unittest.TestCase): branches = " else ".join(body(companion, signature) for signature in command_signatures) macros = ("CMD_GET_CHANNEL", "CMD_SET_CHANNEL", "RESP_CODE_CHANNEL_INFO", "ERR_CODE_UNSUPPORTED_CMD", "ERR_CODE_NOT_FOUND", "ERR_CODE_FILE_IO_ERROR", - "ERR_CODE_ILLEGAL_ARG") + "ERR_CODE_ILLEGAL_ARG", "ERR_CODE_BAD_STATE") constants = "\n".join(re.search(r"^#define\s+" + name + r"\s+[^\r\n]+", companion, flags=re.MULTILINE).group(0) for name in macros) shared = HARNESS[:HARNESS.index("static void assertAlias(")] @@ -1008,10 +1038,86 @@ class CompanionChannelAliasTest(unittest.TestCase): fixture = fixture.replace("class MyMesh :", COMMAND_STUBS + "\nclass MyMesh :") fixture = fixture.replace("@SAVE_GETTER@", save_getter + "\n" + COMMAND_MEMBERS) vectors, key_vectors = oracle_vectors() - source_text = (shared + constants + "\n" + fixture + COMMAND_HARNESS).replace( + commands = COMMAND_HARNESS if cases is None else ( + COMMAND_HARNESS[:COMMAND_HARNESS.index("\nint main() {")] + cases) + source_text = (shared + constants + "\n" + fixture + commands).replace( "@VECTORS@", vectors).replace("@KEY_VECTORS@", key_vectors).replace( "@METHODS@", methods).replace("@COMMAND_BRANCHES@", branches) - self.run_native_program(source_text, "command") + return source_text + + def test_production_binary_get_set_raw_keys_and_rollback(self): + self.run_native_program(self.binary_channel_program(), "command") + + def test_mediamesh_joins_stage_setup_and_ack_only_after_both_saves(self): + cases = r''' +int main() { + for (const char* name : {"#r2-mediamesh", "r2-mediamesh", + "#r2-mediamesh-range", "r2-mediamesh-range"}) { + MyMesh node; + auto joined = channel(name); + applySet(node,0,joined); + assert(node.ok && node.error==-1 && node.save_calls==1); + expectRaw(node,0,joined); + expectGet(node,0,joined); + const char* preset=companionChannelRadio2Preset(name); + assert(node._radio_profiles.stages==1 && node._radio_profiles.commits==1); + assert(!node._radio_profiles.pending && !strcmp(node._radio_profiles.requested,preset)); + // App replay, key edit and hashtag-only rename are not new preset choices. + applySet(node,0,joined); + for(unsigned i=0;i<16;++i)joined.channel.secret[i]=uint8_t(i+1); + applySet(node,0,joined); + strcpy(joined.name,name[0]=='#' ? name+1 : (strstr(name,"-range") ? "#r2-mediamesh-range":"#r2-mediamesh")); + applySet(node,0,joined); + assert(node.ok && node._radio_profiles.stages==1); + // A different newly joined preset selects radio2 even if another named + // channel remains in its slot; there is only one shared radio2 profile. + auto other=channel(strstr(name,"-range") ? "#r2-mediamesh":"#r2-mediamesh-range"); + applySet(node,1,other); + assert(node.ok && node._radio_profiles.stages==2 && node._radio_profiles.commits==2); + assert(!strcmp(node._radio_profiles.requested,companionChannelRadio2Preset(other.name))); + ChannelDetails empty{};applySet(node,1,empty); + assert(node.ok && node._radio_profiles.stages==2); // removal is not radio2 Off + applySet(node,1,other); + assert(node.ok && node._radio_profiles.stages==3); + } + for(bool stage_fail:{false,true}) { + MyMesh node;const auto before=channel("#custom");assert(node.setChannel(0,before)); + node._radio_profiles.stage_ok=!stage_fail;node.save_result=stage_fail; + applySet(node,0,channel("#r2-mediamesh")); + assert(!node.ok && node.error==(stage_fail ? ERR_CODE_BAD_STATE:ERR_CODE_FILE_IO_ERROR)); + assert(node.save_calls==(stage_fail ? 0u:1u));expectRaw(node,0,before); + assert(!node._radio_profiles.pending && node._radio_profiles.commits==0); + assert(node._radio_profiles.cancels==(stage_fail ? 0u:1u)); + } + { + MyMesh node;const auto before=channel("#custom");assert(node.setChannel(0,before)); + node._radio_profiles.commit_ok=false; + applySet(node,0,channel("#r2-mediamesh-range")); + assert(!node.ok && node.error==ERR_CODE_FILE_IO_ERROR && node.save_calls==2); + expectRaw(node,0,before);assert(!node._radio_profiles.pending && node._radio_profiles.cancels==1); + } + { + // An mt- fallback label on a build without Meshtext must not be made + // unusable by silently enabling radio2 with another channel's join. + MyMesh node;const auto mt=channel("#mt-emergency");assert(node.setChannel(1,mt)); + applySet(node,0,channel("#r2-mediamesh")); + assert(!node.ok && node.error==ERR_CODE_BAD_STATE); + assert(!node._radio_profiles.stages && !node.save_calls);expectRaw(node,1,mt); + } + { + MyMesh node;applySet(node,MAX_GROUP_CHANNELS,channel("#r2-mediamesh")); + assert(!node.ok && node.error==ERR_CODE_NOT_FOUND && !node._radio_profiles.stages); + for(const char* name:{"#mediamesh","#r2-custom","#r2-emergency"}) { + applySet(node,0,channel(name));assert(node.ok && !node._radio_profiles.stages); + } + // Disk loading has no RF side effect. An operator's later Off remains Off. + assert(node.setChannel(1,channel("#r2-mediamesh"))); + assert(!node._radio_profiles.stages); + } + puts("PASS mediamesh-join"); +} +''' + self.run_native_program(self.binary_channel_program(cases), "mediamesh-join") def test_production_binary_get_zero_pads_dirty_fixed_width_name(self): companion = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text(encoding="utf-8") diff --git a/test/test_companion_channel_publication.py b/test/test_companion_channel_publication.py index a536b5bb2..993be28cc 100644 --- a/test/test_companion_channel_publication.py +++ b/test/test_companion_channel_publication.py @@ -115,6 +115,13 @@ struct StrHelper { #endif """, 1) source = source.replace(" bool handleTxRoutingCommand(const char*,char*,size_t);", """ + using BaseChatMesh = MyMesh; + // This publication fixture only mutates ordinary channels. RF preset + // behavior is exercised with the real CLI by the Meshtext fixture. + struct { + bool stageChannelPreset(const char*) { assert(false); return false; } + bool finishChannelPreset(bool) { assert(false); return false; } + } _radio_profiles; bool handleTxRoutingCommand(const char*,char*,size_t); int last_error = 0; bool binary_ack = false; diff --git a/test/test_companion_meshtext.py b/test/test_companion_meshtext.py index 7980f8a89..f07311aa2 100644 --- a/test/test_companion_meshtext.py +++ b/test/test_companion_meshtext.py @@ -213,6 +213,9 @@ class CompanionMeshtextTest(unittest.TestCase): def test_binary_get_set_raw_psk_and_save_failure_rollback(self): self.run_case("commands") + def test_binary_mediamesh_presets_commit_delay_replay_and_failure_rollback(self): + self.run_case("channel-presets") + def test_private_cli_provisioning_metadata_masking_and_transactional_delete(self): self.run_case("cli") diff --git a/test/test_radio_profile_cli.py b/test/test_radio_profile_cli.py index 4166d7512..2b5000893 100644 --- a/test/test_radio_profile_cli.py +++ b/test/test_radio_profile_cli.py @@ -9,6 +9,22 @@ import unittest ROOT = Path(__file__).resolve().parents[1] class RadioProfileCLITest(unittest.TestCase): + def test_channel_preset_preserves_secondary_owners(self): + compiler = shutil.which('g++') or shutil.which('clang++') + self.assertIsNotNone(compiler) + with tempfile.TemporaryDirectory(prefix='profile-channel-owner-') as work: + binary = Path(work) / 'channel-owner' + compiled = subprocess.run([ + compiler, '-std=c++17', '-Wall', '-Wextra', + '-DMESH_ENABLE_MESHTEXT_CHAT=1', + '-I', str(ROOT/'test/fixtures/radio_profiles/mocks'), + '-I', str(ROOT/'test/mocks'), '-I', str(ROOT/'src'), + str(ROOT/'src/helpers/RadioProfileCLI.cpp'), + str(ROOT/'test/fixtures/radio_profiles/cli_test.cpp'), + '-o', str(binary)], capture_output=True, text=True, timeout=60) + self.assertEqual(compiled.returncode, 0, compiled.stderr) + subprocess.run([str(binary), 'channel_preset'], check=True, timeout=10) + def test_all_companions_keep_rf_presets_without_unused_region_code(self): compiler = shutil.which('g++') or shutil.which('clang++') self.assertIsNotNone(compiler) @@ -80,7 +96,8 @@ int main() { '-o', str(exe)], check=True, capture_output=True, text=True) for scenario in (None, 'permanent_order', 'temporary_boundary', 'lease_creation', 'save_failure', 'schedule_permutations', 'storage_isolation', - 'relative_schedule', 'spectrum_overlap', 'mediamesh', 'media_scope'): + 'relative_schedule', 'spectrum_overlap', 'mediamesh', 'channel_preset', + 'media_scope'): with self.subTest(fleet=fleet_enabled, carrier=carrier_enabled, scenario=scenario or 'commands_persistence_and_timers'): subprocess.run([str(exe)] + ([scenario] if scenario else []), check=True)