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] 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); + }, + ); }