init: RoboCon 2027 BR 上位机 sru_ws(仅源码/文档/模型;排除构建产物与 venv)

- src/: sru_nav_ros2 (策略) + odin_ros_driver (0.14.x, ament ROS2) + techx_r2_chassis_control (串口桥)
- 修复: 驱动目录此前是悬空 gitlink,clone 后为空 -> 现改为普通文件(55 个)
- 排除: build/ install/ log/ venv/ .Trash-0/ __pycache__ 及驱动 map/log 运行期产物
- docs/: USAGE / PORT_NOTES / HANDOVER / ROS2_PORT_PLAN / 协议核查报告
This commit is contained in:
kevin
2026-10-19 11:15:15 +08:00
commit eba4570f4e
210 changed files with 40533 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
recorddata/
/config/calib.yaml
/log
/map
+38
View File
@@ -0,0 +1,38 @@
0.14.4 2260910
1.modify lidar_api_type.h RGB comments
2.update sdk to fix signal printf backtrace
0.14.3 20260903
1.Fix crash problem
0.14.2 20260825
1. Add RGB DTOF filter
2. Fix USB disconnect deadlock issue
3. Add RGB parameter configuration
4. Add save_map, reset_algo, get_device_logs service
0.14.1 20260809
1. Fixed the SDK's USB memory leak issue
2. Fixed the problem of 'transfer no mem' caused by USB buffer full during machine transfer
0.13.1 20260724
1.modify frame_id for image topic
2.fix tf transform fail in ROS2 Jazzy
3.Fix the issue where the driver's initial configuration could not read the calibration file
0.13.0 20260709
1.add large file transfer
v0.11.0 2026_0618
Required Minimum Firmware Version:0.12.0
1.Reduce cloud slam latency
2.Improve get mapping result
v0.10.5 2026_0525
1.modify recorddata format,add device_id、algorithm_version key
2.fix download map fail when in slam mode(USB2.0)
3.fix upload map fail when in relocalization mode(USB2.0)
v0.10.4 2026_0522
1.fix usb2.0 heartBeat timeout to cause soft detaching
2.add custom_init_pose_search_radius and custom_init_pose_max_rot_deg in control_command.yaml
+508
View File
@@ -0,0 +1,508 @@
cmake_minimum_required(VERSION 3.5)
project(odin_ros_driver)
if(DEFINED BUILD_SYSTEM)
set(ROS_VERSION ${BUILD_SYSTEM})
message(STATUS "ROS_VERSION: ${ROS_VERSION}")
elseif(DEFINED ENV{ROS_DISTRO})
if("$ENV{ROS_DISTRO}" MATCHES "foxy|galactic|humble|iron|rolling")
set(ROS_VERSION "ROS2")
else()
set(ROS_VERSION "ROS1")
endif()
elseif(DEFINED ENV{ROS_VERSION})
if("$ENV{ROS_VERSION}" EQUAL "2")
set(ROS_VERSION "ROS2")
else()
set(ROS_VERSION "ROS1")
endif()
else()
# Attempt automatic detection
if(COMMAND catkin_package)
set(ROS_VERSION "ROS1")
elseif(COMMAND ament_package)
set(ROS_VERSION "ROS2")
else()
# Default to ROS2
set(ROS_VERSION "ROS2")
message(WARNING "Unable to determine ROS version, defaulting to ROS2")
endif()
endif()
# Add compile definitions after detecting ROS version
if(ROS_VERSION STREQUAL "ROS2")
add_definitions(-DROS2)
message(STATUS "Defining ROS2")
else()
add_definitions(-DROS1)
message(STATUS "Defining ROS1")
endif()
message(STATUS "Build system: ${ROS_VERSION}")
# Platform detection
execute_process(
COMMAND uname -m
OUTPUT_VARIABLE ARCH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if(ARCH STREQUAL "x86_64")
set(TARGET_PLATFORM "x86")
message(STATUS "Detected x86_64 architecture")
elseif(ARCH MATCHES "arm|aarch64")
set(TARGET_PLATFORM "arm")
message(STATUS "Detected ARM architecture: ${ARCH}")
else()
message(WARNING "Unsupported architecture: ${ARCH}. Using default settings")
set(TARGET_PLATFORM "unknown")
endif()
# Set library path
set(LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/lib")
message(STATUS "Library directory: ${LIB_DIR}")
# Set library name based on platform
if(TARGET_PLATFORM STREQUAL "arm")
set(LYD_HOST_API_LIB_NAME "lydHostApi_arm")
else()
set(LYD_HOST_API_LIB_NAME "lydHostApi_amd")
endif()
# Find precompiled lydHostApi library
find_library(LYD_HOST_API_LIB
NAMES
${LYD_HOST_API_LIB_NAME}
lib${LYD_HOST_API_LIB_NAME}.a
lib${LYD_HOST_API_LIB_NAME}.so
PATHS ${LIB_DIR}
NO_DEFAULT_PATH
)
if(LYD_HOST_API_LIB)
message(STATUS "Found lydHostApi library: ${LYD_HOST_API_LIB}")
else()
file(GLOB LIB_FILES "${LIB_DIR}/lib${LYD_HOST_API_LIB_NAME}.*")
if(LIB_FILES)
message(STATUS "Found library files: ${LIB_FILES}")
set(LYD_HOST_API_LIB ${LIB_FILES})
else()
message(FATAL_ERROR "Could not find precompiled lydHostApi library in ${LIB_DIR}")
endif()
endif()
# Set common compile options
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Set optimization flags
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O2")
# Symbolization support for the SDK crash handler.
# -g keeps DWARF info so addr2line can report file/line, the frame-pointer and
# unwind-table flags keep the stack walkable, and CMAKE_ENABLE_EXPORTS adds
# -rdynamic so symbols pulled in from the static SDK archive land in .dynsym
# and become visible to dladdr()/backtrace_symbols() at runtime.
option(ODIN_ENABLE_BACKTRACE "Keep symbols and frame pointers for crash backtraces" ON)
if(ODIN_ENABLE_BACKTRACE)
set(BACKTRACE_FLAGS "-g -fno-omit-frame-pointer -funwind-tables -fasynchronous-unwind-tables")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${BACKTRACE_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${BACKTRACE_FLAGS}")
set(CMAKE_ENABLE_EXPORTS ON)
message(STATUS "Backtrace symbols enabled (-g, frame pointers, -rdynamic)")
endif()
# Find common dependencies
find_package(PkgConfig REQUIRED)
find_package(OpenCV REQUIRED)
find_package(Eigen3 REQUIRED)
find_package(PCL REQUIRED)
find_package(yaml-cpp REQUIRED)
find_package(OpenSSL REQUIRED)
pkg_check_modules(LIBUSB REQUIRED libusb-1.0)
# Shared include directories
include_directories(
include
${EIGEN3_INCLUDE_DIRS}
${OpenCV_INCLUDE_DIRS}
${PCL_INCLUDE_DIRS}
${yaml-cpp_INCLUDE_DIR}
${LIBUSB_INCLUDE_DIRS}
${CMAKE_CURRENT_SOURCE_DIR}/include
)
# Shared library list
set(COMMON_LIBS
${OpenCV_LIBS}
${PCL_LIBRARIES}
${yaml-cpp_LIBRARIES}
${OPENSSL_LIBRARIES}
${LIBUSB_LIBRARIES}
pthread
rt
${CMAKE_DL_LIBS}
${LYD_HOST_API_LIB}
)
# ===== ROS1 Configuration =====
if(ROS_VERSION STREQUAL "ROS1")
message(STATUS "Configuring for ROS1 build")
find_package(catkin REQUIRED COMPONENTS
roscpp
std_msgs
sensor_msgs
nav_msgs
cv_bridge
tf
image_transport
message_generation
)
# ---- AE/AWB debug services ----
# Declare custom .srv files; catkin generates ros1 message headers for them.
add_service_files(
FILES
GetAe.srv
GetAwb.srv
SetAe.srv
SetAwb.srv
GetDeviceLogs.srv
SaveMap.srv
ResetAlgo.srv
)
generate_messages(
DEPENDENCIES
std_msgs
)
include_directories(${catkin_INCLUDE_DIRS})
catkin_package(
CATKIN_DEPENDS roscpp std_msgs sensor_msgs nav_msgs cv_bridge image_transport message_runtime
INCLUDE_DIRS include
)
# Set output directories
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CATKIN_DEVEL_PREFIX}/lib/${PROJECT_NAME})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CATKIN_DEVEL_PREFIX}/lib)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CATKIN_DEVEL_PREFIX}/lib)
add_executable(host_sdk_sample
src/host_sdk_sample.cpp
src/yaml_parser.cpp
src/rawCloudRender.cpp
src/camera_pose_visualization.cpp
)
target_link_libraries(host_sdk_sample
${catkin_LIBRARIES}
${COMMON_LIBS}
${LYD_HOST_API_LIB}
${LIBUSB_LIBRARIES}
yaml-cpp
${OpenCV_LIBS}
pthread
usb-1.0
)
# Make sure the AE/AWB srv headers are generated before host_sdk_sample
# is compiled (catkin's generate_messages produces this target).
add_dependencies(host_sdk_sample ${PROJECT_NAME}_generate_messages_cpp)
add_library(pointcloud_depth_converter src/pointcloud_depth_converter.cpp)
target_link_libraries(pointcloud_depth_converter
${OpenCV_LIBS}
${PCL_LIBRARIES}
)
add_library(depth_image_ros_node src/depth_image_ros_node.cpp)
target_link_libraries(depth_image_ros_node
pointcloud_depth_converter
${catkin_LIBRARIES}
${OpenCV_LIBS}
${PCL_LIBRARIES}
)
add_executable(pcd2depth_node src/pcd2depth_ros.cpp)
target_link_libraries(pcd2depth_node
depth_image_ros_node
${catkin_LIBRARIES}
${OpenCV_LIBS}
${PCL_LIBRARIES}
)
add_library(cloud_reprojector src/cloud_reprojector.cpp)
target_link_libraries(cloud_reprojector
${OpenCV_LIBS}
${PCL_LIBRARIES}
)
add_executable(cloud_reprojection_node src/cloud_reprojection_ros.cpp)
target_link_libraries(cloud_reprojection_node
cloud_reprojector
${catkin_LIBRARIES}
${OpenCV_LIBS}
${PCL_LIBRARIES}
)
add_executable(image_overlay_node src/image_overlay_node.cpp)
target_link_libraries(image_overlay_node
${catkin_LIBRARIES}
${OpenCV_LIBS}
)
# Installation rules
install(TARGETS host_sdk_sample
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
install(DIRECTORY include/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
FILES_MATCHING PATTERN "*.h"
)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/config")
install(DIRECTORY config/
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/config
)
endif()
# ===== ROS2 Configuration =====
elseif(ROS_VERSION STREQUAL "ROS2")
message(STATUS "Configuring for ROS2 build")
# Find all necessary ROS2 packages
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
find_package(sensor_msgs REQUIRED)
find_package(nav_msgs REQUIRED)
find_package(visualization_msgs REQUIRED)
find_package(cv_bridge REQUIRED)
find_package(image_transport REQUIRED)
find_package(pcl_conversions REQUIRED)
find_package(message_filters REQUIRED)
find_package(tf2 REQUIRED)
find_package(tf2_ros REQUIRED)
find_package(geometry_msgs REQUIRED)
find_package(tf2_geometry_msgs REQUIRED)
find_package(ament_index_cpp REQUIRED)
# ---- AE/AWB debug services ----
# Generate C++ bindings for the 4 .srv files in srv/. The generated
# headers are linked into host_sdk_sample so it can host the services.
find_package(rosidl_default_generators REQUIRED)
rosidl_generate_interfaces(${PROJECT_NAME}
"srv/GetAe.srv"
"srv/GetAwb.srv"
"srv/SetAe.srv"
"srv/SetAwb.srv"
"srv/GetDeviceLogs.srv"
"srv/SaveMap.srv"
"srv/ResetAlgo.srv"
)
# Create executable
add_executable(host_sdk_sample
src/host_sdk_sample.cpp
src/yaml_parser.cpp
src/rawCloudRender.cpp
src/camera_pose_visualization.cpp
)
# Link libraries
target_link_libraries(host_sdk_sample
${COMMON_LIBS}
yaml-cpp
usb-1.0
)
# Link the generated AE/AWB srv typesupport into host_sdk_sample so it
# can host the 4 debug services.
rosidl_get_typesupport_target(cpp_typesupport_target
${PROJECT_NAME} "rosidl_typesupport_cpp")
target_link_libraries(host_sdk_sample "${cpp_typesupport_target}")
# Add ROS2 dependencies
ament_target_dependencies(host_sdk_sample
rclcpp
std_msgs
sensor_msgs
nav_msgs
visualization_msgs
cv_bridge
image_transport
tf2
tf2_ros
geometry_msgs
tf2_geometry_msgs
ament_index_cpp
)
add_library(pointcloud_depth_converter_ros2 src/pointcloud_depth_converter.cpp)
target_link_libraries(pointcloud_depth_converter_ros2
${OpenCV_LIBS}
${PCL_LIBRARIES}
)
add_library(depth_image_ros2_node_lib src/depth_image_ros2_node.cpp)
target_link_libraries(depth_image_ros2_node_lib
pointcloud_depth_converter_ros2
${OpenCV_LIBS}
${PCL_LIBRARIES}
)
ament_target_dependencies(depth_image_ros2_node_lib
rclcpp
sensor_msgs
std_msgs
cv_bridge
image_transport
pcl_conversions
message_filters
)
add_executable(pcd2depth_ros2_node src/pcd2depth_ros2.cpp)
target_link_libraries(pcd2depth_ros2_node
depth_image_ros2_node_lib
${OpenCV_LIBS}
${PCL_LIBRARIES}
yaml-cpp
)
ament_target_dependencies(pcd2depth_ros2_node
rclcpp
sensor_msgs
std_msgs
cv_bridge
image_transport
pcl_conversions
message_filters
)
add_library(cloud_reprojector_ros2 src/cloud_reprojector.cpp)
target_compile_definitions(cloud_reprojector_ros2 PRIVATE ROS2)
target_link_libraries(cloud_reprojector_ros2
${OpenCV_LIBS}
${PCL_LIBRARIES}
)
add_executable(cloud_reprojection_ros2_node src/cloud_reprojection_ros.cpp)
target_compile_definitions(cloud_reprojection_ros2_node PRIVATE ROS2)
target_link_libraries(cloud_reprojection_ros2_node
cloud_reprojector_ros2
${OpenCV_LIBS}
${PCL_LIBRARIES}
yaml-cpp
)
ament_target_dependencies(cloud_reprojection_ros2_node
rclcpp
sensor_msgs
nav_msgs
cv_bridge
image_transport
pcl_conversions
message_filters
)
add_executable(image_overlay_node src/image_overlay_node.cpp)
target_compile_definitions(image_overlay_node PRIVATE ROS2)
target_link_libraries(image_overlay_node
${OpenCV_LIBS}
)
ament_target_dependencies(image_overlay_node
rclcpp
sensor_msgs
cv_bridge
image_transport
message_filters
)
# Installation rules - ensure all install targets are defined before ament_package()
# Install executable
install(TARGETS
host_sdk_sample
pcd2depth_ros2_node
cloud_reprojection_ros2_node
image_overlay_node
depth_image_ros2_node_lib
pointcloud_depth_converter_ros2
cloud_reprojector_ros2
EXPORT export_${PROJECT_NAME}
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
RUNTIME DESTINATION lib/${PROJECT_NAME}
)
# Install package.xml
install(FILES package.xml
DESTINATION share/${PROJECT_NAME}
)
# Install headers
install(DIRECTORY include/
DESTINATION include
)
# Install launch_ROS2 directory
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/launch_ROS2")
install(DIRECTORY launch_ROS2/
DESTINATION share/${PROJECT_NAME}/launch
)
message(STATUS "Installing launch_ROS2 directory to share/${PROJECT_NAME}/launch")
else()
message(WARNING "launch_ROS2 directory not found")
endif()
# Install config files
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/config")
install(DIRECTORY config/
DESTINATION share/${PROJECT_NAME}/config
)
endif()
# Install launch files
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/launch")
install(DIRECTORY launch/
DESTINATION share/${PROJECT_NAME}/launch
)
endif()
ament_export_targets(export_${PROJECT_NAME})
# Declare dependencies
ament_export_dependencies(
rclcpp
std_msgs
sensor_msgs
nav_msgs
visualization_msgs
cv_bridge
image_transport
pcl_conversions
message_filters
tf2
tf2_ros
geometry_msgs
tf2_geometry_msgs
ament_index_cpp
)
ament_package()
message(STATUS "Install targets added")
else()
message(FATAL_ERROR "Invalid ROS_VERSION: ${ROS_VERSION}")
endif()
# ARM platform specific link options
if(TARGET_PLATFORM STREQUAL "arm")
set_target_properties(host_sdk_sample PROPERTIES
LINK_FLAGS "-Wl,--no-as-needed -Wl,--rpath=${LIB_DIR}"
)
message(STATUS "Adding ARM-specific link options and RPATH")
endif()
# Add debug information
message(STATUS "=======================================")
message(STATUS "Project: ${PROJECT_NAME}")
message(STATUS "ROS_VERSION: ${ROS_VERSION}")
message(STATUS "Target platform: ${TARGET_PLATFORM}")
message(STATUS "lydHostApi library: ${LYD_HOST_API_LIB}")
message(STATUS "libusb library: ${LIBUSB_LIBRARIES}")
message(STATUS "=======================================")
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025 Manifold Tech Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,642 @@
# Relocalization Guide / 重定位使用指南
This guide explains how to use the relocalization feature in Odin ROS Driver, including automatic relocalization and init position relocalization modes.
本指南介绍如何使用 Odin ROS Driver 的重定位功能,包括自动重定位和指定初始位置重定位两种模式。
---
## Table of Contents / 目录
1. [Overview / 概述](#overview--概述)
2. [Prerequisites / 前提条件](#prerequisites--前提条件)
3. [Mode 1: Auto Relocalization / 自动重定位](#mode-1-auto-relocalization--自动重定位)
4. [Mode 2: Init Position Relocalization / 指定初始位置重定位](#mode-2-init-position-relocalization--指定初始位置重定位)
5. [init_pos Format / init_pos 格式说明](#init_pos-format--init_pos-格式说明)
6. [Configuration Examples / 配置示例](#configuration-examples--配置示例)
7. [Programmatic API / 编程接口](#programmatic-api--编程接口)
8. [Troubleshooting / 故障排除](#troubleshooting--故障排除)
---
## Overview / 概述
### English
Relocalization mode (`custom_map_mode: 2`) allows Odin to localize itself within a pre-built map. There are two approaches:
| Mode | Description | Use Case |
|------|-------------|----------|
| **Auto Relocalization** | Algorithm automatically searches for position in the map | Starting position is unknown or within recommended range |
| **Init Position Relocalization** | User provides an initial pose estimate via `init_pos` | Starting position is known, faster convergence needed |
### 中文
重定位模式(`custom_map_mode: 2`)允许 Odin 在预先构建的地图中进行自我定位。有两种方式:
| 模式 | 描述 | 适用场景 |
|------|------|----------|
| **自动重定位** | 算法自动在地图中搜索位置 | 起始位置未知,或在推荐范围内 |
| **指定初始位置重定位** | 用户通过 `init_pos` 提供初始位姿估计 | 起始位置已知,需要更快收敛 |
---
## Prerequisites / 前提条件
### English
1. **Pre-built map file**: A `.bin` map file created in SLAM mode (`custom_map_mode: 1`)
2. **Map file path**: Know the absolute path to your map file
3. **Starting position**: For init position mode, know the approximate starting pose in map coordinates
### 中文
1. **预构建的地图文件**:在 SLAM 模式(`custom_map_mode: 1`)下创建的 `.bin` 地图文件
2. **地图文件路径**:知道地图文件的绝对路径
3. **起始位置**:对于指定初始位置模式,需要知道在地图坐标系中的大致起始位姿
---
## Mode 1: Auto Relocalization / 自动重定位
### English
In auto relocalization mode, the algorithm automatically searches for the device's position within the map based on current sensor observations.
**Configuration** (`config/control_command.yaml`):
```yaml
register_keys:
custom_map_mode: 2
relocalization_map_abs_path: "/path/to/your/map.bin"
# custom_init_pos is NOT set or uses default [0,0,0,0,0,0,1]
```
**Recommended Starting Conditions**:
- Within **1 meter** of a position on the original SLAM trajectory
- Within **±10 degrees** of the original orientation
- In a visually distinctive area of the map
**Behavior**:
1. On startup, Odin attempts to match current observations with the map
2. If successful, TF between `map` and `odom` frames is published
3. If unsuccessful, system operates in fallback SLAM mode (map saving disabled)
4. Relocalization attempts continue in background until successful
**Tips**:
- Gently shaking or moving the device after startup can improve relocalization accuracy
- Highly distinctive scenes may allow successful matching beyond the 1m/10° range
### 中文
在自动重定位模式下,算法根据当前传感器观测自动在地图中搜索设备位置。
**配置** (`config/control_command.yaml`):
```yaml
register_keys:
custom_map_mode: 2
relocalization_map_abs_path: "/path/to/your/map.bin"
# custom_init_pos 不设置或使用默认值 [0,0,0,0,0,0,1]
```
**推荐起始条件**:
- 距离原始 SLAM 轨迹上某点 **1 米**以内
- 朝向与原始方向偏差在 **±10 度**以内
- 位于地图中视觉特征明显的区域
**行为**:
1. 启动时,Odin 尝试将当前观测与地图匹配
2. 如果成功,发布 `map` 和 `odom` 坐标系之间的 TF
3. 如果失败,系统进入后备 SLAM 模式(地图保存功能禁用)
4. 后台持续尝试重定位直到成功
**提示**:
- 启动后轻轻晃动或移动设备可以提高重定位精度
- 在特征明显的场景中,可能在超出 1m/10° 范围时也能成功匹配
---
## Mode 2: Init Position Relocalization / 指定初始位置重定位
### English
In init position relocalization mode, you provide an initial pose estimate to help the algorithm converge faster.
**Configuration** (`config/control_command.yaml`):
```yaml
register_keys:
custom_map_mode: 2
relocalization_map_abs_path: "/path/to/your/map.bin"
custom_init_pos: [x, y, z, qx, qy, qz, qw]
```
**When to Use**:
- You know the approximate starting position (e.g., from external localization system)
- Starting position is far from the recommended 1m/10° range
- You need faster relocalization convergence
- Deploying in a fixed docking station with known pose
**Behavior**:
1. Algorithm uses provided `init_pos` as initial pose estimate
2. Searches for matches in the vicinity of the provided position
3. Faster convergence compared to auto mode when estimate is accurate
### 中文
在指定初始位置重定位模式下,您提供初始位姿估计以帮助算法更快收敛。
**配置** (`config/control_command.yaml`):
```yaml
register_keys:
custom_map_mode: 2
relocalization_map_abs_path: "/path/to/your/map.bin"
custom_init_pos: [x, y, z, qx, qy, qz, qw]
```
**适用场景**:
- 您知道大致的起始位置(例如,来自外部定位系统)
- 起始位置远离推荐的 1m/10° 范围
- 需要更快的重定位收敛速度
- 部署在已知位姿的固定充电桩
**行为**:
1. 算法使用提供的 `init_pos` 作为初始位姿估计
2. 在提供位置的附近搜索匹配
3. 当估计准确时,比自动模式收敛更快
---
## init_pos Format / init_pos 格式说明
### English
`init_pos` is an array of **7 float values** representing position and orientation:
```yaml
custom_init_pos: [x, y, z, qx, qy, qz, qw]
```
| Index | Parameter | Description | Unit |
|-------|-----------|-------------|------|
| 0 | x | X position in map frame | meters |
| 1 | y | Y position in map frame | meters |
| 2 | z | Z position in map frame | meters |
| 3 | qx | Quaternion X component | - |
| 4 | qy | Quaternion Y component | - |
| 5 | qz | Quaternion Z component | - |
| 6 | qw | Quaternion W component | - |
**Important Notes**:
- The quaternion must be normalized: `sqrt(qx² + qy² + qz² + qw²) ≈ 1.0`
- Coordinates are relative to the **map frame** (world frame at SLAM start)
- Default value `[0, 0, 0, 0, 0, 0, 1]` represents origin with no rotation
**Common Quaternion Values**:
| Orientation | qx | qy | qz | qw |
|-------------|----|----|----|----|
| No rotation (identity) | 0 | 0 | 0 | 1 |
| 90° around Z-axis | 0 | 0 | 0.707 | 0.707 |
| 180° around Z-axis | 0 | 0 | 1 | 0 |
| -90° around Z-axis | 0 | 0 | -0.707 | 0.707 |
### 中文
`init_pos` 是一个包含 **7 个 float 值**的数组,表示位置和朝向:
```yaml
custom_init_pos: [x, y, z, qx, qy, qz, qw]
```
| 索引 | 参数 | 描述 | 单位 |
|------|------|------|------|
| 0 | x | 地图坐标系中的 X 位置 | 米 |
| 1 | y | 地图坐标系中的 Y 位置 | 米 |
| 2 | z | 地图坐标系中的 Z 位置 | 米 |
| 3 | qx | 四元数 X 分量 | - |
| 4 | qy | 四元数 Y 分量 | - |
| 5 | qz | 四元数 Z 分量 | - |
| 6 | qw | 四元数 W 分量 | - |
**重要说明**:
- 四元数必须归一化:`sqrt(qx² + qy² + qz² + qw²) ≈ 1.0`
- 坐标相对于**地图坐标系**(SLAM 启动时的世界坐标系)
- 默认值 `[0, 0, 0, 0, 0, 0, 1]` 表示原点且无旋转
**常用四元数值**:
| 朝向 | qx | qy | qz | qw |
|------|----|----|----|----|
| 无旋转(单位四元数) | 0 | 0 | 0 | 1 |
| 绕 Z 轴旋转 90° | 0 | 0 | 0.707 | 0.707 |
| 绕 Z 轴旋转 180° | 0 | 0 | 1 | 0 |
| 绕 Z 轴旋转 -90° | 0 | 0 | -0.707 | 0.707 |
---
## Configuration Examples / 配置示例
### Example 1: Auto Relocalization / 自动重定位示例
```yaml
register_keys:
custom_map_mode: 2
relocalization_map_abs_path: "/home/user/maps/office_map.bin"
```
### Example 2: Init Position at Origin / 在原点指定初始位置
```yaml
register_keys:
custom_map_mode: 2
relocalization_map_abs_path: "/home/user/maps/office_map.bin"
custom_init_pos: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]
```
### Example 3: Init Position with Offset / 带偏移的初始位置
Position at (5.2, -3.1, 0) with 90° rotation around Z-axis:
位置在 (5.2, -3.1, 0),绕 Z 轴旋转 90°:
```yaml
register_keys:
custom_map_mode: 2
relocalization_map_abs_path: "/home/user/maps/warehouse_map.bin"
custom_init_pos: [5.2, -3.1, 0.0, 0.0, 0.0, 0.707, 0.707]
```
### Example 4: Docking Station Pose / 充电桩位置
Known docking station at (10.5, 2.3, 0) facing -X direction (180° rotation):
已知充电桩位置在 (10.5, 2.3, 0),朝向 -X 方向(旋转 180°):
```yaml
register_keys:
custom_map_mode: 2
relocalization_map_abs_path: "/home/user/maps/factory_map.bin"
custom_init_pos: [10.5, 2.3, 0.0, 0.0, 0.0, 1.0, 0.0]
```
---
## Programmatic API / 编程接口
### English
You can also set `init_pos` programmatically using the `lidar_set_custom_parameter` API. This is useful for:
- Dynamic relocalization during runtime
- Integration with external localization systems
- Setting initial pose from robot's last known position
#### API Function
```cpp
#include "lidar_api.h"
/**
* @brief Set a custom parameter on the device
* @param device Device handle obtained from lidar_open_device()
* @param param_name Parameter name (e.g., "init_pos")
* @param value_data Pointer to the parameter data
* @param value_length Size of the data in bytes
* @return 0 on success, -1 on error, -2 if file transfer in progress
*/
int lidar_set_custom_parameter(device_handle device,
const char* param_name,
const void* value_data,
size_t value_length);
```
#### Complete Example
```cpp
#include "lidar_api.h"
#include <cstdio>
#include <cmath>
// Helper function to create quaternion from yaw angle (rotation around Z-axis)
void yaw_to_quaternion(float yaw_rad, float* qx, float* qy, float* qz, float* qw) {
*qx = 0.0f;
*qy = 0.0f;
*qz = sinf(yaw_rad / 2.0f);
*qw = cosf(yaw_rad / 2.0f);
}
int set_init_position(device_handle device,
float x, float y, float z,
float qx, float qy, float qz, float qw) {
// init_pos format: [x, y, z, qx, qy, qz, qw] - 7 floats
float init_pos[7] = {x, y, z, qx, qy, qz, qw};
int result = lidar_set_custom_parameter(
device,
"init_pos", // Parameter name
init_pos, // Data pointer
sizeof(init_pos) // 7 * sizeof(float) = 28 bytes
);
if (result == 0) {
printf("Successfully set init_pos: [%.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f]\n",
x, y, z, qx, qy, qz, qw);
} else {
printf("Failed to set init_pos, error code: %d\n", result);
}
return result;
}
// Usage examples:
// Example 1: Set position at origin with no rotation
void example_origin(device_handle device) {
set_init_position(device,
0.0f, 0.0f, 0.0f, // x, y, z
0.0f, 0.0f, 0.0f, 1.0f // qx, qy, qz, qw (identity)
);
}
// Example 2: Set position with 90° yaw rotation
void example_with_rotation(device_handle device) {
float qx, qy, qz, qw;
float yaw_degrees = 90.0f;
float yaw_rad = yaw_degrees * M_PI / 180.0f;
yaw_to_quaternion(yaw_rad, &qx, &qy, &qz, &qw);
set_init_position(device,
5.2f, -3.1f, 0.0f, // x, y, z
qx, qy, qz, qw // quaternion from yaw
);
}
// Example 3: Set position from external localization system
void example_from_external_localization(device_handle device,
double ext_x, double ext_y, double ext_yaw) {
float qx, qy, qz, qw;
yaw_to_quaternion((float)ext_yaw, &qx, &qy, &qz, &qw);
set_init_position(device,
(float)ext_x, (float)ext_y, 0.0f,
qx, qy, qz, qw
);
}
```
#### ROS Integration Example
```cpp
#include "lidar_api.h"
#include <geometry_msgs/PoseWithCovarianceStamped.h> // ROS1
// or
#include <geometry_msgs/msg/pose_with_covariance_stamped.hpp> // ROS2
// Callback for /initialpose topic (from RViz "2D Pose Estimate" tool)
void initialPoseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg,
device_handle device) {
float init_pos[7] = {
(float)msg->pose.pose.position.x,
(float)msg->pose.pose.position.y,
(float)msg->pose.pose.position.z,
(float)msg->pose.pose.orientation.x,
(float)msg->pose.pose.orientation.y,
(float)msg->pose.pose.orientation.z,
(float)msg->pose.pose.orientation.w
};
int result = lidar_set_custom_parameter(device, "init_pos", init_pos, sizeof(init_pos));
if (result == 0) {
ROS_INFO("Set init_pos from RViz: [%.2f, %.2f, %.2f]",
init_pos[0], init_pos[1], init_pos[2]);
} else {
ROS_ERROR("Failed to set init_pos: %d", result);
}
}
```
#### Important Notes
1. **Call timing**: Set `init_pos` **before** starting the stream with `lidar_start_stream()`
2. **Map mode**: Ensure `custom_map_mode` is set to `2` (relocalization mode)
3. **Map file**: The relocalization map must be set via `lidar_set_relocalization_map()` or YAML config
4. **Thread safety**: `lidar_set_custom_parameter` is thread-safe but blocks until response received
### 中文
您也可以使用 `lidar_set_custom_parameter` API 以编程方式设置 `init_pos`。适用于:
- 运行时动态重定位
- 与外部定位系统集成
- 从机器人上次已知位置设置初始位姿
#### API 函数
```cpp
#include "lidar_api.h"
/**
* @brief 在设备上设置自定义参数
* @param device 从 lidar_open_device() 获取的设备句柄
* @param param_name 参数名称(如 "init_pos")
* @param value_data 指向参数数据的指针
* @param value_length 数据大小(字节)
* @return 成功返回 0,错误返回 -1,文件传输中返回 -2
*/
int lidar_set_custom_parameter(device_handle device,
const char* param_name,
const void* value_data,
size_t value_length);
```
#### 完整示例
```cpp
#include "lidar_api.h"
#include <cstdio>
#include <cmath>
// 辅助函数:从偏航角(绕 Z 轴旋转)创建四元数
void yaw_to_quaternion(float yaw_rad, float* qx, float* qy, float* qz, float* qw) {
*qx = 0.0f;
*qy = 0.0f;
*qz = sinf(yaw_rad / 2.0f);
*qw = cosf(yaw_rad / 2.0f);
}
int set_init_position(device_handle device,
float x, float y, float z,
float qx, float qy, float qz, float qw) {
// init_pos 格式: [x, y, z, qx, qy, qz, qw] - 7 个 float
float init_pos[7] = {x, y, z, qx, qy, qz, qw};
int result = lidar_set_custom_parameter(
device,
"init_pos", // 参数名
init_pos, // 数据指针
sizeof(init_pos) // 7 * sizeof(float) = 28 字节
);
if (result == 0) {
printf("成功设置 init_pos: [%.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f]\n",
x, y, z, qx, qy, qz, qw);
} else {
printf("设置 init_pos 失败,错误码: %d\n", result);
}
return result;
}
// 使用示例:
// 示例 1:在原点设置位置,无旋转
void example_origin(device_handle device) {
set_init_position(device,
0.0f, 0.0f, 0.0f, // x, y, z
0.0f, 0.0f, 0.0f, 1.0f // qx, qy, qz, qw(单位四元数)
);
}
// 示例 2:设置带 90° 偏航旋转的位置
void example_with_rotation(device_handle device) {
float qx, qy, qz, qw;
float yaw_degrees = 90.0f;
float yaw_rad = yaw_degrees * M_PI / 180.0f;
yaw_to_quaternion(yaw_rad, &qx, &qy, &qz, &qw);
set_init_position(device,
5.2f, -3.1f, 0.0f, // x, y, z
qx, qy, qz, qw // 从偏航角计算的四元数
);
}
// 示例 3:从外部定位系统设置位置
void example_from_external_localization(device_handle device,
double ext_x, double ext_y, double ext_yaw) {
float qx, qy, qz, qw;
yaw_to_quaternion((float)ext_yaw, &qx, &qy, &qz, &qw);
set_init_position(device,
(float)ext_x, (float)ext_y, 0.0f,
qx, qy, qz, qw
);
}
```
#### ROS 集成示例
```cpp
#include "lidar_api.h"
#include <geometry_msgs/PoseWithCovarianceStamped.h> // ROS1
// 或
#include <geometry_msgs/msg/pose_with_covariance_stamped.hpp> // ROS2
// /initialpose 话题的回调函数(来自 RViz 的 "2D Pose Estimate" 工具)
void initialPoseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg,
device_handle device) {
float init_pos[7] = {
(float)msg->pose.pose.position.x,
(float)msg->pose.pose.position.y,
(float)msg->pose.pose.position.z,
(float)msg->pose.pose.orientation.x,
(float)msg->pose.pose.orientation.y,
(float)msg->pose.pose.orientation.z,
(float)msg->pose.pose.orientation.w
};
int result = lidar_set_custom_parameter(device, "init_pos", init_pos, sizeof(init_pos));
if (result == 0) {
ROS_INFO("从 RViz 设置 init_pos: [%.2f, %.2f, %.2f]",
init_pos[0], init_pos[1], init_pos[2]);
} else {
ROS_ERROR("设置 init_pos 失败: %d", result);
}
}
```
#### 重要说明
1. **调用时机**:在调用 `lidar_start_stream()` 启动数据流**之前**设置 `init_pos`
2. **地图模式**:确保 `custom_map_mode` 设置为 `2`(重定位模式)
3. **地图文件**:必须通过 `lidar_set_relocalization_map()` 或 YAML 配置设置重定位地图
4. **线程安全**:`lidar_set_custom_parameter` 是线程安全的,但会阻塞直到收到响应
---
## Troubleshooting / 故障排除
### Relocalization Fails / 重定位失败
**English**:
- Ensure starting position is within recommended range (1m/10°)
- Check that the map file path is correct and file exists
- Verify the environment hasn't changed significantly since mapping
- Try gently moving the device to provide more observations
**中文**:
- 确保起始位置在推荐范围内(1m/10°)
- 检查地图文件路径是否正确且文件存在
- 验证环境自建图以来没有显著变化
- 尝试轻轻移动设备以提供更多观测
### init_pos Not Taking Effect / init_pos 未生效
**English**:
- Verify `custom_map_mode` is set to `2`
- Check that `custom_init_pos` has exactly 7 values
- Ensure quaternion is normalized (sum of squares ≈ 1)
- Restart the driver after modifying configuration
**中文**:
- 验证 `custom_map_mode` 设置为 `2`
- 检查 `custom_init_pos` 是否恰好有 7 个值
- 确保四元数已归一化(平方和 ≈ 1)
- 修改配置后重启驱动程序
### TF Not Published / TF 未发布
**English**:
- Relocalization may still be in progress
- Check ROS logs for relocalization status messages
- System operates in fallback mode until relocalization succeeds
**中文**:
- 重定位可能仍在进行中
- 检查 ROS 日志中的重定位状态消息
- 系统在重定位成功前以后备模式运行
### Map File Not Found / 地图文件未找到
**English**:
- Use absolute path (starting with `/`)
- Check file permissions
- Verify file extension is `.bin`
**中文**:
- 使用绝对路径(以 `/` 开头)
- 检查文件权限
- 验证文件扩展名为 `.bin`
---
## Related Topics / 相关话题
| Topic | Description |
|-------|-------------|
| `/odin1/odometry` | Odometry in odom frame |
| `/odin1/odometry_highfreq` | High-frequency odometry |
| `/odin1/cloud_slam` | SLAM point cloud in odom frame |
| `/tf` | Transform tree (includes map→odom after successful relocalization) |
---
## See Also / 参见
- [README.md](README.md) - Main documentation
- [config/control_command.yaml](config/control_command.yaml) - Configuration file
@@ -0,0 +1,140 @@
register_keys:
# if off, allow connection even if usb connection is below usb 3.0
# ATTENTION: usb 3.0 is always recommended, as advance functionality like SLAM mode requires usb 3.0 for reliable map file transfer
strict_usb3.0_check: 0 # 0: off: 1: on;
# 0: use odin internal system time as data time stamp, typical and recommended;
# 1: use host ros time (upon receive) as data time stamp, only use if you specifically require this setup, not recommended for most users
# 2: align odin1 time to host time, timestamp is the sensor data reception time on host time axis
use_host_ros_time: 0 # Changed to 0 to use device timestamp without PTP offset correction
streamctrl: 1 # 0: off; 1: on
# original rgb data in jpeg format from device
sendrgbcompressed: 1 # 0: off; 1: on
# RGB data, decoded from original jpeg data from device, bgr8 format
# Processed on host device
sendrgb: 1 # 0: off; 1: on
# undistort rgb image processed from decoded rgb data.
# depends on sendrgb. related camera parameters can be found in ws/src/odin_ros_driver/config/calib.yaml
# Processed on host device
sendrgbundistort: 0 # 0: off; 1: on.
# IMU data
sendimu: 1 # 0: off; 1: on
# SDK IMU smooth sending feature
# When enabled, SDK will send IMU data at precise intervals (default 400Hz)
# using a dedicated high-priority thread to reduce jitter and timing variance
enable_imu_smooth: 0 # 0: disable SDK IMU smooth sending; 1: enable (default)
# SDK IMU smooth sending frequency in Hz (only effective when enable_imu_smooth = 1)
imu_smooth_frequency: 400 # 1-1000 Hz, recommended 400 Hz
# Odometry data
sendodom: 1 # 0: off; 1: on
# TF from odom to imu. Leave it on unless you specifically need it off.
# ATTENTION: critical for rviz to show cloud_raw.
send_odom_baselink_tf: 1 # 0: off; 1: on.
# Extra TF publish rate (Hz) for odom->imu transform.
# 0: disabled (TF only published with odom data, at actual rate)
# >0: additionally publish TF at this rate using a timer (e.g. 50 for 50Hz)
# Useful for ROS2 Jazzy where tf2 has strict timestamp lookup
tf_extra_publish_rate: 0 # 0: off; >0: rate in Hz
# raw dtof data
senddtof: 1 # 0: off; 1: on
cloud_raw_confidence_threshold: 35 # please refer to readme for more details
# dtof sensor frame rate. Supported values: 100 (10fps) or 145 (14.5fps)
# Higher frame rate provides smoother point cloud data but may increase data bandwidth
# Note: value is multiplied by 10 (e.g., 145 means 14.5fps)
dtof_fps: 100 # 100: 10fps;
# 145: 14.5fps
########################################################
# RGB camera configuration (format, resolution, frame rate)
# RGB 摄像头配置(格式、分辨率、帧率)
#
# Applied via lidar_set_rgb_parameter() before streaming starts.
# 在数据流启动前通过 lidar_set_rgb_parameter() 下发。
#
# ATTENTION: not all combinations are valid; invalid values will
# cause device connection failure. 无效组合会导致设备连接失败。
#
# RGB frame rate is coupled with the DTOF frame rate, so both must
# be set to one of the matching pairs below (3 tiers supported):
# RGB 帧率与 DTOF 帧率联动,二者需按下表配对设置(支持三档):
#
# rgb_fps | dtof_fps | RGB actual rate | DTOF actual rate
# --------+----------+----------------+----------------
# 100 | 100 | 10.264 Hz | 10.0 Hz
# 145 | 145 | 14.472 Hz | 14.5 Hz
# 290 | 100 | 28.92 Hz | 10.0 Hz
########################################################
rgb_format: 1 # 0: NV12 ; 1: MJPEG(default)
rgb_width: 1600 # Image width in pixels / 图像宽度(像素)
rgb_height: 1296 # Image height in pixels / 图像高度(像素)
rgb_fps: 100 # Frame rate * 10 (300 = 30fps, 145 = 14.5fps) / 帧率×10
# slam cloud data
sendcloudslam: 1 # 0: off; 1: on
# processed with raw point cloud, rgb image, and calib.yaml from device
# Processed on host device
sendcloudrender: 1 # 0: off; 1: on
# depth completion demo, high computing resource usage.
# for more information please refer to the readme file.
# Processed on host device
senddepth: 1 # 0: off; 1: on
# cloud reprojection demo, projects cloud_slam to camera image using odometry
# Processed on host device
sendreprojection: 0 # 0: off; 1: on
# image overlay settings - overlays reprojected points on camera image
# Processed on host device
sendoverlay: 0 # 0: off; 1: on
overlay_reprojected_topic: "/odin1/reprojected_image" # reprojected image topic
overlay_camera_topic: "/odin1/image/undistorted" # camera image topic (undistorted)
overlay_output_topic: "/odin1/overlay_image" # output overlay image topic
overlay_alpha: 0.6 # blend alpha (0.0-1.0, higher = more reproj color)
# record rgb, odometry, and slam cloud data as proprietary olx format for further processing in MindCloud(TM) software.
# save path: ws/src/odin_ros_driver/recorddata/{record_start_time}/
# ATTENTION: please copy the full folder for post-processing.
recorddata: 0 # 0: off; 1: on
# Save device runtime status info to ws/src/odin_ros_driver/log/Driver_{drvier_start_time}/Conn_{device_connection_time}/dev_status.csv
devstatuslog: 1 # 0: off; 1: on.
save_log: 0 # 0: off; 1: on;
# raw dtof sensor intensity data in gray format, mostly for debug purpose.
pubintensitygray: 0 # 0: off; 1: on
showpath: 0 # 0: off; 1: on
showcamerapose: 0 # 0: off; 1: on
custom_map_mode: 1 # 0: Odometry mode 1: SLAM mode 2: Relocalization mode
custom_init_pos: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]
custom_init_pose_search_radius: 4.0 # max position offset in meters, recommended <= 10
custom_init_pose_max_rot_deg: 180.0 # max rotation offset in degrees, up to 180
relocalization_map_abs_path: "" # must be set for Relocalization mode or will fail
# To get the mapping result file, please use the set_param.sh script provided: "./set_param.sh save_map 1"
mapping_result_dest_dir: "" # "": if not specified, save to default location of {ws}/src/odin_ros_driver/map/{driver_start_time}/
mapping_result_file_name: "" # "": if not specified, save to location above with default file name of map_{map_save_time}.bin
# Image mask transfer settings
sendimagemask: 0 # 0: off; 1: on - transfer image mask to device on startup
image_mask_abs_path: "" # absolute path to the image mask file (e.g., /path/to/mask.png(1600x1296 resolution)
# Algorithm reset settings
resetalgo: 0 # 0: off; 1: on - send algo_reset command to device on startup
@@ -0,0 +1,438 @@
Panels:
- Class: rviz/Displays
Help Height: 0
Name: Displays
Property Tree Widget:
Expanded:
- /Global Options1
- /Odometry1
- /slam1
- /TF1/Frames1
Splitter Ratio: 0.4993045926094055
Tree Height: 495
- Class: rviz/Selection
Name: Selection
- Class: rviz/Tool Properties
Expanded:
- /2D Pose Estimate1
- /2D Nav Goal1
- /Publish Point1
Name: Tool Properties
Splitter Ratio: 0.5886790156364441
- Class: rviz/Views
Expanded:
- /Current View1
Name: Views
Splitter Ratio: 0.5
- Class: rviz/Time
Name: Time
SyncMode: 0
SyncSource: Image
Preferences:
PromptSaveOnExit: true
Toolbars:
toolButtonStyle: 2
Visualization Manager:
Class: ""
Displays:
- Alpha: 0.5
Cell Size: 1
Class: rviz/Grid
Color: 160; 160; 164
Enabled: true
Line Style:
Line Width: 0.029999999329447746
Value: Lines
Name: Grid
Normal Cell Count: 0
Offset:
X: 0
Y: 0
Z: 0
Plane: XY
Plane Cell Count: 10
Reference Frame: <Fixed Frame>
Value: true
- Class: rviz/Image
Enabled: true
Image Topic: /odin1/image
Max Value: 1
Median window: 5
Min Value: 0
Name: Image
Normalize Range: true
Queue Size: 2
Transport Hint: raw
Unreliable: false
Value: true
- Class: rviz/Image
Enabled: false
Image Topic: /odin1/image/undistorted
Max Value: 1
Median window: 5
Min Value: 0
Name: Image_undistort
Normalize Range: true
Queue Size: 2
Transport Hint: raw
Unreliable: false
Value: false
- Class: rviz/Image
Enabled: false
Image Topic: /odin1/reprojected_image
Max Value: 1
Median window: 5
Min Value: 0
Name: cloudslam_reprojected
Normalize Range: true
Queue Size: 2
Transport Hint: raw
Unreliable: false
Value: false
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz/PointCloud2
Color: 255; 255; 255
Color Transformer: Intensity
Decay Time: 0
Enabled: false
Invert Rainbow: false
Max Color: 255; 255; 255
Min Color: 0; 0; 0
Name: raw
Position Transformer: XYZ
Queue Size: 10
Selectable: true
Size (Pixels): 3
Size (m): 0.009999999776482582
Style: Points
Topic: /odin1/cloud_raw
Unreliable: false
Use Fixed Frame: true
Use rainbow: true
Value: false
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 1.8493094444274902
Min Value: -0.13891705870628357
Value: true
Axis: Z
Channel Name: intensity
Class: rviz/PointCloud2
Color: 255; 255; 255
Color Transformer: RGB8
Decay Time: 0
Enabled: false
Invert Rainbow: false
Max Color: 255; 255; 255
Min Color: 0; 0; 0
Name: render
Position Transformer: XYZ
Queue Size: 10
Selectable: true
Size (Pixels): 3
Size (m): 0.009999999776482582
Style: Points
Topic: /odin1/cloud_render
Unreliable: false
Use Fixed Frame: true
Use rainbow: true
Value: false
- Class: rviz/Group
Displays:
- Angle Tolerance: 0.10000000149011612
Class: rviz/Odometry
Covariance:
Orientation:
Alpha: 0.5
Color: 255; 255; 127
Color Style: Unique
Frame: Local
Offset: 1
Scale: 1
Value: true
Position:
Alpha: 0.30000001192092896
Color: 204; 51; 204
Scale: 1
Value: true
Value: false
Enabled: true
Keep: 1
Name: Odometry
Position Tolerance: 0.10000000149011612
Queue Size: 1
Shape:
Alpha: 1
Axes Length: 1
Axes Radius: 0.10000000149011612
Color: 255; 25; 0
Head Length: 0.30000001192092896
Head Radius: 0.10000000149011612
Shaft Length: 1
Shaft Radius: 0.05000000074505806
Value: Axes
Topic: /odin1/odometry
Unreliable: false
Value: true
- Angle Tolerance: 0.10000000149011612
Class: rviz/Odometry
Covariance:
Orientation:
Alpha: 0.5
Color: 255; 255; 127
Color Style: Unique
Frame: Local
Offset: 1
Scale: 1
Value: true
Position:
Alpha: 0.30000001192092896
Color: 204; 51; 204
Scale: 1
Value: true
Value: true
Enabled: false
Keep: 100
Name: Odometry_high
Position Tolerance: 0.10000000149011612
Queue Size: 10
Shape:
Alpha: 1
Axes Length: 1
Axes Radius: 0.10000000149011612
Color: 52; 101; 164
Head Length: 0.30000001192092896
Head Radius: 0.10000000149011612
Shaft Length: 1
Shaft Radius: 0.05000000074505806
Value: Arrow
Topic: /odin1/odometry_highfreq
Unreliable: false
Value: false
- Class: rviz/MarkerArray
Enabled: false
Marker Topic: /odin1/camera_pose_visual
Name: camera_view
Namespaces:
{}
Queue Size: 100
Value: false
Enabled: true
Name: Odometry
- Class: rviz/Group
Displays:
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: rgb
Class: rviz/PointCloud2
Color: 255; 255; 255
Color Transformer: RGB8
Decay Time: 0
Enabled: true
Invert Rainbow: false
Max Color: 255; 255; 255
Min Color: 0; 0; 0
Name: slam_current
Position Transformer: XYZ
Queue Size: 10
Selectable: true
Size (Pixels): 3
Size (m): 0.009999999776482582
Style: Points
Topic: /odin1/cloud_slam
Unreliable: false
Use Fixed Frame: true
Use rainbow: true
Value: true
- Alpha: 0.10000000149011612
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz/PointCloud2
Color: 255; 255; 255
Color Transformer: RGB8
Decay Time: 5
Enabled: false
Invert Rainbow: false
Max Color: 255; 255; 255
Min Color: 0; 0; 0
Name: slam_decay
Position Transformer: XYZ
Queue Size: 10
Selectable: true
Size (Pixels): 1
Size (m): 0.009999999776482582
Style: Points
Topic: /odin1/cloud_slam
Unreliable: false
Use Fixed Frame: true
Use rainbow: true
Value: false
- Class: rviz/MarkerArray
Enabled: false
Marker Topic: /odin1/path
Name: path
Namespaces:
{}
Queue Size: 100
Value: false
Enabled: true
Name: slam
- Class: rviz/Group
Displays:
- Class: rviz/Image
Enabled: true
Image Topic: /odin1/depth_img_competetion
Max Value: 1
Median window: 5
Min Value: 0
Name: dense_depth_image
Normalize Range: true
Queue Size: 2
Transport Hint: raw
Unreliable: false
Value: true
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz/PointCloud2
Color: 255; 255; 255
Color Transformer: RGB8
Decay Time: 0
Enabled: false
Invert Rainbow: false
Max Color: 255; 255; 255
Min Color: 0; 0; 0
Name: dense_depth_cloud
Position Transformer: XYZ
Queue Size: 10
Selectable: true
Size (Pixels): 3
Size (m): 0.009999999776482582
Style: Points
Topic: /odin1/depth_img_competetion_cloud
Unreliable: false
Use Fixed Frame: true
Use rainbow: true
Value: false
Enabled: false
Name: dense_depth_demo
- Class: rviz/TF
Enabled: true
Filter (blacklist): ""
Filter (whitelist): ""
Frame Timeout: 15
Frames:
All Enabled: true
imu:
Value: true
odom:
Value: true
Marker Alpha: 1
Marker Scale: 1
Name: TF
Show Arrows: true
Show Axes: true
Show Names: true
Tree:
odom:
imu:
{}
Update Interval: 0
Value: true
Enabled: true
Global Options:
Background Color: 48; 48; 48
Default Light: true
Fixed Frame: odom
Frame Rate: 30
Name: root
Tools:
- Class: rviz/Interact
Hide Inactive Objects: true
- Class: rviz/MoveCamera
- Class: rviz/Select
- Class: rviz/FocusCamera
- Class: rviz/Measure
- Class: rviz/SetInitialPose
Theta std deviation: 0.2617993950843811
Topic: /initialpose
X std deviation: 0.5
Y std deviation: 0.5
- Class: rviz/SetGoal
Topic: /move_base_simple/goal
- Class: rviz/PublishPoint
Single click: true
Topic: /clicked_point
Value: true
Views:
Current:
Class: rviz/Orbit
Distance: 16.25591278076172
Enable Stereo Rendering:
Stereo Eye Separation: 0.05999999865889549
Stereo Focal Distance: 1
Swap Stereo Eyes: false
Value: false
Field of View: 0.7853981852531433
Focal Point:
X: 0
Y: 0
Z: 0
Focal Shape Fixed Size: false
Focal Shape Size: 0.05000000074505806
Invert Z Axis: false
Name: Current View
Near Clip Distance: 0.009999999776482582
Pitch: 1.010398030281067
Target Frame: odom
Yaw: 0.8753980994224548
Saved: ~
Window Geometry:
Displays:
collapsed: false
Height: 1016
Hide Left Dock: false
Hide Right Dock: false
Image:
collapsed: false
Image_undistort:
collapsed: false
QMainWindow State: 000000ff00000000fd0000000400000000000001e70000033afc020000000cfb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000b0fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003d0000022c000000c900fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261fb0000000a0049006d006100670065010000026f000001080000001600fffffffb0000002200640065006e00730065005f00640065007000740068005f0069006d006100670065000000047d000001730000001600fffffffb0000001e0049006d006100670065005f0075006e0064006900730074006f007200740000000568000000df0000001600fffffffb0000002a0063006c006f007500640073006c0061006d005f0072006500700072006f006a0065006300740065006400000002b2000000c50000001600ffffff000000010000015f0000033afc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073010000003d0000033a000000a400fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000007380000005efc0100000002fb0000000800540069006d0065010000000000000738000003bc00fffffffb0000000800540069006d00650100000000000004500000000000000000000003e60000033a00000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000
Selection:
collapsed: false
Time:
collapsed: false
Tool Properties:
collapsed: false
Views:
collapsed: false
Width: 1848
X: 72
Y: 27
cloudslam_reprojected:
collapsed: false
dense_depth_image:
collapsed: false
@@ -0,0 +1,499 @@
Panels:
- Class: rviz_common/Displays
Help Height: 0
Name: Displays
Property Tree Widget:
Expanded:
- /Global Options1
- /Status1
- /Image1/Topic1
- /cloudslam_reprojected1
- /Odometry1
- /slam1
- /dense_depth_demo1
Splitter Ratio: 0.5
Tree Height: 593
- Class: rviz_common/Selection
Name: Selection
- Class: rviz_common/Tool Properties
Expanded:
- /2D Goal Pose1
- /Publish Point1
Name: Tool Properties
Splitter Ratio: 0.5886790156364441
- Class: rviz_common/Views
Expanded:
- /Current View1
Name: Views
Splitter Ratio: 0.5
Visualization Manager:
Class: ""
Displays:
- Alpha: 0.5
Cell Size: 1
Class: rviz_default_plugins/Grid
Color: 160; 160; 164
Enabled: true
Line Style:
Line Width: 0.029999999329447746
Value: Lines
Name: Grid
Normal Cell Count: 0
Offset:
X: 0
Y: 0
Z: 0
Plane: XY
Plane Cell Count: 10
Reference Frame: <Fixed Frame>
Value: true
- Class: rviz_default_plugins/Image
Enabled: true
Max Value: 1
Median window: 5
Min Value: 0
Name: Image
Normalize Range: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/image
Value: true
- Class: rviz_default_plugins/Image
Enabled: false
Max Value: 1
Median window: 5
Min Value: 0
Name: Image_undistort
Normalize Range: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/image/undistorted
Value: false
- Class: rviz_default_plugins/Image
Enabled: false
Max Value: 1
Median window: 5
Min Value: 0
Name: cloudslam_reprojected
Normalize Range: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/reprojected_image
Value: false
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz_default_plugins/PointCloud2
Color: 255; 255; 255
Color Transformer: Intensity
Decay Time: 0
Enabled: false
Invert Rainbow: false
Max Color: 255; 255; 255
Max Intensity: 239
Min Color: 0; 0; 0
Min Intensity: 0
Name: raw
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.009999999776482582
Style: Points
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/cloud_raw
Use Fixed Frame: true
Use rainbow: true
Value: false
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 1.8730175495147705
Min Value: -0.12252448499202728
Value: true
Axis: Z
Channel Name: rgb
Class: rviz_default_plugins/PointCloud2
Color: 255; 255; 255
Color Transformer: RGB8
Decay Time: 0
Enabled: false
Invert Rainbow: false
Max Color: 255; 255; 255
Max Intensity: 2.3509885615147286e-38
Min Color: 0; 0; 0
Min Intensity: 0
Name: render
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.009999999776482582
Style: Points
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/cloud_render
Use Fixed Frame: true
Use rainbow: true
Value: false
- Class: rviz_common/Group
Displays:
- Angle Tolerance: 0.10000000149011612
Class: rviz_default_plugins/Odometry
Covariance:
Orientation:
Alpha: 0.5
Color: 255; 255; 127
Color Style: Unique
Frame: Local
Offset: 1
Scale: 1
Value: true
Position:
Alpha: 0.30000001192092896
Color: 204; 51; 204
Scale: 1
Value: true
Value: true
Enabled: true
Keep: 1
Name: Odometry
Position Tolerance: 0.10000000149011612
Shape:
Alpha: 1
Axes Length: 1
Axes Radius: 0.10000000149011612
Color: 255; 25; 0
Head Length: 0.30000001192092896
Head Radius: 0.10000000149011612
Shaft Length: 1
Shaft Radius: 0.05000000074505806
Value: Axes
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/odometry
Value: true
- Angle Tolerance: 0.10000000149011612
Class: rviz_default_plugins/Odometry
Covariance:
Orientation:
Alpha: 0.5
Color: 255; 255; 127
Color Style: Unique
Frame: Local
Offset: 1
Scale: 1
Value: true
Position:
Alpha: 0.30000001192092896
Color: 204; 51; 204
Scale: 1
Value: true
Value: true
Enabled: false
Keep: 10
Name: Odometry_high
Position Tolerance: 0.10000000149011612
Shape:
Alpha: 1
Axes Length: 1
Axes Radius: 0.10000000149011612
Color: 98; 160; 234
Head Length: 0.30000001192092896
Head Radius: 0.10000000149011612
Shaft Length: 1
Shaft Radius: 0.05000000074505806
Value: Arrow
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/odometry_highfreq
Value: false
- Class: rviz_default_plugins/MarkerArray
Enabled: false
Name: camera_view
Namespaces:
{}
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/camera_pose_visual
Value: false
Enabled: true
Name: Odometry
- Class: rviz_common/Group
Displays:
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz_default_plugins/PointCloud2
Color: 255; 255; 255
Color Transformer: RGB8
Decay Time: 0
Enabled: true
Invert Rainbow: false
Max Color: 255; 255; 255
Max Intensity: 4096
Min Color: 0; 0; 0
Min Intensity: 0
Name: slam_current
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.009999999776482582
Style: Points
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/cloud_slam
Use Fixed Frame: true
Use rainbow: true
Value: true
- Alpha: 0.10000000149011612
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz_default_plugins/PointCloud2
Color: 255; 255; 255
Color Transformer: RGB8
Decay Time: 10
Enabled: false
Invert Rainbow: false
Max Color: 255; 255; 255
Max Intensity: 4096
Min Color: 0; 0; 0
Min Intensity: 0
Name: slam_deacy
Position Transformer: XYZ
Selectable: true
Size (Pixels): 1
Size (m): 0.009999999776482582
Style: Points
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/cloud_slam
Use Fixed Frame: true
Use rainbow: true
Value: false
- Class: rviz_default_plugins/MarkerArray
Enabled: false
Name: path
Namespaces:
{}
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/path
Value: false
Enabled: true
Name: slam
- Class: rviz_common/Group
Displays:
- Class: rviz_default_plugins/Image
Enabled: true
Max Value: 1
Median window: 5
Min Value: 0
Name: dense_depth_image
Normalize Range: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/depth_img_competetion
Value: true
- Alpha: 1
Autocompute Intensity Bounds: true
Autocompute Value Bounds:
Max Value: 10
Min Value: -10
Value: true
Axis: Z
Channel Name: intensity
Class: rviz_default_plugins/PointCloud2
Color: 255; 255; 255
Color Transformer: RGB8
Decay Time: 0
Enabled: false
Invert Rainbow: false
Max Color: 255; 255; 255
Max Intensity: 4096
Min Color: 0; 0; 0
Min Intensity: 0
Name: dense_depth_cloud
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.009999999776482582
Style: Flat Squares
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Reliable
Value: /odin1/depth_img_competetion_cloud
Use Fixed Frame: true
Use rainbow: true
Value: false
Enabled: false
Name: dense_depth_demo
- Class: rviz_default_plugins/TF
Enabled: true
Frame Timeout: 15
Frames:
All Enabled: true
imu:
Value: true
odom:
Value: true
Marker Scale: 1
Name: TF
Show Arrows: true
Show Axes: true
Show Names: false
Tree:
odom:
imu:
{}
Update Interval: 0
Value: true
Enabled: true
Global Options:
Background Color: 48; 48; 48
Fixed Frame: odom
Frame Rate: 30
Name: root
Tools:
- Class: rviz_default_plugins/Interact
Hide Inactive Objects: true
- Class: rviz_default_plugins/MoveCamera
- Class: rviz_default_plugins/Select
- Class: rviz_default_plugins/FocusCamera
- Class: rviz_default_plugins/Measure
Line color: 128; 128; 0
- Class: rviz_default_plugins/SetInitialPose
Covariance x: 0.25
Covariance y: 0.25
Covariance yaw: 0.06853891909122467
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /initialpose
- Class: rviz_default_plugins/SetGoal
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /goal_pose
- Class: rviz_default_plugins/PublishPoint
Single click: true
Topic:
Depth: 5
Durability Policy: Volatile
History Policy: Keep Last
Reliability Policy: Reliable
Value: /clicked_point
Transformation:
Current:
Class: rviz_default_plugins/TF
Value: true
Views:
Current:
Class: rviz_default_plugins/Orbit
Distance: 10.9336576461792
Enable Stereo Rendering:
Stereo Eye Separation: 0.05999999865889549
Stereo Focal Distance: 1
Swap Stereo Eyes: false
Value: false
Focal Point:
X: 0.2568470537662506
Y: 2.1451337337493896
Z: 0.3774382472038269
Focal Shape Fixed Size: false
Focal Shape Size: 0.05000000074505806
Invert Z Axis: false
Name: Current View
Near Clip Distance: 0.009999999776482582
Pitch: 0.3953983187675476
Target Frame: odom
Value: Orbit (rviz)
Yaw: 3.230407953262329
Saved: ~
Window Geometry:
Displays:
collapsed: false
Height: 1016
Hide Left Dock: false
Hide Right Dock: false
Image:
collapsed: false
Image_undistort:
collapsed: false
QMainWindow State: 000000ff00000000fd0000000400000000000001d40000039efc020000000cfb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000a3fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003d0000028e000000c900fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261fb0000000a0049006d00610067006501000002d10000010a0000002800fffffffb0000002200640065006e00730065005f00640065007000740068005f0069006d006100670065000000023e0000007a0000002800fffffffb0000001e0049006d006100670065005f0075006e0064006900730074006f00720074000000028f0000014c0000002800fffffffb0000002a0063006c006f007500640073006c0061006d005f0072006500700072006f006a006500630074006500640000000310000000cb0000002800ffffff000000010000010f0000039efc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073010000003d0000039e000000a400fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000004420000003efc0100000002fb0000000800540069006d00650100000000000004420000000000000000fb0000000800540069006d00650100000000000004500000000000000000000004910000039e00000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000
Selection:
collapsed: false
Tool Properties:
collapsed: false
Views:
collapsed: false
Width: 1920
X: 540
Y: 124
cloudslam_reprojected:
collapsed: false
dense_depth_image:
collapsed: false
@@ -0,0 +1,167 @@
# Runtime Service and Parameter Operations / 运行时服务与参数操作
This document describes how to control the Odin ROS driver at runtime through `set_param.sh` and ROS services.
本文档说明如何通过 `set_param.sh` 命令文件和 ROS Service 在运行时控制 Odin ROS driver。
---
## 1. set_param.sh (Command File) / 命令文件
`set_param.sh` writes a `set <key> <value>` line to `/tmp/odin_command.txt`. The driver polls this file every second and executes the command.
`set_param.sh` 会把 `set <key> <value>` 写入 `/tmp/odin_command.txt`,driver 每秒轮询该文件并执行。
```shell
# Save map / 保存地图
./set_param.sh save_map 1
# Reset algorithm / 复位算法
./set_param.sh algo_reset 1
# Unknown keys are rejected by the device with an error / 未知键会被设备拒绝并报错
./set_param.sh map 1 # ERROR: "map" is not a valid device parameter
```
### Supported command parameters / 支持的命令参数
| Parameter / 参数 | Accepted values / 取值 | Description / 说明 |
|---|---|---|
| `save_map` | `0` or `1` | `1` triggers map saving in background; `0` sets the parameter to 0. `1` 在后台触发地图保存,`0` 设置参数为 0。 |
| `algo_reset` | `0` or `1` | Sends the `algo_reset` command to the device. 向设备发送 `algo_reset` 命令。 |
| `spad_filter` | `0` or `1` | Enables/disables the host-side SPAD crosstalk filter. 启用/禁用主机端 SPAD 串扰滤波。 |
---
## 2. ROS Services / ROS 服务
The driver registers the following services while running. All services return `success` (bool) and `rc` (int32). Device must be connected before calling, otherwise `rc = -100` is returned.
driver 运行期间注册以下服务。所有服务返回 `success` (bool) 和 `rc` (int32)。调用前设备必须已连接,否则返回 `rc = -100`。
### 2.1 AE/AWB Services / AE/AWB 服务
See `README.md` section `4.6` for `/odin1/get_ae`, `/odin1/get_awb`, `/odin1/set_ae`, `/odin1/set_awb`.
AE/AWB 服务 `/odin1/get_ae`、`/odin1/get_awb`、`/odin1/set_ae`、`/odin1/set_awb` 详见 `README.md` 4.6 节。
### 2.2 Device Log Retrieval / 设备日志获取
**Service / 服务**: `/odin1/get_device_logs`
**Type / 类型**: `odin_ros_driver/srv/GetDeviceLogs`
**Request / 请求**
| Field | Type | Description / 说明 |
|---|---|---|
| `dest_dir` | `string` | Destination directory for the device log archive. 设备日志压缩包保存目录。 |
**Response / 响应**
| Field | Type | Description / 说明 |
|---|---|---|
| `success` | `bool` | `true` if `rc == 0`. 当 `rc == 0` 时为 true。 |
| `rc` | `int32` | `0`=ok, `-1`=invalid args, `-2`=transfer in progress, `-3`=timeout/stall. |
**Usage / 调用**
ROS2:
```bash
ros2 service call /odin1/get_device_logs odin_ros_driver/srv/GetDeviceLogs '{dest_dir: "/tmp/odin_logs"}'
```
ROS1:
```bash
rosservice call /odin1/get_device_logs '{dest_dir: "/tmp/odin_logs"}'
```
### 2.3 Save Map / 保存地图
**Service / 服务**: `/odin1/save_map`
**Type / 类型**: `odin_ros_driver/srv/SaveMap`
**Request / 请求**
| Field | Type | Description / 说明 |
|---|---|---|
| `value` | `int32` | `1` triggers map saving in background. Other values are forwarded as the `save_map` custom parameter. `1` 在后台触发地图保存,其他值转发为 `save_map` 自定义参数。 |
**Response / 响应**
| Field | Type | Description / 说明 |
|---|---|---|
| `success` | `bool` | `true` if the request was accepted. 请求被接受时为 true。 |
| `rc` | `int32` | `0`=ok, `-2`=another map transfer already in progress. |
**Usage / 调用**
ROS2:
```bash
ros2 service call /odin1/save_map odin_ros_driver/srv/SaveMap '{value: 1}'
```
ROS1:
```bash
rosservice call /odin1/save_map '{value: 1}'
```
When `value = 1`, the driver builds the output path from `mapping_result_dest_dir` and `mapping_result_file_name` in `config/control_command.yaml`, then starts a background transfer. Progress is printed in the driver log.
`value = 1` 时,driver 根据 `config/control_command.yaml` 中的 `mapping_result_dest_dir` 和 `mapping_result_file_name` 构建输出路径,然后在后台开始传输,进度会打印在 driver 日志中。
### 2.4 Reset Algorithm / 复位算法
**Service / 服务**: `/odin1/reset_algo`
**Type / 类型**: `odin_ros_driver/srv/ResetAlgo`
**Request / 请求**
| Field | Type | Description / 说明 |
|---|---|---|
| `value` | `int32` | `1` sends the `algo_reset` command. `1` 发送 `algo_reset` 命令。 |
**Response / 响应**
| Field | Type | Description / 说明 |
|---|---|---|
| `success` | `bool` | `true` if `rc == 0`. |
| `rc` | `int32` | SDK return code from `lidar_set_custom_parameter`. `lidar_set_custom_parameter` 的返回码。 |
**Usage / 调用**
ROS2:
```bash
ros2 service call /odin1/reset_algo odin_ros_driver/srv/ResetAlgo '{value: 1}'
```
ROS1:
```bash
rosservice call /odin1/reset_algo '{value: 1}'
```
---
## 3. Return Code Convention / 返回码说明
All services and command-file operations share the same `rc` convention where applicable:
| `rc` | Meaning / 含义 |
|---|---|
| `0` | Success / 成功 |
| `-1` | Invalid arguments / 参数无效 |
| `-2` | Another transfer already in progress / 另一次传输正在进行 |
| `-3` | Transfer timeout or stalled / 传输超时或卡死 |
| `-100` | Driver has not connected to the device yet / driver 尚未连接到设备 |
---
## 4. Configuration Parameters / 配置参数
Parameters related to runtime operations in `config/control_command.yaml`:
| Parameter / 参数 | Description / 说明 |
|---|---|
| `custom_map_mode` | `0` = Odometry, `1` = SLAM (supports `save_map`), `2` = Relocalization. `0` 里程计模式,`1` SLAM 建图模式(支持 `save_map`),`2` 重定位模式。 |
| `mapping_result_dest_dir` | Directory for saved maps. 保存地图的目录。 |
| `mapping_result_file_name` | File name for saved map. 保存地图的文件名。 |
| `relocalization_map_abs_path` | Absolute path to pre-built map for relocalization. 重定位所需的预建地图绝对路径。 |
@@ -0,0 +1,78 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#ifdef ROS2
#include <rclcpp/rclcpp.hpp>
#include <std_msgs/msg/color_rgba.hpp>
#include <std_msgs/msg/header.hpp>
#include <visualization_msgs/msg/marker.hpp>
#include <visualization_msgs/msg/marker_array.hpp>
#else
#include <ros/ros.h>
#include <std_msgs/ColorRGBA.h>
#include <std_msgs/Header.h>
#include <visualization_msgs/Marker.h>
#include <visualization_msgs/MarkerArray.h>
#endif
#include <Eigen/Dense>
#include <Eigen/Geometry>
class camera_pose_visualization {
public:
std::string m_marker_ns;
camera_pose_visualization(float r, float g, float b, float a);
void setImageBoundaryColor(float r, float g, float b, float a = 1.0);
void setOpticalCenterConnectorColor(float r, float g, float b, float a = 1.0);
void setScale(double s);
void setLineWidth(double width);
void add_pose(const Eigen::Vector3d& p, const Eigen::Quaterniond& q);
void reset();
#ifdef ROS2
using ColorRGBA = std_msgs::msg::ColorRGBA;
using Marker = visualization_msgs::msg::Marker;
using MarkerArray = visualization_msgs::msg::MarkerArray;
using Header = std_msgs::msg::Header;
using Publisher = rclcpp::Publisher<MarkerArray>;
#else
using ColorRGBA = std_msgs::ColorRGBA;
using Marker = visualization_msgs::Marker;
using MarkerArray = visualization_msgs::MarkerArray;
using Header = std_msgs::Header;
using Publisher = ros::Publisher;
#endif
void publish_by(Publisher& pub, const Header& header);
void add_edge(const Eigen::Vector3d& p0, const Eigen::Vector3d& p1);
void add_loopedge(const Eigen::Vector3d& p0, const Eigen::Vector3d& p1);
private:
std::vector<Marker> m_markers;
ColorRGBA m_image_boundary_color;
ColorRGBA m_optical_center_connector_color;
double m_scale;
double m_line_width;
static const Eigen::Vector3d imlt;
static const Eigen::Vector3d imlb;
static const Eigen::Vector3d imrt;
static const Eigen::Vector3d imrb;
static const Eigen::Vector3d oc ;
static const Eigen::Vector3d lt0 ;
static const Eigen::Vector3d lt1 ;
static const Eigen::Vector3d lt2 ;
};
@@ -0,0 +1,122 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#ifdef ROS2
#include <rclcpp/rclcpp.hpp>
#include <sensor_msgs/msg/point_cloud2.hpp>
#include <sensor_msgs/msg/image.hpp>
#include <nav_msgs/msg/odometry.hpp>
#include <image_transport/image_transport.hpp>
// cv_bridge header: ROS2 humble+ provides cv_bridge.hpp; ROS2 jazzy removes the legacy .h.
// Prefer .hpp when available, fall back to .h for older ROS distros (e.g. foxy/galactic).
#if defined(__has_include)
# if __has_include(<cv_bridge/cv_bridge.hpp>)
# include <cv_bridge/cv_bridge.hpp>
# else
# include <cv_bridge/cv_bridge.h>
# endif
#else
# include <cv_bridge/cv_bridge.h>
#endif
#include <message_filters/subscriber.h>
#include <message_filters/time_synchronizer.h>
#include <message_filters/sync_policies/exact_time.h>
#include <message_filters/sync_policies/approximate_time.h>
#else
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/Image.h>
#include <nav_msgs/Odometry.h>
#include <cv_bridge/cv_bridge.h>
#include <message_filters/subscriber.h>
#include <message_filters/time_synchronizer.h>
#include <message_filters/sync_policies/exact_time.h>
#include <message_filters/sync_policies/approximate_time.h>
#endif
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include "cloud_reprojector.hpp"
#include <string>
#include <memory>
#ifdef ROS2
class CloudReprojectionRosNode : public rclcpp::Node
{
public:
CloudReprojectionRosNode(const rclcpp::NodeOptions& options = rclcpp::NodeOptions());
private:
using PointCloud2 = sensor_msgs::msg::PointCloud2;
using Odometry = nav_msgs::msg::Odometry;
using Image = sensor_msgs::msg::Image;
std::string cloud_slam_topic_;
std::string odometry_topic_;
std::string wiwc_topic_;
std::string reprojected_image_topic_;
message_filters::Subscriber<PointCloud2> cloud_sub_;
message_filters::Subscriber<Odometry> odom_sub_;
message_filters::Subscriber<Odometry> wiwc_sub_;
typedef message_filters::sync_policies::ApproximateTime<PointCloud2, Odometry, Odometry> MySyncPolicy;
typedef message_filters::Synchronizer<MySyncPolicy> Sync;
std::shared_ptr<Sync> sync_;
image_transport::Publisher reprojected_image_pub_;
std::unique_ptr<CloudReprojector> reprojector_;
void loadParameters();
void syncCallback(const PointCloud2::ConstSharedPtr& cloud_msg,
const Odometry::ConstSharedPtr& odom_msg,
const Odometry::ConstSharedPtr& wiwc_msg);
};
#else
class CloudReprojectionRosNode
{
public:
CloudReprojectionRosNode(ros::NodeHandle& nh, ros::NodeHandle& pnh);
private:
ros::NodeHandle nh_, pnh_;
std::string cloud_slam_topic_;
std::string odometry_topic_;
std::string wiwc_topic_;
std::string reprojected_image_topic_;
message_filters::Subscriber<sensor_msgs::PointCloud2> cloud_sub_;
message_filters::Subscriber<nav_msgs::Odometry> odom_sub_;
message_filters::Subscriber<nav_msgs::Odometry> wiwc_sub_;
typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::PointCloud2, nav_msgs::Odometry, nav_msgs::Odometry> MySyncPolicy;
typedef message_filters::Synchronizer<MySyncPolicy> Sync;
std::shared_ptr<Sync> sync_;
ros::Publisher reprojected_image_pub_;
std::unique_ptr<CloudReprojector> reprojector_;
void loadParameters();
void syncCallback(const sensor_msgs::PointCloud2ConstPtr& cloud_msg,
const nav_msgs::OdometryConstPtr& odom_msg,
const nav_msgs::OdometryConstPtr& wiwc_msg);
};
#endif
@@ -0,0 +1,86 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <Eigen/Dense>
#include <Eigen/Geometry>
#include <opencv2/opencv.hpp>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/common/transforms.h>
#include "polynomial_camera.hpp"
#include <memory>
class CloudReprojector
{
public:
struct CameraParams
{
int image_width = 1600;
int image_height = 1296;
double A11 = 0.0, A12 = 0.0, A22 = 0.0;
double u0 = 0.0, v0 = 0.0;
double k2 = 0.0, k3 = 0.0, k4 = 0.0, k5 = 0.0, k6 = 0.0, k7 = 0.0;
};
struct ExtrinsicParams
{
Eigen::Matrix4d Tcl = Eigen::Matrix4d::Identity(); // camera to lidar
Eigen::Matrix4d Til = Eigen::Matrix4d::Identity(); // lidar to imu (fixed)
Eigen::Matrix4d Tic = Eigen::Matrix4d::Identity(); // camera to imu (calculated)
};
struct OdomPose
{
Eigen::Quaterniond orientation = Eigen::Quaterniond::Identity();
Eigen::Vector3d position = Eigen::Vector3d::Zero();
};
CloudReprojector();
~CloudReprojector() = default;
bool initialize(const CameraParams& cam_params, const ExtrinsicParams& ext_params);
cv::Mat reprojectCloud(const pcl::PointCloud<pcl::PointXYZRGB>& cloud_odom,
const OdomPose& odom_pose);
void setPointRadius(int radius) { point_radius_ = radius; }
int getPointRadius() const { return point_radius_; }
const CameraParams& getCameraParams() const { return camera_params_; }
const ExtrinsicParams& getExtrinsicParams() const { return extrinsic_params_; }
// Update extrinsic parameters at runtime with real-time values from module
void updateExtrinsics(const Eigen::Matrix4d& Tcl, const Eigen::Matrix4d& Til) {
extrinsic_params_.Tcl = Tcl;
extrinsic_params_.Til = Til;
extrinsic_params_.Tic = calculateTic(Tcl, Til);
}
static Eigen::Matrix4d calculateTic(const Eigen::Matrix4d& Tcl, const Eigen::Matrix4d& Til);
private:
Eigen::Matrix4d odomPoseToMatrix(const OdomPose& odom) const;
cv::Mat projectCloudToImage(const pcl::PointCloud<pcl::PointXYZRGB>& cloud_in_cam) const;
CameraParams camera_params_;
ExtrinsicParams extrinsic_params_;
std::unique_ptr<mini_vikit::PolynomialCamera> camera_model_;
int point_radius_ = 4;
bool initialized_ = false;
};
@@ -0,0 +1,240 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <deque>
#include <filesystem>
#include <fstream>
#include <chrono>
#include <memory>
#include <cstdlib>
#include <ctime>
#include <sstream>
class BinaryDataLogger {
public:
struct Options {
public:
// Number of frames per batch before flushing to disk
size_t batch_size = 20;
// Base directory to place time-stamped run directory under
// If empty, will use $ODIN_DATA_DIR or default to $HOME/OdinData
std::filesystem::path base_dir;
};
explicit BinaryDataLogger(const Options& opts) {
namespace fs = std::filesystem;
// Determine base dir
fs::path base = opts.base_dir;
if (base.empty()) {
const char* env_dir = std::getenv("ODIN_DATA_DIR");
if (env_dir && *env_dir) {
base = fs::path(env_dir);
} else {
const char* home = std::getenv("HOME");
base = home && *home ? fs::path(home) / "OdinData" : fs::current_path() / "OdinData";
}
}
// Make timestamp folder name: YYYYMMDD_HHMMSS
auto now = std::chrono::system_clock::now();
std::time_t t = std::chrono::system_clock::to_time_t(now);
std::tm tm{};
#ifdef _WIN32
localtime_s(&tm, &t);
#else
localtime_r(&t, &tm);
#endif
char buf[32];
std::strftime(buf, sizeof(buf), "%Y%m%d_%H%M%S", &tm);
root_dir_ = base / buf;
fs::create_directories(root_dir_);
fs::create_directories(root_dir_ / "image");
// Convert to std::string
std::string timestamp(buf);
created_at_ = timestamp;
// Compose file name
std::filesystem::path pcFile = root_dir_ / ("MT" + timestamp + ".olx");
// Create placeholder files (device_id / firmware / algorithm filled later via update_info_file)
write_info_file_unlocked();
write_text_file(root_dir_ / "image" / "cam_in_ex.txt", "# camera intrinsics/extrinsics TBD\n");
// Init writers
pose_writer_ = std::make_unique<Writer>(root_dir_ / "OdinPose.bin", opts.batch_size);
cloud_writer_ = std::make_unique<Writer>(pcFile, opts.batch_size);
//cloud_writer_ = std::make_unique<Writer>(root_dir_ / "OdinPointCloud.olx", opts.batch_size);
image_writer_ = std::make_unique<Writer>(root_dir_ / "OdinImage.bin", opts.batch_size);
roatation_writer_ = std::make_unique<Writer>(root_dir_ / "OdinRotate.bin", opts.batch_size);
imu_writer_ = std::make_unique<Writer>(root_dir_ / "OdinIMU.bin", opts.batch_size);
}
~BinaryDataLogger() {
// Ensure all writers flush on destruction
if (pose_writer_) pose_writer_->shutdown();
if (cloud_writer_) cloud_writer_->shutdown();
if (image_writer_) image_writer_->shutdown();
if (roatation_writer_) roatation_writer_->shutdown();
if (imu_writer_) imu_writer_->shutdown();
}
const std::filesystem::path& root_dir() const { return root_dir_; }
// Update info.txt with device_id (SN) / firmware (SoC) / algorithm version.
// Safe to call multiple times; latest values win.
void update_info_file(const std::string& device_id,
const std::string& firmware_version,
const std::string& algorithm_version) {
std::lock_guard<std::mutex> lk(info_mtx_);
device_id_ = device_id;
firmware_version_ = firmware_version;
algorithm_version_ = algorithm_version;
write_info_file_unlocked();
}
// Enqueue ready-to-write frame blobs (already formatted as per spec)
void enqueuePoseFrame(std::vector<uint8_t>&& blob) {
if (pose_writer_) pose_writer_->enqueue(std::move(blob));
}
void enqueuePointCloudFrame(std::vector<uint8_t>&& blob) {
if (cloud_writer_) cloud_writer_->enqueue(std::move(blob));
}
void enqueueImageFrame(std::vector<uint8_t>&& blob) {
if (image_writer_) image_writer_->enqueue(std::move(blob));
}
void enqueueRotateFrame(std::vector<uint8_t>&& blob) {
if (roatation_writer_) roatation_writer_->enqueue(std::move(blob));
}
void enqueueIMUFrame(std::vector<uint8_t>&& blob) {
if (imu_writer_) imu_writer_->enqueue(std::move(blob));
}
private:
struct Writer {
explicit Writer(const std::filesystem::path& filepath, size_t batch)
: file_path(filepath), batch_size(batch), stop(false) {
worker = std::thread([this]() { this->run(); });
}
~Writer() {
shutdown();
}
void enqueue(std::vector<uint8_t>&& frame) {
{
std::lock_guard<std::mutex> lk(mtx);
pending.emplace_back(std::move(frame));
if (pending.size() >= batch_size) {
swap_pending_unlocked();
}
}
cv.notify_one();
}
void shutdown() {
{
std::lock_guard<std::mutex> lk(mtx);
if (stop) return;
// Move leftovers to write buffer
if (!pending.empty()) {
swap_pending_unlocked();
}
stop = true;
}
cv.notify_one();
if (worker.joinable()) worker.join();
}
private:
void swap_pending_unlocked() {
if (!pending.empty()) {
write_queue.emplace_back(std::move(pending));
pending.clear();
}
}
void run() {
std::ofstream out(file_path, std::ios::binary | std::ios::app);
if (!out.is_open()) {
// If file can't be opened, silently drop (or could add logging hook)
return;
}
for (;;) {
std::vector<std::vector<uint8_t>> batch;
{
std::unique_lock<std::mutex> lk(mtx);
cv.wait(lk, [&]{ return stop || !write_queue.empty(); });
if (!write_queue.empty()) {
batch = std::move(write_queue.front());
write_queue.pop_front();
} else if (stop) {
break;
}
}
if (!batch.empty()) {
for (auto& frame : batch) {
if (!frame.empty()) {
out.write(reinterpret_cast<const char*>(frame.data()), static_cast<std::streamsize>(frame.size()));
}
}
out.flush();
}
}
}
std::filesystem::path file_path;
size_t batch_size;
std::mutex mtx;
std::condition_variable cv;
std::vector<std::vector<uint8_t>> pending; // accumulate frames
std::deque<std::vector<std::vector<uint8_t>>> write_queue; // queued batches
std::thread worker;
bool stop;
};
static void write_text_file(const std::filesystem::path& p, const std::string& content) {
std::ofstream f(p, std::ios::out | std::ios::trunc);
if (f.is_open()) {
f << content;
}
}
// Render info.txt from current member fields. Caller must hold info_mtx_.
void write_info_file_unlocked() {
std::ostringstream oss;
oss << "device=OdinOne\n"
<< "pointcloud=xyzrgbi\n";
if (!device_id_.empty()) {
oss << "device_id=" << device_id_ << "\n";
}
if (!firmware_version_.empty()) {
oss << "firmware_version=" << firmware_version_ << "\n";
}
if (!algorithm_version_.empty()) {
oss << "algorithm_version=" << algorithm_version_ << "\n";
}
oss << "created_at=" << created_at_ << "\n";
write_text_file(root_dir_ / "image" / "info.txt", oss.str());
}
std::filesystem::path root_dir_;
std::string created_at_;
std::string device_id_;
std::string firmware_version_;
std::string algorithm_version_;
std::mutex info_mtx_;
std::unique_ptr<Writer> pose_writer_;
std::unique_ptr<Writer> cloud_writer_;
std::unique_ptr<Writer> image_writer_;
std::unique_ptr<Writer> roatation_writer_;
std::unique_ptr<Writer> imu_writer_;
};
@@ -0,0 +1,95 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <rclcpp/rclcpp.hpp>
#include <sensor_msgs/msg/point_cloud2.hpp>
#include <sensor_msgs/msg/image.hpp>
#include <sensor_msgs/msg/compressed_image.hpp>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <opencv2/opencv.hpp>
// cv_bridge header: ROS2 humble+ provides cv_bridge.hpp; ROS2 jazzy removes the legacy .h.
// Prefer .hpp when available, fall back to .h for older ROS distros (e.g. foxy/galactic).
#if defined(__has_include)
# if __has_include(<cv_bridge/cv_bridge.hpp>)
# include <cv_bridge/cv_bridge.hpp>
# else
# include <cv_bridge/cv_bridge.h>
# endif
#else
# include <cv_bridge/cv_bridge.h>
#endif
#include <image_transport/image_transport.hpp>
#include <message_filters/subscriber.h>
#include <message_filters/time_synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <Eigen/Dense>
#include "pointcloud_depth_converter.hpp"
#include <string>
#include <memory>
class DepthImageRos2Node : public rclcpp::Node
{
public:
explicit DepthImageRos2Node(const rclcpp::NodeOptions & options = rclcpp::NodeOptions());
void initialize();
private:
std::string cloud_raw_topic_;
std::string color_compressed_topic_;
std::string color_raw_topic_;
std::string depth_image_topic_;
std::string depth_cloud_topic_;
message_filters::Subscriber<sensor_msgs::msg::PointCloud2> cloud_sub_;
message_filters::Subscriber<sensor_msgs::msg::CompressedImage> color_compressed_sub_;
message_filters::Subscriber<sensor_msgs::msg::Image> color_sub_;
typedef message_filters::sync_policies::ApproximateTime<
sensor_msgs::msg::PointCloud2,
// sensor_msgs::msg::CompressedImage,
sensor_msgs::msg::Image> MySyncPolicy;
typedef message_filters::Synchronizer<MySyncPolicy> Sync;
std::shared_ptr<Sync> sync_;
std::shared_ptr<image_transport::ImageTransport> it_;
image_transport::Publisher depth_image_pub_;
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr depth_cloud_pub_;
std::unique_ptr<PointCloudToDepthConverter> depth_converter_;
PointCloudToDepthConverter::CameraParams loadCameraParams();
void syncCallback(const sensor_msgs::msg::PointCloud2::ConstSharedPtr cloud_msg,
// const sensor_msgs::msg::CompressedImage::ConstSharedPtr image_msg,
const sensor_msgs::msg::Image::ConstSharedPtr color_msg);
void publishDepthImage(const cv::Mat &img,
const std_msgs::msg::Header &header,
const std::string &encoding = "32FC1");
void publishDepthCloud(const pcl::PointCloud<pcl::PointXYZRGB> &colored_cloud,
const std_msgs::msg::Header &header);
};
@@ -0,0 +1,83 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CompressedImage.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <opencv2/opencv.hpp>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <message_filters/subscriber.h>
#include <message_filters/time_synchronizer.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <Eigen/Dense>
#include "pointcloud_depth_converter.hpp"
#include <string>
#include <memory>
class DepthImageRosNode
{
public:
DepthImageRosNode(ros::NodeHandle &nh, ros::NodeHandle &pnh);
private:
ros::NodeHandle nh_, pnh_;
image_transport::ImageTransport it_;
std::string cloud_raw_topic_;
std::string color_raw_topic_;
std::string color_compressed_topic_;
std::string depth_image_topic_;
std::string depth_cloud_topic_;
message_filters::Subscriber<sensor_msgs::PointCloud2> cloud_sub_;
message_filters::Subscriber<sensor_msgs::Image> color_sub_;
message_filters::Subscriber<sensor_msgs::CompressedImage> color_compressed_sub_;
typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::PointCloud2, sensor_msgs::Image> MySyncPolicy;
typedef message_filters::Synchronizer<MySyncPolicy> Sync;
std::shared_ptr<Sync> sync_;
image_transport::Publisher depth_image_pub_;
ros::Publisher depth_cloud_pub_;
std::unique_ptr<PointCloudToDepthConverter> depth_converter_;
PointCloudToDepthConverter::CameraParams loadCameraParams();
void syncCallback(const sensor_msgs::PointCloud2ConstPtr &cloud_msg,
const sensor_msgs::ImageConstPtr &image_msg);
void publishDepthImage(const cv::Mat &img,
const std_msgs::Header &header,
const std::string &encoding = "32FC1");
void publishDepthCloud(const pcl::PointCloud<pcl::PointXYZRGB> &colored_cloud,
const std_msgs::Header &header);
};
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,101 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#ifdef ROS2
#include <rclcpp/rclcpp.hpp>
#include <sensor_msgs/msg/image.hpp>
// cv_bridge header: ROS2 humble+ provides cv_bridge.hpp; ROS2 jazzy removes the legacy .h.
// Prefer .hpp when available, fall back to .h for older ROS distros (e.g. foxy/galactic).
#if defined(__has_include)
# if __has_include(<cv_bridge/cv_bridge.hpp>)
# include <cv_bridge/cv_bridge.hpp>
# else
# include <cv_bridge/cv_bridge.h>
# endif
#else
# include <cv_bridge/cv_bridge.h>
#endif
#include <mutex>
#else
#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <cv_bridge/cv_bridge.h>
#include <message_filters/subscriber.h>
#include <message_filters/sync_policies/approximate_time.h>
#include <message_filters/synchronizer.h>
#endif
#include <opencv2/opencv.hpp>
#include <string>
#include <memory>
#ifdef ROS2
class ImageOverlayNode : public rclcpp::Node
{
public:
ImageOverlayNode(const rclcpp::NodeOptions& options = rclcpp::NodeOptions());
private:
using Image = sensor_msgs::msg::Image;
std::string reprojected_topic_;
std::string camera_topic_;
std::string overlay_topic_;
double alpha_; // blend alpha for overlay
rclcpp::Subscription<Image>::SharedPtr reproj_sub_;
rclcpp::Subscription<Image>::SharedPtr camera_sub_;
rclcpp::Publisher<Image>::SharedPtr overlay_pub_;
// Cache latest images
cv::Mat latest_reproj_img_;
cv::Mat latest_camera_img_;
std_msgs::msg::Header latest_header_;
std::mutex mutex_;
void reprojCallback(Image::ConstSharedPtr msg);
void cameraCallback(Image::ConstSharedPtr msg);
void publishOverlay();
};
#else
#include <mutex>
class ImageOverlayNode
{
public:
ImageOverlayNode(ros::NodeHandle& nh, ros::NodeHandle& pnh);
private:
ros::NodeHandle nh_, pnh_;
std::string reprojected_topic_;
std::string camera_topic_;
std::string overlay_topic_;
double alpha_; // blend alpha for overlay
ros::Subscriber reproj_sub_;
ros::Subscriber camera_sub_;
ros::Publisher overlay_pub_;
// Cache latest images
cv::Mat latest_reproj_img_;
cv::Mat latest_camera_img_;
std_msgs::Header latest_header_;
std::mutex mutex_;
void reprojCallback(const sensor_msgs::ImageConstPtr& msg);
void cameraCallback(const sensor_msgs::ImageConstPtr& msg);
void publishOverlay();
};
#endif
@@ -0,0 +1,803 @@
#ifndef LIDAR_API_H
#define LIDAR_API_H
/**
* @file lidar_api.h
* @brief LiDAR device API for controlling and accessing LiDAR sensor data
*
* This header provides the public interface for interacting with LiDAR devices.
* It includes functions for device management, data streaming control, and
* device configuration.
*
* @copyright Copyright (c) 2025, Manifold Tech Limited, All Rights Reserved
* @version 1.0
*
* ┌──────────────────────────────────────────────────────────────────────────────┐
* │ QUICK START │
* ├──────────────────────────────────────────────────────────────────────────────┤
* │ 1. API Call Sequence (typical usage): │
* │ │
* │ lidar_system_init(device_cb) // Initialize system, register device cb│
* │ ↓ │
* │ [Wait for device_cb with attach=true to get device info] │
* │ ↓ │
* │ lidar_create_device(&dev_info, &handle) // Create device handle │
* │ ↓ │
* │ lidar_register_stream_callback(handle, cb_info) // Register data callback│
* │ ↓ │
* │ lidar_open_device(handle) // Connect to device │
* │ ↓ │
* │ lidar_set_mode(handle, mode) // Set RAW or SLAM mode │
* │ ↓ │
* │ lidar_start_stream(handle, type, odr) // Start specific data stream │
* │ ↓ │
* │ [Data arrives via registered callback] │
* │ ↓ │
* │ lidar_stop_stream(handle, type) // Stop data stream │
* │ ↓ │
* │ lidar_close_device(handle) // Disconnect │
* │ ↓ │
* │ lidar_destory_device(handle) // Release device handle │
* │ ↓ │
* │ lidar_system_deinit() // Cleanup system resources │
* │ │
* ├──────────────────────────────────────────────────────────────────────────────┤
* │ 2. Operating Modes and Available Data Types: │
* │ │
* │ LIDAR_MODE_RAW: │
* │ - LIDAR_DT_RAW_RGB (RGB camera image, NV12 format) │
* │ - LIDAR_DT_RAW_IMU (IMU data at 400Hz) │
* │ - LIDAR_DT_RAW_DTOF (DTOF depth + point cloud + confidence) │
* │ - LIDAR_DT_DEV_STATUS (Device status info) │
* │ - LIDAR_DT_NTP (PTP/NTP sync data) │
* │ │
* │ LIDAR_MODE_SLAM: │
* │ - All RAW mode types, plus: │
* │ - LIDAR_DT_SLAM_CLOUD (SLAM point cloud, XYZRGBA) │
* │ - LIDAR_DT_SLAM_ODOMETRY (SLAM odometry at ~10Hz) │
* │ - LIDAR_DT_SLAM_ODOMETRY_HIGHFREQ (Odometry at IMU rate ~400Hz) │
* │ - LIDAR_DT_SLAM_ODOMETRY_TF (Map-Odom transform) │
* │ │
* ├──────────────────────────────────────────────────────────────────────────────┤
* │ 3. activate_stream_type vs start_stream: │
* │ │
* │ lidar_activate_stream_type(): │
* │ - Configure which stream types are enabled in device │
* │ - Can enable multiple types before starting │
* │ - Does NOT start data transmission │
* │ │
* │ lidar_start_stream(): │
* │ - Actually starts data transmission for the specified type │
* │ - Callback will begin receiving data after this call │
* │ │
* │ Typical flow: │
* │ activate_stream_type(LIDAR_DT_RAW_IMU); // Enable IMU │
* │ activate_stream_type(LIDAR_DT_RAW_DTOF); // Enable DTOF │
* │ start_stream(LIDAR_DT_RAW_IMU, ...); // Start IMU stream │
* │ start_stream(LIDAR_DT_RAW_DTOF, ...); // Start DTOF stream │
* │ │
* ├──────────────────────────────────────────────────────────────────────────────┤
* │ 4. Callback Notes (IMPORTANT): │
* │ │
* │ Thread Safety: │
* │ - Callbacks are invoked from internal SDK threads │
* │ - Different data types may use different threads │
* │ - User callback code must be thread-safe │
* │ │
* │ Data Lifetime: │
* │ - Data pointers (pAddr) are ONLY valid during callback execution │
* │ - If you need to keep data, COPY it before callback returns │
* │ - Do NOT store or dereference pAddr after callback returns │
* │ │
* │ Performance: │
* │ - Avoid blocking or time-consuming operations in callback │
* │ - Long callback execution may cause data loss or jitter │
* │ - For heavy processing, copy data and process in separate thread │
* │ │
* ├──────────────────────────────────────────────────────────────────────────────┤
* │ 5. Error Codes: │
* │ 0 : Success │
* │ -1 : General failure │
* │ -2 : Invalid parameter │
* │ -3 : Device not found / not connected │
* │ -4 : Operation timeout │
* │ -5 : Resource allocation failed │
* │ │
* └──────────────────────────────────────────────────────────────────────────────┘
*/
#include "lidar_api_type.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Initialize the LiDAR system
*
* Must be called before any other lidar function to set up the system resources.
* This function starts device discovery and will invoke the callback when devices
* are found or disconnected.
*
* @param cb Callback function for device events:
* - Called with attach=true when a new device is discovered
* - Called with attach=false when a device is disconnected
* - The lidar_device_info_t contains serial number to identify the device
*
* Example callback:
* void device_callback(const lidar_device_info_t* info, bool attach) {
* if (attach) {
* printf("Device connected: %s\n", info->serial);
* // Save info for lidar_create_device()
* } else {
* printf("Device disconnected: %s\n", info->serial);
* }
* }
*
* @return int 0 on success, negative error code on failure
*/
int lidar_system_init(lidar_device_callback_t cb);
/**
* @brief Deinitialize the LiDAR system
*
* Releases all resources allocated by the system. Should be called when
* application is shutting down.
*
* @return int 0 on success, negative error code on failure
*/
int lidar_system_deinit(void);
/**
* @brief Create a handle for a LiDAR device
*
* Creates a device handle using the device info received from the device callback.
* The handle is used for all subsequent operations on the device.
*
* @param dev_info Information about the LiDAR device (from lidar_system_init callback)
* - serial: Device serial number (required, used to identify device)
* - model: Device model string
* - online: Device connection status
* @param device [OUTPUT] Pointer to receive the device handle upon success
* @return int 0 on success, negative error code on failure
*
* @note The dev_info should be the same structure received from the device callback
*/
int lidar_create_device(lidar_device_info_t *dev_info, device_handle *device);
/**
* @brief Destroy a LiDAR device handle
*
* Releases resources associated with the device handle. Must be called
* when the device is no longer needed.
*
* @param device Handle to the device to destroy
* @return int 0 on success, negative error code on failure
*/
int lidar_destory_device(device_handle device);
/**
* @brief Register callback function for receiving LiDAR data streams
*
* Sets up a callback function that will be called when new data is available.
* All data types use the same callback; use lidar_data_t.type to distinguish.
*
* @param device Handle to the target device
* @param cb Callback info structure:
* - data_callback: Function pointer, signature: void(const lidar_data_t*, void*)
* - user_data: User context pointer passed to callback (can be NULL)
*
* Example:
* void data_callback(const lidar_data_t* data, void* user_data) {
* switch (data->type) {
* case LIDAR_DT_RAW_IMU:
* imu_convert_data_t* imu = (imu_convert_data_t*)data->stream.imageList[0].pAddr;
* // Process IMU data (COPY if needed, pointer invalid after return)
* break;
* case LIDAR_DT_RAW_DTOF:
* // data->stream.imageList[0]: depth
* // data->stream.imageList[1]: point cloud XYZ
* // data->stream.imageList[2]: confidence
* // data->stream.imageList[3]: intensity
* break;
* }
* }
*
* @return int 0 on success, negative error code on failure
*
* @warning Callback is invoked from SDK internal threads. Avoid blocking operations.
* @warning Data pointers are only valid during callback execution. Copy if needed.
*/
int lidar_register_stream_callback(device_handle device, lidar_data_callback_info_t cb);
/**
* @brief Unregister stream callback for a device
*
* Stops the device from calling back when new data is available.
*
* @param device Handle to the target device
* @return int 0 on success, negative error code on failure
*/
int lidar_unregister_stream_callback(device_handle device);
/**
* @brief Open a LiDAR device for communication
*
* Establishes a connection to the physical device.
*
* @param device Handle to the device to open
* @return int 0 on success, negative error code on failure
*/
int lidar_open_device(device_handle device);
/**
* @brief Close a LiDAR device
*
* Closes the connection to the physical device.
*
* @param device Handle to the device to close
* @return int 0 on success, negative error code on failure
*/
int lidar_close_device(device_handle device);
/**
* @brief Set the operating mode of the LiDAR device
*
* Must be called after lidar_open_device() and before lidar_start_stream().
* Mode determines which data types are available for streaming.
*
* @param device Handle to the target device
* @param mode Operating mode to set:
* - LIDAR_MODE_RAW: Raw sensor data (RGB, IMU, DTOF)
* - LIDAR_MODE_SLAM: SLAM processing enabled (adds odometry, point cloud)
* @return int 0 on success, negative error code on failure
*/
int lidar_set_mode(device_handle device, int mode);
/**
* @brief Start data streaming from the device
*
* Begins the flow of data from the device for the specified type.
* After calling this function, registered callbacks will start receiving data.
*
* @param device Handle to the target device
* @param type Type of data stream to start (lidar_data_type_e):
* - LIDAR_DT_RAW_RGB: RGB camera frames
* - LIDAR_DT_RAW_IMU: IMU data at 400Hz
* - LIDAR_DT_RAW_DTOF: Depth sensor data
* - LIDAR_DT_SLAM_CLOUD: SLAM point cloud (requires SLAM mode)
* - LIDAR_DT_SLAM_ODOMETRY: SLAM odometry (requires SLAM mode)
* - etc. (see lidar_data_type_e in lidar_api_type.h)
* @param dtof_subframe_odr [OUTPUT] Returns DTOF subframe interval in microseconds.
* Only meaningful when type=LIDAR_DT_RAW_DTOF.
* For other types, this value can be ignored.
* @return int 0 on success, negative error code on failure
*
* @note You can start multiple stream types simultaneously by calling this
* function multiple times with different types.
*/
int lidar_start_stream(device_handle device, int type, uint32_t &dtof_subframe_odr);
/**
* @brief Stop data streaming from the device
*
* Stops the flow of data from the device for the specified type.
*
* @param device Handle to the target device
* @param type Type of data stream to stop
* @return int 0 on success, negative error code on failure
*/
int lidar_stop_stream(device_handle device, int type);
/**
* @brief Activate a specific stream type on the device
*
* Enables a specific data stream type in the device configuration.
* This configures the device to be ready for the stream type, but does NOT
* start actual data transmission. Call lidar_start_stream() to begin streaming.
*
* Use this to pre-configure multiple stream types before starting them:
* activate_stream_type(handle, LIDAR_DT_RAW_IMU);
* activate_stream_type(handle, LIDAR_DT_RAW_DTOF);
* start_stream(handle, LIDAR_DT_RAW_IMU, odr);
* start_stream(handle, LIDAR_DT_RAW_DTOF, odr);
*
* @param device Handle to the target device
* @param type Type of data stream to activate (lidar_data_type_e)
* @return int 0 on success, negative error code on failure
*
* @see lidar_start_stream() to actually begin data transmission
* @see lidar_deactivate_stream_type() to disable a stream type
*/
int lidar_activate_stream_type(device_handle device, int type);
/**
* @brief Deactivate a specific stream type on the device
*
* Disables a specific data stream type in the device configuration.
*
* @param device Handle to the target device
* @param type Type of data stream to deactivate
* @return int 0 on success, negative error code on failure
*/
int lidar_deactivate_stream_type(device_handle device, int type);
/**
* @brief Get the calibration file from the device
* @param device Handle to the target device
* @return int 0 on success, negative error code on failure
*/
int lidar_get_calib_file(device_handle device, const char* path);
/**
* @brief Get device calibration parameters
*
* Retrieves the current calibration parameters from the device.
*
* @param device Handle to the target device
* @param param Pointer to receive the calibration parameters
* @return int 0 on success, negative error code on failure
*/
int lidar_get_calibration(device_handle device, lidar_calibration_t* param);
/**
* @brief Set device calibration parameters
*
* Applies new calibration parameters to the device.
*
* @param device Handle to the target device
* @param param Pointer to the calibration parameters to set
* @return int 0 on success, negative error code on failure
*/
int lidar_set_calibration(device_handle device, const lidar_calibration_t *param);
/**
* @brief Set log verbosity level
*
* Controls the amount of log information generated by the LiDAR API.
*
* @param level Log level to set (see level definitions in lidar_api_type.h)
*/
void lidar_log_set_level(lidar_log_level_e level);
/**
* @brief Get the version information of the LiDAR device
*
* Retrieves version information including firmware, system, and application versions.
*
* @param device Handle to the target device
* @param version struct Pointer to receive the version information
* @return int 0 on success, negative error code on failure
*/
int lidar_get_version(device_handle device,lidar_fireware_version_t *version);
/**
* @brief Set custom algorithm parameters for the device
*
* Sends custom parameter settings to the device.
*
* @param device Handle to the target device
* @param param_name String name of the parameter to set
* @param value_data Pointer to the value data to set for the parameter
* @param value_length Length of the value data in bytes
* @return int 0 on success, negative error code on failure
*/
int lidar_set_custom_parameter(device_handle device, const char* param_name, const void* value_data, size_t value_length);
/**
* @brief Get custom algorithm parameters for the device
*
* Get custom parameter settings from the device.
*
* @param device Handle to the target device
* @param param_name String name of the parameter to get
* @param value Integer value to get for the parameter
* @return int 0 on success, negative error code on failure
*/
int lidar_get_custom_parameter(device_handle device, const char* param_name, int* value);
/**
* @brief Get custom algorithm parameters for the device
*
* Get custom parameter settings from the device.
*
* @param device Handle to the target device
* @param param_name String name of the parameter to get
* @param value Integer value to get for the parameter
* @return int 0 on success, negative error code on failure
*/
int lidar_get_custom_parameter(device_handle device, const char* param_name, int* value);
/**
* @brief Set the map file used for relocalization
*
* Read & send specified map file to device for relocalization
*
* @param device Handle to the target device
* @param abs_path Absolute path to the map file
* @return int 0 on success, otherwise on failure
*/
int lidar_set_relocalization_map(device_handle device, const char* abs_path);
/**
* @brief Get the mapping result file from device
*
* Read & send specified map file from device to host
*
* @param device Handle to the target device
* @param dest_dir Destination directory to save the map file
* @param file_name File name to save the map file
* @return int 0 on success, -1 on failure without error code, error code (> 0) otherwise
*/
int lidar_get_mapping_result(device_handle device, const char* dest_dir, const char* file_name);
/**
* @brief Retrieve device logs to the host.
*
* Requests the device to collect its logs and transfer them to the host. The
* resulting file is written into dest_dir.
*
* @param device Device handle.
* @param dest_dir Destination directory on host (must exist).
* @return 0 on success, negative on failure.
* -1: general error
* -2: another transfer in progress
* -3: transfer timeout/stall
*/
int lidar_get_logs(device_handle device, const char *dest_dir);
/**
* @brief Save the current map to a file on the host. Synchronous, all-in-one API.
*
* Internally drives the complete save-map state machine, so callers do not need
* to coordinate the multi-step protocol themselves:
* 1) Set custom parameter save_map = 1 on the device (kicks off generation).
* 2) Poll save_map until the device resets it to 0 (map generation finished).
* 3) Pull the resulting file via the standard mapping-result transfer (same as
* lidar_get_mapping_result).
* 4) Return the final status to the caller.
*
* This is the recommended entry point for saving a map. The lower-level pair
* (lidar_set_custom_parameter("save_map") + lidar_get_mapping_result) remains
* available for advanced use cases.
*
* 同步保存地图到主机上的文件。一站式 API,内部完成「触发生成 → 等待设备完成 →
* 拉取文件」的完整流程,调用方无需自行轮询和处理异步状态。
*
* @param device Device handle.
* @param dest_dir Host directory to save the file into (must already exist).
* @param file_name File name (e.g. "map.bin").
* @param gen_timeout_ms Maximum time (ms) to wait for the device to finish
* generating the map. Pass 0 to use the default (300000 ms).
* @return int
* 0 success, file saved at dest_dir/file_name
* -1 invalid arguments (null device/dir, SDK not initialized, etc.)
* -2 device is busy with another file transfer
* -3 timed out waiting for the device to finish map generation
* -4 file transfer stalled or failed (see logs for details)
* other negative values are propagated from the underlying transfer.
*/
int lidar_save_map(device_handle device,
const char *dest_dir,
const char *file_name,
uint32_t gen_timeout_ms);
/**
* @brief Set the image mask file for the device
*
* Read & send specified image mask file to device
*
* @param device Handle to the target device
* @param abs_path Absolute path to the image mask file (e.g., mask.png)
* @return int 0 on success, -1 on failure, -2 if file transfer in progress
*/
int lidar_set_image_mask(device_handle device, const char* abs_path);
/**
* @brief enable encrypted device log
*
* enable encrypted device log, save to specified directory
* Please send to our support when needed
*
* @param device Handle to the target device
* @param dest_dir Destination directory to save the encrypted logs
* @return int 0 on success, -1 on failure
*/
int lidar_enable_encrypted_device_log(device_handle device, const char* dest_dir);
/**
* @brief Set the depth parameters for the device
*
* This function must be called before starting data stream.
*
* @param device Handle to the target device
* @param params Pointer to the depth parameters to set
* @return int 0 on success, negative error code on failure
*/
int lidar_set_depth_parameter(device_handle device, const lidar_depth_para_t *params);
/**
* @brief Set RGB camera configuration (format, resolution, frame rate)
*
* Configures the RGB image sensor before streaming starts. Must be called
* after lidar_open_device() and before lidar_start_stream().
*
* The device replies with CMD_CODE_OK on success or CMD_CODE_FAIL if the
* requested combination is unsupported.
*
* RGB frame rate is coupled with the DTOF frame rate. Only three frame-rate
* tiers are supported (the fps field in lidar_rgb_para_t is multiplied by 10):
*
########################################################
# RGB camera configuration (format, resolution, frame rate)
# RGB 摄像头配置(格式、分辨率、帧率)
#
# Applied via lidar_set_rgb_parameter() before streaming starts.
# 在数据流启动前通过 lidar_set_rgb_parameter() 下发。
#
# ATTENTION: not all combinations are valid; invalid values will
# cause device connection failure. 无效组合会导致设备连接失败。
#
# RGB frame rate is coupled with the DTOF frame rate, so both must
# be set to one of the matching pairs below (3 tiers supported):
# RGB 帧率与 DTOF 帧率联动,二者需按下表配对设置(支持三档):
#
# rgb_fps | dtof_fps | RGB actual rate | DTOF actual rate
# --------+----------+----------------+----------------
# 100 | 100 | 10.264 Hz | 10.0 Hz
# 145 | 145 | 14.472 Hz | 14.5 Hz
# 290 | 100 | 28.92 Hz | 10.0 Hz
########################################################
*
* An invalid combination will cause device connection failure.
*
* @param device Handle to the target device
* @param params Pointer to RGB configuration parameters (see lidar_rgb_para_t)
* @return int 0 on success, negative error code on failure
*/
int lidar_set_rgb_parameter(device_handle device, const lidar_rgb_para_t *params);
/**
* @brief Enable or disable IMU smooth sending feature
*
* When enabled, IMU data will be sent at precise intervals (default 400Hz)
* using a dedicated high-priority thread to reduce jitter and timing variance.
* When disabled, IMU data will be sent immediately upon reception.
*
* @param enable 1 to enable smooth sending, 0 to disable
* @return int 0 on success, -1 on failure
*/
int lidar_enable_imu_smooth_sending(int enable);
/**
* @brief Set IMU smooth sending frequency
*
* Set the target frequency for IMU smooth sending. Only effective when
* smooth sending is enabled via lidar_enable_imu_smooth_sending().
*
* @param frequency_hz Target frequency in Hz (1-1000 Hz, recommended 400 Hz)
* @return int 0 on success, -1 on failure
*/
int lidar_set_imu_smooth_frequency(uint32_t frequency_hz);
/**
* @brief Enable or disable SPAD crosstalk filter for DTOF point cloud
*
* When enabled, the SDK applies a multi-stage noise filter on raw DTOF
* point cloud data before delivering it to the user callback:
* - String noise detection (gradient-based)
* - Crosstalk detection (confidence-based edge point detection)
* - Distance filtering (min/max range)
* - FOV edge filtering (135 degrees)
* - Intensity threshold filtering (distance-dependent)
* - Confidence filtering (distance-dependent)
*
* Filtered points have their XYZ values set to 0.0 in the callback data.
* Only applies to the new 4-channel DTOF format (depth + xyz + intensity + confidence).
* Has no effect on the legacy 3-channel format.
*
* @param enable 1 to enable SPAD crosstalk filter, 0 to disable
* @return int 0 on success, -1 on failure (SDK not initialized)
*/
int lidar_enable_spad_filter(int enable);
/**
* @brief Reset the USB connection to the device
*
* Performs a USB port reset on the device (libusb_reset_device). This
* re-enumerates the device on the host without requiring a physical
* re-plug. The device handle should typically be reopened after the
* device reconnects.
*
* @param device Handle to the target device
* @return int 0 on success, negative error code on failure
*/
int lidar_reset_usb(device_handle device);
/**
* @brief Query the current device initial/running state.
*
* Returns the latest state reported by the device through heartbeats. The
* value corresponds to ::lidar_device_initial_state_e (NONE,
* NOT_INITIALIZED, INITIALIZED, STREAMING, STREAM_STOPPED). Callers that
* need to wait until the device is fully booted (for example before
* uploading a relocalization map) should poll this until it becomes
* LIDAR_DEVICE_STREAMING (or LIDAR_DEVICE_INITIALIZED at minimum).
*
*
* @param state Output pointer that receives the current state. Must not be NULL.
* @return int 0 on success, negative error code on failure.
*/
int lidar_get_device_state(lidar_device_initial_state_e *state);
/**
* @brief Send a host-defined pass-through user-data blob to the device.
*
* The device forwards data[] as-is to SLAM via shared memory
* ("user_data_shm"). No acknowledgment is returned from the device
* (fire-and-forget). An SDK-internal monotonic counter is packed into
* the on-wire frameId field so SLAM can still distinguish consecutive
* frames without the caller having to manage an id.
*
* Preconditions:
* - SDK initialized and the device opened (lidar_open_device).
* - SLAM has been started on the device side; otherwise the device
* silently drops the frame and logs a warning.
*
* Constraints:
* - blob != NULL.
* - 0 < blob_len <= 8 MiB (8 * 1024 * 1024).
* - Sending faster than SLAM can consume causes device-side timeouts
* and dropped frames. Pace according to SLAM throughput.
*
* @param device Handle returned by lidar_create_device / lidar_open_device.
* @param blob Pointer to user payload.
* @param blob_len Length in bytes.
* @return int 0 on success, negative error code on failure.
*/
int lidar_send_user_data(device_handle device,
const void *blob, uint32_t blob_len);
/* ---------------------------------------------------------------------
* Camera AE / AWB control APIs.
*
* All four APIs are synchronous (send + wait response) and serialised by
* an internal mutex (the same mutex protecting other control commands).
* Return value convention:
* == 0 success
* > 0 device-side error, see lidar_ae_error_e / lidar_rgb_error_e
* < 0 SDK-side error (not initialised, bad argument, USB failure,
* response timeout, malformed reply, ...)
*
* Wire-level details: sdk/api/Host_USB_AE_Protocol.md.
* ------------------------------------------------------------------- */
/**
* @brief Query current AE (auto exposure) state.
*
* Sends AE opcode 0x01 and decodes the 25-byte little-endian payload
* returned by the device-side ae_control service.
*
* Output fields and their physical meaning:
* exposure_time : current exposure time in seconds (manual range
* 0.0001 .. 0.033; in auto mode it varies with
* scene illumination).
* gain : current analog gain (manual range 1.0 .. 64.0;
* higher = brighter but noisier).
* iso : equivalent ISO, typically 100 .. 6400.
* brightness : average frame brightness (0 .. 255).
* is_converged : 1 = AE has settled, 0 = still adjusting.
* env_lv : ambient luminance index, typically 0 .. 15
* (higher = brighter scene).
* fps : actual frame rate, follows dtof_fps config
* (~10 / 14.5 / 29 Hz).
*
* @param device Device handle returned by lidar_create_device / lidar_open_device.
* @param out Output buffer, must not be NULL.
* @return See return value convention above.
*/
int lidar_get_ae_info(device_handle device, lidar_ae_info_t *out);
/**
* @brief Query current AWB (auto white balance) state.
*
* Sends AE opcode 0x30 and decodes the 25-byte little-endian payload.
*
* Output fields and their physical meaning:
* rgain : R channel gain (manual range 0.1 .. 4.0).
* grgain : Gr channel gain, always 1.0 (device-fixed).
* gbgain : Gb channel gain, always 1.0 (device-fixed).
* bgain : B channel gain (manual range 0.1 .. 4.0).
* cct : correlated color temperature in Kelvin
* (typically 2500 .. 8000 K).
* ccri : color temperature deviation index (-50 .. 50,
* signed; 0 means on the Planckian locus).
* is_converged : 1 = AWB has settled, 0 = still adjusting.
*
* @param device Device handle.
* @param out Output buffer, must not be NULL.
* @return See return value convention above.
*/
int lidar_get_awb_info(device_handle device, lidar_awb_info_t *out);
/**
* @brief Set AE mode and (in manual mode) exposure/gain.
*
* Behaviour:
* - mode == LIDAR_CAM_MODE_AUTO : sends opcode 0x02 only;
* exposure_time / gain are ignored.
* - mode == LIDAR_CAM_MODE_MANUAL : sends opcode 0x03 to switch to
* manual AE, then opcode 0x06 to
* apply (exposure_time, gain).
*
* Parameter ranges and physical meaning
* (manual mode only; out-of-range returns rc = 403):
*
* exposure_time : 0.0001 s .. 0.033 s
* Sensor exposure time per frame. Longer = brighter but more
* motion blur and lower effective fps if it exceeds the frame
* period (1/fps). For dtof_fps = 290 (29 Hz, period ~34 ms) the
* upper bound 0.033 s is already at the frame limit.
*
* gain : 1.0 .. 64.0
* Analog gain applied to the raw sensor signal. Higher = brighter
* output but worse SNR. Typical sweet spot: 1.0 .. 8.0 for daylight,
* 8.0 .. 32.0 for indoor / dim light, 32.0 .. 64.0 only when image
* must be visible at any cost.
*
* Recommended starting points by scene:
* bright outdoor : exposure 0.001~0.005 s, gain 1.0~2.0
* normal indoor : exposure 0.008~0.015 s, gain 2.0~8.0
* dim light : exposure 0.020~0.030 s, gain 8.0~32.0
*
* @param device Device handle.
* @param mode See lidar_cam_mode_e.
* @param exposure_time Exposure time in seconds (manual mode only).
* @param gain Analog gain (manual mode only).
* @return See return value convention above.
*/
int lidar_set_ae_param(device_handle device, lidar_cam_mode_e mode,
float exposure_time, float gain);
/**
* @brief Set AWB mode and (in manual mode) R/B channel gains.
*
* Behaviour:
* - mode == LIDAR_CAM_MODE_AUTO : sends opcode 0x31 only;
* rgain / bgain are ignored.
* - mode == LIDAR_CAM_MODE_MANUAL : sends opcode 0x32 to switch to
* manual AWB, then opcode 0x33 to
* apply (rgain, bgain). Gr/Gb are
* fixed to 1.0 by the device.
*
* Parameter ranges and physical meaning
* (manual mode only; out-of-range returns rc = 403):
*
* rgain : 0.1 .. 4.0
* Multiplier on the R channel before color matrix. Higher rgain
* relative to bgain shifts the image toward warm (yellow/red).
*
* bgain : 0.1 .. 4.0
* Multiplier on the B channel. Higher bgain relative to rgain
* shifts the image toward cool (blue).
*
* Color-temperature cookbook (approximate):
* warm (tungsten, sunset) : rgain ~2.0..2.5, bgain ~1.0..1.2
* neutral (daylight D65) : rgain ~1.5..1.7, bgain ~1.8..2.0
* cool (cloudy, fluor.) : rgain ~1.2..1.4, bgain ~2.2..2.6
*
* @param device Device handle.
* @param mode See lidar_cam_mode_e.
* @param rgain R channel gain (manual mode only).
* @param bgain B channel gain (manual mode only).
* @return See return value convention above.
*/
int lidar_set_awb_param(device_handle device, lidar_cam_mode_e mode,
float rgain, float bgain);
#ifdef __cplusplus
}
#endif
#endif // LIDAR_API_H
@@ -0,0 +1,503 @@
#ifndef LIDAR_TYPES_H
#define LIDAR_TYPES_H
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define LIDAR_SERIAL_MAX 64
#define LIDAR_MODEL_MAX 64
#define LIDAR_IP_MAX 64
typedef void * device_handle;
typedef enum {
LIDAR_LOG_ERROR = 0,
LIDAR_LOG_WARN,
LIDAR_LOG_INFO,
LIDAR_LOG_DEBUG,
} lidar_log_level_e;
typedef enum {
LIDAR_OTA_ALGORITHM,
LIDAR_OTA_FIRMWARE,
LIDAR_OTA_SCRIPT,
LIDAR_OTA_CALIBRATION
} lidar_ota_type_e;
typedef enum {
LIDAR_MODE_RAW,
LIDAR_MODE_SLAM,
} lidar_mode_e;
/**
* @brief Data types for lidar_data_callback_t
*
* Each type corresponds to a specific stream format in lidar_data_t.stream (capture_Image_List_t).
*
* ┌─────────────────────────────────────────────────────────────────────────────────────────────┐
* │ LIDAR_DT_RAW_RGB │
* │ imageCount: 1 │
* │ imageList[0]: NV12 image data │
* │ - pAddr: uint8_t* (Y plane followed by UV plane) │
* │ - width: 1600, height: 1296 │
* │ - length: width * height * 3 / 2 bytes │
* ├─────────────────────────────────────────────────────────────────────────────────────────────┤
* │ LIDAR_DT_RAW_IMU │
* │ imageCount: 1 │
* │ imageList[0]: IMU data │
* │ - pAddr: imu_convert_data_t* │
* │ - accel[3]: float (m/s^2) │
* │ - gyro[3]: float (rad/s) │
* │ - stamp: uint64_t (ns) │
* │ - sequence: uint64_t │
* │ - length: sizeof(imu_convert_data_t) │
* ├─────────────────────────────────────────────────────────────────────────────────────────────┤
* │ LIDAR_DT_RAW_DTOF │
* │ imageCount: 4 │
* │ Resolution: 256 x 192 │
* │ imageList[0]: Depth image │
* │ - pAddr: float* (depth in meters) │
* │ - length: 256 * 192 * sizeof(float) │
* │ imageList[1]: Point cloud XYZ │
* │ - pAddr: float* (x,y,z interleaved) │
* │ - length: 256 * 192 * 3 * sizeof(float) │
* │ imageList[2]: Intensity/Reflectivity │
* │ - pAddr: uint8_t* │
* │ - length: 256 * 192 * sizeof(uint8_t) │
* │ imageList[3]: Confidence │
* │ - pAddr: uint16_t* │
* │ - length: 256 * 192 * sizeof(uint16_t) │
* ├─────────────────────────────────────────────────────────────────────────────────────────────┤
* │ LIDAR_DT_SLAM_CLOUD │
* │ imageCount: 1 │
* │ imageList[0]: SLAM point cloud (XYZRGBA, fixed-point on the wire) │
* │ - pAddr: slam_cloud_point_t* (7 * int32_t per point, see struct below) │
* │ - length: num_points * sizeof(slam_cloud_point_t) ( == num_points * 28 bytes ) │
* │ xyz are stored in 0.1 mm units: meters = xyz * SLAM_CLOUD_XYZ_TO_M │
* ├─────────────────────────────────────────────────────────────────────────────────────────────┤
* │ LIDAR_DT_SLAM_ODOMETRY / LIDAR_DT_SLAM_ODOMETRY_HIGHFREQ / LIDAR_DT_SLAM_ODOMETRY_TF │
* │ imageCount: 1 │
* │ imageList[0]: Odometry data │
* │ - pAddr: ros_odom_convert_complete_t* │
* │ - timestamp_ns: uint64_t │
* │ - pos[3]: int64_t (x,y,z in μm, divide by 1e6 for meters) │
* │ - orient[4]: int64_t (quaternion x,y,z,w, divide by 1e6) │
* │ - linear_velocity[3]: int64_t │
* │ - angular_velocity[3]: int64_t │
* │ - pose_cov[36]: double │
* │ - twist_cov[36]: double │
* │ - length: sizeof(ros_odom_convert_complete_t) │
* ├─────────────────────────────────────────────────────────────────────────────────────────────┤
* │ LIDAR_DT_DEV_STATUS │
* │ imageCount: 1 │
* │ imageList[0]: Device status │
* │ - pAddr: lidar_device_status_t* │
* │ - length: sizeof(lidar_device_status_t) │
* ├─────────────────────────────────────────────────────────────────────────────────────────────┤
* │ LIDAR_DT_NTP │
* │ imageCount: 1 │
* │ imageList[0]: PTP/NTP sync data │
* │ - pAddr: ptp_sync_data_t* │
* │ - delay: double │
* │ - offset: double │
* │ - length: sizeof(ptp_sync_data_t) │
* └─────────────────────────────────────────────────────────────────────────────────────────────┘
*/
typedef enum {
LIDAR_DT_NONE = 0, /**< No data */
LIDAR_DT_RAW_RGB, /**< RGB image (NV12 format, 1536x1280) */
LIDAR_DT_RAW_IMU, /**< IMU data (imu_convert_data_t) */
LIDAR_DT_RAW_DTOF, /**< DTOF raw data (depth + xyz + confidence + intensity, 256x192) */
LIDAR_DT_SLAM_CLOUD, /**< SLAM point cloud (XYZRGBA) */
LIDAR_DT_SLAM_ODOMETRY, /**< SLAM odometry (ros_odom_convert_complete_t) */
LIDAR_DT_DEV_STATUS, /**< Device status (lidar_device_status_t) */
LIDAR_DT_SLAM_ODOMETRY_HIGHFREQ,/**< High frequency odometry (ros_odom_convert_complete_t) */
LIDAR_DT_SLAM_ODOMETRY_TF, /**< Map-Odom TF transform (ros_odom_convert_complete_t) */
LIDAR_DT_SLAM_WIWC, /**< WIWC odometry */
LIDAR_DT_NTP /**< PTP/NTP sync data (ptp_sync_data_t) */
} lidar_data_type_e;
typedef struct {
int8_t serial[LIDAR_SERIAL_MAX];
int8_t model[LIDAR_MODEL_MAX];
bool online;
uint32_t initial_state;
} lidar_device_info_t;
typedef struct {
float x, y, z;
float intensity;
} lidar_point_t;
typedef struct {
float intrinsics[9];
float extrinsics[16];
} lidar_calibration_t;
#define DEVICE_MAX_CH_NUMBER 4
typedef struct {
uint64_t timestamp_ns;
int64_t pos[3];
int64_t orient[4];
} ros2_odom_convert_t;
typedef struct {
uint64_t timestamp_ns;
int64_t pos[3]; // x, y, z in μm
int64_t orient[4]; // quaternion x, y, z, w in 1e6 precision
int64_t linear_velocity[3];
int64_t angular_velocity[3];
double pose_cov[36];
double twist_cov[36];
} ros_odom_convert_complete_t;
typedef struct {
double delay;
double offset;
} ptp_sync_data_t;
/* ---------------------------------------------------------------------
* SLAM cloud wire format.
*
* One LIDAR_DT_SLAM_CLOUD point on the bus is a 7 * int32_t record:
* xyz[0..2] : x, y, z in 0.1 mm fixed-point.
* meters = xyz * SLAM_CLOUD_XYZ_TO_M.
* rgba[0..3]: r, g, b, a; each stored in the low byte of an int32_t.
*
* Consumers (SDK hooks, ROS driver, etc.) should reference this struct
* and the scale macro below as the single source of truth rather than
* re-hardcoding the stride or the divisor.
* ------------------------------------------------------------------- */
#define SLAM_CLOUD_XYZ_TO_M (1.0e-4) /* device 0.1mm units -> meters */
#define SLAM_CLOUD_XYZ_FROM_M (1.0e4) /* meters -> device 0.1mm units */
typedef struct {
int32_t xyz[3]; /* x, y, z in 0.1 mm fixed-point */
int32_t rgba[4]; /* r, g, b, a; only low byte of each is meaningful */
} slam_cloud_point_t;
typedef struct icm_6aixs_data_t {
int16_t aacx;
int16_t aacy;
int16_t aacz;
int16_t gyrox;
int16_t gyroy;
int16_t gyroz;
uint8_t valid;
uint32_t nums;
uint8_t fsync_pack;
uint16_t interval;
uint64_t stamp;
} icm_6aixs_data_t;
typedef struct {
float accel_x;
float accel_y;
float accel_z;
float gyro_x;
float gyro_y;
float gyro_z;
uint64_t stamp;
uint64_t sequence;
} imu_convert_data_t;
typedef struct {
uint32_t length;
uint64_t sequence;
uint64_t timestamp;
uint64_t interval;
void* pAddr;
uint32_t width;
uint32_t height;
uint32_t format; /**< Pixel format: 0=NV12, 1=MJPEG (see lidar_rgb_format_e); 0 for non-RGB frames */
} buffer_List_t;
typedef struct capture_Image_List_t {
uint32_t imageCount;
buffer_List_t imageList[DEVICE_MAX_CH_NUMBER];
} capture_Image_List_t;
typedef struct {
uint32_t type;
capture_Image_List_t stream;
} lidar_data_t;
typedef void (*lidar_device_callback_t)(const lidar_device_info_t* device, bool attach);
typedef void (*lidar_data_callback_t)(const lidar_data_t *data, void *user_data);
typedef struct {
lidar_data_callback_t data_callback;
void *user_data;
} lidar_data_callback_info_t;
typedef struct {
int major;
int minor;
int patch;
}lidar_version_t;
typedef struct {
lidar_version_t kernel_version;
lidar_version_t mcu_version;
lidar_version_t soc_version;
lidar_version_t Daemon_proc_version;
lidar_version_t slam_version;
} lidar_fireware_version_t;
/**
* @brief RGB image sensor frame rate
*
*/
typedef struct{
int configured_odr;/*rgb image sensor frame rate, offset: */
int tx_odr;/*The actual rgb image sensor frame rate, offset: */
} lidar_rgb_sensor_status_t;
/**
* @brief DTOF Lidar frame rate
*
*/
typedef struct{
int configured_odr;/* dtof lidar sensor frame rate, offset: */
int tx_odr;/*The actual dtof lidar sensor frame rate, offset: */
int subframe_odr;/*DTOF 6行为一组 这个是组间隔时间*/
short tx_temp;/* dtof lidar tx temp offset: */
short rx_temp;/* dtof lidar rx temp offset: */
} lidar_dtof_sensor_status_t;
/**
* @brief IMU Sensor
*
*/
typedef struct{
int configured_odr;
int tx_odr;
} lidar_imu_sensor_status_t;
typedef struct{
int package_temp;/*SOC整体温度*/
// int bigcore_temp;/*大核集群温度:4*A76*/
// int littlecore_temp;/*小核集群温度:4*A53*/
int cpu_temp;
int center_temp;/*SOC中心温度:4*A53*/
int gpu_temp;/* GPU模块温度 */
int npu_temp;/* NPU模块温度 */
} lidar_soc_thermal_t;
typedef struct
{
double uptime_seconds;
lidar_soc_thermal_t soc_thermal; /*offset: 0*/
int cpu_use_rate[8];/*cpu 使用率,offset: */
int ram_use_rate;/*运行内存使用率 ,offset: */
lidar_rgb_sensor_status_t rgb_sensor;
lidar_dtof_sensor_status_t dtof_sensor;
lidar_imu_sensor_status_t imu_sensor;
int slam_cloud_tx_odr; /* Actual frame rate of slam cloud offset: */
int slam_odom_tx_odr; /* Actual frame rate of slam odom offset: */
int slam_odom_highfreq_tx_odr; /* Actual frame rate of slam odom offset: */
} lidar_device_status_t;
typedef enum {
LIDAR_DEVICE_NONE = 0,
LIDAR_DEVICE_NOT_INITIALIZED,
LIDAR_DEVICE_INITIALIZED,
LIDAR_DEVICE_STREAMING,
LIDAR_DEVICE_STREAM_STOPPED,
} lidar_device_initial_state_e;
typedef enum {
LIDAR_DEPTH_ODR_10HZ = 0,
LIDAR_DEPTH_ODR_14_5HZ = 1,
LIDAR_DEPTH_ODR_29HZ = 2,
} lidar_depth_odr_e;
typedef struct {
lidar_depth_odr_e odr;
} lidar_depth_para_t;
/* ---------------------------------------------------------------------
* RGB camera configuration types.
*
* The host SDK sends the configuration through the standard USB control
* channel (CMD_CODE_CONTROL_CMD + SYS_CONTROL_RGB_SET_CONFIG). The
* device-side lydapp applies the settings to the RGB image sensor before
* streaming starts. See sdk/api/Host_USB_RGB_Config_Protocol.md for the
* wire-level details.
* ------------------------------------------------------------------- */
/**
* @brief RGB camera pixel format
*/
typedef enum {
LIDAR_RGB_FMT_NV12 = 0, /**< NV12 (default, 1536x1280) */
LIDAR_RGB_FMT_MJPEG = 1, /**< Motion JPEG compressed */
} lidar_rgb_format_e;
/**
* @brief RGB camera configuration parameters
*
* Used with lidar_set_rgb_parameter(). Must be called after
* lidar_open_device() and before lidar_start_stream().
*
* Field meaning and valid ranges:
* format : pixel format, see lidar_rgb_format_e
* width : image width in pixels (device-dependent, e.g. 1600)
* height : image height in pixels (device-dependent, e.g. 1296)
* fps : target frame rate * 10 (e.g. 300 = 30fps, 145 = 14.5fps)
*
* Not all combinations are valid. Invalid combinations return rc = -1
* with device-side CMD_CODE_FAIL. Use lidar_get_device_status() to
* verify the actual configured_odr after setting.
*/
typedef struct {
lidar_rgb_format_e format;
uint32_t width;
uint32_t height;
uint32_t fps;
} lidar_rgb_para_t;
/* ---------------------------------------------------------------------
* Camera AE / AWB control types.
*
* The host SDK forwards AE/AWB requests through the USB control channel
* (CMD_CODE_CONTROL_CMD + SYS_CONTROL_AE_UDP). The device-side lydapp
* relays them via UDP loopback to its ISP service. See
* sdk/api/Host_USB_AE_Protocol.md for the wire-level details.
* ------------------------------------------------------------------- */
/**
* @brief AE/AWB control mode used by lidar_set_ae_param / lidar_set_awb_param.
*
* - AUTO : the device runs its own AE/AWB convergence loop. The two
* float parameters of the corresponding Set call are ignored.
* - MANUAL : the device locks AE/AWB and applies the user-supplied
* (exposure_time, gain) or (rgain, bgain). Out-of-range
* values are rejected with rc = 403
* (LIDAR_AE_PARAM_OUT_OF_RANGE).
*/
typedef enum {
LIDAR_CAM_MODE_AUTO = 0, /**< switch to auto AE / AWB */
LIDAR_CAM_MODE_MANUAL = 1, /**< switch to manual AE / AWB and apply params */
} lidar_cam_mode_e;
/**
* @brief Current AE status returned by lidar_get_ae_info().
*
* Field-by-field meaning and typical range:
*
* exposure_time : current sensor exposure time, in seconds.
* Manual-mode valid range: 0.0001 .. 0.033.
* In auto mode varies with scene illumination.
* gain : current analog gain (linear, not dB).
* Manual-mode valid range: 1.0 .. 64.0.
* Higher value = brighter output but worse SNR.
* iso : equivalent ISO speed, typically 100 .. 6400.
* Derived from gain; informational only.
* brightness : average frame brightness in [0, 255]. AE target
* converges toward a mid-range value.
* is_converged : 1 = AE has settled, 0 = still adjusting.
* env_lv : ambient luminance index, typically 0 .. 15
* (higher = brighter scene).
* fps : actual frame rate in Hz, follows dtof_fps config
* (~10 / 14.5 / 29).
*/
typedef struct {
float exposure_time; /**< current exposure time (s), 0.0001..0.033 */
float gain; /**< current analog gain, 1.0..64.0 */
int32_t iso; /**< equivalent ISO, ~100..6400 */
float brightness; /**< average frame brightness, 0..255 */
uint8_t is_converged; /**< 1 = AE converged, 0 = not converged */
float env_lv; /**< ambient luminance level, ~0..15 */
float fps; /**< current frame rate (Hz) */
} lidar_ae_info_t;
/**
* @brief Current AWB status returned by lidar_get_awb_info().
*
* Field-by-field meaning and typical range:
*
* rgain : R channel gain. Manual-mode valid range: 0.1 .. 4.0.
* Raising rgain relative to bgain shifts the image
* toward warm (yellow/red).
* grgain : Gr channel gain. Device-fixed at 1.0, not adjustable.
* gbgain : Gb channel gain. Device-fixed at 1.0, not adjustable.
* bgain : B channel gain. Manual-mode valid range: 0.1 .. 4.0.
* Raising bgain relative to rgain shifts the image
* toward cool (blue).
* cct : correlated color temperature in Kelvin, typically
* 2500 .. 8000 K.
* ccri : color temperature deviation index, signed value
* roughly in -50 .. 50; 0 = on the Planckian locus.
* is_converged : 1 = AWB has settled, 0 = still adjusting.
*/
typedef struct {
float rgain; /**< R channel gain, 0.1..4.0 */
float grgain; /**< Gr channel gain, device-fixed 1.0 */
float gbgain; /**< Gb channel gain, device-fixed 1.0 */
float bgain; /**< B channel gain, 0.1..4.0 */
float cct; /**< color temperature (K), ~2500..8000 */
float ccri; /**< color temperature deviation, ~-50..50 */
uint8_t is_converged; /**< 1 = AWB converged, 0 = not converged */
} lidar_awb_info_t;
/**
* @brief AE/AWB device-side error codes.
*
* Mapped to positive return values of lidar_get_ae_info / lidar_set_ae_param /
* lidar_get_awb_info / lidar_set_awb_param when the device replies with
* CMD_CODE_FAIL. See Host_USB_AE_Protocol.md section 6.
*/
typedef enum {
LIDAR_AE_OK = 0,
LIDAR_AE_BAD_REQUEST = 400, /**< payload too short */
LIDAR_AE_UNSUPPORTED_OPCODE = 401,
LIDAR_AE_BAD_PARAM_LEN = 402,
LIDAR_AE_PARAM_OUT_OF_RANGE = 403,
LIDAR_AE_SOCKET_ERROR = 404,
LIDAR_AE_NO_RESPONSE = 405, /**< ae_control UDP timeout */
LIDAR_AE_UNKNOWN_OPCODE = 0xFF,/**< status byte from ae_control */
} lidar_ae_error_e;
/**
* @brief RGB config device-side error codes.
*
* Mapped to positive return values of lidar_set_rgb_parameter when the
* device replies with CMD_CODE_FAIL, or returned directly by the SDK
* for host-side pre-checks (e.g. LIDAR_RGB_DTOF_NOT_CONFIGURED).
* See Host_USB_RGB_Config_Protocol.md section 8.
*/
typedef enum {
LIDAR_RGB_OK = 0,
LIDAR_RGB_BAD_REQUEST = 500, /**< payload too short */
LIDAR_RGB_UNSUPPORTED_FORMAT = 501, /**< format not NV12/MJPEG */
LIDAR_RGB_UNSUPPORTED_RESOLUTION = 502, /**< resolution not supported */
LIDAR_RGB_UNSUPPORTED_FPS = 503, /**< fps not in capability table */
LIDAR_RGB_INVALID_COMBINATION = 504, /**< rgb fps + dtof odr combo invalid */
LIDAR_RGB_DTOF_NOT_CONFIGURED = 505, /**< dtof not set, call lidar_set_depth_parameter first */
} lidar_rgb_error_e;
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,48 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ODIN_CALIB_PATH_H
#define ODIN_CALIB_PATH_H
#include <cstdlib>
#include <string>
// Single source of truth for the calibration file location, shared by the
// writer (host_sdk_sample) and every reader (cloud_reprojection, pcd2depth).
// Header-only inline functions avoid multiple-definition across translation units.
namespace odin_ros_driver {
// Resolve the writable runtime directory that stores calib.yaml.
// Priority: ODIN_CALIB_DIR -> ROS_HOME -> ~/.ros -> /tmp.
// Works for both ROS1 and ROS2 (~/.ros is the shared default ROS_HOME).
inline std::string GetOdinRuntimeDir() {
if (const char* custom = std::getenv("ODIN_CALIB_DIR")) {
return std::string(custom);
}
if (const char* ros_home = std::getenv("ROS_HOME")) {
return std::string(ros_home) + "/odin_ros_driver";
}
if (const char* home = std::getenv("HOME")) {
return std::string(home) + "/.ros/odin_ros_driver";
}
return "/tmp/odin_ros_driver";
}
// Canonical calib.yaml path shared by writer and all readers.
inline std::string GetOdinCalibFile() {
return GetOdinRuntimeDir() + "/calib.yaml";
}
} // namespace odin_ros_driver
#endif // ODIN_CALIB_PATH_H
@@ -0,0 +1,93 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/common/transforms.h>
#include <opencv2/opencv.hpp>
#include <Eigen/Dense>
#include <vector>
class PointCloudToDepthConverter
{
public:
struct CameraParams
{
int image_width;
int image_height;
double A11, A12, A22;
double u0, v0;
double k2, k3, k4, k5, k6, k7;
double scale;
int point_sampling_rate;
Eigen::Matrix4d Tcl;
};
struct ProcessResult
{
cv::Mat depth_image;
pcl::PointCloud<pcl::PointXYZRGB> colored_cloud;
bool success;
std::string error_message;
};
explicit PointCloudToDepthConverter(const CameraParams &params);
ProcessResult processCloudAndImage(const pcl::PointCloud<pcl::PointXYZ> &cloud,
const cv::Mat &image);
cv::Mat customResize(const cv::Mat& src, const cv::Size& size);
const CameraParams &getCameraParams() const { return params_; }
void updateCameraParams(const CameraParams &params);
private:
CameraParams params_;
Eigen::Matrix3d K_;
Eigen::Matrix3d Kl_;
Eigen::Matrix4d K_4x4_;
Eigen::Matrix4d Kcl_;
cv::Mat map_x_, map_y_;
cv::Mat inv_map_x_, inv_map_y_;
int scaled_width_, scaled_height_;
void initializeInternalParams();
void createDistortionMaps();
cv::Mat projectCloudToDepth(const pcl::PointCloud<pcl::PointXYZ> &cloud_in_cam);
cv::Mat postProcessDepthImage(const cv::Mat &depth_img);
pcl::PointCloud<pcl::PointXYZRGB> generateColoredCloud(const cv::Mat &depth_img,
const cv::Mat &color_img);
std::pair<bool, std::string> validateInputs(const pcl::PointCloud<pcl::PointXYZ> &cloud,
const cv::Mat &image);
};
@@ -0,0 +1,144 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <Eigen/Dense>
#include <cmath>
namespace mini_vikit {
using namespace Eigen;
class PolynomialCamera {
private:
const double fx_, fy_;
const double cx_, cy_;
const double skew_;
bool distortion_;
double k2_, k3_, k4_, k5_, k6_, k7_;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
PolynomialCamera(double width, double height,
double fx, double fy, double cx, double cy, double skew,
double k2=0.0, double k3=0.0, double k4=0.0,
double k5=0.0, double k6=0.0, double k7=0.0)
: fx_(fx), fy_(fy), cx_(cx), cy_(cy), skew_(skew),
distortion_(std::abs(k2) > 1e-7) {
k2_ = k2; k3_ = k3; k4_ = k4; k5_ = k5; k6_ = k6; k7_ = k7;
}
Vector3d cam2world(const double& u, const double& v) const {
Vector3d xyz;
if (!distortion_) {
double y = (v - cy_) / fy_;
double x = (u - cx_ - y * skew_) / fx_;
xyz << x, y, 1.0;
} else {
double y = (v - cy_) / fy_;
double x = (u - cx_ - y * skew_) / fx_;
const double thetad = std::sqrt(x * x + y * y);
double theta = thetad;
for (int i = 0; i < 7; ++i) {
const double theta2 = theta * theta;
const double theta3 = theta2 * theta;
const double theta4 = theta3 * theta;
const double theta5 = theta4 * theta;
const double theta6 = theta5 * theta;
theta = thetad / (1.0 + k2_ * theta + k3_ * theta2 + k4_ * theta3 +
k5_ * theta4 + k6_ * theta5 + k7_ * theta6);
}
const double scaling = std::tan(theta) / thetad;
x *= scaling;
y *= scaling;
xyz << x, y, 1.0;
}
return xyz.normalized();
}
Vector3d cam2world(const Vector2d& px) const {
return cam2world(px[0], px[1]);
}
Vector2d world2cam(const Vector3d& xyz) const {
Vector2d px;
if (!distortion_) {
px[0] = fx_ * xyz[0] + cx_;
px[1] = fy_ * xyz[1] + cy_;
} else {
double xd, yd;
const double r = std::sqrt(xyz(1) * xyz(1) + xyz(0) * xyz(0));
const double theta = std::acos(xyz(2) / xyz.norm());
const double thetad = thetad_from_theta(theta);
const double scaling = thetad / r;
xd = xyz[0] * scaling;
yd = xyz[1] * scaling;
px[0] = xd * fx_ + yd * skew_ + cx_;
px[1] = yd * fy_ + cy_;
}
return px;
}
Vector2d world2cam(const Vector2d& uv) const {
Vector2d px;
if (!distortion_) {
px[0] = fx_ * uv[0] + cx_;
px[1] = fy_ * uv[1] + cy_;
} else {
double xd, yd;
const double r = uv.norm();
if (r < 1e-8) {
return uv;
}
const double theta = std::atan(r);
const double thetad = thetad_from_theta(theta);
const double scaling = thetad / r;
xd = uv[0] * scaling;
yd = uv[1] * scaling;
px[0] = xd * fx_ + yd * skew_ + cx_;
px[1] = yd * fy_ + cy_;
}
return px;
}
inline double thetad_from_theta(const double theta) const {
const double theta2 = theta * theta;
const double theta3 = theta2 * theta;
const double theta4 = theta3 * theta;
const double theta5 = theta4 * theta;
const double theta6 = theta5 * theta;
const double theta7 = theta6 * theta;
const double thetad = theta + k2_ * theta2 + k3_ * theta3 +
k4_ * theta4 + k5_ * theta5 + k6_ * theta6 + k7_ * theta7;
return thetad;
}
double fx() const { return fx_; }
double fy() const { return fy_; }
double cx() const { return cx_; }
double cy() const { return cy_; }
double skew() const { return skew_; }
bool has_distortion() const { return distortion_; }
double k2() const { return k2_; }
double k3() const { return k3_; }
double k4() const { return k4_; }
double k5() const { return k5_; }
double k6() const { return k6_; }
double k7() const { return k7_; }
};
} // namespace mini_vikit
@@ -0,0 +1,83 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef RGBCLOUD_H
#define RGBCLOUD_H
#include <vector>
#include <string>
#include <Eigen/Dense>
#include "lidar_api.h"
namespace GlobalCameraParams {
extern float g_fx;
extern float g_fy;
extern float g_cx;
extern float g_cy;
extern float g_skew;
extern float g_k2;
extern float g_k3;
extern float g_k4;
extern float g_k5;
extern float g_k6;
extern float g_k7;
extern Eigen::Matrix4f g_T_camera_lidar;
}
class rawCloudRender {
public:
bool init(const std::string& yamlFilePath);
void nv12buffer_2_rgb(buffer_List_t &image, std::vector<std::vector<float>>& rgb_image);
void render(std::vector<std::vector<float>>& rgb_image, capture_Image_List_t* pcdStream, int pcdIdx, std::vector<float>& rgbCloud_flat);
void print_camera_calib();
int getImageWidth() const { return image_width_; }
int getImageHeight() const { return image_height_; }
private:
std::string model_type_;
std::string camera_name_;
int image_width_;
int image_height_;
int frame_size_;
bool opencv_available_;
// 4x4 transformation matrix (T_camera_lidar)
Eigen::Matrix4f T_camera_lidar_;
float k2_;
float k3_;
float k4_;
float k5_;
float k6_;
float k7_;
float p1_;
float p2_;
float A11_fx_;
float A12_skew_;
float A22_fy_;
float u0_cx_;
float v0_cy_;
bool isFast_;
int numDiff_;
float maxIncidentAngle_;
};
#endif // RGBCLOUD_H
@@ -0,0 +1,149 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef YAML_PARSER_H
#define YAML_PARSER_H
#include <cstdio>
#include <string>
#include <map>
#include <unordered_set>
#include <vector>
#include <memory>
#include <yaml-cpp/yaml.h>
#include "lidar_api.h"
namespace odin_ros_driver {
// Data type enum for supporting different value types
enum class DataType {
INT_TYPE,
FLOAT_ARRAY_TYPE,
INT_ARRAY_TYPE,
};
// Generic parameter value holder
struct ParameterValue {
DataType type;
std::vector<uint8_t> data;
ParameterValue() : type(DataType::INT_TYPE) {}
template<typename T>
void setData(const T& value) {
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(&value);
data.assign(ptr, ptr + sizeof(T));
}
template<typename T>
void setArray(const std::vector<T>& arr) {
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(arr.data());
data.assign(ptr, ptr + arr.size() * sizeof(T));
}
size_t getSize() const {
return data.size();
}
const void* getData() const {
return data.empty() ? nullptr : data.data();
}
};
class YamlParser {
public:
YamlParser(const std::string& config_file);
bool loadConfig();
const std::map<std::string, int>& getRegisterKeys() const;
const std::map<std::string, std::string>& getRegisterKeysStrVal() const;
const std::map<std::string, ParameterValue>& getCustomParameters() const;
void printConfig() const;
bool applyCustomParameters(device_handle device);
int getCustomParameterInt(const std::string& param_name, int default_value) const;
int getCustomMapMode(int default_value) const {
auto it = custom_parameters_.find("map_mode");
if (it != custom_parameters_.end() && it->second.type == DataType::INT_TYPE) {
printf("custom_map_mode = %d\n", *(int*)it->second.getData());
return *(int*)it->second.getData();
} else {
return default_value;
}
};
private:
std::string config_file_;
std::map<std::string, int> register_keys_;
std::map<std::string, std::string> register_keys_str_val_;
std::map<std::string, double> register_keys_float_val_;
std::map<std::string, ParameterValue> custom_parameters_;
// Keys whose YAML value is a string (not int).
std::unordered_set<std::string> allowed_key_w_str_val = {
"relocalization_map_abs_path",
"mapping_result_dest_dir",
"mapping_result_file_name",
"image_mask_abs_path",
"overlay_reprojected_topic",
"overlay_camera_topic",
"overlay_output_topic"
};
// Keys whose YAML value is a floating-point number (not int).
std::unordered_set<std::string> allowed_key_w_float_val = {
"overlay_alpha"
};
// Whitelist of all recognized integer-valued keys.
// Any key not in this set (and not custom_*, string, or float) will trigger an error.
std::unordered_set<std::string> allowed_key_w_int_val = {
"streamctrl",
"sendrgbcompressed",
"sendrgb",
"sendrgbundistort",
"sendimu",
"enable_imu_smooth",
"imu_smooth_frequency",
"sendodom",
"send_odom_baselink_tf",
"tf_extra_publish_rate",
"senddtof",
"cloud_raw_confidence_threshold",
"dtof_fps",
"rgb_format",
"rgb_width",
"rgb_height",
"rgb_fps",
"sendcloudslam",
"sendcloudrender",
"senddepth",
"sendreprojection",
"sendoverlay",
"recorddata",
"devstatuslog",
"save_log",
"pubintensitygray",
"showpath",
"showcamerapose",
"strict_usb3.0_check",
"use_host_ros_time",
"showfps",
"log_devel",
"sendimagemask",
"resetalgo"
};
};
}
#endif
@@ -0,0 +1,37 @@
<launch>
<!--
Usage: roslaunch odin_ros_driver odin1_ros1.launch
-->
<!-- Set node name -->
<arg name="node_name" default="host_sdk_sample"/>
<!-- Set parameter file path -->
<arg name="config_file" default="$(find odin_ros_driver)/config/control_command.yaml"/>
<!-- Set RViz configuration file path -->
<arg name="rviz_config" default="$(find odin_ros_driver)/config/odin_ros.rviz"/>
<!-- Launch main node -->
<node name="$(arg node_name)" pkg="odin_ros_driver" type="host_sdk_sample" output="screen">
<param name="config_file" value="$(arg config_file)"/>
</node>
<node pkg="odin_ros_driver" type="pcd2depth_node" name="pcd2depth_node" output="screen" >
<rosparam command="load" file="$(find odin_ros_driver)/config/control_command.yaml"/>
<!-- calib_file_path left unset: node falls back to the shared runtime dir (~/.ros/odin_ros_driver/calib.yaml) -->
</node>
<node pkg="odin_ros_driver" type="cloud_reprojection_node" name="cloud_reprojection_node" output="screen" >
<rosparam command="load" file="$(find odin_ros_driver)/config/control_command.yaml"/>
<!-- calib_file_path left unset: node falls back to the shared runtime dir (~/.ros/odin_ros_driver/calib.yaml) -->
</node>
<!-- Image overlay node - overlays reprojected points on camera image -->
<node pkg="odin_ros_driver" type="image_overlay_node" name="image_overlay_node" output="screen" >
<rosparam command="load" file="$(find odin_ros_driver)/config/control_command.yaml"/>
</node>
<!-- Launch RViz with configuration -->
<node name="rviz" pkg="rviz" type="rviz" args="-d $(arg rviz_config)" output="screen"/>
</launch>
@@ -0,0 +1,116 @@
# USAGE: ros2 launch odin_ros_driver odin1_ros2.launch.py
import os
import yaml
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def get_odin_runtime_dir():
# Resolve the writable runtime directory that stores calib.yaml.
# Priority: ODIN_CALIB_DIR -> ROS_HOME -> ~/.ros -> /tmp.
# Must stay in sync with get_odin_runtime_dir() in host_sdk_sample.cpp.
custom = os.environ.get('ODIN_CALIB_DIR')
if custom:
return custom
ros_home = os.environ.get('ROS_HOME')
if ros_home:
return os.path.join(ros_home, 'odin_ros_driver')
home = os.environ.get('HOME')
if home:
return os.path.join(home, '.ros', 'odin_ros_driver')
return '/tmp/odin_ros_driver'
def generate_launch_description():
# Get package directory
package_dir = get_package_share_directory('odin_ros_driver')
# Shared, writable calib.yaml path (matches host_sdk_sample writer)
calib_file_path = os.path.join(get_odin_runtime_dir(), 'calib.yaml')
# Declare configuration parameter
config_file_arg = DeclareLaunchArgument(
'config_file',
default_value=os.path.join(package_dir, 'config', 'control_command.yaml'),
description='Path to the control config YAML file'
)
# Add RViz2 configuration file parameter
rviz_config_arg = DeclareLaunchArgument(
'rviz_config',
default_value=os.path.join(package_dir, 'config', 'odin_ros2.rviz'),
description='Path to RViz2 config file'
)
# Create main node
host_sdk_node = Node(
package='odin_ros_driver',
executable='host_sdk_sample',
name='host_sdk_sample',
output='screen',
# arguments=['--ros-args', '--log-level', 'debug'],
parameters=[{
'config_file': LaunchConfiguration('config_file')
}]
)
pcd2depth_config_path = os.path.join(package_dir, 'config', 'control_command.yaml')
with open(pcd2depth_config_path, 'r') as f:
pcd2depth_params = yaml.safe_load(f)
pcd2depth_params['calib_file_path'] = calib_file_path
pcd2depth_node = Node(
package='odin_ros_driver',
executable='pcd2depth_ros2_node',
name='pcd2depth_ros2_node',
output='screen',
parameters=[pcd2depth_params]
)
# Cloud reprojection node
reprojection_config_path = os.path.join(package_dir, 'config', 'control_command.yaml')
with open(reprojection_config_path, 'r') as f:
reprojection_params = yaml.safe_load(f)
reprojection_params['calib_file_path'] = calib_file_path
cloud_reprojection_node = Node(
package='odin_ros_driver',
executable='cloud_reprojection_ros2_node',
name='cloud_reprojection_ros2_node',
output='screen',
parameters=[reprojection_params]
)
# Image overlay node - overlays reprojected points on camera image
overlay_config_path = os.path.join(package_dir, 'config', 'control_command.yaml')
with open(overlay_config_path, 'r') as f:
overlay_params = yaml.safe_load(f)
image_overlay_node = Node(
package='odin_ros_driver',
executable='image_overlay_node',
name='image_overlay_node',
output='screen',
parameters=[overlay_params]
)
# Create RViz2 node - loads specified configuration file
rviz_node = Node(
package='rviz2',
executable='rviz2',
name='rviz2',
output='screen',
arguments=['-d', LaunchConfiguration('rviz_config')]
)
# Create launch description
ld = LaunchDescription()
ld.add_action(config_file_arg)
ld.add_action(rviz_config_arg) # Add RViz configuration argument
ld.add_action(host_sdk_node)
ld.add_action(pcd2depth_node)
ld.add_action(cloud_reprojection_node)
ld.add_action(image_overlay_node)
ld.add_action(rviz_node) # Add RViz node
return ld
Binary file not shown.
Binary file not shown.
+33
View File
@@ -0,0 +1,33 @@
<?xml version="1.0"?>
<package format="3">
<name>odin_ros_driver</name>
<version>0.14.2</version>
<description>ROS2 driver for Odin sensor</description>
<maintainer email="[email protected]">rlk</maintainer>
<license>Apache 2.0</license>
<!-- ROS2 uses colcon as the build tool -->
<buildtool_depend>ament_cmake</buildtool_depend>
<!-- ROS2 dependencies -->
<depend>rclcpp</depend>
<!-- System dependencies -->
<depend>std_msgs</depend>
<depend>sensor_msgs</depend>
<depend>nav_msgs</depend>
<depend>geometry_msgs</depend>
<depend>cv_bridge</depend>
<depend>image_transport</depend>
<depend>pcl_conversions</depend>
<depend>message_filters</depend>
<depend>tf2</depend>
<depend>tf2_ros</depend>
<depend>tf2_geometry_msgs</depend>
<depend>ament_index_cpp</depend>
<!-- AE/AWB debug services (custom .srv files in srv/) -->
<buildtool_depend>rosidl_default_generators</buildtool_depend>
<exec_depend>rosidl_default_runtime</exec_depend>
<member_of_group>rosidl_interface_packages</member_of_group>
<!-- Specify build type as ament -->
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
@@ -0,0 +1,33 @@
<?xml version="1.0"?>
<package format="3">
<name>odin_ros_driver</name>
<version>0.14.4</version>
<description>ROS driver for Odin sensor</description>
<maintainer email="[email protected]">rlk</maintainer>
<license>Apache 2.0</license>
<!-- ROS1 uses catkin as the build tool -->
<buildtool_depend>catkin</buildtool_depend>
<!-- ROS1 dependencies -->
<depend>roscpp</depend>
<depend>std_msgs</depend>
<depend>sensor_msgs</depend>
<depend>nav_msgs</depend>
<depend>cv_bridge</depend>
<depend>image_transport</depend>
<!-- AE/AWB debug services (custom .srv files in srv/) -->
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
<!-- System dependencies -->
<depend>eigen</depend>
<depend>opencv</depend>
<depend>yaml-cpp</depend>
<!-- Specify build type as catkin -->
<export>
<build_type>catkin</build_type>
</export>
</package>
@@ -0,0 +1,33 @@
<?xml version="1.0"?>
<package format="3">
<name>odin_ros_driver</name>
<version>0.14.4</version>
<description>ROS2 driver for Odin sensor</description>
<maintainer email="[email protected]">rlk</maintainer>
<license>Apache 2.0</license>
<!-- ROS2 uses colcon as the build tool -->
<buildtool_depend>ament_cmake</buildtool_depend>
<!-- ROS2 dependencies -->
<depend>rclcpp</depend>
<!-- System dependencies -->
<depend>std_msgs</depend>
<depend>sensor_msgs</depend>
<depend>nav_msgs</depend>
<depend>geometry_msgs</depend>
<depend>cv_bridge</depend>
<depend>image_transport</depend>
<depend>pcl_conversions</depend>
<depend>message_filters</depend>
<depend>tf2</depend>
<depend>tf2_ros</depend>
<depend>tf2_geometry_msgs</depend>
<depend>ament_index_cpp</depend>
<!-- AE/AWB debug services (custom .srv files in srv/) -->
<buildtool_depend>rosidl_default_generators</buildtool_depend>
<exec_depend>rosidl_default_runtime</exec_depend>
<member_of_group>rosidl_interface_packages</member_of_group>
<!-- Specify build type as ament -->
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
+128
View File
@@ -0,0 +1,128 @@
#!/bin/bash
# Get the directory where the script is located (Odin_ROS_Driver directory)
PKG_DIR="$(cd "$(dirname "$0")/.."; pwd)"
# Calculate the workspace root directory (contains devel, build, src)
WORKSPACE_ROOT="$(dirname "$(dirname "$PKG_DIR")")"
# Workspace source directory (contains all packages)
WORKSPACE_SRC="${WORKSPACE_ROOT}/src"
PROJECT_NAME="odin_ros_driver"
# Define color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# Clean workspace function
clean_workspace() {
echo -e "${YELLOW}Cleaning build directories${NC}"
# Clean build artifacts in workspace
rm -rf "${WORKSPACE_ROOT}/build"
rm -rf "${WORKSPACE_ROOT}/install"
rm -rf "${WORKSPACE_ROOT}/log"
rm -rf "${WORKSPACE_ROOT}/devel"
echo -e "${GREEN}Cleanup complete${NC}"
}
# Run node function
run_node() {
echo -e "${YELLOW}Running ROS1 node${NC}"
# Check if environment file exists
if [ ! -f "${WORKSPACE_ROOT}/devel/setup.bash" ]; then
echo -e "${RED}Could not find devel/setup.bash, please build the project with ./build_ros1.sh first${NC}"
return 1
fi
# Source environment and run node
source "${WORKSPACE_ROOT}/devel/setup.bash"
}
# Build workspace function
build_workspace() {
echo -e "${YELLOW}Workspace structure:${NC}"
echo " Workspace root: ${WORKSPACE_ROOT}"
echo " Source directory: ${WORKSPACE_SRC}"
echo " Package directory: ${PKG_DIR}"
echo " ROS version: ROS1"
echo -e "${YELLOW}Starting ROS1 project build...${NC}"
# Clean
cd $WS_DIR
rm -rf build devel install
# Ensure ROS1 environment is loaded
if [ -f "/opt/ros/noetic/setup.bash" ]; then
source "/opt/ros/noetic/setup.bash"
elif [ -f "/opt/ros/melodic/setup.bash" ]; then
source "/opt/ros/melodic/setup.bash"
else
echo -e "${RED}Could not find ROS1 setup.bash file. Please ensure ROS1 is installed.${NC}"
return 1
fi
# Create temporary package.xml
if [ -f "${PKG_DIR}/package_ros1.xml" ]; then
echo "Creating temporary package.xml (using package_ros1.xml)"
cp "${PKG_DIR}/package_ros1.xml" "${PKG_DIR}/package.xml"
TEMP_PACKAGE=true
elif [ -f "${PKG_DIR}/package.xml" ]; then
echo "Using existing package.xml"
else
echo -e "${RED}Could not find package.xml in package directory${NC}"
return 1
fi
# Set build system variable
export BUILD_SYSTEM=ROS1
# Switch to workspace root and build
cd "${WORKSPACE_ROOT}" || return 1
catkin_make -DBUILD_SYSTEM=ROS1 -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -j$(nproc)
BUILD_RESULT=$?
# If build successful, source environment
if [[ $BUILD_RESULT -eq 0 ]]; then
echo -e "${GREEN}ROS1 build successful, loading environment: source devel/setup.bash${NC}"
source "${WORKSPACE_ROOT}/devel/setup.bash"
else
echo -e "${RED}ROS1 build failed, please check error logs${NC}"
fi
}
# Help function
show_help() {
echo -e "${YELLOW}Usage:${NC}"
echo " ./build_ros.sh # Build project"
echo " ./build_ros.sh -c # Clean build artifacts"
echo " ./build_ros.sh -h # Show help information"
echo ""
echo -e "${YELLOW}Current configuration:${NC}"
echo " Project name: ${PROJECT_NAME}"
echo " Package directory: ${PKG_DIR}"
echo " Workspace root: ${WORKSPACE_ROOT}"
echo " Source directory: ${WORKSPACE_SRC}"
}
# Main
case "$1" in
-c|--clean)
clean_workspace
;;
-r|--run)
run_node
;;
-h|--help)
show_help
;;
*)
build_workspace
;;
esac
+172
View File
@@ -0,0 +1,172 @@
#!/bin/bash
# Get the directory where the script is located (Odin_ROS_Driver directory)
PKG_DIR="$(cd "$(dirname "$0")/.."; pwd)"
# Calculate the workspace root directory (contains devel, build, src)
WORKSPACE_ROOT="$(dirname "$(dirname "$PKG_DIR")")"
# Workspace source directory (contains all packages)
WORKSPACE_SRC="${WORKSPACE_ROOT}/src"
PROJECT_NAME="odin_ros_driver"
PACKAGE_DIR_NAME=$(basename "$PKG_DIR")
# Define color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
# Extract package name from package.xml
get_package_name() {
local package_xml="$1"
if [ -f "$package_xml" ]; then
# Extract content of <name> tag
grep -oP '<name>\K[^<]+' "$package_xml" | head -1
else
echo ""
fi
}
# Clean workspace function
clean_workspace() {
echo -e "${YELLOW}Cleaning build directories${NC}"
# Clean build artifacts in workspace
rm -rf "${WORKSPACE_ROOT}/build"
rm -rf "${WORKSPACE_ROOT}/install"
rm -rf "${WORKSPACE_ROOT}/log"
rm -rf "${WORKSPACE_ROOT}/devel"
echo -e "${GREEN}Cleanup complete${NC}"
}
# Run node function
run_node() {
echo -e "${YELLOW}Running ROS2 node${NC}"
# Check if environment file exists
if [ ! -f "${WORKSPACE_ROOT}/install/setup.bash" ]; then
echo -e "${RED}Could not find install/setup.bash, please build the project with ./build_ros2.sh first${NC}"
return 1
fi
# Source environment and run node
source "${WORKSPACE_ROOT}/install/setup.bash"
}
# Build workspace function
build_workspace() {
echo -e "${YELLOW}Workspace structure:${NC}"
echo " Workspace root: ${WORKSPACE_ROOT}"
echo " Source directory: ${WORKSPACE_SRC}"
echo " Package directory: ${PKG_DIR}"
echo " Directory name: ${PACKAGE_DIR_NAME}"
echo " ROS version: ROS2"
echo -e "${YELLOW}Starting ROS2 project build...${NC}"
cd $WS_DIR
rm -rf build install log
# Ensure ROS2 environment is loaded.
# 1) Prefer the currently active distro (ROS_DISTRO env var) if its setup.bash exists.
# 2) Otherwise probe a known list of ROS2 distros from newest to oldest.
ROS2_DISTRO_CANDIDATES=("rolling" "jazzy" "iron" "humble" "galactic" "foxy")
ROS2_SETUP_BASH=""
if [ -n "${ROS_DISTRO}" ] && [ -f "/opt/ros/${ROS_DISTRO}/setup.bash" ]; then
ROS2_SETUP_BASH="/opt/ros/${ROS_DISTRO}/setup.bash"
else
for distro in "${ROS2_DISTRO_CANDIDATES[@]}"; do
if [ -f "/opt/ros/${distro}/setup.bash" ]; then
ROS2_SETUP_BASH="/opt/ros/${distro}/setup.bash"
break
fi
done
fi
if [ -n "${ROS2_SETUP_BASH}" ]; then
echo -e "${GREEN}Sourcing ROS2 environment: ${ROS2_SETUP_BASH}${NC}"
# shellcheck disable=SC1090
source "${ROS2_SETUP_BASH}"
else
echo -e "${RED}Could not find ROS2 setup.bash file. Please ensure ROS2 is installed.${NC}"
return 1
fi
# Create temporary package.xml
if [ -f "${PKG_DIR}/package_ros2.xml" ]; then
echo "Creating temporary package.xml (using package_ros2.xml)"
cp "${PKG_DIR}/package_ros2.xml" "${PKG_DIR}/package.xml"
TEMP_PACKAGE=true
elif [ -f "${PKG_DIR}/package.xml" ]; then
echo "Using existing package.xml"
TEMP_PACKAGE=false
else
echo -e "${RED}Could not find package.xml in package directory${NC}"
return 1
fi
# Extract package name from package.xml
PACKAGE_NAME=$(get_package_name "${PKG_DIR}/package.xml")
if [ -z "$PACKAGE_NAME" ]; then
echo -e "${RED}Failed to extract package name from package.xml${NC}"
return 1
fi
echo " Package name: ${PACKAGE_NAME}"
# Set build system variable
export BUILD_SYSTEM=ROS2
# Switch to workspace root and build
cd "${WORKSPACE_ROOT}" || return 1
# Build with correct package name
colcon build \
--packages-select "${PACKAGE_NAME}" \
--parallel-workers $(nproc) \
--cmake-args \
-DBUILD_SYSTEM=ROS2 \
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON
BUILD_RESULT=$?
# If build successful, source environment
if [[ $BUILD_RESULT -eq 0 ]]; then
echo -e "${GREEN}ROS2 build successful, loading environment: source install/setup.bash${NC}"
source "${WORKSPACE_ROOT}/install/setup.bash"
else
echo -e "${RED}ROS2 build failed, please check error logs${NC}"
fi
}
# Help function
show_help() {
echo -e "${YELLOW}Usage:${NC}"
echo " ./build_ros2.sh # Build project"
echo " ./build_ros2.sh -c # Clean build artifacts"
echo " ./build_ros2.sh -h # Show help information"
echo ""
echo -e "${YELLOW}Current configuration:${NC}"
echo " Project name: ${PROJECT_NAME}"
echo " Package directory: ${PKG_DIR}"
echo " Workspace root: ${WORKSPACE_ROOT}"
echo " Source directory: ${WORKSPACE_SRC}"
}
# Main program
case "$1" in
-c|--clean)
clean_workspace
;;
-r|--run)
run_node
;;
-h|--help)
show_help
;;
*)
build_workspace
;;
esac
@@ -0,0 +1,18 @@
# rosbag2_qos.yaml
# QoS overrides for rosbag2 recording
# 用于 rosbag2 录制的 QoS 配置
#
# Usage / 使用方法:
# ros2 bag record -a --qos-profile-overrides-path rosbag2_qos.yaml
# High frequency data (IMU 400Hz, Odom 100Hz)
# 高频数据 (IMU 400Hz, 里程计 100Hz)
/odin1/imu:
reliability: reliable
history: keep_last
depth: 4000
/odin1/odometry_highfreq:
reliability: reliable
history: keep_last
depth: 4000
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
# Usage: ./set_param.sh <parameter_name> <value>
# Example: ./set_param.sh save_map 1
if [ $# -ne 2 ]; then
echo "Usage: $0 <parameter_name> <value>"
echo "Example: $0 save_map 1"
exit 1
fi
PARAM_NAME=$1
VALUE=$2
COMMAND_FILE="/tmp/odin_command.txt"
# Create the command file with the parameter
echo "set $PARAM_NAME $VALUE" > "$COMMAND_FILE"
echo "Command sent: set $PARAM_NAME $VALUE"
echo "Command file: $COMMAND_FILE"
@@ -0,0 +1,232 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "camera_pose_visualization.h"
const Eigen::Vector3d camera_pose_visualization::imlt = Eigen::Vector3d(-1.0, -0.5, 1.0);
const Eigen::Vector3d camera_pose_visualization::imrt = Eigen::Vector3d( 1.0, -0.5, 1.0);
const Eigen::Vector3d camera_pose_visualization::imlb = Eigen::Vector3d(-1.0, 0.5, 1.0);
const Eigen::Vector3d camera_pose_visualization::imrb = Eigen::Vector3d( 1.0, 0.5, 1.0);
const Eigen::Vector3d camera_pose_visualization::lt0 = Eigen::Vector3d(-0.7, -0.5, 1.0);
const Eigen::Vector3d camera_pose_visualization::lt1 = Eigen::Vector3d(-0.7, -0.2, 1.0);
const Eigen::Vector3d camera_pose_visualization::lt2 = Eigen::Vector3d(-1.0, -0.2, 1.0);
const Eigen::Vector3d camera_pose_visualization::oc = Eigen::Vector3d(0.0, 0.0, 0.0);
#ifdef ROS2
using GeometryPoint = geometry_msgs::msg::Point;
#else
using GeometryPoint = geometry_msgs::Point;
#endif
void Eigen2Point(const Eigen::Vector3d& v, GeometryPoint& p) {
p.x = v.x();
p.y = v.y();
p.z = v.z();
}
camera_pose_visualization::camera_pose_visualization(float r, float g, float b, float a)
: m_marker_ns("camera_pose_visualization"), m_scale(0.3), m_line_width(0.03) {
m_image_boundary_color.r = r;
m_image_boundary_color.g = g;
m_image_boundary_color.b = b;
m_image_boundary_color.a = a;
m_optical_center_connector_color.r = r;
m_optical_center_connector_color.g = g;
m_optical_center_connector_color.b = b;
m_optical_center_connector_color.a = a;
}
void camera_pose_visualization::setImageBoundaryColor(float r, float g, float b, float a) {
m_image_boundary_color.r = r;
m_image_boundary_color.g = g;
m_image_boundary_color.b = b;
m_image_boundary_color.a = a;
}
void camera_pose_visualization::setOpticalCenterConnectorColor(float r, float g, float b, float a) {
m_optical_center_connector_color.r = r;
m_optical_center_connector_color.g = g;
m_optical_center_connector_color.b = b;
m_optical_center_connector_color.a = a;
}
void camera_pose_visualization::setScale(double s) {
m_scale = s;
}
void camera_pose_visualization::setLineWidth(double width) {
m_line_width = width;
}
void camera_pose_visualization::add_edge(const Eigen::Vector3d& p0, const Eigen::Vector3d& p1) {
Marker marker;
marker.ns = m_marker_ns;
marker.id = m_markers.size() + 1;
#ifdef ROS2
marker.type = Marker::LINE_LIST;
marker.action = Marker::ADD;
#else
marker.type = visualization_msgs::Marker::LINE_LIST;
marker.action = visualization_msgs::Marker::ADD;
#endif
marker.scale.x = 0.005;
marker.color.g = 1.0f;
marker.color.a = 1.0;
GeometryPoint point0, point1;
Eigen2Point(p0, point0);
Eigen2Point(p1, point1);
marker.points.push_back(point0);
marker.points.push_back(point1);
m_markers.push_back(marker);
}
void camera_pose_visualization::add_loopedge(const Eigen::Vector3d& p0, const Eigen::Vector3d& p1) {
Marker marker;
marker.ns = m_marker_ns;
marker.id = m_markers.size() + 1;
#ifdef ROS2
marker.type = Marker::LINE_LIST;
marker.action = Marker::ADD;
#else
marker.type = visualization_msgs::Marker::LINE_LIST;
marker.action = visualization_msgs::Marker::ADD;
#endif
marker.scale.x = 0.04;
//marker.scale.x = 0.3;
marker.color.r = 1.0f;
marker.color.b = 1.0f;
marker.color.a = 1.0;
GeometryPoint point0, point1;
Eigen2Point(p0, point0);
Eigen2Point(p1, point1);
marker.points.push_back(point0);
marker.points.push_back(point1);
m_markers.push_back(marker);
}
void camera_pose_visualization::add_pose(const Eigen::Vector3d& p, const Eigen::Quaterniond& q) {
Marker marker;
marker.ns = m_marker_ns;
marker.id = m_markers.size() + 1;
#ifdef ROS2
marker.type = Marker::LINE_STRIP;
marker.action = Marker::ADD;
#else
marker.type = visualization_msgs::Marker::LINE_STRIP;
marker.action = visualization_msgs::Marker::ADD;
#endif
marker.scale.x = m_line_width;
marker.pose.position.x = 0.0;
marker.pose.position.y = 0.0;
marker.pose.position.z = 0.0;
marker.pose.orientation.w = 1.0;
marker.pose.orientation.x = 0.0;
marker.pose.orientation.y = 0.0;
marker.pose.orientation.z = 0.0;
GeometryPoint pt_lt, pt_lb, pt_rt, pt_rb, pt_oc, pt_lt0, pt_lt1, pt_lt2;
Eigen2Point(q * (m_scale * imlt) + p, pt_lt);
Eigen2Point(q * (m_scale * imlb) + p, pt_lb);
Eigen2Point(q * (m_scale * imrt) + p, pt_rt);
Eigen2Point(q * (m_scale * imrb) + p, pt_rb);
Eigen2Point(q * (m_scale * lt0 ) + p, pt_lt0);
Eigen2Point(q * (m_scale * lt1 ) + p, pt_lt1);
Eigen2Point(q * (m_scale * lt2 ) + p, pt_lt2);
Eigen2Point(q * (m_scale * oc ) + p, pt_oc);
// image boundaries
marker.points.push_back(pt_lt);
marker.points.push_back(pt_lb);
marker.colors.push_back(m_image_boundary_color);
marker.colors.push_back(m_image_boundary_color);
marker.points.push_back(pt_lb);
marker.points.push_back(pt_rb);
marker.colors.push_back(m_image_boundary_color);
marker.colors.push_back(m_image_boundary_color);
marker.points.push_back(pt_rb);
marker.points.push_back(pt_rt);
marker.colors.push_back(m_image_boundary_color);
marker.colors.push_back(m_image_boundary_color);
marker.points.push_back(pt_rt);
marker.points.push_back(pt_lt);
marker.colors.push_back(m_image_boundary_color);
marker.colors.push_back(m_image_boundary_color);
// top-left indicator
marker.points.push_back(pt_lt0);
marker.points.push_back(pt_lt1);
marker.colors.push_back(m_image_boundary_color);
marker.colors.push_back(m_image_boundary_color);
marker.points.push_back(pt_lt1);
marker.points.push_back(pt_lt2);
marker.colors.push_back(m_image_boundary_color);
marker.colors.push_back(m_image_boundary_color);
// optical center connector
marker.points.push_back(pt_lt);
marker.points.push_back(pt_oc);
marker.colors.push_back(m_optical_center_connector_color);
marker.colors.push_back(m_optical_center_connector_color);
marker.points.push_back(pt_lb);
marker.points.push_back(pt_oc);
marker.colors.push_back(m_optical_center_connector_color);
marker.colors.push_back(m_optical_center_connector_color);
marker.points.push_back(pt_rt);
marker.points.push_back(pt_oc);
marker.colors.push_back(m_optical_center_connector_color);
marker.colors.push_back(m_optical_center_connector_color);
marker.points.push_back(pt_rb);
marker.points.push_back(pt_oc);
marker.colors.push_back(m_optical_center_connector_color);
marker.colors.push_back(m_optical_center_connector_color);
m_markers.push_back(marker);
}
void camera_pose_visualization::reset() {
m_markers.clear();
}
void camera_pose_visualization::publish_by( Publisher& pub, const Header& header ) {
MarkerArray markerArray_msg;
for (auto& marker : m_markers) {
marker.header = header;
markerArray_msg.markers.push_back(marker);
}
pub.publish(markerArray_msg);
}
@@ -0,0 +1,507 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "cloud_reprojection_ros_node.hpp"
#include "odin_calib_path.h"
#include <fstream>
#include <sys/stat.h>
#include <thread>
#include <chrono>
#ifdef ROS2
#include <functional>
#include <yaml-cpp/yaml.h>
#include <rcpputils/filesystem_helper.hpp>
#else
#include <boost/bind.hpp>
#endif
// Fixed Til (T_imu_lidar): lidar position in imu frame, transforms from lidar to imu
// TODO: Fill in the actual Til values for your sensor setup
static Eigen::Matrix4d getFixedTil()
{
Eigen::Matrix4d Til = Eigen::Matrix4d::Identity();
Til(0, 3) = -0.02663;
Til(1, 3) = 0.03447;
Til(2, 3) = 0.02174;
return Til;
}
static bool fileExists(const std::string& filename) {
struct stat buffer;
return (stat(filename.c_str(), &buffer) == 0);
}
#ifdef ROS2
// Helper function to get package source directory for ROS2
static std::string get_package_source_directory() {
std::string current_file = __FILE__;
size_t pos = current_file.find("/src/cloud_reprojection_ros.cpp");
if (pos != std::string::npos) {
return current_file.substr(0, pos);
}
return "";
}
// ==================== ROS2 Implementation ====================
CloudReprojectionRosNode::CloudReprojectionRosNode(const rclcpp::NodeOptions& options)
: Node("cloud_reprojection_node", options)
{
loadParameters();
RCLCPP_INFO_STREAM(this->get_logger(),
"\n cloud_slam_topic: " << cloud_slam_topic_
<< "\n odometry_topic: " << odometry_topic_
<< "\n wiwc_topic: " << wiwc_topic_
<< "\n reprojected_image_topic: " << reprojected_image_topic_);
cloud_sub_.subscribe(this, cloud_slam_topic_);
odom_sub_.subscribe(this, odometry_topic_);
wiwc_sub_.subscribe(this, wiwc_topic_);
sync_ = std::make_shared<Sync>(MySyncPolicy(10), cloud_sub_, odom_sub_, wiwc_sub_);
sync_->registerCallback(std::bind(&CloudReprojectionRosNode::syncCallback, this,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
reprojected_image_pub_ = image_transport::create_publisher(this, reprojected_image_topic_);
RCLCPP_INFO(this->get_logger(), "CloudReprojectionRosNode initialized successfully");
}
void CloudReprojectionRosNode::loadParameters()
{
// Declare and get parameters
this->declare_parameter<std::string>("cloud_slam_topic", "/odin1/cloud_slam");
this->declare_parameter<std::string>("odometry_topic", "/odin1/odometry");
this->declare_parameter<std::string>("wiwc_topic", "/odin1/wiwc");
this->declare_parameter<std::string>("reprojected_image_topic", "/odin1/reprojected_image");
cloud_slam_topic_ = this->get_parameter("cloud_slam_topic").as_string();
odometry_topic_ = this->get_parameter("odometry_topic").as_string();
wiwc_topic_ = this->get_parameter("wiwc_topic").as_string();
reprojected_image_topic_ = this->get_parameter("reprojected_image_topic").as_string();
// Load camera parameters from calib.yaml in the shared runtime dir
std::string calib_file = odin_ros_driver::GetOdinCalibFile();
RCLCPP_INFO(this->get_logger(), "========== [CALIB] READ <- %s ==========", calib_file.c_str());
YAML::Node calib_config;
try {
calib_config = YAML::LoadFile(calib_file);
} catch (const std::exception& e) {
RCLCPP_ERROR(this->get_logger(), "Failed to load calib.yaml: %s", e.what());
rclcpp::shutdown();
return;
}
CloudReprojector::CameraParams cam_params;
try {
cam_params.image_width = calib_config["cam_0"]["image_width"].as<int>();
cam_params.image_height = calib_config["cam_0"]["image_height"].as<int>();
cam_params.A11 = calib_config["cam_0"]["A11"].as<double>();
cam_params.A12 = calib_config["cam_0"]["A12"].as<double>();
cam_params.A22 = calib_config["cam_0"]["A22"].as<double>();
cam_params.u0 = calib_config["cam_0"]["u0"].as<double>();
cam_params.v0 = calib_config["cam_0"]["v0"].as<double>();
cam_params.k2 = calib_config["cam_0"]["k2"].as<double>();
cam_params.k3 = calib_config["cam_0"]["k3"].as<double>();
cam_params.k4 = calib_config["cam_0"]["k4"].as<double>();
cam_params.k5 = calib_config["cam_0"]["k5"].as<double>();
cam_params.k6 = calib_config["cam_0"]["k6"].as<double>();
cam_params.k7 = calib_config["cam_0"]["k7"].as<double>();
} catch (const std::exception& e) {
RCLCPP_ERROR(this->get_logger(), "Failed to parse camera parameters: %s", e.what());
rclcpp::shutdown();
return;
}
// Load extrinsic parameters
CloudReprojector::ExtrinsicParams ext_params;
try {
auto Tcl_vec = calib_config["Tcl_0"].as<std::vector<double>>();
if (Tcl_vec.size() == 16)
{
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
ext_params.Tcl(i, j) = Tcl_vec[i * 4 + j];
}
else
{
RCLCPP_ERROR(this->get_logger(), "Tcl_0 has invalid size: %zu (expected 16)", Tcl_vec.size());
rclcpp::shutdown();
return;
}
} catch (const std::exception& e) {
RCLCPP_ERROR(this->get_logger(), "Failed to parse Tcl_0: %s", e.what());
rclcpp::shutdown();
return;
}
ext_params.Til = getFixedTil();
ext_params.Tic = CloudReprojector::calculateTic(ext_params.Tcl, ext_params.Til);
RCLCPP_INFO_STREAM(this->get_logger(), "Loaded Tcl (camera to lidar):\n" << ext_params.Tcl);
RCLCPP_INFO_STREAM(this->get_logger(), "Fixed Til (lidar to imu):\n" << ext_params.Til);
RCLCPP_INFO_STREAM(this->get_logger(), "Calculated Tic:\n" << ext_params.Tic);
RCLCPP_INFO(this->get_logger(), "Camera intrinsics:");
RCLCPP_INFO(this->get_logger(), "Image size: %dx%d", cam_params.image_width, cam_params.image_height);
RCLCPP_INFO(this->get_logger(), "Intrinsics: A11=%f A12=%f A22=%f u0=%f v0=%f",
cam_params.A11, cam_params.A12, cam_params.A22, cam_params.u0, cam_params.v0);
reprojector_ = std::make_unique<CloudReprojector>();
if (!reprojector_->initialize(cam_params, ext_params))
{
RCLCPP_ERROR(this->get_logger(), "Failed to initialize CloudReprojector");
rclcpp::shutdown();
}
}
void CloudReprojectionRosNode::syncCallback(
const PointCloud2::ConstSharedPtr& cloud_msg,
const Odometry::ConstSharedPtr& odom_msg,
const Odometry::ConstSharedPtr& wiwc_msg)
{
// Debug: print that syncCallback is called
static int sync_count = 0;
// RCLCPP_INFO(this->get_logger(), "=== syncCallback called, count: %d ===", ++sync_count);
pcl::PointCloud<pcl::PointXYZRGB> cloud_odom;
pcl::fromROSMsg(*cloud_msg, cloud_odom);
if (cloud_odom.empty())
{
RCLCPP_WARN(this->get_logger(), "Empty cloud_slam received");
return;
}
// Extract real-time extrinsics from WIWC message covariance fields
// pose.covariance contains T_CL (first 16 values), twist.covariance contains T_IL (first 16 values)
Eigen::Matrix4d T_CL = Eigen::Matrix4d::Identity();
Eigen::Matrix4d T_IL = Eigen::Matrix4d::Identity();
for (int i = 0; i < 16; ++i) {
T_CL(i / 4, i % 4) = wiwc_msg->pose.covariance[i];
T_IL(i / 4, i % 4) = wiwc_msg->twist.covariance[i];
}
// Update extrinsics if valid (not identity matrix)
bool T_CL_valid = (T_CL - Eigen::Matrix4d::Identity()).norm() > 1e-6;
bool T_IL_valid = (T_IL - Eigen::Matrix4d::Identity()).norm() > 1e-6;
// // Debug print to compare with host_sdk_sample values
// static int print_count = 0;
// if (print_count++) {
// // Extract rotation (3x3) and translation (3x1) from T_CL
// Eigen::Matrix3d RCL = T_CL.block<3,3>(0,0);
// Eigen::Vector3d TCL = T_CL.block<3,1>(0,3);
// RCLCPP_INFO_STREAM(this->get_logger(), "=== cloud_reprojection RCL (3x3 rotation from T_CL) ===\n" << RCL);
// RCLCPP_INFO_STREAM(this->get_logger(), "=== cloud_reprojection TCL (3x1 translation from T_CL) ===\n" << TCL.transpose());
// // Extract rotation (3x3) and translation (3x1) from T_IL
// Eigen::Matrix3d RIL = T_IL.block<3,3>(0,0);
// Eigen::Vector3d TIL = T_IL.block<3,1>(0,3);
// RCLCPP_INFO_STREAM(this->get_logger(), "=== cloud_reprojection RIL (3x3 rotation from T_IL) ===\n" << RIL);
// RCLCPP_INFO_STREAM(this->get_logger(), "=== cloud_reprojection TIL (3x1 translation from T_IL) ===\n" << TIL.transpose());
// RCLCPP_INFO(this->get_logger(), "T_CL_valid: %d, T_IL_valid: %d", T_CL_valid, T_IL_valid);
// if (T_CL_valid && T_IL_valid) {
// Eigen::Matrix4d Tic = CloudReprojector::calculateTic(T_CL, T_IL);
// RCLCPP_INFO_STREAM(this->get_logger(), "=== cloud_reprojection calculated Tic ===\n" << Tic);
// }
// }
if (T_CL_valid && T_IL_valid) {
reprojector_->updateExtrinsics(T_CL, T_IL);
}
CloudReprojector::OdomPose odom_pose;
odom_pose.orientation = Eigen::Quaterniond(
odom_msg->pose.pose.orientation.w,
odom_msg->pose.pose.orientation.x,
odom_msg->pose.pose.orientation.y,
odom_msg->pose.pose.orientation.z
);
odom_pose.position = Eigen::Vector3d(
odom_msg->pose.pose.position.x,
odom_msg->pose.pose.position.y,
odom_msg->pose.pose.position.z
);
cv::Mat reprojected_img = reprojector_->reprojectCloud(cloud_odom, odom_pose);
auto img_msg = cv_bridge::CvImage(cloud_msg->header, "bgr8", reprojected_img).toImageMsg();
reprojected_image_pub_.publish(*img_msg);
}
// ==================== ROS2 Main ====================
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
auto temp_node = std::make_shared<rclcpp::Node>("cloud_reprojection_check");
// Check if reprojection is enabled from control_command.yaml
std::string package_path = get_package_source_directory();
std::string config_file = package_path + "/config/control_command.yaml";
try {
YAML::Node config = YAML::LoadFile(config_file);
std::cout << "config: " << config_file << std::endl;
if (!config["register_keys"] || !config["register_keys"]["sendreprojection"]) {
RCLCPP_INFO(temp_node->get_logger(), "sendreprojection parameter not found, cloud reprojection disabled.");
rclcpp::shutdown();
return 0;
}
int sendreprojection = config["register_keys"]["sendreprojection"].as<int>();
if (sendreprojection == 0) {
RCLCPP_INFO(temp_node->get_logger(), "Cloud reprojection will not be published.");
rclcpp::shutdown();
return 0;
}
} catch (const std::exception& e) {
RCLCPP_ERROR(temp_node->get_logger(), "Failed to read config: %s", e.what());
rclcpp::shutdown();
return 1;
}
// Wait for calib.yaml file to be generated by host_sdk_sample
std::string calib_file = odin_ros_driver::GetOdinCalibFile();
RCLCPP_INFO(temp_node->get_logger(), "========== [CALIB] WAIT <- %s ==========", calib_file.c_str());
int wait_count = 0;
while (rclcpp::ok() && !fileExists(calib_file)) {
if (wait_count % 10 == 0) {
RCLCPP_INFO(temp_node->get_logger(), "Still waiting for calib.yaml file...");
}
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
wait_count++;
// Timeout after 5 seconds
if (wait_count > 10) {
RCLCPP_ERROR(temp_node->get_logger(), "Timeout waiting for calib.yaml file");
rclcpp::shutdown();
return 1;
}
}
if (!rclcpp::ok()) {
RCLCPP_INFO(temp_node->get_logger(), "Node shutdown before calib.yaml file was found.");
return 0;
}
RCLCPP_INFO(temp_node->get_logger(), "Found calib.yaml file! Starting cloud reprojection node...");
auto node = std::make_shared<CloudReprojectionRosNode>();
RCLCPP_INFO(node->get_logger(), "CloudReprojectionRosNode started");
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}
#else
// ==================== ROS1 Implementation ====================
CloudReprojectionRosNode::CloudReprojectionRosNode(ros::NodeHandle& nh, ros::NodeHandle& pnh)
: nh_(nh), pnh_(pnh)
{
loadParameters();
ROS_INFO_STREAM("\n cloud_slam_topic: " << cloud_slam_topic_
<< "\n odometry_topic: " << odometry_topic_
<< "\n wiwc_topic: " << wiwc_topic_
<< "\n reprojected_image_topic: " << reprojected_image_topic_);
cloud_sub_.subscribe(nh_, cloud_slam_topic_, 1);
odom_sub_.subscribe(nh_, odometry_topic_, 1);
wiwc_sub_.subscribe(nh_, wiwc_topic_, 1);
sync_ = std::make_shared<Sync>(MySyncPolicy(10), cloud_sub_, odom_sub_, wiwc_sub_);
sync_->registerCallback(boost::bind(&CloudReprojectionRosNode::syncCallback, this, _1, _2, _3));
reprojected_image_pub_ = nh_.advertise<sensor_msgs::Image>(reprojected_image_topic_, 1);
ROS_INFO("CloudReprojectionRosNode initialized successfully");
}
void CloudReprojectionRosNode::loadParameters()
{
pnh_.param<std::string>("cloud_slam_topic", cloud_slam_topic_, std::string("/odin1/cloud_slam"));
pnh_.param<std::string>("odometry_topic", odometry_topic_, std::string("/odin1/odometry"));
pnh_.param<std::string>("wiwc_topic", wiwc_topic_, std::string("/odin1/wiwc"));
pnh_.param<std::string>("reprojected_image_topic", reprojected_image_topic_, std::string("/odin1/reprojected_image"));
// Load camera parameters
CloudReprojector::CameraParams cam_params;
pnh_.param<int>("cam_0/image_width", cam_params.image_width, 1600);
pnh_.param<int>("cam_0/image_height", cam_params.image_height, 1296);
pnh_.param<double>("cam_0/A11", cam_params.A11, 0.0);
pnh_.param<double>("cam_0/A12", cam_params.A12, 0.0);
pnh_.param<double>("cam_0/A22", cam_params.A22, 0.0);
pnh_.param<double>("cam_0/u0", cam_params.u0, 0.0);
pnh_.param<double>("cam_0/v0", cam_params.v0, 0.0);
pnh_.param<double>("cam_0/k2", cam_params.k2, 0.0);
pnh_.param<double>("cam_0/k3", cam_params.k3, 0.0);
pnh_.param<double>("cam_0/k4", cam_params.k4, 0.0);
pnh_.param<double>("cam_0/k5", cam_params.k5, 0.0);
pnh_.param<double>("cam_0/k6", cam_params.k6, 0.0);
pnh_.param<double>("cam_0/k7", cam_params.k7, 0.0);
// Load extrinsic parameters
CloudReprojector::ExtrinsicParams ext_params;
std::vector<double> Tcl_vec_param;
if (pnh_.getParam("Tcl_0", Tcl_vec_param) && Tcl_vec_param.size() == 16)
{
for (int i = 0; i < 4; ++i)
for (int j = 0; j < 4; ++j)
ext_params.Tcl(i, j) = Tcl_vec_param[i * 4 + j];
}
else
{
ROS_ERROR("Tcl_0 param missing or invalid.");
ros::shutdown();
return;
}
ext_params.Til = getFixedTil();
ext_params.Tic = CloudReprojector::calculateTic(ext_params.Tcl, ext_params.Til);
ROS_INFO_STREAM("Loaded Tcl (camera to lidar):\n" << ext_params.Tcl);
ROS_INFO_STREAM("Fixed Til (lidar to imu):\n" << ext_params.Til);
ROS_INFO_STREAM("Calculated Tic:\n" << ext_params.Tic);
ROS_INFO("Camera intrinsics:");
ROS_INFO("Image size: %dx%d", cam_params.image_width, cam_params.image_height);
ROS_INFO("Intrinsics: A11=%f A12=%f A22=%f u0=%f v0=%f",
cam_params.A11, cam_params.A12, cam_params.A22, cam_params.u0, cam_params.v0);
reprojector_ = std::make_unique<CloudReprojector>();
if (!reprojector_->initialize(cam_params, ext_params))
{
ROS_ERROR("Failed to initialize CloudReprojector");
ros::shutdown();
}
}
void CloudReprojectionRosNode::syncCallback(
const sensor_msgs::PointCloud2ConstPtr& cloud_msg,
const nav_msgs::OdometryConstPtr& odom_msg,
const nav_msgs::OdometryConstPtr& wiwc_msg)
{
pcl::PointCloud<pcl::PointXYZRGB> cloud_odom;
pcl::fromROSMsg(*cloud_msg, cloud_odom);
if (cloud_odom.empty())
{
ROS_WARN("Empty cloud_slam received");
return;
}
// Extract real-time extrinsics from WIWC message covariance fields
// pose.covariance contains T_CL (first 16 values), twist.covariance contains T_IL (first 16 values)
Eigen::Matrix4d T_CL = Eigen::Matrix4d::Identity();
Eigen::Matrix4d T_IL = Eigen::Matrix4d::Identity();
for (int i = 0; i < 16; ++i) {
T_CL(i / 4, i % 4) = wiwc_msg->pose.covariance[i];
T_IL(i / 4, i % 4) = wiwc_msg->twist.covariance[i];
}
// Update extrinsics if valid (not identity matrix)
bool T_CL_valid = (T_CL - Eigen::Matrix4d::Identity()).norm() > 1e-6;
bool T_IL_valid = (T_IL - Eigen::Matrix4d::Identity()).norm() > 1e-6;
if (T_CL_valid && T_IL_valid) {
reprojector_->updateExtrinsics(T_CL, T_IL);
}
CloudReprojector::OdomPose odom_pose;
odom_pose.orientation = Eigen::Quaterniond(
odom_msg->pose.pose.orientation.w,
odom_msg->pose.pose.orientation.x,
odom_msg->pose.pose.orientation.y,
odom_msg->pose.pose.orientation.z
);
odom_pose.position = Eigen::Vector3d(
odom_msg->pose.pose.position.x,
odom_msg->pose.pose.position.y,
odom_msg->pose.pose.position.z
);
cv::Mat reprojected_img = reprojector_->reprojectCloud(cloud_odom, odom_pose);
sensor_msgs::ImagePtr img_msg = cv_bridge::CvImage(cloud_msg->header, "bgr8", reprojected_img).toImageMsg();
reprojected_image_pub_.publish(img_msg);
}
// ==================== ROS1 Main ====================
int main(int argc, char **argv)
{
ros::init(argc, argv, "cloud_reprojection");
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
// Check if reprojection is enabled
int sendreprojection = 0;
pnh.param("register_keys/sendreprojection", sendreprojection, 0);
if(sendreprojection == 0)
{
ROS_INFO("Cloud reprojection will not be published.");
return 0;
}
std::string calib_file_path;
pnh.param<std::string>("calib_file_path", calib_file_path, "");
if (calib_file_path.empty()) {
calib_file_path = odin_ros_driver::GetOdinCalibFile();
}
ROS_INFO("========== [CALIB] WAIT <- %s ==========", calib_file_path.c_str());
while(ros::ok() && !fileExists(calib_file_path))
{
ROS_INFO_THROTTLE(5, "Still waiting for calib.yaml file...");
ros::Duration(0.5).sleep();
ros::spinOnce();
}
if(!ros::ok())
{
ROS_INFO("Node shutdown before calib.yaml file was found.");
return 0;
}
ROS_INFO("Found calib.yaml file! Loading parameters...");
std::string node_name = ros::this_node::getName();
std::string rosparam_command = "rosparam load " + calib_file_path + " " + node_name;
int result = system(rosparam_command.c_str());
if(result == 0)
{
ROS_INFO("Successfully loaded parameters from calib.yaml to namespace: %s", node_name.c_str());
}
else
{
ROS_ERROR("Failed to load parameters from calib.yaml");
return 1;
}
CloudReprojectionRosNode reprojection_node(nh, pnh);
ros::spin();
return 0;
}
#endif
@@ -0,0 +1,128 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "cloud_reprojector.hpp"
#include <cmath>
CloudReprojector::CloudReprojector()
{
}
bool CloudReprojector::initialize(const CameraParams& cam_params, const ExtrinsicParams& ext_params)
{
camera_params_ = cam_params;
extrinsic_params_ = ext_params;
if (camera_params_.A11 < 1e-6 || camera_params_.A22 < 1e-6 ||
camera_params_.u0 < 1e-6 || camera_params_.v0 < 1e-6)
{
return false;
}
camera_model_ = std::make_unique<mini_vikit::PolynomialCamera>(
camera_params_.image_width, camera_params_.image_height,
camera_params_.A11, camera_params_.A22,
camera_params_.u0, camera_params_.v0,
camera_params_.A12,
camera_params_.k2, camera_params_.k3, camera_params_.k4,
camera_params_.k5, camera_params_.k6, camera_params_.k7
);
initialized_ = true;
return true;
}
Eigen::Matrix4d CloudReprojector::calculateTic(const Eigen::Matrix4d& Tcl, const Eigen::Matrix4d& Til)
{
// Tic = Til * Tlc = Til * Tcl.inverse()
Eigen::Matrix4d Tlc = Tcl.inverse();
return Til * Tlc;
}
Eigen::Matrix4d CloudReprojector::odomPoseToMatrix(const OdomPose& odom) const
{
Eigen::Matrix4d T = Eigen::Matrix4d::Identity();
T.block<3, 3>(0, 0) = odom.orientation.toRotationMatrix();
T(0, 3) = odom.position.x();
T(1, 3) = odom.position.y();
T(2, 3) = odom.position.z();
return T;
}
cv::Mat CloudReprojector::reprojectCloud(const pcl::PointCloud<pcl::PointXYZRGB>& cloud_odom,
const OdomPose& odom_pose)
{
if (!initialized_)
{
return cv::Mat();
}
// T_odom_imu: imu pose in odom frame
Eigen::Matrix4d T_odom_imu = odomPoseToMatrix(odom_pose);
// T_imu_odom: transforms points from odom frame to imu frame
Eigen::Matrix4d T_imu_odom = T_odom_imu.inverse();
// T_cam_imu = Tic.inverse(): transforms from imu to camera
Eigen::Matrix4d T_cam_imu = extrinsic_params_.Tic.inverse();
// T_cam_odom: transforms points from odom frame to camera frame
Eigen::Matrix4d T_cam_odom = T_cam_imu * T_imu_odom;
pcl::PointCloud<pcl::PointXYZRGB> cloud_in_cam;
pcl::transformPointCloud(cloud_odom, cloud_in_cam, T_cam_odom);
return projectCloudToImage(cloud_in_cam);
}
cv::Mat CloudReprojector::projectCloudToImage(const pcl::PointCloud<pcl::PointXYZRGB>& cloud_in_cam) const
{
cv::Mat img = cv::Mat::zeros(camera_params_.image_height, camera_params_.image_width, CV_8UC3);
img.setTo(cv::Scalar(255, 255, 255));
const double fx = camera_model_->fx();
const double fy = camera_model_->fy();
const double cx = camera_model_->cx();
const double cy = camera_model_->cy();
for (const auto& pt : cloud_in_cam)
{
if (pt.z <= 0.01)
continue;
int u_int, v_int;
if (1)
{
// Pinhole projection (undistorted image)
u_int = static_cast<int>(std::round(fx * pt.x / pt.z + cx));
v_int = static_cast<int>(std::round(fy * pt.y / pt.z + cy));
}
else
{
// Distorted projection (original image)
Eigen::Vector3d pt_cam(pt.x, pt.y, pt.z);
Eigen::Vector2d uv = camera_model_->world2cam(pt_cam);
u_int = static_cast<int>(std::round(uv[0]));
v_int = static_cast<int>(std::round(uv[1]));
}
if (u_int >= 0 && u_int < camera_params_.image_width &&
v_int >= 0 && v_int < camera_params_.image_height)
{
cv::circle(img, cv::Point(u_int, v_int), point_radius_,
cv::Scalar(pt.b, pt.g, pt.r), -1);
}
}
return img;
}
@@ -0,0 +1,172 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "depth_image_ros2_node.hpp"
#include <functional>
DepthImageRos2Node::DepthImageRos2Node(const rclcpp::NodeOptions & options)
: Node("depth_image_ros2_node", options)
{
PointCloudToDepthConverter::CameraParams camera_params = loadCameraParams();
depth_converter_ = std::make_unique<PointCloudToDepthConverter>(camera_params);
cloud_raw_topic_ = this->declare_parameter<std::string>("cloud_raw_topic", "/odin1/cloud_raw");
color_compressed_topic_ = this->declare_parameter<std::string>("color_compressed_topic", "/odin1/image/compressed");
color_raw_topic_ = this->declare_parameter<std::string>("color_raw_topic", "/odin1/image");
depth_image_topic_ = this->declare_parameter<std::string>("depth_image_topic", "/odin1/depth_img_competetion");
depth_cloud_topic_ = this->declare_parameter<std::string>("depth_cloud_topic", "/odin1/depth_img_competetion_cloud");
RCLCPP_INFO_STREAM(this->get_logger(),
"\n cloud_raw_topic: " << cloud_raw_topic_
<< "\n color_compressed_topic: " << color_compressed_topic_
<< "\n color_raw_topic: " << color_raw_topic_
<< "\n depth_image_topic: " << depth_image_topic_
<< "\n depth_cloud_topic: " << depth_cloud_topic_);
}
void DepthImageRos2Node::initialize()
{
cloud_sub_.subscribe(this, cloud_raw_topic_);
color_compressed_sub_.subscribe(this, color_compressed_topic_);
color_sub_.subscribe(this, color_raw_topic_);
sync_ = std::make_shared<Sync>(MySyncPolicy(10), cloud_sub_, color_sub_);
sync_->registerCallback(std::bind(&DepthImageRos2Node::syncCallback, this,
std::placeholders::_1, std::placeholders::_2));
it_ = std::make_shared<image_transport::ImageTransport>(shared_from_this());
depth_image_pub_ = it_->advertise(depth_image_topic_, 1);
depth_cloud_pub_ = this->create_publisher<sensor_msgs::msg::PointCloud2>(depth_cloud_topic_, 1);
RCLCPP_INFO(this->get_logger(), "DepthImageRos2Node initialized successfully");
}
PointCloudToDepthConverter::CameraParams DepthImageRos2Node::loadCameraParams()
{
PointCloudToDepthConverter::CameraParams params;
params.image_width = this->declare_parameter<int>("cam_0.image_width", 1600);
params.image_height = this->declare_parameter<int>("cam_0.image_height", 1296);
params.A11 = this->declare_parameter<double>("cam_0.A11", 0.0);
params.A12 = this->declare_parameter<double>("cam_0.A12", 0.0);
params.A22 = this->declare_parameter<double>("cam_0.A22", 0.0);
params.u0 = this->declare_parameter<double>("cam_0.u0", 0.0);
params.v0 = this->declare_parameter<double>("cam_0.v0", 0.0);
params.k2 = this->declare_parameter<double>("cam_0.k2", 0.0);
params.k3 = this->declare_parameter<double>("cam_0.k3", 0.0);
params.k4 = this->declare_parameter<double>("cam_0.k4", 0.0);
params.k5 = this->declare_parameter<double>("cam_0.k5", 0.0);
params.k6 = this->declare_parameter<double>("cam_0.k6", 0.0);
params.k7 = this->declare_parameter<double>("cam_0.k7", 0.0);
params.scale = this->declare_parameter<double>("scale", 7.0);
params.point_sampling_rate = this->declare_parameter<int>("point_sampling_rate", 5);
std::vector<double> Tcl_vec_param = this->declare_parameter<std::vector<double>>("Tcl_0", std::vector<double>(16, 0.0));
if (Tcl_vec_param.size() == 16)
{
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
params.Tcl(i, j) = Tcl_vec_param[i * 4 + j];
}
}
}
else
{
RCLCPP_ERROR(this->get_logger(), "Tcl_0 param missing or invalid, colored reproject cloud disabled.");
rclcpp::shutdown();
}
if (params.A11 < 1e-6 || params.A22 < 1e-6 || params.u0 < 1e-6 || params.v0 < 1e-6)
{
RCLCPP_ERROR(this->get_logger(), "Invalid camera intrinsics A11 or A22");
rclcpp::shutdown();
}
RCLCPP_INFO(this->get_logger(), "Camera intrinsics:");
RCLCPP_INFO(this->get_logger(), "Image size: %dx%d", params.image_width, params.image_height);
RCLCPP_INFO(this->get_logger(), "Intrinsics: A11=%f A12=%f A22=%f u0=%f v0=%f",
params.A11, params.A12, params.A22, params.u0, params.v0);
RCLCPP_INFO(this->get_logger(), "Distortions: k2=%f k3=%f k4=%f k5=%f k6=%f k7=%f",
params.k2, params.k3, params.k4, params.k5, params.k6, params.k7);
RCLCPP_INFO(this->get_logger(), "Scale: %f, Point sampling rate: %d", params.scale, params.point_sampling_rate);
RCLCPP_INFO_STREAM(this->get_logger(), "Extrinsics (Tcl):\n" << params.Tcl);
return params;
}
void DepthImageRos2Node::syncCallback(const sensor_msgs::msg::PointCloud2::ConstSharedPtr cloud_msg,
// const sensor_msgs::msg::CompressedImage::ConstSharedPtr image_msg,
const sensor_msgs::msg::Image::ConstSharedPtr color_msg)
{
pcl::PointCloud<pcl::PointXYZ> cloud;
pcl::fromROSMsg(*cloud_msg, cloud);
if (cloud.empty())
{
RCLCPP_WARN(this->get_logger(), "Empty point cloud received");
return;
}
cv::Mat img_raw;
try
{
// img_raw = cv::imdecode(cv::Mat(image_msg->data), cv::IMREAD_COLOR);
cv_bridge::CvImageConstPtr cv_ptr = cv_bridge::toCvShare(color_msg, "bgr8");
img_raw = cv_ptr->image;
if (img_raw.empty())
{
RCLCPP_WARN(this->get_logger(), "Failed to decode compressed image");
return;
}
}
catch (const cv_bridge::Exception &e)
{
RCLCPP_ERROR(this->get_logger(), "cv_bridge: %s", e.what());
return;
}
auto result = depth_converter_->processCloudAndImage(cloud, img_raw);
if (!result.success)
{
RCLCPP_WARN(this->get_logger(), "Data processing failed: %s", result.error_message.c_str());
return;
}
publishDepthImage(result.depth_image, cloud_msg->header);
publishDepthCloud(result.colored_cloud, cloud_msg->header);
}
void DepthImageRos2Node::publishDepthImage(const cv::Mat &img,
const std_msgs::msg::Header &header,
const std::string &encoding)
{
sensor_msgs::msg::Image::SharedPtr depth_msg = cv_bridge::CvImage(header, encoding, img).toImageMsg();
depth_image_pub_.publish(*depth_msg);
}
void DepthImageRos2Node::publishDepthCloud(const pcl::PointCloud<pcl::PointXYZRGB> &colored_cloud,
const std_msgs::msg::Header &header)
{
if (!colored_cloud.points.empty())
{
sensor_msgs::msg::PointCloud2 cloud_msg;
pcl::toROSMsg(colored_cloud, cloud_msg);
cloud_msg.header = header;
depth_cloud_pub_->publish(cloud_msg);
}
}
@@ -0,0 +1,165 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "depth_image_ros_node.hpp"
#include <boost/bind.hpp>
DepthImageRosNode::DepthImageRosNode(ros::NodeHandle &nh, ros::NodeHandle &pnh)
: nh_(nh), pnh_(pnh), it_(nh_)
{
PointCloudToDepthConverter::CameraParams camera_params = loadCameraParams();
depth_converter_ = std::make_unique<PointCloudToDepthConverter>(camera_params);
pnh_.param<std::string>("cloud_raw_topic", cloud_raw_topic_, std::string("/odin1/cloud_raw"));
pnh_.param<std::string>("color_raw_topic", color_raw_topic_, std::string("/odin1/image"));
pnh_.param<std::string>("color_compressed_topic_", color_compressed_topic_, std::string("/odin1/image/compressed"));
pnh_.param<std::string>("depth_image_topic", depth_image_topic_, std::string("/odin1/depth_img_competetion"));
pnh_.param<std::string>("depth_cloud_topic", depth_cloud_topic_, std::string("/odin1/depth_img_competetion_cloud"));
ROS_INFO_STREAM("\n cloud_raw_topic: " << cloud_raw_topic_
<< "\n color_raw_topic: " << color_raw_topic_
<< "\n color_compressed_topic: " << color_compressed_topic_
<< "\n depth_image_topic: " << depth_image_topic_
<< "\n depth_cloud_topic: " << depth_cloud_topic_);
cloud_sub_.subscribe(nh_, cloud_raw_topic_, 1);
color_sub_.subscribe(nh_, color_raw_topic_, 1);
color_compressed_sub_.subscribe(nh_, color_compressed_topic_, 1);
sync_ = std::make_shared<Sync>(MySyncPolicy(10), cloud_sub_, color_sub_);
sync_->registerCallback(boost::bind(&DepthImageRosNode::syncCallback, this, _1, _2));
depth_image_pub_ = it_.advertise(depth_image_topic_, 1);
depth_cloud_pub_ = nh_.advertise<sensor_msgs::PointCloud2>(depth_cloud_topic_, 1);
ROS_INFO("DepthImageRosNode initialized successfully");
}
PointCloudToDepthConverter::CameraParams DepthImageRosNode::loadCameraParams()
{
PointCloudToDepthConverter::CameraParams params;
pnh_.param<int>("cam_0/image_width", params.image_width, 1600);
pnh_.param<int>("cam_0/image_height", params.image_height, 1296);
pnh_.param<double>("cam_0/A11", params.A11, 0.0);
pnh_.param<double>("cam_0/A12", params.A12, 0.0);
pnh_.param<double>("cam_0/A22", params.A22, 0.0);
pnh_.param<double>("cam_0/u0", params.u0, 0.0);
pnh_.param<double>("cam_0/v0", params.v0, 0.0);
pnh_.param<double>("cam_0/k2", params.k2, 0.0);
pnh_.param<double>("cam_0/k3", params.k3, 0.0);
pnh_.param<double>("cam_0/k4", params.k4, 0.0);
pnh_.param<double>("cam_0/k5", params.k5, 0.0);
pnh_.param<double>("cam_0/k6", params.k6, 0.0);
pnh_.param<double>("cam_0/k7", params.k7, 0.0);
pnh_.param<double>("scale", params.scale, 7.0);
pnh_.param<int>("point_sampling_rate", params.point_sampling_rate, 5);
std::vector<double> Tcl_vec_param;
if (pnh_.getParam("Tcl_0", Tcl_vec_param) && Tcl_vec_param.size() == 16)
{
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
params.Tcl(i, j) = Tcl_vec_param[i * 4 + j];
}
}
}
else
{
ROS_ERROR("Tcl_0 param missing or invalid, colored reproject cloud disabled.");
ros::shutdown();
}
if (params.A11 < 1e-6 || params.A22 < 1e-6 || params.u0 < 1e-6 || params.v0 < 1e-6)
{
ROS_ERROR("Invalid camera intrinsics A11 or A22");
ros::shutdown();
}
ROS_INFO("Camera intrinsics:");
ROS_INFO("Image size: %dx%d", params.image_width, params.image_height);
ROS_INFO("Intrinsics: A11=%f A12=%f A22=%f u0=%f v0=%f",
params.A11, params.A12, params.A22, params.u0, params.v0);
ROS_INFO("Distortions: k2=%f k3=%f k4=%f k5=%f k6=%f k7=%f",
params.k2, params.k3, params.k4, params.k5, params.k6, params.k7);
ROS_INFO("Scale: %f, Point sampling rate: %d", params.scale, params.point_sampling_rate);
ROS_INFO_STREAM("Extrinsics (Tcl):\n"
<< params.Tcl);
return params;
}
void DepthImageRosNode::syncCallback(const sensor_msgs::PointCloud2ConstPtr &cloud_msg,
const sensor_msgs::ImageConstPtr &image_msg)
{
pcl::PointCloud<pcl::PointXYZ> cloud;
pcl::fromROSMsg(*cloud_msg, cloud);
if (cloud.empty())
{
ROS_WARN("Empty point cloud received");
return;
}
cv::Mat img_raw;
try
{
// img_raw = cv::imdecode(cv::Mat(image_msg->data), cv::IMREAD_COLOR);
cv_bridge::CvImageConstPtr cv_ptr = cv_bridge::toCvShare(image_msg, "bgr8");
img_raw = cv_ptr->image;
if (img_raw.empty())
{
ROS_WARN("Failed to decode compressed image");
return;
}
}
catch (const cv_bridge::Exception &e)
{
ROS_ERROR("cv_bridge: %s", e.what());
return;
}
auto result = depth_converter_->processCloudAndImage(cloud, img_raw);
if (!result.success)
{
ROS_WARN("Data processing failed: %s", result.error_message.c_str());
return;
}
publishDepthImage(result.depth_image, cloud_msg->header);
publishDepthCloud(result.colored_cloud, cloud_msg->header);
}
void DepthImageRosNode::publishDepthImage(const cv::Mat &img,
const std_msgs::Header &header,
const std::string &encoding)
{
sensor_msgs::ImagePtr depth_msg = cv_bridge::CvImage(header, encoding, img).toImageMsg();
depth_image_pub_.publish(depth_msg);
}
void DepthImageRosNode::publishDepthCloud(const pcl::PointCloud<pcl::PointXYZRGB> &colored_cloud,
const std_msgs::Header &header)
{
if (!colored_cloud.points.empty())
{
sensor_msgs::PointCloud2 cloud_msg;
pcl::toROSMsg(colored_cloud, cloud_msg);
cloud_msg.header = header;
depth_cloud_pub_.publish(cloud_msg);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,254 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "image_overlay_node.hpp"
#ifdef ROS2
// ==================== ROS2 Implementation ====================
ImageOverlayNode::ImageOverlayNode(const rclcpp::NodeOptions& options)
: Node("image_overlay_node", options)
{
// Read from register_keys (same structure as control_command.yaml)
this->declare_parameter<std::string>("register_keys.overlay_reprojected_topic", "/odin1/reprojected_image");
this->declare_parameter<std::string>("register_keys.overlay_camera_topic", "/odin1/image/undistorted");
this->declare_parameter<std::string>("register_keys.overlay_output_topic", "/odin1/overlay_image");
this->declare_parameter<double>("register_keys.overlay_alpha", 0.6);
reprojected_topic_ = this->get_parameter("register_keys.overlay_reprojected_topic").as_string();
camera_topic_ = this->get_parameter("register_keys.overlay_camera_topic").as_string();
overlay_topic_ = this->get_parameter("register_keys.overlay_output_topic").as_string();
alpha_ = this->get_parameter("register_keys.overlay_alpha").as_double();
RCLCPP_INFO(this->get_logger(), "Subscribing to: %s and %s",
reprojected_topic_.c_str(), camera_topic_.c_str());
RCLCPP_INFO(this->get_logger(), "Publishing to: %s (alpha=%.2f)", overlay_topic_.c_str(), alpha_);
// Independent subscriptions - no synchronization needed
reproj_sub_ = this->create_subscription<Image>(
reprojected_topic_, 10,
std::bind(&ImageOverlayNode::reprojCallback, this, std::placeholders::_1));
camera_sub_ = this->create_subscription<Image>(
camera_topic_, 10,
std::bind(&ImageOverlayNode::cameraCallback, this, std::placeholders::_1));
overlay_pub_ = this->create_publisher<sensor_msgs::msg::Image>(overlay_topic_, 10);
RCLCPP_INFO(this->get_logger(), "ImageOverlayNode initialized (no-sync mode)");
}
void ImageOverlayNode::reprojCallback(Image::ConstSharedPtr msg)
{
try {
cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, "bgr8");
{
std::lock_guard<std::mutex> lock(mutex_);
latest_reproj_img_ = cv_ptr->image.clone();
latest_header_ = msg->header;
}
} catch (cv_bridge::Exception& e) {
RCLCPP_ERROR(this->get_logger(), "cv_bridge exception (reproj): %s", e.what());
return;
}
publishOverlay();
}
void ImageOverlayNode::cameraCallback(Image::ConstSharedPtr msg)
{
try {
cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, "bgr8");
{
std::lock_guard<std::mutex> lock(mutex_);
latest_camera_img_ = cv_ptr->image.clone();
}
} catch (cv_bridge::Exception& e) {
RCLCPP_ERROR(this->get_logger(), "cv_bridge exception (camera): %s", e.what());
return;
}
publishOverlay();
}
void ImageOverlayNode::publishOverlay()
{
cv::Mat reproj_copy, camera_copy;
std_msgs::msg::Header header_copy;
{
std::lock_guard<std::mutex> lock(mutex_);
if (latest_reproj_img_.empty() || latest_camera_img_.empty()) {
return;
}
reproj_copy = latest_reproj_img_.clone();
camera_copy = latest_camera_img_.clone();
header_copy = latest_header_;
}
if (reproj_copy.size() != camera_copy.size()) {
RCLCPP_WARN(this->get_logger(),
"Image sizes don't match: reproj(%dx%d) vs camera(%dx%d)",
reproj_copy.cols, reproj_copy.rows,
camera_copy.cols, camera_copy.rows);
return;
}
// Create overlay using alpha blending
// Replace white background in reproj with camera image, keep colored points
cv::Mat overlay = camera_copy.clone();
// Blend: where reproj has color (non-white), show reproj color semi-transparently
// where reproj is white (background), show camera image
for (int y = 0; y < reproj_copy.rows; ++y) {
for (int x = 0; x < reproj_copy.cols; ++x) {
cv::Vec3b reproj_pixel = reproj_copy.at<cv::Vec3b>(y, x);
// Check if pixel is not white (has point cloud color)
if (reproj_pixel[0] < 250 || reproj_pixel[1] < 250 || reproj_pixel[2] < 250) {
// Blend reproj color with camera color
cv::Vec3b cam_pixel = camera_copy.at<cv::Vec3b>(y, x);
overlay.at<cv::Vec3b>(y, x) = cv::Vec3b(
static_cast<uchar>(alpha_ * reproj_pixel[0] + (1 - alpha_) * cam_pixel[0]),
static_cast<uchar>(alpha_ * reproj_pixel[1] + (1 - alpha_) * cam_pixel[1]),
static_cast<uchar>(alpha_ * reproj_pixel[2] + (1 - alpha_) * cam_pixel[2])
);
}
// else: keep camera image (already in overlay)
}
}
auto overlay_msg = cv_bridge::CvImage(header_copy, "bgr8", overlay).toImageMsg();
overlay_pub_->publish(*overlay_msg);
}
// ==================== ROS2 Main ====================
int main(int argc, char **argv)
{
rclcpp::init(argc, argv);
auto node = std::make_shared<ImageOverlayNode>();
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}
#else
// ==================== ROS1 Implementation ====================
ImageOverlayNode::ImageOverlayNode(ros::NodeHandle& nh, ros::NodeHandle& pnh)
: nh_(nh), pnh_(pnh)
{
// Read from register_keys (same structure as control_command.yaml)
pnh_.param<std::string>("register_keys/overlay_reprojected_topic", reprojected_topic_, "/odin1/reprojected_image");
pnh_.param<std::string>("register_keys/overlay_camera_topic", camera_topic_, "/odin1/image/undistorted");
pnh_.param<std::string>("register_keys/overlay_output_topic", overlay_topic_, "/odin1/overlay_image");
pnh_.param<double>("register_keys/overlay_alpha", alpha_, 0.6);
ROS_INFO("Subscribing to: %s and %s", reprojected_topic_.c_str(), camera_topic_.c_str());
ROS_INFO("Publishing to: %s (alpha=%.2f)", overlay_topic_.c_str(), alpha_);
// Independent subscriptions - no synchronization needed
reproj_sub_ = nh_.subscribe(reprojected_topic_, 10, &ImageOverlayNode::reprojCallback, this);
camera_sub_ = nh_.subscribe(camera_topic_, 10, &ImageOverlayNode::cameraCallback, this);
overlay_pub_ = nh_.advertise<sensor_msgs::Image>(overlay_topic_, 10);
ROS_INFO("ImageOverlayNode initialized (no-sync mode)");
}
void ImageOverlayNode::reprojCallback(const sensor_msgs::ImageConstPtr& msg)
{
try {
cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, "bgr8");
{
std::lock_guard<std::mutex> lock(mutex_);
latest_reproj_img_ = cv_ptr->image.clone();
latest_header_ = msg->header;
}
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception (reproj): %s", e.what());
return;
}
publishOverlay();
}
void ImageOverlayNode::cameraCallback(const sensor_msgs::ImageConstPtr& msg)
{
try {
cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, "bgr8");
{
std::lock_guard<std::mutex> lock(mutex_);
latest_camera_img_ = cv_ptr->image.clone();
}
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge exception (camera): %s", e.what());
return;
}
publishOverlay();
}
void ImageOverlayNode::publishOverlay()
{
cv::Mat reproj_copy, camera_copy;
std_msgs::Header header_copy;
{
std::lock_guard<std::mutex> lock(mutex_);
if (latest_reproj_img_.empty() || latest_camera_img_.empty()) {
return;
}
reproj_copy = latest_reproj_img_.clone();
camera_copy = latest_camera_img_.clone();
header_copy = latest_header_;
}
if (reproj_copy.size() != camera_copy.size()) {
ROS_WARN_THROTTLE(2, "Image sizes don't match: reproj(%dx%d) vs camera(%dx%d)",
reproj_copy.cols, reproj_copy.rows, camera_copy.cols, camera_copy.rows);
return;
}
// Create overlay using alpha blending
cv::Mat overlay = camera_copy.clone();
for (int y = 0; y < reproj_copy.rows; ++y) {
for (int x = 0; x < reproj_copy.cols; ++x) {
cv::Vec3b reproj_pixel = reproj_copy.at<cv::Vec3b>(y, x);
if (reproj_pixel[0] < 250 || reproj_pixel[1] < 250 || reproj_pixel[2] < 250) {
cv::Vec3b cam_pixel = camera_copy.at<cv::Vec3b>(y, x);
overlay.at<cv::Vec3b>(y, x) = cv::Vec3b(
static_cast<uchar>(alpha_ * reproj_pixel[0] + (1 - alpha_) * cam_pixel[0]),
static_cast<uchar>(alpha_ * reproj_pixel[1] + (1 - alpha_) * cam_pixel[1]),
static_cast<uchar>(alpha_ * reproj_pixel[2] + (1 - alpha_) * cam_pixel[2])
);
}
}
}
sensor_msgs::ImagePtr overlay_msg = cv_bridge::CvImage(header_copy, "bgr8", overlay).toImageMsg();
overlay_pub_.publish(overlay_msg);
}
// ==================== ROS1 Main ====================
int main(int argc, char **argv)
{
ros::init(argc, argv, "image_overlay_node");
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
ImageOverlayNode node(nh, pnh);
ros::spin();
return 0;
}
#endif
@@ -0,0 +1,78 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <ros/ros.h>
#include <fstream>
#include <sys/stat.h>
#include "depth_image_ros_node.hpp"
#include "odin_calib_path.h"
bool fileExists(const std::string& filename) {
struct stat buffer;
return (stat(filename.c_str(), &buffer) == 0);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "depth_projector");
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
int senddepth=0;
pnh.param("register_keys/senddepth", senddepth, 0);
if(senddepth==0)
{
ROS_INFO("Depth image will not be published.");
return 0;
}
std::string calib_file_path;
pnh.param<std::string>("calib_file_path", calib_file_path, "");
if (calib_file_path.empty()) {
calib_file_path = odin_ros_driver::GetOdinCalibFile();
}
ROS_INFO("========== [CALIB] WAIT <- %s ==========", calib_file_path.c_str());
while(ros::ok() && !fileExists(calib_file_path))
{
ROS_INFO_THROTTLE(5, "Still waiting for calib.yaml file...");
ros::Duration(0.5).sleep();
ros::spinOnce();
}
if(!ros::ok())
{
ROS_INFO("Node shutdown before calib.yaml file was found.");
return 0;
}
ROS_INFO("Found calib.yaml file! Loading parameters...");
std::string node_name = ros::this_node::getName();
std::string rosparam_command = "rosparam load " + calib_file_path + " " + node_name;
int result = system(rosparam_command.c_str());
if(result == 0)
{
ROS_INFO("Successfully loaded parameters from calib.yaml to namespace: %s", node_name.c_str());
}
else
{
ROS_ERROR("Failed to load parameters from calib.yaml");
return 1;
}
DepthImageRosNode projector(nh, pnh);
ros::spin();
return 0;
}
@@ -0,0 +1,242 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <rclcpp/rclcpp.hpp>
#include <fstream>
#include <sys/stat.h>
#include <yaml-cpp/yaml.h>
#include <iostream>
#include <fstream>
#include <string>
#include "depth_image_ros2_node.hpp"
#include "odin_calib_path.h"
#include <rcpputils/filesystem_helper.hpp>
bool fileExists(const std::string& filename) {
struct stat buffer;
return (stat(filename.c_str(), &buffer) == 0);
}
bool loadCalibParameters(std::shared_ptr<rclcpp::Node> node, const std::string& calib_file_path) {
try {
RCLCPP_INFO(node->get_logger(), "========== [CALIB] READ <- %s ==========", calib_file_path.c_str());
YAML::Node config = YAML::LoadFile(calib_file_path);
if (config["cam_num"]) {
int cam_num = config["cam_num"].as<int>();
node->declare_parameter("cam_num", cam_num);
RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_num = %d", cam_num);
}
if (config["img_topic_0"]) {
std::string img_topic = config["img_topic_0"].as<std::string>();
node->declare_parameter("img_topic_0", img_topic);
RCLCPP_INFO(node->get_logger(), "Loaded parameter: img_topic_0 = %s", img_topic.c_str());
}
if (config["Tcl_0"]) {
std::vector<double> tcl_matrix = config["Tcl_0"].as<std::vector<double>>();
node->declare_parameter("Tcl_0", tcl_matrix);
RCLCPP_INFO(node->get_logger(), "Loaded parameter: Tcl_0 (transform matrix with %zu elements)", tcl_matrix.size());
}
if (config["cam_0"]) {
YAML::Node cam_0 = config["cam_0"];
if (cam_0["cam_model"]) {
std::string cam_model = cam_0["cam_model"].as<std::string>();
node->declare_parameter("cam_0.cam_model", cam_model);
RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.cam_model = %s", cam_model.c_str());
}
if (cam_0["image_width"]) {
int image_width = cam_0["image_width"].as<int>();
node->declare_parameter("cam_0.image_width", image_width);
RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.image_width = %d", image_width);
}
if (cam_0["image_height"]) {
int image_height = cam_0["image_height"].as<int>();
node->declare_parameter("cam_0.image_height", image_height);
RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.image_height = %d", image_height);
}
std::vector<std::string> distortion_params = {"k2", "k3", "k4", "k5", "k6", "k7", "p1", "p2"};
for (const auto& param : distortion_params) {
if (cam_0[param]) {
double value = cam_0[param].as<double>();
node->declare_parameter("cam_0." + param, value);
RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.%s = %f", param.c_str(), value);
}
}
std::vector<std::string> intrinsic_params = {"A11", "A12", "A22", "u0", "v0"};
for (const auto& param : intrinsic_params) {
if (cam_0[param]) {
double value = cam_0[param].as<double>();
node->declare_parameter("cam_0." + param, value);
RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.%s = %f", param.c_str(), value);
}
}
if (cam_0["isFast"]) {
int is_fast = cam_0["isFast"].as<int>();
node->declare_parameter("cam_0.isFast", is_fast);
RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.isFast = %d", is_fast);
}
if (cam_0["numDiff"]) {
int num_diff = cam_0["numDiff"].as<int>();
node->declare_parameter("cam_0.numDiff", num_diff);
RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.numDiff = %d", num_diff);
}
if (cam_0["maxIncidentAngle"]) {
int max_incident_angle = cam_0["maxIncidentAngle"].as<int>();
node->declare_parameter("cam_0.maxIncidentAngle", max_incident_angle);
RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.maxIncidentAngle = %d", max_incident_angle);
}
}
RCLCPP_INFO(node->get_logger(), "Successfully loaded all parameters from calib.yaml");
return true;
} catch (const YAML::Exception& e) {
RCLCPP_ERROR(node->get_logger(), "YAML parsing error: %s", e.what());
return false;
} catch (const std::exception& e) {
RCLCPP_ERROR(node->get_logger(), "Error loading calib parameters: %s", e.what());
return false;
}
}
std::string get_package_source_directory() {
// 使用 rcpputils::fs::path 替代 std::filesystem::path
rcpputils::fs::path current_file(__FILE__);
// 回溯到包根目录
auto path = current_file.parent_path();
// 使用 rcpputils::fs::exists 替代 std::filesystem::exists
while (!path.empty() && !rcpputils::fs::exists(path / "package.xml")) {
path = path.parent_path();
}
if (path.empty()) {
throw std::runtime_error("Failed to locate package root directory");
}
return path.string();
}
int main(int argc, char **argv)
{
rclcpp::init(argc, argv);
auto node = std::make_shared<rclcpp::Node>("pcd2depth_node");
RCLCPP_INFO(node->get_logger(), "Node created");
std::string package_path = get_package_source_directory();
RCLCPP_INFO(node->get_logger(), "Package path: %s", package_path.c_str());
std::string config_file = package_path + "/config/control_command.yaml";
RCLCPP_INFO(node->get_logger(), "Loading config from: %s", config_file.c_str());
YAML::Node config = YAML::LoadFile(config_file);
if (!config["register_keys"]) {
throw std::runtime_error("Missing 'register_keys' section");
}
if (!config["register_keys"]["senddepth"]) {
throw std::runtime_error("Missing 'senddepth' parameter");
}
int senddepth = config["register_keys"]["senddepth"].as<int>();
std::cout << "senddepth: " << senddepth << std::endl;
if(senddepth == 0)
{
RCLCPP_INFO(node->get_logger(), "Depth image will not be published.");
return 0;
}
std::string calib_file_path = node->declare_parameter<std::string>("calib_file_path", "");
if (calib_file_path.empty()) {
calib_file_path = odin_ros_driver::GetOdinCalibFile();
}
RCLCPP_INFO(node->get_logger(), "========== [CALIB] WAIT <- %s ==========", calib_file_path.c_str());
while(rclcpp::ok() && !fileExists(calib_file_path))
{
RCLCPP_INFO_THROTTLE(node->get_logger(), *node->get_clock(), 5000, "Still waiting for calib.yaml file...");
rclcpp::sleep_for(std::chrono::milliseconds(500)); // 等待0.5秒后再检查
rclcpp::spin_some(node);
}
if(!rclcpp::ok())
{
RCLCPP_INFO(node->get_logger(), "Node shutdown before calib.yaml file was found.");
return 0;
}
RCLCPP_INFO(node->get_logger(), "Found calib.yaml file! Loading parameters...");
if (!loadCalibParameters(node, calib_file_path)) {
RCLCPP_ERROR(node->get_logger(), "Failed to load parameters from calib.yaml file");
return 1;
}
rclcpp::NodeOptions depth_node_options;
std::vector<rclcpp::Parameter> params_override;
try {
params_override.push_back(rclcpp::Parameter("cam_0.image_width", node->get_parameter("cam_0.image_width").as_int()));
params_override.push_back(rclcpp::Parameter("cam_0.image_height", node->get_parameter("cam_0.image_height").as_int()));
params_override.push_back(rclcpp::Parameter("cam_0.A11", node->get_parameter("cam_0.A11").as_double()));
params_override.push_back(rclcpp::Parameter("cam_0.A12", node->get_parameter("cam_0.A12").as_double()));
params_override.push_back(rclcpp::Parameter("cam_0.A22", node->get_parameter("cam_0.A22").as_double()));
params_override.push_back(rclcpp::Parameter("cam_0.u0", node->get_parameter("cam_0.u0").as_double()));
params_override.push_back(rclcpp::Parameter("cam_0.v0", node->get_parameter("cam_0.v0").as_double()));
params_override.push_back(rclcpp::Parameter("cam_0.k2", node->get_parameter("cam_0.k2").as_double()));
params_override.push_back(rclcpp::Parameter("cam_0.k3", node->get_parameter("cam_0.k3").as_double()));
params_override.push_back(rclcpp::Parameter("cam_0.k4", node->get_parameter("cam_0.k4").as_double()));
params_override.push_back(rclcpp::Parameter("cam_0.k5", node->get_parameter("cam_0.k5").as_double()));
params_override.push_back(rclcpp::Parameter("cam_0.k6", node->get_parameter("cam_0.k6").as_double()));
params_override.push_back(rclcpp::Parameter("cam_0.k7", node->get_parameter("cam_0.k7").as_double()));
params_override.push_back(rclcpp::Parameter("Tcl_0", node->get_parameter("Tcl_0").as_double_array()));
depth_node_options.parameter_overrides(params_override);
RCLCPP_INFO(node->get_logger(), "Parameters successfully prepared for DepthImageRos2Node");
}
catch (const std::exception& e) {
RCLCPP_ERROR(node->get_logger(), "Error preparing parameters for DepthImageRos2Node: %s", e.what());
return 1;
}
try
{
auto depth_node = std::make_shared<DepthImageRos2Node>(depth_node_options);
depth_node->initialize();
rclcpp::executors::MultiThreadedExecutor executor;
executor.add_node(depth_node);
executor.spin();
}
catch (const std::exception& e)
{
RCLCPP_ERROR(node->get_logger(), "Error creating depth node: %s", e.what());
return 1;
}
rclcpp::shutdown();
return 0;
}
@@ -0,0 +1,376 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "pointcloud_depth_converter.hpp"
#include <cmath>
#include <iostream>
PointCloudToDepthConverter::PointCloudToDepthConverter(const CameraParams &params)
: params_(params)
{
initializeInternalParams();
createDistortionMaps();
}
void PointCloudToDepthConverter::initializeInternalParams()
{
scaled_width_ = static_cast<int>(params_.image_width / params_.scale);
scaled_height_ = static_cast<int>(params_.image_height / params_.scale);
K_ = Eigen::Matrix3d::Identity();
K_(0, 0) = params_.A11;
K_(0, 1) = params_.A12;
K_(0, 2) = params_.u0;
K_(1, 1) = params_.A22;
K_(1, 2) = params_.v0;
Kl_ = Eigen::Matrix3d::Identity();
Kl_(0, 0) = params_.A11 / params_.scale;
Kl_(0, 1) = 0.0;
Kl_(0, 2) = params_.u0 / params_.scale;
Kl_(1, 1) = params_.A22 / params_.scale;
Kl_(1, 2) = params_.v0 / params_.scale;
K_4x4_ = Eigen::Matrix4d::Identity();
K_4x4_.block<3, 3>(0, 0) = Kl_;
Kcl_ = K_4x4_ * params_.Tcl;
}
void PointCloudToDepthConverter::createDistortionMaps()
{
map_x_ = cv::Mat::zeros(params_.image_height, params_.image_width, CV_32FC1);
map_y_ = cv::Mat::zeros(params_.image_height, params_.image_width, CV_32FC1);
for (int u = 0; u < params_.image_width; ++u)
{
for (int v = 0; v < params_.image_height; ++v)
{
double y = (v - params_.v0) / params_.A22;
double x = (u - params_.u0 - params_.A12 * y) / params_.A11;
double r = sqrt(x * x + y * y);
double theta = atan(r);
double theta_d = theta + params_.k2 * pow(theta, 2) + params_.k3 * pow(theta, 3) +
params_.k4 * pow(theta, 4) + params_.k5 * pow(theta, 5) +
params_.k6 * pow(theta, 6) + params_.k7 * pow(theta, 7);
double x_distorted = x * (r / theta_d);
double y_distorted = y * (r / theta_d);
map_x_.at<float>(v, u) = static_cast<float>(x_distorted * params_.A11 + params_.A12 * y_distorted + params_.u0);
map_y_.at<float>(v, u) = static_cast<float>(y_distorted * params_.A22 + params_.v0);
}
}
inv_map_x_ = cv::Mat::zeros(params_.image_height, params_.image_width, CV_32FC1);
inv_map_y_ = cv::Mat::zeros(params_.image_height, params_.image_width, CV_32FC1);
for (int u = 0; u < params_.image_width; ++u)
{
for (int v = 0; v < params_.image_height; ++v)
{
double y = (v - params_.v0) / params_.A22;
double x = (u - params_.u0 - params_.A12 * y) / params_.A11;
double r = sqrt(x * x + y * y);
double theta = atan(r);
double theta_d = theta + params_.k2 * pow(theta, 2) + params_.k3 * pow(theta, 3) +
params_.k4 * pow(theta, 4) + params_.k5 * pow(theta, 5) +
params_.k6 * pow(theta, 6) + params_.k7 * pow(theta, 7);
double x_distorted = x * (theta_d / r);
double y_distorted = y * (theta_d / r);
inv_map_x_.at<float>(v, u) = static_cast<float>(x_distorted * params_.A11 + params_.A12 * y_distorted + params_.u0);
inv_map_y_.at<float>(v, u) = static_cast<float>(y_distorted * params_.A22 + params_.v0);
}
}
}
PointCloudToDepthConverter::ProcessResult PointCloudToDepthConverter::processCloudAndImage(
const pcl::PointCloud<pcl::PointXYZ> &cloud,
const cv::Mat &image)
{
ProcessResult result;
result.success = false;
auto validation_result = validateInputs(cloud, image);
if (!validation_result.first)
{
result.error_message = validation_result.second;
return result;
}
try
{
pcl::PointCloud<pcl::PointXYZ> cloud_in_cam;
pcl::transformPointCloud(cloud, cloud_in_cam, Kcl_);
cv::Mat depth_img = projectCloudToDepth(cloud_in_cam);
cv::Mat processed_depth = postProcessDepthImage(depth_img);
pcl::PointCloud<pcl::PointXYZRGB> colored_cloud = generateColoredCloud(processed_depth, image);
result.depth_image = processed_depth;
result.colored_cloud = colored_cloud;
result.success = true;
}
catch (const std::exception &e)
{
result.error_message = std::string("Processing error: ") + e.what();
}
return result;
}
cv::Mat PointCloudToDepthConverter::projectCloudToDepth(const pcl::PointCloud<pcl::PointXYZ> &cloud_in_cam)
{
cv::Mat depth_img = cv::Mat::zeros(scaled_height_, scaled_width_, CV_32FC1);
for (const auto &camera_point : cloud_in_cam)
{
if (camera_point.z <= 0)
continue;
int u = static_cast<int>(std::round(camera_point.x / camera_point.z));
int v = static_cast<int>(std::round(camera_point.y / camera_point.z));
if (u >= 0 && u < scaled_width_ && v >= 0 && v < scaled_height_)
{
depth_img.at<float>(v, u) = static_cast<float>(camera_point.z);
for (int du = -1; du <= 1; ++du)
{
for (int dv = -1; dv <= 1; ++dv)
{
int nu = u + du;
int nv = v + dv;
if (nu >= 0 && nu < scaled_width_ && nv >= 0 && nv < scaled_height_)
{
if (depth_img.at<float>(nv, nu) == 0.0f)
{
depth_img.at<float>(nv, nu) = static_cast<float>(camera_point.z);
}
}
}
}
}
}
return depth_img;
}
cv::Mat PointCloudToDepthConverter::postProcessDepthImage(const cv::Mat &depth_img) {
if (depth_img.empty()) {
std::cerr << "ERROR: Input depth image is empty!" << std::endl;
return cv::Mat();
}
if (depth_img.data == nullptr) {
std::cerr << "ERROR: Input depth image has null data pointer!" << std::endl;
return cv::Mat();
}
if (depth_img.rows <= 0 || depth_img.cols <= 0) {
std::cerr << "ERROR: Invalid input dimensions: "
<< depth_img.rows << "x" << depth_img.cols << std::endl;
return cv::Mat();
}
if (params_.image_width <= 0 || params_.image_height <= 0) {
std::cerr << "ERROR: Invalid target size: "
<< params_.image_width << "x" << params_.image_height << std::endl;
return cv::Mat();
}
cv::Mat safe_input = depth_img.clone();
if (safe_input.empty()) {
std::cerr << "ERROR: Failed to create safe copy of input image!" << std::endl;
return cv::Mat();
}
cv::Mat depth_img_upsampled;
try {
depth_img_upsampled = customResize(safe_input, cv::Size(1600, 1296));
} catch (const std::exception& e) {
std::cerr << "ERROR: Custom resize failed: " << e.what() << std::endl;
return cv::Mat();
}
if (depth_img_upsampled.empty()) {
std::cerr << "ERROR: Resized image is empty!" << std::endl;
return cv::Mat();
}
if (depth_img_upsampled.rows != 1296 || depth_img_upsampled.cols != 1600) {
std::cerr << "ERROR: Resized image has wrong dimensions: "
<< depth_img_upsampled.cols << "x" << depth_img_upsampled.rows
<< " (expected " << 1600 << "x" << 1296 << ")" << std::endl;
return cv::Mat();
}
cv::Mat grad_x, grad_y, grad_magnitude;
try {
cv::Sobel(depth_img_upsampled, grad_x, CV_32F, 1, 0, 3);
cv::Sobel(depth_img_upsampled, grad_y, CV_32F, 0, 1, 3);
cv::magnitude(grad_x, grad_y, grad_magnitude);
} catch (const cv::Exception& e) {
std::cerr << "ERROR: Sobel/magnitude failed: " << e.what() << std::endl;
return cv::Mat();
}
if (grad_magnitude.type() != CV_32F) {
std::cerr << "ERROR: grad_magnitude has wrong type: "
<< grad_magnitude.type() << " (expected CV_32F)" << std::endl;
return cv::Mat();
}
cv::Mat threshold_mask;
try {
cv::threshold(grad_magnitude, threshold_mask, 0.75, 1, cv::THRESH_BINARY);
threshold_mask.convertTo(threshold_mask, CV_8U);
depth_img_upsampled.setTo(0, threshold_mask);
} catch (const cv::Exception& e) {
std::cerr << "ERROR: Threshold mask failed: " << e.what() << std::endl;
return cv::Mat();
}
return depth_img_upsampled;
}
cv::Mat PointCloudToDepthConverter::customResize(const cv::Mat& src, const cv::Size& size) {
if (src.empty()) {
throw std::runtime_error("Source image is empty");
}
if (size.width <= 0 || size.height <= 0) {
throw std::runtime_error("Invalid target size");
}
cv::Mat dst(size.height, size.width, src.type());
float scale_x = src.cols / static_cast<float>(size.width);
float scale_y = src.rows / static_cast<float>(size.height);
if (src.channels() != 1 || src.type() != CV_32F) {
throw std::runtime_error("Unsupported image type - expected single channel float");
}
for (int y = 0; y < dst.rows; y++) {
int src_y = static_cast<int>(y * scale_y);
src_y = std::min(src_y, src.rows - 1);
for (int x = 0; x < dst.cols; x++) {
int src_x = static_cast<int>(x * scale_x);
src_x = std::min(src_x, src.cols - 1);
dst.at<float>(y, x) = src.at<float>(src_y, src_x);
}
}
return dst;
}
pcl::PointCloud<pcl::PointXYZRGB> PointCloudToDepthConverter::generateColoredCloud(
const cv::Mat &depth_img, const cv::Mat &color_img)
{
cv::Mat depth_undistorted, color_undistorted;
depth_undistorted = depth_img.clone();
cv::remap(color_img, color_undistorted, inv_map_x_, inv_map_y_, cv::INTER_LINEAR);
pcl::PointCloud<pcl::PointXYZRGB> cloud_colored;
Eigen::Matrix4d Tlc = params_.Tcl.inverse();
for (int v = 0; v < depth_undistorted.rows; v += params_.point_sampling_rate)
{
for (int u = 0; u < depth_undistorted.cols; u += params_.point_sampling_rate)
{
float depth = depth_undistorted.at<float>(v, u);
if (depth > 0.1f && depth < 100.0f)
{
double y_cam = (v - params_.v0) * depth / params_.A22;
double x_cam = ((u - params_.u0) * depth - params_.A12 * y_cam)/ params_.A11;
double z_cam = depth;
Eigen::Vector4d point_cam(x_cam, y_cam, z_cam, 1.0);
Eigen::Vector4d point_lidar = Tlc * point_cam;
pcl::PointXYZRGB point;
point.x = static_cast<float>(point_lidar[0]);
point.y = static_cast<float>(point_lidar[1]);
point.z = static_cast<float>(point_lidar[2]);
if (u < color_undistorted.cols && v < color_undistorted.rows)
{
cv::Vec3b color = color_undistorted.at<cv::Vec3b>(v, u);
point.b = color[0];
point.g = color[1];
point.r = color[2];
}
else
{
point.r = point.g = point.b = 255;
}
cloud_colored.points.push_back(point);
}
}
}
cloud_colored.width = cloud_colored.points.size();
cloud_colored.height = 1;
cloud_colored.is_dense = false;
return cloud_colored;
}
std::pair<bool, std::string> PointCloudToDepthConverter::validateInputs(
const pcl::PointCloud<pcl::PointXYZ> &cloud, const cv::Mat &image)
{
if (cloud.empty())
{
return {false, "Empty point cloud"};
}
if (image.empty())
{
return {false, "Empty image"};
}
if (params_.A11 < 1e-6 || params_.A22 < 1e-6)
{
return {false, "Invalid camera intrinsics"};
}
return {true, ""};
}
void PointCloudToDepthConverter::updateCameraParams(const CameraParams &params)
{
params_ = params;
initializeInternalParams();
createDistortionMaps();
}
@@ -0,0 +1,299 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "rawCloudRender.h"
#include <yaml-cpp/yaml.h>
#include <iostream>
#include <vector>
#include <Eigen/Dense>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <array>
#include <algorithm>
struct ValidPointInfo {
float x;
float y;
float z;
int u;
int v;
};
namespace GlobalCameraParams {
float g_fx = 0.0f;
float g_fy = 0.0f;
float g_cx = 0.0f;
float g_cy = 0.0f;
float g_skew = 0.0f;
float g_k2 = 0.0f;
float g_k3 = 0.0f;
float g_k4 = 0.0f;
float g_k5 = 0.0f;
float g_k6 = 0.0f;
float g_k7 = 0.0f;
Eigen::Matrix4f g_T_camera_lidar = Eigen::Matrix4f::Identity();
}
bool raw_debug=0;
bool rawCloudRender::init(const std::string& yamlFilePath) {
YAML::Node config;
try {
config = YAML::LoadFile(yamlFilePath);
} catch (const YAML::BadFile& e) {
std::cerr << "Error: Could not open file '" << yamlFilePath << "' - " << e.what() << std::endl;
return false;
} catch (const YAML::ParserException& e) {
std::cerr << "Error: YAML parsing failed - " << e.what() << std::endl;
return false;
} catch (const std::exception& e) {
std::cerr << "Unexpected error: " << e.what() << std::endl;
return false;
}
// Intrinsic parameters node (cam_0)
const std::string cam_node_name = "cam_0";
if (!config[cam_node_name]) {
std::cerr << "Error: Missing camera node '" << cam_node_name << "'" << std::endl;
return false;
}
YAML::Node cam_node = config[cam_node_name];
// Directly access Tcl_0 node
const std::string tcl_node_name = "Tcl_0";
if (!config[tcl_node_name]) {
std::cerr << "Error: Missing transformation matrix node '" << tcl_node_name << "'" << std::endl;
return false;
}
YAML::Node tclNode = config[tcl_node_name];
if (tclNode.size() != 16) {
std::cerr << "Error: Transformation matrix must be 4x4 (16 elements)" << std::endl;
return false;
}
// === Read intrinsic parameters ===
GlobalCameraParams::g_k2 = cam_node["k2"].as<float>();
GlobalCameraParams::g_k3 = cam_node["k3"].as<float>();
GlobalCameraParams::g_k4 = cam_node["k4"].as<float>();
GlobalCameraParams::g_k5 = cam_node["k5"].as<float>();
GlobalCameraParams::g_k6 = cam_node["k6"].as<float>();
GlobalCameraParams::g_k7 = cam_node["k7"].as<float>();
GlobalCameraParams::g_fx = cam_node["A11"].as<float>();
GlobalCameraParams::g_skew = cam_node["A12"].as<float>();
GlobalCameraParams::g_fy = cam_node["A22"].as<float>();
GlobalCameraParams::g_cx = cam_node["u0"].as<float>();
GlobalCameraParams::g_cy = cam_node["v0"].as<float>();
// === Read extrinsic transformation matrix ===
GlobalCameraParams::g_T_camera_lidar <<
tclNode[0].as<float>(), tclNode[1].as<float>(), tclNode[2].as<float>(), tclNode[3].as<float>(),
tclNode[4].as<float>(), tclNode[5].as<float>(), tclNode[6].as<float>(), tclNode[7].as<float>(),
tclNode[8].as<float>(), tclNode[9].as<float>(), tclNode[10].as<float>(), tclNode[11].as<float>(),
tclNode[12].as<float>(), tclNode[13].as<float>(), tclNode[14].as<float>(), tclNode[15].as<float>();
// === Display key parameters concisely ===
std::cout << "=== Camera Calibration Parameters ===" << std::endl;
std::cout << "Intrinsics:" << std::endl;
std::cout << " fx: " << GlobalCameraParams::g_fx
<< ", fy: " << GlobalCameraParams::g_fy
<< ", cx: " << GlobalCameraParams::g_cx
<< ", cy: " << GlobalCameraParams::g_cy << std::endl;
std::cout << "Distortion: k2=" << GlobalCameraParams::g_k2
<< ", k3=" << GlobalCameraParams::g_k3 << std::endl;
Eigen::Vector3f translation = GlobalCameraParams::g_T_camera_lidar.block<3,1>(0,3);
Eigen::Matrix3f rotation = GlobalCameraParams::g_T_camera_lidar.block<3,3>(0,0);
std::cout << "Extrinsics:" << std::endl;
std::cout << " Translation: [" << translation.x() << ", "
<< translation.y() << ", " << translation.z() << "]" << std::endl;
std::cout << " Rotation (euler angles): "
<< rotation.eulerAngles(0,1,2).transpose() * 180/M_PI << "°" << std::endl;
return true;
}
void rawCloudRender::render(std::vector<std::vector<float>>& rgb_image,
capture_Image_List_t* pcd_stream,
int pcdIdx,
std::vector<float>& rgbCloud_flat)
{
// Initialize constants
constexpr float inv_1000 = 0.001f;
const float fx = GlobalCameraParams::g_fx;
const float fy = GlobalCameraParams::g_fy;
const float cx = GlobalCameraParams::g_cx;
const float cy = GlobalCameraParams::g_cy;
const float skew = GlobalCameraParams::g_skew;
const float k2 = GlobalCameraParams::g_k2;
const float k3 = GlobalCameraParams::g_k3;
const float k4 = GlobalCameraParams::g_k4;
const float k5 = GlobalCameraParams::g_k5;
const float k6 = GlobalCameraParams::g_k6;
const float k7 = GlobalCameraParams::g_k7;
const Eigen::Matrix4f& T = GlobalCameraParams::g_T_camera_lidar;
// Precompute matrix elements
const float T00 = T(0,0), T01 = T(0,1), T02 = T(0,2), T03 = T(0,3);
const float T10 = T(1,0), T11 = T(1,1), T12 = T(1,2), T13 = T(1,3);
const float T20 = T(2,0), T21 = T(2,1), T22 = T(2,2), T23 = T(2,3);
// Initialize lookup table
static std::array<float, 10000> dist_table;
static bool table_init = [&](){
for (size_t i=0; i<dist_table.size(); ++i) {
float theta = i * (M_PI/2) / dist_table.size();
dist_table[i] = theta*(1 + theta*(k2 + theta*(k3 + theta*(k4 + theta*(k5 + theta*(k6 + theta*k7))))));
}
return true;
}();
// Get point cloud data (direct access)
if (!pcd_stream || pcdIdx < 0 || pcdIdx >= 10) {
std::cerr << "ERROR: Invalid pcd_stream or index in render function" << std::endl;
return;
}
buffer_List_t& pcd_buffer = pcd_stream->imageList[pcdIdx];
const int total_points = pcd_buffer.height * pcd_buffer.width;
if (!pcd_buffer.pAddr) {
std::cerr << "ERROR: Null point cloud data pointer in render function" << std::endl;
return;
}
float* data = static_cast<float*>(pcd_buffer.pAddr);
// Prepare output
rgbCloud_flat.clear();
rgbCloud_flat.resize(total_points * 4); // Preallocate maximum space
float* output_ptr = rgbCloud_flat.data();
// Get image dimensions
const int img_height = 1296;
const int img_width = 1600;
// Process point cloud
int valid_count = 0;
for (int idx = 0; idx < total_points; ++idx)
{
float* pf = data + idx*4;
// Quick check for invalid points
if (std::abs(pf[0]) < 1e-5f && std::abs(pf[1]) < 1e-5f && std::abs(pf[2]) < 1e-5f) {
continue;
}
// Coordinate transformation
const float x = pf[2] * inv_1000;
const float y = -pf[0] * inv_1000;
const float z = pf[1] * inv_1000;
// Manual matrix transformation
const float x1 = T00*x + T01*y + T02*z + T03;
const float y1 = T10*x + T11*y + T12*z + T13;
const float z1 = T20*x + T21*y + T22*z + T23;
// Check for points behind camera
if (z1 <= 0.0f) continue;
// Calculate projection
const float x1_sq = x1*x1;
const float y1_sq = y1*y1;
const float z1_sq = z1*z1;
const float norm = std::sqrt(x1_sq + y1_sq + z1_sq);
if (norm < 1e-7f) continue;
const float r = std::sqrt(x1_sq + y1_sq);
if (r < 1e-7f) continue;
const float cost = z1 / norm;
const float theta = std::acos(cost);
// Safe table lookup
const size_t table_idx = static_cast<size_t>(theta * (2.0f/M_PI) * dist_table.size());
const size_t safe_idx = std::min(table_idx, dist_table.size()-1);
const float thetad = dist_table[safe_idx];
const float scaling = thetad / r;
const float xd = x1 * scaling;
const float yd = y1 * scaling;
const float pd_2d_x = xd * fx + yd * skew + cx;
const float pd_2d_y = yd * fy + cy;
// Quick boundary check
const int u = static_cast<int>(pd_2d_x);
const int v = static_cast<int>(pd_2d_y);
// Strict boundary check
if (u < 0 || u >= img_width || v < 0 || v >= img_height) {
continue;
}
// Safe image data access
if (v < static_cast<int>(rgb_image.size()) && u < static_cast<int>(rgb_image[v].size())) {
*output_ptr++ = x;
*output_ptr++ = y;
*output_ptr++ = z;
*output_ptr++ = rgb_image[v][u];
valid_count++;
} else {
// Handle invalid coordinates
static bool warned = false;
if (!warned) {
if(raw_debug)
{
std::cerr << "WARNING: Invalid image coordinates: u=" << u << ", v=" << v
<< " (image size: " << rgb_image.size() << "x"
<< (rgb_image.empty() ? 0 : rgb_image[0].size()) << ")" << std::endl;
}
warned = true;
}
}
}
// Resize output
rgbCloud_flat.resize(output_ptr - rgbCloud_flat.data());
if(raw_debug)
{
std::cout << "Render completed: " << total_points << " points processed, "
<< valid_count << " valid points ("
<< (100.0 * valid_count / total_points) << "%)" << std::endl;
}
}
void rawCloudRender::print_camera_calib() {
std::cout << model_type_ << std::endl;
std::cout << image_width_ << std::endl;
std::cout << image_height_ << std::endl;
std::cout << "T_camera_lidar" << std::endl;
std::cout << T_camera_lidar_(0,0) << " " << T_camera_lidar_(0,1) << " " << T_camera_lidar_(0,2) << " " << T_camera_lidar_(0,3) << std::endl;
std::cout << T_camera_lidar_(1,0) << " " << T_camera_lidar_(1,1) << " " << T_camera_lidar_(1,2) << " " << T_camera_lidar_(1,3) << std::endl;
std::cout << T_camera_lidar_(2,0) << " " << T_camera_lidar_(2,1) << " " << T_camera_lidar_(2,2) << " " << T_camera_lidar_(2,3) << std::endl;
std::cout << T_camera_lidar_(3,0) << " " << T_camera_lidar_(3,1) << " " << T_camera_lidar_(3,2) << " " << T_camera_lidar_(3,3) << std::endl;
std::cout << "cam" << std::endl;
std::cout << k2_ << std::endl;
std::cout << k3_ << std::endl;
std::cout << k4_ << std::endl;
std::cout << k5_ << std::endl;
std::cout << k6_ << std::endl;
std::cout << k7_ << std::endl;
std::cout << A11_fx_ << std::endl;
std::cout << A12_skew_ << std::endl;
std::cout << A22_fy_ << std::endl;
std::cout << u0_cx_ << std::endl;
std::cout << v0_cy_ << std::endl;
}
@@ -0,0 +1,249 @@
/*
Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "yaml_parser.h"
#include <fstream>
#include <filesystem>
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
namespace odin_ros_driver {
YamlParser::YamlParser(const std::string& config_file)
: config_file_(config_file) {}
bool YamlParser::loadConfig() {
try {
std::cerr << "Loading config file: " << config_file_ << std::endl;
// Check if file exists
if (!std::filesystem::exists(config_file_)) {
std::cerr << "Config file not found: " << config_file_ << std::endl;
return false;
}
// Print file contents
std::ifstream file(config_file_);
std::string content((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
std::cerr << "Config file content:\n" << content << "\n--- End of file ---" << std::endl;
// Load YAML
YAML::Node config = YAML::LoadFile(config_file_);
// Check if 'register_keys' node exists
if (!config["register_keys"]) {
std::cerr << "Missing 'register_keys' section in config file" << std::endl;
return false;
}
YAML::Node register_keys = config["register_keys"];
register_keys_.clear();
register_keys_str_val_.clear();
custom_parameters_.clear();
// Print number of key-value pairs found
std::cerr << "Found " << register_keys.size() << " keys in config" << std::endl;
for (YAML::const_iterator it = register_keys.begin(); it != register_keys.end(); ++it) {
std::string key = it->first.as<std::string>();
const YAML::Node& value_node = it->second;
// Convert key to lowercase
std::transform(key.begin(), key.end(), key.begin(),
[](unsigned char c){ return std::tolower(c); });
// Check if this is a custom parameter
if (key.substr(0, 7) == "custom_") {
std::string param_name = key.substr(7);
// Handle different value types
if (value_node.IsScalar()) {
// Single scalar value (int or float)
try {
int int_value = value_node.as<int>();
ParameterValue param_value;
param_value.type = DataType::INT_TYPE;
param_value.setData(int_value);
custom_parameters_[param_name] = param_value;
std::cerr << "Loaded custom parameter (int): " << param_name << " = " << int_value << std::endl;
} catch (...) {
try {
double float_value = value_node.as<double>();
ParameterValue param_value;
param_value.type = DataType::FLOAT_ARRAY_TYPE;
std::vector<float> float_array = {static_cast<float>(float_value)};
param_value.setArray(float_array);
custom_parameters_[param_name] = param_value;
std::cerr << "Loaded custom parameter (float): " << param_name << " = " << float_value << std::endl;
} catch (const std::exception& e) {
std::cerr << "Failed to parse custom parameter " << param_name << ": " << e.what() << std::endl;
}
}
} else if (value_node.IsSequence()) {
// Array of values
size_t array_size = value_node.size();
if (array_size == 0) {
std::cerr << "Empty array for custom parameter: " << param_name << std::endl;
continue;
}
// Try to detect if it's a float or int array based on first element
try {
// Try to parse as float array first
std::vector<float> float_array;
for (size_t i = 0; i < array_size; ++i) {
float_array.push_back(value_node[i].as<float>());
}
ParameterValue param_value;
param_value.type = DataType::FLOAT_ARRAY_TYPE;
param_value.setArray(float_array);
custom_parameters_[param_name] = param_value;
std::cerr << "Loaded custom parameter (float array): " << param_name << " = [";
for (size_t i = 0; i < float_array.size(); ++i) {
if (i > 0) std::cerr << ", ";
std::cerr << std::fixed << std::setprecision(4) << float_array[i];
}
std::cerr << "]" << std::endl;
} catch (const std::exception& e) {
std::cerr << "Failed to parse custom parameter array " << param_name << ": " << e.what() << std::endl;
}
}
} else if (allowed_key_w_str_val.find(key) != allowed_key_w_str_val.end()) {
try {
std::string value = value_node.as<std::string>();
register_keys_str_val_[key] = value;
std::cerr << "Loaded key: " << key << " = " << value << std::endl;
} catch (const std::exception& e) {
std::cerr << "Failed to parse key " << key << ": " << e.what() << std::endl;
}
} else if (allowed_key_w_float_val.find(key) != allowed_key_w_float_val.end()) {
try {
double value = value_node.as<double>();
register_keys_float_val_[key] = value;
std::cerr << "Loaded key: " << key << " = " << value << std::endl;
} catch (const std::exception& e) {
std::cerr << "Failed to parse key " << key << ": " << e.what() << std::endl;
}
} else if (allowed_key_w_int_val.find(key) != allowed_key_w_int_val.end()) {
// Regular (non-custom) integer parameter
try {
int value = value_node.as<int>();
register_keys_[key] = value;
std::cerr << "Loaded key: " << key << " = " << value << std::endl;
} catch (const std::exception& e) {
std::cerr << "Failed to parse key " << key << ": " << e.what() << std::endl;
}
} else {
std::cerr << "[ERROR] Unknown/unsupported key in register_keys: '" << key
<< "'. Please check spelling or remove it." << std::endl;
}
}
return true;
} catch (const YAML::Exception& e) {
std::cerr << "YAML exception: " << e.what() << std::endl;
return false;
} catch (const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
return false;
}
}
const std::map<std::string, int>& YamlParser::getRegisterKeys() const {
return register_keys_;
}
const std::map<std::string, ParameterValue>& YamlParser::getCustomParameters() const {
return custom_parameters_;
}
const std::map<std::string, std::string>& YamlParser::getRegisterKeysStrVal() const {
return register_keys_str_val_;
}
void YamlParser::printConfig() const {
std::cerr << "Configuration Keys:" << std::endl;
if (register_keys_.empty()) {
std::cerr << " (int val empty)" << std::endl;
} else {
for (const auto& [key, value] : register_keys_) {
std::cerr << " " << key << ": " << value << std::endl;
}
}
if (register_keys_str_val_.empty()) {
std::cerr << " (str_val empty)" << std::endl;
} else {
for (const auto& [key, value] : register_keys_str_val_) {
std::cerr << " " << key << ": " << value << std::endl;
}
}
std::cerr << "Custom Parameters:" << std::endl;
if (custom_parameters_.empty()) {
std::cerr << " (custom param empty)" << std::endl;
} else {
for (const auto& [key, param_val] : custom_parameters_) {
std::cerr << " " << key << ": (size=" << param_val.getSize() << " bytes)";
if (param_val.type == DataType::INT_TYPE && param_val.getSize() == sizeof(int)) {
int int_val = *reinterpret_cast<const int*>(param_val.getData());
std::cerr << " = " << int_val;
} else if (param_val.type == DataType::FLOAT_ARRAY_TYPE && param_val.getSize() % sizeof(float) == 0) {
size_t count = param_val.getSize() / sizeof(float);
const float* float_arr = reinterpret_cast<const float*>(param_val.getData());
std::cerr << " = [";
for (size_t i = 0; i < count; ++i) {
if (i > 0) std::cerr << ", ";
std::cerr << std::fixed << std::setprecision(4) << float_arr[i];
}
std::cerr << "]";
}
std::cerr << std::endl;
}
}
}
bool YamlParser::applyCustomParameters(device_handle device) {
bool success = true;
for (const auto& [param_name, param_value] : custom_parameters_) {
std::cerr << "Setting custom parameter: " << param_name << " (size=" << param_value.getSize() << " bytes)" << std::endl;
int result = lidar_set_custom_parameter(device, param_name.c_str(), param_value.getData(), param_value.getSize());
if (result != 0) {
std::cerr << "Failed to set custom parameter " << param_name << ": error code " << result << std::endl;
success = false;
} else {
std::cerr << "Successfully set custom parameter " << param_name << std::endl;
}
}
return success;
}
int YamlParser::getCustomParameterInt(const std::string& param_name, int default_value) const {
auto it = custom_parameters_.find(param_name);
if (it != custom_parameters_.end()) {
const ParameterValue& param_value = it->second;
if (param_value.type == DataType::INT_TYPE && param_value.getSize() == sizeof(int)) {
return *reinterpret_cast<const int*>(param_value.getData());
}
}
return default_value;
}
}
+13
View File
@@ -0,0 +1,13 @@
# Query current AE (auto exposure) state.
# Request: empty.
# Response: success + raw return code + decoded fields.
---
bool success # true if rc == 0
int32 rc # 0=ok, >0=device error (400..405 or 0xFF), <0=SDK error
float32 exposure_time # seconds (manual range 0.0001 .. 0.033)
float32 gain # analog gain
int32 iso # equivalent ISO
float32 brightness # average frame brightness
uint8 is_converged # 1=converged, 0=not converged
float32 env_lv # ambient luminance level
float32 fps # current frame rate
+13
View File
@@ -0,0 +1,13 @@
# Query current AWB (auto white balance) state.
# Request: empty.
# Response: success + raw return code + decoded fields.
---
bool success # true if rc == 0
int32 rc # 0=ok, >0=device error (400..405 or 0xFF), <0=SDK error
float32 rgain
float32 grgain
float32 gbgain
float32 bgain
float32 cct # color temperature in Kelvin
float32 ccri # color temperature deviation
uint8 is_converged # 1=converged, 0=not converged
@@ -0,0 +1,9 @@
# Retrieve device logs from the Odin sensor.
#
# Request: destination directory to save the log archive.
# Response: success flag and raw return code.
string dest_dir
---
bool success # true if rc == 0
int32 rc # 0=ok, -1=invalid args, -2=transfer in progress, -3=timeout/stall
@@ -0,0 +1,8 @@
# Send algorithm reset command to the Odin device.
#
# value == 1 : send algo_reset command.
# other : forwarded as "algo_reset" custom parameter.
int32 value
---
bool success # true if rc == 0
int32 rc # 0=ok, see lidar_set_custom_parameter error codes
@@ -0,0 +1,12 @@
# Trigger map save on the Odin device.
#
# value == 1 : start the save-map flow (uses the configured
# mapping_result_dest_dir and mapping_result_file_name;
# runs in a background thread because the transfer may
# take a long time).
# value == 0 : just set the "save_map" custom parameter to 0.
# other : forwarded as "save_map" custom parameter.
int32 value
---
bool success # true if the request was accepted (or rc == 0)
int32 rc # 0=ok, -2=another map transfer already in progress
+14
View File
@@ -0,0 +1,14 @@
# Set AE (auto exposure) mode and (in manual mode) exposure / gain.
#
# mode == 0 (AUTO) : sends opcode 0x02 only; exposure_time and gain ignored.
# mode == 1 (MANUAL) : sends opcode 0x03 then 0x06 (exposure_time, gain).
#
# Valid manual ranges (device-enforced; out-of-range returns rc=403):
# exposure_time : 0.0001 s .. 0.033 s
# gain : 1.0 .. 64.0
uint8 mode
float32 exposure_time
float32 gain
---
bool success
int32 rc # 0=ok, >0=device error (400..405 or 0xFF), <0=SDK error
+15
View File
@@ -0,0 +1,15 @@
# Set AWB (auto white balance) mode and (in manual mode) R/B gains.
#
# mode == 0 (AUTO) : sends opcode 0x31 only; rgain and bgain ignored.
# mode == 1 (MANUAL) : sends opcode 0x32 then 0x33 (rgain, bgain).
# Gr/Gb are fixed to 1.0 by the device.
#
# Valid manual ranges:
# rgain : 0.1 .. 4.0
# bgain : 0.1 .. 4.0
uint8 mode
float32 rgain
float32 bgain
---
bool success
int32 rc # 0=ok, >0=device error (400..405 or 0xFF), <0=SDK error
+260
View File
@@ -0,0 +1,260 @@
# =============================================================================
# sru_nav_node — runtime parameters (SRU-Odin, ROS 2 Humble)
#
# Loaded by launch/sru_nav.launch.py via
# parameters=[os.path.join(share, 'config', 'sru_nav.yaml')]
#
# This is a *node parameter file*, so the top-level key is the node name
# `sru_nav_node`. That name is deliberately identical to the ROS 1 package's
# node name, so that the ROS 1 private-topic names `~base_vel` / `~vis/*` expand
# to exactly the same fully-qualified topics under ROS 2 (`/sru_nav_node/...`)
# and existing rviz configs keep working.
#
# Items marked VERIFY were never validated on real hardware. Every one of them
# is exposed here on purpose: measure it, then change this file only — no code
# edits are required.
# =============================================================================
sru_nav_node:
ros__parameters:
# ------------------------------------------------------------- topics ----
# RESOLVED (was open item 1): this name is CONFIRMED correct. It is the
# default value of the `depth_image_topic` parameter in
# odin_ros_driver/src/depth_image_ros2_node.cpp, and the Rc2026 reference
# project references it in 38 places. It simply is not in the driver's
# mainline docs because it belongs to the pcd2depth depth node.
# Still worth a sanity check on the robot:
# ros2 topic hz /odin1/depth_img_competetion # expect ~10 Hz
# ros2 topic echo /odin1/depth_img_competetion --once --field encoding # 32FC1
depth_topic: "/odin1/depth_img_competetion" # sensor_msgs/msg/Image, 32FC1, meters
odom_topic: "/odin1/odometry_highfreq" # nav_msgs/msg/Odometry @ ~300-400 Hz
# alt: /odin1/odometry (~10 Hz SLAM rate,
# less drift but laggier)
joy_topic: "/joy" # sensor_msgs/msg/Joy
goal_topic: "/goal_pose" # geometry_msgs/msg/PoseStamped
# frame_id MUST equal odom's
# header.frame_id, or the goal is rejected
cmd_vel_topic: "/cmd_vel" # geometry_msgs/msg/Twist, body frame
# ============= DRIVER PREREQUISITES (verified on this machine) ==========
# This node publishes /cmd_vel ONLY from generate_cmd_vel(), which is called
# ONLY from depth_callback() -- exactly like the ROS 1 blueprint (one call
# site in each). So with no depth arriving you get NO /cmd_vel at all, and
# not even the once-per-second `cmd_vel_ratio:` / `Published cmd_vel:` log
# lines. That is the signature to look for when diagnosing.
#
# 1) Endpoints are not data. `/odin1/depth_img_competetion` appears in
# `ros2 topic list` (and shows Subscription count 1) as soon as THIS node
# subscribes to it, and the driver creates its publishers at startup even
# when it streams nothing. `ros2 topic info` counts endpoints, so it can
# read "Publisher count: 1" with zero data flowing. Use:
# ros2 topic hz /odin1/depth_img_competetion # the only real check
# BUT beware for the RGB topic: `/odin1/image` is 1600x1296 bgr8 (~6.2 MB
# per frame, NOT scaled -- calib.yaml: image_width/height = 1600x1296).
# A Python `ros2 topic hz` subscriber cannot keep up with that, and since
# the publisher is RELIABLE with a small queue it gets dragged down too --
# so `hz` can read ~0.3 Hz on a stream that is actually fine (the driver's
# own dev_status.csv showed 10.2 Hz for it). Cross-check with that CSV
# before believing a low number on /odin1/image.
#
# NOTE the depth image is NOT full resolution: the depth node divides the
# camera size by the `scale` parameter (default 7.0, and control_command.yaml
# sets no override):
# pointcloud_depth_converter.cpp:27-28 scaled_w/h = image_w/h / scale
# => 1600/7 x 1296/7 = 228x185 32FC1, i.e. only ~165 KiB per frame.
# So the depth stream is small: a low `/cmd_vel` rate is then NOT this
# node being swamped, and `ros2 topic hz` on the depth topic is trustworthy.
#
# 2) The driver reads its config from the SOURCE TREE, not from install/.
# All three driver binaries resolve it with get_package_source_directory(),
# which walks up from the compile-time `__FILE__` until it finds
# package.xml (host_sdk_sample.cpp:869 & :2491, pcd2depth_ros2.cpp:122,
# cloud_reprojection_ros.cpp:48). For this machine the compiled-in path is
# /home/kevin/catkin_ws/src/odin_ros_driver/src/*.cpp
# (confirmed in build/odin_ros_driver/CMakeFiles/*/src/*.cpp.o.d), so the
# file that is actually read is
# ~/catkin_ws/src/odin_ros_driver/config/control_command.yaml
# Editing the copy under install/odin_ros_driver/share/... has NO effect.
#
# 3) THREE keys must be flipped there -- all ship as 0 on this machine:
# senddtof: 1 # "send raw cloud data" (host_sdk_sample.h:2152) --
# # this is /odin1/cloud_raw. It is gated TWICE:
# # the device stream is deactivated
# # (host_sdk_sample.cpp:1950 lidar_deactivate_stream_type
# # LIDAR_DT_RAW_DTOF) and the publish itself is skipped
# # (host_sdk_sample.cpp:1057 if (g_senddtof)).
# # Without it the depth node's ApproximateTime sync --
# # which needs the PAIR {/odin1/cloud_raw, /odin1/image}
# # (depth_image_ros2_node.cpp:40-44) -- can never fire.
# senddepth: 1 # else pcd2depth logs "Depth image will not be
# # published." and returns 0 (pcd2depth_ros2.cpp:164)
# sendrgb: 1 # else /odin1/image (raw bgr8) is never produced
# These are `register_keys`, pushed to the device at startup, so RESTART
# the whole driver after editing. `sendodom: 1` + `send_odom_baselink_tf: 1`
# are already on and are what feed this node's odom.
#
# The driver's own device-status log is the authoritative rate check -- far
# better than `ros2 topic hz` for the multi-MB topics (see the doc):
# tail -1 ~/catkin_ws/src/odin_ros_driver/log/Driver_*/Conn_*/dev_status.csv
# A healthy run shows rgb_rx_odr ~10, dtof_rx_odr ~10, slam_cloud_rx_odr ~10,
# slam_odom_highfreq_rx_odr ~400. A 0.00 in *_rx_odr means that stream is off.
#
# Start / restart the driver (this launch brings up the depth node too):
# source /opt/ros/humble/setup.bash
# source ~/catkin_ws/install/setup.bash
# ros2 launch odin_ros_driver odin1_ros2.launch.py
# Never run two host_sdk_sample processes at once: the Odin1 USB link is
# exclusive, so Ctrl-C the old one first.
#
# MIND use_host_ros_time: it is 0 on this machine, i.e. the odom stamp comes
# from the ODIN DEVICE clock, not the host wall clock. The control-frequency
# gate below is unaffected (odom time vs odom time), but the joystick deadman
# compares odom time against `time.time()` -- with require_joystick: true that
# domain mismatch can make the timeout fire instantly or never. See
# docs/DEPLOY_ROS2.md §11 item 8.
# =======================================================================
# ------------------------------------------------------------- models ----
# Leave empty to auto-discover <share>/sru_nav_ros2/models/*.onnx
vae_model_path: ""
policy_model_path: ""
# ------------------------------------------------------- depth filter ----
# Training-aligned. Do not change unless you know what you are doing.
min_depth: 0.25 # meters
max_depth: 10.0 # meters
# ------------------------------------------------------------ control ----
control_frequency: 5.0 # Hz — matches training
# [vx_max, vy_max, omega_max].
# Training used [1.5, 1.0, 1.0]; these are the deliberately conservative
# deployment values. NOTE: ROS 2 params are strictly typed — these MUST be
# written as floats. `policy_scale: [1, 1, 1]` (ints) is rejected.
policy_scale: [0.6, 0.3, 0.6]
# ---------------------------------------------------------- semantics ----
# Renamed from the ROS 1 `use_sim`. It has NOTHING to do with the ROS 2
# built-in `use_sim_time`; the old name was a misnomer.
# true -> odom twist is already in a body frame -> pass it through
# false -> odom twist is in the world frame -> rotate it into the body frame
#
# RESOLVED (was open item 3) from the Rc2026 reference project,
# src/driver/vehicle_driver/script/calib/calib_chassis_speed.py:
# "twist.twist.linear.x/y -> linear velocity (odin1_base_link frame)"
# "odin1 velocity is in odin1_base_link frame. If the Odin mounting
# orientation matches the chassis forward direction, linear.x is the
# forward/backward speed directly."
# So the Odin1 driver reports the twist in odin1_base_link, i.e. a BODY frame:
# this must be `true`, and the world->body rotation must NOT be applied.
#
# Residual caveat: with a non-zero Odin1 pitch/roll that frame is tilted w.r.t.
# the platform, so linear.x is scaled by ~cos(pitch) and a small spurious
# linear.z shows up. The reference project accepts this (same comment above);
# removing it exactly would require the mounting extrinsic, i.e. a TF lookup.
#
# This is the value the node runs with. The launch file also exposes it as
# `odom_twist_in_base_frame:=<bool>` for a per-run flip, and its launch
# default is read FROM THIS FILE (launch/sru_nav.launch.py::_yaml_default),
# so the two can never disagree. Editing the line below is enough.
odom_twist_in_base_frame: true
# ---------------------------------------------------------------- QoS ----
# CONFIRMED from the driver source on this machine -- both publishers are
# RELIABLE:
# host_sdk_sample.h:1928 qos_sensor = QoS(5).reliability(RELIABLE)
# host_sdk_sample.h:1937 odom_highfreq_publisher_ -> qos_small
# = QoS(4000).reliability(RELIABLE)
# depth_image_ros2_node.cpp:49 image_transport advertise() -> falls back to
# rmw_qos_profile_default (= RELIABLE, depth 10)
#
# We still default to BEST_EFFORT on purpose: a BEST_EFFORT subscriber is
# compatible with BOTH RELIABLE and BEST_EFFORT publishers, whereas a RELIABLE
# subscriber silently receives NOTHING from a BEST_EFFORT publisher. Flip to
# true if you want an exact match with this driver (no drops under load).
depth_qos_reliable: false # false = BEST_EFFORT (compatible with both)
odom_qos_reliable: true # true = RELIABLE (matches the driver)
# ------------------------------------------------------------- deadman ---
# true (SAFE, default): /cmd_vel stays 0 until a /joy publisher exists AND
# the throttle/smart axis is pushed; 15 s without /joy
# forces a stop. Keep this on real hardware.
# false (TESTING ONLY) : bypass the deadman; useful for headless closed-loop
# tests with no operator. Overridable from the launch
# file via `require_joystick:=false`.
require_joystick: true
# ---------------------------------------------------- joystick mapping ---
# VERIFY (item 6): Humble's `joy` package may map axes/buttons differently
# from ROS 1. Drive each stick/button and read `ros2 topic echo /joy`, then
# correct the indices below. Defaults mirror the PS5 layout in constants.py.
joy_axis_linear_x: 1
joy_axis_linear_y: 0
joy_axis_linear_z: 3
joy_axis_angular_z: 2
joy_axis_smart: 5
joy_button_reset_hidden_state: 2
joy_button_record_waypoint: 6
joy_button_clear_waypoint: 4
joy_button_send_goal: 10
joy_button_abort: 9
joy_button_trigger_waypoints: 1
joy_button_forward: 11
joy_button_backward: 12
joy_button_left: 13
joy_button_right: 14
joy_button_up: 3
joy_button_down: 0
# =====================================================================
# GOAL HEADING (final yaw) -- ROS 2 ADDITION, not in the ROS 1 blueprint
# =====================================================================
# The policy has NO heading input: its 16-dim state is
# [linear_vel(3), angular_vel(3), gravity(3), last_action(3), target(4)]
# and the target is only a body-frame direction + log distance. Arrival is
# also position-only (`||target_xy - robot_xy|| <= ARRIVE_GOAL_THRESHOLD`).
# So a goal heading cannot be expressed through the policy at all.
#
# Instead, once the position goal has been reached, this node runs its own
# in-place rotation stage until the heading is aligned, then releases the
# goal as usual. It is a SEPARATE 20 Hz timer, deliberately NOT part of
# `generate_cmd_vel`: that function is driven by the depth callback and only
# runs at ~1.5 Hz in practice (0.66 s per step = ~19 deg per step at
# 0.6 rad/s), which cannot align anything precisely.
#
# How to use:
# * publish the heading on `goal_yaw_topic` (std_msgs/msg/Float64, radians,
# in the SAME frame as /goal_pose, i.e. odom; 0 = odom +X, CCW positive)
# * NaN means "no heading requirement for this goal"
# * waypoint_runner sets both for you:
# ros2 run sru_nav_ros2 waypoint_runner --waypoints "1,0 2,0 3,0,0,1.5708"
# (4th number = yaw; intermediate waypoints simply omit it, so only the
# waypoints that carry a yaw are aligned)
# * a goal published AT the robot's current position with a yaw is just a
# "turn in place to this heading" command
#
# Behaviour is unchanged when no heading is ever published.
goal_yaw_topic: "/goal_yaw" # std_msgs/msg/Float64, radians, odom frame
# Precision / motion of the in-place rotation.
# tolerance : stop when |error| <= this. 0.0873 rad = 5 deg.
# Achievable floor is set by (a) the Odin1 yaw estimate,
# (b) the chassis' yaw dead-zone / minimum turn rate and
# (c) the 20 Hz discretisation -- so verify on the robot.
# max_rate : hard cap on |angular.z| during alignment. Kept equal to the
# policy's own yaw cap (policy_scale[2] = 0.6) so the stage is
# never more aggressive than normal driving.
# decel : braking profile. |w| = min(max_rate, sqrt(2*decel*|error|))
# -> full rate far away, tapers to zero at the target, which is
# what removes the overshoot.
# frequency : 20 Hz is ample and stays far below the odom rate.
# settle_time: the error must stay inside the tolerance this long before the
# goal is declared done (rejects transients / overshoot).
# timeout : give up and log the residual error rather than spin forever.
goal_yaw_tolerance: 0.0873 # rad (+/- 5 deg)
goal_yaw_max_rate: 0.6 # rad/s
goal_yaw_decel: 0.8 # rad/s^2
goal_yaw_update_frequency: 20.0 # Hz (own timer, NOT control_frequency)
goal_yaw_settle_time: 0.4 # s
goal_yaw_timeout: 15.0 # s
@@ -0,0 +1,26 @@
# Example waypoint list for scripts/waypoint_runner.py
#
# All waypoints are in the odometry frame (matches what /goal_pose expects).
# z is optional; if 0 the main node substitutes the robot's current z.
frame_id: odom
# Arrival / timing
arrive_threshold: 0.75 # meters (matches constants.ARRIVE_GOAL_THRESHOLD)
settle_time: 1.5 # seconds the robot must stay within threshold
per_goal_timeout: 60.0 # seconds before giving up on a single goal
# Stuck detection (script-side; no main-node changes required)
stuck_window: 10.0 # seconds of trailing window
stuck_displacement: 0.10 # meters; below this -> skip current goal
# Republish the same goal periodically to defend against missed messages.
republish_interval: 5.0
# Append the script-start odom pose as a final goal after the list.
return_home: true
waypoints:
- [3.0, 0.0, 0.0]
- [3.0, 2.0, 0.0]
- [0.0, 2.0, 0.0]
@@ -0,0 +1,152 @@
# AI Agent 提示词(整段复制粘贴给新机器上的 AI Agent)
> **用法**:在新机器上打开 AI Agent,把下面「─── 提示词开始 ───」到「─── 提示词结束 ───」
> 之间的**全文**粘进对话框发送。
>
> 配套资料(都在包里,Agent 需要自己读):
> - `docs/HANDOVER_TEAM.md` ← 交接流程与清单(先读这个)
> - `docs/DEPLOY_ROS2.md` ← **权威细节**(环境原理、话题契约、排错表、存疑项状态)
>
> 如果你已经手动把环境装好了,就把「第二步」跳过,直接告诉 Agent「环境已装好,从验收开始」。
---
─── 提示词开始 ───
你是一名熟悉 ROS 2 Humble、rclpy、ONNX Runtime 与机器人真机部署的高级工程师。请帮我把一个**已经移植完成**的 ROS 2 包在这台机器上跑起来,并为上机实测做好准备。
## 一、任务背景(`~/sru_ws/src/sru_nav_ros2/`,已存在,不要重写)
这是把 SRU-Odin 的 ROS 1 部署代码反向移植成 **ROS 2 Humble `ament_python` 包**的结果,
用于 **Odin1 传感器上的无图端到端导航**:
```
/odin1/depth_img_competetion ─┐
├─► sru_nav_node ─► /cmd_vel (geometry_msgs/Twist)
/odin1/odometry_highfreq ─────┘ ▲
└── /goal_pose(位置) + /goal_yaw(朝向)
```
**先读这两份文档再动手**:`docs/HANDOVER_TEAM.md`(交接流程、打包与安全须知)、
`docs/DEPLOY_ROS2.md`(权威细节;环境原理在 §2,话题契约在 §4,参数在 §5,排错在 §8)。
**这个包已经在开发机上验证过的部分(不要从头重验)**:
`colcon build --symlink-install` 通过;节点启动打印 `Navigation policy node is ready.`;
两个 ONNX 正确加载;深度话题到达且 `encoding == 32FC1`;**带目标时 `/cmd_vel` 输出非零且有界**
(`|linear_x|≤0.6`、`|linear_y|≤0.18`、`|angular_z|≤0.6`);`/goal_pose`、`/goal_yaw` 收发正常;
`waypoint_runner` 全流程正常;静态 TF 正常;整包检索 ROS 1 客户端库名零命中。
## 二、环境配置(严格按顺序;**所有路径按本机家目录替换,不要把 `/home/kevin` 抄进去**)
1. **确认前提**:`lsb_release -a` 应为 Ubuntu 22.04;`uname -m` 记下架构
(若**不是 x86_64**,先告诉我,`onnxruntime`/`scipy` 的 wheel 可用性要单独确认)。
2. **apt 包**:
```bash
sudo apt update
sudo apt install -y ros-humble-desktop ros-humble-cv-bridge ros-humble-joy \
ros-humble-tf2-ros ros-humble-rviz2 python3-colcon-common-extensions python3.10-venv
```
3. **重建 venv(⚠️ 千万不要从开发机拷 `venv/` 过来,里面全是绝对路径)**:
```bash
/usr/bin/python3 -m venv --system-site-packages ~/sru_ws/venv
~/sru_ws/venv/bin/pip install --upgrade pip
~/sru_ws/venv/bin/pip install "numpy<2" onnxruntime
~/sru_ws/venv/bin/pip install "scipy==1.11.4" # 必须精确版本号,原因见 DEPLOY_ROS2 §2.2
```
**不要 `pip install opencv-python`** —— 本包用系统 `python3-opencv`(与 `cv_bridge` 同源)。
4. **往 venv 的 activate 末尾追加两行**(把路径换成本机真实路径):
```bash
echo "export PYTHONNOUSERSITE=1" >> ~/sru_ws/venv/bin/activate
echo "export PYTHONPATH=\"$HOME/sru_ws/venv/lib/python3.10/site-packages\${PYTHONPATH:+:\$PYTHONPATH}\"" >> ~/sru_ws/venv/bin/activate
```
这两行是**必需**的,不要删、不要改成赋值覆盖:
- `PYTHONNOUSERSITE=1`:`--system-site-packages` 的 venv **不会**禁用用户级 site,
`~/.local` 里的 pip 版 numpy2/opencv 会顶掉系统版 ⇒ `cv_bridge` 崩、`import cv2` 段错误。
- `PYTHONPATH` **追加**:`colcon`/`ros2` 的 shebang 硬编码 `#!/usr/bin/python3`,
所以节点永远跑在系统 python 下(**激活 venv 改变不了**),不加这行就
`ModuleNotFoundError: No module named 'onnxruntime'`。**只能追加**,覆盖式会冲掉 ROS 路径 ⇒ 无 `cv_bridge`。
5. **两个 `COLCON_IGNORE`(缺了 `colcon build` 必炸)**:
```bash
touch ~/sru_ws/reference/COLCON_IGNORE ~/sru_ws/venv/COLCON_IGNORE
```
原因:colcon 从工作区根**递归爬全部子目录**(不是只爬 `src/`),否则会去构建蓝本的 catkin 包
(Humble 没 catkin ⇒ 致命)、`isaaclab_nav_task`、以及 venv 里 setuptools 自带的 `my-test-package`。
## 三、验收标准(这些全部通过才算装好)
```bash
source /opt/ros/humble/setup.bash && source ~/sru_ws/venv/bin/activate
cd ~/sru_ws && colcon build --symlink-install && source install/setup.bash
ros2 pkg prefix sru_nav_ros2
```
| # | 标准 | 期望 |
|---|---|---|
| 1 | `colcon build --symlink-install` | 退出码 0 |
| 2 | `colcon list` | **只有一行** `sru_nav_ros2 src/sru_nav_ros2 (ros.ament_python)`,stderr 为空 |
| 3 | 依赖自检 | `numpy` 在 **venv** 下且为 `1.26.x`;`cv2` 为 **4.5.4** 且路径在 `/usr/lib/python3/dist-packages`;`scipy` 为 **1.11.4** 且在 venv 下;`onnxruntime.get_available_providers()` 含 `CPUExecutionProvider`;`CvBridge()` 能构造 |
| 4 | `ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false` | 打印 `Navigation policy node is ready.`,且 `odom_twist_in_base_frame=True` |
没有 Odin 数据源时,节点会每 5 s 刷 `Odometry not ready, skipping depth callback.` —— **这是预期行为,不是故障**。
## 四、⛔ 绝对不能改的东西
- **数值硬约束**(与训练对齐,改了行为就废):`control_frequency=5.0`、`rnn_hidden_size=512`、
`rnn_num_layers=1`、深度 `0.25~10.0 m`、`resize(40,64)`、latent 2560、obs 2576、
`ARRIVE_GOAL_THRESHOLD=0.75`、`JOYSTICK_TIMEOUT=15.0`、`LOW_PASS_FILTER_COEF=[0.9,0.5,0.5]`、
`LATERAL_VELOCITY_SCALE=0.6`。
- **安全默认值,禁止"优化"**:`policy_scale=[0.6,0.3,0.6]`(训练值本是 `[1.5,1.0,1.0]`,部署刻意保守化)、
`require_joystick=true`。
- `sru_nav_ros2/constants.py`、`model.py`、`utils.py` 是**逐字节原样的蓝本拷贝** —— **不要改**。
新增常量也不要往 `constants.py` 里塞,放到用它的模块里。
- **不要改** `~/sru_ws/reference/` 下的任何东西(只读蓝本,留着 diff 用)。
- **不要"顺手优化"**:策略输出链路、低通滤波、频率门控、QoS 都不要动。
发现疑点先报告,由我决定。
## 五、已知问题(**不要当成 bug 去修**)
| # | 现象 / 问题 | 说明 |
|---|---|---|
| 1 | 深度与 `/cmd_vel` 实测只有 **~1.5 Hz**(设备端是 10 Hz) | **已定性:瓶颈在 Odin 驱动的发布/DDS 交付,不在本包**(本节点平均 CPU 只占 11%,89% 时间在空等)。`control_frequency` 是**上限**不是目标值。候选修法在驱动侧(把硬编码的 `QoS(5)` 改成 `QoS(50)`,或发布/订阅**成对**改 BEST_EFFORT)—— ⛔ **绝不能只改发布端**。**这属于驱动侧改动,先报告再动** |
| 2 | Odin1 装订外参默认值是 **Rc2026 比赛车**的实测值,不是我们的载体 | 必须重测,见 `HANDOVER_TEAM.md` §6.2 第 1 项 |
| 3 | 目标朝向(`/goal_yaw`,到点后原地自转对准)**从未在真机上验证** | ±5° 是**设计目标**不是实测结论。逻辑在 `update_goal_yaw()`(20 Hz 独立定时器) |
| 4 | `/joy` 的手柄轴/键索引沿用 PS5 映射,**没在真手柄上验过** | 需要逐个推 |
| 5 | 驱动的 `use_host_ros_time` 可能是 `0`(设备时钟),与主机墙钟不同基准 | 而 deadman 判断式把两者相减 ⇒ 可能"一上来就超时"或"deadman 失效"。开手柄前必须处理 |
| 6 | **路点间距 ≤ 0.75 m 时机器人一步都不走** | 因为 `ARRIVE_GOAL_THRESHOLD=0.75 m` 且发布即判到达。**用 3–5 m 间距** |
| 7 | odom twist 直接透传,但 Odin1 若带俯仰角安装会有残余量 | `linear.x` 会被乘 `cos(pitch)`,并有轻微虚假 `linear.z`;参考工程也这么接受 |
## 六、执行纪律(请严格遵守)
1. **不要写自检脚本 / 验收脚本**,不要做离线模拟验证,不要复算算法或数括号配平。
只做必要的静态核对(语法、参数名前后一致、残留旧引用),结论用文字告诉我。
2. **不要"先做一堆环境探测"**:装完就按第三步验收,把**实际输出**贴给我。不要凭"沙箱里 import 不到"
就改写实现或换方案。
3. **正规方式不可用时停下来问我**:如果某个依赖装不上、或必须确认权限/系统资源才能继续,
告诉我「正规方式 X 不可用,我不会自行改用替代方案」并说明需要我决定什么,
**不要自己发明替代实现、mock 核心依赖、静默降级或改用非官方 hack**。
4. **改代码前先问**。除了环境配置和跑验收,任何对 `src/sru_nav_ros2/` 的修改都先说明理由和改动面,
我确认后再动手。修复要**先给根因、再做最小修复**,仍然用正规方法。
5. **不要自作聪明加功能**。之前没提过的功能/优化,只提建议,我采纳了再加。
6. **安全第一**:任何会让机器人动的操作(发目标、跑 runner、改 `policy_scale`),
**必须我明确说"已抬轮/可以动"之后再做**。默认只做静态与只读的验证。
7. **交付时讲清楚**:改了哪些文件/函数/配置、实现流程是怎样的、关键调用链与数据流在哪、
怎么运行或触发、以及你没能确认的事项。不要只丢结果。
## 七、做完之后请汇报
1. 第三步验收的**原始输出**(尤其 `colcon list`、依赖自检、launch 日志那行)。
2. 你改过的任何文件的清单与原因。
3. 你**没能**确认、或与文档描述不一致的地方。
4. 你对「下一步该测什么」的建议(对照 `HANDOVER_TEAM.md` §6.2 的待测清单)。
─── 提示词结束 ───
---
## 附:如果环境已经手动装好
把上面提示词里的「二、环境配置」整段跳过,改成告诉 Agent:
> 环境我已经按 `docs/HANDOVER_TEAM.md` 装好了,venv 也重建并追加了两行 export。
> 你从「三、验收标准」开始,逐条跑并把原始输出给我。
> 之后不要动代码,等我说可以上机动了再往下。
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,569 @@
# 交接文档:SRU-Odin 无图端到端导航(ROS 2 Humble)→ 迁移到新机器上机实测
> **给谁看**:接手移植、并要在我们自己的机器人上做实车测试的人(以及他那边的 AI Agent)。
> **配套文档**:
> - `DEPLOY_ROS2.md` ← **本包的权威细节**(环境原理、话题契约、排错、存疑项状态,约 1000 行)。本文件是**入门流程 + 交接清单**,细节都在它里面。
> - `AI_AGENT_PROMPT.md` ← 整段复制给你那边的 AI Agent 用的提示词。
>
> 读完本文件应该能独立把这套装起来、跑起来、并对"什么已验证 / 什么没验证"心里有数。
---
## 0. 这个包是什么
把 SRU-Odin(ManifoldTech 的 Odin1 空间记忆传感器 + ETH RSL 的 SRU 策略)的 **ROS 1 部署代码**反向移植成
**ROS 2 Humble** 的 `ament_python` 包,用于**无图、无 GPS 的端到端导航**。
```
/odin1/depth_img_competetion ─┐
├─► sru_nav_node ─► /cmd_vel (geometry_msgs/Twist)
/odin1/odometry_highfreq ─────┘ ▲
│
/goal_pose (位置) + /goal_yaw (朝向)
```
**几个必须先建立的认知**:
| 事实 | 说明 |
|---|---|
| 它是**端到端反应式策略**,不是导航栈 | 没有地图、没有 SLAM、没有规划器。唯一决策入口是一次 ONNX 前向:`深度图 + 16 维状态 → [vx, vy, ω]`。所以**不存在"规划出的路径"** |
| 三个速度是**同时**输出的 | 动作空间是 SE2 三自由度 `[vx, vy, ω]`,一次算出来一起发。**不是"先转好再走"**;因为横移被限得比前进小 3 倍多,实际会边走边转(弧线接近) |
| **机型无关** | 本包只发布 `Twist` 到 `/cmd_vel`,不绑定任何底盘,桥上你自己接 |
| 没有深度就**一条 `/cmd_vel` 都不发** | 推理只由 `depth_callback` 触发。看到 `/cmd_vel` 全无输出,先查驱动有没有把深度开起来 |
| **到达判定只看 XY 距离** | 0.75 m 内就算到,**不要求朝向**。朝向是另外用 `/goal_yaw` 指定的(见 §4.5) |
| 节点名固定 `sru_nav_node` | 私有话题 `~/vis/*` 等的展开结果与 ROS 1 一致 |
---
## 1. 交付物与打包(**先看这节,最容易在这里出错**)
### 1.1 带什么 / 不带什么
| 路径 | 体积 | 带不带 | 说明 |
|---|---|---|---|
| `src/sru_nav_ros2/` | 28 MB | ✅ **必需** | 交付包本体(含两个 ONNX,27 MB) |
| `reference/COLCON_IGNORE` | 528 B | ✅ **必需** | 见 §2.5,缺了 `colcon build` 会炸 |
| `reference/SRU-Odin/Deployment/` | 32 MB | ✅ 建议 | ROS 1 只读蓝本,方便日后 diff 对照 |
| `docs/HANDOVER.md`、`docs/ROS2_PORT_PLAN.md` | 小 | ✅ 建议 | 当初的移植方案(**注意:其中两处结论已被实测推翻,以 `DEPLOY_ROS2.md` 为准**);2026-09-30 起由 `reference/` 移入 `docs/` |
| `reference/SRU-Odin/Train/` | 342 MB | ⬜ 可选 → **建议带精简版(打包后约 130 KB)** | 训练侧代码与配置,是部署代码的"规格书"(见 §1.4)。**整目录 342 MB 里只有约 800 KB(87 个文件)是代码/配置**,其余全是权重与地形资源 |
| `reference/SRU-Odin/` 其它(`Img/`、`Prompt/`、README) | 小 | ⬜ 可选 | |
| **`venv/`** | 266 MB | ❌ **千万不要拷** | **见 §1.2,必须在新机器上重建** |
| `build/`、`install/`、`log/` | <1 MB | ❌ 不要 | 构建产物,`colcon` 会重新生成 |
**一句话**:`src/` 必需;`docs/` 整个带走;`reference/` 里只留 `Deployment/` + 那个 `COLCON_IGNORE` 就够(约 60 MB)。
### 1.2 ⚠️ 为什么 `venv/` 不能拷过去 —— 这是最容易翻车的一处
本机(也就是开发机)的路径是 `/home/kevin/sru_ws/`,而你那边大概率不是。venv **到处都是绝对路径**:
| 位置 | 内容 |
|---|---|
| `venv/bin/activate` | 我们追加的 `export PYTHONPATH="/home/kevin/sru_ws/venv/lib/python3.10/site-packages..."` |
| `venv/pyvenv.cfg` | `home = /usr/bin`、`command = ... /home/kevin/sru_ws/venv` |
| `venv/bin/*` 下所有入口脚本 | shebang 指向 `/home/kevin/sru_ws/venv/bin/python` |
拷过去只会得到一堆指向不存在路径的脚本。**正确做法是在新机器上重建**(§2.3),重建后激活就能用。
### 1.3 打包(**已实测可用**,产物 ≈ 51 MB)
```bash
cd ~
TAR_OPTS=(
--exclude='sru_ws/build' --exclude='sru_ws/install' --exclude='sru_ws/log'
--exclude='sru_ws/venv'
--exclude='*/__pycache__'
--exclude='*/assets' --exclude='*.usd' --exclude='*.jpg'
--exclude='*.pth' --exclude='*.pt'
)
tar czf sru_nav_handover.tgz "${TAR_OPTS[@]}" \
sru_ws/src/sru_nav_ros2 \
sru_ws/docs \
sru_ws/reference/COLCON_IGNORE \
sru_ws/reference/SRU-Odin/Deployment \
sru_ws/reference/SRU-Odin/README.md \
sru_ws/reference/SRU-Odin/LICENSE \
sru_ws/reference/SRU-Odin/Train
```
实测结果(本机):**53,696,793 字节 ≈ 51 MB**,181 个条目。
`--exclude='*/assets'` 等几条同时把**精简版 Train** 里的权重/地形/图片排除掉了(见 §1.4),
所以 `Train/` 也一并带上了。
**归档内部结构就是 `sru_ws/…`**,所以队友在**家目录**直接解压即得文档描述的布局:
```bash
cd ~ && tar xzf sru_nav_handover.tgz # 解出 ~/sru_ws/{src,reference}
```
> 已验证:归档内两个 ONNX 与源文件**逐字节一致**(`cmp` 通过)、包内容与源树 `diff -r` 完全一致、
> `venv/` / `build/` / `install/` / `log/` / `__pycache__` / 权重 / 地形 / 图片**均未进入归档**。
> 另一条路:**直接用 git 传 `src/sru_nav_ros2/` 一个目录**(它是自包含的),
> `reference/` 那边自己 `git clone https://github.com/ManifoldTechLtd/SRU-Odin` 到
> `~/sru_ws/reference/SRU-Odin`,然后 checkout `6a81ba77f46d4ab010d3d3354d54ec25ef730955`。
### 1.4 `Train/` 值得带什么(如果你要带的话)
`Train/` 是**训练侧**(Isaac Sim 4.5 + IsaacLab 的 Docker 环境),**不能用来部署**,
但它是**部署代码的规格书** —— 凡是"部署必须与训练一致"的地方,最终都要以它为准。
开发过程中它就是靠这个目录定下了下面这些结论(而不是"相信交接文档"):
| 用 `Train/` 定下的结论 | 出处 |
|---|---|
| 目标向量归一化公式 `log(distance + 1.0)` + 方向分量 —— **独立验证了 `model.py` 与 ONNX 的 I/O 契约** | `mdp/navigation/goal_commands.py` |
| 动作空间是 **SE2 三维 `[vx, vy, ω]`**(同时输出,不是"先转后走") | `navigation_se2_actions.py` 的 `self._action_dim = 3` |
| 训练用的动作尺度是 **`policy_scaling = [1.5, 1.0, 1.0]`** —— 证实部署里的 `policy_scale` 就是它对应的旋钮 | `navigation_env_cfg.py` |
| 训练**到达阈值 0.5 m**(部署蓝本用 0.75 m,更松) | `mdp/terminations.py` |
| 低通 α 随机范围 `(0.1, 0.6)` ⇒ 部署的 `[0.1, 0.5, 0.5]` 落在训练区间内 | `config/b2w/navigation_env_cfg.py` |
另外 `mount/sru-navigation-sim/scripts/` 里有几个**方法值得借鉴**的脚本:
- **`ablate_depth.py`** —— 判断"策略到底有没有真在用深度,还是学会了忽略(perception-blind)"。
这个思路可以搬到我们的部署侧做上机前验证:**把深度输入置零/替换,看 `/cmd_vel` 有没有跟着变**。
- `export_onnx.py` —— ONNX 是从 checkpoint 怎么导出来的。以后要重训/换模型,这是唯一依据。
- `analyze_collisions.py` / `eval_terminations.py` / `inspect_run.py` —— 训练侧的分析工具。
⚠️ **别搞混**:`Train/` 里的 `.pt` / `.pth` 是**低层步态策略**(给腿足/轮腿底盘走的)和 **VAE 预训练权重**,
**不是**我们部署用的 `nav_policy.onnx` / `vae_encoder.onnx`,**不要**拿它们去替换模型。
**精简打包(342 MB → 打包后约 130 KB)**:
```bash
tar czf sru_nav_train_slim.tgz \
--exclude='*/assets/*' --exclude='*.usd' --exclude='*.jpg' \
--exclude='*.pth' --exclude='*.pt' --exclude='*/__pycache__' \
-C ~/sru_ws/reference/SRU-Odin Train
# 实测:打包后约 130 KB(129,517 B),解压后约 800 KB / 87 个文件
# 排除掉的正是那 341 MB 的权重(.pt/.pth)、地形(.usd)与图片(.jpg)
```
---
## 2. 新机器上的环境安装
### 2.1 前提(先确认,不满足就别往下走)
| 项 | 要求 |
|---|---|
| 系统 | **Ubuntu 22.04**(Jammy)。ROS 2 Humble 只支持这个 LTS |
| CPU 架构 | **先确认 `uname -m`**。本包在 `x86_64` 上验证过;若是 **ARM(如 Jetson)**,`onnxruntime` / `scipy` 的 wheel 可用性不同,需要单独确认,可能装不上 |
| 磁盘 | 至少 2 GB 余量(包 28 MB + venv ~300 MB + ROS) |
| ROS 2 | Humble,**必须已装**(本包不自带) |
| 网络 | 装 apt / pip 时可用 |
### 2.2 apt 包
```bash
sudo apt update
sudo apt install -y \
ros-humble-desktop \
ros-humble-cv-bridge \
ros-humble-joy \
ros-humble-tf2-ros \
ros-humble-rviz2 \
python3-colcon-common-extensions \
python3.10-venv
```
### 2.3 建 venv(**在新机器上重建,不要拷**)
```bash
/usr/bin/python3 -m venv --system-site-packages ~/sru_ws/venv
~/sru_ws/venv/bin/pip install --upgrade pip
~/sru_ws/venv/bin/pip install "numpy<2" onnxruntime
~/sru_ws/venv/bin/pip install "scipy==1.11.4"
```
三个参数/版本**都不是可选项**:
- **`--system-site-packages`**:venv 必须能看到 ROS 2 的 `rclpy` / `cv_bridge`,否则白建。
- **`"numpy<2"`**:不锁的话 pip 会装 numpy 2.x,而 numpy 2.x 会让 `cv_bridge` 报
`_ARRAY_API not found`、`import cv2` 直接段错误。
- **`scipy==1.11.4` 用精确版本号**:`--system-site-packages` 的 venv 里,pip 会把
`/usr/lib/python3/dist-packages` 的包**当成"已满足"**,写 `pip install scipy`(哪怕是 `scipy<1.14`)
只会回 `Requirement already satisfied` 而**不装进 venv**,运行时仍命中 apt 的 scipy 1.8.0
(它 pin 了 `numpy<1.25`,与 venv 的 numpy 1.26.4 冲突)。**必须给精确版本号**才能强制装进去。
> **绝对不要 `pip install opencv-python`**:本包用的是系统 `python3-opencv`(4.5.4),
> 与 `cv_bridge` 同源。装了 pip 版会把系统版顶掉,回到上面那个崩溃状态。
### 2.4 往 venv 的 activate 里追加两行(**把路径换成你的**)
```bash
cat >> ~/sru_ws/venv/bin/activate <<'EOF'
export PYTHONNOUSERSITE=1
export PYTHONPATH="__YOUR_VENV__/lib/python3.10/site-packages${PYTHONPATH:+:$PYTHONPATH}"
EOF
# 把 __YOUR_VENV__ 换成真实路径,例如 /home/你的用户名/sru_ws/venv
sed -i "s|__YOUR_VENV__|$HOME/sru_ws/venv|" ~/sru_ws/venv/bin/activate
tail -3 ~/sru_ws/venv/bin/activate # 确认两行在里面,且路径正确
```
**这两行分别在治什么病**(完整原理见 `DEPLOY_ROS2.md` §2.3):
- **`PYTHONNOUSERSITE=1`**:`--system-site-packages` 建的 venv,CPython **不会**禁用用户级 site,
于是 `~/.local/lib/python3.10/site-packages` 照旧进 `sys.path`。那里如果有 pip 版 numpy 2 / opencv,
就会顶掉系统版 → `cv_bridge` 崩、`import cv2` 段错误。
**只放 venv 的 activate,不要写进 `~/.bashrc`**(会连累你其它项目)。
- **`PYTHONPATH` 追加**:`/usr/bin/colcon` 与 `ros2` 的 shebang **硬编码 `#!/usr/bin/python3`**,
所以 `console_scripts` 入口脚本**永远跑在系统 python 上**(激活 venv 改变不了这一点),
它看不见 venv 里的 `onnxruntime` → 启动即 `ModuleNotFoundError: No module named 'onnxruntime'`。
把 venv 的 site-packages 挂到 `PYTHONPATH` 才是正解。
⚠️ **必须"追加"(保留 `$PYTHONPATH`)**:覆盖式赋值会冲掉 `source setup.bash` 注入的 ROS 路径,
立刻变成 `No module named 'cv_bridge'`。
### 2.5 ⚠️ 两个 `COLCON_IGNORE`(重建 venv 后**必须**立刻补上 venv 那个)
```bash
mkdir -p ~/sru_ws/reference ~/sru_ws/src
touch ~/sru_ws/reference/COLCON_IGNORE
touch ~/sru_ws/venv/COLCON_IGNORE # ← 重建 venv 后容易忘,忘了 colcon 必炸
```
**为什么**:`colcon build` 是从工作区根目录**递归爬全部子目录**的,**不是只爬 `src/`**。没有这两个标记它会:
| 被误判成包 | 位置 | 后果 |
|---|---|---|
| `sru_nav_go2_ros1` | `reference/SRU-Odin/Deployment/`(有 `package.xml` + catkin `CMakeLists.txt`) | **致命**:Humble 没有 catkin,`find_package(catkin)` 直接失败 |
| `isaaclab_nav_task` | `reference/SRU-Odin/Train/.../`(有 `setup.py`) | 被当 Python 包一起构建 |
| `my-test-package` | `venv/.../pkg_resources/tests/data/my-test-package-source/` | 同上,外加几千个 site-packages 的 `setup.py` 刷屏报错 |
> 标记文件放在**父目录**(`reference/`、`venv/`),**不要**放进 `reference/SRU-Odin/` 内部(会污染只读蓝本)。
### 2.6 环境验收(这四条全绿再往下)
```bash
source /opt/ros/humble/setup.bash
source ~/sru_ws/venv/bin/activate
# ① 依赖齐全、版本正确
python - <<'PY'
import os, cv2, numpy, scipy, yaml, onnxruntime, rclpy
from cv_bridge import CvBridge
print("PYTHONNOUSERSITE", os.environ.get("PYTHONNOUSERSITE")) # 期望 1
print("numpy ", numpy.__version__, numpy.__file__) # 期望 1.26.x,在 venv 下
print("cv2 ", cv2.__version__, cv2.__file__) # 期望 4.5.4,在 /usr/lib/python3/dist-packages
print("scipy ", scipy.__version__, scipy.__file__) # 期望 1.11.4,在 venv 下
print("ort ", onnxruntime.__version__, onnxruntime.get_available_providers())
print("CvBridge", CvBridge())
PY
# ② colcon 只认到我们的包,且无噪音
cd ~/sru_ws && colcon list
# 期望只有一行:sru_nav_ros2 src/sru_nav_ros2 (ros.ament_python)
```
**关键期望值**:`cv2` 必须是 **4.5.4** 且路径在 `/usr/lib/python3/dist-packages`(不是 `~/.local`、
也不是 venv 里);`numpy`/`scipy` 必须在 **venv** 下。
---
## 3. 构建与运行
```bash
source /opt/ros/humble/setup.bash
source ~/sru_ws/venv/bin/activate
cd ~/sru_ws && colcon build --symlink-install
source install/setup.bash
# 正常启动(手柄 deadman 生效,安全默认)
ros2 launch sru_nav_ros2 sru_nav.launch.py
# 无手柄冒烟测试(TESTING ONLY,务必先抬轮/架空)
ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false
```
**期望日志**:
```
[sru_nav_node-2] [INFO] [...] VAE encoder: .../share/sru_nav_ros2/models/vae_encoder.onnx
[sru_nav_node-2] [INFO] [...] Policy model: .../share/sru_nav_ros2/models/nav_policy.onnx
[sru_nav_node-2] [INFO] [...] Navigation policy node is ready.
[sru_nav_node-2] [INFO] [...] SRU navigation node spinning (odom_twist_in_base_frame=True, require_joystick=False).
```
> **不是故障,别误判**:
> - 没有 Odin 数据源时,每 5 s 刷一次 `Odometry not ready, skipping depth callback.` —— 在等 odom。
> - **没发目标时 `/cmd_vel` 恒为 0,并每秒刷 `Target position reset.`** —— 蓝本原有设计。
> - `waypoint_runner` 约 10 s 后会把原地不动的目标判为 `STUCK` 并跳过 —— 车确实不动,是它的设计行为。
> 💡 `--symlink-install` 下 `install/`、`build/` 里全是指向 `src/` 的**符号链接**:
> 改代码 / launch / config **不需要重新 `colcon build`**,重启 launch 即可
> (但**必须重启进程**,改了不会热加载)。
---
## 4. 功能包怎么用
### 4.1 两个可执行入口
| 入口 | 作用 |
|---|---|
| `ros2 run sru_nav_ros2 sru_nav_node` | 主节点(也是 launch 起的那个)。订阅深度/odom/手柄/目标,发布 `/cmd_vel` |
| `ros2 run sru_nav_ros2 waypoint_runner --waypoints "…"` | 外部航点客户端。按顺序发目标、等到达/超时/卡住、可选回起点。**不碰主节点** |
### 4.2 话题接口
| 话题 | 类型 | 方向 | 说明 |
|---|---|---|---|
| `/odin1/depth_img_competetion` | `sensor_msgs/Image` | 入 | 稠密深度,**`32FC1`、单位米**、约 228×185(`1600/scale × 1296/scale`,`scale=7.0`) |
| `/odin1/odometry_highfreq` | `nav_msgs/Odometry` | 入 | 约 300–400 Hz。`frame_id = odom`、`child_frame_id = odin1_base_link`,**twist 已在 body 系** |
| `/joy` | `sensor_msgs/Joy` | 入 | 手柄(deadman + 手动速度叠加 + 智能摇杆功能) |
| `/goal_pose` | `geometry_msgs/PoseStamped` | 入/出 | 目标**位置**。`frame_id` 必须等于 odom 的 `header.frame_id`,否则被拒。⚠️ 它的 `orientation` 字段**从不被读取** |
| `/goal_yaw` | `std_msgs/Float64` | 入 | 目标**朝向**(弧度、odom 系)。`NaN` = 本目标无朝向要求。见 §4.5 |
| `/cmd_vel` | `geometry_msgs/Twist` | 出 | 速度指令(body 系)。**机型无关,桥上你自己接** |
| `/sru_nav_node/base_vel` | `geometry_msgs/Twist` | 出 | 调试用:转换后的 base 系速度 |
| `/sru_nav_node/vis/*` | `Marker` ×4 | 出 | rviz 用:速度箭头、目标方向箭头、moving goal、已记录路点 |
| `/sru_nav_node/vis/executed_path` | `nav_msgs/Path` | 出 | 实际走过的轨迹(1 Hz 采样) |
| `/sru_nav_node/vis/goal_path` | `nav_msgs/Path` | 出 | 当前位置 → 当前目标的直线 |
### 4.3 launch 参数
| 参数 | 默认 | 说明 |
|---|---|---|
| `params_file` | `share/sru_nav_ros2/config/sru_nav.yaml` | 参数文件路径 |
| `require_joystick` | `true` | 手柄 deadman。`false` **仅供测试** |
| `launch_joy` | `true` | 是否顺带起 `joy_node` |
| `launch_static_tf` | `true` | 是否发布静态 TF `odin1_base_link → base_link` |
| `base_link_x/y/z/roll/pitch/yaw` | Rc2026 比赛车实测值 | **`base_link` 在 `odin1_base_link` 下的位姿,必须按我们的载体实测替换**(见 §6 第 5 项) |
| `odom_twist_in_base_frame` | `true` | 语义见下 |
⚠️ 后两个参数(`require_joystick` / `odom_twist_in_base_frame`)的 **launch 默认值是从 YAML 里读出来的**,
不是写死的。原因:ROS 2 的 `parameters` 列表**后者覆盖前者**,launch 里硬编码的默认值会**静默盖掉 YAML**
(这个包踩过)。所以**改参数只改 `config/sru_nav.yaml` 就够了**;想临时翻一次用
`odom_twist_in_base_frame:=false` 这种命令行覆盖。
⚠️ **TF 方向与 ROS 1 蓝本相反,是有意为之**:驱动自己会广播 `odom → odin1_base_link`,
所以机器人侧只需补 `odin1_base_link → base_link`,TF 树才完整
(`odom → odin1_base_link → base_link`)。按蓝本发会让你有两个父节点,TF 树直接断。
### 4.4 参数(39 个,全在 `config/sru_nav.yaml`)
分组速查:
| 组 | 数量 | 说明 |
|---|---|---|
| 话题名 | 6 | `*_topic`,含 `goal_yaw_topic` |
| 模型路径 | 2 | 留空即从 `share/sru_nav_ros2/models/` 找 |
| 深度裁剪 | 2 | `min_depth` / `max_depth` |
| 控制 | 2 | `control_frequency`(**上限**,不是目标值)、`policy_scale` |
| 语义 / QoS | 3 | `odom_twist_in_base_frame`、`depth_qos_reliable`、`odom_qos_reliable` |
| 手柄 | 1 + 17 | `require_joystick` + 轴/键索引(沿用 constants.py 的 PS5 映射,**未在真手柄上验证过**) |
| 目标朝向 | 7 | `goal_yaw_*`,见 §4.5 |
**⛔ 绝对不要改的**(与训练对齐,改了行为就废):
```
control_frequency = 5.0 Hz policy_scale = [0.6, 0.3, 0.6] ← 训练值是 [1.5,1.0,1.0],部署刻意保守
require_joystick = true rnn_hidden_size = 512 / rnn_num_layers = 1
min/max_depth = 0.25 / 10.0 m resize(40, 64);latent 2560;obs 2576
ARRIVE_GOAL_THRESHOLD = 0.75 m JOYSTICK_TIMEOUT = 15.0 s
LOW_PASS_FILTER_COEF = [0.9,0.5,0.5] LATERAL_VELOCITY_SCALE = 0.6
```
> 这些**故意不放进 YAML**,从 `constants.py` 取值,不给被误配的机会。
> `constants.py` / `model.py` / `utils.py` 三个文件是**逐字节原样**的蓝本拷贝,**不要改**。
### 4.5 目标朝向(本包新增功能,蓝本没有)
策略**无法表达朝向**(观测里没有这一维,到达也只看 XY 距离)。所以本包补了一条链路:
**位置到达后,用自己的 20 Hz 定时器原地自转对准,然后才释放目标**。
```bash
# runner:第 4 个数就是 yaw(弧度);前面几点省略它 ⇒ 只有最后一点要求朝向
ros2 run sru_nav_ros2 waypoint_runner --waypoints "1,0 2,0 3,0,0,1.5708"
# 手发:位置走 /goal_pose,朝向走 /goal_yaw
ros2 topic pub --once --qos-durability transient_local \
/goal_yaw std_msgs/msg/Float64 "{data: 1.5708}" # 90°;发 NaN 则取消朝向要求
```
⚠️ 手发 `/goal_yaw` **必须带 `--qos-durability transient_local`**:节点是 TRANSIENT_LOCAL 订阅者,
`ros2 topic pub` 默认 VOLATILE 发布者,**不兼容 ⇒ 消息被静默丢弃**(发了完全没反应)。
关键参数:`goal_yaw_tolerance`(默认 0.0873 ≈ **±5°**)、`goal_yaw_max_rate`(0.6 rad/s)、
`goal_yaw_timeout`(15 s)。完整说明(含无载体自测方法)见 `DEPLOY_ROS2.md` **§6.4**。
### 4.6 在 rviz 里看
Fixed Frame 设 **`odom`**,Add → By topic 加:
`vis/executed_path`(Path)、`vis/goal_path`(Path)、`vis/twist_cmd_marker`、`vis/goal_vector_marker`、
`/goal_pose`(Pose)、`/odin1/odometry_highfreq`(Odometry),建议再打开 `/tf`。
⚠️ 再说一次:**`executed_path` 是"实际走过的轨迹",不是"规划路径"** —— 这策略没有规划器。
### 4.7 `/cmd_vel` 桥(接车的接口)
本包只发 `geometry_msgs/msg/Twist`。你们的底盘需要一个订阅 `/cmd_vel` 的桥(厂商 SDK 自写节点)。
**上机前必须确认一件事**:`sru_nav_node` 被杀掉之后,你的桥**会不会自动归零**?
如果不会,节点一死机器人会**保持最后一条速度指令**继续跑 —— 这是最容易出事故的点。
---
## 5. Odin1 驱动前置(不属于本包,但决定本包能不能跑)
### 5.1 深度默认是**关**的,必须改三个键
⚠️ **要改的是"源码树"里那份,不是 `install/` 里那份。**
驱动三个可执行文件都用 `get_package_source_directory()` 定位配置 —— 它从**编译期的 `__FILE__`**
逐级向上找到含 `package.xml` 的目录。所以**实际被读的文件**是:
```
<你的驱动源码目录>/src/odin_ros_driver/config/control_command.yaml ← 改这份
.../install/odin_ros_driver/share/odin_ros_driver/config/*.yaml ← 改了没用
```
三个键(出厂都是 `0`):
```yaml
senddtof: 1 # = "send raw cloud data",它才是 /odin1/cloud_raw 的开关
senddepth: 1 # 稠密深度图 /odin1/depth_img_competetion
sendrgb: 1 # 解码后的 RGB /odin1/image
```
**为什么三个都要开**:
- `senddepth: 0` 时深度节点打印 `Depth image will not be published.` 后**直接退出**;
- 深度节点用 `message_filters` 同步 **`{/odin1/cloud_raw, /odin1/image}` 一对**,
少任何一路,回调永不触发 ⇒ **永远没有深度 ⇒ `/cmd_vel` 一条都不发**。
这三个键属 `register_keys`(启动时下发给设备)⇒ **改完必须整体重启驱动**。
⚠️ **Odin1 的 USB 链路是独占的,不能同时跑两个 `host_sdk_sample`**,重启前先 Ctrl-C 掉旧的。
### 5.2 启动与验证
```bash
source /opt/ros/humble/setup.bash
source /sru_nav_handover/sru_ws/install/setup.bash
ros2 launch odin_ros_driver odin1_ros2.launch.py
```
**验证判据(很重要,别用错方法)**:
| 方法 | 可靠性 |
|---|---|
| `ros2 topic list` | ❌ 只要存在**任一**端点(哪怕只有订阅者)就会列出来 |
| `ros2 topic info` 的 `Publisher count` | ❌ 驱动启动时就建好了 publisher,没数据时它照样是 1 |
| **`ros2 topic hz <topic>`** | ✅ 唯一可信,但它会明确打印 `does not appear to be published yet` |
| **驱动自己写的设备状态 CSV** | ✅✅ 最权威 |
```bash
# 最权威:设备端发送率 vs 主机端接收率;rx = 0.00 的那一路就是没通
CSV=$(ls -1t <驱动源码目录>/log/Driver_*/Conn_*/dev_status.csv | head -1)
head -1 "$CSV"; tail -1 "$CSV"
# 健康值:rgb_rx_odr ~10、dtof_rx_odr ~10、slam_cloud_rx_odr ~10、slam_odom_highfreq_rx_odr ~400
```
⚠️ **大消息的 `hz` 会骗人**:`/odin1/image` 是 6.2 MB/帧、发布端 RELIABLE + 小队列,
Python 订阅者跟不上会把发布端一起拖慢(实测把 10 Hz 显示成 0.3 Hz)。
(深度图只有约 165 KiB,它的 `hz` **可信**。)
---
## 6. ⚠️ 已知问题 / 必须上机实测(**本节最重要**)
### 6.1 一条已经定性的"不是问题的问题"
**`/cmd_vel` 实测只有 1.4–1.7 Hz,深度也只有约 1.5 Hz,而设备端是 10 Hz。**
已经查到的事实:设备到主机是 10 Hz;主机到 ROS 订阅者只剩约 1.5 Hz —— **8 倍的损耗发生在
Odin 驱动的发布/DDS 交付环节**。本节点平均 CPU 只占 11%(89% 时间在空等),
**已排除本包**(`control_frequency: 5.0` 在代码里是**上限**不是目标值,输入慢就自然慢,
逻辑与 5 Hz 时完全一致,不会算错)。
可疑点是驱动里两个大话题硬编码的 `qos_sensor = rclcpp::QoS(5)`(odom 用的是 `QoS(4000)`,所以odom正常)。
**候选修法(驱动侧,1 行 + 重编)**:把 `QoS(5)` 改成 `QoS(50)`;或发布/订阅**成对**改成 BEST_EFFORT。
⛔ **绝对不能只把发布端改成 BEST_EFFORT** —— 会让现有的 RELIABLE 读者**静默收不到任何数据**。
### 6.2 必须上机实测的清单
| # | 项 | 现状 | 怎么测 | 影响 |
|---|---|---|---|---|
| 1 | **Odin1 装订外参 xyz/rpy** | 默认值是 **Rc2026 比赛车 R2 的实测装订**(`base_link` 在 `odin1_base_link` 下 `-0.268846, 0.028504, 0.067861, 0.017828, 0.245433, 0`)—— **不是我们的载体** | 尺子量 + `ros2 run tf2_ros tf2_echo odin1_base_link base_link`;更规范的是原地慢转做圆拟合 | 直接用错的装订会让目标方向偏差,越远越明显 |
| 2 | **目标朝向的精度(±5° 是设计目标)** | 逻辑已就位,**从未在真机上验证** | 发 `--waypoints "0,0,0,1.5708"` 看日志里的 `Goal heading aligned: residual error X deg` | 到点后的姿态不达标;底盘 yaw 死区大时会超时放弃 |
| 3 | **`/joy` 轴与键索引** | 沿用 `constants.py` 的 PS5 映射,**没在真手柄上验过** | `ros2 topic echo /joy` 逐个推摇杆/按键,改 17 个 `joy_axis_*` / `joy_button_*` 参数 | 手柄不好使;deadman 可能一直触发 |
| 4 | **deadman 的时钟域** | ⚠️ 本机驱动是 `use_host_ros_time: 0` = 用 **Odin 设备内部时间**打时间戳,与主机墙钟**不同基准**。而 deadman 判断式是 `odom 时间戳 − time.time() > 15 s`,**混算两个时间域** | 对比 `ros2 topic echo /odin1/odometry_highfreq --once --field header.stamp` 与 `date +%s` | 两个极端:odom 时间远大于墙钟 → **一上来就超时、`/cmd_vel` 恒为 0**;远小于 → 差值恒负、**deadman 事实上失效**(更危险)。**处理办法:把驱动的 `use_host_ros_time` 设成 `1`(主机时间)或 `2`(对齐到主机时间轴)后重启驱动**。关 `require_joystick` 时不受影响 |
| 5 | **odom twist 的正负号手感 / `odom_twist_in_base_frame`** | 已按参考工程定为 `true`(twist 已在 body 系,直接透传),**方向手感未验证** | 架空后手动推/转机器人,看 `/sru_nav_node/base_vel` 与预期方向是否一致 | 判反了会让车往反方向跑 |
| 6 | **铺密集路点会踩到达阈值** | `ARRIVE_GOAL_THRESHOLD = 0.75 m`,且**发布即判到达** ⇒ **路点间距 ≤ 0.75 m 时机器人一步都不走**。每跳实际只推进"间距 − 0.75 m" | 用间距 ≥ 3–5 m 的航点 | 密集面包屑适得其反。想更密需要把阈值降到训练值 **0.5 m**(属"绝对不能改"清单,**要拍板**) |
| 7 | **装订带俯仰角的残余量** | `odom_twist_in_base_frame: true` 让 twist 透传,但 Odin1 若带俯仰角安装,`odin1_base_link` 是倾斜的:`linear.x` 会被乘上约 `cos(pitch)`,并出现一点虚假的 `linear.z` | 观察 `/sru_nav_node/base_vel` 里有没有不该有的 `linear.z` | 速度略偏小 + 一点噪声。参考工程也是这么接受的;要精确补偿需要一次 TF 查询(属新增功能,未做) |
| 8 | **手柄 deadman 之外的 `/joy` 高级功能**(智能摇杆、按钮发目标/回起点/记录路点) | 代码完整但从未实测 | 按 `constants.py` 的按钮定义逐个试 | 可能按错按钮触发意外动作 |
**其它可能还存在的问题**
- **`/cmd_vel` 只有一个发布者**(本节点)。自转对准期间因为用的是**独立定时器**,
`generate_cmd_vel` 会主动"让路"不发零速,避免两个来源抢话题 —— 这点已验证。
- 若驱动用的是**另一台机器的另一份源码目录**,注意 §5.1 那条:**生效的 config 是编译期路径对应的那份**。
- **CPU 架构**:若是 ARM 小电脑,`onnxruntime` / `scipy` 的 wheel 需要单独确认(见 §2.1)。
---
## 7. 首次上机安全流程
1. **抬轮 / 架空**,别落地。
2. 先确认驱动数据流(§5.2),再起控制器。
3. 用 `require_joystick:=false` 跑冒烟,`ros2 topic echo /cmd_vel` 看数值是否**有界合理**
(已知上限:`|linear_x| ≤ 0.6`、`|linear_y| ≤ 0.18`、`|angular_z| ≤ 0.6`)。
4. 确认急停手段可用:
- 手柄按 `BUTTON_ABORT`(默认 index 9)→ 立刻发零速并放弃当前目标;
- Ctrl-C 停 `sru_nav_node` → **但要先确认桥会不会自动归零**(§4.7);
- 物理断电。
5. 落地后先用**很慢的** `policy_scale`(当前已是保守值)跑一次近目标(2–3 m),
确认方向手感对了再放大。
---
## 8. 出问题先看哪里
| 症状 | 去哪看 |
|---|---|
| 节点起不来、`ModuleNotFoundError: onnxruntime` | §2.4(`PYTHONPATH` 那行);确认是 `source ~/sru_ws/venv/bin/activate` 之后再 `ros2 launch` |
| `import cv2` 段错误 / `cv_bridge` 报 `_ARRAY_API not found` | §2.4(`PYTHONNOUSERSITE`);检查 `cv2.__file__` 是不是被 `~/.local` 顶掉了 |
| `colcon build` 报 catkin 找不到 / 冒出一堆无关包名 | §2.5(`COLCON_IGNORE`) |
| 起崩报 `AttributeError: ... has no attribute 'xxx'` | 改了代码但**没重启进程**;或改动没真落盘 |
| `/cmd_vel` 一条都没有 | **没有深度**(§5.1)。日志里 `cmd_vel_ratio:` 与 `Published cmd_vel:` 会**全然不出现** |
| `/cmd_vel` 恒为 0 | ① 没发目标(正常分支,会刷 `Target position reset.`);② deadman(§6.2 #4);③ 目标比 0.75 m 还近 |
| 订阅了但收不到深度、且不报错 | **QoS 不匹配**:ROS 2 里 BEST_EFFORT 发布端 + RELIABLE 订阅端 = 静默收不到。用 `ros2 topic info -v` 对比两端 |
| 其它 | **`DEPLOY_ROS2.md` §8 排错速查表**(约 20 条现象→原因) |
---
## 9. 速查
```bash
# 环境
source /opt/ros/humble/setup.bash && source ~/sru_nav_handover/sru_ws/venv/bin/activate
source ~/sru_nav_handover/sru_ws/install/setup.bash
# 起控制器(正常 / 无手柄冒烟)
ros2 launch sru_nav_ros2 sru_nav.launch.py
ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false
# 发目标(位置 + 朝向;前面几点省略 yaw ⇒ 只最后一点要求朝向)
ros2 run sru_nav_ros2 waypoint_runner --waypoints "1,0 2,0 3,0,0,1.5708"
# 只看数据(唯一可信的判据)
ros2 topic hz /odin1/odometry_highfreq
ros2 topic hz /odin1/depth_img_competetion
ros2 topic echo /cmd_vel
# 参数
ros2 param dump /sru_nav_node # 看当前值
ros2 param set /sru_nav_node goal_yaw_tolerance 0.05
```
**目录职责**
| 路径 | 说明 |
|---|---|
| `src/sru_nav_ros2/` | 交付包(本文件所在处) |
| `src/sru_nav_ros2/docs/DEPLOY_ROS2.md` | **权威细节文档** |
| `src/sru_nav_ros2/docs/AI_AGENT_PROMPT.md` | 给你那边的 AI Agent 的提示词 |
| `reference/SRU-Odin/Deployment/` | ROS 1 只读蓝本,**禁止修改**(留着 diff 用) |
| `venv/` | 在新机器上重建(§2.3) |
---
**最后一句话**:功能链路在开发机上已经跑通(深度 → 推理 → 非零 `/cmd_vel` 都实测过),
**没验证的都是"需要物理世界"的那些** —— 装订、朝向精度、手柄、正负号手感,以及那个驱动侧的速率问题。
有问题把**日志原文**发回来,比描述现象有用得多。
@@ -0,0 +1,191 @@
"""Launch the SRU navigation controller (Odin1 + ONNX policy) on ROS 2 Humble.
Starts three things:
1. ``joy_node`` -- optional gamepad driver (PS5/PS4 style)
2. ``static_transform_publisher`` -- optional static TF odin1_base_link -> base_link
3. ``sru_nav_node`` -- the controller: Odin1 depth + odometry in,
geometry_msgs/Twist on /cmd_vel out
The Odin1 driver (``odin_ros_driver``) and the /cmd_vel bridge to your platform
are NOT launched here; bring them up separately.
Typical use::
# normal run, joystick deadman armed (safe default)
ros2 launch sru_nav_ros2 sru_nav.launch.py
# headless / bench test with no gamepad (TESTING ONLY)
ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false
All tunables come from ``config/sru_nav.yaml``, installed to the package share
directory. Only the two safety-relevant switches are additionally exposed as
launch arguments, so they can be flipped from the command line; everything else
is changed in the YAML (no code edits needed).
IMPORTANT -- the defaults of those two launch arguments are read *from the YAML*
rather than hardcoded. In ROS 2 a later entry in the ``parameters`` list wins,
so a hardcoded launch default silently overrides the parameter file: exactly how
``odom_twist_in_base_frame`` once stayed ``false`` while the YAML said ``true``.
Sourcing the default from the file keeps a single source of truth.
"""
import os
import yaml
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.conditions import IfCondition
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
def _yaml_default(params_file, name, fallback):
"""Value of ``name`` as written in the shipped parameter file.
Used as the default of the launch arguments below so a launch default can
never contradict ``config/sru_nav.yaml``. Falls back to ``fallback`` if the
file cannot be read, so a broken YAML still lets the launch start and fail
with the node's own (clearer) error message instead.
"""
try:
with open(params_file, 'r') as f:
params = yaml.safe_load(f)['sru_nav_node']['ros__parameters']
return str(params[name]).lower()
except Exception:
return fallback
def generate_launch_description():
share_dir = get_package_share_directory('sru_nav_ros2')
default_params_file = os.path.join(share_dir, 'config', 'sru_nav.yaml')
# ---- launch arguments ----------------------------------------------------
declared_arguments = [
DeclareLaunchArgument(
'params_file', default_value=default_params_file,
description='Node parameter file (defaults to config/sru_nav.yaml '
'in the package share directory).'),
DeclareLaunchArgument(
'odom_twist_in_base_frame',
default_value=_yaml_default(default_params_file,
'odom_twist_in_base_frame', 'true'),
description='Treat the odom twist as already expressed in the body '
'frame and pass it through (renamed from the ROS 1 `sim` '
'argument; NOT related to use_sim_time). Default is '
'taken from config/sru_nav.yaml.'),
DeclareLaunchArgument(
'require_joystick',
default_value=_yaml_default(default_params_file,
'require_joystick', 'true'),
description='Joystick deadman. `false` bypasses it and is TESTING '
'ONLY. Default is taken from config/sru_nav.yaml.'),
DeclareLaunchArgument(
'launch_joy', default_value='true',
description='Start a joy_node alongside (PS5/PS4 etc.).'),
DeclareLaunchArgument(
'launch_static_tf', default_value='true',
description='Publish the static TF base_link -> odin1_base_link.'),
# ---- base_link mounting: MEASURE THESE ON YOUR OWN ROBOT -------------
# The Odin1 driver already broadcasts `odom -> odin1_base_link`
# (control_command.yaml: send_odom_baselink_tf: 1), so the only TF the
# robot side needs to supply is `odin1_base_link -> base_link`. That is
# exactly the chain the Rc2026 reference project builds:
# odom -> odin1_base_link -> base_link
# Publishing it the other way round (base_link -> odin1_base_link) would
# give odin1_base_link two parents and break the TF tree.
#
# The numbers therefore mean "where the platform centre (base_link) sits
# in the Odin1 frame" -- the INVERSE of "where the sensor is bolted on".
# xyz in metres, rpy in radians.
#
# Defaults are the Rc2026 R2 competition robot's MEASURED mounting
# (challenge1_z1.launch.py). They are NOT your platform: re-measure with
# a ruler / `tf2_echo`, or by circle-fitting a slow in-place rotation
# (the reference project ships calib_odin_mount.py for that).
DeclareLaunchArgument(
'base_link_x', default_value='-0.268846',
description='base_link origin in odin1_base_link, x [m]. VERIFY on your robot.'),
DeclareLaunchArgument(
'base_link_y', default_value='0.028504',
description='base_link origin in odin1_base_link, y [m]. VERIFY on your robot.'),
DeclareLaunchArgument(
'base_link_z', default_value='0.067861',
description='base_link origin in odin1_base_link, z [m]. VERIFY on your robot.'),
DeclareLaunchArgument(
'base_link_roll', default_value='0.017828',
description='base_link roll in the Odin1 frame [rad]. VERIFY on your robot.'),
DeclareLaunchArgument(
'base_link_pitch', default_value='0.245433',
description='base_link pitch in the Odin1 frame [rad]. VERIFY on your robot.'),
DeclareLaunchArgument(
'base_link_yaw', default_value='0.0',
description='base_link yaw in the Odin1 frame [rad]. VERIFY on your robot.'),
]
# ---- 1. joy_node ---------------------------------------------------------
joy_node = Node(
package='joy',
executable='joy_node',
name='joy_node',
output='screen',
condition=IfCondition(LaunchConfiguration('launch_joy')),
parameters=[{
'autorepeat_rate': 50.0,
'deadzone': 0.05,
}],
)
# ---- 2. static TF odin1_base_link -> base_link ---------------------------
# Direction matches the Rc2026 reference project: the driver owns
# odom -> odin1_base_link, this node only supplies the platform offset.
# Humble's static_transform_publisher documents only the named-flag form;
# the ROS 1 positional form (x y z yaw pitch roll frame child) is gone from
# its usage text, and the ROS 1 ordering was yaw,pitch,roll -- so the flags
# below are spelled out explicitly rather than copied positionally.
static_tf_node = Node(
package='tf2_ros',
executable='static_transform_publisher',
name='static_tf_odin1_to_base',
output='screen',
condition=IfCondition(LaunchConfiguration('launch_static_tf')),
arguments=[
'--x', LaunchConfiguration('base_link_x'),
'--y', LaunchConfiguration('base_link_y'),
'--z', LaunchConfiguration('base_link_z'),
'--roll', LaunchConfiguration('base_link_roll'),
'--pitch', LaunchConfiguration('base_link_pitch'),
'--yaw', LaunchConfiguration('base_link_yaw'),
'--frame-id', 'odin1_base_link',
'--child-frame-id', 'base_link',
],
)
# ---- 3. the controller ---------------------------------------------------
# YAML first, then the two switches: in ROS 2 parameter lists later entries
# win, so these launch arguments override the file. That is intended -- they
# exist so a run can be flipped from the command line -- and it is safe only
# because their defaults are read from the same YAML (see _yaml_default).
# `ParameterValue` is required to coerce the LaunchConfiguration string into
# a real bool: the node declares these as bool, and handing it the string
# 'false' would be rejected.
nav_node = Node(
package='sru_nav_ros2',
executable='sru_nav_node',
name='sru_nav_node',
output='screen',
parameters=[
LaunchConfiguration('params_file'),
{
'odom_twist_in_base_frame': ParameterValue(
LaunchConfiguration('odom_twist_in_base_frame'), value_type=bool),
'require_joystick': ParameterValue(
LaunchConfiguration('require_joystick'), value_type=bool),
},
],
)
return LaunchDescription(declared_arguments + [joy_node, static_tf_node, nav_node])
Binary file not shown.
Binary file not shown.
+44
View File
@@ -0,0 +1,44 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>sru_nav_ros2</name>
<version>0.1.0</version>
<description>
ROS 2 (Humble) port of the SRU navigation controller.
Loads the pretrained SRU policy (nav_policy.onnx) and the VAE depth encoder
(vae_encoder.onnx) through ONNX Runtime, subscribes to Odin1 depth / odometry
and a joystick, and publishes geometry_msgs/Twist on /cmd_vel.
Robot-agnostic: the /cmd_vel bridge to the actual platform is provided by the
caller (see docs/DEPLOY_ROS2.md).
</description>
<maintainer email="[email protected]">SRU Navigation Port</maintainer>
<license>MIT</license>
<buildtool_depend>ament_python</buildtool_depend>
<!-- ROS interfaces actually imported by the nodes and launch file. -->
<exec_depend>rclpy</exec_depend>
<exec_depend>std_msgs</exec_depend>
<exec_depend>sensor_msgs</exec_depend>
<exec_depend>geometry_msgs</exec_depend>
<exec_depend>nav_msgs</exec_depend>
<exec_depend>visualization_msgs</exec_depend>
<exec_depend>cv_bridge</exec_depend>
<exec_depend>tf2_ros</exec_depend>
<exec_depend>joy</exec_depend>
<exec_depend>ament_index_python</exec_depend>
<exec_depend>launch</exec_depend>
<exec_depend>launch_ros</exec_depend>
<!--
Python numerical dependencies (numpy / scipy / pyyaml / onnxruntime) are NOT
declared here on purpose. They are provided by an isolated virtualenv, not by
apt: the apt `python3-scipy` (1.8.0) pins numpy < 1.25 and conflicts with the
numpy that onnxruntime requires. See docs/DEPLOY_ROS2.md -> "Python environment".
-->
<export>
<build_type>ament_python</build_type>
</export>
</package>
@@ -0,0 +1 @@
+4
View File
@@ -0,0 +1,4 @@
[develop]
script_dir=$base/lib/sru_nav_ros2
[install]
install_scripts=$base/lib/sru_nav_ros2
+37
View File
@@ -0,0 +1,37 @@
import os
from glob import glob
from setuptools import find_packages, setup
package_name = 'sru_nav_ros2'
setup(
name=package_name,
version='0.1.0',
packages=find_packages(exclude=['test']),
data_files=[
# ament index marker: makes `ros2 pkg prefix` / `ros2 launch` find us.
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
# Runtime assets, reachable through ament_index_python.get_package_share_directory().
(os.path.join('share', package_name, 'config'), glob('config/*.yaml')),
(os.path.join('share', package_name, 'launch'), glob('launch/*.launch.py')),
(os.path.join('share', package_name, 'models'), glob('models/*.onnx')),
(os.path.join('share', package_name, 'docs'), glob('docs/*.md')),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='SRU Navigation Port',
maintainer_email='[email protected]',
description=('ROS 2 (Humble) port of the SRU navigation controller: '
'ONNX VAE depth encoder + SRU policy, Odin1 depth/odometry in, '
'geometry_msgs/Twist on /cmd_vel out.'),
license='MIT',
entry_points={
'console_scripts': [
'sru_nav_node = sru_nav_ros2.sru_nav_node:main',
'waypoint_runner = sru_nav_ros2.waypoint_runner:main',
],
},
)
@@ -0,0 +1 @@
@@ -0,0 +1,80 @@
"""Constants and configuration values for the Go2 + Odin1 SRU navigation port.
Defaults are tuned conservatively for Unitree Go2 (no wheels, weaker lateral
ability) versus the original B2W (wheeled). Override at runtime through the
companion YAML / launch parameters.
"""
# ---------------------------------------------------------------------------
# Control parameters
# ---------------------------------------------------------------------------
DEFAULT_CONTROL_FREQUENCY = 5.0 # Hz (matches training)
DEFAULT_MIN_DEPTH = 0.25 # meters
DEFAULT_MAX_DEPTH = 10.0 # meters
ARRIVE_GOAL_THRESHOLD = 0.75 # meters
NEAR_GOAL_THRESHOLD_MULTIPLIER = 2.0
JOYSTICK_TIMEOUT = 15.0 # seconds (safety deadman timeout)
# ---------------------------------------------------------------------------
# Policy output scaling. Original B2W used [1.5, 1.0, 1.0].
# Go2 is conservative until verified safe in real hardware.
# ---------------------------------------------------------------------------
POLICY_SCALE = [0.6, 0.3, 0.6] # [linear_x, linear_y, angular_z]
LATERAL_VELOCITY_SCALE = 0.6 # extra damping on linear_y
# Low-pass filter coefficients (alpha): output = a*new + (1-a)*prev
LOW_PASS_FILTER_COEF = [0.9, 0.5, 0.5]
# ---------------------------------------------------------------------------
# Joystick axis / button mappings (PS5-style, same as original)
# ---------------------------------------------------------------------------
JOYSTICK_AXIS_LINEAR_X = 1
JOYSTICK_AXIS_LINEAR_Y = 0
JOYSTICK_AXIS_LINEAR_Z = 3
JOYSTICK_AXIS_ANGULAR_Z = 2
JOYSTICK_AXIS_SMART = 5
BUTTON_RESET_HIDDEN_STATE = 2
BUTTON_RECORD_WAYPOINT = 6
BUTTON_CLEAR_WAYPOINT = 4
BUTTON_SEND_GOAL = 10
BUTTON_ABORT = 9
BUTTON_TRIGGER_WAYPOINTS = 1
BUTTON_FORWARD = 11
BUTTON_BACKWARD = 12
BUTTON_LEFT = 13
BUTTON_RIGHT = 14
BUTTON_UP = 3
BUTTON_DOWN = 0
# ---------------------------------------------------------------------------
# Scales
# ---------------------------------------------------------------------------
LINEAR_SCALE = 1.0
ANGULAR_SCALE = 1.0
MOVING_SCALE = 0.2
SMART_JOYSTICK_SCALE = 5.0
SMART_JOYSTICK_UPDATE_FREQUENCY = 5.0 # Hz
SMART_JOYSTICK_Z_SCALE = 0.25
SMART_JOYSTICK_FILTER_ALPHA = 0.2
# ---------------------------------------------------------------------------
# Timer intervals
# ---------------------------------------------------------------------------
WAYPOINT_PUBLISH_INTERVAL = 0.2 # 5 Hz
TARGET_VECTOR_PUBLISH_INTERVAL = 0.2 # 5 Hz
TRIGGER_BUTTON_COOLDOWN = 1.0 # seconds
# ---------------------------------------------------------------------------
# Visualization
# ---------------------------------------------------------------------------
TWIST_MARKER_SCALE = 5.0
TWIST_MARKER_ID = 0
TARGET_VECTOR_MARKER_ID = 1
MOVING_GOAL_MARKER_ID = 2
WAYPOINTS_MARKER_ID = 3
# ---------------------------------------------------------------------------
# Physics
# ---------------------------------------------------------------------------
GRAVITY_MAGNITUDE = 9.81 # m/s^2
@@ -0,0 +1,176 @@
"""SRU Navigation learning model (ONNX Runtime).
Identical inference pipeline to the original ROS2 deployment. No ROS deps.
"""
import cv2
import numpy as np
import onnxruntime as ort
from sru_nav_ros2 import constants
from sru_nav_ros2.utils import subtract_frame_transforms, transform_points
# Model architecture constants (must match training-time export).
STATE_DIM = 16 # linear_vel(3)+angular_vel(3)+gravity(3)+last_action(3)+target_pos_log(4)
DEPTH_EMBEDDING_DIM = 2560 # 64 * 5 * 8 (flattened VAE output)
POLICY_INPUT_DIM = STATE_DIM + DEPTH_EMBEDDING_DIM # 2576
LSTM_HIDDEN_DIM = 512
class LearningModel:
"""RL navigation policy + depth VAE encoder (ONNX Runtime).
VAE encoder:
depth_image [1, 1, 40, 64] -> mu [1, 64, 5, 8] -> flat [2560]
Policy (LSTM):
obs [1, 2576] + h_in [1, 1, 512] + c_in [1, 1, 512]
-> raw_action [1, 3], h_out, c_out
cmd_vel = tanh(raw_action) * POLICY_SCALE
"""
def __init__(self, preprocess_model_path, policy_model_path,
policy_scale=None, intra_op_num_threads=4):
available_providers = ort.get_available_providers()
if 'CUDAExecutionProvider' in available_providers:
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
print('\033[92m' + 'Using device: CUDA (ONNX Runtime)' + '\033[0m')
elif 'TensorrtExecutionProvider' in available_providers:
providers = ['TensorrtExecutionProvider', 'CUDAExecutionProvider',
'CPUExecutionProvider']
print('\033[92m' + 'Using device: TensorRT (ONNX Runtime)' + '\033[0m')
else:
providers = ['CPUExecutionProvider']
print('\033[93m' + 'Using device: CPU (ONNX Runtime)' + '\033[0m')
sess_options = ort.SessionOptions()
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
sess_options.intra_op_num_threads = int(intra_op_num_threads)
self.preprocess_session = ort.InferenceSession(
preprocess_model_path, sess_options=sess_options, providers=providers
)
self.policy_session = ort.InferenceSession(
policy_model_path, sess_options=sess_options, providers=providers
)
self.preprocess_input_name = self.preprocess_session.get_inputs()[0].name
self.preprocess_output_name = self.preprocess_session.get_outputs()[0].name
self.policy_input_names = {inp.name: inp for inp in self.policy_session.get_inputs()}
self.policy_output_names = [out.name for out in self.policy_session.get_outputs()]
self._h_state = np.zeros((1, 1, LSTM_HIDDEN_DIM), dtype=np.float32)
self._c_state = np.zeros((1, 1, LSTM_HIDDEN_DIM), dtype=np.float32)
if policy_scale is None:
policy_scale = constants.POLICY_SCALE
self._policy_scale = np.array(policy_scale, dtype=np.float32)
self.fake_run_once()
print('\033[92m' + 'Learning model is ready (ONNX Runtime).' + '\033[0m')
# -----------------------------------------------------------------
# Depth preprocessing
# -----------------------------------------------------------------
@staticmethod
def _resize_bilinear(img, target_size):
return cv2.resize(img, (target_size[1], target_size[0]),
interpolation=cv2.INTER_LINEAR)
def depth_preprocess(self, img):
"""Encode a depth image (H, W) into a 2560-dim latent."""
img_resized = self._resize_bilinear(img, (40, 64))
img_tensor = img_resized.astype(np.float32)[np.newaxis, np.newaxis, :, :]
vae_output = self.preprocess_session.run(
[self.preprocess_output_name],
{self.preprocess_input_name: img_tensor},
)[0]
return vae_output.flatten()
# -----------------------------------------------------------------
# Target encoding
# -----------------------------------------------------------------
def normalize_target_position(self, target_pos_w, robot_pos_w, robot_orientation_w):
target_pos_w = np.array(target_pos_w, dtype=np.float32)[np.newaxis]
robot_pos_w = np.array(robot_pos_w, dtype=np.float32)[np.newaxis]
robot_orientation_w = np.array(robot_orientation_w, dtype=np.float32)[np.newaxis]
inv_pos, inv_rot = subtract_frame_transforms(robot_pos_w, robot_orientation_w)
target_vec_b = transform_points(target_pos_w, inv_pos, inv_rot)
dist = np.linalg.norm(target_vec_b, axis=-1, keepdims=True) + 1e-6
target_pos = target_vec_b / dist
dist_log = np.log(dist + 1.0)
target_pos = np.concatenate((target_pos, dist_log), axis=-1).reshape(-1)
return target_pos, target_vec_b
# -----------------------------------------------------------------
# LSTM state management
# -----------------------------------------------------------------
def reset_hidden_state(self):
self._h_state = np.zeros((1, 1, LSTM_HIDDEN_DIM), dtype=np.float32)
self._c_state = np.zeros((1, 1, LSTM_HIDDEN_DIM), dtype=np.float32)
# -----------------------------------------------------------------
# Inference
# -----------------------------------------------------------------
def predict(self, linear_vel, angular_vel, gravity_vector, last_action,
target_pos_w, robot_pos_w, robot_orientation_w, depth_image,
is_reset=False):
if is_reset:
self.reset_hidden_state()
depth_embedding = self.depth_preprocess(depth_image)
target_pos_log, target_vec_b = self.normalize_target_position(
target_pos_w, robot_pos_w, robot_orientation_w
)
state_input = np.array(
list(linear_vel) + list(angular_vel) + list(gravity_vector) +
list(last_action) + target_pos_log.tolist(),
dtype=np.float32,
)
obs = np.concatenate([state_input, depth_embedding])[np.newaxis].astype(np.float32)
outputs = self.policy_session.run(
None,
{
'obs': obs,
'h_in': self._h_state,
'c_in': self._c_state,
},
)
raw_action, h_out, c_out = outputs
self._h_state = h_out
self._c_state = c_out
cmd_vel = np.tanh(raw_action) * self._policy_scale
cmd_vel = cmd_vel.squeeze(0)
raw_action = raw_action.squeeze(0)
return cmd_vel, raw_action, target_vec_b
def fake_run_once(self):
linear_vel = [0.0, 0.0, 0.0]
angular_vel = [0.0, 0.0, 0.0]
gravity_vector = [0.0, 0.0, -1.0]
target_pos_w = [1.0, 0.0, 0.0]
robot_pos_w = [0.0, 0.0, 0.0]
robot_orientation_w = [1.0, 0.0, 0.0, 0.0]
last_action = [0.0, 0.0, 0.0]
depth_image = np.random.rand(600, 960).astype(np.float32)
cmd_vel, _, _ = self.predict(
linear_vel, angular_vel, gravity_vector, last_action,
target_pos_w, robot_pos_w, robot_orientation_w, depth_image,
is_reset=True,
)
print('Warmup predicted cmd_vel: linear_x={:.4f}, linear_y={:.4f}, '
'angular_z={:.4f}'.format(cmd_vel[0], cmd_vel[1], cmd_vel[2]))
self.reset_hidden_state()
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,34 @@
"""Console entry point for the SRU navigation controller (ROS 2 Humble).
Installed as the ``sru_nav_node`` executable through ``setup.py``
``console_scripts``::
ros2 run sru_nav_ros2 sru_nav_node
It owns only the rclpy lifecycle. Everything else -- parameter declaration,
model resolution, publishers, subscribers and timers -- lives in
:class:`~sru_nav_ros2.navigation_policy_node.NavigationPolicyNode`.
"""
import rclpy
from sru_nav_ros2.navigation_policy_node import NavigationPolicyNode
def main(args=None):
rclpy.init(args=args)
node = None
try:
node = NavigationPolicyNode()
rclpy.spin(node)
except KeyboardInterrupt:
pass
finally:
if node is not None:
node.destroy_node()
if rclpy.ok():
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1,252 @@
"""Quaternion and transformation utilities using NumPy (no PyTorch dependency)."""
import numpy as np
def normalize(x: np.ndarray, eps: float = 1e-9) -> np.ndarray:
"""Normalizes a given input array to unit length.
Args:
x: Input array of shape (N, dims) or (dims,).
eps: A small value to avoid division by zero. Defaults to 1e-9.
Returns:
Normalized array of same shape as input.
"""
if x.ndim == 1:
norm = np.linalg.norm(x)
return x / max(norm, eps)
else:
norm = np.linalg.norm(x, axis=-1, keepdims=True)
return x / np.clip(norm, eps, None)
def yaw_quat(quat: np.ndarray) -> np.ndarray:
"""Extract the yaw component of a quaternion.
Args:
quat: The orientation in (w, x, y, z). Shape is (..., 4)
Returns:
A quaternion with only yaw component.
"""
shape = quat.shape
quat_yaw = quat.copy().reshape(-1, 4)
qw = quat_yaw[:, 0]
qx = quat_yaw[:, 1]
qy = quat_yaw[:, 2]
qz = quat_yaw[:, 3]
yaw = np.arctan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz))
quat_yaw[:] = 0.0
quat_yaw[:, 3] = np.sin(yaw / 2)
quat_yaw[:, 0] = np.cos(yaw / 2)
quat_yaw = normalize(quat_yaw)
return quat_yaw.reshape(shape)
def quat_conjugate(q: np.ndarray) -> np.ndarray:
"""Computes the conjugate of a quaternion.
Args:
q: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
Returns:
The conjugate quaternion in (w, x, y, z). Shape is (..., 4).
"""
shape = q.shape
q = q.reshape(-1, 4)
return np.concatenate((q[:, 0:1], -q[:, 1:]), axis=-1).reshape(shape)
def quat_inv(q: np.ndarray) -> np.ndarray:
"""Compute the inverse of a quaternion.
Args:
q: The quaternion orientation in (w, x, y, z). Shape is (N, 4).
Returns:
The inverse quaternion in (w, x, y, z). Shape is (N, 4).
"""
return normalize(quat_conjugate(q))
def quat_mul(q1: np.ndarray, q2: np.ndarray) -> np.ndarray:
"""Multiply two quaternions together.
Args:
q1: The first quaternion in (w, x, y, z). Shape is (..., 4).
q2: The second quaternion in (w, x, y, z). Shape is (..., 4).
Returns:
The product of the two quaternions in (w, x, y, z). Shape is (..., 4).
Raises:
ValueError: Input shapes of ``q1`` and ``q2`` are not matching.
"""
if q1.shape != q2.shape:
msg = f"Expected input quaternion shape mismatch: {q1.shape} != {q2.shape}."
raise ValueError(msg)
shape = q1.shape
q1 = q1.reshape(-1, 4)
q2 = q2.reshape(-1, 4)
w1, x1, y1, z1 = q1[:, 0], q1[:, 1], q1[:, 2], q1[:, 3]
w2, x2, y2, z2 = q2[:, 0], q2[:, 1], q2[:, 2], q2[:, 3]
ww = (z1 + x1) * (x2 + y2)
yy = (w1 - y1) * (w2 + z2)
zz = (w1 + y1) * (w2 - z2)
xx = ww + yy + zz
qq = 0.5 * (xx + (z1 - x1) * (x2 - y2))
w = qq - ww + (z1 - y1) * (y2 - z2)
x = qq - xx + (x1 + w1) * (x2 + w2)
y = qq - yy + (w1 - x1) * (y2 + z2)
z = qq - zz + (z1 + y1) * (w2 - x2)
return np.stack([w, x, y, z], axis=-1).reshape(shape)
def quat_apply(quat: np.ndarray, vec: np.ndarray) -> np.ndarray:
"""Apply a quaternion rotation to a vector.
Args:
quat: The quaternion in (w, x, y, z). Shape is (..., 4).
vec: The vector in (x, y, z). Shape is (..., 3).
Returns:
The rotated vector in (x, y, z). Shape is (..., 3).
"""
shape = vec.shape
quat = quat.reshape(-1, 4)
vec = vec.reshape(-1, 3)
xyz = quat[:, 1:]
t = np.cross(xyz, vec) * 2
return (vec + quat[:, 0:1] * t + np.cross(xyz, t)).reshape(shape)
def matrix_from_quat(quaternions: np.ndarray) -> np.ndarray:
"""Convert rotations given as quaternions to rotation matrices.
Args:
quaternions: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
Returns:
Rotation matrices. The shape is (..., 3, 3).
"""
r, i, j, k = quaternions[..., 0], quaternions[..., 1], quaternions[..., 2], quaternions[..., 3]
two_s = 2.0 / (quaternions * quaternions).sum(-1)
o = np.stack(
(
1 - two_s * (j * j + k * k),
two_s * (i * j - k * r),
two_s * (i * k + j * r),
two_s * (i * j + k * r),
1 - two_s * (i * i + k * k),
two_s * (j * k - i * r),
two_s * (i * k - j * r),
two_s * (j * k + i * r),
1 - two_s * (i * i + j * j),
),
axis=-1,
)
return o.reshape(quaternions.shape[:-1] + (3, 3))
def subtract_frame_transforms(
t01: np.ndarray, q01: np.ndarray, t02: np.ndarray = None, q02: np.ndarray = None
) -> tuple:
r"""Subtract transformations between two reference frames into a stationary frame.
It performs the following transformation operation: :math:`T_{12} = T_{01}^{-1} \times T_{02}`,
where :math:`T_{AB}` is the homogeneous transformation matrix from frame A to B.
Args:
t01: Position of frame 1 w.r.t. frame 0. Shape is (N, 3).
q01: Quaternion orientation of frame 1 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).
t02: Position of frame 2 w.r.t. frame 0. Shape is (N, 3).
Defaults to None, in which case the position is assumed to be zero.
q02: Quaternion orientation of frame 2 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).
Defaults to None, in which case the orientation is assumed to be identity.
Returns:
A tuple containing the position and orientation of frame 2 w.r.t. frame 1.
Shape of the arrays are (N, 3) and (N, 4) respectively.
"""
q10 = quat_inv(q01)
if q02 is not None:
q12 = quat_mul(q10, q02)
else:
q12 = q10
if t02 is not None:
t12 = quat_apply(q10, t02 - t01)
else:
t12 = quat_apply(q10, -t01)
return t12, q12
def transform_points(
points: np.ndarray, pos: np.ndarray = None, quat: np.ndarray = None
) -> np.ndarray:
r"""Transform input points in a given frame to a target frame.
This function transform points from a source frame to a target frame. The transformation is defined by the
position :math:`t` and orientation :math:`R` of the target frame in the source frame.
.. math::
p_{target} = R_{target} \times p_{source} + t_{target}
Args:
points: Points to transform. Shape is (N, P, 3) or (P, 3).
pos: Position of the target frame. Shape is (N, 3) or (3,).
Defaults to None, in which case the position is assumed to be zero.
quat: Quaternion orientation of the target frame in (w, x, y, z). Shape is (N, 4) or (4,).
Defaults to None, in which case the orientation is assumed to be identity.
Returns:
Transformed points in the target frame. Shape is (N, P, 3) or (P, 3).
Raises:
ValueError: If the inputs `points` is not of shape (N, P, 3) or (P, 3).
ValueError: If the inputs `pos` is not of shape (N, 3) or (3,).
ValueError: If the inputs `quat` is not of shape (N, 4) or (4,).
"""
points_batch = points.copy()
is_batched = points_batch.ndim == 3
if points_batch.ndim == 2:
points_batch = points_batch[np.newaxis] # (P, 3) -> (1, P, 3)
if points_batch.ndim != 3:
raise ValueError(f"Expected points to have dim = 2 or dim = 3: got shape {points.shape}")
if not (pos is None or pos.ndim == 1 or pos.ndim == 2):
raise ValueError(f"Expected pos to have dim = 1 or dim = 2: got shape {pos.shape}")
if not (quat is None or quat.ndim == 1 or quat.ndim == 2):
raise ValueError(f"Expected quat to have dim = 1 or dim = 2: got shape {quat.shape}")
# -- rotation
if quat is not None:
rot_mat = matrix_from_quat(quat)
if rot_mat.ndim == 2:
rot_mat = rot_mat[np.newaxis] # (3, 3) -> (1, 3, 3)
# (N, P, 3) -> (N, 3, P)
points_batch = np.transpose(points_batch, (0, 2, 1))
# Apply rotation: (N, 3, 3) @ (N, 3, P) -> (N, 3, P)
points_batch = np.matmul(rot_mat, points_batch)
# (N, 3, P) -> (N, P, 3)
points_batch = np.transpose(points_batch, (0, 2, 1))
# -- translation
if pos is not None:
if pos.ndim == 1:
pos = pos[np.newaxis, np.newaxis, :] # (3,) -> (1, 1, 3)
else:
pos = pos[:, np.newaxis, :] # (N, 3) -> (N, 1, 3)
points_batch = points_batch + pos
if not is_batched:
points_batch = points_batch.squeeze(0) # (1, P, 3) -> (P, 3)
return points_batch
@@ -0,0 +1,232 @@
"""Visualization utilities for the SRU navigation controller (ROS 2 port)."""
from collections import deque
import numpy as np
from geometry_msgs.msg import Point, PoseStamped, Quaternion, Vector3
from nav_msgs.msg import Path
from rclpy.time import Time
from std_msgs.msg import Header
from visualization_msgs.msg import Marker
from sru_nav_ros2 import constants
from sru_nav_ros2.utils import transform_points, yaw_quat
# ---------------------------------------------------------------------------
# Path (trajectory) visualization.
#
# ROS 2 ADDITION -- the ROS 1 blueprint had no path output at all. Nothing here
# is a "planned path": the policy is reactive and end-to-end, so there is no
# planner and no route to draw. What these two topics show is (a) where the
# robot has actually been and (b) which goal it is currently chasing.
# ---------------------------------------------------------------------------
PATH_PUBLISH_INTERVAL = 1.0 # seconds; also the trajectory sampling period
PATH_MAX_POINTS = 600 # trail cap (~10 min at 1 Hz); keeps the message small
class VisualizationManager:
"""Manages visualization markers for the navigation controller."""
def __init__(self, node=None):
# The `node` argument used to be dead weight ("retained for API parity,
# not used in ROS1"). Under ROS 2 it is genuinely needed: every marker
# stamp is produced through this node's clock.
self.node = node
# Travelled trajectory, in the odometry frame. Bounded, so publishing
# it stays cheap no matter how long the node runs.
self._trail = deque(maxlen=PATH_MAX_POINTS)
def _stamp_from_sec(self, sec):
"""Build a ``builtin_interfaces/msg/Time`` for an absolute float-seconds value.
ROS 2 counterpart of the ROS 1 global ``Time.from_sec()``. The numeric value
is preserved: the odom timestamp is converted as-is and is NOT replaced by
the current time. Only the clock type is taken from the injected node, so
the stamp stays on the same clock the node runs on.
"""
return Time(
seconds=float(sec),
clock_type=self.node.get_clock().clock_type,
).to_msg()
def publish_twist_marker(self, twist_msg, robot_odom_time, robot_frame_id, publisher):
if robot_frame_id is None:
return
marker = Marker()
marker.header = Header()
marker.header.stamp = self._stamp_from_sec(robot_odom_time)
marker.header.frame_id = robot_frame_id
marker.type = Marker.ARROW
marker.action = Marker.ADD
marker.id = constants.TWIST_MARKER_ID
start_point = Point(x=0.0, y=0.0, z=0.0)
end_point = Point(
x=twist_msg.linear.x * constants.TWIST_MARKER_SCALE,
y=twist_msg.linear.y * constants.TWIST_MARKER_SCALE,
z=0.0,
)
marker.points = [start_point, end_point]
marker.scale = Vector3(x=0.2, y=0.4, z=0.4)
marker.color.r = 0.0
marker.color.g = 0.0
marker.color.b = 1.0
marker.color.a = 0.8
marker.pose.orientation = Quaternion(w=1.0, x=0.0, y=0.0, z=0.0)
marker.frame_locked = False
publisher.publish(marker)
def publish_target_vector_marker(self, target_vec_b, robot_odom_time, robot_frame_id, publisher):
if robot_frame_id is None:
return
marker = Marker()
marker.header = Header()
marker.header.stamp = self._stamp_from_sec(robot_odom_time)
marker.header.frame_id = robot_frame_id
marker.type = Marker.ARROW
marker.action = Marker.ADD
marker.id = constants.TARGET_VECTOR_MARKER_ID
vec = target_vec_b.flatten()
start_point = Point(x=0.0, y=0.0, z=0.0)
end_point = Point(x=float(vec[0]), y=float(vec[1]), z=float(vec[2]))
marker.points = [start_point, end_point]
marker.scale = Vector3(x=0.1, y=0.2, z=0.2)
marker.pose.orientation = Quaternion(w=1.0, x=0.0, y=0.0, z=0.0)
marker.color.r = 0.0
marker.color.g = 1.0
marker.color.b = 0.0
marker.color.a = 0.5
marker.frame_locked = False
publisher.publish(marker)
def publish_moving_goal_marker(self, moving_goal_delta, robot_pos_w, robot_orientation_w,
robot_odom_time, map_frame_id, publisher):
if robot_pos_w is None or map_frame_id is None:
return
robot_pos = np.array(robot_pos_w, dtype=np.float32)
robot_ori = np.array(robot_orientation_w, dtype=np.float32)
robot_yaw_ori = yaw_quat(robot_ori)
moving_goal_pos = np.array(moving_goal_delta, dtype=np.float32)
moving_goal_pos_w = transform_points(
moving_goal_pos[np.newaxis],
robot_pos[np.newaxis],
robot_yaw_ori[np.newaxis],
)
marker = Marker()
marker.header = Header()
marker.header.stamp = self._stamp_from_sec(robot_odom_time)
marker.header.frame_id = map_frame_id
marker.type = Marker.ARROW
marker.action = Marker.ADD
marker.id = constants.MOVING_GOAL_MARKER_ID
start_point = Point(
x=float(moving_goal_pos_w[0, 0]),
y=float(moving_goal_pos_w[0, 1]),
z=float(moving_goal_pos_w[0, 2]) + 1.0,
)
end_point = Point(
x=float(moving_goal_pos_w[0, 0]),
y=float(moving_goal_pos_w[0, 1]),
z=float(moving_goal_pos_w[0, 2]),
)
marker.points = [start_point, end_point]
marker.scale = Vector3(x=0.3, y=0.6, z=0.6)
marker.color.r = 1.0
marker.color.g = 1.0
marker.color.b = 0.0
marker.color.a = 0.5
marker.pose.orientation = Quaternion(w=1.0, x=0.0, y=0.0, z=0.0)
marker.frame_locked = False
publisher.publish(marker)
def publish_waypoints_marker(self, waypoints_visualization, map_frame_id, publisher):
"""Publish recorded waypoints as a CUBE_LIST marker.
This is the one marker whose stamp genuinely means "now" (the ROS 1 port
used the global ``Time.now()`` here), so it reads the injected node's clock.
"""
if map_frame_id is None:
return
marker = Marker()
marker.header.stamp = self.node.get_clock().now().to_msg()
marker.header.frame_id = map_frame_id
marker.ns = 'recorded_waypoints'
marker.id = constants.WAYPOINTS_MARKER_ID
marker.type = Marker.CUBE_LIST
marker.action = Marker.ADD
marker.scale = Vector3(x=0.3, y=0.3, z=0.3)
marker.color.r = 0.0
marker.color.g = 1.0
marker.color.b = 0.0
marker.color.a = 1.0
marker.points = []
for waypoint in waypoints_visualization:
marker.points.append(Point(x=waypoint[0], y=waypoint[1], z=waypoint[2]))
publisher.publish(marker)
# -------------------------------------------------------------------
# Paths (ros2 addition -- see the note above the constants)
# -------------------------------------------------------------------
def publish_executed_path(self, robot_pos_w, map_frame_id, robot_odom_time, publisher):
"""Append the current pose to the travelled trajectory and republish it.
The trail is sampled once per call, so the caller's timer period is both
the sampling period and the publish period.
"""
if robot_pos_w is None or map_frame_id is None:
return
self._trail.append(tuple(float(v) for v in robot_pos_w))
publisher.publish(self._build_path(
list(self._trail), map_frame_id, robot_odom_time))
def publish_goal_path(self, robot_pos_w, goal_pos_w, map_frame_id, robot_odom_time, publisher):
"""Straight line from the robot to the goal it is currently chasing.
Two poses only, so it is cheap enough to refresh at the control rate.
"""
if robot_pos_w is None or goal_pos_w is None or map_frame_id is None:
return
publisher.publish(self._build_path(
[tuple(float(v) for v in robot_pos_w),
tuple(float(v) for v in goal_pos_w)],
map_frame_id, robot_odom_time))
def _build_path(self, points, frame_id, robot_odom_time):
path = Path()
path.header = Header()
path.header.stamp = self._stamp_from_sec(robot_odom_time)
path.header.frame_id = frame_id
for point in points:
pose = PoseStamped()
pose.header = path.header
pose.pose.position.x = point[0]
pose.pose.position.y = point[1]
pose.pose.position.z = point[2]
pose.pose.orientation.w = 1.0
path.poses.append(pose)
return path
@@ -0,0 +1,139 @@
"""Waypoint management for the SRU navigation controller (ROS 2 port).
This module is logger-agnostic: pass any object exposing .info/.warn/.warning/.error.
Under ROS 2 you pass the node's own logger, i.e. ``node.get_logger()``
(``rclpy.impl.rcutils_logger.RcutilsLogger``), which already provides all four
methods. The ROS 1 ``RospyLogger`` shim that wrapped the module-level loginfo /
logwarn helpers therefore has no counterpart here and was dropped.
"""
from collections import deque
class WaypointManager:
"""Manages waypoint recording, tracking, and playback."""
def __init__(self, logger):
self.logger = logger
self.recorded_waypoints = deque()
self.inversed_ordered_waypoints = deque()
self.waypoints_visualization = deque()
self.is_publish_waypoints_home = False
self.is_publish_waypoints_inversed = False
def record_waypoint(self, robot_pos_w):
if robot_pos_w is None:
self.logger.warn('Robot position is not available yet.')
return False
if len(self.recorded_waypoints) == 0 and len(self.inversed_ordered_waypoints) > 0:
self.inversed_ordered_waypoints.clear()
self.waypoints_visualization.clear()
self.logger.info('Clear the inversed waypoints, and visualization waypoints.')
self.recorded_waypoints.append(robot_pos_w)
self.inversed_ordered_waypoints.appendleft(robot_pos_w)
self.waypoints_visualization.append(robot_pos_w)
self.logger.info(
'Waypoint recorded: {}, total waypoints: {}'.format(
robot_pos_w, len(self.recorded_waypoints)
)
)
return True
def remove_last_waypoint(self):
removed_count = 0
if len(self.recorded_waypoints) > 0:
self.recorded_waypoints.pop()
removed_count += 1
self.logger.info(
'Removed last waypoint (home), total: {}'.format(len(self.recorded_waypoints))
)
if len(self.inversed_ordered_waypoints) > 0:
self.inversed_ordered_waypoints.popleft()
removed_count += 1
self.logger.info(
'Removed last waypoint (inversed), total: {}'.format(
len(self.inversed_ordered_waypoints)
)
)
if len(self.waypoints_visualization) > 0:
self.waypoints_visualization.pop()
removed_count += 1
self.logger.info(
'Removed last waypoint (visualization), total: {}'.format(
len(self.waypoints_visualization)
)
)
if (len(self.waypoints_visualization) < len(self.recorded_waypoints) or
len(self.waypoints_visualization) < len(self.inversed_ordered_waypoints)):
raise ValueError(
'The visualization waypoints is smaller than the recorded waypoints.'
)
if removed_count == 0:
self.logger.warn('No waypoints to remove.')
return removed_count > 0
def get_next_waypoint_home(self):
if self.recorded_waypoints:
return self.recorded_waypoints.pop()
return None
def get_next_waypoint_inversed(self):
if self.inversed_ordered_waypoints:
return self.inversed_ordered_waypoints.pop()
return None
def start_home_waypoint_sequence(self):
if len(self.recorded_waypoints) > 0:
self.is_publish_waypoints_home = True
return True
return False
def start_inversed_waypoint_sequence(self):
if len(self.inversed_ordered_waypoints) > 0:
self.is_publish_waypoints_inversed = True
return True
return False
def stop_home_waypoint_sequence(self):
self.is_publish_waypoints_home = False
def stop_inversed_waypoint_sequence(self):
self.is_publish_waypoints_inversed = False
def reset_visualization_if_complete(self):
if (not self.recorded_waypoints and not self.inversed_ordered_waypoints
and self.waypoints_visualization):
self.logger.info('All waypoints are published, reset visualization.')
self.waypoints_visualization.clear()
return True
return False
def re_add_aborted_waypoint(self, target_pos_w):
if self.is_publish_waypoints_home:
self.recorded_waypoints.append(target_pos_w)
self.logger.info('Goal aborted - re-adding current goal as a recorded (home) waypoint.')
if self.is_publish_waypoints_inversed:
self.inversed_ordered_waypoints.appendleft(target_pos_w)
self.logger.info(
'Goal aborted: reinserting the current goal as recorded (inversed) waypoint.'
)
def has_home_waypoints(self):
return len(self.recorded_waypoints) > 0
def has_inversed_waypoints(self):
return len(self.inversed_ordered_waypoints) > 0
def is_home_sequence_active(self):
return self.is_publish_waypoints_home
def is_inversed_sequence_active(self):
return self.is_publish_waypoints_inversed
@@ -0,0 +1,468 @@
#!/usr/bin/env python3
"""Sequential waypoint runner for sru_nav_ros2 (ROS 2 Humble).
Publishes a list of goals to /goal_pose one at a time, monitors the robot
odometry to decide when each goal is reached (or has timed out, or the robot
is stuck), then moves on to the next. After the last waypoint, optionally
returns to the pose captured at script start.
A waypoint may also carry a GOAL HEADING (the optional 4th number, in RADIANS,
odom frame). It is published on its own latched topic (`goal_yaw_topic`) as a
std_msgs/Float64, where NaN means "no heading requirement"; the navigation node
rotates in place to align after reaching the position. This runner additionally
waits for that heading before advancing, so it never walks a waypoint list
mid-rotation.
It does NOT touch the navigation node: it is purely an external client on top of
the existing /goal_pose + /goal_yaw + /odin1/odometry_highfreq contract.
Usage
-----
# YAML file
ros2 run sru_nav_ros2 waypoint_runner --file waypoints.yaml
# Command line (x,y[,z[,yaw]] tuples separated by spaces)
ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0 3,2 0,2"
# Only the LAST waypoint requires a heading: leave the earlier ones at x,y
ros2 run sru_nav_ros2 waypoint_runner --waypoints "1,0 2,0 3,0,0,1.5708"
YAML format
-----------
frame_id: odom
arrive_threshold: 0.75 # meters, XY distance to consider 'arrived'
settle_time: 1.5 # seconds the robot must stay within threshold
per_goal_timeout: 60.0 # seconds before giving up on a goal
stuck_window: 10.0 # seconds of trailing window for stuck check
stuck_displacement: 0.10 # meters; below this in `stuck_window` -> skip
republish_interval: 5.0 # seconds; re-publish the same goal periodically
return_home: true
goal_yaw_topic: /goal_yaw # std_msgs/Float64, radians
goal_yaw_tolerance: 0.0873 # radians (5 deg); match the node's parameter
goal_yaw_settle_time: 0.4 # seconds the heading must hold inside tolerance
waypoints:
- [3.0, 0.0, 0.0] # position only
- [3.0, 2.0, 0.0, 1.5708] # position + heading (rad)
"""
import argparse
import collections
import math
import sys
import time
import rclpy
import yaml
from geometry_msgs.msg import PoseStamped
from nav_msgs.msg import Odometry
from rclpy.node import Node
from rclpy.qos import DurabilityPolicy, QoSHistoryPolicy, QoSProfile
from rclpy.utilities import remove_ros_args
from scipy.spatial.transform import Rotation as R
from std_msgs.msg import Float64
# ---------------------------------------------------------------------------
# Defaults (mirror sru_nav_ros2/constants.py where applicable)
# ---------------------------------------------------------------------------
DEFAULTS = dict(
frame_id='odom',
arrive_threshold=0.75, # matches constants.ARRIVE_GOAL_THRESHOLD
settle_time=1.5,
per_goal_timeout=60.0,
stuck_window=10.0,
stuck_displacement=0.10,
republish_interval=5.0,
return_home=True,
odom_topic='/odin1/odometry_highfreq',
goal_topic='/goal_pose',
# Goal heading (ROS 2 addition). Published on its own latched topic, so a
# position-only goal stays exactly as it was before this feature existed.
goal_yaw_topic='/goal_yaw',
goal_yaw_tolerance=0.0873, # rad (+/- 5 deg), must match the node's
goal_yaw_settle_time=0.4, # s the heading must hold inside tolerance
)
# ---------------------------------------------------------------------------
# Parsing
# ---------------------------------------------------------------------------
def _parse_inline_waypoints(text):
"""Parse "x,y[,z[,yaw]] x,y[,z[,yaw]] ..." into list[list[float|None]].
The heading is the 4th number, in RADIANS, in the same frame as the position
(odom). A waypoint that omits it carries no heading and -- since the runner
publishes NaN for it -- the node simply does not rotate there. So "only the
last waypoint needs a heading" is expressed just by leaving the earlier ones
at 2 or 3 numbers: --waypoints "1,0 2,0 3,0,0,1.5708"
"""
out = []
if not text:
return out
for tok in text.split():
parts = tok.split(',')
if len(parts) not in (2, 3, 4):
raise ValueError(
"Bad waypoint '{}': expected 'x,y' / 'x,y,z' / 'x,y,z,yaw'".format(tok))
out.append([
float(parts[0]),
float(parts[1]),
float(parts[2]) if len(parts) >= 3 else 0.0,
float(parts[3]) if len(parts) == 4 else None,
])
return out
def _load_yaml(path):
with open(path, 'r') as f:
data = yaml.safe_load(f) or {}
if 'waypoints' not in data or not data['waypoints']:
raise ValueError("YAML '{}' has no 'waypoints' list.".format(path))
norm = []
for wp in data['waypoints']:
if len(wp) not in (2, 3, 4):
raise ValueError(
"Bad waypoint {} (need 2, 3 or 4 floats; the 4th is the goal "
"heading in radians).".format(wp))
x = float(wp[0]); y = float(wp[1])
z = float(wp[2]) if len(wp) >= 3 else 0.0
yaw = float(wp[3]) if len(wp) == 4 else None
norm.append([x, y, z, yaw])
data['waypoints'] = norm
return data
def build_config(args):
cfg = dict(DEFAULTS)
if args.file:
cfg.update({k: v for k, v in _load_yaml(args.file).items() if v is not None})
# Command-line overrides win over YAML
if args.waypoints:
cfg['waypoints'] = _parse_inline_waypoints(args.waypoints)
if args.frame_id is not None:
cfg['frame_id'] = args.frame_id
if args.timeout is not None:
cfg['per_goal_timeout'] = float(args.timeout)
if args.arrive_threshold is not None:
cfg['arrive_threshold'] = float(args.arrive_threshold)
if args.goal_yaw_tolerance is not None:
cfg['goal_yaw_tolerance'] = float(args.goal_yaw_tolerance)
if args.return_home is not None:
cfg['return_home'] = args.return_home
if 'waypoints' not in cfg or not cfg['waypoints']:
raise ValueError("No waypoints provided (use --file or --waypoints).")
return cfg
# ---------------------------------------------------------------------------
# Runner
# ---------------------------------------------------------------------------
class WaypointRunner(Node):
def __init__(self, cfg, odom_wait_timeout=30.0):
super().__init__('waypoint_runner')
self.cfg = cfg
self._pose = None # latest (x, y, z, t)
self._pose_history = collections.deque() # entries: (t, x, y)
self._home = None # (x, y, z) captured at first odom
self._yaw = None # latest yaw [rad], odom frame
self._log_config()
# ROS 1 used queue_size=1, latch=True. `latch` has no direct ROS 2
# equivalent; the idiomatic replacement is a TRANSIENT_LOCAL durability
# publisher. (It only matters for a late-joining TRANSIENT_LOCAL
# subscriber; the navigation node subscribes VOLATILE, exactly like the
# ROS 1 node did, so live-delivery behaviour is unchanged.)
goal_qos = QoSProfile(
history=QoSHistoryPolicy.KEEP_LAST,
depth=1,
durability=DurabilityPolicy.TRANSIENT_LOCAL,
)
self.goal_pub = self.create_publisher(PoseStamped, cfg['goal_topic'], goal_qos)
# Goal heading travels on its own latched topic. A position-only goal
# therefore publishes NaN here, which the node reads as "no heading
# requirement" -- that is what keeps backward compatibility exact.
self.goal_yaw_pub = self.create_publisher(
Float64, cfg['goal_yaw_topic'], goal_qos)
self.odom_sub = self.create_subscription(
Odometry, cfg['odom_topic'], self._odom_cb, 20)
self.get_logger().info(
"waypoint_runner: waiting for first odom on '{}' ...".format(
cfg['odom_topic']))
self._wait_for_odom(timeout=odom_wait_timeout)
self._home = (self._pose[0], self._pose[1], self._pose[2])
self.get_logger().info(
'waypoint_runner: home pose captured at x={:.3f} y={:.3f} z={:.3f}'.format(
*self._home))
# Give the publisher a moment so the first goal isn't lost.
time.sleep(0.5)
# --------------------------------------------------------------- logging
def _log_config(self):
self.get_logger().info('waypoint_runner config:')
for k in ('frame_id', 'arrive_threshold', 'settle_time',
'per_goal_timeout', 'stuck_window', 'stuck_displacement',
'republish_interval', 'return_home', 'odom_topic', 'goal_topic',
'goal_yaw_topic', 'goal_yaw_tolerance', 'goal_yaw_settle_time'):
self.get_logger().info(' {} = {!r}'.format(k, self.cfg[k]))
self.get_logger().info(
' waypoints ({}):'.format(len(self.cfg['waypoints'])))
for i, wp in enumerate(self.cfg['waypoints'], 1):
# The yaw is echoed in degrees as well: it is radians on the wire,
# and seeing both makes a unit slip obvious at a glance.
yaw_txt = ('none' if wp[3] is None
else '{:.4f} rad ({:.1f} deg)'.format(wp[3], math.degrees(wp[3])))
self.get_logger().info(
' {:2d}: ({:.3f}, {:.3f}, {:.3f}) yaw={}'.format(
i, wp[0], wp[1], wp[2], yaw_txt))
# --------------------------------------------------------------- callbacks
def _odom_cb(self, msg):
# ROS 1 read the stamp as float seconds and fell back to the current ROS
# time when it was zero; ROS 2 spells the two integer fields sec/nanosec
# and reads "now" from the node clock.
stamp = msg.header.stamp
t = stamp.sec + stamp.nanosec * 1e-9
if not t:
t = self.get_clock().now().nanoseconds * 1e-9
p = msg.pose.pose.position
self._pose = (p.x, p.y, p.z, t)
# Base heading in the odom frame, needed for the goal-heading check.
q = msg.pose.pose.orientation
self._yaw = R.from_quat([q.x, q.y, q.z, q.w]).as_euler('zyx')[0]
self._pose_history.append((t, p.x, p.y))
# Trim history to a bit more than stuck_window
cutoff = t - max(self.cfg['stuck_window'] * 2.0, 5.0)
while self._pose_history and self._pose_history[0][0] < cutoff:
self._pose_history.popleft()
def _spin_once(self, timeout_sec):
"""Pump callbacks for up to `timeout_sec`.
`rclpy.spin()` is single-threaded, so the scripted loop below drives the
executor itself; that also replaces the ROS 1 fixed-rate sleep as the loop
pacing mechanism.
"""
rclpy.spin_once(self, timeout_sec=timeout_sec)
def _wait_for_odom(self, timeout):
t0 = time.time()
while rclpy.ok() and self._pose is None:
if time.time() - t0 > timeout:
raise RuntimeError(
"No odometry received on '{}' within {:.1f}s.".format(
self.cfg['odom_topic'], timeout))
self._spin_once(0.05)
# ------------------------------------------------------------------ goals
def _publish_goal(self, wp):
"""Publish a waypoint: position on the goal topic, heading on the yaw topic.
Both are latched and are sent together so the node can pair them; a
heading-less waypoint sends NaN, which means "no heading requirement".
"""
msg = PoseStamped()
msg.header.stamp = self.get_clock().now().to_msg()
msg.header.frame_id = self.cfg['frame_id']
msg.pose.position.x = float(wp[0])
msg.pose.position.y = float(wp[1])
msg.pose.position.z = float(wp[2])
msg.pose.orientation.w = 1.0
self.goal_pub.publish(msg)
yaw_msg = Float64()
yaw_msg.data = float('nan') if wp[3] is None else float(wp[3])
self.goal_yaw_pub.publish(yaw_msg)
def _xy_dist(self, ax, ay, bx, by):
return math.hypot(ax - bx, ay - by)
def _displacement_in_window(self, window):
"""Max XY distance between any two samples within trailing `window` s."""
# Snapshot first: the odometry callback may append/popleft while we
# iterate, which raises "deque mutated during iteration".
snapshot = list(self._pose_history)
if not snapshot:
return 0.0
now = snapshot[-1][0]
cutoff = now - window
pts = [(x, y) for (t, x, y) in snapshot if t >= cutoff]
if len(pts) < 2:
return 0.0
xs = [p[0] for p in pts]; ys = [p[1] for p in pts]
# Bounding box diagonal is a cheap, monotone proxy for "did it move".
return math.hypot(max(xs) - min(xs), max(ys) - min(ys))
def _run_goal(self, idx, total, wp, label):
cfg = self.cfg
xyz = wp[:3]
yaw_goal = wp[3]
self.get_logger().info(
'\033[96m[{}/{} {}] -> x={:.3f} y={:.3f} z={:.3f}{}\033[0m'.format(
idx, total, label, xyz[0], xyz[1], xyz[2],
'' if yaw_goal is None
else ' yaw={:.4f} rad ({:.1f} deg)'.format(
yaw_goal, math.degrees(yaw_goal))))
self._publish_goal(wp)
t_start = time.time()
t_last_pub = t_start
within_since = None
while rclpy.ok():
now = time.time()
elapsed = now - t_start
# 1) Timeout
if elapsed > cfg['per_goal_timeout']:
self.get_logger().warn(
'[{}/{} {}] TIMEOUT after {:.1f}s; skipping.'.format(
idx, total, label, elapsed))
return 'timeout'
# 2) Stuck check (only after the window has elapsed)
if elapsed > cfg['stuck_window']:
disp = self._displacement_in_window(cfg['stuck_window'])
if disp < cfg['stuck_displacement']:
self.get_logger().warn(
'[{}/{} {}] STUCK (disp={:.3f}m < {:.3f}m in last {:.1f}s); '
'skipping.'.format(
idx, total, label, disp, cfg['stuck_displacement'],
cfg['stuck_window']))
return 'stuck'
# 3) Arrived? Position always; heading too when this waypoint asked
# for one. The node rotates in place after reaching the position,
# so waiting for the heading here is what keeps the runner from
# advancing to the next waypoint mid-rotation.
x, y, _z, _t = self._pose
d = self._xy_dist(x, y, xyz[0], xyz[1])
pos_ok = d <= cfg['arrive_threshold']
yaw_err = None
yaw_ok = True
if yaw_goal is not None:
if self._yaw is None:
yaw_ok = False
else:
yaw_err = math.atan2(math.sin(yaw_goal - self._yaw),
math.cos(yaw_goal - self._yaw))
yaw_ok = abs(yaw_err) <= cfg['goal_yaw_tolerance']
if pos_ok and yaw_ok:
if within_since is None:
within_since = now
elif (now - within_since) >= cfg['settle_time']:
detail = 'd={:.2f}m'.format(d)
if yaw_err is not None:
detail += ', yaw_err={:.1f}deg'.format(math.degrees(yaw_err))
self.get_logger().info(
'\033[92m[{}/{} {}] ARRIVED ({}, settled {:.1f}s)'
'\033[0m'.format(idx, total, label, detail, cfg['settle_time']))
return 'arrived'
else:
within_since = None
# 4) Periodic re-publish (protects against missed first publish)
if (cfg['republish_interval'] > 0
and (now - t_last_pub) >= cfg['republish_interval']):
self._publish_goal(wp)
t_last_pub = now
self.get_logger().info(
'[{}/{} {}] re-published goal (d={:.2f}m, t={:.1f}s)'.format(
idx, total, label, d, elapsed),
throttle_duration_sec=5.0)
self._spin_once(0.1)
return 'shutdown'
def run(self):
cfg = self.cfg
wps = list(cfg['waypoints'])
if cfg['return_home']:
# Home carries no heading: returning is a pure position goal.
wps.append([self._home[0], self._home[1], self._home[2], None])
total = len(wps)
results = []
for i, wp in enumerate(wps, start=1):
label = 'HOME' if (cfg['return_home'] and i == total) else 'WP'
res = self._run_goal(i, total, wp, label)
results.append((i, label, wp, res))
if not rclpy.ok():
break
# Summary
self.get_logger().info(
'\033[95m===== waypoint_runner summary =====\033[0m')
for i, label, wp, res in results:
yaw_txt = 'none' if wp[3] is None else '{:.1f}deg'.format(
math.degrees(wp[3]))
self.get_logger().info(
' {:2d}/{} {} ({:.2f}, {:.2f}, {:.2f}) yaw={} -> {}'.format(
i, total, label, wp[0], wp[1], wp[2], yaw_txt, res))
self.get_logger().info(
'\033[95m===================================\033[0m')
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def parse_args(argv):
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('--file', '-f', type=str, default=None,
help='YAML file with waypoints and (optional) parameters.')
p.add_argument('--waypoints', '-w', type=str, default=None,
help='Space-separated "x,y[,z[,yaw]]" tuples (overrides YAML). '
'The optional 4th number is a goal heading in RADIANS.')
p.add_argument('--frame-id', type=str, default=None,
help="Goal frame_id (default 'odom').")
p.add_argument('--timeout', type=float, default=None,
help='Per-goal timeout in seconds.')
p.add_argument('--arrive-threshold', type=float, default=None,
help='XY arrival threshold in meters.')
p.add_argument('--goal-yaw-tolerance', type=float, default=None,
help='Heading tolerance in RADIANS for waypoints that carry a '
'yaw (default 0.0873 = 5 deg). Must match the node\'s '
'goal_yaw_tolerance.')
g = p.add_mutually_exclusive_group()
g.add_argument('--return-home', dest='return_home', action='store_true',
default=None, help='Append start pose as final goal.')
g.add_argument('--no-return-home', dest='return_home', action='store_false',
help='Do not return to start pose after last waypoint.')
return p.parse_args(argv)
def main(args=None):
# `ros2 run` / launch may append ROS-specific arguments (`--ros-args ...`);
# strip them before argparse sees them. This replaces the ROS 1
# argument-filtering helper.
argv = sys.argv if args is None else args
script_argv = remove_ros_args(argv)[1:]
try:
cfg = build_config(parse_args(script_argv))
except (ValueError, OSError) as exc:
sys.stderr.write('[waypoint_runner] config error: {}\n'.format(exc))
sys.exit(2)
rclpy.init(args=argv)
runner = None
try:
runner = WaypointRunner(cfg)
runner.run()
except KeyboardInterrupt:
pass
finally:
if runner is not None:
runner.destroy_node()
if rclpy.ok():
rclpy.shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1,63 @@
# =============================================================================
# chassis_serial_node — 运行参数(R2 底盘串口桥)
#
# 本文件是本节点所有可调项的**唯一真源**。launch/chassis_serial.launch.py 里 port 的
# launch 参数默认值就是从这里反读的,因此 launch 文件不可能再与它冲突。ROS 2 中
# parameters 列表按顺序应用、后者胜,所以 launch 文件只可能覆盖 port,且只在你显式
# 传 port:=... 时才发生。
#
# install 出来的是**拷贝**(setup.py 用拷贝方式安装 config/*.yaml),所以改 src/ 下的
# 本文件必须重新编译才生效。想改完即用、免重建,就把它直接指给节点:
# ros2 launch techx_r2_chassis_control chassis_serial.launch.py \
# params_file:=$HOME/sru_ws/src/techx_r2_chassis_control/config/chassis_serial.yaml
# =============================================================================
chassis_serial_node:
ros__parameters:
# 串口设备。两种命名风格**只能选一种**,并与你的 udev 规则保持一致
# —— 本包不自带 .rules 文件:
# /dev/ttyUSB0 内核原始名;与枚举顺序有关,重启或插入其他 USB 串口设备后
# 可能改名
# /dev/r2_chassis 绑定到适配器序列号的 udev 稳定别名(需你自建规则)
# 请在真机上核实:这两个路径在裸开发机上都不存在,且节点打不开设备时会直接抛错。
port: /dev/ttyUSB0
baudrate: 115200
# 这个值会传给 serial.Serial(),但节点**从不回读**任何帧
# (见 protocol.py:只做 上位机 -> STM32 单向),所以它对行为完全无影响。
serial_timeout_sec: 0.02
# 下行发帧率。**固定定时器**:每隔 1/velocity_rate_hz 秒就写一帧,与 /cmd_vel 到达
# 快慢无关,因此数值没变时也在重发同样的字节。带宽不是瓶颈 —— 每帧 10 B,按此速率
# 只占 115200 8N1 的约 2.6%。
velocity_rate_hz: 30.0
# /cmd_vel 静默超过这么久,就进入 stale 分支(见下方 send_zero_on_timeout)。
# 注意:上游策略发 /cmd_vel 的实际速率只有约 1.4-1.7 Hz(周期约 0.66 s,受 Odin
# 深度流限制),**比本超时更长**。配合 send_zero_on_timeout: true,就意味着每
# 0.66 s 里约有 0.46 s 在发零速帧 —— 轮子会走走停停。请在真机上核实;若确实如此,
# 应把它放宽到 >= 1.0。
cmd_vel_timeout_sec: 0.2
# true = stale 期间持续发零速帧把链路撑住(启动瞬间也算 stale,因为
# _last_cmd_time 初值为 0.0)。
# false = stale 期间完全不发,启动阶段同样不发。
# 两种取值下,下位机都**必须**实现自己的超时:本节点写失败的那一帧,与 STM32
# 从未收到的那一帧,是无法区分的。
send_zero_on_timeout: true
# 输出限幅,作用在 /cmd_vel 各分量**乘 1000 转线上格式之前**。
# 现值已低于上游策略能给出的值,因而几乎每一步都在生效:
# 纯策略、摇杆回中 : |vx| <= 0.6, |wz| <= 0.6
# 策略 + 摇杆推到底 : |vx| <= 2.7, |wz| <= 2.2
# 截断是**静默**的 —— 策略节点收不到任何反馈,无从察觉。
# 这是策略选择而非协议限制:线上格式本身能表达 ±32.767(int16 × 1000)。
max_vx_m_s: 0.5
max_vy_m_s: 0.5
max_wz_rad_s: 0.5
# true = 30 Hz 每帧打一行 INFO,含完整十六进制负载。
# 按默认速率会非常吵;只在调试协议时打开。
log_velocity_frames: true
@@ -0,0 +1,559 @@
# -*- coding: utf-8 -*-
"""生成本包的串口协议 PDF 说明(下位机接收模块对接用)。
用法:
source $WS/venv/bin/activate
python src/techx_r2_chassis_control/docs/build_protocol_pdf.py
依赖:reportlab(已在 $WS/venv 内)+ 系统中文字体 arphic/uming.ttc。
示例帧与 CRC 全部由 ../techx_r2_chassis_control/protocol.py 现算,保证与代码一致。
注意(踩过的坑):
1. 正文里的减号不要用 U+2212(−),UMing 没有该字形,会渲染成空白框;用 ASCII 连字符。
2. 代码块必须做 HTML 转义,否则代码里的 "<h" 会被 reportlab 当成标签吃掉。
3. 代码块字体是 Courier,不含中文字形,注释一律用英文,中文会变成黑块。
"""
from __future__ import annotations
import os
import sys
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import mm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (
BaseDocTemplate,
Frame,
HRFlowable,
KeepTogether,
PageBreak,
PageTemplate,
Paragraph,
Spacer,
Table,
TableStyle,
)
HERE = os.path.dirname(os.path.abspath(__file__))
PKG = os.path.join(os.path.dirname(HERE), "techx_r2_chassis_control")
sys.path.insert(0, PKG)
import protocol as P # noqa: E402
OUT_PDF = os.path.join(HERE, "R2底盘串口协议_v2.pdf")
CJK_FONT_PATH = "/usr/share/fonts/truetype/arphic/uming.ttc"
CJK_SUBFONT_INDEX = 0 # 0 = AR PL UMing CN
CJK = "CJK"
MONO = "Courier"
INK = colors.HexColor("#1A1A1A")
MUTED = colors.HexColor("#5F5E5A")
ACCENT = colors.HexColor("#0F4C81")
RULE = colors.HexColor("#C9D3DC")
CODE_BG = colors.HexColor("#F3F4F3")
WARN_BG = colors.HexColor("#FBEFE6")
WARN_LINE = colors.HexColor("#C0733A")
OK_BG = colors.HexColor("#EDF4E9")
OK_LINE = colors.HexColor("#5A8A3C")
CELL_HDR = colors.HexColor("#0F4C81")
CELL_ALT = colors.HexColor("#F7F9FB")
def register_fonts() -> None:
pdfmetrics.registerFont(TTFont(CJK, CJK_FONT_PATH, subfontIndex=CJK_SUBFONT_INDEX))
pdfmetrics.registerFontFamily(CJK, normal=CJK, bold=CJK, italic=CJK, boldItalic=CJK)
# ---------------------------------------------------------------- styles
def build_styles() -> dict:
s = {}
s["title"] = ParagraphStyle(
"title", fontName=CJK, fontSize=20, leading=27, textColor=ACCENT, spaceAfter=4, alignment=TA_LEFT
)
s["subtitle"] = ParagraphStyle(
"subtitle", fontName=CJK, fontSize=10.5, leading=16, textColor=MUTED, spaceAfter=2
)
s["h1"] = ParagraphStyle(
"h1", fontName=CJK, fontSize=13.5, leading=19, textColor=ACCENT, spaceBefore=13, spaceAfter=5
)
s["h2"] = ParagraphStyle(
"h2", fontName=CJK, fontSize=11.5, leading=17, textColor=INK, spaceBefore=9, spaceAfter=3
)
s["body"] = ParagraphStyle(
"body", fontName=CJK, fontSize=9.8, leading=15.6, textColor=INK, spaceAfter=4
)
s["bullet"] = ParagraphStyle(
"bullet", parent=s["body"], leftIndent=11, bulletIndent=2, spaceAfter=1.5
)
s["code"] = ParagraphStyle(
"code", fontName=MONO, fontSize=8.1, leading=11.6, textColor=INK
)
s["cell"] = ParagraphStyle(
"cell", fontName=CJK, fontSize=8.8, leading=12.6, textColor=INK
)
s["cellh"] = ParagraphStyle(
"cellh", fontName=CJK, fontSize=8.8, leading=12.6, textColor=colors.white
)
s["cellc"] = ParagraphStyle(
"cellc", fontName=MONO, fontSize=8.6, leading=12.6, textColor=INK
)
s["byteidx"] = ParagraphStyle(
"byteidx", fontName=CJK, fontSize=7.6, leading=10, textColor=MUTED, alignment=TA_CENTER
)
s["bytename"] = ParagraphStyle(
"bytename", fontName=CJK, fontSize=9, leading=12, textColor=colors.white, alignment=TA_CENTER
)
s["footnote"] = ParagraphStyle(
"footnote", fontName=CJK, fontSize=8.4, leading=13, textColor=MUTED, spaceAfter=3
)
return s
STYLES = build_styles()
def esc_code(text: str) -> str:
"""代码块转义:先转义 HTML 实体,再保留空格与换行。"""
text = text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
return text.replace("\n", "<br/>").replace(" ", "&nbsp;")
def code_block(text: str, width: float):
inner = Paragraph(esc_code(text), STYLES["code"])
return Table([[inner]], colWidths=[width],
style=TableStyle([
("BACKGROUND", (0, 0), (-1, -1), CODE_BG),
("BOX", (0, 0), (-1, -1), 0.5, RULE),
("LEFTPADDING", (0, 0), (-1, -1), 4.5 * mm),
("RIGHTPADDING", (0, 0), (-1, -1), 4.5 * mm),
("TOPPADDING", (0, 0), (-1, -1), 3.2 * mm),
("BOTTOMPADDING", (0, 0), (-1, -1), 3.2 * mm),
]))
def note(text: str, width: float, kind: str = "warn"):
bg, line = (WARN_BG, WARN_LINE) if kind == "warn" else (OK_BG, OK_LINE)
return Table([[Paragraph(text, STYLES["cell"])]], colWidths=[width],
style=TableStyle([
("BACKGROUND", (0, 0), (-1, -1), bg),
("LINEBEFORE", (0, 0), (0, -1), 2.2, line),
("LEFTPADDING", (0, 0), (-1, -1), 4 * mm),
("RIGHTPADDING", (0, 0), (-1, -1), 4 * mm),
("TOPPADDING", (0, 0), (-1, -1), 3 * mm),
("BOTTOMPADDING", (0, 0), (-1, -1), 3 * mm),
]))
def data_table(rows, col_widths, code_cols=(), align_center=()):
body = []
for r_i, row in enumerate(rows):
out = []
for c_i, cell in enumerate(row):
if isinstance(cell, str):
st = STYLES["cellh"] if r_i == 0 else (STYLES["cellc"] if c_i in code_cols else STYLES["cell"])
out.append(Paragraph(cell, st))
else:
out.append(cell)
body.append(out)
t = Table(body, colWidths=col_widths, repeatRows=1)
t.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), CELL_HDR),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, CELL_ALT]),
("GRID", (0, 0), (-1, -1), 0.4, RULE),
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("LEFTPADDING", (0, 0), (-1, -1), 2.6 * mm),
("RIGHTPADDING", (0, 0), (-1, -1), 2.6 * mm),
("TOPPADDING", (0, 0), (-1, -1), 2.0 * mm),
("BOTTOMPADDING", (0, 0), (-1, -1), 2.0 * mm),
*[("ALIGN", (c, 1), (c, -1), "CENTER") for c in align_center],
]))
return t
# ---------------------------------------------------------------- examples
def frames():
ex = [
("静止(停车)", 0.0, 0.0, 0.0),
("前进", 0.25, 0.0, 0.0),
("后退", -0.20, 0.0, 0.0),
("左横移", 0.0, 0.15, 0.0),
("原地右转", 0.0, 0.0, -0.30),
("斜向 + 转向", 0.10, 0.05, 0.20),
("极限值(前进满速)", 2.5, 0.0, 0.0),
("极限值(旋转满速)", 0.0, 0.0, 1.5),
]
out = []
for name, vx, vy, wz in ex:
raw = P.pack_velocity_frame(vx * P.VX_SCALE, vy * P.VY_SCALE, wz * P.OMEGA_SCALE)
out.append((name, vx, vy, wz, raw))
return out
def main() -> None:
register_fonts()
doc = BaseDocTemplate(
OUT_PDF,
pagesize=A4,
leftMargin=17 * mm,
rightMargin=17 * mm,
topMargin=16 * mm,
bottomMargin=16 * mm,
title="R2 底盘串口通信协议 v2",
author="techx_r2_chassis_control",
subject="下位机(STM32)接收模块实现说明",
)
W = doc.width
def on_page(canv, d):
canv.saveState()
canv.setStrokeColor(RULE)
canv.setLineWidth(0.5)
y = A4[1] - 12 * mm
canv.line(doc.leftMargin, y, A4[0] - doc.rightMargin, y)
canv.setFont(CJK, 7.8)
canv.setFillColor(MUTED)
canv.drawString(doc.leftMargin, y + 2.6 * mm, "R2 底盘串口通信协议 v2 · 下位机接收模块实现说明")
canv.drawRightString(A4[0] - doc.rightMargin, y + 2.6 * mm, "第 %d 页" % d.page)
canv.line(doc.leftMargin, 12 * mm, A4[0] - doc.rightMargin, 12 * mm)
canv.restoreState()
doc.addPageTemplates([PageTemplate(
id="main",
frames=[Frame(doc.leftMargin, doc.bottomMargin, W, doc.height, id="f")],
onPage=on_page)])
F = []
add = F.append
def h1(t):
add(Paragraph(t, STYLES["h1"]))
def h2(t):
add(Paragraph(t, STYLES["h2"]))
def para(t):
add(Paragraph(t, STYLES["body"]))
def bullets(items, numbered=False):
for i, t in enumerate(items):
add(Paragraph(t, STYLES["bullet"], bulletText=("%d." % (i + 1)) if numbered else "·"))
# ------------------------------------------------------------ 封面
add(Paragraph("R2 底盘串口通信协议 v2", STYLES["title"]))
add(Paragraph("下位机(STM32)接收模块实现说明 —— 上位机到 下位机 单向速度指令", STYLES["subtitle"]))
add(HRFlowable(width="100%", thickness=1.4, color=ACCENT, spaceBefore=5, spaceAfter=7))
add(data_table([
["项目", "内容"],
["协议版本", "v2(定长 10 字节,只发速度指令)"],
["上位机实现", "ROS 2 包 techx_r2_chassis_control,节点 chassis_serial_node"],
["通信方向", "上位机 → 下位机,单向。下位机无需回包,协议不含任何上行帧"],
["文档用途", "供下位机开发者实现接收 / 校验 / 解析模块;帧示例与 CRC 由上位机代码现算,可直接作测试向量"],
], [24 * mm, W - 24 * mm]))
add(Spacer(1, 6))
add(note(
"一句话总结:上位机每 33 ms 发一帧 10 字节数据,帧内就是 vx、vy、omega 三个 int16 小端数值加一个 CRC16。"
"下位机要做的事只有三件——<b>按 10 字节切帧</b>、<b>校验 CRC</b>、<b>把三个数取出来驱动电机</b>;"
"另外建议加一条「超时未收到合法帧就停车」的兜底逻辑。", W, kind="ok"))
add(Spacer(1, 3))
# ------------------------------------------------------------ 1
h1("1. 概述")
para("上位机运行 ROS 2 导航 / 遥控栈,把最终速度指令发布在 <font face='%s'>/cmd_vel</font>"
"(geometry_msgs/Twist)话题上。本节点订阅该话题,取出线速度 x、线速度 y、角速度 z 三个分量,"
"换算成整数后按本协议打包,经串口写入下位机。整条链路是单向的:上位机只发,从不读串口,"
"因此协议里没有应答、没有序号、没有回读状态。" % MONO)
para("下位机侧要实现的收帧逻辑,本质是一个「固定长度 + 帧头 + CRC」的字节流解析器。需要注意的是:"
"帧头 <font face='%s'>AA 55</font> 会<b>偶然</b>出现在数据区里(速度值恰好为 0x55AA 或 0xAA55 时),"
"所以不能靠搜索帧头来切帧——必须以「10 字节固定帧 + CRC 校验通过」作为唯一的帧确认条件。"
"这一点在第 6 节展开。" % MONO)
# ------------------------------------------------------------ 2
h1("2. 物理层参数")
add(data_table([
["参数", "取值", "说明"],
["波特率", "115200 bps", "可通过上位机参数 baudrate 修改,下位机需保持一致"],
["数据位 / 校验 / 停止位", "8 / None / 1", "即 8N1,无奇偶校验"],
["流控", "无", "软件与硬件流控都不使用"],
["电平", "按硬件设计", "上位机侧通过 USB-TTL 适配器转为串口设备节点(默认 /dev/r2_chassis)"],
["帧率", "默认 30 Hz", "即约 33 ms 一帧;上位机参数 velocity_rate_hz 可调"],
["链路方向", "上位机 → 下位机", "下位机发回的任何字节上位机都不会读取,请勿依赖上行通道"],
], [38 * mm, 32 * mm, W - 70 * mm]))
# ------------------------------------------------------------ 3
h1("3. 帧结构(定长 10 字节)")
para("所有多字节数值均为<b>小端</b>(little-endian,低字节在前)。")
add(data_table([
["偏移", "长度", "字段", "类型", "单位", "说明"],
["0", "2", "header", "uint8[2]", "—", "固定 0xAA 0x55"],
["2", "2", "vx", "int16 LE", "mm/s", "机体坐标系前后方向,前进为正"],
["4", "2", "vy", "int16 LE", "mm/s", "机体坐标系左右方向,左移为正"],
["6", "2", "omega", "int16 LE", "mrad/s", "绕 Z 轴角速度,逆时针(左转)为正"],
["8", "2", "crc16", "uint16 LE", "—", "CRC16-MODBUS,覆盖 byte0 ~ byte7"],
], [14 * mm, 14 * mm, 20 * mm, 21 * mm, 17 * mm, W - 86 * mm], code_cols=(2,), align_center=(0, 1, 4)))
add(Spacer(1, 4))
cells = [("byte 0-1", "AA 55"), ("byte 2-3", "vx"), ("byte 4-5", "vy"),
("byte 6-7", "omega"), ("byte 8-9", "crc16")]
widths = [22 * mm, 25 * mm, 25 * mm, 30 * mm, 30 * mm]
scale = (W - 8 * mm) / sum(widths)
widths = [w * scale for w in widths]
bd = Table([[Paragraph(c[0], STYLES["byteidx"]) for c in cells],
[Paragraph(c[1], STYLES["bytename"]) for c in cells]], colWidths=widths)
bd.setStyle(TableStyle([
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("TOPPADDING", (0, 0), (-1, 0), 1.2 * mm),
("BOTTOMPADDING", (0, 0), (-1, 0), 0.8 * mm),
("TOPPADDING", (0, 1), (-1, 1), 0.8 * mm),
("BOTTOMPADDING", (0, 1), (-1, 1), 1.6 * mm),
("LEFTPADDING", (0, 0), (-1, -1), 1.6 * mm),
("RIGHTPADDING", (0, 0), (-1, -1), 1.6 * mm),
("BACKGROUND", (0, 1), (0, 1), colors.HexColor("#5F5E5A")),
("BACKGROUND", (1, 1), (3, 1), colors.HexColor("#185FA5")),
("BACKGROUND", (4, 1), (4, 1), colors.HexColor("#993C1D")),
("BOX", (0, 1), (0, 1), 0.6, colors.white),
("BOX", (1, 1), (3, 1), 0.6, colors.white),
("BOX", (4, 1), (4, 1), 0.6, colors.white),
]))
add(KeepTogether([bd, Spacer(1, 3),
Paragraph("图 1 帧字节布局(灰色 = 帧头,蓝色 = 速度数据区,橙色 = 校验)",
STYLES["footnote"])]))
# ------------------------------------------------------------ 4
h1("4. 字段语义与数值换算")
para("三个字段都是 int16(-32768 ~ 32767),单位分别为 mm/s、mm/s、mrad/s,即「米每秒 × 1000」"
"和「弧度每秒 × 1000」,全部靠 1000 这一个比例常数换算,下位机侧反算则是除以 1000。"
"符号约定与 geometry_msgs/Twist 一致。")
add(data_table([
["字段", "上位机换算(→ 下发值)", "下位机反算", "实际上限", "int16 满量程"],
["vx", "mm/s = round(vx_m_s × 1000)", "vx_m_s = vx / 1000.0", "±2500", "±32767"],
["vy", "mm/s = round(vy_m_s × 1000)", "vy_m_s = vy / 1000.0", "±2500", "±32767"],
["omega", "mrad/s = round(wz_rad_s × 1000)", "wz_rad_s = omega / 1000.0", "±1500", "±32767"],
], [13 * mm, 66 * mm, 52 * mm, 18 * mm, 27 * mm], code_cols=(1, 2), align_center=(3, 4)))
add(Spacer(1, 3))
add(Paragraph("实际上限指上位机下发前的限幅:vx/vy 为 ±2500(±2.5 m/s),omega 为 ±1500(±1.5 rad/s),"
"下位机收到的数值不会超出该范围;仍建议下位机做一次范围钳制作为防御性处理。",
STYLES["footnote"]))
# ------------------------------------------------------------ 5
h1("5. CRC16-MODBUS 校验")
para("校验算法为标准 CRC16-MODBUS:多项式 0x8005(反射形式 0xA001),初值 0xFFFF,"
"输入输出都不做取反,也没有最终异或。计算范围是 <b>byte0 ~ byte7</b>(帧头 + 数据),"
"算出的 16 位结果以小端写入 byte8、byte9(低字节在前)。")
h2("5.1 接收端校验要点")
bullets([
"先按小端把 byte8、byte9 拼成期望值:<font face='%s'>expect = byte8 | (byte9 &lt;&lt; 8)</font>" % MONO,
"再对前 8 字节算 CRC,与 expect 比较,不相等即丢帧",
"多项式、初值、位序三者任一不同都会和上位机对不上,请直接使用下面的参考实现",
])
add(KeepTogether([
Paragraph("5.2 C 参考实现(可直接抄进 STM32)", STYLES["h2"]),
code_block(
"/* CRC16-MODBUS: poly=0xA001, init=0xFFFF, no reflect in/out, no final xor */\n"
"uint16_t crc16_modbus(const uint8_t *buf, uint16_t len)\n"
"{\n"
" uint16_t crc = 0xFFFF;\n"
" for (uint16_t i = 0; i < len; i++) {\n"
" crc ^= (uint16_t)buf[i];\n"
" for (int b = 0; b < 8; b++) {\n"
" if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001;\n"
" else crc = (crc >> 1);\n"
" crc &= 0xFFFF;\n"
" }\n"
" }\n"
" return crc;\n"
"}\n"
"\n"
"/* usage: after a full 10-byte frame f[] has arrived */\n"
"uint16_t expect = (uint16_t)f[8] | ((uint16_t)f[9] << 8);\n"
"if (crc16_modbus(f, 8) != expect) { /* drop this frame */ }",
W)]))
# ------------------------------------------------------------ 6
h1("6. 接收端实现建议")
add(note(
"<b>关键坑:帧头不可作为切帧依据。</b>数据区里的 vx / vy / omega 是任意 int16,"
"完全可能等于 0x55AA 或 0xAA55,从而在字节流里造出一个假的 <font face='%s'>AA 55</font>。"
"正确做法是固定 10 字节切帧 + CRC 判定:只有 10 字节对齐且 CRC 通过的帧才采信。"
"若 CRC 失败,不要整帧丢弃后从下一帧开始,而应逐个字节滑动重同步(丢 1 字节再试),"
"这样偶发干扰后最多丢一帧就能重新对齐。" % MONO, W))
h2("6.1 推荐收帧流程")
bullets([
"串口用 DMA + 空闲中断(IDLE)收数据,或中断驱动填环形缓冲,按 10 字节一帧取出;",
"检查字节 0、1 是否为 0xAA 0x55。不是则丢弃 1 字节,回到上一步;",
"对前 8 字节算 CRC16,与 byte8 / byte9(小端拼接)比对。失败则丢弃 1 字节并重新对齐;",
"校验通过:按小端解析 vx、vy、omega,并刷新「最后一次有效帧到达时间」;",
"把三个值写入电机控制环节(可按需再做死区与斜率限制);",
"另设一个定时器:若距上次有效帧超过 300 ~ 500 ms,则强制 vx = vy = omega = 0 并置故障标志。",
], numbered=True)
add(Spacer(1, 4))
add(KeepTogether([code_block(
"/* 10-byte fixed frame + CRC resync */\n"
"static uint8_t buf[10];\n"
"static uint16_t len = 0;\n"
"static uint32_t last_ok_ms = 0;\n"
"\n"
"void on_rx_byte(uint8_t b)\n"
"{\n"
" buf[len++] = b;\n"
" if (len < 10) return;\n"
"\n"
" if (buf[0] == 0xAA && buf[1] == 0x55\n"
" && crc16_modbus(buf, 8) == ((uint16_t)buf[8] | ((uint16_t)buf[9] << 8))) {\n"
" int16_t vx = (int16_t)((uint16_t)buf[2] | ((uint16_t)buf[3] << 8));\n"
" int16_t vy = (int16_t)((uint16_t)buf[4] | ((uint16_t)buf[5] << 8));\n"
" int16_t omega = (int16_t)((uint16_t)buf[6] | ((uint16_t)buf[7] << 8));\n"
" apply_velocity(vx, vy, omega); /* units: mm/s, mm/s, mrad/s */\n"
" last_ok_ms = now_ms();\n"
" len = 0; /* whole frame consumed */\n"
" } else {\n"
" memmove(buf, buf + 1, 9); /* shift by 1 byte and retry */\n"
" len = 9;\n"
" }\n"
"}\n"
"\n"
"/* watchdog: call from a 100 Hz ~ 1 kHz task */\n"
"void safety_tick(void)\n"
"{\n"
" if (now_ms() - last_ok_ms > 400) apply_velocity(0, 0, 0);\n"
"}",
W)]))
h2("6.2 超时停车约定")
para("上位机的行为:只要 200 ms 内没有收到新的 /cmd_vel,它就持续发送全零帧(vx = vy = omega = 0),"
"而不是停发。也就是说链路正常运行时下位机一定会持续收到帧——<b>「收不到帧」本身就意味着异常</b>"
"(上位机崩溃、串口断开、线缆松动)。所以下位机必须自带超时停车,不能只依赖上位机发零帧。")
para("上位机零速帧的固定字节为 <font face='%s'>%s</font>,可用它作为「停车帧」的识别基准。"
% (MONO, P.frame_to_hex(P.pack_velocity_frame(0, 0, 0))))
# ------------------------------------------------------------ 7
add(PageBreak())
h1("7. 示例帧(可直接作单元测试向量)")
para("下表全部由上位机代码 <font face='%s'>protocol.py</font> 现算生成,与实际下发的字节完全一致。"
"建议下位机把这些帧灌进解析函数做回归测试。" % MONO)
rows = [["场景", "vx (m/s)", "vy (m/s)", "omega (rad/s)", "payload byte2~byte7", "完整 10 字节帧"]]
for name, vx, vy, wz, raw in frames():
rows.append([name, "%+.2f" % vx, "%+.2f" % vy, "%+.3f" % wz,
P.frame_to_hex(raw[2:8]), P.frame_to_hex(raw)])
add(data_table(rows, [31 * mm, 15 * mm, 15 * mm, 20 * mm, 40 * mm, W - 121 * mm],
code_cols=(1, 2, 3, 4, 5), align_center=(1, 2, 3)))
add(Spacer(1, 7))
h2("7.1 逐字节解释示例:前进 0.25 m/s")
raw = P.pack_velocity_frame(0.25 * P.VX_SCALE, 0, 0)
bytes_hex = ["%02X" % b for b in raw]
meaning = [
"帧头高字节,固定 0xAA",
"帧头低字节,固定 0x55",
"vx 低字节:250 mm/s = 0x00FA",
"vx 高字节",
"vy 低字节:0 mm/s",
"vy 高字节",
"omega 低字节:0 mrad/s",
"omega 高字节",
"CRC16 低字节",
"CRC16 高字节",
]
rows = [["字节位置", "值", "含义"]] + [["byte %d" % i, bytes_hex[i], meaning[i]] for i in range(10)]
add(data_table(rows, [24 * mm, 16 * mm, W - 40 * mm], code_cols=(1,), align_center=(1,)))
add(Spacer(1, 3))
add(Paragraph("整帧:<font face='%s'>%s</font>;CRC16-MODBUS 计算结果为 "
"<font face='%s'>0x%04X</font>(小端写入即 %s %s)。"
% (MONO, P.frame_to_hex(raw), MONO,
P.crc16_modbus(bytes(b"\xAA\x55" + raw[2:8])), bytes_hex[8], bytes_hex[9]),
STYLES["footnote"]))
# ------------------------------------------------------------ 8
h1("8. 上位机侧行为(对接需知)")
add(data_table([
["参数(ROS 2 参数名)", "默认值", "对下位机的影响"],
["velocity_rate_hz", "30.0", "发包频率,决定下位机收到帧的节奏"],
["cmd_vel_timeout_sec", "0.2", "超过该时长无新指令即发零速帧"],
["send_zero_on_timeout", "true", "置 false 则超时后直接停发(此时下位机的超时兜底更关键)"],
["max_vx_m_s / max_vy_m_s", "2.5 / 2.5", "下发前的限幅,vx / vy 不会超过 ±2500"],
["max_wz_rad_s", "1.5", "下发前的角速度限幅,omega 不会超过 ±1500"],
["baudrate", "115200", "必须与下位机一致"],
["port", "/dev/...", "上位机侧串口设备名(默认 /dev/r2_chassis),与下位机无关"],
], [46 * mm, 26 * mm, W - 72 * mm], code_cols=(0,), align_center=(1,)))
h2("8.1 上电与重启行为")
bullets([
"上位机节点启动后立刻按帧率发帧,在收到第一条 /cmd_vel 之前发的都是零速帧;",
"没有任何握手、心跳或使能流程。下位机随时上电都能从下一帧开始正常接收;",
"下位机重启不需要通知上位机,只要按 10 字节切帧即可重新同步;",
"上位机不会因为下位机不回包而报错——它根本不读串口。",
])
# ------------------------------------------------------------ 9
h1("9. 下位机自检清单")
add(data_table([
["#", "检查项", "通过标准"],
["1", "串口参数", "115200 8N1,无流控"],
["2", "收帧切分", "以 10 字节为单位处理,不用搜帧头切帧"],
["3", "CRC 实现", "对 byte0~7 算 0xA001 / 0xFFFF,结果与 byte8、byte9(小端)一致"],
["4", "字节序", "vx / vy / omega 按小端拼 int16,负数能正确解析(如 0xFF9C = -100)"],
["5", "重同步", "灌入含假帧头或坏 CRC 的脏字节流后,能在 1 ~ 2 帧内恢复对齐"],
["6", "超时停车", "停发数据 300 ~ 500 ms 后电机速度归零并置标志"],
["7", "示例帧回归", "第 7 节所有示例帧的解析结果与表中数值一致"],
["8", "零速帧", "收到全零帧后电机确实停止(而不是仅写入变量)"],
], [9 * mm, 30 * mm, W - 39 * mm], align_center=(0,)))
add(Spacer(1, 6))
add(note("负数字节序自检用例:int16 -100 = 0xFF9C,小端下发为 <font face='%s'>9C FF</font>"
"(低字节 9C 在前,高字节 FF 在后)。若解析出 +155 之类的怪值,"
"说明字节序或符号扩展写错了。" % MONO, W, kind="ok"))
# ------------------------------------------------------------ 附录
add(PageBreak())
h1("附录 A 上位机发送侧实现(Python,节选自 protocol.py)")
add(code_block(
"FRAME_LEN = 10\n"
"HEADER = b\"\\xAA\\x55\"\n"
"VX_SCALE = VY_SCALE = OMEGA_SCALE = 1000.0 # m/s->mm/s, rad/s->mrad/s\n"
"\n"
"def pack_velocity_frame(vx_mm_s, vy_mm_s, omega_mrad_s):\n"
" payload = bytearray(HEADER)\n"
" payload.extend(struct.pack(\"<h\", clamp_i16(vx_mm_s)))\n"
" payload.extend(struct.pack(\"<h\", clamp_i16(vy_mm_s)))\n"
" payload.extend(struct.pack(\"<h\", clamp_i16(omega_mrad_s)))\n"
" payload.extend(struct.pack(\"<H\", crc16_modbus(bytes(payload))))\n"
" return bytes(payload) # always exactly 10 bytes\n"
"\n"
"# node side, inside a 30 Hz timer:\n"
"# frame = pack_velocity_frame(vx*1000, vy*1000, wz*1000)\n"
"# serial.write(frame); serial.flush() # write only, never read",
W))
add(Spacer(1, 4))
h1("附录 B Python 侧解析参考(可当对照实现)")
add(code_block(
"def parse_velocity_frame(raw: bytes):\n"
" assert len(raw) == 10 and raw[0:2] == b\"\\xAA\\x55\"\n"
" expect = raw[8] | (raw[9] << 8)\n"
" assert crc16_modbus(raw[:8]) == expect, \"crc mismatch\"\n"
" vx, vy, omega = struct.unpack_from(\"<hhh\", raw, 2)\n"
" return vx / 1000.0, vy / 1000.0, omega / 1000.0 # m/s, m/s, rad/s",
W))
add(Spacer(1, 6))
add(HRFlowable(width="100%", thickness=0.6, color=RULE, spaceAfter=6))
add(Paragraph("文档由 <font face='%s'>docs/build_protocol_pdf.py</font> 自动生成;协议若有改动,"
"重新运行该脚本即可得到与新版固件一致的新版 PDF。协议权威定义见 "
"<font face='%s'>techx_r2_chassis_control/protocol.py</font> 文件头注释。"
% (MONO, MONO), STYLES["footnote"]))
doc.build(F)
print("written:", OUT_PDF, os.path.getsize(OUT_PDF), "bytes")
if __name__ == "__main__":
main()
@@ -0,0 +1,242 @@
# R2 底盘协议 · 上位机侧核查与自检手册
- 日期:2026-10-03
- 范围:**仅 `src/techx_r2_chassis_control`(ROS 2 上位机包)**,不涉及下位机固件
- 权威实现:`techx_r2_chassis_control/protocol.py`
- 接口契约文档:`docs/R2底盘串口协议_v2.pdf`
---
## 0. 一句话
上位机这一侧**实现是正确的**:帧格式、CRC、字节序、量纲都已用交叉验证跑通(§7 验证记录)。
真正需要你「掌握」的不是写它,而是**能回答下面 6 个问题**——它们全都指向「协议契约」和「失效路径」,而这两样代码里没有。
---
## Q1 · 为什么是小端 `<h` 而不是大端?
**答案**:小端是协议规定,上位机用 `struct.pack("<h", ...)` 直接实现(`protocol.py:77`)。
```python
def i16_to_le(value: int) -> bytes:
return struct.pack("<h", clamp_i16(value))
```
**看懂它的方法**:用一个**负数**做验证,正数看不出字节序。
```python
import struct
struct.pack("<h", -100) # b'\x9c\xff' ← 小端:低字节在前
struct.unpack("<h", b"\x9c\xff")[0] # -100
struct.pack(">h", -100) # b'\xff\x9c' ← 大端:高字节在前
```
`-0.1 m/s` × 1000 = `-100 mm/s` = `0xFF9C`,小端上线就是 `9C FF`。
上位机产出 `AA 55 9C FF 00 ...`(见 §7)。**记住这个 `9C FF`——它是判断字节序写错的最快特征。**
**为什么这件事必须你来定**:字节序是两边各自手工拼装的约定,不是代码内部的自洽性。编译器不会帮你检查,测试也不会自动发现——只有协议文档能定它。
---
## Q2 · CRC 覆盖哪几个字节?校验失败时谁负责?
### CRC 参数(`protocol.py:58-69`)
| 参数 | 值 |
|---|---|
| 多项式 | `0xA001`(MODBUS 反射形式) |
| 初值 | `0xFFFF` |
| 输入/输出位反转 | 无 |
| 最终异或 | 无 |
| **覆盖范围** | **`byte0..byte7`(帧头 + 三个 int16),不含 CRC 自身** |
| CRC 字段摆放 | `byte8` 低字节、`byte9` 高字节 |
代码里的实现与文档一致:
```python
payload.extend(struct.pack("<H", crc16_modbus(bytes(payload)))) # 此时 payload 恰好 8 字节
```
**判据**:`crc16_modbus()` 的入参长度决定了覆盖范围。**看这类实现时,永远先数一下「喂进去几个字节」。** 覆盖范围差一个字节,CRC 全错但代码照样能跑。
### 「校验失败怎么办」——上位机答不了,必须写进文档
这是本题真正的重点:
- 上位机**是单向发送的,从不读回**(`protocol.py:11-12` 写得很明确),所以它**永远不知道** CRC 有没有通过。
- 因此「CRC 失败时下位机的行为」**不是代码问题,是契约问题**:必须在 `R2底盘串口协议_v2.pdf` 里写成强制条款(例如「丢弃该帧」还是「归零停车」),由下位机实现,并在验收时逐条核对。
- 上位机侧唯一相关的动作是**保证 CRC 正确**——这一点已通过 §7 的交叉验证确认。
**顺带一个上位机侧的死参数**:`chassis_serial_node.py:32` 声明了 `serial_timeout_sec: 0.02` 并传给 `serial.Serial(...)`,但节点**从不调用 `read()`**。这个参数对节点行为零影响。
它无害,但暴露了一个模式:**参数名被配齐了,却没有逐个确认「有没有用」**。审这类包时,把每个 `declare_parameter` 都追一遍消费者,是最快的体检手段。
---
## Q3 · 30 Hz 发帧率、`cmd_vel_timeout_sec 0.2`、下位机超时 —— 谁兜底?
三层的时间量级设计得是对的(`200 ms = 6 帧 @ 30 Hz`,留了 6 帧余量):
| 层 | 触发条件 | 动作 | 上位机侧能否验证 |
|---|---|---|---|
| 上位机 | `/cmd_vel` 200 ms 未更新 | 发送**零速帧**(`chassis_serial_node.py:83-94`) | ✅ 可直接看日志验证 |
| 协议契约 | 下位机 200 ms 无**合法帧** | 三轴强制清零 | ❌ 上位机收不到任何反馈,只能靠下位机自检 |
| 硬件 | 固件失控 | 看门狗复位 | ❌ 与上位机无关 |
**关键结论(上位机视角)**:
- 上位机的超时兜底**只在「链路还活着、但没人在发 `/cmd_vel`」时有效**。
- **如果串口本身断了**(拔线、USB 掉设备、下位机复位),上位机的 `write()` 可能仍然成功返回(写进内核缓冲区而已),但**下位机永远收不到那个零速帧**。上位机**没有任何手段感知这一点**。
- 所以「失联后必须自己停下来」这条责任**只能在协议文档里强制下位机承担**。这是当前架构下唯一可行的安全边界,也是你写协议文档时最该加粗的一句话。
**看懂它的方法**:把超时分层列出来,逐层问两个问题——
1. 这一层的判据是什么时钟、什么阈值?
2. **这一层失效时,谁接住?**
第 2 问通常会发现链条上有洞。
---
## Q4 · 粘包 / 半包时 `AA 55` 怎么重新对齐?
**上位机侧的答案很干净:这件事不在上位机的责任范围内。**
理由:上位机是**唯一写者**,且每次 `write()` 都恰好写完整 10 字节(`chassis_serial_node.py:96-99`):
```python
frame = pack_velocity_frame(vx * VX_SCALE, vy * VY_SCALE, wz * OMEGA_SCALE)
with self._write_lock:
self._serial.write(frame)
self._serial.flush()
```
`FRAME_LEN = 10` 定长、单次 write、有 `_write_lock` 串行化 ⇒ **上位机不可能产生粘包或半包**。
**但有两个前提,它们才是上位机该守的**:
1. **这条串口不能有第二个写者。**
只要有人往同一个 `/dev/r2_chassis` 混写别的内容(调试输出、另一个节点、`ros2 topic pub` 之外的临时脚本),线上就会出现非 10 字节片段,此后所有帧永久错位。
→ 建议:把「同一串口禁止其他写者」写进包文档,并在部署时确认没有第二个进程持有该设备。
2. **`write()` 返回成功 ≠ 数据发出去了。**
`pyserial` 的 `write()` 成功只代表写进了内核 TTY 缓冲区。真正的失败(下位机没上电、线松了)**上位机看不到**。
→ 可选的加固:检查 `write()` 返回值是否等于 10(当前代码**没有检查**)。
**「滑 1 字节重同步」是谁的活**:是**下位机**的。因为它收到的字节流可能因为 DMA/中断丢字节而错位。上位机无法也不需要处理对齐——它只保证「自己发出去的永远是完整帧」。
**看懂它的方法**:判断「切帧责任」归属,看**谁是接收方**。接收方负责重同步;发送方只负责帧完整性。这条分工写进协议文档,能省掉后面大量扯皮。
---
## Q5 · `int16 mm/s` 的量化会不会造成抖动?
**上位机侧可以给出确定的答案:量化台阶是 1 mm/s,而且不存在溢出风险。**
1. **台阶**:`VX_SCALE = 1000`、`int16` ⇒ 1 LSB = **1 mm/s = 0.001 m/s**(`protocol.py:28-30`)。
2. **不会溢出**(这是上位机侧可以证明的):`int16` 满量程 ±32767 mm/s = ±32.767 m/s,而上下位机双重限幅在 ±2.5 m/s ⇒ **只用了满量程的 7.6%**。即使去掉所有限幅,`int16` 溢出需要 >32 m/s 的输入,物理上不可能。
3. **限幅后不回写**(`chassis_serial_node.py:72-81`):
```python
def _on_cmd_vel(self, msg: Twist) -> None:
self._latest_vx_m_s = self._clamp(msg.linear.x, ...) # 只存内部变量
```
`msg` 本身没被修改,也没有任何反馈话题。**下游节点不知道指令被截断了**——`/cmd_vel` 上写着 3.0 m/s,实际发出去的是 2.5 m/s,`ros2 topic echo /cmd_vel` 看不出来。
→ 排查「车走不到预期速度」时,这是一个会骗人的地方。诊断方法:把 `log_velocity_frames` 打开,对比日志里的 `TX vx=...` 与 `/cmd_vel` 的原值。
**结论**:`int16` 的 1 mm/s 台阶**不是抖动的可能原因**。真正需要你判断的是:
- **下游(下位机舵轮解算)的死区有多大?** 如果它的死区折算成线速度比 1 mm/s 粗(这类代码的死区常设 0.1 rad/s 量级),那么**主导精度的是那个死区,不是协议量化**。
- **节拍是否对齐?** 上位机 30 Hz 定频发送,下位机以什么频率消费?两个不同频率之间如果没有缓冲,会造成速度指令被随机取样,**这才是低速顿挫的典型成因**,而且它属于**契约层**——需要在协议文档里规定下位机的消费节拍(或规定「每当收到合法帧立即更新目标值」)。
量化、死区、采样节拍,这三者的关系是排查慢速抖动的固定顺序:**先比粗细,再比频率。**
---
## Q6 · 架空状态下怎么证明「下位机收到的是同一条帧」?
上位机侧现有条件:**串口单向,无 ACK,没有回读**。`test_cmd_vel_pub.py` 只发 `/cmd_vel`,不验证任何东西。
分三步补,从便宜到贵:
### 第 1 步(现在就能做,不需要硬件)——固化自检向量
把 §7 的 5 条帧交给下位机做单元测试。**这是唯一能跨过「上位机怎么打包」与「下位机怎么解包」边界、且不需要任何硬件的验证手段。**
| 输入 (m/s, m/s, rad/s) | 线上 10 字节 | 期望解出 |
|---|---|---|
| `(+0.000, +0.000, +0.000)` | `AA 55 00 00 00 00 00 00 CF 09` | `(0, 0, 0)` |
| `(+0.100, +0.000, +0.000)` | `AA 55 64 00 00 00 00 00 C7 2D` | `(+0.1, 0, 0)` |
| `(-0.100, +0.000, +0.000)` | `AA 55 9C FF 00 00 00 00 C6 81` | `(-0.1, 0, 0)` |
| `(+0.000, +0.100, +0.000)` | `AA 55 00 00 64 00 00 00 D0 39` | `(0, +0.1, 0)` |
| `(+0.000, +0.000, +0.100)` | `AA 55 00 00 00 00 64 00 E5 C9` | `(0, 0, +0.1)` |
> 价值:**任一侧改代码,跑这张表就知道有没有破协议。** 它把「口头约定」变成了「可执行断言」。建议直接放进协议文档附录。
### 第 2 步(架空抬轮)——上位机侧发送留痕
给 `chassis_serial_node` 加一个**只读**诊断:把每帧的 `frame_to_hex()` 和时间戳记进环形缓冲,发布到 `~/tx_trace`(`std_msgs/String`),默认关闭。
- 纯观测,不改发送逻辑、不改安全默认值。
- 用 `ros2 topic echo` 就能逐帧核对「打算发什么」和「实际写了什么字节」。
- 注意这只能证明**上位机发出了什么**,证明不了下位机收到了。
### 第 3 步(唯一能证明「下位机真的执行了」的办法)——要求下位机回读
请下位机增加一条**上行帧**(建议用 `55 AA` 起头,与下行 `AA 55` 对称,避免误判),内容为「当前执行的 vx/vy/ω + 本地时间戳」,10 Hz 即可。上位机订阅后与已发送命令做时间对齐比对。
- 这一步会把「单向无回读」的架构改掉,属于**架构决策,需要你拍板**,不是改个参数。
- 收益:直接得到「指令延迟」「CRC 失败率」「失联次数」三个可量化验收指标,也是 §Q3 那条安全边界唯一的验证方式。
---
## 附 A · 上位机包体检清单(本包实测)
| # | 位置 | 现象 | 性质 |
|---|---|---|---|
| 1 | `chassis_serial_node.py:32` | `serial_timeout_sec: 0.02` 声明并传给了 `serial.Serial`,但节点从不 `read()` ⇒ **零影响的死参数** | 无害,但说明参数未逐个确认 |
| 2 | `config/chassis_serial.yaml:12` | `log_velocity_frames: true` ⇒ 30 Hz 每帧打一行 hex 日志。**默认值是否合适要人工判断** | 需决策 |
| 3 | `chassis_serial_node.py:62` | `1.0 / max(1.0, rate_hz)` ⇒ `velocity_rate_hz` 传 0 时**静默降级成 1 Hz**,不报错也不告警 | 静默降级 |
| 4 | `chassis_serial_node.py:57,85` | `_last_cmd_time = 0.0` 初值 ⇒ 启动瞬间即判 stale。配 `send_zero_on_timeout: true` 时会先发零速帧(正确);若设为 `false`,节点启动后**完全不发帧**,下位机必须自己有兜底 | 跨设备安全边界 |
| 5 | `chassis_serial_node.py:72-81` | 限幅结果不回写 `msg`、无反馈话题 ⇒ 下游无法感知截断 | 可观测性缺口 |
| 6 | `yaml:3` vs `launch/chassis_serial.launch.py:14,24` | yaml 写 `port: /dev/ttyUSB0`,launch 的 `port_arg` 默认 `/dev/r2_chassis` 且作为**后置参数覆盖** ⇒ **yaml 里的 port 永远不生效**。两处必须统一 | **真实缺陷** |
| 7 | `chassis_serial_node.py:98` | `self._serial.write(frame)` 未检查返回值是否 == `FRAME_LEN` | 建议加固 |
| 8 | `chassis_serial_node.py:76` | 用 `time.monotonic()` 计时(正确做法);注意不要改成 `time.time()`——墙钟会因 NTP 跳变导致误判 | 已正确 |
**第 6 条是这里唯一需要改代码的**:`launch` 里的 `port` 覆盖会让 yaml 配置失效。两种修法(需你确认):
- 删掉 `launch` 的 `port_arg` 默认覆盖,只保留 `DeclareLaunchArgument('port', default_value='')` 并在为空时不传该参数;
- 或把 yaml 与 launch 的默认值统一为同一个设备路径(并配 udev 规则固定设备名)。
---
## 附 B · 自己验证协议一致性的方法(不需要硬件)
不要「读一遍觉得对」就结束。用**独立实现 + 随机交叉验证**:
1. 按 `docs/R2底盘串口协议_v2.pdf` 的文字描述,**不看 `protocol.py`**,另外写一份最小实现;
2. 用 5000 组随机 8 字节 payload 对比两份实现的 `crc16_modbus()`;
3. 用 3000 组随机 `(vx, vy, ω)`(含超限值)跑「打包 → 解包」闭环,比对是否等于「限幅+四舍五入」后的期望值。
本次核查按此方法执行,结果见 §7。
---
## 7. 验证记录(2026-10-03 实测)
| 项目 | 方法 | 结果 |
|---|---|---|
| CRC16-MODBUS 一致性 | 5000 组随机 8 字节 payload,对照独立实现 | **不一致 0 组** |
| 端到端 pack → parse 闭环 | 3000 组随机 `(vx, vy, ω)`(含 ±3.5 / ±2.0 超限) | **失败 0 组** |
| 负值字节序 | `-0.1 m/s` → 是否产出 `9C FF` | **通过** |
| 双重限幅一致性 | 上位机 ±2.5 / ±2.5 / ±1.5 与协议文档一致 | **通过** |
| 溢出风险 | `int16` 满量程 ±32.767 m/s vs 限幅 ±2.5 m/s | **不可能溢出** |
**可直接粘贴的断言**:
```python
from techx_r2_chassis_control.protocol import pack_velocity_frame, frame_to_hex
assert frame_to_hex(pack_velocity_frame(0, 0, 0)) == "AA 55 00 00 00 00 00 00 CF 09"
assert frame_to_hex(pack_velocity_frame(100, 0, 0)) == "AA 55 64 00 00 00 00 00 C7 2D"
assert frame_to_hex(pack_velocity_frame(-100, 0, 0)) == "AA 55 9C FF 00 00 00 00 C6 81"
assert frame_to_hex(pack_velocity_frame(0, 100, 0)) == "AA 55 00 00 64 00 00 00 D0 39"
assert frame_to_hex(pack_velocity_frame(0, 0, 100)) == "AA 55 00 00 00 00 64 00 E5 C9"
```
@@ -0,0 +1,93 @@
"""启动 R2 底盘串口桥(/cmd_vel -> STM32 速度帧)。
本节点所有可调项的唯一真源是 config/chassis_serial.yaml。这里额外把 port 暴露成 launch
参数,因为台架调试时常需要临时换个设备;它的默认值**从 yaml 反读**,两者因此不可能不一致。
重要 —— 为什么过去改 yaml 对 port 完全无效:
ROS 2 里 parameters 是一个**列表**,按顺序应用、**后者胜**。本文件旧版写的是::
parameters=[LaunchConfiguration('config'), {'port': LaunchConfiguration('port')}]
而 port 的 launch 默认值被硬编码成 /dev/r2_chassis。于是第二段字典永远压过参数文件,
config/chassis_serial.yaml 里写的 port 变成死信 —— 无论怎么改 yaml 都改不动它。
这与 sru_nav_ros2/launch/sru_nav.launch.py 中记录的失败模式同源(当年
odom_twist_in_base_frame 一直是 false,而 yaml 写的是 true),修法也相同:默认值从文件读。
关于 install 拷贝:setup.py 是用**拷贝**方式安装 config/*.yaml 的,所以
install/.../share/techx_r2_chassis_control/config/ 下是另一个文件;改 src/ 里的 yaml
必须重新编译才生效。用 params_file:= 直接指向源码树可以免重建(该参数就是为此存在),
长期方案是 colcon build --symlink-install。
典型用法::
ros2 launch techx_r2_chassis_control chassis_serial.launch.py
# 台架测试临时换设备
ros2 launch techx_r2_chassis_control chassis_serial.launch.py port:=/dev/ttyUSB0
# 改完即用,不必重新编译
ros2 launch techx_r2_chassis_control chassis_serial.launch.py \\
params_file:=$HOME/sru_ws/src/techx_r2_chassis_control/config/chassis_serial.yaml
警告 —— 节点在构造函数里就打开串口,且下位机没有独立的失联兜底:
任何能触达 /cmd_vel 的测试都必须先让轮子离地。
"""
import os
import yaml
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def _yaml_default(params_file, name, fallback):
"""读取参数文件里 name 的写法值。
有意**不做** .lower()。sru_nav_ros2/launch/sru_nav.launch.py 里的同名助手末尾带
.lower(),那是为读布尔值写的;照抄到这里会把设备路径 /dev/ttyUSB0 变成 /dev/ttyusb0。
文件读不出来时回落到 fallback,这样 yaml 坏了也仍能启动,让节点自己报更清楚的错,
而不是死在 launch 系统里。
"""
try:
with open(params_file, 'r') as f:
params = yaml.safe_load(f)['chassis_serial_node']['ros__parameters']
return str(params[name])
except Exception:
return fallback
def generate_launch_description():
pkg_share = get_package_share_directory('techx_r2_chassis_control')
default_params_file = os.path.join(pkg_share, 'config', 'chassis_serial.yaml')
declared_arguments = [
DeclareLaunchArgument(
'params_file', default_value=default_params_file,
description='节点参数文件(默认取包 share 目录下的 config/chassis_serial.yaml)。'
'安装出来的是拷贝而非符号链接 —— 把它指向 src/ 下那份即可改完即用、'
'无需重新编译。'),
DeclareLaunchArgument(
'port', default_value=_yaml_default(default_params_file, 'port', '/dev/ttyUSB0'),
description='串口设备。默认值从 config/chassis_serial.yaml 反读,该文件即唯一真源;'
'临时覆盖一次用 port:=...。'),
]
chassis_node = Node(
package='techx_r2_chassis_control',
executable='chassis_serial_node',
name='chassis_serial_node',
output='screen',
# 顺序有意义:第 0 项是参数文件,第 1 项是命令行覆盖。后者胜 —— 这是故意的
# (port:=... 就靠它生效),而它之所以安全,只因为上面 port 的默认值正是从
# 同一个文件读出来的。
parameters=[
LaunchConfiguration('params_file'),
{'port': LaunchConfiguration('port')},
],
)
return LaunchDescription(declared_arguments + [chassis_node])
@@ -0,0 +1,19 @@
<?xml version="1.0"?>
<package format="3">
<name>techx_r2_chassis_control</name>
<version>0.2.0</version>
<description>Python serial bridge: /cmd_vel -> R2 chassis STM32 velocity frames.</description>
<maintainer email="[email protected]">techx</maintainer>
<license>MIT</license>
<buildtool_depend>ament_python</buildtool_depend>
<exec_depend>rclpy</exec_depend>
<exec_depend>geometry_msgs</exec_depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
<export>
<build_type>ament_python</build_type>
</export>
</package>
@@ -0,0 +1,4 @@
[develop]
script_dir=$base/lib/techx_r2_chassis_control
[install]
install_scripts=$base/lib/techx_r2_chassis_control
@@ -0,0 +1,30 @@
from setuptools import setup
from glob import glob
import os
package_name = 'techx_r2_chassis_control'
setup(
name=package_name,
version='0.2.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages', ['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
(os.path.join('share', package_name, 'launch'), glob('launch/*.launch.py')),
(os.path.join('share', package_name, 'config'), glob('config/*.yaml')),
],
install_requires=['setuptools', 'pyserial'],
zip_safe=True,
maintainer='techx',
maintainer_email='[email protected]',
description='Python serial bridge: /cmd_vel -> R2 chassis STM32 velocity frames.',
license='MIT',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'chassis_serial_node = techx_r2_chassis_control.chassis_serial_node:main',
'test_cmd_vel_pub = techx_r2_chassis_control.test_cmd_vel_pub:main',
],
},
)
@@ -0,0 +1,121 @@
from __future__ import annotations
import threading
import time
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist
try:
import serial
except ImportError as exc: # pragma: no cover - runtime dependency on robot
serial = None
from .protocol import (
OMEGA_SCALE,
VX_SCALE,
VY_SCALE,
frame_to_hex,
pack_velocity_frame,
)
class ChassisSerialNode(Node):
"""Bridge /cmd_vel -> STM32 serial velocity frames."""
def __init__(self) -> None:
super().__init__("chassis_serial_node")
self.declare_parameter("port", "/dev/ttyUSB0")
self.declare_parameter("baudrate", 115200)
self.declare_parameter("serial_timeout_sec", 0.02)
self.declare_parameter("velocity_rate_hz", 30.0)
self.declare_parameter("cmd_vel_timeout_sec", 0.2)
self.declare_parameter("send_zero_on_timeout", True)
self.declare_parameter("max_vx_m_s", 2.5)
self.declare_parameter("max_vy_m_s", 2.5)
self.declare_parameter("max_wz_rad_s", 1.5)
self.declare_parameter("log_velocity_frames", False)
if serial is None:
raise RuntimeError("pyserial is not installed. Install with: sudo apt install python3-serial")
self._port = self.get_parameter("port").value
self._baudrate = int(self.get_parameter("baudrate").value)
self._serial = serial.Serial(
self._port,
self._baudrate,
timeout=float(self.get_parameter("serial_timeout_sec").value),
)
self.get_logger().info(f"Opened chassis serial port {self._port} @ {self._baudrate}")
self._write_lock = threading.Lock()
self._latest_vx_m_s = 0.0
self._latest_vy_m_s = 0.0
self._latest_wz_rad_s = 0.0
self._last_cmd_time = 0.0
self.create_subscription(Twist, "/cmd_vel", self._on_cmd_vel, 10)
rate_hz = float(self.get_parameter("velocity_rate_hz").value)
self.create_timer(1.0 / max(1.0, rate_hz), self._velocity_timer_cb)
def destroy_node(self) -> bool:
try:
if self._serial is not None and self._serial.is_open:
self._serial.close()
except Exception:
pass
return super().destroy_node()
def _on_cmd_vel(self, msg: Twist) -> None:
self._latest_vx_m_s = self._clamp(msg.linear.x, float(self.get_parameter("max_vx_m_s").value))
self._latest_vy_m_s = self._clamp(msg.linear.y, float(self.get_parameter("max_vy_m_s").value))
self._latest_wz_rad_s = self._clamp(msg.angular.z, float(self.get_parameter("max_wz_rad_s").value))
self._last_cmd_time = time.monotonic()
@staticmethod
def _clamp(value: float, limit: float) -> float:
limit = abs(float(limit))
return max(-limit, min(limit, float(value)))
def _velocity_timer_cb(self) -> None:
timeout_sec = float(self.get_parameter("cmd_vel_timeout_sec").value)
stale = self._last_cmd_time <= 0.0 or (time.monotonic() - self._last_cmd_time) > timeout_sec
if stale:
if not bool(self.get_parameter("send_zero_on_timeout").value):
return
vx = vy = wz = 0.0
else:
vx = self._latest_vx_m_s
vy = self._latest_vy_m_s
wz = self._latest_wz_rad_s
frame = pack_velocity_frame(vx * VX_SCALE, vy * VY_SCALE, wz * OMEGA_SCALE)
with self._write_lock:
self._serial.write(frame)
self._serial.flush()
if bool(self.get_parameter("log_velocity_frames").value):
self.get_logger().info(
f"TX vx={vx * VX_SCALE:.0f}mm/s vy={vy * VY_SCALE:.0f}mm/s "
f"omega={wz * OMEGA_SCALE:.0f}mrad/s | {frame_to_hex(frame)}"
)
def main(args=None) -> None:
rclpy.init(args=args)
node = ChassisSerialNode()
try:
rclpy.spin(node)
except KeyboardInterrupt:
pass
finally:
node.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main()
@@ -0,0 +1,117 @@
"""R2 chassis serial protocol, v2 (velocity only).
Frame layout, fixed 10 bytes, little endian:
Byte0-1 0xAA 0x55 header
Byte2-3 vx int16, mm/s
Byte4-5 vy int16, mm/s
Byte6-7 omega int16, mrad/s
Byte8-9 CRC16-MODBUS over byte0..byte7
Host -> STM32 only. The host never reads frames back, so there is no receive
command set.
Sign convention follows geometry_msgs/Twist:
vx = linear.x (m/s, forward positive)
vy = linear.y (m/s, left positive)
omega = angular.z (rad/s, counter-clockwise positive)
"""
from __future__ import annotations
from dataclasses import dataclass
import struct
FRAME_LEN = 10
HEADER = b"\xAA\x55"
VX_SCALE = 1000.0 # m/s -> mm/s
VY_SCALE = 1000.0 # m/s -> mm/s
OMEGA_SCALE = 1000.0 # rad/s -> mrad/s
class ProtocolError(ValueError):
"""Raised when a serial frame is malformed."""
@dataclass(frozen=True)
class VelocityCommand:
"""Parsed chassis velocity frame."""
vx_mm_s: int
vy_mm_s: int
omega_mrad_s: int
@property
def vx_m_s(self) -> float:
return self.vx_mm_s / VX_SCALE
@property
def vy_m_s(self) -> float:
return self.vy_mm_s / VY_SCALE
@property
def omega_rad_s(self) -> float:
return self.omega_mrad_s / OMEGA_SCALE
def crc16_modbus(data: bytes) -> int:
"""Compute CRC16-MODBUS, polynomial 0xA001, init 0xFFFF."""
crc = 0xFFFF
for byte in data:
crc ^= byte
for _ in range(8):
if crc & 0x0001:
crc = (crc >> 1) ^ 0xA001
else:
crc >>= 1
crc &= 0xFFFF
return crc
def clamp_i16(value: float | int) -> int:
return max(-32768, min(32767, int(round(value))))
def i16_to_le(value: int) -> bytes:
return struct.pack("<h", clamp_i16(value))
def le_to_i16(data: bytes, offset: int = 0) -> int:
return struct.unpack_from("<h", data, offset)[0]
def le_to_u16(data: bytes, offset: int = 0) -> int:
return struct.unpack_from("<H", data, offset)[0]
def pack_velocity_frame(vx_mm_s: float | int, vy_mm_s: float | int, omega_mrad_s: float | int) -> bytes:
"""Build a 10-byte velocity frame for the STM32."""
payload = bytearray(HEADER)
payload.extend(i16_to_le(vx_mm_s))
payload.extend(i16_to_le(vy_mm_s))
payload.extend(i16_to_le(omega_mrad_s))
payload.extend(struct.pack("<H", crc16_modbus(bytes(payload))))
return bytes(payload)
def parse_velocity_frame(raw: bytes | bytearray) -> VelocityCommand:
"""Parse a velocity frame. Used by tooling and lower-machine-side tests."""
raw = bytes(raw)
if len(raw) != FRAME_LEN:
raise ProtocolError(f"frame length must be {FRAME_LEN}, got {len(raw)}")
if raw[0:2] != HEADER:
raise ProtocolError("invalid frame header")
expected_crc = le_to_u16(raw, 8)
actual_crc = crc16_modbus(raw[:8])
if expected_crc != actual_crc:
raise ProtocolError(f"crc mismatch expected=0x{expected_crc:04X}, actual=0x{actual_crc:04X}")
return VelocityCommand(
vx_mm_s=le_to_i16(raw, 2),
vy_mm_s=le_to_i16(raw, 4),
omega_mrad_s=le_to_i16(raw, 6),
)
def frame_to_hex(frame: bytes | bytearray) -> str:
return " ".join(f"{b:02X}" for b in bytes(frame))
@@ -0,0 +1,55 @@
from __future__ import annotations
import argparse
import time
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import Twist
class CmdVelPublisher(Node):
def __init__(self, vx: float, vy: float, omega: float, rate_hz: float, duration_sec: float) -> None:
super().__init__("test_cmd_vel_pub")
self._publisher = self.create_publisher(Twist, "/cmd_vel", 10)
self._vx = vx
self._vy = vy
self._omega = omega
self._duration_sec = duration_sec
self._start_time = time.monotonic()
self._timer = self.create_timer(1.0 / max(1.0, rate_hz), self._timer_cb)
def _timer_cb(self) -> None:
elapsed = time.monotonic() - self._start_time
if elapsed > self._duration_sec:
self.get_logger().info("Finished publishing /cmd_vel")
rclpy.shutdown()
return
msg = Twist()
msg.linear.x = self._vx
msg.linear.y = self._vy
msg.angular.z = self._omega
self._publisher.publish(msg)
self.get_logger().info(f"Publish /cmd_vel vx={self._vx:.3f} vy={self._vy:.3f} omega={self._omega:.3f}")
def build_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Publish test /cmd_vel")
parser.add_argument("--vx", type=float, default=0.1, help="linear.x in m/s")
parser.add_argument("--vy", type=float, default=0.0, help="linear.y in m/s")
parser.add_argument("--omega", type=float, default=0.0, help="angular.z in rad/s")
parser.add_argument("--rate-hz", type=float, default=10.0)
parser.add_argument("--duration-sec", type=float, default=3.0)
return parser
def main(args=None) -> None:
parser = build_arg_parser()
parsed_args, ros_args = parser.parse_known_args(args)
rclpy.init(args=ros_args)
node = CmdVelPublisher(parsed_args.vx, parsed_args.vy, parsed_args.omega, parsed_args.rate_hz, parsed_args.duration_sec)
rclpy.spin(node)
if __name__ == "__main__":
main()