Home | History | Annotate | Download | only in sensorservice
      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 <stdint.h>
     18 #include <math.h>
     19 #include <sys/types.h>
     20 
     21 #include <cutils/properties.h>
     22 
     23 #include <utils/SortedVector.h>
     24 #include <utils/KeyedVector.h>
     25 #include <utils/threads.h>
     26 #include <utils/Atomic.h>
     27 #include <utils/Errors.h>
     28 #include <utils/RefBase.h>
     29 #include <utils/Singleton.h>
     30 #include <utils/String16.h>
     31 
     32 #include <binder/BinderService.h>
     33 #include <binder/IServiceManager.h>
     34 #include <binder/PermissionCache.h>
     35 
     36 #include <gui/ISensorServer.h>
     37 #include <gui/ISensorEventConnection.h>
     38 #include <gui/SensorEventQueue.h>
     39 
     40 #include <hardware/sensors.h>
     41 #include <hardware_legacy/power.h>
     42 
     43 #include "BatteryService.h"
     44 #include "CorrectedGyroSensor.h"
     45 #include "GravitySensor.h"
     46 #include "LinearAccelerationSensor.h"
     47 #include "OrientationSensor.h"
     48 #include "RotationVectorSensor.h"
     49 #include "SensorFusion.h"
     50 #include "SensorService.h"
     51 
     52 namespace android {
     53 // ---------------------------------------------------------------------------
     54 
     55 /*
     56  * Notes:
     57  *
     58  * - what about a gyro-corrected magnetic-field sensor?
     59  * - run mag sensor from time to time to force calibration
     60  * - gravity sensor length is wrong (=> drift in linear-acc sensor)
     61  *
     62  */
     63 
     64 const char* SensorService::WAKE_LOCK_NAME = "SensorService";
     65 
     66 SensorService::SensorService()
     67     : mInitCheck(NO_INIT)
     68 {
     69 }
     70 
     71 void SensorService::onFirstRef()
     72 {
     73     ALOGD("nuSensorService starting...");
     74 
     75     SensorDevice& dev(SensorDevice::getInstance());
     76 
     77     if (dev.initCheck() == NO_ERROR) {
     78         sensor_t const* list;
     79         ssize_t count = dev.getSensorList(&list);
     80         if (count > 0) {
     81             ssize_t orientationIndex = -1;
     82             bool hasGyro = false;
     83             uint32_t virtualSensorsNeeds =
     84                     (1<<SENSOR_TYPE_GRAVITY) |
     85                     (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
     86                     (1<<SENSOR_TYPE_ROTATION_VECTOR);
     87 
     88             mLastEventSeen.setCapacity(count);
     89             for (ssize_t i=0 ; i<count ; i++) {
     90                 registerSensor( new HardwareSensor(list[i]) );
     91                 switch (list[i].type) {
     92                     case SENSOR_TYPE_ORIENTATION:
     93                         orientationIndex = i;
     94                         break;
     95                     case SENSOR_TYPE_GYROSCOPE:
     96                         hasGyro = true;
     97                         break;
     98                     case SENSOR_TYPE_GRAVITY:
     99                     case SENSOR_TYPE_LINEAR_ACCELERATION:
    100                     case SENSOR_TYPE_ROTATION_VECTOR:
    101                         virtualSensorsNeeds &= ~(1<<list[i].type);
    102                         break;
    103                 }
    104             }
    105 
    106             // it's safe to instantiate the SensorFusion object here
    107             // (it wants to be instantiated after h/w sensors have been
    108             // registered)
    109             const SensorFusion& fusion(SensorFusion::getInstance());
    110 
    111             if (hasGyro) {
    112                 // Always instantiate Android's virtual sensors. Since they are
    113                 // instantiated behind sensors from the HAL, they won't
    114                 // interfere with applications, unless they looks specifically
    115                 // for them (by name).
    116 
    117                 registerVirtualSensor( new RotationVectorSensor() );
    118                 registerVirtualSensor( new GravitySensor(list, count) );
    119                 registerVirtualSensor( new LinearAccelerationSensor(list, count) );
    120 
    121                 // these are optional
    122                 registerVirtualSensor( new OrientationSensor() );
    123                 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
    124             }
    125 
    126             // build the sensor list returned to users
    127             mUserSensorList = mSensorList;
    128 
    129             if (hasGyro) {
    130                 // virtual debugging sensors are not added to mUserSensorList
    131                 registerVirtualSensor( new GyroDriftSensor() );
    132             }
    133 
    134             if (hasGyro &&
    135                     (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR))) {
    136                 // if we have the fancy sensor fusion, and it's not provided by the
    137                 // HAL, use our own (fused) orientation sensor by removing the
    138                 // HAL supplied one form the user list.
    139                 if (orientationIndex >= 0) {
    140                     mUserSensorList.removeItemsAt(orientationIndex);
    141                 }
    142             }
    143 
    144             // debugging sensor list
    145             for (size_t i=0 ; i<mSensorList.size() ; i++) {
    146                 switch (mSensorList[i].getType()) {
    147                     case SENSOR_TYPE_GRAVITY:
    148                     case SENSOR_TYPE_LINEAR_ACCELERATION:
    149                     case SENSOR_TYPE_ROTATION_VECTOR:
    150                         if (strstr(mSensorList[i].getVendor().string(), "Google")) {
    151                             mUserSensorListDebug.add(mSensorList[i]);
    152                         }
    153                         break;
    154                     default:
    155                         mUserSensorListDebug.add(mSensorList[i]);
    156                         break;
    157                 }
    158             }
    159 
    160             run("SensorService", PRIORITY_URGENT_DISPLAY);
    161             mInitCheck = NO_ERROR;
    162         }
    163     }
    164 }
    165 
    166 void SensorService::registerSensor(SensorInterface* s)
    167 {
    168     sensors_event_t event;
    169     memset(&event, 0, sizeof(event));
    170 
    171     const Sensor sensor(s->getSensor());
    172     // add to the sensor list (returned to clients)
    173     mSensorList.add(sensor);
    174     // add to our handle->SensorInterface mapping
    175     mSensorMap.add(sensor.getHandle(), s);
    176     // create an entry in the mLastEventSeen array
    177     mLastEventSeen.add(sensor.getHandle(), event);
    178 }
    179 
    180 void SensorService::registerVirtualSensor(SensorInterface* s)
    181 {
    182     registerSensor(s);
    183     mVirtualSensorList.add( s );
    184 }
    185 
    186 SensorService::~SensorService()
    187 {
    188     for (size_t i=0 ; i<mSensorMap.size() ; i++)
    189         delete mSensorMap.valueAt(i);
    190 }
    191 
    192 static const String16 sDump("android.permission.DUMP");
    193 
    194 status_t SensorService::dump(int fd, const Vector<String16>& args)
    195 {
    196     const size_t SIZE = 1024;
    197     char buffer[SIZE];
    198     String8 result;
    199     if (!PermissionCache::checkCallingPermission(sDump)) {
    200         snprintf(buffer, SIZE, "Permission Denial: "
    201                 "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
    202                 IPCThreadState::self()->getCallingPid(),
    203                 IPCThreadState::self()->getCallingUid());
    204         result.append(buffer);
    205     } else {
    206         Mutex::Autolock _l(mLock);
    207         snprintf(buffer, SIZE, "Sensor List:\n");
    208         result.append(buffer);
    209         for (size_t i=0 ; i<mSensorList.size() ; i++) {
    210             const Sensor& s(mSensorList[i]);
    211             const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
    212             snprintf(buffer, SIZE,
    213                     "%-48s| %-32s | 0x%08x | maxRate=%7.2fHz | "
    214                     "last=<%5.1f,%5.1f,%5.1f>\n",
    215                     s.getName().string(),
    216                     s.getVendor().string(),
    217                     s.getHandle(),
    218                     s.getMinDelay() ? (1000000.0f / s.getMinDelay()) : 0.0f,
    219                     e.data[0], e.data[1], e.data[2]);
    220             result.append(buffer);
    221         }
    222         SensorFusion::getInstance().dump(result, buffer, SIZE);
    223         SensorDevice::getInstance().dump(result, buffer, SIZE);
    224 
    225         snprintf(buffer, SIZE, "%d active connections\n",
    226                 mActiveConnections.size());
    227         result.append(buffer);
    228         snprintf(buffer, SIZE, "Active sensors:\n");
    229         result.append(buffer);
    230         for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
    231             int handle = mActiveSensors.keyAt(i);
    232             snprintf(buffer, SIZE, "%s (handle=0x%08x, connections=%d)\n",
    233                     getSensorName(handle).string(),
    234                     handle,
    235                     mActiveSensors.valueAt(i)->getNumConnections());
    236             result.append(buffer);
    237         }
    238     }
    239     write(fd, result.string(), result.size());
    240     return NO_ERROR;
    241 }
    242 
    243 void SensorService::cleanupAutoDisabledSensor(const sp<SensorEventConnection>& connection,
    244         sensors_event_t const* buffer, const int count) {
    245     SensorInterface* sensor;
    246     status_t err = NO_ERROR;
    247     for (int i=0 ; i<count ; i++) {
    248         int handle = buffer[i].sensor;
    249         if (getSensorType(handle) == SENSOR_TYPE_SIGNIFICANT_MOTION) {
    250             if (connection->hasSensor(handle)) {
    251                 sensor = mSensorMap.valueFor(handle);
    252                 if (sensor != NULL) {
    253                     sensor->autoDisable(connection.get(), handle);
    254                 }
    255                 cleanupWithoutDisable(connection, handle);
    256             }
    257         }
    258     }
    259 }
    260 
    261 bool SensorService::threadLoop()
    262 {
    263     ALOGD("nuSensorService thread starting...");
    264 
    265     const size_t numEventMax = 16;
    266     const size_t minBufferSize = numEventMax + numEventMax * mVirtualSensorList.size();
    267     sensors_event_t buffer[minBufferSize];
    268     sensors_event_t scratch[minBufferSize];
    269     SensorDevice& device(SensorDevice::getInstance());
    270     const size_t vcount = mVirtualSensorList.size();
    271 
    272     ssize_t count;
    273     bool wakeLockAcquired = false;
    274     const int halVersion = device.getHalDeviceVersion();
    275     do {
    276         count = device.poll(buffer, numEventMax);
    277         if (count<0) {
    278             ALOGE("sensor poll failed (%s)", strerror(-count));
    279             break;
    280         }
    281 
    282         // Poll has returned. Hold a wakelock.
    283         // Todo(): add a flag to the sensors definitions to indicate
    284         // the sensors which can wake up the AP
    285         for (int i = 0; i < count; i++) {
    286             if (getSensorType(buffer[i].sensor) == SENSOR_TYPE_SIGNIFICANT_MOTION) {
    287                  acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
    288                  wakeLockAcquired = true;
    289                  break;
    290             }
    291         }
    292 
    293         recordLastValue(buffer, count);
    294 
    295         // handle virtual sensors
    296         if (count && vcount) {
    297             sensors_event_t const * const event = buffer;
    298             const DefaultKeyedVector<int, SensorInterface*> virtualSensors(
    299                     getActiveVirtualSensors());
    300             const size_t activeVirtualSensorCount = virtualSensors.size();
    301             if (activeVirtualSensorCount) {
    302                 size_t k = 0;
    303                 SensorFusion& fusion(SensorFusion::getInstance());
    304                 if (fusion.isEnabled()) {
    305                     for (size_t i=0 ; i<size_t(count) ; i++) {
    306                         fusion.process(event[i]);
    307                     }
    308                 }
    309                 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
    310                     for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
    311                         if (count + k >= minBufferSize) {
    312                             ALOGE("buffer too small to hold all events: "
    313                                     "count=%u, k=%u, size=%u",
    314                                     count, k, minBufferSize);
    315                             break;
    316                         }
    317                         sensors_event_t out;
    318                         SensorInterface* si = virtualSensors.valueAt(j);
    319                         if (si->process(&out, event[i])) {
    320                             buffer[count + k] = out;
    321                             k++;
    322                         }
    323                     }
    324                 }
    325                 if (k) {
    326                     // record the last synthesized values
    327                     recordLastValue(&buffer[count], k);
    328                     count += k;
    329                     // sort the buffer by time-stamps
    330                     sortEventBuffer(buffer, count);
    331                 }
    332             }
    333         }
    334 
    335         // handle backward compatibility for RotationVector sensor
    336         if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
    337             for (int i = 0; i < count; i++) {
    338                 if (getSensorType(buffer[i].sensor) == SENSOR_TYPE_ROTATION_VECTOR) {
    339                     // All the 4 components of the quaternion should be available
    340                     // No heading accuracy. Set it to -1
    341                     buffer[i].data[4] = -1;
    342                 }
    343             }
    344         }
    345 
    346         // send our events to clients...
    347         const SortedVector< wp<SensorEventConnection> > activeConnections(
    348                 getActiveConnections());
    349         size_t numConnections = activeConnections.size();
    350         for (size_t i=0 ; i<numConnections ; i++) {
    351             sp<SensorEventConnection> connection(
    352                     activeConnections[i].promote());
    353             if (connection != 0) {
    354                 connection->sendEvents(buffer, count, scratch);
    355                 // Some sensors need to be auto disabled after the trigger
    356                 cleanupAutoDisabledSensor(connection, buffer, count);
    357             }
    358         }
    359 
    360         // We have read the data, upper layers should hold the wakelock.
    361         if (wakeLockAcquired) release_wake_lock(WAKE_LOCK_NAME);
    362 
    363     } while (count >= 0 || Thread::exitPending());
    364 
    365     ALOGW("Exiting SensorService::threadLoop => aborting...");
    366     abort();
    367     return false;
    368 }
    369 
    370 void SensorService::recordLastValue(
    371         sensors_event_t const * buffer, size_t count)
    372 {
    373     Mutex::Autolock _l(mLock);
    374 
    375     // record the last event for each sensor
    376     int32_t prev = buffer[0].sensor;
    377     for (size_t i=1 ; i<count ; i++) {
    378         // record the last event of each sensor type in this buffer
    379         int32_t curr = buffer[i].sensor;
    380         if (curr != prev) {
    381             mLastEventSeen.editValueFor(prev) = buffer[i-1];
    382             prev = curr;
    383         }
    384     }
    385     mLastEventSeen.editValueFor(prev) = buffer[count-1];
    386 }
    387 
    388 void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
    389 {
    390     struct compar {
    391         static int cmp(void const* lhs, void const* rhs) {
    392             sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
    393             sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
    394             return l->timestamp - r->timestamp;
    395         }
    396     };
    397     qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
    398 }
    399 
    400 SortedVector< wp<SensorService::SensorEventConnection> >
    401 SensorService::getActiveConnections() const
    402 {
    403     Mutex::Autolock _l(mLock);
    404     return mActiveConnections;
    405 }
    406 
    407 DefaultKeyedVector<int, SensorInterface*>
    408 SensorService::getActiveVirtualSensors() const
    409 {
    410     Mutex::Autolock _l(mLock);
    411     return mActiveVirtualSensors;
    412 }
    413 
    414 String8 SensorService::getSensorName(int handle) const {
    415     size_t count = mUserSensorList.size();
    416     for (size_t i=0 ; i<count ; i++) {
    417         const Sensor& sensor(mUserSensorList[i]);
    418         if (sensor.getHandle() == handle) {
    419             return sensor.getName();
    420         }
    421     }
    422     String8 result("unknown");
    423     return result;
    424 }
    425 
    426 int SensorService::getSensorType(int handle) const {
    427     size_t count = mUserSensorList.size();
    428     for (size_t i=0 ; i<count ; i++) {
    429         const Sensor& sensor(mUserSensorList[i]);
    430         if (sensor.getHandle() == handle) {
    431             return sensor.getType();
    432         }
    433     }
    434     return -1;
    435 }
    436 
    437 
    438 Vector<Sensor> SensorService::getSensorList()
    439 {
    440     char value[PROPERTY_VALUE_MAX];
    441     property_get("debug.sensors", value, "0");
    442     if (atoi(value)) {
    443         return mUserSensorListDebug;
    444     }
    445     return mUserSensorList;
    446 }
    447 
    448 sp<ISensorEventConnection> SensorService::createSensorEventConnection()
    449 {
    450     uid_t uid = IPCThreadState::self()->getCallingUid();
    451     sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
    452     return result;
    453 }
    454 
    455 void SensorService::cleanupConnection(SensorEventConnection* c)
    456 {
    457     Mutex::Autolock _l(mLock);
    458     const wp<SensorEventConnection> connection(c);
    459     size_t size = mActiveSensors.size();
    460     ALOGD_IF(DEBUG_CONNECTIONS, "%d active sensors", size);
    461     for (size_t i=0 ; i<size ; ) {
    462         int handle = mActiveSensors.keyAt(i);
    463         if (c->hasSensor(handle)) {
    464             ALOGD_IF(DEBUG_CONNECTIONS, "%i: disabling handle=0x%08x", i, handle);
    465             SensorInterface* sensor = mSensorMap.valueFor( handle );
    466             ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
    467             if (sensor) {
    468                 sensor->activate(c, false);
    469             }
    470         }
    471         SensorRecord* rec = mActiveSensors.valueAt(i);
    472         ALOGE_IF(!rec, "mActiveSensors[%d] is null (handle=0x%08x)!", i, handle);
    473         ALOGD_IF(DEBUG_CONNECTIONS,
    474                 "removing connection %p for sensor[%d].handle=0x%08x",
    475                 c, i, handle);
    476 
    477         if (rec && rec->removeConnection(connection)) {
    478             ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
    479             mActiveSensors.removeItemsAt(i, 1);
    480             mActiveVirtualSensors.removeItem(handle);
    481             delete rec;
    482             size--;
    483         } else {
    484             i++;
    485         }
    486     }
    487     mActiveConnections.remove(connection);
    488     BatteryService::cleanup(c->getUid());
    489 }
    490 
    491 status_t SensorService::enable(const sp<SensorEventConnection>& connection,
    492         int handle)
    493 {
    494     if (mInitCheck != NO_ERROR)
    495         return mInitCheck;
    496 
    497     SensorInterface* sensor = mSensorMap.valueFor(handle);
    498     if (sensor == NULL) {
    499         return BAD_VALUE;
    500     }
    501 
    502     Mutex::Autolock _l(mLock);
    503     SensorRecord* rec = mActiveSensors.valueFor(handle);
    504     if (rec == 0) {
    505         rec = new SensorRecord(connection);
    506         mActiveSensors.add(handle, rec);
    507         if (sensor->isVirtual()) {
    508             mActiveVirtualSensors.add(handle, sensor);
    509         }
    510     } else {
    511         if (rec->addConnection(connection)) {
    512             // this sensor is already activated, but we are adding a
    513             // connection that uses it. Immediately send down the last
    514             // known value of the requested sensor if it's not a
    515             // "continuous" sensor.
    516             if (sensor->getSensor().getMinDelay() == 0) {
    517                 sensors_event_t scratch;
    518                 sensors_event_t& event(mLastEventSeen.editValueFor(handle));
    519                 if (event.version == sizeof(sensors_event_t)) {
    520                     connection->sendEvents(&event, 1);
    521                 }
    522             }
    523         }
    524     }
    525 
    526     if (connection->addSensor(handle)) {
    527         BatteryService::enableSensor(connection->getUid(), handle);
    528         // the sensor was added (which means it wasn't already there)
    529         // so, see if this connection becomes active
    530         if (mActiveConnections.indexOf(connection) < 0) {
    531             mActiveConnections.add(connection);
    532         }
    533     } else {
    534         ALOGW("sensor %08x already enabled in connection %p (ignoring)",
    535             handle, connection.get());
    536     }
    537 
    538     // we are setup, now enable the sensor.
    539     status_t err = sensor->activate(connection.get(), true);
    540     if (err != NO_ERROR) {
    541         // enable has failed, reset our state.
    542         cleanupWithoutDisableLocked(connection, handle);
    543     }
    544     return err;
    545 }
    546 
    547 status_t SensorService::disable(const sp<SensorEventConnection>& connection,
    548         int handle)
    549 {
    550     if (mInitCheck != NO_ERROR)
    551         return mInitCheck;
    552 
    553     Mutex::Autolock _l(mLock);
    554     status_t err = cleanupWithoutDisableLocked(connection, handle);
    555     if (err == NO_ERROR) {
    556         SensorInterface* sensor = mSensorMap.valueFor(handle);
    557         err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
    558     }
    559     return err;
    560 }
    561 
    562 status_t SensorService::cleanupWithoutDisable(
    563         const sp<SensorEventConnection>& connection, int handle) {
    564     Mutex::Autolock _l(mLock);
    565     return cleanupWithoutDisableLocked(connection, handle);
    566 }
    567 
    568 status_t SensorService::cleanupWithoutDisableLocked(
    569         const sp<SensorEventConnection>& connection, int handle) {
    570     SensorRecord* rec = mActiveSensors.valueFor(handle);
    571     if (rec) {
    572         // see if this connection becomes inactive
    573         if (connection->removeSensor(handle)) {
    574             BatteryService::disableSensor(connection->getUid(), handle);
    575         }
    576         if (connection->hasAnySensor() == false) {
    577             mActiveConnections.remove(connection);
    578         }
    579         // see if this sensor becomes inactive
    580         if (rec->removeConnection(connection)) {
    581             mActiveSensors.removeItem(handle);
    582             mActiveVirtualSensors.removeItem(handle);
    583             delete rec;
    584         }
    585         return NO_ERROR;
    586     }
    587     return BAD_VALUE;
    588 }
    589 
    590 status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
    591         int handle, nsecs_t ns)
    592 {
    593     if (mInitCheck != NO_ERROR)
    594         return mInitCheck;
    595 
    596     SensorInterface* sensor = mSensorMap.valueFor(handle);
    597     if (!sensor)
    598         return BAD_VALUE;
    599 
    600     if (ns < 0)
    601         return BAD_VALUE;
    602 
    603     nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
    604     if (ns < minDelayNs) {
    605         ns = minDelayNs;
    606     }
    607 
    608     if (ns < MINIMUM_EVENTS_PERIOD)
    609         ns = MINIMUM_EVENTS_PERIOD;
    610 
    611     return sensor->setDelay(connection.get(), handle, ns);
    612 }
    613 
    614 // ---------------------------------------------------------------------------
    615 
    616 SensorService::SensorRecord::SensorRecord(
    617         const sp<SensorEventConnection>& connection)
    618 {
    619     mConnections.add(connection);
    620 }
    621 
    622 bool SensorService::SensorRecord::addConnection(
    623         const sp<SensorEventConnection>& connection)
    624 {
    625     if (mConnections.indexOf(connection) < 0) {
    626         mConnections.add(connection);
    627         return true;
    628     }
    629     return false;
    630 }
    631 
    632 bool SensorService::SensorRecord::removeConnection(
    633         const wp<SensorEventConnection>& connection)
    634 {
    635     ssize_t index = mConnections.indexOf(connection);
    636     if (index >= 0) {
    637         mConnections.removeItemsAt(index, 1);
    638     }
    639     return mConnections.size() ? false : true;
    640 }
    641 
    642 // ---------------------------------------------------------------------------
    643 
    644 SensorService::SensorEventConnection::SensorEventConnection(
    645         const sp<SensorService>& service, uid_t uid)
    646     : mService(service), mChannel(new BitTube()), mUid(uid)
    647 {
    648 }
    649 
    650 SensorService::SensorEventConnection::~SensorEventConnection()
    651 {
    652     ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
    653     mService->cleanupConnection(this);
    654 }
    655 
    656 void SensorService::SensorEventConnection::onFirstRef()
    657 {
    658 }
    659 
    660 bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
    661     Mutex::Autolock _l(mConnectionLock);
    662     if (mSensorInfo.indexOf(handle) < 0) {
    663         mSensorInfo.add(handle);
    664         return true;
    665     }
    666     return false;
    667 }
    668 
    669 bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
    670     Mutex::Autolock _l(mConnectionLock);
    671     if (mSensorInfo.remove(handle) >= 0) {
    672         return true;
    673     }
    674     return false;
    675 }
    676 
    677 bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
    678     Mutex::Autolock _l(mConnectionLock);
    679     return mSensorInfo.indexOf(handle) >= 0;
    680 }
    681 
    682 bool SensorService::SensorEventConnection::hasAnySensor() const {
    683     Mutex::Autolock _l(mConnectionLock);
    684     return mSensorInfo.size() ? true : false;
    685 }
    686 
    687 status_t SensorService::SensorEventConnection::sendEvents(
    688         sensors_event_t const* buffer, size_t numEvents,
    689         sensors_event_t* scratch)
    690 {
    691     // filter out events not for this connection
    692     size_t count = 0;
    693     if (scratch) {
    694         Mutex::Autolock _l(mConnectionLock);
    695         size_t i=0;
    696         while (i<numEvents) {
    697             const int32_t curr = buffer[i].sensor;
    698             if (mSensorInfo.indexOf(curr) >= 0) {
    699                 do {
    700                     scratch[count++] = buffer[i++];
    701                 } while ((i<numEvents) && (buffer[i].sensor == curr));
    702             } else {
    703                 i++;
    704             }
    705         }
    706     } else {
    707         scratch = const_cast<sensors_event_t *>(buffer);
    708         count = numEvents;
    709     }
    710 
    711     // NOTE: ASensorEvent and sensors_event_t are the same type
    712     ssize_t size = SensorEventQueue::write(mChannel,
    713             reinterpret_cast<ASensorEvent const*>(scratch), count);
    714     if (size == -EAGAIN) {
    715         // the destination doesn't accept events anymore, it's probably
    716         // full. For now, we just drop the events on the floor.
    717         //ALOGW("dropping %d events on the floor", count);
    718         return size;
    719     }
    720 
    721     return size < 0 ? status_t(size) : status_t(NO_ERROR);
    722 }
    723 
    724 sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
    725 {
    726     return mChannel;
    727 }
    728 
    729 status_t SensorService::SensorEventConnection::enableDisable(
    730         int handle, bool enabled)
    731 {
    732     status_t err;
    733     if (enabled) {
    734         err = mService->enable(this, handle);
    735     } else {
    736         err = mService->disable(this, handle);
    737     }
    738     return err;
    739 }
    740 
    741 status_t SensorService::SensorEventConnection::setEventRate(
    742         int handle, nsecs_t ns)
    743 {
    744     return mService->setEventRate(this, handle, ns);
    745 }
    746 
    747 // ---------------------------------------------------------------------------
    748 }; // namespace android
    749 
    750