diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 8e59a81c..c12dca7c 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -812,7 +812,8 @@ 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. + /// [lastSeen] is left alone: it is the node's advert timestamp, which path + /// and flag writes send back to the radio. void updateContactLocationFromTelemetry( String contactKeyHex, double latitude, @@ -820,13 +821,10 @@ class MeshCoreConnector extends ChangeNotifier { ) { final index = _contacts.indexWhere((c) => c.publicKeyHex == contactKeyHex); if (index < 0) return; - final existing = _contacts[index]; - final updated = existing.copyWith( + final updated = _contacts[index].copyWith( latitude: latitude, longitude: longitude, - lastSeen: DateTime.now(), - telemetryFixAdvertSeen: - existing.telemetryFixAdvertSeen ?? existing.lastSeen, + telemetryFixAt: DateTime.now(), ); if (!updated.hasLocation) return; _contacts[index] = updated; @@ -834,10 +832,24 @@ class MeshCoreConnector extends ChangeNotifier { unawaited(_persistContacts()); } + /// Carries [previous]'s telemetry fix onto [incoming], a record the radio + /// just returned, while it still holds the advert that fix superseded. A + /// newer advert (by the node's own clock) wins. + Contact? _withTelemetryFix(Contact previous, Contact incoming) { + final fixAt = previous.telemetryFixAt; + if (fixAt == null || incoming.lastSeen.isAfter(previous.lastSeen)) { + return null; + } + return incoming.copyWith( + latitude: previous.latitude, + longitude: previous.longitude, + telemetryFixAt: fixAt, + ); + } + /// 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. + /// one we already hold, keeping the user's path choice and any telemetry + /// fix still newer than the radio's advert. Contact _mergeRefreshedContact( Contact existing, Contact incoming, { @@ -847,21 +859,7 @@ class MeshCoreConnector extends ChangeNotifier { 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( + final base = incoming.copyWith( lastMessageAt: mergedLastMessageAt, pathOverride: existing.pathOverride, // Preserve user's path choice pathOverrideBytes: existing.pathOverrideBytes, @@ -873,6 +871,19 @@ class MeshCoreConnector extends ChangeNotifier { : incoming.longitude, clearTelemetryFix: true, ); + return _withTelemetryFix(existing, base) ?? base; + } + + /// Telemetry fixes held across a full contact sync, which clears the list + /// before the radio resends it. + final Map _telemetryFixesDuringSync = {}; + + void _stashTelemetryFixes() { + for (final c in _contacts) { + if (c.telemetryFixAt != null) { + _telemetryFixesDuringSync[c.publicKeyHex] = c; + } + } } String _batteryChemistryForDevice() { @@ -4291,6 +4302,7 @@ class MeshCoreConnector extends ChangeNotifier { _contactSyncUsesSinceFilter = since != null; if (!preserveExisting) { _hasLoadedContacts = false; + _stashTelemetryFixes(); _contacts.clear(); } _armContactSyncWatchdog(); @@ -6086,6 +6098,7 @@ class MeshCoreConnector extends ChangeNotifier { case respCodeContactsStart: debugPrint('Got CONTACTS_START'); if (!_preserveContactsOnRefresh) { + _stashTelemetryFixes(); _contacts.clear(); } _isLoadingContacts = true; @@ -6161,6 +6174,7 @@ class MeshCoreConnector extends ChangeNotifier { } _hasLoadedContacts = true; _preserveContactsOnRefresh = false; + _telemetryFixesDuringSync.clear(); _contactSyncUsesSinceFilter = false; unawaited(updateKnownDiscovered()); notifyListeners(); @@ -6945,7 +6959,12 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'Connector', ); } else { - _contacts.add(contact); + // A full sync cleared the list; restore a telemetry fix it held. + final stashed = _telemetryFixesDuringSync.remove(contact.publicKeyHex); + _contacts.add( + (stashed == null ? null : _withTelemetryFix(stashed, contact)) ?? + contact, + ); appLogger.info( 'Added new contact ${contact.name}: pathLen=${contact.pathLength}', tag: 'Connector', diff --git a/lib/models/contact.dart b/lib/models/contact.dart index 60442997..f37ddf60 100644 --- a/lib/models/contact.dart +++ b/lib/models/contact.dart @@ -22,11 +22,11 @@ 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; + /// When [latitude]/[longitude] came from a telemetry reply rather than the + /// advert, the phone time of that reply. [lastSeen] stays the node's advert + /// timestamp (it is written back to the radio), so a radio refresh carrying + /// the same advert keeps the fix and a newer advert replaces it. + final DateTime? telemetryFixAt; Contact({ required this.publicKey, @@ -45,7 +45,7 @@ class Contact { DateTime? lastMessageAt, this.isActive = true, this.rawPacket, - this.telemetryFixAdvertSeen, + this.telemetryFixAt, }) : lastMessageAt = lastMessageAt ?? lastSeen; /// Cached: it backs ==, hashCode and the per-frame contact lookups, and @@ -92,6 +92,12 @@ class Contact { lon <= 180.0; } + /// The latest time we heard from the node: its advert or a telemetry fix. + DateTime get lastHeard { + final fixAt = telemetryFixAt; + return fixAt != null && fixAt.isAfter(lastSeen) ? fixAt : lastSeen; + } + bool get isFavorite => (flags & contactFlagFavorite) != 0; Contact copyWith({ @@ -112,7 +118,7 @@ class Contact { DateTime? lastModified, bool? isActive, Uint8List? rawPacket, - DateTime? telemetryFixAdvertSeen, + DateTime? telemetryFixAt, bool clearTelemetryFix = false, }) { return Contact( @@ -136,9 +142,9 @@ class Contact { lastModified: lastModified ?? this.lastModified, isActive: isActive ?? this.isActive, rawPacket: rawPacket ?? this.rawPacket, - telemetryFixAdvertSeen: clearTelemetryFix + telemetryFixAt: clearTelemetryFix ? null - : (telemetryFixAdvertSeen ?? this.telemetryFixAdvertSeen), + : (telemetryFixAt ?? this.telemetryFixAt), ); } diff --git a/lib/screens/map_screen.dart b/lib/screens/map_screen.dart index f80965d2..335bf4d1 100644 --- a/lib/screens/map_screen.dart +++ b/lib/screens/map_screen.dart @@ -198,7 +198,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { : MapPalette.markerShadow.withValues(alpha: 0.18); _NodeAge _ageOf(Contact contact) { - final d = DateTime.now().difference(contact.lastSeen); + final d = DateTime.now().difference(contact.lastHeard); if (d.inMinutes <= 60) return _NodeAge.online; if (d.inHours <= 24) return _NodeAge.recent; return _NodeAge.stale; @@ -543,7 +543,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { final filteredByTime = settings.mapTimeFilterHours == 0 ? contacts : contacts.where((c) { - final hoursSinceLastSeen = now.difference(c.lastSeen).inHours; + final hoursSinceLastSeen = now.difference(c.lastHeard).inHours; return hoursSinceLastSeen <= settings.mapTimeFilterHours; }).toList(); @@ -2121,7 +2121,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { if (a.hasLocation != b.hasLocation) { return a.hasLocation ? -1 : 1; } - return b.lastSeen.compareTo(a.lastSeen); + return b.lastHeard.compareTo(a.lastHeard); }); final results = matches.take(8).toList(); return Container( @@ -2469,7 +2469,7 @@ class _MapScreenState extends State with DisconnectNavigationMixin { children: [ _miniMeta( context.l10n.map_lastSeen, - formatNodeLastSeen(context.l10n, contact.lastSeen), + formatNodeLastSeen(context.l10n, contact.lastHeard), ), _miniMeta( context.l10n.map_path, @@ -4054,7 +4054,7 @@ int _mapContactSignature(Contact contact) { _bytesSignature(contact.pathOverrideBytes), contact.latitude, contact.longitude, - contact.lastSeen.millisecondsSinceEpoch, + contact.lastHeard.millisecondsSinceEpoch, contact.lastMessageAt.millisecondsSinceEpoch, contact.isActive, ); diff --git a/lib/storage/contact_store.dart b/lib/storage/contact_store.dart index 0ca2b489..3fc45187 100644 --- a/lib/storage/contact_store.dart +++ b/lib/storage/contact_store.dart @@ -92,8 +92,7 @@ class ContactStore { 'rawPacket': contact.rawPacket != null ? base64Encode(contact.rawPacket!) : null, - 'telemetryFixAdvertSeen': - contact.telemetryFixAdvertSeen?.millisecondsSinceEpoch, + 'telemetryFixAt': contact.telemetryFixAt?.millisecondsSinceEpoch, }; } @@ -101,7 +100,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 telemetryFixMs = json['telemetryFixAt'] as int?; final rawPathLength = json['pathLength'] as int? ?? -1; final rawPath = json['path'] != null @@ -160,7 +159,7 @@ class ContactStore { rawPacket: json['rawPacket'] != null ? Uint8List.fromList(base64Decode(json['rawPacket'] as String)) : null, - telemetryFixAdvertSeen: telemetryFixMs == null + telemetryFixAt: telemetryFixMs == null ? null : DateTime.fromMillisecondsSinceEpoch(telemetryFixMs), ); diff --git a/lib/widgets/contact_visuals.dart b/lib/widgets/contact_visuals.dart index ace35429..64117921 100644 --- a/lib/widgets/contact_visuals.dart +++ b/lib/widgets/contact_visuals.dart @@ -41,12 +41,11 @@ IconData? contactTypeIcon(int type) { } /// The most recent activity for [contact]: for chat nodes this includes the -/// last message, for other node types only the last advert. +/// last message, for other node types only the last advert or telemetry fix. DateTime resolveContactLastSeen(Contact contact) { - if (contact.type != advTypeChat) return contact.lastSeen; - return contact.lastMessageAt.isAfter(contact.lastSeen) - ? contact.lastMessageAt - : contact.lastSeen; + final heard = contact.lastHeard; + if (contact.type != advTypeChat) return heard; + return contact.lastMessageAt.isAfter(heard) ? contact.lastMessageAt : heard; } /// Short relative "last seen" label ("now", "5 mins ago", "2 days ago"). diff --git a/lib/widgets/node_info_sheet.dart b/lib/widgets/node_info_sheet.dart index 1e3bb073..3d10e0ec 100644 --- a/lib/widgets/node_info_sheet.dart +++ b/lib/widgets/node_info_sheet.dart @@ -262,7 +262,7 @@ void showNodeInfoSheet( ), NodeInfoRow( label: l10n.map_lastSeen, - value: formatNodeLastSeen(l10n, contact.lastSeen), + value: formatNodeLastSeen(l10n, contact.lastHeard), ), NodeInfoRow( label: l10n.map_publicKey, diff --git a/test/connector/telemetry_location_test.dart b/test/connector/telemetry_location_test.dart index 0ecbf07a..2db93a0d 100644 --- a/test/connector/telemetry_location_test.dart +++ b/test/connector/telemetry_location_test.dart @@ -52,13 +52,43 @@ void main() { final fixed = connector.contacts.single; expect(fixed.latitude, 11.5); expect(fixed.longitude, 21.5); - expect(fixed.lastSeen.isAfter(DateTime(2024)), isTrue); + // lastSeen stays the advert time the radio holds (path and flag writes + // send it back); the fix only moves lastHeard. + final advertTime = DateTime.fromMillisecondsSinceEpoch(1700000000 * 1000); + expect(fixed.lastSeen, advertTime); + expect(fixed.lastHeard.isAfter(advertTime), isTrue); connector.handleFrameForTest(frame); final refreshed = connector.contacts.single; expect(refreshed.latitude, 11.5); expect(refreshed.longitude, 21.5); - expect(refreshed.lastSeen, fixed.lastSeen); + expect(refreshed.lastSeen, advertTime); + expect(refreshed.telemetryFixAt, fixed.telemetryFixAt); + }); + + test('telemetry fix survives a full contact sync', () { + 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); + + // A full sync clears the list on CONTACTS_START and the radio resends + // the same advert record. + connector.handleFrameForTest([respCodeContactsStart]); + expect(connector.contacts, isEmpty); + connector.handleFrameForTest(frame); + connector.handleFrameForTest([respCodeEndOfContacts]); + + final contact = connector.contacts.single; + expect(contact.latitude, 11.5); + expect(contact.longitude, 21.5); + expect(contact.telemetryFixAt, isNotNull); }); test('a newer advert replaces the telemetry fix', () { @@ -75,7 +105,7 @@ void main() { final contact = connector.contacts.single; expect(contact.latitude, 12); expect(contact.longitude, 22); - expect(contact.telemetryFixAdvertSeen, isNull); + expect(contact.telemetryFixAt, isNull); }); test('telemetryGpsFix skips missing and null-island fixes', () {