迁移标准与快模式上坡任务至实车并统一仿真实现

提取共用任务、双雷达融合与定位适配,新增红蓝方实车入口、预览模式、硬件限速和双 MID360 配置检查工具。

修复 Point-LIO 与任务节点退出流程,底盘串口关闭前发送零速帧;补充迁移测试、验收记录及实车使用文档。

同步 README、仿真兼容入口和构建脚本,调整场景光照并默认关闭阴影。真实雷达、串口及实车动态验收仍待现场完成。
This commit is contained in:
2026-11-18 17:10:41 +08:00
parent 6f1d837b46
commit 9fdc34321e
45 changed files with 3347 additions and 964 deletions
@@ -5,8 +5,9 @@ from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument,IncludeLaunchDescription,OpaqueFunction
from launch.conditions import IfCondition
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch.substitutions import LaunchConfiguration,PythonExpression
from launch_ros.actions import Node
from br_vehicle_mission.profiles import profile_settings
def generate_launch_description():
@@ -18,7 +19,8 @@ def generate_launch_description():
profile=LaunchConfiguration('profile').perform(context)
if profile not in ('standard','fast'):raise ValueError('profile must be standard or fast')
fast=profile=='fast'
defaults=(2.5,1.1,.2,2.0) if fast else (.6,.7,.2,.8)
settings=profile_settings(profile)
defaults=settings['speeds']
def speed(key,default):
value=LaunchConfiguration(key).perform(context)
return default if value=='auto' else float(value)
@@ -40,31 +42,27 @@ def generate_launch_description():
parameters=[os.path.join(scan,'config','planner_vehicle.yaml')]+shared+[
{'fsm.navi_mode':1,'fsm.terrain_motion':False,'grid_map.footprint_margin':.09,'grid_map.cloud_reliable':True,
'manager.max_vel':nav_speed,'optimization.max_vel':nav_speed,
'grid_map.sliding_map_size_y':6.0 if fast else 3.0,'grid_map.local_update_range_y':3.0 if fast else 1.5,
'fsm.thresh_replan':2.0 if fast else 1.0,'fsm.planning_horizon':4.0 if fast else 3.5,'manager.planning_horizon':4.0 if fast else 3.5,
'manager.max_acc':3.0 if fast else .6,'optimization.max_acc':3.0 if fast else .6}],
**settings['planner']}],
remappings=[('body_pose','/sim/navigation/body_odom'),('sensor_pose','/sim/navigation/sensor_odom'),('cloud','/sim/navigation/terrain_planning_cloud')]),
Node(package='scan_planner',executable='closed_loop_controller',name='closed_loop_controller',output='screen',
parameters=[os.path.join(scan,'config','controllers_vehicle.yaml')]+shared+[
{'terrain_motion':False,'align_to_goal_yaw':True,'yaw_goal_tolerance':.015 if fast else .01,'max_vx':nav_speed,'max_vy':nav_speed,
'max_vyaw':yaw_speed,'extended_yaw_limit':fast,
'kp_yaw':5.0 if fast else 1.5,'kp_pos':1.5 if fast else .5,
'state_prediction_limit':.2 if fast else 0.,'goal_braking_acceleration':2.0 if fast else 0.,
'finish_dist':.025 if fast else .015,'goal_v_floor':.01,'goal_slow_gain':3.0 if fast else 2.0}],
{'terrain_motion':False,'align_to_goal_yaw':True,'max_vx':nav_speed,'max_vy':nav_speed,
'max_vyaw':yaw_speed,**settings['controller']}],
remappings=[('body_pose','/sim/navigation/body_odom'),('cmd_vel','/mission/navigation_cmd_vel')]),
Node(package='br_sim_bringup',executable='ramp_mission.py',name='ramp_mission',output='screen',
parameters=[{'use_sim_time':True,'profile':profile,'autostart':LaunchConfiguration('autostart'),'aligned_start':LaunchConfiguration('aligned_start'),'ramp_speed':ramp_speed,'crest_speed':crest_speed}]),
parameters=[{'use_sim_time':True,'profile':profile,'side':LaunchConfiguration('side'),'autostart':LaunchConfiguration('autostart'),'aligned_start':LaunchConfiguration('aligned_start'),'ramp_speed':ramp_speed,'crest_speed':crest_speed}]),
Node(package='br_sim_bringup',executable='mission_command_mux.py',name='mission_command_mux',output='screen',parameters=[{'use_sim_time':True,'max_linear':max(nav_speed,ramp_speed),'nav_max_linear':nav_speed,'max_yaw':yaw_speed}]),
]
return LaunchDescription([
DeclareLaunchArgument('dual_lidar',default_value='true'),DeclareLaunchArgument('autostart',default_value='false'),
DeclareLaunchArgument('aligned_start',default_value='false'),
DeclareLaunchArgument('profile',default_value='standard'),
DeclareLaunchArgument('side',default_value='red'),
DeclareLaunchArgument('nav_speed',default_value='auto'),DeclareLaunchArgument('ramp_speed',default_value='auto'),
DeclareLaunchArgument('crest_speed',default_value='auto'),DeclareLaunchArgument('yaw_speed',default_value='auto'),
DeclareLaunchArgument('gui',default_value='true'),DeclareLaunchArgument('with_rviz',default_value='true'),
DeclareLaunchArgument('sensor_profile',default_value='ideal'),
DeclareLaunchArgument('x',default_value='-4.5'),DeclareLaunchArgument('y',default_value='4.5'),
DeclareLaunchArgument('x',default_value='-4.5'),DeclareLaunchArgument('y',default_value=PythonExpression(["'-4.5' if '",LaunchConfiguration('side'),"' == 'blue' else '4.5'"])),
DeclareLaunchArgument('z',default_value='0.15'),DeclareLaunchArgument('yaw',default_value='0.0'),
OpaqueFunction(function=nodes),
IncludeLaunchDescription(PythonLaunchDescriptionSource(os.path.join(own,'launch','rviz.launch.py')),
+1
View File
@@ -7,6 +7,7 @@
<license>Apache-2.0</license>
<buildtool_depend>ament_cmake</buildtool_depend>
<exec_depend>r2027_robot_description</exec_depend>
<exec_depend>br_vehicle_mission</exec_depend>
<exec_depend>scan_planner</exec_depend>
<exec_depend>step_blocker</exec_depend>
<exec_depend>point_lio</exec_depend>
@@ -1,216 +1,6 @@
#!/usr/bin/python3
"""Deskew two raw Livox scans with estimated body poses; no truth/TF fallback.
"""Compatibility entry; implementation shared with real-vehicle missions."""
from br_vehicle_mission.dual_lidar_fusion import *
The upper lidar alone feeds Point-LIO. Both obstacle scans retain physical ray
origins and original acquisition offsets. Missing streams revoke downstream
readiness through the existing adapter's required_planning_topic gate.
"""
from array import array
from collections import deque
import json
import math
import numpy as np
import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data,QoSProfile
from livox_ros_driver2.msg import CustomMsg
from nav_msgs.msg import Odometry
from sensor_msgs.msg import PointCloud2,PointField
from std_msgs.msg import String
from lio_navigation_adapter import quaternion,rotation
class PoseGapError(ValueError):
pass
def interpolate_poses(history,times,max_gap=.10):
"""Bracket actual per-point times, SLERP orientation, never extrapolate."""
stamps=np.array([v[0] for v in history]);times=np.asarray(times)
if len(stamps)<2 or np.any(np.diff(stamps)<=0):raise ValueError('invalid pose history')
if np.min(times)<stamps[0] or np.max(times)>stamps[-1]:raise LookupError('pose coverage pending')
hi=np.clip(np.searchsorted(stamps,times,side='right'),1,len(stamps)-1);lo=hi-1
dt=stamps[hi]-stamps[lo]
if np.max(dt)>max_gap:raise PoseGapError('pose gap exceeds maximum')
weight=(times-stamps[lo])/dt;poses=np.array([v[1] for v in history]);qs=np.array([v[2] for v in history])
a,b=qs[lo],qs[hi];dot=np.sum(a*b,axis=1);b=np.where(dot[:,None]<0,-b,b);dot=np.abs(dot)
theta=np.arccos(np.clip(dot,-1,1));den=np.sin(theta);safe=np.where(den>1e-8,den,1.)
spherical=(np.sin((1-weight)*theta)[:,None]*a+np.sin(weight*theta)[:,None]*b)/safe[:,None]
linear=(1-weight[:,None])*a+weight[:,None]*b
q=np.where((den>1e-8)[:,None],spherical,linear);q/=np.linalg.norm(q,axis=1)[:,None]
return poses[lo]+weight[:,None]*(poses[hi]-poses[lo]),q
def rotate_rows(q,xyz):
return xyz+2*np.cross(q[:,:3],np.cross(q[:,:3],xyz)+q[:,3,None]*xyz)
def project_scan(xyz,offset_ns,start_ns,history,mount,mount_rotation,front_only):
"""Return world endpoints/origins, exact times, and original body-frame Z.
Body Z is measured before the estimated world transform. It lets the
explicitly flat profile classify ground without following LIO height drift.
"""
xyz=np.asarray(xyz);offset_ns=np.asarray(offset_ns,dtype=np.int64)
if xyz.ndim!=2 or xyz.shape[1]!=3 or len(xyz)!=len(offset_ns) or not np.isfinite(xyz).all():
raise ValueError('invalid point array')
if np.any(offset_ns<0) or np.any(offset_ns>=100000000) or np.any(np.diff(offset_ns)<0):
raise ValueError('invalid acquisition offsets')
body_rays=xyz@mount_rotation.T
# Front half-plane is a DIRECTION relative to the optical origin, not the
# endpoint's translated base x. At yaw=+pi/2 it is raw lidar y<=0.
selected=body_rays[:,0]>=-1e-8 if front_only else np.ones(len(xyz),dtype=bool)
body=body_rays+mount
selected&=~((np.abs(body[:,0])<=.42)&(np.abs(body[:,1])<=.42)&(body[:,2]>=-.17)&(body[:,2]<=.28))
body=body[selected];stamps=start_ns+offset_ns[selected]
if not len(body):return np.empty((0,3)),np.empty((0,3)),stamps,np.empty(0)
pos,q=interpolate_poses(history,stamps*1e-9)
origins=pos+rotate_rows(q,np.broadcast_to(mount,body.shape))
return pos+rotate_rows(q,body),origins,stamps,body[:,2].copy()
def cloud_message(xyz,origins,times,device_ids,end_ns):
"""World-frame endpoints with world-frame origins and source time metadata."""
dtype=np.dtype([(n,'<f4') for n in ('x','y','z','origin_x','origin_y','origin_z')]+
[('time_sec','<i4'),('time_nanosec','<u4'),('sensor_id','u1')])
data=np.zeros(len(xyz),dtype=dtype)
for i,n in enumerate(('x','y','z')):data[n]=xyz[:,i];data['origin_'+n]=origins[:,i]
data['time_sec']=times//1000000000;data['time_nanosec']=times%1000000000;data['sensor_id']=device_ids
msg=PointCloud2();msg.header.frame_id='world';msg.header.stamp.sec=end_ns//1000000000;msg.header.stamp.nanosec=end_ns%1000000000
msg.height=1;msg.width=len(data);msg.point_step=dtype.itemsize;msg.row_step=msg.point_step*msg.width
for name in dtype.names:
offset=dtype.fields[name][1];datatype=PointField.FLOAT32 if offset<24 else (PointField.INT32 if name=='time_sec' else PointField.UINT32 if name=='time_nanosec' else PointField.UINT8)
msg.fields.append(PointField(name=name,offset=offset,datatype=datatype,count=1))
msg.data=array('B',data.tobytes());msg.is_dense=bool(np.isfinite(xyz).all());return msg
class DualLidarFusion(Node):
def __init__(self):
super().__init__('dual_lidar_fusion')
self.mounts=[np.array(self.declare_parameter('upper_position_base',[.015,0.,.33]).value),
np.array(self.declare_parameter('lower_position_base',[.325,0.,.044]).value)]
yaw=float(self.declare_parameter('lower_yaw',math.pi/2).value)
self.base_height=float(self.declare_parameter('nominal_base_height',.15).value)
self.ground_tolerance=float(self.declare_parameter('ground_tolerance',.015).value)
self.ground_mode=self.declare_parameter('ground_mode','flat_body').value
planes=list(self.declare_parameter('traversable_planes',[0.]*7).value)
self.surface_tolerance=float(self.declare_parameter('surface_tolerance',.06).value)
if self.ground_mode not in ('flat_body','known_terrain') or len(planes)%7 or not all(math.isfinite(v) for v in planes) or not 0<self.surface_tolerance<=.06:
raise ValueError('invalid ground mode or known terrain surfaces')
self.planes=[planes[i:i+7] for i in range(0,len(planes),7) if planes[i+1]>planes[i] and planes[i+3]>planes[i+2]]
if self.ground_mode=='known_terrain' and not self.planes:raise ValueError('known terrain needs explicit surface priors')
if not (math.isfinite(self.base_height) and math.isfinite(self.ground_tolerance) and
0<self.ground_tolerance<self.base_height):raise ValueError('invalid flat-ground reference/tolerance')
self.rotations=[np.eye(3),rotation([0.,0.,math.sin(yaw/2),math.cos(yaw/2)])]
if any(m.shape!=(3,) or not np.isfinite(m).all() for m in self.mounts) or not math.isfinite(yaw):raise ValueError('invalid extrinsics')
self.history=deque();self.scans=[deque(maxlen=10),deque(maxlen=10)];self.last=[None,None]
self.fault='';self.published=0;self.dropped=0;self.last_output=None;self.last_drop=''
self.full=self.create_publisher(PointCloud2,'/sim/navigation/fused_cloud',5)
planning_qos=QoSProfile(depth=1 if self.declare_parameter('reliable_planning_cloud',False).value else 5)
self.planning=self.create_publisher(PointCloud2,'/sim/navigation/fused_planning_cloud',planning_qos)
self.status=self.create_publisher(String,'/sim/dual_lidar/status',10)
# The estimator publishes bursts. Retain its full reliable pose sequence;
# sensor-data depth 5 discards intermediate motion during scan processing.
self.create_subscription(Odometry,'/sim/navigation/body_odom',self.on_pose,100)
for i,topic in enumerate(('/sim/mid360/lidar','/sim/mid360_low/lidar')):
self.create_subscription(CustomMsg,topic,lambda msg,i=i:self.on_scan(i,msg),qos_profile_sensor_data)
self.create_timer(.02,self.flush);self.create_timer(.5,self.report)
def now_s(self):return self.get_clock().now().nanoseconds*1e-9
def on_pose(self,m):
if self.fault:return
try:
if m.header.frame_id!='world' or m.child_frame_id!='lio_base_link':raise ValueError('unexpected estimated body frames')
# Use the same whole-nanosecond conversion as scan acquisition
# times. sec+fraction can differ by one floating-point ULP and
# incorrectly fail an exact scan-end pose bracket.
t=(m.header.stamp.sec*1000000000+m.header.stamp.nanosec)*1e-9;p=m.pose.pose.position;q=m.pose.pose.orientation
pos=np.array([p.x,p.y,p.z]);q=quaternion([q.x,q.y,q.z,q.w])
if not np.isfinite(pos).all():raise ValueError('nonfinite estimated pose')
# Clock delivery and odometry callbacks can be ordered differently.
# Preserve near-future source samples; flush still waits for clock
# and rejects stale poses. Never rewrite an input stamp.
if not -0.2<=self.now_s()-t<=2.:return
if self.history and t<=self.history[-1][0]:
if t==self.history[-1][0]:return
raise ValueError('estimated pose time moved backwards')
self.history.append((t,pos,q))
while len(self.history)>2 and self.history[1][0]<t-2.:self.history.popleft()
except ValueError as error:self.fault=str(error)
def on_scan(self,i,m):
if self.fault:return
t=int(m.timebase)
if m.header.frame_id!=('lidar' if i==0 else 'lidar_low') or m.point_num!=len(m.points) or m.lidar_id!=i:
self.fault='unexpected raw lidar identity/count';return
if t!=m.header.stamp.sec*1000000000+m.header.stamp.nanosec:
self.fault='lidar header/timebase mismatch';return
if self.last[i] is not None and t<=self.last[i]:
self.fault='lidar time moved backwards or repeated';return
self.last[i]=t
self.scans[i].append(m)
def flush(self):
if self.fault or len(self.history)<2:return
now=self.now_s()
while self.scans[0] and self.scans[1]:
a,b=self.scans[0][0],self.scans[1][0]
if abs(int(a.timebase)-int(b.timebase))>50000000:
self.scans[int(a.timebase)>int(b.timebase)].popleft();self.dropped+=1;continue
first=min(int(a.timebase),int(b.timebase))*1e-9
end_ns=max(int(a.timebase),int(b.timebase))+99000000
if end_ns*1e-9>now:return # Clock delivery must catch up before publishing source-stamped clouds.
if now-end_ns*1e-9>.2 or first<self.history[0][0]:
self.scans[0].popleft();self.scans[1].popleft();self.dropped+=1;continue
if end_ns*1e-9>self.history[-1][0]:return
if not 0<=now-self.history[-1][0]<=.2:return
try:
bundles=[]
for i,m in enumerate((a,b)):
xyz=np.array([[p.x,p.y,p.z] for p in m.points],dtype=float).reshape(-1,3)
offsets=np.array([p.offset_time for p in m.points],dtype=np.int64)
bundles.append(project_scan(xyz,offsets,int(m.timebase),self.history,self.mounts[i],self.rotations[i],i==1))
xyz=np.concatenate([v[0] for v in bundles]);origins=np.concatenate([v[1] for v in bundles]);times=np.concatenate([v[2] for v in bundles])
body_z=np.concatenate([v[3] for v in bundles])
ids=np.concatenate([np.full(len(v[0]),i,dtype=np.uint8) for i,v in enumerate(bundles)])
full=cloud_message(xyz,origins,times,ids,end_ns);self.full.publish(full)
# Flat-only profile: the base motion reference is nominally
# 0.15 m above the support plane. Use original optical geometry,
# not a world-Z threshold that drifts with the LIO solution.
# Raw world cloud, ray origins and acquisition times stay intact.
ground=body_z<=-self.base_height+self.ground_tolerance
if self.ground_mode=='known_terrain':
# This explicitly selected profile uses surveyed WORLD
# surfaces. A horizontal body-plane cut is wrong when the
# vehicle pitches or a ray crosses a ramp transition.
ground=np.zeros(len(xyz),dtype=bool)
for x0,x1,y0,y1,mx,my,b in self.planes:
ground|=(xyz[:,0]>=x0)&(xyz[:,0]<=x1)&(xyz[:,1]>=y0)&(xyz[:,1]<=y1)&(np.abs(xyz[:,2]-(mx*xyz[:,0]+my*xyz[:,1]+b))<=self.surface_tolerance)
planning=xyz.copy();planning[ground]=np.nan
self.planning.publish(cloud_message(planning,origins,times,ids,end_ns))
self.last_output=end_ns*1e-9;self.published+=1
self.scans[0].popleft();self.scans[1].popleft()
except LookupError:return
except PoseGapError as error:
self.last_drop=str(error);self.scans[0].popleft();self.scans[1].popleft();self.dropped+=1
except ValueError as error:self.fault=str(error);return
def report(self):
self.status.publish(String(data=json.dumps(dict(fault=self.fault,published=self.published,dropped_pairs=self.dropped,
latest_output=self.last_output,last_sensor_timebase_ns=self.last,stamp=self.now_s(),
last_drop=self.last_drop,maximum_recent_pose_gap=max(np.diff([p[0] for p in self.history]),default=0.),
ground_mode=self.ground_mode,
lower_front_half_plane='vehicle directions x>=0; lower local y<=0'))))
def main():
rclpy.init();node=DualLidarFusion()
try:rclpy.spin(node)
except KeyboardInterrupt:pass
finally:
node.destroy_node()
if rclpy.ok():rclpy.shutdown()
if __name__=='__main__':main()
if __name__ == "__main__":
main()
@@ -1,279 +1,6 @@
#!/usr/bin/python3
"""Point-LIO -> SCAN, fixed known-start alignment; no truth/TF input or fallback."""
from array import array
from collections import deque
import copy
import json
import math
"""Compatibility entry; implementation shared with real-vehicle missions."""
from br_vehicle_mission.lio_navigation_adapter import *
import numpy as np
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
from geometry_msgs.msg import TransformStamped
from nav_msgs.msg import Odometry
from sensor_msgs.msg import PointCloud2,PointField
from std_msgs.msg import Bool,String
from tf2_ros import TransformBroadcaster,StaticTransformBroadcaster
def quaternion(values):
q=np.asarray(values,dtype=float)
if q.shape!=(4,) or not np.isfinite(q).all() or abs(np.linalg.norm(q)-1)>.001:
raise ValueError('invalid unit quaternion')
return q/np.linalg.norm(q)
def multiply(a,b):
return np.r_[a[3]*b[:3]+b[3]*a[:3]+np.cross(a[:3],b[:3]),a[3]*b[3]-np.dot(a[:3],b[:3])]
def rotation(q):
x,y,z,w=quaternion(q)
return np.array([[1-2*(y*y+z*z),2*(x*y-z*w),2*(x*z+y*w)],
[2*(x*y+z*w),1-2*(x*x+z*z),2*(y*z-x*w)],
[2*(x*z-y*w),2*(y*z+x*w),1-2*(x*x+y*y)]])
def skew(v):
x,y,z=v
return np.array([[0,-z,y],[z,0,-x],[-y,x,0]])
class FixedAlignment:
def __init__(self,prior_base,imu_position_base,position,orientation):
self.imu_position_base=np.asarray(imu_position_base)
yaw=prior_base[3];prior_q=np.array([0.,0.,math.sin(yaw/2),math.cos(yaw/2)])
inverse=quaternion(orientation).copy();inverse[:3]*=-1
self.q=quaternion(multiply(prior_q,inverse));self.R=rotation(self.q)
self.t=np.array(prior_base[:3])+rotation(prior_q)@self.imu_position_base-self.R@position
def pose(self,position,orientation,offset_from_imu):
q=quaternion(multiply(self.q,quaternion(orientation)))
return self.R@position+self.t+rotation(q)@offset_from_imu,q
def shifted_twist(linear,angular,offset_from_imu):
# All three model axes are aligned; offset is from IMU to target origin.
return np.asarray(linear)+np.cross(angular,offset_from_imu)
def float_fields(msg,names,data=None):
fields={f.name:f for f in msg.fields}
if any(n not in fields or fields[n].datatype!=PointField.FLOAT32 or fields[n].count!=1 for n in names):
raise ValueError('missing float32 point fields: '+','.join(names))
if len(msg.data)<msg.row_step*msg.height:raise ValueError('truncated point data')
return [np.ndarray((msg.height,msg.width),dtype=('>' if msg.is_bigendian else '<')+'f4',
buffer=msg.data if data is None else data,offset=fields[n].offset,
strides=(msg.row_step,msg.point_step)) for n in names]
class LioNavigationAdapter(Node):
def __init__(self):
super().__init__('lio_navigation_adapter')
self.prior=np.array(self.declare_parameter('initial_base_pose',[-4.5,4.5,.15,0.]).value)
self.imu=np.array(self.declare_parameter('imu_position_base',[.026,.02329,.28588]).value)
self.lidar=np.array(self.declare_parameter('lidar_position_base',[.015,0.,.33]).value)
if self.prior.shape!=(4,) or self.imu.shape!=(3,) or self.lidar.shape!=(3,) or not all(np.isfinite(a).all() for a in (self.prior,self.imu,self.lidar)):
raise ValueError('invalid prior or installation geometry')
self.cutoff=float(self.declare_parameter('ground_cutoff_z',.015).value)
if not math.isfinite(self.cutoff):raise ValueError('invalid ground cutoff')
planes=list(self.declare_parameter('traversable_planes',[0.]*7).value)
self.surface_tolerance=float(self.declare_parameter('surface_tolerance',.015).value)
if len(planes)%7 or not all(math.isfinite(v) for v in planes) or not math.isfinite(self.surface_tolerance) or not 0<self.surface_tolerance<=.06:
raise ValueError('invalid known traversable surfaces or tolerance')
self.planes=[planes[i:i+7] for i in range(0,len(planes),7) if planes[i+1]>planes[i] and planes[i+3]>planes[i+2]]
self.planning_topic=self.declare_parameter('required_planning_topic','').value
self.planning_max_age=float(self.declare_parameter('required_planning_max_age',.3).value)
if not math.isfinite(self.planning_max_age) or not 0<self.planning_max_age<=.3:
raise ValueError('downstream planning maximum age must be in (0,0.3]')
self.downstream_stamp=None
self.alignment=None;self.fault='';self.window=deque();self.last=None
self.odom_stamp=None;self.cloud_stamp=None;self.cloud_count=0;self.last_status=-1.;self.last_ready=None
self.pending_planning=deque()
# /clock and sensor callbacks are independently delivered. Keep a small
# bounded queue instead of dropping every source sample that arrives
# just before its clock tick. Nothing is published before source time.
self.pending_odom=deque();self.pending_cloud=deque();self.future_dropped=0
self.anchor_stamp=None
self.body_pub=self.create_publisher(Odometry,'/sim/navigation/body_odom',20)
self.sensor_pub=self.create_publisher(Odometry,'/sim/navigation/sensor_odom',20)
self.world_pub=self.create_publisher(PointCloud2,'/sim/navigation/cloud_registered',5)
self.planning_pub=self.create_publisher(PointCloud2,'/sim/navigation/planning_cloud',5)
self.ready_pub=self.create_publisher(Bool,'/planning/perception_ready',QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.status_pub=self.create_publisher(String,'/sim/navigation/status',QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.tf=TransformBroadcaster(self);self.static_tf=StaticTransformBroadcaster(self)
self.create_subscription(Odometry,'/sim/lio/aft_mapped_to_init',self.on_odom,100)
self.create_subscription(PointCloud2,'/sim/lio/cloud_registered_full_lidar',self.on_cloud,qos_profile_sensor_data)
if self.planning_topic:
if self.planning_topic in ('/sim/navigation/cloud_registered','/sim/navigation/planning_cloud'):
raise ValueError('downstream gate must use a separate derived planning topic')
cloud_qos=QoSProfile(depth=1) if self.declare_parameter('planning_cloud_reliable',False).value else qos_profile_sensor_data
self.create_subscription(PointCloud2,self.planning_topic,self.on_planning_cloud,cloud_qos)
self.create_timer(.05,self.health)
def on_planning_cloud(self,m):
self.defer_until_clock(m,self.pending_planning,self.process_planning_cloud,'world')
def process_planning_cloud(self,m):
if m.width*m.height>0:
self.downstream_stamp=self.stamp(m)
@staticmethod
def stamp(m):return m.header.stamp.sec+m.header.stamp.nanosec*1e-9
def now_s(self):return self.get_clock().now().nanoseconds*1e-9
def fresh(self,stamp,limit):return stamp is not None and 0<=self.now_s()-stamp<=limit
def reject(self,reason):
if not self.fault:self.get_logger().error('Navigation latched stopped: '+reason)
self.fault=reason
@staticmethod
def transform(parent,child,stamp,position,orientation):
tr=TransformStamped();tr.header.frame_id=parent;tr.child_frame_id=child;tr.header.stamp=stamp
tr.transform.translation.x,tr.transform.translation.y,tr.transform.translation.z=map(float,position)
tr.transform.rotation.x,tr.transform.rotation.y,tr.transform.rotation.z,tr.transform.rotation.w=map(float,orientation)
return tr
def defer_until_clock(self,m,pending,handler,expected_frame,expected_child=None):
if self.fault:return
if m.header.frame_id!=expected_frame or (expected_child is not None and m.child_frame_id!=expected_child):
self.reject('unexpected LIO odometry frames' if expected_child else 'unexpected paired cloud frame');return
self.flush_pending()
if self.fault:return
t=self.stamp(m)
if t>self.now_s()+.2:
self.future_dropped+=1;return
if pending or t>self.now_s():
if len(pending)>=64:
self.reject('clock pending queue overflow');return
pending.append(m)
else:handler(m)
def flush_pending(self):
for pending,handler in ((self.pending_odom,self.process_odom),(self.pending_cloud,self.process_cloud),(self.pending_planning,self.process_planning_cloud)):
while pending and not self.fault and self.stamp(pending[0])<=self.now_s():
handler(pending.popleft())
def on_odom(self,m):
self.defer_until_clock(m,self.pending_odom,self.process_odom,'camera_init','body')
def process_odom(self,m):
if self.fault:return
try:
if m.header.frame_id!='camera_init' or m.child_frame_id!='body':raise ValueError('unexpected LIO odometry frames')
p=m.pose.pose.position;q=m.pose.pose.orientation;v=m.twist.twist.linear;w=m.twist.twist.angular
pos=np.array([p.x,p.y,p.z]);q=quaternion([q.x,q.y,q.z,q.w]);linear=np.array([v.x,v.y,v.z]);angular=np.array([w.x,w.y,w.z])
if not all(np.isfinite(a).all() for a in (pos,linear,angular)):raise ValueError('nonfinite odometry')
t=self.stamp(m)
if not self.fresh(t,.2):return
if self.last is not None:
dt=t-self.last[0]
if dt==0:return
if dt<0:raise ValueError('LIO time moved backwards')
if self.alignment and (dt>.5 or np.linalg.norm(pos-self.last[1])>.12+.7*dt or
2*math.acos(min(1.,abs(np.dot(q,self.last[2]))))>.20+dt):
raise ValueError('LIO gap or pose discontinuity; restart with a known start pose')
self.last=(t,pos,q)
if self.alignment is None:
if np.linalg.norm(angular)>.02:self.window.clear();return
self.window.append((t,pos,q,linear))
while len(self.window)>1 and t-self.window[1][0]>1.:self.window.popleft()
if len(self.window)<20 or t-self.window[0][0]<1.:return
# Pointwise EKF velocity jitters even when the physical body is
# still. Require a quiet full window, not a run of quiet samples.
# Keep the original speed, displacement and angular thresholds.
if np.linalg.norm(np.mean([s[3] for s in self.window],axis=0))>.02:return
if max(np.linalg.norm(s[1]-pos) for s in self.window)>.02:return
self.alignment=FixedAlignment(self.prior,self.imu,pos,q);self.anchor_stamp=t
self.static_tf.sendTransform([
self.transform('world','camera_init',m.header.stamp,self.alignment.t,self.alignment.q),
self.transform('lio_imu','lio_base_link',m.header.stamp,-self.imu,[0.,0.,0.,1.]),
self.transform('lio_base_link','lio_lidar',m.header.stamp,self.lidar,[0.,0.,0.,1.])])
self.get_logger().info('Fixed known-start alignment locked; no truth input')
for child,offset,pub in [('lio_base_link',-self.imu,self.body_pub),('lio_lidar',self.lidar-self.imu,self.sensor_pub)]:
out=copy.deepcopy(m);out.header.frame_id='world';out.child_frame_id=child
op,oq=self.alignment.pose(pos,q,offset)
out.pose.pose.position.x,out.pose.pose.position.y,out.pose.pose.position.z=map(float,op)
out.pose.pose.orientation.x,out.pose.pose.orientation.y,out.pose.pose.orientation.z,out.pose.pose.orientation.w=map(float,oq)
ov=shifted_twist(linear,angular,offset)
out.twist.twist.linear.x,out.twist.twist.linear.y,out.twist.twist.linear.z=map(float,ov)
# Rotate pose covariance into world, then move the reference point.
A=np.zeros((6,6));A[:3,:3]=self.alignment.R;A[3:,3:]=self.alignment.R
J=np.eye(6);J[:3,3:]=-skew(rotation(oq)@offset)
C=np.asarray(m.pose.covariance).reshape(6,6)
out.pose.covariance=(J@A@C@A.T@J.T).ravel().tolist()
J=np.eye(6);J[:3,3:]=-skew(offset)
C=np.asarray(m.twist.covariance).reshape(6,6)
out.twist.covariance=(J@C@J.T).ravel().tolist()
pub.publish(out)
self.tf.sendTransform(self.transform('camera_init','lio_imu',m.header.stamp,pos,q))
self.odom_stamp=t
except (ValueError,TypeError,KeyError) as exc:self.reject(str(exc))
def on_cloud(self,m):
self.defer_until_clock(m,self.pending_cloud,self.process_cloud,'camera_init')
def process_cloud(self,m):
if self.fault or self.alignment is None:return
try:
t=self.stamp(m)
if m.header.frame_id!='camera_init':raise ValueError('unexpected paired cloud frame')
if not self.fresh(t,.25) or not self.fresh(self.odom_stamp,.2):return
if self.cloud_stamp is not None and t<=self.cloud_stamp:return
names=('x','y','z','lidar_x','lidar_y','lidar_z')
values=float_fields(m,names)
xyz=np.stack(values[:3],axis=-1)
raw=np.stack(values[3:],axis=-1)
if np.count_nonzero(np.isfinite(xyz).all(axis=-1))<100:return
world=xyz@self.alignment.R.T+self.alignment.t
data=bytearray(m.data)
for i,v in enumerate(float_fields(m,names[:3],data)):v[:]=world[...,i]
out=copy.deepcopy(m);out.header.frame_id='world';out.data=array('B',data)
self.world_pub.publish(out)
# Classify paired ORIGINAL optical points in the vehicle envelope.
# Base remains .15 m above ground; measured roof is .41 m high.
body_raw=raw+self.lidar
self_hit=(np.abs(body_raw[...,0])<=.42)&(np.abs(body_raw[...,1])<=.42)&(body_raw[...,2]>=-.17)&(body_raw[...,2]<=.28)
ground=world[...,2]<=self.cutoff
for x0,x1,y0,y1,mx,my,b in self.planes:
ground|=(world[...,0]>=x0)&(world[...,0]<=x1)&(world[...,1]>=y0)&(world[...,1]<=y1)&(
np.abs(world[...,2]-(mx*world[...,0]+my*world[...,1]+b))<=self.surface_tolerance)
for v in float_fields(m,names[:3],data):v[self_hit|ground]=np.nan
out.data=array('B',data);out.is_dense=False;self.planning_pub.publish(out)
self.cloud_stamp=t;self.cloud_count+=1
except (ValueError,TypeError,KeyError) as exc:self.reject(str(exc))
def health(self):
self.flush_pending()
# When an external planning stream is selected (dual fusion / terrain),
# that is the cloud actually consumed by navigation. The independent
# upper registered cloud remains a display output, not a second gate.
stamp,limit=(self.downstream_stamp,self.planning_max_age) if self.planning_topic else (self.cloud_stamp,.25)
ready=not self.fault and self.alignment is not None and self.fresh(self.odom_stamp,.2) and self.fresh(stamp,limit)
changed=ready!=self.last_ready;self.last_ready=ready
self.ready_pub.publish(Bool(data=bool(ready)))
if self.now_s()-self.last_status<.5 and not changed:return
self.last_status=self.now_s()
status=dict(phase='fault' if self.fault else ('initializing' if self.alignment is None else ('active' if ready else 'stale')),
reason=self.fault,ready=bool(ready),stamp=self.now_s(),anchor_stamp=self.anchor_stamp,
odom_stamp=self.odom_stamp,cloud_stamp=self.cloud_stamp,cloud_count=self.cloud_count,
downstream_stamp=self.downstream_stamp,required_planning_topic=self.planning_topic,
readiness_cloud='downstream' if self.planning_topic else 'registered',readiness_cloud_age=None if stamp is None else self.now_s()-stamp,readiness_cloud_max_age=limit,
pending_odom=len(self.pending_odom),pending_cloud=len(self.pending_cloud),future_dropped=self.future_dropped,
known_start_base=self.prior.tolist(),imu_position_base=self.imu.tolist())
if self.alignment:status.update(rotation=self.alignment.R.tolist(),translation=self.alignment.t.tolist())
self.status_pub.publish(String(data=json.dumps(status)))
def main():
rclpy.init();node=LioNavigationAdapter()
try:rclpy.spin(node)
except KeyboardInterrupt:pass
finally:
node.destroy_node()
if rclpy.ok():rclpy.shutdown()
if __name__=='__main__':main()
if __name__ == "__main__":
main()
@@ -1,99 +1,6 @@
#!/usr/bin/python3
"""One /cmd_vel owner with expiring mission leases and independent health gates."""
import json,math
from collections import deque
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
from geometry_msgs.msg import Twist,TwistStamped
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Imu
from std_msgs.msg import Bool,String
from lio_navigation_adapter import quaternion
"""Compatibility entry; implementation shared with real-vehicle missions."""
from br_vehicle_mission.mission_command_mux import *
def select_command(now,lease,nav,ramp,health,max_linear=.5,max_yaw=.5):
"""Pure fail-closed arbitration. Times are ROS source/receipt seconds."""
zero=(0.,0.,0.)
if lease is None or not 0<=now-lease['stamp']<=.15:return zero,'lease_stale'
if not health:return zero,'health_not_ready'
mode=lease['mode']
if mode=='STOP':return zero,'stop_lease'
source=nav if mode=='NAV' else ramp if mode=='RAMP' else None
if source is None:return zero,'source_missing'
stamp,command=source
if stamp<lease['since'] or not 0<=now-stamp<=.12:return zero,'source_stale_or_before_grant'
if not all(math.isfinite(x) for x in command):return zero,'invalid_command'
vx,vy,wz=command;scale=min(1.,max_linear/max(math.hypot(vx,vy),1e-12))
return (vx*scale,vy*scale,max(-max_yaw,min(max_yaw,wz))),'selected_'+mode.lower()
class MissionCommandMux(Node):
def __init__(self):
super().__init__('mission_command_mux');self.lease=None;self.nav=None;self.ramp=None
self.max_linear=float(self.declare_parameter('max_linear',.5).value)
self.nav_max_linear=float(self.declare_parameter('nav_max_linear',.5).value)
self.max_yaw=float(self.declare_parameter('max_yaw',.5).value)
if not 0<self.max_linear<=2.5 or not 0<self.nav_max_linear<=self.max_linear or not 0<self.max_yaw<=2.:raise ValueError('invalid mux speed limits')
self.ready=False;self.ready_stamp=None;self.odom_stamp=None;self.imu_stamp=None;self.last_now=None
self.pending_odom=deque(maxlen=100);self.pending_imu=deque(maxlen=100)
self.output=self.create_publisher(Twist,'/cmd_vel',10)
self.status=self.create_publisher(String,'/mission/mux_status',10)
self.create_subscription(String,'/mission/control_lease',self.on_lease,1)
self.create_subscription(Twist,'/mission/navigation_cmd_vel',self.on_nav,1)
self.create_subscription(TwistStamped,'/mission/ramp_cmd_vel',self.on_ramp,1)
self.create_subscription(Odometry,'/sim/navigation/body_odom',self.on_odom,20)
self.create_subscription(Imu,'/sim/mid360/imu',self.on_imu,qos_profile_sensor_data)
self.create_subscription(Bool,'/planning/perception_ready',self.on_ready,QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_timer(.02,self.tick);self.last_report=-1.
def now(self):return self.get_clock().now().nanoseconds*1e-9
@staticmethod
def stamp(m):return m.header.stamp.sec+m.header.stamp.nanosec*1e-9
def on_ready(self,m):self.ready=m.data;self.ready_stamp=self.now()
def on_odom(self,m):
try:
if m.header.frame_id!='world' or m.child_frame_id!='lio_base_link':raise ValueError('wrong frames')
q=m.pose.pose.orientation;quaternion([q.x,q.y,q.z,q.w]);p=m.pose.pose.position
if not all(math.isfinite(v) for v in (p.x,p.y,p.z)):raise ValueError('invalid position')
self.pending_odom.append(self.stamp(m))
except ValueError:self.odom_stamp=None
def on_imu(self,m):
a=m.angular_velocity;v=m.linear_acceleration
if m.header.frame_id=='mid360_imu' and all(math.isfinite(x) for x in (a.x,a.y,a.z,v.x,v.y,v.z)):self.pending_imu.append(self.stamp(m))
else:self.imu_stamp=None;self.pending_imu.clear()
def on_lease(self,m):
try:
lease=json.loads(m.data)
if lease['mode'] not in ('STOP','NAV','RAMP') or not all(math.isfinite(lease[k]) for k in ('stamp','since')) or lease['since']>lease['stamp']:raise ValueError('invalid lease')
if self.lease and lease['stamp']<self.lease['stamp']:return
if self.lease is None or (lease['mode'],lease['since'])!=(self.lease['mode'],self.lease['since']):self.nav=None;self.ramp=None
self.lease=lease
except (ValueError,KeyError,TypeError):self.lease=None
@staticmethod
def command(m):return (m.linear.x,m.linear.y,m.angular.z)
def on_nav(self,m):self.nav=(self.now(),self.command(m))
def on_ramp(self,m):
if m.header.frame_id=='lio_base_link':self.ramp=(self.stamp(m),self.command(m.twist))
def tick(self):
now=self.now()
for queue,name in ((self.pending_odom,'odom_stamp'),(self.pending_imu,'imu_stamp')):
while queue and queue[0]<=now:setattr(self,name,queue.popleft())
if self.last_now is not None and now<self.last_now:self.lease=None;self.nav=None;self.ramp=None
self.last_now=now
fresh=lambda t,age:t is not None and 0<=now-t<=age
healthy=self.ready and fresh(self.ready_stamp,.15) and fresh(self.odom_stamp,.20) and fresh(self.imu_stamp,.10)
limit=self.nav_max_linear if self.lease and self.lease['mode']=='NAV' else self.max_linear
command,reason=select_command(now,self.lease,self.nav,self.ramp,healthy,limit,self.max_yaw)
m=Twist();m.linear.x,m.linear.y,m.angular.z=command;self.output.publish(m)
if now-self.last_report>=.1:
self.last_report=now;self.status.publish(String(data=json.dumps(dict(stamp=now,reason=reason,healthy=bool(healthy),lease=self.lease,command=command,nav_source_age_s=None if self.nav is None else now-self.nav[0],ramp_source_age_s=None if self.ramp is None else now-self.ramp[0]))))
def main():
rclpy.init();node=MissionCommandMux()
try:rclpy.spin(node)
except KeyboardInterrupt:pass
finally:
node.output.publish(Twist());node.destroy_node()
if rclpy.ok():rclpy.shutdown()
if __name__=='__main__':main()
if __name__ == "__main__":
main()
@@ -1,324 +1,6 @@
#!/usr/bin/python3
"""Known-field staged mission: SCAN approach, estimated-state ramp control, stop.
"""Compatibility entry; implementation shared with real-vehicle missions."""
from br_vehicle_mission.ramp_mission import *
No Gazebo truth, TF, entity services, or raw IMU orientation is used. All motion
is leased to a separate fail-closed mux; this node never publishes /cmd_vel.
"""
import json,math
from collections import deque
import numpy as np
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
from geometry_msgs.msg import PoseStamped,TwistStamped
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Imu,PointCloud2
from std_msgs.msg import Bool,String
from std_srvs.srv import Trigger
from scan_planner_msgs.msg import TrajectoryStatus
from livox_ros_driver2.msg import CustomMsg
from lio_navigation_adapter import quaternion,rotation,float_fields
def wrap(a):return math.atan2(math.sin(a),math.cos(a))
def attitude(q):
R=rotation(q)
return math.atan2(R[1,0],R[0,0]),math.asin(np.clip(-R[2,0],-1.,1.)),math.atan2(R[2,1],R[2,2])
def ground_height(x):
x=np.asarray(x)
return np.where(x>=2.7,0.,np.where(x<=-.8,.6,(1.6119-.597*x)/3.5))
def body_command(q,speed,y_error):
R=rotation(q)
# Requested speed is along the body ground tangent, not world horizontal.
vx=-speed*math.hypot(R[0,0],R[1,0]);vy=float(np.clip(1.5*y_error,-.06,.06))
command=np.linalg.solve(R[:2,:2],np.array([vx,vy]))
yaw,_,_=attitude(q)
return float(command[0]),float(command[1]),float(np.clip(2.*wrap(math.pi-yaw),-.25,.25))
def envelope(p,q):
R=rotation(q);center=np.asarray(p)+R@np.array([0.,0.,.055])
ext=np.abs(R)@np.array([.4,.4,.205])
return center-ext,center+ext
def speed_target(x,ramp_speed,crest_speed,fast=False):
# Brake before the selected low-speed zone: standard base x=-.25,
# experimental fast base x=-.9 (front on top, rear still clearing the ramp).
# Account for command slew and .10 s reaction; slow again at the endpoint.
deceleration=2.0 if fast else .4
distance=max(0.,x+(.9 if fast else .25))
crest_limit=math.sqrt(crest_speed**2+2*deceleration*distance)
crest_limit=max(crest_speed,crest_limit-deceleration*.10)
return min(ramp_speed,crest_limit,max(.02 if fast else .012,(5. if fast else .8)*(x+1.30)))
def obstacle_count(cloud,p,q,speed,deceleration=.4):
"""Physical-observation strip with reaction+braking distance, known ground.
Does not claim detection of every <=10 cm obstacle under the existing 6 cm
terrain filter. Explicit prior points are not fed into this guard.
"""
if cloud is None:return 0
lo,hi=envelope(p,q);distance=abs(speed)*.35+speed*speed/(2*deceleration)+.05
x,y,z=cloud.T;g=ground_height(x)
mask=np.isfinite(cloud).all(axis=1)&(z>g+.06)&(z<g+.45)&(x>=lo[0]-distance)&(x<p[0]+.1)&(y>=lo[1]-.04)&(y<=hi[1]+.04)
return int(mask.sum())
class RampMission(Node):
DIRECT={'ENTRY','CLIMB','CREST','PLATFORM'}
def __init__(self):
super().__init__('ramp_mission')
self.profile=self.declare_parameter('profile','standard').value
if self.profile not in ('standard','fast'):raise ValueError('invalid mission profile')
self.fast=self.profile=='fast'
self.ramp_acceleration=2.0 if self.fast else .4
self.autostart=self.declare_parameter('autostart',False).value
self.aligned_start=self.declare_parameter('aligned_start',False).value
self.ramp_speed=float(self.declare_parameter('ramp_speed',.7).value)
self.crest_speed=float(self.declare_parameter('crest_speed',.2).value)
if not .10<=self.ramp_speed<=(1.1 if self.fast else .7) or not .03<=self.crest_speed<=.2 or self.crest_speed>self.ramp_speed:raise ValueError('invalid drive envelope')
self.state='IDLE';self.reason='waiting_start';self.requested=bool(self.autostart)
self.pose=None;self.ready=False;self.ready_stamp=None;self.imu_stamp=None;self.gyro=None
self.lower_stamp=None;self.pending_lower=deque()
self.health_failure=None
self.lower_hold=False
self.cloud=None;self.cloud_stamp=None;self.status=None;self.nav_index=0;self.wait_goal_id=0
# Standard keeps two staging stops. Fast replaces the first approach
# goal while moving, then still stops for a checked terminal pi sweep.
self.goals=[(3.7,4.8,0.),(3.7,4.,0.),(3.7,3.5125,math.pi)]
if self.fast:self.goals=[(3.7,4.8,0.),(3.7,3.5125,math.pi)]
self.goal_sent=None;self.stable_since=None;self.enter_since=None;self.flat_since=None;self.seen_slope=False
self.pitch_zero=0.;self.start_time=None;self.last_now=None;self.events=[];self.mode='STOP';self.mode_since=0.
self.command_speed=0.;self.obstacles=0;self.last_report=-1.;self.last_control=None
self.pending_pose=deque();self.pending_imu=deque();self.pending_cloud=deque()
self.pose_window=deque()
self.goal_pub=self.create_publisher(PoseStamped,'/move_base_simple/goal',10)
self.lease_pub=self.create_publisher(String,'/mission/control_lease',1)
self.direct_pub=self.create_publisher(TwistStamped,'/mission/ramp_cmd_vel',1)
self.report_pub=self.create_publisher(String,'/mission/status',QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_subscription(Odometry,'/sim/navigation/body_odom',self.on_pose,50)
self.create_subscription(Imu,'/sim/mid360/imu',self.on_imu,qos_profile_sensor_data)
self.create_subscription(CustomMsg,'/sim/mid360_low/lidar',self.on_lower,qos_profile_sensor_data)
self.create_subscription(PointCloud2,'/sim/navigation/fused_planning_cloud',self.on_cloud,QoSProfile(depth=1))
self.create_subscription(Bool,'/planning/perception_ready',self.on_ready,QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_subscription(TrajectoryStatus,'/planning/trajectory_status',lambda m:setattr(self,'status',m),QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_service(Trigger,'/ramp_mission/start',self.start)
self.create_service(Trigger,'/ramp_mission/cancel',self.cancel)
self.create_timer(.02,self.tick)
def now(self):return self.get_clock().now().nanoseconds*1e-9
@staticmethod
def stamp(m):return m.header.stamp.sec+m.header.stamp.nanosec*1e-9
def start(self,req,res):
res.success=self.state=='IDLE' and not self.requested
if res.success:self.requested=True
res.message='start requested' if res.success else 'one-shot mission already requested or terminal; no automatic restart'
return res
def cancel(self,req,res):self.fail('user_cancel');res.success=True;res.message='latched stopped';return res
def on_ready(self,m):self.ready=m.data;self.ready_stamp=self.now()
def health_snapshot(self,now):
sources={'ready_signal':(self.ready_stamp,.15),'estimated_odom':(None if self.pose is None else self.pose['stamp'],.2),
'imu':(self.imu_stamp,.1),'fused_cloud':(self.cloud_stamp,.3),'lower_scan':(self.lower_stamp,.23)}
snapshot=dict(stamp=now,ready_flag=bool(self.ready),sources={},failed_checks=[] if self.ready else ['perception_not_ready'])
for name,(stamp,limit) in sources.items():
age=None if stamp is None else now-stamp
ok=age is not None and 0<=age<=limit
snapshot['sources'][name]=dict(stamp=stamp,age_s=age,max_age_s=limit,ok=ok)
if not ok:snapshot['failed_checks'].append(name)
return snapshot
def on_pose(self,m):
if len(self.pending_pose)>=100:self.fail('pose_queue_overflow');return
self.pending_pose.append(m)
def process_pose(self,m):
try:
if m.header.frame_id!='world' or m.child_frame_id!='lio_base_link':raise ValueError('pose frames')
p=m.pose.pose.position;q=m.pose.pose.orientation;v=m.twist.twist.linear;w=m.twist.twist.angular
q=quaternion([q.x,q.y,q.z,q.w]);p=np.array([p.x,p.y,p.z]);velocity=np.array([v.x,v.y,v.z])
if not np.isfinite(p).all() or not np.isfinite(velocity).all() or not math.isfinite(w.z):raise ValueError('nonfinite pose')
t=self.stamp(m)
if self.pose is not None and t<self.pose['stamp']:raise ValueError('pose time backwards')
self.pose=dict(stamp=t,p=p,q=q,velocity=velocity,speed=float(np.linalg.norm(velocity)),wz=w.z)
self.pose_window.append(self.pose)
while self.pose_window and self.pose_window[0]['stamp']<t-(.35 if self.fast else .5):self.pose_window.popleft()
except ValueError as exc:self.fail(str(exc))
def on_imu(self,m):
if len(self.pending_imu)>=100:self.fail('imu_queue_overflow');return
self.pending_imu.append(m)
def process_imu(self,m):
g=m.angular_velocity
if m.header.frame_id!='mid360_imu' or not all(math.isfinite(v) for v in (g.x,g.y,g.z)):self.fail('invalid_imu');return
self.imu_stamp=self.stamp(m);self.gyro=np.array([g.x,g.y,g.z])
def on_lower(self,m):
# Independent of fused-cloud latency. Use the actual last acquired
# point's source time, never receipt time or an invented scan period.
if m.header.frame_id!='lidar_low' or m.lidar_id!=1 or not m.points or m.point_num!=len(m.points) or int(m.timebase)!=m.header.stamp.sec*1000000000+m.header.stamp.nanosec:
self.fail('invalid_lower_scan');return
offset=max(p.offset_time for p in m.points)
if offset>=100000000 or len(self.pending_lower)>=20:self.fail('invalid_lower_scan_timing');return
self.pending_lower.append((int(m.timebase)+int(offset))*1e-9)
def on_cloud(self,m):
if m.header.frame_id!='world':self.fail('cloud frame');return
if len(self.pending_cloud)>=10:self.fail('cloud_queue_overflow');return
self.pending_cloud.append(m)
def process_cloud(self,m):
try:
if self.cloud_stamp is not None and self.stamp(m)<self.cloud_stamp:raise ValueError('cloud time backwards')
self.cloud=np.stack(float_fields(m,('x','y','z')),axis=-1).reshape(-1,3)
self.cloud_stamp=self.stamp(m)
except ValueError as exc:self.fail(str(exc))
def transition(self,state,reason):
if self.state==state:return
self.events.append(dict(stamp=self.now(),from_state=self.state,to=state,reason=reason))
self.get_logger().info(self.state+' -> '+state+': '+reason)
self.state=state;self.reason=reason;self.stable_since=None
def fail(self,reason):
if self.state not in ('FAILED','SUCCEEDED'):self.transition('FAILED',reason)
def set_mode(self,mode,now):
if mode!=self.mode:self.mode=mode;self.mode_since=now
self.lease_pub.publish(String(data=json.dumps(dict(stamp=now,since=self.mode_since,mode=mode))))
def stationary(self):
# LIO instantaneous velocity is noisy even while physical truth is
# stopped. Require a mature position-stable window AND mean velocity;
# never accept a single low sample or the IMU flatness alone.
samples=list(self.pose_window)
if len(samples)<(15 if self.fast else 20) or samples[-1]['stamp']-samples[0]['stamp']<(.30 if self.fast else .35):return False
pos=np.array([s['p'] for s in samples]);vel=np.array([s['velocity'] for s in samples])
return bool(np.linalg.norm(np.mean(vel,axis=0))<(.02 if self.fast else .012) and np.linalg.norm(np.ptp(pos,axis=0))<.02 and max(abs(s['wz']) for s in samples)<.02)
def send_goal(self,now):
self.wait_goal_id=self.status.goal_id if self.status else 0
m=PoseStamped();m.header.frame_id='world';m.header.stamp=self.get_clock().now().to_msg()
x,y,yaw=self.goals[self.nav_index];m.pose.position.x=x;m.pose.position.y=y;m.pose.position.z=.15
m.pose.orientation.z=math.sin(yaw/2);m.pose.orientation.w=math.cos(yaw/2)
self.goal_pub.publish(m);self.goal_sent=now
self.get_logger().info('navigation waypoint %d: %.3f %.3f yaw %.3f'%(self.nav_index,x,y,yaw))
self.events.append(dict(stamp=now,goal=[x,y,yaw],event='navigation_goal'))
def tick(self):
now=self.now();dt=.02 if self.last_now is None else now-self.last_now
for queue,handler in ((self.pending_pose,self.process_pose),(self.pending_imu,self.process_imu),(self.pending_cloud,self.process_cloud)):
while queue and self.stamp(queue[0])<=now:handler(queue.popleft())
while self.pending_lower and self.pending_lower[0]<=now:
stamp=self.pending_lower.popleft()
if self.lower_stamp is not None and stamp<=self.lower_stamp:self.fail('lower_time_backwards')
self.lower_stamp=stamp
if self.last_now is not None and dt<0:self.fail('clock_backwards')
self.last_now=now;mode='STOP';command=(0.,0.,0.)
fresh=lambda t,age:t is not None and 0<=now-t<=age
health=self.health_snapshot(now);healthy=not health['failed_checks']
lower_age=None if self.lower_stamp is None else now-self.lower_stamp
holding=bool(self.fast and self.state in self.DIRECT and healthy and lower_age is not None and lower_age>.14)
if holding!=self.lower_hold:
self.events.append(dict(stamp=now,event='lower_scan_hold',active=holding,source_age_s=lower_age))
self.get_logger().info('Lower scan temporary hold: '+str(holding))
self.lower_hold=holding
try:
if self.state=='IDLE' and self.requested:
if healthy:
if self.stable_since is None:self.stable_since=now
if now-self.stable_since>=.5:
self.start_time=now
if self.aligned_start:
p,q=self.pose['p'],self.pose['q'];yaw,pitch,_=attitude(q)
if np.linalg.norm(p[:2]-[3.7,3.5125])>.03 or abs(wrap(yaw-math.pi))>.02 or not self.stationary():self.fail('diagnostic_start_not_aligned')
else:self.pitch_zero=pitch;self.transition('ENTRY','explicit_aligned_diagnostic_start')
else:self.transition('NAVIGATE','perception_initialized');self.send_goal(now)
else:self.stable_since=None
elif self.state not in ('IDLE','FAILED','SUCCEEDED'):
if not healthy:
self.health_failure=health
self.get_logger().error('Health stop in '+self.state+': '+json.dumps(health))
self.fail('perception_or_state_stale')
elif now-self.start_time>180:self.fail('mission_timeout')
elif self.state=='NAVIGATE':
s=self.status;x,y,_=self.goals[self.nav_index]
matched=s is not None and s.goal_id>self.wait_goal_id and abs(s.goal.x-x)<1e-5 and abs(s.goal.y-y)<1e-5 and self.stamp(s)>=self.goal_sent
if now-self.goal_sent>100:self.fail('navigation_timeout')
elif matched and s.state==s.FAILED:self.fail('navigation_failed:'+s.reason)
elif matched and s.state==s.ACTIVE and fresh(self.stamp(s),.2):
mode='NAV'
if self.fast and self.nav_index==0 and self.pose['p'][0]>=3.0 and abs(self.pose['p'][1]-4.8)<.05:
# Replace the approach target without requiring a
# stop at a geometrical staging point. The next
# SCAN trajectory still needs its own safety grant.
self.events.append(dict(stamp=now,event='approach_pass_through',position=self.pose['p'].tolist()))
self.nav_index=1;self.send_goal(now);mode='STOP'
elif matched and s.state==s.SUCCEEDED:
if self.stationary():
if self.stable_since is None:self.stable_since=now
if now-self.stable_since>=(.05 if self.fast else .25):
self.nav_index+=1
if self.nav_index<len(self.goals):self.send_goal(now);self.stable_since=None
else:
yaw,pitch,_=attitude(self.pose['q'])
if abs(wrap(yaw-math.pi))>.02 or abs(self.pose['p'][1]-3.5125)>.03:self.fail('entry_alignment_outside_tolerance')
else:self.pitch_zero=pitch;self.transition('ENTRY','navigation_handoff_stopped')
else:self.stable_since=None
elif self.state in self.DIRECT:
p,q=self.pose['p'],self.pose['q'];yaw,pitch,roll=attitude(q);lo,hi=envelope(p,q)
if abs(wrap(yaw-math.pi))>.06 or abs(roll)>.09 or abs(pitch-self.pitch_zero)>.35:self.fail('attitude_outside_corridor_envelope')
elif p[0]<3.1 and min(lo[1]-3.025,4.-hi[1])<.06:self.fail('estimated_lateral_clearance')
elif lo[0]<-1.76:self.fail('platform_end_guard')
else:
tilted=pitch-self.pitch_zero<-.07
if tilted:
if self.enter_since is None:self.enter_since=now
if now-self.enter_since>=.15:
self.seen_slope=True
if self.state=='ENTRY':self.transition('CLIMB','sustained_uphill_pitch')
else:self.enter_since=None
if not self.seen_slope and p[0]<1.8:self.fail('expected_slope_not_detected')
if self.seen_slope and p[0]<=(-.25 if not self.fast else 0.) and self.state=='CLIMB':self.transition('CREST','braking_before_crest')
flat=self.seen_slope and p[0]<-.85 and abs(pitch-self.pitch_zero)<.035 and abs(self.gyro[1])<.12
if flat:
if self.flat_since is None:self.flat_since=now
if now-self.flat_since>=.15 and self.state=='CREST':self.transition('PLATFORM','sustained_flat_after_climb')
else:self.flat_since=None
remaining=p[0]+1.30
if self.state=='PLATFORM' and remaining<=.012 and hi[0]<=-.84:
self.transition('SETTLE','whole_envelope_on_platform')
elif self.state in self.DIRECT:
control_x=p[0]
if self.fast:
# Control-only prediction, bounded by the same
# .20 s freshness gate. Source data is unchanged.
control_x+=(rotation(q)@self.pose['velocity'])[0]*max(0.,min(.2,now-self.pose['stamp']))
target=speed_target(control_x,self.ramp_speed,self.crest_speed,self.fast)
# Slew commanded longitudinal speed; final STOP and
# safety failures bypass the ramp limiter.
if self.lower_hold:self.command_speed=0.
else:self.command_speed+=float(np.clip(target-self.command_speed,-self.ramp_acceleration*max(0,dt),self.ramp_acceleration*max(0,dt)))
self.obstacles=obstacle_count(self.cloud,p,q,max(self.command_speed,self.pose['speed']),self.ramp_acceleration)
if self.obstacles:self.fail('obstacle_in_braking_corridor')
elif not self.lower_hold:command=body_command(q,self.command_speed,3.5125-p[1]);mode='RAMP'
elif self.state=='SETTLE':
p,q=self.pose['p'],self.pose['q'];lo,hi=envelope(p,q)
if lo[0]<-1.76 or hi[0]>-.84:self.fail('settling_outside_platform')
elif self.stationary():
if self.stable_since is None:self.stable_since=now
if now-self.stable_since>=(.2 if self.fast else .6):self.transition('SUCCEEDED','platform_stopped')
else:self.stable_since=None
except (ValueError,np.linalg.LinAlgError) as exc:self.fail('invalid_control:'+str(exc))
if self.state in ('FAILED','SUCCEEDED','SETTLE'):mode='STOP';command=(0.,0.,0.)
self.set_mode(mode,now)
msg=TwistStamped();msg.header.frame_id='lio_base_link';msg.header.stamp=self.get_clock().now().to_msg()
msg.twist.linear.x,msg.twist.linear.y,msg.twist.angular.z=command;self.direct_pub.publish(msg)
if now-self.last_report>=.1:
self.last_report=now
state=dict(stamp=now,state=self.state,reason=self.reason,profile=self.profile,mode=mode,healthy=bool(healthy),nav_index=self.nav_index,
elapsed_s=None if self.start_time is None else now-self.start_time,seen_slope=self.seen_slope,obstacle_returns=self.obstacles,
command=command,events=self.events)
state['source_age_s']={key:None if stamp is None else now-stamp for key,stamp in (('lower_scan',self.lower_stamp),('fused_cloud',self.cloud_stamp),('imu',self.imu_stamp))}
state['health_failure']=self.health_failure
state['waiting_lower_scan']=self.lower_hold
if self.pose is not None:state.update(estimated_position=self.pose['p'].tolist(),estimated_yaw_pitch_roll=list(attitude(self.pose['q'])),estimated_speed=self.pose['speed'])
self.report_pub.publish(String(data=json.dumps(state)))
def main():
rclpy.init();node=RampMission()
try:rclpy.spin(node)
except KeyboardInterrupt:pass
finally:
node.set_mode('STOP',node.now());node.destroy_node()
if rclpy.ok():rclpy.shutdown()
if __name__=='__main__':main()
if __name__ == "__main__":
main()
@@ -16,9 +16,10 @@
</physics>
<scene>
<ambient>0.4 0.4 0.4 1</ambient>
<!-- 提亮背光面,配合中性主光保留场地配色;默认关闭阴影。 -->
<ambient>0.65 0.65 0.65 1</ambient>
<background>0.7 0.7 0.7 1</background>
<shadows>true</shadows>
<shadows>false</shadows>
</scene>
<!-- 默认从红方(world +Y)外侧俯看红方半场,视线指向约 (0, 2.5, 0.1)。
@@ -34,8 +35,8 @@
<light type="directional" name="sun">
<cast_shadows>true</cast_shadows>
<pose>0 0 10 0 0 0</pose>
<diffuse>0.8 0.8 0.8 1</diffuse>
<specular>0.2 0.2 0.2 1</specular>
<diffuse>0.9 0.9 0.9 1</diffuse>
<specular>0.1 0.1 0.1 1</specular>
<direction>0.1 0.1 -1</direction>
</light>
@@ -48,11 +49,12 @@
world 级 <plugin> 声明已移除。本机头文件确认两者为 SystemPlugin,
不能作为 world <plugin> 加载;改由官方 gzserver.launch.py 以
`-s libgazebo_ros_init.so -s libgazebo_ros_factory.so` 各加载一次。
其余内容与源 world 完全一致。 -->
此插件调整不涉及场地几何与物理配置。 -->
<!-- SIM-P2-001: 官方 libgazebo_ros_state.so(WorldPlugin)提供独立真值查询:
/gazebo/get_entity_state、/gazebo/set_entity_state、/gazebo/link_states。
场地几何、物理与光照与本包 robocon_track_full.world 完全一致。 -->
场地几何与物理配置与本包 robocon_track_full.world 完全一致;
本入口单独设置 GUI 视角和光照。 -->
<plugin name="gazebo_ros_state" filename="libgazebo_ros_state.so">
<ros>
<namespace>/gazebo</namespace>