update
This commit is contained in:
@@ -10,6 +10,7 @@ vslam_add_library(vslam_drivers
|
||||
PUBLIC_HDRS
|
||||
driver_config.h
|
||||
driver_interfaces.h
|
||||
gamepad.h
|
||||
scan_sanitizer.h
|
||||
clock_sync.h
|
||||
mcu_protocol.h
|
||||
|
||||
235
libs/vslam_drivers/include/vslam/gamepad.h
Normal file
235
libs/vslam_drivers/include/vslam/gamepad.h
Normal file
@@ -0,0 +1,235 @@
|
||||
#ifndef VSLAM_GAMEPAD_H
|
||||
#define VSLAM_GAMEPAD_H
|
||||
|
||||
// Tay cam lai tay -- Logitech F710/F310 o mode XInput, qua joydev.
|
||||
//
|
||||
// ================== NGUON GOC ==================
|
||||
// Port 1-1 tu `base_kit/src/joy_control/src/joy_control_node.cpp`, ban dang
|
||||
// chay that tren chinh con robot nay. MOI hang so o day deu co mot dong tuong
|
||||
// ung ben do, va cho nao lech thi duoc ghi ro la lech vi cai gi.
|
||||
//
|
||||
// GIU NGUYEN cam giac lai: he so turbo/slow, cach chon giua can gat va D-pad,
|
||||
// cong thuc deadzone, cu kich toc do toi thieu de thang ma sat tinh, va luat
|
||||
// "gui 0 trong 1.5 giay roi IM de nhuong nguon nhap khac". Bon thu do da duoc
|
||||
// chinh tren robot that; viet lai cho "dep" la vut het cong chinh do di.
|
||||
//
|
||||
// ================== VI SAO KHONG NAM TRONG driver_interfaces.h ==================
|
||||
// Cac interface ben do ton tai de ReplaySource thay the duoc driver that --
|
||||
// do la diem tua cua chien luoc kiem chung. Tay cam KHONG thuoc nhom do: no la
|
||||
// dau vao cua NGUOI VAN HANH, khong phai du lieu cam bien. Phat lai mot ban
|
||||
// ghi ma trong do co ai do dang gat can la dieu KHONG duoc phep xay ra.
|
||||
//
|
||||
// ================== HAI LOP, TACH HAN ==================
|
||||
// GamepadReader -- doc joydev tren luong rieng, CHI nuoi trang thai tho.
|
||||
// GamepadMapper -- THUAN, khong I/O: trang thai tho -> van toc. Test duoc
|
||||
// khong can tay cam, va do la noi toan bo logic nam.
|
||||
//
|
||||
// ================== BAY CUA joydev ==================
|
||||
// joydev CHI gui event khi gia tri DOI. Giu can gat dung yen = khong co event
|
||||
// nao suot ca phut. Ben ROS, `joy_node` che bay nay bang `autorepeat_rate: 50`
|
||||
// (teleop_all.launch.py). O day khong co joy_node, nen NGUOI DOC phai tu bom
|
||||
// lai: `GamepadLoop()` chay 50 Hz va ghi `raw_cmd_` moi vong. Khong lam vay
|
||||
// thi `raw_cmd_stamp_` cu dan va SafetyMonitor ban NO_CMD (cmd_timeout 0.5 s)
|
||||
// dung xe GIUA LUC nguoi lai dang giu can gat.
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "vslam/clock.h"
|
||||
#include "vslam/vslam_common.h"
|
||||
|
||||
namespace vslam {
|
||||
|
||||
// Mac dinh lay tu teleop_all.launch.py + joy_control_node.cpp cua base_kit.
|
||||
// Moi index deu la CAU HINH: bo tay cam khac tra ve layout khac, va sua mot
|
||||
// dong YAML re hon build lai. Dung `vslam_joy_probe` de do index that.
|
||||
struct GamepadConfig {
|
||||
bool enabled = false;
|
||||
std::string device = "/dev/input/js0";
|
||||
|
||||
// = `autorepeat_rate` cua joy_node. Xem bay joydev o dau file.
|
||||
double publish_rate_hz = 50.0;
|
||||
|
||||
// ⚠️ Tran cua RIENG tay cam, giong tham so cua node ROS. robot.yaml
|
||||
// (base.max_linear 0.35) va safety.yaml (max_linear 0.35) van kep lan nua o
|
||||
// duoi, nen de 0.5 o day KHONG lam robot chay 0.5 -- turbo se bao hoa o
|
||||
// 0.35. Giu nguyen so cua base_kit de con doi chieu duoc hai ben.
|
||||
double max_linear_speed = 0.5;
|
||||
double max_angular_speed = 1.0;
|
||||
|
||||
double deadzone = 0.05;
|
||||
|
||||
// --- Ma sat tinh cua dong co -- joy_control_node.cpp:240-250 ---
|
||||
//
|
||||
// Ban phim nhay thang len 0.5 nen xe chay ngay; can gat tang dan tu 0.01 nen
|
||||
// dong co khong thang noi ma sat tinh va nguoi lai tuong tay cam bi tre.
|
||||
// Cu kich nay lam can gat "bat" ngay khi nhich khoi vung chet.
|
||||
//
|
||||
// ⚠️ TREN ROBOT NAY TRAN THAP HON base_kit: 0.2 tren tran 0.5 la 40% dai,
|
||||
// nhung tren tran 0.35 la 57% -- can gat gan nhu thanh cong tac, mat het
|
||||
// dai bo cham. Muon giu dung ti le 40% thi dat 0.14.
|
||||
double min_linear_kick = 0.2;
|
||||
double min_angular_kick = 0.4;
|
||||
|
||||
// Gui 0 bao lau sau khi nha can, roi IM han. joy_control_node.cpp:259.
|
||||
// "Im" la co y: no nhuong quyen lai cho nguon nhap khac (o base_kit la ban
|
||||
// phim; o day la joystick tren web).
|
||||
double idle_publish_sec = 1.5;
|
||||
|
||||
// Thay cho `exit(1)` + systemd Restart cua base_kit. Xem ghi chu o
|
||||
// GamepadReader.
|
||||
double reopen_period_sec = 1.0;
|
||||
|
||||
// He so khi giu RB / LB. joy_control_node.cpp:212-218.
|
||||
double turbo_linear = 2.0;
|
||||
double turbo_angular = 0.5; // quay CHAM lai khi chay nhanh, de khong gat
|
||||
double slow_linear = 0.5;
|
||||
double slow_angular = 0.5;
|
||||
|
||||
// --- Index, layout F710/F310 XInput ---
|
||||
int axis_linear = 1; // can trai Y
|
||||
int axis_linear_dpad = 7; // D-pad Y
|
||||
int axis_angular = 3; // can phai X
|
||||
int axis_angular_dpad = 6; // D-pad X
|
||||
int button_enable = 7; // Start -- BAT/TAT dieu khien
|
||||
int button_zero = 1; // B -- ve 0 ngay
|
||||
int button_turbo = 5; // RB
|
||||
int button_slow = 4; // LB
|
||||
|
||||
// Header cua base_kit hua "LT (axis 2): Emergency stop - HOLD to stop"
|
||||
// nhung code KHONG he doc truc do. Cai dat o day, va de TAT mac dinh dung
|
||||
// bang hanh vi that cua base_kit.
|
||||
//
|
||||
// ⚠️ Coc XInput NGHI o +1.0 va bam ve -1.0, KHONG phai 0. Nhung truoc lan
|
||||
// bam dau tien joydev tra ve 0.0 -- nen nguong phai la "< 0" chu khong phai
|
||||
// "khac 1", neu khong thi vua cam tay vao la xe dung cung.
|
||||
//
|
||||
// KHONG chot e-stop cua he thong: go e-stop bat buoc co token (xem
|
||||
// system.yaml web), nen mot cu va nham vao coc se khoa robot lai cho toi khi
|
||||
// co nguoi mo trinh duyet. Day chi la "giu de dung", dung nhu header hua.
|
||||
bool lt_stop = false;
|
||||
int axis_lt = 2;
|
||||
double lt_press_below = 0.0;
|
||||
};
|
||||
|
||||
// Anh chup trang thai tho. Index NGOAI KHOANG tra 0 / false thay vi doc ra
|
||||
// ngoai vector.
|
||||
//
|
||||
// ⚠️ Day chinh la cho base_kit sap: `msg->buttons[7]` va `msg->axes[7]` duoc
|
||||
// doc THANG, khong kiem `.size()` (joy_control_node.cpp:180, 223). Bo tay cam
|
||||
// bao it truc/nut hon la doc ra ngoai vector -- UB, va tren tay PS thi so truc
|
||||
// khac that.
|
||||
struct GamepadState {
|
||||
bool connected = false;
|
||||
std::vector<float> axes;
|
||||
std::vector<uint8_t> buttons;
|
||||
|
||||
double Axis(int i) const {
|
||||
if (i < 0 || static_cast<size_t>(i) >= axes.size()) return 0.0;
|
||||
return static_cast<double>(axes[i]);
|
||||
}
|
||||
bool Button(int i) const {
|
||||
if (i < 0 || static_cast<size_t>(i) >= buttons.size()) return false;
|
||||
return buttons[i] != 0;
|
||||
}
|
||||
};
|
||||
|
||||
struct GamepadCommand {
|
||||
// Co nen GHI `raw_cmd_` vong nay khong. false = im, nhuong nguon khac.
|
||||
bool publish = false;
|
||||
double linear = 0.0;
|
||||
double angular = 0.0;
|
||||
|
||||
bool enabled = false; // trang thai toggle cua nut Start
|
||||
double linear_mult = 1.0; // de log, giong dong log cua base_kit
|
||||
double angular_mult = 1.0;
|
||||
|
||||
// Chuyen trang thai, chi de LOG. Mapper khong tu log: no thuan.
|
||||
bool enabled_changed = false;
|
||||
bool connected_changed = false;
|
||||
};
|
||||
|
||||
// Tho -> van toc. THUAN: khong doc dong ho, khong doc file, khong log.
|
||||
// Moc thoi gian do nguoi goi truyen vao, nen test lai duoc dung chuoi su kien.
|
||||
class GamepadMapper {
|
||||
public:
|
||||
explicit GamepadMapper(const GamepadConfig& cfg);
|
||||
|
||||
// `now` chi dung cho cua so idle 1.5 s.
|
||||
GamepadCommand Step(const GamepadState& s, UnixTime now);
|
||||
|
||||
bool enabled() const { return enabled_; }
|
||||
|
||||
// Cong thuc deadzone cua base_kit: cat o nguong roi GIAN LAI phan con lai ra
|
||||
// ca dai [0, 1], de ngay sau vung chet khong bi nhay bac.
|
||||
double ApplyDeadzone(double v) const;
|
||||
|
||||
private:
|
||||
GamepadConfig cfg_;
|
||||
|
||||
bool enabled_ = false;
|
||||
bool enable_pressed_ = false; // chong dap phim, = start_pressed_ ben kia
|
||||
bool was_connected_ = false;
|
||||
bool have_active_ = false; // da tung co lenh chuyen dong
|
||||
UnixTime last_active_;
|
||||
};
|
||||
|
||||
// Doc joydev tren luong rieng.
|
||||
//
|
||||
// ================== KHONG exit(1) ==================
|
||||
// base_kit goi `exit(1)` khi mat tay cam (joy_control_node.cpp:145) va de
|
||||
// systemd dung lai node. O do dieu do an toan: no la mot tien trinh ROS rieng.
|
||||
//
|
||||
// O day `vslam_node` la MOT tien trinh giu ca SLAM, EKF, web va luong safety.
|
||||
// Rut day tay cam ma giet tien trinh nghia la robot mat vong an toan giua luc
|
||||
// dang chay. Thay bang: danh dau mat ket noi, de GamepadMapper tat dieu khien
|
||||
// (giong het hanh vi sau timeout cua base_kit -- phai bam Start lai), va thu
|
||||
// mo lai thiet bi moi `reopen_period_sec`.
|
||||
class GamepadReader {
|
||||
public:
|
||||
GamepadReader(const GamepadConfig& cfg, ClockPtr clock);
|
||||
~GamepadReader();
|
||||
|
||||
GamepadReader(const GamepadReader&) = delete;
|
||||
GamepadReader& operator=(const GamepadReader&) = delete;
|
||||
|
||||
// Bat luong doc. Chua cam tay cam KHONG phai la loi chet: tra ve
|
||||
// kUnavailable de nguoi goi log WARN, nhung luong van chay va van thu mo
|
||||
// lai. Tu choi khoi dong ca node vi thieu tay cam la sai.
|
||||
StatusResponse Open();
|
||||
void Close();
|
||||
|
||||
GamepadState Snapshot() const;
|
||||
|
||||
// Ten thiet bi + so truc/nut, lay luc mo duoc. Do la thu DUY NHAT noi cho
|
||||
// nguoi van hanh biet layout index co khop config khong.
|
||||
std::string DeviceInfo() const;
|
||||
|
||||
private:
|
||||
void ReadLoop();
|
||||
bool TryOpen();
|
||||
void Drop(const std::string& why);
|
||||
|
||||
GamepadConfig cfg_;
|
||||
ClockPtr clock_;
|
||||
|
||||
int fd_ = -1;
|
||||
// atomic: Close() ghi tu luong goi, ReadLoop doc moi vong. Mot bool thuong o
|
||||
// day la data race that, va ThreadSanitizer cua repo nay se bat dung no.
|
||||
std::atomic<bool> running_{false};
|
||||
std::thread thread_;
|
||||
|
||||
mutable std::mutex mu_;
|
||||
GamepadState state_;
|
||||
std::string info_;
|
||||
bool warned_missing_ = false;
|
||||
};
|
||||
|
||||
} // namespace vslam
|
||||
|
||||
#endif // VSLAM_GAMEPAD_H
|
||||
384
libs/vslam_drivers/src/gamepad.cc
Normal file
384
libs/vslam_drivers/src/gamepad.cc
Normal file
@@ -0,0 +1,384 @@
|
||||
// Tay cam lai tay. Xem gamepad.h truoc khi sua bat cu gi o day -- moi hang so
|
||||
// deu co mot dong tuong ung trong base_kit/src/joy_control.
|
||||
|
||||
#include "vslam/gamepad.h"
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <linux/joystick.h>
|
||||
#include <poll.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
|
||||
#include "vslam/log.h"
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
// Gia tri truc cua joydev la int16. Chia cho 32767 ra [-1, 1], dung he so ma
|
||||
// `joy_node` cua ROS dung -- de hai ben cho cung con so tren cung tay cam.
|
||||
constexpr double kAxisScale = 1.0 / 32767.0;
|
||||
|
||||
// Cho poll() truoc khi ngo lai co running_. Du ngan de Close() khong treo,
|
||||
// du dai de khong quay tit CPU.
|
||||
constexpr int kPollTimeoutMs = 100;
|
||||
|
||||
// Chon trong hai truc cai nao dang duoc gat manh hon.
|
||||
// joy_control_node.cpp:223 va :229 -- can gat va D-pad dung chung mot duong,
|
||||
// khong cong vao nhau.
|
||||
double PickLarger(double a, double b) {
|
||||
return (std::abs(a) > std::abs(b)) ? a : b;
|
||||
}
|
||||
|
||||
double Clamp(double v, double limit) {
|
||||
const double l = std::abs(limit);
|
||||
return std::max(-l, std::min(l, v));
|
||||
}
|
||||
|
||||
// Nang do lon len toi thieu `floor`, giu nguyen dau. Khong dung khi v == 0:
|
||||
// khong co dau nao de giu, va "dang dung yen" khong phai truong hop can thang
|
||||
// ma sat tinh.
|
||||
double LiftMagnitude(double v, double floor) {
|
||||
if (floor <= 0.0 || v == 0.0) return v;
|
||||
if (v > 0.0 && v < floor) return floor;
|
||||
if (v < 0.0 && v > -floor) return -floor;
|
||||
return v;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GamepadMapper -- THUAN
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
GamepadMapper::GamepadMapper(const GamepadConfig& cfg) : cfg_(cfg) {}
|
||||
|
||||
double GamepadMapper::ApplyDeadzone(double value) const {
|
||||
// joy_control_node.cpp:157-164, giu nguyen cong thuc.
|
||||
if (std::abs(value) < cfg_.deadzone) return 0.0;
|
||||
const double sign = (value > 0.0) ? 1.0 : -1.0;
|
||||
const double span = 1.0 - cfg_.deadzone;
|
||||
if (span <= 1e-9) return sign;
|
||||
return sign * (std::abs(value) - cfg_.deadzone) / span;
|
||||
}
|
||||
|
||||
GamepadCommand GamepadMapper::Step(const GamepadState& s, UnixTime now) {
|
||||
GamepadCommand out;
|
||||
|
||||
// --- Mat ket noi ---------------------------------------------------------
|
||||
// Tuong duong nhanh timeout cua base_kit (joy_control_node.cpp:327-331): tat
|
||||
// dieu khien, bat nguoi lai bam Start lai sau khi cam lai. KHAC mot cho:
|
||||
// base_kit goi exit(1) o day, xem ghi chu trong gamepad.h.
|
||||
if (!s.connected) {
|
||||
if (was_connected_) {
|
||||
out.connected_changed = true;
|
||||
if (enabled_) out.enabled_changed = true;
|
||||
enabled_ = false;
|
||||
enable_pressed_ = false;
|
||||
was_connected_ = false;
|
||||
}
|
||||
out.enabled = false;
|
||||
// Van gui 0 trong cua so idle: rut day giua luc dang chay thi lenh cuoi
|
||||
// cung phai duoc don, chu khong de SafetyMonitor cho het NO_CMD.
|
||||
if (have_active_ && SecondsBetween(now, last_active_) < cfg_.idle_publish_sec) {
|
||||
out.publish = true;
|
||||
} else {
|
||||
have_active_ = false;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
if (!was_connected_) {
|
||||
was_connected_ = true;
|
||||
out.connected_changed = true;
|
||||
}
|
||||
|
||||
// --- Nut Start: BAT/TAT dieu khien --------------------------------------
|
||||
// joy_control_node.cpp:180-194. Chong dap phim bang co canh len.
|
||||
if (s.Button(cfg_.button_enable)) {
|
||||
if (!enable_pressed_) {
|
||||
enable_pressed_ = true;
|
||||
enabled_ = !enabled_;
|
||||
out.enabled_changed = true;
|
||||
if (!enabled_) {
|
||||
// ⚠️ LECH base_kit MOT CHUT, co y.
|
||||
//
|
||||
// Ben do, tat dieu khien xong thi node IM luon (dong publish bi comment
|
||||
// lai de "nhuong ban phim"), va xe dung nho cmd_timeout 0.5 s cua
|
||||
// Zlac. O day ta don lenh ve 0 trong cua so idle 1.5 s -- dung duong
|
||||
// ma cu nha can gat da di. Chan hon, va van im sau 1.5 s nen joystick
|
||||
// tren web khong bi cuop quyen.
|
||||
last_active_ = now;
|
||||
have_active_ = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
enable_pressed_ = false;
|
||||
}
|
||||
out.enabled = enabled_;
|
||||
|
||||
// --- Nut B: ve 0 ngay ----------------------------------------------------
|
||||
// joy_control_node.cpp:197-201. Chay BAT KE dang bat hay tat.
|
||||
if (s.Button(cfg_.button_zero)) {
|
||||
out.publish = true;
|
||||
out.linear = 0.0;
|
||||
out.angular = 0.0;
|
||||
have_active_ = false;
|
||||
return out;
|
||||
}
|
||||
|
||||
// --- Coc LT: giu de dung -------------------------------------------------
|
||||
// Thu ma header base_kit hua nhung code khong co. Mac dinh TAT.
|
||||
if (cfg_.lt_stop && s.Axis(cfg_.axis_lt) < cfg_.lt_press_below) {
|
||||
out.publish = true;
|
||||
out.linear = 0.0;
|
||||
out.angular = 0.0;
|
||||
last_active_ = now;
|
||||
have_active_ = true;
|
||||
return out;
|
||||
}
|
||||
|
||||
if (!enabled_) {
|
||||
// joy_control_node.cpp:204-206: chua bat thi khong xu ly chuyen dong.
|
||||
// Van con cua so idle de don not lenh cuoi.
|
||||
if (have_active_ && SecondsBetween(now, last_active_) < cfg_.idle_publish_sec) {
|
||||
out.publish = true;
|
||||
} else {
|
||||
have_active_ = false;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// --- He so turbo / slow --------------------------------------------------
|
||||
// joy_control_node.cpp:208-218. Phai VUA GIU nut VUA gat can moi an.
|
||||
double lin_mult = 1.0;
|
||||
double ang_mult = 1.0;
|
||||
if (s.Button(cfg_.button_turbo)) {
|
||||
lin_mult = cfg_.turbo_linear;
|
||||
ang_mult = cfg_.turbo_angular;
|
||||
} else if (s.Button(cfg_.button_slow)) {
|
||||
lin_mult = cfg_.slow_linear;
|
||||
ang_mult = cfg_.slow_angular;
|
||||
}
|
||||
out.linear_mult = lin_mult;
|
||||
out.angular_mult = ang_mult;
|
||||
|
||||
// --- Truc ----------------------------------------------------------------
|
||||
const double lin_axis =
|
||||
PickLarger(s.Axis(cfg_.axis_linear), s.Axis(cfg_.axis_linear_dpad));
|
||||
const double ang_axis =
|
||||
PickLarger(s.Axis(cfg_.axis_angular), s.Axis(cfg_.axis_angular_dpad));
|
||||
|
||||
double linear = ApplyDeadzone(lin_axis) * cfg_.max_linear_speed * lin_mult;
|
||||
double angular = ApplyDeadzone(ang_axis) * cfg_.max_angular_speed * ang_mult;
|
||||
|
||||
// Kep theo tran DA NHAN he so, khong theo tran co ban: turbo duoc phep vuot
|
||||
// nguong thuong. joy_control_node.cpp:236-238.
|
||||
linear = Clamp(linear, cfg_.max_linear_speed * lin_mult);
|
||||
angular = Clamp(angular, cfg_.max_angular_speed * ang_mult);
|
||||
|
||||
// --- Ma sat tinh ---------------------------------------------------------
|
||||
// joy_control_node.cpp:243-250. Nguong xet la TRUC THO, khong phai van toc
|
||||
// da tinh: nguoi lai nhich can la phai co luc, bat ke he so dang la bao nhieu.
|
||||
if (std::abs(lin_axis) > cfg_.deadzone) {
|
||||
linear = LiftMagnitude(linear, cfg_.min_linear_kick);
|
||||
}
|
||||
if (std::abs(ang_axis) > cfg_.deadzone) {
|
||||
angular = LiftMagnitude(angular, cfg_.min_angular_kick);
|
||||
}
|
||||
|
||||
const bool idle = (linear == 0.0 && angular == 0.0);
|
||||
if (!idle) {
|
||||
last_active_ = now;
|
||||
have_active_ = true;
|
||||
out.publish = true;
|
||||
out.linear = linear;
|
||||
out.angular = angular;
|
||||
return out;
|
||||
}
|
||||
|
||||
// --- Idle: gui 0 trong 1.5 s roi IM --------------------------------------
|
||||
// joy_control_node.cpp:255-267. Cai "im" moi la phan quan trong: no tra
|
||||
// quyen lai cho nguon nhap khac (ben do la ban phim, o day la joystick web).
|
||||
if (have_active_ && SecondsBetween(now, last_active_) < cfg_.idle_publish_sec) {
|
||||
out.publish = true;
|
||||
out.linear = 0.0;
|
||||
out.angular = 0.0;
|
||||
} else {
|
||||
have_active_ = false;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GamepadReader -- joydev
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
GamepadReader::GamepadReader(const GamepadConfig& cfg, ClockPtr clock)
|
||||
: cfg_(cfg), clock_(std::move(clock)) {}
|
||||
|
||||
GamepadReader::~GamepadReader() { Close(); }
|
||||
|
||||
bool GamepadReader::TryOpen() {
|
||||
const int fd = ::open(cfg_.device.c_str(), O_RDONLY | O_NONBLOCK);
|
||||
if (fd < 0) {
|
||||
if (!warned_missing_) {
|
||||
// MOT lan thoi. Thu lai moi giay ma log moi giay thi log thanh vo dung.
|
||||
VSLAM_WARN("gamepad: khong mo duoc " << cfg_.device << " ("
|
||||
<< std::strerror(errno) << ") -- se thu lai moi "
|
||||
<< cfg_.reopen_period_sec << " s");
|
||||
warned_missing_ = true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t n_axes = 0;
|
||||
uint8_t n_buttons = 0;
|
||||
char name[128] = {};
|
||||
if (::ioctl(fd, JSIOCGAXES, &n_axes) < 0) n_axes = 0;
|
||||
if (::ioctl(fd, JSIOCGBUTTONS, &n_buttons) < 0) n_buttons = 0;
|
||||
if (::ioctl(fd, JSIOCGNAME(sizeof(name)), name) < 0) {
|
||||
std::snprintf(name, sizeof(name), "(khong doc duoc ten)");
|
||||
}
|
||||
|
||||
fd_ = fd;
|
||||
warned_missing_ = false;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
state_.axes.assign(n_axes, 0.0f);
|
||||
state_.buttons.assign(n_buttons, 0);
|
||||
state_.connected = true;
|
||||
info_ = std::string(name) + ", " + std::to_string(n_axes) + " truc, " +
|
||||
std::to_string(n_buttons) + " nut";
|
||||
}
|
||||
|
||||
// In ra layout THAT. Config noi "can trai Y la axes[1]"; dong nay la cach
|
||||
// duy nhat de nguoi van hanh doi chieu ma khong phai doan.
|
||||
VSLAM_INFO("gamepad: mo " << cfg_.device << " -- " << info_
|
||||
<< ". Kiem index bang `vslam_joy_probe` neu lai thay nguoc.");
|
||||
return true;
|
||||
}
|
||||
|
||||
void GamepadReader::Drop(const std::string& why) {
|
||||
if (fd_ >= 0) {
|
||||
::close(fd_);
|
||||
fd_ = -1;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (!state_.connected) return;
|
||||
state_.connected = false;
|
||||
// Xoa trang thai: giu lai gia tri cuoi cung cua mot tay cam da rut ra la
|
||||
// cach de mot cu gat con sot lai "song day" sau khi cam lai.
|
||||
std::fill(state_.axes.begin(), state_.axes.end(), 0.0f);
|
||||
std::fill(state_.buttons.begin(), state_.buttons.end(), 0);
|
||||
}
|
||||
VSLAM_WARN("gamepad: MAT KET NOI (" << why << "). Dieu khien tat; cam lai "
|
||||
"roi bam Start de bat lai.");
|
||||
}
|
||||
|
||||
StatusResponse GamepadReader::Open() {
|
||||
if (running_) return StatusResponse::Ok();
|
||||
running_ = true;
|
||||
const bool ok = TryOpen();
|
||||
thread_ = std::thread([this] { ReadLoop(); });
|
||||
if (!ok) {
|
||||
return StatusResponse::Error(StatusCode::kUnavailable,
|
||||
"chua mo duoc " + cfg_.device);
|
||||
}
|
||||
return StatusResponse::Ok();
|
||||
}
|
||||
|
||||
void GamepadReader::Close() {
|
||||
if (!running_) return;
|
||||
running_ = false;
|
||||
if (thread_.joinable()) thread_.join();
|
||||
if (fd_ >= 0) {
|
||||
::close(fd_);
|
||||
fd_ = -1;
|
||||
}
|
||||
}
|
||||
|
||||
void GamepadReader::ReadLoop() {
|
||||
const auto reopen_period = std::chrono::duration_cast<Clock::SteadyPoint::duration>(
|
||||
std::chrono::duration<double>(cfg_.reopen_period_sec > 0.0
|
||||
? cfg_.reopen_period_sec
|
||||
: 1.0));
|
||||
// Open() vua thu mot lan roi, nen lan thu tiep theo cach mot chu ky -- khong
|
||||
// thu lai ngay o vong dau.
|
||||
Clock::SteadyPoint next_try = clock_->Steady() + reopen_period;
|
||||
|
||||
while (running_) {
|
||||
if (fd_ < 0) {
|
||||
// Cam nong. KHONG exit(1) nhu base_kit -- xem ghi chu o gamepad.h.
|
||||
if (clock_->Steady() < next_try) {
|
||||
clock_->SleepFor(std::chrono::milliseconds(kPollTimeoutMs));
|
||||
continue;
|
||||
}
|
||||
next_try = clock_->Steady() + reopen_period;
|
||||
TryOpen();
|
||||
continue;
|
||||
}
|
||||
|
||||
pollfd pfd{};
|
||||
pfd.fd = fd_;
|
||||
pfd.events = POLLIN;
|
||||
const int rc = ::poll(&pfd, 1, kPollTimeoutMs);
|
||||
if (rc < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
Drop(std::string("poll(): ") + std::strerror(errno));
|
||||
next_try = clock_->Steady() + reopen_period;
|
||||
continue;
|
||||
}
|
||||
if (rc == 0) continue; // khong co event -- binh thuong, xem bay joydev
|
||||
if ((pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) {
|
||||
Drop("thiet bi bien mat");
|
||||
next_try = clock_->Steady() + reopen_period;
|
||||
continue;
|
||||
}
|
||||
|
||||
js_event ev{};
|
||||
const ssize_t n = ::read(fd_, &ev, sizeof(ev));
|
||||
if (n < 0) {
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) continue;
|
||||
Drop(std::string("read(): ") + std::strerror(errno));
|
||||
next_try = clock_->Steady() + reopen_period;
|
||||
continue;
|
||||
}
|
||||
if (n != static_cast<ssize_t>(sizeof(ev))) continue;
|
||||
|
||||
// Bo co JS_EVENT_INIT nhung VAN ap gia tri: cac event do la trang thai
|
||||
// hien tai cua thiet bi luc vua mo, khong phai rac.
|
||||
const uint8_t type = ev.type & ~JS_EVENT_INIT;
|
||||
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (type == JS_EVENT_AXIS) {
|
||||
if (ev.number < state_.axes.size()) {
|
||||
state_.axes[ev.number] = static_cast<float>(ev.value * kAxisScale);
|
||||
}
|
||||
} else if (type == JS_EVENT_BUTTON) {
|
||||
if (ev.number < state_.buttons.size()) {
|
||||
state_.buttons[ev.number] = ev.value ? 1 : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GamepadState GamepadReader::Snapshot() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return state_;
|
||||
}
|
||||
|
||||
std::string GamepadReader::DeviceInfo() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return info_;
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
Reference in New Issue
Block a user