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

提取共用任务、双雷达融合与定位适配,新增红蓝方实车入口、预览模式、硬件限速和双 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
+13 -2
View File
@@ -38,7 +38,17 @@ ros2 launch br_sim_bringup ramp_mission.launch.py autostart:=true
ros2 launch br_sim_bringup ramp_mission.launch.py profile:=fast autostart:=true
```
本轮带 Gazebo/RViz 的理想、轻度噪声路线分别为 19.42/19.46 秒仿真时间,含全车上平台和停稳确认。
2026-11-12 带 Gazebo/RViz 的理想、轻度噪声路线分别为 19.42/19.46 秒仿真时间,含全车上平台和停稳确认。
标准/快模式也支持 `side:=blue`,起点及航点沿世界 Y 镜像,起点车头仍朝 +X:
```bash
ros2 launch br_sim_bringup ramp_mission.launch.py side:=blue profile:=fast autostart:=true
```
任务与感知实现现共用 `minco_ws/src/scan/br_vehicle_mission`;本包原脚本保留兼容入口。
修改后先运行 `bash sim_ws/tools/build_sim.sh` 更新依赖,再加载环境。
实车使用独立入口和系统时间,不能把本页仿真 launch 直接接串口;见 [实车接入指南](../minco_ws/docs/RAMP_VEHICLE.md)。
## 先看懂功能包与文件归属
@@ -51,13 +61,14 @@ ros2 launch br_sim_bringup ramp_mission.launch.py profile:=fast autostart:=true
| 1 场地 | `robocon_gazebo robocon_gazebo.launch.py` | 系统包 `gazebo_ros` 的 `gzserver.launch.py`;开启窗口时还有 `gzclient.launch.py` | `sim_ws/src/robocon_gazebo/` |
| 2 机器人 | `r2027_robot_description robocon_robot.launch.py` | 本包的 `spawn_existing_world.py` 生成实体、`cmd_vel_timeout.py` 保护停车,另有 TF 节点;底盘插件由 Gazebo 加载 | `sim_ws/src/r2027_robot_description/` |
| 3 传感器 | `r2027_robot_description mid360_sensors.launch.py` | 本包的 `mid360_control.py` 启用并维持机器人上的 MID360、IMU 插件采样 | `sim_ws/src/r2027_robot_description/` |
| 4 导航 | `br_sim_bringup scan_lio_navigation.launch.py` | `point_lio` 的 `pointlio_mapping`、本包的 `lio_navigation_adapter.py`、`scan_planner` 的 `scan_planner_node` 和 `closed_loop_controller` | 入口和适配器在 `sim_ws/src/br_sim_bringup/`;算法在 `minco_ws/src/` |
| 4 导航 | `br_sim_bringup scan_lio_navigation.launch.py` | `point_lio` 的 `pointlio_mapping`、兼容入口 `lio_navigation_adapter.py`、`scan_planner` 的 `scan_planner_node` 和 `closed_loop_controller` | 仿真入口在 `sim_ws/src/br_sim_bringup/`;适配与任务共用实现、算法在 `minco_ws/src/` |
| 5 显示 | `br_sim_bringup rviz.launch.py` | 系统包 `rviz2` 的 `rviz2`,载入本工程的显示配置 | launch 和配置在 `sim_ws/src/br_sim_bringup/` |
模型和传感器代码的位置:
- **场地模型**:默认场景是 [`src/robocon_gazebo/worlds/robocon_robot.world`](src/robocon_gazebo/worlds/robocon_robot.world),引用 [`src/robocon_gazebo/models/robocon_ground_full/model.sdf`](src/robocon_gazebo/models/robocon_ground_full/model.sdf);网格在同一模型目录的 `meshes/`。
Gazebo 默认视角从红方(世界坐标 +Y)外侧上方俯看红方半场,可用鼠标自由调整;重启场景恢复默认视角。
默认场景已提高环境光与主光照亮度、降低镜面反光,关闭阴影(`shadows=false`);这些显示设置位于上述 world 文件中,修改后重启场景生效。
- **机器人模型**:外形、底盘、传感器安装位置和插件声明在 [`src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro`](src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro)。机器人入口展开该文件,再向已运行的 Gazebo 生成实体。
- **传感器仿真**:MID360 与 IMU 插件源码分别是 [`mid360_sensor.cpp`](src/r2027_robot_description/src/mid360_sensor.cpp) 和 [`mid360_imu.cpp`](src/r2027_robot_description/src/mid360_imu.cpp),噪声档位在 [`sensor_profiles.yaml`](src/r2027_robot_description/config/sensor_profiles.yaml)。插件随机器人实体装入 Gazebo,初始不采样;第三个入口负责启用和维持采样。`minco_ws/src/perception/livox_ros_driver2/` 提供点云使用的 Livox 消息类型,并非这里的传感器仿真程序。
- **定位与规划**:Point-LIO 源码在 `minco_ws/src/perception/Point-LIO/`;SCAN 规划器、控制器及其依赖在 `minco_ws/src/scan/`。本仿真的算法参数在 `src/br_sim_bringup/config/`,RViz 配置在 [`src/br_sim_bringup/rviz/scan_lio.rviz`](src/br_sim_bringup/rviz/scan_lio.rviz)。
+19 -1
View File
@@ -1,4 +1,22 @@
# 当前交接(分段上坡更新:2026-11-12)
# 当前交接(实车迁移:2026-11-16)
用户确认实际场地与当前地图一致,车体及安装采用仿真现值(80×80×41 cm);
蓝方只镜像世界 Y,起点为 (−4.5,−4.5,0.15,0)。第二颗雷达尚未配置,高速和刹停能力尚未实测。
新增 `minco_ws/src/scan/br_vehicle_mission`:原四个仿真脚本成为兼容入口,
真正的任务、仲裁、融合、LIO 适配统一在该包 Python 模块中,禁止再维护第二份实现。
`profiles.py` 共用算法参数;实车入口单独使用系统时间、设备话题和串口限速。
原实车 `vehicle_bringup`/`run_vehicle` 不自动切换;新入口默认只发布预览速度,不打开串口。
真实 Livox handle/frame 可显式配置,融合源结束时刻改为实际末点 offset,不再假定 99 ms。
新配置生成器不访问硬件,时钟同步和 IMU 单位缺口保持未确认;配置未填齐时禁止运行任务。
操作、构建及实车验收边界见 [实车指南](../../minco_ws/docs/RAMP_VEHICLE.md),
本轮离线启动与红蓝四条完整仿真路线见 [迁移验收](validation/20261116_vehicle_migration.json)。
独立实车前缀 12 包从零构建、87 项单元测试、两模式实车离线预览(含 Point-LIO 和正常退出)通过。
最终红/蓝标准为 49.01/49.42 s,红/蓝快模式为 19.24/19.46 s(均无界面);蓝方坡上断流诊断 0.486 s 停稳。
修复了 Point-LIO 自定义 SIGINT 导致 executor 不退出、任务在 context 关闭后发布的问题;
串口桥正常销毁先直接发送零速帧再关闭端口,有模拟串口测试,无真实 STM32 执行证据。
未连接真实雷达或串口,不能把软件测试结论写成实车动态通过;Git 状态以 `git log` / `git status` 为准,push 由用户执行。
## 历史交接:2026-11-12 分段上坡
当前新增独立 `profile:=fast`,默认仍是 `standard`。快模式直道 2.5、坡中 1.1 m/s,
转向 2.0 rad/s;平台低速目标仍为 0.2 m/s,但低速区从标准的 base x=-0.25 后移到 -0.90。
+15 -1
View File
@@ -3,7 +3,9 @@
本入口自动完成:**默认起点 → 北侧通道 → 坡前对准 → 上坡 → 平台停车**。
上坡阶段采用固定中心线、航向和横向闭环,结合姿态变化判断进入坡道与恢复水平;
不使用 SCAN 的上坡轨迹,也不会把“倾角回零”直接当成任务成功。
Point-LIO 定位与双雷达感知全程继续工作。此版本针对当前已知地图的红侧坡道,尚未迁移实车。
Point-LIO 定位与双雷达感知全程继续工作。默认红侧坡道,`side:=blue` 选择沿世界 Y 镜像的蓝方路线。
任务、融合与适配已提取为 `minco_ws/src/scan/br_vehicle_mission` 的共用实现;
独立实车入口、现场配置及验收边界见 [实车指南](../../minco_ws/docs/RAMP_VEHICLE.md),尚未通过实车动态验收。
## 1. 直接运行
@@ -80,6 +82,18 @@ ros2 service call /ramp_mission/cancel std_srvs/srv/Trigger '{}'
重新体验时关闭整个本入口、重新启动,机器人会重新生成在默认起点。
不要拖动车体、重置世界后继续沿用原定位;已知起点对齐只在初始化时锁定一次。
红蓝方切换示例(先关闭上一入口):
```bash
ros2 launch br_sim_bringup ramp_mission.launch.py side:=blue profile:=standard autostart:=true
ros2 launch br_sim_bringup ramp_mission.launch.py side:=blue profile:=fast autostart:=true
```
蓝方默认起点 (−4.5,−4.5,0.15),yaw=0;接近航点 Y 取反,坡前仍朝 −X,
停车参考点为 (−1.30,−3.5125)。传感器外参、速度正方向和世界高度不变。
2026-11-16 共享实现迁移后的红蓝四条完整路线及蓝方断流回归见
[迁移验收记录](validation/20261116_vehicle_migration.json),不覆盖历史测试文件。
## 3. 本地图的坐标与停车条件
长度米、角度弧度,world Z 向上,X 前/Y 左/Z 上为车体坐标。
+11 -5
View File
@@ -439,9 +439,16 @@ ros2 launch scan_planner vehicle_bringup.launch.py \
实际话题以运行图为准:mid360.yaml 中的设备后缀话题会被某些 launch 覆盖,不能只看 YAML 猜最终名称。
IMU 单位和 Point-LIO acc_norm 必须一致;仿真 SI 比力对应的配置不能直接复制给不同单位的真实驱动。
### 9.4 第三步:补齐当前实车适配的已知缺口
### 9.4 第三步:使用共享适配,并核对旧实车入口的缺口
**当前还不能把实车配置换成仿真配置后直接发导航目标。** 源码核对发现以下待完成项:
2026-11-16 已交付独立实车入口 `br_vehicle_mission ramp_vehicle.launch.py`,支持红蓝方标准/快模式。
任务、融合与完整姿态/参考点适配由 `minco_ws/src/scan/br_vehicle_mission` 共用实现,
默认预览、不发布实车 `/cmd_vel`,全部使用系统时间并按串口配置限速。
当前尚缺第二颗雷达现场配置、同步验证和实车动态测试;操作步骤见
[双雷达上坡实车指南](../../minco_ws/docs/RAMP_VEHICLE.md)。
**旧 `vehicle_bringup.launch.py` 不会自动切换到新方案。** 下列是旧链路需要留意的差异,
新入口已使用共享适配处理完整姿态、参考点速度、坐标变换与持续就绪门控:
1. Point-LIO 输出参考点为 IMU,header.frame_id=camera_init、child_frame_id=body。
旧实车文档和 body_odom 注释部分仍写“雷达中心”,外参必须按实际输入参考点重新解释。
@@ -452,8 +459,7 @@ IMU 单位和 Point-LIO acc_norm 必须一致;仿真 SI 比力对应的配置
算法直接读取的点云 XYZ。点云、车体里程计、雷达位姿和目标必须在一致的世界定义下使用。
5. 实车接入必须保留持续感知就绪、消息源时间年龄和失效停车检查。不能为让旧入口启动而关闭这些门控。
仿真适配已处理这些转换中的通用部分,但含固定已知起点和地面模型等假设;后续应提取或配置成
可实车使用的共享适配,经测试后接入,**当前尚未交付一套已经验收的统一实车适配入口**。
新入口仍依赖用户确认的固定起点、安装外参和已知地表模型;代码迁移和离线测试通过不代表实车验收通过。
不要为消除视觉错位而在线吸附真值、重置估计或改点云高度。
### 9.5 第四步:测量尺寸、外参与底盘方向
@@ -506,4 +512,4 @@ Gazebo 留在笔记本、算法放机器人电脑,是跨机仿真联调;真
| [实车入口源码](../../minco_ws/src/scan/plan_manage/launch/vehicle_bringup.launch.py) | 核对真实 launch 参数与覆盖关系 |
| [实车上机旧指南](../../minco_ws/docs/QUICKSTART.md) | 网络和硬件操作参考;参考点等冲突以本指南核对结果及源码为准 |
本次只整理使用与迁移文档,未连接真实硬件、未安装 SDK、未把实车流程标记为通过。
实车流程尚未连接真实硬件验收;新增入口的软件验证不包含 SDK 硬件驱动、串口或实际行驶通过。
@@ -0,0 +1,935 @@
{
"date": "2026-11-16",
"status": "PASS_SCOPED_SOFTWARE",
"git_head_before_changes": "6f1d837b46ed6b8ba9d94721006ff3e9549b3823",
"scope": "Shared real/simulation runtime, isolated system-time entry, headless red/blue simulation regression. No physical-robot acceptance.",
"confirmed_by_user": {
"layout_matches_simulation": true,
"body_size_m": [
0.8,
0.8,
0.41
],
"blue_start_world": [
-4.5,
-4.5,
0.15,
0.0
],
"blue_is_world_y_mirror": true,
"upper_optical_ground_m": [
0.015,
0.0,
0.48
],
"lower_optical_ground_m": [
0.325,
0.0,
0.194
],
"lower_yaw_rad": 1.5707963267948966,
"second_lidar_not_yet_configured": true,
"fast_motion_not_measured": true
},
"build": {
"status": "PASS",
"clean_prefix": "minco_ws/install/mission",
"packages": 12,
"livox_interfaces_only": true,
"hardware_sdk_driver_built": false,
"log": {
"path": "minco_ws/log/vehicle_migration/build_vehicle_interfaces.log",
"sha256": "5631c6d5b251b961e2f8c6f4545c0ce2fdf75da3b0ac152490039fd6f601ad52"
},
"lio_lifecycle_rebuild": {
"path": "minco_ws/log/vehicle_migration/build_lio_shutdown.log",
"sha256": "5df8ad00b474cef15cbad38629481c2e2a843d6877496622ffb97ecf71755535"
},
"sim_lio_lifecycle_rebuild": {
"path": "minco_ws/log/vehicle_migration/build_sim_lio_shutdown.log",
"sha256": "cbbf3e6d142ac8c54dce1c5d568681f20b8d200548a8ec8d99fb6742b9315b55"
}
},
"units": {
"status": "PASS",
"unique_tests": 87,
"suites": {
"deployment_and_real_messages": {
"path": "minco_ws/log/vehicle_migration/vehicle_units_final.log",
"sha256": "bf54628751fdbc1a18c53fc4505ae7bac941b2b7c1b9e267ee90a124caf3b230",
"status": "PASS",
"tests": 11
},
"mission_and_mux": {
"path": "minco_ws/log/vehicle_migration/ramp_units_final.log",
"sha256": "f698a009822f21caf16490ab96b550f2feabbe063acd51fb5323e360cecbe04a",
"status": "PASS",
"tests": 28
},
"full_pose_adapter": {
"path": "minco_ws/log/vehicle_migration/adapter_units.log",
"sha256": "d69c5dbedf4152f4b27dc5e467220ad11bc51e22ef73b86f8b9b7c8432569567",
"status": "PASS",
"tests": 19
},
"dual_fusion": {
"path": "minco_ws/log/vehicle_migration/fusion_units.log",
"sha256": "a8fec39f338892bc828cd9939da776296a10058f726b186db4e3aa7ecf79a476",
"status": "PASS",
"tests": 18
},
"known_terrain": {
"path": "minco_ws/log/vehicle_migration/terrain_units.log",
"sha256": "49857a9209777defc498d42043d91f67fcae1dc9cd4c78fdd165565cc0240eea",
"status": "PASS",
"tests": 7
},
"mock_serial_stop": {
"path": "minco_ws/log/vehicle_migration/chassis_stop_units.log",
"sha256": "ff31cc8ab1b3642c5bb8d2f59fa7270fa458e9dcfe730a293a92f499410bed20",
"status": "PASS",
"tests": 4
}
},
"colcon_note": "colcon reports 12 including the CTest wrapper; deployment suite has 11 unique Python tests",
"colcon_result": {
"path": "minco_ws/log/vehicle_migration/colcon_vehicle_results.txt",
"sha256": "58c6dee09452e642c94662b29772d89881f770a8b9b96df3df216c62a82d7fd2"
}
},
"real_entry_offline": {
"status": "PASS",
"report": {
"path": "minco_ws/log/vehicle_migration/launch_final/result.json",
"sha256": "edc6c0bc81e18f65b55696c1d6dab081ccbd5c4f58e50a73b5d21312b590c5ce"
},
"cases": {
"standard": {
"status": "PASS",
"checks": {
"nodes_started": true,
"no_simulation_topics": true,
"no_live_cmd_vel_publisher": true,
"one_preview_owner": true,
"no_serial_or_driver": true,
"zero_with_missing_sensors": true,
"waiting_without_perception": true,
"selected_side": true,
"upper_only_estimator": true,
"all_system_time": true,
"hardware_limits_applied": true,
"clean_shutdown": true
},
"parameters": {
"scan_planner_node": {
"use_sim_time": false,
"manager.max_vel": 0.5,
"grid_map.footprint_length": 0.8,
"fsm.require_perception_ready": true
},
"closed_loop_controller": {
"use_sim_time": false,
"max_vx": 0.5,
"max_vy": 0.5,
"max_vyaw": 0.5
},
"ramp_mission": {
"use_sim_time": false,
"profile": "standard",
"side": "red",
"ramp_speed": 0.5,
"ramp_acceleration": 0.4
},
"mission_command_mux": {
"use_sim_time": false,
"max_linear": 0.5,
"max_yaw": 0.5,
"exclusive_output": true
}
},
"command_count": 89,
"side": "red",
"nodes": [
[
"vehicle_launch_contract_probe",
"/"
],
[
"lio_navigation_adapter",
"/vehicle_mission"
],
[
"dual_lidar_fusion",
"/vehicle_mission"
],
[
"step_blocker",
"/vehicle_mission"
],
[
"scan_planner_node",
"/vehicle_mission"
],
[
"closed_loop_controller",
"/vehicle_mission"
],
[
"ramp_mission",
"/vehicle_mission"
],
[
"mission_command_mux",
"/vehicle_mission"
],
[
"point_lio_vehicle",
"/vehicle_mission/lio"
]
]
},
"fast": {
"status": "PASS",
"checks": {
"nodes_started": true,
"no_simulation_topics": true,
"no_live_cmd_vel_publisher": true,
"one_preview_owner": true,
"no_serial_or_driver": true,
"zero_with_missing_sensors": true,
"waiting_without_perception": true,
"selected_side": true,
"upper_only_estimator": true,
"all_system_time": true,
"hardware_limits_applied": true,
"clean_shutdown": true
},
"parameters": {
"scan_planner_node": {
"use_sim_time": false,
"manager.max_vel": 0.5,
"grid_map.footprint_length": 0.8,
"fsm.require_perception_ready": true
},
"closed_loop_controller": {
"use_sim_time": false,
"max_vx": 0.5,
"max_vy": 0.5,
"max_vyaw": 0.5
},
"ramp_mission": {
"use_sim_time": false,
"profile": "fast",
"side": "blue",
"ramp_speed": 0.5,
"ramp_acceleration": 0.4
},
"mission_command_mux": {
"use_sim_time": false,
"max_linear": 0.5,
"max_yaw": 0.5,
"exclusive_output": true
}
},
"command_count": 86,
"side": "blue",
"nodes": [
[
"vehicle_launch_contract_probe",
"/"
],
[
"lio_navigation_adapter",
"/vehicle_mission"
],
[
"dual_lidar_fusion",
"/vehicle_mission"
],
[
"step_blocker",
"/vehicle_mission"
],
[
"scan_planner_node",
"/vehicle_mission"
],
[
"closed_loop_controller",
"/vehicle_mission"
],
[
"ramp_mission",
"/vehicle_mission"
],
[
"mission_command_mux",
"/vehicle_mission"
],
[
"point_lio_vehicle",
"/vehicle_mission/lio"
]
]
}
},
"runtime_prefixes": {
"br_vehicle_mission": "/home/kevin/RC2027_BR_code/minco_ws/install/mission/br_vehicle_mission",
"scan_planner": "/home/kevin/RC2027_BR_code/minco_ws/install/mission/scan_planner",
"point_lio": "/home/kevin/RC2027_BR_code/minco_ws/install/mission/point_lio",
"livox_ros_driver2": "/home/kevin/RC2027_BR_code/minco_ws/install/mission/livox_ros_driver2"
},
"note": "Synthetic site contract; real Point-LIO starts without sensor input; no driver, serial, /cmd_vel publisher or /clock. Both profiles respect 0.5 m/s and 0.5 rad/s caps; clean shutdown checked."
},
"simulation": {
"status": "PASS",
"cases": {
"standard_red": {
"path": "sim_ws/log/vehicle_migration_20261116/final_standard_red/result.json",
"sha256": "1901ac2f6a777dc3f528fabd104483af4b5b1b4a7971f704c07d597952102777",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"scan_end_odometry_enabled": true,
"critical_cloud_qos_reliable": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"mission_succeeded": true,
"straight_without_intermediate_stop": true,
"requested_straight_speed_reached": true,
"requested_uphill_speed_reached": true,
"requested_turn_speed_reached": true,
"crest_speed_respected": true,
"north_corridor_clearance": true,
"no_wall_contacts": true,
"all_phases": true,
"started_at_default": true,
"final_whole_body_on_platform": true,
"platform_height": true,
"full_ramp_clearance": true,
"ramp_lateral_error": true,
"actual_ramp_contacts": true,
"contact_penetration": true
},
"profile": "standard",
"side": "red",
"task_duration_sim_s": 49.010000000000005,
"gui": false,
"with_rviz": false,
"aligned_start": false,
"ramp_clearance_m": 0.07020501637717347,
"teardown": {
"known_pids": [
31387,
31405,
31407,
31409,
31411,
31413,
31415,
31417,
31419,
31421,
31423,
31425,
31427,
31429,
31431,
31433,
31435
],
"sigterm": [
31387,
31405,
31409,
31411,
31413,
31415,
31417,
31419,
31421,
31423,
31425,
31427,
31429,
31431,
31433,
31435
],
"sigkill": [
31405
],
"port_free": true,
"seconds": 8.16,
"never_touched_unknown_pid": true
},
"maximum_ramp_lateral_error_m": 0.013276266616681909,
"stop_latency_s": null,
"final": {
"stamp": 52.79,
"pos": [
-1.3451225468754497,
3.4992237338550076,
0.7489874383468182
],
"yaw": -3.131503385194633,
"rpy": [
-3.631862799334387e-08,
1.9472308422249026e-14,
-3.131503385194633
],
"quaternion": [
9.159697182103916e-11,
-1.8159082984131474e-08,
0.9999872758598903,
-0.005044612801351136
],
"twist_world": [
2.6218800085957745e-13,
-1.2897895808614213e-11,
5.284969263185923e-05
],
"wz": 4.880919355875033e-19
}
},
"fast_red": {
"path": "sim_ws/log/vehicle_migration_20261116/final_fast_red/result.json",
"sha256": "3cdc78c7621f7559c7357ff34f506049d9a792eb38bb1860af31e2f6fb0a5ca7",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"scan_end_odometry_enabled": true,
"critical_cloud_qos_reliable": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"within_20_seconds": true,
"mission_succeeded": true,
"straight_without_intermediate_stop": true,
"requested_straight_speed_reached": true,
"requested_uphill_speed_reached": true,
"requested_turn_speed_reached": true,
"crest_speed_respected": true,
"north_corridor_clearance": true,
"no_wall_contacts": true,
"all_phases": true,
"started_at_default": true,
"final_whole_body_on_platform": true,
"platform_height": true,
"full_ramp_clearance": true,
"ramp_lateral_error": true,
"actual_ramp_contacts": true,
"contact_penetration": true
},
"profile": "fast",
"side": "red",
"task_duration_sim_s": 19.240000000000002,
"gui": false,
"with_rviz": false,
"aligned_start": false,
"ramp_clearance_m": 0.07917418744098681,
"teardown": {
"known_pids": [
32585,
32604,
32606,
32608,
32610,
32612,
32614,
32616,
32618,
32620,
32622,
32624,
32626,
32628,
32630,
32632,
32636
],
"sigterm": [
32585,
32604,
32608,
32610,
32612,
32614,
32616,
32618,
32620,
32622,
32624,
32626,
32628,
32630,
32632,
32636
],
"sigkill": [
32604
],
"port_free": true,
"seconds": 8.16,
"never_touched_unknown_pid": true
},
"maximum_ramp_lateral_error_m": 0.008090183732430756,
"stop_latency_s": null,
"final": {
"stamp": 24.17,
"pos": [
-1.2923188720656018,
3.507625246699975,
0.7489874383468182
],
"yaw": -3.1392914693053604,
"rpy": [
-3.631862731061725e-08,
1.9840338263796926e-14,
-3.1392914693053604
],
"quaternion": [
-2.0884038827155136e-11,
1.8159301646508846e-08,
-0.9999993380689342,
0.0011505918883455437
],
"twist_world": [
1.786154780957962e-13,
-1.290320066835265e-11,
5.284969252215801e-05
],
"wz": 4.768583714823872e-19
}
},
"standard_blue": {
"path": "sim_ws/log/vehicle_migration_20261116/final_standard_blue/result.json",
"sha256": "727833254481b975cebe5c28c7395f5d0f1478e41ecb4fd3decee98eee04ea99",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"scan_end_odometry_enabled": true,
"critical_cloud_qos_reliable": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"mission_succeeded": true,
"straight_without_intermediate_stop": true,
"requested_straight_speed_reached": true,
"requested_uphill_speed_reached": true,
"requested_turn_speed_reached": true,
"crest_speed_respected": true,
"north_corridor_clearance": true,
"no_wall_contacts": true,
"all_phases": true,
"started_at_default": true,
"final_whole_body_on_platform": true,
"platform_height": true,
"full_ramp_clearance": true,
"ramp_lateral_error": true,
"actual_ramp_contacts": true,
"contact_penetration": true
},
"profile": "standard",
"side": "blue",
"task_duration_sim_s": 49.42,
"gui": false,
"with_rviz": false,
"aligned_start": false,
"ramp_clearance_m": 0.07902892679713025,
"teardown": {
"known_pids": [
33232,
33250,
33252,
33254,
33256,
33258,
33260,
33262,
33264,
33266,
33268,
33270,
33272,
33274,
33276,
33278,
33280
],
"sigterm": [
33232,
33250,
33254,
33256,
33258,
33260,
33262,
33264,
33266,
33268,
33270,
33272,
33274,
33276,
33278,
33280
],
"sigkill": [
33250
],
"port_free": true,
"seconds": 8.17,
"never_touched_unknown_pid": true
},
"maximum_ramp_lateral_error_m": 0.007635084121969005,
"stop_latency_s": null,
"final": {
"stamp": 53.03,
"pos": [
-1.3491970626919487,
-3.5094866195847256,
0.7489874383468182
],
"yaw": 3.130931774839157,
"rpy": [
-3.631862765109253e-08,
1.9924609485569688e-14,
3.130931774839157
],
"quaternion": [
-9.680662521612223e-11,
-1.8159055787460126e-08,
0.9999857932416718,
0.0053304141325394875
],
"twist_world": [
-5.033938670057897e-15,
-1.2907551976872214e-11,
5.284969259449369e-05
],
"wz": 4.516255343835164e-19
}
},
"fast_blue": {
"path": "sim_ws/log/vehicle_migration_20261116/final_fast_blue/result.json",
"sha256": "524489e013e27c91b4d788c7647582afcaf85d71b5eedbb5377821e4d5d3d3df",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"scan_end_odometry_enabled": true,
"critical_cloud_qos_reliable": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"within_20_seconds": true,
"mission_succeeded": true,
"straight_without_intermediate_stop": true,
"requested_straight_speed_reached": true,
"requested_uphill_speed_reached": true,
"requested_turn_speed_reached": true,
"crest_speed_respected": true,
"north_corridor_clearance": true,
"no_wall_contacts": true,
"all_phases": true,
"started_at_default": true,
"final_whole_body_on_platform": true,
"platform_height": true,
"full_ramp_clearance": true,
"ramp_lateral_error": true,
"actual_ramp_contacts": true,
"contact_penetration": true
},
"profile": "fast",
"side": "blue",
"task_duration_sim_s": 19.46,
"gui": false,
"with_rviz": false,
"aligned_start": false,
"ramp_clearance_m": 0.07694013414840395,
"teardown": {
"known_pids": [
33927,
33945,
33947,
33949,
33951,
33953,
33955,
33957,
33959,
33961,
33963,
33965,
33967,
33971,
33973,
33976,
33983
],
"sigterm": [
33927,
33945,
33949,
33951,
33953,
33955,
33957,
33959,
33961,
33963,
33965,
33967,
33971,
33973,
33976,
33983
],
"sigkill": [
33945
],
"port_free": true,
"seconds": 8.16,
"never_touched_unknown_pid": true
},
"maximum_ramp_lateral_error_m": 0.00920097920067331,
"stop_latency_s": null,
"final": {
"stamp": 23.1,
"pos": [
-1.3278143874098984,
-3.5215114016646454,
0.7489874383468184
],
"yaw": 3.1380167347655026,
"rpy": [
-3.631862724543596e-08,
1.990852664440438e-14,
3.1380167347655026
],
"quaternion": [
3.247805265824423e-11,
1.8159284579091364e-08,
-0.999998401600996,
-0.0017879584595209645
],
"twist_world": [
9.367884862101693e-14,
-1.2929373155356436e-11,
5.284969255641195e-05
],
"wz": 4.660954567941754e-19
}
},
"fast_blue_lower_loss": {
"path": "sim_ws/log/vehicle_migration_20261116/final_fast_blue_lower_loss/result.json",
"sha256": "442b9a13f9edc2491a2c8be31df33a63b27ea1b747af4cb6e8028cc7d4d2bf37",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"scan_end_odometry_enabled": true,
"critical_cloud_qos_reliable": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"fault_stop_latency": true,
"fault_exercised": true,
"upper_continued": true,
"lower_stopped": true,
"restored_data_without_motion": true
},
"profile": "fast",
"side": "blue",
"task_duration_sim_s": 2.4,
"gui": false,
"with_rviz": false,
"aligned_start": true,
"ramp_clearance_m": 0.08462722829046943,
"teardown": {
"known_pids": [
34563,
34581,
34583,
34585,
34587,
34589,
34591,
34593,
34595,
34597,
34599,
34601,
34603,
34605,
34607,
34609,
34613
],
"sigterm": [
34563,
34581,
34585,
34587,
34589,
34591,
34593,
34595,
34597,
34599,
34601,
34603,
34605,
34607,
34609,
34613
],
"sigkill": [
34581
],
"port_free": true,
"seconds": 8.16,
"never_touched_unknown_pid": true
},
"maximum_ramp_lateral_error_m": 0.0010292781514009697,
"stop_latency_s": 0.48599999999999977,
"final": {
"stamp": 7.34,
"pos": [
1.3705884825419967,
-3.5114825720780938,
0.37789870766856026
],
"yaw": 3.1368841459887307,
"rpy": [
0.0007916631327093589,
-0.16894364140012139,
3.1368841459887307
],
"quaternion": [
0.08437208672402936,
0.00019578759004146434,
0.9964316159056887,
0.00231246029816058
],
"twist_world": [
9.015465413896385e-06,
-1.4346643950277983e-11,
5.284989443017031e-05
],
"wz": -1.608181230156947e-11
}
}
},
"timing": "NAVIGATE to SUCCEEDED includes whole-body landing and settle, excludes initialization; simulation time, not hardware time",
"fault_scope": "fast_blue_lower_loss starts at aligned staging pose; not a full-route time result",
"gui_scope": "All final migration cases headless; no screenshot or fresh GUI acceptance",
"teardown_note": "Each run freed the master port and touched only recorded owned PIDs; the owned gzserver required SIGKILL after timeout. These motion passes do not establish graceful Gazebo teardown. Real-entry clean shutdown was tested separately without Gazebo."
},
"tools": {
"config_generation": {
"status": "PASS",
"log": {
"path": "minco_ws/log/vehicle_migration/config_generator_r2.log",
"sha256": "9810823c097769b3f1b56765ed774e5a261d0173e097f7627c99b1c0684e263d"
},
"note": "Fixture IPs only; leaves time_sync_verified=false and imu_acc_norm=null"
},
"missing_sensor_probe": {
"status": "EXPECTED_FAILURE",
"expected_exit_code": 30,
"report": {
"path": "minco_ws/log/vehicle_migration/probe_missing_sources.json",
"sha256": "3ed2ca69d22c45e3f30d94833abc509620259a7a3de74a83030b0711249e5a65"
}
}
},
"source_sha256": {
"minco_ws/src/chassis/techx_r2_chassis_control/config/chassis_serial.yaml": "df865fb00bb1c24f0d414e52744518140ef1af759f65f2ec9d431054aec61e36",
"minco_ws/src/chassis/techx_r2_chassis_control/package.xml": "bdf9fae61a34298903475a5de9dccd8ddda362ae74875229dd75ddc0d4158ffa",
"minco_ws/src/chassis/techx_r2_chassis_control/techx_r2_chassis_control/chassis_serial_node.py": "98b8af55e2a5c4c35fe110582f3513d31b26f31a84f95664baf6b3a628fd9277",
"minco_ws/src/chassis/techx_r2_chassis_control/test/test_stop.py": "bed9fdeab6ca4e869dabf3190630cd2f913510853f97c400f1b11f3498a0584e",
"minco_ws/src/perception/Point-LIO/src/laserMapping.cpp": "d1bdd7b88bbdc5e158e09901206b06c27291a4525c896ddff1c19bc7bd1d9e4e",
"minco_ws/src/scan/br_vehicle_mission/CMakeLists.txt": "e240f25f42adadc938fcc69e13dd1ecaa6e736ba6bf4cc24904714ee93101819",
"minco_ws/src/scan/br_vehicle_mission/br_vehicle_mission/__init__.py": "f56276e1cc80e572f1c8745d0cde4ce0c809da5cb278233a946b4aa571d5bbbd",
"minco_ws/src/scan/br_vehicle_mission/br_vehicle_mission/deployment.py": "2e508ff3b0202f4755d79efc9526bd5d687149b3310203cddc16f16c0f1be312",
"minco_ws/src/scan/br_vehicle_mission/br_vehicle_mission/dual_lidar_fusion.py": "61e4cf662416d3c97b21d5555ab7f811675316b980900d7b57703a8aeba1cd28",
"minco_ws/src/scan/br_vehicle_mission/br_vehicle_mission/lio_navigation_adapter.py": "963417cca379f59750ac89c4325f5f9bce54f051052478877abe56b6481b30f3",
"minco_ws/src/scan/br_vehicle_mission/br_vehicle_mission/mission_command_mux.py": "305fd694d7301f5b3e43b0202bc42b21661ae5d77084e78e109a50feea948166",
"minco_ws/src/scan/br_vehicle_mission/br_vehicle_mission/profiles.py": "9697408d0d0c887b5b006a29f847acbe21148b810222e025aa3b4b38e659aaff",
"minco_ws/src/scan/br_vehicle_mission/br_vehicle_mission/ramp_mission.py": "b12b115daa3447a500e7c154fe49cb90cbc04962deb56495636ebf6b3a8f9086",
"minco_ws/src/scan/br_vehicle_mission/config/driver_network.template.json": "b0bbee9c024141b4fdc80238698dea8d4d56337b5f4e29cd10ea5f98a7614226",
"minco_ws/src/scan/br_vehicle_mission/config/mission_navigation.yaml": "22fd75d4342340255b724bcdce54c49f66e9455e32bf08ab6d3348add365c05a",
"minco_ws/src/scan/br_vehicle_mission/config/vehicle_site.example.yaml": "e936d8e2180f39277308e8315bb23e791fb92db1137e407b4b06ab088ca90fc1",
"minco_ws/src/scan/br_vehicle_mission/launch/dual_mid360_driver.launch.py": "ce35685925b4a63c14fc91c327ec6fa1f292891284333032eadbb36a8ea1c0f9",
"minco_ws/src/scan/br_vehicle_mission/launch/ramp_vehicle.launch.py": "c2955640200149135f76d0e05493b9a16483fede3e90be52a83cb5b77ea4df84",
"minco_ws/src/scan/br_vehicle_mission/package.xml": "2fa10f06ac4189e9e141b9b314e3f1e9f5a965554876d2997045c0c3434ab86d",
"minco_ws/src/scan/br_vehicle_mission/scripts/configure_dual_mid360.py": "7f121ae0907429348dab50a122c9f7a4b60c23ef7439bea65c2988071b471d5a",
"minco_ws/src/scan/br_vehicle_mission/scripts/dual_lidar_fusion.py": "d33b4bf40ad3f720d1305594f51344abac09e608c5e94dbf3eac1003a85e7ec7",
"minco_ws/src/scan/br_vehicle_mission/scripts/lio_navigation_adapter.py": "c468a3f5d30bc407a67ddb121ca4e4ecb12c044f19c60dc3c39801c402df4806",
"minco_ws/src/scan/br_vehicle_mission/scripts/mission_command_mux.py": "71b68517fb42e2ab59a66f84ca90aede336ece1c92b737ad17dfbc81b638200f",
"minco_ws/src/scan/br_vehicle_mission/scripts/probe_vehicle_sensors.py": "5919245602f6837bb654ab9500025378b6fb08714dcac54c4f625cbadf59ac53",
"minco_ws/src/scan/br_vehicle_mission/scripts/ramp_mission.py": "c715262fceb4291c1af26e27c5ffe99dc29515d105929644b286a897ca0747a2",
"minco_ws/src/scan/br_vehicle_mission/test/check_vehicle_launch.py": "0f8dbfe09db4282bb2d935eeeb1689e6e8a44cbbc91cd66a9d464a45880658b5",
"minco_ws/src/scan/br_vehicle_mission/test/test_vehicle_migration.py": "9f3b178a8fb1dec5f231bbcfa9a4bdcd7dfe486a93acae7db09da17e619f243e",
"minco_ws/tools/build_vehicle_mission.sh": "1c1655f8120cd57115278c1c38ceaa509a790f1b2d958b8ee19888412d825938",
"sim_ws/src/br_sim_bringup/launch/ramp_mission.launch.py": "321b4c9b7fc26a14fbb9fcc62c1a8a94057f0f42369cab96d9dca0c122c35518",
"sim_ws/src/br_sim_bringup/package.xml": "0456f74d4883e49b2da492e6d3a9d88c6d1a868d1a90336b4aa9963c948d9713",
"sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py": "d33b4bf40ad3f720d1305594f51344abac09e608c5e94dbf3eac1003a85e7ec7",
"sim_ws/src/br_sim_bringup/scripts/lio_navigation_adapter.py": "c468a3f5d30bc407a67ddb121ca4e4ecb12c044f19c60dc3c39801c402df4806",
"sim_ws/src/br_sim_bringup/scripts/mission_command_mux.py": "71b68517fb42e2ab59a66f84ca90aede336ece1c92b737ad17dfbc81b638200f",
"sim_ws/src/br_sim_bringup/scripts/ramp_mission.py": "c715262fceb4291c1af26e27c5ffe99dc29515d105929644b286a897ca0747a2",
"sim_ws/src/robocon_gazebo/worlds/robocon_robot.world": "6c1c12852bd70f6676d03ae2abe428ddce3500fd7ad283dfaf0046cafd3a2efb",
"sim_ws/tools/build_sim.sh": "1b41a4056194465f79ad72bcf7a05634f4cf3a8f7aad150c57ad9fe26f782149",
"sim_ws/tools/check_omni_robot.py": "88ad6f2950d1f7c6e81db2e41029866b9674d588c22298ad0212f742fdc8f84e",
"sim_ws/tools/check_ramp_mission.py": "f2aba02da7ff90f4f73377e44151544e03a2642de4050bd0d009df3639f983b7"
},
"binary_sha256": {
"minco_ws/install/mission/point_lio/lib/libpoint_lio_component.so": "07b0424baab55f9284211fa7f037bc7b010b24826ce796eb67aa63789aef0a43",
"minco_ws/install/mission/point_lio/lib/point_lio/pointlio_mapping": "e588e82dbab8c08809c471ebb3d5738a22408fe1c906b66ccfcb47f0e1736475",
"sim_ws/install/localization/point_lio/lib/libpoint_lio_component.so": "0ba8ead8a2a7e00bdbce11cccd93482673d29a0f9871db1a3d7587690e8245c2",
"sim_ws/install/localization/point_lio/lib/point_lio/pointlio_mapping": "ca90b7980fe7fad4ce1451062999aa65db313a9d3ae1b72e5ccff972b509ce54",
"minco_ws/install/mission/scan_planner/lib/scan_planner/closed_loop_controller": "047b10e123d39b03c77bc6e11ba127ef94ca999b696f31b0becc06481188537c",
"sim_ws/install/navigation/scan_planner/lib/scan_planner/closed_loop_controller": "78023eecf4333ebb9a314944f688f44b0737e392bf05d6567979dbe109053e72"
},
"history": [
{
"path": "minco_ws/log/vehicle_migration/vehicle_units.log",
"classification": "failed test assertion",
"reason": "Exact comparison of binary floating-point seconds; changed to approximate assertion, source nanoseconds unchanged"
},
{
"path": "minco_ws/log/vehicle_migration/config_generator.log",
"classification": "failed invocation",
"reason": "New symlink-installed helper lacked executable permission; source executable bits fixed"
},
{
"path": "minco_ws/log/vehicle_migration/launch_real_with_lio",
"classification": "NOT_ACCEPTED",
"reason": "Original checker accepted startup only; logs show mission publish-after-shutdown and Point-LIO SIGINT escalation/abnormal exit. Fixed lifecycle and strengthened checker; original reports unmodified"
},
{
"path": "minco_ws/log/vehicle_migration/launch_clean_shutdown",
"classification": "NOT_ACCEPTED",
"reason": "Shutdown clean, first node inventory sampled before DDS discovery completed. Checker now waits for named nodes; final launch_final rerun used"
},
{
"path": "sim_ws/log/vehicle_migration_20261116/{standard_red,fast_red,standard_blue,fast_blue,fast_blue_lower_loss}",
"classification": "earlier motion passes only",
"reason": "Before lifecycle fix; final_* independently rerun after rebuilding Point-LIO"
}
],
"not_verified": [
"Actual dual-lidar IP/network setup, power and mounting occlusion",
"Physical lidar/IMU clock synchronization and stationary units",
"Livox SDK hardware-driver build and live sensor startup on robot",
"Actual serial/STM32 direction, watchdog, emergency stop and execution of final zero frame",
"Physical braking acceleration, slip, ramp clearance, localization error and platform stop",
"Physical standard/fast red/blue full routes or 20-second performance"
]
}
@@ -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>
+1 -1
View File
@@ -17,7 +17,7 @@ colcon --log-base sim_ws/log/build_localization build --base-paths minco_ws/src/
--executor sequential --cmake-args "${BR_SIM_CMAKE[@]}" -DBUILD_TESTING=OFF
source sim_ws/install/localization/setup.bash
colcon --log-base sim_ws/log/build_navigation build --base-paths minco_ws/src/scan \
--packages-up-to scan_planner step_blocker --build-base sim_ws/build/navigation --install-base sim_ws/install/navigation \
--packages-up-to scan_planner step_blocker br_vehicle_mission --build-base sim_ws/build/navigation --install-base sim_ws/install/navigation \
--executor sequential --cmake-args "${BR_SIM_CMAKE[@]}" -DBUILD_TESTING=ON
source sim_ws/install/navigation/setup.bash
colcon --log-base sim_ws/log/build_classic build --base-paths sim_ws/src \
+3 -1
View File
@@ -239,7 +239,7 @@ class Sim(object):
if value.isdigit() and self.owns(int(value)):
self.known[int(value)] = _comm(int(value))
def start(self, gui=False, timeout=90.0, lidar=False, navigation=False, spawn=None, drive='planar', world=None, terrain=False, sensor_model='generic', localization=False, lio_navigation=False, sensor_profile='ideal', split=False, dual_lidar=False, mission=False, ramp_speed=.3, nav_speed=.3, aligned_start=False, crest_speed=.2, yaw_speed=.8, with_rviz=False, mission_profile='standard'):
def start(self, gui=False, timeout=90.0, lidar=False, navigation=False, spawn=None, drive='planar', world=None, terrain=False, sensor_model='generic', localization=False, lio_navigation=False, sensor_profile='ideal', split=False, dual_lidar=False, mission=False, ramp_speed=.3, nav_speed=.3, aligned_start=False, crest_speed=.2, yaw_speed=.8, with_rviz=False, mission_profile='standard', mission_side='red'):
if port_open(port=11355):
return False, 'master 端口 11355 已被占用;本工具不去动占用者,直接退出'
if terrain and not navigation:
@@ -264,6 +264,8 @@ class Sim(object):
options = ('gui:=%s' % ('true' if gui else 'false'))
if dual_lidar:options += ' dual_lidar:=true'
if mission:
if mission_side not in ('red','blue'):raise ValueError('invalid mission side')
options+=' side:='+mission_side
if mission_profile not in ('standard','fast'):raise ValueError('invalid mission profile')
if not .1<=nav_speed<=(2.5 if mission_profile=='fast' else .6) or not .1<=ramp_speed<=(1.1 if mission_profile=='fast' else .7):raise ValueError('mission speed outside selected profile')
options+=' autostart:=true profile:=%s ramp_speed:=%g nav_speed:=%g'%(mission_profile,ramp_speed,nav_speed)
+25 -12
View File
@@ -35,6 +35,12 @@ def bounds(s):
c=np.asarray(s['pos'])+R@np.array([0.,0.,.055]);e=np.abs(R)@np.array([.4,.4,.205])
return c-e,c+e
def corridor_bounds(s,side):
"""Score symmetric corridors in +Y coordinates; retain raw truth in report."""
lo,hi=bounds(s)
if side=='blue':lo[1],hi[1]=-hi[1],-lo[1]
return lo,hi
def motion_metrics(truth,events,fast=False):
entry=next((e['stamp'] for e in events if e.get('to')=='ENTRY'),None)
nav_start=next((e['stamp'] for e in events if e.get('to')=='NAVIGATE'),None)
@@ -58,6 +64,7 @@ def motion_metrics(truth,events,fast=False):
def main():
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True)
ap.add_argument('--profile',choices=('standard','fast'),default='standard')
ap.add_argument('--side',choices=('red','blue'),default='red')
ap.add_argument('--ramp-speed',type=float);ap.add_argument('--nav-speed',type=float)
ap.add_argument('--crest-speed',type=float,default=.2);ap.add_argument('--yaw-speed',type=float)
ap.add_argument('--gui',action='store_true');ap.add_argument('--sensor-profile',choices=('ideal','mild'),default='ideal')
@@ -73,7 +80,10 @@ def main():
if (out/'result.json').exists():ap.error('use a fresh output directory')
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',profile=args.profile,gui=args.gui,with_rviz=args.with_rviz,ramp_speed=args.ramp_speed,nav_speed=args.nav_speed,crest_speed=args.crest_speed,yaw_speed=args.yaw_speed,fault=args.fault,aligned_start=args.aligned_start,collector_sha256=hashlib.sha256(source).hexdigest())
side_sign=1. if args.side=='red' else -1.
ramp_name='ramp_north' if args.side=='red' else 'ramp_south'
platform_name='Cube.005' if args.side=='red' else 'Cube.010'
report=dict(status='INVALID',profile=args.profile,side=args.side,gui=args.gui,with_rviz=args.with_rviz,ramp_speed=args.ramp_speed,nav_speed=args.nav_speed,crest_speed=args.crest_speed,yaw_speed=args.yaw_speed,fault=args.fault,aligned_start=args.aligned_start,collector_sha256=hashlib.sha256(source).hexdigest())
root=Path(__file__).resolve().parents[2]
report['source_sha256']={str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in [
root/name for name in ('sim_ws/src/br_sim_bringup/scripts/ramp_mission.py','sim_ws/src/br_sim_bringup/scripts/mission_command_mux.py','sim_ws/src/br_sim_bringup/launch/ramp_mission.launch.py',
@@ -84,13 +94,16 @@ def main():
'minco_ws/src/perception/Point-LIO/include/common_lib.h','minco_ws/src/perception/Point-LIO/include/sensor_timestamp.h',
'sim_ws/src/br_sim_bringup/scripts/lio_navigation_adapter.py','minco_ws/src/scan/step_blocker/step_blocker/step_blocker_node.py',
'minco_ws/src/perception/Point-LIO/include/sensor_time_rate_limiter.h','minco_ws/src/perception/Point-LIO/src/laserMapping.cpp','sim_ws/src/robocon_gazebo/worlds/robocon_robot.world')]}
for name in report['source_sha256']:(out/Path(name).name).write_bytes((root/name).read_bytes())
for path in (root/'minco_ws/src/scan/br_vehicle_mission/br_vehicle_mission').glob('*.py'):
report['source_sha256'][str(path.relative_to(root))]=hashlib.sha256(path.read_bytes()).hexdigest()
for name in report['source_sha256']:
target=out/'sources'/name;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes((root/name).read_bytes())
sim=Sim(str(out/'sim'));p=None;states=[];mission=[];mux=[];fault={};actuator=[]
try:
ok,why=sim.start(lio_navigation=True,dual_lidar=True,mission=True,ramp_speed=args.ramp_speed,nav_speed=args.nav_speed,gui=args.gui,sensor_profile=args.sensor_profile,
with_rviz=args.with_rviz,mission_profile=args.profile,
with_rviz=args.with_rviz,mission_profile=args.profile,mission_side=args.side,
crest_speed=args.crest_speed,yaw_speed=args.yaw_speed,
aligned_start=args.aligned_start,spawn=(3.7,3.5125,.15,math.pi) if args.aligned_start else None);report['startup']=why
aligned_start=args.aligned_start,spawn=(3.7,side_sign*3.5125,.15,math.pi) if args.aligned_start else None);report['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=TerrainProbe(out,True)
for pub in (p.pub,p.goal_pub,p.path_pub):p.destroy_publisher(pub)
@@ -111,7 +124,7 @@ def main():
state=mission[-1]['state']
if args.fault=='obstacle' and not fixture and state in ('NAVIGATE','ENTRY'):
req=SpawnEntity.Request();req.name='mission_ramp_obstacle';req.reference_frame='world'
req.initial_pose.position.x=1.;req.initial_pose.position.y=3.5125;req.initial_pose.position.z=float((1.6119-.597)/3.5+.15);req.initial_pose.orientation.w=1.
req.initial_pose.position.x=1.;req.initial_pose.position.y=side_sign*3.5125;req.initial_pose.position.z=float((1.6119-.597)/3.5+.15);req.initial_pose.orientation.w=1.
req.xml='<sdf version="1.6"><model name="mission_ramp_obstacle"><static>true</static><link name="box"><collision name="box"><geometry><box><size>0.25 0.25 0.30</size></box></geometry></collision></link></model></sdf>'
res=p._call(p.spawn,req,15)
if res is None or not res.success:raise RuntimeError('fixture spawn failed')
@@ -184,9 +197,9 @@ def main():
stopped_drift=bool(tail) and max(math.dist(s['pos'],tail[0]['pos']) for s in tail)<.02)
events=mission[-1]['events'];entry=next((e['stamp'] for e in events if e.get('to')=='ENTRY'),None)
ramp=[s for s in truth if entry is not None and s['stamp']>=entry and s['pos'][0]<3.1]
clearance=[min(bounds(s)[0][1]-3.025,4.-bounds(s)[1][1]) for s in ramp]
clearance=[min(corridor_bounds(s,args.side)[0][1]-3.025,4.-corridor_bounds(s,args.side)[1][1]) for s in ramp]
report['ramp_clearance_m']=min(clearance,default=None)
report['maximum_ramp_lateral_error_m']=max((abs(s['pos'][1]-3.5125) for s in ramp),default=None)
report['maximum_ramp_lateral_error_m']=max((abs(s['pos'][1]-side_sign*3.5125) for s in ramp),default=None)
pairs=sorted({(c.collision1_name,c.collision2_name) for m in p.contacts for c in m.states})
report['contacts']=dict(pairs=pairs,maximum_depth_m=max((d for m in p.contacts for c in m.states for d in c.depths),default=None))
report['final']=final;report['events']=events;report['elapsed_sim_s']=mission[-1].get('elapsed_s')
@@ -195,14 +208,14 @@ def main():
report['task_duration_sim_s']=terminal[-1]-starts[0] if terminal and starts else None
report['motion_metrics']=motion_metrics(truth,events,args.profile=='fast')
if args.fault=='none':
lo,hi=bounds(final)
lo,hi=corridor_bounds(final,args.side)
north=[]
for a,b in zip(truth,truth[1:]):
if entry is None or b['stamp']>entry:continue
qa=np.array(a['quaternion']);qb=np.array(b['quaternion'])
angle=2*math.acos(np.clip(abs(float(qa@qb)),0,1));pad=(math.dist(a['pos'],b['pos'])+.62*angle)/2
for s in (a,b):
blo,bhi=bounds(s)
blo,bhi=corridor_bounds(s,args.side)
# The inner wall ends at x=2.7; the east staging area is open.
if bhi[0]+pad>=-3. and blo[0]-pad<=2.7:north.append(min(blo[1]-4.,5.5-bhi[1])-pad)
report['north_corridor_gap_bound_m']=min(north,default=None)
@@ -215,14 +228,14 @@ def main():
requested_turn_speed_reached=mm['nav_yaw_peak_radps']>=.85*args.yaw_speed,
crest_speed_respected=mm['crest_median_mps'] is not None and mm['crest_peak_mps']<=args.crest_speed+.03,
north_corridor_clearance=bool(north) and min(north)>.03,
no_wall_contacts=all(any(name.endswith(suffix) for suffix in ('::ground','::ramp_north','::Cube.005')) for pair in pairs for name in pair if not name.startswith('r2027_omni::')),
no_wall_contacts=all(any(name.endswith(suffix) for suffix in ('::ground','::'+ramp_name,'::'+platform_name)) for pair in pairs for name in pair if not name.startswith('r2027_omni::')),
all_phases=all(any(e.get('to')==stage for e in events) for stage in ('NAVIGATE','ENTRY','CLIMB','CREST','PLATFORM','SETTLE','SUCCEEDED')),
started_at_default=math.dist(truth[0]['pos'],[-4.5,4.5,.15])<.03,
started_at_default=math.dist(truth[0]['pos'],[-4.5,side_sign*4.5,.15])<.03,
final_whole_body_on_platform=lo[0]>=-1.76 and hi[0]<=-.84 and lo[1]>=3.065 and hi[1]<=3.96,
platform_height=abs(final['pos'][2]-.75)<.03,
full_ramp_clearance=bool(clearance) and min(clearance)>.04,
ramp_lateral_error=bool(ramp) and report['maximum_ramp_lateral_error_m']<.03,
actual_ramp_contacts=any('ramp_north' in c.collision1_name or 'ramp_north' in c.collision2_name for m in p.contacts for c in m.states),
actual_ramp_contacts=any(ramp_name in c.collision1_name or ramp_name in c.collision2_name for m in p.contacts for c in m.states),
contact_penetration=max((d for m in p.contacts for c in m.states for d in c.depths),default=1)<.005)
else:
if args.fault=='obstacle':