blob: 8b512c4b4e85921d8acfb6c94a39137d2a50b767 [file] [log] [blame]
Yifan Hong830cdb12021-01-11 20:47:23 -08001/*
2 * Copyright (C) 2021 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 "health-impl/Health.h"
18
19#include <android-base/file.h>
20#include <android-base/logging.h>
21#include <android/binder_manager.h>
22#include <android/binder_process.h>
23#include <android/hardware/health/translate-ndk.h>
24#include <health/utils.h>
25
26#include "LinkedCallback.h"
27#include "health-convert.h"
28
29using std::string_literals::operator""s;
30
31namespace aidl::android::hardware::health {
32
33namespace {
34// Wrap LinkedCallback::OnCallbackDied() into a void(void*).
35void OnCallbackDiedWrapped(void* cookie) {
36 LinkedCallback* linked = reinterpret_cast<LinkedCallback*>(cookie);
37 linked->OnCallbackDied();
38}
39} // namespace
40
41/*
42// If you need to call healthd_board_init, construct the Health instance with
43// the healthd_config after calling healthd_board_init:
44class MyHealth : public Health {
45 protected:
46 MyHealth() : Health(CreateConfig()) {}
47 private:
48 static std::unique_ptr<healthd_config> CreateConfig() {
49 auto config = std::make_unique<healthd_config>();
50 ::android::hardware::health::InitHealthdConfig(config.get());
51 healthd_board_init(config.get());
52 return std::move(config);
53 }
54};
55*/
56Health::Health(std::string_view instance_name, std::unique_ptr<struct healthd_config>&& config)
57 : instance_name_(instance_name),
58 healthd_config_(std::move(config)),
59 death_recipient_(AIBinder_DeathRecipient_new(&OnCallbackDiedWrapped)) {
60 battery_monitor_.init(healthd_config_.get());
61}
62
Yifan Hong2d418a22021-11-12 18:13:51 -080063Health::~Health() {}
64
Yifan Hong830cdb12021-01-11 20:47:23 -080065//
66// Getters.
67//
68
69template <typename T>
70static ndk::ScopedAStatus GetProperty(::android::BatteryMonitor* monitor, int id, T defaultValue,
71 T* out) {
72 *out = defaultValue;
73 struct ::android::BatteryProperty prop;
74 ::android::status_t err = monitor->getProperty(static_cast<int>(id), &prop);
75 if (err == ::android::OK) {
76 *out = static_cast<T>(prop.valueInt64);
77 } else {
78 LOG(DEBUG) << "getProperty(" << id << ")"
79 << " fails: (" << err << ") " << ::android::statusToString(err);
80 }
81
82 switch (err) {
83 case ::android::OK:
84 return ndk::ScopedAStatus::ok();
85 case ::android::NAME_NOT_FOUND:
86 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
87 default:
88 return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage(
89 IHealth::STATUS_UNKNOWN, ::android::statusToString(err).c_str());
90 }
91}
92
93ndk::ScopedAStatus Health::getChargeCounterUah(int32_t* out) {
94 return GetProperty<int32_t>(&battery_monitor_, ::android::BATTERY_PROP_CHARGE_COUNTER, 0, out);
95}
96
97ndk::ScopedAStatus Health::getCurrentNowMicroamps(int32_t* out) {
98 return GetProperty<int32_t>(&battery_monitor_, ::android::BATTERY_PROP_CURRENT_NOW, 0, out);
99}
100
101ndk::ScopedAStatus Health::getCurrentAverageMicroamps(int32_t* out) {
102 return GetProperty<int32_t>(&battery_monitor_, ::android::BATTERY_PROP_CURRENT_AVG, 0, out);
103}
104
105ndk::ScopedAStatus Health::getCapacity(int32_t* out) {
106 return GetProperty<int32_t>(&battery_monitor_, ::android::BATTERY_PROP_CAPACITY, 0, out);
107}
108
109ndk::ScopedAStatus Health::getEnergyCounterNwh(int64_t* out) {
110 return GetProperty<int64_t>(&battery_monitor_, ::android::BATTERY_PROP_ENERGY_COUNTER, 0, out);
111}
112
113ndk::ScopedAStatus Health::getChargeStatus(BatteryStatus* out) {
114 return GetProperty(&battery_monitor_, ::android::BATTERY_PROP_BATTERY_STATUS,
115 BatteryStatus::UNKNOWN, out);
116}
117
Jack Wu33561612022-11-24 12:10:55 +0800118ndk::ScopedAStatus Health::setChargingPolicy(BatteryChargingPolicy in_value) {
119 ::android::status_t err = battery_monitor_.setChargingPolicy(static_cast<int>(in_value));
120
121 switch (err) {
122 case ::android::OK:
123 return ndk::ScopedAStatus::ok();
124 case ::android::NAME_NOT_FOUND:
125 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
126 case ::android::BAD_VALUE:
127 return ndk::ScopedAStatus::fromStatus(::android::INVALID_OPERATION);
128 default:
129 return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage(
130 IHealth::STATUS_UNKNOWN, ::android::statusToString(err).c_str());
131 }
132}
133
134ndk::ScopedAStatus Health::getChargingPolicy(BatteryChargingPolicy* out) {
135 return GetProperty(&battery_monitor_, ::android::BATTERY_PROP_CHARGING_POLICY,
136 BatteryChargingPolicy::DEFAULT, out);
137}
138
139ndk::ScopedAStatus Health::getBatteryHealthData(BatteryHealthData* out) {
140 if (auto res =
141 GetProperty<int64_t>(&battery_monitor_, ::android::BATTERY_PROP_MANUFACTURING_DATE,
142 0, &out->batteryManufacturingDateSeconds);
143 !res.isOk()) {
144 LOG(WARNING) << "Cannot get Manufacturing_date: " << res.getDescription();
145 }
146 if (auto res = GetProperty<int64_t>(&battery_monitor_, ::android::BATTERY_PROP_FIRST_USAGE_DATE,
147 0, &out->batteryFirstUsageSeconds);
148 !res.isOk()) {
149 LOG(WARNING) << "Cannot get First_usage_date: " << res.getDescription();
150 }
Jack Wucbbf24f2023-02-18 12:34:19 +0800151 if (auto res = GetProperty<int64_t>(&battery_monitor_, ::android::BATTERY_PROP_STATE_OF_HEALTH,
152 0, &out->batteryStateOfHealth);
153 !res.isOk()) {
154 LOG(WARNING) << "Cannot get Battery_state_of_health: " << res.getDescription();
155 }
David Anderson85b3b032023-12-05 21:34:32 -0800156 out->batterySerialNumber = std::nullopt;
157 out->batteryPartStatus = BatteryPartStatus::UNSUPPORTED;
Jack Wu33561612022-11-24 12:10:55 +0800158 return ndk::ScopedAStatus::ok();
159}
160
Yifan Hong830cdb12021-01-11 20:47:23 -0800161ndk::ScopedAStatus Health::getDiskStats(std::vector<DiskStats>*) {
162 // This implementation does not support DiskStats. An implementation may extend this
163 // class and override this function to support disk stats.
164 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
165}
166
167ndk::ScopedAStatus Health::getStorageInfo(std::vector<StorageInfo>*) {
168 // This implementation does not support StorageInfo. An implementation may extend this
169 // class and override this function to support storage info.
170 return ndk::ScopedAStatus::fromExceptionCode(EX_UNSUPPORTED_OPERATION);
171}
172
173ndk::ScopedAStatus Health::getHealthInfo(HealthInfo* out) {
174 battery_monitor_.updateValues();
175
Yifan Hongbc84a792022-03-01 12:24:55 -0800176 *out = battery_monitor_.getHealthInfo();
Yifan Hong830cdb12021-01-11 20:47:23 -0800177
178 // Fill in storage infos; these aren't retrieved by BatteryMonitor.
179 if (auto res = getStorageInfo(&out->storageInfos); !res.isOk()) {
180 if (res.getServiceSpecificError() == 0 &&
181 res.getExceptionCode() != EX_UNSUPPORTED_OPERATION) {
182 return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage(
183 IHealth::STATUS_UNKNOWN,
184 ("getStorageInfo fails: " + res.getDescription()).c_str());
185 }
186 LOG(DEBUG) << "getHealthInfo: getStorageInfo fails with service-specific error, clearing: "
187 << res.getDescription();
188 out->storageInfos = {};
189 }
190 if (auto res = getDiskStats(&out->diskStats); !res.isOk()) {
191 if (res.getServiceSpecificError() == 0 &&
192 res.getExceptionCode() != EX_UNSUPPORTED_OPERATION) {
193 return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage(
194 IHealth::STATUS_UNKNOWN,
195 ("getDiskStats fails: " + res.getDescription()).c_str());
196 }
197 LOG(DEBUG) << "getHealthInfo: getDiskStats fails with service-specific error, clearing: "
198 << res.getDescription();
199 out->diskStats = {};
200 }
201
202 // A subclass may want to update health info struct before returning it.
203 UpdateHealthInfo(out);
204
205 return ndk::ScopedAStatus::ok();
206}
207
208binder_status_t Health::dump(int fd, const char**, uint32_t) {
209 battery_monitor_.dumpState(fd);
210
211 ::android::base::WriteStringToFd("\ngetHealthInfo -> ", fd);
212 HealthInfo health_info;
213 auto res = getHealthInfo(&health_info);
214 if (res.isOk()) {
215 ::android::base::WriteStringToFd(health_info.toString(), fd);
216 } else {
217 ::android::base::WriteStringToFd(res.getDescription(), fd);
218 }
219
220 fsync(fd);
221 return STATUS_OK;
222}
223
224std::optional<bool> Health::ShouldKeepScreenOn() {
225 if (!healthd_config_->screen_on) {
226 return std::nullopt;
227 }
228
229 HealthInfo health_info;
230 auto res = getHealthInfo(&health_info);
231 if (!res.isOk()) {
232 return std::nullopt;
233 }
234
235 ::android::BatteryProperties props = {};
236 convert(health_info, &props);
237 return healthd_config_->screen_on(&props);
238}
239
240namespace {
241bool IsDeadObjectLogged(const ndk::ScopedAStatus& ret) {
242 if (ret.isOk()) return false;
243 if (ret.getStatus() == ::STATUS_DEAD_OBJECT) return true;
244 LOG(ERROR) << "Cannot call healthInfoChanged on callback: " << ret.getDescription();
245 return false;
246}
247} // namespace
248
249//
250// Subclass helpers / overrides
251//
252
253void Health::UpdateHealthInfo(HealthInfo* /* health_info */) {
254 /*
255 // Sample code for a subclass to implement this:
256 // If you need to modify values (e.g. batteryChargeTimeToFullNowSeconds), do it here.
257 health_info->batteryChargeTimeToFullNowSeconds = calculate_charge_time_seconds();
258
259 // If you need to call healthd_board_battery_update, modify its signature
260 // and implementation to operate on HealthInfo directly, then call:
261 healthd_board_battery_update(health_info);
262 */
263}
264
265//
266// Methods that handle callbacks.
267//
268
269ndk::ScopedAStatus Health::registerCallback(const std::shared_ptr<IHealthInfoCallback>& callback) {
270 if (callback == nullptr) {
271 // For now, this shouldn't happen because argument is not nullable.
272 return ndk::ScopedAStatus::fromExceptionCode(EX_NULL_POINTER);
273 }
274
275 {
276 std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
Yifan Hong70197262023-07-06 17:08:41 -0700277 auto linked_callback_result = LinkedCallback::Make(ref<Health>(), callback);
278 if (!linked_callback_result.ok()) {
279 return ndk::ScopedAStatus::fromStatus(-linked_callback_result.error().code());
280 }
281 callbacks_.emplace_back(std::move(*linked_callback_result));
Yifan Hong830cdb12021-01-11 20:47:23 -0800282 // unlock
283 }
284
285 HealthInfo health_info;
286 if (auto res = getHealthInfo(&health_info); !res.isOk()) {
287 LOG(WARNING) << "Cannot call getHealthInfo: " << res.getDescription();
288 // No health info to send, so return early.
289 return ndk::ScopedAStatus::ok();
290 }
291
292 if (auto res = callback->healthInfoChanged(health_info); IsDeadObjectLogged(res)) {
293 (void)unregisterCallback(callback);
294 }
295 return ndk::ScopedAStatus::ok();
296}
297
298ndk::ScopedAStatus Health::unregisterCallback(
299 const std::shared_ptr<IHealthInfoCallback>& callback) {
300 if (callback == nullptr) {
301 // For now, this shouldn't happen because argument is not nullable.
302 return ndk::ScopedAStatus::fromExceptionCode(EX_NULL_POINTER);
303 }
304
305 std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
306
307 auto matches = [callback](const auto& linked) {
Yifan Hong6839f672021-10-28 22:24:35 -0700308 return linked->callback()->asBinder() == callback->asBinder(); // compares binder object
Yifan Hong830cdb12021-01-11 20:47:23 -0800309 };
310 auto it = std::remove_if(callbacks_.begin(), callbacks_.end(), matches);
311 bool removed = (it != callbacks_.end());
312 callbacks_.erase(it, callbacks_.end()); // calls unlinkToDeath on deleted callbacks.
313 return removed ? ndk::ScopedAStatus::ok()
314 : ndk::ScopedAStatus::fromExceptionCode(EX_ILLEGAL_ARGUMENT);
315}
316
317// A combination of the HIDL version
318// android::hardware::health::V2_1::implementation::Health::update() and
319// android::hardware::health::V2_1::implementation::BinderHealth::update()
320ndk::ScopedAStatus Health::update() {
321 HealthInfo health_info;
322 if (auto res = getHealthInfo(&health_info); !res.isOk()) {
323 LOG(DEBUG) << "Cannot call getHealthInfo for update(): " << res.getDescription();
324 // Propagate service specific errors. If there's none, report unknown error.
325 if (res.getServiceSpecificError() != 0 ||
326 res.getExceptionCode() == EX_UNSUPPORTED_OPERATION) {
327 return res;
328 }
329 return ndk::ScopedAStatus::fromServiceSpecificErrorWithMessage(
330 IHealth::STATUS_UNKNOWN, res.getDescription().c_str());
331 }
332 battery_monitor_.logValues();
333 OnHealthInfoChanged(health_info);
334 return ndk::ScopedAStatus::ok();
335}
336
337void Health::OnHealthInfoChanged(const HealthInfo& health_info) {
338 // Notify all callbacks
339 std::unique_lock<decltype(callbacks_lock_)> lock(callbacks_lock_);
340 // is_dead notifies a callback and return true if it is dead.
341 auto is_dead = [&](const auto& linked) {
342 auto res = linked->callback()->healthInfoChanged(health_info);
343 return IsDeadObjectLogged(res);
344 };
345 auto it = std::remove_if(callbacks_.begin(), callbacks_.end(), is_dead);
346 callbacks_.erase(it, callbacks_.end()); // calls unlinkToDeath on deleted callbacks.
347 lock.unlock();
348
349 // Let HalHealthLoop::OnHealthInfoChanged() adjusts uevent / wakealarm periods
350}
351
352void Health::BinderEvent(uint32_t /*epevents*/) {
353 if (binder_fd_ >= 0) {
354 ABinderProcess_handlePolledCommands();
355 }
356}
357
358void Health::OnInit(HalHealthLoop* hal_health_loop, struct healthd_config* config) {
359 LOG(INFO) << instance_name_ << " instance initializing with healthd_config...";
360
361 // Similar to HIDL's android::hardware::health::V2_1::implementation::HalHealthLoop::Init,
362 // copy configuration parameters to |config| for HealthLoop (e.g. uevent / wake alarm periods)
363 *config = *healthd_config_.get();
364
365 binder_status_t status = ABinderProcess_setupPolling(&binder_fd_);
366
367 if (status == ::STATUS_OK && binder_fd_ >= 0) {
368 std::shared_ptr<Health> thiz = ref<Health>();
369 auto binder_event = [thiz](auto*, uint32_t epevents) { thiz->BinderEvent(epevents); };
370 if (hal_health_loop->RegisterEvent(binder_fd_, binder_event, EVENT_NO_WAKEUP_FD) != 0) {
371 PLOG(ERROR) << instance_name_ << " instance: Register for binder events failed";
372 }
373 }
374
375 std::string health_name = IHealth::descriptor + "/"s + instance_name_;
376 CHECK_EQ(STATUS_OK, AServiceManager_addService(this->asBinder().get(), health_name.c_str()))
377 << instance_name_ << ": Failed to register HAL";
378
379 LOG(INFO) << instance_name_ << ": Hal init done";
380}
381
382// Unlike hwbinder, for binder, there's no need to explicitly call flushCommands()
383// in PrepareToWait(). See b/139697085.
384
385} // namespace aidl::android::hardware::health