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