update
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user