28 Commits

Author SHA1 Message Date
e942a7d157 build: default the tests to the build mode instead of always on
The standalone CMake build is the robot deployment path and must not produce
test executables; a catkin workspace is a development machine and keeps them.
Force with -D<option>=ON to build the tests from a standalone build.
2026-08-15 12:41:31 +07:00
75078db589 optimal vitural function 2026-08-10 21:42:52 +07:00
771ee5d5e7 add new file 2026-08-10 13:21:31 +07:00
ad28a413cc add new file nav_c_api2 and function 2026-08-06 19:50:46 +07:00
565e18bfb8 Add recovery and mission manager structure 2026-07-03 17:37:39 +07:00
33d6537947 Tạm bỏ 2026-04-27 15:09:17 +07:00
62a2fed488 fix lỗi xoay khi về đích 2026-04-27 14:24:40 +07:00
1a19e38b2d update 2026-04-25 16:26:12 +07:00
0d10ec2208 update config 2026-04-25 15:35:10 +07:00
270bbcc0c4 update 2026-04-25 15:29:44 +07:00
dbbda958a2 update logic xoay 2026-04-24 15:01:37 +07:00
875db4ba1e Hiep sử custom và thông số rotate 2026-04-24 14:52:11 +07:00
9c14054d3f update reduce speed 2026-04-24 12:32:47 +07:00
498a85a199 update lan 1 2026-04-24 11:23:35 +07:00
d681201698 update 2026-04-23 20:10:57 +07:00
5812542eaf uodate lần 3 2026-04-23 18:26:13 +07:00
0c65a5b6ba update xoay 2026-04-23 17:57:31 +07:00
1616ac8d7b uodate 2026-04-23 17:26:51 +07:00
5d4d77155b update khi lui 2026-04-23 17:11:47 +07:00
274d3dd858 update rotation 2026-04-23 10:29:19 +07:00
251c741dd9 update phan di thang 2026-04-23 10:28:28 +07:00
a9c56261ea Dương update custom 2026-04-18 08:32:14 +02:00
cac2343d47 Thuat toan 2026-04-18 08:31:50 +02:00
HiepLM
9f0bd9f485 update custom 2026-04-06 12:19:31 +07:00
HiepLM
ef76c43029 test rotate 2026-04-06 04:46:09 +07:00
HiepLM
d88e547676 fix direction 2026-04-06 04:36:23 +07:00
01e278befb update 2026-03-27 13:05:23 +07:00
7df2365d96 fix 2026-03-27 12:58:40 +07:00
74 changed files with 5893 additions and 7198 deletions

1
.gitignore vendored
View File

@@ -422,4 +422,3 @@ build
install install
devel devel
obstacle

View File

@@ -20,7 +20,11 @@ The specified base path contains a CMakeLists.txt but "catkin_make" must be invo
# Build trong workspace mới # Build trong workspace mới
cd ../pnkx_nav_catkin_ws cd ../pnkx_nav_catkin_ws
catkin_make rm -rf build devel
catkin_make -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DCMAKE_CXX_FLAGS="-fsanitize=address -fno-omit-frame-pointer" \
-DCMAKE_C_FLAGS="-fsanitize=address -fno-omit-frame-pointer" \
-DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address"
source devel/setup.bash source devel/setup.bash
``` ```

View File

@@ -138,22 +138,6 @@ if (NOT TARGET pnkx_local_planner)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Packages/local_planners/pnkx_local_planner) add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Packages/local_planners/pnkx_local_planner)
endif() endif()
if (NOT TARGET robot_angles)
add_subdirectory(${CMAKE_SOURCE_DIR}/obstacle/angles)
endif()
if (NOT TARGET grid_map_core)
add_subdirectory(${CMAKE_SOURCE_DIR}/obstacle/grid_map_core)
endif()
if (NOT TARGET robot_base_local_planner)
add_subdirectory(${CMAKE_SOURCE_DIR}/obstacle/base_local_planner)
endif()
if (NOT TARGET hybrid_local_planner)
add_subdirectory(${CMAKE_SOURCE_DIR}/obstacle/hybrid_local_planner)
endif()
if (NOT TARGET robot_actionlib_msgs) if (NOT TARGET robot_actionlib_msgs)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Libraries/robot_actionlib_msgs) add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Libraries/robot_actionlib_msgs)
endif() endif()
@@ -166,19 +150,89 @@ if (NOT TARGET robot_clear_costmap_recovery)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Libraries/robot_clear_costmap_recovery) add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Libraries/robot_clear_costmap_recovery)
endif() endif()
# 2. Main packages (phụ thuộc vào cores) # 3. Packages being migrated from AMR_T800/Test
# message(STATUS "[move_base] Shared library configured") #
if (NOT TARGET move_base) # Prefer the future in-tree location. Until the migration is physically done,
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Packages/move_base) # keep the current sibling Test directory buildable from this root CMake file.
option(PNKX_NAV_CORE_BUILD_TEST_PACKAGES
"Build navigation packages currently kept in AMR_T800/Test"
ON)
option(PNKX_NAV_CORE_BUILD_CATKIN_TEST_PACKAGES
"Build Test packages that require a catkin workspace instead of standalone CMake"
OFF)
set(PNKX_NAV_CORE_TEST_PACKAGES_DIR ""
CACHE PATH "Directory containing the migrated navigation Test packages")
if(NOT PNKX_NAV_CORE_TEST_PACKAGES_DIR)
if(IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/Test")
set(PNKX_NAV_CORE_TEST_PACKAGES_DIR "${CMAKE_CURRENT_SOURCE_DIR}/Test")
elseif(IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/../Test")
set(PNKX_NAV_CORE_TEST_PACKAGES_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../Test")
endif()
endif() endif()
# C API for .NET/C# integration function(pnkx_add_test_package package_name)
if (NOT TARGET navigation_c_api) set(package_dir "${PNKX_NAV_CORE_TEST_PACKAGES_DIR}/${package_name}")
if(EXISTS "${package_dir}/CMakeLists.txt")
message(STATUS "[pnkx_nav_core] Adding migrated Test package: ${package_name}")
add_subdirectory("${package_dir}" "${CMAKE_BINARY_DIR}/Test/${package_name}")
else()
message(WARNING
"[pnkx_nav_core] Test package '${package_name}' was not found in "
"'${PNKX_NAV_CORE_TEST_PACKAGES_DIR}'.")
endif()
endfunction()
if(PNKX_NAV_CORE_BUILD_TEST_PACKAGES)
if(NOT PNKX_NAV_CORE_TEST_PACKAGES_DIR)
message(FATAL_ERROR
"PNKX_NAV_CORE_BUILD_TEST_PACKAGES is ON, but no Test package directory was found. "
"Set PNKX_NAV_CORE_TEST_PACKAGES_DIR explicitly.")
endif()
# Foundation and message packages.
pnkx_add_test_package(angles)
pnkx_add_test_package(image_geometry)
pnkx_add_test_package(grid_map_core)
pnkx_add_test_package(vda5050_msgs)
# Planner libraries and plugins. SBPL must precede its lattice plugin.
pnkx_add_test_package(sbpl)
pnkx_add_test_package(sbpl_lattice_planner)
pnkx_add_test_package(base_local_planner)
pnkx_add_test_package(hybrid_local_planner)
pnkx_add_test_package(mppi_local_planner)
pnkx_add_test_package(priest_local_planner)
pnkx_add_test_package(stanley_local_planner)
# Supporting runtime packages and test utilities.
pnkx_add_test_package(depth_image_proc)
pnkx_add_test_package(action_core)
pnkx_add_test_package(recovery_core)
pnkx_add_test_package(mission_adapters)
pnkx_add_test_package(nav_test_harness)
# Must be last: it consumes planners, actions, recovery and mission APIs.
pnkx_add_test_package(move_base2)
endif()
# These packages call find_package(catkin REQUIRED ...) for T800 packages.
# Keep them outside the standalone graph until their dependencies export
# *Config.cmake files, or build them through a catkin workspace.
if(PNKX_NAV_CORE_BUILD_CATKIN_TEST_PACKAGES)
pnkx_add_test_package(deep_mpc_local_planner)
pnkx_add_test_package(nav_ros_bridge)
pnkx_add_test_package(depth_local_costmap_noetic_test)
endif()
# C API for .NET/C# integration. Target is `nav_c_api` — the guard must name the same target,
# otherwise it never matches and the subdirectory is added twice on a re-entrant configure.
if (NOT TARGET nav_c_api)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/APIs/c_api) add_subdirectory(${CMAKE_SOURCE_DIR}/src/APIs/c_api)
endif() endif()
message(STATUS "========================================") message(STATUS "========================================")
message(STATUS "All packages configured successfully") message(STATUS "All packages configured successfully")
message(STATUS "========================================") message(STATUS "========================================")

View File

@@ -8,4 +8,8 @@ voxel_layer:
unknown_threshold: 15.0 unknown_threshold: 15.0
mark_threshold: 0 mark_threshold: 0
combination_method: 1 combination_method: 1
frustum_clearing_enabled: true
frustum_clearing_pixel_step: 8
frustum_min_range: 0.20
frustum_max_range: 3.0
frustum_depth_camera_topic: /camera/depth/data

View File

@@ -1,5 +1,7 @@
robot_base_frame: base_link robot_base_frame: base_link
transform_tolerance: 1.0 transform_tolerance: 1.0
performance_metrics_enabled: true
performance_metrics_period: 5.0
obstacle_range: 3.0 obstacle_range: 3.0
#mark_threshold: 1 #mark_threshold: 1
publish_voxel_map: true publish_voxel_map: true
@@ -11,7 +13,7 @@ navigation_map:
map_file: maze map_file: maze
virtual_walls_map: virtual_walls_map:
map_topic: /virtual_walls/map map_topic: /map
namespace: /virtual_walls namespace: /virtual_walls
map_pkg: managerments map_pkg: managerments
map_file: maze map_file: maze
@@ -19,55 +21,80 @@ virtual_walls_map:
lethal_cost_threshold: 100 lethal_cost_threshold: 100
obstacles: obstacles:
observation_sources: l_scan_marking l_scan_clearing r_scan_marking r_scan_clearing b_scan_marking b_scan_clearing observation_sources: b_scan pc_marking pc_clearing pc_r_marking pc_r_clearing
l_scan_marking: # f_scan_marking: f_scan_marking f_scan_clearing
topic: /l_scan # topic: /f_scan
data_type: LaserScan # data_type: LaserScan
clearing: false # clearing: false
marking: true # marking: true
inf_is_valid: true # inf_is_valid: true
min_obstacle_height: 0.0 # min_obstacle_height: 0.0
max_obstacle_height: 0.25 # max_obstacle_height: 0.25
l_scan_clearing: # f_scan_clearing:
topic: /l_scan # topic: /f_scan
data_type: LaserScan # data_type: LaserScan
clearing: true # clearing: true
marking: false # marking: false
inf_is_valid: true # inf_is_valid: true
min_obstacle_height: 0.0 # min_obstacle_height: 0.0
max_obstacle_height: 0.25 # max_obstacle_height: 0.25
r_scan_marking: b_scan:
topic: /r_scan
data_type: LaserScan
clearing: false
marking: true
inf_is_valid: true
min_obstacle_height: 0.0
max_obstacle_height: 0.25
r_scan_clearing:
topic: /r_scan
data_type: LaserScan
clearing: true
marking: false
inf_is_valid: true
min_obstacle_height: 0.0
max_obstacle_height: 0.25
b_scan_marking:
topic: /b_scan
data_type: LaserScan
clearing: false
marking: true
inf_is_valid: true
min_obstacle_height: 0.0
max_obstacle_height: 0.25
b_scan_clearing:
topic: /b_scan topic: /b_scan
data_type: LaserScan data_type: LaserScan
clearing: true clearing: true
marking: false marking: true
inf_is_valid: true inf_is_valid: true
frustum_clearing_enabled: false
min_obstacle_height: 0.0 min_obstacle_height: 0.0
max_obstacle_height: 0.25 max_obstacle_height: 0.25
pc_marking:
topic: /camera/depth/points_proc
data_type: PointCloud2
clearing: false
marking: true
inf_is_valid: false
frustum_clearing_enabled: false
observation_persistence: 0.0
expected_update_rate: 0.5
obstacle_range: 2.5
raytrace_range: 3.0
min_obstacle_height: 0.1
max_obstacle_height: 1.0
pc_clearing:
topic: /camera/depth/data
data_type: DepthCameraData
clearing: false
marking: true
frustum_clearing_enabled: true
frustum_clearing_pixel_step: 8
frustum_min_range: 0.20
frustum_max_range: 3.5
pc_r_marking:
topic: /camera_right/depth/points_proc
data_type: PointCloud2
clearing: false
marking: true
inf_is_valid: false
frustum_clearing_enabled: false
observation_persistence: 0.0
expected_update_rate: 0.5
obstacle_range: 2.5
raytrace_range: 3.0
min_obstacle_height: 0.1
max_obstacle_height: 1.0
pc_r_clearing:
topic: /camera_right/depth/data
data_type: DepthCameraData
clearing: false
marking: true
frustum_clearing_enabled: true
frustum_clearing_pixel_step: 8
frustum_min_range: 0.20
frustum_max_range: 3.5
# Depth camera clearing is handled by VoxelLayer frustum clearing from
# /camera/depth/image_raw + /camera/depth/camera_info. /camera_right/depth/data

View File

@@ -4,7 +4,7 @@ global_costmap:
global_frame: map global_frame: map
update_frequency: 1.0 update_frequency: 1.0
publish_frequency: 1.0 publish_frequency: 1.0
raytrace_range: 3.5 raytrace_range: 3.0
resolution: 0.05 resolution: 0.05
z_resolution: 0.2 z_resolution: 0.2
rolling_window: false rolling_window: false

View File

@@ -7,4 +7,4 @@ global_costmap:
- {name: inflation, type: "InflationLayer" } - {name: inflation, type: "InflationLayer" }
obstacles: obstacles:
enabled: false enabled: false
footprint_clearing_enabled: false footprint_clearing_enabled: true

View File

@@ -5,7 +5,7 @@ local_costmap:
update_frequency: 6.0 update_frequency: 6.0
publish_frequency: 6.0 publish_frequency: 6.0
rolling_window: true rolling_window: true
raytrace_range: 3.5 raytrace_range: 3.0
resolution: 0.05 resolution: 0.05
z_resolution: 0.15 z_resolution: 0.15
z_voxels: 8 z_voxels: 8

View File

@@ -1,6 +1,7 @@
local_costmap: local_costmap:
frame_id: odom frame_id: odom
plugins: plugins:
# - {name: virtual_walls_map, type: "StaticLayer" }
- {name: obstacles, type: "VoxelLayer" } - {name: obstacles, type: "VoxelLayer" }
- {name: inflation, type: "InflationLayer" } - {name: inflation, type: "InflationLayer" }
obstacles: obstacles:

View File

@@ -1,59 +1,55 @@
LocalPlannerAdapter:
library_path: liblocal_planner_adapter
yaw_goal_tolerance: 0.017
xy_goal_tolerance: 0.03
min_approach_linear_velocity: 0.06
HybridLocalPlanner: HybridLocalPlanner:
# base_local_planner: "hybrid_local_planner/HybridLocalPlanner" # base_local_planner: "hybrid_local_planner/HybridLocalPlanner"
# HybridLocalPlanner: # HybridLocalPlanner:
library_path: libhybrid_local_planner library_path: libhybrid_local_planner
odom_topic: odom
# Trajectory
max_global_plan_lookahead_dist: 4.0
global_plan_viapoint_sep: 0.5
global_plan_prune_distance: 0.0
global_plan_goal_sep: 0.05
# Robot # Robot
max_forward_velocity: 1.0
robot_max_v_ac: 0.4 max_reverse_velocity: 0.25 # [m/s], positive magnitude
robot_max_w_ac: 0.4 avoidance_max_velocity: 0.4
robot_max_v_pt: 1.0 max_angular_velocity: 0.6
robot_max_w_pt: 0.4 min_in_place_angular_velocity: 0.3
robot_max_v_backwards_pt: -0.2 acc_lim_x: 0.1
acc_lim_x: 1.0 decel_lim_x: 0.5
acc_lim_theta: 2.0 acc_lim_theta: 2.0
turn_around_priority: True min_turn_radius: 0.0
stop_dist: 0.5 robot_radius: 0.1
dec_dist: 1.0 footprint_padding: 0.08
use_footprint: true
# GoalTolerance # GoalTolerance
xy_goal_tolerance: 0.02
yaw_goal_tolerance: 0.02
xy_goal_tolerance: 0.05 # Trajectory
yaw_goal_tolerance: 0.05 max_global_plan_lookahead_dist: 3.0
global_plan_viapoint_sep: 0.5
global_plan_goal_sep: 0.05
predict_time: 3.0
sim_period: 0.1
sim_time_samples: 10
# Optimization # Optimization
w_omega: 2.5
obs_cost_gain: 1.3
path_cost_gain: 0.5
to_goal_cost_gain: 0.8
speed_cost_gain: 0.5
# PP Parameters # Obstacles
w_vel: 0.8 obs_range: 2.5
w_omega: 1.0
# DWA Parameters
enable_backward_motion: false
w_targetheading_ac: 1.7
w_velocity_ac: 0.2
w_clearance_ac: 0.2
w_pathDistance_ac: 0.05
w_smoothness_ac: 0.3
w_targetheading_pt: 0.2
w_velocity_pt: 0.8
w_clearance_pt: 0.1
w_pathDistance_pt: 2.1
w_smoothness_pt: 0.3
time_horizon: 3.0
velocity_resolution: 0.015
segment_transition_threshold: 0.01 # Ngưỡng khoảng cách chuyển segment #GeneralSetting
calibration_factor: 1.5 # Hệ số hiệu chuẩn segment_transition_threshold: 0.03 # [m], also used as DWA stop distance for intermediate segments
use_obstacle_avoidance: true # Bật tắt tránh vật cản rotation_segment_yaw_threshold: 0.05 # [rad], ignore tiny yaw noise at duplicate positions
direction_change_hysteresis: 0.15 # normalized dot product
use_obstacle_avoidance: true
slow_velocity_th: 0.1
turn_direction_th: 0.1
avoidance_clear_hold_time: 0.5 # [s]
rejoin_blend_time: 0.8 # [s]
rejoin_max_velocity: 0.25 # [m/s]
rejoin_heading_tolerance: 0.35 # [rad]
rejoin_path_tolerance: 0.20 # [m]
pp_max_omega_correction: 0.15 # [rad/s]
rejoin_acc_lim_theta: 1.0 # [rad/s^2]
rejoin_lookahead_distance: 0.8 # [m]

View File

@@ -37,7 +37,7 @@ charger:
- {name: charger, docking_planner: "DockPlanner", docking_nav: ""} - {name: charger, docking_planner: "DockPlanner", docking_nav: ""}
charger: charger:
maker_goal_frame: charger maker_goal_frame: charger_goal
footprint: [[0.583,-0.48],[0.583,0.48],[-0.583,0.48],[-0.583,-0.48]] footprint: [[0.583,-0.48],[0.583,0.48],[-0.583,0.48],[-0.583,-0.48]]
delay: 1.5 # Cấm sửa không là không chạy được delay: 1.5 # Cấm sửa không là không chạy được
timeout: 60 timeout: 60

View File

@@ -0,0 +1,78 @@
# =================================================================================================
# mission_adapters — tham số RUNTIME của mission layer.
#
# Quy ước comment: dòng mô tả = LÀ GÌ / vì sao; `► Chỉnh:` = tăng giảm theo triệu chứng nào.
#
# Mission layer đứng GIỮA nguồn nhiệm vụ (VDA5050 Order, goal trần) và navigation: nó cắt order
# thành từng CHẶNG tại mỗi node có action, chỉ chạy phần `released`, nối tiếp theo `orderUpdateId`
# thay vì chạy lại từ đầu, và giữ hàng đợi chặng.
#
# Đây là bản đang có hiệu lực. Bản trong `Test/mission_adapters/test/config/` chỉ phục vụ test và
# chỉ được đọc khi chạy kèm PNKX_NAV_CORE_CONFIG_DIR trỏ vào đúng thư mục đó.
#
# Bật/tắt cả tầng này bằng `mission_layer_enabled` trong `move_base_common_params.yaml`.
# =================================================================================================
mission_adapters:
# Nguồn mission. Thêm một loại nguồn mới = thêm một entry ở đây + một plugin .so, không phải sửa
# code của gói.
# name: tên instance, cũng là namespace param riêng của nó
# type: tên symbol export bằng BOOST_DLL_ALIAS, phải có khoá library_path tương ứng bên dưới
#
# goal_src : goal trần từ host (không có edge) — dùng khi test bằng RViz/sim.
# vda5050_src : Order VDA5050 đầy đủ (node + edge + action), đường chạy production.
#
# ► Chỉnh: bỏ bớt một nguồn = tắt đường vào tương ứng. Bỏ HẾT thì runtime tự quay về đường trực
# tiếp (như `mission_layer_enabled: false`) kèm log cảnh báo — thiếu plugin không được phép biến
# thành robot đứng im không rõ lý do.
mission_sources:
- {name: goal_src, type: GoalSourceAdapter}
- {name: vda5050_src, type: VDA5050SourceAdapter}
# [s] Trần thời gian cho MỘT chặng (navigation + action), tính từ lúc chặng được giao.
# 0 = tắt. Quá hạn thì chặng bị đánh dấu thất bại VÀ navigation được bảo dừng — lưới cuối cho
# trường hợp navigation không bao giờ báo kết quả về.
#
# ► Chỉnh: đây là lưới an toàn CUỐI CÙNG, không phải cơ chế timeout chính (mỗi action handler đã
# tự timeout, và navigation có `planner_patience`/`controller_patience`).
# - Bật (vd 120–300 s) khi cần chắc chắn fleet luôn nhận được kết quả chặng.
# - Đặt phải LỚN HƠN chặng dài nhất cộng toàn bộ thời gian recovery có thể xảy ra, nếu không
# robot đang phục hồi bình thường sẽ bị cắt ngang và báo fail oan.
mission_timeout: 0.0
# Một chặng thất bại thì xử lý phần còn lại của hàng đợi thế nào.
# true = xoá sạch hàng đợi (mặc định, an toàn cho tuyến đường tuần tự kiểu VDA5050: không tới
# được node n thì chạy tiếp chặng n+1 là cắt ngang đoạn chưa được cho phép đi)
# false = chỉ bỏ chặng lỗi rồi chạy tiếp.
#
# ► Chỉnh: chỉ đặt false khi các mission trong hàng đợi ĐỘC LẬP với nhau, không phải các chặng của
# cùng một tuyến. Với compound action (charge/PickUp) thì BẮT BUỘC true: nó chính là thứ ngăn
# robot chạy bước `startCharging`/`LiftFork` khi bước dò hoặc bước tiến vào đã hỏng.
clear_queue_on_failure: true
# =================================================================================================
# Param riêng của từng instance nguồn mission, đặt theo `name` khai ở `mission_sources`.
# =================================================================================================
vda5050_src:
# Frame gán cho goal/start sinh ra từ nodePosition của VDA5050.
# Lưu ý: `mapId` trong VDA5050 là danh tính bản đồ, KHÔNG phải frame TF, nên không dùng làm frame.
#
# ► Chỉnh: phải khớp `global_frame` của costmap global. Sai frame ở đây thì mọi goal lệch vị trí
# hoặc TF không quy đổi được, và lỗi hiện ra ở tận tầng planner nên rất khó truy.
global_frame: map
# Bảng compound action (`charge`, `PickUp`, ...) KHÔNG khai ở đây mà ở
# `Test/move_base2/config/runtime/compound_actions_params.yaml` — file đó cũng dùng khoá
# `vda5050_src` và được `robot::NodeHandle` GỘP vào chung một cây. Tách file vì file này là
# symlink sang submodule `pnkx_nav_core`.
# Bảng symbol -> thư viện cho Boost.DLL. KHÔNG phải tham số tinh chỉnh.
#
# Thiếu khoá library_path là nguyên nhân phổ biến nhất của lỗi "plugin build xong nhưng runtime báo
# không tìm thấy". Tên không có đuôi .so được resolve qua PNKX_NAV_CORE_LIBRARY_PATH / devel/lib /
# LD_LIBRARY_PATH — tức phải `source devel/setup.bash` trước khi chạy.
GoalSourceAdapter:
library_path: libmission_adapters_goal_source
VDA5050SourceAdapter:
library_path: libmission_adapters_vda5050_source

View File

@@ -1,13 +1,13 @@
position_planner_name: PNKXLocalPlanner position_planner_name: StanleyLocalPlanner #ybridLocalPlanner MPPILocalPlanner PriestLocalPlanner PNKXLocalPlanner
docking_planner_name: PNKXDockingLocalPlanner docking_planner_name: PNKXDockingLocalPlanner #StanleyDockingLocalPlanner PNKXDockingLocalPlanner
go_straight_planner_name: PNKXGoStraightLocalPlanner go_straight_planner_name: PNKXGoStraightLocalPlanner
rotate_planner_name: PNKXRotateLocalPlanner rotate_planner_name: PNKXRotateLocalPlanner
base_local_planner: LocalPlannerAdapter base_local_planner: LocalPlannerAdapter
base_global_planner: CustomPlanner base_global_planner: CustomPlanner
PNKXLocalPlanner: StanleyLocalPlanner:
base_local_planner: LocalPlannerAdapter base_local_planner: LocalPlannerAdapter
base_global_planner: CustomPlanner base_global_planner: CustomPlanner #CustomPlanner SBPLLatticePlanner
PNKXDockingLocalPlanner: PNKXDockingLocalPlanner:
base_local_planner: LocalPlannerAdapter base_local_planner: LocalPlannerAdapter
@@ -22,15 +22,25 @@ PNKXRotateLocalPlanner:
base_global_planner: TwoPointsPlanner base_global_planner: TwoPointsPlanner
### replanning ### replanning
controller_frequency: 30.0 # run controller at 15.0 Hz controller_frequency: 30.0 # run controller at 30.0 Hz
controller_patience: 0.0 # if the controller failed, clear obstacles and retry; after 15.0 s, abort and replan controller_patience: 0.0 # if the controller failed, clear obstacles and retry; after 15.0 s, abort and replan
planner_frequency: 0.0 # don't continually replan (only when controller failed) planner_frequency: 0.0 # don't continually replan (only when controller failed)
planner_patience: 2.0 # if the first planning attempt failed, abort planning retries after 5.0 s... planner_patience: 2.0 # if the first planning attempt failed, abort planning retries after 5.0 s...
max_planning_retries: 0 # ... or after 10 attempts (whichever happens first) max_planning_retries: 0 # ... or after 10 attempts (whichever happens first)
oscillation_timeout: -1 # abort controller and trigger recovery behaviors after 30.0 s oscillation_timeout: -1 # abort controller and trigger recovery behaviors after 30.0 s
oscillation_distance: 0.5 oscillation_distance: 0.5
### recovery behaviors ## recovery behaviors
recovery_behavior_enabled: true #
# Recovery của move_base cũ đã dừng: bộ behavior gen-2 (tick-based) khai ở
# `recovery_behaviors_params.yaml` và do `recovery_core::RecoveryRegistry` nạp, không phải khoá
# `recovery_behaviors` ở đây.
#
# Danh sách gen-1 đã được gỡ hẳn thay vì để lại: các entry cũ trỏ tên alias `RotateRecovery` /
# `ClearCostmapRecovery` vào file .so gen-2, trong khi loader ở đây import theo chữ ký gen-1
# (`robot_nav_core::RecoveryBehavior`). Boost.DLL không kiểm kiểu qua ranh giới .so, nên hai bên
# không bao giờ gặp nhau ở compile time và lỗi chỉ hiện ra lúc chạy. Giữ lại khoá cũng làm hai file
# config tranh nhau cùng một tên alias.
recovery_behavior_enabled: false
recovery_behaviors: [ recovery_behaviors: [
{name: aggressive_reset, type: ClearCostmapRecovery}, {name: aggressive_reset, type: ClearCostmapRecovery},
{name: conservative_reset, type: ClearCostmapRecovery}, {name: conservative_reset, type: ClearCostmapRecovery},

View File

@@ -0,0 +1,98 @@
LocalPlannerAdapter:
library_path: liblocal_planner_adapter
yaw_goal_tolerance: 0.017
xy_goal_tolerance: 0.03
min_approach_linear_velocity: 0.06
MPPILocalPlanner:
library_path: libmppi_local_planner
# Robot limits [m/s, rad/s]
min_velocity: 0.0
# Cao hon reference_velocity mot khoang dem (headroom). Neu de sat ref thi
# nua tren cua nhieu sampling bi clamp o max, keo van toc trung binh xuong
# (do duoc: ref0.45/max0.50 -> chi dat 0.33; max0.65 -> dat 0.41). Robot chay
# duoc >0.6 m/s nen dat 0.65.
max_velocity: 0.65
max_angular_velocity: 1.0
robot_radius: 0.30
obstacle_point_radius: 0.08
footprint_padding: 0.05
# MPPI core
# Horizon = model_dt * time_steps = 3.6 s ~ 1.8 m @0.5 m/s.
# Truoc day 1.4 s (0.7 m) qua ngan: robot chi "thay" vat can khi da sat, khong con
# cho de vong qua -> hoac ket hoac lang nhang. Do thuc te: 0.7m/1.2m khong toi dich;
# 1.8m toi dich voi quang duong chi dai hon 6% so voi duong thang.
# Khong tang dt qua 0.15: dt=0.20 lam dao dong tang gap 4 lan.
model_dt: 0.2
time_steps: 20
batch_size: 220
# So thread OpenMP. De mac dinh (= 16 core) thi tranh chap voi gazebo/rviz/perception
# lam 1 chu ky solveMPPI cham tu 0.9 ms len ~25 ms.
num_threads: 4
param_lambda: 100.0
param_alpha: 0.98
param_exploration: 0.05
vx_std: 0.2
wz_std: 0.25
reference_velocity: 0.48
# Path and goal
# Phai lon hon horizon (1.8 m), neu khong terminal goal_weight se keo robot ve
# diem cat cua reference path va lam no giam toc moi chu ky.
max_global_plan_lookahead_dist: 3.0
xy_goal_tolerance: 0.10
yaw_goal_tolerance: 0.10
# Costmap and cost weights
obstacle_range: 2.5
obstacle_cost_threshold: 150
obstacle_cell_step: 2
max_obstacle_points: 180
obstacle_influence_radius: 1.0
# Cost vat can gio CONG DON tren tung cell (truoc day lay max), nen thang nay phai
# nho hon nhieu. Giu 85 voi che do sum lam cost vot len ~180x85, ap dao moi thanh
# phan khac -> dao dong manh va di vong xa 45%. Do thuc te tai T=24/dt=0.15:
# weight=10 cho dao dong thap nhat va khoang ho 0.48 m (du 13 cm).
obstacle_cost_use_sum: true
obstacle_weight: 10.0
collision_cost: 1000000.0
progress_weight: 8.0
terminal_progress_weight: 20.0
goal_weight: 30.0
# Phat v^2: gan 0 vi no truc tiep keo van toc xuong (phan truc giac voi robot
# muon chay nhanh). Giu nho de van co chut smoothing.
linear_control_weight: 0.2
angular_control_weight: 0.2
control_change_weight: 1.0
# Giam toc khi lech huong: ha tu 0.8 xuong 0.3. Truoc day khi ne vat can
# (yaw error lon) robot bo <0.1 m/s. 0.3 van giam toc vao cua nhung khong bo.
yaw_error_slowdown: 0.1
min_tracking_velocity: 0.08
# Phat hien ket: MPPI co the tra lenh hop le nhung ~0 mai o cuc tieu dia phuong.
# Qua nguong nay controller bao that bai -> move_base PLANNING roi CLEARING.
stuck_velocity_threshold: 0.03
stuck_omega_threshold: 0.05
stuck_patience_cycles: 40
# --- Covariance thich nghi (giai doan 2) ---
# Moi chu ky fit lai do rong nhieu cho TUNG buoc thoi gian tu chinh batch.
# vx_std/wz_std o tren chi con la gia tri khoi tao va gia tri sau reset.
adaptive_covariance: true
gaussian_fitting_lambda: 5.0 # phai < param_lambda de trong so du nhon
# San chon bang thuc nghiem: thap hon -> muot hon nhung cham va sat vat can hon.
min_vx_std: 0.08
max_vx_std: 0.35
min_wz_std: 0.10
max_wz_std: 0.60
# Khi bi ket, no rong sigma dan qua tung chu ky de thoat cuc tieu dia phuong.
stuck_sigma_inflation: 1.6
hard_obstacle_cost_threshold: 254
stage_xy_weight: 60.0
stage_yaw_weight: 1.0
stage_speed_weight: 12.0
terminal_xy_weight: 90.0
terminal_yaw_weight: 1.0
terminal_speed_weight: 12.0

View File

@@ -1,8 +1,8 @@
MQTT: # MQTT:
Name: T800 # Name: T800
Host: 172.20.235.170 # Host: 172.20.235.170
Port: 1885 # Port: 1885
Client_ID: T800 # Client_ID: T800
Username: robotics # Username: robotics
Password: robotics # Password: robotics
Keep_Alive: 60 # Keep_Alive: 60

View File

@@ -1,5 +1,5 @@
yaw_goal_tolerance: 0.03 yaw_goal_tolerance: 0.02
xy_goal_tolerance: 0.02 xy_goal_tolerance: 0.03
min_approach_linear_velocity: 0.05 min_approach_linear_velocity: 0.05
LocalPlannerAdapter: LocalPlannerAdapter:
@@ -48,17 +48,17 @@ LimitedAccelGenerator:
min_vel_y: 0.0 # diff drive robot min_vel_y: 0.0 # diff drive robot
max_speed_xy: 2.0 # max_trans_vel: 0.8 # choose slightly less than the base's capability max_speed_xy: 2.0 # max_trans_vel: 0.8 # choose slightly less than the base's capability
min_speed_xy: 0.15 # min_trans_vel: 0.1 # this is the min trans velocity when there is negligible rotational velocity min_speed_xy: 0.25 # min_trans_vel: 0.1 # this is the min trans velocity when there is negligible rotational velocity
max_vel_theta: 0.4 # max_rot_vel: 1.0 # choose slightly less than the base's capability max_vel_theta: 0.4 # max_rot_vel: 1.0 # choose slightly less than the base's capability
min_vel_theta: 0.05 # min_rot_vel: 0.1 default: 0.4 # this is the min angular velocity when there is negligible translational velocity min_vel_theta: 0.05 # min_rot_vel: 0.1 default: 0.4 # this is the min angular velocity when there is negligible translational velocity
acc_lim_x: 1.5 acc_lim_x: 3.0
acc_lim_y: 0.0 # diff drive robot acc_lim_y: 0.0 # diff drive robot
acc_lim_theta: 1.5 acc_lim_theta: 1.5
decel_lim_x: -1.5 decel_lim_x: -3.0
decel_lim_y: -0.0 decel_lim_y: -0.0
decel_lim_theta: -1.5 decel_lim_theta: -2.0
# Whether to split the path into segments or not # Whether to split the path into segments or not
split_path: true split_path: true
@@ -74,8 +74,8 @@ LimitedAccelGenerator:
MKTAlgorithmDiffPredictiveTrajectory: MKTAlgorithmDiffPredictiveTrajectory:
library_path: libmkt_algorithm_diff library_path: libmkt_algorithm_diff
xy_local_goal_tolerance: 0.02 xy_local_goal_tolerance: 0.05
angle_threshold: 0.47 angle_threshold: 0.6
index_samples: 60 index_samples: 60
follow_step_path: true follow_step_path: true
@@ -119,7 +119,7 @@ MKTAlgorithmDiffPredictiveTrajectory:
MKTAlgorithmDiffGoStraight: MKTAlgorithmDiffGoStraight:
library_path: libmkt_algorithm_diff library_path: libmkt_algorithm_diff
xy_local_goal_tolerance: 0.02 xy_local_goal_tolerance: 0.05
angle_threshold: 0.8 angle_threshold: 0.8
index_samples: 60 index_samples: 60
follow_step_path: true follow_step_path: true
@@ -156,7 +156,7 @@ MKTAlgorithmDiffGoStraight:
MKTAlgorithmDiffRotateToGoal: MKTAlgorithmDiffRotateToGoal:
library_path: libmkt_algorithm_diff library_path: libmkt_algorithm_diff
xy_local_goal_tolerance: 0.02 xy_local_goal_tolerance: 0.05
angle_threshold: 0.47 angle_threshold: 0.47
index_samples: 60 index_samples: 60
follow_step_path: true follow_step_path: true

View File

@@ -0,0 +1,56 @@
PriestLocalPlanner:
library_path: libpriest_local_planner
# ================= Horizon / optimizer =================
t_fin: 7.0 # [s] planning horizon
num_steps: 30 # trajectory samples over the horizon
num_batch: 60 # trajectories per CEM iteration
initial_up_sampling: 5 # candidate oversampling factor
ellite_num: 40 # elites ranked by projection residual
num_warm: 20 # warm-started trajectories between cycles
max_proj_iter: 8 # alternating projection iterations
max_cem_iter: 4 # CEM iterations per control cycle
optimizer_threads: 4 # bounded workers; avoid severe overhead from using all CPU cores
solve_time_warn_ms: 30.0 # [ms] leaves margin inside the 30 Hz controller period
lateral_std: 0.8 # [m] std of lateral waypoint perturbations
# ================= Robot limits (differential drive) =================
max_velocity: 0.5 # [m/s] forward velocity limit
max_angular_velocity: 0.4 # [rad/s] also enforced inside the optimizer as a
# lateral-acceleration clamp |a_n| <= omega_max * v
max_acceleration: 0.5 # [m/s^2] used in the trajectory projection
reference_velocity: 0.4 # [m/s] desired cruise speed along the path
v_eps: 0.05 # [m/s] below this speed the curvature clamp/cost is skipped
v_min_seed: 0.05 # [m/s] initial-velocity seed along yaw when the robot is stopped
# Trajectory -> differential (v, omega) conversion with curvature feedforward:
# omega = clamp(omega_traj, +-max_angular_velocity) - heading_gain * heading_error
heading_gain: 1.5 # [1/s] feedback gain on the heading error
heading_error_stop: 1.2 # [rad] above this, rotate in place (v = 0)
min_in_place_yawrate: 0.2 # [rad/s]
# ================= Goal / plan =================
xy_goal_tolerance: 0.10 # [m]
yaw_goal_tolerance: 0.10 # [rad]
max_global_plan_lookahead_dist: 3.0 # [m]
# ================= Obstacles (from local costmap) =================
num_obs: 40 # obstacles in the CEM cost
num_obs_proj: 30 # closest obstacles inside the projection
obstacle_range: 2.5 # [m] costmap scan radius around the robot
robot_radius: 0.50 # [m]
obstacle_point_radius: 0.08 # [m]
footprint_padding: 0.05 # [m]
obstacle_cost_threshold: 150
obstacle_cell_step: 2
max_obstacle_points: 150
# ================= Cost weights =================
weight_smoothness: 0.1
weight_track: 0.2
weight_obs: 1.2
weight_clearance: 3.0 # bounded proximity term in (0,1]: 1 at an obstacle
# centre, 0.5 on the collision boundary, 0 out of range
weight_angular: 0.5 # hinge penalty on |omega| > max_angular_velocity
cem_lamda: 0.9 # CEM temperature
cem_alpha: 0.7 # CEM mean/cov blending factor

View File

@@ -0,0 +1,310 @@
# =================================================================================================
# recovery_core — bộ recovery behavior (gen-2, tick-based) và tham số vận hành.
#
# Quy ước comment: dòng mô tả = LÀ GÌ / vì sao; `► Chỉnh:` = tăng giảm theo triệu chứng nào.
#
# Đây là cây config RUNTIME. Bản dùng cho test của gói nằm ở
# `Test/recovery_core/test/config/recovery_behaviors_params.yaml` — sửa tham số vận hành thì sửa ở
# đây, đừng sửa bản test.
#
# Danh sách này được `recovery_core::RecoveryRegistry` đọc; caller (RecoveryRunner của move_base2)
# truyền namespace `recovery` vào. Khoá `recovery_behaviors:` trong `move_base_common_params.yaml`
# thuộc về move_base cũ và KHÔNG liên quan tới file này.
# =================================================================================================
recovery:
# `behaviors` là registry mọi plugin/instance CÓ THỂ dùng. Thứ tự ở đây chỉ là thứ tự nạp,
# không còn quyết định luồng chạy. `routes` bên dưới chọn riêng chuỗi theo trigger.
#
# wait : không di chuyển. Vật cản động (người, xe khác) tự đi qua là xong.
# clear : xoá vật cản đã tích trong costmap, gần trước rồi xa sau.
# rotate : quay tại chỗ cho costmap nhìn lại xung quanh.
# back_up: LÙI — hướng robot không có sensor, nên xếp cuối cùng.
#
# ► Chỉnh: khai ở đây KHÔNG làm behavior chạy — phải đưa tên nó vào một `route` bên dưới. Một
# `type` được phép khai nhiều `name` khác nhau để có nhiều instance khác tuning (vd một
# `back_up` lùi 0.1 m và một `back_up_far` lùi 0.6 m).
behaviors:
- {name: wait, type: WaitRecovery}
- {name: clear, type: ClearCostmapRecovery}
# Đặt schema trước plugin: chưa có `DetourPathRecovery`/library_path thì RecoveryRunner bỏ
# entry này cùng warning, và bỏ nó khỏi từng route. Khi plugin SBPL được thêm sau này, không
# cần sửa move_base2 hay route.
- {name: detour_path, type: DetourPathRecovery}
- {name: rotate, type: RotateRecovery}
- {name: back_up, type: BackUpRecovery}
# trigger -> tên behavior thử tuần tự; lần lỗi kế tiếp cùng trigger mới tiến tới phần tử tiếp
# theo của route đó. Đường quay về sau khi một behavior kết thúc (contract 2026-08-04b):
# - planning_failed -> quay về PLANNING lập plan lại (không có plan nào để bám);
# - controlling/oscillation-> quay về CONTROLLING bám tiếp GLOBAL PATH CŨ, KHÔNG lập plan lại
# (thay plan trong lúc chạy là việc riêng của planner_frequency);
# riêng khi leo thang từ PLANNING vì mất pose thì về PLANNING;
# - behavior họ detour (output kPath, vd DetourPathRecovery) nộp path mới -> path đó được áp
# và robot bám tiếp — cách duy nhất một recovery được thay plan.
# Robot đi được quá `oscillation_distance` thì mọi cursor route được reset — ngân sách recovery
# đầy lại theo tiến độ thật (2026-08-04).
#
# Ý NGHĨA TỪNG TRIGGER:
# planning_failed : planner CÓ dữ liệu nhưng không tìm được đường.
# controlling_failed : MẤT DỮ LIỆU/LỆNH — controller không ra lệnh (kể cả mất pose) quá
# `controller_patience`, hoặc mất pose ngay trong PLANNING, hoặc costmap
# stale liên tục quá `sensor_patience`.
# oscillation : quẩn trong bán kính `oscillation_distance` quá `oscillation_timeout`.
# path_blocked : DỰ BÁO tuyến phía trước bị chắn (giám sát tuyến).
# off_path : DỰ BÁO robot đã lệch khỏi plan quá ngưỡng.
#
# ► Chỉnh route:
# - route RỖNG = tắt hẳn trigger đó. `path_blocked`/`off_path` được phép rỗng; ba route còn lại
# bắt buộc có ít nhất một behavior (config validate chặn).
# - route được phép LẶP behavior: mỗi lần xuất hiện là một lượt thử (`[detour, wait, detour]`).
# - route dài hơn = kiên nhẫn hơn nhưng chậm báo lỗi lên fleet hơn.
# - thứ tự nên đi từ RẺ và AN TOÀN tới ĐẮT và RỦI RO: wait/clear -> rotate -> detour -> back_up.
routes:
planning_failed: [wait, clear]
controlling_failed: [detour_path]
oscillation: [wait]
# Cursor reset (2026-08-05): recovery THÀNH CÔNG + NỘP PATH MỚI (detour) thì cursor của trigger
# đó reset NGAY — lần chắn kế tiếp là sự cố mới, detour được chạy lại. Từ chối/thất bại mới ăn
# vào ngân sách route.
#
# Cạn route KHÔNG còn nghĩa là ABORT (contract 2026-08-05e): `path_blocked`/`off_path` là DỰ
# BÁO, plan vẫn hợp lệ và controller vẫn ra lệnh được, nên robot bám tiếp plan cũ và trigger bị
# KHOÁ tới khi đi được quá `oscillation_distance`. Đường ABORT hợp lệ duy nhất đi qua
# `controlling_failed` (controller thật sự hết ra lệnh quá controller_patience) hoặc
# `planning_failed`.
path_blocked: [detour_path]
off_path: [detour_path]
# --- wait: đứng yên, không phát vận tốc ---------------------------------------------------------
wait:
# [s] Thời gian đứng yên.
# ► Chỉnh: TĂNG (5–10) ở khu đông người để vật cản động kịp đi qua; GIẢM nếu robot đứng chờ quá
# lâu ở chỗ vật cản thật ra là tĩnh. Thời gian này robot KHÔNG phát cmd_vel.
wait_duration: 3.0
# --- clear: xoá vật cản đã tích trong costmap ---------------------------------------------------
#
# Đường thoát đúng khi bẫy là VẬT CẢN MA (costmap giữ lại thứ không còn ở đó). Rẻ nhất trong bộ,
# nên thường đặt đầu route.
clear:
# [m] Cạnh vùng vuông quanh robot sẽ bị xoá.
# ► Chỉnh: TĂNG nếu ma nằm xa hơn (nhưng xoá rộng = mất cả vật cản THẬT vừa quan sát được, robot
# có thể lao vào chỗ vừa xoá). GIẢM để an toàn hơn. Đừng vượt quá cửa sổ costmap local (8 m).
reset_distance: 3.0
# false = xoá BÊN TRONG vùng; true = xoá BÊN NGOÀI (giữ lại vùng gần robot).
# ► Chỉnh: true chỉ hợp lý khi muốn giữ vật cản gần và bỏ dữ liệu xa đã cũ.
invert_area_to_clear: false
# local | global | both — costmap nào bị xoá.
# ► Chỉnh: `local` nếu chỉ muốn làm mới dữ liệu sensor mà không đụng bản đồ tích luỹ.
affected_maps: both
# Phải khớp `plugins:` của costmap; sai tên -> log kèm tên layer thật.
# ► Chỉnh: thêm tên layer nếu costmap có nhiều layer vật cản (vd `[obstacles, voxel_layer]`).
# Đây KHÔNG phải số tinh chỉnh — sai tên là behavior không xoá gì cả.
layer_names: [obstacles]
# --- rotate: quay tại chỗ cho sensor quét lại xung quanh -----------------------------------------
rotate:
# true = quay đủ 2*pi để costmap thấy toàn bộ xung quanh.
# ► Chỉnh: false = quay theo `goal.angle` do caller đặt, và nếu caller không đặt thì dùng
# `target_angle` bên dưới. Giữ true cho mục đích "nhìn lại xung quanh".
full_rotation: true
# [rad] Góc quay mặc định khi `full_rotation: false` VÀ caller không truyền `goal.angle`.
# Giá trị hiện tại = 2*pi (tức bằng full_rotation), nên khi `full_rotation: true` nó nằm im.
# ► Chỉnh: viết SỐ CỤ THỂ, đừng viết biểu thức kiểu `2 * 3.14159` — parser YAML không tính.
# Dấu quyết định chiều quay. Ví dụ nửa vòng: 3.141592653589793.
# Giá trị bị clamp về |target_angle| nên không thể quay quá một vòng.
target_angle: 6.283185307179586
# [rad/s] Độ lớn tốc độ quay; dấu do goal.angle quyết định.
# ► Chỉnh: phải <= max_vel_theta của robot. GIẢM nếu có tải cao/dễ đổ; TĂNG để recovery nhanh
# hơn nhưng sensor có thể nhoè khi quét.
angular_speed: 0.4
# [rad/s^2] Ramp gia tốc, tránh giật khi có tải.
# ► Chỉnh: GIẢM khi chở hàng dễ đổ; TĂNG nếu robot mất quá nhiều thời gian mới đạt tốc độ.
acc_lim_theta: 0.8
# [rad] Bước quét footprint dọc cung lúc start (kiểm va chạm trước khi quay).
# ► Chỉnh: GIẢM (0.05) để kiểm kỹ hơn ở chỗ chật, đổi lại tốn CPU lúc start. TĂNG thì có nguy cơ
# bỏ sót một vị trí góc bị chạm.
sim_granularity: 0.1
# [s] Lưới cuối nếu robot bị giữ cơ học (bánh trượt, bị chèn).
# ► Chỉnh: phải > thời gian quay 2*pi ở `angular_speed` (2π/0.4 ≈ 15.7 s) cộng dư địa ramp.
# Đặt thấp hơn là behavior LUÔN kết thúc bằng timeout.
timeout: 20.0
# --- back_up: lùi thẳng -------------------------------------------------------------------------
#
# Hướng lùi KHÔNG có sensor -> rủi ro cao nhất trong bộ, thường xếp cuối route.
back_up:
# [m] Quãng lùi mặc định khi caller không chỉ định.
# ► Chỉnh: TĂNG (0.3–0.6) nếu robot cần lùi hẳn ra khỏi hốc/khe kệ mới xoay được; GIẢM nếu phía
# sau thường có người/vật. Nhớ phía sau là vùng mù.
backup_distance: 0.1
# [m] Trần cứng, chặn cả `goal.distance` do caller truyền lẫn param ở trên.
# ► Chỉnh: đây là chốt an toàn, đặt bằng quãng lùi mù xa nhất còn chấp nhận được ở hiện trường.
backup_distance_max: 1.0
# [m/s] ĐỘ LỚN; dấu âm (lùi) do plugin đặt.
# ► Chỉnh: giữ chậm (<= 0.15) vì đi mù. TĂNG chỉ khi có sensor sau.
linear_speed: 0.1
# [m/s^2] Ramp gia tốc.
# ► Chỉnh: GIẢM khi chở tải dễ đổ.
acc_lim_x: 0.3
# [s] Lưới cuối.
# ► Chỉnh: phải > backup_distance_max / linear_speed (1.0/0.1 = 10 s) cộng dư địa ramp.
timeout: 15.0
# --- detour_path: lập đường vòng quanh vật cản rồi NỐI LẠI tuyến --------------------------------
#
# Gói `sbpl_recovery`, họ kPath: nó KHÔNG lái robot, chỉ TRẢ VỀ một path; runtime áp path đó và
# local planner đang active bám theo. Đường vòng được bám ngay, không replan (contract 08-04b).
detour_path:
# Instance planner RIÊNG, không dùng chung SBPLLatticePlanner của backup: detour gọi makePlan
# ĐỒNG BỘ trên control thread, nên `allocated_time` của instance này là trần treo control loop
# mỗi tick. Xem khối SBPLDetourPlanner ở cuối file.
#
# ► Chỉnh: `planner_name` là NAMESPACE PARAM (khối bên dưới), `planner_symbol` là ALIAS Boost.DLL
# CÓ THẬT trong .so. Đây không phải số tinh chỉnh — đổi sai là runtime không nạp được plugin.
planner_name: SBPLDetourPlanner
planner_symbol: SBPLLatticePlanner # libsbpl_lattice_planner chỉ export đúng một symbol này.
# Khác bộ local planner, nơi mỗi biến thể là một class riêng
# nên tên instance trùng alias.
# "combined" (2026-08-05, vòng 3 — LƯỚI GỘP, xem DETOUR_MERGED_GRID_PLAN.md): snapshot global
# làm nền (tường/kệ tĩnh toàn bản đồ) + đè cửa sổ local lên (vật cản sensor tươi), SBPL lập
# đường TRÊN BẢN CHỤP GỘP — không giữ mutex costmap nào trong lúc search, map update không bị
# bỏ đói dù attempt thua. Một bên báo chắn là chắn; local FREE không xoá tường global.
# Cần planner export capability "<planner_symbol>ExternalGrid" (sbpl_lattice_planner có sẵn).
#
# ► Chỉnh: giữ `combined`. `local` = chỉ cửa sổ lăn, cho hệ không có global costmap — điểm nối
# kẹt trong cửa sổ. `global` = chỉ lưới tĩnh: ĐÃ ĐO và LOẠI trên sim, global không nạp sensor
# nên goal nào SBPL cũng vẽ xuyên đúng chỗ vật cản tươi (6/6 attempt hỏng).
costmap_source: combined
# [m] Điểm nối phải cách robot tối thiểu chừng này (đo Euclid).
# ► Chỉnh: TĂNG nếu đường vòng quá ngắn/gấp khiến local planner không bám nổi. GIẢM nếu ở chỗ
# chật không tìm nổi điểm nối. Phải < `max_rejoin_distance` khi cái đó > 0.
planning_distance: 1.0
# [m] TRẦN quét dọc plan, thuần tuỳ chọn. 0 = quét tới CUỐI PLAN (lưới gộp phủ toàn bản đồ nên
# không còn ràng buộc cửa sổ local). Quét luôn tự dừng ở rìa lưới.
# ► Chỉnh: GIỮ 0. Hai lần sim 2026-08-05 đặt cap hữu hạn (3.8 rồi 8.0) đều cắt quét ngay sau pose
# bẩn cuối và báo "không có chỗ sạch" OAN. Chỉ đặt > 0 khi muốn chặn cứng độ dài đường vòng.
max_rejoin_distance: 0.0
# [m] Khoảng cách dọc plan giữa hai ứng viên điểm nối liên tiếp.
# ► Chỉnh: TĂNG để ba ứng viên trải rộng hơn (thử được nhiều chỗ khác nhau hơn); GIẢM để thử
# dày quanh một vùng. Cùng `attempts_per_run` quyết định tầm phủ: 3 x 0.5 = ~1.5 m.
sample_step: 0.5
# [m] Điểm nối phải cách pose bẩn gần nhất CẢ HAI PHÍA dọc plan chừng này, và nằm SAU pose bẩn
# CUỐI CÙNG CÒN NHÌN THẤY ĐƯỢC (trong cửa sổ local — contract 2026-08-05f). Chỗ chắn ngoài tầm
# nhìn là dữ liệu cũ, không được quyền quyết định điểm nối.
# ► Chỉnh: TĂNG (0.8–1.0) nếu nhiều lượt SBPL báo `Solution not found` — 0.5 m có thể quá sát:
# "bẩn" ở đây do kiểm MỘT ô, còn SBPL kiểm footprint đầy đủ (0.6x0.6 + inflation 0.55 m).
# GIẢM nếu ở khu chật không bao giờ tìm được điểm nối.
rejoin_clearance: 0.5
# Số ứng viên điểm nối thử tối đa trong một lượt; mỗi control cycle thử ĐÚNG MỘT ứng viên.
# ► Chỉnh: TĂNG = kiên nhẫn hơn nhưng mỗi lượt hỏng tốn thêm `allocated_time` giây treo control
# thread. GIẢM = từ bỏ nhanh, nhường cho behavior kế tiếp của route.
attempts_per_run: 3
# Tuyến để NỐI LẠI (2026-08-05e). "reference" = tuyến GỐC của chặng, tức plan do planner sinh và
# recovery không thay được: đường vòng luôn quay về tuyến order, và `max_deviation` đo đúng hành
# lang fleet đã duyệt. "current" = plan đang bám (hành vi cũ) — sim đo được tuyến bị ăn mòn dần
# qua từng lượt detour (rejoin 106/305 -> 130/289 -> 132/273) và robot không bao giờ về tuyến.
# ► Chỉnh: giữ `reference`. Chỉ đổi sang `current` khi runtime không cấp được tuyến tham chiếu
# (khi đó behavior tự quay về `current` kèm cảnh báo, không cần sửa gì).
rejoin_on: reference
# [m] Hành lang lệch tuyến cho phép quanh tuyến gốc của order. 0 = KHÔNG giới hạn.
# ► Chỉnh: giữ 0 cho tới khi biết dung sai thật của fleet master — đặt số mò còn tệ hơn tắt.
# Khi bật, đặt bằng chiều rộng hành lang mà fleet cho phép robot rời tuyến (thường 1–2 m).
# Đường vòng vượt hành lang sẽ bị TỪ CHỐI và thử ứng viên kế tiếp.
max_deviation: 0.0
# [s] Trần cho cả lượt recovery này (base cưỡng chế, khác `allocated_time` của một lượt SBPL).
# ► Chỉnh: phải > attempts_per_run * allocated_time (3 x 0.4 = 1.2 s) cộng dư địa, nếu không
# behavior bị cắt giữa chừng trước khi thử hết ứng viên.
timeout: 10.0
# Bảng symbol -> thư viện cho Boost.DLL. KHÔNG phải tham số tinh chỉnh — thiếu khoá `library_path`
# là nguyên nhân phổ biến nhất của lỗi "plugin build xong nhưng runtime báo không tìm thấy".
WaitRecovery:
library_path: librecovery_core_wait_recovery
ClearCostmapRecovery:
library_path: librecovery_core_clear_costmap_recovery
RotateRecovery:
library_path: librecovery_core_rotate_recovery
BackUpRecovery:
library_path: librecovery_core_back_up_recovery
DetourPathRecovery:
library_path: libsbpl_recovery
# =================================================================================================
# Instance SBPL RIÊNG cho detour — cùng .so với SBPLLatticePlanner, khác tuning.
#
# Vì sao không dùng chung: `DetourPathRecovery::onUpdate` gọi makePlan ĐỒNG BỘ trên control thread,
# nên `allocated_time` ở đây là trần thời gian control loop bị treo mỗi tick — `cancel`/`pause` từ
# host không được xử lý trong khoảng đó. Bản backup để 10.0 s là hợp lý cho vai trò của nó, nhưng
# treo loop 10 s thì không.
# =================================================================================================
SBPLDetourPlanner:
# KHÔNG có `library_path` ở đây: `SBPLDetourPlanner` không phải symbol, nó chỉ là namespace param.
# Việc nạp .so đi theo `planner_symbol: SBPLLatticePlanner` ở trên.
# Kiểu môi trường và thuật toán. XYThetaLattice là loại DUY NHẤT port này hỗ trợ.
# ► Chỉnh: `planner_type` có ARAPlanner (anytime, dùng epsilon) và ADPlanner (anytime + dynamic,
# tận dụng thay đổi costmap giữa hai lượt). Giữ ARAPlanner trừ khi đo được ADPlanner nhanh hơn.
environment_type: XYThetaLattice
planner_type: ARAPlanner
# [s] TRẦN CỨNG cho một lượt SBPL — cũng là trần treo control thread mỗi tick.
# ► Chỉnh: TĂNG nếu log nhiều `Solution not found` mà thời điểm trả về đúng bằng giá trị này (tức
# HẾT GIỜ). GIẢM nếu control loop bị giật khi detour chạy. Trả về sớm hơn nhiều giá trị này
# nghĩa là search CẠN STATE — tăng thêm cũng vô ích, vấn đề nằm ở goal không tới được.
allocated_time: 0.4
# Hệ số nới heuristic của ARA*: nghiệm đầu được phép đắt gấp `initial_epsilon` lần tối ưu, rồi
# thuật toán siết dần trong thời gian còn lại.
# ► Chỉnh: đây là nút ĐÁNH ĐỔI TỐC ĐỘ/CHẤT LƯỢNG quan trọng nhất.
# - TĂNG (5–15) = ra nghiệm rất nhanh nhưng đường xấu: gấp khúc, xoay tại chỗ, vòng xoắn.
# - GIẢM (1.0–2.0) = đường đẹp nhưng chậm, dễ hết giờ ở quãng xa.
# Đường vòng xấu mà vẫn ra nghiệm ⇒ giảm số này TRƯỚC khi đụng vào .mprim.
initial_epsilon: 2.0
# Số ô costmap thay đổi tối đa còn cho phép lập plan tăng dần; vượt ngưỡng thì lập lại từ đầu.
# ► Chỉnh: hiếm khi cần. GIẢM nếu nghi plan tăng dần đang dùng dữ liệu cũ.
force_scratch_limit: 10000
# Hướng tìm kiếm: true = từ start tới goal.
# ► Chỉnh: đổi sang false (backward) chỉ khi đo được nhanh hơn cho hình học tuyến của mình.
forward_search: true
# Bỏ ràng buộc heading tại điểm xuất phát: SBPL được phép giả định robot đã xoay sẵn theo hướng
# tới goal, phần xoay để local planner lo.
# ► Chỉnh: `true` làm mỗi lượt HỎNG chạy HAI lần search (log: "no solution with free start
# heading, retrying with actual robot heading"), và lượt thành công có thể chạy BA lần (thêm
# một lượt "realign"). Đặt `false` cho detour để tiết kiệm — detour chạy khi robot ĐANG BÁM plan
# nên heading thật đã xuôi theo tuyến. Chỉ để `true` nếu local planner có bước xoay tại chỗ đầu
# path (turn_around_priority).
free_start_heading: true
# [m/s] và [s] — dùng để quy quãng đường/góc thành CHI PHÍ thời gian, không phải giới hạn vận tốc
# thật của robot (giới hạn thật nằm ở local planner).
# ► Chỉnh: tỉ lệ giữa hai số này quyết định robot "thà đi vòng" hay "thà xoay tại chỗ".
# `timetoturn45degsinplace_secs` LỚN ⇒ xoay tại chỗ đắt ⇒ SBPL vẽ cung vòng thay vì xoay.
# Đặt sát tốc độ hành trình thật để chi phí phản ánh đúng thời gian.
nominalvel_mpersecs: 0.3
timetoturn45degsinplace_secs: 1.31
# File motion primitive: tập cử động cơ sở (tiến, lùi, cung rẽ, xoay tại chỗ) kèm hệ số chi phí.
# ► Chỉnh: `resolution_m` trong file PHẢI khớp resolution costmap (0.05 m), nếu không SBPL từ chối
# nạp. Hình dạng đường vòng (gấp khúc / xoắn / nhiều đoạn xoay tại chỗ) do các
# `additionalactioncostmult` trong file này quyết định — sinh lại bằng `Test/mprim_gen`. Nên
# dùng file RIÊNG cho detour, đừng đè file mà global planner đang dùng chung.
primitive_filename: /home/duongtd/rl_ws/mir_robot/mir_navigation/mprim/unicycle_highcost_5cm.mprim

View File

@@ -0,0 +1,15 @@
SBPLLatticePlanner:
library_path: libsbpl_lattice_planner
environment_type: XYThetaLattice
planner_type: ARAPlanner
allocated_time: 10.0
initial_epsilon: 1.0
force_scratch_limit: 10000
forward_search: true
# Bỏ ràng buộc heading xuất phát: local planner đã có bước quay tại chỗ đầu path
# (turn_around_priority) nên không cần SBPL vẽ cung quay đầu khi goal ở phía sau.
# Nếu không ra nghiệm, planner tự retry một lần với heading thật của robot.
free_start_heading: true
nominalvel_mpersecs: 0.3
timetoturn45degsinplace_secs: 1.31 # = 0.6 rad/s
primitive_filename: /home/duongtd/rl_ws/mir_robot/mir_navigation/mprim/unicycle_highcost_5cm.mprim

View File

@@ -0,0 +1,179 @@
LocalPlannerAdapter:
library_path: liblocal_planner_adapter
yaw_goal_tolerance: 0.017
xy_goal_tolerance: 0.03
min_approach_linear_velocity: 0.06
StanleyLocalPlanner:
library_path: libstanley_local_planner
# ============================================================================
# PROFILE MO PHONG (move_base2 runtime). Khac profile robot that
# (stanley_local_planner/cfg/...) dung 3 diem:
# steer_zero_offset 0.0 | heading_bias_mode "off" | steer_bias_gain 0.0
# (sim khong co zero servo / IMU anchor -> cac bo bu tat het)
# max_plan_tf_jump_rate 1.5 (dynamic TF sim jitter chu dich, 0.6 gay reset oan)
# ============================================================================
# ================= Robot limits =================
max_vel_x: 0.50 # [m/s] forward, > 0
min_vel_x: -0.25 # [m/s] reverse, < 0
wheel_base: 0.0 # [m] 0 = derive from TF front_axle_frame -> rear_axle_frame
front_axle_frame: "steer_link"
rear_axle_frame: "base_link"
# Two SEPARATE steering limits.
# Path tracking must not use a large angle: forward_vel_ scales with cos(delta) so it
# collapses to speed_base, and vel_steer = v/cos(steer) is guarded to 0 as cos -> 0.
# Pivoting in place uses the full 90 deg the hardware has.
steer_limit_standstill: 1.5708 # [rad] TO BE MEASURED - ceiling at |v| ~ 0
steer_limit_at_max_vel: 0.5000 # [rad] TO BE MEASURED - ceiling at |v| = max_vel_x
align_steer_angle: 1.5708 # [rad] steering while pivoting. Literal number, NOT M_PI/2
min_steer_angle: 0.20 # [rad] threshold for "steering is engaged"
max_steer_rate: 1.00 # [rad/s] measured by [DBG-STEER] 07/08: servo peak 1.08-1.35
# Measured zero offset of the steering channel, ADDED to every command.
# 05/08 log: robot driving straight while the encoder read +0.0373 rad (2.1 deg)
# -> the proportional law paid for it with a standing 5-8 cm cross-track error.
# BRIDGE until the servo encoder zero is calibrated; set back to 0.0 after that.
steer_zero_offset: 0.0 # [rad]
# ================= Goal tolerance =================
xy_goal_tolerance: 0.030 # [m] should match LocalPlannerAdapter
yaw_goal_tolerance: 0.020 # [rad]
goal_sq_dist_tol: 0.05 # [m^2] early exit of the closest-point scan
# ================= Control law (Stanley) =================
path_yaw_mode: "tangent" # tangent | bearing - "bearing" is the old behaviour, kept for rollback
control_gain_e: 2.0 # heading gain (path tangent - robot yaw)
control_gain_d: 1.5 # base cross-track gain
gain_cte_weight: 0.8 # added to k per |cross-track error| [1/m]
gain_heading_weight: 0.5 # added to k per |heading error| [1/rad]
gain_min: 0.5 # lower clamp of k
gain_max: 1.8 # upper clamp of k
soft_min_vel: 0.20 # [m/s] FLOOR of the atan2(k*e, v) denominator. NO ceiling
alpha_gain: 0.0 # steering low-pass [0..1]; 0 = off, max_steer_rate is used instead
curve_gain_e_bonus: 2.0 # added to control_gain_e in curve mode
tangent_window_pts: 3 # points averaged for the tangent when the plan carries no yaw
# Curve tracking rework (08/08): cross-track error is measured at the BASE in both
# directions (front-axle variants manufacture an L^2/2R curve phantom - the robot
# cut INSIDE curves forward and drifted OUTSIDE in reverse); the heading reference
# previews a short distance ahead symmetrically; the curve itself is carried by an
# explicit atan(L*kappa) feedforward. Swept optimum in sim (R=1.5/3.0, both
# directions): max error 0.013-0.016 m vs 0.061/0.129 before.
heading_preview: 0.10 # [m] heading (tangent) reference ahead of the base anchor
curve_feedforward_gain: 1.0 # atan(L*kappa) gain; 0 = OFF (rollback), 1.0 = geometric nominal
# ================= Heading bias (yawR - course, measured +0.030 rad 07/08) =========
# The yaw estimate leads the actual course by a constant that RE-ANCHORS differently
# every session (IMU absolute anchor), so it is learned online from course-over-ground
# instead of configured. A steering offset cannot compensate this: the heading
# REFERENCE is wrong, not the actuator.
heading_bias_mode: "off" # off = disabled
# log = estimate only, [DBG-YAWBIAS] prints the calib number
# apply= subtract the learned bias from the yaw being controlled
# (rollback in the field: switch to "log", no rebuild)
heading_bias_tau: 30.0 # [s] EMA time constant
heading_bias_min_vel: 0.45 # [m/s] below this the course is too noisy to learn from
heading_bias_clamp: 0.05 # [rad] ceiling of the APPLIED correction
heading_bias_min_samples: 60 # [cycles] learned samples required before applying
# ================= Steering bias (integrator, cleans up the residue) =============
# With heading_bias_mode: apply the main disturbance is handled above; the
# integrator only sweeps up what is left. Do NOT run both at full strength.
steer_bias_gain: 0.0 # [rad/(m*s)] SIM: 0 = OFF — plant sim khong co zero servo hay
# heading bias, integrator bat len chi tich nhieu.
# ROBOT THAT: 0.10 khi mode != apply, 0.02 khi mode = apply.
steer_bias_clamp: 0.05 # [rad] anti-windup ceiling
steer_bias_decay: 0.9999 # per-cycle bleed when the integrate conditions do not hold
# (robot that dung 0.9999 de bias song qua cac quang dung 30-60 s)
steer_bias_min_vel: 0.30 # [m/s] below this, do not integrate
steer_bias_max_heading_err: 0.10 # [rad] above this, do not integrate
# ================= Plan window / lookahead =================
max_global_plan_lookahead_dist: 3.0 # [m] window ceiling
min_lookahead: 0.50 # [m] window floor
min_lookahead_near_goal: 0.40 # [m] separate floor near the goal
dyn_lookahead_gain: 2.50 # [m/(m/s)] lookahead = min + gain*|v|
near_goal_freeze_dist: 0.50 # [m] below this: freeze yaw_path, run theta_d only
# Index continuity thresholds, given in METRES and converted to indices with the
# point spacing measured at runtime - the plan resolution is the global planner's
# choice, not a constant.
# The old code used fixed indices (back=3, fwd=15 ~ 0.75 m on a 0.05 m/point plan) and
# therefore never fired: at 1.2 m/s the robot covers 0.04 m = 0.8 index per 33 ms cycle.
# Applied to BOTH closest (window anchor) and target_idx_ (inside the core).
max_advance_dist: 0.20 # [m] forward travel allowed along the plan per cycle
max_back_dist: 0.10 # [m] backward travel allowed along the plan per cycle
# ================= Curvature =================
high_curvature: 0.30 # [1/m] above: shrink lookahead
mid_curvature: 0.20 # [1/m] above: cut the transform window
low_curvature: 0.10 # [1/m] above: enter curve mode
straight_confirm_steps: 110 # consecutive straight cycles before leaving curve mode
# ================= Speed profile =================
speed_base: 0.30 # [m/s] base of the cosine steering profile
curve_max_speed: 0.25 # [m/s] ceiling while curving
min_drive_speed: 0.07 # [m/s] floor while driving
accel_distance: 2.00 # [m] ramp length after leaving a curve
decel_min: 0.05 # [m/s per cycle] deceleration on predicted collision
decel_max: 0.10 # [m/s per cycle]
collision_horizon_factor: 2.0 # multiplies max_vel_x to get the collision check distance
# Braking-distance governor: v <= sqrt(2*a*d_to_stop). The horizon profile alone
# starts braking ~v*horizon out (1.5 m at 1.2 m/s, demanding ~1 m/s^2) — the drive
# cannot follow and the robot overshot 30 cm. The old build was saved by an
# accident (the bearing blow-up tripped the steer gate and cut the drive early).
goal_decel_limit: 0.40 # [m/s^2] TO BE MEASURED — must stay BELOW the drive's real brake.
# Braking starts at v^2/(2a): 1.8 m @ 1.2 m/s, 0.3 m @ 0.5 m/s
min_approach_speed: 0.06 # [m/s] approach floor so the sqrt profile still reaches the goal
# ================= Align / phase =================
heading_eps: 0.020 # [rad] heading error accepted as aligned
steer_eps: 0.020 # [rad] steering error accepted as "servo arrived"
heading_align_tol: 0.050 # [rad] gate for the final straight-line approach (was 0.01 = too tight)
near_goal_dist: 1.00 # [m] below this: enable the final straight mode
steer_realign_off: 0.503 # [rad] above this: CUT drive (0.16*pi)
steer_realign_on: 0.150 # [rad] below this: RESUME drive - must be smaller than _off
steering_active: 0.094 # [rad] above this the steering counts as active (0.03*pi)
segment_transition_threshold: 0.010 # [m]
segment_end_ratio: 0.05 # fraction of the segment left before advancing
xy_reached_gate_factor: 3.0 # multiplies xy_goal_tolerance; a 1-point window may only latch inside this
# ================= TF guard =================
# Measured on the robot: 225 map->odom jumps, max 12.381 m, coinciding with the
# localisation FinishTrajectory(1) 10:41:18 / AddTrajectory(2) 10:41:21. The source is
# outside this package; this is containment, not a cure.
tf_lookup_at_pose_stamp: true # true = look up at pose.header.stamp instead of "latest".
# "latest" returns a different entry each call when the
# buffer holds two map->odom transforms
transform_tolerance: 0.20 # [s] accepted age when looking up by timestamp
max_plan_tf_jump_rate: 1.50 # [m/s] threshold as a RATE, multiplied by the real elapsed time.
# SIM: 1.5 — dynamic TF sim jitter 0.02-0.065 m/chu ky; de 0.6
# thi budget ~0.02 m -> reject don 30/30, reset giua duong
# (log 08/08: 8 reset trong 2 luot lui). ROBOT THAT: 0.60.
max_plan_tf_jump_abs: 1.00 # [m] hard cap of the accepted step: the rate budget grows while
# the transform sits still, and without the cap a multi-metre
# step after a long static stretch would be accepted outright
max_plan_tf_yaw_jump: 0.20 # [rad] rotation threshold - the old code checked translation only
tf_reject_window_cycles: 30 # sliding window; exceeding it means a real relocalisation
tf_reject_ratio: 0.5 # reject fraction inside the window that triggers the reset
# ================= Debug =================
debug_tf: false # nhom log TF (accepted-step, authority, chi tiet reject, fallback).
# SIM: dynamic_tf nhieu chu dich -> tat cho log doc duoc.
# ROBOT THAT: bat lai (true) khi san TF that.
# Reset do reject keo dai van LUON duoc log bat ke cong tac nay.
debug_offset: true # [DBG-OFF] 5 Hz bam path + thong ke max/mean |e| moi luot cua
# (in kem dong DBG-CURVE exit) — soi lech trong duong cong.
debug_level: 2 # 0=off 1=on state change 2=throttled 1 Hz 3=every cycle
# 2 is safe as the operating default: this package throttles with
# its own per-purpose clocks (robot_cpp's log_*_throttle shares ONE
# static timer per function for the whole process, so its throttled
# lines silently eat each other - never rely on it).
# 3 produces >1800 lines/min at 30 Hz - field debugging only
StanleyDockingLocalPlanner:
library_path: libstanley_local_planner

View File

@@ -39,7 +39,7 @@ flowchart TB
%% ========== INTERFACE LAYER ========== %% ========== INTERFACE LAYER ==========
subgraph Interface["🔌 Interface Layer"] subgraph Interface["🔌 Interface Layer"]
direction TB direction TB
BaseNav["<b>📋 BaseNavigation</b><br/>━━━━━━━━━━━━━━━━<br/>🏗️ move_base_core::BaseNavigation<br/>🎯 Abstract Interface<br/>━━━━━━━━━━━━━━━━<br/>📍 moveTo, dockTo<br/>🔄 rotateTo, moveStraightTo<br/>⏸️ pause, resume, cancel<br/>📊 getRobotPose"] BaseNav["<b>📋 BaseNavigation</b><br/>━━━━━━━━━━━━━━━━<br/>🏗️ move_base_core::BaseNavigation<br/>🎯 Abstract Interface<br/>━━━━━━━━━━━━━━━━<br/>📍 moveTo (goal / order)<br/>🔄 executeInstantActions<br/>⏸️ pause, resume, cancel<br/>📊 getRobotPose"]
style Interface fill:#FFF3E0,stroke:#E65100,stroke-width:4px,color:#000 style Interface fill:#FFF3E0,stroke:#E65100,stroke-width:4px,color:#000
style BaseNav fill:#FFE0B2,stroke:#E65100,stroke-width:3px,font-size:14px style BaseNav fill:#FFE0B2,stroke:#E65100,stroke-width:3px,font-size:14px
end end
@@ -194,7 +194,7 @@ Cần làm rõ:
3. **Interface Layer** ✅ 3. **Interface Layer** ✅
- `move_base_core::BaseNavigation`: Abstract interface cho navigation - `move_base_core::BaseNavigation`: Abstract interface cho navigation
- Định nghĩa các operations: moveTo, dockTo, rotateTo, moveStraightTo, pause, resume, cancel - Định nghĩa các operations: moveTo (goal / order), executeInstantActions, pause, resume, cancel
- Là lớp trung gian định nghĩa các phương thức và thuộc tính liên quan đến navigation - Là lớp trung gian định nghĩa các phương thức và thuộc tính liên quan đến navigation
4. **Move Base Core** ✅ 4. **Move Base Core** ✅
@@ -288,9 +288,13 @@ Cần làm rõ:
- `move_base_core::BaseNavigation` ✅ - `move_base_core::BaseNavigation` ✅
- `initialize(TFListenerPtr)` - Khởi tạo với TF listener - `initialize(TFListenerPtr)` - Khởi tạo với TF listener
- `moveTo(goal, xy_tol, yaw_tol)` - Di chuyển đến goal - `moveTo(goal, xy_tol, yaw_tol)` - Di chuyển đến goal
- `dockTo(marker, goal, ...)` - Docking đến marker - `moveTo(order, goal, ...)` - Một order VDA5050, cắt thành từng chặng
- `rotateTo(goal, yaw_tol)` - Xoay tại chỗ - `executeInstantActions(actions)` - Một message `instantActions`, nở theo bảng compound
- `moveStraightTo(goal, xy_tol)` - Đi thẳng
> **2026-08-10:** `dockTo` ×2, `rotateTo`, `moveStraightTo` đã bị **gỡ khỏi interface**. Chúng đẩy
> goal thẳng vào lõi, bỏ qua mission layer, nên một goal đến giữa chừng thay thế chặng mà hàng đợi
> đang chạy. Docking / xoay tại chỗ / đi thẳng giờ là khoá `profile:` của từng chặng trong order
> (`compound_actions_params.yaml`), nên vẫn dùng được nguyên vẹn qua hai entry point còn lại.
- `pause()`, `resume()`, `cancel()` - Điều khiển trạng thái - `pause()`, `resume()`, `cancel()` - Điều khiển trạng thái
- `getRobotPose(...)` - Lấy vị trí robot - `getRobotPose(...)` - Lấy vị trí robot

View File

@@ -144,26 +144,14 @@ namespace NavigationExample
[return: MarshalAs(UnmanagedType.I1)] [return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_move_to_nodes_edges(NavigationHandle handle, IntPtr nodes, UIntPtr node_count, IntPtr edges, UIntPtr edge_count, PoseStamped goal); public static extern bool navigation_move_to_nodes_edges(NavigationHandle handle, IntPtr nodes, UIntPtr node_count, IntPtr edges, UIntPtr edge_count, PoseStamped goal);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] // navigation_dock_to, navigation_dock_to_order, navigation_dock_to_nodes_edges,
[return: MarshalAs(UnmanagedType.I1)] // navigation_move_straight_to and navigation_rotate_to no longer exist in the native
public static extern bool navigation_dock_to(NavigationHandle handle, string marker, PoseStamped goal); // library. They pushed a goal past the mission layer, so one of them arriving mid-route
// replaced the leg the mission queue was running without the queue noticing.
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)] //
[return: MarshalAs(UnmanagedType.I1)] // Docking, go-straight and rotate are per-leg properties of an order now: set `profile:`
public static extern bool navigation_dock_to_order(NavigationHandle handle, Order order, string marker, PoseStamped goal); // on the leg (`docking | go_straight | rotate`) plus `marker` for docking, then send it
// through navigation_move_to_order or navigation_move_to_nodes_edges.
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_dock_to_nodes_edges(NavigationHandle handle, string marker, Node[] nodes, Edge[] edges, PoseStamped goal);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_move_straight_to(NavigationHandle handle, double distance);
/// <summary>Rotate in place to align with target orientation (radians).</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_rotate_to(NavigationHandle handle, double goal_yaw);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)] [return: MarshalAs(UnmanagedType.I1)]

View File

@@ -405,8 +405,11 @@ namespace NavigationExample
goal.pose.orientation.w = 1.0; goal.pose.orientation.w = 1.0;
// Console.WriteLine("Docking to docking_point"); // Docking used to be its own call, navigation_dock_to(navHandle, "charger", goal).
NavigationAPI.navigation_dock_to(navHandle, "charger", goal); // It is a per-leg property of the order now: put `profile: docking` and `marker:
// charger` on the leg and send the order, so the leg gets the same mission id,
// lifecycle and cancel path as every other leg.
NavigationAPI.navigation_move_to(navHandle, goal);
// NavigationAPI.navigation_move_to_nodes_edges(navHandle, order.nodes, order.nodes_count, order.edges, order.edges_count, goal); // NavigationAPI.navigation_move_to_nodes_edges(navHandle, order.nodes, order.nodes_count, order.edges, order.edges_count, goal);
@@ -414,8 +417,6 @@ namespace NavigationExample
NavigationAPI.navigation_set_twist_linear(navHandle, 0.1, 0.0, 0.0); NavigationAPI.navigation_set_twist_linear(navHandle, 0.1, 0.0, 0.0);
NavigationAPI.navigation_set_twist_angular(navHandle, 0.0, 0.0, 0.2); NavigationAPI.navigation_set_twist_angular(navHandle, 0.0, 0.0, 0.2);
// NavigationAPI.navigation_move_straight_to(navHandle, 1.0);
while (true) while (true)
{ {
System.Threading.Thread.Sleep(100); System.Threading.Thread.Sleep(100);

View File

@@ -106,6 +106,45 @@ install(EXPORT nav_c_api-targets
option(BUILD_SHARED_LIBS "Build shared libraries" ON) option(BUILD_SHARED_LIBS "Build shared libraries" ON)
option(BUILD_TESTS "Build test programs" OFF) option(BUILD_TESTS "Build test programs" OFF)
# Test cho lớp chuyển đổi. Không cần dựng navigation thật: mọi thứ ở đây là chuyển đổi thuần và
# quản lý bộ nhớ, đúng chỗ tập trung rủi ro của gói này.
#
# Bật bằng: cmake -DBUILD_C_API_TESTS=ON, rồi chạy ./devel/lib/nav_c_api/test_convertor
option(BUILD_C_API_TESTS "Build the C API converter tests" OFF)
if(BUILD_C_API_TESTS OR BUILD_TESTS)
find_package(GTest QUIET)
if(GTest_FOUND OR GTEST_FOUND)
add_executable(test_convertor test/test_convertor.cpp)
target_link_libraries(test_convertor
PRIVATE
nav_c_api
${GTEST_BOTH_LIBRARIES}
pthread
)
target_include_directories(test_convertor
PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/include
${GTEST_INCLUDE_DIRS}
)
# Test phải build với cảnh báo bật: -w của thư viện che đúng nhóm lỗi mà test này đi tìm.
target_compile_options(test_convertor PRIVATE -Wall -Wextra)
set_target_properties(test_convertor PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
)
enable_testing()
add_test(NAME test_convertor COMMAND test_convertor)
message(STATUS "nav_c_api: converter tests enabled")
else()
message(WARNING "nav_c_api: GTest not found, converter tests skipped")
endif()
endif()
# Flags biên dịch # Flags biên dịch
# Warning flags - disabled to suppress warnings during build # Warning flags - disabled to suppress warnings during build
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic") # set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wpedantic")

View File

@@ -0,0 +1,500 @@
# Rà soát gói `c_api` — những chỗ chưa hoàn thiện
Phạm vi: `pnkx_nav_core/src/APIs/c_api`. Đọc toàn bộ `src/nav_c_api.cpp` (1396 dòng),
`src/convertor.cpp` (831), `src/std_msgs/Header.cpp`, `src/std_msgs/Time.cpp`, đối chiếu với
`include/nav_c_api.h` và với `Test/move_base2` ở phía sau.
Ràng buộc: **không đổi chữ ký hàm, không đổi chức năng chính**.
Ngày rà soát: 2026-08-08. **Đã sửa cùng ngày** — xem cột trạng thái ở mỗi mục và mục "Đã làm gì"
ở cuối. Một điểm nữa (**F25**) lộ ra trong lúc sửa, do chính bộ test mới bắt được.
---
## Tóm tắt
24 điểm, chia bốn mức. Ba điểm P0 là lỗi hành vi thật, không phải chuyện style:
| Mức | Số điểm | Bản chất |
|---|---|---|
| **P0** | 3 | Sai hành vi hoặc UB — ảnh hưởng trực tiếp tới robot |
| **P1** | 3 | Hợp đồng lỏng: host không phân biệt được lỗi với dữ liệu rỗng |
| **P2** | 6 | Rác debug, log sai cấp, format sai |
| **P3** | 5 | Khai báo và tài liệu lệch với hiện thực |
| **P4** | 7 | Nhỏ, nhất quán, hạ tầng |
Trong 24 điểm, **20 điểm sửa được mà không đụng chữ ký lẫn chức năng chính**. Bốn điểm còn lại
(F4, F5, F6 một phần, và phần capacity của F5) buộc phải hoặc đổi hợp đồng trả về, hoặc thêm hàm mới
song song — ghi rõ ở mục cuối.
---
## P0 — sai hành vi thật
### F1. `navigation_set_twist_linear` bỏ qua tham số `linear_x`
**Vị trí:** `src/nav_c_api.cpp:574-584`
```cpp
robot_geometry_msgs::Vector3 linear;
linear.x = 0.1; // <-- linear_x KHÔNG hề được dùng
linear.y = linear_y;
linear.z = linear_z;
bool result = nav_ptr->setTwistLinear(linear);
robot::log_info("setTwistLinear Forward %f", linear.x);
linear.x = -0.1; // <-- cũng hard-code
result &= result && nav_ptr->setTwistLinear(linear);
robot::log_info("setTwistLinear Backward %f", linear.x);
return result;
```
**Vấn đề.** Tham số `linear_x` của hàm không bao giờ được đọc. Trần vận tốc gửi xuống lõi luôn là
`+0.1 m/s` cho chiều tiến và `-0.1 m/s` cho chiều lùi, bất kể host truyền giá trị nào. Hai tham số
`linear_y` và `linear_z` thì lại được truyền đúng — đây là dấu hiệu code viết dở rồi bỏ quên, không
phải quyết định thiết kế.
**Ảnh hưởng lên hành vi robot.** Hai chiều, đều xấu:
1. Đường hạ tốc của tầng an toàn không tới được lõi. Host tính ra "chỉ được chạy 0.3 m/s vì đang vào
vùng hẹp" rồi gọi hàm này — lõi nhận 0.1 m/s. Ngược lại host muốn nâng lên 1.0 m/s cũng chỉ nhận
được 0.1.
2. Ngay khi host gọi hàm này lần đầu, robot bị khoá ở 0.1 m/s cho tới hết phiên chạy. Nếu host chỉ
gọi khi cần giảm tốc thì robot sẽ không bao giờ về lại tốc độ bình thường.
**Lỗi thứ hai trong cùng hàm.** `result &= result && nav_ptr->setTwistLinear(linear)` — toán tử `&&`
short-circuit: nếu lời gọi đầu trả `false` thì lời gọi thứ hai **không chạy**, nên trần chiều lùi
không được đặt. Ý định rõ ràng là gọi cả hai rồi AND kết quả lại.
**Đã sửa.** Hợp đồng đúng: giá trị đi xuống lõi **nguyên dạng, giữ dấu**. Dấu của `linear_x` là thứ
chọn chiều mà trần áp vào — âm đặt trần lùi, dương đặt trần tiến; local planner giữ hai trần riêng
(`navigation_server.cpp:921-944`). Lấy trị tuyệt đối là vứt bỏ nửa thông tin của lời gọi.
Một lời gọi vì thế đặt **một** chiều. Host muốn chặn cả hai thì gọi hai lần — đúng như host ROS đang
làm (`amr_control.cpp:707-709`, `amr_vda_5050_client_api.cpp:410-414`).
```c
navigation_set_twist_linear(h, 0.6, 0.0, 0.0); // tiến <= 0.6 m/s
navigation_set_twist_linear(h, -0.3, 0.0, 0.0); // lùi <= 0.3 m/s
```
---
### F2. Gán `char*` có thể NULL vào `std::string`
**Vị trí:** `src/convertor.cpp:13` (LaserScan), `:44` (OccupancyGrid), `:115` (PoseStamped)
```cpp
robot_laser_scan.header.frame_id = laser_scan.header.frame_id; // char* có thể NULL
```
**Vấn đề.** Dựng `std::string` từ con trỏ NULL là hành vi không xác định — thực tế là segfault trong
`strlen`. Các converter khác trong **chính file này** đều đã guard:
| Đã guard | Chưa guard |
|---|---|
| `convert2CppOdometry:73,75` | `convert2CppLaserScan:13` |
| `convert2CppPointCloud:383` | `convert2CppOccupancyGrid:44` |
| `convert2CppPointCloud2:408` | `convert2CppPoseStamped:115` |
| `convert2CppOrder:731-745` | |
| `convert2CppNode`, `convert2CppEdge`, `convert2CppAction`, `convert2CppNodePosition` | |
Nghĩa là quy ước "guard NULL" đã có sẵn và được áp dụng ở 7 chỗ; ba chỗ này bị bỏ sót.
**Ảnh hưởng.** `frame_id = NULL` hoàn toàn hợp lệ trong C, và **chính thư viện này sinh ra NULL**:
`convert2COccupancyGrid:181` viết `frame_id.empty() ? nullptr : strdup(...)`. Nên vòng
`navigation_get_static_map()` rồi `navigation_add_static_map()` — hoặc bất kỳ đường round-trip nào
qua một message có `frame_id` rỗng — là segfault chắc chắn.
**Hướng sửa.** Thêm `? :` đúng như 7 chỗ còn lại. Không đụng chữ ký, không đổi chức năng.
---
### F3. `strdup(frame_id)` không kiểm NULL
**Vị trí:** `src/std_msgs/Header.cpp:8` (`header_create`) và `:18` (`header_set_data`)
```cpp
extern "C" Header header_create(const char *frame_id) {
Header header{};
header.frame_id = strdup(frame_id); // NULL -> segfault
```
**Vấn đề.** `strdup(NULL)` là UB. Hai hàm này nằm trong bề mặt công khai và C# gọi trực tiếp
(`NavigationAPI.cs:69,72`).
**Hướng sửa.** `frame_id ? strdup(frame_id) : nullptr`.
---
## P1 — hợp đồng lỏng, host không phân biệt được lỗi
### F4. Bốn getter sensor luôn trả `true` kể cả khi tên không tồn tại
**Vị trí:** `src/nav_c_api.cpp:858` (`get_static_map`), `:882` (`get_laser_scan`), `:906`
(`get_point_cloud`), `:930` (`get_point_cloud2`)
**Vấn đề.** `move_base2::NavigationServer::getStaticMap` dùng `lookupOrDefault`
(`navigation_server.cpp:607-611`): tên không có trong map thì trả về object mặc định, không báo lỗi.
`c_api` chuyển thẳng object rỗng đó ra rồi `return true`.
**Ảnh hưởng.** Host nhận `OccupancyGrid` với `width = 0`, `data = NULL` và một giá trị trả về `true`.
Không có cách nào phân biệt "bản đồ tồn tại nhưng rỗng" với "gõ sai tên bản đồ". Sai tên là lỗi cấu
hình phổ biến nhất ở đường sensor (tên phải khớp `topic` trong YAML costmap) — mà nó lại đúng là
trường hợp API im lặng nhất.
**Hướng sửa.** Không sửa được nếu giữ nguyên chữ ký lẫn ngữ nghĩa: contract `BaseNavigation` không có
đường báo "không tìm thấy". Ba lựa chọn, đều nằm ngoài ràng buộc đợt này:
(a) tài liệu hoá rõ trong header rằng `true` không có nghĩa là tìm thấy;
(b) đổi quy ước: trả `false` khi kết quả rỗng — **đổi hành vi**, có thể vỡ host đang chạy;
(c) thêm hàm `navigation_has_static_map(handle, name)` bên `nav_c_api_2` để hỏi trước.
Khuyến nghị: (a) ngay, (c) khi có dịp.
---
### F5. Bốn hàm `get_all_*` và `get_robot_footprint` ghi vào mảng caller mà không biết dung lượng
**Vị trí:** `src/nav_c_api.cpp:954`, `:985`, `:1021`, `:1057`, và `:203`
(`navigation_get_robot_footprint`)
```cpp
auto maps = nav_ptr->getAllStaticMaps();
out_count = maps.size();
size_t i = 0;
for (const auto &p : maps)
{
out_maps[i].name = strdup(p.first.c_str()); // ghi mù, không biết mảng dài bao nhiêu
convert2COccupancyGrid(p.second, out_maps[i].grid);
++i;
}
```
**Vấn đề.** Chữ ký chỉ có con trỏ ra và `size_t &out_count` (là tham số **ra**, không phải vào). Hàm
không có cách nào biết mảng host cấp đủ chỗ hay không, và ghi đúng bằng số phần tử nó có.
**Ảnh hưởng.** Host cấp mảng 4 phần tử, lõi đang giữ 6 point cloud → ghi tràn 2 phần tử. Với
`NamedOccupancyGrid` mỗi phần tử là một struct lớn, nên tràn không phải một byte mà hàng chục byte
ra ngoài vùng — hỏng stack hoặc heap của host, và triệu chứng sẽ hiện ra ở chỗ hoàn toàn khác.
**Hướng sửa.** Không sửa được mà giữ chữ ký. Hai lựa chọn:
(a) ghi cảnh báo trong header, nói rõ host phải cấp dư và bao nhiêu là đủ;
(b) thêm biến thể có `size_t capacity` bên `nav_c_api_2`, giữ nguyên hàm cũ.
---
### F6. `navigation_initialize` luôn trả `true`
**Vị trí:** `src/nav_c_api.cpp:127`
**Vấn đề.** `BaseNavigation::initialize()` trả `void`, nên `c_api` `return true` ngay sau khi gọi.
`move_base2` có năm đường thất bại trong `initialize()` (dựng costmap, cấu hình sensor, nạp plugin,
cấu hình control loop, start control thread — `navigation_server.cpp:340-479`), mỗi đường chỉ đặt
`nav_feedback_->is_ready = false` kèm lý do rồi return bình thường.
**Ảnh hưởng.** Host tưởng lõi đã sẵn sàng, gửi goal vào một lõi không có control thread. Goal nằm im
vĩnh viễn: không cycle nào chạy, không state nào đổi, **không log gì**.
**Hướng sửa.** Đã có sẵn: `navigation_initialize_checked()` trong `nav_c_api_2` làm đúng việc này mà
không đụng hàm cũ. Còn lại là chuyện host đổi sang gọi hàm mới.
---
## P2 — rác debug, log sai cấp, format sai
| # | Vị trí | Vấn đề | Ảnh hưởng |
|---|---|---|---|
| **F7** | `convertor.cpp:36-39` | `log_info` in `sizeof(OccupancyGrid)`, `offsetof(data)`, `offsetof(data_count)` **mỗi lần** convert map | Leftover của một lần dò lệch ABI. Chạy trên mọi `add_static_map` |
| **F8** | `nav_c_api.cpp:190` | `printf("footprint x: %f, y: %f")` **trong vòng lặp từng điểm** | Footprint 8 điểm = 8 dòng mỗi lần đặt footprint |
| **F9** | `nav_c_api.cpp:284, 319` (call site `move_straight_to` đã bị xoá cùng hàm) | `log_error` dùng để in giá trị bình thường: goal của `move_to_order`, goal của `move_to_nodes_edges` | Sai cấp log. Ai lọc log theo mức ERROR sẽ thấy toàn dữ liệu bình thường, lỗi thật bị chìm |
| **F10** | `nav_c_api.cpp:86` | `log_warning("%s", path_file_so.c_str())` in đường dẫn `.so` mỗi lần `navigation_create` | Sai cấp; nên là `log_info` hoặc `log_debug` |
| **F11** | `nav_c_api.cpp:748` | `log_info("occupancy_grid.data_count: %d", occupancy_grid.data_count)` — `%d` cho `size_t` | Format không khớp kiểu: UB, in ra số sai trên 64-bit. Bị `-w` che nên không có warning |
| **F12** | 9 chỗ trong `nav_c_api.cpp` | `printf` trộn lẫn với `robot::log_*` | Hai hệ log song song. `printf` đi thẳng stdout, không vào file log, không có timestamp, không lọc theo mức được |
Tất cả P2 sửa được mà không đụng chữ ký lẫn chức năng.
---
## P3 — khai báo và tài liệu lệch với hiện thực
### F13. Ba symbol export nhưng không khai báo trong header
`navigation_state_to_string` (`nav_c_api.cpp:38`), `navigation_offset_goal_2d` (`:51`),
`navigation_offset_goal_stamped` (`:66`).
Binding theo tên symbol (P/Invoke) vẫn gọi được, nhưng bên gọi C/C++ include `nav_c_api.h` thì không
thấy. `NavigationAPI.cs:87` đang khai báo tay `navigation_state_to_string` — đúng, nhưng là đoán.
### F14. Header nhắc tới một hàm không tồn tại
`include/nav_c_api.h:119`:
> `@param out_points Output array of points (allocated by library, free with navigation_free_points)`
`navigation_free_points` **không tồn tại ở đâu cả** — không khai báo, không hiện thực, không export.
Ngoài ra câu này còn sai thêm một tầng: `out_points` **không** do thư viện cấp phát, nó là mảng của
caller (xem F5).
### F15. Doc của `navigation_rotate_to` mô tả một chữ ký khác
> **Không còn áp dụng, 2026-08-10.** `navigation_rotate_to` đã bị **xoá khỏi API** cùng nhóm
> `navigation_dock_to*` và `navigation_move_straight_to` — chúng đi thẳng xuống lõi, bỏ qua mission
> layer. Binding C# sai chữ ký nói ở đây vì thế cũng đã được gỡ. Giữ lại mục này làm ghi chép: bug
> gốc là **binding đọc doc thay vì đọc chữ ký**, và rủi ro đó không mất đi cùng hàm.
`include/nav_c_api.h:196-202`:
```c
/**
* @brief Rotate in place to align with target orientation
* @param handle Navigation handle
* @param goal_yaw Desired heading (radians) <-- không có tham số nào tên goal_yaw
* @return true if rotation command was sent successfully
*/
bool navigation_rotate_to(NavigationHandle handle, const PoseStamped goal);
```
**Đây gần như chắc chắn là nguồn của một bug đang tồn tại phía C#.**
`examples/NavigationExample/NavigationAPI.cs:165` khai báo:
```csharp
public static extern bool navigation_rotate_to(NavigationHandle handle, double goal_yaw);
```
Người viết binding đọc doc chứ không đọc chữ ký. Hậu quả ở tầng ABI: C# đẩy một `double` vào `xmm0`,
C đọc một `PoseStamped` (struct lớn) từ stack — goal nhận được là rác, `isQuaternionValid` sẽ chặn
hoặc `frame_id` là con trỏ rác.
### F16. Header khai `extern "C"` nhưng dùng tham chiếu C++
`size_t &out_count`, `PoseStamped &out_pose`, `OccupancyGrid &out_map`… Trình biên dịch C thuần không
dịch được file này. ABI thì vẫn là con trỏ nên P/Invoke không bị ảnh hưởng. Không sửa được mà giữ chữ
ký — chỉ ghi nhận.
### F17. Ghi chú giải phóng bộ nhớ không đầy đủ
`nav_c_api.h:265` có nhắc `out_twist->header.frame_id` phải free; `:274` nhắc `feed_back_str`. Nhưng
`navigation_get_robot_pose_stamped` (`:250`) cũng `strdup` `frame_id` (`convertor.cpp:134`) mà doc
không nhắc gì. Bốn getter sensor và hai getter planner data cũng cấp phát mà doc không nói (nay đã có
`navigation_free_*` bên `nav_c_api_2`, nhưng doc của header cũ chưa trỏ sang).
---
## P4 — nhỏ, nhất quán, hạ tầng
### F18. `resize()` trước khi kiểm con trỏ NULL
`convertor.cpp:384` (`convert2CppPointCloud`) và `:423` (`convert2CppPointCloud2`):
```cpp
cpp.points.resize(c.points_count); // resize trước
for (size_t i = 0; i < c.points_count && c.points; ++i) // kiểm NULL sau
```
Nếu host truyền `points = NULL` nhưng `points_count` lớn thì `resize` vẫn cấp phát đủ chỗ rồi vòng
lặp không chạy. Không crash, nhưng cấp phát vô ích có thể rất lớn. `convert2CppLaserScan:21-22` làm
đúng: tính size đã guard trước rồi mới resize.
### F19. `get_all_static_maps` lệch với ba hàm cùng nhóm
`nav_c_api.cpp:954` không có nhánh `if (empty()) { out_count = 0; return true; }` mà `:1000`, `:1036`,
`:1072` đều có. Kết quả cuối giống nhau (vòng lặp không chạy, `out_count = 0`), chỉ là lệch hình thức.
### F20. `header_create` đọc đồng hồ hai lần
`std_msgs/Header.cpp:9-10`:
```cpp
header.sec = robot::Time::now().sec;
header.nsec = robot::Time::now().nsec;
```
Hai lời gọi riêng biệt. Nếu rơi đúng lúc `nsec` vòng qua giây thì `sec` lấy từ lần đọc trước còn
`nsec` từ lần sau — timestamp lệch tới một giây. Xác suất thấp nhưng hậu quả nằm ở TF lookup.
### F21. `catch (...)` nuốt lỗi không log
Phần lớn hàm kết thúc bằng `catch (...) { return false; }` trần. Host chỉ nhận `false`, không có cách
nào biết vì sao. `navigation_create` (`:100-107`) còn nuốt cả `std::exception &e` mà không in `e.what()`
— trong khi đây đúng là chỗ hay hỏng nhất (không tìm thấy `.so`, sai `library_path`).
### F22. CMake guard không bao giờ khớp
`pnkx_nav_core/CMakeLists.txt:237`: `if (NOT TARGET navigation_c_api)` — nhưng target thật tên
`nav_c_api` (`src/APIs/c_api/CMakeLists.txt:61`). Guard vô tác dụng; `.so` sinh ra là
`libnav_c_api.so`, không phải `libnavigation_c_api.so` như tài liệu ở nơi khác ghi.
### F23. Không có test nào
`src/APIs/c_api/` không có thư mục `test/`. Không có test đơn vị cho lớp converter — nơi tập trung
gần hết các lỗi P0 ở trên và là nơi test rẻ nhất (không cần dựng navigation thật).
### F24. Năng lực contract chưa phơi ra ở bề mặt cũ
`BaseNavigation` có `addDepthCameraData()` (thuần ảo) và `shutdown()` mà `nav_c_api.h` không có hàm
tương ứng. Đã bù bằng `navigation_add_depth_camera_data()` và `navigation_shutdown()` trong
`nav_c_api_2`; ghi lại ở đây để bảng rà soát đầy đủ.
---
## Sửa được gì trong ràng buộc "không đổi chữ ký, không đổi chức năng chính"
**Sửa được ngay — 20 điểm:** F1, F2, F3, F7, F8, F9, F10, F11, F12, F13, F14, F15, F17, F18, F19,
F20, F21, F22, F23, và phần tài liệu của F5.
- F1 là làm cho hàm **thực hiện đúng chức năng nó đã khai** — dùng tham số thay vì hằng số. Chữ ký
không đổi, mục đích không đổi.
- F2, F3, F18, F20, F21 là bổ sung guard và sửa lỗi nhỏ, không chạm hợp đồng.
- F7–F12 là dọn log.
- F13–F15, F17 là sửa khai báo và doc cho khớp hiện thực — F15 quan trọng vì nó đang dẫn người viết
binding đi sai.
**Không sửa được mà giữ nguyên chữ ký — 3 điểm:**
| # | Vì sao | Lối ra |
|---|---|---|
| **F4** | Cần một đường báo "không tìm thấy" mà chữ ký hiện tại không có | Tài liệu hoá ngay; thêm `navigation_has_*` bên `nav_c_api_2` khi có dịp |
| **F5** | Cần tham số `capacity` | Tài liệu hoá ngay; thêm biến thể có `capacity` bên `nav_c_api_2` |
| **F16** | Bỏ tham chiếu C++ khỏi header là đổi chữ ký toàn bộ | Ghi nhận; chỉ đổi nếu có đợt phá vỡ ABI |
Riêng **F6** đã có lối ra không phá vỡ gì: `navigation_initialize_checked()` đã tồn tại.
---
## Thứ tự đề nghị
1. **F1** — một mình nó đủ khiến trần vận tốc không hoạt động. Cần chốt ý định trước (xem dưới).
2. **F2, F3** — ba dòng guard, chặn ba đường segfault.
3. **F15, F14, F13** — sửa doc và khai báo, vì chúng đang tạo ra bug ở phía binding.
4. **F7–F12** — dọn log, gộp một lần.
5. **F23** — một binary GTest cho riêng lớp converter: `frame_id` NULL, mảng NULL với count > 0,
`Order` với mọi trường NULL, round-trip C++ → C → C++. Không cần dựng navigation thật.
6. **F4, F5** — chốt hướng rồi mới làm.
---
## Câu hỏi mở — cần xác nhận trước khi sửa
1. ~~**F1 — ý định của `navigation_set_twist_linear` là gì?**~~ **Đã chốt:** truyền nguyên dạng, dấu
chọn chiều, một lời gọi đặt một chiều. Xem F1.
2. **Giá trị `0.1` cũ có phải trần an toàn cố ý của một lần thử nghiệm không?** Nếu đúng là có chủ ý
thì nó phải nằm trong YAML chứ không phải hard-code trong lớp binding — và sau bản sửa này robot
sẽ chạy đúng tốc độ host yêu cầu, không còn bị kẹp ở 0.1 m/s. **Cần biết trước khi chạy thật.**
3. **F4 — có host nào đang dựa vào việc getter luôn trả `true` không?** Nếu không, đổi sang trả
`false` khi rỗng là hợp lý hơn nhiều — nhưng đó là đổi hành vi.
4. **Phía C# hiện có đang gọi `header_create` với `frame_id` NULL không** (F3), và có gọi
`navigation_get_all_*` với mảng cấp sẵn bao nhiêu phần tử (F5)?
---
## F25 — hàm được khai báo và được gọi nhưng chưa bao giờ hiện thực
**Vị trí:** `include/convertor.h:137` khai báo, `src/nav_c_api.cpp:61` gọi, **không có định nghĩa ở
đâu cả**.
```cpp
robot_geometry_msgs::Pose2D convert2CppPose2D(const Pose2D& pose_2d); // chỉ có khai báo
```
**Vì sao không ai phát hiện.** Thư viện chia sẻ được phép link với symbol chưa phân giải: `.so` build
sạch, không một cảnh báo nào. Symbol nằm im trong bảng undefined:
```
$ nm -D --undefined-only libnav_c_api.so | grep convert2CppPose2D
U _Z17convert2CppPose2DRK6Pose2D
```
**Ảnh hưởng.** `navigation_offset_goal_2d()` — hàm duy nhất gọi nó — chết ngay ở lời gọi đầu tiên với
`symbol lookup error`, hoặc làm `dlopen` thất bại tuỳ cách nạp. Hàm này chưa bao giờ chạy được.
**Cách nó lộ ra.** Không phải do đọc mã. Bộ test mới (F23) link một **executable** vào thư viện, và
executable thì không được phép có symbol chưa phân giải — trình liên kết báo ngay. Đây đúng là lý do
bộ test tồn tại.
**Trạng thái: đã sửa** — hiện thực trong `convertor.cpp` ngay cạnh `convert2CPose2D`.
---
## Đã làm gì
Sửa **21/25 điểm**, giữ nguyên chữ ký và chức năng chính của mọi hàm.
| Nhóm | Điểm | Trạng thái |
|---|---|---|
| P0 | F1, F2, F3 | Đã sửa |
| P1 | F6 | Đã có `navigation_initialize_checked` từ trước; header nay trỏ sang nó |
| P1 | F4, F5 | Không sửa được mà giữ chữ ký — **đã ghi cảnh báo rõ trong header** |
| P2 | F7–F12 | Đã sửa |
| P3 | F13, F14, F15, F17 | Đã sửa |
| P3 | F16 | Không sửa — cần phá vỡ ABI |
| P4 | F18, F19, F20, F21, F22, F23 | Đã sửa |
| P4 | F24 | Đã bù từ trước bằng `nav_c_api_2` |
| — | **F25** | Đã sửa |
### File đã chạm
| File | Thay đổi |
|---|---|
| `src/nav_c_api.cpp` | F1 (dùng `linear_x` thật, bỏ short-circuit), F8–F12 (bỏ 9 `printf`, chuyển sang `robot::log_*`, hạ cấp log debug), F19, F21 (log lý do trong `catch`) |
| `src/convertor.cpp` | F2 (`safe_cstr` cho 3 chỗ), F7 (bỏ log ABI), F18 (lấy kích thước từ con trỏ), **F25** |
| `src/std_msgs/Header.cpp` | F3 (`strdup` chấp nhận NULL), F20 (đọc đồng hồ một lần) |
| `include/nav_c_api.h` | F13 (3 khai báo thiếu), F14, F15, F17, cảnh báo F4/F5/F6, đơn vị `[m/s]`/`[rad/s]` |
| `CMakeLists.txt` (gói) | F22 sửa tên target trong guard; thêm nhánh build test |
| `../../../CMakeLists.txt` | F22 |
| `test/test_convertor.cpp` | **Mới** — F23 |
### Hai thay đổi cần chú ý khi đọc diff
**F1 — `navigation_set_twist_linear` giờ truyền `linear_x` nguyên dạng, giữ dấu.** Dấu chọn chiều:
âm đặt trần lùi, dương đặt trần tiến; một lời gọi đặt một chiều. **Đây là thay đổi hành vi thật** —
trước đó trần luôn là ±0.1 m/s bất kể host truyền gì. Host nào từng "quen" với việc robot chạy
0.1 m/s sẽ thấy robot chạy đúng tốc độ nó yêu cầu kể từ bản này.
**F5 — vẫn còn ghi mù.** Cảnh báo đã vào header nhưng bản chất không đổi: `get_all_*` và
`get_robot_footprint` vẫn ghi theo số phần tử lõi đang giữ. Nếu muốn chặn thật thì phải thêm biến thể
có `capacity` bên `nav_c_api_2`.
---
## Đã kiểm chứng tới đâu
**Lệnh đã chạy và kết quả thật:**
```
$ cmake -S . -B build -DBUILD_C_API_TESTS=ON
-- nav_c_api: converter tests enabled
$ cmake --build build --target nav_c_api test_convertor -j4
[100%] Built target nav_c_api
[100%] Built target test_convertor
$ ./build/test_convertor
[==========] 20 tests from 6 test cases ran. (0 ms total)
[ PASSED ] 20 tests.
$ nm -D --undefined-only build/libnav_c_api.so | grep -E "convert2|isQuaternion|order_free|header_"
(không còn)
$ g++ -std=c++17 -Wall -Wextra -fsyntax-only # cả 5 file nguồn
nav_c_api OK (0 warning)
convertor OK (0 warning)
nav_c_api_2 OK (0 warning)
convertor_2 OK (0 warning)
Header.cpp OK
```
20 test phủ: `frame_id` NULL trên 4 loại message, mảng NULL kèm bộ đếm khác 0 trên 3 loại, round-trip
C++ → C → C++ cho OccupancyGrid và LaserScan, `Order` zero-init và `Order` có node/edge với chuỗi
NULL, chuyển đổi depth camera (gồm kiểm tra copy chứ không alias), 5 hàm `navigation_free_*` (gọi với
NULL, gọi hai lần, giải phóng buffer lồng nhau), và `isQuaternionValid`.
**Chưa kiểm chứng:**
- Chưa chạy trên robot hay Gazebo. Không có test tích hợp nào dựng navigation thật.
- **F1 chưa được xác nhận trên phần cứng.** Trần vận tốc giờ đi đúng giá trị host truyền — cần một
lần chạy thật để xác nhận robot không vọt quá tốc độ mong đợi, vì trước đây nó luôn bị kẹp ở
0.1 m/s. Đây là thay đổi cần chú ý nhất khi triển khai.
- `valgrind` chưa cài trên máy này, nên phần rò bộ nhớ của các hàm `free` mới chỉ được kiểm bằng
kiểm tra con trỏ sau khi giải phóng, không bằng công cụ.
- Bốn câu hỏi mở ở mục trên vẫn còn nguyên; F1 đã tự trả lời được bằng cách đọc host ROS, ba câu còn
lại vẫn cần phía host xác nhận.

File diff suppressed because it is too large Load Diff

View File

@@ -180,6 +180,17 @@ Twist2DStamped convert2CTwist2DStamped(const robot_nav_2d_msgs::Twist2DStamped&
*/ */
robot_protocol_msgs::Order convert2CppOrder(const Order& order); robot_protocol_msgs::Order convert2CppOrder(const Order& order);
/**
* @brief Convert a C Action to a C++ Action.
*
* Null char* fields become empty strings, so a partially filled struct converts without crashing —
* the callee validates content, this only crosses the language boundary.
*
* @param action C Action
* @return C++ Action
*/
robot_protocol_msgs::Action convert2CppAction(const Action& action);
/** /**
* @brief Convert C++ Order to C Order * @brief Convert C++ Order to C Order
* @param cpp_order C++ Order * @param cpp_order C++ Order

View File

@@ -0,0 +1,51 @@
#ifndef C_API_CONVERTOR_2_H
#define C_API_CONVERTOR_2_H
/**
* @file convertor_2.h
* @brief Converters that only the move_base2 entry points need.
*
* Kept apart from convertor.h so the move_base2 surface can be added, reviewed and reverted without
* touching the converters the existing binding already depends on.
*/
// C
#include "std_msgs/Header.h"
#include "sensor_msgs/Image.h"
#include "sensor_msgs/CameraInfo.h"
#include "sensor_msgs/DepthCameraData.h"
// C++
#include <robot_std_msgs/Header.h>
#include <robot_sensor_msgs/Image.h>
#include <robot_sensor_msgs/CameraInfo.h>
#include <robot_sensor_msgs/DepthCameraData.h>
/**
* @brief Convert C Header to C++ Header.
* @param header C header; `frame_id` may be NULL (becomes an empty string).
*/
robot_std_msgs::Header convert2CppHeader(const Header& header);
/**
* @brief Convert C Image to C++ Image.
*
* The pixel buffer is copied, so the caller keeps ownership of `image.data` and may free it as
* soon as this call returns.
*
* @param image C image; `data` and `encoding` may be NULL.
*/
robot_sensor_msgs::Image convert2CppImage(const Image& image);
/**
* @brief Convert C CameraInfo to C++ CameraInfo.
* @param info C camera info; `D` and `distortion_model` may be NULL. K/R/P are fixed size (9/9/12).
*/
robot_sensor_msgs::CameraInfo convert2CppCameraInfo(const CameraInfo& info);
/**
* @brief Convert C DepthCameraData to C++ DepthCameraData. Everything is deep-copied.
*/
robot_sensor_msgs::DepthCameraData convert2CppDepthCameraData(const DepthCameraData& data);
#endif // C_API_CONVERTOR_2_H

View File

@@ -79,6 +79,34 @@ extern "C"
*/ */
void nav_c_api_free_string(char *str); void nav_c_api_free_string(char *str);
/**
* @brief Name of a navigation state, for logging.
* @return Newly allocated string; free with nav_c_api_free_string().
*/
char *navigation_state_to_string(NavigationState state);
/**
* @brief Offset a 2D pose along its own heading.
* @param in_pose Source pose.
* @param frame_id Frame the result is expressed in; must not be NULL.
* @param offset_distance [m] Positive moves forward, negative backward.
* @param out_goal Result. `out_goal.header.frame_id` is allocated — free it with
* nav_c_api_free_string().
* @return false if @p frame_id is NULL.
*/
bool navigation_offset_goal_2d(const Pose2D &in_pose, const char *frame_id,
double offset_distance, PoseStamped &out_goal);
/**
* @brief Offset a stamped pose along its own heading, keeping its frame.
* @param in_pose Source pose.
* @param offset_distance [m] Positive moves forward, negative backward.
* @param out_goal Result. `out_goal.header.frame_id` is allocated — free it with
* nav_c_api_free_string().
*/
bool navigation_offset_goal_stamped(const PoseStamped &in_pose, double offset_distance,
PoseStamped &out_goal);
/** /**
* @brief Create a new navigation instance * @brief Create a new navigation instance
* @return Navigation handle, or NULL on failure * @return Navigation handle, or NULL on failure
@@ -100,7 +128,16 @@ extern "C"
* Caller retains ownership of the buffer and must call tf3_buffer_destroy when done (after navigation_destroy). * Caller retains ownership of the buffer and must call tf3_buffer_destroy when done (after navigation_destroy).
* @param handle Navigation handle * @param handle Navigation handle
* @param tf3_buffer Pointer to tf3 BufferCore (TF3_BufferCore from libtf3) * @param tf3_buffer Pointer to tf3 BufferCore (TF3_BufferCore from libtf3)
* @return true on success, false on failure * @return true if the arguments were valid and the call did not throw — **not** whether the core
* actually came up. The underlying contract method returns void, so a runtime that fails
* to build its costmaps or load its plugins still returns here normally.
*
* @warning Blocking and expensive: it builds the costmaps, loads every plugin named in the YAML
* and starts the control thread. Do not call it from a UI thread.
* @warning Push at least one static map with navigation_add_static_map() **before** this call.
* The lattice planner blocks until the costmap has a non-zero size, and aborts the whole
* process if it waits too long.
* @see navigation_initialize_checked() in nav_c_api_2.h, which reports the real outcome.
*/ */
bool navigation_initialize(NavigationHandle handle, TFListenerHandle tf3_buffer); bool navigation_initialize(NavigationHandle handle, TFListenerHandle tf3_buffer);
@@ -116,9 +153,15 @@ extern "C"
/** /**
* @brief Get the robot's footprint (outline shape) * @brief Get the robot's footprint (outline shape)
* @param handle Navigation handle * @param handle Navigation handle
* @param out_points Output array of points (allocated by library, free with navigation_free_points) * @param out_points Array **the caller allocates and owns**. Nothing here is allocated by the
* @param out_count Output number of points in the array * library, and nothing needs freeing.
* @return true on success, false on failure * @param out_count Output only — the number of points written. It is NOT read as a capacity.
* @return true on success, false if the footprint is empty or the handle is invalid
*
* @warning The signature carries no capacity, so this function writes as many points as the robot
* footprint has, whatever the array can hold. Size @p out_points for the largest
* footprint the deployment can configure (64 points is comfortable) — a short array is
* overrun, and the corruption will surface somewhere unrelated.
*/ */
bool navigation_get_robot_footprint(NavigationHandle handle, Point *out_points, size_t &out_count); bool navigation_get_robot_footprint(NavigationHandle handle, Point *out_points, size_t &out_count);
@@ -153,53 +196,16 @@ extern "C"
*/ */
bool navigation_move_to_nodes_edges(NavigationHandle handle, const Node *nodes, size_t node_count, const Edge *edges, size_t edge_count, const PoseStamped goal); bool navigation_move_to_nodes_edges(NavigationHandle handle, const Node *nodes, size_t node_count, const Edge *edges, size_t edge_count, const PoseStamped goal);
/** /*
* @brief Send a docking goal to a predefined marker * navigation_dock_to, navigation_dock_to_order, navigation_dock_to_nodes_edges,
* @param handle Navigation handle * navigation_move_straight_to and navigation_rotate_to were removed. They pushed a goal past
* @param marker Marker name or ID (null-terminated string) * the mission layer, which left them free to replace the leg the mission queue was running
* @param goal Target pose for docking * while the queue kept handing out the next leg of a route the robot had already left.
* @return true if docking command succeeded *
* Docking, go-straight and rotate are now ordinary legs of an order: set `profile:` on the leg
* (`docking | go_straight | rotate`) and `marker` for docking, then send the order through
* navigation_move_to_order() or navigation_move_to_nodes_edges().
*/ */
bool navigation_dock_to(NavigationHandle handle, const char *marker, const PoseStamped goal);
/**
* @brief Send a docking goal to a predefined marker
* @param handle Navigation handle
* @param order Order message
* @param goal Target pose for docking
* @return true if docking command succeeded
*/
bool navigation_dock_to_order(NavigationHandle handle, const Order order, const char *marker, const PoseStamped goal);
/**
* @brief Send a goal for the robot to navigate to
* @param handle Navigation handle
* @param marker Marker name or ID (null-terminated string)
* @param nodes Nodes array
* @param node_count Number of nodes in the array
* @param edges Edges array
* @param edge_count Number of edges in the array
* @param goal Target pose in the global frame
* @return true if goal was accepted and sent successfully
*/
bool navigation_dock_to_nodes_edges(NavigationHandle handle, const char *marker, const Node *nodes, size_t node_count, const Edge *edges, size_t edge_count, const PoseStamped goal);
/**
* @brief Move straight toward the target position
* @param handle Navigation handle
* @param distance Distance to move (meters)
* @return true if command issued successfully
*/
bool navigation_move_straight_to(NavigationHandle handle, const double distance);
/**
* @brief Rotate in place to align with target orientation
* @param handle Navigation handle
* @param goal_yaw Desired heading (radians)
* @return true if rotation command was sent successfully
*/
bool navigation_rotate_to(NavigationHandle handle, const PoseStamped goal);
/** /**
* @brief Pause the robot's movement * @brief Pause the robot's movement
@@ -220,23 +226,39 @@ extern "C"
void navigation_cancel(NavigationHandle handle); void navigation_cancel(NavigationHandle handle);
/** /**
* @brief Send limited linear velocity command * @brief Set the linear velocity **ceiling** — not a jog command.
*
* This is the path a safety layer uses to slow the robot down. The value is passed to the core
* exactly as given, sign included: the local planner keeps a separate ceiling per direction and
* **the sign of @p linear_x selects which one this call sets** — negative sets the backward
* ceiling, positive the forward one.
*
* One call therefore sets one direction. To bound both, call twice:
* @code
* navigation_set_twist_linear(h, 0.6, 0.0, 0.0); // forward <= 0.6 m/s
* navigation_set_twist_linear(h, -0.3, 0.0, 0.0); // backward <= 0.3 m/s
* @endcode
*
* @param handle Navigation handle * @param handle Navigation handle
* @param linear_x Linear velocity in X direction * @param linear_x [m/s] Ceiling, signed. The sign picks the direction; it is not discarded.
* @param linear_y Linear velocity in Y direction * @param linear_y [m/s] Lateral ceiling (holonomic bases only).
* @param linear_z Linear velocity in Z direction * @param linear_z [m/s] Unused by ground bases.
* @return true if the command was accepted * @return true if the ceiling was accepted. NaN/Inf are rejected.
*
* @note The new ceiling takes effect on the core's next control cycle, not inside this call.
*/ */
bool navigation_set_twist_linear(NavigationHandle handle, bool navigation_set_twist_linear(NavigationHandle handle,
double linear_x, double linear_y, double linear_z); double linear_x, double linear_y, double linear_z);
/** /**
* @brief Send limited angular velocity command * @brief Set the angular velocity **ceiling** — not a jog command.
* @param handle Navigation handle * @param handle Navigation handle
* @param angular_x Angular velocity around X axis * @param angular_x [rad/s] Unused by ground bases.
* @param angular_y Angular velocity around Y axis * @param angular_y [rad/s] Unused by ground bases.
* @param angular_z Angular velocity around Z axis * @param angular_z [rad/s] Yaw rate ceiling.
* @return true if the command was accepted * @return true if the ceiling was accepted. NaN/Inf are rejected.
*
* @note Takes effect on the core's next control cycle.
*/ */
bool navigation_set_twist_angular(NavigationHandle handle, bool navigation_set_twist_angular(NavigationHandle handle,
double angular_x, double angular_y, double angular_z); double angular_x, double angular_y, double angular_z);
@@ -246,6 +268,7 @@ extern "C"
* @param handle Navigation handle * @param handle Navigation handle
* @param out_pose Output parameter with the robot's current pose * @param out_pose Output parameter with the robot's current pose
* @return true if pose was successfully retrieved * @return true if pose was successfully retrieved
* @note out_pose.header.frame_id is allocated — free it with nav_c_api_free_string().
*/ */
bool navigation_get_robot_pose_stamped(NavigationHandle handle, PoseStamped &out_pose); bool navigation_get_robot_pose_stamped(NavigationHandle handle, PoseStamped &out_pose);
@@ -320,12 +343,26 @@ extern "C"
*/ */
bool navigation_add_odometry(NavigationHandle handle, const char *odometry_name, const Odometry odometry); bool navigation_add_odometry(NavigationHandle handle, const char *odometry_name, const Odometry odometry);
// ==========================================================================
// Reading data back
//
// @warning The four navigation_get_<sensor>() functions below return true for a name the core has
// never seen: the lookup falls back to a default-constructed message, and this API cannot
// tell that apart from a message that is genuinely empty. Check the payload (a grid with
// width 0, a scan with no ranges) rather than trusting the return value. A misspelt name
// is the most common configuration mistake on the sensor path, and it is exactly the case
// this API stays silent about.
//
// Everything these functions fill is allocated by the library. Release it with the
// matching navigation_free_*() in nav_c_api_2.h.
// ==========================================================================
/** /**
* @brief Get a static map from the navigation system * @brief Get a static map from the navigation system
* @param handle Navigation handle * @param handle Navigation handle
* @param map_name Name of the map * @param map_name Name of the map
* @param out_map Output parameter for the map handle * @param out_map Output parameter for the map handle
* @return true if the map was retrieved successfully * @return true if the call succeeded — see the warning above, this is not "the map exists"
*/ */
bool navigation_get_static_map(NavigationHandle handle, const char *map_name, OccupancyGrid &out_map); bool navigation_get_static_map(NavigationHandle handle, const char *map_name, OccupancyGrid &out_map);
@@ -356,11 +393,25 @@ extern "C"
*/ */
bool navigation_get_point_cloud2(NavigationHandle handle, const char *point_cloud2_name, PointCloud2 &out_cloud); bool navigation_get_point_cloud2(NavigationHandle handle, const char *point_cloud2_name, PointCloud2 &out_cloud);
// ==========================================================================
// Reading every entry at once
//
// @warning The four navigation_get_all_*() functions take an array the CALLER allocates, and the
// signature carries no capacity — @c out_count is an output, never read as a limit. Each
// function writes one element per entry the core currently holds, however large the
// array is. Size the array for the largest number of sensor streams the deployment can
// register; a short array is overrun by whole structs, and the damage surfaces far from
// here.
//
// Each element's `name` and payload are allocated by the library: free `name` with
// nav_c_api_free_string() and the payload with the matching navigation_free_*().
// ==========================================================================
/** /**
* @brief Get all static maps from the navigation system * @brief Get all static maps from the navigation system
* @param handle Navigation handle * @param handle Navigation handle
* @param out_maps Output parameter for the maps array * @param out_maps Caller-allocated array — see the capacity warning above
* @param out_count Output parameter for the number of maps * @param out_count Output only: how many entries were written
* @return true if the maps were retrieved successfully * @return true if the maps were retrieved successfully
*/ */
bool navigation_get_all_static_maps(NavigationHandle handle, NamedOccupancyGrid *out_maps, size_t &out_count); bool navigation_get_all_static_maps(NavigationHandle handle, NamedOccupancyGrid *out_maps, size_t &out_count);

View File

@@ -0,0 +1,323 @@
#ifndef NAVIGATION_C_API_2_H
#define NAVIGATION_C_API_2_H
/**
* @file nav_c_api_2.h
* @brief Additional C entry points required by the move_base2 navigation runtime.
*
* ## What this file is
*
* `nav_c_api.h` covers the navigation contract as the previous runtime exposed it. Every one of
* those functions keeps working against move_base2 — move_base2 implements
* `robot::move_base_core::BaseNavigation` with the signatures unchanged, so no existing binding
* breaks. This file adds what that contract gained but the C surface never exposed, plus the two
* entry points move_base2 makes newly necessary:
*
* - navigation_shutdown() — quiesce the core before destroying it.
* - navigation_is_ready() — did initialize() actually succeed?
* - navigation_initialize_checked() — initialize + verify, in one call.
* - navigation_get_state() — poll the state without allocating a string.
* - navigation_get_status_text() — the core's own explanation, for logging.
* - navigation_add_depth_camera_data() — the depth-camera input path, never exposed before.
* - navigation_move_to_order_v2() — an order carrying a real orderId / orderUpdateId.
* - navigation_execute_instant_actions() — a VDA5050 instantActions message, expanded like node actions.
*
* Include this header **in addition to** nav_c_api.h. It adds symbols; it replaces none.
*
* ## What changed underneath the functions you already call
*
* These keep their signatures and their meaning, but behave differently enough to matter:
*
* 1. navigation_initialize() is now heavy and blocking — it builds both costmaps, loads the
* planners, the controller, the recovery behaviours and the mission layer, then starts the
* control thread. It still returns `true` unconditionally because the underlying contract
* returns void. Use navigation_initialize_checked(), or call navigation_is_ready() after it.
*
* 2. A static map must be pushed **before** initialize(). The lattice planner blocks until the
* costmap has a non-zero size, and that size only exists once a static map has reached the
* static layer. It aborts the whole process if it waits too long.
*
* 3. navigation_set_robot_footprint() may now be called before initialize() — the footprint is
* cached and applied while the costmaps are built. Under the old runtime the same call was
* dropped silently because the costmaps did not exist yet.
*
* 4. navigation_pause() / _resume() / _cancel() no longer take effect inside the call. They record
* the request; the control thread applies it on its next cycle. Returning from the call does
* not mean the robot stopped — watch the state, or watch the twist.
*
* 5. navigation_set_twist_linear() / _angular() set a velocity **ceiling**, and the sign of the
* linear x component selects which direction the ceiling applies to. They now only reject
* NaN/Inf; the old runtime also returned false while a cancel was in flight, and that signal no
* longer exists. The new ceiling takes effect on the next control cycle.
*
* 6. navigation_get_twist() returns the command being issued, not a measurement. While no request
* is running its stamp stops advancing; a zero stamp means the core has never commanded
* anything. Check the stamp before republishing it as a velocity command.
*
* 7. NavFeedback.feed_back_str now carries the core's own reason strings — different text from the
* old runtime. Branch on NavigationState, never on the string.
*
* 8. NavFeedback.navigation_state deliberately reports ACTIVE between the legs of a multi-leg
* order, where the core itself is momentarily SUCCEEDED or PENDING. Treating SUCCEEDED as "the
* order finished" stays correct only because of that; do not bypass it.
*
* 9. navigation_add_odometry() feeds the controller's measured velocity every cycle, not just a
* stored value. Push it at the rate the odometry source produces it.
*
* 10. The `footprint` field of navigation_get_global_data() / _local_data() is the raw footprint the
* host set, in the robot base frame, and it is empty if the host never set one. The old runtime
* returned the padded footprint already transformed to the robot pose in the global frame.
*
* 11. navigation_destroy() alone is no longer enough — call navigation_shutdown() first, from a
* point in your own shutdown sequence where the process is still fully alive.
*
* See NAV_C_API_2_GUIDE.md in this directory for the per-function walkthrough and the startup and
* shutdown sequences.
*/
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include "nav_c_api.h"
#include "sensor_msgs/DepthCameraData.h"
#include "sensor_msgs/LaserScan.h"
#include "sensor_msgs/PointCloud.h"
#include "sensor_msgs/PointCloud2.h"
#include "nav_msgs/OccupancyGrid.h"
#include "protocol_msgs/Node.h"
#include "protocol_msgs/Edge.h"
// ============================================================================================
// Lifecycle
// ============================================================================================
/**
* @brief Initialize the navigation core and report whether it actually came up.
*
* Wraps navigation_initialize(). The underlying contract method returns void, so every failure
* path inside the runtime — costmap construction, sensor configuration, plugin loading, control
* loop configuration, control thread startup — returns normally and only records the reason in
* the feedback. This function reads that back and turns it into a return value.
*
* Blocking and expensive: it builds two costmaps, loads every plugin named in the YAML, starts
* the map-update threads, the mission threads and the control thread. Do not call it from a UI
* thread.
*
* @param handle Navigation handle from navigation_create().
* @param tf3_buffer tf3 BufferCore the host owns; must outlive the navigation instance.
* @return true only when the core is ready to accept goals.
*
* @pre At least one static map has been pushed with navigation_add_static_map().
* @pre The robot footprint has been set with navigation_set_robot_footprint(), if the host wants
* its own footprint rather than the one in the YAML.
* @see navigation_get_status_text() for the reason behind a false return.
*/
bool navigation_initialize_checked(NavigationHandle handle, TFListenerHandle tf3_buffer);
/**
* @brief Is the core initialized and accepting goals?
*
* Cheap enough to poll. Reads the same flag navigation_initialize_checked() checks, without
* allocating the feedback string.
*
* @return false if the handle is null, the core never initialized, or initialization failed.
*/
bool navigation_is_ready(NavigationHandle handle);
/**
* @brief Stop the core's threads without destroying the instance.
*
* Gives the host a point inside its own shutdown sequence — while the process is still fully
* alive — to stop the control thread, the costmap update threads and the mission threads.
* Destroying the instance from a finalizer, after the runtime has already begun tearing down, is
* the race this exists to avoid.
*
* After this call the core issues no further velocity commands, and every getter
* (navigation_get_feedback, navigation_get_twist, navigation_get_robot_pose_*) remains safe to
* call. Safe to call more than once.
*
* @warning No thread may be calling navigation_add_* while this runs, and none may call them
* afterwards. The sensor path is not thread-safe and there is no longer a control thread
* consuming what it produces.
*/
void navigation_shutdown(NavigationHandle handle);
// ============================================================================================
// Status
// ============================================================================================
/**
* @brief Current navigation state, without allocating anything.
*
* navigation_get_feedback() strdup()s its message on every call, so polling it at control rate
* means one allocation and one free per poll — and one leak per missed free. Use this when only
* the state matters, which is the common case.
*
* @param handle Navigation handle.
* @param out_state Receives the current state; untouched on failure.
* @return false if the handle is null or the core has no feedback yet.
*/
bool navigation_get_state(NavigationHandle handle, NavigationState *out_state);
/**
* @brief The core's own description of what it is doing, or why it refused.
*
* For logging and diagnostics only. The wording comes from the runtime and changes between
* versions — never branch on it. Branch on navigation_get_state().
*
* @return Newly allocated string, or NULL. Free with nav_c_api_free_string().
*/
char *navigation_get_status_text(NavigationHandle handle);
// ============================================================================================
// Sensor input
// ============================================================================================
/**
* @brief Push one coherent depth-camera sample into the navigation core.
*
* This is the only way to reach the depth-camera path from C. The voxel layer projects the depth
* image through the intrinsics to build the camera frustum, which is what lets it *clear* stale
* obstacles inside the field of view. A point cloud cannot substitute: it carries no intrinsics,
* so no frustum can be reconstructed and nothing gets cleared.
*
* @param handle Navigation handle.
* @param topic Logical name of the stream. Must match an `observation_source` declared for the
* voxel layer in the costmap YAML — a name no layer subscribes to is accepted here
* and then dropped, silently, further down.
* @param data Depth image and its matching intrinsics. Deep-copied; the caller may release its
* buffers as soon as this returns.
* @return true if the sample was accepted.
*
* @pre `data.header.frame_id` is the camera's optical frame, and a transform from it to the robot
* base frame exists in the tf3 buffer at `data.header.stamp`.
* @pre `data.depth.encoding` matches the real encoding ("16UC1" or "32FC1") and `step` is the
* real row stride in bytes.
* @pre `data.camera_info` describes the resolution actually being sent, not the colour stream's.
* @pre The depth image and the camera info come from the same instant.
*
* @note Push at the camera's real rate. This is the most expensive sensor path in the core;
* pushing faster than the source only burns CPU.
*/
bool navigation_add_depth_camera_data(NavigationHandle handle, const char *topic,
const DepthCameraData data);
// ============================================================================================
// Orders
// ============================================================================================
/**
* @brief Send a multi-node order with a real identity.
*
* Under move_base2 an order goes through the mission layer, which splits it into legs at the
* nodes that carry actions, filters by `released`, and can extend the route when the fleet master
* releases more of the horizon. `orderId` plus `orderUpdateId` is what identifies an order there:
* the same `orderId` with a higher `orderUpdateId` is an update of the route in progress, while a
* different `orderId` is a new order that replaces it.
*
* navigation_move_to_nodes_edges() cannot express that — it has nowhere to put either field — so
* every call looks like a different order and no update can ever be sent. Use this instead
* whenever the fleet master sends order updates or releases the horizon progressively.
*
* @param handle Navigation handle.
* @param order_id VDA5050 orderId. Must not be NULL or empty.
* @param order_update_id VDA5050 orderUpdateId. Must increase within one orderId.
* @param nodes Node array; the host keeps ownership.
* @param node_count Number of nodes.
* @param edges Edge array; the host keeps ownership.
* @param edge_count Number of edges.
* @param goal Final pose, in the global frame.
* @return true if the order was accepted.
*/
bool navigation_move_to_order_v2(NavigationHandle handle,
const char *order_id, uint32_t order_update_id,
const Node *nodes, size_t node_count,
const Edge *edges, size_t edge_count,
const PoseStamped goal);
/*
* navigation_dock_to_order_v2 was removed. Docking is a per-leg property of the order now: set
* `profile: docking` and `marker` on the leg, then send it through navigation_move_to_order_v2.
*/
/**
* @brief Run one VDA5050 `instantActions` message — the whole list, as one batch.
*
* Each action is expanded against the same compound-action table that node actions use, so
* `PickUp` sent as an instantAction produces the same detect / approach / lift / back-out
* sequence it produces inside an order. One vocabulary, one set of handlers, one meaning per
* actionType regardless of how it arrived.
*
* Pass the message's actions together rather than calling this once per action: a second `HARD`
* action submitted on its own preempts and wipes the legs of the first, so two actions sent in
* one message would eat each other.
*
* Execution stops at the first leg that fails and the rest of the message is dropped with it, so
* the caller reports ONE outcome for the message — which is all VDA5050 asks for.
*
* `blockingType` decides how the batch meets a running order: any `HARD` action makes the whole
* message preempt it, otherwise it queues behind it. `NONE` requests execution in parallel with
* driving, which this runtime cannot do — it is queued instead and the narrowing is logged. An
* unset or unknown blockingType is treated as `HARD`, the safe direction.
*
* Do NOT route `cancelOrder`, `startPause` or `stopPause` here. Those steer the queue rather
* than being work in it: call navigation_cancel(), navigation_pause() and navigation_resume().
*
* Progress is reported through the ordinary state, not per action: poll navigation_get_state()
* and map ACTIVE/CONTROLLING to RUNNING, SUCCEEDED to FINISHED, ABORTED/PREEMPTED to FAILED.
* That mapping is only unambiguous while this message is the only work in the queue, which holds
* as long as the fleet master sends one message at a time and none during an order.
*
* @param handle Navigation handle.
* @param actions Array of actions, in the order received. The host keeps ownership.
* @param count Number of actions. Must be > 0.
* @return true if the message was accepted. false means rejected outright — report it failed
* rather than waiting for a result that will not come.
*/
bool navigation_execute_instant_actions(NavigationHandle handle, const Action *actions,
size_t count);
// ============================================================================================
// Releasing what the getters allocate
// ============================================================================================
//
// Every navigation_get_* function that returns a grid, a scan, a cloud or a plan fills it with
// buffers allocated inside the library. Only two release helpers ever shipped —
// nav_c_api_free_string() and order_free() — so the rest had no counterpart and leaked one
// allocation per call. At four display timers polling at 10 Hz that is a steady leak, not a
// rounding error. These close it.
//
// All are null-safe, clear the pointers and counts they release, and are safe to call twice.
/** @brief Release the buffers inside an OccupancyGrid filled by navigation_get_static_map(). */
void navigation_free_occupancy_grid(OccupancyGrid *grid);
/** @brief Release the buffers inside a LaserScan filled by navigation_get_laser_scan(). */
void navigation_free_laser_scan(LaserScan *scan);
/** @brief Release the buffers inside a PointCloud filled by navigation_get_point_cloud(). */
void navigation_free_point_cloud(PointCloud *cloud);
/** @brief Release the buffers inside a PointCloud2 filled by navigation_get_point_cloud2(). */
void navigation_free_point_cloud2(PointCloud2 *cloud);
/**
* @brief Release the buffers inside a PlannerDataOutput.
*
* navigation_get_global_data() / _local_data() already release the previous contents of the
* struct they are handed, so reusing one struct across polls does not leak. What does leak is the
* last fill, once the host stops polling — free it here.
*/
void navigation_free_planner_data(PlannerDataOutput *data);
#ifdef __cplusplus
}
#endif
#endif // NAVIGATION_C_API_2_H

View File

@@ -0,0 +1,36 @@
#ifndef C_API_SENSOR_MSGS_DEPTHCAMERADATA_H
#define C_API_SENSOR_MSGS_DEPTHCAMERADATA_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "sensor_msgs/Image.h"
#include "sensor_msgs/CameraInfo.h"
/**
* @brief One coherent depth-camera sample: a depth image plus the intrinsics that describe it.
*
* Mirrors robot_sensor_msgs::DepthCameraData. "Coherent" is the whole point of the struct: the
* voxel layer projects every depth pixel through the intrinsics to build a frustum, so a depth
* image paired with intrinsics from a different resolution or a different instant clears the wrong
* volume of space. Pair them at the source, not here.
*/
typedef struct
{
/** Canonical timestamp and optical frame of this sample. */
Header header;
/** Depth image. `encoding` must be the true encoding ("16UC1" or "32FC1"). */
Image depth;
/** Intrinsics of the exact image above — same resolution, same instant. */
CameraInfo camera_info;
} DepthCameraData;
#ifdef __cplusplus
}
#endif
#endif // C_API_SENSOR_MSGS_DEPTHCAMERADATA_H

View File

@@ -0,0 +1,485 @@
# Báo cáo ghép khung C# (RobotNet12) với move_base2 qua nav_c_api_2
- **Ngày:** 2026-08-10 · **Đối chiếu lại:** 2026-08-10 (mục 1b) · **Cập nhật theo API mới:** 2026-08-10 tối (mục 1c)
> ⚠ **API đã đổi sau khi bản đầu được viết.** Năm hàm bị xoá, một hàm mới thêm vào. Đây là thay đổi
> **phá vỡ tương thích** và RobotNet12 **đang gọi 4/5 hàm đã xoá**. Đọc **mục 1c trước** mọi mục khác.
- **Phạm vi:** RobotApp `Modules/Navigation` (P/Invoke binding + client + integration service) ghép với `libnav_c_api.so` build từ `pnkx_nav_core` chạy runtime `libmove_base2.so`.
- **Nguồn đối chiếu (đã kiểm tra thực tế):**
- `T800_ws/src/AMR_T800/pnkx_nav_core/src/APIs/c_api/include/nav_c_api.h`, `nav_c_api_2.h`
- `T800_ws/src/AMR_T800/pnkx_nav_core/src/APIs/c_api/NAV_C_API_2_GUIDE.md` (gọi tắt: **Guide**)
- `nm -D` trên `T800_ws/src/AMR_T800/pnkx_nav_core/build/libnav_c_api.so`
- `T800_ws/src/AMR_T800/Test/move_base2/config/runtime/*.yaml`
- `RobotNet12/RobotApp/RobotNet12.RobotApp/Modules/Navigation/*.cs`
- `RobotNet12/RobotApp/RobotNet12.RobotApp/systemd/robotnet-robotapp.service` *(bổ sung ở lần đối chiếu lại — đây là cách robot thật khởi động)*
> **Đây là bản kiểm điểm một thời điểm**, gắn với trạng thái `RobotNet12` ngày 2026-08-10. Nó liệt kê
> lỗi đang có và sẽ cũ đi khi những lỗi đó được sửa. Phần **hướng dẫn ghép bền vững** — kiến trúc host,
> ánh xạ VDA5050, triển khai systemd, checklist nghiệm thu — nằm ở **Guide mục 12–15**; sửa xong danh
> sách dưới đây thì dùng Guide, không dùng file này.
>
> **Bản này tồn tại ở hai chỗ, nội dung giống hệt nhau:**
> `T800_ws/.../c_api/nav-c-api-2-csharp-integration-report.md` và
> `RobotNet12/docs/nav-c-api-2-csharp-integration-report.md`. Sửa một bên thì đồng bộ bên kia, nếu
> không hai bản sẽ trôi lệch.
---
## 1. Kết luận tóm tắt
| Phía | Cần đổi gì |
|---|---|
| **move_base2 / nav_c_api_2** | **Không cần đổi gì để ghép được.** Bề mặt API đủ, 13 symbol mới đã có trong `.so`, struct khớp header. Còn 1 việc đã ghi nhận sẵn (footprint hiển thị, mục 2) + 2 khuyến nghị không chặn. |
| **C# (RobotNet12)** | Toàn bộ công việc nằm ở đây, chia 4 nhóm: (A) sửa binding cũ đang sai/chết, (B) thêm 13 `DllImport` + 4 struct, (C) đổi hành vi theo runtime mới, (D) đổi config/môi trường. Chi tiết mục 3–6. |
Các khẳng định của Guide đã được xác minh đúng với thực tế: 13 symbol mới tồn tại; struct `DepthCameraData`/`Image`/`CameraInfo`/`RegionOfInterest` khớp header C từng field; enum `NavigationState` C# khớp C (0–13); config move_base2 khớp (`library_path: libmove_base2` tại `move_base_common_params.yaml:304`, `controller_frequency: 30.0`, topic `/map`, `/b_scan`, `/camera/depth/points_proc`, `/camera/depth/data`, `/camera_right/...`); `tf3_buffer_create/destroy` đã có trong `TF3NativeInterface.cs`.
---
## 1b. Kết quả đối chiếu lại (2026-08-10)
Toàn bộ mục 3–6 đã được kiểm lại bằng `file:line` trên mã C# thật và `nm -D` trên `.so`. **Không mục
nào sai.** Bảng dưới ghi kết quả kiểm chứng; ba mục bổ sung phát hiện thêm nằm ở **A6** và **mục 6**
(viết lại).
| Mục | Kết quả kiểm | Ghi chú |
|---|---|---|
| **A1** | ✓ đúng dòng `NavigationNativeInterface.cs:193-198` | Call site `NavigationClient.cs:608` là **code sống**, có vòng `Marshal.PtrToStructure` ở `:621-627`. Mô tả "24 byte/điểm vào ô 8 byte" chính xác |
| **A2** | ✓ khai `:205`, gọi `NavigationClient.cs:636` | `nm` xác nhận `navigation_free_points` **không tồn tại** trong `.so` |
| **A3** | ✓ đúng cả 10 dòng | Cảnh báo trùng tên **đúng và là mục nguy hiểm nhất của nhóm A**: `navigation_free_occupancy_grid` và `navigation_free_laser_scan` **có thật** trong `.so` mới nhưng nhận `OccupancyGrid*` / `LaserScan*`. Bản C# khai `IntPtr handle` sẽ resolve trúng symbol thật rồi truyền một con trỏ sai kiểu vào — hàm sẽ `free()` những gì nó tưởng là `header.frame_id` và `data` |
| **A4** | ✓ đếm được đúng **23** `UnmanagedType.Bool`, 2 `I1` | |
| **A5** | ✓ nhưng **chưa đủ nghiêm trọng như mô tả** | Có fallback `NativeLibrary.TryLoad(...)` theo `LD_LIBRARY_PATH` tại `:40-42`, nên hard-code sai đường không chết cứng ngay. Vấn đề thật nằm ở A6 và mục 6 |
| **C1** | ✓ `Initialize()` :345 → footprint :358 → vòng poll :373-380; `navigation_initialize` tại `NavigationClient.cs:123` | Thứ tự thật sự sai với move_base2 |
| **C2** | ✓ `grep` cả `NavigationClient.cs` chỉ có `navigation_destroy` (`:127`, `:2463`), `Dispose` tại `:2445` | Không có `navigation_shutdown` ở đâu |
| **D** | ✓ đúng dòng 13, 14 của `launchSettings.json` | Nhưng **sửa hai dòng này không ảnh hưởng robot thật** — xem mục 6 viết lại |
| **§2.3** | ✓ Guide thiếu 3 symbol | `header_create`, `header_set_data`, `time_create` đều có trong `.so`. **Đã sửa Guide** (Phụ lục A) |
**Báo cáo cũng đúng ở chỗ nó KHÔNG nêu.** Bốn lệch chữ ký từng tìm thấy trong
`pnkx_nav_core/examples/NavigationExample/NavigationAPI.cs` **không áp dụng cho RobotNet12** — binding
của RobotApp là bản khác và tốt hơn: `navigation_rotate_to` nhận `PoseStamped` (`:273-275`),
`navigation_pause/resume/cancel` khai `void` (`:282`, `:289`, `:296`),
`navigation_move_to_nodes_edges` có đủ hai tham số đếm (`:510-515`),
`navigation_dock_to_nodes_edges` không được khai báo. Không cần đụng tới.
---
## 1c. API đã đổi — nhóm E (mới, ưu tiên cao nhất)
Đọc lại mã nguồn ngày 2026-08-10 tối. So với thời điểm viết bản đầu, bề mặt API đã đổi: **62 symbol**
thay vì 64 (`nm -D` trên `build/libnav_c_api.so`, build 20:19).
### E1. Năm hàm bị XOÁ — RobotNet12 đang gọi 4/5
| Hàm | Còn trong `.so`? | RobotNet12 dùng ở đâu |
|---|---|---|
| `navigation_dock_to` | **không** | khai `NavigationNativeInterface.cs:246` · gọi `NavigationClient.cs:1053` · wrapper `DockTo()` `:970` · caller `NavigationIntegrationService.cs:836` |
| `navigation_dock_to_order` | **không** | khai `:502` · gọi `NavigationClient.cs:1150` · wrapper `DockToOrder()` `:1134` · caller `NavigationIntegrationService.cs:854` |
| `navigation_dock_to_nodes_edges` | **không** | *không dùng* |
| `navigation_move_straight_to` | **không** | khai `:260` · gọi `NavigationClient.cs:1179` · wrapper `MoveStraightTo()` `:1169` · caller `NavigationIntegrationService.cs:882` **và** `Endpoints/NavigationTestEndpoints.cs:83` |
| `navigation_rotate_to` | **không** | khai `:273` · gọi `NavigationClient.cs:1209` · wrapper `RotateTo()` `:1196` · caller `NavigationIntegrationService.cs:901` **và** `Endpoints/NavigationTestEndpoints.cs:126` |
Cả năm đã bị gỡ khỏi contract `BaseNavigation` (`move_base_core/navigation.h`), khỏi `move_base`,
`move_base2`, `nav_c_api`, `nav_c_api_2`, và khỏi host ROS (`amr_control`). **Gọi là
`EntryPointNotFoundException`** — không phải lỗi biên dịch, nên nó chỉ nổ lúc chạy, ở đúng lần dock
hoặc lần đi thẳng đầu tiên.
**Phải xoá ở C#:** 4 khai báo `DllImport`, 4 wrapper public, 6 call site (4 trong
`NavigationIntegrationService`, 2 trong `NavigationTestEndpoints`).
### E2. Năng lực không mất — nó chuyển vào compound action
Docking, đi thẳng, quay tại chỗ giờ là **thuộc tính của từng chặng** khai trong
`Test/move_base2/config/runtime/compound_actions_params.yaml`:
```yaml
PickUp:
steps:
- {action: detect}
- {move_to: dock_target, profile: docking, marker: trolley}
- {action: LiftFork}
- {move: -0.5, profile: go_straight}
UnDockFromStation:
steps:
- {move: -1.0, profile: go_straight}
- {move: 0.0, profile: rotate}
```
`profile` ∈ `position | docking | go_straight | rotate`; `marker` **chỉ hợp lệ với
`profile: docking`**, chọn override trong `maker_sources.yaml`.
Host gửi **tên action** thay vì gọi động tác:
| Đường | Hàm | Khi nào |
|---|---|---|
| Action trong node của order | `navigation_move_to_order_v2` | Fleet giao tuyến có action giữa đường |
| `instantActions` ngoài order | `navigation_execute_instant_actions` **(mới)** | Fleet hoặc HMI yêu cầu ngay |
**Vì sao đổi:** ba hàm cũ đi thẳng xuống lõi, **không qua mission layer** — chúng preempt order đang
chạy trong im lặng. `UnDockFromStation` gọi `moveStraightTo` là ca đã gặp thật. Đường mới đưa mọi
chuyển động về chung một hàng đợi, chung đường huỷ, chung đường báo kết quả.
### E3. Hàm mới `navigation_execute_instant_actions`
```c
bool navigation_execute_instant_actions(NavigationHandle handle, const Action *actions, size_t count);
```
Chạy trọn một message `instantActions` như **một lô**. Dùng `Action` — struct C **đã có sẵn**
(`protocol_msgs/Action.h`), không phải khai struct mới.
Bốn ràng buộc, đầy đủ ở Guide §11.8:
1. **Gửi cả lô một lần.** Gọi từng action riêng thì action `HARD` sau sẽ preempt và xoá chặng của
action trước — hai action cùng message ăn nhau.
2. **`blockingType` quyết định cách gặp order đang chạy.** Có `HARD` → preempt cả message; `SOFT` →
xếp hàng; `NONE` → runtime không chạy song song được nên **bị hạ xuống xếp hàng** và ghi log; không
khai / không hiểu → coi như `HARD`.
3. **Không route `cancelOrder` / `startPause` / `stopPause` qua đây** — chúng lái hàng đợi, không nằm
trong hàng đợi. Vẫn dùng `navigation_cancel()` / `_pause()` / `_resume()`.
4. **Một kết quả cho cả message.** Dừng ở chặng lỗi đầu tiên, phần còn lại bị bỏ. Theo dõi bằng
`navigation_get_state`: `ACTIVE`/`CONTROLLING` → RUNNING, `SUCCEEDED` → FINISHED,
`ABORTED`/`PREEMPTED` → FAILED. Ánh xạ chỉ đúng khi message là việc duy nhất trong hàng đợi.
Điều này **thay thế** đường instant action mà mục 6 của báo cáo trước mô tả là "host tự dịch từng
actionType". Nay chỉ ba action điều khiển hàng đợi còn phải tự dịch; phần còn lại đẩy nguyên lô.
### E4. Ảnh hưởng tới các mục khác của báo cáo
| Mục | Ảnh hưởng |
|---|---|
| §4 nhóm B | Danh sách 13 `DllImport` đổi: **bỏ** `navigation_dock_to_order_v2`, **thêm** `navigation_execute_instant_actions`. Vẫn đúng 13 hàm. 4 struct mới không đổi |
| §5 C4 | `navigation_dock_to_order_v2` không còn tồn tại — bỏ khỏi khuyến nghị |
| Guide | Đã cập nhật: §0 (9 việc), §6.4 (5 hàm xoá + mô hình mới), §11.8 (thay bằng instant actions), Phụ lục A (62 symbol), Phụ lục B.2 |
| **Guide §12–15 (mới)** | Phần ghép bền vững: **§12** kiến trúc host + khung `NavigationHost` + mô hình thread · **§13** ánh xạ VDA5050 → C API (gồm ba action lái hàng đợi phải tách riêng) · **§14** triển khai systemd, `ProtectHome`, bố cục cài, xác minh runtime · **§15** checklist nghiệm thu 7 tầng |
### E5. Tài liệu test thủ công của RobotNet12 đã cũ
`RobotApp/RobotNet12.RobotApp/Modules/Navigation/navigation-capi-manual-test-guide.md` viết cho
`navigation_move_straight_to` và `navigation_rotate_to` — cả hai **không còn tồn tại**. Mục 2 và 3 của
file đó không chạy được nữa. Viết lại theo đường mới: chuyển động thẳng/quay giờ là chặng
`profile: go_straight | rotate` bên trong một action, gọi qua `navigation_execute_instant_actions`
hoặc nằm trong node của order. Mẫu nghiệm thu ở Guide §15 tầng 3–4.
---
## 2. Phía move_base2 / nav_c_api_2 — cần thay đổi gì?
**Không có thay đổi bắt buộc.** Ba mục dưới đây không chặn việc ghép:
1. **Đã ghi nhận, nên sửa ở move_base2 (không phải ở C#):** trường `footprint` trong `navigation_get_global_data`/`_local_data` giờ trả polygon **thô** trong frame `base_link` (rỗng nếu host chưa set), thay vì bản đã pad + transform theo pose robot như bản cũ → vỡ hiển thị footprint trên bản đồ. Chỗ sửa đúng là move_base2 lấy footprint từ costmap (Guide mục 6.10, tham chiếu `C_API_MOVE_BASE2_PLAN.md` §8.4). **Tạm thời C# phải tự transform** theo pose từ `navigation_get_robot_pose_2d` nếu muốn vẽ đúng.
2. **Khuyến nghị (tuỳ chọn) cho nav_c_api_2:** `navigation_get_robot_footprint` và nhóm `navigation_get_all_*` nhận mảng do caller cấp mà **không có tham số dung lượng** — cấp thiếu là tràn mảng. Nên thêm biến thể capacity-aware về sau. Trước mắt C# né bằng cách cấp dư (≥ 64 điểm cho footprint).
3. **Sửa tài liệu (không sửa code):** Phụ lục A của Guide thiếu 3 symbol có thật trong `.so`: `header_create`, `header_set_data`, `time_create`; và Guide thiếu mục "xoá các khai báo C# cũ không còn symbol" (chính là nhóm lỗi ở mục 3 dưới đây). — **Đã sửa phần Phụ lục A ngày 2026-08-10** (bổ sung cả ba, kèm mô tả và quy tắc giải phóng `frame_id`). Phần "xoá khai báo chết" vẫn chỉ nằm ở báo cáo này, chưa đưa vào Guide.
Ngoài ra, theo Guide mục 10: đường depth camera và `navigation_move_straight_to` lùi **chưa chạy thử trên robot/Gazebo** — đây là việc kiểm thử, không phải sửa code.
---
## 3. C# nhóm A — SỬA binding cũ đang sai hoặc chết
Guide viết "binding cũ chạy nguyên trạng" — sai ở các điểm sau (đã đối chiếu `nm` với code):
### A1. `navigation_get_robot_footprint` — chữ ký C# sai hẳn (hỏng bộ nhớ nếu gọi)
- Chữ ký thật (`nav_c_api.h:166`): `bool navigation_get_robot_footprint(NavigationHandle, Point *out_points, size_t &out_count)` — **caller cấp mảng**.
- C# hiện tại (`NavigationNativeInterface.cs:193`): `out IntPtr out_points, out nuint out_count` — chờ thư viện cấp phát. Gọi như hiện tại (call site `NavigationClient.cs:608`) là core ghi mảng `Point` 24 byte/điểm vào ô 8 byte trên stack.
- **Sửa:** khai lại thành `[In, Out] Point[] out_points, ref nuint out_count`, cấp sẵn mảng 64 điểm trước khi gọi; bỏ vòng `Marshal.PtrToStructure` và bỏ `navigation_free_points` (A2).
### A2. `navigation_free_points` — symbol không tồn tại trong `.so` mới
- Khai tại `NavigationNativeInterface.cs:205`, **đang gọi sống** tại `NavigationClient.cs:636` → `EntryPointNotFoundException` ngay lần đầu đọc footprint. Xoá cả khai báo lẫn call site (tự hết khi sửa A1).
### A3. Xoá các khai báo chết — đặc biệt 2 khai báo trùng tên symbol mới
Không còn tồn tại trong `.so` (call site đều đã comment, nhưng khai báo phải xoá để không ai gọi lại):
| Khai báo (NavigationNativeInterface.cs) | Dòng | Ghi chú |
|---|---|---|
| `navigation_free_feedback` | 398 | chỉ cần free `feed_back_str` bằng `nav_c_api_free_string` (đang làm đúng) |
| `navigation_free_occupancy_grid(IntPtr)` | 404 | ⚠️ **trùng tên** symbol mới `navigation_free_occupancy_grid(OccupancyGrid*)` — giữ lại rồi gọi nhầm bản `IntPtr` là free con trỏ rác |
| `navigation_free_occupancy_grid_update` | 410 | |
| `navigation_free_laser_scan(IntPtr)` | 416 | ⚠️ **trùng tên** symbol mới `navigation_free_laser_scan(LaserScan*)` — cùng rủi ro trên |
| `navigation_free_odometry` | 422 | |
| `navigation_free_path2d` | 428 | |
| `navigation_free_polygon_stamped` | 434 | |
| `navigation_free_order` | 440 | symbol thật tên `order_free` |
| `navigation_free_named_occupancy_grids` | 446 | |
| `navigation_free_named_laser_scans` | 452 | |
### A4. `UnmanagedType.Bool` → `UnmanagedType.I1` (23 khai báo)
`bool` C++ là 1 byte, trả về trong thanh ghi AL; `UnmanagedType.Bool` marshal 4 byte — 3 byte cao không xác định, có thể đọc `false` thành `true`. Guide nêu đúng rule I1 nhưng không nói binding cũ đang vi phạm. **Sửa toàn bộ `[return: MarshalAs(UnmanagedType.Bool)]` trong `NavigationNativeInterface.cs` thành `UnmanagedType.I1`** (2 chỗ `navigation_dock_to_order`, `navigation_move_to_nodes_edges` đã đúng I1 sẵn).
### A5. Đường tìm `.so` hardcode máy cũ
`NavigationNativeInterface.cs:20` chỉ có candidate `/home/mic-733ao/sonvh/pnkx_nav_core/build/libnav_c_api.so`. Thêm đường build hiện tại (`/home/duongtd/T800_ws/src/AMR_T800/pnkx_nav_core/build/libnav_c_api.so`) hoặc chuyển hẳn sang cấu hình/`PNKX_NAV_CORE_LIBRARY_PATH`.
**Bổ sung 2026-08-10 — mức độ nhẹ hơn tưởng.** Có fallback tại `:40-42`:
```csharp
return NativeLibrary.TryLoad("libnav_c_api.so", assembly, searchPath, out var fallback)
? fallback : IntPtr.Zero;
```
nên khi candidate không tồn tại, .NET vẫn dò tiếp theo `LD_LIBRARY_PATH` và thư mục output. Hard-code
sai đường **không** làm chết ngay. Nhưng trên robot đường `/home/...` còn bị chặn ở tầng systemd —
xem mục 6.
### A6. `NavigationClient.cs:49-52` — đọc nhầm **tên** biến môi trường thành **giá trị**, và hardcode thứ hai
*(phát hiện ở lần đối chiếu lại; báo cáo bản đầu bỏ sót)*
```csharp
string navCorePath = "PNKX_NAV_CORE_LIBRARY_PATH"; // :49 ← TÊN biến
// string navCoreBuildPath = Path.Combine(navCorePath, "lib"); // :50 (đã comment)
string navCoreBuildPath = "/home/mic-733ao/sonvh/pnkx_nav_core/build"; // :52 ← hardcode THỨ HAI
...
if (Directory.Exists(navCorePath)) // :78 → Directory.Exists("PNKX_NAV_CORE_LIBRARY_PATH")
{
Directory.SetCurrentDirectory(navCorePath); // :82 → KHÔNG BAO GIỜ chạy
}
else
{
_logger?.LogWarning("Navigation core path not found: {Path}", navCorePath); // :93
}
```
Thiếu `Environment.GetEnvironmentVariable(...)`. `Directory.Exists` gọi trên **chuỗi tên biến** nên
luôn `false`; `chdir` chưa từng thực hiện, và log ra đúng chữ
`Navigation core path not found: PNKX_NAV_CORE_LIBRARY_PATH` — nhìn log là thấy ngay.
Đây là **hardcode thứ hai**, độc lập với A5: `:52` đặt `LD_LIBRARY_PATH` cho việc nạp plugin
(`libmove_base2.so` và các planner), còn A5 là đường nạp chính `libnav_c_api.so`. Sửa A5 mà quên A6
thì `.so` chính nạp được nhưng plugin thì không.
**Sửa:**
```csharp
string? navCorePath = Environment.GetEnvironmentVariable("PNKX_NAV_CORE_LIBRARY_PATH");
if (string.IsNullOrEmpty(navCorePath))
{
_logger?.LogError("PNKX_NAV_CORE_LIBRARY_PATH chưa được đặt — plugin navigation sẽ không nạp được");
}
```
rồi dùng chính `navCorePath` cho cả `LD_LIBRARY_PATH` lẫn `chdir`, bỏ hằng số ở `:52`.
**Ghi chú về `chdir`.** Việc đổi thư mục làm việc **không** giúp tìm cây config: `robot::NodeHandle`
dò theo `PNKX_NAV_CORE_CONFIG_DIR` → `PNKX_NAV_CORE_DIR/config` → các đường tương đối so với
**`/proc/self/exe`**, không phải so với cwd. Đặt đúng biến môi trường mới là cách duy nhất.
---
## 4. C# nhóm B — THÊM khai báo mới
Toàn bộ phần thêm nằm sẵn ở **Guide Phụ lục B** (đã đối chiếu đúng với `.so` và header):
- **4 struct mới** (B.1): `RegionOfInterest`, `Image`, `CameraInfo`, `DepthCameraData` — layout khớp header C từng field. Đặt vào `NavigationInterop.cs`.
- **13 `DllImport` mới** (B.2): `navigation_initialize_checked`, `navigation_is_ready`, `navigation_shutdown`, `navigation_get_state`, `navigation_get_status_text`, `navigation_add_depth_camera_data`, `navigation_move_to_order_v2`, `navigation_execute_instant_actions`, `navigation_free_occupancy_grid`, `navigation_free_laser_scan`, `navigation_free_point_cloud`, `navigation_free_point_cloud2`, `navigation_free_planner_data`. Đặt vào `NavigationNativeInterface.cs` — **sau khi đã xoá 2 khai báo trùng tên ở A3**.
---
## 5. C# nhóm C — ĐỔI hành vi (đối chiếu code hiện tại)
### C1. Trình tự khởi tạo hiện tại SAI thứ tự với move_base2 — sẽ chết cả tiến trình
Hiện tại (`NavigationIntegrationService.InitializeAsync`):
```
navigationClient.Initialize() ← dòng 345, bên trong gọi navigation_initialize (NavigationClient.cs:123)
SetRobotFootprint(...) ← dòng 358, SAU initialize
AddStaticMap(...) ← chỉ chạy khi map đến, SAU initialize
```
Với move_base2: planner SBPL chặn chờ costmap có kích thước ≠ 0, kích thước chỉ có khi static map đã vào **trước** `initialize` — chờ quá lâu là `exit(1)` **giết cả tiến trình RobotApp**. Trình tự bắt buộc mới:
```
1. tf3_buffer_create + bơm TF liên tục (bắt đầu ngay)
2. navigation_create
3. navigation_set_robot_footprint ← TRƯỚC initialize (bản mới cache, áp lúc dựng costmap)
4. navigation_add_static_map("/map", …) ← BẮT BUỘC trước initialize
5. navigation_initialize_checked ← thay navigation_initialize
6. false → đọc navigation_get_status_text, log, retry/abort
7. bật vòng bơm sensor định kỳ
8. mới nhận goal
```
Ghi chú thêm:
- `navigation_initialize` dưới move_base2 **luôn trả `true`** — check `initResult` tại `NavigationClient.cs:123-130` thành vô nghĩa. Phải chuyển sang `navigation_initialize_checked`.
- Vòng chờ ready hiện tại (poll `GetFeedback().IsReady`, 50 × 100 ms tại `NavigationIntegrationService.cs:373-380`) thay bằng: `initialize_checked` đã blocking và trả kết quả thật; health-check về sau dùng `navigation_is_ready` (rẻ, không cấp phát).
- Tên map bơm vào phải đúng `"/map"` (khớp `map_topic` trong `costmap_common_params.yaml:11`) — rà giá trị `mapName`/`gridMapName` đang truyền tại `NavigationClient.cs:357` và `:505`.
- `navigation_initialize_checked` chặn hàng giây — giữ nguyên pattern chạy nền `Task.Run` hiện có, không gọi từ UI thread.
### C2. Trình tự tắt thiếu `navigation_shutdown`
Hiện tại (`NavigationIntegrationService.cs:670-687`): dừng timer → `_navigationClient.Dispose()` → bên trong gọi thẳng `navigation_destroy`. Với move_base2 (control thread + costmap thread + mission thread đang chạy) phải chen thêm bước quiesce:
```
1. Dừng MỌI thread/timer C# đang gọi navigation_add_* và đợi thoát hẳn
2. navigation_shutdown(handle) ← MỚI — lõi ngừng phát lệnh vận tốc, getter vẫn an toàn
3. navigation_destroy(handle)
4. tf3_buffer_destroy(tfHandle) ← sau cùng
```
Không để `navigation_destroy` rơi vào finalizer/GC.
### C3. Tám thay đổi hành vi còn lại (rà theo call site)
| # | Việc | Chỗ trong code |
|---|---|---|
| 1 | `pause`/`resume`/`cancel` trả về ≠ robot đã dừng — hiệu lực ở cycle sau (≤ 33 ms @ 30 Hz). Nếu tầng an toàn nào giả định dừng tức thì → chờ state `PAUSED` hoặc theo dõi twist | call site `navigation_pause/resume/cancel` trong `NavigationClient.cs` |
| 2 | `set_twist_linear/_angular`: là **trần vận tốc**, dấu `x` chọn chiều (âm = trần lùi), muốn chặn 2 chiều gọi 2 lần; giá trị hợp lệ **luôn trả `true`** — tín hiệu "false khi đang cancel" của bản cũ không còn | mỗi hàm 1 call site trong `NavigationClient.cs` |
| 3 | Không so sánh chuỗi `feed_back_str` — chỉ rẽ nhánh theo enum. `FeedbackString` đang được expose tại `NavigationClient.cs:1709` — rà mọi consumer phía trên | consumer của `FeedbackString` |
| 4 | Vòng poll trạng thái chuyển sang `navigation_get_state` (không cấp phát chuỗi); `GetFeedback` chỉ dùng khi cần message. Việc free `feed_back_str` hiện tại đã đúng (`:544`, `:1388`, `:1737`) | update timer / máy trạng thái |
| 5 | `navigation_get_twist` trả **lệnh đang phát**, stamp đứng yên khi không có request, stamp = 0 nghĩa chưa từng điều khiển — check stamp trước khi publish `cmd_vel` để không đè teleop | 3 call site `navigation_get_twist` |
| 6 | `get_global_data`/`_local_data`: tái dùng 1 struct/consumer (hàm tự free nội dung cũ), khi dừng consumer gọi `navigation_free_planner_data`; **không dùng chung struct giữa 2 timer**; footprint trả về giờ là bản thô `base_link` (mục 2.1) | 4+4 call site trong `NavigationClient.cs` |
| 7 | Getter grid/scan/cloud: sau khi dùng phải gọi `navigation_free_*` tương ứng (trước đây không có hàm free → mỗi lời gọi rò ~1 MB với map 1000×1000) | các hàm Get*Map/Scan/Cloud |
| 8 | `navigation_add_odometry` giờ là **feedback vận tốc cho controller mỗi cycle** — bơm đúng nhịp nguồn odometry, không được thưa/bỏ | đường bơm odometry |
### C4. Nên làm thêm (không bắt buộc để chạy)
- `navigation_add_depth_camera_data` cho `/camera/depth/data` và `/camera_right/depth/data` — đường duy nhất bật clear theo frustum (xoá vật cản ma). Point cloud không thay thế được. Mẫu code ghim mảng: Guide Phụ lục B.3.
- `navigation_move_to_order_v2` nếu fleet gửi order update (cùng `orderId`, `orderUpdateId` tăng). `navigation_move_to_nodes_edges` (đang dùng 6 chỗ) không mang được định danh — mọi lời gọi là order mới.
---
## 6. C# nhóm D — config/môi trường (viết lại 2026-08-10)
Bản đầu của mục này chỉ nói tới `launchSettings.json`. Đối chiếu lại cho thấy **như vậy chưa đủ**:
sửa file đó chỉ có tác dụng trên máy dev, robot thật không đọc nó. Chia lại thành hai đường triển
khai.
### D1. Máy dev (`dotnet run`)
| File | Hiện tại | Phải đổi thành |
|---|---|---|
| `Properties/launchSettings.json:13` | `PNKX_NAV_CORE_LIBRARY_PATH: /home/mic-733ao/sonvh/pnkx_nav_core/build` | đường chứa `libnav_c_api.so` + `libmove_base2.so` + toàn bộ plugin trên máy đang chạy |
| `Properties/launchSettings.json:14` | `PNKX_NAV_CORE_CONFIG_DIR: /home/mic-733ao/sonvh/pnkx_nav_core/config` | `.../Test/move_base2/config/runtime` — **không** phải `pnkx_nav_core/config`; sai chỗ này là đổi tham số planner mãi không ăn |
| `NavigationNativeInterface.cs:20` | candidate path máy cũ | xem A5 |
| `NavigationClient.cs:49-52` | tên biến dùng như giá trị + hardcode | xem A6 |
### D2. Robot thật (systemd) — phần bản đầu bỏ sót
**`launchSettings.json` là file chỉ dành cho phát triển.** `dotnet publish` không đóng gói nó và
runtime không đọc nó ở môi trường Production. Robot khởi động qua unit:
```
RobotApp/RobotNet12.RobotApp/systemd/robotnet-robotapp.service
ExecStart=/opt/robotnet/robotapp/RobotNet12.RobotApp
WorkingDirectory=/opt/robotnet/robotapp
Environment=DOTNET_ENVIRONMENT=Production
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=ASPNETCORE_URLS=http://0.0.0.0:8080
```
`grep` toàn repo: hai biến `PNKX_NAV_CORE_*` **chỉ xuất hiện trong `launchSettings.json`**. Nghĩa là
trên robot **cả hai đều không được đặt**, và `robot::NodeHandle` rơi xuống nhánh cuối cùng — dò
`../../config`, `../config`, `config` tương đối với `/proc/self/exe`, tức quanh
`/opt/robotnet/robotapp/`. Không có cây config nào ở đó, nên `findLibraryPath("MoveBase")` trả rỗng
và `navigation_create()` trả `NULL`.
**Phải thêm vào unit file:**
```ini
[Service]
Environment=PNKX_NAV_CORE_CONFIG_DIR=/opt/robotnet/navcore/config/runtime
Environment=PNKX_NAV_CORE_LIBRARY_PATH=/opt/robotnet/navcore/lib
```
### D3. `ProtectHome=true` chặn mọi đường dẫn `/home` trên robot
Cùng unit file:
```ini
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/dev/shm /var/log/robotnet /opt/robotnet/robotapp
```
`ProtectHome=true` làm `/home` **không truy cập được** đối với tiến trình. Hệ quả trực tiếp:
- candidate `/home/mic-733ao/sonvh/pnkx_nav_core/build/...` ở A5 — không dùng được trên robot;
- hardcode `/home/mic-733ao/...` ở A6 (`NavigationClient.cs:52`) — không dùng được trên robot;
- **và cả đề xuất thay bằng `/home/duongtd/T800_ws/...`** — cũng không dùng được. Đường đó chỉ hợp
cho máy dev.
`ProtectSystem=strict` giữ phần còn lại của hệ thống ở chế độ chỉ đọc, nhưng **vẫn đọc được** — nên
`.so` và cây config đặt ở `/usr/local/lib` hoặc `/opt/robotnet/navcore/` đều hợp lệ.
**Bố cục triển khai đề nghị** (ngoài `/home`, khớp với D2):
```
/opt/robotnet/navcore/lib/ libnav_c_api.so, libmove_base2.so, toàn bộ plugin planner/recovery/costmap
/opt/robotnet/navcore/config/runtime/ bản chép của Test/move_base2/config/runtime
```
và bổ sung `/opt/robotnet/navcore/lib/libnav_c_api.so` vào `CandidateLibraryPaths` (A5) để không phụ
thuộc hoàn toàn vào `LD_LIBRARY_PATH`.
### D4. Cách xác minh đang nạp đúng runtime nào
`navigation_create()` in đường dẫn `.so` đã resolve, ở cấp `debug` nhưng `robot_cpp` **không lọc theo
cấp** nên dòng này luôn hiện:
```
navigation_create: loading navigation plugin from '/…/libmove_base2.so'
```
`journalctl -u robotnet-robotapp | grep "loading navigation plugin"` — thấy `libmove_base2.so` là
đúng runtime mới; thấy `libmove_base.so` là vẫn đang chạy bản cũ (xảy ra khi `PNKX_NAV_CORE_CONFIG_DIR`
trỏ vào `pnkx_nav_core/config`, nơi `move_base_common_params.yaml:60` ghi `library_path: libmove_base`).
Cả hai `.so` đều export alias `MoveBase`, nên nạp nhầm **không sinh lỗi nào** — đây là lý do phải kiểm
bằng dòng log này thay vì suy đoán.
### D5. Cảnh báo vận hành
Từ Guide §6.6: bản `.so` trước 2026-08-08 bỏ qua tham số `linear_x` và hãm trần ±0.1 m/s — sau khi
cập nhật thư viện, robot chạy đúng tốc độ host yêu cầu. **Lần deploy đầu phải quan sát tốc độ thật
trước khi cho chạy tự động.**
---
## 7. Thứ tự thi công đề xuất
0. **Nhóm E (API đã đổi)** — xoá 4 khai báo + 4 wrapper + 6 call site của các hàm không còn tồn tại,
rồi thêm `navigation_execute_instant_actions`. Không làm bước này thì dock/đi thẳng/quay ném
`EntryPointNotFoundException` lúc chạy.
1. **Nhóm D1 + D2 + D3 (môi trường)** — làm **ngay sau E**, không phải bước 3 như bản đầu. Chưa có
biến môi trường đúng thì `navigation_create()` trả `NULL` và mọi việc sau đó không kiểm chứng
được. Trên robot còn phải giải quyết `ProtectHome` trước khi bàn tới code.
2. Nhóm A (sửa binding sai/chết) — A3 làm trước A1/A2 để tránh trùng tên symbol; A6 đi cùng A5.
3. Nhóm B (thêm 13 DllImport + 4 struct).
4. Nhóm C1 + C2 (trình tự khởi tạo/tắt) — không có C1 thì tiến trình chết ngay khi initialize.
5. Nhóm C3 (8 hành vi) — rà từng call site.
6. Chạy thử: xác minh dòng log `loading navigation plugin from '…libmove_base2.so'` (D4) → khởi tạo →
`initialize_checked` trả `true` → gửi goal đơn → pause/cancel → tắt sạch. Sau đó mới bật depth
camera và order_v2 (C4).
7. Kiểm thử thực tế các mục Guide §10 chưa xác nhận: đường depth camera; và đường instant action mới
(E3) — `PickUp` gửi dạng instantAction phải sinh ra đúng chuỗi chặng như khi nó nằm trong order.
---
## 8. Bảng file C# phải sửa
| File | Việc |
|---|---|
| `Modules/Navigation/NavigationNativeInterface.cs` | **E1 (xoá 4 `DllImport` của hàm đã xoá)**, A1–A5, B (13 `DllImport`, nay gồm `navigation_execute_instant_actions` thay cho `navigation_dock_to_order_v2`) |
| `Modules/Navigation/NavigationInterop.cs` | B (4 struct mới) |
| `Modules/Navigation/NavigationClient.cs` | **E1 (xoá 4 wrapper `DockTo`/`DockToOrder`/`MoveStraightTo`/`RotateTo`)**, A1/A2 (footprint), **A6 (đọc env + bỏ hardcode `:49-52`)**, C1 (initialize_checked), C2 (shutdown trong Dispose), C3 |
| `Modules/Navigation/NavigationIntegrationService.cs` | **E1 (4 call site `:836`, `:854`, `:882`, `:901`)**, C1 (đảo thứ tự map/footprint/initialize), C2 (chen shutdown), C3.4 (bỏ vòng poll IsReady) |
| **`Endpoints/NavigationTestEndpoints.cs`** | **E1 — 2 call site `MoveStraightTo`/`RotateTo` (`:83`, `:126`) trỏ vào hàm đã xoá** |
| `Properties/launchSettings.json` | D1 — **chỉ có tác dụng trên máy dev** |
| **`RobotApp/RobotNet12.RobotApp/systemd/robotnet-robotapp.service`** | **D2 (thêm 2 dòng `Environment=`), D3 (bố cục cài đặt ngoài `/home`)** — file này bản đầu không nhắc tới, nhưng đây mới là thứ quyết định trên robot |
| *(triển khai, không phải mã nguồn)* | D3 — chép `.so` + plugin vào `/opt/robotnet/navcore/lib`, cây config vào `/opt/robotnet/navcore/config/runtime` |
---
## 9. Nhật ký sửa đổi
| Ngày | Nội dung |
|---|---|
| 2026-08-10 | Bản đầu: mục 1–8 |
| 2026-08-10 tối | **Đọc lại mã sau đợt refactor.** Thêm **mục 1c / nhóm E**: 5 hàm dock/straight/rotate bị xoá khỏi API (RobotNet12 đang gọi 4/5), năng lực chuyển vào compound action `profile`+`marker`, hàm mới `navigation_execute_instant_actions`. Cập nhật §4, §5 C4, §7 (E lên bước 0), §8. Guide cập nhật đồng bộ |
| 2026-08-10 | **Đối chiếu lại trên mã RobotNet12 thật + `nm`.** Thêm mục **1b** (bảng kiểm chứng, 9/9 khẳng định đúng); thêm **A6**; viết lại **mục 6** thành D1–D5 sau khi phát hiện `launchSettings.json` không áp dụng cho robot và `ProtectHome=true` chặn `/home`; đảo thứ tự thi công (môi trường lên bước 1); bổ sung unit file vào bảng mục 8; đánh dấu §2.3 đã sửa trong Guide |

View File

@@ -3,6 +3,22 @@
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
namespace
{
/**
* @brief Chuỗi rỗng cho một con trỏ NULL.
*
* Mọi `char*` đi qua biên C đều là tuỳ chọn, và chính thư viện này sinh ra NULL cho chuỗi rỗng
* (xem `convert2COccupancyGrid`). Dựng `std::string` thẳng từ con trỏ đó là hành vi không xác định,
* và vòng get -> add của cùng một message là đường chạm vào nó nhanh nhất.
*/
inline const char* safe_cstr(const char* s)
{
return s != nullptr ? s : "";
}
} // namespace
robot_sensor_msgs::LaserScan convert2CppLaserScan(const LaserScan& laser_scan) robot_sensor_msgs::LaserScan convert2CppLaserScan(const LaserScan& laser_scan)
{ {
@@ -10,7 +26,7 @@ robot_sensor_msgs::LaserScan convert2CppLaserScan(const LaserScan& laser_scan)
robot_laser_scan.header.seq = laser_scan.header.seq; robot_laser_scan.header.seq = laser_scan.header.seq;
robot_laser_scan.header.stamp.sec = laser_scan.header.sec; robot_laser_scan.header.stamp.sec = laser_scan.header.sec;
robot_laser_scan.header.stamp.nsec = laser_scan.header.nsec; robot_laser_scan.header.stamp.nsec = laser_scan.header.nsec;
robot_laser_scan.header.frame_id = laser_scan.header.frame_id; robot_laser_scan.header.frame_id = safe_cstr(laser_scan.header.frame_id);
robot_laser_scan.angle_min = laser_scan.angle_min; robot_laser_scan.angle_min = laser_scan.angle_min;
robot_laser_scan.angle_max = laser_scan.angle_max; robot_laser_scan.angle_max = laser_scan.angle_max;
robot_laser_scan.angle_increment = laser_scan.angle_increment; robot_laser_scan.angle_increment = laser_scan.angle_increment;
@@ -33,15 +49,11 @@ robot_sensor_msgs::LaserScan convert2CppLaserScan(const LaserScan& laser_scan)
robot_nav_msgs::OccupancyGrid convert2CppOccupancyGrid(const OccupancyGrid& occupancy_grid) { robot_nav_msgs::OccupancyGrid convert2CppOccupancyGrid(const OccupancyGrid& occupancy_grid) {
robot::log_info("OccupancyGrid sizeof=%zu data_off=%zu data_count_off=%zu",
sizeof(OccupancyGrid),
offsetof(OccupancyGrid, data),
offsetof(OccupancyGrid, data_count));
robot_nav_msgs::OccupancyGrid robot_occupancy_grid; robot_nav_msgs::OccupancyGrid robot_occupancy_grid;
robot_occupancy_grid.header.seq = occupancy_grid.header.seq; robot_occupancy_grid.header.seq = occupancy_grid.header.seq;
robot_occupancy_grid.header.stamp.sec = occupancy_grid.header.sec; robot_occupancy_grid.header.stamp.sec = occupancy_grid.header.sec;
robot_occupancy_grid.header.stamp.nsec = occupancy_grid.header.nsec; robot_occupancy_grid.header.stamp.nsec = occupancy_grid.header.nsec;
robot_occupancy_grid.header.frame_id = occupancy_grid.header.frame_id; robot_occupancy_grid.header.frame_id = safe_cstr(occupancy_grid.header.frame_id);
robot_occupancy_grid.info.map_load_time.sec = occupancy_grid.info.map_load_time.sec; robot_occupancy_grid.info.map_load_time.sec = occupancy_grid.info.map_load_time.sec;
robot_occupancy_grid.info.map_load_time.nsec = occupancy_grid.info.map_load_time.nsec; robot_occupancy_grid.info.map_load_time.nsec = occupancy_grid.info.map_load_time.nsec;
robot_occupancy_grid.info.resolution = occupancy_grid.info.resolution; robot_occupancy_grid.info.resolution = occupancy_grid.info.resolution;
@@ -112,7 +124,8 @@ robot_geometry_msgs::PoseStamped convert2CppPoseStamped(const PoseStamped& c_pos
cpp_pose.header.seq = c_pose.header.seq; cpp_pose.header.seq = c_pose.header.seq;
cpp_pose.header.stamp.sec = c_pose.header.sec; cpp_pose.header.stamp.sec = c_pose.header.sec;
cpp_pose.header.stamp.nsec = c_pose.header.nsec; cpp_pose.header.stamp.nsec = c_pose.header.nsec;
cpp_pose.header.frame_id = c_pose.header.frame_id; cpp_pose.header.frame_id = safe_cstr(c_pose.header.frame_id);
cpp_pose.pose.position.x = c_pose.pose.position.x; cpp_pose.pose.position.x = c_pose.pose.position.x;
cpp_pose.pose.position.y = c_pose.pose.position.y; cpp_pose.pose.position.y = c_pose.pose.position.y;
@@ -151,6 +164,20 @@ Pose2D convert2CPose2D(const robot_geometry_msgs::Pose2D& cpp_pose)
c_pose.theta = cpp_pose.theta; c_pose.theta = cpp_pose.theta;
return c_pose; return c_pose;
} }
// Convert C Pose2D to C++ Pose2D.
//
// Đã được khai báo trong convertor.h và được navigation_offset_goal_2d gọi từ đầu, nhưng chưa bao
// giờ có định nghĩa: thư viện chia sẻ vẫn link được với một symbol chưa phân giải, nên lỗi chỉ hiện
// ra lúc chạy, ở đúng lời gọi đầu tiên.
robot_geometry_msgs::Pose2D convert2CppPose2D(const Pose2D& pose_2d)
{
robot_geometry_msgs::Pose2D cpp_pose;
cpp_pose.x = pose_2d.x;
cpp_pose.y = pose_2d.y;
cpp_pose.theta = pose_2d.theta; // [rad]
return cpp_pose;
}
Header convert2CHeader(const robot_std_msgs::Header& cpp_header) Header convert2CHeader(const robot_std_msgs::Header& cpp_header)
{ {
Header c_header; Header c_header;
@@ -380,21 +407,28 @@ robot_sensor_msgs::PointCloud convert2CppPointCloud(const PointCloud& c)
cpp.header.seq = c.header.seq; cpp.header.seq = c.header.seq;
cpp.header.stamp.sec = c.header.sec; cpp.header.stamp.sec = c.header.sec;
cpp.header.stamp.nsec = c.header.nsec; cpp.header.stamp.nsec = c.header.nsec;
cpp.header.frame_id = c.header.frame_id ? c.header.frame_id : ""; cpp.header.frame_id = safe_cstr(c.header.frame_id);
cpp.points.resize(c.points_count);
for (size_t i = 0; i < c.points_count && c.points; ++i) // Kích thước lấy TỪ con trỏ, không từ bộ đếm: con trỏ NULL kèm bộ đếm khác 0 là dữ liệu hỏng, và
// resize theo bộ đếm sẽ cấp phát một vector khổng lồ rồi không bao giờ điền vào.
const size_t points_size = c.points ? c.points_count : 0;
cpp.points.resize(points_size);
for (size_t i = 0; i < points_size; ++i)
{ {
cpp.points[i].x = c.points[i].x; cpp.points[i].x = c.points[i].x;
cpp.points[i].y = c.points[i].y; cpp.points[i].y = c.points[i].y;
cpp.points[i].z = c.points[i].z; cpp.points[i].z = c.points[i].z;
} }
cpp.channels.resize(c.channels_count);
for (size_t i = 0; i < c.channels_count && c.channels; ++i) const size_t channels_size = c.channels ? c.channels_count : 0;
cpp.channels.resize(channels_size);
for (size_t i = 0; i < channels_size; ++i)
{ {
cpp.channels[i].name = c.channels[i].name ? c.channels[i].name : ""; cpp.channels[i].name = safe_cstr(c.channels[i].name);
cpp.channels[i].values.resize(c.channels[i].values_count); const size_t values_size = c.channels[i].values ? c.channels[i].values_count : 0;
if (c.channels[i].values && c.channels[i].values_count > 0) cpp.channels[i].values.resize(values_size);
memcpy(cpp.channels[i].values.data(), c.channels[i].values, c.channels[i].values_count * sizeof(float)); if (values_size > 0)
memcpy(cpp.channels[i].values.data(), c.channels[i].values, values_size * sizeof(float));
} }
return cpp; return cpp;
} }
@@ -405,24 +439,29 @@ robot_sensor_msgs::PointCloud2 convert2CppPointCloud2(const PointCloud2& c)
cpp.header.seq = c.header.seq; cpp.header.seq = c.header.seq;
cpp.header.stamp.sec = c.header.sec; cpp.header.stamp.sec = c.header.sec;
cpp.header.stamp.nsec = c.header.nsec; cpp.header.stamp.nsec = c.header.nsec;
cpp.header.frame_id = c.header.frame_id ? c.header.frame_id : ""; cpp.header.frame_id = safe_cstr(c.header.frame_id);
cpp.height = c.height; cpp.height = c.height;
cpp.width = c.width; cpp.width = c.width;
cpp.is_bigendian = c.is_bigendian; cpp.is_bigendian = c.is_bigendian;
cpp.point_step = c.point_step; cpp.point_step = c.point_step;
cpp.row_step = c.row_step; cpp.row_step = c.row_step;
cpp.is_dense = c.is_dense; cpp.is_dense = c.is_dense;
cpp.fields.resize(c.fields_count);
for (size_t i = 0; i < c.fields_count && c.fields; ++i) // Kích thước lấy từ con trỏ, không từ bộ đếm — xem ghi chú ở convert2CppPointCloud.
const size_t fields_size = c.fields ? c.fields_count : 0;
cpp.fields.resize(fields_size);
for (size_t i = 0; i < fields_size; ++i)
{ {
cpp.fields[i].name = c.fields[i].name ? c.fields[i].name : ""; cpp.fields[i].name = safe_cstr(c.fields[i].name);
cpp.fields[i].offset = c.fields[i].offset; cpp.fields[i].offset = c.fields[i].offset;
cpp.fields[i].datatype = c.fields[i].datatype; cpp.fields[i].datatype = c.fields[i].datatype;
cpp.fields[i].count = c.fields[i].count; cpp.fields[i].count = c.fields[i].count;
} }
cpp.data.resize(c.data_count);
if (c.data && c.data_count > 0) const size_t data_size = c.data ? c.data_count : 0;
memcpy(cpp.data.data(), c.data, c.data_count); cpp.data.resize(data_size);
if (data_size > 0)
memcpy(cpp.data.data(), c.data, data_size);
return cpp; return cpp;
} }
@@ -529,7 +568,7 @@ static Trajectory convert2CTrajectory(const robot_protocol_msgs::Trajectory& cpp
return c; return c;
} }
static robot_protocol_msgs::Action convert2CppAction(const Action& c) robot_protocol_msgs::Action convert2CppAction(const Action& c)
{ {
robot_protocol_msgs::Action cpp; robot_protocol_msgs::Action cpp;
cpp.actionType = c.actionType ? c.actionType : ""; cpp.actionType = c.actionType ? c.actionType : "";

View File

@@ -0,0 +1,78 @@
#include "convertor_2.h"
#include <algorithm>
#include <cstddef>
#include <string>
namespace
{
/// Empty string for a NULL C string — every char* coming from the host is optional.
inline std::string safe_string(const char* s)
{
return s != nullptr ? std::string(s) : std::string();
}
} // namespace
robot_std_msgs::Header convert2CppHeader(const Header& header)
{
robot_std_msgs::Header cpp;
cpp.seq = header.seq;
cpp.stamp.sec = header.sec;
cpp.stamp.nsec = header.nsec;
cpp.frame_id = safe_string(header.frame_id);
return cpp;
}
robot_sensor_msgs::Image convert2CppImage(const Image& image)
{
robot_sensor_msgs::Image cpp;
cpp.header = convert2CppHeader(image.header);
cpp.height = image.height;
cpp.width = image.width;
cpp.encoding = safe_string(image.encoding);
cpp.is_bigendian = image.is_bigendian;
cpp.step = image.step;
// Copy, never alias: the host buffer may be a pinned .NET array released right after this call,
// while the voxel layer reads the sample later on the map-update thread.
const size_t count = image.data != nullptr ? image.data_count : 0;
cpp.data.assign(image.data, image.data + count);
return cpp;
}
robot_sensor_msgs::CameraInfo convert2CppCameraInfo(const CameraInfo& info)
{
robot_sensor_msgs::CameraInfo cpp;
cpp.header = convert2CppHeader(info.header);
cpp.height = info.height;
cpp.width = info.width;
cpp.distortion_model = safe_string(info.distortion_model);
const size_t d_count = info.D != nullptr ? info.D_count : 0;
cpp.D.assign(info.D, info.D + d_count);
std::copy(info.K, info.K + 9, cpp.K.begin());
std::copy(info.R, info.R + 9, cpp.R.begin());
std::copy(info.P, info.P + 12, cpp.P.begin());
cpp.binning_x = info.binning_x;
cpp.binning_y = info.binning_y;
cpp.roi.x_offset = info.roi.x_offset;
cpp.roi.y_offset = info.roi.y_offset;
cpp.roi.height = info.roi.height;
cpp.roi.width = info.roi.width;
cpp.roi.do_rectify = info.roi.do_rectify;
return cpp;
}
robot_sensor_msgs::DepthCameraData convert2CppDepthCameraData(const DepthCameraData& data)
{
robot_sensor_msgs::DepthCameraData cpp;
cpp.header = convert2CppHeader(data.header);
cpp.depth = convert2CppImage(data.depth);
cpp.camera_info = convert2CppCameraInfo(data.camera_info);
return cpp;
}

View File

@@ -83,7 +83,7 @@ extern "C" NavigationHandle navigation_create(void)
// Using default constructor - initialization will be done via navigation_initialize() // Using default constructor - initialization will be done via navigation_initialize()
robot::PluginLoaderHelper loader; robot::PluginLoaderHelper loader;
std::string path_file_so = loader.findLibraryPath("MoveBase"); std::string path_file_so = loader.findLibraryPath("MoveBase");
robot::log_warning("%s", path_file_so.c_str()); robot::log_debug("navigation_create: loading navigation plugin from '%s'", path_file_so.c_str());
auto move_base_loader = boost::dll::import_alias<robot::move_base_core::BaseNavigation::Ptr()>( auto move_base_loader = boost::dll::import_alias<robot::move_base_core::BaseNavigation::Ptr()>(
path_file_so, "MoveBase", boost::dll::load_mode::append_decorations); path_file_so, "MoveBase", boost::dll::load_mode::append_decorations);
auto move_base_ptr = move_base_loader(); auto move_base_ptr = move_base_loader();
@@ -101,11 +101,15 @@ extern "C" NavigationHandle navigation_create(void)
} }
catch (const std::exception &e) catch (const std::exception &e)
{ {
// Log error if possible (in production, use proper logging) // Đây là chỗ hỏng thường xuyên nhất của cả API: sai `library_path`, sai
// PNKX_NAV_CORE_CONFIG_DIR, hoặc .so không nằm trong đường tìm. Nuốt lý do là buộc người dùng
// đoán mò từ một con trỏ NULL.
robot::log_error("navigation_create failed: %s", e.what());
return nullptr; return nullptr;
} }
catch (...) catch (...)
{ {
robot::log_error("navigation_create failed: unknown exception");
return nullptr; return nullptr;
} }
} }
@@ -128,12 +132,12 @@ extern "C" bool navigation_initialize(NavigationHandle handle, TFListenerHandle
{ {
if (!handle || !tf_handle) if (!handle || !tf_handle)
{ {
printf("[%s:%d]\n Error: Invalid parameters\n", __FILE__, __LINE__); robot::log_error("navigation_initialize: null handle or tf3 buffer");
return false; return false;
} }
try try
{ {
printf("[%s:%d]: Initialize navigation\n", __FILE__, __LINE__); robot::log_info("navigation_initialize: bringing up the navigation core");
std::shared_ptr<robot::move_base_core::BaseNavigation> nav_ptr = std::shared_ptr<robot::move_base_core::BaseNavigation> nav_ptr =
std::shared_ptr<robot::move_base_core::BaseNavigation>( std::shared_ptr<robot::move_base_core::BaseNavigation>(
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {}); reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
@@ -145,7 +149,7 @@ extern "C" bool navigation_initialize(NavigationHandle handle, TFListenerHandle
std::shared_ptr<tf3::BufferCore>(reinterpret_cast<tf3::BufferCore *>(tf_handle), [](::tf3::BufferCore *) {}); std::shared_ptr<tf3::BufferCore>(reinterpret_cast<tf3::BufferCore *>(tf_handle), [](::tf3::BufferCore *) {});
if (!tf_ptr) if (!tf_ptr)
{ {
printf("[%s:%d]\n Error: Invalid TF listener", __FILE__, __LINE__); robot::log_error("navigation_initialize: invalid TF listener");
return false; return false;
} }
nav_ptr->initialize(tf_ptr); nav_ptr->initialize(tf_ptr);
@@ -154,11 +158,12 @@ extern "C" bool navigation_initialize(NavigationHandle handle, TFListenerHandle
} }
catch (const std::exception &e) catch (const std::exception &e)
{ {
printf("[%s:%d]\n Error: Failed to initialize navigation: %s\n", __FILE__, __LINE__, e.what()); robot::log_error("navigation_initialize failed: %s", e.what());
return false; return false;
} }
catch (...) catch (...)
{ {
robot::log_error("navigation_initialize failed: unknown exception");
return false; return false;
} }
} }
@@ -183,17 +188,21 @@ extern "C" bool navigation_set_robot_footprint(NavigationHandle handle, const Po
footprint.reserve(point_count); footprint.reserve(point_count);
for (size_t i = 0; i < point_count; ++i) for (size_t i = 0; i < point_count; ++i)
{ {
robot_geometry_msgs::Point pt; robot_geometry_msgs::Point pt;
pt.x = points[i].x; pt.x = points[i].x;
pt.y = points[i].y; pt.y = points[i].y;
pt.z = points[i].z; pt.z = points[i].z;
printf("footprint x: %f, y: %f\n", pt.x, pt.y);
footprint.push_back(pt); footprint.push_back(pt);
} }
nav_ptr->setRobotFootprint(footprint); nav_ptr->setRobotFootprint(footprint);
robot::log_debug("navigation_set_robot_footprint: %zu points", point_count);
return true; return true;
} }
catch (const std::exception &e)
{
robot::log_error("navigation_set_robot_footprint failed: %s", e.what());
return false;
}
catch (...) catch (...)
{ {
return false; return false;
@@ -281,18 +290,20 @@ extern "C" bool navigation_move_to_order(NavigationHandle handle, const Order or
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {}); reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
if (!nav_ptr) if (!nav_ptr)
return false; return false;
robot::log_error("navigation_move_to_order goal %f %f", goal.pose.position.x, goal.pose.position.y); robot::log_debug("navigation_move_to_order: goal (%.3f, %.3f)", goal.pose.position.x,
goal.pose.position.y);
robot_protocol_msgs::Order cpp_order = convert2CppOrder(order); robot_protocol_msgs::Order cpp_order = convert2CppOrder(order);
robot_geometry_msgs::PoseStamped cpp_goal = convert2CppPoseStamped(goal); robot_geometry_msgs::PoseStamped cpp_goal = convert2CppPoseStamped(goal);
return nav_ptr->moveTo(cpp_order, cpp_goal); return nav_ptr->moveTo(cpp_order, cpp_goal);
} }
catch (const std::exception &e) catch (const std::exception &e)
{ {
robot::log_error("navigation_move_to_order failed: %s", e.what());
return false; return false;
} }
catch (...) catch (...)
{ {
printf("[%s:%d]\n Error: Failed to move to order\n", __FILE__, __LINE__); robot::log_error("navigation_move_to_order failed: unknown exception");
return false; return false;
} }
} }
@@ -316,8 +327,11 @@ extern "C" bool navigation_move_to_nodes_edges(NavigationHandle handle, const No
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {}); reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
if (!nav_ptr) if (!nav_ptr)
return false; return false;
robot::log_error("navigation_move_to_nodes_edges goal %f %f", goal.pose.position.x, goal.pose.position.y); robot::log_debug("navigation_move_to_nodes_edges: goal (%.3f, %.3f)", goal.pose.position.x,
Order order; goal.pose.position.y);
// Zero-init: the fields left unset below are all char*, and convert2CppOrder treats any
// non-null pointer as a valid string — an uninitialized struct hands it stack garbage.
Order order{};
order.nodes = const_cast<Node *>(nodes); order.nodes = const_cast<Node *>(nodes);
order.nodes_count = node_count; order.nodes_count = node_count;
order.edges = const_cast<Edge *>(edges); order.edges = const_cast<Edge *>(edges);
@@ -328,171 +342,23 @@ extern "C" bool navigation_move_to_nodes_edges(NavigationHandle handle, const No
} }
catch (const std::exception &e) catch (const std::exception &e)
{ {
robot::log_error("navigation_move_to_nodes_edges failed: %s", e.what());
return false; return false;
} }
catch (...) catch (...)
{ {
printf("[%s:%d]\n Error: Failed to move to order\n", __FILE__, __LINE__); robot::log_error("navigation_move_to_nodes_edges failed: unknown exception");
return false;
}
}
extern "C" bool navigation_dock_to(NavigationHandle handle, const char *marker, const PoseStamped goal)
{
if (!handle || !marker)
{
return false;
}
if (!isQuaternionValid(goal.pose.orientation))
{
robot::log_error("Goal quaternion is invalid");
return false;
}
try
{
std::shared_ptr<robot::move_base_core::BaseNavigation> nav_ptr =
std::shared_ptr<robot::move_base_core::BaseNavigation>(
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
if (!nav_ptr)
return false;
robot_geometry_msgs::PoseStamped cpp_goal = convert2CppPoseStamped(goal);
return nav_ptr->dockTo(std::string(marker), cpp_goal);
}
catch (...)
{
return false; return false;
} }
} }
extern "C" bool navigation_dock_to_order(NavigationHandle handle, const Order order, const char *marker, const PoseStamped goal) // navigation_dock_to, navigation_dock_to_order, navigation_dock_to_nodes_edges,
{ // navigation_move_straight_to and navigation_rotate_to were removed along with the
if (!handle || !marker) // BaseNavigation methods they forwarded to. Those methods bypassed the mission layer, so a goal
{ // arriving through them replaced the leg the mission queue was running without the queue noticing.
return false; // Docking, go-straight and rotate now travel as ordinary legs of an order: set `profile:` on the
} // leg (`docking | go_straight | rotate`) plus `marker` for docking, then send it through
if (!isQuaternionValid(goal.pose.orientation)) // navigation_move_to_order / navigation_move_to_nodes_edges.
{
robot::log_error("Goal quaternion is invalid");
return false;
}
try
{
std::shared_ptr<robot::move_base_core::BaseNavigation> nav_ptr =
std::shared_ptr<robot::move_base_core::BaseNavigation>(
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
if (!nav_ptr)
return false;
robot_protocol_msgs::Order cpp_order = convert2CppOrder(order);
robot_geometry_msgs::PoseStamped cpp_goal = convert2CppPoseStamped(goal);
return nav_ptr->dockTo(cpp_order, std::string(marker), cpp_goal);
}
catch (const std::exception &e)
{
return false;
}
catch (...)
{
printf("[%s:%d]\n Error: Failed to dock to order\n", __FILE__, __LINE__);
return false;
}
}
extern "C" bool navigation_dock_to_nodes_edges(NavigationHandle handle, const char *marker, const Node *nodes, size_t node_count, const Edge *edges, size_t edge_count, const PoseStamped goal)
{
if (!handle || !marker)
{
return false;
}
if (!isQuaternionValid(goal.pose.orientation))
{
robot::log_error("Goal quaternion is invalid");
return false;
}
try
{
std::shared_ptr<robot::move_base_core::BaseNavigation> nav_ptr =
std::shared_ptr<robot::move_base_core::BaseNavigation>(
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
if (!nav_ptr)
return false;
Order order;
order.nodes = const_cast<Node *>(nodes);
order.nodes_count = node_count;
order.edges = const_cast<Edge *>(edges);
order.edges_count = edge_count;
robot_protocol_msgs::Order cpp_order = convert2CppOrder(order);
robot_geometry_msgs::PoseStamped cpp_goal = convert2CppPoseStamped(goal);
return nav_ptr->dockTo(cpp_order, std::string(marker), cpp_goal);
}
catch (const std::exception &e)
{
return false;
}
catch (...)
{
printf("[%s:%d]\n Error: Failed to dock to nodes edges\n", __FILE__, __LINE__);
return false;
}
}
extern "C" bool navigation_move_straight_to(NavigationHandle handle, const double distance)
{
if (!handle)
{
return false;
}
try
{
std::shared_ptr<robot::move_base_core::BaseNavigation> nav_ptr =
std::shared_ptr<robot::move_base_core::BaseNavigation>(
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
if (!nav_ptr)
return false;
robot_geometry_msgs::PoseStamped pose;
if (!nav_ptr->getRobotPose(pose))
return false;
robot_geometry_msgs::Pose2D pose2d;
pose2d.x = pose.pose.position.x;
pose2d.y = pose.pose.position.y;
pose2d.theta = data_convert::getYaw(pose.pose.orientation);
robot::log_error("pose2d: %f %f %f", pose2d.x, pose2d.y, pose2d.theta);
robot_geometry_msgs::PoseStamped goal = robot::move_base_core::offset_goal(pose, distance);
return nav_ptr->moveStraightTo(goal);
}
catch (...)
{
return false;
}
}
extern "C" bool navigation_rotate_to(NavigationHandle handle, const PoseStamped goal)
{
if (!handle)
{
return false;
}
if (!isQuaternionValid(goal.pose.orientation))
{
robot::log_error("Goal quaternion is invalid");
return false;
}
try
{
std::shared_ptr<robot::move_base_core::BaseNavigation> nav_ptr =
std::shared_ptr<robot::move_base_core::BaseNavigation>(
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
if (!nav_ptr)
return false;
robot_geometry_msgs::PoseStamped cpp_goal = convert2CppPoseStamped(goal);
return nav_ptr->rotateTo(cpp_goal);
}
catch (...)
{
return false;
}
}
extern "C" void navigation_pause(NavigationHandle handle) extern "C" void navigation_pause(NavigationHandle handle)
{ {
@@ -568,11 +434,28 @@ extern "C" bool navigation_set_twist_linear(NavigationHandle handle,
if (!nav_ptr) if (!nav_ptr)
return false; return false;
// Giá trị đi xuống lõi NGUYÊN DẠNG, không lấy trị tuyệt đối: DẤU của linear_x là thứ chọn chiều
// mà trần này áp vào — âm đặt trần lùi, dương đặt trần tiến (local planner giữ hai trần riêng,
// xem move_base2 navigation_server.cpp:921-944). Ép về trị tuyệt đối là bỏ mất nửa thông tin
// của lời gọi.
//
// Vì vậy một lời gọi chỉ đặt MỘT chiều. Host muốn đặt cả hai thì gọi hai lần, đúng như host ROS
// đang làm (amr_control.cpp:707-709, amr_vda_5050_client_api.cpp:410-414).
robot_geometry_msgs::Vector3 linear; robot_geometry_msgs::Vector3 linear;
linear.x = linear_x; linear.x = linear_x;
linear.y = linear_y; linear.y = linear_y;
linear.z = linear_z; linear.z = linear_z;
return nav_ptr->setTwistLinear(linear);
const bool accepted = nav_ptr->setTwistLinear(linear);
robot::log_debug("navigation_set_twist_linear: %s ceiling %.3f m/s (%s)",
linear_x < 0.0 ? "backward" : "forward", linear_x,
accepted ? "accepted" : "rejected");
return accepted;
}
catch (const std::exception &e)
{
robot::log_error("navigation_set_twist_linear failed: %s", e.what());
return false;
} }
catch (...) catch (...)
{ {
@@ -736,12 +619,19 @@ extern "C" bool navigation_add_static_map(NavigationHandle handle, const char *m
if (!nav_ptr) if (!nav_ptr)
return false; return false;
robot::log_info("occupancy_grid.data_count: %d", occupancy_grid.data_count);
robot_nav_msgs::OccupancyGrid robot_occupancy_grid = convert2CppOccupancyGrid(occupancy_grid); robot_nav_msgs::OccupancyGrid robot_occupancy_grid = convert2CppOccupancyGrid(occupancy_grid);
robot::log_debug("navigation_add_static_map: '%s' %ux%u, %zu cells", map_name,
occupancy_grid.info.width, occupancy_grid.info.height,
occupancy_grid.data_count);
nav_ptr->addStaticMap(std::string(map_name), robot_occupancy_grid); nav_ptr->addStaticMap(std::string(map_name), robot_occupancy_grid);
return true; return true;
} }
catch (const std::exception &e)
{
robot::log_error("navigation_add_static_map('%s') failed: %s", map_name, e.what());
return false;
}
catch (...) catch (...)
{ {
return false; return false;
@@ -957,6 +847,11 @@ extern "C" bool navigation_get_all_static_maps(NavigationHandle handle, NamedOcc
return false; return false;
auto maps = nav_ptr->getAllStaticMaps(); auto maps = nav_ptr->getAllStaticMaps();
if (maps.empty())
{
out_count = 0;
return true;
}
out_count = maps.size(); out_count = maps.size();
size_t i = 0; size_t i = 0;
for (const auto &p : maps) for (const auto &p : maps)

View File

@@ -0,0 +1,445 @@
/**
* @file nav_c_api_2.cpp
* @brief Implementation of the move_base2 additions to the C navigation API.
*
* Deliberately separate from nav_c_api.cpp: the surface the existing binding depends on stays byte
* for byte where it is, and everything move_base2 needs on top of it lands here, where it can be
* reviewed — or dropped — on its own.
*
* The handle is the same opaque `robot::move_base_core::BaseNavigation*` navigation_create()
* returns; ownership still lives in nav_c_api.cpp, so nothing here creates or frees an instance.
*/
#include "nav_c_api_2.h"
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <boost/make_shared.hpp>
#include <robot/robot.h>
#include <move_base_core/common.h>
#include <move_base_core/navigation.h>
#include <robot_sensor_msgs/DepthCameraData.h>
#include "convertor.h"
#include "convertor_2.h"
namespace
{
/// Non-owning view of the handle. The instance is owned by the table in nav_c_api.cpp.
inline robot::move_base_core::BaseNavigation *as_navigation(NavigationHandle handle)
{
return static_cast<robot::move_base_core::BaseNavigation *>(handle);
}
/**
* @brief Build a C Order from an id plus the node/edge arrays the host owns.
*
* Zero-initialized on purpose. Every optional field of Order is a char*, and the converter treats a
* non-null pointer as a valid string — an uninitialized struct therefore hands it stack garbage to
* build std::string from. The pointers below stay non-owning: the converter copies before this
* returns, and the arrays are never freed here.
*/
Order make_order(const char *order_id, uint32_t order_update_id,
const Node *nodes, size_t node_count,
const Edge *edges, size_t edge_count)
{
Order order{};
order.orderId = const_cast<char *>(order_id);
order.orderUpdateId = order_update_id;
order.nodes = const_cast<Node *>(nodes);
order.nodes_count = nodes != nullptr ? node_count : 0;
order.edges = const_cast<Edge *>(edges);
order.edges_count = edges != nullptr ? edge_count : 0;
return order;
}
} // namespace
// ================================================================================================
// Lifecycle
// ================================================================================================
extern "C" bool navigation_initialize_checked(NavigationHandle handle, TFListenerHandle tf3_buffer)
{
if (!handle || !tf3_buffer)
{
robot::log_error("navigation_initialize_checked: null handle or tf3 buffer");
return false;
}
try
{
auto *nav = as_navigation(handle);
// The host owns the buffer and must outlive the core; hand over a non-owning alias.
robot::TFListenerPtr tf(static_cast<tf3::BufferCore *>(tf3_buffer),
[](tf3::BufferCore *) {});
nav->initialize(tf);
// initialize() returns void, so the runtime reports failure the only way it can: it leaves
// is_ready false and writes the reason into the feedback. Not reading it back is how a host
// ends up pushing goals into a core that has no control thread.
robot::move_base_core::NavFeedback *feedback = nav->getFeedback();
if (feedback == nullptr)
{
robot::log_error("navigation_initialize_checked: core exposes no feedback");
return false;
}
if (!feedback->is_ready)
{
robot::log_error("navigation_initialize_checked: core not ready: %s",
feedback->feed_back_str.c_str());
return false;
}
return true;
}
catch (const std::exception &e)
{
robot::log_error("navigation_initialize_checked failed: %s", e.what());
return false;
}
catch (...)
{
robot::log_error("navigation_initialize_checked failed: unknown exception");
return false;
}
}
extern "C" bool navigation_is_ready(NavigationHandle handle)
{
if (!handle)
{
return false;
}
try
{
robot::move_base_core::NavFeedback *feedback = as_navigation(handle)->getFeedback();
return feedback != nullptr && feedback->is_ready;
}
catch (...)
{
return false;
}
}
extern "C" void navigation_shutdown(NavigationHandle handle)
{
if (!handle)
{
return;
}
try
{
as_navigation(handle)->shutdown();
}
catch (const std::exception &e)
{
// Swallowed on purpose: this runs inside the host's shutdown sequence, where throwing across
// the C boundary would abort a process that is already on its way down.
robot::log_error("navigation_shutdown failed: %s", e.what());
}
catch (...)
{
robot::log_error("navigation_shutdown failed: unknown exception");
}
}
// ================================================================================================
// Status
// ================================================================================================
extern "C" bool navigation_get_state(NavigationHandle handle, NavigationState *out_state)
{
if (!handle || !out_state)
{
return false;
}
try
{
robot::move_base_core::NavFeedback *feedback = as_navigation(handle)->getFeedback();
if (feedback == nullptr)
{
return false;
}
*out_state = static_cast<NavigationState>(static_cast<int>(feedback->navigation_state));
return true;
}
catch (...)
{
return false;
}
}
extern "C" char *navigation_get_status_text(NavigationHandle handle)
{
if (!handle)
{
return nullptr;
}
try
{
robot::move_base_core::NavFeedback *feedback = as_navigation(handle)->getFeedback();
if (feedback == nullptr || feedback->feed_back_str.empty())
{
return nullptr;
}
return strdup(feedback->feed_back_str.c_str());
}
catch (...)
{
return nullptr;
}
}
// ================================================================================================
// Sensor input
// ================================================================================================
extern "C" bool navigation_add_depth_camera_data(NavigationHandle handle, const char *topic,
const DepthCameraData data)
{
if (!handle || !topic)
{
return false;
}
try
{
// ConstPtr is a boost::shared_ptr and the core keeps the sample for as long as it needs it, so
// hand it a copy rather than a view of host memory.
auto sample = boost::make_shared<robot_sensor_msgs::DepthCameraData>(
convert2CppDepthCameraData(data));
as_navigation(handle)->addDepthCameraData(std::string(topic), sample);
return true;
}
catch (const std::exception &e)
{
robot::log_error("navigation_add_depth_camera_data failed: %s", e.what());
return false;
}
catch (...)
{
return false;
}
}
// ================================================================================================
// Orders
// ================================================================================================
extern "C" bool navigation_move_to_order_v2(NavigationHandle handle,
const char *order_id, uint32_t order_update_id,
const Node *nodes, size_t node_count,
const Edge *edges, size_t edge_count,
const PoseStamped goal)
{
if (!handle || order_id == nullptr || order_id[0] == '\0')
{
robot::log_error("navigation_move_to_order_v2: null handle or empty orderId");
return false;
}
if (!isQuaternionValid(goal.pose.orientation))
{
robot::log_error("navigation_move_to_order_v2: goal quaternion is invalid");
return false;
}
try
{
const Order order = make_order(order_id, order_update_id, nodes, node_count, edges, edge_count);
return as_navigation(handle)->moveTo(convert2CppOrder(order), convert2CppPoseStamped(goal));
}
catch (const std::exception &e)
{
robot::log_error("navigation_move_to_order_v2 failed: %s", e.what());
return false;
}
catch (...)
{
return false;
}
}
extern "C" bool navigation_execute_instant_actions(NavigationHandle handle, const Action *actions,
size_t count)
{
if (!handle || actions == nullptr || count == 0)
{
robot::log_error("navigation_execute_instant_actions: null handle, null array or zero count");
return false;
}
// Kiểm ở đây thay vì để adapter làm: bên kia ranh giới C, một con trỏ null và một chuỗi rỗng nhìn
// giống nhau, và thông báo lỗi phải nói được là phía gọi thiếu gì, ở phần tử nào.
std::vector<robot_protocol_msgs::Action> cpp_actions;
cpp_actions.reserve(count);
for (size_t i = 0; i < count; ++i)
{
const Action &action = actions[i];
if (action.actionType == nullptr || action.actionType[0] == '\0')
{
robot::log_error("navigation_execute_instant_actions: action %zu has a null or empty "
"actionType", i);
return false;
}
if (action.actionId == nullptr || action.actionId[0] == '\0')
{
robot::log_error("navigation_execute_instant_actions: action %zu ('%s') has a null or empty "
"actionId — the fleet needs it to match the result back to its request",
i, action.actionType);
return false;
}
cpp_actions.push_back(convert2CppAction(action));
}
try
{
return as_navigation(handle)->executeInstantActions(cpp_actions);
}
catch (const std::exception &e)
{
robot::log_error("navigation_execute_instant_actions failed: %s", e.what());
return false;
}
catch (...)
{
robot::log_error("navigation_execute_instant_actions failed: unknown exception");
return false;
}
}
// navigation_dock_to_order_v2 was removed together with BaseNavigation::dockTo. Docking is now a
// per-leg property of the order: set `profile: docking` and `marker` on the leg and send it
// through navigation_move_to_order_v2, so it gets the same mission id, lifecycle and cancel as
// every other leg instead of bypassing the mission layer.
// ================================================================================================
// Releasing what the getters allocate
// ================================================================================================
//
// The converters allocate with malloc()/strdup(), so these release with free(). Mixing in delete[]
// here would be undefined behaviour, and the host cannot free these itself on Windows-style
// runtimes anyway — allocation and release must happen inside the same C runtime.
namespace
{
/// free() a buffer and clear both the pointer and its element count in one step.
template <typename T>
inline void free_array(T *&ptr, size_t &count)
{
free(ptr);
ptr = nullptr;
count = 0;
}
inline void free_string_field(char *&str)
{
free(str);
str = nullptr;
}
} // namespace
extern "C" void navigation_free_occupancy_grid(OccupancyGrid *grid)
{
if (!grid)
{
return;
}
free_string_field(grid->header.frame_id);
free_array(grid->data, grid->data_count);
}
extern "C" void navigation_free_laser_scan(LaserScan *scan)
{
if (!scan)
{
return;
}
free_string_field(scan->header.frame_id);
free_array(scan->ranges, scan->ranges_count);
free_array(scan->intensities, scan->intensities_count);
}
extern "C" void navigation_free_point_cloud(PointCloud *cloud)
{
if (!cloud)
{
return;
}
free_string_field(cloud->header.frame_id);
free_array(cloud->points, cloud->points_count);
// Each channel owns a name and a value buffer of its own; freeing the array alone leaks both.
if (cloud->channels != nullptr)
{
for (size_t i = 0; i < cloud->channels_count; ++i)
{
free_string_field(cloud->channels[i].name);
free_array(cloud->channels[i].values, cloud->channels[i].values_count);
}
}
free_array(cloud->channels, cloud->channels_count);
}
extern "C" void navigation_free_point_cloud2(PointCloud2 *cloud)
{
if (!cloud)
{
return;
}
free_string_field(cloud->header.frame_id);
if (cloud->fields != nullptr)
{
for (size_t i = 0; i < cloud->fields_count; ++i)
{
free_string_field(cloud->fields[i].name);
}
}
free_array(cloud->fields, cloud->fields_count);
free_array(cloud->data, cloud->data_count);
}
extern "C" void navigation_free_planner_data(PlannerDataOutput *data)
{
if (!data)
{
return;
}
if (data->plan.poses != nullptr)
{
for (size_t i = 0; i < data->plan.poses_count; ++i)
{
free_string_field(data->plan.poses[i].header.frame_id);
}
}
free_array(data->plan.poses, data->plan.poses_count);
free_string_field(data->plan.header.frame_id);
navigation_free_occupancy_grid(&data->costmap);
free_string_field(data->costmap_update.header.frame_id);
free_array(data->costmap_update.data, data->costmap_update.data_count);
free_string_field(data->footprint.header.frame_id);
free_array(data->footprint.polygon.points, data->footprint.polygon.points_count);
data->is_costmap_updated = false;
}

View File

@@ -3,11 +3,27 @@
#include <cstring> #include <cstring>
#include <cstdlib> #include <cstdlib>
namespace
{
/// strdup() chấp nhận NULL. strdup(NULL) là hành vi không xác định, và frame_id là tuỳ chọn.
char *dup_or_null(const char *s)
{
return s != nullptr ? strdup(s) : nullptr;
}
} // namespace
extern "C" Header header_create(const char *frame_id) { extern "C" Header header_create(const char *frame_id) {
Header header{}; Header header{};
header.frame_id = strdup(frame_id); header.frame_id = dup_or_null(frame_id);
header.sec = robot::Time::now().sec;
header.nsec = robot::Time::now().nsec; // Đọc đồng hồ MỘT lần: hai lời gọi Time::now() riêng có thể rơi hai bên một mốc giây, để lại
// sec của lần đọc trước ghép với nsec của lần đọc sau — timestamp lệch tới một giây, và nó sẽ
// hiện ra ở tra cứu TF chứ không phải ở đây.
const robot::Time now = robot::Time::now();
header.sec = now.sec;
header.nsec = now.nsec;
return header; return header;
} }
@@ -16,6 +32,6 @@ extern "C" Header header_set_data(uint32_t seq, uint32_t sec, uint32_t nsec, cha
header.seq = seq; header.seq = seq;
header.sec = sec; header.sec = sec;
header.nsec = nsec; header.nsec = nsec;
header.frame_id = strdup(frame_id); header.frame_id = dup_or_null(frame_id);
return header; return header;
} }

View File

@@ -0,0 +1,473 @@
/**
* @file test_convertor.cpp
* @brief Tests for the C <-> C++ conversion layer of the navigation C API.
*
* The conversion layer is where this package concentrates its risk: every message crossing the
* boundary passes through it, every optional field arrives as a raw pointer that may be NULL, and
* every allocation it makes has to be released by a matching free helper. None of that needs a
* running navigation core to test, which is what makes these tests worth having.
*
* The cases below are the ones that actually broke: a NULL frame_id built a std::string from a null
* pointer, a null array paired with a non-zero count sized a vector from the count, and an
* uninitialized Order handed the converter stack garbage to read as strings.
*/
#include <gtest/gtest.h>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include "convertor.h"
#include "convertor_2.h"
#include "nav_c_api_2.h"
namespace
{
/// A C header with no frame — the shape the library itself produces for an empty frame_id.
Header makeNullFrameHeader()
{
Header header{};
header.seq = 7;
header.sec = 123;
header.nsec = 456;
header.frame_id = nullptr;
return header;
}
} // namespace
// ================================================================================================
// NULL frame_id must not build a std::string from a null pointer
// ================================================================================================
TEST(ConvertorNullSafety, LaserScanAcceptsNullFrameId)
{
LaserScan scan{};
scan.header = makeNullFrameHeader();
scan.range_min = 0.1f;
scan.range_max = 10.0f;
const robot_sensor_msgs::LaserScan cpp = convert2CppLaserScan(scan);
EXPECT_EQ(cpp.header.frame_id, std::string());
EXPECT_EQ(cpp.header.seq, 7u);
EXPECT_EQ(cpp.header.stamp.sec, 123u);
EXPECT_FLOAT_EQ(cpp.range_max, 10.0f);
EXPECT_TRUE(cpp.ranges.empty());
}
TEST(ConvertorNullSafety, OccupancyGridAcceptsNullFrameId)
{
OccupancyGrid grid{};
grid.header = makeNullFrameHeader();
grid.info.resolution = 0.05f;
grid.info.width = 4;
grid.info.height = 2;
const robot_nav_msgs::OccupancyGrid cpp = convert2CppOccupancyGrid(grid);
EXPECT_EQ(cpp.header.frame_id, std::string());
EXPECT_EQ(cpp.info.width, 4u);
EXPECT_TRUE(cpp.data.empty());
}
TEST(ConvertorNullSafety, PoseStampedAcceptsNullFrameId)
{
PoseStamped pose{};
pose.header = makeNullFrameHeader();
pose.pose.position.x = 1.5;
pose.pose.orientation.w = 1.0;
const robot_geometry_msgs::PoseStamped cpp = convert2CppPoseStamped(pose);
EXPECT_EQ(cpp.header.frame_id, std::string());
EXPECT_DOUBLE_EQ(cpp.pose.position.x, 1.5);
EXPECT_DOUBLE_EQ(cpp.pose.orientation.w, 1.0);
}
TEST(ConvertorNullSafety, PointCloud2AcceptsNullFrameIdAndNullFieldNames)
{
PointField field{};
field.name = nullptr;
field.offset = 0;
field.datatype = 7;
field.count = 1;
PointCloud2 cloud{};
cloud.header = makeNullFrameHeader();
cloud.height = 1;
cloud.width = 3;
cloud.fields = &field;
cloud.fields_count = 1;
const robot_sensor_msgs::PointCloud2 cpp = convert2CppPointCloud2(cloud);
EXPECT_EQ(cpp.header.frame_id, std::string());
ASSERT_EQ(cpp.fields.size(), 1u);
EXPECT_EQ(cpp.fields[0].name, std::string());
EXPECT_EQ(cpp.fields[0].datatype, 7);
}
// ================================================================================================
// A null array with a non-zero count must not size the vector from the count
// ================================================================================================
TEST(ConvertorNullSafety, LaserScanIgnoresCountWhenRangesAreNull)
{
LaserScan scan{};
scan.header = makeNullFrameHeader();
scan.ranges = nullptr;
scan.ranges_count = 1000; // dữ liệu hỏng: bộ đếm khác 0 nhưng không có mảng
scan.intensities = nullptr;
scan.intensities_count = 1000;
const robot_sensor_msgs::LaserScan cpp = convert2CppLaserScan(scan);
EXPECT_TRUE(cpp.ranges.empty());
EXPECT_TRUE(cpp.intensities.empty());
}
TEST(ConvertorNullSafety, PointCloudIgnoresCountWhenArraysAreNull)
{
PointCloud cloud{};
cloud.header = makeNullFrameHeader();
cloud.points = nullptr;
cloud.points_count = 100000;
cloud.channels = nullptr;
cloud.channels_count = 100000;
const robot_sensor_msgs::PointCloud cpp = convert2CppPointCloud(cloud);
EXPECT_TRUE(cpp.points.empty());
EXPECT_TRUE(cpp.channels.empty());
}
TEST(ConvertorNullSafety, PointCloud2IgnoresCountWhenDataIsNull)
{
PointCloud2 cloud{};
cloud.header = makeNullFrameHeader();
cloud.data = nullptr;
cloud.data_count = 100000;
cloud.fields = nullptr;
cloud.fields_count = 100000;
const robot_sensor_msgs::PointCloud2 cpp = convert2CppPointCloud2(cloud);
EXPECT_TRUE(cpp.data.empty());
EXPECT_TRUE(cpp.fields.empty());
}
// ================================================================================================
// Round trip: what the library hands out must be safe to hand straight back in
// ================================================================================================
TEST(ConvertorRoundTrip, OccupancyGridWithEmptyFrameSurvivesRoundTrip)
{
// An empty frame_id becomes a NULL char* on the way out — that is the exact value that used to
// crash on the way back in.
robot_nav_msgs::OccupancyGrid source;
source.header.frame_id = "";
source.info.width = 2;
source.info.height = 2;
source.data = { 0, 100, -1, 50 };
OccupancyGrid c_grid{};
convert2COccupancyGrid(source, c_grid);
ASSERT_EQ(c_grid.header.frame_id, nullptr) << "empty string is expected to become NULL";
ASSERT_EQ(c_grid.data_count, 4u);
const robot_nav_msgs::OccupancyGrid back = convert2CppOccupancyGrid(c_grid);
EXPECT_EQ(back.header.frame_id, std::string());
ASSERT_EQ(back.data.size(), 4u);
EXPECT_EQ(back.data[1], 100);
EXPECT_EQ(back.data[2], -1);
navigation_free_occupancy_grid(&c_grid);
EXPECT_EQ(c_grid.data, nullptr);
EXPECT_EQ(c_grid.data_count, 0u);
}
TEST(ConvertorRoundTrip, LaserScanSurvivesRoundTrip)
{
robot_sensor_msgs::LaserScan source;
source.header.frame_id = "front_laser";
source.angle_min = -1.57f;
source.angle_max = 1.57f;
source.ranges = { 1.0f, 2.0f, 3.0f };
source.intensities = { 10.0f, 20.0f, 30.0f };
LaserScan c_scan{};
convert2CLaserScan(source, c_scan);
ASSERT_NE(c_scan.header.frame_id, nullptr);
EXPECT_STREQ(c_scan.header.frame_id, "front_laser");
const robot_sensor_msgs::LaserScan back = convert2CppLaserScan(c_scan);
EXPECT_EQ(back.header.frame_id, "front_laser");
ASSERT_EQ(back.ranges.size(), 3u);
EXPECT_FLOAT_EQ(back.ranges[2], 3.0f);
ASSERT_EQ(back.intensities.size(), 3u);
navigation_free_laser_scan(&c_scan);
EXPECT_EQ(c_scan.ranges, nullptr);
EXPECT_EQ(c_scan.ranges_count, 0u);
}
// ================================================================================================
// Order: every optional string is allowed to be NULL
// ================================================================================================
TEST(ConvertorOrder, ZeroInitialisedOrderConvertsToEmptyStrings)
{
// This is what the *_nodes_edges entry points build: only the arrays are set, every string field
// stays NULL. Reading those as strings is what used to be undefined behaviour.
Order order{};
const robot_protocol_msgs::Order cpp = convert2CppOrder(order);
EXPECT_EQ(cpp.orderId, std::string());
EXPECT_EQ(cpp.timestamp, std::string());
EXPECT_EQ(cpp.version, std::string());
EXPECT_EQ(cpp.manufacturer, std::string());
EXPECT_EQ(cpp.serialNumber, std::string());
EXPECT_EQ(cpp.zoneSetId, std::string());
EXPECT_EQ(cpp.orderUpdateId, 0u);
EXPECT_TRUE(cpp.nodes.empty());
EXPECT_TRUE(cpp.edges.empty());
}
TEST(ConvertorOrder, NodesAndEdgesWithNullStringsConvert)
{
Node node{};
node.nodeId = nullptr;
node.sequenceId = 3;
node.released = 1;
node.nodePosition.x = 1.0;
node.nodePosition.y = 2.0;
Edge edge{};
edge.edgeId = nullptr;
edge.sequenceId = 4;
edge.maxSpeed = 0.5;
Order order{};
order.orderId = const_cast<char*>("order-1");
order.orderUpdateId = 2;
order.nodes = &node;
order.nodes_count = 1;
order.edges = &edge;
order.edges_count = 1;
const robot_protocol_msgs::Order cpp = convert2CppOrder(order);
EXPECT_EQ(cpp.orderId, "order-1");
EXPECT_EQ(cpp.orderUpdateId, 2u);
ASSERT_EQ(cpp.nodes.size(), 1u);
EXPECT_EQ(cpp.nodes[0].nodeId, std::string());
EXPECT_EQ(cpp.nodes[0].sequenceId, 3);
EXPECT_DOUBLE_EQ(cpp.nodes[0].nodePosition.y, 2.0);
ASSERT_EQ(cpp.edges.size(), 1u);
EXPECT_EQ(cpp.edges[0].edgeId, std::string());
EXPECT_DOUBLE_EQ(cpp.edges[0].maxSpeed, 0.5);
}
TEST(ConvertorOrder, NullArraysAreIgnoredEvenWithNonZeroCounts)
{
Order order{};
order.nodes = nullptr;
order.nodes_count = 50;
order.edges = nullptr;
order.edges_count = 50;
const robot_protocol_msgs::Order cpp = convert2CppOrder(order);
EXPECT_TRUE(cpp.nodes.empty());
EXPECT_TRUE(cpp.edges.empty());
}
// ================================================================================================
// Depth camera conversion (move_base2 path)
// ================================================================================================
TEST(ConvertorDepthCamera, CopiesPixelsAndIntrinsics)
{
std::vector<uint8_t> pixels(8 * 4 * 2, 0);
pixels[0] = 0xAB;
pixels[1] = 0xCD;
DepthCameraData data{};
data.header.sec = 10;
data.header.nsec = 20;
data.header.frame_id = const_cast<char*>("camera_depth_optical_frame");
data.depth.header = data.header;
data.depth.height = 4;
data.depth.width = 8;
data.depth.step = 8 * 2;
data.depth.encoding = const_cast<char*>("16UC1");
data.depth.data = pixels.data();
data.depth.data_count = pixels.size();
data.camera_info.header = data.header;
data.camera_info.height = 4;
data.camera_info.width = 8;
data.camera_info.distortion_model = const_cast<char*>("plumb_bob");
data.camera_info.K[0] = 500.0;
data.camera_info.K[4] = 500.0;
data.camera_info.K[8] = 1.0;
const robot_sensor_msgs::DepthCameraData cpp = convert2CppDepthCameraData(data);
EXPECT_EQ(cpp.header.frame_id, "camera_depth_optical_frame");
EXPECT_EQ(cpp.depth.encoding, "16UC1");
EXPECT_EQ(cpp.depth.step, 16u);
ASSERT_EQ(cpp.depth.data.size(), pixels.size());
EXPECT_EQ(cpp.depth.data[0], 0xAB);
// Copy, không alias: sửa buffer của host sau lời gọi không được đụng tới bản đã chuyển đổi.
pixels[0] = 0x00;
EXPECT_EQ(cpp.depth.data[0], 0xAB);
EXPECT_EQ(cpp.camera_info.distortion_model, "plumb_bob");
EXPECT_DOUBLE_EQ(cpp.camera_info.K[0], 500.0);
EXPECT_TRUE(cpp.camera_info.D.empty());
}
TEST(ConvertorDepthCamera, AcceptsNullOptionalFields)
{
DepthCameraData data{};
data.depth.data = nullptr;
data.depth.data_count = 4096; // bộ đếm khác 0 nhưng không có buffer
data.camera_info.D = nullptr;
data.camera_info.D_count = 5;
const robot_sensor_msgs::DepthCameraData cpp = convert2CppDepthCameraData(data);
EXPECT_EQ(cpp.header.frame_id, std::string());
EXPECT_EQ(cpp.depth.encoding, std::string());
EXPECT_TRUE(cpp.depth.data.empty());
EXPECT_TRUE(cpp.camera_info.D.empty());
}
// ================================================================================================
// Free helpers
// ================================================================================================
TEST(FreeHelpers, NullPointersAreNoOps)
{
navigation_free_occupancy_grid(nullptr);
navigation_free_laser_scan(nullptr);
navigation_free_point_cloud(nullptr);
navigation_free_point_cloud2(nullptr);
navigation_free_planner_data(nullptr);
nav_c_api_free_string(nullptr);
SUCCEED() << "no crash on NULL";
}
TEST(FreeHelpers, DoubleFreeIsSafe)
{
robot_sensor_msgs::LaserScan source;
source.header.frame_id = "laser";
source.ranges = { 1.0f, 2.0f };
LaserScan c_scan{};
convert2CLaserScan(source, c_scan);
navigation_free_laser_scan(&c_scan);
navigation_free_laser_scan(&c_scan); // các con trỏ đã bị xoá ở lần đầu
EXPECT_EQ(c_scan.header.frame_id, nullptr);
EXPECT_EQ(c_scan.ranges, nullptr);
}
TEST(FreeHelpers, PlannerDataReleasesEveryNestedBuffer)
{
robot::move_base_core::PlannerDataOutput source;
source.plan.header.frame_id = "map";
for (int i = 0; i < 3; ++i)
{
robot_nav_2d_msgs::Pose2DStamped pose;
pose.header.frame_id = "map"; // mỗi pose mang frame_id RIÊNG — chỗ dễ rò nhất
pose.pose.x = i;
source.plan.poses.push_back(pose);
}
source.costmap.header.frame_id = "map";
source.costmap.data = { 0, 1, 2, 3 };
source.footprint.header.frame_id = "base_link";
robot_geometry_msgs::Point32 p;
p.x = 0.3f;
source.footprint.polygon.points.push_back(p);
PlannerDataOutput c_data{};
convert2CPath2D(source.plan, c_data.plan);
convert2COccupancyGrid(source.costmap, c_data.costmap);
convert2CPolygonStamped(source.footprint, c_data.footprint);
ASSERT_EQ(c_data.plan.poses_count, 3u);
ASSERT_NE(c_data.plan.poses[0].header.frame_id, nullptr);
ASSERT_EQ(c_data.costmap.data_count, 4u);
ASSERT_EQ(c_data.footprint.polygon.points_count, 1u);
navigation_free_planner_data(&c_data);
EXPECT_EQ(c_data.plan.poses, nullptr);
EXPECT_EQ(c_data.plan.poses_count, 0u);
EXPECT_EQ(c_data.plan.header.frame_id, nullptr);
EXPECT_EQ(c_data.costmap.data, nullptr);
EXPECT_EQ(c_data.footprint.polygon.points, nullptr);
EXPECT_EQ(c_data.footprint.polygon.points_count, 0u);
}
TEST(FreeHelpers, PointCloudReleasesChannelNamesAndValues)
{
robot_sensor_msgs::PointCloud source;
source.header.frame_id = "cloud";
robot_geometry_msgs::Point32 p;
p.x = 1.0f;
source.points.push_back(p);
robot_sensor_msgs::ChannelFloat32 channel;
channel.name = "intensity";
channel.values = { 1.0f, 2.0f };
source.channels.push_back(channel);
PointCloud c_cloud{};
convert2CPointCloud(source, c_cloud);
ASSERT_EQ(c_cloud.channels_count, 1u);
ASSERT_NE(c_cloud.channels[0].name, nullptr);
ASSERT_NE(c_cloud.channels[0].values, nullptr);
navigation_free_point_cloud(&c_cloud);
EXPECT_EQ(c_cloud.points, nullptr);
EXPECT_EQ(c_cloud.channels, nullptr);
EXPECT_EQ(c_cloud.channels_count, 0u);
}
// ================================================================================================
// Quaternion validation guards the goal entry points
// ================================================================================================
TEST(QuaternionValidation, RejectsNanAndZeroLength)
{
Quaternion nan_q{};
nan_q.x = std::nan("");
nan_q.w = 1.0;
EXPECT_FALSE(isQuaternionValid(nan_q));
Quaternion zero_q{};
EXPECT_FALSE(isQuaternionValid(zero_q));
}
TEST(QuaternionValidation, RejectsTiltedAndAcceptsUpright)
{
Quaternion upright{};
upright.w = 1.0;
EXPECT_TRUE(isQuaternionValid(upright));
// Quay 90 độ quanh trục X: trục z của robot nằm ngang -> không hợp lệ cho navigation phẳng.
Quaternion tilted{};
tilted.x = 0.7071067811865476;
tilted.w = 0.7071067811865476;
EXPECT_FALSE(isQuaternionValid(tilted));
}

View File

@@ -206,7 +206,7 @@ bool score_algorithm::ScoreAlgorithm::computePlanCommand(const robot_nav_2d_msgs
// Process index_s with multiple elements // Process index_s with multiple elements
if (index_s.size() > 1) if (index_s.size() > 1)
{ {
for (size_t i = 0; i < index_s.size(); ++i) for (size_t i = 1; i < index_s.size(); ++i)
{ {
if (index_s[i - 1] >= (unsigned int)global_plan.poses.size() || index_s[i] >= (unsigned int)global_plan.poses.size()) if (index_s[i - 1] >= (unsigned int)global_plan.poses.size() || index_s[i] >= (unsigned int)global_plan.poses.size())
{ {
@@ -219,11 +219,12 @@ bool score_algorithm::ScoreAlgorithm::computePlanCommand(const robot_nav_2d_msgs
double x = cos(global_plan.poses[index_s[i - 1]].pose.theta) * dx + sin(global_plan.poses[index_s[i - 1]].pose.theta) * dy; double x = cos(global_plan.poses[index_s[i - 1]].pose.theta) * dx + sin(global_plan.poses[index_s[i - 1]].pose.theta) * dy;
double y = -sin(global_plan.poses[index_s[i - 1]].pose.theta) * dx + cos(global_plan.poses[index_s[i - 1]].pose.theta) * dy; double y = -sin(global_plan.poses[index_s[i - 1]].pose.theta) * dx + cos(global_plan.poses[index_s[i - 1]].pose.theta) * dy;
if (std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_local_goal_tolerance_ + 0.1) if (std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_local_goal_tolerance_ + 0.2)
{ {
double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y;
if (fabs(tolerance) <= xy_local_goal_tolerance_) if (fabs(tolerance) <= xy_local_goal_tolerance_)
{ {
if (index_s[i] > sub_goal_index_saved_) if (index_s[i] > sub_goal_index_saved_)
{ {
sub_goal_index = (i < index_s.size() - 1) ? index_s[i] : (unsigned int)global_plan.poses.size() - 1; sub_goal_index = (i < index_s.size() - 1) ? index_s[i] : (unsigned int)global_plan.poses.size() - 1;
@@ -257,7 +258,7 @@ bool score_algorithm::ScoreAlgorithm::computePlanCommand(const robot_nav_2d_msgs
double theta = angles::normalize_angle(robot_pose.pose.theta - global_plan.poses[sub_goal_index].pose.theta); double theta = angles::normalize_angle(robot_pose.pose.theta - global_plan.poses[sub_goal_index].pose.theta);
double x = cos(global_plan.poses[sub_goal_index].pose.theta) * dx + sin(global_plan.poses[sub_goal_index].pose.theta) * dy; double x = cos(global_plan.poses[sub_goal_index].pose.theta) * dx + sin(global_plan.poses[sub_goal_index].pose.theta) * dy;
double y = -sin(global_plan.poses[sub_goal_index].pose.theta) * dx + cos(global_plan.poses[sub_goal_index].pose.theta) * dy; double y = -sin(global_plan.poses[sub_goal_index].pose.theta) * dx + cos(global_plan.poses[sub_goal_index].pose.theta) * dy;
if (std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_local_goal_tolerance_ + 0.1) if (std::abs(std::sqrt(dx * dx + dy * dy)) <= xy_local_goal_tolerance_ + 0.2)
{ {
double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y; double tolerance = fabs(cos(theta)) >= fabs(sin(theta)) ? x : y;
if (fabs(tolerance) <= xy_local_goal_tolerance_) if (fabs(tolerance) <= xy_local_goal_tolerance_)
@@ -415,7 +416,7 @@ bool score_algorithm::ScoreAlgorithm::computePlanCommand(const robot_nav_2d_msgs
robot_nav_2d_msgs::Pose2DStamped sub_pose; robot_nav_2d_msgs::Pose2DStamped sub_pose;
sub_pose = global_plan.poses[closet_index]; sub_pose = global_plan.poses[closet_index];
#ifdef SCORE_ALGORITHM_WITH_ROS #ifdef BUILD_WITH_ROS
{ {
robot_geometry_msgs::PoseStamped sub_pose_stamped = robot_nav_2d_utils::pose2DToPoseStamped(sub_pose); robot_geometry_msgs::PoseStamped sub_pose_stamped = robot_nav_2d_utils::pose2DToPoseStamped(sub_pose);
geometry_msgs::PoseStamped sub_pose_stamped_ros; geometry_msgs::PoseStamped sub_pose_stamped_ros;
@@ -423,7 +424,7 @@ bool score_algorithm::ScoreAlgorithm::computePlanCommand(const robot_nav_2d_msgs
sub_pose_stamped_ros.header.frame_id = sub_pose_stamped.header.frame_id; sub_pose_stamped_ros.header.frame_id = sub_pose_stamped.header.frame_id;
sub_pose_stamped_ros.pose.position.x = sub_pose_stamped.pose.position.x; sub_pose_stamped_ros.pose.position.x = sub_pose_stamped.pose.position.x;
sub_pose_stamped_ros.pose.position.y = sub_pose_stamped.pose.position.y; sub_pose_stamped_ros.pose.position.y = sub_pose_stamped.pose.position.y;
sub_pose_stamped_ros.pose.position.z = sub_pose_stamped.pose.position.z; sub_pose_stamped_ros.pose.position.z = 0.9;
sub_pose_stamped_ros.pose.orientation.x = sub_pose_stamped.pose.orientation.x; sub_pose_stamped_ros.pose.orientation.x = sub_pose_stamped.pose.orientation.x;
sub_pose_stamped_ros.pose.orientation.y = sub_pose_stamped.pose.orientation.y; sub_pose_stamped_ros.pose.orientation.y = sub_pose_stamped.pose.orientation.y;
sub_pose_stamped_ros.pose.orientation.z = sub_pose_stamped.pose.orientation.z; sub_pose_stamped_ros.pose.orientation.z = sub_pose_stamped.pose.orientation.z;
@@ -434,7 +435,7 @@ bool score_algorithm::ScoreAlgorithm::computePlanCommand(const robot_nav_2d_msgs
robot_nav_2d_msgs::Pose2DStamped sub_goal; robot_nav_2d_msgs::Pose2DStamped sub_goal;
sub_goal = global_plan.poses[goal_index]; sub_goal = global_plan.poses[goal_index];
#ifdef SCORE_ALGORITHM_WITH_ROS #ifdef BUILD_WITH_ROS
{ {
robot_geometry_msgs::PoseStamped sub_goal_stamped = robot_nav_2d_utils::pose2DToPoseStamped(sub_goal); robot_geometry_msgs::PoseStamped sub_goal_stamped = robot_nav_2d_utils::pose2DToPoseStamped(sub_goal);
geometry_msgs::PoseStamped sub_goal_stamped_ros; geometry_msgs::PoseStamped sub_goal_stamped_ros;
@@ -442,7 +443,7 @@ bool score_algorithm::ScoreAlgorithm::computePlanCommand(const robot_nav_2d_msgs
sub_goal_stamped_ros.header.frame_id = sub_goal_stamped.header.frame_id; sub_goal_stamped_ros.header.frame_id = sub_goal_stamped.header.frame_id;
sub_goal_stamped_ros.pose.position.x = sub_goal_stamped.pose.position.x; sub_goal_stamped_ros.pose.position.x = sub_goal_stamped.pose.position.x;
sub_goal_stamped_ros.pose.position.y = sub_goal_stamped.pose.position.y; sub_goal_stamped_ros.pose.position.y = sub_goal_stamped.pose.position.y;
sub_goal_stamped_ros.pose.position.z = sub_goal_stamped.pose.position.z; sub_goal_stamped_ros.pose.position.z = 0.9;
sub_goal_stamped_ros.pose.orientation.x = sub_goal_stamped.pose.orientation.x; sub_goal_stamped_ros.pose.orientation.x = sub_goal_stamped.pose.orientation.x;
sub_goal_stamped_ros.pose.orientation.y = sub_goal_stamped.pose.orientation.y; sub_goal_stamped_ros.pose.orientation.y = sub_goal_stamped.pose.orientation.y;
sub_goal_stamped_ros.pose.orientation.z = sub_goal_stamped.pose.orientation.z; sub_goal_stamped_ros.pose.orientation.z = sub_goal_stamped.pose.orientation.z;

View File

@@ -117,9 +117,7 @@ namespace mkt_algorithm
* @return lookahead point * @return lookahead point
*/ */
std::vector<robot_nav_2d_msgs::Pose2DStamped>::iterator std::vector<robot_nav_2d_msgs::Pose2DStamped>::iterator
getLookAheadPoint(const robot_nav_2d_msgs::Twist2D &velocity, getLookAheadPoint(const robot_nav_2d_msgs::Twist2D &velocity, const double &lookahead_dist, robot_nav_2d_msgs::Path2D global_plan);
const double &lookahead_dist,
robot_nav_2d_msgs::Path2D& global_plan);
/** /**
* @brief Prune global plan * @brief Prune global plan
@@ -183,7 +181,7 @@ namespace mkt_algorithm
*/ */
robot_nav_2d_msgs::Path2D generateTrajectory( robot_nav_2d_msgs::Path2D generateTrajectory(
const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &drive_target, const robot_nav_2d_msgs::Path2D &path, const robot_nav_2d_msgs::Twist2D &drive_target,
const robot_nav_2d_msgs::Twist2D &velocity, const double &sign_x, robot_nav_2d_msgs::Twist2D &drive_cmd); const robot_nav_2d_msgs::Twist2D &velocity, const double &sign_x, robot_nav_2d_msgs::Twist2D &drive_cmd, const double &dt);
/** /**
* @brief Generate trajectory * @brief Generate trajectory

View File

@@ -131,19 +131,19 @@ mkt_msgs::Trajectory2D mkt_algorithm::diff::GoStraight::calculator(
auto carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan); auto carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan);
robot_geometry_msgs::PoseStamped carrot_pose_stamped = robot_nav_2d_utils::pose2DToPoseStamped(carrot_pose); robot_geometry_msgs::PoseStamped carrot_pose_stamped = robot_nav_2d_utils::pose2DToPoseStamped(carrot_pose);
// === Final Heading Alignment Check === // // === Final Heading Alignment Check ===
double xy_error = 0.0, heading_error = 0.0; // double xy_error = 0.0, heading_error = 0.0;
if (shouldAlignToFinalHeading(transformed_plan, carrot_pose, velocity, xy_error, heading_error, sign_x)) // if (shouldAlignToFinalHeading(transformed_plan, carrot_pose, velocity, xy_error, heading_error, sign_x))
{ // {
// Use Arc Motion controller for final heading alignment // // Use Arc Motion controller for final heading alignment
alignToFinalHeading(xy_error, heading_error, velocity, sign_x, dt, drive_cmd); // alignToFinalHeading(xy_error, heading_error, velocity, sign_x, dt, drive_cmd);
#ifdef BUILD_WITH_ROS // #ifdef BUILD_WITH_ROS
ROS_INFO("xy_err=%.3f, heading_err=%.3f deg, v=%.3f, w_current=%.3f, w_target=%.3f", // ROS_INFO("xy_err=%.3f, heading_err=%.3f deg, v=%.3f, w_current=%.3f, w_target=%.3f",
xy_error, heading_error * 180.0 / M_PI, drive_cmd.x, velocity.theta, drive_cmd.theta); // xy_error, heading_error * 180.0 / M_PI, drive_cmd.x, velocity.theta, drive_cmd.theta);
#endif // #endif
} // }
else // else
{ // {
// robot::log_info_at(__FILE__, __LINE__, "journey : %f lookahead_dist : %f", // robot::log_info_at(__FILE__, __LINE__, "journey : %f lookahead_dist : %f",
// journey(transformed_plan.poses, 0, transformed_plan.poses.size() - 1), lookahead_dist); // journey(transformed_plan.poses, 0, transformed_plan.poses.size() - 1), lookahead_dist);
if(fabs(carrot_pose.pose.y) > 0.2) if(fabs(carrot_pose.pose.y) > 0.2)
@@ -151,7 +151,7 @@ mkt_msgs::Trajectory2D mkt_algorithm::diff::GoStraight::calculator(
lookahead_dist = sqrt(carrot_pose.pose.y *carrot_pose.pose.y + lookahead_dist * lookahead_dist); lookahead_dist = sqrt(carrot_pose.pose.y *carrot_pose.pose.y + lookahead_dist * lookahead_dist);
} }
robot_nav_2d_msgs::Twist2D drive_target; robot_nav_2d_msgs::Twist2D drive_target;
transformed_plan = this->generateTrajectory(transformed_plan, drive_cmd, velocity, sign_x, drive_target); transformed_plan = this->generateTrajectory(transformed_plan, drive_cmd, velocity, sign_x, drive_target, dt);
carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan); carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan);
// Normal Pure Pursuit // Normal Pure Pursuit
@@ -164,7 +164,7 @@ mkt_msgs::Trajectory2D mkt_algorithm::diff::GoStraight::calculator(
sign_x, sign_x,
dt, dt,
drive_cmd); drive_cmd);
} // }
applyDistanceSpeedScaling(compute_plan_, velocity, drive_cmd, sign_x, dt); applyDistanceSpeedScaling(compute_plan_, velocity, drive_cmd, sign_x, dt);
if (this->nav_stop_) if (this->nav_stop_)

View File

@@ -279,7 +279,6 @@ bool mkt_algorithm::diff::PredictiveTrajectory::prepare(const robot_nav_2d_msgs:
const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan, const robot_nav_2d_msgs::Pose2DStamped &goal, const robot_nav_2d_msgs::Path2D &global_plan,
double &x_direction, double &y_direction, double &theta_direction) double &x_direction, double &y_direction, double &theta_direction)
{ {
// robot::log_error("DEBUG STEP 2.0");
if (!initialized_) if (!initialized_)
{ {
robot::log_error("[%s:%d]\n This planner has not been initialized, please call initialize() before using this planner", __FILE__, __LINE__); robot::log_error("[%s:%d]\n This planner has not been initialized, please call initialize() before using this planner", __FILE__, __LINE__);
@@ -289,7 +288,7 @@ bool mkt_algorithm::diff::PredictiveTrajectory::prepare(const robot_nav_2d_msgs:
{ {
last_actuator_update_ = robot::Time::now(); last_actuator_update_ = robot::Time::now();
} }
// robot::log_error("DEBUG STEP 3.0");
std::vector<robot_geometry_msgs::Point> footprint = costmap_robot_ ? costmap_robot_->getRobotFootprint() : std::vector<robot_geometry_msgs::Point>(); std::vector<robot_geometry_msgs::Point> footprint = costmap_robot_ ? costmap_robot_->getRobotFootprint() : std::vector<robot_geometry_msgs::Point>();
if (footprint.size() > 1) if (footprint.size() > 1)
{ {
@@ -312,14 +311,14 @@ bool mkt_algorithm::diff::PredictiveTrajectory::prepare(const robot_nav_2d_msgs:
this->min_path_distance_ = min_length > 0.1 ? min_length : 0.1; this->min_path_distance_ = min_length > 0.1 ? min_length : 0.1;
this->max_path_distance_ = max_length > 0.1 ? max_length : 0.1; this->max_path_distance_ = max_length > 0.1 ? max_length : 0.1;
} }
// robot::log_error("DEBUG STEP 4.0");
if (global_plan.poses.empty() || (unsigned int)global_plan.poses.size() < 2) if (global_plan.poses.empty() || (unsigned int)global_plan.poses.size() < 2)
{ {
robot::log_error("[%s:%d]\n The Local plan is empty or less than 1 points %d", __FILE__, __LINE__, (unsigned int)global_plan.poses.size()); robot::log_error("[%s:%d]\n The Local plan is empty or less than 1 points %d", __FILE__, __LINE__, (unsigned int)global_plan.poses.size());
return false; return false;
} }
this->getParams(); this->getParams();
// robot::log_error("DEBUG STEP 5.0");
frame_id_path_ = global_plan.header.frame_id; frame_id_path_ = global_plan.header.frame_id;
goal_ = goal; goal_ = goal;
global_plan_ = global_plan; global_plan_ = global_plan;
@@ -330,14 +329,14 @@ bool mkt_algorithm::diff::PredictiveTrajectory::prepare(const robot_nav_2d_msgs:
robot::log_error("[%s:%d]\n pruneGlobalPlan Failed", __FILE__, __LINE__); robot::log_error("[%s:%d]\n pruneGlobalPlan Failed", __FILE__, __LINE__);
return false; return false;
} }
// robot::log_error("DEBUG STEP 6.0");
double S = std::numeric_limits<double>::infinity(); double S = std::numeric_limits<double>::infinity();
S = std::max(costmap_robot_->getCostmap()->getSizeInCellsX() * costmap_robot_->getCostmap()->getResolution() / 2.0, S = std::max(costmap_robot_->getCostmap()->getSizeInCellsX() * costmap_robot_->getCostmap()->getResolution() / 2.0,
costmap_robot_->getCostmap()->getSizeInCellsY() * costmap_robot_->getCostmap()->getResolution() / 2.0); costmap_robot_->getCostmap()->getSizeInCellsY() * costmap_robot_->getCostmap()->getResolution() / 2.0);
const double min_S = min_lookahead_dist_ * 1.5 + max_path_distance_, max_S = max_lookahead_dist_ * 1.5 + max_path_distance_; const double min_S = min_lookahead_dist_ * 1.5 + max_path_distance_, max_S = max_lookahead_dist_ * 1.5 + max_path_distance_;
S = std::clamp(S * fabs(velocity.x) * lookahead_time_, min_S, max_S); S = std::clamp(S * fabs(velocity.x) * lookahead_time_, min_S, max_S);
compute_plan_.poses.clear(); compute_plan_.poses.clear();
// robot::log_error("DEBUG STEP 7.0");
if ((unsigned int)global_plan_.poses.size() == 2) if ((unsigned int)global_plan_.poses.size() == 2)
{ {
double dx = global_plan_.poses.back().pose.x - global_plan_.poses.front().pose.x; double dx = global_plan_.poses.back().pose.x - global_plan_.poses.front().pose.x;
@@ -361,7 +360,6 @@ bool mkt_algorithm::diff::PredictiveTrajectory::prepare(const robot_nav_2d_msgs:
return false; return false;
} }
} }
// robot::log_error("DEBUG STEP 8.0");
double lookahead_dist = this->getLookAheadDistance(velocity); double lookahead_dist = this->getLookAheadDistance(velocity);
transform_plan_.poses.clear(); transform_plan_.poses.clear();
@@ -370,7 +368,7 @@ bool mkt_algorithm::diff::PredictiveTrajectory::prepare(const robot_nav_2d_msgs:
robot::log_warning("[%s:%d]\n Could not transform the global plan to the frame of the controller", __FILE__, __LINE__); robot::log_warning("[%s:%d]\n Could not transform the global plan to the frame of the controller", __FILE__, __LINE__);
return false; return false;
} }
// robot::log_error("DEBUG STEP 9.0");
const auto carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transform_plan_); const auto carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transform_plan_);
if(fabs(carrot_pose.pose.y) > 0.2) if(fabs(carrot_pose.pose.y) > 0.2)
{ {
@@ -381,15 +379,14 @@ bool mkt_algorithm::diff::PredictiveTrajectory::prepare(const robot_nav_2d_msgs:
return false; return false;
} }
} }
// robot::log_error("DEBUG STEP 10.0");
x_direction = x_direction_; x_direction = x_direction_;
y_direction = y_direction_ = 0; y_direction = y_direction_ = 0;
theta_direction = theta_direction_; theta_direction = theta_direction_;
// robot::log_error("DEBUG STATUS : %x, %x", (unsigned int)(compute_plan_.poses.size() > 1), journey(compute_plan_.poses, 0, compute_plan_.poses.size() - 1) >= costmap_robot_->getCostmap()->getResolution());
if ((unsigned int)(compute_plan_.poses.size() > 1) && if ((unsigned int)(compute_plan_.poses.size() > 1) &&
journey(compute_plan_.poses, 0, compute_plan_.poses.size() - 1) >= costmap_robot_->getCostmap()->getResolution()) journey(compute_plan_.poses, 0, compute_plan_.poses.size() - 1) >= costmap_robot_->getCostmap()->getResolution())
{ {
// robot::log_error("DEBUG STEP 10.1");
const robot_geometry_msgs::Pose2D p2 = compute_plan_.poses.back().pose; const robot_geometry_msgs::Pose2D p2 = compute_plan_.poses.back().pose;
int index; int index;
for (index = (unsigned int)(compute_plan_.poses.size() - 1); index > 0; index--) for (index = (unsigned int)(compute_plan_.poses.size() - 1); index > 0; index--)
@@ -408,54 +405,50 @@ bool mkt_algorithm::diff::PredictiveTrajectory::prepare(const robot_nav_2d_msgs:
} }
} }
else else if(compute_plan_.poses.size() == 1)
{ {
// robot::log_error("DEBUG STEP 11.1");
try try
{ {
// auto carrot_pose_it = getLookAheadPoint(velocity, lookahead_dist, transform_plan_);
// auto prev_carrot_pose_it = transform_plan_.poses.begin();
// double distance_it = 0;
// for (auto it = carrot_pose_it - 1; it != transform_plan_.poses.begin(); --it)
// {
// double dx = it->pose.x - carrot_pose_it->pose.x;
// double dy = it->pose.y - carrot_pose_it->pose.y;
// distance_it += std::hypot(dx, dy);
// if (distance_it > costmap_robot_->getCostmap()->getResolution())
// {
// prev_carrot_pose_it = it;
// break;
// }
// }
auto carrot_pose_it = getLookAheadPoint(velocity, lookahead_dist, transform_plan_); // robot_geometry_msgs::Pose front = journey(transform_plan_.poses, 0, transform_plan_.poses.size() - 1) > 5.0 * costmap_robot_->getCostmap()->getResolution()
// robot::log_error("DEBUG STEP 11.2"); // ? robot_nav_2d_utils::pose2DToPose((*(prev_carrot_pose_it)).pose)
auto prev_carrot_pose_it = transform_plan_.poses.begin(); // : robot_nav_2d_utils::pose2DToPose(robot_geometry_msgs::Pose2D());
// robot::log_error("DEBUG STEP 11.2.1 carrot_pose_it: %d", (int)std::distance(transform_plan_.poses.begin(), carrot_pose_it));
double distance_it = 0;
auto it = carrot_pose_it == transform_plan_.poses.begin() ? transform_plan_.poses.end() : carrot_pose_it - 1; // robot_geometry_msgs::Pose back = robot_nav_2d_utils::pose2DToPose((*(carrot_pose_it)).pose);
for ( ; it != transform_plan_.poses.begin(); --it)
{
double dx = it->pose.x - carrot_pose_it->pose.x;
double dy = it->pose.y - carrot_pose_it->pose.y;
distance_it += std::hypot(dx, dy);
if (distance_it > costmap_robot_->getCostmap()->getResolution())
{
prev_carrot_pose_it = it;
break;
}
}
// robot::log_error("DEBUG STEP 11.3");
robot_geometry_msgs::Pose front = journey(transform_plan_.poses, 0, transform_plan_.poses.size() - 1) > 5.0 * costmap_robot_->getCostmap()->getResolution()
? robot_nav_2d_utils::pose2DToPose((*(prev_carrot_pose_it)).pose)
: robot_nav_2d_utils::pose2DToPose(robot_geometry_msgs::Pose2D());
robot_geometry_msgs::Pose back = robot_nav_2d_utils::pose2DToPose((*(carrot_pose_it)).pose);
// robot::log_error("DEBUG STEP 11.4");
// teb_local_planner::PoseSE2 start_pose(front); // teb_local_planner::PoseSE2 start_pose(front);
// teb_local_planner::PoseSE2 goal_pose(back); // teb_local_planner::PoseSE2 goal_pose(back);
// const double dir_path = (goal_pose.position() - start_pose.position()).dot(start_pose.orientationUnitVec()); // const double dir_path = (goal_pose.position() - start_pose.position()).dot(start_pose.orientationUnitVec());
const double dir_path = 0.0;
auto goal_pose = compute_plan_.poses.front().pose;
auto start_pose = pose.pose;
double angle_path = atan2(goal_pose.y - start_pose.y, goal_pose.x - start_pose.x);
double dir_path = cos(fabs(angle_path - goal_pose.theta));
if (fabs(dir_path) > M_PI / 6 || x_direction < 1e-9) if (fabs(dir_path) > M_PI / 6 || x_direction < 1e-9)
x_direction = dir_path > 0 ? FORWARD : BACKWARD; x_direction = dir_path > 0 ? FORWARD : BACKWARD;
// robot::log_error("DEBUG STEP 11.5");
} }
catch (std::exception &e) catch (std::exception &e)
{ {
robot::log_error("[%s:%d]\n getLookAheadPoint throw an exception: %s", __FILE__, __LINE__, e.what()); robot::log_warning_throttle(0.2, "[%s:%d]\n getLookAheadPoint throw an exception: %s", __FILE__, __LINE__, e.what());
return false; x_direction = x_direction_;
} }
} }
// robot::log_error("DEBUG STEP 11.0");
x_direction_ = x_direction; x_direction_ = x_direction;
y_direction_ = y_direction; y_direction_ = y_direction;
theta_direction_ = theta_direction; theta_direction_ = theta_direction;
@@ -489,8 +482,8 @@ mkt_msgs::Trajectory2D mkt_algorithm::diff::PredictiveTrajectory::calculator(
twist = traj_->nextTwist(); twist = traj_->nextTwist();
} }
double v_max = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x; double v_max = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x;
// drive_cmd.x = std::min(sqrt(twist.x * twist.x), fabs(v_max)); drive_cmd.x = std::min(sqrt(twist.x * twist.x), fabs(v_max));
drive_cmd.x = sqrt(twist.x * twist.x); // drive_cmd.x = sqrt(twist.x * twist.x);
robot_nav_2d_msgs::Path2D transformed_plan = this->transform_plan_; robot_nav_2d_msgs::Path2D transformed_plan = this->transform_plan_;
if (transformed_plan.poses.empty()) if (transformed_plan.poses.empty())
@@ -527,7 +520,11 @@ mkt_msgs::Trajectory2D mkt_algorithm::diff::PredictiveTrajectory::calculator(
const double distance_allow_rotate = min_journey_squared_; const double distance_allow_rotate = min_journey_squared_;
const double path_distance_to_rotate = journey(transformed_plan.poses, 0, transformed_plan.poses.size() - 1); const double path_distance_to_rotate = journey(transformed_plan.poses, 0, transformed_plan.poses.size() - 1);
allow_rotate |= path_distance_to_rotate >= distance_allow_rotate; allow_rotate |= path_distance_to_rotate >= distance_allow_rotate;
allow_rotate &= std::hypot(compute_plan_.poses.front().pose.x - pose.pose.x, compute_plan_.poses.front().pose.y - pose.pose.y) <= 0.1; // robot_geometry_msgs::Pose2D back_pose = transformed_plan.poses.back().pose;
// allow_rotate |= fabs(atan2(back_pose.y, back_pose.x) - back_pose.theta) > M_PI / 3.0;
allow_rotate &= (fabs(transformed_plan.poses.front().pose.y) <= 0.5);
double angle_to_heading; double angle_to_heading;
if (allow_rotate && shouldRotateToPath(transformed_plan, carrot_pose, velocity, angle_to_heading, sign_x)) if (allow_rotate && shouldRotateToPath(transformed_plan, carrot_pose, velocity, angle_to_heading, sign_x))
{ {
@@ -557,7 +554,7 @@ mkt_msgs::Trajectory2D mkt_algorithm::diff::PredictiveTrajectory::calculator(
// else // else
// { // {
robot_nav_2d_msgs::Twist2D drive_target = drive_cmd; robot_nav_2d_msgs::Twist2D drive_target = drive_cmd;
transformed_plan = this->generateTrajectory(transformed_plan, drive_cmd, velocity, sign_x, drive_target); transformed_plan = this->generateTrajectory(transformed_plan, drive_cmd, velocity, sign_x, drive_target, dt);
carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan); carrot_pose = *getLookAheadPoint(velocity, lookahead_dist, transformed_plan);
// Normal Pure Pursuit // Normal Pure Pursuit
@@ -584,6 +581,7 @@ mkt_msgs::Trajectory2D mkt_algorithm::diff::PredictiveTrajectory::calculator(
result.velocity = drive_cmd; result.velocity = drive_cmd;
return result; return result;
} }
} }
result.poses.clear(); result.poses.clear();
result.poses.reserve(transformed_plan.poses.size()); result.poses.reserve(transformed_plan.poses.size());
@@ -597,7 +595,11 @@ mkt_msgs::Trajectory2D mkt_algorithm::diff::PredictiveTrajectory::calculator(
} }
if(fabs(v_max == 0.0)) if(fabs(v_max == 0.0))
{
drive_cmd.x = 0.0; drive_cmd.x = 0.0;
robot::log_warning_throttle(0.2, "[%s:%d]\n v_max is 0.0", __FILE__, __LINE__);
return result;
}
result.velocity = drive_cmd; result.velocity = drive_cmd;
prevous_drive_cmd_ = drive_cmd; prevous_drive_cmd_ = drive_cmd;
return result; return result;
@@ -623,15 +625,15 @@ void mkt_algorithm::diff::PredictiveTrajectory::computePurePursuit(
// 3) Adjust speed using Hermite trajectory curvature + remaining distance // 3) Adjust speed using Hermite trajectory curvature + remaining distance
double v_target = adjustSpeedWithHermiteTrajectory(velocity, trajectory, drive_target.x, sign_x); double v_target = adjustSpeedWithHermiteTrajectory(velocity, trajectory, drive_target.x, sign_x);
const double L_min = 0.1; // m, chỉnh theo nhu cầu // const double L_min = 0.1; // m, chỉnh theo nhu cầu
double scale_close = std::clamp(L / L_min, 0.0, 1.0); // double scale_close = std::clamp(L / L_min, 0.0, 1.0);
v_target *= scale_close; // v_target *= scale_close;
const double y_abs = std::fabs(carrot_pose.pose.y); const double y_abs = std::fabs(carrot_pose.pose.y);
const double y_soft = 0.1; const double y_soft = 0.1;
if (y_abs > y_soft) if (y_abs > y_soft)
{ {
double scale = y_soft / y_abs; // y càng lớn => scale càng nhỏ double scale = y_soft / y_abs; // y càng lớn => scale càng nhỏ
scale = std::clamp(scale, 0.2, 1.0); // không giảm quá sâu scale = std::clamp(scale, 0.6, 1.0); // không giảm quá sâu
v_target *= scale; v_target *= scale;
robot_nav_2d_msgs::Twist2D cmd, result; robot_nav_2d_msgs::Twist2D cmd, result;
cmd.x = v_target; cmd.x = v_target;
@@ -642,9 +644,6 @@ void mkt_algorithm::diff::PredictiveTrajectory::computePurePursuit(
// 4) Maintain minimum approach speed // 4) Maintain minimum approach speed
if (std::fabs(v_target) < min_approach_linear_velocity) if (std::fabs(v_target) < min_approach_linear_velocity)
v_target = std::copysign(min_approach_linear_velocity, sign_x); v_target = std::copysign(min_approach_linear_velocity, sign_x);
std::stringstream ss;
// 5) Angular speed from curvature // 5) Angular speed from curvature
double w_target = v_target * kappa; double w_target = v_target * kappa;
if(journey(trajectory.poses, 0, trajectory.poses.size() - 1) <= min_journey_squared_) if(journey(trajectory.poses, 0, trajectory.poses.size() - 1) <= min_journey_squared_)
@@ -662,7 +661,6 @@ void mkt_algorithm::diff::PredictiveTrajectory::computePurePursuit(
if(fabs(dx) < 1e-6 && fabs(dy) < 1e-6) if(fabs(dx) < 1e-6 && fabs(dy) < 1e-6)
continue; continue;
heading_ref = std::atan2(dy, dx); heading_ref = std::atan2(dy, dx);
ss << "error " << heading_ref << " ";
if(sign_x < 0.0) if(sign_x < 0.0)
heading_ref += std::copysign(M_PI, heading_ref) * (-1.0); heading_ref += std::copysign(M_PI, heading_ref) * (-1.0);
break; break;
@@ -670,7 +668,6 @@ void mkt_algorithm::diff::PredictiveTrajectory::computePurePursuit(
} }
const double error = heading_ref; const double error = heading_ref;
ss << error << " ";
double w_heading = 0.0; double w_heading = 0.0;
pid(error, pid(error,
near_goal_heading_integral_, near_goal_heading_integral_,
@@ -682,8 +679,8 @@ void mkt_algorithm::diff::PredictiveTrajectory::computePurePursuit(
w_heading); w_heading);
// Apply acceleration limits // Apply acceleration limits
double dw_heading = std::clamp(w_heading - velocity.theta, -acc_lim_theta_ * dt, acc_lim_theta_ * dt); double dw_heading = std::clamp(w_heading - velocity.theta, -acc_lim_theta_ * dt, acc_lim_theta_ * dt);
ss << "dw_heading " << dw_heading << " ";
w_target = velocity.theta + dw_heading; w_target = velocity.theta + dw_heading;
w_target = std::clamp(w_target, -fabs(drive_target.theta), fabs(drive_target.theta));
} }
else else
{ {
@@ -695,7 +692,6 @@ void mkt_algorithm::diff::PredictiveTrajectory::computePurePursuit(
{ {
near_goal_heading_was_active_ = false; near_goal_heading_was_active_ = false;
} }
w_target = std::clamp(w_target, -fabs(drive_target.theta), fabs(drive_target.theta)); w_target = std::clamp(w_target, -fabs(drive_target.theta), fabs(drive_target.theta));
// 6) Apply acceleration limits (linear + angular) // 6) Apply acceleration limits (linear + angular)
@@ -723,8 +719,8 @@ void mkt_algorithm::diff::PredictiveTrajectory::computePurePursuit(
drive_cmd.x = std::clamp(kf_->state()[0], -fabs(v_target), fabs(v_target)); drive_cmd.x = std::clamp(kf_->state()[0], -fabs(v_target), fabs(v_target));
drive_cmd.x = fabs(drive_cmd.x) >= v_min ? drive_cmd.x : std::copysign(v_min, sign_x); drive_cmd.x = fabs(drive_cmd.x) >= v_min ? drive_cmd.x : std::copysign(v_min, sign_x);
if (kf_filter_angular_) if (kf_filter_angular_)
drive_cmd.theta = std::clamp(kf_->state()[3], -max_vel_theta_, max_vel_theta_); drive_cmd.theta = std::clamp(kf_->state()[3], -fabs(drive_target.theta), fabs(drive_target.theta));
// robot::log_info("%s", ss.str().c_str()); // robot::log_info("drive_cmd.theta: %f, drive_target.theta: %f", drive_cmd.theta, drive_target.theta);
} }
void mkt_algorithm::diff::PredictiveTrajectory::applyDistanceSpeedScaling( void mkt_algorithm::diff::PredictiveTrajectory::applyDistanceSpeedScaling(
@@ -748,8 +744,9 @@ void mkt_algorithm::diff::PredictiveTrajectory::applyDistanceSpeedScaling(
double cosine_factor = 0.5 * (1.0 + std::cos(M_PI * (1.0 - r))); double cosine_factor = 0.5 * (1.0 + std::cos(M_PI * (1.0 - r)));
target_speed = max_speed * cosine_factor; target_speed = max_speed * cosine_factor;
} }
const double v_limited = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x;
double reduce_speed = std::min(max_speed, min_speed_xy_); const double v_min = std::min(fabs(v_limited), min_speed_xy_);
double reduce_speed = std::min(max_speed, v_min);
if (s < S_final) if (s < S_final)
{ {
double r = std::clamp(s / S_final, 0.0, 1.0); double r = std::clamp(s / S_final, 0.0, 1.0);
@@ -782,15 +779,16 @@ bool mkt_algorithm::diff::PredictiveTrajectory::shouldRotateToPath(
// const double max_kappa = calculateMaxKappa(global_plan); // const double max_kappa = calculateMaxKappa(global_plan);
// const bool curvature = max_kappa > straight_threshold; // const bool curvature = max_kappa > straight_threshold;
double path_angle = std::atan2(carrot_pose.pose.y, carrot_pose.pose.x); double path_angle = std::atan2(carrot_pose.pose.y, carrot_pose.pose.x);
if(is_stopped && global_plan.poses.size() >= 2) if(is_stopped && global_plan.poses.size() >= 4 &&
journey(global_plan.poses, 0, global_plan.poses.size() - 1) >= 0.7 * min_lookahead_dist_)
{ {
const auto& p1 = global_plan.poses[1]; const auto& p1 = global_plan.poses[2];
for(int i = 2; i < global_plan.poses.size(); i++) for(int i = 3; i < global_plan.poses.size(); i++)
{ {
const auto& p = global_plan.poses[i]; const auto& p = global_plan.poses[i];
const auto& dx = p.pose.x - p1.pose.x; const auto& dx = p.pose.x - p1.pose.x;
const auto& dy = p.pose.y - p1.pose.y; const auto& dy = p.pose.y - p1.pose.y;
if(std::hypot(p.pose.x, p.pose.y) > costmap_robot_->getCostmap()->getResolution()) if(std::hypot(dx, dy) > costmap_robot_->getCostmap()->getResolution())
{ {
if(fabs(dx) < 1e-9 && fabs(dy) < 1e-9) if(fabs(dx) < 1e-9 && fabs(dy) < 1e-9)
continue; continue;
@@ -801,9 +799,10 @@ bool mkt_algorithm::diff::PredictiveTrajectory::shouldRotateToPath(
} }
// Whether we should rotate robot to rough path heading // Whether we should rotate robot to rough path heading
if(sign_x < 0.0) // if(sign_x < 0.0)
path_angle += std::copysign(M_PI, path_angle) * (-1.0); // path_angle += std::copysign(M_PI, path_angle) * (-1.0);
angle_to_path = path_angle; // angle_to_path = path_angle;
angle_to_path = sign_x < 0.0 ? angles::normalize_angle(M_PI + path_angle) : path_angle;
double heading_linear = sqrt(velocity.x * velocity.x + velocity.y * velocity.y); double heading_linear = sqrt(velocity.x * velocity.x + velocity.y * velocity.y);
// The difference in the path orientation and the starting robot orientation (radians) to trigger a rotate in place. (default: 0.785) // The difference in the path orientation and the starting robot orientation (radians) to trigger a rotate in place. (default: 0.785)
double heading_rotate = rotate_to_heading_min_angle_; double heading_rotate = rotate_to_heading_min_angle_;
@@ -819,12 +818,9 @@ bool mkt_algorithm::diff::PredictiveTrajectory::shouldRotateToPath(
#ifdef BUILD_WITH_ROS #ifdef BUILD_WITH_ROS
if (result) if (result)
ROS_WARN_THROTTLE(0.1, "angle_to_path: %f, heading_rotate: %f, is_stopped: %x %x, sign_x: %f", angle_to_path, heading_rotate, is_stopped, sign(angle_to_path) * sign_x < 0, sign_x); ROS_WARN_THROTTLE(0.1, "angle_to_path: %f, heading_rotate: %f, is_stopped: %x %x, sign_x: %f", angle_to_path, heading_rotate, is_stopped, sign(angle_to_path) * sign_x < 0, sign_x);
#else
// else if(fabs(velocity.x) < min_speed_xy_) if (result)
// { robot::log_info_throttle(0.1, "angle_to_path: %f, heading_rotate: %f, is_stopped: %x %x, sign_x: %f", angle_to_path, heading_rotate, is_stopped, sign(angle_to_path) * sign_x < 0, sign_x);
// ROS_INFO_THROTTLE(0.1, "velocity.x: %f, velocity.theta: %f, ", velocity.x, velocity.theta);
// ROS_INFO_THROTTLE(0.1, "angle_to_path: %f, heading_rotate: %f, is_stopped: %x %x, sign_x: %f", angle_to_path, heading_rotate, is_stopped, sign(angle_to_path) * sign_x < 0, sign_x);
// }
#endif #endif
return result; return result;
} }
@@ -961,8 +957,10 @@ void mkt_algorithm::diff::PredictiveTrajectory::alignToFinalHeading(
// --- Linear velocity calculation --- // --- Linear velocity calculation ---
// Base velocity proportional to distance, with minimum for smooth motion // Base velocity proportional to distance, with minimum for smooth motion
double v_base = std::sqrt(2.0 * std::fabs(decel_lim_x_) * xy_error); double v_base = std::sqrt(2.0 * std::fabs(decel_lim_x_) * xy_error);
const double v_limited = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x;
const double v_min = std::min(fabs(v_limited), min_speed_xy_);
v_base = std::max(v_base, final_heading_min_velocity_); v_base = std::max(v_base, final_heading_min_velocity_);
v_base = std::min(v_base, min_speed_xy_); v_base = std::min(v_base, v_min);
// Scale down when heading error is large (prioritize rotation) // Scale down when heading error is large (prioritize rotation)
double heading_scale = 1.0; double heading_scale = 1.0;
@@ -1034,7 +1032,7 @@ void mkt_algorithm::diff::PredictiveTrajectory::alignToFinalHeading(
cmd_vel.theta = omega_current + domega; cmd_vel.theta = omega_current + domega;
// --- Apply velocity limits --- // --- Apply velocity limits ---
cmd_vel.x = std::clamp(cmd_vel.x, -min_speed_xy_, min_speed_xy_); cmd_vel.x = std::clamp(cmd_vel.x, -v_min, v_min);
cmd_vel.theta = std::clamp(cmd_vel.theta, -max_vel_theta_, max_vel_theta_); cmd_vel.theta = std::clamp(cmd_vel.theta, -max_vel_theta_, max_vel_theta_);
// --- Safety: ensure we can stop --- // --- Safety: ensure we can stop ---
@@ -1086,8 +1084,7 @@ double mkt_algorithm::diff::PredictiveTrajectory::getLookAheadDistance(const rob
} }
std::vector<robot_nav_2d_msgs::Pose2DStamped>::iterator std::vector<robot_nav_2d_msgs::Pose2DStamped>::iterator
mkt_algorithm::diff::PredictiveTrajectory::getLookAheadPoint(const robot_nav_2d_msgs::Twist2D &velocity, mkt_algorithm::diff::PredictiveTrajectory::getLookAheadPoint(const robot_nav_2d_msgs::Twist2D &velocity, const double &lookahead_dist, robot_nav_2d_msgs::Path2D global_plan)
const double &lookahead_dist, robot_nav_2d_msgs::Path2D& global_plan)
{ {
if (global_plan.poses.empty()) if (global_plan.poses.empty())
throw robot_nav_core2::PlannerTFException("The global plan passed to the local planner is empty."); throw robot_nav_core2::PlannerTFException("The global plan passed to the local planner is empty.");
@@ -1124,104 +1121,9 @@ mkt_algorithm::diff::PredictiveTrajectory::getLookAheadPoint(const robot_nav_2d_
if (goal_pose_it == global_plan.poses.end()) if (goal_pose_it == global_plan.poses.end())
goal_pose_it = std::prev(global_plan.poses.end()); goal_pose_it = std::prev(global_plan.poses.end());
// --- Final safety check ---
if (goal_pose_it < global_plan.poses.begin() || goal_pose_it >= global_plan.poses.end())
{
// fallback cuối cùng
goal_pose_it = std::prev(global_plan.poses.end());
}
return goal_pose_it; return goal_pose_it;
} }
// std::vector<robot_nav_2d_msgs::Pose2DStamped>::iterator
// mkt_algorithm::diff::PredictiveTrajectory::getLookAheadPoint(
// const robot_nav_2d_msgs::Twist2D &velocity,
// const double &lookahead_dist,
// robot_nav_2d_msgs::Path2D &global_plan)
// {
// auto &poses = global_plan.poses;
// // --- Guard ---
// if (poses.empty())
// throw robot_nav_core2::PlannerTFException("The global plan is empty.");
// if (poses.size() == 1)
// return poses.begin();
// if (poses.size() == 2)
// return std::prev(poses.end());
// // --- Init ---
// size_t goal_index = poses.size() - 1;
// const auto &p0 = poses[0].pose;
// const auto &p1 = poses[1].pose;
// double start_angle = atan2(p1.y - p0.y, p1.x - p0.x);
// double turn_threshold = M_PI_2 * 0.6;
// // --- Detect turn ---
// for (size_t i = 1; i < poses.size(); ++i)
// {
// const auto &a = poses[i - 1].pose;
// const auto &b = poses[i].pose;
// double current_angle = atan2(b.y - a.y, b.x - a.x);
// double delta = angles::normalize_angle(current_angle - start_angle);
// goal_index = i;
// if (fabs(delta) >= turn_threshold)
// break;
// }
// // --- Clamp goal_index ---
// if (goal_index >= poses.size())
// goal_index = poses.size() - 1;
// // --- Safe search range ---
// auto search_begin = poses.begin();
// // ❗ IMPORTANT: +1 để iterator hợp lệ
// auto search_end = poses.begin() + goal_index + 1;
// if (search_end > poses.end())
// search_end = poses.end();
// // --- Find lookahead ---
// double accumulated_dist = 0.0;
// auto goal_pose_it = search_begin;
// for (auto it = search_begin + 1; it != search_end; ++it)
// {
// double dx = it->pose.x - std::prev(it)->pose.x;
// double dy = it->pose.y - std::prev(it)->pose.y;
// accumulated_dist += std::hypot(dx, dy);
// if (accumulated_dist >= lookahead_dist)
// {
// goal_pose_it = it;
// break;
// }
// }
// // --- Fallback an toàn ---
// if (goal_pose_it == search_begin)
// {
// goal_pose_it = std::prev(search_end); // safe vì search_end > search_begin
// }
// // --- Final safety check ---
// if (goal_pose_it < poses.begin() || goal_pose_it >= poses.end())
// {
// // fallback cuối cùng
// return std::prev(poses.end());
// }
// return goal_pose_it;
// }
bool mkt_algorithm::diff::PredictiveTrajectory::pruneGlobalPlan(TFListenerPtr tf, const robot_nav_2d_msgs::Pose2DStamped &pose, robot_nav_2d_msgs::Path2D &global_plan, double dist_behind_robot) bool mkt_algorithm::diff::PredictiveTrajectory::pruneGlobalPlan(TFListenerPtr tf, const robot_nav_2d_msgs::Pose2DStamped &pose, robot_nav_2d_msgs::Path2D &global_plan, double dist_behind_robot)
{ {
if (global_plan.poses.empty()) if (global_plan.poses.empty())
@@ -1312,9 +1214,11 @@ double mkt_algorithm::diff::PredictiveTrajectory::adjustSpeedWithHermiteTrajecto
double v_limit = std::fabs(v_target); double v_limit = std::fabs(v_target);
double journey_distance = journey(trajectory.poses, 0, trajectory.poses.size() - 1); double journey_distance = journey(trajectory.poses, 0, trajectory.poses.size() - 1);
const double v_limited = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x;
const double v_min = std::min(fabs(v_limited), min_speed_xy_);
if (journey_distance < min_journey_squared_) if (journey_distance < min_journey_squared_)
{ {
v_limit = std::clamp(sqrt(2.0 * fabs(decel_lim_x_) * journey_distance), min_approach_linear_velocity_, min_speed_xy_) * sign_x; v_limit = std::clamp(sqrt(2.0 * fabs(decel_lim_x_) * journey_distance), min_approach_linear_velocity_, v_min) * sign_x;
} }
if (max_kappa > 1e-6 && max_lateral_accel_ > 1e-6) if (max_kappa > 1e-6 && max_lateral_accel_ > 1e-6)
@@ -1324,7 +1228,7 @@ double mkt_algorithm::diff::PredictiveTrajectory::adjustSpeedWithHermiteTrajecto
} }
if(trajectory.poses.size() > 2 && fabs(trajectory.poses.front().pose.theta) >= angle_threshold_) if(trajectory.poses.size() > 2 && fabs(trajectory.poses.front().pose.theta) >= angle_threshold_)
v_limit = min_speed_xy_ * sign_x; v_limit = v_min * sign_x;
if (fabs(decel_lim_x_) > 1e-6) if (fabs(decel_lim_x_) > 1e-6)
{ {
@@ -1342,7 +1246,8 @@ robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generateTra
const robot_nav_2d_msgs::Twist2D &drive_target, const robot_nav_2d_msgs::Twist2D &drive_target,
const robot_nav_2d_msgs::Twist2D &velocity, const robot_nav_2d_msgs::Twist2D &velocity,
const double &sign_x, const double &sign_x,
robot_nav_2d_msgs::Twist2D &drive_cmd) robot_nav_2d_msgs::Twist2D &drive_cmd,
const double &dt)
{ {
if (path.poses.empty()) if (path.poses.empty())
{ {
@@ -1350,23 +1255,30 @@ robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generateTra
drive_cmd.theta = 0.0; drive_cmd.theta = 0.0;
return robot_nav_2d_msgs::Path2D(); return robot_nav_2d_msgs::Path2D();
} }
drive_cmd.x = drive_target.x;
drive_cmd.theta = max_vel_theta_;
double max_kappa = calculateMaxKappa(path); double max_kappa = calculateMaxKappa(path);
const double straight_threshold = std::max(0.05, 2.0 * (costmap_robot_ ? costmap_robot_->getCostmap()->getResolution() : 0.05)); const double straight_threshold = std::max(0.05, 2.0 * (costmap_robot_ ? costmap_robot_->getCostmap()->getResolution() : 0.05));
drive_cmd.x = this->adjustSpeedWithHermiteTrajectory(velocity, path, drive_target.x, sign_x); // nếu đường thẳng
drive_cmd.theta = max_vel_theta_; if (max_kappa <= straight_threshold)
if (max_kappa <= straight_threshold && fabs(path.poses.back().pose.x) < min_lookahead_dist_) // nếu đường thẳng
{ {
if(fabs(path.poses.front().pose.y) <= 0.03 && fabs(path.poses.back().pose.x) < min_lookahead_dist_ ) if(fabs(path.poses.back().pose.x) < min_lookahead_dist_ * 0.8)
{ {
if(fabs(path.poses.back().pose.x) < min_journey_squared_)
drive_cmd.theta = 0.01;
return generateParallelPath(path, sign_x); return generateParallelPath(path, sign_x);
} }
return generateHermiteTrajectory(path, sign_x); return generateHermiteTrajectory(path, sign_x);
} }
else // nếu đường cong else // nếu đường cong
{ {
if(fabs(drive_cmd.x) < min_speed_xy_) const double v_limited = sign_x > 0 ? traj_->getTwistLinear(true).x : traj_->getTwistLinear(false).x;
drive_cmd.x = std::copysign(min_speed_xy_, sign_x); const double v_min = std::min(fabs(v_limited), min_speed_xy_);
if(fabs(drive_cmd.x) < v_min)
{
drive_cmd.x = std::copysign(v_min, sign_x);
}
return generateHermiteQuadraticTrajectory(path, sign_x); return generateHermiteQuadraticTrajectory(path, sign_x);
} }
} }
@@ -1411,8 +1323,6 @@ robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generatePar
return parallel_path; return parallel_path;
} }
robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generateHermiteTrajectory( robot_nav_2d_msgs::Path2D mkt_algorithm::diff::PredictiveTrajectory::generateHermiteTrajectory(
const robot_nav_2d_msgs::Path2D &path, const double &sign_x) const robot_nav_2d_msgs::Path2D &path, const double &sign_x)
{ {

View File

@@ -46,6 +46,8 @@ namespace two_points_planner
name_ = name; name_ = name;
costmap_robot_ = costmap_robot; costmap_robot_ = costmap_robot;
if(!costmap_robot_ || !costmap_robot_->getCostmap()) if(!costmap_robot_ || !costmap_robot_->getCostmap())
{ {
robot::log_warning("[%s:%d]TwoPointsPlanner Initialized failed", __FILE__, __LINE__); robot::log_warning("[%s:%d]TwoPointsPlanner Initialized failed", __FILE__, __LINE__);
@@ -55,6 +57,8 @@ namespace two_points_planner
current_env_height_ = costmap_robot_->getCostmap()->getSizeInCellsY(); current_env_height_ = costmap_robot_->getCostmap()->getSizeInCellsY();
footprint_ = costmap_robot_->getRobotFootprint(); footprint_ = costmap_robot_->getRobotFootprint();
robot::log_info("size x: %d, size y: %d, resolution: %f", costmap_robot_->getCostmap()->getSizeInCellsX(), costmap_robot_->getCostmap()->getSizeInCellsY(), costmap_robot_->getCostmap()->getResolution());
robot::log_info("TwoPointsPlanner Initialized successfully"); robot::log_info("TwoPointsPlanner Initialized successfully");
initialized_ = true; initialized_ = true;
return true; return true;
@@ -120,6 +124,17 @@ namespace two_points_planner
return false; return false;
} }
robot::Time start_time = robot::Time::now();
robot::Rate rate(1.0);
while(costmap_robot_->getCostmap()->getSizeInCellsX() == 0 || costmap_robot_->getCostmap()->getSizeInCellsY() == 0){
robot::log_warning("Waiting for costmap to be initialized...");
rate.sleep();
if((robot::Time::now() - start_time).toSec() > 5.0){
robot::log_error("Costmap not initialized after 10 seconds, exiting...");
exit(1);
}
}
robot_nav_2d_msgs::Pose2DStamped start_2d = robot_nav_2d_utils::poseStampedToPose2D(start); robot_nav_2d_msgs::Pose2DStamped start_2d = robot_nav_2d_utils::poseStampedToPose2D(start);
robot_nav_2d_msgs::Pose2DStamped goal_2d = robot_nav_2d_utils::poseStampedToPose2D(goal); robot_nav_2d_msgs::Pose2DStamped goal_2d = robot_nav_2d_utils::poseStampedToPose2D(goal);
robot::log_info_at(__FILE__, __LINE__, "Making plan from start (%.2f,%.2f,%.2f) to goal (%.2f,%.2f,%.2f)", robot::log_info_at(__FILE__, __LINE__, "Making plan from start (%.2f,%.2f,%.2f) to goal (%.2f,%.2f,%.2f)",
@@ -190,14 +205,9 @@ namespace two_points_planner
} }
else else
{ {
auto goal_2d = robot_nav_2d_utils::poseStampedToPose2D(goal); // hoặc start.theta robot_geometry_msgs::PoseStamped pose = start;
robot_geometry_msgs::PoseStamped pose = goal; pose.pose.position.x += resolution * cos(theta);
pose.pose.position.x += resolution * std::cos(goal_2d.pose.theta); pose.pose.position.y += resolution * sin(theta);
pose.pose.position.y += resolution * std::sin(goal_2d.pose.theta);
plan.push_back(pose);
pose = goal;
pose.pose.position.x -= resolution * std::cos(goal_2d.pose.theta);
pose.pose.position.y -= resolution * std::sin(goal_2d.pose.theta);
plan.push_back(pose); plan.push_back(pose);
plan.push_back(goal); plan.push_back(goal);
return true; return true;

View File

@@ -31,8 +31,6 @@ namespace pnkx_local_planner
void initialize(robot::NodeHandle &parent, const std::string &name, void initialize(robot::NodeHandle &parent, const std::string &name,
TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override; TFListenerPtr tf, robot_costmap_2d::Costmap2DROBOT *costmap_robot) override;
void setPlan(const robot_nav_2d_msgs::Path2D &path) override;
/** /**
* @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity * @brief robot_nav_core2 computeVelocityCommands - calculates the best command given the current pose and velocity
* *

View File

@@ -240,12 +240,6 @@ void pnkx_local_planner::PNKXDockingLocalPlanner::getParams(robot::NodeHandle &n
} }
} }
void pnkx_local_planner::PNKXDockingLocalPlanner::setPlan(const robot_nav_2d_msgs::Path2D &path)
{
this->reset();
pnkx_local_planner::PNKXLocalPlanner::setPlan(path);
}
void pnkx_local_planner::PNKXDockingLocalPlanner::reset() void pnkx_local_planner::PNKXDockingLocalPlanner::reset()
{ {
robot::log_info_at(__FILE__, __LINE__, "New Docking Goal Received."); robot::log_info_at(__FILE__, __LINE__, "New Docking Goal Received.");
@@ -261,12 +255,11 @@ void pnkx_local_planner::PNKXDockingLocalPlanner::reset()
parent_.setParam(algorithm_nav_name, original_papams_); parent_.setParam(algorithm_nav_name, original_papams_);
robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name); robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name);
// nh_algorithm.setParam("allow_rotate", false); nh_algorithm.setParam("allow_rotate", false);
} }
void pnkx_local_planner::PNKXDockingLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) void pnkx_local_planner::PNKXDockingLocalPlanner::prepare(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity)
{ {
// robot::log_debug_at(__FILE__, __LINE__, "DEBUG STEP 1.0");
this->getParams(planner_nh_); this->getParams(planner_nh_);
if (update_costmap_before_planning_) if (update_costmap_before_planning_)
{ {
@@ -280,12 +273,11 @@ void pnkx_local_planner::PNKXDockingLocalPlanner::prepare(const robot_nav_2d_msg
if (!costmap_robot_->isCurrent()) if (!costmap_robot_->isCurrent())
throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow."); throw robot_nav_core2::CostmapDataLagException("Costmap2DROBOT is out of date somehow.");
} }
// robot::log_debug_at(__FILE__, __LINE__, "DEBUG STEP 2.0");
// Update time stamp of goal pose // Update time stamp of goal pose
// goal_pose_.header.stamp = pose.header.stamp; // goal_pose_.header.stamp = pose.header.stamp;
robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose), robot_nav_2d_msgs::Pose2DStamped local_start_pose = this->transformPoseToLocal(pose),
local_goal_pose = this->transformPoseToLocal(goal_pose_); local_goal_pose = this->transformPoseToLocal(goal_pose_);
// robot::log_debug_at(__FILE__, __LINE__, "DEBUG STEP 3.0");
if (start_docking_) if (start_docking_)
{ {
local_goal_pose = goal_pose_; local_goal_pose = goal_pose_;
@@ -293,14 +285,6 @@ void pnkx_local_planner::PNKXDockingLocalPlanner::prepare(const robot_nav_2d_msg
try try
{ {
// robot::log_error("local_start_pose (%f, %f, %f)", local_start_pose.pose.x, local_start_pose.pose.y, local_start_pose.pose.theta);
// robot::log_error("local_goal_pose (%f, %f, %f)", local_goal_pose.pose.x, local_goal_pose.pose.y, local_goal_pose.pose.theta);
// for(size_t i = 0; i < global_plan_.poses.size(); i++)
// {
// robot::log_error("global_plan_ [%zu] (%f, %f, %f)", i, global_plan_.poses[i].pose.x, global_plan_.poses[i].pose.y, global_plan_.poses[i].pose.theta);
// }
// robot::log_error("costmap_robot_->getGlobalFrameID(): %s", costmap_robot_->getGlobalFrameID().c_str());
if (!pnkx_local_planner::transformGlobalPlan(tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_)) if (!pnkx_local_planner::transformGlobalPlan(tf_, global_plan_, local_start_pose, costmap_robot_, costmap_robot_->getGlobalFrameID(), 2.0, transformed_global_plan_))
robot::log_warning_at(__FILE__, __LINE__, "Transform global plan is failed"); robot::log_warning_at(__FILE__, __LINE__, "Transform global plan is failed");
} }
@@ -310,60 +294,53 @@ void pnkx_local_planner::PNKXDockingLocalPlanner::prepare(const robot_nav_2d_msg
} }
double x_direction, y_direction, theta_direction; double x_direction, y_direction, theta_direction;
if (!ret_nav_ && !dkpl_.empty()) if (!ret_nav_)
{ {
// robot::log_debug_at(__FILE__, __LINE__, "DEBUG STEP 4.0"); if (!nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction))
if(nav_algorithm_)
{ {
if (!nav_algorithm_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction)) robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str());
{ throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare");
robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str()); }
throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare"); // else
} // ROS_INFO_THROTTLE(0.2, "chieu %f %f %f", x_direction, y_direction, theta_direction);
// else
// ROS_INFO_THROTTLE(0.2, "chieu %f %f %f", x_direction, y_direction, theta_direction);
// robot::log_debug_at(__FILE__, __LINE__, "DEBUG STEP 5.0");
if (!dkpl_.empty() && dkpl_.front()->initialized_ && dkpl_.front()->is_detected_ && !dkpl_.front()->is_goal_reached_)
{
// robot::log_debug_at(__FILE__, __LINE__, "DEBUG STEP 6.0");
this->lock();
robot_geometry_msgs::Vector3 linear = dkpl_.front()->linear_;
traj_generator_->setTwistLinear(linear);
linear.x *= (-1);
traj_generator_->setTwistLinear(linear);
traj_generator_->setTwistAngular(dkpl_.front()->angular_);
std::string algorithm_nav_name; if (!dkpl_.empty() && dkpl_.front()->initialized_ && dkpl_.front()->is_detected_ && !dkpl_.front()->is_goal_reached_)
planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA")); {
robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name); this->lock();
nh_algorithm.setParam("allow_rotate", dkpl_.front()->allow_rotate_); robot_geometry_msgs::Vector3 linear = dkpl_.front()->linear_;
nh_algorithm.setParam("min_lookahead_dist", dkpl_.front()->min_lookahead_dist_); traj_generator_->setTwistLinear(linear);
nh_algorithm.setParam("max_lookahead_dist", dkpl_.front()->max_lookahead_dist_); linear.x *= (-1);
nh_algorithm.setParam("lookahead_time", dkpl_.front()->lookahead_time_); traj_generator_->setTwistLinear(linear);
nh_algorithm.setParam("angle_threshold", dkpl_.front()->angle_threshold_); traj_generator_->setTwistAngular(dkpl_.front()->angular_);
parent_.setParam("xy_goal_tolerance", dkpl_.front()->xy_goal_tolerance_); std::string algorithm_nav_name;
parent_.setParam("yaw_goal_tolerance", dkpl_.front()->yaw_goal_tolerance_); planner_nh_.param("algorithm_nav_name", algorithm_nav_name, std::string("pnkx_local_planner::PTA"));
// robot::log_debug_at(__FILE__, __LINE__, "DEBUG STEP 7.0"); robot::NodeHandle nh_algorithm = robot::NodeHandle(parent_, algorithm_nav_name);
if (dkpl_.front()->docking_nav_ && !dkpl_.front()->docking_planner_) nh_algorithm.setParam("allow_rotate", dkpl_.front()->allow_rotate_);
nh_algorithm.setParam("min_lookahead_dist", dkpl_.front()->min_lookahead_dist_);
nh_algorithm.setParam("max_lookahead_dist", dkpl_.front()->max_lookahead_dist_);
nh_algorithm.setParam("lookahead_time", dkpl_.front()->lookahead_time_);
nh_algorithm.setParam("angle_threshold", dkpl_.front()->angle_threshold_);
parent_.setParam("xy_goal_tolerance", dkpl_.front()->xy_goal_tolerance_);
parent_.setParam("yaw_goal_tolerance", dkpl_.front()->yaw_goal_tolerance_);
if (dkpl_.front()->docking_nav_ && !dkpl_.front()->docking_planner_)
{
if (dkpl_.front()->following_)
{ {
robot_nav_2d_msgs::Pose2DStamped follow_pose;
if (dkpl_.front()->following_) if (dkpl_.front()->geLocalGoal(local_goal_pose))
{ {
robot_nav_2d_msgs::Pose2DStamped follow_pose; local_goal_pose = follow_pose;
if (dkpl_.front()->geLocalGoal(local_goal_pose))
{
local_goal_pose = follow_pose;
}
}
if (!dkpl_.front()->docking_nav_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction))
{
throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare");
robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str());
} }
} }
if (!dkpl_.front()->docking_nav_->prepare(local_start_pose, velocity, local_goal_pose, transformed_global_plan_, x_direction, y_direction, theta_direction))
// robot::log_debug_at(__FILE__, __LINE__, "DEBUG STEP 8.0"); {
throw robot_nav_core2::LocalPlannerException("Algorithm failed to prepare");
robot::log_warning_at(__FILE__, __LINE__, "Algorithm \"%s\" failed to prepare", nav_algorithm_->getName().c_str());
}
} }
} }
} }
@@ -388,26 +365,15 @@ void pnkx_local_planner::PNKXDockingLocalPlanner::prepare(const robot_nav_2d_msg
robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXDockingLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose, robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXDockingLocalPlanner::computeVelocityCommands(const robot_nav_2d_msgs::Pose2DStamped &pose,
const robot_nav_2d_msgs::Twist2D &velocity) const robot_nav_2d_msgs::Twist2D &velocity)
{ {
// // boost::recursive_mutex::scoped_lock l(configuration_mutex_); // boost::recursive_mutex::scoped_lock l(configuration_mutex_);
// for(size_t i = 0; i < global_plan_.poses.size(); i++) robot::log_error("DEBUG 300");
// {
// robot::log_error("computeVelocityCommands global_plan_ [%d] (%f, %f, %f)", i, global_plan_.poses[i].pose.x, global_plan_.poses[i].pose.y, global_plan_.poses[i].pose.theta);
// }
robot_nav_2d_msgs::Twist2DStamped cmd_vel; robot_nav_2d_msgs::Twist2DStamped cmd_vel;
cmd_vel.header.stamp = robot::Time::now();
cmd_vel.velocity.x = 0.0;
cmd_vel.velocity.y = 0.0;
cmd_vel.velocity.theta = 0.0;
try try
{ {
// robot::log_debug_at(__FILE__, __LINE__, "DEBUG STEP 1.0"); if (global_plan_.poses.empty())
if ( global_plan_.poses.empty())
return cmd_vel; return cmd_vel;
// robot::log_debug_at(__FILE__, __LINE__, "DEBUG STEP 1.11");
this->prepare(pose, velocity); this->prepare(pose, velocity);
// robot::log_debug_at(__FILE__, __LINE__, "DEBUG STEP 2");
cmd_vel = this->ScoreAlgorithm(pose, velocity); cmd_vel = this->ScoreAlgorithm(pose, velocity);
// robot::log_debug_at(__FILE__, __LINE__, "DEBUG STEP 3");
return cmd_vel; return cmd_vel;
} }
catch (const robot_nav_core2::PlannerException &e) catch (const robot_nav_core2::PlannerException &e)
@@ -454,19 +420,14 @@ robot_nav_2d_msgs::Twist2DStamped pnkx_local_planner::PNKXDockingLocalPlanner::S
bool pnkx_local_planner::PNKXDockingLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity) bool pnkx_local_planner::PNKXDockingLocalPlanner::isGoalReached(const robot_nav_2d_msgs::Pose2DStamped &pose, const robot_nav_2d_msgs::Twist2D &velocity)
{ {
// if(global_plan_.poses.size() <= 2)
// {
// robot::log_error("DEBUG GOAL");
// return true;
// }
if (goal_pose_.header.frame_id == "") if (goal_pose_.header.frame_id == "")
{ {
robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!"); robot::log_warning_at(__FILE__, __LINE__, "Cannot check if the goal is reached without the goal being set!");
return false; return false;
} }
robot::log_error("DEBUG 400.1");
bool dock_ok = dockingHanlde(pose, velocity); bool dock_ok = dockingHanlde(pose, velocity);
robot::log_error("DEBUG 400.2");
// Update time stamp of goal pose // Update time stamp of goal pose
// goal_pose_.header.stamp = pose.header.stamp; // goal_pose_.header.stamp = pose.header.stamp;
robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose); robot_nav_2d_msgs::Pose2DStamped local_pose = this->transformPoseToLocal(pose);
@@ -493,8 +454,7 @@ bool pnkx_local_planner::PNKXDockingLocalPlanner::isGoalReached(const robot_nav_
} }
} }
// if (ret_nav_ && !ret_angle_ && !dock_ok) if (ret_nav_ && !ret_angle_ && !dock_ok)
if (ret_nav_ && !ret_angle_)
{ {
double delta_orient = double delta_orient =
fabs(angles::normalize_angle(local_goal.pose.theta - local_pose.pose.theta)); fabs(angles::normalize_angle(local_goal.pose.theta - local_pose.pose.theta));
@@ -544,6 +504,7 @@ bool pnkx_local_planner::PNKXDockingLocalPlanner::dockingHanlde(const robot_nav_
{ {
if (dkpl_.front()->geLocalGoal(local_goal)) if (dkpl_.front()->geLocalGoal(local_goal))
{ {
robot::log_error("DEBUG 100");
dkpl_.front()->is_detected_ = true; dkpl_.front()->is_detected_ = true;
start_docking_ = true; start_docking_ = true;
robot_nav_msgs::Path path; robot_nav_msgs::Path path;
@@ -551,7 +512,6 @@ bool pnkx_local_planner::PNKXDockingLocalPlanner::dockingHanlde(const robot_nav_
dkpl_.front()->getLocalPath(local_pose, local_goal, path); dkpl_.front()->getLocalPath(local_pose, local_goal, path);
this->setPlan(robot_nav_2d_utils::pathToPath(path)); this->setPlan(robot_nav_2d_utils::pathToPath(path));
this->setGoalPose(local_goal); this->setGoalPose(local_goal);
robot::log_debug(__FILE__, __LINE__, "DEBUG 1 size path: %d", (int)path.poses.size());
} }
} }
catch (const std::exception &e) catch (const std::exception &e)
@@ -566,6 +526,7 @@ bool pnkx_local_planner::PNKXDockingLocalPlanner::dockingHanlde(const robot_nav_
{ {
if (dkpl_.front()->geLocalGoal(local_goal)) if (dkpl_.front()->geLocalGoal(local_goal))
{ {
robot::log_error("DEBUG 200");
dkpl_.front()->is_detected_ = true; dkpl_.front()->is_detected_ = true;
start_docking_ = true; start_docking_ = true;
robot_nav_2d_msgs::Path2D path; robot_nav_2d_msgs::Path2D path;
@@ -576,7 +537,6 @@ bool pnkx_local_planner::PNKXDockingLocalPlanner::dockingHanlde(const robot_nav_
path.poses.push_back(local_goal); path.poses.push_back(local_goal);
this->setPlan(path); this->setPlan(path);
this->setGoalPose(local_goal); this->setGoalPose(local_goal);
robot::log_debug(__FILE__, __LINE__, "DEBUG 2 size path: %d", (int)path.poses.size());
} }
} }
catch (const std::exception &e) catch (const std::exception &e)
@@ -585,7 +545,6 @@ bool pnkx_local_planner::PNKXDockingLocalPlanner::dockingHanlde(const robot_nav_
} }
} }
} }
} }
else else
{ {

View File

@@ -208,12 +208,14 @@ void pnkx_local_planner::PNKXLocalPlanner::reset()
void pnkx_local_planner::PNKXLocalPlanner::setGoalPose(const robot_nav_2d_msgs::Pose2DStamped &goal_pose) void pnkx_local_planner::PNKXLocalPlanner::setGoalPose(const robot_nav_2d_msgs::Pose2DStamped &goal_pose)
{ {
// boost::recursive_mutex::scoped_lock l(configuration_mutex_); // boost::recursive_mutex::scoped_lock l(configuration_mutex_);
robot::log_error("[PNKXLocalPlanner] Receive new goal(%f, %f)!", goal_pose.pose.x, goal_pose.pose.y);
reset(); reset();
goal_pose_ = goal_pose; goal_pose_ = goal_pose;
} }
void pnkx_local_planner::PNKXLocalPlanner::setPlan(const robot_nav_2d_msgs::Path2D &path) void pnkx_local_planner::PNKXLocalPlanner::setPlan(const robot_nav_2d_msgs::Path2D &path)
{ {
robot::log_error("[PNKXLocalPlanner] size path: %d", (int)path.poses.size());
// boost::recursive_mutex::scoped_lock l(configuration_mutex_); // boost::recursive_mutex::scoped_lock l(configuration_mutex_);
costmap_robot_->resetLayers(); costmap_robot_->resetLayers();
global_plan_ = path; global_plan_ = path;

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -66,6 +66,7 @@ std::string PluginLoaderHelper::findLibraryPath(const std::string& symbol_name)
} }
// Try to read from NodeHandle // Try to read from NodeHandle
std::string library_path; std::string library_path;
robot::log_info_at(__FILE__, __LINE__, "%s", symbol_name.c_str());
if (nh_.hasParam(param_path)) { if (nh_.hasParam(param_path)) {
nh_.getParam(param_path, library_path, std::string("")); nh_.getParam(param_path, library_path, std::string(""));
if (!library_path.empty()) { if (!library_path.empty()) {
@@ -343,7 +344,7 @@ std::string PluginLoaderHelper::getBuildDirectory()
std::string PluginLoaderHelper::getWorkspacePath() std::string PluginLoaderHelper::getWorkspacePath()
{ {
// Method 1: Từ environment variable PNKX_NAV_CORE_DIR // Method 1: Từ environment variable PNKX_NAV_CORE_DIR
const char* workspace_path = std::getenv("PNKX_NAV_CORE_DIR"); const char* workspace_path = std::getenv("PNKX_NAV_CORE_LIBRARY_PATH");
if (workspace_path && std::filesystem::exists(workspace_path)) { if (workspace_path && std::filesystem::exists(workspace_path)) {
return std::string(workspace_path); return std::string(workspace_path);
} }

View File

@@ -35,10 +35,9 @@ Thư viện này được thiết kế để:
- Quản lý nhiều nguồn dữ liệu với tên riêng biệt - Quản lý nhiều nguồn dữ liệu với tên riêng biệt
- **Quản lý odometry**: `addOdometry()` - cập nhật thông tin vị trí robot - **Quản lý odometry**: `addOdometry()` - cập nhật thông tin vị trí robot
- **Navigation commands**: - **Navigation commands**:
- `moveTo()` - di chuyển đến một điểm đích - `moveTo(goal, …)` - di chuyển đến một điểm đích
- `dockTo()` - docking đến marker (ví dụ: trạm sạc) - `moveTo(order, goal, …)` - một order VDA5050, được cắt thành từng chặng
- `moveStraightTo()` - di chuyển thẳng đến đích - `executeInstantActions(actions)` - một message `instantActions` của VDA5050 (0..n action)
- `rotateTo()` - quay tại chỗ đến hướng mong muốn
- **Điều khiển motion**: - **Điều khiển motion**:
- `pause()` - tạm dừng di chuyển - `pause()` - tạm dừng di chuyển
- `resume()` - tiếp tục di chuyển - `resume()` - tiếp tục di chuyển
@@ -50,6 +49,21 @@ Thư viện này được thiết kế để:
- `getFeedback()` - lấy feedback về trạng thái navigation - `getFeedback()` - lấy feedback về trạng thái navigation
- `getGlobalData()`, `getLocalData()` - lấy dữ liệu từ planner - `getGlobalData()`, `getLocalData()` - lấy dữ liệu từ planner
**Bốn entry point đã bị gỡ khỏi interface**
`dockTo()` (hai overload), `moveStraightTo()` và `rotateTo()` không còn tồn tại. Chúng đẩy goal
thẳng vào lõi navigation, bỏ qua mission layer, nên một goal đến giữa chừng lặng lẽ thay thế chặng
mà hàng đợi mission đang chạy — rồi hàng đợi vẫn giao chặng kế tiếp của một tuyến robot đã rời khỏi.
Bốn kiểu chuyển động đó **không mất**: chúng là thuộc tính của từng chặng trong order
(`profile: position | docking | go_straight | rotate`, cộng `marker` cho docking), nên đi cùng đường
với mọi chặng khác — cùng mission id, cùng vòng đời, cùng đường cancel.
Ai còn gọi bốn hàm này: `nav_c_api` đã gỡ năm export tương ứng, `nav_c_api_2` gỡ
`navigation_dock_to_order_v2`, OPC-UA gỡ ba method node `DockToNode` / `RotateTo` / `MoveStraight`.
Binding .NET nào còn khai chúng sẽ hỏng lúc **chạy** (`EntryPointNotFoundException`), không phải lúc
biên dịch.
**Đặc điểm:** **Đặc điểm:**
- Tất cả các phương thức đều là pure virtual, đảm bảo implementation đầy đủ - Tất cả các phương thức đều là pure virtual, đảm bảo implementation đầy đủ
@@ -149,7 +163,7 @@ Các hàm tiện ích hỗ trợ các thao tác phổ biến.
Các ứng dụng sử dụng navigation system: Các ứng dụng sử dụng navigation system:
- Gọi các phương thức `moveTo()`, `dockTo()`, `rotateTo()` để điều khiển robot - Gọi `moveTo()` hoặc `executeInstantActions()` để điều khiển robot
- Theo dõi `NavFeedback` để biết trạng thái navigation - Theo dõi `NavFeedback` để biết trạng thái navigation
- Sử dụng `getRobotPose()` để lấy vị trí hiện tại - Sử dụng `getRobotPose()` để lấy vị trí hiện tại
- Quản lý dữ liệu cảm biến thông qua các phương thức add/remove - Quản lý dữ liệu cảm biến thông qua các phương thức add/remove

View File

@@ -14,9 +14,11 @@
#include <robot_nav_msgs/Odometry.h> #include <robot_nav_msgs/Odometry.h>
#include <robot_nav_msgs/OccupancyGrid.h> #include <robot_nav_msgs/OccupancyGrid.h>
#include <robot_map_msgs/OccupancyGridUpdate.h> #include <robot_map_msgs/OccupancyGridUpdate.h>
#include <robot_sensor_msgs/DepthCameraData.h>
#include <robot_sensor_msgs/LaserScan.h> #include <robot_sensor_msgs/LaserScan.h>
#include <robot_sensor_msgs/PointCloud.h> #include <robot_sensor_msgs/PointCloud.h>
#include <robot_sensor_msgs/PointCloud2.h> #include <robot_sensor_msgs/PointCloud2.h>
#include <robot_protocol_msgs/Action.h>
#include <robot_protocol_msgs/Order.h> #include <robot_protocol_msgs/Order.h>
#include <robot_nav_2d_utils/conversions.h> #include <robot_nav_2d_utils/conversions.h>
@@ -174,7 +176,8 @@ namespace robot
{ {
public: public:
using Ptr = std::shared_ptr<BaseNavigation>; using Ptr = std::shared_ptr<BaseNavigation>;
robot_nav_msgs::OccupancyGrid map_save_;
std::string map_name_save_;
virtual ~BaseNavigation() {} virtual ~BaseNavigation() {}
/** /**
@@ -183,6 +186,19 @@ namespace robot
*/ */
virtual void initialize(TFListenerPtr tf) = 0; virtual void initialize(TFListenerPtr tf) = 0;
/**
* @brief Stop internal activity (control loop, planner...) before destruction.
*
* The host MUST be able to quiesce the navigation core at a chosen point in its
* own shutdown sequence, while the process is still fully alive — destroying the
* object from a static-destruction context after main() has returned is exactly
* the race that produced boost::lock_error crashes. Default is a no-op so legacy
* implementations remain source-compatible; after this call the object must stop
* producing velocity commands, and queries (getFeedback, getTwist...) must remain
* safe to call. Safe to call multiple times.
*/
virtual void shutdown() {}
/** /**
* @brief Set the robot's footprint (outline shape) in the global frame. * @brief Set the robot's footprint (outline shape) in the global frame.
* This can be used for planning or collision checking. * This can be used for planning or collision checking.
@@ -244,6 +260,14 @@ namespace robot
*/ */
virtual void addPointCloud2(const std::string &point_cloud2_name, robot_sensor_msgs::PointCloud2 point_cloud2) = 0; virtual void addPointCloud2(const std::string &point_cloud2_name, robot_sensor_msgs::PointCloud2 point_cloud2) = 0;
/**
* @brief Add one coherent depth-camera sample to the navigation system.
* @param topic The logical topic of the combined depth-camera stream.
* @param data Depth image and matching camera intrinsics.
*/
virtual void addDepthCameraData(const std::string &topic,
robot_sensor_msgs::DepthCameraData::ConstPtr data) = 0;
/** /**
* @brief Get a static map from the navigation system. * @brief Get a static map from the navigation system.
* @param map_name The name of the map. * @param map_name The name of the map.
@@ -386,49 +410,54 @@ namespace robot
double yaw_goal_tolerance = 0.0) = 0; double yaw_goal_tolerance = 0.0) = 0;
/** /**
* @brief Send a docking goal to a predefined marker (e.g. charger). * Docking, go-straight and rotate are no longer entry points of this contract.
* @param maker Marker name or ID. *
* @param goal Target pose for docking. * They used to exist as `dockTo` (two overloads), `moveStraightTo` and `rotateTo`, each
* @param xy_goal_tolerance Acceptable XY error (meters). * pushing a goal straight into the navigation core and bypassing the mission layer. That
* @param yaw_goal_tolerance Acceptable heading error (radians). * bypass had no defined preemption semantics: a goal arriving through one of them silently
* @return True if docking command succeeded. * replaced whatever leg the mission queue was running, and the queue kept handing out the
* next leg of a route the robot had already left.
*
* The motion profiles themselves are unchanged and still reachable — an order carries them
* per leg (`profile: docking | go_straight | rotate`, plus `marker` for docking), so they
* now travel the same path as every other leg: one mission id, one lifecycle, one cancel.
*/ */
virtual bool dockTo(const std::string &maker,
const robot_geometry_msgs::PoseStamped &goal,
double xy_goal_tolerance = 0.0,
double yaw_goal_tolerance = 0.0) = 0;
/** /**
* @brief Send a docking goal to a predefined marker (e.g. charger). * @brief Execute one VDA5050 `instantActions` message — a list of actions sent outside any order.
* @param msg Order message. *
* @param goal Target pose for docking. * This is the one entry point that takes bare actions. It exists because the four
* @param xy_goal_tolerance Acceptable XY error (meters). * removed above did not: it does not push anything into the core directly. The actions
* @param yaw_goal_tolerance Acceptable heading error (radians). * are handed to the mission layer, which expands each against the same compound-action
* @return True if docking command succeeded. * table that node actions use and queues the resulting legs, so an instantAction gets
* the same mission id, lifecycle and cancel path as any other work.
*
* The whole message goes down as ONE batch, in the order given. Submitting the actions
* one at a time would break as soon as a message carried two of them: the second `HARD`
* action preempts and wipes the legs of the first, so two commands sent together would
* eat each other.
*
* Execution stops at the first leg that fails, and the rest of the message is dropped
* with it (`clear_queue_on_failure`). The caller therefore reports one outcome for the
* message, not one per action.
*
* `blockingType` decides how the batch meets a running order: any `HARD` action makes
* the whole message preempt it; otherwise it queues behind it. `NONE` asks for
* execution in parallel with driving, which this runtime cannot do — it is queued
* instead, and the narrowing is logged.
*
* Lifecycle instantActions — `cancelOrder`, `startPause`, `stopPause` — must NOT come
* through here. They steer the queue rather than being work in it; the host calls
* @ref cancel, @ref pause and @ref resume for those.
*
* @param actions The actions of one `instantActions` message, in the order received.
* Must not be empty; every action needs `actionType` and `actionId`.
* @return True if the message was accepted. False means it was rejected outright — empty
* list, missing identity, or the mission layer is not running — and the caller
* must report failure rather than wait for a result that will not come.
*/ */
virtual bool dockTo(const robot_protocol_msgs::Order &msg, virtual bool executeInstantActions(
const std::string &marker, const std::vector<robot_protocol_msgs::Action> &actions) = 0;
const robot_geometry_msgs::PoseStamped &goal,
double xy_goal_tolerance = 0.0,
double yaw_goal_tolerance = 0.0) = 0;
/**
* @brief Move straight toward the target position (X-axis).
* @param goal Target pose.
* @param xy_goal_tolerance Acceptable positional error (meters).
* @return True if command issued successfully.
*/
virtual bool moveStraightTo(const robot_geometry_msgs::PoseStamped &goal,
double xy_goal_tolerance = 0.0) = 0;
/**
* @brief Rotate in place to align with target orientation.
* @param goal Pose containing desired heading (only Z-axis used).
* @param yaw_goal_tolerance Acceptable angular error (radians).
* @return True if rotation command was sent successfully.
*/
virtual bool rotateTo(const robot_geometry_msgs::PoseStamped &goal,
double yaw_goal_tolerance = 0.0) = 0;
/** /**
* @brief Pause the robot's movement (e.g. during obstacle avoidance). * @brief Pause the robot's movement (e.g. during obstacle avoidance).

View File

@@ -146,7 +146,7 @@ namespace robot_nav_core
* @brief Gets the current global plan * @brief Gets the current global plan
* @param path The global plan * @param path The global plan
*/ */
virtual void getGlobalPlan(std::vector<robot_geometry_msgs::PoseStamped> &path) {return;} virtual void getGlobalPlan(std::vector<robot_geometry_msgs::PoseStamped> &path) = 0;
/** /**
* @brief Constructs the local planner * @brief Constructs the local planner

View File

@@ -36,6 +36,7 @@
#include <robot_nav_core2/common.h> #include <robot_nav_core2/common.h>
#include <robot_nav_core2/costmap.h> #include <robot_nav_core2/costmap.h>
#include <robot_nav_core2/exceptions.h>
#include <robot_nav_2d_msgs/Path2D.h> #include <robot_nav_2d_msgs/Path2D.h>
#include <robot_nav_2d_msgs/Pose2DStamped.h> #include <robot_nav_2d_msgs/Pose2DStamped.h>
#include <string> #include <string>

View File

@@ -36,6 +36,7 @@
#include <robot_nav_core2/common.h> #include <robot_nav_core2/common.h>
#include <robot_nav_core2/costmap.h> #include <robot_nav_core2/costmap.h>
#include <robot_nav_core2/exceptions.h>
#include <robot_nav_2d_msgs/Path2D.h> #include <robot_nav_2d_msgs/Path2D.h>
#include <robot_nav_2d_msgs/Pose2DStamped.h> #include <robot_nav_2d_msgs/Pose2DStamped.h>
#include <robot_nav_2d_msgs/Twist2D.h> #include <robot_nav_2d_msgs/Twist2D.h>
@@ -103,7 +104,7 @@ namespace robot_nav_core2
* @brief Gets the current global plan * @brief Gets the current global plan
* @param path The global plan * @param path The global plan
*/ */
virtual void getGlobalPlan(robot_nav_2d_msgs::Path2D &path) {return;} virtual void getGlobalPlan(robot_nav_2d_msgs::Path2D &path) = 0;
/** /**
* @brief Compute the best command given the current pose, velocity and goal * @brief Compute the best command given the current pose, velocity and goal

View File

@@ -134,11 +134,17 @@ endif()
# ======================================================== # ========================================================
# Test executables # Test executables
# ======================================================== # ========================================================
if(GTest_FOUND OR GTEST_FOUND) # Tests are a development-machine concern: a catkin workspace is where they run,
# while the standalone CMake build is the robot deployment path and must not
# produce test executables. Force with -DBUILD_NAV_GRID_TESTS=ON to build them
# from a standalone build.
option(BUILD_NAV_GRID_TESTS "Build the nav_grid unit tests" ${BUILDING_WITH_CATKIN})
if(BUILD_NAV_GRID_TESTS AND (GTest_FOUND OR GTEST_FOUND))
enable_testing() enable_testing()
find_package(Threads REQUIRED) find_package(Threads REQUIRED)
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/utest.cpp) if(BUILD_NAV_GRID_TESTS AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/test/utest.cpp)
add_executable(${PROJECT_NAME}_test test/utest.cpp) add_executable(${PROJECT_NAME}_test test/utest.cpp)
target_link_libraries(${PROJECT_NAME}_test PRIVATE target_link_libraries(${PROJECT_NAME}_test PRIVATE
${PROJECT_NAME} ${PROJECT_NAME}

View File

@@ -1,142 +0,0 @@
# Move Base - Dual Build System Support
Package `move_base` có thể được build bằng cả **Catkin** và **Standalone CMake**.
## Cách Build
### 1. Build với Catkin (ROS Workspace)
**⚠️ QUAN TRỌNG**: Thư mục gốc của project (`pnkx_robot_nav_core`) có `CMakeLists.txt` ở root,
nên **KHÔNG THỂ** chạy `catkin_make` trực tiếp trong thư mục đó. Catkin workspace không được
phép có `CMakeLists.txt` ở root.
**Giải pháp**: Tạo một catkin workspace riêng và link packages vào đó.
#### Cách 1: Sử dụng script tự động (Khuyến nghị)
```bash
# Chạy script setup từ thư mục gốc của project
cd /home/robotics/AGV/Diff_Wheel_Prj/pnkx_robot_nav_core
./setup_catkin_workspace.sh
# Script sẽ tạo workspace và link các packages có package.xml
# Sau đó build:
cd ../pnkx_nav_catkin_ws
catkin_make
source devel/setup.bash
```
#### Cách 2: Tạo workspace thủ công
```bash
# Tạo catkin workspace
mkdir -p ~/pnkx_nav_catkin_ws/src
cd ~/pnkx_nav_catkin_ws/src
# Link package move_base vào workspace
ln -s /home/robotics/AGV/Diff_Wheel_Prj/pnkx_robot_nav_core/src/Navigations/Packages/move_base move_base
# Link các dependencies cần thiết (nếu có package.xml)
ln -s /home/robotics/AGV/Diff_Wheel_Prj/pnkx_robot_nav_core/src/Libraries/tf3 tf3
ln -s /home/robotics/AGV/Diff_Wheel_Prj/pnkx_robot_nav_core/src/Libraries/nav_2d_utils nav_2d_utils
# Build với catkin
cd ~/pnkx_nav_catkin_ws
catkin_make
source devel/setup.bash
```
**Lưu ý**: Khi build với catkin, package sẽ tự động detect và sử dụng:
- `catkin_package()` để export dependencies
- Catkin installation paths
- ROS message dependencies
### 2. Build với Standalone CMake
```bash
cd /path/to/move_base
mkdir -p build
cd build
cmake ..
make
```
**Lưu ý**: Khi build standalone, bạn cần đảm bảo:
- Tất cả dependencies đã được build trước
- CMake có thể tìm thấy các internal packages (move_base_core, robot_nav_core, etc.)
- ROS packages (nếu cần) được cài đặt và có trong CMAKE_PREFIX_PATH
## Cách CMakeLists.txt Detect Build Mode
CMakeLists.txt tự động detect build mode bằng cách kiểm tra:
- `CATKIN_DEVEL_PREFIX` - biến môi trường của catkin
- `CATKIN_TOPLEVEL` - biến môi trường của catkin
Nếu một trong hai biến này được định nghĩa, package sẽ build ở **Catkin mode**.
Ngược lại, sẽ build ở **Standalone CMake mode**.
## Dependencies
### ROS Packages (khi build với Catkin):
- roscpp, rospy
- robot_std_msgs, geometry_msgs, robot_nav_msgs
- tf2, tf2_ros
- actionlib, dynamic_reconfigure
### Internal Packages (cần build trước):
- move_base_core
- robot_nav_core
- robot_costmap_2d
- xmlrpcpp
- node_handle
- robot_tf3_sensor_msgs
- robot_tf3_geometry_msgs
### System Libraries:
- Boost
- yaml-cpp
- pthread, dl
## Kiểm tra Build Mode
Khi chạy `cmake`, bạn sẽ thấy message:
```
Building move_base with Catkin
```
hoặc
```
Building move_base with Standalone CMake
```
## Troubleshooting
### Lỗi: "catkin_make must be invoked in the root of workspace"
**Nguyên nhân**: Thư mục hiện tại có `CMakeLists.txt` ở root, catkin không cho phép điều này.
**Giải pháp**:
- Tạo catkin workspace riêng (xem hướng dẫn ở trên)
- Hoặc đổi tên/ẩn `CMakeLists.txt` ở root khi build với catkin (không khuyến nghị)
### Lỗi: "Cannot find package X"
- **Với Catkin**:
- Đảm bảo package X đã được build trong cùng workspace
- Đảm bảo package X có `package.xml` và được link vào `src/` của workspace
- Kiểm tra dependencies trong `package.xml`
- **Với Standalone**:
- Đảm bảo package X đã được build và cài đặt
- Thêm vào `CMAKE_PREFIX_PATH` nếu cần
### Lỗi: "catkin_package() not found"
- Đảm bảo bạn đang build trong catkin workspace (không phải thư mục gốc có CMakeLists.txt)
- Kiểm tra `CATKIN_DEVEL_PREFIX` có được set không
- Source ROS setup: `source /opt/ros/noetic/setup.bash`
### Lỗi: "Cannot find ROS packages"
- Cài đặt ROS Noetic: `sudo apt-get install ros-noetic-<package-name>`
- Source ROS setup: `source /opt/ros/noetic/setup.bash`
- Kiểm tra `ROS_PACKAGE_PATH` environment variable
### Lỗi: Internal packages không tìm thấy (move_base_core, robot_nav_core, etc.)
- **Với Catkin**: Các internal packages cần có `package.xml` và được link vào workspace
- **Với Standalone**: Đảm bảo các packages đã được build trước trong project chính

View File

@@ -1,226 +0,0 @@
cmake_minimum_required(VERSION 3.0.2)
project(move_base VERSION 1.0.0 LANGUAGES CXX)
if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL)
set(BUILDING_WITH_CATKIN TRUE)
message(STATUS "Building move_base with Catkin")
else()
set(BUILDING_WITH_CATKIN FALSE)
message(STATUS "Building move_base with Standalone CMake")
endif()
# C++ Standard - must be set before find_package
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# Find dependencies
find_package(Boost REQUIRED COMPONENTS filesystem system)
find_package(Threads REQUIRED)
find_package(yaml-cpp REQUIRED)
find_package(console_bridge REQUIRED)
if (NOT BUILDING_WITH_CATKIN)
# Enable Position Independent Code
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
# Cấu hình RPATH để tránh cycle trong runtime search path
set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}")
set(PACKAGES_DIR
geometry_msgs
robot_std_msgs
move_base_core
robot_nav_core
robot_costmap_2d
plugins
tf3
robot_tf3_sensor_msgs
robot_tf3_geometry_msgs
data_convert
robot_nav_2d_utils
robot_cpp
robot_move_base_msgs
laser_filter
)
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
else()
# ========================================================
# Catkin specific configuration
# ========================================================
find_package(catkin REQUIRED COMPONENTS
geometry_msgs
robot_std_msgs
move_base_core
robot_nav_core
robot_costmap_2d
robot_tf3_sensor_msgs
robot_tf3_geometry_msgs
data_convert
robot_nav_2d_utils
robot_cpp
robot_move_base_msgs
)
find_library(TF3_LIBRARY NAMES tf3 PATHS /usr/lib /usr/local/lib /usr/lib/x86_64-linux-gnu)
catkin_package(
INCLUDE_DIRS include
LIBRARIES ${PROJECT_NAME}
CATKIN_DEPENDS geometry_msgs robot_std_msgs move_base_core robot_nav_core robot_costmap_2d robot_tf3_sensor_msgs robot_tf3_geometry_msgs data_convert robot_nav_2d_utils robot_cpp robot_move_base_msgs
DEPENDS Boost yaml-cpp
)
include_directories(
include
${catkin_INCLUDE_DIRS}
${Boost_INCLUDE_DIRS}
${TF3_INCLUDE_DIR}
)
endif()
# ========================================================
# Libraries
# ========================================================
add_library(${PROJECT_NAME} SHARED
src/move_base.cpp
src/convert_data.cpp
src/simple_action_server.cpp
)
if(BUILDING_WITH_CATKIN)
add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_compile_definitions(${PROJECT_NAME}
PUBLIC BUILD_WITH_ROS
)
target_include_directories(${PROJECT_NAME}
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
${TF3_INCLUDE_DIR}
)
target_link_libraries(${PROJECT_NAME}
PUBLIC ${catkin_LIBRARIES}
PRIVATE Boost::filesystem Boost::system
dl
${TF3_LIBRARY}
${console_bridge_LIBRARIES}
)
else()
target_include_directories(${PROJECT_NAME}
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
${TF3_INCLUDE_DIR}
)
target_link_libraries(${PROJECT_NAME}
PUBLIC
${PACKAGES_DIR}
${TF3_LIBRARY}
${console_bridge_LIBRARIES}
PRIVATE
Boost::filesystem Boost::system
yaml-cpp
dl
)
set_target_properties(${PROJECT_NAME} PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
BUILD_RPATH "${CMAKE_BINARY_DIR}"
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
)
endif()
# ========================================================
# Executable
# ========================================================
add_executable(${PROJECT_NAME}_main src/move_base_main.cpp)
if(BUILDING_WITH_CATKIN)
target_link_libraries(${PROJECT_NAME}_main PRIVATE
${PROJECT_NAME}
robot_cpp
Boost::filesystem Boost::system
dl
${TF3_LIBRARY}
${console_bridge_LIBRARIES}
)
else()
target_link_libraries(${PROJECT_NAME}_main PRIVATE
${PROJECT_NAME}
robot_cpp
Boost::filesystem Boost::system
dl
${TF3_LIBRARY}
${console_bridge_LIBRARIES}
)
# Configure RPATH to find libraries in devel space
set_target_properties(${PROJECT_NAME}_main PROPERTIES
BUILD_WITH_INSTALL_RPATH FALSE
INSTALL_RPATH_USE_LINK_PATH TRUE
BUILD_RPATH "${CMAKE_BINARY_DIR}"
)
endif()
# ========================================================
# Install
# ========================================================
if(BUILDING_WITH_CATKIN)
## Mark libraries for installation
## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_main
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
)
## Mark cpp header files for installation
install(DIRECTORY include/${PROJECT_NAME}/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
FILES_MATCHING PATTERN "*.h"
PATTERN ".svn" EXCLUDE
)
else()
install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_main
EXPORT ${PROJECT_NAME}-targets
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
RUNTIME DESTINATION bin
)
# Export targets
install(EXPORT ${PROJECT_NAME}-targets
FILE ${PROJECT_NAME}-targets.cmake
NAMESPACE ${PROJECT_NAME}::
DESTINATION lib/cmake/${PROJECT_NAME}
)
## Mark cpp header files for installation
install(DIRECTORY include/${PROJECT_NAME}/
DESTINATION include
FILES_MATCHING PATTERN "*.h"
PATTERN ".svn" EXCLUDE
)
# Print configuration info
message(STATUS "=================================")
message(STATUS "Project: ${PROJECT_NAME}")
message(STATUS "Version: ${PROJECT_VERSION}")
message(STATUS "C++ Standard: ${CMAKE_CXX_STANDARD}")
message(STATUS "Libraries: ${PROJECT_NAME}")
message(STATUS "Executables: ${PROJECT_NAME}_main")
message(STATUS "Dependencies: geometry_msgs, robot_std_msgs, move_base_core, robot_nav_core, robot_costmap_2d, robot_tf3_sensor_msgs, robot_tf3_geometry_msgs, data_convert, robot_nav_2d_utils, robot_cpp, robot_move_base_msgs, Boost, yaml-cpp")
message(STATUS "=================================")
endif()

View File

@@ -1,265 +0,0 @@
# Hướng dẫn triển khai SimpleActionServer trong MoveBase
## Tổng quan
Tài liệu này hướng dẫn cách tích hợp `SimpleActionServer` vào class `MoveBase` hiện có.
## Bước 1: Thêm SimpleActionServer vào MoveBase class
### Trong `move_base.h`:
```cpp
#include <move_base/simple_action_server.h>
namespace move_base
{
class MoveBase : public robot::move_base_core::BaseNavigation
{
private:
// Thêm member variable
std::shared_ptr<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>> as_;
// Thêm method declaration
void executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr& goal);
};
}
```
## Bước 2: Khởi tạo trong constructor hoặc initialize()
### Trong `move_base.cpp` constructor hoặc `initialize()`:
```cpp
void move_base::MoveBase::initialize(robot::TFListenerPtr tf)
{
// ... existing initialization code ...
// Khởi tạo action server
as_ = std::make_shared<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>>(
"move_base",
std::bind(&MoveBase::executeCb, this, std::placeholders::_1),
true // auto_start
);
// Setup callbacks (optional)
setupActionServerCallbacks();
robot::log_info("[MoveBase] Action server initialized");
}
```
## Bước 3: Setup callbacks (nếu cần publish messages)
```cpp
void move_base::MoveBase::setupActionServerCallbacks()
{
if (!as_)
return;
// Set callback để publish result
// Customize để gửi qua hệ thống communication của bạn
as_->setResultCallback([](const auto& result) {
// TODO: Gửi result qua hệ thống communication của bạn
// your_communication_system.send(result);
robot::log_info("Result: status=%d", result->status.status);
});
// Set callback để publish feedback
as_->setFeedbackCallback([](const auto& feedback) {
// TODO: Gửi feedback qua hệ thống communication của bạn
// your_communication_system.send(feedback);
});
// Set callback để publish status
as_->setStatusCallback([](const auto& status) {
// TODO: Gửi status qua hệ thống communication của bạn
// your_communication_system.send(status);
});
}
```
## Bước 4: Triển khai executeCb()
### Trong `move_base.cpp`:
```cpp
void move_base::MoveBase::executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr& goal)
{
robot::log_info("[MoveBase] Execute callback: x=%.2f, y=%.2f",
goal->target_pose.pose.position.x,
goal->target_pose.pose.position.y);
// Validate quaternion
if (!isQuaternionValid(goal->target_pose.pose.orientation))
{
robot::log_error("[MoveBase] Invalid quaternion in goal");
as_->setAborted(robot_move_base_msgs::MoveBaseResult(),
"Invalid quaternion in goal");
return;
}
// Convert goal to global frame
robot_geometry_msgs::PoseStamped target_pose = goalToGlobalFrame(goal->target_pose);
// Send goal to move_base
bool success = moveTo(target_pose, 0.2, 0.2);
if (!success)
{
robot::log_error("[MoveBase] Failed to send goal");
as_->setAborted(robot_move_base_msgs::MoveBaseResult(),
"Failed to send goal to move_base");
return;
}
// Monitor execution
robot::Rate rate(10.0);
robot::Time last_feedback_time = robot::Time::now();
while (as_->isActive() && !as_->isPreemptRequested())
{
// Get feedback
robot::move_base_core::NavFeedback* feedback = getFeedback();
if (feedback)
{
// Check if goal reached
if (feedback->goal_checked &&
feedback->navigation_state == robot::move_base_core::State::SUCCEEDED)
{
as_->setSucceeded(robot_move_base_msgs::MoveBaseResult(),
"Goal reached");
return;
}
// Check for errors
if (feedback->navigation_state == robot::move_base_core::State::ABORTED)
{
as_->setAborted(robot_move_base_msgs::MoveBaseResult(),
feedback->feed_back_str);
return;
}
// Publish feedback periodically
robot::Time now = robot::Time::now();
if ((now - last_feedback_time).toSec() >= 0.5)
{
robot_move_base_msgs::MoveBaseFeedback fb;
fb.base_position.x = feedback->current_pose.x;
fb.base_position.y = feedback->current_pose.y;
fb.base_position.theta = feedback->current_pose.theta;
fb.base_position.header.stamp = robot::Time::now();
fb.base_position.header.frame_id = global_frame_;
as_->publishFeedback(fb);
last_feedback_time = now;
}
}
// Check for preemption
if (as_->isPreemptRequested())
{
cancel();
as_->setPreempted(robot_move_base_msgs::MoveBaseResult(),
"Preempted");
return;
}
rate.sleep();
}
// Handle unexpected exit
if (as_->isPreemptRequested())
{
cancel();
as_->setPreempted(robot_move_base_msgs::MoveBaseResult(), "Preempted");
}
else
{
as_->setAborted(robot_move_base_msgs::MoveBaseResult(),
"Execution ended unexpectedly");
}
}
```
## Bước 5: Xử lý goal và cancel messages từ bên ngoài
Nhận goal và cancel messages từ hệ thống communication của bạn:
```cpp
// Trong callback nhận goal từ hệ thống communication của bạn
void move_base::MoveBase::goalCallback(
const robot_move_base_msgs::MoveBaseActionGoalConstPtr& msg)
{
if (as_)
{
as_->processGoal(msg);
}
}
// Trong callback nhận cancel từ hệ thống communication của bạn
void move_base::MoveBase::cancelCallback(
const robot_actionlib_msgs::GoalIDConstPtr& msg)
{
if (as_)
{
as_->processCancel(msg);
}
}
// Ví dụ: Đăng ký với hệ thống communication của bạn
// your_communication_system.onGoal(
// std::bind(&MoveBase::goalCallback, this, std::placeholders::_1));
// your_communication_system.onCancel(
// std::bind(&MoveBase::cancelCallback, this, std::placeholders::_1));
```
## Bước 6: Cleanup trong destructor
```cpp
move_base::MoveBase::~MoveBase()
{
// ... existing cleanup ...
// Stop action server
if (as_)
{
as_->stop();
as_.reset();
}
}
```
## Ví dụ hoàn chỉnh
Xem các file trong thư mục `examples/`:
- `simple_usage_example.cpp` - Ví dụ đơn giản nhất
- `simple_action_server_example.cpp` - Ví dụ đầy đủ
- `move_base_with_action_server_example.cpp` - Ví dụ tích hợp vào MoveBase
## Lưu ý
1. **Thread Safety**: `executeCb` chạy trong thread riêng, đảm bảo thread-safe khi truy cập các member variables
2. **State Management**: Action server tự động quản lý state, không cần can thiệp thủ công
3. **Feedback Rate**: Điều chỉnh rate publish feedback phù hợp (khuyến nghị 0.5-1.0 giây)
4. **Error Handling**: Luôn kiểm tra và xử lý các trường hợp lỗi
## Testing
Để test action server:
```cpp
// Tạo goal message
robot_move_base_msgs::MoveBaseActionGoalPtr goal =
boost::make_shared<robot_move_base_msgs::MoveBaseActionGoal>();
goal->goal_id.id = "test_goal_1";
goal->goal.target_pose.pose.position.x = 5.0;
goal->goal.target_pose.pose.position.y = 3.0;
// Gửi goal
move_base_ptr->getActionServer()->processGoal(goal);
// Kiểm tra status
auto status = move_base_ptr->getActionServer()->getCurrentStatus();
```

View File

@@ -1,220 +0,0 @@
# SimpleActionServer - Hướng dẫn sử dụng
## Tổng quan
`SimpleActionServer` là một thư viện tương tự ROS actionlib::SimpleActionServer nhưng không phụ thuộc vào ROS. Nó cung cấp interface đơn giản để triển khai action server với các tính năng:
- Quản lý goal requests
- Hỗ trợ preemption (hủy goal)
- Publish feedback và result thông qua callbacks
- Thread-safe và thread-safe state management
- Tương thích với framework robot hiện có
## Cấu trúc Files
- `simple_action_server.h` - Header file với class declaration
- `simple_action_server.cpp` - Implementation file với template code
- `simple_action_server_example.cpp` - Ví dụ triển khai đầy đủ
## Ví dụ sử dụng cơ bản
### 1. Khởi tạo SimpleActionServer
```cpp
#include <move_base/simple_action_server.h>
// Tạo action server với execute callback
auto action_server = std::make_shared<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>>(
"move_base",
[this](const auto& goal) { this->executeCb(goal); },
true // auto_start
);
```
### 2. Setup callbacks để publish messages
```cpp
// Set callback để publish result
action_server->setResultCallback([](const auto& result) {
// Publish result message qua ROS hoặc hệ thống khác
result_pub_.publish(*result);
});
// Set callback để publish feedback
action_server->setFeedbackCallback([](const auto& feedback) {
// Publish feedback message
feedback_pub_.publish(*feedback);
});
// Set callback để publish status
action_server->setStatusCallback([](const auto& status) {
// Publish status message
status_pub_.publish(*status);
});
```
### 3. Xử lý goal messages từ bên ngoài
```cpp
// Trong ROS subscriber callback hoặc nơi nhận goal
void goalCallback(const robot_move_base_msgs::MoveBaseActionGoalConstPtr& msg)
{
action_server->processGoal(msg);
}
// Trong cancel callback
void cancelCallback(const robot_actionlib_msgs::GoalIDConstPtr& msg)
{
action_server->processCancel(msg);
}
```
### 4. Triển khai execute callback
```cpp
void executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr& goal)
{
robot::log_info("Received goal: x=%.2f, y=%.2f",
goal->target_pose.pose.position.x,
goal->target_pose.pose.position.y);
// Gửi goal đến move_base
bool success = move_base_ptr_->moveTo(goal->target_pose, 0.2, 0.2);
if (!success)
{
action_server_->setAborted(robot_move_base_msgs::MoveBaseResult(),
"Failed to send goal");
return;
}
// Monitor execution
robot::Rate rate(10.0);
while (action_server_->isActive() && !action_server_->isPreemptRequested())
{
// Kiểm tra trạng thái
auto* feedback = move_base_ptr_->getFeedback();
if (feedback->goal_checked &&
feedback->navigation_state == robot::move_base_core::State::SUCCEEDED)
{
action_server_->setSucceeded(robot_move_base_msgs::MoveBaseResult(),
"Goal reached");
return;
}
// Publish feedback
robot_move_base_msgs::MoveBaseFeedback fb;
fb.base_position.x = feedback->current_pose.x;
fb.base_position.y = feedback->current_pose.y;
action_server_->publishFeedback(fb);
rate.sleep();
}
// Xử lý preemption
if (action_server_->isPreemptRequested())
{
move_base_ptr_->cancel();
action_server_->setPreempted(robot_move_base_msgs::MoveBaseResult(),
"Preempted");
}
}
```
## Tích hợp vào MoveBase
### Cách 1: Thêm vào MoveBase class
```cpp
// Trong move_base.h
#include <move_base/simple_action_server.h>
class MoveBase : public robot::move_base_core::BaseNavigation
{
private:
std::shared_ptr<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>> as_;
void executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr& goal);
};
```
```cpp
// Trong move_base.cpp constructor
MoveBase::MoveBase(robot::TFListenerPtr tf)
{
// ... existing initialization ...
// Create action server
as_ = std::make_shared<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>>(
"move_base",
std::bind(&MoveBase::executeCb, this, std::placeholders::_1),
true
);
// Setup callbacks
as_->setResultCallback([this](const auto& result) {
// Publish result if needed
});
}
```
### Cách 2: Sử dụng trong wrapper class
Xem file `simple_action_server_example.cpp` để xem ví dụ đầy đủ.
## API Reference
### Constructor
```cpp
SimpleActionServer(const std::string& name,
ExecuteCallback execute_callback,
bool auto_start = true)
```
### Main Methods
- `void processGoal(const ActionGoalConstPtr& goal_msg)` - Xử lý goal message
- `void processCancel(const GoalIDConstPtr& cancel_msg)` - Xử lý cancel message
- `GoalConstPtr acceptNewGoal()` - Chấp nhận goal mới
- `bool isNewGoalAvailable()` - Kiểm tra có goal mới
- `bool isPreemptRequested()` - Kiểm tra preemption
- `void setSucceeded(const Result&, const std::string&)` - Đặt thành công
- `void setAborted(const Result&, const std::string&)` - Đặt lỗi
- `void setPreempted(const Result&, const std::string&)` - Đặt preempted
- `void publishFeedback(const Feedback&)` - Publish feedback
### Callback Setup
- `void setGoalCallback(GoalCallback)` - Callback khi nhận goal
- `void setCancelCallback(CancelCallback)` - Callback khi nhận cancel
- `void setFeedbackCallback(FeedbackCallback)` - Callback để publish feedback
- `void setResultCallback(ResultCallback)` - Callback để publish result
- `void setStatusCallback(StatusCallback)` - Callback để publish status
## Lưu ý
1. **Thread Safety**: Tất cả các phương thức đều thread-safe
2. **Callbacks**: Các callbacks được gọi trong context của thread tương ứng
3. **State Management**: Action server tự động quản lý state machine
4. **No ROS Dependency**: Không cần ROS, chỉ cần setup callbacks để publish messages
## Tích hợp với hệ thống communication khác
SimpleActionServer không phụ thuộc vào ROS. Bạn có thể tích hợp với bất kỳ hệ thống communication nào bằng cách setup callbacks:
```cpp
// Setup callbacks để publish messages qua hệ thống của bạn
action_server->setResultCallback([](const auto& result) {
// Gửi result qua hệ thống communication của bạn
// your_communication_system.send(result);
});
action_server->setFeedbackCallback([](const auto& feedback) {
// Gửi feedback qua hệ thống communication của bạn
// your_communication_system.send(feedback);
});
// Nhận goal messages từ hệ thống của bạn
// your_communication_system.onGoal([&action_server](const auto& msg) {
// action_server->processGoal(msg);
// });
```

View File

@@ -1,343 +0,0 @@
/**
* @file simple_action_server_example.cpp
* @brief Example implementation of SimpleActionServer for MoveBaseAction
*
* This example demonstrates how to use SimpleActionServer to implement
* an action server without ROS dependency. It shows:
* - How to initialize the action server
* - How to set up callbacks for publishing messages
* - How to handle goal execution
* - How to publish feedback and results
*/
#include <move_base/simple_action_server.h>
#include <move_base/move_base.h>
// Message types
#include <robot_move_base_msgs/MoveBaseActionGoal.h>
#include <robot_move_base_msgs/MoveBaseActionResult.h>
#include <robot_move_base_msgs/MoveBaseActionFeedback.h>
#include <robot_actionlib_msgs/GoalID.h>
#include <robot_actionlib_msgs/GoalStatusArray.h>
#include <robot/robot.h>
#include <memory>
#include <thread>
#include <chrono>
namespace move_base
{
/**
* @class MoveBaseActionServerExample
* @brief Example class demonstrating SimpleActionServer usage
*/
class MoveBaseActionServerExample
{
public:
MoveBaseActionServerExample()
: move_base_ptr_(nullptr)
{
// Initialize move_base (your existing navigation system)
// move_base_ptr_ = std::make_shared<MoveBase>(tf_);
// Create SimpleActionServer with execute callback
action_server_ = std::make_shared<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>>(
"move_base",
std::bind(&MoveBaseActionServerExample::executeCb, this, std::placeholders::_1),
true // auto_start
);
// Set up callbacks for publishing messages
setupCallbacks();
robot::log_info("[MoveBaseActionServerExample] Initialized");
}
~MoveBaseActionServerExample()
{
if (action_server_)
{
action_server_->stop();
}
}
/**
* @brief Setup callbacks for SimpleActionServer
* You can customize these callbacks to publish messages to your communication system
*/
void setupCallbacks()
{
if (!action_server_)
return;
// Set callback for result publishing
// Customize this to send result to your communication system
action_server_->setResultCallback(
[this](const robot_move_base_msgs::MoveBaseActionResultConstPtr& result)
{
// TODO: Publish result to your communication system (e.g., custom message bus, network, etc.)
robot::log_info("[MoveBaseActionServerExample] Result: status=%d, text=%s",
result->status.status, result->status.text.c_str());
}
);
// Set callback for feedback publishing
// Customize this to send feedback to your communication system
action_server_->setFeedbackCallback(
[this](const robot_move_base_msgs::MoveBaseActionFeedbackConstPtr& feedback)
{
// TODO: Publish feedback to your communication system
robot::log_debug("[MoveBaseActionServerExample] Published feedback");
}
);
// Set callback for status publishing
// Customize this to send status to your communication system
action_server_->setStatusCallback(
[this](const robot_actionlib_msgs::GoalStatusArrayConstPtr& status)
{
// TODO: Publish status to your communication system
}
);
// Set callback for goal messages (optional - for logging)
action_server_->setGoalCallback(
[this](const robot_move_base_msgs::MoveBaseActionGoalConstPtr& goal)
{
robot::log_info("[MoveBaseActionServerExample] Goal callback: x=%.2f, y=%.2f",
goal->goal.target_pose.pose.position.x,
goal->goal.target_pose.pose.position.y);
}
);
// Set callback for cancel messages (optional - for logging)
action_server_->setCancelCallback(
[this](const robot_actionlib_msgs::GoalIDConstPtr& cancel)
{
robot::log_info("[MoveBaseActionServerExample] Cancel callback: id=%s", cancel->id.c_str());
}
);
// Set status publish rate (default is 10 Hz)
action_server_->setStatusPublishRate(10.0);
robot::log_info("[MoveBaseActionServerExample] Callbacks setup complete");
}
/**
* @brief Process goal message from external source
* Call this when you receive a goal message from your communication system
*/
void processGoalMessage(const robot_move_base_msgs::MoveBaseActionGoalConstPtr& msg)
{
if (action_server_)
{
action_server_->processGoal(msg);
}
}
/**
* @brief Process cancel message from external source
* Call this when you receive a cancel message from your communication system
*/
void processCancelMessage(const robot_actionlib_msgs::GoalIDConstPtr& msg)
{
if (action_server_)
{
action_server_->processCancel(msg);
}
}
/**
* @brief Execute callback - called when a new goal is received
* This is the main function that processes the goal
*/
void executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr& goal)
{
robot::log_info("[MoveBaseActionServerExample] Execute callback started");
robot::log_info(" Goal: x=%.2f, y=%.2f, frame_id=%s",
goal->target_pose.pose.position.x,
goal->target_pose.pose.position.y,
goal->target_pose.header.frame_id.c_str());
// Check if we have a valid move_base instance
if (!move_base_ptr_)
{
robot::log_error("[MoveBaseActionServerExample] move_base_ptr_ is null, aborting goal");
action_server_->setAborted(robot_move_base_msgs::MoveBaseResult(),
"MoveBase not initialized");
return;
}
// Convert goal to PoseStamped
robot_geometry_msgs::PoseStamped target_pose = goal->target_pose;
// Send goal to move_base
bool success = move_base_ptr_->moveTo(target_pose, 0.2, 0.2);
if (!success)
{
robot::log_error("[MoveBaseActionServerExample] Failed to send goal to move_base");
action_server_->setAborted(robot_move_base_msgs::MoveBaseResult(),
"Failed to send goal to move_base");
return;
}
// Monitor execution and publish feedback
robot::Rate rate(10.0); // 10 Hz
robot::Time start_time = robot::Time::now();
robot::Time last_feedback_time = start_time;
while (action_server_->isActive() && !action_server_->isPreemptRequested())
{
// Check if goal is reached
if (move_base_ptr_->getFeedback())
{
auto* feedback_ptr = move_base_ptr_->getFeedback();
if (feedback_ptr->goal_checked &&
feedback_ptr->navigation_state == robot::move_base_core::State::SUCCEEDED)
{
robot::log_info("[MoveBaseActionServerExample] Goal reached!");
action_server_->setSucceeded(robot_move_base_msgs::MoveBaseResult(),
"Goal reached successfully");
return;
}
// Check for errors
if (feedback_ptr->navigation_state == robot::move_base_core::State::ABORTED)
{
robot::log_error("[MoveBaseActionServerExample] Navigation aborted: %s",
feedback_ptr->feed_back_str.c_str());
action_server_->setAborted(robot_move_base_msgs::MoveBaseResult(),
feedback_ptr->feed_back_str);
return;
}
// Publish feedback periodically (every 0.5 seconds)
robot::Time now = robot::Time::now();
if ((now - last_feedback_time).toSec() >= 0.5)
{
robot_move_base_msgs::MoveBaseFeedback feedback;
feedback.base_position.x = feedback_ptr->current_pose.x;
feedback.base_position.y = feedback_ptr->current_pose.y;
feedback.base_position.theta = feedback_ptr->current_pose.theta;
feedback.base_position.header.stamp = robot::Time::now();
feedback.base_position.header.frame_id = "map";
action_server_->publishFeedback(feedback);
last_feedback_time = now;
}
}
// Check for preemption
if (action_server_->isPreemptRequested())
{
robot::log_info("[MoveBaseActionServerExample] Goal preempted");
move_base_ptr_->cancel();
action_server_->setPreempted(robot_move_base_msgs::MoveBaseResult(),
"Goal preempted by user");
return;
}
// Sleep
rate.sleep();
}
// If we exit the loop without success, check why
if (action_server_->isPreemptRequested())
{
robot::log_info("[MoveBaseActionServerExample] Goal was preempted");
move_base_ptr_->cancel();
action_server_->setPreempted(robot_move_base_msgs::MoveBaseResult(),
"Goal preempted");
}
else
{
robot::log_warning("[MoveBaseActionServerExample] Goal execution ended unexpectedly");
action_server_->setAborted(robot_move_base_msgs::MoveBaseResult(),
"Goal execution ended unexpectedly");
}
}
/**
* @brief Get the action server instance
*/
std::shared_ptr<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>> getActionServer()
{
return action_server_;
}
/**
* @brief Set move_base instance
*/
void setMoveBase(robot::move_base_core::BaseNavigation::Ptr move_base)
{
move_base_ptr_ = move_base;
}
private:
// Action server
std::shared_ptr<SimpleActionServer<robot_move_base_msgs::MoveBaseAction>> action_server_;
// Move base instance
robot::move_base_core::BaseNavigation::Ptr move_base_ptr_;
};
} // namespace move_base
/**
* @brief Example main function showing how to use MoveBaseActionServerExample
*/
int main()
{
try
{
// Create example instance
move_base::MoveBaseActionServerExample example;
// If you have a move_base instance, set it
// example.setMoveBase(move_base_ptr);
robot::log_info("[Example] Action server is running. Waiting for goals...");
// Example: Create and send a goal message
// In real usage, you would receive this from your communication system
robot_move_base_msgs::MoveBaseActionGoalPtr goal_msg =
boost::make_shared<robot_move_base_msgs::MoveBaseActionGoal>();
goal_msg->header.stamp = robot::Time::now();
goal_msg->header.frame_id = "map";
goal_msg->goal_id.stamp = robot::Time::now();
goal_msg->goal_id.id = "example_goal_1";
goal_msg->goal.target_pose.header.stamp = robot::Time::now();
goal_msg->goal.target_pose.header.frame_id = "map";
goal_msg->goal.target_pose.pose.position.x = 5.0;
goal_msg->goal.target_pose.pose.position.y = 3.0;
goal_msg->goal.target_pose.pose.position.z = 0.0;
goal_msg->goal.target_pose.pose.orientation.w = 1.0;
// Process the goal
example.processGoalMessage(goal_msg);
// Your event loop here
// while (your_system_running())
// {
// // Receive messages from your communication system
// // Process goals and cancels
// // example.processGoalMessage(goal_msg);
// // example.processCancelMessage(cancel_msg);
// }
// Keep running for a while
robot::Time::sleep(robot::Duration(10.0));
}
catch (const std::exception& e)
{
robot::log_error("[Example] Exception: %s", e.what());
return 1;
}
return 0;
}

View File

@@ -1,37 +0,0 @@
#ifndef MOVE_BASE_CONVERT_DATA_H
#define MOVE_BASE_CONVERT_DATA_H
#include <robot_costmap_2d/costmap_2d_robot.h>
#include <robot_nav_msgs/OccupancyGrid.h>
#include <robot_map_msgs/OccupancyGridUpdate.h>
namespace move_base
{
class ConvertData
{
public:
ConvertData(robot_costmap_2d::Costmap2DROBOT* costmap, std::string global_frame, bool always_send_full_costmap = false);
~ConvertData();
/** @brief Update data for publication. */
void updateCostmap(robot_nav_msgs::OccupancyGrid &grid, robot_map_msgs::OccupancyGridUpdate &update, bool &is_updated);
void updateFootprint(robot_geometry_msgs::PolygonStamped &footprint);
private:
/** @brief Prepare grid_ message for publication. */
void prepareGrid();
/** @brief Include the given bounds in the changed-rectangle. */
void updateBounds(unsigned int x0, unsigned int xn, unsigned int y0, unsigned int yn);
robot_costmap_2d::Costmap2DROBOT* costmap_;
std::string global_frame_;
unsigned int x0_, xn_, y0_, yn_;
double saved_origin_x_, saved_origin_y_;
bool always_send_full_costmap_;
robot_nav_msgs::OccupancyGrid grid_;
static char* cost_translation_table_; ///< Translate from 0-255 values in costmap to -1 to 100 values in message.
};
}
#endif

View File

@@ -1,707 +0,0 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Author: Kevin Lee
*********************************************************************/
#ifndef NAV_MOVE_BASE_ACTION_H_
#define NAV_MOVE_BASE_ACTION_H_
#include <robot/robot.h>
#include <vector>
#include <string>
#include <tf3/buffer_core.h>
#include <move_base/simple_action_server.h>
// interfaces headers
#include <move_base_core/navigation.h>
#include <robot_nav_core/base_global_planner.h>
#include <robot_nav_core/base_local_planner.h>
#include <robot_nav_core/recovery_behavior.h>
// boost headers
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <robot_costmap_2d/costmap_2d_robot.h>
#include <robot_costmap_2d/costmap_2d.h>
#include <robot_nav_msgs/GetPlan.h>
#include <robot_protocol_msgs/Order.h>
#include <robot_move_base_msgs/MoveBaseAction.h>
#include <memory>
#include <functional>
namespace move_base
{
template <class T>
void move_parameter(robot::NodeHandle& old_h, robot::NodeHandle& new_h, std::string name,T& value)
{
if (!old_h.hasParam(name))
return;
old_h.getParam(name, value);
new_h.setParam(name, value);
}
// typedefs to help us out with the action server so that we don't hace to type so much
typedef move_base::SimpleActionServer<robot_move_base_msgs::MoveBaseAction> MoveBaseActionServer;
enum MoveBaseState
{
PLANNING,
CONTROLLING,
CLEARING
};
enum RecoveryTrigger
{
PLANNING_R,
CONTROLLING_R,
OSCILLATION_R
};
struct MoveBaseConfig
{
std::string base_global_planner;
};
/**
* @class MoveBase
* @brief A class that uses the actionlib::ActionServer interface that moves the robot base to a goal location.
*/
class MoveBase : public robot::move_base_core::BaseNavigation
{
public:
/**
* @brief Constructor for the actions
* @param tf A reference to a TransformListener
*/
MoveBase(robot::TFListenerPtr tf);
/**
* @brief Default constructor for the actions
*/
MoveBase();
/**
* @brief Initialize the navigation system.
* @param tf Shared pointer to the TF listener or buffer.
*/
virtual void initialize(robot::TFListenerPtr tf) override;
/**
* @brief Initialize the cost-to-occupancy lookup table for costmap conversion
*/
static void initializeCostToOccupancyLUT();
/**
* @brief Set the robot's footprint (outline shape) in the global frame.
* This can be used for planning or collision checking.
*
* @param fprt A vector of points representing the robot's footprint polygon.
* The points should be ordered counter-clockwise.
*/
virtual void setRobotFootprint(const std::vector<robot_geometry_msgs::Point> &fprt) override;
/**
* @brief Get the robot's footprint (outline shape) in the global frame.
* @return A vector of points representing the robot's footprint polygon.
*/
virtual std::vector<robot_geometry_msgs::Point> getRobotFootprint() override;
/**
* @brief Add a static map to the navigation system.
* @param map_name The name of the map.
* @param map The map to add.
*/
virtual void addStaticMap(const std::string &map_name, robot_nav_msgs::OccupancyGrid map) override;
/**
* @brief Add a laser scan to the navigation system.
* @param laser_scan_name The name of the laser scan.
* @param laser_scan The laser scan to add.
*/
virtual void addLaserScan(const std::string &laser_scan_name, robot_sensor_msgs::LaserScan laser_scan) override;
/**
* @brief Add a point cloud to the navigation system.
* @param point_cloud_name The name of the point cloud.
* @param point_cloud The point cloud to add.
*/
virtual void addPointCloud(const std::string &point_cloud_name, robot_sensor_msgs::PointCloud point_cloud) override;
/**
* @brief Add a point cloud2 to the navigation system.
* @param point_cloud2_name The name of the point cloud2.
* @param point_cloud2 The point cloud2 to add.
*/
virtual void addPointCloud2(const std::string &point_cloud2_name, robot_sensor_msgs::PointCloud2 point_cloud2) override;
/**
* @brief Get a static map from the navigation system.
* @param map_name The name of the map.
* @return The map.
*/
virtual robot_nav_msgs::OccupancyGrid getStaticMap(const std::string &map_name) override;
/**
* @brief Get a laser scan from the navigation system.
* @param laser_scan_name The name of the laser scan.
* @return The laser scan.
*/
virtual robot_sensor_msgs::LaserScan getLaserScan(const std::string &laser_scan_name) override;
/**
* @brief Get a point cloud from the navigation system.
* @param point_cloud_name The name of the point cloud.
* @return The point cloud.
*/
virtual robot_sensor_msgs::PointCloud getPointCloud(const std::string &point_cloud_name) override;
/**
* @brief Get a point cloud2 from the navigation system.
* @param point_cloud2_name The name of the point cloud2.
* @return The point cloud2.
*/
virtual robot_sensor_msgs::PointCloud2 getPointCloud2(const std::string &point_cloud2_name) override;
/**
* @brief Get all static maps from the navigation system.
* @return The static maps.
*/
virtual std::map<std::string, robot_nav_msgs::OccupancyGrid> getAllStaticMaps() override;
/**
* @brief Get all laser scans from the navigation system.
* @return The laser scans.
*/
virtual std::map<std::string, robot_sensor_msgs::LaserScan> getAllLaserScans() override;
/**
* @brief Get all point clouds from the navigation system.
* @return The point clouds.
*/
virtual std::map<std::string, robot_sensor_msgs::PointCloud> getAllPointClouds() override;
/**
* @brief Get all point cloud2s from the navigation system.
* @return The point cloud2s.
*/
virtual std::map<std::string, robot_sensor_msgs::PointCloud2> getAllPointCloud2s() override;
/**
* @brief Remove a static map from the navigation system.
* @param map_name The name of the map.
* @return True if the map was removed successfully.
*/
virtual bool removeStaticMap(const std::string &map_name) override;
/**
* @brief Remove a laser scan from the navigation system.
* @param laser_scan_name The name of the laser scan.
* @return True if the laser scan was removed successfully.
*/
virtual bool removeLaserScan(const std::string &laser_scan_name) override;
/**
* @brief Remove a point cloud from the navigation system.
* @param point_cloud_name The name of the point cloud.
* @return True if the point cloud was removed successfully.
*/
virtual bool removePointCloud(const std::string &point_cloud_name) override;
/**
* @brief Remove a point cloud2 from the navigation system.
* @param point_cloud2_name The name of the point cloud2.
* @return True if the point cloud2 was removed successfully.
*/
virtual bool removePointCloud2(const std::string &point_cloud2_name) override;
/**
* @brief Remove all static maps from the navigation system.
* @return True if the static maps were removed successfully.
*/
virtual bool removeAllStaticMaps() override;
/**
* @brief Remove all laser scans from the navigation system.
* @return True if the laser scans were removed successfully.
*/
virtual bool removeAllLaserScans() override;
/**
* @brief Remove all point clouds from the navigation system.
* @return True if the point clouds were removed successfully.
*/
virtual bool removeAllPointClouds() override;
/**
* @brief Remove all point cloud2s from the navigation system.
* @return True if the point cloud2s were removed successfully.
*/
virtual bool removeAllPointCloud2s() override;
/**
* @brief Remove all data from the navigation system.
* @return True if the data was removed successfully.
*/
virtual bool removeAllData() override;
/**
* @brief Add an odometry to the navigation system.
* @param odometry_name The name of the odometry.
* @param odometry The odometry to add.
*/
virtual void addOdometry(const std::string &odometry_name, robot_nav_msgs::Odometry odometry) override;
/**
* @brief Send a goal for the robot to navigate to.
* @param goal Target pose in the global frame.
* @param xy_goal_tolerance Acceptable error in X/Y (meters).
* @param yaw_goal_tolerance Acceptable angular error (radians).
* @return True if goal was accepted and sent successfully.
*/
virtual bool moveTo(const robot_geometry_msgs::PoseStamped &goal,
double xy_goal_tolerance = 0.0,
double yaw_goal_tolerance = 0.0) override;
/**
* @brief Send a goal for the robot to navigate to.
* @param msg Order message.
* @param goal Target pose in the global frame.
* @param xy_goal_tolerance Acceptable error in X/Y (meters).
* @param yaw_goal_tolerance Acceptable angular error (radians).
* @return True if goal was accepted and sent successfully.
*/
virtual bool moveTo(const robot_protocol_msgs::Order &msg,
const robot_geometry_msgs::PoseStamped &goal,
double xy_goal_tolerance = 0.0,
double yaw_goal_tolerance = 0.0) override;
/**
* @brief Send a docking goal to a predefined marker (e.g. charger).
* @param maker Marker name or ID.
* @param goal Target pose for docking.
* @param xy_goal_tolerance Acceptable XY error (meters).
* @param yaw_goal_tolerance Acceptable heading error (radians).
* @return True if docking command succeeded.
*/
virtual bool dockTo(const std::string &maker,
const robot_geometry_msgs::PoseStamped &goal,
double xy_goal_tolerance = 0.0,
double yaw_goal_tolerance = 0.0) override;
/**
* @brief Send a docking goal to a predefined marker (e.g. charger).
* @param msg Order message.
* @param goal Target pose for docking.
* @param xy_goal_tolerance Acceptable XY error (meters).
* @param yaw_goal_tolerance Acceptable heading error (radians).
* @return True if docking command succeeded.
*/
virtual bool dockTo(const robot_protocol_msgs::Order &msg,
const std::string &marker,
const robot_geometry_msgs::PoseStamped &goal,
double xy_goal_tolerance = 0.0,
double yaw_goal_tolerance = 0.0) override;
/**
* @brief Move straight toward the target position (X-axis).
* @param msg Order message.
* @param goal Target pose.
* @param xy_goal_tolerance Acceptable positional error (meters).
* @return True if command issued successfully.
*/
virtual bool moveStraightTo(const robot_geometry_msgs::PoseStamped &goal,
double xy_goal_tolerance = 0.0) override;
/**
* @brief Rotate in place to align with target orientation.
* @param goal Pose containing desired heading (only Z-axis used).
* @param yaw_goal_tolerance Acceptable angular error (radians).
* @return True if rotation command was sent successfully.
*/
virtual bool rotateTo(const robot_geometry_msgs::PoseStamped &goal,
double yaw_goal_tolerance = 0.0) override;
/**
* @brief Pause the robot's movement (e.g. during obstacle avoidance).
*/
virtual void pause() override;
/**
* @brief Resume motion after a pause.
*/
virtual void resume() override;
/**
* @brief Cancel the current goal and stop the robot.
*/
virtual void cancel() override;
/**
* @brief Send direct linear velocity command.
* @param linear Linear velocity vector (x, y, z).
* @return True if the command was accepted.
*/
virtual bool setTwistLinear(const robot_geometry_msgs::Vector3 &linear) override;
/**
* @brief Send limited angular velocity command.
* @param angular Angular velocity vector (x, y, z).
* @return True if the command was accepted.
*/
virtual bool setTwistAngular(const robot_geometry_msgs::Vector3 &angular) override;
/**
* @brief Get the robot’s pose as a PoseStamped.
* @param pose Output parameter with the robot’s current pose.
* @return True if pose was successfully retrieved.
*/
virtual bool getRobotPose(robot_geometry_msgs::PoseStamped &pose) override;
/**
* @brief Get the robot’s pose as a 2D pose.
* @param pose Output parameter with the robot’s current 2D pose.
* @return True if pose was successfully retrieved.
*/
virtual bool getRobotPose(robot_geometry_msgs::Pose2D &pose) override;
/**
* @brief Get the robot’s twist.
* @return The robot’s current twist.
*/
virtual robot_nav_2d_msgs::Twist2DStamped getTwist() override;
/**
* @brief Get the navigation feedback.
* @return Pointer to the navigation feedback.
*/
virtual robot::move_base_core::NavFeedback *getFeedback() override;
/**
* @brief Get the global data.
* @return The global data.
*/
virtual robot::move_base_core::PlannerDataOutput getGlobalData() override;
/**
* @brief Get the local data.
* @return The local data.
*/
virtual robot::move_base_core::PlannerDataOutput getLocalData() override;
/**
* @brief Destructor - Cleans up
*/
virtual ~MoveBase();
/**
* @brief Create a new MoveBase
* @return A shared pointer to the new MoveBase
*/
static robot::move_base_core::BaseNavigation::Ptr create();
private:
/**
* @brief Update the global costmap.
* @param value The value to update the costmap.
* @param layer_type The type of the layer.
* @param name The name of the costmap.
*/
template<typename T>
void updateGlobalCostmap(const T& value, robot_costmap_2d::LayerType layer_type, const std::string &name);
/**
* @brief Update the local costmap.
* @param value The value to update the costmap.
* @param layer_type The type of the layer.
* @param name The name of the costmap.
*/
template<typename T>
void updateLocalCostmap(const T& value, robot_costmap_2d::LayerType layer_type, const std::string &name);
/**
* @brief Performs a control cycle
* @param goal A reference to the goal to pursue
* @return True if processing of the goal is done, false otherwise
*/
bool executeCycle(robot_geometry_msgs::PoseStamped &goal);
/**
* @brief Set velocity for yaw goal tolerance of the robot
* @param yaw_goal_tolerance the value command
*/
void setYawGoalTolerance(double yaw_goal_tolerance);
/**
* @brief Set the XY goal tolerance for the robot
* @param xy_goal_tolerance The XY tolerance value in meters
*/
void setXyGoalTolerance(double xy_goal_tolerance);
/**
* @brief Swaps the current global planner with a new one specified by name
* @param base_global_planner The name of the new global planner to use
*/
void swapPlanner(std::string base_global_planner);
/**
* @brief Make a new global plan
* @param goal The goal to plan to
* @param plan Will be filled in with the plan made by the planner
* @return True if planning succeeds, false otherwise
*/
bool makePlan(const robot_geometry_msgs::PoseStamped &goal, std::vector<robot_geometry_msgs::PoseStamped> &plan);
/**
* @brief Make a new global plan
* @param msg The order message
* @param goal The goal to plan to
* @param plan Will be filled in with the plan made by the planner
* @return True if planning succeeds, false otherwise
*/
bool makePlan(const robot_protocol_msgs::Order &msg, const robot_geometry_msgs::PoseStamped &goal, std::vector<robot_geometry_msgs::PoseStamped> &plan);
/**
* @brief Load the recovery behaviors for the navigation stack from the parameter server
* @return True if the recovery behaviors were loaded successfully, false otherwise
*/
bool loadRecoveryBehaviors(const robot::NodeHandle &node);
/**
* @brief Loads the default recovery behaviors for the navigation stack
*/
void loadDefaultRecoveryBehaviors();
/**
* @brief Clears obstacles within a window around the robot
* @param size_x The x size of the window
* @param size_y The y size of the window
*/
void clearCostmapWindows(double size_x, double size_y);
/**
* @brief Publishes a velocity command of zero to the base
*/
void publishZeroVelocity();
/**
* @brief Reset the state of the move_base action and send a zero velocity command to the base
*/
void resetState();
/**
* @brief Thread function that continuously plans paths to the goal
*/
void planThread();
/**
* @brief Callback function to execute a move_base goal
* @param move_base_goal The goal message to execute
*/
void executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr &move_base_goal);
/**
* @brief Setup callbacks for the action server
*/
void setupActionServerCallbacks();
/**
* @brief Check if a quaternion is valid (normalized)
* @param q The quaternion to validate
* @return True if the quaternion is valid, false otherwise
*/
bool isQuaternionValid(const robot_geometry_msgs::Quaternion &q);
/**
* @brief Get the robot's pose in the global frame using a specific costmap
* @param global_pose Output parameter with the robot's current pose
* @param costmap The costmap to use for pose lookup
* @return True if pose was successfully retrieved
*/
bool getRobotPose(robot_geometry_msgs::PoseStamped &global_pose, robot_costmap_2d::Costmap2DROBOT *costmap);
/**
* @brief Calculate the Euclidean distance between two poses
* @param p1 First pose
* @param p2 Second pose
* @return The distance between the two poses in meters
*/
double distance(const robot_geometry_msgs::PoseStamped &p1, const robot_geometry_msgs::PoseStamped &p2);
/**
* @brief Transform a goal pose to the global frame
* @param goal_pose_msg The goal pose to transform
* @return The transformed pose in the global frame
*/
robot_geometry_msgs::PoseStamped goalToGlobalFrame(const robot_geometry_msgs::PoseStamped &goal_pose_msg);
/**
* @brief This is used to wake the planner at periodic intervals.
*/
void wakePlanner(const robot::TimerEvent &event);
private:
/** @brief Flag indicating if the move_base has been initialized */
bool initialized_;
/** @brief Transform listener for coordinate frame transformations */
robot::TFListenerPtr tf_;
/** @brief Private node handle for ROS parameters and topics */
robot::NodeHandle private_nh_;
/** @brief Action server for move_base goals */
MoveBaseActionServer *as_;
/** @brief Function loader for global planner plugins */
boost::function<robot_nav_core::BaseGlobalPlanner::Ptr()> planner_loader_;
/** @brief Function loader for local planner (controller) plugins */
boost::function<robot_nav_core::BaseLocalPlanner::Ptr()> controller_loader_;
/** @brief Map of recovery behavior loaders by name */
std::map<std::string, boost::function<robot_nav_core::RecoveryBehavior::Ptr()>> recovery_loaders_;
/** @brief Local planner (trajectory controller) instance */
robot_nav_core::BaseLocalPlanner::Ptr tc_;
/** @brief Global planner instance */
robot_nav_core::BaseGlobalPlanner::Ptr planner_;
/** @brief Vector of recovery behavior instances */
std::vector<robot_nav_core::RecoveryBehavior::Ptr> recovery_behaviors_;
/** @brief Costmap for the local planner/controller */
robot_costmap_2d::Costmap2DROBOT *controller_costmap_robot_;
/** @brief Costmap for the global planner */
robot_costmap_2d::Costmap2DROBOT *planner_costmap_robot_;
/** @brief Robot base frame name and global frame name */
std::string robot_base_frame_, global_frame_;
/** @brief Names of recovery behaviors to use */
std::vector<std::string> recovery_behavior_names_;
/** @brief Current index in the recovery behavior list */
unsigned int recovery_index_;
/** @brief Flag indicating if recovery behaviors are enabled */
bool recovery_behavior_enabled_;
/** @brief Current global pose of the robot */
robot_geometry_msgs::PoseStamped global_pose_;
/** @brief Frequency for planner execution (Hz) */
double planner_frequency_;
/** @brief Frequency for controller execution (Hz) */
double controller_frequency_;
/** @brief Inscribed radius of the robot footprint (meters) */
double inscribed_radius_;
/** @brief Circumscribed radius of the robot footprint (meters) */
double circumscribed_radius_;
/** @brief Maximum time to wait for a valid plan before triggering recovery (seconds) */
double planner_patience_;
/** @brief Maximum time to wait for valid control before triggering recovery (seconds) */
double controller_patience_;
/** @brief Maximum number of planning retries before giving up */
int32_t max_planning_retries_;
/** @brief Current number of planning retries */
uint32_t planning_retries_;
/** @brief Conservative distance threshold for resetting costmaps (meters) */
double conservative_reset_dist_;
/** @brief Radius around robot to clear obstacles during recovery (meters) */
double clearing_radius_;
/** @brief Flag to shutdown costmaps when not in use */
bool shutdown_costmaps_;
/** @brief Flag allowing rotation during costmap clearing */
bool clearing_rotation_allowed_;
/** @brief Flag to clear costmap when making a new plan */
bool make_plan_clear_costmap_;
/** @brief Flag to add unreachable goals to costmap */
bool make_plan_add_unreachable_goal_;
/** @brief Time threshold for detecting oscillation (seconds) */
double oscillation_timeout_;
/** @brief Distance threshold for detecting oscillation (meters) */
double oscillation_distance_;
/** @brief Current state of the move_base (PLANNING, CONTROLLING, CLEARING) */
MoveBaseState state_;
/** @brief Trigger that caused recovery behavior (PLANNING_R, CONTROLLING_R, OSCILLATION_R) */
RecoveryTrigger recovery_trigger_;
/** @brief Timestamp of the last valid plan */
robot::Time last_valid_plan_;
/** @brief Timestamp of the last valid control command */
robot::Time last_valid_control_;
/** @brief Timestamp of the last oscillation reset */
robot::Time last_oscillation_reset_;
/** @brief Pose used for oscillation detection */
robot_geometry_msgs::PoseStamped oscillation_pose_;
/** @brief Plan triple buffer: plan from the planner thread */
std::vector<robot_geometry_msgs::PoseStamped> *planner_plan_;
/** @brief Plan triple buffer: latest plan (intermediate buffer) */
std::vector<robot_geometry_msgs::PoseStamped> *latest_plan_;
/** @brief Plan triple buffer: plan used by the controller */
std::vector<robot_geometry_msgs::PoseStamped> *controller_plan_;
/** @brief Flag to control planner thread execution */
bool runPlanner_;
/** @brief Mutex for protecting planner thread data */
boost::recursive_mutex planner_mutex_;
/** @brief Condition variable to wake planner thread */
boost::condition_variable_any planner_cond_;
/** @brief Goal pose for the planner thread */
robot_geometry_msgs::PoseStamped planner_goal_;
/** @brief Order message for the planner thread (nullptr if not using Order-based planning) */
boost::shared_ptr<robot_protocol_msgs::Order> planner_order_;
/** @brief Thread handle for the planner */
boost::thread *planner_thread_;
/** @brief Mutex for protecting configuration changes */
boost::recursive_mutex configuration_mutex_;
/** @brief Last configuration used */
move_base::MoveBaseConfig last_config_;
/** @brief Default configuration */
move_base::MoveBaseConfig default_config_;
/** @brief Flag indicating if setup is complete */
bool setup_;
/** @brief Flag indicating planner frequency changed */
bool p_freq_change_;
/** @brief Flag indicating controller frequency changed */
bool c_freq_change_;
/** @brief Flag indicating a new global plan is available */
bool new_global_plan_;
/** @brief Flag indicating cancel control request */
bool cancel_ctr_;
/** @brief Flag indicating pause control request */
bool pause_ctr_;
/** @brief Flag indicating if robot is currently paused */
bool paused_;
/** @brief Minimum linear velocity when approaching goal (m/s) */
double min_approach_linear_velocity_{0.1};
/** @brief Previous forward linear velocity command */
robot_geometry_msgs::Vector3 old_linear_fwd_;
/** @brief Previous backward linear velocity command */
robot_geometry_msgs::Vector3 old_linear_bwd_;
/** @brief Previous forward angular velocity command */
robot_geometry_msgs::Vector3 old_angular_fwd_;
/** @brief Previous reverse angular velocity command */
robot_geometry_msgs::Vector3 old_angular_rev_;
/** @brief Original XY goal tolerance value (meters) */
double original_xy_goal_tolerance_;
/** @brief Original yaw goal tolerance value (radians) */
double original_yaw_goal_tolerance_;
/** @brief Name of the position/local planner plugin */
std::string position_planner_name_{"MKTLocalPlanner"};
/** @brief Name of the docking planner plugin */
std::string docking_planner_name_{"NAVDockingLocalPlanner"};
/** @brief Name of the go-straight planner plugin */
std::string go_straight_planner_name_{"NAVGoStraightLocalPlanner"};
/** @brief Name of the rotate planner plugin */
std::string rotate_planner_name_{"NAVRotateLocalPlanner"};
};
} // namespace move_base
#endif // NAV_MOVE_BASE_ACTION_H_

View File

@@ -1,259 +0,0 @@
#ifndef MOVE_BASE_SIMPLE_ACTION_SERVER_H_
#define MOVE_BASE_SIMPLE_ACTION_SERVER_H_
#include <string>
#include <memory>
#include <functional>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
// Action message types
#include <robot_move_base_msgs/MoveBaseAction.h>
#include <robot_move_base_msgs/MoveBaseActionGoal.h>
#include <robot_move_base_msgs/MoveBaseActionResult.h>
#include <robot_move_base_msgs/MoveBaseActionFeedback.h>
#include <robot_move_base_msgs/MoveBaseGoal.h>
#include <robot_move_base_msgs/MoveBaseResult.h>
#include <robot_move_base_msgs/MoveBaseFeedback.h>
// Actionlib message types
#include <robot_actionlib_msgs/GoalID.h>
#include <robot_actionlib_msgs/GoalStatus.h>
#include <robot_actionlib_msgs/GoalStatusArray.h>
// Robot framework
#include <robot/robot.h>
namespace move_base
{
/**
* @class SimpleActionServer
* @brief A simplified action server implementation similar to ROS actionlib::SimpleActionServer
*
* This class provides a simple interface for implementing action servers without ROS dependency.
* It handles goal requests, preemption, feedback publishing, and result publishing using callback functions.
*
* @tparam ActionSpec The action message type (e.g., robot_move_base_msgs::MoveBaseAction)
*/
template<class ActionSpec>
class SimpleActionServer
{
public:
// Typedefs for action message types
typedef typename ActionSpec::_action_goal_type ActionGoal;
typedef typename ActionSpec::_action_result_type ActionResult;
typedef typename ActionSpec::_action_feedback_type ActionFeedback;
typedef typename ActionGoal::_goal_type Goal;
typedef typename ActionResult::_result_type Result;
typedef typename ActionFeedback::_feedback_type Feedback;
typedef boost::shared_ptr<const Goal> GoalConstPtr;
typedef boost::shared_ptr<const Result> ResultConstPtr;
typedef boost::shared_ptr<const Feedback> FeedbackConstPtr;
typedef typename ActionGoal::ConstPtr ActionGoalConstPtr;
typedef typename ActionResult::ConstPtr ActionResultConstPtr;
typedef typename ActionFeedback::ConstPtr ActionFeedbackConstPtr;
typedef robot_actionlib_msgs::GoalStatusArrayConstPtr GoalStatusArrayConstPtr;
// Callback function types
typedef std::function<void(const ActionGoalConstPtr&)> GoalCallback;
typedef std::function<void(const robot_actionlib_msgs::GoalIDConstPtr&)> CancelCallback;
typedef std::function<void(const ActionFeedbackConstPtr&)> FeedbackCallback;
typedef std::function<void(const ActionResultConstPtr&)> ResultCallback;
typedef std::function<void(const GoalStatusArrayConstPtr&)> StatusCallback;
typedef std::function<void(const GoalConstPtr&)> ExecuteCallback;
// Typedefs for non-const pointers
typedef typename ActionResult::Ptr ActionResultPtr;
typedef typename ActionFeedback::Ptr ActionFeedbackPtr;
/**
* @brief Constructor
* @param name Action name (e.g., "move_base")
* @param execute_callback Callback function to execute when a goal is received
* @param auto_start If true, automatically start the server
*/
SimpleActionServer(const std::string& name,
ExecuteCallback execute_callback,
bool auto_start = true);
/**
* @brief Destructor
*/
~SimpleActionServer();
/**
* @brief Start the action server
*/
void start();
/**
* @brief Stop the action server
*/
void stop();
/**
* @brief Set callback for goal messages
* @param callback Function to call when a goal is received
*/
void setGoalCallback(GoalCallback callback);
/**
* @brief Set callback for cancel messages
* @param callback Function to call when a cancel is received
*/
void setCancelCallback(CancelCallback callback);
/**
* @brief Set callback for feedback publishing
* @param callback Function to call when feedback needs to be published
*/
void setFeedbackCallback(FeedbackCallback callback);
/**
* @brief Set callback for result publishing
* @param callback Function to call when result needs to be published
*/
void setResultCallback(ResultCallback callback);
/**
* @brief Set callback for status publishing
* @param callback Function to call when status needs to be published
*/
void setStatusCallback(StatusCallback callback);
/**
* @brief Set status publish rate
* @param rate Publishing rate in Hz
*/
void setStatusPublishRate(double rate);
/**
* @brief Process an incoming goal message
* @param goal_msg The goal message to process
*/
void processGoal(const ActionGoalConstPtr& goal_msg);
/**
* @brief Process an incoming cancel message
* @param cancel_msg The cancel message to process
*/
void processCancel(const robot_actionlib_msgs::GoalIDConstPtr& cancel_msg);
/**
* @brief Check if a new goal is available
* @return True if a new goal is available
*/
bool isNewGoalAvailable();
/**
* @brief Check if preemption has been requested
* @return True if preemption has been requested
*/
bool isPreemptRequested();
/**
* @brief Accept a new goal
* @return The new goal, or nullptr if no new goal is available
*/
GoalConstPtr acceptNewGoal();
/**
* @brief Set the action as succeeded
* @param result The result to send
* @param text Success message
*/
void setSucceeded(const Result& result = Result(), const std::string& text = "");
/**
* @brief Set the action as aborted
* @param result The result to send
* @param text Error message
*/
void setAborted(const Result& result = Result(), const std::string& text = "");
/**
* @brief Set the action as preempted
* @param result The result to send
* @param text Message
*/
void setPreempted(const Result& result = Result(), const std::string& text = "");
/**
* @brief Publish feedback
* @param feedback The feedback to publish
*/
void publishFeedback(const Feedback& feedback);
/**
* @brief Get the current goal
* @return The current goal, or nullptr if no goal is active
*/
GoalConstPtr getCurrentGoal();
/**
* @brief Get the current status
* @return The current goal status
*/
robot_actionlib_msgs::GoalStatus getCurrentStatus();
/**
* @brief Check if the server is active
* @return True if the server is active
*/
bool isActive();
/**
* @brief Get the action name
* @return The action name
*/
std::string getName() const;
private:
/**
* @brief Execute the goal in a separate thread
*/
void executeGoal();
/**
* @brief Thread function to publish status periodically
*/
void statusPublishThread();
// Action name
std::string name_;
// Execute callback
ExecuteCallback execute_callback_;
// Callbacks for external communication
GoalCallback goal_callback_;
CancelCallback cancel_callback_;
FeedbackCallback feedback_callback_;
ResultCallback result_callback_;
StatusCallback status_callback_;
// State
boost::mutex state_mutex_;
boost::condition_variable goal_condition_;
bool active_;
bool preempt_requested_;
bool new_goal_available_;
GoalConstPtr goal_;
robot_actionlib_msgs::GoalID current_goal_id_;
robot_actionlib_msgs::GoalStatus current_status_;
double status_publish_rate_;
// Threads
boost::thread status_thread_;
boost::thread execute_thread_;
};
} // namespace move_base
#endif // MOVE_BASE_SIMPLE_ACTION_SERVER_H_

View File

@@ -1,55 +0,0 @@
<package>
<name>move_base</name>
<version>0.7.10</version>
<description>
move_base is the second generation of the transform library, which lets
the user keep track of multiple coordinate frames over time. move_base
maintains the relationship between coordinate frames in a tree
structure buffered in time, and lets the user transform points,
vectors, etc between any two coordinate frames at any desired
point in time.
</description>
<author>Tully Foote</author>
<author>Eitan Marder-Eppstein</author>
<author>Wim Meeussen</author>
<maintainer email="tfoote@osrfoundation.org">Tully Foote</maintainer>
<license>BSD</license>
<url type="website">http://www.ros.org/wiki/move_base</url>
<buildtool_depend version_gte="0.5.68">catkin</buildtool_depend>
<build_depend>geometry_msgs</build_depend>
<run_depend>geometry_msgs</run_depend>
<build_depend>robot_std_msgs</build_depend>
<run_depend>robot_std_msgs</run_depend>
<build_depend>move_base_core</build_depend>
<run_depend>move_base_core</run_depend>
<build_depend>robot_nav_core</build_depend>
<run_depend>robot_nav_core</run_depend>
<build_depend>robot_costmap_2d</build_depend>
<run_depend>robot_costmap_2d</run_depend>
<build_depend>robot_tf3_sensor_msgs</build_depend>
<run_depend>robot_tf3_sensor_msgs</run_depend>
<build_depend>robot_tf3_geometry_msgs</build_depend>
<run_depend>robot_tf3_geometry_msgs</run_depend>
<build_depend>data_convert</build_depend>
<run_depend>data_convert</run_depend>
<build_depend>robot_nav_2d_utils</build_depend>
<run_depend>robot_nav_2d_utils</run_depend>
<build_depend>robot_cpp</build_depend>
<run_depend>robot_cpp</run_depend>
<build_depend>robot_move_base_msgs</build_depend>
<run_depend>robot_move_base_msgs</run_depend>
</package>

View File

@@ -1,130 +0,0 @@
#include <move_base/convert_data.h>
#include <robot/robot.h>
#include <robot_costmap_2d/cost_values.h>
char* move_base::ConvertData::cost_translation_table_ = NULL;
move_base::ConvertData::ConvertData(robot_costmap_2d::Costmap2DROBOT* costmap, std::string global_frame, bool always_send_full_costmap)
: costmap_(costmap), global_frame_(global_frame), always_send_full_costmap_(always_send_full_costmap)
{
if (cost_translation_table_ == NULL)
{
cost_translation_table_ = new char[256];
// special values:
cost_translation_table_[(const int)robot_costmap_2d::PREFERRED_SPACE] = 120; // Preferred place
for(int i = (int)robot_costmap_2d::PREFERRED_SPACE+1; i <= (const int)robot_costmap_2d::FREE_SPACE; i++)
cost_translation_table_[i] = 0; // NO obstacle
cost_translation_table_[(const int)robot_costmap_2d::CRITICAL_SPACE] = 150; // CRITICAL_SPACE
cost_translation_table_[(const int)robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE] = 99; // INSCRIBED obstacle
cost_translation_table_[(const int)robot_costmap_2d::LETHAL_OBSTACLE] = 100; // LETHAL obstacle
cost_translation_table_[(const int)robot_costmap_2d::NO_INFORMATION] = -1; // UNKNOWN
// regular cost values scale the range 10 to 252 (inclusive) to fit
// into 1 to 98 (inclusive).
for (int i = (int)robot_costmap_2d::FREE_SPACE + 1; i < (const int)robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE; i++)
{
cost_translation_table_[ i ] = char(1 + (97 * (i - 1)) / 251);
}
}
xn_ = yn_ = 0;
x0_ = costmap_->getCostmap()->getSizeInCellsX();
y0_ = costmap_->getCostmap()->getSizeInCellsY();
}
move_base::ConvertData::~ConvertData()
{
}
// prepare grid_ message for publication.
void move_base::ConvertData::prepareGrid()
{
// boost::unique_lock<Costmap2D::mutex_t> lock(*(costmap_->getMutex()));
double resolution = costmap_->getCostmap()->getResolution();
grid_.header.frame_id = global_frame_;
grid_.header.stamp = robot::Time::now();
grid_.info.resolution = resolution;
grid_.info.width = costmap_->getCostmap()->getSizeInCellsX();
grid_.info.height = costmap_->getCostmap()->getSizeInCellsY();
double wx, wy;
costmap_->getCostmap()->mapToWorld(0, 0, wx, wy);
grid_.info.origin.position.x = wx - resolution / 2;
grid_.info.origin.position.y = wy - resolution / 2;
grid_.info.origin.position.z = 0.0;
grid_.info.origin.orientation.w = 1.0;
saved_origin_x_ = costmap_->getCostmap()->getOriginX();
saved_origin_y_ = costmap_->getCostmap()->getOriginY();
grid_.data.resize(grid_.info.width * grid_.info.height);
unsigned char* data = costmap_->getCostmap()->getCharMap();
for (unsigned int i = 0; i < grid_.data.size(); i++)
{
grid_.data[i] = cost_translation_table_[ data[ i ]];
}
}
void move_base::ConvertData::updateCostmap(robot_nav_msgs::OccupancyGrid &grid, robot_map_msgs::OccupancyGridUpdate &update, bool &is_updated)
{
boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(costmap_->getCostmap()->getMutex()));
float resolution = costmap_->getCostmap()->getResolution();
unsigned int x0, y0, xn, yn;
costmap_->getLayeredCostmap()->getBounds(&x0, &xn, &y0, &yn);
updateBounds(x0, xn, y0, yn);
if (always_send_full_costmap_ || grid_.info.resolution != resolution ||
grid_.info.width != costmap_->getCostmap()->getSizeInCellsX() ||
grid_.info.height != costmap_->getCostmap()->getSizeInCellsY() ||
saved_origin_x_ != costmap_->getCostmap()->getOriginX() ||
saved_origin_y_ != costmap_->getCostmap()->getOriginY())
{
prepareGrid();
grid = grid_;
is_updated = false;
}
else if (x0_ < xn_)
{
update.header.stamp = robot::Time::now();
update.header.frame_id = global_frame_;
update.x = x0_;
update.y = y0_;
update.width = xn_ - x0_;
update.height = yn_ - y0_;
update.data.resize(update.width * update.height);
unsigned int i = 0;
for (unsigned int y = y0_; y < yn_; y++)
{
for (unsigned int x = x0_; x < xn_; x++)
{
unsigned char cost = costmap_->getCostmap()->getCost(x, y);
update.data[i++] = cost_translation_table_[ cost ];
}
}
is_updated = true;
}
xn_ = yn_ = 0;
x0_ = costmap_->getCostmap()->getSizeInCellsX();
y0_ = costmap_->getCostmap()->getSizeInCellsY();
}
void move_base::ConvertData::updateFootprint(robot_geometry_msgs::PolygonStamped &footprint)
{
footprint.header.frame_id = global_frame_;
footprint.header.stamp = robot::Time::now();
footprint.polygon = costmap_->getRobotFootprintPolygonStamped().polygon;
}
void move_base::ConvertData::updateBounds(unsigned int x0, unsigned int xn, unsigned int y0, unsigned int yn)
{
x0_ = std::min(x0, x0_);
xn_ = std::max(xn, xn_);
y0_ = std::min(y0, y0_);
yn_ = std::max(yn, yn_);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,123 +0,0 @@
/*
* Copyright (c) 2013, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <move_base/move_base.h>
#include <iostream>
#include <robot/robot.h>
#include <robot_nav_2d_utils/parameters.h>
#include <boost/dll/import.hpp>
#include <tf3/buffer_core.h>
#include <tf3/transform_datatypes.h>
int main(int argc, char** argv)
{
try {
std::shared_ptr<tf3::BufferCore> tf = std::make_shared<tf3::BufferCore>();
// Lambda function để set static transform (tương tự tf_listener_set_static_transform trong nav_c_api.cpp)
auto set_static_transform = [&tf](const std::string& parent_frame,
const std::string& child_frame,
double x, double y, double z,
double qx, double qy, double qz, double qw) -> bool {
if (!tf || parent_frame.empty() || child_frame.empty()) {
return false;
}
try {
tf3::TransformStampedMsg st;
st.header.stamp = tf3::Time::now();
st.header.frame_id = parent_frame;
st.child_frame_id = child_frame;
st.transform.translation.x = x;
st.transform.translation.y = y;
st.transform.translation.z = z;
st.transform.rotation.x = qx;
st.transform.rotation.y = qy;
st.transform.rotation.z = qz;
st.transform.rotation.w = qw;
return tf->setTransform(st, "move_base_main(static)", true /*is_static*/);
} catch (...) {
return false;
}
};
if (set_static_transform("map", "odom", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)) {
robot::log_info("[%s:%d]\n Static transform set: map -> odom", __FILE__, __LINE__);
} else {
robot::log_error("[%s:%d]\n Failed to set static transform: map -> odom", __FILE__, __LINE__);
}
if (set_static_transform("odom", "base_footprint", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)) {
robot::log_info("[%s:%d]\n Static transform set: odom -> base_footprint", __FILE__, __LINE__);
} else {
robot::log_error("[%s:%d]\n Failed to set static transform: odom -> base_footprint", __FILE__, __LINE__);
}
if (set_static_transform("base_footprint", "base_link", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)) {
robot::log_info("[%s:%d]\n Static transform set: base_footprint -> base_link", __FILE__, __LINE__);
} else {
robot::log_error("[%s:%d]\n Failed to set static transform: base_footprint -> base_link", __FILE__, __LINE__);
}
robot::log_info("[%s:%d]\n Loading MoveBase library...", __FILE__, __LINE__);
robot::PluginLoaderHelper loader;
std::string path_file_so = loader.findLibraryPath("MoveBase");
auto create_plugin = boost::dll::import_alias<robot::move_base_core::BaseNavigation::Ptr()>(
path_file_so,
"MoveBase", boost::dll::load_mode::append_decorations);
robot::log_info("[%s:%d]\n Creating MoveBase instance...", __FILE__, __LINE__);
robot::move_base_core::BaseNavigation::Ptr nav_ptr = create_plugin();
if (nav_ptr == nullptr) {
robot::log_error("[%s:%d]\n Error: Failed to create navigation", __FILE__, __LINE__);
return 1;
}
robot::log_info("[%s:%d]\n Navigation created, initializing...", __FILE__, __LINE__);
nav_ptr->initialize(tf);
robot::log_info("[%s:%d]\n Navigation initialized successfully", __FILE__, __LINE__);
std::cout << "Move Base Main Function :" << robot::Time::now().toSec() << std::endl;
// Explicitly reset before create_plugin goes out of scope to ensure proper cleanup order
robot::log_info("[%s:%d]\n Cleaning up...", __FILE__, __LINE__);
nav_ptr.reset();
robot::log_info("[%s:%d]\n Cleanup complete", __FILE__, __LINE__);
return 0;
} catch (const std::exception &e) {
robot::log_error("[%s:%d]\n Exception: %s", __FILE__, __LINE__, e.what());
return 1;
} catch (...) {
robot::log_error("[%s:%d]\n Unknown exception occurred", __FILE__, __LINE__);
return 1;
}
return 0;
}

View File

@@ -1,632 +0,0 @@
#include <move_base/simple_action_server.h>
namespace move_base
{
// Constructor
template<class ActionSpec>
SimpleActionServer<ActionSpec>::SimpleActionServer(const std::string& name,
ExecuteCallback execute_callback,
bool auto_start)
: name_(name),
execute_callback_(execute_callback),
active_(false),
preempt_requested_(false),
new_goal_available_(false),
goal_(nullptr),
status_publish_rate_(10.0)
{
// Initialize status
current_status_.status = robot_actionlib_msgs::GoalStatus::PENDING;
current_status_.goal_id.stamp = robot::Time::now();
current_status_.goal_id.id = "";
current_status_.text = "";
if (auto_start)
{
start();
}
robot::log_info("[SimpleActionServer] Initialized action server: %s", name_.c_str());
}
// Destructor
template<class ActionSpec>
SimpleActionServer<ActionSpec>::~SimpleActionServer()
{
stop();
}
// Start the action server
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::start()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (!active_)
{
active_ = true;
// Start status publishing thread
status_thread_ = boost::thread(boost::bind(&SimpleActionServer::statusPublishThread, this));
robot::log_info("[SimpleActionServer] Started action server: %s", name_.c_str());
}
}
// Stop the action server
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::stop()
{
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (active_)
{
active_ = false;
}
}
// Notify all waiting threads
goal_condition_.notify_all();
if (status_thread_.joinable())
{
status_thread_.join();
}
if (execute_thread_.joinable())
{
execute_thread_.join();
}
robot::log_info("[SimpleActionServer] Stopped action server: %s", name_.c_str());
}
// Set callback for goal messages
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::setGoalCallback(GoalCallback callback)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
goal_callback_ = callback;
}
// Set callback for cancel messages
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::setCancelCallback(CancelCallback callback)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
cancel_callback_ = callback;
}
// Set callback for feedback publishing
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::setFeedbackCallback(FeedbackCallback callback)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
feedback_callback_ = callback;
}
// Set callback for result publishing
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::setResultCallback(ResultCallback callback)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
result_callback_ = callback;
}
// Set callback for status publishing
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::setStatusCallback(StatusCallback callback)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
status_callback_ = callback;
}
// Set status publish rate
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::setStatusPublishRate(double rate)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
status_publish_rate_ = rate;
}
// Process an incoming goal message
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::processGoal(const ActionGoalConstPtr& goal_msg)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (!active_)
{
robot::log_warning("[SimpleActionServer] Received goal but server is not active");
return;
}
// Check if we should accept this goal
bool accept_goal = false;
if (current_status_.status == robot_actionlib_msgs::GoalStatus::PENDING ||
current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE ||
current_status_.status == robot_actionlib_msgs::GoalStatus::PREEMPTING)
{
// Check if this is a new goal (different ID)
if (goal_msg->goal_id.id != current_goal_id_.id ||
goal_msg->goal_id.stamp != current_goal_id_.stamp)
{
// If we have an active goal, preempt it
if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE)
{
preempt_requested_ = true;
current_status_.status = robot_actionlib_msgs::GoalStatus::PREEMPTING;
robot::log_info("[SimpleActionServer] Preempting current goal for new goal");
}
accept_goal = true;
}
}
else
{
// No active goal, accept this one
accept_goal = true;
}
if (accept_goal)
{
// Store the new goal
goal_ = boost::make_shared<Goal>(goal_msg->goal);
current_goal_id_ = goal_msg->goal_id;
new_goal_available_ = true;
current_status_.status = robot_actionlib_msgs::GoalStatus::PENDING;
current_status_.goal_id = current_goal_id_;
current_status_.text = "";
robot::log_info("[SimpleActionServer] Received new goal, ID: %s", current_goal_id_.id.c_str());
// Notify waiting threads
goal_condition_.notify_one();
// Start execute thread if not already running
if (execute_callback_)
{
if (!execute_thread_.joinable())
{
execute_thread_ = boost::thread(boost::bind(&SimpleActionServer::executeGoal, this));
}
}
// Call goal callback if set
if (goal_callback_)
{
goal_callback_(goal_msg);
}
}
}
// Process an incoming cancel message
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::processCancel(const robot_actionlib_msgs::GoalIDConstPtr& cancel_msg)
{
robot::log_info("[SimpleActionServer::processCancel] ===== ENTRY =====");
robot::log_info("[SimpleActionServer::processCancel] Cancel message ID: '%s'", cancel_msg->id.c_str());
robot::log_info("[SimpleActionServer::processCancel] Cancel message stamp: %ld.%09ld",
cancel_msg->stamp.sec, cancel_msg->stamp.nsec);
boost::lock_guard<boost::mutex> lock(state_mutex_);
robot::log_info("[SimpleActionServer::processCancel] Current goal ID: '%s'", current_goal_id_.id.c_str());
robot::log_info("[SimpleActionServer::processCancel] Current goal stamp: %ld.%09ld",
current_goal_id_.stamp.sec, current_goal_id_.stamp.nsec);
robot::log_info("[SimpleActionServer::processCancel] Current status: %d", current_status_.status);
// Check if this cancel request is for the current goal
bool should_cancel = false;
bool is_empty_id = (cancel_msg->id == "");
bool is_matching_id = (cancel_msg->id == current_goal_id_.id);
bool is_matching_stamp = (cancel_msg->stamp == current_goal_id_.stamp);
robot::log_debug("[SimpleActionServer::processCancel] Cancel check: empty_id=%s, matching_id=%s, matching_stamp=%s",
is_empty_id ? "true" : "false",
is_matching_id ? "true" : "false",
is_matching_stamp ? "true" : "false");
if (is_empty_id || (is_matching_id && is_matching_stamp))
{
should_cancel = true;
robot::log_info("[SimpleActionServer::processCancel] Cancel request matches current goal - will cancel");
if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE)
{
robot::log_info("[SimpleActionServer::processCancel] Goal is ACTIVE - setting preemption");
preempt_requested_ = true;
current_status_.status = robot_actionlib_msgs::GoalStatus::PREEMPTING;
robot::log_info("[SimpleActionServer::processCancel] Cancel requested for goal ID: %s", current_goal_id_.id.c_str());
robot::log_info("[SimpleActionServer::processCancel] Status changed to PREEMPTING");
}
else if (current_status_.status == robot_actionlib_msgs::GoalStatus::PENDING)
{
robot::log_info("[SimpleActionServer::processCancel] Goal is PENDING - rejecting it");
// Goal hasn't started yet, just reject it
current_status_.status = robot_actionlib_msgs::GoalStatus::REJECTED;
current_status_.text = "Goal cancelled before execution";
goal_.reset();
new_goal_available_ = false;
robot::log_info("[SimpleActionServer::processCancel] Goal cancelled before execution");
robot::log_info("[SimpleActionServer::processCancel] Status changed to REJECTED");
}
else
{
robot::log_info("[SimpleActionServer::processCancel] Goal status is %d - no action needed", current_status_.status);
}
}
else
{
robot::log_info("[SimpleActionServer::processCancel] Cancel request does NOT match current goal - ignoring");
robot::log_info("[SimpleActionServer::processCancel] Cancel ID '%s' != Current ID '%s'",
cancel_msg->id.c_str(), current_goal_id_.id.c_str());
}
// Call cancel callback if set
robot::log_debug("[SimpleActionServer::processCancel] Checking cancel_callback_: %s",
cancel_callback_ ? "set" : "null");
if (cancel_callback_)
{
robot::log_debug("[SimpleActionServer::processCancel] Calling cancel_callback_...");
try
{
cancel_callback_(cancel_msg);
robot::log_debug("[SimpleActionServer::processCancel] cancel_callback_ executed successfully");
}
catch (const std::exception& e)
{
robot::log_error("[SimpleActionServer::processCancel] EXCEPTION in cancel_callback_: %s", e.what());
}
}
robot::log_info("[SimpleActionServer::processCancel] ===== EXIT =====");
}
// Check if a new goal is available
template<class ActionSpec>
bool SimpleActionServer<ActionSpec>::isNewGoalAvailable()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
return new_goal_available_;
}
// Check if preemption has been requested
template<class ActionSpec>
bool SimpleActionServer<ActionSpec>::isPreemptRequested()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
return preempt_requested_;
}
// Accept a new goal
template<class ActionSpec>
typename SimpleActionServer<ActionSpec>::GoalConstPtr SimpleActionServer<ActionSpec>::acceptNewGoal()
{
robot::log_info("[SimpleActionServer::acceptNewGoal] ===== ENTRY =====");
boost::lock_guard<boost::mutex> lock(state_mutex_);
robot::log_debug("[SimpleActionServer::acceptNewGoal] new_goal_available_: %s",
new_goal_available_ ? "true" : "false");
robot::log_debug("[SimpleActionServer::acceptNewGoal] goal_ is %s",
goal_ ? "valid" : "null");
if (!new_goal_available_)
{
robot::log_warning("[SimpleActionServer::acceptNewGoal] No new goal available - returning null");
robot::log_info("[SimpleActionServer::acceptNewGoal] ===== EXIT (null) =====");
return GoalConstPtr();
}
// Accept the new goal
GoalConstPtr new_goal = goal_;
goal_.reset();
new_goal_available_ = false;
preempt_requested_ = false;
// Update status
current_status_.status = robot_actionlib_msgs::GoalStatus::ACTIVE;
current_status_.goal_id = current_goal_id_;
current_status_.text = "";
robot::log_info("[SimpleActionServer::acceptNewGoal] Goal accepted successfully");
robot::log_info("[SimpleActionServer::acceptNewGoal] Goal ID: %s", current_goal_id_.id.c_str());
robot::log_info("[SimpleActionServer::acceptNewGoal] Status changed to ACTIVE");
if (new_goal)
{
robot::log_info("[SimpleActionServer::acceptNewGoal] Goal position: x=%.3f, y=%.3f",
new_goal->target_pose.pose.position.x,
new_goal->target_pose.pose.position.y);
}
robot::log_info("[SimpleActionServer::acceptNewGoal] ===== EXIT (success) =====");
return new_goal;
}
// Set the action as succeeded
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::setSucceeded(const Result& result, const std::string& text)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE ||
current_status_.status == robot_actionlib_msgs::GoalStatus::PREEMPTING)
{
current_status_.status = robot_actionlib_msgs::GoalStatus::SUCCEEDED;
current_status_.text = text;
// Create and publish result
ActionResultPtr action_result = boost::make_shared<ActionResult>();
action_result->header.stamp = robot::Time::now();
action_result->status = current_status_;
action_result->result = result;
// Call result callback if set
if (result_callback_)
{
result_callback_(action_result);
}
// Clear goal
goal_.reset();
new_goal_available_ = false;
preempt_requested_ = false;
robot::log_info("[SimpleActionServer] Goal succeeded: %s", text.c_str());
}
}
// Set the action as aborted
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::setAborted(const Result& result, const std::string& text)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE ||
current_status_.status == robot_actionlib_msgs::GoalStatus::PREEMPTING)
{
current_status_.status = robot_actionlib_msgs::GoalStatus::ABORTED;
current_status_.text = text;
// Create and publish result
ActionResultPtr action_result = boost::make_shared<ActionResult>();
action_result->header.stamp = robot::Time::now();
action_result->status = current_status_;
action_result->result = result;
// Call result callback if set
if (result_callback_)
{
result_callback_(action_result);
}
// Clear goal
goal_.reset();
new_goal_available_ = false;
preempt_requested_ = false;
robot::log_warning("[SimpleActionServer] Goal aborted: %s", text.c_str());
}
}
// Set the action as preempted
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::setPreempted(const Result& result, const std::string& text)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE ||
current_status_.status == robot_actionlib_msgs::GoalStatus::PREEMPTING)
{
current_status_.status = robot_actionlib_msgs::GoalStatus::PREEMPTED;
current_status_.text = text;
// Create and publish result
ActionResultPtr action_result = boost::make_shared<ActionResult>();
action_result->header.stamp = robot::Time::now();
action_result->status = current_status_;
action_result->result = result;
// Call result callback if set
if (result_callback_)
{
result_callback_(action_result);
}
// Clear goal
goal_.reset();
new_goal_available_ = false;
preempt_requested_ = false;
robot::log_info("[SimpleActionServer] Goal preempted: %s", text.c_str());
}
}
// Publish feedback
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::publishFeedback(const Feedback& feedback)
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE)
{
ActionFeedbackPtr action_feedback = boost::make_shared<ActionFeedback>();
action_feedback->header.stamp = robot::Time::now();
action_feedback->status = current_status_;
action_feedback->feedback = feedback;
// Call feedback callback if set
if (feedback_callback_)
{
feedback_callback_(action_feedback);
}
}
}
// Get the current goal
template<class ActionSpec>
typename SimpleActionServer<ActionSpec>::GoalConstPtr SimpleActionServer<ActionSpec>::getCurrentGoal()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
return goal_;
}
// Get the current status
template<class ActionSpec>
robot_actionlib_msgs::GoalStatus SimpleActionServer<ActionSpec>::getCurrentStatus()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
return current_status_;
}
// Check if the server is active
template<class ActionSpec>
bool SimpleActionServer<ActionSpec>::isActive()
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
return active_;
}
// Get the action name
template<class ActionSpec>
std::string SimpleActionServer<ActionSpec>::getName() const
{
return name_;
}
// Execute the goal in a separate thread
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::executeGoal()
{
robot::log_info("[SimpleActionServer::executeGoal] ===== THREAD STARTED =====");
robot::log_info("[SimpleActionServer::executeGoal] Action server name: %s", name_.c_str());
robot::log_debug("[SimpleActionServer::executeGoal] execute_callback_ is %s",
execute_callback_ ? "set" : "null");
// Continuously process goals
while (active_)
{
robot::log_debug("[SimpleActionServer::executeGoal] Waiting for new goal...");
GoalConstPtr goal_to_execute;
// Wait for a new goal to be available
{
boost::unique_lock<boost::mutex> lock(state_mutex_);
robot::log_debug("[SimpleActionServer::executeGoal] Mutex lock acquired in executeGoal");
robot::log_debug("[SimpleActionServer::executeGoal] active_=%s, new_goal_available_=%s",
active_ ? "true" : "false",
new_goal_available_ ? "true" : "false");
// Wait until a new goal is available or server is stopped
while (active_ && !new_goal_available_)
{
robot::log_debug("[SimpleActionServer::executeGoal] Waiting on condition variable...");
goal_condition_.wait(lock);
robot::log_debug("[SimpleActionServer::executeGoal] Woke up from condition wait");
robot::log_debug("[SimpleActionServer::executeGoal] After wake: active_=%s, new_goal_available_=%s",
active_ ? "true" : "false",
new_goal_available_ ? "true" : "false");
}
if (!active_)
{
robot::log_info("[SimpleActionServer::executeGoal] Server is not active - exiting thread");
break;
}
// Accept the new goal
if (new_goal_available_)
{
robot::log_info("[SimpleActionServer::executeGoal] New goal available - accepting it...");
// Release lock before calling acceptNewGoal() to avoid deadlock
// (acceptNewGoal() will acquire its own lock)
lock.unlock();
goal_to_execute = acceptNewGoal();
robot::log_info("[SimpleActionServer::executeGoal] Goal accepted: %s",
goal_to_execute ? "valid" : "null");
}
else
{
robot::log_warning("[SimpleActionServer::executeGoal] Woke up but new_goal_available_ is false!");
lock.unlock();
}
}
// Execute the goal callback
if (goal_to_execute)
{
robot::log_info("[SimpleActionServer::executeGoal] Executing goal callback...");
robot::log_info("[SimpleActionServer::executeGoal] Goal position: x=%.3f, y=%.3f",
goal_to_execute->target_pose.pose.position.x,
goal_to_execute->target_pose.pose.position.y);
if (execute_callback_)
{
try
{
robot::log_info("[SimpleActionServer::executeGoal] Calling execute_callback_...");
execute_callback_(goal_to_execute);
robot::log_info("[SimpleActionServer::executeGoal] execute_callback_ completed");
}
catch (const std::exception& e)
{
robot::log_error("[SimpleActionServer::executeGoal] EXCEPTION in execute_callback_: %s", e.what());
}
}
else
{
robot::log_error("[SimpleActionServer::executeGoal] execute_callback_ is null - cannot execute goal!");
}
}
else
{
robot::log_warning("[SimpleActionServer::executeGoal] goal_to_execute is null - skipping execution");
}
}
robot::log_info("[SimpleActionServer::executeGoal] ===== THREAD EXITING =====");
}
// Thread function to publish status periodically
template<class ActionSpec>
void SimpleActionServer<ActionSpec>::statusPublishThread()
{
double rate = status_publish_rate_;
robot::Duration sleep_duration(1.0 / rate);
while (active_)
{
{
boost::lock_guard<boost::mutex> lock(state_mutex_);
// Create status array
robot_actionlib_msgs::GoalStatusArrayPtr status_array =
boost::make_shared<robot_actionlib_msgs::GoalStatusArray>();
status_array->header.stamp = robot::Time::now();
status_array->status_list.clear();
if (current_status_.status != robot_actionlib_msgs::GoalStatus::PENDING ||
!current_goal_id_.id.empty())
{
status_array->status_list.push_back(current_status_);
}
// Call status callback if set
if (status_callback_)
{
status_callback_(status_array);
}
}
// Sleep
robot::Time::sleepUntil(robot::Time::now() + sleep_duration);
}
}
} // namespace move_base
// Explicit template instantiation for MoveBaseAction
// This is required because template method definitions are in .cpp file
template class move_base::SimpleActionServer<robot_move_base_msgs::MoveBaseAction>;