SensorService.cpp revision e04a63b3053270d64890f156869e7cf75c436fbb
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 <utils/SortedVector.h>
22#include <utils/KeyedVector.h>
23#include <utils/threads.h>
24#include <utils/Atomic.h>
25#include <utils/Errors.h>
26#include <utils/RefBase.h>
27#include <utils/Singleton.h>
28#include <utils/String16.h>
29
30#include <binder/BinderService.h>
31#include <binder/IServiceManager.h>
32
33#include <gui/ISensorServer.h>
34#include <gui/ISensorEventConnection.h>
35
36#include <hardware/sensors.h>
37
38#include "SensorService.h"
39#include "GravitySensor.h"
40#include "LinearAccelerationSensor.h"
41#include "RotationVectorSensor.h"
42
43namespace android {
44// ---------------------------------------------------------------------------
45
46SensorService::SensorService()
47    : mDump("android.permission.DUMP"),
48      mInitCheck(NO_INIT)
49{
50}
51
52void SensorService::onFirstRef()
53{
54    LOGD("nuSensorService starting...");
55
56    SensorDevice& dev(SensorDevice::getInstance());
57
58    if (dev.initCheck() == NO_ERROR) {
59        uint32_t virtualSensorsNeeds =
60                (1<<SENSOR_TYPE_GRAVITY) |
61                (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
62                (1<<SENSOR_TYPE_ROTATION_VECTOR);
63        sensor_t const* list;
64        int count = dev.getSensorList(&list);
65        mLastEventSeen.setCapacity(count);
66        for (int i=0 ; i<count ; i++) {
67            registerSensor( new HardwareSensor(list[i]) );
68            switch (list[i].type) {
69                case SENSOR_TYPE_GRAVITY:
70                case SENSOR_TYPE_LINEAR_ACCELERATION:
71                case SENSOR_TYPE_ROTATION_VECTOR:
72                    virtualSensorsNeeds &= ~(1<<list[i].type);
73                    break;
74            }
75        }
76
77        if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
78            registerVirtualSensor( new GravitySensor(list, count) );
79        }
80        if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
81            registerVirtualSensor( new LinearAccelerationSensor(list, count) );
82        }
83        if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
84            registerVirtualSensor( new RotationVectorSensor(list, count) );
85        }
86
87        run("SensorService", PRIORITY_URGENT_DISPLAY);
88        mInitCheck = NO_ERROR;
89    }
90}
91
92void SensorService::registerSensor(SensorInterface* s)
93{
94    sensors_event_t event;
95    memset(&event, 0, sizeof(event));
96
97    const Sensor sensor(s->getSensor());
98    // add to the sensor list (returned to clients)
99    mSensorList.add(sensor);
100    // add to our handle->SensorInterface mapping
101    mSensorMap.add(sensor.getHandle(), s);
102    // create an entry in the mLastEventSeen array
103    mLastEventSeen.add(sensor.getHandle(), event);
104}
105
106void SensorService::registerVirtualSensor(SensorInterface* s)
107{
108    registerSensor(s);
109    mVirtualSensorList.add( s );
110}
111
112SensorService::~SensorService()
113{
114    for (size_t i=0 ; i<mSensorMap.size() ; i++)
115        delete mSensorMap.valueAt(i);
116}
117
118status_t SensorService::dump(int fd, const Vector<String16>& args)
119{
120    const size_t SIZE = 1024;
121    char buffer[SIZE];
122    String8 result;
123    if (!mDump.checkCalling()) {
124        snprintf(buffer, SIZE, "Permission Denial: "
125                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
126                IPCThreadState::self()->getCallingPid(),
127                IPCThreadState::self()->getCallingUid());
128        result.append(buffer);
129    } else {
130        Mutex::Autolock _l(mLock);
131        snprintf(buffer, SIZE, "Sensor List:\n");
132        result.append(buffer);
133        for (size_t i=0 ; i<mSensorList.size() ; i++) {
134            const Sensor& s(mSensorList[i]);
135            const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle()));
136            snprintf(buffer, SIZE, "%-48s| %-32s | 0x%08x | maxRate=%7.2fHz | last=<%5.1f,%5.1f,%5.1f>\n",
137                    s.getName().string(),
138                    s.getVendor().string(),
139                    s.getHandle(),
140                    s.getMinDelay() ? (1000000.0f / s.getMinDelay()) : 0.0f,
141                    e.data[0], e.data[1], e.data[2]);
142            result.append(buffer);
143        }
144        SensorDevice::getInstance().dump(result, buffer, SIZE);
145
146        snprintf(buffer, SIZE, "%d active connections\n",
147                mActiveConnections.size());
148        result.append(buffer);
149        snprintf(buffer, SIZE, "Active sensors:\n");
150        result.append(buffer);
151        for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
152            int handle = mActiveSensors.keyAt(i);
153            snprintf(buffer, SIZE, "%s (handle=0x%08x, connections=%d)\n",
154                    getSensorName(handle).string(),
155                    handle,
156                    mActiveSensors.valueAt(i)->getNumConnections());
157            result.append(buffer);
158        }
159    }
160    write(fd, result.string(), result.size());
161    return NO_ERROR;
162}
163
164bool SensorService::threadLoop()
165{
166    LOGD("nuSensorService thread starting...");
167
168    const size_t numEventMax = 16 * (1 + mVirtualSensorList.size());
169    sensors_event_t buffer[numEventMax];
170    sensors_event_t scratch[numEventMax];
171    SensorDevice& device(SensorDevice::getInstance());
172    const size_t vcount = mVirtualSensorList.size();
173
174    ssize_t count;
175    do {
176        count = device.poll(buffer, numEventMax);
177        if (count<0) {
178            LOGE("sensor poll failed (%s)", strerror(-count));
179            break;
180        }
181
182        recordLastValue(buffer, count);
183
184        // handle virtual sensors
185        if (count && vcount) {
186            const DefaultKeyedVector<int, SensorInterface*> virtualSensors(
187                    getActiveVirtualSensors());
188            const size_t activeVirtualSensorCount = virtualSensors.size();
189            if (activeVirtualSensorCount) {
190                size_t k = 0;
191                for (size_t i=0 ; i<size_t(count) ; i++) {
192                    sensors_event_t const * const event = buffer;
193                    for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
194                        sensors_event_t out;
195                        if (virtualSensors.valueAt(j)->process(&out, event[i])) {
196                            buffer[count + k] = out;
197                            k++;
198                        }
199                    }
200                }
201                if (k) {
202                    // record the last synthesized values
203                    recordLastValue(&buffer[count], k);
204                    count += k;
205                    // sort the buffer by time-stamps
206                    sortEventBuffer(buffer, count);
207                }
208            }
209        }
210
211        // send our events to clients...
212        const SortedVector< wp<SensorEventConnection> > activeConnections(
213                getActiveConnections());
214        size_t numConnections = activeConnections.size();
215        for (size_t i=0 ; i<numConnections ; i++) {
216            sp<SensorEventConnection> connection(
217                    activeConnections[i].promote());
218            if (connection != 0) {
219                connection->sendEvents(buffer, count, scratch);
220            }
221        }
222    } while (count >= 0 || Thread::exitPending());
223
224    LOGW("Exiting SensorService::threadLoop!");
225    return false;
226}
227
228void SensorService::recordLastValue(
229        sensors_event_t const * buffer, size_t count)
230{
231    Mutex::Autolock _l(mLock);
232
233    // record the last event for each sensor
234    int32_t prev = buffer[0].sensor;
235    for (size_t i=1 ; i<count ; i++) {
236        // record the last event of each sensor type in this buffer
237        int32_t curr = buffer[i].sensor;
238        if (curr != prev) {
239            mLastEventSeen.editValueFor(prev) = buffer[i-1];
240            prev = curr;
241        }
242    }
243    mLastEventSeen.editValueFor(prev) = buffer[count-1];
244}
245
246void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
247{
248    struct compar {
249        static int cmp(void const* lhs, void const* rhs) {
250            sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
251            sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
252            return r->timestamp - l->timestamp;
253        }
254    };
255    qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
256}
257
258SortedVector< wp<SensorService::SensorEventConnection> >
259SensorService::getActiveConnections() const
260{
261    Mutex::Autolock _l(mLock);
262    return mActiveConnections;
263}
264
265DefaultKeyedVector<int, SensorInterface*>
266SensorService::getActiveVirtualSensors() const
267{
268    Mutex::Autolock _l(mLock);
269    return mActiveVirtualSensors;
270}
271
272String8 SensorService::getSensorName(int handle) const {
273    size_t count = mSensorList.size();
274    for (size_t i=0 ; i<count ; i++) {
275        const Sensor& sensor(mSensorList[i]);
276        if (sensor.getHandle() == handle) {
277            return sensor.getName();
278        }
279    }
280    String8 result("unknown");
281    return result;
282}
283
284Vector<Sensor> SensorService::getSensorList()
285{
286    return mSensorList;
287}
288
289sp<ISensorEventConnection> SensorService::createSensorEventConnection()
290{
291    sp<SensorEventConnection> result(new SensorEventConnection(this));
292    return result;
293}
294
295void SensorService::cleanupConnection(SensorEventConnection* c)
296{
297    Mutex::Autolock _l(mLock);
298    const wp<SensorEventConnection> connection(c);
299    size_t size = mActiveSensors.size();
300    for (size_t i=0 ; i<size ; ) {
301        int handle = mActiveSensors.keyAt(i);
302        if (c->hasSensor(handle)) {
303            SensorInterface* sensor = mSensorMap.valueFor( handle );
304            if (sensor) {
305                sensor->activate(c, false);
306            }
307        }
308        SensorRecord* rec = mActiveSensors.valueAt(i);
309        if (rec && rec->removeConnection(connection)) {
310            mActiveSensors.removeItemsAt(i, 1);
311            mActiveVirtualSensors.removeItem(handle);
312            delete rec;
313            size--;
314        } else {
315            i++;
316        }
317    }
318    mActiveConnections.remove(connection);
319}
320
321status_t SensorService::enable(const sp<SensorEventConnection>& connection,
322        int handle)
323{
324    if (mInitCheck != NO_ERROR)
325        return mInitCheck;
326
327    Mutex::Autolock _l(mLock);
328    SensorInterface* sensor = mSensorMap.valueFor(handle);
329    status_t err = sensor ? sensor->activate(connection.get(), true) : status_t(BAD_VALUE);
330    if (err == NO_ERROR) {
331        SensorRecord* rec = mActiveSensors.valueFor(handle);
332        if (rec == 0) {
333            rec = new SensorRecord(connection);
334            mActiveSensors.add(handle, rec);
335            if (sensor->isVirtual()) {
336                mActiveVirtualSensors.add(handle, sensor);
337            }
338        } else {
339            if (rec->addConnection(connection)) {
340                // this sensor is already activated, but we are adding a
341                // connection that uses it. Immediately send down the last
342                // known value of the requested sensor if it's not a
343                // "continuous" sensor.
344                if (sensor->getSensor().getMinDelay() == 0) {
345                    sensors_event_t scratch;
346                    sensors_event_t& event(mLastEventSeen.editValueFor(handle));
347                    if (event.version == sizeof(sensors_event_t)) {
348                        connection->sendEvents(&event, 1);
349                    }
350                }
351            }
352        }
353        if (err == NO_ERROR) {
354            // connection now active
355            if (connection->addSensor(handle)) {
356                // the sensor was added (which means it wasn't already there)
357                // so, see if this connection becomes active
358                if (mActiveConnections.indexOf(connection) < 0) {
359                    mActiveConnections.add(connection);
360                }
361            }
362        }
363    }
364    return err;
365}
366
367status_t SensorService::disable(const sp<SensorEventConnection>& connection,
368        int handle)
369{
370    if (mInitCheck != NO_ERROR)
371        return mInitCheck;
372
373    status_t err = NO_ERROR;
374    Mutex::Autolock _l(mLock);
375    SensorRecord* rec = mActiveSensors.valueFor(handle);
376    if (rec) {
377        // see if this connection becomes inactive
378        connection->removeSensor(handle);
379        if (connection->hasAnySensor() == false) {
380            mActiveConnections.remove(connection);
381        }
382        // see if this sensor becomes inactive
383        if (rec->removeConnection(connection)) {
384            mActiveSensors.removeItem(handle);
385            mActiveVirtualSensors.removeItem(handle);
386            delete rec;
387        }
388        SensorInterface* sensor = mSensorMap.valueFor(handle);
389        err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
390    }
391    return err;
392}
393
394status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
395        int handle, nsecs_t ns)
396{
397    if (mInitCheck != NO_ERROR)
398        return mInitCheck;
399
400    if (ns < 0)
401        return BAD_VALUE;
402
403    if (ns < MINIMUM_EVENTS_PERIOD)
404        ns = MINIMUM_EVENTS_PERIOD;
405
406    SensorInterface* sensor = mSensorMap.valueFor(handle);
407    if (!sensor) return BAD_VALUE;
408    return sensor->setDelay(connection.get(), handle, ns);
409}
410
411// ---------------------------------------------------------------------------
412
413SensorService::SensorRecord::SensorRecord(
414        const sp<SensorEventConnection>& connection)
415{
416    mConnections.add(connection);
417}
418
419bool SensorService::SensorRecord::addConnection(
420        const sp<SensorEventConnection>& connection)
421{
422    if (mConnections.indexOf(connection) < 0) {
423        mConnections.add(connection);
424        return true;
425    }
426    return false;
427}
428
429bool SensorService::SensorRecord::removeConnection(
430        const wp<SensorEventConnection>& connection)
431{
432    ssize_t index = mConnections.indexOf(connection);
433    if (index >= 0) {
434        mConnections.removeItemsAt(index, 1);
435    }
436    return mConnections.size() ? false : true;
437}
438
439// ---------------------------------------------------------------------------
440
441SensorService::SensorEventConnection::SensorEventConnection(
442        const sp<SensorService>& service)
443    : mService(service), mChannel(new SensorChannel())
444{
445}
446
447SensorService::SensorEventConnection::~SensorEventConnection()
448{
449    mService->cleanupConnection(this);
450}
451
452void SensorService::SensorEventConnection::onFirstRef()
453{
454}
455
456bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
457    Mutex::Autolock _l(mConnectionLock);
458    if (mSensorInfo.indexOf(handle) <= 0) {
459        mSensorInfo.add(handle);
460        return true;
461    }
462    return false;
463}
464
465bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
466    Mutex::Autolock _l(mConnectionLock);
467    if (mSensorInfo.remove(handle) >= 0) {
468        return true;
469    }
470    return false;
471}
472
473bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
474    Mutex::Autolock _l(mConnectionLock);
475    return mSensorInfo.indexOf(handle) >= 0;
476}
477
478bool SensorService::SensorEventConnection::hasAnySensor() const {
479    Mutex::Autolock _l(mConnectionLock);
480    return mSensorInfo.size() ? true : false;
481}
482
483status_t SensorService::SensorEventConnection::sendEvents(
484        sensors_event_t const* buffer, size_t numEvents,
485        sensors_event_t* scratch)
486{
487    // filter out events not for this connection
488    size_t count = 0;
489    if (scratch) {
490        Mutex::Autolock _l(mConnectionLock);
491        size_t i=0;
492        while (i<numEvents) {
493            const int32_t curr = buffer[i].sensor;
494            if (mSensorInfo.indexOf(curr) >= 0) {
495                do {
496                    scratch[count++] = buffer[i++];
497                } while ((i<numEvents) && (buffer[i].sensor == curr));
498            } else {
499                i++;
500            }
501        }
502    } else {
503        scratch = const_cast<sensors_event_t *>(buffer);
504        count = numEvents;
505    }
506
507    if (count == 0)
508        return 0;
509
510    ssize_t size = mChannel->write(scratch, count*sizeof(sensors_event_t));
511    if (size == -EAGAIN) {
512        // the destination doesn't accept events anymore, it's probably
513        // full. For now, we just drop the events on the floor.
514        LOGW("dropping %d events on the floor", count);
515        return size;
516    }
517
518    LOGE_IF(size<0, "dropping %d events on the floor (%s)",
519            count, strerror(-size));
520
521    return size < 0 ? status_t(size) : status_t(NO_ERROR);
522}
523
524sp<SensorChannel> SensorService::SensorEventConnection::getSensorChannel() const
525{
526    return mChannel;
527}
528
529status_t SensorService::SensorEventConnection::enableDisable(
530        int handle, bool enabled)
531{
532    status_t err;
533    if (enabled) {
534        err = mService->enable(this, handle);
535    } else {
536        err = mService->disable(this, handle);
537    }
538    return err;
539}
540
541status_t SensorService::SensorEventConnection::setEventRate(
542        int handle, nsecs_t ns)
543{
544    return mService->setEventRate(this, handle, ns);
545}
546
547// ---------------------------------------------------------------------------
548}; // namespace android
549
550