392 lines
17 KiB
C++
392 lines
17 KiB
C++
// NOI DUY NHAT noi nguon voi stage.
|
|
//
|
|
// Day la tuong duong cua toan bo 20 file `.launch` cua ban ROS, gom lai thanh
|
|
// mot ham doc duoc tu tren xuong. Muon biet du lieu di dau thi doc file nay,
|
|
// khong phai grep remap qua 20 file XML.
|
|
//
|
|
// ================== BON DUONG ==================
|
|
// LiDAR -> ScanSanitizer -> {safety, web}
|
|
// IMU -> {gravity_align, wheel_odom (gyro), ekf}
|
|
// Encoder -> wheel_odom -> {ekf, gravity_align (tru gia toc rieng)}
|
|
// Camera -> perception (INLINE) -> {safety (co vuc), web (cloud)}
|
|
//
|
|
// Lenh di NGUOC lai va chi mot duong:
|
|
// web -> teleop -> raw_cmd -> [luong safety] -> base
|
|
// Khong nhanh nao cho lenh di thang xuong base. Ke ca e-stop: no dat co, roi
|
|
// luong safety thay co va zero lenh trong vong mot chu ky.
|
|
|
|
#include "runtime.h"
|
|
|
|
#include "vslam/geometry.h"
|
|
#include "vslam/json_parse.h"
|
|
#include "vslam/log.h"
|
|
|
|
#include <cmath>
|
|
|
|
namespace vslam {
|
|
|
|
StatusResponse Runtime::Wire() {
|
|
// ---------------- LiDAR ----------------
|
|
if (lidar_ != nullptr) {
|
|
lidar_->SetCallback([this](LaserScanPtr s) {
|
|
// Ve sinh MOT lan, ngay tai bien. Moi nguoi doc phia sau nhan cung mot
|
|
// ban -- khong ai duoc ve sinh lai, va khong ai thay ban tho.
|
|
//
|
|
// ScanSanitizer gop header-fix va sector mask lam MOT ham: hai bo loc
|
|
// rieng thi "cai nao chay truoc" la mot bay co that.
|
|
auto copy = std::make_shared<LaserScan>(*s);
|
|
sanitizer_->Apply(copy.get());
|
|
std::lock_guard<std::mutex> lk(scan_mu_);
|
|
latest_scan_ = copy;
|
|
});
|
|
}
|
|
|
|
// ---------------- IMU ----------------
|
|
if (mcu_ != nullptr) {
|
|
mcu_->SetImuCallback([this](ImuPtr m) {
|
|
// gravity_align chay TRUOC: no o 200 Hz va re, va cliff_detect can
|
|
// nghieng moi nhat.
|
|
perception_->FeedImu(*m);
|
|
|
|
// Cong bo nghieng cho luong web. Phai qua atomic: `GravityAlign` thuoc
|
|
// ve luong nay va khong tu khoa -- doc thang tu luong khac la data
|
|
// race, va ThreadSanitizer da bat dung no.
|
|
tilt_roll_.store(perception_->gravity().roll(), std::memory_order_relaxed);
|
|
tilt_pitch_.store(perception_->gravity().pitch(), std::memory_order_relaxed);
|
|
tilt_accel_ok_.store(perception_->gravity().accel_ok(),
|
|
std::memory_order_relaxed);
|
|
|
|
std::lock_guard<std::mutex> lk(odom_mu_);
|
|
wheel_odom_->FeedGyroZ(m->header.stamp, m->angular_velocity.z);
|
|
// ⚠️ TICH PHAN gyro, khong lay mot mau.
|
|
//
|
|
// IMU chay 200 Hz con encoder 50 Hz, nen moi khoang odom co ~4 mau.
|
|
// Lay MOT mau roi nhan voi ca khoang 20 ms la phep hinh chu nhat tren
|
|
// mot tin hieu dang doi nhanh -- da do: sai goc 150 do sau mot lan xoay.
|
|
if (have_gyro_) {
|
|
const double dti = SecondsBetween(m->header.stamp, gyro_stamp_);
|
|
if (dti > 0.0 && dti < 0.1) {
|
|
gyro_dtheta_ += 0.5 * (gyro_z_ + m->angular_velocity.z) * dti;
|
|
gyro_dt_ += dti;
|
|
}
|
|
}
|
|
gyro_z_ = m->angular_velocity.z;
|
|
gyro_stamp_ = m->header.stamp;
|
|
have_gyro_ = true;
|
|
ekf_->UpdateImuYawRate(m->header.stamp, m->angular_velocity.z,
|
|
m->angular_velocity_covariance[8] > 0.0
|
|
? m->angular_velocity_covariance[8]
|
|
: 2.4e-7);
|
|
});
|
|
}
|
|
|
|
// ---------------- Sieu am + bumper ----------------
|
|
if (mcu_ != nullptr) {
|
|
mcu_->SetUltrasonicCallback([this](const UltrasonicReading& u) {
|
|
std::lock_guard<std::mutex> lk(mcu_mu_);
|
|
ultrasonic_.clear();
|
|
for (size_t i = 0; i < u.count; ++i) {
|
|
// GIU CA NaN. Truoc day o day loc NaN di, va do la sai: map rong
|
|
// trong y het "khong lap sieu am", nen mot day cam bien DUT hoan
|
|
// toan vo hinh voi FSM. Chinh FSM phan biet ba ngu nghia (huu han /
|
|
// inf / NaN) -- day chi truyen nguyen ven.
|
|
ultrasonic_["us" + std::to_string(i)] = u.range[i];
|
|
}
|
|
us_stamp_ = u.stamp;
|
|
// `have_us_` van true ke ca khi moi dau do deu NaN: co cam bien lap
|
|
// dat, chi la chung khong tra loi -> dung la truong hop US_TIMEOUT.
|
|
have_us_ = true;
|
|
});
|
|
|
|
mcu_->SetBumperCallback([this](const BumperReading& b) {
|
|
std::lock_guard<std::mutex> lk(mcu_mu_);
|
|
bumper_ = b.any();
|
|
bumper_stamp_ = b.stamp;
|
|
have_bumper_ = true;
|
|
});
|
|
}
|
|
|
|
// ---------------- Encoder ----------------
|
|
if (base_ != nullptr) {
|
|
base_->SetEncoderCallback([this](const EncoderReading& e) {
|
|
if (!e.valid) return;
|
|
Odometry o;
|
|
{
|
|
std::lock_guard<std::mutex> lk(odom_mu_);
|
|
if (!wheel_odom_->Update(e.stamp, e.left_rad, e.right_rad, &o)) return;
|
|
|
|
// Truyen THANG twist.covariance vao EKF.
|
|
//
|
|
// Do chinh la cach wheel_odom bao "dang truot, dung tin toi". Thay
|
|
// bang hang so o day la vut bo toan bo co che phat hien truot -- va
|
|
// no im lang, vi EKF van chay va van cho ra mot pose trong nhu that.
|
|
// ⚠️ Mo hinh chuyen dong theo DELTA, khong theo van toc da loc.
|
|
//
|
|
// Do duoc: sau mot lan xoay tai cho, goc cua wheel odometry lech
|
|
// +0.000 do so voi ground truth, goc cua EKF lech +0.814 do. Bo loc
|
|
// lam hong mot phep do von chinh xac, va sai so goc do khong bao gio
|
|
// duoc tra lai. Xem ghi chu o `EkfSe2::UpdateOdomDelta`.
|
|
const Pose2D now_pose = wheel_odom_->pose();
|
|
if (have_prev_odom_) {
|
|
const double dx = now_pose.x - prev_odom_.x;
|
|
const double dy = now_pose.y - prev_odom_.y;
|
|
// Dau cua doan di chuyen theo huong dang quay ve.
|
|
const double heading = std::cos(prev_odom_.theta) * dx +
|
|
std::sin(prev_odom_.theta) * dy;
|
|
const double d_trans = std::copysign(std::hypot(dx, dy), heading);
|
|
double d_theta = NormalizeAngle(now_pose.theta - prev_odom_.theta);
|
|
|
|
const double dt = SecondsBetween(e.stamp, prev_odom_stamp_);
|
|
// Gyro da duoc TICH PHAN trong callback IMU. Chi nhan neu no phu
|
|
// gan het khoang odom -- thieu mau thi tich phan khong dai dien.
|
|
const bool gyro_ok = gyro_dt_ > 0.5 * dt && dt > 0.0;
|
|
const double d_theta_gyro = gyro_ok ? gyro_dtheta_ : d_theta;
|
|
|
|
// Phuong sai: wheel_odom bao qua twist.covariance -- do chinh la
|
|
// cho no noi "dang truot, dung tin toi".
|
|
//
|
|
// Gyro: nhieu trang, nen phuong sai cua TICH PHAN ti le voi dt
|
|
// (buoc ngau nhien), khong voi dt^2.
|
|
const double var_th_enc =
|
|
std::max(o.twist.covariance[35] * dt * dt, 1e-12);
|
|
const double var_th_gyro =
|
|
gyro_ok ? std::max(2.4e-7 * dt, 1e-12) : 1e9;
|
|
const double var_tr = std::max(o.twist.covariance[0] * dt * dt, 1e-12);
|
|
|
|
ekf_->UpdateOdomDelta(e.stamp, d_trans, d_theta, d_theta_gyro,
|
|
var_tr, var_th_enc, var_th_gyro);
|
|
}
|
|
gyro_dtheta_ = 0.0;
|
|
gyro_dt_ = 0.0;
|
|
prev_odom_ = now_pose;
|
|
prev_odom_stamp_ = e.stamp;
|
|
have_prev_odom_ = true;
|
|
latest_odom_ = o;
|
|
have_odom_ = true;
|
|
|
|
// ⚠️ CHOT ground truth NGAY DAY, cung luc voi EKF.
|
|
//
|
|
// `ekf_->pose()` la uoc luong tai thoi diem cap nhat NAY. Neu web doc
|
|
// ground truth TUOI luc chup snapshot roi dem so voi pose cu, thi cai
|
|
// do duoc khong phai sai so dinh vi ma la DO TRE nhan van toc.
|
|
//
|
|
// Do duoc: dung yen lech 0.0000 m; dang chay lech ti le thang voi toc
|
|
// do -- 0.018 m o 0.87 m/s, 0.044 m o 1.14 m/s, 0.118 m o 2.0 m/s.
|
|
// Chia ra la 20-60 ms, dung bang mot chu ky cam bien. Hinh ground
|
|
// truth xanh la vi the tach ra ngay khi robot vua chay, va nguoi van
|
|
// hanh tuong robot lac.
|
|
if (gt_fn_) {
|
|
gt_at_ekf_ = gt_fn_();
|
|
have_gt_at_ekf_ = true;
|
|
}
|
|
}
|
|
|
|
// gravity_align phai TRU gia toc rieng cua robot truoc khi coi phan con
|
|
// lai la trong luc. Khong co duong nay, moi lan tang toc bi hieu thanh
|
|
// mot cu nghieng -- da do tren robot that: bien do pitch 11.23 do thay
|
|
// vi 1.32 do, va cliff_detect bao vuc gia 1625/1832 mau.
|
|
//
|
|
// Goi NGOAI odom_mu_: PerceptionPipeline thuoc ve luong nay, khong can
|
|
// mutex, va giu lock khi goi code khac la cach tao ra deadlock.
|
|
perception_->FeedOdom(e.stamp, o.twist.twist.linear.x,
|
|
o.twist.twist.angular.z);
|
|
});
|
|
}
|
|
|
|
// ---------------- Camera ----------------
|
|
if (camera_ != nullptr) {
|
|
camera_->SetCallback([this](const CameraFrame& f) {
|
|
if (!f.depth) return;
|
|
|
|
// --- Latch cho SLAM 3D, TRUOC chuoi perception ---
|
|
//
|
|
// Tap thang vao CameraFrame tho: `depth_filter` chan 30 Hz xuong 10 Hz,
|
|
// nhung RTAB-Map tu bo khung bang RGBD/LinearUpdate va Rtabmap/DetectionRate,
|
|
// nen cho no khung day du va de no tu chon.
|
|
//
|
|
// Khong dung `approx_sync.h` o day co y: queue_size mac dinh 30 se ghim
|
|
// 30 khung librealsense, va `Fire()` goi callback tren CHINH luong goi
|
|
// Add() -- tuc chay Rtabmap::process() (100-600 ms) tren luong camera.
|
|
// SlamLoop von da la vong pull "scan moi nhat + odom moi nhat"; them
|
|
// "depth moi nhat" la cung mot hinh. Khi nao depth that su can XEP HANG
|
|
// thi moi quay lai approx_sync.
|
|
if (slam_use_depth_) {
|
|
std::lock_guard<std::mutex> lk(depth_mu_);
|
|
latest_depth_ = f.depth;
|
|
latest_infra1_ = f.infra1;
|
|
// CameraInfo nam trong CameraFrame theo VALUE -> phai dong hop de
|
|
// SlamLoop cam duoc con tro ra ngoai lock.
|
|
latest_depth_info_ = std::make_shared<const CameraInfo>(f.depth_info);
|
|
latest_depth_stamp_ = f.header.stamp;
|
|
// Qua atomic, khong doc thang GravityAlign: tren --live camera va IMU
|
|
// chay tren HAI luong khac nhau.
|
|
latest_depth_roll_ = tilt_roll_.load(std::memory_order_relaxed);
|
|
latest_depth_pitch_ = tilt_pitch_.load(std::memory_order_relaxed);
|
|
have_depth_ = true;
|
|
}
|
|
|
|
// Ca chuoi perception chay INLINE o day: depth -> cloud -> loc ->
|
|
// can trong luc -> phat hien vuc. Mot loi goi ham, tren chinh luong
|
|
// camera.
|
|
const PerceptionOutput po = perception_->Process(*f.depth, f.depth_info);
|
|
|
|
std::lock_guard<std::mutex> lk(perc_mu_);
|
|
// ⚠️ CHI ghi de khi CO cloud that. `po.cloud_aligned` la null o moi
|
|
// khung bi depth_filter chan (30 Hz vao, 10 Hz ra); gan null vao day la
|
|
// xoa mat dam may cuoi cung con dung.
|
|
//
|
|
// Da do: WebLoop chay 10 Hz, DUNG BANG nhip ra cua bo loc, nen hai ben
|
|
// khoa pha -- co luc WebLoop luon doc trung khoang null va web khong co
|
|
// cloud nao suot 14 giay lien (log "cloud: tuoi", trong tu 10:03:26 den
|
|
// 10:03:40). Man hinh giu dam may cu, nguoi lai thay "cloud tut sau
|
|
// scan". Do tre khong nam o duong ong -- duong ong cho ra cloud chi 25-50
|
|
// ms tuoi -- no nam o day.
|
|
if (po.cloud_aligned) latest_cloud_ = po.cloud_aligned;
|
|
latest_cliff_cloud_ = po.cloud_cliff;
|
|
cliff_flag_ = po.cliff_detected;
|
|
cliff_stamp_ = po.stamp;
|
|
cliff_detail_ = po.cliff_detail;
|
|
have_cliff_ = true;
|
|
});
|
|
}
|
|
|
|
// ---------------- Web ----------------
|
|
WebConfig wc = cfg_->web;
|
|
if (opts_.port_override != 0) wc.port = opts_.port_override;
|
|
if (!opts_.token_override.empty()) wc.auth_token = opts_.token_override;
|
|
|
|
web_.reset(new WebServer(
|
|
wc,
|
|
// --- Lenh POST /api/* ---
|
|
[this](const std::string& cmd, const std::string& body) -> StatusResponse {
|
|
if (cmd == "safety/estop") {
|
|
bool on = false;
|
|
if (!JsonGetBool(body, "on", &on)) {
|
|
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
|
"can truong bool \"on\"");
|
|
}
|
|
estop_.store(on);
|
|
{
|
|
std::lock_guard<std::mutex> lk(safety_mu_);
|
|
safety_->SetEstop(on);
|
|
}
|
|
// KHONG tu goi SetVelocity: luong safety thay co va zero lenh trong
|
|
// vong mot chu ky (50 ms). Mot duong duy nhat toi base, ke ca o
|
|
// duong khan cap -- hai duong nghia la hai cho de sai.
|
|
return StatusResponse::Ok();
|
|
}
|
|
if (cmd == "safety/reset") {
|
|
estop_.store(false);
|
|
std::lock_guard<std::mutex> lk(safety_mu_);
|
|
safety_->SetEstop(false);
|
|
safety_->Reset();
|
|
return StatusResponse::Ok();
|
|
}
|
|
if (cmd == "teleop/adjust") {
|
|
std::string axis;
|
|
double dir = 0.0;
|
|
if (!JsonGetString(body, "axis", &axis) ||
|
|
!JsonGetNumber(body, "dir", &dir)) {
|
|
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
|
"can \"axis\" va \"dir\"");
|
|
}
|
|
std::lock_guard<std::mutex> lk(teleop_mu_);
|
|
if (axis == "lin") teleop_->AdjustLinearSpeed(dir);
|
|
else if (axis == "ang") teleop_->AdjustAngularSpeed(dir);
|
|
else {
|
|
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
|
"axis phai la \"lin\" hoac \"ang\"");
|
|
}
|
|
return StatusResponse::Ok();
|
|
}
|
|
// Dat THANG gia tri, thay vi cong don tung buoc.
|
|
//
|
|
// ⚠️ `teleop/adjust` di mot buoc 0.05 m/s. Tu mac dinh 0.30 len tran
|
|
// 2.00 la **34 lan bam** -- nguoi van hanh bam vai cai, thay van cham,
|
|
// roi ket luan la lenh khong an. Da xay ra that.
|
|
if (cmd == "teleop/set") {
|
|
std::string axis;
|
|
double value = 0.0;
|
|
if (!JsonGetString(body, "axis", &axis) ||
|
|
!JsonGetNumber(body, "value", &value)) {
|
|
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
|
"can \"axis\" va \"value\"");
|
|
}
|
|
std::lock_guard<std::mutex> lk(teleop_mu_);
|
|
// Model tu kep vao [min, max]; khong kep o day de chi co MOT cho
|
|
// giu gioi han.
|
|
if (axis == "lin") teleop_->SetLinearSpeed(value);
|
|
else if (axis == "ang") teleop_->SetAngularSpeed(value);
|
|
else {
|
|
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
|
"axis phai la \"lin\" hoac \"ang\"");
|
|
}
|
|
return StatusResponse::Ok();
|
|
}
|
|
return StatusResponse::Error(StatusCode::kNotFound, "lenh la");
|
|
},
|
|
|
|
// --- Joypad qua WebSocket ---
|
|
[this](double vx_norm, double wz_norm) {
|
|
if (estop_.load()) {
|
|
std::lock_guard<std::mutex> lk(teleop_mu_);
|
|
teleop_->ClearMotion();
|
|
return;
|
|
}
|
|
|
|
// Truc joystick cua trang web dung quy uoc cua TeleopModel:
|
|
// vertical duong = keo XUONG = lui
|
|
// horizontal duong = keo PHAI = quay phai
|
|
// app.js gui theo chieu NGUOI LAI (duong = tien/trai), nen doi dau o
|
|
// day. Doi dau o MOT cho, khong rai rac hai phia.
|
|
std::pair<double, double> c;
|
|
{
|
|
std::lock_guard<std::mutex> lk(teleop_mu_);
|
|
teleop_->SetJoystick(-wz_norm, -vx_norm);
|
|
c = teleop_->Command();
|
|
}
|
|
|
|
// CHI ghi lai lenh THO. Viec danh gia an toan do LUONG SAFETY lam, o
|
|
// 20 Hz tren dong ho cua no.
|
|
//
|
|
// Goi Step() ngay o day la sai: FSM se chi chay khi CO lenh toi, ma
|
|
// NO_CMD / SCAN_TIMEOUT / cliff_hold ton tai chinh xac cho truong hop
|
|
// lenh NGUNG toi. Da mac loi nay mot lan.
|
|
std::lock_guard<std::mutex> lk(cmd_mu_);
|
|
raw_cmd_.linear.x = c.first;
|
|
raw_cmd_.angular.z = c.second;
|
|
raw_cmd_stamp_ = clock_->Now();
|
|
have_raw_cmd_ = true;
|
|
}));
|
|
|
|
// ---------------- Tay cam ----------------
|
|
//
|
|
// Duong thu hai cua LENH, va no di y het duong cua web: tinh ra van toc roi
|
|
// ghi `raw_cmd_`. KHONG co nhanh nao cho tay cam goi thang `SetVelocity` --
|
|
// lenh tu tay cam van phai qua FSM an toan nhu moi lenh khac.
|
|
//
|
|
// ⚠️ KHAC base_kit o day, va khac co y: ben do `/joy/cmd_vel` di thang toi
|
|
// `zlac_ros_node`, khong co lop an toan nao o giua. Hau qua thuc te: day can
|
|
// het co ma truoc mat co vat can trong `slow_distance` (0.80 m) thi xe VAN
|
|
// cham lai, trong `stop_distance` (0.35 m) thi VAN dung. Nguoi quen lai
|
|
// base_kit se thay "tay cam bi hut mat", va do la lop an toan dang lam viec.
|
|
//
|
|
// Viec bom lenh nam o `GamepadLoop()`, khong phai o day: joydev khong co
|
|
// nhip, nen khong co callback nao de treo vao.
|
|
{
|
|
GamepadConfig gc = cfg_->gamepad;
|
|
if (opts_.gamepad_override > 0) gc.enabled = true;
|
|
if (opts_.gamepad_override < 0) gc.enabled = false;
|
|
if (!opts_.gamepad_device.empty()) gc.device = opts_.gamepad_device;
|
|
if (gc.enabled) {
|
|
gamepad_.reset(new GamepadReader(gc, clock_));
|
|
gamepad_map_.reset(new GamepadMapper(gc));
|
|
gamepad_rate_hz_ = gc.publish_rate_hz;
|
|
}
|
|
}
|
|
|
|
return StatusResponse::Ok();
|
|
}
|
|
|
|
} // namespace vslam
|