Files
vslam_cpp/libs/vslam_drivers/src/gamepad.cc
trung09122002 f17dbdce2b update
2026-09-22 17:18:02 +07:00

413 lines
14 KiB
C++

// 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].
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
// Kep ve [-1, 1], KHONG dao dau. Xem gamepad.h: da thu dao va robot that cho
// thay nguoc ca hai truc.
//
// Kep can that: int16 nho nhat la -32768, chia 32767 ra -1.00003.
double NormalizeJoydevAxis(int16_t raw) {
const double v = static_cast<double>(raw) * kAxisScale;
return std::max(-1.0, std::min(1.0, v));
}
// ---------------------------------------------------------------------------
// 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.
// Do bang probe tren tay cam nay: coc nghi o -1.0, bop len +1.0. Xem
// gamepad.h truoc khi doi chieu so sanh nay.
if (cfg_.lt_stop && s.Axis(cfg_.axis_lt) > cfg_.lt_press_above) {
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 ----------------------------------------------------------------
double lin_axis =
PickLarger(s.Axis(cfg_.axis_linear), s.Axis(cfg_.axis_linear_dpad));
double ang_axis =
PickLarger(s.Axis(cfg_.axis_angular), s.Axis(cfg_.axis_angular_dpad));
// Dao dau o DAY, sau khi da chon giua can gat va D-pad: hai nguon do cung
// mot truc logic nen phai chiu cung mot phep dao.
if (cfg_.invert_linear) lin_axis = -lin_axis;
if (cfg_.invert_angular) ang_axis = -ang_axis;
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);
}
// ⚠️ KEP LAI SAU CU KICH -- base_kit KHONG lam buoc nay.
//
// Ben do cu kich la lenh cuoi cung, nen no VUOT duoc tran vua kep o tren.
// Voi so cua base_kit dieu do khong bao gio lo ra: tran 0.5, che do cham con
// 0.25, van tren muc kich 0.2. Nhung dat `max_linear_speed: 0.35` cho khop
// tran that cua robot nay thi che do cham con 0.175 -- va cu kich day len
// 0.2, tuc nut LB "chay cham" lai NHANH HON tran cua chinh no.
//
// O moi cau hinh ma base_kit thuc su dung, hai ban cho ket qua giong het.
linear = Clamp(linear, cfg_.max_linear_speed * lin_mult);
angular = Clamp(angular, cfg_.max_angular_speed * ang_mult);
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>(NormalizeJoydevAxis(ev.value));
}
} 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