Paul Lawrence | 8799917 | 2014-02-20 12:21:31 -0800 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2014 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 "VoldCheckBattery" |
| 18 | #include <cutils/log.h> |
| 19 | |
| 20 | #include <binder/IServiceManager.h> |
| 21 | #include <batteryservice/IBatteryPropertiesRegistrar.h> |
| 22 | |
| 23 | using namespace android; |
| 24 | |
| 25 | namespace |
| 26 | { |
| 27 | // How often to check battery in seconds |
| 28 | const int CHECK_PERIOD = 30; |
| 29 | const String16 serviceName("batteryproperties"); |
| 30 | |
| 31 | sp<IBinder> bs; |
| 32 | sp<IBatteryPropertiesRegistrar> interface; |
| 33 | |
| 34 | bool singletonInitialized = false; |
| 35 | time_t last_checked = {0}; |
| 36 | int battery_ok = 1; |
| 37 | } |
| 38 | |
| 39 | extern "C" int is_battery_ok() |
| 40 | { |
| 41 | time_t now = time(NULL); |
| 42 | if (now == -1 || difftime(now, last_checked) < 5) { |
| 43 | return battery_ok; |
| 44 | } |
| 45 | last_checked = now; |
| 46 | |
| 47 | if (!singletonInitialized) { |
| 48 | bs = defaultServiceManager()->checkService(serviceName); |
| 49 | if (bs == NULL) { |
| 50 | SLOGE("No batteryproperties service!"); |
| 51 | return 1; |
| 52 | } |
| 53 | |
| 54 | interface = interface_cast<IBatteryPropertiesRegistrar>(bs); |
| 55 | if (interface == NULL) { |
| 56 | SLOGE("No IBatteryPropertiesRegistrar interface"); |
| 57 | return 1; |
| 58 | } |
| 59 | |
| 60 | singletonInitialized = true; |
| 61 | } |
| 62 | |
| 63 | BatteryProperty val; |
| 64 | status_t status = interface->getProperty(android::BATTERY_PROP_CAPACITY, |
| 65 | &val); |
| 66 | if (status == NO_ERROR) { |
| 67 | SLOGD("Capacity is %d", val.valueInt); |
| 68 | battery_ok = val.valueInt > 5 ? 1 : 0; |
| 69 | } else { |
| 70 | SLOGE("Failed to get battery charge"); |
| 71 | battery_ok = 1; |
| 72 | } |
| 73 | |
| 74 | return battery_ok; |
| 75 | } |