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