191 lines
8.3 KiB
Python
191 lines
8.3 KiB
Python
"""Existing continuous pipeline in a spawned CPU process, apart from Isaac's GIL.
|
|
|
|
Bounded standard multiprocessing queues carry measured arrays and original host
|
|
timestamps. Physics only reads local state; IPC never runs in its callback.
|
|
The existing command/intent lock and capture leases still own actuator writes.
|
|
"""
|
|
import multiprocessing
|
|
from queue import Empty, Full
|
|
import threading
|
|
from types import SimpleNamespace
|
|
|
|
from continuous_pipeline import ContinuousPipeline
|
|
|
|
|
|
def guarded(pipeline, name, target, stop=None):
|
|
try:
|
|
target()
|
|
except Exception as exc:
|
|
pipeline.fail(name, exc)
|
|
if stop is not None:
|
|
stop.set()
|
|
|
|
|
|
def composition_factory(root, run, directory):
|
|
from continuous_composition import ContinuousComposition
|
|
return ContinuousComposition(root, run, directory)
|
|
|
|
|
|
def run_pipeline(factory, arguments, directory, incoming, outgoing, stop):
|
|
pipeline = ContinuousPipeline(lambda: factory(*arguments), directory)
|
|
|
|
def publish():
|
|
previous = None
|
|
while not stop.is_set():
|
|
with pipeline.condition:
|
|
signature = (pipeline.epoch, pipeline.intent_revision, pipeline.count,
|
|
pipeline.control[0] if pipeline.control else None, pipeline.error)
|
|
if signature == previous:
|
|
pipeline.condition.wait(timeout=.05)
|
|
continue
|
|
model = pipeline.model
|
|
mission = model.mission if model is not None else None
|
|
target = (getattr(mission, 'perception_target', mission.orientation_target)()
|
|
if mission is not None else None)
|
|
snapshot = dict(epoch=pipeline.epoch, result=pipeline.result, control=pipeline.control,
|
|
intent_revision=pipeline.intent_revision, intent_key=pipeline.intent_key,
|
|
count=pipeline.count, dropped=pipeline.dropped, ready=pipeline.ready,
|
|
ever_ready=pipeline.ever_ready, error=pipeline.error, failure=pipeline.failure,
|
|
mission_index=mission.index if mission is not None else 0, view_target=target)
|
|
try:
|
|
outgoing.put(snapshot, timeout=.05)
|
|
previous = signature
|
|
except Full:
|
|
pass # Re-read the latest state; never wait in a control/physics thread.
|
|
|
|
publisher = threading.Thread(target=guarded, args=(pipeline, 'pipeline-status', publish, stop),
|
|
name='pipeline-status', daemon=True)
|
|
pipeline.start()
|
|
publisher.start()
|
|
try:
|
|
while not stop.is_set():
|
|
try:
|
|
message = incoming.get(timeout=.05)
|
|
except Empty:
|
|
continue
|
|
pipeline.enable(message['enabled'], epoch=message['epoch'])
|
|
if message['pose'] is not None:
|
|
pose, speed, stamp = message['pose']
|
|
twist = message['twist']
|
|
simulated = message['pose_simulation_time']
|
|
pipeline.observe_pose(pose, speed, stamp, measured_twist=(
|
|
twist[0] if twist is not None and twist[1] == stamp else None),
|
|
simulation_time_ns=simulated[0] if simulated is not None and simulated[1] == stamp else None)
|
|
packet = message['sensor']
|
|
if packet is not None and packet[0] == pipeline.epoch:
|
|
_, frame, observation = packet
|
|
pipeline.submit(None, frame, observation['captured_at'],
|
|
observation['simulation_time_ns'], observation)
|
|
finally:
|
|
stop.set()
|
|
pipeline.close()
|
|
publisher.join(timeout=2)
|
|
outgoing.cancel_join_thread()
|
|
incoming.close()
|
|
outgoing.close()
|
|
|
|
|
|
class ProcessPipeline(ContinuousPipeline):
|
|
def __init__(self, root, run, directory, *, factory=composition_factory):
|
|
super().__init__(None, directory)
|
|
self.arguments = (root, run, self.directory)
|
|
self.child_factory = factory
|
|
self.context = multiprocessing.get_context('spawn')
|
|
self.incoming, self.outgoing = self.context.Queue(1), self.context.Queue(1)
|
|
self.stop_process = self.context.Event()
|
|
self.mission = SimpleNamespace(index=0, perception_target=lambda: self.view_target,
|
|
orientation_target=lambda: self.view_target)
|
|
self.view_target = None
|
|
self.sequence = 0
|
|
|
|
def start(self):
|
|
self.directory.mkdir(parents=True, exist_ok=True)
|
|
self.process = self.context.Process(target=run_pipeline, name='mission-core-navigation',
|
|
args=(self.child_factory, self.arguments, self.directory,
|
|
self.incoming, self.outgoing, self.stop_process))
|
|
self.process.start()
|
|
for name, target in [('pipeline-input', self.send), ('pipeline-output', self.receive)]:
|
|
thread = threading.Thread(target=guarded, args=(self, name, target),
|
|
name=name, daemon=True)
|
|
thread.start()
|
|
self.threads.append(thread)
|
|
|
|
def enable(self, enabled):
|
|
super().enable(enabled)
|
|
with self.condition:
|
|
self.sequence += 1
|
|
self.condition.notify_all()
|
|
|
|
def submit(self, *args, **kwargs):
|
|
super().submit(*args, **kwargs)
|
|
with self.condition:
|
|
self.sequence += 1
|
|
self.condition.notify_all()
|
|
|
|
def observe_pose(self, *args, **kwargs):
|
|
super().observe_pose(*args, **kwargs)
|
|
with self.condition:
|
|
self.sequence += 1
|
|
self.condition.notify_all()
|
|
|
|
def send(self):
|
|
previous, sent_sensor = None, None
|
|
while not self.closed:
|
|
with self.condition:
|
|
self.condition.wait_for(lambda: self.closed or self.sequence != previous)
|
|
if self.closed:
|
|
return
|
|
sequence = self.sequence
|
|
identity = self.sensor[:2] if self.sensor is not None else None
|
|
message = dict(epoch=self.epoch, enabled=self.enabled, pose=self.pose,
|
|
twist=getattr(self, 'pose_twist', None),
|
|
pose_simulation_time=getattr(self, 'pose_simulation_time', None),
|
|
sensor=self.sensor if identity != sent_sensor else None)
|
|
try:
|
|
self.incoming.put(message, timeout=.05)
|
|
previous, sent_sensor = sequence, identity
|
|
except Full:
|
|
pass
|
|
|
|
def receive(self):
|
|
while not self.closed:
|
|
try:
|
|
snapshot = self.outgoing.get(timeout=.05)
|
|
except Empty:
|
|
if not self.process.is_alive():
|
|
self.fail('pipeline-process', RuntimeError(
|
|
f'Navigation process exited ({self.process.exitcode})'))
|
|
return
|
|
continue
|
|
with self.condition:
|
|
# The actuator-side pause/resume epoch wins immediately, even
|
|
# when an older packet was already in an IPC feeder thread.
|
|
if snapshot['epoch'] != self.epoch or self.closed or self.failure is not None:
|
|
continue
|
|
for key in ('result', 'control', 'intent_revision', 'intent_key', 'count',
|
|
'dropped', 'ready', 'ever_ready', 'error', 'failure'):
|
|
setattr(self, key, snapshot[key])
|
|
self.mission.index, self.view_target = snapshot['mission_index'], snapshot['view_target']
|
|
self.condition.notify_all()
|
|
|
|
def close(self):
|
|
with self.condition:
|
|
self.enabled, self.closed, self.control = False, True, None
|
|
self.condition.notify_all()
|
|
# A forcibly terminated process may have died while holding an Event
|
|
# lock. Do not touch its shared synchronization objects after death.
|
|
if self.process.is_alive():
|
|
self.stop_process.set()
|
|
self.process.join(timeout=20)
|
|
forced = self.process.is_alive()
|
|
if forced:
|
|
self.process.terminate()
|
|
self.process.join(timeout=5)
|
|
for thread in self.threads:
|
|
thread.join(timeout=2)
|
|
for channel in (self.incoming, self.outgoing):
|
|
channel.cancel_join_thread()
|
|
channel.close()
|
|
if forced or self.process.is_alive() or any(t.is_alive() for t in self.threads):
|
|
raise RuntimeError('Navigation process required forced cleanup')
|