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