upload
This commit is contained in:
513
app/src/app_config.cc
Normal file
513
app/src/app_config.cc
Normal file
@@ -0,0 +1,513 @@
|
||||
#include "app_config.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/log.h"
|
||||
#include "vslam/node_constants.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
|
||||
// Nap mot file, doi ngoai le thanh StatusResponse.
|
||||
//
|
||||
// ConfigNode::LoadFile nem ConfigError. Mot file config sai KHONG duoc phep
|
||||
// lam sap tien trinh: nguoi van hanh phai doc duoc loi, khong phai mot
|
||||
// backtrace.
|
||||
StatusResponse Open(const std::string& dir, const char* name, ConfigNode* out) {
|
||||
const std::string path = dir + "/" + name;
|
||||
try {
|
||||
*out = ConfigNode::LoadFile(path);
|
||||
return StatusResponse::Ok();
|
||||
} catch (const std::exception& e) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
std::string(name) + " (" + path + "): " + e.what());
|
||||
}
|
||||
}
|
||||
|
||||
// Tu choi khoi dong khi co khoa la.
|
||||
//
|
||||
// Go sai ten khoa hien tai roi ve mac dinh mot cach im lang. `stop_distence`
|
||||
// thay vi `stop_distance` nghia la robot dung o 0.35 m mac dinh thay vi gia
|
||||
// tri ban vua dat -- va ban se khong biet cho toi khi no khong dung.
|
||||
StatusResponse Reject(const ConfigNode& n, const char* where,
|
||||
const std::vector<std::string>& known) {
|
||||
if (n.IsNull()) return StatusResponse::Ok();
|
||||
const std::vector<std::string> unknown = n.UnknownKeys(known);
|
||||
if (unknown.empty()) return StatusResponse::Ok();
|
||||
std::string m = std::string(where) + ": khoa la:";
|
||||
for (const auto& k : unknown) m += " " + k;
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
|
||||
// ---------- robot.yaml ----------
|
||||
{
|
||||
const StatusResponse st = out->robot.LoadFile(dir + "/" + kRobotConfigFile);
|
||||
if (!st.ok()) return st;
|
||||
}
|
||||
const RobotGeometry& geom = out->robot.geometry();
|
||||
|
||||
// ---------- sensors.yaml ----------
|
||||
{
|
||||
ConfigNode root;
|
||||
const StatusResponse st = Open(dir, kSensorsConfigFile, &root);
|
||||
if (!st.ok()) return st;
|
||||
{
|
||||
const StatusResponse r = Reject(root, "sensors.yaml", {"lidar", "camera", "mcu"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
|
||||
const ConfigNode l = root["lidar"];
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(l, "sensors.yaml lidar",
|
||||
{"host", "port", "expected_rate_hz", "range_min", "range_max",
|
||||
"stamp_mismatch_warn", "sector_masks"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
out->sanitizer.range_min = l.get<double>("range_min", 0.05);
|
||||
out->sanitizer.range_max = l.get<double>("range_max", 40.0);
|
||||
out->sensors.lidar_hz = l.get<double>("expected_rate_hz", 25.0);
|
||||
|
||||
// Sector mask ghi bang DO trong YAML (doc duoc bang mat), dung bang RAD.
|
||||
// Doi mot lan o day, khong de moi noi tu doi.
|
||||
const ConfigNode masks = l["sector_masks"];
|
||||
out->sanitizer.sector_masks.clear();
|
||||
if (!masks.IsNull()) {
|
||||
if (!masks.IsSequence()) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
"sensors.yaml lidar.sector_masks phai la chuoi");
|
||||
}
|
||||
for (size_t i = 0; i < masks.size(); ++i) {
|
||||
const ConfigNode m = masks.at(i);
|
||||
if (!m.IsSequence() || m.size() != 2) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"sensors.yaml lidar.sector_masks[" + std::to_string(i) +
|
||||
"] phai la [bat_dau_do, ket_thuc_do]");
|
||||
}
|
||||
const double a = m.at(0).as<double>() * kPi / 180.0;
|
||||
const double b = m.at(1).as<double>() * kPi / 180.0;
|
||||
if (!(b > a)) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"sensors.yaml lidar.sector_masks[" + std::to_string(i) +
|
||||
"]: ket thuc phai lon hon bat dau (quat rong 0 do khong che gi)");
|
||||
}
|
||||
out->sanitizer.sector_masks.push_back(SectorMask{a, b});
|
||||
}
|
||||
}
|
||||
|
||||
const ConfigNode c = root["camera"];
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(c, "sensors.yaml camera",
|
||||
{"enable", "width", "height", "fps", "decimate", "enable_infra1",
|
||||
"enable_infra2", "prefer_global_time"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
out->sensors.camera_enable = c.get<bool>("enable", true);
|
||||
out->sensors.camera_width = static_cast<uint32_t>(c.get<int>("width", 640));
|
||||
out->sensors.camera_height = static_cast<uint32_t>(c.get<int>("height", 480));
|
||||
out->sensors.camera_hz = c.get<double>("fps", 30.0);
|
||||
out->sensors.camera_decimate = static_cast<uint32_t>(c.get<int>("decimate", 2));
|
||||
|
||||
const ConfigNode mc = root["mcu"];
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(mc, "sensors.yaml mcu",
|
||||
{"port", "baud", "sync_window", "max_skew_warn",
|
||||
"expected_imu_rate_hz", "ticks_per_rev"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
out->sensors.imu_hz = mc.get<double>("expected_imu_rate_hz", 200.0);
|
||||
}
|
||||
|
||||
// ---------- pipeline.yaml ----------
|
||||
{
|
||||
ConfigNode root;
|
||||
const StatusResponse st = Open(dir, kPipelineConfigFile, &root);
|
||||
if (!st.ok()) return st;
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(root, "pipeline.yaml",
|
||||
{"ekf", "depth_filter", "gravity_align", "cliff_detect"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
|
||||
const ConfigNode e = root["ekf"];
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(e, "pipeline.yaml ekf",
|
||||
{"q_x", "q_y", "q_yaw", "q_vx", "q_vyaw", "max_dt"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
out->ekf.q_x = e.get<double>("q_x", out->ekf.q_x);
|
||||
out->ekf.q_y = e.get<double>("q_y", out->ekf.q_y);
|
||||
out->ekf.q_yaw = e.get<double>("q_yaw", out->ekf.q_yaw);
|
||||
out->ekf.q_vx = e.get<double>("q_vx", out->ekf.q_vx);
|
||||
out->ekf.q_vyaw = e.get<double>("q_vyaw", out->ekf.q_vyaw);
|
||||
out->ekf.sensor_timeout = e.get<double>("max_dt", out->ekf.sensor_timeout);
|
||||
|
||||
const ConfigNode d = root["depth_filter"];
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(d, "pipeline.yaml depth_filter",
|
||||
{"min_range", "max_range", "voxel_size", "max_rate",
|
||||
"enable_temporal", "min_hits", "temporal_window"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
DepthFilterConfig& df = out->perception.filter;
|
||||
df.min_range = d.get<double>("min_range", df.min_range);
|
||||
df.max_range = d.get<double>("max_range", df.max_range);
|
||||
df.voxel_size = d.get<double>("voxel_size", df.voxel_size);
|
||||
df.max_rate = d.get<double>("max_rate", df.max_rate);
|
||||
df.enable_temporal = d.get<bool>("enable_temporal", df.enable_temporal);
|
||||
df.min_hits = d.get<int>("min_hits", df.min_hits);
|
||||
df.temporal_window = d.get<double>("temporal_window", df.temporal_window);
|
||||
|
||||
const ConfigNode ga = root["gravity_align"];
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(ga, "pipeline.yaml gravity_align",
|
||||
{"alpha", "accel_lpf_alpha", "accel_gate", "use_odom_accel",
|
||||
"odom_accel_alpha", "min_height", "max_height"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
GravityAlignConfig& g = out->perception.gravity;
|
||||
g.alpha = ga.get<double>("alpha", g.alpha);
|
||||
g.accel_lpf_alpha = ga.get<double>("accel_lpf_alpha", g.accel_lpf_alpha);
|
||||
g.accel_gate = ga.get<double>("accel_gate", g.accel_gate);
|
||||
g.use_odom_accel = ga.get<bool>("use_odom_accel", g.use_odom_accel);
|
||||
g.odom_accel_alpha = ga.get<double>("odom_accel_alpha", g.odom_accel_alpha);
|
||||
g.min_height = ga.get<double>("min_height", g.min_height);
|
||||
g.max_height = ga.get<double>("max_height", g.max_height);
|
||||
// HE QUA cua robot.yaml, khong doc tu pipeline.yaml.
|
||||
g.wheel_radius = geom.wheel_radius;
|
||||
|
||||
const ConfigNode cd = root["cliff_detect"];
|
||||
{
|
||||
// `nominal_tz` va `wheel_radius` CO Y khong nam trong danh sach nay:
|
||||
// dat chung o pipeline.yaml se tao ra mot ban sao thu hai cua mot gia
|
||||
// tri da co trong robot.yaml. Go chung vao file se bao "khoa la".
|
||||
const StatusResponse r =
|
||||
Reject(cd, "pipeline.yaml cliff_detect",
|
||||
{"enabled", "min_dist", "max_dist", "cliff_margin",
|
||||
"pitch_uncertainty_deg", "pixel_step", "min_neighbors",
|
||||
"min_cluster", "imu_timeout", "require_accel_ok", "self_level",
|
||||
"min_level_samples", "level_gate", "max_level_slope",
|
||||
"max_level_residual", "max_obstructed_frac", "max_level_offset",
|
||||
"max_tz_dev", "fail_safe", "fail_safe_after"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
CliffDetectConfig& cf = out->perception.cliff;
|
||||
cf.enabled = cd.get<bool>("enabled", cf.enabled);
|
||||
cf.min_dist = cd.get<double>("min_dist", cf.min_dist);
|
||||
cf.max_dist = cd.get<double>("max_dist", cf.max_dist);
|
||||
cf.cliff_margin = cd.get<double>("cliff_margin", cf.cliff_margin);
|
||||
cf.pitch_uncertainty_deg =
|
||||
cd.get<double>("pitch_uncertainty_deg", cf.pitch_uncertainty_deg);
|
||||
cf.pixel_step = cd.get<int>("pixel_step", cf.pixel_step);
|
||||
cf.min_neighbors = cd.get<int>("min_neighbors", cf.min_neighbors);
|
||||
cf.min_cluster = cd.get<int>("min_cluster", cf.min_cluster);
|
||||
cf.imu_timeout = cd.get<double>("imu_timeout", cf.imu_timeout);
|
||||
cf.require_accel_ok = cd.get<bool>("require_accel_ok", cf.require_accel_ok);
|
||||
cf.self_level = cd.get<bool>("self_level", cf.self_level);
|
||||
cf.min_level_samples = cd.get<int>("min_level_samples", cf.min_level_samples);
|
||||
cf.level_gate = cd.get<double>("level_gate", cf.level_gate);
|
||||
cf.max_level_slope = cd.get<double>("max_level_slope", cf.max_level_slope);
|
||||
cf.max_level_residual =
|
||||
cd.get<double>("max_level_residual", cf.max_level_residual);
|
||||
cf.max_obstructed_frac =
|
||||
cd.get<double>("max_obstructed_frac", cf.max_obstructed_frac);
|
||||
cf.max_level_offset = cd.get<double>("max_level_offset", cf.max_level_offset);
|
||||
cf.max_tz_dev = cd.get<double>("max_tz_dev", cf.max_tz_dev);
|
||||
cf.fail_safe = cd.get<bool>("fail_safe", cf.fail_safe);
|
||||
cf.fail_safe_after = cd.get<double>("fail_safe_after", cf.fail_safe_after);
|
||||
// HE QUA cua robot.yaml.
|
||||
cf.wheel_radius = geom.wheel_radius;
|
||||
cf.nominal_tz = out->robot.camera_height_above_floor();
|
||||
}
|
||||
|
||||
// ---------- wheel_odom: robot.yaml ----------
|
||||
{
|
||||
const WheelOdomNoise& w = out->robot.wheel_odom();
|
||||
out->wheel_odom.wheel_radius = geom.wheel_radius;
|
||||
out->wheel_odom.wheel_separation = geom.wheel_separation;
|
||||
out->wheel_odom.sigma_x = w.sigma_x_per_m;
|
||||
out->wheel_odom.sigma_y = w.sigma_y_per_m;
|
||||
out->wheel_odom.sigma_yaw = w.sigma_yaw_per_rad;
|
||||
out->wheel_odom.slip_omega_threshold = w.slip_threshold;
|
||||
}
|
||||
|
||||
// ---------- safety.yaml ----------
|
||||
{
|
||||
ConfigNode root;
|
||||
const StatusResponse st = Open(dir, kSafetyConfigFile, &root);
|
||||
if (!st.ok()) return st;
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(root, "safety.yaml",
|
||||
{"scan", "ultrasonic", "cliff", "timeouts", "limits", "bumper"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
|
||||
const ConfigNode sc = root["scan"];
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(sc, "safety.yaml scan",
|
||||
{"stop_distance", "slow_distance", "slow_factor", "front_angle",
|
||||
"min_valid_range", "min_front_rays"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
SafetyConfig& sf = out->safety;
|
||||
sf.stop_distance = sc.get<double>("stop_distance", sf.stop_distance);
|
||||
sf.slow_distance = sc.get<double>("slow_distance", sf.slow_distance);
|
||||
sf.slow_factor = sc.get<double>("slow_factor", sf.slow_factor);
|
||||
sf.front_angle = sc.get<double>("front_angle", sf.front_angle);
|
||||
sf.min_valid_range = sc.get<double>("min_valid_range", sf.min_valid_range);
|
||||
sf.min_front_rays = sc.get<int>("min_front_rays", sf.min_front_rays);
|
||||
|
||||
const ConfigNode us = root["ultrasonic"];
|
||||
{
|
||||
const StatusResponse r = Reject(us, "safety.yaml ultrasonic", {"us_stop_distance"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
sf.us_stop_distance = us.get<double>("us_stop_distance", sf.us_stop_distance);
|
||||
|
||||
const ConfigNode cl = root["cliff"];
|
||||
{
|
||||
const StatusResponse r = Reject(
|
||||
cl, "safety.yaml cliff", {"enable_cliff_stop", "cliff_timeout", "cliff_hold"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
sf.enable_cliff_stop = cl.get<bool>("enable_cliff_stop", sf.enable_cliff_stop);
|
||||
sf.cliff_timeout = cl.get<double>("cliff_timeout", sf.cliff_timeout);
|
||||
sf.cliff_hold = cl.get<double>("cliff_hold", sf.cliff_hold);
|
||||
|
||||
const ConfigNode to = root["timeouts"];
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(to, "safety.yaml timeouts", {"sensor_timeout", "cmd_timeout"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
sf.sensor_timeout = to.get<double>("sensor_timeout", sf.sensor_timeout);
|
||||
sf.cmd_timeout = to.get<double>("cmd_timeout", sf.cmd_timeout);
|
||||
|
||||
const ConfigNode li = root["limits"];
|
||||
{
|
||||
const StatusResponse r = Reject(li, "safety.yaml limits", {"max_linear", "max_angular"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
sf.max_linear = li.get<double>("max_linear", sf.max_linear);
|
||||
sf.max_angular = li.get<double>("max_angular", sf.max_angular);
|
||||
|
||||
const ConfigNode bu = root["bumper"];
|
||||
{
|
||||
const StatusResponse r = Reject(bu, "safety.yaml bumper",
|
||||
{"escape_linear", "escape_angular"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
sf.escape_linear = bu.get<double>("escape_linear", sf.escape_linear);
|
||||
sf.escape_angular = bu.get<double>("escape_angular", sf.escape_angular);
|
||||
|
||||
// --- Kiem CHEO voi robot.yaml, khong tin mot trong hai ---
|
||||
//
|
||||
// safety.cmd_timeout phai DAI hon base.cmd_timeout. Neu ngan hon thi base
|
||||
// da tu dung robot truoc, va nhanh NO_CMD cua FSM khong bao gio chay --
|
||||
// tuc la mot nhanh an toan ton tai tren giay ma khong bao gio duoc thu.
|
||||
if (sf.cmd_timeout <= out->robot.base().cmd_timeout) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"safety.yaml timeouts.cmd_timeout (" + std::to_string(sf.cmd_timeout) +
|
||||
") phai LON HON robot.yaml base.cmd_timeout (" +
|
||||
std::to_string(out->robot.base().cmd_timeout) +
|
||||
") -- neu khong, base tu dung truoc va nhanh NO_CMD khong bao gio chay");
|
||||
}
|
||||
// Gioi han cua safety khong duoc VUOT gioi han co hoc cua base.
|
||||
if (sf.max_linear > out->robot.base().max_linear + 1e-9 ||
|
||||
sf.max_angular > out->robot.base().max_angular + 1e-9) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"safety.yaml limits vuot qua robot.yaml base -- lop an toan khong "
|
||||
"duoc phep cho phep nhieu hon phan cung chiu duoc");
|
||||
}
|
||||
// Toc do thoat khi bumper dang chot khong duoc vuot gioi han thuong.
|
||||
//
|
||||
// Phia sau KHONG co cam bien nao che, va robot dang CHAM vao vat gi do --
|
||||
// day la luc nguy hiem nhat, khong phai luc de di nhanh hon.
|
||||
if (sf.escape_linear > sf.max_linear + 1e-9 ||
|
||||
sf.escape_angular > sf.max_angular + 1e-9) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"safety.yaml bumper.escape_* vuot qua limits.max_* -- toc do THOAT "
|
||||
"khi dang cham vat can khong duoc lon hon toc do binh thuong");
|
||||
}
|
||||
if (sf.escape_linear <= 0.0) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"safety.yaml bumper.escape_linear phai > 0 -- bang 0 nghia la robot "
|
||||
"dam roi nam vinh vien tai cho, khong lui ra duoc de reset");
|
||||
}
|
||||
|
||||
// Vuc bien mat khoi tam nhin khi lai gan hon min_dist, nen cliff_hold
|
||||
// phai du dai de phu quang duong do. Duoi 1 s la gan nhu chac chan lot.
|
||||
if (sf.enable_cliff_stop && sf.cliff_hold < 1.0) {
|
||||
VSLAM_WARN("safety.yaml cliff.cliff_hold = "
|
||||
<< sf.cliff_hold
|
||||
<< " s. Vuc bien mat khoi tam nhin camera khi lai gan hon "
|
||||
<< out->perception.cliff.min_dist
|
||||
<< " m; gia tri nay nhieu kha nang qua ngan.");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- cliff.min_dist co khop HINH HOC camera khong ----------
|
||||
//
|
||||
// `min_dist` KHONG phai mot tham so chinh duoc tuy y: no la vung mu HINH
|
||||
// HOC. Tia duoi cung cua truong nhin cham san o
|
||||
// d = z_camera / tan(pitch + vfov/2)
|
||||
// va duoi d do khong mot tia nao cham san -- detector im lang hoan toan.
|
||||
//
|
||||
// Doi `camera_pitch` trong robot.yaml ma quen sua `min_dist` trong
|
||||
// pipeline.yaml la mot kieu hong IM LANG: cliff_detect van chay, van bao
|
||||
// "judged", chi la no dang nhin vao mot dai khong co du lieu.
|
||||
//
|
||||
// ⚠️ CANH BAO chu khong TU CHOI: `vfov` o day la mac dinh cua D410
|
||||
// (42 do), CHUA doi chieu voi CameraInfo that. Tu choi khoi dong dua tren
|
||||
// mot so chua xac minh la sai. Khi driver camera chay tren thiet bi that
|
||||
// thi thay bang vfov do duoc va co the siet thanh loi.
|
||||
{
|
||||
constexpr double kD410VfovRad = 0.733; // 42 do, mac dinh -- CHUA XAC MINH
|
||||
const double cam_h = out->robot.camera_height_above_floor();
|
||||
const double drop = out->robot.camera_pitch() + kD410VfovRad / 2.0;
|
||||
if (drop > 1e-3 && drop < 1.5 && cam_h > 0.0) {
|
||||
const double geom_min = cam_h / std::tan(drop);
|
||||
const double got = out->perception.cliff.min_dist;
|
||||
if (std::fabs(got - geom_min) > 0.15) {
|
||||
VSLAM_WARN("pipeline.yaml cliff_detect.min_dist = "
|
||||
<< got << " m, nhung hinh hoc camera cho "
|
||||
<< geom_min << " m (cao " << cam_h << " m, chuc "
|
||||
<< out->robot.camera_pitch() * 180.0 / kPi << " do, vfov 42 do). "
|
||||
<< "Dat THAP hon vung mu that thi detector nhin vao dai "
|
||||
"khong co du lieu; dat CAO hon thi bo phi tam nhin.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- slam.yaml ----------
|
||||
#ifdef VSLAM_HAVE_SLAM
|
||||
{
|
||||
ConfigNode root;
|
||||
const StatusResponse st = Open(dir, kSlamConfigFile, &root);
|
||||
if (!st.ok()) return st;
|
||||
// Ten key RTAB-Map duoc kiem trong BuildRtabmapParams (doi chieu voi bang
|
||||
// mac dinh cua chinh RTAB-Map), nen o day khong kiem lai.
|
||||
try {
|
||||
out->slam = LoadRtabmapConfig(root);
|
||||
} catch (const std::exception& e) {
|
||||
return StatusResponse::Error(StatusCode::kInvalidArgument,
|
||||
std::string("slam.yaml: ") + e.what());
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// ---------- system.yaml ----------
|
||||
{
|
||||
ConfigNode root;
|
||||
const StatusResponse st = Open(dir, kSystemConfigFile, &root);
|
||||
if (!st.ok()) return st;
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(root, "system.yaml",
|
||||
{"web", "logging", "record", "threads", "watchdog"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
|
||||
const ConfigNode w = root["web"];
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(w, "system.yaml web",
|
||||
{"port", "bind", "auth_token", "asset_dir", "status_rate_hz",
|
||||
"scan_rate_hz", "cloud_rate_hz", "path_rate_hz",
|
||||
"cloud_max_points", "cloud_quant_m", "map_rebuild_rate_hz"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
out->web.port = static_cast<uint16_t>(w.get<int>("port", 8080));
|
||||
out->web.bind_address = w.get<std::string>("bind", out->web.bind_address);
|
||||
out->web.auth_token = w.get<std::string>("auth_token", "");
|
||||
out->web.asset_dir = w.get<std::string>("asset_dir", "");
|
||||
out->web.state_hz = w.get<double>("status_rate_hz", out->web.state_hz);
|
||||
out->web.scan_hz = w.get<double>("scan_rate_hz", out->web.scan_hz);
|
||||
out->web.cloud_hz = w.get<double>("cloud_rate_hz", out->web.cloud_hz);
|
||||
out->web.path_hz = w.get<double>("path_rate_hz", out->web.path_hz);
|
||||
out->web.cloud_max_points =
|
||||
static_cast<uint32_t>(w.get<int>("cloud_max_points", 4000));
|
||||
out->slam_runtime.map_rebuild_rate_hz =
|
||||
w.get<double>("map_rebuild_rate_hz", out->slam_runtime.map_rebuild_rate_hz);
|
||||
|
||||
if (out->web.auth_token.empty()) {
|
||||
// Khong tu choi khoi dong: mot robot trong phong lab khong can token.
|
||||
// Nhung phai TO, vi bat doi xung cua lop xac thuc (go e-stop can token)
|
||||
// tro nen vo nghia khi khong co token nao.
|
||||
VSLAM_WARN("system.yaml web.auth_token DE TRONG -- bat ky ai vao duoc "
|
||||
"mang deu GO duoc e-stop va reset duoc bumper.");
|
||||
}
|
||||
|
||||
const ConfigNode lg = root["logging"];
|
||||
{
|
||||
const StatusResponse r = Reject(lg, "system.yaml logging", {"level"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
out->log_level = lg.get<std::string>("level", "info");
|
||||
|
||||
const ConfigNode rc = root["record"];
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(rc, "system.yaml record",
|
||||
{"enabled", "dir", "max_queue_bytes", "depth_rate_hz",
|
||||
"record_infra1", "record_infra2", "compress"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
out->record.enabled = rc.get<bool>("enabled", false);
|
||||
out->record.dir = rc.get<std::string>("dir", out->record.dir);
|
||||
out->record.max_queue_bytes =
|
||||
static_cast<size_t>(rc.get<int>("max_queue_bytes", 67108864));
|
||||
out->record.depth_rate_hz = rc.get<double>("depth_rate_hz", 10.0);
|
||||
out->record.record_infra1 = rc.get<bool>("record_infra1", false);
|
||||
out->record.record_infra2 = rc.get<bool>("record_infra2", false);
|
||||
out->record.compress = rc.get<bool>("compress", false);
|
||||
|
||||
const ConfigNode th = root["threads"];
|
||||
{
|
||||
const StatusResponse r =
|
||||
Reject(th, "system.yaml threads",
|
||||
{"safety_priority", "driver_priority", "estimator_priority",
|
||||
"use_realtime", "safety_rate_hz"});
|
||||
if (!r.ok()) return r;
|
||||
}
|
||||
out->threads.safety_priority = th.get<int>("safety_priority", 50);
|
||||
out->threads.driver_priority = th.get<int>("driver_priority", 45);
|
||||
out->threads.estimator_priority = th.get<int>("estimator_priority", 40);
|
||||
out->threads.use_realtime = th.get<bool>("use_realtime", true);
|
||||
out->threads.safety_rate_hz = th.get<double>("safety_rate_hz", 20.0);
|
||||
|
||||
// Luong safety phai co uu tien CAO NHAT. Dat nguoc lai la vo hieu hoa ca
|
||||
// ly do dung SCHED_FIFO.
|
||||
if (out->threads.use_realtime &&
|
||||
(out->threads.safety_priority <= out->threads.driver_priority ||
|
||||
out->threads.safety_priority <= out->threads.estimator_priority)) {
|
||||
return StatusResponse::Error(
|
||||
StatusCode::kInvalidArgument,
|
||||
"system.yaml threads: safety_priority phai CAO HON moi uu tien khac");
|
||||
}
|
||||
}
|
||||
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
112
app/src/app_config.h
Normal file
112
app/src/app_config.h
Normal file
@@ -0,0 +1,112 @@
|
||||
#ifndef VSLAM_APP_APP_CONFIG_H
|
||||
#define VSLAM_APP_APP_CONFIG_H
|
||||
|
||||
// Nap sau file YAML thanh cac struct config ma tung lib da dinh nghia.
|
||||
//
|
||||
// ================== VI SAO O `app/` CHU KHONG O TUNG LIB ==================
|
||||
// Thiet ke sach hon la "moi lib tu doc config cua no". Nhung lam vay bat moi
|
||||
// lib phu thuoc yaml-cpp, ke ca `vslam_odometry` va `vslam_safety` -- hai lib
|
||||
// ma ca ly do ton tai la KHONG co dep ngoai nao, de review duoc doc lap va
|
||||
// build duoc truoc moi thu khac.
|
||||
//
|
||||
// Nen phep nap nam o day. Doi lai, moi khi them mot truong config thi phai
|
||||
// sua hai cho. De giam cho do: MOI khoi deu goi `UnknownKeys()` va TU CHOI
|
||||
// khoi dong khi co khoa la, nen mot truong duoc them vao YAML ma quen noi o
|
||||
// day se bao loi ngay chu khong am tham bi bo qua.
|
||||
//
|
||||
// ================== KHONG CO GIA TRI NAO O HAI NOI ==================
|
||||
// `cliff_detect.nominal_tz` KHONG doc tu pipeline.yaml -- no la he qua cua
|
||||
// robot.yaml (camera_link.z + wheel_radius) va duoc dat tu `RobotModel`.
|
||||
// Tuong tu, gioi han base trong safety.yaml duoc KIEM cheo voi robot.yaml
|
||||
// thay vi tin mot trong hai.
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "vslam/cliff_detect.h"
|
||||
#include "vslam/depth_filter.h"
|
||||
#include "vslam/ekf_se2.h"
|
||||
#include "vslam/gravity_align.h"
|
||||
#include "vslam/perception_pipeline.h"
|
||||
#include "vslam/robot_model.h"
|
||||
#include "vslam/safety_monitor.h"
|
||||
#include "vslam/scan_sanitizer.h"
|
||||
#include "vslam/vslam_common.h"
|
||||
#include "vslam/web_server.h"
|
||||
#include "vslam/wheel_odometry.h"
|
||||
|
||||
#ifdef VSLAM_HAVE_SLAM
|
||||
#include "vslam/rtabmap_params.h"
|
||||
#endif
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// Tan so toi da dung lai occupancy grid tu do thi SLAM. Xem system.yaml.
|
||||
struct SlamRuntimeConfig {
|
||||
double map_rebuild_rate_hz = 0.5;
|
||||
};
|
||||
|
||||
struct ThreadConfig {
|
||||
int safety_priority = 50;
|
||||
int driver_priority = 45;
|
||||
int estimator_priority = 40;
|
||||
bool use_realtime = true;
|
||||
double safety_rate_hz = 20.0;
|
||||
};
|
||||
|
||||
struct RecordConfig {
|
||||
bool enabled = false;
|
||||
std::string dir = "/var/lib/vslam/records";
|
||||
size_t max_queue_bytes = 64u * 1024u * 1024u;
|
||||
double depth_rate_hz = 10.0;
|
||||
bool record_infra1 = false;
|
||||
bool record_infra2 = false;
|
||||
bool compress = false;
|
||||
};
|
||||
|
||||
struct SensorRates {
|
||||
double lidar_hz = 25.0;
|
||||
double camera_hz = 30.0;
|
||||
double imu_hz = 200.0;
|
||||
bool camera_enable = true;
|
||||
uint32_t camera_width = 640;
|
||||
uint32_t camera_height = 480;
|
||||
uint32_t camera_decimate = 2;
|
||||
};
|
||||
|
||||
// Toan bo cau hinh cua mot lan chay.
|
||||
struct AppConfig {
|
||||
RobotModel robot; // robot.yaml -- nguon DUY NHAT cho hinh hoc
|
||||
|
||||
ScanSanitizerConfig sanitizer; // sensors.yaml
|
||||
SensorRates sensors;
|
||||
|
||||
WheelOdometryConfig wheel_odom; // robot.yaml + pipeline.yaml
|
||||
EkfSe2Config ekf; // pipeline.yaml
|
||||
PerceptionConfig perception; // pipeline.yaml + robot.yaml
|
||||
|
||||
SafetyConfig safety; // safety.yaml
|
||||
#ifdef VSLAM_HAVE_SLAM
|
||||
RtabmapConfig slam; // slam.yaml
|
||||
#endif
|
||||
|
||||
WebConfig web; // system.yaml
|
||||
ThreadConfig threads;
|
||||
SlamRuntimeConfig slam_runtime;
|
||||
RecordConfig record;
|
||||
std::string log_level = "info";
|
||||
|
||||
AppConfig() = default;
|
||||
AppConfig(const AppConfig&) = delete;
|
||||
AppConfig& operator=(const AppConfig&) = delete;
|
||||
};
|
||||
|
||||
// Nap tat ca tu `dir` (mac dinh `ConfigDir()`).
|
||||
//
|
||||
// Tra loi dau tien gap phai, KHONG gom het: mot file config sai thi cac gia
|
||||
// tri sau no khong con dang tin, va mot danh sach dai lam nguoi doc bo qua
|
||||
// dong dau.
|
||||
StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out);
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_APP_APP_CONFIG_H
|
||||
239
app/src/main.cc
Normal file
239
app/src/main.cc
Normal file
@@ -0,0 +1,239 @@
|
||||
// vslam_node -- tien trinh duy nhat.
|
||||
//
|
||||
// Thay cho `roslaunch robot_bringup bringup.launch` + 20 file .launch + 14
|
||||
// file YAML + roscore.
|
||||
//
|
||||
// vslam_node --sim chay voi bo mo phong
|
||||
// vslam_node --sim --map nha.yaml mo phong tren ban do that
|
||||
// vslam_node --replay X.vsr phat lai ban ghi
|
||||
// vslam_node --live phan cung that (driver CHUA viet)
|
||||
//
|
||||
// Doc `src/wiring.cc` de hieu he thong: no la noi duy nhat noi nguon voi
|
||||
// stage.
|
||||
|
||||
#include <atomic>
|
||||
#include <csignal>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
#include "app_config.h"
|
||||
#include "runtime.h"
|
||||
#include "vslam/log.h"
|
||||
#include "vslam/node_constants.h"
|
||||
|
||||
namespace {
|
||||
|
||||
std::atomic<bool> g_stop{false};
|
||||
vslam::Runtime* g_runtime = nullptr;
|
||||
|
||||
void OnSignal(int) {
|
||||
g_stop.store(true);
|
||||
// Chi dat co va goi RequestStop -- ca hai deu an toan trong signal handler
|
||||
// vi chung chi cham vao atomic. KHONG log, khong cap phat: hai thu do
|
||||
// khong async-signal-safe va mot lan treo o day la mot lan phai rut dien.
|
||||
if (g_runtime != nullptr) g_runtime->RequestStop();
|
||||
}
|
||||
|
||||
void Usage(const char* argv0) {
|
||||
std::printf(
|
||||
"cach dung: %s [--sim | --replay FILE | --live] [tuy chon]\n"
|
||||
"\n"
|
||||
" --sim chay voi bo mo phong (thay Gazebo)\n"
|
||||
" --replay FILE phat lai ban ghi .vsr\n"
|
||||
" --live phan cung that (driver CHUA viet)\n"
|
||||
"\n"
|
||||
" --config DIR thu muc cau hinh (mac dinh: $VSLAM_CONFIG_DIR\n"
|
||||
" hoac %s)\n"
|
||||
" --map FILE.yaml ban do cho --sim; khong co thi dung the gioi\n"
|
||||
" tong hop\n"
|
||||
" --world FILE.world the gioi Gazebo cho --sim. Raster hoa mesh va\n"
|
||||
" cham -> luoi; uu tien hon --map\n"
|
||||
" --x X --y Y --yaw R vi tri xuat phat cho --sim\n"
|
||||
" --port N ghi de system.yaml web.port\n"
|
||||
" --token S ghi de system.yaml web.auth_token\n"
|
||||
" --sim-glass-at X dat buc KINH ngang hanh lang o x = X m.\n"
|
||||
" LiDAR/depth KHONG thay; chi sieu am + bumper.\n"
|
||||
" --max-speed V ghi de tran toc do (m/s). CHI CHO MO PHONG --\n"
|
||||
" base that gioi han o robot.yaml base.max_linear\n"
|
||||
" --slam bat SLAM (ghi de slam.yaml enabled)\n"
|
||||
" --slam-db PATH ghi de slam.yaml database_path;\n"
|
||||
" \"\" = DB trong RAM, khong de lai gi tren dia\n"
|
||||
" --slam-mode M mapping | localization (ghi de slam.yaml)\n"
|
||||
" --slam-init-pose x,y,yaw\n"
|
||||
" pose ban dau cho localization -- tuong duong\n"
|
||||
" /initialpose. BAT BUOC tren robot that: RTAB-Map\n"
|
||||
" khong dinh vi toan cuc duoc bang scan khong.\n"
|
||||
" --check nap va KIEM cau hinh roi thoat, khong chay gi\n",
|
||||
argv0, vslam::ConfigDir().c_str());
|
||||
}
|
||||
|
||||
// Sau khi nap cau hinh that bai, CHI THANG cach sua neu doan duoc.
|
||||
//
|
||||
// Loi "khong mo duoc file" mot minh la vo ich: no noi cai gi hong nhung khong
|
||||
// noi phai lam gi. Truong hop pho bien nhat la chay binary tu CAY NGUON trong
|
||||
// khi `ConfigDir()` tro toi duong dan CAI DAT (/etc/vslam/...) -- va khi do
|
||||
// thu muc dung dang nam ngay canh, trong thu muc hien tai.
|
||||
//
|
||||
// ⚠️ CHI GOI Y, khong tu nap. Am tham nap mot bo cau hinh khac voi cai nguoi
|
||||
// van hanh tuong la dung lop bug ma ca du an nay chong: xem ghi chu "KHONG
|
||||
// mac dinh sang --sim" ben duoi.
|
||||
void SuggestConfigDir(const std::string& tried) {
|
||||
// Thu muc da thu CO `robot.yaml` khong?
|
||||
//
|
||||
// Neu CO thi duong dan dung -- loi nam o NOI DUNG file (go sai khoa, cong
|
||||
// kiem cheo khong qua...). Goi y doi thu muc luc do la nhieu, va con day
|
||||
// nguoi doc di sai huong.
|
||||
//
|
||||
// Day cung la cach phan biet duy nhat dang tin: `LoadAppConfig` tra cung
|
||||
// ma loi cho ca "khong mo duoc file" lan "gia tri sai".
|
||||
{
|
||||
std::ifstream at_tried(tried + "/" + vslam::kRobotConfigFile);
|
||||
if (at_tried) return;
|
||||
}
|
||||
|
||||
const std::string local = "configuration_files";
|
||||
|
||||
// Co `./configuration_files/robot.yaml` ngay canh khong?
|
||||
std::ifstream probe(local + "/" + vslam::kRobotConfigFile);
|
||||
if (!probe) return;
|
||||
|
||||
std::fprintf(stderr,
|
||||
"\n Dang chay tu cay nguon? Thu muc cau hinh nam ngay canh:\n"
|
||||
" export VSLAM_CONFIG_DIR=$PWD/%s\n"
|
||||
" hoac chi cho lan chay nay:\n"
|
||||
" --config %s\n",
|
||||
local.c_str(), local.c_str());
|
||||
|
||||
if (std::getenv(vslam::kConfigDirEnv) == nullptr) {
|
||||
std::fprintf(stderr, " (%s dang KHONG duoc dat)\n", vslam::kConfigDirEnv);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
vslam::RuntimeOptions opts;
|
||||
std::string config_dir = vslam::ConfigDir();
|
||||
bool have_source = false;
|
||||
bool check_only = false;
|
||||
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
const std::string a = argv[i];
|
||||
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
|
||||
if (a == "--sim") { opts.source = vslam::SourceKind::kSim; have_source = true; }
|
||||
else if (a == "--replay") {
|
||||
opts.source = vslam::SourceKind::kReplay;
|
||||
opts.replay_path = next();
|
||||
have_source = true;
|
||||
} else if (a == "--live") {
|
||||
opts.source = vslam::SourceKind::kLive;
|
||||
have_source = true;
|
||||
}
|
||||
else if (a == "--config") config_dir = next();
|
||||
else if (a == "--map") opts.map_yaml = next();
|
||||
else if (a == "--world") opts.world_path = next();
|
||||
else if (a == "--x") opts.sim_start_x = std::atof(next().c_str());
|
||||
else if (a == "--y") opts.sim_start_y = std::atof(next().c_str());
|
||||
else if (a == "--yaw") opts.sim_start_yaw = std::atof(next().c_str());
|
||||
else if (a == "--port")
|
||||
opts.port_override = static_cast<uint16_t>(std::atoi(next().c_str()));
|
||||
else if (a == "--token") opts.token_override = next();
|
||||
else if (a == "--sim-glass-at") opts.sim_glass_at = std::atof(next().c_str());
|
||||
else if (a == "--max-speed") opts.max_speed_override = std::atof(next().c_str());
|
||||
else if (a == "--slam") opts.force_slam = true;
|
||||
else if (a == "--slam-db") { opts.slam_db = next(); opts.have_slam_db = true; }
|
||||
else if (a == "--slam-mode") opts.slam_mode_override = next();
|
||||
else if (a == "--slam-init-pose") {
|
||||
const std::string v = next();
|
||||
if (std::sscanf(v.c_str(), "%lf,%lf,%lf", &opts.slam_init_pose.x,
|
||||
&opts.slam_init_pose.y, &opts.slam_init_pose.theta) != 3) {
|
||||
std::fprintf(stderr, "--slam-init-pose can dang x,y,yaw\n");
|
||||
return 2;
|
||||
}
|
||||
opts.have_slam_init_pose = true;
|
||||
}
|
||||
else if (a == "--check") check_only = true;
|
||||
else if (a == "--help" || a == "-h") { Usage(argv[0]); return 0; }
|
||||
else {
|
||||
std::fprintf(stderr, "tham so la: %s\n\n", a.c_str());
|
||||
Usage(argv[0]);
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
if (!have_source && !check_only) {
|
||||
// KHONG mac dinh sang --sim. Mot node am tham chay mo phong trong khi
|
||||
// nguoi van hanh tuong no dang doc cam bien that la kieu hong te nhat co
|
||||
// the nghi ra.
|
||||
std::fprintf(stderr,
|
||||
"phai chon mot nguon: --sim, --replay FILE, hoac --live\n\n");
|
||||
Usage(argv[0]);
|
||||
return 2;
|
||||
}
|
||||
|
||||
// --- Cau hinh ---
|
||||
vslam::AppConfig cfg;
|
||||
{
|
||||
const vslam::StatusResponse st = vslam::LoadAppConfig(config_dir, &cfg);
|
||||
if (!st.ok()) {
|
||||
std::fprintf(stderr, "cau hinh (%s): %s\n", config_dir.c_str(),
|
||||
st.message.c_str());
|
||||
SuggestConfigDir(config_dir);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if (cfg.log_level == "debug") vslam::SetLogLevel(vslam::LogLevel::kDebug);
|
||||
else if (cfg.log_level == "warn") vslam::SetLogLevel(vslam::LogLevel::kWarn);
|
||||
else if (cfg.log_level == "error") vslam::SetLogLevel(vslam::LogLevel::kError);
|
||||
else vslam::SetLogLevel(vslam::LogLevel::kInfo);
|
||||
|
||||
if (check_only) {
|
||||
std::printf("cau hinh OK: %s\n", config_dir.c_str());
|
||||
std::printf(" banh : r=%.4f m, cach nhau %.4f m\n",
|
||||
cfg.robot.geometry().wheel_radius,
|
||||
cfg.robot.geometry().wheel_separation);
|
||||
std::printf(" camera cao : %.4f m so voi san, chuc %.2f do\n",
|
||||
cfg.robot.camera_height_above_floor(),
|
||||
cfg.robot.camera_pitch() * 180.0 / 3.14159265358979323846);
|
||||
std::printf(" safety dung : %.3f m, cham lai tu %.3f m\n",
|
||||
cfg.safety.stop_distance, cfg.safety.slow_distance);
|
||||
std::printf(" cliff cua so : %.2f - %.2f m (duoi %.2f m la VUNG MU)\n",
|
||||
cfg.perception.cliff.min_dist, cfg.perception.cliff.max_dist,
|
||||
cfg.perception.cliff.min_dist);
|
||||
std::printf(" web : %s:%u%s\n", cfg.web.bind_address.c_str(),
|
||||
cfg.web.port,
|
||||
cfg.web.auth_token.empty() ? " (KHONG CO TOKEN)" : "");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// --- Chay ---
|
||||
vslam::Runtime runtime(&cfg, opts);
|
||||
g_runtime = &runtime;
|
||||
std::signal(SIGINT, OnSignal);
|
||||
std::signal(SIGTERM, OnSignal);
|
||||
|
||||
{
|
||||
const vslam::StatusResponse st = runtime.Start();
|
||||
if (!st.ok()) {
|
||||
std::fprintf(stderr, "khong khoi dong duoc: %s\n", st.message.c_str());
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
std::printf("\n vslam_node dang chay\n");
|
||||
std::printf(" nguon : %s\n",
|
||||
opts.source == vslam::SourceKind::kSim ? "mo phong"
|
||||
: opts.source == vslam::SourceKind::kReplay ? opts.replay_path.c_str()
|
||||
: "phan cung");
|
||||
std::printf(" web UI : http://localhost:%u\n",
|
||||
opts.port_override != 0 ? opts.port_override : cfg.web.port);
|
||||
std::printf(" cau hinh : %s\n", config_dir.c_str());
|
||||
std::printf(" Ctrl-C de dung\n\n");
|
||||
|
||||
runtime.Join();
|
||||
g_runtime = nullptr;
|
||||
std::printf("da dung.\n");
|
||||
return 0;
|
||||
}
|
||||
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
|
||||
255
app/src/runtime.h
Normal file
255
app/src/runtime.h
Normal file
@@ -0,0 +1,255 @@
|
||||
#ifndef VSLAM_APP_RUNTIME_H
|
||||
#define VSLAM_APP_RUNTIME_H
|
||||
|
||||
// Tien trinh duy nhat. So huu moi luong va moi stage.
|
||||
//
|
||||
// ================== BAN DO LUONG ==================
|
||||
// luong tan so uu tien lam gi
|
||||
// ------------------------------------------------------------------
|
||||
// safety 20 Hz SCHED_FIFO 50 DUONG DUY NHAT toi motor
|
||||
// source theo nguon FIFO 45 driver / sim / replay
|
||||
// web_tx 10 Hz CFS serialize va phat
|
||||
//
|
||||
// Cac stage con lai chay INLINE trong callback cua nguon, tren luong source.
|
||||
// Do la co y: chuoi perception (depth -> cloud -> loc -> can trong luc ->
|
||||
// cliff) tung la ba nodelet chung mot manager; o day no la ba loi goi ham
|
||||
// trong mot ham. Khong intrusive_ptr, khong dispatch theo topic, va thu tu
|
||||
// buoc la thu tu dong lenh.
|
||||
//
|
||||
// ================== QUY TAC SONG CON ==================
|
||||
// Luong `safety` KHONG chia se mutex nao voi luong `slam`.
|
||||
// `Rtabmap::process()` chan 100-600 ms; mot mutex chung la du de treo vong an
|
||||
// toan trong ngan do.
|
||||
//
|
||||
// Trong ban ROS dieu nay duoc bao dam MIEN PHI boi tien trinh rieng +
|
||||
// respawn="true". O day no la quy tac review, va chi ThreadSanitizer moi kiem
|
||||
// duoc. Cac mutex duoi day duoc dat ten theo DU LIEU chung bao ve, khong
|
||||
// theo luong, de review thay ngay cai nao cham vao cai nao.
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "app_config.h"
|
||||
#include "vslam/driver_interfaces.h"
|
||||
#include "vslam/ekf_se2.h"
|
||||
#include "vslam/perception_pipeline.h"
|
||||
#include "vslam/safety_monitor.h"
|
||||
#include "vslam/scan_sanitizer.h"
|
||||
#include "vslam/teleop_model.h"
|
||||
#include "vslam/web_server.h"
|
||||
#include "vslam/wheel_odometry.h"
|
||||
|
||||
#ifdef VSLAM_HAVE_SLAM
|
||||
#include "vslam/rtabmap_slam.h"
|
||||
#endif
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// Nguon du lieu: sim, replay, hay phan cung that. `vslam_node` KHONG phan
|
||||
// biet duoc -- do la ca ly do cac interface driver ton tai.
|
||||
enum class SourceKind { kSim, kReplay, kLive };
|
||||
|
||||
struct RuntimeOptions {
|
||||
SourceKind source = SourceKind::kSim;
|
||||
std::string replay_path;
|
||||
std::string map_yaml; // chi co nghia voi sim
|
||||
std::string world_path; // .world cua Gazebo; uu tien hon map_yaml
|
||||
double sim_start_x = 0.0, sim_start_y = 0.0, sim_start_yaw = 0.0;
|
||||
uint16_t port_override = 0; // 0 = dung system.yaml
|
||||
std::string token_override;
|
||||
|
||||
// Tran toc do, GHI DE ca robot.yaml lan safety.yaml. 0 = khong ghi de.
|
||||
//
|
||||
// ⚠️ CHO MO PHONG. `robot.yaml base.max_linear = 0.35` la gioi han CO HOC
|
||||
// that cua base; co nay khong lam base that chay nhanh hon, no chi go tran
|
||||
// trong mo phong de quet mot toa nha 58 m khong mat nua tieng.
|
||||
//
|
||||
// Phai ghi de CA HAI: lop safety kep lenh o `safety.yaml max_linear`, nen
|
||||
// chi nang tran teleop thoi thi so tren man hinh len 2.0 con robot van chay
|
||||
// 0.35 -- do dung la thu da xay ra truoc khi co co nay.
|
||||
double max_speed_override = 0.0;
|
||||
// Dat mot buc KINH chan ngang hanh lang o x = met nay. 0 = khong dat.
|
||||
// Kinh vo hinh voi LiDAR va depth; chi sieu am thay. Dung de chay nhanh
|
||||
// US_BLOCKED va BUMPER cua FSM -- hai nhanh chua bao gio chay end-to-end.
|
||||
double sim_glass_at = 0.0;
|
||||
bool force_slam = false; // --slam: ghi de slam.yaml enabled
|
||||
bool have_slam_db = false; // --slam-db "" nghia la DB trong RAM
|
||||
std::string slam_db;
|
||||
std::string slam_mode_override; // "mapping" | "localization"
|
||||
// Pose ban dau cho che do localization -- tuong duong /initialpose cua ban
|
||||
// ROS, thu ma `dock_init.py` phat tu dock.
|
||||
bool have_slam_init_pose = false;
|
||||
Pose2D slam_init_pose;
|
||||
};
|
||||
|
||||
class Runtime {
|
||||
public:
|
||||
Runtime(AppConfig* cfg, RuntimeOptions opts);
|
||||
~Runtime();
|
||||
|
||||
Runtime(const Runtime&) = delete;
|
||||
Runtime& operator=(const Runtime&) = delete;
|
||||
|
||||
StatusResponse Start();
|
||||
void RequestStop();
|
||||
void Join();
|
||||
|
||||
private:
|
||||
// wiring.cc -- noi duy nhat noi nguon voi stage. Tuong duong toan bo 20
|
||||
// file .launch cua ban ROS.
|
||||
StatusResponse Wire();
|
||||
|
||||
// runtime.cc
|
||||
StatusResponse OpenSource();
|
||||
void SafetyLoop();
|
||||
void WebLoop();
|
||||
void SlamLoop();
|
||||
void ApplyThreadPriority(std::thread* t, int prio, const char* name);
|
||||
|
||||
AppConfig* cfg_;
|
||||
RuntimeOptions opts_;
|
||||
|
||||
// --- Nguon ---
|
||||
// Giu bang con tro kieu co so: node khong biet minh dang chay live, replay
|
||||
// hay sim. Khong co nhanh `if (replay)` nao trong logic.
|
||||
struct SourceHolder;
|
||||
std::unique_ptr<SourceHolder> source_;
|
||||
LidarInterface* lidar_ = nullptr;
|
||||
CameraInterface* camera_ = nullptr;
|
||||
McuInterface* mcu_ = nullptr;
|
||||
BaseInterface* base_ = nullptr;
|
||||
ClockPtr clock_;
|
||||
|
||||
// --- Stage ---
|
||||
std::unique_ptr<ScanSanitizer> sanitizer_;
|
||||
std::unique_ptr<WheelOdometry> wheel_odom_;
|
||||
std::unique_ptr<EkfSe2> ekf_;
|
||||
std::unique_ptr<PerceptionPipeline> perception_;
|
||||
std::unique_ptr<SafetyMonitor> safety_;
|
||||
std::unique_ptr<TeleopModel> teleop_;
|
||||
std::unique_ptr<WebServer> web_;
|
||||
#ifdef VSLAM_HAVE_SLAM
|
||||
std::unique_ptr<RtabmapSlam> slam_;
|
||||
#endif
|
||||
|
||||
// --- Du lieu chia se, moi mutex bao ve dung mot nhom ---
|
||||
|
||||
// scan_mu_: scan da ve sinh gan nhat. Luong source ghi, luong safety va
|
||||
// web_tx doc.
|
||||
mutable std::mutex scan_mu_;
|
||||
LaserScanPtr latest_scan_;
|
||||
|
||||
// odom_mu_: wheel_odom_ va ekf_. CHI luong source cham vao chung; hai luong
|
||||
// kia chi doc ban sao pose.
|
||||
mutable std::mutex odom_mu_;
|
||||
Odometry latest_odom_;
|
||||
bool have_odom_ = false;
|
||||
|
||||
// perc_mu_: ket qua perception.
|
||||
mutable std::mutex perc_mu_;
|
||||
PointCloudXYZPtr latest_cloud_;
|
||||
PointCloudXYZPtr latest_cliff_cloud_;
|
||||
bool cliff_flag_ = false;
|
||||
UnixTime cliff_stamp_;
|
||||
bool have_cliff_ = false;
|
||||
std::string cliff_detail_;
|
||||
|
||||
// mcu_mu_: sieu am va bumper.
|
||||
//
|
||||
// Hai cam bien nay o tren MCU vi ca hai deu la cam bien MUC THAP phai toi
|
||||
// duoc vong an toan ke ca khi may tinh chinh dang ban. Luong source ghi,
|
||||
// luong safety doc o 20 Hz.
|
||||
mutable std::mutex mcu_mu_;
|
||||
std::map<std::string, double> ultrasonic_;
|
||||
UnixTime us_stamp_;
|
||||
bool have_us_ = false;
|
||||
bool bumper_ = false;
|
||||
UnixTime bumper_stamp_;
|
||||
bool have_bumper_ = false;
|
||||
|
||||
// cmd_mu_: lenh teleop THO, chua qua lop an toan.
|
||||
//
|
||||
// Luong web ghi, luong safety doc o 20 Hz. Luong web KHONG BAO GIO goi
|
||||
// thang SetVelocity -- xem ghi chu trong wiring.cc.
|
||||
mutable std::mutex cmd_mu_;
|
||||
Twist raw_cmd_;
|
||||
UnixTime raw_cmd_stamp_;
|
||||
bool have_raw_cmd_ = false;
|
||||
|
||||
// teleop_mu_: TeleopModel co trang thai (toc do dieu chinh duoc luc chay).
|
||||
mutable std::mutex teleop_mu_;
|
||||
|
||||
// safety_mu_: SafetyMonitor. KHONG duoc chia se voi bat ky mutex nao ma
|
||||
// luong slam cham toi.
|
||||
mutable std::mutex safety_mu_;
|
||||
SafetyOutput last_safety_;
|
||||
|
||||
// Quy dao de ve len web.
|
||||
mutable std::mutex traj_mu_;
|
||||
std::vector<Pose2D> trajectory_;
|
||||
UnixTime last_traj_stamp_;
|
||||
|
||||
// slam_mu_: ket qua cua SLAM.
|
||||
//
|
||||
// ⚠️ QUY TAC SONG CON: mutex nay KHONG duoc luong safety cham vao, va luong
|
||||
// slam KHONG duoc giu bat ky mutex nao trong luc goi `Process()` --
|
||||
// `Rtabmap::process()` chan 100-600 ms (p95 do duoc 722-1008 ms tren may
|
||||
// nay). Xem SlamLoop().
|
||||
//
|
||||
// Luong slam chi cham `scan_mu_` va `odom_mu_` de COPY mot shared_ptr va
|
||||
// mot Pose2D, roi nha ngay. Do la khuon mau `Channel::Latest()`: mot lan
|
||||
// copy duoi mutex, khong bao gio giu lock khi goi code nang.
|
||||
mutable std::mutex slam_mu_;
|
||||
Pose2D map_correction_;
|
||||
bool slam_localized_ = false;
|
||||
uint64_t slam_map_version_ = 0;
|
||||
uint64_t slam_published_version_ = 0;
|
||||
// Thanh phan ban do lan truoc, de chi log KHI DOI. Xem ghi chu o cho log.
|
||||
size_t last_map_occ_ = 0;
|
||||
size_t last_map_free_ = 0;
|
||||
OccupancyGridPtr slam_map_;
|
||||
double slam_process_ms_ = 0.0;
|
||||
int slam_loops_ = 0;
|
||||
|
||||
// Doc-only sau Start(), nen khong can mutex.
|
||||
bool slam_enabled_ = false;
|
||||
bool slam_should_save_ = false;
|
||||
// Tran toc do dang dung (m/s): tu robot.yaml, hoac --max-speed ghi de.
|
||||
double speed_limit_ = 0.35;
|
||||
#ifdef VSLAM_HAVE_SLAM
|
||||
SlamMode slam_mode_ = SlamMode::kMapping;
|
||||
#endif
|
||||
|
||||
// Nghieng, CHI de hien thi. Luong source ghi o 200 Hz, luong web doc o
|
||||
// 10 Hz.
|
||||
//
|
||||
// ⚠️ ThreadSanitizer da bat dung cho nay: truoc do WebLoop goi thang
|
||||
// `perception_->gravity().roll()` trong khi luong source dang ghi bien do
|
||||
// trong `FeedImu`. `GravityAlign` co hop dong la MOT LUONG -- sua bang
|
||||
// cach them khoa vao thu vien se pha hop dong do va bat moi nguoi dung
|
||||
// tra gia cho mot nhu cau chi cua rieng web UI.
|
||||
//
|
||||
// Ba atomic rieng, KHONG phai mot bo ba nguyen tu: doc co the lay roll cua
|
||||
// mau N va pitch cua mau N+1. Voi mot so hien tren man hinh o 10 Hz thi
|
||||
// dieu do vo hai, va noi ro o day con hon gia vo rang no nguyen tu.
|
||||
std::atomic<double> tilt_roll_{0.0};
|
||||
std::atomic<double> tilt_pitch_{0.0};
|
||||
std::atomic<bool> tilt_accel_ok_{false};
|
||||
|
||||
std::atomic<bool> estop_{false};
|
||||
std::atomic<bool> stop_{false};
|
||||
|
||||
std::thread source_thread_;
|
||||
std::thread safety_thread_;
|
||||
std::thread web_thread_;
|
||||
std::thread slam_thread_;
|
||||
};
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_APP_RUNTIME_H
|
||||
234
app/src/wiring.cc
Normal file
234
app/src/wiring.cc
Normal file
@@ -0,0 +1,234 @@
|
||||
// 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);
|
||||
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.
|
||||
ekf_->UpdateOdomTwist(e.stamp, o.twist.twist.linear.x,
|
||||
o.twist.twist.angular.z, o.twist.covariance[0],
|
||||
o.twist.covariance[35]);
|
||||
latest_odom_ = o;
|
||||
have_odom_ = 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;
|
||||
// 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_);
|
||||
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();
|
||||
}
|
||||
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;
|
||||
}));
|
||||
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
Reference in New Issue
Block a user