This commit is contained in:
trung09122002
2026-09-18 18:14:42 +07:00
commit 48bd5377dc
224 changed files with 37685 additions and 0 deletions

View File

@@ -0,0 +1,67 @@
# Nen tang cua ca he. Dep ngoai: Eigen3 (chi header, dung trong geometry) va
# yaml-cpp (config). Khong gi khac -- moi lib kia phu thuoc lib nay nen giu no
# nhe la dieu kien de P0 build duoc truoc khi co RTAB-Map hay PCL.
find_package(Eigen3 REQUIRED)
find_package(yaml-cpp REQUIRED)
find_package(Threads REQUIRED)
vslam_add_library(vslam_common
PUBLIC_HDRS
vslam_common.h
unix_time.h
clock.h
log.h
config.h
node_constants.h
geometry.h
stats.h
json_parse.h
robot_model.h
teleop_model.h
channel.h
approx_sync.h
buffer_pool.h
transform_tree.h
# FIND_DEPS chi liet ke dep PUBLIC -- tuc la dep co mat trong
# INTERFACE_LINK_LIBRARIES cua target da cai, nen nguoi dung thu vien PHAI
# co chung. yaml-cpp link PRIVATE nen khong nam trong do: dua no vao day se
# bat nguoi dung phai cai yaml-cpp mot cach vo co.
#
# Nguoc lai, thieu mot dep PUBLIC o day thi find_package() that bai voi thong
# bao "links to target Threads::Threads but the target was not found" --
# dung loai loi ma file Config.cmake nay sinh ra de chan.
FIND_DEPS
Eigen3
Threads
)
# yaml-cpp: ten target khac nhau theo phien ban va theo cach cai.
# 0.6 (focal, apt) -> bien yaml-cpp_LIBRARIES, doi khi target `yaml-cpp`
# 0.7 (jammy, apt) -> target `yaml-cpp`
# >=0.8 / vcpkg -> target `yaml-cpp::yaml-cpp`
# Dung sai ten o day la loi link kho doc tren Jetson, nen do het truong hop.
if(TARGET yaml-cpp::yaml-cpp)
target_link_libraries(vslam_common PRIVATE yaml-cpp::yaml-cpp)
elseif(TARGET yaml-cpp)
target_link_libraries(vslam_common PRIVATE yaml-cpp)
else()
target_include_directories(vslam_common SYSTEM PRIVATE ${YAML_CPP_INCLUDE_DIR})
target_link_libraries(vslam_common PRIVATE ${YAML_CPP_LIBRARIES})
endif()
if(TARGET Eigen3::Eigen)
target_link_libraries(vslam_common PUBLIC Eigen3::Eigen)
else()
target_include_directories(vslam_common SYSTEM PUBLIC ${EIGEN3_INCLUDE_DIR})
endif()
# Moi target trong cay phai cung mot EIGEN_MAX_ALIGN_BYTES. Dat PUBLIC o day
# de no lan sang moi lib phu thuoc vslam_common -- do la toan bo cay.
# Xem ke hoach, muc "Bay arm64": hai phia compile voi gia tri khac nhau sinh
# loi alignment chi hien ra luc chay, tren arm64, khong tai lap on dinh.
target_compile_definitions(vslam_common
PUBLIC EIGEN_MAX_ALIGN_BYTES=${VSLAM_EIGEN_MAX_ALIGN_BYTES})
# PUBLIC: Channel va TransformTree deu co std::mutex trong header cong khai.
target_link_libraries(vslam_common PUBLIC Threads::Threads)

View File

@@ -0,0 +1,345 @@
#ifndef VSLAM_APPROX_SYNC_H
#define VSLAM_APPROX_SYNC_H
// Thay message_filters::Synchronizer<ApproximateTime<...>>.
//
// Cau hinh hien tai can khop lai: rtabmap.launch:235-237 dat approx_sync=true,
// sync_queue_size=30, dong bo scan + odom + depth + rgb.
// cliff_detect_nodelet.cpp:101-102 dong bo depth + camera_info.
//
// Thuat toan o day DON GIAN VA DE DOAN HON ApproximateTime cua ROS. ROS dung
// mot thuat toan toi uu cua so co the giu ban tin lai kha lau va rat kho suy
// luan khi mot nguon tut. O day:
//
// 1. Moi ban tin moi o stream PIVOT (scan, 25 Hz -- cham nhat) tao mot moc.
// 2. Voi moi stream khac, chon ban tin co |stamp - pivot| nho nhat, yeu cau
// <= max_slop_sec.
// 3. Phat khi:
// (a) du moi stream REQUIRED, va moi stream TUY CHON hoac da co hoac ban
// tin moi nhat cua no DA VUOT pivot (khong the khop hon duoc nua); hoac
// (b) now - pivot > wait_timeout_sec -- phat voi stream tuy chon de trong.
// 4. Pivot cu hon queue_size bi bo, dem vao dropped_queue.
//
// Nhanh (b) khong lam mat tin hieu: RTAB-Map chay duoc voi scan + odom ma
// khong can depth (subscribe_depth la tuy chon), chi mat visual word.
//
// SyncStats dem RIENG ba loai drop -- slop, timeout, queue -- vi ba nguyen
// nhan nay can ba cach sua khac han nhau:
// slop -> lech dong ho giua hai nguon, hoac max_slop_sec qua chat
// timeout -> mot nguon cham hon du kien hoac da chet
// queue -> consumer khong theo kip producer
#include <algorithm>
#include <array>
#include <cmath>
#include <cstddef>
#include <deque>
#include <functional>
#include <memory>
#include <mutex>
#include <tuple>
#include <utility>
#include <vector>
#include "vslam/stats.h"
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
template <typename... Ts>
class ApproxTimeSync {
public:
static constexpr size_t kN = sizeof...(Ts);
using Tuple = std::tuple<std::shared_ptr<const Ts>...>;
using Callback = std::function<void(UnixTime pivot_stamp, const Tuple&)>;
struct Options {
size_t queue_size = 30; // khop sync_queue_size=30 hien tai
double max_slop_sec = 0.05; // ~1.5 khung camera o 30 Hz
double wait_timeout_sec = 0.20; // het han cho input tuy chon
size_t pivot_index = 0; // stream cham nhat lam moc (scan)
std::array<bool, kN> required{}; // scan+odom = true; depth+infra = false
};
ApproxTimeSync(Options opt, Callback cb)
: opt_(std::move(opt)), cb_(std::move(cb)) {
if (opt_.queue_size == 0) opt_.queue_size = 1;
if (opt_.pivot_index >= kN) opt_.pivot_index = 0;
}
// Them ban tin vao stream thu I.
template <size_t I>
void Add(UnixTime stamp,
std::shared_ptr<const std::tuple_element_t<I, std::tuple<Ts...>>> msg) {
static_assert(I < kN, "chi so stream vuot so stream");
std::vector<std::pair<UnixTime, Tuple>> emit;
{
std::lock_guard<std::mutex> lk(mu_);
auto& q = queues_[I];
if (!q.empty() && stamp < q.back().stamp) {
// Stamp lui: ban ghi bi xao tron hoac hai nguon ghi cung stream.
stats_.dropped_queue++;
return;
}
q.push_back(Slot{stamp, std::static_pointer_cast<const void>(std::move(msg))});
while (q.size() > opt_.queue_size) {
q.pop_front();
if (I == opt_.pivot_index) stats_.dropped_queue++;
}
CollectLocked(kTimeZero, false, &emit);
}
Fire(emit);
}
// Lai nhanh wait_timeout. Goi tu vong lap cua luong so huu sync.
void Tick(UnixTime now) {
std::vector<std::pair<UnixTime, Tuple>> emit;
{
std::lock_guard<std::mutex> lk(mu_);
CollectLocked(now, true, &emit);
}
Fire(emit);
}
SyncStats stats() const {
std::lock_guard<std::mutex> lk(mu_);
return stats_;
}
void Reset() {
std::lock_guard<std::mutex> lk(mu_);
for (auto& q : queues_) q.clear();
stats_ = SyncStats{};
}
private:
struct Slot {
UnixTime stamp;
std::shared_ptr<const void> msg;
};
// Goi khi da giu mu_. Khong goi callback o day -- chi gom vao `emit`.
void CollectLocked(UnixTime now, bool allow_timeout,
std::vector<std::pair<UnixTime, Tuple>>* emit) {
auto& pivot_q = queues_[opt_.pivot_index];
while (!pivot_q.empty()) {
const UnixTime pivot = pivot_q.front().stamp;
std::array<size_t, kN> pick{};
std::array<bool, kN> have{};
bool all_required = true;
bool all_settled = true;
double worst_slop = 0.0;
for (size_t s = 0; s < kN; ++s) {
if (s == opt_.pivot_index) {
pick[s] = 0;
have[s] = true;
continue;
}
const auto& q = queues_[s];
if (q.empty()) {
all_settled = false;
if (opt_.required[s]) all_required = false;
continue;
}
size_t best = 0;
double best_d = std::abs(SecondsBetween(q[0].stamp, pivot));
for (size_t i = 1; i < q.size(); ++i) {
const double d = std::abs(SecondsBetween(q[i].stamp, pivot));
if (d < best_d) { best_d = d; best = i; }
}
if (best_d <= opt_.max_slop_sec) {
pick[s] = best;
have[s] = true;
worst_slop = std::max(worst_slop, best_d);
} else {
if (opt_.required[s]) all_required = false;
// Ban tin moi nhat cua stream nay DA VUOT pivot: khong the khop hon
// duoc nua, nen stream coi nhu da chot (du la chot rong).
if (q.back().stamp <= pivot) all_settled = false;
}
}
const bool timed_out =
allow_timeout && !now.isZero() &&
SecondsBetween(now, pivot) > opt_.wait_timeout_sec;
if (!all_required) {
if (!timed_out) break; // con co the cho them
// Het gio ma van thieu stream bat buoc -> bo pivot nay.
stats_.dropped_timeout++;
pivot_q.pop_front();
continue;
}
if (!all_settled && !timed_out) break; // cho stream tuy chon
Tuple t;
FillTuple(t, pick, have, std::index_sequence_for<Ts...>{});
emit->emplace_back(pivot, std::move(t));
stats_.matched++;
stats_.last_slop_sec = worst_slop;
if (timed_out && !all_settled) stats_.dropped_timeout++;
// Bo moi ban tin da dung va moi ban tin cu hon no.
for (size_t s = 0; s < kN; ++s) {
if (s == opt_.pivot_index || !have[s]) continue;
auto& q = queues_[s];
q.erase(q.begin(), q.begin() + static_cast<long>(pick[s]) + 1);
}
pivot_q.pop_front();
}
}
template <size_t... Is>
void FillTuple(Tuple& t, const std::array<size_t, kN>& pick,
const std::array<bool, kN>& have, std::index_sequence<Is...>) {
(void)std::initializer_list<int>{
(std::get<Is>(t) =
have[Is] ? std::static_pointer_cast<
const std::tuple_element_t<Is, std::tuple<Ts...>>>(
queues_[Is][pick[Is]].msg)
: nullptr,
0)...};
}
// Goi callback NGOAI khoa. Callback cua SLAM chan 100-600 ms; giu khoa
// trong do se chan luong lidar_rx.
void Fire(const std::vector<std::pair<UnixTime, Tuple>>& emit) {
for (const auto& e : emit) cb_(e.first, e.second);
}
Options opt_;
Callback cb_;
mutable std::mutex mu_;
std::array<std::deque<Slot>, kN> queues_;
SyncStats stats_;
};
// --- Bien the hai luong ----------------------------------------------------
// Truong hop hai nguon pho bien den muc dang co ban rieng: de doc hon, compile
// nhanh hon, va khong phai dien std::array<bool,2> cho moi lan dung.
// Dung boi cliff_detect (depth + camera_info).
//
// HEADER-ONLY, khong pimpl. Ban dau viet pimpl + khoi tao tuong minh cho
// PairSync<Image, CameraInfo>, nhung nhu the thi khong ai dung duoc no voi
// kieu khac -- ke ca unit test voi struct gia. Voi mot lop nho nhu nay thi
// cai gia cua pimpl (mot ban khoi tao tuong minh cho moi cap kieu) lon hon
// cai loi.
template <typename A, typename B>
class PairSync {
public:
using Callback = std::function<void(UnixTime, std::shared_ptr<const A>,
std::shared_ptr<const B>)>;
PairSync(size_t queue_size, double max_slop_sec, Callback cb)
: queue_size_(queue_size == 0 ? 1 : queue_size),
max_slop_sec_(max_slop_sec),
cb_(std::move(cb)) {}
void AddFirst(UnixTime stamp, std::shared_ptr<const A> msg) {
std::vector<Emit> emit;
{
std::lock_guard<std::mutex> lk(mu_);
qa_.push_back(SlotA{stamp, std::move(msg)});
TrimLocked();
MatchLocked(&emit);
}
Fire(emit);
}
void AddSecond(UnixTime stamp, std::shared_ptr<const B> msg) {
std::vector<Emit> emit;
{
std::lock_guard<std::mutex> lk(mu_);
qb_.push_back(SlotB{stamp, std::move(msg)});
TrimLocked();
MatchLocked(&emit);
}
Fire(emit);
}
SyncStats stats() const {
std::lock_guard<std::mutex> lk(mu_);
return stats_;
}
void Reset() {
std::lock_guard<std::mutex> lk(mu_);
qa_.clear();
qb_.clear();
stats_ = SyncStats{};
}
private:
struct SlotA { UnixTime stamp; std::shared_ptr<const A> msg; };
struct SlotB { UnixTime stamp; std::shared_ptr<const B> msg; };
struct Emit {
UnixTime stamp;
std::shared_ptr<const A> a;
std::shared_ptr<const B> b;
};
// Goi khi da giu mu_. Chi gom vao `emit`, khong goi callback o day.
void MatchLocked(std::vector<Emit>* emit) {
while (!qa_.empty() && !qb_.empty()) {
const SlotA& a = qa_.front();
size_t best = 0;
double best_d = std::abs(SecondsBetween(qb_[0].stamp, a.stamp));
for (size_t i = 1; i < qb_.size(); ++i) {
const double d = std::abs(SecondsBetween(qb_[i].stamp, a.stamp));
if (d < best_d) { best_d = d; best = i; }
}
if (best_d <= max_slop_sec_) {
emit->push_back(Emit{a.stamp, a.msg, qb_[best].msg});
stats_.matched++;
stats_.last_slop_sec = best_d;
// Bo moi phan tu b cu hon phan tu vua khop: chung khong con co hoi
// khop voi bat ky a nao ve sau (a chi tien len).
qb_.erase(qb_.begin(), qb_.begin() + static_cast<long>(best) + 1);
qa_.pop_front();
continue;
}
// Chua khop duoc. Neu a da cu hon MOI phan tu b thi no khong bao gio
// khop nua -> bo. Nguoc lai thi cho them b.
if (a.stamp < qb_.back().stamp) {
stats_.dropped_slop++;
qa_.pop_front();
continue;
}
break;
}
}
void TrimLocked() {
while (qa_.size() > queue_size_) { qa_.pop_front(); stats_.dropped_queue++; }
while (qb_.size() > queue_size_) { qb_.pop_front(); stats_.dropped_queue++; }
}
// Goi callback NGOAI khoa. Callback cua cliff_detect lam viec nang
// (ray-cast toan anh depth); giu khoa trong do se chan luong camera.
void Fire(const std::vector<Emit>& emit) {
for (const auto& e : emit) cb_(e.stamp, e.a, e.b);
}
size_t queue_size_;
double max_slop_sec_;
Callback cb_;
mutable std::mutex mu_;
std::deque<SlotA> qa_;
std::deque<SlotB> qb_;
SyncStats stats_;
};
} // namespace vslam
#endif // VSLAM_APPROX_SYNC_H

View File

@@ -0,0 +1,92 @@
#ifndef VSLAM_BUFFER_POOL_H
#define VSLAM_BUFFER_POOL_H
// Pool tai su dung buffer, de chuoi perception khong cap phat gi o trang thai
// on dinh.
//
// Chuoi hien tai moi khung sinh: cloud_raw (320x240 = 76800 diem) ->
// cloud_filtered -> cloud_aligned. Neu moi buoc malloc mot vector moi thi o
// 10 Hz la ~9 MB/s di qua allocator, va tren Jetson dieu do the hien thanh
// jitter chu khong phai thong luong.
//
// Cach dung: hai buffer luan phien, 0 malloc o trang thai on dinh.
// Acquire() tra shared_ptr co deleter tu tra ve pool. Neu pool da bi huy
// truoc object thi deleter xoa that -- an toan khi tat may.
//
// allocated() ra /api/status: con so nay khong duoc tang sau khi he chay on
// dinh. Tang nghia la co cho giu shared_ptr lau hon can (ro ri thuc su, hoac
// mot Channel capacity qua lon).
#include <atomic>
#include <cstddef>
#include <memory>
#include <mutex>
#include <vector>
namespace vslam {
template <typename T>
class BufferPool : public std::enable_shared_from_this<BufferPool<T>> {
public:
// max_idle: giu toi da bao nhieu buffer roi. Vuot qua thi tra buffer se xoa
// that thay vi giu -- tranh pool phinh vinh vien sau mot dot tai cao.
static std::shared_ptr<BufferPool<T>> Create(size_t max_idle = 4) {
return std::shared_ptr<BufferPool<T>>(new BufferPool<T>(max_idle));
}
std::shared_ptr<T> Acquire() {
std::unique_ptr<T> obj;
{
std::lock_guard<std::mutex> lk(mu_);
if (!idle_.empty()) {
obj = std::move(idle_.back());
idle_.pop_back();
}
}
if (!obj) {
obj = std::make_unique<T>();
allocated_.fetch_add(1, std::memory_order_relaxed);
}
// weak_ptr: neu pool chet truoc object thi deleter xoa that.
std::weak_ptr<BufferPool<T>> weak = this->shared_from_this();
T* raw = obj.release();
return std::shared_ptr<T>(raw, [weak](T* p) {
if (auto pool = weak.lock()) {
pool->Release(std::unique_ptr<T>(p));
} else {
delete p;
}
});
}
size_t idle() const {
std::lock_guard<std::mutex> lk(mu_);
return idle_.size();
}
size_t allocated() const { return allocated_.load(std::memory_order_relaxed); }
void Clear() {
std::lock_guard<std::mutex> lk(mu_);
idle_.clear();
}
private:
explicit BufferPool(size_t max_idle) : max_idle_(max_idle) {}
void Release(std::unique_ptr<T> obj) {
std::lock_guard<std::mutex> lk(mu_);
if (idle_.size() >= max_idle_) return; // xoa that
idle_.push_back(std::move(obj));
}
const size_t max_idle_;
mutable std::mutex mu_;
std::vector<std::unique_ptr<T>> idle_;
std::atomic<size_t> allocated_{0};
};
} // namespace vslam
#endif // VSLAM_BUFFER_POOL_H

View File

@@ -0,0 +1,247 @@
#ifndef VSLAM_CHANNEL_H
#define VSLAM_CHANNEL_H
// Thay pub/sub cua ROS.
//
// QUY TAC RANH GIOI -- doc truoc khi dung:
//
// Channel<T> CHI dung khi du lieu di QUA BIEN LUONG.
// Trong cung mot luong: goi ham truc tiep.
//
// Day la cach giu nguyen loi the "3 nodelet chung 1 manager" cua ban ROS.
// Chuoi depth_to_cloud -> depth_filter -> gravity_align -> cliff_detect chay
// inline tren chinh luong camera trong mot loi goi PerceptionPipeline::Process().
// Tot hon nodelet manager: khong intrusive_ptr, khong dispatch theo topic,
// khong nodelet loader.
//
// Don vi du lieu duy nhat la std::shared_ptr<const T>. Publish() copy mot
// con tro (mot atomic increment), khong bao gio copy cloud/anh/scan.
//
// KHAC BIET QUAN TRONG SO VOI QUEUE CUA ROS: so ban tin bi bo duoc DEM va bao
// cao ra /api/status. Queue cua ROS drop im lang, va do la ly do repo cu phai
// doan mo ve viec costmap co nhan du cloud hay khong.
//
// AN TOAN LUONG:
// * Publish() khong bao gio chan. Day la bat buoc: luong lidar_rx hay
// camera_rx khong duoc phep dung cho luong slam (Rtabmap::process() chan
// 100-600 ms).
// * Latest() la duong doc cua luong safety: mot lan copy shared_ptr duoi
// khoa, khong bao gio giu khoa khi goi code nguoi dung.
// * Tap Reader co dinh truoc khi chay. MakeReader() phai goi xong trong
// giai doan wiring, khong duoc goi khi he dang chay.
#include <atomic>
#include <cassert>
#include <condition_variable>
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "vslam/stats.h"
#include "vslam/unix_time.h"
namespace vslam {
template <typename T>
class Channel {
public:
using Ptr = std::shared_ptr<const T>;
struct Item {
Ptr msg;
UnixTime stamp;
uint64_t seq = 0;
};
Channel(size_t capacity, std::string name)
: capacity_(capacity), name_(std::move(name)), ring_(capacity) {
assert(capacity > 0 && "Channel capacity phai > 0");
}
Channel(const Channel&) = delete;
Channel& operator=(const Channel&) = delete;
// Khong bao gio chan. Tra ve false neu phai ghi de mot phan tu ma con reader
// chua doc toi -- goi co the dung gia tri nay de dem hoac de canh bao.
bool Publish(Ptr msg, UnixTime stamp) {
bool overwrote = false;
{
std::lock_guard<std::mutex> lk(mu_);
const uint64_t seq = head_++;
// Ghi de o cu nhat neu vong da day.
if (seq >= capacity_) {
const uint64_t evicted = seq - capacity_;
for (const auto& r : readers_) {
if (r->cursor.load(std::memory_order_relaxed) <= evicted) {
overwrote = true;
break;
}
}
}
Item& slot = ring_[seq % capacity_];
slot.msg = std::move(msg);
slot.stamp = stamp;
slot.seq = seq;
latest_ = slot;
published_++;
if (overwrote) overwritten_++;
}
rate_.Tick();
cv_.notify_all();
return !overwrote;
}
// Con tro doc rieng cua tung consumer. Khong sao chep duoc -- moi consumer
// giu mot Reader va chi minh no dung.
class Reader {
public:
// Chan toi khi co ban tin moi hoac het `timeout`. Tra false neu het gio
// hoac channel da dong.
bool Read(Ptr* out, UnixTime* stamp, std::chrono::milliseconds timeout) {
std::unique_lock<std::mutex> lk(ch_->mu_);
const bool got = ch_->cv_.wait_for(lk, timeout, [this] {
return ch_->closed_ || state_->cursor.load(std::memory_order_relaxed) < ch_->head_;
});
if (!got || ch_->closed_) return false;
return PopLocked(out, stamp);
}
// Khong chan.
bool TryRead(Ptr* out, UnixTime* stamp) {
std::lock_guard<std::mutex> lk(ch_->mu_);
if (state_->cursor.load(std::memory_order_relaxed) >= ch_->head_) return false;
return PopLocked(out, stamp);
}
// So ban tin reader nay KHONG BAO GIO nhin thay vi bi ghi de.
uint64_t dropped() const { return state_->dropped.load(std::memory_order_relaxed); }
// So ban tin dang cho doc.
uint64_t lag() const {
std::lock_guard<std::mutex> lk(ch_->mu_);
const uint64_t c = state_->cursor.load(std::memory_order_relaxed);
return ch_->head_ > c ? ch_->head_ - c : 0;
}
const std::string& name() const { return state_->name; }
private:
friend class Channel<T>;
struct State {
std::atomic<uint64_t> cursor{0};
std::atomic<uint64_t> dropped{0};
std::string name;
};
Reader(Channel<T>* ch, State* st) : ch_(ch), state_(st) {}
// Goi khi da giu mu_.
bool PopLocked(Ptr* out, UnixTime* stamp) {
uint64_t c = state_->cursor.load(std::memory_order_relaxed);
const uint64_t oldest = ch_->head_ > ch_->capacity_ ? ch_->head_ - ch_->capacity_ : 0;
if (c < oldest) {
// Reader da bi nhay qua. Dem phan mat roi tua toi o cu nhat con song.
state_->dropped.fetch_add(oldest - c, std::memory_order_relaxed);
c = oldest;
}
const Item& slot = ch_->ring_[c % ch_->capacity_];
*out = slot.msg;
if (stamp) *stamp = slot.stamp;
state_->cursor.store(c + 1, std::memory_order_relaxed);
return true;
}
Channel<T>* ch_ = nullptr;
State* state_ = nullptr;
};
// Phai goi xong trong giai doan wiring, truoc khi bat ky luong nao chay.
// `name` chi de bao cao so lieu.
Reader MakeReader(std::string name) {
std::lock_guard<std::mutex> lk(mu_);
assert(!started_ && "MakeReader() sau khi he da chay");
auto st = std::make_unique<typename Reader::State>();
st->name = std::move(name);
st->cursor.store(head_, std::memory_order_relaxed); // bat dau tu hien tai
auto* raw = st.get();
readers_.push_back(std::move(st));
return Reader(this, raw);
}
// Danh dau ket thuc wiring. Sau loi goi nay MakeReader() se assert.
void Freeze() {
std::lock_guard<std::mutex> lk(mu_);
started_ = true;
}
// O(1), khong dung cursor. Day la duong doc cua luong safety va web_tx:
// chung khong quan tam lich su, chi can ban moi nhat.
bool Latest(Ptr* out, UnixTime* stamp = nullptr) const {
std::lock_guard<std::mutex> lk(mu_);
if (!latest_.msg) return false;
*out = latest_.msg;
if (stamp) *stamp = latest_.stamp;
return true;
}
// Danh thuc moi reader dang cho.
void Close() {
{
std::lock_guard<std::mutex> lk(mu_);
closed_ = true;
}
cv_.notify_all();
}
bool closed() const {
std::lock_guard<std::mutex> lk(mu_);
return closed_;
}
ChannelStats stats() const {
std::lock_guard<std::mutex> lk(mu_);
ChannelStats s;
s.name = name_;
s.capacity = capacity_;
s.published = published_;
s.overwritten = overwritten_;
s.readers = readers_.size();
s.hz = rate_.hz();
for (const auto& r : readers_) {
const uint64_t c = r->cursor.load(std::memory_order_relaxed);
const uint64_t lag = head_ > c ? head_ - c : 0;
if (lag > s.max_reader_lag) s.max_reader_lag = lag;
s.total_reader_drops += r->dropped.load(std::memory_order_relaxed);
}
return s;
}
const std::string& name() const { return name_; }
size_t capacity() const { return capacity_; }
private:
mutable std::mutex mu_;
std::condition_variable cv_;
const size_t capacity_;
const std::string name_;
std::vector<Item> ring_;
uint64_t head_ = 0; // seq se cap cho lan Publish ke tiep
Item latest_;
bool closed_ = false;
bool started_ = false;
uint64_t published_ = 0;
uint64_t overwritten_ = 0;
mutable RateMonitor rate_{2.0};
std::vector<std::unique_ptr<typename Reader::State>> readers_;
};
} // namespace vslam
#endif // VSLAM_CHANNEL_H

View File

@@ -0,0 +1,92 @@
#ifndef VSLAM_CLOCK_H
#define VSLAM_CLOCK_H
// QUY TAC TU NGAY DAU, KHONG RETROFIT DUOC SAU:
//
// Khong stage nao duoc goi UnixTime::now() hay steady_clock::now() truc tiep.
// Moi stage nhan mot `std::shared_ptr<Clock>` qua constructor.
//
// Ly do: replay tat dinh. Neu mot stage doc dong ho that thi chay lai cung mot
// file .vsr se cho ket qua khac, va toan bo tang 2 cua chien luoc kiem chung
// (regress.sh so JSON voi expected/) sup do. Bo qua quy tac nay bay gio nghia
// la khong bao gio lam duoc replay tat dinh sau.
//
// Clock tach LAM HAI ham khong phai ngau nhien -- day la quy tac hai dong ho
// noi o unix_time.h:
//
// Now() -> UnixTime, tu system_clock. Dung DONG DAU du lieu. Co the nhay
// khi NTP dieu chinh.
// Steady() -> steady_clock. Dung do THOI LUONG va tinh TIMEOUT. Khong bao gio
// nhay, khong bao gio lui.
//
// safety_monitor_node.cpp hien dung ros::Time::now() cho ca hai. 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. Day la bug that
// dang nam trong repo, va viec tach hai ham o day la cach sua no.
#include <chrono>
#include <memory>
#include "vslam/unix_time.h"
namespace vslam {
class Clock {
public:
using SteadyPoint = std::chrono::steady_clock::time_point;
virtual ~Clock() = default;
// Dong dau du lieu.
virtual UnixTime Now() const = 0;
// Do thoi luong va tinh timeout.
virtual SteadyPoint Steady() const = 0;
// Ngu toi mot moc steady. Ban replay khong ngu that.
virtual void SleepUntil(SteadyPoint tp) = 0;
// true neu day la dong ho ao (replay). Chi dung de log, khong duoc dung de
// re nhanh logic -- neu can re nhanh thi thiet ke da sai.
virtual bool is_virtual() const = 0;
void SleepFor(std::chrono::nanoseconds d) { SleepUntil(Steady() + d); }
};
using ClockPtr = std::shared_ptr<Clock>;
// Dong ho that: system_clock cho Now(), steady_clock cho Steady().
ClockPtr MakeSystemClock();
// Dong ho ao cho replay. Thoi gian chi tien khi co nguoi goi Advance() hoac
// SleepUntil(). Trong che do --deterministic thi replay source lai no theo
// dung thu tu stamp cua ban ghi.
class ReplayClock : public Clock {
public:
explicit ReplayClock(UnixTime start);
~ReplayClock() override;
UnixTime Now() const override;
SteadyPoint Steady() const override;
void SleepUntil(SteadyPoint tp) override;
bool is_virtual() const override { return true; }
// Dat thoi gian ao. Chi lui neu `allow_backward` -- lui thoi gian la dau
// hieu ban ghi bi xao tron thu tu, mac dinh phai bao loi.
void SetNow(UnixTime t, bool allow_backward = false);
void Advance(Duration d);
// He so toc do doi voi thoi gian tuong that khi SleepUntil() thuc su ngu.
// 0 = chay nhanh nhat co the (khong ngu). 1 = thoi gian that.
void SetSpeed(double speed);
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
std::shared_ptr<ReplayClock> MakeReplayClock(UnixTime start);
} // namespace vslam
#endif // VSLAM_CLOCK_H

View File

@@ -0,0 +1,134 @@
#ifndef VSLAM_CONFIG_H
#define VSLAM_CONFIG_H
// Doc cau hinh YAML. Bao yaml-cpp de khong ro kieu cua no ra API cong khai.
//
// HAI THU MA BAN ROS THIEU, va ca hai deu da gay ton that that:
//
// 1. require<T>() -- nem loi kem TEN KEY DAY DU khi thieu.
// Hien tai pnh_.param("stop_distance", stop_distance_, 0.35) khien mot key
// go sai AM THAM roi ve default C++ va khong ai biet. Voi tham so an toan
// (stop_distance, min_front_rays) hay hinh hoc (wheel_separation) thi day
// la kieu loi im lang nguy hiem nhat: he van chay, chi la chay sai.
//
// 2. UnknownKeys() -- liet ke key CO trong file nhung KHONG co trong danh
// sach biet truoc. Bat duoc "stop_distence". Kiem o startup, log ERROR.
//
// Quy tac: dung require() cho moi thu lien quan an toan, hinh hoc, va duong
// dan. Dung get(key, fallback) chi cho tuy chon thuc su co default hop ly.
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
namespace vslam {
class ConfigError : public std::runtime_error {
public:
explicit ConfigError(const std::string& msg) : std::runtime_error(msg) {}
};
class ConfigNode {
public:
ConfigNode();
ConfigNode(const ConfigNode&);
ConfigNode(ConfigNode&&) noexcept;
ConfigNode& operator=(const ConfigNode&);
ConfigNode& operator=(ConfigNode&&) noexcept;
~ConfigNode();
// Nem ConfigError neu file khong doc duoc hoac YAML sai cu phap.
static ConfigNode LoadFile(const std::string& path);
static ConfigNode LoadString(const std::string& yaml, std::string origin = "<string>");
// Key thieu tra ve node Null thay vi nem -- de chuoi a["b"]["c"] khong no
// giua chung. Cho phep kiem IsNull() o cuoi.
ConfigNode operator[](const std::string& key) const;
ConfigNode at(size_t index) const; // cho chuoi (sequence)
bool IsNull() const;
bool IsMap() const;
bool IsSequence() const;
bool IsScalar() const;
size_t size() const;
// Duong dan day du toi node nay, vd "safety.scan.stop_distance".
// Dung trong moi thong bao loi.
const std::string& path() const;
// Ten file goc, de thong bao loi noi ro key nam o dau.
const std::string& origin() const;
// --- Doc gia tri --------------------------------------------------------
// Thieu key -> tra `fallback`. Sai kieu -> nem ConfigError (khac han voi
// thieu key: sai kieu luon la loi cua nguoi viet config).
template <typename T>
T get(const std::string& key, const T& fallback) const;
// Thieu key hoac sai kieu -> nem ConfigError kem duong dan day du.
template <typename T>
T require(const std::string& key) const;
// Doc chinh node nay (khi da di toi la).
template <typename T>
T as() const;
template <typename T>
T as(const T& fallback) const;
// --- Kiem key la ---------------------------------------------------------
// Tra ve cac key CO trong node nay nhung KHONG nam trong `known`.
// Rong nghia la khong co typo.
std::vector<std::string> UnknownKeys(const std::vector<std::string>& known) const;
// Tien loi: goi UnknownKeys() roi log ERROR cho tung key la.
// Tra ve false neu co key la.
bool WarnUnknownKeys(const std::vector<std::string>& known) const;
// Danh sach moi key cua node map nay.
std::vector<std::string> Keys() const;
// Cac cap key/value dang chuoi, giu nguyen van. Dung cho khoi `rtabmap:`
// trong slam.yaml -- 26 key cua RTAB-Map di thang vao ParametersMap ma
// khong qua kiem kieu nao o day.
std::vector<std::pair<std::string, std::string>> AsStringMap() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
explicit ConfigNode(std::unique_ptr<Impl> impl);
};
// Khai bao tuong minh cac kieu duoc ho tro. Dinh nghia o config.cc.
// Them kieu moi thi phai them ca o day va o .cc -- co y, de khong ai vo tinh
// doc mot kieu ma yaml-cpp chuyen doi theo cach bat ngo.
#define VSLAM_CONFIG_DECLARE(T) \
extern template T ConfigNode::get<T>(const std::string&, const T&) const; \
extern template T ConfigNode::require<T>(const std::string&) const; \
extern template T ConfigNode::as<T>() const; \
extern template T ConfigNode::as<T>(const T&) const;
VSLAM_CONFIG_DECLARE(bool)
VSLAM_CONFIG_DECLARE(int)
VSLAM_CONFIG_DECLARE(unsigned int)
VSLAM_CONFIG_DECLARE(float)
VSLAM_CONFIG_DECLARE(double)
VSLAM_CONFIG_DECLARE(std::string)
#undef VSLAM_CONFIG_DECLARE
// Chuoi thi khai bao rieng vi khong dung duoc trong macro (co dau phay).
extern template std::vector<double> ConfigNode::get<std::vector<double>>(
const std::string&, const std::vector<double>&) const;
extern template std::vector<double> ConfigNode::require<std::vector<double>>(
const std::string&) const;
extern template std::vector<std::string> ConfigNode::get<std::vector<std::string>>(
const std::string&, const std::vector<std::string>&) const;
extern template std::vector<std::string> ConfigNode::require<std::vector<std::string>>(
const std::string&) const;
} // namespace vslam
#endif // VSLAM_CONFIG_H

View File

@@ -0,0 +1,108 @@
#ifndef VSLAM_GEOMETRY_H
#define VSLAM_GEOMETRY_H
// Phep bien doi hinh hoc tren cac kieu POD cua vslam_common.h.
//
// Eigen chi xuat hien trong PHAN CAI DAT (.cc), khong o chu ky ham. Ly do o
// vslam_common.h: kieu Eigen fixed-size di qua bien .so la nguon loi alignment
// tren arm64. Ai can Eigen thi tu chuyen o phia minh bang ToEigen()/FromEigen()
// khai bao trong geometry_eigen.h (header noi bo, khong phat hanh).
#include <cmath>
#include "vslam/vslam_common.h"
namespace vslam {
// --- Goc -------------------------------------------------------------------
// Dua goc ve [-pi, pi). Port tu wheel_odom_node.cpp:45-50 va
// slam_core_node.cpp:39-44 (hai ban giong het nhau trong repo cu).
double NormalizeAngle(double a);
// Hieu hai goc, da chuan hoa.
inline double AngleDiff(double a, double b) { return NormalizeAngle(a - b); }
// --- Quaternion <-> Euler --------------------------------------------------
Quaternion QuaternionFromYaw(double yaw);
Quaternion QuaternionFromRPY(double roll, double pitch, double yaw);
double YawFromQuaternion(const Quaternion& q);
void RPYFromQuaternion(const Quaternion& q, double* roll, double* pitch, double* yaw);
Quaternion QuaternionNormalized(const Quaternion& q);
Quaternion QuaternionInverse(const Quaternion& q);
Quaternion QuaternionMultiply(const Quaternion& a, const Quaternion& b);
// Noi suy cau. t kep ve [0,1]. Tu dong lat dau de di duong ngan.
Quaternion QuaternionSlerp(const Quaternion& a, const Quaternion& b, double t);
// --- Vector ----------------------------------------------------------------
inline Vector3 operator+(const Vector3& a, const Vector3& b) {
return Vector3{a.x + b.x, a.y + b.y, a.z + b.z};
}
inline Vector3 operator-(const Vector3& a, const Vector3& b) {
return Vector3{a.x - b.x, a.y - b.y, a.z - b.z};
}
inline Vector3 operator*(const Vector3& v, double s) {
return Vector3{v.x * s, v.y * s, v.z * s};
}
inline double Norm(const Vector3& v) {
return std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
inline Vector3 Lerp(const Vector3& a, const Vector3& b, double t) {
return Vector3{a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t};
}
// Xoay vector bang quaternion.
Vector3 RotateVector(const Quaternion& q, const Vector3& v);
// --- Transform -------------------------------------------------------------
Transform TransformIdentity();
// Ghep: ket qua bien doi tu frame cua `b` sang frame cua `a`.
// Tuong duong phep nhan ma tran a * b.
Transform TransformCompose(const Transform& a, const Transform& b);
Transform TransformInverse(const Transform& t);
// Ap bien doi len mot diem.
Point TransformPoint(const Transform& t, const Point& p);
Vector3 TransformVector(const Transform& t, const Vector3& v);
// Noi suy giua hai transform: LERP tinh tien + SLERP quay.
// Day la phep TransformTree dung khi lookup o mot stamp nam giua hai mau.
Transform TransformInterpolate(const Transform& a, const Transform& b, double t);
// --- SE(2) -----------------------------------------------------------------
// Pose cua he nay la SE(2): x, y, yaw. Roll/pitch duoc DO tu IMU chu khong
// bao gio uoc luong, va z gia dinh bang 0. Xem docs/ARCHITECTURE.md cua repo cu.
Pose2D Pose2DFromPose(const Pose& p);
Pose PoseFromPose2D(const Pose2D& p, double z = 0.0);
Pose2D Pose2DCompose(const Pose2D& a, const Pose2D& b);
Pose2D Pose2DInverse(const Pose2D& p);
// b trong he toa do cua a: a^-1 * b. Dung khi tinh delta giua hai keyframe.
Pose2D Pose2DBetween(const Pose2D& a, const Pose2D& b);
Transform TransformFromPose2D(const Pose2D& p, double z = 0.0);
Pose2D Pose2DFromTransform(const Transform& t);
inline double Distance2D(const Pose2D& a, const Pose2D& b) {
const double dx = a.x - b.x, dy = a.y - b.y;
return std::sqrt(dx * dx + dy * dy);
}
// --- Chuyen doi tien loi --------------------------------------------------
Transform TransformFromPose(const Pose& p);
Pose PoseFromTransform(const Transform& t);
} // namespace vslam
#endif // VSLAM_GEOMETRY_H

View File

@@ -0,0 +1,40 @@
#ifndef VSLAM_JSON_PARSE_H
#define VSLAM_JSON_PARSE_H
// Trich truong tu body JSON cua POST /api/*.
//
// PHAT HANH co y: ai viet mot WebServer::CommandHandler deu PHAI dung chinh
// cac ham nay de doc body. Neu handler doc body theo mot cach khac voi lop
// xac thuc thi khoang cach giua hai cach doc la mot lo hong -- da tung nhu
// vay o ban dau, khi handler tim chuoi "true" con lop xac thuc goi
// JsonGetBool, va mot body hong lam hai ben hieu nguoc nhau.
//
// CO Y KHONG phai mot parser JSON day du. Body ma server nhan chi co dang
// {"on":true} hoac {"x":1.0,"y":2.0,"yaw":0.5} -- vai truong phang, khong
// long nhau, khong mang.
//
// Viet mot parser day du o day nghia la them mot be mat tan cong tren mot
// endpoint khong xac thuc. Ham trich truong theo ten thi khong co trang thai
// de pha hong.
#include <string>
// Nam o vslam_common chu khong o vslam_web: lop XAC THUC cua web va cac
// handler PHAI dung CHUNG mot ham parse (khoang cach giua hai cach doc cung
// mot body tung la lo hong fail-open cho e-stop), va `tools/vslam_replay`
// cung can doc lai JSON ky vong ma khong duoc phep keo theo Boost.
namespace vslam {
// Tim "key": <so> va tra ve gia tri. false neu khong thay hoac khong parse duoc.
bool JsonGetNumber(const std::string& body, const std::string& key, double* out);
// Tim "key": true|false.
bool JsonGetBool(const std::string& body, const std::string& key, bool* out);
// Tim "key": "<chuoi>". Xu ly escape \" va \\.
bool JsonGetString(const std::string& body, const std::string& key, std::string* out);
} // namespace vslam
#endif // VSLAM_JSON_PARSE_H

View File

@@ -0,0 +1,98 @@
#ifndef VSLAM_LOG_H
#define VSLAM_LOG_H
// Thay ROS_DEBUG / ROS_INFO / ROS_WARN / ROS_ERROR va cac bien the _THROTTLE.
//
// Yeu cau tu hien trang:
// * _THROTTLE la bat buoc, khong phai tien nghi. Nhieu cho trong repo hien
// tai log o tan so cam bien (200 Hz IMU, 30 Hz camera); khong bop lai thi
// journald tren Jetson day o va I/O tro thanh nut co chai that.
// * Throttle phai dung steady_clock, khong phai stamp du lieu. Neu dung
// stamp thi khi replay nhanh (speed=0) moi dong se bi bop nham.
// * Ghi log tuyet doi khong duoc chan vong an toan. Sink mac dinh ghi
// thang ra stderr co khoa; neu sau nay can sink ton kem (file, mang) thi
// phai la sink bat dong bo co hang doi va DROP chu khong block.
#include <atomic>
#include <chrono>
#include <cstdint>
#include <functional>
#include <sstream>
#include <string>
namespace vslam {
enum class LogLevel : int { kDebug = 0, kInfo = 1, kWarn = 2, kError = 3, kOff = 4 };
const char* LogLevelName(LogLevel l);
bool ParseLogLevel(const std::string& s, LogLevel* out);
// Sink nhan dong da dinh dang san (khong co newline).
using LogSink = std::function<void(LogLevel, const char* file, int line,
const std::string& msg)>;
void SetLogLevel(LogLevel l);
LogLevel GetLogLevel();
void SetLogSink(LogSink sink);
// Bat/tat mau ANSI. Mac dinh: tu dong theo isatty(stderr).
void SetLogColor(bool on);
namespace detail {
void EmitLog(LogLevel level, const char* file, int line, const std::string& msg);
// Tra ve true neu da du `period_sec` ke tu lan cuoi cho diem goi nay.
// `state` la bien tinh rieng cua tung diem goi.
bool ThrottlePass(std::atomic<int64_t>* state, double period_sec);
} // namespace detail
#define VSLAM_LOG_AT(level, ...) \
do { \
if (static_cast<int>(level) >= static_cast<int>(::vslam::GetLogLevel())) { \
std::ostringstream _vslam_oss; \
_vslam_oss << __VA_ARGS__; \
::vslam::detail::EmitLog((level), __FILE__, __LINE__, _vslam_oss.str()); \
} \
} while (0)
#define VSLAM_DEBUG(...) VSLAM_LOG_AT(::vslam::LogLevel::kDebug, __VA_ARGS__)
#define VSLAM_INFO(...) VSLAM_LOG_AT(::vslam::LogLevel::kInfo, __VA_ARGS__)
#define VSLAM_WARN(...) VSLAM_LOG_AT(::vslam::LogLevel::kWarn, __VA_ARGS__)
#define VSLAM_ERROR(...) VSLAM_LOG_AT(::vslam::LogLevel::kError, __VA_ARGS__)
// Bien the throttle. `period` tinh bang giay, theo steady_clock.
#define VSLAM_LOG_THROTTLE_AT(level, period, ...) \
do { \
static std::atomic<int64_t> _vslam_throttle_state{0}; \
if (::vslam::detail::ThrottlePass(&_vslam_throttle_state, (period))) { \
VSLAM_LOG_AT(level, __VA_ARGS__); \
} \
} while (0)
#define VSLAM_DEBUG_THROTTLE(period, ...) \
VSLAM_LOG_THROTTLE_AT(::vslam::LogLevel::kDebug, period, __VA_ARGS__)
#define VSLAM_INFO_THROTTLE(period, ...) \
VSLAM_LOG_THROTTLE_AT(::vslam::LogLevel::kInfo, period, __VA_ARGS__)
#define VSLAM_WARN_THROTTLE(period, ...) \
VSLAM_LOG_THROTTLE_AT(::vslam::LogLevel::kWarn, period, __VA_ARGS__)
#define VSLAM_ERROR_THROTTLE(period, ...) \
VSLAM_LOG_THROTTLE_AT(::vslam::LogLevel::kError, period, __VA_ARGS__)
// Chi log mot lan duy nhat cho diem goi nay.
#define VSLAM_LOG_ONCE_AT(level, ...) \
do { \
static std::atomic<bool> _vslam_once{false}; \
bool _vslam_expected = false; \
if (_vslam_once.compare_exchange_strong(_vslam_expected, true)) { \
VSLAM_LOG_AT(level, __VA_ARGS__); \
} \
} while (0)
#define VSLAM_INFO_ONCE(...) VSLAM_LOG_ONCE_AT(::vslam::LogLevel::kInfo, __VA_ARGS__)
#define VSLAM_WARN_ONCE(...) VSLAM_LOG_ONCE_AT(::vslam::LogLevel::kWarn, __VA_ARGS__)
} // namespace vslam
#endif // VSLAM_LOG_H

View File

@@ -0,0 +1,98 @@
#ifndef VSLAM_NODE_CONSTANTS_H
#define VSLAM_NODE_CONSTANTS_H
// Duong dan va hang so toan he, tap trung mot cho.
// Khuon mau: xloc_cpp/include/node_constants.h, voi mot sua loi quan trong.
//
// xloc_cpp/include/node_constants.h:30-31 hardcode
// kMapDirectory = "/home/robotics/.local/share/xloc/resources/maps/"
// kPoseDirectory = "/home/robotics/.local/share/xloc/resources/poses/"
// nen goi .deb cua no khong chay duoc tren may co username khac, va lech han
// voi dich install() o CMakeLists.txt:269-273 (/var/lib/xloc/resources).
//
// O day: mac dinh theo FHS, va co the ghi de bang bien moi truong -- can cho
// viec chay tu build tree khi phat trien va cho test chay song song.
#include <string>
namespace vslam {
// --- Duong dan mac dinh ----------------------------------------------------
constexpr char kConfigurationDirectory[] = "/etc/vslam/configuration_files";
constexpr char kResourceDirectory[] = "/var/lib/vslam/resources";
constexpr char kMapDirectory[] = "/var/lib/vslam/resources/maps";
constexpr char kRecordDirectory[] = "/var/lib/vslam/resources/records";
constexpr char kWebAssetDirectory[] = "/var/lib/vslam/www";
// --- Bien moi truong ghi de ------------------------------------------------
constexpr char kConfigDirEnv[] = "VSLAM_CONFIG_DIR";
constexpr char kResourceDirEnv[] = "VSLAM_RESOURCE_DIR";
constexpr char kCorpusDirEnv[] = "VSLAM_CORPUS_DIR"; // ../vSLAM_ws/maps khi test
// --- Ten file cau hinh -----------------------------------------------------
// Mot file cho mot lib, cong robot.yaml. 14 file YAML cua ban ROS gop lai
// thanh sau file nay.
constexpr char kRobotConfigFile[] = "robot.yaml";
constexpr char kSensorsConfigFile[] = "sensors.yaml";
constexpr char kPipelineConfigFile[] = "pipeline.yaml";
constexpr char kSlamConfigFile[] = "slam.yaml";
constexpr char kSafetyConfigFile[] = "safety.yaml";
constexpr char kSystemConfigFile[] = "system.yaml";
// --- Ten frame -------------------------------------------------------------
// Cay TF: map -> odom -> base_footprint -> base_link -> {laser, camera, imu}
// va camera_link -> camera_depth_optical_frame -> camera_infra1/2.
// Chi BA canh la dong (xem transform_tree.h); con lai tinh, nap tu robot.yaml.
constexpr char kMapFrame[] = "map";
constexpr char kOdomFrame[] = "odom";
constexpr char kBaseFootprintFrame[] = "base_footprint";
constexpr char kBaseLinkFrame[] = "base_link";
constexpr char kLaserFrame[] = "laser_link";
constexpr char kImuFrame[] = "imu_link";
constexpr char kCameraFrame[] = "camera_link";
constexpr char kCameraDepthOpticalFrame[] = "camera_depth_optical_frame";
constexpr char kCameraInfra1OpticalFrame[] = "camera_infra1_optical_frame";
constexpr char kCameraInfra2OpticalFrame[] = "camera_infra2_optical_frame";
// --- Tan so danh dinh ------------------------------------------------------
// Gia tri that nam trong config; nhung hang so nay la mac dinh va la moc de
// RateMonitor canh bao khi lech.
constexpr double kLidarRateHz = 25.0;
constexpr double kCameraRateHz = 30.0;
constexpr double kImuRateHz = 200.0;
constexpr double kEkfRateHz = 50.0;
constexpr double kBaseIoRateHz = 50.0;
constexpr double kSafetyRateHz = 20.0;
constexpr double kWebStateRateHz = 10.0;
// --- Hang so vat ly --------------------------------------------------------
constexpr double kGravity = 9.80665; // m/s^2, khop voi gravity_align_nodelet
// --- Ham tra ve duong dan (co ghi de bang env) -----------------------------
// Thu muc cau hinh: $VSLAM_CONFIG_DIR neu co, khong thi kConfigurationDirectory.
std::string ConfigDir();
// Thu muc tai nguyen: $VSLAM_RESOURCE_DIR neu co, khong thi kResourceDirectory.
std::string ResourceDir();
// ConfigDir() + "/" + file_name
std::string ConfigPath(const std::string& file_name);
// ResourceDir() + "/" + rel
std::string ResourcePath(const std::string& rel);
// Thu muc ban do: ResourceDir() + "/maps"
std::string MapDir();
// Thu muc ban ghi .vsr: ResourceDir() + "/records"
std::string RecordDir();
// Corpus .db de test: $VSLAM_CORPUS_DIR neu co, khong thi MapDir().
// Trong luc port, tro sang ../vSLAM_ws/maps de dung lai map_house.db va
// map_hospital.db ma khong phai copy 3.8 GB.
std::string CorpusDir();
} // namespace vslam
#endif // VSLAM_NODE_CONSTANTS_H

View File

@@ -0,0 +1,112 @@
#ifndef VSLAM_ROBOT_MODEL_H
#define VSLAM_ROBOT_MODEL_H
// Hinh hoc robot + cay frame, nap tu `robot.yaml`. THAY CHO URDF.
//
// ================== VI SAO LOP NAY TON TAI ==================
// Truoc khi co no, phep dung `camera_depth_optical_frame -> base_link` bi
// LAP LAI o bon file (hai tool va hai file test), moi cho mot ban chep cua
// cung mot chuoi QuaternionMultiply. Va `cliff_detect.nominal_tz = 0.803` da
// lech voi `sim.camera_z = 0.80` -- hai con so le ra phai la MOT.
//
// Do dung la lop bug "hai cho phai giu dong bo" ma `PROJECT_CONTEXT.md:71`
// cua repo cu da ghi nhan giua URDF va launch param.
//
// Quy tac: KHONG stage nao duoc tu dung lai mot phep bien doi tu cac so trong
// robot.yaml. Moi stage goi `RobotModel::StaticTransform()` hoac lay tu
// `tree()`.
#include <memory>
#include <string>
#include <vector>
#include "vslam/config.h"
#include "vslam/transform_tree.h"
#include "vslam/vslam_common.h"
namespace vslam {
struct RobotGeometry {
double wheel_radius = 0.075;
double wheel_separation = 0.36;
double robot_radius = 0.24;
double body_half_width = 0.17;
};
struct BaseLimits {
double max_linear = 0.35;
double max_angular = 0.80;
double accel_limit = 0.30;
double cmd_timeout = 0.30;
};
struct WheelOdomNoise {
double sigma_x_per_m = 0.02;
double sigma_y_per_m = 0.02;
double sigma_yaw_per_rad = 0.05;
double slip_threshold = 0.20;
bool slip_sigma_is_measured = true;
};
class RobotModel {
public:
RobotModel();
~RobotModel();
RobotModel(const RobotModel&) = delete;
RobotModel& operator=(const RobotModel&) = delete;
// Nap tu node goc cua robot.yaml. Tra loi thay vi nem: nguoi goi quyet dinh
// dung han hay chay voi mac dinh.
//
// Kiem, va TU CHOI neu sai:
// - canh trung lap (hai dong cung `child`) -- cai sau se am tham thang;
// - canh tao chu trinh;
// - `child` mo coi (parent khong ton tai va khong phai base_link);
// - khoa la trong `geometry:` / `base:` / `wheel_odom:` (go sai ten).
StatusResponse Load(const ConfigNode& root);
// Nap tu duong dan file. Tien loi cho tool.
StatusResponse LoadFile(const std::string& path);
const RobotGeometry& geometry() const { return geometry_; }
const BaseLimits& base() const { return base_; }
const WheelOdomNoise& wheel_odom() const { return wheel_odom_; }
// Cay frame, DA nap moi canh tinh. Ba canh dong (map->odom,
// odom->base_footprint, base_footprint->base_link) do cac stage tuong ung
// ghi vao, moi canh dung mot writer.
TransformTree& tree() { return *tree_; }
const TransformTree& tree() const { return *tree_; }
// Phep bien doi TINH giua hai frame. Chi di qua cac canh tinh, nen khong
// can dau thoi gian va khong bao gio "chua co du lieu".
//
// Tra false neu mot trong hai frame khong ton tai hoac duong di di qua mot
// canh dong -- truong hop do phai dung tree().Lookup() voi stamp.
bool StaticTransform(const std::string& target, const std::string& source,
Transform* out) const;
// Chieu cao camera so voi MAT SAN (khong phai so voi tam truc).
//
// Day chinh la `tz` ma cliff_detect mong doi, va la ly do
// `cliff_detect.nominal_tz` KHONG duoc go tay: no la
// camera_link.z + wheel_radius, tinh tu cung mot nguon.
double camera_height_above_floor() const;
// Goc chuc xuong cua camera (rad), lay tu canh base_link -> camera_link.
double camera_pitch() const;
private:
RobotGeometry geometry_;
BaseLimits base_;
WheelOdomNoise wheel_odom_;
std::unique_ptr<TransformTree> tree_;
double camera_z_in_base_link_ = 0.0;
double camera_pitch_ = 0.0;
bool have_camera_ = false;
};
} // namespace vslam
#endif // VSLAM_ROBOT_MODEL_H

View File

@@ -0,0 +1,125 @@
#ifndef VSLAM_STATS_H
#define VSLAM_STATS_H
// Do dac runtime. Khong phai tien nghi -- day la thu ROS khong cho va vi vay
// repo cu phai doan mo:
// * khong biet mot subscriber bo lo bao nhieu ban tin (queue ROS drop im lang)
// * khong biet mot chuoi nodelet tre bao nhieu
// Moi Channel va moi stage deu phai bao cao duoc so lieu nay ra /api/status.
#include <atomic>
#include <chrono>
#include <cstdint>
#include <memory>
#include <string>
#include "vslam/clock.h"
namespace vslam {
// Do tan so bang cua so truot, dung steady_clock.
// An toan cho mot nguoi ghi + nhieu nguoi doc.
class RateMonitor {
public:
explicit RateMonitor(double window_sec = 2.0);
// Goi moi lan co su kien.
void Tick(std::chrono::steady_clock::time_point now);
void Tick(); // dung steady_clock::now(), chi cho main/tool
// Hz uoc luong trong cua so. 0 neu chua du mau.
double hz() const;
// Giay ke tu su kien cuoi. +inf neu chua co su kien nao.
double age_sec(std::chrono::steady_clock::time_point now) const;
uint64_t count() const { return count_.load(std::memory_order_relaxed); }
void Reset();
private:
const double window_sec_;
std::atomic<uint64_t> count_{0};
std::atomic<int64_t> first_ns_{0}; // moc cua so hien tai
std::atomic<int64_t> last_ns_{0};
std::atomic<uint64_t> window_count_{0};
std::atomic<double> hz_{0.0};
};
// Dem su kien bi bo. Chia hai loai vi chung co nguyen nhan khac han nhau.
struct DropCounter {
std::atomic<uint64_t> total{0};
void Add(uint64_t n = 1) { total.fetch_add(n, std::memory_order_relaxed); }
uint64_t get() const { return total.load(std::memory_order_relaxed); }
void Reset() { total.store(0, std::memory_order_relaxed); }
};
// So lieu cua mot Channel.
struct ChannelStats {
std::string name;
uint64_t capacity = 0;
uint64_t published = 0; // tong so ban tin da Publish()
uint64_t overwritten = 0; // so ban tin bi ghi de truoc khi moi reader doc xong
uint64_t readers = 0;
uint64_t max_reader_lag = 0; // reader tut hau nhat, tinh bang so ban tin
uint64_t total_reader_drops = 0;
double hz = 0.0;
};
// So lieu cua ApproxTimeSync.
struct SyncStats {
uint64_t matched = 0;
uint64_t dropped_slop = 0; // co ban tin nhung lech thoi gian qua max_slop
uint64_t dropped_timeout = 0; // het han cho, phat voi input tuy chon de trong
uint64_t dropped_queue = 0; // pivot bi day ra khoi hang doi truoc khi khop
double last_slop_sec = 0.0;
};
// So lieu cua mot driver phan cung.
struct DriverStats {
double hz = 0.0;
uint64_t frames = 0;
uint64_t errors = 0;
uint64_t packets_lost = 0; // LiDAR: suy ra tu do dai sweep
uint64_t short_sweeps = 0; // sweep thieu tia
double stamp_skew_ms = 0.0; // MCU: lech dong ho host <-> thiet bi
double clock_skew_ppm = 0.0; // MCU: he so skew cua ClockSync, tinh theo ppm
bool connected = false;
std::string last_error;
};
// Do thoi luong mot doan code, giu p50/p95/max.
// Dung cho process_ms cua SLAM va cho vong perception.
class LatencyMonitor {
public:
explicit LatencyMonitor(size_t window = 128);
~LatencyMonitor();
void Add(double ms);
double p50() const;
double p95() const;
double max() const;
double last() const;
uint64_t count() const;
void Reset();
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
// RAII: do thoi gian song cua object roi day vao LatencyMonitor.
class ScopedLatency {
public:
ScopedLatency(LatencyMonitor* m, const Clock* clock);
~ScopedLatency();
private:
LatencyMonitor* m_;
std::chrono::steady_clock::time_point t0_;
};
} // namespace vslam
#endif // VSLAM_STATS_H

View File

@@ -0,0 +1,144 @@
#ifndef VSLAM_TELEOP_MODEL_H
#define VSLAM_TELEOP_MODEL_H
// Mo hinh trang thai teleop.
//
// ============ NGUON GOC ============
// Port tu robot_bringup/scripts/teleop_model.py cua vSLAM_ws, ma ban than no
// duoc port tu package `virtual_joystick_teleop` (BSD-3-Clause), tac gia
// duongtd, https://git.pnkr.asia/DuongTD/virtual_joystick_teleop.git
//
// LOGIC GIU NGUYEN VEN. Day la ban dich sang C++, khong phai ban viet lai:
// moi nguong, moi thu tu uu tien, moi phep kep deu giong het ban Python.
// test_teleop_model.cc so ket qua voi vector sinh tu chinh ban Python do.
//
// ============ VI SAO KHONG VIET LAI BANG JS ============
// Ban dau toi viet mot joystick moi hoan toan trong app.js va bo qua file
// nay. Do la sai: mo hinh nay da chay that, da duoc chinh theo cam giac lai
// that, va co nhung thu mot ban viet voi khong co -- nhat la toc do chinh
// duoc khi dang chay.
//
// Trang web chi gui truc joystick da chuan hoa [-1, 1] va su kien phim.
// TOAN BO viec quy ra van toc nam o day, trong C++.
//
// ============ BA NGUON NHAP, CO THU TU UU TIEN ============
// manual (thanh truot kieu rqt) -- cao nhat
// joystick (truc analog)
// phim mui ten -- thap nhat
// Dat mot nguon se GIAI PHONG cac nguon khac. Khong bao gio tron hai nguon.
//
// LUU Y: mo hinh nay KHONG co ramp gia toc. Ramp nam o tang duoi (gioi han
// gia toc cua base). Do la dung: teleop noi "muon di bao nhanh", con base noi
// "den do nhanh duoc bao nhieu".
#include <set>
#include <string>
#include <utility>
namespace vslam {
enum class TeleopKey { kUp, kDown, kLeft, kRight };
// Tra ve false neu ten phim khong duoc ho tro. Ten khop ban Python:
// "Up", "Down", "Left", "Right".
bool ParseTeleopKey(const std::string& name, TeleopKey* out);
const char* TeleopKeyName(TeleopKey k);
struct TeleopConfig {
double linear_speed = 0.30; // scale hien tai, chinh duoc luc chay
double angular_speed = 0.70;
double linear_step = 0.05; // buoc chinh
double angular_step = 0.10;
double min_linear_speed = 0.05; // gioi han cua scale
double max_linear_speed = 2.00;
double min_angular_speed = 0.10;
double max_angular_speed = 2.00;
// Gioi han duoi cua LENH (co dau). Mac dinh = -max_*_speed.
// Tach rieng de gioi han lui khac gioi han tien duoc.
bool has_min_linear_command = false;
double min_linear_command = 0.0;
bool has_min_angular_command = false;
double min_angular_command = 0.0;
};
class TeleopModel {
public:
// Nem std::invalid_argument neu cau hinh vo ly, giong ban Python nem
// ValueError. Kiem o day chu khong im lang roi ve default: mot gioi han
// van toc sai la mot robot chay nhanh hon nguoi lai nghi.
explicit TeleopModel(TeleopConfig cfg = TeleopConfig());
// --- Nguon nhap ----------------------------------------------------------
// Dat trang thai mot phim. Tra false neu phim khong ho tro.
bool SetKey(TeleopKey key, bool pressed);
void ClearKeys();
// Truc analog trong [-1, 1] tu joystick chuot/cham.
void SetJoystick(double horizontal, double vertical);
void ReleaseJoystick();
// Lenh co dau ben vung, kieu thanh truot rqt.
// Truyen nullptr cho truc khong muon doi.
std::pair<double, double> SetManualCommand(const double* linear_x,
const double* angular_z);
void ReleaseManualControl();
// Nha het moi nguon -> lenh ve 0.
void ClearMotion();
// --- Ket qua -------------------------------------------------------------
// (linear_x m/s, angular_z rad/s).
std::pair<double, double> Command() const;
// Truc hien thi [-1, 1] cho knob tren trang. Phim mui ten cung lam knob
// dich -- de nguoi lai thay duoc minh dang bam gi.
std::pair<double, double> JoystickPosition() const;
// --- Chinh toc do luc dang chay -----------------------------------------
double AdjustLinearSpeed(double direction);
double AdjustAngularSpeed(double direction);
double SetLinearSpeed(double value);
double SetAngularSpeed(double value);
double SetMaxLinearSpeed(double value);
double SetMaxAngularSpeed(double value);
double SetMinLinearCommand(double value);
double SetMinAngularCommand(double value);
// --- Truy van ------------------------------------------------------------
double linear_speed() const { return linear_speed_; }
double angular_speed() const { return angular_speed_; }
double max_linear_speed() const { return max_linear_speed_; }
double max_angular_speed() const { return max_angular_speed_; }
double min_linear_command() const { return min_linear_command_; }
double min_angular_command() const { return min_angular_command_; }
bool joystick_active() const { return joystick_active_; }
bool manual_control_active() const { return manual_active_; }
bool key_pressed(TeleopKey k) const { return keys_.count(k) != 0; }
private:
std::pair<double, double> ClampCommand(double linear_x, double angular_z) const;
void ClampManualCommand();
double linear_step_, angular_step_;
double min_linear_speed_, max_linear_speed_;
double min_angular_speed_, max_angular_speed_;
double min_linear_command_, min_angular_command_;
double linear_speed_, angular_speed_;
std::set<TeleopKey> keys_;
bool joystick_active_ = false;
double joy_h_ = 0.0, joy_v_ = 0.0;
bool manual_active_ = false;
double manual_lin_ = 0.0, manual_ang_ = 0.0;
};
} // namespace vslam
#endif // VSLAM_TELEOP_MODEL_H

View File

@@ -0,0 +1,169 @@
#ifndef VSLAM_TRANSFORM_TREE_H
#define VSLAM_TRANSFORM_TREE_H
// Thay tf2_ros::Buffer.
//
// Khong dung tf3 (github.com/Huandaotien/tf3, cai ma xloc_cpp dung) vi:
// submodule third_party/tf3 chua bao gio duoc checkout nen khong kiem chung
// duoc, license cua fork ca nhan chua ro, va no la thu vien TONG QUAT cho cay
// tuy y voi re-parent va da publisher. Bai toan o day hep hon nhieu.
//
// BE MAT API van giu tuong thich tf3 (lookupTransform / setTransform) de sau
// nay muon doi sang tf3 chi la thay header.
//
// CAY TF CUA HE NAY -- 9 frame, va chi BA canh la dong:
//
// map
// | <- slam, ~1 Hz, tu getMapCorrection()
// odom
// | <- ekf, 50 Hz
// base_footprint
// | <- gravity_align, 50 Hz (roll/pitch DO duoc)
// base_link
// |-- laser_link tinh
// |-- imu_link tinh
// `-- camera_link tinh
// `-- camera_depth_optical_frame tinh
// |-- camera_infra1_optical_frame tinh
// `-- camera_infra2_optical_frame tinh
//
// Moi canh tinh nap tu robot.yaml. Day chinh la thu THAY URDF, va no xoa luon
// bug "hai cho phai giu dong bo" ma PROJECT_CONTEXT.md ghi: hien gia tri hinh
// hoc nam ca trong robot.urdf.xacro lan robot.yaml.
//
// QUY TAC BAT BUOC: MOI CANH CO DUNG MOT NGUOI GHI.
// Vi pham quy tac nay la lop bug TF kho debug nhat. localization.launch cua
// repo cu da phai canh bao dieu nay bang mot khoi comment o dau file.
//
// Vi cha cua moi frame co dinh luc khoi tao, duong di child->root duoc tinh
// truoc thanh mot mang: vong lookup khong tra map, khong cap phat.
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "vslam/unix_time.h"
#include "vslam/vslam_common.h"
namespace vslam {
using FrameId = uint16_t;
constexpr FrameId kInvalidFrame = 0xFFFF;
class TransformTree {
public:
// history_sec: giu bao lau lich su canh dong.
// slots_per_edge: so mau moi canh dong (ring buffer).
// 50 Hz * 10 s = 500, nen 512 la du cho canh nhanh nhat.
explicit TransformTree(double history_sec = 10.0, size_t slots_per_edge = 512);
~TransformTree();
TransformTree(const TransformTree&) = delete;
TransformTree& operator=(const TransformTree&) = delete;
// --- Dang ky frame ------------------------------------------------------
// Tra ve id on dinh cho ten frame. Goi nhieu lan cung ten tra cung id.
// Chuoi chi bam MOT LAN o day; moi thao tac sau deu dung FrameId.
FrameId Resolve(const std::string& name);
// kInvalidFrame neu chua dang ky.
FrameId Find(const std::string& name) const;
const std::string& Name(FrameId id) const;
size_t frame_count() const;
// --- Canh tinh ----------------------------------------------------------
// Dat canh tinh parent -> child. Goi lai voi cung cap se GHI DE (cho phep,
// vi nap lai config la thao tac hop le).
// Nem ConfigError neu tao vong.
StatusResponse SetStatic(FrameId parent, FrameId child, const Transform& tf);
StatusResponse SetStatic(const std::string& parent, const std::string& child,
const Transform& tf);
// --- Canh dong ----------------------------------------------------------
// Dat mau moi cho canh dong parent -> child.
//
// Tra false neu:
// * stamp lui ve qua khu so voi mau moi nhat (du hieu ban ghi bi xao tron
// thu tu, hoac hai nguoi cung ghi mot canh -- vi pham quy tac tren)
// * canh nay da duoc khai la tinh
//
// Lan goi dau tien tren mot cap (parent, child) se dang ky canh do la dong.
bool SetTransform(FrameId parent, FrameId child, UnixTime stamp,
const Transform& tf);
// --- Tra cuu ------------------------------------------------------------
// Bien doi dua diem tu `source` sang `target` tai thoi diem `stamp`.
//
// Noi suy: LERP tinh tien + SLERP quay giua hai mau kep `stamp`.
// Ngoai suy: TU CHOI neu stamp > mau moi nhat + extrapolation_limit.
// Day la khac biet co y voi tf2: tf2 nem TransformExtrapolationException va
// rat nhieu code goi bat roi bo qua im lang. O day tra false va dien `err`.
bool Lookup(FrameId target, FrameId source, UnixTime stamp, Transform* out,
std::string* err = nullptr) const;
bool Lookup(const std::string& target, const std::string& source, UnixTime stamp,
Transform* out, std::string* err = nullptr) const;
// Dung mau moi nhat cua tung canh, khong noi suy. Tuong duong
// lookupTransform(..., ros::Time(0), ...) cua tf2.
bool LookupLatest(FrameId target, FrameId source, Transform* out,
std::string* err = nullptr) const;
// Thoi diem moi nhat ma CA HAI nhanh deu co du lieu. kTimeZero neu khong co.
UnixTime LatestCommonTime(FrameId a, FrameId b) const;
// Co du lieu de tra cuu tai `stamp` khong, khong thuc su tinh.
bool CanTransform(FrameId target, FrameId source, UnixTime stamp) const;
// --- Cau hinh -----------------------------------------------------------
void SetExtrapolationLimit(double sec);
double extrapolation_limit() const;
// Danh sach canh dong kem tan so va tuoi mau moi nhat -- ra /api/status.
struct EdgeStatus {
std::string parent;
std::string child;
bool is_static = false;
uint64_t samples = 0;
UnixTime latest;
double hz = 0.0;
};
std::vector<EdgeStatus> EdgeStatuses() const;
// In cay ra chuoi nhieu dong, dung de chan doan. Thay rqt_tf_tree.
std::string DumpTree() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
using TransformTreePtr = std::shared_ptr<TransformTree>;
// Tuong duong xloc_cpp/include/tf_bridge.h: thu hep be mat xuong dung mot
// thao tac ma cac stage can -- dua mot frame ve frame theo doi.
class TfBridge {
public:
TfBridge(std::string tracking_frame, double lookup_timeout_sec,
std::shared_ptr<const TransformTree> tree);
bool LookupToTracking(UnixTime time, FrameId frame, Transform* out) const;
bool LookupToTracking(UnixTime time, const std::string& frame, Transform* out) const;
const std::string& tracking_frame() const { return tracking_frame_; }
private:
std::string tracking_frame_;
double lookup_timeout_sec_;
std::shared_ptr<const TransformTree> tree_;
};
} // namespace vslam
#endif // VSLAM_TRANSFORM_TREE_H

View File

@@ -0,0 +1,197 @@
#ifndef VSLAM_UNIX_TIME_H
#define VSLAM_UNIX_TIME_H
// Thay ros::Time / ros::Duration.
//
// Dua tren xloc_cpp/include/unix_time.h, giu nguyen layout {uint32 sec, nsec}
// de tuong thich API voi xloc. Ba sua loi so voi ban goc:
//
// 1. fromSec() voi input am: ban goc lam static_cast<uint32_t>(std::floor(s))
// -> tran im lang. Ban nay kep ve 0 va co fromSecChecked() de goi biet.
// 2. So hoc noi bo lam bang int64_t nanoseconds. Ban goc ep hieu hai UnixTime
// sang int32_t; nam 2038 se tran, va ngay bay gio thi sec ~1.7e9 da sat
// gioi han 2.1e9 cua int32_t.
// 3. TIME_MAX: ban goc dat trong anonymous namespace TRONG HEADER, nen moi
// translation unit co mot ban sao rieng (va sinh canh bao unused). Ban nay
// dung `inline constexpr` cua C++17.
//
// QUY TAC HAI DONG HO -- doc ky truoc khi dung:
// * UnixTime dung de DONG DAU du lieu (stamp). Nguon la system_clock, co the
// nhay khi NTP dieu chinh.
// * Timeout, chu ky, do thoi luong PHAI dung std::chrono::steady_clock.
// Lan lon hai thu nay la lop bug dang co trong safety_monitor_node.cpp: no
// dung ros::Time::now() cho ca hai, nen 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.
// Xem clock.h: moi stage nhan Clock& thay vi goi UnixTime::now() truc tiep.
#include <cstdint>
#include <cstdlib>
#include <cmath>
#include <chrono>
#include <limits>
#include <string>
#include <thread>
namespace vslam {
class Duration;
constexpr int64_t kNsPerSec = 1000000000LL;
class UnixTime {
public:
uint32_t sec;
uint32_t nsec;
constexpr UnixTime() : sec(0), nsec(0) {}
constexpr UnixTime(uint32_t s, uint32_t ns) : sec(s), nsec(ns) {}
static UnixTime now() {
using namespace std::chrono;
const auto ns =
duration_cast<nanoseconds>(system_clock::now().time_since_epoch()).count();
return fromNSec(ns);
}
static constexpr UnixTime fromNSec(int64_t ns) {
return ns <= 0 ? UnixTime()
: UnixTime(static_cast<uint32_t>(ns / kNsPerSec),
static_cast<uint32_t>(ns % kNsPerSec));
}
// Input am bi kep ve 0. Ban goc tran im lang o day.
static UnixTime fromSec(double s) {
if (!(s > 0.0)) return UnixTime(); // bat ca NaN
return fromNSec(static_cast<int64_t>(std::llround(s * 1e9)));
}
// Nhu fromSec() nhung bao cho goi biet input co hop le khong.
static bool fromSecChecked(double s, UnixTime* out) {
if (!(s >= 0.0) || s > static_cast<double>(std::numeric_limits<uint32_t>::max())) {
return false;
}
*out = fromNSec(static_cast<int64_t>(std::llround(s * 1e9)));
return true;
}
constexpr int64_t toNSec() const {
return static_cast<int64_t>(sec) * kNsPerSec + static_cast<int64_t>(nsec);
}
constexpr double toSec() const {
return static_cast<double>(sec) + static_cast<double>(nsec) * 1e-9;
}
constexpr bool isZero() const { return sec == 0 && nsec == 0; }
constexpr bool operator==(const UnixTime& o) const {
return sec == o.sec && nsec == o.nsec;
}
constexpr bool operator!=(const UnixTime& o) const { return !(*this == o); }
constexpr bool operator<(const UnixTime& o) const {
return sec < o.sec || (sec == o.sec && nsec < o.nsec);
}
constexpr bool operator>(const UnixTime& o) const { return o < *this; }
constexpr bool operator<=(const UnixTime& o) const { return !(*this > o); }
constexpr bool operator>=(const UnixTime& o) const { return !(*this < o); }
friend Duration operator-(const UnixTime& a, const UnixTime& b);
friend UnixTime operator+(const UnixTime& t, const Duration& d);
friend UnixTime operator-(const UnixTime& t, const Duration& d);
// Giu lai dang ham de tuong thich voi ma goi theo kieu xloc.
static constexpr UnixTime TIME_MAX() {
return UnixTime(std::numeric_limits<uint32_t>::max(),
static_cast<uint32_t>(kNsPerSec - 1));
}
// "1737000000.123456789" -- dung cho log va JSON, khong mat do chinh xac
// nhu khi in double.
std::string toString() const;
};
inline constexpr UnixTime kTimeMax = UnixTime::TIME_MAX();
inline constexpr UnixTime kTimeZero = UnixTime();
class Duration {
public:
int32_t sec;
int32_t nsec;
constexpr Duration() : sec(0), nsec(0) {}
Duration(int32_t s, int32_t ns) : sec(s), nsec(ns) { normalize(); }
explicit Duration(double seconds) { *this = fromNSec(static_cast<int64_t>(std::llround(seconds * 1e9))); }
static Duration fromSec(double s) { return Duration(s); }
static Duration fromNSec(int64_t ns_total) {
Duration d;
d.sec = static_cast<int32_t>(ns_total / kNsPerSec);
d.nsec = static_cast<int32_t>(ns_total % kNsPerSec);
d.normalize();
return d;
}
constexpr int64_t toNSec() const {
return static_cast<int64_t>(sec) * kNsPerSec + static_cast<int64_t>(nsec);
}
constexpr double toSec() const {
return static_cast<double>(sec) + static_cast<double>(nsec) * 1e-9;
}
constexpr bool isZero() const { return sec == 0 && nsec == 0; }
void normalize() {
if (nsec >= kNsPerSec) {
sec += static_cast<int32_t>(nsec / kNsPerSec);
nsec = static_cast<int32_t>(nsec % kNsPerSec);
} else if (nsec < 0) {
const int32_t borrow = (std::abs(nsec) / static_cast<int32_t>(kNsPerSec)) + 1;
sec -= borrow;
nsec += borrow * static_cast<int32_t>(kNsPerSec);
}
}
Duration operator+(const Duration& o) const { return fromNSec(toNSec() + o.toNSec()); }
Duration operator-(const Duration& o) const { return fromNSec(toNSec() - o.toNSec()); }
Duration operator-() const { return fromNSec(-toNSec()); }
Duration& operator+=(const Duration& o) { *this = *this + o; return *this; }
Duration& operator-=(const Duration& o) { *this = *this - o; return *this; }
constexpr bool operator==(const Duration& o) const { return sec == o.sec && nsec == o.nsec; }
constexpr bool operator!=(const Duration& o) const { return !(*this == o); }
bool operator<(const Duration& o) const { return toNSec() < o.toNSec(); }
bool operator>(const Duration& o) const { return o < *this; }
bool operator<=(const Duration& o) const { return !(*this > o); }
bool operator>=(const Duration& o) const { return !(*this < o); }
// Chi dung o main/tool. Trong stage phai dung Clock::SleepUntil() de replay
// tat dinh chay duoc.
void sleep() const {
const int64_t ns = toNSec();
if (ns <= 0) return;
std::this_thread::sleep_for(std::chrono::nanoseconds(ns));
}
};
inline Duration operator-(const UnixTime& a, const UnixTime& b) {
return Duration::fromNSec(a.toNSec() - b.toNSec());
}
inline UnixTime operator+(const UnixTime& t, const Duration& d) {
return UnixTime::fromNSec(t.toNSec() + d.toNSec());
}
inline UnixTime operator-(const UnixTime& t, const Duration& d) {
return UnixTime::fromNSec(t.toNSec() - d.toNSec());
}
// Giay troi qua giua hai stamp. Dung cho moi phep so sanh timeout theo stamp
// du lieu (khong phai timeout tuong doi -- cai do dung steady_clock).
inline double SecondsBetween(const UnixTime& later, const UnixTime& earlier) {
return static_cast<double>(later.toNSec() - earlier.toNSec()) * 1e-9;
}
} // namespace vslam
#endif // VSLAM_UNIX_TIME_H

View File

@@ -0,0 +1,272 @@
#ifndef VSLAM_VSLAM_COMMON_H
#define VSLAM_VSLAM_COMMON_H
// Dinh nghia lai cac kieu ban tin thuong dung, thay cho sensor_msgs /
// geometry_msgs / nav_msgs. Khuon mau: xloc_cpp/include/xloc_common.h.
//
// HAI QUY TAC BAT BUOC cho moi struct trong file nay:
//
// 1. KHONG chua kieu Eigen fixed-size (Eigen::Vector3d, Matrix4d, ...).
// Dung double x, y, z. Eigen fixed-size co yeu cau can chinh 16/32 byte;
// dat chung trong struct di qua bien .so la nguon loi alignment kinh dien
// tren arm64 khi hai phia compile voi EIGEN_MAX_ALIGN_BYTES khac nhau.
// Chuyen sang Eigen o trong ham, khong o trong kieu du lieu.
//
// 2. KHONG include header cua ROS, PCL, OpenCV hay RTAB-Map. File nay phai
// compile duoc voi mot Eigen-less, PCL-less toolchain. Cac lib phia tren
// tu chuyen doi sang kieu cua ho o bien cua minh.
//
// Vung du lieu lon (anh, point cloud, scan) luon di qua he thong duoi dang
// std::shared_ptr<const T>. Khong bao gio copy. Xem channel.h.
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "vslam/unix_time.h"
namespace vslam {
// ---------------------------------------------------------------------------
// Trang thai tra ve
// ---------------------------------------------------------------------------
enum class StatusCode : int32_t {
kOk = 0,
kInvalidArgument = 1,
kNotFound = 2,
kFailedPrecondition = 3,
kUnavailable = 4,
kTimeout = 5,
kInternal = 6,
kUnauthenticated = 7,
};
struct StatusResponse {
StatusCode code = StatusCode::kOk;
std::string message;
bool ok() const { return code == StatusCode::kOk; }
explicit operator bool() const { return ok(); }
static StatusResponse Ok() { return {}; }
static StatusResponse Error(StatusCode c, std::string m) {
return StatusResponse{c, std::move(m)};
}
};
// ---------------------------------------------------------------------------
// std_msgs
// ---------------------------------------------------------------------------
struct Header {
uint32_t seq = 0;
UnixTime stamp;
std::string frame_id;
};
// ---------------------------------------------------------------------------
// geometry_msgs
// ---------------------------------------------------------------------------
struct Point {
double x = 0.0, y = 0.0, z = 0.0;
};
struct Vector3 {
double x = 0.0, y = 0.0, z = 0.0;
};
struct Quaternion {
double x = 0.0, y = 0.0, z = 0.0, w = 1.0;
};
struct Pose {
Point position;
Quaternion orientation;
};
struct Pose2D {
double x = 0.0, y = 0.0, theta = 0.0;
};
struct PoseStamped {
Header header;
Pose pose;
};
struct PoseWithCovariance {
Pose pose;
double covariance[36] = {}; // row-major 6x6: x y z roll pitch yaw
};
struct PoseWithCovarianceStamped {
Header header;
PoseWithCovariance pose;
};
struct Twist {
Vector3 linear;
Vector3 angular;
};
struct TwistWithCovariance {
Twist twist;
double covariance[36] = {};
};
// Phep bien doi cung. Dung trong TransformTree.
struct Transform {
Vector3 translation;
Quaternion rotation;
};
struct TransformStamped {
Header header; // header.frame_id = frame CHA
std::string child_frame_id;
Transform transform;
};
// ---------------------------------------------------------------------------
// nav_msgs
// ---------------------------------------------------------------------------
struct Odometry {
Header header; // header.frame_id = frame tham chieu (vd "odom")
std::string child_frame_id; // vd "base_footprint"
PoseWithCovariance pose;
TwistWithCovariance twist;
};
// value: -1 = chua biet, 0..100 = xac suat bi chiem.
// Bo cuc giong nav_msgs/OccupancyGrid: hang chinh, goc o (origin), o (0,0)
// nam o phan tu data[0].
struct OccupancyGrid {
Header header;
float resolution = 0.05f; // met / o
uint32_t width = 0;
uint32_t height = 0;
Pose origin; // goc duoi-trai cua o (0,0), trong frame header
std::vector<int8_t> data; // size = width * height
};
// ---------------------------------------------------------------------------
// sensor_msgs
// ---------------------------------------------------------------------------
struct Imu {
Header header;
Quaternion orientation;
double orientation_covariance[9] = {}; // [0] < 0 nghia la khong co orientation
Vector3 angular_velocity; // rad/s
double angular_velocity_covariance[9] = {};
Vector3 linear_acceleration; // m/s^2
double linear_acceleration_covariance[9] = {};
};
struct FluidPressure {
Header header;
double fluid_pressure = 0.0; // Pa
double variance = 0.0;
};
struct Temperature {
Header header;
double temperature = 0.0; // do C
double variance = 0.0;
};
// BA NGU NGHIA CUA MOT TIA -- doc truoc khi cham vao bat cu code nao doc scan.
// Duoc dinh nghia o scan_sanitizer va safety_monitor dua vao dung ba thu nay:
//
// NaN : khong do duoc (duoi range_min, hoac driver tra 0).
// +inf : do duoc nhung khong co phan xa (vuot range_max).
// range_max + 1.0 : SENTINEL -- tia bi che boi than robot, da bi cat co
// y boi sector mask. KHAC HAN voi hai truong hop tren:
// day khong phai "khong thay gi", ma la "khong duoc
// phep nhin". safety_monitor dem rieng so tia nay
// (front_blanked) va khong tinh vao front_usable.
//
// Nham ba thu nay lai lam robot hoac dung im (SCAN_SPARSE) hoac dam vao tuong.
struct LaserScan {
Header header;
float angle_min = 0.0f; // rad
float angle_max = 0.0f;
float angle_increment = 0.0f;
float time_increment = 0.0f; // giay giua hai tia
float scan_time = 0.0f; // giay giua hai sweep
float range_min = 0.0f; // met
float range_max = 0.0f;
std::vector<float> ranges;
std::vector<float> intensities; // co the rong
};
struct CameraInfo {
Header header;
uint32_t width = 0;
uint32_t height = 0;
double k[9] = {}; // ma tran noi 3x3, hang chinh
double d[5] = {}; // meo anh (plumb bob)
uint32_t binning_x = 1;
uint32_t binning_y = 1;
double fx() const { return k[0]; }
double fy() const { return k[4]; }
double cx() const { return k[2]; }
double cy() const { return k[5]; }
// Noi suy sau khi decimate: crop_decimate cua image_proc cap nhat binning
// chu KHONG chia lai K. Consumer phai tu bu, dung nhu image_geometry lam.
double fx_binned() const { return k[0] / static_cast<double>(binning_x); }
double fy_binned() const { return k[4] / static_cast<double>(binning_y); }
double cx_binned() const { return k[2] / static_cast<double>(binning_x); }
double cy_binned() const { return k[5] / static_cast<double>(binning_y); }
};
enum class PixelFormat : uint8_t {
kMono8 = 0, // 8UC1 -- infra1 / infra2
kMono16 = 1, // 16UC1 -- depth thang do theo depth_scale
kFloat32 = 2, // 32FC1 -- depth met
};
// Anh KHONG so huu bo nho khi den tu librealsense: `data` tro vao buffer cua
// SDK va `keep_alive` giu rs2::frame song. Xem realsense_driver.
struct Image {
Header header;
uint32_t width = 0;
uint32_t height = 0;
uint32_t step = 0; // byte moi hang
PixelFormat format = PixelFormat::kMono8;
float depth_scale = 0.001f; // met moi don vi, chi co nghia voi kMono16
const uint8_t* data = nullptr;
std::shared_ptr<void> keep_alive; // giu nguon buffer song
size_t size_bytes() const { return static_cast<size_t>(step) * height; }
};
struct PointXYZ {
float x = 0.0f, y = 0.0f, z = 0.0f;
};
// Cloud phang (khong to chuc theo anh). Cac buoc loc tra ve kieu nay.
struct PointCloudXYZ {
Header header;
std::vector<PointXYZ> points;
bool is_dense = false; // false nghia la co the co NaN
};
// ---------------------------------------------------------------------------
// Bi danh cho con tro chia se -- moi thu di qua Channel deu la kieu nay.
// ---------------------------------------------------------------------------
using LaserScanPtr = std::shared_ptr<const LaserScan>;
using ImuPtr = std::shared_ptr<const Imu>;
using ImagePtr = std::shared_ptr<const Image>;
using PointCloudXYZPtr = std::shared_ptr<const PointCloudXYZ>;
using OccupancyGridPtr = std::shared_ptr<const OccupancyGrid>;
using OdometryPtr = std::shared_ptr<const Odometry>;
} // namespace vslam
#endif // VSLAM_VSLAM_COMMON_H

View File

@@ -0,0 +1,101 @@
#include "vslam/clock.h"
#include <mutex>
#include <thread>
#include "vslam/log.h"
namespace vslam {
namespace {
class SystemClock : public Clock {
public:
UnixTime Now() const override { return UnixTime::now(); }
SteadyPoint Steady() const override { return std::chrono::steady_clock::now(); }
void SleepUntil(SteadyPoint tp) override {
std::this_thread::sleep_until(tp);
}
bool is_virtual() const override { return false; }
};
} // namespace
ClockPtr MakeSystemClock() { return std::make_shared<SystemClock>(); }
// ---------------------------------------------------------------------------
struct ReplayClock::Impl {
mutable std::mutex mu;
UnixTime now;
SteadyPoint steady_origin;
std::chrono::nanoseconds steady_offset{0};
double speed = 0.0; // 0 = chay nhanh nhat, khong ngu that
};
ReplayClock::ReplayClock(UnixTime start) : impl_(std::make_unique<Impl>()) {
impl_->now = start;
impl_->steady_origin = std::chrono::steady_clock::now();
}
ReplayClock::~ReplayClock() = default;
UnixTime ReplayClock::Now() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->now;
}
Clock::SteadyPoint ReplayClock::Steady() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->steady_origin + impl_->steady_offset;
}
void ReplayClock::SleepUntil(SteadyPoint tp) {
double speed;
SteadyPoint current;
{
std::lock_guard<std::mutex> lk(impl_->mu);
speed = impl_->speed;
current = impl_->steady_origin + impl_->steady_offset;
if (tp > current) {
// Thoi gian ao luon tien toi moc yeu cau, ke ca khi khong ngu that.
impl_->steady_offset += (tp - current);
}
}
if (speed > 0.0 && tp > current) {
const auto wall = std::chrono::duration_cast<std::chrono::nanoseconds>(
(tp - current) / speed);
std::this_thread::sleep_for(wall);
}
}
void ReplayClock::SetNow(UnixTime t, bool allow_backward) {
std::lock_guard<std::mutex> lk(impl_->mu);
if (!allow_backward && t < impl_->now) {
// Lui thoi gian la dau hieu ban ghi bi xao tron thu tu. Bao chu khong
// im lang chap nhan -- neu im lang thi moi phep timeout sau do deu sai.
VSLAM_WARN("ReplayClock: tu choi lui thoi gian " << impl_->now.toString()
<< " -> " << t.toString());
return;
}
impl_->now = t;
}
void ReplayClock::Advance(Duration d) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->now = impl_->now + d;
impl_->steady_offset += std::chrono::nanoseconds(d.toNSec());
}
void ReplayClock::SetSpeed(double speed) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->speed = speed < 0.0 ? 0.0 : speed;
}
std::shared_ptr<ReplayClock> MakeReplayClock(UnixTime start) {
return std::make_shared<ReplayClock>(start);
}
} // namespace vslam

View File

@@ -0,0 +1,234 @@
#include "vslam/config.h"
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <sstream>
#include "vslam/log.h"
namespace vslam {
struct ConfigNode::Impl {
YAML::Node node;
std::string path; // "safety.scan.stop_distance"
std::string origin; // ten file
Impl() = default;
Impl(YAML::Node n, std::string p, std::string o)
: node(std::move(n)), path(std::move(p)), origin(std::move(o)) {}
};
namespace {
std::string JoinPath(const std::string& base, const std::string& key) {
return base.empty() ? key : base + "." + key;
}
// Thong bao loi luon co ba manh: file, duong dan key day du, va ly do.
// Thieu bat cu manh nao la nguoi doc phai di tim, va do chinh la thu lam
// viec sua config trong ban ROS ton thoi gian.
//
// Nhan chuoi chu khong nhan ConfigNode::Impl: Impl la kieu private, ham tu do
// trong namespace vo danh khong goi ten no duoc.
std::string Where(const std::string& origin, const std::string& path,
const std::string& key) {
std::ostringstream oss;
oss << origin << ": " << JoinPath(path, key);
return oss.str();
}
} // namespace
ConfigNode::ConfigNode() : impl_(std::make_unique<Impl>()) {}
ConfigNode::ConfigNode(std::unique_ptr<Impl> impl) : impl_(std::move(impl)) {}
ConfigNode::ConfigNode(const ConfigNode& o) : impl_(std::make_unique<Impl>(*o.impl_)) {}
ConfigNode::ConfigNode(ConfigNode&&) noexcept = default;
ConfigNode& ConfigNode::operator=(const ConfigNode& o) {
if (this != &o) impl_ = std::make_unique<Impl>(*o.impl_);
return *this;
}
ConfigNode& ConfigNode::operator=(ConfigNode&&) noexcept = default;
ConfigNode::~ConfigNode() = default;
ConfigNode ConfigNode::LoadFile(const std::string& path) {
try {
YAML::Node root = YAML::LoadFile(path);
return ConfigNode(std::make_unique<Impl>(std::move(root), "", path));
} catch (const YAML::BadFile&) {
throw ConfigError("khong mo duoc file cau hinh: " + path);
} catch (const YAML::Exception& e) {
throw ConfigError("YAML sai cu phap trong " + path + ": " + e.what());
}
}
ConfigNode ConfigNode::LoadString(const std::string& yaml, std::string origin) {
try {
YAML::Node root = YAML::Load(yaml);
return ConfigNode(std::make_unique<Impl>(std::move(root), "", std::move(origin)));
} catch (const YAML::Exception& e) {
throw ConfigError("YAML sai cu phap trong " + origin + ": " + e.what());
}
}
ConfigNode ConfigNode::operator[](const std::string& key) const {
// Key thieu tra node Null thay vi nem, de chuoi a["b"]["c"] khong no giua
// chung. Nguoi goi kiem IsNull() hoac dung require() o buoc cuoi.
if (!impl_->node || !impl_->node.IsMap()) {
return ConfigNode(std::make_unique<Impl>(YAML::Node(YAML::NodeType::Undefined),
JoinPath(impl_->path, key), impl_->origin));
}
return ConfigNode(std::make_unique<Impl>(impl_->node[key],
JoinPath(impl_->path, key), impl_->origin));
}
ConfigNode ConfigNode::at(size_t index) const {
std::ostringstream oss;
oss << impl_->path << "[" << index << "]";
if (!impl_->node || !impl_->node.IsSequence() || index >= impl_->node.size()) {
return ConfigNode(std::make_unique<Impl>(YAML::Node(YAML::NodeType::Undefined),
oss.str(), impl_->origin));
}
return ConfigNode(std::make_unique<Impl>(impl_->node[index], oss.str(), impl_->origin));
}
bool ConfigNode::IsNull() const {
return !impl_->node || impl_->node.IsNull() ||
impl_->node.Type() == YAML::NodeType::Undefined;
}
bool ConfigNode::IsMap() const { return impl_->node && impl_->node.IsMap(); }
bool ConfigNode::IsSequence() const { return impl_->node && impl_->node.IsSequence(); }
bool ConfigNode::IsScalar() const { return impl_->node && impl_->node.IsScalar(); }
size_t ConfigNode::size() const { return impl_->node ? impl_->node.size() : 0; }
const std::string& ConfigNode::path() const { return impl_->path; }
const std::string& ConfigNode::origin() const { return impl_->origin; }
// --- Doc gia tri -----------------------------------------------------------
template <typename T>
T ConfigNode::get(const std::string& key, const T& fallback) const {
const ConfigNode child = (*this)[key];
if (child.IsNull()) return fallback;
try {
return child.impl_->node.template as<T>();
} catch (const YAML::Exception&) {
// Sai KIEU luon la loi, khac han voi THIEU key. Thieu key co the co y
// (dung default); sai kieu thi khong bao gio co y.
throw ConfigError(Where(impl_->origin, impl_->path, key) + ": sai kieu du lieu");
}
}
template <typename T>
T ConfigNode::require(const std::string& key) const {
const ConfigNode child = (*this)[key];
if (child.IsNull()) {
throw ConfigError(Where(impl_->origin, impl_->path, key) + ": thieu key bat buoc");
}
try {
return child.impl_->node.template as<T>();
} catch (const YAML::Exception&) {
throw ConfigError(Where(impl_->origin, impl_->path, key) + ": sai kieu du lieu");
}
}
template <typename T>
T ConfigNode::as() const {
if (IsNull()) {
throw ConfigError(impl_->origin + ": " + impl_->path + ": thieu gia tri");
}
try {
return impl_->node.template as<T>();
} catch (const YAML::Exception&) {
throw ConfigError(impl_->origin + ": " + impl_->path + ": sai kieu du lieu");
}
}
template <typename T>
T ConfigNode::as(const T& fallback) const {
if (IsNull()) return fallback;
try {
return impl_->node.template as<T>();
} catch (const YAML::Exception&) {
throw ConfigError(impl_->origin + ": " + impl_->path + ": sai kieu du lieu");
}
}
// --- Kiem key la -----------------------------------------------------------
std::vector<std::string> ConfigNode::Keys() const {
std::vector<std::string> out;
if (!IsMap()) return out;
for (const auto& kv : impl_->node) {
out.push_back(kv.first.as<std::string>());
}
return out;
}
std::vector<std::string> ConfigNode::UnknownKeys(
const std::vector<std::string>& known) const {
std::vector<std::string> out;
for (const auto& k : Keys()) {
if (std::find(known.begin(), known.end(), k) == known.end()) {
out.push_back(JoinPath(impl_->path, k));
}
}
return out;
}
bool ConfigNode::WarnUnknownKeys(const std::vector<std::string>& known) const {
const auto unknown = UnknownKeys(known);
for (const auto& k : unknown) {
// ERROR chu khong phai WARN: mot key la gan nhu luon la go sai ten cua
// mot key that, nghia la gia tri nguoi dung DINH dat dang khong co tac
// dung. "stop_distence" thay vi "stop_distance" van cho robot chay, chi
// la chay voi khoang cach dung mac dinh.
VSLAM_ERROR(impl_->origin << ": key khong nhan ra: " << k);
}
return unknown.empty();
}
std::vector<std::pair<std::string, std::string>> ConfigNode::AsStringMap() const {
std::vector<std::pair<std::string, std::string>> out;
if (!IsMap()) return out;
for (const auto& kv : impl_->node) {
// Giu nguyen van ca khoa lan gia tri. Khoi `rtabmap:` trong slam.yaml di
// thang vao rtabmap::ParametersMap, noi moi gia tri deu la chuoi -- kiem
// kieu o day se lam hong "true"/"0.05" thanh bool/double roi in lai khac.
out.emplace_back(kv.first.as<std::string>(), kv.second.as<std::string>());
}
return out;
}
// --- Khoi tao tuong minh ---------------------------------------------------
#define VSLAM_CONFIG_DEFINE(T) \
template T ConfigNode::get<T>(const std::string&, const T&) const; \
template T ConfigNode::require<T>(const std::string&) const; \
template T ConfigNode::as<T>() const; \
template T ConfigNode::as<T>(const T&) const;
VSLAM_CONFIG_DEFINE(bool)
VSLAM_CONFIG_DEFINE(int)
VSLAM_CONFIG_DEFINE(unsigned int)
VSLAM_CONFIG_DEFINE(float)
VSLAM_CONFIG_DEFINE(double)
VSLAM_CONFIG_DEFINE(std::string)
#undef VSLAM_CONFIG_DEFINE
template std::vector<double> ConfigNode::get<std::vector<double>>(
const std::string&, const std::vector<double>&) const;
template std::vector<double> ConfigNode::require<std::vector<double>>(
const std::string&) const;
template std::vector<std::string> ConfigNode::get<std::vector<std::string>>(
const std::string&, const std::vector<std::string>&) const;
template std::vector<std::string> ConfigNode::require<std::vector<std::string>>(
const std::string&) const;
} // namespace vslam

View File

@@ -0,0 +1,235 @@
#include "vslam/geometry.h"
#include <algorithm>
namespace vslam {
namespace {
constexpr double kPi = 3.14159265358979323846;
constexpr double kTwoPi = 2.0 * kPi;
} // namespace
// --- Goc -------------------------------------------------------------------
double NormalizeAngle(double a) {
// Port tu wheel_odom_node.cpp:45-50. Ban goc dung vong while; std::fmod
// nhanh hon va khong treo khi input la mot so rat lon (vd NaN lan vao tu
// encoder hong -> vong while chay vo han).
if (!std::isfinite(a)) return 0.0;
a = std::fmod(a + kPi, kTwoPi);
if (a < 0.0) a += kTwoPi;
return a - kPi;
}
// --- Quaternion ------------------------------------------------------------
Quaternion QuaternionFromYaw(double yaw) {
const double h = yaw * 0.5;
return Quaternion{0.0, 0.0, std::sin(h), std::cos(h)};
}
Quaternion QuaternionFromRPY(double roll, double pitch, double yaw) {
const double cr = std::cos(roll * 0.5), sr = std::sin(roll * 0.5);
const double cp = std::cos(pitch * 0.5), sp = std::sin(pitch * 0.5);
const double cy = std::cos(yaw * 0.5), sy = std::sin(yaw * 0.5);
Quaternion q;
q.w = cr * cp * cy + sr * sp * sy;
q.x = sr * cp * cy - cr * sp * sy;
q.y = cr * sp * cy + sr * cp * sy;
q.z = cr * cp * sy - sr * sp * cy;
return q;
}
double YawFromQuaternion(const Quaternion& q) {
const double siny = 2.0 * (q.w * q.z + q.x * q.y);
const double cosy = 1.0 - 2.0 * (q.y * q.y + q.z * q.z);
return std::atan2(siny, cosy);
}
void RPYFromQuaternion(const Quaternion& q, double* roll, double* pitch, double* yaw) {
const double sinr = 2.0 * (q.w * q.x + q.y * q.z);
const double cosr = 1.0 - 2.0 * (q.x * q.x + q.y * q.y);
if (roll) *roll = std::atan2(sinr, cosr);
// Kep truoc khi asin: sai so lam tron co the day gia tri ra ngoai [-1,1]
// va asin tra NaN. NaN o pitch lan vao gravity_align roi vao TF la mot
// trong nhung duong lan truyen loi kho truy nhat.
double sinp = 2.0 * (q.w * q.y - q.z * q.x);
sinp = std::max(-1.0, std::min(1.0, sinp));
if (pitch) *pitch = std::asin(sinp);
if (yaw) *yaw = YawFromQuaternion(q);
}
Quaternion QuaternionNormalized(const Quaternion& q) {
const double n = std::sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w);
if (n < 1e-12) return Quaternion{0.0, 0.0, 0.0, 1.0};
const double inv = 1.0 / n;
return Quaternion{q.x * inv, q.y * inv, q.z * inv, q.w * inv};
}
Quaternion QuaternionInverse(const Quaternion& q) {
// Gia dinh q da chuan hoa -> nghich dao = lien hop.
return Quaternion{-q.x, -q.y, -q.z, q.w};
}
Quaternion QuaternionMultiply(const Quaternion& a, const Quaternion& b) {
Quaternion r;
r.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;
r.x = a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y;
r.y = a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x;
r.z = a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w;
return r;
}
Quaternion QuaternionSlerp(const Quaternion& a, const Quaternion& b, double t) {
t = std::max(0.0, std::min(1.0, t));
double dot = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
// Lat dau de di duong ngan. Thieu buoc nay thi noi suy qua mot goc gan 360
// do thay vi goc nho -- TF se "quay nguoc" mot cach ngoan muc.
Quaternion bb = b;
if (dot < 0.0) {
bb = Quaternion{-b.x, -b.y, -b.z, -b.w};
dot = -dot;
}
// Gan trung nhau: LERP roi chuan hoa, tranh chia cho sin(theta) ~ 0.
if (dot > 0.9995) {
Quaternion r{a.x + (bb.x - a.x) * t, a.y + (bb.y - a.y) * t,
a.z + (bb.z - a.z) * t, a.w + (bb.w - a.w) * t};
return QuaternionNormalized(r);
}
const double theta_0 = std::acos(dot);
const double theta = theta_0 * t;
const double sin_theta_0 = std::sin(theta_0);
const double s0 = std::cos(theta) - dot * std::sin(theta) / sin_theta_0;
const double s1 = std::sin(theta) / sin_theta_0;
return Quaternion{a.x * s0 + bb.x * s1, a.y * s0 + bb.y * s1,
a.z * s0 + bb.z * s1, a.w * s0 + bb.w * s1};
}
Vector3 RotateVector(const Quaternion& q, const Vector3& v) {
// v' = v + 2w(u x v) + 2(u x (u x v)), voi u la phan vector cua q.
// Re hon chuyen sang ma tran quay khi chi xoay mot vai vector.
const double ux = q.x, uy = q.y, uz = q.z, w = q.w;
const double cx = uy * v.z - uz * v.y;
const double cy = uz * v.x - ux * v.z;
const double cz = ux * v.y - uy * v.x;
const double ccx = uy * cz - uz * cy;
const double ccy = uz * cx - ux * cz;
const double ccz = ux * cy - uy * cx;
return Vector3{v.x + 2.0 * (w * cx + ccx),
v.y + 2.0 * (w * cy + ccy),
v.z + 2.0 * (w * cz + ccz)};
}
// --- Transform -------------------------------------------------------------
Transform TransformIdentity() {
Transform t;
t.translation = Vector3{0.0, 0.0, 0.0};
t.rotation = Quaternion{0.0, 0.0, 0.0, 1.0};
return t;
}
Transform TransformCompose(const Transform& a, const Transform& b) {
Transform r;
r.rotation = QuaternionMultiply(a.rotation, b.rotation);
const Vector3 rb = RotateVector(a.rotation, b.translation);
r.translation = a.translation + rb;
return r;
}
Transform TransformInverse(const Transform& t) {
Transform r;
r.rotation = QuaternionInverse(t.rotation);
const Vector3 neg{-t.translation.x, -t.translation.y, -t.translation.z};
r.translation = RotateVector(r.rotation, neg);
return r;
}
Point TransformPoint(const Transform& t, const Point& p) {
const Vector3 v{p.x, p.y, p.z};
const Vector3 r = RotateVector(t.rotation, v) + t.translation;
return Point{r.x, r.y, r.z};
}
Vector3 TransformVector(const Transform& t, const Vector3& v) {
return RotateVector(t.rotation, v) + t.translation;
}
Transform TransformInterpolate(const Transform& a, const Transform& b, double t) {
Transform r;
r.translation = Lerp(a.translation, b.translation, t);
r.rotation = QuaternionSlerp(a.rotation, b.rotation, t);
return r;
}
// --- SE(2) -----------------------------------------------------------------
Pose2D Pose2DFromPose(const Pose& p) {
return Pose2D{p.position.x, p.position.y, YawFromQuaternion(p.orientation)};
}
Pose PoseFromPose2D(const Pose2D& p, double z) {
Pose out;
out.position = Point{p.x, p.y, z};
out.orientation = QuaternionFromYaw(p.theta);
return out;
}
Pose2D Pose2DCompose(const Pose2D& a, const Pose2D& b) {
const double c = std::cos(a.theta), s = std::sin(a.theta);
return Pose2D{a.x + c * b.x - s * b.y,
a.y + s * b.x + c * b.y,
NormalizeAngle(a.theta + b.theta)};
}
Pose2D Pose2DInverse(const Pose2D& p) {
const double c = std::cos(p.theta), s = std::sin(p.theta);
return Pose2D{-(c * p.x + s * p.y),
-(-s * p.x + c * p.y),
NormalizeAngle(-p.theta)};
}
Pose2D Pose2DBetween(const Pose2D& a, const Pose2D& b) {
// a^-1 * b, viet truc tiep thay vi ghep hai ham -- it phep tinh hon va
// day la duong nong khi tinh delta giua hai keyframe.
const double c = std::cos(a.theta), s = std::sin(a.theta);
const double dx = b.x - a.x, dy = b.y - a.y;
return Pose2D{c * dx + s * dy,
-s * dx + c * dy,
NormalizeAngle(b.theta - a.theta)};
}
Transform TransformFromPose2D(const Pose2D& p, double z) {
Transform t;
t.translation = Vector3{p.x, p.y, z};
t.rotation = QuaternionFromYaw(p.theta);
return t;
}
Pose2D Pose2DFromTransform(const Transform& t) {
return Pose2D{t.translation.x, t.translation.y, YawFromQuaternion(t.rotation)};
}
Transform TransformFromPose(const Pose& p) {
Transform t;
t.translation = Vector3{p.position.x, p.position.y, p.position.z};
t.rotation = p.orientation;
return t;
}
Pose PoseFromTransform(const Transform& t) {
Pose p;
p.position = Point{t.translation.x, t.translation.y, t.translation.z};
p.orientation = t.rotation;
return p;
}
} // namespace vslam

View File

@@ -0,0 +1,65 @@
#include "vslam/json_parse.h"
#include <cctype>
#include <cstdlib>
namespace vslam {
namespace {
// Tra ve vi tri ngay sau dau ':' cua "key", hoac npos.
size_t FindValue(const std::string& body, const std::string& key) {
const std::string pat = "\"" + key + "\"";
size_t p = body.find(pat);
if (p == std::string::npos) return std::string::npos;
p += pat.size();
while (p < body.size() && std::isspace(static_cast<unsigned char>(body[p]))) ++p;
if (p >= body.size() || body[p] != ':') return std::string::npos;
++p;
while (p < body.size() && std::isspace(static_cast<unsigned char>(body[p]))) ++p;
return p < body.size() ? p : std::string::npos;
}
} // namespace
bool JsonGetNumber(const std::string& body, const std::string& key, double* out) {
const size_t p = FindValue(body, key);
if (p == std::string::npos) return false;
char* end = nullptr;
const double v = std::strtod(body.c_str() + p, &end);
if (end == body.c_str() + p) return false;
*out = v;
return true;
}
bool JsonGetBool(const std::string& body, const std::string& key, bool* out) {
const size_t p = FindValue(body, key);
if (p == std::string::npos) return false;
if (body.compare(p, 4, "true") == 0) { *out = true; return true; }
if (body.compare(p, 5, "false") == 0) { *out = false; return true; }
return false;
}
bool JsonGetString(const std::string& body, const std::string& key, std::string* out) {
const size_t p = FindValue(body, key);
if (p == std::string::npos || body[p] != '"') return false;
out->clear();
for (size_t i = p + 1; i < body.size(); ++i) {
if (body[i] == '\\' && i + 1 < body.size()) {
++i;
switch (body[i]) {
case 'n': out->push_back('\n'); break;
case 't': out->push_back('\t'); break;
case 'r': out->push_back('\r'); break;
default: out->push_back(body[i]); break;
}
continue;
}
if (body[i] == '"') return true;
out->push_back(body[i]);
}
return false; // chuoi khong dong
}
} // namespace vslam

View File

@@ -0,0 +1,141 @@
#include "vslam/log.h"
#include <unistd.h>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <mutex>
namespace vslam {
namespace {
std::atomic<int> g_level{static_cast<int>(LogLevel::kInfo)};
std::atomic<bool> g_color{false};
std::atomic<bool> g_color_init{false};
std::mutex& SinkMutex() {
static std::mutex m;
return m;
}
LogSink& SinkRef() {
static LogSink sink; // rong = dung sink mac dinh ra stderr
return sink;
}
const char* ColorFor(LogLevel l) {
switch (l) {
case LogLevel::kDebug: return "\033[2m"; // mo
case LogLevel::kInfo: return "";
case LogLevel::kWarn: return "\033[33m"; // vang
case LogLevel::kError: return "\033[31m"; // do
default: return "";
}
}
// Chi lay ten file, bo duong dan. __FILE__ trong build tree rat dai.
const char* BaseName(const char* path) {
const char* slash = std::strrchr(path, '/');
return slash != nullptr ? slash + 1 : path;
}
bool ColorEnabled() {
if (!g_color_init.load(std::memory_order_relaxed)) {
g_color.store(::isatty(STDERR_FILENO) != 0, std::memory_order_relaxed);
g_color_init.store(true, std::memory_order_relaxed);
}
return g_color.load(std::memory_order_relaxed);
}
} // namespace
const char* LogLevelName(LogLevel l) {
switch (l) {
case LogLevel::kDebug: return "DEBUG";
case LogLevel::kInfo: return "INFO";
case LogLevel::kWarn: return "WARN";
case LogLevel::kError: return "ERROR";
case LogLevel::kOff: return "OFF";
}
return "?";
}
bool ParseLogLevel(const std::string& s, LogLevel* out) {
if (s == "debug" || s == "DEBUG") { *out = LogLevel::kDebug; return true; }
if (s == "info" || s == "INFO") { *out = LogLevel::kInfo; return true; }
if (s == "warn" || s == "WARN") { *out = LogLevel::kWarn; return true; }
if (s == "error" || s == "ERROR") { *out = LogLevel::kError; return true; }
if (s == "off" || s == "OFF") { *out = LogLevel::kOff; return true; }
return false;
}
void SetLogLevel(LogLevel l) { g_level.store(static_cast<int>(l), std::memory_order_relaxed); }
LogLevel GetLogLevel() {
return static_cast<LogLevel>(g_level.load(std::memory_order_relaxed));
}
void SetLogSink(LogSink sink) {
std::lock_guard<std::mutex> lk(SinkMutex());
SinkRef() = std::move(sink);
}
void SetLogColor(bool on) {
g_color.store(on, std::memory_order_relaxed);
g_color_init.store(true, std::memory_order_relaxed);
}
namespace detail {
void EmitLog(LogLevel level, const char* file, int line, const std::string& msg) {
{
std::lock_guard<std::mutex> lk(SinkMutex());
if (SinkRef()) {
SinkRef()(level, file, line, msg);
return;
}
}
// Sink mac dinh: stderr, mot lan fwrite co khoa. Dinh dang:
// HH:MM:SS.mmm WARN scan_sanitizer.cc:88 noi dung
using namespace std::chrono;
const auto now = system_clock::now();
const auto t = system_clock::to_time_t(now);
const auto ms = duration_cast<milliseconds>(now.time_since_epoch()).count() % 1000;
std::tm tm_buf{};
::localtime_r(&t, &tm_buf);
char stamp[32];
std::snprintf(stamp, sizeof(stamp), "%02d:%02d:%02d.%03d", tm_buf.tm_hour,
tm_buf.tm_min, tm_buf.tm_sec, static_cast<int>(ms));
const bool color = ColorEnabled();
const char* c_on = color ? ColorFor(level) : "";
const char* c_off = (color && c_on[0] != '\0') ? "\033[0m" : "";
static std::mutex out_mu;
std::lock_guard<std::mutex> lk(out_mu);
std::fprintf(stderr, "%s%s %-5s %s:%d %s%s\n", c_on, stamp,
LogLevelName(level), BaseName(file), line, msg.c_str(), c_off);
}
bool ThrottlePass(std::atomic<int64_t>* state, double period_sec) {
// steady_clock, KHONG phai stamp du lieu. Neu dung stamp thi khi replay
// nhanh (speed=0) moi dong se bi bop nham.
const auto now = std::chrono::steady_clock::now().time_since_epoch();
const int64_t now_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
const int64_t period_ns = static_cast<int64_t>(period_sec * 1e9);
int64_t last = state->load(std::memory_order_relaxed);
if (last != 0 && now_ns - last < period_ns) return false;
// CAS: neu hai luong cung toi day thi chi mot luong duoc in.
return state->compare_exchange_strong(last, now_ns, std::memory_order_relaxed);
}
} // namespace detail
} // namespace vslam

View File

@@ -0,0 +1,43 @@
#include "vslam/node_constants.h"
#include <cstdlib>
namespace vslam {
namespace {
// Tra ve $name neu co va khong rong, khong thi `fallback`.
std::string EnvOr(const char* name, const char* fallback) {
const char* v = std::getenv(name);
if (v != nullptr && v[0] != '\0') return std::string(v);
return std::string(fallback);
}
std::string Join(const std::string& dir, const std::string& rel) {
if (dir.empty()) return rel;
if (dir.back() == '/') return dir + rel;
return dir + "/" + rel;
}
} // namespace
std::string ConfigDir() { return EnvOr(kConfigDirEnv, kConfigurationDirectory); }
std::string ResourceDir() { return EnvOr(kResourceDirEnv, kResourceDirectory); }
std::string ConfigPath(const std::string& file_name) {
return Join(ConfigDir(), file_name);
}
std::string ResourcePath(const std::string& rel) { return Join(ResourceDir(), rel); }
std::string MapDir() { return Join(ResourceDir(), "maps"); }
std::string RecordDir() { return Join(ResourceDir(), "records"); }
std::string CorpusDir() {
const char* v = std::getenv(kCorpusDirEnv);
if (v != nullptr && v[0] != '\0') return std::string(v);
return MapDir();
}
} // namespace vslam

View File

@@ -0,0 +1,222 @@
#include "vslam/robot_model.h"
#include <algorithm>
#include <cmath>
#include <set>
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/node_constants.h"
namespace vslam {
namespace {
// Doc mot chuoi 3 so tu node YAML. Tra false kem duong day du khi hong --
// mot phep bien doi sai im lang la ca ban do lech.
bool ReadVec3(const ConfigNode& n, double out[3], std::string* err) {
if (n.IsNull()) {
*err = "thieu";
return false;
}
if (!n.IsSequence() || n.size() != 3) {
*err = "phai la chuoi 3 so, " + n.path();
return false;
}
for (size_t i = 0; i < 3; ++i) {
out[i] = n.at(i).as<double>();
}
return true;
}
} // namespace
RobotModel::RobotModel() : tree_(new TransformTree) {}
RobotModel::~RobotModel() = default;
StatusResponse RobotModel::LoadFile(const std::string& path) {
// ConfigNode::LoadFile nem ConfigError khi file thieu hoac YAML hong. Mot
// file config sai khong duoc phep lam sap tien trinh -- doi thanh loi doc
// duoc de nguoi goi quyet dinh.
try {
return Load(ConfigNode::LoadFile(path));
} catch (const std::exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml (" + path + "): " + e.what());
}
}
StatusResponse RobotModel::Load(const ConfigNode& root) {
// --- geometry ---
const ConfigNode g = root["geometry"];
if (!g.IsNull()) {
// Go sai ten khoa hien tai roi ve mac dinh mot cach im lang. `wheel_base`
// thay vi `wheel_separation` nghia la moi phep quay sai ti le, va khong
// co gi bao.
const std::vector<std::string> unknown = g.UnknownKeys(
{"wheel_radius", "wheel_separation", "robot_radius", "body_half_width"});
if (!unknown.empty()) {
std::string m = "robot.yaml geometry: khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
geometry_.wheel_radius = g.get<double>("wheel_radius", geometry_.wheel_radius);
geometry_.wheel_separation =
g.get<double>("wheel_separation", geometry_.wheel_separation);
geometry_.robot_radius = g.get<double>("robot_radius", geometry_.robot_radius);
geometry_.body_half_width =
g.get<double>("body_half_width", geometry_.body_half_width);
}
if (!(geometry_.wheel_radius > 0.0) || !(geometry_.wheel_separation > 0.0)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml: wheel_radius va wheel_separation "
"phai duong");
}
// --- base ---
const ConfigNode b = root["base"];
if (!b.IsNull()) {
const std::vector<std::string> unknown = b.UnknownKeys(
{"max_linear", "max_angular", "accel_limit", "cmd_timeout"});
if (!unknown.empty()) {
std::string m = "robot.yaml base: khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
base_.max_linear = b.get<double>("max_linear", base_.max_linear);
base_.max_angular = b.get<double>("max_angular", base_.max_angular);
base_.accel_limit = b.get<double>("accel_limit", base_.accel_limit);
base_.cmd_timeout = b.get<double>("cmd_timeout", base_.cmd_timeout);
}
// --- wheel_odom ---
const ConfigNode w = root["wheel_odom"];
if (!w.IsNull()) {
const std::vector<std::string> unknown =
w.UnknownKeys({"sigma_x_per_m", "sigma_y_per_m", "sigma_yaw_per_rad",
"slip_threshold", "slip_sigma_is_measured"});
if (!unknown.empty()) {
std::string m = "robot.yaml wheel_odom: khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
wheel_odom_.sigma_x_per_m =
w.get<double>("sigma_x_per_m", wheel_odom_.sigma_x_per_m);
wheel_odom_.sigma_y_per_m =
w.get<double>("sigma_y_per_m", wheel_odom_.sigma_y_per_m);
wheel_odom_.sigma_yaw_per_rad =
w.get<double>("sigma_yaw_per_rad", wheel_odom_.sigma_yaw_per_rad);
wheel_odom_.slip_threshold =
w.get<double>("slip_threshold", wheel_odom_.slip_threshold);
wheel_odom_.slip_sigma_is_measured =
w.get<bool>("slip_sigma_is_measured", wheel_odom_.slip_sigma_is_measured);
}
// --- frames ---
const ConfigNode frames = root["frames"];
if (frames.IsNull() || !frames.IsSequence() || frames.size() == 0) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml: thieu khoi `frames:` -- khong co "
"no thi khong stage nao dat duoc cam bien vao "
"dau");
}
// Mot `child` chi duoc xuat hien MOT lan. Hai dong cung child thi dong sau
// am tham thang, va nua so doc file se tin dong dau.
std::set<std::string> seen_children;
for (size_t i = 0; i < frames.size(); ++i) {
const ConfigNode f = frames.at(i);
const std::vector<std::string> unknown =
f.UnknownKeys({"parent", "child", "xyz", "rpy"});
if (!unknown.empty()) {
std::string m = "robot.yaml frames[" + std::to_string(i) + "]: khoa la:";
for (const auto& k : unknown) m += " " + k;
return StatusResponse::Error(StatusCode::kInvalidArgument, m);
}
const std::string parent = f.require<std::string>("parent");
const std::string child = f.require<std::string>("child");
if (parent == child) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml frames[" + std::to_string(i) +
"]: parent trung child (" + parent + ")");
}
if (!seen_children.insert(child).second) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"robot.yaml: frame `" + child +
"` duoc khai hai lan -- lan sau am tham thang, va do la lop bug "
"ma file nay sinh ra de xoa");
}
double xyz[3] = {0, 0, 0}, rpy[3] = {0, 0, 0};
std::string err;
if (!ReadVec3(f["xyz"], xyz, &err)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml frames[" + std::to_string(i) +
"].xyz: " + err);
}
if (!ReadVec3(f["rpy"], rpy, &err)) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml frames[" + std::to_string(i) +
"].rpy: " + err);
}
Transform tf = TransformIdentity();
tf.translation = Vector3{xyz[0], xyz[1], xyz[2]};
tf.rotation = QuaternionFromRPY(rpy[0], rpy[1], rpy[2]);
// SetStatic nem ConfigError khi tao vong -- bat lai va tra ve loi doc
// duoc, vi mot file config sai khong duoc phep lam sap tien trinh.
try {
const StatusResponse st = tree_->SetStatic(parent, child, tf);
if (!st.ok()) return st;
} catch (const std::exception& e) {
return StatusResponse::Error(StatusCode::kInvalidArgument,
"robot.yaml frames[" + std::to_string(i) +
"] " + parent + " -> " + child + ": " +
e.what());
}
if (parent == kBaseLinkFrame && child == kCameraFrame) {
camera_z_in_base_link_ = xyz[2];
camera_pitch_ = rpy[1];
have_camera_ = true;
}
}
VSLAM_INFO("robot: " << frames.size() << " canh tinh, banh r="
<< geometry_.wheel_radius << " d=" << geometry_.wheel_separation
<< (have_camera_
? ", camera cao " + std::to_string(camera_height_above_floor()) +
" m so voi san"
: ", KHONG co camera_link"));
return StatusResponse::Ok();
}
bool RobotModel::StaticTransform(const std::string& target,
const std::string& source, Transform* out) const {
// Canh tinh khong co dau thoi gian, nen LookupLatest la dung: no dung mau
// moi nhat cua tung canh, va voi canh tinh thi chi co mot mau.
//
// `Find` chu khong `Resolve`: tra cuu mot frame chua ton tai phai TRA FALSE
// chu khong duoc am tham tao ra no. Resolve() tao frame moi, va mot frame
// go sai ten se thanh mot nhanh roi ma khong ai bao.
const FrameId t = tree_->Find(target);
const FrameId s = tree_->Find(source);
if (t == kInvalidFrame || s == kInvalidFrame) return false;
return tree_->LookupLatest(t, s, out);
}
double RobotModel::camera_height_above_floor() const {
// base_link o tam truc, cach san dung bang ban kinh banh.
//
// Day la ly do `cliff_detect.nominal_tz` KHONG duoc go tay: no la mot HE
// QUA cua hai so khac, va go tay lan thu hai la cho mot trong hai duoc
// phep lech.
return camera_z_in_base_link_ + geometry_.wheel_radius;
}
double RobotModel::camera_pitch() const { return camera_pitch_; }
} // namespace vslam

View File

@@ -0,0 +1,150 @@
#include "vslam/stats.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <mutex>
#include <vector>
namespace vslam {
namespace {
int64_t ToNs(std::chrono::steady_clock::time_point tp) {
return std::chrono::duration_cast<std::chrono::nanoseconds>(tp.time_since_epoch())
.count();
}
} // namespace
// --- RateMonitor -----------------------------------------------------------
RateMonitor::RateMonitor(double window_sec) : window_sec_(window_sec) {}
void RateMonitor::Tick(std::chrono::steady_clock::time_point now) {
const int64_t ns = ToNs(now);
count_.fetch_add(1, std::memory_order_relaxed);
last_ns_.store(ns, std::memory_order_relaxed);
const int64_t first = first_ns_.load(std::memory_order_relaxed);
if (first == 0) {
first_ns_.store(ns, std::memory_order_relaxed);
window_count_.store(1, std::memory_order_relaxed);
return;
}
const uint64_t wc = window_count_.fetch_add(1, std::memory_order_relaxed) + 1;
const double elapsed = static_cast<double>(ns - first) * 1e-9;
if (elapsed >= window_sec_) {
hz_.store(elapsed > 0.0 ? static_cast<double>(wc) / elapsed : 0.0,
std::memory_order_relaxed);
// Mo cua so moi. Khong dung cua so truot that (deque timestamp) vi o
// 200 Hz thi chi phi bo nho va khoa khong dang -- sai so cua cua so nhay
// la chap nhan duoc cho muc dich chan doan.
first_ns_.store(ns, std::memory_order_relaxed);
window_count_.store(0, std::memory_order_relaxed);
}
}
void RateMonitor::Tick() { Tick(std::chrono::steady_clock::now()); }
double RateMonitor::hz() const { return hz_.load(std::memory_order_relaxed); }
double RateMonitor::age_sec(std::chrono::steady_clock::time_point now) const {
const int64_t last = last_ns_.load(std::memory_order_relaxed);
if (last == 0) return std::numeric_limits<double>::infinity();
return static_cast<double>(ToNs(now) - last) * 1e-9;
}
void RateMonitor::Reset() {
count_.store(0, std::memory_order_relaxed);
first_ns_.store(0, std::memory_order_relaxed);
last_ns_.store(0, std::memory_order_relaxed);
window_count_.store(0, std::memory_order_relaxed);
hz_.store(0.0, std::memory_order_relaxed);
}
// --- LatencyMonitor --------------------------------------------------------
struct LatencyMonitor::Impl {
mutable std::mutex mu;
std::vector<double> ring;
size_t head = 0;
size_t filled = 0;
double max_seen = 0.0;
double last = 0.0;
uint64_t count = 0;
explicit Impl(size_t window) : ring(window, 0.0) {}
// Goi khi da giu mu.
double PercentileLocked(double p) const {
if (filled == 0) return 0.0;
std::vector<double> tmp(ring.begin(), ring.begin() + static_cast<long>(filled));
const size_t idx = static_cast<size_t>(p * static_cast<double>(filled - 1));
std::nth_element(tmp.begin(), tmp.begin() + static_cast<long>(idx), tmp.end());
return tmp[idx];
}
};
LatencyMonitor::LatencyMonitor(size_t window)
: impl_(std::make_unique<Impl>(window == 0 ? 1 : window)) {}
LatencyMonitor::~LatencyMonitor() = default;
void LatencyMonitor::Add(double ms) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->ring[impl_->head] = ms;
impl_->head = (impl_->head + 1) % impl_->ring.size();
if (impl_->filled < impl_->ring.size()) impl_->filled++;
if (ms > impl_->max_seen) impl_->max_seen = ms;
impl_->last = ms;
impl_->count++;
}
double LatencyMonitor::p50() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->PercentileLocked(0.50);
}
double LatencyMonitor::p95() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->PercentileLocked(0.95);
}
double LatencyMonitor::max() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->max_seen;
}
double LatencyMonitor::last() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->last;
}
uint64_t LatencyMonitor::count() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->count;
}
void LatencyMonitor::Reset() {
std::lock_guard<std::mutex> lk(impl_->mu);
std::fill(impl_->ring.begin(), impl_->ring.end(), 0.0);
impl_->head = 0;
impl_->filled = 0;
impl_->max_seen = 0.0;
impl_->last = 0.0;
impl_->count = 0;
}
// --- ScopedLatency ---------------------------------------------------------
ScopedLatency::ScopedLatency(LatencyMonitor* m, const Clock* clock)
: m_(m), t0_(clock != nullptr ? clock->Steady() : std::chrono::steady_clock::now()) {}
ScopedLatency::~ScopedLatency() {
if (m_ == nullptr) return;
const auto dt = std::chrono::steady_clock::now() - t0_;
m_->Add(std::chrono::duration<double, std::milli>(dt).count());
}
} // namespace vslam

View File

@@ -0,0 +1,262 @@
#include "vslam/teleop_model.h"
#include <algorithm>
#include <cmath>
#include <stdexcept>
namespace vslam {
namespace {
double Clamp(double v, double lo, double hi) { return std::max(lo, std::min(v, hi)); }
void ValidateFinite(const char* name, double v) {
if (!std::isfinite(v)) {
throw std::invalid_argument(std::string(name) + " must be a finite number");
}
}
void ValidateRange(const char* name, double minimum, double maximum, double step) {
ValidateFinite(name, minimum);
ValidateFinite(name, maximum);
ValidateFinite(name, step);
if (minimum < 0.0) {
throw std::invalid_argument(std::string("minimum ") + name +
" must be non-negative");
}
if (maximum < minimum) {
throw std::invalid_argument(std::string("maximum ") + name +
" must not be less than its minimum");
}
if (step <= 0.0) {
throw std::invalid_argument(std::string(name) + " step must be positive");
}
}
void ValidateCommandRange(const char* name, double minimum, double maximum) {
ValidateFinite(name, minimum);
ValidateFinite(name, maximum);
if (minimum > 0.0) {
throw std::invalid_argument(std::string("minimum ") + name +
" must be zero or negative");
}
if (maximum < 0.0) {
throw std::invalid_argument(std::string("maximum ") + name +
" must be zero or positive");
}
if (minimum >= maximum) {
throw std::invalid_argument(std::string("minimum ") + name +
" must be less than its maximum");
}
}
} // namespace
bool ParseTeleopKey(const std::string& name, TeleopKey* out) {
if (name == "Up") { *out = TeleopKey::kUp; return true; }
if (name == "Down") { *out = TeleopKey::kDown; return true; }
if (name == "Left") { *out = TeleopKey::kLeft; return true; }
if (name == "Right") { *out = TeleopKey::kRight; return true; }
return false;
}
const char* TeleopKeyName(TeleopKey k) {
switch (k) {
case TeleopKey::kUp: return "Up";
case TeleopKey::kDown: return "Down";
case TeleopKey::kLeft: return "Left";
case TeleopKey::kRight: return "Right";
}
return "?";
}
TeleopModel::TeleopModel(TeleopConfig cfg) {
ValidateRange("linear speed", cfg.min_linear_speed, cfg.max_linear_speed,
cfg.linear_step);
ValidateRange("angular speed", cfg.min_angular_speed, cfg.max_angular_speed,
cfg.angular_step);
ValidateFinite("linear_speed", cfg.linear_speed);
ValidateFinite("angular_speed", cfg.angular_speed);
// Mac dinh: gioi han duoi doi xung voi gioi han tren.
const double min_lin_cmd =
cfg.has_min_linear_command ? cfg.min_linear_command : -cfg.max_linear_speed;
const double min_ang_cmd =
cfg.has_min_angular_command ? cfg.min_angular_command : -cfg.max_angular_speed;
ValidateCommandRange("linear command", min_lin_cmd, cfg.max_linear_speed);
ValidateCommandRange("angular command", min_ang_cmd, cfg.max_angular_speed);
linear_step_ = cfg.linear_step;
angular_step_ = cfg.angular_step;
min_linear_speed_ = cfg.min_linear_speed;
max_linear_speed_ = cfg.max_linear_speed;
min_angular_speed_ = cfg.min_angular_speed;
max_angular_speed_ = cfg.max_angular_speed;
min_linear_command_ = min_lin_cmd;
min_angular_command_ = min_ang_cmd;
linear_speed_ = Clamp(cfg.linear_speed, min_linear_speed_, max_linear_speed_);
angular_speed_ = Clamp(cfg.angular_speed, min_angular_speed_, max_angular_speed_);
}
// --- Nguon nhap ------------------------------------------------------------
bool TeleopModel::SetKey(TeleopKey key, bool pressed) {
if (pressed) {
// Bam phim GIAI PHONG lenh manual. Khong bao gio tron hai nguon.
ReleaseManualControl();
keys_.insert(key);
} else {
keys_.erase(key);
}
return true;
}
void TeleopModel::ClearKeys() { keys_.clear(); }
void TeleopModel::SetJoystick(double horizontal, double vertical) {
ValidateFinite("joystick horizontal axis", horizontal);
ValidateFinite("joystick vertical axis", vertical);
joy_h_ = Clamp(horizontal, -1.0, 1.0);
joy_v_ = Clamp(vertical, -1.0, 1.0);
joystick_active_ = true;
ReleaseManualControl();
}
void TeleopModel::ReleaseJoystick() { joystick_active_ = false; }
void TeleopModel::ClearMotion() {
ClearKeys();
ReleaseJoystick();
ReleaseManualControl();
}
std::pair<double, double> TeleopModel::SetManualCommand(const double* linear_x,
const double* angular_z) {
double cur_lin, cur_ang;
if (!manual_active_) {
const auto c = Command();
cur_lin = c.first;
cur_ang = c.second;
} else {
cur_lin = manual_lin_;
cur_ang = manual_ang_;
}
if (linear_x != nullptr) {
ValidateFinite("manual linear command", *linear_x);
cur_lin = *linear_x;
}
if (angular_z != nullptr) {
ValidateFinite("manual angular command", *angular_z);
cur_ang = *angular_z;
}
ClearKeys();
ReleaseJoystick();
const auto clamped = ClampCommand(cur_lin, cur_ang);
manual_lin_ = clamped.first;
manual_ang_ = clamped.second;
manual_active_ = true;
return clamped;
}
void TeleopModel::ReleaseManualControl() { manual_active_ = false; }
// --- Ket qua ---------------------------------------------------------------
std::pair<double, double> TeleopModel::ClampCommand(double linear_x,
double angular_z) const {
return {Clamp(linear_x, min_linear_command_, max_linear_speed_),
Clamp(angular_z, min_angular_command_, max_angular_speed_)};
}
void TeleopModel::ClampManualCommand() {
if (!manual_active_) return;
const auto c = ClampCommand(manual_lin_, manual_ang_);
manual_lin_ = c.first;
manual_ang_ = c.second;
}
std::pair<double, double> TeleopModel::Command() const {
// Thu tu uu tien: manual > joystick > phim.
if (manual_active_) return {manual_lin_, manual_ang_};
if (joystick_active_) {
return ClampCommand(-joy_v_ * linear_speed_, -joy_h_ * angular_speed_);
}
const int linear_axis = static_cast<int>(keys_.count(TeleopKey::kUp)) -
static_cast<int>(keys_.count(TeleopKey::kDown));
const int angular_axis = static_cast<int>(keys_.count(TeleopKey::kLeft)) -
static_cast<int>(keys_.count(TeleopKey::kRight));
return ClampCommand(linear_axis * linear_speed_, angular_axis * angular_speed_);
}
std::pair<double, double> TeleopModel::JoystickPosition() const {
if (joystick_active_) return {joy_h_, joy_v_};
const int h = static_cast<int>(keys_.count(TeleopKey::kRight)) -
static_cast<int>(keys_.count(TeleopKey::kLeft));
const int v = static_cast<int>(keys_.count(TeleopKey::kDown)) -
static_cast<int>(keys_.count(TeleopKey::kUp));
return {static_cast<double>(h), static_cast<double>(v)};
}
// --- Chinh toc do ----------------------------------------------------------
double TeleopModel::AdjustLinearSpeed(double direction) {
return SetLinearSpeed(linear_speed_ + direction * linear_step_);
}
double TeleopModel::AdjustAngularSpeed(double direction) {
return SetAngularSpeed(angular_speed_ + direction * angular_step_);
}
double TeleopModel::SetLinearSpeed(double value) {
ValidateFinite("linear speed", value);
linear_speed_ = Clamp(value, min_linear_speed_, max_linear_speed_);
return linear_speed_;
}
double TeleopModel::SetAngularSpeed(double value) {
ValidateFinite("angular speed", value);
angular_speed_ = Clamp(value, min_angular_speed_, max_angular_speed_);
return angular_speed_;
}
double TeleopModel::SetMaxLinearSpeed(double value) {
ValidateFinite("maximum linear speed", value);
max_linear_speed_ = std::max(min_linear_speed_, value);
linear_speed_ = std::min(linear_speed_, max_linear_speed_);
ClampManualCommand();
return max_linear_speed_;
}
double TeleopModel::SetMaxAngularSpeed(double value) {
ValidateFinite("maximum angular speed", value);
max_angular_speed_ = std::max(min_angular_speed_, value);
angular_speed_ = std::min(angular_speed_, max_angular_speed_);
ClampManualCommand();
return max_angular_speed_;
}
double TeleopModel::SetMinLinearCommand(double value) {
ValidateFinite("minimum linear command", value);
min_linear_command_ = std::min(0.0, value);
if (min_linear_command_ >= max_linear_speed_) {
min_linear_command_ = std::min(0.0, max_linear_speed_ - linear_step_);
}
ClampManualCommand();
return min_linear_command_;
}
double TeleopModel::SetMinAngularCommand(double value) {
ValidateFinite("minimum angular command", value);
min_angular_command_ = std::min(0.0, value);
if (min_angular_command_ >= max_angular_speed_) {
min_angular_command_ = std::min(0.0, max_angular_speed_ - angular_step_);
}
ClampManualCommand();
return min_angular_command_;
}
} // namespace vslam

View File

@@ -0,0 +1,485 @@
#include "vslam/transform_tree.h"
#include <algorithm>
#include <functional>
#include <mutex>
#include <sstream>
#include <unordered_map>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/log.h"
#include "vslam/stats.h"
namespace vslam {
namespace {
constexpr size_t kMaxDepth = 32; // cay that co 5 muc; 32 la chan an toan
struct Sample {
UnixTime stamp;
Transform tf;
};
} // namespace
// Mot canh = quan he cha-con. Canh tinh giu mot Transform; canh dong giu ring
// buffer cac mau theo thoi gian.
struct Edge {
FrameId parent = kInvalidFrame;
bool is_static = false;
Transform static_tf; // chi co nghia khi is_static
std::vector<Sample> ring;
size_t head = 0; // vi tri se ghi tiep
size_t filled = 0;
uint64_t samples = 0;
RateMonitor rate{2.0};
const Sample& at(size_t i) const { return ring[i % ring.size()]; }
// Mau moi nhat. Goi phai bao dam filled > 0.
const Sample& newest() const { return ring[(head + ring.size() - 1) % ring.size()]; }
// Mau cu nhat con song.
const Sample& oldest() const {
return filled < ring.size() ? ring[0] : ring[head % ring.size()];
}
};
struct TransformTree::Impl {
mutable std::mutex mu;
std::unordered_map<std::string, FrameId> name_to_id;
std::vector<std::string> id_to_name;
// Chi muc theo frame CON: moi frame co dung mot cha, nen mot canh la du.
// Day chinh la gia dinh cho phep bo toan bo may tra cuu tong quat cua tf2.
std::unordered_map<FrameId, Edge> edges;
double history_sec;
size_t slots_per_edge;
double extrapolation_limit = 0.1;
std::string empty_name;
// Duong di tu `frame` len goc. Tra ve so muc, hoac 0 neu vuot kMaxDepth.
size_t PathToRoot(FrameId frame, FrameId* out) const {
size_t n = 0;
FrameId cur = frame;
while (n < kMaxDepth) {
out[n++] = cur;
auto it = edges.find(cur);
if (it == edges.end()) return n; // toi goc
cur = it->second.parent;
}
return 0; // vong hoac qua sau
}
// To tien chung gan nhat cua a va b. kInvalidFrame neu hai frame khong noi.
bool CommonAncestor(FrameId a, FrameId b, FrameId* pa, size_t* na, FrameId* pb,
size_t* nb, FrameId* lca) const {
*na = PathToRoot(a, pa);
*nb = PathToRoot(b, pb);
if (*na == 0 || *nb == 0) return false;
for (size_t i = 0; i < *na; ++i) {
for (size_t j = 0; j < *nb; ++j) {
if (pa[i] == pb[j]) {
*lca = pa[i];
*na = i; // so canh phai di tu a len lca
*nb = j;
return true;
}
}
}
return false;
}
// Bien doi canh don parent<-child tai `stamp`, noi suy neu can.
bool EdgeAt(const Edge& e, UnixTime stamp, bool latest, Transform* out,
std::string* err) const {
if (e.is_static) {
*out = e.static_tf;
return true;
}
if (e.filled == 0) {
if (err) *err = "canh chua co mau nao";
return false;
}
const Sample& newest = e.newest();
if (latest) {
*out = newest.tf;
return true;
}
// Ngoai suy ve tuong lai: tu choi neu vuot gioi han.
// tf2 nem ExtrapolationException o day va rat nhieu code goi bat roi bo
// qua im lang; tra false + dien err de goi khong the lo.
if (stamp > newest.stamp) {
const double ahead = SecondsBetween(stamp, newest.stamp);
if (ahead > extrapolation_limit) {
if (err) {
std::ostringstream oss;
oss << "ngoai suy " << ahead << " s vuot gioi han "
<< extrapolation_limit << " s";
*err = oss.str();
}
return false;
}
*out = newest.tf;
return true;
}
const Sample& oldest = e.oldest();
if (stamp < oldest.stamp) {
if (err) {
std::ostringstream oss;
oss << "stamp cu hon lich su " << SecondsBetween(oldest.stamp, stamp) << " s";
*err = oss.str();
}
return false;
}
// Tim hai mau kep stamp. Ring nho (512) va truy van gan dau moi nen quet
// nguoc tu moi nhat nhanh hon tim nhi phan tren bo dem vong.
const size_t n = e.filled;
const size_t base = e.filled < e.ring.size() ? 0 : e.head;
for (size_t k = n; k-- > 1;) {
const Sample& hi = e.at(base + k);
const Sample& lo = e.at(base + k - 1);
if (stamp >= lo.stamp && stamp <= hi.stamp) {
const int64_t span = hi.stamp.toNSec() - lo.stamp.toNSec();
if (span <= 0) {
*out = hi.tf;
return true;
}
const double t =
static_cast<double>(stamp.toNSec() - lo.stamp.toNSec()) /
static_cast<double>(span);
*out = TransformInterpolate(lo.tf, hi.tf, t);
return true;
}
}
*out = newest.tf;
return true;
}
};
// ---------------------------------------------------------------------------
TransformTree::TransformTree(double history_sec, size_t slots_per_edge)
: impl_(std::make_unique<Impl>()) {
impl_->history_sec = history_sec;
impl_->slots_per_edge = slots_per_edge == 0 ? 1 : slots_per_edge;
}
TransformTree::~TransformTree() = default;
FrameId TransformTree::Resolve(const std::string& name) {
std::lock_guard<std::mutex> lk(impl_->mu);
auto it = impl_->name_to_id.find(name);
if (it != impl_->name_to_id.end()) return it->second;
const FrameId id = static_cast<FrameId>(impl_->id_to_name.size());
impl_->id_to_name.push_back(name);
impl_->name_to_id.emplace(name, id);
return id;
}
FrameId TransformTree::Find(const std::string& name) const {
std::lock_guard<std::mutex> lk(impl_->mu);
auto it = impl_->name_to_id.find(name);
return it == impl_->name_to_id.end() ? kInvalidFrame : it->second;
}
const std::string& TransformTree::Name(FrameId id) const {
std::lock_guard<std::mutex> lk(impl_->mu);
if (id >= impl_->id_to_name.size()) return impl_->empty_name;
return impl_->id_to_name[id];
}
size_t TransformTree::frame_count() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->id_to_name.size();
}
StatusResponse TransformTree::SetStatic(FrameId parent, FrameId child,
const Transform& tf) {
std::lock_guard<std::mutex> lk(impl_->mu);
// Kiem vong truoc khi ghi: di tu `parent` len goc, neu gap `child` thi viec
// dat canh nay se tao vong va moi lookup sau do se treo.
FrameId cur = parent;
for (size_t i = 0; i < kMaxDepth; ++i) {
if (cur == child) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"SetStatic tao vong trong cay TF: " + impl_->id_to_name[child]);
}
auto it = impl_->edges.find(cur);
if (it == impl_->edges.end()) break;
cur = it->second.parent;
}
Edge& e = impl_->edges[child];
if (!e.is_static && e.samples > 0) {
return StatusResponse::Error(
StatusCode::kFailedPrecondition,
"canh " + impl_->id_to_name[child] + " da la canh dong, khong the dat tinh");
}
e.parent = parent;
e.is_static = true;
e.static_tf = tf;
return StatusResponse::Ok();
}
StatusResponse TransformTree::SetStatic(const std::string& parent,
const std::string& child,
const Transform& tf) {
return SetStatic(Resolve(parent), Resolve(child), tf);
}
bool TransformTree::SetTransform(FrameId parent, FrameId child, UnixTime stamp,
const Transform& tf) {
std::lock_guard<std::mutex> lk(impl_->mu);
Edge& e = impl_->edges[child];
if (e.is_static) {
VSLAM_WARN_THROTTLE(5.0, "SetTransform tren canh tinh "
<< impl_->id_to_name[child] << ", bo qua");
return false;
}
if (e.parent != kInvalidFrame && e.parent != parent) {
// Doi cha giua chung la dau hieu hai nguoi cung ghi mot canh -- vi pham
// quy tac "moi canh dung mot nguoi ghi". Bao to, dung im lang.
VSLAM_ERROR_THROTTLE(5.0, "canh " << impl_->id_to_name[child]
<< " doi cha tu " << impl_->id_to_name[e.parent]
<< " sang " << impl_->id_to_name[parent]);
return false;
}
e.parent = parent;
if (e.ring.empty()) e.ring.resize(impl_->slots_per_edge);
if (e.filled > 0 && stamp < e.newest().stamp) {
// Lui thoi gian: ban ghi bi xao tron thu tu, hoac hai nguoi ghi. Noi suy
// tren ring khong con don dieu nua nen moi lookup sau do se sai.
VSLAM_WARN_THROTTLE(5.0, "canh " << impl_->id_to_name[child]
<< ": stamp lui " << e.newest().stamp.toString()
<< " -> " << stamp.toString() << ", bo qua");
return false;
}
e.ring[e.head] = Sample{stamp, tf};
e.head = (e.head + 1) % e.ring.size();
if (e.filled < e.ring.size()) e.filled++;
e.samples++;
e.rate.Tick();
return true;
}
bool TransformTree::Lookup(FrameId target, FrameId source, UnixTime stamp,
Transform* out, std::string* err) const {
std::lock_guard<std::mutex> lk(impl_->mu);
if (target == source) {
*out = TransformIdentity();
return true;
}
FrameId pa[kMaxDepth], pb[kMaxDepth], lca = kInvalidFrame;
size_t na = 0, nb = 0;
if (!impl_->CommonAncestor(source, target, pa, &na, pb, &nb, &lca)) {
if (err) {
*err = "khong co duong noi " + impl_->id_to_name[source] + " -> " +
impl_->id_to_name[target];
}
return false;
}
const bool latest = stamp.isZero();
// source -> lca: ghep xuoi cac canh child->parent.
Transform src_to_lca = TransformIdentity();
for (size_t i = 0; i < na; ++i) {
auto it = impl_->edges.find(pa[i]);
if (it == impl_->edges.end()) break;
Transform e;
if (!impl_->EdgeAt(it->second, stamp, latest, &e, err)) {
if (err) *err = impl_->id_to_name[pa[i]] + ": " + *err;
return false;
}
src_to_lca = TransformCompose(e, src_to_lca);
}
// target -> lca, roi lay nghich dao.
Transform tgt_to_lca = TransformIdentity();
for (size_t i = 0; i < nb; ++i) {
auto it = impl_->edges.find(pb[i]);
if (it == impl_->edges.end()) break;
Transform e;
if (!impl_->EdgeAt(it->second, stamp, latest, &e, err)) {
if (err) *err = impl_->id_to_name[pb[i]] + ": " + *err;
return false;
}
tgt_to_lca = TransformCompose(e, tgt_to_lca);
}
*out = TransformCompose(TransformInverse(tgt_to_lca), src_to_lca);
return true;
}
bool TransformTree::Lookup(const std::string& target, const std::string& source,
UnixTime stamp, Transform* out, std::string* err) const {
const FrameId t = Find(target), s = Find(source);
if (t == kInvalidFrame || s == kInvalidFrame) {
if (err) *err = "frame chua dang ky: " + (t == kInvalidFrame ? target : source);
return false;
}
return Lookup(t, s, stamp, out, err);
}
bool TransformTree::LookupLatest(FrameId target, FrameId source, Transform* out,
std::string* err) const {
return Lookup(target, source, kTimeZero, out, err);
}
UnixTime TransformTree::LatestCommonTime(FrameId a, FrameId b) const {
std::lock_guard<std::mutex> lk(impl_->mu);
FrameId pa[kMaxDepth], pb[kMaxDepth], lca = kInvalidFrame;
size_t na = 0, nb = 0;
if (!impl_->CommonAncestor(a, b, pa, &na, pb, &nb, &lca)) return kTimeZero;
// Thoi diem chung moi nhat = MIN cua cac mau moi nhat tren duong di.
// Canh tinh khong gioi han gi nen bo qua.
UnixTime best = kTimeMax;
bool any_dynamic = false;
auto scan = [&](const FrameId* path, size_t n) {
for (size_t i = 0; i < n; ++i) {
auto it = impl_->edges.find(path[i]);
if (it == impl_->edges.end() || it->second.is_static) continue;
if (it->second.filled == 0) {
best = kTimeZero;
return;
}
any_dynamic = true;
const UnixTime s = it->second.newest().stamp;
if (s < best) best = s;
}
};
scan(pa, na);
if (best.isZero()) return kTimeZero;
scan(pb, nb);
if (!any_dynamic) return kTimeZero; // toan canh tinh: moi luc deu hop le
return best.isZero() ? kTimeZero : best;
}
bool TransformTree::CanTransform(FrameId target, FrameId source,
UnixTime stamp) const {
Transform tmp;
return Lookup(target, source, stamp, &tmp, nullptr);
}
void TransformTree::SetExtrapolationLimit(double sec) {
std::lock_guard<std::mutex> lk(impl_->mu);
impl_->extrapolation_limit = sec;
}
double TransformTree::extrapolation_limit() const {
std::lock_guard<std::mutex> lk(impl_->mu);
return impl_->extrapolation_limit;
}
std::vector<TransformTree::EdgeStatus> TransformTree::EdgeStatuses() const {
std::lock_guard<std::mutex> lk(impl_->mu);
std::vector<EdgeStatus> out;
out.reserve(impl_->edges.size());
for (const auto& kv : impl_->edges) {
EdgeStatus s;
s.child = impl_->id_to_name[kv.first];
s.parent = kv.second.parent < impl_->id_to_name.size()
? impl_->id_to_name[kv.second.parent]
: "?";
s.is_static = kv.second.is_static;
s.samples = kv.second.samples;
s.hz = kv.second.rate.hz();
if (kv.second.filled > 0) s.latest = kv.second.newest().stamp;
out.push_back(std::move(s));
}
std::sort(out.begin(), out.end(),
[](const EdgeStatus& a, const EdgeStatus& b) { return a.child < b.child; });
return out;
}
std::string TransformTree::DumpTree() const {
// Thay rqt_tf_tree. In ra dang cay, danh dau canh tinh/dong kem tan so.
const auto edges = EdgeStatuses();
std::lock_guard<std::mutex> lk(impl_->mu);
std::unordered_map<std::string, std::vector<const EdgeStatus*>> children;
std::vector<std::string> roots;
for (const auto& e : edges) children[e.parent].push_back(&e);
for (const auto& name : impl_->id_to_name) {
if (impl_->edges.find(impl_->name_to_id.at(name)) == impl_->edges.end()) {
roots.push_back(name);
}
}
std::ostringstream oss;
std::function<void(const std::string&, int)> walk = [&](const std::string& node,
int depth) {
oss << std::string(static_cast<size_t>(depth) * 2, ' ') << node;
if (depth > 0) {
for (const auto& e : edges) {
if (e.child != node) continue;
if (e.is_static) {
oss << " [tinh]";
} else {
oss << " [dong " << e.hz << " Hz, " << e.samples << " mau]";
}
break;
}
}
oss << "\n";
auto it = children.find(node);
if (it == children.end()) return;
for (const auto* c : it->second) walk(c->child, depth + 1);
};
for (const auto& r : roots) walk(r, 0);
return oss.str();
}
// --- TfBridge --------------------------------------------------------------
TfBridge::TfBridge(std::string tracking_frame, double lookup_timeout_sec,
std::shared_ptr<const TransformTree> tree)
: tracking_frame_(std::move(tracking_frame)),
lookup_timeout_sec_(lookup_timeout_sec),
tree_(std::move(tree)) {}
bool TfBridge::LookupToTracking(UnixTime time, FrameId frame, Transform* out) const {
const FrameId tracking = tree_->Find(tracking_frame_);
if (tracking == kInvalidFrame) return false;
std::string err;
if (tree_->Lookup(tracking, frame, time, out, &err)) return true;
VSLAM_DEBUG_THROTTLE(2.0, "TfBridge: " << err);
return false;
}
bool TfBridge::LookupToTracking(UnixTime time, const std::string& frame,
Transform* out) const {
const FrameId id = tree_->Find(frame);
if (id == kInvalidFrame) return false;
return LookupToTracking(time, id, out);
}
} // namespace vslam

View File

@@ -0,0 +1,15 @@
#include "vslam/unix_time.h"
#include <cstdio>
namespace vslam {
std::string UnixTime::toString() const {
// In nguyen ven sec.nsec thay vi qua double: double chi co 53 bit mantissa,
// khong du de giu ca 1.7e9 giay lan do phan giai nanosecond.
char buf[32];
std::snprintf(buf, sizeof(buf), "%u.%09u", sec, nsec);
return std::string(buf);
}
} // namespace vslam