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