drivers: IMU WT61PC noi thang UART (mcu.protocol: wt61pc), bo ESP32 -- doc quyen cong, tach khung co resync, canh bao khi im
This commit is contained in:
@@ -60,7 +60,7 @@ Use this file for verified target-repository facts only. Keep unknown values as
|
||||
|
||||
- Cameras: RealSense D410 (depth + IR, **no RGB** — left IR doubles as the "rgb" channel for SLAM). 640x480 @ 30 fps, `decimate: 2` with CameraInfo still carrying full-res K (consumers must compensate). Driver `realsense_driver.cc`, built only with `-DVSLAM_WITH_REALSENSE=ON`; sensors.yaml states it is **not yet verified against real hardware**.
|
||||
- LiDAR: LakiBeam 1L over UDP, bind 0.0.0.0:2368, expected 25 Hz, 270° FOV, range 0.05–40.0 m. Angle convention `theta = (flip ? -alpha : alpha) + angle_offset_deg` with `angle_offset_deg: 178.75`, `angle_flip: true` (sensors.yaml:52-53; the 1.25 deg off 180 is a MEASURED mount error, and the driver logs a suggestion line every 10 s that reads as a no-op when the value is already right).
|
||||
- IMU: WT61PC behind an ESP32-S3 MCU on `/dev/ttyACM0` @ 115200 baud, expected 200 Hz. `ClockSync` fits MCU `micros()` to host clock; `McuTimeUnwrapper` is mandatory (uint32 wraps every 71.58 min).
|
||||
- IMU: WT61PC wired straight to a UART (USB-FTDI adapter, `/dev/imu`, `mcu.protocol: wt61pc`), 9600 baud, 10 Hz by default. Stamped from the host clock minus `imu_lag_sec` (no `ClockSync`). The older ESP32-S3 path (`mcu.protocol: esp`, `/dev/ttyACM0`, `ClockSync`, `McuTimeUnwrapper` for uint32 `micros()` wrap every 71.58 min) is still supported.
|
||||
- Compute target: Jetson AGX (arm64); jetson preset uses `CMAKE_PREFIX_PATH=/opt/vslam` and `CMAKE_INSTALL_PREFIX=/opt/vslam`, deps built from source (tools/build_deps.sh referenced by CMakePresets.json:40 — **script not present in repo**).
|
||||
- Accelerators: none used. No CUDA/TensorRT/OpenCL in the build; all processing is CPU.
|
||||
- Actuators or robot base: ZLAC8015D dual motor driver over **CANopen on `can0`, node id 1** (not serial), via `liblely-coapp`, gated by `-DVSLAM_WITH_CANOPEN=ON`. DCF at `configuration_files/master.dcf`, path resolved relative to the config dir. `encoder_counts_per_rev: 0` = fall back to 16384 (4096 "wire" x4); the x4 factor is **confirmed** by field data (2026-09-23, see Verification Notes).
|
||||
|
||||
@@ -27,7 +27,7 @@ Tai lieu chi tiet: [RUNTIME](docs/RUNTIME.md) · [SLAM](docs/SLAM.md) ·
|
||||
| An toan | FSM 20 Hz tren luong rieng: LiDAR, sieu am, bumper, e-stop |
|
||||
| Web UI | Boost.Beast (HTTP + WebSocket), JavaScript + three.js |
|
||||
| Cau hinh | yaml-cpp, 6 file trong `configuration_files/` |
|
||||
| Phan cung | LiDAR LakiBeam 1L (UDP) · RealSense D410 (librealsense2) · IMU WT61PC qua MCU ESP32-S3 (serial) · base ZLAC8015D (CANopen, lely-core) · tay cam Logitech F710 |
|
||||
| Phan cung | LiDAR LakiBeam 1L (UDP) · RealSense D410 (librealsense2) · IMU WT61PC (UART, cap USB-FTDI `/dev/imu`) · base ZLAC8015D (CANopen, lely-core) · tay cam Logitech F710 |
|
||||
| Cong cu Python | `tools/render_map.py` (anh bao cao ban do), `tools/vpr_eval.py` (danh gia VPR), `tools/vpr_export_onnx.py` (xuat model VPR sang ONNX) |
|
||||
|
||||
## Build
|
||||
|
||||
@@ -206,13 +206,27 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(mc, "sensors.yaml mcu",
|
||||
{"port", "baud", "sync_window", "max_skew_warn",
|
||||
{"protocol", "port", "baud", "sync_window", "max_skew_warn",
|
||||
"expected_imu_rate_hz", "ticks_per_rev", "imu_lag_sec",
|
||||
"expect_timestamps"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
out->sensors.imu_hz = mc.get<double>("expected_imu_rate_hz", 200.0);
|
||||
|
||||
// esp = ESP32 + USB-CDC (cach cu). wt61pc = cam bien noi thang UART/USB-FTDI.
|
||||
// Sai ten thi tu choi, khong doan: chon nham thi IMU im lang.
|
||||
{
|
||||
const std::string p = mc.get<std::string>("protocol", "esp");
|
||||
if (p == "esp") {
|
||||
out->mcu_driver.protocol = McuProtocol::kEspText;
|
||||
} else if (p == "wt61pc") {
|
||||
out->mcu_driver.protocol = McuProtocol::kWt61pc;
|
||||
} else {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"sensors.yaml mcu.protocol = \"" + p + "\" khong biet. Chon: esp | wt61pc.");
|
||||
}
|
||||
}
|
||||
out->mcu_driver.port = mc.get<std::string>("port", "/dev/ttyACM0");
|
||||
out->mcu_driver.baud = static_cast<uint32_t>(mc.get<int>("baud", 115200));
|
||||
out->mcu_driver.imu_frame_id = kImuFrame;
|
||||
|
||||
@@ -167,12 +167,24 @@ camera:
|
||||
# TIME_OF_ARRIVAL. Giu true van dung, duong lui da chay.
|
||||
prefer_global_time: true
|
||||
|
||||
# ============ MCU ============
|
||||
# ============ MCU / IMU ============
|
||||
mcu:
|
||||
port: /dev/ttyACM0
|
||||
# 115200 theo firmware that (ESP32-S3 + WT61PC). Gia tri cu la 921600 -- doc
|
||||
# sai baud cho ra RAC chu khong cho ra loi, nen no hong im lang.
|
||||
baud: 115200
|
||||
# ============ NOI IMU VAO MAY ============
|
||||
# wt61pc = WT61PC noi THANG UART hoac cap USB-FTDI, khung nhi phan 0x55 cua
|
||||
# cam bien (wt61pc_protocol.h). Khong con ESP32, khong co ClockSync:
|
||||
# stamp lay tu dong ho HOST, tru imu_lag_sec.
|
||||
# esp = ESP32-S3 + WT61PC qua USB-CDC (cach cu, firmware/imu_uart/).
|
||||
# Cac muc sync_window, max_skew_warn, expect_timestamps, ticks_per_rev ben
|
||||
# duoi CHI co nghia voi `esp`.
|
||||
protocol: wt61pc
|
||||
|
||||
# wt61pc: /dev/imu do luat udev tao (cap FTDI 0403:6001 -> SYMLINK+="imu");
|
||||
# 9600 la baud mac dinh cua cam bien. Cong duoc KHOA DOC QUYEN: chuong trinh
|
||||
# khac (imu_ros_node cua motor_control) mo cong sau se loi EBUSY.
|
||||
# esp: /dev/ttyACM0 @ 115200 theo firmware that. Gia tri cu la 921600 --
|
||||
# doc sai baud cho ra RAC chu khong cho ra loi, nen no hong im lang.
|
||||
port: /dev/imu
|
||||
baud: 9600
|
||||
|
||||
# ClockSync khop micros() cua MCU voi dong ho host bang fit tuyen tinh.
|
||||
#
|
||||
@@ -243,6 +255,10 @@ mcu:
|
||||
#
|
||||
# ⚠️ Phai do lai neu doi tan so cam bien hoac baud cua day UART1 -- ca hai so
|
||||
# hang tren deu phu thuoc chung.
|
||||
#
|
||||
# ⚠️ 0.07 do duoc tren duong ESP32 + USB-CDC. Voi protocol: wt61pc (UART
|
||||
# thang, khong ESP32) duong truyen khac, nen DO LAI bang quy trinh o tren
|
||||
# truoc khi tin con so nay.
|
||||
imu_lag_sec: 0.07
|
||||
|
||||
# Ban ghi encoder `E,<micros>,<ticks_l>,<ticks_r>` la MO RONG moi -- giao
|
||||
|
||||
@@ -14,6 +14,7 @@ vslam_add_library(vslam_drivers
|
||||
scan_sanitizer.h
|
||||
clock_sync.h
|
||||
mcu_protocol.h
|
||||
wt61pc_protocol.h
|
||||
record_format.h
|
||||
record_io.h
|
||||
replay_source.h
|
||||
|
||||
@@ -175,7 +175,17 @@ struct CameraConfig {
|
||||
|
||||
// --- MCU: IMU + barometer --------------------------------------------------
|
||||
|
||||
// Cach IMU noi vao may.
|
||||
enum class McuProtocol {
|
||||
// ESP32-S3 + WT61PC, text qua USB-CDC (/dev/ttyACM0). Xem mcu_bridge.cc.
|
||||
kEspText,
|
||||
// WT61PC noi THANG UART hoac cap USB-FTDI (/dev/imu), khung nhi phan 0x55.
|
||||
// Khong con ESP32, khong co ClockSync. Xem wt61pc_bridge.cc.
|
||||
kWt61pc,
|
||||
};
|
||||
|
||||
struct McuConfig {
|
||||
McuProtocol protocol = McuProtocol::kEspText;
|
||||
std::string port = "/dev/ttyACM0";
|
||||
// 115200, theo firmware that (base_kit/src/imu_uart). Gia tri cu o day la
|
||||
// 921600 -- doc sai baud thi ra rac chu khong ra loi, nen no im lang.
|
||||
@@ -219,6 +229,10 @@ struct McuConfig {
|
||||
double baro_variance = 9.0;
|
||||
|
||||
double read_timeout_sec = 1.0;
|
||||
|
||||
// Chi cho kWt61pc: khong co khung hop le nao trong chung nay (giay) thi WARN
|
||||
// kem goi y. Cam bien 10 Hz nen 2 s la mat ~20 khung, khong con la jitter.
|
||||
double no_data_warn_sec = 2.0;
|
||||
};
|
||||
|
||||
// --- Base: encoder + motor -------------------------------------------------
|
||||
|
||||
81
libs/vslam_drivers/include/vslam/wt61pc_protocol.h
Normal file
81
libs/vslam_drivers/include/vslam/wt61pc_protocol.h
Normal file
@@ -0,0 +1,81 @@
|
||||
#ifndef VSLAM_WT61PC_PROTOCOL_H
|
||||
#define VSLAM_WT61PC_PROTOCOL_H
|
||||
|
||||
// Khung nhi phan cua WT61PC (IMU 6 truc, WitMotion) khi cam THANG vao UART hoac
|
||||
// cap USB-FTDI cua Jetson, khong qua ESP32.
|
||||
//
|
||||
// Khac mcu_protocol.h: day KHONG phai giao thuc cua du an. No la giao thuc cua
|
||||
// cam bien, nen file nay GHI LAI dac ta cua nha san xuat; ben phai khop la
|
||||
// cam bien, khong phai firmware.
|
||||
//
|
||||
// ================== KHUNG ==================
|
||||
// 11 byte. Cam bien phat lien tuc, moi chu ky ba khung theo thu tu:
|
||||
// 0x55 0x51 axL axH ayL ayH azL azH TL TH SUM gia toc
|
||||
// 0x55 0x52 gxL gxH gyL gyH gzL gzH TL TH SUM van toc goc
|
||||
// 0x55 0x53 rL rH pL pH yL yH TL TH SUM goc (roll, pitch, yaw)
|
||||
// Moi truong la int16 little-endian. SUM = tong 10 byte dau, lay 8 bit thap.
|
||||
//
|
||||
// ================== DOI DON VI ==================
|
||||
// gia toc : raw / 32768 * 16 g -> m/s^2 (g = 9.80665)
|
||||
// van toc : raw / 32768 * 2000 do/s -> rad/s
|
||||
// goc : raw / 32768 * 180 do -> rad
|
||||
// Cung cong thuc voi firmware/imu_uart/main/main.c, nen truc va dau KHONG doi so
|
||||
// voi ban ghi `I` cua ESP32: doi nguon IMU khong dong toi EKF hay gravity_align.
|
||||
//
|
||||
// ================== TAN SO ==================
|
||||
// Mac dinh cua cam bien la 10 Hz o 9600 baud (do duoc: chu ky 0.1001 s). Moi
|
||||
// chu ky 33 byte, nen 9600 baud tran o ~29 Hz. Muon cao hon phai doi baud CUA
|
||||
// CAM BIEN (lenh cau hinh cua WitMotion), khong phai chi baud ben host.
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace vslam {
|
||||
|
||||
constexpr size_t kWt61pcFrameBytes = 11;
|
||||
constexpr uint8_t kWt61pcHeader = 0x55;
|
||||
|
||||
enum class Wt61pcType : uint8_t {
|
||||
kAccel = 0x51, // m/s^2
|
||||
kGyro = 0x52, // rad/s
|
||||
kAngle = 0x53, // rad
|
||||
};
|
||||
|
||||
struct Wt61pcFrame {
|
||||
Wt61pcType type = Wt61pcType::kAccel;
|
||||
// Da DOI DON VI theo `type`, xem tren.
|
||||
double x = 0.0;
|
||||
double y = 0.0;
|
||||
double z = 0.0;
|
||||
};
|
||||
|
||||
// Bo tach khung theo tung byte. Khong doc dong ho, khong goi he thong: chi la
|
||||
// ham thuan tren chuoi byte, nen test duoc ma khong can cong serial.
|
||||
class Wt61pcParser {
|
||||
public:
|
||||
// Nap mot byte. true khi byte nay hoan tat mot khung HOP LE loai
|
||||
// kAccel/kGyro/kAngle (checksum dung) va *out da duoc dien.
|
||||
bool Push(uint8_t byte, Wt61pcFrame* out);
|
||||
|
||||
void Reset();
|
||||
|
||||
uint64_t bad_checksum() const { return bad_checksum_; }
|
||||
// Byte bi bo vi khong thuoc khung nao (rac, hoac mat dong bo).
|
||||
uint64_t skipped_bytes() const { return skipped_bytes_; }
|
||||
// Khung dung checksum nhung loai khac 0x51..0x53 (vd 0x54). WT61PC khong co
|
||||
// tu ke nen binh thuong bang 0; dem de thay khi cam nham mot cam bien khac.
|
||||
uint64_t other_frames() const { return other_frames_; }
|
||||
|
||||
private:
|
||||
void Resync();
|
||||
|
||||
uint8_t buf_[kWt61pcFrameBytes] = {};
|
||||
size_t n_ = 0;
|
||||
uint64_t bad_checksum_ = 0;
|
||||
uint64_t skipped_bytes_ = 0;
|
||||
uint64_t other_frames_ = 0;
|
||||
};
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_WT61PC_PROTOCOL_H
|
||||
@@ -1,5 +1,8 @@
|
||||
// Cau noi toi MCU: IMU qua UART.
|
||||
//
|
||||
// (Cach thu ba -- WT61PC noi THANG UART, khong ESP32 -- nam o wt61pc_bridge.cc;
|
||||
// CreateMcuBridge() o cuoi file chon theo mcu.protocol.)
|
||||
//
|
||||
// ================== HAI NHANH, CHON BANG mcu.expect_timestamps ==================
|
||||
//
|
||||
// `true` -- firmware trong firmware/imu_uart/ cua repo nay. Phat theo dung
|
||||
@@ -516,8 +519,15 @@ class McuBridge : public McuInterface {
|
||||
|
||||
} // namespace
|
||||
|
||||
// Dinh nghia o wt61pc_bridge.cc.
|
||||
std::unique_ptr<McuInterface> CreateWt61pcBridge(const McuConfig& cfg,
|
||||
ClockPtr clock);
|
||||
|
||||
std::unique_ptr<McuInterface> CreateMcuBridge(const McuConfig& cfg,
|
||||
ClockPtr clock) {
|
||||
if (cfg.protocol == McuProtocol::kWt61pc) {
|
||||
return CreateWt61pcBridge(cfg, std::move(clock));
|
||||
}
|
||||
return std::make_unique<McuBridge>(cfg, std::move(clock));
|
||||
}
|
||||
|
||||
|
||||
389
libs/vslam_drivers/src/wt61pc_bridge.cc
Normal file
389
libs/vslam_drivers/src/wt61pc_bridge.cc
Normal file
@@ -0,0 +1,389 @@
|
||||
// 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. 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 <sys/ioctl.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#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;
|
||||
}
|
||||
}
|
||||
|
||||
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.");
|
||||
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.");
|
||||
}
|
||||
::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
|
||||
100
libs/vslam_drivers/src/wt61pc_protocol.cc
Normal file
100
libs/vslam_drivers/src/wt61pc_protocol.cc
Normal file
@@ -0,0 +1,100 @@
|
||||
#include "vslam/wt61pc_protocol.h"
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
constexpr double kWt61pcG = 9.80665;
|
||||
constexpr double kDeg2Rad = M_PI / 180.0;
|
||||
|
||||
// Loai khung cua dong WitMotion nam trong 0x50..0x5A. 0x55 bi loai ra: no
|
||||
// trung voi byte dau khung, nen "0x55 0x55" nghia la byte truoc la rac va byte
|
||||
// nay moi la dau khung that.
|
||||
bool IsFrameType(uint8_t b) {
|
||||
return b >= 0x50 && b <= 0x5A && b != kWt61pcHeader;
|
||||
}
|
||||
|
||||
double Int16LE(const uint8_t* p) {
|
||||
return static_cast<double>(
|
||||
static_cast<int16_t>(static_cast<uint16_t>(p[1]) << 8 | p[0]));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void Wt61pcParser::Reset() {
|
||||
n_ = 0;
|
||||
}
|
||||
|
||||
bool Wt61pcParser::Push(uint8_t byte, Wt61pcFrame* out) {
|
||||
if (n_ == 0) {
|
||||
if (byte == kWt61pcHeader) {
|
||||
buf_[n_++] = byte;
|
||||
} else {
|
||||
++skipped_bytes_;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (n_ == 1) {
|
||||
if (IsFrameType(byte)) {
|
||||
buf_[n_++] = byte;
|
||||
} else {
|
||||
++skipped_bytes_;
|
||||
if (byte != kWt61pcHeader) n_ = 0; // 0x55 0x55: giu lai, byte nay la dau khung
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
buf_[n_++] = byte;
|
||||
if (n_ < kWt61pcFrameBytes) return false;
|
||||
|
||||
uint8_t sum = 0;
|
||||
for (size_t i = 0; i + 1 < kWt61pcFrameBytes; ++i) {
|
||||
sum = static_cast<uint8_t>(sum + buf_[i]);
|
||||
}
|
||||
if (sum != buf_[kWt61pcFrameBytes - 1]) {
|
||||
++bad_checksum_;
|
||||
Resync();
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint8_t type = buf_[1];
|
||||
n_ = 0;
|
||||
if (type != static_cast<uint8_t>(Wt61pcType::kAccel) &&
|
||||
type != static_cast<uint8_t>(Wt61pcType::kGyro) &&
|
||||
type != static_cast<uint8_t>(Wt61pcType::kAngle)) {
|
||||
++other_frames_;
|
||||
return false;
|
||||
}
|
||||
|
||||
out->type = static_cast<Wt61pcType>(type);
|
||||
double scale = 0.0;
|
||||
switch (out->type) {
|
||||
case Wt61pcType::kAccel: scale = 16.0 * kWt61pcG / 32768.0; break;
|
||||
case Wt61pcType::kGyro: scale = 2000.0 * kDeg2Rad / 32768.0; break;
|
||||
case Wt61pcType::kAngle: scale = 180.0 * kDeg2Rad / 32768.0; break;
|
||||
}
|
||||
out->x = Int16LE(buf_ + 2) * scale;
|
||||
out->y = Int16LE(buf_ + 4) * scale;
|
||||
out->z = Int16LE(buf_ + 6) * scale;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Checksum sai co the la mat dong bo: dau khung that nam NGAY TRONG 10 byte sau
|
||||
// dau gia. Bo ca 11 byte se nuot luon khung dung ngay sau, va o 10 Hz do la
|
||||
// mat ca mot mau. Nen truot toi 0x55 ke tiep va nap lai phan con lai.
|
||||
void Wt61pcParser::Resync() {
|
||||
uint8_t keep[kWt61pcFrameBytes];
|
||||
size_t m = 0;
|
||||
size_t j = 1;
|
||||
while (j < kWt61pcFrameBytes && buf_[j] != kWt61pcHeader) ++j;
|
||||
skipped_bytes_ += j;
|
||||
for (; j < kWt61pcFrameBytes; ++j) keep[m++] = buf_[j];
|
||||
n_ = 0;
|
||||
// Toi da 10 byte nen khong the ra mot khung moi (can 11), cung khong de quy
|
||||
// vao Resync lan nua.
|
||||
Wt61pcFrame unused;
|
||||
for (size_t i = 0; i < m; ++i) Push(keep[i], &unused);
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
@@ -62,6 +62,8 @@ if(VSLAM_BUILD_DRIVERS)
|
||||
vslam_add_test(test_scan_sanitizer LIBS vslam_drivers vslam_common)
|
||||
vslam_add_test(test_clock_sync LIBS vslam_drivers vslam_common)
|
||||
vslam_add_test(test_mcu_protocol LIBS vslam_drivers vslam_common)
|
||||
vslam_add_test(test_wt61pc_protocol LIBS vslam_drivers vslam_common)
|
||||
vslam_add_test(test_wt61pc_bridge LIBS vslam_drivers vslam_common)
|
||||
vslam_add_test(test_record_io LIBS vslam_drivers vslam_common)
|
||||
# Tay cam: khoa CAM GIAC LAI port tu base_kit (he so turbo/slow, deadzone,
|
||||
# cu kich thang ma sat tinh, luat nhuong quyen 1.5 s). Khong can tay cam.
|
||||
|
||||
283
test/test_wt61pc_bridge.cc
Normal file
283
test/test_wt61pc_bridge.cc
Normal file
@@ -0,0 +1,283 @@
|
||||
// Cau noi WT61PC qua mot cap pty: phia slave la "cong serial" ma driver mo, phia
|
||||
// master la "cam bien" ghi khung vao. Chay duoc ma khong can phan cung, va di
|
||||
// qua dung termios/read cua driver that.
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cmath>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/clock.h"
|
||||
#include "vslam/driver_config.h"
|
||||
#include "vslam/driver_interfaces.h"
|
||||
|
||||
using namespace vslam;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr double kG = 9.80665;
|
||||
constexpr double kDeg = M_PI / 180.0;
|
||||
|
||||
std::vector<uint8_t> MakeFrame(uint8_t type, int16_t x, int16_t y, int16_t z) {
|
||||
auto lo = [](int16_t v) {
|
||||
return static_cast<uint8_t>(static_cast<uint16_t>(v) & 0xFF);
|
||||
};
|
||||
auto hi = [](int16_t v) {
|
||||
return static_cast<uint8_t>((static_cast<uint16_t>(v) >> 8) & 0xFF);
|
||||
};
|
||||
std::vector<uint8_t> f = {0x55, type, lo(x), hi(x), lo(y), hi(y),
|
||||
lo(z), hi(z), 0x00, 0x00, 0x00};
|
||||
uint8_t sum = 0;
|
||||
for (size_t i = 0; i < 10; ++i) sum = static_cast<uint8_t>(sum + f[i]);
|
||||
f[10] = sum;
|
||||
return f;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> Cat(std::initializer_list<std::vector<uint8_t>> parts) {
|
||||
std::vector<uint8_t> out;
|
||||
for (const auto& p : parts) out.insert(out.end(), p.begin(), p.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
class FakePort {
|
||||
public:
|
||||
FakePort() {
|
||||
master_ = ::posix_openpt(O_RDWR | O_NOCTTY);
|
||||
if (master_ < 0) return;
|
||||
char name[128] = {};
|
||||
if (::grantpt(master_) != 0 || ::unlockpt(master_) != 0 ||
|
||||
::ptsname_r(master_, name, sizeof(name)) != 0) {
|
||||
::close(master_);
|
||||
master_ = -1;
|
||||
return;
|
||||
}
|
||||
slave_ = name;
|
||||
}
|
||||
~FakePort() {
|
||||
if (master_ >= 0) ::close(master_);
|
||||
}
|
||||
|
||||
bool ok() const { return master_ >= 0; }
|
||||
const std::string& slave() const { return slave_; }
|
||||
|
||||
void Write(const std::vector<uint8_t>& bytes) {
|
||||
size_t off = 0;
|
||||
while (off < bytes.size()) {
|
||||
const ssize_t n = ::write(master_, bytes.data() + off, bytes.size() - off);
|
||||
if (n <= 0) break;
|
||||
off += static_cast<size_t>(n);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
int master_ = -1;
|
||||
std::string slave_;
|
||||
};
|
||||
|
||||
class ImuCollector {
|
||||
public:
|
||||
void Add(const Imu& imu) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
list_.push_back(imu);
|
||||
}
|
||||
cv_.notify_all();
|
||||
}
|
||||
bool WaitFor(size_t n, std::chrono::milliseconds timeout) {
|
||||
std::unique_lock<std::mutex> lk(mu_);
|
||||
return cv_.wait_for(lk, timeout, [&] { return list_.size() >= n; });
|
||||
}
|
||||
std::vector<Imu> Get() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return list_;
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::condition_variable cv_;
|
||||
std::vector<Imu> list_;
|
||||
};
|
||||
|
||||
McuConfig MakeConfig(const std::string& port) {
|
||||
McuConfig c;
|
||||
c.protocol = McuProtocol::kWt61pc;
|
||||
c.port = port;
|
||||
c.baud = 9600;
|
||||
c.imu_lag_sec = 0.0;
|
||||
return c;
|
||||
}
|
||||
|
||||
// Kernel/pty khong chac ap TIOCEXCL (root thi khong bao gio bi chan). Tu kiem
|
||||
// truoc de test khong bao dong gia.
|
||||
bool PtyHonoursExcl(const std::string& slave) {
|
||||
const int a = ::open(slave.c_str(), O_RDWR | O_NOCTTY);
|
||||
if (a < 0) return false;
|
||||
bool honoured = false;
|
||||
if (::ioctl(a, TIOCEXCL) == 0) {
|
||||
errno = 0;
|
||||
const int b = ::open(slave.c_str(), O_RDWR | O_NOCTTY);
|
||||
honoured = (b < 0 && errno == EBUSY);
|
||||
if (b >= 0) ::close(b);
|
||||
::ioctl(a, TIOCNXCL);
|
||||
}
|
||||
::close(a);
|
||||
return honoured;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(Wt61pcBridge, PhatNgayKhiCoKhungGyroKhongDoiAngle) {
|
||||
FakePort port;
|
||||
if (!port.ok()) GTEST_SKIP() << "khong tao duoc pty (container khong co /dev/ptmx?)";
|
||||
auto bridge = CreateMcuBridge(MakeConfig(port.slave()), MakeSystemClock());
|
||||
ImuCollector got;
|
||||
bridge->SetImuCallback([&](ImuPtr imu) { got.Add(*imu); });
|
||||
ASSERT_TRUE(bridge->Open().ok());
|
||||
|
||||
// Chi Acc + Gyro, khong gui Angle: phai ra dung mot mau.
|
||||
port.Write(Cat({MakeFrame(0x51, 0, 0, 2048), MakeFrame(0x52, 0, 0, 16384)}));
|
||||
ASSERT_TRUE(got.WaitFor(1, 2000ms));
|
||||
|
||||
const auto v = got.Get();
|
||||
ASSERT_EQ(v.size(), 1u);
|
||||
EXPECT_NEAR(v[0].linear_acceleration.z, kG, 1e-9);
|
||||
EXPECT_NEAR(v[0].angular_velocity.z, 1000.0 * kDeg, 1e-9);
|
||||
// Khong mang orientation.
|
||||
EXPECT_LT(v[0].orientation_covariance[0], 0.0);
|
||||
EXPECT_TRUE(bridge->Stats().connected);
|
||||
bridge->Close();
|
||||
}
|
||||
|
||||
TEST(Wt61pcBridge, GyroKhongCoGiaTocDiTruocThiBoMau) {
|
||||
FakePort port;
|
||||
if (!port.ok()) GTEST_SKIP() << "khong tao duoc pty (container khong co /dev/ptmx?)";
|
||||
auto bridge = CreateMcuBridge(MakeConfig(port.slave()), MakeSystemClock());
|
||||
ImuCollector got;
|
||||
bridge->SetImuCallback([&](ImuPtr imu) { got.Add(*imu); });
|
||||
ASSERT_TRUE(bridge->Open().ok());
|
||||
|
||||
// Gyro lac loai, hoac Angle don doc: khong duoc ghep voi gia toc cu.
|
||||
port.Write(Cat({MakeFrame(0x52, 0, 0, 16384), MakeFrame(0x53, 1, 2, 3)}));
|
||||
EXPECT_FALSE(got.WaitFor(1, 400ms));
|
||||
|
||||
// Chu ky day du sau do thi ra mau.
|
||||
port.Write(Cat({MakeFrame(0x51, 0, 0, 2048), MakeFrame(0x52, 0, 0, 16384)}));
|
||||
EXPECT_TRUE(got.WaitFor(1, 2000ms));
|
||||
bridge->Close();
|
||||
}
|
||||
|
||||
TEST(Wt61pcBridge, DauThoiGianKhongLuiVaTruImuLag) {
|
||||
FakePort port;
|
||||
if (!port.ok()) GTEST_SKIP() << "khong tao duoc pty (container khong co /dev/ptmx?)";
|
||||
McuConfig cfg = MakeConfig(port.slave());
|
||||
cfg.imu_lag_sec = 0.2;
|
||||
auto clock = MakeSystemClock();
|
||||
auto bridge = CreateMcuBridge(cfg, clock);
|
||||
|
||||
std::mutex mu;
|
||||
std::vector<double> stamps;
|
||||
std::vector<double> seen_at;
|
||||
ImuCollector got;
|
||||
bridge->SetImuCallback([&](ImuPtr imu) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
stamps.push_back(imu->header.stamp.toSec());
|
||||
seen_at.push_back(clock->Now().toSec());
|
||||
}
|
||||
got.Add(*imu);
|
||||
});
|
||||
ASSERT_TRUE(bridge->Open().ok());
|
||||
|
||||
// Nam chu ky lien nhau trong mot lan ghi: co the vao cung mot lan read().
|
||||
std::vector<uint8_t> burst;
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
const auto c = Cat({MakeFrame(0x51, 0, 0, 2048), MakeFrame(0x52, 0, 0, 16384),
|
||||
MakeFrame(0x53, 0, 0, 0)});
|
||||
burst.insert(burst.end(), c.begin(), c.end());
|
||||
}
|
||||
port.Write(burst);
|
||||
ASSERT_TRUE(got.WaitFor(5, 3000ms));
|
||||
bridge->Close();
|
||||
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
ASSERT_GE(stamps.size(), 5u);
|
||||
for (size_t i = 1; i < stamps.size(); ++i) {
|
||||
EXPECT_GE(stamps[i], stamps[i - 1]) << "stamp lui o mau " << i;
|
||||
}
|
||||
// Moi stamp phai cu hon luc nhan it nhat imu_lag_sec (0.2 s), va khong cu hon
|
||||
// qua mot khoang vo ly.
|
||||
for (size_t i = 0; i < stamps.size(); ++i) {
|
||||
EXPECT_LE(stamps[i], seen_at[i] - 0.2 + 1e-3) << "mau " << i;
|
||||
EXPECT_GE(stamps[i], seen_at[i] - 0.2 - 1.0) << "mau " << i;
|
||||
}
|
||||
}
|
||||
|
||||
TEST(Wt61pcBridge, ImLangThiBaoLoiVaHetLoiKhiCoDuLieu) {
|
||||
FakePort port;
|
||||
if (!port.ok()) GTEST_SKIP() << "khong tao duoc pty (container khong co /dev/ptmx?)";
|
||||
McuConfig cfg = MakeConfig(port.slave());
|
||||
cfg.no_data_warn_sec = 0.3;
|
||||
auto bridge = CreateMcuBridge(cfg, MakeSystemClock());
|
||||
ImuCollector got;
|
||||
bridge->SetImuCallback([&](ImuPtr imu) { got.Add(*imu); });
|
||||
ASSERT_TRUE(bridge->Open().ok());
|
||||
|
||||
std::this_thread::sleep_for(800ms);
|
||||
EXPECT_FALSE(bridge->Stats().connected);
|
||||
EXPECT_NE(bridge->Stats().last_error.find("khong co khung"), std::string::npos)
|
||||
<< bridge->Stats().last_error;
|
||||
|
||||
port.Write(Cat({MakeFrame(0x51, 0, 0, 2048), MakeFrame(0x52, 0, 0, 16384)}));
|
||||
ASSERT_TRUE(got.WaitFor(1, 2000ms));
|
||||
EXPECT_TRUE(bridge->Stats().connected);
|
||||
bridge->Close();
|
||||
}
|
||||
|
||||
TEST(Wt61pcBridge, CongKhongTonTaiLaLoiUnavailable) {
|
||||
McuConfig cfg = MakeConfig("/dev/khong_co_imu_nay");
|
||||
auto bridge = CreateMcuBridge(cfg, MakeSystemClock());
|
||||
const StatusResponse st = bridge->Open();
|
||||
ASSERT_FALSE(st.ok());
|
||||
EXPECT_EQ(st.code, StatusCode::kUnavailable);
|
||||
EXPECT_NE(st.message.find("/dev/khong_co_imu_nay"), std::string::npos) << st.message;
|
||||
}
|
||||
|
||||
TEST(Wt61pcBridge, BaudKhongHoTroBiTuChoi) {
|
||||
FakePort port;
|
||||
if (!port.ok()) GTEST_SKIP() << "khong tao duoc pty (container khong co /dev/ptmx?)";
|
||||
McuConfig cfg = MakeConfig(port.slave());
|
||||
cfg.baud = 12345;
|
||||
auto bridge = CreateMcuBridge(cfg, MakeSystemClock());
|
||||
const StatusResponse st = bridge->Open();
|
||||
ASSERT_FALSE(st.ok());
|
||||
EXPECT_EQ(st.code, StatusCode::kInvalidArgument);
|
||||
}
|
||||
|
||||
TEST(Wt61pcBridge, DocQuyenCongChuongTrinhThuHaiBiEbusy) {
|
||||
FakePort port;
|
||||
if (!port.ok()) GTEST_SKIP() << "khong tao duoc pty (container khong co /dev/ptmx?)";
|
||||
if (!PtyHonoursExcl(port.slave())) {
|
||||
GTEST_SKIP() << "pty/kernel/quyen root nay khong ap TIOCEXCL";
|
||||
}
|
||||
auto bridge = CreateMcuBridge(MakeConfig(port.slave()), MakeSystemClock());
|
||||
ASSERT_TRUE(bridge->Open().ok());
|
||||
|
||||
errno = 0;
|
||||
const int fd = ::open(port.slave().c_str(), O_RDWR | O_NOCTTY);
|
||||
EXPECT_LT(fd, 0);
|
||||
EXPECT_EQ(errno, EBUSY);
|
||||
if (fd >= 0) ::close(fd);
|
||||
bridge->Close();
|
||||
}
|
||||
170
test/test_wt61pc_protocol.cc
Normal file
170
test/test_wt61pc_protocol.cc
Normal file
@@ -0,0 +1,170 @@
|
||||
#include "vslam/wt61pc_protocol.h"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
using namespace vslam;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr double kG = 9.80665;
|
||||
constexpr double kDeg = M_PI / 180.0;
|
||||
|
||||
// Dung mot khung 11 byte dung checksum.
|
||||
std::vector<uint8_t> MakeFrame(uint8_t type, int16_t x, int16_t y, int16_t z) {
|
||||
auto lo = [](int16_t v) {
|
||||
return static_cast<uint8_t>(static_cast<uint16_t>(v) & 0xFF);
|
||||
};
|
||||
auto hi = [](int16_t v) {
|
||||
return static_cast<uint8_t>((static_cast<uint16_t>(v) >> 8) & 0xFF);
|
||||
};
|
||||
std::vector<uint8_t> f = {0x55, type, lo(x), hi(x), lo(y), hi(y),
|
||||
lo(z), hi(z), 0x00, 0x00, 0x00};
|
||||
uint8_t sum = 0;
|
||||
for (size_t i = 0; i < 10; ++i) sum = static_cast<uint8_t>(sum + f[i]);
|
||||
f[10] = sum;
|
||||
return f;
|
||||
}
|
||||
|
||||
// Nap het chuoi byte, tra ve cac khung hop le theo thu tu.
|
||||
std::vector<Wt61pcFrame> Feed(Wt61pcParser& p, const std::vector<uint8_t>& bytes) {
|
||||
std::vector<Wt61pcFrame> out;
|
||||
Wt61pcFrame f;
|
||||
for (uint8_t b : bytes) {
|
||||
if (p.Push(b, &f)) out.push_back(f);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// --- Doi don vi ------------------------------------------------------------
|
||||
|
||||
TEST(Wt61pc, GiaToc) {
|
||||
Wt61pcParser p;
|
||||
// 2048 = 32768 / 16: dung 1 g.
|
||||
const auto fr = Feed(p, MakeFrame(0x51, 0, 0, 2048));
|
||||
ASSERT_EQ(fr.size(), 1u);
|
||||
EXPECT_EQ(fr[0].type, Wt61pcType::kAccel);
|
||||
EXPECT_NEAR(fr[0].x, 0.0, 1e-12);
|
||||
EXPECT_NEAR(fr[0].z, kG, 1e-9);
|
||||
}
|
||||
|
||||
TEST(Wt61pc, VanTocGocGiuDau) {
|
||||
Wt61pcParser p;
|
||||
// 16384 = nua thang do = 1000 do/s. Gia tri am phai giu dau (int16).
|
||||
const auto fr = Feed(p, MakeFrame(0x52, 16384, -16384, 0));
|
||||
ASSERT_EQ(fr.size(), 1u);
|
||||
EXPECT_EQ(fr[0].type, Wt61pcType::kGyro);
|
||||
EXPECT_NEAR(fr[0].x, 1000.0 * kDeg, 1e-9);
|
||||
EXPECT_NEAR(fr[0].y, -1000.0 * kDeg, 1e-9);
|
||||
EXPECT_NEAR(fr[0].z, 0.0, 1e-12);
|
||||
}
|
||||
|
||||
TEST(Wt61pc, Goc) {
|
||||
Wt61pcParser p;
|
||||
// 16384 = nua thang = 90 do.
|
||||
const auto fr = Feed(p, MakeFrame(0x53, 16384, -8192, 0));
|
||||
ASSERT_EQ(fr.size(), 1u);
|
||||
EXPECT_EQ(fr[0].type, Wt61pcType::kAngle);
|
||||
EXPECT_NEAR(fr[0].x, M_PI / 2.0, 1e-9);
|
||||
EXPECT_NEAR(fr[0].y, -M_PI / 4.0, 1e-9);
|
||||
}
|
||||
|
||||
// --- Dong byte ---------------------------------------------------------------
|
||||
|
||||
TEST(Wt61pc, MotChuKyBaKhungDungThuTu) {
|
||||
Wt61pcParser p;
|
||||
std::vector<uint8_t> in;
|
||||
for (uint8_t t : {0x51, 0x52, 0x53}) {
|
||||
const auto f = MakeFrame(t, 1, 2, 3);
|
||||
in.insert(in.end(), f.begin(), f.end());
|
||||
}
|
||||
const auto fr = Feed(p, in);
|
||||
ASSERT_EQ(fr.size(), 3u);
|
||||
EXPECT_EQ(fr[0].type, Wt61pcType::kAccel);
|
||||
EXPECT_EQ(fr[1].type, Wt61pcType::kGyro);
|
||||
EXPECT_EQ(fr[2].type, Wt61pcType::kAngle);
|
||||
EXPECT_EQ(p.bad_checksum(), 0u);
|
||||
EXPECT_EQ(p.skipped_bytes(), 0u);
|
||||
}
|
||||
|
||||
TEST(Wt61pc, KhungBiCatLamDoiQuaHaiLanNap) {
|
||||
// read() co the dut khung o bat ky byte nao.
|
||||
Wt61pcParser p;
|
||||
const auto f = MakeFrame(0x52, 100, 200, 300);
|
||||
const std::vector<uint8_t> a(f.begin(), f.begin() + 5);
|
||||
const std::vector<uint8_t> b(f.begin() + 5, f.end());
|
||||
EXPECT_TRUE(Feed(p, a).empty());
|
||||
const auto fr = Feed(p, b);
|
||||
ASSERT_EQ(fr.size(), 1u);
|
||||
EXPECT_EQ(fr[0].type, Wt61pcType::kGyro);
|
||||
}
|
||||
|
||||
TEST(Wt61pc, RacTruocKhungKhongPhaKhung) {
|
||||
Wt61pcParser p;
|
||||
std::vector<uint8_t> in = {0x01, 0x02, 0xFF, 0x00};
|
||||
const auto f = MakeFrame(0x52, 100, 200, 300);
|
||||
in.insert(in.end(), f.begin(), f.end());
|
||||
const auto fr = Feed(p, in);
|
||||
ASSERT_EQ(fr.size(), 1u);
|
||||
EXPECT_EQ(p.skipped_bytes(), 4u);
|
||||
}
|
||||
|
||||
TEST(Wt61pc, ChecksumSaiBiBoVaDem) {
|
||||
auto f = MakeFrame(0x51, 1, 2, 3);
|
||||
f[10] ^= 0x01;
|
||||
Wt61pcParser p;
|
||||
EXPECT_TRUE(Feed(p, f).empty());
|
||||
EXPECT_EQ(p.bad_checksum(), 1u);
|
||||
}
|
||||
|
||||
TEST(Wt61pc, HaiByteDauKhungLienTiepThiByteSauLaDauKhung) {
|
||||
// 0x55 0x55 ...: byte dau la rac, byte thu hai moi la dau khung that.
|
||||
Wt61pcParser p;
|
||||
std::vector<uint8_t> in = {0x55};
|
||||
const auto f = MakeFrame(0x51, 0, 0, 2048);
|
||||
in.insert(in.end(), f.begin(), f.end());
|
||||
const auto fr = Feed(p, in);
|
||||
ASSERT_EQ(fr.size(), 1u);
|
||||
EXPECT_NEAR(fr[0].z, kG, 1e-9);
|
||||
EXPECT_EQ(p.skipped_bytes(), 1u);
|
||||
}
|
||||
|
||||
TEST(Wt61pc, MatDongBoTrongKhungGiaVanLayDuocKhungThat) {
|
||||
// Dau gia "0x55 0x51" + 2 byte rac gom du 11 byte cung 7 byte dau cua khung
|
||||
// that, nen checksum sai. Neu bo ca 11 byte thi mat luon khung that -- o
|
||||
// 10 Hz do la mat ca mot mau. Parser phai truot toi 0x55 that.
|
||||
Wt61pcParser p;
|
||||
std::vector<uint8_t> in = {0x55, 0x51, 0x00, 0x00};
|
||||
const auto real = MakeFrame(0x52, 1000, -2000, 3000);
|
||||
in.insert(in.end(), real.begin(), real.end());
|
||||
const auto fr = Feed(p, in);
|
||||
ASSERT_EQ(fr.size(), 1u);
|
||||
EXPECT_EQ(fr[0].type, Wt61pcType::kGyro);
|
||||
EXPECT_NEAR(fr[0].x, 1000.0 * 2000.0 / 32768.0 * kDeg, 1e-9);
|
||||
EXPECT_NEAR(fr[0].y, -2000.0 * 2000.0 / 32768.0 * kDeg, 1e-9);
|
||||
EXPECT_NEAR(fr[0].z, 3000.0 * 2000.0 / 32768.0 * kDeg, 1e-9);
|
||||
EXPECT_EQ(p.bad_checksum(), 1u);
|
||||
}
|
||||
|
||||
TEST(Wt61pc, KhungLoaiKhacDungChecksumKhongTraVe) {
|
||||
// 0x54 = tu ke. WT61PC khong co; dem de thay khi cam nham cam bien.
|
||||
Wt61pcParser p;
|
||||
EXPECT_TRUE(Feed(p, MakeFrame(0x54, 1, 2, 3)).empty());
|
||||
EXPECT_EQ(p.other_frames(), 1u);
|
||||
EXPECT_EQ(p.bad_checksum(), 0u);
|
||||
// Khung ke tiep van doc duoc.
|
||||
EXPECT_EQ(Feed(p, MakeFrame(0x51, 0, 0, 2048)).size(), 1u);
|
||||
}
|
||||
|
||||
TEST(Wt61pc, ResetBoKhungDangDo) {
|
||||
Wt61pcParser p;
|
||||
const auto f = MakeFrame(0x51, 0, 0, 2048);
|
||||
const std::vector<uint8_t> head(f.begin(), f.begin() + 5);
|
||||
EXPECT_TRUE(Feed(p, head).empty());
|
||||
p.Reset();
|
||||
EXPECT_EQ(Feed(p, f).size(), 1u);
|
||||
}
|
||||
Reference in New Issue
Block a user