update
This commit is contained in:
76
libs/vslam_drivers/thirdparty/zlac/include/zlac_ros/differential_drive_kinematics.hpp
vendored
Normal file
76
libs/vslam_drivers/thirdparty/zlac/include/zlac_ros/differential_drive_kinematics.hpp
vendored
Normal 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_
|
||||
167
libs/vslam_drivers/thirdparty/zlac/include/zlac_ros/zlac_motor_driver.hpp
vendored
Normal file
167
libs/vslam_drivers/thirdparty/zlac/include/zlac_ros/zlac_motor_driver.hpp
vendored
Normal 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_
|
||||
85
libs/vslam_drivers/thirdparty/zlac/src/differential_drive_kinematics.cpp
vendored
Normal file
85
libs/vslam_drivers/thirdparty/zlac/src/differential_drive_kinematics.cpp
vendored
Normal 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
|
||||
328
libs/vslam_drivers/thirdparty/zlac/src/zlac_motor_driver.cpp
vendored
Normal file
328
libs/vslam_drivers/thirdparty/zlac/src/zlac_motor_driver.cpp
vendored
Normal 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
|
||||
Reference in New Issue
Block a user