feat(nav): emergency stop latch xuyên BaseNavigation + C API

Copy nội dung sau fix từ T800_ws pnkx_nav_core (branch
dev_recovery_and_manager_mission, commit f4a5c96) — rb_ws khớp byte-for-byte
bản trước fix nên copy thẳng.

CẤP THIẾT: move_base2 submodule (đã bump lên 8d9932c) đã có
NavigationServer::emergency()/clearEmergency() override — thiếu commit này
thì BaseNavigation ở rb_ws không khai virtual tương ứng, override không
khớp base, rb_ws build gãy ngay.

BaseNavigation thêm 2 virtual MỚI Ở CUỐI vtable: emergency(),
clearEmergency() — không đổi chữ ký method cũ (ABI: rebuild đồng bộ
libmove_base.so + C API + mọi host). State EMERGENCY = 14 append cuối enum,
giá trị cũ không đổi (đã verify cả bên C mirror nav_c_api.h).

emergency(): lệnh 0 ngay, huỷ chặng đang chạy (báo CANCELLED đúng 1 lần),
xoá hàng đợi mission, chốt state. Hiệu lực TRƯỚC KHI hàm trả về trên chính
thread gọi (getTwist/getFeedback đổi ngay cả khi control thread đang block
trong plugin); dọn dẹp thật (planner, recovery, action, mission layer)
chạy ở chu kỳ kế tiếp. Trong lúc chốt: moveTo/executeInstantActions bị từ
chối, pause/resume/cancel bị bỏ qua. clearEmergency() đưa về PENDING,
không tự chạy lại — host phải gửi goal mới.

C API: navigation_emergency() / navigation_clear_emergency() trong
nav_c_api_2.h.

Đã verify: virtual signature emergency()/clearEmergency() khớp override
trong move_base2/src/navigation_server.cpp; EMERGENCY=14 append cuối enum
cả hai bên C/C++, không đụng giá trị enum cũ.
This commit is contained in:
2026-09-15 15:21:41 +07:00
parent 1485e7c19c
commit 2921fede24
7 changed files with 240 additions and 6 deletions

View File

@@ -486,6 +486,45 @@ host sẽ lệch nhịp với lõi. Trước 2026-09-11 lõi báo `PREEMPTED` sa
planner; host tin, gửi goal kế, goal kế bị coi là hỏng và `ABORTED` sau ~3 s. Trần chờ là khoá
`settle_timeout` của `move_base2` (mặc định 2 s); quá trần lõi vẫn báo `PREEMPTED` và in lỗi.
#### Dừng khẩn — `navigation_emergency` / `navigation_clear_emergency` (2026-09-14)
| | Hàm | |
|---|---|---|
| **MỚI** | `void navigation_emergency(NavigationHandle)` | chốt dừng khẩn |
| **MỚI** | `void navigation_clear_emergency(NavigationHandle)` | gỡ chốt |
Khác hẳn `cancel` ở hai điểm, và cả hai đều là lý do nó tồn tại:
1. **Có hiệu lực trước khi hàm trả về, trên chính thread gọi.** `navigation_get_twist()` trả 0 và
`navigation_get_state()` trả `EMERGENCY` ngay lần đọc kế — không chờ control thread. Ba lệnh
lifecycle kia đều chờ drain ở cycle kế, tức chờ control thread rảnh; control thread đang kẹt
trong một lượt `makePlan` (detour SBPL tới ~1.2 s) thì `cancel` cũng trễ theo. Dừng khẩn không
được phép trễ theo.
2. **Là chốt, không phải kết quả.** Sau `cancel`, lõi về `PREEMPTED` rồi nhận goal kế. Sau
`emergency`, lõi ở `EMERGENCY` và **từ chối** mọi `navigation_move_to*` /
`navigation_execute_instant_actions` (trả `false`, `navigation_get_status_text` nêu lý do), bỏ
qua `pause/resume/cancel`, cho tới khi host gọi `navigation_clear_emergency()`. Sau clear: state
`PENDING`, hàng đợi trống, **robot không tự chạy lại** — host phải gửi goal mới.
Việc lõi làm ở cycle kế: cắt lượt planner đang chạy, bảo recovery/action dừng, báo outcome chặng
đang chạy (một lần, cancelled) lên mission layer, xoá hàng đợi mission (mission layer cũng vào
`EMERGENCY` và gạt mọi order tới khi clear). Tick action vẫn chạy trong lúc chốt để handler thiết
bị về vị trí an toàn — không cấp vận tốc.
Stamp của `navigation_get_twist()` trong lúc chốt: tươi trong ~0.5 s sau lời gọi (host publish
được lệnh 0 tường minh), rồi đóng băng như sau mọi yêu cầu kết thúc — lõi không giữ `/cmd_vel`
vĩnh viễn, teleop lái được robot ra khỏi tình huống. E-stop phần cứng là tầng khác.
```cpp
navigation_emergency(h); // twist = 0, state = EMERGENCY ngay sau dòng này
// ... người vận hành xử lý tình huống ...
navigation_clear_emergency(h); // state → PENDING trong ≤ 1 cycle
navigation_move_to(h, goal); // phải gửi lại; không gì tự chạy
```
Idempotent cả hai chiều. `clear` rồi `emergency` trong cùng cửa sổ một cycle: lệnh gọi **sau**
thắng (hai cờ đối nghịch đặt dưới một lock, như pause/resume).
### 6.5b. Trạng thái từng thành phần và `LOST` (2026-09-11)
| | Hàm | Đổi |
@@ -1158,6 +1197,35 @@ là hai thread cùng ghi vào một chỗ — đúng nhóm lỗi đã từng gâ
**Nguyên tắc.** Cấp phát trong `.so` thì trả bằng hàm của `.so`. Đừng gọi `free()` của libc từ C#:
vừa không đi hết các tầng lồng nhau, vừa không đảm bảo cùng một C runtime.
### 11.14 – 11.15. `navigation_emergency` / `navigation_clear_emergency` — dừng khẩn có chốt (2026-09-14)
```c
void navigation_emergency(NavigationHandle handle);
void navigation_clear_emergency(NavigationHandle handle);
```
Mô tả đầy đủ ở **mục 6.5, "Dừng khẩn"**. Tóm tắt cho người viết binding:
| | `navigation_emergency` | `navigation_clear_emergency` |
|---|---|---|
| Có hiệu lực | **trước khi trả về**, trên thread gọi: `get_twist` = 0, `get_state` = `EMERGENCY` | `get_state` → `PENDING` trong ≤ 1 cycle |
| Lõi làm ở cycle kế | cắt planner, dừng recovery/action, báo outcome chặng (một lần), xoá hàng đợi mission | về `IDLE`, hàng đợi trống, **không tự chạy lại** |
| Trong lúc chốt | `move_to*` / `execute_instant_actions` trả `false`; `pause`/`resume`/`cancel` bị bỏ qua | — |
| Thread | bất kỳ | bất kỳ |
| Gọi lặp | idempotent | idempotent; no-op khi chưa chốt |
| Ném | không bao giờ qua biên C (log lỗi) | như trên |
```csharp
Nav.navigation_emergency(h);
Debug.Assert(Nav.navigation_get_state(h, out var s) && s == NavigationState.EMERGENCY);
// ... xử lý ...
Nav.navigation_clear_emergency(h);
// gửi lại goal — lõi không nhớ goal cũ
```
**Bẫy.** Đừng ánh xạ `EMERGENCY` sang cùng nhánh với `PREEMPTED`/`FAILED` rồi tự động gửi goal kế:
goal đó bị từ chối, và log lõi in cảnh báo mỗi giây chừng nào host còn thử.
---
## Phụ lục A — bảng symbol đầy đủ trong `libnav_c_api.so`
@@ -1165,7 +1233,7 @@ 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`.
**Tổng: 62 symbol** = 45 cũ + 4 trợ giúp + 13 mới. Lấy bằng
**Tổng: 64 symbol** = 45 cũ + 4 trợ giúp + 15 mới (13 của 2026-09 + 2 dừng khẩn 2026-09-14). 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ì**
@@ -1224,7 +1292,7 @@ time_create ← std_msgs/Time.cpp
`frame_id`, nên giải phóng bằng `nav_c_api_free_string`. Truyền `frame_id = NULL` là hợp lệ (trả về
`frame_id` NULL).
### 13 symbol mới — `nav_c_api_2.cpp`
### 15 symbol mới — `nav_c_api_2.cpp`
```
navigation_initialize_checked navigation_add_depth_camera_data
@@ -1234,6 +1302,7 @@ 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_emergency navigation_clear_emergency (2026-09-14, mục 6.5)
```
`navigation_dock_to_order_v2` từng nằm trong danh sách này nhưng **đã bị xoá cùng nhóm docking**;
@@ -1321,9 +1390,13 @@ public enum NavigationState
CONTROLLING = 11,
CLEARING = 12,
PAUSED = 13,
EMERGENCY = 14, // 2026-09-14 — chốt dừng khẩn, thêm cuối, giá trị cũ không đổi
}
```
**Thiếu `EMERGENCY` thì build mới vẫn trả về 14** — C# nhận một giá trị ngoài enum, `switch` rơi
vào `default` và host tưởng "trạng thái lạ". Thêm member trước khi triển khai build này.
Nguồn: `nav_c_api.h`, khớp `robot::move_base_core::State` trong `move_base_core/navigation.h`. Ánh xạ
sang `actionStatus` của VDA5050 ở mục 13.3.
@@ -1353,7 +1426,7 @@ Bốn quy tắc dịch, đúng cho mọi struct trong bảng:
4. Mảng cố định (`double K[9]`, `R[9]`, `P[12]`, `covariance[36]`) →
`[MarshalAs(UnmanagedType.ByValArray, SizeConst = N)]`.
### B.2. Mười ba `DllImport` mới
### B.2. Mười lăm `DllImport` mới
```csharp
private const string Lib = "nav_c_api";
@@ -1369,6 +1442,13 @@ public static extern bool navigation_is_ready(IntPtr handle);
[DllImport(Lib, CallingConvention = Cdecl)]
public static extern void navigation_shutdown(IntPtr handle);
// ---- dừng khẩn (2026-09-14) — an toàn từ thread bất kỳ, có hiệu lực trước khi trả về ----------
[DllImport(Lib, CallingConvention = Cdecl)]
public static extern void navigation_emergency(IntPtr handle);
[DllImport(Lib, CallingConvention = Cdecl)]
public static extern void navigation_clear_emergency(IntPtr handle);
// ---- trạng thái -------------------------------------------------------------------------
[DllImport(Lib, CallingConvention = Cdecl)] [return: MarshalAs(UnmanagedType.I1)]
public static extern bool navigation_get_state(IntPtr handle, out NavigationState state);
@@ -1831,6 +1911,7 @@ Không có báo cáo theo từng action. Nguồn duy nhất là trạng thái ch
| `ABORTED`, `REJECTED`, `LOST` | `FAILED` | false |
| `PREEMPTED`, `PREEMPTING` | `FAILED` | false |
| `PAUSED` | giữ nguyên trạng thái trước, `paused = true` | false |
| `EMERGENCY` | `FAILED` cho action đang chạy; `safetyState.eStop` theo nguồn dừng khẩn của host (`MANUAL`/`REMOTE`); mọi order tới bị từ chối tới khi clear | false |
Hai điều phải nhớ:
@@ -1970,6 +2051,7 @@ Chạy theo đúng thứ tự. Mỗi bước là điều kiện của bước sa
- [ ] `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
- [ ] `navigation_emergency` → `get_twist` = 0 và `get_state` = `EMERGENCY` **ngay lần đọc kế, không chờ cycle**; `move_to` trả `false`; `clear_emergency` → `PENDING`, robot không tự chạy
- [ ] `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

View File

@@ -48,7 +48,11 @@ extern "C"
PLANNING = 10,
CONTROLLING = 11,
CLEARING = 12,
PAUSED = 13
PAUSED = 13,
/* Emergency stop latched (2026-09-14): zero command, running leg cancelled, mission queue
* wiped; every goal is rejected until navigation_clear_emergency(). Appended last so the
* values above keep their numbers. See nav_c_api_2.h. */
EMERGENCY = 14
} NavigationState;
typedef struct

View File

@@ -21,6 +21,8 @@
* - navigation_add_depth_camera_data() — the depth-camera input path, never exposed before.
* - navigation_move_to_order_v2() — an order carrying a real orderId / orderUpdateId.
* - navigation_execute_instant_actions() — a VDA5050 instantActions message, expanded like node actions.
* - navigation_emergency() — emergency stop, latched until cleared (2026-09-14).
* - navigation_clear_emergency() — release the latch; the host must send a new goal.
*
* Include this header **in addition to** nav_c_api.h. It adds symbols; it replaces none.
*
@@ -82,6 +84,17 @@
* 11. navigation_destroy() alone is no longer enough — call navigation_shutdown() first, from a
* point in your own shutdown sequence where the process is still fully alive.
*
* 12. NavigationState gained EMERGENCY (= 14, appended; no older value moved) — 2026-09-14. It
* is a latch, not a result: after navigation_emergency() the core reports EMERGENCY, rejects
* every goal and ignores pause/resume/cancel until navigation_clear_emergency(), after which
* it reports PENDING with nothing queued. Do not treat EMERGENCY like PREEMPTED ("done, send
* the next goal"): the next goal is refused. A C# enum that does not know value 14 will
* receive it anyway — add the member before deploying this build.
*
* ABI: `BaseNavigation` gained two virtual methods (at the end of its vtable). Rebuild the
* plugin (`libmove_base.so`), this library and every host together — an old plugin loaded by a
* new host crashes on the first navigation_emergency() call.
*
* See NAV_C_API_2_GUIDE.md in this directory for the per-function walkthrough and the startup and
* shutdown sequences.
*/
@@ -159,6 +172,34 @@ extern "C"
*/
void navigation_shutdown(NavigationHandle handle);
/**
* @brief Emergency stop (added 2026-09-14).
*
* From this call onward the core commands zero, cancels the running leg (its outcome reaches the
* mission layer once, as cancelled), wipes the mission queue and latches the EMERGENCY state. While
* latched every navigation_move_to* / navigation_execute_instant_actions call returns false,
* and navigation_pause() / _resume() / _cancel() are ignored.
*
* Unlike the other lifecycle calls this one is visible **before it returns**:
* navigation_get_twist() reads zero and navigation_get_state() reads EMERGENCY immediately, from
* the calling thread, even if the control thread is currently blocked inside a plugin. The
* clean-up (planner, recovery, action, mission layer) happens on the control thread's next
* cycle. Safe from any thread; idempotent.
*
* The twist stamp stays fresh for ~0.5 s after the call so the host publishes an explicit zero,
* then freezes like after any finished request — the core does not hold /cmd_vel forever, a
* teleop source may drive the robot out of the situation. The hardware e-stop is another layer.
*/
void navigation_emergency(NavigationHandle handle);
/**
* @brief Release the emergency latch (added 2026-09-14).
*
* The core returns to PENDING with nothing queued. Nothing resumes by itself: the host must
* submit a new goal. Idempotent; a no-op when not latched.
*/
void navigation_clear_emergency(NavigationHandle handle);
// ============================================================================================
// Status
// ============================================================================================

View File

@@ -158,6 +158,50 @@ extern "C" void navigation_shutdown(NavigationHandle handle)
}
}
extern "C" void navigation_emergency(NavigationHandle handle)
{
if (!handle)
{
return;
}
try
{
as_navigation(handle)->emergency();
}
catch (const std::exception &e)
{
// Never throw across the C boundary — and never let an exception here read as "the stop
// was not taken": the core latches before anything that could throw. Log loudly.
robot::log_error("navigation_emergency failed: %s", e.what());
}
catch (...)
{
robot::log_error("navigation_emergency failed: unknown exception");
}
}
extern "C" void navigation_clear_emergency(NavigationHandle handle)
{
if (!handle)
{
return;
}
try
{
as_navigation(handle)->clearEmergency();
}
catch (const std::exception &e)
{
robot::log_error("navigation_clear_emergency failed: %s", e.what());
}
catch (...)
{
robot::log_error("navigation_clear_emergency failed: unknown exception");
}
}
// ================================================================================================
// Status
// ================================================================================================

View File

@@ -286,6 +286,24 @@ TEST(ConvertorOrder, NullArraysAreIgnoredEvenWithNonZeroCounts)
EXPECT_TRUE(cpp.edges.empty());
}
// ================================================================================================
// NavigationState mirror — the C enum must stay value-for-value equal to move_base_core::State
// ================================================================================================
TEST(NavigationStateMirror, EmergencyIsAppendedAsFourteenOnBothSides)
{
// Appended last on purpose (2026-09-14): no older value may move, or a C# host built against the
// previous header silently misreads every state above the insertion point.
EXPECT_EQ(static_cast<int>(EMERGENCY), 14);
EXPECT_EQ(static_cast<int>(robot::move_base_core::State::EMERGENCY), 14);
EXPECT_EQ(static_cast<int>(PAUSED), static_cast<int>(robot::move_base_core::State::PAUSED));
char *name = navigation_state_to_string(EMERGENCY);
ASSERT_NE(name, nullptr);
EXPECT_STREQ(name, "EMERGENCY");
nav_c_api_free_string(name);
}
// ================================================================================================
// Depth camera conversion (move_base2 path)
// ================================================================================================