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