add op_lidstate
[pandora-misc.git] / op_lidstate.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 #include <sys/ioctl.h>
6 #include <fcntl.h>
7 #include <unistd.h>
8 #include <errno.h>
9 #include <linux/input.h>
10
11 int main(int argc, char *argv[])
12 {
13         unsigned int state = 0;
14         int fd = -1;
15         int id, ret;
16
17         if (argv[1] != NULL
18             && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")))
19         {
20                 fprintf(stderr, "prints 1 if lid is closed, "
21                                 "0 if open or in unknown state "
22                                 "or if an error occurs\n");
23                 return 0;
24         }
25
26         for (id = 0; id < 100; id++)
27         {
28                 char fname[64];
29                 char name[64];
30
31                 snprintf(fname, sizeof(fname), "/dev/input/event%i", id);
32                 fd = open(fname, O_RDONLY);
33                 if (fd == -1)
34                 {
35                         if (errno == EACCES)
36                                 continue;
37                         break;
38                 }
39
40                 name[0] = 0;
41                 ioctl(fd, EVIOCGNAME(sizeof(name)), name);
42                 if (!strcmp(name, "gpio-keys"))
43                         break;
44
45                 close(fd);
46                 fd = -1;
47         }
48
49         if (fd == -1)
50         {
51                 fprintf(stderr, "unable to find or access gpio-keys\n");
52                 fprintf(stdout, "0\n");
53                 return 1;
54         }
55
56         ret = ioctl(fd, EVIOCGSW(sizeof(state)), &state);
57         close(fd);
58         if (ret < 0)
59         {
60                 perror("ioctl EVIOCGSW");
61                 fprintf(stdout, "0\n");
62                 return 1;
63         }
64
65         printf("%d\n", state & (1u << SW_LID) ? 1 : 0);
66
67         return 0;
68 }