From f0144ca959ddd3ff8238d806c7a1be2a53975abd Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sun, 25 Oct 2026 11:10:27 -0700 Subject: [PATCH] Show telemetry GPS fixes on the map and add a map location request Telemetry replies carried a GPS fix that was only shown on the telemetry screen, so the map kept the node at its last advert position. The fix now updates the contact and survives radio contact refreshes until the node adverts again (compared on the node's own advert clock). The map node card gains an "Update location" button for companions and sensors; repeaters and rooms only share GPS with logged-in admins, so they don't get it. --- lib/connector/meshcore_connector.dart | 89 ++++++++++--- lib/l10n/app_bg.arb | 4 + lib/l10n/app_de.arb | 4 + lib/l10n/app_en.arb | 6 + lib/l10n/app_es.arb | 4 + lib/l10n/app_fr.arb | 4 + lib/l10n/app_hu.arb | 4 + lib/l10n/app_it.arb | 4 + lib/l10n/app_ja.arb | 4 + lib/l10n/app_ko.arb | 4 + lib/l10n/app_localizations.dart | 24 ++++ lib/l10n/app_localizations_bg.dart | 16 +++ lib/l10n/app_localizations_de.dart | 16 +++ lib/l10n/app_localizations_en.dart | 16 +++ lib/l10n/app_localizations_es.dart | 16 +++ lib/l10n/app_localizations_fr.dart | 16 +++ lib/l10n/app_localizations_hu.dart | 16 +++ lib/l10n/app_localizations_it.dart | 16 +++ lib/l10n/app_localizations_ja.dart | 16 +++ lib/l10n/app_localizations_ko.dart | 16 +++ lib/l10n/app_localizations_nl.dart | 16 +++ lib/l10n/app_localizations_pl.dart | 16 +++ lib/l10n/app_localizations_pt.dart | 16 +++ lib/l10n/app_localizations_ru.dart | 16 +++ lib/l10n/app_localizations_sk.dart | 16 +++ lib/l10n/app_localizations_sl.dart | 16 +++ lib/l10n/app_localizations_sv.dart | 16 +++ lib/l10n/app_localizations_uk.dart | 16 +++ lib/l10n/app_localizations_zh.dart | 16 +++ lib/l10n/app_nl.arb | 4 + lib/l10n/app_pl.arb | 4 + lib/l10n/app_pt.arb | 4 + lib/l10n/app_ru.arb | 4 + lib/l10n/app_sk.arb | 4 + lib/l10n/app_sl.arb | 4 + lib/l10n/app_sv.arb | 4 + lib/l10n/app_uk.arb | 4 + lib/l10n/app_zh.arb | 4 + lib/models/contact.dart | 12 ++ lib/screens/map_screen.dart | 60 +++++++++ lib/screens/telemetry_screen.dart | 9 ++ lib/services/telemetry_location_request.dart | 127 +++++++++++++++++++ lib/storage/contact_store.dart | 6 + test/connector/telemetry_location_test.dart | 110 ++++++++++++++++ 44 files changed, 780 insertions(+), 19 deletions(-) create mode 100644 lib/services/telemetry_location_request.dart create mode 100644 test/connector/telemetry_location_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 0784a1ed..8e59a81c 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -810,6 +810,71 @@ class MeshCoreConnector extends ChangeNotifier { } } + /// Applies a GPS fix from a telemetry reply to the contact so the map and + /// lists show where the node is now, not where its last advert put it. + /// [_mergeRefreshedContact] keeps this fix until a newer advert arrives. + void updateContactLocationFromTelemetry( + String contactKeyHex, + double latitude, + double longitude, + ) { + final index = _contacts.indexWhere((c) => c.publicKeyHex == contactKeyHex); + if (index < 0) return; + final existing = _contacts[index]; + final updated = existing.copyWith( + latitude: latitude, + longitude: longitude, + lastSeen: DateTime.now(), + telemetryFixAdvertSeen: + existing.telemetryFixAdvertSeen ?? existing.lastSeen, + ); + if (!updated.hasLocation) return; + _contacts[index] = updated; + notifyListeners(); + unawaited(_persistContacts()); + } + + /// Merges a contact record from the radio (contact list or advert) into the + /// one we already hold. The radio only knows the advert position, so a + /// telemetry fix stays until the node adverts again; timestamps are + /// compared only against the node's own advert clock. + Contact _mergeRefreshedContact( + Contact existing, + Contact incoming, { + bool keepLocationWhenMissing = false, + }) { + final mergedLastMessageAt = + existing.lastMessageAt.isAfter(incoming.lastMessageAt) + ? existing.lastMessageAt + : incoming.lastMessageAt; + final fixAdvertSeen = existing.telemetryFixAdvertSeen; + final keepTelemetryFix = + fixAdvertSeen != null && !incoming.lastSeen.isAfter(fixAdvertSeen); + if (keepTelemetryFix) { + return incoming.copyWith( + lastMessageAt: mergedLastMessageAt, + pathOverride: existing.pathOverride, // Preserve user's path choice + pathOverrideBytes: existing.pathOverrideBytes, + latitude: existing.latitude, + longitude: existing.longitude, + lastSeen: existing.lastSeen, + telemetryFixAdvertSeen: fixAdvertSeen, + ); + } + return incoming.copyWith( + lastMessageAt: mergedLastMessageAt, + pathOverride: existing.pathOverride, // Preserve user's path choice + pathOverrideBytes: existing.pathOverrideBytes, + latitude: keepLocationWhenMissing + ? incoming.latitude ?? existing.latitude + : incoming.latitude, + longitude: keepLocationWhenMissing + ? incoming.longitude ?? existing.longitude + : incoming.longitude, + clearTelemetryFix: true, + ); + } + String _batteryChemistryForDevice() { final deviceId = batteryDeviceKey; if (deviceId == null || _appSettingsService == null) return 'nmc'; @@ -6861,10 +6926,6 @@ class MeshCoreConnector extends ChangeNotifier { if (existingIndex >= 0) { final existing = _contacts[existingIndex]; - final mergedLastMessageAt = - existing.lastMessageAt.isAfter(contact.lastMessageAt) - ? existing.lastMessageAt - : contact.lastMessageAt; appLogger.info( 'Refreshing contact ${contact.name}: devicePath=${contact.pathLength}, existingOverride=${existing.pathOverride}', @@ -6873,12 +6934,10 @@ class MeshCoreConnector extends ChangeNotifier { // Preserve user-selected path settings and previously known GPS when // refreshed frames omit coordinates (lat/lon encoded as 0,0). - _contacts[existingIndex] = contact.copyWith( - lastMessageAt: mergedLastMessageAt, - pathOverride: existing.pathOverride, // Preserve user's path choice - pathOverrideBytes: existing.pathOverrideBytes, - latitude: contact.latitude ?? existing.latitude, - longitude: contact.longitude ?? existing.longitude, + _contacts[existingIndex] = _mergeRefreshedContact( + existing, + contact, + keepLocationWhenMissing: true, ); appLogger.info( @@ -6945,10 +7004,6 @@ class MeshCoreConnector extends ChangeNotifier { if (existingIndex >= 0) { final existing = _contacts[existingIndex]; - final mergedLastMessageAt = - existing.lastMessageAt.isAfter(contact.lastMessageAt) - ? existing.lastMessageAt - : contact.lastMessageAt; appLogger.info( 'Refreshing contact ${contact.name}: devicePath=${contact.pathLength}, existingOverride=${existing.pathOverride}', @@ -6956,11 +7011,7 @@ class MeshCoreConnector extends ChangeNotifier { ); // CRITICAL: Preserve user's path override when contact is refreshed from device - _contacts[existingIndex] = contact.copyWith( - lastMessageAt: mergedLastMessageAt, - pathOverride: existing.pathOverride, // Preserve user's path choice - pathOverrideBytes: existing.pathOverrideBytes, - ); + _contacts[existingIndex] = _mergeRefreshedContact(existing, contact); appLogger.info( 'After merge: pathOverride=${_contacts[existingIndex].pathOverride}, devicePath=${_contacts[existingIndex].pathLength}', diff --git a/lib/l10n/app_bg.arb b/lib/l10n/app_bg.arb index 31faa683..1e65d44c 100644 --- a/lib/l10n/app_bg.arb +++ b/lib/l10n/app_bg.arb @@ -3301,6 +3301,10 @@ "map_youWithMarkers": "Вие и {count} маркера", "map_sharedMarkerSemantics": "Споделен маркер: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Обнови местоположението", + "map_locationUpdated": "Местоположението е обновено", + "map_locationNotShared": "{name} отговори без местоположение", + "map_locationRequestFailed": "Няма отговор от {name}", "mapCache_zoomLevel": "Мащаб {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 34f6e580..16f1c302 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -3436,6 +3436,10 @@ "map_youWithMarkers": "Du und {count} Marker", "map_sharedMarkerSemantics": "Geteilter Marker: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Standort aktualisieren", + "map_locationUpdated": "Standort aktualisiert", + "map_locationNotShared": "{name} hat ohne Standort geantwortet", + "map_locationRequestFailed": "Keine Antwort von {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e1a0c35d..01d38be4 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -3455,6 +3455,12 @@ "@map_sharedMarkerSemantics": {"placeholders": {"label": {"type": "String"}}}, "map_nodeMarkerSemantics": "{name}, {type}, {status}", "@map_nodeMarkerSemantics": {"placeholders": {"name": {"type": "String"}, "type": {"type": "String"}, "status": {"type": "String"}}}, + "map_requestLocation": "Update location", + "map_locationUpdated": "Location updated", + "map_locationNotShared": "{name} replied without a location", + "@map_locationNotShared": {"placeholders": {"name": {"type": "String"}}}, + "map_locationRequestFailed": "No reply from {name}", + "@map_locationRequestFailed": {"placeholders": {"name": {"type": "String"}}}, "mapCache_zoomLevel": "Zoom {zoom}", "@mapCache_zoomLevel": {"placeholders": {"zoom": {"type": "int"}}}, "mapCache_sizeBytes": "{size} B", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index a435a366..cbf53be7 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -3318,6 +3318,10 @@ "map_youWithMarkers": "Tú y {count} marcadores", "map_sharedMarkerSemantics": "Marcador compartido: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Actualizar ubicación", + "map_locationUpdated": "Ubicación actualizada", + "map_locationNotShared": "{name} respondió sin ubicación", + "map_locationRequestFailed": "Sin respuesta de {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index a6a75dd0..72e9b92f 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -3318,6 +3318,10 @@ "map_youWithMarkers": "Vous et {count} marqueurs", "map_sharedMarkerSemantics": "Marqueur partagé : {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Actualiser la position", + "map_locationUpdated": "Position actualisée", + "map_locationNotShared": "{name} a répondu sans position", + "map_locationRequestFailed": "Aucune réponse de {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} o", "mapCache_sizeKilobytes": "{size} Ko", diff --git a/lib/l10n/app_hu.arb b/lib/l10n/app_hu.arb index 08adc56d..fe2e8760 100644 --- a/lib/l10n/app_hu.arb +++ b/lib/l10n/app_hu.arb @@ -3340,6 +3340,10 @@ "map_youWithMarkers": "Ön és {count} jelölő", "map_sharedMarkerSemantics": "Megosztott jelölő: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Hely frissítése", + "map_locationUpdated": "Hely frissítve", + "map_locationNotShared": "{name} helyadat nélkül válaszolt", + "map_locationRequestFailed": "Nincs válasz tőle: {name}", "mapCache_zoomLevel": "Nagyítás: {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index 20b61e49..29f5323a 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -3318,6 +3318,10 @@ "map_youWithMarkers": "Tu e {count} segnaposti", "map_sharedMarkerSemantics": "Segnaposto condiviso: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Aggiorna posizione", + "map_locationUpdated": "Posizione aggiornata", + "map_locationNotShared": "{name} ha risposto senza posizione", + "map_locationRequestFailed": "Nessuna risposta da {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 525ceac7..af3e173b 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -3318,6 +3318,10 @@ "map_youWithMarkers": "自分と{count}件のマーカー", "map_sharedMarkerSemantics": "共有マーカー: {label}", "map_nodeMarkerSemantics": "{name}、{type}、{status}", + "map_requestLocation": "位置情報を更新", + "map_locationUpdated": "位置情報を更新しました", + "map_locationNotShared": "{name} は位置情報なしで応答しました", + "map_locationRequestFailed": "{name} から応答がありません", "mapCache_zoomLevel": "ズーム {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 21b017ac..f0d9a4e2 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -3318,6 +3318,10 @@ "map_youWithMarkers": "나와 마커 {count}개", "map_sharedMarkerSemantics": "공유 마커: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "위치 업데이트", + "map_locationUpdated": "위치가 업데이트되었습니다", + "map_locationNotShared": "{name}이(가) 위치 없이 응답했습니다", + "map_locationRequestFailed": "{name}의 응답이 없습니다", "mapCache_zoomLevel": "줌 {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 4a309227..2e999b8c 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -10238,6 +10238,30 @@ abstract class AppLocalizations { /// **'{name}, {type}, {status}'** String map_nodeMarkerSemantics(String name, String type, String status); + /// No description provided for @map_requestLocation. + /// + /// In en, this message translates to: + /// **'Update location'** + String get map_requestLocation; + + /// No description provided for @map_locationUpdated. + /// + /// In en, this message translates to: + /// **'Location updated'** + String get map_locationUpdated; + + /// No description provided for @map_locationNotShared. + /// + /// In en, this message translates to: + /// **'{name} replied without a location'** + String map_locationNotShared(String name); + + /// No description provided for @map_locationRequestFailed. + /// + /// In en, this message translates to: + /// **'No reply from {name}'** + String map_locationRequestFailed(String name); + /// No description provided for @mapCache_zoomLevel. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 11561b05..77a7d5fe 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -6083,6 +6083,22 @@ class AppLocalizationsBg extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Обнови местоположението'; + + @override + String get map_locationUpdated => 'Местоположението е обновено'; + + @override + String map_locationNotShared(String name) { + return '$name отговори без местоположение'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Няма отговор от $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Мащаб $zoom'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index c6b5c63e..97bb05dc 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -6097,6 +6097,22 @@ class AppLocalizationsDe extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Standort aktualisieren'; + + @override + String get map_locationUpdated => 'Standort aktualisiert'; + + @override + String map_locationNotShared(String name) { + return '$name hat ohne Standort geantwortet'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Keine Antwort von $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 586a9b1c..fcbdda5a 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -5998,6 +5998,22 @@ class AppLocalizationsEn extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Update location'; + + @override + String get map_locationUpdated => 'Location updated'; + + @override + String map_locationNotShared(String name) { + return '$name replied without a location'; + } + + @override + String map_locationRequestFailed(String name) { + return 'No reply from $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 5a81f399..95cbe0b3 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -6087,6 +6087,22 @@ class AppLocalizationsEs extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Actualizar ubicación'; + + @override + String get map_locationUpdated => 'Ubicación actualizada'; + + @override + String map_locationNotShared(String name) { + return '$name respondió sin ubicación'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Sin respuesta de $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index e69000f7..1d9aa184 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -6110,6 +6110,22 @@ class AppLocalizationsFr extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Actualiser la position'; + + @override + String get map_locationUpdated => 'Position actualisée'; + + @override + String map_locationNotShared(String name) { + return '$name a répondu sans position'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Aucune réponse de $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 1e5a433e..d214bf44 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -6075,6 +6075,22 @@ class AppLocalizationsHu extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Hely frissítése'; + + @override + String get map_locationUpdated => 'Hely frissítve'; + + @override + String map_locationNotShared(String name) { + return '$name helyadat nélkül válaszolt'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Nincs válasz tőle: $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Nagyítás: $zoom'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index cf90297e..c86a6c9e 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -6093,6 +6093,22 @@ class AppLocalizationsIt extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Aggiorna posizione'; + + @override + String get map_locationUpdated => 'Posizione aggiornata'; + + @override + String map_locationNotShared(String name) { + return '$name ha risposto senza posizione'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Nessuna risposta da $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 57043f48..2fc11840 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -5799,6 +5799,22 @@ class AppLocalizationsJa extends AppLocalizations { return '$name、$type、$status'; } + @override + String get map_requestLocation => '位置情報を更新'; + + @override + String get map_locationUpdated => '位置情報を更新しました'; + + @override + String map_locationNotShared(String name) { + return '$name は位置情報なしで応答しました'; + } + + @override + String map_locationRequestFailed(String name) { + return '$name から応答がありません'; + } + @override String mapCache_zoomLevel(int zoom) { return 'ズーム $zoom'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index e1eb65df..b68ed368 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -5806,6 +5806,22 @@ class AppLocalizationsKo extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => '위치 업데이트'; + + @override + String get map_locationUpdated => '위치가 업데이트되었습니다'; + + @override + String map_locationNotShared(String name) { + return '$name이(가) 위치 없이 응답했습니다'; + } + + @override + String map_locationRequestFailed(String name) { + return '$name의 응답이 없습니다'; + } + @override String mapCache_zoomLevel(int zoom) { return '줌 $zoom'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 55c59595..6e8d5a27 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -6053,6 +6053,22 @@ class AppLocalizationsNl extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Locatie bijwerken'; + + @override + String get map_locationUpdated => 'Locatie bijgewerkt'; + + @override + String map_locationNotShared(String name) { + return '$name antwoordde zonder locatie'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Geen antwoord van $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index bbd9758b..376647e6 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -6117,6 +6117,22 @@ class AppLocalizationsPl extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Zaktualizuj lokalizację'; + + @override + String get map_locationUpdated => 'Lokalizacja zaktualizowana'; + + @override + String map_locationNotShared(String name) { + return '$name odpowiedział bez lokalizacji'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Brak odpowiedzi od $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index ee29d2b6..e1e839b9 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -6082,6 +6082,22 @@ class AppLocalizationsPt extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Atualizar localização'; + + @override + String get map_locationUpdated => 'Localização atualizada'; + + @override + String map_locationNotShared(String name) { + return '$name respondeu sem localização'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Sem resposta de $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index dec6ceee..af5cf4cd 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -6104,6 +6104,22 @@ class AppLocalizationsRu extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Обновить местоположение'; + + @override + String get map_locationUpdated => 'Местоположение обновлено'; + + @override + String map_locationNotShared(String name) { + return '$name ответил без местоположения'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Нет ответа от $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Масштаб $zoom'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index fee4b155..663775a1 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -6066,6 +6066,22 @@ class AppLocalizationsSk extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Aktualizovať polohu'; + + @override + String get map_locationUpdated => 'Poloha aktualizovaná'; + + @override + String map_locationNotShared(String name) { + return '$name odpovedal bez polohy'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Žiadna odpoveď od $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Priblíženie $zoom'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index e42cbf0a..5eceb5df 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -6069,6 +6069,22 @@ class AppLocalizationsSl extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Posodobi lokacijo'; + + @override + String get map_locationUpdated => 'Lokacija posodobljena'; + + @override + String map_locationNotShared(String name) { + return '$name je odgovoril brez lokacije'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Ni odgovora od $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Povečava $zoom'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 4ed1fd88..c507128d 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -6033,6 +6033,22 @@ class AppLocalizationsSv extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Uppdatera plats'; + + @override + String get map_locationUpdated => 'Platsen uppdaterad'; + + @override + String map_locationNotShared(String name) { + return '$name svarade utan plats'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Inget svar från $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Zoom $zoom'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 7fa20972..4647cb65 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -6107,6 +6107,22 @@ class AppLocalizationsUk extends AppLocalizations { return '$name, $type, $status'; } + @override + String get map_requestLocation => 'Оновити геопозицію'; + + @override + String get map_locationUpdated => 'Геопозицію оновлено'; + + @override + String map_locationNotShared(String name) { + return '$name відповів без геопозиції'; + } + + @override + String map_locationRequestFailed(String name) { + return 'Немає відповіді від $name'; + } + @override String mapCache_zoomLevel(int zoom) { return 'Масштаб $zoom'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 68b6ea28..df3779a0 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -5658,6 +5658,22 @@ class AppLocalizationsZh extends AppLocalizations { return '$name,$type,$status'; } + @override + String get map_requestLocation => '更新位置'; + + @override + String get map_locationUpdated => '位置已更新'; + + @override + String map_locationNotShared(String name) { + return '$name 回复中未包含位置'; + } + + @override + String map_locationRequestFailed(String name) { + return '$name 没有回复'; + } + @override String mapCache_zoomLevel(int zoom) { return '缩放 $zoom'; diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index d2804e84..629e3a8f 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -3202,6 +3202,10 @@ "map_youWithMarkers": "Jij en {count} markeringen", "map_sharedMarkerSemantics": "Gedeelde markering: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Locatie bijwerken", + "map_locationUpdated": "Locatie bijgewerkt", + "map_locationNotShared": "{name} antwoordde zonder locatie", + "map_locationRequestFailed": "Geen antwoord van {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index d4b46891..b78d70fd 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -3334,6 +3334,10 @@ "map_youWithMarkers": "Ty i znaczniki: {count}", "map_sharedMarkerSemantics": "Udostępniony znacznik: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Zaktualizuj lokalizację", + "map_locationUpdated": "Lokalizacja zaktualizowana", + "map_locationNotShared": "{name} odpowiedział bez lokalizacji", + "map_locationRequestFailed": "Brak odpowiedzi od {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 40590afb..c123ddba 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -3184,6 +3184,10 @@ "map_youWithMarkers": "Você e {count} marcadores", "map_sharedMarkerSemantics": "Marcador compartilhado: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Atualizar localização", + "map_locationUpdated": "Localização atualizada", + "map_locationNotShared": "{name} respondeu sem localização", + "map_locationRequestFailed": "Sem resposta de {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 2771a68c..cdf1b5fc 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -2598,6 +2598,10 @@ "map_youWithMarkers": "Вы и маркеров: {count}", "map_sharedMarkerSemantics": "Общий маркер: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Обновить местоположение", + "map_locationUpdated": "Местоположение обновлено", + "map_locationNotShared": "{name} ответил без местоположения", + "map_locationRequestFailed": "Нет ответа от {name}", "mapCache_zoomLevel": "Масштаб {zoom}", "mapCache_sizeBytes": "{size} Б", "mapCache_sizeKilobytes": "{size} КБ", diff --git a/lib/l10n/app_sk.arb b/lib/l10n/app_sk.arb index e8938a13..90a8c4d6 100644 --- a/lib/l10n/app_sk.arb +++ b/lib/l10n/app_sk.arb @@ -3302,6 +3302,10 @@ "map_youWithMarkers": "Vy a značky: {count}", "map_sharedMarkerSemantics": "Zdieľaná značka: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Aktualizovať polohu", + "map_locationUpdated": "Poloha aktualizovaná", + "map_locationNotShared": "{name} odpovedal bez polohy", + "map_locationRequestFailed": "Žiadna odpoveď od {name}", "mapCache_zoomLevel": "Priblíženie {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_sl.arb b/lib/l10n/app_sl.arb index 9148675c..5d9a18a2 100644 --- a/lib/l10n/app_sl.arb +++ b/lib/l10n/app_sl.arb @@ -3185,6 +3185,10 @@ "map_youWithMarkers": "Vi in oznak: {count}", "map_sharedMarkerSemantics": "Deljena oznaka: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Posodobi lokacijo", + "map_locationUpdated": "Lokacija posodobljena", + "map_locationNotShared": "{name} je odgovoril brez lokacije", + "map_locationRequestFailed": "Ni odgovora od {name}", "mapCache_zoomLevel": "Povečava {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_sv.arb b/lib/l10n/app_sv.arb index 9fd33f8f..0956dec1 100644 --- a/lib/l10n/app_sv.arb +++ b/lib/l10n/app_sv.arb @@ -3179,6 +3179,10 @@ "map_youWithMarkers": "Du och {count} markörer", "map_sharedMarkerSemantics": "Delad markör: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Uppdatera plats", + "map_locationUpdated": "Platsen uppdaterad", + "map_locationNotShared": "{name} svarade utan plats", + "map_locationRequestFailed": "Inget svar från {name}", "mapCache_zoomLevel": "Zoom {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index ce219889..a017fc1f 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -3281,6 +3281,10 @@ "map_youWithMarkers": "Ви та маркерів: {count}", "map_sharedMarkerSemantics": "Спільний маркер: {label}", "map_nodeMarkerSemantics": "{name}, {type}, {status}", + "map_requestLocation": "Оновити геопозицію", + "map_locationUpdated": "Геопозицію оновлено", + "map_locationNotShared": "{name} відповів без геопозиції", + "map_locationRequestFailed": "Немає відповіді від {name}", "mapCache_zoomLevel": "Масштаб {zoom}", "mapCache_sizeBytes": "{size} Б", "mapCache_sizeKilobytes": "{size} КБ", diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 51a8e2d3..0b627b1d 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3189,6 +3189,10 @@ "map_youWithMarkers": "你和 {count} 个标记", "map_sharedMarkerSemantics": "共享标记:{label}", "map_nodeMarkerSemantics": "{name},{type},{status}", + "map_requestLocation": "更新位置", + "map_locationUpdated": "位置已更新", + "map_locationNotShared": "{name} 回复中未包含位置", + "map_locationRequestFailed": "{name} 没有回复", "mapCache_zoomLevel": "缩放 {zoom}", "mapCache_sizeBytes": "{size} B", "mapCache_sizeKilobytes": "{size} KB", diff --git a/lib/models/contact.dart b/lib/models/contact.dart index 27a276ca..60442997 100644 --- a/lib/models/contact.dart +++ b/lib/models/contact.dart @@ -22,6 +22,12 @@ class Contact { final bool isActive; final Uint8List? rawPacket; + /// Set while [latitude]/[longitude]/[lastSeen] come from a telemetry reply + /// rather than an advert: the advert timestamp that fix superseded. A + /// radio refresh carrying that same advert keeps the fix; a newer advert + /// replaces it. + final DateTime? telemetryFixAdvertSeen; + Contact({ required this.publicKey, required this.name, @@ -39,6 +45,7 @@ class Contact { DateTime? lastMessageAt, this.isActive = true, this.rawPacket, + this.telemetryFixAdvertSeen, }) : lastMessageAt = lastMessageAt ?? lastSeen; /// Cached: it backs ==, hashCode and the per-frame contact lookups, and @@ -105,6 +112,8 @@ class Contact { DateTime? lastModified, bool? isActive, Uint8List? rawPacket, + DateTime? telemetryFixAdvertSeen, + bool clearTelemetryFix = false, }) { return Contact( publicKey: publicKey ?? this.publicKey, @@ -127,6 +136,9 @@ class Contact { lastModified: lastModified ?? this.lastModified, isActive: isActive ?? this.isActive, rawPacket: rawPacket ?? this.rawPacket, + telemetryFixAdvertSeen: clearTelemetryFix + ? null + : (telemetryFixAdvertSeen ?? this.telemetryFixAdvertSeen), ); } diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index 2c62f423..f80965d2 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -24,6 +24,7 @@ import '../services/app_settings_service.dart'; import '../services/path_history_service.dart'; import '../services/map_marker_service.dart'; import '../services/map_tile_cache_service.dart'; +import '../services/telemetry_location_request.dart'; import '../services/network_map/network_map_api_client.dart'; import '../services/ui_view_state_service.dart'; import '../storage/prefs_manager.dart'; @@ -104,6 +105,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { bool _showNodeLabels = true; double _zoom = 10.0; String? _selectedKey; + String? _locatingKey; LatLng? _selectedGuessPos; _Freshness _freshness = _Freshness.all; final TextEditingController _searchController = TextEditingController(); @@ -2494,6 +2496,33 @@ class _MapScreenState extends State with DisconnectNavigationMixin { crossAxisAlignment: WrapCrossAlignment.center, children: [ ..._selectedNodeActions(context, contact, connector), + // Repeaters and rooms only send GPS to logged-in admins. + if (contact.isActive && + (contact.type == advTypeChat || + contact.type == advTypeSensor)) + OutlinedButton.icon( + style: OutlinedButton.styleFrom( + foregroundColor: _overlayPrimaryTextColor, + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 8, + ), + minimumSize: const Size(0, 44), + ), + onPressed: _locatingKey == null + ? () => _requestNodeLocation(contact, connector) + : null, + icon: _locatingKey == contact.publicKeyHex + ? const SizedBox.square( + dimension: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.my_location, size: 18), + label: Text( + context.l10n.map_requestLocation, + style: const TextStyle(fontSize: 14), + ), + ), TextButton( style: TextButton.styleFrom( foregroundColor: MapPalette.selected, @@ -2519,6 +2548,36 @@ class _MapScreenState extends State with DisconnectNavigationMixin { ); } + /// Asks the node for telemetry; a GPS fix in the reply moves its marker. + Future _requestNodeLocation( + Contact contact, + MeshCoreConnector connector, + ) async { + setState(() => _locatingKey = contact.publicKeyHex); + final result = await requestTelemetryLocation(connector, contact); + if (!mounted) return; + setState(() => _locatingKey = null); + final l10n = context.l10n; + final message = switch (result) { + TelemetryLocationResult.located => l10n.map_locationUpdated, + TelemetryLocationResult.noLocation => l10n.map_locationNotShared( + contact.name, + ), + TelemetryLocationResult.failed => l10n.map_locationRequestFailed( + contact.name, + ), + }; + showDismissibleSnackBar(context, content: Text(message)); + final updated = connector.contacts + .where((c) => c.publicKeyHex == contact.publicKeyHex) + .firstOrNull; + if (result == TelemetryLocationResult.located && + updated != null && + updated.hasLocation) { + _mapController.move(LatLng(updated.latitude!, updated.longitude!), _zoom); + } + } + Widget _miniMeta(String label, String value) { return Column( mainAxisSize: MainAxisSize.min, @@ -2999,6 +3058,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { showDialog( context: context, builder: (dialogContext) => AlertDialog( + scrollable: true, title: Text( marker.label.isEmpty ? context.l10n.map_sharedPin : marker.label, ), diff --git a/lib/screens/telemetry_screen.dart b/lib/screens/telemetry_screen.dart index b6f085e8..f73e7040 100644 --- a/lib/screens/telemetry_screen.dart +++ b/lib/screens/telemetry_screen.dart @@ -12,6 +12,7 @@ import '../connector/meshcore_connector.dart'; import '../connector/meshcore_protocol.dart'; import '../services/app_settings_service.dart'; import '../services/repeater_command_service.dart'; +import '../services/telemetry_location_request.dart'; import '../utils/app_logger.dart'; import '../widgets/routing_sheet.dart'; import '../helpers/cayenne_lpp.dart'; @@ -208,6 +209,14 @@ class _TelemetryScreenState extends State { source: 'telemetry', ); } + final fix = telemetryGpsFix(parsedTelemetry); + if (fix != null && !widget.isSelf) { + context.read().updateContactLocationFromTelemetry( + widget.contact.publicKeyHex, + fix.latitude, + fix.longitude, + ); + } if (!mounted) return; final isAutoRefreshRequest = _activeTelemetryRequestIsAutoRefresh; setState(() { diff --git a/lib/services/telemetry_location_request.dart b/lib/services/telemetry_location_request.dart new file mode 100644 index 00000000..dec338e2 --- /dev/null +++ b/lib/services/telemetry_location_request.dart @@ -0,0 +1,127 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/meshcore_protocol.dart'; +import '../helpers/cayenne_lpp.dart'; +import '../models/contact.dart'; +import '../models/path_selection.dart'; +import '../utils/app_logger.dart'; + +enum TelemetryLocationResult { located, noLocation, failed } + +/// Returns the first valid GPS fix in parsed Cayenne LPP telemetry, or null. +({double latitude, double longitude})? telemetryGpsFix( + List> entries, +) { + for (final entry in entries) { + final values = entry['values']; + if (values is! Map) continue; + final gps = values['gps']; + if (gps is! Map) continue; + final lat = gps['latitude']; + final lon = gps['longitude']; + if (lat is! num || lon is! num) continue; + final latitude = lat.toDouble(); + final longitude = lon.toDouble(); + const double epsilon = 1e-6; + final valid = + (latitude.abs() > epsilon || longitude.abs() > epsilon) && + latitude >= -90.0 && + latitude <= 90.0 && + longitude >= -180.0 && + longitude <= 180.0; + if (valid) return (latitude: latitude, longitude: longitude); + } + return null; +} + +/// Asks [contact] for its telemetry and, when the reply carries a GPS fix, +/// stores it on the contact so the map moves the node right away. +Future requestTelemetryLocation( + MeshCoreConnector connector, + Contact contact, +) async { + final completer = Completer>?>(); + var awaitingSent = true; + int? tag; + Timer? timeout; + void finish(List>? parsed) { + if (completer.isCompleted) return; + timeout?.cancel(); + completer.complete(parsed); + } + + // Guards the wait for the radio's send ack; the ack's trip time replaces it. + timeout = Timer(const Duration(seconds: 10), () => finish(null)); + final isChat = contact.type == advTypeChat; + final subscription = connector.receivedFrames.listen((frame) { + if (frame.isEmpty || completer.isCompleted) return; + final reader = BufferReader(frame); + try { + final cmd = reader.readByte(); + if (cmd == respCodeSent && awaitingSent) { + awaitingSent = false; + reader.skipBytes(1); // reserved + tag = reader.readUInt32LE(); + final tripTime = reader.readUInt32LE(); + timeout?.cancel(); + timeout = Timer(Duration(milliseconds: tripTime), () => finish(null)); + } else if (cmd == respCodeErr && awaitingSent) { + awaitingSent = false; + finish(null); + } else if (cmd == pushCodeBinaryResponse) { + // Binary requests always answer here. A chat telemetry reply also + // lands here, tagged, when another request replaced it as the + // radio's pending request. + reader.skipBytes(1); // reserved + if (tag == null || reader.readUInt32LE() != tag) return; + finish(CayenneLpp.parseByChannel(reader.readRemainingBytes())); + } else if (cmd == pushCodeTelemetryResponse && isChat) { + reader.skipBytes(1); // reserved + final prefix = reader.readBytes(6); + if (!listEquals(contact.publicKey.sublist(0, 6), prefix)) return; + finish(CayenneLpp.parseByChannel(reader.readRemainingBytes())); + } + } catch (e) { + appLogger.error('Error parsing telemetry location frame: $e'); + } + }); + + PathSelection? selection; + try { + selection = await connector.preparePathForContactSend(contact); + await connector.sendFrame( + isChat + ? buildSendTelemetryReq(contact.publicKey) + : buildSendBinaryReq( + contact.publicKey, + payload: buildTelemetryBinaryPayload(), + ), + ); + } catch (e) { + appLogger.error('Telemetry location request failed: $e'); + finish(null); + } + + final parsed = await completer.future; + await subscription.cancel(); + if (selection != null) { + connector.recordRepeaterPathResult( + contact, + selection, + parsed != null, + null, + ); + } + if (parsed == null) return TelemetryLocationResult.failed; + final fix = telemetryGpsFix(parsed); + if (fix == null) return TelemetryLocationResult.noLocation; + connector.updateContactLocationFromTelemetry( + contact.publicKeyHex, + fix.latitude, + fix.longitude, + ); + return TelemetryLocationResult.located; +} diff --git a/lib/storage/contact_store.dart b/lib/storage/contact_store.dart index e80ee952..0ca2b489 100644 --- a/lib/storage/contact_store.dart +++ b/lib/storage/contact_store.dart @@ -92,6 +92,8 @@ class ContactStore { 'rawPacket': contact.rawPacket != null ? base64Encode(contact.rawPacket!) : null, + 'telemetryFixAdvertSeen': + contact.telemetryFixAdvertSeen?.millisecondsSinceEpoch, }; } @@ -99,6 +101,7 @@ class ContactStore { final lastSeenMs = json['lastSeen'] as int? ?? 0; final lastMessageMs = json['lastMessageAt'] as int?; final lastModifiedMs = json['lastModified'] as int?; + final telemetryFixMs = json['telemetryFixAdvertSeen'] as int?; final rawPathLength = json['pathLength'] as int? ?? -1; final rawPath = json['path'] != null @@ -157,6 +160,9 @@ class ContactStore { rawPacket: json['rawPacket'] != null ? Uint8List.fromList(base64Decode(json['rawPacket'] as String)) : null, + telemetryFixAdvertSeen: telemetryFixMs == null + ? null + : DateTime.fromMillisecondsSinceEpoch(telemetryFixMs), ); } } diff --git a/test/connector/telemetry_location_test.dart b/test/connector/telemetry_location_test.dart new file mode 100644 index 00000000..0ecbf07a --- /dev/null +++ b/test/connector/telemetry_location_test.dart @@ -0,0 +1,110 @@ +import 'dart:typed_data'; + +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/services/telemetry_location_request.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Uint8List _contactFrame( + Uint8List key, { + required int advertTimestamp, + required double lat, + required double lon, +}) { + final data = ByteData(1 + 32 + 3 + 64 + 32 + 4 + 12); + final bytes = data.buffer.asUint8List(); + bytes[0] = respCodeContact; + bytes.setRange(1, 33, key); + bytes[33] = advTypeChat; + bytes[35] = 0xFF; // path unknown + bytes.setRange(100, 103, 'Bob'.codeUnits); + data.setUint32(132, advertTimestamp, Endian.little); + data.setInt32(136, (lat * 1e6).round(), Endian.little); + data.setInt32(140, (lon * 1e6).round(), Endian.little); + return bytes; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + final key = Uint8List.fromList(List.generate(32, (i) => i + 1)); + + test('telemetry fix survives a refresh of the same advert', () { + final connector = MeshCoreConnector(); + final frame = _contactFrame( + key, + advertTimestamp: 1700000000, + lat: 10, + lon: 20, + ); + connector.handleFrameForTest(frame); + final keyHex = connector.contacts.single.publicKeyHex; + + connector.updateContactLocationFromTelemetry(keyHex, 11.5, 21.5); + final fixed = connector.contacts.single; + expect(fixed.latitude, 11.5); + expect(fixed.longitude, 21.5); + expect(fixed.lastSeen.isAfter(DateTime(2024)), isTrue); + + connector.handleFrameForTest(frame); + final refreshed = connector.contacts.single; + expect(refreshed.latitude, 11.5); + expect(refreshed.longitude, 21.5); + expect(refreshed.lastSeen, fixed.lastSeen); + }); + + test('a newer advert replaces the telemetry fix', () { + final connector = MeshCoreConnector(); + connector.handleFrameForTest( + _contactFrame(key, advertTimestamp: 1700000000, lat: 10, lon: 20), + ); + final keyHex = connector.contacts.single.publicKeyHex; + connector.updateContactLocationFromTelemetry(keyHex, 11.5, 21.5); + + connector.handleFrameForTest( + _contactFrame(key, advertTimestamp: 1700000100, lat: 12, lon: 22), + ); + final contact = connector.contacts.single; + expect(contact.latitude, 12); + expect(contact.longitude, 22); + expect(contact.telemetryFixAdvertSeen, isNull); + }); + + test('telemetryGpsFix skips missing and null-island fixes', () { + expect(telemetryGpsFix([]), isNull); + expect( + telemetryGpsFix([ + { + 'channel': 1, + 'values': { + 'gps': {'latitude': 0.0, 'longitude': 0.0, 'altitude': 0.0}, + }, + }, + ]), + isNull, + ); + expect( + telemetryGpsFix([ + { + 'channel': 1, + 'values': {'voltage': 4.1}, + }, + { + 'channel': 2, + 'values': { + 'gps': {'latitude': 45.5, 'longitude': -122.6, 'altitude': 10.0}, + }, + }, + ]), + (latitude: 45.5, longitude: -122.6), + ); + }); +}