SensorService.cpp revision 0cc8f809924706c7d683da30605f432635dd5bb6
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#include <cutils/properties.h>
18
19#include <binder/AppOpsManager.h>
20#include <binder/BinderService.h>
21#include <binder/IServiceManager.h>
22#include <binder/PermissionCache.h>
23
24#include <gui/SensorEventQueue.h>
25
26#include <hardware/sensors.h>
27#include <hardware_legacy/power.h>
28
29#include "BatteryService.h"
30#include "CorrectedGyroSensor.h"
31#include "GravitySensor.h"
32#include "LinearAccelerationSensor.h"
33#include "OrientationSensor.h"
34#include "RotationVectorSensor.h"
35#include "SensorFusion.h"
36
37#include "SensorService.h"
38#include "SensorEventConnection.h"
39#include "SensorEventAckReceiver.h"
40#include "SensorRecord.h"
41#include "SensorRegistrationInfo.h"
42#include "MostRecentEventLogger.h"
43
44#include <inttypes.h>
45#include <math.h>
46#include <stdint.h>
47#include <sys/types.h>
48#include <sys/socket.h>
49
50namespace android {
51// ---------------------------------------------------------------------------
52
53/*
54 * Notes:
55 *
56 * - what about a gyro-corrected magnetic-field sensor?
57 * - run mag sensor from time to time to force calibration
58 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
59 *
60 */
61
62const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
63// Permissions.
64static const String16 sDump("android.permission.DUMP");
65
66SensorService::SensorService()
67    : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
68      mWakeLockAcquired(false) {
69}
70
71void SensorService::onFirstRef() {
72    ALOGD("nuSensorService starting...");
73    SensorDevice& dev(SensorDevice::getInstance());
74
75    if (dev.initCheck() == NO_ERROR) {
76        sensor_t const* list;
77        ssize_t count = dev.getSensorList(&list);
78        if (count > 0) {
79            ssize_t orientationIndex = -1;
80            bool hasGyro = false, hasAccel = false, hasMag = false;
81            uint32_t virtualSensorsNeeds =
82                    (1<<SENSOR_TYPE_GRAVITY) |
83                    (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
84                    (1<<SENSOR_TYPE_ROTATION_VECTOR) |
85                    (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
86                    (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
87
88            mLastEventSeen.setCapacity(count);
89            for (ssize_t i=0 ; i<count ; i++) {
90                bool useThisSensor=true;
91
92                switch (list[i].type) {
93                    case SENSOR_TYPE_ACCELEROMETER:
94                        hasAccel = true;
95                        break;
96                    case SENSOR_TYPE_MAGNETIC_FIELD:
97                        hasMag = true;
98                        break;
99                    case SENSOR_TYPE_ORIENTATION:
100                        orientationIndex = i;
101                        break;
102                    case SENSOR_TYPE_GYROSCOPE:
103                    case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
104                        hasGyro = true;
105                        break;
106                    case SENSOR_TYPE_GRAVITY:
107                    case SENSOR_TYPE_LINEAR_ACCELERATION:
108                    case SENSOR_TYPE_ROTATION_VECTOR:
109                    case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
110                    case SENSOR_TYPE_GAME_ROTATION_VECTOR:
111                        if (IGNORE_HARDWARE_FUSION) {
112                            useThisSensor = false;
113                        } else {
114                            virtualSensorsNeeds &= ~(1<<list[i].type);
115                        }
116                        break;
117                }
118                if (useThisSensor) {
119                    registerSensor( new HardwareSensor(list[i]) );
120                }
121            }
122
123            // it's safe to instantiate the SensorFusion object here
124            // (it wants to be instantiated after h/w sensors have been
125            // registered)
126            SensorFusion::getInstance();
127
128            if (hasGyro && hasAccel && hasMag) {
129                // Add Android virtual sensors if they're not already
130                // available in the HAL
131                bool needRotationVector =
132                        (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
133
134                registerSensor(new RotationVectorSensor(), !needRotationVector, true);
135                registerSensor(new OrientationSensor(), !needRotationVector, true);
136
137                bool needLinearAcceleration =
138                        (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
139
140                registerSensor(new LinearAccelerationSensor(list, count),
141                               !needLinearAcceleration, true);
142
143                // virtual debugging sensors are not for user
144                registerSensor( new CorrectedGyroSensor(list, count), false, true);
145                registerSensor( new GyroDriftSensor(), false, true);
146            }
147
148            if (hasAccel && hasGyro) {
149                bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
150                registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
151
152                bool needGameRotationVector =
153                        (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
154                registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
155            }
156
157            if (hasAccel && hasMag) {
158                bool needGeoMagRotationVector =
159                        (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
160                registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
161            }
162
163            // Check if the device really supports batching by looking at the FIFO event
164            // counts for each sensor.
165            bool batchingSupported = false;
166            mSensors.forEachSensor(
167                    [&batchingSupported] (const Sensor& s) -> bool {
168                        if (s.getFifoMaxEventCount() > 0) {
169                            batchingSupported = true;
170                        }
171                        return !batchingSupported;
172                    });
173
174            if (batchingSupported) {
175                // Increase socket buffer size to a max of 100 KB for batching capabilities.
176                mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
177            } else {
178                mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
179            }
180
181            // Compare the socketBufferSize value against the system limits and limit
182            // it to maxSystemSocketBufferSize if necessary.
183            FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
184            char line[128];
185            if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
186                line[sizeof(line) - 1] = '\0';
187                size_t maxSystemSocketBufferSize;
188                sscanf(line, "%zu", &maxSystemSocketBufferSize);
189                if (mSocketBufferSize > maxSystemSocketBufferSize) {
190                    mSocketBufferSize = maxSystemSocketBufferSize;
191                }
192            }
193            if (fp) {
194                fclose(fp);
195            }
196
197            mWakeLockAcquired = false;
198            mLooper = new Looper(false);
199            const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
200            mSensorEventBuffer = new sensors_event_t[minBufferSize];
201            mSensorEventScratch = new sensors_event_t[minBufferSize];
202            mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
203            mCurrentOperatingMode = NORMAL;
204
205            mNextSensorRegIndex = 0;
206            for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
207                mLastNSensorRegistrations.push();
208            }
209
210            mInitCheck = NO_ERROR;
211            mAckReceiver = new SensorEventAckReceiver(this);
212            mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
213            run("SensorService", PRIORITY_URGENT_DISPLAY);
214        }
215    }
216}
217
218const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
219    int handle = s->getSensor().getHandle();
220    if (mSensors.add(handle, s, isDebug, isVirtual)){
221        mLastEventSeen.add(handle, nullptr);
222        return s->getSensor();
223    } else {
224        return mSensors.getNonSensor();
225    }
226}
227
228const Sensor& SensorService::registerDynamicSensor(SensorInterface* s, bool isDebug) {
229    return registerSensor(s, isDebug);
230}
231
232bool SensorService::unregisterDynamicSensor(int handle) {
233    bool ret = mSensors.remove(handle);
234    MostRecentEventLogger *buf = mLastEventSeen.valueFor(handle);
235    if (buf) {
236        delete buf;
237    }
238    mLastEventSeen.removeItem(handle);
239    return ret;
240}
241
242const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
243    return registerSensor(s, isDebug, true);
244}
245
246SensorService::~SensorService() {
247}
248
249status_t SensorService::dump(int fd, const Vector<String16>& args) {
250    String8 result;
251    if (!PermissionCache::checkCallingPermission(sDump)) {
252        result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
253                IPCThreadState::self()->getCallingPid(),
254                IPCThreadState::self()->getCallingUid());
255    } else {
256        if (args.size() > 2) {
257           return INVALID_OPERATION;
258        }
259        Mutex::Autolock _l(mLock);
260        SensorDevice& dev(SensorDevice::getInstance());
261        if (args.size() == 2 && args[0] == String16("restrict")) {
262            // If already in restricted mode. Ignore.
263            if (mCurrentOperatingMode == RESTRICTED) {
264                return status_t(NO_ERROR);
265            }
266            // If in any mode other than normal, ignore.
267            if (mCurrentOperatingMode != NORMAL) {
268                return INVALID_OPERATION;
269            }
270            mCurrentOperatingMode = RESTRICTED;
271            dev.disableAllSensors();
272            // Clear all pending flush connections for all active sensors. If one of the active
273            // connections has called flush() and the underlying sensor has been disabled before a
274            // flush complete event is returned, we need to remove the connection from this queue.
275            for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
276                mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
277            }
278            mWhiteListedPackage.setTo(String8(args[1]));
279            return status_t(NO_ERROR);
280        } else if (args.size() == 1 && args[0] == String16("enable")) {
281            // If currently in restricted mode, reset back to NORMAL mode else ignore.
282            if (mCurrentOperatingMode == RESTRICTED) {
283                mCurrentOperatingMode = NORMAL;
284                dev.enableAllSensors();
285            }
286            if (mCurrentOperatingMode == DATA_INJECTION) {
287               resetToNormalModeLocked();
288            }
289            mWhiteListedPackage.clear();
290            return status_t(NO_ERROR);
291        } else if (args.size() == 2 && args[0] == String16("data_injection")) {
292            if (mCurrentOperatingMode == NORMAL) {
293                dev.disableAllSensors();
294                status_t err = dev.setMode(DATA_INJECTION);
295                if (err == NO_ERROR) {
296                    mCurrentOperatingMode = DATA_INJECTION;
297                } else {
298                    // Re-enable sensors.
299                    dev.enableAllSensors();
300                }
301                mWhiteListedPackage.setTo(String8(args[1]));
302                return NO_ERROR;
303            } else if (mCurrentOperatingMode == DATA_INJECTION) {
304                // Already in DATA_INJECTION mode. Treat this as a no_op.
305                return NO_ERROR;
306            } else {
307                // Transition to data injection mode supported only from NORMAL mode.
308                return INVALID_OPERATION;
309            }
310        } else if (!mSensors.hasAnySensor()) {
311            result.append("No Sensors on the device\n");
312        } else {
313            // Default dump the sensor list and debugging information.
314            //
315            result.append(mSensors.dump().c_str());
316
317            SensorFusion::getInstance().dump(result);
318            SensorDevice::getInstance().dump(result);
319
320            result.append("Recent Sensor events:\n");
321            auto& lastEvents = mLastEventSeen;
322            mSensors.forEachSensor([&result, &lastEvents] (const Sensor& s) -> bool {
323                    int bufIndex = lastEvents.indexOfKey(s.getHandle());
324                    if (bufIndex >= 0) {
325                        const MostRecentEventLogger* buf = lastEvents.valueAt(bufIndex);
326                        if (buf != nullptr && s.getRequiredPermission().isEmpty()) {
327                            result.appendFormat("%s (handle:0x%08x): ",
328                                          s.getName().string(), s.getHandle());
329                            buf->printBuffer(result);
330                        }
331                    }
332                    return true;
333                });
334
335            result.append("Active sensors:\n");
336            for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
337                int handle = mActiveSensors.keyAt(i);
338                result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
339                        getSensorName(handle).string(),
340                        handle,
341                        mActiveSensors.valueAt(i)->getNumConnections());
342            }
343
344            result.appendFormat("Socket Buffer size = %zd events\n",
345                                mSocketBufferSize/sizeof(sensors_event_t));
346            result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
347                    "not held");
348            result.appendFormat("Mode :");
349            switch(mCurrentOperatingMode) {
350               case NORMAL:
351                   result.appendFormat(" NORMAL\n");
352                   break;
353               case RESTRICTED:
354                   result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
355                   break;
356               case DATA_INJECTION:
357                   result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
358            }
359            result.appendFormat("%zd active connections\n", mActiveConnections.size());
360
361            for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
362                sp<SensorEventConnection> connection(mActiveConnections[i].promote());
363                if (connection != 0) {
364                    result.appendFormat("Connection Number: %zu \n", i);
365                    connection->dump(result);
366                }
367            }
368
369            result.appendFormat("Previous Registrations:\n");
370            // Log in the reverse chronological order.
371            int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
372                SENSOR_REGISTRATIONS_BUF_SIZE;
373            const int startIndex = currentIndex;
374            do {
375                const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
376                if (SensorRegistrationInfo::isSentinel(reg_info)) {
377                    // Ignore sentinel, proceed to next item.
378                    currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
379                        SENSOR_REGISTRATIONS_BUF_SIZE;
380                    continue;
381                }
382                if (reg_info.mActivated) {
383                   result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x "
384                           "samplingRate=%dus maxReportLatency=%dus\n",
385                           reg_info.mHour, reg_info.mMin, reg_info.mSec,
386                           reg_info.mPackageName.string(), reg_info.mSensorHandle,
387                           reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs);
388                } else {
389                   result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n",
390                           reg_info.mHour, reg_info.mMin, reg_info.mSec,
391                           reg_info.mPackageName.string(), reg_info.mSensorHandle);
392                }
393                currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
394                        SENSOR_REGISTRATIONS_BUF_SIZE;
395            } while(startIndex != currentIndex);
396        }
397    }
398    write(fd, result.string(), result.size());
399    return NO_ERROR;
400}
401
402//TODO: move to SensorEventConnection later
403void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
404        sensors_event_t const* buffer, const int count) {
405    for (int i=0 ; i<count ; i++) {
406        int handle = buffer[i].sensor;
407        if (buffer[i].type == SENSOR_TYPE_META_DATA) {
408            handle = buffer[i].meta_data.sensor;
409        }
410        if (connection->hasSensor(handle)) {
411            SensorInterface* si = mSensors.getInterface(handle);
412            // If this buffer has an event from a one_shot sensor and this connection is registered
413            // for this particular one_shot sensor, try cleaning up the connection.
414            if (si != NULL &&
415                si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
416                si->autoDisable(connection.get(), handle);
417                cleanupWithoutDisableLocked(connection, handle);
418            }
419
420        }
421   }
422}
423
424bool SensorService::threadLoop() {
425    ALOGD("nuSensorService thread starting...");
426
427    // each virtual sensor could generate an event per "real" event, that's why we need to size
428    // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.  in practice, this is too
429    // aggressive, but guaranteed to be enough.
430    const size_t vcount = mSensors.getVirtualSensors().size();
431    const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
432    const size_t numEventMax = minBufferSize / (1 + vcount);
433
434    SensorDevice& device(SensorDevice::getInstance());
435
436    const int halVersion = device.getHalDeviceVersion();
437    do {
438        ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
439        if (count < 0) {
440            ALOGE("sensor poll failed (%s)", strerror(-count));
441            break;
442        }
443
444        // Reset sensors_event_t.flags to zero for all events in the buffer.
445        for (int i = 0; i < count; i++) {
446             mSensorEventBuffer[i].flags = 0;
447        }
448
449        // Make a copy of the connection vector as some connections may be removed during the course
450        // of this loop (especially when one-shot sensor events are present in the sensor_event
451        // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
452        // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
453        // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
454        // strongPointers to a vector before the lock is acquired.
455        SortedVector< sp<SensorEventConnection> > activeConnections;
456        populateActiveConnections(&activeConnections);
457
458        Mutex::Autolock _l(mLock);
459        // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
460        // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
461        // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
462        // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
463        // releasing the wakelock.
464        bool bufferHasWakeUpEvent = false;
465        for (int i = 0; i < count; i++) {
466            if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
467                bufferHasWakeUpEvent = true;
468                break;
469            }
470        }
471
472        if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
473            setWakeLockAcquiredLocked(true);
474        }
475        recordLastValueLocked(mSensorEventBuffer, count);
476
477        // handle virtual sensors
478        if (count && vcount) {
479            sensors_event_t const * const event = mSensorEventBuffer;
480            const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
481            if (activeVirtualSensorCount) {
482                size_t k = 0;
483                SensorFusion& fusion(SensorFusion::getInstance());
484                if (fusion.isEnabled()) {
485                    for (size_t i=0 ; i<size_t(count) ; i++) {
486                        fusion.process(event[i]);
487                    }
488                }
489                for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
490                    for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
491                        if (count + k >= minBufferSize) {
492                            ALOGE("buffer too small to hold all events: "
493                                    "count=%zd, k=%zu, size=%zu",
494                                    count, k, minBufferSize);
495                            break;
496                        }
497                        sensors_event_t out;
498                        SensorInterface* si = mActiveVirtualSensors.valueAt(j);
499                        if (si->process(&out, event[i])) {
500                            mSensorEventBuffer[count + k] = out;
501                            k++;
502                        }
503                    }
504                }
505                if (k) {
506                    // record the last synthesized values
507                    recordLastValueLocked(&mSensorEventBuffer[count], k);
508                    count += k;
509                    // sort the buffer by time-stamps
510                    sortEventBuffer(mSensorEventBuffer, count);
511                }
512            }
513        }
514
515        // handle backward compatibility for RotationVector sensor
516        if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
517            for (int i = 0; i < count; i++) {
518                if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
519                    // All the 4 components of the quaternion should be available
520                    // No heading accuracy. Set it to -1
521                    mSensorEventBuffer[i].data[4] = -1;
522                }
523            }
524        }
525
526        for (int i = 0; i < count; ++i) {
527            // Map flush_complete_events in the buffer to SensorEventConnections which called flush
528            // on the hardware sensor. mapFlushEventsToConnections[i] will be the
529            // SensorEventConnection mapped to the corresponding flush_complete_event in
530            // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
531            mMapFlushEventsToConnections[i] = NULL;
532            if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
533                const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
534                SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
535                if (rec != NULL) {
536                    mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
537                    rec->removeFirstPendingFlushConnection();
538                }
539            }
540
541            // handle dynamic sensor meta events, process registration and unregistration of dynamic
542            // sensor based on content of event.
543            if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
544                if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
545                    int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
546                    const sensor_t& dynamicSensor =
547                            *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
548                    ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
549                          handle, dynamicSensor.type, dynamicSensor.name);
550
551                    if (mSensors.isNewHandle(handle)) {
552                        sensor_t s = dynamicSensor;
553                        // make sure the dynamic sensor flag is set
554                        s.flags |= DYNAMIC_SENSOR_MASK;
555                        // force the handle to be consistent
556                        s.handle = handle;
557                        SensorInterface *si = new HardwareSensor(s);
558
559                        // This will release hold on dynamic sensor meta, so it should be called
560                        // after Sensor object is created.
561                        device.handleDynamicSensorConnection(handle, true /*connected*/);
562                        registerDynamicSensor(si);
563                    } else {
564                        ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
565                    }
566                } else {
567                    int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
568                    ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
569
570                    device.handleDynamicSensorConnection(handle, false /*connected*/);
571                    if (!unregisterDynamicSensor(handle)) {
572                        ALOGE("Dynamic sensor release error.");
573                    }
574
575                    size_t numConnections = activeConnections.size();
576                    for (size_t i=0 ; i < numConnections; ++i) {
577                        if (activeConnections[i] != NULL) {
578                            activeConnections[i]->removeSensor(handle);
579                        }
580                    }
581                }
582            }
583        }
584
585
586        // Send our events to clients. Check the state of wake lock for each client and release the
587        // lock if none of the clients need it.
588        bool needsWakeLock = false;
589        size_t numConnections = activeConnections.size();
590        for (size_t i=0 ; i < numConnections; ++i) {
591            if (activeConnections[i] != 0) {
592                activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
593                        mMapFlushEventsToConnections);
594                needsWakeLock |= activeConnections[i]->needsWakeLock();
595                // If the connection has one-shot sensors, it may be cleaned up after first trigger.
596                // Early check for one-shot sensors.
597                if (activeConnections[i]->hasOneShotSensors()) {
598                    cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
599                            count);
600                }
601            }
602        }
603
604        if (mWakeLockAcquired && !needsWakeLock) {
605            setWakeLockAcquiredLocked(false);
606        }
607    } while (!Thread::exitPending());
608
609    ALOGW("Exiting SensorService::threadLoop => aborting...");
610    abort();
611    return false;
612}
613
614sp<Looper> SensorService::getLooper() const {
615    return mLooper;
616}
617
618void SensorService::resetAllWakeLockRefCounts() {
619    SortedVector< sp<SensorEventConnection> > activeConnections;
620    populateActiveConnections(&activeConnections);
621    {
622        Mutex::Autolock _l(mLock);
623        for (size_t i=0 ; i < activeConnections.size(); ++i) {
624            if (activeConnections[i] != 0) {
625                activeConnections[i]->resetWakeLockRefCount();
626            }
627        }
628        setWakeLockAcquiredLocked(false);
629    }
630}
631
632void SensorService::setWakeLockAcquiredLocked(bool acquire) {
633    if (acquire) {
634        if (!mWakeLockAcquired) {
635            acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
636            mWakeLockAcquired = true;
637        }
638        mLooper->wake();
639    } else {
640        if (mWakeLockAcquired) {
641            release_wake_lock(WAKE_LOCK_NAME);
642            mWakeLockAcquired = false;
643        }
644    }
645}
646
647bool SensorService::isWakeLockAcquired() {
648    Mutex::Autolock _l(mLock);
649    return mWakeLockAcquired;
650}
651
652bool SensorService::SensorEventAckReceiver::threadLoop() {
653    ALOGD("new thread SensorEventAckReceiver");
654    sp<Looper> looper = mService->getLooper();
655    do {
656        bool wakeLockAcquired = mService->isWakeLockAcquired();
657        int timeout = -1;
658        if (wakeLockAcquired) timeout = 5000;
659        int ret = looper->pollOnce(timeout);
660        if (ret == ALOOPER_POLL_TIMEOUT) {
661           mService->resetAllWakeLockRefCounts();
662        }
663    } while(!Thread::exitPending());
664    return false;
665}
666
667void SensorService::recordLastValueLocked(
668        const sensors_event_t* buffer, size_t count) {
669    for (size_t i = 0; i < count; i++) {
670        if (buffer[i].type == SENSOR_TYPE_META_DATA ||
671            buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
672            buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO ||
673            mLastEventSeen.indexOfKey(buffer[i].sensor) <0 ) {
674            continue;
675        }
676
677        MostRecentEventLogger* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
678        if (circular_buf == NULL) {
679            circular_buf = new MostRecentEventLogger(buffer[i].type);
680        }
681        circular_buf->addEvent(buffer[i]);
682    }
683}
684
685void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
686    struct compar {
687        static int cmp(void const* lhs, void const* rhs) {
688            sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
689            sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
690            return l->timestamp - r->timestamp;
691        }
692    };
693    qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
694}
695
696String8 SensorService::getSensorName(int handle) const {
697    return mSensors.getName(handle);
698}
699
700bool SensorService::isVirtualSensor(int handle) const {
701    SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
702    return sensor != NULL && sensor->isVirtual();
703}
704
705bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
706    int handle = event.sensor;
707    if (event.type == SENSOR_TYPE_META_DATA) {
708        handle = event.meta_data.sensor;
709    }
710    SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
711    return sensor != NULL && sensor->getSensor().isWakeUpSensor();
712}
713
714Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
715    char value[PROPERTY_VALUE_MAX];
716    property_get("debug.sensors", value, "0");
717    const Vector<Sensor>& initialSensorList = (atoi(value)) ?
718            mSensors.getUserDebugSensors() : mSensors.getUserSensors();
719    Vector<Sensor> accessibleSensorList;
720    for (size_t i = 0; i < initialSensorList.size(); i++) {
721        Sensor sensor = initialSensorList[i];
722        if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
723            accessibleSensorList.add(sensor);
724        } else {
725            ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
726                  sensor.getName().string(),
727                  sensor.getRequiredPermission().string(),
728                  sensor.getRequiredAppOp());
729        }
730    }
731    return accessibleSensorList;
732}
733
734Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
735    Vector<Sensor> accessibleSensorList;
736    mSensors.forEachSensor(
737            [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
738                if (sensor.isDynamicSensor() &&
739                        canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
740                    accessibleSensorList.add(sensor);
741                } else {
742                    ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
743                          sensor.getName().string(),
744                          sensor.getRequiredPermission().string(),
745                          sensor.getRequiredAppOp());
746                }
747                return true;
748            });
749    return accessibleSensorList;
750}
751
752sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
753        int requestedMode, const String16& opPackageName) {
754    // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
755    if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
756        return NULL;
757    }
758
759    Mutex::Autolock _l(mLock);
760    // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
761    // operating in DI mode.
762    if (requestedMode == DATA_INJECTION) {
763        if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
764        if (!isWhiteListedPackage(packageName)) return NULL;
765    }
766
767    uid_t uid = IPCThreadState::self()->getCallingUid();
768    sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
769            requestedMode == DATA_INJECTION, opPackageName));
770    if (requestedMode == DATA_INJECTION) {
771        if (mActiveConnections.indexOf(result) < 0) {
772            mActiveConnections.add(result);
773        }
774        // Add the associated file descriptor to the Looper for polling whenever there is data to
775        // be injected.
776        result->updateLooperRegistration(mLooper);
777    }
778    return result;
779}
780
781int SensorService::isDataInjectionEnabled() {
782    Mutex::Autolock _l(mLock);
783    return (mCurrentOperatingMode == DATA_INJECTION);
784}
785
786status_t SensorService::resetToNormalMode() {
787    Mutex::Autolock _l(mLock);
788    return resetToNormalModeLocked();
789}
790
791status_t SensorService::resetToNormalModeLocked() {
792    SensorDevice& dev(SensorDevice::getInstance());
793    dev.enableAllSensors();
794    status_t err = dev.setMode(NORMAL);
795    mCurrentOperatingMode = NORMAL;
796    return err;
797}
798
799void SensorService::cleanupConnection(SensorEventConnection* c) {
800    Mutex::Autolock _l(mLock);
801    const wp<SensorEventConnection> connection(c);
802    size_t size = mActiveSensors.size();
803    ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
804    for (size_t i=0 ; i<size ; ) {
805        int handle = mActiveSensors.keyAt(i);
806        if (c->hasSensor(handle)) {
807            ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
808            SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
809            ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
810            if (sensor) {
811                sensor->activate(c, false);
812            }
813            c->removeSensor(handle);
814        }
815        SensorRecord* rec = mActiveSensors.valueAt(i);
816        ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
817        ALOGD_IF(DEBUG_CONNECTIONS,
818                "removing connection %p for sensor[%zu].handle=0x%08x",
819                c, i, handle);
820
821        if (rec && rec->removeConnection(connection)) {
822            ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
823            mActiveSensors.removeItemsAt(i, 1);
824            mActiveVirtualSensors.removeItem(handle);
825            delete rec;
826            size--;
827        } else {
828            i++;
829        }
830    }
831    c->updateLooperRegistration(mLooper);
832    mActiveConnections.remove(connection);
833    BatteryService::cleanup(c->getUid());
834    if (c->needsWakeLock()) {
835        checkWakeLockStateLocked();
836    }
837}
838
839SensorInterface* SensorService::getSensorInterfaceFromHandle(int handle) const {
840    return mSensors.getInterface(handle);
841}
842
843const Sensor& SensorService::getSensorFromHandle(int handle) const {
844    return mSensors.get(handle);
845}
846
847status_t SensorService::enable(const sp<SensorEventConnection>& connection,
848        int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
849        const String16& opPackageName) {
850    if (mInitCheck != NO_ERROR)
851        return mInitCheck;
852
853    SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
854    if (sensor == NULL) {
855        return BAD_VALUE;
856    }
857
858    if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
859        return BAD_VALUE;
860    }
861
862    Mutex::Autolock _l(mLock);
863    if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
864           && !isWhiteListedPackage(connection->getPackageName())) {
865        return INVALID_OPERATION;
866    }
867
868    SensorRecord* rec = mActiveSensors.valueFor(handle);
869    if (rec == 0) {
870        rec = new SensorRecord(connection);
871        mActiveSensors.add(handle, rec);
872        if (sensor->isVirtual()) {
873            mActiveVirtualSensors.add(handle, sensor);
874        }
875    } else {
876        if (rec->addConnection(connection)) {
877            // this sensor is already activated, but we are adding a connection that uses it.
878            // Immediately send down the last known value of the requested sensor if it's not a
879            // "continuous" sensor.
880            if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
881                // NOTE: The wake_up flag of this event may get set to
882                // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
883                MostRecentEventLogger *circular_buf = mLastEventSeen.valueFor(handle);
884                if (circular_buf) {
885                    sensors_event_t event;
886                    memset(&event, 0, sizeof(event));
887                    // It is unlikely that this buffer is empty as the sensor is already active.
888                    // One possible corner case may be two applications activating an on-change
889                    // sensor at the same time.
890                    if(circular_buf->populateLastEvent(&event)) {
891                        event.sensor = handle;
892                        if (event.version == sizeof(sensors_event_t)) {
893                            if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
894                                setWakeLockAcquiredLocked(true);
895                            }
896                            connection->sendEvents(&event, 1, NULL);
897                            if (!connection->needsWakeLock() && mWakeLockAcquired) {
898                                checkWakeLockStateLocked();
899                            }
900                        }
901                    }
902                }
903            }
904        }
905    }
906
907    if (connection->addSensor(handle)) {
908        BatteryService::enableSensor(connection->getUid(), handle);
909        // the sensor was added (which means it wasn't already there)
910        // so, see if this connection becomes active
911        if (mActiveConnections.indexOf(connection) < 0) {
912            mActiveConnections.add(connection);
913        }
914    } else {
915        ALOGW("sensor %08x already enabled in connection %p (ignoring)",
916            handle, connection.get());
917    }
918
919    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
920    if (samplingPeriodNs < minDelayNs) {
921        samplingPeriodNs = minDelayNs;
922    }
923
924    ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
925                                "rate=%" PRId64 " timeout== %" PRId64"",
926             handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
927
928    status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
929                                 maxBatchReportLatencyNs);
930
931    // Call flush() before calling activate() on the sensor. Wait for a first
932    // flush complete event before sending events on this connection. Ignore
933    // one-shot sensors which don't support flush(). Ignore on-change sensors
934    // to maintain the on-change logic (any on-change events except the initial
935    // one should be trigger by a change in value). Also if this sensor isn't
936    // already active, don't call flush().
937    if (err == NO_ERROR &&
938            sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
939            rec->getNumConnections() > 1) {
940        connection->setFirstFlushPending(handle, true);
941        status_t err_flush = sensor->flush(connection.get(), handle);
942        // Flush may return error if the underlying h/w sensor uses an older HAL.
943        if (err_flush == NO_ERROR) {
944            rec->addPendingFlushConnection(connection.get());
945        } else {
946            connection->setFirstFlushPending(handle, false);
947        }
948    }
949
950    if (err == NO_ERROR) {
951        ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
952        err = sensor->activate(connection.get(), true);
953    }
954
955    if (err == NO_ERROR) {
956        connection->updateLooperRegistration(mLooper);
957        SensorRegistrationInfo &reg_info =
958            mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
959        reg_info.mSensorHandle = handle;
960        reg_info.mSamplingRateUs = samplingPeriodNs/1000;
961        reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
962        reg_info.mActivated = true;
963        reg_info.mPackageName = connection->getPackageName();
964        time_t rawtime = time(NULL);
965        struct tm * timeinfo = localtime(&rawtime);
966        reg_info.mHour = timeinfo->tm_hour;
967        reg_info.mMin = timeinfo->tm_min;
968        reg_info.mSec = timeinfo->tm_sec;
969        mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
970    }
971
972    if (err != NO_ERROR) {
973        // batch/activate has failed, reset our state.
974        cleanupWithoutDisableLocked(connection, handle);
975    }
976    return err;
977}
978
979status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
980    if (mInitCheck != NO_ERROR)
981        return mInitCheck;
982
983    Mutex::Autolock _l(mLock);
984    status_t err = cleanupWithoutDisableLocked(connection, handle);
985    if (err == NO_ERROR) {
986        SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
987        err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
988
989    }
990    if (err == NO_ERROR) {
991        SensorRegistrationInfo &reg_info =
992            mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
993        reg_info.mActivated = false;
994        reg_info.mPackageName= connection->getPackageName();
995        reg_info.mSensorHandle = handle;
996        time_t rawtime = time(NULL);
997        struct tm * timeinfo = localtime(&rawtime);
998        reg_info.mHour = timeinfo->tm_hour;
999        reg_info.mMin = timeinfo->tm_min;
1000        reg_info.mSec = timeinfo->tm_sec;
1001        mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
1002    }
1003    return err;
1004}
1005
1006status_t SensorService::cleanupWithoutDisable(
1007        const sp<SensorEventConnection>& connection, int handle) {
1008    Mutex::Autolock _l(mLock);
1009    return cleanupWithoutDisableLocked(connection, handle);
1010}
1011
1012status_t SensorService::cleanupWithoutDisableLocked(
1013        const sp<SensorEventConnection>& connection, int handle) {
1014    SensorRecord* rec = mActiveSensors.valueFor(handle);
1015    if (rec) {
1016        // see if this connection becomes inactive
1017        if (connection->removeSensor(handle)) {
1018            BatteryService::disableSensor(connection->getUid(), handle);
1019        }
1020        if (connection->hasAnySensor() == false) {
1021            connection->updateLooperRegistration(mLooper);
1022            mActiveConnections.remove(connection);
1023        }
1024        // see if this sensor becomes inactive
1025        if (rec->removeConnection(connection)) {
1026            mActiveSensors.removeItem(handle);
1027            mActiveVirtualSensors.removeItem(handle);
1028            delete rec;
1029        }
1030        return NO_ERROR;
1031    }
1032    return BAD_VALUE;
1033}
1034
1035status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
1036        int handle, nsecs_t ns, const String16& opPackageName) {
1037    if (mInitCheck != NO_ERROR)
1038        return mInitCheck;
1039
1040    SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
1041    if (!sensor)
1042        return BAD_VALUE;
1043
1044    if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
1045        return BAD_VALUE;
1046    }
1047
1048    if (ns < 0)
1049        return BAD_VALUE;
1050
1051    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1052    if (ns < minDelayNs) {
1053        ns = minDelayNs;
1054    }
1055
1056    return sensor->setDelay(connection.get(), handle, ns);
1057}
1058
1059status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1060        const String16& opPackageName) {
1061    if (mInitCheck != NO_ERROR) return mInitCheck;
1062    SensorDevice& dev(SensorDevice::getInstance());
1063    const int halVersion = dev.getHalDeviceVersion();
1064    status_t err(NO_ERROR);
1065    Mutex::Autolock _l(mLock);
1066    // Loop through all sensors for this connection and call flush on each of them.
1067    for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1068        const int handle = connection->mSensorInfo.keyAt(i);
1069        SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
1070        if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1071            ALOGE("flush called on a one-shot sensor");
1072            err = INVALID_OPERATION;
1073            continue;
1074        }
1075        if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
1076            // For older devices just increment pending flush count which will send a trivial
1077            // flush complete event.
1078            connection->incrementPendingFlushCount(handle);
1079        } else {
1080            if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1081                err = INVALID_OPERATION;
1082                continue;
1083            }
1084            status_t err_flush = sensor->flush(connection.get(), handle);
1085            if (err_flush == NO_ERROR) {
1086                SensorRecord* rec = mActiveSensors.valueFor(handle);
1087                if (rec != NULL) rec->addPendingFlushConnection(connection);
1088            }
1089            err = (err_flush != NO_ERROR) ? err_flush : err;
1090        }
1091    }
1092    return err;
1093}
1094
1095bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1096        const String16& opPackageName) {
1097    const String8& requiredPermission = sensor.getRequiredPermission();
1098
1099    if (requiredPermission.length() <= 0) {
1100        return true;
1101    }
1102
1103    bool hasPermission = false;
1104
1105    // Runtime permissions can't use the cache as they may change.
1106    if (sensor.isRequiredPermissionRuntime()) {
1107        hasPermission = checkPermission(String16(requiredPermission),
1108                IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
1109    } else {
1110        hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1111    }
1112
1113    if (!hasPermission) {
1114        ALOGE("%s a sensor (%s) without holding its required permission: %s",
1115                operation, sensor.getName().string(), sensor.getRequiredPermission().string());
1116        return false;
1117    }
1118
1119    const int32_t opCode = sensor.getRequiredAppOp();
1120    if (opCode >= 0) {
1121        AppOpsManager appOps;
1122        if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1123                        != AppOpsManager::MODE_ALLOWED) {
1124            ALOGE("%s a sensor (%s) without enabled required app op: %d",
1125                    operation, sensor.getName().string(), opCode);
1126            return false;
1127        }
1128    }
1129
1130    return true;
1131}
1132
1133void SensorService::checkWakeLockState() {
1134    Mutex::Autolock _l(mLock);
1135    checkWakeLockStateLocked();
1136}
1137
1138void SensorService::checkWakeLockStateLocked() {
1139    if (!mWakeLockAcquired) {
1140        return;
1141    }
1142    bool releaseLock = true;
1143    for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1144        sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1145        if (connection != 0) {
1146            if (connection->needsWakeLock()) {
1147                releaseLock = false;
1148                break;
1149            }
1150        }
1151    }
1152    if (releaseLock) {
1153        setWakeLockAcquiredLocked(false);
1154    }
1155}
1156
1157void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1158    Mutex::Autolock _l(mLock);
1159    connection->writeToSocketFromCache();
1160    if (connection->needsWakeLock()) {
1161        setWakeLockAcquiredLocked(true);
1162    }
1163}
1164
1165void SensorService::populateActiveConnections(
1166        SortedVector< sp<SensorEventConnection> >* activeConnections) {
1167    Mutex::Autolock _l(mLock);
1168    for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1169        sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1170        if (connection != 0) {
1171            activeConnections->add(connection);
1172        }
1173    }
1174}
1175
1176bool SensorService::isWhiteListedPackage(const String8& packageName) {
1177    return (packageName.contains(mWhiteListedPackage.string()));
1178}
1179
1180int SensorService::getNumEventsForSensorType(int sensor_event_type) {
1181    if (sensor_event_type >= SENSOR_TYPE_DEVICE_PRIVATE_BASE) {
1182        return 16;
1183    }
1184    switch (sensor_event_type) {
1185        case SENSOR_TYPE_ROTATION_VECTOR:
1186        case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1187            return 5;
1188
1189        case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1190        case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1191            return 6;
1192
1193        case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1194            return 4;
1195
1196        case SENSOR_TYPE_SIGNIFICANT_MOTION:
1197        case SENSOR_TYPE_STEP_DETECTOR:
1198        case SENSOR_TYPE_STEP_COUNTER:
1199            return 1;
1200
1201         default:
1202            return 3;
1203    }
1204}
1205
1206}; // namespace android
1207
1208