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 "ALooper.h"
18 #include "ASensorEventQueue.h"
19 #include "ASensorManager.h"
20 
21 #define LOG_TAG "libsensorndkbridge"
22 #include <aidl/sensors/convert.h>
23 #include <android-base/logging.h>
24 #include <android/binder_auto_utils.h>
25 #include <android/binder_ibinder_platform.h>
26 #include <android/binder_manager.h>
27 #include <android/binder_process.h>
28 #include <android/looper.h>
29 
30 #include <thread>
31 
32 using aidl::android::frameworks::sensorservice::IEventQueue;
33 using aidl::android::frameworks::sensorservice::ISensorManager;
34 using aidl::android::hardware::sensors::SensorInfo;
35 using aidl::android::hardware::sensors::SensorType;
36 using android::BAD_VALUE;
37 using android::Mutex;
38 using android::NO_INIT;
39 using android::OK;
40 using android::status_t;
41 
42 static Mutex gLock;
43 
44 // static
45 ASensorManager *ASensorManager::sInstance = NULL;
46 
47 // static
getInstance()48 ASensorManager *ASensorManager::getInstance() {
49     Mutex::Autolock autoLock(gLock);
50     if (sInstance == NULL) {
51         sInstance = new ASensorManager;
52         if (sInstance->initCheck() != OK) {
53             delete sInstance;
54             sInstance = NULL;
55         }
56     }
57     return sInstance;
58 }
59 
serviceDied(void *)60 void ASensorManager::serviceDied(void*) {
61     LOG(ERROR) << "Sensor service died. Cleanup sensor manager instance!";
62     Mutex::Autolock autoLock(gLock);
63     delete sInstance;
64     sInstance = NULL;
65 }
66 
ASensorManager()67 ASensorManager::ASensorManager()
68     : mInitCheck(NO_INIT) {
69     if (!ABinderProcess_isThreadPoolStarted()) {
70         std::thread([]() {
71             ABinderProcess_joinThreadPool();
72             LOG(ERROR) << "SHOULD NOT EXIT";
73         }).detach();
74         LOG(ERROR) << "The user of libsensorndkbridge did not start a threadpool";
75     }
76     const std::string name = std::string() + ISensorManager::descriptor + "/default";
77     mManager =
78         ISensorManager::fromBinder(ndk::SpAIBinder(AServiceManager_waitForService(name.c_str())));
79     if (mManager != NULL) {
80         mDeathRecipient =
81             ndk::ScopedAIBinder_DeathRecipient(AIBinder_DeathRecipient_new(serviceDied));
82         auto linked =
83             AIBinder_linkToDeath(mManager->asBinder().get(), mDeathRecipient.get(), nullptr);
84         if (linked != OK) {
85             LOG(WARNING) << "Unable to link to sensor service death notifications";
86         } else {
87             LOG(DEBUG) << "Link to sensor service death notification successful";
88             mInitCheck = OK;
89         }
90     }
91 }
92 
initCheck() const93 status_t ASensorManager::initCheck() const {
94     return mInitCheck;
95 }
96 
getSensorList(ASensorList * out)97 int ASensorManager::getSensorList(ASensorList *out) {
98     LOG(VERBOSE) << "ASensorManager::getSensorList";
99 
100     Mutex::Autolock autoLock(mLock);
101 
102     if (mSensorList == NULL) {
103         ndk::ScopedAStatus ret = mManager->getSensorList(&mSensors);
104 
105         if (!ret.isOk()) {
106             LOG(ERROR) << "Failed to get sensor list: " << ret;
107         }
108 
109         mSensorList.reset(new ASensorRef[mSensors.size()]);
110         for (size_t i = 0; i < mSensors.size(); ++i) {
111             mSensorList.get()[i] =
112                 reinterpret_cast<ASensorRef>(&mSensors[i]);
113         }
114     }
115 
116     if (out) {
117         *out = reinterpret_cast<ASensorList>(mSensorList.get());
118     }
119 
120     return mSensors.size();
121 }
122 
getDefaultSensor(int type)123 ASensorRef ASensorManager::getDefaultSensor(int type) {
124     (void)getSensorList(NULL /* list */);
125 
126     ASensorRef defaultSensor = NULL;
127 
128     SensorInfo sensor;
129 
130     ndk::ScopedAStatus ret = mManager->getDefaultSensor(static_cast<SensorType>(type), &sensor);
131 
132     if (!ret.isOk()) {
133         LOG(ERROR) << "Failed to get default sensor of type " << type << " with error: " << ret;
134     }
135 
136     for (size_t i = 0; i < mSensors.size(); ++i) {
137         if (sensor == mSensors[i]) {
138             defaultSensor = reinterpret_cast<ASensorRef>(&mSensors[i]);
139 
140             break;
141         }
142     }
143 
144     return defaultSensor;
145 }
146 
getDefaultSensorEx(int,bool)147 ASensorRef ASensorManager::getDefaultSensorEx(
148         int /* type */, bool /* wakeup */) {
149     // XXX ISensorManager's getDefaultSensorEx() lacks a "wakeup" parameter.
150     return NULL;
151 }
152 
createEventQueue(ALooper * looper,int,ALooper_callbackFunc callback,void * data)153 ASensorEventQueue *ASensorManager::createEventQueue(
154         ALooper *looper,
155         int /* ident */,
156         ALooper_callbackFunc callback,
157         void *data) {
158     LOG(VERBOSE) << "ASensorManager::createEventQueue";
159 
160     std::shared_ptr<ASensorEventQueue> queue =
161         ndk::SharedRefBase::make<ASensorEventQueue>(looper, callback, data);
162 
163     AIBinder_setMinSchedulerPolicy(queue->asBinder().get(), SCHED_FIFO, 98);
164     std::shared_ptr<IEventQueue> eventQueue;
165     ndk::ScopedAStatus ret = mManager->createEventQueue(queue, &eventQueue);
166 
167     if (!ret.isOk()) {
168         LOG(ERROR) << "FAILED to create event queue: " << ret;
169         return NULL;
170     }
171     queue->setImpl(eventQueue);
172 
173     {
174         Mutex::Autolock autoLock(mQueuesLock);
175         mQueues.push_back(queue);
176     }
177 
178     LOG(VERBOSE) << "Returning event queue " << queue.get();
179     return queue.get();
180 }
181 
destroyEventQueue(ASensorEventQueue * queue)182 void ASensorManager::destroyEventQueue(ASensorEventQueue *queue) {
183     LOG(VERBOSE) << "ASensorManager::destroyEventQueue(" << queue << ")";
184 
185     queue->invalidate();
186 
187     {
188         Mutex::Autolock autoLock(mQueuesLock);
189         mQueues.erase(std::remove_if(mQueues.begin(), mQueues.end(),
190                                      [&](const std::shared_ptr<ASensorEventQueue>& ptr) {
191                                          return ptr.get() == queue;
192                                      }),
193                       mQueues.end());
194     }
195 }
196 
197 ////////////////////////////////////////////////////////////////////////////////
198 
ASensorManager_getInstance()199 ASensorManager *ASensorManager_getInstance() {
200     return ASensorManager::getInstance();
201 }
202 
ASensorManager_getInstanceForPackage(const char *)203 ASensorManager *ASensorManager_getInstanceForPackage(
204         const char* /* packageName */) {
205     return ASensorManager::getInstance();
206 }
207 
208 #define RETURN_IF_MANAGER_IS_NULL(x)    \
209     do {                                \
210         if (manager == NULL) {          \
211             return x;                   \
212         }                               \
213     } while (0)
214 
215 #define RETURN_IF_QUEUE_IS_NULL(x)      \
216     do {                                \
217         if (queue == NULL) {            \
218             return x;                   \
219         }                               \
220     } while (0)
221 
222 #define RETURN_IF_SENSOR_IS_NULL(x)     \
223     do {                                \
224         if (sensor == NULL) {           \
225             return x;                   \
226         }                               \
227     } while (0)
228 
ASensorManager_getSensorList(ASensorManager * manager,ASensorList * list)229 int ASensorManager_getSensorList(ASensorManager* manager, ASensorList* list) {
230     RETURN_IF_MANAGER_IS_NULL(BAD_VALUE);
231     return manager->getSensorList(list);
232 }
233 
ASensorManager_getDefaultSensor(ASensorManager * manager,int type)234 ASensor const* ASensorManager_getDefaultSensor(
235         ASensorManager* manager, int type) {
236     RETURN_IF_MANAGER_IS_NULL(NULL);
237 
238     return manager->getDefaultSensor(type);
239 }
240 
241 #if 0
242 ASensor const* ASensorManager_getDefaultSensorEx(
243         ASensorManager* manager, int type, bool wakeUp) {
244     RETURN_IF_MANAGER_IS_NULL(NULL);
245 
246     return manager->getDefaultSensorEx(type, wakeUp);
247 }
248 #endif
249 
ASensorManager_createEventQueue(ASensorManager * manager,ALooper * looper,int ident,ALooper_callbackFunc callback,void * data)250 ASensorEventQueue* ASensorManager_createEventQueue(
251         ASensorManager* manager,
252         ALooper* looper,
253         int ident,
254         ALooper_callbackFunc callback,
255         void* data) {
256     RETURN_IF_MANAGER_IS_NULL(NULL);
257 
258     if (looper == NULL) {
259         return NULL;
260     }
261 
262     return manager->createEventQueue(looper, ident, callback, data);
263 }
264 
ASensorManager_destroyEventQueue(ASensorManager * manager,ASensorEventQueue * queue)265 int ASensorManager_destroyEventQueue(
266         ASensorManager* manager, ASensorEventQueue* queue) {
267     RETURN_IF_MANAGER_IS_NULL(BAD_VALUE);
268     RETURN_IF_QUEUE_IS_NULL(BAD_VALUE);
269 
270     manager->destroyEventQueue(queue);
271     queue = NULL;
272 
273     return OK;
274 }
275 
276 #if 0
277 int ASensorManager_createSharedMemoryDirectChannel(
278         ASensorManager* manager, int fd, size_t size) {
279     RETURN_IF_MANAGER_IS_NULL(BAD_VALUE);
280 
281     return OK;
282 }
283 
284 int ASensorManager_createHardwareBufferDirectChannel(
285         ASensorManager* manager, AHardwareBuffer const * buffer, size_t size) {
286     RETURN_IF_MANAGER_IS_NULL(BAD_VALUE);
287 
288     return OK;
289 }
290 
291 void ASensorManager_destroyDirectChannel(
292         ASensorManager* manager, int channelId) {
293 }
294 
295 int ASensorManager_configureDirectReport(
296         ASensorManager* manager,
297         ASensor const* sensor,
298         int channelId,int rate) {
299     RETURN_IF_MANAGER_IS_NULL(BAD_VALUE);
300     return OK;
301 }
302 #endif
303 
ASensorEventQueue_registerSensor(ASensorEventQueue * queue,ASensor const * sensor,int32_t samplingPeriodUs,int64_t maxBatchReportLatencyUs)304 int ASensorEventQueue_registerSensor(
305         ASensorEventQueue* queue,
306         ASensor const* sensor,
307         int32_t samplingPeriodUs,
308         int64_t maxBatchReportLatencyUs) {
309     LOG(VERBOSE) << "ASensorEventQueue_registerSensor";
310     RETURN_IF_QUEUE_IS_NULL(BAD_VALUE);
311     return queue->registerSensor(
312             sensor, samplingPeriodUs, maxBatchReportLatencyUs);
313 }
314 
ASensorEventQueue_enableSensor(ASensorEventQueue * queue,ASensor const * sensor)315 int ASensorEventQueue_enableSensor(
316         ASensorEventQueue* queue, ASensor const* sensor) {
317     LOG(VERBOSE) << "ASensorEventQueue_enableSensor(queue " << queue << ")";
318     RETURN_IF_QUEUE_IS_NULL(BAD_VALUE);
319     return queue->enableSensor(sensor);
320 }
321 
ASensorEventQueue_disableSensor(ASensorEventQueue * queue,ASensor const * sensor)322 int ASensorEventQueue_disableSensor(
323         ASensorEventQueue* queue, ASensor const* sensor) {
324     LOG(VERBOSE) << "ASensorEventQueue_disableSensor";
325     RETURN_IF_QUEUE_IS_NULL(BAD_VALUE);
326     return queue->disableSensor(sensor);
327 }
328 
ASensorEventQueue_setEventRate(ASensorEventQueue * queue,ASensor const * sensor,int32_t usec)329 int ASensorEventQueue_setEventRate(
330         ASensorEventQueue* queue,
331         ASensor const* sensor,
332         int32_t usec) {
333     RETURN_IF_QUEUE_IS_NULL(BAD_VALUE);
334     return queue->setEventRate(sensor, usec);
335 }
336 
ASensorEventQueue_hasEvents(ASensorEventQueue * queue)337 int ASensorEventQueue_hasEvents(ASensorEventQueue* queue) {
338     RETURN_IF_QUEUE_IS_NULL(BAD_VALUE);
339     return queue->hasEvents();
340 }
341 
ASensorEventQueue_getEvents(ASensorEventQueue * queue,ASensorEvent * events,size_t count)342 ssize_t ASensorEventQueue_getEvents(
343         ASensorEventQueue* queue, ASensorEvent* events, size_t count) {
344     LOG(VERBOSE) << "ASensorEventQueue_getEvents";
345     RETURN_IF_QUEUE_IS_NULL(BAD_VALUE);
346     return queue->getEvents(events, count);
347 }
348 
ASensorEventQueue_requestAdditionalInfoEvents(ASensorEventQueue * queue,bool enable)349 int ASensorEventQueue_requestAdditionalInfoEvents(ASensorEventQueue* queue, bool enable) {
350     RETURN_IF_QUEUE_IS_NULL(BAD_VALUE);
351     return queue->requestAdditionalInfoEvents(enable);
352 }
353 
ASensor_getName(ASensor const * sensor)354 const char *ASensor_getName(ASensor const* sensor) {
355     RETURN_IF_SENSOR_IS_NULL(NULL);
356     return reinterpret_cast<const SensorInfo *>(sensor)->name.c_str();
357 }
358 
ASensor_getVendor(ASensor const * sensor)359 const char *ASensor_getVendor(ASensor const* sensor) {
360     RETURN_IF_SENSOR_IS_NULL(NULL);
361     return reinterpret_cast<const SensorInfo *>(sensor)->vendor.c_str();
362 }
363 
ASensor_getType(ASensor const * sensor)364 int ASensor_getType(ASensor const* sensor) {
365     RETURN_IF_SENSOR_IS_NULL(ASENSOR_TYPE_INVALID);
366     return static_cast<int>(
367             reinterpret_cast<const SensorInfo *>(sensor)->type);
368 }
369 
ASensor_getResolution(ASensor const * sensor)370 float ASensor_getResolution(ASensor const* sensor) {
371     RETURN_IF_SENSOR_IS_NULL(ASENSOR_RESOLUTION_INVALID);
372     return reinterpret_cast<const SensorInfo *>(sensor)->resolution;
373 }
374 
ASensor_getMinDelay(ASensor const * sensor)375 int ASensor_getMinDelay(ASensor const* sensor) {
376     RETURN_IF_SENSOR_IS_NULL(ASENSOR_DELAY_INVALID);
377     return reinterpret_cast<const SensorInfo*>(sensor)->minDelayUs;
378 }
379 
ASensor_getFifoMaxEventCount(ASensor const * sensor)380 int ASensor_getFifoMaxEventCount(ASensor const* sensor) {
381     RETURN_IF_SENSOR_IS_NULL(ASENSOR_FIFO_COUNT_INVALID);
382     return reinterpret_cast<const SensorInfo *>(sensor)->fifoMaxEventCount;
383 }
384 
ASensor_getFifoReservedEventCount(ASensor const * sensor)385 int ASensor_getFifoReservedEventCount(ASensor const* sensor) {
386     RETURN_IF_SENSOR_IS_NULL(ASENSOR_FIFO_COUNT_INVALID);
387     return reinterpret_cast<const SensorInfo *>(sensor)->fifoReservedEventCount;
388 }
389 
ASensor_getStringType(ASensor const * sensor)390 const char* ASensor_getStringType(ASensor const* sensor) {
391     RETURN_IF_SENSOR_IS_NULL(NULL);
392     return reinterpret_cast<const SensorInfo *>(sensor)->typeAsString.c_str();
393 }
394 
ASensor_getMaxRange(ASensor const * sensor)395 extern "C" float ASensor_getMaxRange(ASensor const* sensor) {
396     RETURN_IF_SENSOR_IS_NULL(nanf(""));
397     return reinterpret_cast<const SensorInfo *>(sensor)->maxRange;
398 }
399 
ASensor_getHandle(ASensor const * sensor)400 int ASensor_getHandle(ASensor const* sensor) {
401     RETURN_IF_SENSOR_IS_NULL(ASENSOR_INVALID);
402     return reinterpret_cast<const SensorInfo*>(sensor)->sensorHandle;
403 }
404 
405 #if 0
406 int ASensor_getReportingMode(ASensor const* sensor) {
407     RETURN_IF_SENSOR_IS_NULL(AREPORTING_MODE_INVALID);
408     return 0;
409 }
410 
411 bool ASensor_isWakeUpSensor(ASensor const* sensor) {
412     RETURN_IF_SENSOR_IS_NULL(false);
413     return false;
414 }
415 
416 bool ASensor_isDirectChannelTypeSupported(
417         ASensor const* sensor, int channelType) {
418     RETURN_IF_SENSOR_IS_NULL(false);
419     return false;
420 }
421 
422 int ASensor_getHighestDirectReportRateLevel(ASensor const* sensor) {
423     RETURN_IF_SENSOR_IS_NULL(ASENSOR_DIRECT_RATE_STOP);
424     return 0;
425 }
426 #endif
427 
getTheLooper()428 static ALooper *getTheLooper() {
429     static ALooper *sLooper = NULL;
430 
431     Mutex::Autolock autoLock(gLock);
432     if (sLooper == NULL) {
433         sLooper = new ALooper;
434     }
435 
436     return sLooper;
437 }
438 
439 
ALooper_forThread()440 ALooper *ALooper_forThread() {
441     LOG(VERBOSE) << "ALooper_forThread";
442     return getTheLooper();
443 }
444 
ALooper_prepare(int)445 ALooper *ALooper_prepare(int /* opts */) {
446     LOG(VERBOSE) << "ALooper_prepare";
447     return getTheLooper();
448 }
449 
ALooper_pollOnce(int timeoutMillis,int * outFd,int * outEvents,void ** outData)450 int ALooper_pollOnce(
451         int timeoutMillis, int* outFd, int* outEvents, void** outData) {
452     int res = getTheLooper()->pollOnce(timeoutMillis, outFd, outEvents, outData);
453     LOG(VERBOSE) << "ALooper_pollOnce => " << res;
454     return res;
455 }
456 
ALooper_wake(ALooper * looper)457 void ALooper_wake(ALooper* looper) {
458     LOG(VERBOSE) << "ALooper_wake";
459     looper->wake();
460 }
461