SensorManager.cpp revision d9c8a864e193d7ae3d0a04c1aa7ff15da955fb0f
1/*
2 * Copyright (C) 2010 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#define LOG_TAG "Sensors"
18
19#include <sensor/SensorManager.h>
20
21#include <stdint.h>
22#include <sys/types.h>
23
24#include <cutils/native_handle.h>
25#include <utils/Errors.h>
26#include <utils/RefBase.h>
27#include <utils/Singleton.h>
28
29#include <binder/IBinder.h>
30#include <binder/IServiceManager.h>
31
32#include <sensor/ISensorServer.h>
33#include <sensor/ISensorEventConnection.h>
34#include <sensor/Sensor.h>
35#include <sensor/SensorEventQueue.h>
36
37// ----------------------------------------------------------------------------
38namespace android {
39// ----------------------------------------------------------------------------
40
41android::Mutex android::SensorManager::sLock;
42std::map<String16, SensorManager*> android::SensorManager::sPackageInstances;
43
44SensorManager& SensorManager::getInstanceForPackage(const String16& packageName) {
45    Mutex::Autolock _l(sLock);
46    SensorManager* sensorManager;
47    std::map<String16, SensorManager*>::iterator iterator =
48        sPackageInstances.find(packageName);
49
50    if (iterator != sPackageInstances.end()) {
51        sensorManager = iterator->second;
52    } else {
53        String16 opPackageName = packageName;
54
55        // It is possible that the calling code has no access to the package name.
56        // In this case we will get the packages for the calling UID and pick the
57        // first one for attributing the app op. This will work correctly for
58        // runtime permissions as for legacy apps we will toggle the app op for
59        // all packages in the UID. The caveat is that the operation may be attributed
60        // to the wrong package and stats based on app ops may be slightly off.
61        if (opPackageName.size() <= 0) {
62            sp<IBinder> binder = defaultServiceManager()->getService(String16("permission"));
63            if (binder != 0) {
64                const uid_t uid = IPCThreadState::self()->getCallingUid();
65                Vector<String16> packages;
66                interface_cast<IPermissionController>(binder)->getPackagesForUid(uid, packages);
67                if (!packages.isEmpty()) {
68                    opPackageName = packages[0];
69                } else {
70                    ALOGE("No packages for calling UID");
71                }
72            } else {
73                ALOGE("Cannot get permission service");
74            }
75        }
76
77        sensorManager = new SensorManager(opPackageName);
78
79        // If we had no package name, we looked it up from the UID and the sensor
80        // manager instance we created should also be mapped to the empty package
81        // name, to avoid looking up the packages for a UID and get the same result.
82        if (packageName.size() <= 0) {
83            sPackageInstances.insert(std::make_pair(String16(), sensorManager));
84        }
85
86        // Stash the per package sensor manager.
87        sPackageInstances.insert(std::make_pair(opPackageName, sensorManager));
88    }
89
90    return *sensorManager;
91}
92
93SensorManager::SensorManager(const String16& opPackageName)
94    : mSensorList(0), mOpPackageName(opPackageName), mDirectConnectionHandle(1) {
95    // okay we're not locked here, but it's not needed during construction
96    assertStateLocked();
97}
98
99SensorManager::~SensorManager() {
100    free(mSensorList);
101}
102
103void SensorManager::sensorManagerDied() {
104    Mutex::Autolock _l(mLock);
105    mSensorServer.clear();
106    free(mSensorList);
107    mSensorList = NULL;
108    mSensors.clear();
109}
110
111status_t SensorManager::assertStateLocked() {
112    bool initSensorManager = false;
113    if (mSensorServer == NULL) {
114        initSensorManager = true;
115    } else {
116        // Ping binder to check if sensorservice is alive.
117        status_t err = IInterface::asBinder(mSensorServer)->pingBinder();
118        if (err != NO_ERROR) {
119            initSensorManager = true;
120        }
121    }
122    if (initSensorManager) {
123        // try for 300 seconds (60*5(getService() tries for 5 seconds)) before giving up ...
124        const String16 name("sensorservice");
125        for (int i = 0; i < 60; i++) {
126            status_t err = getService(name, &mSensorServer);
127            if (err == NAME_NOT_FOUND) {
128                sleep(1);
129                continue;
130            }
131            if (err != NO_ERROR) {
132                return err;
133            }
134            break;
135        }
136
137        class DeathObserver : public IBinder::DeathRecipient {
138            SensorManager& mSensorManager;
139            virtual void binderDied(const wp<IBinder>& who) {
140                ALOGW("sensorservice died [%p]", who.unsafe_get());
141                mSensorManager.sensorManagerDied();
142            }
143        public:
144            explicit DeathObserver(SensorManager& mgr) : mSensorManager(mgr) { }
145        };
146
147        LOG_ALWAYS_FATAL_IF(mSensorServer.get() == NULL, "getService(SensorService) NULL");
148
149        mDeathObserver = new DeathObserver(*const_cast<SensorManager *>(this));
150        IInterface::asBinder(mSensorServer)->linkToDeath(mDeathObserver);
151
152        mSensors = mSensorServer->getSensorList(mOpPackageName);
153        size_t count = mSensors.size();
154        mSensorList =
155                static_cast<Sensor const**>(malloc(count * sizeof(Sensor*)));
156        LOG_ALWAYS_FATAL_IF(mSensorList == NULL, "mSensorList NULL");
157
158        for (size_t i=0 ; i<count ; i++) {
159            mSensorList[i] = mSensors.array() + i;
160        }
161    }
162
163    return NO_ERROR;
164}
165
166ssize_t SensorManager::getSensorList(Sensor const* const** list) {
167    Mutex::Autolock _l(mLock);
168    status_t err = assertStateLocked();
169    if (err < 0) {
170        return static_cast<ssize_t>(err);
171    }
172    *list = mSensorList;
173    return static_cast<ssize_t>(mSensors.size());
174}
175
176ssize_t SensorManager::getDynamicSensorList(Vector<Sensor> & dynamicSensors) {
177    Mutex::Autolock _l(mLock);
178    status_t err = assertStateLocked();
179    if (err < 0) {
180        return static_cast<ssize_t>(err);
181    }
182
183    dynamicSensors = mSensorServer->getDynamicSensorList(mOpPackageName);
184    size_t count = dynamicSensors.size();
185
186    return static_cast<ssize_t>(count);
187}
188
189Sensor const* SensorManager::getDefaultSensor(int type)
190{
191    Mutex::Autolock _l(mLock);
192    if (assertStateLocked() == NO_ERROR) {
193        bool wakeUpSensor = false;
194        // For the following sensor types, return a wake-up sensor. These types are by default
195        // defined as wake-up sensors. For the rest of the sensor types defined in sensors.h return
196        // a non_wake-up version.
197        if (type == SENSOR_TYPE_PROXIMITY || type == SENSOR_TYPE_SIGNIFICANT_MOTION ||
198            type == SENSOR_TYPE_TILT_DETECTOR || type == SENSOR_TYPE_WAKE_GESTURE ||
199            type == SENSOR_TYPE_GLANCE_GESTURE || type == SENSOR_TYPE_PICK_UP_GESTURE ||
200            type == SENSOR_TYPE_WRIST_TILT_GESTURE ||
201            type == SENSOR_TYPE_LOW_LATENCY_OFFBODY_DETECT) {
202            wakeUpSensor = true;
203        }
204        // For now we just return the first sensor of that type we find.
205        // in the future it will make sense to let the SensorService make
206        // that decision.
207        for (size_t i=0 ; i<mSensors.size() ; i++) {
208            if (mSensorList[i]->getType() == type &&
209                mSensorList[i]->isWakeUpSensor() == wakeUpSensor) {
210                return mSensorList[i];
211            }
212        }
213    }
214    return NULL;
215}
216
217sp<SensorEventQueue> SensorManager::createEventQueue(String8 packageName, int mode) {
218    sp<SensorEventQueue> queue;
219
220    Mutex::Autolock _l(mLock);
221    while (assertStateLocked() == NO_ERROR) {
222        sp<ISensorEventConnection> connection =
223                mSensorServer->createSensorEventConnection(packageName, mode, mOpPackageName);
224        if (connection == NULL) {
225            // SensorService just died or the app doesn't have required permissions.
226            ALOGE("createEventQueue: connection is NULL.");
227            return NULL;
228        }
229        queue = new SensorEventQueue(connection);
230        break;
231    }
232    return queue;
233}
234
235bool SensorManager::isDataInjectionEnabled() {
236    Mutex::Autolock _l(mLock);
237    if (assertStateLocked() == NO_ERROR) {
238        return mSensorServer->isDataInjectionEnabled();
239    }
240    return false;
241}
242
243int SensorManager::createDirectChannel(
244        size_t size, int channelType, const native_handle_t *resourceHandle) {
245    Mutex::Autolock _l(mLock);
246    if (assertStateLocked() != NO_ERROR) {
247        return NO_INIT;
248    }
249
250    if (channelType != SENSOR_DIRECT_MEM_TYPE_ASHMEM
251            && channelType != SENSOR_DIRECT_MEM_TYPE_GRALLOC) {
252        ALOGE("Bad channel shared memory type %d", channelType);
253        return BAD_VALUE;
254    }
255
256    sp<ISensorEventConnection> conn =
257              mSensorServer->createSensorDirectConnection(mOpPackageName,
258                  static_cast<uint32_t>(size),
259                  static_cast<int32_t>(channelType),
260                  SENSOR_DIRECT_FMT_SENSORS_EVENT, resourceHandle);
261    if (conn == nullptr) {
262        return NO_MEMORY;
263    }
264
265    int nativeHandle = mDirectConnectionHandle++;
266    mDirectConnection.emplace(nativeHandle, conn);
267    return nativeHandle;
268}
269
270void SensorManager::destroyDirectChannel(int channelNativeHandle) {
271    Mutex::Autolock _l(mLock);
272    if (assertStateLocked() == NO_ERROR) {
273        mDirectConnection.erase(channelNativeHandle);
274    }
275}
276
277int SensorManager::configureDirectChannel(int channelNativeHandle, int sensorHandle, int rateLevel) {
278    Mutex::Autolock _l(mLock);
279    if (assertStateLocked() != NO_ERROR) {
280        return NO_INIT;
281    }
282
283    auto i = mDirectConnection.find(channelNativeHandle);
284    if (i == mDirectConnection.end()) {
285        ALOGE("Cannot find the handle in client direct connection table");
286        return BAD_VALUE;
287    }
288
289    int ret;
290    ret = i->second->configureChannel(sensorHandle, rateLevel);
291    ALOGE_IF(ret < 0, "SensorManager::configureChannel (%d, %d) returns %d",
292            static_cast<int>(sensorHandle), static_cast<int>(rateLevel),
293            static_cast<int>(ret));
294    return ret;
295}
296
297// ----------------------------------------------------------------------------
298}; // namespace android
299