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