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