Compare commits
3 Commits
elso-phase
...
e973eb6adb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e973eb6adb | ||
|
|
29b23b5964 | ||
|
|
c42dff6384 |
84
README.md
84
README.md
@@ -1,62 +1,54 @@
|
|||||||
# Device Drivers
|
|
||||||
----------------------------------
|
|
||||||
|
|
||||||
This repository contains Linux **kernel modules** (``.ko``) that implement low-level USB input drivers and expose device events through the Linux **input subsystem** (evdev).
|
Device Driver
|
||||||
|
======================
|
||||||
|
|
||||||
A helper tool (``usb_driver_manager.py``) is included to make it easier to:
|
A collection of USB device drivers for Linux kernel, demonstrating how to interact with various USB HID devices.
|
||||||
- list USB devices and their **interfaces**
|
|
||||||
- load/unload (reload) a chosen ``.ko`` module
|
|
||||||
- unbind/bind a selected interface to a chosen driver during development
|
|
||||||
|
|
||||||
## Drivers
|
## Current Drivers
|
||||||
----------
|
|
||||||
|
|
||||||
### Mouse driver (``mouse/``)
|
### Mouse Driver (`mouse/`)
|
||||||
USB HID boot-protocol mouse driver.
|
A USB HID mouse driver that supports 16-bit coordinate tracking for high-DPI gaming mice. Tested with Cooler Master MM710.
|
||||||
|
|
||||||
**Build:**
|
**Features:**
|
||||||
|
- Left, right, middle, side, and extra button support
|
||||||
|
- 16-bit X/Y movement (high-speed tracking)
|
||||||
|
- Scroll wheel support
|
||||||
|
- Binds to HID Boot Protocol Mouse interfaces
|
||||||
|
|
||||||
|
**Building:**
|
||||||
```bash
|
```bash
|
||||||
cd mouse
|
cd mouse/
|
||||||
make
|
make
|
||||||
```
|
```
|
||||||
|
|
||||||
### Logitech G29 media driver (``g29_media_usb/``)
|
|
||||||
Logitech G29 driver that maps selected wheel inputs to media key events.
|
|
||||||
|
|
||||||
**Current mapping (Mode 0):**
|
|
||||||
- Red rotary clockwise / counter-clockwise -> Volume Up / Volume Down
|
|
||||||
- Return ("Enter") -> Play/Pause
|
|
||||||
- Plus / Minus -> Next track / Previous track
|
|
||||||
|
|
||||||
**Build:**
|
|
||||||
```bash
|
|
||||||
cd g29_media_usb
|
|
||||||
make
|
|
||||||
```
|
|
||||||
|
|
||||||
After building, the module (``*.ko``) is typically placed under ``build/`` by the provided Makefiles.
|
|
||||||
|
|
||||||
## USB Driver Manager
|
## USB Driver Manager
|
||||||
---------------------
|
|
||||||
|
|
||||||
**Usage examples:**
|
The `usb_driver_manager.py` tool simplifies the process of binding USB devices to custom drivers.
|
||||||
|
|
||||||
|
**Usage:**
|
||||||
```bash
|
```bash
|
||||||
# Search for modules in these driver directories (the tool searches recursively)
|
# Search for .ko files in current directory
|
||||||
sudo python3 usb_driver_manager.py ./mouse ./g29_media_usb
|
sudo python3 usb_driver_manager.py
|
||||||
|
|
||||||
# Or point directly at build/ directories
|
# Search in specific directories
|
||||||
sudo python3 usb_driver_manager.py ./mouse/build ./g29_media_usb/build
|
sudo python3 usb_driver_manager.py ./mouse ./keyboard
|
||||||
|
|
||||||
|
# The tool will:
|
||||||
|
# 1. List available USB HID devices
|
||||||
|
# 2. Show available kernel modules (.ko files)
|
||||||
|
# 3. Unbind the device from its current driver
|
||||||
|
# 4. Unload existing module (if already loaded)
|
||||||
|
# 5. Load the new module
|
||||||
|
# 6. Bind the device to the new driver
|
||||||
```
|
```
|
||||||
|
|
||||||
**Workflow:**
|
## Future Drivers
|
||||||
1. Select the USB device.
|
|
||||||
2. (Optional but recommended for non-mouse devices) select the USB **interface** to bind.
|
|
||||||
3. Select the kernel module.
|
|
||||||
4. Confirm; the tool unbinds the current driver, reloads the module if needed, and binds the chosen interface.
|
|
||||||
|
|
||||||
## Testing
|
- **Keyboard**: USB HID keyboard driver
|
||||||
----------
|
- **Racing Wheel**: USB racing wheel driver with force feedback
|
||||||
After binding the driver, use ``evtest`` to confirm key events:
|
|
||||||
```bash
|
## Requirements
|
||||||
sudo evtest
|
|
||||||
```
|
- Linux kernel headers
|
||||||
|
- Python 3.6+
|
||||||
|
- Root/sudo access for driver loading and binding
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
|
|
||||||
.PHONY: all clean install uninstall
|
|
||||||
|
|
||||||
obj-m += g29_usb.o
|
|
||||||
PWD := $(CURDIR)
|
|
||||||
|
|
||||||
all:
|
|
||||||
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
|
|
||||||
mkdir -p build
|
|
||||||
-mv -f -- *.ko *.mod.c *.o .*.o *.mod modules.order .*.cmd *.symvers build/
|
|
||||||
|
|
||||||
clean:
|
|
||||||
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
|
|
||||||
rm -rf build
|
|
||||||
@@ -1,616 +0,0 @@
|
|||||||
// SPDX-License-Identifier: GPL-2.0
|
|
||||||
/*
|
|
||||||
* Logitech G29 -> Media Keys (USB interface driver)
|
|
||||||
*
|
|
||||||
* Proof-of-concept Linux kernel module for low-level programming course.
|
|
||||||
*
|
|
||||||
* This driver:
|
|
||||||
* - Binds to a Logitech G29 USB interface (VID/PID match)
|
|
||||||
* - Receives 12-byte input reports via an interrupt-IN URB
|
|
||||||
* - Parses the report into a normalized state (Stage A)
|
|
||||||
* - Translates selected signals into media key events (Stage B)
|
|
||||||
*
|
|
||||||
* Stage A is designed to remain stable across different mapping policies.
|
|
||||||
* Stage B is designed to be replaced/extended by swapping mapping tables
|
|
||||||
* or adding per-signal handler functions.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <linux/kernel.h>
|
|
||||||
#include <linux/module.h>
|
|
||||||
#include <linux/slab.h>
|
|
||||||
#include <linux/usb.h>
|
|
||||||
#include <linux/usb/input.h>
|
|
||||||
#include <linux/input.h>
|
|
||||||
#include <linux/timer.h>
|
|
||||||
#include <linux/jiffies.h>
|
|
||||||
#include <linux/hid.h>
|
|
||||||
|
|
||||||
#include "g29_usb.h"
|
|
||||||
|
|
||||||
MODULE_AUTHOR("LLP group 16");
|
|
||||||
MODULE_DESCRIPTION("Logitech G29 USB driver");
|
|
||||||
MODULE_LICENSE("GPL");
|
|
||||||
|
|
||||||
enum g29_mode {
|
|
||||||
G29_MODE_MEDIA = 0,
|
|
||||||
G29_MODE_WASD = 1,
|
|
||||||
G29_MODE_MOUSE = 2,
|
|
||||||
};
|
|
||||||
|
|
||||||
static int mode = G29_MODE_MEDIA;
|
|
||||||
module_param(mode, int, 0644);
|
|
||||||
MODULE_PARM_DESC(mode, "Initial mode (0=MEDIA, 1=WASD, 2=MOUSE)");
|
|
||||||
|
|
||||||
/* Steering curve exponent (100 = linear, 200 = squared, 150 = ^1.5)
|
|
||||||
* Higher values reduce sensitivity at low steering angles.
|
|
||||||
*/
|
|
||||||
static int steer_curve = 200;
|
|
||||||
module_param(steer_curve, int, 0644);
|
|
||||||
MODULE_PARM_DESC(steer_curve, "Steering sensitivity curve (100=linear, 200=squared, default=200)");
|
|
||||||
|
|
||||||
static int steer_deadzone = 10;
|
|
||||||
module_param(steer_deadzone, int, 0644);
|
|
||||||
MODULE_PARM_DESC(steer_deadzone, "Steering deadzone radius from center (default=10)");
|
|
||||||
|
|
||||||
static int gas_curve = 100;
|
|
||||||
module_param(gas_curve, int, 0644);
|
|
||||||
MODULE_PARM_DESC(gas_curve, "Gas pedal sensitivity curve (100=linear, 200=squared, default=200)");
|
|
||||||
|
|
||||||
static int clutch_curve = 100;
|
|
||||||
module_param(clutch_curve, int, 0644);
|
|
||||||
MODULE_PARM_DESC(clutch_curve, "Clutch pedal sensitivity curve (100=linear, 200=squared, default=200)");
|
|
||||||
|
|
||||||
#define NORMALIZATION_PRECISION 1000
|
|
||||||
|
|
||||||
struct g29_keymap {
|
|
||||||
u32 mask;
|
|
||||||
unsigned short keycode;
|
|
||||||
};
|
|
||||||
|
|
||||||
static const struct g29_keymap media_mode_keymap[] = {
|
|
||||||
/* Red rotary = volume */
|
|
||||||
{ G29_BTN_RED_CW, KEY_VOLUMEUP },
|
|
||||||
{ G29_BTN_RED_CCW, KEY_VOLUMEDOWN },
|
|
||||||
|
|
||||||
/* Return = play/pause */
|
|
||||||
{ G29_BTN_RETURN, KEY_PLAYPAUSE },
|
|
||||||
|
|
||||||
/* Plus/Minus = next/prev */
|
|
||||||
{ G29_BTN_R1, KEY_NEXTSONG },
|
|
||||||
{ G29_BTN_L1, KEY_PREVIOUSSONG },
|
|
||||||
};
|
|
||||||
|
|
||||||
static const struct g29_keymap mouse_mode_keymap[] = {
|
|
||||||
{ G29_BTN_X, BTN_LEFT },
|
|
||||||
{ G29_BTN_CIRCLE, BTN_RIGHT },
|
|
||||||
{ G29_BTN_TRIANGLE, BTN_MIDDLE },
|
|
||||||
{ G29_BTN_SQUARE, BTN_SIDE },
|
|
||||||
};
|
|
||||||
|
|
||||||
struct g29_dev {
|
|
||||||
char name[128];
|
|
||||||
char phys[64];
|
|
||||||
|
|
||||||
struct usb_device *udev;
|
|
||||||
struct input_dev *input;
|
|
||||||
|
|
||||||
struct urb *urb;
|
|
||||||
u8 *buf;
|
|
||||||
dma_addr_t buf_dma;
|
|
||||||
int maxp;
|
|
||||||
int interval;
|
|
||||||
int endpoint;
|
|
||||||
|
|
||||||
struct timer_list steer_timer;
|
|
||||||
struct timer_list mouse_timer;
|
|
||||||
u32 steer_phase_ms;
|
|
||||||
|
|
||||||
u32 phase_accumulator;
|
|
||||||
u32 gas_phase_accumulator;
|
|
||||||
u32 clutch_phase_accumulator;
|
|
||||||
|
|
||||||
enum g29_mode current_mode;
|
|
||||||
struct g29_state last;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
static void g29_switch_mode(struct g29_dev *g29, enum g29_mode new_mode) {
|
|
||||||
if (g29->current_mode == new_mode)
|
|
||||||
return;
|
|
||||||
|
|
||||||
/* Stop timers when leaving modes */
|
|
||||||
if (g29->current_mode == G29_MODE_WASD) {
|
|
||||||
timer_delete_sync(&g29->steer_timer);
|
|
||||||
}
|
|
||||||
if (g29->current_mode == G29_MODE_MOUSE) {
|
|
||||||
timer_delete_sync(&g29->mouse_timer);
|
|
||||||
}
|
|
||||||
|
|
||||||
g29->current_mode = new_mode;
|
|
||||||
g29->phase_accumulator = 0;
|
|
||||||
g29->gas_phase_accumulator = 0;
|
|
||||||
g29->clutch_phase_accumulator = 0;
|
|
||||||
|
|
||||||
/* Start timers when entering modes */
|
|
||||||
if (new_mode == G29_MODE_WASD) {
|
|
||||||
mod_timer(&g29->steer_timer, jiffies + msecs_to_jiffies(2));
|
|
||||||
}
|
|
||||||
if (new_mode == G29_MODE_MOUSE) {
|
|
||||||
mod_timer(&g29->mouse_timer, jiffies + msecs_to_jiffies(10));
|
|
||||||
}
|
|
||||||
|
|
||||||
dev_info(&g29->udev->dev, "Switched to mode: %s\n",
|
|
||||||
new_mode == G29_MODE_MEDIA ? "MEDIA" :
|
|
||||||
new_mode == G29_MODE_WASD ? "WASD" : "MOUSE");
|
|
||||||
}
|
|
||||||
|
|
||||||
static int calc_adjusted_steering_distance(int distance) {
|
|
||||||
/* Apply non-linear steering curve:
|
|
||||||
* adjusted = (distance / MAX)^(curve/100) * MAX
|
|
||||||
*
|
|
||||||
* For curve=200 (squared): 5% input -> 0.25% output, 50% -> 25%, 100% -> 100%
|
|
||||||
* For curve=150 (^1.5): 5% input -> ~1.1% output, 50% -> ~35%, 100% -> 100%
|
|
||||||
* For curve=100 (linear): 5% input -> 5% output (no change)
|
|
||||||
*
|
|
||||||
* Using integer math: adjusted = (distance^2 / MAX) for curve=200
|
|
||||||
*/
|
|
||||||
if (steer_curve == 100) {
|
|
||||||
return distance;
|
|
||||||
}
|
|
||||||
if (steer_curve == 200) {
|
|
||||||
return(distance * distance) / WHEEL_MAX_DIST;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Generic power curve using normalized values (0-1000 range for precision)
|
|
||||||
* normalized = (distance * 1000) / WHEEL_MAX_DIST
|
|
||||||
* Apply power approximation, then scale back
|
|
||||||
*/
|
|
||||||
int normalized = (distance * NORMALIZATION_PRECISION) / WHEEL_MAX_DIST;
|
|
||||||
int powered;
|
|
||||||
|
|
||||||
if (steer_curve == 150) {
|
|
||||||
/* Approximate ^1.5 with (x * sqrt(x)) */
|
|
||||||
int sqrt_norm = int_sqrt(normalized * NORMALIZATION_PRECISION);
|
|
||||||
powered = (normalized * sqrt_norm) / NORMALIZATION_PRECISION;
|
|
||||||
} else {
|
|
||||||
/* Fallback: squared for any other value > 100 */
|
|
||||||
powered = (normalized * normalized) / NORMALIZATION_PRECISION;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (powered * WHEEL_MAX_DIST) / NORMALIZATION_PRECISION;
|
|
||||||
}
|
|
||||||
|
|
||||||
static int calc_adjusted_pedal_distance(int pedal_pressure, int curve) {
|
|
||||||
if (curve == 100) {
|
|
||||||
return pedal_pressure;
|
|
||||||
}
|
|
||||||
if (curve == 200) {
|
|
||||||
return (pedal_pressure * pedal_pressure) / G29_PEDAL_RELEASED;
|
|
||||||
}
|
|
||||||
|
|
||||||
int normalized = (pedal_pressure * NORMALIZATION_PRECISION) / G29_PEDAL_RELEASED;
|
|
||||||
int powered;
|
|
||||||
|
|
||||||
if (curve == 150) {
|
|
||||||
int sqrt_norm = int_sqrt(normalized * NORMALIZATION_PRECISION);
|
|
||||||
powered = (normalized * sqrt_norm) / NORMALIZATION_PRECISION;
|
|
||||||
} else {
|
|
||||||
powered = (normalized * normalized) / NORMALIZATION_PRECISION;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (powered * G29_PEDAL_RELEASED) / NORMALIZATION_PRECISION;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void mouse_mode_timer_fn(struct timer_list *t) {
|
|
||||||
struct g29_dev *g29 = timer_container_of(g29, t, mouse_timer);
|
|
||||||
|
|
||||||
const int rot = le16_to_cpu(g29->last.rot_le);
|
|
||||||
int gas_pressure = G29_PEDAL_RELEASED - g29->last.gas;
|
|
||||||
int clutch_pressure = G29_PEDAL_RELEASED - g29->last.clt;
|
|
||||||
|
|
||||||
/* Calculate speed: positive for forward (gas), negative for backward (clutch) */
|
|
||||||
int speed = gas_pressure - clutch_pressure;
|
|
||||||
|
|
||||||
/* Apply deadzone to steering */
|
|
||||||
int effective_rot = rot;
|
|
||||||
if (abs(rot - WHEEL_CENTER) <= steer_deadzone) {
|
|
||||||
effective_rot = WHEEL_CENTER;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Calculate angle from wheel rotation
|
|
||||||
* Map wheel rotation to angle:
|
|
||||||
* - Center (32768) = 0° (straight forward)
|
|
||||||
* - Full left (0) = -180° (reverse)
|
|
||||||
* - Full right (65535) = +180° (reverse)
|
|
||||||
* We normalize to -1000 to +1000 representing -π to +π radians
|
|
||||||
*/
|
|
||||||
int angle_normalized = ((effective_rot - WHEEL_CENTER) * 1000) / WHEEL_CENTER;
|
|
||||||
|
|
||||||
/* Clamp angle to prevent overflow */
|
|
||||||
if (angle_normalized > 1000) angle_normalized = 1000;
|
|
||||||
if (angle_normalized < -1000) angle_normalized = -1000;
|
|
||||||
|
|
||||||
/* Calculate movement components using better trigonometric approximations:
|
|
||||||
* dx = sin(angle) * speed
|
|
||||||
* dy = cos(angle) * speed
|
|
||||||
*
|
|
||||||
* sin(x) ≈ x - x³/6 (Taylor series)
|
|
||||||
* cos(x) ≈ 1 - x²/2 + x⁴/24 (Taylor series)
|
|
||||||
*
|
|
||||||
* For angle_normalized in [-1000, 1000] representing [-π, +π]:
|
|
||||||
* This gives us full reverse when fully steered
|
|
||||||
*/
|
|
||||||
long angle_cubed = ((long)angle_normalized * angle_normalized * angle_normalized) / 1000000;
|
|
||||||
int sin_approx = (angle_normalized * 1000 - angle_cubed / 6) / 1000;
|
|
||||||
|
|
||||||
long angle_squared = ((long)angle_normalized * angle_normalized) / 1000;
|
|
||||||
long angle_fourth = (angle_squared * angle_squared) / 1000;
|
|
||||||
int cos_approx = 1000 - angle_squared / 2 + angle_fourth / 24;
|
|
||||||
|
|
||||||
int dx = (sin_approx * speed) / 1000;
|
|
||||||
int dy = -(cos_approx * speed) / 1000; /* Negative because forward is -Y */
|
|
||||||
|
|
||||||
/* Scale down the movement for reasonable mouse speed */
|
|
||||||
int scaled_dx = dx / 50;
|
|
||||||
int scaled_dy = dy / 50;
|
|
||||||
|
|
||||||
/* Report mouse movement if there's any */
|
|
||||||
if (scaled_dx != 0 || scaled_dy != 0) {
|
|
||||||
input_report_rel(g29->input, REL_X, scaled_dx);
|
|
||||||
input_report_rel(g29->input, REL_Y, scaled_dy);
|
|
||||||
input_sync(g29->input);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Reschedule timer if still in mouse mode */
|
|
||||||
if (g29->current_mode == G29_MODE_MOUSE)
|
|
||||||
mod_timer(&g29->mouse_timer, jiffies + msecs_to_jiffies(10));
|
|
||||||
}
|
|
||||||
static void wasd_mode_timer_fn(struct timer_list *t) {
|
|
||||||
struct g29_dev *g29 = timer_container_of(g29, t, steer_timer);
|
|
||||||
|
|
||||||
const int rot = le16_to_cpu(g29->last.rot_le);
|
|
||||||
|
|
||||||
int effective_rot = rot;
|
|
||||||
int distance_from_center = abs(rot - WHEEL_CENTER);
|
|
||||||
if (distance_from_center <= steer_deadzone) {
|
|
||||||
effective_rot = WHEEL_CENTER;
|
|
||||||
}
|
|
||||||
|
|
||||||
int distance_to_center = abs(effective_rot - WHEEL_CENTER);
|
|
||||||
int adjusted_distance = calc_adjusted_steering_distance(distance_to_center);
|
|
||||||
|
|
||||||
/* Phase accumulator approach:
|
|
||||||
* Accumulate the adjusted distance on each tick.
|
|
||||||
* When it exceeds the max distance, press the key and wrap.
|
|
||||||
* This gives us a duty cycle of (adjusted_distance / WHEEL_MAX_DIST).
|
|
||||||
*
|
|
||||||
* Examples (with curve=200):
|
|
||||||
* 5% steering -> ~0.25% press rate
|
|
||||||
* 50% steering -> 25% press rate
|
|
||||||
* 100% steering -> 100% press rate (every tick)
|
|
||||||
*/
|
|
||||||
g29->phase_accumulator += adjusted_distance;
|
|
||||||
|
|
||||||
bool press_key;
|
|
||||||
if (g29->phase_accumulator >= WHEEL_MAX_DIST) {
|
|
||||||
g29->phase_accumulator -= WHEEL_MAX_DIST;
|
|
||||||
press_key = true;
|
|
||||||
} else {
|
|
||||||
press_key = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
input_report_key(g29->input, KEY_A, press_key && (effective_rot < WHEEL_CENTER));
|
|
||||||
input_report_key(g29->input, KEY_D, press_key && (effective_rot >= WHEEL_CENTER));
|
|
||||||
|
|
||||||
/* Gas pedal (0xFF=up, 0x00=down) -> W key */
|
|
||||||
int gas_pressure = 0xFF - g29->last.gas;
|
|
||||||
int gas_adjusted = calc_adjusted_pedal_distance(gas_pressure, gas_curve);
|
|
||||||
g29->gas_phase_accumulator += gas_adjusted;
|
|
||||||
|
|
||||||
bool press_w = false;
|
|
||||||
if (g29->gas_phase_accumulator >= G29_PEDAL_RELEASED) {
|
|
||||||
g29->gas_phase_accumulator -= G29_PEDAL_RELEASED;
|
|
||||||
press_w = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Clutch pedal (0xFF=up, 0x00=down) -> S key */
|
|
||||||
int clutch_pressure = 0xFF - g29->last.clt;
|
|
||||||
int clutch_adjusted = calc_adjusted_pedal_distance(clutch_pressure, clutch_curve);
|
|
||||||
g29->clutch_phase_accumulator += clutch_adjusted;
|
|
||||||
|
|
||||||
bool press_s = false;
|
|
||||||
if (g29->clutch_phase_accumulator >= G29_PEDAL_RELEASED) {
|
|
||||||
g29->clutch_phase_accumulator -= G29_PEDAL_RELEASED;
|
|
||||||
press_s = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
input_report_key(g29->input, KEY_W, press_w);
|
|
||||||
input_report_key(g29->input, KEY_S, press_s);
|
|
||||||
|
|
||||||
input_sync(g29->input);
|
|
||||||
|
|
||||||
if (g29->current_mode == G29_MODE_WASD)
|
|
||||||
mod_timer(&g29->steer_timer, jiffies + msecs_to_jiffies(2));
|
|
||||||
}
|
|
||||||
|
|
||||||
static void process_media_mode(struct g29_dev *g29, const struct g29_state *cur, const struct g29_state *prev) {
|
|
||||||
const u32 pressed = le32_to_cpu(cur->buttons_le & ~prev->buttons_le);
|
|
||||||
const u32 released = le32_to_cpu(~cur->buttons_le & prev->buttons_le);
|
|
||||||
for (int i = 0; i < ARRAY_SIZE(media_mode_keymap); i++) {
|
|
||||||
const struct g29_keymap *k = &media_mode_keymap[i];
|
|
||||||
if (pressed & k->mask) {
|
|
||||||
input_report_key(g29->input, k->keycode, 1);
|
|
||||||
}
|
|
||||||
if (released & k->mask) {
|
|
||||||
input_report_key(g29->input, k->keycode, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
input_sync(g29->input);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void process_wasd_mode(struct g29_dev *g29, const struct g29_state *cur, const struct g29_state *prev) {
|
|
||||||
/* WASD mode is handled by the timer function (g29_steer_timer_fn) */
|
|
||||||
/* No additional processing needed here */
|
|
||||||
}
|
|
||||||
|
|
||||||
static void process_mouse_mode(struct g29_dev *g29, const struct g29_state *cur, const struct g29_state *prev) {
|
|
||||||
const u32 pressed = le32_to_cpu(cur->buttons_le & ~prev->buttons_le);
|
|
||||||
const u32 released = le32_to_cpu(~cur->buttons_le & prev->buttons_le);
|
|
||||||
|
|
||||||
for (int i = 0; i < ARRAY_SIZE(mouse_mode_keymap); i++) {
|
|
||||||
const struct g29_keymap *k = &mouse_mode_keymap[i];
|
|
||||||
if (pressed & k->mask) {
|
|
||||||
input_report_key(g29->input, k->keycode, 1);
|
|
||||||
}
|
|
||||||
if (released & k->mask) {
|
|
||||||
input_report_key(g29->input, k->keycode, 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pressed & G29_BTN_RED_CW) {
|
|
||||||
input_report_rel(g29->input, REL_WHEEL, 1);
|
|
||||||
}
|
|
||||||
if (pressed & G29_BTN_RED_CCW) {
|
|
||||||
input_report_rel(g29->input, REL_WHEEL, -1);
|
|
||||||
}
|
|
||||||
|
|
||||||
input_sync(g29->input);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void g29_check_mode_switch(struct g29_dev *g29, const struct g29_state *cur, const struct g29_state *prev) {
|
|
||||||
u32 pressed = le32_to_cpu(cur->buttons_le & ~prev->buttons_le);
|
|
||||||
|
|
||||||
if (pressed & G29_BTN_SHARE) {
|
|
||||||
g29_switch_mode(g29, G29_MODE_MEDIA);
|
|
||||||
} else if (pressed & G29_BTN_OPTION) {
|
|
||||||
g29_switch_mode(g29, G29_MODE_WASD);
|
|
||||||
} else if (pressed & G29_BTN_PS3_LOGO) {
|
|
||||||
g29_switch_mode(g29, G29_MODE_MOUSE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static void g29_process_report(struct g29_dev *g29, const u8 *data, unsigned int len) {
|
|
||||||
if (len < 12) return;
|
|
||||||
|
|
||||||
struct g29_state *cur = (void *) data;
|
|
||||||
|
|
||||||
g29_check_mode_switch(g29, cur, &g29->last);
|
|
||||||
|
|
||||||
switch (g29->current_mode) {
|
|
||||||
case G29_MODE_MEDIA:
|
|
||||||
process_media_mode(g29, cur, &g29->last);
|
|
||||||
break;
|
|
||||||
case G29_MODE_WASD:
|
|
||||||
process_wasd_mode(g29, cur, &g29->last);
|
|
||||||
break;
|
|
||||||
case G29_MODE_MOUSE:
|
|
||||||
process_mouse_mode(g29, cur, &g29->last);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
g29->last = *cur;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void g29_urb_complete(struct urb *urb) {
|
|
||||||
struct g29_dev *g29 = urb->context;
|
|
||||||
int ret;
|
|
||||||
|
|
||||||
switch (urb->status) {
|
|
||||||
case 0:
|
|
||||||
break; /* success */
|
|
||||||
case -ECONNRESET:
|
|
||||||
case -ENOENT:
|
|
||||||
case -ESHUTDOWN:
|
|
||||||
return; /* cancelled/disconnected */
|
|
||||||
default:
|
|
||||||
goto resubmit; /* transient error */
|
|
||||||
}
|
|
||||||
|
|
||||||
g29_process_report(g29, g29->buf, urb->actual_length);
|
|
||||||
|
|
||||||
resubmit:
|
|
||||||
ret = usb_submit_urb(urb, GFP_ATOMIC);
|
|
||||||
if (ret)
|
|
||||||
dev_err(&g29->udev->dev, "usb_submit_urb failed: %d\n", ret);
|
|
||||||
}
|
|
||||||
|
|
||||||
static int g29_input_open(struct input_dev *input) {
|
|
||||||
struct g29_dev *g29 = input_get_drvdata(input);
|
|
||||||
|
|
||||||
g29->urb->dev = g29->udev;
|
|
||||||
if (usb_submit_urb(g29->urb, GFP_KERNEL))
|
|
||||||
return -EIO;
|
|
||||||
|
|
||||||
g29_switch_mode(g29, mode);
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void g29_input_close(struct input_dev *input) {
|
|
||||||
struct g29_dev *g29 = input_get_drvdata(input);
|
|
||||||
|
|
||||||
if (g29->current_mode == G29_MODE_WASD)
|
|
||||||
timer_delete_sync(&g29->steer_timer);
|
|
||||||
if (g29->current_mode == G29_MODE_MOUSE)
|
|
||||||
timer_delete_sync(&g29->mouse_timer);
|
|
||||||
|
|
||||||
usb_kill_urb(g29->urb);
|
|
||||||
}
|
|
||||||
|
|
||||||
static int g29_probe(struct usb_interface *intf, const struct usb_device_id *id) {
|
|
||||||
struct usb_device *udev = interface_to_usbdev(intf);
|
|
||||||
int ret;
|
|
||||||
|
|
||||||
/* Find an interrupt IN endpoint capable of carrying the 12-byte report. */
|
|
||||||
struct usb_endpoint_descriptor *ep = NULL;
|
|
||||||
const struct usb_host_interface *alts = intf->cur_altsetting;
|
|
||||||
for (int i = 0; i < alts->desc.bNumEndpoints; i++) {
|
|
||||||
struct usb_endpoint_descriptor *d = &alts->endpoint[i].desc;
|
|
||||||
if (!usb_endpoint_is_int_in(d))
|
|
||||||
continue;
|
|
||||||
if (usb_maxpacket(udev, usb_rcvintpipe(udev, d->bEndpointAddress)) >= 12) {
|
|
||||||
ep = d;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!ep) return -ENODEV;
|
|
||||||
|
|
||||||
struct g29_dev *g29;
|
|
||||||
if ((g29 = kzalloc(sizeof(*g29), GFP_KERNEL)) == NULL) {
|
|
||||||
return -ENOMEM;
|
|
||||||
}
|
|
||||||
|
|
||||||
struct input_dev *input;
|
|
||||||
if ((input = input_allocate_device()) == NULL) {
|
|
||||||
ret = -ENOMEM;
|
|
||||||
goto err_free_g29;
|
|
||||||
}
|
|
||||||
|
|
||||||
g29->udev = udev;
|
|
||||||
g29->input = input;
|
|
||||||
|
|
||||||
g29->endpoint = usb_endpoint_num(ep);
|
|
||||||
g29->maxp = usb_endpoint_maxp(ep);
|
|
||||||
g29->interval = ep->bInterval;
|
|
||||||
memset(&g29->last, 0, sizeof(g29->last));
|
|
||||||
g29->current_mode = mode; /* Initialize to module parameter */
|
|
||||||
|
|
||||||
timer_setup(&g29->steer_timer, wasd_mode_timer_fn, 0);
|
|
||||||
timer_setup(&g29->mouse_timer, mouse_mode_timer_fn, 0);
|
|
||||||
|
|
||||||
if ((g29->buf = usb_alloc_coherent(udev, g29->maxp, GFP_KERNEL, &g29->buf_dma)) == NULL) {
|
|
||||||
ret = -ENOMEM;
|
|
||||||
goto err_free_input;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((g29->urb = usb_alloc_urb(0, GFP_KERNEL)) == NULL) {
|
|
||||||
ret = -ENOMEM;
|
|
||||||
goto err_free_buf;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (udev->manufacturer)
|
|
||||||
strscpy(g29->name, udev->manufacturer, sizeof(g29->name));
|
|
||||||
if (udev->product) {
|
|
||||||
if (udev->manufacturer)
|
|
||||||
strlcat(g29->name, " ", sizeof(g29->name));
|
|
||||||
strlcat(g29->name, udev->product, sizeof(g29->name));
|
|
||||||
}
|
|
||||||
if (!strlen(g29->name))
|
|
||||||
snprintf(g29->name, sizeof(g29->name),
|
|
||||||
"Logitech G29 USB %04x:%04x",
|
|
||||||
le16_to_cpu(udev->descriptor.idVendor),
|
|
||||||
le16_to_cpu(udev->descriptor.idProduct));
|
|
||||||
|
|
||||||
usb_make_path(udev, g29->phys, sizeof(g29->phys));
|
|
||||||
strlcat(g29->phys, "/input0", sizeof(g29->phys));
|
|
||||||
|
|
||||||
input->name = g29->name;
|
|
||||||
input->phys = g29->phys;
|
|
||||||
usb_to_input_id(udev, &input->id);
|
|
||||||
input->dev.parent = &intf->dev;
|
|
||||||
|
|
||||||
__set_bit(EV_KEY, input->evbit);
|
|
||||||
__set_bit(EV_REL, input->evbit);
|
|
||||||
|
|
||||||
/* Media mode keys */
|
|
||||||
input_set_capability(input, EV_KEY, KEY_VOLUMEUP);
|
|
||||||
input_set_capability(input, EV_KEY, KEY_VOLUMEDOWN);
|
|
||||||
input_set_capability(input, EV_KEY, KEY_PLAYPAUSE);
|
|
||||||
input_set_capability(input, EV_KEY, KEY_NEXTSONG);
|
|
||||||
input_set_capability(input, EV_KEY, KEY_PREVIOUSSONG);
|
|
||||||
|
|
||||||
/* WASD mode keys */
|
|
||||||
input_set_capability(input, EV_KEY, KEY_W);
|
|
||||||
input_set_capability(input, EV_KEY, KEY_A);
|
|
||||||
input_set_capability(input, EV_KEY, KEY_S);
|
|
||||||
input_set_capability(input, EV_KEY, KEY_D);
|
|
||||||
|
|
||||||
/* Mouse mode capabilities */
|
|
||||||
input_set_capability(input, EV_KEY, BTN_LEFT);
|
|
||||||
input_set_capability(input, EV_KEY, BTN_RIGHT);
|
|
||||||
input_set_capability(input, EV_KEY, BTN_MIDDLE);
|
|
||||||
input_set_capability(input, EV_REL, REL_X);
|
|
||||||
input_set_capability(input, EV_REL, REL_Y);
|
|
||||||
input_set_capability(input, EV_REL, REL_WHEEL);
|
|
||||||
|
|
||||||
input_set_drvdata(input, g29);
|
|
||||||
input->open = g29_input_open;
|
|
||||||
input->close = g29_input_close;
|
|
||||||
|
|
||||||
usb_fill_int_urb(g29->urb, udev, usb_rcvintpipe(udev, ep->bEndpointAddress),
|
|
||||||
g29->buf, g29->maxp,
|
|
||||||
g29_urb_complete, g29, ep->bInterval);
|
|
||||||
g29->urb->transfer_dma = g29->buf_dma;
|
|
||||||
g29->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
|
|
||||||
|
|
||||||
if ((ret = input_register_device(input)) != 0) {
|
|
||||||
goto err_free_urb;
|
|
||||||
}
|
|
||||||
|
|
||||||
usb_set_intfdata(intf, g29);
|
|
||||||
|
|
||||||
dev_info(&intf->dev,
|
|
||||||
"G29 media driver bound (ep=%02x interval=%u)\n",
|
|
||||||
ep->bEndpointAddress, ep->bInterval);
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
|
|
||||||
err_free_urb:
|
|
||||||
usb_free_urb(g29->urb);
|
|
||||||
err_free_buf:
|
|
||||||
usb_free_coherent(udev, g29->maxp, g29->buf, g29->buf_dma);
|
|
||||||
err_free_input:
|
|
||||||
input_free_device(input);
|
|
||||||
err_free_g29:
|
|
||||||
kfree(g29);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void g29_disconnect(struct usb_interface *intf) {
|
|
||||||
struct g29_dev *g29 = usb_get_intfdata(intf);
|
|
||||||
usb_set_intfdata(intf, NULL);
|
|
||||||
if (!g29) return;
|
|
||||||
usb_kill_urb(g29->urb);
|
|
||||||
input_unregister_device(g29->input);
|
|
||||||
usb_free_urb(g29->urb);
|
|
||||||
usb_free_coherent(interface_to_usbdev(intf), g29->maxp, g29->buf, g29->buf_dma);
|
|
||||||
kfree(g29);
|
|
||||||
dev_info(&intf->dev, "G29 driver disconnected\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
static const struct usb_device_id g29_id_table[] = {
|
|
||||||
{ USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G29) },
|
|
||||||
{ USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G29_ALT) },
|
|
||||||
{ }
|
|
||||||
};
|
|
||||||
MODULE_DEVICE_TABLE(usb, g29_id_table);
|
|
||||||
|
|
||||||
static struct usb_driver g29_driver = {
|
|
||||||
.name = "g29_usb",
|
|
||||||
.id_table = g29_id_table,
|
|
||||||
.probe = g29_probe,
|
|
||||||
.disconnect = g29_disconnect,
|
|
||||||
};
|
|
||||||
|
|
||||||
module_usb_driver(g29_driver);
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
/*
|
|
||||||
* Logitech G29 USB/HID Protocol Definitions
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef G29_USB_H
|
|
||||||
#define G29_USB_H
|
|
||||||
|
|
||||||
#include <linux/types.h>
|
|
||||||
|
|
||||||
#define USB_VENDOR_ID_LOGITECH 0x046d
|
|
||||||
#define USB_DEVICE_ID_LOGITECH_G29 0xc24f
|
|
||||||
#define USB_DEVICE_ID_LOGITECH_G29_ALT 0xc260
|
|
||||||
|
|
||||||
#define G29_BTN_X 0x00000010u
|
|
||||||
#define G29_BTN_SQUARE 0x00000020u
|
|
||||||
#define G29_BTN_CIRCLE 0x00000040u
|
|
||||||
#define G29_BTN_TRIANGLE 0x00000080u
|
|
||||||
#define G29_BTN_R1 0x00000100u
|
|
||||||
#define G29_BTN_L1 0x00000200u
|
|
||||||
#define G29_BTN_R2 0x00000400u
|
|
||||||
#define G29_BTN_L2 0x00000800u
|
|
||||||
#define G29_BTN_SHARE 0x00001000u
|
|
||||||
#define G29_BTN_OPTION 0x00002000u
|
|
||||||
#define G29_BTN_R3 0x00004000u
|
|
||||||
#define G29_BTN_L3 0x00008000u
|
|
||||||
#define G29_BTN_GEAR_1 0x00010000u
|
|
||||||
#define G29_BTN_GEAR_2 0x00020000u
|
|
||||||
#define G29_BTN_GEAR_3 0x00040000u
|
|
||||||
#define G29_BTN_GEAR_4 0x00080000u
|
|
||||||
#define G29_BTN_GEAR_5 0x00100000u
|
|
||||||
#define G29_BTN_GEAR_6 0x00200000u
|
|
||||||
#define G29_BTN_GEAR_REV 0x00400000u
|
|
||||||
#define G29_BTN_PLUS 0x00800000u
|
|
||||||
#define G29_BTN_MINUS 0x01000000u
|
|
||||||
#define G29_BTN_RED_CW 0x02000000u
|
|
||||||
#define G29_BTN_RED_CCW 0x04000000u
|
|
||||||
#define G29_BTN_RETURN 0x08000000u
|
|
||||||
#define G29_BTN_PS3_LOGO 0xF0000000u
|
|
||||||
|
|
||||||
#define G29_DPAD_MASK 0x0000000Eu
|
|
||||||
#define G29_DPAD_UP 0x00000000u
|
|
||||||
#define G29_DPAD_RIGHT 0x00000002u
|
|
||||||
#define G29_DPAD_DOWN 0x00000004u
|
|
||||||
#define G29_DPAD_LEFT 0x00000006u
|
|
||||||
#define G29_DPAD_NONE 0x00000008u
|
|
||||||
|
|
||||||
#define G29_WHEEL_MIN_ROTATION 0x0000
|
|
||||||
#define G29_WHEEL_MAX_ROTATION 0xFFFF
|
|
||||||
|
|
||||||
#define G29_PEDAL_RELEASED 0xFF
|
|
||||||
#define G29_PEDAL_PRESSED 0x00
|
|
||||||
#define G29_PEDAL_THRESHOLD 0x80
|
|
||||||
|
|
||||||
#define G29_GEARSHIFT_X_LEFT 0x30 /* Gears 1-2 */
|
|
||||||
#define G29_GEARSHIFT_X_CENTER 0x80 /* Gears 3-4 */
|
|
||||||
#define G29_GEARSHIFT_X_RIGHT 0xB0 /* Gears 5-6-R */
|
|
||||||
#define G29_GEARSHIFT_Y_TOP 0xD0 /* Gears 1-3-5 */
|
|
||||||
#define G29_GEARSHIFT_Y_BOTTOM 0x40 /* Gears 2-4-6-R */
|
|
||||||
#define G29_GEARSHIFT_Z_NEUTRAL 0x9C /* Neutral position */
|
|
||||||
#define G29_GEARSHIFT_Z_PRESSED 0xDC /* Pressed down */
|
|
||||||
|
|
||||||
#define WHEEL_CENTER 32768
|
|
||||||
#define WHEEL_MAX_DIST 32768
|
|
||||||
|
|
||||||
struct g29_state {
|
|
||||||
u32 buttons_le; /* Button bitmask (little-endian) */
|
|
||||||
u16 rot_le; /* Wheel rotation (little-endian) */
|
|
||||||
u8 gas; /* Gas pedal (0xFF=up, 0x00=down) */
|
|
||||||
u8 brk; /* Brake pedal (0xFF=up, 0x00=down) */
|
|
||||||
u8 clt; /* Clutch pedal (0xFF=up, 0x00=down) */
|
|
||||||
u8 gr_x; /* Gearshift X-axis */
|
|
||||||
u8 gr_y; /* Gearshift Y-axis */
|
|
||||||
u8 gr_z; /* Gearshift Z-axis */
|
|
||||||
} __packed;
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
|
|
||||||
Logitech G29 USB Protocol
|
|
||||||
=========================
|
|
||||||
|
|
||||||
- 12 bytes per event
|
|
||||||
- Little-endian (= smaller value bytes first)
|
|
||||||
|
|
||||||
```
|
|
||||||
1
|
|
||||||
0 1 2 3 4 5 6 7 8 9 0 1
|
|
||||||
+---+---+---+---+---+---+---+---+---+---+---+---+
|
|
||||||
| Buttons | Rot |Gas|Brk|Clt|GrX|GrY|GrZ|
|
|
||||||
+---+---+---+---+---+---+---+---+---+---+---+---+
|
|
||||||
```
|
|
||||||
|
|
||||||
- `Buttons`: Bitmask of pressed buttons (mask values are in big endian).
|
|
||||||
- `0x00000001` - ?
|
|
||||||
- `0x0000000E` - Arrow keys
|
|
||||||
- `0x00000000` - Up
|
|
||||||
- `0x00000002` - Right
|
|
||||||
- `0x00000004` - Down
|
|
||||||
- `0x00000006` - Left
|
|
||||||
- `0x00000008` - No arrow key pressed
|
|
||||||
- `0x00000010` - X
|
|
||||||
- `0x00000020` - Square
|
|
||||||
- `0x00000040` - Circle
|
|
||||||
- `0x00000080` - Triangle
|
|
||||||
- `0x00000100` - R1
|
|
||||||
- `0x00000200` - L1
|
|
||||||
- `0x00000400` - R2
|
|
||||||
- `0x00000800` - L2
|
|
||||||
- `0x00001000` - Share
|
|
||||||
- `0x00002000` - Option
|
|
||||||
- `0x00004000` - R3
|
|
||||||
- `0x00008000` - L3
|
|
||||||
- `0x00010000` - Gear 1
|
|
||||||
- `0x00020000` - Gear 2
|
|
||||||
- `0x00040000` - Gear 3
|
|
||||||
- `0x00080000` - Gear 4
|
|
||||||
- `0x00100000` - Gear 5
|
|
||||||
- `0x00200000` - Gear 6
|
|
||||||
- `0x00400000` - Gear reverse
|
|
||||||
- `0x00800000` - Plus
|
|
||||||
- `0x01000000` - Minus
|
|
||||||
- `0x02000000` - Red rotation clockwise
|
|
||||||
- `0x04000000` - Red rotation counterclockwise
|
|
||||||
- `0x08000000` - Return
|
|
||||||
- `0xF0000000` - Playstation 3 Logo Button (verify)
|
|
||||||
- `Rot`: Wheel rotation (little-endian). `0x0000` (leftmost) - `0xFFFF` (rightmost).
|
|
||||||
- `Gas`: Gas pedal. `0xFF` (up, default) - `0x00` (down).
|
|
||||||
- `Brk`: Brake pedal. `0xFF` (up, default) - `0x00` (down).
|
|
||||||
- `Clt`: Clutch pedal. `0xFF` (up, default) - `0x00` (down).
|
|
||||||
- `GrX`: Gearshift X axis. ~`0x30` (gear 1+2), ~`0x80` (gear 3+4), ~`0xB0` (gear 5+6+reverse).
|
|
||||||
- `GrY`: Gearshift Y axis. ~`0xD0` (gear 1+3+5), ~`0x40` (gear 2+4+6+reverse).
|
|
||||||
- `GrZ`: Gearshift Z axis. ~`0x9C` (neutral), ~`0xDC` (pressed down).
|
|
||||||
|
|
||||||
|
|
||||||
## Sample event
|
|
||||||
|
|
||||||
Sample event:
|
|
||||||
```
|
|
||||||
08 00 00 00 00 80 ff ff ff 81 80 9c
|
|
||||||
```
|
|
||||||
|
|
||||||
* No buttons pressed / no gear engaged
|
|
||||||
* Wheel rotation at `0x8000` ~ center
|
|
||||||
* Gas pedal up
|
|
||||||
* Brake pedal up
|
|
||||||
* Clutch pedal up
|
|
||||||
* Gearshift neutral
|
|
||||||
@@ -6,11 +6,6 @@ and binding USB devices to new drivers.
|
|||||||
|
|
||||||
Note: USB drivers typically bind to interfaces, not devices. This script
|
Note: USB drivers typically bind to interfaces, not devices. This script
|
||||||
handles both device-level and interface-level driver binding.
|
handles both device-level and interface-level driver binding.
|
||||||
|
|
||||||
Wheel-friendly improvements:
|
|
||||||
- Finds kernel modules (*.ko) recursively under provided directories (e.g. ./build).
|
|
||||||
- Lets the user select which USB interface(s) to unbind/bind.
|
|
||||||
Default selection: all HID interfaces (bInterfaceClass==03).
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
@@ -79,7 +74,7 @@ def get_usb_devices():
|
|||||||
result = subprocess.run(['lsusb'], capture_output=True, text=True)
|
result = subprocess.run(['lsusb'], capture_output=True, text=True)
|
||||||
for line in result.stdout.splitlines():
|
for line in result.stdout.splitlines():
|
||||||
# Format: Bus 001 Device 005: ID 046d:c52b Logitech, Inc. Unifying Receiver
|
# Format: Bus 001 Device 005: ID 046d:c52b Logitech, Inc. Unifying Receiver
|
||||||
match = re.match(r'Bus (\d+) Device (\d+): ID ([0-9a-f]{4}):([0-9a-f]{4})\s+(.*)', line, re.IGNORECASE)
|
match = re.match(r'Bus (\d+) Device (\d+): ID ([0-9a-f]{4}):([0-9a-f]{4})\s+(.*)', line)
|
||||||
if match:
|
if match:
|
||||||
bus, dev, vendor, product, name = match.groups()
|
bus, dev, vendor, product, name = match.groups()
|
||||||
key = f"{int(bus)}-{int(dev)}"
|
key = f"{int(bus)}-{int(dev)}"
|
||||||
@@ -98,7 +93,7 @@ def get_usb_devices():
|
|||||||
|
|
||||||
# Only process actual device entries (format: busnum-devnum or busnum-port.port...)
|
# Only process actual device entries (format: busnum-devnum or busnum-port.port...)
|
||||||
device_name = device_path.name
|
device_name = device_path.name
|
||||||
if not re.match(r'\d+-[\d.]+$', device_name):
|
if not re.match(r'\d+-[\d.]+', device_name):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Skip root hubs
|
# Skip root hubs
|
||||||
@@ -121,9 +116,21 @@ def get_usb_devices():
|
|||||||
if driver_link.exists() and driver_link.is_symlink():
|
if driver_link.exists() and driver_link.is_symlink():
|
||||||
driver = driver_link.resolve().name
|
driver = driver_link.resolve().name
|
||||||
|
|
||||||
|
# Try to get better name from lsusb
|
||||||
|
lsusb_key = f"{int(busnum)}-{int(devnum)}"
|
||||||
|
if lsusb_key in lsusb_output:
|
||||||
|
product = lsusb_output[lsusb_key]['name']
|
||||||
|
|
||||||
|
# Check if it's an input device by looking at device class or interfaces
|
||||||
|
is_input = False
|
||||||
|
device_class = (device_path / "bDeviceClass").read_text().strip() if (device_path / "bDeviceClass").exists() else "00"
|
||||||
|
|
||||||
|
# Class 03 is HID (Human Interface Device)
|
||||||
|
if device_class == "03":
|
||||||
|
is_input = True
|
||||||
|
|
||||||
# Check interfaces for HID class and collect interface information
|
# Check interfaces for HID class and collect interface information
|
||||||
interfaces = []
|
interfaces = []
|
||||||
is_input = False
|
|
||||||
for interface_path in device_path.glob("*:*.*"):
|
for interface_path in device_path.glob("*:*.*"):
|
||||||
if not interface_path.is_dir():
|
if not interface_path.is_dir():
|
||||||
continue
|
continue
|
||||||
@@ -153,12 +160,6 @@ def get_usb_devices():
|
|||||||
except Exception:
|
except Exception:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Improve product string from lsusb when possible (safe conversion)
|
|
||||||
if busnum.isdigit() and devnum.isdigit():
|
|
||||||
lsusb_key = f"{int(busnum)}-{int(devnum)}"
|
|
||||||
if lsusb_key in lsusb_output:
|
|
||||||
product = lsusb_output[lsusb_key]['name']
|
|
||||||
|
|
||||||
devices.append({
|
devices.append({
|
||||||
'path': str(device_path),
|
'path': str(device_path),
|
||||||
'name': device_name,
|
'name': device_name,
|
||||||
@@ -171,7 +172,7 @@ def get_usb_devices():
|
|||||||
'driver': driver,
|
'driver': driver,
|
||||||
'is_input': is_input,
|
'is_input': is_input,
|
||||||
'interfaces': interfaces,
|
'interfaces': interfaces,
|
||||||
'display_name': f"{manufacturer} {product}".strip()
|
'display_name': f"{manufacturer} {product}"
|
||||||
})
|
})
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -216,45 +217,42 @@ def get_kernel_modules(directories=None):
|
|||||||
modules = []
|
modules = []
|
||||||
seen_modules = set() # Track module names to avoid duplicates
|
seen_modules = set() # Track module names to avoid duplicates
|
||||||
|
|
||||||
# Search for .ko files recursively in each specified directory
|
# Search for .ko files in each specified directory
|
||||||
for directory in directories:
|
for directory in directories:
|
||||||
if not os.path.exists(directory):
|
if not os.path.exists(directory):
|
||||||
print_warning(f"Directory not found: {directory}")
|
print_warning(f"Directory not found: {directory}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
for root, dirs, files in os.walk(directory):
|
for ko_file in glob.glob(os.path.join(directory, "*.ko")):
|
||||||
for filename in files:
|
module_name = os.path.basename(ko_file)
|
||||||
if not filename.endswith('.ko'):
|
module_path = os.path.abspath(ko_file)
|
||||||
continue
|
|
||||||
|
|
||||||
module_name = filename
|
# Skip duplicates (same module name already found)
|
||||||
module_path = os.path.abspath(os.path.join(root, filename))
|
if module_name in seen_modules:
|
||||||
|
continue
|
||||||
|
seen_modules.add(module_name)
|
||||||
|
|
||||||
# Skip duplicates (same module name already found)
|
# Get module info if possible
|
||||||
if module_name in seen_modules:
|
try:
|
||||||
continue
|
result = subprocess.run(['modinfo', module_path],
|
||||||
seen_modules.add(module_name)
|
capture_output=True, text=True)
|
||||||
|
description = "No description"
|
||||||
|
for line in result.stdout.splitlines():
|
||||||
|
if line.startswith("description:"):
|
||||||
|
description = line.split(":", 1)[1].strip()
|
||||||
|
break
|
||||||
|
|
||||||
# Get module info if possible
|
modules.append({
|
||||||
try:
|
'name': module_name,
|
||||||
result = subprocess.run(['modinfo', module_path], capture_output=True, text=True)
|
'path': module_path,
|
||||||
description = "No description"
|
'description': description
|
||||||
for line in result.stdout.splitlines():
|
})
|
||||||
if line.startswith("description:"):
|
except Exception:
|
||||||
description = line.split(":", 1)[1].strip()
|
modules.append({
|
||||||
break
|
'name': module_name,
|
||||||
|
'path': module_path,
|
||||||
modules.append({
|
'description': "No description available"
|
||||||
'name': module_name,
|
})
|
||||||
'path': module_path,
|
|
||||||
'description': description
|
|
||||||
})
|
|
||||||
except Exception:
|
|
||||||
modules.append({
|
|
||||||
'name': module_name,
|
|
||||||
'path': module_path,
|
|
||||||
'description': "No description available"
|
|
||||||
})
|
|
||||||
|
|
||||||
return modules
|
return modules
|
||||||
|
|
||||||
@@ -297,55 +295,6 @@ def get_user_choice(prompt, max_choice):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def get_interface_selection(device):
|
|
||||||
"""Select which interface(s) to unbind/bind.
|
|
||||||
|
|
||||||
Default (Enter): all HID interfaces (class 03).
|
|
||||||
'a' selects all interfaces.
|
|
||||||
Comma-separated list selects specific interfaces.
|
|
||||||
"""
|
|
||||||
if not device.get('interfaces'):
|
|
||||||
return []
|
|
||||||
|
|
||||||
print_header("Interfaces")
|
|
||||||
for idx, iface in enumerate(device['interfaces'], 1):
|
|
||||||
driver_color = Colors.GREEN if iface['driver'] != "none" else Colors.YELLOW
|
|
||||||
print(f" {idx:>2}. {iface['name']}: class={iface['class']} subclass={iface['subclass']} protocol={iface['protocol']} driver={driver_color}{iface['driver']}{Colors.END}")
|
|
||||||
|
|
||||||
print("\nSelect interfaces to bind:")
|
|
||||||
print(" [Enter] AUTO: all HID interfaces (class 03)")
|
|
||||||
print(" a ALL interfaces")
|
|
||||||
print(" 1,3 Comma-separated list")
|
|
||||||
|
|
||||||
raw = input("Selection: ").strip().lower()
|
|
||||||
if raw == "":
|
|
||||||
picked = [i for i in device['interfaces'] if i['class'] == "03"]
|
|
||||||
if not picked:
|
|
||||||
print_warning("No HID interfaces found; selecting ALL interfaces.")
|
|
||||||
picked = list(device['interfaces'])
|
|
||||||
return picked
|
|
||||||
|
|
||||||
if raw == "a":
|
|
||||||
return list(device['interfaces'])
|
|
||||||
|
|
||||||
picked = []
|
|
||||||
parts = [p.strip() for p in raw.split(',') if p.strip()]
|
|
||||||
for p in parts:
|
|
||||||
try:
|
|
||||||
i = int(p)
|
|
||||||
if 1 <= i <= len(device['interfaces']):
|
|
||||||
picked.append(device['interfaces'][i - 1])
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if not picked:
|
|
||||||
print_warning("No valid interfaces selected; using AUTO (all HID interfaces).")
|
|
||||||
picked = [i for i in device['interfaces'] if i['class'] == "03"]
|
|
||||||
if not picked:
|
|
||||||
picked = list(device['interfaces'])
|
|
||||||
return picked
|
|
||||||
|
|
||||||
|
|
||||||
def unbind_device(device, interface=None):
|
def unbind_device(device, interface=None):
|
||||||
"""Unbind device interface from current driver"""
|
"""Unbind device interface from current driver"""
|
||||||
# If specific interface provided, unbind that interface
|
# If specific interface provided, unbind that interface
|
||||||
@@ -406,7 +355,8 @@ def load_module(module):
|
|||||||
"""Load kernel module"""
|
"""Load kernel module"""
|
||||||
try:
|
try:
|
||||||
print(f"Loading module {module['name']}...")
|
print(f"Loading module {module['name']}...")
|
||||||
result = subprocess.run(['insmod', module['path']], capture_output=True, text=True)
|
result = subprocess.run(['insmod', module['path']],
|
||||||
|
capture_output=True, text=True)
|
||||||
if result.returncode == 0:
|
if result.returncode == 0:
|
||||||
print_success(f"Successfully loaded {module['name']}")
|
print_success(f"Successfully loaded {module['name']}")
|
||||||
return True
|
return True
|
||||||
@@ -485,7 +435,7 @@ def bind_device(device, module, interface=None):
|
|||||||
print_error(f"Failed to bind interface: {e}")
|
print_error(f"Failed to bind interface: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Default behavior (kept for backwards compatibility): try boot mouse, then device.
|
# Otherwise try to bind all HID mouse interfaces (class 03, subclass 01, protocol 02)
|
||||||
target_interfaces = []
|
target_interfaces = []
|
||||||
for iface in device.get('interfaces', []):
|
for iface in device.get('interfaces', []):
|
||||||
# Look for HID Boot Mouse interfaces
|
# Look for HID Boot Mouse interfaces
|
||||||
@@ -532,35 +482,13 @@ def bind_device(device, module, interface=None):
|
|||||||
return success
|
return success
|
||||||
|
|
||||||
|
|
||||||
def bind_interface_to_driver(interface_name, driver_name):
|
|
||||||
"""Bind a specific USB interface back to a given driver name (sysfs)."""
|
|
||||||
driver_path = Path(f"/sys/bus/usb/drivers/{driver_name}")
|
|
||||||
bind_path = driver_path / "bind"
|
|
||||||
|
|
||||||
if not driver_path.exists():
|
|
||||||
print_warning(f"Cannot restore: driver path not found: {driver_path}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
if not bind_path.exists():
|
|
||||||
print_warning(f"Cannot restore: bind path not found: {bind_path}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
try:
|
|
||||||
print(f"Restoring interface {interface_name} to driver {driver_name}...")
|
|
||||||
bind_path.write_text(interface_name)
|
|
||||||
print_success(f"Restored {interface_name} to {driver_name}")
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
print_warning(f"Failed to restore interface {interface_name} to {driver_name}: {e}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def unload_module(module):
|
def unload_module(module):
|
||||||
"""Unload kernel module"""
|
"""Unload kernel module"""
|
||||||
driver_name = get_module_driver_name(module)
|
driver_name = get_module_driver_name(module)
|
||||||
try:
|
try:
|
||||||
print(f"Unloading module {driver_name}...")
|
print(f"Unloading module {driver_name}...")
|
||||||
result = subprocess.run(['rmmod', driver_name], capture_output=True, text=True)
|
result = subprocess.run(['rmmod', driver_name],
|
||||||
|
capture_output=True, text=True)
|
||||||
if result.returncode == 0:
|
if result.returncode == 0:
|
||||||
print_success(f"Successfully unloaded {driver_name}")
|
print_success(f"Successfully unloaded {driver_name}")
|
||||||
return True
|
return True
|
||||||
@@ -634,16 +562,12 @@ def main():
|
|||||||
print(f" Device: {selected_device['name']}")
|
print(f" Device: {selected_device['name']}")
|
||||||
print(f" Current driver: {selected_device['driver']}")
|
print(f" Current driver: {selected_device['driver']}")
|
||||||
|
|
||||||
# Step 2b: Select interfaces
|
# Show interfaces
|
||||||
selected_interfaces = get_interface_selection(selected_device)
|
if selected_device.get('interfaces'):
|
||||||
if not selected_interfaces:
|
print(f"\n Interfaces:")
|
||||||
print_warning("No interfaces available/selected; cannot bind.")
|
for iface in selected_device['interfaces']:
|
||||||
sys.exit(1)
|
driver_color = Colors.GREEN if iface['driver'] != "none" else Colors.YELLOW
|
||||||
|
print(f" {iface['name']}: class={iface['class']} subclass={iface['subclass']} protocol={iface['protocol']} driver={driver_color}{iface['driver']}{Colors.END}")
|
||||||
# Remember original per-interface drivers for restore attempts
|
|
||||||
original_interface_drivers = {}
|
|
||||||
for iface in selected_interfaces:
|
|
||||||
original_interface_drivers[iface['name']] = iface.get('driver', 'none')
|
|
||||||
|
|
||||||
# Step 3: List available kernel modules
|
# Step 3: List available kernel modules
|
||||||
if len(args.directories) > 1 or args.directories[0] != '.':
|
if len(args.directories) > 1 or args.directories[0] != '.':
|
||||||
@@ -670,14 +594,17 @@ def main():
|
|||||||
|
|
||||||
# Step 5: Confirm operation
|
# Step 5: Confirm operation
|
||||||
print(f"\n{Colors.YELLOW}This will:{Colors.END}")
|
print(f"\n{Colors.YELLOW}This will:{Colors.END}")
|
||||||
print(f" 1. Unbind {len(selected_interfaces)} interface(s) from current driver(s)")
|
if selected_device.get('interfaces'):
|
||||||
|
print(f" 1. Unbind interface(s) from current driver(s)")
|
||||||
|
else:
|
||||||
|
print(f" 1. Unbind {selected_device['name']} from {selected_device['driver']}")
|
||||||
if module_already_loaded:
|
if module_already_loaded:
|
||||||
print(f" 2. Unload existing module {selected_module['name']}")
|
print(f" 2. Unload existing module {selected_module['name']}")
|
||||||
print(f" 3. Load module {selected_module['name']} (fresh version)")
|
print(f" 3. Load module {selected_module['name']} (fresh version)")
|
||||||
print(f" 4. Bind selected interface(s) to the new driver")
|
print(f" 4. Bind interface(s) to the new driver")
|
||||||
else:
|
else:
|
||||||
print(f" 2. Load module {selected_module['name']}")
|
print(f" 2. Load module {selected_module['name']}")
|
||||||
print(f" 3. Bind selected interface(s) to the new driver")
|
print(f" 3. Bind interface(s) to the new driver")
|
||||||
|
|
||||||
confirm = input(f"\n{Colors.BOLD}Proceed? (yes/no): {Colors.END}").strip().lower()
|
confirm = input(f"\n{Colors.BOLD}Proceed? (yes/no): {Colors.END}").strip().lower()
|
||||||
if confirm not in ['yes', 'y']:
|
if confirm not in ['yes', 'y']:
|
||||||
@@ -687,11 +614,10 @@ def main():
|
|||||||
# Step 6: Perform operations
|
# Step 6: Perform operations
|
||||||
print_header("\nExecuting operations...")
|
print_header("\nExecuting operations...")
|
||||||
|
|
||||||
# Unbind selected interfaces from current drivers
|
# Unbind from current driver
|
||||||
for iface in selected_interfaces:
|
if not unbind_device(selected_device):
|
||||||
if not unbind_device(selected_device, iface):
|
print_error("Failed to unbind device. Aborting.")
|
||||||
print_error("Failed to unbind interface. Aborting.")
|
sys.exit(1)
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
# Unload module if already loaded
|
# Unload module if already loaded
|
||||||
if module_already_loaded:
|
if module_already_loaded:
|
||||||
@@ -705,36 +631,24 @@ def main():
|
|||||||
# Load new module
|
# Load new module
|
||||||
if not load_module(selected_module):
|
if not load_module(selected_module):
|
||||||
print_error("Failed to load module. Attempting to restore...")
|
print_error("Failed to load module. Attempting to restore...")
|
||||||
# Try to rebind each selected interface to its original driver
|
# Try to rebind to original driver if available
|
||||||
for iface in selected_interfaces:
|
if selected_device['driver'] != "none":
|
||||||
orig = original_interface_drivers.get(iface['name'], 'none')
|
bind_device(selected_device, {'name': selected_device['driver'] + '.ko'})
|
||||||
if orig != 'none':
|
|
||||||
bind_interface_to_driver(iface['name'], orig)
|
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# Give kernel time to auto-probe and bind
|
# Give kernel time to auto-probe and bind
|
||||||
print("Waiting for kernel to probe interfaces...")
|
print("Waiting for kernel to probe interfaces...")
|
||||||
time.sleep(0.5)
|
time.sleep(0.5)
|
||||||
|
|
||||||
# Bind selected interfaces to new driver
|
# Bind to new driver
|
||||||
bound_any = False
|
if not bind_device(selected_device, selected_module):
|
||||||
for iface in selected_interfaces:
|
print_error("Failed to bind device to new driver.")
|
||||||
if bind_device(selected_device, selected_module, iface):
|
print_warning("Device may be unbound. You might need to reconnect it or bind manually.")
|
||||||
bound_any = True
|
|
||||||
else:
|
|
||||||
# Restore interfaces that failed to bind to the new driver
|
|
||||||
orig = original_interface_drivers.get(iface['name'], 'none')
|
|
||||||
if orig != 'none':
|
|
||||||
bind_interface_to_driver(iface['name'], orig)
|
|
||||||
|
|
||||||
if not bound_any:
|
|
||||||
print_error("Failed to bind any interface to the new driver.")
|
|
||||||
print_warning("All selected interfaces were restored where possible. You might need to reconnect the device.")
|
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# Success
|
# Success
|
||||||
print_header("\nOperation completed successfully!")
|
print_header("\nOperation completed successfully!")
|
||||||
print(f"{Colors.GREEN}Device {selected_device['name']} interface(s) are now using the new driver{Colors.END}")
|
print(f"{Colors.GREEN}Device {selected_device['name']} is now using the new driver{Colors.END}")
|
||||||
|
|
||||||
# Offer to show new device status
|
# Offer to show new device status
|
||||||
print("\nVerifying device status...")
|
print("\nVerifying device status...")
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
|
|
||||||
.PHONY: all
|
|
||||||
|
|
||||||
obj-m += wasd.o
|
|
||||||
KVER := $(shell uname -r)
|
|
||||||
KDIR ?= $(firstword $(wildcard /lib/modules/$(KVER)/build) $(wildcard /usr/lib/modules/$(KVER)/build))
|
|
||||||
PWD := $(shell pwd)
|
|
||||||
OUT := $(PWD)/out
|
|
||||||
|
|
||||||
all:
|
|
||||||
@if [ -z "$(KDIR)" ]; then \
|
|
||||||
echo "ERROR: kernel build dir not found for $(KVER). Install kernel headers (e.g. linux-headers)"; \
|
|
||||||
exit 2; \
|
|
||||||
fi
|
|
||||||
mkdir -p $(OUT)
|
|
||||||
$(MAKE) -C $(KDIR) M=$(PWD) modules
|
|
||||||
-mv -f -- *.ko *.mod.c *.o .*.o *.mod modules.order .*.cmd *.symvers $(OUT)
|
|
||||||
|
|
||||||
clean:
|
|
||||||
@if [ -z "$(KDIR)" ]; then \
|
|
||||||
echo "ERROR: kernel build dir not found for $(KVER)."; \
|
|
||||||
exit 2; \
|
|
||||||
fi
|
|
||||||
$(MAKE) -C $(KDIR) M=$(PWD) clean
|
|
||||||
rm -rf $(OUT) *.cmd *.order *.mod *.o
|
|
||||||
@@ -1,223 +0,0 @@
|
|||||||
|
|
||||||
#include <linux/kernel.h>
|
|
||||||
#include <linux/module.h>
|
|
||||||
#include <linux/usb.h>
|
|
||||||
#include <linux/usb/ch9.h>
|
|
||||||
#include <linux/usb/input.h>
|
|
||||||
#include <linux/input.h>
|
|
||||||
#include <linux/slab.h>
|
|
||||||
|
|
||||||
#define DRV_NAME "usb_steeringwheel_wasd"
|
|
||||||
|
|
||||||
struct wheel_evt {
|
|
||||||
uint32_t buttons_be;
|
|
||||||
uint16_t rot_be;
|
|
||||||
uint8_t gas;
|
|
||||||
uint8_t brk;
|
|
||||||
uint8_t clt;
|
|
||||||
uint8_t gr_x;
|
|
||||||
uint8_t gr_y;
|
|
||||||
uint8_t gr_z;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct wheel {
|
|
||||||
struct usb_device *udev;
|
|
||||||
struct usb_interface *intf;
|
|
||||||
struct input_dev *input;
|
|
||||||
|
|
||||||
struct urb *irq_urb;
|
|
||||||
struct wheel_evt *irq_data;
|
|
||||||
dma_addr_t irq_dma;
|
|
||||||
int irq_len;
|
|
||||||
int irq_interval;
|
|
||||||
int irq_ep;
|
|
||||||
|
|
||||||
char phys[64];
|
|
||||||
atomic_t opened;
|
|
||||||
};
|
|
||||||
|
|
||||||
static int drv_open(struct input_dev *dev) {
|
|
||||||
struct wheel *w = input_get_drvdata(dev);
|
|
||||||
if (!w) return -ENODEV;
|
|
||||||
atomic_set(&w->opened, 1);
|
|
||||||
int ret;
|
|
||||||
if ((ret = usb_submit_urb(w->irq_urb, GFP_KERNEL))) {
|
|
||||||
atomic_set(&w->opened, 0);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drv_irq(struct urb *urb) {
|
|
||||||
// called every 2ms?
|
|
||||||
struct wheel *w = urb->context;
|
|
||||||
if (!w || !atomic_read(&w->opened))
|
|
||||||
return;
|
|
||||||
|
|
||||||
const int status = urb->status;
|
|
||||||
if (status) {
|
|
||||||
if (status == -ENOENT || status == -ECONNRESET || status == -ESHUTDOWN)
|
|
||||||
return;
|
|
||||||
dev_dbg(&w->intf->dev, "irq urb status %d\n", status);
|
|
||||||
goto resubmit;
|
|
||||||
}
|
|
||||||
|
|
||||||
const struct wheel_evt *data = w->irq_data;
|
|
||||||
const int rot = be16_to_cpu(data->buttons_be);
|
|
||||||
// TODO set keys according to ratio
|
|
||||||
input_report_key(w->input, KEY_W, data->gas <= 0x80);
|
|
||||||
input_report_key(w->input, KEY_S, data->brk <= 0x80);
|
|
||||||
input_report_key(w->input, KEY_A, rot <= 0x6000);
|
|
||||||
input_report_key(w->input, KEY_D, rot >= 0xA000);
|
|
||||||
input_sync(w->input);
|
|
||||||
|
|
||||||
resubmit:
|
|
||||||
usb_submit_urb(w->irq_urb, GFP_ATOMIC);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drv_close(struct input_dev *dev) {
|
|
||||||
struct wheel *w = input_get_drvdata(dev);
|
|
||||||
if (!w) return;
|
|
||||||
atomic_set(&w->opened, 0);
|
|
||||||
usb_kill_urb(w->irq_urb);
|
|
||||||
}
|
|
||||||
|
|
||||||
static int drv_probe(struct usb_interface *intf, const struct usb_device_id *id) {
|
|
||||||
struct usb_device *udev = interface_to_usbdev(intf);
|
|
||||||
int ret;
|
|
||||||
|
|
||||||
// Logitech G29
|
|
||||||
//if (le16_to_cpu(udev->descriptor.idVendor) != 0x046d || le16_to_cpu(udev->descriptor.idProduct) != 0xc24f)
|
|
||||||
// return -ENODEV;
|
|
||||||
|
|
||||||
struct usb_endpoint_descriptor *ep = NULL;
|
|
||||||
const struct usb_host_interface *alts = intf->cur_altsetting;
|
|
||||||
for (int i = 0; i < alts->desc.bNumEndpoints; i++) {
|
|
||||||
struct usb_endpoint_descriptor *d = &alts->endpoint[i].desc;
|
|
||||||
if (usb_endpoint_is_int_in(d)) {
|
|
||||||
ep = d;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!ep) return -ENODEV;
|
|
||||||
|
|
||||||
struct wheel *w;
|
|
||||||
if ((w = kzalloc(sizeof(*w), GFP_KERNEL)) == NULL)
|
|
||||||
return -ENOMEM;
|
|
||||||
|
|
||||||
w->udev = usb_get_dev(udev);
|
|
||||||
w->intf = intf;
|
|
||||||
atomic_set(&w->opened, 0);
|
|
||||||
|
|
||||||
w->irq_ep = usb_endpoint_num(ep);
|
|
||||||
w->irq_len = usb_endpoint_maxp(ep);
|
|
||||||
w->irq_interval = ep->bInterval;
|
|
||||||
|
|
||||||
if ((w->irq_urb = usb_alloc_urb(0, GFP_KERNEL)) == NULL) {
|
|
||||||
ret = -ENOMEM;
|
|
||||||
goto err_free;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((w->irq_data = usb_alloc_coherent(udev, w->irq_len, GFP_KERNEL, &w->irq_dma)) == NULL) {
|
|
||||||
ret = -ENOMEM;
|
|
||||||
goto err_free_urb;
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((w->input = input_allocate_device()) == NULL) {
|
|
||||||
ret = -ENOMEM;
|
|
||||||
goto err_free_buf;
|
|
||||||
}
|
|
||||||
|
|
||||||
usb_make_path(udev, w->phys, sizeof(w->phys));
|
|
||||||
strlcat(w->phys, "/input0", sizeof(w->phys));
|
|
||||||
|
|
||||||
w->input->name = "USB Boot Mouse (example driver)";
|
|
||||||
w->input->phys = w->phys;
|
|
||||||
usb_to_input_id(udev, &w->input->id);
|
|
||||||
w->input->dev.parent = &intf->dev;
|
|
||||||
|
|
||||||
w->input->open = drv_open;
|
|
||||||
w->input->close = drv_close;
|
|
||||||
|
|
||||||
input_set_drvdata(w->input, w);
|
|
||||||
|
|
||||||
usb_fill_int_urb(
|
|
||||||
w->irq_urb,
|
|
||||||
udev,
|
|
||||||
usb_rcvintpipe(udev, ep->bEndpointAddress),
|
|
||||||
w->irq_data,
|
|
||||||
w->irq_len,
|
|
||||||
drv_irq,
|
|
||||||
w,
|
|
||||||
w->irq_interval);
|
|
||||||
|
|
||||||
w->irq_urb->transfer_dma = w->irq_dma;
|
|
||||||
w->irq_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
|
|
||||||
|
|
||||||
usb_set_intfdata(intf, w);
|
|
||||||
|
|
||||||
if ((ret = input_register_device(w->input)) != 0)
|
|
||||||
goto err_clear_intfdata;
|
|
||||||
|
|
||||||
dev_info(&intf->dev,
|
|
||||||
"bound to %04x:%04x, int-in ep 0x%02x maxp %u interval %u\n",
|
|
||||||
le16_to_cpu(udev->descriptor.idVendor),
|
|
||||||
le16_to_cpu(udev->descriptor.idProduct),
|
|
||||||
ep->bEndpointAddress,
|
|
||||||
w->irq_len,
|
|
||||||
w->irq_interval);
|
|
||||||
|
|
||||||
return 0;
|
|
||||||
|
|
||||||
err_clear_intfdata:
|
|
||||||
usb_set_intfdata(intf, NULL);
|
|
||||||
input_free_device(w->input);
|
|
||||||
w->input = NULL;
|
|
||||||
err_free_buf:
|
|
||||||
usb_free_coherent(udev, w->irq_len, w->irq_data, w->irq_dma);
|
|
||||||
err_free_urb:
|
|
||||||
usb_free_urb(w->irq_urb);
|
|
||||||
err_free:
|
|
||||||
usb_put_dev(w->udev);
|
|
||||||
kfree(w);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drv_disconnect(struct usb_interface *intf) {
|
|
||||||
struct wheel *w = usb_get_intfdata(intf);
|
|
||||||
usb_set_intfdata(intf, NULL);
|
|
||||||
if (!w) return;
|
|
||||||
|
|
||||||
if (w->input) {
|
|
||||||
input_unregister_device(w->input);
|
|
||||||
w->input = NULL;
|
|
||||||
}
|
|
||||||
|
|
||||||
usb_kill_urb(w->irq_urb);
|
|
||||||
usb_free_coherent(w->udev, w->irq_len, w->irq_data, w->irq_dma);
|
|
||||||
usb_free_urb(w->irq_urb);
|
|
||||||
usb_put_dev(w->udev);
|
|
||||||
kfree(w);
|
|
||||||
|
|
||||||
dev_info(&intf->dev, "disconnected\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
static const struct usb_device_id drv_id_table[] = {
|
|
||||||
{ USB_DEVICE_INTERFACE_NUMBER(0x046d, 0xc24f, 0) },
|
|
||||||
{ USB_INTERFACE_INFO(3, 1, 1) },
|
|
||||||
{}
|
|
||||||
};
|
|
||||||
MODULE_DEVICE_TABLE(usb, drv_id_table);
|
|
||||||
|
|
||||||
static struct usb_driver drv = {
|
|
||||||
.name = DRV_NAME,
|
|
||||||
.probe = drv_probe,
|
|
||||||
.disconnect = drv_disconnect,
|
|
||||||
.id_table = drv_id_table,
|
|
||||||
};
|
|
||||||
|
|
||||||
module_usb_driver(drv);
|
|
||||||
|
|
||||||
MODULE_AUTHOR("Lorenz Stechauner");
|
|
||||||
MODULE_DESCRIPTION("Steering wheel WASD emulator");
|
|
||||||
MODULE_LICENSE("GPL");
|
|
||||||
Reference in New Issue
Block a user