From 04b940e8e1d35f9264f8cd34f6a9ff1e9c5f484c Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Sat, 10 Oct 2026 00:46:23 +0300 Subject: [PATCH] Preserve native command ownership for a moving direction hint --- simulation/ai-polygon/nav2/server.py | 8 ++-- .../ai-polygon/navigation/arrival_approach.py | 17 ++++++- .../simulation/ai_polygon/route_mission.py | 7 ++- tests/test_nav2_route_support.py | 45 ++++++++++++++++++- 4 files changed, 70 insertions(+), 7 deletions(-) diff --git a/simulation/ai-polygon/nav2/server.py b/simulation/ai-polygon/nav2/server.py index 16ede6d2..0572c17a 100644 --- a/simulation/ai-polygon/nav2/server.py +++ b/simulation/ai-polygon/nav2/server.py @@ -20,7 +20,7 @@ import yaml from action_msgs.msg import GoalStatus from configuration import observed_configuration from differential_motion import alignment_angle -from navigation.arrival_approach import validate_orientation +from navigation.arrival_approach import validate_orientation, orientation_identity from navigation.continuous_control import ContinuousControl from navigation.footprint import Footprint from navigation.route_observation import route_observation @@ -103,8 +103,8 @@ class Navigation: or not value.get('continuous', False)): return None target = value.get('arrival_target') - return (orientation['key'], tuple(orientation['xy']), - value['max_speed_mps'], tuple(target) if target is not None else None) + return (orientation_identity(orientation), value['max_speed_mps'], + tuple(target) if target is not None else None) @staticmethod def reply(reason, *, status='waiting-for-plan', **extra): @@ -199,7 +199,7 @@ class Navigation: if not value.get('visual_goal_available'): goal[:2] = target reverse = value['allow_reverse'] - orientation_key = ('spin', orientation['key'], tuple(orientation['xy'])) if orientation else None + orientation_key = ('spin', *orientation_identity(orientation)) if orientation else None if (orientation_key is not None and self.action_key == orientation_key and self.node.terminal is not None and self.node.terminal.done() and self.node.terminal.result().status == GoalStatus.STATUS_SUCCEEDED): diff --git a/simulation/ai-polygon/navigation/arrival_approach.py b/simulation/ai-polygon/navigation/arrival_approach.py index d3469480..2f66e6cc 100644 --- a/simulation/ai-polygon/navigation/arrival_approach.py +++ b/simulation/ai-polygon/navigation/arrival_approach.py @@ -182,7 +182,7 @@ def validate_orientation(value): return None if ( not isinstance(value, dict) - or set(value) != {"key", "xy"} + or set(value) not in ({"key", "xy"}, {"key", "xy", "direction_xy"}) or not isinstance(value["key"], str) or not re.fullmatch(r"[a-zA-Z0-9_-]{1,80}", value["key"]) or not isinstance(value["xy"], list) @@ -193,9 +193,24 @@ def validate_orientation(value): ) ): raise ValueError("Invalid orientation intent") + direction = value.get("direction_xy") + if "direction_xy" in value and ( + not isinstance(direction, list) or len(direction) != 2 + or any(isinstance(v, bool) or not isinstance(v, (float, int)) + or not math.isfinite(v) for v in direction) + or not math.isclose(math.hypot(*direction), 1., abs_tol=1e-9) + ): + raise ValueError("Invalid orientation direction") return value +def orientation_identity(value): + """A translated bearing endpoint is the same intent; a new bearing is not.""" + direction = value.get("direction_xy") + return (value["key"], "direction", tuple(direction)) if direction is not None else ( + value["key"], "point", tuple(value["xy"])) + + class ArrivalApproach: def __init__(self): self.turning = self.completed = False diff --git a/src/k1link/simulation/ai_polygon/route_mission.py b/src/k1link/simulation/ai_polygon/route_mission.py index cc3d7eb7..30f2c757 100644 --- a/src/k1link/simulation/ai_polygon/route_mission.py +++ b/src/k1link/simulation/ai_polygon/route_mission.py @@ -209,11 +209,16 @@ class RoutedMission(WaypointMission): def orientation_target(self): if self.route_target is None or self.route_failure or self.fault: return None - return { + target = { "key": self.orientation_key(f"route-{self.index}-{self.segment_index}" + (f"-revision-{self.route_revision}" if self.route_revision else "")), "xy": list(self.route_target), } + if self.advisory_joint(): + segment = self.leg["segments"][self.segment_index] + direction = np.asarray(segment["end_xy"]) - segment["start_xy"] + target["direction_xy"] = (direction / np.linalg.norm(direction)).tolist() + return target def observe_maneuver(self, maneuver, pose, seconds): """A bound observed local placement earns time, never a route receipt.""" diff --git a/tests/test_nav2_route_support.py b/tests/test_nav2_route_support.py index eacc56e2..cab6b350 100644 --- a/tests/test_nav2_route_support.py +++ b/tests/test_nav2_route_support.py @@ -17,6 +17,7 @@ def bridge(monkeypatch): root = Path(__file__).parents[1] / 'simulation/ai-polygon' monkeypatch.syspath_prepend(str(root)) monkeypatch.syspath_prepend(str(root / 'nav2')) + from navigation.arrival_approach import validate_orientation, orientation_identity from navigation.footprint import Footprint from navigation.route_observation import route_observation from route_support import route_support @@ -24,7 +25,8 @@ def bridge(monkeypatch): tree = ast.parse((root / 'nav2/server.py').read_text()) cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Navigation') scope = dict(np=np, math=math, time=time, route_support=route_support, - route_observation=route_observation, validate_orientation=lambda _: None, + route_observation=route_observation, validate_orientation=validate_orientation, + orientation_identity=orientation_identity, alignment_angle=lambda *args: None) exec(compile(ast.Module(body=[cls], type_ignores=[]), str(root / 'nav2/server.py'), 'exec'), scope) navigation = scope['Navigation'].__new__(scope['Navigation']) @@ -219,3 +221,44 @@ def test_planner_rejection_revokes_inflight_command_before_native_stop(moving_br result = navigation.tick(dict(pose=value['pose'], pose_age_seconds=0., measured_twist=[.4,0.,0.])) assert result == dict(speed_mps=0., yaw_rate_rps=0., reason='changed-path') assert seen == [None] + + +@pytest.mark.parametrize('changed', [False, True]) +def test_directional_route_translation_preserves_owner_but_turn_revokes_it(moving_bridge, changed): + navigation, value, _, seen = moving_bridge + orientation = dict(key='route-0-1', xy=[6., 0.], direction_xy=[1., 0.]) + navigation.path_context = navigation.forward_context(value, orientation) + # The rover moves one metre. Its six-metre bearing endpoint moves too. + # Repeated sensor refreshes must not cancel FollowPath or its live command. + value['orientation_target'] = {**orientation, 'xy': [7., 0.]} + if changed: + value['orientation_target'].update(xy=[1., 6.], direction_xy=[0., 1.]) + result = navigation.plan(value) + assert result['controller_generation'] == (8 if changed else 7) + assert seen[0]['continuing'] is (not changed) + assert (seen[0]['command'] is not None) is (not changed) + + +@pytest.mark.parametrize('direction', [None, [0., 0.], [2., 0.], [True, 0.], [float('nan'), 0.], [1.]]) +def test_orientation_direction_must_be_finite_unit_vector(bridge, direction): + navigation, _, value = bridge + value['orientation_target'] = dict(key='route-0-1', xy=[6., 0.], direction_xy=direction) + with pytest.raises(ValueError, match='orientation direction'): + navigation.plan(value) + + +@pytest.mark.parametrize('changed', [False, True]) +def test_view_spin_is_not_restarted_by_translated_direction_endpoint(moving_bridge, changed): + navigation, value, _, _ = moving_bridge + identity = navigation._plan.__globals__['orientation_identity'] + orientation = dict(key='route-0-1', xy=[6., 0.], direction_xy=[1., 0.]) + navigation.action_key = ('spin', *identity(orientation)) + calls = [] + navigation.node.spin = lambda *args: calls.append(args) + value.update(translation_allowed=False, + orientation_target={**orientation, 'xy': [7., 0.]}) + if changed: + value['orientation_target'].update(xy=[1., 6.], direction_xy=[0., 1.]) + result = navigation.plan(value) + assert len(calls) == int(changed) + assert result['controller_generation'] == (8 if changed else 7)