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