Files
vslam_cpp/libs/vslam_drivers/src/wt61pc_bridge.cc

427 lines
15 KiB
C++

// Cau noi toi IMU WT61PC noi THANG vao UART (cap USB-FTDI), khong qua ESP32.
//
// Chon bang `mcu.protocol: wt61pc` trong sensors.yaml. CreateMcuBridge() trong
// mcu_bridge.cc chuyen sang day; cach cu (ESP32 + USB-CDC) van o do.
//
// ================== KHAC McuBridge O DAU ==================
//
// 1. KHONG CO ClockSync.
// ESP32 dong dau bang micros() cua chinh no roi ClockSync anh xa sang dong
// ho host. O day khong co MCU, nen stamp lay tu dong ho HOST luc nhan xong
// khung gyro. De jitter khong chui thang vao stamp: cap USB-FTDI gom byte
// theo latency_timer (mac dinh 16 ms), nen mot lan read() co the mang nhieu
// khung. Driver bat ASYNC_LOW_LATENCY (ftdi_sio -> 1 ms) va luat udev
// configuration_files/udev/99-imu.rules dat san 1 ms: o 200 Hz (5 ms/mau)
// 16 ms la ~3 mau mot lan doc. Log luc mo cong bao gia tri that.
// Thoi diem cua mot khung duoc suy NGUOC tu luc read() tra ve, tru
// di thoi gian truyen cua cac byte toi sau no trong cung lan doc.
// Phan tre con lai (loc noi bo cua cam bien + thoi gian truyen khung) la
// HANG SO, tru bang `mcu.imu_lag_sec`. Con so 0.07 do duoc tren duong ESP32;
// sau khi doi sang UART thang PHAI do lai (log `wheel_odom/lag`).
//
// 2. PHAT NGAY KHI CO KHUNG GYRO, khong doi khung Angle.
// Mot chu ky la Acc -> Gyro -> Angle. Doi Angle them ~11.5 ms o 9600 baud,
// ma khong ai doc imu.orientation trong libs/ va app/ (firmware ESP32 cung
// lam vay, xem firmware/imu_uart/main/main.c). Gyro khong co Acc di truoc
// trong cung chu ky thi bo mau, khong ghep voi gia toc cu.
//
// 3. DOC QUYEN CONG (TIOCEXCL).
// Hai chuong trinh cung doc mot tty thi chia nhau luong byte: da gap tren
// robot nay khi imu_ros_node cua motor_control doc chung cong, IMU chi con
// mot nua so mau (chu ky 0.2 s thay vi 0.1 s) va khong bao loi nao. Co
// TIOCEXCL thi chuong trinh thu hai (khong phai root) mo cong se loi EBUSY
// ngay. Luu y: neu chuong trinh kia mo TRUOC thi khong chan duoc -- Open()
// van thanh cong; kiem bang `sudo fuser -v /dev/imu`.
//
// 4. KHONG IM LANG.
// Khong co khung hop le nao trong `no_data_warn_sec` -> WARN kem goi y. Cap
// bi rut -> read() loi, driver tu mo lai moi giay thay vi ket vinh vien.
//
// 5. KHONG CO BARO / SIEU AM / BUMPER. Ba callback do khong bao gio duoc goi,
// giong mcu_bridge.cc muc 3.
#include <errno.h>
#include <fcntl.h>
#include <linux/serial.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#include <atomic>
#include <chrono>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include "vslam/clock.h"
#include "vslam/driver_config.h"
#include "vslam/driver_interfaces.h"
#include "vslam/log.h"
#include "vslam/wt61pc_protocol.h"
namespace vslam {
namespace {
speed_t BaudConstant(uint32_t baud) {
switch (baud) {
case 9600: return B9600;
case 19200: return B19200;
case 38400: return B38400;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
case 460800: return B460800;
case 921600: return B921600;
default: return 0;
}
}
// Cap FTDI gom byte latency_timer ms roi moi day len host (mac dinh 16 ms; o
// 200 Hz la ~3 mau mot lan). ASYNC_LOW_LATENCY -> ftdi_sio dat 1 ms. Cong khong
// phai FTDI (pty khi test) thi ioctl loi -> bo qua.
void SetLowLatency(int fd) {
serial_struct ss{};
if (::ioctl(fd, TIOCGSERIAL, &ss) != 0) return;
ss.flags |= ASYNC_LOW_LATENCY;
::ioctl(fd, TIOCSSERIAL, &ss);
}
// latency_timer (ms) cua cap FTDI sau `port` (/dev/imu -> ttyUSB0); -1 = khong
// doc duoc (khong phai FTDI, hoac khong co sysfs).
int FtdiLatencyMs(const std::string& port) {
char real[PATH_MAX];
if (::realpath(port.c_str(), real) == nullptr) return -1;
const char* name = std::strrchr(real, '/');
std::ifstream f(std::string("/sys/class/tty/") + (name != nullptr ? name + 1 : real) +
"/device/latency_timer");
int ms = -1;
return (f >> ms) ? ms : -1;
}
class Wt61pcBridge : public McuInterface {
public:
Wt61pcBridge(const McuConfig& cfg, ClockPtr clock)
: cfg_(cfg), clock_(std::move(clock)) {}
~Wt61pcBridge() override { Close(); }
void SetImuCallback(ImuCallback cb) override { imu_cb_ = std::move(cb); }
// WT61PC chi co IMU. Dac biet bumper: lop safety coi mat bumper la mot duong
// doc lap, o day no khong ton tai.
void SetBaroCallback(BaroCallback) override {}
void SetUltrasonicCallback(UltrasonicCallback) override {}
void SetBumperCallback(BumperCallback) override {}
StatusResponse Open() override {
if (running_) {
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"imu: da mo roi");
}
if (!clock_) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"imu: thieu clock");
}
if (BaudConstant(cfg_.baud) == 0) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"imu: baud " + std::to_string(cfg_.baud) + " khong ho tro");
}
byte_s_ = 10.0 / static_cast<double>(cfg_.baud); // 1 start + 8 data + 1 stop
const StatusResponse st = OpenPort();
if (!st.ok()) return st;
VSLAM_INFO("imu: WT61PC o " << cfg_.port << " @" << cfg_.baud
<< ", doc quyen cong. Stamp lay tu dong ho HOST luc nhan xong "
"khung gyro, tru imu_lag_sec = " << cfg_.imu_lag_sec * 1000.0
<< " ms -- do lai bang log `wheel_odom/lag` sau khi doi nguon IMU.");
const int lat = FtdiLatencyMs(cfg_.port);
if (lat > 2) {
VSLAM_WARN("imu: latency_timer cap FTDI = " << lat << " ms -- moi lan doc gom nhieu "
"mau, stamp IMU giat. Cai configuration_files/udev/99-imu.rules (1 ms).");
} else if (lat >= 0) {
VSLAM_INFO("imu: latency_timer cap FTDI = " << lat << " ms");
}
if (cfg_.baud <= 9600) {
VSLAM_INFO("imu: 9600 baud chi du ~29 Hz (cam bien mac dinh 10 Hz). "
"wheel_odom bo gyro khi IMU cham hon encoder -- xem muc mcu "
"trong sensors.yaml.");
}
last_frame_ = std::chrono::steady_clock::now();
running_ = true;
thread_ = std::thread([this] { ReadLoop(); });
return StatusResponse::Ok();
}
void Close() override {
running_ = false;
// read() tra ve sau nhieu nhat 0.1 s (VTIME) nen join nhanh; dong fd SAU
// khi luong doc da thoat, khong dong duoi chan no.
if (thread_.joinable()) thread_.join();
CloseFd();
}
DriverStats Stats() const override {
std::lock_guard<std::mutex> lk(stats_mu_);
return stats_;
}
private:
StatusResponse OpenPort() {
const int fd = ::open(cfg_.port.c_str(), O_RDWR | O_NOCTTY);
if (fd < 0) {
const int e = errno;
std::string hint;
if (e == EACCES) {
hint = " -- thieu quyen? kiem luat udev (MODE/GROUP) hoac them user vao "
"nhom dialout";
} else if (e == ENOENT) {
hint = " -- khong thay thiet bi: cap USB-UART da cam chua? luat udev "
"da cai chua (ls -l " + cfg_.port + ")?";
} else if (e == EBUSY) {
hint = " -- co chuong trinh khac dang giu cong (imu_ros_node cua "
"motor_control?): sudo fuser -v " + cfg_.port;
}
return StatusResponse::Error(
StatusCode::kUnavailable,
"imu: mo " + cfg_.port + " that bai: " + std::strerror(e) + hint);
}
termios tty{};
if (::tcgetattr(fd, &tty) != 0) {
const std::string err = std::strerror(errno);
::close(fd);
return StatusResponse::Error(StatusCode::kInternal,
"imu: tcgetattr that bai: " + err);
}
const speed_t speed = BaudConstant(cfg_.baud);
::cfsetospeed(&tty, speed);
::cfsetispeed(&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8 bit
tty.c_cflag |= (CLOCAL | CREAD);
tty.c_cflag &= ~(PARENB | PARODD); // khong parity
tty.c_cflag &= ~CSTOPB; // 1 stop bit
tty.c_cflag &= ~CRTSCTS; // khong flow control
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL);
tty.c_iflag &= ~(IXON | IXOFF | IXANY);
tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tty.c_oflag &= ~OPOST;
// VMIN=0 + VTIME=1: read() tra ve ngay khi co byte, hoac sau 0.1 s neu khong
// co. Du ngan de Close() va bo dem im lang chay deu.
tty.c_cc[VMIN] = 0;
tty.c_cc[VTIME] = 1;
if (::tcsetattr(fd, TCSANOW, &tty) != 0) {
const std::string err = std::strerror(errno);
::close(fd);
return StatusResponse::Error(StatusCode::kInternal,
"imu: tcsetattr that bai: " + err);
}
if (::ioctl(fd, TIOCEXCL) != 0) {
VSLAM_WARN("imu: khong khoa duoc quyen doc cong " << cfg_.port << " ("
<< std::strerror(errno) << ") -- chuong trinh khac mo cong "
"sau se chia nhau luong byte.");
}
SetLowLatency(fd);
::tcflush(fd, TCIOFLUSH); // bo byte cu, tranh bat dau giua mot khung
fd_ = fd;
return StatusResponse::Ok();
}
void CloseFd() {
const int fd = fd_.exchange(-1);
if (fd >= 0) ::close(fd);
}
void ReadLoop() {
uint8_t buf[512];
Wt61pcFrame frame;
while (running_) {
const ssize_t n = ::read(fd_, buf, sizeof(buf));
const UnixTime t_read = clock_->Now(); // ngay sau khi read() tra ve
if (n < 0) {
if (!running_) break;
if (errno == EAGAIN || errno == EINTR) continue;
Fail(std::string("read() that bai: ") + std::strerror(errno) +
" -- cap bi rut? driver thu mo lai moi giay");
Reopen();
continue;
}
if (n > 0) {
bytes_ += static_cast<uint64_t>(n);
for (ssize_t i = 0; i < n; ++i) {
if (!parser_.Push(buf[i], &frame)) continue;
// Byte cuoi cua khung la byte thu i. (n - 1 - i) byte da toi SAU no
// trong cung lan doc, nen khung that ra som hon luc read() mot chut.
const UnixTime t_end =
t_read - Duration::fromSec(static_cast<double>(n - 1 - i) * byte_s_);
OnFrame(frame, t_end);
}
}
CheckSilence();
}
}
void OnFrame(const Wt61pcFrame& f, UnixTime t_end) {
last_frame_ = std::chrono::steady_clock::now();
switch (f.type) {
case Wt61pcType::kAccel:
ax_ = f.x; ay_ = f.y; az_ = f.z;
have_acc_ = true;
return;
case Wt61pcType::kAngle:
return; // khong dung, xem dau file muc 2
case Wt61pcType::kGyro:
break;
}
if (!have_acc_) {
++incomplete_; // mat khung gia toc cua chu ky nay
return;
}
have_acc_ = false;
Publish(f, t_end - Duration::fromSec(cfg_.imu_lag_sec));
}
void Publish(const Wt61pcFrame& gyro, UnixTime stamp) {
// Gom byte cua cap USB-FTDI co the khien thoi diem suy nguoc cua mot khung
// som hon khung truoc vai ms. Dau thoi gian khong duoc lui: wheel_odom chi
// chiu duoc lech thu tu nho.
if (have_pub_ && stamp < last_stamp_) {
stamp = last_stamp_;
++clamped_;
}
auto imu = std::make_shared<Imu>();
imu->header.seq = seq_++;
imu->header.stamp = stamp;
imu->header.frame_id = cfg_.imu_frame_id;
imu->angular_velocity.x = gyro.x;
imu->angular_velocity.y = gyro.y;
imu->angular_velocity.z = gyro.z;
imu->linear_acceleration.x = ax_;
imu->linear_acceleration.y = ay_;
imu->linear_acceleration.z = az_;
// Khong mang orientation (khung Angle khong duoc dung). [0] < 0 la quy uoc
// "khong co orientation", giong record_format.cc va sim_source.cc.
imu->orientation_covariance[0] = -1.0;
for (int i = 0; i < 3; ++i) {
imu->angular_velocity_covariance[i * 4] = cfg_.gyro_variance;
imu->linear_acceleration_covariance[i * 4] = cfg_.accel_variance;
}
{
std::lock_guard<std::mutex> lk(stats_mu_);
++stats_.frames;
stats_.connected = true;
if (have_pub_) {
const double dt = (stamp - last_stamp_).toSec();
if (dt > 0.0) stats_.hz = 1.0 / dt;
}
// Khong co MCU de so dong ho -> hai so nay luon 0.
stats_.stamp_skew_ms = 0.0;
stats_.clock_skew_ppm = 0.0;
}
last_stamp_ = stamp;
have_pub_ = true;
if (imu_cb_) imu_cb_(imu);
}
// Goi sau moi lan read(), ke ca khi het thoi gian cho (n == 0).
void CheckSilence() {
const double quiet = std::chrono::duration<double>(
std::chrono::steady_clock::now() - last_frame_).count();
if (quiet < cfg_.no_data_warn_sec) return;
const std::string msg =
"khong co khung WT61PC hop le nao trong " + std::to_string(quiet) +
" s (nhan " + std::to_string(bytes_) + " byte, checksum sai " +
std::to_string(parser_.bad_checksum()) + ", byte bo " +
std::to_string(parser_.skipped_bytes()) + "). Kiem: day TX cua cam "
"bien -> RX cua cap USB-UART co long khong; cam bien co dang o baud "
"khac " + std::to_string(cfg_.baud) + " (co byte ma checksum sai "
"nhieu thi gan chac la sai baud); chuong trinh khac dang doc cong "
"(sudo fuser -v " + cfg_.port + ").";
{
std::lock_guard<std::mutex> lk(stats_mu_);
stats_.connected = false;
stats_.last_error = msg;
}
VSLAM_WARN_THROTTLE(5.0, "imu: " << msg);
}
void Fail(const std::string& msg) {
{
std::lock_guard<std::mutex> lk(stats_mu_);
++stats_.errors;
stats_.connected = false;
stats_.last_error = msg;
}
VSLAM_WARN_THROTTLE(5.0, "imu: " << msg);
}
// Cap bi rut roi cam lai: read() loi mai mai neu khong mo lai. Mo lai moi
// giay cho toi khi duoc hoac Close().
void Reopen() {
CloseFd();
parser_.Reset();
have_acc_ = false;
while (running_) {
for (int i = 0; i < 10 && running_; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
if (!running_) return;
const StatusResponse st = OpenPort();
if (st.ok()) {
VSLAM_INFO("imu: mo lai " << cfg_.port << " thanh cong");
last_frame_ = std::chrono::steady_clock::now();
return;
}
VSLAM_WARN_THROTTLE(5.0, st.message);
}
}
McuConfig cfg_;
ClockPtr clock_;
ImuCallback imu_cb_;
std::atomic<int> fd_{-1};
std::atomic<bool> running_{false};
std::thread thread_;
// Chi cham tu luong doc.
Wt61pcParser parser_;
double byte_s_ = 0.0;
uint64_t bytes_ = 0;
double ax_ = 0.0, ay_ = 0.0, az_ = 0.0;
bool have_acc_ = false;
uint64_t incomplete_ = 0; // gyro khong co acc di truoc trong chu ky
uint64_t clamped_ = 0; // stamp bi keo len de khong lui
uint32_t seq_ = 0;
UnixTime last_stamp_;
bool have_pub_ = false;
std::chrono::steady_clock::time_point last_frame_;
mutable std::mutex stats_mu_;
DriverStats stats_;
};
} // namespace
std::unique_ptr<McuInterface> CreateWt61pcBridge(const McuConfig& cfg,
ClockPtr clock) {
return std::make_unique<Wt61pcBridge>(cfg, std::move(clock));
}
} // namespace vslam