337 lines
12 KiB
C++
337 lines
12 KiB
C++
// Base ZLAC8015D -- LOP BOC quanh `ZlacMotorDriver` cua base_kit.
|
|
//
|
|
// ================== KIEN TRUC THAT KHAC DAC TA ==================
|
|
// driver_config.h gia dinh encoder ve qua serial MCU (`E,<micros>,...`).
|
|
// Tren robot nay KHONG PHAI VAY: encoder va motor deu di qua `can0`, CANopen
|
|
// DS402 Profile Velocity Mode.
|
|
//
|
|
// Hau qua truc tiep: khong co duong nao dong bo dong ho base voi dong ho host.
|
|
// ClockSync chi bac cau duoc cho MCU serial. Stamp cua EncoderReading la dong
|
|
// ho HOST luc doc xong cache telemetry.
|
|
//
|
|
// ================== VI SAO BOC CHU KHONG TU VIET ==================
|
|
// Ban truoc cua file nay tu dieu khien lely. No chay duoc toi tan 0x6064,
|
|
// nhung mat ba vong thu-sai cho nhung thu ban goc da biet: phai cho slave
|
|
// BOOT xong roi moi gui SDO dau tien, thu tu chuoi DS402, va 0x608F khong
|
|
// ton tai tren thiet bi nay.
|
|
//
|
|
// `ZlacMotorDriver` la ban CHUAN dang lai con robot nay. Xem
|
|
// thirdparty/PROVENANCE.md.
|
|
//
|
|
// ================== MOT CHO DA SUA TRONG BAN NHUNG ==================
|
|
// Ban goc chi co `getActualRPM()` -- tuc chi co VAN TOC. `EncoderReading` can
|
|
// GOC QUAY TICH LUY: tich phan van toc thi lo mot mau telemetry la mat vinh
|
|
// vien mot doan quang duong va khong co cach nao phat hien (mcu_protocol.h).
|
|
// Da them `getPositionCounts()` doc 0x6064 -- bo dem TUYET DOI trong driver
|
|
// motor, lo mau khong mat gi.
|
|
|
|
#include <algorithm>
|
|
#include <cmath>
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <string>
|
|
#include <thread>
|
|
|
|
#include "zlac_ros/differential_drive_kinematics.hpp"
|
|
#include "zlac_ros/zlac_motor_driver.hpp"
|
|
|
|
#include "vslam/clock.h"
|
|
#include "vslam/driver_config.h"
|
|
#include "vslam/driver_interfaces.h"
|
|
#include "vslam/log.h"
|
|
|
|
namespace vslam {
|
|
namespace {
|
|
|
|
constexpr double kTwoPi = 2.0 * M_PI;
|
|
|
|
// 0x200E:01 tren thiet bi nay doc ra 4096 "wire". Quy uoc cau phuong pho bien
|
|
// cho 4 count moi wire.
|
|
//
|
|
// ⚠️ CHUA KIEM CHUNG: can_help.pdf goi 0x200E la "wire number" va don vi cua
|
|
// 0x6064 la "count", khong cho nao trong 37 trang noi he so giua hai cai.
|
|
// Sai he so nay lam odometry sai dung 4 lan. Do (2 phut): ke banh len, doc
|
|
// 0x6064:01, quay banh mot vong bang tay, doc lai, lay hieu -- roi dat vao
|
|
// `base.encoder_counts_per_rev` de khong con phai doan.
|
|
constexpr uint32_t kDefaultCountsPerRev = 4096 * 4;
|
|
|
|
class ZlacWrapper : public BaseInterface {
|
|
public:
|
|
ZlacWrapper(const BaseConfig& cfg, ClockPtr clock)
|
|
: cfg_(cfg), clock_(std::move(clock)) {}
|
|
|
|
~ZlacWrapper() override { Close(); }
|
|
|
|
void SetEncoderCallback(EncoderCallback cb) override { cb_ = std::move(cb); }
|
|
|
|
StatusResponse Open() override {
|
|
if (impl_) {
|
|
return StatusResponse::Error(StatusCode::kFailedPrecondition,
|
|
"base: da mo roi");
|
|
}
|
|
if (!clock_) {
|
|
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
|
"base: thieu clock");
|
|
}
|
|
if (cfg_.dcf_path.empty()) {
|
|
return StatusResponse::Error(
|
|
StatusCode::kInvalidArgument,
|
|
"base: thieu dcf_path. lely can file master.dcf sinh bang `dcfgen`.");
|
|
}
|
|
if (!(cfg_.wheel_radius > 0.0) || !(cfg_.wheel_separation > 0.0)) {
|
|
return StatusResponse::Error(
|
|
StatusCode::kInvalidArgument,
|
|
"base: wheel_radius / wheel_separation <= 0");
|
|
}
|
|
|
|
counts_per_rev_ = cfg_.encoder_counts_per_rev != 0
|
|
? cfg_.encoder_counts_per_rev
|
|
: kDefaultCountsPerRev;
|
|
if (cfg_.encoder_counts_per_rev == 0) {
|
|
VSLAM_WARN("base: encoder_counts_per_rev chua dat, dung mac dinh "
|
|
<< counts_per_rev_ << " (4096 wire x 4 cau phuong, CHUA kiem "
|
|
"chung). Sai he so nay lam odometry sai 4 lan -- do bang cach "
|
|
"quay banh mot vong roi so hieu 0x6064.");
|
|
}
|
|
|
|
// Hinh hoc lay tu BaseConfig, ma no da duoc sao tu robot.yaml luc nap
|
|
// config -- robot.yaml la nguon duy nhat cho hinh hoc.
|
|
zlac_ros::KinematicsConfig kc;
|
|
kc.wheel_diameter_m = cfg_.wheel_radius * 2.0;
|
|
kc.wheel_base_m = cfg_.wheel_separation;
|
|
kc.invert_left_wheel = false;
|
|
kc.invert_right_wheel = true; // mac dinh cua base_kit cho con robot nay
|
|
kin_ = std::make_unique<zlac_ros::DifferentialDriveKinematics>(kc);
|
|
|
|
impl_ = std::make_unique<zlac_ros::ZlacMotorDriver>(
|
|
cfg_.can_channel, cfg_.can_node_id, cfg_.dcf_path);
|
|
|
|
if (!impl_->initMaster()) {
|
|
impl_.reset();
|
|
return StatusResponse::Error(
|
|
StatusCode::kUnavailable,
|
|
"base: khong mo duoc CANopen master tren " + cfg_.can_channel +
|
|
".\n - `ip link show " + cfg_.can_channel + "` co UP khong?"
|
|
"\n - co tien trinh khac dang giu bus khong? "
|
|
"(systemctl status motor_control zlac_ros)"
|
|
"\n - dcf_path: " + cfg_.dcf_path);
|
|
}
|
|
if (!impl_->enableHardware(cfg_.accel_ramp_ms)) {
|
|
impl_.reset();
|
|
return StatusResponse::Error(
|
|
StatusCode::kUnavailable,
|
|
"base: enableHardware() that bai -- khong vao duoc Profile Velocity "
|
|
"Mode.\n - can_node_id dang la " +
|
|
std::to_string(cfg_.can_node_id) +
|
|
", co dung khong?\n - driver motor da co dien chua?");
|
|
}
|
|
|
|
VSLAM_INFO("base: ZLAC8015D tren " << cfg_.can_channel << " node "
|
|
<< static_cast<int>(cfg_.can_node_id) << ", banh r="
|
|
<< cfg_.wheel_radius << " m cach nhau " << cfg_.wheel_separation
|
|
<< " m, " << counts_per_rev_ << " count/vong, ramp "
|
|
<< cfg_.accel_ramp_ms << " ms");
|
|
|
|
running_ = true;
|
|
poll_thread_ = std::thread([this] { PollLoop(); });
|
|
return StatusResponse::Ok();
|
|
}
|
|
|
|
void Close() override {
|
|
running_ = false;
|
|
if (poll_thread_.joinable()) poll_thread_.join();
|
|
if (impl_) {
|
|
// disableHardware() tat power stage va gui NMT STOP. Goi TRUOC khi huy
|
|
// object: destructor cua no cung goi, nhung goi tuong minh o day thi
|
|
// thu tu tat chac chan, khong phu thuoc luc nao unique_ptr bi huy.
|
|
impl_->disableHardware();
|
|
impl_.reset();
|
|
}
|
|
kin_.reset();
|
|
}
|
|
|
|
void SetVelocity(double linear, double angular) override {
|
|
// Kep o day la CHAN CUOI, doc lap voi lop safety va deadman cua teleop.
|
|
linear = Clamp(linear, cfg_.max_linear);
|
|
angular = Clamp(angular, cfg_.max_angular);
|
|
|
|
std::lock_guard<std::mutex> lk(cmd_mu_);
|
|
cmd_linear_ = linear;
|
|
cmd_angular_ = angular;
|
|
last_cmd_ = clock_->Now();
|
|
have_cmd_ = true;
|
|
}
|
|
|
|
DriverStats Stats() const override {
|
|
std::lock_guard<std::mutex> lk(stats_mu_);
|
|
return stats_;
|
|
}
|
|
|
|
private:
|
|
static double Clamp(double v, double lim) {
|
|
if (!(lim > 0.0)) return v;
|
|
return (v > lim) ? lim : ((v < -lim) ? -lim : v);
|
|
}
|
|
|
|
void PollLoop() {
|
|
const double period = (cfg_.rate_hz > 0.0) ? 1.0 / cfg_.rate_hz : 0.02;
|
|
while (running_) {
|
|
PushVelocity();
|
|
ReadEncoders();
|
|
std::this_thread::sleep_for(std::chrono::duration<double>(period));
|
|
}
|
|
// Ra khoi vong thi dung xe, du vi ly do gi.
|
|
if (impl_) impl_->setTargetRPM(0, 0);
|
|
}
|
|
|
|
void PushVelocity() {
|
|
double v = 0.0, w = 0.0;
|
|
{
|
|
std::lock_guard<std::mutex> lk(cmd_mu_);
|
|
const double age = have_cmd_ ? (clock_->Now() - last_cmd_).toSec() : 1e9;
|
|
// Watchdog: khong nhan lenh trong cmd_timeout_sec thi TU DUNG. Chan cuoi
|
|
// cung, doc lap voi lop safety va deadman cua teleop.
|
|
if (age <= cfg_.cmd_timeout_sec) {
|
|
v = cmd_linear_;
|
|
w = cmd_angular_;
|
|
} else if (have_cmd_) {
|
|
VSLAM_WARN_THROTTLE(2.0,
|
|
"base: khong co cmd trong " << age << " s -- dung motor");
|
|
}
|
|
}
|
|
if (!impl_) return;
|
|
const zlac_ros::WheelSpeedRPM rpm = kin_->computeInverseKinematics(v, w);
|
|
impl_->setTargetRPM(rpm.left, rpm.right);
|
|
}
|
|
|
|
void ReadEncoders() {
|
|
if (!impl_) return;
|
|
|
|
int32_t l = 0, r = 0;
|
|
double skew = 0.0, age = 0.0;
|
|
uint64_t seq = 0;
|
|
EncoderReading out;
|
|
if (!impl_->getPositionCounts(l, r, &skew, &seq, &age)) {
|
|
out.stamp = clock_->Now();
|
|
out.valid = false;
|
|
{
|
|
std::lock_guard<std::mutex> lk(stats_mu_);
|
|
++stats_.errors;
|
|
stats_.connected = false;
|
|
stats_.last_error = "chua co vi tri tu 0x6064";
|
|
}
|
|
if (cb_) cb_(out);
|
|
return;
|
|
}
|
|
// ⚠️ BO QUA mau KHONG DOI.
|
|
//
|
|
// telemetryLoop cua driver cap nhat cache o 50 Hz, va vong poll nay cung
|
|
// 50 Hz. Hai vong doc lap cung tan so bi NHIEU PHA: co luc hai lan poll
|
|
// thay cung mot gia tri -> van toc ra 0; co luc mot lan poll nuot hai lan
|
|
// cap nhat -> van toc gap doi. Da do tren robot: cach mot lai ra
|
|
// "encoder 0.25 / gyro 0" roi "encoder 0 / gyro 0.7", xen ke -- va
|
|
// wheel_odometry doc ca hai thanh TRUOT BANH.
|
|
//
|
|
// Chi phat khi `seq` doi, tuc khi thuc su co mau moi.
|
|
if (seq == last_seq_) return;
|
|
last_seq_ = seq;
|
|
|
|
// Dong dau theo luc LAY MAU, khong phai luc doc cache: tru tuoi cua mau.
|
|
out.stamp = clock_->Now() - Duration::fromSec(age);
|
|
|
|
if (!have_origin_) {
|
|
// Tru moc dau tien de pose bat dau tu 0 thay vi tu mot so tuy y con lai
|
|
// tu lan chay truoc.
|
|
origin_l_ = l;
|
|
origin_r_ = r;
|
|
have_origin_ = true;
|
|
}
|
|
|
|
const double scale = kTwoPi / static_cast<double>(counts_per_rev_);
|
|
double left_counts = static_cast<double>(l - origin_l_);
|
|
|
|
// ⚠️ BU DO LECH LAY MAU GIUA HAI BANH.
|
|
//
|
|
// Duong SDO doc hai banh bang hai giao dich tuan tu, nen banh PHAI duoc
|
|
// lay mau muon hon banh TRAI khoang `skew` giay. Cong thuc vi sai
|
|
// omega = (v_r - v_l) / L
|
|
// bien dung khoang lech do thanh QUAY GIA: o 0.3 m/s voi skew 5 ms, hai
|
|
// banh lech 1.5 mm, ra ~0.2 rad/s -- vua dung do lon cua canh bao
|
|
// "nghi TRUOT BANH" do duoc tren robot.
|
|
//
|
|
// Ngoai suy banh trai toi THOI DIEM cua banh phai bang chinh van toc gan
|
|
// nhat cua no, de hai gia tri cung mot moc thoi gian.
|
|
//
|
|
// Duong sua tan goc la map 0x6064:01 va :02 vao MOT TPDO (hai I32 = dung
|
|
// 8 byte CAN) -- luc do skew = 0 va khoi bu. Can khai bao mapping do
|
|
// trong master.dcf.
|
|
if (skew > 0.0 && have_prev_left_) {
|
|
const double dt = (out.stamp - prev_left_stamp_).toSec();
|
|
if (dt > 1e-4) {
|
|
const double v_counts = (left_counts - prev_left_counts_) / dt;
|
|
left_counts += v_counts * skew;
|
|
}
|
|
}
|
|
prev_left_counts_ = static_cast<double>(l - origin_l_);
|
|
prev_left_stamp_ = out.stamp;
|
|
have_prev_left_ = true;
|
|
|
|
out.left_rad = left_counts * scale;
|
|
// Banh phai lap doi chieu -- cung quy uoc voi KinematicsConfig o tren.
|
|
// Thieu phep doi dau nay thi robot di thang ma odometry bao dang quay.
|
|
out.right_rad = -static_cast<double>(r - origin_r_) * scale;
|
|
out.valid = true;
|
|
|
|
{
|
|
std::lock_guard<std::mutex> lk(stats_mu_);
|
|
++stats_.frames;
|
|
stats_.connected = !impl_->hasConnectionLost();
|
|
if (!last_enc_.isZero()) {
|
|
const double dt = (out.stamp - last_enc_).toSec();
|
|
if (dt > 0.0) stats_.hz = 1.0 / dt;
|
|
}
|
|
last_enc_ = out.stamp;
|
|
}
|
|
|
|
if (cb_) cb_(out);
|
|
}
|
|
|
|
BaseConfig cfg_;
|
|
ClockPtr clock_;
|
|
EncoderCallback cb_;
|
|
|
|
std::unique_ptr<zlac_ros::ZlacMotorDriver> impl_;
|
|
std::unique_ptr<zlac_ros::DifferentialDriveKinematics> kin_;
|
|
|
|
std::atomic<bool> running_{false};
|
|
std::thread poll_thread_;
|
|
|
|
uint32_t counts_per_rev_ = 0;
|
|
int32_t origin_l_ = 0, origin_r_ = 0;
|
|
bool have_origin_ = false;
|
|
UnixTime last_enc_;
|
|
// Mau truoc cua banh TRAI, de uoc van toc khi bu do lech lay mau.
|
|
double prev_left_counts_ = 0.0;
|
|
UnixTime prev_left_stamp_;
|
|
bool have_prev_left_ = false;
|
|
// Mau gan nhat da phat. Chi phat khi driver co mau MOI -- xem ReadEncoders.
|
|
uint64_t last_seq_ = 0;
|
|
|
|
mutable std::mutex cmd_mu_;
|
|
double cmd_linear_ = 0.0, cmd_angular_ = 0.0;
|
|
UnixTime last_cmd_;
|
|
bool have_cmd_ = false;
|
|
|
|
mutable std::mutex stats_mu_;
|
|
DriverStats stats_;
|
|
};
|
|
|
|
} // namespace
|
|
|
|
std::unique_ptr<BaseInterface> CreateDiffDriveBase(const BaseConfig& cfg,
|
|
ClockPtr clock) {
|
|
return std::make_unique<ZlacWrapper>(cfg, std::move(clock));
|
|
}
|
|
|
|
} // namespace vslam
|