commit
2ca7974738
@ -0,0 +1,244 @@
|
||||
{
|
||||
"format": "meshcore-upstream-radio-presets",
|
||||
"format_version": 1,
|
||||
"source": "https://api.meshcore.nz/api/v1/config",
|
||||
"credit": "Radio presets maintained by Liam Cottle for MeshCore (meshcore.nz), the list the stock MeshCore app shows. Mirrored unmodified from https://api.meshcore.nz/api/v1/config. Offband's own additions live in offband.json. Credit: https://github.com/OffbandMesh/config-profiles#credit",
|
||||
"updated_at": "2026-10-01T07:48:36Z",
|
||||
"suggested_radio_settings": {
|
||||
"info_message": "These presets are suggested by the community.",
|
||||
"entries": [
|
||||
{
|
||||
"title": "Australia",
|
||||
"description": "915.800MHz / SF10 / BW250 / CR5",
|
||||
"frequency": "915.800",
|
||||
"spreading_factor": "10",
|
||||
"bandwidth": "250",
|
||||
"coding_rate": "5"
|
||||
},
|
||||
{
|
||||
"title": "Australia (Narrow)",
|
||||
"description": "916.575MHz / SF7 / BW62.5 / CR7",
|
||||
"frequency": "916.575",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "7"
|
||||
},
|
||||
{
|
||||
"title": "Australia (Mid)",
|
||||
"description": "915.075MHz / SF9 / BW125 / CR5",
|
||||
"frequency": "915.075",
|
||||
"spreading_factor": "9",
|
||||
"bandwidth": "125",
|
||||
"coding_rate": "5"
|
||||
},
|
||||
{
|
||||
"title": "Australia: SA, WA",
|
||||
"description": "923.125MHz / SF8 / BW62.5 / CR8",
|
||||
"frequency": "923.125",
|
||||
"spreading_factor": "8",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "8"
|
||||
},
|
||||
{
|
||||
"title": "Australia: QLD",
|
||||
"description": "923.125MHz / SF8 / BW62.5 / CR5",
|
||||
"frequency": "923.125",
|
||||
"spreading_factor": "8",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "5"
|
||||
},
|
||||
{
|
||||
"title": "Brazil",
|
||||
"description": "923.125MHz / SF8 / BW62.5 / CR8",
|
||||
"frequency": "923.125",
|
||||
"spreading_factor": "8",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "8"
|
||||
},
|
||||
{
|
||||
"title": "Canada",
|
||||
"description": "910.525MHz / SF7 / BW62.5 / CR5 / 3B",
|
||||
"frequency": "910.525",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "5",
|
||||
"network_settings": {
|
||||
"path_hash_size": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Costa Rica",
|
||||
"description": "910.525MHz / SF11 / BW125 / CR5",
|
||||
"frequency": "910.525",
|
||||
"spreading_factor": "11",
|
||||
"bandwidth": "125",
|
||||
"coding_rate": "5"
|
||||
},
|
||||
{
|
||||
"title": "EU/UK (Narrow)",
|
||||
"description": "869.618MHz / SF8 / BW62.5 / CR8",
|
||||
"frequency": "869.618",
|
||||
"spreading_factor": "8",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "8"
|
||||
},
|
||||
{
|
||||
"title": "EU/UK (Deprecated)",
|
||||
"description": "869.525MHz / SF11 / BW250 / CR5",
|
||||
"frequency": "869.525",
|
||||
"spreading_factor": "11",
|
||||
"bandwidth": "250",
|
||||
"coding_rate": "5"
|
||||
},
|
||||
{
|
||||
"title": "Czech Republic (Narrow)",
|
||||
"description": "869.432MHz / SF7 / BW62.5 / CR5 / 2B",
|
||||
"frequency": "869.432",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "5",
|
||||
"network_settings": {
|
||||
"path_hash_size": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "EU 433MHz (Long Range)",
|
||||
"description": "433.650MHz / SF11 / BW250 / CR5",
|
||||
"frequency": "433.650",
|
||||
"spreading_factor": "11",
|
||||
"bandwidth": "250",
|
||||
"coding_rate": "5"
|
||||
},
|
||||
{
|
||||
"title": "EU 433MHz (Narrow)",
|
||||
"description": "433.650MHz / SF8 / BW62.5 / CR8",
|
||||
"frequency": "433.650",
|
||||
"spreading_factor": "8",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "8"
|
||||
},
|
||||
{
|
||||
"title": "Hungary",
|
||||
"description": "869.618MHz / SF7 / BW62.5 / CR5 / 2B",
|
||||
"frequency": "869.618",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "5",
|
||||
"network_settings": {
|
||||
"path_hash_size": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Netherlands",
|
||||
"description": "869.618MHz / SF7 / BW62.5 / CR5",
|
||||
"frequency": "869.618",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "5"
|
||||
},
|
||||
{
|
||||
"title": "Netherlands (Limburg)",
|
||||
"description": "869.618MHz / SF8 / BW62.5 / CR8 / 2B",
|
||||
"frequency": "869.618",
|
||||
"spreading_factor": "8",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "8",
|
||||
"network_settings": {
|
||||
"path_hash_size": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "New Zealand (Narrow)",
|
||||
"description": "917.375MHz / SF7 / BW62.5 / CR5 / 2B",
|
||||
"frequency": "917.375",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "5",
|
||||
"network_settings": {
|
||||
"path_hash_size": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "New Zealand (Gisborne)",
|
||||
"description": "917.375MHz / SF11 / BW250 / CR5 / 1B",
|
||||
"frequency": "917.375",
|
||||
"spreading_factor": "11",
|
||||
"bandwidth": "250",
|
||||
"coding_rate": "5",
|
||||
"network_settings": {
|
||||
"path_hash_size": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Portugal 433",
|
||||
"description": "433.375MHz / SF9 / BW62.5 / CR6",
|
||||
"frequency": "433.375",
|
||||
"spreading_factor": "9",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "6"
|
||||
},
|
||||
{
|
||||
"title": "Portugal 868",
|
||||
"description": "869.618MHz / SF7 / BW62.5 / CR6",
|
||||
"frequency": "869.618",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "6"
|
||||
},
|
||||
{
|
||||
"title": "Slovakia",
|
||||
"description": "869.618MHz / SF7 / BW62.5 / CR5 / 2B",
|
||||
"frequency": "869.618",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "5",
|
||||
"network_settings": {
|
||||
"path_hash_size": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Switzerland",
|
||||
"description": "869.618MHz / SF8 / BW62.5 / CR8",
|
||||
"frequency": "869.618",
|
||||
"spreading_factor": "8",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "8"
|
||||
},
|
||||
{
|
||||
"title": "USA",
|
||||
"description": "910.525MHz / SF7 / BW62.5 / CR5",
|
||||
"frequency": "910.525",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "5"
|
||||
},
|
||||
{
|
||||
"title": "USA - Southern California",
|
||||
"description": "927.875MHz / SF7 / BW62.5 / CR5 / 3B",
|
||||
"frequency": "927.875",
|
||||
"spreading_factor": "7",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "5",
|
||||
"network_settings": {
|
||||
"path_hash_size": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"title": "Vietnam (Narrow)",
|
||||
"description": "920.250MHz / SF8 / BW62.5 / CR5",
|
||||
"frequency": "920.250",
|
||||
"spreading_factor": "8",
|
||||
"bandwidth": "62.5",
|
||||
"coding_rate": "5"
|
||||
},
|
||||
{
|
||||
"title": "Vietnam (Deprecated)",
|
||||
"description": "920.250MHz / SF11 / BW250 / CR5",
|
||||
"frequency": "920.250",
|
||||
"spreading_factor": "11",
|
||||
"bandwidth": "250",
|
||||
"coding_rate": "5"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,407 @@
|
||||
{
|
||||
"format": "offband-radio-presets",
|
||||
"format_version": 1,
|
||||
"description": "Offband radio preset overlay. These entries are added to the MeshCore preset list mirrored in meshcore-upstream.json, and win over it when a title matches. Edit this file to add, change or retire a preset; the app picks the change up on its next refresh, with no app release. See SCHEMA.md.",
|
||||
"presets": [
|
||||
{
|
||||
"id": "usa-arizona",
|
||||
"title": "USA - Arizona",
|
||||
"region": "USA",
|
||||
"frequency": 908.205,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 9,
|
||||
"coding_rate": 8,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "SF9/CR8 per zjs81/meshcore-open#507 (Tucson / Phoenix alignment). Unconfirmed by an Arizona authority; owner decision 2026-10-01."
|
||||
},
|
||||
{
|
||||
"id": "usa-philly-mesh",
|
||||
"title": "USA - Philly Mesh",
|
||||
"region": "USA",
|
||||
"frequency": 919.5,
|
||||
"bandwidth": 500,
|
||||
"spreading_factor": 10,
|
||||
"coding_rate": 5,
|
||||
"tx_power": 20,
|
||||
"path_hash_size": 2,
|
||||
"status": "published",
|
||||
"notes": "phillymesh.net, 2026-10-01: 919.500 / 500 kHz / SF10 / CR 4/5 / path hash mode 1 (2-byte). Replaces their original 902.25 guidance. TX power not published; 20 dBm matches the US entries."
|
||||
},
|
||||
{
|
||||
"id": "usa-oki-mesh-500khz-test",
|
||||
"title": "USA - OKI-Mesh 500kHz Test",
|
||||
"region": "USA",
|
||||
"frequency": 909.75,
|
||||
"bandwidth": 500,
|
||||
"spreading_factor": 10,
|
||||
"coding_rate": 5,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "docs.okimesh.org 500kHz-testing (test started 2026-09-23). OKI has not settled on a frequency; expect this to change. TX power not published; 20 dBm matches the US entries."
|
||||
},
|
||||
{
|
||||
"id": "russia-artyom-vvo",
|
||||
"title": "Russia Artyom (VVO)",
|
||||
"region": "Russia",
|
||||
"frequency": 864.281,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 6,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-biysk-bsk",
|
||||
"title": "Russia Biysk (BSK)",
|
||||
"region": "Russia",
|
||||
"frequency": 869.0,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 5,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-chelyabinsk-cek",
|
||||
"title": "Russia Chelyabinsk (CEK)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.731,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 6,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-cherepovets-cee",
|
||||
"title": "Russia Cherepovets (CEE)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.57,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 7,
|
||||
"coding_rate": 8,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-irkutsk-ikt",
|
||||
"title": "Russia Irkutsk (IKT)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.731,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 7,
|
||||
"coding_rate": 7,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-ivanovo-iwa",
|
||||
"title": "Russia Ivanovo (IWA)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.731,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 8,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-izhevsk-ijk",
|
||||
"title": "Russia Izhevsk (IJK)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.732,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 8,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-kaluga-klf",
|
||||
"title": "Russia Kaluga (KLF)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.731,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 7,
|
||||
"coding_rate": 7,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-kazan-kzn",
|
||||
"title": "Russia Kazan (KZN)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.731,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 6,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-khabarovsk-khv",
|
||||
"title": "Russia Khabarovsk (KHV)",
|
||||
"region": "Russia",
|
||||
"frequency": 864.281,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 6,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-kirov-kvx",
|
||||
"title": "Russia Kirov (KVX)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.731,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 8,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-lipetsk-lpk",
|
||||
"title": "Russia Lipetsk (LPK)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.95,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 9,
|
||||
"coding_rate": 7,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-moscow-mow",
|
||||
"title": "Russia Moscow (MOW)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.731,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 7,
|
||||
"coding_rate": 7,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-nizhny-novgorod-goj",
|
||||
"title": "Russia Nizhny Novgorod (GOJ)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.731,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 6,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-novosibirsk-ovb",
|
||||
"title": "Russia Novosibirsk (OVB)",
|
||||
"region": "Russia",
|
||||
"frequency": 869.0,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 9,
|
||||
"coding_rate": 8,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-rostov-on-don-rov",
|
||||
"title": "Russia Rostov-on-Don (ROV)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.731,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 9,
|
||||
"coding_rate": 7,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-ryazan-rzn",
|
||||
"title": "Russia Ryazan (RZN)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.88,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 9,
|
||||
"coding_rate": 5,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-samara-kuf",
|
||||
"title": "Russia Samara (KUF)",
|
||||
"region": "Russia",
|
||||
"frequency": 864.281,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 7,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-saratov-gsv",
|
||||
"title": "Russia Saratov (GSV)",
|
||||
"region": "Russia",
|
||||
"frequency": 864.281,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 7,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-st-petersburg-led",
|
||||
"title": "Russia St. Petersburg (LED)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.856,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 7,
|
||||
"coding_rate": 7,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-tambov-tbw",
|
||||
"title": "Russia Tambov (TBW)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.95,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 10,
|
||||
"coding_rate": 5,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-tula-tya",
|
||||
"title": "Russia Tula (TYA)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.731,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 7,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-tver-kld",
|
||||
"title": "Russia Tver (KLD)",
|
||||
"region": "Russia",
|
||||
"frequency": 869.169,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 8,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-ufa-ufa",
|
||||
"title": "Russia Ufa (UFA)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.732,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 8,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-volgograd-vog",
|
||||
"title": "Russia Volgograd (VOG)",
|
||||
"region": "Russia",
|
||||
"frequency": 869.525,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 7,
|
||||
"coding_rate": 7,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-voronezh-voz",
|
||||
"title": "Russia Voronezh (VOZ)",
|
||||
"region": "Russia",
|
||||
"frequency": 868.731,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 8,
|
||||
"coding_rate": 6,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "russia-yekaterinburg-svx",
|
||||
"title": "Russia Yekaterinburg (SVX)",
|
||||
"region": "Russia",
|
||||
"frequency": 869.046,
|
||||
"bandwidth": 62.5,
|
||||
"spreading_factor": 7,
|
||||
"coding_rate": 7,
|
||||
"tx_power": 20,
|
||||
"status": "published",
|
||||
"notes": "Carried over from zjs81/meshcore-open (Russian regional presets, 2026-05-13)."
|
||||
},
|
||||
{
|
||||
"id": "off-grid-433",
|
||||
"title": "Off-Grid 433",
|
||||
"region": "Off-Grid",
|
||||
"frequency": 433.0,
|
||||
"bandwidth": 250,
|
||||
"spreading_factor": 11,
|
||||
"coding_rate": 8,
|
||||
"tx_power": 20,
|
||||
"off_grid": true,
|
||||
"status": "published",
|
||||
"notes": "Client-repeat frequency, used by the companion's off-grid repeat mode."
|
||||
},
|
||||
{
|
||||
"id": "off-grid-869",
|
||||
"title": "Off-Grid 869",
|
||||
"region": "Off-Grid",
|
||||
"frequency": 869.0,
|
||||
"bandwidth": 250,
|
||||
"spreading_factor": 11,
|
||||
"coding_rate": 8,
|
||||
"tx_power": 14,
|
||||
"off_grid": true,
|
||||
"status": "published",
|
||||
"notes": "Client-repeat frequency, used by the companion's off-grid repeat mode."
|
||||
},
|
||||
{
|
||||
"id": "off-grid-918",
|
||||
"title": "Off-Grid 918",
|
||||
"region": "Off-Grid",
|
||||
"frequency": 918.0,
|
||||
"bandwidth": 250,
|
||||
"spreading_factor": 11,
|
||||
"coding_rate": 8,
|
||||
"tx_power": 20,
|
||||
"off_grid": true,
|
||||
"status": "published",
|
||||
"notes": "Client-repeat frequency, used by the companion's off-grid repeat mode."
|
||||
}
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 306 KiB |
|
After Width: | Height: | Size: 1.9 MiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 2.9 MiB |
@ -0,0 +1,40 @@
|
||||
# Feature #647: outcomes
|
||||
|
||||
Written from what happened, including what failed. Plan: [PLAN.md](PLAN.md). All dates 2026-10-01.
|
||||
|
||||
## In plain language
|
||||
|
||||
Offband's radio presets now come from two files in the config repo: MeshCore's suggested settings (Liam Cottle's list, mirrored daily and credited) and our own overlay, which wins when both name the same preset. Regional entries like Philly Mesh, Arizona and the OKI 500 kHz test are there, grouped by region and labelled by source. Changing a preset is now an edit to `offband.json`, not an app release. The same presets can be applied to Companion and Observer radios, and to Repeaters, Room Servers and Sensors over stock admin commands, including a temporary option that reverts on its own.
|
||||
|
||||
The owner tested the combined build on his phone and Windows and approved it.
|
||||
|
||||
## What was delivered
|
||||
|
||||
| Epic | PR | What |
|
||||
|---|---|---|
|
||||
| A (#721) | config-profiles#3, merged | `radio-presets/offband.json` (33 presets), `meshcore-upstream.json` (mirror with credit), validator, workflow (validate on change, mirror daily) |
|
||||
| B (#726) | #744 | Preset model and parsers, bundled copies, refresh with last-good cache, merge (ours over Liam's), grouped picker with source labels, Companion/Observer apply incl. path hash (cmd 61), About credit, #747 (USA radio shown as Canada) |
|
||||
| C (#733) | #746 | Picker on remote settings, `set radio`, `tempradio` (sent last, 1 to 35791 minutes, default 1440), `set path.hash.mode`, Sensor admin entry (#745) |
|
||||
| D (#737) | this PR | D1 owner test (#738), this document (#739), plan amendment, #748 tests |
|
||||
|
||||
## Evidence
|
||||
|
||||
- **Owner D1 (#738):** approved. In his words, in substance: it matches what he expected; he sees Philly, USA and the MeshCore entries; it is clean and reads well; the source labels are understandable; grouping by region is an improvement. His notes cover the preset picker; the per-node-type checklist items were not itemized in his reply.
|
||||
- **Build tested:** local `throwaway/647-combined` @ `e1d30482`, containing #744 `04025cb0` and #746 `9c17f8a5`, release-signed, installed on the S25 FE and Windows.
|
||||
- **Automated, same build:** analyze clean, 1087 tests pass, live preset test passes against config-profiles `main`.
|
||||
- **CI:** every check green on #744 and #746 at those heads.
|
||||
- **Config repo:** both files return HTTP 200 on `main`; validate passed on the merge push; the dispatched mirror ran end to end (no commit, Liam's list unchanged).
|
||||
- **Acceptance bar (PLAN §6):** tests cover coding rates, path hash bytes to mode, `tempradio` ordering and its cap, and an overlay edit reaching the app with no release.
|
||||
|
||||
## What went wrong
|
||||
|
||||
- **The plan had a gap.** D1 checked preset refresh, but Epic A's merge was a stop at the end of the chain, so the files 404'd on `main` and that check could not pass. The owner was handed builds showing "Couldn't update presets. Showing the saved list." twice, and a third untestable handoff. Fixed by merging Epic A before D1 (PLAN §10).
|
||||
- **No test touched the real dependency.** Every preset test faked the network, so the 404 passed all tests and CI. Fixed by #748: a live test in the default suite, so CI now fails if the files go missing.
|
||||
- **A test build was installed mid-chain** on the owner's phone and Windows, replacing his working build. Both were restored to his earlier build until the chain was done. Canon now says an install is testing and happens once, at the end.
|
||||
- **ADB diagnosis** blamed his phone before reading adb's own log; the real cause was a wedged USB link (`write terminated: Input/output error`), cleared by reconnecting.
|
||||
|
||||
## What's left
|
||||
|
||||
- Merge #744, then #746, then this PR, in that order (plan grant, budget 3).
|
||||
- Owner sign-off on Epic verifications (#725 for A) and Epic closure.
|
||||
- Remove the `throwaway/647-combined` worktree after merge.
|
||||
@ -0,0 +1,168 @@
|
||||
# Feature PLAN: MESH 500 regional preset system
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Feature** | [#647](https://github.com/OffbandMesh/meshcore-client/issues/647) · Citadel `meshcore-open-mli` |
|
||||
| **Serves** | No parent Initiative; a standalone Feature. |
|
||||
| **Status** | Draft. Approved when this PR merges. |
|
||||
| **Owner** | @Strycher |
|
||||
| **Last updated** | 2026-10-01 |
|
||||
|
||||
## At a glance
|
||||
|
||||
- **What:** one radio preset list in the app, with regional defaults plus local meshes (Arizona, SoCal, OKI, Philly). Pick a preset and apply it to a Companion, Observer, Repeater, Room Server or Sensor.
|
||||
- **Why now:** our presets are a hardcoded list that can only change with an app release, it has no 500 kHz option, and several of its values are wrong. Regions change their settings: Philly has moved frequency, and OKI's isn't settled.
|
||||
- **How:** four Epics, in order:
|
||||
- A: preset files in `config-profiles`;
|
||||
- B: the catalog and picker in the app, applied to Companion and Observer;
|
||||
- C: applying presets to remote nodes;
|
||||
- D: integration testing.
|
||||
- **Done when:**
|
||||
- Editing a preset in `config-profiles` reaches users on their next refresh, with no app release (within about five minutes, GitHub's cache).
|
||||
- Every node type can apply a preset using stock firmware commands only.
|
||||
|
||||
## 1. Diagnosis
|
||||
|
||||
Verified 2026-09-23 to 2026-10-01. Full write-ups are on #647 and #722.
|
||||
|
||||
| # | Finding | Evidence | Effect |
|
||||
|---|---|---|---|
|
||||
| 1 | Presets are a hardcoded Dart list with no update path | `lib/models/radio_settings.dart:63` (46 entries) | Any preset change needs an app release |
|
||||
| 2 | Our coding rates are wrong for several regions | zjs81#72 dropped the CR column and set all to CR 5; Liam's registry (archived Oct 2025 by openhop, live today) has EU/UK Narrow CR8, Switzerland CR8, Portugal 433 CR6, Australia Narrow CR7 | Users picking those presets get the wrong CR |
|
||||
| 3 | No preset can carry path hash | `RadioSettings` has no field (`radio_settings.dart:47-52`); Liam's list publishes it in bytes on 8 entries | Presets that need path hash leave it unset |
|
||||
| 4 | Liam's list is the de facto community source | Stock app (`app.meshcore.nz`) fetches `api.meshcore.nz/api/v1/config` and bundles nothing; official map and config tools use it; CORS is open | It's the base we build on, with credit |
|
||||
| 5 | Liam's list lacks entries our users need | Live list: 26 entries, none at 500 kHz, no Philly, OKI, Arizona or Russia | We need our own overlay |
|
||||
| 6 | Stock firmware has no preset list | `meshcore-dev/MeshCore` `e9412598`: only one build default (869.618 / 62.5 / SF8) | Presets are a client concern; no firmware work needed |
|
||||
| 7 | Every apply path exists in stock firmware | Companion cmd 11 + cmd 61; CLI `set radio`, `tempradio`, `set path.hash.mode` (upstream `CommonCLI.cpp`) | No Offband-specific codes |
|
||||
| 8 | Path hash is published in bytes; firmware takes a zero-based mode | `sendFlood(..., path_hash_mode + 1)`; 2 bytes = mode 1 | A straight copy of the number puts the node off the mesh |
|
||||
| 9 | `tempradio` retunes 2 s after replying; its timer overflows past ~35,791 minutes | `simple_repeater/MyMesh.cpp:1026-1034` | Must be sent last in a save, and the duration capped |
|
||||
| 10 | The app has no admin path for Sensors | A Sensor contact only opens a chat (`contacts_screen.dart:981-987`); stock sensor firmware does run the shared CLI (`SensorMesh.cpp:450`) | Sensor apply needs an admin entry point |
|
||||
| 11 | Room Servers already share the repeater admin screens | `contacts_screen.dart:1063` opens `RepeaterHubScreen` for room management | Repeater work covers Room Servers |
|
||||
|
||||
## 2. Scope
|
||||
|
||||
**In:**
|
||||
- An Offband overlay preset file and a CI mirror of Liam's list in `OffbandMesh/config-profiles` (owner decision on #650 and #722).
|
||||
- In the app: bundled snapshots of both, refresh, merge (ours over Liam's), last-good cache, a grouped picker with source labels, and credits.
|
||||
- Applying presets to Companion, Observer, Repeater, Room Server and Sensor through stock commands only.
|
||||
- A Temporary (`tempradio`) option for remote nodes (#662).
|
||||
|
||||
**Out:**
|
||||
- Firmware changes.
|
||||
- Changing any non-US preset beyond matching Liam's published values.
|
||||
- Regulatory or legal advice.
|
||||
|
||||
## 3. Epics
|
||||
|
||||
Each Epic ends with a verification task and gets one PR. Issue numbers are already filed on board #2.
|
||||
|
||||
### Epic A: preset sources in config-profiles (#721)
|
||||
|
||||
Code lands in `OffbandMesh/config-profiles`.
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **A1 · Overlay file + schema (#722):** OKI test, Philly (current values not yet known; to be found from a Philly Mesh source, or the chain stops), Arizona SF9/CR8, Russia, Off-Grid. Schema documents add, change and retire. Checked by a validation script. | 3 |
|
||||
| **A2 · CI mirror of Liam's list (#723):** scheduled job. It runs A1's validation script on the fetched data **before** committing; if validation fails, the run fails and nothing is committed. Commits directly only on change. Checked by a manual run, a no-change rerun, and a simulated bad response. | 3 |
|
||||
| **A3 · README credit (#724):** Liam Cottle / MeshCore, and the precedence rules. | 1 |
|
||||
| **A4 · Epic verification (#725)** | 1 |
|
||||
|
||||
### Epic B: in-app catalog and picker, Companion and Observer (#726)
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **B1 · Preset model (#727):** replaces the hardcoded list. Unit tests. | 3 |
|
||||
| **B1b · Path hash field and bytes-to-mode conversion (#649):** tested conversion. | 2 |
|
||||
| **B2 · Bundled snapshots, refresh, merge, last-good cache (#728, closes #648):** tests for offline, refresh, failure fallback, precedence, an edit with no release, and malformed entries. | 4 |
|
||||
| **B3 · Grouped picker with source labels (#729):** widget test; preset match on load still works. | 3 |
|
||||
| **B4 · Apply to Companion and Observer (#730):** cmd 11, TX power, cmd 61; client repeat preserved. Tests. | 3 |
|
||||
| **B5 · Credits on About (#731)** | 1 |
|
||||
| **B6 · Epic verification (#732)** | 1 |
|
||||
|
||||
### Epic C: apply to remote nodes (#733)
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **C1 · Picker on the remote-node settings screen (#734):** Repeater and Room Server share it. | 3 |
|
||||
| **C2 · Temporary checkbox (#662):** `tempradio`, sent last, duration capped. Tests. | 3 |
|
||||
| **C3 · Path hash via `set path.hash.mode` (#735):** tests. | 2 |
|
||||
| **C5 · Sensor admin entry point (new issue at merge):** log in to a Sensor and reach the same settings screen (owner choice 1: in scope). | 3 |
|
||||
| **C4 · Epic verification (#736)** | 1 |
|
||||
|
||||
### Epic D: integration testing (#737)
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **D1 · End-to-end on every node type (#738):** owner hardware. | 3 |
|
||||
| **D2 · OUTCOMES.md (#739)** | 1 |
|
||||
|
||||
## 4. Order and dependencies
|
||||
|
||||
- A, B, C, D in that order. Each Epic's verification task blocks the next Epic (wired in Citadel).
|
||||
- B needs A's file format. C reuses B's catalog and conversion. D needs all three.
|
||||
- Within B: B1, B1b, B2, B3 and B4 all touch `radio_settings.dart` and `settings_screen.dart`, so they run in sequence.
|
||||
- Within C: C1, C2, C3 and C5 all touch `repeater_settings_screen.dart` (C5 also `contacts_screen.dart`), so they run in sequence.
|
||||
- Because merges wait until the end, C's branch is stacked on B's, and D's on C's. A fix found in B during D's hardware testing gets rebased up through C.
|
||||
|
||||
## 5. Grants and authorization
|
||||
|
||||
| Term | Proposed | Why |
|
||||
|---|---|---|
|
||||
| **What merging this plan authorizes** | Running Epics B, C and D in order without stopping between them: code, tests, builds, and one PR per Epic as it finishes. | The owner asked for the chain to run unattended unless a decision or fault needs him. |
|
||||
| **Merges** | Deferred to the end of the chain, in order B, C, D, after the owner's hardware review in D. | Owner direction: merges come at the end. |
|
||||
| **Epic verification** | Owner mode. My verification task (analyze, full test suite, format, em-dash check, Windows and APK builds) closes each Epic and lets the chain continue. The owner's approval of each PR happens at the end, before merge. | Hardware testing is the owner's gate; consolidating it at D avoids pausing the chain. |
|
||||
| **Owner steps during the run** | None, unless a stop below fires. At the end: hardware review (D1), then approve the PRs. | |
|
||||
| **Stops** | A new decision; a fault I can't fix; Philly's current values if no public source; Epic A's PR, because it's in `config-profiles` and outside this grant (needs a separate `dw-approve merge`). | Grants cover this repo only. |
|
||||
| **Flash** | None. | No firmware is flashed. |
|
||||
|
||||
```grant-terms
|
||||
{
|
||||
"epic_chain": [726, 733, 737],
|
||||
"chain": true,
|
||||
"verification": { "mode": "owner" },
|
||||
"merge": { "budget": 3, "basis": "One PR per Epic in this repo: B (#726), C (#733), D (#737, OUTCOMES.md). Epic A merges in config-profiles, outside this grant." },
|
||||
"flash": null,
|
||||
"reset": null,
|
||||
"expires_after_hours": 168
|
||||
}
|
||||
```
|
||||
|
||||
`expires_after_hours` basis: A plus B plus C is roughly four to five working sessions of build time, plus the owner's end-of-chain hardware review. 168 hours (the maximum) leaves room for his day job.
|
||||
|
||||
## 6. Verification
|
||||
|
||||
- **Named command (this repo):** `flutter analyze` with CI flags, `dart format --set-exit-if-changed`, the em-dash check, and `flutter test` (full suite). Every Epic PR shows the output.
|
||||
- **Named command (config-profiles):** the A1 validation script over both files, plus one mirror job run.
|
||||
- **Acceptance bar:** each finding in section 1 has a test that would have caught it. Most important: wrong CR values, path hash bytes-to-mode, `tempradio` ordering and cap, and an overlay edit reaching the app with no release.
|
||||
|
||||
## 7. Done when
|
||||
|
||||
- The picker shows Liam's presets plus ours, grouped, with sources and credits, and works offline.
|
||||
- An overlay edit in `config-profiles` reaches the app on its next refresh with no new build, within about five minutes (GitHub's raw-file cache, #452).
|
||||
- Companion, Observer, Repeater, Room Server and Sensor can each apply a preset with stock commands, including path hash and the Temporary option.
|
||||
- The owner signs off D1, and `OUTCOMES.md` is approved.
|
||||
|
||||
## 8. Your choices
|
||||
|
||||
| # | Question | Option A | Option B | Rec. | Your choice |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | Sensors have no admin path in the app today | Add one (C5): log in, reuse the repeater settings screen | Drop Sensor from this Feature and file it separately | ⭐ A | **A**: add the Sensor admin path (2026-10-01) |
|
||||
| 2 | When does your hardware testing happen? | Once, at Epic D, before any merge; the chain runs straight through. Risk: a hardware fault in B is found only after C is built on it, so the rework is bigger. | After each Epic, before the next starts. Catches faults earlier, but the chain pauses for you each time. | ⭐ A (your stated direction) | **A**: at the end; the chain does not stop between Epics (2026-10-01) |
|
||||
|
||||
## 9. Carried-in work
|
||||
|
||||
| Item | Goes to |
|
||||
|---|---|
|
||||
| #648 (hardcoded list, no update path) | B2 |
|
||||
| #649 (preset path hash) | B1b |
|
||||
| #662 (Temporary checkbox) | C2 |
|
||||
| #661 (OKI stopgap, closed) | A1 |
|
||||
| #650 (source decision, closed) | Decisions recorded; this plan implements them |
|
||||
| Sensor admin path (finding 10) | C5, new issue when this plan merges |
|
||||
|
||||
## 10. Amendments
|
||||
|
||||
| Date | Change | Why |
|
||||
|---|---|---|
|
||||
| 2026-10-01 | Epic A (config-profiles#3) merged **before** D1, not at the end. The owner minted its grant separately. App PRs still merge after D1. | Gap in this plan: D1 checks preset refresh, which can't pass until the files are on config-profiles `main`. Stopping for A only at the end made D1 untestable. |
|
||||
| 2026-10-01 | Added #748: a live test that refreshes from the real config-profiles URLs in CI, plus tests that each preset error message is absent under ideal conditions. | Owner requirement after "Couldn't update presets" reached him on two test builds. No build goes to him while that error still appears under ideal conditions. |
|
||||
@ -0,0 +1,197 @@
|
||||
# Feature PLAN: fake radio for automated testing in CI
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Feature** | [#755](https://github.com/OffbandMesh/meshcore-client/issues/755) · Citadel `meshcore-open-6o3` |
|
||||
| **Serves** | No parent Initiative; a standalone Feature. Absorbs #601 from Epic #598. Depends on OffbandMesh/meshcore-firmware#1318. |
|
||||
| **Status** | Draft. Approved when this PR merges. |
|
||||
| **Owner** | @Strycher |
|
||||
| **Last updated** | 2026-10-02 |
|
||||
|
||||
## At a glance
|
||||
|
||||
- **What:** a software MeshCore companion radio, written in Dart, that the real client connects to with no hardware. It plays either **stock MeshCore** or **Offband** firmware, answers the same frames a real radio does from a seeded, deterministic state, and can play scripted faults.
|
||||
- **Why now:** no test can take the client through a real connect, sync, send or settings change. Everything past "connected" is tested by the owner, by hand, on hardware. The #647 remote preset commands shipped with no on-air test for exactly this reason.
|
||||
- **How it stays in sync:** the firmware publishes a machine-readable protocol manifest at every tag and merge (firmware#1318). The fake radio's profiles load it, and client CI fails when the client disagrees with it. Captured traces from a real Offband radio and a real stock radio check behavior.
|
||||
- **How:** four Epics, in order:
|
||||
- A: the fake radio core, both profiles, the manifest check, in-process and over TCP;
|
||||
- B: messaging, radio settings, remote nodes, faults, and trace replay;
|
||||
- C: test suites that run in CI under both profiles, plus a runner for manual use;
|
||||
- D: integration testing, including capturing the real-radio traces.
|
||||
- **Done when:**
|
||||
- Every PR's CI runs connect, sync, messaging and preset flows (including on a repeater, room server and sensor) against the fake radio, under both the stock and Offband profiles, with no hardware.
|
||||
- Client CI fails when the client's protocol constants disagree with the firmware's published manifest.
|
||||
- The owner can start the fake radio on his PC and connect the Windows app to it over TCP.
|
||||
|
||||
## 1. Diagnosis
|
||||
|
||||
Verified 2026-10-02 against `dev` @ `0fc407d4` and firmware `53951759`.
|
||||
|
||||
| # | Finding | Evidence | Effect |
|
||||
|---|---|---|---|
|
||||
| 1 | Nothing past "connected" can be tested without a radio | `scanner_screen.dart:66` routes to the channel UI only on `connected`; #598 diagnosis | Connect, sync and messaging regressions reach users before anyone sees them |
|
||||
| 2 | No test drives the protocol end to end | The only TCP tests are the transport (`tcp_transport_service_native_test.dart`, raw sockets) and `tcp_flow_test.dart`, which stubs `connectTcp` out entirely | The connector's handshake, sync and send logic (9,368 lines in `meshcore_connector.dart`) has no end-to-end test |
|
||||
| 3 | The fake radio was planned, never built | #601 has no branch, comments or code | Nothing to build on but a plan |
|
||||
| 4 | The connector already has an in-process seam | `handleFrameForTest` and `sendFrameOverrideForTest` (`meshcore_connector.dart:3112-3117`) | A fake radio can plug in with no sockets, so widget tests stay fast and deterministic |
|
||||
| 5 | The TCP path needs no app changes, but uses serial framing | `connectTcp` (`meshcore_connector.dart:2295`); the transport wraps frames with `wrapUsbSerialTxFrame` (start `0x3c`) and decodes with `UsbSerialFrameDecoder` (start `0x3e`) (`tcp_transport_service_native.dart:11,92`) | The fake's TCP server must speak that framing |
|
||||
| 6 | The handshake is a known, finite set | On connect the client sends `DEVICE_QUERY`, `APP_START`, `GET_CUSTOM_VARS`, battery, `GET_AUTO_ADD_CONFIG`, then contacts, channels and message sync (`meshcore_connector.dart:3592-3600`, `3712`); 53 frame builders, 34 response and push codes handled | The core can be built against a fixed list |
|
||||
| 7 | Stock and Offband differ in what the radio reports | The client gates every Offband feature on the reported capability bytes (`_offbandCaps`, `_offbandCaps2`, `meshcore_connector.dart:370`) and the version code; the bits are defined in `OffbandConfigProtocol.h:275-299`; stock firmware reports none | A fake radio can play either by changing what it reports and which Offband commands it answers |
|
||||
| 8 | The firmware publishes no machine-readable contract | The caps and `FIRMWARE_VER_CODE` registry is a prose comment table (firmware#514) | Today any copy of the protocol drifts silently; firmware#1318 fixes this at the source |
|
||||
| 9 | Firmware version reporting is inconsistent | firmware#873 (`ver` vs `version` disagree), #958, #1277, #1311 | A test of the reported version catches this; firmware#1318 adds the firmware-side check |
|
||||
| 10 | The firmware is the reference for every reply | `examples/companion_radio/MyMesh.cpp`, `handleCmdFrame` at line 1964; remote CLI in the shared `CommonCLI` | Each fake reply is copied from a named firmware function, not guessed |
|
||||
| 11 | Remote-node presets are untested on air | #738 addendum: owner reviewed the screen, never applied a preset to a real node | The fake radio covers `set radio`, `tempradio` and `set path.hash.mode` in CI |
|
||||
| 12 | No radio is on stock firmware today | Owner, 2026-10-02: one can be flashed | The stock trace capture needs one radio flashed to stock (section 5, Flash) |
|
||||
| 13 | #598 scoped its bench out of CI | #598 body, owner 2026-08-24 | Reversed for the fake radio only (owner, 2026-10-02, logged on #598) |
|
||||
|
||||
## 2. Scope
|
||||
|
||||
**In:**
|
||||
- A fake companion radio in Dart: frame codec, command dispatch, seeded state, deterministic clock.
|
||||
- Two firmware profiles, stock and Offband, built from the firmware's published protocol manifests.
|
||||
- A client CI check that the client's protocol constants match the manifest.
|
||||
- Two ways to connect: in-process (through the connector's test seam) and a TCP loopback server.
|
||||
- Messaging, acks, incoming messages, channels, radio settings, and repeater, room server and sensor admin (login and CLI) over the mesh.
|
||||
- Scripted faults: dropped acks, error replies, disconnect mid-sync, slow replies.
|
||||
- Trace replay: frames recorded from a real Offband radio and a real stock radio, which the fake must reproduce.
|
||||
- Test suites in the default `flutter test`, so CI runs them on every PR.
|
||||
- A standalone runner (`dart run tool/fake_radio.dart`) so the desktop app can connect over TCP.
|
||||
|
||||
**Out:**
|
||||
- The firmware side of the manifest and the reported-version check: firmware#1318.
|
||||
- BLE and USB serial fakes. TCP and in-process cover the protocol; the transports already have their own tests.
|
||||
- Simulating RF, propagation or multi-hop routing. The fake radio reports paths and hops from its seed.
|
||||
- The rest of #598: the `integration_test` harness (#602) and Win32 input injection (#603) stay on-demand.
|
||||
- Any change to `lib/` beyond what a test needs to attach. The fake radio never ships in a release build.
|
||||
|
||||
## 3. Epics
|
||||
|
||||
Each Epic ends with a verification task and gets one PR. The first task reproduces the diagnosis as a failing test.
|
||||
|
||||
### Epic A: core, profiles and the manifest check (#756)
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **A1 · Failing scenario test:** the real `MeshCoreConnector` connects and reaches `connected` with self info, contacts and channels loaded. Fails today: there is nothing to connect to. | 2 |
|
||||
| **A2 · Core (absorbs #601):** frame codec, dispatch, seeded state (self info, device info, contacts, channels, queued messages, battery, custom vars, auto-add), deterministic clock. Every delay the fake produces (including B4's slow replies) runs on that clock, never wall time, so tests advance it with the test's fake clock. Every reply cites its firmware function. Unknown commands get the firmware's error reply. Unit tests per command. | 4 |
|
||||
| **A3 · In-process and TCP adapters:** the same core behind `sendFrameOverrideForTest`/`handleFrameForTest`, and behind a loopback `ServerSocket` speaking the transport's serial framing (finding 5). | 3 |
|
||||
| **A4 · Profiles from manifests:** the fake loads a `protocol-manifest.json` per profile. Offband: firmware version, version code and capability bits; answers the Offband commands. Stock: no capability bytes; rejects Offband commands as stock firmware does. Pinned copies are checked in under `test/` so CI runs offline. Until firmware#1318 publishes them, the pinned copies are generated once from the firmware source at the pinned tags, in the same format, and replaced by the published ones when they land. | 3 |
|
||||
| **A5 · Manifest contract check:** a test that fails when `meshcore_protocol.dart` disagrees with the pinned Offband manifest (a command or response code, a capability bit, a version gate). Includes the reported-version fields. | 3 |
|
||||
| **A6 · Epic verification:** A1 passes on both adapters and both profiles; same seed, same result over 20 runs; A5 fails on a deliberately wrong constant. | 1 |
|
||||
|
||||
### Epic B: messaging, settings, remote nodes, faults and replay (#757)
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **B1 · Messaging:** direct and channel send (`SENT`, then `SEND_CONFIRMED` with a settable delay or drop), incoming messages through `MSG_WAITING` and `SYNC_NEXT_MESSAGE` in the V3 formats. | 4 |
|
||||
| **B2 · Radio settings:** cmd 11, 12, 38 and 61 change the fake's state and show in the next `SELF_INFO`. | 2 |
|
||||
| **B3 · Remote nodes:** seeded repeater, room server and sensor contacts; login success and failure; CLI replies for `get radio`, `set radio`, `tempradio`, `set path.hash.mode`, `set tx`, `ver` and `version`, copied from firmware `CommonCLI`. | 4 |
|
||||
| **B4 · Scripted faults:** drop an ack, return an error, close the connection mid-sync, delay a reply. | 3 |
|
||||
| **B5 · Trace capture and replay tooling:** a recorder that saves a real radio's frames from a client session to a fixture file, and a replay test that requires the fake to produce the same frames for the same requests and seed. Built and tested here against a recorded fake session; real-radio fixtures are captured in D1. | 4 |
|
||||
| **B6 · Epic verification** | 1 |
|
||||
|
||||
### Epic C: CI suites and the manual runner (#758)
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **C1 · Connector scenario suite, both profiles:** connect and sync; direct send, ack, retry and timeout; channel send; Companion preset apply (#647: cmd 11 radio params, cmd 12 TX power, cmd 61 path hash mode, checked in the fake's state and the next `SELF_INFO`); remote preset apply on a repeater, room server and sensor, including `tempradio` going last. Under the stock profile, also: no Offband feature is offered and no Offband command is sent. Runs in the default `flutter test`. | 4 |
|
||||
| **C2 · Screen-level tests:** the channels screen and a chat screen, attached in-process to the fake radio; a composer send reaches the fake and the ack shows. | 4 |
|
||||
| **C3 · Manual runner:** `dart run tool/fake_radio.dart --profile offband|stock --port 5000 --seed <file>`; seed file format documented. The Windows app connects to it by TCP. | 3 |
|
||||
| **C4 · Release guard:** the fake radio lives only under `test/` and `tool/`; a test fails if anything under `lib/` imports it. | 2 |
|
||||
| **C5 · Epic verification** | 1 |
|
||||
|
||||
### Epic D: integration testing (#759)
|
||||
|
||||
| Task | Pts |
|
||||
|---|---|
|
||||
| **D1 · Owner session:** the Windows app connected to the manual runner (both profiles); then one real Offband radio and one radio flashed to stock MeshCore, each connected once while B5's recorder runs. | 3 |
|
||||
| **D2 · Real-radio conformance:** the D1 traces committed as fixtures; the replay test passes against both, or each difference is fixed or recorded. | 3 |
|
||||
| **D3 · OUTCOMES.md** | 1 |
|
||||
|
||||
## 4. Order and dependencies
|
||||
|
||||
- A, B, C, D in that order. Each Epic's verification task blocks the next Epic (wired in Citadel).
|
||||
- B builds on A's core and profiles; C uses everything in A and B; D needs all three.
|
||||
- All Epics touch the same new files (`test/support/fake_radio/`, `tool/fake_radio.dart`), so they run in sequence. C2 is the only task that touches app screens, and only from tests.
|
||||
- Merges wait until the end, so each Epic's branch is stacked on the one before.
|
||||
- **firmware#1318** is not a blocker: A4 starts from pinned manifests generated from the firmware source, and switches to the published ones when #1318 lands. If #1318 changes the manifest format, A4's loader follows it.
|
||||
- #598 keeps #599, #600, #602, #603 and #604. Its bench will use this fake radio, so #598 depends on this Feature.
|
||||
|
||||
## 5. Grants and authorization
|
||||
|
||||
| Term | Proposed | Why |
|
||||
|---|---|---|
|
||||
| **What merging this plan authorizes** | Running Epics A to D in order without stopping between them: code, tests, builds, and one PR per Epic, stacked. | Canon: once the plan grant is minted, run the whole chain. |
|
||||
| **Merges** | Held to the end of the Feature, in order A, B, C, D, after the owner's D1 session. | Canon. |
|
||||
| **Epic verification** | Command mode: the merge hook runs `flutter test` on each PR's exact commit. | This Feature is test infrastructure; its own suites are the evidence. It also spares the owner a verify step per PR. |
|
||||
| **Owner steps during the run** | None until D1. Before D1: pick the radio to flash to stock and mint its flash grant. At D1: the runner session and the two radio captures, in one sitting. | Canon: owner steps are one message, at the end. |
|
||||
| **Stops** | A new decision; a fault I can't fix; a firmware reply I can't find a source for. | |
|
||||
| **Flash** | Not in this grant. Before D1, the session flashes one radio the owner picks to a stock MeshCore companion release file, with `scripts/pio-flash` under its own `dw-approve flash <device>` grant. | Finding 12. A plan's flash term must name one registered device, and the radio isn't chosen yet, so the flash gets its own grant when it is. `pio-flash` flashes any firmware file, stock included (owner, 2026-10-02). |
|
||||
|
||||
```grant-terms
|
||||
{
|
||||
"epic_chain": [756, 757, 758, 759],
|
||||
"chain": true,
|
||||
"verification": { "mode": "command", "command": "flutter test" },
|
||||
"merge": { "budget": 4, "basis": "One PR per Epic: A (#756), B (#757), C (#758), D (#759: conformance fixtures and OUTCOMES.md)." },
|
||||
"flash": null,
|
||||
"reset": null,
|
||||
"expires_after_hours": 168
|
||||
}
|
||||
```
|
||||
|
||||
`expires_after_hours` basis: 55 points of work, roughly five to six working sessions, plus the owner's D1 session around his day job. 168 hours is the maximum.
|
||||
|
||||
## 6. Verification
|
||||
|
||||
- **Named command:** `flutter analyze --fatal-infos --fatal-warnings`, `dart format --set-exit-if-changed`, the em-dash check, and `flutter test` (full suite, which includes the new suites). Every Epic PR shows the output.
|
||||
- **Acceptance bar:** each finding in section 1 has a test that would have caught it. Most important: the handshake reaches `connected` under both profiles; the stock profile never sees an Offband feature or command; the manifest check fails on a wrong constant; a dropped ack is retried; a remote `tempradio` is sent last; a release build contains no fake radio code.
|
||||
- **Owner requirement (#748):** every error message these flows show is tested present on failure and absent under ideal conditions.
|
||||
|
||||
## 7. Done when
|
||||
|
||||
- The default `flutter test`, and so every PR's CI, connects the real connector to the fake radio under both profiles and covers connect, sync, messaging, Companion presets and remote-node presets.
|
||||
- Client CI fails when the client's protocol constants disagree with the pinned Offband manifest.
|
||||
- The fake radio reproduces the captured traces from a real Offband radio and a real stock radio.
|
||||
- The same fake radio runs from `tool/fake_radio.dart`, and the Windows app connects to it over TCP.
|
||||
- Nothing under `lib/` imports the fake radio.
|
||||
- The owner signs off D1, and `OUTCOMES.md` is approved.
|
||||
|
||||
## 8. Your choices
|
||||
|
||||
| # | Question | Option A | Option B | Rec. | Your choice |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | Where #601 lives | Move it into this Feature (A2); #598 depends on #755 | Leave it under #598 and build a second fake here | ⭐ A | **A** (2026-10-02) |
|
||||
| 2 | Manual runner (C3) | In this Feature | Later, separately | ⭐ A (it's the "USB cables are tied up" case, and small once the TCP adapter exists) | **A** (2026-10-02) |
|
||||
| 3 | Remote-node emulation (B3) | In this Feature | Later, separately | ⭐ A (it covers the #647 remote-preset gap in CI) | **A** (2026-10-02) |
|
||||
|
||||
## Decisions
|
||||
|
||||
| Date | Decision |
|
||||
|---|---|
|
||||
| 2026-10-02 | The fake radio runs in CI (reverses #598's "not in CI" for the fake radio only). |
|
||||
| 2026-10-02 | Stock and Offband are emulated as separate profiles. |
|
||||
| 2026-10-02 | The firmware publishes the protocol manifest at every tag and merge (firmware#1318); the fake radio consumes it, never a hand copy. |
|
||||
| 2026-10-02 | Behavior is checked against captured traces from a real Offband radio and a radio flashed to stock. |
|
||||
| 2026-10-02 | The session flashes the stock radio with `scripts/pio-flash`, which flashes stock files too (owner). |
|
||||
| 2026-10-02 | The stock flash moves out of the plan grant to its own `dw-approve flash <device>` grant: `dw-approve plan` refused a flash term with no device. |
|
||||
| 2026-10-02 | Section 8: all three recommendations accepted. #601 moves under Epic A (#756); the manual runner and remote-node emulation are in scope. |
|
||||
|
||||
## 9. Carried-in work
|
||||
|
||||
| Item | Goes to |
|
||||
|---|---|
|
||||
| #601 (loopback fake radio, planned only) | A2 and A3 |
|
||||
| #598 owner decision (not in CI) | Reversed for the fake radio only (2026-10-02, logged on #598) |
|
||||
| #738 remote-preset test gap | C1 (in CI) |
|
||||
| firmware#1318 (manifest, reported-version check) | Firmware repo; A4 and A5 consume it |
|
||||
| firmware#514, #873 | Referenced by firmware#1318; firmware side |
|
||||
|
||||
## Alternatives considered but not chosen
|
||||
|
||||
- **Firmware CI builds the fake radio itself:** the fake is Dart code in the client repo; firmware CI builds C++. Firmware publishes the contract instead, and the client builds from it.
|
||||
- **Hand-copied protocol constants in the fake:** drifts silently, the failure firmware#514 already documents.
|
||||
- **`integration_test` on a Linux desktop runner in CI:** needs a display server and a full app build per run; the in-process adapter reaches the same screens from `flutter test`.
|
||||
- **A Python or firmware-native simulator:** a second toolchain in CI, and it can't use the connector's in-process seam.
|
||||
- **Running the real companion firmware on the host:** not investigated; it would mean building and maintaining a host port of the firmware, a much larger effort than this Feature.
|
||||
|
||||
When this plan merges, each Task gets a GitHub issue and a Citadel task, per canon.
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,17 @@
|
||||
/// Returns a channel-send timestamp (Unix seconds) strictly greater than
|
||||
/// [lastSecs] for the same channel, so no two sends on one channel ever share a
|
||||
/// `(ts, channel_idx)` key.
|
||||
///
|
||||
/// This is a correctness requirement for the 0xC6 packet-hash correlation
|
||||
/// (#524/#611): `msg_timestamp` is only second-resolution and MeshCore channel
|
||||
/// encryption is deterministic (AES-128-ECB), so two different messages on the
|
||||
/// same channel within one second would otherwise map to the same key but
|
||||
/// different hashes, and the client would query CoreScope with the wrong hash.
|
||||
///
|
||||
/// Uses [nowSecs] unless it would collide with or precede [lastSecs], in which
|
||||
/// case it bumps to `lastSecs + 1`. Mirrors the firmware's own
|
||||
/// `getCurrentTimeUnique()`.
|
||||
int monotonicChannelSendTs(int nowSecs, int? lastSecs) {
|
||||
if (lastSecs != null && nowSecs <= lastSecs) return lastSecs + 1;
|
||||
return nowSecs;
|
||||
}
|
||||
@ -0,0 +1,102 @@
|
||||
import '../models/radio_preset.dart';
|
||||
|
||||
// Radio presets on remote nodes (repeater, room server, sensor) through the
|
||||
// stock admin CLI (#733). Kept out of the screen so it can be tested.
|
||||
|
||||
/// Default `tempradio` duration (owner decision on #662).
|
||||
const int kTempRadioDefaultMinutes = 1440;
|
||||
|
||||
/// Longest `tempradio` duration that works. Firmware schedules the revert at
|
||||
/// `futureMillis(2000 + timeout_mins * 60 * 1000)` in a 32-bit int
|
||||
/// (simple_repeater/MyMesh.cpp), which overflows past this.
|
||||
const int kTempRadioMaxMinutes = 35791;
|
||||
|
||||
String _bandwidthKHz(int bandwidthHz) => '${bandwidthHz / 1000}';
|
||||
|
||||
/// Stock CLI: persist radio params (applied after a reboot).
|
||||
String setRadioCommand(
|
||||
String frequencyText,
|
||||
int bandwidthHz,
|
||||
int spreadingFactor,
|
||||
int codingRate,
|
||||
) =>
|
||||
'set radio $frequencyText,${_bandwidthKHz(bandwidthHz)},'
|
||||
'$spreadingFactor,$codingRate';
|
||||
|
||||
/// Stock CLI: apply radio params now, reverting after [minutes]. Nothing is
|
||||
/// saved on the node. Coding rate is the 4/x denominator (4/5 is 5), which
|
||||
/// is what firmware range-checks (5-8).
|
||||
String tempRadioCommand(
|
||||
String frequencyText,
|
||||
int bandwidthHz,
|
||||
int spreadingFactor,
|
||||
int codingRate,
|
||||
int minutes,
|
||||
) =>
|
||||
'tempradio $frequencyText,${_bandwidthKHz(bandwidthHz)},'
|
||||
'$spreadingFactor,$codingRate,$minutes';
|
||||
|
||||
/// A valid `tempradio` duration in minutes (1 to [kTempRadioMaxMinutes]),
|
||||
/// or null.
|
||||
int? parseTempRadioMinutes(String text) {
|
||||
final minutes = int.tryParse(text.trim());
|
||||
if (minutes == null || minutes < 1 || minutes > kTempRadioMaxMinutes) {
|
||||
return null;
|
||||
}
|
||||
return minutes;
|
||||
}
|
||||
|
||||
/// `tempradio` retunes the node 2 s after it replies, so anything sent after
|
||||
/// it in the same save would go out on the old frequency. Keep the original
|
||||
/// order otherwise, with retuning commands moved to the end.
|
||||
List<T> withRetuneLast<T>(List<T> commands, bool Function(T) retunes) => [
|
||||
...commands.where((c) => !retunes(c)),
|
||||
...commands.where(retunes),
|
||||
];
|
||||
|
||||
bool isRetuneCommand(String command) => command.startsWith('tempradio ');
|
||||
|
||||
/// Stock CLI: path hash mode, zero-based (2 bytes = mode 1).
|
||||
String setPathHashModeCommand(int mode) => 'set path.hash.mode $mode';
|
||||
|
||||
/// Whether a path hash that came from a preset goes out in this save (#735).
|
||||
/// Firmware has no temporary path hash, so with a temporary radio change it
|
||||
/// would outlive the revert; it stays pending for a normal save instead. A
|
||||
/// path hash the user set by hand is always sent.
|
||||
bool sendsPresetPathHash({
|
||||
required bool temporaryRadio,
|
||||
required bool pathHashFromPreset,
|
||||
}) => !(temporaryRadio && pathHashFromPreset);
|
||||
|
||||
/// The preset whose radio values match the form's, or null for custom values.
|
||||
/// The form holds frequency as text (the repeater reports e.g. "908.205017"),
|
||||
/// so frequency matches to the nearest kHz. TX power is not compared: the
|
||||
/// remote screen sets it separately. A preset with a path hash only matches
|
||||
/// a node on that mode (#747): MeshCore's "Canada" and "USA" differ only there.
|
||||
String? matchRemotePresetId(
|
||||
List<RadioPreset> presets, {
|
||||
required String frequencyText,
|
||||
required int? bandwidthHz,
|
||||
required int? spreadingFactor,
|
||||
required int? codingRate,
|
||||
required int pathHashMode,
|
||||
}) {
|
||||
final mhz = double.tryParse(frequencyText.trim());
|
||||
if (mhz == null ||
|
||||
bandwidthHz == null ||
|
||||
spreadingFactor == null ||
|
||||
codingRate == null) {
|
||||
return null;
|
||||
}
|
||||
final khz = (mhz * 1000).round();
|
||||
for (final p in presets) {
|
||||
if (p.frequencyKHz == khz &&
|
||||
p.bandwidth.hz == bandwidthHz &&
|
||||
p.spreadingFactor.value == spreadingFactor &&
|
||||
p.codingRate.value == codingRate &&
|
||||
presetPathHashMatches(p, pathHashMode + 1)) {
|
||||
return p.id;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@ -1,56 +1,25 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// showDismissibleSnackBar shows a [SnackBar] with tap to dismiss
|
||||
// all other properties are default and optional
|
||||
import '../widgets/top_toast.dart';
|
||||
|
||||
/// Shows a transient notification that dismisses on tap, on an upward swipe,
|
||||
/// or after [duration].
|
||||
///
|
||||
/// Kept under its original name so existing call sites are unchanged; the
|
||||
/// notification itself moved from a bottom [SnackBar] to a top-anchored
|
||||
/// overlay (#638), because the bottom placement covered the chat composer.
|
||||
void showDismissibleSnackBar(
|
||||
BuildContext context, {
|
||||
Key? key,
|
||||
required Widget content,
|
||||
Color? backgroundColor,
|
||||
double? elevation,
|
||||
EdgeInsetsGeometry? margin,
|
||||
EdgeInsetsGeometry? padding,
|
||||
double? width,
|
||||
ShapeBorder? shape,
|
||||
HitTestBehavior? hitTestBehavior,
|
||||
SnackBarBehavior? behavior,
|
||||
SnackBarAction? action,
|
||||
double? actionOverflowThreshold,
|
||||
bool? showCloseIcon,
|
||||
Color? closeIconColor,
|
||||
Duration? duration,
|
||||
bool? persist,
|
||||
Animation<double>? animation,
|
||||
void Function()? onVisible,
|
||||
DismissDirection? dismissDirection,
|
||||
Clip? clipBehavior,
|
||||
}) {
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
key: key,
|
||||
content: GestureDetector(
|
||||
onTap: () => messenger.hideCurrentSnackBar(),
|
||||
child: content,
|
||||
),
|
||||
backgroundColor: backgroundColor,
|
||||
elevation: elevation,
|
||||
margin: margin,
|
||||
padding: padding,
|
||||
width: width,
|
||||
shape: shape,
|
||||
hitTestBehavior: hitTestBehavior,
|
||||
behavior: behavior,
|
||||
action: action,
|
||||
actionOverflowThreshold: actionOverflowThreshold,
|
||||
showCloseIcon: showCloseIcon,
|
||||
closeIconColor: closeIconColor,
|
||||
duration: duration ?? const Duration(seconds: 4),
|
||||
persist: persist,
|
||||
animation: animation,
|
||||
onVisible: onVisible,
|
||||
dismissDirection: dismissDirection ?? DismissDirection.down,
|
||||
clipBehavior: clipBehavior ?? Clip.hardEdge,
|
||||
),
|
||||
TopToast.show(
|
||||
context,
|
||||
content: content,
|
||||
backgroundColor: backgroundColor,
|
||||
duration: duration ?? TopToast.defaultDuration,
|
||||
persist: persist ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
@ -0,0 +1,294 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'radio_settings.dart';
|
||||
|
||||
// Regional radio presets (#647). Two sources, both published in the
|
||||
// OffbandMesh/config-profiles repo under radio-presets/ (schema in its SCHEMA.md):
|
||||
// - meshcore-upstream.json: MeshCore's suggested presets (maintained by Liam
|
||||
// Cottle), mirrored unmodified; numbers arrive as strings.
|
||||
// - offband.json: Offband's overlay; numbers are JSON numbers.
|
||||
// Parsing is resilient: a malformed entry is skipped and counted, never fatal,
|
||||
// but a file of the wrong format or a newer format_version is rejected.
|
||||
|
||||
const String kUpstreamPresetFormat = 'meshcore-upstream-radio-presets';
|
||||
const String kOverlayPresetFormat = 'offband-radio-presets';
|
||||
|
||||
/// Highest format_version this build understands, for both files.
|
||||
const int kRadioPresetFormatVersion = 1;
|
||||
|
||||
enum RadioPresetSource { meshcore, offband }
|
||||
|
||||
class RadioPreset {
|
||||
const RadioPreset({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.region,
|
||||
required this.frequencyMHz,
|
||||
required this.bandwidth,
|
||||
required this.spreadingFactor,
|
||||
required this.codingRate,
|
||||
required this.source,
|
||||
this.txPowerDbm,
|
||||
this.pathHashBytes,
|
||||
this.offGrid = false,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String title;
|
||||
|
||||
/// Picker group, e.g. "USA", "Australia", "Off-Grid".
|
||||
final String region;
|
||||
final double frequencyMHz;
|
||||
final LoRaBandwidth bandwidth;
|
||||
final LoRaSpreadingFactor spreadingFactor;
|
||||
final LoRaCodingRate codingRate;
|
||||
final RadioPresetSource source;
|
||||
|
||||
/// Null leaves the radio's TX power alone (upstream presets never set it).
|
||||
final int? txPowerDbm;
|
||||
|
||||
/// Path hash size in bytes (1-3), as published. Null leaves the radio's
|
||||
/// setting alone.
|
||||
final int? pathHashBytes;
|
||||
|
||||
/// A client-repeat (off-grid) frequency rather than a regional preset.
|
||||
final bool offGrid;
|
||||
|
||||
/// Frequency in kHz, the unit CMD_SET_RADIO_PARAMS carries.
|
||||
int get frequencyKHz => (frequencyMHz * 1000).round();
|
||||
|
||||
/// The firmware's path hash mode for [pathHashBytes], or null to leave it.
|
||||
///
|
||||
/// Presets publish the size in bytes; firmware takes a zero-based mode
|
||||
/// (`sendFlood(..., path_hash_mode + 1)`): 1 byte = mode 0, 2 bytes = mode 1,
|
||||
/// 3 bytes = mode 2. Passing a published 2 straight through would select
|
||||
/// 3-byte hashes and put the node off its mesh.
|
||||
int? get pathHashMode => pathHashModeForBytes(pathHashBytes);
|
||||
}
|
||||
|
||||
/// Whether a radio using [radioPathHashBytes] fits [preset]'s path hash
|
||||
/// (#747). Presets without a path hash fit any radio; one with a size only
|
||||
/// fits a radio on that size. Without this, presets that differ only by path
|
||||
/// hash (MeshCore's "Canada" 3-byte and "USA") are indistinguishable.
|
||||
bool presetPathHashMatches(RadioPreset preset, int radioPathHashBytes) =>
|
||||
preset.pathHashBytes == null || preset.pathHashBytes == radioPathHashBytes;
|
||||
|
||||
/// Zero-based firmware path hash mode for a published size in bytes (1-3).
|
||||
/// Null for null or out-of-range input, so nothing is sent.
|
||||
int? pathHashModeForBytes(int? bytes) {
|
||||
if (bytes == null || bytes < 1 || bytes > 3) return null;
|
||||
return bytes - 1;
|
||||
}
|
||||
|
||||
class RadioPresetFormatException implements Exception {
|
||||
const RadioPresetFormatException(this.message);
|
||||
final String message;
|
||||
@override
|
||||
String toString() => 'RadioPresetFormatException: $message';
|
||||
}
|
||||
|
||||
class RadioPresetParseResult {
|
||||
const RadioPresetParseResult(this.presets, this.skipped);
|
||||
final List<RadioPreset> presets;
|
||||
|
||||
/// Malformed entries left out, so a partly bad file never looks complete.
|
||||
final int skipped;
|
||||
}
|
||||
|
||||
/// Parse the mirrored MeshCore list (`meshcore-upstream.json`).
|
||||
RadioPresetParseResult parseUpstreamPresets(String source) {
|
||||
final doc = _decodeObject(source, kUpstreamPresetFormat);
|
||||
final srs = doc['suggested_radio_settings'];
|
||||
final entries = srs is Map ? srs['entries'] : null;
|
||||
if (entries is! List) {
|
||||
throw const RadioPresetFormatException(
|
||||
'suggested_radio_settings.entries must be a list',
|
||||
);
|
||||
}
|
||||
final presets = <RadioPreset>[];
|
||||
var skipped = 0;
|
||||
for (final e in entries) {
|
||||
final preset = e is Map ? _upstreamEntry(e) : null;
|
||||
if (preset == null) {
|
||||
skipped++;
|
||||
} else {
|
||||
presets.add(preset);
|
||||
}
|
||||
}
|
||||
return RadioPresetParseResult(presets, skipped);
|
||||
}
|
||||
|
||||
/// Parse the Offband overlay (`offband.json`). Retired entries are dropped.
|
||||
RadioPresetParseResult parseOverlayPresets(String source) {
|
||||
final doc = _decodeObject(source, kOverlayPresetFormat);
|
||||
final entries = doc['presets'];
|
||||
if (entries is! List) {
|
||||
throw const RadioPresetFormatException('presets must be a list');
|
||||
}
|
||||
final presets = <RadioPreset>[];
|
||||
var skipped = 0;
|
||||
for (final e in entries) {
|
||||
if (e is Map && e['status'] == 'retired') continue;
|
||||
final preset = e is Map ? _overlayEntry(e) : null;
|
||||
if (preset == null) {
|
||||
skipped++;
|
||||
} else {
|
||||
presets.add(preset);
|
||||
}
|
||||
}
|
||||
return RadioPresetParseResult(presets, skipped);
|
||||
}
|
||||
|
||||
Map _decodeObject(String source, String format) {
|
||||
final dynamic doc;
|
||||
try {
|
||||
doc = jsonDecode(source);
|
||||
} on FormatException catch (e) {
|
||||
throw RadioPresetFormatException('not valid JSON: ${e.message}');
|
||||
}
|
||||
if (doc is! Map) {
|
||||
throw const RadioPresetFormatException('must be a JSON object');
|
||||
}
|
||||
if (doc['format'] != format) {
|
||||
throw RadioPresetFormatException('format must be "$format"');
|
||||
}
|
||||
final version = doc['format_version'];
|
||||
if (version is! int) {
|
||||
throw const RadioPresetFormatException('format_version is required');
|
||||
}
|
||||
if (version > kRadioPresetFormatVersion) {
|
||||
throw RadioPresetFormatException(
|
||||
'format_version $version is newer than this app supports '
|
||||
'($kRadioPresetFormatVersion). Update the app.',
|
||||
);
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
RadioPreset? _upstreamEntry(Map e) {
|
||||
final title = e['title'];
|
||||
if (title is! String || title.trim().isEmpty) return null;
|
||||
final ns = e['network_settings'];
|
||||
final hash = ns is Map ? _asInt(ns['path_hash_size']) : null;
|
||||
if (ns is Map && ns.containsKey('path_hash_size') && !_validHash(hash)) {
|
||||
return null;
|
||||
}
|
||||
return _build(
|
||||
id: 'meshcore:$title',
|
||||
title: title,
|
||||
region: upstreamRegionFor(title),
|
||||
frequency: _asDouble(e['frequency']),
|
||||
bandwidthKHz: _asDouble(e['bandwidth']),
|
||||
sf: _asInt(e['spreading_factor']),
|
||||
cr: _asInt(e['coding_rate']),
|
||||
source: RadioPresetSource.meshcore,
|
||||
pathHashBytes: hash,
|
||||
);
|
||||
}
|
||||
|
||||
RadioPreset? _overlayEntry(Map e) {
|
||||
final id = e['id'];
|
||||
final title = e['title'];
|
||||
final region = e['region'];
|
||||
if (id is! String || id.isEmpty) return null;
|
||||
if (title is! String || title.trim().isEmpty) return null;
|
||||
if (region is! String || region.trim().isEmpty) return null;
|
||||
// The overlay is hand-edited: numbers must be JSON numbers, not strings.
|
||||
for (final key in const [
|
||||
'frequency',
|
||||
'bandwidth',
|
||||
'spreading_factor',
|
||||
'coding_rate',
|
||||
]) {
|
||||
if (e[key] is! num) return null;
|
||||
}
|
||||
final tx = e['tx_power'];
|
||||
if (tx != null && (tx is! int || tx < -9 || tx > 30)) return null;
|
||||
final hash = e['path_hash_size'];
|
||||
if (hash != null && (hash is! int || !_validHash(hash))) return null;
|
||||
final offGrid = e['off_grid'];
|
||||
if (offGrid != null && offGrid is! bool) return null;
|
||||
return _build(
|
||||
id: 'offband:$id',
|
||||
title: title,
|
||||
region: region,
|
||||
frequency: (e['frequency'] as num).toDouble(),
|
||||
bandwidthKHz: (e['bandwidth'] as num).toDouble(),
|
||||
sf: _asInt(e['spreading_factor']),
|
||||
cr: _asInt(e['coding_rate']),
|
||||
source: RadioPresetSource.offband,
|
||||
txPowerDbm: tx as int?,
|
||||
pathHashBytes: hash as int?,
|
||||
offGrid: offGrid == true,
|
||||
);
|
||||
}
|
||||
|
||||
RadioPreset? _build({
|
||||
required String id,
|
||||
required String title,
|
||||
required String region,
|
||||
required double? frequency,
|
||||
required double? bandwidthKHz,
|
||||
required int? sf,
|
||||
required int? cr,
|
||||
required RadioPresetSource source,
|
||||
int? txPowerDbm,
|
||||
int? pathHashBytes,
|
||||
bool offGrid = false,
|
||||
}) {
|
||||
if (frequency == null || frequency < 150 || frequency > 2500) return null;
|
||||
if (bandwidthKHz == null) return null;
|
||||
final bwHz = (bandwidthKHz * 1000).round();
|
||||
final bandwidth = LoRaBandwidth.values
|
||||
.where((b) => (b.hz - bwHz).abs() <= 50)
|
||||
.firstOrNull;
|
||||
final spreading = LoRaSpreadingFactor.values
|
||||
.where((s) => s.value == sf)
|
||||
.firstOrNull;
|
||||
final coding = LoRaCodingRate.values.where((c) => c.value == cr).firstOrNull;
|
||||
if (bandwidth == null || spreading == null || coding == null) return null;
|
||||
return RadioPreset(
|
||||
id: id,
|
||||
title: title.trim(),
|
||||
region: region.trim(),
|
||||
frequencyMHz: frequency,
|
||||
bandwidth: bandwidth,
|
||||
spreadingFactor: spreading,
|
||||
codingRate: coding,
|
||||
source: source,
|
||||
txPowerDbm: txPowerDbm,
|
||||
pathHashBytes: pathHashBytes,
|
||||
offGrid: offGrid,
|
||||
);
|
||||
}
|
||||
|
||||
bool _validHash(int? bytes) => bytes != null && bytes >= 1 && bytes <= 3;
|
||||
|
||||
double? _asDouble(Object? v) {
|
||||
if (v is num) return v.toDouble();
|
||||
if (v is String) return double.tryParse(v.trim());
|
||||
return null;
|
||||
}
|
||||
|
||||
int? _asInt(Object? v) {
|
||||
final d = _asDouble(v);
|
||||
if (d == null || d != d.roundToDouble()) return null;
|
||||
return d.round();
|
||||
}
|
||||
|
||||
/// The picker group for an upstream title, which carries no region field:
|
||||
/// the part before " - ", ":" or " (" ("USA - Southern California" -> "USA",
|
||||
/// "Australia: QLD" -> "Australia", "EU/UK (Narrow)" -> "EU/UK"), otherwise the
|
||||
/// title without a trailing band number ("Portugal 433" -> "Portugal"),
|
||||
/// otherwise the whole title ("Costa Rica").
|
||||
String upstreamRegionFor(String title) {
|
||||
final t = title.trim();
|
||||
var cut = t.length;
|
||||
for (final sep in const [' - ', ':', ' (']) {
|
||||
final i = t.indexOf(sep);
|
||||
if (i > 0 && i < cut) cut = i;
|
||||
}
|
||||
if (cut < t.length) return t.substring(0, cut).trim();
|
||||
final band = RegExp(r'^(.+?)\s+\d+$').firstMatch(t);
|
||||
return band != null ? band.group(1)! : t;
|
||||
}
|
||||
@ -0,0 +1,624 @@
|
||||
/// MeshCore stock companion config export format (#572, epic #568).
|
||||
///
|
||||
/// This is a faithful model of the JSON file the official MeshCore Companion
|
||||
/// app writes from its Export Config screen, so that a stock export imports
|
||||
/// into Offband and an Offband export imports into stock. The shape was
|
||||
/// reverse-engineered from ten real exports across five radios (2359 contacts,
|
||||
/// 76 channels); the evidence is recorded on issue #569.
|
||||
///
|
||||
/// Rules the format imposes, none of them obvious:
|
||||
///
|
||||
/// * **There is no version field.** Stock writes none, so we write none, and
|
||||
/// validation is by shape alone. Every top-level section is independently
|
||||
/// optional because the export screen lets the user deselect any of them.
|
||||
/// * `public_key` and `private_key` are one unit: stock's single "Private
|
||||
/// Identity Key" control emits both or neither.
|
||||
/// * `radio_settings` mixes units: `frequency` is kHz, `bandwidth` is Hz, and
|
||||
/// `coding_rate` is a bare denominator (5 means 4/5).
|
||||
/// * Latitudes and longitudes are JSON **strings**, never numbers.
|
||||
/// * `channels` has no index field; array position is the channel index.
|
||||
/// * Contact timestamps are whatever the mesh reported and are not sanitized.
|
||||
/// The real corpus contains values from epoch 14 to the year 2095.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../connector/meshcore_protocol.dart' show pubKeyToHex;
|
||||
|
||||
/// Thrown when a config file does not match the stock format.
|
||||
///
|
||||
/// Carries the offending JSON path so an import screen can tell the user which
|
||||
/// part of the file is wrong rather than just "invalid file".
|
||||
class StockConfigFormatException implements Exception {
|
||||
StockConfigFormatException(this.message, {this.path});
|
||||
|
||||
final String message;
|
||||
|
||||
/// Dotted path to the offending value, e.g. `contacts[3].out_path_list`.
|
||||
final String? path;
|
||||
|
||||
@override
|
||||
String toString() => path == null
|
||||
? 'StockConfigFormatException: $message'
|
||||
: 'StockConfigFormatException at $path: $message';
|
||||
}
|
||||
|
||||
/// Firmware caps a contact name at `char name[32]`, so 31 usable characters.
|
||||
const int kStockMaxContactNameChars = 31;
|
||||
|
||||
const int _publicKeyBytes = 32;
|
||||
const int _privateKeyBytes = 64;
|
||||
const int _channelSecretBytes = 16;
|
||||
|
||||
/// Hop-hash widths the parser will accept, in bytes.
|
||||
///
|
||||
/// Only width 2 has been observed in the wild (a single path across the whole
|
||||
/// corpus). 1 and 3 are accepted because the firmware path-length byte encodes
|
||||
/// widths 1..3 (#309) and there is no reason stock would refuse to emit them.
|
||||
/// Anything else is rejected rather than guessed at.
|
||||
const Set<int> kStockPathHashWidths = {1, 2, 3};
|
||||
|
||||
Uint8List _parseHex(String value, String path, {int? expectBytes}) {
|
||||
if (value.length.isOdd) {
|
||||
throw StockConfigFormatException(
|
||||
'expected hex, got an odd number of characters (${value.length})',
|
||||
path: path,
|
||||
);
|
||||
}
|
||||
final bytes = Uint8List(value.length ~/ 2);
|
||||
for (var i = 0; i < bytes.length; i++) {
|
||||
final byte = int.tryParse(value.substring(i * 2, i * 2 + 2), radix: 16);
|
||||
if (byte == null) {
|
||||
throw StockConfigFormatException('expected hex characters', path: path);
|
||||
}
|
||||
bytes[i] = byte;
|
||||
}
|
||||
if (expectBytes != null && bytes.length != expectBytes) {
|
||||
throw StockConfigFormatException(
|
||||
'expected $expectBytes bytes, got ${bytes.length}',
|
||||
path: path,
|
||||
);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
Map<String, dynamic> _asObject(Object? value, String path) {
|
||||
if (value is! Map) {
|
||||
throw StockConfigFormatException('expected an object', path: path);
|
||||
}
|
||||
return value.cast<String, dynamic>();
|
||||
}
|
||||
|
||||
int _asInt(Object? value, String path) {
|
||||
if (value is int) return value;
|
||||
throw StockConfigFormatException('expected an integer', path: path);
|
||||
}
|
||||
|
||||
bool _asBool(Object? value, String path) {
|
||||
if (value is bool) return value;
|
||||
throw StockConfigFormatException('expected a boolean', path: path);
|
||||
}
|
||||
|
||||
String _asString(Object? value, String path) {
|
||||
if (value is String) return value;
|
||||
throw StockConfigFormatException('expected a string', path: path);
|
||||
}
|
||||
|
||||
/// Stock writes coordinates as decimal strings, so `0.0` and `39.561991` both
|
||||
/// appear verbatim. Dart's shortest-round-trip `double.toString()` reproduces
|
||||
/// exactly that, which is why [_coordToJson] is a plain `toString`.
|
||||
double _parseCoord(Object? value, String path) {
|
||||
final text = _asString(value, path);
|
||||
final parsed = double.tryParse(text);
|
||||
if (parsed == null) {
|
||||
throw StockConfigFormatException(
|
||||
'expected a decimal coordinate string',
|
||||
path: path,
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
String _coordToJson(double value) => value.toString();
|
||||
|
||||
/// LoRa parameters. Units differ per field. See the class doc on [StockConfig].
|
||||
class StockRadioSettings {
|
||||
const StockRadioSettings({
|
||||
required this.frequencyKhz,
|
||||
required this.bandwidthHz,
|
||||
required this.spreadingFactor,
|
||||
required this.codingRate,
|
||||
required this.txPower,
|
||||
});
|
||||
|
||||
/// `frequency`, in **kHz** (910525 means 910.525 MHz).
|
||||
final int frequencyKhz;
|
||||
|
||||
/// `bandwidth`, in **Hz** (62500 means 62.5 kHz).
|
||||
final int bandwidthHz;
|
||||
|
||||
final int spreadingFactor;
|
||||
|
||||
/// `coding_rate`, the **denominator only**, 5 means 4/5.
|
||||
final int codingRate;
|
||||
|
||||
/// `tx_power`, in dBm.
|
||||
final int txPower;
|
||||
|
||||
factory StockRadioSettings.fromJson(Map<String, dynamic> json, String path) {
|
||||
return StockRadioSettings(
|
||||
frequencyKhz: _asInt(json['frequency'], '$path.frequency'),
|
||||
bandwidthHz: _asInt(json['bandwidth'], '$path.bandwidth'),
|
||||
spreadingFactor: _asInt(
|
||||
json['spreading_factor'],
|
||||
'$path.spreading_factor',
|
||||
),
|
||||
codingRate: _asInt(json['coding_rate'], '$path.coding_rate'),
|
||||
txPower: _asInt(json['tx_power'], '$path.tx_power'),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'frequency': frequencyKhz,
|
||||
'bandwidth': bandwidthHz,
|
||||
'spreading_factor': spreadingFactor,
|
||||
'coding_rate': codingRate,
|
||||
'tx_power': txPower,
|
||||
};
|
||||
}
|
||||
|
||||
/// The device's own advertised position. Both values are strings on the wire.
|
||||
class StockPositionSettings {
|
||||
const StockPositionSettings({
|
||||
required this.latitude,
|
||||
required this.longitude,
|
||||
});
|
||||
|
||||
final double latitude;
|
||||
final double longitude;
|
||||
|
||||
factory StockPositionSettings.fromJson(
|
||||
Map<String, dynamic> json,
|
||||
String path,
|
||||
) {
|
||||
return StockPositionSettings(
|
||||
latitude: _parseCoord(json['latitude'], '$path.latitude'),
|
||||
longitude: _parseCoord(json['longitude'], '$path.longitude'),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'latitude': _coordToJson(latitude),
|
||||
'longitude': _coordToJson(longitude),
|
||||
};
|
||||
}
|
||||
|
||||
/// Stock's "Other Settings". Both fields are ints on the wire even though they
|
||||
/// read as booleans in the UI: `manual_add_contacts` is emitted as 0/1, not
|
||||
/// true/false, unlike the [StockAutoAddSettings] block.
|
||||
class StockOtherSettings {
|
||||
const StockOtherSettings({
|
||||
required this.manualAddContacts,
|
||||
required this.advertLocationPolicy,
|
||||
});
|
||||
|
||||
final int manualAddContacts;
|
||||
|
||||
/// Shown in stock's UI as "Share Position in Advert".
|
||||
final int advertLocationPolicy;
|
||||
|
||||
factory StockOtherSettings.fromJson(Map<String, dynamic> json, String path) {
|
||||
return StockOtherSettings(
|
||||
manualAddContacts: _asInt(
|
||||
json['manual_add_contacts'],
|
||||
'$path.manual_add_contacts',
|
||||
),
|
||||
advertLocationPolicy: _asInt(
|
||||
json['advert_location_policy'],
|
||||
'$path.advert_location_policy',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'manual_add_contacts': manualAddContacts,
|
||||
'advert_location_policy': advertLocationPolicy,
|
||||
};
|
||||
}
|
||||
|
||||
/// Stock's "Auto Add Settings". Booleans here really are JSON booleans.
|
||||
class StockAutoAddSettings {
|
||||
const StockAutoAddSettings({
|
||||
required this.autoAddChat,
|
||||
required this.autoAddRepeater,
|
||||
required this.autoAddRoomServer,
|
||||
required this.autoAddSensor,
|
||||
required this.overwriteOldest,
|
||||
required this.autoAddMaxHops,
|
||||
});
|
||||
|
||||
final bool autoAddChat;
|
||||
final bool autoAddRepeater;
|
||||
final bool autoAddRoomServer;
|
||||
final bool autoAddSensor;
|
||||
final bool overwriteOldest;
|
||||
|
||||
/// `auto_add_max_hops`; stock renders 0 as "(no limit)".
|
||||
final int autoAddMaxHops;
|
||||
|
||||
factory StockAutoAddSettings.fromJson(
|
||||
Map<String, dynamic> json,
|
||||
String path,
|
||||
) {
|
||||
return StockAutoAddSettings(
|
||||
autoAddChat: _asBool(json['auto_add_chat'], '$path.auto_add_chat'),
|
||||
autoAddRepeater: _asBool(
|
||||
json['auto_add_repeater'],
|
||||
'$path.auto_add_repeater',
|
||||
),
|
||||
autoAddRoomServer: _asBool(
|
||||
json['auto_add_room_server'],
|
||||
'$path.auto_add_room_server',
|
||||
),
|
||||
autoAddSensor: _asBool(json['auto_add_sensor'], '$path.auto_add_sensor'),
|
||||
overwriteOldest: _asBool(
|
||||
json['overwrite_oldest'],
|
||||
'$path.overwrite_oldest',
|
||||
),
|
||||
autoAddMaxHops: _asInt(
|
||||
json['auto_add_max_hops'],
|
||||
'$path.auto_add_max_hops',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'auto_add_chat': autoAddChat,
|
||||
'auto_add_repeater': autoAddRepeater,
|
||||
'auto_add_room_server': autoAddRoomServer,
|
||||
'auto_add_sensor': autoAddSensor,
|
||||
'overwrite_oldest': overwriteOldest,
|
||||
'auto_add_max_hops': autoAddMaxHops,
|
||||
};
|
||||
}
|
||||
|
||||
/// One channel. The array position in [StockConfig.channels] is the index:
|
||||
/// the record itself carries no index field.
|
||||
class StockChannel {
|
||||
const StockChannel({required this.name, required this.secret});
|
||||
|
||||
final String name;
|
||||
|
||||
/// The 16-byte PSK, hex on the wire.
|
||||
final Uint8List secret;
|
||||
|
||||
factory StockChannel.fromJson(Map<String, dynamic> json, String path) {
|
||||
return StockChannel(
|
||||
name: _asString(json['name'], '$path.name'),
|
||||
secret: _parseHex(
|
||||
_asString(json['secret'], '$path.secret'),
|
||||
'$path.secret',
|
||||
expectBytes: _channelSecretBytes,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'name': name,
|
||||
'secret': pubKeyToHex(secret),
|
||||
};
|
||||
}
|
||||
|
||||
/// A contact's routing path, as carried by `out_path_list`.
|
||||
///
|
||||
/// Stock writes one comma-separated element per hop, each element being that
|
||||
/// hop's hash in hex, so `"a1b2,c3d4"` is two hops at width 2. That maps
|
||||
/// directly onto our width-aware path model (#309): [hopCount] is our hash
|
||||
/// count and [hashWidth] is our per-hop width. Neither is inferred.
|
||||
class StockOutPath {
|
||||
StockOutPath({required this.hashWidth, required this.bytes})
|
||||
: assert(hashWidth > 0),
|
||||
assert(bytes.length % hashWidth == 0);
|
||||
|
||||
/// The `""` form of the field, as distinct from the key being null.
|
||||
///
|
||||
/// Both mean "no path" and the corpus contains 10 of these against 2448
|
||||
/// nulls, but stock writes both and we do not know what distinguishes them.
|
||||
/// Keeping them apart costs one constructor and makes an Offband re-export
|
||||
/// byte-identical to its source, so we keep them apart.
|
||||
StockOutPath.empty() : hashWidth = 0, bytes = _noBytes;
|
||||
|
||||
static final Uint8List _noBytes = Uint8List(0);
|
||||
|
||||
/// Bytes per hop hash, 1..3, or 0 for [StockOutPath.empty].
|
||||
/// See [kStockPathHashWidths].
|
||||
final int hashWidth;
|
||||
|
||||
/// Flattened hop hashes, `hopCount * hashWidth` bytes.
|
||||
final Uint8List bytes;
|
||||
|
||||
int get hopCount => hashWidth == 0 ? 0 : bytes.length ~/ hashWidth;
|
||||
|
||||
/// Parses `out_path_list`. A null key returns null; `""` returns
|
||||
/// [StockOutPath.empty]. Both mean the contact has no route.
|
||||
static StockOutPath? fromJson(Object? value, String path) {
|
||||
if (value == null) return null;
|
||||
final text = _asString(value, path);
|
||||
if (text.isEmpty) return StockOutPath.empty();
|
||||
|
||||
final elements = text.split(',');
|
||||
final widths = elements.map((e) => e.length).toSet();
|
||||
if (widths.length != 1) {
|
||||
throw StockConfigFormatException(
|
||||
'hop hashes must all be the same width, got $widths',
|
||||
path: path,
|
||||
);
|
||||
}
|
||||
final chars = widths.single;
|
||||
if (chars.isOdd || !kStockPathHashWidths.contains(chars ~/ 2)) {
|
||||
throw StockConfigFormatException(
|
||||
'unsupported hop hash width of $chars characters',
|
||||
path: path,
|
||||
);
|
||||
}
|
||||
|
||||
final width = chars ~/ 2;
|
||||
final bytes = BytesBuilder();
|
||||
for (final element in elements) {
|
||||
bytes.add(_parseHex(element, path, expectBytes: width));
|
||||
}
|
||||
return StockOutPath(hashWidth: width, bytes: bytes.toBytes());
|
||||
}
|
||||
|
||||
String toJson() {
|
||||
if (hashWidth == 0) return '';
|
||||
final hops = <String>[];
|
||||
for (var i = 0; i < bytes.length; i += hashWidth) {
|
||||
hops.add(pubKeyToHex(Uint8List.sublistView(bytes, i, i + hashWidth)));
|
||||
}
|
||||
return hops.join(',');
|
||||
}
|
||||
}
|
||||
|
||||
/// One contact. This is a near 1:1 serialization of the firmware's
|
||||
/// `ContactInfo` struct, with [customName] as the one app-side addition.
|
||||
class StockContact {
|
||||
const StockContact({
|
||||
required this.type,
|
||||
required this.name,
|
||||
required this.publicKey,
|
||||
required this.flags,
|
||||
required this.latitude,
|
||||
required this.longitude,
|
||||
required this.lastAdvert,
|
||||
required this.lastModified,
|
||||
this.customName,
|
||||
this.outPath,
|
||||
});
|
||||
|
||||
/// `ADV_TYPE_*`: 1 chat, 2 repeater, 3 room, 4 sensor.
|
||||
final int type;
|
||||
|
||||
final String name;
|
||||
|
||||
/// App-side rename. Null in all 2359 contacts of the reference corpus, so
|
||||
/// its round-trip behavior is carried but unverified (#569).
|
||||
final String? customName;
|
||||
|
||||
final Uint8List publicKey;
|
||||
|
||||
/// Bit 0 is "favourite" (firmware `flags & 0x01`).
|
||||
final int flags;
|
||||
|
||||
final double latitude;
|
||||
final double longitude;
|
||||
|
||||
/// Epoch seconds by THEIR clock. **Not sanitized**: the reference corpus
|
||||
/// ranges from 14 to the year 2095. Kept as a raw int so no caller mistakes
|
||||
/// it for a trustworthy time.
|
||||
final int lastAdvert;
|
||||
|
||||
/// Epoch seconds by OUR clock. Same caveat as [lastAdvert].
|
||||
final int lastModified;
|
||||
|
||||
final StockOutPath? outPath;
|
||||
|
||||
bool get isFavourite => flags & 0x01 != 0;
|
||||
|
||||
factory StockContact.fromJson(Map<String, dynamic> json, String path) {
|
||||
return StockContact(
|
||||
type: _asInt(json['type'], '$path.type'),
|
||||
name: _asString(json['name'], '$path.name'),
|
||||
customName: json['custom_name'] == null
|
||||
? null
|
||||
: _asString(json['custom_name'], '$path.custom_name'),
|
||||
publicKey: _parseHex(
|
||||
_asString(json['public_key'], '$path.public_key'),
|
||||
'$path.public_key',
|
||||
expectBytes: _publicKeyBytes,
|
||||
),
|
||||
flags: _asInt(json['flags'], '$path.flags'),
|
||||
latitude: _parseCoord(json['latitude'], '$path.latitude'),
|
||||
longitude: _parseCoord(json['longitude'], '$path.longitude'),
|
||||
lastAdvert: _asInt(json['last_advert'], '$path.last_advert'),
|
||||
lastModified: _asInt(json['last_modified'], '$path.last_modified'),
|
||||
outPath: StockOutPath.fromJson(
|
||||
json['out_path_list'],
|
||||
'$path.out_path_list',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
if (name.length > kStockMaxContactNameChars) {
|
||||
throw StockConfigFormatException(
|
||||
'contact name is ${name.length} characters; stock firmware stores at '
|
||||
'most $kStockMaxContactNameChars and would truncate it',
|
||||
path: 'contacts[].name',
|
||||
);
|
||||
}
|
||||
return {
|
||||
'type': type,
|
||||
'name': name,
|
||||
'custom_name': customName,
|
||||
'public_key': pubKeyToHex(publicKey),
|
||||
'flags': flags,
|
||||
'latitude': _coordToJson(latitude),
|
||||
'longitude': _coordToJson(longitude),
|
||||
'last_advert': lastAdvert,
|
||||
'last_modified': lastModified,
|
||||
'out_path_list': outPath?.toJson(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// A whole stock config export.
|
||||
///
|
||||
/// Every section is nullable, and null means "the user did not select this
|
||||
/// section", which is distinct from an empty list. Absent sections are omitted
|
||||
/// from [toJson] entirely rather than written as null, matching stock.
|
||||
class StockConfig {
|
||||
const StockConfig({
|
||||
this.name,
|
||||
this.publicKey,
|
||||
this.privateKey,
|
||||
this.radioSettings,
|
||||
this.positionSettings,
|
||||
this.otherSettings,
|
||||
this.autoAddSettings,
|
||||
this.channels,
|
||||
this.contacts,
|
||||
});
|
||||
|
||||
final String? name;
|
||||
|
||||
/// 32 bytes. Travels as a unit with [privateKey]: stock's identity control
|
||||
/// emits both or neither.
|
||||
final Uint8List? publicKey;
|
||||
|
||||
/// 64 bytes. See [publicKey].
|
||||
final Uint8List? privateKey;
|
||||
|
||||
final StockRadioSettings? radioSettings;
|
||||
final StockPositionSettings? positionSettings;
|
||||
final StockOtherSettings? otherSettings;
|
||||
final StockAutoAddSettings? autoAddSettings;
|
||||
|
||||
/// Ordered; array position is the channel index.
|
||||
final List<StockChannel>? channels;
|
||||
|
||||
final List<StockContact>? contacts;
|
||||
|
||||
/// Parses a decoded JSON object.
|
||||
///
|
||||
/// Unknown top-level keys are ignored, not rejected: the format has no
|
||||
/// version field, so tolerating additions is the only way to survive a stock
|
||||
/// release that adds one.
|
||||
factory StockConfig.fromJson(Map<String, dynamic> json) {
|
||||
final channelsJson = json['channels'];
|
||||
final contactsJson = json['contacts'];
|
||||
|
||||
return StockConfig(
|
||||
name: json['name'] == null ? null : _asString(json['name'], 'name'),
|
||||
publicKey: json['public_key'] == null
|
||||
? null
|
||||
: _parseHex(
|
||||
_asString(json['public_key'], 'public_key'),
|
||||
'public_key',
|
||||
expectBytes: _publicKeyBytes,
|
||||
),
|
||||
privateKey: json['private_key'] == null
|
||||
? null
|
||||
: _parseHex(
|
||||
_asString(json['private_key'], 'private_key'),
|
||||
'private_key',
|
||||
expectBytes: _privateKeyBytes,
|
||||
),
|
||||
radioSettings: json['radio_settings'] == null
|
||||
? null
|
||||
: StockRadioSettings.fromJson(
|
||||
_asObject(json['radio_settings'], 'radio_settings'),
|
||||
'radio_settings',
|
||||
),
|
||||
positionSettings: json['position_settings'] == null
|
||||
? null
|
||||
: StockPositionSettings.fromJson(
|
||||
_asObject(json['position_settings'], 'position_settings'),
|
||||
'position_settings',
|
||||
),
|
||||
otherSettings: json['other_settings'] == null
|
||||
? null
|
||||
: StockOtherSettings.fromJson(
|
||||
_asObject(json['other_settings'], 'other_settings'),
|
||||
'other_settings',
|
||||
),
|
||||
autoAddSettings: json['auto_add_settings'] == null
|
||||
? null
|
||||
: StockAutoAddSettings.fromJson(
|
||||
_asObject(json['auto_add_settings'], 'auto_add_settings'),
|
||||
'auto_add_settings',
|
||||
),
|
||||
channels: channelsJson == null
|
||||
? null
|
||||
: _parseList(
|
||||
channelsJson,
|
||||
'channels',
|
||||
(item, path) =>
|
||||
StockChannel.fromJson(_asObject(item, path), path),
|
||||
),
|
||||
contacts: contactsJson == null
|
||||
? null
|
||||
: _parseList(
|
||||
contactsJson,
|
||||
'contacts',
|
||||
(item, path) =>
|
||||
StockContact.fromJson(_asObject(item, path), path),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
static List<T> _parseList<T>(
|
||||
Object? value,
|
||||
String path,
|
||||
T Function(Object? item, String itemPath) parse,
|
||||
) {
|
||||
if (value is! List) {
|
||||
throw StockConfigFormatException('expected an array', path: path);
|
||||
}
|
||||
final result = <T>[];
|
||||
for (var i = 0; i < value.length; i++) {
|
||||
result.add(parse(value[i], '$path[$i]'));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Parses raw file text.
|
||||
factory StockConfig.parse(String source) {
|
||||
final Object? decoded;
|
||||
try {
|
||||
decoded = jsonDecode(source);
|
||||
} on FormatException catch (e) {
|
||||
throw StockConfigFormatException('file is not valid JSON: ${e.message}');
|
||||
}
|
||||
return StockConfig.fromJson(_asObject(decoded, r'$'));
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
if (name != null) 'name': name,
|
||||
if (publicKey != null) 'public_key': pubKeyToHex(publicKey!),
|
||||
if (privateKey != null) 'private_key': pubKeyToHex(privateKey!),
|
||||
if (radioSettings != null) 'radio_settings': radioSettings!.toJson(),
|
||||
if (positionSettings != null)
|
||||
'position_settings': positionSettings!.toJson(),
|
||||
if (otherSettings != null) 'other_settings': otherSettings!.toJson(),
|
||||
if (autoAddSettings != null)
|
||||
'auto_add_settings': autoAddSettings!.toJson(),
|
||||
if (channels != null) 'channels': [for (final c in channels!) c.toJson()],
|
||||
if (contacts != null) 'contacts': [for (final c in contacts!) c.toJson()],
|
||||
};
|
||||
}
|
||||
|
||||
String encode() => jsonEncode(toJson());
|
||||
}
|
||||
@ -0,0 +1,46 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../helpers/snack_bar_builder.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../models/contact.dart';
|
||||
import '../utils/platform_info.dart';
|
||||
import '../widgets/qr_scanner_widget.dart';
|
||||
|
||||
/// Whether a contact QR can be scanned on this platform.
|
||||
///
|
||||
/// `mobile_scanner` covers Android, iOS, macOS and web, but not Windows or
|
||||
/// Linux. On those the QR half of the exchange is the RENDER side: show your
|
||||
/// own code from the desktop and let the other person scan it with a phone.
|
||||
///
|
||||
/// Lives here rather than on a caller because both the key-entry field and the
|
||||
/// contacts menu need it. (#629)
|
||||
bool get contactQrScanAvailable =>
|
||||
PlatformInfo.isMobile || PlatformInfo.isMacOS || PlatformInfo.isWeb;
|
||||
|
||||
/// Scans a contact QR and pops the raw `meshcore://contact/add` string. (#629)
|
||||
///
|
||||
/// A contact QR is only that URI rendered visually, so this validates with the
|
||||
/// same [Contact.isValidShareUri] the paste path uses. There is no second
|
||||
/// format and no second parser.
|
||||
class ContactQrScannerScreen extends StatelessWidget {
|
||||
const ContactQrScannerScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(context.l10n.contacts_scanContactQr),
|
||||
centerTitle: true,
|
||||
),
|
||||
body: QrScannerWidget(
|
||||
instructions: context.l10n.contacts_scanContactQrInstructions,
|
||||
validator: Contact.isValidShareUri,
|
||||
onScanned: (data) => Navigator.of(context).pop(data),
|
||||
onValidationFailed: (_) => showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(context.l10n.contacts_invalidContactQr),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,310 @@
|
||||
/// Stock-compatible config export (#574, epic #568).
|
||||
///
|
||||
/// Mirrors the stock app's Export Config screen: a list of sections, Select All
|
||||
/// and Deselect All, and **everything checked by default**. The asymmetry with
|
||||
/// the import screen (which starts with nothing checked) is deliberate and
|
||||
/// copied from stock: opt out on the way out, opt in on the way in.
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../services/stock_config_export_service.dart';
|
||||
import '../utils/stock_config_file.dart';
|
||||
import '../widgets/adaptive_app_bar_title.dart';
|
||||
|
||||
class ExportConfigScreen extends StatefulWidget {
|
||||
const ExportConfigScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ExportConfigScreen> createState() => _ExportConfigScreenState();
|
||||
}
|
||||
|
||||
class _ExportConfigScreenState extends State<ExportConfigScreen> {
|
||||
/// Every section starts selected, matching stock.
|
||||
final Set<StockConfigSection> _selected = StockConfigSection.values.toSet();
|
||||
bool _busy = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final connector = context.watch<MeshCoreConnector>();
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: AdaptiveAppBarTitle(l10n.exportConfig_title),
|
||||
centerTitle: true,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.check),
|
||||
onPressed: _busy ? null : () => _export(connector),
|
||||
tooltip: l10n.exportConfig_title,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: ListView(
|
||||
children: [
|
||||
_Banner(text: l10n.exportConfig_instruction),
|
||||
_Banner(text: l10n.exportConfig_lossyNotice, subdued: true),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
setState(() => _selected.addAll(StockConfigSection.values)),
|
||||
child: Text(l10n.stockConfig_selectAll),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => setState(_selected.clear),
|
||||
child: Text(l10n.stockConfig_deselectAll),
|
||||
),
|
||||
],
|
||||
),
|
||||
for (final section in StockConfigSection.values)
|
||||
_SectionTile(
|
||||
title: sectionLabel(context, section, connector),
|
||||
subtitle: _subtitleFor(section, connector),
|
||||
selected: _selected.contains(section),
|
||||
onChanged: (value) => setState(() {
|
||||
if (value) {
|
||||
_selected.add(section);
|
||||
} else {
|
||||
_selected.remove(section);
|
||||
}
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String? _subtitleFor(
|
||||
StockConfigSection section,
|
||||
MeshCoreConnector connector,
|
||||
) {
|
||||
final l10n = context.l10n;
|
||||
switch (section) {
|
||||
case StockConfigSection.name:
|
||||
return connector.selfName;
|
||||
case StockConfigSection.identity:
|
||||
final key = connector.selfPublicKeyHex;
|
||||
final abbreviated = key.length > 12
|
||||
? '${key.substring(0, 6)}...${key.substring(key.length - 6)}'
|
||||
: key;
|
||||
// The private key is never rendered, not even abbreviated.
|
||||
return '${l10n.stockConfig_identityWarning}\n'
|
||||
'${l10n.stockConfig_publicKeyLabel(abbreviated)}\n'
|
||||
'${l10n.stockConfig_privateKeyHidden}';
|
||||
case StockConfigSection.radioSettings:
|
||||
final freq = connector.currentFreqHz;
|
||||
final bw = connector.currentBwHz;
|
||||
if (freq == null || bw == null) return null;
|
||||
// currentFreqHz is kHz despite its name; currentBwHz really is Hz.
|
||||
return '${l10n.settings_frequency}: ${freq / 1000} MHz\n'
|
||||
'${l10n.settings_bandwidth}: ${bw / 1000} kHz\n'
|
||||
'${l10n.settings_spreadingFactor}: ${connector.currentSf}\n'
|
||||
'${l10n.settings_codingRate}: ${connector.currentCr}\n'
|
||||
'${l10n.settings_txPower}: ${connector.currentTxPower}';
|
||||
case StockConfigSection.positionSettings:
|
||||
return '${connector.selfLatitude ?? 0}, ${connector.selfLongitude ?? 0}';
|
||||
case StockConfigSection.otherSettings:
|
||||
return null;
|
||||
case StockConfigSection.autoAddSettings:
|
||||
return null;
|
||||
case StockConfigSection.channels:
|
||||
return l10n.exportConfig_allChannels;
|
||||
case StockConfigSection.contacts:
|
||||
return l10n.exportConfig_allContacts;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _export(MeshCoreConnector connector) async {
|
||||
final l10n = context.l10n;
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
|
||||
if (!connector.isConnected) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.exportConfig_notConnected)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (_selected.isEmpty) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.exportConfig_nothingSelected)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() => _busy = true);
|
||||
try {
|
||||
final result = await StockConfigExportService(
|
||||
connector,
|
||||
).build(sections: Set.of(_selected));
|
||||
|
||||
// A section the user asked for that could not be gathered is surfaced
|
||||
// before the file is written, never dropped quietly.
|
||||
if (!result.isComplete) {
|
||||
if (!mounted) return;
|
||||
final proceed = await _confirmOmissions(result);
|
||||
if (proceed != true) return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
|
||||
await saveStockConfigFile(
|
||||
context,
|
||||
json: result.config.encode(),
|
||||
fileName: stockConfigFileName(connector.selfName, DateTime.now()),
|
||||
subject: l10n.exportConfig_shareSubject,
|
||||
);
|
||||
} catch (e) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.exportConfig_failed('$e'))),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool?> _confirmOmissions(StockConfigExportResult result) {
|
||||
final l10n = context.l10n;
|
||||
final connector = context.read<MeshCoreConnector>();
|
||||
return showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(l10n.exportConfig_omittedTitle),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
for (final entry in result.omitted.entries)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Text(
|
||||
_omissionText(
|
||||
context,
|
||||
sectionLabel(context, entry.key, connector),
|
||||
entry.value,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: Text(l10n.exportConfig_cancel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: Text(l10n.exportConfig_exportAnyway),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _omissionText(
|
||||
BuildContext context,
|
||||
String section,
|
||||
StockConfigOmission reason,
|
||||
) {
|
||||
final l10n = context.l10n;
|
||||
switch (reason) {
|
||||
case StockConfigOmission.unsupported:
|
||||
return l10n.exportConfig_omittedUnsupported(section);
|
||||
case StockConfigOmission.noReply:
|
||||
return l10n.exportConfig_omittedNoReply(section);
|
||||
case StockConfigOmission.rejected:
|
||||
return l10n.exportConfig_omittedRejected(section);
|
||||
case StockConfigOmission.unavailable:
|
||||
return l10n.exportConfig_omittedUnavailable(section);
|
||||
}
|
||||
}
|
||||
|
||||
/// Section titles, shared with the import screen so the two cannot drift.
|
||||
String sectionLabel(
|
||||
BuildContext context,
|
||||
StockConfigSection section,
|
||||
MeshCoreConnector connector,
|
||||
) {
|
||||
final l10n = context.l10n;
|
||||
switch (section) {
|
||||
case StockConfigSection.name:
|
||||
return l10n.stockConfig_sectionName;
|
||||
case StockConfigSection.identity:
|
||||
return l10n.stockConfig_sectionIdentity;
|
||||
case StockConfigSection.radioSettings:
|
||||
return l10n.stockConfig_sectionRadio;
|
||||
case StockConfigSection.positionSettings:
|
||||
return l10n.stockConfig_sectionPosition;
|
||||
case StockConfigSection.otherSettings:
|
||||
return l10n.stockConfig_sectionOther;
|
||||
case StockConfigSection.autoAddSettings:
|
||||
return l10n.stockConfig_sectionAutoAdd;
|
||||
case StockConfigSection.channels:
|
||||
return l10n.stockConfig_sectionChannels(
|
||||
connector.channels.where((c) => !c.isEmpty).length,
|
||||
);
|
||||
case StockConfigSection.contacts:
|
||||
return l10n.stockConfig_sectionContacts(connector.contacts.length);
|
||||
}
|
||||
}
|
||||
|
||||
class _SectionTile extends StatelessWidget {
|
||||
const _SectionTile({
|
||||
required this.title,
|
||||
required this.selected,
|
||||
required this.onChanged,
|
||||
this.subtitle,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String? subtitle;
|
||||
final bool selected;
|
||||
final ValueChanged<bool> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CheckboxListTile(
|
||||
value: selected,
|
||||
onChanged: (value) => onChanged(value ?? false),
|
||||
controlAffinity: ListTileControlAffinity.trailing,
|
||||
isThreeLine: subtitle != null,
|
||||
title: Text(title),
|
||||
subtitle: subtitle == null ? null : Text(subtitle!),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Banner extends StatelessWidget {
|
||||
const _Banner({required this.text, this.subdued = false});
|
||||
|
||||
final String text;
|
||||
final bool subdued;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
color: theme.colorScheme.surfaceContainerHighest,
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(Icons.info_outline, size: 18, color: theme.colorScheme.primary),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
text,
|
||||
style: subdued ? theme.textTheme.bodySmall : null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,353 @@
|
||||
/// Stock-compatible config import (#576, epic #568).
|
||||
///
|
||||
/// Mirrors the stock app's Import Config screen, including the detail that
|
||||
/// **nothing is checked by default**. Export opts out, import opts in; that
|
||||
/// asymmetry is stock's and it is the safe default in each direction.
|
||||
///
|
||||
/// The per-section wording is stock's own, because the behavior is stock's own:
|
||||
/// contacts are upserted, existing channels are never overwritten, and
|
||||
/// importing an identity is destructive.
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:file_selector/file_selector.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../models/stock_config.dart';
|
||||
import '../services/stock_config_export_service.dart' show StockConfigSection;
|
||||
import '../services/stock_config_import_service.dart';
|
||||
import '../widgets/adaptive_app_bar_title.dart';
|
||||
import 'export_config_screen.dart' show sectionLabel;
|
||||
|
||||
class ImportConfigScreen extends StatefulWidget {
|
||||
const ImportConfigScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ImportConfigScreen> createState() => _ImportConfigScreenState();
|
||||
}
|
||||
|
||||
class _ImportConfigScreenState extends State<ImportConfigScreen> {
|
||||
StockConfig? _config;
|
||||
|
||||
/// Starts empty: import is opt-in, matching stock.
|
||||
final Set<StockConfigSection> _selected = {};
|
||||
bool _busy = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final connector = context.watch<MeshCoreConnector>();
|
||||
final config = _config;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: AdaptiveAppBarTitle(l10n.importConfig_title),
|
||||
centerTitle: true,
|
||||
actions: [
|
||||
if (config != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.check),
|
||||
onPressed: _busy ? null : () => _import(connector, config),
|
||||
tooltip: l10n.importConfig_title,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: config == null
|
||||
? Center(
|
||||
child: FilledButton.icon(
|
||||
onPressed: _busy ? null : _pickFile,
|
||||
icon: const Icon(Icons.folder_open),
|
||||
label: Text(l10n.importConfig_chooseFile),
|
||||
),
|
||||
)
|
||||
: ListView(
|
||||
children: [
|
||||
_Banner(text: l10n.importConfig_instruction),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
setState(() => _selected.addAll(_present(config))),
|
||||
child: Text(l10n.stockConfig_selectAll),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => setState(_selected.clear),
|
||||
child: Text(l10n.stockConfig_deselectAll),
|
||||
),
|
||||
],
|
||||
),
|
||||
// Only sections the file actually carries are offered.
|
||||
for (final section in _present(config))
|
||||
CheckboxListTile(
|
||||
value: _selected.contains(section),
|
||||
controlAffinity: ListTileControlAffinity.trailing,
|
||||
isThreeLine: _noteFor(section) != null,
|
||||
title: Text(_titleFor(section, config, connector)),
|
||||
subtitle: _noteFor(section) == null
|
||||
? null
|
||||
: Text(_noteFor(section)!),
|
||||
onChanged: (value) => setState(() {
|
||||
if (value ?? false) {
|
||||
_selected.add(section);
|
||||
} else {
|
||||
_selected.remove(section);
|
||||
}
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// The sections this particular file carries. A stock export omits whatever
|
||||
/// the exporting user deselected, so an absent section is normal.
|
||||
List<StockConfigSection> _present(StockConfig config) {
|
||||
return [
|
||||
if (config.name != null) StockConfigSection.name,
|
||||
if (config.privateKey != null) StockConfigSection.identity,
|
||||
if (config.radioSettings != null) StockConfigSection.radioSettings,
|
||||
if (config.positionSettings != null) StockConfigSection.positionSettings,
|
||||
if (config.otherSettings != null) StockConfigSection.otherSettings,
|
||||
if (config.autoAddSettings != null) StockConfigSection.autoAddSettings,
|
||||
if (config.channels != null) StockConfigSection.channels,
|
||||
if (config.contacts != null) StockConfigSection.contacts,
|
||||
];
|
||||
}
|
||||
|
||||
String _titleFor(
|
||||
StockConfigSection section,
|
||||
StockConfig config,
|
||||
MeshCoreConnector connector,
|
||||
) {
|
||||
final l10n = context.l10n;
|
||||
// Channel and contact counts come from the FILE here, not the device.
|
||||
switch (section) {
|
||||
case StockConfigSection.channels:
|
||||
return l10n.stockConfig_sectionChannels(config.channels?.length ?? 0);
|
||||
case StockConfigSection.contacts:
|
||||
return l10n.stockConfig_sectionContacts(config.contacts?.length ?? 0);
|
||||
default:
|
||||
return sectionLabel(context, section, connector);
|
||||
}
|
||||
}
|
||||
|
||||
String? _noteFor(StockConfigSection section) {
|
||||
final l10n = context.l10n;
|
||||
switch (section) {
|
||||
case StockConfigSection.identity:
|
||||
return l10n.importConfig_identityWarning;
|
||||
case StockConfigSection.channels:
|
||||
return l10n.importConfig_channelsNote;
|
||||
case StockConfigSection.contacts:
|
||||
return l10n.importConfig_contactsNote;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pickFile() async {
|
||||
final l10n = context.l10n;
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
setState(() => _busy = true);
|
||||
try {
|
||||
final file = await openFile(
|
||||
acceptedTypeGroups: const [
|
||||
XTypeGroup(label: 'JSON', extensions: ['json']),
|
||||
],
|
||||
);
|
||||
if (file == null) return;
|
||||
final source = utf8.decode(
|
||||
await file.readAsBytes(),
|
||||
allowMalformed: true,
|
||||
);
|
||||
final parsed = StockConfig.parse(source);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_config = parsed;
|
||||
_selected.clear();
|
||||
});
|
||||
} on StockConfigFormatException catch (e) {
|
||||
// The exception carries the offending JSON path, so the user is told
|
||||
// which part of the file is wrong rather than just "invalid".
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.importConfig_parseFailed(e.toString()))),
|
||||
);
|
||||
} catch (e) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.importConfig_parseFailed('$e'))),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _import(MeshCoreConnector connector, StockConfig config) async {
|
||||
final l10n = context.l10n;
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
|
||||
if (!connector.isConnected) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.importConfig_notConnected)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (_selected.isEmpty) {
|
||||
messenger.showSnackBar(
|
||||
SnackBar(content: Text(l10n.importConfig_nothingSelected)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Replacing the node identity is irreversible, so it gets its own explicit
|
||||
// confirmation rather than riding along with the rest of the selection.
|
||||
if (_selected.contains(StockConfigSection.identity)) {
|
||||
final confirmed = await _confirmIdentityOverwrite();
|
||||
if (confirmed != true) return;
|
||||
if (!mounted) return;
|
||||
}
|
||||
|
||||
setState(() => _busy = true);
|
||||
try {
|
||||
final result = await StockConfigImportService(
|
||||
connector,
|
||||
).apply(config: config, sections: Set.of(_selected));
|
||||
if (!mounted) return;
|
||||
await _showResult(result, connector);
|
||||
} finally {
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool?> _confirmIdentityOverwrite() {
|
||||
final l10n = context.l10n;
|
||||
return showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(l10n.importConfig_confirmIdentityTitle),
|
||||
content: Text(l10n.importConfig_confirmIdentityBody),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: Text(l10n.importConfig_cancel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: Text(l10n.importConfig_confirmIdentityAccept),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Shows what actually happened. Skipped channels and unapplied sections are
|
||||
/// listed by name with a reason; an import that quietly did less than the
|
||||
/// user asked for is the silent failure SAFELANE section 6 forbids.
|
||||
Future<void> _showResult(
|
||||
StockConfigImportResult result,
|
||||
MeshCoreConnector connector,
|
||||
) {
|
||||
final l10n = context.l10n;
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(l10n.importConfig_resultTitle),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
l10n.importConfig_resultCounts(
|
||||
result.contactsWritten,
|
||||
result.channelsAdded,
|
||||
),
|
||||
),
|
||||
if (result.failed.isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
l10n.importConfig_resultFailedHeading,
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
for (final entry in result.failed.entries)
|
||||
Text(
|
||||
l10n.importConfig_entryLine(
|
||||
sectionLabel(context, entry.key, connector),
|
||||
_reasonText(context, entry.value),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (result.skippedChannels.isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
l10n.importConfig_resultSkippedHeading,
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
for (final skipped in result.skippedChannels)
|
||||
Text(
|
||||
l10n.importConfig_entryLine(
|
||||
skipped.name,
|
||||
_reasonText(context, skipped.reason),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(l10n.importConfig_close),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _reasonText(BuildContext context, StockConfigImportIssue reason) {
|
||||
final l10n = context.l10n;
|
||||
switch (reason) {
|
||||
case StockConfigImportIssue.absentFromFile:
|
||||
return l10n.importConfig_reasonAbsentFromFile;
|
||||
case StockConfigImportIssue.noReply:
|
||||
return l10n.importConfig_reasonNoReply;
|
||||
case StockConfigImportIssue.unsupported:
|
||||
return l10n.importConfig_reasonUnsupported;
|
||||
case StockConfigImportIssue.rejected:
|
||||
return l10n.importConfig_reasonRejected;
|
||||
case StockConfigImportIssue.alreadyPresent:
|
||||
return l10n.importConfig_reasonAlreadyPresent;
|
||||
case StockConfigImportIssue.noFreeSlot:
|
||||
return l10n.importConfig_reasonNoFreeSlot;
|
||||
case StockConfigImportIssue.notWritable:
|
||||
return l10n.importConfig_reasonNotWritable;
|
||||
}
|
||||
}
|
||||
|
||||
class _Banner extends StatelessWidget {
|
||||
const _Banner({required this.text});
|
||||
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
color: theme.colorScheme.surfaceContainerHighest,
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(Icons.info_outline, size: 18, color: theme.colorScheme.primary),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(child: Text(text)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,113 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
/// Default CoreScope instance (OKIMesh). Owner-run; its read API is public.
|
||||
const String kDefaultCoreScopeHost = 'map.okimesh.org';
|
||||
|
||||
/// The two counts CoreScope reports for a packet. [observers] is the number of
|
||||
/// distinct observers (the meaningful reach); [observations] is the total
|
||||
/// sightings, which counts one observer hearing the packet via several paths
|
||||
/// more than once (this is the "Observations (N)" number in CoreScope's UI).
|
||||
class CoreScopeCounts {
|
||||
const CoreScopeCounts({required this.observers, required this.observations});
|
||||
final int observers;
|
||||
final int observations;
|
||||
}
|
||||
|
||||
/// Outcome of a CoreScope query, so the UI can tell "no record of this packet
|
||||
/// yet" apart from "couldn't reach CoreScope" (#571).
|
||||
enum CoreScopeStatus { found, notFound, unreachable }
|
||||
|
||||
class CoreScopeResult {
|
||||
const CoreScopeResult(this.status, [this.counts]);
|
||||
final CoreScopeStatus status;
|
||||
final CoreScopeCounts? counts;
|
||||
|
||||
static const CoreScopeResult notFound = CoreScopeResult(
|
||||
CoreScopeStatus.notFound,
|
||||
);
|
||||
static const CoreScopeResult unreachable = CoreScopeResult(
|
||||
CoreScopeStatus.unreachable,
|
||||
);
|
||||
factory CoreScopeResult.found(CoreScopeCounts counts) =>
|
||||
CoreScopeResult(CoreScopeStatus.found, counts);
|
||||
}
|
||||
|
||||
/// Queries a CoreScope instance for how many observers reported a given packet,
|
||||
/// keyed by the firmware/mesh packet hash (#524). Read-only and best-effort:
|
||||
/// any failure (offline, timeout, non-200, bad body, unknown packet) returns
|
||||
/// null so the chat UI can silently fall back to radio-only. Never throws.
|
||||
class CoreScopeService {
|
||||
CoreScopeService({
|
||||
http.Client? client,
|
||||
this.host = kDefaultCoreScopeHost,
|
||||
this.useTls = true,
|
||||
this.timeout = const Duration(seconds: 6),
|
||||
}) : _client = client ?? http.Client();
|
||||
|
||||
final http.Client _client;
|
||||
final String host;
|
||||
final bool useTls;
|
||||
final Duration timeout;
|
||||
|
||||
/// Distinct observers and total observations for [packetHash] (16 lowercase
|
||||
/// hex chars). `notFound` = CoreScope reachable but has no record of the hash
|
||||
/// yet; `unreachable` = network/HTTP/parse error. Never throws.
|
||||
Future<CoreScopeResult> fetchCounts(String packetHash) async {
|
||||
if (packetHash.isEmpty) return CoreScopeResult.unreachable;
|
||||
final uri = Uri(
|
||||
scheme: useTls ? 'https' : 'http',
|
||||
host: host,
|
||||
path: '/api/packets',
|
||||
queryParameters: {
|
||||
'hash': packetHash,
|
||||
'groupByHash': 'true',
|
||||
'limit': '1',
|
||||
},
|
||||
);
|
||||
appLogger.info('GET $uri', tag: 'CoreScope');
|
||||
try {
|
||||
final resp = await _client.get(uri).timeout(timeout);
|
||||
if (resp.statusCode != 200) {
|
||||
appLogger.warn(
|
||||
'HTTP ${resp.statusCode} for hash $packetHash',
|
||||
tag: 'CoreScope',
|
||||
);
|
||||
return CoreScopeResult.unreachable;
|
||||
}
|
||||
final body = jsonDecode(resp.body);
|
||||
if (body is! Map) return CoreScopeResult.unreachable;
|
||||
final packets = body['packets'];
|
||||
if (packets is! List) return CoreScopeResult.unreachable;
|
||||
if (packets.isEmpty) {
|
||||
appLogger.info('no record yet for $packetHash', tag: 'CoreScope');
|
||||
return CoreScopeResult.notFound;
|
||||
}
|
||||
final first = packets.first;
|
||||
if (first is! Map) return CoreScopeResult.unreachable;
|
||||
final observers = first['observer_count'];
|
||||
if (observers is! num) return CoreScopeResult.unreachable;
|
||||
final observations = first['observation_count'];
|
||||
final counts = CoreScopeCounts(
|
||||
observers: observers.toInt(),
|
||||
observations: observations is num
|
||||
? observations.toInt()
|
||||
: observers.toInt(),
|
||||
);
|
||||
appLogger.info(
|
||||
'observers=${counts.observers} observations=${counts.observations} '
|
||||
'for $packetHash',
|
||||
tag: 'CoreScope',
|
||||
);
|
||||
return CoreScopeResult.found(counts);
|
||||
} catch (e) {
|
||||
appLogger.warn('Query failed for $packetHash: $e', tag: 'CoreScope');
|
||||
return CoreScopeResult.unreachable;
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() => _client.close();
|
||||
}
|
||||
@ -0,0 +1,217 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart' show rootBundle;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../models/radio_preset.dart';
|
||||
import '../storage/prefs_manager.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import 'config_source_service.dart';
|
||||
|
||||
/// Where the preset files are published (OffbandMesh/config-profiles, #721).
|
||||
const String kRadioPresetBaseUrl =
|
||||
'https://raw.githubusercontent.com/OffbandMesh/config-profiles/main/radio-presets/';
|
||||
const String kUpstreamPresetFile = 'meshcore-upstream.json';
|
||||
const String kOverlayPresetFile = 'offband.json';
|
||||
|
||||
/// The copies bundled with the app, so the picker works offline.
|
||||
const String kRadioPresetAssetDir = 'assets/radio_presets/';
|
||||
|
||||
const String _prefsPrefix = 'radio_presets_v1_';
|
||||
const String _prefsRefreshedKey = '${_prefsPrefix}refreshed_at';
|
||||
|
||||
typedef PresetTextLoader = Future<String> Function(String location);
|
||||
|
||||
/// The regional radio preset list (#728): MeshCore's upstream presets plus
|
||||
/// Offband's overlay, merged with the overlay winning on a matching title.
|
||||
///
|
||||
/// Starts from the last good copy (or the bundled one), and refreshes from
|
||||
/// config-profiles on demand. A file that fails to fetch or parse never
|
||||
/// replaces a good copy; the failure is logged and kept in [refreshError] so
|
||||
/// the picker can show it.
|
||||
class RadioPresetService extends ChangeNotifier {
|
||||
RadioPresetService({
|
||||
PresetTextLoader? fetch,
|
||||
PresetTextLoader? loadAsset,
|
||||
SharedPreferences? prefs,
|
||||
DateTime Function()? clock,
|
||||
}) : _fetch = fetch,
|
||||
_loadAsset = loadAsset ?? rootBundle.loadString,
|
||||
_prefsOverride = prefs,
|
||||
_clock = clock ?? DateTime.now;
|
||||
|
||||
final PresetTextLoader? _fetch;
|
||||
final PresetTextLoader _loadAsset;
|
||||
final SharedPreferences? _prefsOverride;
|
||||
final DateTime Function() _clock;
|
||||
ConfigSourceService? _source;
|
||||
|
||||
SharedPreferences get _prefs => _prefsOverride ?? PrefsManager.instance;
|
||||
|
||||
RadioPresetParseResult _upstream = const RadioPresetParseResult([], 0);
|
||||
RadioPresetParseResult _overlay = const RadioPresetParseResult([], 0);
|
||||
List<RadioPreset> _presets = const [];
|
||||
String? _refreshError;
|
||||
DateTime? _lastRefreshed;
|
||||
bool _refreshing = false;
|
||||
|
||||
List<RadioPreset> get presets => _presets;
|
||||
|
||||
/// Entries left out of the files in use because they were malformed.
|
||||
int get skipped => _upstream.skipped + _overlay.skipped;
|
||||
|
||||
/// Why the last refresh (or load) failed, or null when it succeeded.
|
||||
String? get refreshError => _refreshError;
|
||||
DateTime? get lastRefreshed => _lastRefreshed;
|
||||
bool get refreshing => _refreshing;
|
||||
|
||||
/// Load the last good copy of each file, falling back to the bundled one.
|
||||
Future<void> load() async {
|
||||
final errors = <String>[];
|
||||
_upstream = await _loadLocal(
|
||||
kUpstreamPresetFile,
|
||||
parseUpstreamPresets,
|
||||
errors,
|
||||
);
|
||||
_overlay = await _loadLocal(
|
||||
kOverlayPresetFile,
|
||||
parseOverlayPresets,
|
||||
errors,
|
||||
);
|
||||
final stamp = _prefs.getString(_prefsRefreshedKey);
|
||||
_lastRefreshed = stamp == null ? null : DateTime.tryParse(stamp);
|
||||
_refreshError = errors.isEmpty ? null : errors.join('; ');
|
||||
_rebuild();
|
||||
}
|
||||
|
||||
/// Refresh when the copy in use is older than [maxAge] or was never
|
||||
/// refreshed. Returns whether a refresh ran and succeeded.
|
||||
Future<bool> refreshIfStale({
|
||||
Duration maxAge = const Duration(hours: 12),
|
||||
}) async {
|
||||
final last = _lastRefreshed;
|
||||
if (last != null && _clock().difference(last) < maxAge) return false;
|
||||
return refresh();
|
||||
}
|
||||
|
||||
/// Fetch both files from config-profiles. Each file that parses replaces
|
||||
/// its copy and is saved as the new last good copy; each that fails keeps
|
||||
/// the copy in use. Returns true only when both succeeded.
|
||||
Future<bool> refresh() async {
|
||||
if (_refreshing) return false;
|
||||
_refreshing = true;
|
||||
notifyListeners();
|
||||
final errors = <String>[];
|
||||
final upstream = await _fetchRemote(
|
||||
kUpstreamPresetFile,
|
||||
parseUpstreamPresets,
|
||||
errors,
|
||||
);
|
||||
final overlay = await _fetchRemote(
|
||||
kOverlayPresetFile,
|
||||
parseOverlayPresets,
|
||||
errors,
|
||||
);
|
||||
if (upstream != null) _upstream = upstream;
|
||||
if (overlay != null) _overlay = overlay;
|
||||
if (errors.isEmpty) {
|
||||
_lastRefreshed = _clock();
|
||||
await _prefs.setString(
|
||||
_prefsRefreshedKey,
|
||||
_lastRefreshed!.toIso8601String(),
|
||||
);
|
||||
_refreshError = null;
|
||||
} else {
|
||||
_refreshError = errors.join('; ');
|
||||
}
|
||||
_refreshing = false;
|
||||
_rebuild();
|
||||
return errors.isEmpty;
|
||||
}
|
||||
|
||||
Future<RadioPresetParseResult> _loadLocal(
|
||||
String file,
|
||||
RadioPresetParseResult Function(String) parse,
|
||||
List<String> errors,
|
||||
) async {
|
||||
final cached = _prefs.getString('$_prefsPrefix$file');
|
||||
if (cached != null) {
|
||||
try {
|
||||
return parse(cached);
|
||||
} catch (e) {
|
||||
appLogger.warn(
|
||||
'Saved copy of $file unusable, using the bundled one: $e',
|
||||
tag: 'RadioPresets',
|
||||
);
|
||||
}
|
||||
}
|
||||
try {
|
||||
return parse(await _loadAsset('$kRadioPresetAssetDir$file'));
|
||||
} catch (e) {
|
||||
appLogger.error('Bundled $file failed to load: $e', tag: 'RadioPresets');
|
||||
errors.add('$file: $e');
|
||||
return const RadioPresetParseResult([], 0);
|
||||
}
|
||||
}
|
||||
|
||||
Future<RadioPresetParseResult?> _fetchRemote(
|
||||
String file,
|
||||
RadioPresetParseResult Function(String) parse,
|
||||
List<String> errors,
|
||||
) async {
|
||||
final url = '$kRadioPresetBaseUrl$file';
|
||||
try {
|
||||
final text = _fetch != null
|
||||
? await _fetch(url)
|
||||
: await (_source ??= ConfigSourceService()).fetchText(url);
|
||||
final parsed = parse(text);
|
||||
if (parsed.presets.isEmpty) {
|
||||
throw RadioPresetFormatException('$file has no usable presets');
|
||||
}
|
||||
await _prefs.setString('$_prefsPrefix$file', text);
|
||||
if (parsed.skipped > 0) {
|
||||
appLogger.warn(
|
||||
'$file: ${parsed.skipped} malformed preset(s) skipped',
|
||||
tag: 'RadioPresets',
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
} catch (e) {
|
||||
appLogger.warn('Refreshing $file failed: $e', tag: 'RadioPresets');
|
||||
errors.add('$file: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void _rebuild() {
|
||||
_presets = mergeRadioPresets(_upstream.presets, _overlay.presets);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_source?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// Upstream presets plus the overlay. An overlay entry whose title matches an
|
||||
/// upstream one (ignoring case) replaces it. Sorted by region, then title.
|
||||
List<RadioPreset> mergeRadioPresets(
|
||||
List<RadioPreset> upstream,
|
||||
List<RadioPreset> overlay,
|
||||
) {
|
||||
final byTitle = <String, RadioPreset>{
|
||||
for (final p in upstream) p.title.toLowerCase(): p,
|
||||
};
|
||||
for (final p in overlay) {
|
||||
byTitle[p.title.toLowerCase()] = p;
|
||||
}
|
||||
final merged = byTitle.values.toList()
|
||||
..sort((a, b) {
|
||||
final r = a.region.toLowerCase().compareTo(b.region.toLowerCase());
|
||||
return r != 0
|
||||
? r
|
||||
: a.title.toLowerCase().compareTo(b.title.toLowerCase());
|
||||
});
|
||||
return merged;
|
||||
}
|
||||
@ -0,0 +1,260 @@
|
||||
/// Builds a stock-compatible config export from the connected device (#573,
|
||||
/// epic #568).
|
||||
///
|
||||
/// The wire format lives in `models/stock_config.dart`; this service is only
|
||||
/// concerned with reading live state and mapping it across. Section selection
|
||||
/// mirrors stock's Export Config screen, where every section is individually
|
||||
/// checkable and the file simply omits what was not selected.
|
||||
library;
|
||||
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../models/channel.dart';
|
||||
import '../models/contact.dart';
|
||||
import '../models/stock_config.dart';
|
||||
|
||||
/// One checkbox on the export screen. [identity] covers the public and private
|
||||
/// key together, matching stock's single "Private Identity Key" control.
|
||||
enum StockConfigSection {
|
||||
name,
|
||||
identity,
|
||||
radioSettings,
|
||||
positionSettings,
|
||||
otherSettings,
|
||||
autoAddSettings,
|
||||
channels,
|
||||
contacts,
|
||||
}
|
||||
|
||||
/// Why a requested section did not make it into the file.
|
||||
enum StockConfigOmission {
|
||||
/// The device is not connected, or did not answer in time.
|
||||
noReply,
|
||||
|
||||
/// The radio's firmware was built without the feature. Retrying is pointless.
|
||||
unsupported,
|
||||
|
||||
/// The device refused the request.
|
||||
rejected,
|
||||
|
||||
/// The device has not reported this value, so there is nothing to write.
|
||||
unavailable,
|
||||
}
|
||||
|
||||
/// The outcome of an export attempt.
|
||||
///
|
||||
/// [omitted] is the important half: a section the user ticked that could not be
|
||||
/// gathered must be reported, never dropped quietly. The export screen shows
|
||||
/// these before writing the file.
|
||||
class StockConfigExportResult {
|
||||
const StockConfigExportResult({
|
||||
required this.config,
|
||||
required this.included,
|
||||
required this.omitted,
|
||||
});
|
||||
|
||||
final StockConfig config;
|
||||
final Set<StockConfigSection> included;
|
||||
final Map<StockConfigSection, StockConfigOmission> omitted;
|
||||
|
||||
bool get isComplete => omitted.isEmpty;
|
||||
}
|
||||
|
||||
class StockConfigExportService {
|
||||
StockConfigExportService(this._connector);
|
||||
|
||||
final MeshCoreConnector _connector;
|
||||
|
||||
/// Gathers [sections] from the connected device.
|
||||
///
|
||||
/// Reading the identity is the only step that talks to the radio; everything
|
||||
/// else is already in connector state from the SELF_INFO handshake and the
|
||||
/// contact and channel syncs.
|
||||
Future<StockConfigExportResult> build({
|
||||
required Set<StockConfigSection> sections,
|
||||
}) async {
|
||||
final included = <StockConfigSection>{};
|
||||
final omitted = <StockConfigSection, StockConfigOmission>{};
|
||||
|
||||
void include(StockConfigSection section) => included.add(section);
|
||||
void omit(StockConfigSection section, StockConfigOmission why) =>
|
||||
omitted[section] = why;
|
||||
|
||||
String? name;
|
||||
if (sections.contains(StockConfigSection.name)) {
|
||||
name = _connector.selfName;
|
||||
if (name == null) {
|
||||
omit(StockConfigSection.name, StockConfigOmission.unavailable);
|
||||
} else {
|
||||
include(StockConfigSection.name);
|
||||
}
|
||||
}
|
||||
|
||||
Uint8List? publicKey;
|
||||
Uint8List? privateKey;
|
||||
if (sections.contains(StockConfigSection.identity)) {
|
||||
final result = await _connector.exportPrivateKey();
|
||||
switch (result.outcome) {
|
||||
case IdentityTransfer.ok:
|
||||
// The keys travel as a pair, so a missing public key means we write
|
||||
// neither rather than half an identity.
|
||||
final self = _connector.selfPublicKey;
|
||||
if (self == null) {
|
||||
omit(StockConfigSection.identity, StockConfigOmission.unavailable);
|
||||
} else {
|
||||
publicKey = self;
|
||||
privateKey = result.identity;
|
||||
include(StockConfigSection.identity);
|
||||
}
|
||||
case IdentityTransfer.unsupported:
|
||||
omit(StockConfigSection.identity, StockConfigOmission.unsupported);
|
||||
case IdentityTransfer.rejected:
|
||||
omit(StockConfigSection.identity, StockConfigOmission.rejected);
|
||||
case IdentityTransfer.noReply:
|
||||
omit(StockConfigSection.identity, StockConfigOmission.noReply);
|
||||
}
|
||||
}
|
||||
|
||||
StockRadioSettings? radio;
|
||||
if (sections.contains(StockConfigSection.radioSettings)) {
|
||||
radio = _buildRadioSettings();
|
||||
if (radio == null) {
|
||||
omit(StockConfigSection.radioSettings, StockConfigOmission.unavailable);
|
||||
} else {
|
||||
include(StockConfigSection.radioSettings);
|
||||
}
|
||||
}
|
||||
|
||||
StockPositionSettings? position;
|
||||
if (sections.contains(StockConfigSection.positionSettings)) {
|
||||
position = StockPositionSettings(
|
||||
latitude: _connector.selfLatitude ?? 0,
|
||||
longitude: _connector.selfLongitude ?? 0,
|
||||
);
|
||||
include(StockConfigSection.positionSettings);
|
||||
}
|
||||
|
||||
StockOtherSettings? other;
|
||||
if (sections.contains(StockConfigSection.otherSettings)) {
|
||||
other = StockOtherSettings(
|
||||
// The raw device byte, not the connector's inverted convenience flag.
|
||||
manualAddContacts: _connector.manualAddContactsRaw,
|
||||
advertLocationPolicy: _connector.advertLocationPolicy,
|
||||
);
|
||||
include(StockConfigSection.otherSettings);
|
||||
}
|
||||
|
||||
StockAutoAddSettings? autoAdd;
|
||||
if (sections.contains(StockConfigSection.autoAddSettings)) {
|
||||
autoAdd = StockAutoAddSettings(
|
||||
autoAddChat: _connector.autoAddUsers ?? false,
|
||||
autoAddRepeater: _connector.autoAddRepeaters ?? false,
|
||||
autoAddRoomServer: _connector.autoAddRoomServers ?? false,
|
||||
autoAddSensor: _connector.autoAddSensors ?? false,
|
||||
overwriteOldest: _connector.autoAddOverwriteOldest ?? false,
|
||||
autoAddMaxHops: _connector.autoAddMaxHops,
|
||||
);
|
||||
include(StockConfigSection.autoAddSettings);
|
||||
}
|
||||
|
||||
List<StockChannel>? channels;
|
||||
if (sections.contains(StockConfigSection.channels)) {
|
||||
channels = [
|
||||
for (final channel in _connector.channels)
|
||||
if (!channel.isEmpty) toStockChannel(channel),
|
||||
];
|
||||
include(StockConfigSection.channels);
|
||||
}
|
||||
|
||||
List<StockContact>? contacts;
|
||||
if (sections.contains(StockConfigSection.contacts)) {
|
||||
contacts = [
|
||||
for (final contact in _connector.contacts) toStockContact(contact),
|
||||
];
|
||||
include(StockConfigSection.contacts);
|
||||
}
|
||||
|
||||
return StockConfigExportResult(
|
||||
config: StockConfig(
|
||||
name: name,
|
||||
publicKey: publicKey,
|
||||
privateKey: privateKey,
|
||||
radioSettings: radio,
|
||||
positionSettings: position,
|
||||
otherSettings: other,
|
||||
autoAddSettings: autoAdd,
|
||||
channels: channels,
|
||||
contacts: contacts,
|
||||
),
|
||||
included: included,
|
||||
omitted: omitted,
|
||||
);
|
||||
}
|
||||
|
||||
/// Null until the device has reported its radio parameters. Partial radio
|
||||
/// state is never written: stock's reader takes the five values together.
|
||||
StockRadioSettings? _buildRadioSettings() {
|
||||
// `currentFreqHz` is misnamed: the value is kHz, which is what stock's
|
||||
// `frequency` field also carries, so it passes through unconverted.
|
||||
// `currentBwHz` really is Hz, matching stock's `bandwidth`. The units
|
||||
// differ between the two fields in both our state and the file.
|
||||
final frequencyKhz = _connector.currentFreqHz;
|
||||
final bandwidthHz = _connector.currentBwHz;
|
||||
final sf = _connector.currentSf;
|
||||
final cr = _connector.currentCr;
|
||||
final txPower = _connector.currentTxPower;
|
||||
if (frequencyKhz == null ||
|
||||
bandwidthHz == null ||
|
||||
sf == null ||
|
||||
cr == null ||
|
||||
txPower == null) {
|
||||
return null;
|
||||
}
|
||||
return StockRadioSettings(
|
||||
frequencyKhz: frequencyKhz,
|
||||
bandwidthHz: bandwidthHz,
|
||||
spreadingFactor: sf,
|
||||
codingRate: cr,
|
||||
txPower: txPower,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps one of our channels onto the stock record. The channel's index is not
|
||||
/// written: stock derives it from array position.
|
||||
StockChannel toStockChannel(Channel channel) =>
|
||||
StockChannel(name: channel.name, secret: channel.psk);
|
||||
|
||||
/// Maps one of our contacts onto the stock record.
|
||||
StockContact toStockContact(Contact contact) {
|
||||
return StockContact(
|
||||
type: contact.type,
|
||||
name: contact.name,
|
||||
publicKey: contact.publicKey,
|
||||
flags: contact.flags,
|
||||
latitude: contact.latitude ?? 0,
|
||||
longitude: contact.longitude ?? 0,
|
||||
lastAdvert: _epochSeconds(contact.lastSeen),
|
||||
lastModified: _epochSeconds(contact.lastModified ?? contact.lastSeen),
|
||||
outPath: _toStockOutPath(contact),
|
||||
);
|
||||
}
|
||||
|
||||
/// Our path is a hash count plus a per-hop width (#309); stock writes one
|
||||
/// comma-separated hash per hop, so the width survives as each element's
|
||||
/// length. A flood route (`pathLength` of -1) and an empty path both mean
|
||||
/// "no route", which stock spells as a null field.
|
||||
StockOutPath? _toStockOutPath(Contact contact) {
|
||||
if (contact.pathLength <= 0 || contact.path.isEmpty) return null;
|
||||
final width = contact.pathHashWidth;
|
||||
if (!kStockPathHashWidths.contains(width)) return null;
|
||||
final usable = contact.pathLength * width;
|
||||
if (usable > contact.path.length) return null;
|
||||
return StockOutPath(
|
||||
hashWidth: width,
|
||||
bytes: Uint8List.sublistView(contact.path, 0, usable),
|
||||
);
|
||||
}
|
||||
|
||||
int _epochSeconds(DateTime time) => time.millisecondsSinceEpoch ~/ 1000;
|
||||
@ -0,0 +1,396 @@
|
||||
/// Applies a stock-compatible config file to the connected device (#575,
|
||||
/// epic #568).
|
||||
///
|
||||
/// Merge semantics deliberately match the stock app, which states them on its
|
||||
/// own Import Config screen:
|
||||
///
|
||||
/// * **Contacts**: "New contacts will be added. Existing contacts will be
|
||||
/// updated." An upsert keyed on public key. Nothing is ever deleted.
|
||||
/// * **Channels**: "New channels will be added. Existing channels will not
|
||||
/// change." Purely additive, so a rotated PSK for a channel the user already
|
||||
/// has does not apply.
|
||||
/// * **Identity**: "Importing this private key will overwrite your current
|
||||
/// identity." Destructive, and the caller must have confirmed with the user.
|
||||
///
|
||||
/// We match that behavior but not stock's silence about it: anything skipped
|
||||
/// comes back in [StockConfigImportResult] so the UI can name it. A channel
|
||||
/// that quietly failed to import is exactly the kind of silent no-op SAFELANE
|
||||
/// section 6 forbids.
|
||||
library;
|
||||
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../models/channel.dart';
|
||||
import '../models/stock_config.dart';
|
||||
import 'stock_config_export_service.dart' show StockConfigSection;
|
||||
|
||||
/// Why a section or a single channel was not applied.
|
||||
enum StockConfigImportIssue {
|
||||
/// The file did not contain this section.
|
||||
absentFromFile,
|
||||
|
||||
/// The device is not connected, or did not answer.
|
||||
noReply,
|
||||
|
||||
/// The radio's firmware was built without the feature.
|
||||
unsupported,
|
||||
|
||||
/// The device refused the request.
|
||||
rejected,
|
||||
|
||||
/// The device already has this channel, and stock's rule is that existing
|
||||
/// channels are never overwritten.
|
||||
alreadyPresent,
|
||||
|
||||
/// Every channel slot on the device is occupied.
|
||||
noFreeSlot,
|
||||
|
||||
/// We have no supported way to write this value to the device.
|
||||
notWritable,
|
||||
}
|
||||
|
||||
/// A channel present in the file that did not land on the device.
|
||||
class SkippedChannel {
|
||||
const SkippedChannel(this.name, this.reason);
|
||||
|
||||
final String name;
|
||||
final StockConfigImportIssue reason;
|
||||
}
|
||||
|
||||
class StockConfigImportResult {
|
||||
const StockConfigImportResult({
|
||||
required this.applied,
|
||||
required this.failed,
|
||||
required this.skippedChannels,
|
||||
required this.contactsWritten,
|
||||
required this.channelsAdded,
|
||||
});
|
||||
|
||||
/// Sections whose commands were **sent** to the device without error.
|
||||
///
|
||||
/// This is not device confirmation. Apart from the identity import, which
|
||||
/// waits for a real OK or ERR, the firmware's generic OK for these commands
|
||||
/// is not currently awaited, so a frame lost or refused after it left our
|
||||
/// side would still land here. Wiring per-command confirmation is tracked
|
||||
/// separately; until then this set means "sent", and the UI says so rather
|
||||
/// than claiming more than we know.
|
||||
final Set<StockConfigSection> applied;
|
||||
|
||||
final Map<StockConfigSection, StockConfigImportIssue> failed;
|
||||
|
||||
/// Channels in the file that were not written, each with a reason. Shown to
|
||||
/// the user; never discarded.
|
||||
final List<SkippedChannel> skippedChannels;
|
||||
|
||||
/// Contacts whose write command was sent. See [applied] for why this is a
|
||||
/// send count and not a confirmed count.
|
||||
final int contactsWritten;
|
||||
|
||||
/// Channels whose write command was sent. Same caveat as [contactsWritten].
|
||||
final int channelsAdded;
|
||||
|
||||
bool get isComplete => failed.isEmpty && skippedChannels.isEmpty;
|
||||
}
|
||||
|
||||
class StockConfigImportService {
|
||||
StockConfigImportService(this._connector);
|
||||
|
||||
final MeshCoreConnector _connector;
|
||||
|
||||
/// Applies the selected [sections] of [config] to the device.
|
||||
///
|
||||
/// [StockConfigSection.identity] is destructive and is only applied when the
|
||||
/// caller includes it; confirming that with the user is the UI's job.
|
||||
Future<StockConfigImportResult> apply({
|
||||
required StockConfig config,
|
||||
required Set<StockConfigSection> sections,
|
||||
}) async {
|
||||
final applied = <StockConfigSection>{};
|
||||
final failed = <StockConfigSection, StockConfigImportIssue>{};
|
||||
final skippedChannels = <SkippedChannel>[];
|
||||
var contactsWritten = 0;
|
||||
var channelsAdded = 0;
|
||||
|
||||
if (!_connector.isConnected) {
|
||||
return StockConfigImportResult(
|
||||
applied: const {},
|
||||
failed: {for (final s in sections) s: StockConfigImportIssue.noReply},
|
||||
skippedChannels: const [],
|
||||
contactsWritten: 0,
|
||||
channelsAdded: 0,
|
||||
);
|
||||
}
|
||||
|
||||
if (sections.contains(StockConfigSection.name)) {
|
||||
final name = config.name;
|
||||
if (name == null) {
|
||||
failed[StockConfigSection.name] = StockConfigImportIssue.absentFromFile;
|
||||
} else {
|
||||
await _connector.setNodeName(name);
|
||||
applied.add(StockConfigSection.name);
|
||||
}
|
||||
}
|
||||
|
||||
if (sections.contains(StockConfigSection.identity)) {
|
||||
final identity = config.privateKey;
|
||||
if (identity == null) {
|
||||
failed[StockConfigSection.identity] =
|
||||
StockConfigImportIssue.absentFromFile;
|
||||
} else {
|
||||
// Destructive: replaces the node's identity outright.
|
||||
switch (await _connector.importPrivateKey(identity)) {
|
||||
case IdentityTransfer.ok:
|
||||
applied.add(StockConfigSection.identity);
|
||||
case IdentityTransfer.unsupported:
|
||||
failed[StockConfigSection.identity] =
|
||||
StockConfigImportIssue.unsupported;
|
||||
case IdentityTransfer.rejected:
|
||||
failed[StockConfigSection.identity] =
|
||||
StockConfigImportIssue.rejected;
|
||||
case IdentityTransfer.noReply:
|
||||
failed[StockConfigSection.identity] =
|
||||
StockConfigImportIssue.noReply;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sections.contains(StockConfigSection.radioSettings)) {
|
||||
final radio = config.radioSettings;
|
||||
if (radio == null) {
|
||||
failed[StockConfigSection.radioSettings] =
|
||||
StockConfigImportIssue.absentFromFile;
|
||||
} else {
|
||||
// The device takes frequency in the same kHz unit the file uses, so
|
||||
// this is a straight pass-through. See the note in the export service.
|
||||
await _connector.sendFrame(
|
||||
buildSetRadioParamsFrame(
|
||||
radio.frequencyKhz,
|
||||
radio.bandwidthHz,
|
||||
radio.spreadingFactor,
|
||||
radio.codingRate,
|
||||
),
|
||||
);
|
||||
applied.add(StockConfigSection.radioSettings);
|
||||
}
|
||||
}
|
||||
|
||||
if (sections.contains(StockConfigSection.positionSettings)) {
|
||||
final position = config.positionSettings;
|
||||
if (position == null) {
|
||||
failed[StockConfigSection.positionSettings] =
|
||||
StockConfigImportIssue.absentFromFile;
|
||||
} else {
|
||||
await _connector.setNodeLocation(
|
||||
lat: position.latitude,
|
||||
lon: position.longitude,
|
||||
);
|
||||
applied.add(StockConfigSection.positionSettings);
|
||||
}
|
||||
}
|
||||
|
||||
if (sections.contains(StockConfigSection.otherSettings)) {
|
||||
final other = config.otherSettings;
|
||||
if (other == null) {
|
||||
failed[StockConfigSection.otherSettings] =
|
||||
StockConfigImportIssue.absentFromFile;
|
||||
} else {
|
||||
// buildSetOtherParamsFrame deliberately pins the auto-add-contacts
|
||||
// byte to disabled, so `manual_add_contacts` from the file cannot be
|
||||
// written without changing app-wide behavior. Only the advert location
|
||||
// policy is applied, and the section is reported as partially written
|
||||
// rather than claimed as done.
|
||||
await _connector.sendFrame(
|
||||
buildSetOtherParamsFrame(
|
||||
(_connector.telemetryModeEnv << 4) |
|
||||
(_connector.telemetryModeLoc << 2) |
|
||||
_connector.telemetryModeBase,
|
||||
other.advertLocationPolicy,
|
||||
_connector.multiAcks,
|
||||
),
|
||||
);
|
||||
failed[StockConfigSection.otherSettings] =
|
||||
StockConfigImportIssue.notWritable;
|
||||
}
|
||||
}
|
||||
|
||||
if (sections.contains(StockConfigSection.autoAddSettings)) {
|
||||
final autoAdd = config.autoAddSettings;
|
||||
if (autoAdd == null) {
|
||||
failed[StockConfigSection.autoAddSettings] =
|
||||
StockConfigImportIssue.absentFromFile;
|
||||
} else {
|
||||
await _connector.sendFrame(
|
||||
buildSetAutoAddConfigFrame(
|
||||
autoAddChat: autoAdd.autoAddChat,
|
||||
autoAddRepeater: autoAdd.autoAddRepeater,
|
||||
autoAddRoomServer: autoAdd.autoAddRoomServer,
|
||||
autoAddSensor: autoAdd.autoAddSensor,
|
||||
overwriteOldest: autoAdd.overwriteOldest,
|
||||
maxHops: autoAdd.autoAddMaxHops,
|
||||
),
|
||||
);
|
||||
applied.add(StockConfigSection.autoAddSettings);
|
||||
}
|
||||
}
|
||||
|
||||
if (sections.contains(StockConfigSection.channels)) {
|
||||
final channels = config.channels;
|
||||
if (channels == null) {
|
||||
failed[StockConfigSection.channels] =
|
||||
StockConfigImportIssue.absentFromFile;
|
||||
} else {
|
||||
channelsAdded = await _applyChannels(channels, skippedChannels);
|
||||
applied.add(StockConfigSection.channels);
|
||||
}
|
||||
}
|
||||
|
||||
if (sections.contains(StockConfigSection.contacts)) {
|
||||
final contacts = config.contacts;
|
||||
if (contacts == null) {
|
||||
failed[StockConfigSection.contacts] =
|
||||
StockConfigImportIssue.absentFromFile;
|
||||
} else {
|
||||
contactsWritten = await _applyContacts(contacts);
|
||||
applied.add(StockConfigSection.contacts);
|
||||
}
|
||||
}
|
||||
|
||||
return StockConfigImportResult(
|
||||
applied: applied,
|
||||
failed: failed,
|
||||
skippedChannels: skippedChannels,
|
||||
contactsWritten: contactsWritten,
|
||||
channelsAdded: channelsAdded,
|
||||
);
|
||||
}
|
||||
|
||||
Future<int> _applyChannels(
|
||||
List<StockChannel> incoming,
|
||||
List<SkippedChannel> skipped,
|
||||
) async {
|
||||
final plan = planChannelImport(
|
||||
existing: _connector.channels,
|
||||
incoming: incoming,
|
||||
maxChannels: _connector.maxChannels,
|
||||
);
|
||||
for (final assignment in plan.assignments) {
|
||||
await _connector.setChannel(
|
||||
assignment.slot,
|
||||
assignment.channel.name,
|
||||
assignment.channel.secret,
|
||||
);
|
||||
}
|
||||
skipped.addAll(plan.skipped);
|
||||
return plan.assignments.length;
|
||||
}
|
||||
|
||||
/// Upserts every contact. The firmware's add-or-update command keys on the
|
||||
/// public key, so an existing contact is updated in place and a new one is
|
||||
/// created. Nothing is removed, in either direction.
|
||||
Future<int> _applyContacts(List<StockContact> contacts) async {
|
||||
var written = 0;
|
||||
for (final contact in contacts) {
|
||||
final path = contact.outPath;
|
||||
// Position is always passed through, including (0, 0). Suppressing zero
|
||||
// would be pointless here: the frame builder emits the position block
|
||||
// whenever lastModified is present, which it always is below, so a
|
||||
// suppressed position writes 0/0 anyway. Passing it straight through
|
||||
// means the file's value is what lands, with no special case to
|
||||
// misread.
|
||||
await _connector.sendFrame(
|
||||
buildUpdateContactPathFrame(
|
||||
contact.publicKey,
|
||||
path?.bytes ?? _emptyPath,
|
||||
// No path in the file means flood, which the frame encodes as -1.
|
||||
path == null || path.hopCount == 0 ? -1 : path.hopCount,
|
||||
hashWidth: path == null || path.hashWidth == 0 ? 1 : path.hashWidth,
|
||||
type: contact.type,
|
||||
flags: contact.flags,
|
||||
name: contact.name,
|
||||
lat: contact.latitude,
|
||||
lon: contact.longitude,
|
||||
lastModified: DateTime.fromMillisecondsSinceEpoch(
|
||||
contact.lastModified * 1000,
|
||||
),
|
||||
),
|
||||
);
|
||||
written++;
|
||||
}
|
||||
return written;
|
||||
}
|
||||
}
|
||||
|
||||
/// A zero-length path, which the frame builder pads out to the fixed-size
|
||||
/// path field.
|
||||
final Uint8List _emptyPath = Uint8List(0);
|
||||
|
||||
/// One incoming channel and the device slot it will occupy.
|
||||
class ChannelAssignment {
|
||||
const ChannelAssignment(this.slot, this.channel);
|
||||
|
||||
final int slot;
|
||||
final StockChannel channel;
|
||||
}
|
||||
|
||||
/// The decision of which incoming channels get written, and where.
|
||||
class ChannelImportPlan {
|
||||
const ChannelImportPlan(this.assignments, this.skipped);
|
||||
|
||||
final List<ChannelAssignment> assignments;
|
||||
final List<SkippedChannel> skipped;
|
||||
}
|
||||
|
||||
/// Decides which of [incoming] to write, honoring stock's additive rule.
|
||||
///
|
||||
/// A channel counts as already present when either its PSK or its name matches
|
||||
/// one already on the device. Stock says only that existing channels do not
|
||||
/// change, without defining what makes a channel "existing"; matching on both
|
||||
/// is the non-destructive reading, and pinning down what stock actually does is
|
||||
/// one of the T1 gate's questions.
|
||||
///
|
||||
/// New channels go into the lowest free slot. Stock's file has no index field,
|
||||
/// so incoming order is the only ordering information there is, and slots
|
||||
/// already occupied are left alone.
|
||||
ChannelImportPlan planChannelImport({
|
||||
required List<Channel> existing,
|
||||
required List<StockChannel> incoming,
|
||||
required int maxChannels,
|
||||
}) {
|
||||
final live = existing.where((c) => !c.isEmpty).toList();
|
||||
final takenSlots = live.map((c) => c.index).toSet();
|
||||
final psks = live.map((c) => c.pskHex).toSet();
|
||||
final names = live.map((c) => c.name).toSet();
|
||||
|
||||
final assignments = <ChannelAssignment>[];
|
||||
final skipped = <SkippedChannel>[];
|
||||
|
||||
for (final channel in incoming) {
|
||||
final pskHex = pubKeyToHex(channel.secret);
|
||||
if (psks.contains(pskHex) || names.contains(channel.name)) {
|
||||
skipped.add(
|
||||
SkippedChannel(channel.name, StockConfigImportIssue.alreadyPresent),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
int? slot;
|
||||
for (var i = 0; i < maxChannels; i++) {
|
||||
if (!takenSlots.contains(i)) {
|
||||
slot = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (slot == null) {
|
||||
skipped.add(
|
||||
SkippedChannel(channel.name, StockConfigImportIssue.noFreeSlot),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
assignments.add(ChannelAssignment(slot, channel));
|
||||
takenSlots.add(slot);
|
||||
psks.add(pskHex);
|
||||
names.add(channel.name);
|
||||
}
|
||||
return ChannelImportPlan(assignments, skipped);
|
||||
}
|
||||
@ -0,0 +1,70 @@
|
||||
/// Naming and writing of stock-compatible config files (#574, epic #568).
|
||||
library;
|
||||
|
||||
import 'dart:io' show File;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import 'log_export.dart';
|
||||
import 'log_web_download.dart';
|
||||
|
||||
/// Characters Windows forbids in a file name, plus the path separators.
|
||||
final _illegalFileNameChars = RegExp(r'[<>:"/\\|?*\x00-\x1F]');
|
||||
|
||||
/// Builds the file name stock uses: `<device name>_meshcore_config_<stamp>`.
|
||||
///
|
||||
/// Real device names contain emoji and, in at least one observed case, a
|
||||
/// trailing space, so the name is sanitized for the filesystem here. The name
|
||||
/// written *inside* the file is never touched: it must round-trip exactly.
|
||||
String stockConfigFileName(String? deviceName, DateTime at) {
|
||||
final safeName = _sanitizeForFileName(deviceName ?? '');
|
||||
final stamp = [
|
||||
at.year.toString().padLeft(4, '0'),
|
||||
at.month.toString().padLeft(2, '0'),
|
||||
at.day.toString().padLeft(2, '0'),
|
||||
].join('-');
|
||||
final time = [
|
||||
at.hour.toString().padLeft(2, '0'),
|
||||
at.minute.toString().padLeft(2, '0'),
|
||||
at.second.toString().padLeft(2, '0'),
|
||||
].join();
|
||||
final prefix = safeName.isEmpty ? '' : '${safeName}_';
|
||||
return '${prefix}meshcore_config_$stamp-$time.json';
|
||||
}
|
||||
|
||||
String _sanitizeForFileName(String name) {
|
||||
final cleaned = name.replaceAll(_illegalFileNameChars, '');
|
||||
// Windows also rejects names ending in a space or a dot.
|
||||
return cleaned.replaceAll(RegExp(r'[ .]+$'), '').trim();
|
||||
}
|
||||
|
||||
/// Writes [json] out as [fileName], using each platform's normal mechanism:
|
||||
/// the share sheet on mobile, a Save As dialog on desktop, a browser download
|
||||
/// on web. Reuses [LogExport], which already owns that per-platform logic, so
|
||||
/// there is only one place where export behavior can drift.
|
||||
Future<void> saveStockConfigFile(
|
||||
BuildContext context, {
|
||||
required String json,
|
||||
required String fileName,
|
||||
String? subject,
|
||||
}) async {
|
||||
if (kIsWeb) {
|
||||
downloadTextFile(fileName, json);
|
||||
return;
|
||||
}
|
||||
// A temp file is the handoff format LogExport works in. It holds the node's
|
||||
// private key when the identity section was included, so it is written under
|
||||
// the app's own temp directory and never anywhere shared.
|
||||
final dir = await getTemporaryDirectory();
|
||||
final file = File('${dir.path}/$fileName');
|
||||
await file.writeAsString(json, flush: true);
|
||||
if (!context.mounted) return;
|
||||
await LogExport.shareFile(
|
||||
context,
|
||||
file,
|
||||
subject: subject,
|
||||
fileName: fileName,
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,261 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../helpers/snack_bar_builder.dart';
|
||||
import '../models/contact.dart';
|
||||
import '../screens/contact_qr_scanner_screen.dart';
|
||||
|
||||
/// Adds a contact from an identity alone: a public key, a name and a type.
|
||||
///
|
||||
/// This is the manual half of the identity exchange (#628). It exists because
|
||||
/// a public key is never present in channel traffic, so for anyone who has not
|
||||
/// recently adverted there is otherwise no way to reach them at all (#620).
|
||||
///
|
||||
/// The field also accepts a whole `meshcore://contact/add` link, since that is
|
||||
/// what someone is most likely to paste, and a QR is only that same link
|
||||
/// rendered visually.
|
||||
/// [initialKeyText] seeds the key field, so a scan taken from somewhere else
|
||||
/// can open this already filled in rather than making the user paste. (#629)
|
||||
Future<void> showAddContactByKeyDialog(
|
||||
BuildContext context, {
|
||||
String? initialKeyText,
|
||||
}) {
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
builder: (_) => _AddContactByKeyDialog(initialKeyText: initialKeyText),
|
||||
);
|
||||
}
|
||||
|
||||
class _AddContactByKeyDialog extends StatefulWidget {
|
||||
const _AddContactByKeyDialog({this.initialKeyText});
|
||||
|
||||
final String? initialKeyText;
|
||||
|
||||
@override
|
||||
State<_AddContactByKeyDialog> createState() => _AddContactByKeyDialogState();
|
||||
}
|
||||
|
||||
class _AddContactByKeyDialogState extends State<_AddContactByKeyDialog> {
|
||||
final _keyController = TextEditingController();
|
||||
final _nameController = TextEditingController();
|
||||
int _type = advTypeChat;
|
||||
String? _keyError;
|
||||
bool _submitting = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final seed = widget.initialKeyText;
|
||||
if (seed != null && seed.isNotEmpty) {
|
||||
_keyController.text = seed;
|
||||
// Route the seed through the same handler as a paste, so a full link
|
||||
// populates name and type instead of sitting there as raw text.
|
||||
_onKeyChanged(seed);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_keyController.dispose();
|
||||
_nameController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Strips whitespace so a key copied across a line break still works.
|
||||
String get _cleanedKey =>
|
||||
_keyController.text.replaceAll(RegExp(r'\s+'), '').toLowerCase();
|
||||
|
||||
bool get _keyLooksValid => Contact.isValidShareUri(
|
||||
Contact.buildShareUri(publicKeyHex: _cleanedKey, name: 'x', type: _type),
|
||||
);
|
||||
|
||||
/// If a full contact link OR a channel contact card was pasted, absorb every
|
||||
/// field from it rather than making the user retype a name they already have.
|
||||
///
|
||||
/// Both formats are accepted because both are real and a user will meet both:
|
||||
/// the `meshcore://` link comes from a QR or a DM, and the compact
|
||||
/// `<key:type:name>` card is what appears in channel traffic, including the
|
||||
/// cards this app itself posts. Accepting only the link would mean rejecting
|
||||
/// our own output.
|
||||
void _onKeyChanged(String raw) {
|
||||
final pasted = Contact.fromShareUri(raw) ?? Contact.fromChannelShare(raw);
|
||||
if (pasted != null) {
|
||||
setState(() {
|
||||
_keyController.value = TextEditingValue(
|
||||
text: pasted.publicKeyHex,
|
||||
selection: TextSelection.collapsed(
|
||||
offset: pasted.publicKeyHex.length,
|
||||
),
|
||||
);
|
||||
if (pasted.name != 'Unknown') _nameController.text = pasted.name;
|
||||
_type = pasted.type;
|
||||
_keyError = null;
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (_keyError != null) setState(() => _keyError = null);
|
||||
}
|
||||
|
||||
Future<void> _scan() async {
|
||||
final scanned = await Navigator.of(context).push<String>(
|
||||
MaterialPageRoute(builder: (_) => const ContactQrScannerScreen()),
|
||||
);
|
||||
if (!mounted || scanned == null) return;
|
||||
// Route the scan through the same handler as a paste. A QR is only the
|
||||
// link rendered visually, so it must not get its own code path.
|
||||
_keyController.text = scanned;
|
||||
_onKeyChanged(scanned);
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
final l10n = context.l10n;
|
||||
if (!_keyLooksValid) {
|
||||
setState(() => _keyError = l10n.contacts_publicKeyInvalid);
|
||||
return;
|
||||
}
|
||||
|
||||
final name = _nameController.text.trim();
|
||||
// Round-trip through the share URI so a manually typed contact and a
|
||||
// scanned QR produce byte-identical state. One code path, no drift.
|
||||
final stub = Contact.fromShareUri(
|
||||
Contact.buildShareUri(publicKeyHex: _cleanedKey, name: name, type: _type),
|
||||
);
|
||||
if (stub == null) {
|
||||
setState(() => _keyError = l10n.contacts_publicKeyInvalid);
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() => _submitting = true);
|
||||
final connector = Provider.of<MeshCoreConnector>(context, listen: false);
|
||||
final added = await connector.addContactByKey(stub);
|
||||
if (!mounted) return;
|
||||
|
||||
Navigator.of(context).pop();
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(
|
||||
added
|
||||
? l10n.contacts_addByKeyAdded(stub.name)
|
||||
: l10n.contacts_addByKeyFailed,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return AlertDialog(
|
||||
title: Text(l10n.contacts_addByKey),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
l10n.contacts_addByKeyDescription,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _keyController,
|
||||
autofocus: true,
|
||||
maxLines: 2,
|
||||
minLines: 1,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.contacts_publicKeyLabel,
|
||||
helperText: l10n.contacts_publicKeyHelper,
|
||||
helperMaxLines: 2,
|
||||
errorText: _keyError,
|
||||
errorMaxLines: 2,
|
||||
border: const OutlineInputBorder(),
|
||||
suffixIcon: contactQrScanAvailable
|
||||
? IconButton(
|
||||
icon: const Icon(Icons.qr_code_scanner),
|
||||
tooltip: l10n.contacts_scanContactQr,
|
||||
onPressed: _submitting ? null : _scan,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
onChanged: _onKeyChanged,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _nameController,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.contacts_nameLabel,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
DropdownButtonFormField<int>(
|
||||
initialValue: _type,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.contacts_typeLabel,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
items: [
|
||||
DropdownMenuItem(
|
||||
value: advTypeChat,
|
||||
child: Text(l10n.contact_typeChat),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: advTypeRepeater,
|
||||
child: Text(l10n.contact_typeRepeater),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: advTypeRoom,
|
||||
child: Text(l10n.contact_typeRoom),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: advTypeSensor,
|
||||
child: Text(l10n.contact_typeSensor),
|
||||
),
|
||||
],
|
||||
onChanged: (v) => setState(() => _type = v ?? advTypeChat),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
// Honest about what a key-only add actually gives you. Deliberately
|
||||
// informational, not a warning: nothing is wrong with this contact
|
||||
// (#630).
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.info_outline,
|
||||
size: 16,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
l10n.contacts_addByKeyUnverifiedNote,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: _submitting ? null : () => Navigator.of(context).pop(),
|
||||
child: Text(l10n.common_cancel),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _submitting ? null : _submit,
|
||||
child: Text(l10n.common_add),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,116 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
|
||||
/// Explains a composer whose byte budget is too small to carry a message.
|
||||
///
|
||||
/// #592 was reported twice as "the keyboard doesn't respond". It was not an
|
||||
/// input bug: the byte budget had collapsed to 0, so the length limiter
|
||||
/// rejected every keystroke while the field still focused and blinked. Nothing
|
||||
/// on screen said why.
|
||||
///
|
||||
/// This is a persistent inline notice rather than a toast on purpose. The
|
||||
/// condition is a *state* that lasts as long as the link does, not an event, so
|
||||
/// a transient snackbar would scroll away and leave the same dead field behind.
|
||||
/// SAFELANE 6 requires a user-facing error to persist; sitting directly above
|
||||
/// the composer it also lands where the confusion is (#684).
|
||||
///
|
||||
/// Renders nothing when the budget is healthy, so both composers can include it
|
||||
/// unconditionally.
|
||||
class ComposerBudgetNotice extends StatelessWidget {
|
||||
/// The composer's computed limit, from `maxChannelMessageBytes` or
|
||||
/// `maxContactMessageBytes`.
|
||||
final int maxBytes;
|
||||
|
||||
/// Transport in use, so the cause can be named plainly instead of described
|
||||
/// as generic failure.
|
||||
final MeshCoreTransportType transport;
|
||||
|
||||
/// Whether a radio is actually connected.
|
||||
///
|
||||
/// Required, and not cosmetic. While disconnected, `_activeTransport` still
|
||||
/// reads `bluetooth` (its default) and there is no device, so the frame
|
||||
/// budget falls to the same 20-byte floor an unreported MTU produces. Without
|
||||
/// this gate the notice would appear on every disconnect and blame the link
|
||||
/// for a small packet size when there is no link at all.
|
||||
final bool isConnected;
|
||||
|
||||
const ComposerBudgetNotice({
|
||||
super.key,
|
||||
required this.maxBytes,
|
||||
required this.transport,
|
||||
required this.isConnected,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!isConnected) return const SizedBox.shrink();
|
||||
if (isComposerBudgetUsable(maxBytes)) return const SizedBox.shrink();
|
||||
|
||||
final l10n = context.l10n;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
|
||||
// A budget of 0 blocks every keystroke; 1-15 accepts input but cannot carry
|
||||
// a sentence. Those are different severities and must not look the same.
|
||||
// Zero is a failure: nothing can be sent. Non-zero is a fact about a
|
||||
// working link, so it is stated rather than alarmed about - a permanent red
|
||||
// banner over a link that genuinely only fits a few characters is noise,
|
||||
// and noise is what teaches people to ignore the banner that matters.
|
||||
final blocked = maxBytes <= 0;
|
||||
|
||||
final title = blocked
|
||||
? l10n.composerBudgetBlockedTitle
|
||||
: l10n.composerBudgetLimitedTitle(maxBytes);
|
||||
|
||||
final cause = transport == MeshCoreTransportType.bluetooth
|
||||
? l10n.composerBudgetBluetoothCause
|
||||
: l10n.composerBudgetGenericCause;
|
||||
|
||||
final background = blocked
|
||||
? scheme.errorContainer
|
||||
: scheme.secondaryContainer;
|
||||
final foreground = blocked
|
||||
? scheme.onErrorContainer
|
||||
: scheme.onSecondaryContainer;
|
||||
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
color: background,
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// No semanticLabel on purpose: Icon wraps its glyph in
|
||||
// ExcludeSemantics and only announces a label when given one, so an
|
||||
// unlabelled icon is correctly decorative here. The two Text children
|
||||
// below already carry the whole message to a screen reader, and
|
||||
// labelling the icon too would just repeat it.
|
||||
Icon(
|
||||
blocked ? Icons.error_outline : Icons.info_outline,
|
||||
size: 18,
|
||||
color: foreground,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: foreground,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(cause, style: TextStyle(fontSize: 12, color: foreground)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,120 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../models/contact.dart';
|
||||
import 'add_contact_by_key_dialog.dart';
|
||||
|
||||
/// Renders a received contact share card as a tappable Add Contact affordance
|
||||
/// instead of the raw `<key:type:name>` text. (#610)
|
||||
///
|
||||
/// This is the receive half of the exchange. The send half (#611) already
|
||||
/// emits this format, and the stock app already renders it as a native Add
|
||||
/// Contact button, so until now sharing worked outbound only: a stock user
|
||||
/// could add an Offband user from a card, but not the reverse.
|
||||
///
|
||||
/// Tapping opens the add dialog seeded with the card, so the user sees the key,
|
||||
/// name and type before anything is written to the radio. It does NOT add
|
||||
/// silently: a contact is an identity, and adding one should be a deliberate
|
||||
/// act with the details visible.
|
||||
class ContactCardChip extends StatelessWidget {
|
||||
const ContactCardChip({super.key, required this.card, required this.style});
|
||||
|
||||
/// The raw matched card text, `<key:type:name>`.
|
||||
final String card;
|
||||
|
||||
final TextStyle style;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final parsed = Contact.fromChannelShare(card);
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final l10n = context.l10n;
|
||||
|
||||
// The regex matched the shape but the parser rejected the contents, e.g. a
|
||||
// type outside the documented range. Show the original text rather than a
|
||||
// chip that would lie about being addable.
|
||||
if (parsed == null) return Text(card, style: style);
|
||||
|
||||
// Mirrors what stock does: it warned the owner when the contact was
|
||||
// already held rather than silently re-adding.
|
||||
//
|
||||
// O(1) against the connector's maintained key set. Scanning `contacts`
|
||||
// here would run per rendered chip on every notification, which is
|
||||
// hundreds of comparisons in a message list on a device with a large
|
||||
// contact book. (Gemini review, #610)
|
||||
final known = context.select<MeshCoreConnector, bool>(
|
||||
(c) => c.isKnownContact(parsed.publicKeyHex),
|
||||
);
|
||||
|
||||
final label = known
|
||||
? l10n.contacts_cardAlreadyAdded(parsed.name)
|
||||
: l10n.contacts_cardAddContact(parsed.name);
|
||||
|
||||
// A WidgetSpan gives its child unbounded width, so Flexible needs a real
|
||||
// ceiling to ellipsize against. Without this the chip grows to whatever
|
||||
// name the sender chose, which overflowed the message layout.
|
||||
//
|
||||
// Scaled off the viewport rather than a fixed pixel count, so a large
|
||||
// accessibility font on a wide screen is not ellipsized while space
|
||||
// remains, and a narrow phone still gets a sane bound. (Gemini recheck)
|
||||
final maxChipWidth = MediaQuery.sizeOf(context).width * 0.7;
|
||||
final chip = ConstrainedBox(
|
||||
constraints: BoxConstraints(maxWidth: maxChipWidth),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: known
|
||||
? scheme.onSurface.withValues(alpha: 0.08)
|
||||
: scheme.primaryContainer,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
known ? Icons.how_to_reg : Icons.person_add_alt_1,
|
||||
size: 15,
|
||||
color: known
|
||||
? scheme.onSurfaceVariant
|
||||
: scheme.onPrimaryContainer,
|
||||
),
|
||||
const SizedBox(width: 5),
|
||||
// Bounded and ellipsized. The name comes off a public radio channel
|
||||
// and is attacker-controlled, so an unbounded label lets anyone
|
||||
// overflow the message layout by posting a card with a long name.
|
||||
// Reproduced before this: a 405 pixel RenderFlex overflow.
|
||||
// (Gemini review prompted the adversarial case, #610)
|
||||
Flexible(
|
||||
child: Text(
|
||||
label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: style.copyWith(
|
||||
fontWeight: FontWeight.w500,
|
||||
color: known
|
||||
? scheme.onSurfaceVariant
|
||||
: scheme.onPrimaryContainer,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (known) {
|
||||
return Tooltip(
|
||||
message: l10n.contacts_cardAlreadyAddedTooltip,
|
||||
child: chip,
|
||||
);
|
||||
}
|
||||
|
||||
return InkWell(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
onTap: () => showAddContactByKeyDialog(context, initialKeyText: card),
|
||||
child: chip,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,150 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
|
||||
/// Shown above the whole app when a full contact sync delivered fewer contacts
|
||||
/// than the radio reported (#668), after the forced resync (#703) has tried
|
||||
/// and is still short. The banner stays until dismissed, and a modal asks
|
||||
/// whether to keep the saved contacts (the default) or accept the radio's
|
||||
/// shorter list.
|
||||
///
|
||||
/// SAFELANE §6: the short sync that silently replaced 350 saved contacts with
|
||||
/// 106 (#660) must now be loud. Sits in `MaterialApp.builder`, above the
|
||||
/// Navigator, so the modal is drawn here rather than pushed as a route.
|
||||
class ContactSyncShortfallBanner extends StatelessWidget {
|
||||
final ContactSyncShortfall? shortfall;
|
||||
final bool decisionPending;
|
||||
final int undeliveredCount;
|
||||
final VoidCallback onDismiss;
|
||||
final VoidCallback onKeep;
|
||||
final VoidCallback onUseRadio;
|
||||
final Widget child;
|
||||
|
||||
const ContactSyncShortfallBanner({
|
||||
super.key,
|
||||
required this.shortfall,
|
||||
required this.decisionPending,
|
||||
required this.undeliveredCount,
|
||||
required this.onDismiss,
|
||||
required this.onKeep,
|
||||
required this.onUseRadio,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final current = shortfall;
|
||||
if (current == null && !decisionPending) return child;
|
||||
|
||||
final content = current == null
|
||||
? child
|
||||
: Column(
|
||||
children: [
|
||||
_banner(context, current),
|
||||
Expanded(child: child),
|
||||
],
|
||||
);
|
||||
if (!decisionPending) return content;
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
content,
|
||||
const ModalBarrier(dismissible: false, color: Colors.black54),
|
||||
Center(
|
||||
child: _decision(
|
||||
context,
|
||||
current?.received ?? 0,
|
||||
current?.confirmedGone ?? 0,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
static String _withGone(String text, int gone, BuildContext context) =>
|
||||
gone > 0 ? '$text ${context.l10n.contactSyncConfirmedGone(gone)}' : text;
|
||||
|
||||
Widget _banner(BuildContext context, ContactSyncShortfall current) {
|
||||
final l10n = context.l10n;
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final declared = current.declared;
|
||||
final body = _withGone(
|
||||
declared == null
|
||||
? l10n.contactSyncShortfallBodyNoTotal(current.received)
|
||||
: l10n.contactSyncShortfallBody(declared, current.received),
|
||||
current.confirmedGone,
|
||||
context,
|
||||
);
|
||||
return Material(
|
||||
color: scheme.errorContainer,
|
||||
child: SafeArea(
|
||||
bottom: false,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 10, 4, 10),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(Icons.sync_problem, color: scheme.onErrorContainer),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
l10n.contactSyncShortfallTitle,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: scheme.onErrorContainer,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
body,
|
||||
style: TextStyle(color: scheme.onErrorContainer),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// No tooltip: this sits above the Navigator, where there is no
|
||||
// Overlay, and a Tooltip without one blanks the window (#713).
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
Icons.close,
|
||||
color: scheme.onErrorContainer,
|
||||
semanticLabel: l10n.common_close,
|
||||
),
|
||||
onPressed: onDismiss,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _decision(BuildContext context, int received, int gone) {
|
||||
final l10n = context.l10n;
|
||||
return AlertDialog(
|
||||
title: Text(l10n.contactSyncDecisionTitle),
|
||||
content: Text(
|
||||
_withGone(
|
||||
l10n.contactSyncDecisionBody(received, undeliveredCount),
|
||||
gone,
|
||||
context,
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: onUseRadio,
|
||||
child: Text(l10n.contactSyncUseRadio),
|
||||
),
|
||||
FilledButton(
|
||||
autofocus: true,
|
||||
onPressed: onKeep,
|
||||
child: Text(l10n.contactSyncKeep),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,109 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../models/contact.dart';
|
||||
import '../models/message.dart';
|
||||
|
||||
/// How far a contact identity has actually been confirmed. (#630)
|
||||
enum ContactVerification {
|
||||
/// Added from a bare key. Nothing has confirmed it on air.
|
||||
keyOnly,
|
||||
|
||||
/// A message with this contact went through. That is cryptographic proof
|
||||
/// the holder of the matching private key is live and reachable, because
|
||||
/// direct messages are encrypted with an ECDH secret derived from this
|
||||
/// contact key, and the ACK is computed over the decrypted plaintext
|
||||
/// (firmware `BaseChatMesh.cpp:442,451`). It does NOT prove the person is
|
||||
/// who the name claims: names are display, keys are identity.
|
||||
keyConfirmed,
|
||||
|
||||
/// A signed advert has been received. Strongest state: the node itself
|
||||
/// asserted its name, type and position, and the raw advert is stored, so
|
||||
/// the contact can also be re-shared.
|
||||
advertVerified,
|
||||
}
|
||||
|
||||
/// Resolves the verification state for [contact].
|
||||
///
|
||||
/// This runs from a widget `build` inside a contact `ListView`, so it does as
|
||||
/// little as possible:
|
||||
///
|
||||
/// 1. An advert-verified contact returns immediately on a single integer
|
||||
/// comparison. That is most contacts, and no message list is touched.
|
||||
/// 2. Only a key-only contact scans, and it scans **newest first**, because a
|
||||
/// delivered message is overwhelmingly likely to be recent.
|
||||
///
|
||||
/// A `lastMessageAt == epoch` shortcut was considered and **rejected**:
|
||||
/// `_setContactLastMessageAt` maintains that field only for `advTypeChat`, so
|
||||
/// a key-added repeater that had been messaged would have reported the wrong
|
||||
/// badge. A cheap wrong answer is worse than a slightly slower right one.
|
||||
///
|
||||
/// Remaining worst case is a key-only contact carrying many messages of which
|
||||
/// none ever delivered. If that shows up in practice the fix is a cached flag
|
||||
/// set once on first delivery, not a bounded scan, which could misreport.
|
||||
ContactVerification resolveContactVerification(
|
||||
Contact contact,
|
||||
MeshCoreConnector connector,
|
||||
) {
|
||||
if (contact.isAdvertVerified) return ContactVerification.advertVerified;
|
||||
final messages = connector.getMessages(contact);
|
||||
for (var i = messages.length - 1; i >= 0; i--) {
|
||||
if (messages[i].status == MessageStatus.delivered) {
|
||||
return ContactVerification.keyConfirmed;
|
||||
}
|
||||
}
|
||||
return ContactVerification.keyOnly;
|
||||
}
|
||||
|
||||
/// A small, deliberately calm indicator of how far a contact is confirmed.
|
||||
///
|
||||
/// Owner steer (#630): a green check for fully verified and a different icon
|
||||
/// otherwise. Explicitly NOT amber and NOT a hazard glyph, because nothing is
|
||||
/// wrong with a key-added contact. The scale reads as "how much we know",
|
||||
/// never as "how risky".
|
||||
class ContactVerificationBadge extends StatelessWidget {
|
||||
const ContactVerificationBadge({
|
||||
super.key,
|
||||
required this.contact,
|
||||
this.size = 15,
|
||||
});
|
||||
|
||||
final Contact contact;
|
||||
final double size;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final state = resolveContactVerification(
|
||||
contact,
|
||||
context.read<MeshCoreConnector>(),
|
||||
);
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final l10n = context.l10n;
|
||||
|
||||
final (IconData icon, Color color, String tooltip) = switch (state) {
|
||||
ContactVerification.advertVerified => (
|
||||
Icons.verified,
|
||||
// The one deliberately positive colour in the set.
|
||||
Colors.green,
|
||||
l10n.contacts_verifiedByAdvert,
|
||||
),
|
||||
ContactVerification.keyConfirmed => (
|
||||
Icons.check_circle_outline,
|
||||
scheme.onSurfaceVariant,
|
||||
l10n.contacts_verifiedByMessage,
|
||||
),
|
||||
ContactVerification.keyOnly => (
|
||||
Icons.key_outlined,
|
||||
scheme.onSurfaceVariant,
|
||||
l10n.contacts_verifiedKeyOnly,
|
||||
),
|
||||
};
|
||||
|
||||
return Tooltip(
|
||||
message: tooltip,
|
||||
child: Icon(icon, size: size, color: color),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,87 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../connector/meshcore_connector.dart';
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../helpers/snack_bar_builder.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../models/contact.dart';
|
||||
import 'qr_code_display.dart';
|
||||
|
||||
/// Shows this device's own identity as a scannable QR plus a copyable link.
|
||||
/// (#629)
|
||||
///
|
||||
/// This is the fast, definitive way to hand someone your identity: it carries
|
||||
/// the public key itself, so it cannot fail on a name mismatch and it does not
|
||||
/// ask them to wait for an advert. It also costs the mesh no airtime, which
|
||||
/// asking for a couple of flood adverts does.
|
||||
///
|
||||
/// Rendering works on every platform, which matters on desktop: put this on
|
||||
/// screen and the other person scans it with their phone.
|
||||
Future<void> showMyContactQrDialog(BuildContext context) {
|
||||
final connector = Provider.of<MeshCoreConnector>(context, listen: false);
|
||||
final keyHex = connector.selfPublicKeyHex;
|
||||
|
||||
// Without a connection we do not know our own key, so there is nothing
|
||||
// truthful to render.
|
||||
if (keyHex.length != pubKeySize * 2) {
|
||||
showDismissibleSnackBar(
|
||||
context,
|
||||
content: Text(context.l10n.contacts_qrNeedsConnection),
|
||||
);
|
||||
return Future<void>.value();
|
||||
}
|
||||
|
||||
final uri = Contact.buildShareUri(
|
||||
publicKeyHex: keyHex,
|
||||
name: connector.selfName ?? '',
|
||||
// This device is a companion.
|
||||
type: advTypeChat,
|
||||
);
|
||||
|
||||
return showDialog<void>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(dialogContext.l10n.contacts_myContactQr),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
QrCodeDisplay(
|
||||
data: uri,
|
||||
instructions: dialogContext.l10n.contacts_myContactQrInstructions,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
SelectableText(
|
||||
uri,
|
||||
style: Theme.of(dialogContext).textTheme.bodySmall?.copyWith(
|
||||
fontFamily: 'monospace',
|
||||
color: Theme.of(dialogContext).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton.icon(
|
||||
onPressed: () async {
|
||||
await Clipboard.setData(ClipboardData(text: uri));
|
||||
if (!dialogContext.mounted) return;
|
||||
showDismissibleSnackBar(
|
||||
dialogContext,
|
||||
content: Text(dialogContext.l10n.contacts_contactLinkCopied),
|
||||
);
|
||||
},
|
||||
icon: const Icon(Icons.copy),
|
||||
label: Text(dialogContext.l10n.common_copy),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(),
|
||||
child: Text(dialogContext.l10n.common_close),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,175 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../l10n/l10n.dart';
|
||||
import '../models/radio_preset.dart';
|
||||
import '../services/radio_preset_service.dart';
|
||||
|
||||
/// The regional preset picker (#729): presets grouped by region under
|
||||
/// non-selectable headers, each labelled with its source, plus a status line
|
||||
/// saying where the list came from (and any refresh failure) with a refresh
|
||||
/// button. Used by the companion Radio Settings form and the remote-node
|
||||
/// settings screen.
|
||||
class RadioPresetPicker extends StatelessWidget {
|
||||
const RadioPresetPicker({
|
||||
super.key,
|
||||
required this.service,
|
||||
required this.presets,
|
||||
required this.selectedId,
|
||||
required this.onSelected,
|
||||
});
|
||||
|
||||
final RadioPresetService service;
|
||||
|
||||
/// The presets to offer, already filtered and in display order (grouped
|
||||
/// by region).
|
||||
final List<RadioPreset> presets;
|
||||
final String? selectedId;
|
||||
final ValueChanged<RadioPreset> onSelected;
|
||||
|
||||
static const _regionHeaderPrefix = 'region:';
|
||||
|
||||
RadioPreset? _byId(String? id) =>
|
||||
id == null ? null : presets.where((p) => p.id == id).firstOrNull;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final theme = Theme.of(context);
|
||||
final selected = _byId(selectedId)?.id;
|
||||
final titlesById = {for (final p in presets) p.id: p.title};
|
||||
final items = <DropdownMenuItem<String>>[];
|
||||
String? region;
|
||||
for (final preset in presets) {
|
||||
if (preset.region != region) {
|
||||
region = preset.region;
|
||||
items.add(
|
||||
DropdownMenuItem<String>(
|
||||
value: '$_regionHeaderPrefix$region',
|
||||
enabled: false,
|
||||
child: Text(
|
||||
region,
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: theme.colorScheme.primary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
items.add(
|
||||
DropdownMenuItem<String>(
|
||||
value: preset.id,
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.only(start: 12),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(preset.title, overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
switch (preset.source) {
|
||||
RadioPresetSource.meshcore =>
|
||||
l10n.settings_presetSourceMeshCore,
|
||||
RadioPresetSource.offband =>
|
||||
l10n.settings_presetSourceOffband,
|
||||
},
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
DropdownButtonFormField<String>(
|
||||
key: ValueKey<String?>(selected),
|
||||
initialValue: selected,
|
||||
isExpanded: true,
|
||||
decoration: InputDecoration(
|
||||
labelText: l10n.settings_presets,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
selectedItemBuilder: (context) => [
|
||||
for (final item in items)
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: Text(
|
||||
titlesById[item.value] ?? '',
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
items: items,
|
||||
// Disabled while a refresh runs, so a pick can't vanish when the
|
||||
// refreshed list lands.
|
||||
onChanged: service.refreshing
|
||||
? null
|
||||
: (id) {
|
||||
final preset = _byId(id);
|
||||
if (preset != null) onSelected(preset);
|
||||
},
|
||||
),
|
||||
_PresetStatus(service: service),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the list came from, and any refresh failure, kept on screen until
|
||||
/// the next successful refresh.
|
||||
class _PresetStatus extends StatelessWidget {
|
||||
const _PresetStatus({required this.service});
|
||||
|
||||
final RadioPresetService service;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final theme = Theme.of(context);
|
||||
final String text;
|
||||
Color? color;
|
||||
if (service.refreshing) {
|
||||
text = l10n.settings_presetsUpdating;
|
||||
} else if (service.refreshError != null) {
|
||||
text = l10n.settings_presetsUpdateFailed;
|
||||
color = theme.colorScheme.error;
|
||||
} else if (service.lastRefreshed != null) {
|
||||
text = l10n.settings_presetsUpdatedAt(
|
||||
MaterialLocalizations.of(
|
||||
context,
|
||||
).formatMediumDate(service.lastRefreshed!.toLocal()),
|
||||
);
|
||||
} else {
|
||||
text = l10n.settings_presetsBundled;
|
||||
}
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
text,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: color ?? theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: l10n.settings_presetsRefresh,
|
||||
onPressed: service.refreshing ? null : service.refresh,
|
||||
icon: service.refreshing
|
||||
? const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.refresh),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,222 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
/// A transient, tap-to-dismiss notification anchored to the TOP of the screen.
|
||||
///
|
||||
/// The app previously used bottom-anchored [SnackBar]s, which sat on top of the
|
||||
/// chat composer (#638). A [SnackBar] is positioned by its [Scaffold] and can
|
||||
/// only be pushed upward with a near-full-height bottom margin, which delays
|
||||
/// its reveal animation and turns the whole screen into a hit-test target, so
|
||||
/// this renders through the [Overlay] instead.
|
||||
class TopToast {
|
||||
TopToast._();
|
||||
|
||||
static const Duration _animationDuration = Duration(milliseconds: 220);
|
||||
static const Duration defaultDuration = Duration(seconds: 4);
|
||||
static const double _maxWidth = 560;
|
||||
|
||||
/// Removes the toast currently on screen. Non-null only while one is visible.
|
||||
static VoidCallback? _dismissCurrent;
|
||||
|
||||
/// Shows [content] at the top of the screen.
|
||||
///
|
||||
/// When [persist] is true the toast stays until the user dismisses it, for
|
||||
/// messages that must be read rather than glimpsed (SAFELANE 6).
|
||||
static void show(
|
||||
BuildContext context, {
|
||||
required Widget content,
|
||||
Color? backgroundColor,
|
||||
Duration duration = defaultDuration,
|
||||
bool persist = false,
|
||||
}) {
|
||||
final overlay = Overlay.maybeOf(context, rootOverlay: true);
|
||||
if (overlay == null) {
|
||||
// SAFELANE 6: a message we cannot display must not disappear silently.
|
||||
appLogger.warn(
|
||||
'No Overlay in this context; notification was not shown',
|
||||
tag: 'TopToast',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// A newer message replaces the visible one outright: two entries would
|
||||
// otherwise stack on top of each other at the same position.
|
||||
_dismissCurrent?.call();
|
||||
|
||||
late final OverlayEntry entry;
|
||||
var removed = false;
|
||||
void remove() {
|
||||
if (removed) return;
|
||||
removed = true;
|
||||
entry.remove();
|
||||
if (_dismissCurrent == remove) {
|
||||
_dismissCurrent = null;
|
||||
}
|
||||
}
|
||||
|
||||
entry = OverlayEntry(
|
||||
builder: (_) => _TopToastHost(
|
||||
backgroundColor: backgroundColor,
|
||||
duration: duration,
|
||||
persist: persist,
|
||||
animationDuration: _animationDuration,
|
||||
maxWidth: _maxWidth,
|
||||
onDismissed: remove,
|
||||
child: content,
|
||||
),
|
||||
);
|
||||
_dismissCurrent = remove;
|
||||
overlay.insert(entry);
|
||||
}
|
||||
}
|
||||
|
||||
class _TopToastHost extends StatefulWidget {
|
||||
const _TopToastHost({
|
||||
required this.child,
|
||||
required this.duration,
|
||||
required this.persist,
|
||||
required this.animationDuration,
|
||||
required this.maxWidth,
|
||||
required this.onDismissed,
|
||||
this.backgroundColor,
|
||||
});
|
||||
|
||||
final Widget child;
|
||||
final Duration duration;
|
||||
final bool persist;
|
||||
final Duration animationDuration;
|
||||
final double maxWidth;
|
||||
final VoidCallback onDismissed;
|
||||
final Color? backgroundColor;
|
||||
|
||||
@override
|
||||
State<_TopToastHost> createState() => _TopToastHostState();
|
||||
}
|
||||
|
||||
class _TopToastHostState extends State<_TopToastHost>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _controller = AnimationController(
|
||||
vsync: this,
|
||||
duration: widget.animationDuration,
|
||||
);
|
||||
Timer? _timer;
|
||||
bool _dismissing = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller.forward();
|
||||
if (!widget.persist) {
|
||||
_timer = Timer(widget.duration, _dismiss);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _dismiss() async {
|
||||
if (_dismissing || !mounted) return;
|
||||
_dismissing = true;
|
||||
_timer?.cancel();
|
||||
try {
|
||||
await _controller.reverse();
|
||||
} on TickerCanceled {
|
||||
// Replaced by a newer toast mid-animation; that path already removed us.
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
widget.onDismissed();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_timer?.cancel();
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final background =
|
||||
widget.backgroundColor ??
|
||||
theme.snackBarTheme.backgroundColor ??
|
||||
theme.colorScheme.inverseSurface;
|
||||
final textStyle =
|
||||
theme.snackBarTheme.contentTextStyle ??
|
||||
theme.textTheme.titleMedium!.copyWith(
|
||||
color: theme.colorScheme.onInverseSurface,
|
||||
);
|
||||
|
||||
return Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: SafeArea(
|
||||
bottom: false,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 8, 12, 0),
|
||||
child: Align(
|
||||
alignment: Alignment.topCenter,
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxWidth: widget.maxWidth),
|
||||
child: SlideTransition(
|
||||
position:
|
||||
Tween<Offset>(
|
||||
begin: const Offset(0, -0.4),
|
||||
end: Offset.zero,
|
||||
).animate(
|
||||
CurvedAnimation(
|
||||
parent: _controller,
|
||||
curve: Curves.easeOutCubic,
|
||||
reverseCurve: Curves.easeInCubic,
|
||||
),
|
||||
),
|
||||
child: FadeTransition(
|
||||
opacity: _controller,
|
||||
// Parity with SnackBar, which wraps its content the same way
|
||||
// (snack_bar.dart): without liveRegion a screen reader never
|
||||
// announces the message at all.
|
||||
child: Semantics(
|
||||
container: true,
|
||||
liveRegion: true,
|
||||
onDismiss: _dismiss,
|
||||
child: Material(
|
||||
color: background,
|
||||
elevation: 6,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
// One recognizer for both gestures: a nested InkWell would
|
||||
// also splash on the tap-up that ends a dismissing swipe.
|
||||
child: GestureDetector(
|
||||
onTap: _dismiss,
|
||||
onVerticalDragEnd: (details) {
|
||||
if ((details.primaryVelocity ?? 0) < 0) {
|
||||
_dismiss();
|
||||
}
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 14,
|
||||
),
|
||||
child: DefaultTextStyle(
|
||||
style: textStyle,
|
||||
child: IconTheme(
|
||||
data: IconThemeData(color: textStyle.color),
|
||||
child: widget.child,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,3 @@
|
||||
# Disable clang-format for this vendored submodule so that local patches
|
||||
# are not stomped by editor auto-formatting.
|
||||
DisableFormat: true
|
||||
@ -0,0 +1,29 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
/pubspec.lock
|
||||
**/doc/api/
|
||||
.dart_tool/
|
||||
build/
|
||||
@ -0,0 +1,42 @@
|
||||
# This file tracks properties of this Flutter project.
|
||||
# Used by Flutter tool to assess capabilities and perform upgrades etc.
|
||||
#
|
||||
# This file should be version controlled and should not be manually edited.
|
||||
|
||||
version:
|
||||
revision: "dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668"
|
||||
channel: "stable"
|
||||
|
||||
project_type: plugin_ffi
|
||||
|
||||
# Tracks metadata for the flutter migrate command
|
||||
migration:
|
||||
platforms:
|
||||
- platform: root
|
||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
- platform: android
|
||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
- platform: ios
|
||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
- platform: linux
|
||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
- platform: macos
|
||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
- platform: windows
|
||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||
|
||||
# User provided section
|
||||
|
||||
# List of Local paths (relative to this file) that should be
|
||||
# ignored by the migrate tool.
|
||||
#
|
||||
# Files that are not part of the templates will be ignored by default.
|
||||
unmanaged_files:
|
||||
- 'lib/main.dart'
|
||||
- 'ios/Runner.xcodeproj/project.pbxproj'
|
||||
@ -0,0 +1,49 @@
|
||||
## 0.3.5
|
||||
* Add support 16KB Page Size
|
||||
|
||||
## 0.3.4
|
||||
* Changelog fix
|
||||
|
||||
## 0.3.3
|
||||
* Replace fifo library
|
||||
|
||||
## 0.3.2
|
||||
* MacOS support
|
||||
* Memory allocation fix
|
||||
|
||||
## 0.3.1
|
||||
* Update libs
|
||||
|
||||
## 0.3.0
|
||||
* Import project to new plugin ffi template
|
||||
* Few Api changes
|
||||
|
||||
## 0.2.0
|
||||
* New event model
|
||||
* Cleaning up unnecessary libs
|
||||
* Performance improvements
|
||||
* Api changes, main functions:
|
||||
|
||||
Stream based events, before:
|
||||
```
|
||||
serial.onSerialData.subscribe(
|
||||
```
|
||||
to:
|
||||
```
|
||||
serial.onSerialData.stream.listen(
|
||||
```
|
||||
|
||||
Write serial port, before:
|
||||
```
|
||||
serial.write(data.length, data);
|
||||
```
|
||||
to:
|
||||
```
|
||||
serial.write(data);
|
||||
```
|
||||
|
||||
## 0.1.2
|
||||
* Android compilation
|
||||
|
||||
## 0.1.1
|
||||
* Initial beta version
|
||||
@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Grzegorz Leśniak
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@ -0,0 +1,63 @@
|
||||
# flserial
|
||||
Flutter Serial Port Plugin FFI based on great C library. Useful to communicate with RS232 devices.
|
||||
|
||||
Based on great serial library: https://github.com/wjwwood/serial
|
||||
|
||||
Supported platforms:
|
||||
- Linux
|
||||
- Windows
|
||||
- Android
|
||||
- MacOS
|
||||
|
||||
Example of usage:
|
||||
|
||||
```
|
||||
FlSerial serial = FlSerial();
|
||||
serial.init();
|
||||
serial.openPort("COM3", 9600);
|
||||
serial.onSerialData.stream.listen(
|
||||
(args) {
|
||||
if (args.len > 0) {
|
||||
print(args.serial.readList());
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
serial.setByteSize8();
|
||||
serial.setBitParityNone();
|
||||
serial.setStopBits1();
|
||||
serial.setFlowControlNone();
|
||||
|
||||
String msg = "Hello World!";
|
||||
var list = msg.codeUnits;
|
||||
serial.write(Uint8List.fromList(list));
|
||||
|
||||
serial.closePort();
|
||||
serial.free();
|
||||
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Grzegorz Leśniak
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue