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.
This commit is contained in:
zjs81 committed 2026-10-25 11:10:27 -07:00
1 parent d2eff6eb78
commit f0144ca959
44 files changed
+780 -19

No files matched your search

+70 -19
View File
@@ -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}',
+4
View File
@@ -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",
+4
View File
@@ -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",
+6
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -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",
+24
View File
@@ -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:
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+16
View File
@@ -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';
+4
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -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} КБ",
+4
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -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",
+4
View File
@@ -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} КБ",
+4
View File
@@ -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",
+12
View File
@@ -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),
);
}
+60
View File
@@ -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<MapScreen> 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<MapScreen> 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<MapScreen> with DisconnectNavigationMixin {
);
}
/// Asks the node for telemetry; a GPS fix in the reply moves its marker.
Future<void> _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<MapScreen> with DisconnectNavigationMixin {
showDialog(
context: context,
builder: (dialogContext) => AlertDialog(
scrollable: true,
title: Text(
marker.label.isEmpty ? context.l10n.map_sharedPin : marker.label,
),
+9
View File
@@ -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<TelemetryScreen> {
source: 'telemetry',
);
}
final fix = telemetryGpsFix(parsedTelemetry);
if (fix != null && !widget.isSelf) {
context.read<MeshCoreConnector>().updateContactLocationFromTelemetry(
widget.contact.publicKeyHex,
fix.latitude,
fix.longitude,
);
}
if (!mounted) return;
final isAutoRefreshRequest = _activeTelemetryRequestIsAutoRefresh;
setState(() {
@@ -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<Map<String, dynamic>> 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<TelemetryLocationResult> requestTelemetryLocation(
MeshCoreConnector connector,
Contact contact,
) async {
final completer = Completer<List<Map<String, dynamic>>?>();
var awaitingSent = true;
int? tag;
Timer? timeout;
void finish(List<Map<String, dynamic>>? 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;
}
+6
View File
@@ -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),
);
}
}
+110
View File
@@ -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<int>.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),
);
});
}