Scoping out API

This commit is contained in:
2025-03-07 14:24:30 -06:00
parent 54355f07bc
commit 53cf0641b4
4 changed files with 172 additions and 9 deletions

106
src/jstick.cpp Normal file
View File

@@ -0,0 +1,106 @@
#include <jstick.hpp>
#include <linux/joystick.h>
#include <cstddef>
#include <cstdio>
#include <format>
#include <filesystem>
#include <unistd.h>
#include <bits/fs_fwd.h>
int js_handle;
bool js_connected;
struct axis_state {
short x, y;
};
/// Reads a joystick event from the joystick device.
/// @returns 0 on success. Otherwise -1 is returned.
int read_event(int fd, struct js_event *event) {
ssize_t bytes;
bytes = read(fd, event, sizeof(*event));
if (bytes == sizeof(*event))
return 0;
/// Error, could not read full event.
return -1;
}
bool jstick::JoystickDetected(int jsHandle) {
return std::filesystem::exists(std::format("/dev/input/js{}", jsHandle));
}
int jstick::NumJoysticksDetected() {
int max = 4;
for (int i = 0; i < max; i++) {
if (!JoystickDetected(i))
return i;
}
return max;
}
void jstick::JoystickServiceUpdate() {
bool has = JoystickDetected();
}
void ProcessButtonEvent(uint8_t button_index, bool value) {
}
void ProcessAxisEvent(uint8_t axis, short x, short y) {
}
/// Keeps track of the current axis state.
/// @note This function assumes that axes are numbered starting from 0, and that
/// the X axis is an even number, and the Y axis is an odd number. However, this
/// is usually a safe assumption.
/// @returns the axis that the event indicated.
size_t get_axis_state(struct js_event *event, struct axis_state axes[3])
{
size_t axis = event->number / 2;
if (axis < 3)
{
if (event->number % 2 == 0)
axes[axis].x = event->value;
else
axes[axis].y = event->value;
}
return axis;
}
struct js_event event;
struct axis_state axes[3] = {0};
size_t axis;
void jstick::ReadEventLoop() {
while (read_event(js_handle, &event) == 0) {
switch (event.type) {
case JS_EVENT_BUTTON:
ProcessButtonEvent(event.number, event.value ? true : false);
break;
case JS_EVENT_AXIS:
axis = get_axis_state(&event, axes);
if (axis < 3)
ProcessAxisEvent(axis, axes[axis].x, axes[axis].y);
break;
case JS_EVENT_INIT:
default:
break;
}
fflush(stdout);
}
}