3 Commits

Author SHA1 Message Date
felix.peterka 8ca379fa13 First implementation of Media Control 2026-01-17 10:22:49 +01:00
thomas.hilscher 29b23b5964 Fixed mouse driver and moved to seperate folder 2026-01-15 22:04:34 +01:00
thomas.hilscher c42dff6384 Added first tries 2026-01-09 17:22:38 +01:00
9 changed files with 417 additions and 1456 deletions
+5 -4
View File
@@ -1,6 +1,5 @@
Device Driver
=============
# 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).
@@ -10,6 +9,7 @@ A helper tool (``usb_driver_manager.py``) is included to make it easier to:
- unbind/bind a selected interface to a chosen driver during development
## Drivers
----------
### Mouse driver (``mouse/``)
USB HID boot-protocol mouse driver.
@@ -37,6 +37,7 @@ make
After building, the module (``*.ko``) is typically placed under ``build/`` by the provided Makefiles.
## USB Driver Manager
---------------------
**Usage examples:**
```bash
@@ -54,7 +55,7 @@ sudo python3 usb_driver_manager.py ./mouse/build ./g29_media_usb/build
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
View File
@@ -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
-578
View File
@@ -1,578 +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)");
static int steer_deadzone = 10;
module_param(steer_deadzone, int, 0644);
MODULE_PARM_DESC(steer_deadzone, "Steering deadzone radius from center (default=10)");
#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_L1, BTN_LEFT},
{G29_BTN_R1, BTN_RIGHT},
{G29_BTN_RETURN, BTN_MIDDLE},
};
struct g29_dev {
char name[128];
char phys[64];
struct usb_device *udev;
struct usb_interface *intf;
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;
struct work_struct autocenter_work;
int out_ep_addr;
int out_ep_maxp;
int out_ep_interval;
enum g29_mode current_mode;
struct g29_state last;
};
static void g29_find_int_out_ep(struct g29_dev *g29) {
const struct usb_host_interface *alts = g29->intf->cur_altsetting;
g29->out_ep_addr = 0;
g29->out_ep_maxp = 0;
g29->out_ep_interval = 0;
for (int i = 0; i < alts->desc.bNumEndpoints; i++) {
const struct usb_endpoint_descriptor *d = &alts->endpoint[i].desc;
if (!usb_endpoint_is_int_out(d))
continue;
g29->out_ep_addr = d->bEndpointAddress;
g29->out_ep_maxp = usb_endpoint_maxp(d);
g29->out_ep_interval = d->bInterval;
dev_info(&g29->intf->dev, "Found interrupt OUT ep=%02x maxp=%d interval=%d\n", g29->out_ep_addr, g29->out_ep_maxp, g29->out_ep_interval);
return;
}
dev_info(&g29->intf->dev, "No interrupt OUT endpoint found on this interface (will use SET_REPORT)\n");
}
static int g29_send_interrupt_out(struct g29_dev *g29, const u8 *buf, int len) {
int ret, actual = 0;
if (!g29->out_ep_addr)
return -ENODEV;
ret = usb_interrupt_msg(g29->udev,
usb_sndintpipe(g29->udev, g29->out_ep_addr),
(void *) buf, len, &actual, 1000);
if (ret < 0)
return ret;
if (actual != len)
return -EIO;
return 0;
}
static int g29_send_set_report(const struct g29_dev *g29, const int ifnum, const int report_id, const u8 *buf, const int len) {
const u16 wValue = ((u16) 0x02 << 8) | (report_id & 0xff);
const int ret = usb_control_msg(g29->udev, usb_sndctrlpipe(g29->udev, 0), 0x09,
USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_OUT,
wValue, ifnum, (void *) buf, len, USB_CTRL_SET_TIMEOUT);
if (ret < 0)
return ret;
if (ret != len)
return -EIO;
return 0;
}
static int g29_send_cmd7(struct g29_dev *g29, const u8 cmd0, const u8 cmd1, const u8 cmd2, const u8 cmd3, const u8 cmd4, const u8 cmd5, const u8 cmd6) {
const u8 cmd[] = {cmd0, cmd1, cmd2, cmd3, cmd4, cmd5, cmd6};
int ret;
if ((ret = g29_send_interrupt_out(g29, cmd, 7)) == 0)
return 0;
const int ifnum = 0, report_id = 0;
if ((ret = g29_send_set_report(g29, ifnum, report_id, cmd, 7)) < 0) {
dev_warn(&g29->intf->dev,
"autocenter cmd %02x %02x %02x %02x %02x %02x %02x failed: %d (ifnum=%d report_id=%d out_ep=%02x)\n",
cmd[0], cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6],
ret, ifnum, report_id, g29->out_ep_addr);
}
return ret;
}
static void g29_set_autocenter_default(struct g29_dev *g29, const u16 magnitude) {
if (magnitude == 0) {
g29_send_cmd7(g29, 0xf5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
return;
}
u32 expand_a, expand_b;
if (magnitude <= 0xaaaa) {
expand_a = 0x0c * magnitude;
expand_b = 0x80 * magnitude;
} else {
expand_a = (0x0c * 0xaaaa) + 0x06 * (magnitude - 0xaaaa);
expand_b = (0x80 * 0xaaaa) + 0xff * (magnitude - 0xaaaa);
}
expand_a >>= 1;
if (g29_send_cmd7(g29, 0xfe, 0x0d, expand_a / 0xaaaa, expand_a / 0xaaaa, expand_b / 0xaaaa, 0x00, 0x00) < 0)
return;
g29_send_cmd7(g29, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
}
static void g29_autocenter_work_fn(struct work_struct *work) {
struct g29_dev *g29 = container_of(work, struct g29_dev, autocenter_work);
const u16 mag = 0xFFFF;
if (mag == 0)
return;
g29_set_autocenter_default(g29, mag);
}
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(1));
}
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 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);
const int up = G29_PEDAL_RELEASED - g29->last.gas;
const int down = G29_PEDAL_RELEASED - g29->last.clt;
const int left = rot < 0x8000 ? WHEEL_CENTER - rot : 0;
const int right = rot > 0x8000 ? rot - WHEEL_CENTER : 0;
const int dx = (right - left) / 0x400;
const int dy = (down - up) / 0x20;
if (dx != 0 || dy != 0) {
input_report_rel(g29->input, REL_X, dx);
input_report_rel(g29->input, REL_Y, dy);
input_sync(g29->input);
}
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 period = 50;
const int rot = le16_to_cpu(g29->last.rot_le);
const int gas = G29_PEDAL_RELEASED - g29->last.gas;
const int brk = G29_PEDAL_RELEASED - g29->last.brk;
const int gas_duty = gas * period / 0x40;
input_report_key(g29->input, KEY_W, g29->gas_phase_accumulator < gas_duty);
g29->gas_phase_accumulator++;
g29->gas_phase_accumulator %= period;
input_report_key(g29->input, KEY_S, brk >= G29_PEDAL_THRESHOLD);
if (rot >= 0x7ff8 && rot <= 0x8008) {
input_report_key(g29->input, KEY_A, 0);
input_report_key(g29->input, KEY_D, 0);
} else {
const int mag = rot < WHEEL_CENTER ? WHEEL_CENTER - rot : rot - WHEEL_CENTER;
const int duty = mag * period / 0x3000;
const int k1 = rot > WHEEL_CENTER ? KEY_D : KEY_A;
const int k2 = rot > WHEEL_CENTER ? KEY_A : KEY_D;
input_report_key(g29->input, k2, 0);
input_report_key(g29->input, k1, g29->phase_accumulator < duty);
}
g29->phase_accumulator++;
g29->phase_accumulator %= period;
input_sync(g29->input);
if (g29->current_mode == G29_MODE_WASD)
mod_timer(&g29->steer_timer, jiffies + msecs_to_jiffies(1));
}
static void process_media_mode(const struct g29_dev *g29, const struct g29_state *cur, const struct g29_state *prev) {
const u32 buttons = le32_to_cpu(cur->buttons_le);
for (int i = 0; i < ARRAY_SIZE(media_mode_keymap); i++) {
const struct g29_keymap *k = &media_mode_keymap[i];
input_report_key(g29->input, k->keycode, !!(buttons & k->mask));
}
input_sync(g29->input);
}
static void process_wasd_mode(const 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)
const u32 buttons = le32_to_cpu(cur->buttons_le);
input_report_key(g29->input, KEY_C, !!(buttons & G29_BTN_L1));
input_report_key(g29->input, KEY_SPACE, !!(buttons & G29_BTN_R1));
input_report_key(g29->input, KEY_ENTER, !!(buttons & G29_BTN_RETURN));
input_report_key(g29->input, KEY_M, !!(buttons & G29_BTN_CIRCLE));
if (buttons & G29_BTN_RED_CW) {
input_report_rel(g29->input, REL_WHEEL, 1);
} else if (buttons & G29_BTN_RED_CCW) {
input_report_rel(g29->input, REL_WHEEL, -1);
} else {
input_report_rel(g29->input, REL_WHEEL, 0);
}
input_sync(g29->input);
}
static void process_mouse_mode(const struct g29_dev *g29, const struct g29_state *cur, const struct g29_state *prev) {
const u32 buttons = le32_to_cpu(cur->buttons_le);
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];
input_report_key(g29->input, k->keycode, !!(buttons & k->mask));
}
if (pressed & G29_BTN_RED_CW) {
input_report_rel(g29->input, REL_WHEEL, 1);
} else if (pressed & G29_BTN_RED_CCW) {
input_report_rel(g29->input, REL_WHEEL, -1);
} else {
input_report_rel(g29->input, REL_WHEEL, 0);
}
input_sync(g29->input);
}
static void g29_check_mode_switch(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);
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) {
g29_switch_mode(g29, G29_MODE_MOUSE);
}
}
static void g29_process_report(struct g29_dev *g29, const u8 *data, const unsigned int len) {
if (len < 12) return;
const 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);
schedule_work(&g29->autocenter_work);
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);
cancel_work_sync(&g29->autocenter_work);
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->intf = intf;
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;
g29_find_int_out_ep(g29);
INIT_WORK(&g29->autocenter_work, g29_autocenter_work_fn);
__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);
input_set_capability(input, EV_KEY, KEY_C);
input_set_capability(input, EV_KEY, KEY_SPACE);
input_set_capability(input, EV_KEY, KEY_ENTER);
input_set_capability(input, EV_KEY, KEY_M);
// 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;
timer_delete_sync(&g29->steer_timer);
cancel_work_sync(&g29->autocenter_work);
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);
-75
View File
@@ -1,75 +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 0x10000000u
#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 0x8000
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
+28
View File
@@ -0,0 +1,28 @@
obj-m += g29_media_usb.o
PWD := $(CURDIR)
.PHONY: all clean install uninstall
all:
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
mkdir -p build
mv -f *.ko build/ 2>/dev/null || true
clean:
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
rm -rf build
install:
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules_install
depmod -a
uninstall:
@modpath=$$(modinfo -n g29_media_usb 2>/dev/null); \
if [ -z "$$modpath" ]; then \
echo "Module g29_media_usb not found via modinfo (not installed?)"; \
exit 1; \
fi; \
echo "Removing $$modpath"; \
rm -f "$$modpath"; \
depmod -a
+361
View File
@@ -0,0 +1,361 @@
// 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 <asm/unaligned.h>
MODULE_AUTHOR("LLP group 32");
MODULE_DESCRIPTION("Logitech G29 -> Media keys (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_REPORT_LEN 12
/*
* Button masks
*/
#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;
u16 rot;
u8 gas;
u8 brk;
u8 clt;
u8 grx;
u8 gry;
u8 grz;
};
/*
* Mapping table entry
*/
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;
struct g29_state last;
};
/* Parsing */
static bool g29_parse_report(struct g29_state *out, const u8 *data, int len)
{
if (len < G29_REPORT_LEN)
return false;
/* bytes 0..3 buttons bitfield */
out->buttons = get_unaligned_le32(&data[0]);
/* bytes 4..5 rotation */
out->rot = get_unaligned_le16(&data[4]);
out->gas = data[6];
out->brk = data[7];
out->clt = data[8];
out->grx = data[9];
out->gry = data[10];
out->grz = data[11];
return true;
}
/* Mapping policy */
static void g29_pulse_key(struct input_dev *input, unsigned short keycode)
{
/* A pulse is a press+release within one report frame. */
input_report_key(input, keycode, 1);
input_report_key(input, keycode, 0);
}
static void g29_apply_media_mode(struct g29_dev *g29,
const struct g29_state *prev,
const struct g29_state *cur)
{
u32 pressed = cur->buttons & ~prev->buttons;
size_t i;
for (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)
g29_pulse_key(g29->input, e->keycode);
}
input_sync(g29->input);
}
static void g29_process_report(struct g29_dev *g29, const u8 *data, int len)
{
struct g29_state cur;
if (!g29_parse_report(&cur, data, len))
return;
switch (mode) {
case G29_MODE_MEDIA:
default:
g29_apply_media_mode(g29, &g29->last, &cur);
break;
}
g29->last = cur;
}
/* URB plumbing */
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;
return 0;
}
static void g29_input_close(struct input_dev *input)
{
struct g29_dev *g29 = input_get_drvdata(input);
usb_kill_urb(g29->urb);
}
/* USB driver binding */
static int g29_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct usb_host_interface *alts = intf->cur_altsetting;
struct usb_endpoint_descriptor *ep = NULL;
struct g29_dev *g29;
struct input_dev *input;
int i, pipe, maxp, error;
/* Find an interrupt IN endpoint capable of carrying the 12-byte report. */
for (i = 0; i < alts->desc.bNumEndpoints; i++) {
struct usb_endpoint_descriptor *cand = &alts->endpoint[i].desc;
if (!usb_endpoint_is_int_in(cand))
continue;
pipe = usb_rcvintpipe(udev, cand->bEndpointAddress);
maxp = usb_maxpacket(udev, pipe);
if (maxp >= G29_REPORT_LEN) {
ep = cand;
break;
}
}
if (!ep)
return -ENODEV;
g29 = kzalloc(sizeof(*g29), GFP_KERNEL);
if (!g29)
return -ENOMEM;
input = input_allocate_device();
if (!input) {
error = -ENOMEM;
goto err_free_g29;
}
g29->udev = udev;
g29->input = input;
memset(&g29->last, 0, sizeof(g29->last));
/* Allocate a fixed-size report buffer (12 bytes). */
g29->buf = usb_alloc_coherent(udev, G29_REPORT_LEN, GFP_KERNEL, &g29->buf_dma);
if (!g29->buf) {
error = -ENOMEM;
goto err_free_input;
}
g29->urb = usb_alloc_urb(0, GFP_KERNEL);
if (!g29->urb) {
error = -ENOMEM;
goto err_free_buf;
}
/* Build a friendly input device name. */
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 Media %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_drvdata(input, g29);
input->open = g29_input_open;
input->close = g29_input_close;
pipe = usb_rcvintpipe(udev, ep->bEndpointAddress);
usb_fill_int_urb(g29->urb, udev, pipe,
g29->buf, G29_REPORT_LEN,
g29_urb_complete, g29, ep->bInterval);
g29->urb->transfer_dma = g29->buf_dma;
g29->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
error = input_register_device(input);
if (error)
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_REPORT_LEN, g29->buf, g29->buf_dma);
err_free_input:
input_free_device(input);
err_free_g29:
kfree(g29);
return error;
}
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_REPORT_LEN,
g29->buf, g29->buf_dma);
kfree(g29);
dev_info(&intf->dev, "G29 media 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_media_usb",
.probe = g29_probe,
.disconnect = g29_disconnect,
.id_table = g29_id_table,
};
module_usb_driver(g29_driver);
-71
View File
@@ -1,71 +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
- `0x10000000` - PS3 Logo
- `0xE0000000` - ?
- `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
+23 -39
View File
@@ -1,39 +1,23 @@
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
obj-m += simple_usb_mouse.o
PWD := $(CURDIR)
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
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
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
rm -rf build
install:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules_install
depmod -a
uninstall:
rm -f /lib/modules/$(shell uname -r)/kernel/drivers/usb/input/simple_usb_mouse.ko
depmod -a
-675
View File
@@ -1,675 +0,0 @@
// 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);