81 lines
2.4 KiB
C++
81 lines
2.4 KiB
C++
#include "joystick-reader.h"
|
|
#include <iostream>
|
|
#include <thread>
|
|
#include <chrono>
|
|
|
|
JoystickReader::JoystickReader()
|
|
: joystick(nullptr) {}
|
|
|
|
JoystickReader::~JoystickReader() {
|
|
if (joystick) {
|
|
SDL_JoystickClose(joystick);
|
|
}
|
|
SDL_Quit();
|
|
}
|
|
|
|
bool JoystickReader::initialize() {
|
|
if (SDL_Init(SDL_INIT_JOYSTICK) < 0) {
|
|
std::cerr << "SDL initialization failed: " << SDL_GetError() << std::endl;
|
|
return false;
|
|
}
|
|
|
|
int numJoysticks = SDL_NumJoysticks();
|
|
if (numJoysticks < 1) {
|
|
std::cerr << "No joysticks found" << std::endl;
|
|
return false;
|
|
}
|
|
|
|
std::cout << "Found " << numJoysticks << " joystick(s)" << std::endl;
|
|
|
|
// Открываем первый джойстик
|
|
joystick = SDL_JoystickOpen(0);
|
|
if (!joystick) {
|
|
std::cerr << "Failed to open joystick: " << SDL_GetError() << std::endl;
|
|
return false;
|
|
}
|
|
|
|
joystickName = SDL_JoystickName(joystick);
|
|
std::cout << "Opened joystick: " << joystickName << std::endl;
|
|
std::cout << "Axes: " << SDL_JoystickNumAxes(joystick)
|
|
<< ", Buttons: " << SDL_JoystickNumButtons(joystick)
|
|
<< ", Balls: " << SDL_JoystickNumBalls(joystick)
|
|
<< ", Hats: " << SDL_JoystickNumHats(joystick) << std::endl;
|
|
|
|
return true;
|
|
}
|
|
|
|
bool JoystickReader::readData(std::vector<uint16_t>& data) {
|
|
if (!joystick) return false;
|
|
if (SDL_JoystickGetAttached(joystick) != SDL_TRUE) { return false; }
|
|
|
|
SDL_JoystickUpdate();
|
|
|
|
data.resize(24); // Заполняем нейтральным значением
|
|
for (auto& i: data) { i = 1500; }
|
|
|
|
int axes = std::min(SDL_JoystickNumAxes(joystick), 8);
|
|
for (int i = 0; i < std::min(8, axes); ++i) {
|
|
Sint16 axisValue = SDL_JoystickGetAxis(joystick, i);
|
|
// Преобразуем из [-32768, 32767] в [1000, 2000]
|
|
data[i] = static_cast<uint16_t>((axisValue + 32768) * 1000 / 65536 + 1000);
|
|
}
|
|
axes = 8;
|
|
|
|
// Читаем кнопки
|
|
int buttons = SDL_JoystickNumButtons(joystick);
|
|
for (int i = 0; i < buttons && i < data.size() - axes; ++i) {
|
|
auto buttonState = SDL_JoystickGetButton(joystick, i);
|
|
data[axes + i] = static_cast<uint16_t>(1000.0 + (buttonState * (1000.0 / 255.0)));
|
|
}
|
|
|
|
for (auto& i: data) {
|
|
if (i < 950) i = 950;
|
|
if (i > 2050) i = 2050;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
std::string JoystickReader::getJoystickName() const {
|
|
return joystickName;
|
|
}
|