feat(br_vehicle_mission): CustomMsg 零拷贝解析 + 第二网口设备发现
livox_scan.py:用 struct/ndarray 直接读 CustomMsg 的 CDR1 布局,不再为每个点 构造 Python 对象。view 保留输入缓冲,坐标/时间戳/偏移量一个数都不改; 不支持的编码与长度不一致必须 fail-closed(抛 ValueError)。 订阅端统一改为 raw=True + read_scan()。这是跨模块契约,四个消费方必须同批改, 否则中间态是坏的:dual_lidar_fusion.py、ramp_mission.py、probe_vehicle_sensors.py, 以及 CMakeLists 新增的 test_livox_scan 用例。原来的逐点校验 (point_num == len(points))在零拷贝下退化为只看 point_num。 driver_discovery.py + scripts/discover_mid360.py:无交换机、两颗雷达分别直连时, SDK 的自动发现只覆盖一个网口。这里在明确指定的第二个网口上补发设备类型查询, 只发查询、不改配置。ramp_vehicle.launch.py 通过 driver_discovery_interface / driver_discovery_host_ip 两个参数接入,默认空即不启用。 测试:test_vehicle_migration 新增序列化消息与对象消息输出等价的断言—— 这是 raw=True 的前提,两者必须产出同样的融合结果。
This commit is contained in:
@@ -6,12 +6,13 @@ ament_python_install_package(${PROJECT_NAME})
|
||||
install(PROGRAMS
|
||||
scripts/lio_navigation_adapter.py scripts/dual_lidar_fusion.py
|
||||
scripts/ramp_mission.py scripts/mission_command_mux.py
|
||||
scripts/configure_dual_mid360.py scripts/probe_vehicle_sensors.py
|
||||
scripts/configure_dual_mid360.py scripts/probe_vehicle_sensors.py scripts/discover_mid360.py
|
||||
DESTINATION lib/${PROJECT_NAME})
|
||||
install(DIRECTORY launch config DESTINATION share/${PROJECT_NAME}
|
||||
PATTERN "__pycache__" EXCLUDE)
|
||||
if(BUILD_TESTING)
|
||||
find_package(ament_cmake_pytest REQUIRED)
|
||||
ament_add_pytest_test(vehicle_migration test/test_vehicle_migration.py TIMEOUT 60)
|
||||
ament_add_pytest_test(livox_scan test/test_livox_scan.py TIMEOUT 60)
|
||||
endif()
|
||||
ament_package()
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Optional, bounded discovery on an explicitly selected second lidar link."""
|
||||
import ipaddress
|
||||
import os
|
||||
import socket
|
||||
from ament_index_python.packages import get_package_prefix
|
||||
from launch.actions import ExecuteProcess, TimerAction, RegisterEventHandler, EmitEvent
|
||||
from launch.event_handlers import OnProcessExit
|
||||
from launch.events import Shutdown
|
||||
|
||||
|
||||
def discovery_actions(interface, host_ip):
|
||||
if not interface and not host_ip:
|
||||
return []
|
||||
if not interface or not host_ip:
|
||||
raise ValueError('driver_discovery_interface and driver_discovery_host_ip must be supplied together')
|
||||
host = ipaddress.IPv4Address(host_ip)
|
||||
if host.is_unspecified or host.is_multicast or host.is_loopback:
|
||||
raise ValueError('driver discovery needs a local non-loopback unicast host IP')
|
||||
socket.if_nametoindex(interface)
|
||||
executable = os.path.join(get_package_prefix('br_vehicle_mission'),
|
||||
'lib', 'br_vehicle_mission', 'discover_mid360.py')
|
||||
sender = ExecuteProcess(cmd=[executable, '--interface', interface, '--host-ip', str(host)],
|
||||
name='mid360_interface_discovery', output='screen')
|
||||
|
||||
def check_exit(event, context):
|
||||
if event.returncode != 0:
|
||||
return [EmitEvent(event=Shutdown(reason='explicit MID360 interface discovery failed'))]
|
||||
return []
|
||||
|
||||
return [RegisterEventHandler(OnProcessExit(target_action=sender, on_exit=check_exit)),
|
||||
TimerAction(period=2., actions=[sender])]
|
||||
@@ -18,6 +18,7 @@ from nav_msgs.msg import Odometry
|
||||
from sensor_msgs.msg import PointCloud2,PointField
|
||||
from std_msgs.msg import String
|
||||
from br_vehicle_mission.lio_navigation_adapter import quaternion,rotation
|
||||
from br_vehicle_mission.livox_scan import read_scan
|
||||
|
||||
|
||||
class PoseGapError(ValueError):
|
||||
@@ -125,7 +126,7 @@ class DualLidarFusion(Node):
|
||||
# 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_subscription(CustomMsg,topic,lambda msg,i=i:self.on_scan(i,msg),qos_profile_sensor_data,raw=True)
|
||||
self.create_timer(.02,self.flush);self.create_timer(.5,self.report)
|
||||
|
||||
def now_s(self):return self.get_clock().now().nanoseconds*1e-9
|
||||
@@ -153,12 +154,14 @@ class DualLidarFusion(Node):
|
||||
|
||||
def on_scan(self,i,m):
|
||||
if self.fault:return
|
||||
try:m=read_scan(m)
|
||||
except ValueError as error:self.fault=str(error);return
|
||||
t=int(m.timebase)
|
||||
if m.header.frame_id!=self.raw_frames[i] or m.point_num!=len(m.points) or (self.raw_ids[i]>=0 and m.lidar_id!=self.raw_ids[i]):
|
||||
if m.frame!=self.raw_frames[i] or (self.raw_ids[i]>=0 and m.lidar_id!=self.raw_ids[i]):
|
||||
self.fault='unexpected raw lidar identity/count';return
|
||||
if not m.points:
|
||||
if not m.point_num:
|
||||
self.fault='empty raw lidar scan';return
|
||||
if t!=m.header.stamp.sec*1000000000+m.header.stamp.nanosec:
|
||||
if t!=m.stamp_ns:
|
||||
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
|
||||
@@ -175,7 +178,7 @@ class DualLidarFusion(Node):
|
||||
first=min(int(a.timebase),int(b.timebase))*1e-9
|
||||
# Real driver can publish 20 Hz (or other supported batching).
|
||||
# End time comes from acquired points, never an assumed 99 ms.
|
||||
end_ns=max(int(m.timebase)+max(int(p.offset_time) for p in m.points) for m in (a,b))
|
||||
end_ns=max(int(m.timebase)+int(m.offsets.max()) for m in (a,b))
|
||||
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
|
||||
@@ -184,9 +187,7 @@ class DualLidarFusion(Node):
|
||||
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,self.self_min,self.self_max))
|
||||
bundles.append(project_scan(m.xyz,m.offsets,int(m.timebase),self.history,self.mounts[i],self.rotations[i],i==1,self.self_min,self.self_max))
|
||||
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)])
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Read the installed Livox CustomMsg CDR1 layout without per-point objects.
|
||||
|
||||
Views retain their input buffer. No coordinates, timestamps or offsets change.
|
||||
Unsupported encodings and inconsistent lengths fail closed.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
import struct
|
||||
import numpy as np
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LivoxScan:
|
||||
frame: str
|
||||
stamp_ns: int
|
||||
timebase: int
|
||||
lidar_id: int
|
||||
xyz: np.ndarray
|
||||
offsets: np.ndarray
|
||||
|
||||
@property
|
||||
def point_num(self):
|
||||
return len(self.offsets)
|
||||
|
||||
|
||||
def read_scan(message):
|
||||
"""Accept raw ROS bytes, or message objects for direct callers/replay tests."""
|
||||
if isinstance(message, LivoxScan):
|
||||
return message
|
||||
if not isinstance(message, (bytes, bytearray, memoryview)):
|
||||
m = message
|
||||
if m.point_num != len(m.points):
|
||||
raise ValueError('raw lidar point count mismatch')
|
||||
return LivoxScan(m.header.frame_id,
|
||||
m.header.stamp.sec * 1000000000 + m.header.stamp.nanosec,
|
||||
int(m.timebase), int(m.lidar_id),
|
||||
np.array([(p.x, p.y, p.z) for p in m.points], dtype=float).reshape(-1, 3),
|
||||
np.array([p.offset_time for p in m.points], dtype=np.int64))
|
||||
raw = message
|
||||
try:
|
||||
if bytes(raw[:4]) != b'\x00\x01\x00\x00':
|
||||
raise ValueError('unsupported Livox serialization; require little-endian CDR1')
|
||||
sec, nsec, frame_len = struct.unpack_from('<iII', raw, 4)
|
||||
if not 0 <= nsec < 1000000000 or not 1 <= frame_len <= len(raw) - 16:
|
||||
raise ValueError('invalid raw lidar header')
|
||||
frame_bytes = bytes(raw[16:16 + frame_len])
|
||||
if frame_bytes[-1] != 0 or b'\0' in frame_bytes[:-1]:
|
||||
raise ValueError('invalid raw lidar frame string')
|
||||
frame = frame_bytes[:-1].decode('utf-8')
|
||||
# CDR alignment starts after the four-byte encapsulation header.
|
||||
pos = 4 + ((12 + frame_len + 7) // 8) * 8
|
||||
base, declared_count, lidar_id = struct.unpack_from('<QIB', raw, pos)
|
||||
count = struct.unpack_from('<I', raw, pos + 16)[0]
|
||||
pos += 20
|
||||
# CustomPoint: uint32 offset, 3 float32 XYZ, 3 uint8 attributes.
|
||||
# The next point is aligned to four bytes; the last needs no padding.
|
||||
end = pos + (count * 20 - 1 if count else 0)
|
||||
if count != declared_count or not end <= len(raw) <= (end + 3) // 4 * 4:
|
||||
raise ValueError('raw lidar count/serialized length mismatch')
|
||||
if count:
|
||||
offsets = np.ndarray((count,), '<u4', raw, pos, (20,))
|
||||
xyz = np.ndarray((count, 3), '<f4', raw, pos + 4, (20, 4))
|
||||
else:
|
||||
offsets = np.empty(0, dtype=np.uint32)
|
||||
xyz = np.empty((0, 3), dtype=np.float32)
|
||||
return LivoxScan(frame, sec * 1000000000 + nsec, base, lidar_id, xyz, offsets)
|
||||
except (struct.error, UnicodeError, TypeError, BufferError, OverflowError) as exc:
|
||||
raise ValueError('malformed raw lidar serialization') from exc
|
||||
@@ -17,6 +17,7 @@ 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 br_vehicle_mission.livox_scan import read_scan
|
||||
from br_vehicle_mission.lio_navigation_adapter import quaternion,rotation,float_fields
|
||||
|
||||
|
||||
@@ -117,7 +118,7 @@ class RampMission(Node):
|
||||
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(CustomMsg,'/sim/mid360_low/lidar',self.on_lower,qos_profile_sensor_data,raw=True)
|
||||
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))
|
||||
@@ -169,9 +170,11 @@ class RampMission(Node):
|
||||
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!=self.lower_frame or (self.lower_raw_id>=0 and m.lidar_id!=self.lower_raw_id) or not m.points or m.point_num!=len(m.points) or int(m.timebase)!=m.header.stamp.sec*1000000000+m.header.stamp.nanosec:
|
||||
try:m=read_scan(m)
|
||||
except ValueError:self.fail('invalid_lower_scan');return
|
||||
if m.frame!=self.lower_frame or (self.lower_raw_id>=0 and m.lidar_id!=self.lower_raw_id) or not m.point_num or int(m.timebase)!=m.stamp_ns:
|
||||
self.fail('invalid_lower_scan');return
|
||||
offset=max(p.offset_time for p in m.points)
|
||||
offset=int(m.offsets.max())
|
||||
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):
|
||||
|
||||
@@ -5,15 +5,21 @@ from launch.substitutions import LaunchConfiguration
|
||||
from launch_ros.actions import ComposableNodeContainer
|
||||
from launch_ros.descriptions import ComposableNode
|
||||
from br_vehicle_mission.deployment import load_driver
|
||||
from br_vehicle_mission.driver_discovery import discovery_actions
|
||||
|
||||
|
||||
def start_driver(context):
|
||||
params=load_driver(LaunchConfiguration('driver_params_file').perform(context))
|
||||
extra = discovery_actions(LaunchConfiguration('driver_discovery_interface').perform(context),
|
||||
LaunchConfiguration('driver_discovery_host_ip').perform(context))
|
||||
return [ComposableNodeContainer(name='vehicle_livox_container',namespace='/vehicle_mission',
|
||||
package='rclcpp_components',executable='component_container_mt',output='screen',
|
||||
composable_node_descriptions=[ComposableNode(package='livox_ros_driver2',plugin='livox_ros::DriverNode',
|
||||
name='livox_driver_node',namespace='/',parameters=[params,{'use_sim_time':False}])])]
|
||||
name='livox_driver_node',namespace='/',parameters=[params,{'use_sim_time':False}])])] + extra
|
||||
|
||||
|
||||
def generate_launch_description():
|
||||
return LaunchDescription([DeclareLaunchArgument('driver_params_file'),OpaqueFunction(function=start_driver)])
|
||||
return LaunchDescription([DeclareLaunchArgument('driver_params_file'),
|
||||
DeclareLaunchArgument('driver_discovery_interface', default_value=''),
|
||||
DeclareLaunchArgument('driver_discovery_host_ip', default_value=''),
|
||||
OpaqueFunction(function=start_driver)])
|
||||
|
||||
@@ -11,6 +11,7 @@ from launch_ros.actions import Node, ComposableNodeContainer
|
||||
from launch_ros.descriptions import ComposableNode
|
||||
from br_vehicle_mission.deployment import load_site, load_driver
|
||||
from br_vehicle_mission.profiles import profile_settings
|
||||
from br_vehicle_mission.driver_discovery import discovery_actions
|
||||
|
||||
|
||||
def build_nodes(context):
|
||||
@@ -124,8 +125,11 @@ def build_nodes(context):
|
||||
'odometry.publish_scan_end':True}],
|
||||
remappings=[('/cloud_registered_full_lidar',ns+'/lio/cloud_registered_full_lidar'),
|
||||
('/cloud_registered_full',ns+'/lio/cloud_registered_full')]))
|
||||
extra_driver_actions = []
|
||||
if boolean('launch_driver'):
|
||||
driver = load_driver(site['driver_params_file'])
|
||||
extra_driver_actions = discovery_actions(value('driver_discovery_interface'),
|
||||
value('driver_discovery_host_ip'))
|
||||
critical.append(ComposableNodeContainer(name='vehicle_livox_container', namespace=ns,
|
||||
package='rclcpp_components', executable='component_container_mt', output='screen',
|
||||
composable_node_descriptions=[ComposableNode(package='livox_ros_driver2',plugin='livox_ros::DriverNode',
|
||||
@@ -135,7 +139,7 @@ def build_nodes(context):
|
||||
name='chassis_serial_node',output='screen',parameters=[chassis,{'use_sim_time':False}]))
|
||||
guards = [RegisterEventHandler(OnProcessExit(target_action=node,
|
||||
on_exit=[EmitEvent(event=Shutdown(reason='critical real mission process exited'))])) for node in critical]
|
||||
return critical+guards
|
||||
return critical+guards+extra_driver_actions
|
||||
|
||||
|
||||
def generate_launch_description():
|
||||
@@ -149,6 +153,8 @@ def generate_launch_description():
|
||||
DeclareLaunchArgument('drive_enabled',default_value='false'),
|
||||
DeclareLaunchArgument('launch_chassis',default_value='false'),
|
||||
DeclareLaunchArgument('launch_driver',default_value='false'),
|
||||
DeclareLaunchArgument('driver_discovery_interface',default_value=''),
|
||||
DeclareLaunchArgument('driver_discovery_host_ip',default_value=''),
|
||||
DeclareLaunchArgument('launch_lio',default_value='true'),
|
||||
OpaqueFunction(function=build_nodes),
|
||||
])
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/python3
|
||||
"""Send only MID360 device-type queries through one explicit Linux interface."""
|
||||
import argparse
|
||||
import binascii
|
||||
import ipaddress
|
||||
import math
|
||||
import socket
|
||||
import struct
|
||||
import time
|
||||
|
||||
|
||||
def discovery_packet(sequence):
|
||||
# SDK2 SdkProtocol: 18-byte preamble, CRC16/CCITT-FALSE, empty payload.
|
||||
header = struct.pack('<BBHIHBB6s', 0xaa, 0, 24, sequence & 0xffff,
|
||||
0x0000, 0, 0, b'\0' * 6)
|
||||
return header + struct.pack('<HI', binascii.crc_hqx(header, 0xffff), 0)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--host-ip', required=True)
|
||||
parser.add_argument('--interface', required=True)
|
||||
parser.add_argument('--count', type=int, default=4)
|
||||
parser.add_argument('--interval', type=float, default=.5)
|
||||
args = parser.parse_args()
|
||||
host = ipaddress.IPv4Address(args.host_ip)
|
||||
if host.is_unspecified or host.is_multicast or host.is_loopback:
|
||||
parser.error('host-ip must be an assigned non-loopback unicast IPv4 address')
|
||||
if not 2 <= args.count <= 20 or not math.isfinite(args.interval) or not .05 <= args.interval <= 2:
|
||||
parser.error('count must be in [2,20], interval in [0.05,2] seconds')
|
||||
interface_index = socket.if_nametoindex(args.interface)
|
||||
# Linux IP_PKTINFO selects the egress independently of the address owner.
|
||||
pktinfo = struct.pack('I4s4s', interface_index, host.packed, b'\0' * 4)
|
||||
sequence = time.monotonic_ns() & 0xffff
|
||||
for attempt in range(args.count):
|
||||
packet = discovery_packet(sequence + attempt)
|
||||
# Close immediately after send: do not retain a second SDK receive socket.
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender:
|
||||
sender.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sender.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
sender.bind((str(host), 56000))
|
||||
sent = sender.sendmsg([packet], [(socket.IPPROTO_IP, 8, pktinfo)], 0,
|
||||
('255.255.255.255', 56000))
|
||||
if sent != len(packet):
|
||||
raise RuntimeError('incomplete MID360 device-type query send')
|
||||
print(f'MID360 device-type query {attempt+1}/{args.count}: '
|
||||
f'{host} via {args.interface}, {sent} bytes', flush=True)
|
||||
if attempt + 1 < args.count:
|
||||
time.sleep(args.interval)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -11,6 +11,8 @@ from rclpy.node import Node
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
from livox_ros_driver2.msg import CustomMsg
|
||||
from sensor_msgs.msg import Imu
|
||||
import numpy as np
|
||||
from br_vehicle_mission.livox_scan import read_scan
|
||||
|
||||
|
||||
def main():
|
||||
@@ -25,28 +27,33 @@ def main():
|
||||
rclpy.init();node=Node('vehicle_sensor_probe')
|
||||
rows={'upper':[],'lower':[],'imu':[]};errors=[];last={}
|
||||
def record(kind,msg):
|
||||
t=msg.header.stamp.sec*1000000000+msg.header.stamp.nanosec
|
||||
now=node.get_clock().now().nanoseconds
|
||||
if kind!='imu':
|
||||
try:msg=read_scan(msg)
|
||||
except ValueError as exc:errors.append(kind+': '+str(exc));return
|
||||
t=msg.stamp_ns;frame=msg.frame
|
||||
else:
|
||||
t=msg.header.stamp.sec*1000000000+msg.header.stamp.nanosec;frame=msg.header.frame_id
|
||||
if kind in last and t<=last[kind]:errors.append(kind+': nonmonotonic source stamp')
|
||||
last[kind]=t
|
||||
row=dict(stamp_ns=t,age_s=(now-t)*1e-9,frame=msg.header.frame_id)
|
||||
row=dict(stamp_ns=t,age_s=(now-t)*1e-9,frame=frame)
|
||||
if kind!='imu':
|
||||
offsets=[int(p.offset_time) for p in msg.points]
|
||||
if not offsets or msg.point_num!=len(offsets) or int(msg.timebase)!=t:
|
||||
offsets=msg.offsets;maximum=int(offsets.max()) if len(offsets) else 0
|
||||
if not len(offsets) or int(msg.timebase)!=t:
|
||||
errors.append(kind+': count/timebase/header mismatch')
|
||||
if offsets and (max(offsets)>=100000000 or any(a>b for a,b in zip(offsets,offsets[1:]))):
|
||||
if len(offsets) and (maximum>=100000000 or np.any(offsets[1:]<offsets[:-1])):
|
||||
errors.append(kind+': incompatible acquisition offsets')
|
||||
row.update(lidar_id=msg.lidar_id,point_count=msg.point_num,
|
||||
duration_s=max(offsets,default=0)*1e-9,
|
||||
end_age_s=(now-t-max(offsets,default=0))*1e-9)
|
||||
duration_s=maximum*1e-9,
|
||||
end_age_s=(now-t-maximum)*1e-9)
|
||||
else:
|
||||
a=msg.linear_acceleration;g=msg.angular_velocity
|
||||
values=(a.x,a.y,a.z,g.x,g.y,g.z)
|
||||
if not all(math.isfinite(v) for v in values):errors.append('imu: nonfinite sample')
|
||||
row.update(acc_norm=math.sqrt(a.x*a.x+a.y*a.y+a.z*a.z),gyro_norm=math.sqrt(g.x*g.x+g.y*g.y+g.z*g.z))
|
||||
rows[kind].append(row)
|
||||
node.create_subscription(CustomMsg,args.upper,lambda m:record('upper',m),qos_profile_sensor_data)
|
||||
node.create_subscription(CustomMsg,args.lower,lambda m:record('lower',m),qos_profile_sensor_data)
|
||||
node.create_subscription(CustomMsg,args.upper,lambda m:record('upper',m),qos_profile_sensor_data,raw=True)
|
||||
node.create_subscription(CustomMsg,args.lower,lambda m:record('lower',m),qos_profile_sensor_data,raw=True)
|
||||
node.create_subscription(Imu,args.imu,lambda m:record('imu',m),qos_profile_sensor_data)
|
||||
try:
|
||||
end=time.monotonic()+args.duration
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Check the raw reader against the installed ROS serializer and reject corruption."""
|
||||
import gc
|
||||
import struct
|
||||
import unittest
|
||||
import numpy as np
|
||||
from rclpy.serialization import serialize_message
|
||||
from livox_ros_driver2.msg import CustomMsg, CustomPoint
|
||||
from br_vehicle_mission.livox_scan import read_scan
|
||||
|
||||
|
||||
class LivoxSerializationTests(unittest.TestCase):
|
||||
def message(self, frame='livox_frame', count=3):
|
||||
m = CustomMsg()
|
||||
m.header.frame_id = frame
|
||||
m.header.stamp.sec = 1795070800
|
||||
m.header.stamp.nanosec = 123456789
|
||||
m.timebase = 1795070800123456789
|
||||
m.lidar_id = 192
|
||||
m.rsvd = [1, 2, 3]
|
||||
for i in range(count):
|
||||
p = CustomPoint()
|
||||
p.offset_time = i * 12345678
|
||||
p.x, p.y, p.z = 2.5 + i, -3.25 - i, .125 * i
|
||||
p.reflectivity, p.tag, p.line = 10 + i, 20 + i, i
|
||||
m.points.append(p)
|
||||
m.point_num = count
|
||||
return m
|
||||
|
||||
def test_installed_serializer_matches_coordinates_identity_and_source_times(self):
|
||||
for frame in ('', 'x', 'abcd', 'livox_frame', 'abcdefghijklmnop', '雷达'):
|
||||
for count in (0, 1, 3):
|
||||
with self.subTest(frame=frame, count=count):
|
||||
m = self.message(frame, count)
|
||||
raw = serialize_message(m)
|
||||
scan = read_scan(raw)
|
||||
del raw
|
||||
gc.collect()
|
||||
expected = read_scan(m)
|
||||
self.assertEqual((scan.frame, scan.stamp_ns, scan.timebase, scan.lidar_id, scan.point_num),
|
||||
(frame, expected.stamp_ns, expected.timebase, 192, count))
|
||||
np.testing.assert_array_equal(scan.xyz, expected.xyz)
|
||||
np.testing.assert_array_equal(scan.offsets, expected.offsets)
|
||||
|
||||
def test_truncation_encoding_header_and_counts_fail_closed(self):
|
||||
raw = serialize_message(self.message())
|
||||
for length in (0, 3, 10, 16, 30, len(raw)-1):
|
||||
with self.subTest(length=length), self.assertRaises(ValueError):
|
||||
read_scan(raw[:length])
|
||||
for offset, replacement in ((1, b'\x00'), (8, struct.pack('<I', 1000000000)),
|
||||
(12, struct.pack('<I', 0xffffffff)),
|
||||
(16, b'\xff'), (27, b'x'),
|
||||
(36, struct.pack('<I', 2)),
|
||||
(44, struct.pack('<I', 0xffffffff))):
|
||||
bad = bytearray(raw)
|
||||
bad[offset:offset+len(replacement)] = replacement
|
||||
with self.subTest(offset=offset), self.assertRaises(ValueError):
|
||||
read_scan(bad)
|
||||
with self.assertRaises(ValueError):
|
||||
read_scan(raw+b'extra bytes')
|
||||
m = self.message()
|
||||
m.point_num += 1
|
||||
with self.assertRaises(ValueError):
|
||||
read_scan(m)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -9,6 +9,7 @@ import numpy as np
|
||||
import yaml
|
||||
import rclpy
|
||||
from rclpy.parameter import Parameter
|
||||
from rclpy.serialization import serialize_message
|
||||
from br_vehicle_mission.deployment import load_site, load_driver
|
||||
from br_vehicle_mission.ramp_mission import RampMission, envelope, speed_target
|
||||
from br_vehicle_mission.dual_lidar_fusion import DualLidarFusion
|
||||
@@ -117,12 +118,33 @@ class RuntimeTests(unittest.TestCase):
|
||||
self.assertEqual(n.full.messages[0].header.stamp.nanosec,49000000)
|
||||
self.assertAlmostEqual(n.last_output,1.049)
|
||||
finally:n.destroy_node()
|
||||
def test_serialized_fusion_preserves_projected_points_origins_and_acquisition_times(self):
|
||||
class Capture:
|
||||
def __init__(self):self.messages=[]
|
||||
def publish(self,m):self.messages.append(m)
|
||||
outputs=[]
|
||||
for serialized in (False,True):
|
||||
n=DualLidarFusion()
|
||||
try:
|
||||
n.now_s=lambda:1.06;n.full=Capture();n.planning=Capture()
|
||||
n.history.extend((1.+k*.01,np.array([k*.001,0.,.15]),np.array([0.,0.,0.,1.])) for k in range(7))
|
||||
for i in (0,1):
|
||||
m=CustomMsg();m.header.frame_id=('lidar','lidar_low')[i];m.header.stamp.sec=1;m.timebase=1000000000;m.lidar_id=i
|
||||
for j in range(3):
|
||||
p=CustomPoint();p.x=2.+j;p.y=-1.-j;p.z=.1*j;p.offset_time=j*24500000;m.points.append(p)
|
||||
m.point_num=3;n.on_scan(i,serialize_message(m) if serialized else m)
|
||||
n.flush();self.assertFalse(n.fault);self.assertEqual(len(n.full.messages),1)
|
||||
outputs.append((n.full.messages[0],n.planning.messages[0]))
|
||||
finally:n.destroy_node()
|
||||
self.assertEqual(outputs[0],outputs[1])
|
||||
def test_raw_lower_watchdog_accepts_explicit_real_frame_without_relabelling(self):
|
||||
n=RampMission(parameter_overrides=[Parameter('lower_raw_frame',value='livox_frame'),Parameter('lower_raw_id',value=-1)])
|
||||
try:
|
||||
m=CustomMsg();m.header.frame_id='livox_frame';m.header.stamp.sec=1;m.timebase=1000000000;m.lidar_id=111
|
||||
p=CustomPoint();p.offset_time=49000000;m.points=[p];m.point_num=1
|
||||
n.on_lower(m);self.assertAlmostEqual(n.pending_lower[0],1.049);self.assertEqual(m.lidar_id,111)
|
||||
n.on_lower(m);n.on_lower(serialize_message(m))
|
||||
self.assertEqual(len(n.pending_lower),2)
|
||||
self.assertTrue(all(abs(t-1.049)<1e-12 for t in n.pending_lower));self.assertEqual(m.lidar_id,111)
|
||||
self.assertEqual(m.header.frame_id,'livox_frame')
|
||||
finally:n.destroy_node()
|
||||
def test_second_output_publisher_latches_mux_stop(self):
|
||||
|
||||
Reference in New Issue
Block a user