From c60173d320c81a6e9a5f7ffd3b89002e0be7ec73 Mon Sep 17 00:00:00 2001 From: duongtd Date: Wed, 26 Aug 2026 11:37:28 +0700 Subject: [PATCH] One place raw sensor readings live, shared by everything that needs them Sensor data entered the navigation runtime and disappeared into the costmap. At 0.05 m with inflation the costmap has destroyed ray order and object shape, so a dock detector fitting lines to find a V plate cannot reconstruct what the laser saw; two 0.2 m wings on that grid are one blob. A reinforcement-learning local planner wants the raw scan for the same reason. Neither had a route to it: ActionContext held only TF, and LocalPlanner::initialize takes only a costmap. The store keeps readings raw. Anything that wants filtering filters before publishing here; the store does not know a filter exists. That split is deliberate - a costmap wants outliers removed, a detector wants the true shape, and a store deciding for both would be wrong for one of them. Sharing is by shared_ptr to an immutable reading. Producers build a new one and swap the pointer rather than writing in place, so a reader copies the pointer under the mutex in tens of nanoseconds and then walks a thousand ranges with nobody able to change them underneath. Two consumers reading one topic share one copy rather than taking one each, which is what makes a megabyte depth cloud affordable to share. A bare pointer into the store would instead force every reader to hold the lock for the whole read, putting the sensor input path behind however long a detector takes. The store keeps its own mutex for the same reason: NavigationServer's already covers five kinds of data, and readers running at control-loop rate do not belong in that queue. Readers order on an arrival counter, not on the stamp. A stamp can go backwards - host restart, a switch to simulated time, a replayed bag - and a reader filtering on stamp then treats every later reading as old and freezes for good, silently. The stamp is still kept, for TF lookups and for age, which are different jobs. A consumer faster than its sensor gets null on the ticks with nothing new rather than the same reading handed back to be counted twice. The interface is type-erased because boost::dll-loaded plugins cross it. One virtual per message type would mean a new virtual per sensor, reshuffling the vtable and silently breaking every .so not rebuilt in the same pass - dlsym plus reinterpret_cast catches none of that at compile time. So identity travels as a string, payload as shared_ptr, and five virtuals cover every message type that exists or will. The typed sugar is a header-only template on the caller's side. typeid is avoided deliberately: comparing type_index across a .so depends on visibility and on how the linker merges typeinfo, and it fails quietly. Adding a message type is one line of a list that generates both the trait and the YAML short-name table, so a type can never be castable without being nameable, or the reverse. A read with the wrong identity is refused and logged once, never cast. static_pointer_cast to the wrong type reads garbage instead of crashing and surfaces somewhere unrelated; that check is the only thing standing between the erasure and it. 22 of the 24 robot_sensor_msgs types are registered. Imu and TimeReference are not, because their headers do not compile here at all - Imu.h still carries the unported ROS tail specialising ros::message_operations::Printer, and TimeReference.h declares its field as ros::Time. Both are faults in robot_sensor_msgs, and fixing them makes each one line here. Config is refused at boot rather than at first use, and an undeclared topic is dropped rather than added on the fly: an undeclared depth cloud would otherwise cost megabytes a frame and the config would stop describing what the process holds. A store with nothing declared stays silent - warning once per topic about a feature nobody switched on is how a working system starts printing errors after an upgrade. SensorConsumer is the side channel for a local planner: widening LocalPlanner::initialize would break every planner in the workspace at once for the sake of the one that wants a scan, so a planner that wants sensor data inherits this as well and the runtime finds out with a dynamic_cast. --- CMakeLists.txt | 307 ++++++++++ README.md | 243 ++++++++ include/robot_sensor_ports/sensor_consumer.h | 64 +++ include/robot_sensor_ports/sensor_reader.h | 170 ++++++ include/robot_sensor_ports/sensor_sample.h | 97 ++++ include/robot_sensor_ports/sensor_store.h | 155 ++++++ .../robot_sensor_ports/sensor_store_config.h | 94 ++++ include/robot_sensor_ports/sensor_type.h | 97 ++++ include/robot_sensor_ports/sensor_types.h | 91 +++ include/robot_sensor_ports/sensor_writer.h | 87 +++ package.xml | 49 ++ src/sensor_store.cpp | 398 +++++++++++++ src/sensor_store_config.cpp | 133 +++++ src/sensor_type.cpp | 148 +++++ test/config/sensor_store_params.yaml | 97 ++++ test/sensor_store_config_test.cpp | 187 +++++++ test/sensor_store_test.cpp | 527 ++++++++++++++++++ test/sensor_type_test.cpp | 136 +++++ 18 files changed, 3080 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 README.md create mode 100644 include/robot_sensor_ports/sensor_consumer.h create mode 100644 include/robot_sensor_ports/sensor_reader.h create mode 100644 include/robot_sensor_ports/sensor_sample.h create mode 100644 include/robot_sensor_ports/sensor_store.h create mode 100644 include/robot_sensor_ports/sensor_store_config.h create mode 100644 include/robot_sensor_ports/sensor_type.h create mode 100644 include/robot_sensor_ports/sensor_types.h create mode 100644 include/robot_sensor_ports/sensor_writer.h create mode 100644 package.xml create mode 100644 src/sensor_store.cpp create mode 100644 src/sensor_store_config.cpp create mode 100644 src/sensor_type.cpp create mode 100644 test/config/sensor_store_params.yaml create mode 100644 test/sensor_store_config_test.cpp create mode 100644 test/sensor_store_test.cpp create mode 100644 test/sensor_type_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..abf07d6 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,307 @@ +cmake_minimum_required(VERSION 3.0.2) +project(robot_sensor_ports VERSION 0.1.0 LANGUAGES CXX) + +# ======================================================== +# Build mode detection +# ======================================================== +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) + message(STATUS "Building robot_sensor_ports with Catkin") +else() + set(BUILDING_WITH_CATKIN FALSE) + message(STATUS "Building robot_sensor_ports with Standalone CMake") +endif() + + +# ======================================================== +# C++ Standard +# ======================================================== +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + + +# ======================================================== +# Common dependencies +# ======================================================== +# Boost chỉ dùng phần header (shared_ptr, make_shared, pointer_cast) — không link component nào. +find_package(Boost REQUIRED) + +find_package(Threads REQUIRED) +find_package(yaml-cpp REQUIRED) + + +# ======================================================== +# Standalone configuration +# ======================================================== +if(NOT BUILDING_WITH_CATKIN) + + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + set(CMAKE_BUILD_RPATH_USE_ORIGIN TRUE) + set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) + set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}") + + # Test/robot_sensor_ports -> Test -> AMR_T800. Cây nguồn của nav core nằm ngay dưới đó. + set(PNKX_NAV_CORE_SRC_DIR + "${CMAKE_CURRENT_SOURCE_DIR}/../../.." + ) + + set(WORKSPACE_DEVEL_LIB_DIR + "${CMAKE_CURRENT_SOURCE_DIR}/../../../../devel/lib" + ) + + file(GLOB STANDALONE_PACKAGE_INCLUDE_DIRS + LIST_DIRECTORIES true + + ${PNKX_NAV_CORE_SRC_DIR}/*/include + ${PNKX_NAV_CORE_SRC_DIR}/*/*/include + ${PNKX_NAV_CORE_SRC_DIR}/*/*/*/include + ${PNKX_NAV_CORE_SRC_DIR}/*/*/*/*/include + ) + + set(STANDALONE_INCLUDE_DIRS + ${STANDALONE_PACKAGE_INCLUDE_DIRS} + + /opt/ros/noetic/include + /usr/local/include + ) + + if(EXISTS ${WORKSPACE_DEVEL_LIB_DIR}) + link_directories(${WORKSPACE_DEVEL_LIB_DIR}) + endif() + + link_directories( + /usr/local/lib + ) + + # Gói này KHÔNG kéo costmap, tf3 hay boost::dll: nó chỉ cất message và trả con trỏ. Đây là lý do + # mọi tầng khác phụ thuộc được vào nó mà không tạo vòng. + set(STANDALONE_LIBRARIES + robot_cpp + robot_time + robot_xmlrpcpp + ) + + include_directories( + include + ) + + include_directories(SYSTEM + ${STANDALONE_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ) + + +# ======================================================== +# Catkin configuration +# ======================================================== +else() + + find_package(catkin REQUIRED COMPONENTS + robot_cpp + robot_time + robot_sensor_msgs + robot_xmlrpcpp + ) + + catkin_package( + INCLUDE_DIRS + include + + LIBRARIES + robot_sensor_ports + + CATKIN_DEPENDS + robot_cpp + robot_time + robot_sensor_msgs + robot_xmlrpcpp + + DEPENDS + Boost + ) + + include_directories( + include + ) + + # Header của dependency vào dạng SYSTEM: gói này build với -Wall -Wextra, mà robot_cpp sinh hàng + # trăm warning riêng của nó — để lẫn vào thì warning của chính gói này vô hình. + include_directories(SYSTEM + ${catkin_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ) + +endif() + + +# ======================================================== +# Library +# ======================================================== +add_library(robot_sensor_ports SHARED + src/sensor_type.cpp + src/sensor_store.cpp + src/sensor_store_config.cpp +) + +target_compile_options(robot_sensor_ports PRIVATE -Wall -Wextra) + + +if(BUILDING_WITH_CATKIN) + + add_dependencies(robot_sensor_ports + ${${PROJECT_NAME}_EXPORTED_TARGETS} + ${catkin_EXPORTED_TARGETS} + ) + + target_include_directories(robot_sensor_ports + PUBLIC + $ + $ + + ${Boost_INCLUDE_DIRS} + ) + + target_link_libraries(robot_sensor_ports + PUBLIC + ${catkin_LIBRARIES} + + PRIVATE + Boost::boost + + yaml-cpp + + Threads::Threads + ) + +else() + + target_include_directories(robot_sensor_ports + PUBLIC + $ + $ + ) + + # SYSTEM phải đứng ngay sau tên target. Include trong cây nguồn phải bọc BUILD_INTERFACE, + # nếu không install(EXPORT) fail "prefixed in the source directory" khi package nằm in-tree. + target_include_directories(robot_sensor_ports SYSTEM + PUBLIC + "$" + ${Boost_INCLUDE_DIRS} + ) + + target_link_libraries(robot_sensor_ports + PUBLIC + ${STANDALONE_LIBRARIES} + + PRIVATE + Boost::boost + + yaml-cpp + + Threads::Threads + ) + + # .so ra root build dir như action_core/mission_adapters, để runtime tìm thấy ở cùng một chỗ. + set_target_properties(robot_sensor_ports PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + BUILD_RPATH "${CMAKE_BINARY_DIR}" + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" + ) + +endif() + + +# ======================================================== +# Install +# ======================================================== +if(BUILDING_WITH_CATKIN) + + install(TARGETS robot_sensor_ports + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} + FILES_MATCHING PATTERN "*.h" + ) + +else() + + include(GNUInstallDirs) + + install(TARGETS robot_sensor_ports + EXPORT ${PROJECT_NAME}-targets + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ) + + install(EXPORT ${PROJECT_NAME}-targets + FILE ${PROJECT_NAME}-targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} + ) + + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} + FILES_MATCHING PATTERN "*.h" + ) + +endif() + + +# ======================================================== +# Tests +# ======================================================== +if(CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN) + + if(NOT COMMAND catkin_add_gtest) + message(FATAL_ERROR "catkin_add_gtest NOT FOUND") + endif() + + set(ROBOT_SENSOR_PORTS_TESTS + sensor_type_test + sensor_store_test + sensor_store_config_test + ) + + foreach(test_name ${ROBOT_SENSOR_PORTS_TESTS}) + catkin_add_gtest(${test_name} test/${test_name}.cpp) + + if(TARGET ${test_name}) + # catkin_add_gtest đặt target EXCLUDE_FROM_ALL; mở ra để binary có mặt sau `catkin_make` + # thường, đúng quy trình verify của repo (chạy thẳng ./devel/lib//). + set_target_properties(${test_name} PROPERTIES EXCLUDE_FROM_ALL FALSE) + + target_compile_options(${test_name} PRIVATE -Wall -Wextra) + + target_include_directories(${test_name} + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include + ) + + target_include_directories(${test_name} SYSTEM + PRIVATE + ${catkin_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS} + ) + + # catkin_add_gtest dùng target_link_libraries dạng plain, nên phần bổ sung cũng phải plain. + target_link_libraries(${test_name} + robot_sensor_ports + ${catkin_LIBRARIES} + yaml-cpp + pthread + ) + + # Đường tới cây config test — ctest không mang theo PNKX_NAV_CORE_CONFIG_DIR của shell. + target_compile_definitions(${test_name} PRIVATE + ROBOT_SENSOR_PORTS_TEST_CONFIG_DIR="${CMAKE_CURRENT_SOURCE_DIR}/test/config" + ) + endif() + endforeach() + +endif() diff --git a/README.md b/README.md new file mode 100644 index 0000000..be6f0d1 --- /dev/null +++ b/README.md @@ -0,0 +1,243 @@ +# robot_sensor_ports + +Kho dữ liệu cảm biến **thô** dùng chung cho navigation runtime, cộng hai cổng hẹp nhìn vào nó. + +Gói này không biết navigation, costmap hay planner là gì. Nó chỉ trả lời một câu: *bản đọc mới nhất +của topic này là gì, và đã có bản nào mới hơn cái tôi đang cầm chưa.* + +## Vì sao cần + +Dữ liệu cảm biến vào runtime rồi biến mất vào costmap. Nhưng costmap ở `0.05 m` kèm inflation đã +**xoá mất thứ tự tia và hình dạng vật thể** — không dựng lại được `ranges` từ đó. + +Hai bên cần bản thô: + +- **Bộ dò dock**: fit đường thẳng cần đúng mảng `ranges` theo thứ tự góc. Hai cánh chữ V dài 0.2 m + trên lưới `0.05 m` đã inflate là một cục, không fit được. +- **Local planner học tăng cường**: observation lấy từ scan thô. + +Trước gói này thì không có đường nào: `ActionContext` chỉ có TF, còn +`robot_nav_core2::LocalPlanner::initialize` chỉ nhận `Costmap2DROBOT*`. + +## Kho giữ bản THÔ + +Muốn lọc thì **lọc trước khi đẩy vào**; kho không biết bộ lọc nào tồn tại. + +Hệ quả có chủ đích: khi bật lọc SOR, **costmap và kho nhìn hai bản khác nhau**. Costmap muốn bớt +điểm nhiễu; bộ dò muốn hình dạng thật. Một kho quyết định thay cả hai thì sai với một trong hai. + +## Chia sẻ bằng con trỏ tới bản bất biến + +```cpp +// producer — dựng bản mới rồi TRÁO, không bao giờ sửa tại chỗ +robot_sensor_ports::put(writer, "/f_scan", scan, stamp); + +// consumer — giữ khoá đúng lúc copy con trỏ, rồi đọc ngoài khoá +auto snap = robot_sensor_ports::latest(reader, "/f_scan", cursor); +if (snap) { detect(snap->ranges); } +``` + +Ba luật: + +1. **Đã publish là bất biến.** Không có luật này thì reader đang duyệt `ranges` giữa chừng sẽ thấy + nửa bản cũ nửa bản mới — race không crash, chỉ ra kết quả sai. +2. **Khoá chỉ che lúc copy con trỏ**, vài chục nano giây. Đọc 1000 điểm nằm ngoài khoá. +3. **Reader giữ con trỏ bao lâu tuỳ nó.** Bản đó sống tới khi reader cuối cùng thả. + +Hai consumer đọc cùng một topic **dùng chung một bản**, không phải mỗi người một bản copy — đó là +thứ khiến một depth cloud hàng MB chia được mà không nhân lên. + +## `sequence`, không phải stamp + +Reader so cursor với `sequence` (thứ tự đến), không phải `stamp`. + +Stamp **lùi được**: host restart, đổi sang sim time, replay bag. Lọc theo stamp thì sau cú lùi +reader coi mọi bản mới là cũ và **đứng im vĩnh viễn, không log gì**. Thứ tự đến thì không lùi. + +Stamp vẫn giữ, nhưng để tra TF và tính tuổi — hai việc khác hẳn. + +Hệ quả cho consumer chạy nhanh hơn cảm biến: control loop 20 Hz đọc lidar 15 Hz thì **một phần tư +số tick không có gì mới**. `latest()` trả null ở những tick đó, thay vì đưa lại đúng bản cũ để bị +xử lý hai lần. + +## Hai cổng + +| | ai giữ | làm được gì | +|---|---|---| +| `SensorWriter` | runtime, một mình | `put` | +| `SensorReader` | plugin, planner, handler | `latest`, `history`, `has`, `describe`, `inventory` | +| `SensorConsumer` | planner tự khai nhận | nhận cổng đọc qua `dynamic_cast`, không đổi chữ ký nào | + +Reader **không xoá được kho, không đổi được topic nào**. Một writer, nhiều reader, và khác biệt đó +nằm ngay trong kiểu. + +`SensorStore` hiện thực cả hai; runtime giữ nó và chỉ phát ra tham chiếu `SensorReader`. + +## Đưa cổng cho một local planner mà không phá chữ ký + +`robot_nav_core2::LocalPlanner::initialize` nhận đúng `(NodeHandle, tên, TF, costmap)`. Nới chữ ký +đó để một planner đọc được LiDAR sẽ **gãy tất cả planner còn lại cùng lúc** — hybrid, mppi, priest, +stanley, deep_mpc. + +Nên planner nào cần thì kế thừa thêm `SensorConsumer`, và `ControllerRunner` hỏi bằng +`dynamic_cast` sau khi nạp plugin: + +```cpp +class RLLocalPlanner : public robot_nav_core2::LocalPlanner, + public robot_sensor_ports::SensorConsumer +{ + void setSensorReader(const robot_sensor_ports::SensorReader* reader) override { sensors_ = reader; } +}; +``` + +Không kế thừa thì cast ra null, không có gì xảy ra. Cổng được đưa **trước `initialize()`**, nên +planner dùng được ngay khi tự cấu hình. + +> ⚠ Cast qua ranh giới `.so` cần RTTI khớp: cùng định nghĩa, cùng toolchain, cùng `-fvisibility`. +> **Build xanh không chứng minh điều đó** — nên `ControllerRunner` log kết quả cast thật, và +> `controller_runner_test` có plugin `TestControllerSensorProbe` bị `dlopen` như plugin thật để kiểm. + +## Xoá kiểu — và vì sao + +Interface bị **plugin nạp bằng `boost::dll` đi qua**. Một virtual cho mỗi loại message nghĩa là +thêm cảm biến mới = thêm virtual = xáo vtable = **gãy im lặng mọi `.so` không build lại cùng lượt**. +`dlsym` + `reinterpret_cast` không bắt được gì lúc biên dịch; lời gọi ảo trúng sai slot lúc chạy. + +Nên định danh đi bằng chuỗi, payload đi bằng `boost::shared_ptr`, và **5 virtual phủ mọi +loại message đang có lẫn sẽ có**. Phần có kiểu (`latest`, `history`, `put`) là template header-only +nằm ở **phía gọi**, không nằm trên ranh giới `.so`. + +`typeid` cố ý không dùng: so `std::type_index` qua `.so` phụ thuộc visibility và cách linker gộp +typeinfo, hỏng thì hỏng im lặng. + +> ⚠ Thêm **virtual** vào `SensorReader` vẫn phá ABI. Thêm **loại message** thì không. Giữ nguyên như +> vậy: năng lực mới đưa vào phần template, đừng đẻ virtual. + +### Sai kiểu bị từ chối, không bao giờ cast bừa + +Kho ghi lại định danh lúc `put` và so trước khi trả. Lệch thì `false` + log **một lần**. + +Đây là hàng rào duy nhất giữa type erasure và UB: `static_pointer_cast` sai kiểu **đọc ra rác chứ +không crash**, rồi hỏng ở một chỗ hoàn toàn khác. + +## Thêm một loại message + +Một dòng trong `ROBOT_SENSOR_PORTS_TYPE_LIST` (`sensor_types.h`): + +```cpp +X(::robot_sensor_msgs::Range, "robot_sensor_msgs/Range") +``` + +Danh sách đó sinh **cả hai**: specialisation `SensorType` và bảng tên ngắn cho YAML. Một nguồn, +nên không thể có loại cast được mà không khai được trong YAML, hay ngược lại. + +Không đổi interface. **Không plugin nào phải build lại.** + +Loại thuộc package khác thì đăng ký ở nơi nó sống — `ROBOT_SENSOR_PORTS_REGISTER_TYPE` cộng một lời +gọi `TypeNames::add()` lúc khởi động — để không kéo dependency của nó vào mọi nơi include header này. + +### 22/24 loại của `robot_sensor_msgs` được đăng ký sẵn + +Thiếu `Imu` và `TimeReference` vì **header của chúng không biên dịch được trong workspace này**: + +- `Imu.h:295` còn nguyên phần đuôi ROS chưa port, specialise + `ros::message_operations::Printer` — template không tồn tại ở đây; +- `TimeReference.h:39` khai field là `ros::Time` thay vì `robot::Time`. + +Cả hai là lỗi có sẵn của `robot_sensor_msgs`, không phải giới hạn của kho. Sửa hai header đó thì mỗi +loại thành đúng một dòng. + +### Thêm một NGUỒN dữ liệu mới thì khác + +Kho chứa được mọi loại, nhưng dữ liệu **chỉ vào được qua `BaseNavigation`**, mà `navigation.h` hiện +chỉ có **5 cửa**: `addStaticMap`, `addLaserScan`, `addPointCloud`, `addPointCloud2`, +`addDepthCameraData`. Không có `addImu`. + +Mở cửa mới là đụng ba nơi, cả ba đều là ranh giới cứng: + +1. `move_base_core/navigation.h` — pure virtual mới, gãy cả ba host; +2. `nav_c_api.h` / `.cpp` — hàm `extern "C"` mới, phía .NET phải cập nhật; +3. `amr_control/sensor_converter.cpp` — subscribe + convert (chỉ cho host ROS). + +Nói ngắn: **kho không chặn, cửa vào mới chặn.** + +## Config + +```yaml +sensor_store: + sensors: + - topic: /f_scan + data_type: LaserScan # dạng ngắn; robot_sensor_msgs/LaserScan cũng nhận + capacity: 1 # số bản giữ lại + max_age: 0.5 # [s] +``` + +Quy ước tên, áp cho mọi cây config: khoá trỏ tới **luồng cảm biến** kết thúc bằng `_topic`, khoá trỏ +tới **frame TF** kết thúc bằng `_frame`. + +`topic` là chuỗi host dùng khi gọi `add*(...)`. Dưới host ROS nó đúng là tên topic ROS; dưới host +.NET nó là chuỗi C# tự đặt. + +Dạng ngắn chỉ tồn tại tới hết parser: mọi tầng dưới, và **mọi thông báo lỗi**, dùng dạng đầy đủ. + +`capacity > 1` dành cho consumer cần nhiều frame liên tiếp kèm đúng `dt`. Nhớ nó nhân theo **kích +thước message**: 5 scan là vài KB, 5 depth cloud là hàng chục MB. + +### Từ chối lúc BOOT, không phải lúc chạy + +- `data_type` không có thật, hoặc **tên ngắn bị hai package cùng dùng** (không đoán — chọn bừa là + cất nhầm kiểu trong im lặng); +- thiếu `topic` hoặc `data_type`; +- `capacity < 1`, `max_age` không hữu hạn hoặc `<= 0`; +- một `topic` khai hai lần (cái nào thắng chỉ do thứ tự viết). + +Không khai sensor nào là **hợp lệ** — runtime không có consumer nào của dữ liệu thô thì giữ rỗng. +Đó là câu trả lời, không phải lý do chặn robot khởi động. + +Kho **chưa khai gì cả** thì im lặng hoàn toàn: runtime không có consumer nào của dữ liệu thô thì +không có kho, và cảnh báo mỗi topic một lần về tính năng chưa ai bật chính là cách một hệ đang chạy +bỗng in lỗi sau khi nâng cấp. Khai rồi mà thiếu một topic thì đó là nhầm lẫn thật, và nói ra. + +Topic không khai mà có người đẩy vào thì **bị bỏ** kèm log một lần, không tự thêm slot: một depth +cloud không ai khai sẽ ngốn hàng MB mỗi frame, và config thôi không còn trả lời được câu "tiến +trình này đang giữ những gì". + +## Đồng bộ với host khi host bỏ dữ liệu + +`clearTopic(topic)` và `clearOfType(type_id)` bỏ dữ liệu nhưng **giữ khai báo**. `NavigationServer` +gọi chúng trong `removeLaserScan` / `removeAllLaserScans` / … — host đã bỏ dữ liệu mà kho còn phát +bản cũ là hai nguồn nói hai chuyện khác nhau về thứ robot đang nhìn thấy, và `max_age` chỉ che được +phần ngọn. + +Số đếm `sequence` **không** quay về 0 khi xoá: cursor cũ sẽ trông mới hơn dữ liệu vừa tới và reader +đó đứng im vĩnh viễn. + +## Chẩn đoán + +`inventory()` liệt kê topic + kiểu + Hz + tuổi + số bản bị từ chối. Việc thật của nó là biến *"action +hết giờ"* thành *"ông xin `/front_scan`, kho có `/f_scan` (14.9 Hz) và `/b_scan` (15.0 Hz)"* — gõ sai +topic thì triệu chứng giống hệt cảm biến chết. + +`describe(topic)` rẻ, gọi được trong control loop; consumer đọc `max_age` từ đó thay vì tự khai một +ngưỡng tươi riêng rồi trôi lệch khỏi kho. + +Hz đo từ **stamp delta**, không từ thời điểm nhận: đúng cả dưới sim time, và gói này **không bao giờ +gọi `robot::Time::now()`** — hàm đó ném exception trước khi có NodeHandle, và đọc wall clock khi +đang chạy sim time. + +## Build và test + +```bash +catkin_make --pkg robot_sensor_ports + +./devel/lib/robot_sensor_ports/sensor_type_test # 8 test +./devel/lib/robot_sensor_ports/sensor_store_test # 24 test +./devel/lib/robot_sensor_ports/sensor_store_config_test # 12 test + +# Đường dữ liệu thật, phía move_base2 +./devel/lib/move_base2/navigation_server_test --gtest_filter='NavigationServerSensorStore*' +./devel/lib/move_base2/controller_runner_test --gtest_filter='ControllerRunnerSensors*' +``` + +Gói build được cả hai nhánh catkin và standalone. Không kéo costmap, tf3 hay `boost::dll` — đó là lý +do mọi tầng khác phụ thuộc được vào nó mà không tạo vòng. diff --git a/include/robot_sensor_ports/sensor_consumer.h b/include/robot_sensor_ports/sensor_consumer.h new file mode 100644 index 0000000..3b64754 --- /dev/null +++ b/include/robot_sensor_ports/sensor_consumer.h @@ -0,0 +1,64 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_sensor_ports — opt-in hook for plugins whose own interface carries no sensor data. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROBOT_SENSOR_PORTS_SENSOR_CONSUMER_H_ +#define ROBOT_SENSOR_PORTS_SENSOR_CONSUMER_H_ + +namespace robot_sensor_ports +{ + +class SensorReader; + +/** + * @class SensorConsumer + * @brief Side channel for a plugin that needs raw sensor data its own interface does not carry. + * + * `robot_nav_core2::LocalPlanner::initialize` takes a node handle, a name, TF and a costmap, and + * nothing else. Widening that signature would break every planner in the workspace at once — + * hybrid, mppi, priest, stanley, deep_mpc — for the sake of the one that wants a laser scan. + * + * So a planner that wants sensor data inherits this as well, and the runtime finds out with a + * `dynamic_cast` after loading the plugin. A planner that does not inherit it casts to null and + * nothing happens: no signature changed, no existing plugin needs rebuilding. + * + * @code + * class RLLocalPlanner : public robot_nav_core2::LocalPlanner, + * public robot_sensor_ports::SensorConsumer + * { + * void setSensorReader(const robot_sensor_ports::SensorReader* reader) override + * { + * sensors_ = reader; // non-owning; outlives the plugin + * } + * }; + * @endcode + * + * @warning The cast reaches across a `.so` boundary, so it works only while both sides see the same + * definition and were built with the same toolchain and visibility settings. A green build + * proves none of that — it is why `ControllerRunner` logs whether the cast actually + * matched, rather than assuming it did. + * + * @note The runtime calls this **before** `initialize`, so a planner may already use the reader + * while configuring itself. It may also be called again with a different reader, or with + * null; the last value wins, and null means there is no store. + */ +class SensorConsumer +{ +public: + virtual ~SensorConsumer() = default; + + /** + * @brief Hand over the read port. + * @param reader Non-owning, may be null. Outlives the plugin — the runtime owns the store and + * tears plugins down first. + */ + virtual void setSensorReader(const SensorReader* reader) = 0; +}; + +} // namespace robot_sensor_ports + +#endif // ROBOT_SENSOR_PORTS_SENSOR_CONSUMER_H_ diff --git a/include/robot_sensor_ports/sensor_reader.h b/include/robot_sensor_ports/sensor_reader.h new file mode 100644 index 0000000..4832c4a --- /dev/null +++ b/include/robot_sensor_ports/sensor_reader.h @@ -0,0 +1,170 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_sensor_ports — read port onto the shared sensor store. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROBOT_SENSOR_PORTS_SENSOR_READER_H_ +#define ROBOT_SENSOR_PORTS_SENSOR_READER_H_ + +#include +#include +#include +#include + +#include +#include + +#include +#include + +namespace robot_sensor_ports +{ + +/** + * @class SensorReader + * @brief Read-only view of the shared sensor store, handed to plugins. + * + * Consumers get this, not the store itself: a read port cannot clear the store, drop a topic or + * overwrite a reading. One writer, many readers, and the difference is visible in the type. + * + * ## Why the interface is type-erased + * + * This class is crossed by `boost::dll`-loaded plugins — action handlers today, local planners once + * they need raw sensor data. A virtual per message type would mean a new virtual for every new + * sensor, which reshuffles the vtable, which silently breaks every `.so` not rebuilt in the same + * pass. `dlsym` plus `reinterpret_cast` catches none of that at compile time; a virtual call lands + * in the wrong slot at run time instead. + * + * So the identity of the message travels as a string and the payload as `shared_ptr`. + * These five virtuals cover every message type that exists and every one that ever will, and the + * typed sugar below — @ref latest, @ref history, @ref has — is a header-only template that lives on + * the caller's side of the boundary, where template instantiation is nobody else's problem. + * + * @warning Adding a virtual here still breaks the ABI. Adding a *message type* does not. Keep it + * that way: put new capability in the typed helpers, not in new virtuals. + * + * @note Every method is safe to call concurrently with the writer and with other readers. + */ +class SensorReader +{ +public: + virtual ~SensorReader() = default; + + /** + * @brief Fetch the newest reading of @p topic, but only if it is newer than @p since. + * + * @param[in] type_id Identity the caller expects, from `SensorType::id()`. + * @param[in] topic Topic name as configured. + * @param[in,out] since Caller's cursor. Advanced to the new sequence on success, untouched + * otherwise. Start at 0 to get whatever is there. + * @param[out] out Filled on success, untouched otherwise. + * @return false when the topic is unknown, when it holds a different message type, or when + * nothing newer than @p since has arrived. + * + * Returning false for "nothing new" rather than re-handing the same reading is the point of the + * cursor: a control loop at 20 Hz reading a 15 Hz sensor spends a quarter of its ticks with no + * new data, and it needs to know that rather than reprocess the same scan and count it twice. + * + * A type mismatch is reported once per topic through the store's log and never silently cast — + * casting `shared_ptr` to the wrong type is undefined behaviour that reads garbage + * instead of crashing. + */ + virtual bool latestErased(const char* type_id, const std::string& topic, uint64_t& since, + SensorSample& out) const = 0; + + /** + * @brief Fetch up to @p count of the most recent readings, **oldest first**. + * + * Oldest first because the caller stacking frames needs them in the order they happened, and + * because reversing at every call site is exactly how one site ends up not reversing. + * + * @param[out] out Cleared, then filled. Fewer than @p count entries when the topic has not + * collected that many yet — check `out.size()` before assuming a full stack. + * @return false when the topic is unknown, holds another type, or holds nothing at all. + * + * @note Bounded by the topic's `capacity`; a topic configured with `capacity: 1` can never return + * more than one, no matter what @p count says. The config loader rejects a consumer asking + * for a deeper stack than the store keeps, so that mismatch fails at boot rather than + * showing up as an observation quietly missing frames. + */ + virtual bool historyErased(const char* type_id, const std::string& topic, std::size_t count, + std::vector& out) const = 0; + + /// @brief Whether @p topic is configured and holds that message type. No reading required. + virtual bool has(const char* type_id, const std::string& topic) const = 0; + + /** + * @brief What is known about one topic, without building the whole inventory. + * @return false when the topic is not configured. + * + * Cheap enough for a control loop, which is the point: a consumer reads `max_age` from here + * instead of declaring its own freshness limit and drifting away from the store's. + */ + virtual bool describe(const std::string& topic, SensorInfo& out) const = 0; + + /** + * @brief Every configured topic. + * + * Allocates; call it when something has gone wrong, not every cycle. Its real job is turning + * "the action timed out" into "you asked for /front_scan, the store has /f_scan at 14.9 Hz and + * /b_scan at 15.0 Hz" — a mistyped topic is otherwise indistinguishable from a dead sensor. + */ + virtual std::vector inventory() const = 0; +}; + +/** + * @brief Typed form of @ref SensorReader::latestErased. + * @return Null when there is nothing newer, when the topic is unknown, or on a type mismatch. + * + * @code + * auto scan = latest(*ctx_.sensors, scan_topic_, scan_cursor_); + * if (scan) { detect(scan->ranges); } + * @endcode + */ +template +boost::shared_ptr latest(const SensorReader& reader, const std::string& topic, + uint64_t& since) +{ + SensorSample sample; + if (!reader.latestErased(SensorType::id(), topic, since, sample)) + { + return boost::shared_ptr(); + } + // Safe: latestErased only returns true after matching the identity string recorded at put time. + return boost::static_pointer_cast(sample.data); +} + +/// @brief Typed form of @ref SensorReader::historyErased. Empty on failure. Oldest first. +template +std::vector> history(const SensorReader& reader, + const std::string& topic, std::size_t count) +{ + std::vector> typed; + + std::vector samples; + if (!reader.historyErased(SensorType::id(), topic, count, samples)) + { + return typed; + } + + typed.reserve(samples.size()); + for (const SensorSample& sample : samples) + { + typed.push_back(boost::static_pointer_cast(sample.data)); + } + return typed; +} + +/// @brief Typed form of @ref SensorReader::has. +template +bool has(const SensorReader& reader, const std::string& topic) +{ + return reader.has(SensorType::id(), topic); +} + +} // namespace robot_sensor_ports + +#endif // ROBOT_SENSOR_PORTS_SENSOR_READER_H_ diff --git a/include/robot_sensor_ports/sensor_sample.h b/include/robot_sensor_ports/sensor_sample.h new file mode 100644 index 0000000..ce442bb --- /dev/null +++ b/include/robot_sensor_ports/sensor_sample.h @@ -0,0 +1,97 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_sensor_ports — one stored reading, and what is known about a topic. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROBOT_SENSOR_PORTS_SENSOR_SAMPLE_H_ +#define ROBOT_SENSOR_PORTS_SENSOR_SAMPLE_H_ + +#include +#include +#include + +#include + +#include + +namespace robot_sensor_ports +{ + +/** + * @struct SensorSample + * @brief One reading handed out by the store, still type-erased. + * + * `data` points at an object the store published and will never modify again. The producer builds a + * new message and swaps the pointer; it does not write into a message a reader might be holding. + * That is what lets a reader work outside the lock: it copies the `shared_ptr` under the mutex — + * tens of nanoseconds — and then reads a thousand range values with nobody able to touch them. + * + * The reading stays alive as long as any reader holds it, so there is no dangling pointer and no + * lock held during use. Two consumers reading the same topic share one copy rather than taking one + * each, which is what makes a megabyte-sized depth cloud affordable to share. + */ +struct SensorSample +{ + /// Non-null after a successful read. Cast back with @ref latest, never by hand. + boost::shared_ptr data; + + /** + * @brief Arrival counter of this reading, starting at 1. + * + * Readers compare against this, **not** against @ref stamp. A stamp can go backwards — host + * restart, switching to simulated time, replaying a bag — and a reader that filters on stamp then + * treats every later reading as old and freezes for good, silently. Arrival order cannot go + * backwards. + * + * The stamp still matters, for looking up TF and for measuring age. Two different jobs. + */ + uint64_t sequence = 0; + + /// Stamp the producer supplied. Use for TF lookups and for age; never for ordering. + robot::Time stamp; +}; + +/** + * @struct SensorInfo + * @brief What the store knows about one configured topic. + * + * Serves three jobs that would otherwise each grow their own mechanism: telling an operator which + * topics exist when they mistype one, giving a consumer the freshness policy without re-declaring + * `max_age` in its own config, and supplying the age/sequence that observation metadata needs. + */ +struct SensorInfo +{ + /// Name the host passes to `add*(...)`. Under a ROS host this is the ROS topic. + std::string topic; + + /// Full identity, e.g. `robot_sensor_msgs/LaserScan`. + std::string data_type; + + /// Arrival counter of the newest reading; 0 while nothing has arrived yet. + uint64_t sequence = 0; + + /// Stamp of the newest reading. + robot::Time stamp; + + /// [Hz] Smoothed publish rate derived from stamp deltas. 0 until two usable stamps have arrived. + double rate_hz = 0.0; + + /// [s] Age beyond which a reader should treat the newest reading as stale. + double max_age = 0.0; + + /// How many readings this topic is allowed to keep. + std::size_t capacity = 1; + + /// How many readings it currently holds. + std::size_t size = 0; + + /// Readings rejected so far: unconfigured topic, or a type that does not match the configured one. + uint64_t rejected = 0; +}; + +} // namespace robot_sensor_ports + +#endif // ROBOT_SENSOR_PORTS_SENSOR_SAMPLE_H_ diff --git a/include/robot_sensor_ports/sensor_store.h b/include/robot_sensor_ports/sensor_store.h new file mode 100644 index 0000000..8fcb1aa --- /dev/null +++ b/include/robot_sensor_ports/sensor_store.h @@ -0,0 +1,155 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_sensor_ports — the shared store itself. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROBOT_SENSOR_PORTS_SENSOR_STORE_H_ +#define ROBOT_SENSOR_PORTS_SENSOR_STORE_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace robot_sensor_ports +{ + +/** + * @class SensorStore + * @brief One place raw sensor readings live, shared by everything that needs them. + * + * Owned by the navigation runtime, which is also the only holder of the @ref SensorWriter side. + * Everyone else gets a @ref SensorReader and can look but not touch. + * + * ## What makes it safe to read without a lock + * + * A published reading is never modified. `put` builds a new one and swaps the pointer in; readers + * hold the mutex only long enough to copy a `shared_ptr` out, then walk a thousand ranges with + * nobody able to change them underneath. The old reading dies when its last reader lets go. + * + * The alternative — a bare pointer into the store — would force every reader to hold the lock for + * the whole read, which puts the sensor input path behind however long a detector takes. + * + * ## Its own mutex, on purpose + * + * Not `NavigationServer::data_mutex_`. That one already covers five kinds of data; adding readers + * running at control-loop rate would put the sensor input path and the control path in contention + * over a lock neither of them needed to share. + * + * @note Every public method is thread-safe. @ref configure is the exception in spirit: call it once + * at startup, before any producer or consumer exists. + */ +class SensorStore : public SensorReader, public SensorWriter +{ +public: + SensorStore() = default; + + SensorStore(const SensorStore&) = delete; + SensorStore& operator=(const SensorStore&) = delete; + + /** + * @brief Declare which topics exist. Everything not declared here is dropped on arrival. + * + * @param[out] error Why it was refused; the store is left untouched in that case. + * @return false when the config is invalid. + * + * Reconfiguring discards whatever was held. Readers holding a sample keep it alive and valid; + * their cursors just stop advancing, which is the correct outcome for a store that was rebuilt + * underneath them. + */ + bool configure(const SensorStoreConfig& config, std::string& error); + + /// @brief Drop every reading but keep the topics. For a host restarting its sensor stream. + void clear(); + + /** + * @brief Drop the readings of one topic, keeping its declaration. + * @return false when the topic is not configured. + * + * Mirrors the host dropping its own cache of that topic. Without it the store would keep handing + * out a reading the host has already disowned, and the two would disagree about what the robot + * can currently see — which `max_age` only papers over. + */ + bool clearTopic(const std::string& topic); + + /** + * @brief Drop the readings of every topic holding @p type_id, keeping their declarations. + * @return How many topics were affected. + * + * The host drops sensor data a whole kind at a time (`removeAllLaserScans`), and the store is + * indexed by topic, so this is the translation between the two. + */ + std::size_t clearOfType(const char* type_id); + + /// @brief Whether @ref configure has run with at least one topic. + bool configured() const; + + // ============================================================================================== + // SensorWriter + // ============================================================================================== + + bool putErased(const char* type_id, const std::string& topic, + const boost::shared_ptr& data, const robot::Time& stamp) override; + + // ============================================================================================== + // SensorReader + // ============================================================================================== + + bool latestErased(const char* type_id, const std::string& topic, uint64_t& since, + SensorSample& out) const override; + + bool historyErased(const char* type_id, const std::string& topic, std::size_t count, + std::vector& out) const override; + + bool has(const char* type_id, const std::string& topic) const override; + + bool describe(const std::string& topic, SensorInfo& out) const override; + + std::vector inventory() const override; + +private: + struct Slot + { + std::string data_type; + std::size_t capacity = 1; + double max_age = 0.5; + + /// Oldest at the front, newest at the back. + std::deque ring; + + uint64_t sequence = 0; ///< Arrival counter of the newest reading. + uint64_t rejected = 0; ///< Readings refused: wrong type, or null payload. + double rate_hz = 0.0; ///< Smoothed from stamp deltas. + bool have_last_stamp = false; + robot::Time last_stamp; + }; + + /// @brief Log a complaint about @p key at most once, so a per-cycle mistake logs once, not 20 Hz. + /// @return true the first time this key is seen. Caller must already hold @ref mutex_. + bool shouldLog(const std::string& key) const; + + /// @brief Fill @p out from @p slot. Caller must already hold @ref mutex_. + static void describeLocked(const std::string& topic, const Slot& slot, SensorInfo& out); + + mutable std::mutex mutex_; + std::map slots_; + + /// Complaints already made. Mutable because refusing a read is a const operation that still needs + /// to say so exactly once. + mutable std::set logged_; +}; + +} // namespace robot_sensor_ports + +#endif // ROBOT_SENSOR_PORTS_SENSOR_STORE_H_ diff --git a/include/robot_sensor_ports/sensor_store_config.h b/include/robot_sensor_ports/sensor_store_config.h new file mode 100644 index 0000000..ef3624b --- /dev/null +++ b/include/robot_sensor_ports/sensor_store_config.h @@ -0,0 +1,94 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_sensor_ports — what the store is allowed to hold, read from YAML. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROBOT_SENSOR_PORTS_SENSOR_STORE_CONFIG_H_ +#define ROBOT_SENSOR_PORTS_SENSOR_STORE_CONFIG_H_ + +#include +#include +#include + +#include + +namespace robot_sensor_ports +{ + +/** + * @struct SensorEntryConfig + * @brief One topic the store accepts. + * + * Naming convention across every config tree: a key naming a sensor stream ends in `_topic`, a key + * naming a TF frame ends in `_frame`. `topic` here is the bare form of the first. + */ +struct SensorEntryConfig +{ + /// Name the host passes to `add*(...)`. Under a ROS host this is the ROS topic name. + std::string topic; + + /// Full identity, e.g. `robot_sensor_msgs/LaserScan`. YAML may say either the short or full form. + std::string data_type; + + /** + * @brief How many readings to keep. + * + * 1 keeps only the newest and costs what the old single-slot behaviour cost. Above 1 is for + * consumers that need consecutive frames with their true `dt`. + * + * @warning Scales by message size, not by count. Five laser scans is a few kilobytes; five depth + * clouds is tens of megabytes. + */ + std::size_t capacity = 1; + + /// [s] Age past which a reader should treat the newest reading as stale. Must be > 0. + double max_age = 0.5; +}; + +/** + * @struct SensorStoreConfig + * @brief Everything the store accepts, and nothing else. + * + * Expected YAML, under whatever namespace the caller passes: + * + * @code{.yaml} + * sensor_store: + * sensors: + * - topic: /f_scan + * data_type: LaserScan # or robot_sensor_msgs/LaserScan + * capacity: 1 + * max_age: 0.5 + * @endcode + */ +struct SensorStoreConfig +{ + std::vector sensors; + + /** + * @brief Read and validate the whole section. + * + * @param nh Node handle the caller has already scoped as it wants. + * @param ns Namespace holding the `sensors` list, e.g. `sensor_store`. Empty reads `sensors` + * at the root. + * @param[out] out Filled only on success — a rejected config never half-configures the store. + * @param[out] error What was wrong, naming the offending entry by index and topic. + * @return false on anything invalid. + * + * Rejected at boot, every one of them, rather than at the moment of use: + * - a `data_type` no package has registered, or a short name two packages share; + * - `capacity` below 1, or `max_age` that is not finite and positive; + * - an empty topic, or the same topic declared twice. + * + * A missing section is not an error: a runtime with no consumer of raw sensor data holds nothing, + * which is the right answer rather than a reason to refuse to start. + */ + static bool load(robot::NodeHandle& nh, const std::string& ns, SensorStoreConfig& out, + std::string& error); +}; + +} // namespace robot_sensor_ports + +#endif // ROBOT_SENSOR_PORTS_SENSOR_STORE_CONFIG_H_ diff --git a/include/robot_sensor_ports/sensor_type.h b/include/robot_sensor_ports/sensor_type.h new file mode 100644 index 0000000..14e2aa1 --- /dev/null +++ b/include/robot_sensor_ports/sensor_type.h @@ -0,0 +1,97 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_sensor_ports — compile-time identity of a stored message type. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROBOT_SENSOR_PORTS_SENSOR_TYPE_H_ +#define ROBOT_SENSOR_PORTS_SENSOR_TYPE_H_ + +#include +#include + +namespace robot_sensor_ports +{ + +/** + * @struct SensorType + * @brief Stable identity string for a message type carried by the store. + * + * The store is type-erased: it hands out `boost::shared_ptr` and the caller casts back. + * A cast to the wrong type is undefined behaviour that does not crash — it reads garbage and the + * damage surfaces somewhere else entirely. The only thing standing between the erasure and that + * bug is an identity string that both sides agree on, which is what this trait provides. + * + * `typeid` is deliberately not used. Comparing `std::type_index` across a `.so` boundary depends on + * symbol visibility and on how the dynamic linker merges typeinfo; when it goes wrong it goes wrong + * silently. An explicit string cannot. + * + * The primary template is intentionally left undefined: using an unregistered type is a compile + * error at the call site, not a runtime surprise. + * + * @note The generated headers in this workspace are stripped down — unlike upstream gencpp they + * carry no `message_traits`, so there is no `DataType::value()` to borrow. Hence this. + */ +template +struct SensorType; + +/** + * @brief Register one message type with the store. + * + * @param Msg Fully qualified message type. + * @param IdString Identity string, by convention `"/"`. + * + * Adding a message type to the system costs exactly one line of this macro. It changes no + * interface and forces no rebuild of unrelated plugins — see @ref SensorReader for why that + * matters at the Boost.DLL boundary. + */ +#define ROBOT_SENSOR_PORTS_REGISTER_TYPE(Msg, IdString) \ + template <> \ + struct SensorType \ + { \ + static const char* id() \ + { \ + return IdString; \ + } \ + }; + +/** + * @brief Runtime table mapping the short name an operator types in YAML to the full identity. + * + * YAML says `data_type: LaserScan`; everything below the config parser uses + * `robot_sensor_msgs/LaserScan`. Operators get the short form, error messages get the unambiguous + * one. + * + * The table is filled from the same list that generates the @ref SensorType specialisations, so a + * type can never be known to one and not the other. + */ +class TypeNames +{ +public: + /// @brief Add one identity. `full_id` must contain a '/'; the part after it is the short name. + static void add(const std::string& full_id); + + /** + * @brief Resolve what the YAML said into a full identity. + * + * Accepts either form: `LaserScan` or `robot_sensor_msgs/LaserScan`. + * + * @param[out] full_id Resolved identity, untouched on failure. + * @param[out] error Human-readable reason, listing the candidates when the short name is + * ambiguous or unknown. + * @return false when unknown, or when two registered packages share that short name. + * + * @note Ambiguity is a hard failure on purpose. Short names span packages, so picking one for the + * operator would mean silently storing a different message than the one they meant. + */ + static bool resolve(const std::string& name, std::string& full_id, std::string& error); + + /// @brief Every registered identity, in full form, sorted. For error messages and diagnostics. + static std::vector all(); +}; + +} // namespace robot_sensor_ports + +#endif // ROBOT_SENSOR_PORTS_SENSOR_TYPE_H_ diff --git a/include/robot_sensor_ports/sensor_types.h b/include/robot_sensor_ports/sensor_types.h new file mode 100644 index 0000000..7aa24c0 --- /dev/null +++ b/include/robot_sensor_ports/sensor_types.h @@ -0,0 +1,91 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_sensor_ports — the message types of robot_sensor_msgs, registered with the store. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROBOT_SENSOR_PORTS_SENSOR_TYPES_H_ +#define ROBOT_SENSOR_PORTS_SENSOR_TYPES_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace robot_sensor_ports +{ + +/** + * @def ROBOT_SENSOR_PORTS_TYPE_LIST + * @brief Every message type this package registers out of the box. + * + * One list, two expansions: the header below turns it into @ref SensorType specialisations, and + * `sensor_type.cpp` turns the same list into the short-name table. Keeping both from one source is + * what makes it impossible for a type to be castable but not nameable in YAML, or the reverse. + * + * Adding a type is one line here. It changes no interface, so no plugin needs rebuilding. + * + * + * Two message types of `robot_sensor_msgs` are missing on purpose, because their headers do not + * compile in this workspace at all: + * - `Imu.h` still carries the un-ported ROS tail, specialising `ros::message_operations::Printer`, + * a template that does not exist here; + * - `TimeReference.h` declares its field as `ros::Time` instead of `robot::Time`. + * Both are pre-existing faults in `robot_sensor_msgs`, not limitations of the store. Fix those two + * headers and each becomes one line here, nothing more. + * + * Types from other packages do not belong in this list — that would drag their dependencies into + * everything that includes this header. Register those where they live, with + * @ref ROBOT_SENSOR_PORTS_REGISTER_TYPE plus a `TypeNames::add()` call at startup. + */ +#define ROBOT_SENSOR_PORTS_TYPE_LIST(X) \ + X(::robot_sensor_msgs::BatteryState, "robot_sensor_msgs/BatteryState") \ + X(::robot_sensor_msgs::CameraInfo, "robot_sensor_msgs/CameraInfo") \ + X(::robot_sensor_msgs::ChannelFloat32, "robot_sensor_msgs/ChannelFloat32") \ + X(::robot_sensor_msgs::CompressedImage, "robot_sensor_msgs/CompressedImage") \ + X(::robot_sensor_msgs::DepthCameraData, "robot_sensor_msgs/DepthCameraData") \ + X(::robot_sensor_msgs::FluidPressure, "robot_sensor_msgs/FluidPressure") \ + X(::robot_sensor_msgs::Illuminance, "robot_sensor_msgs/Illuminance") \ + X(::robot_sensor_msgs::Image, "robot_sensor_msgs/Image") \ + X(::robot_sensor_msgs::JointState, "robot_sensor_msgs/JointState") \ + X(::robot_sensor_msgs::Joy, "robot_sensor_msgs/Joy") \ + X(::robot_sensor_msgs::JoyFeedback, "robot_sensor_msgs/JoyFeedback") \ + X(::robot_sensor_msgs::JoyFeedbackArray, "robot_sensor_msgs/JoyFeedbackArray") \ + X(::robot_sensor_msgs::LaserEcho, "robot_sensor_msgs/LaserEcho") \ + X(::robot_sensor_msgs::LaserScan, "robot_sensor_msgs/LaserScan") \ + X(::robot_sensor_msgs::MultiEchoLaserScan, "robot_sensor_msgs/MultiEchoLaserScan") \ + X(::robot_sensor_msgs::PointCloud, "robot_sensor_msgs/PointCloud") \ + X(::robot_sensor_msgs::PointCloud2, "robot_sensor_msgs/PointCloud2") \ + X(::robot_sensor_msgs::PointField, "robot_sensor_msgs/PointField") \ + X(::robot_sensor_msgs::Range, "robot_sensor_msgs/Range") \ + X(::robot_sensor_msgs::RegionOfInterest, "robot_sensor_msgs/RegionOfInterest") \ + X(::robot_sensor_msgs::RelativeHumidity, "robot_sensor_msgs/RelativeHumidity") \ + X(::robot_sensor_msgs::Temperature, "robot_sensor_msgs/Temperature") + +ROBOT_SENSOR_PORTS_TYPE_LIST(ROBOT_SENSOR_PORTS_REGISTER_TYPE) + +} // namespace robot_sensor_ports + +#endif // ROBOT_SENSOR_PORTS_SENSOR_TYPES_H_ diff --git a/include/robot_sensor_ports/sensor_writer.h b/include/robot_sensor_ports/sensor_writer.h new file mode 100644 index 0000000..3ebf6be --- /dev/null +++ b/include/robot_sensor_ports/sensor_writer.h @@ -0,0 +1,87 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_sensor_ports — write port onto the shared sensor store. + * + * Author: DuongTD + *********************************************************************/ +#ifndef ROBOT_SENSOR_PORTS_SENSOR_WRITER_H_ +#define ROBOT_SENSOR_PORTS_SENSOR_WRITER_H_ + +#include + +#include +#include + +#include +#include + +namespace robot_sensor_ports +{ + +/** + * @class SensorWriter + * @brief Write port onto the shared sensor store. Held by the runtime, never by a plugin. + * + * The store keeps **raw** readings. Anything that needs filtering is filtered before it gets here, + * by whoever owns that filter — the store has no idea any filter exists. That split is deliberate: + * a costmap wants outliers removed, a dock detector wants the true shape of what the laser saw, and + * a store that decided for both would be wrong for one of them. + */ +class SensorWriter +{ +public: + virtual ~SensorWriter() = default; + + /** + * @brief Publish one reading. + * + * @param type_id Identity from `SensorType::id()`. + * @param topic Topic name; must be one of the configured ones. + * @param data The reading. Ownership is shared, and the store never writes through it. + * @param stamp When the reading was taken. Used for TF lookups and for age, never for ordering. + * @return false when the topic is not configured, when the type does not match the configured + * one, or when @p data is null. Each rejection is logged once per topic and counted in + * @ref SensorInfo::rejected. + * + * Unconfigured topics are dropped rather than added on the fly. Otherwise a depth cloud nobody + * declared starts costing megabytes per frame, and the config stops being the answer to "what is + * this process holding". + * + * @warning Whatever is passed here must not be modified afterwards. Readers hold that exact + * object without a lock; writing into it while one of them walks its ranges is a race + * that produces half-old, half-new data rather than a crash. Publish a new message and + * let the old one go. + */ + virtual bool putErased(const char* type_id, const std::string& topic, + const boost::shared_ptr& data, const robot::Time& stamp) = 0; +}; + +/** + * @brief Typed publish, zero copy. + * + * Prefer this wherever the producer already holds a shared pointer — `addDepthCameraData` receives + * a `ConstPtr` and copying a megabyte to store it would be waste with nothing gained. + */ +template +bool put(SensorWriter& writer, const std::string& topic, const boost::shared_ptr& msg, + const robot::Time& stamp) +{ + return writer.putErased(SensorType::id(), topic, msg, stamp); +} + +/** + * @brief Typed publish, copying once into a fresh immutable reading. + * + * For producers holding a message by value. The copy happens here, not under the store's lock. + */ +template +bool put(SensorWriter& writer, const std::string& topic, const M& msg, const robot::Time& stamp) +{ + return writer.putErased(SensorType::id(), topic, boost::make_shared(msg), stamp); +} + +} // namespace robot_sensor_ports + +#endif // ROBOT_SENSOR_PORTS_SENSOR_WRITER_H_ diff --git a/package.xml b/package.xml new file mode 100644 index 0000000..4c0dc53 --- /dev/null +++ b/package.xml @@ -0,0 +1,49 @@ + + robot_sensor_ports + 0.1.0 + + Kho cảm biến dùng chung cho navigation runtime, cộng hai cổng hẹp nhìn vào nó. + + Vấn đề gói này giải: dữ liệu cảm biến thô đi vào runtime rồi biến mất vào costmap. Bộ dò dock + cần đúng mảng `ranges` theo thứ tự tia — costmap đã inflate và xoá thứ tự đó nên không dựng lại + được. Consumer thứ hai (local planner học tăng cường) cũng cần bản thô. Kho này giữ một bản duy + nhất và chia cho mọi người. + + Kho giữ bản THÔ. Muốn lọc thì lọc trước khi đẩy vào; kho không biết bộ lọc nào tồn tại. Costmap + và kho cố ý nhìn hai bản khác nhau khi bật lọc — costmap muốn bớt điểm nhiễu, bộ dò muốn hình + dạng thật. + + Chia sẻ bằng `shared_ptr` tới bản BẤT BIẾN: producer dựng bản mới rồi tráo con trỏ, không sửa + tại chỗ. Reader giữ khoá đúng lúc copy con trỏ rồi đọc ngoài khoá. Hai consumer đọc cùng một + topic dùng chung một bản, không phải mỗi người một bản copy. + + Interface xoá kiểu và không có template nào nằm trên ranh giới `.so`: thêm một loại message chỉ + tốn một dòng trong danh sách, không đổi interface và không bắt plugin nào build lại. Kiểu sai + thì bị từ chối kèm log, không bao giờ cast bừa. + + Không chạy roscpp/ROS master; dùng lớp ROS-like robot_* (robot_cpp, robot_time, + robot_sensor_msgs). + + T800 Robotics + T800 Robotics + BSD + + catkin + + robot_cpp + robot_cpp + + robot_time + robot_time + + + robot_sensor_msgs + robot_sensor_msgs + + robot_xmlrpcpp + robot_xmlrpcpp + + yaml-cpp + yaml-cpp + + diff --git a/src/sensor_store.cpp b/src/sensor_store.cpp new file mode 100644 index 0000000..93e888b --- /dev/null +++ b/src/sensor_store.cpp @@ -0,0 +1,398 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_sensor_ports — implementation of the shared sensor store. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include + +#include + +namespace robot_sensor_ports +{ +namespace +{ + +/** + * @brief Weight of a new interval in the smoothed rate. + * + * Low enough that one late frame does not make the reported rate jump, high enough that a sensor + * genuinely slowing down shows up within a second or so. The number is only ever read by a human + * looking at diagnostics, so it does not need to be tight. + */ +constexpr double kRateSmoothing = 0.2; + +/// Longest interval still treated as a real one. Beyond this the sensor stopped and came back, and +/// averaging that gap into the rate would report a number that never existed. +constexpr double kMaxRateInterval = 2.0; // [s] + +} // namespace + +bool SensorStore::configure(const SensorStoreConfig& config, std::string& error) +{ + // Validate everything before touching state: a config rejected halfway would leave the store + // holding some topics and not others, which is worse than not starting. + for (std::size_t i = 0; i < config.sensors.size(); ++i) + { + const SensorEntryConfig& entry = config.sensors[i]; + + if (entry.topic.empty()) + { + error = "sensors[" + std::to_string(i) + "]: topic is empty"; + return false; + } + if (entry.data_type.empty()) + { + error = "sensors[" + std::to_string(i) + "] ('" + entry.topic + "'): data_type is empty"; + return false; + } + if (entry.capacity < 1) + { + error = "sensors[" + std::to_string(i) + "] ('" + entry.topic + "'): capacity must be >= 1"; + return false; + } + if (!std::isfinite(entry.max_age) || entry.max_age <= 0.0) + { + error = "sensors[" + std::to_string(i) + "] ('" + entry.topic + "'): max_age must be > 0"; + return false; + } + } + + std::lock_guard lock(mutex_); + + slots_.clear(); + logged_.clear(); + + for (const SensorEntryConfig& entry : config.sensors) + { + Slot slot; + slot.data_type = entry.data_type; + slot.capacity = entry.capacity; + slot.max_age = entry.max_age; + slots_[entry.topic] = slot; + } + + return true; +} + +void SensorStore::clear() +{ + std::lock_guard lock(mutex_); + + for (auto& entry : slots_) + { + Slot& slot = entry.second; + slot.ring.clear(); + slot.have_last_stamp = false; + slot.rate_hz = 0.0; + // `sequence` deliberately keeps counting. Readers hold cursors; restarting the count would make + // a stale cursor look newer than fresh data and freeze that reader for good. + } +} + +bool SensorStore::clearTopic(const std::string& topic) +{ + std::lock_guard lock(mutex_); + + const auto it = slots_.find(topic); + if (it == slots_.end()) + { + return false; + } + + Slot& slot = it->second; + slot.ring.clear(); + slot.have_last_stamp = false; + slot.rate_hz = 0.0; + // `sequence` keeps counting, for the same reason as in clear(). + return true; +} + +std::size_t SensorStore::clearOfType(const char* type_id) +{ + if (type_id == nullptr) + { + return 0; + } + + std::lock_guard lock(mutex_); + + std::size_t affected = 0; + for (auto& entry : slots_) + { + Slot& slot = entry.second; + if (slot.data_type != type_id) + { + continue; + } + slot.ring.clear(); + slot.have_last_stamp = false; + slot.rate_hz = 0.0; + ++affected; + } + + return affected; +} + +bool SensorStore::configured() const +{ + std::lock_guard lock(mutex_); + return !slots_.empty(); +} + +bool SensorStore::shouldLog(const std::string& key) const +{ + return logged_.insert(key).second; +} + +void SensorStore::describeLocked(const std::string& topic, const Slot& slot, SensorInfo& out) +{ + out.topic = topic; + out.data_type = slot.data_type; + out.sequence = slot.sequence; + out.stamp = slot.ring.empty() ? robot::Time() : slot.ring.back().stamp; + out.rate_hz = slot.rate_hz; + out.max_age = slot.max_age; + out.capacity = slot.capacity; + out.size = slot.ring.size(); + out.rejected = slot.rejected; +} + +// ================================================================================================ +// SensorWriter +// ================================================================================================ + +bool SensorStore::putErased(const char* type_id, const std::string& topic, + const boost::shared_ptr& data, const robot::Time& stamp) +{ + if (type_id == nullptr || data == nullptr) + { + return false; + } + + std::lock_guard lock(mutex_); + + const auto it = slots_.find(topic); + if (it == slots_.end()) + { + // Dropping rather than adding on the fly: an undeclared depth cloud would otherwise start + // costing megabytes a frame, and the config would stop describing what this process holds. + // + // Silent when nothing at all is declared. A runtime with no consumer of raw sensor data has no + // store, and warning once per topic about a feature nobody switched on is how a working system + // starts printing errors after an upgrade. Once even one topic is declared, a missing one is a + // real mistake and gets said out loud. + if (!slots_.empty() && shouldLog("put/unknown/" + topic)) + { + robot::log_warning("[robot_sensor_ports] SensorStore: dropping '%s' — not declared in " + "sensor_store/sensors. Add it there or stop publishing it.\n", + topic.c_str()); + } + return false; + } + + Slot& slot = it->second; + + if (slot.data_type != type_id) + { + // Storing it would let a later reader cast the wrong way. That cast reads garbage instead of + // crashing, and the damage shows up somewhere unrelated. + ++slot.rejected; + if (shouldLog("put/type/" + topic)) + { + robot::log_error("[robot_sensor_ports] SensorStore: '%s' is declared as '%s' but something " + "published '%s'. The reading is dropped.\n", + topic.c_str(), slot.data_type.c_str(), type_id); + } + return false; + } + + // Rate from stamp deltas rather than from arrival time: it stays right under simulated time, and + // it needs no clock of its own — this package must never call robot::Time::now(), which throws + // before a NodeHandle exists and reads the wall clock when simulated time is in use. + // + // Intervals that are zero, negative or absurdly long say nothing about rate: unstamped messages, + // a host restart, a jump to simulated time, a sensor that stopped and came back. Those leave the + // last figure alone rather than averaging in a number that never happened. Ordering is + // `sequence`'s job, so none of this can stall a reader. + if (slot.have_last_stamp) + { + const double interval = stamp.toSec() - slot.last_stamp.toSec(); + if (interval > 0.0 && interval < kMaxRateInterval) + { + const double instant = 1.0 / interval; + slot.rate_hz = slot.rate_hz > 0.0 + ? (1.0 - kRateSmoothing) * slot.rate_hz + kRateSmoothing * instant + : instant; + } + } + slot.last_stamp = stamp; + slot.have_last_stamp = true; + + SensorSample sample; + sample.data = data; + sample.sequence = ++slot.sequence; + sample.stamp = stamp; + + slot.ring.push_back(sample); + while (slot.ring.size() > slot.capacity) + { + slot.ring.pop_front(); + } + + return true; +} + +// ================================================================================================ +// SensorReader +// ================================================================================================ + +bool SensorStore::latestErased(const char* type_id, const std::string& topic, uint64_t& since, + SensorSample& out) const +{ + if (type_id == nullptr) + { + return false; + } + + std::lock_guard lock(mutex_); + + const auto it = slots_.find(topic); + if (it == slots_.end()) + { + if (shouldLog("read/unknown/" + topic)) + { + robot::log_error("[robot_sensor_ports] SensorStore: '%s' was requested but is not declared " + "in sensor_store/sensors.\n", + topic.c_str()); + } + return false; + } + + const Slot& slot = it->second; + + if (slot.data_type != type_id) + { + if (shouldLog("read/type/" + topic)) + { + robot::log_error("[robot_sensor_ports] SensorStore: '%s' holds '%s' but was read as '%s'. " + "Refusing — casting it would be undefined behaviour.\n", + topic.c_str(), slot.data_type.c_str(), type_id); + } + return false; + } + + if (slot.ring.empty() || slot.ring.back().sequence <= since) + { + return false; // Nothing yet, or nothing new. Not an error, and far too common to log. + } + + out = slot.ring.back(); + since = out.sequence; + return true; +} + +bool SensorStore::historyErased(const char* type_id, const std::string& topic, std::size_t count, + std::vector& out) const +{ + out.clear(); + + if (type_id == nullptr || count == 0) + { + return false; + } + + std::lock_guard lock(mutex_); + + const auto it = slots_.find(topic); + if (it == slots_.end()) + { + if (shouldLog("read/unknown/" + topic)) + { + robot::log_error("[robot_sensor_ports] SensorStore: '%s' was requested but is not declared " + "in sensor_store/sensors.\n", + topic.c_str()); + } + return false; + } + + const Slot& slot = it->second; + + if (slot.data_type != type_id) + { + if (shouldLog("read/type/" + topic)) + { + robot::log_error("[robot_sensor_ports] SensorStore: '%s' holds '%s' but was read as '%s'. " + "Refusing — casting it would be undefined behaviour.\n", + topic.c_str(), slot.data_type.c_str(), type_id); + } + return false; + } + + if (slot.ring.empty()) + { + return false; + } + + const std::size_t take = std::min(count, slot.ring.size()); + out.reserve(take); + + // Oldest first, so a caller stacking frames gets them in the order they happened. + for (std::size_t i = slot.ring.size() - take; i < slot.ring.size(); ++i) + { + out.push_back(slot.ring[i]); + } + + return true; +} + +bool SensorStore::has(const char* type_id, const std::string& topic) const +{ + if (type_id == nullptr) + { + return false; + } + + std::lock_guard lock(mutex_); + + const auto it = slots_.find(topic); + return it != slots_.end() && it->second.data_type == type_id; +} + +bool SensorStore::describe(const std::string& topic, SensorInfo& out) const +{ + std::lock_guard lock(mutex_); + + const auto it = slots_.find(topic); + if (it == slots_.end()) + { + return false; + } + + describeLocked(it->first, it->second, out); + return true; +} + +std::vector SensorStore::inventory() const +{ + std::lock_guard lock(mutex_); + + std::vector all; + all.reserve(slots_.size()); + + for (const auto& entry : slots_) + { + SensorInfo info; + describeLocked(entry.first, entry.second, info); + all.push_back(info); + } + + return all; +} + +} // namespace robot_sensor_ports diff --git a/src/sensor_store_config.cpp b/src/sensor_store_config.cpp new file mode 100644 index 0000000..c72bccd --- /dev/null +++ b/src/sensor_store_config.cpp @@ -0,0 +1,133 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_sensor_ports — reading and validating the sensor_store section. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include + +#include + +#include +#include + +namespace robot_sensor_ports +{ +namespace +{ + +constexpr std::size_t kDefaultCapacity = 1; +constexpr double kDefaultMaxAge = 0.5; // [s] + +std::string at(const std::string& key, std::size_t index) +{ + return key + "[" + std::to_string(index) + "]"; +} + +} // namespace + +bool SensorStoreConfig::load(robot::NodeHandle& nh, const std::string& ns, SensorStoreConfig& out, + std::string& error) +{ + const std::string key = ns.empty() ? std::string("sensors") : ns + "/sensors"; + + YAML::Node list; + if (!nh.getParam(key, list) || !list.IsSequence()) + { + // A runtime with no consumer of raw sensor data holds nothing. That is an answer, not a fault, + // so it must not stop the robot from starting. + robot::log_info("[robot_sensor_ports] SensorStoreConfig: '%s' declares no sensor; the shared " + "store will stay empty.\n", + key.c_str()); + out.sensors.clear(); + return true; + } + + std::vector parsed; + std::set seen_topics; + + for (std::size_t i = 0; i < list.size(); ++i) + { + const YAML::Node& node = list[i]; + + if (!node.IsMap()) + { + error = at(key, i) + " is not a map"; + return false; + } + + SensorEntryConfig entry; + + try + { + if (!node["topic"]) + { + error = at(key, i) + " has no 'topic' key"; + return false; + } + entry.topic = node["topic"].as(); + + if (!node["data_type"]) + { + error = at(key, i) + " ('" + entry.topic + "') has no 'data_type' key"; + return false; + } + const std::string declared = node["data_type"].as(); + + entry.capacity = node["capacity"] ? node["capacity"].as() : kDefaultCapacity; + entry.max_age = node["max_age"] ? node["max_age"].as() : kDefaultMaxAge; + + // Short form resolves to the full identity here and nowhere else. Operators type + // `LaserScan`; every layer below this line, and every error message, uses + // `robot_sensor_msgs/LaserScan`. + std::string resolve_error; + if (!TypeNames::resolve(declared, entry.data_type, resolve_error)) + { + error = at(key, i) + " ('" + entry.topic + "'): " + resolve_error; + return false; + } + } + catch (const YAML::Exception& ex) + { + error = at(key, i) + " could not be read: " + ex.what(); + return false; + } + + if (entry.topic.empty()) + { + error = at(key, i) + ": topic is empty"; + return false; + } + if (!seen_topics.insert(entry.topic).second) + { + // Two entries for one topic means one of them is dead config, and which one wins would come + // down to declaration order. Say so instead. + error = at(key, i) + ": topic '" + entry.topic + "' is declared more than once"; + return false; + } + if (entry.capacity < 1) + { + error = at(key, i) + " ('" + entry.topic + "'): capacity must be >= 1"; + return false; + } + if (!std::isfinite(entry.max_age) || entry.max_age <= 0.0) + { + error = at(key, i) + " ('" + entry.topic + "'): max_age must be a finite value > 0"; + return false; + } + + parsed.push_back(entry); + } + + // Assign only once everything parsed: a caller that ignores the return value still ends up with + // the old config rather than a half-built one. + out.sensors = parsed; + return true; +} + +} // namespace robot_sensor_ports diff --git a/src/sensor_type.cpp b/src/sensor_type.cpp new file mode 100644 index 0000000..2b5748f --- /dev/null +++ b/src/sensor_type.cpp @@ -0,0 +1,148 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_sensor_ports — short-name table for registered message types. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include +#include +#include + +#include + +namespace robot_sensor_ports +{ +namespace +{ + +/// Short name -> every full identity claiming it. More than one entry means the short name is +/// ambiguous and must not be resolved for the operator. +using ShortIndex = std::map>; + +struct Table +{ + std::mutex mutex; + ShortIndex by_short; + std::set full; +}; + +std::string shortNameOf(const std::string& full_id) +{ + const std::size_t slash = full_id.rfind('/'); + return slash == std::string::npos ? full_id : full_id.substr(slash + 1); +} + +void insertLocked(Table& t, const std::string& full_id) +{ + t.full.insert(full_id); + t.by_short[shortNameOf(full_id)].insert(full_id); +} + +/** + * @brief The one table, seeded on first use. + * + * A function-local static rather than a namespace-scope object: this is reached from config parsing + * that may itself run while another translation unit is still initialising, and function-local + * initialisation is ordered by first use instead of by link order. + * + * Seeding writes the maps directly instead of calling `TypeNames::add`, which would re-enter this + * function while it is still running. + */ +Table& table() +{ + static Table instance; + static std::once_flag once; + + std::call_once(once, [] { +// Same list that generates the SensorType specialisations, so the two can never disagree about +// which types exist. +#define ROBOT_SENSOR_PORTS_SEED(Msg, IdString) insertLocked(instance, IdString); + ROBOT_SENSOR_PORTS_TYPE_LIST(ROBOT_SENSOR_PORTS_SEED) +#undef ROBOT_SENSOR_PORTS_SEED + }); + + return instance; +} + +std::string join(const std::set& values) +{ + std::string joined; + for (const std::string& value : values) + { + if (!joined.empty()) + { + joined += ", "; + } + joined += value; + } + return joined; +} + +} // namespace + +void TypeNames::add(const std::string& full_id) +{ + if (full_id.empty()) + { + return; + } + + Table& t = table(); + std::lock_guard lock(t.mutex); + + insertLocked(t, full_id); +} + +bool TypeNames::resolve(const std::string& name, std::string& full_id, std::string& error) +{ + if (name.empty()) + { + error = "data_type is empty"; + return false; + } + + Table& t = table(); + std::lock_guard lock(t.mutex); + + // Full form first: it is unambiguous by construction, so someone who typed it deserves to be + // taken at their word even if the short half collides with another package. + if (t.full.find(name) != t.full.end()) + { + full_id = name; + return true; + } + + const auto it = t.by_short.find(name); + if (it == t.by_short.end()) + { + error = "unknown data_type '" + name + "'; known types are: " + join(t.full); + return false; + } + + if (it->second.size() > 1) + { + // Picking one would silently store a different message than the operator meant. Two packages + // sharing a short name is rare, and the fix — write the full form — is one word. + error = "ambiguous data_type '" + name + "'; it matches " + join(it->second) + + ". Write the full form."; + return false; + } + + full_id = *it->second.begin(); + return true; +} + +std::vector TypeNames::all() +{ + Table& t = table(); + std::lock_guard lock(t.mutex); + + return std::vector(t.full.begin(), t.full.end()); +} + +} // namespace robot_sensor_ports diff --git a/test/config/sensor_store_params.yaml b/test/config/sensor_store_params.yaml new file mode 100644 index 0000000..f234bb7 --- /dev/null +++ b/test/config/sensor_store_params.yaml @@ -0,0 +1,97 @@ +# ================================================================================================= +# Cây config của test — KHÔNG phải bản chạy thật. Mỗi khối là một ca kiểm riêng. +# ================================================================================================= + +# Ca thường: hai lidar, giữ bản mới nhất. +sensor_store: + sensors: + - topic: /f_scan + data_type: LaserScan # dạng ngắn + capacity: 1 + max_age: 0.5 # [s] + + - topic: /b_scan + data_type: robot_sensor_msgs/LaserScan # dạng đầy đủ, phải tương đương + capacity: 1 + max_age: 0.5 + +# Thiếu capacity và max_age -> phải rơi về default (1 và 0.5), không được từ chối. +sensor_store_defaults: + sensors: + - topic: /f_scan + data_type: LaserScan + +# Stack frame: capacity > 1 cho consumer cần nhiều frame liên tiếp. +sensor_store_stack: + sensors: + - topic: /f_scan + data_type: LaserScan + capacity: 5 + max_age: 0.5 + +# Nhiều loại cảm biến cùng lúc — kho không ưu ái loại nào. +sensor_store_mixed: + sensors: + - topic: /f_scan + data_type: LaserScan + capacity: 1 + max_age: 0.5 + + - topic: /camera/depth/data + data_type: DepthCameraData + capacity: 1 + max_age: 0.3 # [s] depth chậm hơn lidar nhưng stale thì nguy hơn + + - topic: /front_cloud + data_type: PointCloud2 + capacity: 1 + max_age: 0.4 + +# Không khai sensor nào: hợp lệ, kho rỗng. Runtime không có consumer nào thì đây là câu trả lời +# đúng, không phải lý do để không khởi động. +sensor_store_empty: + other_key: 1 + +# --- Các khối dưới đây đều PHẢI bị từ chối lúc boot ----------------------------------------------- + +# data_type không có thật. +sensor_store_bad_type: + sensors: + - topic: /f_scan + data_type: LazerScan + +# thiếu khoá data_type. +sensor_store_missing_type: + sensors: + - topic: /f_scan + capacity: 1 + +# thiếu khoá topic. +sensor_store_missing_topic: + sensors: + - data_type: LaserScan + +# capacity < 1: không giữ bản nào thì consumer không bao giờ đọc được gì. +sensor_store_bad_capacity: + sensors: + - topic: /f_scan + data_type: LaserScan + capacity: 0 + +# max_age <= 0: mọi bản đều stale ngay khi tới. +sensor_store_bad_max_age: + sensors: + - topic: /f_scan + data_type: LaserScan + max_age: 0.0 + +# Một topic khai hai lần: một trong hai là config chết, và cái nào thắng chỉ do thứ tự khai. +sensor_store_duplicate_topic: + sensors: + - topic: /f_scan + data_type: LaserScan + capacity: 1 + + - topic: /f_scan + data_type: LaserScan + capacity: 5 diff --git a/test/sensor_store_config_test.cpp b/test/sensor_store_config_test.cpp new file mode 100644 index 0000000..30d8907 --- /dev/null +++ b/test/sensor_store_config_test.cpp @@ -0,0 +1,187 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Kiểm việc nạp khối `sensor_store` từ YAML. + * + * Mọi ca hỏng ở đây đều phải nổ LÚC BOOT. Config sai mà chỉ lộ ra giữa ca là kiểu lỗi tệ nhất: robot + * đã ở ngoài hiện trường, và triệu chứng chỉ là một consumer im lặng không nhận được gì. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include + +#include + +#include +#include + +namespace +{ +using robot_sensor_ports::SensorStore; +using robot_sensor_ports::SensorStoreConfig; + +bool load(const std::string& ns, SensorStoreConfig& config, std::string& error) +{ + robot::NodeHandle nh; + return SensorStoreConfig::load(nh, ns, config, error); +} + +TEST(SensorStoreConfig, ReadsTheTopicsAsWritten) +{ + SensorStoreConfig config; + std::string error; + + ASSERT_TRUE(load("sensor_store", config, error)) << error; + ASSERT_EQ(config.sensors.size(), 2u); + + EXPECT_EQ(config.sensors[0].topic, "/f_scan"); + EXPECT_EQ(config.sensors[0].capacity, 1u); + EXPECT_DOUBLE_EQ(config.sensors[0].max_age, 0.5); + EXPECT_EQ(config.sensors[1].topic, "/b_scan"); +} + +TEST(SensorStoreConfig, TheShortAndFullFormsMeanTheSameThing) +{ + SensorStoreConfig config; + std::string error; + + ASSERT_TRUE(load("sensor_store", config, error)) << error; + ASSERT_EQ(config.sensors.size(), 2u); + + // `/f_scan` khai dạng ngắn, `/b_scan` khai dạng đầy đủ. Người vận hành gõ ngắn cho nhanh, mọi + // tầng dưới dòng này chỉ thấy một dạng duy nhất. + EXPECT_EQ(config.sensors[0].data_type, "robot_sensor_msgs/LaserScan"); + EXPECT_EQ(config.sensors[1].data_type, "robot_sensor_msgs/LaserScan"); +} + +TEST(SensorStoreConfig, FallsBackToDefaultsForTheOptionalKeys) +{ + SensorStoreConfig config; + std::string error; + + ASSERT_TRUE(load("sensor_store_defaults", config, error)) << error; + ASSERT_EQ(config.sensors.size(), 1u); + + EXPECT_EQ(config.sensors[0].capacity, 1u); + EXPECT_DOUBLE_EQ(config.sensors[0].max_age, 0.5); +} + +TEST(SensorStoreConfig, ReadsAFrameStackDepth) +{ + SensorStoreConfig config; + std::string error; + + ASSERT_TRUE(load("sensor_store_stack", config, error)) << error; + ASSERT_EQ(config.sensors.size(), 1u); + EXPECT_EQ(config.sensors[0].capacity, 5u); +} + +TEST(SensorStoreConfig, HandlesEveryKindOfSensorTheSameWay) +{ + SensorStoreConfig config; + std::string error; + + ASSERT_TRUE(load("sensor_store_mixed", config, error)) << error; + ASSERT_EQ(config.sensors.size(), 3u); + + EXPECT_EQ(config.sensors[0].data_type, "robot_sensor_msgs/LaserScan"); + EXPECT_EQ(config.sensors[1].data_type, "robot_sensor_msgs/DepthCameraData"); + EXPECT_EQ(config.sensors[2].data_type, "robot_sensor_msgs/PointCloud2"); + + // Và kho nhận được nguyên khối đó, không loại nào phải xử lý riêng. + SensorStore store; + ASSERT_TRUE(store.configure(config, error)) << error; + EXPECT_EQ(store.inventory().size(), 3u); +} + +TEST(SensorStoreConfig, NoSensorSectionIsFineAndLeavesTheStoreEmpty) +{ + SensorStoreConfig config; + std::string error; + + // Runtime không có consumer nào của dữ liệu thô thì không giữ gì. Đó là câu trả lời, không phải + // lỗi, nên tuyệt đối không được chặn robot khởi động. + ASSERT_TRUE(load("sensor_store_empty", config, error)) << error; + EXPECT_TRUE(config.sensors.empty()); +} + +TEST(SensorStoreConfig, RejectsADataTypeThatDoesNotExist) +{ + SensorStoreConfig config; + std::string error; + + EXPECT_FALSE(load("sensor_store_bad_type", config, error)); + EXPECT_NE(error.find("LazerScan"), std::string::npos); + // Lỗi phải chỉ ra được entry nào, và kèm danh sách tên thật. + EXPECT_NE(error.find("/f_scan"), std::string::npos); + EXPECT_NE(error.find("robot_sensor_msgs/LaserScan"), std::string::npos); +} + +TEST(SensorStoreConfig, RejectsAnEntryMissingItsKeys) +{ + SensorStoreConfig config; + std::string error; + + EXPECT_FALSE(load("sensor_store_missing_type", config, error)); + EXPECT_NE(error.find("data_type"), std::string::npos); + + EXPECT_FALSE(load("sensor_store_missing_topic", config, error)); + EXPECT_NE(error.find("topic"), std::string::npos); +} + +TEST(SensorStoreConfig, RejectsACapacityThatCanNeverHoldAnything) +{ + SensorStoreConfig config; + std::string error; + + EXPECT_FALSE(load("sensor_store_bad_capacity", config, error)); + EXPECT_NE(error.find("capacity"), std::string::npos); +} + +TEST(SensorStoreConfig, RejectsAMaxAgeThatMakesEveryReadingStale) +{ + SensorStoreConfig config; + std::string error; + + EXPECT_FALSE(load("sensor_store_bad_max_age", config, error)); + EXPECT_NE(error.find("max_age"), std::string::npos); +} + +TEST(SensorStoreConfig, RejectsTheSameTopicDeclaredTwice) +{ + SensorStoreConfig config; + std::string error; + + // Một trong hai khai là config chết, và cái nào thắng chỉ do thứ tự viết. Nói ra thay vì chọn. + EXPECT_FALSE(load("sensor_store_duplicate_topic", config, error)); + EXPECT_NE(error.find("/f_scan"), std::string::npos); +} + +TEST(SensorStoreConfig, ARejectedLoadLeavesThePreviousConfigAlone) +{ + SensorStoreConfig config; + std::string error; + + ASSERT_TRUE(load("sensor_store", config, error)) << error; + ASSERT_EQ(config.sensors.size(), 2u); + + // Người gọi bỏ qua giá trị trả về vẫn còn config cũ, không phải một cây nửa vời. + EXPECT_FALSE(load("sensor_store_bad_type", config, error)); + EXPECT_EQ(config.sensors.size(), 2u); +} + +} // namespace + +int main(int argc, char** argv) +{ +#ifdef ROBOT_SENSOR_PORTS_TEST_CONFIG_DIR + setenv("PNKX_NAV_CORE_CONFIG_DIR", ROBOT_SENSOR_PORTS_TEST_CONFIG_DIR, 0); +#endif + + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/sensor_store_test.cpp b/test/sensor_store_test.cpp new file mode 100644 index 0000000..2e395f7 --- /dev/null +++ b/test/sensor_store_test.cpp @@ -0,0 +1,527 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Kiểm kho cảm biến dùng chung. + * + * Bốn nhóm, theo đúng thứ tự rủi ro: + * 1. con trỏ — hai reader có dùng chung một bản không, bản cũ có sống đủ lâu không; + * 2. cursor — "chưa có gì mới" phải phân biệt được với "có bản mới trùng giá trị"; + * 3. từ chối — topic lạ và sai kiểu phải trả false, KHÔNG bao giờ cast bừa; + * 4. ring — capacity và thứ tự cũ-trước-mới. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include + +#include +#include + +namespace +{ +using robot_sensor_ports::SensorEntryConfig; +using robot_sensor_ports::SensorInfo; +using robot_sensor_ports::SensorSample; +using robot_sensor_ports::SensorStore; +using robot_sensor_ports::SensorStoreConfig; + +using LaserScan = robot_sensor_msgs::LaserScan; +using PointCloud2 = robot_sensor_msgs::PointCloud2; + +SensorEntryConfig entry(const std::string& topic, const std::string& data_type, + std::size_t capacity = 1, double max_age = 0.5) +{ + SensorEntryConfig e; + e.topic = topic; + e.data_type = data_type; + e.capacity = capacity; + e.max_age = max_age; + return e; +} + +LaserScan makeScan(float first_range) +{ + LaserScan scan; + scan.angle_min = -1.57f; + scan.angle_max = 1.57f; + scan.angle_increment = 0.01f; + scan.range_min = 0.05f; + scan.range_max = 10.0f; + scan.ranges.assign(315, 3.0f); + scan.ranges[0] = first_range; + return scan; +} + +/// Kho với một topic laser, dựng sẵn cho phần lớn test. +class StoreRig +{ +public: + explicit StoreRig(std::size_t capacity = 1) + { + SensorStoreConfig config; + config.sensors.push_back(entry("/f_scan", "robot_sensor_msgs/LaserScan", capacity)); + std::string error; + ok_ = store_.configure(config, error); + error_ = error; + } + + bool ok_ = false; + std::string error_; + SensorStore store_; +}; + +// ================================================================================================ +// 1. Chia sẻ bằng con trỏ +// ================================================================================================ + +TEST(SensorStore, TwoReadersShareOneCopyOfTheReading) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + + uint64_t cursor_a = 0; + uint64_t cursor_b = 0; + auto a = robot_sensor_ports::latest(rig.store_, "/f_scan", cursor_a); + auto b = robot_sensor_ports::latest(rig.store_, "/f_scan", cursor_b); + + ASSERT_TRUE(a); + ASSERT_TRUE(b); + // Cùng một object, không phải hai bản copy. Đây là thứ khiến một depth cloud hàng MB chia được + // cho nhiều consumer mà không nhân lên. + EXPECT_EQ(a.get(), b.get()); + EXPECT_FLOAT_EQ(a->ranges[0], 1.0f); +} + +TEST(SensorStore, AReadingStaysValidAfterItHasBeenReplaced) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + + uint64_t cursor = 0; + auto held = robot_sensor_ports::latest(rig.store_, "/f_scan", cursor); + ASSERT_TRUE(held); + + // Bản mới đè lên slot trong lúc reader vẫn đang cầm bản cũ. Producer tráo con trỏ chứ không sửa + // tại chỗ, nên bản đang cầm không được đổi một byte nào. + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(9.0f), robot::Time(10.1))); + + EXPECT_FLOAT_EQ(held->ranges[0], 1.0f); +} + +// ================================================================================================ +// 2. Cursor +// ================================================================================================ + +TEST(SensorStore, SaysNothingIsNewUntilSomethingIs) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + uint64_t cursor = 0; + + // Chưa có gì. + EXPECT_FALSE(robot_sensor_ports::latest(rig.store_, "/f_scan", cursor)); + + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + ASSERT_TRUE(robot_sensor_ports::latest(rig.store_, "/f_scan", cursor)); + + // Đọc lại ngay: control loop 20 Hz đọc cảm biến 15 Hz, một phần tư số tick rơi vào đây và phải + // biết là không có gì mới, chứ không được xử lý lại đúng scan cũ rồi đếm hai lần. + EXPECT_FALSE(robot_sensor_ports::latest(rig.store_, "/f_scan", cursor)); +} + +TEST(SensorStore, ANewReadingWithIdenticalContentStillCountsAsNew) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + uint64_t cursor = 0; + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + ASSERT_TRUE(robot_sensor_ports::latest(rig.store_, "/f_scan", cursor)); + + // Cùng nội dung, cùng stamp. Thứ tự đến mới là thứ quyết định, nên đây vẫn là bản mới. + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + EXPECT_TRUE(robot_sensor_ports::latest(rig.store_, "/f_scan", cursor)); +} + +TEST(SensorStore, AStampGoingBackwardsDoesNotFreezeTheReader) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + uint64_t cursor = 0; + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(1.0f), robot::Time(100.0))); + ASSERT_TRUE(robot_sensor_ports::latest(rig.store_, "/f_scan", cursor)); + + // Host restart, đổi sang sim time, replay bag — stamp lùi hẳn về. Lọc theo stamp thì reader coi + // mọi bản sau đó là cũ và đứng im vĩnh viễn mà không log gì. Lọc theo thứ tự đến thì không. + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(2.0f), robot::Time(1.0))); + + auto fresh = robot_sensor_ports::latest(rig.store_, "/f_scan", cursor); + ASSERT_TRUE(fresh); + EXPECT_FLOAT_EQ(fresh->ranges[0], 2.0f); +} + +// ================================================================================================ +// 3. Từ chối +// ================================================================================================ + +TEST(SensorStore, DropsATopicNobodyDeclared) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + // Không tự thêm slot: một depth cloud không ai khai sẽ ngốn hàng MB mỗi frame, và config thôi + // không còn trả lời được câu "tiến trình này đang giữ những gì". + EXPECT_FALSE(robot_sensor_ports::put(rig.store_, "/nobody", makeScan(1.0f), robot::Time(10.0))); + + uint64_t cursor = 0; + EXPECT_FALSE(robot_sensor_ports::latest(rig.store_, "/nobody", cursor)); +} + +TEST(SensorStore, AnUnconfiguredStoreIsSilent) +{ + // Runtime chưa khai `sensor_store` thì không có kho. Cảnh báo mỗi topic một lần về một tính năng + // chưa ai bật chính là cách một hệ đang chạy bỗng in lỗi sau khi nâng cấp. + SensorStore store; + EXPECT_FALSE(store.configured()); + EXPECT_FALSE(robot_sensor_ports::put(store, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + EXPECT_TRUE(store.inventory().empty()); +} + +TEST(SensorStore, RefusesAPutOfTheWrongType) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + PointCloud2 cloud; + cloud.width = 4; + + EXPECT_FALSE(robot_sensor_ports::put(rig.store_, "/f_scan", cloud, robot::Time(10.0))); + + SensorInfo info; + ASSERT_TRUE(rig.store_.describe("/f_scan", info)); + EXPECT_EQ(info.rejected, 1u); + EXPECT_EQ(info.size, 0u); +} + +TEST(SensorStore, RefusesAReadOfTheWrongType) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + + // Đây là hàng rào duy nhất giữa type erasure và UB: cast sai kiểu đọc ra rác chứ không crash, + // và hỏng ở một chỗ hoàn toàn khác. + uint64_t cursor = 0; + EXPECT_FALSE(robot_sensor_ports::latest(rig.store_, "/f_scan", cursor)); + EXPECT_EQ(cursor, 0u); + + // Đọc đúng kiểu vẫn phải chạy sau đó. + EXPECT_TRUE(robot_sensor_ports::latest(rig.store_, "/f_scan", cursor)); +} + +TEST(SensorStore, HasChecksTheTypeNotJustTheName) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + EXPECT_TRUE(robot_sensor_ports::has(rig.store_, "/f_scan")); + EXPECT_FALSE(robot_sensor_ports::has(rig.store_, "/f_scan")); + EXPECT_FALSE(robot_sensor_ports::has(rig.store_, "/nobody")); +} + +TEST(SensorStore, RefusesAConfigItCannotHonour) +{ + SensorStore store; + std::string error; + + SensorStoreConfig bad_capacity; + bad_capacity.sensors.push_back(entry("/f_scan", "robot_sensor_msgs/LaserScan", 0)); + EXPECT_FALSE(store.configure(bad_capacity, error)); + EXPECT_NE(error.find("capacity"), std::string::npos); + + SensorStoreConfig bad_age; + bad_age.sensors.push_back(entry("/f_scan", "robot_sensor_msgs/LaserScan", 1, 0.0)); + EXPECT_FALSE(store.configure(bad_age, error)); + EXPECT_NE(error.find("max_age"), std::string::npos); + + SensorStoreConfig empty_topic; + empty_topic.sensors.push_back(entry("", "robot_sensor_msgs/LaserScan")); + EXPECT_FALSE(store.configure(empty_topic, error)); + + // Config hỏng không được để lại kho ở trạng thái nửa vời. + EXPECT_FALSE(store.configured()); +} + +// ================================================================================================ +// 4. Ring +// ================================================================================================ + +TEST(SensorStore, KeepsOnlyTheNewestWhenCapacityIsOne) +{ + StoreRig rig(1); + ASSERT_TRUE(rig.ok_) << rig.error_; + + for (int i = 1; i <= 4; ++i) + { + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(static_cast(i)), + robot::Time(10.0 + 0.1 * i))); + } + + const auto frames = robot_sensor_ports::history(rig.store_, "/f_scan", 4); + ASSERT_EQ(frames.size(), 1u); + EXPECT_FLOAT_EQ(frames[0]->ranges[0], 4.0f); +} + +TEST(SensorStore, HandsBackAFrameStackOldestFirst) +{ + StoreRig rig(3); + ASSERT_TRUE(rig.ok_) << rig.error_; + + for (int i = 1; i <= 5; ++i) + { + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(static_cast(i)), + robot::Time(10.0 + 0.1 * i))); + } + + const auto frames = robot_sensor_ports::history(rig.store_, "/f_scan", 3); + ASSERT_EQ(frames.size(), 3u); + + // Cũ trước, mới sau — đúng thứ tự đã xảy ra, để bên xếp frame không phải tự đảo (và không phải + // nhớ đảo ở mọi chỗ gọi). + EXPECT_FLOAT_EQ(frames[0]->ranges[0], 3.0f); + EXPECT_FLOAT_EQ(frames[1]->ranges[0], 4.0f); + EXPECT_FLOAT_EQ(frames[2]->ranges[0], 5.0f); +} + +TEST(SensorStore, GivesWhatItHasWhenTheStackIsNotFullYet) +{ + StoreRig rig(5); + ASSERT_TRUE(rig.ok_) << rig.error_; + + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(2.0f), robot::Time(10.1))); + + const auto frames = robot_sensor_ports::history(rig.store_, "/f_scan", 5); + EXPECT_EQ(frames.size(), 2u); +} + +TEST(SensorStore, HistoryOfAnEmptyOrUnknownTopicIsEmpty) +{ + StoreRig rig(3); + ASSERT_TRUE(rig.ok_) << rig.error_; + + EXPECT_TRUE(robot_sensor_ports::history(rig.store_, "/f_scan", 3).empty()); + EXPECT_TRUE(robot_sensor_ports::history(rig.store_, "/nobody", 3).empty()); +} + +TEST(SensorStore, ClearTopicForgetsOneTopicButKeepsItDeclared) +{ + SensorStore store; + SensorStoreConfig config; + config.sensors.push_back(entry("/f_scan", "robot_sensor_msgs/LaserScan")); + config.sensors.push_back(entry("/b_scan", "robot_sensor_msgs/LaserScan")); + + std::string error; + ASSERT_TRUE(store.configure(config, error)) << error; + + ASSERT_TRUE(robot_sensor_ports::put(store, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + ASSERT_TRUE(robot_sensor_ports::put(store, "/b_scan", makeScan(2.0f), robot::Time(10.0))); + + EXPECT_TRUE(store.clearTopic("/f_scan")); + EXPECT_FALSE(store.clearTopic("/nobody")); + + uint64_t cursor = 0; + EXPECT_FALSE(robot_sensor_ports::latest(store, "/f_scan", cursor)); + // Bỏ dữ liệu không phải bỏ khai báo — topic vẫn nhận được bản mới. + EXPECT_TRUE(robot_sensor_ports::has(store, "/f_scan")); + // Và topic khác không bị đụng tới. + uint64_t other = 0; + EXPECT_TRUE(robot_sensor_ports::latest(store, "/b_scan", other)); +} + +TEST(SensorStore, ClearOfTypeOnlyTouchesThatKind) +{ + SensorStore store; + SensorStoreConfig config; + config.sensors.push_back(entry("/f_scan", "robot_sensor_msgs/LaserScan")); + config.sensors.push_back(entry("/cloud", "robot_sensor_msgs/PointCloud2")); + + std::string error; + ASSERT_TRUE(store.configure(config, error)) << error; + + PointCloud2 cloud; + cloud.width = 4; + ASSERT_TRUE(robot_sensor_ports::put(store, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + ASSERT_TRUE(robot_sensor_ports::put(store, "/cloud", cloud, robot::Time(10.0))); + + // Host bỏ dữ liệu theo từng LOẠI (removeAllLaserScans), còn kho đánh chỉ mục theo topic — đây là + // chỗ dịch giữa hai cách. + EXPECT_EQ(store.clearOfType(robot_sensor_ports::SensorType::id()), 1u); + + uint64_t scan_cursor = 0; + uint64_t cloud_cursor = 0; + EXPECT_FALSE(robot_sensor_ports::latest(store, "/f_scan", scan_cursor)); + EXPECT_TRUE(robot_sensor_ports::latest(store, "/cloud", cloud_cursor)); +} + +TEST(SensorStore, ClearingDoesNotRewindCursors) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + uint64_t cursor = 0; + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + ASSERT_TRUE(robot_sensor_ports::latest(rig.store_, "/f_scan", cursor)); + + rig.store_.clearTopic("/f_scan"); + + // Số đếm không quay về 0, nếu không cursor cũ sẽ trông mới hơn dữ liệu vừa tới và reader đó đứng + // im vĩnh viễn. + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(3.0f), robot::Time(11.0))); + auto fresh = robot_sensor_ports::latest(rig.store_, "/f_scan", cursor); + ASSERT_TRUE(fresh); + EXPECT_FLOAT_EQ(fresh->ranges[0], 3.0f); +} + +// ================================================================================================ +// Chẩn đoán +// ================================================================================================ + +TEST(SensorStore, InventoryNamesEveryTopicSoAMistypedOneCanBeFound) +{ + SensorStore store; + SensorStoreConfig config; + config.sensors.push_back(entry("/f_scan", "robot_sensor_msgs/LaserScan")); + config.sensors.push_back(entry("/b_scan", "robot_sensor_msgs/LaserScan")); + + std::string error; + ASSERT_TRUE(store.configure(config, error)) << error; + + const std::vector all = store.inventory(); + ASSERT_EQ(all.size(), 2u); + + // Đây là thứ biến "action hết giờ" thành "ông xin /front_scan, kho có /f_scan và /b_scan". + EXPECT_EQ(all[0].topic, "/b_scan"); + EXPECT_EQ(all[1].topic, "/f_scan"); + EXPECT_EQ(all[0].data_type, "robot_sensor_msgs/LaserScan"); + EXPECT_EQ(all[0].sequence, 0u); +} + +TEST(SensorStore, DescribeCarriesTheFreshnessPolicySoConsumersNeedNotRedeclareIt) +{ + SensorStore store; + SensorStoreConfig config; + config.sensors.push_back(entry("/f_scan", "robot_sensor_msgs/LaserScan", 2, 0.3)); + + std::string error; + ASSERT_TRUE(store.configure(config, error)) << error; + + ASSERT_TRUE(robot_sensor_ports::put(store, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + + SensorInfo info; + ASSERT_TRUE(store.describe("/f_scan", info)); + EXPECT_DOUBLE_EQ(info.max_age, 0.3); + EXPECT_EQ(info.capacity, 2u); + EXPECT_EQ(info.size, 1u); + EXPECT_EQ(info.sequence, 1u); + EXPECT_DOUBLE_EQ(info.stamp.toSec(), 10.0); + + EXPECT_FALSE(store.describe("/nobody", info)); +} + +TEST(SensorStore, MeasuresTheRateFromStampsAndIgnoresAGap) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + // 10 Hz đều. + for (int i = 0; i < 10; ++i) + { + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(1.0f), + robot::Time(10.0 + 0.1 * i))); + } + + SensorInfo info; + ASSERT_TRUE(rig.store_.describe("/f_scan", info)); + EXPECT_NEAR(info.rate_hz, 10.0, 0.5); + + // Cảm biến chết 30 giây rồi sống lại. Trung bình cả khoảng nghỉ vào là báo một con số chưa từng + // xảy ra, nên khoảng đó bị bỏ qua và con số cũ giữ nguyên. + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(1.0f), robot::Time(40.0))); + ASSERT_TRUE(rig.store_.describe("/f_scan", info)); + EXPECT_NEAR(info.rate_hz, 10.0, 0.5); +} + +TEST(SensorStore, ClearDropsTheDataButKeepsCursorsMonotonic) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + uint64_t cursor = 0; + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(1.0f), robot::Time(10.0))); + ASSERT_TRUE(robot_sensor_ports::latest(rig.store_, "/f_scan", cursor)); + + rig.store_.clear(); + + SensorInfo info; + ASSERT_TRUE(rig.store_.describe("/f_scan", info)); + EXPECT_EQ(info.size, 0u); + EXPECT_TRUE(rig.store_.configured()); + + // Đếm tiếp chứ không quay về 0: reset số đếm sẽ làm cursor cũ trông mới hơn dữ liệu vừa tới, và + // reader đó đứng im vĩnh viễn. + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(2.0f), robot::Time(11.0))); + auto fresh = robot_sensor_ports::latest(rig.store_, "/f_scan", cursor); + ASSERT_TRUE(fresh); + EXPECT_FLOAT_EQ(fresh->ranges[0], 2.0f); +} + +TEST(SensorStore, ZeroCopyPutSharesTheCallersObject) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + // Đường dành cho producer đã cầm sẵn ConstPtr — addDepthCameraData nhận đúng dạng đó, copy một + // megabyte để cất là phí thuần tuý. + boost::shared_ptr owned = boost::make_shared(makeScan(7.0f)); + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", owned, robot::Time(10.0))); + + uint64_t cursor = 0; + auto read_back = robot_sensor_ports::latest(rig.store_, "/f_scan", cursor); + ASSERT_TRUE(read_back); + EXPECT_EQ(read_back.get(), owned.get()); +} + +TEST(SensorStore, ReadingThroughTheReadOnlyPortWorksTheSame) +{ + StoreRig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + ASSERT_TRUE(robot_sensor_ports::put(rig.store_, "/f_scan", makeScan(5.0f), robot::Time(10.0))); + + // Đây là thứ plugin thật sự cầm: cổng chỉ-đọc, không xoá được kho, không thay được topic nào. + const robot_sensor_ports::SensorReader& reader = rig.store_; + + uint64_t cursor = 0; + auto scan = robot_sensor_ports::latest(reader, "/f_scan", cursor); + ASSERT_TRUE(scan); + EXPECT_FLOAT_EQ(scan->ranges[0], 5.0f); +} + +} // namespace + +int main(int argc, char** argv) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/sensor_type_test.cpp b/test/sensor_type_test.cpp new file mode 100644 index 0000000..7108012 --- /dev/null +++ b/test/sensor_type_test.cpp @@ -0,0 +1,136 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Kiểm định danh kiểu và bảng tên ngắn. + * + * Trọng tâm là hai đường từ chối: tên không có thật, và tên ngắn bị hai package cùng dùng. Cái thứ + * hai là lý do bảng này tồn tại thay vì so chuỗi thẳng — đoán bừa giữa hai kiểu nghĩa là cất một + * message khác hẳn thứ người vận hành định cất. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include +#include + +#include + +namespace +{ +using robot_sensor_ports::SensorType; +using robot_sensor_ports::TypeNames; + +/// Một kiểu giả để dựng ca đụng tên ngắn. Trùng nửa sau với robot_sensor_msgs/Temperature. +struct FakeTemperature +{ +}; + +} // namespace + +namespace robot_sensor_ports +{ +ROBOT_SENSOR_PORTS_REGISTER_TYPE(::FakeTemperature, "test_msgs/Temperature") +} // namespace robot_sensor_ports + +namespace +{ + +TEST(SensorType, GivesTheFullIdentityAtCompileTime) +{ + EXPECT_STREQ(SensorType::id(), "robot_sensor_msgs/LaserScan"); + EXPECT_STREQ(SensorType::id(), "robot_sensor_msgs/PointCloud2"); + EXPECT_STREQ(SensorType::id(), + "robot_sensor_msgs/DepthCameraData"); +} + +TEST(TypeNames, ResolvesTheShortFormAnOperatorTypes) +{ + std::string full; + std::string error; + + ASSERT_TRUE(TypeNames::resolve("LaserScan", full, error)) << error; + EXPECT_EQ(full, "robot_sensor_msgs/LaserScan"); +} + +TEST(TypeNames, AcceptsTheFullFormToo) +{ + std::string full; + std::string error; + + ASSERT_TRUE(TypeNames::resolve("robot_sensor_msgs/DepthCameraData", full, error)) << error; + EXPECT_EQ(full, "robot_sensor_msgs/DepthCameraData"); +} + +TEST(TypeNames, RejectsAnUnknownNameAndListsWhatExists) +{ + std::string full; + std::string error; + + EXPECT_FALSE(TypeNames::resolve("LazerScan", full, error)); + EXPECT_NE(error.find("unknown"), std::string::npos); + // Người gõ sai cần thấy danh sách tên thật ngay tại dòng lỗi, không phải đi tìm trong header. + EXPECT_NE(error.find("robot_sensor_msgs/LaserScan"), std::string::npos); +} + +TEST(TypeNames, RejectsAnEmptyName) +{ + std::string full; + std::string error; + + EXPECT_FALSE(TypeNames::resolve("", full, error)); +} + +TEST(TypeNames, RefusesToGuessWhenTwoPackagesShareAShortName) +{ + TypeNames::add("test_msgs/Temperature"); + + std::string full; + std::string error; + + // `Temperature` giờ khớp cả robot_sensor_msgs lẫn test_msgs. Chọn một cái là cất nhầm kiểu trong + // im lặng. + EXPECT_FALSE(TypeNames::resolve("Temperature", full, error)); + EXPECT_NE(error.find("ambiguous"), std::string::npos); + EXPECT_NE(error.find("robot_sensor_msgs/Temperature"), std::string::npos); + EXPECT_NE(error.find("test_msgs/Temperature"), std::string::npos); +} + +TEST(TypeNames, TheFullFormStillWorksWhenTheShortOneIsAmbiguous) +{ + TypeNames::add("test_msgs/Temperature"); + + std::string full; + std::string error; + + // Người đã gõ dạng đầy đủ thì không có gì để đoán — phải nhận, kể cả khi nửa sau bị trùng. + ASSERT_TRUE(TypeNames::resolve("robot_sensor_msgs/Temperature", full, error)) << error; + EXPECT_EQ(full, "robot_sensor_msgs/Temperature"); +} + +TEST(TypeNames, KnowsEveryTypeInTheBuiltInList) +{ + const std::vector all = TypeNames::all(); + + // 22 loại của robot_sensor_msgs — hai loại còn lại (Imu, TimeReference) có header hỏng sẵn trong + // chính robot_sensor_msgs, xem sensor_types.h. Danh sách sinh ra bảng này cũng sinh ra các + // specialisation của SensorType, nên hai bên không thể lệch nhau — test này canh cả hai. + EXPECT_GE(all.size(), 22u); + + for (const char* expected : {"robot_sensor_msgs/LaserScan", "robot_sensor_msgs/PointCloud2", + "robot_sensor_msgs/DepthCameraData", "robot_sensor_msgs/CameraInfo", + "robot_sensor_msgs/JointState", "robot_sensor_msgs/Image"}) + { + EXPECT_NE(std::find(all.begin(), all.end(), expected), all.end()) << expected; + } +} + +} // namespace + +int main(int argc, char** argv) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +}