upload driver

This commit is contained in:
trung09122002
2026-09-19 18:25:55 +07:00
parent ca6b277a04
commit 3896886349
9 changed files with 1394 additions and 27 deletions

View File

@@ -0,0 +1,434 @@
// Base ZLAC8015D qua CANopen (lely-core).
//
// ================== 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.
//
// 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.
//
// ================== 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 0.1 RPM
// 0x6064:1/2 i32 Position actual, don vi increment <-- doc o day
// 0x608F:1 u32 Encoder increments / vong
//
// ================== 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.
//
// ⚠️ CHUA XAC MINH TREN THIET BI: khong cho nao trong base_kit doc 0x6064, nen
// chua ai chung minh ZLAC8015D co expose object nay. DS402 bat buoc no cho
// che do position, nhung thiet bi chay Profile Velocity co the khong map.
// Open() THU DOC va tra loi RO neu khong co, thay vi im lang tra ve 0 --
// encoder dung yen o 0 trong khi robot dang chay la trieu chung rat kho lan
// ra, no trong het nhu "odometry chet".
//
// ================== 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.
#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 <cmath>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <thread>
#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;
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();
}
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;
class LelyBridge : public lely::canopen::BasicDriver {
public:
LelyBridge(lely::canopen::AsyncMaster& m, uint8_t id, std::atomic<bool>* lost)
: BasicDriver(m, id), lost_(lost) {}
protected:
void OnBoot(lely::canopen::NmtState, char, const std::string&) noexcept override {
master.Command(lely::canopen::NmtCommand::START, id());
}
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;
};
class ZlacBase : public BaseInterface {
public:
ZlacBase(const BaseConfig& cfg, ClockPtr clock)
: cfg_(cfg), clock_(std::move(clock)) {}
~ZlacBase() override { Close(); }
void SetEncoderCallback(EncoderCallback cb) override { cb_ = std::move(cb); }
StatusResponse Open() override {
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` "
"-- xem base_kit/src/Zlac_ros/config/master.yml");
}
if (!(cfg_.wheel_radius > 0.0) || !(cfg_.wheel_separation > 0.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_);
master_->Reset();
lely_thread_ = std::thread([this] {
try { loop_->run(); } catch (...) {}
});
} catch (const std::exception& e) {
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?");
}
if (StatusResponse st = EnableDs402(); !st.ok()) return st;
if (StatusResponse st = ResolveEncoderScale(); !st.ok()) return st;
running_ = true;
poll_thread_ = std::thread([this] { PollLoop(); });
return StatusResponse::Ok();
}
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 (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();
}
void SetVelocity(double linear, double angular) override {
// Kep o day la CHAN CUOI, doc lap voi lop safety va voi deadman 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
const double rpm_l = (v_l / cfg_.wheel_radius) * 60.0 / kTwoPi;
const double rpm_r = (v_r / cfg_.wheel_radius) * 60.0 / kTwoPi;
{
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;
}
}
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);
}
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) {
if (auto inc = SdoRead<uint32_t>(*master_, cfg_.can_node_id, 0x608F, 1)) {
counts_per_rev_ = *inc;
}
}
if (counts_per_rev_ == 0) {
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
"base: khong biet so increment/vong. Thiet bi khong tra loi "
"0x608F:1, va encoder_counts_per_rev trong config dang la 0. Dat "
"tuong minh tu datasheet ZLAC8015D roi chay lai.");
}
// Doc thu 0x6064 -- neu thiet bi khong map object nay thi bao NGAY o day.
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). "
"EncoderReading can goc quay TICH LUY, ma 0x606C chi cho van toc "
"tuc thoi -- tich phan van toc lam mat vinh vien moi doan duong bi "
"lo mot mau. Kiem lai PDO/SDO mapping cua driver, hoac doi thiet ke "
"sang chap nhan troi tich luy.");
}
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));
}
}
void PushVelocity() {
int16_t l = 0, r = 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_;
} else if (have_cmd_) {
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;
}
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);
EncoderReading out;
out.stamp = clock_->Now();
if (!l || !r) {
out.valid = false;
{
std::lock_guard<std::mutex> lk(stats_mu_);
++stats_.errors;
stats_.connected = false;
stats_.last_error = "khong doc duoc 0x6064";
}
if (cb_) cb_(out);
return;
}
// 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.valid = true;
{
std::lock_guard<std::mutex> lk(stats_mu_);
++stats_.frames;
stats_.connected = !lost_.load();
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<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::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;
UnixTime last_enc_;
std::mutex cmd_mu_;
int16_t target_l_ = 0, target_r_ = 0;
int16_t sent_l_ = 0, sent_r_ = 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<ZlacBase>(cfg, std::move(clock));
}
} // namespace vslam