• 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 (3 * 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) {
324         std::optional<bool> out_screen_on = configuration_->ChargerShouldKeepScreenOn();
325         if (out_screen_on.has_value()) {
326             if (!*out_screen_on) {
327                 LOGV("[%" PRId64 "] leave screen off\n", now);
328                 batt_anim_.run = false;
329                 next_screen_transition_ = -1;
330                 if (configuration_->ChargerIsOnline()) {
331                     RequestEnableSuspend();
332                 }
333                 return;
334             }
335         }
336 
337         healthd_draw_ = HealthdDraw::Create(&batt_anim_);
338         if (healthd_draw_ == nullptr) return;
339 
340 #if !defined(__ANDROID_VNDK__)
341         if (android::sysprop::ChargerProperties::disable_init_blank().value_or(false)) {
342             healthd_draw_->blank_screen(true, static_cast<int>(drm_));
343             screen_blanked_ = true;
344         }
345 #endif
346     }
347 
348     /* animation is over, blank screen and leave */
349     if (batt_anim_.num_cycles > 0 && batt_anim_.cur_cycle == batt_anim_.num_cycles) {
350         reset_animation(&batt_anim_);
351         next_screen_transition_ = -1;
352         healthd_draw_->blank_screen(true, static_cast<int>(drm_));
353         if (healthd_draw_->has_multiple_connectors()) {
354             BlankSecScreen();
355         }
356         screen_blanked_ = true;
357         LOGV("[%" PRId64 "] animation done\n", now);
358         if (configuration_->ChargerIsOnline()) {
359             RequestEnableSuspend();
360         }
361         return;
362     }
363 
364     disp_time = batt_anim_.frames[batt_anim_.cur_frame].disp_time;
365 
366     /* turn off all screen */
367     if (screen_switch_ == SCREEN_SWITCH_ENABLE) {
368         healthd_draw_->blank_screen(true, 0 /* drm */);
369         healthd_draw_->blank_screen(true, 1 /* drm */);
370         healthd_draw_->rotate_screen(static_cast<int>(drm_));
371         screen_blanked_ = true;
372         screen_switch_ = SCREEN_SWITCH_DISABLE;
373     }
374 
375     if (screen_blanked_) {
376         healthd_draw_->blank_screen(false, static_cast<int>(drm_));
377         screen_blanked_ = false;
378     }
379 
380     /* animation starting, set up the animation */
381     if (batt_anim_.cur_frame == 0) {
382         LOGV("[%" PRId64 "] animation starting\n", now);
383         batt_anim_.cur_level = health_info_.battery_level;
384         batt_anim_.cur_status = (int)health_info_.battery_status;
385         if (health_info_.battery_level >= 0 && batt_anim_.num_frames != 0) {
386             /* find first frame given current battery level */
387             for (int i = 0; i < batt_anim_.num_frames; i++) {
388                 if (batt_anim_.cur_level >= batt_anim_.frames[i].min_level &&
389                     batt_anim_.cur_level <= batt_anim_.frames[i].max_level) {
390                     batt_anim_.cur_frame = i;
391                     break;
392                 }
393             }
394 
395             if (configuration_->ChargerIsOnline()) {
396                 // repeat the first frame first_frame_repeats times
397                 disp_time = batt_anim_.frames[batt_anim_.cur_frame].disp_time *
398                             batt_anim_.first_frame_repeats;
399             } else {
400                 disp_time = UNPLUGGED_DISPLAY_TIME / batt_anim_.num_cycles;
401             }
402 
403             LOGV("cur_frame=%d disp_time=%d\n", batt_anim_.cur_frame, disp_time);
404         }
405     }
406 
407     /* draw the new frame (@ cur_frame) */
408     healthd_draw_->redraw_screen(&batt_anim_, surf_unknown_);
409 
410     /* if we don't have anim frames, we only have one image, so just bump
411      * the cycle counter and exit
412      */
413     if (batt_anim_.num_frames == 0 || batt_anim_.cur_level < 0) {
414         LOGW("[%" PRId64 "] animation missing or unknown battery status\n", now);
415         next_screen_transition_ = now + BATTERY_UNKNOWN_TIME;
416         batt_anim_.cur_cycle++;
417         return;
418     }
419 
420     /* schedule next screen transition */
421     next_screen_transition_ = curr_time_ms() + disp_time;
422 
423     /* advance frame cntr to the next valid frame only if we are charging
424      * if necessary, advance cycle cntr, and reset frame cntr
425      */
426     if (configuration_->ChargerIsOnline()) {
427         batt_anim_.cur_frame++;
428 
429         while (batt_anim_.cur_frame < batt_anim_.num_frames &&
430                (batt_anim_.cur_level < batt_anim_.frames[batt_anim_.cur_frame].min_level ||
431                 batt_anim_.cur_level > batt_anim_.frames[batt_anim_.cur_frame].max_level)) {
432             batt_anim_.cur_frame++;
433         }
434         if (batt_anim_.cur_frame >= batt_anim_.num_frames) {
435             batt_anim_.cur_cycle++;
436             batt_anim_.cur_frame = 0;
437 
438             /* don't reset the cycle counter, since we use that as a signal
439              * in a test above to check if animation is over
440              */
441         }
442     } else {
443         /* Stop animating if we're not charging.
444          * If we stop it immediately instead of going through this loop, then
445          * the animation would stop somewhere in the middle.
446          */
447         batt_anim_.cur_frame = 0;
448         batt_anim_.cur_cycle++;
449     }
450 }
451 
SetKeyCallback(int code,int value)452 int Charger::SetKeyCallback(int code, int value) {
453     int64_t now = curr_time_ms();
454     int down = !!value;
455 
456     if (code > KEY_MAX) return -1;
457 
458     /* ignore events that don't modify our state */
459     if (keys_[code].down == down) return 0;
460 
461     /* only record the down even timestamp, as the amount
462      * of time the key spent not being pressed is not useful */
463     if (down) keys_[code].timestamp = now;
464     keys_[code].down = down;
465     keys_[code].pending = true;
466     if (down) {
467         LOGV("[%" PRId64 "] key[%d] down\n", now, code);
468     } else {
469         int64_t duration = now - keys_[code].timestamp;
470         int64_t secs = duration / 1000;
471         int64_t msecs = duration - secs * 1000;
472         LOGV("[%" PRId64 "] key[%d] up (was down for %" PRId64 ".%" PRId64 "sec)\n", now, code,
473              secs, msecs);
474     }
475 
476     return 0;
477 }
478 
SetSwCallback(int code,int value)479 int Charger::SetSwCallback(int code, int value) {
480     if (code > SW_MAX) return -1;
481     if (code == SW_LID) {
482         if ((screen_switch_ == SCREEN_SWITCH_DEFAULT) || ((value != 0) && (drm_ == DRM_INNER)) ||
483             ((value == 0) && (drm_ == DRM_OUTER))) {
484             screen_switch_ = SCREEN_SWITCH_ENABLE;
485             drm_ = (value != 0) ? DRM_OUTER : DRM_INNER;
486             keys_[code].pending = true;
487         }
488     }
489 
490     return 0;
491 }
492 
UpdateInputState(input_event * ev)493 void Charger::UpdateInputState(input_event* ev) {
494     if (ev->type == EV_SW && ev->code == SW_LID) {
495         SetSwCallback(ev->code, ev->value);
496         return;
497     }
498 
499     if (ev->type != EV_KEY) return;
500     SetKeyCallback(ev->code, ev->value);
501 }
502 
SetNextKeyCheck(key_state * key,int64_t timeout)503 void Charger::SetNextKeyCheck(key_state* key, int64_t timeout) {
504     int64_t then = key->timestamp + timeout;
505 
506     if (next_key_check_ == -1 || then < next_key_check_) next_key_check_ = then;
507 }
508 
ProcessKey(int code,int64_t now)509 void Charger::ProcessKey(int code, int64_t now) {
510     key_state* key = &keys_[code];
511 
512     if (code == KEY_POWER) {
513         if (key->down) {
514             int64_t reboot_timeout = key->timestamp + POWER_ON_KEY_TIME;
515             if (now >= reboot_timeout) {
516                 /* We do not currently support booting from charger mode on
517                    all devices. Check the property and continue booting or reboot
518                    accordingly. */
519                 if (property_get_bool("ro.enable_boot_charger_mode", false)) {
520                     LOGW("[%" PRId64 "] booting from charger mode\n", now);
521                     property_set("sys.boot_from_charger_mode", "1");
522                 } else {
523                     if (batt_anim_.cur_level >= boot_min_cap_) {
524                         LOGW("[%" PRId64 "] rebooting\n", now);
525                         reboot(RB_AUTOBOOT);
526                     } else {
527                         LOGV("[%" PRId64
528                              "] ignore power-button press, battery level "
529                              "less than minimum\n",
530                              now);
531                     }
532                 }
533             } else {
534                 /* if the key is pressed but timeout hasn't expired,
535                  * make sure we wake up at the right-ish time to check
536                  */
537                 SetNextKeyCheck(key, POWER_ON_KEY_TIME);
538 
539                 /* Turn on the display and kick animation on power-key press
540                  * rather than on key release
541                  */
542                 kick_animation(&batt_anim_);
543                 RequestDisableSuspend();
544             }
545         } else {
546             /* if the power key got released, force screen state cycle */
547             if (key->pending) {
548                 kick_animation(&batt_anim_);
549                 RequestDisableSuspend();
550             }
551         }
552     }
553 
554     key->pending = false;
555 }
556 
ProcessHallSensor(int code)557 void Charger::ProcessHallSensor(int code) {
558     key_state* key = &keys_[code];
559 
560     if (code == SW_LID) {
561         if (key->pending) {
562             reset_animation(&batt_anim_);
563             kick_animation(&batt_anim_);
564             RequestDisableSuspend();
565         }
566     }
567 
568     key->pending = false;
569 }
570 
HandleInputState(int64_t now)571 void Charger::HandleInputState(int64_t now) {
572     ProcessKey(KEY_POWER, now);
573 
574     if (next_key_check_ != -1 && now > next_key_check_) next_key_check_ = -1;
575 
576     ProcessHallSensor(SW_LID);
577 }
578 
HandlePowerSupplyState(int64_t now)579 void Charger::HandlePowerSupplyState(int64_t now) {
580     int timer_shutdown = UNPLUGGED_SHUTDOWN_TIME;
581     if (!have_battery_state_) return;
582 
583     if (!configuration_->ChargerIsOnline()) {
584         RequestDisableSuspend();
585         if (next_pwr_check_ == -1) {
586             /* Last cycle would have stopped at the extreme top of battery-icon
587              * Need to show the correct level corresponding to capacity.
588              *
589              * Reset next_screen_transition_ to update screen immediately.
590              * Reset & kick animation to show complete animation cycles
591              * when charger disconnected.
592              */
593             timer_shutdown =
594                     property_get_int32(UNPLUGGED_SHUTDOWN_TIME_PROP, UNPLUGGED_SHUTDOWN_TIME);
595             next_screen_transition_ = now - 1;
596             reset_animation(&batt_anim_);
597             kick_animation(&batt_anim_);
598             next_pwr_check_ = now + timer_shutdown;
599             LOGW("[%" PRId64 "] device unplugged: shutting down in %" PRId64 " (@ %" PRId64 ")\n",
600                  now, (int64_t)timer_shutdown, next_pwr_check_);
601         } else if (now >= next_pwr_check_) {
602             LOGW("[%" PRId64 "] shutting down\n", now);
603             reboot(RB_POWER_OFF);
604         } else {
605             /* otherwise we already have a shutdown timer scheduled */
606         }
607     } else {
608         /* online supply present, reset shutdown timer if set */
609         if (next_pwr_check_ != -1) {
610             /* Reset next_screen_transition_ to update screen immediately.
611              * Reset & kick animation to show complete animation cycles
612              * when charger connected again.
613              */
614             RequestDisableSuspend();
615             next_screen_transition_ = now - 1;
616             reset_animation(&batt_anim_);
617             kick_animation(&batt_anim_);
618             LOGW("[%" PRId64 "] device plugged in: shutdown cancelled\n", now);
619         }
620         next_pwr_check_ = -1;
621     }
622 }
623 
OnHeartbeat()624 void Charger::OnHeartbeat() {
625     // charger* charger = &charger_state;
626     int64_t now = curr_time_ms();
627 
628     HandleInputState(now);
629     HandlePowerSupplyState(now);
630 
631     /* do screen update last in case any of the above want to start
632      * screen transitions (animations, etc)
633      */
634     UpdateScreenState(now);
635 }
636 
OnHealthInfoChanged(const ChargerHealthInfo & health_info)637 void Charger::OnHealthInfoChanged(const ChargerHealthInfo& health_info) {
638     if (!have_battery_state_) {
639         have_battery_state_ = true;
640         next_screen_transition_ = curr_time_ms() - 1;
641         RequestDisableSuspend();
642         reset_animation(&batt_anim_);
643         kick_animation(&batt_anim_);
644     }
645     health_info_ = health_info;
646 }
647 
OnPrepareToWait(void)648 int Charger::OnPrepareToWait(void) {
649     int64_t now = curr_time_ms();
650     int64_t next_event = INT64_MAX;
651     int64_t timeout;
652 
653     LOGV("[%" PRId64 "] next screen: %" PRId64 " next key: %" PRId64 " next pwr: %" PRId64 "\n",
654          now, next_screen_transition_, next_key_check_, next_pwr_check_);
655 
656     if (next_screen_transition_ != -1) next_event = next_screen_transition_;
657     if (next_key_check_ != -1 && next_key_check_ < next_event) next_event = next_key_check_;
658     if (next_pwr_check_ != -1 && next_pwr_check_ < next_event) next_event = next_pwr_check_;
659 
660     if (next_event != -1 && next_event != INT64_MAX)
661         timeout = max(0, next_event - now);
662     else
663         timeout = -1;
664 
665     return (int)timeout;
666 }
667 
InputCallback(int fd,unsigned int epevents)668 int Charger::InputCallback(int fd, unsigned int epevents) {
669     input_event ev;
670     int ret;
671 
672     ret = ev_get_input(fd, epevents, &ev);
673     if (ret) return -1;
674     UpdateInputState(&ev);
675     return 0;
676 }
677 
charger_event_handler(HealthLoop *,uint32_t)678 static void charger_event_handler(HealthLoop* /*charger_loop*/, uint32_t /*epevents*/) {
679     int ret;
680 
681     ret = ev_wait(-1);
682     if (!ret) ev_dispatch();
683 }
684 
InitAnimation()685 void Charger::InitAnimation() {
686     bool parse_success;
687 
688     std::string content;
689 
690 #if defined(__ANDROID_VNDK__)
691     if (base::ReadFileToString(vendor_animation_desc_path, &content)) {
692         parse_success = parse_animation_desc(content, &batt_anim_);
693         batt_anim_.set_resource_root(vendor_animation_root);
694     } else {
695         LOGW("Could not open animation description at %s\n", vendor_animation_desc_path);
696         parse_success = false;
697     }
698 #else
699     if (base::ReadFileToString(product_animation_desc_path, &content)) {
700         parse_success = parse_animation_desc(content, &batt_anim_);
701         batt_anim_.set_resource_root(product_animation_root);
702     } else if (base::ReadFileToString(animation_desc_path, &content)) {
703         parse_success = parse_animation_desc(content, &batt_anim_);
704         // Fallback resources always exist in system_animation_root. On legacy devices with an old
705         // ramdisk image, resources may be overridden under root. For example,
706         // /res/images/charger/battery_fail.png may not be the same as
707         // system/core/healthd/images/battery_fail.png in the source tree, but is a device-specific
708         // image. Hence, load from /res, and fall back to /system/etc/res.
709         batt_anim_.set_resource_root(legacy_animation_root, system_animation_root);
710     } else {
711         LOGW("Could not open animation description at %s\n", animation_desc_path);
712         parse_success = false;
713     }
714 #endif
715 
716 #if defined(__ANDROID_VNDK__)
717     auto default_animation_root = vendor_default_animation_root;
718 #else
719     auto default_animation_root = system_animation_root;
720 #endif
721 
722     if (!parse_success) {
723         LOGW("Could not parse animation description. "
724              "Using default animation with resources at %s\n",
725              default_animation_root);
726         batt_anim_ = BASE_ANIMATION;
727         batt_anim_.animation_file.assign(default_animation_root + "charger/battery_scale.png"s);
728         InitDefaultAnimationFrames();
729         batt_anim_.frames = owned_frames_.data();
730         batt_anim_.num_frames = owned_frames_.size();
731     }
732     if (batt_anim_.fail_file.empty()) {
733         batt_anim_.fail_file.assign(default_animation_root + "charger/battery_fail.png"s);
734     }
735 
736     LOGV("Animation Description:\n");
737     LOGV("  animation: %d %d '%s' (%d)\n", batt_anim_.num_cycles, batt_anim_.first_frame_repeats,
738          batt_anim_.animation_file.c_str(), batt_anim_.num_frames);
739     LOGV("  fail_file: '%s'\n", batt_anim_.fail_file.c_str());
740     LOGV("  clock: %d %d %d %d %d %d '%s'\n", batt_anim_.text_clock.pos_x,
741          batt_anim_.text_clock.pos_y, batt_anim_.text_clock.color_r, batt_anim_.text_clock.color_g,
742          batt_anim_.text_clock.color_b, batt_anim_.text_clock.color_a,
743          batt_anim_.text_clock.font_file.c_str());
744     LOGV("  percent: %d %d %d %d %d %d '%s'\n", batt_anim_.text_percent.pos_x,
745          batt_anim_.text_percent.pos_y, batt_anim_.text_percent.color_r,
746          batt_anim_.text_percent.color_g, batt_anim_.text_percent.color_b,
747          batt_anim_.text_percent.color_a, batt_anim_.text_percent.font_file.c_str());
748     for (int i = 0; i < batt_anim_.num_frames; i++) {
749         LOGV("  frame %.2d: %d %d %d\n", i, batt_anim_.frames[i].disp_time,
750              batt_anim_.frames[i].min_level, batt_anim_.frames[i].max_level);
751     }
752 }
753 
OnInit(struct healthd_config * config)754 void Charger::OnInit(struct healthd_config* config) {
755     int ret;
756     int i;
757     int epollfd;
758 
759     dump_last_kmsg();
760 
761     LOGW("--------------- STARTING CHARGER MODE ---------------\n");
762 
763     ret = ev_init(
764             std::bind(&Charger::InputCallback, this, std::placeholders::_1, std::placeholders::_2));
765     if (!ret) {
766         epollfd = ev_get_epollfd();
767         configuration_->ChargerRegisterEvent(epollfd, &charger_event_handler, EVENT_WAKEUP_FD);
768     }
769 
770     InitAnimation();
771 
772     ret = CreateDisplaySurface(batt_anim_.fail_file, &surf_unknown_);
773     if (ret < 0) {
774 #if !defined(__ANDROID_VNDK__)
775         LOGE("Cannot load custom battery_fail image. Reverting to built in: %d\n", ret);
776         ret = CreateDisplaySurface((system_animation_root + "charger/battery_fail.png"s).c_str(),
777                                    &surf_unknown_);
778 #endif
779         if (ret < 0) {
780             LOGE("Cannot load built in battery_fail image\n");
781             surf_unknown_ = NULL;
782         }
783     }
784 
785     GRSurface** scale_frames;
786     int scale_count;
787     int scale_fps;  // Not in use (charger/battery_scale doesn't have FPS text
788                     // chunk). We are using hard-coded frame.disp_time instead.
789     ret = CreateMultiDisplaySurface(batt_anim_.animation_file, &scale_count, &scale_fps,
790                                     &scale_frames);
791     if (ret < 0) {
792         LOGE("Cannot load battery_scale image\n");
793         batt_anim_.num_frames = 0;
794         batt_anim_.num_cycles = 1;
795     } else if (scale_count != batt_anim_.num_frames) {
796         LOGE("battery_scale image has unexpected frame count (%d, expected %d)\n", scale_count,
797              batt_anim_.num_frames);
798         batt_anim_.num_frames = 0;
799         batt_anim_.num_cycles = 1;
800     } else {
801         for (i = 0; i < batt_anim_.num_frames; i++) {
802             batt_anim_.frames[i].surface = scale_frames[i];
803         }
804     }
805     drm_ = DRM_INNER;
806     screen_switch_ = SCREEN_SWITCH_DEFAULT;
807     ev_sync_key_state(std::bind(&Charger::SetKeyCallback, this, std::placeholders::_1,
808                                 std::placeholders::_2));
809 
810     (void)ev_sync_sw_state(
811             std::bind(&Charger::SetSwCallback, this, std::placeholders::_1, std::placeholders::_2));
812 
813     next_screen_transition_ = -1;
814     next_key_check_ = -1;
815     next_pwr_check_ = -1;
816     wait_batt_level_timestamp_ = 0;
817 
818     // Retrieve healthd_config from the existing health HAL.
819     configuration_->ChargerInitConfig(config);
820 
821     boot_min_cap_ = config->boot_min_cap;
822 }
823 
CreateDisplaySurface(const std::string & name,GRSurface ** surface)824 int Charger::CreateDisplaySurface(const std::string& name, GRSurface** surface) {
825     return res_create_display_surface(name.c_str(), surface);
826 }
827 
CreateMultiDisplaySurface(const std::string & name,int * frames,int * fps,GRSurface *** surface)828 int Charger::CreateMultiDisplaySurface(const std::string& name, int* frames, int* fps,
829                                        GRSurface*** surface) {
830     return res_create_multi_display_surface(name.c_str(), frames, fps, surface);
831 }
832 
set_resource_root_for(const std::string & root,const std::string & backup_root,std::string * value)833 void set_resource_root_for(const std::string& root, const std::string& backup_root,
834                            std::string* value) {
835     if (value->empty()) {
836         return;
837     }
838 
839     std::string new_value = root + *value + ".png";
840     // If |backup_root| is provided, additionally check whether the file under |root| is
841     // accessible or not. If not accessible, fallback to file under |backup_root|.
842     if (!backup_root.empty() && access(new_value.data(), F_OK) == -1) {
843         new_value = backup_root + *value + ".png";
844     }
845 
846     *value = new_value;
847 }
848 
set_resource_root(const std::string & root,const std::string & backup_root)849 void animation::set_resource_root(const std::string& root, const std::string& backup_root) {
850     CHECK(android::base::StartsWith(root, "/") && android::base::EndsWith(root, "/"))
851             << "animation root " << root << " must start and end with /";
852     CHECK(backup_root.empty() || (android::base::StartsWith(backup_root, "/") &&
853                                   android::base::EndsWith(backup_root, "/")))
854             << "animation backup root " << backup_root << " must start and end with /";
855     set_resource_root_for(root, backup_root, &animation_file);
856     set_resource_root_for(root, backup_root, &fail_file);
857     set_resource_root_for(root, backup_root, &text_clock.font_file);
858     set_resource_root_for(root, backup_root, &text_percent.font_file);
859 }
860 
861 }  // namespace android
862