upload
This commit is contained in:
345
libs/vslam_common/include/vslam/approx_sync.h
Normal file
345
libs/vslam_common/include/vslam/approx_sync.h
Normal 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
|
||||
92
libs/vslam_common/include/vslam/buffer_pool.h
Normal file
92
libs/vslam_common/include/vslam/buffer_pool.h
Normal 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
|
||||
247
libs/vslam_common/include/vslam/channel.h
Normal file
247
libs/vslam_common/include/vslam/channel.h
Normal 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
|
||||
92
libs/vslam_common/include/vslam/clock.h
Normal file
92
libs/vslam_common/include/vslam/clock.h
Normal 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
|
||||
134
libs/vslam_common/include/vslam/config.h
Normal file
134
libs/vslam_common/include/vslam/config.h
Normal 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
|
||||
108
libs/vslam_common/include/vslam/geometry.h
Normal file
108
libs/vslam_common/include/vslam/geometry.h
Normal 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
|
||||
40
libs/vslam_common/include/vslam/json_parse.h
Normal file
40
libs/vslam_common/include/vslam/json_parse.h
Normal 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
|
||||
98
libs/vslam_common/include/vslam/log.h
Normal file
98
libs/vslam_common/include/vslam/log.h
Normal 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
|
||||
98
libs/vslam_common/include/vslam/node_constants.h
Normal file
98
libs/vslam_common/include/vslam/node_constants.h
Normal 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
|
||||
112
libs/vslam_common/include/vslam/robot_model.h
Normal file
112
libs/vslam_common/include/vslam/robot_model.h
Normal 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
|
||||
125
libs/vslam_common/include/vslam/stats.h
Normal file
125
libs/vslam_common/include/vslam/stats.h
Normal 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
|
||||
144
libs/vslam_common/include/vslam/teleop_model.h
Normal file
144
libs/vslam_common/include/vslam/teleop_model.h
Normal 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
|
||||
169
libs/vslam_common/include/vslam/transform_tree.h
Normal file
169
libs/vslam_common/include/vslam/transform_tree.h
Normal 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
|
||||
197
libs/vslam_common/include/vslam/unix_time.h
Normal file
197
libs/vslam_common/include/vslam/unix_time.h
Normal 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
|
||||
272
libs/vslam_common/include/vslam/vslam_common.h
Normal file
272
libs/vslam_common/include/vslam/vslam_common.h
Normal 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
|
||||
Reference in New Issue
Block a user