optimal vitural function

This commit is contained in:
2026-08-10 21:42:52 +07:00
parent 771ee5d5e7
commit 75078db589
29 changed files with 1012 additions and 6823 deletions

View File

@@ -227,12 +227,6 @@ if(PNKX_NAV_CORE_BUILD_CATKIN_TEST_PACKAGES)
pnkx_add_test_package(depth_local_costmap_noetic_test)
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)
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)

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
@@ -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** ✅
@@ -288,9 +288,13 @@ 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

View File

@@ -144,26 +144,14 @@ namespace NavigationExample
[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);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_dock_to(NavigationHandle handle, string marker, PoseStamped goal);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_dock_to_order(NavigationHandle handle, Order order, string marker, PoseStamped goal);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_dock_to_nodes_edges(NavigationHandle handle, string marker, Node[] nodes, Edge[] edges, PoseStamped goal);
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_move_straight_to(NavigationHandle handle, double distance);
/// <summary>Rotate in place to align with target orientation (radians).</summary>
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_rotate_to(NavigationHandle handle, double goal_yaw);
// 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)]

View File

@@ -405,8 +405,11 @@ namespace NavigationExample
goal.pose.orientation.w = 1.0;
// Console.WriteLine("Docking to docking_point");
NavigationAPI.navigation_dock_to(navHandle, "charger", goal);
// 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);
@@ -414,8 +417,6 @@ namespace NavigationExample
NavigationAPI.navigation_set_twist_linear(navHandle, 0.1, 0.0, 0.0);
NavigationAPI.navigation_set_twist_angular(navHandle, 0.0, 0.0, 0.2);
// NavigationAPI.navigation_move_straight_to(navHandle, 1.0);
while (true)
{
System.Threading.Thread.Sleep(100);

View File

@@ -206,7 +206,7 @@ không đụng hàm cũ. Còn lại là chuyện host đổi sang gọi hàm m
|---|---|---|---|
| **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, 463` | `log_error` dùng để in giá trị bình thường: goal của `move_to_order`, goal của `move_to_nodes_edges`, `pose2d` của `move_straight_to` | 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 |
| **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 |
@@ -237,6 +237,11 @@ 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

View File

@@ -9,7 +9,7 @@ Bám sát mã nguồn tại thời điểm viết:
---
## 0. Đọc nhanh — 8 việc phải làm ở phía C#
## 0. Đọc nhanh — 9 việc phải làm ở phía C#
| # | Việc | Vì sao |
|---|---|---|
@@ -21,15 +21,31 @@ Bám sát mã nguồn tại thời điểm viết:
| 6 | Bỏ mọi so sánh chuỗi `feed_back_str`, chuyển sang so enum | Nội dung chuỗi do lõi mới đặt, khác hoàn toàn bản cũ |
| 7 | Không coi `navigation_pause` trả về là robot đã dừng | Lệnh chỉ được ghi nhận, có hiệu lực ở cycle sau (≤ 33 ms @ 30 Hz) |
| 8 | Gọi các hàm `navigation_free_*` mới sau mỗi getter cấp bộ nhớ | Trước đây không có hàm giải phóng nào cho grid/scan/cloud/plan — mỗi lời gọi rò một lần |
| 9 | **Gỡ khai báo và call site của 5 hàm đã bị xoá** — `navigation_dock_to`, `_dock_to_order`, `_dock_to_nodes_edges`, `navigation_move_straight_to`, `navigation_rotate_to` | Symbol không còn trong `.so`; gọi là `EntryPointNotFoundException`. Thay bằng compound action + `navigation_execute_instant_actions` — xem mục 6.4 |
Ba việc **nên** làm thêm: dùng `navigation_get_state` thay cho `navigation_get_feedback` ở vòng poll
(không cấp phát chuỗi); dùng `navigation_add_depth_camera_data` để bật clear theo frustum; dùng
`navigation_move_to_order_v2` nếu fleet master có gửi order update.
> **Thay đổi phá vỡ tương thích, 2026-08-10.** Năm hàm bị **xoá khỏi API**: `navigation_dock_to`,
> `navigation_dock_to_order`, `navigation_dock_to_nodes_edges`, `navigation_move_straight_to`,
> `navigation_rotate_to`. Docking / đi thẳng / quay tại chỗ giờ là `profile` của từng chặng trong
> `compound_actions_params.yaml`, gửi bằng `navigation_move_to_order_v2` hoặc hàm mới
> `navigation_execute_instant_actions`. Chi tiết ở **mục 6.4**, hàm mới ở **mục 11.8**.
**Đọc gì tiếp:** mục 3 (trình tự khởi tạo) và mục 5 (trình tự tắt) là hai chỗ dễ sai nhất. Mục 6 là
tham chiếu toàn bộ API theo nhóm. **Mục 11 là bản chi tiết của 13 hàm mới** — chức năng, từng tham
số, bẫy, ví dụ C#. Phụ lục B là đúng phần khai báo C# phải thêm.
**Nếu bạn đang ghép một khung C# vào từ đầu**, đọc theo thứ tự: mục 2 (điều kiện vận hành) → **mục 12
(kiến trúc host)** → mục 3 và 5 (khởi tạo, tắt) → **mục 13 (ánh xạ VDA5050)** → **mục 14 (triển khai
lên robot)** → **mục 15 (checklist nghiệm thu)**. Mục 6 và 11 tra khi cần từng hàm.
> **Tài liệu này là bản bền vững.** Nó mô tả API và cách ghép, không gắn với trạng thái hiện tại của
> một khung C# cụ thể. Bản kiểm điểm một thời điểm cho `RobotNet12` nằm ở
> `nav-c-api-2-csharp-integration-report.md` — file đó liệt kê lỗi đang có ở một repo tại một ngày cụ
> thể và sẽ cũ đi; file này thì không.
---
## 1. Bố cục — và các hàm cũ nằm ở đâu
@@ -103,7 +119,7 @@ Thứ tự này **bắt buộc**, không phải khuyến nghị. Sai thứ tự
```csharp
// ---- 1..2 -------------------------------------------------------------------------------
tfHandle = tf3_buffer_create();
tfHandle = tf3_buffer_create(10); // cache 10 s
navHandle = navigation_create();
if (navHandle == IntPtr.Zero)
throw new InvalidOperationException("navigation_create failed — kiểm tra library_path của MoveBase");
@@ -369,26 +385,60 @@ tuyến đang chạy; đổi `order_id` = order mới thay thế hoàn toàn. `o
| | Hàm | Đổi |
|---|---|---|
| | `bool navigation_dock_to(NavigationHandle, const char *marker, PoseStamped goal)` | = |
| | `bool navigation_dock_to_order(NavigationHandle, Order, const char *marker, PoseStamped)` | = |
| | `bool navigation_dock_to_nodes_edges(...)` | ~ (cùng vấn đề `Order`, đã sửa) |
| | `bool navigation_dock_to_order_v2(NavigationHandle, const char *marker, const char *order_id, uint32_t, const Node*, size_t, const Edge*, size_t, PoseStamped)` | + |
| | `bool navigation_execute_instant_actions(NavigationHandle, const Action *actions, size_t count)` | + |
Docking dùng profile riêng (`docking_planner_name`) và tên marker. Docking **không** đi qua mission
layer — nó xuống thẳng lõi.
Chạy trọn một message `instantActions` của VDA5050. Xem chi tiết ở **mục 11.8**.
| | Hàm | Đổi |
#### Năm hàm đã bị XOÁ khỏi API
| Hàm | Trạng thái |
|---|---|
| `navigation_dock_to` | **Đã xoá** |
| `navigation_dock_to_order` | **Đã xoá** |
| `navigation_dock_to_nodes_edges` | **Đã xoá** |
| `navigation_move_straight_to` | **Đã xoá** |
| `navigation_rotate_to` | **Đã xoá** |
Cả năm đã bị gỡ khỏi contract `BaseNavigation` (`move_base_core/navigation.h`), khỏi `move_base`,
`move_base2`, `nav_c_api`, `nav_c_api_2` và khỏi host ROS (`amr_control`). **Symbol không còn trong
`.so`** — mọi khai báo P/Invoke còn sót lại sẽ ném `EntryPointNotFoundException` ở lời gọi đầu tiên.
**Năng lực không mất, nó chuyển chỗ.** Docking, đi thẳng và quay tại chỗ giờ là **thuộc tính của
từng chặng bên trong một action**, khai trong `compound_actions_params.yaml`:
```yaml
PickUp:
steps:
- {action: detect} # dò mốc
- {move_to: dock_target, profile: docking, marker: trolley} # tiến vào bằng profile docking
- {action: LiftFork}
- {move: -0.5, profile: go_straight} # lùi ra 0.5 m
UnDockFromStation:
steps:
- {move: -1.0, profile: go_straight}
- {move: 0.0, profile: rotate}
```
`profile` nhận `position | docking | go_straight | rotate`; `marker` **chỉ hợp lệ với
`profile: docking`** và chọn override trong `maker_sources.yaml`. Tolerance thuộc YAML của local
planner mà profile đó chọn, không khai ở đây.
Host không còn gọi ba động tác này trực tiếp. Nó gửi **tên action** — `PickUp`, `charge`,
`UnDockFromStation` — theo một trong hai đường:
| Đường | Hàm | Khi nào |
|---|---|---|
| | `bool navigation_move_straight_to(NavigationHandle, double distance)` | = |
| Action nằm trong node của order | `navigation_move_to_order_v2` | Fleet master giao tuyến có action ở giữa đường |
| `instantActions` ngoài luồng order | `navigation_execute_instant_actions` | Fleet master hoặc HMI yêu cầu ngay |
Đi thẳng theo hướng hiện tại. Tham số là **khoảng cách [m]**, không phải pose: hàm tự đọc pose robot
rồi tính goal. Âm là lùi. Vì nó đọc pose ngay lúc gọi nên TF phải sẵn sàng.
Cùng một bảng compound action, cùng một bộ handler, nên `PickUp` gửi kiểu nào cũng sinh ra đúng chuỗi
chặng như nhau.
| | Hàm | Đổi |
|---|---|---|
| | `bool navigation_rotate_to(NavigationHandle, PoseStamped goal)` | = |
Quay tại chỗ tới hướng của `goal` (chỉ dùng phần orientation).
**Vì sao đổi.** Ba hàm cũ đi **thẳng xuống lõi**, không qua mission layer — nên chúng cướp quyền của
order đang chạy mà mission layer không hề biết. `UnDockFromStation` gọi `moveStraightTo` là một ví dụ
đã gặp: nó preempt order đang chạy trong im lặng. Đưa chúng vào compound action là đưa mọi chuyển
động về chung một hàng đợi, chung một đường huỷ, chung một đường báo kết quả.
### 6.5. Vòng đời nhiệm vụ
@@ -584,7 +634,7 @@ Dịch một pose đi `d` mét dọc theo hướng của chính nó (âm là lù
| `navigation_add_*` (mọi đường sensor) | **Một thread duy nhất.** Đường sensor không thread-safe. Nếu C# có nhiều nguồn chạy song song, dồn qua một hàng đợi rồi bơm từ một thread. |
| `navigation_set_robot_footprint` | Thread bất kỳ (ghi dưới mutex, áp ở cycle sau) |
| `pause` / `resume` / `cancel` / `set_twist_*` | Thread bất kỳ (ghi dưới mutex, áp ở cycle sau) |
| `move_to*` / `dock_to*` / `rotate_to` / `move_straight_to` | Thread bất kỳ |
| `move_to*` / `execute_instant_actions` | Thread bất kỳ |
| `get_feedback` / `get_state` / `get_twist` / `get_robot_pose_*` | Thread bất kỳ |
| `get_global_data` / `get_local_data` | Thread bất kỳ; mỗi consumer nên có **struct riêng**, không dùng chung một `PlannerDataOutput` giữa nhiều timer |
| `navigation_initialize*` / `navigation_shutdown` / `navigation_destroy` | Thread khởi tạo/thread tắt, **không** song song với nhóm sensor |
@@ -616,7 +666,11 @@ Dịch một pose đi `d` mét dọc theo hướng của chính nó (âm là lù
chưa xác nhận phía C# có đang vẽ nó lên bản đồ hay không.
- Các hàm mới trong `nav_c_api_2` mới chỉ được kiểm tra biên dịch, **chưa chạy trên robot hay
Gazebo**. Đường depth camera cần kiểm tra thực tế bằng bộ đếm chẩn đoán của cổng sensor.
- `navigation_move_straight_to` với khoảng cách âm (lùi) trong `move_base2` chưa được kiểm tra.
- Đường **instant action** (mục 11.8) mới thêm, chưa chạy thử trên robot: cần xác nhận `PickUp` gửi
dạng instantAction sinh ra đúng chuỗi chặng như khi nó nằm trong order, và `blockingType` bị hạ từ
`NONE` xuống xếp hàng có ghi log đúng không.
- Chặng `profile: go_straight` với khoảng cách âm (lùi) — đường thay thế cho
`navigation_move_straight_to` cũ — chưa được kiểm tra.
---
@@ -886,24 +940,96 @@ navigation_move_to_order_v2(navHandle, "order-4711", 1, nodesExtended,
---
### 11.8. `navigation_dock_to_order_v2` — bản docking của trên
### 11.8. `navigation_execute_instant_actions` — chạy một message `instantActions`
```c
bool navigation_dock_to_order_v2(NavigationHandle handle, const char *marker,
const char *order_id, uint32_t order_update_id,
const Node *nodes, size_t node_count,
const Edge *edges, size_t edge_count,
const PoseStamped goal);
bool navigation_execute_instant_actions(NavigationHandle handle, const Action *actions,
size_t count);
```
**Làm gì.** Như 11.7 nhưng dùng profile docking và một tên marker.
**Làm gì.** Chạy **trọn một message `instantActions` của VDA5050 — cả danh sách, như một lô**. Mỗi
action được khai triển qua **đúng bảng compound action mà node action dùng**, nên `PickUp` gửi dạng
instantAction sinh ra đúng chuỗi detect / tiến vào / nâng / lùi ra như khi nó nằm trong order. Một bộ
từ vựng, một bộ handler, một ý nghĩa cho mỗi `actionType` bất kể nó đến bằng đường nào.
**Khác biệt so với `move_to_order_v2`.** Docking **không đi qua mission layer** — nó xuống thẳng lõi
với `MotionProfile::kDocking`. `order_id`/`order_update_id` vẫn được mang theo trong order để phần
sau tra cứu, nhưng chúng không lái hàng đợi mission như ở đường `move_to`.
**Vì sao cần.** Đây là hàm thay thế cho `navigation_dock_to*`, `navigation_move_straight_to` và
`navigation_rotate_to` đã bị xoá. Ba hàm cũ đi thẳng xuống lõi, cướp quyền của order đang chạy mà
mission layer không biết. Đường mới đi qua mission layer nên dùng chung hàng đợi, chung đường huỷ,
chung đường báo kết quả.
**Tham số riêng.** `marker` là tên hoặc id của mốc docking; không được `NULL`. Planner docking được
chọn qua `docking_planner_name` trong YAML.
**Tham số.**
| Tham số | Ý nghĩa |
|---|---|
| `actions` | Mảng action **theo đúng thứ tự nhận được**. Host giữ quyền sở hữu; thư viện copy trước khi trả về |
| `count` | Số action. Phải `> 0` |
**Trả về.** `true` nếu message được nhận. `false` nghĩa là **bị từ chối thẳng** — báo failed ngay,
đừng chờ một kết quả sẽ không bao giờ tới.
**Bẫy 1 — gửi cả lô, đừng gọi từng action.** Một action `HARD` gửi riêng sẽ preempt và xoá sạch các
chặng của action trước. Hai action trong cùng một message mà gọi hai lần thì chúng ăn nhau. Truyền cả
mảng trong một lời gọi.
**Bẫy 2 — `blockingType` quyết định cách lô gặp order đang chạy.**
| `blockingType` | Hành vi |
|---|---|
| `HARD` (bất kỳ action nào trong lô) | Cả message **preempt** order đang chạy |
| `SOFT` | Xếp hàng sau order |
| `NONE` | Yêu cầu chạy **song song** với việc di chuyển — runtime này **không làm được**, nên nó bị xếp hàng và việc thu hẹp đó được ghi log |
| không khai / không hiểu | Coi như `HARD` — hướng an toàn |
**Bẫy 3 — không route ba action điều khiển hàng đợi qua đây.** `cancelOrder`, `startPause`,
`stopPause` là lệnh **lái hàng đợi**, không phải việc nằm trong hàng đợi. Gọi
`navigation_cancel()`, `navigation_pause()`, `navigation_resume()`.
**Bẫy 4 — dừng ở chặng lỗi đầu tiên.** Message dừng tại chặng đầu tiên thất bại và phần còn lại bị bỏ
theo. Host báo **một** kết quả cho cả message — đúng bằng những gì VDA5050 yêu cầu.
**Theo dõi tiến độ.** Không có báo cáo theo từng action; dùng trạng thái chung:
| `navigation_get_state` | Báo về fleet |
|---|---|
| `ACTIVE` / `CONTROLLING` | `RUNNING` |
| `SUCCEEDED` | `FINISHED` |
| `ABORTED` / `PREEMPTED` | `FAILED` |
Ánh xạ này chỉ **không nhập nhằng khi message đang là việc duy nhất trong hàng đợi** — đúng chừng nào
fleet master gửi mỗi lần một message và không gửi trong lúc order đang chạy.
```csharp
[DllImport(Lib, CallingConvention = Cdecl)] [return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_execute_instant_actions(
IntPtr handle, [In] Action[] actions, UIntPtr count);
// Nhận nguyên message instantActions từ MQTT rồi đẩy CẢ LÔ xuống một lần.
public bool RunInstantActions(IReadOnlyList<Vda5050Action> incoming)
{
var actions = new Action[incoming.Count];
var pinned = new List<IntPtr>();
try
{
for (int i = 0; i < incoming.Count; i++)
actions[i] = BuildNativeAction(incoming[i], pinned); // strdup các chuỗi
if (!navigation_execute_instant_actions(navHandle, actions, (UIntPtr)actions.Length))
{
ReportFailed(incoming, "rejected by navigation core");
return false;
}
return true; // theo dõi tiếp bằng navigation_get_state
}
finally
{
foreach (var p in pinned) Marshal.FreeHGlobal(p);
}
}
```
`Action` là struct C đã có sẵn (`protocol_msgs/Action.h`): `actionType`, `actionId`,
`actionDescription`, `blockingType`, `actionParameters` + `actionParameters_count`. Không có struct
mới nào cần khai thêm cho hàm này.
---
@@ -992,36 +1118,51 @@ vừa không đi hết các tầng lồng nhau, vừa không đảm bảo cùng
Lấy bằng `nm --defined-only` trên các object file. Cột "Nguồn" cho biết symbol nằm trong file nguồn
nào — chỉ để tra cứu, C# không cần biết: mọi symbol đều nằm chung một `.so`.
### 50 symbol cũ — `nav_c_api.cpp`, C# **không đổi gì**
**Tổng: 62 symbol** = 45 cũ + 4 trợ giúp + 13 mới. Lấy bằng
`nm -D --defined-only build/libnav_c_api.so | grep " T "`.
### 45 symbol cũ — `nav_c_api.cpp`, C# **không đổi gì**
```
nav_c_api_free_string navigation_get_point_cloud2
navigation_add_laser_scan navigation_get_robot_footprint
navigation_add_odometry navigation_get_robot_pose_2d
navigation_add_point_cloud navigation_get_robot_pose_stamped
navigation_add_point_cloud2 navigation_get_static_map
navigation_add_static_map navigation_get_twist
navigation_cancel navigation_initialize
navigation_create navigation_move_straight_to
navigation_destroy navigation_move_to
navigation_dock_to navigation_move_to_nodes_edges
navigation_dock_to_nodes_edges navigation_move_to_order
navigation_dock_to_order navigation_offset_goal_2d
navigation_get_all_laser_scans navigation_offset_goal_stamped
navigation_get_all_point_cloud2s navigation_pause
navigation_get_all_point_clouds navigation_remove_all_data
navigation_get_all_static_maps navigation_remove_all_laser_scans
navigation_get_feedback navigation_remove_all_point_cloud2s
navigation_get_global_data navigation_remove_all_point_clouds
navigation_get_laser_scan navigation_remove_all_static_maps
navigation_get_local_data navigation_remove_laser_scan
navigation_get_point_cloud navigation_remove_point_cloud
navigation_resume navigation_remove_point_cloud2
navigation_rotate_to navigation_remove_static_map
navigation_set_robot_footprint navigation_state_to_string
nav_c_api_free_string navigation_get_robot_pose_stamped
navigation_add_laser_scan navigation_get_static_map
navigation_add_odometry navigation_get_twist
navigation_add_point_cloud navigation_initialize
navigation_add_point_cloud2 navigation_move_to
navigation_add_static_map navigation_move_to_nodes_edges
navigation_cancel navigation_move_to_order
navigation_create navigation_offset_goal_2d
navigation_destroy navigation_offset_goal_stamped
navigation_get_all_laser_scans navigation_pause
navigation_get_all_point_cloud2s navigation_remove_all_data
navigation_get_all_point_clouds navigation_remove_all_laser_scans
navigation_get_all_static_maps navigation_remove_all_point_cloud2s
navigation_get_feedback navigation_remove_all_point_clouds
navigation_get_global_data navigation_remove_all_static_maps
navigation_get_laser_scan navigation_remove_laser_scan
navigation_get_local_data navigation_remove_point_cloud
navigation_get_point_cloud navigation_remove_point_cloud2
navigation_get_point_cloud2 navigation_remove_static_map
navigation_get_robot_footprint navigation_resume
navigation_get_robot_pose_2d navigation_set_robot_footprint
navigation_set_twist_angular navigation_set_twist_linear
navigation_state_to_string
```
### 5 symbol ĐÃ BỊ XOÁ — C# phải gỡ khai báo
```
navigation_dock_to
navigation_dock_to_order
navigation_dock_to_nodes_edges
navigation_move_straight_to
navigation_rotate_to
```
Không còn trong `.so`. Khai báo P/Invoke còn sót lại sẽ ném `EntryPointNotFoundException` ở lời gọi
đầu tiên. Năng lực thay thế: `profile` + `marker` trong `compound_actions_params.yaml`, gửi qua
`navigation_move_to_order_v2` hoặc `navigation_execute_instant_actions` — xem mục 6.4.
Cộng bốn symbol nữa, không nằm trong `nav_c_api.cpp`:
```
@@ -1041,13 +1182,16 @@ time_create ← std_msgs/Time.cpp
```
navigation_initialize_checked navigation_add_depth_camera_data
navigation_is_ready navigation_move_to_order_v2
navigation_shutdown navigation_dock_to_order_v2
navigation_shutdown navigation_execute_instant_actions
navigation_get_state navigation_free_occupancy_grid
navigation_get_status_text navigation_free_laser_scan
navigation_free_point_cloud navigation_free_point_cloud2
navigation_free_planner_data
```
`navigation_dock_to_order_v2` từng nằm trong danh sách này nhưng **đã bị xoá cùng nhóm docking**;
`navigation_execute_instant_actions` là hàm thay thế.
---
## Phụ lục B — phần C# phải thêm
@@ -1145,13 +1289,10 @@ public static extern bool navigation_move_to_order_v2(
[In] Edge[] edges, UIntPtr edgeCount,
PoseStamped goal);
// ---- instant actions --------------------------------------------------------------------
[DllImport(Lib, CallingConvention = Cdecl)] [return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_dock_to_order_v2(
IntPtr handle, [MarshalAs(UnmanagedType.LPStr)] string marker,
[MarshalAs(UnmanagedType.LPStr)] string orderId, uint orderUpdateId,
[In] Node[] nodes, UIntPtr nodeCount,
[In] Edge[] edges, UIntPtr edgeCount,
PoseStamped goal);
public static extern bool navigation_execute_instant_actions(
IntPtr handle, [In] Action[] actions, UIntPtr count);
// ---- giải phóng bộ nhớ ------------------------------------------------------------------
[DllImport(Lib, CallingConvention = Cdecl)]
@@ -1255,3 +1396,492 @@ private void StopGlobalTimer()
navigation_free_planner_data(ref globalData);
}
```
---
## 12. Ghép vào khung C# — kiến trúc host
Mục này mô tả **hình dạng** của phần C# bọc quanh API, độc lập với bất kỳ repo cụ thể nào. Ba mục
6, 11 và Phụ lục B nói *hàm nào làm gì*; mục này nói *xếp chúng vào đâu*.
### 12.1. Bốn tầng, không hơn
```
┌──────────────────────────────────────────────────────────────┐
│ Tầng nghiệp vụ (MQTT/VDA5050, HMI, fleet) │
│ dịch order & instantActions ──► mục 13 │
├──────────────────────────────────────────────────────────────┤
│ NavigationHost — vòng đời + hàng đợi lệnh + poll trạng thái │
│ sở hữu handle, sở hữu thread, là nơi DUY NHẤT gọi add_* │
├──────────────────────────────────────────────────────────────┤
│ Lớp binding — struct [StructLayout] + DllImport │
│ dịch thuần, không logic ──► Phụ lục B │
├──────────────────────────────────────────────────────────────┤
│ libnav_c_api.so → libmove_base2.so → planner/costmap │
└──────────────────────────────────────────────────────────────┘
```
Ranh giới quan trọng nhất là giữa tầng 2 và 3: **lớp binding không được có logic**. Mọi quyết định
(thứ tự khởi tạo, ai gọi từ thread nào, khi nào free) thuộc `NavigationHost`. Trộn hai tầng là cách
nhanh nhất để có một lời gọi `navigation_add_*` chạy từ thread lạ.
### 12.2. Mô hình thread
Đường sensor của lõi **không thread-safe**. Quy tắc:
| Nhóm | Thread |
|---|---|
| `navigation_add_*` (map, laser, cloud, depth, odometry) | **Một thread duy nhất.** Nhiều nguồn thì dồn qua một hàng đợi rồi bơm từ một thread |
| `navigation_create` / `_initialize_checked` / `_shutdown` / `_destroy` | Thread khởi tạo/tắt, **không** song song với nhóm trên |
| `move_to*`, `execute_instant_actions`, `pause`/`resume`/`cancel`, `set_twist_*`, `set_robot_footprint` | Thread bất kỳ |
| `get_state`, `get_feedback`, `get_twist`, `get_robot_pose_*` | Thread bất kỳ |
| `get_global_data` / `_local_data` | Thread bất kỳ, nhưng **mỗi consumer một struct riêng** |
Tối thiểu ba thread ở phía C#: **sensor pump** (một), **state poll** (một), và thread nghiệp vụ gọi
lệnh. Đừng gộp sensor pump vào timer UI — một lần UI đứng là một lần costmap đói dữ liệu.
### 12.3. Khung `NavigationHost`
```csharp
public sealed class NavigationHost : IAsyncDisposable
{
private IntPtr _nav;
private IntPtr _tf;
private CancellationTokenSource? _cts;
private Task? _sensorPump;
private Task? _statePoll;
// ── Khởi tạo — thứ tự BẮT BUỘC, xem mục 3 ────────────────────────────────────────────
public async Task StartAsync(NavConfig cfg, CancellationToken ct)
{
_tf = TF3.tf3_buffer_create(10);
StartTfPump(); // 1. TF chảy TRƯỚC mọi thứ khác
_nav = navigation_create(); // 2. nạp libmove_base2.so theo YAML
if (_nav == IntPtr.Zero)
throw new InvalidOperationException(
"navigation_create failed — kiểm tra PNKX_NAV_CORE_CONFIG_DIR và library_path");
navigation_set_robot_footprint(_nav, cfg.Footprint, (UIntPtr)cfg.Footprint.Length); // 3.
var map = await WaitForMapAsync(ct); // 4. BẮT BUỘC trước initialize
navigation_add_static_map(_nav, "/map", map);
// 5. Nặng và chặn hàng giây — chạy nền, không gọi từ UI thread.
bool ready = await Task.Run(() => navigation_initialize_checked(_nav, _tf), ct);
if (!ready)
throw new InvalidOperationException($"navigation core not ready: {ReadStatusText()}");
_cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
_sensorPump = Task.Run(() => SensorPumpLoop(_cts.Token), _cts.Token); // 6.
_statePoll = Task.Run(() => StatePollLoop(_cts.Token), _cts.Token);
}
// ── Bơm sensor — MỘT thread cho tất cả, xem mục 4 ────────────────────────────────────
private async Task SensorPumpLoop(CancellationToken ct)
{
await foreach (var sample in _sensorQueue.ReadAllAsync(ct))
{
switch (sample)
{
case LaserSample s: navigation_add_laser_scan(_nav, s.Topic, s.Scan); break;
case CloudSample c: navigation_add_point_cloud2(_nav, c.Topic, c.Cloud); break;
case DepthSample d: navigation_add_depth_camera_data(_nav, d.Topic, d.Data); break;
case OdomSample o: navigation_add_odometry(_nav, "odom", o.Odom); break;
case MapSample m: navigation_add_static_map(_nav, "/map", m.Grid); break;
}
}
}
// ── Poll trạng thái — dùng get_state, KHÔNG dùng get_feedback ────────────────────────
private async Task StatePollLoop(CancellationToken ct)
{
var last = NavigationState.PENDING;
while (!ct.IsCancellationRequested)
{
if (navigation_get_state(_nav, out var now) && now != last)
{
OnStateChanged(last, now); // đổi state mới đọc status text
last = now;
}
await Task.Delay(100, ct);
}
}
// ── Tắt — thứ tự BẮT BUỘC, xem mục 5 ────────────────────────────────────────────────
public async ValueTask DisposeAsync()
{
_cts?.Cancel(); // 1. dừng mọi thread gọi add_*
if (_sensorPump is not null) await _sensorPump.ConfigureAwait(false);
if (_statePoll is not null) await _statePoll.ConfigureAwait(false);
if (_nav != IntPtr.Zero)
{
navigation_shutdown(_nav); // 2. quiesce, ~1 s
navigation_destroy(_nav); // 3. thả instance
_nav = IntPtr.Zero;
}
if (_tf != IntPtr.Zero)
{
TF3.tf3_buffer_destroy(_tf); // 4. buffer TF sau cùng
_tf = IntPtr.Zero;
}
}
}
```
### 12.4. Năm quy tắc rút gọn
1. **Handle là tài nguyên có chủ.** Một `NavigationHost` sở hữu một handle; không truyền `IntPtr` ra
ngoài lớp đó.
2. **Không bao giờ để `navigation_destroy` rơi vào finalizer/GC.** Luôn đi qua `DisposeAsync` với
`navigation_shutdown` đứng trước.
3. **`get_state` cho vòng poll, `get_feedback`/`get_status_text` cho sự kiện.** Hai hàm sau cấp phát
chuỗi, quên free là rò.
4. **Rẽ nhánh theo enum, không theo chuỗi.** Nội dung `feed_back_str` đổi giữa các bản.
5. **Mọi getter cấp bộ nhớ đều có hàm `navigation_free_*` đi kèm** — xem mục 7.
---
## 12b. TF — thư viện thứ hai host phải nuôi
`libnav_c_api.so` **không tự lấy được pose robot**. Nó nhận một `tf3::BufferCore` do host tạo và host
bơm, rồi mọi thứ bên trong — costmap lấy pose, laser transform về base frame, depth camera dựng
frustum — đều tra qua buffer đó. Buffer rỗng nghĩa là costmap không cập nhật và không có lỗi nào rõ
ràng để lần ra.
Đây là một `.so` **riêng biệt**: `/usr/local/lib/libtf3.so`, không phải `libnav_c_api.so`.
### 12b.1. Bề mặt C API của tf3
```csharp
private const string Tf3Lib = "/usr/local/lib/libtf3.so";
[DllImport(Tf3Lib, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr tf3_buffer_create(int cacheTimeSec); // 10 s là mặc định hợp lý
[DllImport(Tf3Lib, CallingConvention = CallingConvention.Cdecl)]
public static extern void tf3_buffer_destroy(IntPtr buffer);
[DllImport(Tf3Lib, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_set_transform(IntPtr buffer, ref TF3_Transform transform,
[MarshalAs(UnmanagedType.LPStr)] string authority,
[MarshalAs(UnmanagedType.I1)] bool isStatic);
[DllImport(Tf3Lib, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_lookup_transform(IntPtr buffer, string targetFrame, string sourceFrame,
long timeSec, long timeNsec,
ref TF3_Transform transform, ref TF3_ErrorCode error);
[DllImport(Tf3Lib, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool tf3_can_transform(IntPtr buffer, string targetFrame, string sourceFrame,
long timeSec, long timeNsec,
IntPtr errorMsg, int errorMsgLen);
```
Còn `tf3_clear`, `tf3_get_current_time`, `tf3_get_version`, `tf3_get_all_frame_names`,
`tf3_get_frame_tree`, `tf3_get_last_error` — dùng để chẩn đoán, không nằm trên đường chạy.
### 12b.2. Cây frame tối thiểu
| Transform | Loại | Ai bơm | Nhịp |
|---|---|---|---|
| `map` → `odom` | động | localization (SLAM / AMCL / XLOC) | theo nguồn định vị |
| `odom` → `base_link` | động | odometry bánh xe | theo nhịp odometry, thường 20–50 Hz |
| `base_link` → `<laser_frame>` | **tĩnh** | host, bơm một lần lúc khởi động | một lần |
| `base_link` → `<camera_optical_frame>` | **tĩnh** | host, bơm một lần lúc khởi động | một lần |
Transform tĩnh bơm với `isStatic = true` — nó không hết hạn theo thời gian, nên không cần bơm lại.
Transform động bơm với `isStatic = false` và **phải có stamp đúng**: costmap tra transform tại đúng
stamp của mẫu sensor, không phải tại "bây giờ".
### 12b.3. Thứ tự — TF trước, luôn luôn
```csharp
_tf = tf3_buffer_create(10); // 1. tạo buffer, cache 10 s
PublishStaticTransforms(); // 2. base_link → laser/camera, isStatic = true
StartOdomTfPump(); // 3. odom → base_link, chạy liên tục
StartLocalizationTfPump(); // 4. map → odom, chạy liên tục
// ... chờ cây frame đủ ...
_nav = navigation_create(); // 5. rồi mới tới navigation
```
`navigation_initialize_checked` dựng costmap, và costmap **lấy pose robot ngay trong chu kỳ cập nhật
đầu tiên**. Cây frame chưa đủ tại thời điểm đó thì costmap khởi tạo với pose sai hoặc đứng im.
Chờ cho chắc trước khi initialize:
```csharp
private async Task WaitForTfAsync(CancellationToken ct, int timeoutMs = 10000)
{
var sw = Stopwatch.StartNew();
var t = new TF3_Transform();
var err = TF3_ErrorCode.NoError;
while (sw.ElapsedMilliseconds < timeoutMs)
{
tf3_get_current_time(ref var sec, ref var nsec);
if (tf3_lookup_transform(_tf, "map", "base_link", sec, nsec, ref t, ref err))
return;
await Task.Delay(100, ct);
}
throw new InvalidOperationException("cây TF map→base_link chưa sẵn sàng sau 10 s");
}
```
### 12b.4. Bốn lỗi TF hay gặp
| Triệu chứng | Nguyên nhân |
|---|---|
| Costmap không cập nhật, không log lỗi rõ | Thiếu `map` → `odom` hoặc `odom` → `base_link` |
| Laser vẽ lệch, vật cản trôi | Sai transform tĩnh `base_link` → `laser_frame`, hoặc bơm nhầm `isStatic = false` rồi để hết hạn |
| Depth camera không clear được | Thiếu transform tới **optical frame**, hoặc stamp của mẫu nằm ngoài cache |
| Pose nhảy / robot lệch dần | Hai nguồn cùng bơm một transform, hoặc `cacheTimeSec` quá ngắn so với độ trễ sensor |
### 12b.5. Vòng đời
`tf3_buffer_destroy` gọi **sau cùng**, sau `navigation_destroy` — lõi còn tham chiếu buffer cho tới
lúc đó. Thứ tự đầy đủ ở mục 5.
---
## 13. Ánh xạ VDA5050 → C API
Sau đợt refactor 2026-08-10, ranh giới rất gọn: **lõi hiểu order và action; host chỉ dịch, không diễn
giải**. Bảng dưới là toàn bộ đường đi.
### 13.1. Bảng ánh xạ
| Message / action VDA5050 | Gọi gì | Ghi chú |
|---|---|---|
| `order` mới | `navigation_move_to_order_v2(orderId, orderUpdateId, nodes, edges, goal)` | `orderUpdateId` = 0 cho order đầu |
| `order` cập nhật (release thêm horizon) | `navigation_move_to_order_v2` — **cùng `orderId`**, `orderUpdateId` tăng | Mission layer nối tiếp, không dựng lại tuyến |
| Node action (`PickUp`, `charge`, `wait`, …) | *không gọi gì thêm* — nằm trong `nodes[i].actions` | Lõi tự khai triển qua compound action |
| `instantActions` (mọi action **không** thuộc ba dòng dưới) | `navigation_execute_instant_actions(actions, count)` | **Gửi cả lô một lần**, xem mục 11.8 |
| `instantActions` → `cancelOrder` | `navigation_cancel()` | Lái hàng đợi, **không** route qua `execute_instant_actions` |
| `instantActions` → `startPause` | `navigation_pause()` | như trên |
| `instantActions` → `stopPause` | `navigation_resume()` | như trên |
| Giới hạn tốc độ từ fleet / tầng an toàn | `navigation_set_twist_linear` ×2 (dấu chọn chiều) + `_angular` | Xem mục 6.6 |
| `state` báo về fleet | `navigation_get_state` + `navigation_get_twist` + `navigation_get_robot_pose_2d` | Xem 13.3 |
**Ba action lái hàng đợi phải tách riêng.** Chúng không phải việc *nằm trong* hàng đợi mà là lệnh
*điều khiển* hàng đợi. Đẩy chúng qua `execute_instant_actions` là xếp một lệnh huỷ vào sau chính thứ
nó định huỷ.
### 13.2. Vòng dịch một message `instantActions`
```csharp
public async Task<bool> OnInstantActionsAsync(IReadOnlyList<Vda5050Action> msg)
{
// 1. Tách ba action lái hàng đợi ra trước.
foreach (var a in msg)
{
switch (a.ActionType)
{
case "cancelOrder": navigation_cancel(_nav); await WaitLeftControllingAsync(); return true;
case "startPause": navigation_pause(_nav); return true;
case "stopPause": navigation_resume(_nav); return true;
}
}
// 2. Phần còn lại đi CẢ LÔ xuống lõi — không gọi từng cái.
var native = msg.Select(BuildNativeAction).ToArray();
bool accepted = navigation_execute_instant_actions(_nav, native, (UIntPtr)native.Length);
// 3. false = từ chối thẳng. Báo FAILED ngay, đừng chờ kết quả sẽ không tới.
if (!accepted)
{
ReportActionsFailed(msg, "rejected by navigation core");
return false;
}
return true; // theo dõi tiếp bằng vòng poll state
}
```
`cancelOrder` cần chờ lõi rời `CONTROLLING` trước khi báo `FINISHED` — lệnh chỉ được ghi nhận, hiệu
lực ở cycle sau (≤ 33 ms @ 30 Hz):
```csharp
private async Task WaitLeftControllingAsync(int timeoutMs = 5000)
{
var sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < timeoutMs)
{
if (!navigation_get_state(_nav, out var s)) return;
if (s != NavigationState.CONTROLLING) return;
await Task.Delay(100);
}
}
```
### 13.3. Báo trạng thái ngược lên fleet
Không có báo cáo theo từng action. Nguồn duy nhất là trạng thái chung:
| `navigation_get_state` | `actionStatus` VDA5050 | `driving` |
|---|---|---|
| `PENDING` | `WAITING` | false |
| `ACTIVE` | `RUNNING` | false |
| `PLANNING` | `RUNNING` | false |
| `CONTROLLING` | `RUNNING` | **true** |
| `SUCCEEDED` | `FINISHED` | false |
| `ABORTED`, `REJECTED`, `LOST` | `FAILED` | false |
| `PREEMPTED`, `PREEMPTING` | `FAILED` | false |
| `PAUSED` | giữ nguyên trạng thái trước, `paused = true` | false |
Hai điều phải nhớ:
- **Giữa hai chặng của một order nhiều node, lõi cố ý báo `ACTIVE`** thay vì `SUCCEEDED`/`PENDING`.
Nhờ vậy suy "order xong" từ `SUCCEEDED` vẫn đúng. Đừng đi vòng qua lớp che này.
- **Ánh xạ này chỉ không nhập nhằng khi hàng đợi có đúng một việc.** Nó đúng chừng nào fleet master
gửi mỗi lần một message và không chen instantActions vào giữa một order đang chạy.
### 13.4. Vocabulary phải khớp ba nơi
Một `actionType` chỉ chạy được khi tên của nó khớp ở cả ba chỗ:
| Nơi | File | Vai trò |
|---|---|---|
| Fleet master | — | Gửi `actionType` |
| Bảng compound action | `compound_actions_params.yaml` | Khai triển thành chuỗi chặng (`profile`, `marker`, `action`) |
| Bảng handler | `action_handlers_params.yaml` | Chạy các action nguyên tử mà chuỗi trên sinh ra |
Lệch tên là action bị từ chối tại cửa. Lưu ý cái bẫy đã ghi trong chính YAML: **compound action
(`PickUp`, `charge`) KHÔNG được khai trong `action_handlers_params.yaml`** — adapter đã dịch chúng
thành chuỗi chặng và gỡ khỏi danh sách action; thứ tới được `ActionRunner` là các action nguyên tử do
chuỗi đó sinh ra (`LiftFork`, `startCharging`).
---
## 14. Triển khai lên robot
Mục 2 nói *cần biến môi trường nào*. Mục này nói *đặt chúng ở đâu khi chạy thật*, vì đây là chỗ ghép
hay hỏng nhất và hỏng im lặng.
### 14.1. `launchSettings.json` không áp dụng cho robot
`Properties/launchSettings.json` chỉ có tác dụng với `dotnet run` khi phát triển. `dotnet publish`
**không đóng gói nó** và runtime không đọc nó ở môi trường Production. Đặt biến môi trường ở đó rồi
kết luận "đã cấu hình xong" là sai.
Robot chạy qua systemd, nên biến phải nằm trong unit file:
```ini
[Service]
Environment=PNKX_NAV_CORE_CONFIG_DIR=/opt/robotnet/navcore/config/runtime
Environment=PNKX_NAV_CORE_LIBRARY_PATH=/opt/robotnet/navcore/lib
```
Không đặt thì `robot::NodeHandle` rơi xuống nhánh cuối — dò `../../config`, `../config`, `config`
tương đối với `/proc/self/exe`. Không có cây config nào ở đó, nên `findLibraryPath("MoveBase")` trả
rỗng và `navigation_create()` trả `NULL`.
### 14.2. `ProtectHome=true` chặn mọi đường dẫn `/home`
Unit file có hardening thường bật sẵn:
```ini
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/dev/shm /var/log/robotnet /opt/robotnet/robotapp
```
`ProtectHome=true` làm `/home` **không truy cập được** với tiến trình. Mọi đường dẫn `/home/...` —
kể cả đường build của máy dev — đều vô dụng trên robot. `ProtectSystem=strict` giữ phần còn lại ở
chế độ chỉ đọc nhưng **vẫn đọc được**, nên cài ngoài `/home` là đủ.
### 14.3. Bố cục cài đặt
```
/opt/robotnet/navcore/lib/ libnav_c_api.so
libmove_base2.so
toàn bộ plugin planner / recovery / costmap
/opt/robotnet/navcore/config/runtime/ bản chép của Test/move_base2/config/runtime
```
Thêm `/opt/robotnet/navcore/lib/libnav_c_api.so` vào danh sách candidate của `DllImportResolver` để
không phụ thuộc hoàn toàn vào `LD_LIBRARY_PATH`.
### 14.4. Xác minh đang nạp đúng runtime
`navigation_create()` in đường dẫn `.so` đã resolve. Dòng này ở cấp `debug` nhưng `robot_cpp`
**không lọc theo cấp**, nên nó luôn hiện:
```
navigation_create: loading navigation plugin from '/…/libmove_base2.so'
```
```bash
journalctl -u <service> | grep "loading navigation plugin"
```
Thấy `libmove_base2.so` là đúng runtime mới. Thấy `libmove_base.so` là đang chạy bản cũ — xảy ra khi
`PNKX_NAV_CORE_CONFIG_DIR` trỏ vào cây `pnkx_nav_core/config`, nơi `move_base_common_params.yaml` ghi
`library_path: libmove_base`.
**Cả hai `.so` đều export alias `MoveBase`, nên nạp nhầm KHÔNG sinh lỗi nào** — host chạy bình thường
với runtime cũ. Đây là lý do phải kiểm bằng dòng log này thay vì suy đoán từ hành vi.
---
## 15. Checklist nghiệm thu
Chạy theo đúng thứ tự. Mỗi bước là điều kiện của bước sau; đừng nhảy cóc.
### Tầng 0 — môi trường
- [ ] `nm -D --defined-only libnav_c_api.so | grep " T " | wc -l` → **62**
- [ ] `.so` và plugin nằm ngoài `/home` nếu chạy dưới systemd có `ProtectHome`
- [ ] `PNKX_NAV_CORE_CONFIG_DIR` trỏ vào cây `move_base2` (`.../config/runtime`)
- [ ] `PNKX_NAV_CORE_LIBRARY_PATH` chứa `libmove_base2.so` + toàn bộ plugin
- [ ] Log khởi động in `loading navigation plugin from '…libmove_base2.so'` (mục 14.4)
### Tầng 1 — vòng đời
- [ ] `navigation_create` trả handle khác `NULL`
- [ ] Footprint và static map được bơm **trước** `initialize` (mục 3)
- [ ] `navigation_initialize_checked` trả `true`; nếu `false` thì `navigation_get_status_text` nói rõ
pha nào hỏng
- [ ] Log in `control thread running at 30.00 Hz`
- [ ] Tắt: `shutdown` trả về trong ~1 s, `destroy` không treo, không crash khi thoát
### Tầng 2 — dữ liệu vào
- [ ] Bộ đếm `SensorGatewayStats` tăng cho từng nguồn đang bơm
- [ ] `dropped_no_costmap` = 0 sau khi initialize xong
- [ ] Tên topic khớp `costmap_common_params.yaml` (mục 4)
- [ ] Odometry bơm đều theo nhịp nguồn, không thưa
### Tầng 3 — điều khiển
- [ ] Goal đơn qua `navigation_move_to`: state đi `PLANNING` → `CONTROLLING` → `SUCCEEDED`
- [ ] `navigation_get_twist` có stamp tiến và giá trị khác 0 khi đang chạy
- [ ] `navigation_pause` → state `PAUSED` trong ≤ 1 cycle; `resume` chạy tiếp
- [ ] `navigation_cancel` → rời `CONTROLLING`, robot dừng
- [ ] `set_twist_linear(+v)` rồi `(−v)`: tốc độ thật khớp trần đặt ra ở **cả hai chiều**
### Tầng 4 — order và action
- [ ] Order nhiều node qua `navigation_move_to_order_v2`: chạy hết các chặng, state báo `ACTIVE` giữa
hai chặng (không phải `SUCCEEDED` sớm)
- [ ] Order update: cùng `orderId`, `orderUpdateId` tăng → nối tiếp, không dựng lại tuyến
- [ ] Node action (`PickUp`) sinh đúng chuỗi chặng theo `compound_actions_params.yaml`
- [ ] `navigation_execute_instant_actions` với **cùng action đó** sinh ra **cùng chuỗi chặng**
- [ ] `cancelOrder` / `startPause` / `stopPause` đi qua `cancel`/`pause`/`resume`, **không** qua
`execute_instant_actions`
- [ ] Action lạ bị từ chối và báo `FAILED` kèm `actionNotSupported`, không im lặng
### Tầng 5 — bộ nhớ và ổn định
- [ ] Chạy 1 giờ với đủ 4 timer hiển thị: RSS không tăng đều
- [ ] Mọi `feed_back_str` / `status_text` được free bằng `nav_c_api_free_string`
- [ ] Mọi getter grid/scan/cloud/plan có `navigation_free_*` đi kèm
- [ ] Mỗi consumer `PlannerDataOutput` dùng struct **riêng**, không chia sẻ giữa hai timer
### Tầng 6 — depth camera (nếu dùng)
- [ ] `navigation_add_depth_camera_data` bơm vào đúng topic `data_type: DepthCameraData`
- [ ] TF từ optical frame tới base frame có tại đúng `header.stamp`
- [ ] Vật cản ma trong FOV **biến mất** sau vài chu kỳ — đây là thứ point cloud không làm được

View File

@@ -180,6 +180,17 @@ Twist2DStamped convert2CTwist2DStamped(const robot_nav_2d_msgs::Twist2DStamped&
*/
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

View File

@@ -196,57 +196,16 @@ extern "C"
*/
bool navigation_move_to_nodes_edges(NavigationHandle handle, const Node *nodes, size_t node_count, const Edge *edges, size_t edge_count, const PoseStamped goal);
/**
* @brief Send a docking goal to a predefined marker
* @param handle Navigation handle
* @param marker Marker name or ID (null-terminated string)
* @param goal Target pose for docking
* @return true if docking command succeeded
*/
bool navigation_dock_to(NavigationHandle handle, const char *marker, const PoseStamped goal);
/**
* @brief Send a docking goal to a predefined marker
* @param handle Navigation handle
* @param order Order message
* @param goal Target pose for docking
* @return true if docking command succeeded
*/
bool navigation_dock_to_order(NavigationHandle handle, const Order order, const char *marker, const PoseStamped goal);
/**
* @brief Send a goal for the robot to navigate to
* @param handle Navigation handle
* @param marker Marker name or ID (null-terminated string)
* @param nodes Nodes array
* @param node_count Number of nodes in the array
* @param edges Edges array
* @param edge_count Number of edges in the array
* @param goal Target pose in the global frame
* @return true if goal was accepted and sent successfully
*/
bool navigation_dock_to_nodes_edges(NavigationHandle handle, const char *marker, const Node *nodes, size_t node_count, const Edge *edges, size_t edge_count, const PoseStamped goal);
/**
* @brief Move straight along the robot's current heading.
* @param handle Navigation handle
* @param distance [m] Positive moves forward, negative backward.
* @return true if command issued successfully
/*
* navigation_dock_to, navigation_dock_to_order, navigation_dock_to_nodes_edges,
* navigation_move_straight_to and navigation_rotate_to were removed. They pushed a goal past
* the mission layer, which left them free to replace the leg the mission queue was running
* while the queue kept handing out the next leg of a route the robot had already left.
*
* @note The goal is built from the robot's pose **at the moment of the call**, so TF must already
* be available. Returns false if the pose cannot be read.
* Docking, go-straight and rotate are now ordinary legs of an order: set `profile:` on the leg
* (`docking | go_straight | rotate`) and `marker` for docking, then send the order through
* navigation_move_to_order() or navigation_move_to_nodes_edges().
*/
bool navigation_move_straight_to(NavigationHandle handle, const double distance);
/**
* @brief Rotate in place to align with a target orientation.
* @param handle Navigation handle
* @param goal Target pose — only its orientation is used. Passed **by value as a struct**, not
* as a yaw angle; an invalid quaternion is rejected.
* @return true if rotation command was sent successfully
*/
bool navigation_rotate_to(NavigationHandle handle, const PoseStamped goal);
/**
* @brief Pause the robot's movement

View File

@@ -20,7 +20,7 @@
* - navigation_get_status_text() — the core's own explanation, for logging.
* - navigation_add_depth_camera_data() — the depth-camera input path, never exposed before.
* - navigation_move_to_order_v2() — an order carrying a real orderId / orderUpdateId.
* - navigation_dock_to_order_v2() — same, for docking.
* - navigation_execute_instant_actions() — a VDA5050 instantActions message, expanded like node actions.
*
* Include this header **in addition to** nav_c_api.h. It adds symbols; it replaces none.
*
@@ -241,25 +241,47 @@ extern "C"
const Edge *edges, size_t edge_count,
const PoseStamped goal);
/**
* @brief Docking counterpart of navigation_move_to_order_v2().
*
* @param handle Navigation handle.
* @param marker Docking marker name or id. Must not be NULL.
* @param order_id VDA5050 orderId. Must not be NULL or empty.
* @param order_update_id VDA5050 orderUpdateId.
* @param nodes Node array; the host keeps ownership.
* @param node_count Number of nodes.
* @param edges Edge array; the host keeps ownership.
* @param edge_count Number of edges.
* @param goal Docking pose.
* @return true if the docking order was accepted.
/*
* navigation_dock_to_order_v2 was removed. Docking is a per-leg property of the order now: set
* `profile: docking` and `marker` on the leg, then send it through navigation_move_to_order_v2.
*/
bool navigation_dock_to_order_v2(NavigationHandle handle, const char *marker,
const char *order_id, uint32_t order_update_id,
const Node *nodes, size_t node_count,
const Edge *edges, size_t edge_count,
const PoseStamped goal);
/**
* @brief Run one VDA5050 `instantActions` message — the whole list, as one batch.
*
* Each action is expanded against the same compound-action table that node actions use, so
* `PickUp` sent as an instantAction produces the same detect / approach / lift / back-out
* sequence it produces inside an order. One vocabulary, one set of handlers, one meaning per
* actionType regardless of how it arrived.
*
* Pass the message's actions together rather than calling this once per action: a second `HARD`
* action submitted on its own preempts and wipes the legs of the first, so two actions sent in
* one message would eat each other.
*
* Execution stops at the first leg that fails and the rest of the message is dropped with it, so
* the caller reports ONE outcome for the message — which is all VDA5050 asks for.
*
* `blockingType` decides how the batch meets a running order: any `HARD` action makes the whole
* message preempt it, otherwise it queues behind it. `NONE` requests execution in parallel with
* driving, which this runtime cannot do — it is queued instead and the narrowing is logged. An
* unset or unknown blockingType is treated as `HARD`, the safe direction.
*
* Do NOT route `cancelOrder`, `startPause` or `stopPause` here. Those steer the queue rather
* than being work in it: call navigation_cancel(), navigation_pause() and navigation_resume().
*
* Progress is reported through the ordinary state, not per action: poll navigation_get_state()
* and map ACTIVE/CONTROLLING to RUNNING, SUCCEEDED to FINISHED, ABORTED/PREEMPTED to FAILED.
* That mapping is only unambiguous while this message is the only work in the queue, which holds
* as long as the fleet master sends one message at a time and none during an order.
*
* @param handle Navigation handle.
* @param actions Array of actions, in the order received. The host keeps ownership.
* @param count Number of actions. Must be > 0.
* @return true if the message was accepted. false means rejected outright — report it failed
* rather than waiting for a result that will not come.
*/
bool navigation_execute_instant_actions(NavigationHandle handle, const Action *actions,
size_t count);
// ============================================================================================
// Releasing what the getters allocate

View File

@@ -1,6 +1,9 @@
# Báo cáo ghép khung C# (RobotNet12) với move_base2 qua nav_c_api_2
- **Ngày:** 2026-08-10 · **Đối chiếu lại:** 2026-08-10 (xem mục 1b)
- **Ngày:** 2026-08-10 · **Đối chiếu lại:** 2026-08-10 (mục 1b) · **Cập nhật theo API mới:** 2026-08-10 tối (mục 1c)
> ⚠ **API đã đổi sau khi bản đầu được viết.** Năm hàm bị xoá, một hàm mới thêm vào. Đây là thay đổi
> **phá vỡ tương thích** và RobotNet12 **đang gọi 4/5 hàm đã xoá**. Đọc **mục 1c trước** mọi mục khác.
- **Phạm vi:** RobotApp `Modules/Navigation` (P/Invoke binding + client + integration service) ghép với `libnav_c_api.so` build từ `pnkx_nav_core` chạy runtime `libmove_base2.so`.
- **Nguồn đối chiếu (đã kiểm tra thực tế):**
- `T800_ws/src/AMR_T800/pnkx_nav_core/src/APIs/c_api/include/nav_c_api.h`, `nav_c_api_2.h`
@@ -10,6 +13,11 @@
- `RobotNet12/RobotApp/RobotNet12.RobotApp/Modules/Navigation/*.cs`
- `RobotNet12/RobotApp/RobotNet12.RobotApp/systemd/robotnet-robotapp.service` *(bổ sung ở lần đối chiếu lại — đây là cách robot thật khởi động)*
> **Đây là bản kiểm điểm một thời điểm**, gắn với trạng thái `RobotNet12` ngày 2026-08-10. Nó liệt kê
> lỗi đang có và sẽ cũ đi khi những lỗi đó được sửa. Phần **hướng dẫn ghép bền vững** — kiến trúc host,
> ánh xạ VDA5050, triển khai systemd, checklist nghiệm thu — nằm ở **Guide mục 12–15**; sửa xong danh
> sách dưới đây thì dùng Guide, không dùng file này.
>
> **Bản này tồn tại ở hai chỗ, nội dung giống hệt nhau:**
> `T800_ws/.../c_api/nav-c-api-2-csharp-integration-report.md` và
> `RobotNet12/docs/nav-c-api-2-csharp-integration-report.md`. Sửa một bên thì đồng bộ bên kia, nếu
@@ -55,6 +63,106 @@ của RobotApp là bản khác và tốt hơn: `navigation_rotate_to` nhận `Po
---
## 1c. API đã đổi — nhóm E (mới, ưu tiên cao nhất)
Đọc lại mã nguồn ngày 2026-08-10 tối. So với thời điểm viết bản đầu, bề mặt API đã đổi: **62 symbol**
thay vì 64 (`nm -D` trên `build/libnav_c_api.so`, build 20:19).
### E1. Năm hàm bị XOÁ — RobotNet12 đang gọi 4/5
| Hàm | Còn trong `.so`? | RobotNet12 dùng ở đâu |
|---|---|---|
| `navigation_dock_to` | **không** | khai `NavigationNativeInterface.cs:246` · gọi `NavigationClient.cs:1053` · wrapper `DockTo()` `:970` · caller `NavigationIntegrationService.cs:836` |
| `navigation_dock_to_order` | **không** | khai `:502` · gọi `NavigationClient.cs:1150` · wrapper `DockToOrder()` `:1134` · caller `NavigationIntegrationService.cs:854` |
| `navigation_dock_to_nodes_edges` | **không** | *không dùng* |
| `navigation_move_straight_to` | **không** | khai `:260` · gọi `NavigationClient.cs:1179` · wrapper `MoveStraightTo()` `:1169` · caller `NavigationIntegrationService.cs:882` **và** `Endpoints/NavigationTestEndpoints.cs:83` |
| `navigation_rotate_to` | **không** | khai `:273` · gọi `NavigationClient.cs:1209` · wrapper `RotateTo()` `:1196` · caller `NavigationIntegrationService.cs:901` **và** `Endpoints/NavigationTestEndpoints.cs:126` |
Cả năm đã bị gỡ khỏi contract `BaseNavigation` (`move_base_core/navigation.h`), khỏi `move_base`,
`move_base2`, `nav_c_api`, `nav_c_api_2`, và khỏi host ROS (`amr_control`). **Gọi là
`EntryPointNotFoundException`** — không phải lỗi biên dịch, nên nó chỉ nổ lúc chạy, ở đúng lần dock
hoặc lần đi thẳng đầu tiên.
**Phải xoá ở C#:** 4 khai báo `DllImport`, 4 wrapper public, 6 call site (4 trong
`NavigationIntegrationService`, 2 trong `NavigationTestEndpoints`).
### E2. Năng lực không mất — nó chuyển vào compound action
Docking, đi thẳng, quay tại chỗ giờ là **thuộc tính của từng chặng** khai trong
`Test/move_base2/config/runtime/compound_actions_params.yaml`:
```yaml
PickUp:
steps:
- {action: detect}
- {move_to: dock_target, profile: docking, marker: trolley}
- {action: LiftFork}
- {move: -0.5, profile: go_straight}
UnDockFromStation:
steps:
- {move: -1.0, profile: go_straight}
- {move: 0.0, profile: rotate}
```
`profile` ∈ `position | docking | go_straight | rotate`; `marker` **chỉ hợp lệ với
`profile: docking`**, chọn override trong `maker_sources.yaml`.
Host gửi **tên action** thay vì gọi động tác:
| Đường | Hàm | Khi nào |
|---|---|---|
| Action trong node của order | `navigation_move_to_order_v2` | Fleet giao tuyến có action giữa đường |
| `instantActions` ngoài order | `navigation_execute_instant_actions` **(mới)** | Fleet hoặc HMI yêu cầu ngay |
**Vì sao đổi:** ba hàm cũ đi thẳng xuống lõi, **không qua mission layer** — chúng preempt order đang
chạy trong im lặng. `UnDockFromStation` gọi `moveStraightTo` là ca đã gặp thật. Đường mới đưa mọi
chuyển động về chung một hàng đợi, chung đường huỷ, chung đường báo kết quả.
### E3. Hàm mới `navigation_execute_instant_actions`
```c
bool navigation_execute_instant_actions(NavigationHandle handle, const Action *actions, size_t count);
```
Chạy trọn một message `instantActions` như **một lô**. Dùng `Action` — struct C **đã có sẵn**
(`protocol_msgs/Action.h`), không phải khai struct mới.
Bốn ràng buộc, đầy đủ ở Guide §11.8:
1. **Gửi cả lô một lần.** Gọi từng action riêng thì action `HARD` sau sẽ preempt và xoá chặng của
action trước — hai action cùng message ăn nhau.
2. **`blockingType` quyết định cách gặp order đang chạy.** Có `HARD` → preempt cả message; `SOFT` →
xếp hàng; `NONE` → runtime không chạy song song được nên **bị hạ xuống xếp hàng** và ghi log; không
khai / không hiểu → coi như `HARD`.
3. **Không route `cancelOrder` / `startPause` / `stopPause` qua đây** — chúng lái hàng đợi, không nằm
trong hàng đợi. Vẫn dùng `navigation_cancel()` / `_pause()` / `_resume()`.
4. **Một kết quả cho cả message.** Dừng ở chặng lỗi đầu tiên, phần còn lại bị bỏ. Theo dõi bằng
`navigation_get_state`: `ACTIVE`/`CONTROLLING` → RUNNING, `SUCCEEDED` → FINISHED,
`ABORTED`/`PREEMPTED` → FAILED. Ánh xạ chỉ đúng khi message là việc duy nhất trong hàng đợi.
Điều này **thay thế** đường instant action mà mục 6 của báo cáo trước mô tả là "host tự dịch từng
actionType". Nay chỉ ba action điều khiển hàng đợi còn phải tự dịch; phần còn lại đẩy nguyên lô.
### E4. Ảnh hưởng tới các mục khác của báo cáo
| Mục | Ảnh hưởng |
|---|---|
| §4 nhóm B | Danh sách 13 `DllImport` đổi: **bỏ** `navigation_dock_to_order_v2`, **thêm** `navigation_execute_instant_actions`. Vẫn đúng 13 hàm. 4 struct mới không đổi |
| §5 C4 | `navigation_dock_to_order_v2` không còn tồn tại — bỏ khỏi khuyến nghị |
| Guide | Đã cập nhật: §0 (9 việc), §6.4 (5 hàm xoá + mô hình mới), §11.8 (thay bằng instant actions), Phụ lục A (62 symbol), Phụ lục B.2 |
| **Guide §12–15 (mới)** | Phần ghép bền vững: **§12** kiến trúc host + khung `NavigationHost` + mô hình thread · **§13** ánh xạ VDA5050 → C API (gồm ba action lái hàng đợi phải tách riêng) · **§14** triển khai systemd, `ProtectHome`, bố cục cài, xác minh runtime · **§15** checklist nghiệm thu 7 tầng |
### E5. Tài liệu test thủ công của RobotNet12 đã cũ
`RobotApp/RobotNet12.RobotApp/Modules/Navigation/navigation-capi-manual-test-guide.md` viết cho
`navigation_move_straight_to` và `navigation_rotate_to` — cả hai **không còn tồn tại**. Mục 2 và 3 của
file đó không chạy được nữa. Viết lại theo đường mới: chuyển động thẳng/quay giờ là chặng
`profile: go_straight | rotate` bên trong một action, gọi qua `navigation_execute_instant_actions`
hoặc nằm trong node của order. Mẫu nghiệm thu ở Guide §15 tầng 3–4.
---
## 2. Phía move_base2 / nav_c_api_2 — cần thay đổi gì?
**Không có thay đổi bắt buộc.** Ba mục dưới đây không chặn việc ghép:
@@ -167,7 +275,7 @@ dò theo `PNKX_NAV_CORE_CONFIG_DIR` → `PNKX_NAV_CORE_DIR/config` → các đư
Toàn bộ phần thêm nằm sẵn ở **Guide Phụ lục B** (đã đối chiếu đúng với `.so` và header):
- **4 struct mới** (B.1): `RegionOfInterest`, `Image`, `CameraInfo`, `DepthCameraData` — layout khớp header C từng field. Đặt vào `NavigationInterop.cs`.
- **13 `DllImport` mới** (B.2): `navigation_initialize_checked`, `navigation_is_ready`, `navigation_shutdown`, `navigation_get_state`, `navigation_get_status_text`, `navigation_add_depth_camera_data`, `navigation_move_to_order_v2`, `navigation_dock_to_order_v2`, `navigation_free_occupancy_grid`, `navigation_free_laser_scan`, `navigation_free_point_cloud`, `navigation_free_point_cloud2`, `navigation_free_planner_data`. Đặt vào `NavigationNativeInterface.cs` — **sau khi đã xoá 2 khai báo trùng tên ở A3**.
- **13 `DllImport` mới** (B.2): `navigation_initialize_checked`, `navigation_is_ready`, `navigation_shutdown`, `navigation_get_state`, `navigation_get_status_text`, `navigation_add_depth_camera_data`, `navigation_move_to_order_v2`, `navigation_execute_instant_actions`, `navigation_free_occupancy_grid`, `navigation_free_laser_scan`, `navigation_free_point_cloud`, `navigation_free_point_cloud2`, `navigation_free_planner_data`. Đặt vào `NavigationNativeInterface.cs` — **sau khi đã xoá 2 khai báo trùng tên ở A3**.
---
@@ -232,7 +340,7 @@ Không để `navigation_destroy` rơi vào finalizer/GC.
### C4. Nên làm thêm (không bắt buộc để chạy)
- `navigation_add_depth_camera_data` cho `/camera/depth/data` và `/camera_right/depth/data` — đường duy nhất bật clear theo frustum (xoá vật cản ma). Point cloud không thay thế được. Mẫu code ghim mảng: Guide Phụ lục B.3.
- `navigation_move_to_order_v2` / `navigation_dock_to_order_v2` nếu fleet gửi order update (cùng `orderId`, `orderUpdateId` tăng). `navigation_move_to_nodes_edges` (đang dùng 6 chỗ) không mang được định danh — mọi lời gọi là order mới.
- `navigation_move_to_order_v2` nếu fleet gửi order update (cùng `orderId`, `orderUpdateId` tăng). `navigation_move_to_nodes_edges` (đang dùng 6 chỗ) không mang được định danh — mọi lời gọi là order mới.
---
@@ -335,7 +443,10 @@ trước khi cho chạy tự động.**
## 7. Thứ tự thi công đề xuất
1. **Nhóm D1 + D2 + D3 (môi trường)** — làm **trước tiên**, không phải bước 3 như bản đầu. Chưa có
0. **Nhóm E (API đã đổi)** — xoá 4 khai báo + 4 wrapper + 6 call site của các hàm không còn tồn tại,
rồi thêm `navigation_execute_instant_actions`. Không làm bước này thì dock/đi thẳng/quay ném
`EntryPointNotFoundException` lúc chạy.
1. **Nhóm D1 + D2 + D3 (môi trường)** — làm **ngay sau E**, không phải bước 3 như bản đầu. Chưa có
biến môi trường đúng thì `navigation_create()` trả `NULL` và mọi việc sau đó không kiểm chứng
được. Trên robot còn phải giải quyết `ProtectHome` trước khi bàn tới code.
2. Nhóm A (sửa binding sai/chết) — A3 làm trước A1/A2 để tránh trùng tên symbol; A6 đi cùng A5.
@@ -345,7 +456,8 @@ trước khi cho chạy tự động.**
6. Chạy thử: xác minh dòng log `loading navigation plugin from '…libmove_base2.so'` (D4) → khởi tạo →
`initialize_checked` trả `true` → gửi goal đơn → pause/cancel → tắt sạch. Sau đó mới bật depth
camera và order_v2 (C4).
7. Kiểm thử thực tế các mục Guide §10 chưa xác nhận: depth camera path, `move_straight_to` lùi.
7. Kiểm thử thực tế các mục Guide §10 chưa xác nhận: đường depth camera; và đường instant action mới
(E3) — `PickUp` gửi dạng instantAction phải sinh ra đúng chuỗi chặng như khi nó nằm trong order.
---
@@ -353,10 +465,11 @@ trước khi cho chạy tự động.**
| File | Việc |
|---|---|
| `Modules/Navigation/NavigationNativeInterface.cs` | A1–A5, B (13 DllImport) |
| `Modules/Navigation/NavigationNativeInterface.cs` | **E1 (xoá 4 `DllImport` của hàm đã xoá)**, A1–A5, B (13 `DllImport`, nay gồm `navigation_execute_instant_actions` thay cho `navigation_dock_to_order_v2`) |
| `Modules/Navigation/NavigationInterop.cs` | B (4 struct mới) |
| `Modules/Navigation/NavigationClient.cs` | A1/A2 (footprint), **A6 (đọc env + bỏ hardcode `:49-52`)**, C1 (initialize_checked), C2 (shutdown trong Dispose), C3 |
| `Modules/Navigation/NavigationIntegrationService.cs` | C1 (đảo thứ tự map/footprint/initialize), C2 (chen shutdown), C3.4 (bỏ vòng poll IsReady) |
| `Modules/Navigation/NavigationClient.cs` | **E1 (xoá 4 wrapper `DockTo`/`DockToOrder`/`MoveStraightTo`/`RotateTo`)**, A1/A2 (footprint), **A6 (đọc env + bỏ hardcode `:49-52`)**, C1 (initialize_checked), C2 (shutdown trong Dispose), C3 |
| `Modules/Navigation/NavigationIntegrationService.cs` | **E1 (4 call site `:836`, `:854`, `:882`, `:901`)**, C1 (đảo thứ tự map/footprint/initialize), C2 (chen shutdown), C3.4 (bỏ vòng poll IsReady) |
| **`Endpoints/NavigationTestEndpoints.cs`** | **E1 — 2 call site `MoveStraightTo`/`RotateTo` (`:83`, `:126`) trỏ vào hàm đã xoá** |
| `Properties/launchSettings.json` | D1 — **chỉ có tác dụng trên máy dev** |
| **`RobotApp/RobotNet12.RobotApp/systemd/robotnet-robotapp.service`** | **D2 (thêm 2 dòng `Environment=`), D3 (bố cục cài đặt ngoài `/home`)** — file này bản đầu không nhắc tới, nhưng đây mới là thứ quyết định trên robot |
| *(triển khai, không phải mã nguồn)* | D3 — chép `.so` + plugin vào `/opt/robotnet/navcore/lib`, cây config vào `/opt/robotnet/navcore/config/runtime` |
@@ -368,4 +481,5 @@ trước khi cho chạy tự động.**
| Ngày | Nội dung |
|---|---|
| 2026-08-10 | Bản đầu: mục 1–8 |
| 2026-08-10 tối | **Đọc lại mã sau đợt refactor.** Thêm **mục 1c / nhóm E**: 5 hàm dock/straight/rotate bị xoá khỏi API (RobotNet12 đang gọi 4/5), năng lực chuyển vào compound action `profile`+`marker`, hàm mới `navigation_execute_instant_actions`. Cập nhật §4, §5 C4, §7 (E lên bước 0), §8. Guide cập nhật đồng bộ |
| 2026-08-10 | **Đối chiếu lại trên mã RobotNet12 thật + `nm`.** Thêm mục **1b** (bảng kiểm chứng, 9/9 khẳng định đúng); thêm **A6**; viết lại **mục 6** thành D1–D5 sau khi phát hiện `launchSettings.json` không áp dụng cho robot và `ProtectHome=true` chặn `/home`; đảo thứ tự thi công (môi trường lên bước 1); bổ sung unit file vào bảng mục 8; đánh dấu §2.3 đã sửa trong Guide |

View File

@@ -568,7 +568,7 @@ static Trajectory convert2CTrajectory(const robot_protocol_msgs::Trajectory& cpp
return c;
}
static robot_protocol_msgs::Action convert2CppAction(const Action& c)
robot_protocol_msgs::Action convert2CppAction(const Action& c)
{
robot_protocol_msgs::Action cpp;
cpp.actionType = c.actionType ? c.actionType : "";

View File

@@ -352,174 +352,13 @@ extern "C" bool navigation_move_to_nodes_edges(NavigationHandle handle, const No
}
}
extern "C" bool navigation_dock_to(NavigationHandle handle, const char *marker, const PoseStamped goal)
{
if (!handle || !marker)
{
return false;
}
if (!isQuaternionValid(goal.pose.orientation))
{
robot::log_error("Goal quaternion is invalid");
return false;
}
try
{
std::shared_ptr<robot::move_base_core::BaseNavigation> nav_ptr =
std::shared_ptr<robot::move_base_core::BaseNavigation>(
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
if (!nav_ptr)
return false;
robot_geometry_msgs::PoseStamped cpp_goal = convert2CppPoseStamped(goal);
return nav_ptr->dockTo(std::string(marker), cpp_goal);
}
catch (...)
{
return false;
}
}
extern "C" bool navigation_dock_to_order(NavigationHandle handle, const Order order, const char *marker, const PoseStamped goal)
{
if (!handle || !marker)
{
return false;
}
if (!isQuaternionValid(goal.pose.orientation))
{
robot::log_error("Goal quaternion is invalid");
return false;
}
try
{
std::shared_ptr<robot::move_base_core::BaseNavigation> nav_ptr =
std::shared_ptr<robot::move_base_core::BaseNavigation>(
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
if (!nav_ptr)
return false;
robot_protocol_msgs::Order cpp_order = convert2CppOrder(order);
robot_geometry_msgs::PoseStamped cpp_goal = convert2CppPoseStamped(goal);
return nav_ptr->dockTo(cpp_order, std::string(marker), cpp_goal);
}
catch (const std::exception &e)
{
robot::log_error("navigation_dock_to_order failed: %s", e.what());
return false;
}
catch (...)
{
robot::log_error("navigation_dock_to_order failed: unknown exception");
return false;
}
}
extern "C" bool navigation_dock_to_nodes_edges(NavigationHandle handle, const char *marker, const Node *nodes, size_t node_count, const Edge *edges, size_t edge_count, const PoseStamped goal)
{
if (!handle || !marker)
{
return false;
}
if (!isQuaternionValid(goal.pose.orientation))
{
robot::log_error("Goal quaternion is invalid");
return false;
}
try
{
std::shared_ptr<robot::move_base_core::BaseNavigation> nav_ptr =
std::shared_ptr<robot::move_base_core::BaseNavigation>(
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
if (!nav_ptr)
return false;
// Zero-init: see navigation_move_to_nodes_edges.
Order order{};
order.nodes = const_cast<Node *>(nodes);
order.nodes_count = node_count;
order.edges = const_cast<Edge *>(edges);
order.edges_count = edge_count;
robot_protocol_msgs::Order cpp_order = convert2CppOrder(order);
robot_geometry_msgs::PoseStamped cpp_goal = convert2CppPoseStamped(goal);
return nav_ptr->dockTo(cpp_order, std::string(marker), cpp_goal);
}
catch (const std::exception &e)
{
robot::log_error("navigation_dock_to_nodes_edges failed: %s", e.what());
return false;
}
catch (...)
{
robot::log_error("navigation_dock_to_nodes_edges failed: unknown exception");
return false;
}
}
extern "C" bool navigation_move_straight_to(NavigationHandle handle, const double distance)
{
if (!handle)
{
return false;
}
try
{
std::shared_ptr<robot::move_base_core::BaseNavigation> nav_ptr =
std::shared_ptr<robot::move_base_core::BaseNavigation>(
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
if (!nav_ptr)
return false;
// Goal được dựng TỪ pose hiện tại, nên TF phải sẵn sàng ngay lúc gọi. Không lấy được pose thì
// dừng ở đây — đi tiếp với pose mặc định là đi tới một điểm không ai yêu cầu.
robot_geometry_msgs::PoseStamped pose;
if (!nav_ptr->getRobotPose(pose))
{
robot::log_error("navigation_move_straight_to: no robot pose available (TF not ready?)");
return false;
}
robot_geometry_msgs::PoseStamped goal = robot::move_base_core::offset_goal(pose, distance);
robot::log_debug("navigation_move_straight_to: %.3f m from (%.3f, %.3f)", distance,
pose.pose.position.x, pose.pose.position.y);
return nav_ptr->moveStraightTo(goal);
}
catch (const std::exception &e)
{
robot::log_error("navigation_move_straight_to failed: %s", e.what());
return false;
}
catch (...)
{
return false;
}
}
extern "C" bool navigation_rotate_to(NavigationHandle handle, const PoseStamped goal)
{
if (!handle)
{
return false;
}
if (!isQuaternionValid(goal.pose.orientation))
{
robot::log_error("Goal quaternion is invalid");
return false;
}
try
{
std::shared_ptr<robot::move_base_core::BaseNavigation> nav_ptr =
std::shared_ptr<robot::move_base_core::BaseNavigation>(
reinterpret_cast<robot::move_base_core::BaseNavigation *>(handle), [](::robot::move_base_core::BaseNavigation *) {});
if (!nav_ptr)
return false;
robot_geometry_msgs::PoseStamped cpp_goal = convert2CppPoseStamped(goal);
return nav_ptr->rotateTo(cpp_goal);
}
catch (...)
{
return false;
}
}
// navigation_dock_to, navigation_dock_to_order, navigation_dock_to_nodes_edges,
// navigation_move_straight_to and navigation_rotate_to were removed along with the
// BaseNavigation methods they forwarded to. Those methods bypassed the mission layer, so a goal
// arriving through them replaced the leg the mission queue was running without the queue noticing.
// Docking, go-straight and rotate now travel as ordinary legs of an order: set `profile:` on the
// leg (`docking | go_straight | rotate`) plus `marker` for docking, then send it through
// navigation_move_to_order / navigation_move_to_nodes_edges.
extern "C" void navigation_pause(NavigationHandle handle)
{

View File

@@ -15,6 +15,7 @@
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <boost/make_shared.hpp>
@@ -270,40 +271,62 @@ extern "C" bool navigation_move_to_order_v2(NavigationHandle handle,
}
}
extern "C" bool navigation_dock_to_order_v2(NavigationHandle handle, const char *marker,
const char *order_id, uint32_t order_update_id,
const Node *nodes, size_t node_count,
const Edge *edges, size_t edge_count,
const PoseStamped goal)
extern "C" bool navigation_execute_instant_actions(NavigationHandle handle, const Action *actions,
size_t count)
{
if (!handle || !marker || order_id == nullptr || order_id[0] == '\0')
if (!handle || actions == nullptr || count == 0)
{
robot::log_error("navigation_dock_to_order_v2: null handle, marker or empty orderId");
robot::log_error("navigation_execute_instant_actions: null handle, null array or zero count");
return false;
}
if (!isQuaternionValid(goal.pose.orientation))
// Kiểm ở đây thay vì để adapter làm: bên kia ranh giới C, một con trỏ null và một chuỗi rỗng nhìn
// giống nhau, và thông báo lỗi phải nói được là phía gọi thiếu gì, ở phần tử nào.
std::vector<robot_protocol_msgs::Action> cpp_actions;
cpp_actions.reserve(count);
for (size_t i = 0; i < count; ++i)
{
robot::log_error("navigation_dock_to_order_v2: goal quaternion is invalid");
return false;
const Action &action = actions[i];
if (action.actionType == nullptr || action.actionType[0] == '\0')
{
robot::log_error("navigation_execute_instant_actions: action %zu has a null or empty "
"actionType", i);
return false;
}
if (action.actionId == nullptr || action.actionId[0] == '\0')
{
robot::log_error("navigation_execute_instant_actions: action %zu ('%s') has a null or empty "
"actionId — the fleet needs it to match the result back to its request",
i, action.actionType);
return false;
}
cpp_actions.push_back(convert2CppAction(action));
}
try
{
const Order order = make_order(order_id, order_update_id, nodes, node_count, edges, edge_count);
return as_navigation(handle)->dockTo(convert2CppOrder(order), std::string(marker),
convert2CppPoseStamped(goal));
return as_navigation(handle)->executeInstantActions(cpp_actions);
}
catch (const std::exception &e)
{
robot::log_error("navigation_dock_to_order_v2 failed: %s", e.what());
robot::log_error("navigation_execute_instant_actions failed: %s", e.what());
return false;
}
catch (...)
{
robot::log_error("navigation_execute_instant_actions failed: unknown exception");
return false;
}
}
// navigation_dock_to_order_v2 was removed together with BaseNavigation::dockTo. Docking is now a
// per-leg property of the order: set `profile: docking` and `marker` on the leg and send it
// through navigation_move_to_order_v2, so it gets the same mission id, lifecycle and cancel as
// every other leg instead of bypassing the mission layer.
// ================================================================================================
// Releasing what the getters allocate
// ================================================================================================

View File

@@ -134,7 +134,6 @@ namespace two_points_planner
exit(1);
}
}
robot::log_warning("abc testttttt!, SizeInCellsX = %d, SizeInCellsY = %d", costmap_robot_->getCostmap()->getSizeInCellsX(), costmap_robot_->getCostmap()->getSizeInCellsY());
robot_nav_2d_msgs::Pose2DStamped start_2d = robot_nav_2d_utils::poseStampedToPose2D(start);
robot_nav_2d_msgs::Pose2DStamped goal_2d = robot_nav_2d_utils::poseStampedToPose2D(goal);

View File

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

View File

@@ -18,6 +18,7 @@
#include <robot_sensor_msgs/LaserScan.h>
#include <robot_sensor_msgs/PointCloud.h>
#include <robot_sensor_msgs/PointCloud2.h>
#include <robot_protocol_msgs/Action.h>
#include <robot_protocol_msgs/Order.h>
#include <robot_nav_2d_utils/conversions.h>
@@ -409,49 +410,54 @@ namespace robot
double yaw_goal_tolerance = 0.0) = 0;
/**
* @brief Send a docking goal to a predefined marker (e.g. charger).
* @param maker Marker name or ID.
* @param goal Target pose for docking.
* @param xy_goal_tolerance Acceptable XY error (meters).
* @param yaw_goal_tolerance Acceptable heading error (radians).
* @return True if docking command succeeded.
* Docking, go-straight and rotate are no longer entry points of this contract.
*
* They used to exist as `dockTo` (two overloads), `moveStraightTo` and `rotateTo`, each
* pushing a goal straight into the navigation core and bypassing the mission layer. That
* bypass had no defined preemption semantics: a goal arriving through one of them silently
* replaced whatever leg the mission queue was running, and the queue kept handing out the
* next leg of a route the robot had already left.
*
* The motion profiles themselves are unchanged and still reachable — an order carries them
* per leg (`profile: docking | go_straight | rotate`, plus `marker` for docking), so they
* now travel the same path as every other leg: one mission id, one lifecycle, one cancel.
*/
virtual bool dockTo(const std::string &maker,
const robot_geometry_msgs::PoseStamped &goal,
double xy_goal_tolerance = 0.0,
double yaw_goal_tolerance = 0.0) = 0;
/**
* @brief Send a docking goal to a predefined marker (e.g. charger).
* @param msg Order message.
* @param goal Target pose for docking.
* @param xy_goal_tolerance Acceptable XY error (meters).
* @param yaw_goal_tolerance Acceptable heading error (radians).
* @return True if docking command succeeded.
* @brief Execute one VDA5050 `instantActions` message — a list of actions sent outside any order.
*
* This is the one entry point that takes bare actions. It exists because the four
* removed above did not: it does not push anything into the core directly. The actions
* are handed to the mission layer, which expands each against the same compound-action
* table that node actions use and queues the resulting legs, so an instantAction gets
* the same mission id, lifecycle and cancel path as any other work.
*
* The whole message goes down as ONE batch, in the order given. Submitting the actions
* one at a time would break as soon as a message carried two of them: the second `HARD`
* action preempts and wipes the legs of the first, so two commands sent together would
* eat each other.
*
* Execution stops at the first leg that fails, and the rest of the message is dropped
* with it (`clear_queue_on_failure`). The caller therefore reports one outcome for the
* message, not one per action.
*
* `blockingType` decides how the batch meets a running order: any `HARD` action makes
* the whole message preempt it; otherwise it queues behind it. `NONE` asks for
* execution in parallel with driving, which this runtime cannot do — it is queued
* instead, and the narrowing is logged.
*
* Lifecycle instantActions — `cancelOrder`, `startPause`, `stopPause` — must NOT come
* through here. They steer the queue rather than being work in it; the host calls
* @ref cancel, @ref pause and @ref resume for those.
*
* @param actions The actions of one `instantActions` message, in the order received.
* Must not be empty; every action needs `actionType` and `actionId`.
* @return True if the message was accepted. False means it was rejected outright — empty
* list, missing identity, or the mission layer is not running — and the caller
* must report failure rather than wait for a result that will not come.
*/
virtual bool dockTo(const robot_protocol_msgs::Order &msg,
const std::string &marker,
const robot_geometry_msgs::PoseStamped &goal,
double xy_goal_tolerance = 0.0,
double yaw_goal_tolerance = 0.0) = 0;
/**
* @brief Move straight toward the target position (X-axis).
* @param goal Target pose.
* @param xy_goal_tolerance Acceptable positional error (meters).
* @return True if command issued successfully.
*/
virtual bool moveStraightTo(const robot_geometry_msgs::PoseStamped &goal,
double xy_goal_tolerance = 0.0) = 0;
/**
* @brief Rotate in place to align with target orientation.
* @param goal Pose containing desired heading (only Z-axis used).
* @param yaw_goal_tolerance Acceptable angular error (radians).
* @return True if rotation command was sent successfully.
*/
virtual bool rotateTo(const robot_geometry_msgs::PoseStamped &goal,
double yaw_goal_tolerance = 0.0) = 0;
virtual bool executeInstantActions(
const std::vector<robot_protocol_msgs::Action> &actions) = 0;
/**
* @brief Pause the robot's movement (e.g. during obstacle avoidance).

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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