1 /*
2  * Copyright (C) 2011-2017 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 "healthd_mode_charger.h"
18 
19 #include <dirent.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <inttypes.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 <optional>
34 
35 #include <android-base/file.h>
36 #include <android-base/macros.h>
37 
38 #include <linux/netlink.h>
39 #include <sys/socket.h>
40 
41 #include <cutils/android_get_control_file.h>
42 #include <cutils/klog.h>
43 #include <cutils/misc.h>
44 #include <cutils/properties.h>
45 #include <cutils/uevent.h>
46 #include <sys/reboot.h>
47 
48 #include <suspend/autosuspend.h>
49 
50 #include "AnimationParser.h"
51 #include "charger.sysprop.h"
52 #include "charger_utils.h"
53 #include "healthd_draw.h"
54 
55 #include <android/hardware/health/2.0/IHealthInfoCallback.h>
56 #include <health/utils.h>
57 #include <health2impl/HalHealthLoop.h>
58 #include <health2impl/Health.h>
59 #include <healthd/healthd.h>
60 
61 using namespace android;
62 using android::hardware::Return;
63 using android::hardware::health::GetHealthServiceOrDefault;
64 using android::hardware::health::HealthLoop;
65 using android::hardware::health::V1_0::BatteryStatus;
66 using android::hardware::health::V2_0::Result;
67 using android::hardware::health::V2_1::IHealth;
68 using IHealth_2_0 = android::hardware::health::V2_0::IHealth;
69 using HealthInfo_1_0 = android::hardware::health::V1_0::HealthInfo;
70 using HealthInfo_2_1 = android::hardware::health::V2_1::HealthInfo;
71 
72 // main healthd loop
73 extern int healthd_main(void);
74 
75 // minui globals
76 char* locale;
77 
78 #ifndef max
79 #define max(a, b) ((a) > (b) ? (a) : (b))
80 #endif
81 
82 #ifndef min
83 #define min(a, b) ((a) < (b) ? (a) : (b))
84 #endif
85 
86 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
87 
88 #define MSEC_PER_SEC (1000LL)
89 #define NSEC_PER_MSEC (1000000LL)
90 
91 #define BATTERY_UNKNOWN_TIME (2 * MSEC_PER_SEC)
92 #define POWER_ON_KEY_TIME (2 * MSEC_PER_SEC)
93 #define UNPLUGGED_SHUTDOWN_TIME (10 * MSEC_PER_SEC)
94 #define UNPLUGGED_DISPLAY_TIME (3 * MSEC_PER_SEC)
95 #define MAX_BATT_LEVEL_WAIT_TIME (3 * MSEC_PER_SEC)
96 #define UNPLUGGED_SHUTDOWN_TIME_PROP "ro.product.charger.unplugged_shutdown_time"
97 
98 #define LAST_KMSG_MAX_SZ (32 * 1024)
99 
100 #define LOGE(x...) KLOG_ERROR("charger", x);
101 #define LOGW(x...) KLOG_WARNING("charger", x);
102 #define LOGV(x...) KLOG_DEBUG("charger", x);
103 
104 namespace android {
105 
106 // Resources in /product/etc/res overrides resources in /res.
107 // If the device is using the Generic System Image (GSI), resources may exist in
108 // both paths.
109 static constexpr const char* product_animation_desc_path =
110         "/product/etc/res/values/charger/animation.txt";
111 static constexpr const char* product_animation_root = "/product/etc/res/images/";
112 static constexpr const char* animation_desc_path = "/res/values/charger/animation.txt";
113 
114 static const animation BASE_ANIMATION = {
115     .text_clock =
116         {
117             .pos_x = 0,
118             .pos_y = 0,
119 
120             .color_r = 255,
121             .color_g = 255,
122             .color_b = 255,
123             .color_a = 255,
124 
125             .font = nullptr,
126         },
127     .text_percent =
128         {
129             .pos_x = 0,
130             .pos_y = 0,
131 
132             .color_r = 255,
133             .color_g = 255,
134             .color_b = 255,
135             .color_a = 255,
136         },
137 
138     .run = false,
139 
140     .frames = nullptr,
141     .cur_frame = 0,
142     .num_frames = 0,
143     .first_frame_repeats = 2,
144 
145     .cur_cycle = 0,
146     .num_cycles = 3,
147 
148     .cur_level = 0,
149     .cur_status = BATTERY_STATUS_UNKNOWN,
150 };
151 
InitDefaultAnimationFrames()152 void Charger::InitDefaultAnimationFrames() {
153     owned_frames_ = {
154             {
155                     .disp_time = 750,
156                     .min_level = 0,
157                     .max_level = 19,
158                     .surface = NULL,
159             },
160             {
161                     .disp_time = 750,
162                     .min_level = 0,
163                     .max_level = 39,
164                     .surface = NULL,
165             },
166             {
167                     .disp_time = 750,
168                     .min_level = 0,
169                     .max_level = 59,
170                     .surface = NULL,
171             },
172             {
173                     .disp_time = 750,
174                     .min_level = 0,
175                     .max_level = 79,
176                     .surface = NULL,
177             },
178             {
179                     .disp_time = 750,
180                     .min_level = 80,
181                     .max_level = 95,
182                     .surface = NULL,
183             },
184             {
185                     .disp_time = 750,
186                     .min_level = 0,
187                     .max_level = 100,
188                     .surface = NULL,
189             },
190     };
191 }
192 
Charger(const sp<IHealth> & service)193 Charger::Charger(const sp<IHealth>& service)
194     : HalHealthLoop("charger", service), batt_anim_(BASE_ANIMATION) {}
195 
~Charger()196 Charger::~Charger() {}
197 
198 /* current time in milliseconds */
curr_time_ms()199 static int64_t curr_time_ms() {
200     timespec tm;
201     clock_gettime(CLOCK_MONOTONIC, &tm);
202     return tm.tv_sec * MSEC_PER_SEC + (tm.tv_nsec / NSEC_PER_MSEC);
203 }
204 
205 #define MAX_KLOG_WRITE_BUF_SZ 256
206 
dump_last_kmsg(void)207 static void dump_last_kmsg(void) {
208     std::string buf;
209     char* ptr;
210     size_t len;
211 
212     LOGW("\n");
213     LOGW("*************** LAST KMSG ***************\n");
214     LOGW("\n");
215     const char* kmsg[] = {
216         // clang-format off
217         "/sys/fs/pstore/console-ramoops-0",
218         "/sys/fs/pstore/console-ramoops",
219         "/proc/last_kmsg",
220         // clang-format on
221     };
222     for (size_t i = 0; i < arraysize(kmsg) && buf.empty(); ++i) {
223         auto fd = android_get_control_file(kmsg[i]);
224         if (fd >= 0) {
225             android::base::ReadFdToString(fd, &buf);
226         } else {
227             android::base::ReadFileToString(kmsg[i], &buf);
228         }
229     }
230 
231     if (buf.empty()) {
232         LOGW("last_kmsg not found. Cold reset?\n");
233         goto out;
234     }
235 
236     len = min(buf.size(), LAST_KMSG_MAX_SZ);
237     ptr = &buf[buf.size() - len];
238 
239     while (len > 0) {
240         size_t cnt = min(len, MAX_KLOG_WRITE_BUF_SZ);
241         char yoink;
242         char* nl;
243 
244         nl = (char*)memrchr(ptr, '\n', cnt - 1);
245         if (nl) cnt = nl - ptr + 1;
246 
247         yoink = ptr[cnt];
248         ptr[cnt] = '\0';
249         klog_write(6, "<4>%s", ptr);
250         ptr[cnt] = yoink;
251 
252         len -= cnt;
253         ptr += cnt;
254     }
255 
256 out:
257     LOGW("\n");
258     LOGW("************* END LAST KMSG *************\n");
259     LOGW("\n");
260 }
261 
request_suspend(bool enable)262 static int request_suspend(bool enable) {
263     if (!android::sysprop::ChargerProperties::enable_suspend().value_or(false)) {
264         return 0;
265     }
266 
267     if (enable)
268         return autosuspend_enable();
269     else
270         return autosuspend_disable();
271 }
272 
kick_animation(animation * anim)273 static void kick_animation(animation* anim) {
274     anim->run = true;
275 }
276 
reset_animation(animation * anim)277 static void reset_animation(animation* anim) {
278     anim->cur_cycle = 0;
279     anim->cur_frame = 0;
280     anim->run = false;
281 }
282 
UpdateScreenState(int64_t now)283 void Charger::UpdateScreenState(int64_t now) {
284     int disp_time;
285 
286     if (!batt_anim_.run || now < next_screen_transition_) return;
287 
288     // If battery level is not ready, keep checking in the defined time
289     if (health_info_.batteryLevel == 0 && health_info_.batteryStatus == BatteryStatus::UNKNOWN) {
290         if (wait_batt_level_timestamp_ == 0) {
291             // Set max delay time and skip drawing screen
292             wait_batt_level_timestamp_ = now + MAX_BATT_LEVEL_WAIT_TIME;
293             LOGV("[%" PRId64 "] wait for battery capacity ready\n", now);
294             return;
295         } else if (now <= wait_batt_level_timestamp_) {
296             // Do nothing, keep waiting
297             return;
298         }
299         // If timeout and battery level is still not ready, draw unknown battery
300     }
301 
302     if (healthd_draw_ == nullptr) {
303         std::optional<bool> out_screen_on;
304         service()->shouldKeepScreenOn([&](Result res, bool screen_on) {
305             if (res == Result::SUCCESS) {
306                 *out_screen_on = screen_on;
307             }
308         });
309         if (out_screen_on.has_value()) {
310             if (!*out_screen_on) {
311                 LOGV("[%" PRId64 "] leave screen off\n", now);
312                 batt_anim_.run = false;
313                 next_screen_transition_ = -1;
314                 if (charger_online()) request_suspend(true);
315                 return;
316             }
317         }
318 
319         healthd_draw_.reset(new HealthdDraw(&batt_anim_));
320 
321         if (android::sysprop::ChargerProperties::disable_init_blank().value_or(false)) {
322             healthd_draw_->blank_screen(true);
323             screen_blanked_ = true;
324         }
325     }
326 
327     /* animation is over, blank screen and leave */
328     if (batt_anim_.num_cycles > 0 && batt_anim_.cur_cycle == batt_anim_.num_cycles) {
329         reset_animation(&batt_anim_);
330         next_screen_transition_ = -1;
331         healthd_draw_->blank_screen(true);
332         screen_blanked_ = true;
333         LOGV("[%" PRId64 "] animation done\n", now);
334         if (charger_online()) request_suspend(true);
335         return;
336     }
337 
338     disp_time = batt_anim_.frames[batt_anim_.cur_frame].disp_time;
339 
340     if (screen_blanked_) {
341         healthd_draw_->blank_screen(false);
342         screen_blanked_ = false;
343     }
344 
345     /* animation starting, set up the animation */
346     if (batt_anim_.cur_frame == 0) {
347         LOGV("[%" PRId64 "] animation starting\n", now);
348         batt_anim_.cur_level = health_info_.batteryLevel;
349         batt_anim_.cur_status = (int)health_info_.batteryStatus;
350         if (health_info_.batteryLevel >= 0 && batt_anim_.num_frames != 0) {
351             /* find first frame given current battery level */
352             for (int i = 0; i < batt_anim_.num_frames; i++) {
353                 if (batt_anim_.cur_level >= batt_anim_.frames[i].min_level &&
354                     batt_anim_.cur_level <= batt_anim_.frames[i].max_level) {
355                     batt_anim_.cur_frame = i;
356                     break;
357                 }
358             }
359 
360             if (charger_online()) {
361                 // repeat the first frame first_frame_repeats times
362                 disp_time = batt_anim_.frames[batt_anim_.cur_frame].disp_time *
363                             batt_anim_.first_frame_repeats;
364             } else {
365                 disp_time = UNPLUGGED_DISPLAY_TIME / batt_anim_.num_cycles;
366             }
367 
368             LOGV("cur_frame=%d disp_time=%d\n", batt_anim_.cur_frame, disp_time);
369         }
370     }
371 
372     /* draw the new frame (@ cur_frame) */
373     healthd_draw_->redraw_screen(&batt_anim_, surf_unknown_);
374 
375     /* if we don't have anim frames, we only have one image, so just bump
376      * the cycle counter and exit
377      */
378     if (batt_anim_.num_frames == 0 || batt_anim_.cur_level < 0) {
379         LOGW("[%" PRId64 "] animation missing or unknown battery status\n", now);
380         next_screen_transition_ = now + BATTERY_UNKNOWN_TIME;
381         batt_anim_.cur_cycle++;
382         return;
383     }
384 
385     /* schedule next screen transition */
386     next_screen_transition_ = curr_time_ms() + disp_time;
387 
388     /* advance frame cntr to the next valid frame only if we are charging
389      * if necessary, advance cycle cntr, and reset frame cntr
390      */
391     if (charger_online()) {
392         batt_anim_.cur_frame++;
393 
394         while (batt_anim_.cur_frame < batt_anim_.num_frames &&
395                (batt_anim_.cur_level < batt_anim_.frames[batt_anim_.cur_frame].min_level ||
396                 batt_anim_.cur_level > batt_anim_.frames[batt_anim_.cur_frame].max_level)) {
397             batt_anim_.cur_frame++;
398         }
399         if (batt_anim_.cur_frame >= batt_anim_.num_frames) {
400             batt_anim_.cur_cycle++;
401             batt_anim_.cur_frame = 0;
402 
403             /* don't reset the cycle counter, since we use that as a signal
404              * in a test above to check if animation is over
405              */
406         }
407     } else {
408         /* Stop animating if we're not charging.
409          * If we stop it immediately instead of going through this loop, then
410          * the animation would stop somewhere in the middle.
411          */
412         batt_anim_.cur_frame = 0;
413         batt_anim_.cur_cycle++;
414     }
415 }
416 
SetKeyCallback(int code,int value)417 int Charger::SetKeyCallback(int code, int value) {
418     int64_t now = curr_time_ms();
419     int down = !!value;
420 
421     if (code > KEY_MAX) return -1;
422 
423     /* ignore events that don't modify our state */
424     if (keys_[code].down == down) return 0;
425 
426     /* only record the down even timestamp, as the amount
427      * of time the key spent not being pressed is not useful */
428     if (down) keys_[code].timestamp = now;
429     keys_[code].down = down;
430     keys_[code].pending = true;
431     if (down) {
432         LOGV("[%" PRId64 "] key[%d] down\n", now, code);
433     } else {
434         int64_t duration = now - keys_[code].timestamp;
435         int64_t secs = duration / 1000;
436         int64_t msecs = duration - secs * 1000;
437         LOGV("[%" PRId64 "] key[%d] up (was down for %" PRId64 ".%" PRId64 "sec)\n", now, code,
438              secs, msecs);
439     }
440 
441     return 0;
442 }
443 
UpdateInputState(input_event * ev)444 void Charger::UpdateInputState(input_event* ev) {
445     if (ev->type != EV_KEY) return;
446     SetKeyCallback(ev->code, ev->value);
447 }
448 
SetNextKeyCheck(key_state * key,int64_t timeout)449 void Charger::SetNextKeyCheck(key_state* key, int64_t timeout) {
450     int64_t then = key->timestamp + timeout;
451 
452     if (next_key_check_ == -1 || then < next_key_check_) next_key_check_ = then;
453 }
454 
ProcessKey(int code,int64_t now)455 void Charger::ProcessKey(int code, int64_t now) {
456     key_state* key = &keys_[code];
457 
458     if (code == KEY_POWER) {
459         if (key->down) {
460             int64_t reboot_timeout = key->timestamp + POWER_ON_KEY_TIME;
461             if (now >= reboot_timeout) {
462                 /* We do not currently support booting from charger mode on
463                    all devices. Check the property and continue booting or reboot
464                    accordingly. */
465                 if (property_get_bool("ro.enable_boot_charger_mode", false)) {
466                     LOGW("[%" PRId64 "] booting from charger mode\n", now);
467                     property_set("sys.boot_from_charger_mode", "1");
468                 } else {
469                     if (batt_anim_.cur_level >= boot_min_cap_) {
470                         LOGW("[%" PRId64 "] rebooting\n", now);
471                         reboot(RB_AUTOBOOT);
472                     } else {
473                         LOGV("[%" PRId64
474                              "] ignore power-button press, battery level "
475                              "less than minimum\n",
476                              now);
477                     }
478                 }
479             } else {
480                 /* if the key is pressed but timeout hasn't expired,
481                  * make sure we wake up at the right-ish time to check
482                  */
483                 SetNextKeyCheck(key, POWER_ON_KEY_TIME);
484 
485                 /* Turn on the display and kick animation on power-key press
486                  * rather than on key release
487                  */
488                 kick_animation(&batt_anim_);
489                 request_suspend(false);
490             }
491         } else {
492             /* if the power key got released, force screen state cycle */
493             if (key->pending) {
494                 kick_animation(&batt_anim_);
495                 request_suspend(false);
496             }
497         }
498     }
499 
500     key->pending = false;
501 }
502 
HandleInputState(int64_t now)503 void Charger::HandleInputState(int64_t now) {
504     ProcessKey(KEY_POWER, now);
505 
506     if (next_key_check_ != -1 && now > next_key_check_) next_key_check_ = -1;
507 }
508 
HandlePowerSupplyState(int64_t now)509 void Charger::HandlePowerSupplyState(int64_t now) {
510     int timer_shutdown = UNPLUGGED_SHUTDOWN_TIME;
511     if (!have_battery_state_) return;
512 
513     if (!charger_online()) {
514         request_suspend(false);
515         if (next_pwr_check_ == -1) {
516             /* Last cycle would have stopped at the extreme top of battery-icon
517              * Need to show the correct level corresponding to capacity.
518              *
519              * Reset next_screen_transition_ to update screen immediately.
520              * Reset & kick animation to show complete animation cycles
521              * when charger disconnected.
522              */
523             timer_shutdown =
524                     property_get_int32(UNPLUGGED_SHUTDOWN_TIME_PROP, UNPLUGGED_SHUTDOWN_TIME);
525             next_screen_transition_ = now - 1;
526             reset_animation(&batt_anim_);
527             kick_animation(&batt_anim_);
528             next_pwr_check_ = now + timer_shutdown;
529             LOGW("[%" PRId64 "] device unplugged: shutting down in %" PRId64 " (@ %" PRId64 ")\n",
530                  now, (int64_t)timer_shutdown, next_pwr_check_);
531         } else if (now >= next_pwr_check_) {
532             LOGW("[%" PRId64 "] shutting down\n", now);
533             reboot(RB_POWER_OFF);
534         } else {
535             /* otherwise we already have a shutdown timer scheduled */
536         }
537     } else {
538         /* online supply present, reset shutdown timer if set */
539         if (next_pwr_check_ != -1) {
540             /* Reset next_screen_transition_ to update screen immediately.
541              * Reset & kick animation to show complete animation cycles
542              * when charger connected again.
543              */
544             request_suspend(false);
545             next_screen_transition_ = now - 1;
546             reset_animation(&batt_anim_);
547             kick_animation(&batt_anim_);
548             LOGW("[%" PRId64 "] device plugged in: shutdown cancelled\n", now);
549         }
550         next_pwr_check_ = -1;
551     }
552 }
553 
Heartbeat()554 void Charger::Heartbeat() {
555     // charger* charger = &charger_state;
556     int64_t now = curr_time_ms();
557 
558     HandleInputState(now);
559     HandlePowerSupplyState(now);
560 
561     /* do screen update last in case any of the above want to start
562      * screen transitions (animations, etc)
563      */
564     UpdateScreenState(now);
565 }
566 
OnHealthInfoChanged(const HealthInfo_2_1 & health_info)567 void Charger::OnHealthInfoChanged(const HealthInfo_2_1& health_info) {
568     set_charger_online(health_info);
569 
570     if (!have_battery_state_) {
571         have_battery_state_ = true;
572         next_screen_transition_ = curr_time_ms() - 1;
573         request_suspend(false);
574         reset_animation(&batt_anim_);
575         kick_animation(&batt_anim_);
576     }
577     health_info_ = health_info.legacy.legacy;
578 
579     AdjustWakealarmPeriods(charger_online());
580 }
581 
PrepareToWait(void)582 int Charger::PrepareToWait(void) {
583     int64_t now = curr_time_ms();
584     int64_t next_event = INT64_MAX;
585     int64_t timeout;
586 
587     LOGV("[%" PRId64 "] next screen: %" PRId64 " next key: %" PRId64 " next pwr: %" PRId64 "\n",
588          now, next_screen_transition_, next_key_check_, next_pwr_check_);
589 
590     if (next_screen_transition_ != -1) next_event = next_screen_transition_;
591     if (next_key_check_ != -1 && next_key_check_ < next_event) next_event = next_key_check_;
592     if (next_pwr_check_ != -1 && next_pwr_check_ < next_event) next_event = next_pwr_check_;
593 
594     if (next_event != -1 && next_event != INT64_MAX)
595         timeout = max(0, next_event - now);
596     else
597         timeout = -1;
598 
599     return (int)timeout;
600 }
601 
InputCallback(int fd,unsigned int epevents)602 int Charger::InputCallback(int fd, unsigned int epevents) {
603     input_event ev;
604     int ret;
605 
606     ret = ev_get_input(fd, epevents, &ev);
607     if (ret) return -1;
608     UpdateInputState(&ev);
609     return 0;
610 }
611 
charger_event_handler(HealthLoop *,uint32_t)612 static void charger_event_handler(HealthLoop* /*charger_loop*/, uint32_t /*epevents*/) {
613     int ret;
614 
615     ret = ev_wait(-1);
616     if (!ret) ev_dispatch();
617 }
618 
InitAnimation()619 void Charger::InitAnimation() {
620     bool parse_success;
621 
622     std::string content;
623     if (base::ReadFileToString(product_animation_desc_path, &content)) {
624         parse_success = parse_animation_desc(content, &batt_anim_);
625         batt_anim_.set_resource_root(product_animation_root);
626     } else if (base::ReadFileToString(animation_desc_path, &content)) {
627         parse_success = parse_animation_desc(content, &batt_anim_);
628     } else {
629         LOGW("Could not open animation description at %s\n", animation_desc_path);
630         parse_success = false;
631     }
632 
633     if (!parse_success) {
634         LOGW("Could not parse animation description. Using default animation.\n");
635         batt_anim_ = BASE_ANIMATION;
636         batt_anim_.animation_file.assign("charger/battery_scale");
637         InitDefaultAnimationFrames();
638         batt_anim_.frames = owned_frames_.data();
639         batt_anim_.num_frames = owned_frames_.size();
640     }
641     if (batt_anim_.fail_file.empty()) {
642         batt_anim_.fail_file.assign("charger/battery_fail");
643     }
644 
645     LOGV("Animation Description:\n");
646     LOGV("  animation: %d %d '%s' (%d)\n", batt_anim_.num_cycles, batt_anim_.first_frame_repeats,
647          batt_anim_.animation_file.c_str(), batt_anim_.num_frames);
648     LOGV("  fail_file: '%s'\n", batt_anim_.fail_file.c_str());
649     LOGV("  clock: %d %d %d %d %d %d '%s'\n", batt_anim_.text_clock.pos_x,
650          batt_anim_.text_clock.pos_y, batt_anim_.text_clock.color_r, batt_anim_.text_clock.color_g,
651          batt_anim_.text_clock.color_b, batt_anim_.text_clock.color_a,
652          batt_anim_.text_clock.font_file.c_str());
653     LOGV("  percent: %d %d %d %d %d %d '%s'\n", batt_anim_.text_percent.pos_x,
654          batt_anim_.text_percent.pos_y, batt_anim_.text_percent.color_r,
655          batt_anim_.text_percent.color_g, batt_anim_.text_percent.color_b,
656          batt_anim_.text_percent.color_a, batt_anim_.text_percent.font_file.c_str());
657     for (int i = 0; i < batt_anim_.num_frames; i++) {
658         LOGV("  frame %.2d: %d %d %d\n", i, batt_anim_.frames[i].disp_time,
659              batt_anim_.frames[i].min_level, batt_anim_.frames[i].max_level);
660     }
661 }
662 
Init(struct healthd_config * config)663 void Charger::Init(struct healthd_config* config) {
664     int ret;
665     int i;
666     int epollfd;
667 
668     dump_last_kmsg();
669 
670     LOGW("--------------- STARTING CHARGER MODE ---------------\n");
671 
672     ret = ev_init(
673             std::bind(&Charger::InputCallback, this, std::placeholders::_1, std::placeholders::_2));
674     if (!ret) {
675         epollfd = ev_get_epollfd();
676         RegisterEvent(epollfd, &charger_event_handler, EVENT_WAKEUP_FD);
677     }
678 
679     InitAnimation();
680 
681     ret = res_create_display_surface(batt_anim_.fail_file.c_str(), &surf_unknown_);
682     if (ret < 0) {
683         LOGE("Cannot load custom battery_fail image. Reverting to built in: %d\n", ret);
684         ret = res_create_display_surface("charger/battery_fail", &surf_unknown_);
685         if (ret < 0) {
686             LOGE("Cannot load built in battery_fail image\n");
687             surf_unknown_ = NULL;
688         }
689     }
690 
691     GRSurface** scale_frames;
692     int scale_count;
693     int scale_fps;  // Not in use (charger/battery_scale doesn't have FPS text
694                     // chunk). We are using hard-coded frame.disp_time instead.
695     ret = res_create_multi_display_surface(batt_anim_.animation_file.c_str(), &scale_count,
696                                            &scale_fps, &scale_frames);
697     if (ret < 0) {
698         LOGE("Cannot load battery_scale image\n");
699         batt_anim_.num_frames = 0;
700         batt_anim_.num_cycles = 1;
701     } else if (scale_count != batt_anim_.num_frames) {
702         LOGE("battery_scale image has unexpected frame count (%d, expected %d)\n", scale_count,
703              batt_anim_.num_frames);
704         batt_anim_.num_frames = 0;
705         batt_anim_.num_cycles = 1;
706     } else {
707         for (i = 0; i < batt_anim_.num_frames; i++) {
708             batt_anim_.frames[i].surface = scale_frames[i];
709         }
710     }
711     ev_sync_key_state(std::bind(&Charger::SetKeyCallback, this, std::placeholders::_1,
712                                 std::placeholders::_2));
713 
714     next_screen_transition_ = -1;
715     next_key_check_ = -1;
716     next_pwr_check_ = -1;
717     wait_batt_level_timestamp_ = 0;
718 
719     // Retrieve healthd_config from the existing health HAL.
720     HalHealthLoop::Init(config);
721 
722     boot_min_cap_ = config->boot_min_cap;
723 }
724 
725 }  // namespace android
726 
healthd_charger_main(int argc,char ** argv)727 int healthd_charger_main(int argc, char** argv) {
728     int ch;
729 
730     while ((ch = getopt(argc, argv, "cr")) != -1) {
731         switch (ch) {
732             case 'c':
733                 // -c is now a noop
734                 break;
735             case 'r':
736                 // -r is now a noop
737                 break;
738             case '?':
739             default:
740                 LOGE("Unrecognized charger option: %c\n", optopt);
741                 exit(1);
742         }
743     }
744 
745     Charger charger(GetHealthServiceOrDefault());
746     return charger.StartLoop();
747 }
748