first commit

This commit is contained in:
2026-07-29 15:45:16 +07:00
commit 4762a3032c
56 changed files with 15310 additions and 0 deletions

569
src/control_loop.cpp Normal file
View File

@@ -0,0 +1,569 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* move_base2 — cài đặt control loop.
*
* Author: DuongTD
*********************************************************************/
#include <move_base2/control_loop.h>
#include <cmath>
#include <sstream>
namespace move_base2
{
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;
} // namespace
// ================================================================================================
// ControlLoopConfig
// ================================================================================================
bool ControlLoopConfig::validate(std::string& error) const
{
if (!state_machine.validate(error))
{
return false;
}
if (!velocity.validate(error))
{
return false;
}
if (!(nominal_control_period > 0.0))
{
error = "nominal_control_period phải > 0 [s]";
return false;
}
if (position.local_planner_name.empty())
{
error = "profile 'position' bắt buộc phải có local_planner_name";
return false;
}
if (robot_base_frame.empty())
{
// Frame rỗng đi thẳng vào header của lệnh vận tốc gửi host. Chặn ở đây thay vì để host nhận một
// lệnh không biết thuộc hệ toạ độ nào.
error = "robot_base_frame không được rỗng";
return false;
}
return true;
}
std::string ControlLoopConfig::describe() const
{
std::ostringstream out;
out << state_machine.describe();
out << velocity.describe();
out << "ControlLoop:\n";
out << " nominal_control_period: " << nominal_control_period << " s\n";
out << " robot_base_frame : " << robot_base_frame << '\n';
out << " profile position : " << position.global_planner_name << " / "
<< position.local_planner_name << '\n';
out << " profile docking : " << docking.global_planner_name << " / "
<< docking.local_planner_name << '\n';
out << " profile go_straight: " << go_straight.global_planner_name << " / "
<< go_straight.local_planner_name << '\n';
out << " profile rotate : " << rotate.global_planner_name << " / "
<< rotate.local_planner_name << '\n';
return out.str();
}
// ================================================================================================
// ControlLoop
// ================================================================================================
bool ControlLoop::configure(const ControlLoopConfig& config, const ControlLoopDeps& deps,
std::string& error)
{
initialized_ = false;
if (deps.clock == nullptr || deps.pose == nullptr || deps.planner == nullptr ||
deps.controller == nullptr || deps.recovery == nullptr)
{
error = "thiếu cổng bắt buộc (clock/pose/planner/controller/recovery)";
return false;
}
if (!config.validate(error))
{
return false;
}
if (!state_machine_.configure(config.state_machine, error))
{
return false;
}
if (!arbiter_.configure(config.velocity, error))
{
return false;
}
config_ = config;
deps_ = deps;
initialized_ = true;
reset();
return true;
}
void ControlLoop::reset()
{
state_machine_.reset();
arbiter_.reset();
has_pending_request_ = false;
has_active_request_ = false;
pause_requested_ = false;
resume_requested_ = false;
cancel_requested_ = false;
planner_feedback_ = PlannerFeedback::kIdle;
controller_feedback_ = ControllerFeedback::kIdle;
recovery_feedback_ = RecoveryFeedback::kIdle;
action_feedback_ = ActionFeedback::kIdle;
latest_plan_.clear();
planner_running_ = false;
// Nhãn mới + huỷ: lượt đang bay thuộc về vòng đời trước, kết quả của nó không được nhận nhầm.
++plan_tag_;
if (deps_.planner != nullptr)
{
deps_.planner->cancelPlan();
}
has_last_cycle_time_ = false;
has_oscillation_origin_ = false;
has_outcome_ = false;
outcome_report_count_ = 0;
last_reason_ = "";
}
const ProfileBinding* ControlLoop::bindingFor(MotionProfile profile) const
{
switch (profile)
{
case MotionProfile::kPosition:
return &config_.position;
case MotionProfile::kDocking:
return &config_.docking;
case MotionProfile::kGoStraight:
return &config_.go_straight;
case MotionProfile::kRotate:
return &config_.rotate;
}
return nullptr;
}
bool ControlLoop::isQuaternionValid(const robot_geometry_msgs::PoseStamped& pose)
{
const auto& q = pose.pose.orientation;
if (!std::isfinite(q.x) || !std::isfinite(q.y) || !std::isfinite(q.z) || !std::isfinite(q.w))
{
return false;
}
const double norm_sq = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;
return std::abs(std::sqrt(norm_sq) - 1.0) <= kQuaternionNormTolerance;
}
bool ControlLoop::submit(const NavigationRequest& request, std::string& reason)
{
if (!initialized_)
{
reason = "runtime chưa khởi tạo";
return false;
}
// D8: yêu cầu mang action cần có ActionPort; từ chối tại cửa thay vì kẹt sau khi tới goal.
if (!request.actions.empty() && deps_.action == nullptr)
{
reason = "yêu cầu có action nhưng runtime không có action port";
return false;
}
if (!request.has_goal)
{
// D8: yêu cầu chỉ-có-action — không có goal để validate, không có planner để swap.
if (request.actions.empty())
{
reason = "yêu cầu không có goal lẫn action";
return false;
}
pending_request_ = request;
has_pending_request_ = true;
cancel_requested_ = false;
return true;
}
if (!std::isfinite(request.goal.pose.position.x) || !std::isfinite(request.goal.pose.position.y))
{
reason = "goal có toạ độ không hữu hạn";
return false;
}
if (!isQuaternionValid(request.goal))
{
reason = "goal có quaternion không hợp lệ";
return false;
}
const ProfileBinding* binding = bindingFor(request.profile);
if (binding == nullptr || binding->local_planner_name.empty())
{
reason = std::string("chưa cấu hình planner cho profile '") + toString(request.profile) + "'";
return false;
}
// Đổi planner NGAY tại cửa vào, trước khi nhận yêu cầu: nếu không nạp được thì từ chối luôn, chứ
// không để state machine bắt đầu một chặng rồi mới phát hiện không có planner nào chạy được.
if (!binding->global_planner_name.empty() &&
!deps_.planner->swapPlanner(binding->global_planner_name))
{
reason = "không nạp được global planner '" + binding->global_planner_name + "'";
return false;
}
if (!deps_.controller->swapPlanner(binding->local_planner_name))
{
reason = "không nạp được local planner '" + binding->local_planner_name + "'";
return false;
}
deps_.controller->setTolerance(
request.tolerance.hasXy() ? request.tolerance.xy : binding->default_xy_tolerance,
request.tolerance.hasYaw() ? request.tolerance.yaw : binding->default_yaw_tolerance);
pending_request_ = request;
has_pending_request_ = true;
// Yêu cầu mới thay thế yêu cầu đang chờ, không xếp hàng: xếp hàng là việc của mission layer.
cancel_requested_ = false;
return true;
}
void ControlLoop::requestPause()
{
pause_requested_ = true;
resume_requested_ = false;
}
void ControlLoop::requestResume()
{
resume_requested_ = true;
pause_requested_ = false;
}
void ControlLoop::requestCancel()
{
cancel_requested_ = true;
}
void ControlLoop::collectPlannerResult()
{
PlanResult result;
if (!deps_.planner->pollPlan(result))
{
// Chưa có kết quả. Chỉ báo "đang lập" khi thật sự có lượt đang chạy VÀ chưa có phản hồi nào
// khác — `apply_plan` ở cycle trước có thể đã đặt kFailed khi controller từ chối plan, và đó
// là tin quan trọng hơn.
if (planner_running_ && planner_feedback_ == PlannerFeedback::kIdle)
{
planner_feedback_ = PlannerFeedback::kBusy;
}
return;
}
planner_running_ = false;
if (result.tag != plan_tag_)
{
// Kết quả của một yêu cầu đã bị thay hoặc huỷ. Vứt lặng lẽ: bám theo nó nghĩa là robot đi tới
// goal không còn ai yêu cầu. Không phải lỗi, nên cũng không đặt kFailed.
return;
}
// Contract của PlannerPort là "succeeded nghĩa là plan không rỗng". Vẫn kiểm lại ở đây vì plan
// rỗng lọt xuống sẽ thành front()/back() trên vector rỗng ở tầng dưới.
if (!result.succeeded || result.plan.empty())
{
planner_feedback_ = PlannerFeedback::kFailed;
return;
}
latest_plan_.swap(result.plan);
planner_feedback_ = PlannerFeedback::kPlanReady;
}
void ControlLoop::runController(robot_geometry_msgs::Twist& candidate)
{
candidate = robot_geometry_msgs::Twist();
// Giữ nguyên thứ tự của interface được bọc: hỏi đã tới đích trước, chỉ khi chưa mới tính lệnh.
if (deps_.controller->isGoalReached())
{
controller_feedback_ = ControllerFeedback::kGoalReached;
return;
}
robot_geometry_msgs::Twist cmd;
if (deps_.controller->computeVelocityCommands(cmd))
{
controller_feedback_ = ControllerFeedback::kCommandValid;
candidate = cmd;
return;
}
controller_feedback_ = ControllerFeedback::kNoValidCommand;
}
bool ControlLoop::step()
{
if (!initialized_)
{
return false;
}
// --- 1. Thời gian và pose -------------------------------------------------------------------
const robot::Time now = deps_.clock->now();
double dt = config_.nominal_control_period;
if (has_last_cycle_time_)
{
dt = (now - last_cycle_time_).toSec();
if (dt < 0.0)
{
// Đồng hồ lùi (thường do đổi nguồn time). Không có dt tin được thì bỏ giới hạn gia tốc ở
// cycle này thay vì tính ra một giá trị bịa.
dt = 0.0;
}
}
last_cycle_time_ = now;
has_last_cycle_time_ = true;
// Thu kết quả lập plan TRƯỚC khi dựng dữ liệu vào: state machine quyết định dựa trên phản hồi,
// nên phản hồi phải có mặt trước lúc nó chạy.
collectPlannerResult();
robot_geometry_msgs::PoseStamped robot_pose;
const bool pose_available = deps_.pose->getRobotPose(robot_pose);
double travelled = 0.0;
if (pose_available && has_oscillation_origin_)
{
const double dx = robot_pose.pose.position.x - oscillation_origin_.pose.position.x;
const double dy = robot_pose.pose.position.y - oscillation_origin_.pose.position.y;
travelled = std::hypot(dx, dy);
}
// --- 2. State machine -----------------------------------------------------------------------
StateMachineInput input;
input.now = now;
input.has_pending_request = has_pending_request_;
input.pending_request_has_goal = pending_request_.has_goal;
input.pending_request_action_count = pending_request_.actions.size();
input.pause_requested = pause_requested_;
input.resume_requested = resume_requested_;
input.cancel_requested = cancel_requested_;
input.planner = planner_feedback_;
input.controller = controller_feedback_;
input.recovery = recovery_feedback_;
input.action = action_feedback_;
input.pose_available = pose_available;
input.robot_stopped = arbiter_.stopped();
input.travelled_since_oscillation_reset = travelled;
// Cùng một chỉ số dùng cho cả cycle khởi động recovery lẫn các cycle tick: state machine chỉ tăng
// chỉ số khi behavior kết thúc, nên `nextRecoveryIndex()` chính là behavior sắp chạy hoặc đang
// chạy. Hỏi trước khi state machine quyết định để nó biết có nên trao quyền phát vận tốc không.
input.active_recovery_output =
deps_.recovery != nullptr
? deps_.recovery->outputKind(state_machine_.nextRecoveryIndex())
: RecoveryOutputKind::kNone;
const StateMachineOutput output = state_machine_.update(input);
if (output.state_changed)
{
last_reason_ = output.reason;
}
// Cờ một-lần đã được state machine tiêu thụ xong ở lời gọi trên.
pause_requested_ = false;
resume_requested_ = false;
// Phản hồi của cycle trước đã dùng xong; đặt lại để cycle này tự sinh phản hồi mới.
planner_feedback_ = PlannerFeedback::kIdle;
controller_feedback_ = ControllerFeedback::kIdle;
recovery_feedback_ = RecoveryFeedback::kIdle;
action_feedback_ = ActionFeedback::kIdle;
// --- 3. Thi hành output ---------------------------------------------------------------------
if (output.accept_request)
{
active_request_ = pending_request_;
has_active_request_ = true;
has_pending_request_ = false;
latest_plan_.clear();
has_outcome_ = false;
// Nhãn mới: mọi lượt lập plan đang bay thuộc về goal cũ và phải bị vứt khi về.
++plan_tag_;
deps_.planner->cancelPlan();
planner_running_ = false;
}
if (output.reset_oscillation_origin && pose_available)
{
oscillation_origin_ = robot_pose;
has_oscillation_origin_ = true;
}
if (output.stop_planner)
{
// Huỷ thật, không chỉ quên đi: nếu chỉ hạ cờ thì lượt đang chạy vẫn về và chiếm chỗ hộp thư,
// rồi bị nhận nhầm cho lượt kế tiếp mang cùng nhãn.
deps_.planner->cancelPlan();
planner_running_ = false;
}
if (output.apply_plan && !latest_plan_.empty())
{
if (!deps_.controller->setPlan(latest_plan_))
{
// Controller từ chối plan: coi như lần lập plan này hỏng, để chu kỳ kiên nhẫn tiếp tục chạy.
planner_feedback_ = PlannerFeedback::kFailed;
}
}
if (output.cancel_recovery)
{
deps_.recovery->cancel();
}
robot_geometry_msgs::Twist candidate;
if (output.start_recovery)
{
if (!deps_.recovery->start(output.recovery_index, output.recovery_trigger))
{
// Behavior từ chối khởi động (ví dụ đã va chạm ngay tại chỗ) — báo hỏng để state machine
// chuyển sang behavior kế tiếp thay vì tick một behavior chưa start.
recovery_feedback_ = RecoveryFeedback::kFailed;
}
}
else if (output.tick_recovery)
{
const RecoveryTick tick = deps_.recovery->update();
switch (tick.status)
{
case RecoveryTick::Status::kRunning:
recovery_feedback_ = RecoveryFeedback::kRunning;
break;
case RecoveryTick::Status::kSucceeded:
recovery_feedback_ = RecoveryFeedback::kSucceeded;
break;
case RecoveryTick::Status::kFailed:
recovery_feedback_ = RecoveryFeedback::kFailed;
break;
}
if (tick.has_velocity)
{
candidate = tick.cmd;
}
if (tick.has_path && !tick.path.empty())
{
// Họ recovery sinh lại đường đi: coi kết quả như một plan mới, chờ state machine đẩy xuống.
latest_plan_ = tick.path;
planner_feedback_ = PlannerFeedback::kPlanReady;
}
}
if (output.cancel_action && deps_.action != nullptr)
{
deps_.action->cancel();
}
if (output.start_action)
{
// Cửa submit đã chặn yêu cầu có action mà không có port, nhưng vẫn guard: kẹt ở đây nghĩa là
// contract bị phá từ một đường khác — báo action hỏng để state machine kết thúc tường minh.
if (deps_.action == nullptr || output.action_index >= active_request_.actions.size())
{
action_feedback_ = ActionFeedback::kFailed;
}
else if (!deps_.action->start(active_request_.actions[output.action_index]))
{
// Không có handler cho actionType này hoặc handler từ chối — action coi như thất bại.
action_feedback_ = ActionFeedback::kFailed;
}
}
else if (output.tick_action && deps_.action != nullptr)
{
const ActionTick tick = deps_.action->update();
switch (tick.status)
{
case ActionTick::Status::kRunning:
action_feedback_ = ActionFeedback::kRunning;
break;
case ActionTick::Status::kSucceeded:
action_feedback_ = ActionFeedback::kSucceeded;
break;
case ActionTick::Status::kFailed:
action_feedback_ = ActionFeedback::kFailed;
break;
}
}
if (output.run_controller)
{
runController(candidate);
}
if (output.start_planner && pose_available && !planner_running_)
{
// `start_planner` là tín hiệu MỨC ("hãy đang lập plan"), bật lại mỗi cycle chừng nào state
// machine còn ở kPlanning — không phải sườn. Kick lại một lượt đang chạy sẽ vừa bị cổng từ
// chối, vừa làm mất thời gian đã bỏ ra.
planner_running_ = deps_.planner->startPlan(robot_pose, active_request_.goal,
active_request_.order.get(), plan_tag_);
if (!planner_running_)
{
// Không khởi động được (chưa có planner, pose hỏng...). Coi như một lượt hỏng để đồng hồ
// kiên nhẫn tiếp tục chạy, thay vì đứng im ở kPlanning vô hạn.
planner_feedback_ = PlannerFeedback::kFailed;
}
}
// --- 4. Lệnh vận tốc ------------------------------------------------------------------------
arbiter_.arbitrate(output.velocity_source, candidate, dt);
// --- 5. Báo kết quả -------------------------------------------------------------------------
if (output.report_outcome)
{
last_outcome_ = output.outcome;
has_outcome_ = true;
++outcome_report_count_;
if (deps_.mission != nullptr && has_active_request_ &&
active_request_.mission_sequence_id != 0)
{
deps_.mission->reportOutcome(active_request_.mission_sequence_id, output.outcome);
}
has_active_request_ = false;
cancel_requested_ = false;
latest_plan_.clear();
planner_running_ = false;
}
return !output.report_outcome;
}
const char* ControlLoop::lastOutcome() const
{
return has_outcome_ ? toString(last_outcome_) : "";
}
} // namespace move_base2