SensorService.h 20 KB

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