autoclicker/main.c

106 lines
2.0 KiB
C

/*
* LICENSE: WTFPL
*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <limits.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <linux/uinput.h>
#include <linux/input.h>
/* For signal handler */
int uinput_fd;
int event_fd;
void emit(int fd, int type, int code, int val) {
struct input_event ie;
ie.type = type;
ie.code = code;
ie.value = val;
/* timestamp values below are ignored */
ie.time.tv_sec = 0;
ie.time.tv_usec = 0;
write(fd, &ie, sizeof(ie));
}
void press(int fd) {
puts("CLICK");
for (int i = 0; i < 10; i++) {
usleep(50000);
emit(fd, EV_KEY, BTN_LEFT, 1);
emit(fd, EV_SYN, SYN_REPORT, 0);
emit(fd, EV_KEY, BTN_LEFT, 0);
emit(fd, EV_SYN, SYN_REPORT, 0);
}
}
void stop(int sig) {
(void)sig;
ioctl(uinput_fd, UI_DEV_DESTROY);
close(uinput_fd);
close(event_fd);
puts("Stoping...");
exit(0);
}
int main(int argc, char **argv) {
signal(SIGTERM, stop);
signal(SIGINT, stop);
uinput_fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
if (uinput_fd < 0) {
fprintf(stderr, "autoclicker: /dev/uinput: %s\n", strerror(errno));
return 1;
}
/* Keyboard events */
event_fd = open("/dev/input/event1", O_RDONLY);
if (event_fd < 0) {
close(uinput_fd);
fprintf(stderr, "autoclicker: /dev/input/eventX: %s\n", strerror(errno));
return 1;
}
/* Setup uinput */
ioctl(uinput_fd, UI_SET_EVBIT, EV_KEY);
ioctl(uinput_fd, UI_SET_KEYBIT, BTN_LEFT);
/* Setup struct */
struct uinput_setup usetup;
memset(&usetup, 0, sizeof(usetup));
usetup.id.bustype = BUS_USB;
usetup.id.vendor = 0x123;
usetup.id.product = 0x123;
snprintf(usetup.name, UINPUT_MAX_NAME_SIZE, "autoclicker");
ioctl(uinput_fd, UI_DEV_SETUP, &usetup);
ioctl(uinput_fd, UI_DEV_CREATE);
/* Main */
int flag = 0;
struct input_event event;
while (read(event_fd, &event, sizeof(event)) > 0) {
printf("You cliekced: %d\n", event.code);
if (event.code == 275 || event.code == 276)
press(uinput_fd);
}
stop(0);
}