This commit is contained in:
trung09122002
2026-09-19 19:10:14 +07:00
parent 6c3d5bfdc1
commit 3c275cf0af
18 changed files with 2304 additions and 825 deletions

View File

@@ -575,6 +575,27 @@ void Runtime::Join() {
#endif
if (web_) web_->Stop();
// ⚠️ DONG THIET BI O DAY, truoc khi ham nay tra ve.
//
// Driver that chay luong RIENG va goi callback vao ekf_, safety_, web_...
// Nhung `source_` (chu so huu driver) duoc khai bao TRUOC cac stage trong
// runtime.h, ma C++ huy thanh vien theo thu tu NGUOC -- tuc stage chet
// truoc, driver chet sau. Trong khoang do luong driver van dang goi vao bo
// nho vua duoc giai phong.
//
// Da xay ra that tren robot: `malloc(): unsorted double linked list
// corrupted` moi lan Ctrl-C.
//
// Sim va replay khong lo dieu nay vi RequestStop() dung vong Run() cua
// chung truoc; driver that khong co vong Run() nao de dung.
if (camera_ != nullptr) camera_->Close();
if (mcu_ != nullptr) mcu_->Close();
if (lidar_ != nullptr) lidar_->Close();
// Base DONG CUOI: SetVelocity(0) o tren vua gui lenh dung, va Close() cua
// no con tat power stage. Dong no truoc cac driver kia khong sai, nhung de
// cuoi thi cua so "da dung nhung chua tat dien" ngan nhat.
if (base_ != nullptr) base_->Close();
}
void Runtime::SafetyLoop() {

View File

@@ -58,13 +58,23 @@ cliff_detect:
# 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
# max_dist khong phai rang buoc hinh hoc ma la gioi han NHIEU DEPTH: cang
# luot san thi stereo cang khong bat duoc gi tren san phang khong van.
#
# ⚠️ Gia tri cu 2.50 da gay BAO VUC GIA tren robot that: camera 0.3935 m
# nhin toi 2.5 m cho goc luot 8.9 do, D410 khong tra ve depth o do, va
# "khong thay san" bi doc thanh "co vuc".
#
# Chon 1.20 de giu DUNG ngan sach goc cua thiet ke cu: camera 0.80 m nhin
# toi 2.50 m la 17.7 do; camera 0.3935 m dat 17.7 do o 1.23 m.
#
# 0.55 m -> 35.6 do 1.20 m -> 18.2 do
# 0.80 m -> 26.2 do 1.50 m -> 14.7 do
# 1.00 m -> 21.5 do 2.50 m -> 8.9 do (hong)
#
# Doi lai: tam nhin vuc ngan hon truoc. Voi safety dung o 0.35 m va cham
# lai tu 0.80 m thi 1.20 m van con bien.
max_dist: 1.20
cliff_margin: 0.05
pitch_uncertainty_deg: 2.0

View File

@@ -22,14 +22,39 @@ vslam_add_library(vslam_drivers
vslam_common
)
# ---------------------------------------------------------------------------
# Code NHUNG tu base_kit -- ban driver CHUAN cho phan cung nay.
# Xem thirdparty/PROVENANCE.md truoc khi sua bat cu gi trong do.
# ---------------------------------------------------------------------------
# SDK LakiBeam + lidar_core. Chi can Boost, KHONG can ROS.
#
# Gop thang vao vslam_drivers thay vi dung lam mot target rieng: chung khong
# duoc cai ra ngoai, va mot target rieng se phai export/install theo. Bien
# dich voi -w: day la nguon cua nha cung cap, canh bao cua no khong phai viec
# cua du an nay va -Wall -Wextra -Wpedantic toan cuc se nhan chim log build.
find_package(Boost REQUIRED COMPONENTS system thread)
target_sources(vslam_drivers PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lakibeam_sdk/LakiBeamUDP.cpp
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/lakibeam_driver.cpp
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/scan_conversion.cpp)
set_source_files_properties(
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lakibeam_sdk/LakiBeamUDP.cpp
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/lakibeam_driver.cpp
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src/scan_conversion.cpp
PROPERTIES COMPILE_OPTIONS "-w")
target_include_directories(vslam_drivers PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lakibeam_sdk
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/include
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/lidar_core/src)
target_link_libraries(vslam_drivers PRIVATE Boost::system Boost::thread)
# Driver RealSense la file rieng, chi bien dich khi co SDK. GLOB_RECURSE gom
# het src/ nen phai loai no ra khi tat -- neu khong thi `#include <rs.hpp>`
# 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.
# zlac_base.cc cung the, voi liblely-coapp.
get_target_property(_vslam_drv_srcs vslam_drivers SOURCES)
list(FILTER _vslam_drv_srcs EXCLUDE REGEX "(realsense_driver|zlac_base)\\.cc$")
set_target_properties(vslam_drivers PROPERTIES SOURCES "${_vslam_drv_srcs}")
@@ -44,10 +69,18 @@ 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_sources(vslam_drivers PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src/zlac_base.cc
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/zlac/src/zlac_motor_driver.cpp
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/zlac/src/differential_drive_kinematics.cpp)
set_source_files_properties(
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/zlac/src/zlac_motor_driver.cpp
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/zlac/src/differential_drive_kinematics.cpp
PROPERTIES COMPILE_OPTIONS "-w")
target_include_directories(vslam_drivers PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/thirdparty/zlac/include)
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})

View File

@@ -1,133 +1,58 @@
// Driver LakiBeam 1L (UDP MSOP, port 2368).
// Driver LakiBeam 1L -- LOP BOC quanh `lidar_core` cua base_kit.
//
// ================== 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
// ================== VI SAO BOC CHU KHONG TU GIAI MA ==================
// Ban truoc cua file nay tu giai ma goi UDP 1206 byte. No chay duoc, nhung
// ba lan lien tiep lo ra nhung chi tiet chi ban SDK moi biet:
//
// ================== KHUNG GOI (1206 byte CO DINH) ==================
// 12 block x 100 byte + 6 byte duoi. Khop `udp_pack_t` cua SDK.
// 1. Hang magic: byte tren day la `ff ee`, doc little-endian ra 0xEEFF chu
// khong phai 0xFFEE. Moi goi bi tu choi cho toi khi sua.
// 2. Mot block trong moi goi deu dan khong co header -- chua bao gio tim ra
// vi sao.
// 3. Thiet bi gui ca vong quet thanh MOT CHUM roi nghi ~30 ms. Do khoang
// trong chum ra "sweep 0.9 ms" tuc 1100 Hz, va scan_time sai ~30 lan
// mot cach hoan toan im lang.
//
// 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
// `lidar_core` + `lakibeam_sdk` la ban driver CHUAN dang chay that tren robot
// nay, va ba chuyen tren no da xu ly het. Nhung vao repo (xem
// thirdparty/PROVENANCE.md) va boc lai re hon nhieu so voi tiep tuc do lai
// tung chi tiet cua mot dinh dang da co nguoi giai xong.
//
// ⚠️ 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.
// ================== PHAN CON LAI CUA FILE NAY ==================
// Chi lam ba viec:
// * doi LidarConfig cua vslam sang LakibeamConfig cua lidar_core
// * doi lidar_core::LaserScan sang vslam::LaserScan
// * dong dau bang Clock cua vslam, khong dung dong ho ma SDK tu lay
//
// 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_`.
//
// ================== QUY UOC GOC + TU THE GAN ==================
// 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)
//
// LiDAR tren robot nay GAN UP NGUOC, tuc xoay 180do quanh truc X (Y doi dau):
// gan xuoi -> t = 90do - a (offset +90, inverted = true)
// gan up nguoc -> t = a - 90do (offset -90, inverted = FALSE)
//
// Hai phep dao dau -- cua quy uoc va cua tu the gan -- triet tieu nhau. Chi
// tiet va canh bao "dung bu lan thu hai trong TF" nam o driver_config.h.
//
// 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.
// KHONG goi ScanSanitizer: node tu ve sinh (wiring.cc) bang MOT doi tuong duy
// nhat, va ban ghi .vsr co y luu du lieu THO de doi nguong roi test lai.
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#include <array>
#include <atomic>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <limits>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
#include "lidar_core/lakibeam_driver.hpp"
#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
// ⚠️ 0xEEFF, khong phai 0xFFEE.
//
// Tren DAY, hai byte dau moi block la `ff ee` theo dung thu tu do. Doc chung
// bang RdLe16 (little-endian, p[0] | p[1]<<8) ra 0xEEFF. Hang so 0xFFEE la
// cach NGUOI DOC viet chuoi byte, khong phai gia tri sau khi doc LE.
//
// Da mac dung loi nay: lan chay dau tren robot, MOI goi deu bi tu choi voi
// "goi khong bat dau bang 0xFFEE" trong khi du lieu hoan toan binh thuong.
constexpr uint16_t kBlockHead = 0xEEFF;
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<float>::infinity();
uint16_t RdLe16(const uint8_t* p) {
return static_cast<uint16_t>(p[0] | (static_cast<uint16_t>(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 {
class LakiBeamWrapper : public LidarInterface {
public:
LakiBeamDriver(const LidarConfig& cfg, ClockPtr clock)
LakiBeamWrapper(const LidarConfig& cfg, ClockPtr clock)
: cfg_(cfg), clock_(std::move(clock)) {}
~LakiBeamDriver() override { Close(); }
~LakiBeamWrapper() override { Close(); }
void SetCallback(ScanCallback cb) override { cb_ = std::move(cb); }
StatusResponse Open() override {
if (fd_ >= 0) {
if (impl_) {
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"lidar: da mo roi");
}
@@ -135,318 +60,115 @@ class LakiBeamDriver : public LidarInterface {
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) {
lidar_core::LakibeamConfig lc;
lc.host_ip = cfg_.host_ip;
lc.host_port = std::to_string(cfg_.port);
lc.lidar_port = std::to_string(cfg_.port);
lc.frame_id = cfg_.frame_id;
lc.range_min = static_cast<float>(cfg_.sanitizer.range_min);
lc.range_max = static_cast<float>(cfg_.sanitizer.range_max);
// Quy uoc goc. Manual §8.1 cho X = R*sin(a), Y = R*cos(a); REP-103 dung
// x = R*cos(t) => t = 90do - a. LiDAR tren robot nay GAN UP NGUOC, tuc
// xoay 180do quanh truc X (Y doi dau), nen thanh t = a - 90do.
//
// lidar_core tinh: t = (angle_flip ? -a : a) + angle_offset_deg
// Voi gan up nguoc: angle_flip = false, offset = -90.
lc.angle_offset_deg = cfg_.angle_offset_deg;
lc.angle_flip = cfg_.inverted;
// Lay TRON 360 do, khong crop.
//
// vslam co lop cat quat rieng (ScanSanitizer + sector_masks trong
// sensors.yaml) va no la lop DUY NHAT duoc cat. Bat crop o day nua thi co
// hai cho cat doc lap, va khi mot vat can bien mat khoi scan se khong ai
// biet cho nao cat no.
lc.crop_fov = false;
impl_ = std::make_unique<lidar_core::LakiBeamDriver>(lc);
impl_->setCallback([this](const lidar_core::LaserScan& s) { OnScan(s); });
if (!impl_->start()) {
impl_.reset();
return StatusResponse::Error(
StatusCode::kUnavailable,
std::string("lidar: socket() that bai: ") + std::strerror(errno));
"lidar: lidar_core start() that bai tren " + cfg_.host_ip + ":" +
std::to_string(cfg_.port) +
" -- co tien trinh khac dang giu port 2368 khong? "
"(lakibeam_ros cua base_kit chang han)");
}
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<time_t>(cfg_.recv_timeout_sec);
tv.tv_usec = static_cast<suseconds_t>(
(cfg_.recv_timeout_sec - static_cast<double>(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<sockaddr*>(&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(); });
VSLAM_INFO("lidar: lidar_core tren " << cfg_.host_ip << ":" << cfg_.port
<< " angle_offset=" << lc.angle_offset_deg
<< " do flip=" << (lc.angle_flip ? "true" : "false")
<< " range=[" << lc.range_min << ", " << lc.range_max << "] m");
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();
if (!impl_) return;
impl_->stop();
impl_.reset();
}
DriverStats Stats() const override {
std::lock_guard<std::mutex> lk(stats_mu_);
std::lock_guard<std::mutex> lk(mu_);
return stats_;
}
private:
void CloseFd() {
if (fd_ >= 0) {
::close(fd_);
fd_ = -1;
}
}
void OnScan(const lidar_core::LaserScan& in) {
auto out = std::make_shared<LaserScan>();
out->header.seq = seq_++;
out->header.frame_id = cfg_.frame_id;
void Reset() {
points_.clear();
points_.reserve(cfg_.samples + kDepthsPerBlock);
have_pending_ = false;
sweep_start_ = UnixTime();
sweep_end_ = UnixTime();
}
void RecvLoop() {
std::vector<uint8_t> 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<size_t>(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<double>(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<double>(az) + step * static_cast<double>(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<float>(dist * cfg_.range_unit_m);
pt.intensity = static_cast<float>(rssi);
points_.push_back(pt);
}
}
void Emit() {
if (points_.empty()) {
Reset();
return;
}
auto scan = std::make_shared<LaserScan>();
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<float>(-cfg_.fov_rad / 2.0);
scan->angle_max = static_cast<float>(cfg_.fov_rad / 2.0);
scan->angle_increment =
static_cast<float>(cfg_.fov_rad / static_cast<double>(cfg_.samples - 1));
scan->scan_time = static_cast<float>(measured);
scan->time_increment =
static_cast<float>(measured / static_cast<double>(cfg_.samples));
scan->range_min = static_cast<float>(cfg_.sanitizer.range_min);
scan->range_max = static_cast<float>(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<size_t>(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);
// ⚠️ Dong dau bang Clock cua vslam, KHONG dung in.header.stamp_*.
// lidar_core lay thang system_clock; vslam bat buoc moi stage di qua
// Clock& (xem clock.h) vi do la thu giu cho replay tat dinh. Mot cho goi
// dong ho he thong truc tiep la mat tinh tat dinh, va khong sua duoc
// bang cach sua rieng replay.
UnixTime stamp = clock_->Now();
if (cfg_.stamp_offset_sec != 0.0) {
stamp = stamp + Duration::fromSec(cfg_.stamp_offset_sec);
}
scan->header.stamp = stamp;
out->header.stamp = stamp;
out->angle_min = in.angle_min;
out->angle_max = in.angle_max;
out->angle_increment = in.angle_increment;
out->time_increment = in.time_increment;
out->scan_time = in.scan_time;
out->range_min = in.range_min;
out->range_max = in.range_max;
out->ranges = in.ranges;
out->intensities = in.intensities;
// ⚠️ KHONG goi ScanSanitizer o day, du LidarConfig co mang mot
// ScanSanitizerConfig. Driver tra ve scan THO.
//
// Hai ly do, ca hai deu tu kien truc co san:
// 1. Node da ve sinh roi (wiring.cc goi sanitizer_->Apply), va no dung
// DUNG MOT doi tuong ScanSanitizer cho moi nguon. Ve sinh hai lan
// la lam thua, va lam lech thong ke cua chinh sanitizer do.
// 2. Ban ghi .vsr luu du lieu THO co y -- replay_source.h noi ro "de doi
// nguong roi test lai duoc". Neu driver ve sinh truoc khi ghi thi
// nguong bi dong cung vao file va khong bao gio chinh lai duoc.
//
// cfg_.sanitizer o day CHI dung de dien range_min/range_max cua header.
{
std::lock_guard<std::mutex> lk(stats_mu_);
std::lock_guard<std::mutex> lk(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) {
if (in.scan_time > 0.0f) stats_.hz = 1.0 / in.scan_time;
// O trong = mat goi UDP. Dem tia huu han thay vi tin mot bo dem goi nao.
const size_t finite = static_cast<size_t>(std::count_if(
in.ranges.begin(), in.ranges.end(),
[](float r) { return std::isfinite(r); }));
if (!in.ranges.empty() && finite * 2 < in.ranges.size()) {
++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<std::mutex> lk(stats_mu_);
++stats_.errors;
stats_.connected = false;
stats_.last_error = msg;
}
VSLAM_WARN_THROTTLE(5.0, "lidar: " << msg);
if (cb_) cb_(out);
}
LidarConfig cfg_;
ClockPtr clock_;
ScanCallback cb_;
int fd_ = -1;
std::atomic<bool> running_{false};
std::thread thread_;
std::array<uint8_t, kPacketBytes> pending_{};
UnixTime pending_rx_;
bool have_pending_ = false;
std::vector<Point> points_;
UnixTime sweep_start_;
UnixTime sweep_end_;
uint32_t prev_az_ = 0;
bool have_prev_az_ = false;
std::unique_ptr<lidar_core::LakiBeamDriver> impl_;
uint32_t seq_ = 0;
mutable std::mutex stats_mu_;
mutable std::mutex mu_;
DriverStats stats_;
};
@@ -454,7 +176,7 @@ class LakiBeamDriver : public LidarInterface {
std::unique_ptr<LidarInterface> CreateLakiBeamDriver(const LidarConfig& cfg,
ClockPtr clock) {
return std::make_unique<LakiBeamDriver>(cfg, std::move(clock));
return std::make_unique<LakiBeamWrapper>(cfg, std::move(clock));
}
} // namespace vslam

View File

@@ -1,73 +1,40 @@
// Base ZLAC8015D qua CANopen (lely-core).
// Base ZLAC8015D -- LOP BOC quanh `ZlacMotorDriver` cua base_kit.
//
// ================== KIEN TRUC THAT KHAC DAC TA ==================
// driver_config.h gia dinh encoder ve qua serial MCU (`E,<micros>,...`).
// 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.
// Tren robot nay KHONG PHAI VAY: encoder va motor deu di qua `can0`, CANopen
// DS402 Profile Velocity Mode.
//
// 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.
// ClockSync chi bac cau duoc cho MCU serial. Stamp cua EncoderReading la dong
// ho HOST luc doc xong cache telemetry.
//
// ================== 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 r/min
// 0x6064:1/2 i32 Position actual, don vi "count" <-- doc o day
// 0x200E:1/2 u16 Encoder wire number (vung Factory Custom), mac dinh 1024
// ================== VI SAO BOC CHU KHONG TU VIET ==================
// Ban truoc cua file nay tu dieu khien lely. No chay duoc toi tan 0x6064,
// nhung mat ba vong thu-sai cho nhung thu ban goc da biet: phai cho slave
// BOOT xong roi moi gui SDO dau tien, thu tu chuoi DS402, va 0x608F khong
// ton tai tren thiet bi nay.
//
// ⚠️ KHONG dung 0x608F (Position encoder resolution cua DS402). ZLAC8015D
// KHONG co object do -- Appendix A liet ke day du dai CiA402 va no dung o
// 6087h roi nhay thang toi 60FFh. So vong day encoder nam o 0x200E, trong
// vung rieng cua nha san xuat.
// `ZlacMotorDriver` la ban CHUAN dang lai con robot nay. Xem
// thirdparty/PROVENANCE.md.
//
// ================== 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.
//
// DA XAC MINH TRONG TAI LIEU: can_help.pdf (ZLAC8015DD CANopen Communication
// Routine V1.0) Appendix A ghi ro:
// 6064h :01 Position_actual_value (left) I32 RO "unit: count"
// :02 Position_actual_value (right) I32 RO
// Open() van doc thu mot lan: neu vi ly do gi no khong tra loi thi phai biet
// NGAY, chu khong phai sau nua gio thay pose dung yen o goc 0 -- trieu chung
// do trong het nhu "odometry chet" va rat kho lan ra.
//
// ================== 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.
// ================== MOT CHO DA SUA TRONG BAN NHUNG ==================
// Ban goc chi co `getActualRPM()` -- tuc chi co VAN TOC. `EncoderReading` can
// GOC QUAY TICH LUY: tich phan van toc thi lo mot mau telemetry la mat vinh
// vien mot doan quang duong va khong co cach nao phat hien (mcu_protocol.h).
// Da them `getPositionCounts()` doc 0x6064 -- bo dem TUYET DOI trong driver
// motor, lo mau khong mat gi.
#include <lely/coapp/master.hpp>
#include <lely/coapp/driver.hpp>
#include <lely/ev/loop.hpp>
#include <lely/io2/linux/can.hpp>
#include <lely/io2/posix/poll.hpp>
#include <lely/io2/sys/io.hpp>
#include <lely/io2/sys/timer.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <algorithm>
#include <cmath>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <thread>
#include "zlac_ros/differential_drive_kinematics.hpp"
#include "zlac_ros/zlac_motor_driver.hpp"
#include "vslam/clock.h"
#include "vslam/driver_config.h"
#include "vslam/driver_interfaces.h"
@@ -78,82 +45,30 @@ namespace {
constexpr double kTwoPi = 2.0 * M_PI;
template <typename T>
bool SdoWrite(lely::canopen::AsyncMaster& m, uint8_t node, uint16_t idx,
uint8_t sub, T val) {
std::promise<bool> 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();
}
// 0x200E:01 tren thiet bi nay doc ra 4096 "wire". Quy uoc cau phuong pho bien
// cho 4 count moi wire.
//
// ⚠️ CHUA KIEM CHUNG: can_help.pdf goi 0x200E la "wire number" va don vi cua
// 0x6064 la "count", khong cho nao trong 37 trang noi he so giua hai cai.
// Sai he so nay lam odometry sai dung 4 lan. Do (2 phut): ke banh len, doc
// 0x6064:01, quay banh mot vong bang tay, doc lai, lay hieu -- roi dat vao
// `base.encoder_counts_per_rev` de khong con phai doan.
constexpr uint32_t kDefaultCountsPerRev = 4096 * 4;
template <typename T>
std::optional<T> SdoRead(lely::canopen::AsyncMaster& m, uint8_t node,
uint16_t idx, uint8_t sub) {
std::promise<std::optional<T>> prom;
auto fut = prom.get_future();
m.SubmitRead<T>(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<T>(v));
});
if (fut.wait_for(std::chrono::seconds(2)) != std::future_status::ready) {
return std::nullopt;
}
return fut.get();
}
class ZlacBase;
// Tin hieu "slave da boot xong", chia se giua bridge va driver.
struct BootGate {
std::mutex mu;
std::condition_variable cv;
bool booted = false;
};
class LelyBridge : public lely::canopen::BasicDriver {
class ZlacWrapper : public BaseInterface {
public:
LelyBridge(lely::canopen::AsyncMaster& m, uint8_t id, std::atomic<bool>* lost,
BootGate* gate)
: BasicDriver(m, id), lost_(lost), gate_(gate) {}
protected:
void OnBoot(lely::canopen::NmtState, char, const std::string&) noexcept override {
master.Command(lely::canopen::NmtCommand::START, id());
if (gate_) {
{
std::lock_guard<std::mutex> lk(gate_->mu);
gate_->booted = true;
}
gate_->cv.notify_all();
}
}
void OnHeartbeat(bool occurred) noexcept override {
if (lost_) lost_->store(occurred);
if (occurred) {
VSLAM_ERROR("base: mat heartbeat CANopen node " << static_cast<int>(id()));
}
}
private:
std::atomic<bool>* lost_ = nullptr;
BootGate* gate_ = nullptr;
};
class ZlacBase : public BaseInterface {
public:
ZlacBase(const BaseConfig& cfg, ClockPtr clock)
ZlacWrapper(const BaseConfig& cfg, ClockPtr clock)
: cfg_(cfg), clock_(std::move(clock)) {}
~ZlacBase() override { Close(); }
~ZlacWrapper() override { Close(); }
void SetEncoderCallback(EncoderCallback cb) override { cb_ = std::move(cb); }
StatusResponse Open() override {
if (impl_) {
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"base: da mo roi");
}
if (!clock_) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"base: thieu clock");
@@ -161,43 +76,60 @@ class ZlacBase : public BaseInterface {
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");
"base: thieu dcf_path. lely can file master.dcf sinh bang `dcfgen`.");
}
if (!(cfg_.wheel_radius > 0.0) || !(cfg_.wheel_separation > 0.0)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"base: wheel_radius / wheel_separation <= 0");
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"base: wheel_radius / wheel_separation <= 0");
}
try {
io_guard_ = std::make_unique<lely::io::IoGuard>();
ctx_ = std::make_unique<lely::io::Context>();
poll_ = std::make_unique<lely::io::Poll>(*ctx_);
loop_ = std::make_unique<lely::ev::Loop>(poll_->get_poll());
auto exec = loop_->get_executor();
timer_ = std::make_unique<lely::io::Timer>(*poll_, exec, CLOCK_MONOTONIC);
ctrl_ = std::make_unique<lely::io::CanController>(cfg_.can_channel.c_str());
chan_ = std::make_unique<lely::io::CanChannel>(*poll_, exec);
chan_->open(*ctrl_);
master_ = std::make_unique<lely::canopen::AsyncMaster>(
*timer_, *chan_, cfg_.dcf_path, "", 127);
bridge_ = std::make_unique<LelyBridge>(*master_, cfg_.can_node_id, &lost_,
&boot_);
master_->Reset();
lely_thread_ = std::thread([this] {
try { loop_->run(); } catch (...) {}
});
} catch (const std::exception& e) {
counts_per_rev_ = cfg_.encoder_counts_per_rev != 0
? cfg_.encoder_counts_per_rev
: kDefaultCountsPerRev;
if (cfg_.encoder_counts_per_rev == 0) {
VSLAM_WARN("base: encoder_counts_per_rev chua dat, dung mac dinh "
<< counts_per_rev_ << " (4096 wire x 4 cau phuong, CHUA kiem "
"chung). Sai he so nay lam odometry sai 4 lan -- do bang cach "
"quay banh mot vong roi so hieu 0x6064.");
}
// Hinh hoc lay tu BaseConfig, ma no da duoc sao tu robot.yaml luc nap
// config -- robot.yaml la nguon duy nhat cho hinh hoc.
zlac_ros::KinematicsConfig kc;
kc.wheel_diameter_m = cfg_.wheel_radius * 2.0;
kc.wheel_base_m = cfg_.wheel_separation;
kc.invert_left_wheel = false;
kc.invert_right_wheel = true; // mac dinh cua base_kit cho con robot nay
kin_ = std::make_unique<zlac_ros::DifferentialDriveKinematics>(kc);
impl_ = std::make_unique<zlac_ros::ZlacMotorDriver>(
cfg_.can_channel, cfg_.can_node_id, cfg_.dcf_path);
if (!impl_->initMaster()) {
impl_.reset();
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?");
"base: khong mo duoc CANopen master tren " + cfg_.can_channel +
".\n - `ip link show " + cfg_.can_channel + "` co UP khong?"
"\n - co tien trinh khac dang giu bus khong? "
"(systemctl status motor_control zlac_ros)"
"\n - dcf_path: " + cfg_.dcf_path);
}
if (!impl_->enableHardware()) {
impl_.reset();
return StatusResponse::Error(
StatusCode::kUnavailable,
"base: enableHardware() that bai -- khong vao duoc Profile Velocity "
"Mode.\n - can_node_id dang la " +
std::to_string(cfg_.can_node_id) +
", co dung khong?\n - driver motor da co dien chua?");
}
if (StatusResponse st = WaitForBoot(); !st.ok()) return st;
if (StatusResponse st = ProbeIdentity(); !st.ok()) return st;
if (StatusResponse st = EnableDs402(); !st.ok()) return st;
if (StatusResponse st = ResolveEncoderScale(); !st.ok()) return st;
VSLAM_INFO("base: ZLAC8015D tren " << cfg_.can_channel << " node "
<< static_cast<int>(cfg_.can_node_id) << ", banh r="
<< cfg_.wheel_radius << " m cach nhau " << cfg_.wheel_separation
<< " m, " << counts_per_rev_ << " count/vong");
running_ = true;
poll_thread_ = std::thread([this] { PollLoop(); });
@@ -207,50 +139,26 @@ class ZlacBase : public BaseInterface {
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<uint16_t>(*master_, cfg_.can_node_id, 0x6040, 0, 0x0006);
ready_ = false;
if (impl_) {
// disableHardware() tat power stage va gui NMT STOP. Goi TRUOC khi huy
// object: destructor cua no cung goi, nhung goi tuong minh o day thi
// thu tu tat chac chan, khong phu thuoc luc nao unique_ptr bi huy.
impl_->disableHardware();
impl_.reset();
}
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();
kin_.reset();
}
void SetVelocity(double linear, double angular) override {
// Kep o day la CHAN CUOI, doc lap voi lop safety va voi deadman teleop.
// Kep o day la CHAN CUOI, doc lap voi lop safety va deadman cua 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
double rpm_l = (v_l / cfg_.wheel_radius) * 60.0 / kTwoPi;
double rpm_r = (v_r / cfg_.wheel_radius) * 60.0 / kTwoPi;
// 0x60FF nhan -1000..1000 r/min (can_help.pdf Appendix A). Gioi han thuc
// te thap hon nhieu -- max_linear 0.35 m/s voi r=0.0865 chi ra ~39 RPM --
// nhung kep o day de mot config sai khong bao gio gui duoc gia tri ma
// driver se tu dien giai lai.
constexpr double kMaxRpm = 1000.0;
rpm_l = Clamp(rpm_l, kMaxRpm);
rpm_r = Clamp(rpm_r, kMaxRpm);
{
std::lock_guard<std::mutex> lk(cmd_mu_);
target_l_ = static_cast<int16_t>(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<int16_t>(std::lround(-rpm_r));
last_cmd_ = clock_->Now();
have_cmd_ = true;
}
std::lock_guard<std::mutex> lk(cmd_mu_);
cmd_linear_ = linear;
cmd_angular_ = angular;
last_cmd_ = clock_->Now();
have_cmd_ = true;
}
DriverStats Stats() const override {
@@ -264,270 +172,75 @@ class ZlacBase : public BaseInterface {
return (v > lim) ? lim : ((v < -lim) ? -lim : v);
}
// Cho slave BOOT XONG truoc khi gui SDO dau tien.
//
// ⚠️ Day la loi that, do duoc tren robot: ban dau Open() goi thang
// ProbeIdentity() ngay sau master_->Reset(). SDO dau tien di ra sau 116 ms
// va KHONG AI TRA LOI -- slave chua kip boot. Doc log thi trong y het
// "thiet bi khong ho tro object do", va da dan chan doan di sai huong hai
// lan.
//
// base_kit khong gap loi nay nhung cung khong xu ly no: no co mot ROS timer
// 500 ms goi lai enableHardware() cho toi khi duoc, nen boot xong luc nao
// thi tinh co vua dung luc do. Doi day dung tin hieu that -- callback
// OnBoot cua lely -- thay vi ngu mot khoang co dinh doan mo.
StatusResponse WaitForBoot() {
constexpr auto kTimeout = std::chrono::seconds(5);
std::unique_lock<std::mutex> lk(boot_.mu);
if (boot_.cv.wait_for(lk, kTimeout, [this] { return boot_.booted; })) {
return StatusResponse::Ok();
}
return StatusResponse::Error(
StatusCode::kTimeout,
"base: node " + std::to_string(cfg_.can_node_id) +
" khong boot trong 5 s (khong co callback OnBoot cua lely).\n"
" - master.dcf co khai bao dung node nay khong? lely chi boot "
"nhung slave co trong DCF.\n"
" - driver motor da co dien chua?\n"
" - `candump can0` co thay khung 0x70" +
std::to_string(cfg_.can_node_id) + " (heartbeat) khong?");
}
// Hoi 0x1018:01 (Vendor-ID) TRUOC moi thu khac.
//
// Object nay BAT BUOC voi moi thiet bi CANopen -- no nam trong Identity
// Object cua DS301, khong phai mo rong cua nha san xuat. Neu no khong tra
// loi thi van de la SDO/CAN, KHONG phai chuyen thiet bi thieu object nay no.
//
// Tach ra thanh mot buoc rieng vi bai hoc that: lan chay dau tren robot,
// 0x608F:1 khong tra loi va thong bao loi khi do noi "thiet bi khong tra loi
// 0x608F" -- doc len tuong nhu ZLAC khong ho tro object do. Nhung log cua
// lely cho thay 1018:01 CUNG abort, tuc SDO hong tu goc. Chan doan sai huong
// ton nhieu thoi gian hon la mot thong bao chung chung.
StatusResponse ProbeIdentity() {
// Thu NHIEU object, khong chi 0x1018.
//
// can_help.pdf Appendix A xac nhan 0x1018:01 CO ton tai (Vendor Id =
// 0x0100), nen lan hong tren robot khong phai vi thieu object ma vi hoi
// qua som -- WaitForBoot() o tren la cho sua that su.
//
// Van giu ca ba lan thu: chung re, va neu mot firmware ZLAC khac bo trong
// Identity Object thi 0x606C/0x6060 van cho di tiep. 0x606C la object
// base_kit doc thanh cong moi 20 ms nen no chac chan co.
if (SdoRead<uint32_t>(*master_, cfg_.can_node_id, 0x1018, 1)) {
return StatusResponse::Ok();
}
VSLAM_WARN("base: node " << static_cast<int>(cfg_.can_node_id)
<< " khong tra loi 0x1018:01 (Identity). Thu 0x606C...");
if (SdoRead<int32_t>(*master_, cfg_.can_node_id, 0x606C, 1)) {
VSLAM_WARN("base: 0x606C tra loi -- SDO thong, thiet bi chi thieu "
"Identity Object. Di tiep.");
return StatusResponse::Ok();
}
if (SdoRead<int8_t>(*master_, cfg_.can_node_id, 0x6060, 0)) {
VSLAM_WARN("base: 0x6060 tra loi -- SDO thong. Di tiep.");
return StatusResponse::Ok();
}
return StatusResponse::Error(
StatusCode::kUnavailable,
"base: node " + std::to_string(cfg_.can_node_id) +
" khong tra loi BAT KY object nao trong ba thu: 0x1018:01 "
"(Identity), 0x606C:1 (velocity actual), 0x6060:0 (mode). "
"base_kit doc duoc hai cai sau moi 20 ms tren cung con driver, "
"nen neu ca ba deu im thi van de o duong truyen chu khong o thiet "
"bi. Kiem theo thu tu:\n"
" 1. Co tien trinh khac dang giu bus khong? base_kit co "
"zlac_ros.service va motor_control.service -- hai CANopen master "
"tren cung mot bus cho ra dung trieu chung nay.\n"
" systemctl status zlac_ros motor_control\n"
" 2. Bitrate cua " + cfg_.can_channel + " co khop driver khong?\n"
" ip -details link show " + cfg_.can_channel + "\n"
" 3. can_node_id dang la " + std::to_string(cfg_.can_node_id) +
" -- co dung khong?\n"
" 4. Driver motor da co dien chua? (NMT len duoc operational "
"khong co nghia la slave dang song)");
}
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<int8_t>(*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<uint32_t>(*master_, cfg_.can_node_id, 0x6083, 1, acc);
SdoWrite<uint32_t>(*master_, cfg_.can_node_id, 0x6083, 2, acc);
SdoWrite<uint32_t>(*master_, cfg_.can_node_id, 0x6084, 1, acc);
SdoWrite<uint32_t>(*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<uint16_t>(*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) {
// ⚠️ KHONG phai 0x608F. Object do la chuan DS402 (Position encoder
// resolution) nhung ZLAC8015D KHONG co no -- Appendix A cua
// can_help.pdf liet ke day du dai CiA402 va no dung o 6087h roi nhay
// thang toi 60FFh. Doc 0x608F se abort mai mai.
//
// So vong day cua encoder nam trong vung Factory Custom: 0x200E:01
// (trai) / :02 (phai), "Encoder wire number setting", 0-4096, mac dinh
// 1024.
const auto lines =
SdoRead<uint16_t>(*master_, cfg_.can_node_id, 0x200E, 1);
if (!lines || *lines == 0) {
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
"base: khong doc duoc 0x200E:01 (Encoder wire number) va "
"encoder_counts_per_rev trong config dang la 0. Mac dinh cua "
"ZLAC8015D la 1024 -- dat tuong minh roi chay lai.");
}
// ⚠️ GIA DINH CHUA KIEM CHUNG: counts = lines x 4 (giai ma cau phuong).
//
// Tai lieu goi 0x200E la "wire number" (so vong day) va goi don vi cua
// 0x6064 la "count". Hai ten khac nhau, va khong cho nao trong 37 trang
// noi he so giua chung. Suy doan x4 la quy uoc pho bien nhat, nhung no
// VAN LA SUY DOAN.
//
// Sai he so nay lam odometry sai dung 4 lan -- de thay, nhung van nen
// do cho chac. Cach do (2 phut):
// 1. Ke banh len khoi san
// 2. Doc 0x6064:01, quay banh dung MOT vong bang tay, doc lai
// 3. Hieu so chinh la counts/vong that
// 4. Dat vao sensors.yaml: base.encoder_counts_per_rev
counts_per_rev_ = static_cast<uint32_t>(*lines) * 4u;
VSLAM_WARN("base: 0x200E:01 = " << *lines << " wire, SUY RA "
<< counts_per_rev_ << " counts/vong (gia dinh x4 cau phuong, "
"CHUA kiem chung). Sai he so nay lam odometry sai 4 lan -- do "
"bang cach quay banh mot vong roi so hieu 0x6064, va dat vao "
"base.encoder_counts_per_rev.");
}
// 0x6064 la tru cot cua ca thiet ke nay, va can_help.pdf Appendix A xac
// nhan no CO:
// 6064h :01 Position_actual_value (left) I32 RO "unit: count"
// :02 Position_actual_value (right) I32 RO
// Van kiem luc Open(): neu vi ly do gi no khong tra loi thi phai biet
// NGAY, chu khong phai sau nua gio thay robot dung yen o goc 0.
const auto l = SdoRead<int32_t>(*master_, cfg_.can_node_id, 0x6064, 1);
const auto r = SdoRead<int32_t>(*master_, cfg_.can_node_id, 0x6064, 2);
if (!l || !r) {
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
"base: ZLAC8015D khong tra loi 0x6064 (Position Actual Value), du "
"can_help.pdf Appendix A liet ke no la I32 RO. Neu 0x606C doc duoc "
"ma 0x6064 thi khong, kiem lai firmware driver motor.");
}
origin_l_ = *l;
origin_r_ = *r;
VSLAM_INFO("base: CANopen " << cfg_.can_channel << " node "
<< static_cast<int>(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<double>(period));
std::this_thread::sleep_for(std::chrono::duration<double>(period));
}
// Ra khoi vong thi dung xe, du vi ly do gi.
if (impl_) impl_->setTargetRPM(0, 0);
}
void PushVelocity() {
int16_t l = 0, r = 0;
double v = 0.0, w = 0.0;
{
std::lock_guard<std::mutex> 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_;
v = cmd_linear_;
w = cmd_angular_;
} else if (have_cmd_) {
VSLAM_WARN_THROTTLE(2.0, "base: khong co cmd trong " << age
<< " s -- dung motor");
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<uint16_t>(l) & 0xFFFFu) |
(static_cast<uint32_t>(static_cast<uint16_t>(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;
if (!impl_) return;
const zlac_ros::WheelSpeedRPM rpm = kin_->computeInverseKinematics(v, w);
impl_->setTargetRPM(rpm.left, rpm.right);
}
void ReadEncoders() {
if (!master_) return;
const auto l = SdoRead<int32_t>(*master_, cfg_.can_node_id, 0x6064, 1);
const auto r = SdoRead<int32_t>(*master_, cfg_.can_node_id, 0x6064, 2);
if (!impl_) return;
int32_t l = 0, r = 0;
EncoderReading out;
out.stamp = clock_->Now();
if (!l || !r) {
if (!impl_->getPositionCounts(l, r)) {
out.stamp = clock_->Now();
out.valid = false;
{
std::lock_guard<std::mutex> lk(stats_mu_);
++stats_.errors;
stats_.connected = false;
stats_.last_error = "khong doc duoc 0x6064";
stats_.last_error = "chua co vi tri tu 0x6064";
}
if (cb_) cb_(out);
return;
}
out.stamp = clock_->Now();
if (!have_origin_) {
// Tru moc dau tien de pose bat dau tu 0 thay vi tu mot so tuy y con lai
// tu lan chay truoc.
origin_l_ = l;
origin_r_ = r;
have_origin_ = true;
}
// 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<double>(counts_per_rev_);
out.left_rad = static_cast<double>(*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<double>(*r - origin_r_) * scale;
out.left_rad = static_cast<double>(l - origin_l_) * scale;
// Banh phai lap doi chieu -- cung quy uoc voi KinematicsConfig o tren.
// Thieu phep doi dau nay thi robot di thang ma odometry bao dang quay.
out.right_rad = -static_cast<double>(r - origin_r_) * scale;
out.valid = true;
{
std::lock_guard<std::mutex> lk(stats_mu_);
++stats_.frames;
stats_.connected = !lost_.load();
stats_.connected = !impl_->hasConnectionLost();
if (!last_enc_.isZero()) {
const double dt = (out.stamp - last_enc_).toSec();
if (dt > 0.0) stats_.hz = 1.0 / dt;
@@ -542,30 +255,19 @@ class ZlacBase : public BaseInterface {
ClockPtr clock_;
EncoderCallback cb_;
std::unique_ptr<lely::io::IoGuard> io_guard_;
std::unique_ptr<lely::io::Context> ctx_;
std::unique_ptr<lely::io::Poll> poll_;
std::unique_ptr<lely::ev::Loop> loop_;
std::unique_ptr<lely::io::Timer> timer_;
std::unique_ptr<lely::io::CanController> ctrl_;
std::unique_ptr<lely::io::CanChannel> chan_;
std::unique_ptr<lely::canopen::AsyncMaster> master_;
std::unique_ptr<LelyBridge> bridge_;
std::thread lely_thread_;
std::unique_ptr<zlac_ros::ZlacMotorDriver> impl_;
std::unique_ptr<zlac_ros::DifferentialDriveKinematics> kin_;
BootGate boot_;
std::atomic<bool> running_{false};
std::atomic<bool> lost_{false};
bool ready_ = false;
std::thread poll_thread_;
uint32_t counts_per_rev_ = 0;
int32_t origin_l_ = 0, origin_r_ = 0;
bool have_origin_ = false;
UnixTime last_enc_;
std::mutex cmd_mu_;
int16_t target_l_ = 0, target_r_ = 0;
int16_t sent_l_ = 0, sent_r_ = 0;
mutable std::mutex cmd_mu_;
double cmd_linear_ = 0.0, cmd_angular_ = 0.0;
UnixTime last_cmd_;
bool have_cmd_ = false;
@@ -577,7 +279,7 @@ class ZlacBase : public BaseInterface {
std::unique_ptr<BaseInterface> CreateDiffDriveBase(const BaseConfig& cfg,
ClockPtr clock) {
return std::make_unique<ZlacBase>(cfg, std::move(clock));
return std::make_unique<ZlacWrapper>(cfg, std::move(clock));
}
} // namespace vslam

View File

@@ -0,0 +1,53 @@
# Nguon goc cua code trong thu muc nay
Day la code NHUNG (vendored), khong phai code cua du an nay. No duoc chep tu
`base_kit` -- workspace ROS 2 dang chay that tren robot -- va la ban driver
CHUAN cho phan cung nay.
| Thu muc o day | Chep tu |
|---|---|
| `lakibeam_sdk/` | `base_kit/src/lidar/thirdparty/lakibeam_sdk/` |
| `lidar_core/` | `base_kit/src/lidar/lidar_core/` |
| `zlac/` | `base_kit/src/Zlac_ros/` (chi 2 cap file, xem duoi) |
## Vi sao nhung chu khong tro duong dan ngoai
`base_kit` khong nam trong repo nay. Neu build tro ra ngoai thi `git clone`
khong build duoc, va moi may phai co `base_kit` dung cho. Nhung vao day ton
128 KB va doi lai repo tu chua du.
Doi lai: khi `base_kit` sua thi phai dong bo TAY. Xem muc "Sua doi" ben duoi
truoc khi chep de -- co mot cho da bi sua.
## Cai gi KHONG duoc chep
* `LakiBeamHTTP.*` va `rapidjson/` -- SDK chia hai duong, HTTP chi dung de
cau hinh thiet bi qua web. `LakiBeamUDP.cpp` khong include no, nen bo duoc
ca rapidjson (vai tram KB header).
* `Zlac_ros/src/zlac_ros_node.cpp`, `xloc_udp_bridge.*` -- deu la ROS node.
Du an nay khong co ROS.
* `imu_uart/` -- chi co dung mot file va no LA mot ROS node, khong co lop
standalone nao de dung lai. Phan parse (`Acc`/`Gyro`/`Angle`, deg/s ->
rad/s) da duoc viet lai trong `src/mcu_bridge.cc`.
## Sua doi so voi ban goc
⚠️ `zlac/` KHONG con nguyen ban. Da them:
* `ZlacMotorDriver::getPositionCounts()` -- doc `0x6064` (Position actual
value), cung cach telemetryLoop dang cache van toc.
Ban goc chi co `getActualRPM()`, tuc chi co VAN TOC. `EncoderReading` cua du
an nay can GOC QUAY TICH LUY: tich phan van toc thi lo mot mau telemetry la
mat vinh vien mot doan quang duong va khong co cach nao phat hien -- xem
`mcu_protocol.h`. `0x6064` la bo dem tuyet doi trong chinh driver motor nen
lo mau khong mat gi.
`can_help.pdf` Appendix A xac nhan object nay co that:
```
6064h :01 Position_actual_value (left) I32 RO "unit: count"
:02 Position_actual_value (right) I32 RO
```
Moi cho sua deu duoc danh dau bang `// [vslam]` trong nguon, de lan dong bo
sau con tim lai duoc.

View File

@@ -0,0 +1,518 @@
#include "LakiBeamUDP.h"
LakiBeamUDP::LakiBeamUDP(string local_ip, string local_port, string laser_ip, string laser_port)
{
this->local_ip = local_ip;
this->local_port = local_port;
this->laser_ip = laser_ip;
this->laser_port = laser_port;
dbmain = 0;
dbmain_used = 0;
urpmain = 0;
urpmain_used = 0;
char *temp = reinterpret_cast<char *>(udprepack);
memset(temp, 0, CONFIG_MAX_REPACK * sizeof(repark_t));
local_ep = new udp_endpoint_t(address_t::from_string("0.0.0.0"), atoi(local_port.c_str()));
laser_ep = new udp_endpoint_t(address_t::from_string(laser_ip), atoi(laser_port.c_str()));
socket = new udp_socket_t(io_servicess);
socket->open(local_ep->protocol());
socket->set_option(boost::asio::ip::udp::socket::reuse_address(true));
socket->bind(*local_ep);
socket->async_receive_from(boost::asio::buffer(buffff, CONFIG_FRAME), *laser_ep, boost::bind(&LakiBeamUDP::on_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
udprepack_thd.reset(new boost::thread(boost::bind(&LakiBeamUDP::udprepack_thread, this)));
receive_thd.reset(new boost::thread(boost::bind(&LakiBeamUDP::receive_thread, this)));
}
void LakiBeamUDP::receive_thread()
{
while (1)
{
try {
io_servicess.run();
boost::this_thread::interruption_point();
}
catch (boost::system::error_code& err)
{
break;
}
}
}
LakiBeamUDP::~LakiBeamUDP()
{
io_servicess.stop();
receive_thd->interrupt();
receive_thd->join();
delete socket;
delete local_ep;
delete laser_ep;
udprepack_thd->interrupt();
udprepack_thd->join();
}
void LakiBeamUDP::sync_get_repackedpack(repark_t &pack)
{
while (urpmain < 2)
{
}
while (urpmain <= (urpmain_used + 1))
{
}
urpmain_used = urpmain - 1;
pack = udprepack[(urpmain_used) % CONFIG_MAX_REPACK];
}
bool LakiBeamUDP::get_repackedpack(repark_t &pack)
{
bool result = true;
if ((urpmain < 2)||(urpmain <= (urpmain_used + 1)))
{
result = false;
}
else
{
urpmain_used = urpmain - 1;
}
if (result == true)
{
pack = udprepack[(urpmain_used) % CONFIG_MAX_REPACK];
}
return result;
}
void LakiBeamUDP::on_read(const boost::system::error_code& err, std::size_t read_bytes)
{
if (!err)
{
char* temp;
if (read_bytes == CONFIG_FRAME)
{
temp = reinterpret_cast<char*>(&(doublebuffer[dbmain % CONFIG_FRAME_MAX]));
memcpy(temp, buffff, CONFIG_FRAME);
dbmain++;
}
}
socket->async_receive_from(boost::asio::buffer(buffff, CONFIG_FRAME), *laser_ep, boost::bind(&LakiBeamUDP::on_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void LakiBeamUDP::udprepack_thread()
{
while (1)
{
try
{
bool goon = true;
udp_pack_t doublebuffertemp[2];
{
if ((dbmain - dbmain_used) >= 2)
{
char *source1 = reinterpret_cast<char *>(&doublebuffertemp[0]);
char *source2 = reinterpret_cast<char *>(&doublebuffertemp[1]);
char *from1 = reinterpret_cast<char *>(&(doublebuffer[dbmain_used % CONFIG_FRAME_MAX]));
char *from2 = reinterpret_cast<char *>(&(doublebuffer[(dbmain_used + 1) % CONFIG_FRAME_MAX]));
u32_t realindex = dbmain_used % CONFIG_FRAME_MAX;
if (realindex == CONFIG_FRAME_INDEX_MAX)
{
memcpy(source1, from1, CONFIG_FRAME);
memcpy(source2, from2, CONFIG_FRAME);
}
else
{
memcpy(source1, from1, CONFIG_FRAME * 2);
}
dbmain_used++;
}
else
{
goon = false;
}
}
if (goon == true)
{
if ((doublebuffertemp[0].factory == 0x4037) && (doublebuffertemp[1].factory == 0x4037))
{
// 寻找0位包裹
u32_t start_index = 0xFFFFFFFF;
for (int i = 0; i < CONFIG_UDP_BLOCKS; i++)
{
if (doublebuffertemp[0].depths[i].azimuth == 0)
{
start_index = i;
}
}
// 0位数据包
if (start_index != 0xFFFFFFFF)
{
fill_havestart(doublebuffertemp, start_index);
}
// 非0位数据包
else
{
fill_nostart(doublebuffertemp);
}
}
else
{
// DEBUG(doublebuffertemp[1].factory);
// DEBUG(doublebuffertemp[0].factory);
}
}
boost::this_thread::interruption_point();
if ((dbmain - dbmain_used) < 2)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(2));
}
}
catch (...)
{
break;
}
}
}
void LakiBeamUDP::fill_nostart(udp_pack_t pack[2])
{
(void)pack;
u32_t start_time = pack[0].timestamp;
u32_t end_time = pack[1].timestamp;
u16_t tempdots = udprepack[urpmain % CONFIG_MAX_REPACK].maxdots;
u32_t div_time = (end_time - start_time) / CONFIG_BLOCK_DEPTHS / CONFIG_UDP_BLOCKS;
for (int i = 0; i < CONFIG_UDP_BLOCKS; i++)
{
if (pack[0].depths[i].head == 0xEEFF)
{
if (i < (CONFIG_UDP_BLOCKS - 1))
{
u16_t start_angle = pack[0].depths[i].azimuth;
u16_t end_angle = pack[0].depths[i + 1].azimuth;
u16_t div_angle;
if (end_angle >= start_angle)
{
div_angle = (end_angle - start_angle) / CONFIG_BLOCK_DEPTHS;
}
else
{
div_angle = (CONFIG_DEGREE_MAX - start_angle + end_angle) / CONFIG_BLOCK_DEPTHS;
}
for (int j = 0; j < CONFIG_BLOCK_DEPTHS; j++)
{
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].timestamp = start_time;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].angle = start_angle;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].distance = pack->depths[i].depth[j].distance0;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].rssi = pack->depths[i].depth[j].rssi0;
udprepack[urpmain % CONFIG_MAX_REPACK].interval += div_time;
tempdots++;
if ((start_angle + div_angle) >= CONFIG_DEGREE_MAX)
{
start_angle = start_angle + div_angle - CONFIG_DEGREE_MAX;
}
else
{
start_angle += div_angle;
}
start_time += div_time;
}
}
else
{
u16_t start_angle = pack[0].depths[i].azimuth;
u16_t end_angle = pack[1].depths[0].azimuth;
u16_t div_angle;
if (end_angle >= start_angle)
{
div_angle = (end_angle - start_angle) / CONFIG_BLOCK_DEPTHS;
}
else
{
div_angle = (CONFIG_DEGREE_MAX - start_angle + end_angle) / CONFIG_BLOCK_DEPTHS;
}
for (int j = 0; j < CONFIG_BLOCK_DEPTHS; j++)
{
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].timestamp = start_time;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].angle = start_angle;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].distance = pack->depths[i].depth[j].distance0;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].rssi = pack->depths[i].depth[j].rssi0;
udprepack[urpmain % CONFIG_MAX_REPACK].interval += div_time;
tempdots++;
if ((start_angle + div_angle) >= CONFIG_DEGREE_MAX)
{
start_angle = start_angle + div_angle - CONFIG_DEGREE_MAX;
}
else
{
start_angle += div_angle;
}
start_time += div_time;
}
}
}
}
udprepack[urpmain % CONFIG_MAX_REPACK].maxdots = tempdots;
}
void LakiBeamUDP::fill_havestart(udp_pack_t pack[], u32_t start)
{
// 第一包
if (urpmain == 0)
{
urpmain++;
urpmain_used++;
udprepack[urpmain % CONFIG_MAX_REPACK].maxdots = 0;
udprepack[urpmain % CONFIG_MAX_REPACK].interval = 0;
(void)pack;
u32_t start_time = pack[0].timestamp;
u32_t end_time = pack[1].timestamp;
u16_t tempdots = udprepack[urpmain % CONFIG_MAX_REPACK].maxdots;
u32_t div_time = (end_time - start_time) / CONFIG_BLOCK_DEPTHS / CONFIG_UDP_BLOCKS;
for (int i = start; i < CONFIG_UDP_BLOCKS; i++)
{
if (i < (CONFIG_UDP_BLOCKS - 1))
{
u16_t start_angle = pack[0].depths[i].azimuth;
u16_t end_angle = pack[0].depths[i + 1].azimuth;
u16_t div_angle;
if (end_angle >= start_angle)
{
div_angle = (end_angle - start_angle) / CONFIG_BLOCK_DEPTHS;
}
else
{
div_angle = (CONFIG_DEGREE_MAX - start_angle + end_angle) / CONFIG_BLOCK_DEPTHS;
}
for (int j = 0; j < CONFIG_BLOCK_DEPTHS; j++)
{
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].timestamp = start_time;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].angle = start_angle;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].distance = pack->depths[i].depth[j].distance0;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].rssi = pack->depths[i].depth[j].rssi0;
udprepack[urpmain % CONFIG_MAX_REPACK].interval += div_time;
tempdots++;
if ((start_angle + div_angle) >= CONFIG_DEGREE_MAX)
{
start_angle = start_angle + div_angle - CONFIG_DEGREE_MAX;
}
else
{
start_angle += div_angle;
}
start_time += div_time;
}
}
else
{
u16_t start_angle = pack[0].depths[i].azimuth;
u16_t end_angle = pack[1].depths[0].azimuth;
u16_t div_angle;
if (end_angle >= start_angle)
{
div_angle = (end_angle - start_angle) / CONFIG_BLOCK_DEPTHS;
}
else
{
div_angle = (CONFIG_DEGREE_MAX - start_angle + end_angle) / CONFIG_BLOCK_DEPTHS;
}
start_angle = start_angle + div_angle * (start + 1) * CONFIG_BLOCK_DEPTHS;
for (int j = 0; j < CONFIG_BLOCK_DEPTHS; j++)
{
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].timestamp = start_time;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].angle = start_angle;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].distance = pack->depths[i].depth[j].distance0;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].rssi = pack->depths[i].depth[j].rssi0;
udprepack[urpmain % CONFIG_MAX_REPACK].interval += div_time;
tempdots++;
if ((start_angle + div_angle) >= CONFIG_DEGREE_MAX)
{
start_angle = start_angle + div_angle - CONFIG_DEGREE_MAX;
}
else
{
start_angle += div_angle;
}
start_time += div_time;
}
}
}
udprepack[urpmain % CONFIG_MAX_REPACK].maxdots = tempdots;
}
// 其它0包
else
{
{
(void)pack;
u32_t start_time = pack[0].timestamp;
u32_t end_time = pack[1].timestamp;
u16_t tempdots = udprepack[urpmain % CONFIG_MAX_REPACK].maxdots;
u32_t div_time = (end_time - start_time) / CONFIG_BLOCK_DEPTHS / CONFIG_UDP_BLOCKS;
udprepack[urpmain % CONFIG_MAX_REPACK].interval += div_time;
for (u32_t i = 0; i < start; i++)
{
u16_t start_angle = pack[0].depths[i].azimuth;
u16_t end_angle = pack[0].depths[i + 1].azimuth;
u16_t div_angle;
if (end_angle >= start_angle)
{
div_angle = (end_angle - start_angle) / CONFIG_BLOCK_DEPTHS;
}
else
{
div_angle = (CONFIG_DEGREE_MAX - start_angle + end_angle) / CONFIG_BLOCK_DEPTHS;
}
for (int j = 0; j < CONFIG_BLOCK_DEPTHS; j++)
{
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].timestamp = start_time;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].angle = start_angle;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].distance = pack->depths[i].depth[j].distance0;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].rssi = pack->depths[i].depth[j].rssi0;
udprepack[urpmain % CONFIG_MAX_REPACK].interval += div_time;
tempdots++;
if ((start_angle + div_angle) >= CONFIG_DEGREE_MAX)
{
start_angle = start_angle + div_angle - CONFIG_DEGREE_MAX;
}
else
{
start_angle += div_angle;
}
start_time += div_time;
}
}
if((tempdots==1440)||(tempdots==3600))
{
bool lost = false;
if (tempdots == 1440)
{
for (int i = 180; i < (1440 - 17); i++)
{
if (udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[i+1].angle < udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[i].angle)
{
lost = true;
}
}
}
else
{
for (int i = 450; i < (3600 - 17); i++)
{
if (udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[i + 1].angle < udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[i].angle)
{
lost = true;
}
}
}
if (lost == false)
{
udprepack[urpmain % CONFIG_MAX_REPACK].interval /= tempdots;
udprepack[urpmain % CONFIG_MAX_REPACK].maxdots = tempdots;
urpmain++;
}
}
}
{
udprepack[urpmain % CONFIG_MAX_REPACK].maxdots = 0;
(void)pack;
u32_t start_time = pack[0].timestamp;
u32_t end_time = pack[1].timestamp;
u16_t tempdots = udprepack[urpmain % CONFIG_MAX_REPACK].maxdots;
u32_t div_time = (end_time - start_time) / CONFIG_BLOCK_DEPTHS / CONFIG_UDP_BLOCKS;
for (u32_t i = start; i < CONFIG_UDP_BLOCKS; i++)
{
if (i < (CONFIG_UDP_BLOCKS - 1))
{
u16_t start_angle = pack[0].depths[i].azimuth;
u16_t end_angle = pack[0].depths[i + 1].azimuth;
u16_t div_angle;
if (end_angle >= start_angle)
{
div_angle = (end_angle - start_angle) / CONFIG_BLOCK_DEPTHS;
}
else
{
div_angle = (CONFIG_DEGREE_MAX - start_angle + end_angle) / CONFIG_BLOCK_DEPTHS;
}
for (int j = 0; j < CONFIG_BLOCK_DEPTHS; j++)
{
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].timestamp = start_time;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].angle = start_angle;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].distance = pack->depths[i].depth[j].distance0;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].rssi = pack->depths[i].depth[j].rssi0;
udprepack[urpmain % CONFIG_MAX_REPACK].interval += div_time;
tempdots++;
if ((start_angle + div_angle) >= CONFIG_DEGREE_MAX)
{
start_angle = start_angle + div_angle - CONFIG_DEGREE_MAX;
}
else
{
start_angle += div_angle;
}
start_time += div_time;
}
}
else
{
u16_t start_angle = pack[0].depths[i].azimuth;
u16_t end_angle = pack[1].depths[0].azimuth;
u16_t div_angle;
if (end_angle >= start_angle)
{
div_angle = (end_angle - start_angle) / CONFIG_BLOCK_DEPTHS;
}
else
{
div_angle = (CONFIG_DEGREE_MAX - start_angle + end_angle) / CONFIG_BLOCK_DEPTHS;
}
for (u32_t j = 0; j < CONFIG_BLOCK_DEPTHS; j++)
{
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].timestamp = start_time;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].angle = start_angle;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].distance = pack->depths[i].depth[j].distance0;
udprepack[urpmain % CONFIG_MAX_REPACK].dotcloud[tempdots % CONFIG_CIRCLE_DOTS].rssi = pack->depths[i].depth[j].rssi0;
udprepack[urpmain % CONFIG_MAX_REPACK].interval += div_time;
tempdots++;
if ((start_angle + div_angle) >= CONFIG_DEGREE_MAX)
{
start_angle = start_angle + div_angle - CONFIG_DEGREE_MAX;
}
else
{
start_angle += div_angle;
}
start_time += div_time;
}
}
}
udprepack[urpmain % CONFIG_MAX_REPACK].maxdots = tempdots;
}
}
}

View File

@@ -0,0 +1,239 @@
#ifndef LAKIBEAMUDP_H
#define LAKIBEAMUDP_H
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bimap.hpp>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <limits>
using namespace std;
/// 已使用声明:用来消除未使用变量报警,没有功能上面的意义
#ifndef USED
#define USED(x) ((void)x)
#endif
/// 调试接口:快速打印调试信息
#ifndef DEBUG
#define DEBUG(x) (cout << x << endl)
#endif
/// 取消字节对齐:下面定义的数据结构体与雷达的协议结构相互映射,不可以进行自动对齐字节
#define __autoalign__ __attribute__((packed))
/**
* 为了统一代码风格,对部分数据类型进行了重新定义
*/
#ifndef i32_t
typedef signed int i32_t;
#endif
#ifndef u32_t
typedef unsigned int u32_t;
#endif
#ifndef u16_t
typedef unsigned short u16_t;
#endif
#ifndef u16_t
typedef unsigned short i16_t;
#endif
#ifndef u8_t
typedef unsigned char u8_t;
#endif
#ifndef c8_t
typedef char i8_t;
#endif
#ifndef udp_socket_t
typedef boost::asio::ip::udp::socket udp_socket_t;
#endif
#ifndef address_t
typedef boost::asio::ip::address address_t;
#endif
#ifndef service_t
typedef boost::asio::io_service service_t;
#endif
typedef boost::scoped_ptr<boost::thread> thread_t;
#ifndef service_work_t
typedef boost::scoped_ptr<service_t::work> service_work_t;
#endif
#ifndef endpoint_t
typedef boost::asio::ip::udp::endpoint udp_endpoint_t;
#endif
#ifndef mutex_t
typedef boost::mutex mutex_t;
#endif
/// UDP数据报的数据帧大小——42字节UDP数据头不用于数据解码 1206 = 1248-42
#define CONFIG_FRAME (1206)
/// UDP数据包数据帧深度——必须为2的倍数
#define CONFIG_FRAME_MAX (256)
/// UDP数据缓存二位数组的第1个索引下标最大值
#define CONFIG_FRAME_INDEX_MAX (CONFIG_FRAME_MAX - 1)
/// 最大角度值
#define CONFIG_DEGREE_MAX (36000)
/// UDP数据报一帧数据中数据块个数
#define CONFIG_UDP_BLOCKS (12)
/// 数据块中数据池的深度
#define CONFIG_BLOCK_DEPTHS (16)
/// 转换缓存数据块深度
#define CONFIG_CIRCLE_DOTS (3600)
/// 雷达超时时间设置——2s
#define CONFIG_LASER_DISCONNECT (5)
#define CONFIG_LASER_TIMER_HEART (100)
/// 重组数据包大小
#define CONFIG_MAX_REPACK (32)
/// 16位数据大小端转换
#define T16_H8(x) ((u16_t)((((u16_t)x) & ((u16_t)(0xFF00))) >> 8))
#define T16_L8(x) ((u16_t)((((u16_t)x) & ((u16_t)(0x00FF))) << 8))
#define BIG_TO_LITTLE_16(x) ((u16_t)(T16_H8(x) | T16_L8(x)))
/// 32位数据大小端转换
#define T32_HH8(x) ((u32_t)((((u32_t)x) & ((u32_t)(0xFF000000))) >> 24))
#define T32_HL8(x) ((u32_t)((((u32_t)x) & ((u32_t)(0x00FF0000))) >> 8))
#define T32_LH8(x) ((u32_t)((((u32_t)x) & ((u32_t)(0x0000FF00))) << 8))
#define T32_LL8(x) ((u32_t)((((u32_t)x) & ((u32_t)(0x000000FF))) << 24))
#define BIG_TO_LITTLE_32(x) ((u32_t)(T32_HH8(x) | T32_HL8(x) | T32_LH8(x) | T32_LL8(x)))
/** @struct depth_t 雷达元数据包——最小数据包单元
* @brief 雷达深度数据的最小包裹
*/
#pragma pack(push)
#pragma pack(1)
struct depth_t
{
u16_t distance0; ///< 深度数据
u8_t rssi0; ///< 回波强度
u16_t distance1;
u8_t rssi1;
};
/** @struct little_pack_t UDP数据包封装最小结构单元
* @brief 一帧雷达深度数据的数据结构的最小单元
*/
struct little_pack_t
{
u16_t head; ///< 数据头
u16_t azimuth; ///< 测距数据的角度值
depth_t depth[CONFIG_BLOCK_DEPTHS]; ///< 深度数据点位包
};
/** @struct udp_pack_t UDP数据报一帧数据结构
* @brief 一帧UDP数据包的数据结构
*/
struct udp_pack_t
{
little_pack_t depths[CONFIG_UDP_BLOCKS]; ///< 深度数据单元
u32_t timestamp; ///< 时间戳
u16_t factory; ///< 工厂信息
};
/** @struct cicle_pack_t UDP成品数据结构
* @brief 重新封装的深度数据包最小单元
*/
struct cicle_pack_t
{
u32_t timestamp; ///< 时间戳
u16_t angle; ///< 角度值
u16_t distance; ///< 深度数据
u8_t rssi; ///< 回波强度
};
/** @struct repark_t 深度数据块,一块包含雷达一周的深度数据
* @brief 一帧代表一块深度数据
*/
struct repark_t
{
u32_t interval; ///< 间隔时间
u16_t maxdots; ///< 点位个数
cicle_pack_t dotcloud[CONFIG_CIRCLE_DOTS]; ///< 深度数据点云
};
#pragma pack(pop)
class LakiBeamUDP
{
public:
/*!
构造函数
\param local_ip 本地ip
\param local_port 本地端口号
\param laser_ip 雷达ip
\param laser_port 雷达端口号
*/
LakiBeamUDP(string local_ip, string local_port, string laser_ip, string laser_port);
/*!
析构函数
*/
~LakiBeamUDP();
/*!
同步重新组包功能
\param pack 用户包裹出口
*/
void sync_get_repackedpack(repark_t &pack);
/*!
取出数据包裹 返回true那么立即返回数据
\param pack 用户包裹出口
*/
bool get_repackedpack(repark_t &pack);
private:
string local_ip;
string local_port;
string laser_ip;
string laser_port;
thread_t receive_thd;
thread_t udprepack_thd;
mutex_t thd_mutex;
bool everyThingOK;
volatile u32_t dbmain;
volatile u32_t dbmain_used;
udp_pack_t doublebuffer[CONFIG_FRAME_MAX];
volatile u32_t urpmain;
volatile u32_t urpmain_used;
repark_t udprepack[CONFIG_MAX_REPACK];
char buffff[CONFIG_FRAME];
udp_socket_t* socket;
boost::asio::io_service io_servicess;
udp_endpoint_t *local_ep;
udp_endpoint_t *laser_ep;
private:
/*!
接受UDP数据包线程
*/
void receive_thread(void);
/*!
UDP拆包组包线程
*/
void udprepack_thread(void);
/*!
填充没有起始包的包裹(一次需要2包)
\param pack 包裹入口数组
*/
void fill_nostart(udp_pack_t pack[2]);
/*!
填充有起始包的包裹(一次需要2包)
\param pack 包裹入口数组
*/
void fill_havestart(udp_pack_t pack[2], u32_t start);
void on_read(const boost::system::error_code& err, std::size_t read_bytes);
};
#endif // LAKIBEAMUDP_H

View File

@@ -0,0 +1,97 @@
#ifndef LIDAR_CORE__LAKIBEAM_DRIVER_HPP_
#define LIDAR_CORE__LAKIBEAM_DRIVER_HPP_
#include <atomic>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include "lidar_core/laser_scan.hpp"
#include "lidar_core/lidar_source.hpp"
namespace lidar_core
{
/// @brief Cấu hình driver LakiBeam (giá trị mặc định theo User Manual RBDOC-UM-1001)
struct LakibeamConfig
{
// ---- Kết nối UDP (MSOP, mặc định port 2368) ----
std::string lidar_ip = "192.168.198.2"; ///< IP của radar
std::string lidar_port = "2368"; ///< port gửi dữ liệu của radar
std::string host_ip = "0.0.0.0"; ///< IP local (lưu ý: SDK luôn bind 0.0.0.0)
std::string host_port = "2368"; ///< port local để nhận dữ liệu
// ---- Khung LaserScan ----
std::string frame_id = "laser"; ///< frame tọa độ
float range_min = 0.05f; ///< khoảng cách tối thiểu [m]
float range_max = 30.0f; ///< khoảng cách tối đa [m] (LakiBeam1: 25m, 1L: 40m)
// ---- Quy ước góc ----
/// LakiBeam: X = R·sin(α), Y = R·cos(α) (manual §8.1).
/// ROS REP-103: x = R·cos(θ), y = R·sin(θ) → θ = 90° − α
/// ⇒ mặc định: angle_offset_deg = 90.0, angle_flip = true
double angle_offset_deg = 90.0; ///< offset cộng vào góc [deg]
bool angle_flip = false; ///< true → θ = offset − α (đảo chiều quay)
// ---- FOV ----
bool crop_fov = false; ///< false: publish full 360°; true: crop [fov_min, fov_max]
double fov_min_deg = 45.0; ///< góc bắt đầu FOV khi crop [deg] (LakiBeam: 45°)
double fov_max_deg = 315.0; ///< góc kết thúc FOV khi crop [deg] (LakiBeam: 315°)
// ---- Hàng đợi ----
size_t queue_size = 4; ///< số scan tối đa giữ trong hàng đợi (drop-oldest)
};
/// @brief Driver cho LakiBeam1/1L — triển khai ILidarSource.
///
/// Bọc LakiBeamUDP SDK (thirdparty/lakibeam_sdk): nhận gói MSOP qua UDP,
/// repack từng vòng quét (1440 điểm @0.25° hoặc 3600 điểm @0.1°) và chuyển
/// đổi sang lidar_core::LaserScan.
class LakiBeamDriver : public ILidarSource
{
public:
explicit LakiBeamDriver(const LakibeamConfig & config);
~LakiBeamDriver() override;
LakiBeamDriver(const LakiBeamDriver &) = delete;
LakiBeamDriver & operator=(const LakiBeamDriver &) = delete;
bool start() override;
void stop() override;
bool isRunning() const override;
bool waitForScan(LaserScan & out, int32_t timeout_ms) override;
bool tryGetScan(LaserScan & out) override;
void setCallback(ScanCallback callback) override;
uint64_t scansReceived() const override;
/// @return cấu hình hiện tại của driver
const LakibeamConfig & config() const {return config_;}
private:
/// @brief Vòng lặp worker: poll SDK → convert → push queue + fire callback
void workerLoop();
LakibeamConfig config_;
class Impl; // che chi tiết SDK khỏi public header
std::unique_ptr<Impl> impl_;
std::atomic<bool> running_{false};
std::thread worker_;
mutable std::mutex queue_mutex_;
std::condition_variable queue_cv_;
std::deque<LaserScan> scan_queue_;
mutable std::mutex callback_mutex_;
ScanCallback callback_;
std::atomic<uint64_t> scans_received_{0};
};
} // namespace lidar_core
#endif // LIDAR_CORE__LAKIBEAM_DRIVER_HPP_

View File

@@ -0,0 +1,40 @@
#ifndef LIDAR_CORE__LASER_SCAN_HPP_
#define LIDAR_CORE__LASER_SCAN_HPP_
#include <cstdint>
#include <string>
#include <vector>
namespace lidar_core
{
/// @brief Mirror của std_msgs/Header (sensor_msgs/msg/Header)
struct Header
{
int32_t stamp_sec = 0; ///< giây (epoch)
uint32_t stamp_nanosec = 0; ///< phần nano giây
std::string frame_id; ///< frame tọa độ của scan
};
/// @brief Cấu trúc dữ liệu lidar theo chuẩn sensor_msgs/msg/LaserScan
/// (https://docs.ros2.org/foxy/api/sensor_msgs/msg/LaserScan.html)
/// thuần C++, KHÔNG phụ thuộc ROS.
struct LaserScan
{
Header header; ///< header: thời điểm của tia đầu tiên + frame_id
float angle_min = 0.0f; ///< góc bắt đầu tia đầu tiên [rad]
float angle_max = 0.0f; ///< góc kết thúc tia cuối cùng [rad]
float angle_increment = 0.0f; ///< độ phân giải góc giữa 2 tia liên tiếp [rad]
float time_increment = 0.0f; ///< thời gian giữa 2 phép đo liên tiếp [s]
float scan_time = 0.0f; ///< thời gian giữa 2 lần scan liên tiếp [s]
float range_min = 0.0f; ///< khoảng cách đo tối thiểu [m]
float range_max = 0.0f; ///< khoảng cách đo tối đa [m]
std::vector<float> ranges; ///< dữ liệu khoảng cách [m]; +Inf = không có echo
std::vector<float> intensities; ///< dữ liệu cường độ phản hồi (RSSI, theo thiết bị)
};
} // namespace lidar_core
#endif // LIDAR_CORE__LASER_SCAN_HPP_

View File

@@ -0,0 +1,55 @@
#ifndef LIDAR_CORE__LIDAR_SOURCE_HPP_
#define LIDAR_CORE__LIDAR_SOURCE_HPP_
#include <cstdint>
#include <functional>
#include "lidar_core/laser_scan.hpp"
namespace lidar_core
{
/// @brief Interface trừu tượng cho mọi nguồn dữ liệu lidar.
///
/// Dữ liệu đầu ra luôn là lidar_core::LaserScan — cấu trúc tương thích 1:1
/// với sensor_msgs/msg/LaserScan của ROS 2. Lớp triển khai chịu trách nhiệm
/// thu nhận dữ liệu thô từ thiết bị và chuyển đổi về chuẩn này.
class ILidarSource
{
public:
/// @brief Callback nhận scan mới (được gọi từ thread worker của driver)
using ScanCallback = std::function<void(const LaserScan &)>;
virtual ~ILidarSource() = default;
/// @brief Bắt đầu thu nhận dữ liệu (mở socket, khởi động thread worker)
/// @return true nếu khởi động thành công
virtual bool start() = 0;
/// @brief Dừng thu nhận và giải phóng tài nguyên
virtual void stop() = 0;
/// @return true nếu driver đang chạy
virtual bool isRunning() const = 0;
/// @brief Lấy scan mới nhất (chặn đến khi có scan hoặc hết timeout)
/// @param out scan đầu ra
/// @param timeout_ms thời gian chờ tối đa (ms)
/// @return true nếu nhận được scan
virtual bool waitForScan(LaserScan & out, int32_t timeout_ms) = 0;
/// @brief Lấy scan mới nhất (không chặn)
/// @param out scan đầu ra
/// @return true nếu có scan sẵn trong hàng đợi
virtual bool tryGetScan(LaserScan & out) = 0;
/// @brief Đặt callback được gọi mỗi khi có scan mới
virtual void setCallback(ScanCallback callback) = 0;
/// @return tổng số scan đã nhận từ khi start()
virtual uint64_t scansReceived() const = 0;
};
} // namespace lidar_core
#endif // LIDAR_CORE__LIDAR_SOURCE_HPP_

View File

@@ -0,0 +1,151 @@
#include "lidar_core/lakibeam_driver.hpp"
#include <chrono>
#include "LakiBeamUDP.h"
#include "scan_conversion.hpp"
namespace lidar_core
{
/// @brief Che chi tiết SDK khỏi public header (pimpl)
class LakiBeamDriver::Impl
{
public:
std::unique_ptr<LakiBeamUDP> udp;
};
LakiBeamDriver::LakiBeamDriver(const LakibeamConfig & config)
: config_(config), impl_(std::make_unique<Impl>())
{
if (config_.queue_size == 0) {
config_.queue_size = 1;
}
}
LakiBeamDriver::~LakiBeamDriver()
{
stop();
}
bool LakiBeamDriver::start()
{
if (running_.load()) {
return true;
}
// LakiBeamUDP(local_ip, local_port, laser_ip, laser_port)
// Lưu ý: SDK luôn bind 0.0.0.0 (tham số host_ip bị bỏ qua ở tầng SDK).
try {
impl_->udp = std::make_unique<LakiBeamUDP>(
config_.host_ip, config_.host_port, config_.lidar_ip, config_.lidar_port);
} catch (const std::exception & e) {
impl_->udp.reset();
return false;
}
scans_received_.store(0);
running_.store(true);
worker_ = std::thread(&LakiBeamDriver::workerLoop, this);
return true;
}
void LakiBeamDriver::stop()
{
const bool was_running = running_.exchange(false);
if (was_running && worker_.joinable()) {
queue_cv_.notify_all();
worker_.join();
}
impl_->udp.reset(); // ~LakiBeamUDP: stop io_service + join thread SDK
std::lock_guard<std::mutex> lock(queue_mutex_);
scan_queue_.clear();
}
bool LakiBeamDriver::isRunning() const
{
return running_.load();
}
void LakiBeamDriver::workerLoop()
{
repark_t rep;
while (running_.load()) {
bool has_scan = false;
// get_repackedpack là non-blocking: trả false khi chưa có vòng quét hoàn chỉnh
if (impl_->udp) {
has_scan = impl_->udp->get_repackedpack(rep);
}
if (!has_scan) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
LaserScan scan;
if (!detail::convertRepackToScan(rep, config_, scan)) {
continue;
}
scans_received_.fetch_add(1, std::memory_order_relaxed);
// 1) Fire callback (nếu có)
ScanCallback cb;
{
std::lock_guard<std::mutex> lock(callback_mutex_);
cb = callback_;
}
if (cb) {
cb(scan);
}
// 2) Push vào hàng đợi (drop-oldest)
{
std::lock_guard<std::mutex> lock(queue_mutex_);
while (scan_queue_.size() >= config_.queue_size) {
scan_queue_.pop_front();
}
scan_queue_.push_back(scan);
}
queue_cv_.notify_all();
}
}
bool LakiBeamDriver::waitForScan(LaserScan & out, int32_t timeout_ms)
{
std::unique_lock<std::mutex> lock(queue_mutex_);
const bool got =
queue_cv_.wait_for(
lock, std::chrono::milliseconds(timeout_ms),
[this] {return !scan_queue_.empty() || !running_.load();});
if (!got || scan_queue_.empty()) {
return false;
}
out = std::move(scan_queue_.front());
scan_queue_.pop_front();
return true;
}
bool LakiBeamDriver::tryGetScan(LaserScan & out)
{
std::lock_guard<std::mutex> lock(queue_mutex_);
if (scan_queue_.empty()) {
return false;
}
out = std::move(scan_queue_.front());
scan_queue_.pop_front();
return true;
}
void LakiBeamDriver::setCallback(ScanCallback callback)
{
std::lock_guard<std::mutex> lock(callback_mutex_);
callback_ = std::move(callback);
}
uint64_t LakiBeamDriver::scansReceived() const
{
return scans_received_.load(std::memory_order_relaxed);
}
} // namespace lidar_core

View File

@@ -0,0 +1,147 @@
#include "scan_conversion.hpp"
#include <chrono>
#include <cmath>
#include <limits>
namespace lidar_core
{
namespace detail
{
namespace
{
constexpr double kDeg2Rad = 3.14159265358979323846 / 180.0;
constexpr double kTwoPi = 2.0 * 3.14159265358979323846;
/// Góc hiệu dụng của 1 điểm dữ liệu sau khi áp flip + offset (đã chuẩn hóa [0, 2π))
inline double effectiveAngle(const cicle_pack_t & dot, const LakibeamConfig & cfg)
{
// azimuth từ SDK: đơn vị 0.01° (0..36000)
double theta = (static_cast<double>(dot.angle) / 100.0) * kDeg2Rad;
if (cfg.angle_flip) {
theta = -theta;
}
return normalizeAnglePositive(theta + cfg.angle_offset_deg * kDeg2Rad);
}
/// Khoảng cách hợp lệ [m]; 0 / ngoài [range_min, range_max] → +Inf
inline float effectiveRange(const cicle_pack_t & dot, const LakibeamConfig & cfg)
{
const float inf = std::numeric_limits<float>::infinity();
if (dot.distance == 0) {
return inf; // không có echo (theo manual §7.2)
}
const double m = static_cast<double>(dot.distance) / 1000.0; // mm → m
if (m < static_cast<double>(cfg.range_min) || m > static_cast<double>(cfg.range_max)) {
return inf;
}
return static_cast<float>(m);
}
/// Slot chưa được SDK fill (buffer zeroed) — phải bỏ qua, không được ghi đè
/// dữ liệu hợp lệ đã bin trong lưới. Đoạn thật "no echo" tại 0° cũng có cùng
/// dấu hiệu (angle=0, distance=0, rssi=0) nhưng bỏ qua là vô hại vì giá trị
/// mặc định của lưới vốn đã là +Inf.
inline bool isUnfilledSlot(const cicle_pack_t & dot)
{
return dot.angle == 0 && dot.distance == 0 && dot.rssi == 0;
}
} // namespace
double normalizeAnglePositive(double angle)
{
angle = std::fmod(angle, kTwoPi);
if (angle < 0.0) {
angle += kTwoPi;
}
return angle;
}
bool convertRepackToScan(const repark_t & rep, const LakibeamConfig & config, LaserScan & out)
{
const size_t n = static_cast<size_t>(rep.maxdots);
if (n == 0 || n > static_cast<size_t>(CONFIG_CIRCLE_DOTS)) {
return false; // không phải vòng quét hoàn chỉnh (SDK chỉ hoàn tất ở 1440/3600 điểm)
}
const double inc = kTwoPi / static_cast<double>(n); // độ phân giải góc [rad]
const float time_increment = static_cast<float>(rep.interval) * 1e-6f; // µs → s
if (!config.crop_fov) {
// ---------- Full 360° ----------
std::vector<float> ranges(n, std::numeric_limits<float>::infinity());
std::vector<float> intensities(n, 0.0f);
for (size_t i = 0; i < n; ++i) {
const cicle_pack_t & dot = rep.dotcloud[i];
if (isUnfilledSlot(dot)) {
continue;
}
const size_t idx =
static_cast<size_t>(std::lround(effectiveAngle(dot, config) / inc)) % n;
ranges[idx] = effectiveRange(dot, config);
intensities[idx] = static_cast<float>(dot.rssi);
}
out.angle_min = 0.0f;
out.angle_max = static_cast<float>(kTwoPi - inc);
out.ranges = std::move(ranges);
out.intensities = std::move(intensities);
} else {
// ---------- Crop FOV [fov_min_deg, fov_max_deg] ----------
const double fov_min = normalizeAnglePositive(config.fov_min_deg * kDeg2Rad);
const double span =
normalizeAnglePositive(config.fov_max_deg * kDeg2Rad - config.fov_min_deg * kDeg2Rad);
const size_t count = static_cast<size_t>(std::lround(span / inc)) + 1; // số tia
std::vector<float> ranges(count, std::numeric_limits<float>::infinity());
std::vector<float> intensities(count, 0.0f);
for (size_t i = 0; i < n; ++i) {
const cicle_pack_t & dot = rep.dotcloud[i];
if (isUnfilledSlot(dot)) {
continue;
}
const double rel = normalizeAnglePositive(effectiveAngle(dot, config) - fov_min);
if (rel > span + inc * 0.5) {
continue; // ngoài FOV
}
const size_t idx = static_cast<size_t>(std::lround(rel / inc));
if (idx >= count) {
continue;
}
ranges[idx] = effectiveRange(dot, config);
intensities[idx] = static_cast<float>(dot.rssi);
}
out.angle_min = static_cast<float>(fov_min);
out.angle_max = static_cast<float>(fov_min + static_cast<double>(count - 1) * inc);
out.ranges = std::move(ranges);
out.intensities = std::move(intensities);
}
out.angle_increment = static_cast<float>(inc);
out.time_increment = time_increment;
out.scan_time = time_increment * static_cast<float>(n);
out.range_min = config.range_min;
out.range_max = config.range_max;
// Thời điểm nhận (host clock) — ROS node sẽ re-stamp bằng node clock
const auto now = std::chrono::system_clock::now();
const auto epoch = now.time_since_epoch();
const int64_t sec =
std::chrono::duration_cast<std::chrono::seconds>(epoch).count();
const int64_t nsec =
std::chrono::duration_cast<std::chrono::nanoseconds>(epoch).count() - sec * 1000000000LL;
out.header.stamp_sec = static_cast<int32_t>(sec);
out.header.stamp_nanosec = static_cast<uint32_t>(nsec);
out.header.frame_id = config.frame_id;
return true;
}
} // namespace detail
} // namespace lidar_core

View File

@@ -0,0 +1,35 @@
#ifndef LIDAR_CORE__SCAN_CONVERSION_HPP_
#define LIDAR_CORE__SCAN_CONVERSION_HPP_
#include "lidar_core/lakibeam_driver.hpp"
#include "lidar_core/laser_scan.hpp"
// Header của SDK (chỉ dùng nội bộ trong core, không export ra consumer)
#include "LakiBeamUDP.h"
namespace lidar_core
{
namespace detail
{
/// @brief Chuyển 1 vòng quét repack từ SDK sang LaserScan chuẩn ROS.
///
/// - azimuth (đơn vị 0.01°) → radian, áp angle_flip + angle_offset, bin vào
/// lưới đều angle_increment = 2π / maxdots
/// - distance (mm) → m; ngoài [range_min, range_max] hoặc = 0 → +Inf
/// - RSSI → intensities
/// - time_increment từ repark_t.interval [µs/dot]; scan_time = time_increment × maxdots
///
/// @param rep vòng quét hoàn chỉnh từ SDK (rep.maxdots ∈ {1440, 3600})
/// @param config cấu hình driver
/// @param out scan đầu ra (bị ghi đè)
/// @return false nếu rep không phải vòng quét hợp lệ (maxdots == 0 hoặc quá lớn)
bool convertRepackToScan(const repark_t & rep, const LakibeamConfig & config, LaserScan & out);
/// @brief Chuẩn hóa góc về [0, 2π)
double normalizeAnglePositive(double angle);
} // namespace detail
} // namespace lidar_core
#endif // LIDAR_CORE__SCAN_CONVERSION_HPP_

View File

@@ -0,0 +1,76 @@
#ifndef ZLAC_ROS__DIFFERENTIAL_DRIVE_KINEMATICS_HPP_
#define ZLAC_ROS__DIFFERENTIAL_DRIVE_KINEMATICS_HPP_
#include <cmath>
#include <cstdint>
namespace zlac_ros {
/**
* @brief Kinematic parameters loaded from configuration file.
*/
struct KinematicsConfig {
double wheel_diameter_m{0.173}; // 173 mm (r = 0.0865 m)
double wheel_base_m{0.400}; // 400 mm (L = 0.400 m)
bool invert_left_wheel{false};
bool invert_right_wheel{true}; // Invert right wheel direction by default
};
/**
* @brief Individual wheel RPM target output.
*/
struct WheelSpeedRPM {
int16_t left{0};
int16_t right{0};
};
/**
* @brief 2D Velocity Twist (linear_x m/s, angular_z rad/s).
*/
struct Twist2D {
double linear_x{0.0}; // m/s
double angular_z{0.0}; // rad/s
};
/**
* @brief 2D Robot Pose (x m, y m, theta rad).
*/
struct Pose2D {
double x{0.0}; // m
double y{0.0}; // m
double theta{0.0}; // rad
};
/**
* @brief Standalone C++ Differential Drive Kinematics & Odometry Class.
* Implements exact Forward/Inverse kinematics from odometry_kinematics_summary.md.
*/
class DifferentialDriveKinematics {
public:
explicit DifferentialDriveKinematics(const KinematicsConfig& config = KinematicsConfig());
/// Inverse Kinematics: Converts (v, omega) -> (RPM_left, RPM_right)
WheelSpeedRPM computeInverseKinematics(double linear_x, double angular_z) const;
/// Forward Kinematics: Converts (RPM_left, RPM_right) -> (v, omega)
Twist2D computeForwardKinematics(double rpm_left, double rpm_right) const;
/// Odometry Integration: Updates 2D pose (x, y, theta) over time step dt
void updateOdometry(double rpm_left, double rpm_right, double dt, bool use_imu = false, double imu_angular_z = 0.0);
/// Pose Accessors & Reset
Pose2D getPose() const;
void resetPose(double x = 0.0, double y = 0.0, double theta = 0.0);
const KinematicsConfig& getConfig() const { return config_; }
void setConfig(const KinematicsConfig& config);
private:
KinematicsConfig config_;
double wheel_radius_m_;
Pose2D current_pose_;
};
} // namespace zlac_ros
#endif // ZLAC_ROS__DIFFERENTIAL_DRIVE_KINEMATICS_HPP_

View File

@@ -0,0 +1,167 @@
#ifndef ZLAC_ROS__ZLAC_MOTOR_DRIVER_HPP_
#define ZLAC_ROS__ZLAC_MOTOR_DRIVER_HPP_
#include <lely/coapp/driver.hpp>
#include <lely/coapp/master.hpp>
#include <lely/ev/loop.hpp>
#include <lely/io2/linux/can.hpp>
#include <lely/io2/sys/io.hpp>
#include <lely/io2/sys/timer.hpp>
#include <lely/io2/posix/poll.hpp>
#include <iostream>
#include <memory>
#include <atomic>
#include <thread>
#include <chrono>
#include <string>
#include <future>
#include <optional>
#include <system_error>
namespace zlac_ros {
/**
* @brief Synchronous SDO write helper for thread-safe sequential execution.
*/
template <typename T>
bool sdo_write_sync(lely::canopen::AsyncMaster& master, uint8_t node_id, uint16_t idx, uint8_t subidx, T val) {
std::promise<bool> prom;
auto fut = prom.get_future();
master.SubmitWrite(master.get_executor(), node_id, idx, subidx, val,
[&prom](uint8_t, uint16_t, uint8_t, std::error_code ec) {
prom.set_value(!ec);
});
if (fut.wait_for(std::chrono::seconds(2)) == std::future_status::ready) {
return fut.get();
}
return false;
}
/**
* @brief Synchronous SDO read helper.
*/
template <typename T>
std::optional<T> sdo_read_sync(lely::canopen::AsyncMaster& master, uint8_t node_id, uint16_t idx, uint8_t subidx) {
std::promise<std::optional<T>> prom;
auto fut = prom.get_future();
master.SubmitRead<T>(master.get_executor(), node_id, idx, subidx,
[&prom](uint8_t, uint16_t, uint8_t, std::error_code ec, T val) {
if (ec) {
prom.set_value(std::nullopt);
} else {
prom.set_value(val);
}
});
if (fut.wait_for(std::chrono::seconds(2)) == std::future_status::ready) {
return fut.get();
}
return std::nullopt;
}
class ZlacMotorDriver; // Forward declaration
/**
* @brief Lely CANopen Basic Driver implementation for ZLAC8015D.
*/
class ZlacLelyDriver : public lely::canopen::BasicDriver {
public:
ZlacLelyDriver(lely::canopen::AsyncMaster& master, uint8_t id, ZlacMotorDriver* parent)
: BasicDriver(master, id), parent_(parent) {}
protected:
void OnBoot(lely::canopen::NmtState st, char es, const std::string& what) noexcept override;
void OnHeartbeat(bool occurred) noexcept override;
private:
ZlacMotorDriver* parent_{nullptr};
};
/**
* @brief Standalone Core C++ Motor Driver class for ZLAC8015D.
* Decoupled from ROS2 Node logic. Encapsulates all Lely CANopen communication.
*/
class ZlacMotorDriver {
public:
ZlacMotorDriver(const std::string& can_channel, uint8_t node_id, const std::string& dcf_path);
~ZlacMotorDriver();
/// Initialize CANopen master stack and start Lely event loop
bool initMaster();
/// Configure DS402 Profile Velocity Mode (Mode 3) and enable power stage
bool enableHardware(uint32_t acc_dec = 500);
/// Safely disable motor power stage and send NMT STOP
void disableHardware();
/// Quick Stop - Stop motors using Quick Stop command (0x0006)
/// Slightly safer than emergency stop as it follows deceleration ramp
void quickStop();
/// Send Target Velocities (RPM) to Left and Right motors
bool setTargetRPM(int16_t left_rpm, int16_t right_rpm);
/// Read actual velocity telemetry (RPM) from driver
bool getActualRPM(double& out_left_rpm, double& out_right_rpm);
// [vslam] Doc vi tri TICH LUY tu 0x6064 (Position actual value), don vi
// "count". Ban goc chi co getActualRPM() -- tuc chi co van toc, va tich
// phan van toc thi lo mot mau telemetry la mat vinh vien mot doan quang
// duong ma khong phat hien duoc. Xem thirdparty/PROVENANCE.md.
bool getPositionCounts(int32_t& out_left, int32_t& out_right);
bool isReady() const { return hardware_ready_.load(); }
bool hasConnectionLost() const { return connection_lost_.load(); }
void recoverConnection();
void notifyConnectionLost();
void notifyHeartbeatStatus(bool is_lost);
using ConnectionCallback = std::function<void(bool)>;
void setConnectionCallback(ConnectionCallback cb) { connection_cb_ = cb; }
private:
ConnectionCallback connection_cb_;
std::string can_channel_;
uint8_t node_id_;
std::string dcf_path_;
std::unique_ptr<lely::io::IoGuard> io_guard_;
std::unique_ptr<lely::io::Context> ctx_;
std::unique_ptr<lely::io::Poll> poll_;
std::unique_ptr<lely::ev::Loop> loop_;
std::unique_ptr<lely::io::Timer> timer_;
std::unique_ptr<lely::io::CanController> ctrl_;
std::unique_ptr<lely::io::CanChannel> chan_;
std::unique_ptr<lely::canopen::AsyncMaster> master_;
std::unique_ptr<ZlacLelyDriver> driver_;
std::thread lely_thread_;
std::atomic<bool> master_initialized_{false};
std::atomic<bool> hardware_ready_{false};
std::atomic<bool> connection_lost_{false};
// Telemetry caching
std::thread telemetry_thread_;
std::atomic<int32_t> cached_left_vel_raw_{0};
std::atomic<int32_t> cached_right_vel_raw_{0};
std::atomic<bool> cached_vel_valid_{false};
// [vslam] Cache vi tri, cap nhat trong cung telemetryLoop voi van toc.
std::atomic<int32_t> cached_left_pos_raw_{0};
std::atomic<int32_t> cached_right_pos_raw_{0};
std::atomic<bool> cached_pos_valid_{false};
void telemetryLoop();
// Target caching
int16_t last_target_left_rpm_{-1};
int16_t last_target_right_rpm_{-1};
bool pdo_mapped_{false};
};
} // namespace zlac_ros
#endif // ZLAC_ROS__ZLAC_MOTOR_DRIVER_HPP_

View File

@@ -0,0 +1,85 @@
#include "zlac_ros/differential_drive_kinematics.hpp"
#include <algorithm>
namespace zlac_ros {
DifferentialDriveKinematics::DifferentialDriveKinematics(const KinematicsConfig& config)
: config_(config), wheel_radius_m_(config.wheel_diameter_m / 2.0) {
resetPose();
}
void DifferentialDriveKinematics::setConfig(const KinematicsConfig& config) {
config_ = config;
wheel_radius_m_ = config.wheel_diameter_m / 2.0;
}
WheelSpeedRPM DifferentialDriveKinematics::computeInverseKinematics(double linear_x, double angular_z) const {
// 1. Linear velocity for individual wheels (m/s)
// v_L = v - (omega * L / 2)
// v_R = v + (omega * L / 2)
double v_left = linear_x - (angular_z * config_.wheel_base_m / 2.0);
double v_right = linear_x + (angular_z * config_.wheel_base_m / 2.0);
// 2. Convert m/s to RPM: RPM = (v / r) * (30 / pi)
constexpr double rads_to_rpm = 30.0 / M_PI;
double rpm_l = (v_left / wheel_radius_m_) * rads_to_rpm;
double rpm_r = (v_right / wheel_radius_m_) * rads_to_rpm;
// 3. Apply wheel inversion flags
if (config_.invert_left_wheel) rpm_l = -rpm_l;
if (config_.invert_right_wheel) rpm_r = -rpm_r;
WheelSpeedRPM result;
result.left = static_cast<int16_t>(std::round(rpm_l));
result.right = static_cast<int16_t>(std::round(rpm_r));
return result;
}
Twist2D DifferentialDriveKinematics::computeForwardKinematics(double rpm_left, double rpm_right) const {
// Apply inverse of inversion flags to restore true mechanical direction
if (config_.invert_left_wheel) rpm_left = -rpm_left;
if (config_.invert_right_wheel) rpm_right = -rpm_right;
// Convert RPM to linear velocity (m/s): v = RPM * (pi / 30) * r
constexpr double rpm_to_rads = M_PI / 30.0;
double v_left = (rpm_left * rpm_to_rads) * wheel_radius_m_;
double v_right = (rpm_right * rpm_to_rads) * wheel_radius_m_;
Twist2D twist;
twist.linear_x = (v_right + v_left) / 2.0;
twist.angular_z = (v_right - v_left) / config_.wheel_base_m;
return twist;
}
void DifferentialDriveKinematics::updateOdometry(double rpm_left, double rpm_right, double dt, bool use_imu, double imu_angular_z) {
if (dt <= 0.0) return;
Twist2D twist = computeForwardKinematics(rpm_left, rpm_right);
double delta_s = twist.linear_x * dt;
// Use IMU angular velocity if enabled, otherwise use encoder kinematics
double angular_z = use_imu ? imu_angular_z : twist.angular_z;
double delta_theta = angular_z * dt;
// Mid-point integration for robust pose estimation
double theta_mid = current_pose_.theta + (delta_theta / 2.0);
current_pose_.x += delta_s * std::cos(theta_mid);
current_pose_.y += delta_s * std::sin(theta_mid);
current_pose_.theta += delta_theta;
// Normalize theta to [-pi, pi]
current_pose_.theta = std::atan2(std::sin(current_pose_.theta), std::cos(current_pose_.theta));
}
Pose2D DifferentialDriveKinematics::getPose() const {
return current_pose_;
}
void DifferentialDriveKinematics::resetPose(double x, double y, double theta) {
current_pose_.x = x;
current_pose_.y = y;
current_pose_.theta = theta;
}
} // namespace zlac_ros

View File

@@ -0,0 +1,328 @@
#include "zlac_ros/zlac_motor_driver.hpp"
#include <cstring>
#include <iostream>
#include <fstream>
namespace zlac_ros {
void ZlacLelyDriver::OnBoot(lely::canopen::NmtState st, char es, const std::string& what) noexcept {
(void)st; (void)es; (void)what;
std::cout << "[CANopen] Driver Node " << (int)id() << " booted. Forcing NMT START..." << std::endl;
master.Command(lely::canopen::NmtCommand::START, id());
}
void ZlacLelyDriver::OnHeartbeat(bool occurred) noexcept {
if (occurred) {
std::cerr << "[ZlacLelyDriver ERROR] Heartbeat timeout occurred! Connection lost." << std::endl;
if (parent_) {
parent_->notifyConnectionLost();
}
} else {
std::cout << "[ZlacLelyDriver] Heartbeat recovered." << std::endl;
if (parent_) {
parent_->notifyHeartbeatStatus(false);
}
}
}
void ZlacMotorDriver::notifyConnectionLost() {
connection_lost_ = true;
hardware_ready_ = false;
notifyHeartbeatStatus(true);
}
void ZlacMotorDriver::notifyHeartbeatStatus(bool is_lost) {
if (connection_cb_) {
connection_cb_(is_lost);
}
}
ZlacMotorDriver::ZlacMotorDriver(const std::string& can_channel, uint8_t node_id, const std::string& dcf_path)
: can_channel_(can_channel), node_id_(node_id), dcf_path_(dcf_path) {}
ZlacMotorDriver::~ZlacMotorDriver() {
disableHardware();
}
bool ZlacMotorDriver::initMaster() {
if (master_initialized_) return true;
try {
if (!io_guard_) io_guard_ = std::make_unique<lely::io::IoGuard>();
if (!ctx_) ctx_ = std::make_unique<lely::io::Context>();
poll_ = std::make_unique<lely::io::Poll>(*ctx_);
loop_ = std::make_unique<lely::ev::Loop>(poll_->get_poll());
auto exec = loop_->get_executor();
timer_ = std::make_unique<lely::io::Timer>(*poll_, exec, CLOCK_MONOTONIC);
ctrl_ = std::make_unique<lely::io::CanController>(can_channel_.c_str());
chan_ = std::make_unique<lely::io::CanChannel>(*poll_, exec);
chan_->open(*ctrl_);
master_ = std::make_unique<lely::canopen::AsyncMaster>(*timer_, *chan_, dcf_path_, "", 127);
driver_ = std::make_unique<ZlacLelyDriver>(*master_, node_id_, this);
master_->Reset();
lely_thread_ = std::thread([this]() {
try {
loop_->run();
} catch (...) {}
});
master_initialized_ = true;
std::cout << "[ZlacMotorDriver] Lely CANopen Master started successfully on " << can_channel_ << std::endl;
return true;
} catch (const std::exception& e) {
std::cerr << "[ZlacMotorDriver ERROR] Failed to initialize CANopen master: " << e.what() << std::endl;
return false;
}
}
bool ZlacMotorDriver::enableHardware(uint32_t acc_dec) {
if (!master_initialized_) {
if (!initMaster()) return false;
}
std::cout << "[ZlacMotorDriver] Initiating ZLAC8015D DS402 Initialization Sequence..." << std::endl;
// 1. Send NMT START and wait for CAN bus & NMT state to stabilize
master_->Command(lely::canopen::NmtCommand::START, node_id_);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
// 2. Set Profile Velocity Mode (Mode = 3 on 0x6060:00) with retries
bool mode_success = false;
for (int attempt = 1; attempt <= 5; ++attempt) {
std::cout << "[ZlacMotorDriver] Writing Profile Velocity Mode (0x6060:0 = 3), attempt " << attempt << "..." << std::endl;
if (sdo_write_sync<int8_t>(*master_, node_id_, 0x6060, 0, 3)) {
mode_success = true;
break;
}
master_->Command(lely::canopen::NmtCommand::START, node_id_);
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
if (!mode_success) {
std::cerr << "[ZlacMotorDriver ERROR] Failed to write Profile Velocity Mode (0x6060:0) after retries!" << std::endl;
return false;
}
// 3. Set Profile Acceleration and Deceleration (0x6083 / 0x6084)
sdo_write_sync<uint32_t>(*master_, node_id_, 0x6083, 1, acc_dec);
sdo_write_sync<uint32_t>(*master_, node_id_, 0x6083, 2, acc_dec);
sdo_write_sync<uint32_t>(*master_, node_id_, 0x6084, 1, acc_dec);
sdo_write_sync<uint32_t>(*master_, node_id_, 0x6084, 2, acc_dec);
// Set Producer Heartbeat Time (0x1017) to 500ms on the Node
sdo_write_sync<uint16_t>(*master_, node_id_, 0x1017, 0, 500);
// Configure master to consume heartbeat (allow 1000ms timeout)
driver_->ConfigHeartbeat(std::chrono::milliseconds(1000));
// 4. DS402 State Machine Sequence
// Step 1: Ready to switch on (0x0006)
if (!sdo_write_sync<uint16_t>(*master_, node_id_, 0x6040, 0, 0x0006)) return false;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
// Step 2: Switched on (0x0007)
if (!sdo_write_sync<uint16_t>(*master_, node_id_, 0x6040, 0, 0x0007)) return false;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
// Step 3: Operation enabled (0x000F)
if (!sdo_write_sync<uint16_t>(*master_, node_id_, 0x6040, 0, 0x000F)) return false;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
// Step 4: Unlock Ramp Generator (0x007F)
if (!sdo_write_sync<uint16_t>(*master_, node_id_, 0x6040, 0, 0x007F)) return false;
hardware_ready_ = true;
std::cout << "[SUCCESS] ZLAC8015D Motor Hardware ENABLED and READY!" << std::endl;
// Start background telemetry loop thread if not already running
if (!telemetry_thread_.joinable()) {
telemetry_thread_ = std::thread(&ZlacMotorDriver::telemetryLoop, this);
}
return true;
}
void ZlacMotorDriver::disableHardware() {
if (!hardware_ready_.exchange(false)) return;
std::cout << "[ZlacMotorDriver] Safely disabling motor hardware..." << std::endl;
// 1. Send zero target velocity
setTargetRPM(0, 0);
// 2. Disable DS402 power stage (0x0006 Shutdown)
if (master_) {
sdo_write_sync<uint16_t>(*master_, node_id_, 0x6040, 0, 0x0006);
}
// 3. Send NMT STOP
if (master_) {
master_->Command(lely::canopen::NmtCommand::STOP, node_id_);
}
if (telemetry_thread_.joinable()) {
telemetry_thread_.join();
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if (loop_) {
loop_->stop();
}
if (lely_thread_.joinable()) {
lely_thread_.join();
}
master_initialized_ = false;
std::cout << "[SUCCESS] ZLAC8015D Motor Hardware Disabled Safely." << std::endl;
}
void ZlacMotorDriver::quickStop() {
std::cout << "[ZlacMotorDriver] QUICK STOP triggered!" << std::endl;
// Set target velocity to zero
setTargetRPM(0, 0);
// Quick Stop command: 0x0006 = Switch On + Enable Voltage + Quick Stop
// Quick Stop bit (bit 2) = 0 triggers quick stop deceleration
if (master_) {
sdo_write_sync<uint16_t>(*master_, node_id_, 0x6040, 0, 0x0006);
}
std::cout << "[ZlacMotorDriver] QUICK STOP executed - motors stopping!" << std::endl;
}
void ZlacMotorDriver::recoverConnection() {
std::cout << "[ZlacMotorDriver] Recovering connection. Cleaning up old CAN master..." << std::endl;
hardware_ready_ = false;
if (loop_) {
loop_->stop();
}
if (lely_thread_.joinable()) {
lely_thread_.join();
}
if (telemetry_thread_.joinable()) {
telemetry_thread_.join();
}
// Xóa các object Lely theo đúng thứ tự ngược lại để tránh Dangling Pointers (Segfault)
driver_.reset();
master_.reset();
chan_.reset();
ctrl_.reset();
timer_.reset();
loop_.reset();
poll_.reset();
master_initialized_ = false;
pdo_mapped_ = false;
connection_lost_ = false;
cached_vel_valid_ = false;
std::cout << "[ZlacMotorDriver] Old CAN master cleaned up. Ready for re-initialization." << std::endl;
}
bool ZlacMotorDriver::setTargetRPM(int16_t left_rpm, int16_t right_rpm) {
if (!hardware_ready_ || !master_) return false;
if (left_rpm == last_target_left_rpm_ && right_rpm == last_target_right_rpm_) {
return true; // Avoid redundant CAN traffic
}
// ZLAC8015D manual Page 19-20: 0x60FF:03 combines Left (low 16 bits) and Right (high 16 bits)
uint32_t combined_vel = (static_cast<uint16_t>(left_rpm) & 0xFFFF) |
((static_cast<uint16_t>(right_rpm) & 0xFFFF) << 16);
master_->SubmitWrite(master_->get_executor(), node_id_, 0x60FF, 3, combined_vel,
[](uint8_t, uint16_t, uint8_t, std::error_code) {});
last_target_left_rpm_ = left_rpm;
last_target_right_rpm_ = right_rpm;
return true;
}
void ZlacMotorDriver::telemetryLoop() {
while (hardware_ready_.load()) {
if (master_) {
if (!pdo_mapped_) {
try {
auto rpdo = master_->RpdoMapped(node_id_);
int32_t test_val = rpdo[0x606C][1]; // Test access
(void)test_val;
pdo_mapped_ = true;
} catch (...) {
// Fallback to SDO synchronous read if PDO is not mapped yet
auto left_opt = sdo_read_sync<int32_t>(*master_, node_id_, 0x606C, 1);
auto right_opt = sdo_read_sync<int32_t>(*master_, node_id_, 0x606C, 2);
if (left_opt.has_value() && right_opt.has_value()) {
cached_left_vel_raw_ = left_opt.value();
cached_right_vel_raw_ = right_opt.value();
cached_vel_valid_ = true;
}
}
}
if (pdo_mapped_) {
auto rpdo = master_->RpdoMapped(node_id_);
cached_left_vel_raw_ = static_cast<int32_t>(rpdo[0x606C][1]);
cached_right_vel_raw_ = static_cast<int32_t>(rpdo[0x606C][2]);
cached_vel_valid_ = true;
}
// [vslam] Vi tri tich luy. Thu PDO truoc (cung mot khung, hai banh lay
// mau DONG THOI); PDO khong map thi roi ve SDO.
//
// ⚠️ Duong SDO doc hai banh bang HAI giao dich tuan tu, nen hai banh
// lech nhau vai ms. Cong thuc vi sai omega = (v_r - v_l)/L bien dung do
// lech do thanh QUAY GIA -- da do duoc 0.2-0.3 rad/s tren robot. Map
// 0x6064:01 va :02 vao mot TPDO (hai I32 = dung 8 byte) thi het.
bool pos_ok = false;
try {
auto rpdo = master_->RpdoMapped(node_id_);
cached_left_pos_raw_ = static_cast<int32_t>(rpdo[0x6064][1]);
cached_right_pos_raw_ = static_cast<int32_t>(rpdo[0x6064][2]);
pos_ok = true;
} catch (...) {
auto lp = sdo_read_sync<int32_t>(*master_, node_id_, 0x6064, 1);
auto rp = sdo_read_sync<int32_t>(*master_, node_id_, 0x6064, 2);
if (lp.has_value() && rp.has_value()) {
cached_left_pos_raw_ = lp.value();
cached_right_pos_raw_ = rp.value();
pos_ok = true;
}
}
if (pos_ok) cached_pos_valid_ = true;
}
std::this_thread::sleep_for(std::chrono::milliseconds(20)); // 50 Hz telemetry poll
}
}
bool ZlacMotorDriver::getActualRPM(double& out_left_rpm, double& out_right_rpm) {
if (!cached_vel_valid_.load()) return false;
// Velocity values in 0x606C are in 0.1 RPM units according to ZLAC8015D EDS
out_left_rpm = cached_left_vel_raw_.load() / 10.0;
out_right_rpm = cached_right_vel_raw_.load() / 10.0;
return true;
}
// [vslam] Xem PROVENANCE.md. 0x6064 la bo dem TUYET DOI trong driver motor:
// lo mot mau thi mau sau van dung, khac han tich phan van toc.
bool ZlacMotorDriver::getPositionCounts(int32_t& out_left, int32_t& out_right) {
if (!cached_pos_valid_.load()) return false;
out_left = cached_left_pos_raw_.load();
out_right = cached_right_pos_raw_.load();
return true;
}
} // namespace zlac_ros