SensorService.h revision 8a96955c8e14db40b16164236830fc9506a00872
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#ifndef ANDROID_SENSOR_SERVICE_H
18#define ANDROID_SENSOR_SERVICE_H
19
20#include <stdint.h>
21#include <sys/types.h>
22
23#include <utils/Vector.h>
24#include <utils/SortedVector.h>
25#include <utils/KeyedVector.h>
26#include <utils/threads.h>
27#include <utils/AndroidThreads.h>
28#include <utils/RefBase.h>
29#include <utils/Looper.h>
30
31#include <binder/BinderService.h>
32
33#include <gui/Sensor.h>
34#include <gui/BitTube.h>
35#include <gui/ISensorServer.h>
36#include <gui/ISensorEventConnection.h>
37
38#include "SensorInterface.h"
39
40// ---------------------------------------------------------------------------
41
42#define DEBUG_CONNECTIONS   false
43// Max size is 100 KB which is enough to accept a batch of about 1000 events.
44#define MAX_SOCKET_BUFFER_SIZE_BATCHED 100 * 1024
45// For older HALs which don't support batching, use a smaller socket buffer size.
46#define SOCKET_BUFFER_SIZE_NON_BATCHED 4 * 1024
47
48struct sensors_poll_device_t;
49struct sensors_module_t;
50
51namespace android {
52// ---------------------------------------------------------------------------
53
54class SensorService :
55        public BinderService<SensorService>,
56        public BnSensorServer,
57        protected Thread
58{
59    friend class BinderService<SensorService>;
60
61    static const char* WAKE_LOCK_NAME;
62
63    static char const* getServiceName() ANDROID_API { return "sensorservice"; }
64    SensorService() ANDROID_API;
65    virtual ~SensorService();
66
67    virtual void onFirstRef();
68
69    // Thread interface
70    virtual bool threadLoop();
71
72    // ISensorServer interface
73    virtual Vector<Sensor> getSensorList();
74    virtual sp<ISensorEventConnection> createSensorEventConnection();
75    virtual status_t dump(int fd, const Vector<String16>& args);
76
77    class SensorEventConnection : public BnSensorEventConnection, public LooperCallback {
78        friend class SensorService;
79        virtual ~SensorEventConnection();
80        virtual void onFirstRef();
81        virtual sp<BitTube> getSensorChannel() const;
82        virtual status_t enableDisable(int handle, bool enabled, nsecs_t samplingPeriodNs,
83                                       nsecs_t maxBatchReportLatencyNs, int reservedFlags);
84        virtual status_t setEventRate(int handle, nsecs_t samplingPeriodNs);
85        virtual status_t flush();
86        // Count the number of flush complete events which are about to be dropped in the buffer.
87        // Increment mPendingFlushEventsToSend in mSensorInfo. These flush complete events will be
88        // sent separately before the next batch of events.
89        void countFlushCompleteEventsLocked(sensors_event_t const* scratch, int numEventsDropped);
90
91        // Check if there are any wake up events in the buffer. If yes, return the index of the
92        // first wake_up sensor event in the buffer else return -1. This wake_up sensor event will
93        // have the flag WAKE_UP_SENSOR_EVENT_NEEDS_ACK set. Exactly one event per packet will have
94        // the wake_up flag set. SOCK_SEQPACKET ensures that either the entire packet is read or
95        // dropped.
96        int findWakeUpSensorEventLocked(sensors_event_t const* scratch, int count);
97
98        // Send pending flush_complete events. There may have been flush_complete_events that are
99        // dropped which need to be sent separately before other events. On older HALs (1_0) this
100        // method emulates the behavior of flush().
101        void sendPendingFlushEventsLocked();
102
103        // Writes events from mEventCache to the socket.
104        void writeToSocketFromCacheLocked();
105
106        // Compute the approximate cache size from the FIFO sizes of various sensors registered for
107        // this connection. Wake up and non-wake up sensors have separate FIFOs but FIFO may be
108        // shared amongst wake-up sensors and non-wake up sensors.
109        int computeMaxCacheSizeLocked() const;
110
111        // When more sensors register, the maximum cache size desired may change. Compute max cache
112        // size, reallocate memory and copy over events from the older cache.
113        void reAllocateCacheLocked(sensors_event_t const* scratch, int count);
114
115        // LooperCallback method. If there is data to read on this fd, it is an ack from the
116        // app that it has read events from a wake up sensor, decrement mWakeLockRefCount.
117        // If this fd is available for writing send the data from the cache.
118        virtual int handleEvent(int fd, int events, void* data);
119
120        // Increment mPendingFlushEventsToSend for the given sensor handle.
121        void incrementPendingFlushCount(int32_t handle);
122
123        // Add or remove the file descriptor associated with the BitTube to the looper. If mDead is
124        // set to true or there are no more sensors for this connection, the file descriptor is
125        // removed if it has been previously added to the Looper. Depending on the state of the
126        // connection FD may be added to the Looper. The flags to set are determined by the internal
127        // state of the connection. FDs are added to the looper when wake-up sensors are registered
128        // (to poll for acknowledgements) and when write fails on the socket when there are too many
129        // events (to poll when the FD is available for writing). FDs are removed when there is an
130        // error and the other end hangs up or when this client unregisters for this connection.
131        void updateLooperRegistration(const sp<Looper>& looper);
132        void updateLooperRegistrationLocked(const sp<Looper>& looper);
133
134        sp<SensorService> const mService;
135        sp<BitTube> mChannel;
136        uid_t mUid;
137        mutable Mutex mConnectionLock;
138        // Number of events from wake up sensors which are still pending and haven't been delivered
139        // to the corresponding application. It is incremented by one unit for each write to the
140        // socket.
141        uint32_t mWakeLockRefCount;
142
143        // If this flag is set to true, it means that the file descriptor associated with the
144        // BitTube has been added to the Looper in SensorService. This flag is typically set when
145        // this connection has wake-up sensors associated with it or when write has failed on this
146        // connection and we're storing some events in the cache.
147        bool mHasLooperCallbacks;
148        // If there are any errors associated with the Looper this flag is set to true and
149        // mWakeLockRefCount is reset to zero. needsWakeLock method will always return false, if
150        // this flag is set.
151        bool mDead;
152        struct FlushInfo {
153            // The number of flush complete events dropped for this sensor is stored here.
154            // They are sent separately before the next batch of events.
155            int mPendingFlushEventsToSend;
156            // Every activate is preceded by a flush. Only after the first flush complete is
157            // received, the events for the sensor are sent on that *connection*.
158            bool mFirstFlushPending;
159            FlushInfo() : mPendingFlushEventsToSend(0), mFirstFlushPending(false) {}
160        };
161        // protected by SensorService::mLock. Key for this vector is the sensor handle.
162        KeyedVector<int, FlushInfo> mSensorInfo;
163        sensors_event_t *mEventCache;
164        int mCacheSize, mMaxCacheSize;
165
166#if DEBUG_CONNECTIONS
167        int mEventsReceived, mEventsSent, mEventsSentFromCache;
168        int mTotalAcksNeeded, mTotalAcksReceived;
169#endif
170
171    public:
172        SensorEventConnection(const sp<SensorService>& service, uid_t uid);
173
174        status_t sendEvents(sensors_event_t const* buffer, size_t count,
175                sensors_event_t* scratch,
176                SensorEventConnection const * const * mapFlushEventsToConnections = NULL);
177        bool hasSensor(int32_t handle) const;
178        bool hasAnySensor() const;
179        bool hasOneShotSensors() const;
180        bool addSensor(int32_t handle);
181        bool removeSensor(int32_t handle);
182        void setFirstFlushPending(int32_t handle, bool value);
183        void dump(String8& result);
184        bool needsWakeLock();
185
186        uid_t getUid() const { return mUid; }
187    };
188
189    class SensorRecord {
190        SortedVector< wp<SensorEventConnection> > mConnections;
191        // A queue of all flush() calls made on this sensor. Flush complete events will be
192        // sent in this order.
193        Vector< wp<SensorEventConnection> > mPendingFlushConnections;
194    public:
195        SensorRecord(const sp<SensorEventConnection>& connection);
196        bool addConnection(const sp<SensorEventConnection>& connection);
197        bool removeConnection(const wp<SensorEventConnection>& connection);
198        size_t getNumConnections() const { return mConnections.size(); }
199
200        void addPendingFlushConnection(const sp<SensorEventConnection>& connection);
201        void removeFirstPendingFlushConnection();
202        SensorEventConnection * getFirstPendingFlushConnection();
203    };
204
205    class SensorEventAckReceiver : public Thread {
206        sp<SensorService> const mService;
207    public:
208        virtual bool threadLoop();
209        SensorEventAckReceiver(const sp<SensorService>& service): mService(service) {}
210    };
211
212    String8 getSensorName(int handle) const;
213    bool isVirtualSensor(int handle) const;
214    Sensor getSensorFromHandle(int handle) const;
215    bool isWakeUpSensor(int type) const;
216    void recordLastValueLocked(sensors_event_t const* buffer, size_t count);
217    static void sortEventBuffer(sensors_event_t* buffer, size_t count);
218    Sensor registerSensor(SensorInterface* sensor);
219    Sensor registerVirtualSensor(SensorInterface* sensor);
220    status_t cleanupWithoutDisable(
221            const sp<SensorEventConnection>& connection, int handle);
222    status_t cleanupWithoutDisableLocked(
223            const sp<SensorEventConnection>& connection, int handle);
224    void cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
225            sensors_event_t const* buffer, const int count);
226    static bool canAccessSensor(const Sensor& sensor);
227    static bool verifyCanAccessSensor(const Sensor& sensor, const char* operation);
228    // SensorService acquires a partial wakelock for delivering events from wake up sensors. This
229    // method checks whether all the events from these wake up sensors have been delivered to the
230    // corresponding applications, if yes the wakelock is released.
231    void checkWakeLockState();
232    void checkWakeLockStateLocked();
233    bool isWakeUpSensorEvent(const sensors_event_t& event) const;
234
235    SensorRecord * getSensorRecord(int handle);
236
237    sp<Looper> getLooper() const;
238
239    // constants
240    Vector<Sensor> mSensorList;
241    Vector<Sensor> mUserSensorListDebug;
242    Vector<Sensor> mUserSensorList;
243    DefaultKeyedVector<int, SensorInterface*> mSensorMap;
244    Vector<SensorInterface *> mVirtualSensorList;
245    status_t mInitCheck;
246    // Socket buffersize used to initialize BitTube. This size depends on whether batching is
247    // supported or not.
248    uint32_t mSocketBufferSize;
249    sp<Looper> mLooper;
250
251    // protected by mLock
252    mutable Mutex mLock;
253    DefaultKeyedVector<int, SensorRecord*> mActiveSensors;
254    DefaultKeyedVector<int, SensorInterface*> mActiveVirtualSensors;
255    SortedVector< wp<SensorEventConnection> > mActiveConnections;
256    bool mWakeLockAcquired;
257    sensors_event_t *mSensorEventBuffer, *mSensorEventScratch;
258    SensorEventConnection const **mMapFlushEventsToConnections;
259
260    // The size of this vector is constant, only the items are mutable
261    KeyedVector<int32_t, sensors_event_t> mLastEventSeen;
262
263public:
264    void cleanupConnection(SensorEventConnection* connection);
265    status_t enable(const sp<SensorEventConnection>& connection, int handle,
266                    nsecs_t samplingPeriodNs,  nsecs_t maxBatchReportLatencyNs, int reservedFlags);
267    status_t disable(const sp<SensorEventConnection>& connection, int handle);
268    status_t setEventRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns);
269    status_t flushSensor(const sp<SensorEventConnection>& connection);
270};
271
272// ---------------------------------------------------------------------------
273}; // namespace android
274
275#endif // ANDROID_SENSOR_SERVICE_H
276