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