diff --git a/README.md b/README.md index fd2d3ac..81389c2 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,18 @@ Handler dò trạm dock từ **scan LiDAR thô**, nạp qua Boost.DLL như mọi Đây là tầng **adapter**, và là chỗ duy nhất trong chuỗi dò được phép biết tới TF, action và kho cảm biến. +## Hướng vào trạm và cách gắn LiDAR + +`entry_direction: backward` (mặc định) dùng LiDAR nhìn phía sau: robot lùi vào, heading goal +hướng ra khỏi trạm. `forward` dùng LiDAR nhìn phía trước: robot tiến vào, heading goal hướng vào +trạm. Đổi `scan_topic` sang LiDAR cùng phía khi đổi hướng. Handler kiểm tra TF từ frame scan tới +`robot_base_frame`; sai phía hoặc mặt phẳng scan nghiêng quá 5° làm action fail, không ghi goal. +Nếu LiDAR lộn ngược, handler tự nhận từ TF và phản chiếu bearing, không cần cấu hình flip. + +Vị trí goal và `offset_x`, `offset_y`, `offset_yaw` vẫn tính trong hệ hình: trục x hướng từ đỉnh +ra phía robot, y sang trái hệ hình. Với `forward`, `offset_y` dương tương ứng phía phải robot khi +robot hướng vào trạm. Các phép kiểm TF và hình học cần được xác nhận với robot và scan thực tế. + ## Chuỗi bốn tầng ``` diff --git a/doc/MEASURE_AND_CONFIGURE.md b/doc/MEASURE_AND_CONFIGURE.md index 6c8b177..8a46f76 100644 --- a/doc/MEASURE_AND_CONFIGURE.md +++ b/doc/MEASURE_AND_CONFIGURE.md @@ -16,6 +16,7 @@ actions: detect_lidar: # tên action, tuỳ cây config action_types: [DetectCharger] scan_topic: /b_scan + entry_direction: backward ... default_profile: v_std profiles: @@ -29,6 +30,18 @@ actions: - Handler đọc và **kiểm mọi profile lúc boot**. Sửa YAML xong phải khởi động lại nav, nếu không nav vẫn chạy với config cũ. Một profile sai miền giá trị làm handler từ chối nạp và log rõ khoá nào sai. +## Hướng vào trạm và TF LiDAR + +`backward` (mặc định) chọn LiDAR sau: robot lùi vào, heading goal hướng ra khỏi trạm. `forward` +chọn LiDAR trước: robot tiến vào, heading hướng vào trạm. Khi đổi hướng, đổi `scan_topic` sang +LiDAR cùng phía. Handler kiểm TF từ frame scan tới `robot_base_frame`: sai phía hoặc mặt phẳng +nghiêng quá 5° thì action fail, không ghi goal. LiDAR lộn ngược được nhận tự động qua TF, không có +khoá flip. Kiểm TF và hướng LiDAR trên robot trước khi vận hành. + +Các offset giữ hệ hình: x từ đỉnh ra phía robot, y sang trái hệ hình. Khi `forward`, robot quay +mặt vào trạm nên `offset_y` dương nằm bên phải robot. Tính khoảng hở `offset_x` theo footprint sau +khi `backward`, footprint trước khi `forward`. + ## Thứ tự làm 1. Xác định dạng trạm: `pattern`, `v_shape`. @@ -248,6 +261,7 @@ Các khoá này nằm ngay dưới action, áp cho mọi profile. | Khoá | Đơn vị | Mặc định | Dùng khi | |---|---|---|---| | `scan_topic` | — | — | Topic `LaserScan` có trong sensor store của nav core. | +| `entry_direction` | — | backward | `backward` lùi vào; `forward` tiến vào, chọn LiDAR cùng phía. | | `line_extraction/max_range` | m | 30.0 | **Giới hạn tầm tìm.** Tia xa hơn bị bỏ trước khi trích đoạn, nên vật ở xa không thành ứng viên. Đặt lớn hơn khoảng cách xa nhất mà robot bấm dò, cộng nửa chiều dài cánh. | | `line_extraction/min_range` | m | 0.05 | Bỏ tia trúng chính thân xe. | | `line_extraction/min_split_dist` | m | 0.04 | Đặt nhỏ hơn bề dày tấm thì hai mặt của một cánh bị tách thành hai đoạn. | diff --git a/plugins/dock_pattern_action_handler.cpp b/plugins/dock_pattern_action_handler.cpp index 4572440..83f09dc 100644 --- a/plugins/dock_pattern_action_handler.cpp +++ b/plugins/dock_pattern_action_handler.cpp @@ -37,6 +37,7 @@ namespace { constexpr double kDefaultSettleDelay = 0.4; // [s] constexpr double kDefaultTimeout = 15.0; // [s] +constexpr double kMaxScanTilt = 0.0873; // [rad] approximately 5 degrees /// Chu kỳ in lý do chưa dò ra. Control loop ~30 Hz; log mỗi cycle sẽ ngập log và làm chậm chính /// vòng điều khiển. 1 Hz đủ để đọc xem đang hỏng ở cổng nào. @@ -46,6 +47,17 @@ double yawOf(const tf3::QuaternionMsg& q) { 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)); } +double upAxisZ(const tf3::QuaternionMsg& q) +{ + return 1.0 - 2.0 * (q.x * q.x + q.y * q.y); +} + +enum class EntryDirection { kForward, kBackward }; + +const char* toString(EntryDirection direction) +{ + return direction == EntryDirection::kForward ? "forward" : "backward"; +} } // namespace /** @@ -122,6 +134,8 @@ public: nh.param("action_types", action_types_, std::vector{}); nh.param("output_frame", output_frame_, std::string()); nh.param("scan_topic", scan_topic_, std::string()); + std::string direction; + nh.param("entry_direction", direction, std::string("backward")); nh.param("settle_delay", settle_delay_, kDefaultSettleDelay); nh.param("timeout", timeout_, kDefaultTimeout); nh.param("default_profile", default_profile_, std::string()); @@ -144,6 +158,21 @@ public: return false; } + if (direction == "forward") + { + entry_direction_ = EntryDirection::kForward; + } + else if (direction == "backward") + { + entry_direction_ = EntryDirection::kBackward; + } + else + { + robot::log_error("[dock_pattern] '%s': entry_direction '%s' is not 'forward' or 'backward'.", + name_.c_str(), direction.c_str()); + return false; + } + // Gõ sai tên topic là lỗi phổ biến nhất, và triệu chứng của nó GIỐNG HỆT cảm biến chết: dò mãi // không ra. Bắt lúc boot và in ra danh sách topic có thật. if (!robot_sensor_ports::has(*ctx_.sensors, scan_topic_)) @@ -172,6 +201,9 @@ public: return false; } + robot::log_info("[dock_pattern] '%s': scan_topic='%s', entry_direction=%s, output_frame='%s'.", + name_.c_str(), scan_topic_.c_str(), toString(entry_direction_), + output_frame_.c_str()); return true; } @@ -191,6 +223,9 @@ public: have_reason_log_ = false; detections_ = 0; tape_reported_ = false; + mount_tf_valid_ = false; + mount_error_.clear(); + scan_flipped_ = false; std::string profile_name = default_profile_; const auto it = std::find_if(action.actionParameters.begin(), action.actionParameters.end(), @@ -263,6 +298,13 @@ public: processNewScan(now); } + if (!mount_error_.empty()) + { + tick.status = ActionStatus::kFailed; + tick.message = "action '" + action_id_ + "': " + mount_error_; + return tick; + } + if (filter_.holdSatisfied(now)) { if (!publish(filter_.holdPose(), now)) @@ -489,6 +531,59 @@ private: // Vòng dò // ============================================================================================== + // The rigid mount is checked once per run (or again if the scan frame changes). + bool ensureMountTransform(const std::string& frame, const robot::Time& now) + { + if (mount_tf_valid_ && mount_tf_frame_ == frame) + { + return true; + } + tf3::TransformStampedMsg tf; + try + { + tf = ctx_.tf->lookupTransform(ctx_.robot_base_frame, frame, tf3::Time()); + } + catch (const std::exception& ex) + { + noteReason(now, "no transform '" + ctx_.robot_base_frame + "' <- '" + frame + + "' yet: " + ex.what()); + return false; + } + + const double up = upAxisZ(tf.transform.rotation); + const double tilt = std::acos(std::min(1.0, std::fabs(up))); // [rad] + const double yaw = yawOf(tf.transform.rotation); // heading of the scan x axis + char buffer[512]; + if (tilt > kMaxScanTilt) + { + std::snprintf(buffer, sizeof(buffer), + "scan plane of '%s' (frame '%s') is tilted %.3f rad from '%s' " + "(limit %.3f); check the lidar mount in the URDF", + scan_topic_.c_str(), frame.c_str(), tilt, ctx_.robot_base_frame.c_str(), + kMaxScanTilt); + mount_error_ = buffer; + } + else if ((std::cos(yaw) > 0.0) != (entry_direction_ == EntryDirection::kForward)) + { + std::snprintf(buffer, sizeof(buffer), + "entry_direction %s but '%s' (frame '%s') faces %s in '%s' " + "(yaw %.2f rad); the goal heading would be reversed", + toString(entry_direction_), scan_topic_.c_str(), frame.c_str(), + std::cos(yaw) > 0.0 ? "forward" : "backward", + ctx_.robot_base_frame.c_str(), yaw); + mount_error_ = buffer; + } + if (!mount_error_.empty()) + { + robot::log_error("[dock_pattern] '%s': %s.", name_.c_str(), mount_error_.c_str()); + return false; + } + scan_flipped_ = up < 0.0; + mount_tf_frame_ = frame; + mount_tf_valid_ = true; + return true; + } + /** * @brief Lấy scan MỚI (nếu có), dò, quy sang global frame, đẩy vào bộ lọc. * @@ -512,9 +607,14 @@ private: return; } + if (!ensureMountTransform(scan->header.frame_id, now)) + { + return; + } + robot_line_extraction::ScanGeometry geometry; - geometry.angle_min = scan->angle_min; - geometry.angle_increment = scan->angle_increment; + geometry.angle_min = scan_flipped_ ? -scan->angle_min : scan->angle_min; + geometry.angle_increment = scan_flipped_ ? -scan->angle_increment : scan->angle_increment; geometry.size = scan->ranges.size(); // `ranges` là float trong message, double trong lõi. Đổi một lần ở đây, dùng lại buffer để @@ -601,6 +701,7 @@ private: return false; } + // Bearings were mirrored into the upright scan view; its x axis has this same yaw. const double base_yaw = yawOf(sensor_to_global.transform.rotation); const double c = std::cos(base_yaw); const double s = std::sin(base_yaw); @@ -608,7 +709,9 @@ private: PoseSample sample; sample.x = sensor_to_global.transform.translation.x + c * pending_.x - s * pending_.y; sample.y = sensor_to_global.transform.translation.y + s * pending_.x + c * pending_.y; - sample.yaw = std::atan2(std::sin(base_yaw + pending_.yaw), std::cos(base_yaw + pending_.yaw)); + const double goal_yaw = base_yaw + pending_.yaw + + (entry_direction_ == EntryDirection::kForward ? M_PI : 0.0); + sample.yaw = std::atan2(std::sin(goal_yaw), std::cos(goal_yaw)); sample.taken_at = now; ++detections_; @@ -704,6 +807,7 @@ private: std::vector action_types_; std::string output_frame_; std::string scan_topic_; + EntryDirection entry_direction_ = EntryDirection::kBackward; double settle_delay_ = kDefaultSettleDelay; double timeout_ = kDefaultTimeout; @@ -733,6 +837,10 @@ private: tf3::Time pending_stamp_; bool pending_valid_ = false; bool tape_reported_ = false; + bool mount_tf_valid_ = false; + bool scan_flipped_ = false; + std::string mount_tf_frame_; + std::string mount_error_; std::string last_reason_; robot::Time last_reason_log_; diff --git a/test/config/action_handlers_params.yaml b/test/config/action_handlers_params.yaml index f0a3276..fa1405b 100644 --- a/test/config/action_handlers_params.yaml +++ b/test/config/action_handlers_params.yaml @@ -10,6 +10,11 @@ actions_dock: action_types: [DetectCharger] output_frame: dock_target scan_topic: /f_scan + # backward: lùi vào, heading goal hướng RA; forward: tiến vào, heading hướng VÀO trạm. + # Đổi hướng phải đổi scan_topic theo phía lidar; TF tự xác định lidar lộn ngược. + # offset_x theo |footprint sau| khi backward, |footprint trước| khi forward; offset_y dương + # sang trái hệ hình, tức bên PHẢI robot khi forward. + entry_direction: backward settle_delay: 0.0 # [s] test tự điều khiển đồng hồ timeout: 5.0 # [s] diff --git a/test/dock_pattern_action_test.cpp b/test/dock_pattern_action_test.cpp index 3d5e548..27443ca 100644 --- a/test/dock_pattern_action_test.cpp +++ b/test/dock_pattern_action_test.cpp @@ -14,6 +14,7 @@ *********************************************************************/ #include +#include #include #include #include @@ -191,7 +192,8 @@ robot_protocol_msgs::Action makeAction(const std::string& profile = std::string( class Rig { public: - explicit Rig(const std::string& ns = "actions_dock") + explicit Rig(const std::string& ns = "actions_dock", + const std::string& direction = "backward", double base_yaw = M_PI) { robot_sensor_ports::SensorStoreConfig store_config; robot_sensor_ports::SensorEntryConfig entry; @@ -208,15 +210,33 @@ public: // kết quả cũng là lệch của phép DÒ, không phải của phép quy đổi. setSensorPose(0.0, 0.0, 0.0, 0.0); + // Keep the historic map <- scan test geometry and place the robot base so that the + // same lidar is rear-facing by default. This also leaves scan-time TF independent. + tf3::TransformStampedMsg base; + base.header.frame_id = kGlobalFrame; + base.child_frame_id = "base_link"; + base.transform.rotation.z = std::sin(base_yaw / 2.0); + base.transform.rotation.w = std::cos(base_yaw / 2.0); + tf.setTransform(base, "test", /*is_static=*/true); + ctx.tf = &tf; ctx.sensors = &store; ctx.global_frame = kGlobalFrame; registry.setContext(ctx); + if (ns == "actions_dock") + { + nh.setParam("actions_dock/detect/entry_direction", direction); + } loaded = registry.loadFromConfig(nh, ns); + if (ns == "actions_dock") + { + nh.setParam("actions_dock/detect/entry_direction", std::string("backward")); + } handler = registry.find("DetectCharger"); } - void setSensorPose(double x, double y, double yaw, double stamp_s) + void setSensorPose(double x, double y, double yaw, double stamp_s, + double roll = 0.0, double pitch = 0.0) { tf3::TransformStampedMsg t; t.header.stamp = toTf3Time(stamp_s); @@ -225,10 +245,13 @@ public: t.transform.translation.x = x; t.transform.translation.y = y; t.transform.translation.z = 0.0; - t.transform.rotation.x = 0.0; - t.transform.rotation.y = 0.0; - t.transform.rotation.z = std::sin(yaw * 0.5); - t.transform.rotation.w = std::cos(yaw * 0.5); + const double cr = std::cos(roll * 0.5), sr = std::sin(roll * 0.5); + const double cp = std::cos(pitch * 0.5), sp = std::sin(pitch * 0.5); + const double cy = std::cos(yaw * 0.5), sy = std::sin(yaw * 0.5); + t.transform.rotation.x = sr * cp * cy - cr * sp * sy; + t.transform.rotation.y = cr * sp * cy + sr * cp * sy; + t.transform.rotation.z = cr * cp * sy - sr * sp * cy; + t.transform.rotation.w = cr * cp * cy + sr * sp * sy; tf.setTransform(t, "test", /*is_static=*/false); } @@ -295,6 +318,48 @@ public: ActionHandler* handler = nullptr; }; +double yawOf(const tf3::QuaternionMsg& q) +{ + 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)); +} + +double angleDistance(double a, double b) +{ + return std::fabs(std::atan2(std::sin(a - b), std::cos(a - b))); +} + +// A mirrored physical scan keeps the original ray indices and mirrors their bearings; +// reverse both arrays to synthesize the same asymmetric scene with a roll-pi sensor. +ActionStatus feedMounted(Rig& rig, const std::vector& scene, + const std::vector& tapes, double roll, double pitch = 0.0, + double yaw = 0.0) +{ + ActionStatus status = ActionStatus::kRunning; + for (int i = 0; i < 8 && status == ActionStatus::kRunning; ++i) + { + const double t = 10.0 + 0.1 * i; + rig.setSensorPose(0.0, 0.0, yaw, t, roll, pitch); + auto scan = makeScan(scene, t, 600, tapes); + if (std::fabs(roll) > 1.0) + { + std::reverse(scan.ranges.begin(), scan.ranges.end()); + std::reverse(scan.intensities.begin(), scan.intensities.end()); + } + robot_sensor_ports::put(rig.store, kScanTopic, scan, robot::Time(t)); + const auto tick = rig.handler->update(robot::Time(t)); + status = tick.status; + rig.last_message = tick.message; + } + return status; +} + +void expectSameGoal(const tf3::TransformStampedMsg& a, const tf3::TransformStampedMsg& b) +{ + EXPECT_NEAR(a.transform.translation.x, b.transform.translation.x, 0.001); + EXPECT_NEAR(a.transform.translation.y, b.transform.translation.y, 0.001); + EXPECT_LT(angleDistance(yawOf(a.transform.rotation), yawOf(b.transform.rotation)), 0.001); +} + // ================================================================================================ // 1. Đường chạy đủ // ================================================================================================ @@ -620,6 +685,80 @@ TEST(DockPatternAction, RefusesToLoadWithoutASensorStore) EXPECT_EQ(registry.find("DetectCharger"), nullptr); } +TEST(DockPatternAction, ForwardAndBackwardUseSamePositionAndOppositeHeadings) +{ + Rig rear; + Rig front("actions_dock", "forward", 0.0); + ASSERT_TRUE(rear.loaded); + ASSERT_TRUE(front.loaded); + ASSERT_TRUE(rear.handler->start(makeAction(), robot::Time(10.0))); + ASSERT_TRUE(front.handler->start(makeAction(), robot::Time(10.0))); + const auto scene = vPlate(1.20, M_PI / 4.0, 0.30); + ASSERT_EQ(feedMounted(rear, scene, {}, 0.0), ActionStatus::kSucceeded) << rear.last_message; + ASSERT_EQ(feedMounted(front, scene, {}, 0.0), ActionStatus::kSucceeded) << front.last_message; + const auto a = rear.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time()); + const auto b = front.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time()); + EXPECT_NEAR(a.transform.translation.x, b.transform.translation.x, 0.001); + EXPECT_NEAR(a.transform.translation.y, b.transform.translation.y, 0.001); + EXPECT_NEAR(angleDistance(yawOf(a.transform.rotation), yawOf(b.transform.rotation)), M_PI, 0.001); +} + +TEST(DockPatternAction, DirectionMismatchFailsWithoutGoal) +{ + Rig rig("actions_dock", "backward", 0.0); + ASSERT_TRUE(rig.loaded); + ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(10.0))); + EXPECT_EQ(feedMounted(rig, vPlate(1.2, M_PI / 4.0, 0.30), {}, 0.0), ActionStatus::kFailed); + EXPECT_NE(rig.last_message.find("entry_direction backward"), std::string::npos); + EXPECT_NE(rig.last_message.find("faces forward"), std::string::npos); + EXPECT_ANY_THROW(rig.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time())); +} + +TEST(DockPatternAction, UpsideDownScanMatchesUprightForVArcAndTape) +{ + for (const std::string profile : {"v_std", "v_tape", "cradle"}) + { + SCOPED_TRACE(profile); + Rig upright; + Rig flipped; + ASSERT_TRUE(upright.loaded); + ASSERT_TRUE(flipped.loaded); + ASSERT_TRUE(upright.handler->start(makeAction(profile), robot::Time(10.0))); + ASSERT_TRUE(flipped.handler->start(makeAction(profile), robot::Time(10.0))); + auto scene = profile == "cradle" ? concaveCradle(1.20, 0.40, 2.0) + : vPlate(1.20, M_PI / 4.0, 0.30); + auto tapes = profile == "v_tape" ? vPlateTapes(1.20, M_PI / 4.0, 0.30, 0.12) + : std::vector{}; + // Shift the scene sideways so a missing reflection cannot pass by symmetry. + for (auto& s : scene) { s.ay += 0.08; s.by += 0.08; } + for (auto& s : tapes) { s.ay += 0.08; s.by += 0.08; } + ASSERT_EQ(feedMounted(upright, scene, tapes, 0.0, 0.0, 0.4), ActionStatus::kSucceeded) + << upright.last_message; + ASSERT_EQ(feedMounted(flipped, scene, tapes, M_PI, 0.0, 0.4), ActionStatus::kSucceeded) + << flipped.last_message; + expectSameGoal(upright.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time()), + flipped.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time())); + } +} + +TEST(DockPatternAction, TiltedScanPlaneFailsWithoutGoal) +{ + Rig rig; + ASSERT_TRUE(rig.loaded); + ASSERT_TRUE(rig.handler->start(makeAction(), robot::Time(10.0))); + EXPECT_EQ(feedMounted(rig, vPlate(1.2, M_PI / 4.0, 0.30), {}, 0.0, 0.11), + ActionStatus::kFailed); + EXPECT_NE(rig.last_message.find("tilted"), std::string::npos); + EXPECT_ANY_THROW(rig.tf.lookupTransform(kGlobalFrame, kOutFrame, tf3::Time())); +} + +TEST(DockPatternAction, RefusesInvalidEntryDirection) +{ + Rig rig("actions_dock", "sideways"); + EXPECT_FALSE(rig.loaded); + EXPECT_EQ(rig.handler, nullptr); +} + } // namespace int main(int argc, char** argv)