SensorService.cpp revision 4c01b1ad80e084f0cd1057f89fdd1fcedf19dd96
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
52namespace 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
64const char* SensorService::WAKE_LOCK_NAME = "SensorService";
65
66SensorService::SensorService()
67    : mInitCheck(NO_INIT)
68{
69}
70
71void 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
166void 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
180void SensorService::registerVirtualSensor(SensorInterface* s)
181{
182    registerSensor(s);
183    mVirtualSensorList.add( s );
184}
185
186SensorService::~SensorService()
187{
188    for (size_t i=0 ; i<mSensorMap.size() ; i++)
189        delete mSensorMap.valueAt(i);
190}
191
192static const String16 sDump("android.permission.DUMP");
193
194status_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
243void 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                err = sensor ?sensor->resetStateWithoutActuatingHardware(connection.get(), handle)
253                        : status_t(BAD_VALUE);
254                if (err != NO_ERROR) {
255                    ALOGE("Sensor Inteface: Resetting state failed with err: %d", err);
256                }
257                cleanupWithoutDisable(connection, handle);
258            }
259        }
260    }
261}
262
263bool SensorService::threadLoop()
264{
265    ALOGD("nuSensorService thread starting...");
266
267    const size_t numEventMax = 16;
268    const size_t minBufferSize = numEventMax + numEventMax * mVirtualSensorList.size();
269    sensors_event_t buffer[minBufferSize];
270    sensors_event_t scratch[minBufferSize];
271    SensorDevice& device(SensorDevice::getInstance());
272    const size_t vcount = mVirtualSensorList.size();
273
274    ssize_t count;
275    bool wakeLockAcquired = false;
276    const int halVersion = device.getHalDeviceVersion();
277    do {
278        count = device.poll(buffer, numEventMax);
279        if (count<0) {
280            ALOGE("sensor poll failed (%s)", strerror(-count));
281            break;
282        }
283
284        // Poll has returned. Hold a wakelock.
285        // Todo(): add a flag to the sensors definitions to indicate
286        // the sensors which can wake up the AP
287        for (int i = 0; i < count; i++) {
288            if (getSensorType(buffer[i].sensor) == SENSOR_TYPE_SIGNIFICANT_MOTION) {
289                 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
290                 wakeLockAcquired = true;
291                 break;
292            }
293        }
294
295        recordLastValue(buffer, count);
296
297        // handle virtual sensors
298        if (count && vcount) {
299            sensors_event_t const * const event = buffer;
300            const DefaultKeyedVector<int, SensorInterface*> virtualSensors(
301                    getActiveVirtualSensors());
302            const size_t activeVirtualSensorCount = virtualSensors.size();
303            if (activeVirtualSensorCount) {
304                size_t k = 0;
305                SensorFusion& fusion(SensorFusion::getInstance());
306                if (fusion.isEnabled()) {
307                    for (size_t i=0 ; i<size_t(count) ; i++) {
308                        fusion.process(event[i]);
309                    }
310                }
311                for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
312                    for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
313                        if (count + k >= minBufferSize) {
314                            ALOGE("buffer too small to hold all events: "
315                                    "count=%u, k=%u, size=%u",
316                                    count, k, minBufferSize);
317                            break;
318                        }
319                        sensors_event_t out;
320                        SensorInterface* si = virtualSensors.valueAt(j);
321                        if (si->process(&out, event[i])) {
322                            buffer[count + k] = out;
323                            k++;
324                        }
325                    }
326                }
327                if (k) {
328                    // record the last synthesized values
329                    recordLastValue(&buffer[count], k);
330                    count += k;
331                    // sort the buffer by time-stamps
332                    sortEventBuffer(buffer, count);
333                }
334            }
335        }
336
337        // handle backward compatibility for RotationVector sensor
338        if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
339            for (int i = 0; i < count; i++) {
340                if (getSensorType(buffer[i].sensor) == SENSOR_TYPE_ROTATION_VECTOR) {
341                    // All the 4 components of the quaternion should be available
342                    // No heading accuracy. Set it to -1
343                    buffer[i].data[4] = -1;
344                }
345            }
346        }
347
348        // send our events to clients...
349        const SortedVector< wp<SensorEventConnection> > activeConnections(
350                getActiveConnections());
351        size_t numConnections = activeConnections.size();
352        for (size_t i=0 ; i<numConnections ; i++) {
353            sp<SensorEventConnection> connection(
354                    activeConnections[i].promote());
355            if (connection != 0) {
356                connection->sendEvents(buffer, count, scratch);
357                // Some sensors need to be auto disabled after the trigger
358                cleanupAutoDisabledSensor(connection, buffer, count);
359            }
360        }
361
362        // We have read the data, upper layers should hold the wakelock.
363        if (wakeLockAcquired) release_wake_lock(WAKE_LOCK_NAME);
364
365    } while (count >= 0 || Thread::exitPending());
366
367    ALOGW("Exiting SensorService::threadLoop => aborting...");
368    abort();
369    return false;
370}
371
372void SensorService::recordLastValue(
373        sensors_event_t const * buffer, size_t count)
374{
375    Mutex::Autolock _l(mLock);
376
377    // record the last event for each sensor
378    int32_t prev = buffer[0].sensor;
379    for (size_t i=1 ; i<count ; i++) {
380        // record the last event of each sensor type in this buffer
381        int32_t curr = buffer[i].sensor;
382        if (curr != prev) {
383            mLastEventSeen.editValueFor(prev) = buffer[i-1];
384            prev = curr;
385        }
386    }
387    mLastEventSeen.editValueFor(prev) = buffer[count-1];
388}
389
390void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
391{
392    struct compar {
393        static int cmp(void const* lhs, void const* rhs) {
394            sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
395            sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
396            return l->timestamp - r->timestamp;
397        }
398    };
399    qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
400}
401
402SortedVector< wp<SensorService::SensorEventConnection> >
403SensorService::getActiveConnections() const
404{
405    Mutex::Autolock _l(mLock);
406    return mActiveConnections;
407}
408
409DefaultKeyedVector<int, SensorInterface*>
410SensorService::getActiveVirtualSensors() const
411{
412    Mutex::Autolock _l(mLock);
413    return mActiveVirtualSensors;
414}
415
416String8 SensorService::getSensorName(int handle) const {
417    size_t count = mUserSensorList.size();
418    for (size_t i=0 ; i<count ; i++) {
419        const Sensor& sensor(mUserSensorList[i]);
420        if (sensor.getHandle() == handle) {
421            return sensor.getName();
422        }
423    }
424    String8 result("unknown");
425    return result;
426}
427
428int SensorService::getSensorType(int handle) const {
429    size_t count = mUserSensorList.size();
430    for (size_t i=0 ; i<count ; i++) {
431        const Sensor& sensor(mUserSensorList[i]);
432        if (sensor.getHandle() == handle) {
433            return sensor.getType();
434        }
435    }
436    return -1;
437}
438
439
440Vector<Sensor> SensorService::getSensorList()
441{
442    char value[PROPERTY_VALUE_MAX];
443    property_get("debug.sensors", value, "0");
444    if (atoi(value)) {
445        return mUserSensorListDebug;
446    }
447    return mUserSensorList;
448}
449
450sp<ISensorEventConnection> SensorService::createSensorEventConnection()
451{
452    uid_t uid = IPCThreadState::self()->getCallingUid();
453    sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
454    return result;
455}
456
457void SensorService::cleanupConnection(SensorEventConnection* c)
458{
459    Mutex::Autolock _l(mLock);
460    const wp<SensorEventConnection> connection(c);
461    size_t size = mActiveSensors.size();
462    ALOGD_IF(DEBUG_CONNECTIONS, "%d active sensors", size);
463    for (size_t i=0 ; i<size ; ) {
464        int handle = mActiveSensors.keyAt(i);
465        if (c->hasSensor(handle)) {
466            ALOGD_IF(DEBUG_CONNECTIONS, "%i: disabling handle=0x%08x", i, handle);
467            SensorInterface* sensor = mSensorMap.valueFor( handle );
468            ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
469            if (sensor) {
470                sensor->activate(c, false);
471            }
472        }
473        SensorRecord* rec = mActiveSensors.valueAt(i);
474        ALOGE_IF(!rec, "mActiveSensors[%d] is null (handle=0x%08x)!", i, handle);
475        ALOGD_IF(DEBUG_CONNECTIONS,
476                "removing connection %p for sensor[%d].handle=0x%08x",
477                c, i, handle);
478
479        if (rec && rec->removeConnection(connection)) {
480            ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
481            mActiveSensors.removeItemsAt(i, 1);
482            mActiveVirtualSensors.removeItem(handle);
483            delete rec;
484            size--;
485        } else {
486            i++;
487        }
488    }
489    mActiveConnections.remove(connection);
490    BatteryService::cleanup(c->getUid());
491}
492
493status_t SensorService::enable(const sp<SensorEventConnection>& connection,
494        int handle)
495{
496    if (mInitCheck != NO_ERROR)
497        return mInitCheck;
498
499    Mutex::Autolock _l(mLock);
500    SensorInterface* sensor = mSensorMap.valueFor(handle);
501    SensorRecord* rec = mActiveSensors.valueFor(handle);
502    if (rec == 0) {
503        rec = new SensorRecord(connection);
504        mActiveSensors.add(handle, rec);
505        if (sensor->isVirtual()) {
506            mActiveVirtualSensors.add(handle, sensor);
507        }
508    } else {
509        if (rec->addConnection(connection)) {
510            // this sensor is already activated, but we are adding a
511            // connection that uses it. Immediately send down the last
512            // known value of the requested sensor if it's not a
513            // "continuous" sensor.
514            if (sensor->getSensor().getMinDelay() == 0) {
515                sensors_event_t scratch;
516                sensors_event_t& event(mLastEventSeen.editValueFor(handle));
517                if (event.version == sizeof(sensors_event_t)) {
518                    connection->sendEvents(&event, 1);
519                }
520            }
521        }
522    }
523
524    if (connection->addSensor(handle)) {
525        BatteryService::enableSensor(connection->getUid(), handle);
526        // the sensor was added (which means it wasn't already there)
527        // so, see if this connection becomes active
528        if (mActiveConnections.indexOf(connection) < 0) {
529            mActiveConnections.add(connection);
530        }
531    } else {
532        ALOGW("sensor %08x already enabled in connection %p (ignoring)",
533            handle, connection.get());
534    }
535
536
537    // we are setup, now enable the sensor.
538    status_t err = sensor ? sensor->activate(connection.get(), true) : status_t(BAD_VALUE);
539
540    if (err != NO_ERROR) {
541        // enable has failed, reset state in SensorDevice.
542        status_t resetErr = sensor ? sensor->resetStateWithoutActuatingHardware(connection.get(),
543                handle) : status_t(BAD_VALUE);
544        // enable has failed, reset our state.
545        cleanupWithoutDisable(connection, handle);
546    }
547    return err;
548}
549
550status_t SensorService::disable(const sp<SensorEventConnection>& connection,
551        int handle)
552{
553    if (mInitCheck != NO_ERROR)
554        return mInitCheck;
555
556    status_t err = cleanupWithoutDisable(connection, handle);
557    if (err == NO_ERROR) {
558        SensorInterface* sensor = mSensorMap.valueFor(handle);
559        err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
560    }
561    return err;
562}
563
564status_t SensorService::cleanupWithoutDisable(const sp<SensorEventConnection>& connection,
565        int handle) {
566    Mutex::Autolock _l(mLock);
567    SensorRecord* rec = mActiveSensors.valueFor(handle);
568    if (rec) {
569        // see if this connection becomes inactive
570        if (connection->removeSensor(handle)) {
571            BatteryService::disableSensor(connection->getUid(), handle);
572        }
573        if (connection->hasAnySensor() == false) {
574            mActiveConnections.remove(connection);
575        }
576        // see if this sensor becomes inactive
577        if (rec->removeConnection(connection)) {
578            mActiveSensors.removeItem(handle);
579            mActiveVirtualSensors.removeItem(handle);
580            delete rec;
581        }
582        return NO_ERROR;
583    }
584    return BAD_VALUE;
585}
586
587status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
588        int handle, nsecs_t ns)
589{
590    if (mInitCheck != NO_ERROR)
591        return mInitCheck;
592
593    SensorInterface* sensor = mSensorMap.valueFor(handle);
594    if (!sensor)
595        return BAD_VALUE;
596
597    if (ns < 0)
598        return BAD_VALUE;
599
600    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
601    if (ns < minDelayNs) {
602        ns = minDelayNs;
603    }
604
605    if (ns < MINIMUM_EVENTS_PERIOD)
606        ns = MINIMUM_EVENTS_PERIOD;
607
608    return sensor->setDelay(connection.get(), handle, ns);
609}
610
611// ---------------------------------------------------------------------------
612
613SensorService::SensorRecord::SensorRecord(
614        const sp<SensorEventConnection>& connection)
615{
616    mConnections.add(connection);
617}
618
619bool SensorService::SensorRecord::addConnection(
620        const sp<SensorEventConnection>& connection)
621{
622    if (mConnections.indexOf(connection) < 0) {
623        mConnections.add(connection);
624        return true;
625    }
626    return false;
627}
628
629bool SensorService::SensorRecord::removeConnection(
630        const wp<SensorEventConnection>& connection)
631{
632    ssize_t index = mConnections.indexOf(connection);
633    if (index >= 0) {
634        mConnections.removeItemsAt(index, 1);
635    }
636    return mConnections.size() ? false : true;
637}
638
639// ---------------------------------------------------------------------------
640
641SensorService::SensorEventConnection::SensorEventConnection(
642        const sp<SensorService>& service, uid_t uid)
643    : mService(service), mChannel(new BitTube()), mUid(uid)
644{
645}
646
647SensorService::SensorEventConnection::~SensorEventConnection()
648{
649    ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
650    mService->cleanupConnection(this);
651}
652
653void SensorService::SensorEventConnection::onFirstRef()
654{
655}
656
657bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
658    Mutex::Autolock _l(mConnectionLock);
659    if (mSensorInfo.indexOf(handle) < 0) {
660        mSensorInfo.add(handle);
661        return true;
662    }
663    return false;
664}
665
666bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
667    Mutex::Autolock _l(mConnectionLock);
668    if (mSensorInfo.remove(handle) >= 0) {
669        return true;
670    }
671    return false;
672}
673
674bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
675    Mutex::Autolock _l(mConnectionLock);
676    return mSensorInfo.indexOf(handle) >= 0;
677}
678
679bool SensorService::SensorEventConnection::hasAnySensor() const {
680    Mutex::Autolock _l(mConnectionLock);
681    return mSensorInfo.size() ? true : false;
682}
683
684status_t SensorService::SensorEventConnection::sendEvents(
685        sensors_event_t const* buffer, size_t numEvents,
686        sensors_event_t* scratch)
687{
688    // filter out events not for this connection
689    size_t count = 0;
690    if (scratch) {
691        Mutex::Autolock _l(mConnectionLock);
692        size_t i=0;
693        while (i<numEvents) {
694            const int32_t curr = buffer[i].sensor;
695            if (mSensorInfo.indexOf(curr) >= 0) {
696                do {
697                    scratch[count++] = buffer[i++];
698                } while ((i<numEvents) && (buffer[i].sensor == curr));
699            } else {
700                i++;
701            }
702        }
703    } else {
704        scratch = const_cast<sensors_event_t *>(buffer);
705        count = numEvents;
706    }
707
708    // NOTE: ASensorEvent and sensors_event_t are the same type
709    ssize_t size = SensorEventQueue::write(mChannel,
710            reinterpret_cast<ASensorEvent const*>(scratch), count);
711    if (size == -EAGAIN) {
712        // the destination doesn't accept events anymore, it's probably
713        // full. For now, we just drop the events on the floor.
714        //ALOGW("dropping %d events on the floor", count);
715        return size;
716    }
717
718    return size < 0 ? status_t(size) : status_t(NO_ERROR);
719}
720
721sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
722{
723    return mChannel;
724}
725
726status_t SensorService::SensorEventConnection::enableDisable(
727        int handle, bool enabled)
728{
729    status_t err;
730    if (enabled) {
731        err = mService->enable(this, handle);
732    } else {
733        err = mService->disable(this, handle);
734    }
735    return err;
736}
737
738status_t SensorService::SensorEventConnection::setEventRate(
739        int handle, nsecs_t ns)
740{
741    return mService->setEventRate(this, handle, ns);
742}
743
744// ---------------------------------------------------------------------------
745}; // namespace android
746
747