• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 "AidlSensorHalWrapper.h"
18 #include "ISensorsWrapper.h"
19 #include "SensorDeviceUtils.h"
20 #include "android/hardware/sensors/2.0/types.h"
21 
22 #include <aidl/android/hardware/sensors/BnSensorsCallback.h>
23 #include <aidlcommonsupport/NativeHandle.h>
24 #include <android-base/logging.h>
25 #include <android/binder_manager.h>
26 #include <aidl/sensors/convert.h>
27 
28 using ::aidl::android::hardware::sensors::AdditionalInfo;
29 using ::aidl::android::hardware::sensors::DynamicSensorInfo;
30 using ::aidl::android::hardware::sensors::Event;
31 using ::aidl::android::hardware::sensors::ISensors;
32 using ::aidl::android::hardware::sensors::SensorInfo;
33 using ::aidl::android::hardware::sensors::SensorStatus;
34 using ::aidl::android::hardware::sensors::SensorType;
35 using ::android::AidlMessageQueue;
36 using ::android::hardware::EventFlag;
37 using ::android::hardware::sensors::V2_1::implementation::MAX_RECEIVE_BUFFER_EVENT_COUNT;
38 using ::android::hardware::sensors::implementation::convertToStatus;
39 using ::android::hardware::sensors::implementation::convertToSensor;
40 using ::android::hardware::sensors::implementation::convertToSensorEvent;
41 using ::android::hardware::sensors::implementation::convertFromSensorEvent;
42 
43 
44 namespace android {
45 
46 namespace {
47 
serviceDied(void * cookie)48 void serviceDied(void *cookie) {
49     ALOGW("Sensors HAL died, attempting to reconnect.");
50     ((AidlSensorHalWrapper *)cookie)->prepareForReconnect();
51 }
52 
53 template <typename EnumType>
asBaseType(EnumType value)54 constexpr typename std::underlying_type<EnumType>::type asBaseType(EnumType value) {
55     return static_cast<typename std::underlying_type<EnumType>::type>(value);
56 }
57 
58 enum EventQueueFlagBitsInternal : uint32_t {
59     INTERNAL_WAKE = 1 << 16,
60 };
61 
62 } // anonymous namespace
63 
64 class AidlSensorsCallback : public ::aidl::android::hardware::sensors::BnSensorsCallback {
65 public:
AidlSensorsCallback(AidlSensorHalWrapper::SensorDeviceCallback * sensorDeviceCallback)66     AidlSensorsCallback(AidlSensorHalWrapper::SensorDeviceCallback *sensorDeviceCallback)
67           : mSensorDeviceCallback(sensorDeviceCallback) {}
68 
onDynamicSensorsConnected(const std::vector<SensorInfo> & sensorInfos)69     ::ndk::ScopedAStatus onDynamicSensorsConnected(
70             const std::vector<SensorInfo> &sensorInfos) override {
71         std::vector<sensor_t> sensors;
72         for (const SensorInfo &sensorInfo : sensorInfos) {
73             sensor_t sensor;
74             convertToSensor(sensorInfo, &sensor);
75             sensors.push_back(sensor);
76         }
77 
78         mSensorDeviceCallback->onDynamicSensorsConnected(sensors);
79         return ::ndk::ScopedAStatus::ok();
80     }
81 
onDynamicSensorsDisconnected(const std::vector<int32_t> & sensorHandles)82     ::ndk::ScopedAStatus onDynamicSensorsDisconnected(
83             const std::vector<int32_t> &sensorHandles) override {
84         mSensorDeviceCallback->onDynamicSensorsDisconnected(sensorHandles);
85         return ::ndk::ScopedAStatus::ok();
86     }
87 
88 private:
89     ISensorHalWrapper::SensorDeviceCallback *mSensorDeviceCallback;
90 };
91 
AidlSensorHalWrapper()92 AidlSensorHalWrapper::AidlSensorHalWrapper()
93       : mEventQueueFlag(nullptr),
94         mWakeLockQueueFlag(nullptr),
95         mDeathRecipient(AIBinder_DeathRecipient_new(serviceDied)) {}
96 
supportsPolling()97 bool AidlSensorHalWrapper::supportsPolling() {
98     return false;
99 }
100 
supportsMessageQueues()101 bool AidlSensorHalWrapper::supportsMessageQueues() {
102     return true;
103 }
104 
connect(SensorDeviceCallback * callback)105 bool AidlSensorHalWrapper::connect(SensorDeviceCallback *callback) {
106     mSensorDeviceCallback = callback;
107     mSensors = nullptr;
108 
109     auto aidlServiceName = std::string() + ISensors::descriptor + "/default";
110     if (AServiceManager_isDeclared(aidlServiceName.c_str())) {
111         if (mSensors != nullptr) {
112             AIBinder_unlinkToDeath(mSensors->asBinder().get(), mDeathRecipient.get(), this);
113         }
114 
115         ndk::SpAIBinder binder(AServiceManager_waitForService(aidlServiceName.c_str()));
116         if (binder.get() != nullptr) {
117             mSensors = ISensors::fromBinder(binder);
118             mEventQueue = std::make_unique<AidlMessageQueue<
119                     Event, SynchronizedReadWrite>>(MAX_RECEIVE_BUFFER_EVENT_COUNT,
120                                                    /*configureEventFlagWord=*/true);
121 
122             mWakeLockQueue = std::make_unique<AidlMessageQueue<
123                     int32_t, SynchronizedReadWrite>>(MAX_RECEIVE_BUFFER_EVENT_COUNT,
124                                                      /*configureEventFlagWord=*/true);
125             if (mEventQueueFlag != nullptr) {
126                 EventFlag::deleteEventFlag(&mEventQueueFlag);
127             }
128             EventFlag::createEventFlag(mEventQueue->getEventFlagWord(), &mEventQueueFlag);
129             if (mWakeLockQueueFlag != nullptr) {
130                 EventFlag::deleteEventFlag(&mWakeLockQueueFlag);
131             }
132             EventFlag::createEventFlag(mWakeLockQueue->getEventFlagWord(), &mWakeLockQueueFlag);
133 
134             CHECK(mEventQueue != nullptr && mEventQueueFlag != nullptr &&
135                   mWakeLockQueue != nullptr && mWakeLockQueueFlag != nullptr);
136 
137             mCallback = ndk::SharedRefBase::make<AidlSensorsCallback>(mSensorDeviceCallback);
138             mSensors->initialize(mEventQueue->dupeDesc(), mWakeLockQueue->dupeDesc(), mCallback);
139 
140             AIBinder_linkToDeath(mSensors->asBinder().get(), mDeathRecipient.get(), this);
141         } else {
142             ALOGE("Could not connect to declared sensors AIDL HAL");
143         }
144     }
145 
146     return mSensors != nullptr;
147 }
148 
prepareForReconnect()149 void AidlSensorHalWrapper::prepareForReconnect() {
150     mReconnecting = true;
151     if (mEventQueueFlag != nullptr) {
152         mEventQueueFlag->wake(asBaseType(INTERNAL_WAKE));
153     }
154 }
155 
poll(sensors_event_t *,size_t)156 ssize_t AidlSensorHalWrapper::poll(sensors_event_t * /* buffer */, size_t /* count */) {
157     return 0;
158 }
159 
pollFmq(sensors_event_t * buffer,size_t maxNumEventsToRead)160 ssize_t AidlSensorHalWrapper::pollFmq(sensors_event_t *buffer, size_t maxNumEventsToRead) {
161     ssize_t eventsRead = 0;
162     size_t availableEvents = mEventQueue->availableToRead();
163 
164     if (availableEvents == 0) {
165         uint32_t eventFlagState = 0;
166 
167         // Wait for events to become available. This is necessary so that the Event FMQ's read() is
168         // able to be called with the correct number of events to read. If the specified number of
169         // events is not available, then read() would return no events, possibly introducing
170         // additional latency in delivering events to applications.
171         if (mEventQueueFlag != nullptr) {
172             mEventQueueFlag->wait(asBaseType(ISensors::EVENT_QUEUE_FLAG_BITS_READ_AND_PROCESS) |
173                                           asBaseType(INTERNAL_WAKE),
174                                   &eventFlagState);
175         }
176         availableEvents = mEventQueue->availableToRead();
177 
178         if ((eventFlagState & asBaseType(INTERNAL_WAKE)) && mReconnecting) {
179             ALOGD("Event FMQ internal wake, returning from poll with no events");
180             return DEAD_OBJECT;
181         }
182     }
183 
184     size_t eventsToRead = std::min({availableEvents, maxNumEventsToRead, mEventBuffer.size()});
185     if (eventsToRead > 0) {
186         if (mEventQueue->read(mEventBuffer.data(), eventsToRead)) {
187             // Notify the Sensors HAL that sensor events have been read. This is required to support
188             // the use of writeBlocking by the Sensors HAL.
189             if (mEventQueueFlag != nullptr) {
190                 mEventQueueFlag->wake(asBaseType(ISensors::EVENT_QUEUE_FLAG_BITS_EVENTS_READ));
191             }
192 
193             for (size_t i = 0; i < eventsToRead; i++) {
194                 convertToSensorEvent(mEventBuffer[i], &buffer[i]);
195             }
196             eventsRead = eventsToRead;
197         } else {
198             ALOGW("Failed to read %zu events, currently %zu events available", eventsToRead,
199                   availableEvents);
200         }
201     }
202 
203     return eventsRead;
204 }
205 
getSensorsList()206 std::vector<sensor_t> AidlSensorHalWrapper::getSensorsList() {
207     std::vector<sensor_t> sensorsFound;
208 
209     if (mSensors != nullptr) {
210         std::vector<SensorInfo> list;
211         mSensors->getSensorsList(&list);
212         for (size_t i = 0; i < list.size(); i++) {
213             sensor_t sensor;
214             convertToSensor(list[i], &sensor);
215             sensorsFound.push_back(sensor);
216         }
217     }
218 
219     return sensorsFound;
220 }
221 
setOperationMode(SensorService::Mode mode)222 status_t AidlSensorHalWrapper::setOperationMode(SensorService::Mode mode) {
223     if (mSensors == nullptr) return NO_INIT;
224     return convertToStatus(mSensors->setOperationMode(static_cast<ISensors::OperationMode>(mode)));
225 }
226 
activate(int32_t sensorHandle,bool enabled)227 status_t AidlSensorHalWrapper::activate(int32_t sensorHandle, bool enabled) {
228     if (mSensors == nullptr) return NO_INIT;
229     return convertToStatus(mSensors->activate(sensorHandle, enabled));
230 }
231 
batch(int32_t sensorHandle,int64_t samplingPeriodNs,int64_t maxReportLatencyNs)232 status_t AidlSensorHalWrapper::batch(int32_t sensorHandle, int64_t samplingPeriodNs,
233                                      int64_t maxReportLatencyNs) {
234     if (mSensors == nullptr) return NO_INIT;
235     return convertToStatus(mSensors->batch(sensorHandle, samplingPeriodNs, maxReportLatencyNs));
236 }
237 
flush(int32_t sensorHandle)238 status_t AidlSensorHalWrapper::flush(int32_t sensorHandle) {
239     if (mSensors == nullptr) return NO_INIT;
240     return convertToStatus(mSensors->flush(sensorHandle));
241 }
242 
injectSensorData(const sensors_event_t * event)243 status_t AidlSensorHalWrapper::injectSensorData(const sensors_event_t *event) {
244     if (mSensors == nullptr) return NO_INIT;
245 
246     Event ev;
247     convertFromSensorEvent(*event, &ev);
248     return convertToStatus(mSensors->injectSensorData(ev));
249 }
250 
registerDirectChannel(const sensors_direct_mem_t * memory,int32_t * channelHandle)251 status_t AidlSensorHalWrapper::registerDirectChannel(const sensors_direct_mem_t *memory,
252                                                      int32_t *channelHandle) {
253     if (mSensors == nullptr) return NO_INIT;
254 
255     ISensors::SharedMemInfo::SharedMemType type;
256     switch (memory->type) {
257         case SENSOR_DIRECT_MEM_TYPE_ASHMEM:
258             type = ISensors::SharedMemInfo::SharedMemType::ASHMEM;
259             break;
260         case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
261             type = ISensors::SharedMemInfo::SharedMemType::GRALLOC;
262             break;
263         default:
264             return BAD_VALUE;
265     }
266 
267     if (memory->format != SENSOR_DIRECT_FMT_SENSORS_EVENT) {
268         return BAD_VALUE;
269     }
270     ISensors::SharedMemInfo::SharedMemFormat format =
271             ISensors::SharedMemInfo::SharedMemFormat::SENSORS_EVENT;
272 
273     ISensors::SharedMemInfo mem = {
274             .type = type,
275             .format = format,
276             .size = static_cast<int32_t>(memory->size),
277             .memoryHandle = dupToAidl(memory->handle),
278     };
279 
280     return convertToStatus(mSensors->registerDirectChannel(mem, channelHandle));
281 }
282 
unregisterDirectChannel(int32_t channelHandle)283 status_t AidlSensorHalWrapper::unregisterDirectChannel(int32_t channelHandle) {
284     if (mSensors == nullptr) return NO_INIT;
285     return convertToStatus(mSensors->unregisterDirectChannel(channelHandle));
286 }
287 
configureDirectChannel(int32_t sensorHandle,int32_t channelHandle,const struct sensors_direct_cfg_t * config)288 status_t AidlSensorHalWrapper::configureDirectChannel(int32_t sensorHandle, int32_t channelHandle,
289                                                       const struct sensors_direct_cfg_t *config) {
290     if (mSensors == nullptr) return NO_INIT;
291 
292     ISensors::RateLevel rate;
293     switch (config->rate_level) {
294         case SENSOR_DIRECT_RATE_STOP:
295             rate = ISensors::RateLevel::STOP;
296             break;
297         case SENSOR_DIRECT_RATE_NORMAL:
298             rate = ISensors::RateLevel::NORMAL;
299             break;
300         case SENSOR_DIRECT_RATE_FAST:
301             rate = ISensors::RateLevel::FAST;
302             break;
303         case SENSOR_DIRECT_RATE_VERY_FAST:
304             rate = ISensors::RateLevel::VERY_FAST;
305             break;
306         default:
307             return BAD_VALUE;
308     }
309 
310     int32_t token;
311     status_t status = convertToStatus(
312         mSensors->configDirectReport(sensorHandle, channelHandle, rate, &token));
313     if (status == OK && rate != ISensors::RateLevel::STOP) {
314         status = static_cast<status_t>(token);
315     }
316     return status;
317 }
318 
writeWakeLockHandled(uint32_t count)319 void AidlSensorHalWrapper::writeWakeLockHandled(uint32_t count) {
320     int signedCount = (int)count;
321     if (mWakeLockQueue->write(&signedCount)) {
322         mWakeLockQueueFlag->wake(asBaseType(ISensors::WAKE_LOCK_QUEUE_FLAG_BITS_DATA_WRITTEN));
323     } else {
324         ALOGW("Failed to write wake lock handled");
325     }
326 }
327 
328 } // namespace android
329