Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
"""Prepare a pinned Nav2 module in one bounded Worker-owned compiler container.
|
||||
|
||||
No host installation, registry credentials, network changes, or activation.
|
||||
The immutable base, source, scripts and completed image are recorded together.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def digest(path):
|
||||
with Path(path).open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def docker(*args, timeout=60, check=True):
|
||||
return subprocess.run(['docker', *args], capture_output=True, text=True,
|
||||
timeout=timeout, check=check)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--source', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--runtime', type=Path,
|
||||
default=Path('D:/NDC_MISSIONCORE/runtime/simulation'))
|
||||
args = parser.parse_args()
|
||||
root = Path(__file__).resolve().parent
|
||||
lock = json.loads((root / 'source.lock.json').read_text())
|
||||
if (args.runtime / 'state/active.json').exists():
|
||||
raise RuntimeError('A simulation is active; build was not started')
|
||||
if digest(args.source) != lock['archive_sha256']:
|
||||
raise ValueError('Nav2 source archive identity changed')
|
||||
base = docker('image', 'inspect', lock['base_image'], '--format', '{{.Id}}').stdout.strip()
|
||||
if base != lock['base_image']:
|
||||
raise ValueError('Pinned Nav2 dependency image unavailable')
|
||||
files = {name: digest(root / name) for name in
|
||||
('build.py', 'build.sh', 'entrypoint.sh', 'source.lock.json')}
|
||||
identity = hashlib.sha256(json.dumps(files, sort_keys=True).encode()).hexdigest()
|
||||
name = 'ndc-mission-core-nav2-build-' + identity[:16]
|
||||
tag = 'ndc-mission-core-nav2:1.1.17-' + identity[:16]
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
receipt = dict(started_utc=datetime.now(timezone.utc).isoformat(), files=files,
|
||||
source=lock, build_identity=identity, container_name=name,
|
||||
tag=tag, status='preparing', activated=False)
|
||||
receipt_path = args.output / 'build.json'
|
||||
|
||||
def save():
|
||||
receipt_path.write_text(json.dumps(receipt, indent=2) + '\n')
|
||||
|
||||
save()
|
||||
container = None
|
||||
started = time.monotonic()
|
||||
try:
|
||||
container = docker(
|
||||
'create', '--name', name, '--network', 'none', '--cpus', '4',
|
||||
'--memory', '8g', '--pids-limit', '512', '--cap-drop', 'ALL',
|
||||
'--security-opt', 'no-new-privileges',
|
||||
'--label', 'com.nodedc.product=mission-core',
|
||||
'--label', 'com.nodedc.stack=ai-polygon',
|
||||
'--label', 'com.nodedc.role=nav2-build',
|
||||
'--label', 'com.nodedc.managed-by=ai-polygon-preparation',
|
||||
'--label', 'com.nodedc.build-sha256=' + identity,
|
||||
'--entrypoint', '/bin/bash', base,
|
||||
'-c', 'exec timeout --signal=TERM --kill-after=15s 1800 bash /ndc-build/build.sh',
|
||||
).stdout.strip()
|
||||
receipt.update(container_id=container, status='building')
|
||||
save()
|
||||
docker('cp', str(root), container + ':/ndc-build')
|
||||
docker('cp', str(args.source.resolve()), container + ':/source.tar.gz', timeout=120)
|
||||
with (args.output / 'build.log').open('w') as log:
|
||||
subprocess.run(['docker', 'start', '-a', container], stdout=log,
|
||||
stderr=subprocess.STDOUT, timeout=1850, check=True)
|
||||
state = json.loads(docker('inspect', container).stdout)[0]['State']
|
||||
if state['ExitCode'] != 0:
|
||||
raise RuntimeError('Nav2 compiler exited: ' + str(state))
|
||||
docker('cp', container + ':/opt/ndc_nav2/packages.json', str(args.output / 'packages.json'))
|
||||
image = docker(
|
||||
'commit', '--change', 'ENTRYPOINT ["/bin/bash", "/ndc-build/entrypoint.sh"]',
|
||||
'--change', 'CMD ["bash"]', '--change', 'WORKDIR /opt/ndc_nav2',
|
||||
'--change', 'LABEL com.nodedc.role=nav2-runtime',
|
||||
container, tag, timeout=180,
|
||||
).stdout.strip()
|
||||
receipt.update(status='built', image=image,
|
||||
packages=json.loads((args.output / 'packages.json').read_text()))
|
||||
except BaseException as error:
|
||||
receipt.update(status='failed', error=type(error).__name__ + ': ' + str(error))
|
||||
raise
|
||||
finally:
|
||||
if container:
|
||||
docker('rm', '-f', container, check=False)
|
||||
remaining = docker('ps', '-a', '--no-trunc', '-q', '--filter', 'id=' + container)
|
||||
receipt['owned_container_removed'] = not remaining.stdout.strip()
|
||||
receipt['elapsed_s'] = time.monotonic() - started
|
||||
receipt['finished_utc'] = datetime.now(timezone.utc).isoformat()
|
||||
save()
|
||||
if container and not receipt['owned_container_removed']:
|
||||
raise RuntimeError('Owned Nav2 build container cleanup was not confirmed')
|
||||
print(json.dumps(receipt))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/bin/bash
|
||||
set -eo pipefail
|
||||
source /opt/ros/humble/setup.bash
|
||||
source /opt/underlay_ws/install/setup.bash
|
||||
mkdir -p /opt/ndc_nav2/src/navigation2
|
||||
cd /opt/ndc_nav2
|
||||
echo '641b6abe527eb862e9102259e3d4a33d5f8823f0bed7079adf4e785d466b6d1d /source.tar.gz' | sha256sum --check
|
||||
tar -xzf /source.tar.gz --no-same-owner --no-same-permissions --strip-components=1 -C src/navigation2
|
||||
export MAKEFLAGS=-j2 CMAKE_BUILD_PARALLEL_LEVEL=2
|
||||
colcon build --base-paths src --parallel-workers 2 \
|
||||
--packages-up-to nav2_bt_navigator nav2_behaviors nav2_smac_planner \
|
||||
dwb_critics dwb_plugins nav2_controller nav2_planner nav2_smoother \
|
||||
nav2_lifecycle_manager nav2_map_server nav2_collision_monitor nav2_velocity_smoother \
|
||||
--cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
|
||||
source install/setup.bash
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
packages = ('nav2_bt_navigator', 'nav2_behaviors', 'nav2_smac_planner',
|
||||
'dwb_critics', 'dwb_plugins', 'dwb_core', 'nav2_controller',
|
||||
'nav2_planner', 'nav2_smoother', 'nav2_lifecycle_manager',
|
||||
'nav2_map_server', 'nav2_collision_monitor', 'nav2_velocity_smoother')
|
||||
versions = {}
|
||||
for package in packages:
|
||||
share = Path(get_package_share_directory(package))
|
||||
assert share.is_relative_to('/opt/ndc_nav2/install'), str(share)
|
||||
version = ET.parse(share / 'package.xml').findtext('version')
|
||||
assert version == '1.1.17', (package, version)
|
||||
versions[package] = version
|
||||
Path('/opt/ndc_nav2/packages.json').write_text(json.dumps(versions, indent=2))
|
||||
print(json.dumps(versions))
|
||||
PY
|
||||
chmod 755 /ndc-build/entrypoint.sh
|
||||
# Preserve upstream source/licenses and build logs; omit compiler intermediates.
|
||||
rm -rf /opt/ndc_nav2/build
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Exact output comparison for the batched prefilter, without motion authority."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from navigation import terrain_costs as costs # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
for name in ('inputs', 'robot', 'output', 'snapshot'):
|
||||
parser.add_argument('--' + name, type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
args.output.mkdir(exist_ok=False)
|
||||
original = costs._NativeNeighborhoods.candidates
|
||||
source = json.loads(args.snapshot.read_text())
|
||||
grid = np.array([[x, y] for x in np.arange(-.6, .601, .05)
|
||||
for y in np.arange(-.6, .601, .05)])
|
||||
report = dict(qualified=False, scope='exact numerical prefilter equivalence', passed=False,
|
||||
snapshot_sha256=hashlib.sha256(args.snapshot.read_bytes()).hexdigest(), cases=[])
|
||||
maximum = .8*math.tan(math.radians(25+1e-4))+.15
|
||||
try:
|
||||
for dtype in (np.float32, np.float64):
|
||||
slope = np.column_stack((grid, grid[:, 0]*math.tan(math.radians(15)),
|
||||
np.full(len(grid), .2))).astype(dtype)
|
||||
step = slope.copy(); step[:, 2] = np.where(step[:, 0] >= 0, .11, 0)
|
||||
random = np.random.default_rng(53).uniform(-.8, .8, size=(512, 4)).astype(dtype)
|
||||
random[:, 3] = .2
|
||||
cases = [('slope', slope), ('step', step),
|
||||
('gap', slope[np.abs(slope[:, 0]) > .15]), ('random', random),
|
||||
('archive', np.array(source['geometry'], dtype=dtype))]
|
||||
for count in (7, 8, 9):
|
||||
for span in (np.nextafter(dtype(maximum), dtype(-np.inf)), dtype(maximum),
|
||||
np.nextafter(dtype(maximum), dtype(np.inf))):
|
||||
points = np.zeros((count, 4), dtype=dtype)
|
||||
points[:, 0] = np.linspace(-.1, .1, count); points[-1, 2] = span
|
||||
points[:, 3] = .2
|
||||
cases.append((f'count-{count}-span-{span}', points))
|
||||
shifted = slope.copy(); shifted[:, :3] += np.array([500., -320., 10.], dtype=dtype)
|
||||
cases.append(('translated-slope', shifted))
|
||||
for name, terrain in cases:
|
||||
around = costs._NativeNeighborhoods(terrain)
|
||||
assert around.screen is not None, 'New kernel is missing'
|
||||
indices = np.flatnonzero(terrain[:, 3] > .1)
|
||||
expected = []
|
||||
for index in indices:
|
||||
nearby = around(index)
|
||||
if len(nearby) >= 8 and np.ptp(nearby[:, 2]) <= maximum:
|
||||
expected.append(index)
|
||||
assert np.array_equal(around.candidates(indices), expected), (dtype, name)
|
||||
timings, outputs = [], []
|
||||
for batched in (False, True):
|
||||
costs._NativeNeighborhoods.candidates = original if batched else lambda self, ids: ids
|
||||
normalizer = costs.TerrainCostNormalizer()
|
||||
elapsed = []
|
||||
for _ in range(4):
|
||||
started = time.perf_counter(); result, count = normalizer(terrain)
|
||||
elapsed.append((time.perf_counter()-started)*1000)
|
||||
outputs.append((result.tobytes(), count))
|
||||
timings.append(statistics.median(elapsed))
|
||||
assert all(output == outputs[0] for output in outputs), (dtype, name)
|
||||
report['cases'].append(dict(dtype=np.dtype(dtype).name, name=name,
|
||||
points=len(terrain), candidates=len(indices), retained=len(expected),
|
||||
before_ms=timings[0], after_ms=timings[1], bit_exact=True))
|
||||
costs._NativeNeighborhoods.candidates = original
|
||||
report['passed'] = True
|
||||
finally:
|
||||
costs._NativeNeighborhoods.candidates = original
|
||||
(args.output/'result.json').write_text(json.dumps(report, indent=2)+'\n')
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,241 @@
|
||||
"""Full HTTP-to-ROS adapter check on archived ranges, no physics/actuator.
|
||||
|
||||
Stationary odometry and renewed diagnostic capture times are explicit test
|
||||
inputs. The resulting proposals cannot qualify the original native route.
|
||||
"""
|
||||
import argparse
|
||||
import copy
|
||||
import http.client
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser()
|
||||
for key in ('inputs','snapshot','output'):
|
||||
parser.add_argument('--'+key,type=Path,required=True)
|
||||
parser.add_argument('--external-server', action='store_true')
|
||||
parser.add_argument('--port',type=int,default=8010)
|
||||
args=parser.parse_args()
|
||||
inputs=json.loads(args.inputs.read_text())
|
||||
snapshot=json.loads(args.snapshot.read_text())
|
||||
original=snapshot['exchange']['request']
|
||||
assert original['execution_inputs_sha256']==inputs['sha256']
|
||||
args.output.mkdir(parents=True,exist_ok=False)
|
||||
report=dict(qualified=False,authority=None,scope='HTTP/ROS integration; archived geometry, synthetic stationary odometry',passed=False)
|
||||
log=(args.output/'server.log').open('w')
|
||||
env={**os.environ,'MISSIONCORE_RUN_INPUTS':str(args.inputs)}
|
||||
process=None if args.external_server else subprocess.Popen(
|
||||
['python3',str(Path(__file__).with_name('server.py'))],env=env,
|
||||
stdout=log,stderr=subprocess.STDOUT)
|
||||
condition=threading.Lock()
|
||||
state=dict(enabled=False,observation_id='bootstrap')
|
||||
responses=[];errors=[];running=threading.Event();running.set()
|
||||
|
||||
def request(path,value=None):
|
||||
client=http.client.HTTPConnection('127.0.0.1',args.port,timeout=2)
|
||||
try:
|
||||
client.request('GET' if value is None else 'POST',path,
|
||||
body=None if value is None else json.dumps(value),
|
||||
headers={} if value is None else {'Content-Type':'application/json'})
|
||||
response=client.getresponse();body=json.loads(response.read())
|
||||
if response.status!=200:raise RuntimeError((path,response.status,body))
|
||||
return body
|
||||
finally:client.close()
|
||||
|
||||
def ready():
|
||||
deadline=time.monotonic()+15
|
||||
while True:
|
||||
try:
|
||||
receipt=request('/ready')
|
||||
assert receipt['execution_inputs_sha256']==inputs['sha256']
|
||||
return
|
||||
except (OSError,RuntimeError):
|
||||
if (process and process.poll() is not None) or time.monotonic()>=deadline:raise
|
||||
time.sleep(.05)
|
||||
|
||||
def controls():
|
||||
try:
|
||||
while running.is_set():
|
||||
with condition:current=dict(state)
|
||||
packet=dict(execution_inputs_sha256=inputs['sha256'],pose=original['pose'],
|
||||
measured_twist=[0.,0.,0.],speed_mps=0.,pose_age_seconds=.01,
|
||||
perception_age_seconds=0.,**current)
|
||||
result=request('/control',packet)
|
||||
responses.append(result)
|
||||
time.sleep(.05)
|
||||
except BaseException as error:errors.append(error)
|
||||
|
||||
thread=None
|
||||
try:
|
||||
ready()
|
||||
assert request('/reset',{})['reset']
|
||||
ready()
|
||||
thread=threading.Thread(target=controls);thread.start()
|
||||
plans=[];bootstrap=[]
|
||||
# /ready confirms transport and terrain service availability. Native
|
||||
# lifecycle activation starts with the first measured pose/plan. Give
|
||||
# that separate bootstrap the same fixed 15 s readiness deadline;
|
||||
# do not spend the twelve geometry/planning trials on inactive nodes.
|
||||
bootstrap_deadline=time.monotonic()+15
|
||||
index=0
|
||||
while len(plans)<12:
|
||||
value=copy.deepcopy(original)
|
||||
value.update(observation_id='diagnostic-'+str(index),geometry_age_seconds=0.,
|
||||
detection_age_seconds=0.)
|
||||
for sample in value['semantic_observations']:
|
||||
sample['age_seconds']=0.
|
||||
result=request('/plan',value)
|
||||
index+=1
|
||||
if result.get('diagnostic',{}).get('failure')=='waiting-for-measured-controller-state':
|
||||
bootstrap.append(result)
|
||||
assert time.monotonic()<bootstrap_deadline,'Native lifecycle readiness timed out'
|
||||
time.sleep(.15)
|
||||
continue
|
||||
plans.append(result)
|
||||
with condition:
|
||||
state.update(observation_id=value['observation_id'],enabled=result['status']=='path')
|
||||
if result['status']=='path':
|
||||
time.sleep(.2)
|
||||
break
|
||||
time.sleep(.15)
|
||||
report.update(bootstrap_plans=bootstrap,plans=plans,controls=responses)
|
||||
(args.output/'snapshot.json').write_text(json.dumps(request('/diagnostic-snapshot')))
|
||||
assert any(p['status']=='path' for p in plans),'No native path through HTTP'
|
||||
admitted=[row for row in responses if row.get('reason')=='none'
|
||||
and abs(row['speed_mps'])+abs(row['yaw_rate_rps'])>1e-6]
|
||||
report['admitted_commands']=len(admitted)
|
||||
assert admitted,'No native command passed the unchanged rover gates'
|
||||
# A fresh scan for the SAME goal may arrive before its HTTP response
|
||||
# reaches the caller. The preceding, still-fresh observation remains
|
||||
# usable. A changed motion goal must not have that permission.
|
||||
continued = []
|
||||
for index in range(6):
|
||||
with condition:previous_id=state['observation_id']
|
||||
value['observation_id']='refresh-'+str(index)
|
||||
result=request('/plan',value)
|
||||
assert result['status']=='path',result
|
||||
old=request('/control',dict(execution_inputs_sha256=inputs['sha256'],
|
||||
pose=original['pose'],measured_twist=[0.,0.,0.],speed_mps=0.,
|
||||
pose_age_seconds=.01,perception_age_seconds=0.,enabled=True,
|
||||
observation_id=previous_id))
|
||||
assert old['reason']=='none',old
|
||||
continued.append(old)
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
time.sleep(.05)
|
||||
report['same_goal_refresh_commands']=continued
|
||||
old_id=value['observation_id']
|
||||
value['observation_id']='changed-limit'
|
||||
value['max_speed_mps']*=.5
|
||||
result=request('/plan',value)
|
||||
assert result['status']=='path',result
|
||||
old=request('/control',dict(execution_inputs_sha256=inputs['sha256'],
|
||||
pose=original['pose'],measured_twist=[0.,0.,0.],speed_mps=0.,
|
||||
pose_age_seconds=.01,perception_age_seconds=0.,enabled=True,
|
||||
observation_id=old_id))
|
||||
assert old['speed_mps']==old['yaw_rate_rps']==0.,old
|
||||
report['changed_goal_rejects_previous_observation']=old
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
# A measured translation destination belongs to Smac/DWB even during
|
||||
# recovery. A bearing hint must not impose a separate in-place Spin.
|
||||
x,y,z,w=original['pose'][3:]
|
||||
yaw=math.atan2(2*(w*z+x*y),1-2*(y*y+z*z))
|
||||
value.update(recovery_orientation=True,translation_allowed=True,
|
||||
observation_id='recovery-translation',
|
||||
orientation_target=dict(key='http-recovery-bearing',xy=[
|
||||
original['pose'][0]+math.cos(yaw+.4),
|
||||
original['pose'][1]+math.sin(yaw+.4)]))
|
||||
translated=request('/plan',value)
|
||||
assert translated['status']=='path' and translated['controller_goal'][0]=='path',translated
|
||||
report['recovery_translation_uses_native_path']=translated
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
# Explicit orientation-only intent still invokes native Spin. Its
|
||||
# zero-angle completion on stationary test odometry cannot translate.
|
||||
value.update(translation_allowed=False,
|
||||
orientation_target=dict(key='http-spin-complete',xy=[
|
||||
original['pose'][0]+math.cos(yaw),
|
||||
original['pose'][1]+math.sin(yaw)]))
|
||||
orientation_plans=[]
|
||||
deadline=time.monotonic()+3
|
||||
while True:
|
||||
value['observation_id']='spin-complete-'+str(len(orientation_plans))
|
||||
result=request('/plan',value)
|
||||
orientation_plans.append(result)
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
if result.get('diagnostic',{}).get('failure')=='no-permitted-goal':break
|
||||
assert time.monotonic()<deadline,orientation_plans
|
||||
time.sleep(.05)
|
||||
report['orientation_only_spin_completion']=orientation_plans
|
||||
value.update(observation_id='orientation-no-translation',translation_allowed=False)
|
||||
blocked=request('/plan',value)
|
||||
assert blocked['status']=='blocked' and blocked['diagnostic']['failure']=='no-permitted-goal',blocked
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
time.sleep(.1)
|
||||
assert responses[-1]['speed_mps']==responses[-1]['yaw_rate_rps']==0.,responses[-1]
|
||||
report['completed_spin_without_translation']=blocked
|
||||
value.update(observation_id='orientation-translation-restored',translation_allowed=True)
|
||||
restored=request('/plan',value)
|
||||
assert restored['status']=='path' and restored['controller_goal'][0]=='path',restored
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
with condition:state['enabled']=False
|
||||
time.sleep(.1)
|
||||
assert responses[-1]['speed_mps']==responses[-1]['yaw_rate_rps']==0.
|
||||
time.sleep(.85) # Expire the unchanged .8 s range lease; poses stay fresh.
|
||||
with condition:state['enabled']=True
|
||||
time.sleep(.15)
|
||||
assert responses[-1]['reason']=='stale-range',responses[-1]
|
||||
assert responses[-1]['speed_mps']==responses[-1]['yaw_rate_rps']==0.
|
||||
report['expired_range_reason']=responses[-1]['reason']
|
||||
if process:
|
||||
# Losing the run-owned map process must not renew its last map
|
||||
# through otherwise healthy control/odometry traffic.
|
||||
value['observation_id']='map-process-fault'
|
||||
assert request('/plan',value)['status']=='path'
|
||||
with condition:state['observation_id']=value['observation_id']
|
||||
children=[]
|
||||
for entry in Path('/proc').iterdir():
|
||||
if entry.name.isdecimal():
|
||||
try:
|
||||
stat=(entry/'stat').read_text().split(') ',1)[1].split()
|
||||
command=(entry/'cmdline').read_bytes()
|
||||
except (FileNotFoundError,ProcessLookupError):
|
||||
continue
|
||||
if int(stat[1])==process.pid and b'multiprocessing.spawn' in command:
|
||||
children.append(int(entry.name))
|
||||
assert len(children)==1,children
|
||||
os.kill(children[0],signal.SIGTERM)
|
||||
time.sleep(.1)
|
||||
try:
|
||||
request('/plan',value)
|
||||
except RuntimeError as error:
|
||||
assert '503' in str(error),error
|
||||
else:
|
||||
raise AssertionError('A failed map process accepted an observation')
|
||||
time.sleep(.85)
|
||||
assert responses[-1]['speed_mps']==responses[-1]['yaw_rate_rps']==0.
|
||||
report['map_process_failure_zero']=responses[-1]['reason']
|
||||
if errors:raise errors[0]
|
||||
report['passed']=True
|
||||
except BaseException as error:
|
||||
report['error']=type(error).__name__+': '+str(error)
|
||||
raise
|
||||
finally:
|
||||
running.clear()
|
||||
if thread:thread.join(timeout=3)
|
||||
if process:
|
||||
process.terminate()
|
||||
try:process.wait(timeout=7)
|
||||
except subprocess.TimeoutExpired:process.kill();process.wait(timeout=2)
|
||||
log.close()
|
||||
report['controls']=responses
|
||||
(args.output/'result.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(json.dumps({k:v for k,v in report.items() if k not in ('plans','controls')}))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Exercise production ROS adapter against actual Smac/DWB, no actuator."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import Future
|
||||
from pathlib import Path
|
||||
|
||||
import rclpy
|
||||
import yaml
|
||||
from check_ros_integration import Check
|
||||
from configuration import configuration
|
||||
from rclpy.executors import MultiThreadedExecutor
|
||||
from nav_msgs.msg import Odometry
|
||||
from nav2_msgs.action import FollowPath
|
||||
from action_msgs.msg import GoalStatus
|
||||
from ros_navigation import RosNavigation
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
for name in ('inputs', 'robot', 'output'):
|
||||
parser.add_argument('--' + name, type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
args.output.mkdir(exist_ok=False, parents=True)
|
||||
config = configuration(json.loads(args.inputs.read_text()), json.loads(args.robot.read_text()))
|
||||
path = args.output/'parameters.yaml'; path.write_text(yaml.safe_dump(config, sort_keys=False))
|
||||
rclpy.init()
|
||||
fixture, bridge = Check(), RosNavigation()
|
||||
measured = []
|
||||
fixture.create_subscription(Odometry, '/odom', lambda value: measured.append([
|
||||
value.twist.twist.linear.x, value.twist.twist.linear.y,
|
||||
value.twist.twist.angular.z]), 5)
|
||||
fixture.destroy_timer(fixture.timer) # The production adapter owns TF/odometry.
|
||||
running = threading.Event(); running.set()
|
||||
errors = []
|
||||
executor = MultiThreadedExecutor(num_threads=2)
|
||||
spinner = threading.Thread(target=executor.spin)
|
||||
pose = [0.,0.,.37,0.,0.,0.,1.]
|
||||
continuous_updates = threading.Event()
|
||||
continuity_samples = []
|
||||
|
||||
def measurements():
|
||||
try:
|
||||
while running.is_set():
|
||||
bridge.observe_pose(pose, .01, [.03, -.005, .012])
|
||||
if continuous_updates.is_set():
|
||||
continuity_samples.append(bridge.native_command())
|
||||
time.sleep(.04)
|
||||
except BaseException as error:
|
||||
errors.append(error)
|
||||
|
||||
source = threading.Thread(target=measurements)
|
||||
processes, logs = [], []
|
||||
report = dict(qualified=False, scope='native ROS action/odometry integration', passed=False)
|
||||
try:
|
||||
fixture.map_case('free')
|
||||
# map_case uses spin_once for initial map publication; that helper
|
||||
# removes its node from the temporary executor afterwards.
|
||||
executor.add_node(fixture); executor.add_node(bridge)
|
||||
spinner.start(); source.start()
|
||||
for package, name in (('nav2_planner', 'planner_server'), ('nav2_controller', 'controller_server'),
|
||||
('nav2_behaviors', 'behavior_server')):
|
||||
log = (args.output/(name+'.log')).open('w');logs.append(log)
|
||||
processes.append(subprocess.Popen([
|
||||
'/opt/ndc_nav2/install/'+package+'/lib/'+package+'/'+name,
|
||||
'--ros-args','--params-file',str(path), '-r', '/cmd_vel:=/nav2/'+
|
||||
('behavior' if package=='nav2_behaviors' else 'controller')+'_cmd_vel'],
|
||||
stdout=log,stderr=subprocess.STDOUT))
|
||||
bridge.activate()
|
||||
history=[]
|
||||
for goal in ([5.,0.], [3.,1.]):
|
||||
planned=bridge.plan(pose,goal,math.atan2(goal[1],goal[0]))
|
||||
assert planned is not None and len(planned.poses)>1
|
||||
proposed=bridge.follow(planned)
|
||||
assert proposed is not None
|
||||
time.sleep(.3)
|
||||
current=bridge.native_command()
|
||||
assert current is not None and all(math.isfinite(v) for v in current)
|
||||
assert abs(current[1])+abs(current[2])>1e-5
|
||||
history.append(dict(goal=goal,path_points=len(planned.poses),proposal=list(current),
|
||||
command_sequence=bridge.command_sequence))
|
||||
# A new observed path is a native preemption, not a cancel/restart.
|
||||
# Repeated updates must not insert zero commands or reset progress.
|
||||
with bridge.condition:
|
||||
before = bridge.command_sequence
|
||||
continuous_updates.set()
|
||||
refresh_ms=[]
|
||||
for _ in range(6):
|
||||
began=time.monotonic()
|
||||
assert bridge.follow(planned, continuing=True) is not None
|
||||
refresh_ms.append((time.monotonic()-began)*1000)
|
||||
time.sleep(.1)
|
||||
continuous_updates.clear()
|
||||
assert continuity_samples and all(x is not None for x in continuity_samples)
|
||||
report['uninterrupted_command_samples'] = len(continuity_samples)
|
||||
report['same_goal_refresh_ms'] = refresh_ms
|
||||
with bridge.condition:
|
||||
updates = [row for row in bridge.history if row[0] > before]
|
||||
assert updates and all(row[2:] != (0., 0.) for row in updates), updates
|
||||
report['continuous_path_update_commands'] = len(updates)
|
||||
# Lost feedback must not hide a terminal zero. With stationary pose,
|
||||
# the unchanged native progress checker aborts this real action.
|
||||
with bridge.condition:
|
||||
bridge.pending_feedback = object()
|
||||
terminal = bridge.await_result(bridge.terminal, 10.)
|
||||
assert terminal.status == GoalStatus.STATUS_ABORTED
|
||||
assert bridge.native_command() is None
|
||||
bridge.stop()
|
||||
report['unacknowledged_terminal_status'] = terminal.status
|
||||
spin = bridge.spin(.5, 3.)
|
||||
assert spin is not None and spin[1] == 0 and spin[2] > 0
|
||||
# A command from an inactive publisher cannot acquire velocity ownership.
|
||||
from geometry_msgs.msg import Twist
|
||||
foreign=Twist();foreign.linear.x=99.
|
||||
bridge.on_command(foreign, 'controller')
|
||||
assert bridge.native_command()[1] == 0
|
||||
reverse = bridge.backup(.3, .1, 4.)
|
||||
assert reverse is not None and reverse[1] < 0 and reverse[2] == 0
|
||||
report['behaviors'] = dict(spin=list(spin), backup=list(reverse))
|
||||
bridge.stop()
|
||||
assert bridge.native_command() is None
|
||||
with bridge.condition:
|
||||
assert bridge.history[-1][2:] == (0.,0.)
|
||||
commands=list(bridge.history)
|
||||
# No caller may silently turn unsigned speed into odometry.
|
||||
report['received_odometry_samples'] = len(measured)
|
||||
assert measured and measured[-1]==[.03,-.005,.012], measured[-3:]
|
||||
report['measured_twist']=measured[-1]
|
||||
# Delay delivery of a real controller's acceptance beyond the caller's
|
||||
# deadline. The adapter must cancel that late accepted action and latch
|
||||
# closed until reset, even though the native server already started it.
|
||||
accepted, delayed = [], Future()
|
||||
ready = threading.Event()
|
||||
class DelayedAcceptance:
|
||||
def send_goal_async(self, request):
|
||||
def receive(future):
|
||||
accepted.append(future.result()); ready.set()
|
||||
bridge.controller.send_goal_async(request).add_done_callback(receive)
|
||||
return delayed
|
||||
request = FollowPath.Goal()
|
||||
request.path, request.controller_id, request.goal_checker_id = planned, 'FollowPath', 'goal_checker'
|
||||
try:
|
||||
bridge.accept(DelayedAcceptance(), request, .05)
|
||||
raise AssertionError('Delayed acceptance did not time out')
|
||||
except TimeoutError:
|
||||
pass
|
||||
assert ready.wait(1) and accepted[0].accepted
|
||||
terminal = accepted[0].get_result_async()
|
||||
delayed.set_result(accepted[0])
|
||||
result = bridge.await_result(terminal, 1.)
|
||||
assert result.status == GoalStatus.STATUS_CANCELED
|
||||
assert bridge.failed and bridge.native_command() is None
|
||||
report['late_acceptance_cancel_status'] = result.status
|
||||
report.update(paths=history,commands=commands,passed=True)
|
||||
if errors: raise errors[0]
|
||||
except BaseException as error:
|
||||
report.update(passed=False,error=type(error).__name__+': '+str(error))
|
||||
raise
|
||||
finally:
|
||||
running.clear()
|
||||
if source.is_alive(): source.join(timeout=1)
|
||||
for process in processes: process.terminate()
|
||||
for process in processes:
|
||||
try: process.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired: process.kill();process.wait(timeout=3)
|
||||
for log in logs:log.close()
|
||||
executor.shutdown(timeout_sec=2)
|
||||
if spinner.is_alive(): spinner.join(timeout=2)
|
||||
bridge.destroy_node();fixture.destroy_node();rclpy.shutdown()
|
||||
(args.output/'result.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(json.dumps({k:v for k,v in report.items() if k!='commands'}))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Fixed ground/object fixtures for the actual PCL library; no actuator."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from navigation.pcl_ground import PclGround # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser()
|
||||
for name in ('inputs','robot','snapshot','output'):
|
||||
p.add_argument('--'+name,type=Path,required=True)
|
||||
args=p.parse_args();args.output.mkdir(parents=True,exist_ok=False)
|
||||
inputs=json.loads(args.inputs.read_text())
|
||||
ground=PclGround(inputs['robot']['geometry'])
|
||||
report=dict(authority=None,qualified=False,cases=[],parameters=dict(
|
||||
method="PCL SAC_RANSAC perpendicular plane",height_m=ground.height_m,angle=ground.angle))
|
||||
try:
|
||||
for grade in (0,8,20):
|
||||
for angle,shift in ((0,[0,0,0]),(71,[40,-20,2])):
|
||||
x,y=np.meshgrid(np.arange(-1.5,1.51,.04),np.arange(-1.5,1.51,.04))
|
||||
x,y=x.ravel(),y.ravel();z=x*math.tan(math.radians(grade))
|
||||
low=(abs(x)<.18)&(abs(y)<.18)
|
||||
high=(abs(x-.7)<.18)&(abs(y+.4)<.18)
|
||||
z[low]+=.08;z[high]+=.6
|
||||
points=np.column_stack((x,y,z))
|
||||
a=math.radians(angle);rot=np.array([[math.cos(a),-math.sin(a),0],
|
||||
[math.sin(a),math.cos(a),0],[0,0,1]])
|
||||
points=points@rot.T+shift
|
||||
before=time.monotonic();mask=ground.mask(points, ground_anchor=shift);elapsed=time.monotonic()-before
|
||||
interior=(abs(x)<1)&(abs(y)<1)&~(low|high)
|
||||
row=dict(grade=grade,angle=angle,ground_fraction=float(mask[interior].mean()),
|
||||
low_object_ground=int(mask[low].sum()),high_object_ground=int(mask[high].sum()),
|
||||
processing_ms=elapsed*1000)
|
||||
report['cases'].append(row)
|
||||
assert row['ground_fraction']>=.98 and not mask[low|high].any(),row
|
||||
# A different horizontal floor/table cannot use the rover ground reference.
|
||||
elevated=points.copy();elevated[:,2]+=.6
|
||||
assert not ground.mask(elevated, ground_anchor=shift).any()
|
||||
snapshot=json.loads(args.snapshot.read_text())
|
||||
request=snapshot['exchange']['request'];points=np.array(request['points'])
|
||||
anchor=np.array(request['pose'][:3]);anchor[2]-=request['body_contact_height_m']
|
||||
before=time.monotonic();mask=ground.mask(points, ground_anchor=anchor)
|
||||
indices=request['detection_point_indices']
|
||||
report['archive']=dict(candidates=len(indices),pcl_ground=int(mask[indices].sum()),
|
||||
retained_points=points[np.array(indices)[~mask[indices]]].tolist(),
|
||||
processing_ms=(time.monotonic()-before)*1000)
|
||||
report['passed']=True
|
||||
except BaseException as error:
|
||||
report['error']=type(error).__name__+': '+str(error);raise
|
||||
finally:
|
||||
(args.output/'result.json').write_text(json.dumps(report,indent=2))
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Bounded real ROS/Nav2 plugin check on synthetic maps, never vehicle authority.
|
||||
|
||||
Run inside the pinned image. Checks fixed pass/block cases with the actual rig
|
||||
footprint, unknown space, controller output and cancellation. No physics claim.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import rclpy
|
||||
import yaml
|
||||
from action_msgs.msg import GoalStatus
|
||||
from configuration import configuration
|
||||
from geometry_msgs.msg import TransformStamped, Twist
|
||||
from lifecycle_msgs.msg import Transition
|
||||
from lifecycle_msgs.srv import ChangeState
|
||||
from nav2_msgs.action import ComputePathToPose, FollowPath
|
||||
from nav2_msgs.srv import GetCostmap
|
||||
from nav_msgs.msg import OccupancyGrid, Odometry
|
||||
from rclpy.action import ActionClient
|
||||
from rclpy.node import Node
|
||||
from rclpy.qos import DurabilityPolicy, QoSProfile, ReliabilityPolicy
|
||||
from tf2_ros import TransformBroadcaster
|
||||
|
||||
|
||||
class Check(Node):
|
||||
def __init__(self):
|
||||
super().__init__('missioncore_nav2_integration_check')
|
||||
qos = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL,
|
||||
reliability=ReliabilityPolicy.RELIABLE)
|
||||
self.map_pub = self.create_publisher(OccupancyGrid, '/observed_map', qos)
|
||||
self.odom_pub = self.create_publisher(Odometry, '/odom', 5)
|
||||
self.tf = TransformBroadcaster(self)
|
||||
self.timer = self.create_timer(0.02, self.publish_pose)
|
||||
self.commands = []
|
||||
self.create_subscription(Twist, '/cmd_vel', self.command, 20)
|
||||
self.planner = ActionClient(self, ComputePathToPose, '/compute_path_to_pose')
|
||||
self.controller = ActionClient(self, FollowPath, '/follow_path')
|
||||
|
||||
def command(self, value):
|
||||
self.commands.append((time.monotonic(), value.linear.x, value.angular.z))
|
||||
|
||||
def publish_pose(self):
|
||||
tf = TransformStamped()
|
||||
tf.header.stamp = self.get_clock().now().to_msg()
|
||||
tf.header.frame_id, tf.child_frame_id = 'map', 'base_link'
|
||||
tf.transform.rotation.w = 1.0
|
||||
self.tf.sendTransform(tf)
|
||||
odom = Odometry()
|
||||
odom.header = tf.header
|
||||
odom.child_frame_id = 'base_link'
|
||||
odom.pose.pose.orientation.w = 1.0
|
||||
self.odom_pub.publish(odom)
|
||||
|
||||
def spin_for(self, duration):
|
||||
end = time.monotonic() + duration
|
||||
while time.monotonic() < end:
|
||||
rclpy.spin_once(self, timeout_sec=min(0.02, end - time.monotonic()))
|
||||
|
||||
def await_result(self, future, timeout=8.0):
|
||||
rclpy.spin_until_future_complete(self, future, timeout_sec=timeout)
|
||||
if not future.done():
|
||||
raise TimeoutError('ROS response timeout')
|
||||
return future.result()
|
||||
|
||||
def lifecycle(self, name, transition):
|
||||
client = self.create_client(ChangeState, '/' + name + '/change_state')
|
||||
try:
|
||||
if not client.wait_for_service(timeout_sec=10):
|
||||
raise TimeoutError(name + ' lifecycle service unavailable')
|
||||
request = ChangeState.Request()
|
||||
request.transition.id = transition
|
||||
if not self.await_result(client.call_async(request)).success:
|
||||
raise RuntimeError(name + ' lifecycle transition failed')
|
||||
finally:
|
||||
self.destroy_client(client)
|
||||
|
||||
def map_case(self, case):
|
||||
grid = OccupancyGrid()
|
||||
grid.header.frame_id = 'map'
|
||||
grid.header.stamp = self.get_clock().now().to_msg()
|
||||
grid.info.resolution = 0.05
|
||||
grid.info.width, grid.info.height = 240, 160
|
||||
grid.info.origin.position.x, grid.info.origin.position.y = -2.0, -4.0
|
||||
grid.info.origin.orientation.w = 1.0
|
||||
values = []
|
||||
for iy in range(grid.info.height):
|
||||
for ix in range(grid.info.width):
|
||||
x, y = -2 + (ix + 0.5) * 0.05, -4 + (iy + 0.5) * 0.05
|
||||
cost = 100 if ix in (0, 239) or iy in (0, 159) else 0
|
||||
if 2.0 <= x < 2.2:
|
||||
if case == 'blocked-wall':
|
||||
cost = 100
|
||||
elif case == 'unknown-band':
|
||||
cost = -1
|
||||
elif case in ('narrow-gap', 'wide-gap'):
|
||||
half = 0.4 if case == 'narrow-gap' else 0.65
|
||||
cost = 100 if abs(y) >= half else 0
|
||||
values.append(cost)
|
||||
grid.data = values
|
||||
self.map_pub.publish(grid)
|
||||
self.spin_for(0.4)
|
||||
return grid
|
||||
|
||||
def confirm_map(self, case):
|
||||
client = self.create_client(GetCostmap, '/global_costmap/get_costmap')
|
||||
try:
|
||||
if not client.wait_for_service(timeout_sec=5):
|
||||
raise TimeoutError('Costmap service unavailable')
|
||||
value = self.await_result(client.call_async(GetCostmap.Request())).map
|
||||
# Confirm the wall update reached the planner before querying it.
|
||||
ix = int((2.075 - value.metadata.origin.position.x) / value.metadata.resolution)
|
||||
iy = int((0.875 - value.metadata.origin.position.y) / value.metadata.resolution)
|
||||
cost = value.data[iy * value.metadata.size_x + ix]
|
||||
expected = 0 if case == 'free' else 255 if case == 'unknown-band' else 254
|
||||
if cost != expected:
|
||||
raise AssertionError(('Costmap update missing', case, cost, expected))
|
||||
return int(cost)
|
||||
finally:
|
||||
self.destroy_client(client)
|
||||
|
||||
def plan(self):
|
||||
if not self.planner.wait_for_server(timeout_sec=5):
|
||||
raise TimeoutError('Planner action unavailable')
|
||||
request = ComputePathToPose.Goal()
|
||||
request.planner_id, request.use_start = 'GridBased', True
|
||||
for pose, x in ((request.start, 0.0), (request.goal, 5.0)):
|
||||
pose.header.frame_id = 'map'
|
||||
pose.header.stamp = self.get_clock().now().to_msg()
|
||||
pose.pose.position.x, pose.pose.orientation.w = x, 1.0
|
||||
handle = self.await_result(self.planner.send_goal_async(request))
|
||||
if not handle.accepted:
|
||||
raise RuntimeError('Planner action was not accepted')
|
||||
return self.await_result(handle.get_result_async())
|
||||
|
||||
def follow_and_cancel(self, path):
|
||||
if not self.controller.wait_for_server(timeout_sec=5):
|
||||
raise TimeoutError('Controller action unavailable')
|
||||
goal = FollowPath.Goal()
|
||||
goal.path, goal.controller_id, goal.goal_checker_id = path, 'FollowPath', 'goal_checker'
|
||||
first = len(self.commands)
|
||||
handle = self.await_result(self.controller.send_goal_async(goal))
|
||||
if not handle.accepted:
|
||||
raise RuntimeError('Controller action was not accepted')
|
||||
self.spin_for(0.75)
|
||||
active = self.commands[first:]
|
||||
assert active and all(math.isfinite(v) for row in active for v in row)
|
||||
assert any(row[1] > 0.001 for row in active), 'DWB did not propose forward motion'
|
||||
cancel_at = time.monotonic()
|
||||
self.await_result(handle.cancel_goal_async())
|
||||
terminal = self.await_result(handle.get_result_async())
|
||||
self.spin_for(0.15)
|
||||
stopped = [row for row in self.commands if row[0] >= cancel_at]
|
||||
assert terminal.status == GoalStatus.STATUS_CANCELED, terminal.status
|
||||
assert stopped and stopped[-1][1:] == (0.0, 0.0), 'Cancellation did not publish zero'
|
||||
return dict(commands=active, cancelled_status=terminal.status, after_cancel=stopped)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--inputs', type=Path, required=True)
|
||||
parser.add_argument('--robot', type=Path, required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
inputs, robot = json.loads(args.inputs.read_text()), json.loads(args.robot.read_text())
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
config = configuration(inputs, robot)
|
||||
config_path = args.output / 'parameters.yaml'
|
||||
config_path.write_text(yaml.safe_dump(config, sort_keys=False))
|
||||
report = dict(scope='real ROS2 plugins on synthetic maps; no physical motion',
|
||||
qualified=False, execution_inputs_sha256=inputs['sha256'],
|
||||
configuration_sha256=hashlib.sha256(config_path.read_bytes()).hexdigest(),
|
||||
cases=[], passed=False)
|
||||
processes, logs = [], []
|
||||
rclpy.init()
|
||||
node = Check()
|
||||
try:
|
||||
node.map_case('free')
|
||||
for package, executable in (('nav2_planner', 'planner_server'),
|
||||
('nav2_controller', 'controller_server')):
|
||||
log = (args.output / (executable + '.log')).open('w')
|
||||
logs.append(log)
|
||||
binary = '/opt/ndc_nav2/install/' + package + '/lib/' + package + '/' + executable
|
||||
processes.append(subprocess.Popen(
|
||||
[binary, '--ros-args', '--params-file', str(config_path)],
|
||||
stdout=log, stderr=subprocess.STDOUT))
|
||||
node.lifecycle(executable, Transition.TRANSITION_CONFIGURE)
|
||||
node.lifecycle(executable, Transition.TRANSITION_ACTIVATE)
|
||||
for name, expected in (('free', True), ('blocked-wall', False),
|
||||
('unknown-band', False), ('narrow-gap', False), ('wide-gap', True)):
|
||||
grid = node.map_case(name)
|
||||
observed_cost = node.confirm_map(name)
|
||||
result = node.plan()
|
||||
path = result.result.path
|
||||
success = result.status == GoalStatus.STATUS_SUCCEEDED and len(path.poses) > 1
|
||||
row = dict(case=name, expected_path=expected, status=result.status,
|
||||
confirmed_cost=observed_cost,
|
||||
path=[[p.pose.position.x, p.pose.position.y,
|
||||
p.pose.orientation.z, p.pose.orientation.w] for p in path.poses],
|
||||
grid_sha256=hashlib.sha256(bytes(v + 1 for v in grid.data)).hexdigest())
|
||||
report['cases'].append(row)
|
||||
assert success == expected, (name, expected, result.status, len(path.poses))
|
||||
if name == 'free':
|
||||
row['controller'] = node.follow_and_cancel(path)
|
||||
report['passed'] = True
|
||||
except BaseException as error:
|
||||
report['error'] = type(error).__name__ + ': ' + str(error)
|
||||
raise
|
||||
finally:
|
||||
for process in processes:
|
||||
process.terminate()
|
||||
for process in processes:
|
||||
try:
|
||||
process.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=3)
|
||||
for log in logs:
|
||||
log.close()
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
(args.output / 'result.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Archived full sensor-to-Nav2 check with the unchanged CMU terrain node.
|
||||
|
||||
Two pinned images communicate with standard ROS2 messages. There is no
|
||||
actuator. Diagnostic republishing is not a live observation or qualification.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import rclpy
|
||||
from action_msgs.msg import GoalStatus
|
||||
from lifecycle_msgs.msg import Transition
|
||||
from navigation.footprint import Footprint
|
||||
from replay_observations import Replay
|
||||
from rig_collision import collision_geometry
|
||||
from terrain_observation import TerrainObservation
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
for key in ('inputs', 'snapshot', 'output'):
|
||||
parser.add_argument('--' + key, type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
inputs = json.loads(args.inputs.read_text())
|
||||
snapshot = json.loads(args.snapshot.read_text())
|
||||
request = snapshot['exchange']['request']
|
||||
assert request['execution_inputs_sha256'] == inputs['sha256']
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
report = dict(qualified=False, authority=None, scope='archived terrain/ROS integration',
|
||||
source_observation_id=snapshot['exchange']['observation_id'],
|
||||
snapshot_sha256=hashlib.sha256(args.snapshot.read_bytes()).hexdigest(),
|
||||
execution_inputs_sha256=inputs['sha256'], passed=False)
|
||||
rclpy.init()
|
||||
node = Replay(snapshot, inputs['robot']['geometry']['max_step_m'])
|
||||
# Geometry for contact fits remains the measured chassis/track geometry;
|
||||
# the collision monitor separately includes the mounted sensor bodies.
|
||||
geometry = collision_geometry(inputs['robot']['geometry'], inputs['sensors']['mounts'])
|
||||
terrain = TerrainObservation(node, Footprint(geometry), inputs['robot']['geometry'])
|
||||
processes, logs = [], []
|
||||
thread = None
|
||||
observed, failure = [], []
|
||||
try:
|
||||
deadline = time.monotonic()+5
|
||||
while (terrain.scan.get_subscription_count() == 0
|
||||
or terrain.odom.get_subscription_count() == 0):
|
||||
node.spin_for(.02)
|
||||
if time.monotonic() > deadline:
|
||||
raise RuntimeError('Terrain subscriptions unavailable')
|
||||
|
||||
def observe():
|
||||
try:
|
||||
observed.append(terrain.observe(request))
|
||||
except BaseException as error:
|
||||
failure.append(error)
|
||||
|
||||
thread = threading.Thread(target=observe)
|
||||
thread.start()
|
||||
while thread.is_alive():
|
||||
node.spin_for(.01)
|
||||
thread.join()
|
||||
if failure:
|
||||
raise failure[0]
|
||||
result = observed[0]
|
||||
node.hazards = [p for p in result['terrain'] if p[3] > terrain.monitor.max_step + 1e-4]
|
||||
report['terrain'] = dict(metrics=result['metrics'], points=len(result['terrain']),
|
||||
hazards=len(node.hazards), source_points=len(request['points']))
|
||||
(args.output / 'terrain.json').write_text(json.dumps({key:result[key].tolist()
|
||||
for key in ('terrain','physical_terrain','current_points','detected')}))
|
||||
for package, name in (('nav2_planner', 'planner_server'),
|
||||
('nav2_controller', 'controller_server')):
|
||||
log = (args.output / (name + '.log')).open('w'); logs.append(log)
|
||||
processes.append(subprocess.Popen(
|
||||
['/opt/ndc_nav2/install/' + package + '/lib/' + package + '/' + name,
|
||||
'--ros-args', '--params-file', '/check/parameters.yaml'],
|
||||
stdout=log, stderr=subprocess.STDOUT))
|
||||
node.lifecycle(name, Transition.TRANSITION_CONFIGURE)
|
||||
node.lifecycle(name, Transition.TRANSITION_ACTIVATE)
|
||||
node.spin_for(.5)
|
||||
path = node.plan()
|
||||
report['status'] = path.status
|
||||
report['path'] = [[p.pose.position.x, p.pose.position.y,
|
||||
p.pose.orientation.z, p.pose.orientation.w] for p in path.result.path.poses]
|
||||
assert path.status == GoalStatus.STATUS_SUCCEEDED and len(report['path']) > 1
|
||||
report['controller'] = node.follow_and_cancel(path.result.path)
|
||||
report['passed'] = True
|
||||
except BaseException as error:
|
||||
report['error'] = type(error).__name__ + ': ' + str(error)
|
||||
raise
|
||||
finally:
|
||||
if thread:
|
||||
thread.join(timeout=1)
|
||||
for process in processes:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill(); process.wait(timeout=3)
|
||||
for log in logs:
|
||||
log.close()
|
||||
node.destroy_node(); rclpy.shutdown()
|
||||
(args.output/'result.json').write_text(json.dumps(report, indent=2)+'\n')
|
||||
print(json.dumps({k:v for k,v in report.items() if k not in ('path','controller')}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Nav2 Humble parameters derived from the selected rover, without map data.
|
||||
|
||||
The drive limits remain the simulation profile's engineering assumptions.
|
||||
Compiling or activating these parameters does not qualify physical dynamics.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from rig_collision import collision_geometry # noqa: E402
|
||||
|
||||
|
||||
def configuration(inputs, robot):
|
||||
body = {key: value for key, value in inputs.items() if key != 'sha256'}
|
||||
actual = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(',', ':'),
|
||||
allow_nan=False).encode()).hexdigest()
|
||||
if actual != inputs['sha256']:
|
||||
raise ValueError('Execution inputs identity changed')
|
||||
geometry = collision_geometry(inputs['robot']['geometry'], inputs['sensors']['mounts'])
|
||||
x, y = geometry['collision_length_m'] / 2, geometry['collision_width_m'] / 2
|
||||
control = robot['control']
|
||||
speed = float(inputs['behavior']['max_speed_mps'])
|
||||
acceleration = float(control['acceleration_mps2'])
|
||||
deceleration = float(control['deceleration_mps2'])
|
||||
yaw = float(control['max_yaw_rps'])
|
||||
track_width = float(robot['physics']['track_width_m'])
|
||||
track_centres = [(band['lower_xy_m'][1]+band['upper_xy_m'][1])/2
|
||||
for band in inputs['robot']['geometry']['ground_contact']['bands']]
|
||||
if not all(math.isfinite(v) and v > 0 for v in
|
||||
(x, y, speed, acceleration, deceleration, yaw, track_width)):
|
||||
raise ValueError('Invalid rover envelope')
|
||||
footprint = json.dumps([[x, y], [-x, y], [-x, -y], [x, -y]])
|
||||
costmap = dict(
|
||||
use_sim_time=False, global_frame='map', robot_base_frame='base_link',
|
||||
update_frequency=10.0, publish_frequency=5.0, resolution=0.05,
|
||||
rolling_window=False, track_unknown_space=True, footprint=footprint,
|
||||
footprint_padding=0.05, transform_tolerance=0.2,
|
||||
always_send_full_costmap=True, plugins=['static_layer', 'inflation_layer'],
|
||||
static_layer=dict(plugin='nav2_costmap_2d::StaticLayer', map_topic='/observed_map',
|
||||
map_subscribe_transient_local=True, subscribe_to_updates=False),
|
||||
inflation_layer=dict(plugin='nav2_costmap_2d::InflationLayer',
|
||||
cost_scaling_factor=3.0, inflation_radius=math.hypot(x, y) + 0.15),
|
||||
)
|
||||
# The upstream differential primitives include pure rotation. They are
|
||||
# geometrical candidates; the drive/support/freshness gates remain required.
|
||||
lattice = ('/opt/ndc_nav2/install/nav2_smac_planner/share/nav2_smac_planner/'
|
||||
'sample_primitives/5cm_resolution/0.5m_turning_radius/diff/output.json')
|
||||
return {
|
||||
'behavior_server': {'ros__parameters': dict(
|
||||
use_sim_time=False, global_frame='map', robot_base_frame='base_link',
|
||||
costmap_topic='local_costmap/costmap_raw',
|
||||
footprint_topic='local_costmap/published_footprint',
|
||||
cycle_frequency=20.0, transform_tolerance=0.2,
|
||||
behavior_plugins=['spin', 'backup'],
|
||||
spin=dict(plugin='nav2_behaviors/Spin'),
|
||||
backup=dict(plugin='nav2_behaviors/BackUp'),
|
||||
simulate_ahead_time=0.8+speed/deceleration,
|
||||
max_rotational_vel=yaw, min_rotational_vel=0.0,
|
||||
rotational_acc_lim=2*acceleration/track_width,
|
||||
)},
|
||||
'planner_server': {'ros__parameters': dict(
|
||||
use_sim_time=False, expected_planner_frequency=5.0, planner_plugins=['GridBased'],
|
||||
GridBased=dict(plugin='nav2_smac_planner/SmacPlannerLattice',
|
||||
lattice_filepath=lattice, allow_unknown=False,
|
||||
tolerance=0.0, max_planning_time=0.5,
|
||||
allow_reverse_expansion=False, cache_obstacle_heuristic=False,
|
||||
smooth_path=False),
|
||||
)},
|
||||
'controller_server': {'ros__parameters': dict(
|
||||
use_sim_time=False, controller_frequency=20.0, odom_topic='/odom',
|
||||
min_x_velocity_threshold=0.001, min_y_velocity_threshold=0.001,
|
||||
min_theta_velocity_threshold=0.001, failure_tolerance=0.0,
|
||||
progress_checker_plugin='progress_checker', goal_checker_plugins=['goal_checker'],
|
||||
controller_plugins=['FollowPath'],
|
||||
progress_checker=dict(plugin='nav2_controller::SimpleProgressChecker',
|
||||
required_movement_radius=0.05, movement_time_allowance=8.0),
|
||||
goal_checker=dict(plugin='nav2_controller::SimpleGoalChecker', stateful=True,
|
||||
xy_goal_tolerance=float(inputs['mission']['arrival_radius_m']),
|
||||
yaw_goal_tolerance=0.15),
|
||||
FollowPath={
|
||||
'plugin': 'dwb_core::DWBLocalPlanner',
|
||||
# Upstream default: score acceleration-integrated trajectories
|
||||
# over sim_time. A one-control-period DWA window at rest has
|
||||
# sub-cell endpoints on this rover's 5 cm costmap and aliases
|
||||
# the distance critics. The actuator still applies its own
|
||||
# unchanged acceleration/deceleration limits.
|
||||
'trajectory_generator_name': 'dwb_plugins::StandardTrajectoryGenerator',
|
||||
'min_vel_x': 0.0, 'max_vel_x': speed,
|
||||
'min_vel_y': 0.0, 'max_vel_y': 0.0,
|
||||
'max_vel_theta': yaw, 'min_speed_xy': 0.0,
|
||||
'max_speed_xy': speed, 'min_speed_theta': 0.0,
|
||||
'acc_lim_x': acceleration, 'decel_lim_x': -deceleration,
|
||||
'acc_lim_y': 0.0, 'decel_lim_y': 0.0,
|
||||
'acc_lim_theta': 2 * acceleration / track_width,
|
||||
'decel_lim_theta': -2 * deceleration / track_width,
|
||||
'vx_samples': 20, 'vy_samples': 1, 'vtheta_samples': 20,
|
||||
'sim_time': 0.8 + speed / deceleration,
|
||||
'linear_granularity': 0.025, 'angular_granularity': 0.025,
|
||||
'transform_tolerance': 0.2, 'trans_stopped_velocity': 0.01,
|
||||
'xy_goal_tolerance': float(inputs['mission']['arrival_radius_m']),
|
||||
'short_circuit_trajectory_evaluation': True,
|
||||
'critics': ['ndc_rover_critics::ForwardTracksCritic', 'RotateToGoal',
|
||||
'Oscillation', 'ObstacleFootprint', 'PreferForward',
|
||||
'GoalAlign', 'PathAlign', 'PathDist', 'GoalDist'],
|
||||
'ndc_rover_critics::ForwardTracksCritic.track_centres_y_m': track_centres,
|
||||
# Upstream angular preference; no arbitrary minimum speed in
|
||||
# the initial acceleration window. Geometry gates stay hard.
|
||||
'PreferForward.strafe_x': 0.0,
|
||||
'PreferForward.strafe_theta': 0.0,
|
||||
'ObstacleFootprint.scale': 0.02,
|
||||
'PathAlign.scale': 32.0, 'PathAlign.forward_point_distance': x,
|
||||
'GoalAlign.scale': 24.0, 'GoalAlign.forward_point_distance': x,
|
||||
'PathDist.scale': 32.0, 'GoalDist.scale': 24.0,
|
||||
'RotateToGoal.scale': 32.0, 'RotateToGoal.slowing_factor': 5.0,
|
||||
'RotateToGoal.lookahead_time': -1.0,
|
||||
},
|
||||
)},
|
||||
'global_costmap': {'global_costmap': {'ros__parameters': costmap}},
|
||||
'local_costmap': {'local_costmap': {'ros__parameters': copy.deepcopy(costmap)}},
|
||||
}
|
||||
|
||||
|
||||
def observed_configuration(inputs, robot, origin_count):
|
||||
"""Use upstream ray clearing/obstacle marking for a rolling collision map.
|
||||
|
||||
Ground support and surface permission are separate inputs/gates. In
|
||||
particular, a free collision cell is not evidence of supporting pavement.
|
||||
"""
|
||||
if type(origin_count) is not int or not 1 <= origin_count <= 16:
|
||||
raise ValueError('Invalid observed sensor origin count')
|
||||
config = configuration(inputs, robot)
|
||||
sources = {
|
||||
'hazards': dict(topic='/observed_hazards', data_type='PointCloud2',
|
||||
sensor_frame='base_link', marking=True, clearing=False,
|
||||
min_obstacle_height=-0.01, max_obstacle_height=0.01,
|
||||
obstacle_min_range=0.0, obstacle_max_range=16.0,
|
||||
observation_persistence=0.0),
|
||||
}
|
||||
for index in range(origin_count):
|
||||
sources['range' + str(index)] = dict(
|
||||
topic='/observed_rays_' + str(index), data_type='PointCloud2',
|
||||
sensor_frame='range' + str(index), marking=False, clearing=True,
|
||||
min_obstacle_height=-0.01, max_obstacle_height=0.01,
|
||||
raytrace_min_range=0.0, raytrace_max_range=8.0,
|
||||
observation_persistence=0.0,
|
||||
)
|
||||
layer = dict(plugin='nav2_costmap_2d::ObstacleLayer',
|
||||
footprint_clearing_enabled=True,
|
||||
observation_sources=' '.join(sources), **sources)
|
||||
for name in ('global_costmap', 'local_costmap'):
|
||||
costmap = config[name][name]['ros__parameters']
|
||||
costmap.pop('static_layer')
|
||||
costmap.update(rolling_window=True, width=16, height=16,
|
||||
plugins=['obstacle_layer', 'inflation_layer'],
|
||||
obstacle_layer=copy.deepcopy(layer))
|
||||
return config
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
source /opt/ros/humble/setup.bash
|
||||
source /opt/underlay_ws/install/setup.bash
|
||||
source /opt/ndc_nav2/install/setup.bash
|
||||
exec "$@"
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Own only upstream Nav2 processes; stop the group when any node exits."""
|
||||
import argparse
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--parameters', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
processes = []
|
||||
stopped = False
|
||||
|
||||
def stop(signum, frame):
|
||||
nonlocal stopped
|
||||
stopped = True
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
try:
|
||||
for package, executable in (('nav2_planner', 'planner_server'),
|
||||
('nav2_controller', 'controller_server'),
|
||||
('nav2_behaviors', 'behavior_server')):
|
||||
binary = '/opt/ndc_nav2/install/' + package + '/lib/' + package + '/' + executable
|
||||
processes.append(subprocess.Popen(
|
||||
[binary, '--ros-args', '--params-file', str(args.parameters), '-r',
|
||||
'/cmd_vel:=/nav2/'+('behavior' if package=='nav2_behaviors' else 'controller')+'_cmd_vel']))
|
||||
while not stopped and all(p.poll() is None for p in processes):
|
||||
time.sleep(.05)
|
||||
if not stopped:
|
||||
raise RuntimeError('A required Nav2 node exited')
|
||||
finally:
|
||||
for process in processes:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
for process in processes:
|
||||
try:
|
||||
process.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=3)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Publish first-hit clearing rays and measured hazards to Nav2 ObstacleLayer.
|
||||
|
||||
Collision free space is not ground support or permission to drive. Those
|
||||
independent gates keep the existing observed terrain and semantic evidence.
|
||||
"""
|
||||
import math
|
||||
import struct
|
||||
|
||||
from geometry_msgs.msg import TransformStamped
|
||||
from rclpy.time import Time
|
||||
from sensor_msgs.msg import PointCloud2, PointField
|
||||
|
||||
|
||||
def cloud(stamp, frame, points):
|
||||
message = PointCloud2()
|
||||
message.header.stamp, message.header.frame_id = stamp, frame
|
||||
message.height, message.width = 1, len(points)
|
||||
message.fields = [PointField(name=name, offset=4*i, datatype=PointField.FLOAT32, count=1)
|
||||
for i, name in enumerate(('x','y','z'))]
|
||||
message.is_bigendian, message.is_dense = False, True
|
||||
message.point_step, message.row_step = 12, 12*len(points)
|
||||
message.data = b''.join(struct.pack('<fff', float(p[0]), float(p[1]), 0.) for p in points)
|
||||
return message
|
||||
|
||||
|
||||
class ObservedCollision:
|
||||
def __init__(self, node, max_step, origin_count):
|
||||
self.node, self.max_step = node, max_step
|
||||
self.rays = [node.create_publisher(PointCloud2, '/observed_rays_'+str(i), 2)
|
||||
for i in range(origin_count)]
|
||||
self.hazards = node.create_publisher(PointCloud2, '/observed_hazards', 2)
|
||||
|
||||
def publish(self, request, terrain, elapsed):
|
||||
rays = request['range_rays']
|
||||
age = float(request['geometry_age_seconds'])+elapsed
|
||||
if not math.isfinite(age) or age < 0 or len(rays['origins']) != len(self.rays):
|
||||
raise ValueError('Invalid observed collision age/origins')
|
||||
if age > .8:
|
||||
return False
|
||||
stamp = Time(nanoseconds=self.node.get_clock().now().nanoseconds-int(age*1e9)).to_msg()
|
||||
transforms=[]
|
||||
for i, origin in enumerate(rays['origins']):
|
||||
tf = TransformStamped()
|
||||
tf.header.frame_id, tf.child_frame_id, tf.header.stamp = 'map','range'+str(i),stamp
|
||||
tf.transform.translation.x, tf.transform.translation.y = map(float, origin[:2])
|
||||
tf.transform.rotation.w = 1.
|
||||
transforms.append(tf)
|
||||
self.node.tf.sendTransform(transforms)
|
||||
for i, (publisher, origin) in enumerate(zip(self.rays, rays['origins'])):
|
||||
points=[[end[0]-origin[0],end[1]-origin[1]]
|
||||
for end, owner in zip(rays['ends'], rays['origin_indices']) if owner==i]
|
||||
publisher.publish(cloud(stamp,'range'+str(i),points))
|
||||
self.hazards.publish(cloud(stamp,'map',terrain[terrain[:,3]>self.max_step+1e-4]))
|
||||
return True
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Prepare existing geometry kernels and a narrow DWB track critic, offline."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import tarfile
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
BASE = 'sha256:dc6daf1153157860a70dc4a62419da0d61a5dd3941c8f41282ab9f7413a9dac6'
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('--output',type=Path,required=True)
|
||||
parser.add_argument('--ground',action='store_true',help='Build PCL in its existing terrain dependency image')
|
||||
args=parser.parse_args()
|
||||
root=Path(__file__).resolve().parents[1]/'navigation'
|
||||
base = 'sha256:8517fd5d13406648907c87dd4adf771238c6a3a30fcedd555ca5a5287edebc16' if args.ground else BASE
|
||||
sources={name:(root/name).read_bytes() for name in
|
||||
(('pcl_ground.cpp',) if args.ground else ('support_native.cpp','terrain_connectivity.cpp'))}
|
||||
if args.ground:
|
||||
sources['CMakeLists.txt'] = (root/'pcl_ground.cmake').read_bytes()
|
||||
if not args.ground:
|
||||
for path in (root.parent/'nav2/rover_critics').iterdir():
|
||||
if path.is_file(): sources['rover_critics/'+path.name]=path.read_bytes()
|
||||
entrypoint = 'terrain_entrypoint.sh' if args.ground else 'runtime_entrypoint.sh'
|
||||
sources['runtime_entrypoint.sh']=(root.parent/'nav2'/entrypoint).read_bytes()
|
||||
files={name:hashlib.sha256(data).hexdigest() for name,data in sources.items()}
|
||||
files['prepare_kernels.py']=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
|
||||
identity=hashlib.sha256(json.dumps(dict(base=base,files=files),sort_keys=True).encode()).hexdigest()
|
||||
args.output.mkdir(parents=True,exist_ok=False)
|
||||
report=dict(base=base,files=files,identity=identity,utc=datetime.now(timezone.utc).isoformat(),activated=False)
|
||||
cid=None;started=time.monotonic()
|
||||
def docker(*args,timeout=30,check=True):
|
||||
return subprocess.run(['docker',*args],capture_output=True,text=True,timeout=timeout,check=check)
|
||||
try:
|
||||
assert docker('image','inspect',base,'--format','{{.Id}}').stdout.strip()==base
|
||||
assert not Path('D:/NDC_MISSIONCORE/runtime/simulation/state/active.json').exists()
|
||||
command='mkdir -p /opt/missioncore && g++ -std=c++17 -O3 -shared -fPIC /sources/support_native.cpp -o /opt/missioncore/libsupport_surface.so && g++ -O3 -std=c++17 -ffp-contract=off -fno-fast-math -fPIC -shared /sources/terrain_connectivity.cpp -o /opt/missioncore/libterrain_connectivity.so'
|
||||
command += ' && source /opt/ros/humble/setup.bash && source /opt/underlay_ws/install/setup.bash && source /opt/ndc_nav2/install/setup.bash && mkdir -p /opt/ndc_rover && cd /opt/ndc_rover && MAKEFLAGS=-j2 colcon build --base-paths /sources/rover_critics --packages-select ndc_rover_critics --parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF'
|
||||
if args.ground:
|
||||
command = 'mkdir -p /opt/missioncore && cmake -S /sources -B /tmp/pcl-build -DCMAKE_BUILD_TYPE=Release && cmake --build /tmp/pcl-build -j2'
|
||||
cid=docker('create','--name','ndc-mission-core-nav2-kernels-'+identity[:16],
|
||||
'--network','none','--cpus','2','--memory','2g','--pids-limit','128','--cap-drop','ALL',
|
||||
'--security-opt','no-new-privileges','--label','com.nodedc.product=mission-core',
|
||||
'--label','com.nodedc.stack=ai-polygon','--label','com.nodedc.role=nav2-kernel-preparation',
|
||||
'--label','com.nodedc.managed-by=ai-polygon-preparation',
|
||||
'--label','com.nodedc.build-sha256='+identity,
|
||||
'--entrypoint','/bin/bash',base,'-c','exec timeout --signal=TERM --kill-after=5s 90 bash -c '+__import__('shlex').quote(command)).stdout.strip()
|
||||
report['container_id']=cid
|
||||
payload=io.BytesIO()
|
||||
with tarfile.open(fileobj=payload,mode='w') as archive:
|
||||
for name,data in sources.items():
|
||||
entry=tarfile.TarInfo('sources/'+name);entry.size=len(data)
|
||||
archive.addfile(entry,io.BytesIO(data))
|
||||
subprocess.run(['docker','cp','-',cid+':/'],input=payload.getvalue(),capture_output=True,check=True,timeout=10)
|
||||
result=docker('start','-a',cid,timeout=100,check=False)
|
||||
(args.output/'build.log').write_text(result.stdout+result.stderr)
|
||||
if result.returncode:raise RuntimeError('Existing geometry kernels did not compile')
|
||||
docker('cp',cid+':/opt/missioncore',str(args.output/'kernels'))
|
||||
report['kernels']={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in (args.output/'kernels').iterdir()}
|
||||
tag=('ndc-mission-core-terrain:pcl-ground-' if args.ground else 'ndc-mission-core-nav2:1.1.17-rover-')+identity[:16]
|
||||
image=docker('commit','--change','ENTRYPOINT ["/bin/bash", "/sources/runtime_entrypoint.sh"]',
|
||||
'--change','CMD ["bash"]','--change','LABEL com.nodedc.role=nav2-runtime',cid,tag,timeout=120).stdout.strip()
|
||||
report.update(image=image,tag=tag,status='built')
|
||||
except BaseException as error:
|
||||
report.update(status='failed',error=type(error).__name__+': '+str(error));raise
|
||||
finally:
|
||||
if cid:
|
||||
docker('rm','-f',cid)
|
||||
report['cleanup_confirmed']=not docker('ps','-aq','--filter','id='+cid).stdout.strip()
|
||||
report['elapsed_s']=time.monotonic()-started
|
||||
(args.output/'build.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Compare native Nav2 on archived first-hit rays and classified obstacles.
|
||||
|
||||
Replays captured data on a diagnostic ROS clock with no actuator or live
|
||||
command authority. No scene mesh, synthesized floor, or added route points.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import rclpy
|
||||
import yaml
|
||||
from action_msgs.msg import GoalStatus
|
||||
from check_ros_integration import Check
|
||||
from configuration import observed_configuration
|
||||
from geometry_msgs.msg import TransformStamped
|
||||
from lifecycle_msgs.msg import Transition
|
||||
from nav2_msgs.action import ComputePathToPose
|
||||
from nav2_msgs.srv import GetCostmap
|
||||
from nav_msgs.msg import Odometry
|
||||
from sensor_msgs.msg import PointCloud2
|
||||
from observed_collision import cloud
|
||||
|
||||
|
||||
class Replay(Check):
|
||||
def __init__(self, snapshot, max_step):
|
||||
self.request = snapshot['exchange']['request']
|
||||
self.rays = self.request['range_rays']
|
||||
self.pose = self.request['pose']
|
||||
self.hazards = [p for p in snapshot['exchange']['terrain'] if p[3] > max_step + 1e-4]
|
||||
x, y, z, w = self.pose[3:]
|
||||
self.yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
|
||||
super().__init__()
|
||||
self.ray_pubs = [self.create_publisher(PointCloud2, '/observed_rays_' + str(i), 2)
|
||||
for i in range(len(self.rays['origins']))]
|
||||
self.hazard_pub = self.create_publisher(PointCloud2, '/observed_hazards', 2)
|
||||
self.ray_timer = self.create_timer(0.1, self.publish_observation)
|
||||
|
||||
def publish_pose(self):
|
||||
transforms = []
|
||||
stamp = self.get_clock().now().to_msg()
|
||||
for name, xyz, yaw in [('base_link', self.pose[:3], self.yaw), *[
|
||||
('range' + str(i), p, 0.) for i, p in enumerate(self.rays['origins'])]]:
|
||||
tf = TransformStamped()
|
||||
tf.header.stamp, tf.header.frame_id, tf.child_frame_id = stamp, 'map', name
|
||||
tf.transform.translation.x, tf.transform.translation.y = map(float, xyz[:2])
|
||||
tf.transform.rotation.z, tf.transform.rotation.w = math.sin(yaw/2), math.cos(yaw/2)
|
||||
transforms.append(tf)
|
||||
self.tf.sendTransform(transforms)
|
||||
odom = Odometry()
|
||||
odom.header.stamp, odom.header.frame_id, odom.child_frame_id = stamp, 'map', 'base_link'
|
||||
odom.pose.pose.position.x, odom.pose.pose.position.y = map(float, self.pose[:2])
|
||||
odom.pose.pose.orientation = transforms[0].transform.rotation
|
||||
self.odom_pub.publish(odom)
|
||||
|
||||
def publish_observation(self):
|
||||
stamp = self.get_clock().now().to_msg()
|
||||
for index, (publisher, origin) in enumerate(zip(self.ray_pubs, self.rays['origins'])):
|
||||
points = [[end[0]-origin[0], end[1]-origin[1]]
|
||||
for end, owner in zip(self.rays['ends'], self.rays['origin_indices'])
|
||||
if owner == index]
|
||||
publisher.publish(cloud(stamp, 'range' + str(index), points))
|
||||
self.hazard_pub.publish(cloud(stamp, 'map', self.hazards))
|
||||
|
||||
def plan(self):
|
||||
if not self.planner.wait_for_server(timeout_sec=5):
|
||||
raise TimeoutError('Planner action unavailable')
|
||||
request = ComputePathToPose.Goal()
|
||||
request.planner_id, request.use_start = 'GridBased', True
|
||||
goal = self.request['goal']
|
||||
heading = math.atan2(goal[1]-self.pose[1], goal[0]-self.pose[0])
|
||||
for target, position, yaw in ((request.start, self.pose, self.yaw),
|
||||
(request.goal, goal, heading)):
|
||||
target.header.frame_id, target.header.stamp = 'map', self.get_clock().now().to_msg()
|
||||
target.pose.position.x, target.pose.position.y = map(float, position[:2])
|
||||
target.pose.orientation.z, target.pose.orientation.w = math.sin(yaw/2), math.cos(yaw/2)
|
||||
handle = self.await_result(self.planner.send_goal_async(request))
|
||||
if not handle.accepted:
|
||||
raise RuntimeError('Planner action was not accepted')
|
||||
return self.await_result(handle.get_result_async())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
for name in ('inputs', 'robot', 'snapshot', 'output'):
|
||||
parser.add_argument('--' + name, type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
inputs, robot = json.loads(args.inputs.read_text()), json.loads(args.robot.read_text())
|
||||
snapshot = json.loads(args.snapshot.read_text())
|
||||
if snapshot['exchange']['request']['execution_inputs_sha256'] != inputs['sha256']:
|
||||
raise ValueError('Archived observation execution identity mismatch')
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
config = observed_configuration(inputs, robot, len(snapshot['exchange']['request']['range_rays']['origins']))
|
||||
parameters = args.output / 'parameters.yaml'
|
||||
parameters.write_text(yaml.safe_dump(config, sort_keys=False))
|
||||
report = dict(authority=None, qualified=False, scope='archived-input Nav2 diagnostic',
|
||||
snapshot_sha256=hashlib.sha256(args.snapshot.read_bytes()).hexdigest(),
|
||||
configuration_sha256=hashlib.sha256(parameters.read_bytes()).hexdigest(),
|
||||
source_observation_id=snapshot['exchange']['observation_id'])
|
||||
processes, logs = [], []
|
||||
rclpy.init()
|
||||
node = Replay(snapshot, inputs['robot']['geometry']['max_step_m'])
|
||||
try:
|
||||
for package, executable in (('nav2_planner', 'planner_server'),
|
||||
('nav2_controller', 'controller_server')):
|
||||
log = (args.output / (executable + '.log')).open('w'); logs.append(log)
|
||||
processes.append(subprocess.Popen(
|
||||
['/opt/ndc_nav2/install/' + package + '/lib/' + package + '/' + executable,
|
||||
'--ros-args', '--params-file', str(parameters)], stdout=log, stderr=subprocess.STDOUT))
|
||||
node.lifecycle(executable, Transition.TRANSITION_CONFIGURE)
|
||||
node.lifecycle(executable, Transition.TRANSITION_ACTIVATE)
|
||||
node.spin_for(0.5)
|
||||
client = node.create_client(GetCostmap, '/global_costmap/get_costmap')
|
||||
assert client.wait_for_service(timeout_sec=5)
|
||||
grid = node.await_result(client.call_async(GetCostmap.Request())).map
|
||||
(args.output / 'costmap.json').write_text(json.dumps(dict(
|
||||
origin=[grid.metadata.origin.position.x, grid.metadata.origin.position.y],
|
||||
resolution=grid.metadata.resolution, size=[grid.metadata.size_x, grid.metadata.size_y],
|
||||
data=list(grid.data))))
|
||||
result = node.plan()
|
||||
report.update(status=result.status,
|
||||
path=[[p.pose.position.x, p.pose.position.y, p.pose.orientation.z, p.pose.orientation.w]
|
||||
for p in result.result.path.poses],
|
||||
original={k:snapshot['exchange']['result'][k] for k in ('status', 'speed_mps', 'yaw_rate_rps')})
|
||||
if result.status == GoalStatus.STATUS_SUCCEEDED:
|
||||
report['controller'] = node.follow_and_cancel(result.result.path)
|
||||
except BaseException as error:
|
||||
report['error'] = type(error).__name__ + ': ' + str(error)
|
||||
raise
|
||||
finally:
|
||||
for process in processes:
|
||||
process.terminate()
|
||||
for process in processes:
|
||||
try:
|
||||
process.wait(timeout=3)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill(); process.wait(timeout=3)
|
||||
for log in logs:
|
||||
log.close()
|
||||
node.destroy_node(); rclpy.shutdown()
|
||||
(args.output / 'result.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
print(json.dumps({k:v for k,v in report.items() if k not in ('path','controller')}, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,291 @@
|
||||
"""ROS action/message boundary; upstream Nav2 owns paths and velocity proposals.
|
||||
|
||||
The caller spins this node and owns observation/command leases. Repeating TF
|
||||
uses the original measurement stamp. FollowPath updates use Nav2's native
|
||||
preemption; command admission resumes after feedback for the new goal.
|
||||
"""
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
from action_msgs.msg import GoalStatus
|
||||
from builtin_interfaces.msg import Duration
|
||||
from geometry_msgs.msg import TransformStamped, Twist
|
||||
from lifecycle_msgs.msg import Transition
|
||||
from lifecycle_msgs.srv import ChangeState
|
||||
from nav2_msgs.action import BackUp, ComputePathToPose, FollowPath, Spin
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.action import ActionClient
|
||||
from rclpy.node import Node
|
||||
from rclpy.time import Time
|
||||
from tf2_ros import TransformBroadcaster
|
||||
|
||||
|
||||
def yaw_of(pose):
|
||||
x, y, z, w = pose[3:]
|
||||
return math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
|
||||
|
||||
|
||||
class RosNavigation(Node):
|
||||
def __init__(self):
|
||||
super().__init__('missioncore_nav2_adapter')
|
||||
self.condition = threading.Condition()
|
||||
self.action_lock = threading.Lock()
|
||||
self.pose = None
|
||||
self.action_handle = self.terminal = self.latest_command = None
|
||||
self.command_sequence = 0
|
||||
self.action_sequence = 0
|
||||
self.last_zero_sequence = 0
|
||||
self.failed = False
|
||||
self.pending_feedback = None
|
||||
self.history = deque(maxlen=256)
|
||||
self.tf = TransformBroadcaster(self)
|
||||
self.odom = self.create_publisher(Odometry, '/odom', 5)
|
||||
self.create_timer(.02, self.publish_pose)
|
||||
self.active_source = None
|
||||
for source in ('controller', 'behavior'):
|
||||
self.create_subscription(Twist, '/nav2/'+source+'_cmd_vel',
|
||||
lambda value, owner=source: self.on_command(value, owner), 20)
|
||||
self.planner = ActionClient(self, ComputePathToPose, '/compute_path_to_pose')
|
||||
self.controller = ActionClient(self, FollowPath, '/follow_path')
|
||||
self.spin_client = ActionClient(self, Spin, '/spin')
|
||||
self.backup_client = ActionClient(self, BackUp, '/backup')
|
||||
|
||||
@staticmethod
|
||||
def await_result(future, timeout):
|
||||
done = threading.Event()
|
||||
future.add_done_callback(lambda _: done.set())
|
||||
if not done.wait(timeout):
|
||||
raise TimeoutError('Nav2 response timeout')
|
||||
return future.result()
|
||||
|
||||
def activate(self):
|
||||
for name in ('planner_server', 'controller_server', 'behavior_server'):
|
||||
client = self.create_client(ChangeState, '/' + name + '/change_state')
|
||||
try:
|
||||
if not client.wait_for_service(timeout_sec=8):
|
||||
raise TimeoutError(name + ' unavailable')
|
||||
for transition in (Transition.TRANSITION_CONFIGURE, Transition.TRANSITION_ACTIVATE):
|
||||
request = ChangeState.Request()
|
||||
request.transition.id = transition
|
||||
if not self.await_result(client.call_async(request), 8).success:
|
||||
raise RuntimeError(name + ' lifecycle transition failed')
|
||||
finally:
|
||||
self.destroy_client(client)
|
||||
for client in (self.planner, self.controller, self.spin_client, self.backup_client):
|
||||
if not client.wait_for_server(timeout_sec=2):
|
||||
raise TimeoutError('Nav2 action unavailable')
|
||||
|
||||
def observe_pose(self, pose, age, twist=None):
|
||||
if (len(pose) != 7 or (twist is not None and len(twist) != 3)
|
||||
or not all(math.isfinite(float(v)) for v in (*pose, *(twist or []), age))
|
||||
or age < 0 or abs(sum(v*v for v in pose[3:])-1) > .02):
|
||||
raise ValueError('Invalid measured odometry')
|
||||
now = time.monotonic()
|
||||
stamp = self.get_clock().now().nanoseconds-int(age*1e9)
|
||||
if stamp < 0:
|
||||
raise ValueError('Invalid odometry stamp')
|
||||
with self.condition:
|
||||
captured = now-age
|
||||
if self.pose is None or captured >= self.pose[0]:
|
||||
self.pose = (captured, tuple(pose), tuple(twist) if twist is not None else None, stamp)
|
||||
self.publish_pose()
|
||||
|
||||
def publish_pose(self):
|
||||
with self.condition:
|
||||
measured = self.pose
|
||||
if measured is None or time.monotonic()-measured[0] > .5:
|
||||
return
|
||||
_, pose, twist, stamp = measured
|
||||
yaw = yaw_of(pose)
|
||||
transform = TransformStamped()
|
||||
transform.header.frame_id, transform.child_frame_id = 'map', 'base_link'
|
||||
transform.header.stamp = Time(nanoseconds=stamp).to_msg()
|
||||
transform.transform.translation.x, transform.transform.translation.y = map(float, pose[:2])
|
||||
transform.transform.rotation.z, transform.transform.rotation.w = math.sin(yaw/2), math.cos(yaw/2)
|
||||
self.tf.sendTransform(transform)
|
||||
if twist is None:
|
||||
return # A bootstrap pose is not a measured zero velocity.
|
||||
odom = Odometry()
|
||||
odom.header, odom.child_frame_id = transform.header, 'base_link'
|
||||
odom.pose.pose.position.x, odom.pose.pose.position.y = map(float, pose[:2])
|
||||
odom.pose.pose.orientation = transform.transform.rotation
|
||||
odom.twist.twist.linear.x, odom.twist.twist.linear.y, odom.twist.twist.angular.z = map(float, twist)
|
||||
self.odom.publish(odom)
|
||||
|
||||
def on_command(self, value, source):
|
||||
command = (time.monotonic(), float(value.linear.x), float(value.angular.z))
|
||||
with self.condition:
|
||||
if source != self.active_source:
|
||||
return
|
||||
self.command_sequence += 1
|
||||
self.history.append((self.command_sequence, *command))
|
||||
if command[1:] == (0., 0.):
|
||||
self.last_zero_sequence = self.command_sequence
|
||||
if self.pending_feedback is None:
|
||||
self.latest_command = command
|
||||
self.condition.notify_all()
|
||||
|
||||
def plan(self, pose, goal, yaw):
|
||||
request = ComputePathToPose.Goal()
|
||||
request.planner_id, request.use_start = 'GridBased', True
|
||||
for target, xy, heading in ((request.start, pose[:2], yaw_of(pose)),
|
||||
(request.goal, goal[:2], yaw)):
|
||||
target.header.frame_id, target.header.stamp = 'map', self.get_clock().now().to_msg()
|
||||
target.pose.position.x, target.pose.position.y = map(float, xy)
|
||||
target.pose.orientation.z, target.pose.orientation.w = math.sin(heading/2), math.cos(heading/2)
|
||||
handle = self.accept(self.planner, request, .2)
|
||||
if not handle.accepted:
|
||||
raise RuntimeError('Nav2 planner rejected request')
|
||||
try:
|
||||
result = self.await_result(handle.get_result_async(), .65)
|
||||
except TimeoutError:
|
||||
# Do not leave work from a timed-out HTTP transaction as authority.
|
||||
self.await_result(handle.cancel_goal_async(), .2)
|
||||
raise
|
||||
return result.result.path if result.status == GoalStatus.STATUS_SUCCEEDED else None
|
||||
|
||||
def accept(self, client, request, timeout, feedback_callback=None):
|
||||
if self.failed:
|
||||
raise RuntimeError('Nav2 action boundary requires reset')
|
||||
options = {} if feedback_callback is None else {'feedback_callback': feedback_callback}
|
||||
future = client.send_goal_async(request, **options)
|
||||
try:
|
||||
return self.await_result(future, timeout)
|
||||
except TimeoutError:
|
||||
# A late action acceptance must not survive the failed transaction.
|
||||
# The callback cannot block the ROS executor waiting for its reply.
|
||||
with self.condition:
|
||||
self.failed = True
|
||||
self.active_source = self.latest_command = None
|
||||
def cancel_late(done):
|
||||
handle = done.result()
|
||||
if handle is not None and handle.accepted:
|
||||
handle.cancel_goal_async()
|
||||
future.add_done_callback(cancel_late)
|
||||
raise
|
||||
|
||||
def _stop(self):
|
||||
if self.action_handle is None:
|
||||
return
|
||||
with self.condition:
|
||||
self.pending_feedback = None
|
||||
sequence = self.command_sequence
|
||||
if not self.terminal.done():
|
||||
self.await_result(self.action_handle.cancel_goal_async(), .25)
|
||||
result = self.await_result(self.terminal, .4)
|
||||
if result.status not in (GoalStatus.STATUS_CANCELED, GoalStatus.STATUS_SUCCEEDED,
|
||||
GoalStatus.STATUS_ABORTED):
|
||||
raise RuntimeError('Nav2 action did not terminate')
|
||||
with self.condition:
|
||||
if not self.condition.wait_for(lambda: self.last_zero_sequence > sequence, .25):
|
||||
raise TimeoutError('Nav2 cancellation zero was not observed')
|
||||
else:
|
||||
with self.condition:
|
||||
if not self.condition.wait_for(
|
||||
lambda: self.last_zero_sequence > self.action_sequence, .25):
|
||||
raise TimeoutError('Nav2 terminal zero was not observed')
|
||||
self.action_handle = self.terminal = None
|
||||
with self.condition:
|
||||
self.active_source = None
|
||||
self.latest_command = None
|
||||
|
||||
def stop(self):
|
||||
with self.action_lock:
|
||||
self._stop()
|
||||
|
||||
def _execute(self, client, request, source):
|
||||
with self.action_lock:
|
||||
self._stop()
|
||||
with self.condition:
|
||||
self.latest_command = None
|
||||
self.active_source = source
|
||||
sequence = self.command_sequence
|
||||
self.action_sequence = sequence
|
||||
self.action_handle = self.accept(client, request, .25)
|
||||
if not self.action_handle.accepted:
|
||||
self.action_handle = None
|
||||
self.active_source = None
|
||||
raise RuntimeError('Nav2 motion action rejected request')
|
||||
self.terminal = self.action_handle.get_result_async()
|
||||
with self.condition:
|
||||
self.condition.wait_for(lambda: self.command_sequence > sequence
|
||||
and self.latest_command is not None, .25)
|
||||
return self.native_command()
|
||||
|
||||
def follow(self, path, *, continuing=False):
|
||||
request = FollowPath.Goal()
|
||||
request.path, request.controller_id, request.goal_checker_id = path, 'FollowPath', 'goal_checker'
|
||||
with self.action_lock:
|
||||
# The controller's updateGlobalPath accepts a pending FollowPath
|
||||
# without zeroing velocity or resetting its progress checker.
|
||||
# Spin/BackUp still require terminal cancellation and a zero.
|
||||
if self.active_source != 'controller' or self.terminal is None or self.terminal.done():
|
||||
self._stop()
|
||||
continuing = False
|
||||
token = object()
|
||||
received = threading.Event()
|
||||
with self.condition:
|
||||
# Updating geometry for the same goal preserves the native
|
||||
# command stream. A changed goal still needs new feedback.
|
||||
self.pending_feedback = None if continuing else token
|
||||
if not continuing:
|
||||
self.latest_command = None
|
||||
self.active_source = 'controller'
|
||||
sequence = self.command_sequence
|
||||
self.action_sequence = sequence
|
||||
def feedback(_):
|
||||
# Feedback is emitted only after updateGlobalPath and the
|
||||
# new path's computeVelocityCommands in the pinned server.
|
||||
with self.condition:
|
||||
if continuing:
|
||||
received.set()
|
||||
elif self.pending_feedback is token:
|
||||
self.pending_feedback = None
|
||||
self.latest_command = None
|
||||
received.set()
|
||||
handle = self.accept(self.controller, request, .25, feedback)
|
||||
if not handle.accepted:
|
||||
with self.condition:
|
||||
self.failed = True
|
||||
self.active_source = self.latest_command = None
|
||||
raise RuntimeError('Nav2 path update rejected')
|
||||
self.action_handle, self.terminal = handle, handle.get_result_async()
|
||||
if continuing:
|
||||
# This same-goal stream is already admitted during preemption.
|
||||
# Waiting for its feedback only delays the next sensor frame;
|
||||
# accept() still fences rejection and late action acceptance.
|
||||
return self.native_command()
|
||||
if not received.wait(.25):
|
||||
# Do not bind a proposal to a path not yet used by Nav2.
|
||||
# A later /control may use it once matching feedback arrives.
|
||||
return self.native_command() if continuing else None
|
||||
with self.condition:
|
||||
self.condition.wait_for(lambda: self.command_sequence > sequence
|
||||
and self.latest_command is not None, .25)
|
||||
return self.native_command()
|
||||
|
||||
def spin(self, angle, duration):
|
||||
if not math.isfinite(angle) or abs(angle) > math.pi or not math.isfinite(duration) or duration < 0:
|
||||
raise ValueError('Invalid orientation goal')
|
||||
request = Spin.Goal()
|
||||
request.target_yaw = float(angle)
|
||||
request.time_allowance = Duration(sec=int(duration), nanosec=int((duration%1)*1e9))
|
||||
return self._execute(self.spin_client, request, 'behavior')
|
||||
|
||||
def backup(self, distance, speed, duration):
|
||||
if (not all(math.isfinite(v) and v > 0 for v in (distance, speed))
|
||||
or not math.isfinite(duration) or duration < 0):
|
||||
raise ValueError('Invalid reverse goal')
|
||||
request = BackUp.Goal()
|
||||
request.target.x, request.speed = float(distance), float(speed)
|
||||
request.time_allowance = Duration(sec=int(duration), nanosec=int((duration%1)*1e9))
|
||||
return self._execute(self.backup_client, request, 'behavior')
|
||||
|
||||
def native_command(self):
|
||||
with self.condition:
|
||||
if (self.failed or self.pending_feedback is not None or self.action_handle is None
|
||||
or self.terminal is None or self.terminal.done()):
|
||||
return None
|
||||
return self.latest_command
|
||||
@@ -0,0 +1,14 @@
|
||||
cmake_minimum_required(VERSION 3.8)
|
||||
project(ndc_rover_critics)
|
||||
find_package(ament_cmake REQUIRED)
|
||||
find_package(dwb_core REQUIRED)
|
||||
find_package(dwb_msgs REQUIRED)
|
||||
find_package(nav2_util REQUIRED)
|
||||
find_package(rclcpp REQUIRED)
|
||||
find_package(pluginlib REQUIRED)
|
||||
add_library(ndc_rover_critics SHARED forward_tracks.cpp)
|
||||
target_compile_features(ndc_rover_critics PUBLIC cxx_std_17)
|
||||
ament_target_dependencies(ndc_rover_critics dwb_core dwb_msgs nav2_util rclcpp pluginlib)
|
||||
pluginlib_export_plugin_description_file(dwb_core critics.xml)
|
||||
install(TARGETS ndc_rover_critics LIBRARY DESTINATION lib)
|
||||
ament_package()
|
||||
@@ -0,0 +1,5 @@
|
||||
<library path="ndc_rover_critics">
|
||||
<class type="ndc_rover_critics::ForwardTracksCritic" base_class_type="dwb_core::TrajectoryCritic">
|
||||
<description>Reject forward arcs requiring a track to reverse; native in-place spin remains separate.</description>
|
||||
</class>
|
||||
</library>
|
||||
@@ -0,0 +1,40 @@
|
||||
// DWB owns velocity sampling/scoring. This admits the rover's existing forward
|
||||
// mode before scoring; it does not rewrite a velocity or propose another path.
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
#include "dwb_core/trajectory_critic.hpp"
|
||||
#include "dwb_core/exceptions.hpp"
|
||||
#include "nav2_util/node_utils.hpp"
|
||||
#include "pluginlib/class_list_macros.hpp"
|
||||
|
||||
namespace ndc_rover_critics {
|
||||
class ForwardTracksCritic : public dwb_core::TrajectoryCritic {
|
||||
std::vector<double> centres_;
|
||||
public:
|
||||
void onInit() override {
|
||||
auto node = node_.lock();
|
||||
if (!node) {throw std::runtime_error("No DWB lifecycle node");}
|
||||
const auto key = dwb_plugin_name_ + "." + name_ + ".track_centres_y_m";
|
||||
nav2_util::declare_parameter_if_not_declared(
|
||||
node, key, rclcpp::ParameterValue(std::vector<double>{}));
|
||||
node->get_parameter(key, centres_);
|
||||
if (centres_.size() != 2 || !std::isfinite(centres_[0]) ||
|
||||
!std::isfinite(centres_[1]) || centres_[0] <= centres_[1]) {
|
||||
throw std::runtime_error("Ordered measured left/right track centres required");
|
||||
}
|
||||
}
|
||||
double scoreTrajectory(const dwb_msgs::msg::Trajectory2D & traj) override {
|
||||
const double v = traj.velocity.x, w = traj.velocity.theta;
|
||||
// Match SupportPolicy.fresh_context's existing 1e-6 direction boundary:
|
||||
// a stationary inner track needs both front/rear observations, just as a
|
||||
// spin does. Forward mode keeps both tracks moving forward; it cannot
|
||||
// silently request that different observation contract at the boundary.
|
||||
if (v > 1e-8 && (v - w*centres_[0] < 1e-6 || v - w*centres_[1] < 1e-6)) {
|
||||
throw dwb_core::IllegalTrajectoryException(name_, "Forward arc stops or reverses a track");
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
};
|
||||
}
|
||||
PLUGINLIB_EXPORT_CLASS(ndc_rover_critics::ForwardTracksCritic, dwb_core::TrajectoryCritic)
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="3">
|
||||
<name>ndc_rover_critics</name><version>0.1.0</version>
|
||||
<description>Selected track kinematics admission for upstream DWB candidates.</description>
|
||||
<maintainer email="engineering@nodedc.local">Mission Core</maintainer>
|
||||
<license>BSD-3-Clause</license>
|
||||
<buildtool_depend>ament_cmake</buildtool_depend>
|
||||
<depend>dwb_core</depend><depend>dwb_msgs</depend><depend>nav2_util</depend>
|
||||
<depend>rclcpp</depend><depend>pluginlib</depend>
|
||||
<export><build_type>ament_cmake</build_type></export>
|
||||
</package>
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
source /opt/ros/humble/setup.bash
|
||||
source /opt/underlay_ws/install/setup.bash
|
||||
source /opt/ndc_nav2/install/setup.bash
|
||||
source /opt/ndc_rover/install/setup.bash
|
||||
exec "$@"
|
||||
@@ -0,0 +1,324 @@
|
||||
"""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
|
||||
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 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.path = None
|
||||
self.path_planned_at = float('-inf')
|
||||
self.active, self.failure = False, None
|
||||
self.activating = False
|
||||
self.latest_terrain = 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 plan(self, value):
|
||||
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):
|
||||
return self.reply('stale-range')
|
||||
route = route_observation(terrain, pose, value, self.monitor.max_step)
|
||||
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
|
||||
# Smac/DWB owns the approach to a permitted translation destination,
|
||||
# including recovery goals. Forcing a bearing-alignment Spin first can
|
||||
# sweep the rear into an obstacle when a forward arc is available.
|
||||
# Spin belongs only to explicit orientation-only intent; its completion
|
||||
# cannot authorize translation. BackUp keeps the existing body heading.
|
||||
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.node.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:
|
||||
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.)
|
||||
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)
|
||||
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)
|
||||
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 = 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()
|
||||
return self.reply('no-path', status='blocked', route_observation=route)
|
||||
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
|
||||
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(),
|
||||
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()
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"repository": "https://github.com/ros-navigation/navigation2",
|
||||
"version": "1.1.17",
|
||||
"commit": "0f8fda36ca1b84a840ad9b72a6c71776eefa6790",
|
||||
"archive_url": "https://codeload.github.com/ros-navigation/navigation2/tar.gz/0f8fda36ca1b84a840ad9b72a6c71776eefa6790",
|
||||
"archive_sha256": "641b6abe527eb862e9102259e3d4a33d5f8823f0bed7079adf4e785d466b6d1d",
|
||||
"base_image": "sha256:48d3727817bdb1582a40c46f3d2caecea509a60a67895b96e6558ed24b040644",
|
||||
"base_reference": "ghcr.io/ros-navigation/navigation2@sha256:48d3727817bdb1582a40c46f3d2caecea509a60a67895b96e6558ed24b040644"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
source /opt/ros/humble/setup.bash
|
||||
source /opt/cmu/install/setup.bash
|
||||
exec "$@"
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Own/reset the unchanged terrain process inside its pinned dependency image."""
|
||||
import signal
|
||||
import subprocess
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import rclpy
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
from sensor_msgs.msg import PointCloud2, PointField
|
||||
from sensor_msgs_py import point_cloud2
|
||||
from std_srvs.srv import Trigger
|
||||
from terrain_observation import PARAMETERS
|
||||
from navigation.pcl_ground import PclGround
|
||||
|
||||
|
||||
class TerrainNode(Node):
|
||||
def __init__(self):
|
||||
super().__init__('missioncore_terrain_owner')
|
||||
geometry = json.loads(Path(os.environ['MISSIONCORE_RUN_INPUTS']).read_text())['robot']['geometry']
|
||||
self.ground = PclGround(geometry)
|
||||
self.contact_height = geometry['body_contact_height_m']
|
||||
self.pending_scans, self.pending_poses = {}, {}
|
||||
self.ground_reply = self.create_publisher(PointCloud2, '/terrain/current_ground', 2)
|
||||
self.create_subscription(PointCloud2, '/terrain/current_scan', self.scan, 2)
|
||||
self.create_subscription(Odometry, '/state_estimation', self.pose, 2)
|
||||
self.process = None
|
||||
self.start()
|
||||
self.create_service(Trigger, '/terrain/reset', self.reset)
|
||||
self.create_service(Trigger, '/terrain/ready', self.ready)
|
||||
|
||||
def start(self):
|
||||
command = ['/opt/cmu/install/terrain_analysis/lib/terrain_analysis/terrainAnalysis', '--ros-args']
|
||||
for key, value in PARAMETERS.items():
|
||||
command += ['-p', key+':='+str(value).lower()]
|
||||
self.process = subprocess.Popen(command)
|
||||
|
||||
def stop(self):
|
||||
if self.process is None:
|
||||
return
|
||||
self.process.terminate()
|
||||
try:
|
||||
self.process.wait(timeout=1)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.process.kill(); self.process.wait(timeout=1)
|
||||
self.process = None
|
||||
|
||||
def ready(self, request, response):
|
||||
response.success = self.process is not None and self.process.poll() is None
|
||||
return response
|
||||
|
||||
def reset(self, request, response):
|
||||
self.pending_scans.clear(); self.pending_poses.clear()
|
||||
self.stop(); self.start()
|
||||
return self.ready(request, response)
|
||||
|
||||
def pose(self, message):
|
||||
self.pair(message, self.pending_poses)
|
||||
|
||||
def scan(self, message):
|
||||
self.pair(message, self.pending_scans)
|
||||
|
||||
def pair(self, message, pending):
|
||||
stamp = (message.header.stamp.sec, message.header.stamp.nanosec)
|
||||
pending[stamp] = message
|
||||
while len(pending) > 2:
|
||||
del pending[next(iter(pending))]
|
||||
if stamp not in self.pending_scans or stamp not in self.pending_poses:
|
||||
return
|
||||
scan, pose = self.pending_scans.pop(stamp), self.pending_poses.pop(stamp).pose.pose
|
||||
points = point_cloud2.read_points_numpy(scan, field_names=['x','y','z']).copy()
|
||||
q = pose.orientation
|
||||
up = np.array([2*(q.x*q.z+q.w*q.y), 2*(q.y*q.z-q.w*q.x),
|
||||
1-2*(q.x*q.x+q.y*q.y)])
|
||||
anchor = np.array([pose.position.x,pose.position.y,pose.position.z])-self.contact_height*up
|
||||
mask = self.ground.mask(points, ground_anchor=anchor)
|
||||
fields = [PointField(name=name, offset=i*4, datatype=PointField.FLOAT32, count=1)
|
||||
for i,name in enumerate(('x','y','z','intensity'))]
|
||||
self.ground_reply.publish(point_cloud2.create_cloud(scan.header, fields,
|
||||
np.column_stack((points, mask.astype(np.float32)))))
|
||||
|
||||
|
||||
def main():
|
||||
rclpy.init()
|
||||
node = TerrainNode()
|
||||
def stop(*_):
|
||||
rclpy.try_shutdown()
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
try:
|
||||
rclpy.spin(node)
|
||||
finally:
|
||||
node.stop(); node.destroy_node(); rclpy.try_shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,147 @@
|
||||
"""Reuse the existing ground observation stage, without CMU motion planning.
|
||||
|
||||
Only first-hit sensor data and calibrated semantic observations enter here.
|
||||
Output is measured terrain cost; it is not a command or a route permission.
|
||||
"""
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
|
||||
import numpy as np
|
||||
from nav_msgs.msg import Odometry
|
||||
from sensor_msgs.msg import PointCloud2, PointField
|
||||
from sensor_msgs_py import point_cloud2
|
||||
from std_msgs.msg import Header
|
||||
|
||||
from navigation.detection_obstacles import DetectionObstacles
|
||||
from navigation.observed_ground import observed_ground_costs
|
||||
from navigation.observed_space import ObservedSpace
|
||||
from navigation.semantic_surface import SemanticSurface
|
||||
from navigation.support_obstacles import SupportObstacles
|
||||
from navigation.terrain_costs import TerrainCostNormalizer, underbody_support_costs
|
||||
|
||||
|
||||
PARAMETERS = dict(scanVoxelSize=0.06, inputIsMapSnapshot=True, decayTime=0.5,
|
||||
noDecayDis=0.0, useSorting=True, quantileZ=0.25, considerDrop=True,
|
||||
clearDyObs=False, noDataObstacle=False, vehicleHeight=0.9,
|
||||
minRelZ=-2.0, maxRelZ=1.0, voxelPointUpdateThre=1, voxelTimeUpdateThre=0.0)
|
||||
|
||||
|
||||
class TerrainObservation:
|
||||
def __init__(self, node, monitor, geometry):
|
||||
self.node, self.monitor, self.geometry = node, monitor, geometry
|
||||
self.observed = ObservedSpace()
|
||||
self.normalize = TerrainCostNormalizer()
|
||||
self.semantics = SemanticSurface(retain_near=True, fuse_observations=True)
|
||||
self.detections = DetectionObstacles(monitor)
|
||||
self.support_obstacles = SupportObstacles(1.0)
|
||||
self.condition = threading.Condition()
|
||||
self.reply = None
|
||||
self.ground_reply = None
|
||||
self.seen_semantics = OrderedDict()
|
||||
self.scan = node.create_publisher(PointCloud2, '/registered_scan', 2)
|
||||
self.current_scan = node.create_publisher(PointCloud2, '/terrain/current_scan', 2)
|
||||
self.odom = node.create_publisher(Odometry, '/state_estimation', 2)
|
||||
node.create_subscription(PointCloud2, '/terrain_map', self.receive, 2)
|
||||
node.create_subscription(PointCloud2, '/terrain/current_ground', self.receive_ground, 2)
|
||||
|
||||
def receive_ground(self, message):
|
||||
points = point_cloud2.read_points_numpy(
|
||||
message, field_names=['x','y','z','intensity']).copy()
|
||||
stamp = message.header.stamp.sec * 1_000_000_000 + message.header.stamp.nanosec
|
||||
with self.condition:
|
||||
self.ground_reply = stamp, points
|
||||
self.condition.notify_all()
|
||||
|
||||
def receive(self, message):
|
||||
points = point_cloud2.read_points_numpy(
|
||||
message, field_names=['x', 'y', 'z', 'intensity'], skip_nans=True).copy()
|
||||
stamp = message.header.stamp.sec * 1_000_000_000 + message.header.stamp.nanosec
|
||||
with self.condition:
|
||||
self.reply = stamp, points
|
||||
self.condition.notify_all()
|
||||
|
||||
def observe(self, request):
|
||||
started = time.monotonic()
|
||||
pose = np.asarray(request['pose'], dtype=float)
|
||||
current = np.asarray(request['points'], dtype=np.float32)
|
||||
if (current.ndim != 2 or current.shape[1] != 3 or not 50 <= len(current) <= 30000
|
||||
or pose.shape != (7,) or not np.isfinite(current).all()
|
||||
or not np.isfinite(pose).all() or abs(np.linalg.norm(pose[3:])-1) > .01):
|
||||
raise ValueError('Invalid range/pose observation')
|
||||
rays = request['range_rays']
|
||||
points = self.observed.observe(current, pose, started,
|
||||
rays['origins'], rays['ends'], rays['origin_indices'], range_views=rays)
|
||||
remembered_at, remembered_count = time.monotonic(), len(points)
|
||||
for sample in request['semantic_observations']:
|
||||
age = float(sample['age_seconds'])
|
||||
if not math.isfinite(age) or age < 0:
|
||||
raise ValueError('Invalid semantic capture age')
|
||||
identity = sample['frame_id']
|
||||
if identity not in self.seen_semantics:
|
||||
self.semantics.observe(sample['samples'], started-age, pose,
|
||||
evidence_id=sample.get('capture_id', identity))
|
||||
self.seen_semantics[identity] = True
|
||||
while len(self.seen_semantics) > 128:
|
||||
self.seen_semantics.popitem(last=False)
|
||||
semantics_at = time.monotonic()
|
||||
header = Header(stamp=self.node.get_clock().now().to_msg(), frame_id='map')
|
||||
identity = header.stamp.sec * 1_000_000_000 + header.stamp.nanosec
|
||||
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:])
|
||||
fields = [PointField(name=name, offset=i*4, datatype=PointField.FLOAT32, count=1)
|
||||
for i, name in enumerate(('x', 'y', 'z', 'intensity'))]
|
||||
self.odom.publish(odom)
|
||||
self.current_scan.publish(point_cloud2.create_cloud(header, fields,
|
||||
np.column_stack((current, np.zeros(len(current), np.float32)))))
|
||||
self.scan.publish(point_cloud2.create_cloud(header, fields,
|
||||
np.column_stack((points, np.zeros(len(points), np.float32)))))
|
||||
with self.condition:
|
||||
ready = self.condition.wait_for(
|
||||
lambda: (self.reply is not None and abs(self.reply[0]-identity) <= 1000
|
||||
and self.ground_reply is not None and self.ground_reply[0] == identity),
|
||||
timeout=0.6)
|
||||
if not ready:
|
||||
raise TimeoutError('Terrain observation did not match the submitted sensor frame')
|
||||
points = self.reply[1].copy()
|
||||
ground = self.ground_reply[1].copy()
|
||||
if (ground.shape != (len(current), 4) or not np.array_equal(ground[:,:3], current)
|
||||
or not np.isin(ground[:,3], [0,1]).all()):
|
||||
raise ValueError('Ground segmentation changed the source range returns')
|
||||
terrain_at = time.monotonic()
|
||||
points, slope_count = self.normalize(points)
|
||||
points, body_count = underbody_support_costs(points, pose,
|
||||
request['body_contact_height_m'], geometry=self.geometry)
|
||||
points, patch_count = observed_ground_costs(points, pose,
|
||||
request['body_contact_height_m'], monitor=self.monitor)
|
||||
physical = points.copy()
|
||||
ground_at = time.monotonic()
|
||||
self.support_obstacles.revalidate(points, pose, request['body_contact_height_m'],
|
||||
monitor=self.monitor)
|
||||
self.support_obstacles.observe_ahead(points, pose, request['body_contact_height_m'],
|
||||
monitor=self.monitor, speed_mps=float(request['max_speed_mps']))
|
||||
support_at = time.monotonic()
|
||||
candidates = self.detections.observed(request)
|
||||
ground = current[ground[:,3] == 1]
|
||||
detected = self.detections.without_ground(candidates,
|
||||
self.semantics.permitted_terrain(ground, time.monotonic()))
|
||||
points = self.detections.overlay(points, detected)
|
||||
points, forbidden = self.semantics.apply(points, time.monotonic())
|
||||
search, _ = self.support_obstacles.apply(points, pose=pose, monitor=self.monitor)
|
||||
return dict(terrain=points, search_terrain=search, physical_terrain=physical, detected=detected,
|
||||
current_points=current,
|
||||
metrics=dict(detection_candidates=len(candidates),
|
||||
detection_ground_returns=len(candidates)-len(detected),
|
||||
slope_corrected=slope_count, observed_patches=patch_count,
|
||||
underbody_points=body_count, forbidden_points=forbidden,
|
||||
remembered_points=remembered_count, terrain_points=len(points),
|
||||
stage_ms=dict(memory=(remembered_at-started)*1000,
|
||||
semantics=(semantics_at-remembered_at)*1000,
|
||||
terrain=(terrain_at-semantics_at)*1000,
|
||||
ground=(ground_at-terrain_at)*1000,
|
||||
support=(support_at-ground_at)*1000,
|
||||
overlays=(time.monotonic()-support_at)*1000),
|
||||
processing_ms=(time.monotonic()-started)*1000))
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Run map construction apart from the latency-sensitive control interpreter.
|
||||
|
||||
One outstanding observation, ordinary process IPC, unchanged ROS PointCloud2
|
||||
and terrain implementation. All observation deadlines still belong to the
|
||||
caller; completion never makes an old observation fresh.
|
||||
"""
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
import multiprocessing
|
||||
import threading
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
|
||||
from navigation.footprint import Footprint
|
||||
from terrain_observation import TerrainObservation
|
||||
|
||||
_node = _thread = _terrain = None
|
||||
|
||||
|
||||
def initialize(geometry, deceleration, robot_geometry):
|
||||
global _node, _thread, _terrain
|
||||
rclpy.init()
|
||||
_node = Node('missioncore_terrain_observation')
|
||||
_terrain = TerrainObservation(_node, Footprint(geometry, deceleration=deceleration), robot_geometry)
|
||||
_thread = threading.Thread(target=rclpy.spin, args=(_node,), daemon=True)
|
||||
_thread.start()
|
||||
|
||||
|
||||
def ready():
|
||||
deadline = time.monotonic()+8
|
||||
while not (_terrain.scan.get_subscription_count() and _terrain.odom.get_subscription_count()
|
||||
and _terrain.current_scan.get_subscription_count()):
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError('Terrain observation subscriptions unavailable')
|
||||
time.sleep(.02)
|
||||
return True
|
||||
|
||||
|
||||
def observe(value):
|
||||
return _terrain.observe(value)
|
||||
|
||||
|
||||
def close():
|
||||
rclpy.try_shutdown()
|
||||
_thread.join(timeout=2)
|
||||
_node.destroy_node()
|
||||
|
||||
|
||||
class TerrainProcess:
|
||||
def __init__(self, geometry, deceleration, robot_geometry):
|
||||
self.pool = ProcessPoolExecutor(max_workers=1, mp_context=multiprocessing.get_context('spawn'),
|
||||
initializer=initialize, initargs=(geometry, deceleration, robot_geometry))
|
||||
try:
|
||||
self.pool.submit(ready).result(timeout=10)
|
||||
except BaseException:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def observe(self, value):
|
||||
# The enclosing single plan_lock prevents a sensor-frame queue.
|
||||
return self.pool.submit(observe, value).result(timeout=2)
|
||||
|
||||
def close(self):
|
||||
pool, self.pool = self.pool, None
|
||||
if pool is None:
|
||||
return
|
||||
try:
|
||||
pool.submit(close).result(timeout=3)
|
||||
finally:
|
||||
pool.shutdown(wait=True, cancel_futures=True)
|
||||
Reference in New Issue
Block a user