fix(sim): clean up interrupted runs and document usage and migration

Prevent ROS cleanup errors from skipping owned Gazebo process teardown.
Reject occupied master ports before launching nodes and stop the stack when
its GUI closes. Add --gui to the automatic LIO navigation checks.

Expand the root README and add a beginner guide covering manual goals,
automatic tests, restart troubleshooting, MID360 assumptions and staged
migration to real hardware. Preserve lifecycle and GUI validation evidence.

Validation: three navigation restart cycles, two busy-port rejection cases,
SIGINT/SIGHUP cleanup and a GUI straight-route check. Current source hashes,
Python syntax, documentation shell syntax and local links verified. Hardware
migration remains unverified; no push performed.
This commit is contained in:
2026-11-08 22:44:02 +08:00
parent 664eaa81e5
commit ca61aa63b5
21 changed files with 1022 additions and 59 deletions
+5 -5
View File
@@ -17,7 +17,7 @@ from sensor_msgs.msg import PointCloud2
from std_msgs.msg import String
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
from check_omni_robot import Sim,sim_env
from check_omni_robot import Sim,sim_env, shutdown_probe
from check_scan_navigation import NavProbe,run_goal
from check_slope_drive import SlopeProbe
@@ -145,16 +145,17 @@ def main():
ap.add_argument('--laps',type=int,default=1)
ap.add_argument('--sensor-profile',choices=('ideal','mild','stress'),default='ideal')
ap.add_argument('--split',action='store_true')
ap.add_argument('--gui',action='store_true',help='Show Gazebo while testing (default: headless)')
args=ap.parse_args()
if not 1<=args.laps<=5 or (args.laps>1 and (args.straight_only or args.fault_only or args.recovery_only)):
ap.error('laps must be 1..5 and multi-lap mode requires complete navigation')
out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True)
os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros')
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
report=dict(status='INVALID',cases=[],sensor_profile=args.sensor_profile,laps=args.laps,split=args.split,collector_sha256=hashlib.sha256(source).hexdigest())
report=dict(status='INVALID',cases=[],sensor_profile=args.sensor_profile,laps=args.laps,split=args.split,gui=args.gui,collector_sha256=hashlib.sha256(source).hexdigest())
sim,p=Sim(str(out/'sim')),None
try:
ok,why=sim.start(lio_navigation=True,sensor_profile=args.sensor_profile,split=args.split);report['startup']=why
ok,why=sim.start(lio_navigation=True,sensor_profile=args.sensor_profile,split=args.split,gui=args.gui);report['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=LioNavProbe()
if not p.wait_clock():raise RuntimeError('missing clock')
@@ -200,8 +201,7 @@ def main():
except Exception as exc:
report['error']=repr(exc);print(report['error'],flush=True)
finally:
if p is not None:p.send(0.,0.,0.);p.destroy_node()
if rclpy.ok():rclpy.shutdown()
report['ros_cleanup_errors'] = shutdown_probe(p)
report['teardown']=sim.stop();(out/'result.json').write_text(json.dumps(report,indent=2)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
+2 -3
View File
@@ -10,7 +10,7 @@ from geometry_msgs.msg import PoseStamped
from nav_msgs.msg import Path as NavPath
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
from sensor_msgs.msg import PointCloud2
from check_omni_robot import Sim,sim_env
from check_omni_robot import Sim,sim_env, shutdown_probe
from check_lio_navigation import LioNavProbe,graph_evidence
from check_mid360 import interpolate,rotate,json_value
from check_sim_lidar import points
@@ -185,8 +185,7 @@ def main():
report['cloud_snapshots']=p.snapshots;report['navigation_status']=p.navigation_status
except Exception as exc:report['error']=repr(exc);print(report['error'],flush=True)
finally:
if p is not None:p.send(0.,0.,0.);p.destroy_node()
if rclpy.ok():rclpy.shutdown()
report['ros_cleanup_errors'] = shutdown_probe(p)
report['teardown']=sim.stop();(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
+2 -3
View File
@@ -5,7 +5,7 @@ from pathlib import Path
import numpy as np
import rclpy
from gazebo_msgs.srv import SpawnEntity,DeleteEntity,GetEntityState
from check_omni_robot import Sim,sim_env
from check_omni_robot import Sim,sim_env, shutdown_probe
from check_mid360 import SensorProbe,rotate,json_value
@@ -65,8 +65,7 @@ def main():
report['status']='PASS' if all(c['ok'] for c in report['cases']) else 'FAIL'
except Exception as e:report['error']=repr(e);print(report['error'],flush=True)
finally:
if p is not None:p.send(0.,0.,0.);p.destroy_node()
if rclpy.ok():rclpy.shutdown()
report['ros_cleanup_errors'] = shutdown_probe(p)
report['teardown']=sim.stop();(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
return dict(PASS=0,FAIL=30,INVALID=40)[report['status']]
+2 -3
View File
@@ -16,7 +16,7 @@ from livox_ros_driver2.msg import CustomMsg
from sensor_msgs.msg import Imu
from std_msgs.msg import String
from rclpy.qos import qos_profile_sensor_data
from check_omni_robot import Sim,sim_env
from check_omni_robot import Sim,sim_env, shutdown_probe
from check_slope_drive import SlopeProbe
ROOT=Path(__file__).resolve().parents[2]
@@ -246,8 +246,7 @@ def main():
except Exception as exc:
result['status']='INVALID';result['error']=repr(exc);print(result['error'],flush=True)
finally:
if p is not None:p.send(0.,0.,0.);p.destroy_node()
if rclpy.ok():rclpy.shutdown()
result['ros_cleanup_errors'] = shutdown_probe(p)
result['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(result,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[result['status']]
+2 -6
View File
@@ -18,7 +18,7 @@ import rclpy
from gazebo_msgs.srv import GetEntityState, SpawnEntity
from geometry_msgs.msg import PoseStamped
from check_omni_robot import Sim, sim_env
from check_omni_robot import Sim, sim_env, shutdown_probe
from check_scan_navigation import NavProbe, run_goal
from check_sim_lidar import points
@@ -155,11 +155,7 @@ def run_case(name, out):
report['error'] = repr(exc)
print(name, report['error'], flush=True)
finally:
if p is not None:
p.send(0., 0., 0.)
p.destroy_node()
if rclpy.ok():
rclpy.shutdown()
report['ros_cleanup_errors'] = shutdown_probe(p)
report['teardown'] = sim.stop()
(out/'result.json').write_text(json.dumps(report, indent=2)+'\n')
return report
+44 -7
View File
@@ -17,6 +17,7 @@
"""
import argparse
import atexit
import json
import math
import os
@@ -171,6 +172,27 @@ def sim_env(extra=None):
return env
def shutdown_probe(probe):
"""ROS may already be shut down by Ctrl+C; never block process cleanup."""
errors = []
if probe is not None:
if rclpy.ok():
try:
probe.send(0., 0., 0.)
except Exception as exc:
errors.append('stop command: ' + repr(exc))
try:
probe.destroy_node()
except Exception as exc:
errors.append('destroy node: ' + repr(exc))
if rclpy.ok():
try:
rclpy.shutdown()
except Exception as exc:
errors.append('ROS shutdown: ' + repr(exc))
return errors
class Sim(object):
"""一次仿真:启动 → 就绪 → 收尾。只碰自己创建的进程。"""
@@ -182,6 +204,21 @@ class Sim(object):
self.known = {}
self.teardown = {}
self.owner_token = None
self._stopping = False
self._old_hup = None
# Also clean up if a caller raises before its normal finally/stop path.
atexit.register(self.stop)
try:
self._old_hup = signal.getsignal(signal.SIGHUP)
signal.signal(signal.SIGHUP, self._on_hangup)
except ValueError: # Signal installation is limited to the main thread.
pass
def _on_hangup(self, signum, frame):
# Closing a test terminal normally sends SIGHUP. Unwind the caller's
# finally block instead of abandoning its detached launch children.
if not self._stopping:
raise KeyboardInterrupt('Test terminal closed (SIGHUP)')
def owns(self, pid):
if not self.owner_token or pid in (0, 1, os.getpid()):
@@ -273,6 +310,9 @@ class Sim(object):
return ''
def stop(self):
if self.teardown:
return self.teardown
self._stopping = True
port = 11355
sigterm, sigkill = [], []
t0 = time.monotonic()
@@ -323,6 +363,9 @@ class Sim(object):
'never_touched_unknown_pid': True}
if self._fh:
self._fh.close()
atexit.unregister(self.stop)
if self._old_hup is not None and signal.getsignal(signal.SIGHUP) == self._on_hangup:
signal.signal(signal.SIGHUP, self._old_hup)
return self.teardown
@@ -1511,13 +1554,7 @@ def main():
'samples': probe.odom[::10]}, f, ensure_ascii=False, indent=1)
res['tf'] = {'tf': dict(probe.tf_pairs), 'tf_static': dict(probe.tf_static_pairs)}
finally:
try:
probe.send(0.0, 0.0, 0.0)
probe.destroy_node()
except Exception: # noqa: BLE001
pass
if rclpy.ok():
rclpy.shutdown()
res['ros_cleanup_errors'] = shutdown_probe(probe)
res['teardown'] = sim.stop()
log('[teardown] %r' % res['teardown'])
+2 -3
View File
@@ -13,7 +13,7 @@ import time
import numpy as np
import rclpy
from nav_msgs.msg import Odometry
from check_omni_robot import Sim,sim_env
from check_omni_robot import Sim,sim_env, shutdown_probe
from check_mid360 import SensorProbe,phase,interpolate,rotate,json_value
IMU_OFFSET=np.array([.011,.02329,.25588])
@@ -122,8 +122,7 @@ def main():
result['status']='INVALID';result['error']=repr(exc);print(result['error'],flush=True)
if p is not None:result['estimates']=p.estimates
finally:
if p is not None:p.send(0.,0.,0.);p.destroy_node()
if rclpy.ok():rclpy.shutdown()
result['ros_cleanup_errors'] = shutdown_probe(p)
result['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(result,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[result['status']]
+2 -6
View File
@@ -24,7 +24,7 @@ from sensor_msgs.msg import PointCloud2
from scan_planner_msgs.msg import TrajectoryStatus
from std_msgs.msg import Bool
from check_omni_robot import Probe, Sim, sim_env
from check_omni_robot import Probe, Sim, sim_env, shutdown_probe
from check_sim_lidar import points
@@ -292,11 +292,7 @@ def main():
report['error'] = repr(exc)
print(report['error'], flush=True)
finally:
if p is not None:
p.send(0., 0., 0.) # Teardown only, after all measurements have been saved.
p.destroy_node()
if rclpy.ok():
rclpy.shutdown()
report['ros_cleanup_errors'] = shutdown_probe(p)
report['teardown'] = sim.stop()
(out/'result.json').write_text(json.dumps(report, indent=2)+'\n')
return {'PASS': 0, 'FAIL': 30, 'INVALID': 40}[report['status']]
+2 -3
View File
@@ -5,7 +5,7 @@ from pathlib import Path
import numpy as np
import yaml
import rclpy
from check_omni_robot import Sim,sim_env
from check_omni_robot import Sim,sim_env, shutdown_probe
from check_mid360 import SensorProbe,phase,interpolate,rotate,scene_shapes,ray_ranges,json_value
@@ -58,8 +58,7 @@ def main():
report['status']='PASS' if all(checks.values()) else 'FAIL';print(report['status'],checks,flush=True)
except Exception as e:report['error']=repr(e);print(report['error'],flush=True)
finally:
if p is not None:p.send(0.,0.,0.);p.destroy_node()
if rclpy.ok():rclpy.shutdown()
report['ros_cleanup_errors'] = shutdown_probe(p)
report['teardown']=sim.stop();(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
return dict(PASS=0,FAIL=30,INVALID=40)[report['status']]
+2 -6
View File
@@ -15,7 +15,7 @@ from sensor_msgs.msg import PointCloud2
from nav_msgs.msg import Odometry
from rclpy.qos import qos_profile_sensor_data
from check_omni_robot import Probe, Sim, reset_and_settle, sim_env
from check_omni_robot import Probe, Sim, reset_and_settle, sim_env, shutdown_probe
sys.path.insert(0, str(Path(__file__).resolve().parents[1] /
'src/r2027_robot_description/scripts'))
@@ -128,11 +128,7 @@ def main():
report['error'] = repr(exc)
print(report['error'], flush=True)
finally:
if probe is not None:
probe.send(0., 0., 0.)
probe.destroy_node()
if rclpy.ok():
rclpy.shutdown()
report['ros_cleanup_errors'] = shutdown_probe(probe)
report['teardown'] = sim.stop()
(out/'result.json').write_text(json.dumps(report, ensure_ascii=False, indent=2)+'\n')
return {'PASS': 0, 'FAIL': 30, 'INVALID': 40}[report['status']]
+2 -3
View File
@@ -17,7 +17,7 @@ from geometry_msgs.msg import WrenchStamped
from rclpy.qos import qos_profile_sensor_data
from sensor_msgs.msg import PointCloud2
from check_omni_robot import BASE, Probe, Sim, reset_and_settle, sim_env
from check_omni_robot import BASE, Probe, Sim, reset_and_settle, sim_env, shutdown_probe
from check_sim_lidar import points, stamp
@@ -155,8 +155,7 @@ def main():
except Exception as exc:
report['error']=repr(exc);print(report['error'],flush=True)
finally:
if p is not None:p.send(0.,0.,0.);p.destroy_node()
if rclpy.ok():rclpy.shutdown()
report['ros_cleanup_errors'] = shutdown_probe(p)
report['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(report,indent=2,
default=lambda v:v.item() if isinstance(v,np.generic) else str(v))+'\n')
+2 -3
View File
@@ -16,7 +16,7 @@ from nav_msgs.msg import Path as NavPath
from geometry_msgs.msg import PoseStamped
from rclpy.qos import QoSProfile,DurabilityPolicy
from check_omni_robot import Sim,sim_env
from check_omni_robot import Sim,sim_env, shutdown_probe
from check_scan_navigation import NavProbe
from check_slope_drive import SlopeProbe
from check_sim_lidar import points
@@ -131,8 +131,7 @@ def main():
except Exception as exc:
report['error']=repr(exc);print(report['error'],flush=True)
finally:
if p is not None:p.send(0.,0.,0.);p.destroy_node()
if rclpy.ok():rclpy.shutdown()
report['ros_cleanup_errors'] = shutdown_probe(p)
report['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(report,indent=2)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]