secret
anonymous / readinput_c.c
Created

  • Download Gist
readinput_c.c
C
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <dirent.h>
#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/time.h>
#include <termios.h>
#include <signal.h>
#include <ruby.h>
#include <poll.h>
 
 
static VALUE t_init(VALUE self, VALUE device)
{
int k_fd;
int m_fd;
char * path = RSTRING_PTR(device);
if ((k_fd = open (path, O_RDONLY)) == -1)
rb_raise(rb_eIOError, "Cannot open device %s", path);
rb_iv_set(self, "@fd", INT2FIX(k_fd));
return self;
}
 
static VALUE t_read(VALUE self)
{
int fd = FIX2INT(rb_iv_get(self, "@fd"));
 
int retval;
struct pollfd rfds[1] =
{
{fd, POLLIN, 0}
};
 
 
retval = poll(rfds, 1, -1);
 
if (retval == -1)
rb_raise(rb_eIOError, "Poll error");
else if (!retval)
rb_raise(rb_eIOError, "No data");
 
if (!(rfds[0].revents & POLLIN))
rb_raise(rb_eIOError, "No descriptor ready");
 
struct input_event ev[64];
size_t size = sizeof(struct input_event);
size_t maxSize = sizeof(ev);
size_t readSize;
 
if ((readSize = read(fd, ev, maxSize)) < size)
rb_raise(rb_eIOError, "Cannot read on device");
 
size_t i;
for(i = 0; i < readSize / size; i++)
{
struct input_event *event = ev + i;
printf("%d:%d", event->type, event->code);
if (event->type == EV_KEY)
{
VALUE result = rb_funcall(self,
rb_intern("create_event"),
4,
UINT2NUM(event->type),
UINT2NUM(event->code),
INT2NUM(event->value),
rb_time_new(event->time.tv_sec, event->time.tv_usec));
return result;
}
}
 
return Qnil;
}
 
VALUE mReadInput;
VALUE cReader;
 
void Init_readinput_c()
{
mReadInput = rb_define_module("ReadInput");
cReader = rb_define_class_under(mReadInput, "Reader", rb_cObject);
rb_define_method(cReader, "initialize", t_init, 1);
rb_define_method(cReader, "read", t_read, 0);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.