Uinput

From Ilianko
Revision as of 15:40, 13 April 2011 by Anko (talk | contribs)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <linux/input.h>
#include <linux/uinput.h>


int main(void)
{
    int                    fd, kb_fd;
    struct uinput_user_dev uidev;
    struct input_event     ev, kb_ev;
    int                    dx, dy;
    

    fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
    
    if (fd == -1) {
      puts("Can't open file");
    return 1;
    }
    
    
    ioctl(fd, UI_SET_EVBIT, EV_KEY);
    ioctl(fd, UI_SET_KEYBIT, BTN_LEFT);
    ioctl(fd, UI_SET_EVBIT, EV_REL) ;
    ioctl(fd, UI_SET_RELBIT, REL_X);
    ioctl(fd, UI_SET_RELBIT, REL_Y);
   
    memset(&uidev, 0, sizeof(uidev));
    snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "uinput-sample");
    uidev.id.bustype = BUS_USB;
    uidev.id.vendor  = 0x1;
    uidev.id.product = 0x1;
    uidev.id.version = 1;

    if(write(fd, &uidev, sizeof(uidev)) < 0)
        {
      puts("Can't open file");
    return 1;
    }
    
	if(ioctl(fd, UI_DEV_CREATE) < 0)
       {
      puts("Can't open file");
    return 1;
    }

    kb_fd = open("/dev/input/event3", O_RDWR);
    if (kb_fd < 0)
    {  
	puts("cant open kb");
	return 1;
    }
    
    while (1)
    {
		
    read(kb_fd, &kb_ev, sizeof(struct input_event));

    if( kb_ev.type == 1 && (kb_ev.value == 2 || kb_ev.value == 1))
    {
		
		memset(&ev, 0, sizeof(ev));
    gettimeofday(&ev.time, NULL);
    usleep(100);
		 switch (kb_ev.code)
	  {
	    case 105: 
	      ev.type = EV_REL;
          ev.code = REL_X;
          ev.value = -5;
	    break;
	    
	    case 106: 
	      ev.type = EV_REL;
          ev.code = REL_X;
          ev.value = 5;
	    break;
	    
	    case 103: 
	      ev.type = EV_REL;
          ev.code = REL_Y;
          ev.value = -5;
	    break;
	    
	    case 108: 
	      ev.type = EV_REL;
          ev.code = REL_Y;
          ev.value = 5;
	    break;
	    
        default:
          ev.type = EV_REL;
          ev.code = REL_X;
          ev.value = -5;
      }
		
    write(fd, &ev, sizeof(ev));
    usleep(100);
    
    gettimeofday(&ev.time, NULL);
    ev.type = 0;
    ev.code = 0;
    ev.value = 0;
    write(fd, &ev, sizeof(ev));
    }
  }  
    
    

  close(fd);
  return 0;
}