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

@@ -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