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 
17 #ifndef ANDROID_HARDWARE_SENSORS_V2_X_SENSORS_H
18 #define ANDROID_HARDWARE_SENSORS_V2_X_SENSORS_H
19 
20 #include "EventMessageQueueWrapper.h"
21 #include "Sensor.h"
22 
23 #include <android/hardware/sensors/2.0/ISensors.h>
24 #include <android/hardware/sensors/2.0/types.h>
25 #include <fmq/MessageQueue.h>
26 #include <hardware_legacy/power.h>
27 #include <hidl/MQDescriptor.h>
28 #include <hidl/Status.h>
29 #include <log/log.h>
30 
31 #include <atomic>
32 #include <memory>
33 #include <thread>
34 
35 namespace android {
36 namespace hardware {
37 namespace sensors {
38 namespace V2_X {
39 namespace implementation {
40 
41 template <class ISensorsInterface>
42 struct Sensors : public ISensorsInterface, public ISensorsEventCallback {
43     using Event = ::android::hardware::sensors::V1_0::Event;
44     using OperationMode = ::android::hardware::sensors::V1_0::OperationMode;
45     using RateLevel = ::android::hardware::sensors::V1_0::RateLevel;
46     using Result = ::android::hardware::sensors::V1_0::Result;
47     using SharedMemInfo = ::android::hardware::sensors::V1_0::SharedMemInfo;
48     using EventQueueFlagBits = ::android::hardware::sensors::V2_0::EventQueueFlagBits;
49     using SensorTimeout = ::android::hardware::sensors::V2_0::SensorTimeout;
50     using WakeLockQueueFlagBits = ::android::hardware::sensors::V2_0::WakeLockQueueFlagBits;
51     using ISensorsCallback = ::android::hardware::sensors::V2_0::ISensorsCallback;
52     using EventMessageQueue = MessageQueue<Event, kSynchronizedReadWrite>;
53     using WakeLockMessageQueue = MessageQueue<uint32_t, kSynchronizedReadWrite>;
54 
55     static constexpr const char* kWakeLockName = "SensorsHAL_WAKEUP";
56 
SensorsSensors57     Sensors()
58         : mEventQueueFlag(nullptr),
59           mNextHandle(1),
60           mOutstandingWakeUpEvents(0),
61           mReadWakeLockQueueRun(false),
62           mAutoReleaseWakeLockTime(0),
63           mHasWakeLock(false) {
64         AddSensor<AccelSensor>();
65         AddSensor<GyroSensor>();
66         AddSensor<AmbientTempSensor>();
67         AddSensor<DeviceTempSensor>();
68         AddSensor<PressureSensor>();
69         AddSensor<MagnetometerSensor>();
70         AddSensor<LightSensor>();
71         AddSensor<ProximitySensor>();
72         AddSensor<RelativeHumiditySensor>();
73     }
74 
~SensorsSensors75     virtual ~Sensors() {
76         deleteEventFlag();
77         mReadWakeLockQueueRun = false;
78         mWakeLockThread.join();
79     }
80 
81     // Methods from ::android::hardware::sensors::V2_0::ISensors follow.
getSensorsListSensors82     Return<void> getSensorsList(V2_0::ISensors::getSensorsList_cb _hidl_cb) override {
83         std::vector<V1_0::SensorInfo> sensors;
84         for (const auto& sensor : mSensors) {
85             sensors.push_back(
86                     V2_1::implementation::convertToOldSensorInfo(sensor.second->getSensorInfo()));
87         }
88 
89         // Call the HIDL callback with the SensorInfo
90         _hidl_cb(sensors);
91 
92         return Void();
93     }
94 
setOperationModeSensors95     Return<Result> setOperationMode(OperationMode mode) override {
96         for (auto sensor : mSensors) {
97             sensor.second->setOperationMode(mode);
98         }
99         return Result::OK;
100     }
101 
activateSensors102     Return<Result> activate(int32_t sensorHandle, bool enabled) override {
103         auto sensor = mSensors.find(sensorHandle);
104         if (sensor != mSensors.end()) {
105             sensor->second->activate(enabled);
106             return Result::OK;
107         }
108         return Result::BAD_VALUE;
109     }
110 
initializeSensors111     Return<Result> initialize(
112             const ::android::hardware::MQDescriptorSync<Event>& eventQueueDescriptor,
113             const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
114             const sp<ISensorsCallback>& sensorsCallback) override {
115         auto eventQueue =
116                 std::make_unique<EventMessageQueue>(eventQueueDescriptor, true /* resetPointers */);
117         std::unique_ptr<V2_1::implementation::EventMessageQueueWrapperBase> wrapper =
118                 std::make_unique<V2_1::implementation::EventMessageQueueWrapperV1_0>(eventQueue);
119         return initializeBase(wrapper, wakeLockDescriptor, sensorsCallback);
120     }
121 
initializeBaseSensors122     Return<Result> initializeBase(
123             std::unique_ptr<V2_1::implementation::EventMessageQueueWrapperBase>& eventQueue,
124             const ::android::hardware::MQDescriptorSync<uint32_t>& wakeLockDescriptor,
125             const sp<ISensorsCallback>& sensorsCallback) {
126         Result result = Result::OK;
127 
128         // Ensure that all sensors are disabled
129         for (auto sensor : mSensors) {
130             sensor.second->activate(false /* enable */);
131         }
132 
133         // Stop the Wake Lock thread if it is currently running
134         if (mReadWakeLockQueueRun.load()) {
135             mReadWakeLockQueueRun = false;
136             mWakeLockThread.join();
137         }
138 
139         // Save a reference to the callback
140         mCallback = sensorsCallback;
141 
142         // Save the event queue.
143         mEventQueue = std::move(eventQueue);
144 
145         // Ensure that any existing EventFlag is properly deleted
146         deleteEventFlag();
147 
148         // Create the EventFlag that is used to signal to the framework that sensor events have been
149         // written to the Event FMQ
150         if (EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag) != OK) {
151             result = Result::BAD_VALUE;
152         }
153 
154         // Create the Wake Lock FMQ that is used by the framework to communicate whenever WAKE_UP
155         // events have been successfully read and handled by the framework.
156         mWakeLockQueue = std::make_unique<WakeLockMessageQueue>(wakeLockDescriptor,
157                                                                 true /* resetPointers */);
158 
159         if (!mCallback || !mEventQueue || !mWakeLockQueue || mEventQueueFlag == nullptr) {
160             result = Result::BAD_VALUE;
161         }
162 
163         // Start the thread to read events from the Wake Lock FMQ
164         mReadWakeLockQueueRun = true;
165         mWakeLockThread = std::thread(startReadWakeLockThread, this);
166 
167         return result;
168     }
169 
batchSensors170     Return<Result> batch(int32_t sensorHandle, int64_t samplingPeriodNs,
171                          int64_t /* maxReportLatencyNs */) override {
172         auto sensor = mSensors.find(sensorHandle);
173         if (sensor != mSensors.end()) {
174             sensor->second->batch(samplingPeriodNs);
175             return Result::OK;
176         }
177         return Result::BAD_VALUE;
178     }
179 
flushSensors180     Return<Result> flush(int32_t sensorHandle) override {
181         auto sensor = mSensors.find(sensorHandle);
182         if (sensor != mSensors.end()) {
183             return sensor->second->flush();
184         }
185         return Result::BAD_VALUE;
186     }
187 
injectSensorDataSensors188     Return<Result> injectSensorData(const Event& event) override {
189         auto sensor = mSensors.find(event.sensorHandle);
190         if (sensor != mSensors.end()) {
191             return sensor->second->injectEvent(V2_1::implementation::convertToNewEvent(event));
192         }
193 
194         return Result::BAD_VALUE;
195     }
196 
registerDirectChannelSensors197     Return<void> registerDirectChannel(const SharedMemInfo& /* mem */,
198                                        V2_0::ISensors::registerDirectChannel_cb _hidl_cb) override {
199         _hidl_cb(Result::INVALID_OPERATION, -1 /* channelHandle */);
200         return Return<void>();
201     }
202 
unregisterDirectChannelSensors203     Return<Result> unregisterDirectChannel(int32_t /* channelHandle */) override {
204         return Result::INVALID_OPERATION;
205     }
206 
configDirectReportSensors207     Return<void> configDirectReport(int32_t /* sensorHandle */, int32_t /* channelHandle */,
208                                     RateLevel /* rate */,
209                                     V2_0::ISensors::configDirectReport_cb _hidl_cb) override {
210         _hidl_cb(Result::INVALID_OPERATION, 0 /* reportToken */);
211         return Return<void>();
212     }
213 
postEventsSensors214     void postEvents(const std::vector<V2_1::Event>& events, bool wakeup) override {
215         std::lock_guard<std::mutex> lock(mWriteLock);
216         if (mEventQueue->write(events)) {
217             mEventQueueFlag->wake(static_cast<uint32_t>(EventQueueFlagBits::READ_AND_PROCESS));
218 
219             if (wakeup) {
220                 // Keep track of the number of outstanding WAKE_UP events in order to properly hold
221                 // a wake lock until the framework has secured a wake lock
222                 updateWakeLock(events.size(), 0 /* eventsHandled */);
223             }
224         }
225     }
226 
227   protected:
228     /**
229      * Add a new sensor
230      */
231     template <class SensorType>
AddSensorSensors232     void AddSensor() {
233         std::shared_ptr<SensorType> sensor =
234                 std::make_shared<SensorType>(mNextHandle++ /* sensorHandle */, this /* callback */);
235         mSensors[sensor->getSensorInfo().sensorHandle] = sensor;
236     }
237 
238     /**
239      * Utility function to delete the Event Flag
240      */
deleteEventFlagSensors241     void deleteEventFlag() {
242         status_t status = EventFlag::deleteEventFlag(&mEventQueueFlag);
243         if (status != OK) {
244             ALOGI("Failed to delete event flag: %d", status);
245         }
246     }
247 
startReadWakeLockThreadSensors248     static void startReadWakeLockThread(Sensors* sensors) { sensors->readWakeLockFMQ(); }
249 
250     /**
251      * Function to read the Wake Lock FMQ and release the wake lock when appropriate
252      */
readWakeLockFMQSensors253     void readWakeLockFMQ() {
254         while (mReadWakeLockQueueRun.load()) {
255             constexpr int64_t kReadTimeoutNs = 500 * 1000 * 1000;  // 500 ms
256             uint32_t eventsHandled = 0;
257 
258             // Read events from the Wake Lock FMQ. Timeout after a reasonable amount of time to
259             // ensure that any held wake lock is able to be released if it is held for too long.
260             mWakeLockQueue->readBlocking(&eventsHandled, 1 /* count */, 0 /* readNotification */,
261                                          static_cast<uint32_t>(WakeLockQueueFlagBits::DATA_WRITTEN),
262                                          kReadTimeoutNs);
263             updateWakeLock(0 /* eventsWritten */, eventsHandled);
264         }
265     }
266 
267     /**
268      * Responsible for acquiring and releasing a wake lock when there are unhandled WAKE_UP events
269      */
updateWakeLockSensors270     void updateWakeLock(int32_t eventsWritten, int32_t eventsHandled) {
271         std::lock_guard<std::mutex> lock(mWakeLockLock);
272         int32_t newVal = mOutstandingWakeUpEvents + eventsWritten - eventsHandled;
273         if (newVal < 0) {
274             mOutstandingWakeUpEvents = 0;
275         } else {
276             mOutstandingWakeUpEvents = newVal;
277         }
278 
279         if (eventsWritten > 0) {
280             // Update the time at which the last WAKE_UP event was sent
281             mAutoReleaseWakeLockTime =
282                     ::android::uptimeMillis() +
283                     static_cast<uint32_t>(SensorTimeout::WAKE_LOCK_SECONDS) * 1000;
284         }
285 
286         if (!mHasWakeLock && mOutstandingWakeUpEvents > 0 &&
287             acquire_wake_lock(PARTIAL_WAKE_LOCK, kWakeLockName) == 0) {
288             mHasWakeLock = true;
289         } else if (mHasWakeLock) {
290             // Check if the wake lock should be released automatically if
291             // SensorTimeout::WAKE_LOCK_SECONDS has elapsed since the last WAKE_UP event was written
292             // to the Wake Lock FMQ.
293             if (::android::uptimeMillis() > mAutoReleaseWakeLockTime) {
294                 ALOGD("No events read from wake lock FMQ for %d seconds, auto releasing wake lock",
295                       SensorTimeout::WAKE_LOCK_SECONDS);
296                 mOutstandingWakeUpEvents = 0;
297             }
298 
299             if (mOutstandingWakeUpEvents == 0 && release_wake_lock(kWakeLockName) == 0) {
300                 mHasWakeLock = false;
301             }
302         }
303     }
304 
305     /**
306      * The Event FMQ where sensor events are written
307      */
308     std::unique_ptr<V2_1::implementation::EventMessageQueueWrapperBase> mEventQueue;
309 
310     /**
311      * The Wake Lock FMQ that is read to determine when the framework has handled WAKE_UP events
312      */
313     std::unique_ptr<WakeLockMessageQueue> mWakeLockQueue;
314 
315     /**
316      * Event Flag to signal to the framework when sensor events are available to be read
317      */
318     EventFlag* mEventQueueFlag;
319 
320     /**
321      * Callback for asynchronous events, such as dynamic sensor connections.
322      */
323     sp<ISensorsCallback> mCallback;
324 
325     /**
326      * A map of the available sensors
327      */
328     std::map<int32_t, std::shared_ptr<Sensor>> mSensors;
329 
330     /**
331      * The next available sensor handle
332      */
333     int32_t mNextHandle;
334 
335     /**
336      * Lock to protect writes to the FMQs
337      */
338     std::mutex mWriteLock;
339 
340     /**
341      * Lock to protect acquiring and releasing the wake lock
342      */
343     std::mutex mWakeLockLock;
344 
345     /**
346      * Track the number of WAKE_UP events that have not been handled by the framework
347      */
348     uint32_t mOutstandingWakeUpEvents;
349 
350     /**
351      * A thread to read the Wake Lock FMQ
352      */
353     std::thread mWakeLockThread;
354 
355     /**
356      * Flag to indicate that the Wake Lock Thread should continue to run
357      */
358     std::atomic_bool mReadWakeLockQueueRun;
359 
360     /**
361      * Track the time when the wake lock should automatically be released
362      */
363     int64_t mAutoReleaseWakeLockTime;
364 
365     /**
366      * Flag to indicate if a wake lock has been acquired
367      */
368     bool mHasWakeLock;
369 };
370 
371 }  // namespace implementation
372 }  // namespace V2_X
373 }  // namespace sensors
374 }  // namespace hardware
375 }  // namespace android
376 
377 #endif  // ANDROID_HARDWARE_SENSORS_V2_X_SENSORS_H
378