From 79f624c74343855f20ac1f2899e1ff5e4f123914 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:14:32 -0700 Subject: [PATCH 1/2] Ignore impossible hops in path map resolution Reject repeater matches and peer inferences whose distance from the previous plausible hop anchor exceeds the per-hop LoRa range budget (250 km scaled by consecutive unresolved hops). Without a known self location, select the anchor chain that explains the most local hops so a single distant prefix collision does not poison resolution for the remaining hops. Apply the same hop-order resolution and anchor-bounded peer inference in PathTraceMapScreen. --- lib/helpers/path_hop_resolver.dart | 262 ++++++++-- lib/screens/path_trace_map.dart | 480 ++++++++++++------ test/helpers/path_hop_resolver_test.dart | 257 +++++++++- .../channel_message_path_map_test.dart | 292 +++++++++++ test/screens/path_trace_test.dart | 190 ++++++- 5 files changed, 1292 insertions(+), 189 deletions(-) create mode 100644 test/screens/channel_message_path_map_test.dart diff --git a/lib/helpers/path_hop_resolver.dart b/lib/helpers/path_hop_resolver.dart index a6f2c018..af39983d 100644 --- a/lib/helpers/path_hop_resolver.dart +++ b/lib/helpers/path_hop_resolver.dart @@ -1,3 +1,5 @@ +import 'dart:typed_data'; + import 'package:latlong2/latlong.dart'; import '../connector/meshcore_protocol.dart'; @@ -7,59 +9,261 @@ import '../models/contact.dart'; class PathHopResolver { const PathHopResolver._(); + /// Maximum plausible single-hop LoRa RF link distance in meters (250 km). + /// Accommodates long-range line-of-sight mountain-top hops while rejecting + /// multi-hundred/multi-thousand-km prefix collisions. + static const double maxSingleHopDistanceMeters = 250000.0; + static List resolve({ required List pathBytes, required List contacts, LatLng? endpoint, bool resolveFromEnd = false, int pathHashByteWidth = 1, + double maxHopDistanceMeters = maxSingleHopDistanceMeters, }) { final width = pathHashByteWidth.clamp(1, 3).toInt(); + final hops = PathHelper.splitPathBytes(pathBytes, width); + return resolveHops( + hops: hops, + contacts: contacts, + endpoint: endpoint, + resolveFromEnd: resolveFromEnd, + maxHopDistanceMeters: maxHopDistanceMeters, + ); + } + + static List resolveHops({ + required List hops, + required List contacts, + LatLng? endpoint, + bool resolveFromEnd = false, + double maxHopDistanceMeters = maxSingleHopDistanceMeters, + bool Function(Contact)? contactFilter, + }) { + if (hops.isEmpty) return const []; + + final widths = { + for (final hop in hops) + if (hop.isNotEmpty) hop.length, + }; final candidatesByPrefix = >{}; for (final contact in contacts) { - if (contact.publicKey.length < width) continue; - if (contact.type != advTypeRepeater && contact.type != advTypeRoom) { - continue; + final include = + contactFilter?.call(contact) ?? + (contact.type == advTypeRepeater || contact.type == advTypeRoom); + if (!include) continue; + for (final width in widths) { + if (contact.publicKey.length < width) continue; + final prefix = PathHelper.formatHopHex( + contact.publicKey.sublist(0, width), + ); + candidatesByPrefix.putIfAbsent(prefix, () => []).add(contact); } - final prefix = PathHelper.formatHopHex( - contact.publicKey.sublist(0, width), - ); - candidatesByPrefix.putIfAbsent(prefix, () => []).add(contact); } for (final candidates in candidatesByPrefix.values) { candidates.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); } - final hops = PathHelper.splitPathBytes(pathBytes, width); - final resolved = List.filled(hops.length, null); + final hopCount = hops.length; + final resolved = List.filled(hopCount, null); final indexes = resolveFromEnd - ? List.generate(hops.length, (i) => hops.length - 1 - i) - : List.generate(hops.length, (i) => i); + ? List.generate(hopCount, (i) => hopCount - 1 - i) + : List.generate(hopCount, (i) => i); + final stepPrefixes = [ + for (final index in indexes) PathHelper.formatHopHex(hops[index]), + ]; final distance = Distance(); - var previousPosition = endpoint; - for (final index in indexes) { - final candidates = - candidatesByPrefix[PathHelper.formatHopHex(hops[index])]; - if (candidates == null || candidates.isEmpty) continue; + (Contact, double)? pickNearestLocated( + String prefix, + Set used, + LatLng anchor, + double maxDistanceMeters, + ) { + final candidates = candidatesByPrefix[prefix]; + if (candidates == null || candidates.isEmpty) return null; + Contact? best; + double? bestDistance; + for (final candidate in candidates) { + if (used.contains(candidate)) continue; + final position = _positionOf(candidate); + if (position == null) continue; + final d = distance(anchor, position); + if (d <= maxDistanceMeters && + (bestDistance == null || d < bestDistance)) { + bestDistance = d; + best = candidate; + } + } + if (best == null || bestDistance == null) return null; + return (best, bestDistance); + } - var bestIndex = 0; - if (previousPosition != null && candidates.length > 1) { - double? nearestDistance; - for (var i = 0; i < candidates.length; i++) { - final position = _positionOf(candidates[i]); - if (position == null) continue; - final candidateDistance = distance(previousPosition, position); - if (nearestDistance == null || candidateDistance < nearestDistance) { - nearestDistance = candidateDistance; - bestIndex = i; + Contact? pickFirstUnlocated(String prefix, Set used) { + final candidates = candidatesByPrefix[prefix]; + if (candidates == null || candidates.isEmpty) return null; + for (final candidate in candidates) { + if (used.contains(candidate)) continue; + if (_positionOf(candidate) == null) return candidate; + } + return null; + } + + Contact? pickFirstAny(String prefix, Set used) { + final candidates = candidatesByPrefix[prefix]; + if (candidates == null || candidates.isEmpty) return null; + for (final candidate in candidates) { + if (!used.contains(candidate)) return candidate; + } + return null; + } + + final used = Set.identity(); + + if (endpoint != null) { + var previousPosition = endpoint; + var lastAnchorStep = -1; + for (var step = 0; step < hopCount; step++) { + final prefix = stepPrefixes[step]; + final hopGap = step - lastAnchorStep; + final maxAllowed = hopGap * maxHopDistanceMeters; + final match = pickNearestLocated( + prefix, + used, + previousPosition, + maxAllowed, + ); + if (match != null) { + used.add(match.$1); + resolved[indexes[step]] = match.$1; + previousPosition = _positionOf(match.$1)!; + lastAnchorStep = step; + } else { + final unlocated = pickFirstUnlocated(prefix, used); + if (unlocated != null) { + used.add(unlocated); + resolved[indexes[step]] = unlocated; } } } + return resolved; + } - final contact = candidates.removeAt(bestIndex); - resolved[index] = contact; - previousPosition = _positionOf(contact) ?? previousPosition; + // Without a known endpoint, find the located anchor whose plausible chain + // explains the most located hops so a single distant prefix collision does + // not poison the rest of the path. + var hasAnyLocated = false; + for (final prefix in stepPrefixes) { + final candidates = candidatesByPrefix[prefix]; + if (candidates != null && candidates.any((c) => _positionOf(c) != null)) { + hasAnyLocated = true; + break; + } + } + + if (!hasAnyLocated) { + for (var step = 0; step < hopCount; step++) { + final contact = pickFirstAny(stepPrefixes[step], used); + if (contact != null) { + used.add(contact); + resolved[indexes[step]] = contact; + } + } + return resolved; + } + + List? bestRun; + var bestLocatedCount = 0; + var bestTotalDistance = double.infinity; + var bestLastSeenSum = -1; + + for (var anchorStep = 0; anchorStep < hopCount; anchorStep++) { + final candidates = candidatesByPrefix[stepPrefixes[anchorStep]]; + if (candidates == null) continue; + for (final anchorCandidate in candidates) { + final anchorPos = _positionOf(anchorCandidate); + if (anchorPos == null) continue; + + final run = List.filled(hopCount, null); + final runUsed = Set.identity()..add(anchorCandidate); + run[anchorStep] = anchorCandidate; + var locatedCount = 1; + var totalDistance = 0.0; + var lastSeenSum = anchorCandidate.lastSeen.millisecondsSinceEpoch; + + var prevPos = anchorPos; + var lastAnchor = anchorStep; + for (var step = anchorStep + 1; step < hopCount; step++) { + final maxAllowed = (step - lastAnchor) * maxHopDistanceMeters; + final match = pickNearestLocated( + stepPrefixes[step], + runUsed, + prevPos, + maxAllowed, + ); + if (match == null) continue; + run[step] = match.$1; + runUsed.add(match.$1); + prevPos = _positionOf(match.$1)!; + lastAnchor = step; + locatedCount++; + totalDistance += match.$2; + lastSeenSum += match.$1.lastSeen.millisecondsSinceEpoch; + } + + prevPos = anchorPos; + lastAnchor = anchorStep; + for (var step = anchorStep - 1; step >= 0; step--) { + final maxAllowed = (lastAnchor - step) * maxHopDistanceMeters; + final match = pickNearestLocated( + stepPrefixes[step], + runUsed, + prevPos, + maxAllowed, + ); + if (match == null) continue; + run[step] = match.$1; + runUsed.add(match.$1); + prevPos = _positionOf(match.$1)!; + lastAnchor = step; + locatedCount++; + totalDistance += match.$2; + lastSeenSum += match.$1.lastSeen.millisecondsSinceEpoch; + } + + final isBetter = + locatedCount > bestLocatedCount || + (locatedCount == bestLocatedCount && + totalDistance < bestTotalDistance - 1e-6) || + (locatedCount == bestLocatedCount && + (totalDistance - bestTotalDistance).abs() <= 1e-6 && + lastSeenSum > bestLastSeenSum); + if (isBetter) { + bestRun = run; + bestLocatedCount = locatedCount; + bestTotalDistance = totalDistance; + bestLastSeenSum = lastSeenSum; + } + } + } + + if (bestRun != null) { + for (var step = 0; step < hopCount; step++) { + final contact = bestRun[step]; + if (contact != null) { + used.add(contact); + resolved[indexes[step]] = contact; + } + } + for (var step = 0; step < hopCount; step++) { + if (bestRun[step] != null) continue; + final unlocated = pickFirstUnlocated(stepPrefixes[step], used); + if (unlocated != null) { + used.add(unlocated); + resolved[indexes[step]] = unlocated; + } + } } return resolved; diff --git a/lib/screens/path_trace_map.dart b/lib/screens/path_trace_map.dart index 5e5309ae..63d6d59c 100644 --- a/lib/screens/path_trace_map.dart +++ b/lib/screens/path_trace_map.dart @@ -8,6 +8,7 @@ import 'package:latlong2/latlong.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/connector/meshcore_protocol.dart'; import 'package:meshcore_open/helpers/path_helper.dart'; +import 'package:meshcore_open/helpers/path_hop_resolver.dart'; import 'package:meshcore_open/l10n/l10n.dart'; import 'package:meshcore_open/models/app_settings.dart'; import 'package:meshcore_open/models/contact.dart'; @@ -95,8 +96,6 @@ class _PathTraceMapScreenState extends State static const double _labelZoomThreshold = kPathMapLabelZoomThreshold; // Used when the radio never acknowledges the trace request. static const Duration _sendAckTimeout = Duration(seconds: 15); - //miles to meters conversion for filtering out repeaters that are too far from the last known GPS hop to be a likely match, to avoid false matches that throw off the inferred positions of other hops in the path - static const double _maxRepeaterMatchDistanceMeters = 40 * 1609.344; final MapController _mapController = MapController(); StreamSubscription? _frameSubscription; @@ -143,9 +142,10 @@ class _PathTraceMapScreenState extends State bool _animationEnabled = true; bool _followPacket = false; - // Hop-prefix -> contact lookups, invalidated when the contact list changes. - final Map _hopContactCache = {}; - int? _hopContactCacheSignature; + // Resolved hop contacts and inferred positions per display path id, used by + // combined markers and the generic hop list. + final Map contacts, List inferred})> + _resolvedDisplayPaths = {}; String _formatPathPrefixes(Uint8List pathBytes, [int? hashByteWidth]) { return PathHelper.splitPathBytes( @@ -584,78 +584,40 @@ class _PathTraceMapScreenState extends State .map((snr) => snr.toSigned(8).toDouble() / 4) .toList(); - Map pathContacts = {}; - Contact lastContact = Contact( - path: Uint8List(0), - pathLength: 0, - publicKey: connector.selfPublicKey ?? Uint8List(0), - name: context.l10n.pathTrace_you, - type: advTypeChat, - latitude: connector.selfLatitude, - longitude: connector.selfLongitude, - lastSeen: DateTime.now(), + final selfPoint = plausibleSelfPoint(connector); + final outboundHops = _outboundHops(pathData); + final candidateContacts = _mergeTraceContacts( + widget.pathContacts, + connector.allContactsUnfiltered, ); - if (widget.pathContacts != null) { - final hopWidth = width.clamp(1, pubKeySize).toInt(); - pathContacts = { - for (var c in widget.pathContacts!) - if (c.publicKey.length >= hopWidth) - _hopKey(Uint8List.fromList(c.publicKey.sublist(0, hopWidth))): c, - }; - } else { - final contacts = connector.allContactsUnfiltered; - contacts.where((c) => c.type != advTypeChat).forEach((repeater) { - if (lastContact.latitude != null && - lastContact.longitude != null && - repeater.hasLocation && - lastContact.hasLocation && - Distance().distance( - LatLng(lastContact.latitude!, lastContact.longitude!), - LatLng(repeater.latitude!, repeater.longitude!), - ) > - _maxRepeaterMatchDistanceMeters) { - return; //skip reapeaters that are far away from the last one with known GPS, to avoid false matches - } - for (final repeaterData in pathData) { - final hopWidth = repeaterData.length; - if (repeater.publicKey.length < hopWidth) continue; - if (listEquals( - repeater.publicKey.sublist(0, hopWidth), - repeaterData, - )) { - pathContacts[_hopKey(repeaterData)] = repeater; - lastContact = repeater; - } - } - }); + final resolvedOutbound = PathHopResolver.resolveHops( + hops: outboundHops, + contacts: candidateContacts, + endpoint: selfPoint, + contactFilter: (c) => c.type != advTypeChat, + ); + final Map pathContacts = {}; + for (var i = 0; i < outboundHops.length; i++) { + final contact = resolvedOutbound[i]; + if (contact != null) { + pathContacts[_hopKey(outboundHops[i])] = contact; + } } // For hops with no GPS contact, infer position from other contacts - // with known GPS that share the same last-hop byte. + // with known GPS that share the same last-hop byte, bounded by the + // plausible hop distance from neighboring anchors. + final inferredOutbound = _inferHopPositions( + hops: outboundHops, + resolvedContacts: resolvedOutbound, + selfPoint: selfPoint, + peerContacts: connector.contacts, + ); final Map inferredPositions = {}; - for (final hop in pathData) { - final hopKey = _hopKey(hop); - final contact = pathContacts[hopKey]; - if (contact != null && contact.hasLocation) continue; - final peers = connector.contacts - .where( - (c) => - c.hasLocation && - c.path.isNotEmpty && - _matchesHopPrefix( - _lastHopChunk(c.path, c.pathHashWidth), - hop, - ), - ) - .toList(); - if (peers.isNotEmpty) { - final lat = - peers.map((c) => c.latitude!).reduce((a, b) => a + b) / - peers.length; - final lon = - peers.map((c) => c.longitude!).reduce((a, b) => a + b) / - peers.length; - inferredPositions[hopKey] = LatLng(lat, lon); + for (var i = 0; i < outboundHops.length; i++) { + final inferred = inferredOutbound[i]; + if (inferred != null) { + inferredPositions[_hopKey(outboundHops[i])] = inferred; } } @@ -693,7 +655,7 @@ class _PathTraceMapScreenState extends State : hopsForEndpoint.last; final lastHopKey = _hopKey(lastHop); - final peers = connector.allContacts + final rawPeers = connector.allContacts .where( (c) => c.hasLocation && @@ -704,6 +666,19 @@ class _PathTraceMapScreenState extends State ), ) .toList(); + final (anchorPos, anchorGap) = _lastPlausibleAnchor( + outboundHops: outboundHops, + resolvedOutbound: resolvedOutbound, + inferredOutbound: inferredOutbound, + selfPoint: selfPoint, + ); + final peers = _filterPlausiblePeers( + rawPeers, + prevPos: anchorPos, + prevMaxMeters: anchorPos != null + ? anchorGap * PathHopResolver.maxSingleHopDistanceMeters + : null, + ); if (peers.isNotEmpty) { final lat = peers.map((c) => c.latitude!).reduce((a, b) => a + b) / @@ -747,7 +722,6 @@ class _PathTraceMapScreenState extends State _targetContactIsGuessed = targetGuessed; _points = []; - final selfPoint = plausibleSelfPoint(connector); if (selfPoint != null) _points.add(selfPoint); String hopLast = ''; String hopLastLast = ''; @@ -790,8 +764,12 @@ class _PathTraceMapScreenState extends State '${context.l10n.pathTrace_you},${_traceData!.pathData.map(PathHelper.formatHopHex).join(',')}', ); _pathDistanceMeters = getPathDistanceMeters(_points); - _primaryOutboundHops = _outboundHops(pathData); - _rebuildDisplayPaths(connector); + _primaryOutboundHops = outboundHops; + _rebuildDisplayPaths( + connector, + primaryResolved: resolvedOutbound, + primaryInferred: inferredOutbound, + ); }); } catch (e) { appLogger.error( @@ -823,54 +801,170 @@ class _PathTraceMapScreenState extends State return hops; } - Contact? _contactForHop(Uint8List hop, MeshCoreConnector connector) { - final hopKey = _hopKey(hop); - final traced = _traceData?.pathContacts[hopKey]; - if (traced != null) return traced; - _hopContactCacheSignature ??= _refreshHopContactCache(connector); - return _hopContactCache.putIfAbsent(hopKey, () { - for (final c in connector.allContactsUnfiltered) { - if (c.type != advTypeChat && - c.publicKey.length >= hop.length && - listEquals(c.publicKey.sublist(0, hop.length), hop)) { - return c; + List _mergeTraceContacts( + List? explicitContacts, + List allContacts, + ) { + if (explicitContacts == null) return allContacts; + final seenKeys = {}; + final merged = []; + for (final c in explicitContacts) { + if (seenKeys.add(c.publicKeyHex)) merged.add(c); + } + for (final c in allContacts) { + if (seenKeys.add(c.publicKeyHex)) merged.add(c); + } + return merged; + } + + LatLng? _contactLatLng(Contact? contact) { + if (contact == null || + !contact.hasLocation || + contact.latitude == null || + contact.longitude == null) { + return null; + } + return LatLng(contact.latitude!, contact.longitude!); + } + + List _filterPlausiblePeers( + List peers, { + LatLng? prevPos, + double? prevMaxMeters, + LatLng? nextPos, + double? nextMaxMeters, + }) { + if (peers.isEmpty) return const []; + const distance = Distance(); + var filtered = peers; + if (prevPos != null && prevMaxMeters != null) { + filtered = filtered + .where( + (c) => + distance(prevPos, LatLng(c.latitude!, c.longitude!)) <= + prevMaxMeters, + ) + .toList(); + } + if (nextPos != null && nextMaxMeters != null) { + filtered = filtered + .where( + (c) => + distance(nextPos, LatLng(c.latitude!, c.longitude!)) <= + nextMaxMeters, + ) + .toList(); + } + if (prevPos == null && nextPos == null && filtered.length > 1) { + // Without a neighboring anchor, keep only the largest consistent peer + // cluster so a single distant prefix match does not skew the average. + const maxPeerSpreadMeters = + 2 * PathHopResolver.maxSingleHopDistanceMeters; + var bestCluster = [filtered.first]; + for (final seed in filtered) { + final seedPos = LatLng(seed.latitude!, seed.longitude!); + final cluster = filtered.where((other) { + final otherPos = LatLng(other.latitude!, other.longitude!); + return distance(seedPos, otherPos) <= maxPeerSpreadMeters; + }).toList(); + if (cluster.length > bestCluster.length || + (cluster.length == bestCluster.length && + seed.lastSeen.isAfter(bestCluster.first.lastSeen))) { + bestCluster = cluster; } } - return null; - }); - } - - /// Drops cached hop -> contact lookups when the contact list changed; - /// called once per build so per-hop lookups stay cheap. - int _refreshHopContactCache(MeshCoreConnector connector) { - final signature = contactListSignature(connector.allContactsUnfiltered); - if (signature != _hopContactCacheSignature) { - _hopContactCache.clear(); - _hopContactCacheSignature = signature; + return bestCluster; } - return signature; + return filtered; } - LatLng? _inferredPositionForHop(Uint8List hop, MeshCoreConnector connector) { - final hopKey = _hopKey(hop); - final cached = _inferredHopPositions[hopKey]; - if (cached != null) return cached; - final peers = connector.contacts - .where( - (c) => - c.hasLocation && - c.path.isNotEmpty && - _matchesHopPrefix(_lastHopChunk(c.path, c.pathHashWidth), hop), - ) - .toList(); - if (peers.isEmpty) return null; - final lat = - peers.map((c) => c.latitude!).reduce((a, b) => a + b) / peers.length; - final lon = - peers.map((c) => c.longitude!).reduce((a, b) => a + b) / peers.length; - final pos = LatLng(lat, lon); - _inferredHopPositions[hopKey] = pos; - return pos; + List _inferHopPositions({ + required List hops, + required List resolvedContacts, + required LatLng? selfPoint, + required List peerContacts, + }) { + final inferred = List.filled(hops.length, null); + if (hops.isEmpty) return inferred; + + final anchorPositions = [ + for (var i = 0; i < hops.length; i++) + i < resolvedContacts.length + ? _contactLatLng(resolvedContacts[i]) + : null, + ]; + + LatLng? prevPos = selfPoint; + int prevStep = -1; + + for (var i = 0; i < hops.length; i++) { + final knownPos = anchorPositions[i]; + if (knownPos != null) { + prevPos = knownPos; + prevStep = i; + continue; + } + + LatLng? nextPos; + int? nextStep; + for (var j = i + 1; j < hops.length; j++) { + if (anchorPositions[j] != null) { + nextPos = anchorPositions[j]; + nextStep = j; + break; + } + } + + final hop = hops[i]; + final rawPeers = peerContacts + .where( + (c) => + c.hasLocation && + c.path.isNotEmpty && + _matchesHopPrefix(_lastHopChunk(c.path, c.pathHashWidth), hop), + ) + .toList(); + final plausiblePeers = _filterPlausiblePeers( + rawPeers, + prevPos: prevPos, + prevMaxMeters: prevPos != null + ? (i - prevStep) * PathHopResolver.maxSingleHopDistanceMeters + : null, + nextPos: nextPos, + nextMaxMeters: nextPos != null && nextStep != null + ? (nextStep - i) * PathHopResolver.maxSingleHopDistanceMeters + : null, + ); + if (plausiblePeers.isNotEmpty) { + final lat = + plausiblePeers.map((c) => c.latitude!).reduce((a, b) => a + b) / + plausiblePeers.length; + final lon = + plausiblePeers.map((c) => c.longitude!).reduce((a, b) => a + b) / + plausiblePeers.length; + final pos = LatLng(lat, lon); + inferred[i] = pos; + prevPos = pos; + prevStep = i; + } + } + + return inferred; + } + + (LatLng?, int) _lastPlausibleAnchor({ + required List outboundHops, + required List resolvedOutbound, + required List inferredOutbound, + required LatLng? selfPoint, + }) { + for (var i = outboundHops.length - 1; i >= 0; i--) { + final pos = _contactLatLng(resolvedOutbound[i]) ?? inferredOutbound[i]; + if (pos != null) { + return (pos, outboundHops.length - i); + } + } + return (selfPoint, max(1, outboundHops.length)); } String _pathKeyForHops(List hops) { @@ -879,16 +973,42 @@ class _PathTraceMapScreenState extends State /// Rebuilds the renderable paths: the traced path as primary plus up to /// four distinct alternates from the target contact's path history. - void _rebuildDisplayPaths(MeshCoreConnector connector) { - _refreshHopContactCache(connector); + void _rebuildDisplayPaths( + MeshCoreConnector connector, { + List? primaryResolved, + List? primaryInferred, + }) { + final selfPoint = plausibleSelfPoint(connector); final paths = []; + final resolvedMap = + contacts, List inferred})>{}; + + final resolvedPrimary = + primaryResolved ?? + [ + for (final hop in _primaryOutboundHops) + _traceData?.pathContacts[_hopKey(hop)], + ]; + final inferredPrimary = + primaryInferred ?? + [ + for (final hop in _primaryOutboundHops) + _inferredHopPositions[_hopKey(hop)], + ]; + resolvedMap['primary'] = ( + contacts: resolvedPrimary, + inferred: inferredPrimary, + ); + final primary = _buildDisplayPath( id: 'primary', label: context.l10n.pathMap_primary, color: kPrimaryPathColor, isPrimary: true, hops: _primaryOutboundHops, - connector: connector, + resolvedContacts: resolvedPrimary, + inferredPositions: inferredPrimary, + selfPoint: selfPoint, ); if (primary != null) paths.add(primary); @@ -905,14 +1025,30 @@ class _PathTraceMapScreenState extends State ); if (!seen.add(_pathKeyForHops(recordHops))) continue; if (altIndex >= kAlternatePathColors.length) break; + final altId = 'alt-${_pathKeyForHops(recordHops)}'; + final altResolved = PathHopResolver.resolveHops( + hops: recordHops, + contacts: connector.allContactsUnfiltered, + endpoint: selfPoint, + contactFilter: (c) => c.type != advTypeChat, + ); + final altInferred = _inferHopPositions( + hops: recordHops, + resolvedContacts: altResolved, + selfPoint: selfPoint, + peerContacts: connector.contacts, + ); + resolvedMap[altId] = (contacts: altResolved, inferred: altInferred); final alt = _buildDisplayPath( - id: 'alt-${_pathKeyForHops(recordHops)}', + id: altId, label: context.l10n.pathMap_alternate(altIndex + 1), color: kAlternatePathColors[altIndex], isPrimary: false, hops: recordHops, + resolvedContacts: altResolved, + inferredPositions: altInferred, + selfPoint: selfPoint, record: record, - connector: connector, ); if (alt != null) { paths.add(alt); @@ -921,6 +1057,9 @@ class _PathTraceMapScreenState extends State } } + _resolvedDisplayPaths + ..clear() + ..addAll(resolvedMap); _displayPaths = paths; _hiddenPathIds.removeWhere((id) => !paths.any((p) => p.id == id)); if (!paths.any((p) => p.id == _selectedPathId)) { @@ -936,12 +1075,13 @@ class _PathTraceMapScreenState extends State required Color color, required bool isPrimary, required List hops, - required MeshCoreConnector connector, + required List resolvedContacts, + required List inferredPositions, + required LatLng? selfPoint, PathRecord? record, }) { // Without a GPS fix for the local radio the path starts at the first // located hop instead of a bogus "You" at 0,0. - final selfPoint = plausibleSelfPoint(connector); final points = [?selfPoint]; final labels = [if (selfPoint != null) context.l10n.pathTrace_you]; final confirmed = [if (selfPoint != null) true]; @@ -954,15 +1094,14 @@ class _PathTraceMapScreenState extends State for (var i = 0; i < hops.length; i++) { final hop = hops[i]; final hex = PathHelper.formatHopHex(hop); - final contact = _contactForHop(hop, connector); - LatLng? pos; + final contact = i < resolvedContacts.length ? resolvedContacts[i] : null; + LatLng? pos = _contactLatLng(contact); var isGps = false; - if (contact != null && contact.hasLocation) { - pos = LatLng(contact.latitude!, contact.longitude!); + if (pos != null) { isGps = true; gpsConfirmedHops++; - } else { - pos = _inferredPositionForHop(hop, connector); + } else if (i < inferredPositions.length) { + pos = inferredPositions[i]; } if (pos == null) { unresolvedHops++; @@ -1074,7 +1213,6 @@ class _PathTraceMapScreenState extends State Widget build(BuildContext context) { return Consumer( builder: (context, connector, _) { - if (_hasData) _refreshHopContactCache(connector); final settings = context.watch().settings; final isImperial = settings.unitSystem == UnitSystem.imperial; final tileCache = context.read(); @@ -1364,32 +1502,58 @@ class _PathTraceMapScreenState extends State required bool showLabels, required Contact? target, }) { - final connector = context.read(); final markers = []; - // Hop prefix -> paths that use it, in display order. - final hopPaths = >{}; - final hopsByKey = {}; + // Hop prefix + resolved position -> paths that use it, in display order. + final hopNodes = + < + String, + ({ + Uint8List hop, + Contact? contact, + LatLng point, + bool hasGps, + List paths, + }) + >{}; for (final path in _visiblePaths) { - for (final hop in path.hopBytes) { - final hopKey = _hopKey(hop); - hopsByKey[hopKey] = hop; - final list = hopPaths.putIfAbsent(hopKey, () => []); - if (!list.contains(path)) list.add(path); + final resolved = _resolvedDisplayPaths[path.id]; + for (var i = 0; i < path.hopBytes.length; i++) { + final hop = path.hopBytes[i]; + final contact = resolved != null && i < resolved.contacts.length + ? resolved.contacts[i] + : null; + final inferred = resolved != null && i < resolved.inferred.length + ? resolved.inferred[i] + : null; + final gpsPos = _contactLatLng(contact); + final hasGps = gpsPos != null; + final point = gpsPos ?? inferred; + if (point == null) continue; + final hopKey = + '${_hopKey(hop)}|${point.latitude.toStringAsFixed(5)},' + '${point.longitude.toStringAsFixed(5)}'; + final existing = hopNodes[hopKey]; + if (existing == null) { + hopNodes[hopKey] = ( + hop: hop, + contact: contact, + point: point, + hasGps: hasGps, + paths: [path], + ); + } else if (!existing.paths.contains(path)) { + existing.paths.add(path); + } } } - for (final entry in hopPaths.entries) { - final hopKey = entry.key; - final hop = hopsByKey[hopKey]; - if (hop == null) continue; - final paths = entry.value; - final contact = _contactForHop(hop, connector); - final hasGps = contact != null && contact.hasLocation; - final point = hasGps - ? LatLng(contact.latitude!, contact.longitude!) - : _inferredPositionForHop(hop, connector); - if (point == null) continue; + for (final entry in hopNodes.values) { + final hop = entry.hop; + final paths = entry.paths; + final contact = entry.contact; + final hasGps = entry.hasGps; + final point = entry.point; final label = PathHelper.formatHopHex(hop); final baseColor = hasGps ? MeshPalette.signal : MeshPalette.warn; final shared = paths.length > 1; @@ -1796,13 +1960,19 @@ class _PathTraceMapScreenState extends State if (index < path.hopBytes.length) { final hop = path.hopBytes[index]; final hex = PathHelper.formatHopHex(hop); - final contact = _contactForHop(hop, connector); + final resolved = _resolvedDisplayPaths[path.id]; + final contact = resolved != null && index < resolved.contacts.length + ? resolved.contacts[index] + : null; title = contact != null ? '$hex: ${contact.name}' : '$hex: ${l10n.channelPath_unknownRepeater}'; final hasGps = contact != null && contact.hasLocation; final inferred = - !hasGps && _inferredPositionForHop(hop, connector) != null; + !hasGps && + resolved != null && + index < resolved.inferred.length && + resolved.inferred[index] != null; final status = hasGps ? l10n.pathTrace_legendGpsConfirmed : inferred diff --git a/test/helpers/path_hop_resolver_test.dart b/test/helpers/path_hop_resolver_test.dart index 8e903bc6..ebcbcb35 100644 --- a/test/helpers/path_hop_resolver_test.dart +++ b/test/helpers/path_hop_resolver_test.dart @@ -8,13 +8,16 @@ import 'package:meshcore_open/models/contact.dart'; Contact _contact({ required int prefix, + int? secondByte, required String name, required double latitude, required double longitude, DateTime? lastSeen, }) { + final key = Uint8List(32)..first = prefix; + if (secondByte != null) key[1] = secondByte; return Contact( - publicKey: Uint8List(32)..first = prefix, + publicKey: key, name: name, type: advTypeRepeater, pathLength: 0, @@ -91,4 +94,256 @@ void main() { expect(resolved.single?.name, 'Newer'); }); + + test( + 'rejects single candidate impossibly far and preserves previousPosition', + () { + // Arizona self/local repeaters vs East Coast collision (~3700 km away). + const selfArizona = LatLng(33.4484, -112.0740); + final azHop1 = _contact( + prefix: 0x48, + name: 'AZ Repeater 1', + latitude: 33.60097, + longitude: -112.02457, + ); + final eastCoastBogus = _contact( + prefix: 0x9C, + name: 'East Coast 9C', + latitude: 42.3601, + longitude: -71.0589, + ); + final azHop3 = _contact( + prefix: 0x53, + name: 'AZ Repeater 2', + latitude: 33.46300, + longitude: -111.65000, + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0x53, 0x9C, 0x48], + contacts: [azHop1, eastCoastBogus, azHop3], + endpoint: selfArizona, + resolveFromEnd: true, + ); + + expect(resolved.map((c) => c?.name), [ + 'AZ Repeater 2', + null, + 'AZ Repeater 1', + ]); + }, + ); + + test('rejects multiple candidates when all are impossibly far', () { + const selfArizona = LatLng(33.4484, -112.0740); + final eastCoast = _contact( + prefix: 0x9C, + name: 'East Coast 9C', + latitude: 42.3601, + longitude: -71.0589, + lastSeen: DateTime.utc(2026, 2), + ); + final europe = _contact( + prefix: 0x9C, + name: 'Europe 9C', + latitude: 48.8566, + longitude: 2.3522, + lastSeen: DateTime.utc(2026, 1), + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0x9C], + contacts: [eastCoast, europe], + endpoint: selfArizona, + ); + + expect(resolved, [null]); + }); + + test( + 'picks plausible candidate when another candidate is impossibly far', + () { + const selfArizona = LatLng(33.4484, -112.0740); + final eastCoastNewer = _contact( + prefix: 0x9C, + name: 'East Coast 9C', + latitude: 42.3601, + longitude: -71.0589, + lastSeen: DateTime.utc(2026, 5), + ); + final localOlder = _contact( + prefix: 0x9C, + name: 'Local AZ 9C', + latitude: 33.50, + longitude: -111.90, + lastSeen: DateTime.utc(2026, 1), + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0x9C], + contacts: [eastCoastNewer, localOlder], + endpoint: selfArizona, + ); + + expect(resolved.single?.name, 'Local AZ 9C'); + }, + ); + + test('consecutive unresolved hops widen distance budget proportionally', () { + // At equator, 1 degree longitude is ~111.32 km. + // With 2 unresolved intermediate hops (hopGap = 3), budget is 3 * 250 km = 750 km. + // 6.0 degrees (~667.9 km) is beyond 1-hop (250 km) and 2-hop (500 km), + // but within 3-hop (750 km). + const endpoint = LatLng(0, 0); + final distantValid = _contact( + prefix: 0xCC, + name: 'Valid 3-hop target', + latitude: 0, + longitude: 6.0, + ); + + final resolvedWithTwoUnknowns = PathHopResolver.resolve( + pathBytes: const [0xAA, 0xBB, 0xCC], + contacts: [distantValid], + endpoint: endpoint, + ); + expect(resolvedWithTwoUnknowns, [null, null, distantValid]); + + // With only 1 hop (hopGap = 1, budget = 250 km), 6.0 degrees is rejected. + final resolvedDirect = PathHopResolver.resolve( + pathBytes: const [0xCC], + contacts: [distantValid], + endpoint: endpoint, + ); + expect(resolvedDirect, [null]); + }); + + test( + 'endpoint == null rejects a leading distant outlier and keeps local cluster', + () { + final bogusFirst = _contact( + prefix: 0x9C, + name: 'East Coast Outlier', + latitude: 42.3601, + longitude: -71.0589, + lastSeen: DateTime.utc(2026, 6), + ); + final local1 = _contact( + prefix: 0x48, + name: 'Local 1', + latitude: 33.60097, + longitude: -112.02457, + ); + final local2 = _contact( + prefix: 0x53, + name: 'Local 2', + latitude: 33.46300, + longitude: -111.65000, + ); + final local3 = _contact( + prefix: 0x6C, + name: 'Local 3', + latitude: 33.42, + longitude: -111.80, + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0x9C, 0x48, 0x53, 0x6C], + contacts: [bogusFirst, local1, local2, local3], + endpoint: null, + ); + + expect(resolved.map((c) => c?.name), [ + null, + 'Local 1', + 'Local 2', + 'Local 3', + ]); + }, + ); + + test( + 'endpoint != null rejects first-hop outlier and resolves subsequent local hops', + () { + const selfArizona = LatLng(33.4484, -112.0740); + final bogusFirst = _contact( + prefix: 0xEA, + name: 'East Coast First Hop', + latitude: 42.3601, + longitude: -71.0589, + ); + final local2 = _contact( + prefix: 0x48, + name: 'Local 2', + latitude: 33.60097, + longitude: -112.02457, + ); + final local3 = _contact( + prefix: 0x53, + name: 'Local 3', + latitude: 33.46300, + longitude: -111.65000, + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0xEA, 0x48, 0x53], + contacts: [bogusFirst, local2, local3], + endpoint: selfArizona, + ); + + expect(resolved.map((c) => c?.name), [null, 'Local 2', 'Local 3']); + }, + ); + + test('legitimate long-range line-of-sight LoRa hops still resolve', () { + // ~200 km mountain-to-mountain hop (within 250 km single-hop budget). + const self = LatLng(33.4484, -112.0740); + final mountainPeak = _contact( + prefix: 0xAA, + name: 'Mountain Peak', + latitude: 35.1983, + longitude: -111.6513, // Flagstaff (~198 km from Phoenix) + ); + final secondPeak = _contact( + prefix: 0xBB, + name: 'North Rim', + latitude: 36.2100, + longitude: -112.0600, // ~118 km from Flagstaff + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0xAA, 0xBB], + contacts: [mountainPeak, secondPeak], + endpoint: self, + ); + + expect(resolved.map((c) => c?.name), ['Mountain Peak', 'North Rim']); + }); + + test('multi-byte path hash width rejects impossible hop', () { + const self = LatLng(33.4484, -112.0740); + final local = _contact( + prefix: 0x48, + secondByte: 0x01, + name: 'Local 2-byte', + latitude: 33.60, + longitude: -112.02, + ); + final bogus = _contact( + prefix: 0x9C, + secondByte: 0x02, + name: 'Bogus 2-byte', + latitude: 40.7128, + longitude: -74.0060, + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0x48, 0x01, 0x9C, 0x02], + contacts: [local, bogus], + endpoint: self, + pathHashByteWidth: 2, + ); + + expect(resolved.map((c) => c?.name), ['Local 2-byte', null]); + }); } diff --git a/test/screens/channel_message_path_map_test.dart b/test/screens/channel_message_path_map_test.dart new file mode 100644 index 00000000..50d1a3c1 --- /dev/null +++ b/test/screens/channel_message_path_map_test.dart @@ -0,0 +1,292 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/screens/channel_message_path_screen.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:provider/provider.dart'; + +class _FakeConnector extends MeshCoreConnector { + _FakeConnector(this._contacts, {this.lat = 33.4484, this.lon = -112.0740}); + + final List _contacts; + final double? lat; + final double? lon; + + @override + List get allContacts => _contacts; + + @override + double? get selfLatitude => lat; + + @override + double? get selfLongitude => lon; +} + +Contact _repeater({ + required int prefix, + required String name, + required double latitude, + required double longitude, +}) { + return Contact( + publicKey: Uint8List(32)..first = prefix, + name: name, + type: advTypeRepeater, + pathLength: 0, + path: Uint8List(0), + latitude: latitude, + longitude: longitude, + lastSeen: DateTime.utc(2026), + ); +} + +Widget _wrapWithProviders(MeshCoreConnector connector, Widget child) { + final settings = AppSettingsService(); + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider( + create: (_) => MapTileCacheService(appSettingsService: settings), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: child, + ), + ); +} + +void main() { + testWidgets( + 'ChannelMessagePathMapScreen ignores impossible distant hop in polylines, markers, bounds, distance, and hop list', + (tester) async { + final localHop3 = _repeater( + prefix: 0x53, + name: "Rod's Repeater", + latitude: 33.46300, + longitude: -111.65000, + ); + final localHop4 = _repeater( + prefix: 0x48, + name: 'Twain - Clearview', + latitude: 33.60097, + longitude: -112.02457, + ); + final bogusEastCoastHop5 = _repeater( + prefix: 0x9C, + name: 'Beacon Hill 1W Repeater', + latitude: 42.3601, + longitude: -71.0589, + ); + final connector = _FakeConnector([ + localHop3, + localHop4, + bogusEastCoastHop5, + ]); + + final message = ChannelMessage( + senderName: 'Alice', + text: 'test', + timestamp: DateTime.utc(2026), + isOutgoing: false, + pathBytes: Uint8List.fromList([ + 0x6C, + 0x84, + 0x53, + 0x48, + 0x9C, + 0x21, + 0xC9, + 0xEA, + ]), + channelIndex: 0, + ); + + await tester.pumpWidget( + _wrapWithProviders( + connector, + ChannelMessagePathMapScreen(message: message, channelMessage: true), + ), + ); + await tester.pumpAndSettle(); + + // East Coast repeater must not appear as a resolved repeater or in markers. + expect(find.textContaining('Beacon Hill 1W Repeater'), findsNothing); + expect(find.textContaining('42.36010'), findsNothing); + + // Expand the hop list panel so all 8 hops in the ListView are built. + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.text('(9C) Unknown Repeater'), findsOneWidget); + + // Local repeaters should still be listed and plotted. + expect(find.text("(53) Rod's Repeater"), findsOneWidget); + expect(find.text('(48) Twain - Clearview'), findsOneWidget); + + // Collapse back so map assertions (PolylineLayer, MarkerLayer, header distance) are visible. + await tester.tap(find.byIcon(Icons.close_fullscreen)); + await tester.pumpAndSettle(); + + // Polyline points and markers must stay in Arizona (no East Coast jump). + final polylineLayer = tester.widget( + find.byType(PolylineLayer), + ); + final allPolylinePoints = polylineLayer.polylines + .expand((p) => p.points) + .toList(); + expect(allPolylinePoints, isNotEmpty); + for (final point in allPolylinePoints) { + expect(point.latitude, inInclusiveRange(33.0, 34.0)); + expect(point.longitude, inInclusiveRange(-113.0, -111.0)); + } + + // Segment across unresolved/ignored hops (4 -> You) must be dashed while + // adjacent local hops (3 -> 4) remain solid. + expect( + polylineLayer.polylines.any((p) => p.pattern != StrokePattern.solid()), + isTrue, + ); + + final markerLayer = tester.widget( + find.byType(MarkerLayer).first, + ); + for (final marker in markerLayer.markers) { + expect(marker.point.latitude, inInclusiveRange(33.0, 34.0)); + expect(marker.point.longitude, inInclusiveRange(-113.0, -111.0)); + } + + // Camera bounds must stay local, not continental. + final flutterMap = tester.widget(find.byType(FlutterMap)); + final fit = flutterMap.options.initialCameraFit as FitBounds; + expect(fit.bounds.north, lessThan(34.0)); + expect(fit.bounds.east, lessThan(-111.0)); + + // Reported path distance must be local (~50-65 km), not thousands of km. + final distanceFinder = find.textContaining(' km)'); + expect(distanceFinder, findsOneWidget); + final distanceText = tester.widget(distanceFinder).data!; + final kmMatch = RegExp(r'\((\d+\.\d+) km\)').firstMatch(distanceText); + expect(kmMatch, isNotNull); + final kmValue = double.parse(kmMatch!.group(1)!); + expect(kmValue, lessThan(200.0)); + expect(kmValue, greaterThan(10.0)); + }, + ); + + testWidgets( + 'ChannelMessagePathMapScreen without self GPS rejects leading outlier and keeps local cluster', + (tester) async { + final bogusEastCoast = _repeater( + prefix: 0x9C, + name: 'Beacon Hill 1W Repeater', + latitude: 42.3601, + longitude: -71.0589, + ); + final localHop1 = _repeater( + prefix: 0x48, + name: 'Twain - Clearview', + latitude: 33.60097, + longitude: -112.02457, + ); + final localHop2 = _repeater( + prefix: 0x53, + name: "Rod's Repeater", + latitude: 33.46300, + longitude: -111.65000, + ); + final connector = _FakeConnector( + [bogusEastCoast, localHop1, localHop2], + lat: null, + lon: null, + ); + + final message = ChannelMessage( + senderName: 'Alice', + text: 'test', + timestamp: DateTime.utc(2026), + isOutgoing: false, + pathBytes: Uint8List.fromList([0x53, 0x48, 0x9C]), + channelIndex: 0, + ); + + await tester.pumpWidget( + _wrapWithProviders( + connector, + ChannelMessagePathMapScreen(message: message, channelMessage: true), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.textContaining('Beacon Hill 1W Repeater'), findsNothing); + expect(find.text('(9C) Unknown Repeater'), findsOneWidget); + expect(find.text('(48) Twain - Clearview'), findsOneWidget); + expect(find.text("(53) Rod's Repeater"), findsOneWidget); + + final polylineLayer = tester.widget( + find.byType(PolylineLayer), + ); + final allPoints = polylineLayer.polylines + .expand((p) => p.points) + .toList(); + expect(allPoints.length, 2); + for (final point in allPoints) { + expect(point.latitude, inInclusiveRange(33.0, 34.0)); + expect(point.longitude, inInclusiveRange(-113.0, -111.0)); + } + }, + ); + + testWidgets( + 'ChannelMessagePathScreen timeline treats impossible distant hop as unknown', + (tester) async { + final localHop = _repeater( + prefix: 0x48, + name: 'Twain - Clearview', + latitude: 33.60097, + longitude: -112.02457, + ); + final bogusHop = _repeater( + prefix: 0x9C, + name: 'Beacon Hill 1W Repeater', + latitude: 42.3601, + longitude: -71.0589, + ); + final connector = _FakeConnector([localHop, bogusHop]); + + final message = ChannelMessage( + senderName: 'Alice', + text: 'test', + timestamp: DateTime.utc(2026), + isOutgoing: false, + pathBytes: Uint8List.fromList([0x48, 0x9C]), + channelIndex: 0, + ); + + await tester.pumpWidget( + _wrapWithProviders( + connector, + ChannelMessagePathScreen(message: message, channelMessage: true), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('(48) Twain - Clearview'), findsOneWidget); + expect(find.text('(9C) Unknown Repeater'), findsOneWidget); + expect(find.textContaining('Beacon Hill 1W Repeater'), findsNothing); + }, + ); +} diff --git a/test/screens/path_trace_test.dart b/test/screens/path_trace_test.dart index 74b2b37a..825c76d2 100644 --- a/test/screens/path_trace_test.dart +++ b/test/screens/path_trace_test.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'package:flutter/material.dart'; +import 'package:flutter_map/flutter_map.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:provider/provider.dart'; import 'dart:typed_data'; @@ -40,16 +41,31 @@ class _FakeMeshCoreConnector extends MeshCoreConnector { Uint8List.fromList(List.generate(32, (i) => i)); @override - double? get selfLatitude => 48.8566; + double? get selfLatitude => _selfLat; @override - double? get selfLongitude => 2.3522; + double? get selfLongitude => _selfLon; @override - List get allContactsUnfiltered => []; + List get allContactsUnfiltered => _allContacts; @override - List get contacts => []; + List get contacts => _peerContacts; + + final double? _selfLat; + final double? _selfLon; + final List _allContacts; + final List _peerContacts; + + _FakeMeshCoreConnector({ + double? selfLat = 48.8566, + double? selfLon = 2.3522, + List allContacts = const [], + List peerContacts = const [], + }) : _selfLat = selfLat, + _selfLon = selfLon, + _allContacts = allContacts, + _peerContacts = peerContacts; void emitFrame(Uint8List frame) { _receivedFramesController.add(frame); @@ -400,4 +416,170 @@ void main() { // Verify it parsed correctly (should not show the unavailable message) expect(find.text('Path trace not available.'), findsNothing); }); + + testWidgets( + 'PathTraceMapScreen ignores impossible distant repeater and peer inference', + (tester) async { + final localHop1 = Contact( + publicKey: Uint8List(32)..first = 0x48, + name: 'Local Hop', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.60097, + longitude: -112.02457, + lastSeen: DateTime.utc(2026), + ); + final eastCoastBogus = Contact( + publicKey: Uint8List(32)..first = 0x9C, + name: 'East Coast 9C', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 42.3601, + longitude: -71.0589, + lastSeen: DateTime.utc(2026), + ); + final distantPeerSharing9C = Contact( + publicKey: Uint8List(32)..first = 0xAA, + name: 'Distant Chat Peer', + type: advTypeChat, + path: Uint8List.fromList([0x9C]), + pathLength: 1, + latitude: 42.35, + longitude: -71.06, + lastSeen: DateTime.utc(2026), + ); + final connector = _FakeMeshCoreConnector( + selfLat: 33.4484, + selfLon: -112.0740, + allContacts: [localHop1, eastCoastBogus], + peerContacts: [distantPeerSharing9C], + ); + + final screen = PathTraceMapScreen( + title: 'Trace Impossible Hop', + path: Uint8List.fromList([0x48, 0x9C]), + pathHashByteWidth: 1, + ); + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: screen), + ); + await tester.pump(); + + final sentFrame = connector.sentFrames.first; + final tag = sentFrame.sublist(1, 5); + + final pushTraceFrame = Uint8List(17); + pushTraceFrame[0] = pushCodeTraceData; + pushTraceFrame[1] = 0; + pushTraceFrame[2] = 2; + pushTraceFrame[3] = 0; + pushTraceFrame.setRange(4, 8, tag); + pushTraceFrame.setRange(12, 14, [0x48, 0x9C]); + pushTraceFrame.setRange(14, 17, [12, 16, 20]); + + connector.emitFrame(pushTraceFrame); + for (int i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.textContaining('East Coast 9C'), findsNothing); + expect(find.textContaining('9C: Unknown Repeater'), findsWidgets); + + final polylineLayer = tester.widget( + find.byType(PolylineLayer), + ); + final allPoints = polylineLayer.polylines + .expand((p) => p.points) + .toList(); + expect(allPoints, isNotEmpty); + for (final point in allPoints) { + expect(point.latitude, inInclusiveRange(33.0, 34.0)); + expect(point.longitude, inInclusiveRange(-113.0, -111.0)); + } + }, + ); + + testWidgets( + 'PathTraceMapScreen ignores impossible distant contact passed via pathContacts', + (tester) async { + final localHop1 = Contact( + publicKey: Uint8List(32)..first = 0x48, + name: 'Local Hop', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.60097, + longitude: -112.02457, + lastSeen: DateTime.utc(2026), + ); + final eastCoastBogus = Contact( + publicKey: Uint8List(32)..first = 0x9C, + name: 'East Coast 9C', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 42.3601, + longitude: -71.0589, + lastSeen: DateTime.utc(2026), + ); + final connector = _FakeMeshCoreConnector( + selfLat: 33.4484, + selfLon: -112.0740, + allContacts: [localHop1, eastCoastBogus], + ); + + final screen = PathTraceMapScreen( + title: 'Manual Trace Impossible Hop', + path: Uint8List.fromList([0x48, 0x9C]), + pathHashByteWidth: 1, + pathContacts: [localHop1, eastCoastBogus], + ); + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: screen), + ); + await tester.pump(); + + final sentFrame = connector.sentFrames.first; + final tag = sentFrame.sublist(1, 5); + + final pushTraceFrame = Uint8List(17); + pushTraceFrame[0] = pushCodeTraceData; + pushTraceFrame[1] = 0; + pushTraceFrame[2] = 2; + pushTraceFrame[3] = 0; + pushTraceFrame.setRange(4, 8, tag); + pushTraceFrame.setRange(12, 14, [0x48, 0x9C]); + pushTraceFrame.setRange(14, 17, [12, 16, 20]); + + connector.emitFrame(pushTraceFrame); + for (int i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.textContaining('East Coast 9C'), findsNothing); + expect(find.textContaining('9C: Unknown Repeater'), findsWidgets); + + final polylineLayer = tester.widget( + find.byType(PolylineLayer), + ); + final allPoints = polylineLayer.polylines + .expand((p) => p.points) + .toList(); + expect(allPoints.length, 2); + for (final point in allPoints) { + expect(point.latitude, inInclusiveRange(33.0, 34.0)); + expect(point.longitude, inInclusiveRange(-113.0, -111.0)); + } + }, + ); } From 222b45e13051c557322cda713ca893d1e220b916 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:44:39 -0700 Subject: [PATCH 2/2] Keep explicit trace contacts and re-resolve on self move Keep plausible explicit pathContacts authoritative over nearer general contacts sharing a hop prefix while still rejecting impossibly far hops. Re-resolve primary outbound hops, inferred positions, target guess, and map points when _rebuildDisplayPaths runs after self location changes. --- lib/helpers/path_hop_resolver.dart | 185 +++++++++-- lib/screens/path_trace_map.dart | 401 +++++++++++------------ test/helpers/path_hop_resolver_test.dart | 80 +++++ test/screens/path_trace_test.dart | 247 +++++++++++++- 4 files changed, 671 insertions(+), 242 deletions(-) diff --git a/lib/helpers/path_hop_resolver.dart b/lib/helpers/path_hop_resolver.dart index af39983d..ac712dd6 100644 --- a/lib/helpers/path_hop_resolver.dart +++ b/lib/helpers/path_hop_resolver.dart @@ -21,6 +21,7 @@ class PathHopResolver { bool resolveFromEnd = false, int pathHashByteWidth = 1, double maxHopDistanceMeters = maxSingleHopDistanceMeters, + List? preferredContacts, }) { final width = pathHashByteWidth.clamp(1, 3).toInt(); final hops = PathHelper.splitPathBytes(pathBytes, width); @@ -30,6 +31,7 @@ class PathHopResolver { endpoint: endpoint, resolveFromEnd: resolveFromEnd, maxHopDistanceMeters: maxHopDistanceMeters, + preferredContacts: preferredContacts, ); } @@ -40,6 +42,7 @@ class PathHopResolver { bool resolveFromEnd = false, double maxHopDistanceMeters = maxSingleHopDistanceMeters, bool Function(Contact)? contactFilter, + List? preferredContacts, }) { if (hops.isEmpty) return const []; @@ -47,21 +50,41 @@ class PathHopResolver { for (final hop in hops) if (hop.isNotEmpty) hop.length, }; - final candidatesByPrefix = >{}; - for (final contact in contacts) { - final include = - contactFilter?.call(contact) ?? - (contact.type == advTypeRepeater || contact.type == advTypeRoom); - if (!include) continue; + bool includeContact(Contact contact) => + contactFilter?.call(contact) ?? + (contact.type == advTypeRepeater || contact.type == advTypeRoom); + + void indexContact(Map> buckets, Contact contact) { for (final width in widths) { if (contact.publicKey.length < width) continue; final prefix = PathHelper.formatHopHex( contact.publicKey.sublist(0, width), ); - candidatesByPrefix.putIfAbsent(prefix, () => []).add(contact); + buckets.putIfAbsent(prefix, () => []).add(contact); } } - for (final candidates in candidatesByPrefix.values) { + + final preferredKeys = {}; + final preferredByPrefix = >{}; + if (preferredContacts != null) { + for (final contact in preferredContacts) { + if (!includeContact(contact)) continue; + preferredKeys.add(contact.publicKeyHex); + indexContact(preferredByPrefix, contact); + } + } + + final fallbackByPrefix = >{}; + for (final contact in contacts) { + if (!includeContact(contact)) continue; + if (preferredKeys.contains(contact.publicKeyHex)) continue; + indexContact(fallbackByPrefix, contact); + } + + for (final candidates in preferredByPrefix.values) { + candidates.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); + } + for (final candidates in fallbackByPrefix.values) { candidates.sort((a, b) => b.lastSeen.compareTo(a.lastSeen)); } @@ -75,13 +98,14 @@ class PathHopResolver { ]; final distance = Distance(); - (Contact, double)? pickNearestLocated( + (Contact, double)? pickNearestLocatedFrom( + Map> buckets, String prefix, Set used, LatLng anchor, double maxDistanceMeters, ) { - final candidates = candidatesByPrefix[prefix]; + final candidates = buckets[prefix]; if (candidates == null || candidates.isEmpty) return null; Contact? best; double? bestDistance; @@ -100,8 +124,12 @@ class PathHopResolver { return (best, bestDistance); } - Contact? pickFirstUnlocated(String prefix, Set used) { - final candidates = candidatesByPrefix[prefix]; + Contact? pickFirstUnlocatedFrom( + Map> buckets, + String prefix, + Set used, + ) { + final candidates = buckets[prefix]; if (candidates == null || candidates.isEmpty) return null; for (final candidate in candidates) { if (used.contains(candidate)) continue; @@ -110,8 +138,12 @@ class PathHopResolver { return null; } - Contact? pickFirstAny(String prefix, Set used) { - final candidates = candidatesByPrefix[prefix]; + Contact? pickFirstAnyFrom( + Map> buckets, + String prefix, + Set used, + ) { + final candidates = buckets[prefix]; if (candidates == null || candidates.isEmpty) return null; for (final candidate in candidates) { if (!used.contains(candidate)) return candidate; @@ -119,6 +151,44 @@ class PathHopResolver { return null; } + (Contact, double, bool)? pickBestLocated( + String prefix, + Set used, + LatLng anchor, + double maxDistanceMeters, + ) { + final preferred = pickNearestLocatedFrom( + preferredByPrefix, + prefix, + used, + anchor, + maxDistanceMeters, + ); + if (preferred != null) return (preferred.$1, preferred.$2, true); + if (pickFirstUnlocatedFrom(preferredByPrefix, prefix, used) != null) { + return null; + } + final fallback = pickNearestLocatedFrom( + fallbackByPrefix, + prefix, + used, + anchor, + maxDistanceMeters, + ); + if (fallback != null) return (fallback.$1, fallback.$2, false); + return null; + } + + Contact? pickBestUnlocated(String prefix, Set used) { + return pickFirstUnlocatedFrom(preferredByPrefix, prefix, used) ?? + pickFirstUnlocatedFrom(fallbackByPrefix, prefix, used); + } + + Contact? pickBestAny(String prefix, Set used) { + return pickFirstAnyFrom(preferredByPrefix, prefix, used) ?? + pickFirstAnyFrom(fallbackByPrefix, prefix, used); + } + final used = Set.identity(); if (endpoint != null) { @@ -128,19 +198,48 @@ class PathHopResolver { final prefix = stepPrefixes[step]; final hopGap = step - lastAnchorStep; final maxAllowed = hopGap * maxHopDistanceMeters; - final match = pickNearestLocated( + final preferred = pickNearestLocatedFrom( + preferredByPrefix, prefix, used, previousPosition, maxAllowed, ); - if (match != null) { - used.add(match.$1); - resolved[indexes[step]] = match.$1; - previousPosition = _positionOf(match.$1)!; + if (preferred != null) { + used.add(preferred.$1); + resolved[indexes[step]] = preferred.$1; + previousPosition = _positionOf(preferred.$1)!; + lastAnchorStep = step; + continue; + } + final preferredUnlocated = pickFirstUnlocatedFrom( + preferredByPrefix, + prefix, + used, + ); + if (preferredUnlocated != null) { + used.add(preferredUnlocated); + resolved[indexes[step]] = preferredUnlocated; + continue; + } + final fallback = pickNearestLocatedFrom( + fallbackByPrefix, + prefix, + used, + previousPosition, + maxAllowed, + ); + if (fallback != null) { + used.add(fallback.$1); + resolved[indexes[step]] = fallback.$1; + previousPosition = _positionOf(fallback.$1)!; lastAnchorStep = step; } else { - final unlocated = pickFirstUnlocated(prefix, used); + final unlocated = pickFirstUnlocatedFrom( + fallbackByPrefix, + prefix, + used, + ); if (unlocated != null) { used.add(unlocated); resolved[indexes[step]] = unlocated; @@ -153,18 +252,24 @@ class PathHopResolver { // Without a known endpoint, find the located anchor whose plausible chain // explains the most located hops so a single distant prefix collision does // not poison the rest of the path. - var hasAnyLocated = false; - for (final prefix in stepPrefixes) { - final candidates = candidatesByPrefix[prefix]; - if (candidates != null && candidates.any((c) => _positionOf(c) != null)) { - hasAnyLocated = true; - break; + bool bucketHasLocated(Map> buckets) { + for (final prefix in stepPrefixes) { + final candidates = buckets[prefix]; + if (candidates != null && + candidates.any((c) => _positionOf(c) != null)) { + return true; + } } + return false; } + final hasAnyLocated = + bucketHasLocated(preferredByPrefix) || + bucketHasLocated(fallbackByPrefix); + if (!hasAnyLocated) { for (var step = 0; step < hopCount; step++) { - final contact = pickFirstAny(stepPrefixes[step], used); + final contact = pickBestAny(stepPrefixes[step], used); if (contact != null) { used.add(contact); resolved[indexes[step]] = contact; @@ -175,13 +280,19 @@ class PathHopResolver { List? bestRun; var bestLocatedCount = 0; + var bestPreferredCount = 0; var bestTotalDistance = double.infinity; var bestLastSeenSum = -1; for (var anchorStep = 0; anchorStep < hopCount; anchorStep++) { - final candidates = candidatesByPrefix[stepPrefixes[anchorStep]]; - if (candidates == null) continue; - for (final anchorCandidate in candidates) { + final prefix = stepPrefixes[anchorStep]; + final anchorCandidates = <(Contact, bool)>[ + for (final c in preferredByPrefix[prefix] ?? const []) + (c, true), + for (final c in fallbackByPrefix[prefix] ?? const []) + (c, false), + ]; + for (final (anchorCandidate, isPreferredAnchor) in anchorCandidates) { final anchorPos = _positionOf(anchorCandidate); if (anchorPos == null) continue; @@ -189,6 +300,7 @@ class PathHopResolver { final runUsed = Set.identity()..add(anchorCandidate); run[anchorStep] = anchorCandidate; var locatedCount = 1; + var preferredCount = isPreferredAnchor ? 1 : 0; var totalDistance = 0.0; var lastSeenSum = anchorCandidate.lastSeen.millisecondsSinceEpoch; @@ -196,7 +308,7 @@ class PathHopResolver { var lastAnchor = anchorStep; for (var step = anchorStep + 1; step < hopCount; step++) { final maxAllowed = (step - lastAnchor) * maxHopDistanceMeters; - final match = pickNearestLocated( + final match = pickBestLocated( stepPrefixes[step], runUsed, prevPos, @@ -208,6 +320,7 @@ class PathHopResolver { prevPos = _positionOf(match.$1)!; lastAnchor = step; locatedCount++; + if (match.$3) preferredCount++; totalDistance += match.$2; lastSeenSum += match.$1.lastSeen.millisecondsSinceEpoch; } @@ -216,7 +329,7 @@ class PathHopResolver { lastAnchor = anchorStep; for (var step = anchorStep - 1; step >= 0; step--) { final maxAllowed = (lastAnchor - step) * maxHopDistanceMeters; - final match = pickNearestLocated( + final match = pickBestLocated( stepPrefixes[step], runUsed, prevPos, @@ -228,6 +341,7 @@ class PathHopResolver { prevPos = _positionOf(match.$1)!; lastAnchor = step; locatedCount++; + if (match.$3) preferredCount++; totalDistance += match.$2; lastSeenSum += match.$1.lastSeen.millisecondsSinceEpoch; } @@ -235,13 +349,18 @@ class PathHopResolver { final isBetter = locatedCount > bestLocatedCount || (locatedCount == bestLocatedCount && + preferredCount > bestPreferredCount) || + (locatedCount == bestLocatedCount && + preferredCount == bestPreferredCount && totalDistance < bestTotalDistance - 1e-6) || (locatedCount == bestLocatedCount && + preferredCount == bestPreferredCount && (totalDistance - bestTotalDistance).abs() <= 1e-6 && lastSeenSum > bestLastSeenSum); if (isBetter) { bestRun = run; bestLocatedCount = locatedCount; + bestPreferredCount = preferredCount; bestTotalDistance = totalDistance; bestLastSeenSum = lastSeenSum; } @@ -258,7 +377,7 @@ class PathHopResolver { } for (var step = 0; step < hopCount; step++) { if (bestRun[step] != null) continue; - final unlocated = pickFirstUnlocated(stepPrefixes[step], used); + final unlocated = pickBestUnlocated(stepPrefixes[step], used); if (unlocated != null) { used.add(unlocated); resolved[indexes[step]] = unlocated; diff --git a/lib/screens/path_trace_map.dart b/lib/screens/path_trace_map.dart index 63d6d59c..198616de 100644 --- a/lib/screens/path_trace_map.dart +++ b/lib/screens/path_trace_map.dart @@ -25,6 +25,7 @@ import 'package:meshcore_open/widgets/path_map_ui.dart'; import 'package:meshcore_open/widgets/snr_indicator.dart'; import 'package:meshcore_open/widgets/set_my_location_dialog.dart'; import 'package:provider/provider.dart'; + import '../theme/mesh_theme.dart'; export 'package:meshcore_open/widgets/path_map_ui.dart' @@ -584,192 +585,20 @@ class _PathTraceMapScreenState extends State .map((snr) => snr.toSigned(8).toDouble() / 4) .toList(); - final selfPoint = plausibleSelfPoint(connector); - final outboundHops = _outboundHops(pathData); - final candidateContacts = _mergeTraceContacts( - widget.pathContacts, - connector.allContactsUnfiltered, - ); - final resolvedOutbound = PathHopResolver.resolveHops( - hops: outboundHops, - contacts: candidateContacts, - endpoint: selfPoint, - contactFilter: (c) => c.type != advTypeChat, - ); - final Map pathContacts = {}; - for (var i = 0; i < outboundHops.length; i++) { - final contact = resolvedOutbound[i]; - if (contact != null) { - pathContacts[_hopKey(outboundHops[i])] = contact; - } - } - - // For hops with no GPS contact, infer position from other contacts - // with known GPS that share the same last-hop byte, bounded by the - // plausible hop distance from neighboring anchors. - final inferredOutbound = _inferHopPositions( - hops: outboundHops, - resolvedContacts: resolvedOutbound, - selfPoint: selfPoint, - peerContacts: connector.contacts, - ); - final Map inferredPositions = {}; - for (var i = 0; i < outboundHops.length; i++) { - final inferred = inferredOutbound[i]; - if (inferred != null) { - inferredPositions[_hopKey(outboundHops[i])] = inferred; - } - } - setState(() { _isLoading = false; _hasData = true; - _inferredHopPositions = inferredPositions; + _targetContact = widget.targetContact; + _primaryOutboundHops = _outboundHops(pathData); _traceData = PathTraceData( pathData: pathData, snrData: snrData, - pathContacts: pathContacts, + pathContacts: const {}, ); - // Compute endpoint position for the target contact. - LatLng? targetPos; - bool targetGuessed = false; - _targetContact = widget.targetContact; - - if (_targetContact != null) { - final tc = _targetContact!; - if (tc.hasLocation) { - targetPos = LatLng(tc.latitude!, tc.longitude!); - } else if (pathData.length > 1 || _tracedPath.isNotEmpty) { - // Infer from the last hop: average GPS contacts sharing that hop. - // For a round-trip path (flipPathAround/reversePathAround), the target-side hop - // sits in the middle of the symmetric sequence; .last is the local side. - final tracedHops = PathHelper.splitPathBytes( - _tracedPath, - _tracedPathHashWidth, - ); - final hopsForEndpoint = tracedHops.isNotEmpty - ? tracedHops - : pathData; - final lastHop = widget.reversePathAround - ? hopsForEndpoint.first - : hopsForEndpoint.last; - final lastHopKey = _hopKey(lastHop); - - final rawPeers = connector.allContacts - .where( - (c) => - c.hasLocation && - c.path.isNotEmpty && - _matchesHopPrefix( - _lastHopChunk(c.path, c.pathHashWidth), - lastHop, - ), - ) - .toList(); - final (anchorPos, anchorGap) = _lastPlausibleAnchor( - outboundHops: outboundHops, - resolvedOutbound: resolvedOutbound, - inferredOutbound: inferredOutbound, - selfPoint: selfPoint, - ); - final peers = _filterPlausiblePeers( - rawPeers, - prevPos: anchorPos, - prevMaxMeters: anchorPos != null - ? anchorGap * PathHopResolver.maxSingleHopDistanceMeters - : null, - ); - if (peers.isNotEmpty) { - final lat = - peers.map((c) => c.latitude!).reduce((a, b) => a + b) / - peers.length; - final lon = - peers.map((c) => c.longitude!).reduce((a, b) => a + b) / - peers.length; - const offsetDeg = 0.003; - final angle = (tc.publicKey[1] / 255.0) * 2 * pi; - targetPos = LatLng( - lat + offsetDeg * cos(angle), - lon + offsetDeg * sin(angle), - ); - targetGuessed = true; - } else if (inferredPositions.containsKey(lastHopKey)) { - final lat = inferredPositions[lastHopKey]!.latitude; - final lon = inferredPositions[lastHopKey]!.longitude; - const offsetDeg = 0.003; - final angle = (tc.publicKey[1] / 255.0) * 2 * pi; - targetPos = LatLng( - lat + offsetDeg * cos(angle), - lon + offsetDeg * sin(angle), - ); - targetGuessed = true; - } else { - // As a last resort, just place it at the same position as the last hop. - final contact = pathContacts[lastHopKey]; - if (contact != null && contact.hasLocation) { - const offsetDeg = 0.003; - final angle = (tc.publicKey[1] / 255.0) * 2 * pi; - targetPos = LatLng( - contact.latitude! + offsetDeg * cos(angle), - contact.longitude! + offsetDeg * sin(angle), - ); - targetGuessed = true; - } - } - } - } - _targetContactPosition = targetPos; - _targetContactIsGuessed = targetGuessed; - - _points = []; - if (selfPoint != null) _points.add(selfPoint); - String hopLast = ''; - String hopLastLast = ''; - for (final hop in _traceData!.pathData) { - final hopKey = _hopKey(hop); - if (hopKey == hopLastLast && widget.flipPathAround) { - break; //skip duplicate hops in round-trip paths - } - final contact = _traceData!.pathContacts[hopKey]; - if (contact != null && contact.hasLocation) { - _points.add(LatLng(contact.latitude!, contact.longitude!)); - } else { - final inferred = inferredPositions[hopKey]; - if (inferred != null) _points.add(inferred); - } - hopLastLast = hopLast; - hopLast = hopKey; - } - if (targetPos != null) { - if (_targetContact != null && _targetContact!.type == advTypeChat) { - _points.add(targetPos); - } - } - _polylines = _points.length > 1 - ? [ - Polyline( - points: _points, - strokeWidth: 4, - color: kPrimaryPathColor, - ), - ] - : []; - - _initialCenter = _points.isNotEmpty - ? _points.first - : const LatLng(0, 0); - _initialZoom = _points.isNotEmpty ? 13.0 : 2.0; - _bounds = _points.length > 1 ? LatLngBounds.fromPoints(_points) : null; _mapKey = ValueKey( - '${context.l10n.pathTrace_you},${_traceData!.pathData.map(PathHelper.formatHopHex).join(',')}', - ); - _pathDistanceMeters = getPathDistanceMeters(_points); - _primaryOutboundHops = outboundHops; - _rebuildDisplayPaths( - connector, - primaryResolved: resolvedOutbound, - primaryInferred: inferredOutbound, + '${context.l10n.pathTrace_you},${pathData.map(PathHelper.formatHopHex).join(',')}', ); + _rebuildDisplayPaths(connector); }); } catch (e) { appLogger.error( @@ -801,20 +630,173 @@ class _PathTraceMapScreenState extends State return hops; } - List _mergeTraceContacts( - List? explicitContacts, - List allContacts, - ) { - if (explicitContacts == null) return allContacts; - final seenKeys = {}; - final merged = []; - for (final c in explicitContacts) { - if (seenKeys.add(c.publicKeyHex)) merged.add(c); + (LatLng?, bool) _resolveTargetContactPosition({ + required MeshCoreConnector connector, + required List pathData, + required List outboundHops, + required List resolvedOutbound, + required List inferredOutbound, + required Map pathContacts, + required Map inferredPositions, + required LatLng? selfPoint, + }) { + final tc = _targetContact; + if (tc == null) return (null, false); + if (tc.hasLocation) { + return (LatLng(tc.latitude!, tc.longitude!), false); } - for (final c in allContacts) { - if (seenKeys.add(c.publicKeyHex)) merged.add(c); + if (pathData.length <= 1 && _tracedPath.isEmpty) { + return (null, false); } - return merged; + + // Infer from the last hop: average GPS contacts sharing that hop. + // For a round-trip path (flipPathAround/reversePathAround), the target-side hop + // sits in the middle of the symmetric sequence; .last is the local side. + final tracedHops = PathHelper.splitPathBytes( + _tracedPath, + _tracedPathHashWidth, + ); + final hopsForEndpoint = tracedHops.isNotEmpty ? tracedHops : pathData; + final lastHop = widget.reversePathAround + ? hopsForEndpoint.first + : hopsForEndpoint.last; + final lastHopKey = _hopKey(lastHop); + + final rawPeers = connector.allContacts + .where( + (c) => + c.hasLocation && + c.path.isNotEmpty && + _matchesHopPrefix( + _lastHopChunk(c.path, c.pathHashWidth), + lastHop, + ), + ) + .toList(); + final (anchorPos, anchorGap) = _lastPlausibleAnchor( + outboundHops: outboundHops, + resolvedOutbound: resolvedOutbound, + inferredOutbound: inferredOutbound, + selfPoint: selfPoint, + ); + final peers = _filterPlausiblePeers( + rawPeers, + prevPos: anchorPos, + prevMaxMeters: anchorPos != null + ? anchorGap * PathHopResolver.maxSingleHopDistanceMeters + : null, + ); + const offsetDeg = 0.003; + final angle = (tc.publicKey[1] / 255.0) * 2 * pi; + if (peers.isNotEmpty) { + final lat = + peers.map((c) => c.latitude!).reduce((a, b) => a + b) / peers.length; + final lon = + peers.map((c) => c.longitude!).reduce((a, b) => a + b) / peers.length; + return ( + LatLng(lat + offsetDeg * cos(angle), lon + offsetDeg * sin(angle)), + true, + ); + } + if (inferredPositions.containsKey(lastHopKey)) { + final inferred = inferredPositions[lastHopKey]!; + return ( + LatLng( + inferred.latitude + offsetDeg * cos(angle), + inferred.longitude + offsetDeg * sin(angle), + ), + true, + ); + } + // As a last resort, just place it at the same position as the last hop. + final contact = pathContacts[lastHopKey]; + if (contact != null && contact.hasLocation) { + return ( + LatLng( + contact.latitude! + offsetDeg * cos(angle), + contact.longitude! + offsetDeg * sin(angle), + ), + true, + ); + } + return (null, false); + } + + void _syncPrimaryTraceState({ + required MeshCoreConnector connector, + required PathTraceData traceData, + required List resolvedOutbound, + required List inferredOutbound, + required LatLng? selfPoint, + }) { + final pathContacts = {}; + for (var i = 0; i < _primaryOutboundHops.length; i++) { + final contact = resolvedOutbound[i]; + if (contact != null) { + pathContacts[_hopKey(_primaryOutboundHops[i])] = contact; + } + } + + final inferredPositions = {}; + for (var i = 0; i < _primaryOutboundHops.length; i++) { + final inferred = inferredOutbound[i]; + if (inferred != null) { + inferredPositions[_hopKey(_primaryOutboundHops[i])] = inferred; + } + } + + _inferredHopPositions = inferredPositions; + _traceData = PathTraceData( + pathData: traceData.pathData, + snrData: traceData.snrData, + pathContacts: pathContacts, + ); + + final (targetPos, targetGuessed) = _resolveTargetContactPosition( + connector: connector, + pathData: traceData.pathData, + outboundHops: _primaryOutboundHops, + resolvedOutbound: resolvedOutbound, + inferredOutbound: inferredOutbound, + pathContacts: pathContacts, + inferredPositions: inferredPositions, + selfPoint: selfPoint, + ); + _targetContactPosition = targetPos; + _targetContactIsGuessed = targetGuessed; + + final points = [?selfPoint]; + String hopLast = ''; + String hopLastLast = ''; + for (final hop in traceData.pathData) { + final hopKey = _hopKey(hop); + if (hopKey == hopLastLast && widget.flipPathAround) { + break; //skip duplicate hops in round-trip paths + } + final contact = pathContacts[hopKey]; + if (contact != null && contact.hasLocation) { + points.add(LatLng(contact.latitude!, contact.longitude!)); + } else { + final inferred = inferredPositions[hopKey]; + if (inferred != null) points.add(inferred); + } + hopLastLast = hopLast; + hopLast = hopKey; + } + if (targetPos != null && + _targetContact != null && + _targetContact!.type == advTypeChat) { + points.add(targetPos); + } + + _points = points; + _polylines = points.length > 1 + ? [Polyline(points: points, strokeWidth: 4, color: kPrimaryPathColor)] + : []; + _initialCenter = points.isNotEmpty ? points.first : const LatLng(0, 0); + _initialZoom = points.isNotEmpty ? 13.0 : 2.0; + _bounds = points.length > 1 ? LatLngBounds.fromPoints(points) : null; + _pathDistanceMeters = getPathDistanceMeters(points); } LatLng? _contactLatLng(Contact? contact) { @@ -973,28 +955,35 @@ class _PathTraceMapScreenState extends State /// Rebuilds the renderable paths: the traced path as primary plus up to /// four distinct alternates from the target contact's path history. - void _rebuildDisplayPaths( - MeshCoreConnector connector, { - List? primaryResolved, - List? primaryInferred, - }) { + void _rebuildDisplayPaths(MeshCoreConnector connector) { final selfPoint = plausibleSelfPoint(connector); final paths = []; final resolvedMap = contacts, List inferred})>{}; - final resolvedPrimary = - primaryResolved ?? - [ - for (final hop in _primaryOutboundHops) - _traceData?.pathContacts[_hopKey(hop)], - ]; - final inferredPrimary = - primaryInferred ?? - [ - for (final hop in _primaryOutboundHops) - _inferredHopPositions[_hopKey(hop)], - ]; + final resolvedPrimary = PathHopResolver.resolveHops( + hops: _primaryOutboundHops, + preferredContacts: widget.pathContacts, + contacts: connector.allContactsUnfiltered, + endpoint: selfPoint, + contactFilter: (c) => c.type != advTypeChat, + ); + final inferredPrimary = _inferHopPositions( + hops: _primaryOutboundHops, + resolvedContacts: resolvedPrimary, + selfPoint: selfPoint, + peerContacts: connector.contacts, + ); + final traceData = _traceData; + if (traceData != null) { + _syncPrimaryTraceState( + connector: connector, + traceData: traceData, + resolvedOutbound: resolvedPrimary, + inferredOutbound: inferredPrimary, + selfPoint: selfPoint, + ); + } resolvedMap['primary'] = ( contacts: resolvedPrimary, inferred: inferredPrimary, diff --git a/test/helpers/path_hop_resolver_test.dart b/test/helpers/path_hop_resolver_test.dart index ebcbcb35..c3c230c5 100644 --- a/test/helpers/path_hop_resolver_test.dart +++ b/test/helpers/path_hop_resolver_test.dart @@ -346,4 +346,84 @@ void main() { expect(resolved.map((c) => c?.name), ['Local 2-byte', null]); }); + + test( + 'preferredContacts overrides nearer general contact with same prefix when plausible', + () { + const self = LatLng(33.4484, -112.0740); + final nearerGeneral = _contact( + prefix: 0x48, + secondByte: 0x01, + name: 'Nearer General 48', + latitude: 33.4600, + longitude: -112.0700, + lastSeen: DateTime.utc(2026, 6), + ); + final selectedPreferred = _contact( + prefix: 0x48, + secondByte: 0x02, + name: 'Selected Preferred 48', + latitude: 33.9000, + longitude: -111.7000, + lastSeen: DateTime.utc(2026, 1), + ); + final secondHopGeneral = _contact( + prefix: 0x53, + name: 'Second Hop 53', + latitude: 33.9500, + longitude: -111.6500, + ); + + final resolvedWithEndpoint = PathHopResolver.resolve( + pathBytes: const [0x48, 0x53], + contacts: [nearerGeneral, selectedPreferred, secondHopGeneral], + preferredContacts: [selectedPreferred], + endpoint: self, + ); + expect(resolvedWithEndpoint.map((c) => c?.name), [ + 'Selected Preferred 48', + 'Second Hop 53', + ]); + + final resolvedWithoutEndpoint = PathHopResolver.resolve( + pathBytes: const [0x48, 0x53], + contacts: [nearerGeneral, selectedPreferred, secondHopGeneral], + preferredContacts: [selectedPreferred], + endpoint: null, + ); + expect(resolvedWithoutEndpoint.map((c) => c?.name), [ + 'Selected Preferred 48', + 'Second Hop 53', + ]); + }, + ); + + test( + 'impossibly far preferredContact is rejected and falls back to plausible general contact', + () { + const self = LatLng(33.4484, -112.0740); + final bogusPreferred = _contact( + prefix: 0x9C, + secondByte: 0x01, + name: 'East Coast Preferred 9C', + latitude: 42.3601, + longitude: -71.0589, + ); + final localGeneral = _contact( + prefix: 0x9C, + secondByte: 0x02, + name: 'Local General 9C', + latitude: 33.60097, + longitude: -112.02457, + ); + + final resolved = PathHopResolver.resolve( + pathBytes: const [0x9C], + contacts: [bogusPreferred, localGeneral], + preferredContacts: [bogusPreferred], + endpoint: self, + ); + expect(resolved.map((c) => c?.name), ['Local General 9C']); + }, + ); } diff --git a/test/screens/path_trace_test.dart b/test/screens/path_trace_test.dart index 825c76d2..32c3fe9a 100644 --- a/test/screens/path_trace_test.dart +++ b/test/screens/path_trace_test.dart @@ -1,8 +1,11 @@ import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_map/flutter_map.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:latlong2/latlong.dart'; import 'package:provider/provider.dart'; + import 'dart:typed_data'; import 'package:meshcore_open/connector/meshcore_connector.dart'; @@ -40,6 +43,9 @@ class _FakeMeshCoreConnector extends MeshCoreConnector { Uint8List? get selfPublicKey => Uint8List.fromList(List.generate(32, (i) => i)); + @override + bool get isConnected => _isConnected; + @override double? get selfLatitude => _selfLat; @@ -52,21 +58,44 @@ class _FakeMeshCoreConnector extends MeshCoreConnector { @override List get contacts => _peerContacts; - final double? _selfLat; - final double? _selfLon; + final bool _isConnected; + double? _selfLat; + double? _selfLon; + double? _pendingLat; + double? _pendingLon; final List _allContacts; final List _peerContacts; _FakeMeshCoreConnector({ + bool isConnected = false, double? selfLat = 48.8566, double? selfLon = 2.3522, List allContacts = const [], List peerContacts = const [], - }) : _selfLat = selfLat, + }) : _isConnected = isConnected, + _selfLat = selfLat, _selfLon = selfLon, _allContacts = allContacts, _peerContacts = peerContacts; + @override + Future setNodeLocation({ + required double lat, + required double lon, + }) async { + _pendingLat = lat; + _pendingLon = lon; + } + + @override + Future refreshDeviceInfo() async { + if (_pendingLat != null && _pendingLon != null) { + _selfLat = _pendingLat; + _selfLon = _pendingLon; + notifyListeners(); + } + } + void emitFrame(Uint8List frame) { _receivedFramesController.add(frame); } @@ -582,4 +611,216 @@ void main() { } }, ); + + testWidgets( + 'PathTraceMapScreen preserves plausible explicit pathContacts over nearer contact with same prefix', + (tester) async { + final nearerCollision = Contact( + publicKey: Uint8List(32) + ..[0] = 0x48 + ..[1] = 0x01, + name: 'Nearer 48', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.4600, + longitude: -112.0700, + lastSeen: DateTime.utc(2026, 6), + ); + final selectedExplicit = Contact( + publicKey: Uint8List(32) + ..[0] = 0x48 + ..[1] = 0x02, + name: 'Selected 48', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.9000, + longitude: -111.7000, + lastSeen: DateTime.utc(2026, 1), + ); + final fallbackHop2 = Contact( + publicKey: Uint8List(32)..first = 0x53, + name: 'Fallback 53', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.9500, + longitude: -111.6500, + lastSeen: DateTime.utc(2026), + ); + final connector = _FakeMeshCoreConnector( + selfLat: 33.4484, + selfLon: -112.0740, + allContacts: [nearerCollision, selectedExplicit, fallbackHop2], + ); + + final screen = PathTraceMapScreen( + title: 'Explicit Contact Priority', + path: Uint8List.fromList([0x48, 0x53]), + pathHashByteWidth: 1, + pathContacts: [selectedExplicit], + ); + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: screen), + ); + await tester.pump(); + + final sentFrame = connector.sentFrames.first; + final tag = sentFrame.sublist(1, 5); + + final pushTraceFrame = Uint8List(17); + pushTraceFrame[0] = pushCodeTraceData; + pushTraceFrame[1] = 0; + pushTraceFrame[2] = 2; + pushTraceFrame[3] = 0; + pushTraceFrame.setRange(4, 8, tag); + pushTraceFrame.setRange(12, 14, [0x48, 0x53]); + pushTraceFrame.setRange(14, 17, [12, 16, 20]); + + connector.emitFrame(pushTraceFrame); + for (int i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.textContaining('Selected 48'), findsWidgets); + expect(find.textContaining('Fallback 53'), findsWidgets); + expect(find.textContaining('Nearer 48'), findsNothing); + + final polylineLayer = tester.widget( + find.byType(PolylineLayer), + ); + final allPoints = polylineLayer.polylines + .expand((p) => p.points) + .toList(); + expect(allPoints.length, 3); + expect(allPoints[1].latitude, closeTo(33.9000, 1e-4)); + expect(allPoints[1].longitude, closeTo(-111.7000, 1e-4)); + expect(allPoints[2].latitude, closeTo(33.9500, 1e-4)); + expect(allPoints[2].longitude, closeTo(-111.6500, 1e-4)); + }, + ); + + testWidgets( + 'PathTraceMapScreen re-resolves primary hops when self location changes via _setMyLocation', + (tester) async { + final localHop1 = Contact( + publicKey: Uint8List(32)..first = 0x48, + name: 'Phoenix Hop 1', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.60097, + longitude: -112.02457, + lastSeen: DateTime.utc(2026), + ); + final localHop2 = Contact( + publicKey: Uint8List(32)..first = 0x53, + name: 'Phoenix Hop 2', + type: advTypeRepeater, + path: Uint8List(0), + pathLength: 0, + latitude: 33.46300, + longitude: -111.65000, + lastSeen: DateTime.utc(2026), + ); + final connector = _FakeMeshCoreConnector( + isConnected: true, + // Incorrect initial self location on the East Coast causes local hops to be rejected. + selfLat: 42.3601, + selfLon: -71.0589, + allContacts: [localHop1, localHop2], + ); + + final screen = PathTraceMapScreen( + title: 'Relocate Self Trace', + path: Uint8List.fromList([0x48, 0x53]), + pathHashByteWidth: 1, + ); + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: screen), + ); + await tester.pump(); + + expect(connector.sentFrames.length, 1); + final tag = connector.sentFrames.first.sublist(1, 5); + + final pushTraceFrame = Uint8List(17); + pushTraceFrame[0] = pushCodeTraceData; + pushTraceFrame[1] = 0; + pushTraceFrame[2] = 2; + pushTraceFrame[3] = 0; + pushTraceFrame.setRange(4, 8, tag); + pushTraceFrame.setRange(12, 14, [0x48, 0x53]); + pushTraceFrame.setRange(14, 17, [12, 16, 20]); + + connector.emitFrame(pushTraceFrame); + for (int i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + // Initially, both Phoenix hops are rejected as impossibly far from Boston. + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.textContaining('Phoenix Hop 1'), findsNothing); + expect(find.textContaining('Phoenix Hop 2'), findsNothing); + expect(find.textContaining('48: Unknown Repeater'), findsWidgets); + expect(find.textContaining('53: Unknown Repeater'), findsWidgets); + + await tester.tap(find.byIcon(Icons.close_fullscreen)); + await tester.pumpAndSettle(); + + expect(find.byType(PolylineLayer), findsNothing); + + // Update self location to Phoenix via the map's long-press action. + final flutterMap = tester.widget(find.byType(FlutterMap)); + flutterMap.options.onLongPress!( + const TapPosition(Offset.zero, Offset.zero), + const LatLng(33.4484, -112.0740), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.widgetWithText(FilledButton, 'Set location')); + await tester.pumpAndSettle(); + + // Primary hops must now be resolved without waiting for another trace packet. + expect(connector.sentFrames.length, 1); + + final polylineLayer = tester.widget( + find.byType(PolylineLayer), + ); + final allPoints = polylineLayer.polylines + .expand((p) => p.points) + .toList(); + expect(allPoints.length, 3); + expect(allPoints[0].latitude, closeTo(33.4484, 1e-4)); + expect(allPoints[0].longitude, closeTo(-112.0740, 1e-4)); + expect(allPoints[1].latitude, closeTo(33.60097, 1e-4)); + expect(allPoints[1].longitude, closeTo(-112.02457, 1e-4)); + expect(allPoints[2].latitude, closeTo(33.46300, 1e-4)); + expect(allPoints[2].longitude, closeTo(-111.65000, 1e-4)); + + final markerLayer = tester.widget( + find.byType(MarkerLayer).first, + ); + expect(markerLayer.markers.length, greaterThanOrEqualTo(3)); + for (final marker in markerLayer.markers) { + expect(marker.point.latitude, inInclusiveRange(33.0, 34.0)); + expect(marker.point.longitude, inInclusiveRange(-113.0, -111.0)); + } + + await tester.tap(find.byIcon(Icons.open_in_full)); + await tester.pumpAndSettle(); + + expect(find.textContaining('Phoenix Hop 1'), findsWidgets); + expect(find.textContaining('Phoenix Hop 2'), findsWidgets); + expect(find.textContaining('Unknown Repeater'), findsNothing); + }, + ); }