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
51char *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
80struct key_state {
81    bool pending;
82    bool down;
83    int64_t timestamp;
84};
85
86struct frame {
87    int disp_time;
88    int min_capacity;
89    bool level_only;
90
91    GRSurface* surface;
92};
93
94struct 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
108struct 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    GRSurface* surf_unknown;
119    int boot_min_cap;
120};
121
122static struct frame batt_anim_frames[] = {
123    {
124        .disp_time = 750,
125        .min_capacity = 0,
126        .level_only = false,
127        .surface = NULL,
128    },
129    {
130        .disp_time = 750,
131        .min_capacity = 20,
132        .level_only = false,
133        .surface = NULL,
134    },
135    {
136        .disp_time = 750,
137        .min_capacity = 40,
138        .level_only = false,
139        .surface = NULL,
140    },
141    {
142        .disp_time = 750,
143        .min_capacity = 60,
144        .level_only = false,
145        .surface = NULL,
146    },
147    {
148        .disp_time = 750,
149        .min_capacity = 80,
150        .level_only = true,
151        .surface = NULL,
152    },
153    {
154        .disp_time = 750,
155        .min_capacity = BATTERY_FULL_THRESH,
156        .level_only = false,
157        .surface = NULL,
158    },
159};
160
161static struct animation battery_animation = {
162    .run = false,
163    .frames = batt_anim_frames,
164    .cur_frame = 0,
165    .num_frames = ARRAY_SIZE(batt_anim_frames),
166    .cur_cycle = 0,
167    .num_cycles = 3,
168    .capacity = 0,
169};
170
171static struct charger charger_state;
172static struct healthd_config *healthd_config;
173static struct android::BatteryProperties *batt_prop;
174static int char_width;
175static int char_height;
176static bool minui_inited;
177
178/* current time in milliseconds */
179static int64_t curr_time_ms(void)
180{
181    struct timespec tm;
182    clock_gettime(CLOCK_MONOTONIC, &tm);
183    return tm.tv_sec * MSEC_PER_SEC + (tm.tv_nsec / NSEC_PER_MSEC);
184}
185
186static void clear_screen(void)
187{
188    gr_color(0, 0, 0, 255);
189    gr_clear();
190}
191
192#define MAX_KLOG_WRITE_BUF_SZ 256
193
194static void dump_last_kmsg(void)
195{
196    char *buf;
197    char *ptr;
198    unsigned sz = 0;
199    int len;
200
201    LOGW("\n");
202    LOGW("*************** LAST KMSG ***************\n");
203    LOGW("\n");
204    buf = (char *)load_file(LAST_KMSG_PSTORE_PATH, &sz);
205
206    if (!buf || !sz) {
207        buf = (char *)load_file(LAST_KMSG_PATH, &sz);
208        if (!buf || !sz) {
209            LOGW("last_kmsg not found. Cold reset?\n");
210            goto out;
211        }
212    }
213
214    len = min(sz, LAST_KMSG_MAX_SZ);
215    ptr = buf + (sz - len);
216
217    while (len > 0) {
218        int cnt = min(len, MAX_KLOG_WRITE_BUF_SZ);
219        char yoink;
220        char *nl;
221
222        nl = (char *)memrchr(ptr, '\n', cnt - 1);
223        if (nl)
224            cnt = nl - ptr + 1;
225
226        yoink = ptr[cnt];
227        ptr[cnt] = '\0';
228        klog_write(6, "<4>%s", ptr);
229        ptr[cnt] = yoink;
230
231        len -= cnt;
232        ptr += cnt;
233    }
234
235    free(buf);
236
237out:
238    LOGW("\n");
239    LOGW("************* END LAST KMSG *************\n");
240    LOGW("\n");
241}
242
243#ifdef CHARGER_ENABLE_SUSPEND
244static int request_suspend(bool enable)
245{
246    if (enable)
247        return autosuspend_enable();
248    else
249        return autosuspend_disable();
250}
251#else
252static int request_suspend(bool /*enable*/)
253{
254    return 0;
255}
256#endif
257
258static int draw_text(const char *str, int x, int y)
259{
260    int str_len_px = gr_measure(str);
261
262    if (x < 0)
263        x = (gr_fb_width() - str_len_px) / 2;
264    if (y < 0)
265        y = (gr_fb_height() - char_height) / 2;
266    gr_text(x, y, str, 0);
267
268    return y + char_height;
269}
270
271static void android_green(void)
272{
273    gr_color(0xa4, 0xc6, 0x39, 255);
274}
275
276/* returns the last y-offset of where the surface ends */
277static int draw_surface_centered(struct charger* /*charger*/, GRSurface* surface)
278{
279    int w;
280    int h;
281    int x;
282    int y;
283
284    w = gr_get_width(surface);
285    h = gr_get_height(surface);
286    x = (gr_fb_width() - w) / 2 ;
287    y = (gr_fb_height() - h) / 2 ;
288
289    LOGV("drawing surface %dx%d+%d+%d\n", w, h, x, y);
290    gr_blit(surface, 0, 0, w, h, x, y);
291    return y + h;
292}
293
294static void draw_unknown(struct charger *charger)
295{
296    int y;
297    if (charger->surf_unknown) {
298        draw_surface_centered(charger, charger->surf_unknown);
299    } else {
300        android_green();
301        y = draw_text("Charging!", -1, -1);
302        draw_text("?\?/100", -1, y + 25);
303    }
304}
305
306static void draw_battery(struct charger *charger)
307{
308    struct animation *batt_anim = charger->batt_anim;
309    struct frame *frame = &batt_anim->frames[batt_anim->cur_frame];
310
311    if (batt_anim->num_frames != 0) {
312        draw_surface_centered(charger, frame->surface);
313        LOGV("drawing frame #%d min_cap=%d time=%d\n",
314             batt_anim->cur_frame, frame->min_capacity,
315             frame->disp_time);
316    }
317}
318
319static void redraw_screen(struct charger *charger)
320{
321    struct animation *batt_anim = charger->batt_anim;
322
323    clear_screen();
324
325    /* try to display *something* */
326    if (batt_anim->capacity < 0 || batt_anim->num_frames == 0)
327        draw_unknown(charger);
328    else
329        draw_battery(charger);
330    gr_flip();
331}
332
333static void kick_animation(struct animation *anim)
334{
335    anim->run = true;
336}
337
338static void reset_animation(struct animation *anim)
339{
340    anim->cur_cycle = 0;
341    anim->cur_frame = 0;
342    anim->run = false;
343}
344
345static void update_screen_state(struct charger *charger, int64_t now)
346{
347    struct animation *batt_anim = charger->batt_anim;
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
391        LOGV("[%" PRId64 "] animation starting\n", now);
392        if (batt_prop && batt_prop->batteryLevel >= 0 && batt_anim->num_frames != 0) {
393            int i;
394
395            /* find first frame given current capacity */
396            for (i = 1; i < batt_anim->num_frames; i++) {
397                if (batt_prop->batteryLevel < batt_anim->frames[i].min_capacity)
398                    break;
399            }
400            batt_anim->cur_frame = i - 1;
401
402            /* show the first frame for twice as long */
403            disp_time = batt_anim->frames[batt_anim->cur_frame].disp_time * 2;
404        }
405        if (batt_prop)
406            batt_anim->capacity = batt_prop->batteryLevel;
407    }
408
409    /* unblank the screen  on first cycle */
410    if (batt_anim->cur_cycle == 0)
411        gr_fb_blank(false);
412
413    /* draw the new frame (@ cur_frame) */
414    redraw_screen(charger);
415
416    /* if we don't have anim frames, we only have one image, so just bump
417     * the cycle counter and exit
418     */
419    if (batt_anim->num_frames == 0 || batt_anim->capacity < 0) {
420        LOGV("[%" PRId64 "] animation missing or unknown battery status\n", now);
421        charger->next_screen_transition = now + BATTERY_UNKNOWN_TIME;
422        batt_anim->cur_cycle++;
423        return;
424    }
425
426    /* schedule next screen transition */
427    charger->next_screen_transition = now + disp_time;
428
429    /* advance frame cntr to the next valid frame only if we are charging
430     * if necessary, advance cycle cntr, and reset frame cntr
431     */
432    if (charger->charger_connected) {
433        batt_anim->cur_frame++;
434
435        /* if the frame is used for level-only, that is only show it when it's
436         * the current level, skip it during the animation.
437         */
438        while (batt_anim->cur_frame < batt_anim->num_frames &&
439               batt_anim->frames[batt_anim->cur_frame].level_only)
440            batt_anim->cur_frame++;
441        if (batt_anim->cur_frame >= batt_anim->num_frames) {
442            batt_anim->cur_cycle++;
443            batt_anim->cur_frame = 0;
444
445            /* don't reset the cycle counter, since we use that as a signal
446             * in a test above to check if animation is over
447             */
448        }
449    } else {
450        /* Stop animating if we're not charging.
451         * If we stop it immediately instead of going through this loop, then
452         * the animation would stop somewhere in the middle.
453         */
454        batt_anim->cur_frame = 0;
455        batt_anim->cur_cycle++;
456    }
457}
458
459static int set_key_callback(int code, int value, void *data)
460{
461    struct charger *charger = (struct charger *)data;
462    int64_t now = curr_time_ms();
463    int down = !!value;
464
465    if (code > KEY_MAX)
466        return -1;
467
468    /* ignore events that don't modify our state */
469    if (charger->keys[code].down == down)
470        return 0;
471
472    /* only record the down even timestamp, as the amount
473     * of time the key spent not being pressed is not useful */
474    if (down)
475        charger->keys[code].timestamp = now;
476    charger->keys[code].down = down;
477    charger->keys[code].pending = true;
478    if (down) {
479        LOGV("[%" PRId64 "] key[%d] down\n", now, code);
480    } else {
481        int64_t duration = now - charger->keys[code].timestamp;
482        int64_t secs = duration / 1000;
483        int64_t msecs = duration - secs * 1000;
484        LOGV("[%" PRId64 "] key[%d] up (was down for %" PRId64 ".%" PRId64 "sec)\n",
485             now, code, secs, msecs);
486    }
487
488    return 0;
489}
490
491static void update_input_state(struct charger *charger,
492                               struct input_event *ev)
493{
494    if (ev->type != EV_KEY)
495        return;
496    set_key_callback(ev->code, ev->value, charger);
497}
498
499static void set_next_key_check(struct charger *charger,
500                               struct key_state *key,
501                               int64_t timeout)
502{
503    int64_t then = key->timestamp + timeout;
504
505    if (charger->next_key_check == -1 || then < charger->next_key_check)
506        charger->next_key_check = then;
507}
508
509static void process_key(struct charger *charger, int code, int64_t now)
510{
511    struct key_state *key = &charger->keys[code];
512
513    if (code == KEY_POWER) {
514        if (key->down) {
515            int64_t reboot_timeout = key->timestamp + POWER_ON_KEY_TIME;
516            if (now >= reboot_timeout) {
517                /* We do not currently support booting from charger mode on
518                   all devices. Check the property and continue booting or reboot
519                   accordingly. */
520                if (property_get_bool("ro.enable_boot_charger_mode", false)) {
521                    LOGW("[%" PRId64 "] booting from charger mode\n", now);
522                    property_set("sys.boot_from_charger_mode", "1");
523                } else {
524                    if (charger->batt_anim->capacity >= charger->boot_min_cap) {
525                        LOGW("[%" PRId64 "] rebooting\n", now);
526                        android_reboot(ANDROID_RB_RESTART, 0, 0);
527                    } else {
528                        LOGV("[%" PRId64 "] ignore power-button press, battery level "
529                            "less than minimum\n", now);
530                    }
531                }
532            } else {
533                /* if the key is pressed but timeout hasn't expired,
534                 * make sure we wake up at the right-ish time to check
535                 */
536                set_next_key_check(charger, key, POWER_ON_KEY_TIME);
537
538               /* Turn on the display and kick animation on power-key press
539                * rather than on key release
540                */
541                kick_animation(charger->batt_anim);
542                request_suspend(false);
543            }
544        } else {
545            /* if the power key got released, force screen state cycle */
546            if (key->pending) {
547                kick_animation(charger->batt_anim);
548            }
549        }
550    }
551
552    key->pending = false;
553}
554
555static void handle_input_state(struct charger *charger, int64_t now)
556{
557    process_key(charger, KEY_POWER, now);
558
559    if (charger->next_key_check != -1 && now > charger->next_key_check)
560        charger->next_key_check = -1;
561}
562
563static void handle_power_supply_state(struct charger *charger, int64_t now)
564{
565    if (!charger->have_battery_state)
566        return;
567
568    if (!charger->charger_connected) {
569
570        /* Last cycle would have stopped at the extreme top of battery-icon
571         * Need to show the correct level corresponding to capacity.
572         */
573        kick_animation(charger->batt_anim);
574        request_suspend(false);
575        if (charger->next_pwr_check == -1) {
576            charger->next_pwr_check = now + UNPLUGGED_SHUTDOWN_TIME;
577            LOGW("[%" PRId64 "] device unplugged: shutting down in %" PRId64 " (@ %" PRId64 ")\n",
578                 now, (int64_t)UNPLUGGED_SHUTDOWN_TIME, charger->next_pwr_check);
579        } else if (now >= charger->next_pwr_check) {
580            LOGW("[%" PRId64 "] shutting down\n", now);
581            android_reboot(ANDROID_RB_POWEROFF, 0, 0);
582        } else {
583            /* otherwise we already have a shutdown timer scheduled */
584        }
585    } else {
586        /* online supply present, reset shutdown timer if set */
587        if (charger->next_pwr_check != -1) {
588            LOGW("[%" PRId64 "] device plugged in: shutdown cancelled\n", now);
589            kick_animation(charger->batt_anim);
590        }
591        charger->next_pwr_check = -1;
592    }
593}
594
595void healthd_mode_charger_heartbeat()
596{
597    struct charger *charger = &charger_state;
598    int64_t now = curr_time_ms();
599
600    handle_input_state(charger, now);
601    handle_power_supply_state(charger, now);
602
603    /* do screen update last in case any of the above want to start
604     * screen transitions (animations, etc)
605     */
606    update_screen_state(charger, now);
607}
608
609void healthd_mode_charger_battery_update(
610    struct android::BatteryProperties *props)
611{
612    struct charger *charger = &charger_state;
613
614    charger->charger_connected =
615        props->chargerAcOnline || props->chargerUsbOnline ||
616        props->chargerWirelessOnline;
617
618    if (!charger->have_battery_state) {
619        charger->have_battery_state = true;
620        charger->next_screen_transition = curr_time_ms() - 1;
621        reset_animation(charger->batt_anim);
622        kick_animation(charger->batt_anim);
623    }
624    batt_prop = props;
625}
626
627int healthd_mode_charger_preparetowait(void)
628{
629    struct charger *charger = &charger_state;
630    int64_t now = curr_time_ms();
631    int64_t next_event = INT64_MAX;
632    int64_t timeout;
633
634    LOGV("[%" PRId64 "] next screen: %" PRId64 " next key: %" PRId64 " next pwr: %" PRId64 "\n", now,
635         charger->next_screen_transition, charger->next_key_check,
636         charger->next_pwr_check);
637
638    if (charger->next_screen_transition != -1)
639        next_event = charger->next_screen_transition;
640    if (charger->next_key_check != -1 && charger->next_key_check < next_event)
641        next_event = charger->next_key_check;
642    if (charger->next_pwr_check != -1 && charger->next_pwr_check < next_event)
643        next_event = charger->next_pwr_check;
644
645    if (next_event != -1 && next_event != INT64_MAX)
646        timeout = max(0, next_event - now);
647    else
648        timeout = -1;
649
650   return (int)timeout;
651}
652
653static int input_callback(int fd, unsigned int epevents, void *data)
654{
655    struct charger *charger = (struct charger *)data;
656    struct input_event ev;
657    int ret;
658
659    ret = ev_get_input(fd, epevents, &ev);
660    if (ret)
661        return -1;
662    update_input_state(charger, &ev);
663    return 0;
664}
665
666static void charger_event_handler(uint32_t /*epevents*/)
667{
668    int ret;
669
670    ret = ev_wait(-1);
671    if (!ret)
672        ev_dispatch();
673}
674
675void healthd_mode_charger_init(struct healthd_config* config)
676{
677    int ret;
678    struct charger *charger = &charger_state;
679    int i;
680    int epollfd;
681
682    dump_last_kmsg();
683
684    LOGW("--------------- STARTING CHARGER MODE ---------------\n");
685
686    ret = ev_init(input_callback, charger);
687    if (!ret) {
688        epollfd = ev_get_epollfd();
689        healthd_register_event(epollfd, charger_event_handler);
690    }
691
692    ret = res_create_display_surface("charger/battery_fail", &charger->surf_unknown);
693    if (ret < 0) {
694        LOGE("Cannot load battery_fail image\n");
695        charger->surf_unknown = NULL;
696    }
697
698    charger->batt_anim = &battery_animation;
699
700    GRSurface** scale_frames;
701    int scale_count;
702    ret = res_create_multi_display_surface("charger/battery_scale", &scale_count, &scale_frames);
703    if (ret < 0) {
704        LOGE("Cannot load battery_scale image\n");
705        charger->batt_anim->num_frames = 0;
706        charger->batt_anim->num_cycles = 1;
707    } else if (scale_count != charger->batt_anim->num_frames) {
708        LOGE("battery_scale image has unexpected frame count (%d, expected %d)\n",
709             scale_count, charger->batt_anim->num_frames);
710        charger->batt_anim->num_frames = 0;
711        charger->batt_anim->num_cycles = 1;
712    } else {
713        for (i = 0; i < charger->batt_anim->num_frames; i++) {
714            charger->batt_anim->frames[i].surface = scale_frames[i];
715        }
716    }
717
718    ev_sync_key_state(set_key_callback, charger);
719
720    charger->next_screen_transition = -1;
721    charger->next_key_check = -1;
722    charger->next_pwr_check = -1;
723    healthd_config = config;
724    charger->boot_min_cap = config->boot_min_cap;
725}
726