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