"""Mission Core transport for upstream Nav2 and the existing observed terrain. No scene geometry, global route invention or alternative velocity controller. The HTTP interface stays compatible with the run-owned simulation pipeline. """ import json import math import os import signal import subprocess import sys import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path import numpy as np import rclpy import yaml from action_msgs.msg import GoalStatus from configuration import observed_configuration 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 from navigation.support_policy import SupportPolicy from observed_collision import ObservedCollision from rig_collision import collision_geometry from route_support import route_support from ros_navigation import RosNavigation, yaw_of from std_srvs.srv import Trigger from terrain_process import TerrainProcess class Navigation: def __init__(self, node, inputs, robot): self.node, self.inputs = node, inputs self.geometry = collision_geometry(inputs['robot']['geometry'], inputs['sensors']['mounts']) self.monitor = Footprint(self.geometry, deceleration=robot['control']['deceleration_mps2']) self.support = SupportPolicy(self.monitor, observed_pivots=True, observed_approaches=True, body_top_m=self.geometry['collision_top_m']) self.terrain = TerrainProcess(self.geometry, robot['control']['deceleration_mps2'], inputs['robot']['geometry'], range_limits_m=[ inputs['sensors']['mounts']['k1']['range_m'][1], 8.]) self.collision = ObservedCollision(node, self.monitor.max_step, 2) self.plan_lock, self.owner_lock = threading.Lock(), threading.Lock() self.action_key = None self.command_generation = 0 self.path_context = None self.completed_orientation = None self.path = None self.path_planned_at = float('-inf') self.active, self.failure = False, None self.activating = False self.latest_terrain = None self.latest_exchange = None self.control = ContinuousControl(self.monitor, self.support, lambda _:None, lambda *_:None, self.native_command, body_top_m=self.geometry['collision_top_m'], native_only=True) def activate(self): try: self.node.activate() self.active = True except BaseException as error: self.failure = type(error).__name__+': '+str(error) def native_command(self): with self.control.lock: plan = self.control.plans.get(self.control.path_id) with self.owner_lock: if plan is None or plan['result'].get('controller_generation') != self.command_generation: return None return self.node.native_command() def tick(self, value): self.node.observe_pose(value['pose'], float(value['pose_age_seconds']), value['measured_twist'], value.get('pose_simulation_time_ns')) with self.owner_lock: owner = self.command_generation result = self.control.tick(value) with self.owner_lock: if owner != self.command_generation: result.update(speed_mps=0., yaw_rate_rps=0., reason='changed-path') return result def revoke_command(self): with self.owner_lock: self.command_generation += 1 self.action_key = None def stop(self): self.revoke_command() self.node.stop() @staticmethod def forward_context(value, orientation): # Only refinements within the same ordinary route leg may share a # native command stream. Recovery, an unbound intent, a changed speed # limit or terminal placement all require a new action/feedback fence. if (orientation is None or value.get('recovery_orientation', False) or not value.get('continuous', False)): return None target = value.get('arrival_target') 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): return dict(speed_mps=0., yaw_rate_rps=0., status=status, path=[], diagnostic=dict(failure=reason), **extra) def completed_action(self, key, route): terminal = self.node.terminal if (key == self.action_key and key[0] in {'path', 'backup'} and terminal is not None and terminal.done() and terminal.result().status in (GoalStatus.STATUS_SUCCEEDED, GoalStatus.STATUS_ABORTED)): # Preserve the native terminal result before a sensor refresh can # submit the same FollowPath again. This is local-action completion, # not whole-body arrival admission and never a motion proposal. succeeded = terminal.result().status == GoalStatus.STATUS_SUCCEEDED return self.reply('native-action-complete' if succeeded else 'native-action-aborted', status='waiting-for-plan' if succeeded else 'blocked', route_observation=route, action_result=dict(status='succeeded' if succeeded else 'aborted', kind=key[0], goal_xy=list(key[1]))) return None def plan(self, value): # Transaction-local metadata cannot survive a stale/failed observation. receipts = {} result = {**self._plan(value, receipts), **receipts} self.latest_exchange = dict(request=value, result=result) return result def _plan(self, value, receipts): entered = time.monotonic() if self.failure: raise RuntimeError(self.failure) pose, goal = np.asarray(value['pose'], dtype=float), np.asarray(value['goal'], dtype=float) limit, age = float(value['max_speed_mps']), float(value['geometry_age_seconds']) if (pose.shape != (7,) or goal.shape != (3,) or not np.isfinite(pose).all() or not np.isfinite(goal).all() or not math.isfinite(limit) or not 0 <= limit <= self.inputs['behavior']['max_speed_mps'] or not math.isfinite(age) or age < 0 or type(value['allow_reverse']) is not bool or type(value['translation_allowed']) is not bool): raise ValueError('Invalid navigation request') if age > .8 or value['detection_age_seconds'] > 2.: return self.reply('stale-observation') self.control.observe(value) if self.node.pose is None: self.node.observe_pose(value['pose'], age, None, round(value['simulation_time_seconds']*1e9)) # TF only. if not self.activating: self.activating = True threading.Thread(target=self.activate, daemon=True).start() if not self.active or self.node.pose is None or self.node.pose[2] is None: return self.reply('waiting-for-measured-controller-state') if time.monotonic()-self.node.pose[0] > .5: return self.reply('stale-pose') observed = self.terrain.observe(value) terrain = observed['terrain'] self.latest_terrain = observed observed['observation_id'] = value['observation_id'] if not self.collision.publish(value, observed['collision_terrain'], time.monotonic()-entered, search_terrain=observed['search_terrain'], detected=observed['detected']): return self.reply('stale-range') route = route_observation(terrain, pose, value, self.monitor.max_step) # Centre between observed solids, including unlabelled ones. Search # hints for rejected contact patches are not objects: assigning their # nearest return an obstacle radius moves the local endpoint across a # clear passage as patch queries change. Smac still receives the full # search layer; semantic/contact gates still admit every actual sweep. hazards = observed['collision_terrain'] hazards = hazards[hazards[:, 3] > self.monitor.max_step + 1e-4, :2] if len(hazards): _, indices = np.unique(np.floor(hazards / .05), axis=0, return_index=True) hazards = hazards[np.sort(indices)] receipts['clearance_observation'] = dict( observation=route['observation'], obstacles_xy=hazards.tolist()) support = route_support(self.monitor, observed, value, self.inputs) if support is not None: receipts["route_support"] = support orientation = validate_orientation(value.get('orientation_target')) target = value.get('arrival_target') if target is not None: if len(target) != 2 or not all(math.isfinite(x) for x in target): raise ValueError('Invalid arrival target') if math.dist(pose[:2], target) <= self.inputs['mission']['arrival_radius_m']: assessment = self.monitor.assess_pose(terrain, pose, value['body_contact_height_m']) if assessment['admitted']: self.stop() return self.reply('arrival', status='arrival-accepted', arrival={**assessment, 'observation':dict(pose=pose.tolist(), target_xy=list(target), simulation_time_seconds=value['simulation_time_seconds'], execution_inputs_sha256=self.inputs['sha256'])}) if not value.get('visual_goal_available'): goal[:2] = target reverse = value['allow_reverse'] 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): self.completed_orientation = orientation_key # Smac plans from the measured heading. A destination bearing is not # a path tangent or evidence of reachability, including after a failed # action. Never turn toward an unplanned translation goal. DWB retains # differential steering/pivots while following a feasible native path; # separate Spin is reserved for an explicit non-translating survey. following = (self.action_key is not None and self.action_key[0] == 'path' and self.node.terminal is not None and not self.node.terminal.done()) orienting = (not reverse and orientation is not None and orientation_key != self.completed_orientation and not value['translation_allowed']) if not value['translation_allowed'] and not orienting: self.stop() return self.reply('no-permitted-goal', status='blocked', route_observation=route) if orienting: delta = np.asarray(orientation['xy'])-pose[:2] heading = math.atan2(delta[1], delta[0]) angle = math.atan2(math.sin(heading-yaw_of(pose)), math.cos(heading-yaw_of(pose))) key = orientation_key if key != self.action_key: self.revoke_command() # Existing mission budgets use simulation time. Do not invent # a second wall-clock maneuver budget in a slower simulation. # The unchanged command/data leases still gate every output. self.node.spin(angle, 0.) local_path = [[0.,0.,0.],[0.,0.,0.]] elif reverse: key = ('backup', tuple(goal[:2]), limit) completed = self.completed_action(key, route) if completed is not None: return completed delta = goal[:2]-pose[:2] heading = yaw_of(pose) rear = -float(delta @ [math.cos(heading), math.sin(heading)]) if rear <= 0: self.stop() return self.reply('reverse-goal-is-not-behind', status='blocked') if key != self.action_key: self.revoke_command() self.node.backup(rear, min(limit,.1), 0.) local_path = [[0.,0.,0.],[-rear,0.,0.]] else: # Local endpoint refinements can share one route command stream. # A different route/recovery context gets a fresh feedback fence; # every tick still uses its capture leases and raw range gates. key = ('path', tuple(goal[:2]), limit) completed = self.completed_action(key, route) if completed is not None: return completed context = self.forward_context(value, orientation) continuing = ((key == self.action_key and context == self.path_context) or (following and context is not None and context == self.path_context)) # Match the pinned Nav2 BT's 1 Hz ComputePathToPose cadence. # The path is an intent, not a sensor sample: terrain, costmaps, # capture leases and command gates still refresh above/every tick. if (key != self.action_key or not continuing or self.path is None or self.node.native_command() is None or entered-self.path_planned_at >= 1.0): path, status = self.node.plan(pose, goal, math.atan2(goal[1]-pose[1],goal[0]-pose[0])) if path is None or len(path.poses) < 2: native = self.node.native_command() # A rejected extension does not invalidate the executing # path. Never restart it or recycle its old velocity: keep # only a live same-leg action, admitted below against this # observation and against current range on every tick. if (status == GoalStatus.STATUS_ABORTED and following and continuing and context is not None and value.get('arrival_target') is None and key != self.action_key and self.path is not None and len(self.path.poses) >= 2 and self.node.terminal is not None and not self.node.terminal.done() and native is not None and time.monotonic()-native[0] <= .25): receipts['refinement_result'] = dict(status='aborted', goal_xy=goal[:2].tolist(), executing_goal_xy=list(self.action_key[1])) key = self.action_key else: self.stop() # Humble has no typed planner error code. Preserve its # terminal abort without inventing an obstacle diagnosis. feedback = (dict(planning_result=dict(status='aborted', goal_xy=goal[:2].tolist())) if status == GoalStatus.STATUS_ABORTED else {}) return self.reply('no-path', status='blocked', route_observation=route, **feedback) else: if not continuing: self.revoke_command() self.node.follow(path, continuing=continuing) self.path, self.path_planned_at = path, entered self.path_context = context path = self.path c, s = math.cos(yaw_of(pose)), math.sin(yaw_of(pose)) local_path = [[(p.pose.position.x-pose[0])*c+(p.pose.position.y-pose[1])*s, -(p.pose.position.x-pose[0])*s+(p.pose.position.y-pose[1])*c, 0.] for p in path.poses] with self.owner_lock: self.action_key = key completed = self.completed_action(key, route) if completed is not None: return completed native = self.node.native_command() if native is None: terminal = self.node.terminal.result() if self.node.terminal and self.node.terminal.done() else None return self.reply('native-action-complete' if terminal and terminal.status==GoalStatus.STATUS_SUCCEEDED else 'waiting-for-controller', route_observation=route) result = dict(speed_mps=native[1], yaw_rate_rps=native[2], status='path', path=local_path, controller_goal=key, controller_generation=self.command_generation, route_observation=route, diagnostic=dict(terrain=observed['metrics'], controller='nav2')) # This is a proposal returned to the mission layer; /control supplies # the separately admitted command bound to current pose/range/intent. self.control.accept(value, result, terrain, detections=observed['detected'], collision_terrain=observed['collision_terrain']) return result def main(): inputs = json.loads(Path(os.environ['MISSIONCORE_RUN_INPUTS']).read_text()) root = Path(__file__).resolve().parents[1] robot = json.loads((root/'robots'/ (inputs['robot']['robot_id']+'.json')).read_text()) config = observed_configuration(inputs, robot, 2, use_sim_time=True) # Mounted K1 and depth origins. parameters = Path('/tmp/missioncore-nav2.yaml') parameters.write_text(yaml.safe_dump(config, sort_keys=False)) rclpy.init() node = RosNavigation(simulation_clock=True) navigation = Navigation(node, inputs, robot) thread = threading.Thread(target=rclpy.spin, args=(node,), daemon=True); thread.start() terrain_reset = node.create_client(Trigger, '/terrain/reset') terrain_ready = node.create_client(Trigger, '/terrain/ready') process = subprocess.Popen([sys.executable, str(Path(__file__).with_name('nodes.py')), '--parameters', str(parameters)]) class Handler(BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' 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': with navigation.plan_lock: observed = navigation.latest_terrain self.reply(200,dict(schema_version='missioncore.navigation-diagnostic/v1', authority='none',execution_inputs_sha256=inputs['sha256'], exchange=navigation.control.snapshot(), latest_plan=navigation.latest_exchange, native=navigation.node.diagnostic(), search_terrain=observed['search_terrain'].tolist() if observed else [], current_observation_id=observed['observation_id'] if observed else None, current_metrics=observed['metrics'] if observed else None, current_detected=observed['detected'].tolist() if observed else [], current_collision_terrain=observed['collision_terrain'].tolist() if observed else [], current_surface_terrain=observed['terrain'].tolist() if observed else [], geometry=observed['physical_terrain'].tolist() if observed else [])) return ready = process.poll() is None and terrain_ready.service_is_ready() and not navigation.failure if ready: try: ready = node.await_result(terrain_ready.call_async(Trigger.Request()), .3).success except Exception: ready = False self.reply(200 if self.path=='/ready' and ready else 503, dict(ready=ready,execution_inputs_sha256=inputs['sha256'], robot_geometry=inputs['robot']['geometry'])) def do_POST(self): try: entered = time.perf_counter() 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)) decoded = time.perf_counter() if self.path=='/reset': with navigation.plan_lock: navigation.node.stop() response=node.await_result(terrain_reset.call_async(Trigger.Request()),2.) if not response.success: raise RuntimeError('Terrain reset failed') navigation.terrain.close() process.terminate(); process.wait(timeout=5) self.reply(200,dict(reset=True)) os.execv(sys.executable,[sys.executable,str(Path(__file__).resolve())]) if value.get('execution_inputs_sha256') != inputs['sha256']: raise ValueError('Execution input identity mismatch') if self.path=='/plan': with navigation.plan_lock: locked = time.perf_counter() result=navigation.plan(value) result.setdefault('diagnostic',{})['server_stage_ms'] = dict( read_decode=(decoded-entered)*1000, plan_lock=(locked-decoded)*1000, plan=(time.perf_counter()-locked)*1000) self.reply(200,result) elif self.path=='/control': self.reply(200,navigation.tick(value)) else: self.reply(404,dict(error='unknown endpoint')) except (ValueError,KeyError,TypeError) as error: self.reply(400,dict(error=str(error))) except Exception as error: self.reply(503,dict(error=str(error))) def log_message(self,*_): pass def shutdown(*_): raise SystemExit(0) signal.signal(signal.SIGTERM,shutdown) try: ThreadingHTTPServer(('0.0.0.0',8010),Handler).serve_forever() finally: try: navigation.terrain.close() finally: process.terminate() try: process.wait(timeout=5) except subprocess.TimeoutExpired: process.kill();process.wait(timeout=2) rclpy.try_shutdown(); thread.join(timeout=2); node.destroy_node() if __name__=='__main__': main()