SensorService.cpp revision d4dabf872ac0a12e12aebae9032f7d62762c2aeb
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 <inttypes.h>
18#include <math.h>
19#include <stdint.h>
20#include <sys/types.h>
21
22#include <cutils/properties.h>
23
24#include <utils/SortedVector.h>
25#include <utils/KeyedVector.h>
26#include <utils/threads.h>
27#include <utils/Atomic.h>
28#include <utils/Errors.h>
29#include <utils/RefBase.h>
30#include <utils/Singleton.h>
31#include <utils/String16.h>
32
33#include <binder/BinderService.h>
34#include <binder/IServiceManager.h>
35#include <binder/PermissionCache.h>
36
37#include <gui/ISensorServer.h>
38#include <gui/ISensorEventConnection.h>
39#include <gui/SensorEventQueue.h>
40
41#include <hardware/sensors.h>
42#include <hardware_legacy/power.h>
43
44#include "BatteryService.h"
45#include "CorrectedGyroSensor.h"
46#include "GravitySensor.h"
47#include "LinearAccelerationSensor.h"
48#include "OrientationSensor.h"
49#include "RotationVectorSensor.h"
50#include "SensorFusion.h"
51#include "SensorService.h"
52
53namespace android {
54// ---------------------------------------------------------------------------
55
56/*
57 * Notes:
58 *
59 * - what about a gyro-corrected magnetic-field sensor?
60 * - run mag sensor from time to time to force calibration
61 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
62 *
63 */
64
65const char* SensorService::WAKE_LOCK_NAME = "SensorService";
66
67SensorService::SensorService()
68    : mInitCheck(NO_INIT)
69{
70}
71
72void SensorService::onFirstRef()
73{
74    ALOGD("nuSensorService starting...");
75
76    SensorDevice& dev(SensorDevice::getInstance());
77
78    if (dev.initCheck() == NO_ERROR) {
79        sensor_t const* list;
80        ssize_t count = dev.getSensorList(&list);
81        if (count > 0) {
82            ssize_t orientationIndex = -1;
83            bool hasGyro = false;
84            uint32_t virtualSensorsNeeds =
85                    (1<<SENSOR_TYPE_GRAVITY) |
86                    (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
87                    (1<<SENSOR_TYPE_ROTATION_VECTOR);
88
89            mLastEventSeen.setCapacity(count);
90            for (ssize_t i=0 ; i<count ; i++) {
91                registerSensor( new HardwareSensor(list[i]) );
92                switch (list[i].type) {
93                    case SENSOR_TYPE_ORIENTATION:
94                        orientationIndex = i;
95                        break;
96                    case SENSOR_TYPE_GYROSCOPE:
97                    case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
98                        hasGyro = true;
99                        break;
100                    case SENSOR_TYPE_GRAVITY:
101                    case SENSOR_TYPE_LINEAR_ACCELERATION:
102                    case SENSOR_TYPE_ROTATION_VECTOR:
103                        virtualSensorsNeeds &= ~(1<<list[i].type);
104                        break;
105                }
106            }
107
108            // it's safe to instantiate the SensorFusion object here
109            // (it wants to be instantiated after h/w sensors have been
110            // registered)
111            const SensorFusion& fusion(SensorFusion::getInstance());
112
113            // build the sensor list returned to users
114            mUserSensorList = mSensorList;
115
116            if (hasGyro) {
117                Sensor aSensor;
118
119                // Add Android virtual sensors if they're not already
120                // available in the HAL
121
122                aSensor = registerVirtualSensor( new RotationVectorSensor() );
123                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
124                    mUserSensorList.add(aSensor);
125                }
126
127                aSensor = registerVirtualSensor( new GravitySensor(list, count) );
128                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
129                    mUserSensorList.add(aSensor);
130                }
131
132                aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );
133                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
134                    mUserSensorList.add(aSensor);
135                }
136
137                aSensor = registerVirtualSensor( new OrientationSensor() );
138                if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
139                    // if we are doing our own rotation-vector, also add
140                    // the orientation sensor and remove the HAL provided one.
141                    mUserSensorList.replaceAt(aSensor, orientationIndex);
142                }
143
144                // virtual debugging sensors are not added to mUserSensorList
145                registerVirtualSensor( new CorrectedGyroSensor(list, count) );
146                registerVirtualSensor( new GyroDriftSensor() );
147            }
148
149            // debugging sensor list
150            mUserSensorListDebug = mSensorList;
151
152            mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
153            FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
154            char line[128];
155            if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
156                line[sizeof(line) - 1] = '\0';
157                sscanf(line, "%zu", &mSocketBufferSize);
158                if (mSocketBufferSize > MAX_SOCKET_BUFFER_SIZE_BATCHED) {
159                    mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
160                }
161            }
162            ALOGD("Max socket buffer size %u", mSocketBufferSize);
163            if (fp) {
164                fclose(fp);
165            }
166
167            run("SensorService", PRIORITY_URGENT_DISPLAY);
168            mInitCheck = NO_ERROR;
169        }
170    }
171}
172
173Sensor SensorService::registerSensor(SensorInterface* s)
174{
175    sensors_event_t event;
176    memset(&event, 0, sizeof(event));
177
178    const Sensor sensor(s->getSensor());
179    // add to the sensor list (returned to clients)
180    mSensorList.add(sensor);
181    // add to our handle->SensorInterface mapping
182    mSensorMap.add(sensor.getHandle(), s);
183    // create an entry in the mLastEventSeen array
184    mLastEventSeen.add(sensor.getHandle(), event);
185
186    return sensor;
187}
188
189Sensor SensorService::registerVirtualSensor(SensorInterface* s)
190{
191    Sensor sensor = registerSensor(s);
192    mVirtualSensorList.add( s );
193    return sensor;
194}
195
196SensorService::~SensorService()
197{
198    for (size_t i=0 ; i<mSensorMap.size() ; i++)
199        delete mSensorMap.valueAt(i);
200}
201
202static const String16 sDump("android.permission.DUMP");
203
204status_t SensorService::dump(int fd, const Vector<String16>& /*args*/)
205{
206    String8 result;
207    if (!PermissionCache::checkCallingPermission(sDump)) {
208        result.appendFormat("Permission Denial: "
209                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
210                IPCThreadState::self()->getCallingPid(),
211                IPCThreadState::self()->getCallingUid());
212    } else {
213        Mutex::Autolock _l(mLock);
214        result.append("Sensor List:\n");
215        for (size_t i=0 ; i<mSensorList.size() ; i++) {
216            const Sensor& s(mSensorList[i]);
217            const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
218            result.appendFormat(
219                    "%-48s| %-32s | 0x%08x | ",
220                    s.getName().string(),
221                    s.getVendor().string(),
222                    s.getHandle());
223
224            if (s.getMinDelay() > 0) {
225                result.appendFormat(
226                    "maxRate=%7.2fHz | ", 1e6f / s.getMinDelay());
227            } else {
228                result.append(s.getMinDelay() == 0
229                        ? "on-demand         | "
230                        : "one-shot          | ");
231            }
232            if (s.getFifoMaxEventCount() > 0) {
233                result.appendFormat("getFifoMaxEventCount=%d events | ", s.getFifoMaxEventCount());
234            } else {
235                result.append("no batching support | ");
236            }
237
238            switch (s.getType()) {
239                case SENSOR_TYPE_ROTATION_VECTOR:
240                case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
241                    result.appendFormat(
242                            "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n",
243                            e.data[0], e.data[1], e.data[2], e.data[3], e.data[4]);
244                    break;
245                case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
246                case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
247                    result.appendFormat(
248                            "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n",
249                            e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5]);
250                    break;
251                case SENSOR_TYPE_GAME_ROTATION_VECTOR:
252                    result.appendFormat(
253                            "last=<%5.1f,%5.1f,%5.1f,%5.1f>\n",
254                            e.data[0], e.data[1], e.data[2], e.data[3]);
255                    break;
256                case SENSOR_TYPE_SIGNIFICANT_MOTION:
257                case SENSOR_TYPE_STEP_DETECTOR:
258                    result.appendFormat( "last=<%f>\n", e.data[0]);
259                    break;
260                case SENSOR_TYPE_STEP_COUNTER:
261                    result.appendFormat( "last=<%" PRIu64 ">\n", e.u64.step_counter);
262                    break;
263                default:
264                    // default to 3 values
265                    result.appendFormat(
266                            "last=<%5.1f,%5.1f,%5.1f>\n",
267                            e.data[0], e.data[1], e.data[2]);
268                    break;
269            }
270        }
271        SensorFusion::getInstance().dump(result);
272        SensorDevice::getInstance().dump(result);
273
274        result.append("Active sensors:\n");
275        for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
276            int handle = mActiveSensors.keyAt(i);
277            result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
278                    getSensorName(handle).string(),
279                    handle,
280                    mActiveSensors.valueAt(i)->getNumConnections());
281        }
282
283        result.appendFormat("%zu Max Socket Buffer size\n", mSocketBufferSize);
284        result.appendFormat("%zd active connections\n", mActiveConnections.size());
285
286        for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
287            sp<SensorEventConnection> connection(mActiveConnections[i].promote());
288            if (connection != 0) {
289                result.appendFormat("Connection Number: %zu \n", i);
290                connection->dump(result);
291            }
292        }
293    }
294    write(fd, result.string(), result.size());
295    return NO_ERROR;
296}
297
298void SensorService::cleanupAutoDisabledSensor(const sp<SensorEventConnection>& connection,
299        sensors_event_t const* buffer, const int count) {
300    SensorInterface* sensor;
301    status_t err = NO_ERROR;
302    for (int i=0 ; i<count ; i++) {
303        int handle = buffer[i].sensor;
304        int type = buffer[i].type;
305        if (type == SENSOR_TYPE_SIGNIFICANT_MOTION) {
306            if (connection->hasSensor(handle)) {
307                sensor = mSensorMap.valueFor(handle);
308                if (sensor != NULL) {
309                    sensor->autoDisable(connection.get(), handle);
310                }
311                cleanupWithoutDisable(connection, handle);
312            }
313        }
314    }
315}
316
317bool SensorService::threadLoop()
318{
319    ALOGD("nuSensorService thread starting...");
320
321    // each virtual sensor could generate an event per "real" event, that's why we need
322    // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT.
323    // in practice, this is too aggressive, but guaranteed to be enough.
324    const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
325    const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
326
327    sensors_event_t buffer[minBufferSize];
328    sensors_event_t scratch[minBufferSize];
329    SensorDevice& device(SensorDevice::getInstance());
330    const size_t vcount = mVirtualSensorList.size();
331
332    ssize_t count;
333    bool wakeLockAcquired = false;
334    const int halVersion = device.getHalDeviceVersion();
335    do {
336        count = device.poll(buffer, numEventMax);
337        if (count<0) {
338            ALOGE("sensor poll failed (%s)", strerror(-count));
339            break;
340        }
341
342        // Poll has returned. Hold a wakelock.
343        // Todo(): add a flag to the sensors definitions to indicate
344        // the sensors which can wake up the AP
345        for (int i = 0; i < count; i++) {
346            if (buffer[i].type == SENSOR_TYPE_SIGNIFICANT_MOTION) {
347                 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
348                 wakeLockAcquired = true;
349                 break;
350            }
351        }
352
353        recordLastValue(buffer, count);
354
355        // handle virtual sensors
356        if (count && vcount) {
357            sensors_event_t const * const event = buffer;
358            const DefaultKeyedVector<int, SensorInterface*> virtualSensors(
359                    getActiveVirtualSensors());
360            const size_t activeVirtualSensorCount = virtualSensors.size();
361            if (activeVirtualSensorCount) {
362                size_t k = 0;
363                SensorFusion& fusion(SensorFusion::getInstance());
364                if (fusion.isEnabled()) {
365                    for (size_t i=0 ; i<size_t(count) ; i++) {
366                        fusion.process(event[i]);
367                    }
368                }
369                for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
370                    for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
371                        if (count + k >= minBufferSize) {
372                            ALOGE("buffer too small to hold all events: "
373                                    "count=%u, k=%u, size=%u",
374                                    count, k, minBufferSize);
375                            break;
376                        }
377                        sensors_event_t out;
378                        SensorInterface* si = virtualSensors.valueAt(j);
379                        if (si->process(&out, event[i])) {
380                            buffer[count + k] = out;
381                            k++;
382                        }
383                    }
384                }
385                if (k) {
386                    // record the last synthesized values
387                    recordLastValue(&buffer[count], k);
388                    count += k;
389                    // sort the buffer by time-stamps
390                    sortEventBuffer(buffer, count);
391                }
392            }
393        }
394
395        // handle backward compatibility for RotationVector sensor
396        if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
397            for (int i = 0; i < count; i++) {
398                if (buffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
399                    // All the 4 components of the quaternion should be available
400                    // No heading accuracy. Set it to -1
401                    buffer[i].data[4] = -1;
402                }
403            }
404        }
405
406        // send our events to clients...
407        const SortedVector< wp<SensorEventConnection> > activeConnections(
408                getActiveConnections());
409        size_t numConnections = activeConnections.size();
410        for (size_t i=0 ; i<numConnections ; i++) {
411            sp<SensorEventConnection> connection(
412                    activeConnections[i].promote());
413            if (connection != 0) {
414                connection->sendEvents(buffer, count, scratch);
415                // Some sensors need to be auto disabled after the trigger
416                cleanupAutoDisabledSensor(connection, buffer, count);
417            }
418        }
419
420        // We have read the data, upper layers should hold the wakelock.
421        if (wakeLockAcquired) release_wake_lock(WAKE_LOCK_NAME);
422    } while (count >= 0 || Thread::exitPending());
423
424    ALOGW("Exiting SensorService::threadLoop => aborting...");
425    abort();
426    return false;
427}
428
429void SensorService::recordLastValue(
430        const sensors_event_t* buffer, size_t count) {
431    Mutex::Autolock _l(mLock);
432    const sensors_event_t* last = NULL;
433    for (size_t i = 0; i < count; i++) {
434        const sensors_event_t* event = &buffer[i];
435        if (event->type != SENSOR_TYPE_META_DATA) {
436            if (last && event->sensor != last->sensor) {
437                mLastEventSeen.editValueFor(last->sensor) = *last;
438            }
439            last = event;
440        }
441    }
442    if (last) {
443        mLastEventSeen.editValueFor(last->sensor) = *last;
444    }
445}
446
447void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
448{
449    struct compar {
450        static int cmp(void const* lhs, void const* rhs) {
451            sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
452            sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
453            return l->timestamp - r->timestamp;
454        }
455    };
456    qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
457}
458
459SortedVector< wp<SensorService::SensorEventConnection> >
460SensorService::getActiveConnections() const
461{
462    Mutex::Autolock _l(mLock);
463    return mActiveConnections;
464}
465
466DefaultKeyedVector<int, SensorInterface*>
467SensorService::getActiveVirtualSensors() const
468{
469    Mutex::Autolock _l(mLock);
470    return mActiveVirtualSensors;
471}
472
473String8 SensorService::getSensorName(int handle) const {
474    size_t count = mUserSensorList.size();
475    for (size_t i=0 ; i<count ; i++) {
476        const Sensor& sensor(mUserSensorList[i]);
477        if (sensor.getHandle() == handle) {
478            return sensor.getName();
479        }
480    }
481    String8 result("unknown");
482    return result;
483}
484
485bool SensorService::isVirtualSensor(int handle) const {
486    SensorInterface* sensor = mSensorMap.valueFor(handle);
487    return sensor->isVirtual();
488}
489
490Vector<Sensor> SensorService::getSensorList()
491{
492    char value[PROPERTY_VALUE_MAX];
493    property_get("debug.sensors", value, "0");
494    if (atoi(value)) {
495        return mUserSensorListDebug;
496    }
497    return mUserSensorList;
498}
499
500sp<ISensorEventConnection> SensorService::createSensorEventConnection()
501{
502    uid_t uid = IPCThreadState::self()->getCallingUid();
503    sp<SensorEventConnection> result(new SensorEventConnection(this, uid));
504    return result;
505}
506
507void SensorService::cleanupConnection(SensorEventConnection* c)
508{
509    Mutex::Autolock _l(mLock);
510    const wp<SensorEventConnection> connection(c);
511    size_t size = mActiveSensors.size();
512    ALOGD_IF(DEBUG_CONNECTIONS, "%d active sensors", size);
513    for (size_t i=0 ; i<size ; ) {
514        int handle = mActiveSensors.keyAt(i);
515        if (c->hasSensor(handle)) {
516            ALOGD_IF(DEBUG_CONNECTIONS, "%i: disabling handle=0x%08x", i, handle);
517            SensorInterface* sensor = mSensorMap.valueFor( handle );
518            ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
519            if (sensor) {
520                sensor->activate(c, false);
521            }
522        }
523        SensorRecord* rec = mActiveSensors.valueAt(i);
524        ALOGE_IF(!rec, "mActiveSensors[%d] is null (handle=0x%08x)!", i, handle);
525        ALOGD_IF(DEBUG_CONNECTIONS,
526                "removing connection %p for sensor[%d].handle=0x%08x",
527                c, i, handle);
528
529        if (rec && rec->removeConnection(connection)) {
530            ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
531            mActiveSensors.removeItemsAt(i, 1);
532            mActiveVirtualSensors.removeItem(handle);
533            delete rec;
534            size--;
535        } else {
536            i++;
537        }
538    }
539    mActiveConnections.remove(connection);
540    BatteryService::cleanup(c->getUid());
541}
542
543status_t SensorService::enable(const sp<SensorEventConnection>& connection,
544        int handle, nsecs_t samplingPeriodNs,  nsecs_t maxBatchReportLatencyNs, int reservedFlags)
545{
546    if (mInitCheck != NO_ERROR)
547        return mInitCheck;
548
549    SensorInterface* sensor = mSensorMap.valueFor(handle);
550    if (sensor == NULL) {
551        return BAD_VALUE;
552    }
553    Mutex::Autolock _l(mLock);
554    SensorRecord* rec = mActiveSensors.valueFor(handle);
555    if (rec == 0) {
556        rec = new SensorRecord(connection);
557        mActiveSensors.add(handle, rec);
558        if (sensor->isVirtual()) {
559            mActiveVirtualSensors.add(handle, sensor);
560        }
561    } else {
562        if (rec->addConnection(connection)) {
563            // this sensor is already activated, but we are adding a
564            // connection that uses it. Immediately send down the last
565            // known value of the requested sensor if it's not a
566            // "continuous" sensor.
567            if (sensor->getSensor().getMinDelay() == 0) {
568                sensors_event_t scratch;
569                sensors_event_t& event(mLastEventSeen.editValueFor(handle));
570                if (event.version == sizeof(sensors_event_t)) {
571                    connection->sendEvents(&event, 1);
572                }
573            }
574        }
575    }
576
577    if (connection->addSensor(handle)) {
578        BatteryService::enableSensor(connection->getUid(), handle);
579        // the sensor was added (which means it wasn't already there)
580        // so, see if this connection becomes active
581        if (mActiveConnections.indexOf(connection) < 0) {
582            mActiveConnections.add(connection);
583        }
584    } else {
585        ALOGW("sensor %08x already enabled in connection %p (ignoring)",
586            handle, connection.get());
587    }
588
589    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
590    if (samplingPeriodNs < minDelayNs) {
591        samplingPeriodNs = minDelayNs;
592    }
593
594    ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d rate=%lld timeout== %lld",
595             handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
596
597    status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs,
598                                 maxBatchReportLatencyNs);
599    if (err == NO_ERROR) {
600        connection->setFirstFlushPending(handle, true);
601        status_t err_flush = sensor->flush(connection.get(), handle);
602        // Flush may return error if the sensor is not activated or the underlying h/w sensor does
603        // not support flush.
604        if (err_flush != NO_ERROR) {
605            connection->setFirstFlushPending(handle, false);
606        }
607    }
608
609    if (err == NO_ERROR) {
610        ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
611        err = sensor->activate(connection.get(), true);
612    }
613
614    if (err != NO_ERROR) {
615        // batch/activate has failed, reset our state.
616        cleanupWithoutDisableLocked(connection, handle);
617    }
618    return err;
619}
620
621status_t SensorService::disable(const sp<SensorEventConnection>& connection,
622        int handle)
623{
624    if (mInitCheck != NO_ERROR)
625        return mInitCheck;
626
627    Mutex::Autolock _l(mLock);
628    status_t err = cleanupWithoutDisableLocked(connection, handle);
629    if (err == NO_ERROR) {
630        SensorInterface* sensor = mSensorMap.valueFor(handle);
631        err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
632    }
633    return err;
634}
635
636status_t SensorService::cleanupWithoutDisable(
637        const sp<SensorEventConnection>& connection, int handle) {
638    Mutex::Autolock _l(mLock);
639    return cleanupWithoutDisableLocked(connection, handle);
640}
641
642status_t SensorService::cleanupWithoutDisableLocked(
643        const sp<SensorEventConnection>& connection, int handle) {
644    SensorRecord* rec = mActiveSensors.valueFor(handle);
645    if (rec) {
646        // see if this connection becomes inactive
647        if (connection->removeSensor(handle)) {
648            BatteryService::disableSensor(connection->getUid(), handle);
649        }
650        if (connection->hasAnySensor() == false) {
651            mActiveConnections.remove(connection);
652        }
653        // see if this sensor becomes inactive
654        if (rec->removeConnection(connection)) {
655            mActiveSensors.removeItem(handle);
656            mActiveVirtualSensors.removeItem(handle);
657            delete rec;
658        }
659        return NO_ERROR;
660    }
661    return BAD_VALUE;
662}
663
664status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
665        int handle, nsecs_t ns)
666{
667    if (mInitCheck != NO_ERROR)
668        return mInitCheck;
669
670    SensorInterface* sensor = mSensorMap.valueFor(handle);
671    if (!sensor)
672        return BAD_VALUE;
673
674    if (ns < 0)
675        return BAD_VALUE;
676
677    nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
678    if (ns < minDelayNs) {
679        ns = minDelayNs;
680    }
681
682    return sensor->setDelay(connection.get(), handle, ns);
683}
684
685status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
686                                    int handle) {
687  if (mInitCheck != NO_ERROR) return mInitCheck;
688  SensorInterface* sensor = mSensorMap.valueFor(handle);
689  if (sensor == NULL) {
690      return BAD_VALUE;
691  }
692  if (sensor->getSensor().getType() == SENSOR_TYPE_SIGNIFICANT_MOTION) {
693      ALOGE("flush called on Significant Motion sensor");
694      return INVALID_OPERATION;
695  }
696  return sensor->flush(connection.get(), handle);
697}
698// ---------------------------------------------------------------------------
699
700SensorService::SensorRecord::SensorRecord(
701        const sp<SensorEventConnection>& connection)
702{
703    mConnections.add(connection);
704}
705
706bool SensorService::SensorRecord::addConnection(
707        const sp<SensorEventConnection>& connection)
708{
709    if (mConnections.indexOf(connection) < 0) {
710        mConnections.add(connection);
711        return true;
712    }
713    return false;
714}
715
716bool SensorService::SensorRecord::removeConnection(
717        const wp<SensorEventConnection>& connection)
718{
719    ssize_t index = mConnections.indexOf(connection);
720    if (index >= 0) {
721        mConnections.removeItemsAt(index, 1);
722    }
723    return mConnections.size() ? false : true;
724}
725
726// ---------------------------------------------------------------------------
727
728SensorService::SensorEventConnection::SensorEventConnection(
729        const sp<SensorService>& service, uid_t uid)
730    : mService(service), mUid(uid)
731{
732    const SensorDevice& device(SensorDevice::getInstance());
733    if (device.getHalDeviceVersion() >= SENSORS_DEVICE_API_VERSION_1_1) {
734        // Increase socket buffer size to 1MB for batching capabilities.
735        mChannel = new BitTube(service->mSocketBufferSize);
736    } else {
737        mChannel = new BitTube(SOCKET_BUFFER_SIZE_NON_BATCHED);
738    }
739}
740
741SensorService::SensorEventConnection::~SensorEventConnection()
742{
743    ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this);
744    mService->cleanupConnection(this);
745}
746
747void SensorService::SensorEventConnection::onFirstRef()
748{
749}
750
751void SensorService::SensorEventConnection::dump(String8& result) {
752    Mutex::Autolock _l(mConnectionLock);
753    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
754        const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
755        result.appendFormat("\t %s | status: %s | pending flush events %d\n",
756                            mService->getSensorName(mSensorInfo.keyAt(i)).string(),
757                            flushInfo.mFirstFlushPending ? "First flush pending" :
758                                                           "active",
759                            flushInfo.mPendingFlushEventsToSend);
760    }
761}
762
763bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
764    Mutex::Autolock _l(mConnectionLock);
765    if (mSensorInfo.indexOfKey(handle) < 0) {
766        mSensorInfo.add(handle, FlushInfo());
767        return true;
768    }
769    return false;
770}
771
772bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
773    Mutex::Autolock _l(mConnectionLock);
774    if (mSensorInfo.removeItem(handle) >= 0) {
775        return true;
776    }
777    return false;
778}
779
780bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
781    Mutex::Autolock _l(mConnectionLock);
782    return mSensorInfo.indexOfKey(handle) >= 0;
783}
784
785bool SensorService::SensorEventConnection::hasAnySensor() const {
786    Mutex::Autolock _l(mConnectionLock);
787    return mSensorInfo.size() ? true : false;
788}
789
790void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
791                                bool value) {
792    Mutex::Autolock _l(mConnectionLock);
793    ssize_t index = mSensorInfo.indexOfKey(handle);
794    if (index >= 0) {
795        FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
796        flushInfo.mFirstFlushPending = value;
797    }
798}
799
800status_t SensorService::SensorEventConnection::sendEvents(
801        sensors_event_t const* buffer, size_t numEvents,
802        sensors_event_t* scratch)
803{
804    // filter out events not for this connection
805    size_t count = 0;
806
807    if (scratch) {
808        Mutex::Autolock _l(mConnectionLock);
809        size_t i=0;
810        while (i<numEvents) {
811            int32_t curr = buffer[i].sensor;
812            if (buffer[i].type == SENSOR_TYPE_META_DATA) {
813                ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ",
814                         buffer[i].meta_data.sensor);
815                // Setting curr to the correct sensor to ensure the sensor events per connection are
816                // filtered correctly. buffer[i].sensor is zero for meta_data events.
817                curr = buffer[i].meta_data.sensor;
818            }
819            ssize_t index = mSensorInfo.indexOfKey(curr);
820            if (index >= 0 && mSensorInfo[index].mFirstFlushPending == true &&
821                buffer[i].type == SENSOR_TYPE_META_DATA) {
822                // This is the first flush before activate is called. Events can now be sent for
823                // this sensor on this connection.
824                ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ",
825                         buffer[i].meta_data.sensor);
826                mSensorInfo.editValueAt(index).mFirstFlushPending = false;
827            }
828            if (index >= 0 && mSensorInfo[index].mFirstFlushPending == false)  {
829                do {
830                    scratch[count++] = buffer[i++];
831                } while ((i<numEvents) && ((buffer[i].sensor == curr) ||
832                         (buffer[i].type == SENSOR_TYPE_META_DATA  &&
833                          buffer[i].meta_data.sensor == curr)));
834            } else {
835                i++;
836            }
837        }
838    } else {
839        scratch = const_cast<sensors_event_t *>(buffer);
840        count = numEvents;
841    }
842
843    // Send pending flush events (if any) before sending events from the cache.
844    {
845        ASensorEvent flushCompleteEvent;
846        flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
847        flushCompleteEvent.sensor = 0;
848        Mutex::Autolock _l(mConnectionLock);
849        // Loop through all the sensors for this connection and check if there are any pending
850        // flush complete events to be sent.
851        for (size_t i = 0; i < mSensorInfo.size(); ++i) {
852            FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
853            while (flushInfo.mPendingFlushEventsToSend > 0) {
854                flushCompleteEvent.meta_data.sensor = mSensorInfo.keyAt(i);
855                ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1);
856                if (size < 0) {
857                    // ALOGW("dropping %d events on the floor", count);
858                    countFlushCompleteEventsLocked(scratch, count);
859                    return size;
860                }
861                ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ",
862                         flushCompleteEvent.meta_data.sensor);
863                flushInfo.mPendingFlushEventsToSend--;
864            }
865        }
866    }
867
868    // Early return if there are no events for this connection.
869    if (count == 0) {
870        return status_t(NO_ERROR);
871    }
872
873    // NOTE: ASensorEvent and sensors_event_t are the same type
874    ssize_t size = SensorEventQueue::write(mChannel,
875            reinterpret_cast<ASensorEvent const*>(scratch), count);
876    if (size == -EAGAIN) {
877        // the destination doesn't accept events anymore, it's probably
878        // full. For now, we just drop the events on the floor.
879        // ALOGW("dropping %d events on the floor", count);
880        Mutex::Autolock _l(mConnectionLock);
881        countFlushCompleteEventsLocked(scratch, count);
882        return size;
883    }
884
885    return size < 0 ? status_t(size) : status_t(NO_ERROR);
886}
887
888void SensorService::SensorEventConnection::countFlushCompleteEventsLocked(
889                sensors_event_t* scratch, const int numEventsDropped) {
890    ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped);
891    // Count flushComplete events in the events that are about to the dropped. These will be sent
892    // separately before the next batch of events.
893    for (int j = 0; j < numEventsDropped; ++j) {
894        if (scratch[j].type == SENSOR_TYPE_META_DATA) {
895            FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor);
896            flushInfo.mPendingFlushEventsToSend++;
897            ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
898                     flushInfo.mPendingFlushEventsToSend);
899        }
900    }
901    return;
902}
903
904sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
905{
906    return mChannel;
907}
908
909status_t SensorService::SensorEventConnection::enableDisable(
910        int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
911        int reservedFlags)
912{
913    status_t err;
914    if (enabled) {
915        err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs,
916                               reservedFlags);
917    } else {
918        err = mService->disable(this, handle);
919    }
920    return err;
921}
922
923status_t SensorService::SensorEventConnection::setEventRate(
924        int handle, nsecs_t samplingPeriodNs)
925{
926    return mService->setEventRate(this, handle, samplingPeriodNs);
927}
928
929status_t  SensorService::SensorEventConnection::flush() {
930    SensorDevice& dev(SensorDevice::getInstance());
931    const int halVersion = dev.getHalDeviceVersion();
932    Mutex::Autolock _l(mConnectionLock);
933    status_t err(NO_ERROR);
934    // Loop through all sensors for this connection and call flush on each of them.
935    for (size_t i = 0; i < mSensorInfo.size(); ++i) {
936        const int handle = mSensorInfo.keyAt(i);
937        if (halVersion < SENSORS_DEVICE_API_VERSION_1_1 || mService->isVirtualSensor(handle)) {
938            // For older devices just increment pending flush count which will send a trivial
939            // flush complete event.
940            FlushInfo& flushInfo = mSensorInfo.editValueFor(handle);
941            flushInfo.mPendingFlushEventsToSend++;
942        } else {
943            status_t err_flush = mService->flushSensor(this, handle);
944            if (err_flush != NO_ERROR) {
945                ALOGE("Flush error handle=%d %s", handle, strerror(-err_flush));
946            }
947            err = (err_flush != NO_ERROR) ? err_flush : err;
948        }
949    }
950    return err;
951}
952
953// ---------------------------------------------------------------------------
954}; // namespace android
955
956