MH2 | Implement ScopeWakelock ctor and dtor

Put the ScopedWakelock class into its own header and its implementation
into its own cpp. Implement the refcounting of the wakelocks. However,
do not incorporate the wakelock handling into post events in halproxy
yet.

Bug: 136511617
Test: No new tests yet. Will add more in a later patchset once more
fleshed out and integrated with postEvents.
Change-Id: I0815c6a6659ec5933b799294956595b11e7bf1b3
diff --git a/sensors/2.0/multihal/HalProxy.cpp b/sensors/2.0/multihal/HalProxy.cpp
index 5a45a44..81d1b64 100644
--- a/sensors/2.0/multihal/HalProxy.cpp
+++ b/sensors/2.0/multihal/HalProxy.cpp
@@ -20,6 +20,8 @@
 
 #include <android/hardware/sensors/2.0/types.h>
 
+#include "hardware_legacy/power.h"
+
 #include <dlfcn.h>
 
 #include <fstream>
@@ -36,10 +38,6 @@
 
 typedef ISensorsSubHal*(SensorsHalGetSubHalFunc)(uint32_t*);
 
-ScopedWakelock::ScopedWakelock() {
-    // TODO: Implement
-}
-
 HalProxy::HalProxy() {
     const char* kMultiHalConfigFile = "/vendor/etc/sensors/hals.conf";
     initializeSubHalListFromConfigFile(kMultiHalConfigFile);
@@ -277,6 +275,25 @@
     }
 }
 
+// TODO: Implement the wakelock timeout in these next two methods. Also pass in the subhal
+// index for better tracking.
+
+void HalProxy::incrementRefCountAndMaybeAcquireWakelock() {
+    std::lock_guard<std::mutex> lockGuard(mWakelockRefCountMutex);
+    if (mWakelockRefCount == 0) {
+        acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLockName);
+    }
+    mWakelockRefCount++;
+}
+
+void HalProxy::decrementRefCountAndMaybeReleaseWakelock() {
+    std::lock_guard<std::mutex> lockGuard(mWakelockRefCountMutex);
+    mWakelockRefCount--;
+    if (mWakelockRefCount == 0) {
+        release_wake_lock(kWakeLockName);
+    }
+}
+
 void HalProxy::setDirectChannelFlags(SensorInfo* sensorInfo, ISensorsSubHal* subHal) {
     bool sensorSupportsDirectChannel =
             (sensorInfo->flags & (V1_0::SensorFlagBits::MASK_DIRECT_REPORT |
@@ -319,8 +336,7 @@
 }
 
 ScopedWakelock HalProxyCallback::createScopedWakelock(bool lock) {
-    ScopedWakelock wakelock;
-    wakelock.mLocked = lock;
+    ScopedWakelock wakelock(mHalProxy, lock);
     return wakelock;
 }