Files
VSAG_SENTRY_SIM_27RMUL/tools/tests/test_motion_interlock.py
T

93 lines
4.5 KiB
Python

#!/usr/bin/env python3
"""Isolated live relay test. No Gazebo, TF, or real actuator subscribers."""
import argparse
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import project_env
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--binary', type=Path)
args=parser.parse_args()
try:
binary = args.binary or project_env.find_bin_dir()/'cmd_vel_relay'
binary = project_env.require_executable(binary, 'cmd_vel_relay')
except project_env.ProbeError as error:
parser.exit(1, f'{parser.prog}: {error}\n')
os.environ.update(ROS_DOMAIN_ID=str(130+int(uuid.uuid4().hex[:4],16)%40),
FASTDDS_BUILTIN_TRANSPORTS='UDPv4',ROS2CLI_DISABLE_DAEMON='1')
import rclpy
from geometry_msgs.msg import Twist
from std_msgs.msg import Bool
from action_msgs.srv import CancelGoal
rclpy.init();node=rclpy.create_node('test_motion_interlock')
received=[];cancellations=[]
subscription=node.create_subscription(Twist,'/model/sentry/cmd_vel',lambda m:received.append((time.monotonic(),m.linear.x)),100)
health=node.create_publisher(Bool,'/field_localization/navigation_valid',1)
final=node.create_publisher(Twist,'/cmd_vel',1)
upstream=node.create_publisher(Twist,'/cmd_vel_smoothed',1)
raw=node.create_publisher(Twist,'/cmd_vel_nav',1)
def cancel(req,response):
cancellations.append(time.monotonic());response.return_code=0
return response
services=[node.create_service(CancelGoal,name+'/_action/cancel_goal',cancel)
for name in ['/navigate_to_pose','/navigate_through_poses']]
process=subprocess.Popen([str(binary),'--ros-args','-p','navigation_mode:=true'],
start_new_session=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,text=True)
checks=0
def check(ok,message):
nonlocal checks
checks+=1
if not ok: raise RuntimeError(message)
print('PASS',message,flush=True)
def drive(duration,valid=True,publish_health=True,publish_final=True):
until=time.monotonic()+duration
while time.monotonic()<until:
if publish_health:
h=Bool();h.data=valid;health.publish(h)
if publish_final:
m=Twist();m.linear.x=0.1;final.publish(m)
m=Twist();m.linear.x=1.5;upstream.publish(m);raw.publish(m)
rclpy.spin_once(node,timeout_sec=0.01)
try:
deadline=time.monotonic()+10
while final.get_subscription_count()<1 and time.monotonic()<deadline:
rclpy.spin_once(node,timeout_sec=0.02)
check(final.get_subscription_count()==1,'one final velocity subscription')
drive(0.5,publish_health=False)
check(received and all(v==0 for _,v in received),'no motion before valid localization')
# A blocked nonzero command requests cancellation; allow both services to acknowledge.
drive(0.8)
check(any(v==0.1 for _,v in received),'valid final velocity reaches actuator')
check(all(v<=0.1 for _,v in received),'raw and smoothed topics cannot bypass collision output')
before=time.monotonic();drive(0.4,valid=False)
zeros=[t for t,v in received if t>=before and v==0]
check(bool(zeros) and min(zeros)-before<0.1,'invalid health stops within 100 ms')
check(len(cancellations)>=2,'navigation action servers receive cancellation')
drive(0.5)
before=time.monotonic();drive(0.6,publish_health=False)
zeros=[t for t,v in received if t>=before+0.3 and v==0]
check(bool(zeros) and min(zeros)-before<0.4,'stale health stops within 400 ms')
drive(0.5)
before=time.monotonic();drive(0.6,publish_final=False)
zeros=[t for t,v in received if t>=before+0.3 and v==0]
check(bool(zeros) and min(zeros)-before<0.4,'stale final command stops despite upstream traffic')
check(process.poll() is None,'relay remains alive')
print(f'{checks} live checks passed; health_stop_ms={(min(t for t,v in received if t>=before+0.3 and v==0)-before)*1000:.3f}')
finally:
if process.poll() is None:os.killpg(process.pid,signal.SIGINT)
try:process.wait(timeout=5)
except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait()
_=subscription,services
node.destroy_node();rclpy.shutdown()
if __name__=='__main__':main()