evmapperd can now have a max-hold set for a key, so that power and pandora buttons can
[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 // -> now that I've put together pnd_io_evdev, should leverage that; be much cleaner.
11
12 #include <stdio.h> /* for printf, NULL */
13 #include <stdlib.h> /* for free */
14 #include <string.h> /* for strdup */
15 #include <unistd.h>    // for exit()
16 #include <sys/types.h> // for umask
17 #include <sys/stat.h>  // for umask
18 #include <fcntl.h> // for open(2)
19 #include <errno.h> // for errno
20 #include <time.h> // for time(2)
21 #include <ctype.h> // for isdigit
22 #include <signal.h> // for sigaction
23 #include <sys/wait.h> // for wait
24 #include <sys/time.h> // setitimer
25
26 #include <linux/input.h> // for keys
27 //#include "../../kernel-rip/input.h" // for keys
28
29 #include "pnd_conf.h"
30 #include "pnd_container.h"
31 #include "pnd_apps.h"
32 #include "pnd_discovery.h"
33 #include "pnd_locate.h"
34 #include "pnd_pndfiles.h"
35 #include "pnd_pxml.h"
36 #include "pnd_logger.h"
37 #include "pnd_utility.h"
38 #include "pnd_notify.h"
39 #include "pnd_device.h"
40
41 // daemon and logging
42 //
43 unsigned char g_daemon_mode = 0;
44 unsigned int g_minimum_separation = 1;
45
46 typedef enum {
47   pndn_debug = 0,
48   pndn_rem,          // will set default log level to here, so 'debug' is omitted
49   pndn_warning,
50   pndn_error,
51   pndn_none
52 } pndnotify_loglevels_e;
53
54 // key/event definition
55 //
56 typedef struct {
57   int keycode;
58   char *keyname;
59 } keycode_t;
60
61 keycode_t keycodes[] = {
62   { KEY_A, "a" },
63   { KEY_B, "b" },
64   { KEY_MENU, "pandora" },
65   { KEY_POWER, "power" },
66   { KEY_DELETE, "del" },
67   { KEY_COMMA, "comma" },
68   { KEY_1, "1" },
69   { KEY_2, "2" },
70   { KEY_3, "3" },
71   { KEY_4, "4" },
72   { KEY_5, "5" },
73   { KEY_6, "6" },
74   { KEY_7, "7" },
75   { KEY_8, "8" },
76   { KEY_9, "9" },
77   { KEY_0, "0" },
78   { KEY_BRIGHTNESSDOWN, "lcdbrightdown" },
79   { KEY_BRIGHTNESSUP, "lcdbrightup" },
80   { -1, NULL }
81 };
82
83 typedef struct {
84   int type;
85   int code;
86   char *name;
87 } generic_event_t;
88
89 generic_event_t generics[] = {
90   { EV_SW, 0, "lid-toggle" }, // expecting value 1 (lid close) or 0 (lid open)
91   { -1, -1, NULL }
92 };
93
94 // event-to-sh mapping
95 //
96 typedef struct {
97
98   unsigned char key_p; // 1 if its a key, otherwise an event
99
100   /* template information
101    */
102   void *reqs;          // scancode/etc for the event in question
103
104   char *script;        // script to invoke
105   unsigned int maxhold;   // maximum hold-time before forcing script invocation
106
107   /* state
108    */
109   time_t last_trigger_time;
110   time_t keydown_time;
111
112 } evmap_t;
113
114 #define MAXEVENTS 255
115 evmap_t g_evmap [ MAXEVENTS ];
116 unsigned int g_evmap_max = 0;
117
118 // battery
119 unsigned char b_threshold = 5;    // %battery
120 unsigned int b_frequency = 300;   // frequency to check
121 unsigned int b_blinkfreq = 2;     // blink every 2sec
122 unsigned int b_blinkdur = 1000;   // blink duration (uSec), 0sec + uSec is assumed
123 unsigned char b_active = 0;       // 0=inactive, 1=active and waiting to blink, 2=blink is on, waiting to turn off
124 unsigned char b_shutdown = 1;     // %age battery to force a shutdown!
125 char *b_shutdown_script = NULL;
126
127 /* get to it
128  */
129 void dispatch_key ( int keycode, int val );
130 void dispatch_event ( int code, int val );
131 void sigchld_handler ( int n );
132 unsigned char set_next_alarm ( unsigned int secs, unsigned int usecs );
133 void sigalrm_handler ( int n );
134
135 static void usage ( char *argv[] ) {
136   printf ( "%s [-d]\n", argv [ 0 ] );
137   printf ( "-d\tDaemon mode; detach from terminal, chdir to /tmp, suppress output. Optional.\n" );
138   printf ( "-l#\tLog-it; -l is 0-and-up (or all), and -l2 means 2-and-up (not all); l[0-3] for now. Log goes to /tmp/pndevmapperd.log\n" );
139   return;
140 }
141
142 int main ( int argc, char *argv[] ) {
143   int i;
144   int logall = -1; // -1 means normal logging rules; >=0 means log all!
145
146   for ( i = 1; i < argc; i++ ) {
147
148     if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'd' ) {
149       //printf ( "Going daemon mode. Silent running.\n" );
150       g_daemon_mode = 1;
151     } else if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'l' ) {
152
153       if ( isdigit ( argv [ i ][ 2 ] ) ) {
154         unsigned char x = atoi ( argv [ i ] + 2 );
155         if ( x >= 0 &&
156              x < pndn_none )
157         {
158           logall = x;
159         }
160       } else {
161         logall = 0;
162       }
163     } else {
164       usage ( argv );
165       exit ( 0 );
166     }
167
168   } // for
169
170   /* enable logging?
171    */
172   pnd_log_set_pretext ( "pndevmapperd" );
173   pnd_log_set_flush ( 1 );
174
175   if ( logall == -1 ) {
176     // standard logging; non-daemon versus daemon
177
178     if ( g_daemon_mode ) {
179       // nada
180     } else {
181       pnd_log_set_filter ( pndn_rem );
182       pnd_log_to_stdout();
183     }
184
185   } else {
186     FILE *f;
187
188     f = fopen ( "/tmp/pndevmapperd.log", "w" );
189
190     if ( f ) {
191       pnd_log_set_filter ( logall );
192       pnd_log_to_stream ( f );
193       pnd_log ( pndn_rem, "logall mode - logging to /tmp/pndevmapperd.log\n" );
194     }
195
196     if ( logall == pndn_debug ) {
197       pnd_log_set_buried_logging ( 1 ); // log the shit out of it
198       pnd_log ( pndn_rem, "logall mode 0 - turned on buried logging\n" );
199     }
200
201   } // logall
202
203   pnd_log ( pndn_rem, "%s built %s %s", argv [ 0 ], __DATE__, __TIME__ );
204
205   pnd_log ( pndn_rem, "log level starting as %u", pnd_log_get_filter() );
206
207   // basic daemon set up
208   if ( g_daemon_mode ) {
209
210     // set a CWD somewhere else
211     chdir ( "/tmp" );
212
213     // detach from terminal
214     if ( ( i = fork() ) < 0 ) {
215       pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
216       exit ( i );
217     }
218     if ( i ) {
219       exit ( 0 ); // exit parent
220     }
221     setsid();
222
223     // umask
224     umask ( 022 ); // emitted files can be rwxr-xr-x
225     
226   } // set up daemon
227
228   /* hmm, seems to not like working right after boot.. do we depend on another daemon or
229    * on giving kernel time to init something, or ... wtf?
230    * -- lets give the system some time to wake up
231    */
232   { // delay
233
234     // this one works for pndnotifyd, which actually needs INOTIFYH..
235     //
236
237     // check if inotify is awake yet; if not, try waiting for awhile to see if it does
238     pnd_log ( pndn_rem, "Starting INOTIFY test; should be instant, but may take awhile...\n" );
239
240     if ( ! pnd_notify_wait_until_ready ( 120 /* seconds */ ) ) {
241       pnd_log ( pndn_error, "ERROR: INOTIFY refuses to be useful and quite awhile has passed. Bailing out.\n" );
242       return ( -1 );
243     }
244
245     pnd_log ( pndn_rem, "INOTIFY seems to be useful, whew.\n" );
246
247     // pndnotifyd also waits for user to log in .. pretty excessive, especially since
248     // what if user wants to close the lid while at the log in screen? for now play the
249     // odds as thats pretty unliekly usage scenariom but is clearly not acceptible :/
250     //
251
252     // wait for a user to be logged in - we should probably get hupped when a user logs in, so we can handle
253     // log-out and back in again, with SDs popping in and out between..
254     pnd_log ( pndn_rem, "Checking to see if a user is logged in\n" );
255     char tmp_username [ 128 ];
256     while ( 1 ) {
257       if ( pnd_check_login ( tmp_username, 127 ) ) {
258         break;
259       }
260       pnd_log ( pndn_debug, "  No one logged in yet .. spinning.\n" );
261       sleep ( 2 );
262     } // spin
263     pnd_log ( pndn_rem, "Looks like user '%s' is in, continue.\n", tmp_username );
264
265   } // delay
266
267   /* inhale config or die trying
268    */
269   char *configpath;
270
271   // attempt to fetch a sensible default searchpath for configs
272   configpath = pnd_conf_query_searchpath();
273
274   // attempt to fetch the apps config. since it finds us the runscript
275   pnd_conf_handle evmaph;
276
277   evmaph = pnd_conf_fetch_by_id ( pnd_conf_evmap, configpath );
278
279   if ( ! evmaph ) {
280     // couldn't locate conf, just bail
281     pnd_log ( pndn_error, "ERROR: Couldn't locate conf file\n" );
282     exit ( -1 );
283   }
284
285   /* iterate across conf, stocking the event map
286    */
287   void *n = pnd_box_get_head ( evmaph );
288
289   while ( n ) {
290     char *k = pnd_box_get_key ( n );
291     //printf ( "key %s\n", k );
292
293     if ( strncmp ( k, "keys.", 5 ) == 0 ) {
294       k += 5;
295
296       // keys should really push push generic-events onto the table, since they;'re just a special case of them
297       // to make things easier to read
298
299       // figure out which keycode we're talking about
300       keycode_t *p = keycodes;
301       while ( p -> keycode != -1 ) {
302         if ( strcasecmp ( p -> keyname, k ) == 0 ) {
303           break;
304         }
305         p++;
306       }
307
308       if ( p -> keycode != -1 ) {
309         g_evmap [ g_evmap_max ].key_p = 1;    // its a key, not an event
310         g_evmap [ g_evmap_max ].reqs = p;     // note the keycode
311
312         // note the script to activate in response
313         if ( strchr ( n, ' ' ) ) {
314           char *foo = strdup ( n );
315           char *t = strchr ( foo, ' ' );
316           *t = '\0';
317           g_evmap [ g_evmap_max ].script = foo;
318           g_evmap [ g_evmap_max ].maxhold = atoi ( t + 1 );
319         } else {
320           g_evmap [ g_evmap_max ].script = n;
321           g_evmap [ g_evmap_max ].maxhold = 0;
322         }
323
324         pnd_log ( pndn_rem, "Registered key %s [%d] to script %s with maxhold %d\n",
325                   p -> keyname, p -> keycode, (char*) n, g_evmap [ g_evmap_max ].maxhold );
326
327         g_evmap_max++;
328       } else {
329         pnd_log ( pndn_warning, "WARNING! Key '%s' is not handled by pndevmapperd yet! Skipping.", k );
330       }
331
332     } else if ( strncmp ( k, "events.", 7 ) == 0 ) {
333       k += 7;
334
335       // yes, key events could really be defined in this generic sense, and really we could just let people
336       // put the code and so on right in the conf, but trying to keep it easy on people; maybe should
337       // add a 'generic' section to conf file and just let folks redefine random events that way
338       // Really, it'd be nice if the /dev/input/events could spit out useful text, and just use scripts
339       // to respond without a daemon per se; for that matter, pnd-ls and pnd-map pnd-dotdesktopemitter
340       // should just exist as scripts rather than daemons, but whose counting?
341
342       // figure out which keycode we're talking about
343       generic_event_t *p = generics;
344       while ( p -> code != -1 ) {
345         if ( strcasecmp ( p -> name, k ) == 0 ) {
346           break;
347         }
348         p++;
349       }
350
351       if ( p -> code != -1 ) {
352         g_evmap [ g_evmap_max ].key_p = 0;    // its an event, not a key
353         g_evmap [ g_evmap_max ].reqs = p;     // note the keycode
354         g_evmap [ g_evmap_max ].script = n;   // note the script to activate in response
355         pnd_log ( pndn_rem, "Registered generic event %s [%d] to script %s\n", p -> name, p -> code, (char*) n );
356         g_evmap_max++;
357       } else {
358         pnd_log ( pndn_warning, "WARNING! Generic event '%s' is not handled by pndevmapperd yet! Skipping.", k );
359       }
360
361     } else if ( strncmp ( k, "pndevmapperd.", 7 ) == 0 ) {
362       // not consumed here, skip silently
363
364     } else if ( strncmp ( k, "battery.", 8 ) == 0 ) {
365       // not consumed here, skip silently
366
367     } else {
368       // uhhh
369       pnd_log ( pndn_warning, "Unknown config key '%s'; skipping.\n", k );
370     }
371
372     n = pnd_box_get_next ( n );
373   } // while
374
375   if ( pnd_conf_get_as_int ( evmaph, "pndevmapperd.loglevel" ) != PND_CONF_BADNUM ) {
376     pnd_log_set_filter ( pnd_conf_get_as_int ( evmaph, "pndevmapperd.loglevel" ) );
377     pnd_log ( pndn_rem, "config file causes loglevel to change to %u", pnd_log_get_filter() );
378   }
379
380   if ( pnd_conf_get_as_int ( evmaph, "pndevmapperd.minimum_separation" ) != PND_CONF_BADNUM ) {
381     g_minimum_separation = pnd_conf_get_as_int ( evmaph, "pndevmapperd.minimum_separation" );
382     pnd_log ( pndn_rem, "config file causes minimum_separation to change to %u", g_minimum_separation );
383   }
384
385   // battery conf
386   if ( pnd_conf_get_as_int ( evmaph, "battery.threshold" ) != PND_CONF_BADNUM ) {
387     b_threshold = pnd_conf_get_as_int ( evmaph, "battery.threshold" );
388     pnd_log ( pndn_rem, "Battery threshold set to %u", b_threshold );
389   }
390   if ( pnd_conf_get_as_int ( evmaph, "battery.check_interval" ) != PND_CONF_BADNUM ) {
391     b_frequency = pnd_conf_get_as_int ( evmaph, "battery.check_interval" );
392     pnd_log ( pndn_rem, "Battery check interval set to %u", b_frequency );
393   }
394   if ( pnd_conf_get_as_int ( evmaph, "battery.blink_interval" ) != PND_CONF_BADNUM ) {
395     b_blinkfreq = pnd_conf_get_as_int ( evmaph, "battery.blink_interval" );
396     pnd_log ( pndn_rem, "Battery blink interval set to %u", b_blinkfreq );
397   }
398   if ( pnd_conf_get_as_int ( evmaph, "battery.blink_duration" ) != PND_CONF_BADNUM ) {
399     b_blinkdur = pnd_conf_get_as_int ( evmaph, "battery.blink_duration" );
400     pnd_log ( pndn_rem, "Battery blink duration set to %u", b_blinkdur );
401   }
402   b_active = 0;
403   if ( pnd_conf_get_as_int ( evmaph, "battery.shutdown_threshold" ) != PND_CONF_BADNUM ) {
404     b_shutdown = pnd_conf_get_as_int ( evmaph, "battery.shutdown_threshold" );
405     pnd_log ( pndn_rem, "Battery shutdown threshold set to %u", b_shutdown );
406   }
407   if ( pnd_conf_get_as_char ( evmaph, "battery.shutdown_script" ) != NULL ) {
408     b_shutdown_script = strdup ( pnd_conf_get_as_char ( evmaph, "battery.shutdown_script" ) );
409     pnd_log ( pndn_rem, "Battery shutdown script set to %s", b_shutdown_script );
410   }
411
412   /* do we have anything to do?
413    */
414   if ( ! g_evmap_max ) {
415     // uuuh, nothing to do?
416     pnd_log ( pndn_warning, "WARNING! No events configured to watch, so just spinning wheels...\n" );
417     exit ( -1 );
418   } // spin
419
420   /* set up sigchld -- don't want zombies all over; well, we do, but not process zombies
421    */
422   sigset_t ss;
423   sigemptyset ( &ss );
424
425   struct sigaction siggy;
426   siggy.sa_handler = sigchld_handler;
427   siggy.sa_mask = ss; /* implicitly blocks the origin signal */
428   siggy.sa_flags = SA_RESTART; /* don't need anything */
429   sigaction ( SIGCHLD, &siggy, NULL );
430
431   /* set up the battery level warning timers
432    */
433   siggy.sa_handler = sigalrm_handler;
434   siggy.sa_mask = ss; /* implicitly blocks the origin signal */
435   siggy.sa_flags = SA_RESTART; /* don't need anything */
436   sigaction ( SIGALRM, &siggy, NULL );
437
438   if ( set_next_alarm ( b_frequency, 0 ) ) { // check every 'frequency' seconds
439     pnd_log ( pndn_rem, "Checking for low battery every %u seconds\n", b_frequency );
440   } else {
441     pnd_log ( pndn_error, "ERROR: Couldn't set up timer for every %u seconds\n", b_frequency );
442   }
443
444   /* actually try to do something useful
445    */
446
447   // stolen in part from notaz :)
448
449   // try to locate the appropriate devices
450   int id;
451   int fds [ 8 ] = { -1, -1, -1, -1, -1, -1, -1, -1 }; // 0 = keypad, 1 = gpio keys
452   int imaxfd = 0;
453
454   for ( id = 0; ; id++ ) {
455     char fname[64];
456     char name[256] = { 0, };
457     int fd;
458
459     snprintf ( fname, sizeof ( fname ), "/dev/input/event%i", id );
460     fd = open ( fname, O_RDONLY );
461
462     if ( fd == -1 ) {
463       break;
464     }
465
466     if ( ioctl (fd, EVIOCGNAME(sizeof(name)), name ) < 0 ) {
467       name [ 0 ] = '\0';
468     }
469
470     pnd_log ( pndn_rem, "%s maps to %s\n", fname, name );
471
472     if ( strcmp ( name, "omap_twl4030keypad" ) == 0 ) {
473       fds [ 0 ] = fd;
474     } else if ( strcmp ( name, "gpio-keys" ) == 0) {
475       fds [ 1 ] = fd;
476     } else if ( strcmp ( name, "AT Translated Set 2 keyboard" ) == 0) { // for vmware, my dev environment
477       fds [ 0 ] = fd;
478     } else if ( strcmp ( name, "triton2-pwrbutton" ) == 0) {
479       fds [ 2 ] = fd;
480     } else if ( strcmp ( name, "ADS784x Touchscreen" ) == 0) {
481       fds [ 3 ] = fd;
482     } else if ( strcmp ( name, "vsense66" ) == 0) {
483       fds [ 4 ] = fd;
484     } else if ( strcmp ( name, "vsense67" ) == 0) {
485       fds [ 5 ] = fd;
486     } else {
487       pnd_log ( pndn_rem, "Ignoring unknown device '%s'\n", name );
488       //fds [ 6 ] = fd;
489       close ( fd );
490       fd = -1;
491       continue;
492     }
493
494     if (imaxfd < fd) imaxfd = fd;
495
496   } // for
497
498   if ( fds [ 0 ] == -1 ) {
499     pnd_log ( pndn_warning, "WARNING! Couldn't find keypad device\n" );
500   }
501
502   if ( fds [ 1 ] == -1 ) {
503     pnd_log ( pndn_warning, "WARNING! couldn't find button device\n" );
504   }
505
506   if ( fds [ 0 ] == -1 && fds [ 1 ] == -1 ) {
507     pnd_log ( pndn_error, "ERROR! Couldn't find either device!\n" );
508     //exit ( -2 );
509   }
510
511   /* loop forever, watching for events
512    */
513
514   while ( 1 ) {
515     struct input_event ev[64];
516
517     unsigned int max_fd = 3; /* imaxfd */
518     int fd = -1, rd, ret;
519     fd_set fdset;
520
521     FD_ZERO ( &fdset );
522
523     imaxfd = 0;
524     for (i = 0; i < max_fd /*imaxfd*/; i++) {
525       if ( fds [ i ] != -1 ) {
526         FD_SET( fds [ i ], &fdset );
527
528         if ( fds [ i ] > imaxfd ) {
529           imaxfd = fds [ i ];
530         }
531
532       }
533     }
534
535     ret = select ( imaxfd + 1, &fdset, NULL, NULL, NULL /* no timeout */ );
536
537     if ( ret == -1 ) {
538       pnd_log ( pndn_error, "ERROR! select(2) failed with: %s\n", strerror ( errno ) );
539       continue; // retry!
540
541     } else { // an fd was fiddled with
542
543       for ( i = 0; i < max_fd; i++ ) {
544         if ( fds [ i ] != -1 && FD_ISSET ( fds [ i ], &fdset ) ) {
545           fd = fds [ i ];
546         } // fd is set?
547       } // for
548
549       /* buttons or keypad */
550       rd = read ( fd, ev, sizeof(struct input_event) * 64 );
551       if ( rd < (int) sizeof(struct input_event) ) {
552         pnd_log ( pndn_error, "ERROR! read(2) input_event failed with: %s\n", strerror ( errno ) );
553         break;
554       }
555
556       for (i = 0; i < rd / sizeof(struct input_event); i++ ) {
557
558         if ( ev[i].type == EV_SYN ) {
559           continue;
560         } else if ( ev[i].type == EV_KEY ) {
561
562           // do we even know about this key at all?
563           keycode_t *p = keycodes;
564           while ( p -> keycode != -1 ) {
565             if ( p -> keycode == ev [ i ].code ) {
566               break;
567             }
568             p++;
569           }
570
571           // if we do, hand it off to dispatcher to look up if we actually do something with it
572           if ( p -> keycode != -1 ) {
573             if ( logall >= 0 ) {
574               pnd_log ( pndn_debug, "Key Event: key %s [%d] value %d\n", p -> keyname, p -> keycode, ev [ i ].value );
575             }
576             dispatch_key ( p -> keycode, ev [ i ].value );
577           } else {
578             if ( logall >= 0 ) {
579               pnd_log ( pndn_warning, "Unknown Key Event: keycode %d value %d\n",  ev [ i ].code, ev [ i ].value );
580             }
581           }
582
583         } else if ( ev[i].type == EV_SW ) {
584
585           // do we even know about this event at all?
586           generic_event_t *p = generics;
587           while ( p -> code != -1 ) {
588             if ( p -> code == ev [ i ].code ) {
589               break;
590             }
591             p++;
592           }
593
594           // if we do, hand it off to dispatcher to look up if we actually do something with it
595           if ( p -> code != -1 ) {
596             if ( logall >= 0 ) {
597               pnd_log ( pndn_debug, "Generic Event: event %s [%d] value %d\n", p -> name, p -> code, ev [ i ].value );
598             }
599             dispatch_event ( p -> code, ev [ i ].value );
600           } else {
601             if ( logall >= 0 ) {
602               pnd_log ( pndn_warning, "Unknown Generic Event: code %d value %d\n",  ev [ i ].code, ev [ i ].value );
603             }
604           }
605
606         } else {
607           pnd_log ( pndn_debug, "DEBUG: Unexpected event type %i received\n", ev[i].type );
608           continue;
609         } // type?
610
611       } // for
612
613     } // an fd was touched
614
615   } // while
616
617   for (i = 0; i < 2; i++) {
618     if ( i != 2 && fds [ i ] != -1 ) {
619       close (fds [ i ] );
620     }
621   }
622
623   return ( 0 );
624 } // main
625
626 // this should really register the keystate and time, and then another func to monitor
627 // time-passage and check the registered list and act on the event..
628 void dispatch_key ( int keycode, int val ) {
629   unsigned int i;
630
631   // val decodes as:
632   // 1 - down (pressed)
633   // 2 - down again (hold)
634   // 0 - up (released)
635
636   for ( i = 0; i < g_evmap_max; i++ ) {
637
638     if ( ( g_evmap [ i ].key_p ) &&
639          ( ((keycode_t*) (g_evmap [ i ].reqs)) -> keycode == keycode ) &&
640          ( g_evmap [ i ].script ) )
641     {
642       unsigned char invoke_it = 0;
643
644       // is this a keydown or a keyup?
645       if ( val == 1 ) {
646         // keydown
647         g_evmap [ i ].keydown_time = time ( NULL );
648
649       } else if ( val == 2 && g_evmap [ i ].keydown_time ) {
650         // key is being held; we should check if max-hold is set
651
652         if ( g_evmap [ i ].maxhold &&
653              time ( NULL ) - g_evmap [ i ].keydown_time >= g_evmap [ i ].maxhold )
654         {
655           invoke_it = 1;
656         }
657
658       } else if ( val == 0 && g_evmap [ i ].keydown_time ) {
659         // keyup (while key is down)
660
661         if ( time ( NULL ) - g_evmap [ i ].last_trigger_time >= g_minimum_separation ) {
662           invoke_it = 1;
663         } else {
664           pnd_log ( pndn_rem, "Skipping invokation.. falls within minimum_separation threshold\n" );
665         }
666
667       } // key up or down?
668
669       if ( invoke_it ) {
670
671         char holdtime [ 128 ];
672         sprintf ( holdtime, "%d", (int)( time(NULL) - g_evmap [ i ].keydown_time ) );
673         pnd_log ( pndn_rem, "Will attempt to invoke: %s %s\n", g_evmap [ i ].script, holdtime );
674
675         // state
676         g_evmap [ i ].keydown_time = 0; // clear the keydown-ness
677         g_evmap [ i ].last_trigger_time = time ( NULL );
678
679         // invocation
680         int x;
681
682         if ( ( x = fork() ) < 0 ) {
683           pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
684           exit ( -3 );
685         }
686
687         if ( x == 0 ) {
688           execl ( g_evmap [ i ].script, g_evmap [ i ].script, holdtime, (char*)NULL );
689           pnd_log ( pndn_error, "ERROR: Couldn't exec(%s)\n", g_evmap [ i ].script );
690           exit ( -4 );
691         }
692
693       } // invoke the script!
694
695       return;
696     } // found matching event for keycode
697
698   } // while
699
700   return;
701 }
702
703 void dispatch_event ( int code, int val ) {
704   unsigned int i;
705
706   // LID val decodes as:
707   // 1 - closing
708   // 0 - opening
709
710   pnd_log ( pndn_rem, "Dispatching Event..\n" );
711
712   for ( i = 0; i < g_evmap_max; i++ ) {
713
714     if ( ( g_evmap [ i ].key_p == 0 ) &&
715          ( ((generic_event_t*) (g_evmap [ i ].reqs)) -> code == code ) &&
716          ( g_evmap [ i ].script ) )
717     {
718
719       // just hand the code to the script (ie: 0 or 1 to script)
720       if ( time ( NULL ) - g_evmap [ i ].last_trigger_time >= g_minimum_separation ) {
721         int x;
722         char value [ 100 ];
723
724         sprintf ( value, "%d", val );
725
726         g_evmap [ i ].last_trigger_time = time ( NULL );
727
728         pnd_log ( pndn_rem, "Will attempt to invoke: %s %s\n", g_evmap [ i ].script, value );
729
730         if ( ( x = fork() ) < 0 ) {
731           pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
732           exit ( -3 );
733         }
734
735         if ( x == 0 ) {
736           execl ( g_evmap [ i ].script, g_evmap [ i ].script, value, (char*)NULL );
737           pnd_log ( pndn_error, "ERROR: Couldn't exec(%s)\n", g_evmap [ i ].script );
738           exit ( -4 );
739         }
740
741       } else {
742         pnd_log ( pndn_rem, "Skipping invokation.. falls within minimum_separation threshold\n" );
743       }
744
745       return;
746     } // found matching event for keycode
747
748   } // while
749
750   return;
751 }
752
753 void sigchld_handler ( int n ) {
754
755   pnd_log ( pndn_rem, "---[ SIGCHLD received ]---\n" );
756
757   int status;
758   wait ( &status );
759
760   pnd_log ( pndn_rem, "     SIGCHLD done ]---\n" );
761
762   return;
763 }
764
765 unsigned char set_next_alarm ( unsigned int secs, unsigned int usecs ) {
766
767   // assume that SIGALRM is already being caught, we just set the itimer here
768
769   struct itimerval itv;
770
771   // if no timer at all, set the 'current' one so it does something; otherwise
772   // let it continue..
773   getitimer ( ITIMER_REAL, &itv );
774
775   if ( itv.it_value.tv_sec == 0 && itv.it_value.tv_sec == 0 ) {
776     itv.it_value.tv_sec = secs;
777     itv.it_value.tv_usec = usecs;
778   }
779
780   // set the next timer
781   //bzero ( &itv, sizeof(struct itimerval) );
782
783   itv.it_interval.tv_sec = secs;
784   itv.it_interval.tv_usec = usecs;
785
786   // if next-timer is less than current, set current too
787   if ( itv.it_value.tv_sec > itv.it_interval.tv_sec ) {
788     itv.it_value.tv_sec = secs;
789     itv.it_value.tv_usec = usecs;
790   }
791
792   if ( setitimer ( ITIMER_REAL, &itv, NULL /* old value returned here */ ) < 0 ) {
793     // sucks
794     return ( 0 );
795   }
796   
797   return ( 1 );
798 }
799
800 void sigalrm_handler ( int n ) {
801
802   pnd_log ( pndn_debug, "---[ SIGALRM ]---\n" );
803
804   int batlevel = pnd_device_get_battery_gauge_perc();
805
806   if ( batlevel < 0 ) {
807 #if 0
808     // couldn't read the battery level, so just assume low and make blinks?
809     batlevel = 4; // low, but not cause a shutdown
810 #else
811     // couldn't read the battery level, so just assume ok!
812     batlevel = 50;
813 #endif
814   }
815
816   // first -- are we critical yet? if so, shut down!
817   if ( batlevel <= b_shutdown && b_shutdown_script ) {
818     int mamps = 0;
819
820     if ( pnd_device_get_charge_current ( &mamps ) && mamps > 100 ) {
821       // critical battery, but charging, so relax.
822     } else {
823       int x;
824
825       pnd_log ( pndn_error, "CRITICAL BATTERY LEVEL -- shutdown the system down! Invoke: %s\n",
826                 b_shutdown_script );
827
828       if ( ( x = fork() ) < 0 ) {
829         pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
830         exit ( -3 );
831       }
832
833       if ( x == 0 ) {
834         execl ( b_shutdown_script, b_shutdown_script, (char*)NULL );
835         pnd_log ( pndn_error, "ERROR: Couldn't exec(%s)\n", b_shutdown_script );
836         exit ( -4 );
837       }
838
839     } // charging
840
841   }
842
843   // is battery warning already active?
844   if ( b_active ) {
845     // warning is on!
846
847     // is user charging up? if so, stop blinking.
848     // perhaps we shoudl check if charger is connected, and not blink at all in that case..
849     if ( batlevel > b_threshold + 1 /* allow for error in read */ ) {
850       pnd_log ( pndn_debug, "Battery is high again, flipping to non-blinker mode\n" );
851       b_active = 0;
852       set_next_alarm ( b_frequency, 0 );
853       pnd_device_set_led_charger_brightness ( 250 );
854       return;
855     }
856
857     if ( b_active == 1 ) {
858       // turn LED on
859       pnd_log ( pndn_debug, "Blink on\n" );
860       pnd_device_set_led_charger_brightness ( 200 );
861       // set timer to short duration
862       b_active = 2;
863       set_next_alarm ( 0, b_blinkdur );
864     } else if ( b_active == 2 ) {
865       // turn LED off
866       pnd_log ( pndn_debug, "Blink off\n" );
867       pnd_device_set_led_charger_brightness ( 10 );
868       // back to longer duration
869       b_active = 1;
870       set_next_alarm ( b_blinkfreq, 0 );
871     }
872
873     return;
874   }
875
876   // warning is off..
877   if ( batlevel <= b_threshold ) {
878     // battery seems low, go to active mode
879     pnd_log ( pndn_debug, "Battery is low, flipping to blinker mode\n" );
880     b_active = 1;
881     set_next_alarm ( b_blinkfreq, 0 );
882   } // battery level
883
884   return;
885 }