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,338 @@
// Cau noi toi MCU: IMU qua UART.
//
// ================== KHONG KHOP DAC TA, VA VI SAO VAN VIET ==================
// mcu_protocol.h la DAC TA ma firmware phai khop:
// I,<micros>,<gx>,<gy>,<gz>,<ax>,<ay>,<az>
// Firmware dang chay (base_kit/src/hardware/IMU_uart -- ESP32-S3 + DFRobot
// WT61PC) KHONG phat theo do. No phat text ba dong roi rac, tab/space:
// Acc 0.05 -0.10 9.82 <- m/s^2
// Gyro 0.00 0.00 0.00 <- DO/s, khong phai rad/s
// Angle -0.55 -0.34 -176.61 <- do
//
// Driver nay doc DUNG cai firmware dang phat, va danh dau ro moi cho phai
// chap nhan vi the. Viet theo dac ta roi cho firmware doi thi khong ai chay
// duoc gi hom nay; viet theo thuc te roi im lang thi no thanh no ky thuat
// khong ai thay. Nen: chay duoc, va noi to cai gia phai tra.
//
// ================== BA CAI GIA, THEO MUC NGHIEM TRONG ==================
//
// 1. KHONG CO TIMESTAMP -> ClockSync khong chay duoc.
// Dac ta yeu cau `micros()` cua MCU de ClockSync fit tuyen tinh dong ho
// MCU <-> host. Firmware khong phat gi ca, nen stamp o day la luc HOST
// DOC DUOC DONG -- da qua bo dem USB-CDC, qua scheduler, qua ca do tre gom
// dong cua chinh driver nay. Do tre do KHONG do duoc va KHONG bu duoc.
// Hau qua thuc te: moi phep dong bo IMU voi LiDAR/camera deu mang mot sai
// so khong biet do lon. `stamp_skew_ms` trong DriverStats se luon la 0 --
// khong phai vi dong bo tot, ma vi KHONG CO GI DE SO.
//
// 2. GYRO LAM TRON 2 CHU SO.
// Firmware in "0.00" nghia la do phan giai 0.01 do/s ~ 0.17 mrad/s. Doc
// duoc tren thiet bi dung yen: gyro_z = 0.00 o MOI mau. EKF yaw se khong
// thay chuyen dong cham hon nguong do.
//
// 3. KHONG CO BARO / SIEU AM / BUMPER.
// Dac ta co ban ghi B, U, K. Firmware khong co cai nao. Cac callback
// tuong ung KHONG BAO GIO duoc goi -- xem ghi chu tai cho dang ky.
// Dac biet nguy hiem voi bumper: lop safety cho rang mat bumper la mot
// duong doc lap, o day no khong ton tai.
//
// Duong sua dung la firmware phat theo mcu_protocol.h. Khi do xoa file nay
// va dung duong `I/B/E/U/K/P` da co san trong mcu_protocol.cc.
#include <errno.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <atomic>
#include <cmath>
#include <cstring>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include "vslam/clock.h"
#include "vslam/driver_config.h"
#include "vslam/driver_interfaces.h"
#include "vslam/geometry.h"
#include "vslam/log.h"
namespace vslam {
namespace {
constexpr double kDeg2Rad = M_PI / 180.0;
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;
}
}
class McuBridge : public McuInterface {
public:
McuBridge(const McuConfig& cfg, ClockPtr clock)
: cfg_(cfg), clock_(std::move(clock)) {}
~McuBridge() override { Close(); }
void SetImuCallback(ImuCallback cb) override { imu_cb_ = std::move(cb); }
// Ba callback duoi day KHONG BAO GIO duoc goi voi firmware hien tai --
// khong phai quen noi day, ma la firmware khong phat B/U/K. Van nhan va
// giu de khi firmware dung dac ta thi chi phai sua mot cho.
void SetBaroCallback(BaroCallback cb) override { baro_cb_ = std::move(cb); }
void SetUltrasonicCallback(UltrasonicCallback cb) override {
ultra_cb_ = std::move(cb);
}
void SetBumperCallback(BumperCallback cb) override {
bumper_cb_ = std::move(cb);
}
StatusResponse Open() override {
if (fd_ >= 0) {
return StatusResponse::Error(StatusCode::kFailedPrecondition,
"mcu: da mo roi");
}
if (!clock_) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"mcu: thieu clock");
}
const speed_t speed = BaudConstant(cfg_.baud);
if (speed == 0) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"mcu: baud " + std::to_string(cfg_.baud) + " khong ho tro");
}
fd_ = ::open(cfg_.port.c_str(), O_RDWR | O_NOCTTY | O_SYNC);
if (fd_ < 0) {
return StatusResponse::Error(
StatusCode::kUnavailable,
"mcu: mo " + cfg_.port + " that bai: " + std::strerror(errno) +
(errno == EACCES ? " -- thieu quyen? them user vao nhom dialout"
: ""));
}
termios tty{};
if (::tcgetattr(fd_, &tty) != 0) {
const std::string err = std::strerror(errno);
CloseFd();
return StatusResponse::Error(StatusCode::kInternal,
"mcu: tcgetattr that bai: " + err);
}
::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: read() tra ve sau nhieu nhat VTIME*100 ms du khong co
// byte nao. Can the de vong doc con thoat duoc khi Close().
tty.c_cc[VMIN] = 0;
tty.c_cc[VTIME] = static_cast<cc_t>(
cfg_.read_timeout_sec > 0.0 ? cfg_.read_timeout_sec * 10.0 : 10);
if (::tcsetattr(fd_, TCSANOW, &tty) != 0) {
const std::string err = std::strerror(errno);
CloseFd();
return StatusResponse::Error(StatusCode::kInternal,
"mcu: tcsetattr that bai: " + err);
}
VSLAM_INFO("mcu: mo " << cfg_.port << " @" << cfg_.baud);
if (!cfg_.expect_timestamps) {
VSLAM_WARN(
"mcu: firmware khong phat timestamp -- stamp lay tu dong ho HOST luc "
"doc duoc dong. Moi phep dong bo IMU voi LiDAR/camera mang mot do "
"tre khong do duoc. Xem mcu_bridge.cc, muc 1.");
}
running_ = true;
thread_ = std::thread([this] { ReadLoop(); });
return StatusResponse::Ok();
}
void Close() override {
running_ = false;
CloseFd();
if (thread_.joinable()) thread_.join();
}
DriverStats Stats() const override {
std::lock_guard<std::mutex> lk(stats_mu_);
return stats_;
}
private:
void CloseFd() {
if (fd_ >= 0) {
::close(fd_);
fd_ = -1;
}
}
void ReadLoop() {
char buf[512];
std::string line;
while (running_) {
const ssize_t n = ::read(fd_, buf, sizeof(buf));
if (n < 0) {
if (!running_) break;
if (errno == EAGAIN || errno == EINTR) continue;
Fail(std::string("read() that bai: ") + std::strerror(errno));
continue;
}
if (n == 0) continue; // timeout, khong phai loi
for (ssize_t i = 0; i < n; ++i) {
if (buf[i] == '\n') {
ProcessLine(line);
line.clear();
} else if (buf[i] != '\r') {
// Chan dong rac dai vo han neu thiet bi phat nhieu: mot dong hop le
// dai chung 30 ky tu.
if (line.size() < 256) line += buf[i];
}
}
}
}
void ProcessLine(const std::string& line) {
if (line.empty()) return;
std::istringstream iss(line);
std::string type;
double x = 0.0, y = 0.0, z = 0.0;
if (!(iss >> type >> x >> y >> z)) {
// Dong khong doc duoc KHONG tinh la loi: firmware in ca banner luc
// khoi dong. Chi dem de thay khi ty le rac tang bat thuong.
++unparsed_;
return;
}
if (type == "Acc") {
ax_ = x; ay_ = y; az_ = z;
have_acc_ = true;
} else if (type == "Gyro") {
// DO/s -> rad/s. Firmware in do/s; Imu.angular_velocity la rad/s.
gx_ = x * kDeg2Rad; gy_ = y * kDeg2Rad; gz_ = z * kDeg2Rad;
have_gyro_ = true;
} else if (type == "Angle") {
roll_ = x * kDeg2Rad; pitch_ = y * kDeg2Rad; yaw_ = z * kDeg2Rad;
have_angle_ = true;
} else {
++unparsed_;
return;
}
if (have_acc_ && have_gyro_ && have_angle_) {
Publish();
have_acc_ = have_gyro_ = have_angle_ = false;
}
}
void Publish() {
auto imu = std::make_shared<Imu>();
imu->header.seq = seq_++;
// ⚠️ Dong ho HOST, khong phai dong ho thiet bi -- xem dau file, muc 1.
imu->header.stamp = clock_->Now();
imu->header.frame_id = cfg_.imu_frame_id;
imu->angular_velocity.x = gx_;
imu->angular_velocity.y = gy_;
imu->angular_velocity.z = gz_;
imu->linear_acceleration.x = ax_;
imu->linear_acceleration.y = ay_;
imu->linear_acceleration.z = az_;
imu->orientation = QuaternionFromRPY(roll_, pitch_, yaw_);
// Covariance tu datasheet ICM-42688-P, deu la DOAN cho toi khi chay
// allan_variance. Dat tren duong cheo, khong de 0: 0 nghia la "chinh xac
// tuyet doi" voi moi bo loc doc no.
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;
}
// WT61PC co fusion rieng cho ra Angle, nhung do tin cay cua no khong do
// duoc o day. Khong dat [0] < 0 (tuc "khong co orientation") vi yaw van
// dung duoc lam goi y; de covariance lon de bo loc tu ha trong so.
for (int i = 0; i < 3; ++i) imu->orientation_covariance[i * 4] = 0.05;
{
std::lock_guard<std::mutex> lk(stats_mu_);
++stats_.frames;
stats_.connected = true;
const UnixTime now = imu->header.stamp;
if (!last_pub_.isZero()) {
const double dt = (now - last_pub_).toSec();
if (dt > 0.0) stats_.hz = 1.0 / dt;
}
last_pub_ = now;
// KHONG co gi de so -> de 0. Xem dau file, muc 1.
stats_.stamp_skew_ms = 0.0;
stats_.clock_skew_ppm = 0.0;
}
if (imu_cb_) imu_cb_(imu);
}
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, "mcu: " << msg);
}
McuConfig cfg_;
ClockPtr clock_;
ImuCallback imu_cb_;
BaroCallback baro_cb_;
UltrasonicCallback ultra_cb_;
BumperCallback bumper_cb_;
int fd_ = -1;
std::atomic<bool> running_{false};
std::thread thread_;
double ax_ = 0.0, ay_ = 0.0, az_ = 0.0;
double gx_ = 0.0, gy_ = 0.0, gz_ = 0.0;
double roll_ = 0.0, pitch_ = 0.0, yaw_ = 0.0;
bool have_acc_ = false, have_gyro_ = false, have_angle_ = false;
uint64_t unparsed_ = 0;
uint32_t seq_ = 0;
UnixTime last_pub_;
mutable std::mutex stats_mu_;
DriverStats stats_;
};
} // namespace
std::unique_ptr<McuInterface> CreateMcuBridge(const McuConfig& cfg,
ClockPtr clock) {
return std::make_unique<McuBridge>(cfg, std::move(clock));
}
} // namespace vslam