• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011-2013 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <dirent.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <inttypes.h>
21 #include <linux/input.h>
22 #include <stdbool.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/epoll.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <sys/un.h>
30 #include <time.h>
31 #include <unistd.h>
32 
33 #include <sys/socket.h>
34 #include <linux/netlink.h>
35 
36 #include <batteryservice/BatteryService.h>
37 #include <cutils/android_reboot.h>
38 #include <cutils/klog.h>
39 #include <cutils/misc.h>
40 #include <cutils/uevent.h>
41 #include <cutils/properties.h>
42 
43 #ifdef CHARGER_ENABLE_SUSPEND
44 #include <suspend/autosuspend.h>
45 #endif
46 
47 #include "minui/minui.h"
48 
49 #include "healthd.h"
50 
51 char *locale;
52 
53 #ifndef max
54 #define max(a,b) ((a) > (b) ? (a) : (b))
55 #endif
56 
57 #ifndef min
58 #define min(a,b) ((a) < (b) ? (a) : (b))
59 #endif
60 
61 #define ARRAY_SIZE(x)           (sizeof(x)/sizeof(x[0]))
62 
63 #define MSEC_PER_SEC            (1000LL)
64 #define NSEC_PER_MSEC           (1000000LL)
65 
66 #define BATTERY_UNKNOWN_TIME    (2 * MSEC_PER_SEC)
67 #define POWER_ON_KEY_TIME       (2 * MSEC_PER_SEC)
68 #define UNPLUGGED_SHUTDOWN_TIME (10 * MSEC_PER_SEC)
69 
70 #define BATTERY_FULL_THRESH     95
71 
72 #define LAST_KMSG_PATH          "/proc/last_kmsg"
73 #define LAST_KMSG_PSTORE_PATH   "/sys/fs/pstore/console-ramoops"
74 #define LAST_KMSG_MAX_SZ        (32 * 1024)
75 
76 #define LOGE(x...) do { KLOG_ERROR("charger", x); } while (0)
77 #define LOGW(x...) do { KLOG_WARNING("charger", x); } while (0)
78 #define LOGV(x...) do { KLOG_DEBUG("charger", x); } while (0)
79 
80 struct key_state {
81     bool pending;
82     bool down;
83     int64_t timestamp;
84 };
85 
86 struct frame {
87     int disp_time;
88     int min_capacity;
89     bool level_only;
90 
91     gr_surface surface;
92 };
93 
94 struct animation {
95     bool run;
96 
97     struct frame *frames;
98     int cur_frame;
99     int num_frames;
100 
101     int cur_cycle;
102     int num_cycles;
103 
104     /* current capacity being animated */
105     int capacity;
106 };
107 
108 struct charger {
109     bool have_battery_state;
110     bool charger_connected;
111     int64_t next_screen_transition;
112     int64_t next_key_check;
113     int64_t next_pwr_check;
114 
115     struct key_state keys[KEY_MAX + 1];
116 
117     struct animation *batt_anim;
118     gr_surface surf_unknown;
119 };
120 
121 static struct frame batt_anim_frames[] = {
122     {
123         .disp_time = 750,
124         .min_capacity = 0,
125         .level_only = false,
126         .surface = NULL,
127     },
128     {
129         .disp_time = 750,
130         .min_capacity = 20,
131         .level_only = false,
132         .surface = NULL,
133     },
134     {
135         .disp_time = 750,
136         .min_capacity = 40,
137         .level_only = false,
138         .surface = NULL,
139     },
140     {
141         .disp_time = 750,
142         .min_capacity = 60,
143         .level_only = false,
144         .surface = NULL,
145     },
146     {
147         .disp_time = 750,
148         .min_capacity = 80,
149         .level_only = true,
150         .surface = NULL,
151     },
152     {
153         .disp_time = 750,
154         .min_capacity = BATTERY_FULL_THRESH,
155         .level_only = false,
156         .surface = NULL,
157     },
158 };
159 
160 static struct animation battery_animation = {
161     .run = false,
162     .frames = batt_anim_frames,
163     .cur_frame = 0,
164     .num_frames = ARRAY_SIZE(batt_anim_frames),
165     .cur_cycle = 0,
166     .num_cycles = 3,
167     .capacity = 0,
168 };
169 
170 static struct charger charger_state;
171 static struct healthd_config *healthd_config;
172 static struct android::BatteryProperties *batt_prop;
173 static int char_width;
174 static int char_height;
175 static bool minui_inited;
176 
177 /* current time in milliseconds */
curr_time_ms(void)178 static int64_t curr_time_ms(void)
179 {
180     struct timespec tm;
181     clock_gettime(CLOCK_MONOTONIC, &tm);
182     return tm.tv_sec * MSEC_PER_SEC + (tm.tv_nsec / NSEC_PER_MSEC);
183 }
184 
clear_screen(void)185 static void clear_screen(void)
186 {
187     gr_color(0, 0, 0, 255);
188     gr_clear();
189 }
190 
191 #define MAX_KLOG_WRITE_BUF_SZ 256
192 
dump_last_kmsg(void)193 static void dump_last_kmsg(void)
194 {
195     char *buf;
196     char *ptr;
197     unsigned sz = 0;
198     int len;
199 
200     LOGW("\n");
201     LOGW("*************** LAST KMSG ***************\n");
202     LOGW("\n");
203     buf = (char *)load_file(LAST_KMSG_PSTORE_PATH, &sz);
204 
205     if (!buf || !sz) {
206         buf = (char *)load_file(LAST_KMSG_PATH, &sz);
207         if (!buf || !sz) {
208             LOGW("last_kmsg not found. Cold reset?\n");
209             goto out;
210         }
211     }
212 
213     len = min(sz, LAST_KMSG_MAX_SZ);
214     ptr = buf + (sz - len);
215 
216     while (len > 0) {
217         int cnt = min(len, MAX_KLOG_WRITE_BUF_SZ);
218         char yoink;
219         char *nl;
220 
221         nl = (char *)memrchr(ptr, '\n', cnt - 1);
222         if (nl)
223             cnt = nl - ptr + 1;
224 
225         yoink = ptr[cnt];
226         ptr[cnt] = '\0';
227         klog_write(6, "<4>%s", ptr);
228         ptr[cnt] = yoink;
229 
230         len -= cnt;
231         ptr += cnt;
232     }
233 
234     free(buf);
235 
236 out:
237     LOGW("\n");
238     LOGW("************* END LAST KMSG *************\n");
239     LOGW("\n");
240 }
241 
242 #ifdef CHARGER_ENABLE_SUSPEND
request_suspend(bool enable)243 static int request_suspend(bool enable)
244 {
245     if (enable)
246         return autosuspend_enable();
247     else
248         return autosuspend_disable();
249 }
250 #else
request_suspend(bool)251 static int request_suspend(bool /*enable*/)
252 {
253     return 0;
254 }
255 #endif
256 
draw_text(const char * str,int x,int y)257 static int draw_text(const char *str, int x, int y)
258 {
259     int str_len_px = gr_measure(str);
260 
261     if (x < 0)
262         x = (gr_fb_width() - str_len_px) / 2;
263     if (y < 0)
264         y = (gr_fb_height() - char_height) / 2;
265     gr_text(x, y, str, 0);
266 
267     return y + char_height;
268 }
269 
android_green(void)270 static void android_green(void)
271 {
272     gr_color(0xa4, 0xc6, 0x39, 255);
273 }
274 
275 /* returns the last y-offset of where the surface ends */
draw_surface_centered(struct charger *,gr_surface surface)276 static int draw_surface_centered(struct charger* /*charger*/, gr_surface surface)
277 {
278     int w;
279     int h;
280     int x;
281     int y;
282 
283     w = gr_get_width(surface);
284     h = gr_get_height(surface);
285     x = (gr_fb_width() - w) / 2 ;
286     y = (gr_fb_height() - h) / 2 ;
287 
288     LOGV("drawing surface %dx%d+%d+%d\n", w, h, x, y);
289     gr_blit(surface, 0, 0, w, h, x, y);
290     return y + h;
291 }
292 
draw_unknown(struct charger * charger)293 static void draw_unknown(struct charger *charger)
294 {
295     int y;
296     if (charger->surf_unknown) {
297         draw_surface_centered(charger, charger->surf_unknown);
298     } else {
299         android_green();
300         y = draw_text("Charging!", -1, -1);
301         draw_text("?\?/100", -1, y + 25);
302     }
303 }
304 
draw_battery(struct charger * charger)305 static void draw_battery(struct charger *charger)
306 {
307     struct animation *batt_anim = charger->batt_anim;
308     struct frame *frame = &batt_anim->frames[batt_anim->cur_frame];
309 
310     if (batt_anim->num_frames != 0) {
311         draw_surface_centered(charger, frame->surface);
312         LOGV("drawing frame #%d min_cap=%d time=%d\n",
313              batt_anim->cur_frame, frame->min_capacity,
314              frame->disp_time);
315     }
316 }
317 
redraw_screen(struct charger * charger)318 static void redraw_screen(struct charger *charger)
319 {
320     struct animation *batt_anim = charger->batt_anim;
321 
322     clear_screen();
323 
324     /* try to display *something* */
325     if (batt_anim->capacity < 0 || batt_anim->num_frames == 0)
326         draw_unknown(charger);
327     else
328         draw_battery(charger);
329     gr_flip();
330 }
331 
kick_animation(struct animation * anim)332 static void kick_animation(struct animation *anim)
333 {
334     anim->run = true;
335 }
336 
reset_animation(struct animation * anim)337 static void reset_animation(struct animation *anim)
338 {
339     anim->cur_cycle = 0;
340     anim->cur_frame = 0;
341     anim->run = false;
342 }
343 
update_screen_state(struct charger * charger,int64_t now)344 static void update_screen_state(struct charger *charger, int64_t now)
345 {
346     struct animation *batt_anim = charger->batt_anim;
347     int cur_frame;
348     int disp_time;
349 
350     if (!batt_anim->run || now < charger->next_screen_transition)
351         return;
352 
353     if (!minui_inited) {
354 
355         if (healthd_config && healthd_config->screen_on) {
356             if (!healthd_config->screen_on(batt_prop)) {
357                 LOGV("[%" PRId64 "] leave screen off\n", now);
358                 batt_anim->run = false;
359                 charger->next_screen_transition = -1;
360                 if (charger->charger_connected)
361                     request_suspend(true);
362                 return;
363             }
364         }
365 
366         gr_init();
367         gr_font_size(&char_width, &char_height);
368 
369 #ifndef CHARGER_DISABLE_INIT_BLANK
370         gr_fb_blank(true);
371 #endif
372         minui_inited = true;
373     }
374 
375     /* animation is over, blank screen and leave */
376     if (batt_anim->cur_cycle == batt_anim->num_cycles) {
377         reset_animation(batt_anim);
378         charger->next_screen_transition = -1;
379         gr_fb_blank(true);
380         LOGV("[%" PRId64 "] animation done\n", now);
381         if (charger->charger_connected)
382             request_suspend(true);
383         return;
384     }
385 
386     disp_time = batt_anim->frames[batt_anim->cur_frame].disp_time;
387 
388     /* animation starting, set up the animation */
389     if (batt_anim->cur_frame == 0) {
390         int ret;
391 
392         LOGV("[%" PRId64 "] animation starting\n", now);
393         if (batt_prop && batt_prop->batteryLevel >= 0 && batt_anim->num_frames != 0) {
394             int i;
395 
396             /* find first frame given current capacity */
397             for (i = 1; i < batt_anim->num_frames; i++) {
398                 if (batt_prop->batteryLevel < batt_anim->frames[i].min_capacity)
399                     break;
400             }
401             batt_anim->cur_frame = i - 1;
402 
403             /* show the first frame for twice as long */
404             disp_time = batt_anim->frames[batt_anim->cur_frame].disp_time * 2;
405         }
406         if (batt_prop)
407             batt_anim->capacity = batt_prop->batteryLevel;
408     }
409 
410     /* unblank the screen  on first cycle */
411     if (batt_anim->cur_cycle == 0)
412         gr_fb_blank(false);
413 
414     /* draw the new frame (@ cur_frame) */
415     redraw_screen(charger);
416 
417     /* if we don't have anim frames, we only have one image, so just bump
418      * the cycle counter and exit
419      */
420     if (batt_anim->num_frames == 0 || batt_anim->capacity < 0) {
421         LOGV("[%" PRId64 "] animation missing or unknown battery status\n", now);
422         charger->next_screen_transition = now + BATTERY_UNKNOWN_TIME;
423         batt_anim->cur_cycle++;
424         return;
425     }
426 
427     /* schedule next screen transition */
428     charger->next_screen_transition = now + disp_time;
429 
430     /* advance frame cntr to the next valid frame only if we are charging
431      * if necessary, advance cycle cntr, and reset frame cntr
432      */
433     if (charger->charger_connected) {
434         batt_anim->cur_frame++;
435 
436         /* if the frame is used for level-only, that is only show it when it's
437          * the current level, skip it during the animation.
438          */
439         while (batt_anim->cur_frame < batt_anim->num_frames &&
440                batt_anim->frames[batt_anim->cur_frame].level_only)
441             batt_anim->cur_frame++;
442         if (batt_anim->cur_frame >= batt_anim->num_frames) {
443             batt_anim->cur_cycle++;
444             batt_anim->cur_frame = 0;
445 
446             /* don't reset the cycle counter, since we use that as a signal
447              * in a test above to check if animation is over
448              */
449         }
450     } else {
451         /* Stop animating if we're not charging.
452          * If we stop it immediately instead of going through this loop, then
453          * the animation would stop somewhere in the middle.
454          */
455         batt_anim->cur_frame = 0;
456         batt_anim->cur_cycle++;
457     }
458 }
459 
set_key_callback(int code,int value,void * data)460 static int set_key_callback(int code, int value, void *data)
461 {
462     struct charger *charger = (struct charger *)data;
463     int64_t now = curr_time_ms();
464     int down = !!value;
465 
466     if (code > KEY_MAX)
467         return -1;
468 
469     /* ignore events that don't modify our state */
470     if (charger->keys[code].down == down)
471         return 0;
472 
473     /* only record the down even timestamp, as the amount
474      * of time the key spent not being pressed is not useful */
475     if (down)
476         charger->keys[code].timestamp = now;
477     charger->keys[code].down = down;
478     charger->keys[code].pending = true;
479     if (down) {
480         LOGV("[%" PRId64 "] key[%d] down\n", now, code);
481     } else {
482         int64_t duration = now - charger->keys[code].timestamp;
483         int64_t secs = duration / 1000;
484         int64_t msecs = duration - secs * 1000;
485         LOGV("[%" PRId64 "] key[%d] up (was down for %" PRId64 ".%" PRId64 "sec)\n",
486              now, code, secs, msecs);
487     }
488 
489     return 0;
490 }
491 
update_input_state(struct charger * charger,struct input_event * ev)492 static void update_input_state(struct charger *charger,
493                                struct input_event *ev)
494 {
495     if (ev->type != EV_KEY)
496         return;
497     set_key_callback(ev->code, ev->value, charger);
498 }
499 
set_next_key_check(struct charger * charger,struct key_state * key,int64_t timeout)500 static void set_next_key_check(struct charger *charger,
501                                struct key_state *key,
502                                int64_t timeout)
503 {
504     int64_t then = key->timestamp + timeout;
505 
506     if (charger->next_key_check == -1 || then < charger->next_key_check)
507         charger->next_key_check = then;
508 }
509 
process_key(struct charger * charger,int code,int64_t now)510 static void process_key(struct charger *charger, int code, int64_t now)
511 {
512     struct key_state *key = &charger->keys[code];
513     int64_t next_key_check;
514 
515     if (code == KEY_POWER) {
516         if (key->down) {
517             int64_t reboot_timeout = key->timestamp + POWER_ON_KEY_TIME;
518             if (now >= reboot_timeout) {
519                 /* We do not currently support booting from charger mode on
520                    all devices. Check the property and continue booting or reboot
521                    accordingly. */
522                 if (property_get_bool("ro.enable_boot_charger_mode", false)) {
523                     LOGW("[%" PRId64 "] booting from charger mode\n", now);
524                     property_set("sys.boot_from_charger_mode", "1");
525                 } else {
526                     LOGW("[%" PRId64 "] rebooting\n", now);
527                     android_reboot(ANDROID_RB_RESTART, 0, 0);
528                 }
529             } else {
530                 /* if the key is pressed but timeout hasn't expired,
531                  * make sure we wake up at the right-ish time to check
532                  */
533                 set_next_key_check(charger, key, POWER_ON_KEY_TIME);
534             }
535         } else {
536             /* if the power key got released, force screen state cycle */
537             if (key->pending) {
538                 request_suspend(false);
539                 kick_animation(charger->batt_anim);
540             }
541         }
542     }
543 
544     key->pending = false;
545 }
546 
handle_input_state(struct charger * charger,int64_t now)547 static void handle_input_state(struct charger *charger, int64_t now)
548 {
549     process_key(charger, KEY_POWER, now);
550 
551     if (charger->next_key_check != -1 && now > charger->next_key_check)
552         charger->next_key_check = -1;
553 }
554 
handle_power_supply_state(struct charger * charger,int64_t now)555 static void handle_power_supply_state(struct charger *charger, int64_t now)
556 {
557     if (!charger->have_battery_state)
558         return;
559 
560     if (!charger->charger_connected) {
561         request_suspend(false);
562         if (charger->next_pwr_check == -1) {
563             charger->next_pwr_check = now + UNPLUGGED_SHUTDOWN_TIME;
564             LOGW("[%" PRId64 "] device unplugged: shutting down in %" PRId64 " (@ %" PRId64 ")\n",
565                  now, (int64_t)UNPLUGGED_SHUTDOWN_TIME, charger->next_pwr_check);
566         } else if (now >= charger->next_pwr_check) {
567             LOGW("[%" PRId64 "] shutting down\n", now);
568             android_reboot(ANDROID_RB_POWEROFF, 0, 0);
569         } else {
570             /* otherwise we already have a shutdown timer scheduled */
571         }
572     } else {
573         /* online supply present, reset shutdown timer if set */
574         if (charger->next_pwr_check != -1) {
575             LOGW("[%" PRId64 "] device plugged in: shutdown cancelled\n", now);
576             kick_animation(charger->batt_anim);
577         }
578         charger->next_pwr_check = -1;
579     }
580 }
581 
healthd_mode_charger_heartbeat()582 void healthd_mode_charger_heartbeat()
583 {
584     struct charger *charger = &charger_state;
585     int64_t now = curr_time_ms();
586     int ret;
587 
588     handle_input_state(charger, now);
589     handle_power_supply_state(charger, now);
590 
591     /* do screen update last in case any of the above want to start
592      * screen transitions (animations, etc)
593      */
594     update_screen_state(charger, now);
595 }
596 
healthd_mode_charger_battery_update(struct android::BatteryProperties * props)597 void healthd_mode_charger_battery_update(
598     struct android::BatteryProperties *props)
599 {
600     struct charger *charger = &charger_state;
601 
602     charger->charger_connected =
603         props->chargerAcOnline || props->chargerUsbOnline ||
604         props->chargerWirelessOnline;
605 
606     if (!charger->have_battery_state) {
607         charger->have_battery_state = true;
608         charger->next_screen_transition = curr_time_ms() - 1;
609         reset_animation(charger->batt_anim);
610         kick_animation(charger->batt_anim);
611     }
612     batt_prop = props;
613 }
614 
healthd_mode_charger_preparetowait(void)615 int healthd_mode_charger_preparetowait(void)
616 {
617     struct charger *charger = &charger_state;
618     int64_t now = curr_time_ms();
619     int64_t next_event = INT64_MAX;
620     int64_t timeout;
621     struct input_event ev;
622     int ret;
623 
624     LOGV("[%" PRId64 "] next screen: %" PRId64 " next key: %" PRId64 " next pwr: %" PRId64 "\n", now,
625          charger->next_screen_transition, charger->next_key_check,
626          charger->next_pwr_check);
627 
628     if (charger->next_screen_transition != -1)
629         next_event = charger->next_screen_transition;
630     if (charger->next_key_check != -1 && charger->next_key_check < next_event)
631         next_event = charger->next_key_check;
632     if (charger->next_pwr_check != -1 && charger->next_pwr_check < next_event)
633         next_event = charger->next_pwr_check;
634 
635     if (next_event != -1 && next_event != INT64_MAX)
636         timeout = max(0, next_event - now);
637     else
638         timeout = -1;
639 
640    return (int)timeout;
641 }
642 
input_callback(int fd,unsigned int epevents,void * data)643 static int input_callback(int fd, unsigned int epevents, void *data)
644 {
645     struct charger *charger = (struct charger *)data;
646     struct input_event ev;
647     int ret;
648 
649     ret = ev_get_input(fd, epevents, &ev);
650     if (ret)
651         return -1;
652     update_input_state(charger, &ev);
653     return 0;
654 }
655 
charger_event_handler(uint32_t)656 static void charger_event_handler(uint32_t /*epevents*/)
657 {
658     int ret;
659 
660     ret = ev_wait(-1);
661     if (!ret)
662         ev_dispatch();
663 }
664 
healthd_mode_charger_init(struct healthd_config * config)665 void healthd_mode_charger_init(struct healthd_config* config)
666 {
667     int ret;
668     struct charger *charger = &charger_state;
669     int i;
670     int epollfd;
671 
672     dump_last_kmsg();
673 
674     LOGW("--------------- STARTING CHARGER MODE ---------------\n");
675 
676     ret = ev_init(input_callback, charger);
677     if (!ret) {
678         epollfd = ev_get_epollfd();
679         healthd_register_event(epollfd, charger_event_handler);
680     }
681 
682     ret = res_create_display_surface("charger/battery_fail", &charger->surf_unknown);
683     if (ret < 0) {
684         LOGE("Cannot load battery_fail image\n");
685         charger->surf_unknown = NULL;
686     }
687 
688     charger->batt_anim = &battery_animation;
689 
690     gr_surface* scale_frames;
691     int scale_count;
692     ret = res_create_multi_display_surface("charger/battery_scale", &scale_count, &scale_frames);
693     if (ret < 0) {
694         LOGE("Cannot load battery_scale image\n");
695         charger->batt_anim->num_frames = 0;
696         charger->batt_anim->num_cycles = 1;
697     } else if (scale_count != charger->batt_anim->num_frames) {
698         LOGE("battery_scale image has unexpected frame count (%d, expected %d)\n",
699              scale_count, charger->batt_anim->num_frames);
700         charger->batt_anim->num_frames = 0;
701         charger->batt_anim->num_cycles = 1;
702     } else {
703         for (i = 0; i < charger->batt_anim->num_frames; i++) {
704             charger->batt_anim->frames[i].surface = scale_frames[i];
705         }
706     }
707 
708     ev_sync_key_state(set_key_callback, charger);
709 
710     charger->next_screen_transition = -1;
711     charger->next_key_check = -1;
712     charger->next_pwr_check = -1;
713     healthd_config = config;
714 }
715