upload
This commit is contained in:
846
app/src/runtime.cc
Normal file
846
app/src/runtime.cc
Normal file
@@ -0,0 +1,846 @@
|
||||
#include "runtime.h"
|
||||
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
|
||||
#include "vslam/clock.h"
|
||||
#include "vslam/geometry.h"
|
||||
#include "vslam/log.h"
|
||||
#include "vslam/node_constants.h"
|
||||
#include "vslam/replay_source.h"
|
||||
#include "vslam/sim_source.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// Giu nguon song. Mot trong hai con tro khac null; `vslam_node` chi cham vao
|
||||
// cac interface, khong cham vao kieu cu the.
|
||||
struct Runtime::SourceHolder {
|
||||
std::unique_ptr<SimSource> sim;
|
||||
std::unique_ptr<ReplaySource> replay;
|
||||
};
|
||||
|
||||
Runtime::Runtime(AppConfig* cfg, RuntimeOptions opts)
|
||||
: cfg_(cfg), opts_(std::move(opts)), source_(new SourceHolder) {}
|
||||
|
||||
Runtime::~Runtime() {
|
||||
RequestStop();
|
||||
Join();
|
||||
}
|
||||
|
||||
StatusResponse Runtime::OpenSource() {
|
||||
switch (opts_.source) {
|
||||
case SourceKind::kSim: {
|
||||
SimConfig sc;
|
||||
sc.map_yaml = opts_.map_yaml;
|
||||
sc.world_path = opts_.world_path;
|
||||
sc.start_x = opts_.sim_start_x;
|
||||
sc.start_y = opts_.sim_start_y;
|
||||
sc.start_yaw = opts_.sim_start_yaw;
|
||||
|
||||
// Hinh hoc lay tu robot.yaml, KHONG go tay. Neu sim dung mot bo so va
|
||||
// duong ong dung bo khac thi moi phep do deu do nham.
|
||||
const RobotGeometry& g = cfg_->robot.geometry();
|
||||
sc.wheel_radius = g.wheel_radius;
|
||||
sc.wheel_separation = g.wheel_separation;
|
||||
sc.robot_radius = g.robot_radius;
|
||||
sc.camera_z = cfg_->robot.camera_height_above_floor();
|
||||
sc.camera_pitch = cfg_->robot.camera_pitch();
|
||||
sc.max_linear = speed_limit_;
|
||||
sc.max_angular = cfg_->robot.base().max_angular;
|
||||
sc.accel_limit = cfg_->robot.base().accel_limit;
|
||||
sc.lidar_rate_hz = cfg_->sensors.lidar_hz;
|
||||
sc.camera_rate_hz = cfg_->sensors.camera_hz;
|
||||
sc.imu_rate_hz = cfg_->sensors.imu_hz;
|
||||
sc.enable_depth_camera = cfg_->sensors.camera_enable;
|
||||
|
||||
Transform t;
|
||||
if (cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &t)) {
|
||||
sc.lidar_x = t.translation.x;
|
||||
}
|
||||
if (cfg_->robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t)) {
|
||||
sc.camera_x = t.translation.x;
|
||||
}
|
||||
|
||||
source_->sim.reset(new SimSource(sc));
|
||||
const StatusResponse st = source_->sim->Open();
|
||||
if (!st.ok()) return st;
|
||||
|
||||
if (opts_.sim_glass_at != 0.0) {
|
||||
// Buc kinh chan ngang hanh lang. Phai danh dau o DA BI CHIEM, nen
|
||||
// chen tuong truoc roi moi danh dau la kinh.
|
||||
const double gx = opts_.sim_glass_at;
|
||||
OccupancyGrid m = source_->sim->map();
|
||||
const double res = m.resolution;
|
||||
const int cx = static_cast<int>((gx - m.origin.position.x) / res);
|
||||
for (int cy = 0; cy < static_cast<int>(m.height); ++cy) {
|
||||
if (cx >= 0 && cx < static_cast<int>(m.width)) {
|
||||
const size_t i = static_cast<size_t>(cy) * m.width + cx;
|
||||
if (m.data[i] == 0) m.data[i] = 100; // chi lap cho TRONG
|
||||
}
|
||||
}
|
||||
source_->sim->SetMapForTest(m);
|
||||
source_->sim->SetGlass(gx - res, -50.0, gx + res, 50.0, true);
|
||||
VSLAM_WARN("sim: dat buc KINH o x = " << gx
|
||||
<< " m. LiDAR va depth se KHONG thay no -- chi sieu am va "
|
||||
"bumper thay.");
|
||||
}
|
||||
lidar_ = source_->sim->lidar();
|
||||
camera_ = source_->sim->camera();
|
||||
mcu_ = source_->sim->mcu();
|
||||
base_ = source_->sim->base();
|
||||
clock_ = source_->sim->clock();
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
case SourceKind::kReplay: {
|
||||
ReplayConfig rc;
|
||||
rc.path = opts_.replay_path;
|
||||
// KHONG tat dinh o day, khac voi `tools/vslam_replay`: node nay chay
|
||||
// voi web UI va nguoi dung dang nhin, nen phat theo thoi gian that.
|
||||
rc.deterministic = false;
|
||||
rc.apply_sanitizer = false; // node tu ve sinh, dung CHINH mot doi tuong
|
||||
source_->replay.reset(new ReplaySource(rc));
|
||||
const StatusResponse st = source_->replay->Open();
|
||||
if (!st.ok()) return st;
|
||||
lidar_ = source_->replay->lidar();
|
||||
camera_ = source_->replay->camera();
|
||||
mcu_ = source_->replay->mcu();
|
||||
base_ = source_->replay->base();
|
||||
clock_ = source_->replay->clock();
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
case SourceKind::kLive:
|
||||
// Noi thang: driver LakiBeam / RealSense / base chua viet, va chung bi
|
||||
// chan boi thong tin chua co (byte layout goi UDP, giao thuc encoder
|
||||
// cua base), khong phai boi thoi gian.
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kUnavailable,
|
||||
"che do --live chua chay duoc: driver LakiBeam, RealSense va base "
|
||||
"chua viet. Chung bi chan boi thong tin phan cung chua co -- xem "
|
||||
"README muc \"P2 lam duoc den dau\". Dung --sim hoac --replay.");
|
||||
}
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument, "nguon la");
|
||||
}
|
||||
|
||||
void Runtime::ApplyThreadPriority(std::thread* t, int prio, const char* name) {
|
||||
if (!cfg_->threads.use_realtime) return;
|
||||
|
||||
sched_param sp{};
|
||||
sp.sched_priority = prio;
|
||||
const int rc = pthread_setschedparam(t->native_handle(), SCHED_FIFO, &sp);
|
||||
if (rc != 0) {
|
||||
// KHONG tu choi khoi dong. Thieu CAP_SYS_NICE la chuyen binh thuong khi
|
||||
// chay tu terminal cua nguoi phat trien; robot van chay dung, chi la
|
||||
// jitter cao hon. Tu choi khoi dong o day se khien moi nguoi chay bang
|
||||
// sudo, va do moi la thu nguy hiem.
|
||||
VSLAM_WARN("luong " << name << ": khong dat duoc SCHED_FIFO " << prio << " ("
|
||||
<< std::strerror(rc)
|
||||
<< "). Chay voi uu tien mac dinh -- can CAP_SYS_NICE hoac "
|
||||
"/etc/security/limits.conf.");
|
||||
}
|
||||
}
|
||||
|
||||
StatusResponse Runtime::Start() {
|
||||
// Ghi de tran toc do TRUOC khi mo nguon: `OpenSource()` chep gioi han base
|
||||
// sang `SimConfig`, nen sua sau do se khong toi duoc bo mo phong.
|
||||
//
|
||||
// Ghi de CA BA cho, vi lenh di qua ca ba:
|
||||
// teleop (tran scale) -> safety (kep) -> base cua sim (kep lan nua)
|
||||
// Bo sot mot cho la so tren man hinh len 2.0 con robot van chay 0.35.
|
||||
if (opts_.max_speed_override > 0.0) {
|
||||
const double v = opts_.max_speed_override;
|
||||
VSLAM_WARN("toc do: ghi de tran len " << v
|
||||
<< " m/s (robot.yaml co " << cfg_->robot.base().max_linear
|
||||
<< "). ⚠️ CHI CHO MO PHONG -- base that khong chay nhanh hon "
|
||||
"duoc, day chi la de quet nhanh.");
|
||||
cfg_->safety.max_linear = v;
|
||||
// `RobotModel` khong cho sua truc tiep (co y: no la nguon su that tu
|
||||
// robot.yaml). Gia tri cho sim va teleop lay tu bien duoi day.
|
||||
speed_limit_ = v;
|
||||
} else {
|
||||
speed_limit_ = cfg_->robot.base().max_linear;
|
||||
}
|
||||
|
||||
{
|
||||
const StatusResponse st = OpenSource();
|
||||
if (!st.ok()) return st;
|
||||
}
|
||||
|
||||
sanitizer_.reset(new ScanSanitizer(cfg_->sanitizer));
|
||||
wheel_odom_.reset(new WheelOdometry(cfg_->wheel_odom));
|
||||
ekf_.reset(new EkfSe2(cfg_->ekf));
|
||||
safety_.reset(new SafetyMonitor(cfg_->safety));
|
||||
|
||||
// ============ GIEO POSE XUAT PHAT KHI CHAY MO PHONG ============
|
||||
//
|
||||
// Odometry luon khoi tao o GOC. Tren robot that do la dung: frame `odom` co
|
||||
// goc o cho robot vua khoi dong, va SLAM keo no ve khop ban do qua
|
||||
// `map->odom`.
|
||||
//
|
||||
// Trong mo phong thi KHAC: ban do (vd hospital.yaml) o mot he toa do CO
|
||||
// DINH, va `--x --y` dat robot vao mot cho cu the trong do. Neu odometry
|
||||
// van bat dau o (0,0) thi:
|
||||
// * robot uoc luong ve o (0,0) -- mot phong khac han cho no dang dung;
|
||||
// * ban do SLAM dung ra cung o goc (0,0), nen LECH voi ban do the gioi
|
||||
// dung bang vi tri xuat phat.
|
||||
// Da do: pose (0.00, 0.00) trong khi ground truth (-5.99, -2.91).
|
||||
//
|
||||
// Gieo pose xuat phat la tuong duong mo phong cua "robot biet no khoi dong
|
||||
// o dau" -- tren phan cung that do la viec cua dock, xem --slam-init-pose.
|
||||
if (opts_.source == SourceKind::kSim &&
|
||||
(opts_.sim_start_x != 0.0 || opts_.sim_start_y != 0.0 ||
|
||||
opts_.sim_start_yaw != 0.0)) {
|
||||
Pose2D start;
|
||||
start.x = opts_.sim_start_x;
|
||||
start.y = opts_.sim_start_y;
|
||||
start.theta = opts_.sim_start_yaw;
|
||||
wheel_odom_->SetPose(start);
|
||||
ekf_->SetPose(start);
|
||||
VSLAM_INFO("sim: gieo pose xuat phat (" << start.x << ", " << start.y << ", "
|
||||
<< start.theta << ") vao odometry va EKF -- de uoc luong nam "
|
||||
"dung cho tren ban do the gioi.");
|
||||
}
|
||||
|
||||
// Gioi han tren cua scale teleop lay tu robot.yaml: nguoi lai khong duoc
|
||||
// chinh len qua gioi han co hoc cua base. Lop safety van kep lan nua --
|
||||
// hai lop, co y.
|
||||
TeleopConfig tc;
|
||||
tc.max_linear_speed = speed_limit_;
|
||||
tc.max_angular_speed = cfg_->robot.base().max_angular;
|
||||
teleop_.reset(new TeleopModel(tc));
|
||||
|
||||
perception_.reset(new PerceptionPipeline(cfg_->perception, *clock_));
|
||||
{
|
||||
Transform cam_to_base;
|
||||
if (!cfg_->robot.StaticTransform(kBaseLinkFrame, kCameraDepthOpticalFrame,
|
||||
&cam_to_base)) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"robot.yaml: khong co duong camera_depth_optical_frame -> base_link");
|
||||
}
|
||||
perception_->SetCameraExtrinsic(cam_to_base);
|
||||
}
|
||||
|
||||
#ifdef VSLAM_HAVE_SLAM
|
||||
if (cfg_->slam.enabled || opts_.force_slam) {
|
||||
RtabmapConfig sc = cfg_->slam;
|
||||
if (opts_.have_slam_db) sc.database_path = opts_.slam_db;
|
||||
if (opts_.slam_mode_override == "mapping") sc.mode = SlamMode::kMapping;
|
||||
else if (opts_.slam_mode_override == "localization") sc.mode = SlamMode::kLocalization;
|
||||
slam_.reset(new RtabmapSlam);
|
||||
const StatusResponse st = slam_->Init(sc);
|
||||
if (!st.ok()) {
|
||||
// KHONG chay tiep im lang. Nguoi van hanh bat SLAM len va phai biet no
|
||||
// khong len duoc -- chay tiep ma khong co SLAM trong khi ho tuong co la
|
||||
// dung kieu hong `--sim` mac dinh sinh ra de tranh.
|
||||
return StatusResponse::Error(st.code, "slam: " + st.message);
|
||||
}
|
||||
slam_enabled_ = true;
|
||||
slam_mode_ = sc.mode;
|
||||
|
||||
// Chi LUU o che do mapping va khi co duong dan that.
|
||||
//
|
||||
// ⚠️ `RtabmapSlam::~RtabmapSlam()` goi `Close(false)` -- VUT BO ban do.
|
||||
// Khong goi Close(true) tuong minh thi mot phien quet dai xong se khong
|
||||
// de lai gi, va khong co loi nao: file .db van ton tai, chi la trong.
|
||||
//
|
||||
// O che do localization thi KHONG luu: ghi phien dinh vi vao ban do da
|
||||
// quet se lam ban do phinh dan moi lan chay, va khong ai co y do do.
|
||||
slam_should_save_ =
|
||||
(sc.mode == SlamMode::kMapping) && !sc.database_path.empty();
|
||||
if (slam_should_save_) {
|
||||
VSLAM_INFO("slam: che do mapping, se LUU vao " << sc.database_path
|
||||
<< " khi thoat (Ctrl-C).");
|
||||
} else if (sc.mode == SlamMode::kMapping) {
|
||||
VSLAM_WARN("slam: che do mapping nhung database_path de RONG -- ban do "
|
||||
"chi nam trong RAM va se MAT khi thoat. Dat --slam-db PATH "
|
||||
"de luu.");
|
||||
}
|
||||
|
||||
// --- Pose ban dau cho localization ---
|
||||
//
|
||||
// ⚠️ RTAB-Map KHONG dinh vi toan cuc duoc bang scan khong. Vong dong toan
|
||||
// cuc di qua tui tu thi giac; `RGBD/ProximityBySpace` chi tim trong mot
|
||||
// ban kinh quanh uoc luong HIEN TAI. Va o che do localization no khoi
|
||||
// dong tu pose CUOI CUNG cua phien quet, khong phai tu goc.
|
||||
//
|
||||
// Khong dat pose ban dau thi robot vat ly o (0,0) con RTAB-Map tuong no o
|
||||
// cuoi quy dao da quet. Do duoc: sai so 1.08 m, va `localized` VAN bao
|
||||
// true -- mot kieu hong trong y het "dang chay tot".
|
||||
//
|
||||
// He that giai quyet dung nhu vay: `dock_init.py` phat /initialpose tu
|
||||
// dock. Robot LUON biet no bat dau o dau.
|
||||
// Ca MAPPING lan LOCALIZATION deu can pose ban dau khi chay mo phong tren
|
||||
// mot ban do co san.
|
||||
//
|
||||
// Mapping: RTAB-Map dung ban do trong frame rieng, goc o pose ban dau. De
|
||||
// no o (0,0) trong khi robot dang o (-5.99, -2.91) thi ban do SLAM LECH
|
||||
// voi ban do the gioi dung bang vi tri xuat phat -- hai khung o che do
|
||||
// "chia doi" khong con chong khop duoc.
|
||||
if (sc.mode == SlamMode::kLocalization || opts_.have_slam_init_pose ||
|
||||
opts_.source == SourceKind::kSim) {
|
||||
Pose2D init;
|
||||
const char* src = nullptr;
|
||||
if (opts_.have_slam_init_pose) {
|
||||
init = opts_.slam_init_pose;
|
||||
src = "--slam-init-pose";
|
||||
} else if (opts_.source == SourceKind::kSim) {
|
||||
// Trong mo phong, "dock" la vi tri xuat phat. Noi RO day la mot
|
||||
// tien nghi cua mo phong, khong phai thu robot that co mien phi.
|
||||
init.x = opts_.sim_start_x;
|
||||
init.y = opts_.sim_start_y;
|
||||
init.theta = opts_.sim_start_yaw;
|
||||
src = "vi tri xuat phat cua mo phong (thay cho dock)";
|
||||
}
|
||||
if (src != nullptr) {
|
||||
slam_->SetInitialPose(init);
|
||||
VSLAM_INFO("slam: pose ban dau (" << init.x << ", " << init.y << ", "
|
||||
<< init.theta << ") tu " << src);
|
||||
} else {
|
||||
VSLAM_WARN("slam: che do localization nhung KHONG co pose ban dau. "
|
||||
"RTAB-Map khong dinh vi toan cuc duoc bang scan khong -- "
|
||||
"no se khoi dong tu pose CUOI cua phien quet va gan nhu "
|
||||
"chac chan sai. Dung --slam-init-pose x,y,yaw.");
|
||||
}
|
||||
}
|
||||
|
||||
Transform laser_to_base = TransformIdentity();
|
||||
if (!cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &laser_to_base)) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"robot.yaml: khong co duong laser -> base_link");
|
||||
}
|
||||
// Quen cai nay la moi scan bi dat lech 24 cm so voi pose. ICP van hoi tu
|
||||
// (no chi thay ca the gioi dich di) nhung do thi tich luy sai so: da do
|
||||
// ATE 0.2378 m thay vi 0.0146 m tren map_house.db, khong mot loi nao.
|
||||
Transform cam_to_base = TransformIdentity();
|
||||
cfg_->robot.StaticTransform(kBaseLinkFrame, kCameraDepthOpticalFrame, &cam_to_base);
|
||||
slam_->SetExtrinsics(laser_to_base, cam_to_base);
|
||||
}
|
||||
#else
|
||||
if (opts_.force_slam) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kUnavailable,
|
||||
"--slam: binary nay build KHONG kem vslam_slam. Build lai voi "
|
||||
"-DVSLAM_BUILD_SLAM=ON.");
|
||||
}
|
||||
#endif
|
||||
|
||||
{
|
||||
const StatusResponse st = Wire();
|
||||
if (!st.ok()) return st;
|
||||
}
|
||||
|
||||
if (lidar_ != nullptr) lidar_->Open();
|
||||
if (mcu_ != nullptr) mcu_->Open();
|
||||
if (base_ != nullptr) base_->Open();
|
||||
if (camera_ != nullptr) camera_->Open();
|
||||
|
||||
// Hinh hoc 3D cua the gioi -- chi co khi chay tu file `.world`.
|
||||
//
|
||||
// Dung mesh HIEN THI chu khong phai mesh va cham: khung 3D de nguoi van hanh
|
||||
// NHAN RA cho dung, va mesh va cham cua bo model nay la khoi hop tho. 6.7 MB
|
||||
// tho (~1.4 MB sau nen) tai MOT lan luc mo trang.
|
||||
if (source_->sim != nullptr && !opts_.world_path.empty()) {
|
||||
WorldMeshes wm;
|
||||
const StatusResponse st = ExportWorldMeshes(source_->sim->world(),
|
||||
/*visual=*/true, &wm);
|
||||
if (st.ok()) {
|
||||
const size_t n_col = ApplyModelColors(ResourcePath("model_colors.json"),
|
||||
&wm);
|
||||
std::string blob;
|
||||
EncodeWorldMeshes(wm, &blob);
|
||||
VSLAM_INFO("web: hinh hoc 3D " << wm.geoms.size() << " hinh hoc ("
|
||||
<< n_col << " co mau), " << wm.instances.size()
|
||||
<< " the hien, " << (blob.size() / 1048576.0) << " MB");
|
||||
web_->SetWorldMesh(std::move(blob));
|
||||
} else {
|
||||
VSLAM_WARN("web: khong xuat duoc hinh hoc 3D (" << st.message
|
||||
<< ") -- khung 3D se dung khoi hop dung tu luoi");
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
const StatusResponse st = web_->Start();
|
||||
if (!st.ok()) return st;
|
||||
}
|
||||
|
||||
// --- Luong ---
|
||||
source_thread_ = std::thread([this] {
|
||||
if (source_->sim) source_->sim->Run();
|
||||
else if (source_->replay) {
|
||||
source_->replay->Run();
|
||||
// Ban ghi het la mot su kien, khong phai mot trang thai im lang. Khong
|
||||
// noi ra thi no giong het "replay bi treo o khung cuoi".
|
||||
const ReplaySource::Stats st = source_->replay->stats();
|
||||
VSLAM_INFO("replay: het ban ghi -- " << st.chunks << " chunk trong "
|
||||
<< st.duration_sec << " s"
|
||||
<< (st.truncated ? " (FILE BI CAT GIUA CHUNG)" : "")
|
||||
<< ". Node van chay; Ctrl-C de dung.");
|
||||
}
|
||||
});
|
||||
ApplyThreadPriority(&source_thread_, cfg_->threads.driver_priority, "source");
|
||||
|
||||
safety_thread_ = std::thread([this] { SafetyLoop(); });
|
||||
ApplyThreadPriority(&safety_thread_, cfg_->threads.safety_priority, "safety");
|
||||
|
||||
if (slam_enabled_) {
|
||||
slam_thread_ = std::thread([this] { SlamLoop(); });
|
||||
// CFS, KHONG realtime. Luong nay chan hang tram ms; cho no uu tien cao la
|
||||
// cach chac chan nhat de treo vong an toan.
|
||||
}
|
||||
|
||||
web_thread_ = std::thread([this] { WebLoop(); });
|
||||
// web_tx chay CFS: no khong o trong vong an toan, va nang no len se lay mat
|
||||
// CPU cua luong dang giu robot khong dam vao tuong.
|
||||
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
void Runtime::RequestStop() {
|
||||
stop_.store(true);
|
||||
if (source_->sim) source_->sim->RequestStop();
|
||||
if (source_->replay) source_->replay->RequestStop();
|
||||
}
|
||||
|
||||
void Runtime::Join() {
|
||||
if (safety_thread_.joinable()) safety_thread_.join();
|
||||
if (web_thread_.joinable()) web_thread_.join();
|
||||
if (slam_thread_.joinable()) slam_thread_.join();
|
||||
if (source_thread_.joinable()) source_thread_.join();
|
||||
|
||||
// Dung base TRUOC khi dong web: neu dong web truoc thi trong khoang giua,
|
||||
// khong con ai gui lenh nhung robot van con van toc cuoi cung.
|
||||
if (base_ != nullptr) base_->SetVelocity(0.0, 0.0);
|
||||
|
||||
#ifdef VSLAM_HAVE_SLAM
|
||||
if (slam_) {
|
||||
const StatusResponse st = slam_->Close(slam_should_save_);
|
||||
if (!st.ok()) {
|
||||
VSLAM_ERROR("slam: dong that bai: " << st.message);
|
||||
} else if (slam_should_save_) {
|
||||
VSLAM_INFO("slam: da luu ban do.");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if (web_) web_->Stop();
|
||||
}
|
||||
|
||||
void Runtime::SafetyLoop() {
|
||||
// Chu ky theo STEADY CLOCK, khong theo UnixTime.
|
||||
//
|
||||
// `safety_monitor_node.cpp` cua ban ROS dung ros::Time::now() cho ca dau
|
||||
// thoi gian lan chu ky. Mot buoc NTP sau khi Jetson bat WiFi lam
|
||||
// (now - last_cmd_time) nhay vot -> NO_CMD dung robot dot ngot, hoac nhay
|
||||
// lui -> watchdog khong bao gio kich.
|
||||
const auto period = std::chrono::duration<double>(
|
||||
cfg_->threads.safety_rate_hz > 0.0 ? 1.0 / cfg_->threads.safety_rate_hz : 0.05);
|
||||
auto next = std::chrono::steady_clock::now();
|
||||
|
||||
while (!stop_.load()) {
|
||||
SafetyInputs si;
|
||||
si.now = clock_->Now();
|
||||
|
||||
Twist cmd_copy;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(cmd_mu_);
|
||||
if (have_raw_cmd_) {
|
||||
cmd_copy = raw_cmd_;
|
||||
si.cmd = &cmd_copy;
|
||||
si.cmd_stamp = raw_cmd_stamp_;
|
||||
}
|
||||
}
|
||||
|
||||
LaserScanPtr scan_copy;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(scan_mu_);
|
||||
scan_copy = latest_scan_;
|
||||
}
|
||||
if (scan_copy) {
|
||||
si.scan = scan_copy.get();
|
||||
si.scan_stamp = scan_copy->header.stamp;
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mcu_mu_);
|
||||
if (have_us_) {
|
||||
si.ultrasonic = ultrasonic_;
|
||||
si.us_stamp = us_stamp_;
|
||||
}
|
||||
if (have_bumper_) {
|
||||
si.have_bumper = true;
|
||||
si.bumper = bumper_;
|
||||
si.bumper_stamp = bumper_stamp_;
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(perc_mu_);
|
||||
if (have_cliff_) {
|
||||
si.have_cliff = true;
|
||||
si.cliff = cliff_flag_;
|
||||
si.cliff_stamp = cliff_stamp_;
|
||||
// "judged" = detector THUC SU phan xet duoc; con lai la fail-safe
|
||||
// luc mu. FSM xu ly hai truong hop nay khac nhau -- xem nhanh 4.
|
||||
si.cliff_judged = (cliff_detail_ == "judged");
|
||||
si.cliff_window_min = cfg_->perception.cliff.min_dist;
|
||||
}
|
||||
}
|
||||
|
||||
SafetyOutput so;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(safety_mu_);
|
||||
so = safety_->Step(si);
|
||||
last_safety_ = so;
|
||||
}
|
||||
|
||||
// DUONG DUY NHAT lenh toi duoc base. Khong co nhanh nao cho lenh di thang
|
||||
// xuong, ke ca teleop, ke ca e-stop.
|
||||
if (base_ != nullptr) base_->SetVelocity(so.cmd.linear.x, so.cmd.angular.z);
|
||||
|
||||
next += std::chrono::duration_cast<std::chrono::steady_clock::duration>(period);
|
||||
std::this_thread::sleep_until(next);
|
||||
}
|
||||
|
||||
if (base_ != nullptr) base_->SetVelocity(0.0, 0.0);
|
||||
}
|
||||
|
||||
void Runtime::SlamLoop() {
|
||||
#ifdef VSLAM_HAVE_SLAM
|
||||
// ============ QUY TAC SONG CON ============
|
||||
// `Rtabmap::process()` chan 100-600 ms (p95 do duoc 722-1008 ms tren may
|
||||
// dev). Vong nay KHONG duoc giu bat ky mutex nao trong luc goi no.
|
||||
//
|
||||
// Cach lam: copy dau vao duoi mutex (mot shared_ptr + mot Pose2D, vai chuc
|
||||
// nano giay), NHA, roi moi goi. Luong safety doc cung nhung mutex do va vi
|
||||
// the khong bao gio cho qua mot phep copy con tro.
|
||||
//
|
||||
// Trong ban ROS dieu nay duoc bao dam MIEN PHI boi tien trinh rieng. O day
|
||||
// no la quy tac review, va ThreadSanitizer la thu duy nhat kiem duoc.
|
||||
UnixTime last_used;
|
||||
bool have_last = false;
|
||||
// Chi phi lan xuat ban do gan nhat (trung binh truot). Dung de nhip theo
|
||||
// TAI THAT chu khong theo mot hang so -- xem khoi ben duoi.
|
||||
double map_export_cost_s_ = 0.0;
|
||||
constexpr double kMapExportDuty = 0.25; // toi da 25% luong slam
|
||||
auto last_map_build = std::chrono::steady_clock::time_point{};
|
||||
|
||||
while (!stop_.load()) {
|
||||
// --- Lay dau vao, KHONG giu lock lau ---
|
||||
LaserScanPtr scan;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(scan_mu_);
|
||||
scan = latest_scan_; // chi copy shared_ptr
|
||||
}
|
||||
Pose2D odom;
|
||||
bool have_odom = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(odom_mu_);
|
||||
odom = wheel_odom_->pose();
|
||||
have_odom = have_odom_;
|
||||
}
|
||||
|
||||
if (!scan || !have_odom ||
|
||||
(have_last && scan->header.stamp.toSec() <= last_used.toSec())) {
|
||||
// Chua co scan MOI. Ngu ngan roi thu lai -- khong ban chay vong.
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
||||
continue;
|
||||
}
|
||||
last_used = scan->header.stamp;
|
||||
have_last = true;
|
||||
|
||||
SlamInput in;
|
||||
in.stamp = scan->header.stamp;
|
||||
in.odom = odom;
|
||||
in.scan = scan.get();
|
||||
|
||||
// --- KHONG MOT MUTEX NAO duoc giu qua dong nay ---
|
||||
const SlamOutput out = slam_->Process(in);
|
||||
|
||||
bool need_map = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(slam_mu_);
|
||||
map_correction_ = out.map_correction;
|
||||
slam_localized_ = out.localized;
|
||||
slam_process_ms_ = out.process_ms;
|
||||
if (out.loop_closure_id > 0) slam_loops_++;
|
||||
need_map = out.map_version != slam_map_version_;
|
||||
slam_map_version_ = out.map_version;
|
||||
}
|
||||
|
||||
// Xuat ban do CHI khi do thi doi, VA khong qua `map_rebuild_rate_hz`.
|
||||
//
|
||||
// Chi kiem "do thi doi" la khong du: o che do mapping do thi doi o gan
|
||||
// nhu MOI khung, nen SlamLoop se dung lai ban do ~9 lan/giay. Da do
|
||||
// trong mo phong. `OccupancyGrid::update()` quet lai toan bo cache moi
|
||||
// lan (5.65 s cho 1990 node tren map_hospital.db), va tren ban do that
|
||||
// 2000x2000 thi 9 lan/giay la 221 kB/s -- gan gap doi ca ngan sach
|
||||
// 120 kB/s cua toan bo web UI.
|
||||
//
|
||||
// ============ NHIP THEO CHI PHI DO DUOC, KHONG THEO HANG SO ============
|
||||
//
|
||||
// Mot tan so co dinh sai o CA HAI dau:
|
||||
// * 0.5 Hz (ban truoc): do thi con nho, xuat het 20 ms, ma van bat nguoi
|
||||
// dung doi 2 giay moi lan -- khung SLAM trong nhu treo dung luc ho
|
||||
// muon nhin no day dan.
|
||||
// * 2 Hz co dinh: khi do thi len 1990 node thi `OccupancyGrid::update()`
|
||||
// mat 5.65 s, va luong slam khong con lam gi khac duoc.
|
||||
//
|
||||
// Nen nhip theo CHI PHI THAT: sau moi lan xuat, cho
|
||||
// nghi = thoi_gian_xuat * (1/duty - 1)
|
||||
// de viec dung ban do khong chiem qua `duty` phan luong slam. Do thi nho
|
||||
// -> gan nhu realtime; do thi lon -> tu dong lui ra.
|
||||
//
|
||||
// `map_rebuild_rate_hz` gio la TRAN, khong phai tan so co dinh.
|
||||
const auto now_wall = std::chrono::steady_clock::now();
|
||||
if (need_map) {
|
||||
const double since =
|
||||
std::chrono::duration<double>(now_wall - last_map_build).count();
|
||||
double wait = map_export_cost_s_ * (1.0 / kMapExportDuty - 1.0);
|
||||
if (cfg_->slam_runtime.map_rebuild_rate_hz > 0.0) {
|
||||
wait = std::max(wait, 1.0 / cfg_->slam_runtime.map_rebuild_rate_hz);
|
||||
}
|
||||
if (since < wait) need_map = false;
|
||||
}
|
||||
if (need_map) {
|
||||
last_map_build = now_wall;
|
||||
OccupancyGrid grid;
|
||||
const auto t_export = std::chrono::steady_clock::now();
|
||||
const StatusResponse st = slam_->ExportMap(&grid);
|
||||
const double cost =
|
||||
std::chrono::duration<double>(std::chrono::steady_clock::now() - t_export)
|
||||
.count();
|
||||
// Trung binh truot: mot lan xuat cham bat thuong khong duoc lam nhip
|
||||
// giat cuc, va chi phi that thi tang dan chu khong nhay.
|
||||
map_export_cost_s_ = 0.7 * map_export_cost_s_ + 0.3 * cost;
|
||||
|
||||
if (st.ok()) {
|
||||
// Dem NOI DUNG ban do, khong dem so lan xuat.
|
||||
//
|
||||
// Mot ban do TOAN O CHUA BIET co dung moi chi so van hanh voi mot ban
|
||||
// do dung: `ExportMap` tra ve ok, `map_version` tang deu, khung gui di
|
||||
// dung kich thuoc. Da mat nhieu lan do de tim ra `RGBD/CreateOccupancy
|
||||
// Grid` mac dinh la false, vi khong co gi dem noi dung ca.
|
||||
//
|
||||
// Ba con so nay noi ngay dieu do: 0 o trong nghia la tia khong duoc
|
||||
// truy (`Grid/RayTracing`), 0 o bi chiem nghia la khong co cam bien
|
||||
// nao nap vao (`Grid/Sensor`), va ca hai bang 0 nghia la ban do rong.
|
||||
size_t occ = 0, fre = 0, unk = 0;
|
||||
for (int8_t v : grid.data) {
|
||||
if (v < 0) unk++;
|
||||
else if (v >= 50) occ++;
|
||||
else fre++;
|
||||
}
|
||||
if (occ != last_map_occ_ || fre != last_map_free_) {
|
||||
VSLAM_INFO("slam: ban do " << grid.width << "x" << grid.height
|
||||
<< " -- " << occ << " bi chiem, " << fre << " trong, "
|
||||
<< unk << " chua biet");
|
||||
last_map_occ_ = occ;
|
||||
last_map_free_ = fre;
|
||||
}
|
||||
auto ptr = std::make_shared<const OccupancyGrid>(std::move(grid));
|
||||
std::lock_guard<std::mutex> lk(slam_mu_);
|
||||
slam_map_ = ptr;
|
||||
slam_published_version_ = slam_map_version_;
|
||||
}
|
||||
// Loi o day khong phai chuyen la: do thi co the chua co pose toi uu nao
|
||||
// o nhung khung dau. Khong log moi lan de khong lap day log.
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void Runtime::WebLoop() {
|
||||
const auto period = std::chrono::duration<double>(
|
||||
cfg_->web.state_hz > 0.0 ? 1.0 / cfg_->web.state_hz : 0.1);
|
||||
auto next = std::chrono::steady_clock::now();
|
||||
|
||||
OccupancyGridPtr map_ptr;
|
||||
if (source_->sim) {
|
||||
map_ptr = std::make_shared<const OccupancyGrid>(source_->sim->map());
|
||||
}
|
||||
|
||||
// Hinh hoc robot cho trinh ve 3D. Dung MOT lan -- `robot.yaml` khong doi
|
||||
// luc chay, va dung lai moi khung la 10 lan/giay lang phi.
|
||||
//
|
||||
// ⚠️ Moi so o day lay tu `RobotModel`, KHONG go tay. Truoc khoi nay app.js
|
||||
// hardcode `L = 0.30, W = 0.17` -- khong khop voi bat ky gia tri nao trong
|
||||
// robot.yaml, va khong ai phat hien vi mot tam giac sai kich thuoc van
|
||||
// trong "nhu that".
|
||||
RobotShape shape;
|
||||
{
|
||||
const RobotGeometry& g = cfg_->robot.geometry();
|
||||
shape.radius = g.robot_radius;
|
||||
shape.wheel_radius = g.wheel_radius;
|
||||
shape.wheel_separation = g.wheel_separation;
|
||||
shape.body_half_width = g.body_half_width;
|
||||
|
||||
Transform t;
|
||||
if (cfg_->robot.StaticTransform(kBaseLinkFrame, kLaserFrame, &t)) {
|
||||
shape.laser_x = t.translation.x;
|
||||
shape.laser_y = t.translation.y;
|
||||
shape.laser_z = t.translation.z;
|
||||
}
|
||||
if (cfg_->robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t)) {
|
||||
shape.camera_x = t.translation.x;
|
||||
shape.camera_y = t.translation.y;
|
||||
shape.camera_z = t.translation.z;
|
||||
}
|
||||
shape.camera_pitch = cfg_->robot.camera_pitch();
|
||||
shape.cliff_min = cfg_->perception.cliff.min_dist;
|
||||
shape.cliff_max = cfg_->perception.cliff.max_dist;
|
||||
shape.valid = true;
|
||||
// `camera_hfov`/`vfov` giu mac dinh D410 cho toi khi co CameraInfo THAT:
|
||||
// chung la thong so ONG KINH, khong suy ra duoc tu robot.yaml. Cap nhat
|
||||
// trong vong lap khi khung dau tien toi.
|
||||
}
|
||||
|
||||
while (!stop_.load()) {
|
||||
WebSnapshot snap;
|
||||
snap.robot = shape;
|
||||
snap.stamp = clock_->Now();
|
||||
Pose2D ekf_pose;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(odom_mu_);
|
||||
snap.pose_odom = wheel_odom_->pose();
|
||||
snap.slip_metric = wheel_odom_->slip_metric();
|
||||
if (have_odom_) {
|
||||
snap.vx = latest_odom_.twist.twist.linear.x;
|
||||
snap.vyaw = latest_odom_.twist.twist.angular.z;
|
||||
}
|
||||
snap.pose_odom = wheel_odom_->pose();
|
||||
ekf_pose = ekf_->pose();
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(scan_mu_);
|
||||
snap.scan = latest_scan_;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(perc_mu_);
|
||||
snap.cloud = latest_cloud_;
|
||||
|
||||
// So do CU khong duoc hien nhu so do MOI.
|
||||
//
|
||||
// Da mac: khi ban ghi phat het, `cliff_flag_` ket lai o gia tri cuoi va
|
||||
// web hien "VUC PHIA TRUOC" mai mai tu mot so do da 10 giay tuoi -- ke
|
||||
// ca khi FSM da bo qua no tu lau (cliff_timeout). Dung CHINH nguong ma
|
||||
// FSM dung, neu khong thi web va FSM noi hai chuyen khac nhau.
|
||||
const bool fresh =
|
||||
have_cliff_ &&
|
||||
SecondsBetween(snap.stamp, cliff_stamp_) <= cfg_->safety.cliff_timeout;
|
||||
snap.safety.cliff = fresh && cliff_flag_;
|
||||
if (!fresh) {
|
||||
snap.safety.detail = "cliff:stale";
|
||||
} else if (!cliff_detail_.empty() && cliff_detail_ != "judged") {
|
||||
snap.safety.detail = "cliff:" + cliff_detail_;
|
||||
}
|
||||
}
|
||||
// Doc tu atomic, KHONG goi thang vao GravityAlign: doi tuong do thuoc ve
|
||||
// luong source va dang duoc ghi o 200 Hz. Xem ghi chu o runtime.h.
|
||||
snap.roll = tilt_roll_.load(std::memory_order_relaxed);
|
||||
snap.pitch = tilt_pitch_.load(std::memory_order_relaxed);
|
||||
snap.accel_ok = tilt_accel_ok_.load(std::memory_order_relaxed);
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(safety_mu_);
|
||||
snap.safety.state = SafetyStateName(last_safety_.state);
|
||||
if (snap.safety.detail.empty()) snap.safety.detail = last_safety_.detail;
|
||||
snap.safety.min_front = last_safety_.min_front;
|
||||
snap.safety.front_rays = last_safety_.front_rays;
|
||||
snap.safety.front_blanked = last_safety_.front_blanked;
|
||||
snap.safety.front_usable = last_safety_.front_usable;
|
||||
snap.safety.estop = estop_.load();
|
||||
}
|
||||
|
||||
|
||||
// Ground truth, CHI khi mo phong. Di THANG tu nguon len web -- khong
|
||||
// stage nao duoc doc no, do la ca dieu kien de no dung lam thuoc do.
|
||||
if (source_->sim) {
|
||||
snap.have_ground_truth = true;
|
||||
snap.ground_truth = source_->sim->ground_truth();
|
||||
source_->sim->true_tilt(&snap.gt_roll, &snap.gt_pitch);
|
||||
}
|
||||
|
||||
// pose_map = map_correction * pose_odom.
|
||||
//
|
||||
// Khong co SLAM thi map_correction la dong nhat, tuc map == odom -- va
|
||||
// noi ro dieu do tren web (`slam.mode = "off"`) thay vi de nguoi xem
|
||||
// tuong dang nhin mot pose da duoc SLAM sua.
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(slam_mu_);
|
||||
if (slam_map_version_ > 0) {
|
||||
snap.pose_map = Pose2DCompose(map_correction_, ekf_pose);
|
||||
snap.slam.localized = slam_localized_;
|
||||
snap.slam.map_version = static_cast<uint32_t>(slam_published_version_);
|
||||
snap.slam.process_ms = slam_process_ms_;
|
||||
#ifdef VSLAM_HAVE_SLAM
|
||||
snap.slam.mode = SlamModeName(slam_mode_);
|
||||
#endif
|
||||
if (slam_map_) snap.map = slam_map_;
|
||||
} else {
|
||||
snap.pose_map = ekf_pose;
|
||||
snap.slam.mode = slam_enabled_ ? "dang cho" : "off";
|
||||
}
|
||||
}
|
||||
|
||||
// ⚠️ Quy dao phai lay SAU khi `pose_map` da duoc tinh.
|
||||
//
|
||||
// Khoi nay truoc day nam TRUOC phep tinh pose_map, nen no doc mot
|
||||
// `snap.pose_map` vua moi khoi tao mac dinh -- tuc la (0, 0, 0). Lan dau
|
||||
// no day goc toa do vao quy dao, va tu do `Distance2D(back, (0,0)) == 0`
|
||||
// nen khong bao gio them diem nao nua.
|
||||
//
|
||||
// Hau qua: lop `duong di` chi la MOT diem dung yen o goc the gioi, trong
|
||||
// khi robot chay di cho khac. Khong mot loi nao: khung PATH van gui dung
|
||||
// nhip, chi la no luon mang dung 1 diem (28 byte).
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(traj_mu_);
|
||||
// Thua hoa: chi them diem khi da di du xa. Gui lai ca quy dao moi khung
|
||||
// la 8 kB/s vo ich.
|
||||
const Pose2D p = snap.pose_map;
|
||||
if (trajectory_.empty() ||
|
||||
Distance2D(trajectory_.back(), p) > cfg_->web.path_min_step_m) {
|
||||
trajectory_.push_back(p);
|
||||
}
|
||||
snap.trajectory = trajectory_;
|
||||
}
|
||||
|
||||
// Ban do THE GIOI di rieng, LUON gui khi chay mo phong -- do la khung
|
||||
// nhin "Gazebo" de lai cho chuan.
|
||||
//
|
||||
// ⚠️ KHONG gan no vao `snap.map`. `snap.map` la ban do SLAM DUNG; tron
|
||||
// hai thu lam nguoi xem tuong SLAM da dung xong ca tang trong khi no moi
|
||||
// thay mot hanh lang. Trinh duyet ve chung o hai khung rieng.
|
||||
snap.world_map = map_ptr;
|
||||
|
||||
// Chua bat SLAM thi khong co ban do SLAM nao -- de trong va bao mode
|
||||
// "off", chu KHONG muon ban do the gioi roi goi no la ban do SLAM.
|
||||
if (!snap.map && map_ptr && !slam_enabled_) {
|
||||
snap.slam.map_version = 0;
|
||||
}
|
||||
snap.health.lidar_hz = cfg_->sensors.lidar_hz;
|
||||
snap.health.camera_hz = camera_ != nullptr ? cfg_->sensors.camera_hz : 0.0;
|
||||
snap.health.imu_hz = cfg_->sensors.imu_hz;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(teleop_mu_);
|
||||
snap.teleop.linear_speed = teleop_->linear_speed();
|
||||
snap.teleop.angular_speed = teleop_->angular_speed();
|
||||
snap.teleop.max_linear_speed = teleop_->max_linear_speed();
|
||||
snap.teleop.max_angular_speed = teleop_->max_angular_speed();
|
||||
}
|
||||
|
||||
web_->Publish(snap);
|
||||
|
||||
next += std::chrono::duration_cast<std::chrono::steady_clock::duration>(period);
|
||||
std::this_thread::sleep_until(next);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
Reference in New Issue
Block a user