Merge branch 'master' of git://git.openpandora.org/pandora-libraries
[pandora-libraries.git] / apps / pndevmapperd.c
1
2 /* pndevmapperd exists to watch for a few interesting events and to launch scripts when they occur
3  * ie: when the lid closes, should invoke power-mode toggle sh-script
4  */
5
6 // woot for writing code while sick.
7
8 // this code begs a rewrite, but should work fine; its just arranged goofily
9 // -> I mean, why the racial divide between keys and other events
10
11 #include <stdio.h> /* for printf, NULL */
12 #include <stdlib.h> /* for free */
13 #include <string.h> /* for strdup */
14 #include <unistd.h>    // for exit()
15 #include <sys/types.h> // for umask
16 #include <sys/stat.h>  // for umask
17 #include <fcntl.h> // for open(2)
18 #include <errno.h> // for errno
19 #include <time.h> // for time(2)
20
21 #include <linux/input.h> // for keys
22 //#include "../../kernel-rip/input.h" // for keys
23
24 #include "pnd_conf.h"
25 #include "pnd_container.h"
26 #include "pnd_apps.h"
27 #include "pnd_discovery.h"
28 #include "pnd_locate.h"
29 #include "pnd_pndfiles.h"
30 #include "pnd_pxml.h"
31 #include "pnd_logger.h"
32
33 // daemon and logging
34 //
35 unsigned char g_daemon_mode = 0;
36 unsigned int g_minimum_separation = 1;
37
38 typedef enum {
39   pndn_debug = 0,
40   pndn_rem,          // will set default log level to here, so 'debug' is omitted
41   pndn_warning,
42   pndn_error,
43   pndn_none
44 } pndnotify_loglevels_e;
45
46 // key/event definition
47 //
48 typedef struct {
49   int keycode;
50   char *keyname;
51 } keycode_t;
52
53 keycode_t keycodes[] = {
54   { KEY_A, "a" },
55   { KEY_MENU, "pandora" },
56   { KEY_POWER, "power" },
57   { -1, NULL }
58 };
59
60 typedef struct {
61   int type;
62   int code;
63   char *name;
64 } generic_event_t;
65
66 generic_event_t generics[] = {
67   { EV_SW, 0, "lid-toggle" }, // expecting value 1 (lid close) or 0 (lid open)
68   { -1, -1, NULL }
69 };
70
71 // event-to-sh mapping
72 //
73 typedef struct {
74
75   unsigned char key_p; // 1 if its a key, otherwise an event
76
77   /* template information
78    */
79   void *reqs;          // scancode/etc for the event in question
80
81   char *script;        // script to invoke
82   //unsigned int hold_min; // minimum hold-time to trigger
83
84   /* state
85    */
86   time_t last_trigger_time;
87   time_t keydown_time;
88
89 } evmap_t;
90
91 #define MAXEVENTS 255
92 evmap_t g_evmap [ MAXEVENTS ];
93 unsigned int g_evmap_max = 0;
94
95 /* get to it
96  */
97 void dispatch_key ( int keycode, int val );
98 void dispatch_event ( int code, int val );
99
100 static void usage ( char *argv[] ) {
101   printf ( "%s [-d]\n", argv [ 0 ] );
102   printf ( "-d\tDaemon mode; detach from terminal, chdir to /tmp, suppress output. Optional.\n" );
103   printf ( "Signal: HUP the process to force reload of configuration and reset the notifier watch paths\n" );
104   return;
105 }
106
107 int main ( int argc, char *argv[] ) {
108   int i;
109
110   for ( i = 1; i < argc; i++ ) {
111
112     if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'd' ) {
113       //printf ( "Going daemon mode. Silent running.\n" );
114       g_daemon_mode = 1;
115     } else {
116       usage ( argv );
117       exit ( 0 );
118     }
119
120   } // for
121
122   /* enable logging?
123    */
124   if ( g_daemon_mode ) {
125     // nada
126   } else {
127     pnd_log_set_filter ( pndn_rem );
128     pnd_log_set_pretext ( "pndevmapperd" );
129     pnd_log_to_stdout();
130     pnd_log ( pndn_rem, "log level starting as %u", pnd_log_get_filter() );
131   }
132
133   // basic daemon set up
134   if ( g_daemon_mode ) {
135
136     // set a CWD somewhere else
137     chdir ( "/tmp" );
138
139     // detach from terminal
140     if ( ( i = fork() ) < 0 ) {
141       pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
142       exit ( i );
143     }
144     if ( i ) {
145       exit ( 0 ); // exit parent
146     }
147     setsid();
148
149     // umask
150     umask ( 022 ); // emitted files can be rwxr-xr-x
151     
152   } // set up daemon
153
154   /* inhale config or die trying
155    */
156   char *configpath;
157
158   // attempt to fetch a sensible default searchpath for configs
159   configpath = pnd_conf_query_searchpath();
160
161   // attempt to fetch the apps config. since it finds us the runscript
162   pnd_conf_handle evmaph;
163
164   evmaph = pnd_conf_fetch_by_id ( pnd_conf_evmap, configpath );
165
166   if ( ! evmaph ) {
167     // couldn't locate conf, just bail
168     pnd_log ( pndn_error, "ERROR: Couldn't locate conf file\n" );
169     exit ( -1 );
170   }
171
172   /* iterate across conf, stocking the event map
173    */
174   void *n = pnd_box_get_head ( evmaph );
175
176   while ( n ) {
177     char *k = pnd_box_get_key ( n );
178     //printf ( "key %s\n", k );
179
180     if ( strncmp ( k, "keys.", 5 ) == 0 ) {
181       k += 5;
182
183       // keys should really push push generic-events onto the table, since they;'re just a special case of them
184       // to make things easier to read
185
186       // figure out which keycode we're talking about
187       keycode_t *p = keycodes;
188       while ( p -> keycode != -1 ) {
189         if ( strcasecmp ( p -> keyname, k ) == 0 ) {
190           break;
191         }
192         p++;
193       }
194
195       if ( p -> keycode != -1 ) {
196         g_evmap [ g_evmap_max ].key_p = 1;    // its a key, not an event
197         g_evmap [ g_evmap_max ].reqs = p;     // note the keycode
198         g_evmap [ g_evmap_max ].script = n;   // note the script to activate in response
199         pnd_log ( pndn_rem, "Registered key %s [%d] to script %s\n", p -> keyname, p -> keycode, (char*) n );
200         g_evmap_max++;
201       } else {
202         pnd_log ( pndn_warning, "WARNING! Key '%s' is not handled by pndevmapperd yet! Skipping.", k );
203       }
204
205     } else if ( strncmp ( k, "events.", 7 ) == 0 ) {
206       k += 7;
207
208       // yes, key events could really be defined in this generic sense, and really we could just let people
209       // put the code and so on right in the conf, but trying to keep it easy on people; maybe should
210       // add a 'generic' section to conf file and just let folks redefine random events that way
211       // Really, it'd be nice if the /dev/input/events could spit out useful text, and just use scripts
212       // to respond without a daemon per se; for that matter, pnd-ls and pnd-map pnd-dotdesktopemitter
213       // should just exist as scripts rather than daemons, but whose counting?
214
215       // figure out which keycode we're talking about
216       generic_event_t *p = generics;
217       while ( p -> code != -1 ) {
218         if ( strcasecmp ( p -> name, k ) == 0 ) {
219           break;
220         }
221         p++;
222       }
223
224       if ( p -> code != -1 ) {
225         g_evmap [ g_evmap_max ].key_p = 0;    // its an event, not a key
226         g_evmap [ g_evmap_max ].reqs = p;     // note the keycode
227         g_evmap [ g_evmap_max ].script = n;   // note the script to activate in response
228         pnd_log ( pndn_rem, "Registered generic event %s [%d] to script %s\n", p -> name, p -> code, (char*) n );
229         g_evmap_max++;
230       } else {
231         pnd_log ( pndn_warning, "WARNING! Generic event '%s' is not handled by pndevmapperd yet! Skipping.", k );
232       }
233
234     } else if ( strncmp ( k, "pndevmapperd.", 7 ) == 0 ) {
235       // not consumed here, skip silently
236
237     } else {
238       // uhhh
239       pnd_log ( pndn_warning, "Unknown config key '%s'; skipping.\n", k );
240     }
241
242     n = pnd_box_get_next ( n );
243   } // while
244
245   if ( pnd_conf_get_as_int ( evmaph, "pndevmapperd.loglevel" ) != PND_CONF_BADNUM ) {
246     pnd_log_set_filter ( pnd_conf_get_as_int ( evmaph, "pndevmapperd.loglevel" ) );
247     pnd_log ( pndn_rem, "config file causes loglevel to change to %u", pnd_log_get_filter() );
248   }
249
250   if ( pnd_conf_get_as_int ( evmaph, "pndevmapperd.minimum_separation" ) != PND_CONF_BADNUM ) {
251     g_minimum_separation = pnd_conf_get_as_int ( evmaph, "pndevmapperd.minimum_separation" );
252     pnd_log ( pndn_rem, "config file causes minimum_separation to change to %u", g_minimum_separation );
253   }
254
255   /* do we have anything to do?
256    */
257   if ( ! g_evmap_max ) {
258     // uuuh, nothing to do?
259     pnd_log ( pndn_warning, "WARNING! No events configured to watch, so just spinning wheels...\n" );
260     exit ( -1 );
261   } // spin
262
263   /* actually try to do something useful
264    */
265
266   // stolen in part from notaz :)
267
268   // try to locate the appropriate devices
269   int id;
270   int fds [ 5 ] = { -1, -1, -1, -1, -1 }; // 0 = keypad, 1 = gpio keys
271   int imaxfd = 0;
272
273   for ( id = 0; ; id++ ) {
274     char fname[64];
275     char name[256] = { 0, };
276     int fd;
277
278     snprintf ( fname, sizeof ( fname ), "/dev/input/event%i", id );
279     fd = open ( fname, O_RDONLY );
280
281     if ( fd == -1 ) {
282       break;
283     }
284
285     ioctl (fd, EVIOCGNAME(sizeof(name)), name );
286
287     if ( strcmp ( name, "omap_twl4030keypad" ) == 0 ) {
288       fds [ 0 ] = fd;
289     } else if ( strcmp ( name, "gpio-keys" ) == 0) {
290       fds [ 1 ] = fd;
291     } else if ( strcmp ( name, "AT Translated Set 2 keyboard" ) == 0) { // for vmware, my dev environment
292       fds [ 0 ] = fd;
293     } else {
294       pnd_log ( pndn_rem, "Ignoring unknown device '%s'\n", name );
295       close ( fd );
296       continue;
297     }
298
299     if (imaxfd < fd) imaxfd = fd;
300   } // for
301
302   if ( fds [ 0 ] == -1 ) {
303     pnd_log ( pndn_warning, "WARNING! Couldn't find keypad device\n" );
304   }
305
306   if ( fds [ 1 ] == -1 ) {
307     pnd_log ( pndn_warning, "WARNING! couldn't find button device\n" );
308   }
309
310   if ( fds [ 0 ] == -1 && fds [ 1 ] == -1 ) {
311     pnd_log ( pndn_error, "ERROR! Couldn't find either device; exiting!\n" );
312     exit ( -2 );
313   }
314
315   /* loop forever, watching for events
316    */
317
318   while ( 1 ) {
319     struct input_event ev[64];
320
321     int fd = -1, rd, ret;
322     fd_set fdset;
323
324     FD_ZERO ( &fdset );
325
326     for (i = 0; i < 2; i++) {
327       if ( fds [ i ] != -1 ) {
328         FD_SET( fds [ i ], &fdset );
329       }
330     }
331
332     ret = select ( imaxfd + 1, &fdset, NULL, NULL, NULL );
333
334     if ( ret == -1 ) {
335       pnd_log ( pndn_error, "ERROR! select(2) failed with: %s\n", strerror ( errno ) );
336       break;
337     }
338
339     for ( i = 0; i < 2; i++ ) {
340       if ( fds [ i ] != -1 && FD_ISSET ( fds [ i ], &fdset ) ) {
341         fd = fds [ i ];
342       }
343     }
344
345     /* buttons or keypad */
346     rd = read ( fd, ev, sizeof(struct input_event) * 64 );
347     if ( rd < (int) sizeof(struct input_event) ) {
348       pnd_log ( pndn_error, "ERROR! read(2) input_event failed with: %s\n", strerror ( errno ) );
349       break;
350     }
351
352     for (i = 0; i < rd / sizeof(struct input_event); i++ ) {
353
354       if ( ev[i].type == EV_SYN ) {
355         continue;
356       } else if ( ev[i].type == EV_KEY ) {
357
358         // do we even know about this key at all?
359         keycode_t *p = keycodes;
360         while ( p -> keycode != -1 ) {
361           if ( p -> keycode == ev [ i ].code ) {
362             break;
363           }
364           p++;
365         }
366
367         // if we do, hand it off to dispatcher to look up if we actually do something with it
368         if ( p -> keycode != -1 ) {
369           pnd_log ( pndn_debug, "Key Event: key %s [%d] value %d\n", p -> keyname, p -> keycode, ev [ i ].value );
370           dispatch_key ( p -> keycode, ev [ i ].value );
371         } else {
372           pnd_log ( pndn_warning, "Unknown Key Event: keycode %d value %d\n",  ev [ i ].code, ev [ i ].value );
373         }
374
375       } else if ( ev[i].type == EV_SW ) {
376
377         // do we even know about this event at all?
378         generic_event_t *p = generics;
379         while ( p -> code != -1 ) {
380           if ( p -> code == ev [ i ].code ) {
381             break;
382           }
383           p++;
384         }
385
386         // if we do, hand it off to dispatcher to look up if we actually do something with it
387         if ( p -> code != -1 ) {
388           pnd_log ( pndn_debug, "Generic Event: event %s [%d] value %d\n", p -> name, p -> code, ev [ i ].value );
389           dispatch_event ( p -> code, ev [ i ].value );
390         } else {
391           pnd_log ( pndn_warning, "Unknown Generic Event: code %d value %d\n",  ev [ i ].code, ev [ i ].value );
392         }
393
394       } else {
395         pnd_log ( pndn_debug, "DEBUG: Unexpected event type %i received\n", ev[i].type );
396         continue;
397       } // type?
398
399     } // for
400
401   } // while
402
403   for (i = 0; i < 2; i++) {
404     if ( i != 2 && fds [ i ] != -1 ) {
405       close (fds [ i ] );
406     }
407   }
408
409   return ( 0 );
410 } // main
411
412 // this should really register the keystate and time, and then another func to monitor
413 // time-passage and check the registered list and act on the event..
414 void dispatch_key ( int keycode, int val ) {
415   unsigned int i;
416
417   // val decodes as:
418   // 1 - down (pressed)
419   // 2 - down again (hold)
420   // 0 - up (released)
421
422   for ( i = 0; i < g_evmap_max; i++ ) {
423
424     if ( ( g_evmap [ i ].key_p ) &&
425          ( ((keycode_t*) (g_evmap [ i ].reqs)) -> keycode == keycode ) &&
426          ( g_evmap [ i ].script ) )
427     {
428
429       // is this a keydown or a keyup?
430       if ( val == 1 ) {
431         // keydown
432         g_evmap [ i ].keydown_time = time ( NULL );
433
434       } else if ( val == 0 ) {
435         // keyup
436
437         char holdtime [ 128 ];
438         sprintf ( holdtime, "%d", (int)( time(NULL) - g_evmap [ i ].keydown_time ) );
439
440         if ( time ( NULL ) - g_evmap [ i ].last_trigger_time >= g_minimum_separation ) {
441           int x;
442
443           g_evmap [ i ].last_trigger_time = time ( NULL );
444
445           pnd_log ( pndn_rem, "Will attempt to invoke: %s %s\n", g_evmap [ i ].script, holdtime );
446
447           if ( ( x = fork() ) < 0 ) {
448             pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
449             exit ( -3 );
450           }
451
452           if ( x == 0 ) {
453             execl ( g_evmap [ i ].script, g_evmap [ i ].script, holdtime, (char*)NULL );
454             pnd_log ( pndn_error, "ERROR: Couldn't exec(%s)\n", g_evmap [ i ].script );
455             exit ( -4 );
456           }
457
458         } else {
459           pnd_log ( pndn_rem, "Skipping invokation.. falls within minimum_separation threshold\n" );
460         }
461
462       } // key up or down?
463
464       return;
465     } // found matching event for keycode
466
467   } // while
468
469   return;
470 }
471
472 void dispatch_event ( int code, int val ) {
473   unsigned int i;
474
475   // LID val decodes as:
476   // 1 - closing
477   // 0 - opening
478
479   for ( i = 0; i < g_evmap_max; i++ ) {
480
481     if ( ( g_evmap [ i ].key_p == 0 ) &&
482          ( ((generic_event_t*) (g_evmap [ i ].reqs)) -> code == code ) &&
483          ( g_evmap [ i ].script ) )
484     {
485
486       // just hand the code to the script (ie: 0 or 1 to script)
487       if ( time ( NULL ) - g_evmap [ i ].last_trigger_time >= g_minimum_separation ) {
488         int x;
489         char value [ 100 ];
490
491         sprintf ( value, "%d", val );
492
493         g_evmap [ i ].last_trigger_time = time ( NULL );
494
495         pnd_log ( pndn_rem, "Will attempt to invoke: %s %s\n", g_evmap [ i ].script, value );
496
497         if ( ( x = fork() ) < 0 ) {
498           pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
499           exit ( -3 );
500         }
501
502         if ( x == 0 ) {
503           execl ( g_evmap [ i ].script, g_evmap [ i ].script, value, (char*)NULL );
504           pnd_log ( pndn_error, "ERROR: Couldn't exec(%s)\n", g_evmap [ i ].script );
505           exit ( -4 );
506         }
507
508       } else {
509         pnd_log ( pndn_rem, "Skipping invokation.. falls within minimum_separation threshold\n" );
510       }
511
512       return;
513     } // found matching event for keycode
514
515   } // while
516
517   return;
518 }