1 /*
2  * Copyright (C) 2018 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 #define LOG_TAG "android.hardware.health@2.0-impl"
17 #include <android-base/logging.h>
18 
19 #include <android-base/file.h>
20 #include <android/hardware/health/2.0/types.h>
21 #include <health2/Health.h>
22 
23 #include <hal_conversion.h>
24 #include <hidl/HidlTransportSupport.h>
25 
26 using HealthInfo_1_0 = android::hardware::health::V1_0::HealthInfo;
27 using android::hardware::health::V1_0::hal_conversion::convertFromHealthInfo;
28 
29 extern void healthd_battery_update_internal(bool);
30 
31 namespace android {
32 namespace hardware {
33 namespace health {
34 namespace V2_0 {
35 namespace implementation {
36 
37 sp<Health> Health::instance_;
38 
Health(struct healthd_config * c)39 Health::Health(struct healthd_config* c) {
40     // TODO(b/69268160): remove when libhealthd is removed.
41     healthd_board_init(c);
42     battery_monitor_ = std::make_unique<BatteryMonitor>();
43     battery_monitor_->init(c);
44 }
45 
46 // Methods from IHealth follow.
registerCallback(const sp<IHealthInfoCallback> & callback)47 Return<Result> Health::registerCallback(const sp<IHealthInfoCallback>& callback) {
48     if (callback == nullptr) {
49         return Result::SUCCESS;
50     }
51 
52     {
53         std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
54         callbacks_.push_back(callback);
55         // unlock
56     }
57 
58     auto linkRet = callback->linkToDeath(this, 0u /* cookie */);
59     if (!linkRet.withDefault(false)) {
60         LOG(WARNING) << __func__ << "Cannot link to death: "
61                      << (linkRet.isOk() ? "linkToDeath returns false" : linkRet.description());
62         // ignore the error
63     }
64 
65     return updateAndNotify(callback);
66 }
67 
unregisterCallbackInternal(const sp<IBase> & callback)68 bool Health::unregisterCallbackInternal(const sp<IBase>& callback) {
69     if (callback == nullptr) return false;
70 
71     bool removed = false;
72     std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
73     for (auto it = callbacks_.begin(); it != callbacks_.end();) {
74         if (interfacesEqual(*it, callback)) {
75             it = callbacks_.erase(it);
76             removed = true;
77         } else {
78             ++it;
79         }
80     }
81     (void)callback->unlinkToDeath(this).isOk();  // ignore errors
82     return removed;
83 }
84 
unregisterCallback(const sp<IHealthInfoCallback> & callback)85 Return<Result> Health::unregisterCallback(const sp<IHealthInfoCallback>& callback) {
86     return unregisterCallbackInternal(callback) ? Result::SUCCESS : Result::NOT_FOUND;
87 }
88 
89 template <typename T>
getProperty(const std::unique_ptr<BatteryMonitor> & monitor,int id,T defaultValue,const std::function<void (Result,T)> & callback)90 void getProperty(const std::unique_ptr<BatteryMonitor>& monitor, int id, T defaultValue,
91                  const std::function<void(Result, T)>& callback) {
92     struct BatteryProperty prop;
93     T ret = defaultValue;
94     Result result = Result::SUCCESS;
95     status_t err = monitor->getProperty(static_cast<int>(id), &prop);
96     if (err != OK) {
97         LOG(DEBUG) << "getProperty(" << id << ")"
98                    << " fails: (" << err << ") " << strerror(-err);
99     } else {
100         ret = static_cast<T>(prop.valueInt64);
101     }
102     switch (err) {
103         case OK:
104             result = Result::SUCCESS;
105             break;
106         case NAME_NOT_FOUND:
107             result = Result::NOT_SUPPORTED;
108             break;
109         default:
110             result = Result::UNKNOWN;
111             break;
112     }
113     callback(result, static_cast<T>(ret));
114 }
115 
getChargeCounter(getChargeCounter_cb _hidl_cb)116 Return<void> Health::getChargeCounter(getChargeCounter_cb _hidl_cb) {
117     getProperty<int32_t>(battery_monitor_, BATTERY_PROP_CHARGE_COUNTER, 0, _hidl_cb);
118     return Void();
119 }
120 
getCurrentNow(getCurrentNow_cb _hidl_cb)121 Return<void> Health::getCurrentNow(getCurrentNow_cb _hidl_cb) {
122     getProperty<int32_t>(battery_monitor_, BATTERY_PROP_CURRENT_NOW, 0, _hidl_cb);
123     return Void();
124 }
125 
getCurrentAverage(getCurrentAverage_cb _hidl_cb)126 Return<void> Health::getCurrentAverage(getCurrentAverage_cb _hidl_cb) {
127     getProperty<int32_t>(battery_monitor_, BATTERY_PROP_CURRENT_AVG, 0, _hidl_cb);
128     return Void();
129 }
130 
getCapacity(getCapacity_cb _hidl_cb)131 Return<void> Health::getCapacity(getCapacity_cb _hidl_cb) {
132     getProperty<int32_t>(battery_monitor_, BATTERY_PROP_CAPACITY, 0, _hidl_cb);
133     return Void();
134 }
135 
getEnergyCounter(getEnergyCounter_cb _hidl_cb)136 Return<void> Health::getEnergyCounter(getEnergyCounter_cb _hidl_cb) {
137     getProperty<int64_t>(battery_monitor_, BATTERY_PROP_ENERGY_COUNTER, 0, _hidl_cb);
138     return Void();
139 }
140 
getChargeStatus(getChargeStatus_cb _hidl_cb)141 Return<void> Health::getChargeStatus(getChargeStatus_cb _hidl_cb) {
142     getProperty(battery_monitor_, BATTERY_PROP_BATTERY_STATUS, BatteryStatus::UNKNOWN, _hidl_cb);
143     return Void();
144 }
145 
update()146 Return<Result> Health::update() {
147     if (!healthd_mode_ops || !healthd_mode_ops->battery_update) {
148         LOG(WARNING) << "health@2.0: update: not initialized. "
149                      << "update() should not be called in charger";
150         return Result::UNKNOWN;
151     }
152 
153     // Retrieve all information and call healthd_mode_ops->battery_update, which calls
154     // notifyListeners.
155     battery_monitor_->updateValues();
156     const HealthInfo_1_0& health_info = battery_monitor_->getHealthInfo_1_0();
157     struct BatteryProperties props;
158     convertFromHealthInfo(health_info, &props);
159     bool log = (healthd_board_battery_update(&props) == 0);
160     if (log) {
161         battery_monitor_->logValues();
162     }
163     healthd_mode_ops->battery_update(&props);
164     bool chargerOnline = battery_monitor_->isChargerOnline();
165 
166     // adjust uevent / wakealarm periods
167     healthd_battery_update_internal(chargerOnline);
168 
169     return Result::SUCCESS;
170 }
171 
updateAndNotify(const sp<IHealthInfoCallback> & callback)172 Return<Result> Health::updateAndNotify(const sp<IHealthInfoCallback>& callback) {
173     std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
174     std::vector<sp<IHealthInfoCallback>> storedCallbacks{std::move(callbacks_)};
175     callbacks_.clear();
176     if (callback != nullptr) {
177         callbacks_.push_back(callback);
178     }
179     Return<Result> result = update();
180     callbacks_ = std::move(storedCallbacks);
181     return result;
182 }
183 
notifyListeners(HealthInfo * healthInfo)184 void Health::notifyListeners(HealthInfo* healthInfo) {
185     std::vector<StorageInfo> info;
186     get_storage_info(info);
187 
188     std::vector<DiskStats> stats;
189     get_disk_stats(stats);
190 
191     int32_t currentAvg = 0;
192 
193     struct BatteryProperty prop;
194     status_t ret = battery_monitor_->getProperty(BATTERY_PROP_CURRENT_AVG, &prop);
195     if (ret == OK) {
196         currentAvg = static_cast<int32_t>(prop.valueInt64);
197     }
198 
199     healthInfo->batteryCurrentAverage = currentAvg;
200     healthInfo->diskStats = stats;
201     healthInfo->storageInfos = info;
202 
203     std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
204     for (auto it = callbacks_.begin(); it != callbacks_.end();) {
205         auto ret = (*it)->healthInfoChanged(*healthInfo);
206         if (!ret.isOk() && ret.isDeadObject()) {
207             it = callbacks_.erase(it);
208         } else {
209             ++it;
210         }
211     }
212 }
213 
debug(const hidl_handle & handle,const hidl_vec<hidl_string> &)214 Return<void> Health::debug(const hidl_handle& handle, const hidl_vec<hidl_string>&) {
215     if (handle != nullptr && handle->numFds >= 1) {
216         int fd = handle->data[0];
217         battery_monitor_->dumpState(fd);
218 
219         getHealthInfo([fd](auto res, const auto& info) {
220             android::base::WriteStringToFd("\ngetHealthInfo -> ", fd);
221             if (res == Result::SUCCESS) {
222                 android::base::WriteStringToFd(toString(info), fd);
223             } else {
224                 android::base::WriteStringToFd(toString(res), fd);
225             }
226             android::base::WriteStringToFd("\n", fd);
227         });
228 
229         fsync(fd);
230     }
231     return Void();
232 }
233 
getStorageInfo(getStorageInfo_cb _hidl_cb)234 Return<void> Health::getStorageInfo(getStorageInfo_cb _hidl_cb) {
235     std::vector<struct StorageInfo> info;
236     get_storage_info(info);
237     hidl_vec<struct StorageInfo> info_vec(info);
238     if (!info.size()) {
239         _hidl_cb(Result::NOT_SUPPORTED, info_vec);
240     } else {
241         _hidl_cb(Result::SUCCESS, info_vec);
242     }
243     return Void();
244 }
245 
getDiskStats(getDiskStats_cb _hidl_cb)246 Return<void> Health::getDiskStats(getDiskStats_cb _hidl_cb) {
247     std::vector<struct DiskStats> stats;
248     get_disk_stats(stats);
249     hidl_vec<struct DiskStats> stats_vec(stats);
250     if (!stats.size()) {
251         _hidl_cb(Result::NOT_SUPPORTED, stats_vec);
252     } else {
253         _hidl_cb(Result::SUCCESS, stats_vec);
254     }
255     return Void();
256 }
257 
getHealthInfo(getHealthInfo_cb _hidl_cb)258 Return<void> Health::getHealthInfo(getHealthInfo_cb _hidl_cb) {
259     using android::hardware::health::V1_0::hal_conversion::convertToHealthInfo;
260 
261     updateAndNotify(nullptr);
262     HealthInfo healthInfo = battery_monitor_->getHealthInfo_2_0();
263 
264     std::vector<StorageInfo> info;
265     get_storage_info(info);
266 
267     std::vector<DiskStats> stats;
268     get_disk_stats(stats);
269 
270     int32_t currentAvg = 0;
271 
272     struct BatteryProperty prop;
273     status_t ret = battery_monitor_->getProperty(BATTERY_PROP_CURRENT_AVG, &prop);
274     if (ret == OK) {
275         currentAvg = static_cast<int32_t>(prop.valueInt64);
276     }
277 
278     healthInfo.batteryCurrentAverage = currentAvg;
279     healthInfo.diskStats = stats;
280     healthInfo.storageInfos = info;
281 
282     _hidl_cb(Result::SUCCESS, healthInfo);
283     return Void();
284 }
285 
serviceDied(uint64_t,const wp<IBase> & who)286 void Health::serviceDied(uint64_t /* cookie */, const wp<IBase>& who) {
287     (void)unregisterCallbackInternal(who.promote());
288 }
289 
initInstance(struct healthd_config * c)290 sp<IHealth> Health::initInstance(struct healthd_config* c) {
291     if (instance_ == nullptr) {
292         instance_ = new Health(c);
293     }
294     return instance_;
295 }
296 
getImplementation()297 sp<Health> Health::getImplementation() {
298     CHECK(instance_ != nullptr);
299     return instance_;
300 }
301 
302 }  // namespace implementation
303 }  // namespace V2_0
304 }  // namespace health
305 }  // namespace hardware
306 }  // namespace android
307