1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
#include <linux/input.h>
#include <linux/uinput.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h> /* memset */
#include <stdlib.h> /* EXIT_FAILURE */
int keys[] = {
KEY_Q, /* prev */
KEY_E, /* next */
KEY_Z, /* shoot */
KEY_W,
KEY_A,
KEY_S,
KEY_D,
KEY_P, /* pause */
KEY_BACKSPACE, /* really "backspace" */
};
#define ARRAY_SIZE(a) (sizeof (a) / sizeof *(a) )
int main() {
int i;
int fd = open("/dev/uinput", O_WRONLY);
if (fd < 0) {
perror("open");
return 1;
}
if (ioctl(fd, UI_SET_EVBIT, EV_KEY) < 0) {
perror("Cannot set EV_KEY bit");
goto err_close;
}
if (ioctl(fd, UI_SET_EVBIT, EV_SYN) < 0) {
perror("Cannot set EV_SYN bit");
goto err_close;
}
for (i = 0; i < ARRAY_SIZE(keys); ++i) {
if (ioctl(fd, UI_SET_KEYBIT, keys[i]) < 0) {
perror("SET_KEYBIT");
goto err_close;
}
}
struct uinput_user_dev uidev;
memset(&uidev, 0, sizeof(uidev));
snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "Boxhead");
if (write(fd, &uidev, sizeof(uidev)) < 0) {
perror("write uinput struct");
goto err_close;
}
if (ioctl(fd, UI_DEV_CREATE) < 0) {
perror("UI_DEV_CREATE");
goto err_close;
}
unsigned int code, is_pressed;
printf("Waiting for input...\n");
struct input_event ev;
memset(&ev, 0, sizeof(ev));
while (scanf("%u %u", &code, &is_pressed) == 2) {
if (code >= 1 && code <= ARRAY_SIZE(keys)) {
ev.type = EV_KEY;
ev.code = keys[code - 1];
ev.value = !!is_pressed;
//printf("code=%u value=%u\n", ev.code, ev.value);
if (write(fd, &ev, sizeof(ev)) < 0)
perror("write key");
/* input_sync() */
ev.type = EV_SYN;
ev.code = SYN_REPORT;
ev.value = 0;
if (write(fd, &ev, sizeof(ev)) < 0)
perror("write sync");
} else {
fprintf(stderr, "Unexpected key: %u (%#02x)\n", code, code);
break;
}
}
if (ioctl(fd, UI_DEV_DESTROY) < 0)
perror("Cannot destroy device");
if (close(fd) < 0)
perror("close");
return 0;
err_close:
if (close(fd) < 0)
perror("close");
return EXIT_FAILURE;
}
|