"""Bounded local HTTP adapter for the pinned CMU ROS 2 navigation nodes. Only simulated sensor observations enter ROS; no scene mesh or oracle route. The container is owned by one episode. A reset restarts all causal ROS state. """ import json import math import os import signal import subprocess import sys import threading import time from collections import OrderedDict from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path import numpy as np import rclpy from local_velocity_search import admit_forward_prefix from arrival_approach import ( ArrivalApproach, follower_stopped_short, admit_path_alignment, separate_counter_rotation, terminal_path_command, validate_orientation, ) from footprint import Footprint from command_status import command_failure from detection_obstacles import DetectionObstacles from geometry_msgs.msg import PointStamped, TwistStamped, PoseStamped from continuous_control import ContinuousControl from nav_msgs.msg import Odometry from nav_msgs.msg import Path as RosPath from observed_space import ObservedSpace from rcl_interfaces.srv import SetParameters from rclpy.node import Node from rclpy.parameter import Parameter from route_observation import route_observation from semantic_surface import SemanticSurface from sensor_msgs.msg import PointCloud2, PointField from sensor_msgs_py import point_cloud2 from std_msgs.msg import Float32, Header from support_policy import SupportPolicy from terrain_costs import TerrainCostNormalizer, underbody_support_costs from turn_staging import TurnStaging from arrival_search import ArrivalPoseSearch from support_obstacles import SupportObstacles from observed_ground import observed_ground_costs def execution_geometry(): path = os.environ.get("MISSIONCORE_RUN_INPUTS") if path: import hashlib inputs = json.loads(Path(path).read_text()) body = {k: v for k, v in inputs.items() if k != "sha256"} actual = hashlib.sha256( json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() ).hexdigest() if ( inputs["schema_version"] not in { "missioncore.simulation-inputs/v1", "missioncore.simulation-inputs/v2", "missioncore.simulation-inputs/v3", } or actual != inputs["sha256"] ): raise ValueError("Navigation execution inputs changed") if ( inputs["schema_version"] == "missioncore.simulation-inputs/v1" and "ground_contact" in inputs["robot"]["geometry"] ): raise ValueError("Contact geometry requires execution inputs v2") return ( inputs["robot"]["geometry"], inputs["sha256"], inputs["sensors"]["schema_version"] in {"missioncore.simulation-sensor-rig/v2", "missioncore.simulation-sensor-rig/v3", "missioncore.simulation-sensor-rig/v4"}, ) # Explicit compatibility for old lockstep/diagnostic callers only. Realtime # requires the run identity in /ready and cannot silently use this branch. legacy = Path(__file__).parents[1] / "robots/dcd006-v020.json" return json.loads(legacy.read_text())["physics"], None, False PROFILE, INPUTS_SHA256, MOUNTED_RIG = execution_geometry() # Nodes normalize /speed by maxSpeed, so its envelope must also follow the run. NAVIGATION_MAX_SPEED = max(1.0, float(json.loads(Path(os.environ["MISSIONCORE_RUN_INPUTS"]).read_text())["behavior"]["max_speed_mps"])) if INPUTS_SHA256 else 1.0 CONTINUOUS_RIG = bool(os.environ.get("MISSIONCORE_RUN_INPUTS") and json.loads(Path(os.environ["MISSIONCORE_RUN_INPUTS"]).read_text())["sensors"]["schema_version"] == "missioncore.simulation-sensor-rig/v4") CONTINUOUS_BODY_TOP = PROFILE["height_m"] if CONTINUOUS_RIG: mounts = json.loads(Path(os.environ["MISSIONCORE_RUN_INPUTS"]).read_text())["sensors"]["mounts"] CONTINUOUS_BODY_TOP = max(CONTINUOUS_BODY_TOP, *( float(spec.get("body_center_m", spec.get("origin_m"))[2]) + float(np.linalg.norm(spec["body_size_m"]))/2 for key, spec in mounts.items() if isinstance(spec, dict) and "body_size_m" in spec )) MONITOR = Footprint(PROFILE) DETECTIONS = DetectionObstacles(MONITOR) SUPPORT_POLICY = SupportPolicy(MONITOR, observed_pivots=MOUNTED_RIG, observed_approaches=CONTINUOUS_RIG, body_top_m=CONTINUOUS_BODY_TOP) MAX_STEP_M = PROFILE["max_step_m"] FOLLOWER_STOP_DISTANCE_M = 0.08 FOLLOWER_LOOKAHEAD_M = 0.7 def stamp_ns(stamp): return stamp.sec * 1_000_000_000 + stamp.nanosec def bind_maneuver(maneuver, pose, seconds): if maneuver is None: return None return { **maneuver, "observation": { "pose": pose.tolist(), "simulation_time_seconds": seconds, "execution_inputs_sha256": INPUTS_SHA256, }, } class Navigation(Node): def __init__(self): super().__init__("missioncore_navigation_adapter") self.condition = threading.Condition() self.plan_lock = threading.Lock() self.seen_semantics = OrderedDict() self.continuous_command = None self.processes = [] self.path = self.command = self.terrain = None self.terrain_geometry = None self.odom = self.create_publisher(Odometry, "/state_estimation", 5) self.scan = self.create_publisher(PointCloud2, "/registered_scan", 5) self.goal = self.create_publisher(PointStamped, "/way_point", 5) self.speed = self.create_publisher(Float32, "/speed", 5) self.obstacles = self.create_publisher(PointCloud2, "/added_obstacles", 5) self.surface = self.create_publisher(PointCloud2, "/terrain_map", 5) self.create_subscription(RosPath, "/path", self.on_path, 5) self.create_subscription(TwistStamped, "/cmd_vel", self.on_command, 5) self.create_subscription(PointCloud2, "/terrain_map_raw", self.on_terrain, 5) if CONTINUOUS_RIG: self.live_odom = self.create_publisher(Odometry, "/continuous_state", 1) self.live_path = self.create_publisher(RosPath, "/continuous_path", 1) self.create_subscription(TwistStamped, "/continuous_cmd_vel", self.on_continuous_command, 1) self.continuous = ContinuousControl(MONITOR, SUPPORT_POLICY, self.publish_continuous_pose, self.publish_continuous_path, lambda: self.continuous_command, body_top_m=CONTINUOUS_BODY_TOP) self.slope_corrected = 0 self.terrain_processing_ms = 0.0 self.normalize_costs = TerrainCostNormalizer() self.semantic_surface = SemanticSurface(retain_near=MOUNTED_RIG, fuse_observations=CONTINUOUS_RIG) self.observed_space = ObservedSpace(range_limits_m=( [mounts["k1"]["range_m"][1], 8.] if CONTINUOUS_RIG else None)) self.support_poses = OrderedDict() self.detection_observations = OrderedDict() self.arrival_goal = None # Search the complete mission acceptance region. Native braking is # handled by the guarded terminal approach; only the measured pose # and full-body support can actually satisfy the mission goal. self.arrival_search = ArrivalPoseSearch() # A measured support veto is a path constraint, not a soft preference: # search must go around it before the track reaches the rejected patch. # Use the same exclusion cost as semantics, so voxel aggregation does # not dilute it back below the obstacle threshold. This search-only # layer never changes physical geometry or the independent support fit. self.support_obstacles = SupportObstacles(1.0) self.terrain_search = None self.arrival_approach = ArrivalApproach() self.recovery_approach = ArrivalApproach() self.turn_staging = TurnStaging(MONITOR) self.motion_observation = None self.underbody_corrected = 0 self.direction = False self.direction_clients = [ self.create_client(SetParameters, f"/{name}/set_parameters") for name in ("localPlanner", "pathFollower") ] self.start_nodes() def start_nodes(self): common = dict( autonomyMode=True, autonomySpeed=0.3, maxSpeed=NAVIGATION_MAX_SPEED, twoWayDrive=False, joyToSpeedDelay=0.0, ) configs = [ ( "terrain_analysis", "terrainAnalysis", dict( scanVoxelSize=0.06, # ObservedSpace owns memory. CMU replaces staging clouds # per snapshot, without averaging old/fresh timestamps or # resurrecting points removed by valid free rays. inputIsMapSnapshot=True, decayTime=0.5, noDecayDis=0.0, useSorting=True, # Keep CMU's upstream ground quantile. Lower values make # shallow scan depressions the reference for the entire # 0.6 m neighbourhood; the median admits too much wall. quantileZ=0.25, considerDrop=True, clearDyObs=False, noDataObstacle=False, vehicleHeight=0.9, minRelZ=-2.0, maxRelZ=1.0, voxelPointUpdateThre=1, voxelTimeUpdateThre=0.0, ), ), ( "local_planner", "localPlanner", dict( **common, pathFolder="/opt/cmu/install/local_planner/share/local_planner/paths", # Match the final monitor's 5 cm margin on every side; # otherwise CMU repeatedly proposes a forbidden corner turn. vehicleLength=PROFILE["length_m"] + 0.1, vehicleWidth=PROFILE["width_m"] + 0.1, # Smooth obstacle cost across free space avoids choosing a # route along the emergency-clearance boundary. Scale with # the selected chassis; this is preference, not permission. **({"footprintClearanceScale": PROFILE["width_m"] / 2, "usePrefixGoalDirection": True} if CONTINUOUS_RIG else {}), useTerrainAnalysis=True, checkObstacle=True, # The pinned rectangular-filter image checks the complete # initial turn and primitive before selection. The upstream # angular wedge can wrongly exclude a clear straight escape # from an obstacle beside the rear corner. checkRotObstacle=False, adjacentRange=5.0, obstacleHeightThre=MAX_STEP_M, groundHeightThre=MAX_STEP_M * 0.8, costHeightThre=MAX_STEP_M * 0.8, useCost=True, pointPerPathThre=1, terrainVoxelSize=0.08, minRelZ=-0.5, maxRelZ=0.9, # Propose with a 56 cm half-width. The final swept square # check below covers front/rear corners and turning. pathScale=1.25, minPathScale=1.25, pathScaleBySpeed=False, pathRangeBySpeed=False, # Permit a safe short prefix when a full metre is obstructed. # The swept-body monitor still covers command latency and # braking; a prefix is not permission to cross its endpoint. # Upstream decrements range by 0.5 m by default, so merely # lowering the minimum skips every shorter candidate. minPathRange=0.2, pathRangeStep=0.1, dirThre=80.0, goalClearRange=0.0, ), ), ( "local_planner", "pathFollower", dict( **common, lookAheadDis=FOLLOWER_LOOKAHEAD_M, **({"usePurePursuit": True} if CONTINUOUS_RIG else {}), yawRateGain=2.0, stopYawRateGain=2.0, maxYawRate=20.0, maxAccel=0.4, dirDiffThre=0.3, # The follower sees the cropped local prefix, not the # mission endpoint. Do not stop before its 0.2 m minimum; # waypoint arrival and the braking monitor remain separate. stopDisThre=FOLLOWER_STOP_DISTANCE_M, slowDwnDisThre=0.7, useInclToStop=True, inclThre=30.0, stopTime=0.5, noRotAtGoal=True, pubSkipNum=0, ), ), ] for package, executable, parameters in configs: args = ["ros2", "run", package, executable, "--ros-args"] if executable == "terrainAnalysis": args += ["-r", "/terrain_map:=/terrain_map_raw"] for key, value in parameters.items(): args += ["-p", f"{key}:={str(value).lower() if isinstance(value, bool) else value}"] self.processes.append(subprocess.Popen(args, start_new_session=True)) if CONTINUOUS_RIG and executable == "pathFollower": follower = args + ["-r", "__node:=continuousFollower", "-r", "/state_estimation:=/continuous_state", "-r", "/path:=/continuous_path", "-r", "/cmd_vel:=/continuous_cmd_vel", "-p", "pathInMapFrame:=true"] self.processes.append(subprocess.Popen(follower, start_new_session=True)) def on_continuous_command(self, message): self.continuous_command = (time.monotonic(), message.twist.linear.x, message.twist.angular.z) def publish_continuous_pose(self, pose): odom = Odometry(header=Header(stamp=self.get_clock().now().to_msg(), frame_id="map"), child_frame_id="vehicle") odom.pose.pose.position.x, odom.pose.pose.position.y, odom.pose.pose.position.z = map(float, pose[:3]) q = odom.pose.pose.orientation q.x, q.y, q.z, q.w = map(float, pose[3:]) self.live_odom.publish(odom) def publish_continuous_path(self, points, pose): pose = np.asarray(pose) x, y, z, w = pose[3:] yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z)) rotation = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]]) message = RosPath(header=Header(stamp=self.get_clock().now().to_msg(), frame_id="map")) for point in points: item = PoseStamped(header=message.header) xy = np.asarray(point[:2]) @ rotation.T + pose[:2] item.pose.position.x, item.pose.position.y = map(float, xy) item.pose.position.z = float(pose[2]) item.pose.orientation.w = 1.0 message.poses.append(item) self.live_path.publish(message) def stop_nodes(self): for process in self.processes: if process.poll() is None: os.killpg(process.pid, signal.SIGTERM) for process in self.processes: try: process.wait(timeout=3) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait() self.processes.clear() def ready(self): return ( len(self.processes) == (4 if CONTINUOUS_RIG else 3) and all(p.poll() is None for p in self.processes) and self.odom.get_subscription_count() >= 3 and self.scan.get_subscription_count() >= 2 and all(client.service_is_ready() for client in self.direction_clients) and (not CONTINUOUS_RIG or ( self.live_odom.get_subscription_count() >= 1 and self.live_path.get_subscription_count() >= 1 and self.count_publishers("/continuous_cmd_vel") >= 1 )) ) def set_direction(self, reverse): if reverse == self.direction: return # Both nodes acknowledge the same permission before receiving this # observation. Rejecting negative speed after primitive selection is # too late: its preparatory turn can already point away from the goal. request = SetParameters.Request( parameters=[Parameter("twoWayDrive", value=reverse).to_parameter_msg()] ) self.direction = None futures = [client.call_async(request) for client in self.direction_clients] completed = threading.Event() for future in futures: future.add_done_callback(lambda _: completed.set()) deadline = time.monotonic() + 0.5 while not all(future.done() for future in futures): completed.wait(max(0, deadline - time.monotonic())) completed.clear() if time.monotonic() >= deadline: raise RuntimeError("navigation direction was not acknowledged") if not all(all(result.successful for result in f.result().results) for f in futures): raise RuntimeError("navigation direction was rejected") self.direction = reverse def on_path(self, message): with self.condition: self.path = ( stamp_ns(message.header.stamp), time.monotonic(), [[p.pose.position.x, p.pose.position.y, p.pose.position.z] for p in message.poses], ) self.condition.notify_all() def on_command(self, message): with self.condition: self.command = ( stamp_ns(message.header.stamp), time.monotonic(), message.twist.linear.x, message.twist.angular.z, ) self.condition.notify_all() def on_terrain(self, message): started = time.monotonic() points = point_cloud2.read_points_numpy( message, field_names=["x", "y", "z", "intensity"], skip_nans=True ).copy() points, corrected = self.normalize_costs(points) with self.condition: # CMU round-trips the stamp through double seconds. Match the same # sub-microsecond tolerance as the observation transaction below; # never substitute an unrelated latest pose for a delayed map. stamp = stamp_ns(message.header.stamp) support = next( ( value for key, value in reversed(self.support_poses.items()) if abs(key - stamp) <= 1000 ), None, ) detected = next((value for key, value in reversed(self.detection_observations.items()) if abs(key - stamp) <= 1000), np.empty((0, 3))) underbody = 0 if support is not None: points, underbody = underbody_support_costs(points, *support, geometry=PROFILE) if CONTINUOUS_RIG: points, patches = observed_ground_costs(points, *support, monitor=MONITOR) corrected += patches with self.condition: geometry = points.copy() if CONTINUOUS_RIG: if support is not None: self.support_obstacles.revalidate(points, *support, monitor=MONITOR) self.support_obstacles.observe_ahead(points, *support, monitor=MONITOR, speed_mps=NAVIGATION_MAX_SPEED) points = DETECTIONS.overlay(points, detected) points, semantic_forbidden = self.semantic_surface.apply(points, time.monotonic()) # Search feedback must not become physical collision evidence or # remove measured ground from the independent support assessment. # Semantic exclusions and detected objects remain hard costs in # BOTH layers. Bind any occupied-body hint exclusion to this exact # stamped observation, never to an unrelated latest pose. search_points = points if CONTINUOUS_RIG: search_points, _ = self.support_obstacles.apply(points, pose=support[0] if support is not None else None, monitor=MONITOR) fields = [ PointField(name=name, offset=i * 4, datatype=PointField.FLOAT32, count=1) for i, name in enumerate(("x", "y", "z", "intensity")) ] self.surface.publish(point_cloud2.create_cloud(message.header, fields, search_points)) with self.condition: self.terrain = (stamp_ns(message.header.stamp), len(points), points) self.terrain_geometry = geometry self.terrain_search = search_points self.slope_corrected = corrected self.underbody_corrected = underbody self.terrain_processing_ms = (time.monotonic() - started) * 1000 self.condition.notify_all() def plan(self, value): if not self.ready(): raise RuntimeError("navigation nodes are not ready") points = np.asarray(value["points"], dtype=np.float32) pose = np.asarray(value["pose"], dtype=np.float64) goal = np.asarray(value["goal"], dtype=np.float64) speed = float(value["max_speed_mps"]) reverse = value.get("allow_reverse", False) arrival_target = value.get("arrival_target") orientation = validate_orientation(value.get("orientation_target")) recovery_orientation = value.get("recovery_orientation", False) if type(recovery_orientation) is not bool: raise ValueError("Invalid recovery orientation") translation_allowed = value.get("translation_allowed", True) goal_from_visual = value.get("visual_goal_available", False) if type(goal_from_visual) is not bool: raise ValueError("Invalid visual-goal provenance") if type(translation_allowed) is not bool: raise ValueError("Invalid translation permission") contact_height = float(value.get("body_contact_height_m", 0.37)) if ( points.ndim != 2 or points.shape[1] != 3 or not 50 <= len(points) <= 30000 or pose.shape != (7,) or goal.shape != (3,) or not math.isfinite(speed) or not 0 <= speed <= NAVIGATION_MAX_SPEED or not isinstance(reverse, bool) or not math.isfinite(contact_height) or not 0.1 <= contact_height <= 1.0 or not all(np.isfinite(v).all() for v in (points, pose, goal)) or abs(float(np.linalg.norm(pose[3:])) - 1) > 0.01 ): raise ValueError("invalid range/odometry contract") detected = DETECTIONS.observed(value) if value.get("detection_age_seconds", 0) > DETECTIONS.deadline_seconds: return dict(speed_mps=0.0, yaw_rate_rps=0.0, status="blocked", path=[], diagnostic={"failure": "stale-detection"}) original_orientation = orientation simulation_time = float(value.get("simulation_time_seconds", 0)) if not math.isfinite(simulation_time) or simulation_time < 0: raise ValueError("Invalid observation time") stationary = False if self.motion_observation is not None: previous_pose, previous_time = self.motion_observation dt = simulation_time - previous_time stationary = ( 0 < dt <= 0.8 and np.linalg.norm(pose[:2] - previous_pose[:2]) <= 0.025 * dt ) self.motion_observation = (pose.copy(), simulation_time) maneuver = ( self.turn_staging.current(pose, orientation, simulation_time) if MOUNTED_RIG else None ) staging = maneuver is not None if staging: goal = np.asarray(maneuver["goal"]) orientation = {"key": orientation["key"] + "-stage", "xy": goal[:2].tolist()} translation_allowed, arrival_target, reverse = True, None, False speed = min(speed, 0.1) goal_from_visual = False if arrival_target is not None: arrival_target = np.asarray(arrival_target, dtype=float) simulation_time = float(value["simulation_time_seconds"]) if ( not math.isfinite(simulation_time) or simulation_time < 0 or arrival_target.shape != (2,) or not np.isfinite(arrival_target).all() or np.linalg.norm(arrival_target - pose[:2]) > 3.5 ): raise ValueError("invalid arrival candidate") if arrival_target is None: self.arrival_goal = None else: if ( self.arrival_goal is not None and self.arrival_goal["target_xy"] != arrival_target.tolist() ): self.arrival_goal = None if ( self.arrival_goal is not None and self.arrival_goal.get("kind") == "observed-approach" and np.linalg.norm(np.asarray(self.arrival_goal["goal"][:2]) - pose[:2]) <= 2 * FOLLOWER_STOP_DISTANCE_M ): # Replan a short observed placement; its follower stop disk # never stands in for the still-unreached mission target. self.arrival_goal = None # Once body-goal admission starts, visual intermediate goals cannot # steer past the task region. Preserve its identity until completion # or explicit rejection by a new observation. if self.arrival_goal is not None: goal = np.asarray(self.arrival_goal["goal"], dtype=float) goal_from_visual = False elif not goal_from_visual: goal = np.array([*arrival_target, goal[2]]) self.set_direction(reverse) memory_started = time.monotonic() rays = value.get("range_rays") or {} current_points = points points = self.observed_space.observe( points, pose, memory_started, rays.get("origins"), rays.get("ends"), rays.get("origin_indices"), range_views=rays, ) memory_metrics = { **self.observed_space.metrics, "processing_ms": (time.monotonic() - memory_started) * 1000, } header = Header(stamp=self.get_clock().now().to_msg(), frame_id="map") identity = stamp_ns(header.stamp) with self.condition: self.semantic_surface.observe(value.get("semantic_points", []), time.monotonic(), pose) for sample in value.get("semantic_observations", []): age = float(sample["age_seconds"]) if not math.isfinite(age) or age < 0: raise ValueError("Invalid semantic capture age") if sample["frame_id"] not in self.seen_semantics: self.semantic_surface.observe(sample["samples"], time.monotonic()-age, pose, evidence_id=sample.get("capture_id", sample["frame_id"])) self.seen_semantics[sample["frame_id"]] = True while len(self.seen_semantics) > 128: self.seen_semantics.popitem(last=False) self.support_poses[identity] = (pose.copy(), contact_height) self.detection_observations[identity] = detected while len(self.support_poses) > 8: self.support_poses.popitem(last=False) while len(self.detection_observations) > 8: self.detection_observations.popitem(last=False) odom = Odometry(header=header, child_frame_id="vehicle") odom.pose.pose.position.x, odom.pose.pose.position.y, odom.pose.pose.position.z = map( float, pose[:3] ) q = odom.pose.pose.orientation q.x, q.y, q.z, q.w = map(float, pose[3:]) target = PointStamped(header=header) target.point.x, target.point.y, target.point.z = map(float, goal) fields = [ PointField(name=n, offset=i * 4, datatype=PointField.FLOAT32, count=1) for i, n in enumerate(("x", "y", "z", "intensity")) ] cloud = point_cloud2.create_cloud( header, fields, np.column_stack((points, np.zeros(len(points), np.float32))) ) # The single HTTP writer establishes one observation transaction. self.goal.publish(target) self.speed.publish(Float32(data=speed)) self.odom.publish(odom) self.scan.publish(cloud) with self.condition: fresh = self.condition.wait_for( lambda: ( self.path is not None and abs(self.path[0] - identity) <= 1000 and self.command is not None and abs(self.command[0] - identity) <= 1000 and self.command[1] >= self.path[1] and self.terrain is not None and abs(self.terrain[0] - identity) <= 1000 ), # R26's accumulated 26k-point map needs ~0.33 s. Returning at # 0.3 s perpetually abandons each matching observation just # before its terrain/path arrives. Wait for that transaction, # bounded below the independent 0.8 s camera deadman. A late # result is still rejected by LatestInference, never reused. timeout=0.6, ) if not fresh: return { "speed_mps": 0.0, "yaw_rate_rps": 0.0, "status": "waiting-for-plan", "path": [], "maneuver": bind_maneuver(maneuver, pose, simulation_time), "pending": { "path_stamp_delta_ns": None if self.path is None else self.path[0] - identity, "command_stamp_delta_ns": None if self.command is None else self.command[0] - identity, "terrain_stamp_delta_ns": None if self.terrain is None else self.terrain[0] - identity, "path_points": None if self.path is None else len(self.path[2]), "terrain_processing_ms": self.terrain_processing_ms, "terrain_points": None if self.terrain is None else self.terrain[1], }, **( {"observed_terrain": self.terrain[2].tolist()} if value.get("include_terrain") is True and self.terrain is not None else {} ), } path, command = self.path, self.command route_evidence = route_observation(self.terrain[2], pose, value, MAX_STEP_M) if staging and not self.turn_staging.confirm_surface( self.terrain[2], self.semantic_surface.permitted_terrain(self.terrain[2], time.monotonic()), pose, contact_height, ): return { "speed_mps": 0.0, "yaw_rate_rps": 0.0, "status": "waiting-for-plan", "path": [], "route_observation": route_evidence, "maneuver": bind_maneuver(self.turn_staging.active, pose, simulation_time), "diagnostic": { "failure": self.turn_staging.transition if self.turn_staging.active is None else "turn-placement-needs-surface-view", "placement_hazards": [ { "point": point.tolist(), "geometry_cost": float(geometry[3]), "semantic_cell": self.semantic_surface.cells.get( tuple(self.semantic_surface.cell_keys(point[None])[0]) ), } for point, geometry in zip( self.terrain[2], self.terrain_geometry, strict=True ) if point[3] > MAX_STEP_M + 1e-4 and np.linalg.norm(point[:2] - np.asarray(maneuver["goal"][:2])) < 0.8 ][:16], }, } valid = len(path[2]) > 1 and all(math.isfinite(v) for v in command[2:]) velocity = max(-speed, min(speed, command[2])) if valid else 0.0 yaw_rate = command[3] if valid else 0.0 orientation_controller = self.recovery_approach if recovery_orientation else self.arrival_approach velocity, yaw_rate, approach = orientation_controller.command( pose, orientation, float(value.get("simulation_time_seconds", 0)), velocity, yaw_rate, enabled=not reverse, ) orienting = approach["phase"] in {"braking", "aligning"} # A pivot can acquire a view before a path exists. It has zero # translation and still needs the full sensor-based sweep below. valid = orienting or (valid and translation_allowed) arrival = None terminal_proposal = None destination_pending = False if arrival_target is not None and not orienting: # Completion within an entered task region requires geometric # support and retains all known semantic barriers. Acquiring a # blind-strip destination outside it also requires positive # semantic evidence over all selected ground contact patches. # Chassis collision clearance remains independent and full-body. inside_arrival = np.linalg.norm(arrival_target - pose[:2]) <= 0.4 support = ( None if inside_arrival else self.semantic_surface.permitted_terrain(self.terrain[2], time.monotonic()) ) arrival = MONITOR.assess_pose( self.terrain[2], pose, contact_height, support_terrain=support ) arrival["observation"] = { "pose": pose.tolist(), "target_xy": arrival_target.tolist(), "simulation_time_seconds": simulation_time, "execution_inputs_sha256": value["execution_inputs_sha256"], } # Assessment uses this transaction's terrain and exact pose; # a point inside the arrival circle cannot bypass the body. arrival["positive_surface_required"] = not inside_arrival if arrival["admitted"] and inside_arrival: return { "speed_mps": 0.0, "yaw_rate_rps": 0.0, "status": "arrival-accepted", "route_observation": route_evidence, "path": [], "arrival": arrival, } # Keep approaching only an observed body-sized destination. # This guard grants no route: the existing swept command and # direction checks must still admit every actual command. destination = pose.copy() destination[:2] = goal[:2] # Goal Z is observed ground; retain the measured body attitude. up_z = 1 - 2 * (pose[3] ** 2 + pose[4] ** 2) destination[2] = goal[2] + contact_height / max(up_z, 0.1) arrival["destination"] = MONITOR.assess_pose( self.terrain[2], destination, contact_height, support_terrain=support ) if valid and arrival["destination"]["admitted"]: terminal_proposal = terminal_path_command( pose, goal, path[2], command[2:], stop_distance=FOLLOWER_STOP_DISTANCE_M, maximum_speed=speed, command_bounds=MONITOR.command_bounds, ) # CMU stops within a disk around its target. A supported target # does not certify the different measured pose in that disk. # If it holds there without body admission, select another # observed destination outside the old stopping disk. Keep the # same mission region and finite recovery/progress budget. follower_at_goal = terminal_proposal is None and follower_stopped_short( pose, goal, command[2:], arrival_complete=arrival["admitted"] and inside_arrival, stop_distance=FOLLOWER_STOP_DISTANCE_M, ) if not arrival["destination"]["admitted"] or follower_at_goal: candidate = MONITOR.find_arrival_pose( self.terrain[2], pose, arrival_target, contact_height, support_terrain=support, minimum_translation_m=2 * FOLLOWER_STOP_DISTANCE_M if follower_at_goal else 0.0, refinement=self.arrival_search, ) intermediate = False if candidate is None and MOUNTED_RIG and not inside_arrival and not reverse: candidate = MONITOR.find_observed_approach( self.terrain[2], pose, arrival_target, contact_height, support_terrain=support, minimum_translation_m=2 * FOLLOWER_STOP_DISTANCE_M, ) intermediate = candidate is not None self.arrival_goal = None if candidate is not None: candidate_up_z = 1 - 2 * (candidate[3] ** 2 + candidate[4] ** 2) self.arrival_goal = { "target_xy": arrival_target.tolist(), "goal": [ *candidate[:2], candidate[2] - contact_height / candidate_up_z, ], **({"kind": "observed-approach"} if intermediate else {}), } # A distant stopping footprint is not the current command # sweep. An unchanged visual goal may retain its freshly # computed local prefix while destination admission is # pending. It receives NO body receipt or new capture age; # every existing sweep/fresh-track/unknown limit below and # the visual intent deadman still apply. Inside the actual # task region only the full body admission can complete it. destination_pending = bool( candidate is None and MOUNTED_RIG and goal_from_visual and valid and not inside_arrival and not reverse and not follower_at_goal ) if candidate is None and not destination_pending and MOUNTED_RIG and stationary: maneuver = self.turn_staging.propose( self.terrain[2], None, pose, original_orientation, simulation_time, contact_height, ) if not destination_pending: return { "speed_mps": 0.0, "yaw_rate_rps": 0.0, "status": "waiting-for-plan" if candidate is not None else "blocked", "route_observation": route_evidence, "path": [], "arrival": arrival, "arrival_goal": self.arrival_goal, "maneuver": bind_maneuver(maneuver, pose, simulation_time), "diagnostic": { "failure": "goal-body-support", "follower_at_goal": bool(follower_at_goal), "turn_placement_candidates": self.turn_staging.candidates if MOUNTED_RIG else [], }, } if not destination_pending: self.arrival_goal = { "target_xy": arrival_target.tolist(), "goal": goal.tolist(), **( {"kind": "observed-approach"} if self.arrival_goal is not None and self.arrival_goal.get("kind") == "observed-approach" else {} ), } if (staging and valid and not orienting and maneuver.get("positive_surface_admitted")): # A turn placement has the same native stopping disk as a # mission destination. Stopping short must not strand the body # before the measured pose can admit its turn. confirm_surface # already rechecked the complete destination this transaction; # the terminal proposal still needs every live sweep gate. terminal_proposal = terminal_path_command( pose, goal, path[2], command[2:], stop_distance=FOLLOWER_STOP_DISTANCE_M, maximum_speed=speed, command_bounds=MONITOR.command_bounds, ) if terminal_proposal is not None: velocity, yaw_rate, _ = terminal_proposal local_turn = None if MOUNTED_RIG and MONITOR.contacts is not None and not reverse: velocity, yaw_rate, local_turn = separate_counter_rotation( velocity, yaw_rate, [(low[1] + high[1]) / 2 for low, high in MONITOR.contacts.bands], stationary=stationary, ) local_pivot = local_turn is not None or (abs(velocity) < 1e-8 and abs(yaw_rate) > 1e-8) if MOUNTED_RIG and abs(velocity) < 1e-8 and abs(yaw_rate) > 1e-8: limit = SUPPORT_POLICY.partial_yaw_rps yaw_rate = max(-limit, min(limit, yaw_rate)) if stationary else 0.0 # Reverse is admitted only by the composed recovery policy after # observing full-width support. Bound heading changes to that strip. direction_clear = velocity <= 0 and abs(yaw_rate) <= 0.15 if reverse else velocity >= 0 velocity, yaw_rate, command_scale = ( MONITOR.regulate_command(velocity, yaw_rate, self.terrain[2], pose) if valid and direction_clear else (0.0, 0.0, 0.0) ) footprint_clear = command_scale > 0 # Assess the actual obstacle-regulated command. Fresh returns are # kept separate from causal memory: old ground cannot excuse loss # of current view. Unknown cells remain unknown after regulation. velocity, yaw_rate, support_scale, motion_support = SUPPORT_POLICY.regulate( velocity, yaw_rate, self.terrain[2], pose, contact_height, current_points=current_points, ) if (CONTINUOUS_RIG and valid and direction_clear and (command_scale == 0 or support_scale == 0)): alignment = admit_path_alignment( path[2], MONITOR, SUPPORT_POLICY, self.terrain[2], pose, contact_height, current_points, stationary=stationary, reverse=reverse, orienting=orienting, lookahead_m=FOLLOWER_LOOKAHEAD_M) if alignment is not None: velocity, yaw_rate, command_scale, support_scale, motion_support, detail = alignment approach = {**approach, **detail} footprint_clear, local_pivot = True, True if (CONTINUOUS_RIG and valid and translation_allowed and (command_scale == 0 or support_scale == 0 or (local_pivot and not stationary)) and not orienting and not reverse): forward = admit_forward_prefix(path[2], MONITOR, SUPPORT_POLICY, self.terrain[2], pose, contact_height, current_points, lookahead_m=FOLLOWER_LOOKAHEAD_M, maximum_speed=speed) if forward is not None: velocity, yaw_rate, command_scale, support_scale, motion_support, local_turn = forward footprint_clear, direction_clear = True, True motion_support["observation"] = { "pose": pose.tolist(), "simulation_time_seconds": value.get("simulation_time_seconds"), "execution_inputs_sha256": value["execution_inputs_sha256"], } if CONTINUOUS_RIG: # Keep this transaction's veto. On the next observation CMU # sees measured non-traversable patches as costs and can choose a # different primitive instead of repeating the rejected arc. self.support_obstacles.observe( motion_support.get("roughness_obstacles_xyz", []), self.terrain[2]) self.support_obstacles.observe_patches( motion_support.get("support_obstacle_samples", []), self.terrain[2]) velocity, yaw_rate, detection_scale = DETECTIONS.regulate( velocity, yaw_rate, detected, pose) valid = (valid and footprint_clear and direction_clear and support_scale > 0 and detection_scale > 0) qx, qy, qz, qw = pose[3:] tilt = math.degrees(math.acos(max(-1, min(1, 1 - 2 * (qx * qx + qy * qy))))) failure = command_failure( tilt=tilt, orienting=orienting, translation_allowed=translation_allowed, path_points=len(path[2]), footprint_clear=footprint_clear, direction_clear=direction_clear, support_scale=support_scale, support_reason=motion_support["policy"]["reason"], velocity=velocity, yaw_rate=yaw_rate, ) if detection_scale == 0 and failure in {"none", "controller-hold"}: failure = "detected-object-sweep" if MOUNTED_RIG and not staging and orienting and support_scale == 0 and stationary: maneuver = self.turn_staging.propose( self.terrain[2], None, pose, original_orientation, simulation_time, contact_height, ) maneuver = bind_maneuver(maneuver, pose, simulation_time) obstacles = self.terrain[2][self.terrain[2][:, 3] > MAX_STEP_M] distances = np.linalg.norm(obstacles[:, :2] - pose[:2], axis=1) near = obstacles[np.argsort(distances)[:12]] return { "speed_mps": velocity if valid else 0.0, "yaw_rate_rps": max(-0.8, min(0.8, yaw_rate)) if valid else 0.0, "status": "path" if valid else "blocked", "route_observation": route_evidence, # This path also feeds the independent live follower. Dropping # samples here (especially the endpoint) changes its stopping # distance and curvature relative to the planning follower. "path": path[2], "terrain_points": self.terrain[1], "maneuver": maneuver, "footprint_clear": bool(footprint_clear), "path_frame": "vehicle-yaw", **( {"arrival": arrival, "arrival_goal": self.arrival_goal} if arrival is not None else {} ), "diagnostic": { "failure": failure, "tilt_degrees": tilt, "controller_command": list(command[2:]), "arrival_approach": approach, "local_turn": local_turn, "terminal_approach": terminal_proposal[2] if terminal_proposal else None, "destination_admission_pending": destination_pending, "near_obstacles": near.tolist(), "slope_corrected_points": self.slope_corrected, "underbody_support_points": self.underbody_corrected, "terrain_processing_ms": self.terrain_processing_ms, "command_scale": command_scale, "detected_object_points": len(detected), "detection_command_scale": detection_scale, "motion_support": motion_support, "range_memory": memory_metrics, "turn_placement_candidates": self.turn_staging.candidates if MOUNTED_RIG else [], }, # Engineering replay only; this local endpoint never forwards # dense geometry to the operator or changes the control input. **( {"observed_terrain": self.terrain[2].tolist()} if value.get("include_terrain") is True else {} ), } def main(): # All ROS traffic stays inside this container. Avoid persistent Fast DDS # shared-memory segments across causal node resets on Docker/WSL. os.environ["FASTRTPS_DEFAULT_PROFILES_FILE"] = str(Path(__file__).with_name("fastdds.xml")) rclpy.init() node = Navigation() thread = threading.Thread(target=rclpy.spin, args=(node,), daemon=True) thread.start() class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" # Tiny control replies must not wait for delayed ACK between their # headers and JSON body. Each connection remains keep-alive and bounded. disable_nagle_algorithm = True def reply(self, status, value): body = json.dumps(value, allow_nan=False).encode() self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def do_GET(self): if self.path == "/diagnostic-snapshot" and CONTINUOUS_RIG: # Read-only, bounded to the latest transaction. Never insert # diagnostic material back into the causal observation stream. with node.plan_lock: exchange = node.continuous.snapshot() with node.condition: geometry = (node.terrain_geometry.tolist() if node.terrain_geometry is not None else []) search = (node.terrain_search.tolist() if node.terrain_search is not None else []) self.reply(200, dict(schema_version="missioncore.navigation-diagnostic/v1", authority="none", execution_inputs_sha256=INPUTS_SHA256, exchange=exchange, geometry=geometry, search=search)) return self.reply( 200 if self.path == "/ready" and node.ready() else 503, { "ready": node.ready(), "execution_inputs_sha256": INPUTS_SHA256, "robot_geometry": PROFILE, }, ) def do_POST(self): try: size = int(self.headers.get("Content-Length", "0")) if not 0 < size <= 3_000_000: raise ValueError("bounded JSON body required") value = json.loads(self.rfile.read(size)) if self.path == "/reset": node.stop_nodes() self.reply(200, {"reset": True}) # Reset DDS publishers/subscribers as well as child nodes. # Replacing PID 1 preserves container ownership and clears # all cached graph/history state before the next observation. os.execv(sys.executable, [sys.executable, str(Path(__file__).resolve())]) elif self.path == "/plan": if value.get("execution_inputs_sha256") != INPUTS_SHA256: raise ValueError("Navigation execution input identity mismatch") with node.plan_lock: if value.get("continuous"): if not CONTINUOUS_RIG: raise ValueError("Continuous input requires the v4 rig") node.continuous.observe(value) result = node.plan(value) if value.get("continuous"): node.continuous.accept(value, result, node.terrain[2] if node.terrain is not None else []) # Bounded engineering snapshots must also cover rejected # arrivals. Successful-path-only traces hid the terrain # responsible for a stop. Never expose these in the UI or # feed them back into the observation stream. if value.get("include_terrain") is True: with node.condition: if node.terrain is not None: now = time.monotonic() result["observation_debug"] = { "terrain_stamp_ns": node.terrain[0], "geometry": node.terrain_geometry.tolist(), "terrain": node.terrain[2].tolist(), "permitted": node.semantic_surface.permitted_terrain( node.terrain[2], now ).tolist(), "semantic_cells": node.semantic_surface.snapshot(now), "semantic_cell_size_m": node.semantic_surface.cell_size.tolist(), "semantic_cell_columns": ["x", "y", "z", "permitted", "age_seconds"], } self.reply(200, result) elif self.path == "/control" and CONTINUOUS_RIG: if value.get("execution_inputs_sha256") != INPUTS_SHA256: raise ValueError("Continuous execution identity mismatch") self.reply(200, node.continuous.tick(value)) else: self.reply(404, {"error": "unknown endpoint"}) except (ValueError, KeyError, TypeError) as exc: self.reply(400, {"error": str(exc)}) except Exception as exc: self.reply(503, {"error": str(exc)}) def log_message(self, *_): pass try: ThreadingHTTPServer(("0.0.0.0", 8010), Handler).serve_forever() finally: node.stop_nodes() rclpy.shutdown() if __name__ == "__main__": main()