feat(#727): add the radio preset model and parsers for both preset files

RadioPreset carries frequency, bandwidth, SF, CR, and optional TX power,
path hash (bytes) and off-grid flag, plus its region and source.
parseUpstreamPresets reads the mirrored MeshCore list (string numbers);
parseOverlayPresets reads Offband's overlay (JSON numbers, retired
entries dropped). Malformed entries are skipped and counted; a wrong
format or a newer format_version is rejected. Upstream titles carry no
region, so upstreamRegionFor derives the picker group from the title.

Epic: #726
Agent: MagentaHawk (session 5a8922d6)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pull/744/head
diffwireauto 2 months ago
parent 2c7e21e484
commit 0ed9bd717a

@ -0,0 +1,271 @@
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;
int get frequencyHz => (frequencyMHz * 1000).round();
}
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,196 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/radio_preset.dart';
import 'package:meshcore_open/models/radio_settings.dart';
String upstream(List<Map<String, dynamic>> entries, {int version = 1}) =>
jsonEncode({
'format': kUpstreamPresetFormat,
'format_version': version,
'source': 'https://api.meshcore.nz/api/v1/config',
'credit': 'Liam Cottle / MeshCore',
'updated_at': '2026-10-01T00:00:00Z',
'suggested_radio_settings': {'entries': entries},
});
String overlay(List<Map<String, dynamic>> presets, {int version = 1}) =>
jsonEncode({
'format': kOverlayPresetFormat,
'format_version': version,
'presets': presets,
});
Map<String, dynamic> overlayEntry(String id, {Map<String, dynamic>? extra}) => {
'id': id,
'title': 'USA - $id',
'region': 'USA',
'frequency': 909.75,
'bandwidth': 500,
'spreading_factor': 10,
'coding_rate': 5,
'status': 'published',
...?extra,
};
void main() {
group('parseUpstreamPresets (#727)', () {
test('reads the API shape, where numbers are strings', () {
final r = parseUpstreamPresets(
upstream([
{
'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': 'EU/UK (Narrow)',
'frequency': '869.618',
'spreading_factor': '8',
'bandwidth': '62.5',
'coding_rate': '8',
},
]),
);
expect(r.skipped, 0);
final socal = r.presets[0];
expect(socal.id, 'meshcore:USA - Southern California');
expect(socal.region, 'USA');
expect(socal.frequencyHz, 927875);
expect(socal.bandwidth, LoRaBandwidth.bw62_5);
expect(socal.spreadingFactor, LoRaSpreadingFactor.sf7);
expect(socal.codingRate, LoRaCodingRate.cr4_5);
expect(socal.pathHashBytes, 3);
expect(socal.txPowerDbm, isNull);
expect(socal.source, RadioPresetSource.meshcore);
expect(r.presets[1].codingRate, LoRaCodingRate.cr4_8);
expect(r.presets[1].pathHashBytes, isNull);
});
test('skips and counts malformed entries instead of failing', () {
final r = parseUpstreamPresets(
upstream([
{
'title': 'Good',
'frequency': '910.525',
'spreading_factor': '7',
'bandwidth': '62.5',
'coding_rate': '5',
},
{
'title': 'Bad BW',
'frequency': '910.525',
'spreading_factor': '7',
'bandwidth': '63',
'coding_rate': '5',
},
{
'title': 'Bad hash',
'frequency': '910.525',
'spreading_factor': '7',
'bandwidth': '62.5',
'coding_rate': '5',
'network_settings': {'path_hash_size': 4},
},
{'title': 'Missing values'},
]),
);
expect(r.presets.map((p) => p.title), ['Good']);
expect(r.skipped, 3);
});
test('rejects a wrong format or a newer format_version', () {
expect(
() => parseUpstreamPresets(overlay([])),
throwsA(isA<RadioPresetFormatException>()),
);
expect(
() => parseUpstreamPresets(upstream([], version: 2)),
throwsA(isA<RadioPresetFormatException>()),
);
expect(
() => parseUpstreamPresets('<html>502</html>'),
throwsA(isA<RadioPresetFormatException>()),
);
});
});
group('parseOverlayPresets (#727)', () {
test(
'reads overlay entries with optional TX power, path hash, off-grid',
() {
final r = parseOverlayPresets(
overlay([
overlayEntry(
'philly',
extra: {'tx_power': 20, 'path_hash_size': 2},
),
overlayEntry(
'grid',
extra: {
'region': 'Off-Grid',
'frequency': 918.0,
'bandwidth': 250,
'spreading_factor': 11,
'coding_rate': 8,
'off_grid': true,
},
),
]),
);
expect(r.skipped, 0);
final philly = r.presets[0];
expect(philly.id, 'offband:philly');
expect(philly.bandwidth, LoRaBandwidth.bw500);
expect(philly.txPowerDbm, 20);
expect(philly.pathHashBytes, 2);
expect(philly.source, RadioPresetSource.offband);
expect(philly.offGrid, isFalse);
expect(r.presets[1].offGrid, isTrue);
expect(r.presets[1].region, 'Off-Grid');
},
);
test('drops retired entries without counting them as skipped', () {
final r = parseOverlayPresets(
overlay([
overlayEntry('old', extra: {'status': 'retired'}),
overlayEntry('new'),
]),
);
expect(r.presets.map((p) => p.id), ['offband:new']);
expect(r.skipped, 0);
});
test('skips hand-edit mistakes: string numbers, bad TX, bad hash', () {
final r = parseOverlayPresets(
overlay([
overlayEntry('a', extra: {'frequency': '909.75'}),
overlayEntry('b', extra: {'tx_power': 40}),
overlayEntry('c', extra: {'path_hash_size': '2'}),
overlayEntry('d', extra: {'coding_rate': 4}),
]),
);
expect(r.presets, isEmpty);
expect(r.skipped, 4);
});
});
group('upstreamRegionFor (#727)', () {
test('groups upstream titles by their leading region', () {
expect(upstreamRegionFor('USA'), 'USA');
expect(upstreamRegionFor('USA - Southern California'), 'USA');
expect(upstreamRegionFor('Australia: QLD'), 'Australia');
expect(upstreamRegionFor('Australia (Narrow)'), 'Australia');
expect(upstreamRegionFor('EU/UK (Narrow)'), 'EU/UK');
expect(upstreamRegionFor('Portugal 433'), 'Portugal');
expect(upstreamRegionFor('Portugal 868'), 'Portugal');
expect(upstreamRegionFor('Costa Rica'), 'Costa Rica');
expect(upstreamRegionFor('New Zealand (Gisborne)'), 'New Zealand');
});
});
}
Loading…
Cancel
Save

Powered by TurnKey Linux.