health 2.1 implementation.

Test: VTS health 2.1 test
Bug: 137670450

Change-Id: I04ea74facbaa534eee00a51474a013db3b6eb212
diff --git a/health/utils/libhealth2impl/Android.bp b/health/utils/libhealth2impl/Android.bp
new file mode 100644
index 0000000..14374a2
--- /dev/null
+++ b/health/utils/libhealth2impl/Android.bp
@@ -0,0 +1,51 @@
+// Copyright (C) 2019 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// A helper library for health@2.x HAL implementation.
+// HAL implementations can link to this library and extend the Health class.
+cc_library_static {
+    name: "libhealth2impl",
+    vendor_available: true,
+    recovery_available: true,
+    srcs: [
+        "BinderHealth.cpp",
+        "HalHealthLoop.cpp",
+        "Health.cpp",
+    ],
+    shared_libs: [
+        "libbase",
+        "libcutils",
+        "libhidlbase",
+        "liblog",
+        "libutils",
+        "android.hardware.health@2.1",
+        "android.hardware.health@2.0",
+    ],
+    static_libs: [
+        "libbatterymonitor",
+        "libhealthloop",
+        "android.hardware.health@1.0-convert",
+    ],
+    cflags: [
+        "-Wall",
+        "-Werror",
+    ],
+    export_static_lib_headers: [
+        "libbatterymonitor",
+        "libhealthloop",
+    ],
+    export_include_dirs: [
+        "include",
+    ],
+}
diff --git a/health/utils/libhealth2impl/BinderHealth.cpp b/health/utils/libhealth2impl/BinderHealth.cpp
new file mode 100644
index 0000000..625d0e0
--- /dev/null
+++ b/health/utils/libhealth2impl/BinderHealth.cpp
@@ -0,0 +1,190 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <health2impl/BinderHealth.h>
+
+#include <android-base/logging.h>
+#include <hidl/HidlTransportSupport.h>
+#include <hwbinder/IPCThreadState.h>
+
+#include <health2impl/Callback.h>
+#include <health2impl/Health.h>
+
+using android::hardware::handleTransportPoll;
+using android::hardware::IPCThreadState;
+using android::hardware::setupTransportPolling;
+
+using android::hardware::health::V2_0::Result;
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+bool IsDeadObjectLogged(const Return<void>& ret) {
+    if (ret.isOk()) return false;
+    if (ret.isDeadObject()) return true;
+    LOG(ERROR) << "Cannot call healthInfoChanged* on callback: " << ret.description();
+    return false;
+}
+
+BinderHealth::BinderHealth(const std::string& name, const sp<IHealth>& impl)
+    : HalHealthLoop(name, impl) {
+    CHECK_NE(this, impl.get());
+    CHECK(!impl->isRemote());
+}
+
+//
+// Methods that handle callbacks.
+//
+
+Return<Result> BinderHealth::registerCallback(const sp<V2_0::IHealthInfoCallback>& callback) {
+    if (callback == nullptr) {
+        return Result::SUCCESS;
+    }
+
+    Callback* wrapped = nullptr;
+    {
+        std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
+        wrapped = callbacks_.emplace_back(Wrap(callback)).get();
+        // unlock
+    }
+
+    auto linkRet = callback->linkToDeath(this, 0u /* cookie */);
+    if (!linkRet.withDefault(false)) {
+        LOG(WARNING) << __func__ << "Cannot link to death: "
+                     << (linkRet.isOk() ? "linkToDeath returns false" : linkRet.description());
+        // ignore the error
+    }
+
+    getHealthInfo_2_1([&](auto res, const auto& health_info) {
+        if (res != Result::SUCCESS) {
+            LOG(ERROR) << "Cannot call getHealthInfo_2_1: " << toString(res);
+            return;
+        }
+        auto ret = wrapped->Notify(health_info);
+        if (IsDeadObjectLogged(ret)) {
+            // Remove callback reference.
+            std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
+            auto it = std::find_if(callbacks_.begin(), callbacks_.end(),
+                                   [wrapped](const auto& cb) { return cb.get() == wrapped; });
+            if (it != callbacks_.end()) {
+                callbacks_.erase(it);
+            }
+            // unlock
+        }
+    });
+
+    return Result::SUCCESS;
+}
+
+bool BinderHealth::unregisterCallbackInternal(const sp<IBase>& callback) {
+    if (callback == nullptr) {
+        return false;
+    }
+
+    bool removed = false;
+    std::lock_guard<decltype(callbacks_lock_)> lock(callbacks_lock_);
+    for (auto it = callbacks_.begin(); it != callbacks_.end();) {
+        if (interfacesEqual((*it)->Get(), callback)) {
+            it = callbacks_.erase(it);
+            removed = true;
+        } else {
+            ++it;
+        }
+    }
+    (void)callback->unlinkToDeath(this).isOk();  // ignore errors
+    return removed;
+}
+
+Return<Result> BinderHealth::update() {
+    Result result = service()->update();
+    if (result != Result::SUCCESS) return result;
+    getHealthInfo_2_1([&](auto res, const auto& health_info) {
+        if (res != Result::SUCCESS) {
+            result = res;
+            return;
+        }
+        OnHealthInfoChanged(health_info);
+    });
+    return result;
+}
+
+Return<Result> BinderHealth::unregisterCallback(const sp<V2_0::IHealthInfoCallback>& callback) {
+    return unregisterCallbackInternal(callback) ? Result::SUCCESS : Result::NOT_FOUND;
+}
+
+void BinderHealth::OnHealthInfoChanged(const HealthInfo& health_info) {
+    // Notify all callbacks
+    std::unique_lock<decltype(callbacks_lock_)> lock(callbacks_lock_);
+    for (auto it = callbacks_.begin(); it != callbacks_.end();) {
+        auto ret = (*it)->Notify(health_info);
+        if (IsDeadObjectLogged(ret)) {
+            it = callbacks_.erase(it);
+        } else {
+            ++it;
+        }
+    }
+    lock.unlock();
+
+    // adjusts uevent / wakealarm periods
+    HalHealthLoop::OnHealthInfoChanged(health_info);
+}
+
+void BinderHealth::serviceDied(uint64_t /* cookie */, const wp<IBase>& who) {
+    (void)unregisterCallbackInternal(who.promote());
+}
+
+void BinderHealth::BinderEvent(uint32_t /*epevents*/) {
+    if (binder_fd_ >= 0) {
+        handleTransportPoll(binder_fd_);
+    }
+}
+
+void BinderHealth::Init(struct healthd_config* config) {
+    // Set up epoll and get uevent / wake alarm periods
+    HalHealthLoop::Init(config);
+
+    LOG(INFO) << instance_name() << " instance initializing with healthd_config...";
+
+    binder_fd_ = setupTransportPolling();
+
+    if (binder_fd_ >= 0) {
+        auto binder_event = [](auto* health_loop, uint32_t epevents) {
+            static_cast<BinderHealth*>(health_loop)->BinderEvent(epevents);
+        };
+        if (RegisterEvent(binder_fd_, binder_event, EVENT_NO_WAKEUP_FD) != 0) {
+            PLOG(ERROR) << instance_name() << " instance: Register for binder events failed";
+        }
+    }
+
+    CHECK_EQ(registerAsService(instance_name()), android::OK)
+            << instance_name() << ": Failed to register HAL";
+
+    LOG(INFO) << instance_name() << ": Hal init done";
+}
+
+int BinderHealth::PrepareToWait(void) {
+    IPCThreadState::self()->flushCommands();
+    return HalHealthLoop::PrepareToWait();
+}
+
+}  // namespace implementation
+}  // namespace V2_1
+}  // namespace health
+}  // namespace hardware
+}  // namespace android
diff --git a/health/utils/libhealth2impl/HalHealthLoop.cpp b/health/utils/libhealth2impl/HalHealthLoop.cpp
new file mode 100644
index 0000000..3901a76
--- /dev/null
+++ b/health/utils/libhealth2impl/HalHealthLoop.cpp
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <health2impl/HalHealthLoop.h>
+
+#include <android-base/logging.h>
+#include <hal_conversion.h>
+#include <hidl/HidlTransportSupport.h>
+#include <hwbinder/IPCThreadState.h>
+
+#include <health2impl/Health.h>
+
+using android::hardware::configureRpcThreadpool;
+using android::hardware::handleTransportPoll;
+using android::hardware::IPCThreadState;
+using android::hardware::setupTransportPolling;
+
+using android::hardware::health::V1_0::hal_conversion::convertFromHealthConfig;
+using android::hardware::health::V2_0::Result;
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+void HalHealthLoop::Init(struct healthd_config* config) {
+    // Retrieve healthd_config from the HAL.
+    service_->getHealthConfig([config](auto res, const auto& health_config) {
+        CHECK(res == Result::SUCCESS);
+
+        convertFromHealthConfig(health_config.battery, config);
+        config->boot_min_cap = health_config.bootMinCap;
+
+        // Leave screen_on empty because it is handled in GetScreenOn below.
+
+        // Leave ignorePowerSupplyNames empty because it isn't
+        // used by clients of health HAL.
+    });
+}
+
+void HalHealthLoop::Heartbeat(void) {
+    // noop
+}
+
+void HalHealthLoop::ScheduleBatteryUpdate() {
+    // ignore errors. impl may not be able to handle any callbacks, so
+    // update() may return errors.
+    Result res = service_->update();
+    if (res != Result::SUCCESS) {
+        LOG(WARNING) << "update() on the health HAL implementation failed with " << toString(res);
+    }
+
+    service_->getHealthInfo_2_1([this](auto res, const auto& health_info) {
+        CHECK(res == Result::SUCCESS)
+                << "getHealthInfo_2_1() on the health HAL implementation failed with "
+                << toString(res);
+        this->OnHealthInfoChanged(health_info);
+    });
+}
+
+int HalHealthLoop::PrepareToWait() {
+    return -1;
+}
+
+void HalHealthLoop::OnHealthInfoChanged(const HealthInfo& health_info) {
+    set_charger_online(health_info);
+    AdjustWakealarmPeriods(charger_online());
+}
+
+void HalHealthLoop::set_charger_online(const HealthInfo& health_info) {
+    const auto& props = health_info.legacy.legacy;
+    charger_online_ =
+            props.chargerAcOnline || props.chargerUsbOnline || props.chargerWirelessOnline;
+}
+
+}  // namespace implementation
+}  // namespace V2_1
+}  // namespace health
+}  // namespace hardware
+}  // namespace android
diff --git a/health/utils/libhealth2impl/Health.cpp b/health/utils/libhealth2impl/Health.cpp
new file mode 100644
index 0000000..f4684ae
--- /dev/null
+++ b/health/utils/libhealth2impl/Health.cpp
@@ -0,0 +1,267 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <health2impl/Health.h>
+
+#include <functional>
+#include <string_view>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android/hardware/health/1.0/types.h>
+#include <android/hardware/health/2.0/IHealthInfoCallback.h>
+#include <android/hardware/health/2.0/types.h>
+#include <android/hardware/health/2.1/IHealthInfoCallback.h>
+#include <hal_conversion.h>
+#include <healthd/healthd.h>
+#include <hidl/HidlTransportSupport.h>
+#include <hwbinder/IPCThreadState.h>
+
+#include <health2impl/Callback.h>
+#include <health2impl/HalHealthLoop.h>
+
+using android::hardware::health::V1_0::BatteryStatus;
+using android::hardware::health::V1_0::toString;
+using android::hardware::health::V1_0::hal_conversion::convertFromHealthInfo;
+using android::hardware::health::V1_0::hal_conversion::convertToHealthConfig;
+using android::hardware::health::V1_0::hal_conversion::convertToHealthInfo;
+using android::hardware::health::V2_0::Result;
+using android::hardware::health::V2_1::IHealth;
+
+using ScreenOn = decltype(healthd_config::screen_on);
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+/*
+// If you need to call healthd_board_init, construct the Health instance with
+// the healthd_config after calling healthd_board_init:
+struct healthd_config* init_config(struct healthd_config* config) {
+    healthd_board_init(config);
+    return config;
+}
+class MyHealth : public Health {
+    MyHealth(struct healthd_config* config) :
+        Health(init_config(config)) {}
+};
+*/
+
+Health::Health(std::unique_ptr<healthd_config>&& config) : healthd_config_(std::move(config)) {
+    battery_monitor_.init(healthd_config_.get());
+}
+
+//
+// Callbacks are not supported by the passthrough implementation.
+//
+
+Return<Result> Health::registerCallback(const sp<V2_0::IHealthInfoCallback>&) {
+    return Result::NOT_SUPPORTED;
+}
+
+Return<Result> Health::unregisterCallback(const sp<V2_0::IHealthInfoCallback>&) {
+    return Result::NOT_SUPPORTED;
+}
+
+Return<Result> Health::update() {
+    Result result = Result::UNKNOWN;
+    getHealthInfo_2_1([&](auto res, const auto& /* health_info */) {
+        result = res;
+        if (res != Result::SUCCESS) {
+            LOG(ERROR) << "Cannot call getHealthInfo_2_1: " << toString(res);
+            return;
+        }
+
+        battery_monitor_.logValues();
+    });
+    return result;
+}
+
+//
+// Getters.
+//
+
+template <typename T>
+static Return<void> GetProperty(BatteryMonitor* monitor, int id, T defaultValue,
+                                const std::function<void(Result, T)>& callback) {
+    struct BatteryProperty prop;
+    T ret = defaultValue;
+    Result result = Result::SUCCESS;
+    status_t err = monitor->getProperty(static_cast<int>(id), &prop);
+    if (err != OK) {
+        LOG(DEBUG) << "getProperty(" << id << ")"
+                   << " fails: (" << err << ") " << strerror(-err);
+    } else {
+        ret = static_cast<T>(prop.valueInt64);
+    }
+    switch (err) {
+        case OK:
+            result = Result::SUCCESS;
+            break;
+        case NAME_NOT_FOUND:
+            result = Result::NOT_SUPPORTED;
+            break;
+        default:
+            result = Result::UNKNOWN;
+            break;
+    }
+    callback(result, static_cast<T>(ret));
+    return Void();
+}
+
+Return<void> Health::getChargeCounter(getChargeCounter_cb _hidl_cb) {
+    return GetProperty<int32_t>(&battery_monitor_, BATTERY_PROP_CHARGE_COUNTER, 0, _hidl_cb);
+}
+
+Return<void> Health::getCurrentNow(getCurrentNow_cb _hidl_cb) {
+    return GetProperty<int32_t>(&battery_monitor_, BATTERY_PROP_CURRENT_NOW, 0, _hidl_cb);
+}
+
+Return<void> Health::getCurrentAverage(getCurrentAverage_cb _hidl_cb) {
+    return GetProperty<int32_t>(&battery_monitor_, BATTERY_PROP_CURRENT_AVG, 0, _hidl_cb);
+}
+
+Return<void> Health::getCapacity(getCapacity_cb _hidl_cb) {
+    return GetProperty<int32_t>(&battery_monitor_, BATTERY_PROP_CAPACITY, 0, _hidl_cb);
+}
+
+Return<void> Health::getEnergyCounter(getEnergyCounter_cb _hidl_cb) {
+    return GetProperty<int64_t>(&battery_monitor_, BATTERY_PROP_ENERGY_COUNTER, 0, _hidl_cb);
+}
+
+Return<void> Health::getChargeStatus(getChargeStatus_cb _hidl_cb) {
+    return GetProperty(&battery_monitor_, BATTERY_PROP_BATTERY_STATUS, BatteryStatus::UNKNOWN,
+                       _hidl_cb);
+}
+
+Return<void> Health::getStorageInfo(getStorageInfo_cb _hidl_cb) {
+    // This implementation does not support StorageInfo. An implementation may extend this
+    // class and override this function to support storage info.
+    _hidl_cb(Result::NOT_SUPPORTED, {});
+    return Void();
+}
+
+Return<void> Health::getDiskStats(getDiskStats_cb _hidl_cb) {
+    // This implementation does not support DiskStats. An implementation may extend this
+    // class and override this function to support disk stats.
+    _hidl_cb(Result::NOT_SUPPORTED, {});
+    return Void();
+}
+
+template <typename T, typename Method>
+static inline void GetHealthInfoField(Health* service, Method func, T* out) {
+    *out = T{};
+    std::invoke(func, service, [out](Result result, const T& value) {
+        if (result == Result::SUCCESS) *out = value;
+    });
+}
+
+Return<void> Health::getHealthInfo(getHealthInfo_cb _hidl_cb) {
+    return getHealthInfo_2_1(
+            [&](auto res, const auto& health_info) { _hidl_cb(res, health_info.legacy); });
+}
+
+Return<void> Health::getHealthInfo_2_1(getHealthInfo_2_1_cb _hidl_cb) {
+    battery_monitor_.updateValues();
+
+    HealthInfo health_info = battery_monitor_.getHealthInfo_2_1();
+
+    // Fill in storage infos; these aren't retrieved by BatteryMonitor.
+    GetHealthInfoField(this, &Health::getStorageInfo, &health_info.legacy.storageInfos);
+    GetHealthInfoField(this, &Health::getDiskStats, &health_info.legacy.diskStats);
+
+    // A subclass may want to update health info struct before returning it.
+    UpdateHealthInfo(&health_info);
+
+    _hidl_cb(Result::SUCCESS, health_info);
+    return Void();
+}
+
+Return<void> Health::debug(const hidl_handle& handle, const hidl_vec<hidl_string>&) {
+    if (handle == nullptr || handle->numFds == 0) {
+        return Void();
+    }
+
+    int fd = handle->data[0];
+    battery_monitor_.dumpState(fd);
+    getHealthInfo_2_1([fd](auto res, const auto& info) {
+        android::base::WriteStringToFd("\ngetHealthInfo -> ", fd);
+        if (res == Result::SUCCESS) {
+            android::base::WriteStringToFd(toString(info), fd);
+        } else {
+            android::base::WriteStringToFd(toString(res), fd);
+        }
+        android::base::WriteStringToFd("\n", fd);
+    });
+
+    fsync(fd);
+    return Void();
+}
+
+Return<void> Health::getHealthConfig(getHealthConfig_cb _hidl_cb) {
+    HealthConfig config = {};
+    convertToHealthConfig(healthd_config_.get(), config.battery);
+    config.bootMinCap = static_cast<int32_t>(healthd_config_->boot_min_cap);
+
+    _hidl_cb(Result::SUCCESS, config);
+    return Void();
+}
+
+Return<void> Health::shouldKeepScreenOn(shouldKeepScreenOn_cb _hidl_cb) {
+    if (!healthd_config_->screen_on) {
+        _hidl_cb(Result::NOT_SUPPORTED, true);
+        return Void();
+    }
+
+    Result returned_result = Result::UNKNOWN;
+    bool screen_on = true;
+    getHealthInfo_2_1([&](auto res, const auto& health_info) {
+        returned_result = res;
+        if (returned_result != Result::SUCCESS) return;
+
+        struct BatteryProperties props = {};
+        V1_0::hal_conversion::convertFromHealthInfo(health_info.legacy.legacy, &props);
+        screen_on = healthd_config_->screen_on(&props);
+    });
+    _hidl_cb(returned_result, screen_on);
+    return Void();
+}
+
+//
+// Subclass helpers / overrides
+//
+
+void Health::UpdateHealthInfo(HealthInfo* /* health_info */) {
+    /*
+        // Sample code for a subclass to implement this:
+        // If you need to modify values (e.g. batteryChargeTimeToFullNowSeconds), do it here.
+        health_info->batteryChargeTimeToFullNowSeconds = calculate_charge_time_seconds();
+
+        // If you need to call healthd_board_battery_update:
+        struct BatteryProperties props;
+        convertFromHealthInfo(health_info.legacy.legacy, &props);
+        healthd_board_battery_update(&props);
+        convertToHealthInfo(&props, health_info.legacy.legacy);
+    */
+}
+
+}  // namespace implementation
+}  // namespace V2_1
+}  // namespace health
+}  // namespace hardware
+}  // namespace android
diff --git a/health/utils/libhealth2impl/include/health2impl/BinderHealth.h b/health/utils/libhealth2impl/include/health2impl/BinderHealth.h
new file mode 100644
index 0000000..1da5bd1
--- /dev/null
+++ b/health/utils/libhealth2impl/include/health2impl/BinderHealth.h
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android-base/unique_fd.h>
+#include <android/hardware/health/2.1/IHealth.h>
+#include <healthd/healthd.h>
+
+#include <health2impl/Callback.h>
+#include <health2impl/HalHealthLoop.h>
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+// binderized health HAL implementation.
+class BinderHealth : public HalHealthLoop, public IHealth, public hidl_death_recipient {
+  public:
+    // |impl| should be the passthrough implementation.
+    BinderHealth(const std::string& name, const sp<IHealth>& impl);
+
+    // Methods from ::android::hardware::health::V2_0::IHealth follow.
+    Return<::android::hardware::health::V2_0::Result> registerCallback(
+            const sp<::android::hardware::health::V2_0::IHealthInfoCallback>& callback) override;
+    Return<::android::hardware::health::V2_0::Result> unregisterCallback(
+            const sp<::android::hardware::health::V2_0::IHealthInfoCallback>& callback) override;
+    Return<::android::hardware::health::V2_0::Result> update() override;
+    Return<void> getChargeCounter(getChargeCounter_cb _hidl_cb) override {
+        return service()->getChargeCounter(_hidl_cb);
+    }
+    Return<void> getCurrentNow(getCurrentNow_cb _hidl_cb) override {
+        return service()->getCurrentNow(_hidl_cb);
+    }
+    Return<void> getCurrentAverage(getCurrentAverage_cb _hidl_cb) override {
+        return service()->getCurrentAverage(_hidl_cb);
+    }
+    Return<void> getCapacity(getCapacity_cb _hidl_cb) override {
+        return service()->getCapacity(_hidl_cb);
+    }
+    Return<void> getEnergyCounter(getEnergyCounter_cb _hidl_cb) override {
+        return service()->getEnergyCounter(_hidl_cb);
+    }
+    Return<void> getChargeStatus(getChargeStatus_cb _hidl_cb) override {
+        return service()->getChargeStatus(_hidl_cb);
+    }
+    Return<void> getStorageInfo(getStorageInfo_cb _hidl_cb) override {
+        return service()->getStorageInfo(_hidl_cb);
+    }
+    Return<void> getDiskStats(getDiskStats_cb _hidl_cb) override {
+        return service()->getDiskStats(_hidl_cb);
+    }
+    Return<void> getHealthInfo(getHealthInfo_cb _hidl_cb) override {
+        return service()->getHealthInfo(_hidl_cb);
+    }
+
+    // Methods from ::android::hardware::health::V2_1::IHealth follow.
+    Return<void> getHealthConfig(getHealthConfig_cb _hidl_cb) override {
+        return service()->getHealthConfig(_hidl_cb);
+    }
+    Return<void> getHealthInfo_2_1(getHealthInfo_2_1_cb _hidl_cb) override {
+        return service()->getHealthInfo_2_1(_hidl_cb);
+    }
+    Return<void> shouldKeepScreenOn(shouldKeepScreenOn_cb _hidl_cb) override {
+        return service()->shouldKeepScreenOn(_hidl_cb);
+    }
+
+    // Methods from ::android::hidl::base::V1_0::IBase follow.
+    Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) override {
+        return service()->debug(fd, args);
+    }
+
+    // hidl_death_recipient implementation.
+    void serviceDied(uint64_t cookie, const wp<IBase>& who) override;
+
+    // Called by BinderHealthCallback.
+    void OnHealthInfoChanged(const HealthInfo& health_info) override;
+
+  protected:
+    void Init(struct healthd_config* config) override;
+    int PrepareToWait() override;
+    // A subclass may override this if it wants to handle binder events differently.
+    virtual void BinderEvent(uint32_t epevents);
+
+  private:
+    bool unregisterCallbackInternal(const sp<IBase>& callback);
+    int binder_fd_ = -1;
+    std::mutex callbacks_lock_;
+    std::vector<std::unique_ptr<Callback>> callbacks_;
+};
+
+}  // namespace implementation
+}  // namespace V2_1
+}  // namespace health
+}  // namespace hardware
+}  // namespace android
diff --git a/health/utils/libhealth2impl/include/health2impl/Callback.h b/health/utils/libhealth2impl/include/health2impl/Callback.h
new file mode 100644
index 0000000..a30480b
--- /dev/null
+++ b/health/utils/libhealth2impl/include/health2impl/Callback.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <android/hardware/health/2.1/IHealth.h>
+#include <android/hardware/health/2.1/IHealthInfoCallback.h>
+
+using ::android::sp;
+using ::android::hardware::Return;
+using ::android::hidl::base::V1_0::IBase;
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+// Wraps an IHealthInfoCallback.
+class Callback {
+  public:
+    virtual ~Callback() {}
+    virtual Return<void> Notify(const HealthInfo&) = 0;
+    virtual sp<IBase> Get() = 0;
+};
+
+class Callback_2_0 : public Callback {
+  public:
+    Callback_2_0(const sp<V2_0::IHealthInfoCallback>& callback) : callback_(callback) {}
+    Return<void> Notify(const HealthInfo& info) override {
+        return callback_->healthInfoChanged(info.legacy);
+    }
+    sp<IBase> Get() override { return callback_; }
+
+  private:
+    sp<V2_0::IHealthInfoCallback> callback_;
+};
+
+class Callback_2_1 : public Callback {
+  public:
+    Callback_2_1(const sp<IHealthInfoCallback>& callback) : callback_(callback) {}
+    Return<void> Notify(const HealthInfo& info) override {
+        return callback_->healthInfoChanged_2_1(info);
+    }
+    sp<IBase> Get() override { return callback_; }
+
+  private:
+    sp<IHealthInfoCallback> callback_;
+};
+
+inline std::unique_ptr<Callback> Wrap(const sp<V2_0::IHealthInfoCallback>& callback_2_0) {
+    auto callback_2_1 = IHealthInfoCallback::castFrom(callback_2_0).withDefault(nullptr);
+    if (callback_2_1) return std::make_unique<Callback_2_1>(callback_2_1);
+    return std::make_unique<Callback_2_0>(callback_2_0);
+}
+
+}  // namespace implementation
+}  // namespace V2_1
+}  // namespace health
+}  // namespace hardware
+}  // namespace android
diff --git a/health/utils/libhealth2impl/include/health2impl/HalHealthLoop.h b/health/utils/libhealth2impl/include/health2impl/HalHealthLoop.h
new file mode 100644
index 0000000..d9b5580
--- /dev/null
+++ b/health/utils/libhealth2impl/include/health2impl/HalHealthLoop.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <optional>
+
+#include <android/hardware/health/2.1/IHealth.h>
+#include <health/HealthLoop.h>
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+// An implementation of HealthLoop for using a given health HAL. This is useful
+// for services that opens the passthrough implementation and starts the HealthLoop
+// to periodically poll data from the implementation.
+class HalHealthLoop : public HealthLoop {
+  public:
+    HalHealthLoop(const std::string& name, const sp<IHealth>& service)
+        : instance_name_(name), service_(service) {}
+
+  protected:
+    virtual void Init(struct healthd_config* config) override;
+    virtual void Heartbeat() override;
+    virtual int PrepareToWait() override;
+    virtual void ScheduleBatteryUpdate() override;
+
+    // HealthLoop periodically calls ScheduleBatteryUpdate, which calls
+    // OnHealthInfoChanged callback. A client can override this function to
+    // broadcast the health_info to interested listeners. By default, this
+    // adjust uevents / wakealarm periods.
+    virtual void OnHealthInfoChanged(const HealthInfo& health_info);
+
+    const std::string& instance_name() const { return instance_name_; }
+    const sp<IHealth>& service() const { return service_; }
+    bool charger_online() const { return charger_online_; }
+
+    // Helpers for subclasses to implement OnHealthInfoChanged.
+    void set_charger_online(const HealthInfo& health_info);
+
+  private:
+    const std::string& instance_name_;
+    sp<IHealth> service_;
+    bool charger_online_ = false;
+};
+
+}  // namespace implementation
+}  // namespace V2_1
+}  // namespace health
+}  // namespace hardware
+}  // namespace android
diff --git a/health/utils/libhealth2impl/include/health2impl/Health.h b/health/utils/libhealth2impl/include/health2impl/Health.h
new file mode 100644
index 0000000..853b0cd
--- /dev/null
+++ b/health/utils/libhealth2impl/include/health2impl/Health.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <memory>
+#include <mutex>
+#include <vector>
+
+#include <android-base/unique_fd.h>
+#include <android/hardware/health/2.1/IHealth.h>
+#include <healthd/BatteryMonitor.h>
+#include <hidl/Status.h>
+
+#include <health2impl/Callback.h>
+
+using ::android::sp;
+using ::android::hardware::hidl_string;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hidl::base::V1_0::IBase;
+
+namespace android {
+namespace hardware {
+namespace health {
+namespace V2_1 {
+namespace implementation {
+
+class Health : public IHealth {
+  public:
+    Health(std::unique_ptr<healthd_config>&& config);
+
+    // Methods from ::android::hardware::health::V2_0::IHealth follow.
+    Return<::android::hardware::health::V2_0::Result> registerCallback(
+            const sp<::android::hardware::health::V2_0::IHealthInfoCallback>& callback) override;
+    Return<::android::hardware::health::V2_0::Result> unregisterCallback(
+            const sp<::android::hardware::health::V2_0::IHealthInfoCallback>& callback) override;
+    Return<::android::hardware::health::V2_0::Result> update() override;
+    Return<void> getChargeCounter(getChargeCounter_cb _hidl_cb) override;
+    Return<void> getCurrentNow(getCurrentNow_cb _hidl_cb) override;
+    Return<void> getCurrentAverage(getCurrentAverage_cb _hidl_cb) override;
+    Return<void> getCapacity(getCapacity_cb _hidl_cb) override;
+    Return<void> getEnergyCounter(getEnergyCounter_cb _hidl_cb) override;
+    Return<void> getChargeStatus(getChargeStatus_cb _hidl_cb) override;
+    Return<void> getStorageInfo(getStorageInfo_cb _hidl_cb) override;
+    Return<void> getDiskStats(getDiskStats_cb _hidl_cb) override;
+    Return<void> getHealthInfo(getHealthInfo_cb _hidl_cb) override;
+
+    // Methods from ::android::hardware::health::V2_1::IHealth follow.
+    Return<void> getHealthConfig(getHealthConfig_cb _hidl_cb) override;
+    Return<void> getHealthInfo_2_1(getHealthInfo_2_1_cb _hidl_cb) override;
+    Return<void> shouldKeepScreenOn(shouldKeepScreenOn_cb _hidl_cb) override;
+
+    // Methods from ::android::hidl::base::V1_0::IBase follow.
+    Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) override;
+
+  protected:
+    // A subclass can override this to modify any health info object before
+    // returning to clients. This is similar to healthd_board_battery_update().
+    // By default, it does nothing.
+    virtual void UpdateHealthInfo(HealthInfo* health_info);
+
+  private:
+    bool unregisterCallbackInternal(const sp<IBase>& callback);
+
+    BatteryMonitor battery_monitor_;
+    std::unique_ptr<healthd_config> healthd_config_;
+
+    std::mutex callbacks_lock_;
+    std::vector<std::unique_ptr<Callback>> callbacks_;
+};
+
+}  // namespace implementation
+}  // namespace V2_1
+}  // namespace health
+}  // namespace hardware
+}  // namespace android