feat(rotate): áp relative_yaw trong resolveDeferredGoal, đổi binding rotate

- NavigationRequest: thêm relative_yaw [rad], NaN = không dùng, đi kèm
  được với goal_frame/relative_distance thay vì loại trừ.

- resolveDeferredGoal(): thêm nhánh has_yaw. Trước đây relative_distance
  = 0 khiến goal CHÉP NGUYÊN pose hiện tại kể cả orientation — chặng
  rotate coi như đã tới đích ngay khi nhận, không quay độ nào. Giờ tính
  yaw nền (từ pose hiện tại, hoặc từ frame nếu goal_frame có) rồi cộng
  relative_yaw, dựng lại quaternion đủ 4 thành phần. Log "Goal received"
  thêm yaw= để chặng quay không còn trông giống hệt chặng vị trí.

- mission_adapter_bridge.cpp: chở relative_yaw qua nguyên vẹn.

- Thêm 3 dòng debug (nhóm debug_plan, mặc định bật) trong
  runController(): kết quả isGoalReached() khi true (candidate=0, chưa
  từng tính lệnh), v/omega trước arbiter, v/omega sau arbiter — phân
  biệt "chưa từng có lệnh" / "lệnh bị cắt" / "lỗi ngoài move_base2".
  Bật khối log đã có sẵn nhưng bị comment từ trước.

- Binding rotate: PNKXRotateLocalPlanner -> HybridRotateLocalPlanner.

- 13 test mới (deferred_goal_test.cpp + 2 ca bridge): quay giữ nguyên
  x/y chỉ đổi yaw, góc là delta theo hướng hiện tại, dấu âm quay ngược,
  quaternion chuẩn hoá, go_straight không bị đụng hướng, distance+yaw
  đi cùng nhau, frame+yaw lấy nền là hướng robot chứ không phải hướng
  frame đích, mất pose bị từ chối, NaN passthrough.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-11 10:46:58 +07:00
parent 180c0e1cd4
commit 7d00c5ab66
10 changed files with 606 additions and 30 deletions

View File

@@ -466,6 +466,7 @@ if(BUILD_MOVE_BASE2_TESTS AND BUILDING_WITH_CATKIN)
controller_runner_test
mission_adapter_bridge_test
mission_layer_test
deferred_goal_test
move_base2_scenario_test # tên có tiền tố gói: nav_test_harness đã có target scenario_test
)

View File

@@ -22,9 +22,12 @@
# move_to_param: <key> chặng nav, frame lấy từ actionParameters[<key>] của action gốc
# move: <mét> chặng nav tương đối; dương = tiến, âm = lùi
#
# Tuỳ chọn cho step navigation: profile (position | docking | go_straight | rotate), marker.
# Tuỳ chọn cho step navigation: profile (position | docking | go_straight | rotate), marker,
# turn_param.
# `marker` chỉ hợp lệ với `profile: docking`: nó chọn override trong
# maker_sources.yaml/docking_marker_profiles. Không khai = dùng cặp docking mặc định.
# `turn_param: <key>` chỉ hợp lệ với `profile: rotate`: góc quay [deg] lấy từ actionParameters[<key>]
# của chính order. Gắn nhầm profile thì node TRƯỢT LÚC BOOT, không phải bị bỏ qua lúc chạy.
# Tolerance thuộc YAML riêng của local planner đang được profile chọn, không khai ở đây.
#
# ── Ba quy tắc khi sửa ───────────────────────────────────────────────────────────────────────────
@@ -101,7 +104,21 @@ vda5050_src:
rotate:
steps:
# ► Chỉnh: `move: 0.0` = không tịnh tiến; góc quay lấy từ actionParameters của order.
# Profile `rotate` dùng PNKXRotateLocalPlanner, tham số ở YAML của plugin đó.
- {move: 0.0, profile: rotate}
# `move: 0.0` = không tịnh tiến. Góc quay KHÔNG khai ở đây: `turn_param: angle_deg` nói rằng
# góc lấy từ actionParameters['angle_deg'] của chính order, tính bằng ĐỘ, dương = ngược
# chiều kim đồng hồ. Nhờ vậy đổi góc quay không phải sửa file này.
#
# ► Chỉnh: đổi `angle_deg` nếu fleet gửi khoá tên khác. Order thiếu khoá đó, hoặc gửi giá trị
# không phải số, hoặc vượt [-180, 180] độ -> adapter BỎ CẢ MESSAGE, robot không nhúc nhích.
#
# ⚠ Biên 180 độ không phải để cho đẹp: đích của chặng là một pose, mà pose chỉ nói hướng
# cuối chứ không nói quay bao nhiêu hay chiều nào. Xin 270 độ ngược kim đồng hồ thì robot
# sẽ quay 90 độ THUẬN kim đồng hồ — nên adapter từ chối thẳng thay vì quay ngược ý người gửi.
#
# ⚠ Chặng quay hiện KHÔNG kiểm va chạm: footprint quét qua vùng xung quanh mà không ai chặn.
# Chỉ dùng ở nơi biết là trống quanh robot.
#
# Profile `rotate` dùng HybridRotateLocalPlanner, tham số ở khối cùng tên trong
# hybrid_local_planner_params.yaml.
- {move: 0.0, profile: rotate, turn_param: angle_deg}

View File

@@ -538,3 +538,64 @@ HybridDockingLocalPlanner:
# chiều đi của path), sai lệch hướng so với tiếp tuyến path, cự ly còn lại
# tới cuối chặng, và ngưỡng chuyển chặng. Đây là dòng để trả lời "robot có
# bám path không" và "chuyển chặng có đúng ở cusp không".
# =================================================================================================
# HybridRotateLocalPlanner — quay tại chỗ, KHÔNG tịnh tiến.
#
# Ai đọc khối này: profile `rotate` của move_base2 (chặng sinh từ compound action `rotate`, khai
# trong compound_actions_params.yaml). Chặng đó có goal trùng vị trí robot và chỉ khác hướng.
#
# Planner này KHÔNG đọc các pose giữa của global plan: chặng quay có start trùng goal nên global
# planner không có gì để nội suy, hướng các pose giữa sinh ra từ jitter localization. Nó chỉ dùng
# pose hiện tại và pose đích. Vì vậy ở đây không có khoá nào về lookahead hay bám path.
#
# Vận tốc thẳng luôn bằng 0 trên mọi nhánh — không có khoá nào chỉnh được điều đó.
# =================================================================================================
HybridRotateLocalPlanner:
library_path: libhybrid_local_planner
# ===== Giới hạn vận tốc góc =====
# ► Chỉnh: [rad/s] trần tốc độ quay. Phải <= max_vel_theta của move_base2 (move_base_common_params.yaml),
# vì VelocityArbiter cắt phần vượt — mà lệnh bị cắt thì phá luôn đoạn giảm tốc tính ở đây.
# TĂNG = quay nhanh hơn, rung lắc và trượt bánh nhiều hơn; GIẢM = chậm và êm.
max_angular_velocity: 0.5
# ► Chỉnh: [rad/s] sàn tốc độ khi CHƯA vào tolerance, để thắng ma sát tĩnh.
# Quá THẤP: bánh kêu mà robot không nhúc nhích, chặng không bao giờ xong.
# Quá CAO: bước một chu kỳ rộng hơn dải tolerance, robot vọt qua rồi quay lại liên tục.
# Ràng buộc an toàn: min_angular_velocity * control_period phải NHỎ HƠN yaw_goal_tolerance;
# sai điều kiện này thì planner in lỗi lúc boot.
min_angular_velocity: 0.05
# ► Chỉnh: [rad/s^2] trần gia tốc góc mỗi chu kỳ, tính từ giá trị lớn hơn giữa tốc độ đo được
# và lệnh chu kỳ trước. GIẢM = khởi động mềm, lâu đạt tốc; TĂNG = giật khi bắt đầu quay.
angular_acceleration: 0.8
# ► Chỉnh: [rad/s^2] gia tốc hãm dùng để dựng đoạn giảm tốc (omega = sqrt(2 * decel * góc_còn_lại)).
# GIẢM = phanh sớm và tới đích chậm rãi, ít vọt qua; TĂNG = giữ tốc lâu rồi phanh gấp,
# dễ vọt qua tolerance nếu base không theo kịp.
angular_deceleration: 0.6
# ===== Điều kiện kết thúc chặng =====
# ► Chỉnh: [rad] sai số hướng chấp nhận là "đã tới". 0.02 rad ~ 1.15 độ.
# GIẢM = đích chính xác hơn nhưng dễ hunt quanh goal nếu base không quay được chậm như vậy.
yaw_goal_tolerance: 0.02
# ► Chỉnh: [rad/s] dưới ngưỡng này coi như thân robot đã dừng hẳn. Chặng chỉ báo xong khi
# VỪA vào tolerance VỪA dừng — báo xong lúc còn trôi theo quán tính là giao cho chặng sau
# một hướng vẫn đang đổi. TĂNG = kết thúc sớm hơn nhưng kém chính xác.
rot_stopped_velocity: 0.03
# ► Chỉnh: [s] chu kỳ điều khiển giả định khi không đo được thời gian giữa hai lần gọi (chu kỳ
# đầu, hoặc đồng hồ nhảy lùi lúc replay bag). Nên khớp controller_frequency của move_base2
# (20 Hz -> 0.05 s).
control_period: 0.05
# ===== Debug =====
# Hai nhóm log, mặc định BẬT. Log LỖI không nằm sau cờ nào — tắt được một dòng lỗi nghĩa là
# tồn tại cấu hình khiến robot hỏng trong im lặng.
debug_state: true # đổi trạng thái: nhận goal mới, tới đích, từ chối chặng
debug_command: true # lệnh đang phát: sai số góc, omega, tốc độ đo được, dt
debug_command_throttle_cycles: 20 # in tối đa 1 dòng debug_command mỗi ngần này chu kỳ
# (20 Hz -> 20 chu kỳ = 1 dòng/giây). Đặt 1 = in mọi chu kỳ,
# rất nặng I/O, chỉ dùng khi bắt lỗi ngắn.

View File

@@ -41,8 +41,10 @@ go_straight:
local_planner: HybridDockingLocalPlanner # instance Stanley riêng, block cùng tên (path 2 điểm thẳng)
rotate:
global_planner: TwoPointsPlanner
local_planner: HybridDockingLocalPlanner # instance Stanley riêng: XY đã trong tolerance -> Phase B xoay về yaw goal
global_planner: TwoPointsPlanner # chặng quay có start trùng goal: plan chỉ để hợp lệ, planner
# dưới không đọc các pose giữa
local_planner: HybridRotateLocalPlanner # quay tại chỗ, v = 0 tuyệt đối; tham số ở khối cùng tên
# trong hybrid_local_planner_params.yaml
# Đường lùi chung cho mọi profile: planner chính trả false hoặc plan rỗng thì move_base2 đổi sang
# planner này đúng MỘT lần cho request hiện tại. Backup cũng fail thì mới chạy recovery; request mới

View File

@@ -96,6 +96,20 @@ struct NavigationRequest
*/
double relative_distance = std::numeric_limits<double>::quiet_NaN();
/**
* Góc quay tương đối [rad] so với hướng hiện tại của robot; dương = ngược chiều kim đồng hồ
* (REP-103). NaN = không dùng, và khi đó orientation của @ref goal không bị đụng tới.
*
* Cũng được quy ra @ref goal tuyệt đối tại `submit`. Khác @ref relative_distance và
* @ref goal_frame — vốn loại trừ nhau — trường này ĐI KÈM được với cả hai: chặng quay tại chỗ
* chính là `relative_distance = 0` cộng một góc khác 0.
*
* Giới hạn của cách biểu diễn: @ref goal là một pose, mà pose chỉ nói hướng cuối chứ không nói
* quay bao nhiêu hay quay chiều nào. Mission layer vì thế chỉ nhận góc trong [-pi, pi]; quay
* nhiều vòng hay ép chiều quay cần một contract khác.
*/
double relative_yaw = std::numeric_limits<double>::quiet_NaN();
/**
* Số hiệu chặng do mission layer cấp. 0 = goal trực tiếp, không thuộc mission nào.
*

View File

@@ -93,6 +93,8 @@ NavigationRequest MissionAdapterBridge::toRequest(const mission_adapters::Missio
// Đích đến muộn đi qua nguyên vẹn; `ControlLoop::submit` mới là chỗ quy về pose tuyệt đối.
request.goal_frame = mission.goal_frame;
request.relative_distance = mission.relative_distance;
// [rad] Mission layer đã quy từ độ sang radian tại biên đọc payload; ở đây chỉ chở qua.
request.relative_yaw = mission.relative_yaw;
// Chặng của order PHẢI mang theo phần order của nó. Global planner cấu hình cho profile position
// là `CustomPlanner`, mà lớp này chỉ hiện thực nhánh `makePlan(Order, start, goal, plan)`; nhánh

View File

@@ -25,6 +25,13 @@ namespace
/// [-] Sai lệch chuẩn quaternion còn chấp nhận được trước khi coi goal là hỏng.
constexpr double kQuaternionNormTolerance = 1e-2;
/// @brief Yaw [rad] của một pose. Robot chạy trên mặt phẳng nên chỉ z-w của quaternion có nghĩa.
double yawOf(const robot_geometry_msgs::PoseStamped& pose)
{
const auto& q = pose.pose.orientation;
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
}
/// [s] Giãn cách log cho guard "không đi mù". Tình trạng này kéo dài hàng giây, và đây là vòng lặp
/// điều khiển — log mỗi cycle sẽ nhấn chìm mọi dòng khác.
constexpr double kStaleCostmapLogThrottle = 5.0;
@@ -370,8 +377,11 @@ bool ControlLoop::resolveDeferredGoal(NavigationRequest& request, std::string& r
{
const bool has_frame = !request.goal_frame.empty();
const bool has_distance = std::isfinite(request.relative_distance);
// Góc quay ĐI KÈM được với hai nguồn đích kia, không loại trừ: chặng quay tại chỗ là
// relative_distance = 0 cộng một góc khác 0.
const bool has_yaw = std::isfinite(request.relative_yaw);
if (!has_frame && !has_distance)
if (!has_frame && !has_distance && !has_yaw)
{
return true; // Goal tuyệt đối, không có gì phải quy.
}
@@ -389,6 +399,19 @@ bool ControlLoop::resolveDeferredGoal(NavigationRequest& request, std::string& r
return false;
}
// Pose hiện tại: cần cho quãng tương đối, và cần cho góc tương đối kể cả khi vị trí đích tới từ
// một TF frame — góc luôn tính so với hướng robot đang quay về LÚC chặng được nhận.
robot_geometry_msgs::PoseStamped robot_pose;
const bool needs_robot_pose = has_distance || has_yaw;
if (needs_robot_pose && !deps_.pose->getRobotPose(robot_pose))
{
// Mất định vị thì không quy được quãng đường tương đối. Đoán ở đây là robot đi mù một đoạn.
reason = "a relative goal needs the robot pose, which is not available";
return false;
}
const double robot_yaw = needs_robot_pose ? yawOf(robot_pose) : 0.0;
if (has_frame)
{
if (!deps_.pose->lookupPose(request.goal_frame, request.goal))
@@ -396,23 +419,34 @@ bool ControlLoop::resolveDeferredGoal(NavigationRequest& request, std::string& r
reason = "cannot resolve goal_frame '" + request.goal_frame + "'";
return false;
}
return true;
}
robot_geometry_msgs::PoseStamped robot_pose;
if (!deps_.pose->getRobotPose(robot_pose))
else if (has_distance)
{
// Mất định vị thì không quy được quãng đường tương đối. Đoán ở đây là robot đi mù một đoạn.
reason = "relative_distance needs the robot pose, which is not available";
return false;
request.goal = robot_pose;
request.goal.pose.position.x += request.relative_distance * std::cos(robot_yaw);
request.goal.pose.position.y += request.relative_distance * std::sin(robot_yaw);
}
else
{
// Chỉ có góc: đích là chính chỗ robot đang đứng, chỉ khác hướng.
request.goal = robot_pose;
}
if (has_yaw)
{
// Hướng đích = hướng HIỆN TẠI cộng góc yêu cầu. Ghi đè orientation của goal chứ không cộng dồn
// vào orientation vừa lấy ở trên: với has_frame, orientation của frame đích là hướng của trạm
// chứ không phải hướng robot, và chặng quay nói về robot.
//
// Không normalize góc tổng: mission layer đã chặn ở [-pi, pi], và quaternion tự bọc.
const double goal_yaw = robot_yaw + request.relative_yaw;
const double half = 0.5 * goal_yaw;
request.goal.pose.orientation.x = 0.0;
request.goal.pose.orientation.y = 0.0;
request.goal.pose.orientation.z = std::sin(half);
request.goal.pose.orientation.w = std::cos(half);
}
const auto& q = robot_pose.pose.orientation;
const double yaw = std::atan2(2.0 * (q.w * q.z + q.x * q.y),
1.0 - 2.0 * (q.y * q.y + q.z * q.z)); // [rad]
request.goal = robot_pose;
request.goal.pose.position.x += request.relative_distance * std::cos(yaw);
request.goal.pose.position.y += request.relative_distance * std::sin(yaw);
return true;
}
@@ -811,6 +845,16 @@ void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
if (deps_.controller->isGoalReached())
{
controller_feedback_ = ControllerFeedback::kGoalReached;
if (config_.debug_plan)
{
// Nhánh này trả candidate RỖNG — không có lệnh nào được tính ở cycle này. Một planner báo
// "đã tới" ngay từ cycle đầu (trước khi computeVelocityCommands từng chạy lần nào) là triệu
// chứng ĐÚNG của "robot đứng im, không phát lệnh": không phải lệnh bị chặn, mà chưa bao giờ
// có lệnh nào được tính.
robot::log_info_throttle(kDebugControlLogThrottle,
"[move_base2][debug] runController: isGoalReached() = true -- "
"không tính lệnh cycle này (candidate = 0).\n");
}
return;
}
@@ -819,6 +863,16 @@ void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
{
controller_feedback_ = ControllerFeedback::kCommandValid;
candidate = cmd;
if (config_.debug_plan)
{
// v/omega TRƯỚC VelocityArbiter — phân biệt "planner không phát lệnh" (giá trị ở đây đã là
// 0 hoặc gần 0) với "lệnh phát ra nhưng bị guard/arbiter cắt về 0 phía sau" (giá trị ở đây
// khác 0 nhưng /cmd_vel lại là 0 — xem log EnvMonitor / VelocityArbiter cho cycle này).
robot::log_info_throttle(kDebugControlLogThrottle,
"[move_base2][debug] runController: command_valid v=%.3f m/s "
"omega=%.4f rad/s (trước arbiter).\n",
cmd.linear.x, cmd.angular.z);
}
return;
}
@@ -958,10 +1012,12 @@ bool ControlLoop::step()
// Log một lần tại sườn nhận goal — không nằm trên đường lặp của control loop.
if (active_request_.has_goal)
{
robot::log_info("[move_base2] Goal received (mission %llu): x=%.3f y=%.3f frame=%s.\n",
// yaw có mặt ở đây vì một chặng quay tại chỗ KHÁC chặng thường đúng ở con số này: x, y giữ
// nguyên và chỉ hướng đổi. Thiếu nó thì một chặng quay hỏng trông y hệt một chặng quay đúng.
robot::log_info("[move_base2] Goal received (mission %llu): x=%.3f y=%.3f yaw=%.4f frame=%s.\n",
static_cast<unsigned long long>(active_request_.mission_sequence_id),
active_request_.goal.pose.position.x, active_request_.goal.pose.position.y,
active_request_.goal.header.frame_id.c_str());
yawOf(active_request_.goal), active_request_.goal.header.frame_id.c_str());
}
else
{
@@ -1022,13 +1078,16 @@ bool ControlLoop::step()
if (config_.debug_plan)
{
// yaw của pose CUỐI: đây là thứ setGoalPose() thực sự trao cho local planner. Chặng quay
// tại chỗ có first/last CÙNG vị trí — không có yaw ở đây thì log không phân biệt được
// "goal đúng nhưng chưa quay tới" với "goal sai ngay từ khi lập plan".
robot::log_info("[move_base2][debug] controller accepted plan with %zu pose(s); "
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, frame=%s).\n",
"first=(%.3f, %.3f, frame=%s), last=(%.3f, %.3f, yaw=%.4f, frame=%s).\n",
latest_plan_.size(), latest_plan_.front().pose.position.x,
latest_plan_.front().pose.position.y,
latest_plan_.front().header.frame_id.c_str(),
latest_plan_.back().pose.position.x, latest_plan_.back().pose.position.y,
latest_plan_.back().header.frame_id.c_str());
yawOf(latest_plan_.back()), latest_plan_.back().header.frame_id.c_str());
}
}
}
@@ -1270,12 +1329,6 @@ bool ControlLoop::step()
output.recovery_route_cursor, output.recovery_route_size);
}
}
// else if (controller_feedback_ == ControllerFeedback::kCommandValid)
// {
// robot::log_info_throttle(kDebugControlLogThrottle,
// "[move_base2][debug] controller command valid: v=%.3f wz=%.3f.\n",
// candidate.linear.x, candidate.angular.z);
// }
}
// Replan nền (contract 2026-08-04): đang bám plan và tới nhịp `planner_frequency` thì khởi động
@@ -1324,6 +1377,21 @@ bool ControlLoop::step()
arbiter_.arbitrate((costmap_stale || env_brake_) ? VelocitySource::kNone : output.velocity_source,
candidate, dt);
if (config_.debug_plan && output.run_controller)
{
// Sau arbiter — thứ AmrPublisher thật sự lấy để phát /cmd_vel. Đối chiếu với dòng
// "runController: command_valid v=... omega=... (trước arbiter)" ở trên: hai dòng khác
// nhau nghĩa là VelocityArbiter (kẹp trần/gia tốc) hoặc EnvMonitor brake đã sửa lệnh; hai
// dòng giống hệt mà /cmd_vel vẫn đo được 0 thì lỗi nằm ngoài move_base2 (AmrPublisher, driver
// bánh xe, hoặc sim).
const robot_geometry_msgs::Twist& published = arbiter_.lastCommand();
robot::log_info_throttle(kDebugControlLogThrottle,
"[move_base2][debug] runController: sau arbiter v=%.3f m/s "
"omega=%.4f rad/s (nguồn=%s, source_in=%s).\n",
published.linear.x, published.angular.z,
toString(controller_feedback_), toString(output.velocity_source));
}
// --- 5. Báo kết quả -------------------------------------------------------------------------
if (output.report_outcome)
{

336
test/deferred_goal_test.cpp Normal file
View File

@@ -0,0 +1,336 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* move_base2 — quy đích đến muộn về pose tuyệt đối (ControlLoop::resolveDeferredGoal).
*
* Mission layer sinh chặng lúc robot còn chưa tới chỗ xuất phát, nên đích của chặng có thể tới dưới
* ba dạng chưa-phải-pose: một TF frame, một quãng đường tương đối, một góc quay tương đối. Cả ba
* được quy về pose tuyệt đối đúng một lần, tại `submit`, và test này khoá phép quy đó.
*
* Vì sao đáng test riêng: một chặng quay tại chỗ từng chạy suốt mà robot không quay độ nào, vì
* nhánh quãng-tương-đối chép NGUYÊN pose hiện tại (gồm cả orientation) rồi cộng 0 mét — goal trùng
* khít chỗ đang đứng nên goal checker báo đã tới ngay lập tức.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
#include <string>
#include <move_base2/control_loop.h>
#include "fake_ports.h"
using move_base2::ControlLoop;
using move_base2::ControlLoopConfig;
using move_base2::ControlLoopDeps;
using move_base2::MotionProfile;
using move_base2::NavigationRequest;
using move_base2::testing::FakeActionPort;
using move_base2::testing::FakeClockPort;
using move_base2::testing::FakeControllerPort;
using move_base2::testing::FakeCostmapStatusPort;
using move_base2::testing::FakeEnvironmentPort;
using move_base2::testing::FakeMissionPort;
using move_base2::testing::FakePlannerPort;
using move_base2::testing::FakePosePort;
using move_base2::testing::FakeRecoveryPort;
namespace
{
constexpr double kNaN = std::numeric_limits<double>::quiet_NaN();
ControlLoopConfig baseConfig()
{
ControlLoopConfig config;
config.state_machine.planner_patience = 0.5; // [s]
config.state_machine.controller_patience = 0.5; // [s]
config.state_machine.oscillation_timeout = 0.0; // tắt
config.state_machine.recovery_enabled = false;
config.velocity.max_vel_x = 0.5; // [m/s]
config.velocity.min_vel_x = -0.2; // [m/s]
config.velocity.max_vel_theta = 1.0; // [rad/s]
config.velocity.max_accel_x = 100.0; // [m/s^2]
config.velocity.max_accel_theta = 100.0; // [rad/s^2]
config.nominal_control_period = 0.05; // [s]
config.position.global_planner_name = "FakeGlobalPlanner";
config.position.local_planner_name = "FakeLocalPlanner";
config.docking = config.position;
config.go_straight = config.position;
config.rotate = config.position;
config.rotate.local_planner_name = "FakeRotatePlanner";
return config;
}
/// @brief Yaw [rad] của một pose, để đọc lại kết quả đã quy.
double yawOf(const robot_geometry_msgs::PoseStamped& pose)
{
const auto& q = pose.pose.orientation;
return std::atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z));
}
/**
* @class Fixture
* @brief Control loop nối cổng giả, đủ để `submit` chạy tới lượt lập plan đầu tiên.
*/
class Fixture
{
public:
Fixture() : recovery_(0)
{
pose_.setPosition(2.0, 3.0); // [m]
pose_.setYaw(0.0); // [rad]
deps_.clock = &clock_;
deps_.pose = &pose_;
deps_.planner = &planner_;
deps_.controller = &controller_;
deps_.recovery = &recovery_;
deps_.mission = &mission_;
deps_.action = &action_;
deps_.costmap_status = &costmap_status_;
deps_.environment = &environment_;
std::string error;
EXPECT_TRUE(loop_.configure(baseConfig(), deps_, error)) << error;
}
/// @brief Chặng quay tại chỗ: 0 m tịnh tiến cộng một góc.
static NavigationRequest rotationRequest(double relative_yaw)
{
NavigationRequest request;
request.profile = MotionProfile::kRotate;
request.goal.header.frame_id = "map";
request.goal.pose.orientation.w = 1.0;
request.relative_distance = 0.0; // [m]
request.relative_yaw = relative_yaw;
return request;
}
/// @brief Chặng đi thẳng, không góc — dạng đã chạy từ trước khi có relative_yaw.
static NavigationRequest straightRequest(double relative_distance)
{
NavigationRequest request;
request.profile = MotionProfile::kGoStraight;
request.goal.header.frame_id = "map";
request.goal.pose.orientation.w = 1.0;
request.relative_distance = relative_distance;
return request;
}
bool submit(const NavigationRequest& request, std::string& reason)
{
return loop_.submit(request, reason);
}
/// @brief Đích đã quy, đọc từ cổng planner sau khi lượt lập plan đầu tiên được phát đi.
const robot_geometry_msgs::PoseStamped& resolvedGoal()
{
loop_.step();
return planner_.pendingGoal();
}
FakePosePort& pose()
{
return pose_;
}
private:
ControlLoop loop_;
ControlLoopDeps deps_;
FakeClockPort clock_;
FakePosePort pose_;
FakePlannerPort planner_;
FakeControllerPort controller_;
FakeRecoveryPort recovery_;
FakeMissionPort mission_;
FakeActionPort action_;
FakeCostmapStatusPort costmap_status_;
FakeEnvironmentPort environment_;
};
} // namespace
TEST(DeferredGoal, RotationKeepsThePositionAndTurnsTheHeading)
{
Fixture fixture;
fixture.pose().setYaw(0.0);
std::string reason;
ASSERT_TRUE(fixture.submit(Fixture::rotationRequest(M_PI_2), reason)) << reason;
const auto& goal = fixture.resolvedGoal();
EXPECT_NEAR(goal.pose.position.x, 2.0, 1e-9) << "[m] chặng quay không được dịch chuyển robot";
EXPECT_NEAR(goal.pose.position.y, 3.0, 1e-9);
EXPECT_NEAR(yawOf(goal), M_PI_2, 1e-9);
}
TEST(DeferredGoal, RotationIsRelativeToTheHeadingTheRobotHasNow)
{
Fixture fixture;
fixture.pose().setYaw(1.0); // [rad]
std::string reason;
ASSERT_TRUE(fixture.submit(Fixture::rotationRequest(0.5), reason)) << reason;
// Góc là DELTA, không phải hướng tuyệt đối: cùng một yêu cầu gửi ở hai hướng khác nhau phải cho
// hai đích khác nhau.
EXPECT_NEAR(yawOf(fixture.resolvedGoal()), 1.5, 1e-9);
}
TEST(DeferredGoal, ANegativeAngleTurnsTheOtherWay)
{
Fixture fixture;
fixture.pose().setYaw(0.0);
std::string reason;
ASSERT_TRUE(fixture.submit(Fixture::rotationRequest(-M_PI_4), reason)) << reason;
EXPECT_NEAR(yawOf(fixture.resolvedGoal()), -M_PI_4, 1e-9);
}
TEST(DeferredGoal, TheResolvedQuaternionIsNormalised)
{
Fixture fixture;
fixture.pose().setYaw(0.3);
std::string reason;
// submit() chạy isQuaternionValid() ngay sau khi quy; một quaternion dựng thiếu thành phần sẽ bị
// từ chối ở đó chứ không đi tiếp.
ASSERT_TRUE(fixture.submit(Fixture::rotationRequest(2.0), reason)) << reason;
const auto& q = fixture.resolvedGoal().pose.orientation;
EXPECT_NEAR(std::sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w), 1.0, 1e-9);
EXPECT_DOUBLE_EQ(q.x, 0.0) << "robot đi trên mặt phẳng: chỉ z-w được mang giá trị";
EXPECT_DOUBLE_EQ(q.y, 0.0);
}
TEST(DeferredGoal, AStraightLegWithoutAnAngleKeepsTheCurrentHeading)
{
Fixture fixture;
fixture.pose().setYaw(0.7); // [rad]
std::string reason;
ASSERT_TRUE(fixture.submit(Fixture::straightRequest(1.0), reason)) << reason;
// relative_yaw = NaN phải để orientation nguyên vẹn. Một giá trị 0 ở đây thay vì NaN sẽ ép mọi
// chặng go_straight phải kết thúc ở hướng 0 rad.
const auto& goal = fixture.resolvedGoal();
EXPECT_NEAR(yawOf(goal), 0.7, 1e-9);
EXPECT_NEAR(goal.pose.position.x, 2.0 + std::cos(0.7), 1e-9) << "[m] tiến theo trục thân robot";
EXPECT_NEAR(goal.pose.position.y, 3.0 + std::sin(0.7), 1e-9);
}
TEST(DeferredGoal, DistanceAndAngleCanBeAskedForTogether)
{
Fixture fixture;
fixture.pose().setYaw(0.0);
NavigationRequest request = Fixture::straightRequest(2.0);
request.relative_yaw = M_PI_2;
std::string reason;
ASSERT_TRUE(fixture.submit(request, reason)) << reason;
// Quãng đường tính theo hướng LÚC NHẬN chặng, không theo hướng sau khi quay.
const auto& goal = fixture.resolvedGoal();
EXPECT_NEAR(goal.pose.position.x, 4.0, 1e-9);
EXPECT_NEAR(goal.pose.position.y, 3.0, 1e-9);
EXPECT_NEAR(yawOf(goal), M_PI_2, 1e-9);
}
TEST(DeferredGoal, AnAbsoluteGoalIsLeftAlone)
{
Fixture fixture;
fixture.pose().setYaw(0.0);
NavigationRequest request;
request.profile = MotionProfile::kPosition;
request.goal.header.frame_id = "map";
request.goal.pose.position.x = 9.0; // [m]
request.goal.pose.position.y = 8.0; // [m]
request.goal.pose.orientation.z = std::sin(0.5 * 1.2);
request.goal.pose.orientation.w = std::cos(0.5 * 1.2);
std::string reason;
ASSERT_TRUE(fixture.submit(request, reason)) << reason;
const auto& goal = fixture.resolvedGoal();
EXPECT_NEAR(goal.pose.position.x, 9.0, 1e-9);
EXPECT_NEAR(goal.pose.position.y, 8.0, 1e-9);
EXPECT_NEAR(yawOf(goal), 1.2, 1e-9);
}
TEST(DeferredGoal, AnAngleAppliesOnTopOfAGoalTakenFromAFrame)
{
Fixture fixture;
fixture.pose().setYaw(0.2); // [rad] hướng robot
fixture.pose().setFramePose("dock_target", 5.0, 6.0, 1.0); // [m], [rad] hướng của trạm
NavigationRequest request;
request.profile = MotionProfile::kRotate;
request.goal_frame = "dock_target";
request.relative_yaw = 0.1; // [rad]
std::string reason;
ASSERT_TRUE(fixture.submit(request, reason)) << reason;
const auto& goal = fixture.resolvedGoal();
EXPECT_NEAR(goal.pose.position.x, 5.0, 1e-9) << "[m] vị trí vẫn tới từ frame";
EXPECT_NEAR(goal.pose.position.y, 6.0, 1e-9);
// Góc quay nói về ROBOT, nên nền của nó là hướng robot (0.2), không phải hướng của trạm (1.0).
EXPECT_NEAR(yawOf(goal), 0.3, 1e-9);
}
TEST(DeferredGoal, ARotationWithoutARobotPoseIsRefused)
{
Fixture fixture;
fixture.pose().setAvailable(false); // mất định vị
std::string reason;
EXPECT_FALSE(fixture.submit(Fixture::rotationRequest(M_PI_2), reason))
<< "không có pose thì không có nền để cộng góc; đoán ở đây là quay mù";
EXPECT_FALSE(reason.empty());
}
TEST(DeferredGoal, AFrameAndADistanceTogetherAreStillRefused)
{
Fixture fixture;
fixture.pose().setFramePose("dock_target", 5.0, 6.0, 0.0);
NavigationRequest request;
request.profile = MotionProfile::kPosition;
request.goal_frame = "dock_target";
request.relative_distance = 1.0; // [m]
std::string reason;
EXPECT_FALSE(fixture.submit(request, reason))
<< "hai nguồn VỊ TRÍ cùng lúc vẫn không có thứ tự nào hiển nhiên đúng; chỉ góc mới đi kèm được";
}
TEST(DeferredGoal, ANonFiniteAngleIsTreatedAsNoAngle)
{
Fixture fixture;
fixture.pose().setYaw(0.4);
NavigationRequest request = Fixture::straightRequest(0.0);
request.relative_yaw = kNaN;
std::string reason;
ASSERT_TRUE(fixture.submit(request, reason)) << reason;
EXPECT_NEAR(yawOf(fixture.resolvedGoal()), 0.4, 1e-9);
}
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -132,12 +132,49 @@ public:
pose_.pose.orientation.w = 1.0;
}
/// @param yaw [rad] hướng robot; cần cho mọi chặng quy từ pose tương đối.
void setYaw(double yaw)
{
pose_.header.frame_id = "map";
pose_.pose.orientation.x = 0.0;
pose_.pose.orientation.y = 0.0;
pose_.pose.orientation.z = std::sin(0.5 * yaw);
pose_.pose.orientation.w = std::cos(0.5 * yaw);
}
/// @brief false = mô phỏng TF thiếu/stale.
void setAvailable(bool available)
{
available_ = available;
}
/**
* @brief Đăng một frame mà @ref lookupPose tra được.
* @param x,y [m] ; @param yaw [rad] hướng của CHÍNH frame đó, không phải của robot.
*/
void setFramePose(const std::string& frame, double x, double y, double yaw)
{
robot_geometry_msgs::PoseStamped pose;
pose.header.frame_id = "map";
pose.pose.position.x = x;
pose.pose.position.y = y;
pose.pose.orientation.z = std::sin(0.5 * yaw);
pose.pose.orientation.w = std::cos(0.5 * yaw);
frames_[frame] = pose;
}
bool lookupPose(const std::string& frame,
robot_geometry_msgs::PoseStamped& pose) const override
{
const auto it = frames_.find(frame);
if (it == frames_.end())
{
return false;
}
pose = it->second;
return true;
}
std::size_t callCount() const
{
return call_count_;
@@ -145,6 +182,7 @@ public:
private:
robot_geometry_msgs::PoseStamped pose_;
std::map<std::string, robot_geometry_msgs::PoseStamped> frames_;
bool available_ = true;
mutable std::size_t call_count_ = 0;
};
@@ -191,6 +229,12 @@ public:
return in_flight_;
}
/// @brief Goal mà lõi đã trao cho lượt lập plan gần nhất — đích SAU khi đã quy từ dạng tương đối.
const robot_geometry_msgs::PoseStamped& pendingGoal() const
{
return pending_goal_;
}
bool pollPlan(PlanResult& result) override
{
if (!in_flight_)

View File

@@ -12,6 +12,7 @@
*********************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include <memory>
#include <string>
#include <vector>
@@ -26,6 +27,7 @@ namespace
using mission_adapters::Mission;
using mission_adapters::MissionManager;
using move_base2::MissionAdapterBridge;
using move_base2::MotionProfile;
using move_base2::NavigationOutcome;
using move_base2::NavigationRequest;
@@ -161,6 +163,35 @@ TEST(MissionAdapterBridgeConversion, ActionOnlyLegCarriesNoOrder)
EXPECT_EQ(request.order, nullptr);
}
TEST(MissionAdapterBridgeConversion, CarriesTheRelativeGoalAsItIs)
{
mission_adapters::Mission mission;
mission.id = 7;
mission.motion_hint = "rotate";
mission.relative_distance = 0.0; // [m]
mission.relative_yaw = M_PI / 2.0; // [rad], mission layer đã quy từ độ
const NavigationRequest request = MissionAdapterBridge::toRequest(mission);
EXPECT_EQ(request.profile, MotionProfile::kRotate);
EXPECT_DOUBLE_EQ(request.relative_distance, 0.0);
EXPECT_DOUBLE_EQ(request.relative_yaw, M_PI / 2.0)
<< "bridge chỉ chở qua; mọi phép quy đơn vị đã xong ở mission layer";
}
TEST(MissionAdapterBridgeConversion, AnUnsetRelativeYawStaysUnset)
{
mission_adapters::Mission mission;
mission.id = 8;
mission.motion_hint = "go_straight";
mission.relative_distance = -1.0; // [m]
const NavigationRequest request = MissionAdapterBridge::toRequest(mission);
EXPECT_TRUE(std::isnan(request.relative_yaw))
<< "NaN = không dùng; đổi thành 0 sẽ ép chặng go_straight phải giữ nguyên hướng";
}
TEST(MissionAdapterBridgeConversion, LeavesToleranceAtProfileDefault)
{
// Quy ước của NavigationRequest: sai số <= 0 nghĩa "dùng default của profile trong config".