BatteryMonitor.cpp revision d5fe6675a73c3a831d0c4e41343ee86772633db8
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "healthd"
18
19#include "healthd.h"
20#include "BatteryMonitor.h"
21
22#include <dirent.h>
23#include <errno.h>
24#include <fcntl.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <unistd.h>
28#include <batteryservice/BatteryService.h>
29#include <cutils/klog.h>
30#include <cutils/properties.h>
31#include <sys/types.h>
32#include <utils/Errors.h>
33#include <utils/String8.h>
34#include <utils/Vector.h>
35
36#define POWER_SUPPLY_SUBSYSTEM "power_supply"
37#define POWER_SUPPLY_SYSFS_PATH "/sys/class/" POWER_SUPPLY_SUBSYSTEM
38#define FAKE_BATTERY_CAPACITY 42
39#define FAKE_BATTERY_TEMPERATURE 424
40
41namespace android {
42
43struct sysfsStringEnumMap {
44    const char* s;
45    int val;
46};
47
48static int mapSysfsString(const char* str,
49                          struct sysfsStringEnumMap map[]) {
50    for (int i = 0; map[i].s; i++)
51        if (!strcmp(str, map[i].s))
52            return map[i].val;
53
54    return -1;
55}
56
57int BatteryMonitor::getBatteryStatus(const char* status) {
58    int ret;
59    struct sysfsStringEnumMap batteryStatusMap[] = {
60        { "Unknown", BATTERY_STATUS_UNKNOWN },
61        { "Charging", BATTERY_STATUS_CHARGING },
62        { "Discharging", BATTERY_STATUS_DISCHARGING },
63        { "Not charging", BATTERY_STATUS_NOT_CHARGING },
64        { "Full", BATTERY_STATUS_FULL },
65        { NULL, 0 },
66    };
67
68    ret = mapSysfsString(status, batteryStatusMap);
69    if (ret < 0) {
70        KLOG_WARNING(LOG_TAG, "Unknown battery status '%s'\n", status);
71        ret = BATTERY_STATUS_UNKNOWN;
72    }
73
74    return ret;
75}
76
77int BatteryMonitor::getBatteryHealth(const char* status) {
78    int ret;
79    struct sysfsStringEnumMap batteryHealthMap[] = {
80        { "Unknown", BATTERY_HEALTH_UNKNOWN },
81        { "Good", BATTERY_HEALTH_GOOD },
82        { "Overheat", BATTERY_HEALTH_OVERHEAT },
83        { "Dead", BATTERY_HEALTH_DEAD },
84        { "Over voltage", BATTERY_HEALTH_OVER_VOLTAGE },
85        { "Unspecified failure", BATTERY_HEALTH_UNSPECIFIED_FAILURE },
86        { "Cold", BATTERY_HEALTH_COLD },
87        { NULL, 0 },
88    };
89
90    ret = mapSysfsString(status, batteryHealthMap);
91    if (ret < 0) {
92        KLOG_WARNING(LOG_TAG, "Unknown battery health '%s'\n", status);
93        ret = BATTERY_HEALTH_UNKNOWN;
94    }
95
96    return ret;
97}
98
99int BatteryMonitor::readFromFile(const String8& path, char* buf, size_t size) {
100    char *cp = NULL;
101
102    if (path.isEmpty())
103        return -1;
104    int fd = open(path.string(), O_RDONLY, 0);
105    if (fd == -1) {
106        KLOG_ERROR(LOG_TAG, "Could not open '%s'\n", path.string());
107        return -1;
108    }
109
110    ssize_t count = TEMP_FAILURE_RETRY(read(fd, buf, size));
111    if (count > 0)
112            cp = (char *)memrchr(buf, '\n', count);
113
114    if (cp)
115        *cp = '\0';
116    else
117        buf[0] = '\0';
118
119    close(fd);
120    return count;
121}
122
123BatteryMonitor::PowerSupplyType BatteryMonitor::readPowerSupplyType(const String8& path) {
124    const int SIZE = 128;
125    char buf[SIZE];
126    int length = readFromFile(path, buf, SIZE);
127    BatteryMonitor::PowerSupplyType ret;
128    struct sysfsStringEnumMap supplyTypeMap[] = {
129            { "Unknown", ANDROID_POWER_SUPPLY_TYPE_UNKNOWN },
130            { "Battery", ANDROID_POWER_SUPPLY_TYPE_BATTERY },
131            { "UPS", ANDROID_POWER_SUPPLY_TYPE_AC },
132            { "Mains", ANDROID_POWER_SUPPLY_TYPE_AC },
133            { "USB", ANDROID_POWER_SUPPLY_TYPE_USB },
134            { "USB_DCP", ANDROID_POWER_SUPPLY_TYPE_AC },
135            { "USB_CDP", ANDROID_POWER_SUPPLY_TYPE_AC },
136            { "USB_ACA", ANDROID_POWER_SUPPLY_TYPE_AC },
137            { "Wireless", ANDROID_POWER_SUPPLY_TYPE_WIRELESS },
138            { NULL, 0 },
139    };
140
141    if (length <= 0)
142        return ANDROID_POWER_SUPPLY_TYPE_UNKNOWN;
143
144    ret = (BatteryMonitor::PowerSupplyType)mapSysfsString(buf, supplyTypeMap);
145    if (ret < 0)
146        ret = ANDROID_POWER_SUPPLY_TYPE_UNKNOWN;
147
148    return ret;
149}
150
151bool BatteryMonitor::getBooleanField(const String8& path) {
152    const int SIZE = 16;
153    char buf[SIZE];
154
155    bool value = false;
156    if (readFromFile(path, buf, SIZE) > 0) {
157        if (buf[0] != '0') {
158            value = true;
159        }
160    }
161
162    return value;
163}
164
165int BatteryMonitor::getIntField(const String8& path) {
166    const int SIZE = 128;
167    char buf[SIZE];
168
169    int value = 0;
170    if (readFromFile(path, buf, SIZE) > 0) {
171        value = strtol(buf, NULL, 0);
172    }
173    return value;
174}
175
176bool BatteryMonitor::update(void) {
177    bool logthis;
178
179    props.chargerAcOnline = false;
180    props.chargerUsbOnline = false;
181    props.chargerWirelessOnline = false;
182    props.batteryStatus = BATTERY_STATUS_UNKNOWN;
183    props.batteryHealth = BATTERY_HEALTH_UNKNOWN;
184    props.maxChargingCurrent = 0;
185
186    if (!mHealthdConfig->batteryPresentPath.isEmpty())
187        props.batteryPresent = getBooleanField(mHealthdConfig->batteryPresentPath);
188    else
189        props.batteryPresent = mBatteryDevicePresent;
190
191    props.batteryLevel = mBatteryFixedCapacity ?
192        mBatteryFixedCapacity :
193        getIntField(mHealthdConfig->batteryCapacityPath);
194    props.batteryVoltage = getIntField(mHealthdConfig->batteryVoltagePath) / 1000;
195
196    props.batteryTemperature = mBatteryFixedTemperature ?
197        mBatteryFixedTemperature :
198        getIntField(mHealthdConfig->batteryTemperaturePath);
199
200    const int SIZE = 128;
201    char buf[SIZE];
202    String8 btech;
203
204    if (readFromFile(mHealthdConfig->batteryStatusPath, buf, SIZE) > 0)
205        props.batteryStatus = getBatteryStatus(buf);
206
207    if (readFromFile(mHealthdConfig->batteryHealthPath, buf, SIZE) > 0)
208        props.batteryHealth = getBatteryHealth(buf);
209
210    if (readFromFile(mHealthdConfig->batteryTechnologyPath, buf, SIZE) > 0)
211        props.batteryTechnology = String8(buf);
212
213    unsigned int i;
214
215    for (i = 0; i < mChargerNames.size(); i++) {
216        String8 path;
217        path.appendFormat("%s/%s/online", POWER_SUPPLY_SYSFS_PATH,
218                          mChargerNames[i].string());
219
220        if (readFromFile(path, buf, SIZE) > 0) {
221            if (buf[0] != '0') {
222                path.clear();
223                path.appendFormat("%s/%s/type", POWER_SUPPLY_SYSFS_PATH,
224                                  mChargerNames[i].string());
225                switch(readPowerSupplyType(path)) {
226                case ANDROID_POWER_SUPPLY_TYPE_AC:
227                    props.chargerAcOnline = true;
228                    break;
229                case ANDROID_POWER_SUPPLY_TYPE_USB:
230                    props.chargerUsbOnline = true;
231                    break;
232                case ANDROID_POWER_SUPPLY_TYPE_WIRELESS:
233                    props.chargerWirelessOnline = true;
234                    break;
235                default:
236                    KLOG_WARNING(LOG_TAG, "%s: Unknown power supply type\n",
237                                 mChargerNames[i].string());
238                }
239                path.clear();
240                path.appendFormat("%s/%s/current_max", POWER_SUPPLY_SYSFS_PATH,
241                                  mChargerNames[i].string());
242                if (access(path.string(), R_OK) == 0) {
243                    int maxChargingCurrent = getIntField(path);
244                    if (props.maxChargingCurrent < maxChargingCurrent) {
245                        props.maxChargingCurrent = maxChargingCurrent;
246                    }
247                }
248            }
249        }
250    }
251
252    logthis = !healthd_board_battery_update(&props);
253
254    if (logthis) {
255        char dmesgline[256];
256
257        if (props.batteryPresent) {
258            snprintf(dmesgline, sizeof(dmesgline),
259                 "battery l=%d v=%d t=%s%d.%d h=%d st=%d",
260                 props.batteryLevel, props.batteryVoltage,
261                 props.batteryTemperature < 0 ? "-" : "",
262                 abs(props.batteryTemperature / 10),
263                 abs(props.batteryTemperature % 10), props.batteryHealth,
264                 props.batteryStatus);
265
266            if (!mHealthdConfig->batteryCurrentNowPath.isEmpty()) {
267                int c = getIntField(mHealthdConfig->batteryCurrentNowPath);
268                char b[20];
269
270                snprintf(b, sizeof(b), " c=%d", c / 1000);
271                strlcat(dmesgline, b, sizeof(dmesgline));
272            }
273        } else {
274            snprintf(dmesgline, sizeof(dmesgline),
275                 "battery none");
276        }
277
278        KLOG_WARNING(LOG_TAG, "%s chg=%s%s%s\n", dmesgline,
279                     props.chargerAcOnline ? "a" : "",
280                     props.chargerUsbOnline ? "u" : "",
281                     props.chargerWirelessOnline ? "w" : "");
282    }
283
284    healthd_mode_ops->battery_update(&props);
285    return props.chargerAcOnline | props.chargerUsbOnline |
286            props.chargerWirelessOnline;
287}
288
289status_t BatteryMonitor::getProperty(int id, struct BatteryProperty *val) {
290    status_t ret = BAD_VALUE;
291
292    val->valueInt64 = LONG_MIN;
293
294    switch(id) {
295    case BATTERY_PROP_CHARGE_COUNTER:
296        if (!mHealthdConfig->batteryChargeCounterPath.isEmpty()) {
297            val->valueInt64 =
298                getIntField(mHealthdConfig->batteryChargeCounterPath);
299            ret = NO_ERROR;
300        } else {
301            ret = NAME_NOT_FOUND;
302        }
303        break;
304
305    case BATTERY_PROP_CURRENT_NOW:
306        if (!mHealthdConfig->batteryCurrentNowPath.isEmpty()) {
307            val->valueInt64 =
308                getIntField(mHealthdConfig->batteryCurrentNowPath);
309            ret = NO_ERROR;
310        } else {
311            ret = NAME_NOT_FOUND;
312        }
313        break;
314
315    case BATTERY_PROP_CURRENT_AVG:
316        if (!mHealthdConfig->batteryCurrentAvgPath.isEmpty()) {
317            val->valueInt64 =
318                getIntField(mHealthdConfig->batteryCurrentAvgPath);
319            ret = NO_ERROR;
320        } else {
321            ret = NAME_NOT_FOUND;
322        }
323        break;
324
325    case BATTERY_PROP_CAPACITY:
326        if (!mHealthdConfig->batteryCapacityPath.isEmpty()) {
327            val->valueInt64 =
328                getIntField(mHealthdConfig->batteryCapacityPath);
329            ret = NO_ERROR;
330        } else {
331            ret = NAME_NOT_FOUND;
332        }
333        break;
334
335    case BATTERY_PROP_ENERGY_COUNTER:
336        if (mHealthdConfig->energyCounter) {
337            ret = mHealthdConfig->energyCounter(&val->valueInt64);
338        } else {
339            ret = NAME_NOT_FOUND;
340        }
341        break;
342
343    default:
344        break;
345    }
346
347    return ret;
348}
349
350void BatteryMonitor::dumpState(int fd) {
351    int v;
352    char vs[128];
353
354    snprintf(vs, sizeof(vs), "ac: %d usb: %d wireless: %d current_max: %d\n",
355             props.chargerAcOnline, props.chargerUsbOnline,
356             props.chargerWirelessOnline, props.maxChargingCurrent);
357    write(fd, vs, strlen(vs));
358    snprintf(vs, sizeof(vs), "status: %d health: %d present: %d\n",
359             props.batteryStatus, props.batteryHealth, props.batteryPresent);
360    write(fd, vs, strlen(vs));
361    snprintf(vs, sizeof(vs), "level: %d voltage: %d temp: %d\n",
362             props.batteryLevel, props.batteryVoltage,
363             props.batteryTemperature);
364    write(fd, vs, strlen(vs));
365
366    if (!mHealthdConfig->batteryCurrentNowPath.isEmpty()) {
367        v = getIntField(mHealthdConfig->batteryCurrentNowPath);
368        snprintf(vs, sizeof(vs), "current now: %d\n", v);
369        write(fd, vs, strlen(vs));
370    }
371
372    if (!mHealthdConfig->batteryCurrentAvgPath.isEmpty()) {
373        v = getIntField(mHealthdConfig->batteryCurrentAvgPath);
374        snprintf(vs, sizeof(vs), "current avg: %d\n", v);
375        write(fd, vs, strlen(vs));
376    }
377
378    if (!mHealthdConfig->batteryChargeCounterPath.isEmpty()) {
379        v = getIntField(mHealthdConfig->batteryChargeCounterPath);
380        snprintf(vs, sizeof(vs), "charge counter: %d\n", v);
381        write(fd, vs, strlen(vs));
382    }
383}
384
385void BatteryMonitor::init(struct healthd_config *hc) {
386    String8 path;
387    char pval[PROPERTY_VALUE_MAX];
388
389    mHealthdConfig = hc;
390    DIR* dir = opendir(POWER_SUPPLY_SYSFS_PATH);
391    if (dir == NULL) {
392        KLOG_ERROR(LOG_TAG, "Could not open %s\n", POWER_SUPPLY_SYSFS_PATH);
393    } else {
394        struct dirent* entry;
395
396        while ((entry = readdir(dir))) {
397            const char* name = entry->d_name;
398
399            if (!strcmp(name, ".") || !strcmp(name, ".."))
400                continue;
401
402            // Look for "type" file in each subdirectory
403            path.clear();
404            path.appendFormat("%s/%s/type", POWER_SUPPLY_SYSFS_PATH, name);
405            switch(readPowerSupplyType(path)) {
406            case ANDROID_POWER_SUPPLY_TYPE_AC:
407            case ANDROID_POWER_SUPPLY_TYPE_USB:
408            case ANDROID_POWER_SUPPLY_TYPE_WIRELESS:
409                path.clear();
410                path.appendFormat("%s/%s/online", POWER_SUPPLY_SYSFS_PATH, name);
411                if (access(path.string(), R_OK) == 0)
412                    mChargerNames.add(String8(name));
413                break;
414
415            case ANDROID_POWER_SUPPLY_TYPE_BATTERY:
416                mBatteryDevicePresent = true;
417
418                if (mHealthdConfig->batteryStatusPath.isEmpty()) {
419                    path.clear();
420                    path.appendFormat("%s/%s/status", POWER_SUPPLY_SYSFS_PATH,
421                                      name);
422                    if (access(path, R_OK) == 0)
423                        mHealthdConfig->batteryStatusPath = path;
424                }
425
426                if (mHealthdConfig->batteryHealthPath.isEmpty()) {
427                    path.clear();
428                    path.appendFormat("%s/%s/health", POWER_SUPPLY_SYSFS_PATH,
429                                      name);
430                    if (access(path, R_OK) == 0)
431                        mHealthdConfig->batteryHealthPath = path;
432                }
433
434                if (mHealthdConfig->batteryPresentPath.isEmpty()) {
435                    path.clear();
436                    path.appendFormat("%s/%s/present", POWER_SUPPLY_SYSFS_PATH,
437                                      name);
438                    if (access(path, R_OK) == 0)
439                        mHealthdConfig->batteryPresentPath = path;
440                }
441
442                if (mHealthdConfig->batteryCapacityPath.isEmpty()) {
443                    path.clear();
444                    path.appendFormat("%s/%s/capacity", POWER_SUPPLY_SYSFS_PATH,
445                                      name);
446                    if (access(path, R_OK) == 0)
447                        mHealthdConfig->batteryCapacityPath = path;
448                }
449
450                if (mHealthdConfig->batteryVoltagePath.isEmpty()) {
451                    path.clear();
452                    path.appendFormat("%s/%s/voltage_now",
453                                      POWER_SUPPLY_SYSFS_PATH, name);
454                    if (access(path, R_OK) == 0) {
455                        mHealthdConfig->batteryVoltagePath = path;
456                    } else {
457                        path.clear();
458                        path.appendFormat("%s/%s/batt_vol",
459                                          POWER_SUPPLY_SYSFS_PATH, name);
460                        if (access(path, R_OK) == 0)
461                            mHealthdConfig->batteryVoltagePath = path;
462                    }
463                }
464
465                if (mHealthdConfig->batteryCurrentNowPath.isEmpty()) {
466                    path.clear();
467                    path.appendFormat("%s/%s/current_now",
468                                      POWER_SUPPLY_SYSFS_PATH, name);
469                    if (access(path, R_OK) == 0)
470                        mHealthdConfig->batteryCurrentNowPath = path;
471                }
472
473                if (mHealthdConfig->batteryCurrentAvgPath.isEmpty()) {
474                    path.clear();
475                    path.appendFormat("%s/%s/current_avg",
476                                      POWER_SUPPLY_SYSFS_PATH, name);
477                    if (access(path, R_OK) == 0)
478                        mHealthdConfig->batteryCurrentAvgPath = path;
479                }
480
481                if (mHealthdConfig->batteryChargeCounterPath.isEmpty()) {
482                    path.clear();
483                    path.appendFormat("%s/%s/charge_counter",
484                                      POWER_SUPPLY_SYSFS_PATH, name);
485                    if (access(path, R_OK) == 0)
486                        mHealthdConfig->batteryChargeCounterPath = path;
487                }
488
489                if (mHealthdConfig->batteryTemperaturePath.isEmpty()) {
490                    path.clear();
491                    path.appendFormat("%s/%s/temp", POWER_SUPPLY_SYSFS_PATH,
492                                      name);
493                    if (access(path, R_OK) == 0) {
494                        mHealthdConfig->batteryTemperaturePath = path;
495                    } else {
496                        path.clear();
497                        path.appendFormat("%s/%s/batt_temp",
498                                          POWER_SUPPLY_SYSFS_PATH, name);
499                        if (access(path, R_OK) == 0)
500                            mHealthdConfig->batteryTemperaturePath = path;
501                    }
502                }
503
504                if (mHealthdConfig->batteryTechnologyPath.isEmpty()) {
505                    path.clear();
506                    path.appendFormat("%s/%s/technology",
507                                      POWER_SUPPLY_SYSFS_PATH, name);
508                    if (access(path, R_OK) == 0)
509                        mHealthdConfig->batteryTechnologyPath = path;
510                }
511
512                break;
513
514            case ANDROID_POWER_SUPPLY_TYPE_UNKNOWN:
515                break;
516            }
517        }
518        closedir(dir);
519    }
520
521    if (!mChargerNames.size())
522        KLOG_ERROR(LOG_TAG, "No charger supplies found\n");
523    if (!mBatteryDevicePresent) {
524        KLOG_WARNING(LOG_TAG, "No battery devices found\n");
525        hc->periodic_chores_interval_fast = -1;
526        hc->periodic_chores_interval_slow = -1;
527    } else {
528        if (mHealthdConfig->batteryStatusPath.isEmpty())
529            KLOG_WARNING(LOG_TAG, "BatteryStatusPath not found\n");
530        if (mHealthdConfig->batteryHealthPath.isEmpty())
531            KLOG_WARNING(LOG_TAG, "BatteryHealthPath not found\n");
532        if (mHealthdConfig->batteryPresentPath.isEmpty())
533            KLOG_WARNING(LOG_TAG, "BatteryPresentPath not found\n");
534        if (mHealthdConfig->batteryCapacityPath.isEmpty())
535            KLOG_WARNING(LOG_TAG, "BatteryCapacityPath not found\n");
536        if (mHealthdConfig->batteryVoltagePath.isEmpty())
537            KLOG_WARNING(LOG_TAG, "BatteryVoltagePath not found\n");
538        if (mHealthdConfig->batteryTemperaturePath.isEmpty())
539            KLOG_WARNING(LOG_TAG, "BatteryTemperaturePath not found\n");
540        if (mHealthdConfig->batteryTechnologyPath.isEmpty())
541            KLOG_WARNING(LOG_TAG, "BatteryTechnologyPath not found\n");
542    }
543
544    if (property_get("ro.boot.fake_battery", pval, NULL) > 0
545                                               && strtol(pval, NULL, 10) != 0) {
546        mBatteryFixedCapacity = FAKE_BATTERY_CAPACITY;
547        mBatteryFixedTemperature = FAKE_BATTERY_TEMPERATURE;
548    }
549}
550
551}; // namespace android
552