evmapperd: Added preliminary support for HOLD key
[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   { KEY_COFFEE, "hold" }, /* coffee? lol */
81   { -1, NULL }
82 };
83
84 typedef struct {
85   int type;
86   int code;
87   char *name;
88 } generic_event_t;
89
90 generic_event_t generics[] = {
91   { EV_SW, 0, "lid-toggle" }, // expecting value 1 (lid close) or 0 (lid open)
92   { -1, -1, NULL }
93 };
94
95 // FAKESCRIPT_ entries are to better handle a virtual script name; if we have to parse
96 // "TOGGLE_HOLD" for every key down, it seems a little inefficient; at conf-time, if we
97 // see this string for example, why not change it to a magic number .. and if we see that
98 // down the road, we can act with just an integer compare, instead of a string compare..
99 #define FAKESCRIPT_TOGGLE_HOLD 0001
100
101 // event-to-sh mapping
102 //
103 typedef struct {
104
105   unsigned char key_p; // 1 if its a key, otherwise an event
106
107   /* template information
108    */
109   void *reqs;          // scancode/etc for the event in question
110
111   char *script;        // script to invoke
112   unsigned int maxhold;   // maximum hold-time before forcing script invocation
113
114   /* state
115    */
116   time_t last_trigger_time;
117   time_t keydown_time;
118
119 } evmap_t;
120
121 #define MAXEVENTS 255
122 evmap_t g_evmap [ MAXEVENTS ];
123 unsigned int g_evmap_max = 0;
124 unsigned int g_queued_keyups = 0;
125
126 // battery
127 unsigned char b_threshold = 5;    // %battery
128 unsigned int b_frequency = 300;   // frequency to check
129 unsigned int b_blinkfreq = 2;     // blink every 2sec
130 unsigned int b_blinkdur = 1000;   // blink duration (uSec), 0sec + uSec is assumed
131 unsigned char b_active = 0;       // 0=inactive, 1=active and waiting to blink, 2=blink is on, waiting to turn off
132 unsigned char b_shutdown = 1;     // %age battery to force a shutdown!
133 unsigned int  b_shutdelay = 30;   // delay for shutdown script
134 unsigned char b_warned = 0;       // Shutdown attempted
135 char *b_shutdown_script = NULL;
136 unsigned char bc_enable = 1;      // enable charger control
137 unsigned char bc_stopcap = 99;    // battery capacity threshold as stop condition 1
138 unsigned int bc_stopcur = 80000;  // charge current threshold as stop condition 2, in uA
139 unsigned char bc_startcap = 95;   // battery capacity threshold to resume charging
140 char *bc_charge_devices = NULL;   // charger /sys/class/power_supply/ devices, changes between kernel versions
141
142 // fd's; pulled from main() so I can be lazy
143 int fds [ 8 ] = { -1, -1, -1, -1, -1, -1, -1, -1 }; // 0 = keypad, 1 = gpio keys
144 int imaxfd = 0;
145
146 /* get to it
147  */
148 void dispatch_key ( int keycode, int val );
149 void dispatch_event ( int code, int val );
150 void sigchld_handler ( int n );
151 unsigned char set_next_alarm ( unsigned int secs, unsigned int usecs );
152 void sigalrm_handler ( int n );
153 void fakescript_hold_on ( void );
154 void fakescript_hold_off ( void );
155
156 static void usage ( char *argv[] ) {
157   printf ( "%s [-d]\n", argv [ 0 ] );
158   printf ( "-d\tDaemon mode; detach from terminal, chdir to /tmp, suppress output. Optional.\n" );
159   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" );
160   return;
161 }
162
163 int main ( int argc, char *argv[] ) {
164   int i;
165   int logall = -1; // -1 means normal logging rules; >=0 means log all!
166
167   for ( i = 1; i < argc; i++ ) {
168
169     if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'd' ) {
170       //printf ( "Going daemon mode. Silent running.\n" );
171       g_daemon_mode = 1;
172     } else if ( argv [ i ][ 0 ] == '-' && argv [ i ][ 1 ] == 'l' ) {
173
174       if ( isdigit ( argv [ i ][ 2 ] ) ) {
175         unsigned char x = atoi ( argv [ i ] + 2 );
176         if ( x >= 0 &&
177              x < pndn_none )
178         {
179           logall = x;
180         }
181       } else {
182         logall = 0;
183       }
184     } else {
185       usage ( argv );
186       exit ( 0 );
187     }
188
189   } // for
190
191   /* enable logging?
192    */
193   pnd_log_set_pretext ( "pndevmapperd" );
194   pnd_log_set_flush ( 1 );
195
196   if ( logall == -1 ) {
197     // standard logging; non-daemon versus daemon
198
199     if ( g_daemon_mode ) {
200       // nada
201     } else {
202       pnd_log_set_filter ( pndn_rem );
203       pnd_log_to_stdout();
204     }
205
206   } else {
207     FILE *f;
208
209     f = fopen ( "/tmp/pndevmapperd.log", "w" );
210
211     if ( f ) {
212       pnd_log_set_filter ( logall );
213       pnd_log_to_stream ( f );
214       pnd_log ( pndn_rem, "logall mode - logging to /tmp/pndevmapperd.log\n" );
215     }
216
217     if ( logall == pndn_debug ) {
218       pnd_log_set_buried_logging ( 1 ); // log the shit out of it
219       pnd_log ( pndn_rem, "logall mode 0 - turned on buried logging\n" );
220     }
221
222   } // logall
223
224   pnd_log ( pndn_rem, "%s built %s %s", argv [ 0 ], __DATE__, __TIME__ );
225
226   pnd_log ( pndn_rem, "log level starting as %u", pnd_log_get_filter() );
227
228   // basic daemon set up
229   if ( g_daemon_mode ) {
230
231     // set a CWD somewhere else
232     chdir ( "/tmp" );
233
234     // detach from terminal
235     if ( ( i = fork() ) < 0 ) {
236       pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
237       exit ( i );
238     }
239     if ( i ) {
240       exit ( 0 ); // exit parent
241     }
242     setsid();
243
244     // umask
245     umask ( 022 ); // emitted files can be rwxr-xr-x
246
247   } // set up daemon
248
249   /* hmm, seems to not like working right after boot.. do we depend on another daemon or
250    * on giving kernel time to init something, or ... wtf?
251    * -- lets give the system some time to wake up
252    */
253   { // delay
254
255     // this one works for pndnotifyd, which actually needs INOTIFYH..
256     //
257
258     // check if inotify is awake yet; if not, try waiting for awhile to see if it does
259     pnd_log ( pndn_rem, "Starting INOTIFY test; should be instant, but may take awhile...\n" );
260
261     if ( ! pnd_notify_wait_until_ready ( 120 /* seconds */ ) ) {
262       pnd_log ( pndn_error, "ERROR: INOTIFY refuses to be useful and quite awhile has passed. Bailing out.\n" );
263       return ( -1 );
264     }
265
266     pnd_log ( pndn_rem, "INOTIFY seems to be useful, whew.\n" );
267
268     // pndnotifyd also waits for user to log in .. pretty excessive, especially since
269     // what if user wants to close the lid while at the log in screen? for now play the
270     // odds as thats pretty unliekly usage scenariom but is clearly not acceptible :/
271     //
272
273     // wait for a user to be logged in - we should probably get hupped when a user logs in, so we can handle
274     // log-out and back in again, with SDs popping in and out between..
275     pnd_log ( pndn_rem, "Checking to see if a user is logged in\n" );
276     char tmp_username [ 128 ];
277     while ( 1 ) {
278       if ( pnd_check_login ( tmp_username, 127 ) ) {
279         break;
280       }
281       pnd_log ( pndn_debug, "  No one logged in yet .. spinning.\n" );
282       sleep ( 2 );
283     } // spin
284     pnd_log ( pndn_rem, "Looks like user '%s' is in, continue.\n", tmp_username );
285
286   } // delay
287
288   /* inhale config or die trying
289    */
290   char *configpath;
291
292   // attempt to fetch a sensible default searchpath for configs
293   configpath = pnd_conf_query_searchpath();
294
295   // attempt to fetch the apps config. since it finds us the runscript
296   pnd_conf_handle evmaph;
297
298   evmaph = pnd_conf_fetch_by_id ( pnd_conf_evmap, configpath );
299
300   if ( ! evmaph ) {
301     // couldn't locate conf, just bail
302     pnd_log ( pndn_error, "ERROR: Couldn't locate conf file\n" );
303     exit ( -1 );
304   }
305
306   /* iterate across conf, stocking the event map
307    */
308   void *n = pnd_box_get_head ( evmaph );
309
310   while ( n ) {
311     char *k = pnd_box_get_key ( n );
312     //printf ( "key %s\n", k );
313
314     if ( strncmp ( k, "keys.", 5 ) == 0 ) {
315       k += 5;
316
317       // keys should really push push generic-events onto the table, since they;'re just a special case of them
318       // to make things easier to read
319
320       // figure out which keycode we're talking about
321       keycode_t *p = keycodes;
322       while ( p -> keycode != -1 ) {
323         if ( strcasecmp ( p -> keyname, k ) == 0 ) {
324           break;
325         }
326         p++;
327       }
328
329       if ( p -> keycode != -1 ) {
330         g_evmap [ g_evmap_max ].key_p = 1;    // its a key, not an event
331         g_evmap [ g_evmap_max ].reqs = p;     // note the keycode
332
333         // note the script to activate in response
334         if ( strchr ( n, ' ' ) ) {
335           char *foo = strdup ( n );
336           char *t = strchr ( foo, ' ' );
337           *t = '\0';
338           g_evmap [ g_evmap_max ].script = foo;
339           g_evmap [ g_evmap_max ].maxhold = atoi ( t + 1 );
340         } else {
341           g_evmap [ g_evmap_max ].script = n;
342           g_evmap [ g_evmap_max ].maxhold = 0;
343
344           if ( strcmp ( n, "TOGGLE_HOLD" ) == 0 ) {
345             g_evmap [ g_evmap_max ].script = (char*)FAKESCRIPT_TOGGLE_HOLD;
346           }
347
348         }
349
350         pnd_log ( pndn_rem, "Registered key %s [%d] to script %s with maxhold %d\n",
351                   p -> keyname, p -> keycode, (char*) n, g_evmap [ g_evmap_max ].maxhold );
352
353         g_evmap_max++;
354       } else {
355         pnd_log ( pndn_warning, "WARNING! Key '%s' is not handled by pndevmapperd yet! Skipping.", k );
356       }
357
358     } else if ( strncmp ( k, "events.", 7 ) == 0 ) {
359       k += 7;
360
361       // yes, key events could really be defined in this generic sense, and really we could just let people
362       // put the code and so on right in the conf, but trying to keep it easy on people; maybe should
363       // add a 'generic' section to conf file and just let folks redefine random events that way
364       // Really, it'd be nice if the /dev/input/events could spit out useful text, and just use scripts
365       // to respond without a daemon per se; for that matter, pnd-ls and pnd-map pnd-dotdesktopemitter
366       // should just exist as scripts rather than daemons, but whose counting?
367
368       // figure out which keycode we're talking about
369       generic_event_t *p = generics;
370       while ( p -> code != -1 ) {
371         if ( strcasecmp ( p -> name, k ) == 0 ) {
372           break;
373         }
374         p++;
375       }
376
377       if ( p -> code != -1 ) {
378         g_evmap [ g_evmap_max ].key_p = 0;    // its an event, not a key
379         g_evmap [ g_evmap_max ].reqs = p;     // note the keycode
380         g_evmap [ g_evmap_max ].script = n;   // note the script to activate in response
381         pnd_log ( pndn_rem, "Registered generic event %s [%d] to script %s\n", p -> name, p -> code, (char*) n );
382         g_evmap_max++;
383       } else {
384         pnd_log ( pndn_warning, "WARNING! Generic event '%s' is not handled by pndevmapperd yet! Skipping.", k );
385       }
386
387     } else if ( strncmp ( k, "pndevmapperd.", 7 ) == 0 ) {
388       // not consumed here, skip silently
389
390     } else if ( strncmp ( k, "battery.", 8 ) == 0 ) {
391       // not consumed here, skip silently
392
393     } else if ( strncmp ( k, "battery_charge.", 15 ) == 0 ) {
394       // not consumed here, skip silently
395
396     } else {
397       // uhhh
398       pnd_log ( pndn_warning, "Unknown config key '%s'; skipping.\n", k );
399     }
400
401     n = pnd_box_get_next ( n );
402   } // while
403
404   if ( pnd_conf_get_as_int ( evmaph, "pndevmapperd.loglevel" ) != PND_CONF_BADNUM ) {
405     pnd_log_set_filter ( pnd_conf_get_as_int ( evmaph, "pndevmapperd.loglevel" ) );
406     pnd_log ( pndn_rem, "config file causes loglevel to change to %u", pnd_log_get_filter() );
407   }
408
409   if ( pnd_conf_get_as_int ( evmaph, "pndevmapperd.minimum_separation" ) != PND_CONF_BADNUM ) {
410     g_minimum_separation = pnd_conf_get_as_int ( evmaph, "pndevmapperd.minimum_separation" );
411     pnd_log ( pndn_rem, "config file causes minimum_separation to change to %u", g_minimum_separation );
412   }
413
414   // battery conf
415   if ( pnd_conf_get_as_int ( evmaph, "battery.threshold" ) != PND_CONF_BADNUM ) {
416     b_threshold = pnd_conf_get_as_int ( evmaph, "battery.threshold" );
417     pnd_log ( pndn_rem, "Battery threshold set to %u", b_threshold );
418   }
419   if ( pnd_conf_get_as_int ( evmaph, "battery.check_interval" ) != PND_CONF_BADNUM ) {
420     b_frequency = pnd_conf_get_as_int ( evmaph, "battery.check_interval" );
421     pnd_log ( pndn_rem, "Battery check interval set to %u", b_frequency );
422   }
423   if ( pnd_conf_get_as_int ( evmaph, "battery.blink_interval" ) != PND_CONF_BADNUM ) {
424     b_blinkfreq = pnd_conf_get_as_int ( evmaph, "battery.blink_interval" );
425     pnd_log ( pndn_rem, "Battery blink interval set to %u", b_blinkfreq );
426   }
427   if ( pnd_conf_get_as_int ( evmaph, "battery.blink_duration" ) != PND_CONF_BADNUM ) {
428     b_blinkdur = pnd_conf_get_as_int ( evmaph, "battery.blink_duration" );
429     pnd_log ( pndn_rem, "Battery blink duration set to %u", b_blinkdur );
430   }
431   b_active = 0;
432   if ( pnd_conf_get_as_int ( evmaph, "battery.shutdown_threshold" ) != PND_CONF_BADNUM ) {
433     b_shutdown = pnd_conf_get_as_int ( evmaph, "battery.shutdown_threshold" );
434     pnd_log ( pndn_rem, "Battery shutdown threshold set to %u", b_shutdown );
435   }
436   if ( pnd_conf_get_as_int ( evmaph, "battery.shutdown_delay" ) != PND_CONF_BADNUM ) {
437     b_shutdelay = pnd_conf_get_as_int ( evmaph, "battery.shutdown_delay" );
438     pnd_log ( pndn_rem, "Battery shutdown delay set to %u", b_shutdelay );
439   }
440   if ( pnd_conf_get_as_char ( evmaph, "battery.shutdown_script" ) != NULL ) {
441     b_shutdown_script = strdup ( pnd_conf_get_as_char ( evmaph, "battery.shutdown_script" ) );
442     pnd_log ( pndn_rem, "Battery shutdown script set to %s", b_shutdown_script );
443   }
444   if ( pnd_conf_get_as_int ( evmaph, "battery_charge.enable" ) != PND_CONF_BADNUM ) {
445     bc_enable = pnd_conf_get_as_int ( evmaph, "battery_charge.enable" );
446     pnd_log ( pndn_rem, "Battery charge enable set to %u", bc_enable );
447   }
448   if ( pnd_conf_get_as_int ( evmaph, "battery_charge.stop_capacity" ) != PND_CONF_BADNUM ) {
449     bc_stopcap = pnd_conf_get_as_int ( evmaph, "battery_charge.stop_capacity" );
450     pnd_log ( pndn_rem, "Battery charge stop capacity set to %u", bc_stopcap );
451   }
452   if ( pnd_conf_get_as_int ( evmaph, "battery_charge.stop_current" ) != PND_CONF_BADNUM ) {
453     bc_stopcur = pnd_conf_get_as_int ( evmaph, "battery_charge.stop_current" );
454     pnd_log ( pndn_rem, "Battery charge stop current set to %u", bc_stopcur );
455   }
456   if ( pnd_conf_get_as_int ( evmaph, "battery_charge.start_capacity" ) != PND_CONF_BADNUM ) {
457     bc_startcap = pnd_conf_get_as_int ( evmaph, "battery_charge.start_capacity" );
458     pnd_log ( pndn_rem, "Battery charge start capacity set to %u", bc_startcap );
459   }
460   if ( pnd_conf_get_as_char ( evmaph, "battery_charge.devices" ) != NULL ) {
461     bc_charge_devices = strdup ( pnd_conf_get_as_char ( evmaph, "battery_charge.devices" ) );
462     pnd_log ( pndn_rem, "Battery charge devices set to %s", bc_charge_devices );
463   }
464
465   /* do we have anything to do?
466    */
467   if ( ! g_evmap_max ) {
468     // uuuh, nothing to do?
469     pnd_log ( pndn_warning, "WARNING! No events configured to watch, so just spinning wheels...\n" );
470     exit ( -1 );
471   } // spin
472
473   /* set up sigchld -- don't want zombies all over; well, we do, but not process zombies
474    */
475   sigset_t ss;
476   sigemptyset ( &ss );
477
478   struct sigaction siggy;
479   siggy.sa_handler = sigchld_handler;
480   siggy.sa_mask = ss; /* implicitly blocks the origin signal */
481   siggy.sa_flags = SA_RESTART; /* don't need anything */
482   sigaction ( SIGCHLD, &siggy, NULL );
483
484   /* set up the battery level warning timers
485    */
486   siggy.sa_handler = sigalrm_handler;
487   siggy.sa_mask = ss; /* implicitly blocks the origin signal */
488   siggy.sa_flags = SA_RESTART; /* don't need anything */
489   sigaction ( SIGALRM, &siggy, NULL );
490
491   if ( set_next_alarm ( b_frequency, 0 ) ) { // check every 'frequency' seconds
492     pnd_log ( pndn_rem, "Checking for low battery every %u seconds\n", b_frequency );
493   } else {
494     pnd_log ( pndn_error, "ERROR: Couldn't set up timer for every %u seconds\n", b_frequency );
495   }
496
497   /* actually try to do something useful
498    */
499
500   // stolen in part from notaz :)
501
502   // try to locate the appropriate devices
503   int id;
504
505   for ( id = 0; ; id++ ) {
506     char fname[64];
507     char name[256] = { 0, };
508     int fd;
509
510     snprintf ( fname, sizeof ( fname ), "/dev/input/event%i", id );
511     fd = open ( fname, O_RDONLY );
512
513     if ( fd == -1 ) {
514       break;
515     }
516
517     if ( ioctl (fd, EVIOCGNAME(sizeof(name)), name ) < 0 ) {
518       name [ 0 ] = '\0';
519     }
520
521     pnd_log ( pndn_rem, "%s maps to %s\n", fname, name );
522
523     if ( strcmp ( name, PND_EVDEV_KEYPAD/*"omap_twl4030keypad"*/ ) == 0 ) {
524       fds [ 0 ] = fd;
525     } else if ( strcmp ( name, "gpio-keys" ) == 0) {
526       fds [ 1 ] = fd;
527     } else if ( strcmp ( name, "AT Translated Set 2 keyboard" ) == 0) { // for vmware, my dev environment
528       fds [ 0 ] = fd;
529     } else if ( strcmp ( name, PND_EVDEV_POWER/*"triton2-pwrbutton"*/ ) == 0) {
530       fds [ 2 ] = fd;
531     } else if ( strcmp ( name, PND_EVDEV_TS/*"ADS784x Touchscreen"*/ ) == 0) {
532       fds [ 3 ] = fd;
533     } else if ( strcmp ( name, PND_EVDEV_NUB1/*"vsense66"*/ ) == 0) {
534       fds [ 4 ] = fd;
535     } else if ( strcmp ( name, PND_EVDEV_NUB1/*"vsense67"*/ ) == 0) {
536       fds [ 5 ] = fd;
537     } else {
538       pnd_log ( pndn_rem, "Ignoring unknown device '%s'\n", name );
539       //fds [ 6 ] = fd;
540       close ( fd );
541       fd = -1;
542       continue;
543     }
544
545     if (imaxfd < fd) imaxfd = fd;
546
547   } // for
548
549   if ( fds [ 0 ] == -1 ) {
550     pnd_log ( pndn_warning, "WARNING! Couldn't find keypad device\n" );
551   }
552
553   if ( fds [ 1 ] == -1 ) {
554     pnd_log ( pndn_warning, "WARNING! couldn't find button device\n" );
555   }
556
557   if ( fds [ 0 ] == -1 && fds [ 1 ] == -1 ) {
558     pnd_log ( pndn_error, "ERROR! Couldn't find either device!\n" );
559     //exit ( -2 );
560   }
561
562   /* loop forever, watching for events
563    */
564
565   while ( 1 ) {
566     struct input_event ev[64];
567
568     unsigned int max_fd = 3; /* imaxfd */
569     int fd = -1, rd, ret;
570     fd_set fdset;
571
572     // set up fd list
573     FD_ZERO ( &fdset );
574
575     imaxfd = 0;
576     for (i = 0; i < max_fd /*imaxfd*/; i++) {
577       if ( fds [ i ] != -1 ) {
578         FD_SET( fds [ i ], &fdset );
579
580         if ( fds [ i ] > imaxfd ) {
581           imaxfd = fds [ i ];
582         }
583
584       }
585     }
586
587     // figure out if we can block forever, or not
588     unsigned char do_block = 1;
589     struct timeval tv;
590     tv.tv_usec = 0;
591     tv.tv_sec = 1;
592
593     for ( i = i; i < g_evmap_max; i++ ) {
594       if ( g_evmap [ i ].keydown_time && g_evmap [ i ].maxhold ) {
595         do_block = 0;
596         break;
597       }
598     }
599
600     // wait for fd's or timeout
601     ret = select ( imaxfd + 1, &fdset, NULL, NULL, do_block ? NULL /* no timeout */ : &tv );
602
603     if ( ret == -1 ) {
604       pnd_log ( pndn_error, "ERROR! select(2) failed with: %s\n", strerror ( errno ) );
605       continue; // retry!
606
607     } else if ( ret == 0 ) { // select returned with timeout (no fd)
608
609       // timeout occurred; should only happen when 1 or more keys are being held down and
610       // they're "maxhold" keys, so we have to see if their timer has passed
611       unsigned int now = time ( NULL );
612
613       for ( i = i; i < g_evmap_max; i++ ) {
614
615         if ( g_evmap [ i ].keydown_time &&
616              g_evmap [ i ].maxhold &&
617              now - g_evmap [ i ].keydown_time >= g_evmap [ i ].maxhold )
618         {
619           keycode_t *k = (keycode_t*) g_evmap [ i ].reqs;
620           dispatch_key ( k -> keycode, 0 /* key up */ );
621         }
622
623       } // for
624
625     } else { // an fd was fiddled with
626
627       for ( i = 0; i < max_fd; i++ ) {
628         if ( fds [ i ] != -1 && FD_ISSET ( fds [ i ], &fdset ) ) {
629           fd = fds [ i ];
630         } // fd is set?
631       } // for
632
633       /* buttons or keypad */
634       rd = read ( fd, ev, sizeof(struct input_event) * 64 );
635       if ( rd < (int) sizeof(struct input_event) ) {
636         pnd_log ( pndn_error, "ERROR! read(2) input_event failed with: %s\n", strerror ( errno ) );
637         break;
638       }
639
640       for (i = 0; i < rd / sizeof(struct input_event); i++ ) {
641
642         if ( ev[i].type == EV_SYN ) {
643           continue;
644         } else if ( ev[i].type == EV_KEY ) {
645
646           // do we even know about this key at all?
647           keycode_t *p = keycodes;
648           while ( p -> keycode != -1 ) {
649             if ( p -> keycode == ev [ i ].code ) {
650               break;
651             }
652             p++;
653           }
654
655           // if we do, hand it off to dispatcher to look up if we actually do something with it
656           if ( p -> keycode != -1 ) {
657             if ( logall >= 0 ) {
658               pnd_log ( pndn_debug, "Key Event: key %s [%d] value %d\n", p -> keyname, p -> keycode, ev [ i ].value );
659             }
660             dispatch_key ( p -> keycode, ev [ i ].value );
661           } else {
662             if ( logall >= 0 ) {
663               pnd_log ( pndn_warning, "Unknown Key Event: keycode %d value %d\n",  ev [ i ].code, ev [ i ].value );
664             }
665           }
666
667         } else if ( ev[i].type == EV_SW ) {
668
669           // do we even know about this event at all?
670           generic_event_t *p = generics;
671           while ( p -> code != -1 ) {
672             if ( p -> code == ev [ i ].code ) {
673               break;
674             }
675             p++;
676           }
677
678           // if we do, hand it off to dispatcher to look up if we actually do something with it
679           if ( p -> code != -1 ) {
680             if ( logall >= 0 ) {
681               pnd_log ( pndn_debug, "Generic Event: event %s [%d] value %d\n", p -> name, p -> code, ev [ i ].value );
682             }
683             dispatch_event ( p -> code, ev [ i ].value );
684           } else {
685             if ( logall >= 0 ) {
686               pnd_log ( pndn_warning, "Unknown Generic Event: code %d value %d\n",  ev [ i ].code, ev [ i ].value );
687             }
688           }
689
690         } else {
691           pnd_log ( pndn_debug, "DEBUG: Unexpected event type %i received\n", ev[i].type );
692           continue;
693         } // type?
694
695       } // for
696
697     } // an fd was touched
698
699   } // while
700
701   for (i = 0; i < 2; i++) {
702     if ( i != 2 && fds [ i ] != -1 ) {
703       close (fds [ i ] );
704     }
705   }
706
707   return ( 0 );
708 } // main
709
710 // this should really register the keystate and time, and then another func to monitor
711 // time-passage and check the registered list and act on the event..
712 void dispatch_key ( int keycode, int val ) {
713   unsigned int i;
714
715   // val decodes as:
716   // 1 - down (pressed)
717   // 2 - down again (hold)
718   // 0 - up (released)
719
720   for ( i = 0; i < g_evmap_max; i++ ) {
721
722     if ( ( g_evmap [ i ].key_p ) &&
723          ( ((keycode_t*) (g_evmap [ i ].reqs)) -> keycode == keycode ) &&
724          ( g_evmap [ i ].script ) )
725     {
726       unsigned char invoke_it = 0;
727
728       // is this a keydown or a keyup?
729       if ( val == 1 ) {
730         // keydown
731
732         if ( g_evmap [ i ].maxhold == 0 ) {
733
734           // is this a special internally handled key, or normal key?
735           if ( g_evmap [ i ].script == (char*)FAKESCRIPT_TOGGLE_HOLD ) {
736             // handle this specially
737             fakescript_hold_on();
738           } else {
739             // normal key, with script to run
740             g_evmap [ i ].keydown_time = 0;
741             invoke_it = 1;
742           }
743
744         } else {
745           g_evmap [ i ].keydown_time = time ( NULL );
746         }
747
748       } else if ( val == 2 && g_evmap [ i ].keydown_time ) {
749         // key is being held; we should check if max-hold is set
750
751         if ( g_evmap [ i ].maxhold &&
752              time ( NULL ) - g_evmap [ i ].keydown_time >= g_evmap [ i ].maxhold )
753         {
754           invoke_it = 1;
755         }
756
757       } else if ( val == 0 ) {
758
759         if ( g_evmap [ i ].script == (char*)FAKESCRIPT_TOGGLE_HOLD ) {
760           // handle this specially
761           fakescript_hold_off();
762
763         } else if ( g_evmap [ i ].keydown_time ) {
764           // keyup (while key is down)
765
766           if ( time ( NULL ) - g_evmap [ i ].last_trigger_time >= g_minimum_separation ) {
767             invoke_it = 1;
768           } else {
769             pnd_log ( pndn_rem, "Skipping invokation.. falls within minimum_separation threshold\n" );
770           }
771
772         }
773
774       } // key up or down?
775
776       if ( invoke_it ) {
777
778         char holdtime [ 128 ];
779         sprintf ( holdtime, "%d", (int)( time(NULL) - g_evmap [ i ].keydown_time ) );
780         pnd_log ( pndn_rem, "Will attempt to invoke: %s %s\n", g_evmap [ i ].script, holdtime );
781
782         // state
783         g_evmap [ i ].keydown_time = 0; // clear the keydown-ness
784         g_evmap [ i ].last_trigger_time = time ( NULL );
785
786         // invocation
787         int x;
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 ( g_evmap [ i ].script, g_evmap [ i ].script, holdtime, (char*)NULL );
796           pnd_log ( pndn_error, "ERROR: Couldn't exec(%s)\n", g_evmap [ i ].script );
797           exit ( -4 );
798         }
799
800       } // invoke the script!
801
802       return;
803     } // found matching event for keycode
804
805   } // while
806
807   return;
808 }
809
810 void dispatch_event ( int code, int val ) {
811   unsigned int i;
812
813   // LID val decodes as:
814   // 1 - closing
815   // 0 - opening
816
817   pnd_log ( pndn_rem, "Dispatching Event..\n" );
818
819   for ( i = 0; i < g_evmap_max; i++ ) {
820
821     if ( ( g_evmap [ i ].key_p == 0 ) &&
822          ( ((generic_event_t*) (g_evmap [ i ].reqs)) -> code == code ) &&
823          ( g_evmap [ i ].script ) )
824     {
825
826       // just hand the code to the script (ie: 0 or 1 to script)
827       if ( time ( NULL ) - g_evmap [ i ].last_trigger_time >= g_minimum_separation ) {
828         int x;
829         char value [ 100 ];
830
831         sprintf ( value, "%d", val );
832
833         g_evmap [ i ].last_trigger_time = time ( NULL );
834
835         pnd_log ( pndn_rem, "Will attempt to invoke: %s %s\n", g_evmap [ i ].script, value );
836
837         if ( ( x = fork() ) < 0 ) {
838           pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
839           exit ( -3 );
840         }
841
842         if ( x == 0 ) {
843           execl ( g_evmap [ i ].script, g_evmap [ i ].script, value, (char*)NULL );
844           pnd_log ( pndn_error, "ERROR: Couldn't exec(%s)\n", g_evmap [ i ].script );
845           exit ( -4 );
846         }
847
848       } else {
849         pnd_log ( pndn_rem, "Skipping invokation.. falls within minimum_separation threshold\n" );
850       }
851
852       return;
853     } // found matching event for keycode
854
855   } // while
856
857   return;
858 }
859
860 void sigchld_handler ( int n ) {
861
862   pnd_log ( pndn_rem, "---[ SIGCHLD received ]---\n" );
863
864   int status;
865   wait ( &status );
866
867   pnd_log ( pndn_rem, "     SIGCHLD done ]---\n" );
868
869   return;
870 }
871
872 unsigned char set_next_alarm ( unsigned int secs, unsigned int usecs ) {
873
874   // assume that SIGALRM is already being caught, we just set the itimer here
875
876   struct itimerval itv;
877
878   // if no timer at all, set the 'current' one so it does something; otherwise
879   // let it continue..
880   getitimer ( ITIMER_REAL, &itv );
881
882   if ( itv.it_value.tv_sec == 0 && itv.it_value.tv_sec == 0 ) {
883     itv.it_value.tv_sec = secs;
884     itv.it_value.tv_usec = usecs;
885   }
886
887   // set the next timer
888   //bzero ( &itv, sizeof(struct itimerval) );
889
890   itv.it_interval.tv_sec = secs;
891   itv.it_interval.tv_usec = usecs;
892
893   // if next-timer is less than current, set current too
894   if ( itv.it_value.tv_sec > itv.it_interval.tv_sec ) {
895     itv.it_value.tv_sec = secs;
896     itv.it_value.tv_usec = usecs;
897   }
898
899   if ( setitimer ( ITIMER_REAL, &itv, NULL /* old value returned here */ ) < 0 ) {
900     // sucks
901     return ( 0 );
902   }
903
904   return ( 1 );
905 }
906
907 void sigalrm_handler ( int n ) {
908
909   pnd_log ( pndn_debug, "---[ SIGALRM ]---\n" );
910
911   static time_t last_charge_check, last_charge_worka;
912   int batlevel = pnd_device_get_battery_gauge_perc();
913   int uamps = 0;
914   time_t now;
915
916   pnd_device_get_charge_current ( &uamps );
917
918   if ( batlevel < 0 ) {
919 #if 0
920     // couldn't read the battery level, so just assume low and make blinks?
921     batlevel = 4; // low, but not cause a shutdown
922 #else
923     // couldn't read the battery level, so just assume ok!
924     batlevel = 50;
925 #endif
926   }
927
928   // first -- are we critical yet? if so, shut down!
929   if ( batlevel <= b_shutdown && b_shutdown_script) {
930
931     if ( uamps > 100 ) {
932         // critical battery, but charging, so relax.
933         b_warned = 0;
934     } else {
935       if (b_warned == 0) {
936           // Avoid warning again till re-powered
937           b_warned = 1;
938           int x;
939           pnd_log ( pndn_error, "Battery Current: %d\n", uamps );
940           pnd_log ( pndn_error, "CRITICAL BATTERY LEVEL -- shutdown the system down! Invoke: %s\n",
941                 b_shutdown_script );
942
943           if ( ( x = fork() ) < 0 ) {
944                 pnd_log ( pndn_error, "ERROR: Couldn't fork()\n" );
945             exit ( -3 );
946           }
947
948          if ( x == 0 ) {
949            char value [ 100 ];
950            sprintf ( value, "%d", b_shutdelay );
951            execl ( b_shutdown_script, b_shutdown_script, value, (char*)NULL );
952            pnd_log ( pndn_error, "ERROR: Couldn't exec(%s)\n", b_shutdown_script );
953            exit ( -4 );
954          }
955       }
956     } // charging
957
958   }
959
960   // charge monitoring
961   now = time(NULL);
962   if ( bc_enable && bc_charge_devices != NULL && (unsigned int)(now - last_charge_check) > 60 ) {
963
964     int charge_enabled = pnd_device_get_charger_enable ( bc_charge_devices );
965     if ( charge_enabled < 0 )
966       pnd_log ( pndn_error, "ERROR: Couldn't read charger enable control\n" );
967     else {
968
969       if ( charge_enabled && batlevel >= bc_stopcap && 0 < uamps && uamps < bc_stopcur ) {
970         pnd_log ( pndn_debug, "Charge stop conditions reached, disabling charging\n" );
971         pnd_device_set_charger_enable ( bc_charge_devices, 0 );
972       }
973       else if ( !charge_enabled && batlevel <= bc_startcap ) {
974         pnd_log ( pndn_debug, "Charge start conditions reached, enabling charging\n" );
975         pnd_device_set_charger_enable ( bc_charge_devices, 1 );
976       }
977
978       // for some unknown reason it just stops charging randomly (happens once per week or so),
979       // and does not restart, resulting in a flat battery if machine is unattended.
980       // What seems to help here is writing to chip registers, we can do it here indirectly
981       // by writing to enable. Doing it occasionally should do no harm even with missing charger.
982       if ( batlevel <= bc_startcap && (unsigned int)(now - last_charge_worka) > 20*60 ) {
983         pnd_log ( pndn_debug, "Charge workaround trigger\n" );
984         pnd_device_set_charger_enable ( bc_charge_devices, 1 );
985         last_charge_worka = now;
986       }
987     }
988     last_charge_check = now;
989   }
990
991   // is battery warning already active?
992   if ( b_active ) {
993     // warning is on!
994
995     // is user charging up? if so, stop blinking.
996     // perhaps we shoudl check if charger is connected, and not blink at all in that case..
997     if ( uamps > 0 ) {
998       //Re-arm warning
999       b_warned = 0;
1000       pnd_log ( pndn_debug, "Battery is high again, flipping to non-blinker mode\n" );
1001       b_active = 0;
1002       set_next_alarm ( b_frequency, 0 );
1003       pnd_device_set_led_charger_brightness ( 250 );
1004       return;
1005     }
1006
1007     if ( b_active == 1 ) {
1008       // turn LED on
1009       pnd_log ( pndn_debug, "Blink on\n" );
1010       pnd_device_set_led_charger_brightness ( 200 );
1011       // set timer to short duration
1012       b_active = 2;
1013       set_next_alarm ( 0, b_blinkdur );
1014     } else if ( b_active == 2 ) {
1015       // turn LED off
1016       pnd_log ( pndn_debug, "Blink off\n" );
1017       pnd_device_set_led_charger_brightness ( 10 );
1018       // back to longer duration
1019       b_active = 1;
1020       set_next_alarm ( b_blinkfreq, 0 );
1021     }
1022
1023     return;
1024   }
1025
1026   // warning is off..
1027   if ( batlevel <= b_threshold && uamps < 0 ) {
1028     // battery seems low, go to active mode
1029     pnd_log ( pndn_debug, "Battery is low, flipping to blinker mode\n" );
1030     b_active = 1;
1031     set_next_alarm ( b_blinkfreq, 0 );
1032   } // battery level
1033
1034   return;
1035 }
1036
1037 void fakescript_hold_on ( void ) {
1038   pnd_log ( pndn_rem, "HOLD is being enabled.\n" );
1039
1040   int i;
1041   for ( i = 0; i < imaxfd; i++ ) {
1042     ioctl ( fds [ i ], EVIOCGRAB, 1 /* enable */ );
1043   }
1044
1045   return;
1046 }
1047
1048 void fakescript_hold_off ( void ) {
1049   pnd_log ( pndn_rem, "HOLD is being disabled.\n" );
1050
1051   int i;
1052   for ( i = 0; i < imaxfd; i++ ) {
1053     ioctl ( fds [ i ], EVIOCGRAB, 0 /* disable */ );
1054   }
1055
1056   return;
1057 }