feat(nav): emergency stop latch xuyen BaseNavigation + C API

BaseNavigation them 2 virtual moi o CUOI vtable: emergency() va
clearEmergency(), khong doi so cua method cu (ABI: rebuild dong bo
libmove_base.so + C API + moi host). State them EMERGENCY = 14, append
cuoi enum nen gia tri cu khong doi (ca ben C mirror nav_c_api.h).

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

C API: navigation_emergency() / navigation_clear_emergency() trong
nav_c_api_2.h, cap nhat guide va test_convertor cho enum EMERGENCY moi.
This commit is contained in:
2026-09-15 15:07:25 +07:00
parent 374a09c821
commit f4a5c96c3c
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)
// ================================================================================================

View File

@@ -42,6 +42,11 @@ Thư viện này được thiết kế để:
- `pause()` - tạm dừng di chuyển
- `resume()` - tiếp tục di chuyển
- `cancel()` - hủy mục tiêu hiện tại
- `emergency()` - dừng khẩn: lệnh 0 ngay, huỷ chặng đang chạy, xoá hàng đợi mission, chốt
state `EMERGENCY`; mọi `moveTo`/`executeInstantActions` bị từ chối, `pause/resume/cancel` bị
bỏ qua cho tới khi `clearEmergency()`. Có hiệu lực ngay trên thread host cho `getTwist()` /
`getFeedback()`, không chờ control thread
- `clearEmergency()` - gỡ chốt dừng khẩn, về `PENDING`; không tự chạy lại, host phải gửi goal mới
- `setTwistLinear()`, `setTwistAngular()` - điều khiển vận tốc
- **Lấy thông tin**:
- `getRobotPose()` - lấy vị trí hiện tại của robot
@@ -83,6 +88,8 @@ Enum `State` mô tả các trạng thái khác nhau trong quá trình navigation
- **CONTROLLING**: Đang điều khiển robot di chuyển theo plan
- **CLEARING**: Đang dọn dẹp costmap, thực hiện recovery behaviors
- **PAUSED**: Tạm dừng navigation
- **EMERGENCY**: Dừng khẩn đang chốt (2026-09-14). Giá trị 14, thêm cuối enum để các giá trị cũ và
bản C trong `nav_c_api.h` không đổi số. Chỉ `clearEmergency()` mới ra khỏi state này
- **SUCCEEDED**: Hoàn thành thành công
- **ABORTED**: Bị lỗi, không thể hoàn thành
- **PREEMPTED**: Bị hủy bởi mục tiêu mới

View File

@@ -50,7 +50,14 @@ namespace robot
PLANNING,
CONTROLLING,
CLEARING,
PAUSED
PAUSED,
/**
* Emergency stop latched (2026-09-14). The core commands zero, has cancelled the running
* leg and wiped the mission queue, and rejects every new goal until clearEmergency().
* Appended last so the numeric values of the states above — and of the C mirror in
* nav_c_api.h — do not move.
*/
EMERGENCY
};
/**
@@ -117,6 +124,8 @@ namespace robot
return "CLEARING"; // Đang dọn dẹp bản đồ / costmap
case State::PAUSED:
return "PAUSED"; // Tạm dừng
case State::EMERGENCY:
return "EMERGENCY"; // Dừng khẩn, chốt tới khi clearEmergency()
default:
return "UNKNOWN_STATE"; // Không xác định
}
@@ -474,7 +483,8 @@ namespace robot
*
* 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.
* @ref cancel, @ref pause and @ref resume for those. The same goes for an emergency
* stop: it is @ref emergency / @ref clearEmergency, never an action.
*
* @param actions The actions of one `instantActions` message, in the order received.
* Must not be empty; every action needs `actionType` and `actionId`.
@@ -552,6 +562,34 @@ namespace robot
*/
virtual PlannerDataOutput getLocalData() = 0;
/**
* @brief Emergency stop.
*
* From this call onward the core commands zero, the running leg is cancelled (its outcome
* is reported as CANCELLED exactly once), the mission queue is wiped and the core latches
* State::EMERGENCY. While latched every @ref moveTo / @ref executeInstantActions is
* rejected and @ref pause / @ref resume / @ref cancel are ignored.
*
* Unlike the three lifecycle calls above this one takes effect on the **host thread** for
* what the host reads back — @ref getTwist returns zero and @ref getFeedback reports
* EMERGENCY before the call returns, even if the control thread is currently blocked.
* The control thread does the clean-up (planner, recovery, action, mission layer) on its
* next cycle. Idempotent.
*
* @note Added 2026-09-14 at the END of the vtable so the slots of every older method keep
* their index. Still an ABI change: rebuild the plugin (`libmove_base.so`), the C API
* and every host together — an old plugin under a new host crashes on this call.
*/
virtual void emergency() = 0;
/**
* @brief Release the emergency latch.
*
* The core returns to PENDING with nothing queued: nothing resumes by itself, the host
* must submit a new goal to move again. Idempotent; no-op when not latched.
*/
virtual void clearEmergency() = 0;
protected:
// Shared feedback data for navigation status tracking
std::shared_ptr<NavFeedback> nav_feedback_;