"""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 differential_motion import alignment_angle from navigation.arrival_approach import validate_orientation 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']) self.collision = ObservedCollision(node, self.monitor.max_step, 2) self.plan_lock, self.owner_lock = threading.Lock(), threading.Lock() self.action_key = None self.completed_orientation = None self.attempted_alignment = 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_goal') != self.action_key: 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']) with self.owner_lock: owner = self.action_key result = self.control.tick(value) with self.owner_lock: if owner != self.action_key: result.update(speed_mps=0., yaw_rate_rps=0., reason='changed-path') return result @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 == GoalStatus.STATUS_SUCCEEDED): # 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. return self.reply('native-action-complete', route_observation=route, action_result=dict(status='succeeded', 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) # TF only; no invented velocity. 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['search_terrain'], time.monotonic()-entered, detected=observed['detected']): return self.reply('stale-range') route = route_observation(terrain, pose, value, self.monitor.max_step) 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.node.stop() with self.owner_lock: self.action_key = None 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['key'], tuple(orientation['xy'])) 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 # The tracked rover can change heading without translating. Consider # a native Spin before a large direction change, only if the complete # rectangular body turn fits the obstacle/detector reserve and its # complete newly entered track sweep has measured support. # Unsafe turns leave Smac/DWB free to find an arc. Support and all live # command gates still apply during Spin; completion grants no motion. alignment_key = ('align', tuple(goal[:2]), limit) aligning = (not reverse and value['translation_allowed'] and self.action_key == alignment_key and self.node.terminal is not None and not self.node.terminal.done()) turn = None if (not reverse and value['translation_allowed'] and not aligning and alignment_key != self.attempted_alignment): turn = alignment_angle(pose, goal, terrain, observed['detected'], self.monitor, value['body_contact_height_m']) orienting = aligning or turn is not None or (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.node.stop() return self.reply('no-permitted-goal', status='blocked', route_observation=route) if orienting: automatic = aligning or turn is not None delta = (goal[:2] if automatic else 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 = alignment_key if automatic else orientation_key if key != self.action_key: with self.owner_lock: self.action_key = None # 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.) if automatic: self.attempted_alignment = alignment_key local_path = [[0.,0.,0.],[0.,0.,0.]] elif reverse: delta = goal[:2]-pose[:2] heading = yaw_of(pose) rear = -float(delta @ [math.cos(heading), math.sin(heading)]) if rear <= 0: self.node.stop() return self.reply('reverse-goal-is-not-behind', status='blocked') key = ('backup', tuple(goal[:2]), limit) completed = self.completed_action(key, route) if completed is not None: return completed if key != self.action_key: with self.owner_lock: self.action_key = None self.node.backup(rear, min(limit,.1), 0.) local_path = [[0.,0.,0.],[-rear,0.,0.]] else: # A sensor refresh is not a new motion goal. ROS feedback fences # a path update; the existing capture leases and raw range gates # still validate every command against the caller's observation. key = ('path', tuple(goal[:2]), limit) completed = self.completed_action(key, route) if completed is not None: return completed continuing = key == self.action_key # 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 (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: self.node.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) if not continuing: with self.owner_lock: self.action_key = None self.node.follow(path, continuing=continuing) self.path, self.path_planned_at = path, entered 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, 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']) 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) # 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() 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 [], 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()