update
This commit is contained in:
@@ -1,73 +1,40 @@
|
||||
// Base ZLAC8015D qua CANopen (lely-core).
|
||||
// Base ZLAC8015D -- LOP BOC quanh `ZlacMotorDriver` cua base_kit.
|
||||
//
|
||||
// ================== KIEN TRUC THAT KHAC DAC TA ==================
|
||||
// driver_config.h gia dinh encoder ve qua serial MCU (`E,<micros>,...`).
|
||||
// Tren robot nay KHONG PHAI VAY: encoder va motor deu di qua `can0`, DS402
|
||||
// Profile Velocity Mode. Nguon: base_kit/src/Zlac_ros, la code dang lai con
|
||||
// robot nay that.
|
||||
// Tren robot nay KHONG PHAI VAY: encoder va motor deu di qua `can0`, CANopen
|
||||
// DS402 Profile Velocity Mode.
|
||||
//
|
||||
// Hau qua truc tiep: khong co duong nao dong bo dong ho base voi dong ho host.
|
||||
// ClockSync chi bac cau duoc cho MCU serial. Stamp cua EncoderReading o day la
|
||||
// dong ho HOST luc doc xong SDO/PDO.
|
||||
// ClockSync chi bac cau duoc cho MCU serial. Stamp cua EncoderReading la dong
|
||||
// ho HOST luc doc xong cache telemetry.
|
||||
//
|
||||
// ================== OBJECT DICTIONARY DUNG O DAY ==================
|
||||
// 0x6060:0 i8 Modes of operation = 3 (Profile Velocity)
|
||||
// 0x6083/84 u32 Profile accel/decel (sub 1 = trai, 2 = phai)
|
||||
// 0x6040:0 u16 Controlword 6 -> 7 -> F -> 7F (chuoi DS402)
|
||||
// 0x60FF:3 u32 Target velocity GOP: 16 bit THAP = trai, CAO = phai
|
||||
// (ZLAC8015D manual p.19-20)
|
||||
// 0x606C:1/2 i32 Velocity actual, don vi r/min
|
||||
// 0x6064:1/2 i32 Position actual, don vi "count" <-- doc o day
|
||||
// 0x200E:1/2 u16 Encoder wire number (vung Factory Custom), mac dinh 1024
|
||||
// ================== VI SAO BOC CHU KHONG TU VIET ==================
|
||||
// Ban truoc cua file nay tu dieu khien lely. No chay duoc toi tan 0x6064,
|
||||
// nhung mat ba vong thu-sai cho nhung thu ban goc da biet: phai cho slave
|
||||
// BOOT xong roi moi gui SDO dau tien, thu tu chuoi DS402, va 0x608F khong
|
||||
// ton tai tren thiet bi nay.
|
||||
//
|
||||
// ⚠️ KHONG dung 0x608F (Position encoder resolution cua DS402). ZLAC8015D
|
||||
// KHONG co object do -- Appendix A liet ke day du dai CiA402 va no dung o
|
||||
// 6087h roi nhay thang toi 60FFh. So vong day encoder nam o 0x200E, trong
|
||||
// vung rieng cua nha san xuat.
|
||||
// `ZlacMotorDriver` la ban CHUAN dang lai con robot nay. Xem
|
||||
// thirdparty/PROVENANCE.md.
|
||||
//
|
||||
// ================== VI SAO DOC 0x6064 CHU KHONG TICH PHAN RPM ==================
|
||||
// `EncoderReading` yeu cau GOC QUAY TICH LUY, khong phai van toc. Ly do nam o
|
||||
// mcu_protocol.h: "Dung gui delta -- mat mot dong serial la mat vinh vien mot
|
||||
// doan quang duong, va khong co cach nao phat hien." Tich phan RPM co dung
|
||||
// benh do: moi lan lo mot mau telemetry la mat han mot doan duong, va sai so
|
||||
// do KHONG BAO GIO duoc sua -- no cong don vao pose mai mai.
|
||||
//
|
||||
// base_kit hien tich phan RPM (Euler/mid-point trong
|
||||
// differential_drive_kinematics.cpp). Doc 0x6064 thay the: bo dem tuyet doi
|
||||
// trong driver motor, lo mot mau thi mau sau van dung vi no la TICH LUY.
|
||||
//
|
||||
// DA XAC MINH TRONG TAI LIEU: can_help.pdf (ZLAC8015DD CANopen Communication
|
||||
// Routine V1.0) Appendix A ghi ro:
|
||||
// 6064h :01 Position_actual_value (left) I32 RO "unit: count"
|
||||
// :02 Position_actual_value (right) I32 RO
|
||||
// Open() van doc thu mot lan: neu vi ly do gi no khong tra loi thi phai biet
|
||||
// NGAY, chu khong phai sau nua gio thay pose dung yen o goc 0 -- trieu chung
|
||||
// do trong het nhu "odometry chet" va rat kho lan ra.
|
||||
//
|
||||
// ================== BUILD ==================
|
||||
// Can liblely-coapp. Tat bang -DVSLAM_WITH_CANOPEN=OFF thi file nay khong
|
||||
// duoc bien dich va CreateDiffDriveBase tra ve driver bao kUnavailable --
|
||||
// cung ly do voi realsense: may CI khong co SDK phan cung van phai build duoc.
|
||||
// ================== MOT CHO DA SUA TRONG BAN NHUNG ==================
|
||||
// Ban goc chi co `getActualRPM()` -- tuc chi co VAN TOC. `EncoderReading` can
|
||||
// GOC QUAY TICH LUY: tich phan van toc thi lo mot mau telemetry la mat vinh
|
||||
// vien mot doan quang duong va khong co cach nao phat hien (mcu_protocol.h).
|
||||
// Da them `getPositionCounts()` doc 0x6064 -- bo dem TUYET DOI trong driver
|
||||
// motor, lo mau khong mat gi.
|
||||
|
||||
#include <lely/coapp/master.hpp>
|
||||
#include <lely/coapp/driver.hpp>
|
||||
#include <lely/ev/loop.hpp>
|
||||
#include <lely/io2/linux/can.hpp>
|
||||
#include <lely/io2/posix/poll.hpp>
|
||||
#include <lely/io2/sys/io.hpp>
|
||||
#include <lely/io2/sys/timer.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include "zlac_ros/differential_drive_kinematics.hpp"
|
||||
#include "zlac_ros/zlac_motor_driver.hpp"
|
||||
|
||||
#include "vslam/clock.h"
|
||||
#include "vslam/driver_config.h"
|
||||
#include "vslam/driver_interfaces.h"
|
||||
@@ -78,82 +45,30 @@ namespace {
|
||||
|
||||
constexpr double kTwoPi = 2.0 * M_PI;
|
||||
|
||||
template <typename T>
|
||||
bool SdoWrite(lely::canopen::AsyncMaster& m, uint8_t node, uint16_t idx,
|
||||
uint8_t sub, T val) {
|
||||
std::promise<bool> prom;
|
||||
auto fut = prom.get_future();
|
||||
m.SubmitWrite(m.get_executor(), node, idx, sub, val,
|
||||
[&prom](uint8_t, uint16_t, uint8_t, std::error_code ec) {
|
||||
prom.set_value(!ec);
|
||||
});
|
||||
return fut.wait_for(std::chrono::seconds(2)) == std::future_status::ready &&
|
||||
fut.get();
|
||||
}
|
||||
// 0x200E:01 tren thiet bi nay doc ra 4096 "wire". Quy uoc cau phuong pho bien
|
||||
// cho 4 count moi wire.
|
||||
//
|
||||
// ⚠️ CHUA KIEM CHUNG: can_help.pdf goi 0x200E la "wire number" va don vi cua
|
||||
// 0x6064 la "count", khong cho nao trong 37 trang noi he so giua hai cai.
|
||||
// Sai he so nay lam odometry sai dung 4 lan. Do (2 phut): ke banh len, doc
|
||||
// 0x6064:01, quay banh mot vong bang tay, doc lai, lay hieu -- roi dat vao
|
||||
// `base.encoder_counts_per_rev` de khong con phai doan.
|
||||
constexpr uint32_t kDefaultCountsPerRev = 4096 * 4;
|
||||
|
||||
template <typename T>
|
||||
std::optional<T> SdoRead(lely::canopen::AsyncMaster& m, uint8_t node,
|
||||
uint16_t idx, uint8_t sub) {
|
||||
std::promise<std::optional<T>> prom;
|
||||
auto fut = prom.get_future();
|
||||
m.SubmitRead<T>(m.get_executor(), node, idx, sub,
|
||||
[&prom](uint8_t, uint16_t, uint8_t, std::error_code ec, T v) {
|
||||
prom.set_value(ec ? std::nullopt : std::optional<T>(v));
|
||||
});
|
||||
if (fut.wait_for(std::chrono::seconds(2)) != std::future_status::ready) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return fut.get();
|
||||
}
|
||||
|
||||
class ZlacBase;
|
||||
|
||||
// Tin hieu "slave da boot xong", chia se giua bridge va driver.
|
||||
struct BootGate {
|
||||
std::mutex mu;
|
||||
std::condition_variable cv;
|
||||
bool booted = false;
|
||||
};
|
||||
|
||||
class LelyBridge : public lely::canopen::BasicDriver {
|
||||
class ZlacWrapper : public BaseInterface {
|
||||
public:
|
||||
LelyBridge(lely::canopen::AsyncMaster& m, uint8_t id, std::atomic<bool>* lost,
|
||||
BootGate* gate)
|
||||
: BasicDriver(m, id), lost_(lost), gate_(gate) {}
|
||||
|
||||
protected:
|
||||
void OnBoot(lely::canopen::NmtState, char, const std::string&) noexcept override {
|
||||
master.Command(lely::canopen::NmtCommand::START, id());
|
||||
if (gate_) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(gate_->mu);
|
||||
gate_->booted = true;
|
||||
}
|
||||
gate_->cv.notify_all();
|
||||
}
|
||||
}
|
||||
void OnHeartbeat(bool occurred) noexcept override {
|
||||
if (lost_) lost_->store(occurred);
|
||||
if (occurred) {
|
||||
VSLAM_ERROR("base: mat heartbeat CANopen node " << static_cast<int>(id()));
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::atomic<bool>* lost_ = nullptr;
|
||||
BootGate* gate_ = nullptr;
|
||||
};
|
||||
|
||||
class ZlacBase : public BaseInterface {
|
||||
public:
|
||||
ZlacBase(const BaseConfig& cfg, ClockPtr clock)
|
||||
ZlacWrapper(const BaseConfig& cfg, ClockPtr clock)
|
||||
: cfg_(cfg), clock_(std::move(clock)) {}
|
||||
|
||||
~ZlacBase() override { Close(); }
|
||||
~ZlacWrapper() override { Close(); }
|
||||
|
||||
void SetEncoderCallback(EncoderCallback cb) override { cb_ = std::move(cb); }
|
||||
|
||||
StatusResponse Open() override {
|
||||
if (impl_) {
|
||||
return StatusResponse::Error(StatusCode::kFailedPrecondition,
|
||||
"base: da mo roi");
|
||||
}
|
||||
if (!clock_) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"base: thieu clock");
|
||||
@@ -161,43 +76,60 @@ class ZlacBase : public BaseInterface {
|
||||
if (cfg_.dcf_path.empty()) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"base: thieu dcf_path. lely can file master.dcf sinh bang `dcfgen` "
|
||||
"-- xem base_kit/src/Zlac_ros/config/master.yml");
|
||||
"base: thieu dcf_path. lely can file master.dcf sinh bang `dcfgen`.");
|
||||
}
|
||||
if (!(cfg_.wheel_radius > 0.0) || !(cfg_.wheel_separation > 0.0)) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"base: wheel_radius / wheel_separation <= 0");
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"base: wheel_radius / wheel_separation <= 0");
|
||||
}
|
||||
|
||||
try {
|
||||
io_guard_ = std::make_unique<lely::io::IoGuard>();
|
||||
ctx_ = std::make_unique<lely::io::Context>();
|
||||
poll_ = std::make_unique<lely::io::Poll>(*ctx_);
|
||||
loop_ = std::make_unique<lely::ev::Loop>(poll_->get_poll());
|
||||
auto exec = loop_->get_executor();
|
||||
timer_ = std::make_unique<lely::io::Timer>(*poll_, exec, CLOCK_MONOTONIC);
|
||||
ctrl_ = std::make_unique<lely::io::CanController>(cfg_.can_channel.c_str());
|
||||
chan_ = std::make_unique<lely::io::CanChannel>(*poll_, exec);
|
||||
chan_->open(*ctrl_);
|
||||
master_ = std::make_unique<lely::canopen::AsyncMaster>(
|
||||
*timer_, *chan_, cfg_.dcf_path, "", 127);
|
||||
bridge_ = std::make_unique<LelyBridge>(*master_, cfg_.can_node_id, &lost_,
|
||||
&boot_);
|
||||
master_->Reset();
|
||||
lely_thread_ = std::thread([this] {
|
||||
try { loop_->run(); } catch (...) {}
|
||||
});
|
||||
} catch (const std::exception& e) {
|
||||
counts_per_rev_ = cfg_.encoder_counts_per_rev != 0
|
||||
? cfg_.encoder_counts_per_rev
|
||||
: kDefaultCountsPerRev;
|
||||
if (cfg_.encoder_counts_per_rev == 0) {
|
||||
VSLAM_WARN("base: encoder_counts_per_rev chua dat, dung mac dinh "
|
||||
<< counts_per_rev_ << " (4096 wire x 4 cau phuong, CHUA kiem "
|
||||
"chung). Sai he so nay lam odometry sai 4 lan -- do bang cach "
|
||||
"quay banh mot vong roi so hieu 0x6064.");
|
||||
}
|
||||
|
||||
// Hinh hoc lay tu BaseConfig, ma no da duoc sao tu robot.yaml luc nap
|
||||
// config -- robot.yaml la nguon duy nhat cho hinh hoc.
|
||||
zlac_ros::KinematicsConfig kc;
|
||||
kc.wheel_diameter_m = cfg_.wheel_radius * 2.0;
|
||||
kc.wheel_base_m = cfg_.wheel_separation;
|
||||
kc.invert_left_wheel = false;
|
||||
kc.invert_right_wheel = true; // mac dinh cua base_kit cho con robot nay
|
||||
kin_ = std::make_unique<zlac_ros::DifferentialDriveKinematics>(kc);
|
||||
|
||||
impl_ = std::make_unique<zlac_ros::ZlacMotorDriver>(
|
||||
cfg_.can_channel, cfg_.can_node_id, cfg_.dcf_path);
|
||||
|
||||
if (!impl_->initMaster()) {
|
||||
impl_.reset();
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kUnavailable,
|
||||
"base: khong mo duoc CANopen tren " + cfg_.can_channel + ": " +
|
||||
e.what() + " -- `ip link show " + cfg_.can_channel + "` co UP khong?");
|
||||
"base: khong mo duoc CANopen master tren " + cfg_.can_channel +
|
||||
".\n - `ip link show " + cfg_.can_channel + "` co UP khong?"
|
||||
"\n - co tien trinh khac dang giu bus khong? "
|
||||
"(systemctl status motor_control zlac_ros)"
|
||||
"\n - dcf_path: " + cfg_.dcf_path);
|
||||
}
|
||||
if (!impl_->enableHardware()) {
|
||||
impl_.reset();
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kUnavailable,
|
||||
"base: enableHardware() that bai -- khong vao duoc Profile Velocity "
|
||||
"Mode.\n - can_node_id dang la " +
|
||||
std::to_string(cfg_.can_node_id) +
|
||||
", co dung khong?\n - driver motor da co dien chua?");
|
||||
}
|
||||
|
||||
if (StatusResponse st = WaitForBoot(); !st.ok()) return st;
|
||||
if (StatusResponse st = ProbeIdentity(); !st.ok()) return st;
|
||||
if (StatusResponse st = EnableDs402(); !st.ok()) return st;
|
||||
if (StatusResponse st = ResolveEncoderScale(); !st.ok()) return st;
|
||||
VSLAM_INFO("base: ZLAC8015D tren " << cfg_.can_channel << " node "
|
||||
<< static_cast<int>(cfg_.can_node_id) << ", banh r="
|
||||
<< cfg_.wheel_radius << " m cach nhau " << cfg_.wheel_separation
|
||||
<< " m, " << counts_per_rev_ << " count/vong");
|
||||
|
||||
running_ = true;
|
||||
poll_thread_ = std::thread([this] { PollLoop(); });
|
||||
@@ -207,50 +139,26 @@ class ZlacBase : public BaseInterface {
|
||||
void Close() override {
|
||||
running_ = false;
|
||||
if (poll_thread_.joinable()) poll_thread_.join();
|
||||
|
||||
// Tat power stage TRUOC khi go master: huy master truoc thi lenh dung
|
||||
// khong bao gio toi duoc motor, va xe chay tiep voi target cuoi cung.
|
||||
if (master_ && ready_) {
|
||||
SdoWrite<uint16_t>(*master_, cfg_.can_node_id, 0x6040, 0, 0x0006);
|
||||
ready_ = false;
|
||||
if (impl_) {
|
||||
// disableHardware() tat power stage va gui NMT STOP. Goi TRUOC khi huy
|
||||
// object: destructor cua no cung goi, nhung goi tuong minh o day thi
|
||||
// thu tu tat chac chan, khong phu thuoc luc nao unique_ptr bi huy.
|
||||
impl_->disableHardware();
|
||||
impl_.reset();
|
||||
}
|
||||
if (loop_) loop_->stop();
|
||||
if (lely_thread_.joinable()) lely_thread_.join();
|
||||
|
||||
bridge_.reset(); master_.reset(); chan_.reset(); ctrl_.reset();
|
||||
timer_.reset(); loop_.reset(); poll_.reset(); ctx_.reset(); io_guard_.reset();
|
||||
kin_.reset();
|
||||
}
|
||||
|
||||
void SetVelocity(double linear, double angular) override {
|
||||
// Kep o day la CHAN CUOI, doc lap voi lop safety va voi deadman teleop.
|
||||
// Kep o day la CHAN CUOI, doc lap voi lop safety va deadman cua teleop.
|
||||
linear = Clamp(linear, cfg_.max_linear);
|
||||
angular = Clamp(angular, cfg_.max_angular);
|
||||
|
||||
const double half = cfg_.wheel_separation * 0.5;
|
||||
const double v_l = linear - angular * half; // m/s tai banh
|
||||
const double v_r = linear + angular * half;
|
||||
|
||||
// m/s -> rad/s tai banh -> RPM
|
||||
double rpm_l = (v_l / cfg_.wheel_radius) * 60.0 / kTwoPi;
|
||||
double rpm_r = (v_r / cfg_.wheel_radius) * 60.0 / kTwoPi;
|
||||
|
||||
// 0x60FF nhan -1000..1000 r/min (can_help.pdf Appendix A). Gioi han thuc
|
||||
// te thap hon nhieu -- max_linear 0.35 m/s voi r=0.0865 chi ra ~39 RPM --
|
||||
// nhung kep o day de mot config sai khong bao gio gui duoc gia tri ma
|
||||
// driver se tu dien giai lai.
|
||||
constexpr double kMaxRpm = 1000.0;
|
||||
rpm_l = Clamp(rpm_l, kMaxRpm);
|
||||
rpm_r = Clamp(rpm_r, kMaxRpm);
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(cmd_mu_);
|
||||
target_l_ = static_cast<int16_t>(std::lround(rpm_l));
|
||||
// Banh phai lap doi chieu -- base_kit KinematicsConfig::invert_right_wheel
|
||||
// mac dinh true. Sai dau o day thi robot quay tai cho thay vi di thang.
|
||||
target_r_ = static_cast<int16_t>(std::lround(-rpm_r));
|
||||
last_cmd_ = clock_->Now();
|
||||
have_cmd_ = true;
|
||||
}
|
||||
std::lock_guard<std::mutex> lk(cmd_mu_);
|
||||
cmd_linear_ = linear;
|
||||
cmd_angular_ = angular;
|
||||
last_cmd_ = clock_->Now();
|
||||
have_cmd_ = true;
|
||||
}
|
||||
|
||||
DriverStats Stats() const override {
|
||||
@@ -264,270 +172,75 @@ class ZlacBase : public BaseInterface {
|
||||
return (v > lim) ? lim : ((v < -lim) ? -lim : v);
|
||||
}
|
||||
|
||||
// Cho slave BOOT XONG truoc khi gui SDO dau tien.
|
||||
//
|
||||
// ⚠️ Day la loi that, do duoc tren robot: ban dau Open() goi thang
|
||||
// ProbeIdentity() ngay sau master_->Reset(). SDO dau tien di ra sau 116 ms
|
||||
// va KHONG AI TRA LOI -- slave chua kip boot. Doc log thi trong y het
|
||||
// "thiet bi khong ho tro object do", va da dan chan doan di sai huong hai
|
||||
// lan.
|
||||
//
|
||||
// base_kit khong gap loi nay nhung cung khong xu ly no: no co mot ROS timer
|
||||
// 500 ms goi lai enableHardware() cho toi khi duoc, nen boot xong luc nao
|
||||
// thi tinh co vua dung luc do. Doi day dung tin hieu that -- callback
|
||||
// OnBoot cua lely -- thay vi ngu mot khoang co dinh doan mo.
|
||||
StatusResponse WaitForBoot() {
|
||||
constexpr auto kTimeout = std::chrono::seconds(5);
|
||||
std::unique_lock<std::mutex> lk(boot_.mu);
|
||||
if (boot_.cv.wait_for(lk, kTimeout, [this] { return boot_.booted; })) {
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kTimeout,
|
||||
"base: node " + std::to_string(cfg_.can_node_id) +
|
||||
" khong boot trong 5 s (khong co callback OnBoot cua lely).\n"
|
||||
" - master.dcf co khai bao dung node nay khong? lely chi boot "
|
||||
"nhung slave co trong DCF.\n"
|
||||
" - driver motor da co dien chua?\n"
|
||||
" - `candump can0` co thay khung 0x70" +
|
||||
std::to_string(cfg_.can_node_id) + " (heartbeat) khong?");
|
||||
}
|
||||
|
||||
// Hoi 0x1018:01 (Vendor-ID) TRUOC moi thu khac.
|
||||
//
|
||||
// Object nay BAT BUOC voi moi thiet bi CANopen -- no nam trong Identity
|
||||
// Object cua DS301, khong phai mo rong cua nha san xuat. Neu no khong tra
|
||||
// loi thi van de la SDO/CAN, KHONG phai chuyen thiet bi thieu object nay no.
|
||||
//
|
||||
// Tach ra thanh mot buoc rieng vi bai hoc that: lan chay dau tren robot,
|
||||
// 0x608F:1 khong tra loi va thong bao loi khi do noi "thiet bi khong tra loi
|
||||
// 0x608F" -- doc len tuong nhu ZLAC khong ho tro object do. Nhung log cua
|
||||
// lely cho thay 1018:01 CUNG abort, tuc SDO hong tu goc. Chan doan sai huong
|
||||
// ton nhieu thoi gian hon la mot thong bao chung chung.
|
||||
StatusResponse ProbeIdentity() {
|
||||
// Thu NHIEU object, khong chi 0x1018.
|
||||
//
|
||||
// can_help.pdf Appendix A xac nhan 0x1018:01 CO ton tai (Vendor Id =
|
||||
// 0x0100), nen lan hong tren robot khong phai vi thieu object ma vi hoi
|
||||
// qua som -- WaitForBoot() o tren la cho sua that su.
|
||||
//
|
||||
// Van giu ca ba lan thu: chung re, va neu mot firmware ZLAC khac bo trong
|
||||
// Identity Object thi 0x606C/0x6060 van cho di tiep. 0x606C la object
|
||||
// base_kit doc thanh cong moi 20 ms nen no chac chan co.
|
||||
if (SdoRead<uint32_t>(*master_, cfg_.can_node_id, 0x1018, 1)) {
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
VSLAM_WARN("base: node " << static_cast<int>(cfg_.can_node_id)
|
||||
<< " khong tra loi 0x1018:01 (Identity). Thu 0x606C...");
|
||||
if (SdoRead<int32_t>(*master_, cfg_.can_node_id, 0x606C, 1)) {
|
||||
VSLAM_WARN("base: 0x606C tra loi -- SDO thong, thiet bi chi thieu "
|
||||
"Identity Object. Di tiep.");
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
if (SdoRead<int8_t>(*master_, cfg_.can_node_id, 0x6060, 0)) {
|
||||
VSLAM_WARN("base: 0x6060 tra loi -- SDO thong. Di tiep.");
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kUnavailable,
|
||||
"base: node " + std::to_string(cfg_.can_node_id) +
|
||||
" khong tra loi BAT KY object nao trong ba thu: 0x1018:01 "
|
||||
"(Identity), 0x606C:1 (velocity actual), 0x6060:0 (mode). "
|
||||
"base_kit doc duoc hai cai sau moi 20 ms tren cung con driver, "
|
||||
"nen neu ca ba deu im thi van de o duong truyen chu khong o thiet "
|
||||
"bi. Kiem theo thu tu:\n"
|
||||
" 1. Co tien trinh khac dang giu bus khong? base_kit co "
|
||||
"zlac_ros.service va motor_control.service -- hai CANopen master "
|
||||
"tren cung mot bus cho ra dung trieu chung nay.\n"
|
||||
" systemctl status zlac_ros motor_control\n"
|
||||
" 2. Bitrate cua " + cfg_.can_channel + " co khop driver khong?\n"
|
||||
" ip -details link show " + cfg_.can_channel + "\n"
|
||||
" 3. can_node_id dang la " + std::to_string(cfg_.can_node_id) +
|
||||
" -- co dung khong?\n"
|
||||
" 4. Driver motor da co dien chua? (NMT len duoc operational "
|
||||
"khong co nghia la slave dang song)");
|
||||
}
|
||||
|
||||
StatusResponse EnableDs402() {
|
||||
master_->Command(lely::canopen::NmtCommand::START, cfg_.can_node_id);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
||||
|
||||
bool mode_ok = false;
|
||||
for (int attempt = 0; attempt < 3 && !mode_ok; ++attempt) {
|
||||
mode_ok = SdoWrite<int8_t>(*master_, cfg_.can_node_id, 0x6060, 0, 3);
|
||||
if (!mode_ok) std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
||||
}
|
||||
if (!mode_ok) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kUnavailable,
|
||||
"base: khong dat duoc Profile Velocity Mode (0x6060:0 = 3). Driver "
|
||||
"co dang bat nguon va dung node_id " +
|
||||
std::to_string(cfg_.can_node_id) + " khong?");
|
||||
}
|
||||
|
||||
const uint32_t acc = 500;
|
||||
SdoWrite<uint32_t>(*master_, cfg_.can_node_id, 0x6083, 1, acc);
|
||||
SdoWrite<uint32_t>(*master_, cfg_.can_node_id, 0x6083, 2, acc);
|
||||
SdoWrite<uint32_t>(*master_, cfg_.can_node_id, 0x6084, 1, acc);
|
||||
SdoWrite<uint32_t>(*master_, cfg_.can_node_id, 0x6084, 2, acc);
|
||||
|
||||
// Chuoi chuyen trang thai DS402. Bo qua mot buoc thi power stage khong
|
||||
// bao gio bat, va trieu chung la "gui lenh nhung xe khong nhuc nhich".
|
||||
for (uint16_t cw : {0x0006, 0x0007, 0x000F, 0x007F}) {
|
||||
if (!SdoWrite<uint16_t>(*master_, cfg_.can_node_id, 0x6040, 0, cw)) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kUnavailable,
|
||||
"base: chuoi DS402 dung o controlword 0x" + ToHex(cw));
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
}
|
||||
ready_ = true;
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
// Quyet dinh so increment/vong, va CHUNG MINH 0x6064 doc duoc.
|
||||
StatusResponse ResolveEncoderScale() {
|
||||
counts_per_rev_ = cfg_.encoder_counts_per_rev;
|
||||
if (counts_per_rev_ == 0) {
|
||||
// ⚠️ KHONG phai 0x608F. Object do la chuan DS402 (Position encoder
|
||||
// resolution) nhung ZLAC8015D KHONG co no -- Appendix A cua
|
||||
// can_help.pdf liet ke day du dai CiA402 va no dung o 6087h roi nhay
|
||||
// thang toi 60FFh. Doc 0x608F se abort mai mai.
|
||||
//
|
||||
// So vong day cua encoder nam trong vung Factory Custom: 0x200E:01
|
||||
// (trai) / :02 (phai), "Encoder wire number setting", 0-4096, mac dinh
|
||||
// 1024.
|
||||
const auto lines =
|
||||
SdoRead<uint16_t>(*master_, cfg_.can_node_id, 0x200E, 1);
|
||||
if (!lines || *lines == 0) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kFailedPrecondition,
|
||||
"base: khong doc duoc 0x200E:01 (Encoder wire number) va "
|
||||
"encoder_counts_per_rev trong config dang la 0. Mac dinh cua "
|
||||
"ZLAC8015D la 1024 -- dat tuong minh roi chay lai.");
|
||||
}
|
||||
|
||||
// ⚠️ GIA DINH CHUA KIEM CHUNG: counts = lines x 4 (giai ma cau phuong).
|
||||
//
|
||||
// Tai lieu goi 0x200E la "wire number" (so vong day) va goi don vi cua
|
||||
// 0x6064 la "count". Hai ten khac nhau, va khong cho nao trong 37 trang
|
||||
// noi he so giua chung. Suy doan x4 la quy uoc pho bien nhat, nhung no
|
||||
// VAN LA SUY DOAN.
|
||||
//
|
||||
// Sai he so nay lam odometry sai dung 4 lan -- de thay, nhung van nen
|
||||
// do cho chac. Cach do (2 phut):
|
||||
// 1. Ke banh len khoi san
|
||||
// 2. Doc 0x6064:01, quay banh dung MOT vong bang tay, doc lai
|
||||
// 3. Hieu so chinh la counts/vong that
|
||||
// 4. Dat vao sensors.yaml: base.encoder_counts_per_rev
|
||||
counts_per_rev_ = static_cast<uint32_t>(*lines) * 4u;
|
||||
VSLAM_WARN("base: 0x200E:01 = " << *lines << " wire, SUY RA "
|
||||
<< counts_per_rev_ << " counts/vong (gia dinh x4 cau phuong, "
|
||||
"CHUA kiem chung). Sai he so nay lam odometry sai 4 lan -- do "
|
||||
"bang cach quay banh mot vong roi so hieu 0x6064, va dat vao "
|
||||
"base.encoder_counts_per_rev.");
|
||||
}
|
||||
|
||||
// 0x6064 la tru cot cua ca thiet ke nay, va can_help.pdf Appendix A xac
|
||||
// nhan no CO:
|
||||
// 6064h :01 Position_actual_value (left) I32 RO "unit: count"
|
||||
// :02 Position_actual_value (right) I32 RO
|
||||
// Van kiem luc Open(): neu vi ly do gi no khong tra loi thi phai biet
|
||||
// NGAY, chu khong phai sau nua gio thay robot dung yen o goc 0.
|
||||
const auto l = SdoRead<int32_t>(*master_, cfg_.can_node_id, 0x6064, 1);
|
||||
const auto r = SdoRead<int32_t>(*master_, cfg_.can_node_id, 0x6064, 2);
|
||||
if (!l || !r) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kFailedPrecondition,
|
||||
"base: ZLAC8015D khong tra loi 0x6064 (Position Actual Value), du "
|
||||
"can_help.pdf Appendix A liet ke no la I32 RO. Neu 0x606C doc duoc "
|
||||
"ma 0x6064 thi khong, kiem lai firmware driver motor.");
|
||||
}
|
||||
origin_l_ = *l;
|
||||
origin_r_ = *r;
|
||||
VSLAM_INFO("base: CANopen " << cfg_.can_channel << " node "
|
||||
<< static_cast<int>(cfg_.can_node_id) << ", "
|
||||
<< counts_per_rev_ << " increment/vong, 0x6064 OK");
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
static std::string ToHex(uint16_t v) {
|
||||
static const char* d = "0123456789ABCDEF";
|
||||
std::string s(4, '0');
|
||||
for (int i = 3; i >= 0; --i) { s[i] = d[v & 0xF]; v >>= 4; }
|
||||
return s;
|
||||
}
|
||||
|
||||
void PollLoop() {
|
||||
const double period = (cfg_.rate_hz > 0.0) ? 1.0 / cfg_.rate_hz : 0.02;
|
||||
while (running_) {
|
||||
PushVelocity();
|
||||
ReadEncoders();
|
||||
std::this_thread::sleep_for(
|
||||
std::chrono::duration<double>(period));
|
||||
std::this_thread::sleep_for(std::chrono::duration<double>(period));
|
||||
}
|
||||
// Ra khoi vong thi dung xe, du vi ly do gi.
|
||||
if (impl_) impl_->setTargetRPM(0, 0);
|
||||
}
|
||||
|
||||
void PushVelocity() {
|
||||
int16_t l = 0, r = 0;
|
||||
double v = 0.0, w = 0.0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(cmd_mu_);
|
||||
const double age = have_cmd_ ? (clock_->Now() - last_cmd_).toSec() : 1e9;
|
||||
// Watchdog: khong nhan lenh trong cmd_timeout_sec thi TU DUNG. Chan cuoi
|
||||
// cung, doc lap voi lop safety va deadman cua teleop.
|
||||
if (age <= cfg_.cmd_timeout_sec) {
|
||||
l = target_l_;
|
||||
r = target_r_;
|
||||
v = cmd_linear_;
|
||||
w = cmd_angular_;
|
||||
} else if (have_cmd_) {
|
||||
VSLAM_WARN_THROTTLE(2.0, "base: khong co cmd trong " << age
|
||||
<< " s -- dung motor");
|
||||
VSLAM_WARN_THROTTLE(2.0,
|
||||
"base: khong co cmd trong " << age << " s -- dung motor");
|
||||
}
|
||||
}
|
||||
|
||||
if (l == sent_l_ && r == sent_r_) return; // bot traffic CAN
|
||||
if (!master_ || !ready_) return;
|
||||
|
||||
const uint32_t combined = (static_cast<uint16_t>(l) & 0xFFFFu) |
|
||||
(static_cast<uint32_t>(static_cast<uint16_t>(r) & 0xFFFFu) << 16);
|
||||
master_->SubmitWrite(master_->get_executor(), cfg_.can_node_id, 0x60FF, 3,
|
||||
combined,
|
||||
[](uint8_t, uint16_t, uint8_t, std::error_code) {});
|
||||
sent_l_ = l;
|
||||
sent_r_ = r;
|
||||
if (!impl_) return;
|
||||
const zlac_ros::WheelSpeedRPM rpm = kin_->computeInverseKinematics(v, w);
|
||||
impl_->setTargetRPM(rpm.left, rpm.right);
|
||||
}
|
||||
|
||||
void ReadEncoders() {
|
||||
if (!master_) return;
|
||||
const auto l = SdoRead<int32_t>(*master_, cfg_.can_node_id, 0x6064, 1);
|
||||
const auto r = SdoRead<int32_t>(*master_, cfg_.can_node_id, 0x6064, 2);
|
||||
if (!impl_) return;
|
||||
|
||||
int32_t l = 0, r = 0;
|
||||
EncoderReading out;
|
||||
out.stamp = clock_->Now();
|
||||
if (!l || !r) {
|
||||
if (!impl_->getPositionCounts(l, r)) {
|
||||
out.stamp = clock_->Now();
|
||||
out.valid = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(stats_mu_);
|
||||
++stats_.errors;
|
||||
stats_.connected = false;
|
||||
stats_.last_error = "khong doc duoc 0x6064";
|
||||
stats_.last_error = "chua co vi tri tu 0x6064";
|
||||
}
|
||||
if (cb_) cb_(out);
|
||||
return;
|
||||
}
|
||||
out.stamp = clock_->Now();
|
||||
|
||||
if (!have_origin_) {
|
||||
// Tru moc dau tien de pose bat dau tu 0 thay vi tu mot so tuy y con lai
|
||||
// tu lan chay truoc.
|
||||
origin_l_ = l;
|
||||
origin_r_ = r;
|
||||
have_origin_ = true;
|
||||
}
|
||||
|
||||
// increment -> radian. Tru goc luc Open() de pose bat dau tu 0 thay vi
|
||||
// tu mot so tuy y con lai tu lan chay truoc.
|
||||
const double scale = kTwoPi / static_cast<double>(counts_per_rev_);
|
||||
out.left_rad = static_cast<double>(*l - origin_l_) * scale;
|
||||
// Cung phep doi dau voi lenh gui xuong -- neu khong thi robot di thang
|
||||
// ma odometry bao dang quay.
|
||||
out.right_rad = -static_cast<double>(*r - origin_r_) * scale;
|
||||
out.left_rad = static_cast<double>(l - origin_l_) * scale;
|
||||
// Banh phai lap doi chieu -- cung quy uoc voi KinematicsConfig o tren.
|
||||
// Thieu phep doi dau nay thi robot di thang ma odometry bao dang quay.
|
||||
out.right_rad = -static_cast<double>(r - origin_r_) * scale;
|
||||
out.valid = true;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(stats_mu_);
|
||||
++stats_.frames;
|
||||
stats_.connected = !lost_.load();
|
||||
stats_.connected = !impl_->hasConnectionLost();
|
||||
if (!last_enc_.isZero()) {
|
||||
const double dt = (out.stamp - last_enc_).toSec();
|
||||
if (dt > 0.0) stats_.hz = 1.0 / dt;
|
||||
@@ -542,30 +255,19 @@ class ZlacBase : public BaseInterface {
|
||||
ClockPtr clock_;
|
||||
EncoderCallback cb_;
|
||||
|
||||
std::unique_ptr<lely::io::IoGuard> io_guard_;
|
||||
std::unique_ptr<lely::io::Context> ctx_;
|
||||
std::unique_ptr<lely::io::Poll> poll_;
|
||||
std::unique_ptr<lely::ev::Loop> loop_;
|
||||
std::unique_ptr<lely::io::Timer> timer_;
|
||||
std::unique_ptr<lely::io::CanController> ctrl_;
|
||||
std::unique_ptr<lely::io::CanChannel> chan_;
|
||||
std::unique_ptr<lely::canopen::AsyncMaster> master_;
|
||||
std::unique_ptr<LelyBridge> bridge_;
|
||||
std::thread lely_thread_;
|
||||
std::unique_ptr<zlac_ros::ZlacMotorDriver> impl_;
|
||||
std::unique_ptr<zlac_ros::DifferentialDriveKinematics> kin_;
|
||||
|
||||
BootGate boot_;
|
||||
std::atomic<bool> running_{false};
|
||||
std::atomic<bool> lost_{false};
|
||||
bool ready_ = false;
|
||||
std::thread poll_thread_;
|
||||
|
||||
uint32_t counts_per_rev_ = 0;
|
||||
int32_t origin_l_ = 0, origin_r_ = 0;
|
||||
bool have_origin_ = false;
|
||||
UnixTime last_enc_;
|
||||
|
||||
std::mutex cmd_mu_;
|
||||
int16_t target_l_ = 0, target_r_ = 0;
|
||||
int16_t sent_l_ = 0, sent_r_ = 0;
|
||||
mutable std::mutex cmd_mu_;
|
||||
double cmd_linear_ = 0.0, cmd_angular_ = 0.0;
|
||||
UnixTime last_cmd_;
|
||||
bool have_cmd_ = false;
|
||||
|
||||
@@ -577,7 +279,7 @@ class ZlacBase : public BaseInterface {
|
||||
|
||||
std::unique_ptr<BaseInterface> CreateDiffDriveBase(const BaseConfig& cfg,
|
||||
ClockPtr clock) {
|
||||
return std::make_unique<ZlacBase>(cfg, std::move(clock));
|
||||
return std::make_unique<ZlacWrapper>(cfg, std::move(clock));
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
Reference in New Issue
Block a user