SensorService.h revision af8ed3f06cf5a0fd37357b438da803f53f33fa56
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#include <utils/String8.h> 31 32#include <binder/BinderService.h> 33 34#include <gui/Sensor.h> 35#include <gui/BitTube.h> 36#include <gui/ISensorServer.h> 37#include <gui/ISensorEventConnection.h> 38 39#include "SensorInterface.h" 40 41#if __clang__ 42// Clang warns about SensorEventConnection::dump hiding BBinder::dump 43// The cause isn't fixable without changing the API, so let's tell clang 44// this is indeed intentional. 45#pragma clang diagnostic ignored "-Woverloaded-virtual" 46#endif 47 48// --------------------------------------------------------------------------- 49 50#define DEBUG_CONNECTIONS false 51// Max size is 100 KB which is enough to accept a batch of about 1000 events. 52#define MAX_SOCKET_BUFFER_SIZE_BATCHED 100 * 1024 53// For older HALs which don't support batching, use a smaller socket buffer size. 54#define SOCKET_BUFFER_SIZE_NON_BATCHED 4 * 1024 55 56#define CIRCULAR_BUF_SIZE 10 57 58struct sensors_poll_device_t; 59struct sensors_module_t; 60 61namespace android { 62// --------------------------------------------------------------------------- 63 64class SensorService : 65 public BinderService<SensorService>, 66 public BnSensorServer, 67 protected Thread 68{ 69 friend class BinderService<SensorService>; 70 71 enum Mode { 72 // The regular operating mode where any application can register/unregister/call flush on 73 // sensors. 74 NORMAL = 0, 75 // This mode is only used for testing purposes. Not all HALs support this mode. In this 76 // mode, the HAL ignores the sensor data provided by physical sensors and accepts the data 77 // that is injected from the SensorService as if it were the real sensor data. This mode 78 // is primarily used for testing various algorithms like vendor provided SensorFusion, 79 // Step Counter and Step Detector etc. Typically in this mode, there will be a client 80 // (a SensorEventConnection) which will be injecting sensor data into the HAL. Normal apps 81 // can unregister and register for any sensor that supports injection. Registering to sensors 82 // that do not support injection will give an error. 83 // TODO(aakella) : Allow exactly one client to inject sensor data at a time. 84 DATA_INJECTION = 1, 85 // This mode is used only for testing sensors. Each sensor can be tested in isolation with 86 // the required sampling_rate and maxReportLatency parameters without having to think about 87 // the data rates requested by other applications. End user devices are always expected to be 88 // in NORMAL mode. When this mode is first activated, all active sensors from all connections 89 // are disabled. Calling flush() will return an error. In this mode, only the requests from 90 // selected apps whose package names are whitelisted are allowed (typically CTS apps). Only 91 // these apps can register/unregister/call flush() on sensors. If SensorService switches to 92 // NORMAL mode again, all sensors that were previously registered to are activated with the 93 // corresponding paramaters if the application hasn't unregistered for sensors in the mean 94 // time. 95 // NOTE: Non whitelisted app whose sensors were previously deactivated may still receive 96 // events if a whitelisted app requests data from the same sensor. 97 RESTRICTED = 2 98 99 // State Transitions supported. 100 // RESTRICTED <--- NORMAL ---> DATA_INJECTION 101 // ---> <--- 102 }; 103 104 static const char* WAKE_LOCK_NAME; 105 106 static char const* getServiceName() ANDROID_API { return "sensorservice"; } 107 SensorService() ANDROID_API; 108 virtual ~SensorService(); 109 110 virtual void onFirstRef(); 111 112 // Thread interface 113 virtual bool threadLoop(); 114 115 // ISensorServer interface 116 virtual Vector<Sensor> getSensorList(const String16& opPackageName); 117 virtual sp<ISensorEventConnection> createSensorEventConnection(const String8& packageName, 118 int requestedMode, const String16& opPackageName); 119 virtual status_t enableDataInjection(int enable); 120 virtual status_t dump(int fd, const Vector<String16>& args); 121 122 class SensorEventConnection : public BnSensorEventConnection, public LooperCallback { 123 friend class SensorService; 124 virtual ~SensorEventConnection(); 125 virtual void onFirstRef(); 126 virtual sp<BitTube> getSensorChannel() const; 127 virtual status_t enableDisable(int handle, bool enabled, nsecs_t samplingPeriodNs, 128 nsecs_t maxBatchReportLatencyNs, int reservedFlags); 129 virtual status_t setEventRate(int handle, nsecs_t samplingPeriodNs); 130 virtual status_t flush(); 131 // Count the number of flush complete events which are about to be dropped in the buffer. 132 // Increment mPendingFlushEventsToSend in mSensorInfo. These flush complete events will be 133 // sent separately before the next batch of events. 134 void countFlushCompleteEventsLocked(sensors_event_t const* scratch, int numEventsDropped); 135 136 // Check if there are any wake up events in the buffer. If yes, return the index of the 137 // first wake_up sensor event in the buffer else return -1. This wake_up sensor event will 138 // have the flag WAKE_UP_SENSOR_EVENT_NEEDS_ACK set. Exactly one event per packet will have 139 // the wake_up flag set. SOCK_SEQPACKET ensures that either the entire packet is read or 140 // dropped. 141 int findWakeUpSensorEventLocked(sensors_event_t const* scratch, int count); 142 143 // Send pending flush_complete events. There may have been flush_complete_events that are 144 // dropped which need to be sent separately before other events. On older HALs (1_0) this 145 // method emulates the behavior of flush(). 146 void sendPendingFlushEventsLocked(); 147 148 // Writes events from mEventCache to the socket. 149 void writeToSocketFromCache(); 150 151 // Compute the approximate cache size from the FIFO sizes of various sensors registered for 152 // this connection. Wake up and non-wake up sensors have separate FIFOs but FIFO may be 153 // shared amongst wake-up sensors and non-wake up sensors. 154 int computeMaxCacheSizeLocked() const; 155 156 // When more sensors register, the maximum cache size desired may change. Compute max cache 157 // size, reallocate memory and copy over events from the older cache. 158 void reAllocateCacheLocked(sensors_event_t const* scratch, int count); 159 160 // LooperCallback method. If there is data to read on this fd, it is an ack from the 161 // app that it has read events from a wake up sensor, decrement mWakeLockRefCount. 162 // If this fd is available for writing send the data from the cache. 163 virtual int handleEvent(int fd, int events, void* data); 164 165 // Increment mPendingFlushEventsToSend for the given sensor handle. 166 void incrementPendingFlushCount(int32_t handle); 167 168 // Add or remove the file descriptor associated with the BitTube to the looper. If mDead is 169 // set to true or there are no more sensors for this connection, the file descriptor is 170 // removed if it has been previously added to the Looper. Depending on the state of the 171 // connection FD may be added to the Looper. The flags to set are determined by the internal 172 // state of the connection. FDs are added to the looper when wake-up sensors are registered 173 // (to poll for acknowledgements) and when write fails on the socket when there are too many 174 // error and the other end hangs up or when this client unregisters for this connection. 175 void updateLooperRegistration(const sp<Looper>& looper); 176 void updateLooperRegistrationLocked(const sp<Looper>& looper); 177 178 sp<SensorService> const mService; 179 sp<BitTube> mChannel; 180 uid_t mUid; 181 mutable Mutex mConnectionLock; 182 // Number of events from wake up sensors which are still pending and haven't been delivered 183 // to the corresponding application. It is incremented by one unit for each write to the 184 // socket. 185 uint32_t mWakeLockRefCount; 186 187 // If this flag is set to true, it means that the file descriptor associated with the 188 // BitTube has been added to the Looper in SensorService. This flag is typically set when 189 // this connection has wake-up sensors associated with it or when write has failed on this 190 // connection and we're storing some events in the cache. 191 bool mHasLooperCallbacks; 192 // If there are any errors associated with the Looper this flag is set to true and 193 // mWakeLockRefCount is reset to zero. needsWakeLock method will always return false, if 194 // this flag is set. 195 bool mDead; 196 197 bool mDataInjectionMode; 198 struct FlushInfo { 199 // The number of flush complete events dropped for this sensor is stored here. 200 // They are sent separately before the next batch of events. 201 int mPendingFlushEventsToSend; 202 // Every activate is preceded by a flush. Only after the first flush complete is 203 // received, the events for the sensor are sent on that *connection*. 204 bool mFirstFlushPending; 205 FlushInfo() : mPendingFlushEventsToSend(0), mFirstFlushPending(false) {} 206 }; 207 // protected by SensorService::mLock. Key for this vector is the sensor handle. 208 KeyedVector<int, FlushInfo> mSensorInfo; 209 sensors_event_t *mEventCache; 210 int mCacheSize, mMaxCacheSize; 211 String8 mPackageName; 212 const String16 mOpPackageName; 213#if DEBUG_CONNECTIONS 214 int mEventsReceived, mEventsSent, mEventsSentFromCache; 215 int mTotalAcksNeeded, mTotalAcksReceived; 216#endif 217 218 public: 219 SensorEventConnection(const sp<SensorService>& service, uid_t uid, String8 packageName, 220 bool isDataInjectionMode, const String16& opPackageName); 221 222 status_t sendEvents(sensors_event_t const* buffer, size_t count, 223 sensors_event_t* scratch, 224 SensorEventConnection const * const * mapFlushEventsToConnections = NULL); 225 bool hasSensor(int32_t handle) const; 226 bool hasAnySensor() const; 227 bool hasOneShotSensors() const; 228 bool addSensor(int32_t handle); 229 bool removeSensor(int32_t handle); 230 void setFirstFlushPending(int32_t handle, bool value); 231 void dump(String8& result); 232 bool needsWakeLock(); 233 void resetWakeLockRefCount(); 234 String8 getPackageName() const; 235 236 uid_t getUid() const { return mUid; } 237 }; 238 239 class SensorRecord { 240 SortedVector< wp<SensorEventConnection> > mConnections; 241 // A queue of all flush() calls made on this sensor. Flush complete events will be 242 // sent in this order. 243 Vector< wp<SensorEventConnection> > mPendingFlushConnections; 244 public: 245 SensorRecord(const sp<SensorEventConnection>& connection); 246 bool addConnection(const sp<SensorEventConnection>& connection); 247 bool removeConnection(const wp<SensorEventConnection>& connection); 248 size_t getNumConnections() const { return mConnections.size(); } 249 250 void addPendingFlushConnection(const sp<SensorEventConnection>& connection); 251 void removeFirstPendingFlushConnection(); 252 SensorEventConnection * getFirstPendingFlushConnection(); 253 void clearAllPendingFlushConnections(); 254 }; 255 256 class SensorEventAckReceiver : public Thread { 257 sp<SensorService> const mService; 258 public: 259 virtual bool threadLoop(); 260 SensorEventAckReceiver(const sp<SensorService>& service): mService(service) {} 261 }; 262 263 // sensor_event_t with only the data and the timestamp. 264 struct TrimmedSensorEvent { 265 union { 266 float *mData; 267 uint64_t mStepCounter; 268 }; 269 // Timestamp from the sensor_event. 270 int64_t mTimestamp; 271 // HH:MM:SS local time at which this sensor event is read at SensorService. Useful 272 // for debugging. 273 int32_t mHour, mMin, mSec; 274 275 TrimmedSensorEvent(int numData, int sensorType) { 276 mTimestamp = -1; 277 if (sensorType == SENSOR_TYPE_STEP_COUNTER) { 278 mStepCounter = 0; 279 } else { 280 mData = new float[numData]; 281 for (int i = 0; i < numData; ++i) { 282 mData[i] = -1.0; 283 } 284 } 285 mHour = mMin = mSec = 0; 286 } 287 288 ~TrimmedSensorEvent() { 289 delete [] mData; 290 } 291 }; 292 293 // A circular buffer of TrimmedSensorEvents. The size of this buffer is typically 10. The 294 // last N events generated from the sensor are stored in this buffer. The buffer is NOT 295 // cleared when the sensor unregisters and as a result one may see very old data in the 296 // dumpsys output but this is WAI. 297 class CircularBuffer { 298 int mNextInd; 299 int mSensorType; 300 TrimmedSensorEvent ** mTrimmedSensorEventArr; 301 public: 302 CircularBuffer(int sensor_event_type); 303 void addEvent(const sensors_event_t& sensor_event); 304 void printBuffer(String8& buffer) const; 305 bool populateLastEvent(sensors_event_t *event); 306 ~CircularBuffer(); 307 }; 308 309 static int getNumEventsForSensorType(int sensor_event_type); 310 String8 getSensorName(int handle) const; 311 bool isVirtualSensor(int handle) const; 312 Sensor getSensorFromHandle(int handle) const; 313 bool isWakeUpSensor(int type) const; 314 void recordLastValueLocked(sensors_event_t const* buffer, size_t count); 315 static void sortEventBuffer(sensors_event_t* buffer, size_t count); 316 Sensor registerSensor(SensorInterface* sensor); 317 Sensor registerVirtualSensor(SensorInterface* sensor); 318 status_t cleanupWithoutDisable( 319 const sp<SensorEventConnection>& connection, int handle); 320 status_t cleanupWithoutDisableLocked( 321 const sp<SensorEventConnection>& connection, int handle); 322 void cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection, 323 sensors_event_t const* buffer, const int count); 324 static bool canAccessSensor(const Sensor& sensor, const char* operation, 325 const String16& opPackageName); 326 static bool hasDataInjectionPermissions(); 327 // SensorService acquires a partial wakelock for delivering events from wake up sensors. This 328 // method checks whether all the events from these wake up sensors have been delivered to the 329 // corresponding applications, if yes the wakelock is released. 330 void checkWakeLockState(); 331 void checkWakeLockStateLocked(); 332 bool isWakeLockAcquired(); 333 bool isWakeUpSensorEvent(const sensors_event_t& event) const; 334 335 SensorRecord * getSensorRecord(int handle); 336 337 sp<Looper> getLooper() const; 338 339 // Reset mWakeLockRefCounts for all SensorEventConnections to zero. This may happen if 340 // SensorService did not receive any acknowledgements from apps which have registered for 341 // wake_up sensors. 342 void resetAllWakeLockRefCounts(); 343 344 // Acquire or release wake_lock. If wake_lock is acquired, set the timeout in the looper to 345 // 5 seconds and wake the looper. 346 void setWakeLockAcquiredLocked(bool acquire); 347 348 // Send events from the event cache for this particular connection. 349 void sendEventsFromCache(const sp<SensorEventConnection>& connection); 350 351 // Promote all weak referecences in mActiveConnections vector to strong references and add them 352 // to the output vector. 353 void populateActiveConnections(SortedVector< sp<SensorEventConnection> >* activeConnections); 354 355 // If SensorService is operating in RESTRICTED mode, only select whitelisted packages are 356 // allowed to register for or call flush on sensors. Typically only cts test packages are 357 // allowed. 358 bool isWhiteListedPackage(const String8& packageName); 359 360 // Reset the state of SensorService to NORMAL mode. 361 status_t resetToNormalMode(); 362 status_t resetToNormalModeLocked(); 363 364 // constants 365 Vector<Sensor> mSensorList; 366 Vector<Sensor> mUserSensorListDebug; 367 Vector<Sensor> mUserSensorList; 368 DefaultKeyedVector<int, SensorInterface*> mSensorMap; 369 Vector<SensorInterface *> mVirtualSensorList; 370 status_t mInitCheck; 371 // Socket buffersize used to initialize BitTube. This size depends on whether batching is 372 // supported or not. 373 uint32_t mSocketBufferSize; 374 sp<Looper> mLooper; 375 sp<SensorEventAckReceiver> mAckReceiver; 376 377 // protected by mLock 378 mutable Mutex mLock; 379 DefaultKeyedVector<int, SensorRecord*> mActiveSensors; 380 DefaultKeyedVector<int, SensorInterface*> mActiveVirtualSensors; 381 SortedVector< wp<SensorEventConnection> > mActiveConnections; 382 bool mWakeLockAcquired; 383 sensors_event_t *mSensorEventBuffer, *mSensorEventScratch; 384 SensorEventConnection const **mMapFlushEventsToConnections; 385 Mode mCurrentOperatingMode; 386 387 // The size of this vector is constant, only the items are mutable 388 KeyedVector<int32_t, CircularBuffer *> mLastEventSeen; 389 390public: 391 void cleanupConnection(SensorEventConnection* connection); 392 status_t enable(const sp<SensorEventConnection>& connection, int handle, 393 nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags, 394 const String16& opPackageName); 395 status_t disable(const sp<SensorEventConnection>& connection, int handle); 396 status_t setEventRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns, 397 const String16& opPackageName); 398 status_t flushSensor(const sp<SensorEventConnection>& connection, 399 const String16& opPackageName); 400}; 401 402// --------------------------------------------------------------------------- 403}; // namespace android 404 405#endif // ANDROID_SENSOR_SERVICE_H 406