187 Commits

Author SHA1 Message Date
b9eec680ed fix: them robot_sensor_ports + route_graph vao danh sach build standalone truoc sbpl_lattice_planner
sbpl_lattice_planner (3fff3b1) link ca hai package nay (route graph corridor) nhung root
CMakeLists.txt chua khai pnkx_add_test_package cho chung - build standalone
(PNKX_NAV_CORE_BUILD_TEST_PACKAGES) vo ngay o find_package/target_link_libraries cua no.
2026-09-22 15:54:27 +07:00
c52cbe5734 feat: schema route graph (Voronoi corridor) + anytime ARA* cho SBPLLatticePlanner, BaseNavigation::addRouteGraph
- navigation.h: them virtual addRouteGraph(topic, RouteGraph) - host day graph bien dich san tu
  map vao ke ben addStaticMap; khong co reader thi moi planner hanh xu nhu cu.
- config/sbpl_global_params.yaml: them initial_epsilon/final_epsilon/eps_step/repair_time/
  return_first_solution (ARA* ReplanParams, pha 0) va khoi voronoi_corridor (12 khoa - khoanh
  search trong dai quanh tuyen graph cho goal xa, hard/soft, nguong widen/fallback).
- config/voronoi_route_params.yaml (moi): tham so dung graph (GVD) + dai hanh lang cho tool
  voronoi_route_compile va RBApp luc copy map - ban mac dinh dong goi kem goi.
- Bump submodule common_msgs (RouteGraph message).

Phu thuoc: code doc cac khoa nay o Test/sbpl_lattice_planner + Test/route_graph (chua co repo/
remote, dang giu lai). Config di truoc code khong hai gi - key la khong ai doc thi bi bo qua.
2026-09-22 15:30:55 +07:00
5fe9a188a4 config: bo sung schema/comment snapshot_for_readers + debug_plan/debug_grid_window
Dong bo schema tu cay sim (Test/move_base2/config/runtime) sang cay nav core dung khi chay
ngoai move_base2. costmap_global_params.yaml: comment snapshot_for_readers (gia tri giu
false, cay nay chua do). sbpl_global_params.yaml: khai tuong minh allow_unknown (truoc
ngam default true khong ghi ra), them debug_plan/debug_grid_window (mac dinh bat/0) cho log
chan doan makePlan fail moi o sbpl_lattice_planner. Chi them schema + comment, khong doi
gia tri da tune.
2026-09-18 13:33:07 +07:00
8d27305eac config(priest): dong bo blend_dev_gate_obstacles + nguong dev 0.15/0.30 (do 17/9) 2026-09-17 09:45:50 +07:00
5e7fa3ccf6 config: dong bo schema hybrid_mode + tracker/blend cho priest_local_planner
Sync tu Test/move_base2/config/runtime (cay sim, hybrid_mode=1) va
Test/priest_local_planner/cfg (robot that, hybrid_mode=0) — chi dong bo
KHOA + comment, hybrid_mode giu 0 (tat) o day cho toi khi chay thu. Xem
doc/HYBRID_TRACK_AVOID_PLAN.md o priest_local_planner.
2026-09-16 18:51:26 +07:00
198860a79e test(robot_cpp): tat than NodeHandleTest (WIP, chua bat lai)
Toan bo cac loi goi testXxx() trong try{} cua main() bi comment out.
NodeHandleTest van dang ky qua add_test nen ctest se bao PASS gia (khong
con goi test nao that su). Giu nguyen theo yeu cau - can bat lai hoac go
dang ky add_test truoc khi dua ket qua NodeHandleTest vao bao cao gi ca.
2026-09-15 15:07:51 +07:00
18e1aa9fe3 chore: bump common_msgs submodule pointer
a07145a -> b3e0857, 2 commit da push tren remote common_msgs (Imu tu
chua header sau khi bo ROS traits/serializer khoi Accel va Imu).
2026-09-15 15:07:44 +07:00
384e668995 docs: huong dan nhung nav core vao host C++ thuan
doc/cpp_host_guide.md - danh cho host noi thang voi BaseNavigation,
tach voi NAV_C_API_2_GUIDE.md (lop extern "C" cho .NET). Neu ranh gioi
ABI qua boost::dll giua ba host (amr_control, libnavigation_c_api.so,
host tu viet) va yeu cau rebuild dong bo khi sua navigation.h.
2026-09-15 15:07:44 +07:00
454d5389bc config: tune hybrid/priest/recovery params sau do 27/8-14/9
- hybrid docking: global_plan_viapoint_sep 0.2 -> 0.12 (do 27/8: sep
  0.2 khien khop noi cong->thang mang herr -0.10 rad, lech ngang phong
  toi 30mm; ha xuong khop sac hon ~40%). Ghi lai lich su do de khoi lap
  lai thu nghiem 26/8 (sep 0.2 -> 0.3 lam xau ~50%).
- priest: them nhom key on dinh nghiem doan thoang (lateral_std_clear_*,
  clear_residual, clear_streak_cycles - do 28/8 omega nhay khi thoang),
  hysteresis/delay cho horizon (horizon_hysteresis_buckets,
  horizon_restore_delay_cycles - tranh doi hinh ca batch khi nhay bucket
  hoac hut 1 chu ky do arc), nhom infeasible_residual/streak/cooldown
  (solver tu khai bat kha thi, TAT tren robot that cho toi khi chay
  thu), va nhom accel_comfort/jerk cho lenh xuat em hon max_acceleration
  cua solver.
- recovery: them trigger collision -> detour_path (2026-09-04, truoc do
  rong = guard khong vu trang); go 4 key planning_distance/sample_step/
  rejoin_clearance/max_rejoin_distance da het tac dung tu khi detour
  chuyen sang lap lai ca duong; khai lock_costmap=true tuong minh (gia
  tri = default cu, hanh vi khong doi).
2026-09-15 15:07:37 +07:00
f4a5c96c3c feat(nav): emergency stop latch xuyen BaseNavigation + C API
BaseNavigation them 2 virtual moi o CUOI vtable: emergency() va
clearEmergency(), khong doi so cua method cu (ABI: rebuild dong bo
libmove_base.so + C API + moi host). State them EMERGENCY = 14, append
cuoi enum nen gia tri cu khong doi (ca ben C mirror nav_c_api.h).

emergency(): lenh 0 ngay, huy chang dang chay (bao CANCELLED dung 1
lan), xoa hang doi mission, chot state. Hieu luc TRUOC KHI ham tra ve
tren chinh thread goi (getTwist/getFeedback thay doi ngay ca khi
control thread dang block trong plugin); don dep that (planner,
recovery, action, mission layer) chay o chu ky ke tiep cua control
thread. Trong luc chot: moveTo/executeInstantActions bi tu choi,
pause/resume/cancel bi bo qua. clearEmergency() dua ve PENDING, khong
tu chay lai - host phai gui goal moi.

C API: navigation_emergency() / navigation_clear_emergency() trong
nav_c_api_2.h, cap nhat guide va test_convertor cho enum EMERGENCY moi.
2026-09-15 15:07:25 +07:00
374a09c821 fix(robot_cpp): per-call-site throttle window trong log_*_throttle
static local dung chung 1 window cho ca ham nen nhieu diem goi giam len
nhau (controller_runner co 11 diem goi log_error_throttle, diem no in
truoc se cam diem kia im ca cua so). Chuyen sang bang lock-free keyed
theo return address (__builtin_return_address) + format pointer, moi
call site giu window rieng.

Kem theo:
- color_enabled chuyen std::atomic<bool>, tranh data race khi control
  loop / sensor callback / planner thread cung goi log.
- is_color_supported() cache ket qua qua std::call_once, bo getenv() lap
  lai moi dong log trong control loop.
- NaN/am trong throttle gio la "khong throttle" thay vi cam log vinh
  vien (NaN truoc day fail phep so >= mai mai).
- them test_console_throttle.cpp + dang ky ConsoleThrottleTest qua
  add_test trong CMakeLists.txt.
2026-09-15 15:07:13 +07:00
2b0993bd53 feat: lifecycle contract for move_base2 cancel/pause/resume + component status probe
- robot_nav_core::Preemptable (new header): mixin a BaseGlobalPlanner may
  implement to accept a preempt() cut during makePlan(), no vtable break for
  planners that don't.
- move_base_core::component_status_probe.h (new): ComponentStatusEntry +
  boost::dll alias name ("MoveBaseComponentStatus") a host can probe to read
  per-component phase (idle/busy/stopping/paused/hung) without linking
  move_base2 directly.
- nav_c_api_2.h/.cpp: NavComponentStatus struct and
  navigation_get_component_status() — lazy dlsym of the probe above, returns
  0 rows if the loaded .so doesn't export it. Doc: PREEMPTING is now a
  truthful "still winding down" state, not "acknowledged", and a host must
  poll to quiescence rather than resend immediately.
- move_base_common_params.yaml: settle_timeout, stopped_measured_linear/
  angular_eps, watchdog_period + per-component stall budgets (Vietnamese
  comments, matches the schema). Also fixes a wrong comment on
  max_planning_retries: 0 means escalate on the FIRST failure, not
  "unlimited" (-1 is unlimited) — the inverted comment likely caused the
  dev machine's max_planning_retries: 0.

Root cause and measurements: Test/move_base2/docs/PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md.

Excluded from this commit (pre-existing, unrelated): config/hybrid_local_planner_params.yaml,
config/priest_local_planner_params.yaml, config/recovery_behaviors_params.yaml (dock/PRIEST
tuning, dated before this work), src/Libraries/common_msgs and src/Libraries/costmap_2d
(submodule pointer bumps from other work), src/Libraries/robot_cpp console throttle changes
and doc/cpp_host_guide.md (separate, unrelated task).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-12 22:06:17 +07:00
37e44eb571 fix(nav_2d): xoá UB trong TwoPointsPlanner và pointer hoang trong tf_help
- two_points_planner.cpp: nhánh suy biến (start == goal, ca quay tại chỗ)
  đọc `theta` chưa khởi tạo trước khi dùng trong cos()/sin(). Khởi tạo bằng
  yaw hiện tại của start; comment nêu rõ vì sao chặng rotate chạm nhánh này.

- tf_help.cpp: `canTransform()` nhận `std::string *error_msg` chưa khởi
  tạo — tf3 ghi qua con trỏ đó khi transform thất bại, tức ghi vào vùng nhớ
  bất kỳ. Đổi sang std::string thật + log tên hai frame khi thất bại.

- tf_help.cpp: `transformPose()` gọi transform() rồi `return true` vô điều
  kiện ở cả nhánh chính lẫn nhánh ExtrapolationException — lookup hỏng để
  lại out_pose mặc định (yaw 0, trông như hướng thật) mà vẫn báo thành
  công. Trả thẳng kết quả của transform().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 10:45:44 +07:00
09799dffdd api: the sensor key is a topic, so call it one
Five add* functions each named the same argument differently - map_name,
laser_scan_name, point_cloud_name, point_cloud2_name, odometry_name - while
addDepthCameraData already called it topic. The get* and remove* families
disagreed in the same way, though they take the same key.

It is not a label. It has to match the topic a costmap layer names in
observation_sources, and the entry in sensor_store_params.yaml. A key matching
nothing is accepted in silence and read by nobody, which surfaces as an empty
costmap with no error anywhere - so the parameter name is the first place to
say what the string is for.

Fourteen declarations now say topic. A parameter name has no effect at a call
site, so this touches no host: no ABI change, nothing to rebuild in lockstep.

addDepthCameraData is the one add* taking a const pointer rather than a value,
and the header now says why, because the next reader will otherwise see an
inconsistency and even it up. Every other sensor is reduced by the host before
it arrives - a laser scan is 5.5 KB, a depth cloud is voxel-filtered from
3.26 MB to 24 KB - and copying all four together costs about 25 microseconds
per second of runtime, measured against a running simulation. A depth image
arrives whole at 398 KB because the voxel layer needs the full frame for its
clearing frustum, and copying that costs roughly 250 times the other four
combined. That is what earns a pointer, and a 5 KB scan does not.
2026-08-27 12:05:53 +07:00
ab3a6c68c7 config: bring the nav core config tree up to the current planner schema
hybrid_local_planner_params.yaml gains 120 keys and drops 12, including a whole
HybridDockingLocalPlanner block that was not here at all. The additions are the
two-tier velocity limits the planner has been reading for a while - acc_lim_*
bounding the DWA sampling window, output_acc_lim_*/output_decel_lim_* clamping
the command on its way out - plus min_velocity, min_yawrate and the blend
distances. The removed keys are the old rejoin_* group, which no longer exists
in the planner.

A config tree that names keys the planner does not read, and omits keys it
does, fails silently: the plugin falls back to its C++ defaults and nobody is
told. That is the "works on my machine, not on the robot" shape.

The comments are rewritten around what the two tiers actually decide, because
the split is not obvious from the key names: DWA owns forward velocity and is
the only tier that can command a turn in place, while Pure Pursuit only steers,
through omega = |v| * pp_weight_omega * sin(err) / lookahead - a law that
degenerates at v = 0, which is why steering authority returns to DWA below
pp_min_steering_velocity.

mppi_local_planner_params.yaml is real tuning: goal tolerances tightened from
0.10/0.10 to 0.03/0.02, the control weights zeroed, goal_capture_radius and
goal_overshoot_margin added, and the stale LocalPlannerAdapter block dropped.

move_base_common_params.yaml is a typo in a comment - #ybridLocalPlanner. The
active value is untouched.

All three parse; the key sets were compared with a YAML load rather than by eye.
2026-08-27 09:35:56 +07:00
48db28b4d2 build: bump costmap_2d và data_convert sau khi dọn dependency PCL
costmap_2d  d60e1e8 -> af66991  (bỏ hẳn PCL, gói không dùng)
data_convert f23037b -> 6708cdf  (thu hẹp còn COMPONENTS common)

Cả hai nhằm cắt chuỗi PCL -> VTK -> VTK::mpi -> MPI::MPI_C, thứ làm
`cmake ..` gãy ở generate step trên robot aarch64 có VTK 9.1 build kèm MPI.
Root project khai LANGUAGES CXX nên find_package(MPI COMPONENTS C) không bao
giờ thành công.
2026-08-25 12:39:14 +07:00
e2f2f55660 feat(dock_planner): bump submodule và bổ sung schema động học vào config
Con trỏ submodule dock_planner: a301987 -> 1f04a95 (mô hình động học
differential/ackermann + maneuver straight-pivot-straight).

config/dock_global_params.yaml thêm ba khoá mới khớp với loader:
- kinematics/model: ackermann | differential
- kinematics/minimum_turning_radius: chỉ dùng khi model=differential
- maneuver/pivot_fallback_extension, maneuver/pivot_safety_margin

Giá trị mặc định giữ nguyên hành vi cũ: model=ackermann,
pivot_fallback_extension=0.0 (tắt maneuver mới). Comment đầu file mô tả lại
ba kiểu đường và thứ tự planner thử dựng.
2026-08-25 12:15:39 +07:00
2f204f88d2 chore: bump costmap_2d — tên thread map-update cho pidstat/top
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 10:24:04 +07:00
3a991c2e2a config: khoá metrics/debug/snapshot cho costmap (mặc định tắt) + bump costmap_2d
Đồng bộ schema từ cây move_base2/config/runtime: performance_metrics_enabled,
performance_metrics_period, debug_level, snapshot_for_readers — bản này là
default trung tính nên toàn bộ để tắt/0/false; cây đang chạy khi test là
move_base2/config/runtime (ở đó metrics+snapshot bật).

Bump submodule costmap_2d 3196a19 -> 84c8378: debug metrics updateMap +
snapshot API cho reader (chi tiết ở log submodule).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 20:19:59 +07:00
fccd377505 config: cập nhật comment goal_blocked_check_radius — dò đĩa nửa thân (priest 6d78767)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 21:36:09 +07:00
5456dfef3b config: khoá goal_blocked_check_radius (0 = tắt) cho priest — đồng bộ 8182297
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 21:18:32 +07:00
de677ccc14 config: khoá hold_timeout 10 s cho priest — đồng bộ 245d656
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 21:01:07 +07:00
970dc165cd config: khoá weight_velocity_deficit (mặc định 0 = tắt) — đồng bộ priest 73bbdd1
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:16:17 +07:00
ab3ee1ae97 config: khoá head_slowdown_inscribed_scale (mặc định 1.0) — đồng bộ priest 2455707
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 16:05:21 +07:00
f00fb6a887 config: comment debug_command priest theo format mới (priest eb413f5)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 15:30:25 +07:00
6118cb7b7b config: comment head slowdown — trọng số độ-gần-thời-gian (priest ea05d0d)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 15:25:51 +07:00
9da19da7e5 config: head slowdown priest sang bản so tương đối + head_slowdown_release_cycles (vẫn TẮT)
Đồng bộ schema với priest_local_planner 6d75b73.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 15:20:48 +07:00
98efe89312 feat(config): khoá side_switch_feasible_res + head_slowdown cho priest (mặc định TẮT)
Đồng bộ schema với priest_local_planner 50375f2 — guard đổi bên theo tính
thực thi + giảm tốc theo đầu quỹ đạo. Giữ tắt tới khi thử trên robot.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 15:11:00 +07:00
87cbcf8957 feat(config): khoá obstacle_time_discount cho priest (mặc định TẮT 0.0/1.0)
Đồng bộ schema với priest_local_planner 8405e29 — co ellipse vật cản theo
thời gian horizon, trị vòng rộng đầu mission. Giữ tắt tới khi thử trên robot.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 13:30:27 +07:00
802a528d85 config: đồng bộ schema khoá rotate_settle_yawrate cho PriestLocalPlanner (tắt)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 10:45:45 +07:00
210ba931f1 config: đồng bộ schema khoá side_infeasible_res cho PriestLocalPlanner (tắt)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 10:19:33 +07:00
3d630d0bad config: cập nhật comment rotate_to_path cho PriestLocalPlanner
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 10:06:05 +07:00
5ed80df405 config: đồng bộ schema khoá rotate_to_path_enabled cho PriestLocalPlanner (tắt)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 09:53:22 +07:00
21886bc2fb config: đồng bộ schema khoá start_violation_ramp_time cho PriestLocalPlanner (tắt)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 09:37:39 +07:00
4a66099492 config: đồng bộ schema khoá t_fin_min cho PriestLocalPlanner (tắt)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 22:59:05 +07:00
64929b60cf config: đồng bộ schema khoá omega_ff_min_speed cho PriestLocalPlanner (tắt)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 22:35:09 +07:00
0ff610eed7 config: đồng bộ schema khoá goal_approach_distance cho PriestLocalPlanner (tắt)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 22:26:40 +07:00
b43d1b94df config: đồng bộ schema khoá xy_latch_release_factor cho PriestLocalPlanner (tắt)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 22:10:59 +07:00
b979276e63 config: đồng bộ schema 3 khoá mới của PriestLocalPlanner (tắt)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 21:56:53 +07:00
a230e0665f config: đồng bộ schema proj_early_exit + footprint circles cho PriestLocalPlanner (tắt)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 21:37:16 +07:00
fce619feae config: đồng bộ schema khoá side_hysteresis cho PriestLocalPlanner (tắt)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 20:56:26 +07:00
64863c2286 config: đồng bộ schema khoá obstacle_corridor cho PriestLocalPlanner (tắt)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 20:31:52 +07:00
14e0fdf720 config: đồng bộ schema khối debug + cổng va chạm cho PriestLocalPlanner
Chỉ thêm khoá mới (debug_level 0, collision_check_enabled false) — không đổi
giá trị tuning nào; đồng bộ tập khoá với cây move_base2/config/runtime.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 20:27:27 +07:00
492cafabbf chore: bump con trỏ submodule dock_planner 2026-08-15 13:38:11 +07:00
9009564f56 docs: viết lại comment cây config bằng tiếng Việt, bỏ ba khoá chết
dock_global_params bỏ maneuver/straight_lateral_tolerance,
maneuver/straight_yaw_tolerance và terminal/direction: DockPlannerConfig::load
không đọc khoá nào trong số đó, riêng terminal/direction còn gợi ý sai rằng chiều
đoạn cuối cấu hình được trong khi nó được suy ra từ phía robot đứng. Bổ sung
direct_entry_min_curve_room và straight_length. Không đổi giá trị nào khác.
2026-08-15 13:38:03 +07:00
4a302517c5 chore: bump the submodule pointers
custom_planner, dock_planner, common_msgs, costmap_2d, data_convert, geometry2,
laser_geometry, robot_time and voxel_grid.
2026-08-15 13:09:39 +07:00
d080e1bbd5 docs: update the C API guide and the C# integration report 2026-08-15 13:09:39 +07:00
599bce1731 config: update the installed planner profiles to the current schema
custom_global_params documents the CustomPlanner namespace and drops the stale
SBPL keys; dock_global_params moves to the straight-terminal DockPlanner schema
and keeps its 1.0 m terminal padding.
2026-08-15 13:09:39 +07:00
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
58d925f2be fix 2026-03-26 14:42:26 +07:00
ba503eca85 fix giam toc 2026-03-25 10:33:01 +00:00
ea41848a4a fix gentrajectory 2026-03-25 15:35:15 +07:00
69823442f9 update 2026-03-24 15:26:00 +07:00
6b4d630d09 fix speed 2026-03-24 08:16:56 +00:00
5375a5ea84 update 2026-03-24 08:05:05 +00:00
483ca24418 fix 2026-03-23 17:55:50 +07:00
c1e00fe76d fix bug 2026-03-23 15:06:57 +07:00
472cc4d02c fix 2026-03-23 14:36:59 +07:00
36ce68abf1 update 2026-03-23 14:27:24 +07:00
f7fa96ff8b update plan when docking 2026-03-22 17:19:37 +07:00
d0ad2d0e21 fix move base 2026-03-22 08:57:09 +00:00
5583b3e0f2 fix load path so 2026-03-22 04:42:26 +00:00
7baa7000b8 update path 2026-03-22 09:16:05 +07:00
c05a3e4439 fix bug 2026-03-21 19:04:32 +07:00
d38f6b3954 update 2026-03-20 16:06:47 +07:00
9a4bb95c4c update param yaml 2026-03-20 07:09:05 +00:00
76ee97f2ec change PNKX_NAV_CORE_LIBRARY_PATH 2026-03-20 04:43:29 +00:00
aa63caa188 fix bug docking 2026-03-20 11:24:00 +07:00
e90a84c229 update 2026-03-19 10:34:46 +00:00
ae32077fe2 update 2026-03-19 15:24:09 +07:00
180a646e35 add docking to 2026-03-19 04:02:08 +00:00
98ce71eb69 update make install 2026-03-19 10:08:46 +07:00
c36f3737ba Merge branch '3.0' of https://git.pnkr.asia/HiepLM/pnkx_nav_core into 3.0 2026-03-19 09:40:33 +07:00
f0d987da39 update Kalman Filter 2026-03-19 09:40:32 +07:00
6d3af679a9 add max speed 2026-03-18 07:38:51 +00:00
1c12239478 update 2026-03-17 10:02:02 +00:00
3f1f762f9b add module laser_filter 2026-03-17 10:01:48 +00:00
ddb7df7c50 fix bug isQuaternionValid of Goal 2026-03-13 10:35:53 +07:00
75cbf5a7ef update thuat toan pp 2026-03-12 10:29:55 +07:00
ae2f647fc9 fix 2026-03-11 15:11:59 +07:00
9e7d98934d fix robot_time 2026-03-11 14:57:31 +07:00
66d26e4f22 Update robot_time submodule pointer 2026-03-11 07:32:21 +00:00
7512b6261a fix hiep 2 2026-03-11 07:18:54 +00:00
85355581d1 fix hiep 2026-03-11 07:12:26 +00:00
7afd85e2c6 update 2026-03-11 03:26:15 +00:00
4617ce85b6 update 2026-03-04 09:43:39 +00:00
a1cc2fccb1 add console_brigde 2026-03-03 09:08:33 +00:00
57caf8d213 update build arm64 2026-03-03 08:20:01 +00:00
5550e1cf3b update cost_map2d 2026-03-03 07:27:55 +00:00
b690e93650 update 2026-03-03 07:24:12 +00:00
06c2d01b4a update 2026-03-02 07:50:30 +00:00
ff8a90cbaa update 2026-02-27 06:45:35 +00:00
83f0e85e4a update 2026-02-26 11:12:07 +00:00
ab3e65de1b update 2026-02-26 10:12:04 +00:00
34cabd2083 update 2026-02-26 14:55:46 +07:00
b7e4c73c14 fixbug 2026-02-25 09:14:09 +07:00
95c6fe0f1e update 24/2 2026-02-24 14:39:49 +07:00
5069931a87 update pnkx_nav_core/src/Libraries/xmlrpcpp 2026-02-10 14:40:29 +07:00
99f014e14c update c_api 2026-02-10 14:39:43 +07:00
3f3425228c update tf3 2026-02-07 11:06:51 +07:00
81714a242d delete console_brigde 2026-02-06 10:15:50 +00:00
5e2f7bc712 delete tf3 2026-02-06 15:55:03 +07:00
c0ceccf32c update 2026-02-06 15:54:35 +07:00
6e320bbe5c update rotate to goal 2026-02-05 16:58:55 +07:00
bf74ae84ba common_msgs branch main 2026-02-05 07:18:53 +00:00
a43b714f01 update 5/2 2026-02-05 14:13:40 +07:00
cab5655769 update c_api 2026-02-04 14:33:51 +07:00
fd022bd9d7 add so file 2026-02-04 03:59:19 +00:00
7b3c5b8d5f update 4/2 2026-02-04 09:31:56 +07:00
15f842d703 update 2/2 2026-02-02 14:02:25 +07:00
1fa6af01fd done thuat toan 2026-01-28 17:43:50 +07:00
85789855a8 update thuat toan moi 2026-01-28 10:54:04 +07:00
620db96de0 update 28/2 2026-01-28 09:08:55 +07:00
575e190988 update 2026-01-21 16:00:36 +07:00
3f93370462 update 2026-01-16 17:48:57 +07:00
ebda1f81a1 update 2026-01-16 15:13:14 +07:00
0f58db3481 uodate 2026-01-14 17:53:27 +07:00
6549425279 update 2026-01-14 10:26:27 +07:00
57b77ac14b update 2026-01-13 14:30:22 +07:00
145fb2088e update 2026-01-12 15:49:25 +07:00
f5e7e1f1e0 update 2026-01-09 10:39:30 +07:00
a3e5168d88 update from HiepLM 2026-01-08 10:36:05 +07:00
c7e65910eb Loi 2026-01-07 17:04:02 +07:00
6054f72ba8 update for ROS 2026-01-07 17:02:59 +07:00
768573b2bb update for ROS 2026-01-07 17:01:51 +07:00
ca9e100bd9 update ros 2026-01-07 09:28:31 +07:00
11b7c4a20d update ifdefine 2026-01-05 18:55:45 +07:00
2831959056 update 2026-01-05 18:35:31 +07:00
5eb11f233f test 2026-01-05 18:29:34 +07:00
bd6aaac9d4 update 2026-01-05 18:18:12 +07:00
3ee1346873 update 2026-01-05 17:17:53 +07:00
9b27b9d731 update hieplm 2026-01-05 13:38:02 +07:00
a471130273 update 2026-01-05 10:52:57 +07:00
7f05ee86a0 update 2026-01-05 10:04:13 +07:00
6276f7aaab ad other robot_cpp 2026-01-05 09:56:31 +07:00
6706e1e9fb delete robot_cpp 2026-01-05 09:56:18 +07:00
a50f91d85a add robot_cpp 2026-01-05 09:46:29 +07:00
29c0f2154c Remove robot_cpp submodule 2026-01-05 09:38:46 +07:00
f72998026e update 2025-12-31 16:41:39 +07:00
3d28ae13dc update costmap_2d 2025-12-31 11:17:10 +07:00
596e067050 update 2025-12-30 19:09:12 +07:00
82804ff93a Hiep update 2025-12-30 10:45:58 +07:00
3e8b4db091 update 2025-12-30 10:43:50 +07:00
aa17000951 nham 2025-12-30 10:27:22 +07:00
82afc4c203 update 2025-12-30 10:25:25 +07:00
dad2726eb1 sua docking 2025-12-30 10:00:20 +07:00
e12033556b sua ten file 2025-12-30 09:58:57 +07:00
92fedb1ee8 update 2025-12-30 09:11:56 +07:00
63cb260cb2 update 2025-12-30 09:08:41 +07:00
4962cfbf49 update 2025-12-29 18:23:11 +07:00
18b0f46c64 add module https://git.pnkr.asia/DuongTD/xmlrpcpp.git 2025-12-29 18:17:56 +07:00
dad149d2cb update 2025-12-29 18:01:53 +07:00
4dc37109eb update robot_cpp 2025-12-29 17:50:33 +07:00
6bd0600eb8 update 2025-12-29 17:44:08 +07:00
c220246618 update xmlrpcpp 2025-12-29 17:21:04 +07:00
e7fdc0018d update robot_time 2025-12-29 17:18:03 +07:00
26da8dbc51 update robot_cpp 2025-12-29 17:14:08 +07:00
cbdf8e6525 update 2025-12-29 17:10:32 +07:00
a09cd3d98b update package 2025-12-29 17:05:37 +07:00
9a3e3123c0 add package 2025-12-29 16:40:55 +07:00
461 changed files with 32358 additions and 16112 deletions

2
.gitignore vendored
View File

@@ -420,3 +420,5 @@ FodyWeavers.xsd
build
install
devel

13
.gitmodules vendored
View File

@@ -7,9 +7,6 @@
[submodule "src/Libraries/geometry2"]
path = src/Libraries/geometry2
url = https://git.pnkr.asia/DuongTD/geometry2.git
[submodule "src/Libraries/xmlrpcpp"]
path = src/Libraries/xmlrpcpp
url = https://git.pnkr.asia/DuongTD/xmlrpcpp.git
[submodule "src/Libraries/laser_geometry"]
path = src/Libraries/laser_geometry
url = https://git.pnkr.asia/DuongTD/laser_geometry.git
@@ -22,13 +19,15 @@
[submodule "src/Libraries/data_convert"]
path = src/Libraries/data_convert
url = https://git.pnkr.asia/DuongTD/data_convert.git
[submodule "src/Libraries/robot_cpp"]
path = src/Libraries/robot_cpp
url = http://git.pnkx/HiepLM/robot_cpp.git
[submodule "src/Algorithms/Packages/global_planners/custom_planner"]
path = src/Algorithms/Packages/global_planners/custom_planner
url = https://git.pnkr.asia/DuongTD/custom_planner.git
[submodule "src/Algorithms/Packages/global_planners/dock_planner"]
path = src/Algorithms/Packages/global_planners/dock_planner
url = https://git.pnkr.asia/DuongTD/dock_planner.git
[submodule "src/Libraries/xmlrpcpp"]
path = src/Libraries/xmlrpcpp
url = https://git.pnkr.asia/DuongTD/xmlrpcpp.git
[submodule "src/Libraries/laser_filter"]
path = src/Libraries/laser_filter
url = https://git.pnkr.asia/DuongTD/laser_filter.git

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
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
```

View File

@@ -51,6 +51,7 @@ sudo apt-get install -y \
libyaml-cpp-dev \
libpcl-dev \
libgoogle-glog-dev
sudo apt install liborocos-kdl-dev
# Optional: Cài đặt Google Test (nếu muốn build tests)
sudo apt-get install -y libgtest-dev

View File

@@ -30,10 +30,6 @@ message(STATUS "========================================")
# Build các packages theo thứ tự phụ thuộc
# 1. Core libraries (header-only hoặc base libraries)
if (NOT TARGET tf3)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Libraries/tf3)
endif()
if (NOT TARGET robot_time)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Libraries/robot_time)
endif()
@@ -78,80 +74,169 @@ if (NOT TARGET robot_nav_2d_utils)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Libraries/robot_nav_2d_utils)
endif()
if (NOT TARGET nav_core)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Cores/nav_core)
if (NOT TARGET laser_filter)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Libraries/laser_filter)
endif()
if (NOT TARGET robot_nav_core)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Cores/robot_nav_core)
endif()
if (NOT TARGET nav_grid)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Libraries/nav_grid)
endif()
if (NOT TARGET nav_core2)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Cores/nav_core2)
if (NOT TARGET robot_nav_core2)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Cores/robot_nav_core2)
endif()
if (NOT TARGET nav_core_adapter)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Cores/nav_core_adapter)
if (NOT TARGET robot_nav_core_adapter)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Cores/robot_nav_core_adapter)
endif()
if (NOT TARGET move_base_core)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Cores/move_base_core)
endif()
# if (NOT TARGET mkt_msgs)
# add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Libraries/mkt_msgs)
# endif()
# if (NOT TARGET angles)
# add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Libraries/angles)
# endif()
# if (NOT TARGET kalman)
# add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Libraries/kalman)
# endif()
# if (NOT TARGET score_algorithm)
# add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Cores/score_algorithm)
# endif()
# if (NOT TARGET mkt_plugins)
# add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Libraries/mkt_plugins)
# endif()
# if (NOT TARGET mkt_algorithm)
# add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Libraries/mkt_algorithm)
# endif()
# if (NOT TARGET two_points_planner)
# add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Packages/global_planners/two_points_planner)
# endif()
# if (NOT TARGET custom_planner)
# add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Packages/global_planners/custom_planner)
# endif()
# if (NOT TARGET dock_planner)
# add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Packages/global_planners/dock_planner)
# endif()
# if (NOT TARGET pnkx_local_planner)
# add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Packages/local_planners/pnkx_local_planner)
# endif()
# 2. Main packages (phụ thuộc vào cores)
message(STATUS "[move_base] Shared library configured")
if (NOT TARGET move_base)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Packages/move_base)
if (NOT TARGET mkt_msgs)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Libraries/mkt_msgs)
endif()
# C API for .NET/C# integration
if (NOT TARGET navigation_c_api)
if (NOT TARGET angles)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Libraries/angles)
endif()
if (NOT TARGET kalman)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Libraries/kalman)
endif()
if (NOT TARGET score_algorithm)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Cores/score_algorithm)
endif()
if (NOT TARGET mkt_plugins)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Libraries/mkt_plugins)
endif()
if (NOT TARGET mkt_algorithm)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Libraries/mkt_algorithm)
endif()
if (NOT TARGET two_points_planner)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Packages/global_planners/two_points_planner)
endif()
if (NOT TARGET custom_planner)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Packages/global_planners/custom_planner)
endif()
if (NOT TARGET dock_planner)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Packages/global_planners/dock_planner)
endif()
if (NOT TARGET pnkx_local_planner)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Algorithms/Packages/local_planners/pnkx_local_planner)
endif()
if (NOT TARGET robot_actionlib_msgs)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Libraries/robot_actionlib_msgs)
endif()
if (NOT TARGET robot_move_base_msgs)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Libraries/robot_move_base_msgs)
endif()
if (NOT TARGET robot_clear_costmap_recovery)
add_subdirectory(${CMAKE_SOURCE_DIR}/src/Navigations/Libraries/robot_clear_costmap_recovery)
endif()
# 3. Packages being migrated from AMR_T800/Test
#
# Prefer the future in-tree location. Until the migration is physically done,
# 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()
function(pnkx_add_test_package package_name)
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; sbpl_lattice_planner
# also links robot_sensor_ports (route graph injected via the sensor store) and route_graph
# (2026-09-21 corridor feature) — both must precede it too.
pnkx_add_test_package(sbpl)
pnkx_add_test_package(robot_sensor_ports)
pnkx_add_test_package(route_graph)
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)
endif()
message(STATUS "========================================")
message(STATUS "All packages configured successfully")
message(STATUS "========================================")

View File

@@ -0,0 +1,36 @@
robot_costmap_2d:
global_frame: map
robot_base_frame: base_link
rolling_window: false
track_unknown_space: false
plugins:
- name: static_layer
type: StaticLayer
- name: inflation_layer
type: InflationLayer
- name: obstacle_layer
type: ObstacleLayer
- name: voxel_layer
type: VoxelLayer
library_path: ./libplugins.so
footprint:
- [0.3, 0.3]
- [0.3, -0.3]
- [-0.3, -0.3]
- [-0.3, 0.3]
transform_tolerance: 0.0
update_frequency: 1.0
width: 0.0
height: 0.0
resolution: 0.0
origin_x: 0.0
origin_y: 0.0
footprint_padding: 0.0
robot_radius: 0.0

View File

@@ -0,0 +1,5 @@
inflation_layer:
enabled: true
inflate_unknown: false
cost_scaling_factor: 15.0
inflation_radius: 0.55

View File

@@ -0,0 +1,19 @@
obstacle_layer:
enabled: true
track_unknown_space: true
transform_tolerance: 0.2
topic: "map"
sensor_frame: laser_frame
observation_persistence: 0.0
expected_update_rate: 0.0
data_type: PointCloud
min_obstacle_height: 0.0
max_obstacle_height: 2.0
inf_is_valid: false
clearing: false
marking: true
obstacle_range: 2.5
raytrace_range: 3.0
footprint_clearing_enabled: true
combination_method: 1

View File

@@ -0,0 +1,11 @@
static_layer:
enabled: true
map_topic: "map"
first_map_only: false
subscribe_to_updates: false
track_unknown_space: true
use_maximum: false
lethal_cost_threshold: 100
unknown_cost_value: -1
trinary_costmap: true
base_frame_id: "map"

View File

@@ -0,0 +1,15 @@
voxel_layer:
enabled: true
footprint_clearing_enabled: true
max_obstacle_height: 3.0
origin_z: 0.0
z_resolution: 0.2
z_voxels: 16
unknown_threshold: 15.0
mark_threshold: 0
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_footprint
robot_base_frame: base_link
transform_tolerance: 1.0
performance_metrics_enabled: true
performance_metrics_period: 5.0
obstacle_range: 3.0
#mark_threshold: 1
publish_voxel_map: true
@@ -11,7 +13,7 @@ navigation_map:
map_file: maze
virtual_walls_map:
map_topic: /virtual_walls/map
map_topic: /map
namespace: /virtual_walls
map_pkg: managerments
map_file: maze
@@ -19,36 +21,81 @@ virtual_walls_map:
lethal_cost_threshold: 100
obstacles:
observation_sources: f_scan_marking f_scan_clearing b_scan_marking b_scan_clearing
f_scan_marking:
topic: /f_scan
data_type: LaserScan
clearing: false
marking: true
inf_is_valid: false
min_obstacle_height: 0.0
max_obstacle_height: 0.25
f_scan_clearing:
topic: /f_scan
data_type: LaserScan
clearing: true
marking: false
inf_is_valid: false
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: false
min_obstacle_height: 0.0
max_obstacle_height: 0.25
b_scan_clearing:
observation_sources: b_scan pc_marking pc_clearing pc_r_marking pc_r_clearing
# f_scan_marking: f_scan_marking f_scan_clearing
# topic: /f_scan
# data_type: LaserScan
# clearing: false
# marking: true
# inf_is_valid: true
# min_obstacle_height: 0.0
# max_obstacle_height: 0.25
# f_scan_clearing:
# topic: /f_scan
# data_type: LaserScan
# clearing: true
# marking: false
# inf_is_valid: true
# min_obstacle_height: 0.0
# max_obstacle_height: 0.25
b_scan:
topic: /b_scan
data_type: LaserScan
clearing: true
marking: false
inf_is_valid: false
marking: true
inf_is_valid: true
frustum_clearing_enabled: false
min_obstacle_height: 0.0
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
# Việc xoá vật cản (clearing) của camera depth do VoxelLayer đảm nhiệm bằng
# frustum clearing, lấy dữ liệu từ /camera/depth/image_raw +
# /camera/depth/camera_info. Nhánh /camera_right/depth/data cũng đi đường đó.

View File

@@ -1,10 +1,27 @@
global_costmap:
library_path: libplugins
robot_base_frame: base_footprint
robot_base_frame: base_link
global_frame: map
update_frequency: 1.0
publish_frequency: 1.0
raytrace_range: 2.0
# [bool] Bật log thống kê thời gian update costmap (avg/p95/p99 mỗi cycle + per-layer).
# Chỉ dùng khi đo đạc/tối ưu; log in mỗi performance_metrics_period giây, tắt đi khi chạy thật.
# Lưu ý: key này phải nằm TRONG namespace local_costmap/global_costmap — đặt ở root file common là key chết.
performance_metrics_enabled: false
# [s] Chu kỳ in báo cáo thống kê. Tăng lên thì log thưa hơn, số trung bình mượt hơn.
performance_metrics_period: 5.0
# [0..2] Mức chi tiết debug trong báo cáo thống kê, chỉ có tác dụng khi performance_metrics_enabled: true.
# 0 = giữ nguyên output cũ; 1 = thêm dòng lock_wait/lock_hold (tranh chấp mutex với planner),
# kích thước window update [cells] và số cycle rỗng; 2 = thêm per-layer: layer nào nở bounds bao nhiêu [m^2].
debug_level: 0
# [bool] Global planner tính toán trên BẢN COPY (snapshot) của costmap thay vì lưới live.
# true: PlannerRunner copy lưới dưới lock (~ms) đầu mỗi lượt makePlan rồi đưa bản copy cho planner
# qua capability "<alias>ExternalGrid" (hiện chỉ SBPLLatticePlanner có) — thread update global
# costmap hết bị chặn 6-14 s mỗi lượt SBPL cạn search. Kết quả plan không đổi.
# false: hành vi cũ — giữ mutex suốt makePlan. Công tắc rollback, không cần build lại.
# ► Chỉnh: cây này giữ false tới khi cây sim (Test/move_base2/config/runtime) đo xong.
snapshot_for_readers: false
raytrace_range: 3.0
resolution: 0.05
z_resolution: 0.2
rolling_window: false

View File

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

View File

@@ -1,11 +1,26 @@
local_costmap:
local_costmap:
library_path: libplugins
global_frame: odom
robot_base_frame: base_footprint
robot_base_frame: base_link
update_frequency: 6.0
publish_frequency: 6.0
# [bool] Bật log thống kê thời gian update costmap (avg/p95/p99 mỗi cycle + per-layer).
# Chỉ dùng khi đo đạc/tối ưu; log in mỗi performance_metrics_period giây, tắt đi khi chạy thật.
# Lưu ý: key này phải nằm TRONG namespace local_costmap/global_costmap — đặt ở root file common là key chết.
performance_metrics_enabled: false
# [s] Chu kỳ in báo cáo thống kê. Tăng lên thì log thưa hơn, số trung bình mượt hơn.
performance_metrics_period: 5.0
# [0..2] Mức chi tiết debug trong báo cáo thống kê, chỉ có tác dụng khi performance_metrics_enabled: true.
# 0 = giữ nguyên output cũ; 1 = thêm dòng lock_wait/lock_hold (tranh chấp mutex với planner),
# kích thước window update [cells] và số cycle rỗng; 2 = thêm per-layer: layer nào nở bounds bao nhiêu [m^2].
debug_level: 0
# [bool] Local planner tính toán trên BẢN COPY (snapshot) của costmap thay vì lưới live.
# true: mỗi control cycle copy lưới dưới lock ~vài us rồi planner solve trên bản copy — thread
# update costmap không còn bị planner chặn trong lúc solve. false: hành vi cũ (khoá dài suốt
# computeVelocityCommands). Bản mặc định để false — cây đang chạy là move_base2/config/runtime.
snapshot_for_readers: false
rolling_window: true
raytrace_range: 2.0
raytrace_range: 3.0
resolution: 0.05
z_resolution: 0.15
z_voxels: 8

View File

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

View File

@@ -1,17 +1,35 @@
base_global_planner: CustomPlanner
# custom_planner — tham số runtime, đọc qua robot::NodeHandle("CustomPlanner").
# Thiếu key nào thì dùng default trong CustomPlannerConfig (cùng giá trị ghi ở đây).
CustomPlanner:
library_path: libcustom_planner
environment_type: XYThetaLattice
planner_type: ARAPlanner
allocated_time: 10.0
initial_epsilon: 1.0
force_scratch_limit: 10000
forward_search: false
nominalvel_mpersecs: 0.8
timetoturn45degsinplace_secs: 1.31 # = 0.6 rad/s
allow_unknown: true
directory_to_save_paths: "/init/paths"
pathway_filename: "pathway.txt"
current_pose_topic_name: "/amcl_pose"
# [m] start/goal cách pathway dưới ngưỡng này thì coi là đã bám vào pathway
# (quyết định cách nối NURBS start/goal vào tuyến).
pathway_attach_distance: 0.1
# [m] order không có node/edge (goal trần): chỉ nhận khi start-goal gần hơn
# ngưỡng này, ngược lại trả false để move_base2 dùng backup planner.
bare_goal_max_distance: 0.2
# Bước tham số u trong [0,1] khi đo chiều dài NURBS một cạnh (không phải mét).
nurbs_length_t_interval: 0.01
# [m] khoảng cách mong muốn giữa hai pose khi lấy mẫu NURBS nối start/goal.
nurbs_point_spacing: 0.05
# [rad] hai cạnh thẳng đầu gãy dưới góc này thì bỏ cạnh đầu khi tính yaw.
skip_edge_angle: 0.4712 # = 0.15*pi
# [rad] góc nối giữa hai cạnh <= tight: gãy gắt (cost 20); < wide: gãy vừa (cost 10).
cost_angle_tight: 0.3142 # = 0.1*pi
cost_angle_wide: 1.4137 # = 0.45*pi
# [rad] cửa sổ góc đổi hướng cần chèn chuỗi pose xoay tại chỗ giữa hai cạnh.
rotation_insert_min: 1.4137 # = 0.45*pi
rotation_insert_max: 2.6704 # = 0.85*pi
# [rad] bước yaw giữa hai pose xoay tại chỗ được chèn.
rotation_step: 0.1571 # = 0.05*pi
# [rad] |yaw goal - hướng cạnh cuối| vượt ngưỡng này thì đoạn cuối đi lùi.
backward_decision_angle: 1.5708 # = 0.5*pi

View File

@@ -0,0 +1,159 @@
# DockPlanner — global planner sinh đường vào dock.
#
# Ba kiểu đường. Planner thử theo thứ tự và lấy kiểu ĐẦU TIÊN dựng được; kiểu nào
# không dựng được thì rơi xuống kiểu kế tiếp, KHÔNG bao giờ biến thành lỗi:
# 1. direct_entry — một cung hội tụ vào trục goal rồi đi thẳng vào. Một chiều
# chạy, không dừng, không xoay. Rẻ nhất khi chạy.
# 2. single_cusp — cua rời XA dock tới điểm đổi chiều (cusp) rồi lùi thẳng vào.
# Lấn thêm chỗ về phía xa dock đúng bằng quãng phải đi ra.
# 3. straight_pivot_straight — một đoạn thẳng, một cú XOAY TẠI CHỖ ghi tường
# minh vào path (một khối pose cùng vị trí, yaw tăng dần), rồi một đoạn
# thẳng vào goal. Điểm xoay nằm GIỮA robot và dock nên KHÔNG lấn thêm một
# mét nào, đổi lại có thêm một lần dừng để xoay.
# Thứ tự ưu tiên giữa 2 và 3 do `kinematics/model` và `maneuver/*` quyết định —
# xem comment của từng khoá.
# Đoạn cuối của cả ba kiểu luôn THẲNG và trùng hướng yaw của goal: robot phải đạt
# đúng hướng trước khi chui vào dock — đi cong vào gầm trolley rất dễ va.
#
# Mép nào của robot áp vào dock được SUY RA theo từng lần lập plan, dựa vào phía
# robot đang đứng so với goal. Không khai báo bằng tham số:
# robot ở phía +X của goal -> lead-in đi TIẾN, đoạn cuối đi LÙI
# (mép sau áp dock: càng nâng chui vào pallet)
# robot ở phía -X của goal -> lead-in đi LÙI, đoạn cuối đi TIẾN
# (mép trước áp dock: chấu sạc ở đầu xe)
# Suy được như vậy vì goal đã được offset sẵn từ tầng trên, sao cho base_link
# dừng đúng tại goal khi manơ hoàn tất.
#
# Kiểm tra va chạm / vùng trống CỐ Ý chưa cấu hình ở đây: DockPlanner hiện chỉ
# sinh hình học. Đừng thêm cost_threshold, allow_unknown hay check_free_space
# cho tới khi phần kiểm va chạm được hiện thực.
DockPlanner:
# Thư viện Boost.DLL chứa symbol export tên "DockPlanner".
library_path: libdock_planner
# ══════════════════════════════════════════════════════════════════════════════
# ĐỘNG HỌC — khoá nào có tác dụng phụ thuộc `model`. Khoá của model KIA được
# đọc vào nhưng KHÔNG dùng và KHÔNG kiểm tra, nên để lại giá trị cũ vô hại.
#
# khoá ackermann differential
# ───────────────────────────── ─────────── ────────────
# front_axle_frame DÙNG bỏ qua
# rear_axle_frame DÙNG bỏ qua
# max_steering_angle DÙNG bỏ qua
# minimum_turning_radius bỏ qua DÙNG
# ══════════════════════════════════════════════════════════════════════════════
kinematics:
# Mô hình dẫn động. Quyết định planner ĐO hay ĐỌC bán kính cua nhỏ nhất, và
# robot có được xoay tại chỗ hay không.
# ackermann — có trục lái. R_min được ĐO: wheel_base lấy từ TF hai frame
# trục bánh, chia cho tan(max_steering_angle). Robot không
# đổi được hướng nếu không di chuyển.
# differential — hai bánh chủ động độc lập. KHÔNG có trục lái nên KHÔNG tra
# TF trục bánh. R_min ĐỌC thẳng từ minimum_turning_radius.
# ► Chỉnh: để nhầm `ackermann` cho robot vi sai thì plugin KHÔNG NẠP ĐƯỢC —
# nó đi tra frame `steer_link` mà robot vi sai không hề có.
model: ackermann
# ── chỉ có tác dụng khi model: ackermann ─────────────────────────────────────
# Hai frame trục bánh, dùng để ĐO wheel_base từ TF. Phải trùng cặp frame
# StanleyControl đang dùng, lệch là bán kính cua tính ra sai.
front_axle_frame: "steer_link"
rear_axle_frame: "base_link"
# [rad] Góc lái lớn nhất của mô hình xe đạp tương đương khi đang chạy.
# PHẢI đo trên robot thật. KHÔNG phải tick servo, KHÔNG phải góc vô lăng,
# cũng KHÔNG phải góc pivot tại chỗ.
# R_min = wheel_base / tan(góc này).
# Khai lớn hơn thực tế -> sinh cung robot bám không nổi, robot lệch path.
# Khai nhỏ hơn thực tế -> đường vòng rộng, tốn không gian.
max_steering_angle: 0.5
# ── chỉ có tác dụng khi model: differential ──────────────────────────────────
# [m] Bán kính cua nhỏ nhất, khai trực tiếp vì robot vi sai không có góc lái.
# 0 — CHO PHÉP xoay tại chỗ. Đây là giá trị bình thường của robot vi sai,
# và nó bật kiểu đường 3 (thẳng + xoay + thẳng) làm kiểu CHÍNH: kiểu
# này không lấn thêm một mét nào về phía xa dock.
# > 0 — CẤM xoay tại chỗ (ví dụ đang chở tải cao, xoay tại chỗ dễ đổ).
# Planner quay về dùng cung y như ackermann, bán kính tối thiểu đúng
# bằng số này, và kiểu 3 chỉ còn bật qua pivot_fallback_extension.
minimum_turning_radius: 0.0
maneuver:
# [m] Cusp đặt cách điểm xuất phát ít nhất khoảng này, đo theo hướng RỜI XA
# dock. Bảo đảm luôn có đoạn lead-in thật trước khi đổi chiều, thay vì cusp
# trùng ngay vị trí robot.
minimum_forward_distance: 0.25
# [m] Cusp phải nằm xa hơn khoảng này so với điểm xuất phát thì kiểu 2 bị
# LOẠI (không phải fail): planner chuyển sang kiểu khác, chỉ khi không kiểu
# nào dựng được mới trả lỗi.
# Tăng lên nếu robot đứng lệch nhiều mà vẫn muốn giữ đường có cusp; giảm
# xuống để đẩy sớm sang kiểu 3.
maximum_forward_extension: 3.0
# [m] Bật kiểu 1 (direct_entry — một cung hội tụ vào trục goal rồi đi thẳng
# vào, giữ nguyên một chiều chạy) khi khoảng chỗ còn lại cho cung — khoảng
# cách dọc trục từ robot tới goal trừ độ dài đoạn thẳng cuối — vượt số này.
# Bán kính cung VẪN bị kiểm với R_min. Trượt phép kiểm nào thì rơi xuống
# kiểu sau, nên khoá này chỉ có thể BỚT một lần đổi chiều, không bao giờ thêm.
# 0 = tắt hẳn kiểu 1.
direct_entry_min_curve_room: 0.0
# [m] Chuyển từ kiểu 2 (cusp) sang kiểu 3 (thẳng + xoay + thẳng) khi cusp bắt
# robot chạy RA XA dock thêm quá số này, đo từ chỗ robot ĐANG ĐỨNG.
# So sánh cố ý là TƯƠNG ĐỐI. Lấy một con số tuyệt đối kiểu "chiều sâu lối đi"
# rồi so với vị trí robot là tính cả chỗ robot đang đứng vào phần "cần thêm",
# và mọi manơ xuất phát từ khoảng cách bình thường đều bị loại sạch.
# 0 — TẮT hẳn kiểu 3 (hành vi cũ, luôn lập đường có cusp).
# nhỏ hơn — chuyển sang xoay tại chỗ sớm hơn: tiết kiệm lối đi, thêm 1 lần dừng.
# lớn hơn — ưu tiên cusp: chạy mượt hơn, chiếm nhiều lối đi hơn.
# ⚠ Chỉ khai > 0 khi CHẮC robot xoay tại chỗ được quanh base_link.
# KHÔNG có tác dụng khi model=differential VÀ minimum_turning_radius=0 — lúc
# đó kiểu 3 đã là kiểu chính rồi, không cần ngưỡng nào bật nó.
pivot_fallback_extension: 0.0
# [m] Khoảng hở giữa vòng tròn thân robot quét khi xoay tại chỗ và mặt gần
# của dock. Áp dụng cho CẢ HAI model, mỗi khi kiểu 3 được dùng.
# Xoay tại chỗ quay MỌI điểm footprint quanh base_link, nên kích thước phải
# tính là BÁN KÍNH NGOẠI TIẾP, luôn lớn hơn phần nhô mép dùng cho đoạn thẳng
# cuối. Ví dụ footprint 1.65/0.35 x ±0.40: ngoại tiếp 1.698 m trong khi mép
# sau chỉ 0.35 m — chênh 1.35 m.
# Điểm xoay đặt tại: max(độ dài đoạn thẳng cuối, ngoại tiếp + nửa thân dock
# phía tiếp cận + số này).
# Tăng lên: điểm xoay lùi ra xa dock hơn, an toàn hơn. Tăng quá thì điểm xoay
# vượt qua chỗ robot đứng, kiểu 3 bị loại và planner quay về cusp.
pivot_safety_margin: 0.15
terminal:
# [m] Khoảng hở CỘNG THÊM cho đoạn thẳng cuối, ngoài phần thân robot nhô ra ở
# mép áp dock (rear_extent khi đoạn cuối đi lùi, front_extent khi đi tiến) và,
# nếu dock_anchor=center, ngoài nửa thân dock phía tiếp cận.
# Tăng lên nếu thấy robot dừng quá sát dock.
reverse_distance_padding: 1.0
# [m] Độ dài đoạn thẳng cuối MONG MUỐN. Giá trị thực tế là
# max(giá trị này, phần nhô mép áp dock + nửa thân dock + padding), nên đặt 0
# là chỉ dùng khoảng hở tối thiểu.
# Tăng lên thì robot có quãng thẳng dài hơn để chỉnh hết sai số hướng trước
# khi vào dock, ĐỔI LẠI ăn vào chỗ dành cho cung, nên đặt lớn quá sẽ đẩy plan
# sang kiểu có cusp hoặc kiểu xoay tại chỗ.
straight_length: 0.0
sampling:
# [m] Khoảng cách lớn nhất giữa hai điểm liên tiếp trên đường, áp dụng cho cả
# đoạn cung lẫn đoạn thẳng. Nhỏ hơn = đường mượt hơn nhưng nhiều điểm hơn.
path_point_spacing: 0.05
# footprint_dock và dock_anchor KHÔNG khai ở đây. move_base2 chọn theo từng
# marker rồi rót vào namespace này trước khi khởi tạo plugin.
#
# dock_anchor: 'center' (mặc định) — goal nằm ở tâm dock; nửa thân dock phía
# tiếp cận (lấy từ footprint_dock) được cộng vào khoảng hở cusp.
# 'face' — goal đã nằm sẵn trên mặt tiếp cận; footprint_dock bị bỏ qua.
#
# Đã BỎ ba khoá không có tác dụng: maneuver/straight_lateral_tolerance,
# maneuver/straight_yaw_tolerance và terminal/direction. DockPlannerConfig::load
# không đọc khoá nào trong số đó — chiều đoạn cuối được suy ra từ phía robot
# đứng, không cấu hình được.

View File

@@ -0,0 +1,534 @@
# HybridLocalPlanner — local planner lai Pure Pursuit + DWA.
#
# Phân vai rõ giữa hai tầng:
# - DWA quyết định VẬN TỐC TIẾN: lấy mẫu quỹ đạo, chấm điểm theo vật cản,
# khoảng cách tới path và tới goal. Nó cũng là tầng duy nhất ra được lệnh
# xoay tại chỗ (v = 0, omega khác 0).
# - Pure Pursuit chỉ ĐÁNH LÁI: omega = |v| * pp_weight_omega * sin(err) / lookahead.
# Luật này suy biến ở v = 0 nên dưới pp_min_steering_velocity quyền quay được
# trả về cho DWA.
#
# Khi vật cản chắn path, latch né vật cản bật lên: DWA lái một mình (bỏ path cost),
# Pure Pursuit bị bỏ qua, trần vận tốc hạ về avoidance_max_velocity.
#
# Bật log để soi luồng đó: xem nhóm "Debug" ở cuối file.
HybridLocalPlanner:
library_path: libhybrid_local_planner
# ===== Giới hạn vận tốc =====
max_forward_velocity: 1.0 # [m/s] trần vận tốc tiến khi bám path
max_reverse_velocity: 0.25 # [m/s] trần vận tốc lùi, ghi bằng ĐỘ LỚN DƯƠNG
avoidance_max_velocity: 0.4 # [m/s] trần vận tốc khi đang né vật cản. Thấp hơn
# max_forward_velocity để còn kịp phanh trong không gian hẹp
max_angular_velocity: 0.6 # [rad/s] trần tốc độ quay
min_velocity: 0.0 # [m/s] sàn của cửa sổ động DWA. Đặt khác 0 là ép robot
# không bao giờ được đứng yên — nguy hiểm
min_yawrate: 0.05 # [rad/s] độ lớn quay tối thiểu khi DWA đã quyết định quay.
# Dưới ngưỡng này servo không thắng nổi ma sát tĩnh
# ===== Giới hạn gia tốc — CÓ HAI TẦNG, đừng nhầm =====
# Tầng cửa sổ DWA (acc_lim_*, decel_lim_x): dựng dải vận tốc mà bộ lấy mẫu
# ĐƯỢC PHÉP cân nhắc. Đây là thứ quyết định DWA nghĩ tới những lệnh nào.
# Tầng kẹp đầu ra (output_acc_lim_*): kẹp lệnh cuối so với vận tốc đo từ odom,
# chạy ở cuối mỗi chu kỳ. Đây là thứ quyết định bánh xe bị yêu cầu đổi gấp đến đâu.
# Để tầng cửa sổ chặt hơn tầng đầu ra (như bản đang chạy) thì DWA tự giới hạn
# trước, tầng đầu ra gần như không cắn. Đặt ngược lại thì lệnh bị cắt SAU khi
# đã chấm điểm — DWA chọn một đằng, robot chạy một nẻo. Code sẽ cảnh báo nếu vậy.
acc_lim_x: 0.1 # [m/s^2] cửa sổ DWA, tăng tốc
decel_lim_x: 0.5 # [m/s^2] cửa sổ DWA, giảm tốc (độ lớn dương)
acc_lim_theta: 3.2 # [rad/s^2] cửa sổ DWA, gia tốc góc
output_acc_lim_x: 1.0 # [m/s^2] kẹp đầu ra, tịnh tiến
output_acc_lim_theta: 2.0 # [rad/s^2] kẹp đầu ra, quay. Ở 20 Hz, giá trị 2.0
output_decel_lim_theta: 6.0 # [rad/s^2] kẹp đầu ra khi lệnh quay đi VỀ PHÍA 0.
# Cùng lý do với output_decel_lim_x, và cùng kiểu hỏng khi thiếu:
# gần goal planner đòi -0.222 rad/s trong khi robot đang quay
# +0.59, giới hạn đối xứng 2.0 xuất ra +0.490 — robot quay SAI
# CHIỀU suốt 8 chu kỳ và sai số yaw tăng gấp đôi trước khi gỡ được.
# Giảm |omega| luôn khả thi về vật lý (ma sát giúp), nên số này
# đặt cao hơn hẳn giới hạn tăng tốc được
output_decel_lim_x: 2.0 # [m/s^2] kẹp đầu ra khi lệnh đi VỀ PHÍA 0 (đang phanh).
# Tách riêng khỏi output_acc_lim_x có chủ đích: giới hạn tăng tốc
# là chuyện êm ái, giới hạn giảm tốc là chuyện robot có dừng được
# hay không. Một giới hạn đối xứng đã từng TỪ CHỐI lệnh phanh —
# creep clamp đòi 0.40 m/s, tầng kẹp xuất ra 1.37 m/s và robot
# vọt qua goal. Phải LỚN HƠN output_acc_lim_x, nhưng đừng đặt vô
# cùng lớn: lệnh nhảy từ tốc độ cao về 0 trong một chu kỳ làm
# xê dịch hàng đang chở
brake_margin: 0.15 # [m] biên trừ vào quãng đường còn lại trước khi tính trần phanh
# trong DWA. Bù thời gian phản ứng một chu kỳ và dung sai goal
# cho phép omega đổi 0.1 rad/s mỗi chu kỳ
# ===== Quay tại chỗ =====
max_in_place_angular_velocity: 0.6 # [rad/s] trần tốc độ quay tại chỗ
min_in_place_angular_velocity: 0.3 # [rad/s] sàn tốc độ quay tại chỗ. Phải <= trần,
# nếu lớn hơn thì validate() tự hạ xuống và cảnh báo
# ===== Hình học robot và kiểm va chạm =====
min_turn_radius: 0.0 # [m] bán kính cua nhỏ nhất. 0 = không ràng buộc (vi sai).
# Khác 0 sẽ kẹp omega theo |v| / min_turn_radius
robot_radius: 0.1 # [m] bán kính robot, CHỈ dùng khi use_footprint = false
footprint_padding: 0.07 # [m] nới footprint ra mọi phía để có biên an toàn.
# Tăng = an toàn hơn nhưng khe hẹp sẽ bị coi là chặn.
# Mỗi 0.01 ở đây là 0.02 bề rộng khe cần thêm
use_footprint: true # true = kiểm va chạm theo footprint đa giác;
# false = coi robot là hình tròn bán kính robot_radius
turn_around_priority: true # true = khi lệch hướng quá lớn thì dừng hẳn (v = 0) và
# xoay cho đúng hướng trước, thay vì vừa đi vừa lượn
# ===== Dung sai goal =====
xy_goal_tolerance: 0.05 # [m] sai số vị trí chấp nhận là đã tới goal
yaw_goal_tolerance: 0.03 # [rad] sai số góc chấp nhận là đã tới goal
goal_yaw_gain: 1.0 # [1/s] hệ số tỉ lệ của pha xoay cuối: omega = gain * sai_số_yaw.
# Trước đây ngầm định 1.0 và không chỉnh được từ config. Bộ P
# thuần nối vào một tầng giới hạn tốc độ thay đổi là công thức
# kinh điển của dao động — còn lắc thì HẠ số này trước tiên
goal_yaw_deadband: 0.05 # [rad/s] vùng chết của pha xoay cuối: lệnh nhỏ hơn ngưỡng này
# bị ĐẨY RA bằng ngưỡng, để servo thắng được ma sát tĩnh.
# Chỉ áp khi sai số yaw còn NGOÀI yaw_goal_tolerance; trong dung
# sai thì lệnh bằng 0, nếu không robot vẫn bị bảo quay tiếp sau
# khi đã tới nơi.
# Đặt rộng hơn nhiều so với yaw_goal_tolerance là gây vọt góc
# ===== Lấy mẫu path toàn cục =====
max_global_plan_lookahead_dist: 3.0 # [m] chỉ lấy phần path trong tầm này để bám.
# Ngắn = bám sát nhưng cua gấp; dài = mượt nhưng cắt cua
global_plan_viapoint_sep: 0.5 # [m] khoảng cách tối thiểu giữa hai điểm trung gian
# trích từ path. Lúc chạy lấy max(|v|, giá trị này)
global_plan_goal_sep: 0.05 # [m] lấy mẫu dày hơn ở đoạn sát goal
# ===== Mô phỏng quỹ đạo của DWA =====
predict_time: 3.0 # [s] DWA mô phỏng quỹ đạo ứng viên trước bao lâu
sim_period: 0.1 # [s] bước thời gian dùng khi dựng cửa sổ động
sim_time_samples: 10 # số bước mô phỏng trên mỗi quỹ đạo. Bước không gian
# xấp xỉ v * predict_time / sim_time_samples — ở v = 0.4
# là 0.12 m, tức LỚN HƠN một ô costmap: quỹ đạo có thể
# bước qua vật cản mỏng. Tăng số này để bắt được vật mỏng,
# đổi lại tốn CPU tuyến tính
dwa_arrival_distance: 0.05 # [m] dưới cự ly này tới goal cục bộ, DWA thôi lấy mẫu
# quỹ đạo chạy và chuyển sang xoay tại chỗ
dwa_in_place_turn_angle: 3.1416 # [rad] lệch hướng phải VƯỢT ngưỡng này thì DWA mới dừng
# xoay tại chỗ trước khi đi. Đặt >= pi (giá trị hiện tại)
# là TẮT hẳn nhánh đó — đúng như hành vi cũ. Hạ xuống
# (ví dụ 0.8) nếu muốn robot xoay cho thẳng hướng rồi mới chạy
# ===== Pure Pursuit (chỉ đánh lái) =====
pp_weight_omega: 1.5 # hệ số nhân sai lệch hướng ra tốc độ quay.
# Tăng = bám cua gắt hơn nhưng dễ dao động quanh path
pp_min_steering_velocity: 0.05 # [m/s] dưới ngưỡng này Pure Pursuit KHÔNG được ghi đè omega.
# Luật lái của nó là omega = |v| * pp_weight_omega * sin(err) / lookahead,
# ở v = 0 nó suy biến (không tồn tại bán kính cong) và luôn trả 0,
# nuốt mất lệnh xoay tại chỗ của DWA -> robot tự khoá: không quay
# được vì không chạy, không chạy được vì không quay.
# Trong dải này quyền quay trả về cho DWA.
# Đặt 0 = tắt bảo vệ, quay lại hành vi cũ (dễ kẹt).
# Đặt quá cao = PP hiếm khi lái, robot bám path kém hơn
pp_reference_gain: 2.0 # trọng số của số hạng |omega_ứng_viên − omega_PurePursuit|,
# nhân thêm (1 − b). Pure Pursuit KHÔNG còn ghi đè lệnh; nó chỉ
# nêu ý kiến, DWA chấm điểm ứng viên theo độ gần với ý kiến đó.
# Nhờ vậy lệnh xuất ra luôn là một quỹ đạo ĐÃ được chấm điểm va
# chạm — bản cũ để omega của PP đi thẳng ra bánh, không qua kiểm.
# 0 = bỏ hẳn ảnh hưởng của PP. Tăng = bám path sát hơn khi đường
# trống, nhưng không bao giờ vượt được độ phân giải yawrate_samples
pp_min_lookahead: 0.3 # [m] SÀN cho cự ly nhìn trước khi dựng tham chiếu lái.
# Luật lái mang 1/L, nên khi điểm nhìn trước bị "ăn" hết lúc
# sát goal thì hệ số từ sai số hướng ra độ cong PHÂN KỲ.
# Đo thật: ở L = 0.06 m, sai số 0.9 độ cho ra 0.44 rad/s và
# tham chiếu ĐỔI DẤU theo nhiễu cảm biến — đó chính là hiện
# tượng đánh lái lắc qua lại ở 20 cm cuối
pp_reference_min_distance: 0.5 # [m] dưới cự ly này tới cuối chặng thì TẮT HẲN tham chiếu.
# Bám path không còn gì để nói ở đó — việc duy nhất còn lại là
# đi vào goal — và tham chiếu dựng từ một điểm nhìn trước đã
# nằm dưới bụng robot chỉ là nhiễu
# ===== Trọng số hàm cost của DWA =====
obs_cost_gain: 1.3 # phạt tiến gần vật cản
path_cost_gain: 2.5 # phạt lệch khỏi path toàn cục. Đây là khoá giữ robot
# trong lòng đường; giảm mạnh là robot cắt cua và men mép khe
to_goal_cost_gain: 0.8 # thưởng cho quỹ đạo tiến gần goal
speed_cost_gain: 0.5 # thưởng cho quỹ đạo chạy nhanh
# ===== Cảm nhận vật cản =====
obs_range: 2.5 # [m] bán kính quét vật cản quanh robot
# ===== Ngưỡng hành vi =====
segment_transition_threshold: 0.01 # [m] ngưỡng coi là đã tới hết một chặng path
use_obstacle_avoidance: true # false = tắt latch né vật cản, chỉ chạy Pure Pursuit bám path
# ===== Hoà trộn bám path <-> né vật cản (KHÔNG còn chế độ nhị phân) =====
# Toàn bộ quyết định gói trong MỘT số: b = mức độ path phía trước bị chắn.
# b = 0 path thông -> path cost đủ trọng số, obs cost = 0, DWA bám sát omega của Pure Pursuit
# b = 1 path bị chắn -> path cost = 0, obs cost đủ trọng số, bỏ qua Pure Pursuit
# Hai đầu tái lập ĐÚNG hai chế độ cũ. Khác biệt là ở giữa giờ mới có gì đó.
#
# b tính lại mỗi chu kỳ từ costmap, KHÔNG lưu trạng thái — nên không còn latch,
# không còn hai bộ tham số phải luân phiên set.
blend_start_distance: 3.0 # [m] vật cản xa hơn ngưỡng này thì coi như không có (b = 0)
blend_end_distance: 3.0 # [m] vật cản gần hơn ngưỡng này thì coi như chắn hẳn (b = 1).
# ĐỂ BẰNG blend_start_distance là b thành bậc nhảy, tái lập
# CHÍNH XÁC hành vi latch cũ — đây là cấu hình dùng để chứng minh
# refactor không đổi kết quả. Hạ xuống (vd 1.0) để có vùng
# chuyển tiếp mượt: robot bắt đầu né sớm và nhẹ thay vì giật
use_avoidance_velocity_limit: true # true = khi path bị chắn thì hạ trần về avoidance_max_velocity
# (fleet set 1.0 nhưng đang né thì chạy 0.4)
# false = GIỮ NGUYÊN vận tốc fleet đang set, để một mình hàm cost
# lo việc né. Cost blend không đổi trong cả hai trường hợp —
# cờ này CHỈ quyết định có kẹp tốc độ hay không.
# Đặt false khi muốn né mà không mất thời gian, đổi lại quỹ đạo né
# ở tốc độ cao cần cửa sổ động rộng hơn mới lách được
creep_distance: 0.8 # [m] cự ly tới cuối chặng mà vùng bò chậm bắt đầu.
# Ngưỡng THỰC = max(giá trị này, quãng phanh + creep_margin),
# nên nó chỉ NỚI RA theo tốc độ, không bao giờ thu lại: dưới
# khoảng 0.9 m/s thì số cố định thắng và hành vi y như cũ, còn
# ở tốc độ cao nó cắn đủ sớm để phanh kịp.
# Thu nhỏ số này là mất luôn cái sàn giữ robot không chết đứng
# trước goal
creep_margin: 0.3 # [m] cộng thêm vào quãng phanh khi tính ngưỡng
creep_max_velocity: 0.4 # [m/s] trần trong vùng bò chậm (độ lớn, dùng cho cả hai chiều)
creep_min_velocity: 0.05 # [m/s] sàn trong vùng bò chậm khi tiến — giữ robot không đứng
# lại trước goal
creep_min_velocity_reverse: 0.01 # [m/s] sàn khi lùi (độ lớn). Nhỏ hơn chiều tiến, giữ đúng số cũ
curve_max_velocity: 0.2 # [m/s] trần vận tốc khi đang trong khúc cua
reject_collisions_always: false # false = chỉ loại quỹ đạo va chạm khi b > 0 (HÀNH VI CŨ).
# Lưu ý: nghĩa là khi bám path DWA KHÔNG loại quỹ đạo va chạm
# nào cả, chỉ dựa vào b để né. true = loại mọi lúc, an toàn hơn
# nhưng ĐỔI kết quả solve của chế độ bám path
velocity_samples: 10 # số mẫu vận tốc trong cửa sổ động. Cũ: 10 khi bám path thẳng,
# 7 khi cua và khi né. Cửa sổ rộng <= 0.06 m/s nên chênh lệch
# giữa 7 và 10 là ~5 mm/s, không đo được
yawrate_samples: 20 # số mẫu tốc độ quay cho mỗi mức vận tốc. Đây là thứ quyết định
# omega chọn được bám sát omega của Pure Pursuit đến đâu:
# sai lệch tối đa = bề rộng cửa sổ quay / yawrate_samples
# để robot vẫn xoay được khi đang bò chậm
turn_direction_th: 0.1 # [rad] ngưỡng lệch hướng tối thiểu để DWA coi là cần rẽ
# ===== Bảo vệ TF plan -> global =====
# Mỗi lần AMCL sửa vị trí, transform map->odom dịch vài cm. Robot đứng yên
# nhưng CẢ PATH bị dịch dưới chân nó, nên Pure Pursuit thấy error_angle nhảy
# bậc và DWA thấy path cost nhảy bậc — đó là hiện tượng lắc khi bám path.
# Đóng băng transform trong suốt một chặng làm mất cú dịch đó; robot bám hoàn
# toàn trong frame liên tục (odom). Kiểm va chạm KHÔNG bị ảnh hưởng vì local
# costmap vẫn nằm ở frame liên tục với dữ liệu cảm biến sống.
plan_tf_freeze: true # true = chốt transform cho cả chặng khi nó đã yên.
# Bật lên chỉ sau khi đã chạy thử — xem ghi chú
# freeze_settle_cycles bên dưới
freeze_settle_cycles: 30 # [chu kỳ] số chu kỳ YÊN liên tiếp trước khi chốt.
# PHẢI phủ >= 2 lần chu kỳ cập nhật định vị: AMCL 2 Hz
# với vòng điều khiển 20 Hz là >= 20 chu kỳ. Ngắn hơn thì
# cửa sổ rơi lọt giữa hai lần hiệu chỉnh — ở đó transform
# hằng số THEO ĐỊNH NGHĨA — và sẽ chốt ngay trước một
# hiệu chỉnh đang tới
freeze_settle_eps_xy: 0.005 # [m] bước dịch mỗi chu kỳ dưới ngưỡng này coi là yên
freeze_settle_eps_yaw: 0.005 # [rad] bước quay mỗi chu kỳ dưới ngưỡng này coi là yên
freeze_settle_timeout: 3.0 # [s] hết hạn mà chưa yên thì chốt luôn giá trị mới nhất,
# kèm cảnh báo. Bản đồ nhảy liên tục chính là điều kiện
# mà freeze sinh ra để trị; để sống tiếp là lắc cả chặng
tf_cache_max_age: 0.5 # [s] lookup lỗi thì lái tiếp trên transform đã cache tới
# ngần này rồi mới từ chối ra lệnh. Đặt 0 = dừng ngay khi
# trượt một nhịp TF, gây phanh nhấp khi publisher chập chờn
# ===== Debug =====
# Nhóm khoá bật log chẩn đoán [DBG-HYBRID-*]. Cùng quy ước với priest_local_planner:
# mức càng cao log càng dày, KHÔNG đổi hành vi điều khiển.
# 0 = tắt hẳn (mặc định, dùng khi chạy thật)
# 1 = chỉ log sự kiện đổi trạng thái (đổi hướng tiến/lùi, bật/tắt latch né vật cản,
# DWA trả lệnh 0, ô costmap nào chặn đường)
# 2 = mức 1 + log định kỳ 1 Hz cho từng chỗ ghi (không chỗ nào bị bỏ đói)
# 3 = in mọi chu kỳ điều khiển — chỉ dùng khi bắt lỗi ngắn, rất nặng I/O
debug_level: 0
# Các khoá dưới bật/tắt từng nhóm log, chỉ có tác dụng khi debug_level >= 1.
debug_command: true # [DBG-HYBRID-CMD] pose, lệnh cuối (v, omega), tầng kẹp gia tốc, kẹp bò chậm
debug_dwa: true # [DBG-HYBRID-DWA] output thô của DWA, hồ sơ cost và số mẫu khi đổi chế độ
debug_purepursuit: true # [DBG-HYBRID-PP] error_angle, lookahead, và omega mà PP ghi đè lên DWA
debug_mode: true # [DBG-HYBRID-MODE] đổi hướng tiến/lùi, xong căn hướng đầu, đạt xy_goal
debug_collision: true # [DBG-HYBRID-OBS] swapPlan/checkObstacles: chặn ở pose nào, ô costmap nào, cost bao nhiêu
debug_goal: true # [DBG-HYBRID-GOAL] khoảng cách tới goal, sai lệch yaw, các cờ đã latch
debug_tf: true # [DBG-HYBRID-TF] chốt/nhả đóng băng, độ lệch transform, lái trên cache
debug_path: true # [DBG-HYBRID-PATH] bám path: cross-track có dấu (+ = robot lệch TRÁI so với
# chiều đi của path), sai lệch hướng so với tiếp tuyến path, cự ly còn lại
# tới cuối chặng, và ngưỡng chuyển chặng. Đây là dòng để trả lời "robot có
# bám path không" và "chuyển chặng có đúng ở cusp không".
# =================================================================================================
# HybridDockingLocalPlanner — CÙNG planner, instance RIÊNG cho chặng docking.
#
# move_base2 cache instance controller theo TÊN; tên truyền vào initialize() quyết định block YAML
# mà instance đó đọc. Các block YAML KHÔNG kế thừa nhau: khoá thiếu ở đây rơi về default C++, KHÔNG
# rơi về block HybridLocalPlanner. Vì vậy đây là BẢN SAO ĐẦY ĐỦ, chỉ khác ở các dòng ghi `[DOCK]`.
#
# Thêm khoá mới vào block HybridLocalPlanner thì PHẢI thêm cả vào đây, nếu không chặng docking sẽ
# âm thầm chạy default C++ cho khoá đó.
#
# Các giá trị `[DOCK]` dưới đây là ĐIỂM XUẤT PHÁT, chưa đo trên robot thật.
# =================================================================================================
HybridDockingLocalPlanner:
library_path: libhybrid_local_planner
# ===== Giới hạn vận tốc =====
max_forward_velocity: 0.3 # [DOCK] vào dock chậm để sai số vị trí không tích luỹ
max_reverse_velocity: 0.2 # [DOCK] lùi ra khỏi dock chậm hơn nữa
avoidance_max_velocity: 0.2 # [DOCK] nếu có né thì phải rất chậm — nhưng xem use_obstacle_avoidance dưới
# max_forward_velocity để còn kịp phanh trong không gian hẹp
max_angular_velocity: 0.6 # [rad/s] trần tốc độ quay
min_velocity: 0.0 # [m/s] sàn của cửa sổ động DWA. Đặt khác 0 là ép robot
# không bao giờ được đứng yên — nguy hiểm
min_yawrate: 0.05 # [rad/s] độ lớn quay tối thiểu khi DWA đã quyết định quay.
# Dưới ngưỡng này servo không thắng nổi ma sát tĩnh
# ===== Giới hạn gia tốc — CÓ HAI TẦNG, đừng nhầm =====
# Tầng cửa sổ DWA (acc_lim_*, decel_lim_x): dựng dải vận tốc mà bộ lấy mẫu
# ĐƯỢC PHÉP cân nhắc. Đây là thứ quyết định DWA nghĩ tới những lệnh nào.
# Tầng kẹp đầu ra (output_acc_lim_*): kẹp lệnh cuối so với vận tốc đo từ odom,
# chạy ở cuối mỗi chu kỳ. Đây là thứ quyết định bánh xe bị yêu cầu đổi gấp đến đâu.
# Để tầng cửa sổ chặt hơn tầng đầu ra (như bản đang chạy) thì DWA tự giới hạn
# trước, tầng đầu ra gần như không cắn. Đặt ngược lại thì lệnh bị cắt SAU khi
# đã chấm điểm — DWA chọn một đằng, robot chạy một nẻo. Code sẽ cảnh báo nếu vậy.
acc_lim_x: 0.1 # [m/s^2] cửa sổ DWA, tăng tốc
decel_lim_x: 0.5 # [m/s^2] cửa sổ DWA, giảm tốc (độ lớn dương)
acc_lim_theta: 3.2 # [rad/s^2] cửa sổ DWA, gia tốc góc
output_acc_lim_x: 1.0 # [m/s^2] kẹp đầu ra, tịnh tiến
output_acc_lim_theta: 2.0 # [rad/s^2] kẹp đầu ra, quay. Ở 20 Hz, giá trị 2.0
output_decel_lim_theta: 6.0 # [rad/s^2] kẹp đầu ra khi lệnh quay đi VỀ PHÍA 0.
# Cùng lý do với output_decel_lim_x, và cùng kiểu hỏng khi thiếu:
# gần goal planner đòi -0.222 rad/s trong khi robot đang quay
# +0.59, giới hạn đối xứng 2.0 xuất ra +0.490 — robot quay SAI
# CHIỀU suốt 8 chu kỳ và sai số yaw tăng gấp đôi trước khi gỡ được.
# Giảm |omega| luôn khả thi về vật lý (ma sát giúp), nên số này
# đặt cao hơn hẳn giới hạn tăng tốc được
output_decel_lim_x: 2.0 # [m/s^2] kẹp đầu ra khi lệnh đi VỀ PHÍA 0 (đang phanh).
# Tách riêng khỏi output_acc_lim_x có chủ đích: giới hạn tăng tốc
# là chuyện êm ái, giới hạn giảm tốc là chuyện robot có dừng được
# hay không. Một giới hạn đối xứng đã từng TỪ CHỐI lệnh phanh —
# creep clamp đòi 0.40 m/s, tầng kẹp xuất ra 1.37 m/s và robot
# vọt qua goal. Phải LỚN HƠN output_acc_lim_x, nhưng đừng đặt vô
# cùng lớn: lệnh nhảy từ tốc độ cao về 0 trong một chu kỳ làm
# xê dịch hàng đang chở
brake_margin: 0.15 # [m] biên trừ vào quãng đường còn lại trước khi tính trần phanh
# trong DWA. Bù thời gian phản ứng một chu kỳ và dung sai goal
# cho phép omega đổi 0.1 rad/s mỗi chu kỳ
# ===== Quay tại chỗ =====
max_in_place_angular_velocity: 0.6 # [rad/s] trần tốc độ quay tại chỗ
min_in_place_angular_velocity: 0.3 # [rad/s] sàn tốc độ quay tại chỗ. Phải <= trần,
# nếu lớn hơn thì validate() tự hạ xuống và cảnh báo
# ===== Hình học robot và kiểm va chạm =====
min_turn_radius: 0.0 # [m] bán kính cua nhỏ nhất. 0 = không ràng buộc (vi sai).
# Khác 0 sẽ kẹp omega theo |v| / min_turn_radius
robot_radius: 0.1 # [m] bán kính robot, CHỈ dùng khi use_footprint = false
footprint_padding: 0.07 # [m] nới footprint ra mọi phía để có biên an toàn.
# Tăng = an toàn hơn nhưng khe hẹp sẽ bị coi là chặn.
# Mỗi 0.01 ở đây là 0.02 bề rộng khe cần thêm
use_footprint: true # true = kiểm va chạm theo footprint đa giác;
# false = coi robot là hình tròn bán kính robot_radius
turn_around_priority: false # [DOCK] TẮT: dừng xoay giữa chặng làm gãy đường vào dock
# xoay cho đúng hướng trước, thay vì vừa đi vừa lượn
# ===== Dung sai goal =====
xy_goal_tolerance: 0.015 # [DOCK] dung sai vị trí chặt hơn nhiều so với chạy tự do
yaw_goal_tolerance: 0.01 # [DOCK] dung sai góc chặt hơn: lệch góc ở dock là lệch cả thân robot
goal_yaw_gain: 1.0 # [1/s] hệ số tỉ lệ của pha xoay cuối: omega = gain * sai_số_yaw.
# Trước đây ngầm định 1.0 và không chỉnh được từ config. Bộ P
# thuần nối vào một tầng giới hạn tốc độ thay đổi là công thức
# kinh điển của dao động — còn lắc thì HẠ số này trước tiên
goal_yaw_deadband: 0.05 # [rad/s] vùng chết của pha xoay cuối: lệnh nhỏ hơn ngưỡng này
# bị ĐẨY RA bằng ngưỡng, để servo thắng được ma sát tĩnh.
# Chỉ áp khi sai số yaw còn NGOÀI yaw_goal_tolerance; trong dung
# sai thì lệnh bằng 0, nếu không robot vẫn bị bảo quay tiếp sau
# khi đã tới nơi.
# Đặt rộng hơn nhiều so với yaw_goal_tolerance là gây vọt góc
# ===== Lấy mẫu path toàn cục =====
max_global_plan_lookahead_dist: 1.5 # [DOCK] đường vào dock ngắn; nhìn xa quá là cắt cua vào dock
# Ngắn = bám sát nhưng cua gấp; dài = mượt nhưng cắt cua
global_plan_viapoint_sep: 0.12 # [DOCK] [m] cự ly giữa các điểm ngắm lấy ra từ path — đây
# cũng chính là BỀ RỘNG CỬA SỔ LÀM MƯỢT của luật lái: mọi chỗ
# path đổi độ cong (khớp cung->thẳng) đều bị trung bình hoá trên
# đúng cự ly này, nên robot duỗi thẳng SỚM chừng đó khi ra cung.
# Đo 27/8 (sep 0.2): ra khớp nối mang herr -0.10 rad, lệch ngang
# phồng 3 -> 30 mm trên đoạn thẳng rồi hồi gần cả mét.
# Hạ 0.2 -> 0.12: khớp nối sắc hơn ~40%, gain hồi lệch tăng
# (mẫu số luật lái là cự ly RAW tới điểm ngắm — từ 27/8 không còn
# sàn 0.3 ghim nữa, khoá này mới thật sự điều khiển cửa sổ).
#
# LỊCH SỬ ĐO, đừng lặp lại:
# 26/8 sep 0.2 -> 0.3 khi mẫu số CÒN ghim 0.3: xấu đi ~50%
# (understeer thuần — 30cm cuối 31/23/17/13/10 -> 38/34/27/21/16 mm)
# ► Chỉnh: nhỏ hơn -> bám sát, phản ứng nhanh, dễ nhiễu khi
# localization rung; lớn hơn -> mượt, cắt góc ở khớp nối.
# Sàn cứng kCuspLegLookaheadFloor = 0.10 trong code chặn nổ 1/L.
# trích từ path. Lúc chạy lấy max(|v|, giá trị này)
global_plan_goal_sep: 0.05 # [m] lấy mẫu dày hơn ở đoạn sát goal
# ===== Mô phỏng quỹ đạo của DWA =====
predict_time: 1.0 # [DOCK] [s] DWA mô phỏng quỹ đạo ứng viên trước bao lâu.
# HẠ TỪ 3.0 ngày 27/8. Rollout giữ NGUYÊN (v, omega) suốt
# predict_time, nên ứng viên sửa lệch ngang (omega ~0.3 để
# về path) bị vẽ thành cung 0.9 rad văng xuyên qua path và
# path_cost phủ quyết — đo được: tham chiếu đòi omega +0.29
# ...+0.42, DWA chỉ giao +0.09...+0.14, lệch 30 mm ở khớp
# cung->thẳng hồi gần cả mét. Ở tốc độ dock <=0.25 m/s,
# 3.0 s = chân trời 0.6-0.75 m trên chặng tổng 1.2 m.
# 1.0 s = 0.2 m: đủ thấy va chạm trước mặt, đủ ngắn để lệnh
# sửa lệch được chấm đúng bản chất tức thời của nó.
# ► Chỉnh: tăng nếu dock có vật cản động cần nhìn xa;
# giảm nữa thì cost nhìn quá gần, dễ dao động.
sim_period: 0.1 # [s] bước thời gian dùng khi dựng cửa sổ động
sim_time_samples: 10 # số bước mô phỏng trên mỗi quỹ đạo. Bước không gian
# xấp xỉ v * predict_time / sim_time_samples — ở v = 0.4
# là 0.12 m, tức LỚN HƠN một ô costmap: quỹ đạo có thể
# bước qua vật cản mỏng. Tăng số này để bắt được vật mỏng,
# đổi lại tốn CPU tuyến tính
dwa_arrival_distance: 0.05 # [m] dưới cự ly này tới goal cục bộ, DWA thôi lấy mẫu
# quỹ đạo chạy và chuyển sang xoay tại chỗ
dwa_in_place_turn_angle: 3.1416 # [rad] lệch hướng phải VƯỢT ngưỡng này thì DWA mới dừng
# xoay tại chỗ trước khi đi. Đặt >= pi (giá trị hiện tại)
# là TẮT hẳn nhánh đó — đúng như hành vi cũ. Hạ xuống
# (ví dụ 0.8) nếu muốn robot xoay cho thẳng hướng rồi mới chạy
# ===== Pure Pursuit (chỉ đánh lái) =====
pp_weight_omega: 1.5 # hệ số nhân sai lệch hướng ra tốc độ quay.
# Tăng = bám cua gắt hơn nhưng dễ dao động quanh path
pp_min_steering_velocity: 0.05 # [m/s] dưới ngưỡng này Pure Pursuit KHÔNG được ghi đè omega.
# Luật lái của nó là omega = |v| * pp_weight_omega * sin(err) / lookahead,
# ở v = 0 nó suy biến (không tồn tại bán kính cong) và luôn trả 0,
# nuốt mất lệnh xoay tại chỗ của DWA -> robot tự khoá: không quay
# được vì không chạy, không chạy được vì không quay.
# Trong dải này quyền quay trả về cho DWA.
# Đặt 0 = tắt bảo vệ, quay lại hành vi cũ (dễ kẹt).
# Đặt quá cao = PP hiếm khi lái, robot bám path kém hơn
pp_reference_gain: 2.0 # trọng số của số hạng |omega_ứng_viên − omega_PurePursuit|,
# nhân thêm (1 − b). Pure Pursuit KHÔNG còn ghi đè lệnh; nó chỉ
# nêu ý kiến, DWA chấm điểm ứng viên theo độ gần với ý kiến đó.
# Nhờ vậy lệnh xuất ra luôn là một quỹ đạo ĐÃ được chấm điểm va
# chạm — bản cũ để omega của PP đi thẳng ra bánh, không qua kiểm.
# 0 = bỏ hẳn ảnh hưởng của PP. Tăng = bám path sát hơn khi đường
# trống, nhưng không bao giờ vượt được độ phân giải yawrate_samples
pp_min_lookahead: 0.3 # [m] SÀN cho cự ly nhìn trước khi dựng tham chiếu lái.
# Luật lái mang 1/L, nên khi điểm nhìn trước bị "ăn" hết lúc
# sát goal thì hệ số từ sai số hướng ra độ cong PHÂN KỲ.
# Đo thật: ở L = 0.06 m, sai số 0.9 độ cho ra 0.44 rad/s và
# tham chiếu ĐỔI DẤU theo nhiễu cảm biến — đó chính là hiện
# tượng đánh lái lắc qua lại ở 20 cm cuối
pp_reference_min_distance: 0.05 # [DOCK] [m] dưới cự ly này tới cuối chặng thì TẮT HẲN tham chiếu
# lái. Lý do tồn tại của khoá: điểm nhìn trước bị robot nuốt dần
# ở cuối chặng, mà luật lái mang 1/L nên khi L -> 0 thì gain nổ
# và dấu lật theo nhiễu cảm biến.
#
# ĐÃ HẠ TỪ 0.5 XUỐNG 0.05 ngày 26/8. Lý do: pp_min_lookahead
# (0.3 m) đã chặn đúng cái 1/L đó rồi, nên 0.5 không bảo vệ thêm
# gì — nó chỉ TẮT LÁI ở đúng đoạn cần lái nhất. Terminal vào dock
# dài 0.583 m, tức gần như toàn bộ đoạn chui vào dock chạy không
# có tham chiếu, chỉ còn path cost kéo về. Đo trong sim 26/8:
# lệch ngang 31 mm ngay lúc vào miệng dock, trong khi dock_calc
# dựng đường với padding = 0.000 m, tức không có biên nào để nuốt.
#
# ► Chỉnh: 0.05 m xấp xỉ MỘT pose (global_plan_goal_sep = 0.05),
# tức chỉ tắt khi thật sự không còn gì để bám. Thấy robot rung
# lái ở vài centimet cuối thì tăng dần lên 0.10–0.15, ĐỪNG quay
# lại 0.5. Cũng kiểm pp_min_lookahead trước khi đổ cho khoá này.
# ===== Trọng số hàm cost của DWA =====
obs_cost_gain: 1.3 # phạt tiến gần vật cản
path_cost_gain: 2.5 # phạt lệch khỏi path toàn cục. Đây là khoá giữ robot
# trong lòng đường; giảm mạnh là robot cắt cua và men mép khe
to_goal_cost_gain: 0.8 # thưởng cho quỹ đạo tiến gần goal
speed_cost_gain: 0.5 # thưởng cho quỹ đạo chạy nhanh
# ===== Cảm nhận vật cản =====
obs_range: 2.5 # [m] bán kính quét vật cản quanh robot
# ===== Ngưỡng hành vi =====
segment_transition_threshold: 0.01 # [m] ngưỡng coi là đã tới hết một chặng path
use_obstacle_avoidance: false # [DOCK] TẮT: latch né vật cản bỏ hẳn path cost, robot sẽ lệch khỏi đường vào dock
# ===== Hoà trộn bám path <-> né vật cản (KHÔNG còn chế độ nhị phân) =====
# Toàn bộ quyết định gói trong MỘT số: b = mức độ path phía trước bị chắn.
# b = 0 path thông -> path cost đủ trọng số, obs cost = 0, DWA bám sát omega của Pure Pursuit
# b = 1 path bị chắn -> path cost = 0, obs cost đủ trọng số, bỏ qua Pure Pursuit
# Hai đầu tái lập ĐÚNG hai chế độ cũ. Khác biệt là ở giữa giờ mới có gì đó.
#
# b tính lại mỗi chu kỳ từ costmap, KHÔNG lưu trạng thái — nên không còn latch,
# không còn hai bộ tham số phải luân phiên set.
blend_start_distance: 3.0 # [m] vật cản xa hơn ngưỡng này thì coi như không có (b = 0)
blend_end_distance: 3.0 # [m] vật cản gần hơn ngưỡng này thì coi như chắn hẳn (b = 1).
# ĐỂ BẰNG blend_start_distance là b thành bậc nhảy, tái lập
# CHÍNH XÁC hành vi latch cũ — đây là cấu hình dùng để chứng minh
# refactor không đổi kết quả. Hạ xuống (vd 1.0) để có vùng
# chuyển tiếp mượt: robot bắt đầu né sớm và nhẹ thay vì giật
use_avoidance_velocity_limit: true # true = khi path bị chắn thì hạ trần về avoidance_max_velocity
# (fleet set 1.0 nhưng đang né thì chạy 0.4)
# false = GIỮ NGUYÊN vận tốc fleet đang set, để một mình hàm cost
# lo việc né. Cost blend không đổi trong cả hai trường hợp —
# cờ này CHỈ quyết định có kẹp tốc độ hay không.
# Đặt false khi muốn né mà không mất thời gian, đổi lại quỹ đạo né
# ở tốc độ cao cần cửa sổ động rộng hơn mới lách được
creep_distance: 0.8 # [m] cự ly tới cuối chặng mà vùng bò chậm bắt đầu.
# Ngưỡng THỰC = max(giá trị này, quãng phanh + creep_margin),
# nên nó chỉ NỚI RA theo tốc độ, không bao giờ thu lại: dưới
# khoảng 0.9 m/s thì số cố định thắng và hành vi y như cũ, còn
# ở tốc độ cao nó cắn đủ sớm để phanh kịp.
# Thu nhỏ số này là mất luôn cái sàn giữ robot không chết đứng
# trước goal
creep_margin: 0.3 # [m] cộng thêm vào quãng phanh khi tính ngưỡng
creep_max_velocity: 0.4 # [m/s] trần trong vùng bò chậm (độ lớn, dùng cho cả hai chiều)
creep_min_velocity: 0.05 # [m/s] sàn trong vùng bò chậm khi tiến — giữ robot không đứng
# lại trước goal
creep_min_velocity_reverse: 0.01 # [m/s] sàn khi lùi (độ lớn). Nhỏ hơn chiều tiến, giữ đúng số cũ
curve_max_velocity: 0.2 # [m/s] trần vận tốc khi đang trong khúc cua
reject_collisions_always: false # false = chỉ loại quỹ đạo va chạm khi b > 0 (HÀNH VI CŨ).
# Lưu ý: nghĩa là khi bám path DWA KHÔNG loại quỹ đạo va chạm
# nào cả, chỉ dựa vào b để né. true = loại mọi lúc, an toàn hơn
# nhưng ĐỔI kết quả solve của chế độ bám path
velocity_samples: 10 # số mẫu vận tốc trong cửa sổ động. Cũ: 10 khi bám path thẳng,
# 7 khi cua và khi né. Cửa sổ rộng <= 0.06 m/s nên chênh lệch
# giữa 7 và 10 là ~5 mm/s, không đo được
yawrate_samples: 20 # số mẫu tốc độ quay cho mỗi mức vận tốc. Đây là thứ quyết định
# omega chọn được bám sát omega của Pure Pursuit đến đâu:
# sai lệch tối đa = bề rộng cửa sổ quay / yawrate_samples
# để robot vẫn xoay được khi đang bò chậm
turn_direction_th: 0.1 # [rad] ngưỡng lệch hướng tối thiểu để DWA coi là cần rẽ
# ===== Bảo vệ TF plan -> global =====
# Mỗi lần AMCL sửa vị trí, transform map->odom dịch vài cm. Robot đứng yên
# nhưng CẢ PATH bị dịch dưới chân nó, nên Pure Pursuit thấy error_angle nhảy
# bậc và DWA thấy path cost nhảy bậc — đó là hiện tượng lắc khi bám path.
# Đóng băng transform trong suốt một chặng làm mất cú dịch đó; robot bám hoàn
# toàn trong frame liên tục (odom). Kiểm va chạm KHÔNG bị ảnh hưởng vì local
# costmap vẫn nằm ở frame liên tục với dữ liệu cảm biến sống.
plan_tf_freeze: true # [DOCK] BẬT: hiệu chỉnh định vị giữa chặng không được dịch đường vào dock dưới chân robot
# Bật lên chỉ sau khi đã chạy thử — xem ghi chú
# freeze_settle_cycles bên dưới
freeze_settle_cycles: 20 # [DOCK] chặng dock ngắn, không đủ thời gian chờ 30 chu kỳ; 20 vẫn phủ 2 chu kỳ AMCL ở 20 Hz
# PHẢI phủ >= 2 lần chu kỳ cập nhật định vị: AMCL 2 Hz
# với vòng điều khiển 20 Hz là >= 20 chu kỳ. Ngắn hơn thì
# cửa sổ rơi lọt giữa hai lần hiệu chỉnh — ở đó transform
# hằng số THEO ĐỊNH NGHĨA — và sẽ chốt ngay trước một
# hiệu chỉnh đang tới
freeze_settle_eps_xy: 0.005 # [m] bước dịch mỗi chu kỳ dưới ngưỡng này coi là yên
freeze_settle_eps_yaw: 0.005 # [rad] bước quay mỗi chu kỳ dưới ngưỡng này coi là yên
freeze_settle_timeout: 3.0 # [s] hết hạn mà chưa yên thì chốt luôn giá trị mới nhất,
# kèm cảnh báo. Bản đồ nhảy liên tục chính là điều kiện
# mà freeze sinh ra để trị; để sống tiếp là lắc cả chặng
tf_cache_max_age: 0.5 # [s] lookup lỗi thì lái tiếp trên transform đã cache tới
# ngần này rồi mới từ chối ra lệnh. Đặt 0 = dừng ngay khi
# trượt một nhịp TF, gây phanh nhấp khi publisher chập chờn
# ===== Debug =====
# Nhóm khoá bật log chẩn đoán [DBG-HYBRID-*]. Cùng quy ước với priest_local_planner:
# mức càng cao log càng dày, KHÔNG đổi hành vi điều khiển.
# 0 = tắt hẳn (mặc định, dùng khi chạy thật)
# 1 = chỉ log sự kiện đổi trạng thái (đổi hướng tiến/lùi, bật/tắt latch né vật cản,
# DWA trả lệnh 0, ô costmap nào chặn đường)
# 2 = mức 1 + log định kỳ 1 Hz cho từng chỗ ghi (không chỗ nào bị bỏ đói)
# 3 = in mọi chu kỳ điều khiển — chỉ dùng khi bắt lỗi ngắn, rất nặng I/O
debug_level: 0
# Các khoá dưới bật/tắt từng nhóm log, chỉ có tác dụng khi debug_level >= 1.
debug_command: true # [DBG-HYBRID-CMD] pose, lệnh cuối (v, omega), tầng kẹp gia tốc, kẹp bò chậm
debug_dwa: true # [DBG-HYBRID-DWA] output thô của DWA, hồ sơ cost và số mẫu khi đổi chế độ
debug_purepursuit: true # [DBG-HYBRID-PP] error_angle, lookahead, và omega mà PP ghi đè lên DWA
debug_mode: true # [DBG-HYBRID-MODE] đổi hướng tiến/lùi, xong căn hướng đầu, đạt xy_goal
debug_collision: true # [DBG-HYBRID-OBS] swapPlan/checkObstacles: chặn ở pose nào, ô costmap nào, cost bao nhiêu
debug_goal: true # [DBG-HYBRID-GOAL] khoảng cách tới goal, sai lệch yaw, các cờ đã latch
debug_tf: true # [DBG-HYBRID-TF] chốt/nhả đóng băng, độ lệch transform, lái trên cache
debug_path: true # [DBG-HYBRID-PATH] bám path: cross-track có dấu (+ = robot lệch TRÁI so với
# chiều đi của path), sai lệch hướng so với tiếp tuyến path, cự ly còn lại
# tới cuối chặng, và ngưỡng chuyển chặng. Đây là dòng để trả lời "robot có
# bám path không" và "chuyển chặng có đúng ở cusp không".

View File

@@ -9,14 +9,14 @@ trolley:
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
timeout: 60.0
vel_x: 0.25
vel_x: 0.2
vel_theta: 0.3
yaw_goal_tolerance: 0.015
xy_goal_tolerance: 0.015
min_lookahead_dist: 0.4
max_lookahead_dist: 1.0
lookahead_time: 1.5
angle_threshold: 0.16
angle_threshold: 0.4
qrcode:
maker_goal_frame: qr_trolley
@@ -30,7 +30,7 @@ trolley:
min_lookahead_dist: 0.4
max_lookahead_dist: 1.0
lookahead_time: 1.5
angle_threshold: 0.16
angle_threshold: 0.4
charger:
plugins:
@@ -41,13 +41,13 @@ charger:
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
timeout: 60
vel_x: 0.1
vel_x: 0.15
yaw_goal_tolerance: 0.015
xy_goal_tolerance: 0.015
min_lookahead_dist: 0.4
max_lookahead_dist: 1.0
lookahead_time: 1.5
angle_threshold: 0.16
angle_threshold: 0.4
dock_station:
plugins:
@@ -102,7 +102,7 @@ undock_station:
min_lookahead_dist: 0.4
max_lookahead_dist: 1.0
lookahead_time: 1.5
angle_threshold: 0.16
angle_threshold: 0.4
qrcode:
maker_goal_frame: qr_trolley
@@ -116,7 +116,7 @@ undock_station:
min_lookahead_dist: 0.4
max_lookahead_dist: 1.0
lookahead_time: 1.5
angle_threshold: 0.16
angle_threshold: 0.4
undock_station_2:
plugins:
@@ -135,7 +135,7 @@ undock_station_2:
min_lookahead_dist: 0.4
max_lookahead_dist: 1.0
lookahead_time: 1.5
angle_threshold: 0.16
angle_threshold: 0.4
qrcode:
maker_goal_frame: qr_trolley
@@ -149,4 +149,4 @@ undock_station_2:
min_lookahead_dist: 0.4
max_lookahead_dist: 1.0
lookahead_time: 1.5
angle_threshold: 0.16
angle_threshold: 0.4

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,25 +1,119 @@
position_planner_name: StanleyLocalPlanner #HybridLocalPlanner MPPILocalPlanner PriestLocalPlanner PNKXLocalPlanner
docking_planner_name: PNKXDockingLocalPlanner #StanleyDockingLocalPlanner PNKXDockingLocalPlanner
go_straight_planner_name: PNKXGoStraightLocalPlanner
rotate_planner_name: PNKXRotateLocalPlanner
base_local_planner: LocalPlannerAdapter
base_global_planner: CustomPlanner
StanleyLocalPlanner:
base_local_planner: LocalPlannerAdapter
base_global_planner: CustomPlanner #CustomPlanner SBPLLatticePlanner
PNKXDockingLocalPlanner:
base_local_planner: LocalPlannerAdapter
base_global_planner: TwoPointsPlanner
PNKXGoStraightLocalPlanner:
base_local_planner: LocalPlannerAdapter
base_global_planner: TwoPointsPlanner
PNKXRotateLocalPlanner:
base_local_planner: LocalPlannerAdapter
base_global_planner: TwoPointsPlanner
### replanning
controller_frequency: 20.0 # run controller at 15.0 Hz
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_patience: 5.0 # if the first planning attempt failed, abort planning retries after 5.0 s...
max_planning_retries: 5 # ... or after 10 attempts (whichever happens first)
oscillation_timeout: -1 # abort controller and trigger recovery behaviors after 30.0 s
oscillation_distance: 0.4
### recovery behaviors
recovery_behavior_enabled: true
controller_frequency: 30.0 # [Hz] nhịp chạy vòng điều khiển
controller_patience: 0.0 # [s] controller lỗi thì xoá vật cản rồi thử lại; quá ngưỡng này thì bỏ và lập plan mới. 0 = bỏ ngay
planner_frequency: 0.0 # [Hz] nhịp lập plan lại khi đang bám path. 0 = KHÔNG lập lại, chỉ lập khi controller lỗi
planner_patience: 2.0 # [s] lập plan lỗi thì thử lại trong bấy lâu rồi mới bỏ cuộc...
# Số lần lập plan HỎNG liên tiếp được phép trước khi leo thang recovery (điều kiện nào tới trước
# giữa khoá này và `planner_patience` thì thắng). CHÚ Ý: 0 = hỏng MỘT lượt là leo thang ngay,
# KHÔNG phải "không giới hạn"; muốn không giới hạn thì đặt -1 (chỉ an toàn khi planner_patience > 0).
max_planning_retries: 0
# [s] Trần chờ ở CANCELLING và PAUSING cho tới khi runtime IM HẲN rồi mới báo CANCELLED/PREEMPTED
# hoặc PAUSED ra host (lúc PAUSING host vẫn thấy tên state cũ + feed_back_str "pausing…"):
# lệnh = 0 và odom ≈ 0, thread global planner rảnh và recovery đã dừng (kể cả lượt makePlan đã huỷ mà plugin không cắt
# được), action đã trả terminal. Quá trần vẫn CANCELLED nhưng in LỖI "settle timeout".
# ► Chỉnh: TĂNG (5–10) nếu SBPL `allocated_time` lớn và chưa có preempt. 0 = TẮT (báo ngay khi
# lệnh = 0 như trước 11/9/2026 — host dễ gửi goal kế lúc planner còn bận, goal kế bị coi là hỏng).
settle_timeout: 2.0
# [m/s] Ngưỡng coi robot ĐÃ DỪNG theo odom (bánh xe còn giảm tốc sau khi lệnh = 0). Chỉ có tác dụng
# khi host đẩy odom vào; không có odom thì lùi về đo bằng lệnh. 0 = bỏ odom.
# ► Chỉnh: TĂNG (0.05) nếu odom nhiễu giữ CANCELLING tới tận settle_timeout dù robot đã đứng.
stopped_measured_linear_eps: 0.02
# [rad/s] Như trên cho trục quay.
stopped_measured_angular_eps: 0.02
oscillation_timeout: -1 # [s] robot dao động tại chỗ quá lâu thì bỏ controller và chạy recovery. -1 = tắt
oscillation_distance: 0.5
# [m] Recovery THÀNH CÔNG và nộp path mới chỉ được nạp lại ngân sách route khi robot đã đi được ít
# nhất quãng này kể từ lần nạp lại trước; chưa đi được thì tính như thất bại (chặn vòng "replan
# thành công -> bị chặn tại chỗ -> replan", sim 2026-09-04). 0 = nạp lại vô điều kiện (hành vi cũ).
# Phải <= oscillation_distance.
recovery_reset_min_travel: 0.10
## recovery behaviors
#
# 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: [
{name: aggressive_reset, type: clear_costmap_recovery/ClearCostmapRecovery},
{name: conservative_reset, type: clear_costmap_recovery/ClearCostmapRecovery},
{name: aggressive_reset, type: ClearCostmapRecovery},
{name: conservative_reset, type: ClearCostmapRecovery},
]
conservative_reset:
reset_distance: 3.0 # clear obstacles farther away than 3.0 m
reset_distance: 3.0 # [m] xoá vật cản nằm xa hơn khoảng này khỏi costmap
invert_area_to_clear: true
aggressive_reset:
reset_distance: 3.0
ClearCostmapRecovery:
library_path: librobot_clear_costmap_recovery
MoveBase:
library_path: libmove_base
# =================================================================================================
# Watchdog thành phần (2026-09-11) — thread riêng đọc bảng trạng thái, kết luận "TREO"
#
# Mỗi thành phần (global planner, local planner, recovery, action, control loop) tự khai nó đang
# bận/dừng/rảnh và "nhích" mỗi nhịp. Watchdog chạy trên thread riêng — control thread treo thì
# không tự phát hiện được chính nó — và kết luận treo khi một hàng BẬN mà KHÔNG NHÍCH quá ngân sách.
# Treo → in LỖI một lần (không tắt được); control loop treo → host đọc navigation_state = LOST và
# phải tự đưa cmd_vel về 0. Đây là chẩn đoán, không phải điều khiển: state machine không đổi gì.
# =================================================================================================
# [s] Chu kỳ kiểm của watchdog. 0 = TẮT watchdog (không có thread, không phát hiện treo).
watchdog_period: 0.1
# [s] Trần MỘT lượt makePlan trên thread planner trước khi kết luận global planner TREO. Từ 11/9/2026
# khoá này mới có tác dụng (trước đó đọc mà không dùng). PHẢI LỚN HƠN thời gian một lượt hợp lệ dài
# nhất: với SBPL là `allocated_time` trong sbpl_global_params.yaml (đã là trần chung cho cả 3 lượt
# replan nội bộ). ► Chỉnh: đặt ≈ allocated_time + 1. 0 = không giám sát hàng này.
planner_timeout: 5.0
# [s] Trần MỘT lời gọi computeVelocityCommands của local planner. Priest 30–48 ms, Hybrid < 10 ms;
# 0.5 s là "chắc chắn có gì đó hỏng" chứ không phải chậm. 0 = không giám sát.
local_planner_call_budget: 0.5
# [s] Recovery behavior bận mà không nhích (không tick, worker detour không về) quá đây = treo.
recovery_stall_budget: 5.0
# [s] Action handler bận mà không nhích quá đây = treo. 0 = TẮT (mặc định): handler tự timeout
# theo thiết bị của nó (tầng 1), `action_patience` là tầng 2 — không cần tầng thứ ba.
action_stall_budget: 0.0
# [s] Control thread không kết thúc được một cycle nào trong quãng này = TREO → host thấy LOST.
# 0.5 s = 15 cycle @ 30 Hz. GIẢM (0.2) nếu host cần phản ứng nhanh hơn; không đặt < 3 cycle vì
# một lượt detour/solve dài hợp lệ sẽ bị báo nhầm.
control_loop_stall_budget: 0.5

View File

@@ -0,0 +1,299 @@
MPPILocalPlanner:
library_path: libmppi_local_planner
# ===== Giới hạn robot [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
# [m] Bán kính hình tròn DỰ PHÒNG, chỉ dùng khi chưa có footprint hợp lệ (trước
# setPlan đầu tiên, hoặc footprint suy biến). Có footprint thì hình dạng thật được
# dùng thay và hai khoá này không còn ảnh hưởng tới kiểm va chạm.
robot_radius: 0.30
# [m] Bán kính của MỘT ô costmap. Ô costmap không phải điểm toán học — bỏ qua bán
# kính này làm bán kính va chạm hiệu dụng thiếu đi đúng chừng ấy.
obstacle_point_radius: 0.08
# Hệ số nở khung xe khi kiểm va chạm. Bản Python dùng 1.2, nhưng ở đây footprint
# lấy từ costmap ĐÃ được pad sẵn bằng "footprint_padding" của costmap, nên để 1.0
# để không nở hai lần. Tăng lên nếu muốn thêm biên an toàn; 1.1 = nở 10% mọi chiều.
# Không nhận giá trị < 1.0 (thu nhỏ khung xe không bao giờ là thứ người dùng muốn).
collision_safety_margin_rate: 1.0
footprint_padding: 0.05
# ===== Lõi MPPI =====
# 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
# Tỉ lệ mẫu lấy quanh nominal (ref_velocity, 0) thay vì quanh nghiệm chu kỳ trước.
# Đo trên đường thẳng-cung R=3 m, trung bình 12 lần chạy: 0.20 cho v nhanh hơn 8%
# nhưng sai lệch ngang xấu đi 25%; 1.00 thì robot văng khỏi đường (sai lệch 1.7 m).
# Giữ 0.05 như bản Python.
param_exploration: 0.05
# [bước] Cửa sổ lọc trung bình trượt áp lên bước cập nhật control — cơ chế làm mượt
# chính của MPPI. Nhỏ quá thì lệnh giật (window=1: độ giật gấp 5 lần), lớn quá thì
# phản ứng chậm và bám đường xấu đi (window=20: sai lệch ngang 0.149 m so với 0.117).
# Tự kẹp vào [1, time_steps].
control_filter_window: 10
vx_std: 0.2
wz_std: 0.25
reference_velocity: 0.48
# ===== Path và 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
# [m] Vào trong ngưỡng này thì CHỐT lại: từ đó v = 0 tuyệt đối, robot chỉ còn xoay
# về yaw đích. Chốt là thứ chặn robot đi xuyên qua đích — nó không lùi lại được
# (min_velocity = 0). Chốt được nhả khi có plan mới.
xy_goal_tolerance: 0.03
# [rad] Đạt cả hai ngưỡng thì báo tới đích lên move_base2.
yaw_goal_tolerance: 0.02
# [m] Bán kính BẮT của cơ chế "đã đi qua đích" (theo hybrid_local_planner).
# Chốt theo xy_goal_tolerance một mình là không đủ: khi vật cản chắn lối vào đích,
# robot không bao giờ vào nổi trong tolerance. Đo trên sim: nó tới gần nhất 0.29 m
# rồi trôi ra 0.60 m và không bao giờ báo tới đích — vì min_velocity = 0 nên không
# lùi lại được.
# Trong bán kính này, controller bám khoảng cách NHỎ NHẤT từng đạt; khi khoảng cách
# bắt đầu tăng trở lại quá goal_overshoot_margin thì coi như đã qua điểm gần nhất
# với tới được -> dừng tịnh tiến và xoay về yaw đích.
# Chỉ áp dụng ở chặng CUỐI và sau khi đã đi quá nửa đường tham chiếu.
goal_capture_radius: 0.6
# [m] Phải xa hơn khoảng cách nhỏ nhất thêm ngần này mới coi là đã đi qua — chặn
# việc chốt nhầm vì nhiễu pose vài milimet.
goal_overshoot_margin: 0.05
# ===== Costmap và trọng số hàm chi phí =====
obstacle_range: 2.5
obstacle_cost_threshold: 150
# Bước lấy mẫu costmap: 1 = mọi ô, 2 = cách một ô mỗi trục.
# Giữ 2. Đã đo bước 1: nó KÉM hơn (khoảng hở 0.958 so với 1.020 m) và đắt gấp 2.4
# lần (3.50 so với 1.45 ms), vì cùng một max_obstacle_points thì mật độ gấp 4 làm
# số điểm gần nhất chỉ phủ được bán kính nhỏ hơn ~2 lần — cắt mất đúng dải 1-2 m
# mà obstacle_influence_radius = 2.0 cần tới.
# Đánh đổi còn lại của bước 2: một vật cản mảnh chiếm đúng MỘT ô lethal (cột, chân
# bàn) chỉ có ~25% cơ hội được lấy mẫu, nên nó có thể không được tính là va chạm
# CỨNG. Quầng inflation cost ~253 quanh nó vẫn vào trường mềm nên robot vẫn né,
# chỉ là không có rào 1e6. Muốn chắc chắn với vật cản mảnh thì đặt 1 VÀ nâng
# max_obstacle_points lên ~4000 (kiểm lại CPU: ~11% ngân sách).
# Độ lớn trường cost KHÔNG đổi khi chỉnh khoá này: core chuẩn hoá cost mềm theo
# diện tích ô (obstacle_sample_area), nên obstacle_weight giữ nguyên ý nghĩa.
obstacle_cell_step: 2
# Trần số điểm vật cản đưa vào bộ giải, giữ lại các điểm GẦN NHẤT.
# Đây là van an toàn CPU, không phải tham số tinh chỉnh — đặt cao hơn số điểm thực
# tế để không cắt mất thông tin. Đo trong môi trường dày (hành lang + khối chặn):
# trần 180 cắt từ 281 điểm xuống 168 và làm khoảng hở tụt 1.020 -> 0.750 m;
# trần 400 cho kết quả y hệt không có trần.
# ĐANG ĐỂ 180 = giá trị cuối cùng ĐÃ VERIFY TRÊN SIM (xem obstacle_influence_radius).
# Nâng lên 1200 cùng lúc với influence 2.0 nằm trong cùng lần hỏng đó.
max_obstacle_points: 180
# [m] Bán kính trường cost mềm, đo từ TÂM robot.
#
# GIỮ 1.0 — giá trị cuối cùng ĐÃ VERIFY TRÊN SIM (lần chạy 17:22: tới đích 3 lần,
# v trung vị 0.431). Đã thử 1.5 và HỎNG: 4 lượt chạy liên tiếp sau đó KHÔNG tới đích
# lần nào, robot lượn vòng kín quanh vật cản giữa đường (chu kỳ ~31 s, lặp 5 vòng,
# khoảng cách tới đích không bao giờ xuống dưới 3.1 m).
#
# Về lý thuyết nới R chỉ làm trường VƯƠN XA hơn chứ không MẠNH hơn (core đã chia cho
# (R/1.0)^2, xem influence_scale trong mppi_core.cpp) — nhưng thực tế trên sim vẫn
# hỏng, nên đừng nới lại nếu chưa hiểu tại sao. Bench KHÔNG tái hiện được ca này.
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 / terminal_progress_weight / goal_weight ĐÃ BỊ BỎ ở Phase 3.
# - progress_weight tồn tại để bù cho một phép chiếu có thể trượt lùi; cửa sổ chiếu
# TIẾN (path_search_arclength) đã giải quyết bằng cấu trúc, và (v - ref_v)^2 mới
# là thứ đẩy robot đi tới.
# - goal_weight neo vào pose cuối của đường tham chiếu, mà đó là điểm TRƯỢT (cuối
# segment / cuối cửa sổ), không phải đích nhiệm vụ. Việc dừng ở đích do chốt
# xy_goal_tolerance lo.
# 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.
# Phạt |v|^2 và |omega|^2 thuần tuý. Bản Python KHÔNG có hai khoá này; chúng chống
# trực tiếp với mục tiêu vận tốc nên để 0.
linear_control_weight: 0.0
angular_control_weight: 0.0
# Phạt ĐỔI control giữa hai bước. Đây là chỗ CỐ Ý KHÁC bản Python: ở đó control là
# (steer, accel) nên giới hạn gia tốc có sẵn trong mô hình, còn ở đây control là
# (v, omega) trực tiếp — không có gì chặn lệnh nhảy từ 0 lên 0.65 trong một chu kỳ.
# Giữ lại làm giới hạn gia tốc. Giảm về 0 thì lệnh giật, tăng thì robot ì.
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.
# 0 = bám đúng reference_velocity bất kể sai lệch yaw, giống bản Python. Sai lệch
# yaw lớn đã do pha căn hướng đầu chặng (align_at_path_start) xử lý trước khi MPPI
# chạy, nên không cần giảm tốc theo yaw nữa.
yaw_error_slowdown: 0.0
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 thích nghi (giai đoạn 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
# Nhiệt độ softmax dùng RIÊNG cho phép fit Gaussian ước lượng sigma thích nghi.
# Phải nhỏ hơn param_lambda (100), nhưng KHÔNG được nhỏ quá so với độ trải cost:
# exp(-dS/lambda) với lambda quá nhỏ dồn hết trọng số vào một mẫu, Gaussian fit ra
# cực hẹp và sigma rơi xuống SÀN.
# Giá trị 5.0 được tune khi stage_speed_weight còn 20; nâng lên 400 làm độ trải cost
# lớn hơn ~20 lần và phá vỡ nhiệt độ này. Log robot thật: vx_std nằm ở sàn 0.080
# trong 28/38 chu kỳ, KỂ CẢ khi không có mẫu nào va chạm — mẫu vận tốc chỉ trải
# ±0.16 nên lệnh không leo nổi lên ref_v.
# Đo trên đường thẳng-cung R=3 m, trung bình 12 lần chạy:
# 5 -> v 0.390, sai lệch ngang 0.1272, 81% chu kỳ vx_std ở sàn
# 15 -> v 0.413, sai lệch ngang 0.0340 <- bám đường tốt hơn 3.7 lần
# 30 -> v 0.428, sai lệch ngang 0.0370, độ giật +40%
# 60 -> v 0.434, sai lệch ngang 0.0349, độ giật +170%
# Chỉnh lại nếu đổi mạnh các trọng số cost: giữ tỉ lệ với độ trải cost.
gaussian_fitting_lambda: 15.0
# [m/s] SÀN của độ lệch chuẩn lấy mẫu vận tốc.
#
# GIỮ 0.08 — giá trị đã verify trên sim. Đã thử 0.15 (bench báo tốt hơn trên mọi
# trục: v 0.413 -> 0.430, hồi phục sau vật cản 3.08 s -> 0.16 s) nhưng trên robot
# thật thì TỆ HƠN HẲN: v trung vị 0.431 -> 0.199 (-54%). Nguyên nhân: sàn 0.15 làm
# sigma bị ghim ở sàn Ở MỌI CHU KỲ (trung vị = min = 0.150), mất hẳn tính thích
# nghi, và nhiễu lấy mẫu rộng làm nhiều mẫu va chạm hơn nên trung bình có trọng số
# bị kéo xuống.
# Đừng chỉnh khoá này dựa trên bench — bench không tái hiện được môi trường thật.
min_vx_std: 0.08
max_vx_std: 0.35
min_wz_std: 0.10
max_wz_std: 0.60
# Khi bi ket, nở rộng sigma dần qua từng chu kỳ để thoát cực tiểu địa phương.
stuck_sigma_inflation: 1.6
# Tỉ lệ mẫu va chạm mà từ đó coi batch là KHÔNG MANG THÔNG TIN -> nở sigma thay vì
# fit lại. Trước đây van này chỉ mở khi emergency_stop, tức 100% mẫu va chạm.
# Log robot thật cho thấy đó là quá muộn: suốt đoạn lết, số mẫu va chạm là
# 192-217/220 nên emergency_stop không bao giờ bật; adaptive covariance vẫn fit vào
# vài mẫu sống sót (đều là loại "gần đứng yên") và bóp sigma xuống SÀN —
# wz_std = 0.100 = min_wz_std, trong khi cú lách để thoát cần omega = -0.66, xa 6
# sigma. Càng kẹt càng hẹp, càng hẹp càng kẹt. Chỉ khi chạm đúng 220/220 van mới mở
# và robot thoát ngay chu kỳ sau.
# Đặt quá thấp (< ~0.5): sigma nở khi robot vẫn đang bám đường tốt -> lệnh giật.
# Đặt 1.0 = quay lại hành vi cũ (chỉ mở ở 100%).
# 0.65 chứ không phải 0.8: log robot thật cho thấy vùng KẸT nằm ở 67-77% mẫu va
# chạm (t=1..4: 75/72/77/73%), tức ngay DƯỚI ngưỡng 0.8 nên van không mở và wz_std
# nằm ở sàn. Van chỉ mở đúng một lần ở 83% và robot thoát ngay chu kỳ sau.
# Chu kỳ chạy bình thường ở 0-24%, chuyển tiếp 38-61%, nên 0.65 vẫn nằm trên dải
# bình thường và không nở sigma khi robot đang bám đường tốt.
sigma_inflation_collision_ratio: 0.65
hard_obstacle_cost_threshold: 254
stage_xy_weight: 50.0
stage_yaw_weight: 1.0
# Trọng số bám vận tốc. KHÔNG chép được từ bản Python: số hạng này là
# weight * (v - ref_v)^2 nên đóng góp của nó tỉ lệ với ref_v^2.
# Cán cân quyết định "đứng chờ" hay "đi vòng" là:
# đứng yên tốn speed_weight * ref_v^2
# đi vòng tốn xy_weight * (độ lệch ngang)^2
# Python: xe ~10 m/s, vòng 4 m -> 20*100 = 2000 so với 50*16 = 800, đứng yên đắt
# gấp 2.5 -> xe chọn đi vòng.
# AMR : 0.48 m/s, vòng 1.1 m -> 20*0.23 = 4.6 so với 50*1.21 = 58, đi vòng đắt
# gấp 12 -> robot chọn đứng chờ. Cán cân bị lật ngược.
# Đo trên kịch bản khối chặn nửa lối đi: weight 20 -> 0% qua được; 400 -> 100%.
# Trên đường sạch: 20 -> v 0.316; 400 -> v 0.392 và sai lệch ngang tốt hơn.
# Chỉnh lại nếu đổi reference_velocity nhiều: giữ speed_weight * ref_v^2 không đổi.
stage_speed_weight: 400.0
terminal_xy_weight: 50.0
terminal_yaw_weight: 1.0
terminal_speed_weight: 400.0
# ===== Cửa sổ chiếu tiến (port từ python_simple_mppi) =====
# Điểm tham chiếu chỉ được tìm về PHÍA TRƯỚC, không bao giờ lùi. Không có nó,
# rollout có thể chiếu lên đoạn đường robot đã đi qua — tức là được thưởng cho
# việc quay đầu lại.
# [m] Cửa sổ tìm kiếm tính theo chiều dài đường, không theo số điểm, để không phụ
# thuộc mật độ điểm của global planner. Phải phủ được quãng rollout đi xa nhất
# (time_steps * model_dt * max_velocity = 20 * 0.2 * 0.65 = 2.6 m); đặt nhỏ hơn thì
# trạng thái cuối horizon chiếu nhầm vào waypoint chưa tới. Tự nâng lên nếu quá nhỏ.
path_search_arclength: 4.0
# [m] Ngưỡng nhả khoá. Cửa sổ chỉ tiến nên bám nhầm một lần là bám nhầm mãi; nếu
# điểm gần nhất trong cửa sổ vẫn xa hơn ngưỡng này thì coi như robot đã rời đường
# (recovery đẩy ra, bị đẩy tay, localization nhảy) và quét lại toàn bộ để đặt lại.
# Đặt quá nhỏ: chỉ số bị đặt lại liên tục, mất tính đơn điệu. Quá lớn: robot bám
# theo một điểm tham chiếu nó không còn với tới được.
path_release_distance: 1.5
# ===== Căn hướng đầu chặng =====
# Xoay tại chỗ cho thẳng hướng đường trước khi giao quyền cho MPPI.
# Vì sao cần: sai lệch yaw chỉ vào cost qua stage_yaw_weight, mà trọng số đó rất
# nhỏ so với stage_xy_weight, nên khi lệch hướng ~180 độ nghiệm tối ưu của MPPI là
# "bò thật chậm và quét một cung rộng". Đo trên sim: 19-22 s mỗi chặng, cung rộng
# 0.75 m — trong lối đi hẹp là va chạm.
# Chạy lại mỗi khi có plan mới HOẶC chuyển sang segment kế tiếp.
align_at_path_start: true
# [rad] Sai lệch còn lại thì coi là căn xong. Nhỏ quá thì robot lắc quanh ngưỡng
# và không bao giờ chuyển sang MPPI; lớn quá thì bàn giao khi còn lệch nhiều.
align_yaw_tolerance: 0.15
# [rad/s] Trần tốc độ xoay khi căn hướng. Tự kẹp xuống max_angular_velocity.
# BA khoá align_max/min/gain còn dùng lại cho pha XOAY CUỐI ở đích (xem
# xy_goal_tolerance bên dưới) — cùng một động tác vật lý là xoay tại chỗ.
align_max_angular_velocity: 0.8
# [rad/s] Sàn tốc độ xoay. Dưới sàn thì bánh không thắng nổi ma sát tĩnh, robot
# đứng im trong khi bộ đếm timeout vẫn chạy. Đặt 0.0 để tắt sàn.
# Sàn KHÔNG được áp khi đã nằm trong tolerance — nếu áp, lệnh cuối cùng robot nhận
# là quay vượt qua đúng cái mục tiêu nó vừa chạm.
align_min_angular_velocity: 0.15
# [1/s] Hệ số P: omega = gain * sai_lệch_yaw. Tăng thì xoay dứt khoát hơn nhưng
# dễ vọt qua ngưỡng và lắc.
align_angular_gain: 1.2
# [m] Chiều dài dây cung dùng để đo hướng của đường. Ngắn quá thì nhiễu yaw từng
# điểm của global planner lọt thẳng vào hướng mục tiêu.
align_lookahead: 0.5
# [chu kỳ] Hết số chu kỳ này mà chưa căn xong thì BỎ QUA và đi tiếp bằng MPPI.
# 200 chu kỳ = 10 s @20 Hz. Không để vô hạn: xoay tại chỗ mãi thì không bao giờ
# tới đích, và nếu servo hỏng thật thì đứng im vĩnh viễn sẽ giấu mất lỗi đó.
align_timeout_cycles: 200
# =================================================================================================
# Log chẩn đoán [DBG-MPPI-*]
# =================================================================================================
# Người đọc: người vận hành / kỹ sư đang debug tại chỗ. Log đi ra console của
# `amr_node`, cùng chỗ với log của các planner khác.
#
# debug_level điều khiển TẦN SUẤT, các khoá debug_* bên dưới điều khiển NHÓM nào
# được in. Cùng ngữ nghĩa với hybrid_local_planner:
# 0 = tắt hoàn toàn (mặc định khi chạy thật)
# 1 = chỉ sự kiện đổi trạng thái (plan mới, cắt segment, tới đích, lỗi TF)
# 2 = thêm các dòng định kỳ, throttle 1 Hz theo TỪNG dòng log
# 3 = in mọi chu kỳ điều khiển — CHỈ dùng khi soi một đoạn ngắn, mức này
# sinh ~20 dòng/giây và làm chậm vòng điều khiển
# Bật nhiều nhóm cùng lúc không nhóm nào bị bỏ đói: mỗi dòng có bộ đếm throttle
# riêng.
debug_level: 0
# Các khoá dưới chỉ có tác dụng khi debug_level >= 1.
debug_command: true # [DBG-MPPI-CMD] lệnh cuối (v, omega), số mẫu va chạm, số điểm vật cản
debug_plan: true # [DBG-MPPI-PLAN] cắt segment, plan sau transform, lookahead, plan rỗng
debug_goal: true # [DBG-MPPI-GOAL] khoảng cách tới đích, sai lệch yaw so với tolerance
debug_obstacle: true # [DBG-MPPI-OBS] số điểm vật cản, điểm gần nhất, cửa sổ quét costmap
debug_tf: true # [DBG-MPPI-TF] lookup transform thất bại (frame nào sang frame nào)
debug_stuck: true # [DBG-MPPI-STUCK] bộ đếm kẹt so với stuck_patience_cycles
# Sigma thích nghi in mỗi chu kỳ 1 dòng; chỉ bật khi đang tune adaptive_covariance.
debug_sigma: true # [DBG-MPPI-SIG] độ lệch chuẩn đã thích nghi ở bước đầu và bước cuối
# [DBG-MPPI-TIME] đo thời gian từng giai đoạn, ĐỘC LẬP với debug_level ở trên.
# Đơn vị là số chu kỳ: 0 = tắt, 1 = in mỗi chu kỳ, 20 = in mỗi 20 chu kỳ (~1 s @20 Hz).
# Giữ ở mức thưa khi chạy thật — toàn bộ computeVelocityCommands chạy trong lúc
# move_base2 đang giữ costmap, nên log dày ở đây làm chậm cả vòng cập nhật costmap.
timing_log_period: 0

View File

@@ -62,12 +62,12 @@ publish_acceleration: false
# estimation node from robot_localization! However, that instance should *not* fuse the global data.
map_frame: map # Defaults to "map" if unspecified
odom_frame: $(arg tf_prefix)odom # Defaults to "odom" if unspecified
base_link_frame: $(arg tf_prefix)base_footprint # Defaults to "base_link" if unspecified
base_link_frame: $(arg tf_prefix)base_link # Defaults to "base_link" if unspecified
world_frame: $(arg tf_prefix)odom # Defaults to the value of odom_frame if unspecified
# The filter accepts an arbitrary number of inputs from each input message type (nav_msgs/Odometry,
# The filter accepts an arbitrary number of inputs from each input message type (robot_nav_msgs/Odometry,
# geometry_msgs/PoseWithCovarianceStamped, geometry_msgs/TwistWithCovarianceStamped,
# sensor_msgs/Imu). To add an input, simply append the next number in the sequence to its "base" name, e.g., odom0,
# robot_sensor_msgs/Imu). To add an input, simply append the next number in the sequence to its "base" name, e.g., odom0,
# odom1, twist0, twist1, imu0, imu1, imu2, etc. The value should be the topic name. These parameters obviously have no
# default values, and must be specified.
odom0: odom

View File

@@ -25,7 +25,7 @@ Amcl:
update_min_d: 0.05
update_min_a: 0.05
odom_frame_id: odom
base_frame_id: base_footprint
base_frame_id: base_link
global_frame_id: map
resample_interval: 1
transform_tolerance: 0.2

View File

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

View File

@@ -25,7 +25,7 @@ wheel_radius_multiplier : 1.0 # default: 1.0
cmd_vel_timeout: 1.0
# frame_ids (same as real MiR platform)
base_frame_id: base_footprint # default: base_link base_footprint
base_frame_id: base_link # default: base_link base_link
odom_frame_id: odom # default: odom
# Velocity and acceleration limits

View File

@@ -1,48 +1,41 @@
yaw_goal_tolerance: 0.02
xy_goal_tolerance: 0.03
min_approach_linear_velocity: 0.05
position_planner_name: PNKXLocalPlanner
docking_planner_name: PNKXDockingLocalPlanner
go_straight_planner_name: PNKXGoStraightLocalPlanner
rotate_planner_name: PNKXRotateLocalPlanner
base_local_planner: LocalPlannerAdapter
LocalPlannerAdapter:
library_path: liblocal_planner_adapter
yaw_goal_tolerance: 0.017
xy_goal_tolerance: 0.03
min_approach_linear_velocity: 0.06 # The minimum velocity (m/s) threshold to apply when approaching the goal to ensure progress. Must be > 0.01. (default: 0.05)
PNKXLocalPlanner:
# Algorithm
# Thuật toán
library_path: libpnkx_local_planner
trajectory_generator_name: LimitedAccelGenerator
algorithm_nav_name: MKTAlgorithmDiffPredictiveTrajectory
algorithm_rotate_name: MKTAlgorithmDiffRotateToGoal
# Goal checking
# Bộ kiểm tra đã tới goal
goal_checker_name: GoalChecker
PNKXDockingLocalPlanner:
# Algorithm
# Thuật toán
library_path: libpnkx_local_planner
trajectory_generator_name: LimitedAccelGenerator
algorithm_nav_name: MKTAlgorithmDiffPredictiveTrajectory
algorithm_rotate_name: MKTAlgorithmDiffRotateToGoal
# Goal checking
# Bộ kiểm tra đã tới goal
goal_checker_name: GoalChecker
PNKXGoStraightLocalPlanner:
# Algorithm
# Thuật toán
library_path: libpnkx_local_planner
trajectory_generator_name: LimitedAccelGenerator
algorithm_nav_name: MKTAlgorithmDiffGoStraight
# Goal checking
# Bộ kiểm tra đã tới goal
goal_checker_name: GoalChecker
PNKXRotateLocalPlanner:
# Algorithm
# Thuật toán
library_path: libpnkx_local_planner
algorithm_rotate_name: MKTAlgorithmDiffRotateToGoal
trajectory_generator_name: LimitedAccelGenerator
# Goal checking
# Bộ kiểm tra đã tới goal
goal_checker_name: SimpleGoalChecker
stateful: true
@@ -51,23 +44,23 @@ LimitedAccelGenerator:
max_vel_x: 1.2
min_vel_x: -1.2
max_vel_y: 0.0 # diff drive robot
min_vel_y: 0.0 # diff drive robot
max_vel_y: 0.0 # robot vi sai: không có chuyển động ngang
min_vel_y: 0.0 # robot vi sai: không có chuyển động ngang
max_speed_xy: 2.0 # max_trans_vel: 0.8 # choose slightly less than the base's capability
min_speed_xy: 0.1 # min_trans_vel: 0.1 # this is the min trans velocity when there is negligible rotational velocity
max_speed_xy: 2.0 # [m/s] trần tốc độ tịnh tiến. Đặt thấp hơn khả năng thật của base một chút
min_speed_xy: 0.25 # [m/s] tốc độ tịnh tiến tối thiểu khi gần như không quay
max_vel_theta: 0.9 # max_rot_vel: 1.0 # choose slightly less than the base's capability
min_vel_theta: 0.04 # min_rot_vel: 0.1 default: 0.4 # this is the min angular velocity when there is negligible translational velocity
max_vel_theta: 0.4 # [rad/s] trần tốc độ quay. Đặt thấp hơn khả năng thật của base một chút
min_vel_theta: 0.05 # [rad/s] tốc độ quay tối thiểu khi gần như không tịnh tiến
acc_lim_x: 1.0
acc_lim_y: 0.0 # diff drive robot
acc_lim_theta: 0.9
decel_lim_x: -1.0
acc_lim_x: 3.0
acc_lim_y: 0.0 # robot vi sai: không có chuyển động ngang
acc_lim_theta: 1.5
decel_lim_x: -3.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
# Có cắt path thành từng chặng hay không
split_path: true
sim_time: 1.5
vx_samples: 15
@@ -76,125 +69,135 @@ LimitedAccelGenerator:
discretize_by_time: true
angular_granularity: 0.05
linear_granularity: 0.1
# sim_period
# sim_period: lấy theo chu kỳ điều khiển
include_last_point: true
MKTAlgorithmDiffPredictiveTrajectory:
library_path: libmkt_algorithm_diff
avoid_obstacles: false
xy_local_goal_tolerance: 0.01
xy_local_goal_tolerance: 0.05
angle_threshold: 0.6
index_samples: 60
follow_step_path: true
# Lookahead
use_velocity_scaled_lookahead_dist: true # Whether to use the velocity scaled lookahead distances or constant lookahead_distance. (default: false)
# only when false:
lookahead_dist: 0.5 # The lookahead distance (m) to use to find the lookahead point. (default: 0.6)
# only when true:
min_lookahead_dist: 1.0 # The minimum lookahead distance (m) threshold. (default: 0.3)
max_lookahead_dist: 2.0 # The maximum lookahead distance (m) threshold. (default: 0.9)
lookahead_time: 1.6 # The time (s) to project the velocity by, a.k.a. lookahead gain. (default: 1.5)
min_journey_squared: 0.3 # Minimum squared journey to consider for goal (default: 0.2)
max_journey_squared: 0.8 # Maximum squared journey to consider for goal (default: 0.2)
# Chỉnh bộ lọc Kalman (lọc lệnh v và w trước khi gửi xuống base).
# q_* = nhiễu quá trình, r_* = nhiễu đo. Tăng r_* -> lọc mạnh, lệnh mượt nhưng chậm đáp ứng
kf_q_v: 0.25
kf_q_w: 0.8
kf_r_v: 0.05
kf_r_w: 0.08
kf_p0: 0.5
kf_filter_angular: false
# Rotate to heading param - onle one of use_rotate_to_heading and allow_reversing can be set to true
use_rotate_to_heading: true # Whether to enable rotating to rough heading and goal orientation when using holonomic planners. Recommended on for all robot types that can rotate in place. (default: true)
# only when true:
rotate_to_heading_min_angle: 0.03 # The difference in the path orientation and the starting robot orientation (radians) to trigger a rotate in place. (default: 0.785)
# ----- Điểm nhìn trước (lookahead) -----
use_velocity_scaled_lookahead_dist: true # true = cự ly nhìn trước co giãn theo vận tốc; false = dùng cố định lookahead_dist. (mặc định: false)
# chỉ có tác dụng khi cờ trên = false:
lookahead_dist: 0.5 # [m] cự ly nhìn trước cố định để chọn điểm bám. (mặc định: 0.6)
# chỉ có tác dụng khi cờ trên = true:
min_lookahead_dist: 0.6 # [m] cận dưới của cự ly nhìn trước. Nhỏ quá thì robot lắc ở tốc độ thấp. (mặc định: 0.3)
max_lookahead_dist: 2.0 # [m] cận trên của cự ly nhìn trước. Lớn quá thì robot cắt cua. (mặc định: 0.9)
lookahead_time: 1.9 # [s] nhân với vận tốc hiện tại ra cự ly nhìn trước, tức hệ số lookahead. (mặc định: 1.5)
min_journey_squared: 0.2 # [m^2] quãng đường bình phương tối thiểu mới xét tới goal (mặc định: 0.2)
max_journey_squared: 0.5 # [m^2] quãng đường bình phương tối đa còn xét tới goal (mặc định: 0.2)
max_lateral_accel: 0.9 # [m/s^2] trần gia tốc ngang, dùng để tự giảm tốc khi vào cua
# ----- Quay tại chỗ về đúng hướng -----
# Chỉ được bật MỘT trong hai: use_rotate_to_heading hoặc allow_reversing
use_rotate_to_heading: true # Cho phép quay tại chỗ về hướng path và về hướng goal. Nên bật với mọi robot quay tại chỗ được. (mặc định: true)
# chỉ có tác dụng khi cờ trên = true:
rotate_to_heading_min_angle: 0.03 # [rad] lệch hướng giữa path và robot vượt ngưỡng này thì quay tại chỗ trước khi chạy. (mặc định: 0.785)
angular_decel_zone: 0.1
# stoped
rot_stopped_velocity: 0.1
trans_stopped_velocity: 0.1
# Ngưỡng coi robot là ĐÃ DỪNG
rot_stopped_velocity: 0.03
trans_stopped_velocity: 0.03
# Regulated linear velocity scaling
use_regulated_linear_velocity_scaling: false # Whether to use the regulated features for path curvature (e.g. slow on high curvature paths). (default: true)
# only when true:
regulated_linear_scaling_min_radius: 0.6 # The turning radius (m) for which the regulation features are triggered. Remember, sharper turns have smaller radii. (default: 0.9)
regulated_linear_scaling_min_speed: 0.15 # The minimum speed (m/s) for which any of the regulated heuristics can send, to ensure process is still achievable even in high cost spaces with high curvature. Must be > 0.1. (default: 0.25)
# Inflation cost scaling (Limit velocity by proximity to obstacles)
use_cost_regulated_linear_velocity_scaling: false # Whether to use the regulated features for proximity to obstacles (e.g. slow in close proximity to obstacles). (default: true)
inflation_cost_scaling_factor: 2.0 # (default: 3.0) # must be > 0
cost_scaling_dist: 0.2 # (default: 0.6)
cost_scaling_gain: 2.0 # (default: 1.0)
use_final_heading_alignment: true
final_heading_xy_tolerance: 0.1
final_heading_angle_tolerance: 0.05
final_heading_min_velocity: 0.05
final_heading_kp_angular: 1.2
final_heading_ki_angular: 0.002
final_heading_kd_angular: 0.12
MKTAlgorithmDiffGoStraight:
library_path: libmkt_algorithm_diff
avoid_obstacles: false
xy_local_goal_tolerance: 0.01
angle_threshold: 0.6
xy_local_goal_tolerance: 0.05
angle_threshold: 0.8
index_samples: 60
follow_step_path: true
# Lookahead
use_velocity_scaled_lookahead_dist: true # Whether to use the velocity scaled lookahead distances or constant lookahead_distance. (default: false)
# only when false:
lookahead_dist: 0.5 # The lookahead distance (m) to use to find the lookahead point. (default: 0.6)
# only when true:
min_lookahead_dist: 0.8 # The minimum lookahead distance (m) threshold. (default: 0.3)
max_lookahead_dist: 1.5 # The maximum lookahead distance (m) threshold. (default: 0.9)
lookahead_time: 2.5 # The time (s) to project the velocity by, a.k.a. lookahead gain. (default: 1.5)
min_journey_squared: 0.3 # Minimum squared journey to consider for goal (default: 0.2)
max_journey_squared: 0.6 # Minimum squared journey to consider for goal (default: 0.2)
# ----- Điểm nhìn trước (lookahead) -----
use_velocity_scaled_lookahead_dist: true # true = cự ly nhìn trước co giãn theo vận tốc; false = dùng cố định lookahead_dist. (mặc định: false)
# chỉ có tác dụng khi cờ trên = false:
lookahead_dist: 0.5 # [m] cự ly nhìn trước cố định để chọn điểm bám. (mặc định: 0.6)
# chỉ có tác dụng khi cờ trên = true:
min_lookahead_dist: 0.6 # [m] cận dưới của cự ly nhìn trước. Nhỏ quá thì robot lắc ở tốc độ thấp. (mặc định: 0.3)
max_lookahead_dist: 2.0 # [m] cận trên của cự ly nhìn trước. Lớn quá thì robot cắt cua. (mặc định: 0.9)
lookahead_time: 2.0 # [s] nhân với vận tốc hiện tại ra cự ly nhìn trước, tức hệ số lookahead. (mặc định: 1.5)
min_journey_squared: 1.0 # [m^2] quãng đường bình phương tối thiểu mới xét tới goal (mặc định: 0.2)
max_journey_squared: 1.0 # [m^2] quãng đường bình phương tối đa còn xét tới goal (mặc định: 0.2)
max_lateral_accel: 0.9 # [m/s^2] trần gia tốc ngang, dùng để tự giảm tốc khi vào cua
# Rotate to heading param - onle one of use_rotate_to_heading and allow_reversing can be set to true
use_rotate_to_heading: true # Whether to enable rotating to rough heading and goal orientation when using holonomic planners. Recommended on for all robot types that can rotate in place. (default: true)
# only when true:
rotate_to_heading_min_angle: 0.35 # The difference in the path orientation and the starting robot orientation (radians) to trigger a rotate in place. (default: 0.785)
# ----- Quay tại chỗ về đúng hướng -----
# Chỉ được bật MỘT trong hai: use_rotate_to_heading hoặc allow_reversing
use_rotate_to_heading: true # Cho phép quay tại chỗ về hướng path và về hướng goal. Nên bật với mọi robot quay tại chỗ được. (mặc định: true)
# chỉ có tác dụng khi cờ trên = true:
rotate_to_heading_min_angle: 0.03 # [rad] lệch hướng giữa path và robot vượt ngưỡng này thì quay tại chỗ trước khi chạy. (mặc định: 0.785)
angular_decel_zone: 0.1
# stoped
# Ngưỡng coi robot là ĐÃ DỪNG
rot_stopped_velocity: 0.03
trans_stopped_velocity: 0.06
trans_stopped_velocity: 0.03
use_regulated_linear_velocity_scaling: false
use_cost_regulated_linear_velocity_scaling: false
use_final_heading_alignment: true
final_heading_xy_tolerance: 0.1
final_heading_angle_tolerance: 0.05
final_heading_min_velocity: 0.05
final_heading_kp_angular: 1.5
final_heading_ki_angular: 0.2
final_heading_kd_angular: 0.05
MKTAlgorithmDiffRotateToGoal:
library_path: libmkt_algorithm_diff
avoid_obstacles: false
xy_local_goal_tolerance: 0.01
angle_threshold: 0.6
xy_local_goal_tolerance: 0.05
angle_threshold: 0.47
index_samples: 60
follow_step_path: true
# Lookahead
use_velocity_scaled_lookahead_dist: true # Whether to use the velocity scaled lookahead distances or constant lookahead_distance. (default: false)
# only when false:
lookahead_dist: 0.325 # The lookahead distance (m) to use to find the lookahead point. (default: 0.6)
# only when true:
min_lookahead_dist: 0.8 # The minimum lookahead distance (m) threshold. (default: 0.3)
max_lookahead_dist: 1.5 # The maximum lookahead distance (m) threshold. (default: 0.9)
lookahead_time: 1.8 # The time (s) to project the velocity by, a.k.a. lookahead gain. (default: 1.5)
min_journey_squared: 0.3 # Minimum squared journey to consider for goal (default: 0.2)
max_journey_squared: 0.6 # Maximum squared journey to consider for goal (default: 0.2)
# ----- Điểm nhìn trước (lookahead) -----
use_velocity_scaled_lookahead_dist: true # true = cự ly nhìn trước co giãn theo vận tốc; false = dùng cố định lookahead_dist. (mặc định: false)
# chỉ có tác dụng khi cờ trên = false:
lookahead_dist: 0.5 # [m] cự ly nhìn trước cố định để chọn điểm bám. (mặc định: 0.6)
# chỉ có tác dụng khi cờ trên = true:
min_lookahead_dist: 0.6 # [m] cận dưới của cự ly nhìn trước. Nhỏ quá thì robot lắc ở tốc độ thấp. (mặc định: 0.3)
max_lookahead_dist: 2.0 # [m] cận trên của cự ly nhìn trước. Lớn quá thì robot cắt cua. (mặc định: 0.9)
lookahead_time: 1.9 # [s] nhân với vận tốc hiện tại ra cự ly nhìn trước, tức hệ số lookahead. (mặc định: 1.5)
min_journey_squared: 0.2 # [m^2] quãng đường bình phương tối thiểu mới xét tới goal (mặc định: 0.2)
max_journey_squared: 0.8 # [m^2] quãng đường bình phương tối đa còn xét tới goal (mặc định: 0.2)
max_lateral_accel: 0.9 # [m/s^2] trần gia tốc ngang, dùng để tự giảm tốc khi vào cua
# Rotate to heading param - onle one of use_rotate_to_heading and allow_reversing can be set to true
use_rotate_to_heading: true # Whether to enable rotating to rough heading and goal orientation when using holonomic planners. Recommended on for all robot types that can rotate in place. (default: true)
# only when true:
rotate_to_heading_min_angle: 0.03 # The difference in the path orientation and the starting robot orientation (radians) to trigger a rotate in place. (default: 0.785)
angular_decel_zone: 0.1
# stoped
# ----- Quay tại chỗ về đúng hướng -----
# Chỉ được bật MỘT trong hai: use_rotate_to_heading hoặc allow_reversing
use_rotate_to_heading: true # Cho phép quay tại chỗ về hướng path và về hướng goal. Nên bật với mọi robot quay tại chỗ được. (mặc định: true)
# chỉ có tác dụng khi cờ trên = true:
rotate_to_heading_min_angle: 0.03 # [rad] lệch hướng giữa path và robot vượt ngưỡng này thì quay tại chỗ trước khi chạy. (mặc định: 0.785)
angular_decel_zone: 0.1
# Ngưỡng coi robot là ĐÃ DỪNG
rot_stopped_velocity: 0.03
trans_stopped_velocity: 0.06
trans_stopped_velocity: 0.03
use_final_heading_alignment: true
final_heading_xy_tolerance: 0.1
final_heading_angle_tolerance: 0.05
final_heading_min_velocity: 0.05
final_heading_kp_angular: 2.0
near_goal_heading_kp: 1.5
near_goal_heading_ki: 0.0
near_goal_heading_kd: 0.0
# Regulated linear velocity scaling
use_regulated_linear_velocity_scaling: false # Whether to use the regulated features for path curvature (e.g. slow on high curvature paths). (default: true)
# only when true:
regulated_linear_scaling_min_radius: 0.6 # The turning radius (m) for which the regulation features are triggered. Remember, sharper turns have smaller radii. (default: 0.9)
regulated_linear_scaling_min_speed: 0.05 # The minimum speed (m/s) for which any of the regulated heuristics can send, to ensure process is still achievable even in high cost spaces with high curvature. Must be > 0.1. (default: 0.25)
# Inflation cost scaling (Limit velocity by proximity to obstacles)
use_cost_regulated_linear_velocity_scaling: false # Whether to use the regulated features for proximity to obstacles (e.g. slow in close proximity to obstacles). (default: true)
inflation_cost_scaling_factor: 2.0 # (default: 3.0) # must be > 0
cost_scaling_dist: 0.2 # (default: 0.6)
cost_scaling_gain: 2.0 # (default: 1.0)
GoalChecker:
library_path: libmkt_plugins_goal_checker
SimpleGoalChecker:
library_path: libmkt_plugins_simple_goal_checker
library_path: libmkt_plugins_goal_checker

View File

@@ -0,0 +1,452 @@
PriestLocalPlanner:
library_path: libpriest_local_planner
# ================= Tầm nhìn / bộ tối ưu =================
t_fin: 7.0 # [s] tầm nhìn dự báo, robot lập kế hoạch trước bao lâu
t_fin_min: 0.0 # [s] > 0 = BẬT co horizon theo path còn lại: gần cuối tuyến,
# t_fin hiệu dụng = arc_còn_lại / reference_velocity (không nhỏ hơn sàn
# này) — quỹ đạo phủ path còn lại Ở ĐÚNG tốc độ hành trình, hết bò
# (v ~ remaining/t_fin) và hết mốc 25/50/75 chồng dồn, trong MỘT bộ điều
# khiển, không chuyển chế độ. Chính sàn này định hình cú phanh cuối:
# v ~ remaining/t_fin_min trên đoạn reference_velocity x t_fin_min chót
# (1.0 -> phanh trên 0.4 m cuối). Nhiễu ngang CEM tự co theo tỉ lệ
# horizon. 0 = tắt (horizon cố định như cũ; goal_approach_distance cũ
# lúc đó mới có tác dụng)
num_steps: 30 # số điểm mẫu trên mỗi quỹ đạo trong tầm nhìn đó
num_batch: 60 # số quỹ đạo sinh ra mỗi vòng lặp CEM. Tăng = tìm kỹ hơn, tốn CPU hơn
initial_up_sampling: 5 # hệ số sinh dư ứng viên ở vòng đầu trước khi lọc
ellite_num: 40 # số quỹ đạo "tinh hoa" giữ lại, xếp hạng theo sai số chiếu
num_warm: 20 # số quỹ đạo mang từ chu kỳ trước sang để khởi động nóng
max_proj_iter: 8 # số vòng lặp chiếu luân phiên (alternating projection)
proj_early_exit_tolerance: 0.0 # thoát sớm vòng chiếu khi tổng residual hết cải thiện quá tỉ lệ
# này (0 = tắt, chạy đủ max_proj_iter). Đường thoáng hội tụ sau 3-4
# vòng — phần còn lại tính lại y nguyên kết quả. Sát vật cản residual
# còn động nên vẫn chạy đủ ngân sách; log proj_it= cho thấy số vòng thật
proj_early_exit_residual: 0.0 # [m] vế TUYỆT ĐỐI của early-exit: residual của ELITE TỆ NHẤT (hạng
# ellite_num) dưới ngưỡng này là thoát — mọi thứ CEM sẽ dùng đã khả thi.
# Thiếu vế này tiêu chí tương đối chạy NGƯỢC: thoáng không bao giờ thoát
# (residual bé nhưng còn giảm >1%/vòng), sát vật cản lại thoát sớm khi
# residual LỚN nhưng chững. 0 = tắt vế
max_cem_iter: 4 # số vòng lặp CEM mỗi chu kỳ điều khiển
optimizer_threads: 4 # số thread giới hạn. Đừng lấy hết số core — overhead nuốt hết lợi ích
solve_time_warn_ms: 30.0 # [ms] cảnh báo khi giải lâu hơn ngưỡng này, chừa biên trong chu kỳ 30 Hz
lateral_std: 0.8 # [m] độ lệch chuẩn khi nhiễu loạn waypoint theo phương ngang.
# Lớn = khám phá rộng, dễ tìm đường vòng; nhỏ = bám sát path toàn cục
# ---- E1a/E2: ổn định nghiệm ở đoạn THOÁNG (chống lắc không do vật cản)
lateral_std_clear_scale: 1.0 # nhân vào lateral_std sau khi path giải SẠCH liên tiếp
# clear_streak_cycles chu kỳ (residual < clear_residual). Trên đoạn
# trống KHÔNG có ràng buộc nào ghim nghiệm, batch vẽ lại mỗi chu kỳ
# nên mẫu thắng cứ nhảy -> độ cong đầu quỹ đạo đổi -> omega ngoáy
# (đo 28/8: 5 m cuối thoáng, sai số hướng < 0.08 rad mà omega nhảy
# -0.19/+0.34/-0.50 trong vài giây). Residual vừa tăng là biên độ
# đầy đủ trở lại NGAY, né vật cản không mất khả năng khám phá.
# 1.0 = tắt
clear_residual: 0.05 # [m] residual dưới mức này coi là "đường sạch"
clear_streak_cycles: 3 # số chu kỳ sạch liên tiếp trước khi co biên độ
horizon_hysteresis_buckets: 0.0 # E2: target horizon mới phải lệch quá ngần này BUCKET
# (1 bucket = 0.25 s) mới được nhận. Mỗi lần nhận là rebuild ma trận
# Bernstein/KKT + lật terminal_stop_ = đổi hình cả batch; nhảy qua
# lại giữa hai bucket kề nhau tệ hơn chạy lệch một bucket. 0 = tắt
horizon_restore_delay_cycles: 0 # E2: số chu kỳ "không đo được arc còn lại" chịu đựng
# trước khi horizon bung về full. Arc chỉ đo được khi đuôi plan đã
# cắt còn nằm gần goal; hụt MỘT chu kỳ mà bung full là đổi hình cả
# batch (đo 28/8 gần goal: tfin 3.75 -> 6.00 -> 3.75). Plan mới thật
# sự dài thì khoảng hụt kéo dài qua ngưỡng này và horizon vẫn bung.
# 0 = bung ngay (hành vi cũ)
# --- Solver tu khai bat kha thi (2026-09-04) ---
# Cong va cham cua planner da chuyen sang path_monitor/collision cua move_base2. Planner chi con
# giu best_res_norm — chuan vi pham rang buoc cua ca batch (bam sach 0-0.3, ne 1-2, ngo cut 4-7).
# Treo du lau thi tra "khong co lenh hop le" de move_base2 replan khi con cho.
# TAT tren robot that cho toi khi chay thu — sim dang dung 3.0 / 10.
infeasible_residual: 0.0 # [-] res >= muc nay coi la bat kha thi. 0 = TAT.
infeasible_streak_cycles: 10 # [chu ky] treo lien tuc ngan nay moi khai.
infeasible_cooldown_cycles: 60 # [chu ky] sau khi khai va da nhan plan moi, im chung nay (3 s @20 Hz)
# de plan moi co co hoi that; chi khai khi start_violations > 0.
# ================= Giới hạn robot (dẫn động vi sai) =================
max_velocity: 0.5 # [m/s] trần vận tốc tiến
max_angular_velocity: 0.4 # [rad/s] đồng thời được ép bên trong bộ tối ưu dưới dạng
# chặn gia tốc ngang |a_n| <= max_angular_velocity * v
max_acceleration: 0.5 # [m/s^2] dùng trong phép chiếu quỹ đạo
# ---- Bao êm ái của LỆNH xuất ra (S1/P2). Bộ tối ưu vẫn dùng max_acceleration
# để tìm quỹ đạo; các khoá dưới chỉ nắn LỆNH giao cho đế. Robot chở đồ ăn /
# chở người cần a <= 0.3 m/s^2 và jerk <= 0.5 m/s^3. Đặt 0 = tắt riêng khoá đó
# (hành vi cũ: chỉ chặn chiều TĂNG, chiều giảm tức thì = 0.5 -> 0 trong một
# chu kỳ = -10 m/s^2, đo 28/8).
accel_comfort: 0.0 # [m/s^2] trần TĂNG tốc của lệnh
decel_comfort: 0.0 # [m/s^2] trần GIẢM tốc thường
decel_emergency: 1.0 # [m/s^2] chỉ dùng khi gate va chạm / hold đòi dừng —
# an toàn giữ toàn quyền phanh
jerk_limit: 0.0 # [m/s^3] trần biến thiên gia tốc; 0 = tắt. Không có nó thì
# ramp vẫn vào/ra bằng bậc gia tốc, khay đồ ăn cảm nhận rõ
max_angular_accel: 0.0 # [rad/s^2] trần |d omega| của lệnh; 0 = tắt (hành vi cũ:
# omega nhảy 0 -> ±0.5 trong MỘT chu kỳ, chính là cú giật
# lúc chốt XY rồi bật sang pha xoay)
angular_jerk_limit: 0.0 # [rad/s^3] trần biến thiên gia tốc góc; 0 = tắt
slew_reseed_gap: 0.0 # [s] hai lenh phat ra cach nhau qua chung nay (hoac vua nhan plan moi) thi
# bo truot toc do khoi dong lai tu van toc DO DUOC cua base, khong mang theo
# lenh cu (do 6/9 sim: sau recovery robot nhich 0.07-0.33 m tu toc do ma
# 0.20-0.43 m/s roi moi xoay). TAT tren robot that cho toi khi chay thu —
# sim dang dung 0.3. 0 = TAT.
reference_velocity: 0.4 # [m/s] tốc độ hành trình mong muốn dọc path
v_eps: 0.05 # [m/s] chậm hơn ngưỡng này thì bỏ qua phần chặn/phạt độ cong,
# tránh chia cho số gần 0 khi robot gần đứng yên
v_min_seed: 0.05 # [m/s] vận tốc mồi theo hướng yaw khi robot đang đứng yên,
# để bộ tối ưu có điểm xuất phát khác 0
# Đổi quỹ đạo -> lệnh vi sai (v, omega), có feedforward theo độ cong:
# omega = clamp(omega_traj, +-max_angular_velocity) - heading_gain * sai_số_hướng
heading_gain: 1.5 # [1/s] hệ số phản hồi trên sai số hướng.
# Tăng = bẻ về path nhanh hơn nhưng dễ dao động
heading_error_stop: 1.2 # [rad] lệch hướng lớn hơn ngưỡng này thì quay tại chỗ (v = 0)
min_in_place_yawrate: 0.2 # [rad/s] tốc độ quay tối thiểu khi quay tại chỗ, tránh quay quá chậm
in_place_yawrate_max: 0.0 # [rad/s] trần tốc độ quay khi XOAY TẠI CHỖ (rot2path, rot2goal,
# nhánh inplace). max_angular_velocity là giới hạn GHÉP ĐÔI — trong bộ
# tối ưu nó chặn |a_n| <= omega*v, tức thuộc về robot ĐANG CHẠY. Xoay
# tại chỗ không có ràng buộc ghép đó, mà dùng chung trần lái khiến cú
# quay 172 deg mất 6 GIÂY đứng im trước khi robot lăn bánh (đo 29/8,
# mission đầu). 0 = dùng max_angular_velocity.
# ĐỂ 0 với đế không xoay tại chỗ được (một bánh lái).
rotate_to_path_enabled: false # bật = XOAY TẠI CHỖ về hướng path, CHỈ MỘT LẦN Ở ĐẦU PLAN (như
# stanley/hybrid; vào khi lệch > heading_error_stop, ra khi < nửa
# ngưỡng). Không có nó thì mission quay đầu bị vẽ thành cung rẽ tiến
# bán kính v/max_angular_velocity = 1 m quét qua vật cản. GIỮA mission
# không bao giờ pivot lại: lúc né, heading lệch tangent là CÓ CHỦ ĐÍCH
# (tangent chỉ thẳng vào vật cản đang né) — pivot giữa bãi từng quét
# góc thân vào tiếp xúc (sim 19/8, sv=28). Pivot cũng bị bỏ qua nếu
# probe footprint chạm costmap. Robot không xoay tại chỗ được phải TẮT
rotate_settle_yawrate: 0.0 # [rad/s] > 0 = ramp hạ cánh cho CẢ hai pha xoay tại chỗ (xoay về yaw
# goal sau latch + rotate-to-path đầu plan): trong vùng settle
# (|sai số| <= 0.3 rad) sàn tốc độ quay hạ từ min_in_place_yawrate
# xuống giá trị này — tốc độ đổ dốc theo sai số như deadbandClip
# [0.05, 0.3] của stanley Phase B, thay vì giữ 0.2 rad/s tới tận nơi
# rồi dừng phắt (bước 0.0067 rad/chu kỳ qua dải đích 0.02 rad — gắt,
# dễ lắc mép). Còn xa vẫn dùng sàn min_in_place_yawrate để thắng ma
# sát. 0 = tắt (một sàn duy nhất như cũ)
# ================= Goal / plan =================
xy_goal_tolerance: 0.10 # [m] sai số vị trí chấp nhận là đã tới goal
yaw_goal_tolerance: 0.10 # [rad] sai số góc chấp nhận là đã tới goal
xy_latch_release_factor: 0.0 # chốt XY: vào trong xy_goal_tolerance là coi phần vị trí XONG, chỉ
# còn XOAY TẠI CHỖ về yaw goal. Không chốt thì hai dung sai phải trùng
# cùng một chu kỳ — robot lượn quanh goal chờ trùng khoảnh khắc (đo
# sim 18/8: 22-38 s mới xong hoặc không bao giờ). Nhả chốt khi bị đẩy
# ra quá xy_goal_tolerance x hệ số này (hysteresis). <= 1.0 = tắt
# (hành vi cũ). Robot KHÔNG xoay tại chỗ được (một bánh lái) thì phải
# tắt và để profile rotate lo phần yaw
xy_latch_release_speed: 0.0 # [m/s] chi NHA chot XY khi robot da thuc su DUNG ma van o ngoai
# vong nha. Nha chot nghia la "co thu gi day robot khoi goal" —
# troi theo quan tinh KHONG phai thu do. Do 29/8 tren sim: robot
# vao vung tolerance o 0.34 m/s, chot dong ra lenh v=0 nhung banh
# con 0.32 m/s nen chu ky sau da o 0.102 m, vuot vong nha 0.10 m;
# chot mo lai, quay ve bam vi tri, va vi base chi tien (khong lui)
# robot phai luon mot vong lon moi quay mat ve goal — loay hoay
# 34 giay. TAT tren robot that cho toi khi chay thu (0 = hanh vi cu:
# nha chi theo khoang cach). Sim dang dung 0.05.
goal_brake_decel: 0.0 # [m/s^2] tran toc do theo quang duong CON LAI toi goal:
# v <= sqrt(2 * a * (dist - xy_goal_tolerance))
# Ramp cuoi cua solver tinh tren horizon cua no, khong tinh theo
# goal, nen no tha robot toi goal o 0.34 m/s khi chi con 0.06 m.
# TAT tren robot that cho toi khi chay thu — sim dang dung 0.35,
# o muc do tran chi co tac dung trong ~0.38 m cuoi.
# --- Chot khi robot bat dau DI RA XA goal (muon tu hybrid_local_planner) ---
# Trong ban kinh theo doi, ghi lai khoang cach GAN NHAT tung dat toi goal. Khoang cach bat dau
# tang tro lai nghia la giai doan bam vi tri da qua diem tot nhat cua no — chot XY ngay va
# chuyen sang xoay ve yaw. Co che nay bat duoc thu ma phep thu "goal nam sau lung" ve mat cau
# truc khong bat noi: robot luon sat qua goal o 0.04 m trong khi mui van con huong ve no.
# TAT tren robot that cho toi khi chay thu — sim dang dung 0.5 / 0.03.
goal_regression_watch_dist: 0.0 # [m] khoang cach toi goal ma duoi do bat dau theo doi. 0 = TAT.
goal_regression_margin: 0.03 # [m] khoang cach phai tang qua muc nay so voi diem gan nhat
# thi moi coi la dang di ra xa (hap thu nhieu dinh vi).
goal_approach_distance: 0.0 # [m] vùng tiếp cận goal. Hành lang SẠCH vật cản: bỏ PRIEST, chạy thẳng
# về goal pose với profile giảm tốc vật lý sqrt(2*a_max*dist) — hết bò
# (terminal ghim trải arc còn lại lên trọn t_fin) lẫn lắc đầu (CEM tách
# hai họ cắt-cua/bám-cua trên đoạn cong). CÓ vật cản trong hành lang:
# vẫn PRIEST với reference_velocity co theo quãng còn lại. 0 = tắt
omega_ff_min_speed: 0.0 # [m/s] dưới tốc độ này feedforward độ cong mờ dần tuyến tính.
# omega_ff = cross/v^2 — bò chậm trên đoạn CONG là nó kịch trần và lật
# dấu theo nhiễu (lắc đầu; đoạn thẳng tử số ~0 nên không lắc). Feedback
# heading vẫn lái. 0 = tắt (feedforward đầy đủ mọi tốc độ như cũ)
omega_ff_filter_tau: 0.0 # [s] E1b — hằng số thời gian lọc thông thấp cho FEEDFORWARD độ cong,
# CHỈ áp khi lời giải sạch (residual < clear_residual). Trên đoạn
# thẳng trống độ cong THẬT bằng 0, nhưng CEM vẽ lại quỹ đạo mỗi chu
# kỳ và độ cong ngẫu nhiên nhỏ của nó, chia cho v^2, làm omega ngoáy
# ±0.4 rad/s dù sai số hướng chỉ 0.03 rad (đo 29/8: ff +0.42/-0.18/
# -0.06/-0.15/+0.16 liên tiếp, omega bám theo gần như y hệt).
# Vật cản vừa ràng buộc lời giải là BỎ QUA bộ lọc ngay — né vật cản
# giữ nguyên toàn quyền phản ứng tức thì. 0 = tắt
# --- Tran feedforward theo do cong DUONG THAM CHIEU ---
# Loc thong thap o tren chi dap duoc dao dong NHANH HON hang so thoi gian cua no. Dao dong do
# duoc tren sim (29/8) lai cham hon the: chu ky ~0.8 s so voi tau 0.35 s, nen no lot qua — tren
# doan thang sai so huong chi 0.01 rad ma ff van lat dau +-0.47 rad/s, robot lac du bam path sat.
# Goc re: CEM ve lai quy dao Bernstein moi chu ky, do cong ngau nhien nho cua no chia cho v^2
# thanh so lon. Cach xu ly: chan ff bang chinh do cong ma DUONG THAM CHIEU yeu cau —
# |ff| <= kappa_path * v * margin + floor
# Duong thang thi kappa_path = 0, tran tut ve floor, phan bam con lai do phan hoi huong lo.
# Tran duoc NOI DAN khi residual tang: loi giai bi vat can rang buoc thi cong khac duong tham
# chieu la co chu dich, phai giu nguyen tham quyen ne.
# TAT tren robot that cho toi khi chay thu — bat bang cach dat margin > 0 (sim dang dung 1.5).
omega_ff_curvature_margin: 0.0 # [-] he so noi so voi do cong duong tham chieu. 0 = TAT.
omega_ff_curvature_floor: 0.12 # [rad/s] san cua tran, de path thang tuyet doi van con quyen
# lai nhe giu line. Thap qua = troi khoi duong thang;
# cao qua = lac quay lai.
omega_ff_curvature_window: 1.5 # [m] quang duong phia truoc dung de do do cong tham chieu.
zeta_from_start_tangent: false # [bool] ĐỂ NGUYÊN false. Bật = đo sai số hướng so với tangent quỹ
# đạo ngay tại robot thay vì tangent trung bình cửa sổ lệnh. Thử ở
# sim 7/9 và HỎNG: ràng buộc start ghim vận tốc đầu quỹ đạo vào yaw
# robot nên zeta = 0 theo định nghĩa (98 % mẫu đang chạy), feedback
# heading chết, cross-track error 2.00 m, robot quệt vật cản rồi kẹt.
# Khoá giữ lại để không ai thử lại; không có kịch bản nào nên bật.
max_global_plan_lookahead_dist: 3.0 # [m] chỉ lấy phần path toàn cục trong tầm này để bám
hold_timeout: 10.0 # [s] đứng chờ (pivot bị chặn ở goal / fallback bị chặn) quá chừng
# này thì trả fail cho move_base2 leo thang (recovery/abort báo fleet).
# Trước đây chờ VÔ HẠN: obs tĩnh đè goal + planner_frequency 0 = treo
# câm 30+ s không ai biết (đo 19/8 20h35). 0 = chờ vô hạn như cũ
goal_blocked_check_radius: 0.0 # [m] MẶC ĐỊNH TẮT trên robot — bật sau khi chạy thử. Trong bán kính này quanh goal thì dò ĐĨA nửa thân robot quanh goal trên costmap
# mỗi cycle: cell nào cost >= 253 (vỏ obs đè goal — lidar chỉ mark vỏ, cell tâm thân obs vẫn free/unknown) thì DỪNG-CHỜ
# kiểu hybrid thay vì bám nghiệm solver lượn quanh obs (đo 19/8: 2 vòng
# orbit 0.8-1.9 m). Obs dọn đi thì tự chạy tiếp; không thì hold_timeout
# leo thang. 0 = tắt kiểm tra
# ================= Vật cản (lấy từ local costmap) =================
num_obs: 40 # số vật cản đưa vào hàm chi phí CEM
num_obs_proj: 30 # số vật cản gần nhất đưa vào phép chiếu
obstacle_range: 2.5 # [m] bán kính quét costmap quanh robot
robot_radius: 0.50 # [m] bán kính robot dùng cho phép kiểm va chạm
obstacle_point_radius: 0.08 # [m] bán kính quy ước cho mỗi điểm vật cản
footprint_padding: 0.05 # [m] nới footprint thêm để có biên an toàn
obstacle_cost_threshold: 150 # ô costmap có cost >= ngưỡng này mới coi là vật cản
obstacle_cell_step: 2 # bước nhảy khi quét ô costmap. Lớn = nhanh hơn, bỏ sót nhiều hơn
max_obstacle_points: 150 # trần số điểm vật cản, chặn chi phí tính toán khi môi trường dày
# Footprint phủ bằng nhiều circle dọc thân robot thay cho một disc tại base_link.
# Robot 1.166x0.96 m: disc robot_radius 0.50 hụt mũi/đuôi ~0.13 m (bán kính ngoại tiếp 0.755) —
# lách là quệt góc; phình disc che đủ thì khe ~1.8 m mới qua. 3 circle r=0.52 tâm {-0.39, 0, +0.39}
# che kín chữ nhật mà khe ~1.3 m vẫn lách được. Mỗi cặp (vật cản, circle) là một virtual obstacle
# dịch theo heading quỹ đạo; nhờ sparse gating chi phí chỉ nhân vào cặp va chạm.
footprint_circle_count: 1 # số circle. 1 = disc cũ tại base_link (dùng robot_radius, bỏ qua
# hai khoá dưới)
# ĐỂ 1 (tắt) ở bản này cho tới khi chạy thử trên robot
footprint_circle_spacing: 0.39 # [m] khoảng cách tâm hai circle kề nhau, xếp đối xứng quanh base_link
footprint_circle_radius: 0.52 # [m] bán kính mỗi circle khi count > 1; cộng obstacle_point_radius
# + footprint_padding thành ellipse va chạm mỗi circle
start_violation_ramp_time: 0.0 # [s] > 0 = BẬT ramp cho vật cản mà robot ĐANG vi phạm ellipse ngay
# tại điểm xuất phát (đỗ cách tường 0.5-0.6 m là dính, vì ellipse
# mô hình 0.65 m phóng đại hơn thân thật): không ramp thì phép chiếu
# VÔ NGHIỆM từ sample 0 — res có sàn dương vĩnh viễn, optimizer phát
# lệnh "ít tệ nhất" và robot trườn vào tiếp xúc thật (đo sim 19/8:
# res treo 4-7 suốt 10 s dù thấy đủ 80/88 điểm). Bật: ellipse của
# riêng vật cản đó co về sát khoảng cách hiện tại rồi nở lại đầy đủ
# trong chừng này giây đầu horizon — ràng buộc thành "không chui sâu
# hơn, thoát ra dần". Chỉ áp cho phép chiếu; cost giữ ellipse đầy đủ
# nên vẫn đẩy robot ra xa. 0 = tắt
terminal_slide_max_dist: 0.0 # [m] L1 — cho ĐIỂM GHIM CUỐI của quỹ đạo TRƯỢT DỌC PATH tối đa
# ngần này để thoát khỏi vật cản mà nó rơi vào. Điểm cuối là ràng
# buộc ĐẲNG THỨC: rơi vào vật cản là CẢ BATCH bất khả thi ngay từ
# đầu, phép chiếu không bao giờ về residual 0, solver chỉ còn phát
# lệnh "ít tệ nhất" -> robot LẾT dù phía trước trống (đo 28/8:
# res 4.5-5.1, v 0.05 m/s trong khi front_cone = 2.6 m).
# Trượt TIẾN trước (giữ nguyên quãng đường nên giữ được tốc độ),
# không có chỗ sạch thì mới trượt LÙI; trong tầm này không tìm được
# điểm sạch thì giữ nguyên ghim cũ = hành vi cũ y nguyên.
# Dùng ĐÚNG ellipse mà phép chiếu dùng, nên "bị chặn" ở đây nghĩa
# là "ràng buộc solver không thể thoả". 0 = tắt.
# Dòng SOLVE in tslide=<khoảng cách đã trượt, + tiến / - lùi>
# Chiết khấu ảnh hưởng vật cản theo THỜI GIAN dọc horizon. Cụm vật cản chỉ chạm ĐUÔI quỹ đạo
# (gần góc cua mà path sẽ rẽ trước khi tới nơi) vẫn bẻ cong TOÀN BỘ quỹ đạo ra ngoài — robot
# lượn rộng ngay từ đầu để né thứ nó không bao giờ đi vào. Bật: ELLIPSE ràng buộc của từng
# sample CO theo w(t): w = 1 tới giây _start, giảm tuyến tính về _min tại cuối horizon (co
# ellipse chứ không giảm bước đẩy — giảm bước thì ADMM lặp vẫn đẩy ra biên đầy đủ).
# Cost/clearance CEM đo q trên cùng ellipse co; vật cản xa tự cứng lại khi robot tiến tới.
obstacle_time_discount_start: 0.0 # [s] từ giây này trên horizon ellipse bắt đầu co. ĐỂ 0 (TẮT)
# ở bản này cho tới khi chạy thử trên robot; cây sim thử 2.0
obstacle_time_discount_min: 1.0 # tỉ lệ ellipse còn lại tại cuối horizon (0..1). 1.0 = tắt;
# cây sim thử 0.2. Đừng đặt dưới ~0.1 — đuôi mù hẳn vật cản
# Chọn điểm theo HÀNH LANG dọc plan thay vì gần robot nhất: lọc điểm trong bán kính
# corridor_radius quanh polyline plan (đã cắt lookahead) + vị trí robot, và chia đều trần
# num_obs dọc hành lang (round-robin) — hết cảnh một bức tường sát robot nuốt trọn budget
# trong khi vật cản 2 m phía trước trên tuyến thì vô hình.
obstacle_corridor_enabled: false # ĐỂ TẮT ở bản này cho tới khi chạy thử trên robot (hành vi cũ: gần robot nhất)
corridor_radius: 1.2 # [m] nửa bề rộng hành lang chọn điểm. Sàn tự động = robot_radius +
# obstacle_point_radius + footprint_padding; rộng hơn = nhìn xa hai
# bên hơn nhưng tốn suất điểm hơn
corridor_sample_spacing: 0.3 # [m] bước lấy mẫu plan làm xương hành lang. Nhỏ = bucket mịn,
# chia suất đều hơn dọc tuyến; không cần nhỏ hơn nhiều so với
# resolution costmap (0.05)
# ================= Hình học thân cho các probe còn lại =================
# Cổng va chạm của planner này (dò quỹ đạo / dò cung lệnh / chốt thân-trong-vành) đã CHUYỂN sang
# path_monitor/collision của move_base2 (2026-09-03): LETHAL + chu vi footprint đệm, planner-agnostic.
# Planner không còn tự dừng vì va chạm. Bốn khoá dưới đây chỉ còn là HÌNH HỌC THÂN cho ba phép dò
# mềm còn lại: head_slowdown, quét pivot trước khi xoay tại chỗ, đĩa kiểm goal bị đè. Giữ tên khoá
# để không đổi schema.
collision_check_front_offset: 0.583 # [m] tầm mũi robot tính từ base_link (theo footprint trong
# launch đang chạy — đo lại khi đổi robot)
collision_check_rear_offset: 0.583 # [m] tầm đuôi robot tính từ base_link
collision_check_side_offset: 0.0 # [m] thêm 2 probe HÔNG trái/phải cách trục dọc chừng này (nửa bề
# rộng robot 0.48) — 3 probe trục dọc chỉ che chiều dài, cú quệt
# hông đầu mission 4 (sim 18/8) lách đúng chỗ này. 0 = 3 probe cũ
collision_check_cost_threshold: 253 # cost costmap >= ngưỡng này coi là chạm (253 =
# INSCRIBED_INFLATED_OBSTACLE, 254 = LETHAL; ô NO_INFORMATION
# được bỏ qua). Chỉ còn phục vụ head_slowdown/pivot/goal.
# Head slowdown — bản MỀM của gate: GIẢM TỐC khi đầu quỹ đạo đi vào vùng costmap XẤU HƠN
# chỗ thân robot đang đứng (5 probe chung với gate, đo thêm tại pose hiện tại làm baseline —
# so TƯƠNG ĐỐI, không thì hành lang hẹp phanh đáy suốt vì probe hông nằm sẵn trong vành
# inscribed). Mức phanh nhân theo ĐỘ GẦN thời gian của ô xấu — ô ở mép cửa sổ chỉ rà nhẹ,
# sát mũi mới phanh sâu. Phanh ngay, nhả có debounce. Scale cả v lẫn omega.
head_slowdown_time: 0.0 # [s] cửa sổ đầu quỹ đạo được probe. ĐỂ 0 (TẮT) ở bản này cho
# tới khi chạy thử trên robot; cây sim đang thử 1.5
head_slowdown_cost_free: 128 # sàn dưới của baseline: cost <= max(baseline, ngưỡng này) chạy
# đủ tốc; từ đó tới 253 giảm tuyến tính
head_slowdown_min_scale: 0.2 # sàn tỉ lệ tốc độ khi có ô LETHAL (254) trước mũi. Đừng đặt 0
head_slowdown_inscribed_scale: 1.0 # tỉ lệ khi ô xấu nhất chỉ là INSCRIBED (253) — probe ở mép
# thân nên 253 chỉ là "tường gần", 254 mới là chạm. 1.0 = coi 253
# như tự do (mặc định); cây sim đang thử 0.7
head_slowdown_release_cycles: 10 # số chu kỳ SẠCH liên tiếp mới nhả phanh; trong lúc chờ giữ
# nguyên mức phanh cuối. 0 = nhả tức thì
head_slowdown_scale_slew: 0.0 # S2: trần TĂNG của hệ số giảm tốc mỗi chu kỳ (0 = tắt,
# nhảy bậc như cũ). Phanh vẫn ăn ngay, chỉ NHẢ là ramp — ô
# costmap nhấp nháy hết băm lệnh 0.94/0.80/0.75 trong một
# giây. 0.02 ở 20 Hz = nhả hết trong ~1.5 s
head_slowdown_release_cost: 128 # S2+: cost tuyệt đối mà đầu quỹ đạo phải TỤT DƯỚI mức này
# thì phanh mới được nhả. Hệ số phanh vốn so đầu quỹ đạo với
# baseline PEAK-HELD — baseline này nhấp nháy theo ô costmap
# (253 chu kỳ này, 60 chu kỳ sau), dùng nó làm điều kiện nhả khiến
# phanh bật/tắt vài giây một lần, mà hệ số lại nhân THẲNG vào v nên
# mỗi lần nhả là robot vọt (đo 29/8 qua khe hẹp: hs
# 1.00/0.89/0.80/0.75/1.00 kéo v 0.32/0.17/0.37/0.34/0.50).
# Điều kiện BẬT giữ nguyên — đây chỉ là nửa trên của vòng trễ.
# ================= Trọng số hàm chi phí =================
# Chỉnh các trọng số này là chỉnh "tính cách" của planner. Tăng một cái tức là
# giảm tương đối tất cả những cái còn lại.
weight_smoothness: 0.1 # phạt quỹ đạo gãy khúc
weight_track: 0.2 # phạt lệch khỏi path toàn cục
weight_obs: 1.2 # phạt tiến gần vật cản
weight_clearance: 3.0 # phần thưởng giữ khoảng hở, giá trị trong (0,1]: bằng 1 ngay tại
# tâm vật cản, 0.5 tại biên va chạm, 0 khi ngoài tầm
weight_angular: 0.5 # phạt kiểu bản lề khi |omega| vượt max_angular_velocity
weight_velocity_deficit: 0.0 # phạt hụt tốc ở 1/4 ĐẦU quỹ đạo (nghiệm chậm-đầu thắng ranking gần
# bãi vật cản làm robot bò dù không gì phanh; mốc so đã neo theo
# re-time nên không phá cú phanh cuối). ĐỂ 0 (TẮT) ở bản này cho tới
# khi chạy thử trên robot; cây sim đang thử 2.0
cem_lamda: 0.9 # nhiệt độ CEM. Thấp = chỉ tin nhóm tinh hoa, hội tụ nhanh nhưng dễ kẹt
cem_alpha: 0.7 # hệ số pha trộn mean/cov giữa hai vòng CEM. Cao = đổi chậm, ổn định hơn
# Hysteresis chọn bên khi né vật cản nằm giữa tuyến. Không neo bên thì CEM có hai nghiệm
# trái/phải cost gần bằng nhau: mean phân bố "cưỡi" lên vật cản (trung bình của vòng trái và
# vòng phải là đường xuyên tâm), quỹ đạo nhảy qua lại hai bên và robot trườn dần vào vật cản.
# Bật: lọc elite ngược bên khỏi bước cập nhật CEM, nhớ bên đã chọn qua các chu kỳ.
side_hysteresis_enabled: false # ĐỂ TẮT ở bản này cho tới khi chạy thử trên robot
side_switch_margin: 0.2 # bên kia phải rẻ hơn ít nhất tỉ lệ này mới được đổi bên (0.2 = 20%).
# Tăng = lì hơn, hết nhảy nhưng chậm nhận đường tốt hơn khi map đổi;
# giảm về 0 = tắt tác dụng hysteresis dù cờ đang bật
side_hold_cycles: 0 # số chu kỳ KHOÁ bên vừa commit, chồng lên side_switch_margin. Trường
# vật cản dày cost hai bên đều lớn và nhiễu, chênh 20% giữa hai chu kỳ
# là chuyện thường nên margin đơn lẻ vẫn flap (đo sim 18/8: đảo bên 4
# lần/11 s). Khoá nhả sớm nếu bên cũ biến mất khỏi elite. 0 = tắt
side_infeasible_res: 0.0 # [m] "khả thi thắng bất khả thi": bên đang commit có residual elite
# tốt nhất TRÊN ngưỡng này trong khi bên kia có elite DƯỚI ngưỡng ->
# đổi bên NGAY, bỏ qua cả side_switch_margin lẫn side_hold_cycles.
# Margin so COST chứ không so tính khả thi — đo sim 19/8: robot ôm bên
# bất khả thi 13 s (res 1.2-2.8) trườn dần vào vật cản vì chênh cost
# không bao giờ đạt 20%, trong khi bên kia đổi phát là res sập về 0.03.
# Hai bên cùng khả thi thì margin + hold vẫn cầm quyền như cũ. 0 = tắt
side_switch_feasible_res: 0.0 # [m] > 0 = guard ĐỔI BÊN: rời bên đã commit chỉ được chấp nhận
# khi elite tốt nhất của BÊN MỚI có residual <= ngưỡng này (nghiệm
# mới THỰC THI ĐƯỢC từ pose hiện tại — giữa bãi nghiệm bên kia còn
# cắt xuyên vật cản vì start ghim vào pose robot). ĐỂ 0 (TẮT) ở bản
# này cho tới khi chạy thử trên robot; cây sim đang thử 0.3
# ================= Elite blend (B2, 8/9) =================
# Trên đoạn THOÁNG (không vật cản ràng buộc), nhiều elite của CEM gần đồng cost — batch được vẽ
# lại NGẪU NHIÊN mỗi chu kỳ nên elite thắng (hard-argmin) đổi qua đổi lại, độ cong đầu quỹ đạo
# đổi theo -> omega đảo dấu liên tục dù đường thẳng, không vật cản (đo sim 7-8/9: res=0.00,
# omega nhảy dấu ~50% số chu kỳ). Bật blend: trộn top-N elite theo trọng số softmax thay vì lấy
# đúng 1 elite. KHÔNG đụng cost(k)/obstacle penalty/cập nhật phân phối CEM — chỉ đổi bước chọn
# nghiệm cuối cùng, và có bộ kiểm chứng: quỹ đạo trộn không tốt bằng elite thắng (dùng đúng công
# thức cost đã có) thì tự động dùng lại elite thắng, y hệt hôm nay.
elite_blend_enabled: false # [bool] TẮT cho tới khi chạy thử — tính năng mới thêm vào cây này.
# Bật = kích hoạt trộn elite mọi chu kỳ (bộ kiểm chứng tự thu hẹp
# phạm vi khi có vật cản, không cần công tắc riêng theo obs)
elite_blend_topn: 10 # số elite tham gia trộn, cắt về [1, ellite_num]. ĐO 8/9 (30 chu kỳ,
# đường thẳng thoáng): topn 2-5 làm phương sai omega TĂNG 75-180%
# (trộn nửa vời chỉ thêm nguồn nhiễu mà không trung bình được gì);
# topn=10 giảm 48% VÀ cross-track 0.037 -> 0.009 m; topn 20/40 lợi
# ít dần rồi mất hẳn (kéo cả elite hạng thấp vào). 1 = tắt hiệu quả
elite_blend_lambda: 0.5 # [-] nhiệt độ softmax RIÊNG cho blend, không dùng chung cem_lamda để
# không vô tình đổi tốc độ hội tụ phân phối CEM. Thấp = trọng số sập
# gần về elite thắng ngay khi cost tách biệt (đúng lúc có vật cản);
# cao = san đều trọng số hơn, dễ mượt quá tay
elite_blend_validate_margin: 0.01 # ngưỡng chấp nhận của bộ kiểm chứng, đơn vị cost (giống thang
# cost(k) trừ phần res_norm). Quỹ đạo trộn tệ hơn elite thắng quá
# ngưỡng này thì bị từ chối, dùng lại elite thắng như cũ. 0 = trộn
# phải tốt bằng hoặc hơn elite thắng, không có dung sai
# ================= Hybrid path-tracking + PriestCore avoidance (16/9) =================
# Xem doc/HYBRID_TRACK_AVOID_PLAN.md ở gói priest_local_planner. PriestCore::solve() KHÔNG đổi ở
# bất kỳ mode nào — hai nguồn lệnh: PathTrackerCore (luật Kanayama bám path, tất định) và
# PriestCore (né vật cản, y hệt hôm nay), trộn liên tục theo trọng số b bởi HybridArbiter.
hybrid_mode: 0 # [int] TẮT cho tới khi chạy thử — tính năng mới thêm vào cây này.
# 0=tắt (bit-for-bit hôm nay) 1=shadow (tính+log, lệnh không đổi)
# 2=bật (lệnh trộn thật sự được phát ra)
tracker_heading_gain: 1.5 # [1/s] k_theta — hệ số phản hồi sai số hướng của tracker.
tracker_lateral_gain: 2.0 # [1/(m*s)] k_lat — hệ số phản hồi lệch ngang, nhân v nên đứng yên
# không tự lái để sửa lệch ngang.
tracker_preview_distance: 0.15 # [m] đọc yaw_path/kappa_ref phía trước điểm gần nhất bấy nhiêu mét.
tracker_curvature_ff_gain: 1.0 # [-] hệ số nhân v*kappa_ref (feedforward độ cong). 0 = tắt.
tracker_curvature_margin: 1.0 # [-] trần tốc độ vào cua theo độ cong tham chiếu.
blend_dev_window: 1.5 # [m] cửa sổ đo độ lệch quỹ đạo PriestCore so với path (một trong ba
# nguồn quyết định b).
blend_dev_noise: 0.15 # [m] lệch dưới mức này coi là nhiễu lấy mẫu CEM, không phải né vật cản.
# [17/9] đo sim không vật cản: dev_max p50 0.05, p90 0.13, max 0.22.
blend_dev_avoid: 0.30 # [m] lệch từ mức này coi là né vật cản thật. Phải > blend_dev_noise.
blend_dev_gate_obstacles: true # [bool] chỉ tính b_dev khi solve có vật cản trong tầm (obs_active>0);
# không có vật cản thì lệch là nhiễu solver, không phải né. false = tính
# bất kể (chỉ để đo lại).
blend_path_start_distance: 2.0 # [m] vật cản trên path xa hơn mức này không đẩy b lên.
blend_path_end_distance: 0.6 # [m] vật cản gần hơn/bằng mức này đẩy b lên hẳn 1. Phải <
# blend_path_start_distance.
blend_release_tau: 0.7 # [s] hằng số thời gian khi b GIẢM. b TĂNG luôn tức thì. 0 = tức thì cả hai.
blend_validate_time: 0.5 # [s] cửa sổ dò costmap trên cung lệnh đã trộn, chỉ chạy khi 0<b<1 và
# hybrid_mode=2. 0 = tắt bộ kiểm chứng.
# ================= Debug =================
# Nhóm log chẩn đoán [DBG-PRIEST-*]. debug_level là công tắc tổng; ba cờ dưới chọn nhóm.
# Mức 3 in mỗi chu kỳ (~30 dòng/giây @ 30 Hz) — chỉ dùng khi truy lỗi, xong trả về 0.
debug_level: 0 # 0=tắt 1=chỉ log khi sự kiện đổi (solve fail/hồi, điểm vật cản chạm trần)
# 2=log định kỳ throttle 1 Hz 3=log mọi chu kỳ điều khiển
debug_solve: true # [DBG-PRIEST-SOLVE] thời gian từng stage của optimizer [ms], số cặp
# (điểm quỹ đạo, vật cản) va chạm / tổng, residual + cost của quỹ đạo
# được chọn, warm start. Dùng khi đo CPU/solve time (vd trên RK3588S).
debug_obstacles: true # [DBG-PRIEST-OBS] số điểm vật cản gom từ costmap so với trần thật
# (trần = min(max_obstacle_points, num_obs)). Chạm trần = optimizer
# đang mù vật cản xa hơn theo hướng chạy — cảnh báo một lần khi đổi trạng thái.
debug_command: false # [DBG-PRIEST-CMD] lệnh phát ra + trạng thái lúc đó: state (track /
# inplace / rot2path / rot2goal / fallback), v & omega sau clamp,
# vtraj, ff, zeta, hscale, vmeas, dist, res/sv/side. Ồn nhất,
# chỉ bật khi truy hành vi bám path.
debug_hybrid: true # [DBG-PRIEST-HYB] trọng số b + ba nguồn (solver/dev/path) + lệnh của
# cả hai nhánh mỗi chu kỳ hybrid_mode >= 1. Độc lập với hybrid_mode.
debug_plan: true # [DBG-PRIEST-PLAN] ĐƯỜNG THAM CHIẾU mà solver được giao — nhóm log
# sinh ra để phân biệt "solver tệ" với "path bắt nó đi xuyên vật cản"
# (trường hợp detour path của recovery trong môi trường đông).
# Hai dòng:
# - "new plan": mỗi lần nhận plan mới, in n điểm, arc [m], gap_robot
# [m] (khoảng cách robot tới điểm ĐẦU plan — detour path bắt đầu xa
# robot là dấu hiệu xấu), start/goal, kappa_max [1/m] (độ cong lớn
# nhất, đo trên mẫu cách nhau 0.25 m), và kết quả dò costmap dọc
# path: số waypoint nằm trên ô inscribed(253)/lethal(254)/unknown +
# vị trí điểm bị chặn ĐẦU TIÊN (#index@arc [m]).
# - "track": định kỳ (mức 2 = 1 Hz), pruned=<số điểm sau cắt>/<tổng>,
# cte [m] (lệch ngang robot↔path), arc_ahead [m] (chiều dài phần
# path còn trong lookahead), tail [m], corridor, và blocked_ahead
# = điểm bị chặn đầu tiên PHÍA TRƯỚC kèm cost.
# Rẻ: một lần dò costmap mỗi plan + một lần mỗi giây. Tắt = false.
# LƯU Ý: cảnh báo "reference path crosses N LETHAL cell(s)" KHÔNG tắt
# được bằng khoá này — path xuyên ô lethal là lỗi của global planner,
# không phải thông tin chẩn đoán.

View File

@@ -0,0 +1,297 @@
# =================================================================================================
# 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]
# 2026-09-04: Phép đo 3 (collision guard) có trigger riêng; rỗng = guard không được vũ trang.
collision: [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
# 2026-09-04: BỐN khoá `planning_distance` / `sample_step` / `rejoin_clearance` /
# `max_rejoin_distance` đã bị GỠ. Chúng chỉ phục vụ việc quét chọn ĐIỂM NỐI của mô hình detour
# cũ; từ 2/9 behavior lập lại CẢ ĐƯỜNG tới đích chặng nên plugin KHÔNG đọc chúng nữa.
# Số lượt lập đường tối đa trong MỘT lần chạy behavior; mỗi control cycle chạy ĐÚNG MỘT lượt.
# ► 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
# true = giữ mutex costmap trong lúc đọc dữ liệu lập đường (2026-09-04: khai tường minh, giá trị
# bằng đúng mặc định C++ nên hành vi không đổi).
# ► Chỉnh: giữ true. false chỉ dành cho host tự bảo đảm costmap không bị ghi trong lúc đó.
lock_costmap: true
# 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,164 @@
SBPLLatticePlanner:
library_path: libsbpl_lattice_planner
environment_type: XYThetaLattice
planner_type: ARAPlanner
allocated_time: 10.0
# ===== Anytime (pha 0, 21/9/2026) — ARA* nhận ReplanParams thay vì replan(double) =====
# Chuỗi: tìm nghiệm ĐẦU với heuristic nới eps=initial_epsilon (eps 3 = A* có trọng số, nở ít
# state hơn hàng chục lần so với eps 1 — goal 134 m trên sehc với eps 1.0 nở 925k state/5 s không
# ra), rồi hạ eps từng nấc `eps_step` tới `final_epsilon` chừng nào tổng thời gian còn dưới
# `repair_time`. Path ở eps>1 vẫn mượt (cùng mprim), chỉ có thể dài hơn tối ưu tối đa eps lần.
# ► eps 1.0 = A* thuần: goal xa trên map rộng gần như chắc chắn hết giờ. Chỉ đặt 1.0 khi map nhỏ.
# ⚠ ARA* đo thời gian bằng clock() = CPU time của CẢ tiến trình (mọi thread) nên ngân sách wall
# thực tế ngắn hơn số ghi ở đây khi costmap/control loop bận.
initial_epsilon: 3.0
# eps dừng hạ. 1.0 = tối ưu; 1.5 = chấp nhận dài hơn tối ưu <= 1.5 lần để dư thời gian.
final_epsilon: 1.0
# Mỗi vòng ARA* hạ eps đi ngần này (SBPL mặc định 0.2; 0.5 = ít vòng hơn, mỗi vòng rẻ hơn).
eps_step: 0.5
# [s] Tổng thời gian tối đa (tính từ lúc bắt đầu search) còn được hạ eps SAU khi đã có nghiệm đầu.
# <= 0 = hạ tới hết allocated_time (hành vi cũ, lượt plan luôn dùng trọn ngân sách khi eps chưa
# về final). 2.0 = có nghiệm là trả về trong ~2 s dù chưa tối ưu — hợp goal xa.
repair_time: 2.0
# [bool] true = trả ngay nghiệm đầu (eps = initial_epsilon), không hạ eps. Chỉ để đo/bench.
return_first_solution: false
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
# [bool] Ô UNKNOWN (chưa scan) có đi được không. Khai TƯỜNG MINH — thiếu khoá thì code rơi về true
# và log cảnh báo lúc boot.
# true : unknown = free. Goal ngoài vùng đã map vẫn có "đường điểm" qua vùng trống ngoài nhà ->
# ARA* quét toàn bộ free + unknown (6-7 s trên map 70x39 m, đo máy dev 2026-09-17) rồi
# mới báo không có đường.
# false: unknown = tường. Goal ngoài vùng đã map bị từ chối ngay ở bước "2D reachability: h=INF"
# (~0.1 s). Robot thật nên false — không lập plan xuyên chỗ chưa nhìn thấy.
# ► Giữ true ở bản này để không đổi hành vi đang chạy; đổi false sau khi đã thử trên robot.
allow_unknown: true
# ===== Chẩn đoán lập plan (2026-09-18) =====
# Dòng LỖI KHÔNG tắt được bằng khoá nào: "goal REJECTED ..." (goal đứng trên ô >= 253 hoặc footprint
# đè tường/mép lưới), "2D reachability: h=INF ..." (goal bị bịt kín), "NO SOLUTION ... reason=
# EXHAUSTED|TIMEOUT expands=... phase_elapsed=..." (search chạy mà không ra). Đọc reason:
# EXHAUSTED + h_2d hữu hạn = có đường cho ĐIỂM, không có đường cho FOOTPRINT (khe hẹp, hoặc goal
# hợp lệ nhưng không action nào kết thúc đúng (x,y,theta) đó).
# TIMEOUT = hết allocated_time -> nới allocated_time hoặc tăng initial_epsilon.
# [bool] Nhóm log thông tin: "audit: start cell ... goal cell ...", "2D reachability: h=<số>",
# "solved: ... expands= h_2d= phase=", và "metrics: ... detour= turn_deg= arcs= wiggles=
# plan_ms= corridor= corridor_ms=" (hình học + chi phí mỗi lượt plan thành công — dùng để so
# dải Voronoi on/off, soft/hard, eps; grep "metrics:" rồi so cùng goal; script offline:
# sbpl_lattice_planner/tools/eval_plan_bag.py). Mặc định BẬT; tắt khi log robot thật quá dày.
debug_plan: true
# [ô] Bán kính cửa sổ lưới in ASCII quanh goal VÀ start khi goal bị từ chối / không có đường.
# 0 = tắt. 15 = 31x31 ô = 1.5 m @ 5 cm mỗi cửa sổ (62 dòng log mỗi lần fail). Trần 60.
# Ký hiệu: . free - preferred : inflated/unpreferred i inscribed # lethal ? unknown S G.
# Bật khi cần thấy VÁCH nào chặn mà không cần dump costmap; rất nặng log, tắt lại sau khi xong.
debug_grid_window: 0
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
# ===== Dải hành lang theo route graph (Voronoi) cho goal xa (2026-09-21) =====
# Graph do host biên dịch sẵn từ map (voronoi_route -> voronoi.json trong thư mục map) và đẩy vào kho
# `robot_sensor_ports` cùng lúc với static map (`addRouteGraph`). Planner KHÔNG dựng graph; chỉ nhận
# khi kích thước/resolution/origin VÀ hash mask vật cản khớp static layer sống, rồi với goal xa:
# gắn start/goal vào graph, Dijkstra ra tuyến, đóng dấu dải quanh tuyến; ô NGOÀI dải nhận cost
# inscribed (không lethal) -> ARA* và heuristic 2D chỉ nở trong dải (~3 % map trên sehc thay vì 100 %).
# Search bên trong dải vẫn là lattice + mprim + cost như cũ -> path cùng chất lượng.
# Không graph / lệch map / gắn thất bại / khác thành phần liên thông = chạy full như trước, log
# [debug/corridor] nói lý do. Dòng "route graph REJECTED ..." là LỖI, không tắt được.
voronoi_corridor:
# [bool] Bật cơ chế. false = như chưa có tính năng (không đọc kho).
enabled: true
# Khoá kho nhận graph — phải trùng `topic` trong sensor_store_params.yaml và chuỗi host truyền vào
# addRouteGraph(). Rỗng = không đọc kho.
route_graph_topic: /route_graph
# Tên layer StaticLayer của global costmap để đối chiếu hash (tên trong `plugins:` của
# costmap_global_params*.yaml, ví dụ `navigation_map`). Rỗng = tự lấy StaticLayer ĐẦU TIÊN theo
# kiểu — đủ dùng khi chỉ có một; đặt tên khi có thêm layer tường ảo cũng là StaticLayer.
static_layer_name: ""
# [m] Goal gần hơn ngưỡng này -> không dùng dải (search full đã nhanh, dải chỉ thêm việc).
min_range_m: 15.0
# [m] Nửa bề rộng TỐI THIỂU của dải. Phải >= bán kính ngoại tiếp footprint + 1 ô, nếu không
# footprint tại start/goal đè ô ngoài dải. Hẹp = search nhanh, dễ cạn ở chỗ rẽ gắt.
half_width_m: 1.5
# Nửa bề rộng tại mỗi ô tuyến = max(half_width_m, hệ số × clearance tại ô) — sảnh rộng thì dải
# rộng, lối giữa kệ thì hẹp. 0 = bề rộng cố định.
clearance_scale: 0.8
# [m] Trần nửa bề rộng thích nghi.
max_half_width_m: 6.0
# [m] Bán kính BFS gắn start/goal vào graph. Điểm trong phòng kín xa graph hơn ngần này = không
# gắn được -> full search.
attach_max_radius_m: 10.0
# [m] Edge graph có điểm hẹp nhất dưới ngưỡng này thì tuyến KHÔNG đi qua, start/goal cũng không
# gắn vào (graph do producer lọc chung ở 0.3 m, không biết robot nào dùng). Nếu không, tuyến chui
# khe robot không lọt -> search cạn trong dải -> nới -> bỏ dải -> full: mất hết lợi ích.
# < 0 = tự lấy bán kính NỘI TIẾP footprint (T800: 0.48 m). Đặt lớn hơn khi muốn né lối hẹp.
route_min_clearance_m: -1.0
# hard | soft — ô NGOÀI dải bị xử lý thế nào.
# hard: gán cost inscribed -> tâm robot không đi ra ngoài dải; heuristic 2D dừng ở mép dải.
# Nhanh nhất; cạn trong dải thì nới (`widen_*`), hết nấc thì bỏ dải chạy full.
# soft: chỉ PHẠT cost (`soft_penalty_cost`), search vẫn ra ngoài được khi cần — tuyến chỉ là
# "hướng tổng quát", path không bị ép theo dải, dải không bao giờ là lý do fail; đổi lại
# tăng tốc ít hơn hard. Không có pha nới/bỏ dải, một pha trọn allocated_time.
outside_mode: soft
# [0..252, thang costmap] Cost gán cho ô ngoài dải khi soft (max với cost costmap sẵn có). SBPL
# nhân cost hành động theo (cost_ô/14 + 1): free=60 -> 5x, 200 -> 15x, tức đi ngoài dải đắt ~3 lần.
# Tăng = bám dải chặt hơn, nhanh hơn, đường vòng hơn khi dải chọn sai; giảm = ngược lại.
soft_penalty_cost: 200
# Khi search CẠN trong dải (OPEN rỗng trước giờ) hoặc 2D không nối trong dải: nhân bề rộng lên
# ngần này rồi thử lại, tối đa `max_widen` lần; hết nấc thì bỏ dải, chạy full với thời gian còn lại.
widen_factor: 2.0
max_widen: 1
# Phần `allocated_time` cấp cho pha có dải (0.05..1.0); phần còn lại để nới/fallback. HẾT GIỜ trong
# dải thì KHÔNG fallback (full còn chậm hơn) -> trả lỗi, nới allocated_time hoặc initial_epsilon.
budget_fraction: 0.6
# [bool] false CHỈ để đo (bench): cạn trong dải mà không còn nấc nới thì trả fail thay vì full.
fallback_full_search: true
# [bool] Nhóm log [debug/corridor]: graph nhận/từ chối lý do, gắn, tuyến, mask %, nới, tóm tắt
# mỗi lượt. Mặc định BẬT. Dòng LỖI (graph REJECTED, NO SOLUTION inside the corridor) không qua khoá này.
debug_corridor: true
# ===== Làm mượt path sau search: kéo dây + bo góc (2026-09-22) =====
# Đo trên sehc 22/9 (goal 100 m, dải soft, eps 1.5): path lattice dài hơn đường ngắn nhất 2D 12 %,
# 11 lần đổi chiều rẽ, 11 % chiều dài bỏ được nếu đi thẳng nơi đi thẳng được. Ba nguồn: ARA* dừng ở
# eps>1, dải Voronoi bám trục giữa, lưới 16 hướng làm đường xiên thành răng cưa. Smoother giữ TOPO
# của search (qua khe nào, né đảo bên nào) rồi kéo thẳng mọi đoạn footprint đi thẳng được trên
# costmap SỐNG, bo góc bằng cung bán kính cố định để tracker giữ tốc độ. Luật va chạm y hệt lattice:
# tâm robot không lên ô >= inscribed (253); ô >= cost tại bán kính ngoại tiếp thì xét cả footprint
# (không ô nào LETHAL). Path có đoạn lùi (cusp) KHÔNG làm mượt (giữ nguyên lattice). Chi phí ~10-30
# ms cho 100 m. Kết quả ghi ở dòng "metrics: ... smooth=on raw_m= smooth_ms= anchors= fillets=a/b".
smooth_path:
# [bool] Bật smoother. false = trả path lattice như cũ.
enabled: true
# [m] Cửa sổ kéo dây: từ mỗi mốc chỉ thử tới điểm cách tối đa ngần này THEO CHIỀU DÀI PATH lattice.
# Một đoạn vòng chỉ bị cắt khi cửa sổ phủ hết nó — 30 m đã để sót chữ V dài 33 m trên sehc
# (22/9). Tốn thời gian tuyến tính theo cửa sổ (~200 đoạn thử / mốc ở 80 m), giữ >= goal xa nhất.
max_shortcut_m: 80.0
# [m] Bán kính cung bo góc; nên = bán kính cung trong bộ mprim (diff_r106: 1.06 m) để tracker
# chạy hết tốc. 0 = mọi góc gãy (quay tại chỗ). Cung đè vật cản -> góc đó tự gãy.
fillet_radius_m: 1.06
# [m] Hai cạnh góc ngắn quá thì thu bán kính lại; dưới ngưỡng này thì để gãy (quay tại chỗ) thay
# vì cung tí hon. Đặt = 1/kappa mà base giữ được ở tốc độ danh định: Priest báo "kappa=1.25 1/m at
# 0.40 m/s" -> 0.8 m; cung R=0.4 (22/9) làm nó bò 0.20 m/s suốt cung.
min_fillet_radius_m: 0.8
# [0..252, thang costmap] Ô tâm có cost cao hơn = chặn với smoother (lattice cho tới 252).
# Hạ (vd 200) = đường kéo thẳng giữ khoảng cách với tường lớn hơn, bớt thẳng.
max_cell_cost: 252
# [m] Tâm robot phải cách ô LETHAL (đo bằng distance transform, không phụ thuộc inflation) ít
# nhất ngần này trên mọi đoạn kéo thẳng / cung bo. < 0 = tự lấy bán kính NGOẠI TIẾP footprint
# (T800: 0.755 m). Vì sao cần: kéo dây không nhìn cost nên cắt góc sát đúng mép inscribed
# (0.48 m) của costmap toàn cục; local costmap (laser, inflation 0.55/15) đặt 253 ngay đó ->
# Priest "blocked_ahead cost=253" -> detour -> ABORTED (sehc 22/9, mission 3, cụm cột (-40,-10)).
# Chỗ hẹp không giữ nổi khoảng này thì đoạn đó giữ nguyên path lattice. Tăng = an toàn hơn,
# ít cắt góc hơn; hạ dưới inscribed + 0.1 là mời lại lỗi trên.
min_clearance_m: -1.0
# [m] Khoảng cách pose trên path đầu ra (kiểm va chạm ở nửa bước này).
sample_step_m: 0.05
# [deg] Chỗ đoạn kéo thẳng nối vào đoạn path lattice giữ nguyên (không có chỗ bo cung), hướng
# đoạn thẳng chỉ được lệch heading lattice tối đa ngần này; điểm xa hơn mà lệch nhiều thì bỏ,
# lấy điểm gần hơn thẳng hàng. Không có điểm nào thẳng hàng thì lấy điểm xa nhất như thường.
# Vì sao: mối nối gãy 30-40 độ làm Priest đo kappa 2.3-2.6 và bò 0.2 m/s (sehc 22/9, cụm cột).
# 0 = tắt. Tăng = thẳng hơn nhưng nhiều mối gãy; giảm = ít cắt tắt hơn.
max_junction_deg: 20.0

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

@@ -1,4 +1,3 @@
base_global_planner: TwoPointsPlanner
TwoPointsPlanner:
library_path: libtwo_points_planner
lethal_obstacle: 20

View File

@@ -0,0 +1,104 @@
# =================================================================================================
# voronoi_route — tham số dựng route graph (GVD) và dải hành lang cho goal xa.
#
# Ai đọc: người vận hành / dev khi soát `voronoi_preview.png` thấy graph rối, đứt, hay tuyến đi vòng.
# Ai nạp: RBApp lúc copy map quét xong vào `data/maps/<id>/` (chạy Voronoi một lần, lưu graph vào
# chính thư mục map đó), và tool `voronoi_route_compile` khi chạy tay. Cả hai tìm file này trong
# thư mục config truyền vào (--config-dir / PNKX_NAV_CORE_CONFIG_DIR) giống cách costmap tìm
# *_layer_params.yaml — file khớp tên ĐẦU TIÊN thắng, đừng để hai bản trong cùng cây.
#
# Đây là BẢN MẶC ĐỊNH đóng gói kèm gói. Cây đang chạy thật là RBApp `data/config/runtime/` (thêm
# khi ghép); các bản sao khác chỉ để tham chiếu schema.
#
# Đơn vị: mét ở đây, lib làm việc theo ô — quy đổi bằng `resolution` của map lúc nạp.
# Luật "ô nào là vật cản" (block `obstacle:` dưới) TỰ CHỨA trong file này — gói chạy độc lập, KHÔNG
# đọc, không suy theo config của gói khác (costmap, sbpl...). Mỗi khoá dưới `obstacle:` là quyết định
# của riêng gói này; đổi tay khi muốn map/graph coi vật cản khác đi, không có nguồn nào khác chi phối.
# =================================================================================================
voronoi_route:
graph:
# [m] Nhánh cụt ngắn hơn ngưỡng này bị cắt (nhiễu răng cưa ở góc tường lồi). Tăng = graph gọn
# hơn nhưng có thể mất ngõ cụt ngắn thật (robot vẫn tới được nhờ attach, chỉ không có tuyến sẵn).
min_edge_length_m: 0.3
# Nhánh cụt ngắn hơn `ratio × clearance(ngã rẽ gốc)` bị cắt: nhánh không thoát khỏi đĩa trống
# quanh ngã rẽ thì không dẫn đi đâu — đây là "râu" từ ridge đâm vào vết lõm tường, dài đúng bằng
# khoảng trống nên ngưỡng mét ở trên không cắt được. 1.0–1.5 hợp lý; 0 = tắt.
spur_clearance_ratio: 1.2
# [m] Thành phần liên thông có tổng chiều dài edge nhỏ hơn bị bỏ (túi cô lập trong lòng kệ,
# mảng unknown lẫn free). Tăng nếu preview còn cụm đỏ nhỏ không nối với đâu.
min_component_length_m: 2.0
# [m] Edge có điểm hẹp nhất < ngưỡng này bị bỏ: lối robot không lọt thì không phải tuyến. Đặt =
# bán kính NỘI TIẾP footprint. Map SLAM (xloc) biên free/unknown răng cưa sinh hàng nghìn vòng nhỏ
# đúng loại này — không có khoá này graph gấp 3–5 lần. 0 = tắt. Nguy hiểm nếu đặt lớn hơn nửa cửa
# hẹp nhất trong nhà: cửa đó biến mất khỏi graph, tuyến đi vòng.
min_clearance_m: 0.3
# [m] Bán kính BFS tối đa khi gắn start/goal vào graph. Điểm nằm trong phòng kín xa GVD hơn
# ngần này = gắn thất bại -> planner chạy full, không dùng dải.
attach_max_radius_m: 10.0
# Số ô lethal đổi tích luỹ trước khi trích lại graph (update khoảng cách vẫn chạy ngay). Nhỏ =
# graph luôn tươi nhưng tốn CPU mỗi lượt plan khi map hay đổi.
graph_rebuild_min_changed_cells: 200
# Tỉ lệ ô đổi so với toàn map mà từ đó build lại từ đầu thay vì cập nhật dần (đổi tầng cùng kích
# thước rơi vào đây). Incremental trên thay đổi diện rộng chậm hơn build mới.
full_rebuild_fraction: 0.02
corridor:
# [m] Nửa bề rộng dải tối thiểu quanh tuyến. Phải >= bán kính NGOẠI TIẾP footprint + 1 ô, nếu không
# footprint tại start/goal đè lên ô ngoài dải và planner từ chối. Hẹp = tìm nhanh, dễ cạn ở chỗ rẽ.
half_width_min_m: 1.5
# Nửa bề rộng tại mỗi ô tuyến = max(half_width_min, hệ số × clearance tại ô đó). Sảnh rộng -> dải
# phủ cả sảnh, tránh ép robot đi giữa sảnh vòng hơn đường chéo. 0 = bề rộng cố định.
clearance_scale: 0.8
# [m] Trần của nửa bề rộng thích nghi. Lớn = ít thu hẹp không gian tìm ở sảnh; nhỏ = nhanh hơn
# nhưng đường chéo qua sảnh có thể ra ngoài dải.
half_width_max_m: 6.0
bundle:
# Ghi `voronoi_gvd.pgm` (ô GVD, 8-bit). Consumer dựng lại được từ edge, tắt để tiết kiệm đĩa.
write_gvd: true
# Ghi `voronoi_dist.pgm` (clearance ×10, 16-bit). Cần cho bề rộng thích nghi khi nạp bundle;
# tắt thì corridor dùng half_width_min cố định.
write_dist: true
# Ghi `voronoi_preview.png` — chỉ cho người soát, runtime không đọc. Tool mới ghi được (cần OpenCV).
write_preview: true
# Ghi `voronoi_graph.png` — ẢNH MAP GỐC (đúng pixel map.png) + graph đã lọc vẽ đè: edge đỏ, ngã rẽ
# xanh lá, đầu cụt xanh dương. Không tô lại màu, không GVD thô, không tuyến/dải — để đối chiếu
# graph với tường thật, hoặc hiện lên web thay preview. Tool mới ghi được (cần OpenCV).
write_graph_image: true
# Ghi `voronoi_graph_overlay.png` — cùng nét vẽ nhưng nền TRONG SUỐT (RGBA), để lớp web (Konva)
# đặt đè lên map.png sẵn có mà không nhân đôi ảnh nền.
write_graph_overlay: false
obstacle:
# 4 khoá + `unknown` dưới đây KHÔNG đọc config nào khác lúc chạy, nhưng cùng Ý NGHĨA với costmap
# thật đang chạy — đổi robot/costmap thì soát tay, sửa theo cho khớp, không tự đồng bộ:
# unknown_cost_value / track_unknown_space / lethal_cost_threshold / trinary_costmap
# <-> `static_layer:` trong `static_layer_params.yaml` (cùng cây config với costmap đang dùng,
# unknown (traversable/obstacle) <-> `SBPLLatticePlanner/allow_unknown` trong `sbpl_global_params.yaml`
# cùng cây trên: allow_unknown=true -> đặt `traversable`; allow_unknown=false -> đặt `obstacle`.
# Ô = giá trị này -> coi là "chưa quét".
unknown_cost_value: -1
# true: ô unknown giữ nguyên trạng thái "chưa biết" (đi tiếp theo `unknown` bên dưới).
# false: ô unknown coi luôn là free — tắt thì khoá `unknown` dưới vô nghĩa.
track_unknown_space: true
# Giá trị ô >= ngưỡng này -> vật cản chắc chắn (lethal).
lethal_cost_threshold: 100
# true: mọi ô dưới ngưỡng lethal đều FREE (bản đồ 3 trạng thái). false: dùng giá trị đã scale —
# gói này không nội suy cost trung gian, để false thì mọi ô dưới lethal cũng vẫn coi là free.
trinary_costmap: true
# traversable | obstacle. Ô unknown (NO_INFORMATION, chỉ có tác dụng khi track_unknown_space=true)
# có chặn Voronoi không.
# traversable = không chặn (GVD tràn ra vùng chưa quét qua khe tường).
# obstacle = chặn (graph gọn hơn, nhưng có thể LỆCH với planner nếu planner vẫn đi qua được
# ô unknown — hash bundle vẫn đúng vì luật được ghi vào `source`, chỉ là tuyến có
# thể tránh chỗ planner đi được).
unknown: traversable
# [m] Vùng quan tâm: hộp bao mọi ô vật cản (tường) nở thêm lề này; NGOÀI hộp coi là vật cản.
# Chặn các tia Voronoi bắn từ khe tường ra mép ảnh khi bên ngoài là free/unknown-đi-được (map sim
# `warehouse`: 110 thành phần -> vài chục; map SLAM 9.4M ô: bỏ tính 7M ô unknown ngoài nhà, ~2x nhanh).
# Lề nhỏ (0.5) cố ý: dải free giữa tường ngoài và mép hộp < 2×min_clearance nên không sinh vòng GVD
# bao quanh nhà. Không đổi gì bên trong hộp. Consumer hash theo cùng lề (ghi trong `source`). < 0 = tắt.
roi_margin_m: 0.5

View File

@@ -39,7 +39,7 @@ flowchart TB
%% ========== INTERFACE LAYER ==========
subgraph Interface["🔌 Interface Layer"]
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 BaseNav fill:#FFE0B2,stroke:#E65100,stroke-width:3px,font-size:14px
end
@@ -67,8 +67,8 @@ flowchart TB
%% ========== COSTMAP LAYER ==========
subgraph Costmap["🗺️ Costmap Layer"]
direction LR
GC["<b>🌍 Global Costmap</b><br/>━━━━━━━━━━━━━━━━<br/>📦 costmap_2d::Costmap2DROBOT<br/>🌍 frame: map<br/>━━━━━━━━━━━━━━━━<br/>🗺️ Static Map<br/>🚫 Obstacles<br/>💰 Inflation Layer"]
LC["<b>📍 Local Costmap</b><br/>━━━━━━━━━━━━━━━━<br/>📦 costmap_2d::Costmap2DROBOT<br/>📍 frame: odom<br/>━━━━━━━━━━━━━━━━<br/>🔍 Dynamic Obstacles<br/>📡 Sensor Fusion<br/>⚡ Real-time Updates"]
GC["<b>🌍 Global Costmap</b><br/>━━━━━━━━━━━━━━━━<br/>📦 robot_costmap_2d::Costmap2DROBOT<br/>🌍 frame: map<br/>━━━━━━━━━━━━━━━━<br/>🗺️ Static Map<br/>🚫 Obstacles<br/>💰 Inflation Layer"]
LC["<b>📍 Local Costmap</b><br/>━━━━━━━━━━━━━━━━<br/>📦 robot_costmap_2d::Costmap2DROBOT<br/>📍 frame: odom<br/>━━━━━━━━━━━━━━━━<br/>🔍 Dynamic Obstacles<br/>📡 Sensor Fusion<br/>⚡ Real-time Updates"]
style Costmap fill:#F1F8E9,stroke:#558B2F,stroke-width:4px,color:#000
style GC fill:#DCEDC8,stroke:#558B2F,stroke-width:3px,font-size:13px
style LC fill:#DCEDC8,stroke:#558B2F,stroke-width:3px,font-size:13px
@@ -89,12 +89,12 @@ flowchart TB
%% ========== DATA SOURCES ==========
subgraph DataSources["📡 Data Sources"]
direction TB
Goal["<b>🎯 Goal Input</b><br/>━━━━━━━━━━━━━━━━<br/>📍 geometry_msgs::PoseStamped<br/>📨 move_base_simple/goal"]
Goal["<b>🎯 Goal Input</b><br/>━━━━━━━━━━━━━━━━<br/>📍 robot_geometry_msgs::PoseStamped<br/>📨 move_base_simple/goal"]
Loc["<b>🌍 Localization</b><br/>━━━━━━━━━━━━━━━━<br/>📍 Pnkx Loc<br/>🗺️ Global Pose<br/>🔄 Pose Updates"]
TF["<b>🔄 Transform System</b><br/>━━━━━━━━━━━━━━━━<br/>📐 tf3::BufferCore<br/>🌐 Coordinate Frames<br/>⏱️ Time Synchronization"]
Odom["<b>🚗 Odometry</b><br/>━━━━━━━━━━━━━━━━<br/>📍 geometry_msgs::Odometry<br/>⚡ Robot Velocity<br/>📊 Position Tracking"]
Laser["<b>📡 Laser Sensors</b><br/>━━━━━━━━━━━━━━━━<br/>🔍 sensor_msgs::LaserScan<br/>🚫 Obstacle Detection<br/>📏 Distance Measurement"]
Map["<b>🗺️ Map Server</b><br/>━━━━━━━━━━━━━━━━<br/>📋 nav_msgs::OccupancyGrid<br/>🏗️ Static Map<br/>📐 Map Metadata"]
Odom["<b>🚗 Odometry</b><br/>━━━━━━━━━━━━━━━━<br/>📍 robot_geometry_msgs::Odometry<br/>⚡ Robot Velocity<br/>📊 Position Tracking"]
Laser["<b>📡 Laser Sensors</b><br/>━━━━━━━━━━━━━━━━<br/>🔍 robot_sensor_msgs::LaserScan<br/>🚫 Obstacle Detection<br/>📏 Distance Measurement"]
Map["<b>🗺️ Map Server</b><br/>━━━━━━━━━━━━━━━━<br/>📋 robot_nav_msgs::OccupancyGrid<br/>🏗️ Static Map<br/>📐 Map Metadata"]
style DataSources fill:#FFF9C4,stroke:#F57F17,stroke-width:4px,color:#000
style Goal fill:#FFF59D,stroke:#F57F17,stroke-width:3px,font-size:12px
style Loc fill:#FFF59D,stroke:#F57F17,stroke-width:3px,font-size:12px
@@ -107,7 +107,7 @@ flowchart TB
%% ========== CONTROL LOOP ==========
subgraph ControlLoop["🔄 Control Loop"]
direction LR
CmdVel["<b>⚡ Velocity Command</b><br/>━━━━━━━━━━━━━━━━<br/>📤 geometry_msgs::Twist<br/>📨 cmd_vel<br/>━━━━━━━━━━━━━━━━<br/>➡️ Linear Velocity<br/>🔄 Angular Velocity"]
CmdVel["<b>⚡ Velocity Command</b><br/>━━━━━━━━━━━━━━━━<br/>📤 robot_geometry_msgs::Twist<br/>📨 cmd_vel<br/>━━━━━━━━━━━━━━━━<br/>➡️ Linear Velocity<br/>🔄 Angular Velocity"]
BaseCtrl["<b>🎮 Base Controller</b><br/>━━━━━━━━━━━━━━━━<br/>🚗 diff_driver_controller<br/>🚲 steer_drive_controller<br/>━━━━━━━━━━━━━━━━<br/>⚙️ Kinematics<br/>🔧 Hardware Interface"]
style ControlLoop fill:#FFEBEE,stroke:#C62828,stroke-width:4px,color:#000
style CmdVel fill:#FFCDD2,stroke:#C62828,stroke-width:3px,font-size:13px
@@ -194,7 +194,7 @@ Cần làm rõ:
3. **Interface Layer** ✅
- `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
4. **Move Base Core** ✅
@@ -205,20 +205,64 @@ Cần làm rõ:
- Thực thi control loop (executeCycle)
4. **Planning Layer** ✅
- `nav_core::BaseGlobalPlanner`: Interface cho global planners (A*, D*, etc.)
- `nav_core::BaseLocalPlanner`: Interface cho local planners (DWA, TEB, MKT, etc.)
- `nav_core::RecoveryBehavior`: Interface cho recovery behaviors
- Plugin system sử dụng `boost::dll` để dynamic loading
- `robot_nav_core::BaseGlobalPlanner`: Interface cho global planners
- **Global Planner Implementations**:
- `custom_planner` - Custom path planner với curve support và merge path calculation
- `dock_planner` - Docking-specific planner với dock calculation utilities
- `two_points_planner` - Simple planner cho two-point navigation
- `robot_nav_core::BaseLocalPlanner`: Interface cho local planners
- **Local Planner Implementation**:
- `pnkx_local_planner` - Main local planner với multiple behaviors:
- Position planning (MKT algorithm)
- Docking planning
- Go straight planning
- Rotate planning
- `robot_nav_core::RecoveryBehavior`: Interface cho recovery behaviors
- Plugin system sử dụng `boost::dll` và `robot::PluginLoaderHelper` để dynamic loading
5. **Costmap Layer** ✅
- `costmap_2d::Costmap2DROBOT`: Global và local costmap
- Costmap layers: static map, obstacles, inflation
- `robot_costmap_2d::Costmap2DROBOT`: Global và local costmap wrapper
- `robot_costmap_2d::LayeredCostmap`: Layered costmap system
- **Costmap Layers** (8 implementations):
- `StaticLayer` - Static map từ OccupancyGrid
- `ObstacleLayer` - Dynamic obstacles từ sensors
- `InflationLayer` - Cost inflation cho robot footprint
- `VoxelLayer` - 3D voxel grid cho obstacles
- `CriticalLayer` - Critical zones marking
- `DirectionalLayer` - Directional cost preferences
- `PreferredLayer` - Preferred path zones
- `UnpreferredLayer` - Unpreferred zones
- Frame management: map (global), odom (local)
- Thread-safe access với mutex
- Observation buffer cho sensor data
6. **Algorithms Layer** ✅
- `mkt_algorithm`: Diff drive và bicycle kinematics algorithms
- `score_algorithm`: Trajectory scoring và goal checking
- `kalman`: Filtering algorithms
- **MKT Algorithm** (`mkt_algorithm`):
- Differential drive kinematics:
- `diff_go_straight` - Go straight behavior
- `diff_predictive_trajectory` - Predictive trajectory following
- `diff_rotate_to_goal` - Rotate to goal
- Bicycle model kinematics:
- `bicycle_go_straight` - Go straight với bicycle model
- `bicycle_pure_pursuit` - Pure pursuit control
- `bicycle_rotate_to_goal` - Rotate behavior
- **MKT Plugins** (`mkt_plugins`):
- `goal_checker` - Goal checking algorithms
- `simple_goal_checker` - Simple goal checking
- `standard_traj_generator` - Standard trajectory generation
- `limited_accel_generator` - Acceleration-limited trajectory generation
- `kinematic_parameters` - Kinematics parameter management
- `xy_theta_iterator` - Trajectory iteration utilities
- `velocity_iterator` - Velocity space iteration
- `one_d_velocity_iterator` - 1D velocity iteration
- **Score Algorithm** (`score_algorithm`):
- Trajectory scoring và evaluation
- Goal checking utilities
- Trajectory generator interface
- **Kalman Filter** (`kalman`):
- State estimation
- Sensor fusion
- Noise filtering
7. **Data Sources** ⚠️ (Interface cần định nghĩa)
- Localization source (Pnkx Loc)
@@ -232,10 +276,10 @@ Cần làm rõ:
- Velocity command execution
**Định dạng dữ liệu:**
- `geometry_msgs::Pose2D` / `geometry_msgs::PoseStamped` (vị trí + hướng)
- `geometry_msgs::Twist` (vận tốc linear/angular)
- `std::vector<geometry_msgs::PoseStamped>` (đường đi)
- `costmap_2d::Costmap2D` (bản đồ chi phí)
- `robot_geometry_msgs::Pose2D` / `robot_geometry_msgs::PoseStamped` (vị trí + hướng)
- `robot_geometry_msgs::Twist` (vận tốc linear/angular)
- `std::vector<robot_geometry_msgs::PoseStamped>` (đường đi)
- `robot_costmap_2d::Costmap2D` (bản đồ chi phí)
### 3. Thiết kế từng module (interface level)
@@ -244,27 +288,35 @@ Cần làm rõ:
- `move_base_core::BaseNavigation` ✅
- `initialize(TFListenerPtr)` - Khởi tạo với TF listener
- `moveTo(goal, xy_tol, yaw_tol)` - Di chuyển đến goal
- `dockTo(marker, goal, ...)` - Docking đến marker
- `rotateTo(goal, yaw_tol)` - Xoay tại chỗ
- `moveStraightTo(goal, xy_tol)` - Đi thẳng
- `moveTo(order, goal, ...)` - Một order VDA5050, cắt thành từng chặng
- `executeInstantActions(actions)` - Một message `instantActions`, nở theo bảng compound
> **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
- `getRobotPose(...)` - Lấy vị trí robot
- `nav_core::BaseGlobalPlanner` ✅
- `robot_nav_core::BaseGlobalPlanner` ✅
- `makePlan(start, goal, plan)` - Tạo global path
- `initialize(name, costmap_robot)` - Khởi tạo với costmap
- **Implementations**: `custom_planner`, `dock_planner`, `two_points_planner`
- `nav_core::BaseLocalPlanner` ✅
- `computeVelocityCommands(cmd_vel)` - Tính toán velocity command
- `robot_nav_core::BaseLocalPlanner` ✅
- `computeVelocityCommands(odom, cmd_vel)` - Tính toán velocity command
- `setPlan(plan)` - Set global path để follow
- `isGoalReached()` - Kiểm tra đã đến goal chưa
- `swapPlanner(name)` - Thay đổi planner động
- `swapPlanner(name)` - Thay đổi planner động (position, docking, go_straight, rotate)
- `setTwistLinear/Angular(...)` - Set velocity limits
- `getTwistLinear/Angular(...)` - Get velocity limits
- **Implementation**: `pnkx_local_planner` với multiple behaviors
- `nav_core::RecoveryBehavior` ✅
- `robot_nav_core::RecoveryBehavior` ✅
- `runBehavior()` - Thực thi recovery behavior
- `initialize(name, tf, global_costmap, local_costmap)` - Khởi tạo
- `costmap_2d::Costmap2DROBOT` ✅
- `robot_costmap_2d::Costmap2DROBOT` ✅
- Wrapper cho costmap với robot footprint
- Thread-safe access với mutex
@@ -290,9 +342,15 @@ Cần làm rõ:
**Plugin mechanism:** ✅
- Sử dụng `boost::dll` để dynamic loading plugins
- Factory pattern với `boost::function` và `boost::dll::import`
- Factory pattern với `boost::function` và `boost::dll::import_alias`
- `robot::PluginLoaderHelper` để tìm library path từ plugin name
- Config file YAML để specify plugin names
- Plugin interfaces: `BaseGlobalPlanner`, `BaseLocalPlanner`, `RecoveryBehavior`
- Plugin interfaces:
- `robot_nav_core::BaseGlobalPlanner` - Global planners
- `robot_nav_core::BaseLocalPlanner` - Local planners
- `robot_nav_core::RecoveryBehavior` - Recovery behaviors
- `robot_costmap_2d::Layer` - Costmap layers
- Plugin registration với `BOOST_DLL_ALIAS` macro
### 4. Cơ chế giao tiếp & đồng bộ
@@ -340,36 +398,99 @@ Cần làm rõ:
**Đã hoàn thành:** ✅
1. ✅ **Interface Layer**: `BaseNavigation` interface
2. ✅ **Implementation Layer**: `MoveBase` core logic
3. ✅ **Planning Layer**: Plugin system cho global/local planners và recovery
4. ✅ **Costmap Layer**: Global và local costmap với layers
5. ✅ **Algorithms Layer**: MKT algorithms, score algorithm, kalman
6. ✅ **API Layer**: C API wrapper cho .NET integration
7. ✅ **Supporting Libraries**: tf3, robot_time, geometry_msgs, robot_nav_2d_utils
1. ✅ **Interface Layer**:
- `move_base_core::BaseNavigation` - Abstract interface hoàn chỉnh
- `move_base_core::common.h` - Common types và utilities
2. ✅ **Implementation Layer**:
- `move_base::MoveBase` - Core implementation với state machine
- `executeCycle()` - Control loop implementation
- State management (PLANNING, CONTROLLING, CLEARING, PAUSED)
- Threading với planner thread và control loop
3. ✅ **Planning Layer - Plugin System**:
- **Global Planners** (3 implementations):
- `custom_planner` - Custom path planning với curve support
- `dock_planner` - Docking-specific planner
- `two_points_planner` - Simple two-point planner
- **Local Planners** (1 implementation):
- `pnkx_local_planner` - Main local planner với:
- `pnkx_docking_local_planner` - Docking behavior
- `pnkx_go_straight_local_planner` - Go straight behavior
- `pnkx_rotate_local_planner` - Rotate behavior
- **Recovery Behaviors**: Interface đã định nghĩa
- Plugin loading với `boost::dll` và `robot::PluginLoaderHelper`
4. ✅ **Costmap Layer**:
- `robot_costmap_2d::Costmap2DROBOT` - Global và local costmap
- **Costmap Layers** (8 implementations):
- `static_layer` - Static map layer
- `obstacle_layer` - Dynamic obstacles
- `inflation_layer` - Cost inflation
- `voxel_layer` - 3D voxel grid
- `critical_layer` - Critical zones
- `directional_layer` - Directional costs
- `preferred_layer` - Preferred paths
- `unpreferred_layer` - Unpreferred zones
- Layered costmap system với plugin support
5. ✅ **Algorithms Layer**:
- **MKT Algorithm**:
- Differential drive kinematics (go_straight, rotate, predictive)
- Bicycle model kinematics (go_straight, rotate, pure pursuit)
- **MKT Plugins**:
- `goal_checker` - Goal checking algorithms
- `standard_traj_generator` - Standard trajectory generation
- `kinematic_parameters` - Kinematics parameter management
- `xy_theta_iterator` - Trajectory iteration
- `limited_accel_generator` - Acceleration-limited trajectories
- **Score Algorithm**: Trajectory scoring và goal checking
- **Kalman Filter**: State estimation và filtering
6. ✅ **API Layer**:
- `nav_c_api` - C API wrapper cho .NET/C# P/Invoke
- Wrapper functions cho BaseNavigation methods
7. ✅ **Supporting Libraries**:
- `tf3` - Transform system (buffer_core, transforms)
- `robot_time` - Time management (Time, Duration, Timer, Rate)
- `robot_cpp` - Core utilities:
- `robot::init()` - Initialization
- `robot::NodeHandle` - YAML config loading
- `robot::PluginLoaderHelper` - Plugin discovery
- `robot_nav_2d_utils` - 2D navigation utilities (conversions, path_ops, polygons, bounds, tf_help)
- `robot_nav_2d_msgs` - 2D navigation messages
- `geometry_msgs` - Geometry message types (29 types)
- `robot_nav_msgs` - Navigation messages (24 types)
- `robot_sensor_msgs` - Sensor messages (30 types)
- `laser_geometry` - Laser scan geometry utilities
- `voxel_grid` - Voxel grid implementation
- `data_convert` - Data conversion utilities
- `nav_grid` - Navigation grid utilities
**Đang triển khai / Cần bổ sung:** ⚠️
1. ⚠️ **Data Sources Interfaces**:
- `ILocalizationSource` interface
- `IOdometrySource` interface
- `IMapProvider` interface
- Integration với Pnkx Loc, odometry sources
- `ILocalizationSource` interface - Cần định nghĩa
- `IOdometrySource` interface - Cần định nghĩa
- `IMapProvider` interface - Cần định nghĩa
- Integration với Pnkx Loc, odometry sources - Hiện tại dùng trực tiếp qua MoveBase methods
2. ⚠️ **Base Controller**:
- `IBaseController` interface
- Diff drive controller implementation
- Steer drive controller implementation
- Velocity command execution
- `IBaseController` interface - Cần định nghĩa
- Diff drive controller implementation - Cần implement
- Steer drive controller implementation - Cần implement
- Velocity command execution - Hiện tại chỉ có `setTwistLinear/Angular` trong local planner
3. ⚠️ **Control Loop**:
- Control loop trong MoveBase (executeCycle)
- State machine management hoàn chỉnh
- Threading và synchronization
3. ⚠️ **User Controller Plugin System**:
- Factory để load user controller plugins - Cần implement
- Interface cho User Controller - Cần định nghĩa
- Integration với BaseNavigation - Cần implement
4. ⚠️ **User Controller Plugin System**:
- Factory để load user controller plugins
- Integration với BaseNavigation
4. ⚠️ **Testing & Documentation**:
- Unit tests cho các modules - Một số đã có (costmap, bounds, etc.)
- Integration tests - Cần bổ sung
- Simulation environment - TODO
**Lộ trình tiếp theo:**
@@ -406,38 +527,144 @@ pnkx_nav_core/
├── src/
│ ├── Navigations/
│ │ ├── Cores/
│ │ │ ├── move_base_core/ # BaseNavigation interface
│ │ │ ├── nav_core/ # Planner interfaces
│ │ │ ├── nav_core_adapter/ # Adapter utilities
│ │ │ └── nav_core2/ # Additional nav utilities
│ │ │ ├── move_base_core/ # BaseNavigation interface ✅
│ │ │ │ ├── include/move_base_core/
│ │ │ │ │ ├── navigation.h # BaseNavigation abstract class
│ │ │ │ │ └── common.h # Common types (TFListenerPtr, etc.)
│ │ │ ├── robot_nav_core/ # Planner interfaces ✅
│ │ │ │ ├── include/robot_nav_core/
│ │ │ │ │ ├── base_global_planner.h
│ │ │ │ │ ├── base_local_planner.h
│ │ │ │ │ └── recovery_behavior.h
│ │ │ ├── robot_nav_core_adapter/ # Adapter utilities ✅
│ │ │ │ ├── include/robot_nav_core_adapter/
│ │ │ │ │ ├── global_planner_adapter.h
│ │ │ │ │ ├── local_planner_adapter.h
│ │ │ │ │ └── costmap_adapter.h
│ │ │ └── robot_nav_core2/ # Additional nav utilities ✅
│ │ │ ├── include/robot_nav_core2/
│ │ │ │ ├── global_planner.h
│ │ │ │ ├── local_planner.h
│ │ │ │ └── costmap.h
│ │ ├── Libraries/
│ │ │ ├── costmap_2d/ # Costmap system
│ │ │ ├── tf3/ # Transform system
│ │ │ ├── robot_time/ # Time management
│ │ │ ├── geometry2/ # Geometry utilities
│ │ │ └── ... # Other supporting libraries
│ │ │ ├── nav_grid/ # Navigation grid utilities ✅
│ │ │ └── (costmap, tf3, robot_time ở Libraries/)
│ │ └── Packages/
│ │ └── move_base/ # MoveBase implementation
│ │ └── move_base/ # MoveBase implementation ✅
│ │ ├── include/move_base/
│ │ │ └── move_base.h
│ │ └── src/
│ │ ├── move_base.cpp
│ │ └── move_base_main.cpp
│ │
│ ├── Algorithms/
│ │ ├── Cores/
│ │ │ └── score_algorithm/ # Trajectory scoring
│ │ └── Libraries/
│ │ ├── mkt_algorithm/ # MKT kinematics algorithms
│ │ ├── kalman/ # Kalman filtering
│ │ └── angles/ # Angle utilities
│ │ │ └── score_algorithm/ # Trajectory scoring ✅
│ │ │ ├── include/score_algorithm/
│ │ │ │ ├── score_algorithm.h
│ │ │ │ ├── goal_checker.h
│ │ │ │ └── trajectory_generator.h
│ │ ├── Libraries/
│ │ │ ├── mkt_algorithm/ # MKT kinematics algorithms ✅
│ │ │ │ ├── include/mkt_algorithm/
│ │ │ │ │ ├── diff/ # Differential drive
│ │ │ │ │ │ ├── diff_go_straight.h
│ │ │ │ │ │ ├── diff_predictive_trajectory.h
│ │ │ │ │ │ └── diff_rotate_to_goal.h
│ │ │ │ │ └── bicycle/ # Bicycle model
│ │ │ │ │ ├── bicycle.h
│ │ │ │ │ ├── go_straight.h
│ │ │ │ │ └── rotate_to_goal.h
│ │ │ ├── mkt_plugins/ # MKT plugin components ✅
│ │ │ │ ├── include/mkt_plugins/
│ │ │ │ │ ├── goal_checker.h
│ │ │ │ │ ├── standard_traj_generator.h
│ │ │ │ │ ├── kinematic_parameters.h
│ │ │ │ │ └── xy_theta_iterator.h
│ │ │ ├── mkt_msgs/ # MKT message types ✅
│ │ │ ├── kalman/ # Kalman filtering ✅
│ │ │ └── angles/ # Angle utilities ✅
│ │ └── Packages/
│ │ ├── global_planners/
│ │ │ ├── custom_planner/ # Custom global planner ✅
│ │ │ ├── dock_planner/ # Docking planner ✅
│ │ │ └── two_points_planner/ # Two points planner ✅
│ │ └── local_planners/
│ │ └── pnkx_local_planner/ # PNKX local planner ✅
│ │ ├── include/pnkx_local_planner/
│ │ │ ├── pnkx_local_planner.h
│ │ │ ├── pnkx_docking_local_planner.h
│ │ │ ├── pnkx_go_straight_local_planner.h
│ │ │ └── pnkx_rotate_local_planner.h
│ │
│ ├── Libraries/
│ │ ├── costmap_2d/ # Costmap system ✅
│ │ │ ├── include/robot_costmap_2d/
│ │ │ │ ├── costmap_2d_robot.h
│ │ │ │ ├── layered_costmap.h
│ │ │ │ └── layer.h
│ │ │ ├── plugins/ # Costmap layers ✅
│ │ │ │ ├── static_layer.cpp
│ │ │ │ ├── obstacle_layer.cpp
│ │ │ │ ├── inflation_layer.cpp
│ │ │ │ ├── voxel_layer.cpp
│ │ │ │ ├── critical_layer.cpp
│ │ │ │ ├── directional_layer.cpp
│ │ │ │ ├── preferred_layer.cpp
│ │ │ │ └── unpreferred_layer.cpp
│ │ │ └── config/ # Costmap configs
│ │ ├── tf3/ # Transform system ✅
│ │ ├── robot_time/ # Time management ✅
│ │ ├── robot_cpp/ # Core utilities ✅
│ │ │ ├── include/robot/
│ │ │ │ ├── init.h # Initialization
│ │ │ │ ├── node_handle.h # NodeHandle (YAML config)
│ │ │ │ └── plugin_loader_helper.h # Plugin loader
│ │ ├── robot_nav_2d_utils/ # 2D nav utilities ✅
│ │ ├── robot_nav_2d_msgs/ # 2D nav messages ✅
│ │ ├── geometry2/ # Geometry utilities ✅
│ │ │ ├── robot_tf3_geometry_msgs/
│ │ │ └── robot_tf3_sensor_msgs/
│ │ ├── common_msgs/ # Message types ✅
│ │ │ ├── robot_geometry_msgs/
│ │ │ ├── robot_nav_msgs/
│ │ │ ├── robot_sensor_msgs/
│ │ │ ├── robot_std_msgs/
│ │ │ ├── robot_protocol_msgs/
│ │ │ └── robot_visualization_msgs/
│ │ ├── laser_geometry/ # Laser geometry ✅
│ │ ├── voxel_grid/ # Voxel grid ✅
│ │ ├── data_convert/ # Data conversion ✅
│ │ └── xmlrpcpp/ # XML-RPC utilities ✅
│ │
│ └── APIs/
│ └── c_api/ # C API wrapper
├── build/ # Build artifacts
└── doc/ # Documentation
│ └── c_api/ # C API wrapper ✅
│ ├── include/nav_c_api.h
│ └── src/nav_c_api.cpp
│
├── build/ # Build artifacts
├── config/ # Configuration files
├── examples/ # Example code
└── doc/ # Documentation
├── architecture_discussion.md
├── implementation_plan.md
└── folders.md
```
## Ghi chú
- ✅ Kiến trúc cốt lõi đã được triển khai với plugin system linh hoạt
- ✅ **3 Global Planners** đã triển khai: custom_planner, dock_planner, two_points_planner
- ✅ **1 Local Planner** đã triển khai: pnkx_local_planner với 4 behaviors (position, docking, go_straight, rotate)
- ✅ **8 Costmap Layers** đã triển khai: static, obstacle, inflation, voxel, critical, directional, preferred, unpreferred
- ✅ **MKT Algorithms** hỗ trợ cả differential drive và bicycle model
- ✅ **Plugin System** hoàn chỉnh với `boost::dll` và `robot::PluginLoaderHelper`
- ⚠️ Cần bổ sung data sources interfaces và base controller
- 🔄 Kiến trúc được thiết kế để dễ dàng thay đổi thuật toán và mô hình kinematics thông qua plugin system
- 📦 Tất cả components được build bằng CMake, không phụ thuộc ROS
- 📦 Tất cả components được build bằng CMake, hỗ trợ cả Catkin và Standalone CMake
- 🔌 Plugin system sử dụng `boost::dll` cho dynamic loading
- 🎯 MoveBase đã có control loop (`executeCycle`) và state machine hoàn chỉnh
- 📚 Có đầy đủ message types: geometry_msgs (29), nav_msgs (24), sensor_msgs (30), std_msgs (32)

488
doc/cpp_host_guide.md Normal file
View File

@@ -0,0 +1,488 @@
# Nhúng nav core vào một chương trình C++ thuần
Tài liệu này dành cho người viết host bằng **C++**. Bản hướng dẫn cho C#/.NET nằm ở
[`src/APIs/c_api/NAV_C_API_2_GUIDE.md`](../src/APIs/c_api/NAV_C_API_2_GUIDE.md) và
[`examples/`](../examples) — đó là lớp `extern "C"` bọc ngoài, không phải đường đi của C++.
Host C++ nói chuyện **thẳng** với `robot::move_base_core::BaseNavigation`, không qua lớp C.
---
## 1. Hợp đồng duy nhất: `BaseNavigation`
Toàn bộ nav core lộ ra qua đúng một interface, ở
`src/Navigations/Cores/move_base_core/include/move_base_core/navigation.h`.
**Bên trong nav core KHÔNG có ROS.** Dữ liệu chỉ vào được qua các hàm của interface này. Không có
topic, không có node, không có param server. Host là thứ duy nhất biết dữ liệu từ đâu tới.
Hiện có ba host dùng chung hợp đồng đó:
| host | ngôn ngữ | vị trí |
|---|---|---|
| `amr_control` | C++ | `AMR_T800/Controllers/Packages/amr_control` — cầu nối sang ROS |
| `libnavigation_c_api.so` | C (cho .NET) | `src/APIs/c_api` |
| chương trình của bạn | C++ | tài liệu này |
Sửa `navigation.h` là **cả ba host phải build lại đồng bộ**: nó là ranh giới ABI đi qua
`boost::dll`, và `dlsym` + `reinterpret_cast` không bắt được sai khác nào lúc biên dịch.
---
## 2. Nạp thư viện
Nav core được nạp lúc chạy bằng `boost::dll`, không link tĩnh. Symbol cần tìm tên là `MoveBase`.
```cpp
#include <boost/dll/import.hpp>
#include <robot/plugin_loader_helper.h>
#include <move_base_core/navigation.h>
robot::PluginLoaderHelper loader;
std::string so_path = loader.findLibraryPath("MoveBase"); // tra ra libmove_base2.so
auto factory = boost::dll::import_alias<robot::move_base_core::BaseNavigation::Ptr()>(
so_path, "MoveBase", boost::dll::load_mode::append_decorations);
robot::move_base_core::BaseNavigation::Ptr nav = factory();
```
> **Giữ `factory` sống lâu bằng `nav`.** `import_alias` trả về một đối tượng giữ tham chiếu tới
> `.so`. Để nó hết phạm vi trong khi `nav` còn dùng là thư viện bị unload dưới chân con trỏ —
> segfault ở chỗ không liên quan gì tới lỗi thật.
`findLibraryPath` tra theo thứ tự: `PNKX_NAV_CORE_LIBRARY_PATH`, rồi `LD_LIBRARY_PATH`, rồi các
đường tương đối so với executable. Không tìm thấy thì gần như luôn là do thiếu biến môi trường
hoặc `.so` không nằm trong thư mục build — xem mục 6.
---
## 3. Khởi tạo — thứ tự có ràng buộc
```cpp
// 3.1 TF: host tự dựng và tự nuôi. Nav core KHÔNG tự nghe TF từ đâu cả.
auto tf = std::make_shared<tf3::BufferCore>();
// 3.2 Footprint đặt TRƯỚC initialize().
// Footprint là thuộc tính TĨNH của robot, không phải dữ liệu của một mission. Đặt sau khi
// runtime đã sẵn sàng thì local planner phải dựng lại chỉ để thay cache footprint.
std::vector<robot_geometry_msgs::Point> footprint = { /* >= 3 diem, theo chieu kim dong ho */ };
nav->setRobotFootprint(footprint);
// 3.3 initialize() nạp config, dựng costmap, nạp mọi plugin.
nav->initialize(tf);
// 3.4 CHỜ tới khi thật sự sẵn sàng. initialize() trả về ngay, nhưng runtime dựng xong ở luồng
// khác. Gửi goal trước lúc này là bị từ chối im lặng.
while (!nav->getFeedback()->is_ready) {
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
```
`is_ready` chỉ thành `false` khi khởi tạo hỏng; `feed_back_str` khi đó nói hỏng ở đâu — đọc nó
trước khi đi tìm nguyên nhân ở chỗ khác.
---
## 4. Đẩy dữ liệu vào
Host phải tự bơm. Nav core không đi lấy.
```cpp
nav->addStaticMap("/map", occupancy_grid);
nav->addLaserScan("/f_scan", scan);
nav->addPointCloud2("/camera/depth/points", cloud);
nav->addOdometry("/odom", odom);
// Luu y chu ky: depth camera nhan CONST POINTER, khac moi ham add* con lai von nhan gia tri.
// Anh depth nang, nen no duoc chia se chu khong sao chep — dung sua `data` sau khi da day vao.
robot_sensor_msgs::DepthCameraData::ConstPtr data = /* ... */;
nav->addDepthCameraData("/camera/depth/data", data);
```
Tên chuỗi đầu tiên là **khoá**, và nó phải khớp `topic` khai trong config costmap
(`observation_sources`) cũng như trong `sensor_store_params.yaml`. Sai một chữ là dữ liệu vào kho
nhưng không ai đọc — costmap trống mà không có lỗi nào.
Cùng lúc đó, TF phải được nuôi liên tục:
```cpp
tf->setTransform(transform_stamped, "authority", /*is_static=*/false);
```
### Đồng hồ: đây là chỗ dễ sai nhất
**Nav core chạy theo wall clock** (`robot::Time::now()`). Mọi `header.stamp` bạn đưa vào phải cùng
hệ đó. Nếu nguồn dữ liệu của bạn dùng đồng hồ khác — sim time, timestamp của thiết bị, giờ trong
file bag — thì phải **quy đổi trước khi đưa vào**, không phải sau.
Sai đồng hồ không báo lỗi. Nó hiện ra thành `age ... [STALE]`, thành `extrapolation into the
future` khi tra TF, hoặc thành costmap không bao giờ cập nhật — ba triệu chứng trông chẳng liên
quan gì tới nhau.
---
## 5. Ra lệnh và đọc kết quả
### Gửi đích
```cpp
robot_geometry_msgs::PoseStamped goal;
goal.header.frame_id = "map";
goal.header.stamp = robot::Time::now();
goal.pose.position.x = 10.0;
goal.pose.position.y = 8.3;
goal.pose.orientation = /* quaternion */;
nav->moveTo(goal, /*xy_goal_tolerance=*/0.05, /*yaw_goal_tolerance=*/0.05);
```
Dung sai để `0.0` nghĩa là **dùng giá trị trong config**, không phải "dung sai bằng không".
Bản nạp chồng thứ hai nhận thêm một `robot_protocol_msgs::Order` — dùng khi đích đến từ một order
VDA5050 và bạn muốn mission layer cắt nó thành từng chặng.
### Điều khiển vòng đời
```cpp
nav->pause(); // giu nguyen dich, dung banh
nav->resume();
nav->cancel(); // bo dich
```
### Lấy lệnh vận tốc ra
Đây là thứ bạn gửi xuống bánh xe:
```cpp
robot_nav_2d_msgs::Twist2DStamped twist = nav->getTwist();
```
> **`getTwist()` là LỆNH đang phát, không phải vận tốc đo được.** Đừng đưa odometry ngược vào đây:
> làm vậy tạo vòng lặp dương, robot giữ nguyên tốc độ hiện tại vô hạn.
>
> **Phải kiểm `twist.header.stamp` trước khi dùng.** Nav core cố ý *đóng băng* stamp khi nó không
> còn đang điều khiển. Host phải bỏ lệnh quá hạn, nếu không robot chạy tiếp bằng lệnh cuối cùng
> sau khi mission đã kết thúc:
>
> ```cpp
> if (twist.header.stamp < robot::Time::now() - robot::Duration(0.10)) {
> return; // lenh cu — khong phat
> }
> ```
>
> Cửa sổ nên bằng **khoảng hai chu kỳ** control loop. Đặt bằng đúng một chu kỳ là điều kiện tranh
> chấp: chỉ cần rung nhẹ là lệnh bị coi là quá hạn và robot đi giật cục.
### Trạng thái, pose, plan, costmap
```cpp
robot::move_base_core::NavFeedback* fb = nav->getFeedback();
fb->navigation_state; // PLANNING / CONTROLLING / SUCCEEDED / ABORTED / PAUSED / ...
fb->feed_back_str; // ly do, dang chuoi nguoi doc duoc
fb->current_pose;
robot_geometry_msgs::PoseStamped pose;
nav->getRobotPose(pose);
auto global = nav->getGlobalData(); // plan + costmap
auto local = nav->getLocalData();
```
`getGlobalData()` / `getLocalData()` **không phải getter thuần** — chúng làm việc thật bên trong
(điền plan, chuyển costmap). Gọi trong vòng lặp nhanh là tự tạo tải; chỉ gọi ở nhịp bạn thực sự
cần vẽ.
### `setTwistLinear` / `setTwistAngular`
Hai hàm này đặt **trần vận tốc** cho lớp trọng tài, không phải ra lệnh chạy. Dùng để hạ tốc theo
ngữ cảnh (đang mang hàng, vào khu vực hẹp), không phải để lái.
---
## 6. Môi trường lúc chạy
Nav core đọc config **thẳng từ đĩa**, không qua param server nào:
| biến | dùng để | bắt buộc |
|---|---|---|
| `PNKX_NAV_CORE_CONFIG_DIR` | thư mục chứa `*.yaml` | có, nếu không nằm ở đường mặc định |
| `PNKX_NAV_CORE_LIBRARY_PATH` | nơi tra `.so` plugin | nên có |
| `LD_LIBRARY_PATH` | đường dự phòng cho cả hai việc trên | có |
```bash
export PNKX_NAV_CORE_CONFIG_DIR=/duong/dan/pnkx_nav_core/config/runtime
export PNKX_NAV_CORE_LIBRARY_PATH=/duong/dan/build
export LD_LIBRARY_PATH=/duong/dan/build:$LD_LIBRARY_PATH
```
`tf3` **không** do workspace này build — nó cài sẵn ở `/usr/local/lib/libtf3.so`.
### Khi plugin không nạp được
Gần như luôn là một trong ba:
1. Thiếu hoặc sai khoá `library_path` trong YAML của plugin đó.
2. File `.so` không nằm trong thư mục mà `PluginLoaderHelper` tra.
3. Khai `library_path` dạng đường dẫn (`./libplugins.so`) thay vì tên trần (`libplugins`). Dạng
tên trần có nhiều đường dự phòng; dạng đường dẫn **chỉ** tra được qua
`PNKX_NAV_CORE_LIBRARY_PATH`.
---
## 7. Khung tối thiểu
```cpp
#include <boost/dll/import.hpp>
#include <move_base_core/navigation.h>
#include <robot/plugin_loader_helper.h>
#include <tf3/buffer_core.h>
#include <chrono>
#include <thread>
int main()
{
auto tf = std::make_shared<tf3::BufferCore>();
robot::PluginLoaderHelper loader;
auto factory = boost::dll::import_alias<robot::move_base_core::BaseNavigation::Ptr()>(
loader.findLibraryPath("MoveBase"), "MoveBase",
boost::dll::load_mode::append_decorations);
auto nav = factory();
nav->setRobotFootprint(footprintCuaRobot());
nav->initialize(tf);
while (!nav->getFeedback()->is_ready) {
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
nav->addStaticMap("/map", docBanDo());
nav->moveTo(dichDen(), 0.05, 0.05);
while (dangChay()) {
tf->setTransform(doOdomThanhTf(), "odom", false);
nav->addLaserScan("/f_scan", docLidar());
const auto twist = nav->getTwist();
if (!(twist.header.stamp < robot::Time::now() - robot::Duration(0.10))) {
guiXuongBanhXe(twist); // <- CHI phat khi lenh con tuoi
}
const auto state = nav->getFeedback()->navigation_state;
if (state == robot::move_base_core::State::SUCCEEDED ||
state == robot::move_base_core::State::ABORTED) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
return 0;
}
```
Vòng lặp nên chạy ở **cùng nhịp với control loop** khai trong `move_base_common_params.yaml`
(`controller_frequency`, mặc định 20 Hz). Chạy chậm hơn là lệnh liên tục quá hạn ở cửa sổ tươi.
---
## 8. Link vào chương trình của bạn
Host **không** link vào `libmove_base2.so` — nó được nạp lúc chạy. Bạn chỉ cần header của hợp đồng
và các thư viện message:
```cmake
target_link_libraries(chuong_trinh_cua_ban
PRIVATE
move_base_core
robot_cpp
robot_geometry_msgs
robot_nav_msgs
robot_nav_2d_msgs
robot_sensor_msgs
robot_protocol_msgs
${TF3_LIBRARY}
Boost::filesystem
${CMAKE_DL_LIBS}
)
```
Dựng chương trình trong chính cây này thì `add_subdirectory` của root `CMakeLists.txt` đã định
nghĩa sẵn mọi target đó — chỉ cần nêu tên, không phải khai đường include.
`robot::Time` và `robot::Duration` đến từ `robot_time` và đã được `navigation.h` kéo sẵn qua
`<robot/time.h>`; không phải include thêm.
---
## 9. Tra cứu đầy đủ — toàn bộ 40 hàm
Interface có **38 hàm thuần ảo** (bắt buộc) cộng **2 hàm ảo có thân rỗng** (tuỳ chọn override).
Các mục trên chỉ đi qua những hàm dùng hằng ngày; đây là danh sách đủ.
### 9.1 Vòng đời
| hàm | ghi chú |
|---|---|
| `void initialize(TFListenerPtr tf)` | Nạp config, dựng costmap, nạp plugin. Trả về **ngay**; chờ `is_ready`. |
| `void shutdown()` | **Ảo, thân rỗng** — không bắt buộc và có thể không làm gì. Đừng trông vào nó để dọn tài nguyên; huỷ con trỏ `nav` mới là thứ thật. |
| `~BaseNavigation()` | Ảo, thân rỗng. |
### 9.2 Footprint
| hàm | ghi chú |
|---|---|
| `void setRobotFootprint(const std::vector<Point>&)` | Đặt **trước** `initialize()`. Điểm theo chiều **ngược kim đồng hồ**, tối thiểu 3 điểm, trong hệ `base_link`. |
| `std::vector<Point> getRobotFootprint()` | Đọc lại bản nav core đang dùng — hữu ích khi nghi ngờ host khác đã ghi đè. |
Doxygen trong header có sẵn hình minh hoạ thứ tự điểm; đọc nó trước khi tự bịa thứ tự.
### 9.3 Đẩy dữ liệu vào
| hàm | ghi chú |
|---|---|
| `void addStaticMap(topic, OccupancyGrid)` | |
| `void addLaserScan(topic, LaserScan)` | |
| `void addPointCloud(topic, PointCloud)` | Dạng cũ. Cảm biến mới nên dùng `PointCloud2`. |
| `void addPointCloud2(topic, PointCloud2)` | |
| `void addDepthCameraData(topic, DepthCameraData::ConstPtr)` | **Nhận con trỏ const** — xem dưới. |
| `void addOdometry(topic, Odometry)` | |
`topic` là **KHOÁ**, không phải nhãn: phải khớp `topic` mà một costmap layer khai trong
`observation_sources`, và khớp mục trong `sensor_store_params.yaml`. Khoá không khớp gì được nhận
trong im lặng rồi không ai đọc — costmap trống mà không có lỗi ở đâu cả.
Cùng khoá đó dùng lại cho nhóm `get*` và `remove*`.
### Vì sao riêng depth camera nhận con trỏ
Bất đối xứng này **có chủ đích, không phải bỏ sót — đừng "sửa cho đều"**.
Mọi cảm biến khác đã được host giảm tải trước khi tới đây: laser scan 5.5 KB, còn depth cloud được
lọc voxel từ 3.26 MB xuống 24 KB. Đo trên sim đang chạy, sao chép **cả bốn hàm kia cộng lại** tốn
khoảng **25 µs mỗi giây** — 0.0025% của một lõi.
Ảnh depth thì **không** được giảm trước: nó vào nguyên vẹn, **398 KB**, vì `VoxelLayer` cần trọn
khung để dựng frustum xoá. Sao chép nó tốn gấp khoảng **250 lần** tổng của bốn hàm kia. Đó mới là
mức đáng đổi.
Cái giá của con trỏ là một hợp đồng khó hơn: **người gọi không được sửa `data` sau khi đã đẩy vào**.
Không gì bắt được vi phạm — không trình biên dịch, không crash — costmap chỉ đơn giản thấy thứ khác
với cái host tưởng mình đã gửi. Đáng trả ở đây; không đáng trả cho một scan 5 KB.
### 9.4 Đọc lại dữ liệu đã đẩy vào
| hàm | trả về |
|---|---|
| `OccupancyGrid getStaticMap(name)` | |
| `LaserScan getLaserScan(name)` | |
| `PointCloud getPointCloud(name)` | |
| `PointCloud2 getPointCloud2(name)` | |
| `std::map<std::string, OccupancyGrid> getAllStaticMaps()` | |
| `std::map<std::string, LaserScan> getAllLaserScans()` | |
| `std::map<std::string, PointCloud> getAllPointClouds()` | |
| `std::map<std::string, PointCloud2> getAllPointCloud2s()` | |
Nhóm này để **chẩn đoán và hiển thị**, không phải để lấy dữ liệu về xử lý tiếp. Chúng trả về
**bản sao**, và với point cloud thì bản sao đó không rẻ — gọi trong vòng lặp điều khiển là tự tạo
tải.
Công dụng thật: trả lời câu *"cái nav core đang thấy có đúng cái tôi gửi không"*, khi costmap trống
mà không có lỗi nào. Hai khả năng — chưa gửi tới, hoặc gửi sai khoá — và nhóm này phân biệt được.
Lưu ý: cái ra ở đây có thể **khác** cái bạn đưa vào, nếu bật lọc (ví dụ `laser_sor_enabled`). Đó là
có chủ đích.
### 9.5 Xoá dữ liệu
| hàm | trả về |
|---|---|
| `bool removeStaticMap(name)` | `false` nếu khoá không tồn tại |
| `bool removeLaserScan(name)` | |
| `bool removePointCloud(name)` | |
| `bool removePointCloud2(name)` | |
| `bool removeAllStaticMaps()` | |
| `bool removeAllLaserScans()` | |
| `bool removeAllPointClouds()` | |
| `bool removeAllPointCloud2s()` | |
| `bool removeAllData()` | xoá sạch mọi loại |
**Đây không phải nhóm dọn dẹp cho đẹp — nó là an toàn.** Khi một cảm biến chết hoặc mất kết nối,
host phải gọi `remove*` cho nguồn đó. Không gọi thì dữ liệu cuối cùng nằm lại trong costmap và
robot tiếp tục né một vật cản **không còn ở đó**, hoặc tệ hơn, tin rằng một vùng còn trống trong
khi cảm biến đã ngừng báo.
Nav core không tự phát hiện cảm biến chết — nó không biết cảm biến của bạn là gì. Chỉ host biết.
`removeAllData()` dùng khi đổi bản đồ hoặc khởi động lại mission, để không mang quan sát của cảnh
cũ sang cảnh mới.
### 9.6 Ra lệnh
| hàm | ghi chú |
|---|---|
| `bool moveTo(goal, xy_tol = 0.0, yaw_tol = 0.0)` | `0.0` = **dùng giá trị trong config**, không phải dung sai bằng không. |
| `bool moveTo(Order, goal, xy_tol, yaw_tol)` | Kèm order VDA5050 để mission layer cắt thành chặng. |
| `bool executeInstantActions(const std::vector<Action>&)` | Xem dưới. |
| `void pause()` / `void resume()` / `void cancel()` | Điều khiển hàng đợi. |
**`executeInstantActions`** nhận các action của **một** message `instantActions`, đúng thứ tự nhận
được. Mỗi action cần `actionType` và `actionId`.
Trả `false` nghĩa là **bị từ chối thẳng** — danh sách rỗng, thiếu định danh, hoặc mission layer
không chạy. Khi đó host **phải báo hỏng ngay**, đừng chờ một kết quả sẽ không bao giờ tới.
`cancel` / `pause` / `resume` **không** đi qua đường này: chúng lái hàng đợi chứ không phải việc
nằm trong hàng đợi, nên host gọi thẳng ba hàm riêng ở trên.
### 9.7 Trần vận tốc
| hàm | ghi chú |
|---|---|
| `bool setTwistLinear(const Vector3&)` | |
| `bool setTwistAngular(const Vector3&)` | |
Hai hàm này đặt **trần** cho lớp trọng tài, **không phải lệnh lái**. Dùng để hạ tốc theo ngữ cảnh:
đang mang hàng, vào khu vực hẹp, người ở gần.
Muốn robot chạy thì dùng `moveTo`. Gọi hai hàm này với ý "cho robot đi 0.3 m/s" là hiểu sai — nó
chỉ nói "đừng vượt quá 0.3".
### 9.8 Đọc trạng thái
| hàm | ghi chú |
|---|---|
| `Twist2DStamped getTwist()` | Lệnh đang phát. **Phải kiểm `header.stamp`** — xem mục 5. |
| `NavFeedback* getFeedback()` | Con trỏ tới trạng thái sống. Không sở hữu, đừng `delete`. |
| `bool getRobotPose(PoseStamped&)` | `false` nếu chưa tra được TF. |
| `bool getRobotPose(Pose2D&)` | Bản 2D của cùng thứ. |
| `PlannerDataOutput getGlobalData()` | plan + costmap toàn cục |
| `PlannerDataOutput getLocalData()` | plan + costmap cục bộ |
`PlannerDataOutput` gồm: `plan`, `costmap`, `costmap_update`, `is_costmap_updated`, `footprint`.
Kiểm `is_costmap_updated` trước khi vẽ lại — costmap đầy đủ nặng, `costmap_update` là phần vá.
`getGlobalData()` / `getLocalData()` **không phải getter thuần**: chúng làm việc thật bên trong
(điền plan, chuyển đổi costmap). Chỉ gọi ở nhịp bạn thực sự cần vẽ, không gọi mỗi chu kỳ điều
khiển.
`NavFeedback` gồm `navigation_state`, `feed_back_str`, `current_pose`, `goal_checked`, `is_ready`.
`State` có 14 giá trị: `PENDING`, `ACTIVE`, `PREEMPTED`, `SUCCEEDED`, `ABORTED`, `REJECTED`,
`PREEMPTING`, `RECALLING`, `RECALLED`, `LOST`, `PLANNING`, `CONTROLLING`, `CLEARING`, `PAUSED`.
Kết thúc mission thì chỉ `SUCCEEDED`, `ABORTED`, `REJECTED`, `PREEMPTED` là trạng thái **cuối**;
`PLANNING` và `CONTROLLING` là đang chạy. Coi mọi thứ khác `SUCCEEDED` là hỏng sẽ báo lỗi giả trong
lúc robot đang làm việc bình thường.
---
## 10. Những chỗ đã làm người khác mất thời gian
| triệu chứng | nguyên nhân thật |
|---|---|
| Robot đứng im, mọi lớp báo bình thường | Lệnh quá hạn ở cửa sổ tươi và bị host bỏ. Kiểm `twist.header.stamp` trước khi đi tìm ở planner. |
| `moveTo` trả `true` mà không có gì xảy ra | Gửi trước khi `is_ready`. |
| Costmap trống, không có lỗi | Khoá `addLaserScan` không khớp `observation_sources` trong config. |
| `extrapolation into the future` | Stamp khác hệ đồng hồ. Nav core chạy wall clock. |
| Sửa tham số mãi không có tác dụng | Sửa nhầm cây config. Kiểm `PNKX_NAV_CORE_CONFIG_DIR` trỏ đúng đâu. |
| Plugin "không tìm thấy" dù build xanh | Thiếu `library_path`, hoặc `.so` không nằm trong thư mục tra được. |
| Segfault ở chỗ chẳng liên quan | Đối tượng `factory` đã hết phạm vi, `.so` bị unload trong khi `nav` còn sống. |

View File

@@ -1,53 +1,99 @@
Mô tả cấu trúc:
# Cấu trúc thư mục pnkx_nav_core
├── common_msgs/
│ ├── build/
│ ├── geometry_msgs/
│ │ ├── include/
│ │ └── test/
│ ├── CMakeLists.txt
│ ├── nav_msgs/
│ │ ├── include/
│ │ └── test/
│ ├── CMakeLists.txt
│ ├── sensor_msgs/
│ │ ├── cfg/
│ │ ├── include/
│ │ └── test/
│ ├── CMakeLists.txt
│ ├── std_msgs/
│ │ ├── include/
│ │ └── CMakeLists.txt
│ └── CMakeLists.txt (root)
|
├── Navigations/
│ ├── Cores/
│ │ └── move_base_core/
│ │ ├── build/
│ │ ├── example/
│ │ ├── include/
│ │ ├── .gitignore
│ │ ├── CMakeLists.txt
│ │ └── README.md
Mô tả cấu trúc thư mục thực tế của dự án:
```
pnkx_nav_core/
├── src/
│ ├── Navigations/
│ │ ├── Cores/
│ │ │ ├── move_base_core/ # BaseNavigation interface
│ │ │ ├── robot_nav_core/ # Planner interfaces (BaseGlobalPlanner, BaseLocalPlanner, RecoveryBehavior)
│ │ │ ├── robot_nav_core_adapter/ # Adapter utilities (global_planner_adapter, local_planner_adapter, costmap_adapter)
│ │ │ └── robot_nav_core2/ # Additional nav utilities (global_planner, local_planner, costmap)
│ │ ├── Libraries/
│ │ │ └── nav_grid/ # Navigation grid utilities
│ │ └── Packages/
│ │ └── move_base/ # MoveBase implementation
│ │
│ ├── Algorithms/
│ │ ├── Cores/
│ │ │ └── score_algorithm/ # Trajectory scoring và goal checking
│ │ ├── Libraries/
│ │ │ ├── mkt_algorithm/ # MKT kinematics (diff drive & bicycle)
│ │ │ ├── mkt_plugins/ # MKT plugin components
│ │ │ ├── mkt_msgs/ # MKT message types
│ │ │ ├── kalman/ # Kalman filtering
│ │ │ └── angles/ # Angle utilities
│ │ └── Packages/
│ │ ├── global_planners/
│ │ │ ├── custom_planner/ # Custom global planner
│ │ │ ├── dock_planner/ # Docking planner
│ │ │ └── two_points_planner/ # Two points planner
│ │ └── local_planners/
│ │ └── pnkx_local_planner/ # PNKX local planner
│ │
│ ├── Libraries/
│ │ ├── geometry_msgs/
│ │ │ ├── build/
│ │ │ ├── include/
│ │ │ └── CMakeLists.txt
│ │ └── libtf2/
│ │ ├── .vscode/
│ │ ├── include/
│ │ ├── samples/
│ │ ├── src/
│ │ ├── .gitignore
│ │ ├── DEBIAN_PACKAGING.md
│ │ ├── libtf2_2.0.0_amd64.deb
│ │ ├── Makefile
│ │ └── README.md
│ ├── Packages/
│ │ └── move_base/
│ │ ├── build/
│ │ ├── include/
│ │ ├── src/
│ │ └── CMakeLists.txt
│ └── CMakeLists.txt (root)
│ │ ├── costmap_2d/ # Costmap system với 8 layers
│ │ ├── tf3/ # Transform system
│ │ ├── robot_time/ # Time management
│ │ ├── robot_cpp/ # Core utilities (init, NodeHandle, PluginLoaderHelper)
│ │ ├── robot_nav_2d_utils/ # 2D navigation utilities
│ │ ├── robot_nav_2d_msgs/ # 2D navigation messages
│ │ ├── geometry2/ # Geometry utilities (tf3_geometry_msgs, tf3_sensor_msgs)
│ │ ├── common_msgs/ # Message types
│ │ │ ├── robot_geometry_msgs/ # Geometry messages (29 types)
│ │ │ ├── robot_nav_msgs/ # Navigation messages (24 types)
│ │ │ ├── robot_sensor_msgs/ # Sensor messages (30 types)
│ │ │ ├── robot_std_msgs/ # Standard messages (32 types)
│ │ │ ├── robot_protocol_msgs/ # Protocol messages
│ │ │ ├── robot_visualization_msgs/ # Visualization messages
│ │ │ └── utils/ # Message utilities
│ │ ├── laser_geometry/ # Laser geometry utilities
│ │ ├── voxel_grid/ # Voxel grid
│ │ ├── data_convert/ # Data conversion
│ │ └── xmlrpcpp/ # XML-RPC utilities
│ │
│ └── APIs/
│ └── c_api/ # C API wrapper cho .NET/C#
│
├── build/ # Build artifacts
├── config/ # Configuration files
├── examples/ # Example code
└── doc/ # Documentation
├── architecture_discussion.md
├── implementation_plan.md
├── folders.md
└── readme.md
```
## Chi tiết các thư mục chính
### Navigations/
- **Cores/**: Interfaces và core utilities
- `move_base_core`: BaseNavigation interface
- `robot_nav_core`: Planner interfaces
- `robot_nav_core_adapter`: Adapter layer
- `robot_nav_core2`: Additional utilities
- **Libraries/**: Navigation libraries
- `nav_grid`: Grid utilities
- **Packages/**: Implementations
- `move_base`: MoveBase implementation
### Algorithms/
- **Cores/**: Core algorithms
- `score_algorithm`: Trajectory scoring
- **Libraries/**: Algorithm libraries
- `mkt_algorithm`: Kinematics algorithms
- `mkt_plugins`: Plugin components
- `kalman`: Filtering
- **Packages/**: Algorithm implementations
- `global_planners/`: 3 planners
- `local_planners/`: 1 planner với multiple behaviors
### Libraries/
- **costmap_2d/**: Costmap system với 8 layers
- **tf3/**: Transform system
- **robot_cpp/**: Core utilities (init, NodeHandle, PluginLoaderHelper)
- **common_msgs/**: Message type definitions
- Các utilities khác: time, geometry, sensors, etc.

View File

@@ -15,7 +15,7 @@
- Plugin system với `boost::dll` để load dynamic plugins
3. **Costmap System:**
- `costmap_2d::Costmap2DROBOT` - Global và local costmap
- `robot_costmap_2d::Costmap2DROBOT` - Global và local costmap
- Costmap layers (static, obstacle, inflation, etc.)
4. **Supporting Libraries:**
@@ -56,8 +56,8 @@
**File:** `src/Navigations/Cores/move_base_core/include/move_base_core/odometry_source.h`
```cpp
class IOdometrySource {
virtual geometry_msgs::PoseStamped getCurrentPose() = 0;
virtual geometry_msgs::Twist getCurrentVelocity() = 0;
virtual robot_geometry_msgs::PoseStamped getCurrentPose() = 0;
virtual robot_geometry_msgs::Twist getCurrentVelocity() = 0;
virtual bool isAvailable() = 0;
};
```
@@ -66,7 +66,7 @@ class IOdometrySource {
**File:** `src/Navigations/Cores/move_base_core/include/move_base_core/localization_source.h`
```cpp
class ILocalizationSource {
virtual geometry_msgs::PoseStamped getRobotPose() = 0;
virtual robot_geometry_msgs::PoseStamped getRobotPose() = 0;
virtual std::string getGlobalFrame() = 0;
virtual bool isLocalized() = 0;
};
@@ -76,7 +76,7 @@ class ILocalizationSource {
**File:** `src/Navigations/Cores/move_base_core/include/move_base_core/map_provider.h`
```cpp
class IMapProvider {
virtual nav_msgs::OccupancyGrid getMap() = 0;
virtual robot_nav_msgs::OccupancyGrid getMap() = 0;
virtual bool isMapAvailable() = 0;
};
```
@@ -85,7 +85,7 @@ class IMapProvider {
**File:** `src/Navigations/Cores/move_base_core/include/move_base_core/sensor_source.h`
```cpp
class ISensorSource {
virtual sensor_msgs::LaserScan getLatestScan() = 0;
virtual robot_sensor_msgs::LaserScan getLatestScan() = 0;
virtual bool hasNewData() = 0;
};
```
@@ -96,9 +96,9 @@ class ISensorSource {
**File:** `src/Navigations/Cores/move_base_core/include/move_base_core/base_controller.h`
```cpp
class IBaseController {
virtual bool setVelocity(const geometry_msgs::Twist& cmd_vel) = 0;
virtual bool setVelocity(const robot_geometry_msgs::Twist& cmd_vel) = 0;
virtual bool stop() = 0;
virtual geometry_msgs::Twist getCurrentVelocity() = 0;
virtual robot_geometry_msgs::Twist getCurrentVelocity() = 0;
};
```
@@ -120,7 +120,7 @@ class IBaseController {
**File:** `src/Navigations/Cores/move_base_core/include/move_base_core/user_controller.h`
```cpp
class IUserController {
virtual void onGoalReceived(const geometry_msgs::PoseStamped& goal) = 0;
virtual void onGoalReceived(const robot_geometry_msgs::PoseStamped& goal) = 0;
virtual void onNavigationStateChanged(move_base_core::State state) = 0;
virtual void onFeedback(const NavFeedback& feedback) = 0;
};

View File

@@ -1,360 +0,0 @@
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace NavigationExample
{
/// <summary>
/// C# P/Invoke wrapper for Navigation C API
/// </summary>
public class NavigationAPI
{
private const string DllName = "libnav_c_api.so"; // Linux
// For Windows: "nav_c_api.dll"
// For macOS: "libnav_c_api.dylib"
// ============================================================================
// Enums
// ============================================================================
public enum NavigationState
{
Pending = 0,
Active = 1,
Preempted = 2,
Succeeded = 3,
Aborted = 4,
Rejected = 5,
Preempting = 6,
Recalling = 7,
Recalled = 8,
Lost = 9,
Planning = 10,
Controlling = 11,
Clearing = 12,
Paused = 13
}
// ============================================================================
// Structures
// ============================================================================
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
public double x;
public double y;
public double z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Pose2D
{
public double x;
public double y;
public double theta;
}
[StructLayout(LayoutKind.Sequential)]
public struct Quaternion
{
public double x;
public double y;
public double z;
public double w;
}
[StructLayout(LayoutKind.Sequential)]
public struct Position
{
public double x;
public double y;
public double z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Pose
{
public Position position;
public Quaternion orientation;
}
[StructLayout(LayoutKind.Sequential)]
public struct Header
{
public uint seq;
public long sec;
public uint nsec;
public IntPtr frame_id; // char*
}
[StructLayout(LayoutKind.Sequential)]
public struct PoseStamped
{
public Header header;
public Pose pose;
}
[StructLayout(LayoutKind.Sequential)]
public struct Vector3
{
public double x;
public double y;
public double z;
}
[StructLayout(LayoutKind.Sequential)]
public struct NavFeedback
{
public NavigationState navigation_state;
public IntPtr feed_back_str; // char*
public Pose2D current_pose;
[MarshalAs(UnmanagedType.I1)]
public bool goal_checked;
[MarshalAs(UnmanagedType.I1)]
public bool is_ready;
}
// ============================================================================
// String Management
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void nav_c_api_free_string(IntPtr str);
// ============================================================================
// State Conversion
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr navigation_state_to_string(NavigationState state);
// ============================================================================
// Helper Functions
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_offset_goal_2d(
double pose_x, double pose_y, double pose_theta,
string frame_id, double offset_distance,
ref PoseStamped out_goal);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_offset_goal_stamped(
ref PoseStamped in_pose, double offset_distance,
ref PoseStamped out_goal);
// ============================================================================
// Navigation Handle Management
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr navigation_create();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void navigation_destroy(IntPtr handle);
// ============================================================================
// TF Listener Management
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr tf_listener_create();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void tf_listener_destroy(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf_listener_set_static_transform(
IntPtr tf_handle,
string parent_frame,
string child_frame,
double x, double y, double z,
double qx, double qy, double qz, double qw);
// ============================================================================
// Navigation Interface Methods
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_initialize(IntPtr handle, IntPtr tf_handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_set_robot_footprint(
IntPtr handle, Point[] points, UIntPtr point_count);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_move_to(
IntPtr handle, ref PoseStamped goal,
double xy_goal_tolerance, double yaw_goal_tolerance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_dock_to(
IntPtr handle, string marker, ref PoseStamped goal,
double xy_goal_tolerance, double yaw_goal_tolerance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_move_straight_to(
IntPtr handle, ref PoseStamped goal, double xy_goal_tolerance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_rotate_to(
IntPtr handle, ref PoseStamped goal, double yaw_goal_tolerance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void navigation_pause(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void navigation_resume(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void navigation_cancel(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_set_twist_linear(
IntPtr handle, double linear_x, double linear_y, double linear_z);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_set_twist_angular(
IntPtr handle, double angular_x, double angular_y, double angular_z);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_robot_pose_stamped(
IntPtr handle, ref PoseStamped out_pose);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_robot_pose_2d(
IntPtr handle, ref Pose2D out_pose);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_feedback(
IntPtr handle, ref NavFeedback out_feedback);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void navigation_free_feedback(ref NavFeedback feedback);
// ============================================================================
// Helper Methods for String Conversion
// ============================================================================
public static string MarshalString(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return string.Empty;
return Marshal.PtrToStringAnsi(ptr);
}
}
// ============================================================================
// Example Usage
// ============================================================================
class Program
{
// Helper method để hiển thị file và line number tự động
static void LogError(string message,
[CallerFilePath] string filePath = "",
[CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string memberName = "")
{
// Lấy tên file từ đường dẫn đầy đủ
string fileName = System.IO.Path.GetFileName(filePath);
Console.WriteLine($"[{fileName}:{lineNumber}] {memberName}: {message}");
}
static void Main(string[] args)
{
// Create TF listener
IntPtr tfHandle = NavigationAPI.tf_listener_create();
if (tfHandle == IntPtr.Zero)
{
LogError("Failed to create TF listener");
return;
}
// Inject a static TF so costmap can immediately canTransform(map <-> base_link).
// If you already publish TF from localization/odometry, you can remove this call.
if (!NavigationAPI.tf_listener_set_static_transform(tfHandle, "map", "odom",
0, 0, 0,
0, 0, 0, 1))
{
LogError("Failed to inject static TF map -> odom");
NavigationAPI.tf_listener_destroy(tfHandle);
return;
}
if (!NavigationAPI.tf_listener_set_static_transform(tfHandle, "odom", "base_footprint",
0, 0, 0,
0, 0, 0, 1))
{
LogError("Failed to inject static TF map -> base_link");
NavigationAPI.tf_listener_destroy(tfHandle);
return;
}
if (!NavigationAPI.tf_listener_set_static_transform(tfHandle, "base_footprint", "base_link",
0, 0, 0,
0, 0, 0, 1))
{
LogError("Failed to inject static TF map -> base_link");
NavigationAPI.tf_listener_destroy(tfHandle);
return;
}
// Create navigation instance
IntPtr navHandle = NavigationAPI.navigation_create();
if (navHandle == IntPtr.Zero)
{
LogError("Failed to create navigation instance");
NavigationAPI.tf_listener_destroy(tfHandle);
return;
}
// Initialize navigation
if (!NavigationAPI.navigation_initialize(navHandle, tfHandle))
{
LogError("Failed to initialize navigation");
NavigationAPI.navigation_destroy(navHandle);
NavigationAPI.tf_listener_destroy(tfHandle);
return;
}
// Set robot footprint
NavigationAPI.Point[] footprint = new NavigationAPI.Point[]
{
new NavigationAPI.Point { x = 0.3, y = -0.2, z = 0.0 },
new NavigationAPI.Point { x = 0.3, y = 0.2, z = 0.0 },
new NavigationAPI.Point { x = -0.3, y = 0.2, z = 0.0 },
new NavigationAPI.Point { x = -0.3, y = -0.2, z = 0.0 }
};
NavigationAPI.navigation_set_robot_footprint(navHandle, footprint, new UIntPtr((uint)footprint.Length));
// Get robot pose
NavigationAPI.Pose2D robotPose = new NavigationAPI.Pose2D();
if (NavigationAPI.navigation_get_robot_pose_2d(navHandle, ref robotPose))
{
Console.WriteLine($"Robot pose: x={robotPose.x}, y={robotPose.y}, theta={robotPose.theta}");
}
// Get navigation feedback
NavigationAPI.NavFeedback feedback = new NavigationAPI.NavFeedback();
if (NavigationAPI.navigation_get_feedback(navHandle, ref feedback))
{
string stateStr = NavigationAPI.MarshalString(
NavigationAPI.navigation_state_to_string(feedback.navigation_state));
string feedbackStr = NavigationAPI.MarshalString(feedback.feed_back_str);
Console.WriteLine($"State: {stateStr}, Feedback: {feedbackStr}");
NavigationAPI.navigation_free_feedback(ref feedback);
}
// Cleanup
NavigationAPI.navigation_destroy(navHandle);
NavigationAPI.tf_listener_destroy(tfHandle);
}
}
}

View File

@@ -0,0 +1,287 @@
using System;
using System.Runtime.InteropServices;
using NavigationExample;
namespace NavigationExample
{
/// <summary>
/// C# P/Invoke wrapper for Navigation C API
/// </summary>
public class NavigationAPI
{
private const string DllName = "/usr/local/lib/libnav_c_api.so"; // Linux
// For Windows: "nav_c_api.dll"
// For macOS: "libnav_c_api.dylib"
// ============================================================================
// Enums
// ============================================================================
public enum NavigationState
{
Pending = 0,
Active = 1,
Preempted = 2,
Succeeded = 3,
Aborted = 4,
Rejected = 5,
Preempting = 6,
Recalling = 7,
Recalled = 8,
Lost = 9,
Planning = 10,
Controlling = 11,
Clearing = 12,
Paused = 13
}
[StructLayout(LayoutKind.Sequential)]
public struct NavFeedback
{
public NavigationState navigation_state;
public IntPtr feed_back_str; // char*; free with nav_c_api_free_string
public Pose2D current_pose;
[MarshalAs(UnmanagedType.I1)]
public bool goal_checked;
[MarshalAs(UnmanagedType.I1)]
public bool is_ready;
}
/// <summary>Planner data output (plan, costmap, footprint).</summary>
[StructLayout(LayoutKind.Sequential)]
public struct PlannerDataOutput
{
public Path2D plan;
public OccupancyGrid costmap;
public OccupancyGridUpdate costmap_update;
[MarshalAs(UnmanagedType.I1)]
public bool is_costmap_updated;
public PolygonStamped footprint;
}
[StructLayout(LayoutKind.Sequential)]
public struct NavigationHandle
{
public IntPtr ptr;
}
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern Header header_create(string frame_id);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern Header header_set_data(
uint seq,
uint sec,
uint nsec,
string frame_id);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern Time time_create();
/// <summary>Free a string allocated by the API (strdup).</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void nav_c_api_free_string(IntPtr str);
/// <summary>Convert NavigationState to string; caller must free with nav_c_api_free_string.</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr navigation_state_to_string(NavigationState state);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_feedback(NavigationHandle handle, ref NavFeedback out_feedback);
/// <summary>Helper: copy unmanaged char* to managed string; does not free the pointer.</summary>
public static string MarshalString(IntPtr p)
{
if (p == IntPtr.Zero) return string.Empty;
return Marshal.PtrToStringAnsi(p) ?? string.Empty;
}
/// <summary>Free strings inside NavFeedback (feed_back_str). Call after navigation_get_feedback when done.</summary>
public static void navigation_free_feedback(ref NavFeedback feedback)
{
if (feedback.feed_back_str != IntPtr.Zero)
{
nav_c_api_free_string(feedback.feed_back_str);
feedback.feed_back_str = IntPtr.Zero;
}
}
// ============================================================================
// Navigation Handle Management
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern NavigationHandle navigation_create();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void navigation_destroy(NavigationHandle handle);
/// <summary>Initialize navigation using an existing tf3 buffer (from libtf3). Caller owns the buffer and must call tf3_buffer_destroy after navigation_destroy.</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_initialize(NavigationHandle handle, IntPtr tf3_buffer);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_set_robot_footprint(NavigationHandle handle, Point[] points, UIntPtr point_count);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_robot_footprint(NavigationHandle handle, ref Point[] out_points, ref UIntPtr out_count);
/// <summary>Send a goal for the robot to navigate to (global frame).</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_move_to(NavigationHandle handle, PoseStamped goal);
/// <summary>Navigate using an Order message (graph nodes/edges). Order must be built or obtained from native side; call order_free when done if it was allocated by native.</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_move_to_order(NavigationHandle handle, Order order, PoseStamped goal);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[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);
// navigation_dock_to, navigation_dock_to_order, navigation_dock_to_nodes_edges,
// navigation_move_straight_to and navigation_rotate_to no longer exist in the native
// 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.
//
// Docking, go-straight and rotate are per-leg properties of an order now: set `profile:`
// 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_pause(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_resume(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_cancel(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_set_twist_linear(NavigationHandle handle, double linear_x, double linear_y, double linear_z);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_set_twist_angular(NavigationHandle handle, double angular_x, double angular_y, double angular_z);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_robot_pose_stamped(NavigationHandle handle, ref PoseStamped out_pose);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_robot_pose_2d(NavigationHandle handle, ref Pose2D out_pose);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_twist(NavigationHandle handle, ref Twist2DStamped out_twist);
// ============================================================================
// Navigation Data Management
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_add_laser_scan(NavigationHandle handle, string laser_scan_name, LaserScan laser_scan);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_add_odometry(NavigationHandle handle, string odometry_name, Odometry odometry);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_add_static_map(NavigationHandle handle, string map_name, OccupancyGrid occupancy_grid);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_static_map(NavigationHandle handle, string map_name, ref OccupancyGrid occupancy_grid);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_add_point_cloud(NavigationHandle handle, string point_cloud_name, PointCloud point_cloud);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_add_point_cloud2(NavigationHandle handle, string point_cloud2_name, PointCloud2 point_cloud2);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_laser_scan(NavigationHandle handle, string laser_scan_name, ref LaserScan out_scan);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_point_cloud(NavigationHandle handle, string point_cloud_name, ref PointCloud out_cloud);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_point_cloud2(NavigationHandle handle, string point_cloud2_name, ref PointCloud2 out_cloud);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_static_map(NavigationHandle handle, string map_name);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_laser_scan(NavigationHandle handle, string laser_scan_name);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_point_cloud(NavigationHandle handle, string point_cloud_name);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_point_cloud2(NavigationHandle handle, string point_cloud2_name);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_all_static_maps(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_all_laser_scans(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_all_point_clouds(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_all_point_cloud2s(NavigationHandle handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_remove_all_data(NavigationHandle handle);
/// <summary>Get all static maps. out_maps must be pre-allocated; use navigation_get_all_static_maps_count or similar to get count first if needed.</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_all_static_maps(NavigationHandle handle, [Out] NamedOccupancyGrid[] out_maps, ref UIntPtr out_count);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_all_laser_scans(NavigationHandle handle, [Out] NamedLaserScan[] out_scans, ref UIntPtr out_count);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_all_point_clouds(NavigationHandle handle, [Out] NamedPointCloud[] out_clouds, ref UIntPtr out_count);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_all_point_cloud2s(NavigationHandle handle, [Out] NamedPointCloud2[] out_clouds, ref UIntPtr out_count);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_global_data(NavigationHandle handle, ref PlannerDataOutput out_data);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_local_data(NavigationHandle handle, ref PlannerDataOutput out_data);
}
}

View File

@@ -1,10 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<TargetFramework>net10.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.7" />
</ItemGroup>
<ItemGroup>
<None Include="libnav_c_api.so">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>

View File

@@ -1,253 +1,25 @@
using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using NavigationExample;
namespace NavigationExample
{
/// <summary>
/// C# P/Invoke wrapper for Navigation C API
/// </summary>
public class NavigationAPI
/// <summary>Thông tin map đọc từ file YAML (maze.yaml).</summary>
public struct MazeMapConfig
{
private const string DllName = "libnav_c_api.so"; // Linux
// For Windows: "nav_c_api.dll"
// For macOS: "libnav_c_api.dylib"
// ============================================================================
// Enums
// ============================================================================
public enum NavigationState
{
Pending = 0,
Active = 1,
Preempted = 2,
Succeeded = 3,
Aborted = 4,
Rejected = 5,
Preempting = 6,
Recalling = 7,
Recalled = 8,
Lost = 9,
Planning = 10,
Controlling = 11,
Clearing = 12,
Paused = 13
}
// ============================================================================
// Structures
// ============================================================================
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
public double x;
public double y;
public double z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Pose2D
{
public double x;
public double y;
public double theta;
}
[StructLayout(LayoutKind.Sequential)]
public struct Quaternion
{
public double x;
public double y;
public double z;
public double w;
}
[StructLayout(LayoutKind.Sequential)]
public struct Position
{
public double x;
public double y;
public double z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Pose
{
public Position position;
public Quaternion orientation;
}
[StructLayout(LayoutKind.Sequential)]
public struct Header
{
public uint seq;
public long sec;
public uint nsec;
public IntPtr frame_id; // char*
}
[StructLayout(LayoutKind.Sequential)]
public struct PoseStamped
{
public Header header;
public Pose pose;
}
[StructLayout(LayoutKind.Sequential)]
public struct Vector3
{
public double x;
public double y;
public double z;
}
[StructLayout(LayoutKind.Sequential)]
public struct NavFeedback
{
public NavigationState navigation_state;
public IntPtr feed_back_str; // char*
public Pose2D current_pose;
[MarshalAs(UnmanagedType.I1)]
public bool goal_checked;
[MarshalAs(UnmanagedType.I1)]
public bool is_ready;
}
// ============================================================================
// String Management
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void nav_c_api_free_string(IntPtr str);
// ============================================================================
// State Conversion
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr navigation_state_to_string(NavigationState state);
// ============================================================================
// Helper Functions
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_offset_goal_2d(
double pose_x, double pose_y, double pose_theta,
string frame_id, double offset_distance,
ref PoseStamped out_goal);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_offset_goal_stamped(
ref PoseStamped in_pose, double offset_distance,
ref PoseStamped out_goal);
// ============================================================================
// Navigation Handle Management
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr navigation_create();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void navigation_destroy(IntPtr handle);
// ============================================================================
// TF Listener Management
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr tf_listener_create();
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void tf_listener_destroy(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf_listener_set_static_transform(
IntPtr tf_handle,
string parent_frame,
string child_frame,
double x, double y, double z,
double qx, double qy, double qz, double qw);
// ============================================================================
// Navigation Interface Methods
// ============================================================================
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_initialize(IntPtr handle, IntPtr tf_handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_set_robot_footprint(
IntPtr handle, Point[] points, UIntPtr point_count);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_move_to(
IntPtr handle, ref PoseStamped goal,
double xy_goal_tolerance, double yaw_goal_tolerance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_dock_to(
IntPtr handle, string marker, ref PoseStamped goal,
double xy_goal_tolerance, double yaw_goal_tolerance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_move_straight_to(
IntPtr handle, ref PoseStamped goal, double xy_goal_tolerance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_rotate_to(
IntPtr handle, ref PoseStamped goal, double yaw_goal_tolerance);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void navigation_pause(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void navigation_resume(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void navigation_cancel(IntPtr handle);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_set_twist_linear(
IntPtr handle, double linear_x, double linear_y, double linear_z);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_set_twist_angular(
IntPtr handle, double angular_x, double angular_y, double angular_z);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_robot_pose_stamped(
IntPtr handle, ref PoseStamped out_pose);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_robot_pose_2d(
IntPtr handle, ref Pose2D out_pose);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_feedback(
IntPtr handle, ref NavFeedback out_feedback);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void navigation_free_feedback(ref NavFeedback feedback);
// ============================================================================
// Helper Methods for String Conversion
// ============================================================================
public static string MarshalString(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return string.Empty;
return Marshal.PtrToStringAnsi(ptr);
}
public string ImagePath; // đường dẫn đầy đủ tới file ảnh
public float Resolution;
public double OriginX, OriginY, OriginZ;
public int Negate; // 0 hoặc 1
public double OccupiedThresh;
public double FreeThresh;
}
// ============================================================================
@@ -255,6 +27,105 @@ namespace NavigationExample
// ============================================================================
class Program
{
/// <summary>
/// Đọc file maze.yaml (image, resolution, origin, negate, occupied_thresh, free_thresh).
/// ImagePath được resolve tuyệt đối theo thư mục chứa file yaml.
/// </summary>
static bool TryLoadMazeYaml(string yamlPath, out MazeMapConfig config)
{
config = default;
if (string.IsNullOrEmpty(yamlPath) || !File.Exists(yamlPath))
return false;
string dir = Path.GetDirectoryName(Path.GetFullPath(yamlPath)) ?? "";
try
{
string[] lines = File.ReadAllLines(yamlPath);
foreach (string line in lines)
{
string trimmed = line.Trim();
if (trimmed.Length == 0 || trimmed.StartsWith("#")) continue;
int colon = trimmed.IndexOf(':');
if (colon <= 0) continue;
string key = trimmed.Substring(0, colon).Trim();
string value = trimmed.Substring(colon + 1).Trim();
if (key == "image")
config.ImagePath = Path.Combine(dir, value);
else if (key == "resolution" && float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out float res))
config.Resolution = res;
else if (key == "origin")
{
var m = Regex.Match(value, @"\[\s*([-\d.]+\s*),\s*([-\d.]+\s*),\s*([-\d.]+)\s*\]");
if (m.Success)
{
config.OriginX = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
config.OriginY = double.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture);
config.OriginZ = double.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture);
}
}
else if (key == "negate" && int.TryParse(value, out int neg))
config.Negate = neg;
else if (key == "occupied_thresh" && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double ot))
config.OccupiedThresh = ot;
else if (key == "free_thresh" && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double ft))
config.FreeThresh = ft;
}
return !string.IsNullOrEmpty(config.ImagePath);
}
catch
{
return false;
}
}
/// <summary>
/// Đọc file ảnh PNG và chuyển pixel sang byte[] occupancy (0=free, 100=occupied, 255=unknown).
/// Dùng negate, occupied_thresh, free_thresh từ maze.yaml nếu cung cấp.
/// </summary>
static byte[] LoadMazePixelsAsOccupancy(string imagePath, out int width, out int height,
int negate = 0, double occupiedThresh = 0.65, double freeThresh = 0.196)
{
width = 0;
height = 0;
if (string.IsNullOrEmpty(imagePath) || !File.Exists(imagePath))
{
LogError($"File not found: {imagePath}");
return null;
}
try
{
using var image = Image.Load<Rgba32>(imagePath);
int w = image.Width;
int h = image.Height;
width = w;
height = h;
byte[] data = new byte[w * h];
image.ProcessPixelRows(accessor =>
{
for (int y = 0; y < accessor.Height; y++)
{
Span<Rgba32> row = accessor.GetRowSpan(y);
for (int x = 0; x < row.Length; x++)
{
ref readonly Rgba32 p = ref row[x];
double gray = (p.R + p.G + p.B) / 255.0 / 3.0;
if (negate != 0) gray = 1.0 - gray;
byte occ;
if (gray <= freeThresh) occ = 0;
else if (gray >= occupiedThresh) occ = 100;
else occ = 255; // unknown
data[y * w + x] = occ;
}
}
});
return data;
}
catch (Exception ex)
{
LogError($"Load image failed: {ex.Message}");
return null;
}
}
// Helper method để hiển thị file và line number tự động
static void LogError(string message,
[CallerFilePath] string filePath = "",
@@ -268,93 +139,360 @@ namespace NavigationExample
static void Main(string[] args)
{
// Create TF listener
IntPtr tfHandle = NavigationAPI.tf_listener_create();
if (tfHandle == IntPtr.Zero)
// Create tf3 buffer (replaces TF listener; used for all static transforms and navigation init)
IntPtr tf3Buffer = TF3API.tf3_buffer_create(10);
if (tf3Buffer == IntPtr.Zero)
{
LogError("Failed to create TF listener");
LogError("Failed to create tf3 buffer (libtf3.so may be missing)");
return;
}
Console.WriteLine($"[NavigationExample] TF3 buffer created, handle = 0x{tf3Buffer.ToInt64():X16}");
string version = Marshal.PtrToStringAnsi(TF3API.tf3_get_version()) ?? "?";
Console.WriteLine($"[TF3] {version}");
// Inject static transforms: map -> odom -> base_footprint -> base_link
var tMapOdom = TF3API.CreateStaticTransform("map", "odom", 0, 0, 0, 0, 0, 0, 1);
var tOdomFoot = TF3API.CreateStaticTransform("odom", "base_footprint", 0, 0, 0, 0, 0, 0, 1);
var tFootLink = TF3API.CreateStaticTransform("base_footprint", "base_link", 0, 0, 0, 0, 0, 0, 1);
if (!TF3API.tf3_set_transform(tf3Buffer, ref tMapOdom, "NavigationExample", true) ||
!TF3API.tf3_set_transform(tf3Buffer, ref tOdomFoot, "NavigationExample", true) ||
!TF3API.tf3_set_transform(tf3Buffer, ref tFootLink, "NavigationExample", true))
{
LogError("Failed to set static TF");
TF3API.tf3_buffer_destroy(tf3Buffer);
return;
}
// Inject a static TF so costmap can immediately canTransform(map <-> base_link).
// If you already publish TF from localization/odometry, you can remove this call.
if (!NavigationAPI.tf_listener_set_static_transform(tfHandle, "map", "odom",
0, 0, 0,
0, 0, 0, 1))
{
LogError("Failed to inject static TF map -> odom");
NavigationAPI.tf_listener_destroy(tfHandle);
return;
}
if (!NavigationAPI.tf_listener_set_static_transform(tfHandle, "odom", "base_footprint",
0, 0, 0,
0, 0, 0, 1))
{
LogError("Failed to inject static TF map -> base_link");
NavigationAPI.tf_listener_destroy(tfHandle);
return;
}
if (!NavigationAPI.tf_listener_set_static_transform(tfHandle, "base_footprint", "base_link",
0, 0, 0,
0, 0, 0, 1))
{
LogError("Failed to inject static TF map -> base_link");
NavigationAPI.tf_listener_destroy(tfHandle);
return;
}
// Create navigation instance
IntPtr navHandle = NavigationAPI.navigation_create();
if (navHandle == IntPtr.Zero)
// Create navigation instance and initialize with tf3 buffer
NavigationAPI.NavigationHandle navHandle = NavigationAPI.navigation_create();
if (navHandle.ptr == IntPtr.Zero)
{
LogError("Failed to create navigation instance");
NavigationAPI.tf_listener_destroy(tfHandle);
TF3API.tf3_buffer_destroy(tf3Buffer);
return;
}
// Initialize navigation
if (!NavigationAPI.navigation_initialize(navHandle, tfHandle))
if (!NavigationAPI.navigation_initialize(navHandle, tf3Buffer))
{
LogError("Failed to initialize navigation");
LogError("Failed to initialize navigation with tf3 buffer");
NavigationAPI.navigation_destroy(navHandle);
NavigationAPI.tf_listener_destroy(tfHandle);
TF3API.tf3_buffer_destroy(tf3Buffer);
return;
}
while (true)
{
NavigationAPI.NavFeedback feedback = new NavigationAPI.NavFeedback();
if (NavigationAPI.navigation_get_feedback(navHandle, ref feedback))
{
if (feedback.is_ready)
{
Console.WriteLine("Navigation is ready");
break;
}
else
{
Console.WriteLine("Navigation is not ready");
}
}
System.Threading.Thread.Sleep(100);
}
Console.WriteLine("[NavigationExample] Navigation initialized successfully");
// Set robot footprint
NavigationAPI.Point[] footprint = new NavigationAPI.Point[]
Point[] footprint = new Point[]
{
new NavigationAPI.Point { x = 0.3, y = -0.2, z = 0.0 },
new NavigationAPI.Point { x = 0.3, y = 0.2, z = 0.0 },
new NavigationAPI.Point { x = -0.3, y = 0.2, z = 0.0 },
new NavigationAPI.Point { x = -0.3, y = -0.2, z = 0.0 }
new Point { x = 0.3, y = -0.2, z = 0.0 },
new Point { x = 0.3, y = 0.2, z = 0.0 },
new Point { x = -0.3, y = 0.2, z = 0.0 },
new Point { x = -0.3, y = -0.2, z = 0.0 }
};
NavigationAPI.navigation_set_robot_footprint(navHandle, footprint, new UIntPtr((uint)footprint.Length));
// Get robot pose
NavigationAPI.Pose2D robotPose = new NavigationAPI.Pose2D();
if (NavigationAPI.navigation_get_robot_pose_2d(navHandle, ref robotPose))
IntPtr fFrameId = Marshal.StringToHGlobalAnsi("fscan");
Header fscanHeader = NavigationAPI.header_create(Marshal.PtrToStringAnsi(fFrameId));
LaserScan fscanHandle;
fscanHandle.header = fscanHeader;
fscanHandle.angle_min = -1.57f;
fscanHandle.angle_max = 1.57f;
fscanHandle.angle_increment = 0.785f;
fscanHandle.time_increment = 0.0f;
fscanHandle.scan_time = 0.1f;
fscanHandle.range_min = 0.05f;
fscanHandle.range_max = 10.0f;
fscanHandle.ranges = Marshal.AllocHGlobal(sizeof(float) * 5);
Marshal.Copy(new float[] { 1.0f, 1.2f, 1.1f, 0.9f, 1.3f }, 0, fscanHandle.ranges, 5);
fscanHandle.ranges_count = new UIntPtr(5);
fscanHandle.intensities = Marshal.AllocHGlobal(sizeof(float) * 5);
Marshal.Copy(new float[] { 100.0f, 120.0f, 110.0f, 90.0f, 130.0f }, 0, fscanHandle.intensities, 5);
fscanHandle.intensities_count = new UIntPtr(5);
NavigationAPI.navigation_add_laser_scan(navHandle, "/fscan", fscanHandle);
IntPtr bFrameId = Marshal.StringToHGlobalAnsi("bscan");
Header bscanHeader = NavigationAPI.header_create(Marshal.PtrToStringAnsi(bFrameId));
LaserScan bscanHandle;
bscanHandle.header = bscanHeader;
bscanHandle.angle_min = 1.57f;
bscanHandle.angle_max = -1.57f;
bscanHandle.angle_increment = -0.785f;
bscanHandle.time_increment = 0.0f;
bscanHandle.scan_time = 0.1f;
bscanHandle.range_min = 0.05f;
bscanHandle.range_max = 10.0f;
bscanHandle.ranges = Marshal.AllocHGlobal(sizeof(float) * 5);
Marshal.Copy(new float[] { 1.0f, 1.2f, 1.1f, 0.9f, 1.3f }, 0, bscanHandle.ranges, 5);
bscanHandle.ranges_count = new UIntPtr(5);
bscanHandle.intensities = Marshal.AllocHGlobal(sizeof(float) * 5);
Marshal.Copy(new float[] { 100.0f, 120.0f, 110.0f, 90.0f, 130.0f }, 0, bscanHandle.intensities, 5);
bscanHandle.intensities_count = new UIntPtr(5);
NavigationAPI.navigation_add_laser_scan(navHandle, "/bscan", bscanHandle);
IntPtr oFrameId = Marshal.StringToHGlobalAnsi("odom");
Header odometryHeader = NavigationAPI.header_create(Marshal.PtrToStringAnsi(oFrameId));
Odometry odometryHandle = new Odometry();
odometryHandle.header = odometryHeader;
IntPtr childFrameId = Marshal.StringToHGlobalAnsi("base_footprint");
odometryHandle.child_frame_id = childFrameId;
odometryHandle.pose.pose.position.x = 0.0;
odometryHandle.pose.pose.position.y = 0.0;
odometryHandle.pose.pose.position.z = 0.0;
odometryHandle.pose.pose.orientation.x = 0.0;
odometryHandle.pose.pose.orientation.y = 0.0;
odometryHandle.pose.pose.orientation.z = 0.0;
odometryHandle.pose.pose.orientation.w = 1.0;
double[] pose_covariance = new double[36];
for(int i = 0; i < pose_covariance.Length; i++) {
pose_covariance[i] = 0.0;
}
odometryHandle.pose.covariance = Marshal.AllocHGlobal(sizeof(double) * pose_covariance.Length);
Marshal.Copy(pose_covariance, 0, odometryHandle.pose.covariance, pose_covariance.Length);
odometryHandle.pose.covariance_count = new UIntPtr((uint)pose_covariance.Length);
odometryHandle.twist.twist.linear.x = 0.0;
odometryHandle.twist.twist.linear.y = 0.0;
odometryHandle.twist.twist.linear.z = 0.0;
odometryHandle.twist.twist.angular.x = 0.0;
odometryHandle.twist.twist.angular.y = 0.0;
odometryHandle.twist.twist.angular.z = 0.0;
double[] twist_covariance = new double[36];
for(int i = 0; i < twist_covariance.Length; i++) {
twist_covariance[i] = 0.0;
}
odometryHandle.twist.covariance = Marshal.AllocHGlobal(sizeof(double) * twist_covariance.Length);
Marshal.Copy(twist_covariance, 0, odometryHandle.twist.covariance, twist_covariance.Length);
odometryHandle.twist.covariance_count = new UIntPtr((uint)twist_covariance.Length);
NavigationAPI.navigation_add_odometry(navHandle, "odometry", odometryHandle);
// Add static map: đọc maze.yaml rồi load ảnh và cập nhật mapMetaData
string mapYamlPath = "maze.yaml";
int mapWidth, mapHeight;
byte[] data;
MazeMapConfig mapConfig;
if (TryLoadMazeYaml(mapYamlPath, out mapConfig))
{
Console.WriteLine($"Robot pose: x={robotPose.x}, y={robotPose.y}, theta={robotPose.theta}");
data = LoadMazePixelsAsOccupancy(mapConfig.ImagePath, out mapWidth, out mapHeight,
mapConfig.Negate, mapConfig.OccupiedThresh, mapConfig.FreeThresh);
if (data == null)
{
mapWidth = 3;
mapHeight = 10;
data = new byte[30];
for (int i = 0; i < data.Length; i++) data[i] = 100;
Console.WriteLine("YAML loaded but image failed; using default map 3x10");
}
else
{
Console.WriteLine("Loaded map from {0}: {1}x{2}, resolution={3}, origin=({4},{5},{6})",
mapConfig.ImagePath, mapWidth, mapHeight, mapConfig.Resolution,
mapConfig.OriginX, mapConfig.OriginY, mapConfig.OriginZ);
}
}
else
{
mapWidth = 3;
mapHeight = 10;
data = new byte[30];
for (int i = 0; i < data.Length; i++) data[i] = 100;
mapConfig = default;
mapConfig.Resolution = 0.05f;
mapConfig.OriginX = mapConfig.OriginY = mapConfig.OriginZ = 0.0;
Console.WriteLine("maze.yaml not found, using default map 3x10");
}
// Get navigation feedback
NavigationAPI.NavFeedback feedback = new NavigationAPI.NavFeedback();
if (NavigationAPI.navigation_get_feedback(navHandle, ref feedback))
{
string stateStr = NavigationAPI.MarshalString(
NavigationAPI.navigation_state_to_string(feedback.navigation_state));
string feedbackStr = NavigationAPI.MarshalString(feedback.feed_back_str);
Console.WriteLine($"State: {stateStr}, Feedback: {feedbackStr}");
NavigationAPI.navigation_free_feedback(ref feedback);
}
Time mapLoadTime = NavigationAPI.time_create();
MapMetaData mapMetaData = new MapMetaData();
mapMetaData.map_load_time = mapLoadTime;
mapMetaData.resolution = mapConfig.Resolution;
mapMetaData.width = (uint)mapWidth;
mapMetaData.height = (uint)mapHeight;
mapMetaData.origin = new Pose();
mapMetaData.origin.position.x = mapConfig.OriginX;
mapMetaData.origin.position.y = mapConfig.OriginY;
mapMetaData.origin.position.z = mapConfig.OriginZ;
mapMetaData.origin.orientation.x = 0.0;
mapMetaData.origin.orientation.y = 0.0;
mapMetaData.origin.orientation.z = 0.0;
mapMetaData.origin.orientation.w = 1.0;
OccupancyGrid occupancyGrid = new OccupancyGrid();
IntPtr mapFrameId = Marshal.StringToHGlobalAnsi("map");
occupancyGrid.header = NavigationAPI.header_create(Marshal.PtrToStringAnsi(mapFrameId));
occupancyGrid.info = mapMetaData;
occupancyGrid.data = Marshal.AllocHGlobal(sizeof(byte) * data.Length);
Marshal.Copy(data, 0, occupancyGrid.data, data.Length);
occupancyGrid.data_count = new UIntPtr((uint)data.Length);
Console.WriteLine("data length: {0} {1}", data.Length, occupancyGrid.data_count);
Console.WriteLine("C# OccupancyGrid sizeof={0} data_off={1} data_count_off={2}",
Marshal.SizeOf<OccupancyGrid>(),
Marshal.OffsetOf<OccupancyGrid>("data"),
Marshal.OffsetOf<OccupancyGrid>("data_count"));
NavigationAPI.navigation_add_static_map(navHandle, "/map", occupancyGrid);
Twist2DStamped twist = new Twist2DStamped();
if (NavigationAPI.navigation_get_twist(navHandle, ref twist))
{
Console.WriteLine(
"Twist: {0}, {1}, {2}, {3}",
NavigationAPI.MarshalString(twist.header.frame_id), twist.velocity.x, twist.velocity.y, twist.velocity.theta);
}
// Build order (thao cách bom order): header + nodes + edges giống C++
Order order = new Order();
order.headerId = 1;
order.timestamp = Marshal.StringToHGlobalAnsi("2026-02-28 10:00:00");
order.version = Marshal.StringToHGlobalAnsi("1.0.0");
order.manufacturer = Marshal.StringToHGlobalAnsi("Manufacturer");
order.serialNumber = Marshal.StringToHGlobalAnsi("Serial Number");
order.orderId = Marshal.StringToHGlobalAnsi("Order ID");
order.orderUpdateId = 1;
// Nodes: giống for (auto node : order.nodes) { node_msg.nodeId = ...; node_msg.nodePosition.x = ...; order_msg.nodes.push_back(node_msg); }
int nodeCount = 1;
order.nodes = Marshal.AllocHGlobal(Marshal.SizeOf<Node>() * nodeCount);
order.nodes_count = new UIntPtr((uint)nodeCount);
Node node1 = new Node();
node1.nodeId = Marshal.StringToHGlobalAnsi("node-1");
node1.sequenceId = 0;
node1.nodeDescription = Marshal.StringToHGlobalAnsi("Goal node");
node1.released = 0;
node1.nodePosition.x = 1.0;
node1.nodePosition.y = 1.0;
node1.nodePosition.theta = 0.0;
node1.nodePosition.allowedDeviationXY = 0.1f;
node1.nodePosition.allowedDeviationTheta = 0.05f;
node1.nodePosition.mapId = Marshal.StringToHGlobalAnsi("map");
node1.nodePosition.mapDescription = Marshal.StringToHGlobalAnsi("");
node1.actions = IntPtr.Zero;
node1.actions_count = UIntPtr.Zero;
Marshal.StructureToPtr(node1, order.nodes, false);
// Edges: rỗng trong ví dụ này; nếu cần thì alloc và fill tương tự (edge_msg.edgeId, trajectory.controlPoints, ...)
order.edges = IntPtr.Zero;
order.edges_count = UIntPtr.Zero;
order.zoneSetId = Marshal.StringToHGlobalAnsi("");
PoseStamped goal = new PoseStamped();
goal.header = NavigationAPI.header_create(Marshal.PtrToStringAnsi(mapFrameId));
goal.pose.position.x = 0.01;
goal.pose.position.y = 0.01;
goal.pose.position.z = 0.0;
goal.pose.orientation.x = 0.0;
goal.pose.orientation.y = 0.0;
goal.pose.orientation.z = 0.0;
goal.pose.orientation.w = 1.0;
// Docking used to be its own call, 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_order(navHandle, order, goal);
NavigationAPI.navigation_set_twist_linear(navHandle, 0.1, 0.0, 0.0);
NavigationAPI.navigation_set_twist_angular(navHandle, 0.0, 0.0, 0.2);
while (true)
{
System.Threading.Thread.Sleep(100);
// NavigationAPI.NavFeedback feedback = new NavigationAPI.NavFeedback();
// if (NavigationAPI.navigation_get_feedback(navHandle, ref feedback))
// {
// if (feedback.navigation_state == NavigationAPI.NavigationState.Succeeded)
// {
// Console.WriteLine("Navigation is Succeeded");
// break;
// }
// }
// NavigationAPI.PlannerDataOutput globalData = new NavigationAPI.PlannerDataOutput();
// if (NavigationAPI.navigation_get_global_data(navHandle, ref globalData))
// {
// int n = (int)(uint)globalData.plan.poses_count;
// int poseSize = Marshal.SizeOf<Pose2DStamped>();
// for (int i = 0; i < n; i++)
// {
// IntPtr posePtr = IntPtr.Add(globalData.plan.poses, i * poseSize);
// Pose2DStamped p = Marshal.PtrToStructure<Pose2DStamped>(posePtr);
// double p_x = p.pose.x;
// double p_y = p.pose.y;
// double p_theta = p.pose.theta;
// Console.WriteLine("Plan: {0}, {1}, {2}", p_x, p_y, p_theta);
// }
// if(globalData.is_costmap_updated) {
// for(int i = 0; i < (int)(uint)globalData.costmap.data_count; i++) {
// byte cellValue = Marshal.ReadByte(globalData.costmap.data, i);
// Console.WriteLine("Costmap: {0} {1}", i, cellValue);
// }
// }
// else {
// Console.WriteLine("Global Costmap is not updated");
// }
// }
// NavigationAPI.PlannerDataOutput localData = new NavigationAPI.PlannerDataOutput();
// if(NavigationAPI.navigation_get_local_data(navHandle, ref localData))
// {
// int n = (int)(uint)localData.plan.poses_count;
// int poseSize = Marshal.SizeOf<Pose2DStamped>();
// for (int i = 0; i < n; i++)
// {
// IntPtr posePtr = IntPtr.Add(localData.plan.poses, i * poseSize);
// Pose2DStamped p = Marshal.PtrToStructure<Pose2DStamped>(posePtr);
// double p_x = p.pose.x;
// double p_y = p.pose.y;
// double p_theta = p.pose.theta;
// Console.WriteLine("Plan: {0}, {1}, {2}", p_x, p_y, p_theta);
// }
// if(localData.is_costmap_updated) {
// for(int i = 0; i < (int)(uint)localData.costmap.data_count; i++) {
// byte cellValue = Marshal.ReadByte(localData.costmap.data, i);
// Console.WriteLine("Costmap: {0} {1}", i, cellValue);
// }
// }
// else {
// Console.WriteLine("Local Costmap is not updated");
// }
// }
}
// Cleanup (destroy nav first, then tf3 buffer)
// Cleanup
NavigationAPI.navigation_destroy(navHandle);
NavigationAPI.tf_listener_destroy(tfHandle);
TF3API.tf3_buffer_destroy(tf3Buffer);
Console.WriteLine("Press any key to exit...");
try
{
Console.ReadKey(intercept: true);
}
catch (InvalidOperationException)
{
// Running without a real console (e.g. redirected/automated run).
}
}
}
}

View File

@@ -0,0 +1,133 @@
using System;
using System.Runtime.InteropServices;
namespace NavigationExample
{
// ============================================================================
// TF3 C API - P/Invoke wrapper for libtf3 (tf3 BufferCore)
// ============================================================================
public static class TF3API
{
private const string Tf3DllName = "/usr/local/lib/libtf3.so"; // Linux; Windows: tf3.dll, macOS: libtf3.dylib
public enum TF3_ErrorCode
{
TF3_OK = 0,
TF3_ERROR_LOOKUP = 1,
TF3_ERROR_CONNECTIVITY = 2,
TF3_ERROR_EXTRAPOLATION = 3,
TF3_ERROR_INVALID_ARGUMENT = 4,
TF3_ERROR_TIMEOUT = 5,
TF3_ERROR_UNKNOWN = 99
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct TF3_Transform
{
public long timestamp_sec;
public long timestamp_nsec;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string frame_id;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string child_frame_id;
public double translation_x;
public double translation_y;
public double translation_z;
public double rotation_x;
public double rotation_y;
public double rotation_z;
public double rotation_w;
}
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr tf3_buffer_create(int cache_time_sec);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void tf3_buffer_destroy(IntPtr buffer);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_set_transform(
IntPtr buffer,
ref TF3_Transform transform,
string authority,
[MarshalAs(UnmanagedType.I1)] bool is_static);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_lookup_transform(
IntPtr buffer,
string target_frame,
string source_frame,
long time_sec,
long time_nsec,
out TF3_Transform transform,
out TF3_ErrorCode error_code);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_lookup_transform_full(
IntPtr buffer,
string target_frame,
long target_time_sec,
long target_time_nsec,
string source_frame,
long source_time_sec,
long source_time_nsec,
string fixed_frame,
out TF3_Transform transform,
out TF3_ErrorCode error_code);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_can_transform(
IntPtr buffer,
string target_frame,
string source_frame,
long time_sec,
long time_nsec,
System.Text.StringBuilder error_msg,
int error_msg_len);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern int tf3_get_all_frame_names(IntPtr buffer, System.Text.StringBuilder frames, int frames_len);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_get_frame_tree(IntPtr buffer, System.Text.StringBuilder output, int output_len);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void tf3_clear(IntPtr buffer);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void tf3_get_current_time(out long sec, out long nsec);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_get_last_error(IntPtr buffer, System.Text.StringBuilder error_msg, int error_msg_len);
[DllImport(Tf3DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr tf3_get_version();
/// <summary>Helper: create TF3_Transform for static transform (identity or given pose).</summary>
public static TF3_Transform CreateStaticTransform(string parentFrame, string childFrame,
double tx = 0, double ty = 0, double tz = 0,
double qx = 0, double qy = 0, double qz = 0, double qw = 1)
{
var t = new TF3_Transform();
t.timestamp_sec = 0;
t.timestamp_nsec = 0;
t.frame_id = parentFrame ?? "";
t.child_frame_id = childFrame ?? "";
t.translation_x = tx;
t.translation_y = ty;
t.translation_z = tz;
t.rotation_x = qx;
t.rotation_y = qy;
t.rotation_z = qz;
t.rotation_w = qw;
return t;
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -0,0 +1,6 @@
image: maze.png
resolution: 0.05
origin: [0.0, 0.0, 0.0]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.196

View File

@@ -0,0 +1,274 @@
using System;
using System.Runtime.InteropServices;
namespace NavigationExample
{
// ============================================================================
// Structures
// ============================================================================
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
public double x;
public double y;
public double z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Pose2D
{
public double x;
public double y;
public double theta;
}
[StructLayout(LayoutKind.Sequential)]
public struct Twist2D
{
public double x;
public double y;
public double theta;
}
[StructLayout(LayoutKind.Sequential)]
public struct Quaternion
{
public double x;
public double y;
public double z;
public double w;
}
[StructLayout(LayoutKind.Sequential)]
public struct Position
{
public double x;
public double y;
public double z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Pose
{
public Point position;
public Quaternion orientation;
}
[StructLayout(LayoutKind.Sequential)]
public struct Vector3
{
public double x;
public double y;
public double z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Twist
{
public Vector3 linear;
public Vector3 angular;
}
[StructLayout(LayoutKind.Sequential)]
public struct Header
{
public uint seq;
public uint sec;
public uint nsec;
public IntPtr frame_id; // char*
}
[StructLayout(LayoutKind.Sequential)]
public struct PoseStamped
{
public Header header;
public Pose pose;
}
[StructLayout(LayoutKind.Sequential)]
public struct Twist2DStamped
{
public Header header;
public Twist2D velocity;
}
[StructLayout(LayoutKind.Sequential)]
public struct LaserScan
{
public Header header;
public float angle_min;
public float angle_max;
public float angle_increment;
public float time_increment;
public float scan_time;
public float range_min;
public float range_max;
public IntPtr ranges;
public UIntPtr ranges_count;
public IntPtr intensities;
public UIntPtr intensities_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct PointCloud
{
public Header header;
public IntPtr points;
public UIntPtr points_count;
public IntPtr channels;
public UIntPtr channels_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct PointCloud2
{
public Header header;
public uint height;
public uint width;
public IntPtr fields;
public UIntPtr fields_count;
[MarshalAs(UnmanagedType.I1)]
public bool is_bigendian;
public uint point_step;
public uint row_step;
public IntPtr data;
public UIntPtr data_count;
[MarshalAs(UnmanagedType.I1)]
public bool is_dense;
}
[StructLayout(LayoutKind.Sequential)]
public struct PoseWithCovariance
{
public Pose pose;
public IntPtr covariance;
public UIntPtr covariance_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct TwistWithCovariance {
public Twist twist;
public IntPtr covariance;
public UIntPtr covariance_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct Odometry
{
public Header header;
public IntPtr child_frame_id;
public PoseWithCovariance pose;
public TwistWithCovariance twist;
}
[StructLayout(LayoutKind.Sequential)]
public struct OccupancyGrid
{
public Header header;
public MapMetaData info;
public IntPtr data;
public UIntPtr data_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct MapMetaData
{
public Time map_load_time;
public float resolution;
public uint width;
public uint height;
public Pose origin;
}
[StructLayout(LayoutKind.Sequential)]
public struct Time
{
public uint sec;
public uint nsec;
}
[StructLayout(LayoutKind.Sequential)]
public struct Point32
{
public float x;
public float y;
public float z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Pose2DStamped
{
public Header header;
public Pose2D pose;
}
[StructLayout(LayoutKind.Sequential)]
public struct Polygon
{
public IntPtr points;
public UIntPtr points_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct PolygonStamped
{
public Header header;
public Polygon polygon;
}
[StructLayout(LayoutKind.Sequential)]
public struct OccupancyGridUpdate
{
public Header header;
public int x;
public int y;
public uint width;
public uint height;
public IntPtr data;
public UIntPtr data_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct Path2D
{
public Header header;
public IntPtr poses;
public UIntPtr poses_count;
}
/// <summary>Name (char*) + OccupancyGrid for static map list API.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct NamedOccupancyGrid
{
public IntPtr name;
public OccupancyGrid grid;
}
/// <summary>Name (char*) + LaserScan for laser scan list API.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct NamedLaserScan
{
public IntPtr name;
public LaserScan scan;
}
/// <summary>Name (char*) + PointCloud for point cloud list API.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct NamedPointCloud
{
public IntPtr name;
public PointCloud cloud;
}
/// <summary>Name (char*) + PointCloud2 for point cloud2 list API.</summary>
[StructLayout(LayoutKind.Sequential)]
public struct NamedPointCloud2
{
public IntPtr name;
public PointCloud2 cloud;
}
}

View File

@@ -0,0 +1,109 @@
using System;
using System.Runtime.InteropServices;
namespace NavigationExample
{
/// <summary>
/// C# struct layout cho protocol_msgs (robot_protocol_msgs C API).
/// Khớp với pnkx_nav_core/src/APIs/c_api/include/protocol_msgs/*.h
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct ControlPoint
{
public double x;
public double y;
public double weight;
}
[StructLayout(LayoutKind.Sequential)]
public struct ActionParameter
{
public IntPtr key; // char*
public IntPtr value; // char*
}
[StructLayout(LayoutKind.Sequential)]
public struct NodePosition
{
public double x;
public double y;
public double theta;
public float allowedDeviationXY;
public float allowedDeviationTheta;
public IntPtr mapId; // char*
public IntPtr mapDescription; // char*
}
[StructLayout(LayoutKind.Sequential)]
public struct Trajectory
{
public uint degree;
public IntPtr knotVector; // double*
public UIntPtr knotVector_count;
public IntPtr controlPoints; // ControlPoint*
public UIntPtr controlPoints_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct Action
{
public IntPtr actionType; // char*
public IntPtr actionId; // char*
public IntPtr actionDescription;// char*
public IntPtr blockingType; // char*
public IntPtr actionParameters; // ActionParameter*
public UIntPtr actionParameters_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct Node
{
public IntPtr nodeId; // char*
public int sequenceId;
public IntPtr nodeDescription; // char*
public byte released;
public NodePosition nodePosition;
public IntPtr actions; // Action*
public UIntPtr actions_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct Edge
{
public IntPtr edgeId; // char*
public int sequenceId;
public IntPtr edgeDescription; // char*
public byte released;
public IntPtr startNodeId; // char*
public IntPtr endNodeId; // char*
public double maxSpeed;
public double maxHeight;
public double minHeight;
public double orientation;
public IntPtr orientationType; // char*
public IntPtr direction; // char*
public byte rotationAllowed;
public double maxRotationSpeed;
public Trajectory trajectory;
public double length;
public IntPtr actions; // Action*
public UIntPtr actions_count;
}
[StructLayout(LayoutKind.Sequential)]
public struct Order
{
public int headerId;
public IntPtr timestamp; // char*
public IntPtr version; // char*
public IntPtr manufacturer; // char*
public IntPtr serialNumber; // char*
public IntPtr orderId; // char*
public uint orderUpdateId;
public IntPtr nodes; // Node*
public UIntPtr nodes_count;
public IntPtr edges; // Edge*
public UIntPtr edges_count;
public IntPtr zoneSetId; // char*
}
}

View File

@@ -85,9 +85,9 @@ cp ../../build/src/APIs/c_api/libnav_c_api.so .
# 5. Set library path (quan trọng!)
export LD_LIBRARY_PATH=../../build/src/APIs/c_api:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/costmap_2d:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/tf3_geometry_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/tf3_sensor_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/robot_costmap_2d:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/robot_tf3_geometry_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/robot_tf3_sensor_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Packages/move_base:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Cores/move_base_core:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/tf3:$LD_LIBRARY_PATH
@@ -118,9 +118,9 @@ ls -la ../../build/src/APIs/c_api/libnav_c_api.so
# Set LD_LIBRARY_PATH (bao gồm tất cả dependencies)
export LD_LIBRARY_PATH=../../build/src/APIs/c_api:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/costmap_2d:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/tf3_geometry_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/tf3_sensor_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/robot_costmap_2d:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/robot_tf3_geometry_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/robot_tf3_sensor_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Packages/move_base:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Cores/move_base_core:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/tf3:$LD_LIBRARY_PATH
@@ -143,6 +143,6 @@ ldd libnav_c_api.so
→ Đã được sửa! `navigation_create()` bây giờ tạo instance của `move_base::MoveBase`.
Nếu vẫn gặp lỗi, kiểm tra:
- Library đã được build đầy đủ: `make nav_c_api` trong build directory
- Dependencies đã được build: `make move_base costmap_2d`
- Dependencies đã được build: `make move_base robot_costmap_2d`
- LD_LIBRARY_PATH đã được set đúng

View File

@@ -78,9 +78,9 @@ Tạo file `NavigationExample.csproj`:
```bash
# Set LD_LIBRARY_PATH để tìm được tất cả dependencies
export LD_LIBRARY_PATH=../../build/src/APIs/c_api:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/costmap_2d:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/tf3_geometry_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/tf3_sensor_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/robot_costmap_2d:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/robot_tf3_geometry_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/geometry2/robot_tf3_sensor_msgs:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Packages/move_base:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Cores/move_base_core:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=../../build/src/Navigations/Libraries/tf3:$LD_LIBRARY_PATH

View File

@@ -27,6 +27,7 @@ echo "Building C API library..."
cd "$BUILD_DIR"
cmake ..
make
sudo make install
echo "Library built successfully!"
@@ -82,12 +83,10 @@ fi
# Luôn copy source code mới nhất (cập nhật file nếu đã có)
cd "$EXAMPLE_DIR/NavigationExample"
echo "Updating Program.cs from CSharpExample.cs..."
cp ../CSharpExample.cs Program.cs
# Bước 3: Copy library
echo "Copying library..."
cp "$LIB_DIR/libnav_c_api.so" .
# # Bước 3: Copy library
# echo "Copying library..."
# cp "$LIB_DIR/libnav_c_api.so" .
# Bước 4: Set LD_LIBRARY_PATH để tìm được tất cả dependencies
# Main build directory (contains libtf3.so, librobot_cpp.so, etc.)
@@ -95,9 +94,9 @@ export LD_LIBRARY_PATH="$BUILD_DIR:$LD_LIBRARY_PATH"
# Library directories for dependencies
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/robot_time:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/xmlrpcpp:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/costmap_2d:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/geometry2/tf3_geometry_msgs:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/geometry2/tf3_sensor_msgs:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/robot_costmap_2d:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/geometry2/robot_tf3_geometry_msgs:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Libraries/geometry2/robot_tf3_sensor_msgs:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Navigations/Packages/move_base:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Navigations/Cores/move_base_core:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH="$BUILD_DIR/src/Navigations/Libraries/tf3:$LD_LIBRARY_PATH"

29
pnkx_nav_core.sln Normal file
View File

@@ -0,0 +1,29 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{B36A84DF-456D-A817-6EDD-3EC3E7F6E11F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NavigationExample", "examples\NavigationExample\NavigationExample.csproj", "{995839D6-1E72-F444-6587-97EF24F93814}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{995839D6-1E72-F444-6587-97EF24F93814}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{995839D6-1E72-F444-6587-97EF24F93814}.Debug|Any CPU.Build.0 = Debug|Any CPU
{995839D6-1E72-F444-6587-97EF24F93814}.Release|Any CPU.ActiveCfg = Release|Any CPU
{995839D6-1E72-F444-6587-97EF24F93814}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{995839D6-1E72-F444-6587-97EF24F93814} = {B36A84DF-456D-A817-6EDD-3EC3E7F6E11F}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1A56EED1-5E6A-48A6-9AEE-F39361B34305}
EndGlobalSection
EndGlobal

0
robotapp.db Normal file
View File

View File

@@ -10,17 +10,20 @@ if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
# Find Boost
find_package(Boost REQUIRED)
# Find Boost (filesystem needed for plugin path / boost::dll usage)
find_package(Boost REQUIRED COMPONENTS filesystem system)
# Dependencies
# Dependencies (robot_nav_2d_utils_conversions provides poseStampedToPose2D used by move_base_core/navigation.h)
set(PACKAGES_DIR
move_base_core
move_base
robot_nav_2d_utils
tf3
robot_time
robot_cpp
geometry_msgs
angles
data_convert
robot_protocol_msgs
)
# Thư mục include
@@ -29,8 +32,28 @@ include_directories(
)
# Tìm tất cả file source
file(GLOB SOURCES "src/*.cpp")
file(GLOB HEADERS "include/*.h")
file(GLOB SOURCES
"src/*.cpp"
"src/std_msgs/*.cpp"
"src/sensor_msgs/*.cpp"
"src/geometry_msgs/*.cpp"
"src/nav_msgs/*.cpp"
"src/nav_2d_msgs/*.cpp"
"src/robot_nav_msgs/*.cpp"
"src/robot_geometry_msgs/*.cpp"
"src/map_msgs/*.cpp"
)
file(GLOB HEADERS
"include/*.h"
"include/std_msgs/*.h"
"include/sensor_msgs/*.h"
"include/geometry_msgs/*.h"
"include/nav_msgs/*.h"
"include/nav_2d_msgs/*.h"
"include/robot_nav_msgs/*.h"
"include/robot_geometry_msgs/*.h"
"include/map_msgs/*.h"
)
# Tạo thư viện shared (.so)
add_library(nav_c_api SHARED ${SOURCES} ${HEADERS})
@@ -41,11 +64,15 @@ target_link_libraries(nav_c_api
${PACKAGES_DIR}
PRIVATE
Boost::boost
Boost::filesystem
Boost::system
dl
)
set_target_properties(nav_c_api PROPERTIES
LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
BUILD_RPATH "${CMAKE_BINARY_DIR}"
INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib"
)
# Set include directories
@@ -79,6 +106,45 @@ install(EXPORT nav_c_api-targets
option(BUILD_SHARED_LIBS "Build shared libraries" ON)
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
# Warning flags - disabled to suppress warnings during build
# 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

@@ -0,0 +1,217 @@
#ifndef C_API_CONVERTOR_H
#define C_API_CONVERTOR_H
// C
#include "sensor_msgs/LaserScan.h"
#include "sensor_msgs/PointCloud.h"
#include "sensor_msgs/PointCloud2.h"
#include "nav_msgs/Odometry.h"
#include "std_msgs/Header.h"
#include "nav_msgs/OccupancyGrid.h"
#include "geometry_msgs/Point.h"
#include "geometry_msgs/PoseStamped.h"
#include "geometry_msgs/Pose2D.h"
#include "nav_2d_msgs/Twist2D.h"
#include "nav_2d_msgs/Twist2DStamped.h"
#include "nav_2d_msgs/Path2D.h"
#include "map_msgs/OccupancyGridUpdate.h"
#include "geometry_msgs/PolygonStamped.h"
#include "protocol_msgs/Order.h"
// C++
#include <robot_sensor_msgs/LaserScan.h>
#include <robot_sensor_msgs/PointCloud.h>
#include <robot_sensor_msgs/PointCloud2.h>
#include <robot_nav_msgs/Odometry.h>
#include <robot_nav_msgs/OccupancyGrid.h>
#include <robot_geometry_msgs/PoseStamped.h>
#include <robot_geometry_msgs/Pose2D.h>
#include <robot_nav_2d_msgs/Twist2D.h>
#include <robot_nav_2d_msgs/Twist2DStamped.h>
#include <robot_nav_2d_msgs/Path2D.h>
#include <robot_map_msgs/OccupancyGridUpdate.h>
#include <robot_geometry_msgs/PolygonStamped.h>
#include <robot_protocol_msgs/Order.h>
#include <move_base_core/navigation.h>
#include <move_base_core/common.h>
/**
* @brief Convert C LaserScan to C++ LaserScan
* @param laser_scan C LaserScan
* @return C++ LaserScan
*/
robot_sensor_msgs::LaserScan convert2CppLaserScan(const LaserScan& laser_scan);
/**
* @brief Convert C OccupancyGrid to C++ OccupancyGrid
* @param occupancy_grid C OccupancyGrid
* @return C++ OccupancyGrid
*/
robot_nav_msgs::OccupancyGrid convert2CppOccupancyGrid(const OccupancyGrid& occupancy_grid);
/**
* @brief Convert C++ OccupancyGrid to C OccupancyGrid
* @param cpp C++ OccupancyGrid
* @param out C OccupancyGrid
*/
void convert2COccupancyGrid(const robot_nav_msgs::OccupancyGrid& cpp, OccupancyGrid& out);
/**
* @brief Convert C++ Path2D to C Path2D
*/
void convert2CPath2D(const robot_nav_2d_msgs::Path2D& cpp, Path2D& out);
/**
* @brief Convert C++ OccupancyGridUpdate to C OccupancyGridUpdate
*/
void convert2COccupancyGridUpdate(const robot_map_msgs::OccupancyGridUpdate& cpp, OccupancyGridUpdate& out);
/**
* @brief Convert C++ PolygonStamped to C PolygonStamped
*/
void convert2CPolygonStamped(const robot_geometry_msgs::PolygonStamped& cpp, PolygonStamped& out);
/**
* @brief Convert C++ LaserScan to C LaserScan
* @param cpp C++ LaserScan
* @param out C LaserScan
*/
void convert2CLaserScan(const robot_sensor_msgs::LaserScan& cpp, LaserScan& out);
/**
* @brief Convert C++ PointCloud to C PointCloud
* @param cpp C++ PointCloud
* @param out C PointCloud
*/
void convert2CPointCloud(const robot_sensor_msgs::PointCloud& cpp, PointCloud& out);
/**
* @brief Convert C++ PointCloud2 to C PointCloud2
* @param cpp C++ PointCloud2
* @param out C PointCloud2
*/
void convert2CPointCloud2(const robot_sensor_msgs::PointCloud2& cpp, PointCloud2& out);
/**
* @brief Convert C PointCloud to C++ PointCloud
* @param c C PointCloud
* @return C++ PointCloud
*/
robot_sensor_msgs::PointCloud convert2CppPointCloud(const PointCloud& c);
/**
* @brief Convert C PointCloud2 to C++ PointCloud2
* @param c C PointCloud2
* @return C++ PointCloud2
*/
robot_sensor_msgs::PointCloud2 convert2CppPointCloud2(const PointCloud2& c);
/**
* @brief Convert C Odometry to C++ Odometry
* @param odometry C Odometry
* @return C++ Odometry
*/
robot_nav_msgs::Odometry convert2CppOdometry(const Odometry& odometry);
/**
* @brief Convert C PoseStamped to C++ PoseStamped
* @param pose_stamped C PoseStamped
* @return C++ PoseStamped
*/
robot_geometry_msgs::PoseStamped convert2CppPoseStamped(const PoseStamped& pose_stamped);
/**
* @brief Convert C++ PoseStamped to C PoseStamped
* @param cpp_pose_stamped C++ PoseStamped
* @return C PoseStamped
*/
PoseStamped convert2CPoseStamped(const robot_geometry_msgs::PoseStamped& cpp_pose_stamped);
/**
* @brief Convert C Pose2D to C++ Pose2D
* @param pose_2d C Pose2D
* @return C++ Pose2D
*/
robot_geometry_msgs::Pose2D convert2CppPose2D(const Pose2D& pose_2d);
/**
* @brief Convert C++ Pose2D to C Pose2D
* @param cpp_pose_2d C++ Pose2D
* @return C Pose2D
*/
Pose2D convert2CPose2D(const robot_geometry_msgs::Pose2D& cpp_pose_2d);
/**
* @brief Convert C Twist2D to C++ Twist2D
* @param twist_2d C Twist2D
* @return C++ Twist2D
*/
robot_nav_2d_msgs::Twist2D convert2CppTwist2D(const Twist2D& twist_2d);
/**
* @brief Convert C++ Twist2D to C Twist2D
* @param cpp_twist_2d C++ Twist2D
* @return C Twist2D
*/
Twist2D convert2CTwist2D(const robot_nav_2d_msgs::Twist2D& cpp_twist_2d);
/**
* @brief Convert C Twist2DStamped to C++ Twist2DStamped
* @param twist_2d_stamped C Twist2DStamped
* @return C++ Twist2DStamped
*/
robot_nav_2d_msgs::Twist2DStamped convert2CppTwist2DStamped(const Twist2DStamped& twist_2d_stamped);
/**
* @brief Convert C++ Twist2DStamped to C Twist2DStamped
* @param cpp_twist_2d_stamped C++ Twist2DStamped
* @return C Twist2DStamped
*/
Twist2DStamped convert2CTwist2DStamped(const robot_nav_2d_msgs::Twist2DStamped& cpp_twist_2d_stamped);
/**
* @brief Convert C Order to C++ Order
* @param order C Order
* @return C++ 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
* @param cpp_order C++ Order
* @return C Order (caller must call order_free when done to release memory)
*/
Order convert2COrder(const robot_protocol_msgs::Order& cpp_order);
/**
* @brief Check if a quaternion is valid
* @param q Quaternion
* @return True if valid, false otherwise
*/
bool isQuaternionValid(const Quaternion& q);
/**
* @brief Free dynamic memory held by an Order returned from convert2COrder
* @param order Order to free (pointers and counts are zeroed)
*/
#ifdef __cplusplus
extern "C"
#endif
void order_free(Order* order);
#endif // C_API_CONVERTOR_H

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

@@ -0,0 +1,22 @@
#ifndef C_API_GEOMETRY_MSGS_ACCEL_H
#define C_API_GEOMETRY_MSGS_ACCEL_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "geometry_msgs/Vector3.h"
typedef struct
{
Vector3 linear;
Vector3 angular;
} Accel;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_ACCEL_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_ACCELSTAMPED_H
#define C_API_GEOMETRY_MSGS_ACCELSTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/Accel.h"
typedef struct
{
Header header;
Accel accel;
} AccelStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_ACCELSTAMPED_H

View File

@@ -0,0 +1,22 @@
#ifndef C_API_GEOMETRY_MSGS_ACCELWITHCOVARIANCE_H
#define C_API_GEOMETRY_MSGS_ACCELWITHCOVARIANCE_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "geometry_msgs/Accel.h"
typedef struct
{
Accel accel;
double covariance[36];
} AccelWithCovariance;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_ACCELWITHCOVARIANCE_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_ACCELWITHCOVARIANCESTAMPED_H
#define C_API_GEOMETRY_MSGS_ACCELWITHCOVARIANCESTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/AccelWithCovariance.h"
typedef struct
{
Header header;
AccelWithCovariance accel;
} AccelWithCovarianceStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_ACCELWITHCOVARIANCESTAMPED_H

View File

@@ -0,0 +1,28 @@
#ifndef C_API_GEOMETRY_MSGS_INERTIA_H
#define C_API_GEOMETRY_MSGS_INERTIA_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "geometry_msgs/Vector3.h"
typedef struct
{
double m;
Vector3 com;
double ixx;
double ixy;
double ixz;
double iyy;
double iyz;
double izz;
} Inertia;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_INERTIA_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_INERTIASTAMPED_H
#define C_API_GEOMETRY_MSGS_INERTIASTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/Inertia.h"
typedef struct
{
Header header;
Inertia inertia;
} InertiaStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_INERTIASTAMPED_H

View File

@@ -0,0 +1,21 @@
#ifndef C_API_GEOMETRY_MSGS_POINT_H
#define C_API_GEOMETRY_MSGS_POINT_H
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdint.h>
#include <stddef.h>
typedef struct
{
double x;
double y;
double z;
} Point;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_POINT_H

View File

@@ -0,0 +1,22 @@
#ifndef C_API_GEOMETRY_MSGS_POINT32_H
#define C_API_GEOMETRY_MSGS_POINT32_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
typedef struct
{
float x;
float y;
float z;
} Point32;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_POINT32_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_POINTSTAMPED_H
#define C_API_GEOMETRY_MSGS_POINTSTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/Point.h"
typedef struct
{
Header header;
Point point;
} PointStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_POINTSTAMPED_H

View File

@@ -0,0 +1,22 @@
#ifndef C_API_GEOMETRY_MSGS_POLYGON_H
#define C_API_GEOMETRY_MSGS_POLYGON_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "geometry_msgs/Point32.h"
typedef struct
{
Point32 *points;
size_t points_count;
} Polygon;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_POLYGON_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_POLYGONSTAMPED_H
#define C_API_GEOMETRY_MSGS_POLYGONSTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/Polygon.h"
typedef struct
{
Header header;
Polygon polygon;
} PolygonStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_POLYGONSTAMPED_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_POSE_H
#define C_API_GEOMETRY_MSGS_POSE_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "geometry_msgs/Point.h"
#include "geometry_msgs/Quaternion.h"
typedef struct
{
Point position;
Quaternion orientation;
} Pose;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_POSE_H

View File

@@ -0,0 +1,22 @@
#ifndef C_API_GEOMETRY_MSGS_POSE2D_H
#define C_API_GEOMETRY_MSGS_POSE2D_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
typedef struct
{
double x;
double y;
double theta;
} Pose2D;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_POSE2D_H

View File

@@ -0,0 +1,24 @@
#ifndef C_API_GEOMETRY_MSGS_POSEARRAY_H
#define C_API_GEOMETRY_MSGS_POSEARRAY_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/Pose.h"
typedef struct
{
Header header;
Pose *poses;
size_t poses_count;
} PoseArray;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_POSEARRAY_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_POSESTAMPED_H
#define C_API_GEOMETRY_MSGS_POSESTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/Pose.h"
typedef struct
{
Header header;
Pose pose;
} PoseStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_POSESTAMPED_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_POSEWITHCOVARIANCE_H
#define C_API_GEOMETRY_MSGS_POSEWITHCOVARIANCE_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "geometry_msgs/Pose.h"
typedef struct
{
Pose pose;
double *covariance;
size_t covariance_count;
} PoseWithCovariance;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_POSEWITHCOVARIANCE_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_POSEWITHCOVARIANCESTAMPED_H
#define C_API_GEOMETRY_MSGS_POSEWITHCOVARIANCESTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/PoseWithCovariance.h"
typedef struct
{
Header header;
PoseWithCovariance pose;
} PoseWithCovarianceStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_POSEWITHCOVARIANCESTAMPED_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_QUATERNION_H
#define C_API_GEOMETRY_MSGS_QUATERNION_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
typedef struct
{
double x;
double y;
double z;
double w;
} Quaternion;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_QUATERNION_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_QUATERNIONSTAMPED_H
#define C_API_GEOMETRY_MSGS_QUATERNIONSTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/Quaternion.h"
typedef struct
{
Header header;
Quaternion quaternion;
} QuaternionStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_QUATERNIONSTAMPED_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_TRANSFORM_H
#define C_API_GEOMETRY_MSGS_TRANSFORM_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "geometry_msgs/Vector3.h"
#include "geometry_msgs/Quaternion.h"
typedef struct
{
Vector3 translation;
Quaternion rotation;
} Transform;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_TRANSFORM_H

View File

@@ -0,0 +1,24 @@
#ifndef C_API_GEOMETRY_MSGS_TRANSFORMSTAMPED_H
#define C_API_GEOMETRY_MSGS_TRANSFORMSTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/Transform.h"
typedef struct
{
Header header;
char *child_frame_id;
Transform transform;
} TransformStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_TRANSFORMSTAMPED_H

View File

@@ -0,0 +1,22 @@
#ifndef C_API_GEOMETRY_MSGS_TWIST_H
#define C_API_GEOMETRY_MSGS_TWIST_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "geometry_msgs/Vector3.h"
typedef struct
{
Vector3 linear;
Vector3 angular;
} Twist;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_TWIST_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_TWISTSTAMPED_H
#define C_API_GEOMETRY_MSGS_TWISTSTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/Twist.h"
typedef struct
{
Header header;
Twist twist;
} TwistStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_TWISTSTAMPED_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_TWISTWITHCOVARIANCE_H
#define C_API_GEOMETRY_MSGS_TWISTWITHCOVARIANCE_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "geometry_msgs/Twist.h"
typedef struct
{
Twist twist;
double *covariance;
size_t covariance_count;
} TwistWithCovariance;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_TWISTWITHCOVARIANCE_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_TWISTWITHCOVARIANCESTAMPED_H
#define C_API_GEOMETRY_MSGS_TWISTWITHCOVARIANCESTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/TwistWithCovariance.h"
typedef struct
{
Header header;
TwistWithCovariance twist;
} TwistWithCovarianceStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_TWISTWITHCOVARIANCESTAMPED_H

View File

@@ -0,0 +1,22 @@
#ifndef C_API_GEOMETRY_MSGS_VECTOR3_H
#define C_API_GEOMETRY_MSGS_VECTOR3_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
typedef struct
{
double x;
double y;
double z;
} Vector3;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_VECTOR3_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_VECTOR3STAMPED_H
#define C_API_GEOMETRY_MSGS_VECTOR3STAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/Vector3.h"
typedef struct
{
Header header;
Vector3 vector;
} Vector3Stamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_VECTOR3STAMPED_H

View File

@@ -0,0 +1,22 @@
#ifndef C_API_GEOMETRY_MSGS_WRENCH_H
#define C_API_GEOMETRY_MSGS_WRENCH_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "geometry_msgs/Vector3.h"
typedef struct
{
Vector3 force;
Vector3 torque;
} Wrench;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_WRENCH_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_GEOMETRY_MSGS_WRENCHSTAMPED_H
#define C_API_GEOMETRY_MSGS_WRENCHSTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "geometry_msgs/Wrench.h"
typedef struct
{
Header header;
Wrench wrench;
} WrenchStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_GEOMETRY_MSGS_WRENCHSTAMPED_H

View File

@@ -0,0 +1,33 @@
#ifndef C_API_ROBOT_MAP_MSGS_OCCUPANCYGRIDUPDATE_C_H
#define C_API_ROBOT_MAP_MSGS_OCCUPANCYGRIDUPDATE_C_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
/**
* C representation of robot_map_msgs::OccupancyGridUpdate.
* Note: This header is intentionally named *_c.h to avoid
* shadowing the C++ header `robot_map_msgs/OccupancyGridUpdate.h`.
*/
typedef struct
{
Header header;
int32_t x;
int32_t y;
uint32_t width;
uint32_t height;
int8_t *data;
size_t data_count;
} OccupancyGridUpdate;
#ifdef __cplusplus
}
#endif
#endif // C_API_ROBOT_MAP_MSGS_OCCUPANCYGRIDUPDATE_C_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_NAV_2D_MSGS_COMPLEXPOLYGON2D_H
#define C_API_NAV_2D_MSGS_COMPLEXPOLYGON2D_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "nav_2d_msgs/Polygon2D.h"
typedef struct
{
Polygon2D outer;
Polygon2D *inner;
size_t inner_count;
} ComplexPolygon2D;
#ifdef __cplusplus
}
#endif
#endif // C_API_NAV_2D_MSGS_COMPLEXPOLYGON2D_H

View File

@@ -0,0 +1,25 @@
#ifndef C_API_NAV_2D_MSGS_NAVGRIDINFO_H
#define C_API_NAV_2D_MSGS_NAVGRIDINFO_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
typedef struct
{
uint32_t width;
uint32_t height;
double resolution;
char *frame_id;
double origin_x;
double origin_y;
} NavGridInfo;
#ifdef __cplusplus
}
#endif
#endif // C_API_NAV_2D_MSGS_NAVGRIDINFO_H

View File

@@ -0,0 +1,25 @@
#ifndef C_API_NAV_2D_MSGS_NAVGRIDOFCHARS_H
#define C_API_NAV_2D_MSGS_NAVGRIDOFCHARS_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Time.h"
#include "nav_2d_msgs/NavGridInfo.h"
typedef struct
{
Time stamp;
NavGridInfo info;
uint8_t *data;
size_t data_count;
} NavGridOfChars;
#ifdef __cplusplus
}
#endif
#endif // C_API_NAV_2D_MSGS_NAVGRIDOFCHARS_H

View File

@@ -0,0 +1,25 @@
#ifndef C_API_NAV_2D_MSGS_NAVGRIDOFCHARSUPDATE_H
#define C_API_NAV_2D_MSGS_NAVGRIDOFCHARSUPDATE_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Time.h"
#include "nav_2d_msgs/UIntBounds.h"
typedef struct
{
Time stamp;
UIntBounds bounds;
uint8_t *data;
size_t data_count;
} NavGridOfCharsUpdate;
#ifdef __cplusplus
}
#endif
#endif // C_API_NAV_2D_MSGS_NAVGRIDOFCHARSUPDATE_H

View File

@@ -0,0 +1,25 @@
#ifndef C_API_NAV_2D_MSGS_NAVGRIDOFDOUBLES_H
#define C_API_NAV_2D_MSGS_NAVGRIDOFDOUBLES_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Time.h"
#include "nav_2d_msgs/NavGridInfo.h"
typedef struct
{
Time stamp;
NavGridInfo info;
double *data;
size_t data_count;
} NavGridOfDoubles;
#ifdef __cplusplus
}
#endif
#endif // C_API_NAV_2D_MSGS_NAVGRIDOFDOUBLES_H

View File

@@ -0,0 +1,25 @@
#ifndef C_API_NAV_2D_MSGS_NAVGRIDOFDOUBLESUPDATE_H
#define C_API_NAV_2D_MSGS_NAVGRIDOFDOUBLESUPDATE_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Time.h"
#include "nav_2d_msgs/UIntBounds.h"
typedef struct
{
Time stamp;
UIntBounds bounds;
double *data;
size_t data_count;
} NavGridOfDoublesUpdate;
#ifdef __cplusplus
}
#endif
#endif // C_API_NAV_2D_MSGS_NAVGRIDOFDOUBLESUPDATE_H

View File

@@ -0,0 +1,24 @@
#ifndef C_API_NAV_2D_MSGS_PATH2D_H
#define C_API_NAV_2D_MSGS_PATH2D_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "nav_2d_msgs/Pose2DStamped.h"
typedef struct
{
Header header;
Pose2DStamped *poses;
size_t poses_count;
} Path2D;
#ifdef __cplusplus
}
#endif
#endif // C_API_NAV_2D_MSGS_PATH2D_H

View File

@@ -0,0 +1,21 @@
#ifndef C_API_NAV_2D_MSGS_POINT2D_H
#define C_API_NAV_2D_MSGS_POINT2D_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
typedef struct
{
double x;
double y;
} Point2D;
#ifdef __cplusplus
}
#endif
#endif // C_API_NAV_2D_MSGS_POINT2D_H

View File

@@ -0,0 +1,22 @@
#ifndef C_API_NAV_2D_MSGS_POLYGON2D_H
#define C_API_NAV_2D_MSGS_POLYGON2D_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "nav_2d_msgs/Point2D.h"
typedef struct
{
Point2D *points;
size_t points_count;
} Polygon2D;
#ifdef __cplusplus
}
#endif
#endif // C_API_NAV_2D_MSGS_POLYGON2D_H

View File

@@ -0,0 +1,27 @@
#ifndef C_API_NAV_2D_MSGS_POLYGON2DCOLLECTION_H
#define C_API_NAV_2D_MSGS_POLYGON2DCOLLECTION_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "std_msgs/ColorRGBA.h"
#include "nav_2d_msgs/ComplexPolygon2D.h"
typedef struct
{
Header header;
ComplexPolygon2D *polygons;
size_t polygons_count;
ColorRGBA *colors;
size_t colors_count;
} Polygon2DCollection;
#ifdef __cplusplus
}
#endif
#endif // C_API_NAV_2D_MSGS_POLYGON2DCOLLECTION_H

View File

@@ -0,0 +1,23 @@
#ifndef C_API_NAV_2D_MSGS_POLYGON2DSTAMPED_H
#define C_API_NAV_2D_MSGS_POLYGON2DSTAMPED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "std_msgs/Header.h"
#include "nav_2d_msgs/Polygon2D.h"
typedef struct
{
Header header;
Polygon2D polygon;
} Polygon2DStamped;
#ifdef __cplusplus
}
#endif
#endif // C_API_NAV_2D_MSGS_POLYGON2DSTAMPED_H

View File

@@ -0,0 +1,22 @@
#ifndef C_API_NAV_2D_MSGS_POSE2D32_H
#define C_API_NAV_2D_MSGS_POSE2D32_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
typedef struct
{
float x;
float y;
float theta;
} Pose2D32;
#ifdef __cplusplus
}
#endif
#endif // C_API_NAV_2D_MSGS_POSE2D32_H

Some files were not shown because too many files have changed in this diff Show More