Compare commits
9 Commits
a473f03b10
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 87217f1150 | |||
| aedde65362 | |||
| c77c23c6ed | |||
| 0e6a553740 | |||
|
|
3cc6115694 | ||
|
|
8ab4ca7533 | ||
|
|
6d5c467829 | ||
|
|
7162bf01a1 | ||
|
|
c5010eab08 |
42
.gitignore
vendored
Normal file
42
.gitignore
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
# IDE and Editor
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.DS_Store
|
||||
|
||||
# Dependencies
|
||||
node_modules/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.egg-info/
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# Build outputs
|
||||
dist/
|
||||
build/
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
*.ko
|
||||
*.mod
|
||||
*.mod.c
|
||||
*.cmd
|
||||
.*.cmd
|
||||
Module.symvers
|
||||
modules.order
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.local
|
||||
|
||||
# OS files
|
||||
Thumbs.db
|
||||
.DS_Store
|
||||
63
README.md
63
README.md
@@ -1,5 +1,62 @@
|
||||
# Device Drivers
|
||||
----------------------------------
|
||||
|
||||
Device Driver
|
||||
=============
|
||||
This repository contains Linux **kernel modules** (``.ko``) that implement low-level USB input drivers and expose device events through the Linux **input subsystem** (evdev).
|
||||
|
||||
[Logitech G29 USB Protocol](logitech-G29.md)
|
||||
A helper tool (``usb_driver_manager.py``) is included to make it easier to:
|
||||
- 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
|
||||
----------
|
||||
|
||||
### Mouse driver (``mouse/``)
|
||||
USB HID boot-protocol mouse driver.
|
||||
|
||||
**Build:**
|
||||
```bash
|
||||
cd mouse
|
||||
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
|
||||
---------------------
|
||||
|
||||
**Usage examples:**
|
||||
```bash
|
||||
# Search for modules in these driver directories (the tool searches recursively)
|
||||
sudo python3 usb_driver_manager.py ./mouse ./g29_media_usb
|
||||
|
||||
# Or point directly at build/ directories
|
||||
sudo python3 usb_driver_manager.py ./mouse/build ./g29_media_usb/build
|
||||
```
|
||||
|
||||
**Workflow:**
|
||||
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
|
||||
----------
|
||||
After binding the driver, use ``evtest`` to confirm key events:
|
||||
```bash
|
||||
sudo evtest
|
||||
```
|
||||
|
||||
14
g29-wheel/Makefile
Normal file
14
g29-wheel/Makefile
Normal file
@@ -0,0 +1,14 @@
|
||||
|
||||
.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
|
||||
326
g29-wheel/g29_usb.c
Normal file
326
g29-wheel/g29_usb.c
Normal file
@@ -0,0 +1,326 @@
|
||||
// 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>
|
||||
|
||||
MODULE_AUTHOR("LLP group 16");
|
||||
MODULE_DESCRIPTION("Logitech G29 USB driver");
|
||||
MODULE_LICENSE("GPL");
|
||||
|
||||
#define USB_VENDOR_ID_LOGITECH 0x046d
|
||||
#define USB_DEVICE_ID_LOGITECH_G29 0xc24f
|
||||
#define USB_DEVICE_ID_LOGITECH_G29_ALT 0xc260
|
||||
|
||||
#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_R1 0x00000100u
|
||||
#define G29_BTN_L1 0x00000200u
|
||||
|
||||
enum g29_mode {
|
||||
G29_MODE_MEDIA = 0,
|
||||
};
|
||||
|
||||
static int mode = G29_MODE_MEDIA;
|
||||
module_param(mode, int, 0444);
|
||||
MODULE_PARM_DESC(mode, "Mapping mode (0=MEDIA)");
|
||||
|
||||
struct g29_state {
|
||||
u32 buttons_le;
|
||||
u16 rot_le;
|
||||
u8 gas;
|
||||
u8 brk;
|
||||
u8 clt;
|
||||
u8 gr_x;
|
||||
u8 gr_y;
|
||||
u8 gr_z;
|
||||
};
|
||||
|
||||
struct g29_keymap_edge {
|
||||
u32 mask;
|
||||
unsigned short keycode;
|
||||
};
|
||||
|
||||
static const struct g29_keymap_edge g29_media_edge_map[] = {
|
||||
/* 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 },
|
||||
};
|
||||
|
||||
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;
|
||||
u32 steer_phase_ms;
|
||||
|
||||
struct g29_state last;
|
||||
};
|
||||
|
||||
|
||||
static void g29_steer_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);
|
||||
|
||||
input_report_key(g29->input, KEY_W, g29->last.gas <= 0x80);
|
||||
input_report_key(g29->input, KEY_S, g29->last.clt <= 0x80);
|
||||
input_report_key(g29->input, KEY_A, rot <= 0x6000);
|
||||
input_report_key(g29->input, KEY_D, rot >= 0xA000);
|
||||
|
||||
mod_timer(&g29->steer_timer, jiffies + msecs_to_jiffies(2));
|
||||
}
|
||||
|
||||
static void g29_apply_media_mode(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);
|
||||
for (int i = 0; i < ARRAY_SIZE(g29_media_edge_map); i++) {
|
||||
const struct g29_keymap_edge *e = &g29_media_edge_map[i];
|
||||
if (pressed & e->mask) {
|
||||
input_report_key(g29->input, e->keycode, 1);
|
||||
input_report_key(g29->input, e->keycode, 0);
|
||||
}
|
||||
}
|
||||
|
||||
input_sync(g29->input);
|
||||
}
|
||||
|
||||
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;
|
||||
switch (mode) {
|
||||
case G29_MODE_MEDIA:
|
||||
default:
|
||||
g29_apply_media_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;
|
||||
|
||||
mod_timer(&g29->steer_timer, jiffies + msecs_to_jiffies(2));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void g29_input_close(struct input_dev *input) {
|
||||
struct g29_dev *g29 = input_get_drvdata(input);
|
||||
timer_delete_sync(&g29->steer_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));
|
||||
|
||||
timer_setup(&g29->steer_timer, g29_steer_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);
|
||||
|
||||
/* Advertise only the keys we emit in media mode. */
|
||||
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);
|
||||
|
||||
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);
|
||||
|
||||
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);
|
||||
39
mouse/Makefile
Normal file
39
mouse/Makefile
Normal file
@@ -0,0 +1,39 @@
|
||||
obj-m += simple_usb_mouse.o
|
||||
obj-m += gesture_usb_mouse.o
|
||||
|
||||
PWD := $(CURDIR)
|
||||
KDIR := /lib/modules/$(shell uname -r)/build
|
||||
|
||||
# Function to organize build artifacts
|
||||
# Usage: $(call organize_build,pattern)
|
||||
define organize_build
|
||||
mkdir -p build
|
||||
mv -f *.o *.ko *.mod *.mod.c Module.symvers modules.order build/ 2>/dev/null || true
|
||||
find . -maxdepth 1 -name '.*.cmd' -exec mv {} build/ \; 2>/dev/null || true
|
||||
find . -maxdepth 1 -name '.*.o' -exec mv {} build/ \; 2>/dev/null || true
|
||||
[ -d .tmp_versions ] && mv .tmp_versions build/ || true
|
||||
endef
|
||||
|
||||
all:
|
||||
make -C $(KDIR) M=$(PWD) modules
|
||||
$(call organize_build)
|
||||
simple:
|
||||
make -C $(KDIR) M=$(PWD) simple_usb_mouse.ko
|
||||
$(call organize_build)
|
||||
|
||||
gesture:
|
||||
make -C $(KDIR) M=$(PWD) gesture_usb_mouse.ko
|
||||
$(call organize_build)
|
||||
|
||||
clean:
|
||||
make -C $(KDIR) M=$(PWD) clean
|
||||
rm -rf build
|
||||
|
||||
install:
|
||||
make -C $(KDIR) M=$(PWD) modules_install
|
||||
depmod -a
|
||||
|
||||
uninstall:
|
||||
rm -f /lib/modules/$(shell uname -r)/kernel/drivers/usb/input/simple_usb_mouse.ko
|
||||
rm -f /lib/modules/$(shell uname -r)/kernel/drivers/usb/input/gesture_usb_mouse.ko
|
||||
depmod -a
|
||||
675
mouse/gesture_usb_mouse.c
Normal file
675
mouse/gesture_usb_mouse.c
Normal file
@@ -0,0 +1,675 @@
|
||||
// SPDX-License-Identifier: GPL-2.0
|
||||
/*
|
||||
* Gesture USB Mouse Driver
|
||||
*
|
||||
* A USB HID Boot Protocol mouse driver with gesture recognition.
|
||||
* Detects shapes like "C" (copy) and "V" (paste) and sends keyboard events.
|
||||
* Based on simple_usb_mouse.c
|
||||
*/
|
||||
|
||||
#include <linux/kernel.h>
|
||||
#include <linux/slab.h>
|
||||
#include <linux/module.h>
|
||||
#include <linux/init.h>
|
||||
#include <linux/usb.h>
|
||||
#include <linux/usb/input.h>
|
||||
#include <linux/hid.h>
|
||||
#include <linux/input.h>
|
||||
#include <linux/jiffies.h>
|
||||
|
||||
#define DRIVER_AUTHOR "Testor"
|
||||
#define DRIVER_DESC "Gesture USB Mouse Driver"
|
||||
|
||||
MODULE_AUTHOR(DRIVER_AUTHOR);
|
||||
MODULE_DESCRIPTION(DRIVER_DESC);
|
||||
MODULE_LICENSE("GPL");
|
||||
|
||||
/* Gesture detection parameters */
|
||||
#define HISTORY_SIZE 100 /* Number of movement samples to track */
|
||||
#define GESTURE_MIN_DISTANCE 150 /* Minimum total distance for gesture */
|
||||
#define GESTURE_TIMEOUT_MS 1500 /* Max time for a gesture (ms) */
|
||||
#define MOVEMENT_THRESHOLD 3 /* Ignore tiny movements (noise reduction) */
|
||||
|
||||
/* Module parameters for tuning */
|
||||
static int gesture_enabled = 1;
|
||||
module_param(gesture_enabled, int, 0644);
|
||||
MODULE_PARM_DESC(gesture_enabled, "Enable gesture recognition (default: 1)");
|
||||
|
||||
static int gesture_min_distance = GESTURE_MIN_DISTANCE;
|
||||
module_param(gesture_min_distance, int, 0644);
|
||||
MODULE_PARM_DESC(gesture_min_distance, "Minimum distance for gesture detection");
|
||||
|
||||
static int debug_gestures = 0;
|
||||
module_param(debug_gestures, int, 0644);
|
||||
MODULE_PARM_DESC(debug_gestures, "Print debug info for gestures (default: 0)");
|
||||
|
||||
static int gesture_button = 2;
|
||||
module_param(gesture_button, int, 0644);
|
||||
MODULE_PARM_DESC(gesture_button, "Button for gestures (1=left, 2=middle, 3=right, default: 2)");
|
||||
|
||||
/*
|
||||
* Movement point for gesture tracking
|
||||
*/
|
||||
struct movement_point {
|
||||
int16_t x;
|
||||
int16_t y;
|
||||
unsigned long timestamp;
|
||||
};
|
||||
|
||||
/*
|
||||
* Gesture statistics for debugging
|
||||
*/
|
||||
struct gesture_stats {
|
||||
unsigned long c_detected;
|
||||
unsigned long v_detected;
|
||||
unsigned long invalid;
|
||||
};
|
||||
|
||||
/*
|
||||
* Driver context structure
|
||||
*/
|
||||
struct gesture_usb_mouse {
|
||||
char name[128];
|
||||
char phys[64];
|
||||
struct usb_device *usbdev;
|
||||
struct input_dev *input_dev;
|
||||
struct urb *irq;
|
||||
unsigned char *data;
|
||||
dma_addr_t data_dma;
|
||||
|
||||
/* Gesture detection state */
|
||||
struct movement_point history[HISTORY_SIZE];
|
||||
int history_index;
|
||||
int history_count;
|
||||
unsigned long gesture_start_time;
|
||||
int total_distance;
|
||||
bool gesture_in_progress;
|
||||
bool gesture_button_held;
|
||||
|
||||
/* Statistics */
|
||||
struct gesture_stats stats;
|
||||
};
|
||||
|
||||
/*
|
||||
* Calculate distance between two points
|
||||
*/
|
||||
static int calculate_distance(int16_t x1, int16_t y1, int16_t x2, int16_t y2)
|
||||
{
|
||||
int dx = x2 - x1;
|
||||
int dy = y2 - y1;
|
||||
/* Approximate distance: max(|dx|, |dy|) + min(|dx|, |dy|)/2 */
|
||||
int adx = dx < 0 ? -dx : dx;
|
||||
int ady = dy < 0 ? -dy : dy;
|
||||
return (adx > ady) ? (adx + ady/2) : (ady + adx/2);
|
||||
}
|
||||
|
||||
/*
|
||||
* Send keyboard shortcut
|
||||
*/
|
||||
static void send_keyboard_shortcut(struct input_dev *dev, unsigned int key)
|
||||
{
|
||||
/* Press Ctrl+Key */
|
||||
input_report_key(dev, KEY_LEFTCTRL, 1);
|
||||
input_report_key(dev, key, 1);
|
||||
input_sync(dev);
|
||||
|
||||
/* Release Key+Ctrl */
|
||||
input_report_key(dev, key, 0);
|
||||
input_report_key(dev, KEY_LEFTCTRL, 0);
|
||||
input_sync(dev);
|
||||
}
|
||||
|
||||
/*
|
||||
* Detect "C" shape gesture
|
||||
* C shape: starts from right, curves left and down, then right
|
||||
* Pattern: movement goes left with downward curve, then curves back right
|
||||
*/
|
||||
static bool detect_c_gesture(struct gesture_usb_mouse *mouse)
|
||||
{
|
||||
int i;
|
||||
int left_count = 0, right_count = 0;
|
||||
int down_count = 0, up_count = 0;
|
||||
int start_idx, end_idx;
|
||||
int16_t start_x, start_y, end_x, end_y;
|
||||
int width, height;
|
||||
|
||||
if (mouse->history_count < 20)
|
||||
return false;
|
||||
|
||||
/* Get start and end points */
|
||||
start_idx = (mouse->history_index - mouse->history_count + HISTORY_SIZE) % HISTORY_SIZE;
|
||||
end_idx = (mouse->history_index - 1 + HISTORY_SIZE) % HISTORY_SIZE;
|
||||
|
||||
start_x = mouse->history[start_idx].x;
|
||||
start_y = mouse->history[start_idx].y;
|
||||
end_x = mouse->history[end_idx].x;
|
||||
end_y = mouse->history[end_idx].y;
|
||||
|
||||
/* Analyze movement directions */
|
||||
for (i = 1; i < mouse->history_count; i++) {
|
||||
int idx = (start_idx + i) % HISTORY_SIZE;
|
||||
int prev_idx = (start_idx + i - 1 + HISTORY_SIZE) % HISTORY_SIZE;
|
||||
|
||||
int16_t dx = mouse->history[idx].x - mouse->history[prev_idx].x;
|
||||
int16_t dy = mouse->history[idx].y - mouse->history[prev_idx].y;
|
||||
|
||||
if (dx < -MOVEMENT_THRESHOLD) left_count++;
|
||||
if (dx > MOVEMENT_THRESHOLD) right_count++;
|
||||
if (dy < -MOVEMENT_THRESHOLD) up_count++;
|
||||
if (dy > MOVEMENT_THRESHOLD) down_count++;
|
||||
}
|
||||
|
||||
width = (end_x > start_x) ? (end_x - start_x) : (start_x - end_x);
|
||||
height = (end_y > start_y) ? (end_y - start_y) : (start_y - end_y);
|
||||
|
||||
/* C shape criteria:
|
||||
* - More leftward movement than rightward (opening faces left)
|
||||
* - Significant downward movement
|
||||
* - Start and end X positions are similar (closed C shape)
|
||||
* - Height is reasonable compared to width
|
||||
*/
|
||||
bool is_c = (left_count * 2 > right_count * 3) &&
|
||||
(down_count > up_count) &&
|
||||
(width > 40) &&
|
||||
(height > 30) &&
|
||||
(width < height * 2);
|
||||
|
||||
if (debug_gestures && is_c) {
|
||||
pr_info("gesture_mouse: C detected - L:%d R:%d D:%d U:%d W:%d H:%d\n",
|
||||
left_count, right_count, down_count, up_count, width, height);
|
||||
}
|
||||
|
||||
return is_c;
|
||||
}
|
||||
|
||||
/*
|
||||
* Detect "V" shape gesture
|
||||
* V shape: starts up, goes down-right or down-left, then up in opposite direction
|
||||
* Pattern: down-slope followed by up-slope
|
||||
*/
|
||||
static bool detect_v_gesture(struct gesture_usb_mouse *mouse)
|
||||
{
|
||||
int i, turning_point = -1;
|
||||
int down_before = 0, up_after = 0;
|
||||
int start_idx, end_idx;
|
||||
int16_t start_y, end_y, lowest_y;
|
||||
int height_before = 0, height_after = 0;
|
||||
|
||||
if (mouse->history_count < 15)
|
||||
return false;
|
||||
|
||||
start_idx = (mouse->history_index - mouse->history_count + HISTORY_SIZE) % HISTORY_SIZE;
|
||||
end_idx = (mouse->history_index - 1 + HISTORY_SIZE) % HISTORY_SIZE;
|
||||
|
||||
start_y = mouse->history[start_idx].y;
|
||||
end_y = mouse->history[end_idx].y;
|
||||
lowest_y = start_y;
|
||||
|
||||
/* Find the turning point (lowest Y value) */
|
||||
for (i = 0; i < mouse->history_count; i++) {
|
||||
int idx = (start_idx + i) % HISTORY_SIZE;
|
||||
if (mouse->history[idx].y > lowest_y) {
|
||||
lowest_y = mouse->history[idx].y;
|
||||
turning_point = i;
|
||||
}
|
||||
}
|
||||
|
||||
if (turning_point <= 0 || turning_point >= mouse->history_count - 1)
|
||||
return false;
|
||||
|
||||
/* Count down movements before turning point */
|
||||
for (i = 1; i <= turning_point; i++) {
|
||||
int idx = (start_idx + i) % HISTORY_SIZE;
|
||||
int prev_idx = (start_idx + i - 1 + HISTORY_SIZE) % HISTORY_SIZE;
|
||||
|
||||
int16_t dy = mouse->history[idx].y - mouse->history[prev_idx].y;
|
||||
if (dy > MOVEMENT_THRESHOLD) {
|
||||
down_before++;
|
||||
height_before += dy;
|
||||
}
|
||||
}
|
||||
|
||||
/* Count up movements after turning point */
|
||||
for (i = turning_point + 1; i < mouse->history_count; i++) {
|
||||
int idx = (start_idx + i) % HISTORY_SIZE;
|
||||
int prev_idx = (start_idx + i - 1 + HISTORY_SIZE) % HISTORY_SIZE;
|
||||
|
||||
int16_t dy = mouse->history[idx].y - mouse->history[prev_idx].y;
|
||||
if (dy < -MOVEMENT_THRESHOLD) {
|
||||
up_after++;
|
||||
height_after -= dy;
|
||||
}
|
||||
}
|
||||
|
||||
/* V shape criteria:
|
||||
* - Significant downward movement in first half
|
||||
* - Significant upward movement in second half
|
||||
* - Both sides have reasonable height
|
||||
* - Turning point is roughly in the middle
|
||||
*/
|
||||
bool is_v = (down_before > 5) &&
|
||||
(up_after > 5) &&
|
||||
(height_before > 40) &&
|
||||
(height_after > 40) &&
|
||||
(turning_point > mouse->history_count / 4) &&
|
||||
(turning_point < mouse->history_count * 3 / 4);
|
||||
|
||||
if (debug_gestures && is_v) {
|
||||
pr_info("gesture_mouse: V detected - Down:%d Up:%d HB:%d HA:%d Turn:%d/%d\n",
|
||||
down_before, up_after, height_before, height_after,
|
||||
turning_point, mouse->history_count);
|
||||
}
|
||||
|
||||
return is_v;
|
||||
}
|
||||
|
||||
/*
|
||||
* Process accumulated gesture data
|
||||
*/
|
||||
static void process_gesture(struct gesture_usb_mouse *mouse)
|
||||
{
|
||||
if (!gesture_enabled)
|
||||
return;
|
||||
|
||||
if (mouse->total_distance < gesture_min_distance) {
|
||||
if (debug_gestures)
|
||||
pr_info("gesture_mouse: Gesture too short (%d < %d)\n",
|
||||
mouse->total_distance, gesture_min_distance);
|
||||
return;
|
||||
}
|
||||
|
||||
/* Try to detect gestures */
|
||||
if (detect_c_gesture(mouse)) {
|
||||
pr_info("gesture_mouse: C gesture detected - triggering COPY\n");
|
||||
send_keyboard_shortcut(mouse->input_dev, KEY_C);
|
||||
mouse->stats.c_detected++;
|
||||
} else if (detect_v_gesture(mouse)) {
|
||||
pr_info("gesture_mouse: V gesture detected - triggering PASTE\n");
|
||||
send_keyboard_shortcut(mouse->input_dev, KEY_V);
|
||||
mouse->stats.v_detected++;
|
||||
} else {
|
||||
if (debug_gestures)
|
||||
pr_info("gesture_mouse: No gesture matched (distance: %d, samples: %d)\n",
|
||||
mouse->total_distance, mouse->history_count);
|
||||
mouse->stats.invalid++;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Reset gesture tracking state
|
||||
*/
|
||||
static void reset_gesture_tracking(struct gesture_usb_mouse *mouse)
|
||||
{
|
||||
mouse->history_count = 0;
|
||||
mouse->history_index = 0;
|
||||
mouse->gesture_in_progress = false;
|
||||
mouse->total_distance = 0;
|
||||
mouse->gesture_start_time = 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Add movement to gesture history
|
||||
*/
|
||||
static void add_movement(struct gesture_usb_mouse *mouse, int16_t dx, int16_t dy)
|
||||
{
|
||||
struct movement_point *point;
|
||||
int distance;
|
||||
|
||||
if (!mouse->gesture_in_progress)
|
||||
return;
|
||||
|
||||
/* Ignore very small movements (noise) */
|
||||
if (dx < MOVEMENT_THRESHOLD && dx > -MOVEMENT_THRESHOLD &&
|
||||
dy < MOVEMENT_THRESHOLD && dy > -MOVEMENT_THRESHOLD)
|
||||
return;
|
||||
|
||||
/* Check for timeout */
|
||||
if (time_after(jiffies, mouse->gesture_start_time + msecs_to_jiffies(GESTURE_TIMEOUT_MS))) {
|
||||
if (debug_gestures)
|
||||
pr_info("gesture_mouse: Gesture timeout\n");
|
||||
process_gesture(mouse);
|
||||
reset_gesture_tracking(mouse);
|
||||
return;
|
||||
}
|
||||
|
||||
/* Calculate cumulative position */
|
||||
point = &mouse->history[mouse->history_index];
|
||||
if (mouse->history_count > 0) {
|
||||
int prev_idx = (mouse->history_index - 1 + HISTORY_SIZE) % HISTORY_SIZE;
|
||||
point->x = mouse->history[prev_idx].x + dx;
|
||||
point->y = mouse->history[prev_idx].y + dy;
|
||||
|
||||
distance = calculate_distance(mouse->history[prev_idx].x, mouse->history[prev_idx].y,
|
||||
point->x, point->y);
|
||||
mouse->total_distance += distance;
|
||||
} else {
|
||||
point->x = 0;
|
||||
point->y = 0;
|
||||
}
|
||||
|
||||
point->timestamp = jiffies;
|
||||
|
||||
mouse->history_index = (mouse->history_index + 1) % HISTORY_SIZE;
|
||||
if (mouse->history_count < HISTORY_SIZE)
|
||||
mouse->history_count++;
|
||||
}
|
||||
|
||||
/*
|
||||
* IRQ handler - called when mouse sends data
|
||||
*/
|
||||
static void gesture_mouse_irq(struct urb *urb)
|
||||
{
|
||||
struct gesture_usb_mouse *mouse = urb->context;
|
||||
unsigned char *data = mouse->data;
|
||||
struct input_dev *dev = mouse->input_dev;
|
||||
int status;
|
||||
int16_t x_movement, y_movement;
|
||||
bool gesture_button_pressed;
|
||||
|
||||
/* Check URB status */
|
||||
switch (urb->status) {
|
||||
case 0:
|
||||
break;
|
||||
case -ECONNRESET:
|
||||
case -ENOENT:
|
||||
case -ESHUTDOWN:
|
||||
pr_debug("gesture_mouse: URB stopped (status %d)\n", urb->status);
|
||||
return;
|
||||
default:
|
||||
pr_debug("gesture_mouse: URB error (status %d)\n", urb->status);
|
||||
goto resubmit;
|
||||
}
|
||||
|
||||
/* Extract movement data */
|
||||
x_movement = (int16_t)(data[2] | (data[3] << 8));
|
||||
y_movement = (int16_t)(data[4] | (data[5] << 8));
|
||||
|
||||
/* Determine which button activates gestures */
|
||||
switch (gesture_button) {
|
||||
case 1: gesture_button_pressed = (data[0] & 0x01) != 0; break; /* Left */
|
||||
case 2: gesture_button_pressed = (data[0] & 0x04) != 0; break; /* Middle */
|
||||
case 3: gesture_button_pressed = (data[0] & 0x02) != 0; break; /* Right */
|
||||
default: gesture_button_pressed = false; break;
|
||||
}
|
||||
|
||||
/* Gesture tracking logic */
|
||||
if (gesture_enabled && gesture_button != 0) {
|
||||
/* Start gesture when gesture button is pressed */
|
||||
if (gesture_button_pressed && !mouse->gesture_button_held) {
|
||||
reset_gesture_tracking(mouse);
|
||||
mouse->gesture_in_progress = true;
|
||||
mouse->gesture_start_time = jiffies;
|
||||
if (debug_gestures)
|
||||
pr_info("gesture_mouse: Gesture started\n");
|
||||
}
|
||||
|
||||
/* Track movements while gesture button is held */
|
||||
if (gesture_button_pressed && mouse->gesture_in_progress) {
|
||||
add_movement(mouse, x_movement, y_movement);
|
||||
}
|
||||
|
||||
/* End gesture when gesture button is released */
|
||||
if (!gesture_button_pressed && mouse->gesture_button_held && mouse->gesture_in_progress) {
|
||||
if (debug_gestures)
|
||||
pr_info("gesture_mouse: Gesture ended (dist: %d, samples: %d)\n",
|
||||
mouse->total_distance, mouse->history_count);
|
||||
process_gesture(mouse);
|
||||
reset_gesture_tracking(mouse);
|
||||
}
|
||||
|
||||
mouse->gesture_button_held = gesture_button_pressed;
|
||||
}
|
||||
|
||||
/* Report normal mouse events */
|
||||
input_report_key(dev, BTN_LEFT, data[0] & 0x01);
|
||||
input_report_key(dev, BTN_RIGHT, data[0] & 0x02);
|
||||
//input_report_key(dev, BTN_MIDDLE, data[0] & 0x04);
|
||||
input_report_key(dev, BTN_SIDE, data[0] & 0x08);
|
||||
input_report_key(dev, BTN_EXTRA, data[0] & 0x10);
|
||||
|
||||
input_report_rel(dev, REL_X, x_movement);
|
||||
input_report_rel(dev, REL_Y, y_movement);
|
||||
input_report_rel(dev, REL_WHEEL, (signed char) data[6]);
|
||||
|
||||
input_sync(dev);
|
||||
|
||||
resubmit:
|
||||
status = usb_submit_urb(urb, GFP_ATOMIC);
|
||||
if (status) {
|
||||
dev_err(&mouse->usbdev->dev,
|
||||
"Failed to resubmit URB: %d\n", status);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Device open callback
|
||||
*/
|
||||
static int gesture_mouse_open(struct input_dev *dev)
|
||||
{
|
||||
struct gesture_usb_mouse *mouse = input_get_drvdata(dev);
|
||||
|
||||
pr_info("gesture_mouse: Device opened\n");
|
||||
|
||||
mouse->irq->dev = mouse->usbdev;
|
||||
if (usb_submit_urb(mouse->irq, GFP_KERNEL)) {
|
||||
pr_err("gesture_mouse: Failed to submit URB on open\n");
|
||||
return -EIO;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Device close callback
|
||||
*/
|
||||
static void gesture_mouse_close(struct input_dev *dev)
|
||||
{
|
||||
struct gesture_usb_mouse *mouse = input_get_drvdata(dev);
|
||||
|
||||
pr_info("gesture_mouse: Device closed\n");
|
||||
pr_info("gesture_mouse: Stats - C:%lu V:%lu Invalid:%lu\n",
|
||||
mouse->stats.c_detected, mouse->stats.v_detected, mouse->stats.invalid);
|
||||
usb_kill_urb(mouse->irq);
|
||||
}
|
||||
|
||||
/*
|
||||
* Probe function
|
||||
*/
|
||||
static int gesture_mouse_probe(struct usb_interface *intf,
|
||||
const struct usb_device_id *id)
|
||||
{
|
||||
struct usb_device *usbdev = interface_to_usbdev(intf);
|
||||
struct usb_host_interface *interface;
|
||||
struct usb_endpoint_descriptor *endpoint;
|
||||
struct gesture_usb_mouse *mouse;
|
||||
struct input_dev *input_dev;
|
||||
int pipe, maxp;
|
||||
int error = -ENOMEM;
|
||||
|
||||
pr_info("gesture_mouse: Probing device %04x:%04x\n",
|
||||
le16_to_cpu(usbdev->descriptor.idVendor),
|
||||
le16_to_cpu(usbdev->descriptor.idProduct));
|
||||
|
||||
interface = intf->cur_altsetting;
|
||||
|
||||
if (interface->desc.bNumEndpoints != 1) {
|
||||
pr_err("gesture_mouse: Interface has %d endpoints (expected 1)\n",
|
||||
interface->desc.bNumEndpoints);
|
||||
return -ENODEV;
|
||||
}
|
||||
|
||||
endpoint = &interface->endpoint[0].desc;
|
||||
|
||||
if (!usb_endpoint_is_int_in(endpoint)) {
|
||||
pr_err("gesture_mouse: Endpoint is not interrupt IN\n");
|
||||
return -ENODEV;
|
||||
}
|
||||
|
||||
pipe = usb_rcvintpipe(usbdev, endpoint->bEndpointAddress);
|
||||
maxp = usb_maxpacket(usbdev, pipe);
|
||||
|
||||
mouse = kzalloc(sizeof(struct gesture_usb_mouse), GFP_KERNEL);
|
||||
if (!mouse)
|
||||
return -ENOMEM;
|
||||
|
||||
input_dev = input_allocate_device();
|
||||
if (!input_dev) {
|
||||
pr_err("gesture_mouse: Failed to allocate input device\n");
|
||||
goto fail_input_alloc;
|
||||
}
|
||||
|
||||
mouse->data = usb_alloc_coherent(usbdev, 8, GFP_KERNEL, &mouse->data_dma);
|
||||
if (!mouse->data) {
|
||||
pr_err("gesture_mouse: Failed to allocate DMA buffer\n");
|
||||
goto fail_dma_alloc;
|
||||
}
|
||||
|
||||
mouse->irq = usb_alloc_urb(0, GFP_KERNEL);
|
||||
if (!mouse->irq) {
|
||||
pr_err("gesture_mouse: Failed to allocate URB\n");
|
||||
goto fail_urb_alloc;
|
||||
}
|
||||
|
||||
mouse->usbdev = usbdev;
|
||||
mouse->input_dev = input_dev;
|
||||
|
||||
/* Build device name */
|
||||
if (usbdev->manufacturer)
|
||||
strscpy(mouse->name, usbdev->manufacturer, sizeof(mouse->name));
|
||||
|
||||
if (usbdev->product) {
|
||||
if (usbdev->manufacturer)
|
||||
strlcat(mouse->name, " ", sizeof(mouse->name));
|
||||
strlcat(mouse->name, usbdev->product, sizeof(mouse->name));
|
||||
}
|
||||
|
||||
if (!strlen(mouse->name)) {
|
||||
snprintf(mouse->name, sizeof(mouse->name),
|
||||
"Gesture USB Mouse %04x:%04x",
|
||||
le16_to_cpu(usbdev->descriptor.idVendor),
|
||||
le16_to_cpu(usbdev->descriptor.idProduct));
|
||||
} else {
|
||||
strlcat(mouse->name, " [Gesture]", sizeof(mouse->name));
|
||||
}
|
||||
|
||||
usb_make_path(usbdev, mouse->phys, sizeof(mouse->phys));
|
||||
strlcat(mouse->phys, "/input0", sizeof(mouse->phys));
|
||||
|
||||
pr_info("gesture_mouse: Device name: %s\n", mouse->name);
|
||||
pr_info("gesture_mouse: Physical path: %s\n", mouse->phys);
|
||||
pr_info("gesture_mouse: Gesture detection: %s\n",
|
||||
gesture_enabled ? "ENABLED" : "DISABLED");
|
||||
|
||||
/* Configure input device */
|
||||
input_dev->name = mouse->name;
|
||||
input_dev->phys = mouse->phys;
|
||||
usb_to_input_id(usbdev, &input_dev->id);
|
||||
input_dev->dev.parent = &intf->dev;
|
||||
|
||||
/* Set event types - include KEY events for keyboard shortcuts */
|
||||
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
|
||||
|
||||
/* Mouse buttons */
|
||||
input_dev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |
|
||||
BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_MIDDLE);
|
||||
input_dev->keybit[BIT_WORD(BTN_MOUSE)] |= BIT_MASK(BTN_SIDE) |
|
||||
BIT_MASK(BTN_EXTRA);
|
||||
|
||||
/* Keyboard keys for gestures */
|
||||
input_set_capability(input_dev, EV_KEY, KEY_LEFTCTRL);
|
||||
input_set_capability(input_dev, EV_KEY, KEY_C);
|
||||
input_set_capability(input_dev, EV_KEY, KEY_V);
|
||||
|
||||
/* Relative axes */
|
||||
input_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y) | BIT_MASK(REL_WHEEL);
|
||||
|
||||
input_set_drvdata(input_dev, mouse);
|
||||
input_dev->open = gesture_mouse_open;
|
||||
input_dev->close = gesture_mouse_close;
|
||||
|
||||
/* Initialize URB */
|
||||
usb_fill_int_urb(mouse->irq, usbdev, pipe, mouse->data,
|
||||
(maxp > 8 ? 8 : maxp),
|
||||
gesture_mouse_irq, mouse, endpoint->bInterval);
|
||||
mouse->irq->transfer_dma = mouse->data_dma;
|
||||
mouse->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
|
||||
|
||||
/* Initialize gesture tracking */
|
||||
reset_gesture_tracking(mouse);
|
||||
memset(&mouse->stats, 0, sizeof(mouse->stats));
|
||||
|
||||
/* Register input device */
|
||||
error = input_register_device(mouse->input_dev);
|
||||
if (error) {
|
||||
pr_err("gesture_mouse: Failed to register input device: %d\n", error);
|
||||
goto fail_register;
|
||||
}
|
||||
|
||||
usb_set_intfdata(intf, mouse);
|
||||
|
||||
pr_info("gesture_mouse: Probe successful!\n");
|
||||
return 0;
|
||||
|
||||
fail_register:
|
||||
usb_free_urb(mouse->irq);
|
||||
fail_urb_alloc:
|
||||
usb_free_coherent(usbdev, 8, mouse->data, mouse->data_dma);
|
||||
fail_dma_alloc:
|
||||
input_free_device(input_dev);
|
||||
fail_input_alloc:
|
||||
kfree(mouse);
|
||||
return error;
|
||||
}
|
||||
|
||||
/*
|
||||
* Disconnect function
|
||||
*/
|
||||
static void gesture_mouse_disconnect(struct usb_interface *intf)
|
||||
{
|
||||
struct gesture_usb_mouse *mouse = usb_get_intfdata(intf);
|
||||
|
||||
pr_info("gesture_mouse: Device disconnected\n");
|
||||
|
||||
usb_set_intfdata(intf, NULL);
|
||||
|
||||
if (mouse) {
|
||||
pr_info("gesture_mouse: Final stats - C:%lu V:%lu Invalid:%lu\n",
|
||||
mouse->stats.c_detected, mouse->stats.v_detected,
|
||||
mouse->stats.invalid);
|
||||
|
||||
usb_kill_urb(mouse->irq);
|
||||
input_unregister_device(mouse->input_dev);
|
||||
usb_free_urb(mouse->irq);
|
||||
usb_free_coherent(interface_to_usbdev(intf), 8,
|
||||
mouse->data, mouse->data_dma);
|
||||
kfree(mouse);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Device ID table - same as simple_usb_mouse
|
||||
*/
|
||||
static const struct usb_device_id gesture_mouse_id_table[] = {
|
||||
{
|
||||
USB_INTERFACE_INFO(
|
||||
USB_INTERFACE_CLASS_HID,
|
||||
USB_INTERFACE_SUBCLASS_BOOT,
|
||||
USB_INTERFACE_PROTOCOL_MOUSE
|
||||
)
|
||||
},
|
||||
{ }
|
||||
};
|
||||
|
||||
MODULE_DEVICE_TABLE(usb, gesture_mouse_id_table);
|
||||
|
||||
/*
|
||||
* USB Driver structure
|
||||
*/
|
||||
static struct usb_driver gesture_mouse_driver = {
|
||||
.name = "gesture_usb_mouse",
|
||||
.probe = gesture_mouse_probe,
|
||||
.disconnect = gesture_mouse_disconnect,
|
||||
.id_table = gesture_mouse_id_table,
|
||||
};
|
||||
|
||||
module_usb_driver(gesture_mouse_driver);
|
||||
357
mouse/simple_usb_mouse.c
Normal file
357
mouse/simple_usb_mouse.c
Normal file
@@ -0,0 +1,357 @@
|
||||
// SPDX-License-Identifier: GPL-2.0
|
||||
/*
|
||||
* Simple USB Mouse Driver
|
||||
*
|
||||
* A minimal USB HID Boot Protocol mouse driver for learning purposes.
|
||||
* This driver can bind to any standard USB mouse that supports the
|
||||
* HID Boot Protocol.
|
||||
*/
|
||||
|
||||
#include <linux/kernel.h>
|
||||
#include <linux/slab.h>
|
||||
#include <linux/module.h>
|
||||
#include <linux/init.h>
|
||||
#include <linux/usb.h>
|
||||
#include <linux/usb/input.h>
|
||||
#include <linux/hid.h>
|
||||
#include <linux/input.h>
|
||||
|
||||
#define DRIVER_AUTHOR "Testor"
|
||||
#define DRIVER_DESC "Simple USB Mouse Driver"
|
||||
|
||||
MODULE_AUTHOR(DRIVER_AUTHOR);
|
||||
MODULE_DESCRIPTION(DRIVER_DESC);
|
||||
MODULE_LICENSE("GPL");
|
||||
|
||||
/*
|
||||
* Driver context structure
|
||||
* This holds all the data we need for each connected mouse
|
||||
*/
|
||||
struct simple_usb_mouse {
|
||||
char name[128]; /* Device name */
|
||||
char phys[64]; /* Physical path */
|
||||
struct usb_device *usbdev; /* USB device */
|
||||
struct input_dev *input_dev; /* Input device for reporting events */
|
||||
struct urb *irq; /* URB for interrupt transfers */
|
||||
unsigned char *data; /* Data buffer (8 bytes for mouse data) */
|
||||
dma_addr_t data_dma; /* DMA address for data buffer */
|
||||
};
|
||||
|
||||
/*
|
||||
* IRQ handler - called when mouse sends data
|
||||
*
|
||||
* Cooler Master MM710 format (8 bytes):
|
||||
* Byte 0: Button states
|
||||
* Bit 0: Left button
|
||||
* Bit 1: Right button
|
||||
* Bit 2: Middle button
|
||||
* Bit 3: Side button
|
||||
* Bit 4: Extra button
|
||||
* Bytes 1: (unused)
|
||||
* Bytes 2-3: X movement (16-bit signed, little-endian)
|
||||
* Bytes 4-5: Y movement (16-bit signed, little-endian)
|
||||
* Byte 6: Wheel movement (8-bit signed)
|
||||
* Byte 7: (unused)
|
||||
*/
|
||||
static void simple_mouse_irq(struct urb *urb)
|
||||
{
|
||||
struct simple_usb_mouse *mouse = urb->context;
|
||||
unsigned char *data = mouse->data;
|
||||
struct input_dev *dev = mouse->input_dev;
|
||||
int status;
|
||||
int16_t x_movement, y_movement;
|
||||
|
||||
/* Check URB status */
|
||||
switch (urb->status) {
|
||||
case 0:
|
||||
/* Success - process the data */
|
||||
break;
|
||||
case -ECONNRESET:
|
||||
case -ENOENT:
|
||||
case -ESHUTDOWN:
|
||||
/* Device disconnected or URB killed - don't resubmit */
|
||||
pr_debug("simple_mouse: URB stopped (status %d)\n", urb->status);
|
||||
return;
|
||||
default:
|
||||
/* Transient error - we'll resubmit and try again */
|
||||
pr_debug("simple_mouse: URB error (status %d)\n", urb->status);
|
||||
goto resubmit;
|
||||
}
|
||||
|
||||
/* Debug: Print raw data bytes */
|
||||
/* pr_info("simple_mouse: RAW DATA: [0]=%02x [1]=%02x [2]=%02x [3]=%02x [4]=%02x [5]=%02x [6]=%02x [7]=%02x\n",
|
||||
data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]); */
|
||||
|
||||
/* Report button states */
|
||||
input_report_key(dev, BTN_LEFT, data[0] & 0x01);
|
||||
input_report_key(dev, BTN_RIGHT, data[0] & 0x02);
|
||||
input_report_key(dev, BTN_MIDDLE, data[0] & 0x04);
|
||||
input_report_key(dev, BTN_SIDE, data[0] & 0x08);
|
||||
input_report_key(dev, BTN_EXTRA, data[0] & 0x10);
|
||||
|
||||
/* Combine bytes for 16-bit movement (little-endian) */
|
||||
x_movement = (int16_t)(data[2] | (data[3] << 8));
|
||||
y_movement = (int16_t)(data[4] | (data[5] << 8));
|
||||
|
||||
/* Report movement (relative coordinates) */
|
||||
input_report_rel(dev, REL_X, x_movement);
|
||||
input_report_rel(dev, REL_Y, y_movement);
|
||||
input_report_rel(dev, REL_WHEEL, (signed char) data[6]);
|
||||
|
||||
/* Sync - tell input subsystem we're done with this event */
|
||||
input_sync(dev);
|
||||
|
||||
resubmit:
|
||||
/* Resubmit URB to continue receiving data */
|
||||
status = usb_submit_urb(urb, GFP_ATOMIC);
|
||||
if (status) {
|
||||
dev_err(&mouse->usbdev->dev,
|
||||
"Failed to resubmit URB: %d\n", status);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Called when device is opened (e.g., when an application reads from it)
|
||||
* We start the URB here to save resources when mouse isn't being used
|
||||
*/
|
||||
static int simple_mouse_open(struct input_dev *dev)
|
||||
{
|
||||
struct simple_usb_mouse *mouse = input_get_drvdata(dev);
|
||||
|
||||
pr_info("simple_mouse: Device opened\n");
|
||||
|
||||
mouse->irq->dev = mouse->usbdev;
|
||||
if (usb_submit_urb(mouse->irq, GFP_KERNEL)) {
|
||||
pr_err("simple_mouse: Failed to submit URB on open\n");
|
||||
return -EIO;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Called when device is closed
|
||||
* Stop the URB to save resources
|
||||
*/
|
||||
static void simple_mouse_close(struct input_dev *dev)
|
||||
{
|
||||
struct simple_usb_mouse *mouse = input_get_drvdata(dev);
|
||||
|
||||
pr_info("simple_mouse: Device closed\n");
|
||||
usb_kill_urb(mouse->irq);
|
||||
}
|
||||
|
||||
/*
|
||||
* Probe function - called when a matching USB device is connected
|
||||
*/
|
||||
static int simple_mouse_probe(struct usb_interface *intf,
|
||||
const struct usb_device_id *id)
|
||||
{
|
||||
struct usb_device *usbdev = interface_to_usbdev(intf);
|
||||
struct usb_host_interface *interface;
|
||||
struct usb_endpoint_descriptor *endpoint;
|
||||
struct simple_usb_mouse *mouse;
|
||||
struct input_dev *input_dev;
|
||||
int pipe, maxp;
|
||||
int error = -ENOMEM;
|
||||
|
||||
pr_info("simple_mouse: Probing device %04x:%04x\n",
|
||||
le16_to_cpu(usbdev->descriptor.idVendor),
|
||||
le16_to_cpu(usbdev->descriptor. idProduct));
|
||||
|
||||
interface = intf->cur_altsetting;
|
||||
|
||||
/* Validate interface has exactly 1 endpoint */
|
||||
if (interface->desc.bNumEndpoints != 1) {
|
||||
pr_err("simple_mouse: Interface has %d endpoints (expected 1)\n",
|
||||
interface->desc.bNumEndpoints);
|
||||
return -ENODEV;
|
||||
}
|
||||
|
||||
endpoint = &interface->endpoint[0]. desc;
|
||||
|
||||
/* Ensure it's an interrupt IN endpoint */
|
||||
if (! usb_endpoint_is_int_in(endpoint)) {
|
||||
pr_err("simple_mouse: Endpoint is not interrupt IN\n");
|
||||
return -ENODEV;
|
||||
}
|
||||
|
||||
/* Calculate pipe and max packet size */
|
||||
pipe = usb_rcvintpipe(usbdev, endpoint->bEndpointAddress);
|
||||
maxp = usb_maxpacket(usbdev, pipe);
|
||||
|
||||
/* Allocate our context structure */
|
||||
mouse = kzalloc(sizeof(struct simple_usb_mouse), GFP_KERNEL);
|
||||
if (!mouse)
|
||||
return -ENOMEM;
|
||||
|
||||
/* Allocate input device */
|
||||
input_dev = input_allocate_device();
|
||||
if (!input_dev) {
|
||||
pr_err("simple_mouse: Failed to allocate input device\n");
|
||||
goto fail_input_alloc;
|
||||
}
|
||||
|
||||
/* Allocate DMA-coherent buffer for USB data */
|
||||
mouse->data = usb_alloc_coherent(usbdev, 8, GFP_KERNEL,
|
||||
&mouse->data_dma);
|
||||
if (!mouse->data) {
|
||||
pr_err("simple_mouse: Failed to allocate DMA buffer\n");
|
||||
goto fail_dma_alloc;
|
||||
}
|
||||
|
||||
/* Allocate URB */
|
||||
mouse->irq = usb_alloc_urb(0, GFP_KERNEL);
|
||||
if (!mouse->irq) {
|
||||
pr_err("simple_mouse: Failed to allocate URB\n");
|
||||
goto fail_urb_alloc;
|
||||
}
|
||||
|
||||
/* Store references */
|
||||
mouse->usbdev = usbdev;
|
||||
mouse->input_dev = input_dev;
|
||||
|
||||
/* Build device name from USB descriptors */
|
||||
if (usbdev->manufacturer)
|
||||
strscpy(mouse->name, usbdev->manufacturer, sizeof(mouse->name));
|
||||
|
||||
if (usbdev->product) {
|
||||
if (usbdev->manufacturer)
|
||||
strlcat(mouse->name, " ", sizeof(mouse->name));
|
||||
strlcat(mouse->name, usbdev->product, sizeof(mouse->name));
|
||||
}
|
||||
|
||||
/* Fallback name if no descriptors available */
|
||||
if (! strlen(mouse->name)) {
|
||||
snprintf(mouse->name, sizeof(mouse->name),
|
||||
"Simple USB Mouse %04x:%04x",
|
||||
le16_to_cpu(usbdev->descriptor. idVendor),
|
||||
le16_to_cpu(usbdev->descriptor.idProduct));
|
||||
}
|
||||
|
||||
/* Build physical path */
|
||||
usb_make_path(usbdev, mouse->phys, sizeof(mouse->phys));
|
||||
strlcat(mouse->phys, "/input0", sizeof(mouse->phys));
|
||||
|
||||
pr_info("simple_mouse: Device name: %s\n", mouse->name);
|
||||
pr_info("simple_mouse: Physical path: %s\n", mouse->phys);
|
||||
|
||||
/* Configure input device */
|
||||
input_dev->name = mouse->name;
|
||||
input_dev->phys = mouse->phys;
|
||||
usb_to_input_id(usbdev, &input_dev->id);
|
||||
input_dev->dev.parent = &intf->dev;
|
||||
|
||||
/* Set event types we can generate */
|
||||
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
|
||||
|
||||
/* Set button capabilities */
|
||||
input_dev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |
|
||||
BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_MIDDLE);
|
||||
input_dev->keybit[BIT_WORD(BTN_MOUSE)] |= BIT_MASK(BTN_SIDE) |
|
||||
BIT_MASK(BTN_EXTRA);
|
||||
|
||||
/* Set relative axis capabilities */
|
||||
input_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y) |
|
||||
BIT_MASK(REL_WHEEL);
|
||||
|
||||
/* Set driver data and callbacks */
|
||||
input_set_drvdata(input_dev, mouse);
|
||||
input_dev->open = simple_mouse_open;
|
||||
input_dev->close = simple_mouse_close;
|
||||
|
||||
/* Initialize URB */
|
||||
usb_fill_int_urb(mouse->irq, usbdev, pipe, mouse->data,
|
||||
(maxp > 8 ? 8 : maxp),
|
||||
simple_mouse_irq, mouse, endpoint->bInterval);
|
||||
mouse->irq->transfer_dma = mouse->data_dma;
|
||||
mouse->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
|
||||
|
||||
/* Register input device with the kernel */
|
||||
error = input_register_device(mouse->input_dev);
|
||||
if (error) {
|
||||
pr_err("simple_mouse: Failed to register input device: %d\n",
|
||||
error);
|
||||
goto fail_register;
|
||||
}
|
||||
|
||||
/* Save our context in interface data */
|
||||
usb_set_intfdata(intf, mouse);
|
||||
|
||||
pr_info("simple_mouse: Probe successful!\n");
|
||||
return 0;
|
||||
|
||||
/* Error handling - cleanup in reverse order */
|
||||
fail_register:
|
||||
usb_free_urb(mouse->irq);
|
||||
fail_urb_alloc:
|
||||
usb_free_coherent(usbdev, 8, mouse->data, mouse->data_dma);
|
||||
fail_dma_alloc:
|
||||
input_free_device(input_dev);
|
||||
fail_input_alloc:
|
||||
kfree(mouse);
|
||||
return error;
|
||||
}
|
||||
|
||||
/*
|
||||
* Disconnect function - called when device is unplugged
|
||||
*/
|
||||
static void simple_mouse_disconnect(struct usb_interface *intf)
|
||||
{
|
||||
struct simple_usb_mouse *mouse = usb_get_intfdata(intf);
|
||||
|
||||
pr_info("simple_mouse: Device disconnected\n");
|
||||
|
||||
/* Clear interface data */
|
||||
usb_set_intfdata(intf, NULL);
|
||||
|
||||
if (mouse) {
|
||||
/* Stop URB */
|
||||
usb_kill_urb(mouse->irq);
|
||||
|
||||
/* Unregister from input subsystem */
|
||||
input_unregister_device(mouse->input_dev);
|
||||
|
||||
/* Free URB */
|
||||
usb_free_urb(mouse->irq);
|
||||
|
||||
/* Free DMA buffer */
|
||||
usb_free_coherent(interface_to_usbdev(intf), 8,
|
||||
mouse->data, mouse->data_dma);
|
||||
|
||||
/* Free context structure */
|
||||
kfree(mouse);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Device ID table - matches ANY USB HID Boot Protocol mouse
|
||||
* This is the key to binding to any mouse!
|
||||
*/
|
||||
static const struct usb_device_id simple_mouse_id_table[] = {
|
||||
{
|
||||
USB_INTERFACE_INFO(
|
||||
USB_INTERFACE_CLASS_HID, /* Class: HID */
|
||||
USB_INTERFACE_SUBCLASS_BOOT, /* Subclass: Boot */
|
||||
USB_INTERFACE_PROTOCOL_MOUSE /* Protocol: Mouse */
|
||||
)
|
||||
},
|
||||
{ } /* Terminating entry */
|
||||
};
|
||||
|
||||
MODULE_DEVICE_TABLE(usb, simple_mouse_id_table);
|
||||
|
||||
/*
|
||||
* USB Driver structure
|
||||
*/
|
||||
static struct usb_driver simple_mouse_driver = {
|
||||
.name = "simple_usb_mouse",
|
||||
.probe = simple_mouse_probe,
|
||||
.disconnect = simple_mouse_disconnect,
|
||||
.id_table = simple_mouse_id_table,
|
||||
};
|
||||
|
||||
/*
|
||||
* Module init/exit
|
||||
*/
|
||||
module_usb_driver(simple_mouse_driver);
|
||||
762
usb_driver_manager.py
Executable file
762
usb_driver_manager.py
Executable file
@@ -0,0 +1,762 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
USB Driver Manager - CLI tool for managing USB device driver bindings
|
||||
Helps with finding USB devices, unloading current drivers, loading new drivers,
|
||||
and binding USB devices to new drivers.
|
||||
|
||||
Note: USB drivers typically bind to interfaces, not devices. This script
|
||||
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 sys
|
||||
import subprocess
|
||||
import glob
|
||||
import re
|
||||
import time
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class Colors:
|
||||
"""ANSI color codes for terminal output"""
|
||||
HEADER = '\033[95m'
|
||||
BLUE = '\033[94m'
|
||||
CYAN = '\033[96m'
|
||||
GREEN = '\033[92m'
|
||||
YELLOW = '\033[93m'
|
||||
RED = '\033[91m'
|
||||
END = '\033[0m'
|
||||
BOLD = '\033[1m'
|
||||
|
||||
|
||||
def print_header(text):
|
||||
"""Print colored header"""
|
||||
print(f"\n{Colors.BOLD}{Colors.HEADER}{text}{Colors.END}")
|
||||
|
||||
|
||||
def print_success(text):
|
||||
"""Print success message"""
|
||||
print(f"{Colors.GREEN}✓ {text}{Colors.END}")
|
||||
|
||||
|
||||
def print_error(text):
|
||||
"""Print error message"""
|
||||
print(f"{Colors.RED}✗ {text}{Colors.END}")
|
||||
|
||||
|
||||
def print_warning(text):
|
||||
"""Print warning message"""
|
||||
print(f"{Colors.YELLOW}⚠ {text}{Colors.END}")
|
||||
|
||||
|
||||
def check_root():
|
||||
"""Check if script is running with root privileges"""
|
||||
if os.geteuid() != 0:
|
||||
print_error("This tool requires root privileges.")
|
||||
print("Please run with sudo:")
|
||||
print(f" sudo {' '.join(sys.argv)}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def get_usb_devices():
|
||||
"""Get list of USB devices with their information"""
|
||||
devices = []
|
||||
usb_devices_path = Path("/sys/bus/usb/devices")
|
||||
|
||||
if not usb_devices_path.exists():
|
||||
print_error("USB devices path not found. Is USB subsystem available?")
|
||||
return devices
|
||||
|
||||
# Get lsusb output for human-readable names
|
||||
lsusb_output = {}
|
||||
try:
|
||||
result = subprocess.run(['lsusb'], capture_output=True, text=True)
|
||||
for line in result.stdout.splitlines():
|
||||
# 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)
|
||||
if match:
|
||||
bus, dev, vendor, product, name = match.groups()
|
||||
key = f"{int(bus)}-{int(dev)}"
|
||||
lsusb_output[key] = {
|
||||
'vendor_id': vendor,
|
||||
'product_id': product,
|
||||
'name': name.strip()
|
||||
}
|
||||
except Exception as e:
|
||||
print_warning(f"Could not run lsusb: {e}")
|
||||
|
||||
# Iterate through USB devices
|
||||
for device_path in usb_devices_path.iterdir():
|
||||
if not device_path.is_dir():
|
||||
continue
|
||||
|
||||
# Only process actual device entries (format: busnum-devnum or busnum-port.port...)
|
||||
device_name = device_path.name
|
||||
if not re.match(r'\d+-[\d.]+$', device_name):
|
||||
continue
|
||||
|
||||
# Skip root hubs
|
||||
devpath_file = device_path / "devpath"
|
||||
if not devpath_file.exists():
|
||||
continue
|
||||
|
||||
try:
|
||||
# Read device information
|
||||
vendor_id = (device_path / "idVendor").read_text().strip() if (device_path / "idVendor").exists() else "unknown"
|
||||
product_id = (device_path / "idProduct").read_text().strip() if (device_path / "idProduct").exists() else "unknown"
|
||||
manufacturer = (device_path / "manufacturer").read_text().strip() if (device_path / "manufacturer").exists() else "Unknown"
|
||||
product = (device_path / "product").read_text().strip() if (device_path / "product").exists() else "Unknown"
|
||||
busnum = (device_path / "busnum").read_text().strip() if (device_path / "busnum").exists() else "?"
|
||||
devnum = (device_path / "devnum").read_text().strip() if (device_path / "devnum").exists() else "?"
|
||||
|
||||
# Get current driver
|
||||
driver = "none"
|
||||
driver_link = device_path / "driver"
|
||||
if driver_link.exists() and driver_link.is_symlink():
|
||||
driver = driver_link.resolve().name
|
||||
|
||||
# Check interfaces for HID class and collect interface information
|
||||
interfaces = []
|
||||
is_input = False
|
||||
for interface_path in device_path.glob("*:*.*"):
|
||||
if not interface_path.is_dir():
|
||||
continue
|
||||
try:
|
||||
iface_class = (interface_path / "bInterfaceClass").read_text().strip() if (interface_path / "bInterfaceClass").exists() else "00"
|
||||
iface_subclass = (interface_path / "bInterfaceSubClass").read_text().strip() if (interface_path / "bInterfaceSubClass").exists() else "00"
|
||||
iface_protocol = (interface_path / "bInterfaceProtocol").read_text().strip() if (interface_path / "bInterfaceProtocol").exists() else "00"
|
||||
|
||||
# Get interface driver
|
||||
iface_driver = "none"
|
||||
iface_driver_link = interface_path / "driver"
|
||||
if iface_driver_link.exists() and iface_driver_link.is_symlink():
|
||||
iface_driver = iface_driver_link.resolve().name
|
||||
|
||||
interfaces.append({
|
||||
'name': interface_path.name,
|
||||
'path': str(interface_path),
|
||||
'class': iface_class,
|
||||
'subclass': iface_subclass,
|
||||
'protocol': iface_protocol,
|
||||
'driver': iface_driver
|
||||
})
|
||||
|
||||
# Class 03 is HID (Human Interface Device)
|
||||
if iface_class == "03":
|
||||
is_input = True
|
||||
except Exception:
|
||||
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({
|
||||
'path': str(device_path),
|
||||
'name': device_name,
|
||||
'vendor_id': vendor_id,
|
||||
'product_id': product_id,
|
||||
'manufacturer': manufacturer,
|
||||
'product': product,
|
||||
'bus': busnum,
|
||||
'device': devnum,
|
||||
'driver': driver,
|
||||
'is_input': is_input,
|
||||
'interfaces': interfaces,
|
||||
'display_name': f"{manufacturer} {product}".strip()
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
# Skip devices that can't be read
|
||||
continue
|
||||
|
||||
return devices
|
||||
|
||||
|
||||
def display_usb_devices(devices, filter_input=True):
|
||||
"""Display USB devices in a formatted list"""
|
||||
if filter_input:
|
||||
devices = [d for d in devices if d['is_input']]
|
||||
|
||||
if not devices:
|
||||
print_warning("No USB devices found.")
|
||||
return None
|
||||
|
||||
print_header("Available USB Devices:")
|
||||
print(f"\n{'#':<4} {'Device':<15} {'Vendor:Product':<15} {'Name':<40} {'Interfaces':<15}")
|
||||
print("-" * 100)
|
||||
|
||||
for idx, device in enumerate(devices, 1):
|
||||
vendor_product = f"{device['vendor_id']}:{device['product_id']}"
|
||||
|
||||
display_name = device['display_name']
|
||||
if len(display_name) > 40:
|
||||
display_name = display_name[:37] + "..."
|
||||
|
||||
iface_info = f"{len(device.get('interfaces', []))} interface(s)"
|
||||
|
||||
print(f"{idx:<4} {device['name']:<15} {vendor_product:<15} {display_name:<40} {iface_info}")
|
||||
|
||||
return devices
|
||||
|
||||
|
||||
def get_kernel_modules(directories=None):
|
||||
"""Get list of available kernel modules (.ko files)"""
|
||||
if directories is None:
|
||||
directories = ["."]
|
||||
|
||||
modules = []
|
||||
seen_modules = set() # Track module names to avoid duplicates
|
||||
|
||||
# Search for .ko files recursively in each specified directory
|
||||
for directory in directories:
|
||||
if not os.path.exists(directory):
|
||||
print_warning(f"Directory not found: {directory}")
|
||||
continue
|
||||
|
||||
for root, dirs, files in os.walk(directory):
|
||||
for filename in files:
|
||||
if not filename.endswith('.ko'):
|
||||
continue
|
||||
|
||||
module_name = filename
|
||||
module_path = os.path.abspath(os.path.join(root, filename))
|
||||
|
||||
# Skip duplicates (same module name already found)
|
||||
if module_name in seen_modules:
|
||||
continue
|
||||
seen_modules.add(module_name)
|
||||
|
||||
# Get module info if possible
|
||||
try:
|
||||
result = subprocess.run(['modinfo', module_path], 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
|
||||
|
||||
modules.append({
|
||||
'name': module_name,
|
||||
'path': module_path,
|
||||
'description': description
|
||||
})
|
||||
except Exception:
|
||||
modules.append({
|
||||
'name': module_name,
|
||||
'path': module_path,
|
||||
'description': "No description available"
|
||||
})
|
||||
|
||||
return modules
|
||||
|
||||
|
||||
def display_kernel_modules(modules):
|
||||
"""Display available kernel modules"""
|
||||
if not modules:
|
||||
print_warning("No kernel modules (.ko files) found in current directory.")
|
||||
return None
|
||||
|
||||
print_header("Available Kernel Modules:")
|
||||
print(f"\n{'#':<4} {'Module Name':<30} {'Description':<50}")
|
||||
print("-" * 90)
|
||||
|
||||
for idx, module in enumerate(modules, 1):
|
||||
desc = module['description']
|
||||
if len(desc) > 50:
|
||||
desc = desc[:47] + "..."
|
||||
print(f"{idx:<4} {module['name']:<30} {desc}")
|
||||
|
||||
return modules
|
||||
|
||||
|
||||
def get_user_choice(prompt, max_choice):
|
||||
"""Get user input for selection"""
|
||||
while True:
|
||||
try:
|
||||
choice = input(f"\n{prompt} (1-{max_choice}, or 'q' to quit): ").strip()
|
||||
if choice.lower() == 'q':
|
||||
return None
|
||||
choice = int(choice)
|
||||
if 1 <= choice <= max_choice:
|
||||
return choice - 1 # Return 0-indexed
|
||||
else:
|
||||
print_error(f"Please enter a number between 1 and {max_choice}")
|
||||
except ValueError:
|
||||
print_error("Invalid input. Please enter a number.")
|
||||
except KeyboardInterrupt:
|
||||
print("\n")
|
||||
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):
|
||||
"""Unbind device interface from current driver"""
|
||||
# If specific interface provided, unbind that interface
|
||||
if interface:
|
||||
if interface['driver'] == "none":
|
||||
print_warning(f"Interface {interface['name']} is not bound to any driver.")
|
||||
return True
|
||||
|
||||
driver_path = Path(f"/sys/bus/usb/drivers/{interface['driver']}")
|
||||
unbind_path = driver_path / "unbind"
|
||||
|
||||
if not unbind_path.exists():
|
||||
print_error(f"Cannot unbind: {unbind_path} not found")
|
||||
return False
|
||||
|
||||
try:
|
||||
print(f"Unbinding interface {interface['name']} from driver {interface['driver']}...")
|
||||
unbind_path.write_text(interface['name'])
|
||||
print_success(f"Successfully unbound from {interface['driver']}")
|
||||
return True
|
||||
except Exception as e:
|
||||
print_error(f"Failed to unbind interface: {e}")
|
||||
return False
|
||||
|
||||
# Otherwise unbind all interfaces
|
||||
success = True
|
||||
for iface in device.get('interfaces', []):
|
||||
if iface['driver'] != "none":
|
||||
if not unbind_device(device, iface):
|
||||
success = False
|
||||
|
||||
if not device.get('interfaces'):
|
||||
# Fallback to old behavior for device-level driver
|
||||
if device['driver'] == "none":
|
||||
print_warning("Device is not bound to any driver.")
|
||||
return True
|
||||
|
||||
driver_path = Path(f"/sys/bus/usb/drivers/{device['driver']}")
|
||||
unbind_path = driver_path / "unbind"
|
||||
|
||||
if not unbind_path.exists():
|
||||
print_error(f"Cannot unbind: {unbind_path} not found")
|
||||
return False
|
||||
|
||||
try:
|
||||
print(f"Unbinding device {device['name']} from driver {device['driver']}...")
|
||||
unbind_path.write_text(device['name'])
|
||||
print_success(f"Successfully unbound from {device['driver']}")
|
||||
return True
|
||||
except Exception as e:
|
||||
print_error(f"Failed to unbind device: {e}")
|
||||
return False
|
||||
|
||||
return success
|
||||
|
||||
|
||||
def load_module(module):
|
||||
"""Load kernel module"""
|
||||
try:
|
||||
print(f"Loading module {module['name']}...")
|
||||
result = subprocess.run(['insmod', module['path']], capture_output=True, text=True)
|
||||
if result.returncode == 0:
|
||||
print_success(f"Successfully loaded {module['name']}")
|
||||
return True
|
||||
else:
|
||||
# Module might already be loaded
|
||||
if "File exists" in result.stderr or "already" in result.stderr.lower():
|
||||
print_warning(f"Module {module['name']} is already loaded")
|
||||
return True
|
||||
print_error(f"Failed to load module: {result.stderr}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print_error(f"Failed to load module: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def get_module_driver_name(module):
|
||||
"""Get the driver name from module"""
|
||||
# Extract driver name from module (remove .ko extension)
|
||||
driver_name = os.path.splitext(module['name'])[0]
|
||||
|
||||
# Check if driver exists in /sys/bus/usb/drivers/
|
||||
driver_path = Path(f"/sys/bus/usb/drivers/{driver_name}")
|
||||
if driver_path.exists():
|
||||
return driver_name
|
||||
|
||||
# Try to get it from loaded modules
|
||||
try:
|
||||
result = subprocess.run(['lsmod'], capture_output=True, text=True)
|
||||
for line in result.stdout.splitlines():
|
||||
if line.startswith(driver_name):
|
||||
return driver_name
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return driver_name
|
||||
|
||||
|
||||
def bind_device(device, module, interface=None):
|
||||
"""Bind device interface to new driver"""
|
||||
driver_name = get_module_driver_name(module)
|
||||
driver_path = Path(f"/sys/bus/usb/drivers/{driver_name}")
|
||||
bind_path = driver_path / "bind"
|
||||
|
||||
if not driver_path.exists():
|
||||
print_error(f"Driver path not found: {driver_path}")
|
||||
print_warning("The driver might not be loaded or might use a different name.")
|
||||
return False
|
||||
|
||||
if not bind_path.exists():
|
||||
print_error(f"Bind interface not found: {bind_path}")
|
||||
return False
|
||||
|
||||
# If specific interface provided, bind that interface
|
||||
if interface:
|
||||
# Check if already bound to target driver
|
||||
iface_path = Path(interface['path'])
|
||||
driver_link = iface_path / "driver"
|
||||
if driver_link.exists() and driver_link.is_symlink():
|
||||
current_driver = driver_link.resolve().name
|
||||
if current_driver == driver_name:
|
||||
print_success(f"Interface {interface['name']} already bound to {driver_name}")
|
||||
return True
|
||||
|
||||
try:
|
||||
print(f"Binding interface {interface['name']} to driver {driver_name}...")
|
||||
bind_path.write_text(interface['name'])
|
||||
print_success(f"Successfully bound to {driver_name}")
|
||||
return True
|
||||
except Exception as e:
|
||||
# Check again if it got bound (might be EBUSY because it auto-bound)
|
||||
if driver_link.exists() and driver_link.is_symlink():
|
||||
current_driver = driver_link.resolve().name
|
||||
if current_driver == driver_name:
|
||||
print_success(f"Interface {interface['name']} bound to {driver_name} (auto-probed)")
|
||||
return True
|
||||
print_error(f"Failed to bind interface: {e}")
|
||||
return False
|
||||
|
||||
# Default behavior (kept for backwards compatibility): try boot mouse, then device.
|
||||
target_interfaces = []
|
||||
for iface in device.get('interfaces', []):
|
||||
# Look for HID Boot Mouse interfaces
|
||||
if iface['class'] == "03" and iface['subclass'] == "01" and iface['protocol'] == "02":
|
||||
target_interfaces.append(iface)
|
||||
|
||||
if not target_interfaces:
|
||||
# Fallback: try to bind the device itself
|
||||
try:
|
||||
print(f"Binding device {device['name']} to driver {driver_name}...")
|
||||
bind_path.write_text(device['name'])
|
||||
print_success(f"Successfully bound to {driver_name}")
|
||||
return True
|
||||
except Exception as e:
|
||||
print_error(f"Failed to bind device: {e}")
|
||||
return False
|
||||
|
||||
# Bind each target interface
|
||||
success = True
|
||||
for iface in target_interfaces:
|
||||
# Check if already bound to target driver
|
||||
iface_path = Path(iface['path'])
|
||||
driver_link = iface_path / "driver"
|
||||
if driver_link.exists() and driver_link.is_symlink():
|
||||
current_driver = driver_link.resolve().name
|
||||
if current_driver == driver_name:
|
||||
print_success(f"Interface {iface['name']} already bound to {driver_name}")
|
||||
continue
|
||||
|
||||
try:
|
||||
print(f"Binding interface {iface['name']} to driver {driver_name}...")
|
||||
bind_path.write_text(iface['name'])
|
||||
print_success(f"Successfully bound interface {iface['name']} to {driver_name}")
|
||||
except Exception as e:
|
||||
# Check again if it got bound (might be EBUSY because it auto-bound)
|
||||
if driver_link.exists() and driver_link.is_symlink():
|
||||
current_driver = driver_link.resolve().name
|
||||
if current_driver == driver_name:
|
||||
print_success(f"Interface {iface['name']} bound to {driver_name} (auto-probed)")
|
||||
continue
|
||||
print_error(f"Failed to bind interface {iface['name']}: {e}")
|
||||
success = False
|
||||
|
||||
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):
|
||||
"""Unload kernel module"""
|
||||
driver_name = get_module_driver_name(module)
|
||||
try:
|
||||
print(f"Unloading module {driver_name}...")
|
||||
result = subprocess.run(['rmmod', driver_name], capture_output=True, text=True)
|
||||
if result.returncode == 0:
|
||||
print_success(f"Successfully unloaded {driver_name}")
|
||||
return True
|
||||
else:
|
||||
print_warning(f"Could not unload module: {result.stderr}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print_warning(f"Could not unload module: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def is_module_loaded(module):
|
||||
"""Check if a kernel module is currently loaded"""
|
||||
driver_name = get_module_driver_name(module)
|
||||
try:
|
||||
result = subprocess.run(['lsmod'], capture_output=True, text=True)
|
||||
for line in result.stdout.splitlines():
|
||||
if line.split()[0] == driver_name:
|
||||
return True
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function"""
|
||||
# Parse command line arguments
|
||||
parser = argparse.ArgumentParser(
|
||||
description='USB Driver Manager - CLI tool for managing USB device driver bindings',
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog='Examples:\n'
|
||||
' sudo %(prog)s # Search for .ko files in current directory\n'
|
||||
' sudo %(prog)s /path/to/modules # Search in specific directory\n'
|
||||
' sudo %(prog)s . /path/to/dir2 # Search in multiple directories\n'
|
||||
)
|
||||
parser.add_argument(
|
||||
'directories',
|
||||
nargs='*',
|
||||
default=['.'],
|
||||
help='Directories to search for kernel modules (.ko files). Defaults to current directory.'
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
print(f"{Colors.BOLD}{Colors.CYAN}")
|
||||
print("=" * 60)
|
||||
print(" USB Driver Manager")
|
||||
print("=" * 60)
|
||||
print(Colors.END)
|
||||
|
||||
# Check root privileges
|
||||
check_root()
|
||||
|
||||
# Step 1: List USB devices
|
||||
devices = get_usb_devices()
|
||||
displayed_devices = display_usb_devices(devices, filter_input=True)
|
||||
|
||||
if not displayed_devices:
|
||||
print_error("No input devices found. Showing all USB devices...")
|
||||
displayed_devices = display_usb_devices(devices, filter_input=False)
|
||||
if not displayed_devices:
|
||||
sys.exit(1)
|
||||
|
||||
# Step 2: Select device
|
||||
device_idx = get_user_choice("Select USB device", len(displayed_devices))
|
||||
if device_idx is None:
|
||||
print("\nOperation cancelled.")
|
||||
sys.exit(0)
|
||||
|
||||
selected_device = displayed_devices[device_idx]
|
||||
print(f"\n{Colors.CYAN}Selected device: {selected_device['display_name']}{Colors.END}")
|
||||
print(f" Device: {selected_device['name']}")
|
||||
print(f" Current driver: {selected_device['driver']}")
|
||||
|
||||
# Step 2b: Select interfaces
|
||||
selected_interfaces = get_interface_selection(selected_device)
|
||||
if not selected_interfaces:
|
||||
print_warning("No interfaces available/selected; cannot bind.")
|
||||
sys.exit(1)
|
||||
|
||||
# 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
|
||||
if len(args.directories) > 1 or args.directories[0] != '.':
|
||||
print(f"\nSearching for kernel modules in: {', '.join(args.directories)}")
|
||||
modules = get_kernel_modules(args.directories)
|
||||
displayed_modules = display_kernel_modules(modules)
|
||||
|
||||
if not displayed_modules:
|
||||
sys.exit(1)
|
||||
|
||||
# Step 4: Select module
|
||||
module_idx = get_user_choice("Select kernel module", len(displayed_modules))
|
||||
if module_idx is None:
|
||||
print("\nOperation cancelled.")
|
||||
sys.exit(0)
|
||||
|
||||
selected_module = displayed_modules[module_idx]
|
||||
print(f"\n{Colors.CYAN}Selected module: {selected_module['name']}{Colors.END}")
|
||||
|
||||
# Check if module is already loaded
|
||||
module_already_loaded = is_module_loaded(selected_module)
|
||||
if module_already_loaded:
|
||||
print_warning(f"Module {selected_module['name']} is already loaded and will be reloaded.")
|
||||
|
||||
# Step 5: Confirm operation
|
||||
print(f"\n{Colors.YELLOW}This will:{Colors.END}")
|
||||
print(f" 1. Unbind {len(selected_interfaces)} interface(s) from current driver(s)")
|
||||
if module_already_loaded:
|
||||
print(f" 2. Unload existing module {selected_module['name']}")
|
||||
print(f" 3. Load module {selected_module['name']} (fresh version)")
|
||||
print(f" 4. Bind selected interface(s) to the new driver")
|
||||
else:
|
||||
print(f" 2. Load module {selected_module['name']}")
|
||||
print(f" 3. Bind selected interface(s) to the new driver")
|
||||
|
||||
confirm = input(f"\n{Colors.BOLD}Proceed? (yes/no): {Colors.END}").strip().lower()
|
||||
if confirm not in ['yes', 'y']:
|
||||
print("\nOperation cancelled.")
|
||||
sys.exit(0)
|
||||
|
||||
# Step 6: Perform operations
|
||||
print_header("\nExecuting operations...")
|
||||
|
||||
# Unbind selected interfaces from current drivers
|
||||
for iface in selected_interfaces:
|
||||
if not unbind_device(selected_device, iface):
|
||||
print_error("Failed to unbind interface. Aborting.")
|
||||
sys.exit(1)
|
||||
|
||||
# Unload module if already loaded
|
||||
if module_already_loaded:
|
||||
if not unload_module(selected_module):
|
||||
print_error("Failed to unload existing module.")
|
||||
print_warning("You may need to manually unbind all devices using this driver first.")
|
||||
sys.exit(1)
|
||||
# Give kernel a moment after unloading
|
||||
time.sleep(0.3)
|
||||
|
||||
# Load new module
|
||||
if not load_module(selected_module):
|
||||
print_error("Failed to load module. Attempting to restore...")
|
||||
# Try to rebind each selected interface to its original driver
|
||||
for iface in selected_interfaces:
|
||||
orig = original_interface_drivers.get(iface['name'], 'none')
|
||||
if orig != 'none':
|
||||
bind_interface_to_driver(iface['name'], orig)
|
||||
sys.exit(1)
|
||||
|
||||
# Give kernel time to auto-probe and bind
|
||||
print("Waiting for kernel to probe interfaces...")
|
||||
time.sleep(0.5)
|
||||
|
||||
# Bind selected interfaces to new driver
|
||||
bound_any = False
|
||||
for iface in selected_interfaces:
|
||||
if bind_device(selected_device, selected_module, iface):
|
||||
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)
|
||||
|
||||
# Success
|
||||
print_header("\nOperation completed successfully!")
|
||||
print(f"{Colors.GREEN}Device {selected_device['name']} interface(s) are now using the new driver{Colors.END}")
|
||||
|
||||
# Offer to show new device status
|
||||
print("\nVerifying device status...")
|
||||
new_devices = get_usb_devices()
|
||||
for dev in new_devices:
|
||||
if dev['name'] == selected_device['name']:
|
||||
for iface in dev.get('interfaces', []):
|
||||
driver_color = Colors.GREEN if iface['driver'] != "none" else Colors.YELLOW
|
||||
print(f" Interface {iface['name']}: {driver_color}{iface['driver']}{Colors.END}")
|
||||
if not dev.get('interfaces') and dev['driver'] != 'none':
|
||||
print(f" Current driver: {Colors.GREEN}{dev['driver']}{Colors.END}")
|
||||
break
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
print(f"\n\n{Colors.YELLOW}Operation cancelled by user.{Colors.END}")
|
||||
sys.exit(0)
|
||||
except Exception as e:
|
||||
print_error(f"Unexpected error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
25
wasd-emulator/Makefile
Normal file
25
wasd-emulator/Makefile
Normal file
@@ -0,0 +1,25 @@
|
||||
|
||||
.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
|
||||
223
wasd-emulator/wasd.c
Normal file
223
wasd-emulator/wasd.c
Normal file
@@ -0,0 +1,223 @@
|
||||
|
||||
#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