diff --git a/src/field_localization/include/field_localization/core/localization_core.hpp b/src/field_localization/include/field_localization/core/localization_core.hpp new file mode 100644 index 0000000..098e2cb --- /dev/null +++ b/src/field_localization/include/field_localization/core/localization_core.hpp @@ -0,0 +1,55 @@ +#pragma once + +#include "field_localization/core/types.hpp" + +#include +#include + +namespace field_localization::core { + +struct LocalizationStatus { + bool has_imu{false}; + bool has_point_cloud{false}; + + double last_imu_timestamp{0.0}; + double last_point_cloud_timestamp{0.0}; + + std::size_t imu_count{0}; + std::size_t point_cloud_count{0}; + + std::size_t rejected_imu_count{0}; + std::size_t rejected_point_cloud_count{0}; + + std::size_t last_point_count{0}; +}; + +class LocalizationCore { +public: + LocalizationCore() = default; + + // 接收 IMU 数据 + bool process_imu(const ImuData &imu); + + // 接收点云数据 + bool process_point_cloud(const PointCloud &cloud); + + // 获取当前位姿 + [[nodiscard]] Pose3D get_pose() const; + + // 设置位姿(用于初始化和后续算法集成) + void set_pose(const Pose3D &pose); + + // 获取核心状态 + [[nodiscard]] LocalizationStatus get_status() const; + + // 重置定位状态 + void reset(); + +private: + mutable std::mutex mutex_; + + Pose3D pose_{}; + LocalizationStatus status_{}; +}; + +} // namespace field_localization::core \ No newline at end of file diff --git a/src/field_localization/include/field_localization/core/types.hpp b/src/field_localization/include/field_localization/core/types.hpp new file mode 100644 index 0000000..33f0fe4 --- /dev/null +++ b/src/field_localization/include/field_localization/core/types.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace field_localization::core { + +struct ImuData { + double timestamp_sec{0.0}; + std::string frame_id; + + Eigen::Vector3d angular_velocity{Eigen::Vector3d::Zero()}; + + Eigen::Vector3d linear_acceleration{Eigen::Vector3d::Zero()}; +}; + +struct PointXYZI { + double timestamp_sec{0.0}; + + Eigen::Vector3f position{Eigen::Vector3f::Zero()}; + + float intensity{0.0F}; +}; + +struct PointCloud { + double timestamp_sec{0.0}; + std::string frame_id; + + std::vector points; +}; + +struct Pose3D { + Eigen::Quaterniond rotation{Eigen::Quaterniond::Identity()}; + + Eigen::Vector3d translation{Eigen::Vector3d::Zero()}; +}; + +} // namespace field_localization::core \ No newline at end of file diff --git a/src/field_localization/include/field_localization/ros/localization_node.hpp b/src/field_localization/include/field_localization/ros/localization_node.hpp new file mode 100644 index 0000000..265f37c --- /dev/null +++ b/src/field_localization/include/field_localization/ros/localization_node.hpp @@ -0,0 +1,42 @@ +#pragma once + +#include "field_localization/core/localization_core.hpp" +#include "field_localization/core/types.hpp" + +#include +#include +#include + +#include +#include +#include + +namespace field_localization::ros { + +class LocalizationNode : public rclcpp::Node { +public: + explicit LocalizationNode( + const rclcpp::NodeOptions &options = rclcpp::NodeOptions()); + +private: + void on_point_cloud(sensor_msgs::msg::PointCloud2::ConstSharedPtr msg); + + void on_imu(sensor_msgs::msg::Imu::ConstSharedPtr msg); + + void print_localization_status(); + + rclcpp::TimerBase::SharedPtr status_timer_; + rclcpp::Subscription::SharedPtr + point_cloud_sub_; + + rclcpp::Subscription::SharedPtr imu_sub_; + + std::string point_cloud_topic_; + std::string imu_topic_; + core::LocalizationCore core_; + + std::size_t point_cloud_count_{0}; + std::size_t imu_count_{0}; +}; + +} // namespace field_localization::ros diff --git a/src/field_localization/src/core/localization_core.cpp b/src/field_localization/src/core/localization_core.cpp new file mode 100644 index 0000000..c3d88a3 --- /dev/null +++ b/src/field_localization/src/core/localization_core.cpp @@ -0,0 +1,102 @@ +#include "field_localization/core/localization_core.hpp" + +#include +#include + +namespace field_localization::core { + +bool LocalizationCore::process_imu(const ImuData &imu) { + std::lock_guard lock(mutex_); + + // 时间戳必须有效 + if (!std::isfinite(imu.timestamp_sec) || imu.timestamp_sec < 0.0) { + ++status_.rejected_imu_count; + return false; + } + + // 检查 IMU 数据是否包含 NaN 或 Inf + if (!imu.angular_velocity.allFinite() || + !imu.linear_acceleration.allFinite()) { + ++status_.rejected_imu_count; + return false; + } + + // 拒绝乱序或重复数据 + if (status_.has_imu && imu.timestamp_sec <= status_.last_imu_timestamp) { + ++status_.rejected_imu_count; + return false; + } + + status_.has_imu = true; + status_.last_imu_timestamp = imu.timestamp_sec; + ++status_.imu_count; + + return true; +} + +bool LocalizationCore::process_point_cloud(const PointCloud &cloud) { + std::lock_guard lock(mutex_); + + if (!std::isfinite(cloud.timestamp_sec) || cloud.timestamp_sec < 0.0) { + ++status_.rejected_point_cloud_count; + return false; + } + + // 拒绝乱序或重复点云 + if (status_.has_point_cloud && + cloud.timestamp_sec <= status_.last_point_cloud_timestamp) { + ++status_.rejected_point_cloud_count; + return false; + } + + // 统计有效点数量 + const auto valid_point_count = std::count_if( + cloud.points.begin(), cloud.points.end(), [](const PointXYZI &point) { + return point.position.allFinite() && std::isfinite(point.intensity) && + std::isfinite(point.timestamp_sec); + }); + + if (valid_point_count == 0) { + ++status_.rejected_point_cloud_count; + return false; + } + + status_.has_point_cloud = true; + status_.last_point_cloud_timestamp = cloud.timestamp_sec; + status_.last_point_count = static_cast(valid_point_count); + + ++status_.point_cloud_count; + + return true; +} + +Pose3D LocalizationCore::get_pose() const { + std::lock_guard lock(mutex_); + return pose_; +} + +void LocalizationCore::set_pose(const Pose3D &pose) { + if (!pose.translation.allFinite() || !pose.rotation.coeffs().allFinite() || + pose.rotation.norm() < 1e-12) { + return; + } + + std::lock_guard lock(mutex_); + + pose_ = pose; + pose_.rotation.normalize(); +} + +LocalizationStatus LocalizationCore::get_status() const { + std::lock_guard lock(mutex_); + return status_; +} + +void LocalizationCore::reset() { + std::lock_guard lock(mutex_); + + pose_ = Pose3D{}; + status_ = LocalizationStatus{}; +} + +} // namespace field_localization::core \ No newline at end of file diff --git a/src/field_localization/src/ros/localization_node.cpp b/src/field_localization/src/ros/localization_node.cpp new file mode 100644 index 0000000..14aa9fe --- /dev/null +++ b/src/field_localization/src/ros/localization_node.cpp @@ -0,0 +1,234 @@ +#include "field_localization/ros/localization_node.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +const sensor_msgs::msg::PointField * +find_field(const sensor_msgs::msg::PointCloud2 &cloud, + const std::string &name) { + const auto it = + std::find_if(cloud.fields.begin(), cloud.fields.end(), + [&name](const auto &field) { return field.name == name; }); + + return it != cloud.fields.end() ? &(*it) : nullptr; +} + +bool is_float32_field(const sensor_msgs::msg::PointField *field, + std::uint32_t point_step) { + if (field == nullptr) { + return false; + } + + return field->datatype == sensor_msgs::msg::PointField::FLOAT32 && + field->count >= 1 && + static_cast(field->offset) + sizeof(float) <= point_step; +} + +} // namespace + +namespace field_localization::ros { +LocalizationNode::LocalizationNode(const rclcpp::NodeOptions &options) + : Node("field_localization", options) { + point_cloud_topic_ = + declare_parameter("point_cloud_topic", "/livox/lidar"); + + imu_topic_ = declare_parameter("imu_topic", "/livox/imu"); + + // Subscribe to LiDAR point clouds. + point_cloud_sub_ = create_subscription( + point_cloud_topic_, rclcpp::SensorDataQoS(), + std::bind(&LocalizationNode::on_point_cloud, this, + std::placeholders::_1)); + + // Subscribe to IMU measurements. + imu_sub_ = create_subscription( + imu_topic_, rclcpp::SensorDataQoS(), + std::bind(&LocalizationNode::on_imu, this, std::placeholders::_1)); + + RCLCPP_INFO(get_logger(), "Field localization node started."); + + RCLCPP_INFO(get_logger(), "Point cloud topic: %s", + point_cloud_topic_.c_str()); + + RCLCPP_INFO(get_logger(), "IMU topic: %s", imu_topic_.c_str()); + + status_timer_ = create_wall_timer( + std::chrono::seconds(5), + std::bind(&LocalizationNode::print_localization_status, this)); +} + +void LocalizationNode::on_point_cloud( + sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) { + core::PointCloud cloud; + + cloud.timestamp_sec = rclcpp::Time(msg->header.stamp).seconds(); + + cloud.frame_id = msg->header.frame_id; + + // 查找点云字段 + const auto *field_x = find_field(*msg, "x"); + const auto *field_y = find_field(*msg, "y"); + const auto *field_z = find_field(*msg, "z"); + const auto *field_intensity = find_field(*msg, "intensity"); + + // 检查 XYZ 字段 + if (!is_float32_field(field_x, msg->point_step) || + !is_float32_field(field_y, msg->point_step) || + !is_float32_field(field_z, msg->point_step)) { + RCLCPP_ERROR(get_logger(), "PointCloud2 requires FLOAT32 x/y/z fields."); + return; + } + + // 检查 intensity 字段 + if (field_intensity != nullptr && + !is_float32_field(field_intensity, msg->point_step)) { + RCLCPP_WARN(get_logger(), + "Unsupported intensity datatype. Intensity will be ignored."); + field_intensity = nullptr; + } + + // 检查点云内存布局 + const std::size_t minimum_row_size = + static_cast(msg->width) * msg->point_step; + + const std::size_t required_data_size = + static_cast(msg->row_step) * msg->height; + + if (msg->point_step == 0 || msg->row_step < minimum_row_size || + msg->data.size() < required_data_size) { + RCLCPP_ERROR(get_logger(), "Invalid PointCloud2 memory layout."); + return; + } + + const bool has_intensity = field_intensity != nullptr; + + cloud.points.reserve(static_cast(msg->width) * msg->height); + + try { + sensor_msgs::PointCloud2ConstIterator iter_x(*msg, "x"); + sensor_msgs::PointCloud2ConstIterator iter_y(*msg, "y"); + sensor_msgs::PointCloud2ConstIterator iter_z(*msg, "z"); + + if (has_intensity) { + sensor_msgs::PointCloud2ConstIterator iter_intensity(*msg, + "intensity"); + + for (; iter_x != iter_x.end(); + ++iter_x, ++iter_y, ++iter_z, ++iter_intensity) { + core::PointXYZI point; + + point.position.x() = *iter_x; + point.position.y() = *iter_y; + point.position.z() = *iter_z; + point.intensity = *iter_intensity; + + point.timestamp_sec = cloud.timestamp_sec; + + if (!point.position.allFinite() || !std::isfinite(point.intensity)) { + continue; + } + + cloud.points.push_back(std::move(point)); + } + } else { + for (; iter_x != iter_x.end(); ++iter_x, ++iter_y, ++iter_z) { + core::PointXYZI point; + + point.position.x() = *iter_x; + point.position.y() = *iter_y; + point.position.z() = *iter_z; + + point.timestamp_sec = cloud.timestamp_sec; + + if (!point.position.allFinite() || !std::isfinite(point.intensity)) { + continue; + } + + cloud.points.push_back(std::move(point)); + } + } + } catch (const std::runtime_error &error) { + RCLCPP_ERROR(get_logger(), "Failed to convert PointCloud2: %s", + error.what()); + return; + } + + if (cloud.points.empty()) { + RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 5000, + "Received an empty or invalid point cloud."); + return; + } + + ++point_cloud_count_; + + if (!core_.process_point_cloud(cloud)) { + RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 5000, + "Rejected point cloud"); + return; + } + + RCLCPP_INFO_THROTTLE( + get_logger(), *get_clock(), 5000, + "Received %zu point clouds, latest cloud contains %zu points.", + point_cloud_count_, cloud.points.size()); +} + +void LocalizationNode::on_imu(sensor_msgs::msg::Imu::ConstSharedPtr msg) { + core::ImuData imu; + + imu.timestamp_sec = rclcpp::Time(msg->header.stamp).seconds(); + + imu.frame_id = msg->header.frame_id; + + imu.angular_velocity = + Eigen::Vector3d{msg->angular_velocity.x, msg->angular_velocity.y, + msg->angular_velocity.z}; + + imu.linear_acceleration = + Eigen::Vector3d{msg->linear_acceleration.x, msg->linear_acceleration.y, + msg->linear_acceleration.z}; + + ++imu_count_; + + if (!core_.process_imu(imu)) { + RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 5000, + "Rejected IMU message"); + return; + } + + RCLCPP_INFO_THROTTLE(get_logger(), *get_clock(), 5000, + "Received %zu IMU messages. " + "Gyro: [%.3f, %.3f, %.3f] rad/s", + imu_count_, imu.angular_velocity.x(), + imu.angular_velocity.y(), imu.angular_velocity.z()); +} + +void LocalizationNode::print_localization_status() { + const auto status = core_.get_status(); + + RCLCPP_INFO(get_logger(), "========== Localization Status =========="); + + RCLCPP_INFO( + get_logger(), "IMU: received=%zu, rejected=%zu, last_timestamp=%.6f", + status.imu_count, status.rejected_imu_count, status.last_imu_timestamp); + + RCLCPP_INFO(get_logger(), + "PointCloud: received=%zu, rejected=%zu, last_timestamp=%.6f", + status.point_cloud_count, status.rejected_point_cloud_count, + status.last_point_cloud_timestamp); + + RCLCPP_INFO(get_logger(), "Latest valid point count: %zu", + status.last_point_count); + + RCLCPP_INFO(get_logger(), "=========================================="); +} + +} // namespace field_localization::ros diff --git a/src/field_localization/src/ros/main.cpp b/src/field_localization/src/ros/main.cpp new file mode 100644 index 0000000..4800ff5 --- /dev/null +++ b/src/field_localization/src/ros/main.cpp @@ -0,0 +1,24 @@ +#include "field_localization/ros/localization_node.hpp" + +#include + +#include + +int main(int argc, char **argv) { + rclcpp::init(argc, argv); + + try { + auto node = std::make_shared(); + + rclcpp::spin(node); + } catch (const std::exception &error) { + RCLCPP_ERROR(rclcpp::get_logger("field_localization"), + "Node terminated with exception: %s", error.what()); + + rclcpp::shutdown(); + return 1; + } + + rclcpp::shutdown(); + return 0; +} diff --git a/src/field_localization/tests/test_localization_core.cpp b/src/field_localization/tests/test_localization_core.cpp new file mode 100644 index 0000000..a31f45d --- /dev/null +++ b/src/field_localization/tests/test_localization_core.cpp @@ -0,0 +1,82 @@ +#include "field_localization/core/localization_core.hpp" + +#include +#include + +using namespace field_localization::core; + +int main() { + LocalizationCore core; + + // 1. 检查默认位姿 + Pose3D pose = core.get_pose(); + + assert(pose.translation.isZero()); + assert(pose.rotation.isApprox( + Eigen::Quaterniond::Identity() + )); + + // 2. 设置位姿 + Pose3D new_pose; + new_pose.translation = Eigen::Vector3d{1.0, 2.0, 3.0}; + new_pose.rotation = Eigen::Quaterniond{ + Eigen::AngleAxisd( + 0.5, + Eigen::Vector3d::UnitZ() + ) + }; + + core.set_pose(new_pose); + + pose = core.get_pose(); + + assert(pose.translation.isApprox(new_pose.translation)); + assert(pose.rotation.isApprox(new_pose.rotation)); + + // 3. 输入 IMU 数据 + ImuData imu; + imu.timestamp_sec = 1.0; + imu.angular_velocity = Eigen::Vector3d{0.1, 0.2, 0.3}; + imu.linear_acceleration = Eigen::Vector3d{0.0, 0.0, 9.81}; + + assert(core.process_imu(imu)); + + // 4. 输入点云数据 + PointCloud cloud; + cloud.timestamp_sec = 1.0; + + PointXYZI point; + point.timestamp_sec = 1.0; + point.position = Eigen::Vector3f{1.0F, 2.0F, 3.0F}; + point.intensity = 100.0F; + + cloud.points.push_back(point); + + assert(core.process_point_cloud(cloud)); + + // 5. 检查状态 + const LocalizationStatus status = core.get_status(); + + assert(status.has_imu); + assert(status.has_point_cloud); + assert(status.imu_count == 1); + assert(status.point_cloud_count == 1); + assert(status.last_point_count == 1); + + // 6. 检查乱序 IMU 是否被拒绝 + assert(!core.process_imu(imu)); + + // 7. 检查重置 + core.reset(); + + const auto reset_status = core.get_status(); + assert(!reset_status.has_imu); + assert(!reset_status.has_point_cloud); + assert(reset_status.imu_count == 0); + assert(reset_status.point_cloud_count == 0); + + pose = core.get_pose(); + assert(pose.translation.isZero()); + + return 0; +} diff --git a/src/field_localization/xmake.lua b/src/field_localization/xmake.lua new file mode 100644 index 0000000..541ab57 --- /dev/null +++ b/src/field_localization/xmake.lua @@ -0,0 +1,285 @@ +-- ============================================================================ +-- Field Localization +-- ============================================================================ + +-- ============================================================================ +-- ROS 2 dependency configuration +-- ============================================================================ + +local ros_direct_packages = { + "rclcpp", + "sensor_msgs", + "nav_msgs", + "geometry_msgs", + "tf2_ros", +} + +local message_packages = { + "sensor_msgs", + "nav_msgs", + "geometry_msgs", + "std_msgs", + "tf2_msgs", + "builtin_interfaces", +} + +local ros_config_cache = nil + +local function ros_common() + + on_load(function(target) + + local function get_ros_config() + + if ros_config_cache then + return ros_config_cache + end + + -- Discover ROS installation. + local ROS = os.getenv("ROS_PREFIX") + + if ROS and ROS ~= "" then + + if not os.isdir(ROS .. "/include") + or not os.isdir(ROS .. "/lib") then + raise("Invalid ROS_PREFIX: " .. ROS) + end + + else + + local ament_prefix_path = os.getenv("AMENT_PREFIX_PATH") + ROS = nil + + if ament_prefix_path then + for prefix in string.gmatch( + ament_prefix_path, + "[^:]+" + ) do + + if os.isdir(prefix .. "/include") + and os.isdir(prefix .. "/lib") then + ROS = prefix + break + end + end + end + + if not ROS then + raise( + "ROS installation not found. " + .. "Source ROS setup or set ROS_PREFIX." + ) + end + end + + -- Resolve ROS include directories. + local script = path.join( + target:scriptdir(), + "../../tools/resolve_ros_includes.py" + ) + + if not os.isfile(script) then + raise("ROS include resolver not found: " .. script) + end + + local output_file = path.join( + os.tmpdir(), + "field_localization_ros_include_dirs.txt" + ) + + local error_file = path.join( + os.tmpdir(), + "field_localization_ros_include_errors.txt" + ) + + os.tryrm(output_file) + os.tryrm(error_file) + + os.execv("python3", { + script, + "--prefix", ROS, + "--roots", table.concat(ros_direct_packages, ","), + }, { + stdout = output_file, + stderr = error_file, + }) + + local file = io.open(output_file, "r") + + if not file then + + local error_message = "" + + local error_handle = io.open(error_file, "r") + if error_handle then + error_message = error_handle:read("*a") + error_handle:close() + end + + raise( + "Failed to resolve ROS includes:\n" + .. error_message + ) + end + + local output = file:read("*a") + file:close() + + if output == "" then + raise("ROS dependency resolver returned empty output.") + end + + -- Collect and deduplicate include directories. + local project_include = path.join( + target:scriptdir(), + "include" + ) + + local includes = {project_include} + local include_seen = { + [project_include] = true + } + + for line in output:gmatch("[^\r\n]+") do + + line = line:gsub("^%s+", "") + line = line:gsub("%s+$", "") + + if line ~= "" and not include_seen[line] then + table.insert(includes, line) + include_seen[line] = true + end + end + + -- Collect message typesupport libraries. + local libs = {} + + for _, pkg in ipairs(message_packages) do + + for _, suffix in ipairs({ + "__rosidl_typesupport_cpp", + "__rosidl_typesupport_introspection_cpp", + }) do + + local name = pkg .. suffix + + if os.isfile(ROS .. "/lib/lib" .. name .. ".so") then + table.insert(libs, name) + end + end + end + + -- ROS runtime libraries. + local runtime_libraries = { + "rclcpp", + "rcl", + "rcl_action", + "tf2", + "tf2_ros", + "rosidl_typesupport_cpp", + "rosidl_typesupport_c", + "rosidl_runtime_c", + "rmw", + "rmw_implementation", + "rmw_dds_common", + "rcutils", + "rcpputils", + "tracetools", + "rcl_logging_interface", + "rcl_yaml_param_parser", + "libstatistics_collector", + } + + for _, name in ipairs(runtime_libraries) do + + if os.isfile(ROS .. "/lib/lib" .. name .. ".so") then + table.insert(libs, name) + end + end + + ros_config_cache = { + prefix = ROS, + includes = includes, + libs = libs, + } + + return ros_config_cache + end + + local config = get_ros_config() + + target:add("includedirs", config.includes) + + target:add( + "defines", + "DEFAULT_RMW_IMPLEMENTATION=rmw_fastrtps_cpp" + ) + + target:add("linkdirs", config.prefix .. "/lib") + target:add("rpathdirs", config.prefix .. "/lib") + + target:add( + "linkgroups", + config.libs, + {group = true} + ) + + end) +end + + +-- ============================================================================ +-- Core library: independent of ROS 2 +-- ============================================================================ + +target("field_localization_core") + set_kind("static") + set_languages("c++23") + + add_files("src/core/*.cpp") + + add_includedirs("include", {public = true}) + add_sysincludedirs("/usr/include/eigen3", {public = true}) + + +-- ============================================================================ +-- Core unit tests +-- ============================================================================ + +target("test_localization_core") + set_kind("binary") + set_languages("c++23") + + add_files("tests/test_localization_core.cpp") + add_deps("field_localization_core") + + add_tests("default", {group = "unit"}) + + +-- ============================================================================ +-- ROS adapter library +-- ============================================================================ + +target("field_localization_ros") + set_kind("shared") + set_languages("c++23") + + add_files("src/ros/localization_node.cpp") + + add_deps("field_localization_core") + + ros_common() + + +-- ============================================================================ +-- ROS 2 executable +-- ============================================================================ + +target("field_localization_node") + set_kind("binary") + set_languages("c++23") + + add_files("src/ros/main.cpp") + + add_deps("field_localization_ros") + ros_common() diff --git a/src/sentry_sim/scripts/sentry_up.sh b/src/sentry_sim/scripts/sentry_up.sh index a8eb9b1..b2d7313 100755 --- a/src/sentry_sim/scripts/sentry_up.sh +++ b/src/sentry_sim/scripts/sentry_up.sh @@ -40,7 +40,7 @@ NAV_BIN_DIR="${NAV_BIN_DIR:-${WS}/build/linux/x86_64/release}" # 想回退共享内存:FASTDDS_BUILTIN_TRANSPORTS=SHM scripts/sentry_up.sh export FASTDDS_BUILTIN_TRANSPORTS="${FASTDDS_BUILTIN_TRANSPORTS:-UDPv4}" -source /opt/ros/lyrical/setup.bash +#source /opt/ros/lyrical/setup.bash # 本工程不使用 ament / colcon,节点是 xmake 直接编出的二进制, # 没有资源索引,所以不能 `ros2 run`,只能直接跑路径。 @@ -120,21 +120,63 @@ cleanup() { } trap cleanup EXIT INT TERM -# ---------- 1. Gazebo(系统版,清掉 ROS vendor 的库路径)---------- -GZ_ARGS=(-r --force-version 10) -[ "$HEADLESS" = "1" ] && GZ_ARGS=(-s --force-version 10 -r) -echo "[sentry_up] 启动 Gazebo: ${WORLD}" -env -u LD_LIBRARY_PATH /usr/bin/gz sim "${GZ_ARGS[@]}" "${WORLD}" & -PIDS+=($!) +# ---------- 1. Gazebo ---------- +GZ_BIN="$(command -v gz || true)" + +if [[ -z "$GZ_BIN" ]]; then + echo "[sentry_up] 错误:找不到 Gazebo 命令 gz" >&2 + exit 1 +fi + +GZ_ARGS=(-r) + +if [[ "$HEADLESS" == "1" ]]; then + GZ_ARGS=(-s -r) +fi + +echo "[sentry_up] Gazebo 命令:$GZ_BIN" +echo "[sentry_up] 启动 Gazebo:$WORLD" + +# 不强制指定 Gazebo 版本,让系统使用已安装的默认版本。 +env -u LD_LIBRARY_PATH "$GZ_BIN" sim \ + "${GZ_ARGS[@]}" "$WORLD" & + +GZ_PID=$! +PIDS+=("$GZ_PID") + +# ---------- 2. 等 Gazebo 就绪 ---------- +echo -n "[sentry_up] 等待 Gazebo 就绪" + +GZ_READY=0 -# ---------- 2. 等 Gazebo 就绪(/clock 出现)---------- -echo -n "[sentry_up] 等 Gazebo 就绪" for _ in $(seq 1 120); do - if gz topic -l 2>/dev/null | grep -qx '/clock'; then break; fi - echo -n "." - sleep 1 + + # Gazebo 进程提前退出,立即报告错误。 + if ! kill -0 "$GZ_PID" 2>/dev/null; then + echo + echo "[sentry_up] 错误:Gazebo 启动失败,进程已退出" >&2 + wait "$GZ_PID" || true + exit 1 + fi + + if env -u LD_LIBRARY_PATH "$GZ_BIN" topic -l 2>/dev/null \ + | grep -qx '/clock'; then + GZ_READY=1 + break + fi + + echo -n "." + sleep 1 done -echo " OK" + +echo + +if [[ "$GZ_READY" != "1" ]]; then + echo "[sentry_up] 错误:等待 Gazebo 超时,未发现 /clock" >&2 + exit 1 +fi + +echo "[sentry_up] Gazebo 已就绪" # ---------- 3. ros_gz 桥 ---------- echo "[sentry_up] 启动 ros_gz 桥" diff --git a/tools/audit_absolute_paths.py b/tools/audit_absolute_paths.py new file mode 100755 index 0000000..5bac27a --- /dev/null +++ b/tools/audit_absolute_paths.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 + +from pathlib import Path +from collections import defaultdict +import argparse +import re + +ROOT = Path(__file__).resolve().parent.parent + +EXCLUDED_DIRS = { + ".git", + ".xmake", + "build", + "install", + "log", + "__pycache__", + ".cache", +} + +EXCLUDED_FILES = { + "compile_commands.json", + "CMakeCache.txt", +} + +# 匹配 Linux 绝对路径,避免匹配 URL 中的 // +PATH_PATTERN = re.compile( + r'(? 140: + excerpt = excerpt[:137] + "..." + + findings.append({ + "file": str(relative), + "line": line_no, + "path": path, + "category": category, + "excerpt": excerpt, + }) + + print("=" * 72) + print("仓库绝对路径审计报告") + print("=" * 72) + print(f"仓库:{ROOT}") + print(f"扫描文件数:{file_count}") + print(f"发现路径数:{len(findings)}") + print() + + print("[分类统计]") + for category, count in sorted(category_counts.items()): + print(f" {category:<18} {count:>5}") + print() + + limit = len(findings) if args.all else max(0, args.max_lines) + shown = findings[:limit] + + current_file = None + + for item in shown: + if item["file"] != current_file: + current_file = item["file"] + print(f"\n[{current_file}]") + + print( + f" L{item['line']:<5} " + f"[{item['category']}] {item['path']}" + ) + print(f" {item['excerpt']}") + + remaining = len(findings) - len(shown) + + print("\n" + "=" * 72) + print(f"已显示:{len(shown)} / {len(findings)}") + + if remaining: + print(f"其余隐藏:{remaining} 条") + print("需要完整报告时执行:python3 tools/audit_absolute_paths.py --all") + + print("=" * 72) + + +if __name__ == "__main__": + main() diff --git a/xmake.lua b/xmake.lua index de48d32..35bd8de 100644 --- a/xmake.lua +++ b/xmake.lua @@ -36,3 +36,4 @@ add_rules("plugin.compile_commands.autoupdate", { outputdir = ".", lsp = "clangd -- 真正的目标都在子目录里(与源码放在一起,加文件时不用来回跳)。 includes("src/sentry_nav") +includes("src/field_localization")