summaryrefslogtreecommitdiffstats
path: root/input.c
blob: bb1d82de6f36a169e51d1a5c830aa5093099c96a (plain)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include "project.h"

input_dev_t *input_devs = NULL;


static void
set_nonblocking (int fd)
{
  long arg = 0;
  arg = fcntl (fd, F_GETFL, arg);
  arg |= O_NONBLOCK;
  fcntl (fd, F_SETFL, arg);
}

static char *
input_dev_name (int i)
{
  static char fn[1024];
  sprintf (fn, "/dev/input/event%d", i);
  return fn;
}

static input_dev_t *
get_input_dev (int id)
{
  input_dev_t *ret;
  int fd;
  unsigned short ids[4];
  char *fn;

  for (ret = input_devs; ret; ret = ret->next)
    if (ret->id == id)
      return ret;


  fn = input_dev_name (id);

  fd = open (fn, O_RDWR);
  if (fd < 0)
    return NULL;

  set_nonblocking (fd);

  ret = malloc (sizeof (*ret));
  bzero (ret, sizeof (*ret));

  ret->id = id;
  ret->fd = fd;

  ioctl (fd, EVIOCGID, ids);

  if ((ids[ID_VENDOR] == 0xea0) && (ids[ID_PRODUCT] == 0x2211))
    ret->blacklistid = 1;

  printf
    ("New input device %s (%d) bus 0x%x vendor 0x%x product 0x%x version 0x%x\n",
     fn, id, ids[ID_BUS], ids[ID_VENDOR], ids[ID_PRODUCT], ids[ID_VERSION]);

  ret->next = input_devs;
  input_devs = ret;

  return ret;
}

static void
free_input_dev (input_dev_t * d)
{
  printf ("Removid input device %s (%d)\n", input_dev_name (d->id), d->id);

  if (d->fd > -1)
    close (d->fd);
  free (d);
}


void
scan_input_devs (void)
{
  DIR *dir = opendir ("/dev/input");
  struct dirent *de;
  int i;
  input_dev_t *id, **idp;
  int version;


  for (idp = &input_devs; (id = *idp);)
    {
      id->present = 0;
      if (access (input_dev_name (id->id), F_OK)
          || ioctl (id->fd, EVIOCGVERSION, &version))
        {
          *idp = id->next;
          free_input_dev (id);
        }
      else
        {
          idp = &id->next;
        }
    }

  if (dir)
    {
      while ((de = readdir (dir)))
        {
          if (!strcmp (de->d_name, "event"))
            continue;
          i = atoi (de->d_name + 5);
          id = get_input_dev (i);
          if (id)
            id->present = 1;
        }
      closedir (dir);
    }


  for (idp = &input_devs; (id = *idp);)
    {
      if (!id->present)
        {
          *idp = id->next;
          free_input_dev (id);
        }
      else
        {
          idp = &id->next;
        }
    }


}