1 /*
2  * Copyright (C) 2017 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 "SensorDeviceUtils.h"
18 
19 #include <android/hardware/sensors/1.0/ISensors.h>
20 #include <utils/Log.h>
21 
22 #include <chrono>
23 #include <thread>
24 
25 using ::android::hardware::Void;
26 using namespace android::hardware::sensors::V1_0;
27 
28 namespace android {
29 namespace SensorDeviceUtils {
30 
HidlServiceRegistrationWaiter()31 HidlServiceRegistrationWaiter::HidlServiceRegistrationWaiter() {
32 }
33 
onFirstRef()34 void HidlServiceRegistrationWaiter::onFirstRef() {
35     // Creating sp<...>(this) in the constructor should be avoided, hence
36     // registerForNotifications is called in onFirstRef callback.
37     mRegistered = ISensors::registerForNotifications("default", this);
38 }
39 
onRegistration(const hidl_string & fqName,const hidl_string & name,bool preexisting)40 Return<void> HidlServiceRegistrationWaiter::onRegistration(
41         const hidl_string &fqName, const hidl_string &name, bool preexisting) {
42     ALOGV("onRegistration fqName %s, name %s, preexisting %d",
43           fqName.c_str(), name.c_str(), preexisting);
44 
45     {
46         std::lock_guard<std::mutex> lk(mLock);
47         mRestartObserved = true;
48     }
49     mCondition.notify_all();
50     return Void();
51 }
52 
reset()53 void HidlServiceRegistrationWaiter::reset() {
54     std::lock_guard<std::mutex> lk(mLock);
55     mRestartObserved = false;
56 }
57 
wait()58 bool HidlServiceRegistrationWaiter::wait() {
59     constexpr int DEFAULT_WAIT_MS = 100;
60     constexpr int TIMEOUT_MS = 1000;
61 
62     if (!mRegistered) {
63         ALOGW("Cannot register service notification, use default wait(%d ms)", DEFAULT_WAIT_MS);
64         std::this_thread::sleep_for(std::chrono::milliseconds(DEFAULT_WAIT_MS));
65         // not sure if service is actually restarted
66         return false;
67     }
68 
69     std::unique_lock<std::mutex> lk(mLock);
70     return mCondition.wait_for(lk, std::chrono::milliseconds(TIMEOUT_MS),
71             [this]{return mRestartObserved;});
72 }
73 
74 } // namespace SensorDeviceUtils
75 } // namespace android
76