From 08baae42e7bd2c702c01e93486b3be28b5abbfb0 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:58:05 -0500 Subject: [PATCH] fix(#1166): a node's location is what the radio last fed The radio is the only thing that hears the mesh, so what it feeds is the truth and a value the app stored never beats it (owner ruling). - A contact sync copied the discovered entry's coordinates over the radio's (getFromDiscovered), so a stale value, often a 0,0 from a repeater heard before its location was set, hid the real location on every sync and was written back. It now copies only the raw advert, which the contact record does not carry. - A radio record with no location kept the old one; it now clears it. - A raw advert without a location, or with 0,0, kept the old one and stored 0,0 as a value. The newest advert now sets the location, including "none", and 0,0 is unknown at parse time. - An advert older than the one applied leaves the location and its age alone, unless the applied one is dated ahead of the phone: one advert from a clock set in the future must not freeze a node (Gemini). - Packet Path shows each hop's coordinates with the age of the advert that carried them. A last known location never ages out. Co-Authored-By: Claude Opus 5.5 --- lib/connector/meshcore_connector.dart | 80 ++++--- lib/l10n/app_en.arb | 12 ++ lib/l10n/app_localizations.dart | 6 + lib/l10n/app_localizations_bg.dart | 5 + lib/l10n/app_localizations_de.dart | 5 + lib/l10n/app_localizations_en.dart | 5 + lib/l10n/app_localizations_es.dart | 5 + lib/l10n/app_localizations_fr.dart | 5 + lib/l10n/app_localizations_hu.dart | 5 + lib/l10n/app_localizations_it.dart | 5 + lib/l10n/app_localizations_ja.dart | 5 + lib/l10n/app_localizations_ko.dart | 5 + lib/l10n/app_localizations_nl.dart | 5 + lib/l10n/app_localizations_pl.dart | 5 + lib/l10n/app_localizations_pt.dart | 5 + lib/l10n/app_localizations_ru.dart | 5 + lib/l10n/app_localizations_sk.dart | 5 + lib/l10n/app_localizations_sl.dart | 5 + lib/l10n/app_localizations_sv.dart | 5 + lib/l10n/app_localizations_uk.dart | 5 + lib/l10n/app_localizations_zh.dart | 5 + lib/models/contact.dart | 9 +- lib/screens/channel_message_path_screen.dart | 36 ++-- .../contact_location_truth_test.dart | 200 ++++++++++++++++++ untranslated.json | 17 ++ 25 files changed, 408 insertions(+), 42 deletions(-) create mode 100644 test/connector/contact_location_truth_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 3bfe1555..a6c6e2e6 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -5488,11 +5488,10 @@ class MeshCoreConnector extends ChangeNotifier { (c) => c.publicKeyHex == contact.publicKeyHex, orElse: () => contact, ); - return contact.copyWith( - rawPacket: tmp.rawPacket, - latitude: tmp.latitude, - longitude: tmp.longitude, - ); + // Only the raw advert, which the radio's contact record does not carry. + // The location stays the radio's: a copy the app stored is never newer + // than what the radio sends (#1166). + return contact.copyWith(rawPacket: tmp.rawPacket); } Future getContacts({int? since, bool preserveExisting = false}) async { @@ -9760,8 +9759,9 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'Connector', ); - // Preserve user-selected path settings and previously known GPS when - // refreshed frames omit coordinates (lat/lon encoded as 0,0). + // Preserve user-selected path settings. The location is the radio's, + // including "none": the radio record is the truth, not a position the + // app kept from before (#1166). // `contact` is built from the device frame, which carries no custom // name, so copyWith from it drops the user's label. Reattach it. (#750) _contacts[existingIndex] = _withCustomName( @@ -9769,8 +9769,6 @@ class MeshCoreConnector extends ChangeNotifier { lastMessageAt: mergedLastMessageAt, pathOverride: existing.pathOverride, // Preserve user's path choice pathOverrideBytes: existing.pathOverrideBytes, - latitude: contact.latitude ?? existing.latitude, - longitude: contact.longitude ?? existing.longitude, ), ); @@ -12213,6 +12211,11 @@ class MeshCoreConnector extends ChangeNotifier { latitude = packet.readInt32LE() / 1e6; longitude = packet.readInt32LE() / 1e6; } + // 0,0 is a repeater with no location set, not a place (#1166). + if (!hasValidLocation(latitude, longitude)) { + latitude = null; + longitude = null; + } if (hasName && packet.remaining > 0) { name = packet.readCString(); } @@ -12238,6 +12241,15 @@ class MeshCoreConnector extends ChangeNotifier { ); } + /// Whether an advert sent at [advertAt] replaces the one applied at + /// [appliedAt]: not older, unless the applied one is dated ahead of this + /// phone. Node clocks can be wrong, and one advert from a clock set in the + /// future must not shut out every correct advert after it (#1166). + static bool isNewerAdvert(DateTime advertAt, DateTime appliedAt) { + if (!advertAt.isBefore(appliedAt)) return true; + return appliedAt.isAfter(DateTime.now().add(const Duration(hours: 1))); + } + bool hasValidLocation(double? latitude, double? longitude) { const double epsilon = 1e-6; final lat = latitude ?? 0.0; @@ -12286,8 +12298,12 @@ class MeshCoreConnector extends ChangeNotifier { latitude = advert.readInt32LE() / 1e6; longitude = advert.readInt32LE() / 1e6; } - // Validate location values if present + // No flag, or 0,0, both mean "no location": never stored as a place. hasLocation = hasValidLocation(latitude, longitude); + if (!hasLocation) { + latitude = null; + longitude = null; + } if (hasName && advert.remaining > 0) { name = advert.readCString(); @@ -12354,10 +12370,17 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'Connector', ); + // The newest advert sets the location, including "none". One older than + // the advert already applied (a slow flood copy) leaves the location and + // its age alone (#1166). + final advertAt = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); + final isNewer = isNewerAdvert(advertAt, existing.lastSeen); + // CRITICAL: Preserve user's path override when contact is refreshed from device _contacts[existingIndex] = existing.copyWith( - latitude: hasLocation ? latitude : existing.latitude, - longitude: hasLocation ? longitude : existing.longitude, + latitude: isNewer ? latitude : null, + longitude: isNewer ? longitude : null, + clearLocation: isNewer && !hasLocation, // The received name updates; the user's custom name is untouched, so // what they see does not move. This is the whole point of #750: before // it, an advert took the user's chosen name back every time, which is @@ -12369,10 +12392,11 @@ class MeshCoreConnector extends ChangeNotifier { path: Uint8List.fromList(path.reversed.toList()), pathLength: path.length, lastMessageAt: mergedLastMessageAt, - lastSeen: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000), + lastSeen: isNewer ? advertAt : null, pathOverride: existing.pathOverride, // Preserve user's path choice pathOverrideBytes: existing.pathOverrideBytes, ); + if (isNewer) notifyListeners(); // Add path to history if we have a valid path if (_pathHistoryService != null && @@ -12454,19 +12478,23 @@ class MeshCoreConnector extends ChangeNotifier { // Update existing contact if (existingIndex >= 0) { - _discoveredContacts[existingIndex] = _discoveredContacts[existingIndex] - .copyWith( - rawPacket: rawPacket, - receivedName: contact.receivedName, - type: contact.type, - pathLength: contact.pathLength, - path: contact.path, - latitude: contact.latitude, - longitude: contact.longitude, - lastSeen: contact.lastSeen, - flags: 0, - isActive: addActive, - ); + final existing = _discoveredContacts[existingIndex]; + // The newest advert sets the location, including "none". An older one + // arriving late (a slow flood copy) leaves it and its age alone (#1166). + final isNewer = isNewerAdvert(contact.lastSeen, existing.lastSeen); + _discoveredContacts[existingIndex] = existing.copyWith( + rawPacket: rawPacket, + receivedName: contact.receivedName, + type: contact.type, + pathLength: contact.pathLength, + path: contact.path, + latitude: isNewer ? contact.latitude : null, + longitude: isNewer ? contact.longitude : null, + clearLocation: isNewer && contact.latitude == null, + lastSeen: isNewer ? contact.lastSeen : null, + flags: 0, + isActive: addActive, + ); notifyListeners(); unawaited(_persistDiscoveredContacts()); return; diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index b2f3fda3..8e67779f 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -2438,6 +2438,18 @@ } }, "channelPath_noLocationData": "No location data", + "channelPath_locationWithAge": "{location} • {age}", + "@channelPath_locationWithAge": { + "description": "A repeater's last known location and how long ago its advert carrying it was sent", + "placeholders": { + "location": { + "type": "String" + }, + "age": { + "type": "String" + } + } + }, "channelPath_timeWithDate": "{day}/{month} {time}", "@channelPath_timeWithDate": { "placeholders": { diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index cd0b9837..9860baf5 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -7406,6 +7406,12 @@ abstract class AppLocalizations { /// **'No location data'** String get channelPath_noLocationData; + /// A repeater's last known location and how long ago its advert carrying it was sent + /// + /// In en, this message translates to: + /// **'{location} • {age}'** + String channelPath_locationWithAge(String location, String age); + /// No description provided for @channelPath_timeWithDate. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 16074096..f0cc3bd1 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -4361,6 +4361,11 @@ class AppLocalizationsBg extends AppLocalizations { @override String get channelPath_noLocationData => 'Няма данни за местоположение.'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 86d2d4ac..758cb5ea 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -4367,6 +4367,11 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channelPath_noLocationData => 'Keine Standortdaten'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index c31afc87..2c8694b3 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -4298,6 +4298,11 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channelPath_noLocationData => 'No location data'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 4a731d04..306d9698 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -4356,6 +4356,11 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channelPath_noLocationData => 'No datos de ubicación'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month a las $time'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index ca1692eb..c3727a30 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -4378,6 +4378,11 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channelPath_noLocationData => 'Aucune donnée de localisation'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index f8276eeb..11e49620 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -4373,6 +4373,11 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channelPath_noLocationData => 'Nincs helyszínadat.'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index aa91e014..68d6cdb5 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -4361,6 +4361,11 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channelPath_noLocationData => 'Nessun dato di posizione'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index e7acd1d5..89cb6538 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -4179,6 +4179,11 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channelPath_noLocationData => '場所に関するデータはありません'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 0739a01d..fd491df6 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -4181,6 +4181,11 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channelPath_noLocationData => '위치 정보 없음'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index f54677a7..ca93abed 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -4342,6 +4342,11 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channelPath_noLocationData => 'Geen locatiegegevens'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 455aa673..1523af2b 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -4374,6 +4374,11 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channelPath_noLocationData => 'Brak danych lokalizacyjnych'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index c46b31ee..002e2f2e 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -4355,6 +4355,11 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channelPath_noLocationData => 'Não há dados de localização.'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index a9332831..5b342b85 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -4363,6 +4363,11 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channelPath_noLocationData => 'Нет данных о местоположении'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 18142185..0acce1e8 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -4342,6 +4342,11 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channelPath_noLocationData => 'Žiadne údaje o polohe'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index f2ea851f..82f924d3 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -4337,6 +4337,11 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channelPath_noLocationData => 'Nihče ni določil lokacije.'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 84f5f16a..6b77e46b 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -4317,6 +4317,11 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channelPath_noLocationData => 'Ingen platsdata'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month kl. $time'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 2877c165..23c59539 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -4359,6 +4359,11 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channelPath_noLocationData => 'Немає даних про геопозицію'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index d23c2d3d..56212179 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -4084,6 +4084,11 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channelPath_noLocationData => '无位置信息'; + @override + String channelPath_locationWithAge(String location, String age) { + return '$location • $age'; + } + @override String channelPath_timeWithDate(int day, int month, String time) { return '$day/$month $time'; diff --git a/lib/models/contact.dart b/lib/models/contact.dart index d50acde2..2e8dcfa0 100644 --- a/lib/models/contact.dart +++ b/lib/models/contact.dart @@ -147,6 +147,10 @@ class Contact { bool clearPathOverride = false, double? latitude, double? longitude, + + /// Sets the location to unknown. A null [latitude] means "leave it alone", + /// so withdrawing a location needs its own flag. (#1166) + bool clearLocation = false, DateTime? lastSeen, DateTime? lastMessageAt, DateTime? lastModified, @@ -168,8 +172,8 @@ class Contact { pathOverrideBytes: clearPathOverride ? null : (pathOverrideBytes ?? this.pathOverrideBytes), - latitude: latitude ?? this.latitude, - longitude: longitude ?? this.longitude, + latitude: clearLocation ? null : (latitude ?? this.latitude), + longitude: clearLocation ? null : (longitude ?? this.longitude), lastSeen: lastSeen ?? this.lastSeen, lastMessageAt: lastMessageAt ?? this.lastMessageAt, lastModified: lastModified ?? this.lastModified, @@ -261,7 +265,6 @@ class Contact { final latRaw = reader.readInt32LE(); final lonRaw = reader.readInt32LE(); final lastModRaw = reader.readUInt32LE(); - // TODO: should this be &&? if (latRaw != 0 || lonRaw != 0) { lat = latRaw / 1e6; lon = lonRaw / 1e6; diff --git a/lib/screens/channel_message_path_screen.dart b/lib/screens/channel_message_path_screen.dart index 389ec53e..3ad3c229 100644 --- a/lib/screens/channel_message_path_screen.dart +++ b/lib/screens/channel_message_path_screen.dart @@ -221,7 +221,6 @@ class ChannelMessagePathScreen extends StatelessWidget { } List _buildHopTiles(BuildContext context, List<_PathHop> hops) { - final l10n = context.l10n; return [ for (final hop in hops) Card( @@ -236,12 +235,7 @@ class ChannelMessagePathScreen extends StatelessWidget { ), ), title: Text(hop.displayLabel), - subtitle: Text( - hop.hasLocation - ? '${hop.position!.latitude.toStringAsFixed(5)}, ' - '${hop.position!.longitude.toStringAsFixed(5)}' - : l10n.channelPath_noLocationData, - ), + subtitle: Text(hop.locationLabel), ), ), ]; @@ -910,12 +904,7 @@ class _ChannelMessagePathMapScreenState ), ), title: Text(hop.displayLabel), - subtitle: Text( - hop.hasLocation - ? '${hop.position!.latitude.toStringAsFixed(5)}, ' - '${hop.position!.longitude.toStringAsFixed(5)}' - : l10n.channelPath_noLocationData, - ), + subtitle: Text(hop.locationLabel), ); }, ), @@ -945,6 +934,27 @@ class _PathHop { bool get hasLocation => position != null; + /// The coordinates and how old they are. The location is the last one the + /// node advertised, kept until a newer advert replaces or withdraws it, so + /// its age is the age of that advert (#1166). + String get locationLabel { + final p = position; + if (p == null) return l10n.channelPath_noLocationData; + final coords = + '${p.latitude.toStringAsFixed(5)}, ${p.longitude.toStringAsFixed(5)}'; + final c = contact; + if (c == null || !c.isAdvertVerified) return coords; + return l10n.channelPath_locationWithAge(coords, _advertAge(c.lastSeen)); + } + + String _advertAge(DateTime advertAt) { + final diff = DateTime.now().difference(advertAt); + if (diff.inMinutes < 1) return l10n.time_justNow; + if (diff.inHours < 1) return l10n.time_minutesAgo(diff.inMinutes); + if (diff.inDays < 1) return l10n.time_hoursAgo(diff.inHours); + return l10n.time_daysAgo(diff.inDays); + } + String get displayLabel { final prefixLabel = _formatHash(hash); return '($prefixLabel) ${_resolveName(contact, l10n)}'; diff --git a/test/connector/contact_location_truth_test.dart b/test/connector/contact_location_truth_test.dart new file mode 100644 index 00000000..cf6d479b --- /dev/null +++ b/test/connector/contact_location_truth_test.dart @@ -0,0 +1,200 @@ +// #1166: a node's location is whatever the radio last fed for it. A value the +// app stored never beats it, 0,0 means unknown, and an advert without a +// location withdraws the old one. + +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +final _key = Uint8List.fromList(List.generate(32, (i) => 0x5A + i)); + +const _lat = 12345670; +const _lon = -23456780; + +List _i32(int v) => + (ByteData(4)..setInt32(0, v, Endian.little)).buffer.asUint8List(); + +List _u32(int v) => + (ByteData(4)..setUint32(0, v, Endian.little)).buffer.asUint8List(); + +/// A raw advert as the radio forwards it (0x88). [lat] null leaves the +/// location flag off; 0,0 sets the flag with zeros, as a repeater with no +/// location configured does. +List _rxAdvert(int ts, {int? lat, int? lon, int type = advTypeRepeater}) => + [ + 0x88, 0, 0, + (payloadTypeADVERT << 2) | 0x01, // flood + 0, // no path + ..._key, + ..._u32(ts), + ...List.filled(64, 0), + type | (lat != null ? 0x10 : 0) | 0x80, + if (lat != null) ..._i32(lat), + if (lon != null) ..._i32(lon), + ...'NODE'.codeUnits, + ]; + +/// The radio's own record for the node: a contact sync frame, or the +/// new-advert push, which has the same layout. +List _radioRecord( + int ts, { + int lat = 0, + int lon = 0, + int code = respCodeContact, +}) => [ + code, + ..._key, + advTypeRepeater, + 0, + 0, + ...List.filled(maxPathSize, 0), + ...'NODE'.codeUnits, + ...List.filled(maxNameSize - 4, 0), + ..._u32(ts), + ..._i32(lat), + ..._i32(lon), + ..._u32(ts), +]; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late OffbandDatabase db; + late MeshCoreConnector c; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + c = MeshCoreConnector(); + c.setConnectedForTest(); + c.sendFrameOverrideForTest = (_) {}; + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + Contact contact() => c.contacts.single; + Contact discovered() => c.discoveredContacts.single; + + group('the radio record beats what the app stored', () { + test('a 0,0 heard earlier does not hide the location the radio sends', () { + c.handleFrameForTest(_rxAdvert(1000, lat: 0, lon: 0)); + + c.handleFrameForTest(_radioRecord(2000, lat: _lat, lon: _lon)); + + expect(contact().hasLocation, isTrue); + expect(contact().latitude, closeTo(12.34567, 1e-6)); + }); + + test('an older real location stored by the app does not win either', () { + c.handleFrameForTest(_rxAdvert(1000, lat: 41000000, lon: -87000000)); + + c.handleFrameForTest(_radioRecord(2000, lat: _lat, lon: _lon)); + + expect(contact().latitude, closeTo(12.34567, 1e-6)); + }); + + test('a live location survives the next contact sync', () { + c.handleFrameForTest(_rxAdvert(1000, lat: 0, lon: 0)); + c.handleFrameForTest(_radioRecord(1000)); + c.handleFrameForTest(_rxAdvert(3000, lat: _lat, lon: _lon)); + + c.handleFrameForTest(_radioRecord(3000, lat: _lat, lon: _lon)); + + expect(contact().latitude, closeTo(12.34567, 1e-6)); + }); + + test('a radio record with no location clears the old one', () { + c.handleFrameForTest(_radioRecord(1000, lat: _lat, lon: _lon)); + + c.handleFrameForTest(_radioRecord(2000)); + + expect(contact().hasLocation, isFalse); + expect(contact().latitude, isNull); + }); + }); + + group('the newest advert sets the location', () { + setUp(() => c.handleFrameForTest(_radioRecord(1000, lat: _lat, lon: _lon))); + + test('an advert without a location withdraws it', () { + c.handleFrameForTest(_rxAdvert(2000)); + + expect(contact().latitude, isNull); + }); + + test('an advert with 0,0 withdraws it', () { + c.handleFrameForTest(_rxAdvert(2000, lat: 0, lon: 0)); + + expect(contact().latitude, isNull); + }); + + test('one advert from a clock set in the future does not freeze it', () { + final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + c.handleFrameForTest(_rxAdvert(now + 365 * 86400)); // clock a year ahead + + c.handleFrameForTest(_rxAdvert(now, lat: _lat, lon: _lon)); // clock fixed + + expect(contact().latitude, closeTo(12.34567, 1e-6)); + }); + + test('an advert older than the one already applied changes nothing', () { + c.handleFrameForTest(_rxAdvert(500)); + + expect(contact().latitude, closeTo(12.34567, 1e-6)); + expect(contact().lastSeen.millisecondsSinceEpoch, 1000 * 1000); + }); + }); + + group('a node the radio did not save', () { + test('0,0 is stored as unknown, never as a position', () { + c.handleFrameForTest(_rxAdvert(1000, lat: 0, lon: 0, type: advTypeChat)); + + expect(discovered().latitude, isNull); + expect(discovered().longitude, isNull); + }); + + test('a later advert without a location withdraws the old one', () { + c.handleFrameForTest( + _rxAdvert(1000, lat: _lat, lon: _lon, type: advTypeChat), + ); + + c.handleFrameForTest(_rxAdvert(2000, type: advTypeChat)); + + expect(discovered().latitude, isNull); + }); + + test('one advert from a clock set in the future does not freeze it', () { + final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + c.handleFrameForTest(_rxAdvert(now + 365 * 86400, type: advTypeChat)); + + c.handleFrameForTest( + _rxAdvert(now, lat: _lat, lon: _lon, type: advTypeChat), + ); + + expect(discovered().latitude, closeTo(12.34567, 1e-6)); + }); + + test('an older advert does not roll the location back', () { + c.handleFrameForTest( + _rxAdvert(2000, lat: _lat, lon: _lon, type: advTypeChat), + ); + + c.handleFrameForTest(_rxAdvert(1000, type: advTypeChat)); + + expect(discovered().latitude, closeTo(12.34567, 1e-6)); + }); + }); +} diff --git a/untranslated.json b/untranslated.json index 0bce3ab7..73f95601 100644 --- a/untranslated.json +++ b/untranslated.json @@ -227,6 +227,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -627,6 +628,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -1027,6 +1029,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -1427,6 +1430,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -1827,6 +1831,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -2227,6 +2232,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -2627,6 +2633,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -3027,6 +3034,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -3427,6 +3435,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -3827,6 +3836,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -4227,6 +4237,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -4627,6 +4638,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -5027,6 +5039,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -5427,6 +5440,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -5827,6 +5841,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -6227,6 +6242,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel", @@ -6627,6 +6643,7 @@ "repeater_tempRadioPathHashNote", "repeater_tempRadioMinutesInvalid", "repeater_cliCommandTimeout", + "channelPath_locationWithAge", "channelPath_routeDirect", "channelPath_routeFlood", "channelPath_snrLabel",