ohmu
·
2026-10-15
1#include "gamepad.h"
2#include "common/io.h"
3
4#include <stdio.h>
5#include <fcntl.h>
6#include <usbhid.h>
7
8#if __has_include(<dev/usb/usb_ioctl.h>)
9 #include <dev/usb/usb_ioctl.h> // FreeBSD
10#else
11 #include <bus/u4b/usb_ioctl.h> // DragonFly
12#endif
13
14#define MAX_UHID_JOYS 64
15
16const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) {
17 char path[16];
18 for (int i = 0; i < MAX_UHID_JOYS; i++) {
19 snprintf(path, ARRAY_SIZE(path), "/dev/uhid%d", i);
20 FF_AUTO_CLOSE_FD int fd = open(path, O_RDONLY | O_CLOEXEC);
21 if (fd < 0) {
22 if (errno == ENOENT) {
23 break; // No more devices
24 }
25 continue; // Device not found
26 }
27 report_desc_t repDesc = hid_get_report_desc(fd);
28 if (!repDesc) {
29 continue;
30 }
31
32 int reportId = hid_get_report_id(fd);
33
34 struct hid_data* hData = hid_start_parse(repDesc, 0, reportId);
35 if (hData) {
36 struct hid_item hItem;
37 while (hid_get_item(hData, &hItem) > 0) {
38 if (HID_PAGE(hItem.usage) != 1) {
39 continue;
40 }
41 switch (HID_USAGE(hItem.usage)) {
42 case 1: // Pointer. FreeBSD returns 1 for my Pro Controller for some reason
43 case 4: // Joystick
44 case 5: // Gamepad
45 break;
46 default:
47 continue;
48 }
49
50 struct usb_device_info di;
51 if (ioctl(fd, USB_GET_DEVICEINFO, &di) != -1) {
52 FFGamepadDevice* device = FF_LIST_ADD(FFGamepadDevice, *devices);
53 ffStrbufInitS(&device->serial, di.udi_serial);
54 ffStrbufInitF(&device->name, "%s %s", di.udi_vendor, di.udi_product);
55 device->battery = 0;
56 }
57 }
58 hid_end_parse(hData);
59 }
60
61 hid_dispose_report_desc(repDesc);
62 }
63
64 return nullptr;
65}