diff --git a/config/runtime/action_handlers_params.yaml b/config/runtime/action_handlers_params.yaml index a795ef6..99325cc 100644 --- a/config/runtime/action_handlers_params.yaml +++ b/config/runtime/action_handlers_params.yaml @@ -68,9 +68,9 @@ actions: # Để true trên robot thật = robot tiến vào một điểm bịa. use_simulated_goal: true simulated_parent_frame: base_link - simulated_offset_x: -1.5 # [m] ► Chỉnh: chỉ có nghĩa khi use_simulated_goal: true. - simulated_offset_y: 0.2 # [m] Đặt theo vị trí vật thể giả trong world Gazebo. - simulated_offset_yaw: 0.0 # [rad] + simulated_offset_x: -1.0 # [m] ► Chỉnh: chỉ có nghĩa khi use_simulated_goal: true. + simulated_offset_y: 0.0 # [m] Đặt theo vị trí vật thể giả trong world Gazebo. + simulated_offset_yaw: 0.05 # [rad] # [s] Chờ robot đứng hẳn trước khi lấy mẫu — pose lúc vừa dừng còn dao động cơ khí. # ► Chỉnh: TĂNG nếu robot nặng/treo mềm và mẫu đầu bị lệch. GIẢM để rút ngắn chu kỳ dock. @@ -84,7 +84,7 @@ actions: # Số mẫu tối thiểu phải thu được trong cửa sổ, nếu không -> kFailed. # ► Chỉnh: đặt ~= (tần số publish của perception) x `sample_window` x 0.5 để còn dư địa. Đặt cao # quá là action fail dù frame vẫn tốt. - min_samples: 20 + min_samples: 5 # Độ tản tối đa của tập mẫu. Tản hơn -> kFailed, KHÔNG lùi vào. # ► Chỉnh: đây là chốt AN TOÀN, không phải nút để "cho qua". Nới ra nghĩa là chấp nhận tiến vào diff --git a/config/runtime/compound_actions_params.yaml b/config/runtime/compound_actions_params.yaml index 45bce74..a4fcc68 100644 --- a/config/runtime/compound_actions_params.yaml +++ b/config/runtime/compound_actions_params.yaml @@ -58,7 +58,7 @@ vda5050_src: PickUp: steps: - {action: DetectPallet} - - {move_to: dock_target, profile: docking, marker: trolley} + - {move_to: dock_target, profile: docking, marker: pallet} - {action: LiftFork} # Lùi ra khỏi khe kệ. Quãng đường tương đối được quy ra pose tuyệt đối tại `submit`, từ pose # LÚC ĐÓ — lúc adapter sinh chặng thì robot còn chưa tới nơi. @@ -103,3 +103,4 @@ vda5050_src: # ► 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} + diff --git a/config/runtime/custom_global_params.yaml b/config/runtime/custom_global_params.yaml index f462e6b..12ed66f 100644 --- a/config/runtime/custom_global_params.yaml +++ b/config/runtime/custom_global_params.yaml @@ -1,16 +1,35 @@ +# custom_planner — tham số runtime, đọc qua robot::NodeHandle("CustomPlanner"). +# Thiếu key nào thì dùng default trong CustomPlannerConfig (cùng giá trị ghi ở đây). CustomPlanner: library_path: libcustom_planner - environment_type: XYThetaLattice - planner_type: ARAPlanner - allocated_time: 10.0 - initial_epsilon: 1.0 - force_scratch_limit: 10000 - forward_search: false - nominalvel_mpersecs: 0.8 - timetoturn45degsinplace_secs: 1.31 # = 0.6 rad/s - allow_unknown: true - directory_to_save_paths: "/init/paths" - pathway_filename: "pathway.txt" - current_pose_topic_name: "/amcl_pose" - + # [m] start/goal cách pathway dưới ngưỡng này thì coi là đã bám vào pathway + # (quyết định cách nối NURBS start/goal vào tuyến). + pathway_attach_distance: 0.1 + + # [m] order không có node/edge (goal trần): chỉ nhận khi start-goal gần hơn + # ngưỡng này, ngược lại trả false để move_base2 dùng backup planner. + bare_goal_max_distance: 0.2 + + # Bước tham số u trong [0,1] khi đo chiều dài NURBS một cạnh (không phải mét). + nurbs_length_t_interval: 0.01 + + # [m] khoảng cách mong muốn giữa hai pose khi lấy mẫu NURBS nối start/goal. + nurbs_point_spacing: 0.05 + + # [rad] hai cạnh thẳng đầu gãy dưới góc này thì bỏ cạnh đầu khi tính yaw. + skip_edge_angle: 0.4712 # = 0.15*pi + + # [rad] góc nối giữa hai cạnh <= tight: gãy gắt (cost 20); < wide: gãy vừa (cost 10). + cost_angle_tight: 0.3142 # = 0.1*pi + cost_angle_wide: 1.4137 # = 0.45*pi + + # [rad] cửa sổ góc đổi hướng cần chèn chuỗi pose xoay tại chỗ giữa hai cạnh. + rotation_insert_min: 1.4137 # = 0.45*pi + rotation_insert_max: 2.6704 # = 0.85*pi + + # [rad] bước yaw giữa hai pose xoay tại chỗ được chèn. + rotation_step: 0.1571 # = 0.05*pi + + # [rad] |yaw goal - hướng cạnh cuối| vượt ngưỡng này thì đoạn cuối đi lùi. + backward_decision_angle: 1.5708 # = 0.5*pi diff --git a/config/runtime/dock_global_params.yaml b/config/runtime/dock_global_params.yaml index 3191200..b39b111 100644 --- a/config/runtime/dock_global_params.yaml +++ b/config/runtime/dock_global_params.yaml @@ -1,11 +1,42 @@ +# DockPlanner plugin and approach-curve parameters. +# +# Collision/free-space checking is intentionally not configured here yet: +# DockPlanner currently generates geometry only. Do not add cost_threshold, +# allow_unknown, or check_free_space until the collision checker is implemented. DockPlanner: + # Boost.DLL library containing the exported symbol "DockPlanner". library_path: libdock_planner - MyGlobalPlanner: - cost_threshold: 200 # Ngưỡng chi phí vật cản (0-255) - safety_distance: 2 # Khoảng cách an toàn (cells) - use_dijkstra: false # Sử dụng Dijkstra thay vì A* - - # File: config/costmap_params.yaml - global_costmap: - inflation_radius: 0.3 # Bán kính phình vật cản - cost_scaling_factor: 10.0 # Hệ số tỷ lệ chi phí \ No newline at end of file + + approach: + # [m] Extra straight alignment distance beyond half the combined robot/dock + # X extents. Increase if the robot must align earlier before entering a dock. + alignment_distance_padding: 0.0 + + # [m] Lateral-distance range used to interpolate angle_threshold_*. + # Values outside this range are clamped, so behavior remains bounded. + lateral_distance_near: 0.10 + lateral_distance_far: 1.00 + + # [rad] Permitted joining angle at the near/far lateral-distance limits. + # Required relation: 0 < far < near < pi. + angle_threshold_near: 2.35619449019 # 0.75*pi + angle_threshold_far: 1.09955742876 # 0.35*pi + + # [rad] Relaxes the forward direction test relative to the reverse test. + # Required: 0 <= value < angle_threshold_far. + direction_angle_hysteresis: 0.05 + + # [m] Distance margin used when rejecting a reference-path joining point + # that is already too close to the end of the approach curve. + direction_distance_tolerance: 0.10 + + sampling: + # [m] Target spacing between generated path poses. The curve is sampled by + # arc-length estimate and always includes both endpoints. + path_point_spacing: 0.05 + + # footprint_dock is intentionally not declared here. It describes the + # physical dock, not the robot, and move_base2 copies the value selected from + # docking_marker_profiles//footprint_dock into this namespace before + # constructing the planner. If absent, dock size contributes 0 m to approach + # geometry and DockPlanner emits a warning. diff --git a/config/runtime/maker_sources.yaml b/config/runtime/maker_sources.yaml index a106c5f..0794fbd 100644 --- a/config/runtime/maker_sources.yaml +++ b/config/runtime/maker_sources.yaml @@ -17,24 +17,70 @@ # ► Chỉnh: chỉ thêm/bớt TÊN, cách nhau bằng khoảng trắng. Giữ danh sách tối thiểu — mỗi tên thừa là # một đường vào chưa được kiểm chứng. Sẽ bỏ hẳn khi `dockTo` được chuyển sang dock_sequences khai # báo trong compound_actions_params.yaml. -maker_sources: trolley charger dock_station undock_station dock_station_2 undock_station_2 +maker_sources: trolley charger dock_station pallet # Marker có entry ở đây dùng CẶP PLANNER RIÊNG. Marker rỗng, hoặc chỉ có trong `maker_sources` mà # không nằm trong bảng này, sẽ dùng cặp `docking` mặc định của move_base_common_params.yaml. # -# ► Chỉnh: chỉ khai marker nào THỰC SỰ cần planner khác mặc định — ba entry dưới đây đang trùng y -# hệt cặp mặc định, tức chúng không đổi hành vi gì, giữ lại chỉ để làm chỗ móc khi cần tách sau -# này. Tham số của planner nằm ở YAML riêng của plugin (dock_global_params.yaml, -# hybrid_local_planner_params.yaml), KHÔNG khai ở đây. +# ► Chỉnh: chỉ khai marker nào THỰC SỰ cần planner khác mặc định. Tham số của planner nằm ở YAML +# riêng của plugin (dock_global_params.yaml, hybrid_local_planner_params.yaml), KHÔNG khai ở đây — +# trừ `footprint_dock` dưới đây. +# +# ── footprint_dock ──────────────────────────────────────────────────────────────────────────────── +# +# Đa giác của ĐỐI TƯỢNG DOCK (kệ / trạm sạc), [m], trong frame của goal pose. KHÔNG phải footprint +# robot: footprint robot khai ở costmap và dùng cho collision check, còn khoá này vào khoảng dừng +# của DockCalc — điểm robot bắt đầu đoạn căn thẳng trước dock: +# +# alignment_distance = + + padding +# +# Chỉ dùng khi `dock_anchor: center`. Khai thiếu = dock bị coi là một điểm, robot tiến sát hơn dự +# tính đúng extent tới mặt gần. +# +# ── dock_anchor ─────────────────────────────────────────────────────────────────────────────────── +# +# Goal pose của marker nằm ở đâu trên đối tượng dock: +# center — goal ở tâm footprint dock; DockPlanner cộng thêm extent từ tâm tới mặt tiếp cận +# (lấy từ footprint_dock). Mặc định khi không khai — giữ nguyên hành vi cũ. +# face — goal đã nằm ngay tâm MẶT tiếp cận; dock không đóng góp vào khoảng dừng, +# footprint_dock bị bỏ qua hoàn toàn (DockPlanner log info nếu vẫn khai). +# +# Hai khoá trên là các khoá DUY NHẤT trong bảng này được rót xuống plugin: +# `PlannerRunner::bindDockingMarker()` chép chúng sang namespace của `global_planner` khai ngay bên +# trên, TRƯỚC khi instance được dựng, rồi dựng lại instance khi marker đổi. +# +# ⚠ Chỉ `DockPlanner` đọc hai khoá này. Marker nào khai `global_planner: TwoPointsPlanner` thì giá +# trị vẫn được chép sang namespace đó nhưng không ai đọc — không lỗi, không log, chỉ là không có +# tác dụng. +# +# ► Chỉnh: đo kích thước THẬT của từng loại kệ/trạm — chúng khác nhau, để trùng số là mất tác dụng +# của việc khai theo marker. Trục x là hướng robot tiến vào. Chọn `dock_anchor` theo cách teach +# goal của từng loại: goal teach ở mặt (pallet, charger) → face; goal teach ở tâm (trolley chui +# gầm) → center. docking_marker_profiles: trolley: global_planner: DockPlanner local_planner: HybridLocalPlanner + # Goal ở trọng tâm xe trolley (robot chui gầm) → cộng extent tâm→mặt từ footprint_dock. + dock_anchor: center + footprint_dock: [[0.583,-0.48],[0.583,0.48],[-0.583,0.48],[-0.583,-0.48]] charger: - global_planner: DockPlanner + global_planner: TwoPointsPlanner local_planner: HybridLocalPlanner + # Goal teach ngay tâm mặt trạm sạc. Chỉ có tác dụng nếu đổi sang DockPlanner. + dock_anchor: face + footprint_dock: [[0.583,-0.48],[0.583,0.48],[-0.583,0.48],[-0.583,-0.48]] dock_station: + global_planner: TwoPointsPlanner + local_planner: HybridLocalPlanner + dock_anchor: center + footprint_dock: [[0.583,-0.48],[0.583,0.48],[-0.583,0.48],[-0.583,-0.48]] + + pallet: global_planner: DockPlanner local_planner: HybridLocalPlanner + # Goal teach ở tâm mặt pallet → dock không đóng góp khoảng dừng, footprint_dock bị bỏ qua. + dock_anchor: face + footprint_dock: [[0.9,-0.8],[0.9,0.8],[-0.9,0.8],[-0.9,-0.8]] diff --git a/include/move_base2/ports/planner_port.h b/include/move_base2/ports/planner_port.h index c96d265..988d166 100644 --- a/include/move_base2/ports/planner_port.h +++ b/include/move_base2/ports/planner_port.h @@ -66,6 +66,31 @@ public: */ virtual bool swapPlanner(const std::string& planner_name) = 0; + /** + * @brief Nối tham số riêng của một marker docking vào namespace của global planner sắp dùng. + * Gọi TRƯỚC @ref swapPlanner của chính chặng đó. + * + * Global planner không nhận marker qua chữ ký nào cả: `BaseGlobalPlanner::initialize(name, costmap)` + * chỉ có tên plugin, và plugin tự dựng `robot::NodeHandle` của nó để đọc param. Nên kênh duy nhất + * là param tree — chép `docking_marker_profiles//…` sang `/…` trước khi + * instance được dựng, đúng cách `Costmap2DROBOT::copyParentParameters` rót param xuống từng layer. + * + * Hiện thực phải coi đây là điểm đánh dấu "marker đã đổi": instance đang cache đã đọc param trong + * `initialize()` và không bao giờ đọc lại, nên phải dựng lại nó — nếu không, dock lần hai với + * marker khác vẫn chạy bằng footprint của lần đầu. + * + * @param marker Tên marker; rỗng = chặng không phải docking, không làm gì. + * @param planner_name Alias plugin global planner của chặng đó (đích chép sang). + * @return false nếu marker có khai profile nhưng param của nó hỏng — bên gọi phải từ chối yêu cầu + * thay vì dock bằng hình học sai. + * + * Default trả true (không làm gì): chỉ hiện thực thật (PlannerRunner) mới có param tree. + */ + virtual bool bindDockingMarker(const std::string& /*marker*/, const std::string& /*planner_name*/) + { + return true; + } + /** * @brief Khởi động một lượt lập plan. **Không chặn.** * diff --git a/include/move_base2/runners/planner_runner.h b/include/move_base2/runners/planner_runner.h index 6dbbea5..c2a3bda 100644 --- a/include/move_base2/runners/planner_runner.h +++ b/include/move_base2/runners/planner_runner.h @@ -110,6 +110,8 @@ public: bool swapPlanner(const std::string& planner_name) override; + bool bindDockingMarker(const std::string& marker, const std::string& planner_name) override; + /** * @brief Gắn bộ telemetry (non-owning, có thể null = tắt đo). * @@ -154,6 +156,16 @@ private: { std::function factory; robot_nav_core::BaseGlobalPlanner::Ptr instance; + + /** + * Instance đã bị thay khi marker đổi, giữ lại chứ KHÔNG huỷ. + * + * Thread lập plan chụp `active_` rồi nhả mutex trước khi gọi `makePlan` — huỷ instance cũ ở + * control thread trong lúc đó là use-after-free trên một plugin đang chạy. Cùng lý do với việc + * cache không bao giờ xoá entry. Mỗi lần đổi marker thêm đúng một instance; số marker hữu hạn + * nên bộ nhớ không trôi. + */ + std::vector retired; }; /// @brief Nạp @p name nếu chưa có trong cache. @return nullptr khi thất bại (đã log lý do). @@ -177,6 +189,18 @@ private: std::map planners_; std::string active_name_; + /// Marker vừa đổi và instance đang cache chưa đọc lại param của nó — @ref acquire phải dựng lại. + bool marker_dirty_ = false; + + /** + * Marker đã nối vào từng planner, khoá theo alias plugin. + * + * Dùng để KHÔNG dựng lại instance khi dock lại đúng marker cũ: giá trị trong param tree không đổi + * thì `initialize()` cũng đọc ra đúng ngần ấy. Không có bảng này thì mỗi chặng docking là một lần + * initialize() thừa, và với planner nặng thì nó rơi đúng vào lúc robot đang chờ lệnh. + */ + std::map bound_marker_; + // --- Chia sẻ giữa hai thread, bảo vệ bởi mutex_ ------------------------------------------------ mutable std::mutex mutex_; std::condition_variable cv_; diff --git a/src/control_loop.cpp b/src/control_loop.cpp index 53fc144..23f1efc 100644 --- a/src/control_loop.cpp +++ b/src/control_loop.cpp @@ -435,6 +435,16 @@ bool ControlLoop::submit(const NavigationRequest& incoming, std::string& reason) reason = "marker '" + request.marker + "' is invalid (not listed in maker_sources?)"; return false; } + + // Global planner nhận marker qua param tree, không qua chữ ký hàm: chép + // `docking_marker_profiles//footprint` sang namespace của planner TRƯỚC khi swap, vì + // swap là chỗ instance được dựng và đọc param. Đảo thứ tự = dock bằng hình học của chặng trước. + if (!request.marker.empty() && + !deps_.planner->bindDockingMarker(request.marker, binding->global_planner_name)) + { + reason = "marker '" + request.marker + "' has a malformed docking_marker_profiles entry"; + 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ứ diff --git a/src/runners/planner_runner.cpp b/src/runners/planner_runner.cpp index b1ab32d..fa9b082 100644 --- a/src/runners/planner_runner.cpp +++ b/src/runners/planner_runner.cpp @@ -32,6 +32,47 @@ bool isFinitePose(const robot_geometry_msgs::PoseStamped& pose) std::isfinite(pose.pose.orientation.z) && std::isfinite(pose.pose.orientation.w); } +/// @brief Các khoá được phép chép từ profile marker sang namespace của global planner. +/// +/// Danh sách đóng, không chép cả cụm: `docking_marker_profiles/` còn chứa `global_planner` +/// và `local_planner`, chép sang sẽ đè lên `library_path`-lân cận và tạo ra khoá vô nghĩa trong +/// namespace planner. Thêm khoá mới ở đây thì thêm cả doc trong `maker_sources.yaml`. +/// +/// `footprint_dock` chứ không phải `footprint`: đây là kích thước ĐỐI TƯỢNG DOCK, còn `footprint` +/// trong hệ này luôn có nghĩa là footprint robot (costmap, recovery, collision check). Hai thứ vào +/// hai công thức khác nhau, trùng tên là mời gọi đặt nhầm giá trị. +/// +/// `dock_anchor` khai goal pose của marker nằm ở tâm footprint dock (`center`) hay ngay trên mặt +/// tiếp cận (`face`). `face` thì DockPlanner bỏ qua `footprint_dock` hoàn toàn. +constexpr const char* kMarkerPlannerParams[] = {"footprint_dock", "dock_anchor"}; + +/** + * @brief Chép MỘT khoá giữa hai namespace của param tree, giữ nguyên kiểu. + * + * Cùng ý với `robot_costmap_2d::move_parameter`, khác hai điểm: + * - dùng `YAML::Node` nên chép được cả cấu trúc lồng (footprint là sequence của sequence), không + * phải khai sẵn kiểu C++ cho từng khoá; + * - trả về việc có chép hay không, để bên gọi biết khi nào phải dựng lại instance. + * + * @return true nếu khoá tồn tại ở nguồn và đã được ghi sang đích. + */ +bool copyParamNode(const robot::NodeHandle& from, robot::NodeHandle& to, const std::string& key) +{ + if (!from.hasParam(key)) + { + return false; + } + + YAML::Node value; + if (!from.getParam(key, value) || !value.IsDefined()) + { + return false; + } + + to.setParam(key, value); + return true; +} + } // namespace PlannerRunner::PlannerRunner() = default; @@ -103,6 +144,44 @@ robot_nav_core::BaseGlobalPlanner* PlannerRunner::acquire(const std::string& nam const auto cached = planners_.find(name); if (cached != planners_.end()) { + if (!marker_dirty_) + { + return cached->second.instance.get(); + } + + // Marker vừa đổi: instance này đọc footprint của dock trong initialize() và không bao giờ đọc + // lại. Dựng lại từ factory sẵn có (không dlopen lại). Instance mới chỉ thay chỗ khi + // initialize() thành công — thất bại thì giữ nguyên cache và trả lỗi để bên gọi từ chối yêu + // cầu, không để lại trạng thái nửa vời. + robot_nav_core::BaseGlobalPlanner::Ptr fresh; + try + { + fresh = cached->second.factory(); + if (!fresh) + { + robot::log_error("[move_base2] PlannerRunner: factory of '%s' returned nullptr while " + "rebuilding for the new marker.\n", name.c_str()); + return nullptr; + } + if (!fresh->initialize(name, costmap_)) + { + robot::log_error("[move_base2] PlannerRunner: '%s' reported an initialize() failure while " + "rebuilding for the new marker.\n", name.c_str()); + return nullptr; + } + } + catch (const std::exception& ex) + { + robot::log_error("[move_base2] PlannerRunner: rebuilding '%s' for the new marker failed: %s\n", + name.c_str(), ex.what()); + return nullptr; + } + + // Instance cũ được GIỮ, không huỷ: thread lập plan có thể đang ở trong makePlan() của nó với + // mutex đã nhả. Xem doc của `Loaded::retired`. + cached->second.retired.push_back(std::move(cached->second.instance)); + cached->second.instance = std::move(fresh); + marker_dirty_ = false; return cached->second.instance.get(); } @@ -179,9 +258,72 @@ robot_nav_core::BaseGlobalPlanner* PlannerRunner::acquire(const std::string& nam // Chỉ đưa vào cache khi đã khởi tạo xong — cache một instance hỏng nghĩa là mọi lần thử lại sau // đều nhận lại đúng cái hỏng đó mà không báo gì. const auto inserted = planners_.emplace(name, std::move(loaded)); + // Instance mới vừa initialize() với param marker hiện hành — marker không còn "chưa được đọc". + marker_dirty_ = false; return inserted.first->second.instance.get(); } +bool PlannerRunner::bindDockingMarker(const std::string& marker, const std::string& planner_name) +{ + if (!configured_) + { + robot::log_error("[move_base2] PlannerRunner: bindDockingMarker() before configure().\n"); + return false; + } + + if (marker.empty() || planner_name.empty()) + { + return true; // Chặng không phải docking, hoặc profile không khai global planner riêng. + } + + const std::string profile_ns = "docking_marker_profiles/" + marker; + if (!nh_.hasParam(profile_ns)) + { + // Marker hợp lệ nhưng không có profile riêng: cặp planner mặc định, không có gì để chép. Không + // phải lỗi — `maker_sources` mới là allow-list, bảng profile chỉ là override. + return true; + } + + // Namespace phải được kiểm TRƯỚC khi dựng NodeHandle: `robot::NodeHandle` không báo lỗi khi + // namespace không resolve được mà lặng lẽ rơi về namespace cha. Bỏ qua bước này thì marker gõ sai + // sẽ đọc `footprint` ở ROOT — tức footprint ROBOT — rồi dùng nó làm kích thước trạm dock. + robot::NodeHandle marker_nh(nh_, profile_ns); + robot::NodeHandle planner_nh(nh_, planner_name); + if (marker_nh.getNamespace() == nh_.getNamespace() || + planner_nh.getNamespace() == nh_.getNamespace()) + { + robot::log_error("[move_base2] PlannerRunner: namespace '%s' or '%s' does not resolve in the " + "param tree; refusing to bind marker '%s'.\n", + profile_ns.c_str(), planner_name.c_str(), marker.c_str()); + return false; + } + + bool copied = false; + for (const char* key : kMarkerPlannerParams) + { + copied = copyParamNode(marker_nh, planner_nh, key) || copied; + } + + if (!copied) + { + return true; // Profile có tồn tại nhưng không khai khoá nào của planner — giữ nguyên cấu hình. + } + + // Dựng lại instance CHỈ khi marker nối vào planner này thực sự đổi. Dock lại đúng marker cũ thì + // param tree không đổi, initialize() lại cũng ra đúng ngần ấy — đánh dấu dirty vô điều kiện là mỗi + // chặng docking một lần initialize() thừa. Bảng theo TỪNG planner vì hai marker có thể trỏ về hai + // planner khác nhau và không được xoá dấu của nhau. + const auto bound = bound_marker_.find(planner_name); + if (bound == bound_marker_.end() || bound->second != marker) + { + bound_marker_[planner_name] = marker; + marker_dirty_ = true; + robot::log_info("[move_base2] PlannerRunner: bound marker '%s' params into '%s'.\n", + marker.c_str(), planner_name.c_str()); + } + return true; +} + bool PlannerRunner::swapPlanner(const std::string& planner_name) { if (!configured_) @@ -196,7 +338,7 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name) return false; } - if (planner_name == active_name_) + if (planner_name == active_name_ && !marker_dirty_) { std::lock_guard lock(mutex_); if (active_ != nullptr) @@ -204,6 +346,8 @@ bool PlannerRunner::swapPlanner(const std::string& planner_name) return true; // Đã đúng planner; không log để khỏi spam ở cửa vào mỗi yêu cầu. } } + // Marker vừa đổi thì KHÔNG được đi tắt kể cả khi tên planner không đổi: phải rơi xuống acquire() + // để instance được dựng lại và initialize() đọc footprint mới. robot_nav_core::BaseGlobalPlanner* planner = acquire(planner_name); if (planner == nullptr) diff --git a/test/config/move_base2_params.yaml b/test/config/move_base2_params.yaml index 43d9c7a..80696e2 100644 --- a/test/config/move_base2_params.yaml +++ b/test/config/move_base2_params.yaml @@ -213,6 +213,29 @@ actions_missing_library: NoopActionHandler: library_path: libaction_core_noop_action_handler +# --- Profile marker docking ở ROOT, cho PlannerRunner::bindDockingMarker ------------------------ +# +# Ở runtime bảng này nằm tại ROOT (maker_sources.yaml) và `PlannerRunner` đọc nó qua NodeHandle gốc, +# khác với bản lồng trong `move_base2:`/`root_profiles:` ở trên — bản đó là đầu vào của +# MoveBase2Config, dùng cho config_validation_test. Hai bản cố ý tách nhau: chúng kiểm hai đường đọc +# khác nhau của cùng một khái niệm. +docking_marker_profiles: + dock_a: + global_planner: TestPlannerOk + local_planner: TestControllerOk + footprint_dock: [[0.5, -0.4], [0.5, 0.4], [-0.5, 0.4], [-0.5, -0.4]] # [m] + + dock_b: + global_planner: TestPlannerOk + local_planner: TestControllerOk + footprint_dock: [[0.2, -0.15], [0.2, 0.15], [-0.2, 0.15], [-0.2, -0.15]] # [m], nhỏ hơn dock_a + + # Có profile nhưng KHÔNG khai footprint_dock: bindDockingMarker phải chấp nhận và không đánh dấu + # phải dựng lại instance. + dock_no_footprint: + global_planner: TestPlannerOk + local_planner: TestControllerOk + # --- Global planner giả cho planner_runner_test ------------------------------------------------- # # Bốn alias cùng nằm trong một thư viện; mỗi alias là một hành vi mà PlannerRunner phải xử lý đúng. diff --git a/test/planner_runner_test.cpp b/test/planner_runner_test.cpp index 2566d5c..401a4d0 100644 --- a/test/planner_runner_test.cpp +++ b/test/planner_runner_test.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -17,6 +18,9 @@ #include #include +#include +#include + #include #include @@ -422,6 +426,149 @@ TEST(PlannerRunner, DestructorJoinsWhileAPlanIsInFlight) SUCCEED(); } +// ================================================================================================ +// Nối tham số marker docking vào namespace của global planner +// ================================================================================================ + +namespace +{ + +/// @brief Đọc cửa sổ quan sát trong thư viện plugin test (xem test_global_planner.cpp). +std::size_t pluginInitializeCount() +{ + return boost::dll::import_alias( + "libmove_base2_test_global_planner", "TestPlannerInitializeCount", + boost::dll::load_mode::append_decorations | boost::dll::load_mode::search_system_folders)(); +} + +std::string pluginLastFootprintDock() +{ + return boost::dll::import_alias( + "libmove_base2_test_global_planner", "TestPlannerLastFootprintDock", + boost::dll::load_mode::append_decorations | boost::dll::load_mode::search_system_folders)(); +} + +} // namespace + +TEST(PlannerRunnerDockingMarker, CopiesTheMarkerFootprintIntoThePlannerNamespace) +{ + Fixture fixture; + ASSERT_TRUE(fixture.ok()) << fixture.error(); + + ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_a", "TestPlannerOk")); + + // Đích là namespace của PLANNER, không phải của marker: plugin chỉ đọc namespace mang tên chính + // nó, nên chép sai chỗ là khoá nằm im mãi mãi mà không có lỗi nào. + robot::NodeHandle nh; + YAML::Node copied; + ASSERT_TRUE(nh.getParam("TestPlannerOk/footprint_dock", copied)); + ASSERT_TRUE(copied.IsSequence()); + ASSERT_EQ(copied.size(), 4U); + EXPECT_DOUBLE_EQ(copied[0][0].as(), 0.5); + EXPECT_DOUBLE_EQ(copied[0][1].as(), -0.4); +} + +TEST(PlannerRunnerDockingMarker, TargetsWhateverPlannerTheProfileNamesNotJustDockPlanner) +{ + Fixture fixture; + ASSERT_TRUE(fixture.ok()) << fixture.error(); + + // Tên planner đến từ profile, không hard-code. Planner này còn chưa có block config nào — + // `setParam` phải tự tạo, nếu không thì mọi planner mới thêm đều lặng lẽ không nhận được param. + ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_b", "SomeOtherGlobalPlanner")); + + robot::NodeHandle nh; + YAML::Node copied; + ASSERT_TRUE(nh.getParam("SomeOtherGlobalPlanner/footprint_dock", copied)); + ASSERT_TRUE(copied.IsSequence()); + EXPECT_DOUBLE_EQ(copied[0][0].as(), 0.2); +} + +TEST(PlannerRunnerDockingMarker, RebuildsTheInstanceSoTheNewMarkerFootprintIsActuallyRead) +{ + Fixture fixture; + ASSERT_TRUE(fixture.ok()) << fixture.error(); + + const std::size_t after_configure = pluginInitializeCount(); + + ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_a", "TestPlannerOk")); + ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk")); + EXPECT_EQ(pluginInitializeCount(), after_configure + 1) + << "instance phải được dựng lại thì initialize() mới đọc được footprint mới"; + const std::string dock_a = pluginLastFootprintDock(); + EXPECT_NE(dock_a.find("0.5"), std::string::npos) << dock_a; + + // Marker khác, CÙNG planner: đường tắt "đã đúng planner" trong swapPlanner không được nuốt lần + // dựng lại này — nuốt là dock vào trạm thứ hai bằng kích thước của trạm thứ nhất. + ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_b", "TestPlannerOk")); + ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk")); + EXPECT_EQ(pluginInitializeCount(), after_configure + 2); + const std::string dock_b = pluginLastFootprintDock(); + EXPECT_NE(dock_b.find("0.2"), std::string::npos) << dock_b; + + // Thư viện chỉ được dlopen một lần: dựng lại là gọi lại factory sẵn có, không nạp lại .so. + EXPECT_EQ(fixture.runner_.loadedCount(), 1U); +} + +TEST(PlannerRunnerDockingMarker, DockingTheSameMarkerTwiceDoesNotReinitialiseThePlanner) +{ + Fixture fixture; + ASSERT_TRUE(fixture.ok()) << fixture.error(); + + ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_a", "TestPlannerOk")); + ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk")); + const std::size_t after_first = pluginInitializeCount(); + + ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_a", "TestPlannerOk")); + ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk")); + EXPECT_EQ(pluginInitializeCount(), after_first) + << "param không đổi thì initialize() lại chỉ tốn thời gian ngay lúc robot đang chờ lệnh"; +} + +TEST(PlannerRunnerDockingMarker, MarkerWithoutAProfileIsAcceptedAndChangesNothing) +{ + Fixture fixture; + ASSERT_TRUE(fixture.ok()) << fixture.error(); + + ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk")); + const std::size_t before = pluginInitializeCount(); + + // `maker_sources` mới là allow-list; bảng profile chỉ là override. Marker hợp lệ nhưng không có + // entry riêng phải chạy tiếp bằng cặp planner mặc định, không bị từ chối. + EXPECT_TRUE(fixture.runner_.bindDockingMarker("marker_without_profile", "TestPlannerOk")); + ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk")); + EXPECT_EQ(pluginInitializeCount(), before); +} + +TEST(PlannerRunnerDockingMarker, ProfileWithoutFootprintDockIsAcceptedAndChangesNothing) +{ + Fixture fixture; + ASSERT_TRUE(fixture.ok()) << fixture.error(); + + ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk")); + const std::size_t before = pluginInitializeCount(); + + EXPECT_TRUE(fixture.runner_.bindDockingMarker("dock_no_footprint", "TestPlannerOk")); + ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk")); + EXPECT_EQ(pluginInitializeCount(), before); +} + +TEST(PlannerRunnerDockingMarker, EmptyMarkerOrPlannerNameIsANoOp) +{ + Fixture fixture; + ASSERT_TRUE(fixture.ok()) << fixture.error(); + + // Chặng không phải docking, hoặc profile không khai global planner riêng — cả hai đều hợp lệ. + EXPECT_TRUE(fixture.runner_.bindDockingMarker("", "TestPlannerOk")); + EXPECT_TRUE(fixture.runner_.bindDockingMarker("dock_a", "")); +} + +TEST(PlannerRunnerDockingMarker, RefusesBeforeConfigure) +{ + PlannerRunner runner; + EXPECT_FALSE(runner.bindDockingMarker("dock_a", "TestPlannerOk")); +} + int main(int argc, char** argv) { // ctest không mang theo biến môi trường của shell; binary tự trỏ vào cây config và thư viện của diff --git a/test/plugins/test_global_planner.cpp b/test/plugins/test_global_planner.cpp index 643df90..52723e7 100644 --- a/test/plugins/test_global_planner.cpp +++ b/test/plugins/test_global_planner.cpp @@ -8,11 +8,16 @@ * đúng. Chọn cách này thay vì một plugin đọc config: nó làm test không phụ thuộc vào cây config, và * mỗi kịch bản gọi tên đúng thứ nó kiểm. * + * Hai alias còn lại (`TestPlannerInitializeCount`, `TestPlannerLastFootprintDock`) không phải + * planner: chúng mở cửa sổ quan sát vào việc `initialize()` chạy mấy lần và đọc được param nào — + * thứ mà `bindDockingMarker` phải làm đúng và không có đường nào khác để kiểm từ ngoài. + * * Không alias nào chạm vào con trỏ costmap — đó là điều kiện để test truyền vào một con trỏ giả * thay vì phải dựng `Costmap2DROBOT` thật (cần tf3::BufferCore và cây config đầy đủ). * * Author: DuongTD *********************************************************************/ +#include #include #include #include @@ -20,7 +25,9 @@ #include #include #include +#include +#include #include namespace move_base2 @@ -31,6 +38,18 @@ namespace testing /// @brief Số pose trong plan mà `TestPlannerOk` sinh ra. constexpr std::size_t kPlanLength = 3; +/** + * Số lần `initialize()` được gọi trên MỌI instance của thư viện này, và footprint mà lần gọi cuối + * đọc được. + * + * Cách duy nhất để test quan sát việc PlannerRunner có dựng lại instance khi marker đổi hay không: + * cache của runner không lộ con trỏ instance ra ngoài, và dựng lại đúng là điều kiện để plugin đọc + * lại param. Biến process-global vì mỗi test chạy trong một tiến trình riêng và thư viện chỉ được + * nạp một lần. + */ +std::size_t g_initialize_count = 0; +std::string g_last_footprint_dock; + /** * @class TestGlobalPlanner * @brief Planner giả, hành vi cố định theo tham số dựng. @@ -54,6 +73,17 @@ public: { // Cố ý KHÔNG chạm costmap_robot — xem chú thích đầu file. name_ = std::move(name); + ++g_initialize_count; + + // Đọc param theo đúng cách plugin thật làm — namespace là TÊN PLUGIN. Ghi lại dạng chuỗi để + // test so được giá trị nào đã tới nơi, không chỉ là "có tới hay không". + robot::NodeHandle nh(name_); + YAML::Node footprint; + g_last_footprint_dock.clear(); + if (nh.getParam("footprint_dock", footprint) && footprint.IsDefined()) + { + g_last_footprint_dock = YAML::Dump(footprint); + } return behavior_ != Behavior::kInitFails; } @@ -119,6 +149,18 @@ robot_nav_core::BaseGlobalPlanner::Ptr createInitFailing() return std::make_shared(TestGlobalPlanner::Behavior::kInitFails); } +/// @brief Số lần `initialize()` đã chạy trong thư viện này — cửa sổ quan sát cho test. +std::size_t initializeCount() +{ + return g_initialize_count; +} + +/// @brief `footprint_dock` mà lần `initialize()` gần nhất đọc được; rỗng nếu khoá vắng mặt. +std::string lastFootprintDock() +{ + return g_last_footprint_dock; +} + } // namespace testing } // namespace move_base2 @@ -126,3 +168,5 @@ BOOST_DLL_ALIAS(move_base2::testing::createOk, TestPlannerOk) BOOST_DLL_ALIAS(move_base2::testing::createEmptyPlan, TestPlannerEmptyPlan) BOOST_DLL_ALIAS(move_base2::testing::createThrowing, TestPlannerThrowing) BOOST_DLL_ALIAS(move_base2::testing::createInitFailing, TestPlannerInitFails) +BOOST_DLL_ALIAS(move_base2::testing::initializeCount, TestPlannerInitializeCount) +BOOST_DLL_ALIAS(move_base2::testing::lastFootprintDock, TestPlannerLastFootprintDock)