diff --git a/CMakeLists.txt b/CMakeLists.txt index 6581044..26e8602 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) diff --git a/doc/architecture_discussion.md b/doc/architecture_discussion.md index f80712e..d2c3a1c 100644 --- a/doc/architecture_discussion.md +++ b/doc/architecture_discussion.md @@ -39,7 +39,7 @@ flowchart TB %% ========== INTERFACE LAYER ========== subgraph Interface["🔌 Interface Layer"] direction TB - BaseNav["📋 BaseNavigation
━━━━━━━━━━━━━━━━
🏗️ move_base_core::BaseNavigation
🎯 Abstract Interface
━━━━━━━━━━━━━━━━
📍 moveTo, dockTo
🔄 rotateTo, moveStraightTo
⏸️ pause, resume, cancel
📊 getRobotPose"] + BaseNav["📋 BaseNavigation
━━━━━━━━━━━━━━━━
🏗️ move_base_core::BaseNavigation
🎯 Abstract Interface
━━━━━━━━━━━━━━━━
📍 moveTo (goal / order)
🔄 executeInstantActions
⏸️ pause, resume, cancel
📊 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 diff --git a/examples/NavigationExample/NavigationAPI.cs b/examples/NavigationExample/NavigationAPI.cs index 146fbf1..4a46136 100644 --- a/examples/NavigationExample/NavigationAPI.cs +++ b/examples/NavigationExample/NavigationAPI.cs @@ -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); - - /// Rotate in place to align with target orientation (radians). - [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)] diff --git a/examples/NavigationExample/Program.cs b/examples/NavigationExample/Program.cs index 89ca9fd..f364470 100644 --- a/examples/NavigationExample/Program.cs +++ b/examples/NavigationExample/Program.cs @@ -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); diff --git a/src/APIs/c_api/C_API_AUDIT.md b/src/APIs/c_api/C_API_AUDIT.md index 654277a..af67fb1 100644 --- a/src/APIs/c_api/C_API_AUDIT.md +++ b/src/APIs/c_api/C_API_AUDIT.md @@ -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 diff --git a/src/APIs/c_api/NAV_C_API_2_GUIDE.md b/src/APIs/c_api/NAV_C_API_2_GUIDE.md index 54f80e1..49b15b7 100644 --- a/src/APIs/c_api/NAV_C_API_2_GUIDE.md +++ b/src/APIs/c_api/NAV_C_API_2_GUIDE.md @@ -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 incoming) +{ + var actions = new Action[incoming.Count]; + var pinned = new List(); + 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` → `` | **tĩnh** | host, bơm một lần lúc khởi động | một lần | +| `base_link` → `` | **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 OnInstantActionsAsync(IReadOnlyList 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 | 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 diff --git a/src/APIs/c_api/include/convertor.h b/src/APIs/c_api/include/convertor.h index 30f33af..9620338 100644 --- a/src/APIs/c_api/include/convertor.h +++ b/src/APIs/c_api/include/convertor.h @@ -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 diff --git a/src/APIs/c_api/include/nav_c_api.h b/src/APIs/c_api/include/nav_c_api.h index 92a0033..a812457 100644 --- a/src/APIs/c_api/include/nav_c_api.h +++ b/src/APIs/c_api/include/nav_c_api.h @@ -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 diff --git a/src/APIs/c_api/include/nav_c_api_2.h b/src/APIs/c_api/include/nav_c_api_2.h index c1f6715..c55ed6c 100644 --- a/src/APIs/c_api/include/nav_c_api_2.h +++ b/src/APIs/c_api/include/nav_c_api_2.h @@ -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 diff --git a/src/APIs/c_api/nav-c-api-2-csharp-integration-report.md b/src/APIs/c_api/nav-c-api-2-csharp-integration-report.md index 83a77ef..593c767 100644 --- a/src/APIs/c_api/nav-c-api-2-csharp-integration-report.md +++ b/src/APIs/c_api/nav-c-api-2-csharp-integration-report.md @@ -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 | diff --git a/src/APIs/c_api/src/convertor.cpp b/src/APIs/c_api/src/convertor.cpp index 7fe8c4d..60b92a2 100644 --- a/src/APIs/c_api/src/convertor.cpp +++ b/src/APIs/c_api/src/convertor.cpp @@ -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 : ""; diff --git a/src/APIs/c_api/src/nav_c_api.cpp b/src/APIs/c_api/src/nav_c_api.cpp index ed36a9f..44df65d 100644 --- a/src/APIs/c_api/src/nav_c_api.cpp +++ b/src/APIs/c_api/src/nav_c_api.cpp @@ -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 nav_ptr = - std::shared_ptr( - reinterpret_cast(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 nav_ptr = - std::shared_ptr( - reinterpret_cast(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 nav_ptr = - std::shared_ptr( - reinterpret_cast(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(nodes); - order.nodes_count = node_count; - order.edges = const_cast(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 nav_ptr = - std::shared_ptr( - reinterpret_cast(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 nav_ptr = - std::shared_ptr( - reinterpret_cast(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) { diff --git a/src/APIs/c_api/src/nav_c_api_2.cpp b/src/APIs/c_api/src/nav_c_api_2.cpp index 1d38efc..baeafa6 100644 --- a/src/APIs/c_api/src/nav_c_api_2.cpp +++ b/src/APIs/c_api/src/nav_c_api_2.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include @@ -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 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 // ================================================================================================ diff --git a/src/Algorithms/Packages/global_planners/two_points_planner/src/two_points_planner.cpp b/src/Algorithms/Packages/global_planners/two_points_planner/src/two_points_planner.cpp index 48f15fc..e02c199 100755 --- a/src/Algorithms/Packages/global_planners/two_points_planner/src/two_points_planner.cpp +++ b/src/Algorithms/Packages/global_planners/two_points_planner/src/two_points_planner.cpp @@ -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); diff --git a/src/Navigations/Cores/move_base_core/README.md b/src/Navigations/Cores/move_base_core/README.md index fbab9ef..13779c7 100755 --- a/src/Navigations/Cores/move_base_core/README.md +++ b/src/Navigations/Cores/move_base_core/README.md @@ -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 diff --git a/src/Navigations/Cores/move_base_core/include/move_base_core/navigation.h b/src/Navigations/Cores/move_base_core/include/move_base_core/navigation.h index 4b0fdfe..525bdb3 100755 --- a/src/Navigations/Cores/move_base_core/include/move_base_core/navigation.h +++ b/src/Navigations/Cores/move_base_core/include/move_base_core/navigation.h @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -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 &actions) = 0; /** * @brief Pause the robot's movement (e.g. during obstacle avoidance). diff --git a/src/Navigations/Packages/move_base/BUILD_INSTRUCTIONS.md b/src/Navigations/Packages/move_base/BUILD_INSTRUCTIONS.md deleted file mode 100644 index 42a0fdc..0000000 --- a/src/Navigations/Packages/move_base/BUILD_INSTRUCTIONS.md +++ /dev/null @@ -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-` -- 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 - diff --git a/src/Navigations/Packages/move_base/CMakeLists.txt b/src/Navigations/Packages/move_base/CMakeLists.txt deleted file mode 100644 index 2f761e0..0000000 --- a/src/Navigations/Packages/move_base/CMakeLists.txt +++ /dev/null @@ -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 - $ - $ - ${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 - $ - $ - ${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() diff --git a/src/Navigations/Packages/move_base/examples/IMPLEMENTATION_GUIDE.md b/src/Navigations/Packages/move_base/examples/IMPLEMENTATION_GUIDE.md deleted file mode 100644 index 905110b..0000000 --- a/src/Navigations/Packages/move_base/examples/IMPLEMENTATION_GUIDE.md +++ /dev/null @@ -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 - -namespace move_base -{ - class MoveBase : public robot::move_base_core::BaseNavigation - { - private: - // Thêm member variable - std::shared_ptr> 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>( - "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(); -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(); -``` - diff --git a/src/Navigations/Packages/move_base/examples/README_SIMPLE_ACTION_SERVER.md b/src/Navigations/Packages/move_base/examples/README_SIMPLE_ACTION_SERVER.md deleted file mode 100644 index e512922..0000000 --- a/src/Navigations/Packages/move_base/examples/README_SIMPLE_ACTION_SERVER.md +++ /dev/null @@ -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 - -// Tạo action server với execute callback -auto action_server = std::make_shared>( - "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 - -class MoveBase : public robot::move_base_core::BaseNavigation -{ -private: - std::shared_ptr> 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>( - "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); -// }); -``` - diff --git a/src/Navigations/Packages/move_base/examples/simple_action_server_example.cpp b/src/Navigations/Packages/move_base/examples/simple_action_server_example.cpp deleted file mode 100644 index f780d18..0000000 --- a/src/Navigations/Packages/move_base/examples/simple_action_server_example.cpp +++ /dev/null @@ -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 -#include - -// Message types -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -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(tf_); - - // Create SimpleActionServer with execute callback - action_server_ = std::make_shared>( - "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> 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> 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(); - 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; -} - diff --git a/src/Navigations/Packages/move_base/include/move_base/convert_data.h b/src/Navigations/Packages/move_base/include/move_base/convert_data.h deleted file mode 100644 index 904839b..0000000 --- a/src/Navigations/Packages/move_base/include/move_base/convert_data.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef MOVE_BASE_CONVERT_DATA_H -#define MOVE_BASE_CONVERT_DATA_H - -#include -#include -#include - -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 \ No newline at end of file diff --git a/src/Navigations/Packages/move_base/include/move_base/move_base.h b/src/Navigations/Packages/move_base/include/move_base/move_base.h deleted file mode 100644 index bb8b4fc..0000000 --- a/src/Navigations/Packages/move_base/include/move_base/move_base.h +++ /dev/null @@ -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 -#include -#include -#include -#include - -// interfaces headers -#include -#include -#include -#include -#include - -// boost headers -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - - -namespace move_base -{ - template - 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 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 &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 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 getAllStaticMaps() override; - - /** - * @brief Get all laser scans from the navigation system. - * @return The laser scans. - */ - virtual std::map getAllLaserScans() override; - - /** - * @brief Get all point clouds from the navigation system. - * @return The point clouds. - */ - virtual std::map getAllPointClouds() override; - - /** - * @brief Get all point cloud2s from the navigation system. - * @return The point cloud2s. - */ - virtual std::map 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 - 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 - 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 &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 &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 planner_loader_; - /** @brief Function loader for local planner (controller) plugins */ - boost::function controller_loader_; - /** @brief Map of recovery behavior loaders by name */ - std::map> 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 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 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 *planner_plan_; - /** @brief Plan triple buffer: latest plan (intermediate buffer) */ - std::vector *latest_plan_; - /** @brief Plan triple buffer: plan used by the controller */ - std::vector *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 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_ diff --git a/src/Navigations/Packages/move_base/include/move_base/simple_action_server.h b/src/Navigations/Packages/move_base/include/move_base/simple_action_server.h deleted file mode 100644 index db49f25..0000000 --- a/src/Navigations/Packages/move_base/include/move_base/simple_action_server.h +++ /dev/null @@ -1,259 +0,0 @@ -#ifndef MOVE_BASE_SIMPLE_ACTION_SERVER_H_ -#define MOVE_BASE_SIMPLE_ACTION_SERVER_H_ - -#include -#include -#include -#include -#include -#include -#include -#include - -// Action message types -#include -#include -#include -#include -#include -#include -#include - -// Actionlib message types -#include -#include -#include - -// Robot framework -#include - -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 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 GoalConstPtr; - typedef boost::shared_ptr ResultConstPtr; - typedef boost::shared_ptr 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 GoalCallback; - typedef std::function CancelCallback; - typedef std::function FeedbackCallback; - typedef std::function ResultCallback; - typedef std::function StatusCallback; - typedef std::function 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_ - diff --git a/src/Navigations/Packages/move_base/package.xml b/src/Navigations/Packages/move_base/package.xml deleted file mode 100644 index 9746e12..0000000 --- a/src/Navigations/Packages/move_base/package.xml +++ /dev/null @@ -1,58 +0,0 @@ - - move_base - 0.7.10 - - 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. - - Tully Foote - Eitan Marder-Eppstein - Wim Meeussen - Tully Foote - BSD - - http://www.ros.org/wiki/move_base - - catkin - - geometry_msgs - geometry_msgs - - robot_std_msgs - robot_std_msgs - - move_base_core - move_base_core - - robot_nav_core - robot_nav_core - - robot_costmap_2d - robot_costmap_2d - - robot_tf3_sensor_msgs - robot_tf3_sensor_msgs - - robot_tf3_geometry_msgs - robot_tf3_geometry_msgs - - data_convert - data_convert - - robot_nav_2d_utils - robot_nav_2d_utils - - robot_cpp - robot_cpp - - mission_adapters - mission_adapters - - robot_move_base_msgs - robot_move_base_msgs - - \ No newline at end of file diff --git a/src/Navigations/Packages/move_base/src/convert_data.cpp b/src/Navigations/Packages/move_base/src/convert_data.cpp deleted file mode 100644 index c63f778..0000000 --- a/src/Navigations/Packages/move_base/src/convert_data.cpp +++ /dev/null @@ -1,130 +0,0 @@ -#include -#include -#include - -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 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 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_); -} \ No newline at end of file diff --git a/src/Navigations/Packages/move_base/src/move_base.cpp b/src/Navigations/Packages/move_base/src/move_base.cpp deleted file mode 100644 index c63bb2d..0000000 --- a/src/Navigations/Packages/move_base/src/move_base.cpp +++ /dev/null @@ -1,3266 +0,0 @@ -/********************************************************************* - * - * Software License Agreement (BSD License) - * - * Author: Kevin Lee - *********************************************************************/ -#ifdef BUILD_WITH_ROS -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#ifndef BUILD_WITH_ROS - #include -#endif - -move_base::MoveBase::MoveBase() - : initialized_(false), - tf_(), - as_(NULL), - planner_costmap_robot_(NULL), controller_costmap_robot_(NULL), - planner_plan_(NULL), latest_plan_(NULL), controller_plan_(NULL), - recovery_index_(0), - recovery_behavior_enabled_(false), - planner_frequency_(0.0), controller_frequency_(0.0), - inscribed_radius_(0.0), circumscribed_radius_(0.0), - planner_patience_(0.0), controller_patience_(0.0), - max_planning_retries_(0), planning_retries_(0), - conservative_reset_dist_(0.0), clearing_radius_(0.0), - shutdown_costmaps_(false), clearing_rotation_allowed_(false), - make_plan_clear_costmap_(false), make_plan_add_unreachable_goal_(false), - oscillation_timeout_(0.0), oscillation_distance_(0.0), - state_(PLANNING), recovery_trigger_(PLANNING_R), - runPlanner_(false), planner_thread_(NULL), - setup_(false), p_freq_change_(false), c_freq_change_(false), new_global_plan_(false), - pause_ctr_(false), paused_(false), cancel_ctr_(false), - original_xy_goal_tolerance_(0.0), original_yaw_goal_tolerance_(0.0) -{ -} - -move_base::MoveBase::MoveBase(robot::TFListenerPtr tf) - : initialized_(false), - tf_(), - as_(NULL), - planner_costmap_robot_(NULL), controller_costmap_robot_(NULL), - planner_plan_(NULL), latest_plan_(NULL), controller_plan_(NULL), - recovery_index_(0), - recovery_behavior_enabled_(false), - planner_frequency_(0.0), controller_frequency_(0.0), - inscribed_radius_(0.0), circumscribed_radius_(0.0), - planner_patience_(0.0), controller_patience_(0.0), - max_planning_retries_(0), planning_retries_(0), - conservative_reset_dist_(0.0), clearing_radius_(0.0), - shutdown_costmaps_(false), clearing_rotation_allowed_(false), - make_plan_clear_costmap_(false), make_plan_add_unreachable_goal_(false), - oscillation_timeout_(0.0), oscillation_distance_(0.0), - state_(PLANNING), recovery_trigger_(PLANNING_R), - runPlanner_(false), planner_thread_(NULL), - setup_(false), p_freq_change_(false), c_freq_change_(false), new_global_plan_(false), - pause_ctr_(false), paused_(false), cancel_ctr_(false), - original_xy_goal_tolerance_(0.0), original_yaw_goal_tolerance_(0.0) -{ - initialize(tf); -} - -move_base::MoveBase::~MoveBase() -{ - robot::log_warning("Destroying MoveBase instance..."); - if (as_ != NULL) - { - as_->stop(); - delete as_; - as_ = NULL; - } - - recovery_behaviors_.clear(); - - // Cleanup static maps (shared_ptr tự động cleanup) - static_maps_.clear(); - - // Cleanup laser scans (shared_ptr tự động cleanup) - laser_scans_.clear(); - - // Cleanup point clouds (shared_ptr tự động cleanup) - point_clouds_.clear(); - - // Cleanup point cloud2s (shared_ptr tự động cleanup) - point_cloud2s_.clear(); - - if (planner_costmap_robot_ != NULL) - { - delete planner_costmap_robot_; - planner_costmap_robot_ = NULL; - } - - if (controller_costmap_robot_ != NULL) - { - delete controller_costmap_robot_; - controller_costmap_robot_ = NULL; - } - - if (planner_thread_ != NULL) - { - planner_thread_->interrupt(); - planner_thread_->join(); - delete planner_thread_; - planner_thread_ = NULL; - } - - if (planner_plan_ != NULL) - { - delete planner_plan_; - planner_plan_ = NULL; - } - - if (latest_plan_ != NULL) - { - delete latest_plan_; - latest_plan_ = NULL; - } - - if (controller_plan_ != NULL) - { - delete controller_plan_; - controller_plan_ = NULL; - } - - planner_.reset(); - tc_.reset(); - initialized_ = false; - tf_.reset(); -} - -void move_base::MoveBase::initialize(robot::TFListenerPtr tf) -{ - printf("[%s:%d]\n ========== Begin: initialize() ==========\n", __FILE__, __LINE__); - if (!initialized_) - { - if(tf == nullptr) - { - robot::log_error("[%s:%d]\n ERROR: tf is nullptr", __FILE__, __LINE__); - throw std::runtime_error("Failed to create the tf"); - } - else - { - robot::log_info("[%s:%d]\n INFO: tf is not nullptr", __FILE__, __LINE__); - } - tf_ = tf; - if(tf_) - { - std::string all_frames_string = tf_->allFramesAsString(); - robot::log_info("[%s:%d]\n INFO: tf_ allFramesAsString: %s", __FILE__, __LINE__, all_frames_string.c_str()); - } - as_ = new MoveBaseActionServer("move_base", std::bind(&MoveBase::executeCb, this, std::placeholders::_1), true); - setupActionServerCallbacks(); - - // NodeHandle("~") will automatically load YAML files from config directory - private_nh_ = robot::NodeHandle("~"); - recovery_trigger_ = PLANNING_R; - - // get some parameters that will be global to the move base node - std::string global_planner, local_planner; - private_nh_.getParam("base_global_planner", global_planner, std::string("")); - robot::log_info("[%s %d] global_planner: %s", __FILE__, __LINE__, global_planner.c_str()); - private_nh_.getParam("base_local_planner", local_planner, std::string("")); - robot::log_info("[%s %d] local_planner: %s", __FILE__, __LINE__, local_planner.c_str()); - - // Handle nested YAML nodes for costmap config - std::string robot_base_frame; - private_nh_.getParam("robot_base_frame", robot_base_frame, std::string("base_footprint")); - std::string global_frame; - private_nh_.getParam("global_frame", global_frame, std::string("map")); - robot_base_frame_ = robot_base_frame; - global_frame_ = global_frame; - double planner_frequency; - private_nh_.getParam("planner_frequency", planner_frequency, 0.0); - planner_frequency_ = planner_frequency; - double controller_frequency; - private_nh_.getParam("controller_frequency", controller_frequency, 20.0); - controller_frequency_ = controller_frequency; - double planner_patience; - private_nh_.getParam("planner_patience", planner_patience, 5.0); - planner_patience_ = planner_patience; - private_nh_.getParam("controller_patience", controller_patience_, 15.0); - double max_planning_retries; - private_nh_.getParam("max_planning_retries", max_planning_retries, -1.0); - max_planning_retries_ = max_planning_retries; - double oscillation_timeout; - private_nh_.getParam("oscillation_timeout", oscillation_timeout, 0.0); - oscillation_timeout_ = oscillation_timeout; - double oscillation_distance; - private_nh_.getParam("oscillation_distance", oscillation_distance, 0.5); - oscillation_distance_ = oscillation_distance; - - double original_xy_goal_tolerance; - private_nh_.getParam("xy_goal_tolerance", original_xy_goal_tolerance, 0.2); - original_xy_goal_tolerance_ = original_xy_goal_tolerance; - double original_yaw_goal_tolerance; - private_nh_.getParam("yaw_goal_tolerance", original_yaw_goal_tolerance, 0.2); - original_yaw_goal_tolerance_ = original_yaw_goal_tolerance; - - // defined local planner name - private_nh_.getParam("position_planner_name", position_planner_name_, std::string("mkt_algorithm/MKTPositionPlanner")); - private_nh_.getParam("docking_planner_name", docking_planner_name_, std::string("mkt_algorithm/MKTDockingPlanner")); - private_nh_.getParam("go_straight_planner_name", go_straight_planner_name_, std::string("mkt_algorithm/MKTGoStraightPlanner")); - private_nh_.getParam("rotate_planner_name", rotate_planner_name_, std::string("mkt_algorithm/MKTRotatePlanner")); - - // parameters of make_plan service - private_nh_.getParam("make_plan_clear_costmap", make_plan_clear_costmap_, false); - private_nh_.getParam("make_plan_add_unreachable_goal", make_plan_add_unreachable_goal_, false); - private_nh_.getParam("min_approach_linear_velocity", min_approach_linear_velocity_, 0.0); - min_approach_linear_velocity_ *= 1.2; - // set up plan triple buffer - planner_plan_ = new std::vector(); - latest_plan_ = new std::vector(); - controller_plan_ = new std::vector(); - - // set up the planner's thread - planner_thread_ = new boost::thread(boost::bind(&move_base::MoveBase::planThread, this)); - // we'll assume the radius of the robot to be consistent with what's specified for the costmaps - // From config param - double inscribed_radius; - private_nh_.getParam("local_costmap/inscribed_radius", inscribed_radius, 0.2); - double circumscribed_radius; - private_nh_.getParam("local_costmap/circumscribed_radius", circumscribed_radius, 0.3); - inscribed_radius_ = inscribed_radius; - circumscribed_radius_ = circumscribed_radius; - private_nh_.getParam("clearing_radius", clearing_radius_, 0.0); - double conservative_reset_dist; - private_nh_.getParam("conservative_reset_dist", conservative_reset_dist, 0.0); - conservative_reset_dist_ = conservative_reset_dist; - private_nh_.getParam("shutdown_costmaps", shutdown_costmaps_, false); - private_nh_.getParam("clearing_rotation_allowed", clearing_rotation_allowed_, true); - private_nh_.getParam("recovery_behavior_enabled", recovery_behavior_enabled_, true); - - // create the ros wrapper for the planner's costmap... and initializer a pointer we'll use with the underlying map - try - { - planner_costmap_robot_ = new robot_costmap_2d::Costmap2DROBOT("global_costmap", *tf_); - planner_costmap_robot_->pause(); - robot_costmap_2d::LayeredCostmap *layered_costmap_ = planner_costmap_robot_->getLayeredCostmap(); - } - catch (const std::exception &ex) - { - robot::log_error("[%s:%d]\n EXCEPTION: %s", __FILE__, __LINE__, ex.what()); - throw std::runtime_error("Failed to create the planner_costmap_robot_"); - } - - try - { - controller_costmap_robot_ = new robot_costmap_2d::Costmap2DROBOT("local_costmap", *tf_); - if(controller_costmap_robot_ == nullptr) - { - robot::log_error("[%s:%d]\n ERROR: controller_costmap_robot_ is nullptr", __FILE__, __LINE__); - throw std::runtime_error("Failed to create the controller_costmap_robot_"); - } - controller_costmap_robot_->pause(); - robot_costmap_2d::LayeredCostmap *layered_costmap_ = controller_costmap_robot_->getLayeredCostmap(); - } - catch (const std::exception &ex) - { - robot::log_error("[%s:%d]\n EXCEPTION: %s", __FILE__, __LINE__, ex.what()); - throw std::runtime_error("Failed to create the controller_costmap_robot_"); - } - - addStaticMap(map_name_save_, map_save_); - - // initialize the global planner - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(global_planner); - robot::log_info("[%s:%d]\n INFO: global_planner library path: %s", __FILE__, __LINE__, path_file_so.c_str()); - planner_loader_ = boost::dll::import_alias( - path_file_so, global_planner, boost::dll::load_mode::append_decorations); - - planner_ = planner_loader_(); - if (!planner_) - { - robot::log_error("[%s:%d]\n ERROR: planner_loader_() returned nullptr\n", __FILE__, __LINE__); - throw std::runtime_error("Failed to load global planner " + global_planner); - } - last_config_.base_global_planner = global_planner; - default_config_.base_global_planner = global_planner; - if (planner_->initialize(global_planner, planner_costmap_robot_)) - robot::log_info("[%s:%d]\n Global planner initialized successfully", __FILE__, __LINE__); - else - robot::log_error("[%s:%d]\n Global planner initialized failed", __FILE__, __LINE__); - } - catch (const std::exception &ex) - { - robot::log_error("[%s:%d]\n EXCEPTION in global planner: %s", __FILE__, __LINE__, ex.what()); - throw std::runtime_error("Failed to create the " + global_planner + " planner"); - } - - // create a local planner - try - { - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(local_planner); - robot::log_info("[%s:%d]\n INFO: local_planner library path: %s", __FILE__, __LINE__, path_file_so.c_str()); - controller_loader_ = - boost::dll::import_alias( - path_file_so, local_planner, boost::dll::load_mode::append_decorations); - tc_ = controller_loader_(); - if (!tc_) - { - robot::log_error("[%s:%d]\n ERROR: controller_loader_() returned nullptr", __FILE__, __LINE__); - throw std::runtime_error("Failed to load local planner " + local_planner); - } - tc_->initialize(local_planner, tf_.get(), controller_costmap_robot_); - tc_->setOdom(&odometry_); - } - catch (const std::exception &ex) - { - robot::log_error("[%s:%d]\n EXCEPTION in local planner: %s", __FILE__, __LINE__, ex.what()); - throw std::runtime_error("Failed to create the " + local_planner + " planner"); - } - - // Start actively updating costmaps based on sensor data - planner_costmap_robot_->start(); - controller_costmap_robot_->start(); - - try - { - old_linear_fwd_ = tc_->getTwistLinear(true); - old_linear_bwd_ = tc_->getTwistLinear(false); - - old_angular_fwd_ = tc_->getTwistAngular(true); - old_angular_rev_ = tc_->getTwistAngular(false); - } - catch (const std::exception &e) - { - std::cerr << e.what() << '\n'; - } - - // if we shutdown our costmaps when we're deactivated... we'll do that now - if (shutdown_costmaps_) - { - planner_costmap_robot_->stop(); - controller_costmap_robot_->stop(); - } - - // load any user specified recovery behaviors, and if that fails load the defaults - if (!loadRecoveryBehaviors(private_nh_)) - { - robot::log_warning("[%s:%d]\n Loading default recovery behaviors", __FILE__, __LINE__); - loadDefaultRecoveryBehaviors(); - } - - // initially, we'll need to make a plan - state_ = move_base::PLANNING; - - // we'll start executing recovery behaviors at the beginning of our list - recovery_index_ = 0; - nav_feedback_ = std::make_shared(); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::PLANNING; - nav_feedback_->is_ready = true; - } - else - { - robot::log_error("[%s:%d]\n ERROR: nav_feedback_ is nullptr", __FILE__, __LINE__); - } - initialized_ = true; - setup_ = true; - robot::log_info("========== End: initialize() - SUCCESS =========="); - } - else - { - robot::log_warning("[%s:%d]\n Already initialized, skipping", __FILE__, __LINE__); - } -} - -void move_base::MoveBase::swapPlanner(std::string base_global_planner) -{ - if (base_global_planner != last_config_.base_global_planner) - { - robot_nav_core::BaseGlobalPlanner::Ptr old_planner = planner_; - auto old_loader = planner_loader_; - // initialize the global planner - try - { - // wait for the current planner to finish planning - boost::unique_lock lock(planner_mutex_); - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(base_global_planner); - robot::log_info("[%s:%d]\n INFO: global_planner library path: %s", __FILE__, __LINE__, path_file_so.c_str()); - auto new_loader = boost::dll::import_alias( - path_file_so, base_global_planner, boost::dll::load_mode::append_decorations); - auto new_planner = new_loader(); - if (!new_planner) - { - robot::log_error("[%s:%d]\n ERROR: planner_loader_() returned nullptr", __FILE__, __LINE__); - throw std::runtime_error("Failed to load global planner " + base_global_planner); - } - - if (planner_plan_) - planner_plan_->clear(); - if (latest_plan_) - latest_plan_->clear(); - if (controller_plan_) - controller_plan_->clear(); - resetState(); - - new_planner->initialize(base_global_planner, planner_costmap_robot_); - - planner_ = new_planner; - planner_loader_ = new_loader; - last_config_.base_global_planner = base_global_planner; - - // Release old planner while old loader is still alive. - old_planner.reset(); - old_loader = boost::function(); - lock.unlock(); - } - catch (const std::exception &ex) - { - robot::log_error("[%s:%d]\n Failed to create the %s planner, are you sure it is properly registered and that the \ - containing library is built? Exception: %s",__FILE__, __LINE__, base_global_planner.c_str(), ex.what()); - planner_ = old_planner; - planner_loader_ = old_loader; - } - } -} - -void move_base::MoveBase::setRobotFootprint(const std::vector &fprt) -{ - if (planner_costmap_robot_) - planner_costmap_robot_->setUnpaddedRobotFootprint(fprt); - - if (controller_costmap_robot_) - controller_costmap_robot_->setUnpaddedRobotFootprint(fprt); -} - -std::vector move_base::MoveBase::getRobotFootprint() -{ - if (planner_costmap_robot_) - return planner_costmap_robot_->getUnpaddedRobotFootprint(); - return std::vector(); -} - -void move_base::MoveBase::addStaticMap(const std::string &map_name, robot_nav_msgs::OccupancyGrid map) -{ - // Kiểm tra xem map_name đã tồn tại trong static_maps_ chưa - auto it = static_maps_.find(map_name); - if (it == static_maps_.end()) - { - static_maps_[map_name] = map; - } - else - { - it->second = map; - } - // robot::log_info("map header: %s", map.header.frame_id.c_str()); - // robot::log_info("map header: %ld.%ld", map.header.stamp.sec, map.header.stamp.nsec); - // robot::log_info("map header: %d", map.header.seq); - // robot::log_info("map info resolution: %f", map.info.resolution); - // robot::log_info("map info width: %d", map.info.width); - // robot::log_info("map info height: %d", map.info.height); - // robot::log_info("map info origin position x: %f", map.info.origin.position.x); - // robot::log_info("map info origin position y: %f", map.info.origin.position.y); - // robot::log_info("map info origin position z: %f", map.info.origin.position.z); - // robot::log_info("map info origin orientation x: %f", map.info.origin.orientation.x); - // robot::log_info("map info origin orientation y: %f", map.info.origin.orientation.y); - // robot::log_info("map info origin orientation z: %f", map.info.origin.orientation.z); - // robot::log_info("map info origin orientation w: %f", map.info.origin.orientation.w); - // robot::log_info("map data size: %zu", map.data.size()); - // for(size_t i = 0; i < map.data.size(); i++) { - // robot::log_info("map data[%zu]: %d", i, map.data[i]); - // } - robot::log_info("--------------------------------"); - updateGlobalCostmap(map, robot_costmap_2d::LayerType::STATIC_LAYER, map_name); - updateLocalCostmap(map, robot_costmap_2d::LayerType::STATIC_LAYER, map_name); -} - -robot_nav_msgs::OccupancyGrid move_base::MoveBase::getStaticMap(const std::string &map_name) -{ - auto it = static_maps_.find(map_name); - if (it != static_maps_.end()) - { - return it->second; - } - return robot_nav_msgs::OccupancyGrid(); -} - -void move_base::MoveBase::addLaserScan(const std::string &laser_scan_name, robot_sensor_msgs::LaserScan laser_scan) -{ - auto it = laser_scans_.find(laser_scan_name); -#ifndef BUILD_WITH_ROS - laser_filter::LaserScanSOR sor; - sor.setMeanK(10); // xét 10 điểm láng giềng gần nhất - sor.setStddevMulThresh(1.0); // ngưỡng = mean + 1.0 * stddev - robot_sensor_msgs::LaserScan laser_scan_filter = sor.filter(laser_scan); - if (it == laser_scans_.end()) - { - laser_scans_[laser_scan_name] = laser_scan_filter; - } - else - { - it->second = laser_scan_filter; - } -#else - if (it == laser_scans_.end()) - { - laser_scans_[laser_scan_name] = laser_scan; - } - else - { - it->second = laser_scan; - } -#endif - // robot::log_info("stamp: %ld.%ld", laser_scan.header.stamp.sec, laser_scan.header.stamp.nsec); - // robot::log_info("frame_id: %s", laser_scan.header.frame_id.c_str()); - // robot::log_info("angle_min: %f", laser_scan.angle_min); - // robot::log_info("angle_max: %f", laser_scan.angle_max); - // robot::log_info("angle_increment: %f", laser_scan.angle_increment); - // robot::log_info("time_increment: %f", laser_scan.time_increment); - // robot::log_info("scan_time: %f", laser_scan.scan_time); - // robot::log_info("range_min: %f", laser_scan.range_min); - // robot::log_info("range_max: %f", laser_scan.range_max); - // robot::log_info("ranges_size: %zu", laser_scan.ranges.size()); - // robot::log_info("intensities_size: %zu", laser_scan.intensities.size()); - // std::stringstream ranges_str; - // for (size_t i = 0; i < laser_scan.ranges.size(); i++) { - // ranges_str << laser_scan.ranges[i] << " "; - // } - // robot::log_info("ranges: %s", ranges_str.str().c_str()); - // std::stringstream intensities_str; - // for (size_t i = 0; i < laser_scan.intensities.size(); i++) { - // intensities_str << laser_scan.intensities[i] << " "; - // } - // robot::log_error("intensities: %s", intensities_str.str().c_str()); - -#ifndef BUILD_WITH_ROS - updateLocalCostmap(laser_scan_filter, robot_costmap_2d::LayerType::VOXEL_LAYER, laser_scan_name); - updateGlobalCostmap(laser_scan_filter, robot_costmap_2d::LayerType::VOXEL_LAYER, laser_scan_name); -#else - updateLocalCostmap(laser_scan, robot_costmap_2d::LayerType::VOXEL_LAYER, laser_scan_name); - updateGlobalCostmap(laser_scan, robot_costmap_2d::LayerType::VOXEL_LAYER, laser_scan_name); -#endif -} - -robot_sensor_msgs::LaserScan move_base::MoveBase::getLaserScan(const std::string &laser_scan_name) -{ - auto it = laser_scans_.find(laser_scan_name); - if (it != laser_scans_.end()) - { - return it->second; - } - return robot_sensor_msgs::LaserScan(); -} - -void move_base::MoveBase::addPointCloud(const std::string &point_cloud_name, robot_sensor_msgs::PointCloud point_cloud) -{ - auto it = point_clouds_.find(point_cloud_name); - if (it == point_clouds_.end()) - { - point_clouds_[point_cloud_name] = point_cloud; - } - else - { - it->second = point_cloud; - } - updateLocalCostmap(point_cloud, robot_costmap_2d::LayerType::VOXEL_LAYER, point_cloud_name); - updateGlobalCostmap(point_cloud, robot_costmap_2d::LayerType::VOXEL_LAYER, point_cloud_name); -} - -robot_sensor_msgs::PointCloud move_base::MoveBase::getPointCloud(const std::string &point_cloud_name) -{ - auto it = point_clouds_.find(point_cloud_name); - if (it != point_clouds_.end()) - { - return it->second; - } - return robot_sensor_msgs::PointCloud(); -} - -void move_base::MoveBase::addPointCloud2(const std::string &point_cloud2_name, robot_sensor_msgs::PointCloud2 point_cloud2) -{ - auto it = point_cloud2s_.find(point_cloud2_name); - if (it == point_cloud2s_.end()) - { - point_cloud2s_[point_cloud2_name] = point_cloud2; - } - else - { - it->second = point_cloud2; - } - updateLocalCostmap(point_cloud2, robot_costmap_2d::LayerType::VOXEL_LAYER, point_cloud2_name); - updateGlobalCostmap(point_cloud2, robot_costmap_2d::LayerType::VOXEL_LAYER, point_cloud2_name); -} - -void move_base::MoveBase::addDepthCameraData(const std::string &topic, - robot_sensor_msgs::DepthCameraData::ConstPtr data) -{ - if (!data) - return; - - // robot::log_error("DEBUG"); - - updateLocalCostmap( - data, robot_costmap_2d::LayerType::VOXEL_LAYER, topic); - updateGlobalCostmap( - data, robot_costmap_2d::LayerType::VOXEL_LAYER, topic); -} - -robot_sensor_msgs::PointCloud2 move_base::MoveBase::getPointCloud2(const std::string &point_cloud2_name) -{ - auto it = point_cloud2s_.find(point_cloud2_name); - if (it != point_cloud2s_.end()) - { - return it->second; - } - return robot_sensor_msgs::PointCloud2(); -} - -std::map move_base::MoveBase::getAllStaticMaps() -{ - return static_maps_; -} - -std::map move_base::MoveBase::getAllLaserScans() -{ - return laser_scans_; -} - -std::map move_base::MoveBase::getAllPointClouds() -{ - return point_clouds_; -} - -std::map move_base::MoveBase::getAllPointCloud2s() -{ - return point_cloud2s_; -} - -bool move_base::MoveBase::removeStaticMap(const std::string &map_name) -{ - auto it = static_maps_.find(map_name); - if (it != static_maps_.end()) - { - static_maps_.erase(it); - return true; - } - return false; -} - -bool move_base::MoveBase::removeLaserScan(const std::string &laser_scan_name) -{ - auto it = laser_scans_.find(laser_scan_name); - if (it != laser_scans_.end()) - { - laser_scans_.erase(it); - return true; - } - return false; -} - -bool move_base::MoveBase::removePointCloud(const std::string &point_cloud_name) -{ - auto it = point_clouds_.find(point_cloud_name); - if (it != point_clouds_.end()) - { - point_clouds_.erase(it); - return true; - } - return false; -} - -bool move_base::MoveBase::removePointCloud2(const std::string &point_cloud2_name) -{ - auto it = point_cloud2s_.find(point_cloud2_name); - if (it != point_cloud2s_.end()) - { - point_cloud2s_.erase(it); - return true; - } - return false; -} - -bool move_base::MoveBase::removeAllStaticMaps() -{ - static_maps_.clear(); - return true; -} - -bool move_base::MoveBase::removeAllLaserScans() -{ - laser_scans_.clear(); - return true; -} - -bool move_base::MoveBase::removeAllPointClouds() -{ - point_clouds_.clear(); - return true; -} - -bool move_base::MoveBase::removeAllPointCloud2s() -{ - point_cloud2s_.clear(); - return true; -} - -bool move_base::MoveBase::removeAllData() -{ - static_maps_.clear(); - laser_scans_.clear(); - point_clouds_.clear(); - point_cloud2s_.clear(); - return true; -} - -template -void move_base::MoveBase::updateGlobalCostmap(const T& value, robot_costmap_2d::LayerType layer_type, const std::string &name) -{ - if (!planner_costmap_robot_) - return; - - // Tìm layer phù hợp và update với data đã cho - try - { - for (const auto &layer : *planner_costmap_robot_->getLayeredCostmap()->getPlugins()) - { - // Kiểm tra layer có đúng type và name không - // Nếu layer type khớp HOẶC name khớp thì update - // if(layer->getType() == robot_costmap_2d::LayerType::STATIC_LAYER) - // robot::log_warning ("[%s:%d] Update GlobalCostmap: layer type: %d, name: %s, layer->getType(): %d, layer->getName(): %s", __FILE__, __LINE__, layer_type, name.c_str(), layer->getType(), layer->getName().c_str()); - if (layer->getType() == layer_type || layer->getName() == name) - { - if(layer->getType() == robot_costmap_2d::LayerType::STATIC_LAYER) - { - robot::log_warning("[%s:%d] Update GlobalCostmap: layer type is STATIC_LAYER, name: %s", __FILE__, __LINE__, name.c_str()); - } - - // Update costmap với data - layer->dataCallBack(value, name); - } - } - } - catch (const std::exception &ex) - { - robot::log_error("[%s:%d] EXCEPTION in Update GlobalCostmap: %s", __FILE__, __LINE__, ex.what()); - return; - } -} - -template -void move_base::MoveBase::updateLocalCostmap(const T& value, robot_costmap_2d::LayerType layer_type, const std::string &name) -{ - if (!controller_costmap_robot_) - return; - - // Tìm layer phù hợp và update với data đã cho - try - { - for (const auto &layer : *controller_costmap_robot_->getLayeredCostmap()->getPlugins()) - { - // Kiểm tra layer có đúng type và name không - // Nếu layer type khớp HOẶC name khớp thì update - if (layer->getType() == layer_type || layer->getName() == name) - { - // Update costmap với data - layer->dataCallBack(value, name); - } - } - } - catch (const std::exception &ex) - { - robot::log_error("[%s:%d] EXCEPTION in Update LocalCostmap: %s", __FILE__, __LINE__, ex.what()); - return; - } -} - -void move_base::MoveBase::addOdometry(const std::string &odometry_name, robot_nav_msgs::Odometry odometry) -{ - // robot::log_info("addOdometry: %s", odometry_name.c_str()); - // robot::log_info("odometry header: %s", odometry.header.frame_id.c_str()); - // robot::log_info("odometry child_frame_id: %s", odometry.child_frame_id.c_str()); - // if(tf_) - // { - // try - // { - // robot_geometry_msgs::PoseStamped global_pose_stamped; - // tf3::toMsg(tf3::Transform::getIdentity(), global_pose_stamped.pose); - // robot_geometry_msgs::PoseStamped robot_pose; - // tf3::toMsg(tf3::Transform::getIdentity(), robot_pose.pose); - // robot_pose.header.frame_id = robot_base_frame_; - // robot_pose.header.stamp = robot::Time(); - // robot::Time current_time = robot::Time::now(); // save time for checking tf delay later - - // // Convert robot::Time to tf3::Time - // tf3::Time tf3_current_time = data_convert::convertTime(current_time); - // tf3::Time tf3_zero_time = data_convert::convertTime(robot::Time()); - - // std::string error_msg; - // if (tf_->canTransform("odom", "base_link", tf3_current_time, &error_msg)) - // { - // // Transform is available at current time - // tf3::TransformStampedMsg transform = tf_->lookupTransform("odom", "base_link", tf3_current_time); - // tf3::doTransform(robot_pose, global_pose_stamped, transform); - // robot::log_info("TF x: %f y: %f theta: %f", global_pose_stamped.pose.position.x, global_pose_stamped.pose.position.y, data_convert::getYaw(global_pose_stamped.pose.orientation)); - // } - // } - // catch (const tf3::TransformException &ex) - // { - // robot::log_error("[addOdometry] Failed to lookup base_link in odom: %s", ex.what()); - // } - // // robot::log_info("allFramesAsString: \n%s", tf_->allFramesAsString().c_str()); - // } - // robot::log_info("odometry x: %f y: %f theta: %f", odometry.pose.pose.position.x, odometry.pose.pose.position.y, data_convert::getYaw(odometry.pose.pose.orientation)); - // std::stringstream pose_covariance_str; - // for(int i = 0; i < 36; i++) { - // pose_covariance_str << odometry.pose.covariance[i] << " "; - // } - // robot::log_info("odometry pose covariance: %s", pose_covariance_str.str().c_str()); - // robot::log_info("odometry twist linear x: %f", odometry.twist.twist.linear.x); - // robot::log_info("odometry twist linear y: %f", odometry.twist.twist.linear.y); - // robot::log_info("odometry twist linear z: %f", odometry.twist.twist.linear.z); - // robot::log_info("odometry twist angular x: %f", odometry.twist.twist.angular.x); - // robot::log_info("odometry twist angular y: %f", odometry.twist.twist.angular.y); - // robot::log_info("odometry twist angular z: %f", odometry.twist.twist.angular.z); - // std::stringstream twist_covariance_str; - // for(int i = 0; i < 36; i++) { - // twist_covariance_str << odometry.twist.covariance[i] << " "; - // } - // robot::log_info("odometry twist covariance: %s", twist_covariance_str.str().c_str()); - // robot::log_info("--------------------------------"); - - odometry_ = odometry; -} - -bool move_base::MoveBase::moveTo( const robot_geometry_msgs::PoseStamped &goal, - double xy_goal_tolerance, double yaw_goal_tolerance) -{ - if (setup_) - { - robot::NodeHandle nh_planner = robot::NodeHandle(private_nh_, position_planner_name_); - if(nh_planner.hasParam("base_global_planner")) - { - std::string base_global_planner; - nh_planner.getParam("base_global_planner", base_global_planner); - swapPlanner(base_global_planner); - } - else - { - swapPlanner(default_config_.base_global_planner); - } - } - else - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("The system has not been installed yet"); - nav_feedback_->goal_checked = false; - } - return false; - } - - // Set XY goal tolerance - double final_xy_tolerance; - if (fabs(xy_goal_tolerance) > 0.001) - { - final_xy_tolerance = fabs(xy_goal_tolerance); - this->setXyGoalTolerance(final_xy_tolerance); - } - else - { - final_xy_tolerance = fabs(original_xy_goal_tolerance_); - this->setXyGoalTolerance(final_xy_tolerance); - } - - // Set Yaw goal tolerance - double final_yaw_tolerance; - if (fabs(yaw_goal_tolerance) > 0.001) - { - final_yaw_tolerance = fabs(yaw_goal_tolerance); - this->setYawGoalTolerance(final_yaw_tolerance); - } - else - { - final_yaw_tolerance = fabs(original_yaw_goal_tolerance_); - this->setYawGoalTolerance(final_yaw_tolerance); - } - - // Check pointers - if (!tc_) - { - robot::log_error("[MoveBase::moveTo] tc_ pointer is null"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("Internal error: null tc_"); - nav_feedback_->goal_checked = false; - } - return false; - } - if (!controller_costmap_robot_) - { - robot::log_error("[MoveBase::moveTo] controller_costmap_robot_ pointer is null"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("Internal error: null controller_costmap_robot_"); - nav_feedback_->goal_checked = false; - } - return false; - } - - boost::unique_lock lock(*(controller_costmap_robot_->getCostmap()->getMutex())); - - // Swap planner - try - { - if (!tc_->swapPlanner(position_planner_name_)) - { - robot::log_error("[MoveBase::moveTo] Failed to swapPlanner"); - return false; - } - } - catch (const std::exception &e) - { - robot::log_error("[MoveBase::moveTo] Exception in swapPlanner: %s", e.what()); - lock.unlock(); - return false; - } - - // Update navigation feedback - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::PLANNING; - nav_feedback_->feed_back_str = std::string("Planning"); - nav_feedback_->goal_checked = false; - } - else - { - robot::log_error("[MoveBase::moveTo] nav_feedback_ pointer is null!"); - lock.unlock(); - return false; - } - - // Reset cancel flag - if (cancel_ctr_) - { - cancel_ctr_ = false; - } - // Check if action server exists - if (!as_) - { - robot::log_error("[MoveBase::moveTo] as_ pointer is null!"); - lock.unlock(); - return false; - } - - try - { - robot_move_base_msgs::MoveBaseActionGoalPtr action_goal = boost::make_shared(); - action_goal->header.stamp = robot::Time::now(); - action_goal->goal.target_pose = goal; - - // Generate unique goal ID using timestamp - robot::Time now = robot::Time::now(); - action_goal->goal_id.stamp = now; - std::ostringstream goal_id_stream; - goal_id_stream << "move_base_goal_" << now.sec << "_" << now.nsec; - action_goal->goal_id.id = goal_id_stream.str(); - - robot::log_info("[MoveBase::moveTo] Generated goal ID: %s", action_goal->goal_id.id.c_str()); - robot::log_info("[MoveBase::moveTo] Goal stamp: %ld.%09ld", - action_goal->goal_id.stamp.sec, action_goal->goal_id.stamp.nsec); - - // Clear Order message since this is a non-Order moveTo call - { - boost::unique_lock planner_lock(planner_mutex_); - planner_order_.reset(); - } - - robot::log_info("[MoveBase::moveTo] Processing goal through action server..."); - as_->processGoal(action_goal); - robot::log_info("[MoveBase::moveTo] Goal processed successfully by action server"); - } - catch (const std::exception &e) - { - lock.unlock(); - robot::log_error("[MoveBase::moveTo] Exception during processGoal: %s", e.what()); - return false; - } - lock.unlock(); - return true; -} - -bool move_base::MoveBase::moveTo(const robot_protocol_msgs::Order &msg, - const robot_geometry_msgs::PoseStamped &goal, - double xy_goal_tolerance, double yaw_goal_tolerance) -{ - if (setup_) - { - robot::NodeHandle nh_planner = robot::NodeHandle(private_nh_, position_planner_name_); - if(nh_planner.hasParam("base_global_planner")) - { - std::string base_global_planner; - nh_planner.getParam("base_global_planner", base_global_planner); - swapPlanner(base_global_planner); - } - else - { - swapPlanner(default_config_.base_global_planner); - } - } - else - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("The system has not been installed yet"); - nav_feedback_->goal_checked = false; - } - return false; - } - - if (fabs(xy_goal_tolerance) > 0.001) - this->setXyGoalTolerance(fabs(xy_goal_tolerance)); - else - this->setXyGoalTolerance(fabs(original_xy_goal_tolerance_)); - - if (fabs(yaw_goal_tolerance) > 0.001) - this->setYawGoalTolerance(fabs(yaw_goal_tolerance)); - else - this->setYawGoalTolerance(fabs(original_yaw_goal_tolerance_)); - robot::Duration(0.01).sleep(); - - if (!tc_) - { - robot::log_error("[MoveBase::moveTo] tc_ pointer is null"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("Internal error: null tc_"); - nav_feedback_->goal_checked = false; - } - return false; - } - if (!controller_costmap_robot_) - { - robot::log_error("[MoveBase::moveTo] controller_costmap_robot_ pointer is null"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("Internal error: null controller_costmap_robot_"); - nav_feedback_->goal_checked = false; - } - return false; - } - boost::unique_lock lock(*(controller_costmap_robot_->getCostmap()->getMutex())); - - try - { - if (!tc_->swapPlanner(position_planner_name_)) - { - robot::log_error("[MoveBase::moveTo] Failed to swapPlanner"); - return false; - } - } - catch (const std::exception &e) - { - robot::log_error("[MoveBase::moveTo] Exception in swapPlanner: %s", e.what()); - lock.unlock(); - return false; - } - - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::PLANNING; - nav_feedback_->feed_back_str = std::string("Planning"); - nav_feedback_->goal_checked = false; - } - else - { - robot::log_error("[MoveBase::moveTo] nav_feedback_ pointer is null!"); - lock.unlock(); - return false; - } - - if (cancel_ctr_) - cancel_ctr_ = false; - - if (!as_) - { - robot::log_error("[MoveBase::moveTo] as_ pointer is null!"); - lock.unlock(); - return false; - } - - try - { - robot_move_base_msgs::MoveBaseActionGoalPtr action_goal = boost::make_shared(); - action_goal->header.stamp = robot::Time::now(); - action_goal->goal.target_pose = goal; - - robot::Time now = robot::Time::now(); - action_goal->goal_id.stamp = now; - std::ostringstream goal_id_stream; - goal_id_stream << "move_base_goal_" << now.sec << "_" << now.nsec; - action_goal->goal_id.id = goal_id_stream.str(); - - robot::log_info("[MoveBase::moveTo] Generated goal ID: %s", action_goal->goal_id.id.c_str()); - - // Store Order message for use in planThread - { - boost::unique_lock planner_lock(planner_mutex_); - planner_order_ = boost::make_shared(msg); - robot::log_info("[MoveBase::moveTo] Stored Order message for planning"); - } - if (!planner_order_) - { - robot::log_error("[MoveBase::moveTo] Failed to store Order message for planning"); - lock.unlock(); - return false; - } - - as_->processGoal(action_goal); - } - catch (const std::exception &e) - { - robot::log_error("[MoveBase::moveTo] Exception during processGoal: %s", e.what()); - lock.unlock(); - return false; - } - - lock.unlock(); - return true; -} - -bool move_base::MoveBase::dockTo(const std::string &marker, const robot_geometry_msgs::PoseStamped &goal, - double xy_goal_tolerance, double yaw_goal_tolerance) -{ - std::string maker_sources; - private_nh_.param("maker_sources", maker_sources, std::string("")); - std::stringstream ss(maker_sources); - std::string source; - bool has_maker = false; - while (ss >> source) - { - if (marker == source) - { - private_nh_.setParam("maker_name", marker); - has_maker = true; - } - } - if (!has_maker) - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - std::stringstream fb_ss; - fb_ss << "The system has not been '" << marker << "'"; - nav_feedback_->feed_back_str = fb_ss.str(); - nav_feedback_->goal_checked = false; - } - return false; - } - - if (setup_) - { - robot::NodeHandle nh_planner = robot::NodeHandle(private_nh_, docking_planner_name_); - if(nh_planner.hasParam("base_global_planner")) - { - std::string base_global_planner; - nh_planner.getParam("base_global_planner", base_global_planner); - swapPlanner(base_global_planner); - } - else - { - swapPlanner(default_config_.base_global_planner); - } - } - else - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("The system has not been installed yet"); - nav_feedback_->goal_checked = false; - } - return false; - } - - if (fabs(xy_goal_tolerance) > 0.001) - this->setXyGoalTolerance(fabs(xy_goal_tolerance)); - else - this->setXyGoalTolerance(fabs(original_xy_goal_tolerance_)); - - if (fabs(yaw_goal_tolerance) > 0.001) - this->setYawGoalTolerance(fabs(yaw_goal_tolerance)); - else - this->setYawGoalTolerance(fabs(original_yaw_goal_tolerance_)); - - if (!tc_) - { - robot::log_error("[MoveBase::dockTo] tc_ pointer is null"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("Internal error: null tc_"); - nav_feedback_->goal_checked = false; - } - return false; - } - if (!controller_costmap_robot_) - { - robot::log_error("[MoveBase::dockTo] controller_costmap_robot_ pointer is null"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("Internal error: null controller_costmap_robot_"); - nav_feedback_->goal_checked = false; - } - return false; - } - boost::unique_lock lock(*(controller_costmap_robot_->getCostmap()->getMutex())); - try - { - if (!tc_->swapPlanner(docking_planner_name_)) - { - robot::log_error("[MoveBase::dockTo] Failed to swapPlanner"); - return false; - } - } - catch (const std::exception &e) - { - robot::log_error("[MoveBase::dockTo] Exception in swapPlanner: %s", e.what()); - lock.unlock(); - return false; - } - - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::PLANNING; - nav_feedback_->feed_back_str = std::string("Planning"); - nav_feedback_->goal_checked = false; - } - else - { - robot::log_error("[MoveBase::dockTo] nav_feedback_ pointer is null!"); - lock.unlock(); - return false; - } - if (cancel_ctr_) - cancel_ctr_ = false; - // Check if action server exists - if (!as_) - { - robot::log_error("[MoveBase::moveTo] as_ pointer is null!"); - lock.unlock(); - return false; - } - - try - { - robot_move_base_msgs::MoveBaseActionGoalPtr action_goal = boost::make_shared(); - action_goal->header.stamp = robot::Time::now(); - action_goal->goal.target_pose = goal; - - // Generate unique goal ID using timestamp - robot::Time now = robot::Time::now(); - action_goal->goal_id.stamp = now; - std::ostringstream goal_id_stream; - goal_id_stream << "move_base_goal_" << now.sec << "_" << now.nsec; - action_goal->goal_id.id = goal_id_stream.str(); - - robot::log_info("[MoveBase::moveTo] Generated goal ID: %s", action_goal->goal_id.id.c_str()); - robot::log_info("[MoveBase::moveTo] Goal stamp: %ld.%09ld", - action_goal->goal_id.stamp.sec, action_goal->goal_id.stamp.nsec); - - // Clear Order message since this is a non-Order moveTo call - { - boost::unique_lock planner_lock(planner_mutex_); - planner_order_.reset(); - } - - robot::log_info("[MoveBase::moveTo] Processing goal through action server..."); - as_->processGoal(action_goal); - robot::log_info("[MoveBase::moveTo] Goal processed successfully by action server"); - } - catch (const std::exception &e) - { - lock.unlock(); - robot::log_error("[MoveBase::moveTo] Exception during processGoal: %s", e.what()); - return false; - } - - lock.unlock(); - return true; -} - -bool move_base::MoveBase::dockTo(const robot_protocol_msgs::Order &msg, - const std::string &marker, - const robot_geometry_msgs::PoseStamped &goal, - double xy_goal_tolerance, double yaw_goal_tolerance) -{ - std::string maker_sources; - private_nh_.param("maker_sources", maker_sources, std::string("")); - std::stringstream ss(maker_sources); - std::string source; - bool has_maker = false; - while (ss >> source) - { - if (marker == source) - { - private_nh_.setParam("maker_name", marker); - has_maker = true; - } - } - if (!has_maker) - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - std::stringstream fb_ss; - fb_ss << "The system has not been '" << marker << "'"; - nav_feedback_->feed_back_str = fb_ss.str(); - nav_feedback_->goal_checked = false; - } - return false; - } - - if (setup_) - { - robot::NodeHandle nh_planner = robot::NodeHandle(private_nh_, docking_planner_name_); - if(nh_planner.hasParam("base_global_planner")) - { - std::string base_global_planner; - nh_planner.getParam("base_global_planner", base_global_planner); - swapPlanner(base_global_planner); - } - else - { - swapPlanner(default_config_.base_global_planner); - } - } - else - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("The system has not been installed yet"); - nav_feedback_->goal_checked = false; - } - return false; - } - - if (fabs(xy_goal_tolerance) > 0.001) - this->setXyGoalTolerance(fabs(xy_goal_tolerance)); - else - this->setXyGoalTolerance(fabs(original_xy_goal_tolerance_)); - - if (fabs(yaw_goal_tolerance) > 0.001) - this->setYawGoalTolerance(fabs(yaw_goal_tolerance)); - else - this->setYawGoalTolerance(fabs(original_yaw_goal_tolerance_)); - - if (!tc_) - { - throw std::runtime_error("Null 'tc_' pointer encountered"); - } - if (!controller_costmap_robot_) - { - throw std::runtime_error("Null 'controller_costmap_robot_' pointer encountered"); - } - boost::unique_lock lock(*(controller_costmap_robot_->getCostmap()->getMutex())); - try - { - if(!tc_->swapPlanner(docking_planner_name_)) - { - robot::log_error("[MoveBase::dockTo] Failed to swapPlanner"); - return false; - } - } - catch (const std::exception &e) - { - robot::log_error("[MoveBase::dockTo] Exception in swapPlanner: %s", e.what()); - lock.unlock(); - return false; - } - - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::PLANNING; - nav_feedback_->feed_back_str = std::string("Planning"); - nav_feedback_->goal_checked = false; - } - if (cancel_ctr_) - cancel_ctr_ = false; - - if (!as_) - { - robot::log_error("[MoveBase::dockTo] as_ pointer is null!"); - lock.unlock(); - return false; - } - - try - { - robot_move_base_msgs::MoveBaseActionGoalPtr action_goal = boost::make_shared(); - action_goal->header.stamp = robot::Time::now(); - action_goal->goal.target_pose = goal; - - robot::Time now = robot::Time::now(); - action_goal->goal_id.stamp = now; - std::ostringstream goal_id_stream; - goal_id_stream << "move_base_dock_goal_" << now.sec << "_" << now.nsec; - action_goal->goal_id.id = goal_id_stream.str(); - - robot::log_info("[MoveBase::dockTo] Generated goal ID: %s", action_goal->goal_id.id.c_str()); - - // Store Order message for use in planThread (same as moveTo with Order) - { - boost::unique_lock planner_lock(planner_mutex_); - planner_order_ = boost::make_shared(msg); - robot::log_info("[MoveBase::dockTo] Stored Order message for planning"); - } - if (!planner_order_) - { - robot::log_error("[MoveBase::dockTo] Failed to store Order message for planning"); - lock.unlock(); - return false; - } - as_->processGoal(action_goal); - } - catch (const std::exception &e) - { - robot::log_error("[MoveBase::dockTo] Exception during processGoal: %s", e.what()); - lock.unlock(); - return false; - } - - lock.unlock(); - return true; -} - -bool move_base::MoveBase::moveStraightTo(const robot_geometry_msgs::PoseStamped &goal, double xy_goal_tolerance) -{ - robot::log_info("[MoveBase::moveStraightTo] Entry"); - if (setup_) - { - std::string global_planner = "TwoPointsPlanner"; - robot::NodeHandle nh_planner = robot::NodeHandle(private_nh_, go_straight_planner_name_); - if(nh_planner.hasParam("base_global_planner")) - { - std::string base_global_planner; - nh_planner.getParam("base_global_planner", base_global_planner); - swapPlanner(base_global_planner); - } - else - { - swapPlanner(global_planner); - } - } - else - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("The system has not been installed yet"); - nav_feedback_->goal_checked = false; - } - return false; - } - if (fabs(xy_goal_tolerance) > 0.001) - this->setXyGoalTolerance(fabs(xy_goal_tolerance)); - else - this->setXyGoalTolerance(fabs(original_xy_goal_tolerance_)); - - if (!tc_) - { - robot::log_error("[MoveBase::moveStraightTo] tc_ pointer is null"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("Internal error: null tc_"); - nav_feedback_->goal_checked = false; - } - return false; - } - if (!controller_costmap_robot_) - { - robot::log_error("[MoveBase::moveStraightTo] controller_costmap_robot_ pointer is null"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("Internal error: null controller_costmap_robot_"); - nav_feedback_->goal_checked = false; - } - return false; - } - - boost::unique_lock lock(*(controller_costmap_robot_->getCostmap()->getMutex())); - - try - { - robot::log_info("[MoveBase::moveStraightTo] Entry swapPlanner"); - if (!tc_->swapPlanner(go_straight_planner_name_)) - { - robot::log_error("[MoveBase::moveStraightTo] Failed to swapPlanner"); - lock.unlock(); - return false; - } - } - catch (const std::exception &e) - { - robot::log_error("[MoveBase::moveStraightTo] Exception in swapPlanner: %s", e.what()); - lock.unlock(); - return false; - } - - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::PLANNING; - nav_feedback_->feed_back_str = std::string("Planning"); - nav_feedback_->goal_checked = false; - } - else - { - robot::log_error("[MoveBase::moveStraightTo] nav_feedback_ pointer is null!"); - lock.unlock(); - return false; - } - if (cancel_ctr_) - cancel_ctr_ = false; - - if (!as_) - { - robot::log_error("[MoveBase::moveStraightTo] as_ pointer is null!"); - lock.unlock(); - return false; - } - - try - { - robot_move_base_msgs::MoveBaseActionGoalPtr action_goal = boost::make_shared(); - action_goal->header.stamp = robot::Time::now(); - action_goal->goal.target_pose = goal; - - robot::Time now = robot::Time::now(); - action_goal->goal_id.stamp = now; - std::ostringstream goal_id_stream; - goal_id_stream << "move_base_goal_" << now.sec << "_" << now.nsec; - action_goal->goal_id.id = goal_id_stream.str(); - - robot::log_info("[MoveBase::moveStraightTo] Generated goal ID: %s", action_goal->goal_id.id.c_str()); - robot::log_info("[MoveBase::moveStraightTo] Goal stamp: %ld.%09ld", - action_goal->goal_id.stamp.sec, action_goal->goal_id.stamp.nsec); - - // Clear Order message since this is a non-Order moveStraightTo call - { - boost::unique_lock planner_lock(planner_mutex_); - planner_order_.reset(); - } - - robot::log_info("[MoveBase::moveStraightTo] Processing goal through action server..."); - as_->processGoal(action_goal); - robot::log_info("[MoveBase::moveStraightTo] Goal processed successfully by action server"); - } - catch (const std::exception &e) - { - lock.unlock(); - robot::log_error("[MoveBase::moveStraightTo] Exception during processGoal: %s", e.what()); - return false; - } - - lock.unlock(); - return true; -} - -bool move_base::MoveBase::rotateTo(const robot_geometry_msgs::PoseStamped &goal, double yaw_goal_tolerance) -{ - if (setup_) - { - std::string global_planner = "TwoPointsPlanner"; - robot::NodeHandle nh_planner = robot::NodeHandle(private_nh_, rotate_planner_name_); - if(nh_planner.hasParam("base_global_planner")) - { - std::string base_global_planner; - nh_planner.getParam("base_global_planner", base_global_planner); - swapPlanner(base_global_planner); - } - else - { - swapPlanner(global_planner); - } - } - else - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("The system has not been installed yet"); - nav_feedback_->goal_checked = false; - } - return false; - } - - this->setXyGoalTolerance(std::numeric_limits::infinity()); - - if (fabs(yaw_goal_tolerance) > 0.001) - this->setYawGoalTolerance(fabs(yaw_goal_tolerance)); - else - this->setYawGoalTolerance(fabs(original_yaw_goal_tolerance_)); - - if (!tc_) - { - robot::log_error("[MoveBase::rotateTo] tc_ pointer is null"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("Internal error: null tc_"); - nav_feedback_->goal_checked = false; - } - return false; - } - if (!controller_costmap_robot_) - { - robot::log_error("[MoveBase::rotateTo] controller_costmap_robot_ pointer is null"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("Internal error: null controller_costmap_robot_"); - nav_feedback_->goal_checked = false; - } - return false; - } - boost::unique_lock lock(*(controller_costmap_robot_->getCostmap()->getMutex())); - - try - { - if (!tc_->swapPlanner(rotate_planner_name_)) - { - robot::log_error("[MoveBase::rotateTo] Failed to swapPlanner"); - lock.unlock(); - return false; - } - } - catch (const std::exception &e) - { - robot::log_error("[MoveBase::rotateTo] Exception in swapPlanner: %s", e.what()); - lock.unlock(); - return false; - } - - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::PLANNING; - nav_feedback_->feed_back_str = std::string("Planning"); - nav_feedback_->goal_checked = false; - } - else - { - robot::log_error("[MoveBase::rotateTo] nav_feedback_ pointer is null!"); - lock.unlock(); - return false; - } - if (cancel_ctr_) - cancel_ctr_ = false; - - if (!as_) - { - robot::log_error("[MoveBase::rotateTo] as_ pointer is null!"); - lock.unlock(); - return false; - } - - try - { - robot_geometry_msgs::Pose2D pose; - if (!this->getRobotPose(pose)) - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::REJECTED; - nav_feedback_->feed_back_str = std::string("Couldn't get robot pose"); - nav_feedback_->goal_checked = false; - } - lock.unlock(); - return false; - } - - robot_move_base_msgs::MoveBaseActionGoalPtr action_goal = boost::make_shared(); - action_goal->header.stamp = robot::Time::now(); - action_goal->goal.target_pose = goal; - double distance = planner_costmap_robot_ ? planner_costmap_robot_->getCostmap()->getResolution() : 0.05; - action_goal->goal.target_pose.pose.position.x = pose.x + distance * cos(pose.theta); - action_goal->goal.target_pose.pose.position.y = pose.y + distance * sin(pose.theta); - - robot::Time now = robot::Time::now(); - action_goal->goal_id.stamp = now; - std::ostringstream goal_id_stream; - goal_id_stream << "move_base_goal_" << now.sec << "_" << now.nsec; - action_goal->goal_id.id = goal_id_stream.str(); - - robot::log_info("[MoveBase::rotateTo] Generated goal ID: %s", action_goal->goal_id.id.c_str()); - robot::log_info("[MoveBase::rotateTo] Goal stamp: %ld.%09ld", - action_goal->goal_id.stamp.sec, action_goal->goal_id.stamp.nsec); - - // Clear Order message since this is a non-Order rotateTo call - { - boost::unique_lock planner_lock(planner_mutex_); - planner_order_.reset(); - } - - robot::log_info("[MoveBase::rotateTo] Processing goal through action server..."); - as_->processGoal(action_goal); - robot::log_info("[MoveBase::rotateTo] Goal processed successfully by action server"); - } - catch (const std::exception &e) - { - lock.unlock(); - robot::log_error("[MoveBase::rotateTo] Exception during processGoal: %s", e.what()); - return false; - } - - lock.unlock(); - return true; -} - -void move_base::MoveBase::pause() -{ - if (!controller_costmap_robot_) - { - throw std::runtime_error("Null 'controller_costmap_robot_' pointer encountered"); - } - boost::unique_lock lock(*(controller_costmap_robot_->getCostmap()->getMutex())); - if (!tc_) - { - throw std::runtime_error("Null 'tc_' pointer encountered"); - } - - try - { - old_linear_fwd_ = tc_->getTwistLinear(true); - old_linear_bwd_ = tc_->getTwistLinear(false); - - old_angular_fwd_ = tc_->getTwistAngular(true); - old_angular_rev_ = tc_->getTwistAngular(false); - } - catch (const std::exception &e) - { - std::cerr << e.what() << '\n'; - } - pause_ctr_ = true; - paused_ = false; -} - -void move_base::MoveBase::resume() -{ - if (!controller_costmap_robot_) - { - throw std::runtime_error("Null 'controller_costmap_robot_' pointer encountered"); - } - boost::unique_lock lock(*(controller_costmap_robot_->getCostmap()->getMutex())); - if (!tc_) - { - throw std::runtime_error("Null 'tc_' pointer encountered"); - } - tc_->setTwistLinear(old_linear_fwd_); - tc_->setTwistLinear(old_linear_bwd_); - - tc_->setTwistAngular(old_angular_fwd_); - tc_->setTwistAngular(old_angular_rev_); - - pause_ctr_ = false; - paused_ = false; -} - -void move_base::MoveBase::cancel() -{ - robot::log_info("[MoveBase::cancel] ===== ENTRY ====="); - - if (!controller_costmap_robot_) - { - robot::log_error("[MoveBase::cancel] controller_costmap_robot_ is null!"); - throw std::runtime_error("Null 'controller_costmap_robot_' pointer encountered"); - } - - boost::unique_lock lock(*(controller_costmap_robot_->getCostmap()->getMutex())); - cancel_ctr_ = true; - robot::log_info("[MoveBase::cancel] cancel_ctr_ set to true"); -} - -bool move_base::MoveBase::getRobotPose(robot_geometry_msgs::PoseStamped &pose) -{ - if (!initialized_) - return false; - this->getRobotPose(pose, planner_costmap_robot_); - return true; -} - -bool move_base::MoveBase::getRobotPose(robot_geometry_msgs::Pose2D &pose) -{ - if (!initialized_) - return false; - robot_geometry_msgs::PoseStamped global_pose; - this->getRobotPose(global_pose, planner_costmap_robot_); - pose.x = global_pose.pose.position.x; - pose.y = global_pose.pose.position.y; - - tf3::Quaternion quaternion = tf3::Quaternion( - global_pose.pose.orientation.x, - global_pose.pose.orientation.y, - global_pose.pose.orientation.z, - global_pose.pose.orientation.w); - - pose.theta = tf3::getYaw(quaternion); - return true; -} - -bool move_base::MoveBase::setTwistLinear(const robot_geometry_msgs::Vector3 &linear) -{ - try - { - if (tc_ && !cancel_ctr_) - { - if (tc_->islock()) - return true; - return tc_->setTwistLinear(linear); - } - else if (tc_ && cancel_ctr_) - { - tc_->unlock(); - return false; - } - else - { - throw std::runtime_error("Null 'tc_' pointer encountered"); - } - } - catch (const std::exception &e) - { - return false; - } -} - -bool move_base::MoveBase::setTwistAngular(const robot_geometry_msgs::Vector3 &angular) -{ - if (tc_ && !cancel_ctr_) - { - if (tc_->islock()) - return true; - return tc_->setTwistAngular(angular); - } - else if (tc_ && cancel_ctr_) - { - return false; - } - else - { - throw std::runtime_error("Null 'tc_' pointer encountered"); - } - return false; -} - -void move_base::MoveBase::setYawGoalTolerance(double yaw_goal_tolerance) -{ - double yaw = 0.0; - if (private_nh_.getParam("yaw_goal_tolerance", yaw, 0.0)) - { - private_nh_.setParam("yaw_goal_tolerance", yaw_goal_tolerance); - robot::log_info("yaw_goal_tolerance %s is %f", private_nh_.getNamespace().c_str(), yaw_goal_tolerance); - } - else - robot::log_error("yaw_goal_tolerance couldn't get namespace is %s", private_nh_.getNamespace().c_str()); -} - -void move_base::MoveBase::setXyGoalTolerance(double xy_goal_tolerance) -{ - double xy = 0.0; - if (private_nh_.getParam("xy_goal_tolerance", xy, 0.0)) - { - private_nh_.setParam("xy_goal_tolerance", xy_goal_tolerance); - robot::log_info("xy_goal_tolerance %s is %f", private_nh_.getNamespace().c_str(), xy_goal_tolerance); - } - else - robot::log_error("xy_goal_tolerance couldn't get namespace is %s", private_nh_.getNamespace().c_str()); -} - -bool move_base::MoveBase::makePlan(const robot_geometry_msgs::PoseStamped &goal, std::vector &plan) -{ - // make sure to set the plan to be empty initially - plan.clear(); - - // since this gets called on handle activate - if (!planner_costmap_robot_) - { - robot::log_error("Planner costmap ROS is NULL, unable to create global plan"); - return false; - } - - boost::unique_lock lock(*(planner_costmap_robot_->getCostmap()->getMutex())); - - // get the starting pose of the robot - robot_geometry_msgs::PoseStamped global_pose; - if (!getRobotPose(global_pose, planner_costmap_robot_)) - { - robot::log_error("Unable to get starting pose of robot, unable to create global plan"); - return false; - } - - const robot_geometry_msgs::PoseStamped &start = global_pose; - - // if the planner fails or returns a zero length plan, planning failed - if (!planner_->makePlan(start, goal, plan) || plan.empty()) - { - robot::log_error("Failed to find a plan without Order to point (%f, %f)", goal.pose.position.x, goal.pose.position.y); - return false; - } - else - { - global_data_.plan = robot_nav_2d_utils::posesToPath2D(plan); - } - lock.unlock(); - return true; -} - -bool move_base::MoveBase::makePlan(const robot_protocol_msgs::Order &msg, const robot_geometry_msgs::PoseStamped &goal, std::vector &plan) -{ - // make sure to set the plan to be empty initially - plan.clear(); - - // since this gets called on handle activate - if (!planner_costmap_robot_) - { - robot::log_error("Planner costmap ROS is NULL, unable to create global plan"); - return false; - } - - boost::unique_lock lock(*(planner_costmap_robot_->getCostmap()->getMutex())); - - // get the starting pose of the robot - robot_geometry_msgs::PoseStamped global_pose; - if (!getRobotPose(global_pose, planner_costmap_robot_)) - { - robot::log_error("Unable to get starting pose of robot, unable to create global plan"); - return false; - } - - const robot_geometry_msgs::PoseStamped &start = global_pose; - - // if the planner fails or returns a zero length plan, planning failed - if (!planner_->makePlan(msg, start, goal, plan) || plan.empty()) - { - robot::log_error("Failed to find a plan with Order to point (%f, %f)", goal.pose.position.x, goal.pose.position.y); - return false; - } - else - { - global_data_.plan = robot_nav_2d_utils::posesToPath2D(plan); - } - lock.unlock(); - return true; -} -bool move_base::MoveBase::loadRecoveryBehaviors(const robot::NodeHandle &node) -{ - YAML::Node behavior_list = node.getParamValue("recovery_behaviors"); - if (behavior_list && behavior_list.IsSequence()) - { - // Validate all behaviors first - for (size_t i = 0; i < behavior_list.size(); ++i) - { - YAML::Node behavior = behavior_list[i].as(); - if (!behavior.IsMap()) - { - robot::log_warning("Recovery behaviors must be specified as maps. We'll use the default recovery behaviors instead."); - return false; - } - - if (!behavior["name"] || !behavior["type"]) - { - robot::log_warning("Recovery behaviors must have a name and a type. Using the default recovery behaviors instead."); - return false; - } - - // check for recovery behaviors with the same name - std::string name_i = behavior["name"].as(); - for (size_t j = i + 1; j < behavior_list.size(); ++j) - { - YAML::Node behavior_j = behavior_list[j].as(); - if (behavior_j.IsMap() && behavior_j["name"]) - { - std::string name_j = behavior_j["name"].as(); - if (name_i == name_j) - { - robot::log_warning("A recovery behavior with the name %s already exists, this is not allowed. Using the default recovery behaviors instead.", name_i.c_str()); - return false; - } - } - } - } - - // if we've made it to this point, we know that the list is legal so we'll create all the recovery behaviors - for (size_t i = 0; i < behavior_list.size(); ++i) - { - try - { - YAML::Node behavior = behavior_list[i].as(); - // Load recovery behavior using boost::dll::import_alias - // behavior["type"] should be the factory function name (e.g., "create_plugin") - std::string behavior_type = behavior["type"].as(); - std::string behavior_name = behavior["name"].as(); - robot::PluginLoaderHelper loader; - std::string path_file_so = loader.findLibraryPath(behavior_type); - robot::log_info("Loading recovery behavior '%s' of type '%s' from '%s'", behavior_name.c_str(), behavior_type.c_str(), path_file_so.c_str()); - // Load the factory function from the shared library - recovery_loaders_[behavior_name] = boost::dll::import_alias( - path_file_so, behavior_type, boost::dll::load_mode::append_decorations); - - // Create instance using the factory function - std::shared_ptr behavior_ptr(recovery_loaders_[behavior_name]()); - - // shouldn't be possible, but it won't hurt to check - if (behavior_ptr == nullptr) - { - std::cerr << "The factory function returned a null pointer without throwing an exception. This should not happen" << std::endl; - return false; - } - // initialize the recovery behavior with its name - behavior_ptr->initialize(behavior_name, tf_.get(), planner_costmap_robot_, controller_costmap_robot_); - recovery_behavior_names_.push_back(behavior_name); - recovery_behaviors_.push_back(behavior_ptr); - } - catch (const std::exception &ex) - { - std::cerr << "Failed to load recovery behavior plugin: " << behavior_list[i]["type"].as() - << ". Error: " << ex.what() << std::endl; - return false; - } - } - } - else if (behavior_list) - { - std::cerr << "The recovery behavior specification must be a list. We'll use the default recovery behaviors instead." << std::endl; - return false; - } - else - { - // if no recovery_behaviors are specified, we'll just load the defaults - return false; - } - - // if we've made it here... we've constructed a recovery behavior list successfully - return true; -} - -void move_base::MoveBase::loadDefaultRecoveryBehaviors() -{ - recovery_behaviors_.clear(); - recovery_behavior_names_.clear(); - - try - { - // Note: Parameters should be set via YAML config file, not programmatically - // The recovery behaviors will read their parameters from the YAML node during initialization - // first, we'll load a recovery behavior to clear the costmap (conservative reset) - try - { - std::string path_file_so; - auto clear_costmap_loader = boost::dll::import_alias( - path_file_so, "clear_costmap_recovery", boost::dll::load_mode::append_decorations); - std::shared_ptr cons_clear(clear_costmap_loader()); - cons_clear->initialize("conservative_reset", tf_.get(), planner_costmap_robot_, controller_costmap_robot_); - recovery_behavior_names_.push_back("conservative_reset"); - recovery_behaviors_.push_back(cons_clear); - } - catch (const std::exception &ex) - { - robot::log_error("[%s:%d] Failed to load clear_costmap_recovery plugin: %s", __FILE__, __LINE__, ex.what()); - } - - // next, we'll load a recovery behavior to rotate in place - std::shared_ptr rotate; - if (clearing_rotation_allowed_) - { - try - { - std::string path_file_so; - auto rotate_loader = boost::dll::import_alias( - path_file_so, "rotate_recovery", boost::dll::load_mode::append_decorations); - rotate = std::shared_ptr(rotate_loader()); - rotate->initialize("rotate_recovery", tf_.get(), planner_costmap_robot_, controller_costmap_robot_); - recovery_behavior_names_.push_back("rotate_recovery"); - recovery_behaviors_.push_back(rotate); - } - catch (const std::exception &ex) - { - robot::log_error("[%s:%d] Failed to load rotate_recovery plugin: %s", __FILE__, __LINE__, ex.what()); - } - } - - // next, we'll load a recovery behavior that will do an aggressive reset of the costmap - try - { - std::string path_file_so; - auto clear_costmap_loader = boost::dll::import_alias( - path_file_so, "clear_costmap_recovery", boost::dll::load_mode::append_decorations); - std::shared_ptr ags_clear(clear_costmap_loader()); - ags_clear->initialize("aggressive_reset", tf_.get(), planner_costmap_robot_, controller_costmap_robot_); - recovery_behavior_names_.push_back("aggressive_reset"); - recovery_behaviors_.push_back(ags_clear); - } - catch (const std::exception &ex) - { - std::cerr << "Failed to load clear_costmap_recovery plugin for aggressive reset: " << ex.what() << std::endl; - } - - // we'll rotate in-place one more time - if (clearing_rotation_allowed_ && rotate) - { - recovery_behaviors_.push_back(rotate); - recovery_behavior_names_.push_back("rotate_recovery"); - } - } - catch (const std::exception &ex) - { - std::cerr << "Failed to load default recovery behaviors. Error: " << ex.what() << std::endl; - } - - return; -} - -void move_base::MoveBase::clearCostmapWindows(double size_x, double size_y) -{ - robot_geometry_msgs::PoseStamped global_pose; - - // clear the planner's costmap - getRobotPose(global_pose, planner_costmap_robot_); - - std::vector clear_poly; - double x = global_pose.pose.position.x; - double y = global_pose.pose.position.y; - robot_geometry_msgs::Point pt; - - pt.x = x - size_x / 2; - pt.y = y - size_y / 2; - clear_poly.push_back(pt); - - pt.x = x + size_x / 2; - pt.y = y - size_y / 2; - clear_poly.push_back(pt); - - pt.x = x + size_x / 2; - pt.y = y + size_y / 2; - clear_poly.push_back(pt); - - pt.x = x - size_x / 2; - pt.y = y + size_y / 2; - clear_poly.push_back(pt); - - planner_costmap_robot_->getCostmap()->setConvexPolygonCost(clear_poly, robot_costmap_2d::FREE_SPACE); - - // clear the controller's costmap - getRobotPose(global_pose, controller_costmap_robot_); - - clear_poly.clear(); - x = global_pose.pose.position.x; - y = global_pose.pose.position.y; - - pt.x = x - size_x / 2; - pt.y = y - size_y / 2; - clear_poly.push_back(pt); - - pt.x = x + size_x / 2; - pt.y = y - size_y / 2; - clear_poly.push_back(pt); - - pt.x = x + size_x / 2; - pt.y = y + size_y / 2; - clear_poly.push_back(pt); - - pt.x = x - size_x / 2; - pt.y = y + size_y / 2; - clear_poly.push_back(pt); - - controller_costmap_robot_->getCostmap()->setConvexPolygonCost(clear_poly, robot_costmap_2d::FREE_SPACE); -} - -void move_base::MoveBase::publishZeroVelocity() -{ - twist_.velocity.x = 0.0; - twist_.velocity.y = 0.0; - twist_.velocity.theta = 0.0; - twist_.header.stamp = robot::Time::now(); - twist_.header.frame_id = robot_base_frame_; -} - -void move_base::MoveBase::resetState() -{ - // Disable the planner thread - boost::unique_lock lock(planner_mutex_); - runPlanner_ = false; - lock.unlock(); - - // Reset statemachine - state_ = move_base::PLANNING; - - recovery_index_ = 0; - recovery_trigger_ = PLANNING_R; - paused_ = false; - publishZeroVelocity(); - - // if we shutdown our costmaps when we're deactivated... we'll do that now - if (shutdown_costmaps_) - { - robot::log_info("Stopping costmaps"); - planner_costmap_robot_->stop(); - controller_costmap_robot_->stop(); - } -} - -void move_base::MoveBase::wakePlanner(const robot::TimerEvent &event) -{ - - // Nếu timer bị delay quá nhiều, có thể bỏ qua - robot::Duration drift = event.current_real - event.current_expected; - - if (drift.toSec() > 0.5) // Delay quá nhiều - { - // Có thể skip một số công việc không quan trọng - return; - } - // we have slept long enough for rate - planner_cond_.notify_one(); -} - -void move_base::MoveBase::planThread() -{ - robot::Timer timer; - bool wait_for_wake = false; - boost::unique_lock lock(planner_mutex_); - while (true) - { - // check if we should run the planner (the mutex is locked) - while (wait_for_wake || !runPlanner_) - { - // if we should not be running the planner then suspend this thread - robot::log_info("Planner thread is suspending"); - planner_cond_.wait(lock); - wait_for_wake = false; - } - robot::Time start_time = robot::Time::now(); - - // time to plan! get a copy of the goal and Order message (if available) and unlock the mutex - robot_geometry_msgs::PoseStamped temp_goal = planner_goal_; - boost::shared_ptr temp_order = planner_order_; - lock.unlock(); - robot::log_info("Planning..."); - // run planner - planner_plan_->clear(); - // ROS_INFO("MakePlan goal %f %f", temp_goal.pose.position.x, temp_goal.pose.position.y); - - // Choose makePlan based on whether Order message is available - bool gotPlan = false; - if (temp_order) - { - // Use Order-based makePlan - robot::log_info("[MoveBase::planThread] Using Order-based planning"); - gotPlan = makePlan(*temp_order, temp_goal, *planner_plan_); - } - else - { - // Use standard makePlan without Order - robot::log_info("[MoveBase::planThread] Using standard planning (no Order)"); - gotPlan = makePlan(temp_goal, *planner_plan_); - } - - if (gotPlan) - { - robot::log_info("Got Plan with %d points!", planner_plan_->size()); - // pointer swap the plans under mutex (the controller will pull from latest_plan_) - std::vector *temp_plan = planner_plan_; - - lock.lock(); - planner_plan_ = latest_plan_; - latest_plan_ = temp_plan; - last_valid_plan_ = robot::Time::now(); - planning_retries_ = 0; - new_global_plan_ = true; - - robot::log_info("Generated a plan from the base_global_planner"); - - // make sure we only start the controller if we still haven't reached the goal - if (runPlanner_) - { - state_ = move_base::CONTROLLING; - if (nav_feedback_) - nav_feedback_->navigation_state = robot::move_base_core::State::CONTROLLING; - } - if (planner_frequency_ <= 0) - runPlanner_ = false; - lock.unlock(); - } - // if we didn't get a plan and we are in the planning state (the robot isn't moving) - else if (state_ == move_base::PLANNING) - { - robot::Time attempt_end = last_valid_plan_ + robot::Duration(planner_patience_); - - // check if we've tried to make a plan for over our time limit or our maximum number of retries - // issue #496: we stop planning when one of the conditions is true, but if max_planning_retries_ - // is negative (the default), it is just ignored and we have the same behavior as ever - lock.lock(); - planning_retries_++; - if (runPlanner_ && - (robot::Time::now() > attempt_end || planning_retries_ > uint32_t(max_planning_retries_))) - { - // we'll move into our obstacle clearing mode - state_ = move_base::CLEARING; - if (nav_feedback_) - nav_feedback_->navigation_state = robot::move_base_core::State::CLEARING; - - runPlanner_ = false; // proper solution for issue #523 - publishZeroVelocity(); - recovery_trigger_ = PLANNING_R; - } - - lock.unlock(); - } - - // take the mutex for the next iteration - lock.lock(); - - // setup sleep interface if needed - if (planner_frequency_ > 0) - { - robot::Duration sleep_time = (start_time + robot::Duration(1.0 / planner_frequency_)) - robot::Time::now(); - if (sleep_time > robot::Duration(0.0)) - { - wait_for_wake = true; - timer = robot::Timer(sleep_time, &move_base::MoveBase::wakePlanner, this); - } - } - } -} - -void move_base::MoveBase::executeCb(const robot_move_base_msgs::MoveBaseGoalConstPtr &move_base_goal) -{ - if (!isQuaternionValid(move_base_goal->target_pose.pose.orientation)) - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::ABORTED; - nav_feedback_->feed_back_str = std::string("Aborting on goal because it was sent with an invalid quaternion"); - } - as_->setAborted(robot_move_base_msgs::MoveBaseResult(), "Aborting on goal because it was sent with an invalid quaternion"); - return; - } - else - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::ACTIVE; - nav_feedback_->feed_back_str = std::string("The goal is received"); - robot::log_info("Received goal: x=%.2f, y=%.2f", move_base_goal->target_pose.pose.position.x, move_base_goal->target_pose.pose.position.y); - } - } - robot::log_warning("Received goal: x=%.2f, y=%.2f", move_base_goal->target_pose.pose.position.x, move_base_goal->target_pose.pose.position.y); - robot_geometry_msgs::PoseStamped goal = goalToGlobalFrame(move_base_goal->target_pose); - robot::log_warning("Received goalToGlobalFrame: x=%.2f, y=%.2f", goal.pose.position.x, goal.pose.position.y); - publishZeroVelocity(); - // we have a goal so start the planner - boost::unique_lock lock(planner_mutex_); - planner_goal_ = goal; - runPlanner_ = true; - cancel_ctr_ = false; - planner_cond_.notify_one(); - lock.unlock(); - robot::Rate r(controller_frequency_); - if (shutdown_costmaps_) - { - robot::log_debug("[MoveBase] Starting up costmaps that were shut down previously"); - planner_costmap_robot_->start(); - controller_costmap_robot_->start(); - } - // we want to make sure that we reset the last time we had a valid plan and control - last_valid_control_ = robot::Time::now(); - last_valid_plan_ = robot::Time::now(); - last_oscillation_reset_ = robot::Time::now(); - planning_retries_ = 0; - - while(robot::ok()) - { - if (c_freq_change_) - { - robot::log_info("[MoveBase] Setting controller frequency to %.2f", controller_frequency_); - r = robot::Rate(controller_frequency_); - c_freq_change_ = false; - } - if (as_->isPreemptRequested()) - { - if (as_->isNewGoalAvailable()) - { - // if we're active and a new goal is available, we'll accept it, but we won't shut anything down - robot_move_base_msgs::MoveBaseGoal new_goal = *as_->acceptNewGoal(); - robot::log_info("[MoveBase] new goal %f %f", new_goal.target_pose.pose.position.x, new_goal.target_pose.pose.position.y); - if (!isQuaternionValid(new_goal.target_pose.pose.orientation)) - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::ABORTED; - nav_feedback_->feed_back_str = std::string("Aborting on goal because it was sent with an invalid quaternion"); - } - as_->setAborted(robot_move_base_msgs::MoveBaseResult(), "Aborting on goal because it was sent with an invalid quaternion"); - return; - } - else - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::ACTIVE; - nav_feedback_->feed_back_str = std::string("The new goal is received"); - } - } - - goal = goalToGlobalFrame(new_goal.target_pose); - // we'll make sure that we reset our state for the next execution cycle - recovery_index_ = 0; - state_ = move_base::PLANNING; - if (nav_feedback_) - nav_feedback_->navigation_state = robot::move_base_core::State::PLANNING; - // we have a new goal so make sure the planner is awake - lock.lock(); - planner_goal_ = goal; - // Clear Order message for new goal (will be set if moveTo with Order is called) - planner_order_.reset(); - runPlanner_ = true; - cancel_ctr_ = false; - planner_cond_.notify_one(); - lock.unlock(); - - // publish the goal point to the visualizer - robot::log_debug("[MoveBase] move_base has received a goal of x: %.2f, y: %.2f", goal.pose.position.x, goal.pose.position.y); - // make sure to reset our timeouts and counters - last_valid_control_ = robot::Time::now(); - last_valid_plan_ = robot::Time::now(); - last_oscillation_reset_ = robot::Time::now(); - planning_retries_ = 0; - } - else - { - // if we've been preempted explicitly we need to shut things down - resetState(); - - // notify the ActionServer that we've successfully preempted - robot::log_debug("[MoveBase] Move base preempting the current goal"); - as_->setPreempted(); - if (nav_feedback_) - { - nav_feedback_->feed_back_str = std::string("Move base preempting the current goal."); - nav_feedback_->navigation_state = robot::move_base_core::State::PREEMPTING; - } - // we'll actually return from execute after preempting - return; - } - } - - // we also want to check if we've changed global frames because we need to transform our goal pose - if (goal.header.frame_id != planner_costmap_robot_->getGlobalFrameID()) - { - goal = goalToGlobalFrame(goal); - - // we want to go back to the planning state for the next execution cycle - recovery_index_ = 0; - state_ = move_base::PLANNING; - if (nav_feedback_) - nav_feedback_->navigation_state = robot::move_base_core::State::PLANNING; - - // we have a new goal so make sure the planner is awake - lock.lock(); - planner_goal_ = goal; - // Clear Order message for new goal (will be set if moveTo with Order is called) - planner_order_.reset(); - runPlanner_ = true; - cancel_ctr_ = false; - planner_cond_.notify_one(); - lock.unlock(); - - // publish the goal point to the visualizer - robot::log_debug("[MoveBase] The global frame for move_base has changed, new frame: %s, new goal position x: %.2f, y: %.2f", goal.header.frame_id.c_str(), goal.pose.position.x, goal.pose.position.y); - - // make sure to reset our timeouts and counters - last_valid_control_ = robot::Time::now(); - last_valid_plan_ = robot::Time::now(); - last_oscillation_reset_ = robot::Time::now(); - planning_retries_ = 0; - } - - // // for timing that gives real time even in simulation - // ros::WallTime start = ros::WallTime::now(); - - // the real work on pursuing a goal is done here - bool done = executeCycle(goal); - - // if we're done, then we'll return from execute - if (done) - return; - - // check if execution of the goal has completed in some way - // ros::WallDuration t_diff = ros::WallTime::now() - start; - // ROS_DEBUG_NAMED("move_base", "Full control cycle time: %.9f\n", t_diff.toSec()); - - r.sleep(); - } -} - -void move_base::MoveBase::setupActionServerCallbacks() -{ - if (!as_) - { - robot::log_error("[MoveBase] Action server is not initialized"); - return; - } - - // Set callback for result publishing - // Customize this to send result to your communication system - as_->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("[MoveBase] 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 - as_->setFeedbackCallback( - [this](const robot_move_base_msgs::MoveBaseActionFeedbackConstPtr& feedback) - { - // TODO: Publish feedback to your communication system - robot::log_debug("[MoveBase] Published feedback"); - } - ); - - // Set callback for status publishing - // Customize this to send status to your communication system - as_->setStatusCallback( - [this](const robot_actionlib_msgs::GoalStatusArrayConstPtr& status) - { - // TODO: Publish status to your communication system (e.g., custom message bus, network, etc.) - } - ); - - // Set callback for goal messages (optional - for logging) - as_->setGoalCallback( - [this](const robot_move_base_msgs::MoveBaseActionGoalConstPtr& goal) - { - robot::log_info("[MoveBase] 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) - as_->setCancelCallback( - [this](const robot_actionlib_msgs::GoalIDConstPtr& cancel) - { - robot::log_info("[MoveBase] Cancel callback: id=%s", cancel->id.c_str()); - // Clear Order message for new goal (will be set if moveTo with Order is called) - boost::unique_lock planner_lock(planner_mutex_); - planner_order_.reset(); - } - ); - - // Set status publish rate (default is 10 Hz) - as_->setStatusPublishRate(10.0); - - robot::log_info("[MoveBase] Callbacks setup complete"); -} - -bool move_base::MoveBase::isQuaternionValid(const robot_geometry_msgs::Quaternion &q) -{ - // first we need to check if the quaternion has nan's or infs - if (!std::isfinite(q.x) || !std::isfinite(q.y) || !std::isfinite(q.z) || !std::isfinite(q.w)) - { - robot::log_error("Quaternion has nans or infs... discarding as a navigation goal"); - return false; - } - tf3::Quaternion tf_q(q.x, q.y, q.z, q.w); - - // next, we need to check if the length of the quaternion is close to zero - if (tf_q.length2() < 1e-6) - { - robot::log_error("Quaternion has length close to zero... discarding as navigation goal"); - return false; - } - - // next, we'll normalize the quaternion and check that it transforms the vertical vector correctly - tf_q.normalize(); - - tf3::Vector3 up(0, 0, 1); - - double dot = up.dot(up.rotate(tf_q.getAxis(), tf_q.getAngle())); - - if (fabs(dot - 1) > 1e-3) - { - robot::log_error("Quaternion is invalid... for navigation the z-axis of the quaternion must be close to vertical. dot: %f", dot); - return false; - } - - return true; -} - -bool move_base::MoveBase::getRobotPose(robot_geometry_msgs::PoseStamped &global_pose, robot_costmap_2d::Costmap2DROBOT *costmap) -{ - tf3::toMsg(tf3::Transform::getIdentity(), global_pose.pose); - robot_geometry_msgs::PoseStamped robot_pose; - tf3::toMsg(tf3::Transform::getIdentity(), robot_pose.pose); - robot_pose.header.frame_id = robot_base_frame_; - robot_pose.header.stamp = robot::Time(); // latest available - robot::Time current_time = robot::Time::now(); // save time for checking tf delay later - - // get robot pose on the given costmap frame - try - { - tf3::TransformStampedMsg transform = tf_->lookupTransform(costmap->getGlobalFrameID(), robot_base_frame_, tf3::Time()); - tf3::doTransform(robot_pose, global_pose, transform); - } - catch (tf3::LookupException &ex) - { - robot::log_error("Move Base No Transform available Error looking up robot pose: %s", ex.what()); - return false; - } - catch (tf3::ConnectivityException &ex) - { - robot::log_error("Move Base Connectivity Error looking up robot pose: %s", ex.what()); - return false; - } - catch (tf3::ExtrapolationException &ex) - { - robot::log_error("Move Base Extrapolation Error looking up robot pose: %s", ex.what()); - return false; - } - - // check if global_pose time stamp is within costmap transform tolerance - if (!global_pose.header.stamp.isZero() && - current_time.toSec() - global_pose.header.stamp.toSec() > costmap->getTransformTolerance()) - { - robot::log_error("Transform timeout for %s. Current time: %f, pose stamp: %f, tolerance: %f", costmap->getName().c_str(), current_time.toSec(), global_pose.header.stamp.toSec(), costmap->getTransformTolerance()); - return false; - } - - return true; -} - -double move_base::MoveBase::distance(const robot_geometry_msgs::PoseStamped &p1, const robot_geometry_msgs::PoseStamped &p2) -{ - return hypot(p1.pose.position.x - p2.pose.position.x, p1.pose.position.y - p2.pose.position.y); -} - -bool move_base::MoveBase::executeCycle(robot_geometry_msgs::PoseStamped &goal) -{ - boost::recursive_mutex::scoped_lock ecl(configuration_mutex_); - // we need to be able to publish velocity commands - robot_geometry_msgs::Twist cmd_vel; - - // update feedback to correspond to our curent position - robot_geometry_msgs::PoseStamped global_pose; - getRobotPose(global_pose, planner_costmap_robot_); - robot_geometry_msgs::Pose2D pose2d; - pose2d.x = global_pose.pose.position.x; - pose2d.y = global_pose.pose.position.y; - // Extract yaw from quaternion - tf3::Quaternion q(global_pose.pose.orientation.x, global_pose.pose.orientation.y, - global_pose.pose.orientation.z, global_pose.pose.orientation.w); - pose2d.theta = tf3::getYaw(q); - - if (nav_feedback_) - { - nav_feedback_->current_pose = pose2d; - } - const robot_geometry_msgs::PoseStamped ¤t_position = global_pose; - - // // push the feedback out - // robot_move_base_msgs::MoveBaseFeedback feedback; - // feedback.base_position = current_position; - // as_->publishFeedback(feedback); - - // check to see if we've moved far enough to reset our oscillation timeout - if (distance(current_position, oscillation_pose_) >= oscillation_distance_) - { - last_oscillation_reset_ = robot::Time::now(); - oscillation_pose_ = current_position; - - // if our last recovery was caused by oscillation, we want to reset the recovery index - if (recovery_trigger_ == OSCILLATION_R) - recovery_index_ = 0; - } - - // check that the observation buffers for the costmap are current, we don't want to drive blind - if (!controller_costmap_robot_->isCurrent()) - { - robot::log_warning("Sensor data is out of date, we're not going to allow commanding of the base for safety"); - publishZeroVelocity(); - return false; - } - - // if we have a new plan then grab it and give it to the controller - if (new_global_plan_) - { - // make sure to set the new plan flag to false - new_global_plan_ = false; - - robot::log_debug("Got a new plan...swap pointers"); - - // do a pointer swap under mutex - std::vector *temp_plan = controller_plan_; - - boost::unique_lock lock(planner_mutex_); - controller_plan_ = latest_plan_; - latest_plan_ = temp_plan; - lock.unlock(); - robot::log_debug("pointers swapped!"); - - if (!tc_->setPlan(*controller_plan_)) - { - // ABORT and SHUTDOWN COSTMAPS - robot::log_error("Failed to pass global plan to the controller, aborting."); - resetState(); - - // disable the planner thread - lock.lock(); - runPlanner_ = false; - lock.unlock(); - - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::ABORTED; - nav_feedback_->feed_back_str = std::string("Failed to pass global plan to the controller."); - } - // as_->setAborted(robot_move_base_msgs::MoveBaseResult(), "Failed to pass global plan to the controller."); - return true; - } - - // make sure to reset recovery_index_ since we were able to find a valid plan - if (recovery_trigger_ == PLANNING_R) - recovery_index_ = 0; - } - - - // Cancle executeCycle - if (cancel_ctr_ && tc_) - { - robot_geometry_msgs::Vector3 linear; - // ROS_INFO_THROTTLE(1.0,"MoveTo is Canling ...."); - tc_->setTwistLinear(linear); - try - { - double actual_linear_velocity = sqrt(std::pow(tc_->getActualTwist().linear.x, 2) + std::pow(tc_->getActualTwist().linear.y, 2)); - if (actual_linear_velocity <= min_approach_linear_velocity_) - { - robot::log_info("MoveTo is canceled."); - resetState(); - cancel_ctr_ = false; - // if(default_config_.base_global_planner != last_config_.base_global_planner) - robot::NodeHandle nh_planner = robot::NodeHandle(private_nh_, position_planner_name_); - if(nh_planner.hasParam("base_global_planner")) - { - std::string base_global_planner; - nh_planner.getParam("base_global_planner", base_global_planner); - swapPlanner(base_global_planner); - } - else - { - swapPlanner(default_config_.base_global_planner); - } - cancel_ctr_ = false; - // disable the planner thread - boost::unique_lock lock(planner_mutex_); - runPlanner_ = false; - lock.unlock(); - if (nav_feedback_) - { - nav_feedback_->feed_back_str = std::string("Canled."); - nav_feedback_->navigation_state = robot::move_base_core::State::PREEMPTED; - } - // as_->setPreempted(robot_move_base_msgs::MoveBaseResult(), "Canled."); - - if (as_) - { - robot_actionlib_msgs::GoalIDPtr msg = boost::make_shared(); - msg->id = ""; // Empty string cancels current goal - msg->stamp = robot::Time::now(); - // Convert to ConstPtr for processCancel - robot_actionlib_msgs::GoalIDConstPtr cancel_msg = msg; - as_->processCancel(cancel_msg); - robot::log_info("[MoveBase::cancel] Cancel request processed by action server"); - } - else - { - robot::log_warning("[MoveBase::cancel] Action server (as_) is null - cannot send cancel request"); - } - return true; - } - } - catch (const std::exception &e) - { - robot::log_info("MoveTo is canceled."); - resetState(); - // if(default_config_.base_global_planner != last_config_.base_global_planner) - robot::NodeHandle nh_planner = robot::NodeHandle(private_nh_, position_planner_name_); - if(nh_planner.hasParam("base_global_planner")) - { - std::string base_global_planner; - nh_planner.getParam("base_global_planner", base_global_planner); - swapPlanner(base_global_planner); - } - else - { - swapPlanner(default_config_.base_global_planner); - } - - // disable the planner thread - boost::unique_lock lock(planner_mutex_); - runPlanner_ = false; - lock.unlock(); - if (nav_feedback_) - { - nav_feedback_->feed_back_str = std::string("Canled."); - nav_feedback_->navigation_state = robot::move_base_core::State::PREEMPTED; - } - // as_->setPreempted(robot_move_base_msgs::MoveBaseResult(), "Canled."); - if (as_) - { - robot_actionlib_msgs::GoalIDPtr msg = boost::make_shared(); - msg->id = ""; // Empty string cancels current goal - msg->stamp = robot::Time::now(); - // Convert to ConstPtr for processCancel - robot_actionlib_msgs::GoalIDConstPtr cancel_msg = msg; - as_->processCancel(cancel_msg); - robot::log_info("[MoveBase::cancel] Cancel request processed by action server"); - } - else - { - robot::log_warning("[MoveBase::cancel] Action server (as_) is null - cannot send cancel request"); - } - cancel_ctr_ = false; - return true; - } - } - // the move_base state machine, handles the control logic for navigation - switch (state_) - { - // if we are in a planning state, then we'll attempt to make a plan - case move_base::PLANNING: - { - boost::recursive_mutex::scoped_lock lock(planner_mutex_); - runPlanner_ = true; - cancel_ctr_ = false; - planner_cond_.notify_one(); - } - robot::log_debug("Waiting for plan, in the planning state."); - break; - - // if we're controlling, we'll attempt to find valid velocity commands - case move_base::CONTROLLING: - - // check to see if we've reached our goal - try - { - if (tc_->isGoalReached()) - { - robot::log_debug("[MoveBase] Goal reached!"); - resetState(); - // swapPlanner(default_config_.base_global_planner); - // disable the planner thread - boost::unique_lock lock(planner_mutex_); - runPlanner_ = false; - lock.unlock(); - - if (nav_feedback_) - { - nav_feedback_->feed_back_str = std::string("Goal reached."); - nav_feedback_->goal_checked = true; - nav_feedback_->navigation_state = robot::move_base_core::State::SUCCEEDED; - } - publishZeroVelocity(); - // as_->setSucceeded(robot_move_base_msgs::MoveBaseResult(), "Goal reached."); - return true; - } - } - catch (const std::exception &e) - { - // disable the planner thread - resetState(); - boost::unique_lock lock(planner_mutex_); - runPlanner_ = false; - lock.unlock(); - // as_->setAborted(robot_move_base_msgs::MoveBaseResult(), e.what()); - if (nav_feedback_) - { - nav_feedback_->feed_back_str = e.what(); - nav_feedback_->goal_checked = false; - nav_feedback_->navigation_state = robot::move_base_core::State::ABORTED; - robot::log_error("[Move_base] %s", e.what()); - } - return true; - } - - // check for an oscillation condition - if (oscillation_timeout_ > 0.0 && - last_oscillation_reset_ + robot::Duration(oscillation_timeout_) < robot::Time::now()) - { - publishZeroVelocity(); - state_ = move_base::CLEARING; - robot::log_warning("Oscillation detected. Clearing costmap. %f seconds without progress.", (robot::Time::now() - last_oscillation_reset_).toSec()); - if (nav_feedback_) - nav_feedback_->navigation_state = robot::move_base_core::State::CLEARING; - recovery_trigger_ = OSCILLATION_R; - } - - { - boost::unique_lock lock(*(controller_costmap_robot_->getCostmap()->getMutex())); - if (!paused_) - { - if (tc_->computeVelocityCommands(odometry_.twist.twist, cmd_vel)) - { - robot_nav_msgs::Path path; - tc_->getPlan(path.poses); - if (!path.poses.empty()) - { - path.header.stamp = path.poses[0].header.stamp; - path.header.frame_id = path.poses[0].header.frame_id; - } - else - { - path.header.stamp = robot::Time::now(); - path.header.frame_id = controller_costmap_robot_->getGlobalFrameID(); - } - local_data_.plan = robot_nav_2d_utils::pathToPath(path); - - last_valid_control_ = robot::Time::now(); - // make sure that we send the velocity command to the base - - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::CONTROLLING; - nav_feedback_->feed_back_str = std::string(""); - nav_feedback_->goal_checked = false; - } - if (recovery_trigger_ == CONTROLLING_R) - recovery_index_ = 0; - } - else - { - robot::log_warning_at(__FILE__, __LINE__, "The local planner could not find a valid plan."); - robot::Time attempt_end = last_valid_control_ + robot::Duration(controller_patience_); - - // check if we've tried to find a valid control for longer than our time limit - if (robot::Time::now() > attempt_end) - { - // we'll move into our obstacle clearing mode - publishZeroVelocity(); - state_ = move_base::CLEARING; - - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::CLEARING; - nav_feedback_->feed_back_str = std::string("The local planner could not find a valid plan."); - } - recovery_trigger_ = CONTROLLING_R; - } - else - { - // otherwise, if we can't find a valid control, we'll go back to planning - last_valid_plan_ = robot::Time::now(); - planning_retries_ = 0; - state_ = move_base::PLANNING; - if (nav_feedback_) - nav_feedback_->navigation_state = robot::move_base_core::State::PLANNING; - publishZeroVelocity(); - - // enable the planner thread in case it isn't running on a clock - boost::unique_lock lock(planner_mutex_); - if (as_->isPreemptRequested()) - { - if (as_->isNewGoalAvailable()) - { - // if we're active and a new goal is available, we'll accept it, but we won't shut anything down - robot_move_base_msgs::MoveBaseGoal new_goal = *as_->acceptNewGoal(); - if (!isQuaternionValid(new_goal.target_pose.pose.orientation)) - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::ABORTED; - nav_feedback_->feed_back_str = std::string("Aborting on goal because it was sent with an invalid quaternion"); - } - as_->setAborted(robot_move_base_msgs::MoveBaseResult(), "Aborting on goal because it was sent with an invalid quaternion"); - return false; - } - else - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::ACTIVE; - nav_feedback_->feed_back_str = std::string("The new goal is received"); - } - } - goal = goalToGlobalFrame(new_goal.target_pose); - planner_goal_ = goal; - } - } - runPlanner_ = true; - cancel_ctr_ = false; - planner_cond_.notify_one(); - lock.unlock(); - } - } - twist_.velocity = robot_nav_2d_utils::twist3Dto2D(cmd_vel); - twist_.header.stamp = robot::Time::now(); - twist_.header.frame_id = controller_costmap_robot_->getGlobalFrameID(); - } - else - { - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::PAUSED; - nav_feedback_->feed_back_str = std::string("Paused"); - nav_feedback_->goal_checked = false; - } - } - - if (!paused_ && pause_ctr_) - { - // ROS_WARN("pause_ctr_"); - robot_geometry_msgs::Vector3 linear; - tc_->setTwistLinear(linear); - try - { - double actual_linear_velocity = sqrt(std::pow(tc_->getActualTwist().linear.x, 2) + std::pow(tc_->getActualTwist().linear.y, 2)); - if (actual_linear_velocity <= min_approach_linear_velocity_) - { - paused_ = true; - } - } - catch (const std::exception &e) - { - paused_ = true; - } - } - } - break; - - // we'll try to clear out space with any user-provided recovery behaviors - case move_base::CLEARING: - robot::log_debug("[%s:%d] In clearing/recovery state", __FILE__, __LINE__); - // we'll invoke whatever recovery behavior we're currently on if they're enabled - if (recovery_behavior_enabled_ && recovery_index_ < recovery_behaviors_.size()) - { - robot::log_debug("[%s:%d] Executing behavior %u of %zu", __FILE__, __LINE__, recovery_index_ + 1, recovery_behaviors_.size()); - recovery_behaviors_[recovery_index_]->runBehavior(); - - // we at least want to give the robot some time to stop oscillating after executing the behavior - last_oscillation_reset_ = robot::Time::now(); - - // we'll check if the recovery behavior actually worked - robot::log_debug("Going back to planning state"); - last_valid_plan_ = robot::Time::now(); - planning_retries_ = 0; - state_ = move_base::PLANNING; - if (nav_feedback_) - nav_feedback_->navigation_state = robot::move_base_core::State::PLANNING; - - // update the index of the next recovery behavior that we'll try - recovery_index_++; - } - else - { - robot::log_debug("All recovery behaviors have failed, locking the planner and disabling it."); - resetState(); - // swapPlanner(default_config_.base_global_planner); - - // disable the planner thread - boost::unique_lock lock(planner_mutex_); - runPlanner_ = false; - lock.unlock(); - - robot::log_debug("Something should abort after this."); - - if (recovery_trigger_ == CONTROLLING_R) - { - robot::log_error("Aborting because a valid control could not be found. Even after executing all recovery behaviors"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::ABORTED; - nav_feedback_->feed_back_str = std::string("Failed to find a valid control. Even after executing recovery behaviors."); - } - as_->setAborted(robot_move_base_msgs::MoveBaseResult(), "Failed to find a valid control. Even after executing recovery behaviors."); - } - else if (recovery_trigger_ == PLANNING_R) - { - robot::log_error("Aborting because a valid plan could not be found. Even after executing all recovery behaviors"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::ABORTED; - nav_feedback_->feed_back_str = "Failed to find a valid plan. Even after executing recovery behaviors."; - } - as_->setAborted(robot_move_base_msgs::MoveBaseResult(), "Failed to find a valid plan. Even after executing recovery behaviors."); - } - else if (recovery_trigger_ == OSCILLATION_R) - { - robot::log_error("Aborting because the robot appears to be oscillating over and over. Even after executing all recovery behaviors"); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::ABORTED; - nav_feedback_->feed_back_str = std::string("Robot is oscillating. Even after executing recovery behaviors."); - } - as_->setAborted(robot_move_base_msgs::MoveBaseResult(), "Robot is oscillating. Even after executing recovery behaviors."); - } - return true; - } - break; - default: - robot::log_error("This case should never be reached, something is wrong, aborting"); - resetState(); - // disable the planner thread - boost::unique_lock lock(planner_mutex_); - runPlanner_ = false; - lock.unlock(); - if (nav_feedback_) - { - nav_feedback_->navigation_state = robot::move_base_core::State::ABORTED; - nav_feedback_->feed_back_str = std::string("Reached a case that should not be hit in move_base. This is a bug, please report it."); - } - as_->setAborted(robot_move_base_msgs::MoveBaseResult(), "Reached a case that should not be hit in move_base. This is a bug, please report it."); - return true; - } - - // we aren't done yet - return false; -} - -robot_geometry_msgs::PoseStamped move_base::MoveBase::goalToGlobalFrame(const robot_geometry_msgs::PoseStamped &goal_pose_msg) -{ - - if (!tf_) - { - return goal_pose_msg; - } - - std::string global_frame = planner_costmap_robot_->getGlobalFrameID(); - robot_geometry_msgs::PoseStamped global_pose; - tf3::toMsg(tf3::Transform::getIdentity(), global_pose.pose); - robot_geometry_msgs::PoseStamped goal_pose; - tf3::toMsg(tf3::Transform::getIdentity(), goal_pose.pose); - goal_pose = goal_pose_msg; - robot::Time current_time = robot::Time::now(); // save time for checking tf delay later - tf3::Time tf3_current_time = data_convert::convertTime(current_time); - tf3::Time tf3_zero_time = data_convert::convertTime(robot::Time()); - - try - { - // use current time if possible (makes sure it's not in the future) - std::string error_msg; - if (tf_->canTransform(global_frame, goal_pose.header.frame_id, tf3_current_time, &error_msg)) - { - // Transform is available at current time - tf3::TransformStampedMsg transform = tf_->lookupTransform(global_frame, goal_pose.header.frame_id, tf3_current_time); - tf3::doTransform(goal_pose, global_pose, transform); - } - // use the latest otherwise (tf3::Time() means latest available) - else - { - // Try to get latest transform - tf3::TransformStampedMsg transform = tf_->lookupTransform(global_frame, goal_pose.header.frame_id, tf3_zero_time); - tf3::doTransform(goal_pose, global_pose, transform); - } - } - catch (tf3::LookupException &ex) - { - robot::log_error("Move Base No Transform available Error looking up robot pose: %s", ex.what()); - return goal_pose_msg; - } - catch (tf3::ConnectivityException &ex) - { - robot::log_error("Move Base Connectivity Error looking up robot pose: %s", ex.what()); - return goal_pose_msg; - } - catch (tf3::ExtrapolationException &ex) - { - robot::log_error("Move Base Extrapolation Error looking up robot pose: %s", ex.what()); - return goal_pose_msg; - } - return global_pose; -} - -robot_nav_2d_msgs::Twist2DStamped move_base::MoveBase::getTwist() -{ - return twist_; -} - -robot::move_base_core::NavFeedback *move_base::MoveBase::getFeedback() -{ - if (!nav_feedback_) - { - return nullptr; - } - return nav_feedback_.get(); -} - -robot::move_base_core::PlannerDataOutput move_base::MoveBase::getGlobalData() -{ - if (tc_) - { - robot_nav_msgs::Path path; - tc_->getGlobalPlan(path.poses); - robot_nav_msgs::Path global_path; - global_path.header.stamp = robot::Time::now(); - global_path.header.frame_id = planner_costmap_robot_->getGlobalFrameID(); - for(auto &p : path.poses) - { - robot_geometry_msgs::PoseStamped pose = goalToGlobalFrame(p); - pose.header.stamp = robot::Time::now(); - global_path.poses.push_back(goalToGlobalFrame(pose)); - } - global_data_.plan = robot_nav_2d_utils::pathToPath(global_path); - } - ConvertData convert_data(planner_costmap_robot_, planner_costmap_robot_->getGlobalFrameID(), true); - convert_data.updateCostmap(global_data_.costmap, global_data_.costmap_update, global_data_.is_costmap_updated); - convert_data.updateFootprint(global_data_.footprint); - return global_data_; -} - -robot::move_base_core::PlannerDataOutput move_base::MoveBase::getLocalData() -{ - ConvertData convert_data(controller_costmap_robot_, controller_costmap_robot_->getGlobalFrameID(), true); - convert_data.updateCostmap(local_data_.costmap, local_data_.costmap_update, local_data_.is_costmap_updated); - convert_data.updateFootprint(local_data_.footprint); - return local_data_; -} - -robot::move_base_core::BaseNavigation::Ptr move_base::MoveBase::create() -{ - return std::make_shared(); -} - -BOOST_DLL_ALIAS(move_base::MoveBase::create, MoveBase) diff --git a/src/Navigations/Packages/move_base/src/move_base_main.cpp b/src/Navigations/Packages/move_base/src/move_base_main.cpp deleted file mode 100644 index e276312..0000000 --- a/src/Navigations/Packages/move_base/src/move_base_main.cpp +++ /dev/null @@ -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 -#include -#include -#include -#include -#include -#include - -int main(int argc, char** argv) -{ - try { - std::shared_ptr tf = std::make_shared(); - - // 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( - 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; -} \ No newline at end of file diff --git a/src/Navigations/Packages/move_base/src/simple_action_server.cpp b/src/Navigations/Packages/move_base/src/simple_action_server.cpp deleted file mode 100644 index e5f47b6..0000000 --- a/src/Navigations/Packages/move_base/src/simple_action_server.cpp +++ /dev/null @@ -1,632 +0,0 @@ -#include - -namespace move_base -{ - -// Constructor -template -SimpleActionServer::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 -SimpleActionServer::~SimpleActionServer() -{ - stop(); -} - -// Start the action server -template -void SimpleActionServer::start() -{ - boost::lock_guard 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 -void SimpleActionServer::stop() -{ - { - boost::lock_guard 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 -void SimpleActionServer::setGoalCallback(GoalCallback callback) -{ - boost::lock_guard lock(state_mutex_); - goal_callback_ = callback; -} - -// Set callback for cancel messages -template -void SimpleActionServer::setCancelCallback(CancelCallback callback) -{ - boost::lock_guard lock(state_mutex_); - cancel_callback_ = callback; -} - -// Set callback for feedback publishing -template -void SimpleActionServer::setFeedbackCallback(FeedbackCallback callback) -{ - boost::lock_guard lock(state_mutex_); - feedback_callback_ = callback; -} - -// Set callback for result publishing -template -void SimpleActionServer::setResultCallback(ResultCallback callback) -{ - boost::lock_guard lock(state_mutex_); - result_callback_ = callback; -} - -// Set callback for status publishing -template -void SimpleActionServer::setStatusCallback(StatusCallback callback) -{ - boost::lock_guard lock(state_mutex_); - status_callback_ = callback; -} - -// Set status publish rate -template -void SimpleActionServer::setStatusPublishRate(double rate) -{ - boost::lock_guard lock(state_mutex_); - status_publish_rate_ = rate; -} - -// Process an incoming goal message -template -void SimpleActionServer::processGoal(const ActionGoalConstPtr& goal_msg) -{ - boost::lock_guard 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_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 -void SimpleActionServer::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 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 -bool SimpleActionServer::isNewGoalAvailable() -{ - boost::lock_guard lock(state_mutex_); - return new_goal_available_; -} - -// Check if preemption has been requested -template -bool SimpleActionServer::isPreemptRequested() -{ - boost::lock_guard lock(state_mutex_); - return preempt_requested_; -} - -// Accept a new goal -template -typename SimpleActionServer::GoalConstPtr SimpleActionServer::acceptNewGoal() -{ - robot::log_info("[SimpleActionServer::acceptNewGoal] ===== ENTRY ====="); - boost::lock_guard 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 -void SimpleActionServer::setSucceeded(const Result& result, const std::string& text) -{ - boost::lock_guard 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(); - 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 -void SimpleActionServer::setAborted(const Result& result, const std::string& text) -{ - boost::lock_guard 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(); - 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 -void SimpleActionServer::setPreempted(const Result& result, const std::string& text) -{ - boost::lock_guard 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(); - 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 -void SimpleActionServer::publishFeedback(const Feedback& feedback) -{ - boost::lock_guard lock(state_mutex_); - - if (current_status_.status == robot_actionlib_msgs::GoalStatus::ACTIVE) - { - ActionFeedbackPtr action_feedback = boost::make_shared(); - 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 -typename SimpleActionServer::GoalConstPtr SimpleActionServer::getCurrentGoal() -{ - boost::lock_guard lock(state_mutex_); - return goal_; -} - -// Get the current status -template -robot_actionlib_msgs::GoalStatus SimpleActionServer::getCurrentStatus() -{ - boost::lock_guard lock(state_mutex_); - return current_status_; -} - -// Check if the server is active -template -bool SimpleActionServer::isActive() -{ - boost::lock_guard lock(state_mutex_); - return active_; -} - -// Get the action name -template -std::string SimpleActionServer::getName() const -{ - return name_; -} - -// Execute the goal in a separate thread -template -void SimpleActionServer::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 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 -void SimpleActionServer::statusPublishThread() -{ - double rate = status_publish_rate_; - robot::Duration sleep_duration(1.0 / rate); - - while (active_) - { - { - boost::lock_guard lock(state_mutex_); - - // Create status array - robot_actionlib_msgs::GoalStatusArrayPtr status_array = - boost::make_shared(); - 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; -