From 3896886349ec5fffaaf5b4fd9328bff65601d051 Mon Sep 17 00:00:00 2001 From: trung09122002 Date: Sat, 19 Sep 2026 18:25:55 +0700 Subject: [PATCH] upload driver --- configuration_files/pipeline.yaml | 18 +- configuration_files/robot.yaml | 41 +- configuration_files/sensors.yaml | 21 +- libs/vslam_drivers/CMakeLists.txt | 19 +- .../include/vslam/driver_config.h | 98 +++- libs/vslam_drivers/src/lakibeam_driver.cc | 438 ++++++++++++++++++ libs/vslam_drivers/src/mcu_bridge.cc | 338 ++++++++++++++ libs/vslam_drivers/src/zlac_base.cc | 434 +++++++++++++++++ test/test_robot_model.cc | 14 +- 9 files changed, 1394 insertions(+), 27 deletions(-) create mode 100644 libs/vslam_drivers/src/lakibeam_driver.cc create mode 100644 libs/vslam_drivers/src/mcu_bridge.cc create mode 100644 libs/vslam_drivers/src/zlac_base.cc diff --git a/configuration_files/pipeline.yaml b/configuration_files/pipeline.yaml index 111aee2..ab11982 100644 --- a/configuration_files/pipeline.yaml +++ b/configuration_files/pipeline.yaml @@ -48,10 +48,22 @@ gravity_align: cliff_detect: enabled: true - # ⚠️ min_dist la VUNG MU HINH HOC, khong phai lua chon tuy y. Camera cao - # 0.80 m chuc xuong 15 do: tia cham san gan nhat o ~1.07 m. Ha xuong duoi + # ⚠️ min_dist la VUNG MU HINH HOC, khong phai lua chon tuy y. Ha xuong duoi # nguong do thi khong tia nao cham san va detector im lang hoan toan. - min_dist: 1.10 + # + # Suy tu thiet ke cu (camera 0.80 m, chuc 15 do, tia cham san o ~1.07 m): + # tia thap nhat nam 36.8 do duoi phuong ngang, tuc nua FOV doc ~21.8 do. + # Camera gio cao 0.3935 m so voi san (robot.yaml), nen: + # 0.3935 / tan(36.8 do) = 0.526 m + # Cong bien nhu cu (1.07 -> 1.10) ra 0.55. + min_dist: 0.55 + + # ⚠️ CHUA TINH LAI, va dang la cho yeu nhat sau khi ha camera. + # max_dist khong phai rang buoc hinh hoc ma la gioi han nhieu depth: cang + # luot san thi sai so z cang lon. Ha camera tu 0.80 xuong 0.3935 lam goc + # luot tai 2.5 m tut tu 17.7 do xuong 8.9 do -- mot nua. Rat co the phai + # keo max_dist ve gan (1.5 m cho goc 14.7 do, xap xi goc cu tai 2.5 m). + # Chot bang do that tren san, dung doan. max_dist: 2.50 cliff_margin: 0.05 diff --git a/configuration_files/robot.yaml b/configuration_files/robot.yaml index e8494a8..15b63cb 100644 --- a/configuration_files/robot.yaml +++ b/configuration_files/robot.yaml @@ -23,8 +23,13 @@ # ============ KICH THUOC ============ geometry: - wheel_radius: 0.075 # m. base_link o tam truc, cao ngan nay so voi san. - wheel_separation: 0.36 # m, khoang cach hai banh chu dong + # Lay theo base_kit/src/Zlac_ros (KinematicsConfig): banh Ø173 mm => r = + # 0.0865, wheel_base = 0.400. Gia tri cu la 0.075 / 0.36 -- lech 15% va 11%, + # va lech kieu khong co trieu chung: robot van chay, ban do van dung hinh, + # chi moi quang duong deu sai ti le. base_kit la code that su dang lai con + # robot nay nen no thang. + wheel_radius: 0.0865 # m. base_link o tam truc, cao ngan nay so voi san. + wheel_separation: 0.400 # m, khoang cach hai banh chu dong # Ban kinh bao than robot. Dung de che quat LiDAR nhin vao chinh than. robot_radius: 0.24 # Nua rong than. Cong voi vi tri laser cho ra goc quat bi che. @@ -48,8 +53,22 @@ geometry: frames: - parent: base_link child: laser_link - # LakiBeam gan truoc, tren nap. z do tu TAM TRUC banh, khong phai tu san. - xyz: [0.24, 0.0, 0.125] + # LakiBeam nam NGAY TREN TAM TRUC (x = 0), khong phai gan truoc. z do tu + # TAM TRUC banh, khong phai tu san. + # + # ⚠️ Gia tri cu la x = 0.24. Doi sang 0 lam mat can cu cua sector_masks + # trong sensors.yaml -- xem canh bao o do. + xyz: [0.0, 0.0, 0.13] + # ⚠️⚠️ LiDAR gan UP NGUOC tren robot that, nhung rpy o day VAN LA [0,0,0] + # va do la CO Y -- dung "sua" thanh [3.14159, 0, 0]. + # + # Driver da bu tu the do bang angle_offset_deg = -90 + inverted = false + # (xem driver_config.h, muc 2 va 3). Them roll = pi vao day la bu HAI LAN: + # scan lat guong lai ve dung cho sai, va no khong bao gio crash -- chi cho + # ra mot ban do sai ma moi thu khac trong nhin binh thuong. + # + # Bu o driver vi ScanSanitizer va sector_masks doc THANG goc cua scan, + # chung khong di qua TF. rpy: [0.0, 0.0, 0.0] - parent: base_link @@ -60,10 +79,16 @@ frames: - parent: base_link child: camera_link - # D410 tren cot. z = 0.725 so voi tam truc => 0.800 so voi san - # (0.725 + wheel_radius 0.075). `cliff_detect.nominal_tz` PHAI bang tong - # do; RobotModel tu tinh va kiem, khong de nguoi dung go lai hai lan. - xyz: [0.19, 0.0, 0.725] + # D410 dat so voi LiDAR: cao hon 17.7 cm, va ve phia truoc 9.5 cm. + # LiDAR o [0, 0, 0.13] nen camera o [0.095, 0, 0.307] so voi tam truc + # => 0.307 + wheel_radius 0.0865 = 0.3935 so voi SAN. + # `cliff_detect.nominal_tz` PHAI bang tong do; RobotModel tu tinh va kiem, + # khong de nguoi dung go lai hai lan. + # + # ⚠️ Gia tri cu la [0.19, 0, 0.725] tuc 0.800 so voi san -- cao gap doi. + # Moi so trong cliff_detect deu suy tu chieu cao do, nen chung da duoc + # tinh lai. Xem pipeline.yaml muc min_dist. + xyz: [0.095, 0.0, 0.307] # Chuc xuong 15 do de nhin duoc san o 1.1-2.5 m. Doi goc nay la doi ca # vung mu cua cliff_detect -- xem docs/PERCEPTION.md. rpy: [0.0, 0.2618, 0.0] diff --git a/configuration_files/sensors.yaml b/configuration_files/sensors.yaml index 05791c4..b725399 100644 --- a/configuration_files/sensors.yaml +++ b/configuration_files/sensors.yaml @@ -25,12 +25,23 @@ lidar: # |(t_cuoi - t_dau) - scan_time| > nguong nay. stamp_mismatch_warn: 0.005 - # Quat bi than robot che, don vi DO. Laser o x=0.24, than nua rong 0.17 - # => +-118 do la phan nhin ra ngoai. + # Quat bi than robot che, don vi DO. # - # ⚠️ Huong 0 do THAT cua LiDAR chua do duoc. Cat nham quat truoc thi safety - # thay SCAN_SPARSE va robot dung im. Chay `vslam_scan_check` TRUOC khi bat - # safety tren phan cung that. + # ⚠️⚠️ HAI GIA TRI DUOI DAY DA MAT CAN CU -- PHAI DO LAI TRUOC KHI BAT SAFETY. + # + # Chung duoc suy tu "laser o x=0.24, than nua rong 0.17 => +-118 do". Nhung + # laser gio o x = 0.0 (robot.yaml): no nam NGAY TREN TAM TRUC, khong phai + # gan mep truoc. Hinh hoc che khuat cua mot LiDAR o TAM than hoan toan khac + # mot LiDAR o MEP: o tam thi hoac no cao hon than va khong bi che ti nao, + # hoac no bi che deu moi huong -- khong con quat +-118 do nao ca. + # + # Khong tu sua thanh mot con so khac vi doan sai o day hong theo ca hai + # chieu: mask thieu -> than robot bi doc thanh vat can, robot dung im; + # mask thua -> mot vat can that bi cat mat, khong ai biet. + # + # Huong 0 do THAT cua LiDAR thi da co dap an (khong con phai do): manual + # §8.1 cho X = R*sin(a), Y = R*cos(a), REP-103 dung x = R*cos(t) => t = 90 + # do - a. Da vao driver_config.h: angle_offset_deg = 90, inverted = true. sector_masks: - [118.0, 180.0] - [-180.0, -118.0] diff --git a/libs/vslam_drivers/CMakeLists.txt b/libs/vslam_drivers/CMakeLists.txt index d01d3ad..ac97b3b 100644 --- a/libs/vslam_drivers/CMakeLists.txt +++ b/libs/vslam_drivers/CMakeLists.txt @@ -4,6 +4,7 @@ # cung -- ScanSanitizer, ClockSync, giao thuc MCU -- phai build va test duoc # tren may khong co RealSense SDK, ke ca trong CI. option(VSLAM_WITH_REALSENSE "Build driver RealSense (can librealsense2)" OFF) +option(VSLAM_WITH_CANOPEN "Build driver base ZLAC8015D (can liblely-coapp)" OFF) vslam_add_library(vslam_drivers PUBLIC_HDRS @@ -25,8 +26,12 @@ vslam_add_library(vslam_drivers # het src/ nen phai loai no ra khi tat -- neu khong thi `#include ` # lam hong build tren may khong co librealsense2, tuc dung cai ma cai # `option()` nay sinh ra de tranh. +# +# zlac_base.cc cung the, voi liblely-coapp. Hai driver nay la hai driver DUY +# NHAT can SDK ngoai; lakibeam_driver.cc va mcu_bridge.cc chi dung socket va +# termios cua POSIX nen luon build duoc. get_target_property(_vslam_drv_srcs vslam_drivers SOURCES) -list(FILTER _vslam_drv_srcs EXCLUDE REGEX "realsense_driver\\.cc$") +list(FILTER _vslam_drv_srcs EXCLUDE REGEX "(realsense_driver|zlac_base)\\.cc$") set_target_properties(vslam_drivers PROPERTIES SOURCES "${_vslam_drv_srcs}") if(VSLAM_WITH_REALSENSE) @@ -36,3 +41,15 @@ if(VSLAM_WITH_REALSENSE) target_include_directories(vslam_drivers SYSTEM PRIVATE ${realsense2_INCLUDE_DIR}) target_compile_definitions(vslam_drivers PRIVATE VSLAM_HAVE_REALSENSE=1) endif() + +if(VSLAM_WITH_CANOPEN) + # pkg-config chu khong phai find_package: lely khong ship file Config.cmake. + # Giong cach base_kit/src/Zlac_ros/CMakeLists.txt lam. + find_package(PkgConfig REQUIRED) + pkg_check_modules(LELY REQUIRED liblely-coapp) + target_sources(vslam_drivers PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/zlac_base.cc) + target_link_directories(vslam_drivers PRIVATE ${LELY_LIBRARY_DIRS}) + target_link_libraries(vslam_drivers PRIVATE ${LELY_LIBRARIES}) + target_include_directories(vslam_drivers SYSTEM PRIVATE ${LELY_INCLUDE_DIRS}) + target_compile_definitions(vslam_drivers PRIVATE VSLAM_HAVE_CANOPEN=1) +endif() diff --git a/libs/vslam_drivers/include/vslam/driver_config.h b/libs/vslam_drivers/include/vslam/driver_config.h index f7fefa7..b2fa45c 100644 --- a/libs/vslam_drivers/include/vslam/driver_config.h +++ b/libs/vslam_drivers/include/vslam/driver_config.h @@ -29,6 +29,52 @@ struct LidarConfig { uint32_t samples = 1081; double fov_rad = 4.712389; // 270 do + // --- Ba so lay tu SDK chinh hang, KHONG phai doan --- + // + // Nguon: base_kit/src/lidar (driver ROS dang chay that tren robot nay) va + // LakiBeam User Manual RBDOC-UM-1001 ma no dan lai. + // + // 1. DON VI RANGE = MILIMET. scan_conversion.cpp:36 chia cho 1000. + // Ghi ro o day vi suy tu layout goi se ra 2 mm: goi LakiBeam nhai cau truc + // VLP-16, ma Velodyne dung 2 mm. Doan theo ho la sai dung GAP DOI, va sai + // kieu im lang nhat -- SLAM van hoi tu, occupancy grid van dep, chi moi + // khoang cach deu gap doi. + double range_unit_m = 0.001; + + // 2 va 3. HUONG 0 DO + CHIEU QUAY (rui ro R5) -- SUY RA duoc, khong phai do. + // + // ⚠️ LIDAR TREN ROBOT NAY GAN UP NGUOC. Hai gia tri duoi da tinh cho tu the + // do. Gan lai xuoi thi phai doi CA HAI, khong phai mot. + // + // Manual §8.1: LakiBeam tra ve X_dev = R*sin(a), Y_dev = R*cos(a) + // REP-103: he nay dung x = R*cos(t), y = R*sin(t) + // + // Gan XUOI: x = X_dev, y = Y_dev + // cos t = sin a, sin t = cos a => t = 90do - a + // => angle_offset_deg = +90, inverted = true + // + // Gan UP NGUOC = xoay 180do quanh truc X, tuc Y va Z doi dau: + // x = X_dev, y = -Y_dev + // cos t = sin a, sin t = -cos a => t = a - 90do + // => angle_offset_deg = -90, inverted = FALSE + // + // Hai phep dao dau -- cua QUY UOC va cua TU THE GAN -- triet tieu nhau. Do + // la ly do `inverted` o day la false DU thiet bi dang bi lat; doc luot qua + // rat de tuong nguoc lai. + double angle_offset_deg = -90.0; + bool inverted = false; + + // ⚠️⚠️ KHONG bu tu the up nguoc them mot lan nua trong TF. + // `laser_link` trong robot.yaml giu rpy = [0, 0, 0] CO Y: driver da tra ve + // goc theo quy uoc Z-huong-len roi. Them roll = pi vao TF la bu HAI LAN, va + // scan lat guong lai ve dung cho sai -- mot loi khong bao gio crash. + // Bu o driver chu khong o TF vi ScanSanitizer va sector_masks doc THANG goc + // cua scan, chung khong di qua TF. + // + // ⚠️ base_kit/lakibeam_driver.hpp de mac dinh `angle_flip = false`, trung + // gia tri voi o day nhung VI LY DO KHAC (no gan xuoi, va chinh comment cua + // no ket luan phai la true). Dung lay do lam xac nhan cho gia tri nay. + LidarStampMode stamp_mode = LidarStampMode::kFirstPacket; // Bu do tre da do duoc, cong vao stamp. Chua do -> 0. double stamp_offset_sec = 0.0; @@ -74,9 +120,22 @@ struct CameraConfig { struct McuConfig { std::string port = "/dev/ttyACM0"; - uint32_t baud = 921600; + // 115200, theo firmware that (base_kit/src/imu_uart). Gia tri cu o day la + // 921600 -- doc sai baud thi ra rac chu khong ra loi, nen no im lang. + uint32_t baud = 115200; std::string imu_frame_id = "imu_link"; + // ⚠️ FIRMWARE HIEN TAI KHONG PHAT TIMESTAMP. + // mcu_protocol.h dac ta `I,,...`; ESP32-S3 + WT61PC dang chay lai + // phat text ba dong roi rac: "Acc x y z" / "Gyro x y z" / "Angle x y z", + // khong co micros(). Hau qua: ClockSync KHONG chay duoc, va driver buoc + // phai dong dau bang dong ho host luc NHAN -- tuc mang theo do tre cua + // USB-CDC va cua scheduler, khong do duoc va khong bu duoc. + // + // Duong sua dung la firmware phat theo mcu_protocol.h. Cho toi luc do, + // stamp_skew_ms trong DriverStats se luon la 0 vi khong co gi de so. + bool expect_timestamps = false; + double ping_period_sec = 1.0; // chu ky ping de dong bo dong ho // Datasheet ICM-42688-P / BMP390. TAT CA deu la doan tu datasheet cho toi @@ -98,10 +157,16 @@ struct McuConfig { // Vi vay transport duoc tach hoan toan khoi phep toan odometry: khi biet giao // thuc that thi chi them mot lop mong, khong dung toi WheelOdometry. enum class BaseProtocol { + // ZLAC8015D qua CANopen (lely-core). DAY LA THU THAT TREN ROBOT NAY -- + // base_kit/src/Zlac_ros. Khong phai serial: encoder va motor deu di qua + // `can0`, nen gia dinh "tat ca tren mot serial MCU" cua file nay sai ngay + // tu goc. Xem zlac_base.cc. + kZlacCanOpen, // Mo rong giao thuc text san co cua MCU bang mot ban ghi: // E,,, // Tai dung ClockSync da co, va do la phan kho nhat -- nen day la lua chon - // re nhat neu firmware sua duoc. + // re nhat neu firmware sua duoc. GIU LAI: neu sau nay encoder ve MCU that + // thi duong nay van dung, va no la duong DUY NHAT dong bo duoc dong ho. kMcuTextEncoder, // Serial rieng voi giao thuc nhi phan cua nha san xuat base. kVendorSerial, @@ -110,16 +175,37 @@ enum class BaseProtocol { }; struct BaseConfig { - BaseProtocol protocol = BaseProtocol::kMcuTextEncoder; + BaseProtocol protocol = BaseProtocol::kZlacCanOpen; - // Dung khi protocol = kVendorSerial. + // --- Dung khi protocol = kZlacCanOpen --- + std::string can_channel = "can0"; + uint8_t can_node_id = 1; + // File DCF cua lely. base_kit dat trong share/ cua package ROS; o day phai + // tro tuong minh vi khong co ament index. + std::string dcf_path; + + // Encoder resolution cua ZLAC8015D, dem/vong SAU hop so, doc qua 0x6064. + // 0 = doc tu thiet bi luc Open() (0x608F:1 Encoder Increments) thay vi tin + // mot hang so chep tay. + uint32_t encoder_counts_per_rev = 0; + + // --- Dung khi protocol = kVendorSerial --- std::string port = "/dev/ttyUSB0"; uint32_t baud = 115200; // Hinh hoc. PHAI khop robot.yaml -- day la gia tri duy nhat, khong con ban // sao trong URDF nua. - double wheel_radius = 0.075; - double wheel_separation = 0.36; + // + // Lay theo base_kit/src/Zlac_ros (KinematicsConfig): banh Ø173 mm nen + // r = 0.0865, wheel_base = 0.400. Gia tri cu o day la 0.075 / 0.36 -- lech + // 15% va 11%, va lech kieu KHONG co trieu chung: robot van chay, ban do van + // dung hinh, chi moi quang duong deu sai ti le. base_kit la code that su + // dang lai con robot nay nen no thang. + double wheel_radius = 0.0865; + double wheel_separation = 0.400; + + // Chi dung khi doc tick tho. Voi ZLAC doc qua 0x6064 thi encoder resolution + // nam trong chinh driver (xem zlac_base.cc) va truong nay khong dung toi. uint32_t ticks_per_rev = 0; // 0 = chua biet, PHAI dat truoc khi chay that // Gioi han gui xuong motor. Lop safety da kep roi; day la chan cuoi. diff --git a/libs/vslam_drivers/src/lakibeam_driver.cc b/libs/vslam_drivers/src/lakibeam_driver.cc new file mode 100644 index 0000000..4ccee1a --- /dev/null +++ b/libs/vslam_drivers/src/lakibeam_driver.cc @@ -0,0 +1,438 @@ +// Driver LakiBeam 1L (UDP MSOP, port 2368). +// +// ================== NGUON CUA MOI CON SO O DAY ================== +// Khong con nao la doan. Hai nguon, doi chieu duoc voi nhau: +// 1. `vslam_lidar_probe --seconds 10` tren thiet bi that (Jetson AGX) +// 2. base_kit/src/lidar -- SDK chinh hang + driver ROS dang chay tren robot +// nay, dan lai LakiBeam User Manual RBDOC-UM-1001 +// +// ================== KHUNG GOI (1206 byte CO DINH) ================== +// 12 block x 100 byte + 6 byte duoi. Khop `udp_pack_t` cua SDK. +// +// Block (100 byte) -- `little_pack_t`: +// +0 u16 head 0xFFEE +// +2 u16 azimuth, LE, don vi 1/100 do +// +4 96B 16 x `depth_t`, moi cai 6 byte: +// u16 distance0 | u8 rssi0 | u16 distance1 | u8 rssi1 +// +// ⚠️ CHI distance0/rssi0 duoc dung. SDK (LakiBeamUDP.cpp, fill_havestart) +// khong bao gio doc distance1 -- va probe xac nhan: 3 byte thu hai cua moi +// `depth_t` LUON bang 0 tren ban 1L. Doc ca 32 slot se nhan doi so tia bang +// mot nua so tia rong. +// +// Duoi goi: +1200 u32 timestamp (us), +1204 u16 factory. +// +// ================== GOC: NOI SUY, KHONG DUNG BUOC CO DINH ================== +// Azimuth chi co MOT gia tri cho ca 16 diem trong block. SDK rai 16 diem do +// deu giua azimuth cua block NAY va azimuth cua block KE TIEP: +// div_angle = (azimuth[i+1] - azimuth[i]) / 16 +// +// Lam theo, khong dung buoc co dinh tu config, vi hai ly do: +// - toc do quay khong hang so; buoc co dinh lam tia lech dan trong sweep +// - block cuoi cua goi phai lay azimuth tu goi SAU, nen driver luon giu lai +// mot goi va giai ma tre mot nhip. Do la ly do co `pending_`. +// +// ================== HAI QUY UOC PHAI DOI ================== +// Manual §8.1: LakiBeam tra ve X = R*sin(a), Y = R*cos(a) +// REP-103: he nay dung x = R*cos(t), y = R*sin(t) +// => t = 90do - a. Trong config la angle_offset_deg = 90 VA inverted = true. +// Thieu mot trong hai thi ban do lat guong. +// +// Don vi range la MILIMET (scan_conversion.cpp:36 chia 1000), KHONG phai 2 mm +// nhu Velodyne -- suy tu layout goi se ra sai dung gap doi. +// +// ================== VI SAO KHONG BOC SDK ================== +// SDK keo theo boost::asio + boost::thread, va header cua no co +// `using namespace std;` o pham vi toan cuc. Layout goi da biet het va chi +// co bay nhieu, nen giai ma thang re hon nhieu so voi cai gia phai tra. + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "vslam/clock.h" +#include "vslam/driver_config.h" +#include "vslam/driver_interfaces.h" +#include "vslam/log.h" +#include "vslam/scan_sanitizer.h" + +namespace vslam { +namespace { + +constexpr size_t kPacketBytes = 1206; +constexpr size_t kBlocks = 12; +constexpr size_t kBlockBytes = 100; +constexpr size_t kDepthsPerBlock = 16; // `CONFIG_BLOCK_DEPTHS` cua SDK +constexpr size_t kDepthBytes = 6; // distance0 rssi0 distance1 rssi1 +constexpr uint16_t kBlockHead = 0xFFEE; +constexpr uint32_t kDegreeMax = 36000; // `CONFIG_DEGREE_MAX` + +// Coi la sang vong moi khi goc TUT lai qua nua vong. Dung `cur < prev` tran +// se cat sweep thanh hang tram manh vun moi lan thiet bi jitter mot don vi. +constexpr uint32_t kWrapGuard = 18000; + +constexpr double kDeg2Rad = M_PI / 180.0; +constexpr float kInf = std::numeric_limits::infinity(); + +uint16_t RdLe16(const uint8_t* p) { + return static_cast(p[0] | (static_cast(p[1]) << 8)); +} + +double NormalizePi(double a) { + while (a > M_PI) a -= 2.0 * M_PI; + while (a < -M_PI) a += 2.0 * M_PI; + return a; +} + +struct Point { + double angle_rad = 0.0; // da doi sang quy uoc REP-103 + float range_m = kInf; + float intensity = 0.0f; +}; + +class LakiBeamDriver : public LidarInterface { + public: + LakiBeamDriver(const LidarConfig& cfg, ClockPtr clock) + : cfg_(cfg), clock_(std::move(clock)), sanitizer_(cfg.sanitizer) {} + + ~LakiBeamDriver() override { Close(); } + + void SetCallback(ScanCallback cb) override { cb_ = std::move(cb); } + + StatusResponse Open() override { + if (fd_ >= 0) { + return StatusResponse::Error(StatusCode::kFailedPrecondition, + "lidar: da mo roi"); + } + if (!clock_) { + return StatusResponse::Error(StatusCode::kInvalidArgument, + "lidar: thieu clock"); + } + if (cfg_.samples < 2) { + return StatusResponse::Error(StatusCode::kInvalidArgument, + "lidar: samples phai >= 2"); + } + + fd_ = ::socket(AF_INET, SOCK_DGRAM, 0); + if (fd_ < 0) { + return StatusResponse::Error( + StatusCode::kUnavailable, + std::string("lidar: socket() that bai: ") + std::strerror(errno)); + } + + const int reuse = 1; + ::setsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)); + + // Timeout tren socket thay vi non-blocking + poll: vong nay khong co viec + // gi khac lam giua hai goi, nen them mot syscall moi vong la phi ton + // khong doi lai duoc gi. + timeval tv{}; + tv.tv_sec = static_cast(cfg_.recv_timeout_sec); + tv.tv_usec = static_cast( + (cfg_.recv_timeout_sec - static_cast(tv.tv_sec)) * 1e6); + ::setsockopt(fd_, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_port = htons(cfg_.port); + if (::inet_pton(AF_INET, cfg_.host_ip.c_str(), &addr.sin_addr) != 1) { + CloseFd(); + return StatusResponse::Error( + StatusCode::kInvalidArgument, + "lidar: host_ip khong hop le: " + cfg_.host_ip + + " (day la dia chi de BIND, khong phai IP cua LiDAR)"); + } + if (::bind(fd_, reinterpret_cast(&addr), sizeof(addr)) < 0) { + const std::string err = std::strerror(errno); + CloseFd(); + return StatusResponse::Error( + StatusCode::kUnavailable, + "lidar: bind " + cfg_.host_ip + ":" + std::to_string(cfg_.port) + + " that bai: " + err + + (errno == EADDRINUSE + ? " -- co node khac dang giu port 2368? (lakibeam_ros cua" + " base_kit chang han)" + : "")); + } + + VSLAM_INFO("lidar: bind " << cfg_.host_ip << ":" << cfg_.port + << " range_unit=" << cfg_.range_unit_m << " m/dv" + << " angle_offset=" << cfg_.angle_offset_deg + << " do inverted=" << (cfg_.inverted ? "true" : "false")); + + Reset(); + running_ = true; + thread_ = std::thread([this] { RecvLoop(); }); + return StatusResponse::Ok(); + } + + void Close() override { + running_ = false; + // Dong fd TRUOC khi join: recv() dang ket trong timeout toi 1 s va + // shutdown() tren socket UDP khong danh thuc no tren Linux. + CloseFd(); + if (thread_.joinable()) thread_.join(); + } + + DriverStats Stats() const override { + std::lock_guard lk(stats_mu_); + return stats_; + } + + private: + void CloseFd() { + if (fd_ >= 0) { + ::close(fd_); + fd_ = -1; + } + } + + void Reset() { + points_.clear(); + points_.reserve(cfg_.samples + kDepthsPerBlock); + have_pending_ = false; + sweep_start_ = UnixTime(); + sweep_end_ = UnixTime(); + } + + void RecvLoop() { + std::vector buf(kPacketBytes + 64); + while (running_) { + const ssize_t n = ::recv(fd_, buf.data(), buf.size(), 0); + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { + Fail("khong nhan duoc goi nao trong " + + std::to_string(cfg_.recv_timeout_sec) + " s"); + continue; + } + if (!running_) break; // Close() vua dong fd + Fail(std::string("recv() that bai: ") + std::strerror(errno)); + continue; + } + if (static_cast(n) != kPacketBytes) { + // Kich thuoc khac la dau hieu doi firmware hoac co luong khac vao + // cung port. Noi RO thay vi giai ma bua roi cho ra rac. + Fail("goi dai " + std::to_string(n) + " byte, doi " + + std::to_string(kPacketBytes)); + continue; + } + OnPacket(buf.data(), clock_->Now()); + } + } + + // Giai ma TRE MOT NHIP: block cuoi cua goi truoc can azimuth dau cua goi + // nay de noi suy goc. Do la ly do co `pending_`. + void OnPacket(const uint8_t* pkt, UnixTime rx) { + if (RdLe16(pkt) != kBlockHead) { + Fail("goi khong bat dau bang 0xFFEE"); + return; + } + const uint32_t first_az = RdLe16(pkt + 2); + + if (have_pending_) { + DecodePacket(pending_.data(), first_az, pending_rx_); + } + std::memcpy(pending_.data(), pkt, kPacketBytes); + pending_rx_ = rx; + have_pending_ = true; + } + + void DecodePacket(const uint8_t* pkt, uint32_t next_pkt_az, UnixTime rx) { + for (size_t b = 0; b < kBlocks; ++b) { + const uint8_t* blk = pkt + b * kBlockBytes; + if (RdLe16(blk) != kBlockHead) { + // Bo rieng block hong, giu cac block con lai: mat 16 tia de hon la + // vut ca goi 192 tia. + Fail("block " + std::to_string(b) + " thieu head 0xFFEE"); + continue; + } + + const uint32_t az = RdLe16(blk + 2); + if (az >= kDegreeMax) { + Fail("azimuth " + std::to_string(az) + " >= 36000"); + continue; + } + + // Block cuoi lay azimuth ket tu goi sau -- dung cach SDK lam. + const uint32_t az_next = + (b + 1 < kBlocks) ? RdLe16(blk + kBlockBytes + 2) : next_pkt_az; + + if (have_prev_az_ && az + kWrapGuard < prev_az_) Emit(); + prev_az_ = az; + have_prev_az_ = true; + + if (sweep_start_.isZero()) sweep_start_ = rx; + sweep_end_ = rx; + + DecodeBlock(blk, az, az_next); + } + } + + void DecodeBlock(const uint8_t* blk, uint32_t az, uint32_t az_next) { + // div_angle = (az_next - az) / 16, co xu ly quay vong -- y het SDK. + const uint32_t span = + (az_next >= az) ? (az_next - az) : (kDegreeMax - az + az_next); + const double step = static_cast(span) / kDepthsPerBlock; + + for (size_t j = 0; j < kDepthsPerBlock; ++j) { + const uint8_t* d = blk + 4 + j * kDepthBytes; + const uint16_t dist = RdLe16(d); // distance0 + const uint8_t rssi = d[2]; // rssi0 + // distance1/rssi1 tai d[3..5] CO Y bo qua -- xem dau file. + + double a_dev = (static_cast(az) + step * static_cast(j)); + if (a_dev >= kDegreeMax) a_dev -= kDegreeMax; + a_dev *= 0.01; // 1/100 do -> do + + // t = offset - a khi inverted, nguoc lai t = offset + a + double t_deg = cfg_.inverted ? (cfg_.angle_offset_deg - a_dev) + : (cfg_.angle_offset_deg + a_dev); + + Point pt; + pt.angle_rad = NormalizePi(t_deg * kDeg2Rad); + // dist == 0 la KHONG CO TIENG VONG (manual §7.2), khong phai "0 met". + // Bien no thanh 0.0 se lam robot thay vat can dan vao mat cam bien. + pt.range_m = (dist == 0) ? kInf + : static_cast(dist * cfg_.range_unit_m); + pt.intensity = static_cast(rssi); + points_.push_back(pt); + } + } + + void Emit() { + if (points_.empty()) { + Reset(); + return; + } + + auto scan = std::make_shared(); + scan->header.seq = seq_++; + scan->header.frame_id = cfg_.frame_id; + + // Do dai sweep THAT, khong lay tu scan_freq_hz. Probe do 72 goi/s trong + // khi sensors.yaml ghi 25 Hz -- mot trong hai sai, va lay tu config se + // lam time_increment sai theo, keo moi phep bu chuyen dong lech. + const double measured = (sweep_end_ - sweep_start_).toSec(); + + scan->angle_min = static_cast(-cfg_.fov_rad / 2.0); + scan->angle_max = static_cast(cfg_.fov_rad / 2.0); + scan->angle_increment = + static_cast(cfg_.fov_rad / static_cast(cfg_.samples - 1)); + scan->scan_time = static_cast(measured); + scan->time_increment = + static_cast(measured / static_cast(cfg_.samples)); + scan->range_min = static_cast(cfg_.sanitizer.range_min); + scan->range_max = static_cast(cfg_.sanitizer.range_max); + scan->ranges.assign(cfg_.samples, kInf); + scan->intensities.assign(cfg_.samples, 0.0f); + + size_t placed = 0; + for (const Point& pt : points_) { + if (pt.angle_rad < scan->angle_min || pt.angle_rad > scan->angle_max) { + continue; // ngoai FOV 270 do -- phan bi than robot che + } + const auto idx = static_cast(std::lround( + (pt.angle_rad - scan->angle_min) / scan->angle_increment)); + if (idx >= cfg_.samples) continue; + scan->ranges[idx] = pt.range_m; + scan->intensities[idx] = pt.intensity; + ++placed; + } + + // stamp = luc nhan goi DAU cua sweep, theo quy uoc LaserScan (stamp ung + // voi TIA DAU TIEN). Che do kia tru scan_time khoi goi cuoi. + UnixTime stamp = (cfg_.stamp_mode == LidarStampMode::kFirstPacket) + ? sweep_start_ + : sweep_end_ - Duration::fromSec(measured); + if (cfg_.stamp_offset_sec != 0.0) { + stamp = stamp + Duration::fromSec(cfg_.stamp_offset_sec); + } + scan->header.stamp = stamp; + + sanitizer_.Apply(scan.get()); + + { + std::lock_guard lk(stats_mu_); + ++stats_.frames; + stats_.connected = true; + stats_.hz = (measured > 0.0) ? 1.0 / measured : 0.0; + // O trong = mat goi UDP. Bo phat hien mien phi: khong doc bo dem goi + // nao, chi dem o chua ai ghi. + if (placed + 1 < cfg_.samples) { + ++stats_.short_sweeps; + stats_.packets_lost += (cfg_.samples - placed) / (kDepthsPerBlock * kBlocks) + 1; + } + } + + const double expected = + (cfg_.scan_freq_hz > 0.0) ? 1.0 / cfg_.scan_freq_hz : 0.0; + if (expected > 0.0 && + std::fabs(measured - expected) > cfg_.sweep_duration_tolerance_sec) { + // THROTTLE: neu config sai toc do that thi dong nay no ra hang chuc lan + // moi giay va nhan chim moi log khac. + VSLAM_WARN_THROTTLE(5.0, "lidar: sweep " << measured * 1e3 << " ms, config doi " + << expected * 1e3 << " ms (" + << placed << "/" << cfg_.samples + << " tia)"); + } + + if (cb_) cb_(scan); + Reset(); + } + + void Fail(const std::string& msg) { + { + std::lock_guard lk(stats_mu_); + ++stats_.errors; + stats_.connected = false; + stats_.last_error = msg; + } + VSLAM_WARN_THROTTLE(5.0, "lidar: " << msg); + } + + LidarConfig cfg_; + ClockPtr clock_; + ScanSanitizer sanitizer_; + ScanCallback cb_; + + int fd_ = -1; + std::atomic running_{false}; + std::thread thread_; + + std::array pending_{}; + UnixTime pending_rx_; + bool have_pending_ = false; + + std::vector points_; + UnixTime sweep_start_; + UnixTime sweep_end_; + uint32_t prev_az_ = 0; + bool have_prev_az_ = false; + uint32_t seq_ = 0; + + mutable std::mutex stats_mu_; + DriverStats stats_; +}; + +} // namespace + +std::unique_ptr CreateLakiBeamDriver(const LidarConfig& cfg, + ClockPtr clock) { + return std::make_unique(cfg, std::move(clock)); +} + +} // namespace vslam diff --git a/libs/vslam_drivers/src/mcu_bridge.cc b/libs/vslam_drivers/src/mcu_bridge.cc new file mode 100644 index 0000000..9bef1f8 --- /dev/null +++ b/libs/vslam_drivers/src/mcu_bridge.cc @@ -0,0 +1,338 @@ +// Cau noi toi MCU: IMU qua UART. +// +// ================== KHONG KHOP DAC TA, VA VI SAO VAN VIET ================== +// mcu_protocol.h la DAC TA ma firmware phai khop: +// I,,,,,,, +// Firmware dang chay (base_kit/src/hardware/IMU_uart -- ESP32-S3 + DFRobot +// WT61PC) KHONG phat theo do. No phat text ba dong roi rac, tab/space: +// Acc 0.05 -0.10 9.82 <- m/s^2 +// Gyro 0.00 0.00 0.00 <- DO/s, khong phai rad/s +// Angle -0.55 -0.34 -176.61 <- do +// +// Driver nay doc DUNG cai firmware dang phat, va danh dau ro moi cho phai +// chap nhan vi the. Viet theo dac ta roi cho firmware doi thi khong ai chay +// duoc gi hom nay; viet theo thuc te roi im lang thi no thanh no ky thuat +// khong ai thay. Nen: chay duoc, va noi to cai gia phai tra. +// +// ================== BA CAI GIA, THEO MUC NGHIEM TRONG ================== +// +// 1. KHONG CO TIMESTAMP -> ClockSync khong chay duoc. +// Dac ta yeu cau `micros()` cua MCU de ClockSync fit tuyen tinh dong ho +// MCU <-> host. Firmware khong phat gi ca, nen stamp o day la luc HOST +// DOC DUOC DONG -- da qua bo dem USB-CDC, qua scheduler, qua ca do tre gom +// dong cua chinh driver nay. Do tre do KHONG do duoc va KHONG bu duoc. +// Hau qua thuc te: moi phep dong bo IMU voi LiDAR/camera deu mang mot sai +// so khong biet do lon. `stamp_skew_ms` trong DriverStats se luon la 0 -- +// khong phai vi dong bo tot, ma vi KHONG CO GI DE SO. +// +// 2. GYRO LAM TRON 2 CHU SO. +// Firmware in "0.00" nghia la do phan giai 0.01 do/s ~ 0.17 mrad/s. Doc +// duoc tren thiet bi dung yen: gyro_z = 0.00 o MOI mau. EKF yaw se khong +// thay chuyen dong cham hon nguong do. +// +// 3. KHONG CO BARO / SIEU AM / BUMPER. +// Dac ta co ban ghi B, U, K. Firmware khong co cai nao. Cac callback +// tuong ung KHONG BAO GIO duoc goi -- xem ghi chu tai cho dang ky. +// Dac biet nguy hiem voi bumper: lop safety cho rang mat bumper la mot +// duong doc lap, o day no khong ton tai. +// +// Duong sua dung la firmware phat theo mcu_protocol.h. Khi do xoa file nay +// va dung duong `I/B/E/U/K/P` da co san trong mcu_protocol.cc. + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "vslam/clock.h" +#include "vslam/driver_config.h" +#include "vslam/driver_interfaces.h" +#include "vslam/geometry.h" +#include "vslam/log.h" + +namespace vslam { +namespace { + +constexpr double kDeg2Rad = M_PI / 180.0; + +speed_t BaudConstant(uint32_t baud) { + switch (baud) { + case 9600: return B9600; + case 19200: return B19200; + case 38400: return B38400; + case 57600: return B57600; + case 115200: return B115200; + case 230400: return B230400; + case 460800: return B460800; + case 921600: return B921600; + default: return 0; + } +} + +class McuBridge : public McuInterface { + public: + McuBridge(const McuConfig& cfg, ClockPtr clock) + : cfg_(cfg), clock_(std::move(clock)) {} + + ~McuBridge() override { Close(); } + + void SetImuCallback(ImuCallback cb) override { imu_cb_ = std::move(cb); } + + // Ba callback duoi day KHONG BAO GIO duoc goi voi firmware hien tai -- + // khong phai quen noi day, ma la firmware khong phat B/U/K. Van nhan va + // giu de khi firmware dung dac ta thi chi phai sua mot cho. + void SetBaroCallback(BaroCallback cb) override { baro_cb_ = std::move(cb); } + void SetUltrasonicCallback(UltrasonicCallback cb) override { + ultra_cb_ = std::move(cb); + } + void SetBumperCallback(BumperCallback cb) override { + bumper_cb_ = std::move(cb); + } + + StatusResponse Open() override { + if (fd_ >= 0) { + return StatusResponse::Error(StatusCode::kFailedPrecondition, + "mcu: da mo roi"); + } + if (!clock_) { + return StatusResponse::Error(StatusCode::kInvalidArgument, + "mcu: thieu clock"); + } + + const speed_t speed = BaudConstant(cfg_.baud); + if (speed == 0) { + return StatusResponse::Error( + StatusCode::kInvalidArgument, + "mcu: baud " + std::to_string(cfg_.baud) + " khong ho tro"); + } + + fd_ = ::open(cfg_.port.c_str(), O_RDWR | O_NOCTTY | O_SYNC); + if (fd_ < 0) { + return StatusResponse::Error( + StatusCode::kUnavailable, + "mcu: mo " + cfg_.port + " that bai: " + std::strerror(errno) + + (errno == EACCES ? " -- thieu quyen? them user vao nhom dialout" + : "")); + } + + termios tty{}; + if (::tcgetattr(fd_, &tty) != 0) { + const std::string err = std::strerror(errno); + CloseFd(); + return StatusResponse::Error(StatusCode::kInternal, + "mcu: tcgetattr that bai: " + err); + } + + ::cfsetospeed(&tty, speed); + ::cfsetispeed(&tty, speed); + tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8 bit + tty.c_cflag |= (CLOCAL | CREAD); + tty.c_cflag &= ~(PARENB | PARODD); // khong parity + tty.c_cflag &= ~CSTOPB; // 1 stop bit + tty.c_cflag &= ~CRTSCTS; // khong flow control + tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL); + tty.c_iflag &= ~(IXON | IXOFF | IXANY); + tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); + tty.c_oflag &= ~OPOST; + // VMIN=0 + VTIME: read() tra ve sau nhieu nhat VTIME*100 ms du khong co + // byte nao. Can the de vong doc con thoat duoc khi Close(). + tty.c_cc[VMIN] = 0; + tty.c_cc[VTIME] = static_cast( + cfg_.read_timeout_sec > 0.0 ? cfg_.read_timeout_sec * 10.0 : 10); + + if (::tcsetattr(fd_, TCSANOW, &tty) != 0) { + const std::string err = std::strerror(errno); + CloseFd(); + return StatusResponse::Error(StatusCode::kInternal, + "mcu: tcsetattr that bai: " + err); + } + + VSLAM_INFO("mcu: mo " << cfg_.port << " @" << cfg_.baud); + if (!cfg_.expect_timestamps) { + VSLAM_WARN( + "mcu: firmware khong phat timestamp -- stamp lay tu dong ho HOST luc " + "doc duoc dong. Moi phep dong bo IMU voi LiDAR/camera mang mot do " + "tre khong do duoc. Xem mcu_bridge.cc, muc 1."); + } + + running_ = true; + thread_ = std::thread([this] { ReadLoop(); }); + return StatusResponse::Ok(); + } + + void Close() override { + running_ = false; + CloseFd(); + if (thread_.joinable()) thread_.join(); + } + + DriverStats Stats() const override { + std::lock_guard lk(stats_mu_); + return stats_; + } + + private: + void CloseFd() { + if (fd_ >= 0) { + ::close(fd_); + fd_ = -1; + } + } + + void ReadLoop() { + char buf[512]; + std::string line; + while (running_) { + const ssize_t n = ::read(fd_, buf, sizeof(buf)); + if (n < 0) { + if (!running_) break; + if (errno == EAGAIN || errno == EINTR) continue; + Fail(std::string("read() that bai: ") + std::strerror(errno)); + continue; + } + if (n == 0) continue; // timeout, khong phai loi + + for (ssize_t i = 0; i < n; ++i) { + if (buf[i] == '\n') { + ProcessLine(line); + line.clear(); + } else if (buf[i] != '\r') { + // Chan dong rac dai vo han neu thiet bi phat nhieu: mot dong hop le + // dai chung 30 ky tu. + if (line.size() < 256) line += buf[i]; + } + } + } + } + + void ProcessLine(const std::string& line) { + if (line.empty()) return; + + std::istringstream iss(line); + std::string type; + double x = 0.0, y = 0.0, z = 0.0; + if (!(iss >> type >> x >> y >> z)) { + // Dong khong doc duoc KHONG tinh la loi: firmware in ca banner luc + // khoi dong. Chi dem de thay khi ty le rac tang bat thuong. + ++unparsed_; + return; + } + + if (type == "Acc") { + ax_ = x; ay_ = y; az_ = z; + have_acc_ = true; + } else if (type == "Gyro") { + // DO/s -> rad/s. Firmware in do/s; Imu.angular_velocity la rad/s. + gx_ = x * kDeg2Rad; gy_ = y * kDeg2Rad; gz_ = z * kDeg2Rad; + have_gyro_ = true; + } else if (type == "Angle") { + roll_ = x * kDeg2Rad; pitch_ = y * kDeg2Rad; yaw_ = z * kDeg2Rad; + have_angle_ = true; + } else { + ++unparsed_; + return; + } + + if (have_acc_ && have_gyro_ && have_angle_) { + Publish(); + have_acc_ = have_gyro_ = have_angle_ = false; + } + } + + void Publish() { + auto imu = std::make_shared(); + imu->header.seq = seq_++; + // ⚠️ Dong ho HOST, khong phai dong ho thiet bi -- xem dau file, muc 1. + imu->header.stamp = clock_->Now(); + imu->header.frame_id = cfg_.imu_frame_id; + + imu->angular_velocity.x = gx_; + imu->angular_velocity.y = gy_; + imu->angular_velocity.z = gz_; + imu->linear_acceleration.x = ax_; + imu->linear_acceleration.y = ay_; + imu->linear_acceleration.z = az_; + imu->orientation = QuaternionFromRPY(roll_, pitch_, yaw_); + + // Covariance tu datasheet ICM-42688-P, deu la DOAN cho toi khi chay + // allan_variance. Dat tren duong cheo, khong de 0: 0 nghia la "chinh xac + // tuyet doi" voi moi bo loc doc no. + for (int i = 0; i < 3; ++i) { + imu->angular_velocity_covariance[i * 4] = cfg_.gyro_variance; + imu->linear_acceleration_covariance[i * 4] = cfg_.accel_variance; + } + // WT61PC co fusion rieng cho ra Angle, nhung do tin cay cua no khong do + // duoc o day. Khong dat [0] < 0 (tuc "khong co orientation") vi yaw van + // dung duoc lam goi y; de covariance lon de bo loc tu ha trong so. + for (int i = 0; i < 3; ++i) imu->orientation_covariance[i * 4] = 0.05; + + { + std::lock_guard lk(stats_mu_); + ++stats_.frames; + stats_.connected = true; + const UnixTime now = imu->header.stamp; + if (!last_pub_.isZero()) { + const double dt = (now - last_pub_).toSec(); + if (dt > 0.0) stats_.hz = 1.0 / dt; + } + last_pub_ = now; + // KHONG co gi de so -> de 0. Xem dau file, muc 1. + stats_.stamp_skew_ms = 0.0; + stats_.clock_skew_ppm = 0.0; + } + + if (imu_cb_) imu_cb_(imu); + } + + void Fail(const std::string& msg) { + { + std::lock_guard lk(stats_mu_); + ++stats_.errors; + stats_.connected = false; + stats_.last_error = msg; + } + VSLAM_WARN_THROTTLE(5.0, "mcu: " << msg); + } + + McuConfig cfg_; + ClockPtr clock_; + + ImuCallback imu_cb_; + BaroCallback baro_cb_; + UltrasonicCallback ultra_cb_; + BumperCallback bumper_cb_; + + int fd_ = -1; + std::atomic running_{false}; + std::thread thread_; + + double ax_ = 0.0, ay_ = 0.0, az_ = 0.0; + double gx_ = 0.0, gy_ = 0.0, gz_ = 0.0; + double roll_ = 0.0, pitch_ = 0.0, yaw_ = 0.0; + bool have_acc_ = false, have_gyro_ = false, have_angle_ = false; + uint64_t unparsed_ = 0; + uint32_t seq_ = 0; + UnixTime last_pub_; + + mutable std::mutex stats_mu_; + DriverStats stats_; +}; + +} // namespace + +std::unique_ptr CreateMcuBridge(const McuConfig& cfg, + ClockPtr clock) { + return std::make_unique(cfg, std::move(clock)); +} + +} // namespace vslam diff --git a/libs/vslam_drivers/src/zlac_base.cc b/libs/vslam_drivers/src/zlac_base.cc new file mode 100644 index 0000000..8b07a0d --- /dev/null +++ b/libs/vslam_drivers/src/zlac_base.cc @@ -0,0 +1,434 @@ +// Base ZLAC8015D qua CANopen (lely-core). +// +// ================== KIEN TRUC THAT KHAC DAC TA ================== +// driver_config.h gia dinh encoder ve qua serial MCU (`E,,...`). +// Tren robot nay KHONG PHAI VAY: encoder va motor deu di qua `can0`, DS402 +// Profile Velocity Mode. Nguon: base_kit/src/Zlac_ros, la code dang lai con +// robot nay that. +// +// Hau qua truc tiep: khong co duong nao dong bo dong ho base voi dong ho host. +// ClockSync chi bac cau duoc cho MCU serial. Stamp cua EncoderReading o day la +// dong ho HOST luc doc xong SDO/PDO. +// +// ================== OBJECT DICTIONARY DUNG O DAY ================== +// 0x6060:0 i8 Modes of operation = 3 (Profile Velocity) +// 0x6083/84 u32 Profile accel/decel (sub 1 = trai, 2 = phai) +// 0x6040:0 u16 Controlword 6 -> 7 -> F -> 7F (chuoi DS402) +// 0x60FF:3 u32 Target velocity GOP: 16 bit THAP = trai, CAO = phai +// (ZLAC8015D manual p.19-20) +// 0x606C:1/2 i32 Velocity actual, don vi 0.1 RPM +// 0x6064:1/2 i32 Position actual, don vi increment <-- doc o day +// 0x608F:1 u32 Encoder increments / vong +// +// ================== VI SAO DOC 0x6064 CHU KHONG TICH PHAN RPM ================== +// `EncoderReading` yeu cau GOC QUAY TICH LUY, khong phai van toc. Ly do nam o +// mcu_protocol.h: "Dung gui delta -- mat mot dong serial la mat vinh vien mot +// doan quang duong, va khong co cach nao phat hien." Tich phan RPM co dung +// benh do: moi lan lo mot mau telemetry la mat han mot doan duong, va sai so +// do KHONG BAO GIO duoc sua -- no cong don vao pose mai mai. +// +// base_kit hien tich phan RPM (Euler/mid-point trong +// differential_drive_kinematics.cpp). Doc 0x6064 thay the: bo dem tuyet doi +// trong driver motor, lo mot mau thi mau sau van dung vi no la TICH LUY. +// +// ⚠️ CHUA XAC MINH TREN THIET BI: khong cho nao trong base_kit doc 0x6064, nen +// chua ai chung minh ZLAC8015D co expose object nay. DS402 bat buoc no cho +// che do position, nhung thiet bi chay Profile Velocity co the khong map. +// Open() THU DOC va tra loi RO neu khong co, thay vi im lang tra ve 0 -- +// encoder dung yen o 0 trong khi robot dang chay la trieu chung rat kho lan +// ra, no trong het nhu "odometry chet". +// +// ================== BUILD ================== +// Can liblely-coapp. Tat bang -DVSLAM_WITH_CANOPEN=OFF thi file nay khong +// duoc bien dich va CreateDiffDriveBase tra ve driver bao kUnavailable -- +// cung ly do voi realsense: may CI khong co SDK phan cung van phai build duoc. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "vslam/clock.h" +#include "vslam/driver_config.h" +#include "vslam/driver_interfaces.h" +#include "vslam/log.h" + +namespace vslam { +namespace { + +constexpr double kTwoPi = 2.0 * M_PI; + +template +bool SdoWrite(lely::canopen::AsyncMaster& m, uint8_t node, uint16_t idx, + uint8_t sub, T val) { + std::promise prom; + auto fut = prom.get_future(); + m.SubmitWrite(m.get_executor(), node, idx, sub, val, + [&prom](uint8_t, uint16_t, uint8_t, std::error_code ec) { + prom.set_value(!ec); + }); + return fut.wait_for(std::chrono::seconds(2)) == std::future_status::ready && + fut.get(); +} + +template +std::optional SdoRead(lely::canopen::AsyncMaster& m, uint8_t node, + uint16_t idx, uint8_t sub) { + std::promise> prom; + auto fut = prom.get_future(); + m.SubmitRead(m.get_executor(), node, idx, sub, + [&prom](uint8_t, uint16_t, uint8_t, std::error_code ec, T v) { + prom.set_value(ec ? std::nullopt : std::optional(v)); + }); + if (fut.wait_for(std::chrono::seconds(2)) != std::future_status::ready) { + return std::nullopt; + } + return fut.get(); +} + +class ZlacBase; + +class LelyBridge : public lely::canopen::BasicDriver { + public: + LelyBridge(lely::canopen::AsyncMaster& m, uint8_t id, std::atomic* lost) + : BasicDriver(m, id), lost_(lost) {} + + protected: + void OnBoot(lely::canopen::NmtState, char, const std::string&) noexcept override { + master.Command(lely::canopen::NmtCommand::START, id()); + } + void OnHeartbeat(bool occurred) noexcept override { + if (lost_) lost_->store(occurred); + if (occurred) { + VSLAM_ERROR("base: mat heartbeat CANopen node " << static_cast(id())); + } + } + + private: + std::atomic* lost_ = nullptr; +}; + +class ZlacBase : public BaseInterface { + public: + ZlacBase(const BaseConfig& cfg, ClockPtr clock) + : cfg_(cfg), clock_(std::move(clock)) {} + + ~ZlacBase() override { Close(); } + + void SetEncoderCallback(EncoderCallback cb) override { cb_ = std::move(cb); } + + StatusResponse Open() override { + if (!clock_) { + return StatusResponse::Error(StatusCode::kInvalidArgument, + "base: thieu clock"); + } + if (cfg_.dcf_path.empty()) { + return StatusResponse::Error( + StatusCode::kInvalidArgument, + "base: thieu dcf_path. lely can file master.dcf sinh bang `dcfgen` " + "-- xem base_kit/src/Zlac_ros/config/master.yml"); + } + if (!(cfg_.wheel_radius > 0.0) || !(cfg_.wheel_separation > 0.0)) { + return StatusResponse::Error(StatusCode::kInvalidArgument, + "base: wheel_radius / wheel_separation <= 0"); + } + + try { + io_guard_ = std::make_unique(); + ctx_ = std::make_unique(); + poll_ = std::make_unique(*ctx_); + loop_ = std::make_unique(poll_->get_poll()); + auto exec = loop_->get_executor(); + timer_ = std::make_unique(*poll_, exec, CLOCK_MONOTONIC); + ctrl_ = std::make_unique(cfg_.can_channel.c_str()); + chan_ = std::make_unique(*poll_, exec); + chan_->open(*ctrl_); + master_ = std::make_unique( + *timer_, *chan_, cfg_.dcf_path, "", 127); + bridge_ = std::make_unique(*master_, cfg_.can_node_id, &lost_); + master_->Reset(); + lely_thread_ = std::thread([this] { + try { loop_->run(); } catch (...) {} + }); + } catch (const std::exception& e) { + return StatusResponse::Error( + StatusCode::kUnavailable, + "base: khong mo duoc CANopen tren " + cfg_.can_channel + ": " + + e.what() + " -- `ip link show " + cfg_.can_channel + "` co UP khong?"); + } + + if (StatusResponse st = EnableDs402(); !st.ok()) return st; + if (StatusResponse st = ResolveEncoderScale(); !st.ok()) return st; + + running_ = true; + poll_thread_ = std::thread([this] { PollLoop(); }); + return StatusResponse::Ok(); + } + + void Close() override { + running_ = false; + if (poll_thread_.joinable()) poll_thread_.join(); + + // Tat power stage TRUOC khi go master: huy master truoc thi lenh dung + // khong bao gio toi duoc motor, va xe chay tiep voi target cuoi cung. + if (master_ && ready_) { + SdoWrite(*master_, cfg_.can_node_id, 0x6040, 0, 0x0006); + ready_ = false; + } + if (loop_) loop_->stop(); + if (lely_thread_.joinable()) lely_thread_.join(); + + bridge_.reset(); master_.reset(); chan_.reset(); ctrl_.reset(); + timer_.reset(); loop_.reset(); poll_.reset(); ctx_.reset(); io_guard_.reset(); + } + + void SetVelocity(double linear, double angular) override { + // Kep o day la CHAN CUOI, doc lap voi lop safety va voi deadman teleop. + linear = Clamp(linear, cfg_.max_linear); + angular = Clamp(angular, cfg_.max_angular); + + const double half = cfg_.wheel_separation * 0.5; + const double v_l = linear - angular * half; // m/s tai banh + const double v_r = linear + angular * half; + + // m/s -> rad/s tai banh -> RPM + const double rpm_l = (v_l / cfg_.wheel_radius) * 60.0 / kTwoPi; + const double rpm_r = (v_r / cfg_.wheel_radius) * 60.0 / kTwoPi; + + { + std::lock_guard lk(cmd_mu_); + target_l_ = static_cast(std::lround(rpm_l)); + // Banh phai lap doi chieu -- base_kit KinematicsConfig::invert_right_wheel + // mac dinh true. Sai dau o day thi robot quay tai cho thay vi di thang. + target_r_ = static_cast(std::lround(-rpm_r)); + last_cmd_ = clock_->Now(); + have_cmd_ = true; + } + } + + DriverStats Stats() const override { + std::lock_guard lk(stats_mu_); + return stats_; + } + + private: + static double Clamp(double v, double lim) { + if (!(lim > 0.0)) return v; + return (v > lim) ? lim : ((v < -lim) ? -lim : v); + } + + StatusResponse EnableDs402() { + master_->Command(lely::canopen::NmtCommand::START, cfg_.can_node_id); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + + bool mode_ok = false; + for (int attempt = 0; attempt < 3 && !mode_ok; ++attempt) { + mode_ok = SdoWrite(*master_, cfg_.can_node_id, 0x6060, 0, 3); + if (!mode_ok) std::this_thread::sleep_for(std::chrono::milliseconds(200)); + } + if (!mode_ok) { + return StatusResponse::Error( + StatusCode::kUnavailable, + "base: khong dat duoc Profile Velocity Mode (0x6060:0 = 3). Driver " + "co dang bat nguon va dung node_id " + + std::to_string(cfg_.can_node_id) + " khong?"); + } + + const uint32_t acc = 500; + SdoWrite(*master_, cfg_.can_node_id, 0x6083, 1, acc); + SdoWrite(*master_, cfg_.can_node_id, 0x6083, 2, acc); + SdoWrite(*master_, cfg_.can_node_id, 0x6084, 1, acc); + SdoWrite(*master_, cfg_.can_node_id, 0x6084, 2, acc); + + // Chuoi chuyen trang thai DS402. Bo qua mot buoc thi power stage khong + // bao gio bat, va trieu chung la "gui lenh nhung xe khong nhuc nhich". + for (uint16_t cw : {0x0006, 0x0007, 0x000F, 0x007F}) { + if (!SdoWrite(*master_, cfg_.can_node_id, 0x6040, 0, cw)) { + return StatusResponse::Error( + StatusCode::kUnavailable, + "base: chuoi DS402 dung o controlword 0x" + ToHex(cw)); + } + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + ready_ = true; + return StatusResponse::Ok(); + } + + // Quyet dinh so increment/vong, va CHUNG MINH 0x6064 doc duoc. + StatusResponse ResolveEncoderScale() { + counts_per_rev_ = cfg_.encoder_counts_per_rev; + if (counts_per_rev_ == 0) { + if (auto inc = SdoRead(*master_, cfg_.can_node_id, 0x608F, 1)) { + counts_per_rev_ = *inc; + } + } + if (counts_per_rev_ == 0) { + return StatusResponse::Error( + StatusCode::kFailedPrecondition, + "base: khong biet so increment/vong. Thiet bi khong tra loi " + "0x608F:1, va encoder_counts_per_rev trong config dang la 0. Dat " + "tuong minh tu datasheet ZLAC8015D roi chay lai."); + } + + // Doc thu 0x6064 -- neu thiet bi khong map object nay thi bao NGAY o day. + const auto l = SdoRead(*master_, cfg_.can_node_id, 0x6064, 1); + const auto r = SdoRead(*master_, cfg_.can_node_id, 0x6064, 2); + if (!l || !r) { + return StatusResponse::Error( + StatusCode::kFailedPrecondition, + "base: ZLAC8015D khong tra loi 0x6064 (Position Actual Value). " + "EncoderReading can goc quay TICH LUY, ma 0x606C chi cho van toc " + "tuc thoi -- tich phan van toc lam mat vinh vien moi doan duong bi " + "lo mot mau. Kiem lai PDO/SDO mapping cua driver, hoac doi thiet ke " + "sang chap nhan troi tich luy."); + } + origin_l_ = *l; + origin_r_ = *r; + VSLAM_INFO("base: CANopen " << cfg_.can_channel << " node " + << static_cast(cfg_.can_node_id) << ", " + << counts_per_rev_ << " increment/vong, 0x6064 OK"); + return StatusResponse::Ok(); + } + + static std::string ToHex(uint16_t v) { + static const char* d = "0123456789ABCDEF"; + std::string s(4, '0'); + for (int i = 3; i >= 0; --i) { s[i] = d[v & 0xF]; v >>= 4; } + return s; + } + + void PollLoop() { + const double period = (cfg_.rate_hz > 0.0) ? 1.0 / cfg_.rate_hz : 0.02; + while (running_) { + PushVelocity(); + ReadEncoders(); + std::this_thread::sleep_for( + std::chrono::duration(period)); + } + } + + void PushVelocity() { + int16_t l = 0, r = 0; + { + std::lock_guard lk(cmd_mu_); + const double age = have_cmd_ ? (clock_->Now() - last_cmd_).toSec() : 1e9; + // Watchdog: khong nhan lenh trong cmd_timeout_sec thi TU DUNG. Chan cuoi + // cung, doc lap voi lop safety va deadman cua teleop. + if (age <= cfg_.cmd_timeout_sec) { + l = target_l_; + r = target_r_; + } else if (have_cmd_) { + VSLAM_WARN_THROTTLE(2.0, "base: khong co cmd trong " << age + << " s -- dung motor"); + } + } + + if (l == sent_l_ && r == sent_r_) return; // bot traffic CAN + if (!master_ || !ready_) return; + + const uint32_t combined = (static_cast(l) & 0xFFFFu) | + (static_cast(static_cast(r) & 0xFFFFu) << 16); + master_->SubmitWrite(master_->get_executor(), cfg_.can_node_id, 0x60FF, 3, + combined, + [](uint8_t, uint16_t, uint8_t, std::error_code) {}); + sent_l_ = l; + sent_r_ = r; + } + + void ReadEncoders() { + if (!master_) return; + const auto l = SdoRead(*master_, cfg_.can_node_id, 0x6064, 1); + const auto r = SdoRead(*master_, cfg_.can_node_id, 0x6064, 2); + + EncoderReading out; + out.stamp = clock_->Now(); + if (!l || !r) { + out.valid = false; + { + std::lock_guard lk(stats_mu_); + ++stats_.errors; + stats_.connected = false; + stats_.last_error = "khong doc duoc 0x6064"; + } + if (cb_) cb_(out); + return; + } + + // increment -> radian. Tru goc luc Open() de pose bat dau tu 0 thay vi + // tu mot so tuy y con lai tu lan chay truoc. + const double scale = kTwoPi / static_cast(counts_per_rev_); + out.left_rad = static_cast(*l - origin_l_) * scale; + // Cung phep doi dau voi lenh gui xuong -- neu khong thi robot di thang + // ma odometry bao dang quay. + out.right_rad = -static_cast(*r - origin_r_) * scale; + out.valid = true; + + { + std::lock_guard lk(stats_mu_); + ++stats_.frames; + stats_.connected = !lost_.load(); + if (!last_enc_.isZero()) { + const double dt = (out.stamp - last_enc_).toSec(); + if (dt > 0.0) stats_.hz = 1.0 / dt; + } + last_enc_ = out.stamp; + } + + if (cb_) cb_(out); + } + + BaseConfig cfg_; + ClockPtr clock_; + EncoderCallback cb_; + + std::unique_ptr io_guard_; + std::unique_ptr ctx_; + std::unique_ptr poll_; + std::unique_ptr loop_; + std::unique_ptr timer_; + std::unique_ptr ctrl_; + std::unique_ptr chan_; + std::unique_ptr master_; + std::unique_ptr bridge_; + std::thread lely_thread_; + + std::atomic running_{false}; + std::atomic lost_{false}; + bool ready_ = false; + std::thread poll_thread_; + + uint32_t counts_per_rev_ = 0; + int32_t origin_l_ = 0, origin_r_ = 0; + UnixTime last_enc_; + + std::mutex cmd_mu_; + int16_t target_l_ = 0, target_r_ = 0; + int16_t sent_l_ = 0, sent_r_ = 0; + UnixTime last_cmd_; + bool have_cmd_ = false; + + mutable std::mutex stats_mu_; + DriverStats stats_; +}; + +} // namespace + +std::unique_ptr CreateDiffDriveBase(const BaseConfig& cfg, + ClockPtr clock) { + return std::make_unique(cfg, std::move(clock)); +} + +} // namespace vslam diff --git a/test/test_robot_model.cc b/test/test_robot_model.cc index be63681..b30f80c 100644 --- a/test/test_robot_model.cc +++ b/test/test_robot_model.cc @@ -197,11 +197,17 @@ TEST(RobotModel, FileThatTrongConfigurationFilesNapDuoc) { ASSERT_TRUE(st.ok()) << st.message; // Va no phai khop voi cac gia tri ma phan con lai cua he dang gia dinh. - EXPECT_NEAR(m.camera_height_above_floor(), 0.80, 1e-9) - << "chieu cao camera doi -> cliff_detect.nominal_tz phai doi theo"; - EXPECT_NEAR(m.geometry().wheel_radius, 0.075, 1e-9); + // Ba so nay do tren robot that (banh Ø173 mm; camera cao hon LiDAR 17.7 cm + // va truoc 9.5 cm; LiDAR cao 13 cm so voi tam truc, x = 0). + EXPECT_NEAR(m.camera_height_above_floor(), 0.3935, 1e-9) + << "chieu cao camera doi -> cliff_detect.min_dist va nominal_tz phai " + "doi theo. Xem pipeline.yaml muc cliff_detect."; + EXPECT_NEAR(m.geometry().wheel_radius, 0.0865, 1e-9); + EXPECT_NEAR(m.geometry().wheel_separation, 0.400, 1e-9); Transform t; ASSERT_TRUE(m.StaticTransform(kBaseLinkFrame, kLaserFrame, &t)); - EXPECT_NEAR(t.translation.x, 0.24, 1e-9); + // LiDAR ngay tren tam truc, khong phai gan mep truoc. + EXPECT_NEAR(t.translation.x, 0.0, 1e-9); + EXPECT_NEAR(t.translation.z, 0.13, 1e-9); }