blob: fb1ebcfb1f920b4f6a9a5fe2cee381b42dadc163 [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
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
Mathias Agopian33015422011-05-27 18:18:13 -070017#include <cutils/properties.h>
18
Svetoslavb412f6e2015-04-29 16:50:41 -070019#include <binder/AppOpsManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070021#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070022#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070023
Mathias Agopian907103b2012-04-02 18:38:02 -070024#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070025
26#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070027#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070028
Mathias Agopian787ac1b2012-09-18 18:49:18 -070029#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070030#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080031#include "GravitySensor.h"
32#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070033#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080034#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070035#include "SensorFusion.h"
Peng Xueb4d6282015-12-10 18:02:41 -080036
Mathias Agopian984826c2011-05-17 22:54:42 -070037#include "SensorService.h"
Peng Xueb4d6282015-12-10 18:02:41 -080038#include "SensorEventConnection.h"
39#include "SensorEventAckReceiver.h"
40#include "SensorRecord.h"
41#include "SensorRegistrationInfo.h"
42#include "MostRecentEventLogger.h"
43
44#include <inttypes.h>
45#include <math.h>
46#include <stdint.h>
47#include <sys/types.h>
48#include <sys/socket.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070049
50namespace android {
51// ---------------------------------------------------------------------------
52
Mathias Agopian33015422011-05-27 18:18:13 -070053/*
54 * Notes:
55 *
56 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070057 * - run mag sensor from time to time to force calibration
58 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
59 *
60 */
61
Aravind Akella8ef3c892015-07-10 11:24:28 -070062const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070063// Permissions.
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070064static const String16 sDump("android.permission.DUMP");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070065
Mathias Agopianfc328812010-07-14 23:41:37 -070066SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070067 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070068 mWakeLockAcquired(false) {
Mathias Agopianfc328812010-07-14 23:41:37 -070069}
70
Peng Xu47e96012016-03-28 17:55:56 -070071void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +000072 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -080073 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070074
Mathias Agopianf001c922010-11-11 17:58:51 -080075 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080076 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070077 ssize_t count = dev.getSensorList(&list);
78 if (count > 0) {
Peng Xu47e96012016-03-28 17:55:56 -070079 // this is the only place besides the dynamic sensor register and unregister functions
80 // where write operation to various sensor lists has to be locked.
81 Mutex::Autolock _l(mSensorsLock);
82
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070083 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -070084 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070085 uint32_t virtualSensorsNeeds =
86 (1<<SENSOR_TYPE_GRAVITY) |
87 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -070088 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
89 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
90 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070091
92 mLastEventSeen.setCapacity(count);
93 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -070094 bool useThisSensor=true;
95
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070096 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -070097 case SENSOR_TYPE_ACCELEROMETER:
98 hasAccel = true;
99 break;
100 case SENSOR_TYPE_MAGNETIC_FIELD:
101 hasMag = true;
102 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700103 case SENSOR_TYPE_ORIENTATION:
104 orientationIndex = i;
105 break;
106 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700107 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700108 hasGyro = true;
109 break;
110 case SENSOR_TYPE_GRAVITY:
111 case SENSOR_TYPE_LINEAR_ACCELERATION:
112 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700113 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
114 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
115 if (IGNORE_HARDWARE_FUSION) {
116 useThisSensor = false;
117 } else {
118 virtualSensorsNeeds &= ~(1<<list[i].type);
119 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700120 break;
121 }
Peng Xuf66684a2015-07-23 11:41:53 -0700122 if (useThisSensor) {
123 registerSensor( new HardwareSensor(list[i]) );
124 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700125 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700126
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700127 // it's safe to instantiate the SensorFusion object here
128 // (it wants to be instantiated after h/w sensors have been
129 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700130 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700131
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700132 // build the sensor list returned to users
133 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700134
Aravind Akellaf5047892015-07-20 17:29:33 -0700135 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700136 // Add Android virtual sensors if they're not already
137 // available in the HAL
Peng Xuf66684a2015-07-23 11:41:53 -0700138 Sensor aSensor;
Mathias Agopian03193062013-05-10 19:32:39 -0700139
140 aSensor = registerVirtualSensor( new RotationVectorSensor() );
141 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
142 mUserSensorList.add(aSensor);
143 }
144
Mathias Agopian03193062013-05-10 19:32:39 -0700145 aSensor = registerVirtualSensor( new OrientationSensor() );
146 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
147 // if we are doing our own rotation-vector, also add
148 // the orientation sensor and remove the HAL provided one.
149 mUserSensorList.replaceAt(aSensor, orientationIndex);
150 }
151
Peng Xuf66684a2015-07-23 11:41:53 -0700152 aSensor = registerVirtualSensor(
153 new LinearAccelerationSensor(list, count) );
154 if (virtualSensorsNeeds &
155 (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
156 mUserSensorList.add(aSensor);
157 }
158
Mathias Agopian33264862012-06-28 19:46:54 -0700159 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700160 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700161 registerVirtualSensor( new GyroDriftSensor() );
162 }
163
Peng Xuf66684a2015-07-23 11:41:53 -0700164 if (hasAccel && hasGyro) {
165 Sensor aSensor;
166
167 aSensor = registerVirtualSensor(
168 new GravitySensor(list, count) );
169 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
170 mUserSensorList.add(aSensor);
171 }
172
173 aSensor = registerVirtualSensor(
174 new GameRotationVectorSensor() );
175 if (virtualSensorsNeeds &
176 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) {
177 mUserSensorList.add(aSensor);
178 }
179 }
180
181 if (hasAccel && hasMag) {
182 Sensor aSensor;
183
184 aSensor = registerVirtualSensor(
185 new GeoMagRotationVectorSensor() );
186 if (virtualSensorsNeeds &
187 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) {
188 mUserSensorList.add(aSensor);
189 }
190 }
191
Mathias Agopian33264862012-06-28 19:46:54 -0700192 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700193 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700194
Aravind Akella5466c3d2014-08-22 16:11:10 -0700195 // Check if the device really supports batching by looking at the FIFO event
196 // counts for each sensor.
197 bool batchingSupported = false;
Svetoslavb412f6e2015-04-29 16:50:41 -0700198 for (size_t i = 0; i < mSensorList.size(); ++i) {
Aravind Akella5466c3d2014-08-22 16:11:10 -0700199 if (mSensorList[i].getFifoMaxEventCount() > 0) {
200 batchingSupported = true;
201 break;
202 }
203 }
204
205 if (batchingSupported) {
206 // Increase socket buffer size to a max of 100 KB for batching capabilities.
207 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
208 } else {
209 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
210 }
211
212 // Compare the socketBufferSize value against the system limits and limit
213 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700214 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
215 char line[128];
216 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
217 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700218 size_t maxSystemSocketBufferSize;
219 sscanf(line, "%zu", &maxSystemSocketBufferSize);
220 if (mSocketBufferSize > maxSystemSocketBufferSize) {
221 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700222 }
223 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700224 if (fp) {
225 fclose(fp);
226 }
227
Aravind Akella9a844cf2014-02-11 18:58:52 -0800228 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700229 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700230 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
231 mSensorEventBuffer = new sensors_event_t[minBufferSize];
232 mSensorEventScratch = new sensors_event_t[minBufferSize];
233 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700234 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700235
Aravind Akella18d6d512015-06-18 14:18:28 -0700236 mNextSensorRegIndex = 0;
237 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
238 mLastNSensorRegistrations.push();
239 }
240
241 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700242 mAckReceiver = new SensorEventAckReceiver(this);
243 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700244 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700245 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700246 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700247}
248
Peng Xu47e96012016-03-28 17:55:56 -0700249Sensor SensorService::registerSensor(SensorInterface* s) {
250 //caller of this function has to make sure mSensorsLock is locked
251 assert(mSensorsLock.tryLock() != 0);
252
Mathias Agopianf001c922010-11-11 17:58:51 -0800253 const Sensor sensor(s->getSensor());
Peng Xu47e96012016-03-28 17:55:56 -0700254
255 // add handle to used handle list
256 mUsedHandleList.add(sensor.getHandle());
Mathias Agopianf001c922010-11-11 17:58:51 -0800257 // add to the sensor list (returned to clients)
258 mSensorList.add(sensor);
259 // add to our handle->SensorInterface mapping
260 mSensorMap.add(sensor.getHandle(), s);
261 // create an entry in the mLastEventSeen array
Aravind Akella444f2672015-05-07 12:40:52 -0700262 mLastEventSeen.add(sensor.getHandle(), NULL);
Mathias Agopian03193062013-05-10 19:32:39 -0700263
264 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800265}
266
Peng Xu47e96012016-03-28 17:55:56 -0700267Sensor SensorService::registerDynamicSensor(SensorInterface* s) {
268 Mutex::Autolock _l(mSensorsLock);
269
Peng Xu2576cb62016-01-20 00:22:09 -0800270 Sensor sensor = registerSensor(s);
271 mDynamicSensorList.add(sensor);
Peng Xu47e96012016-03-28 17:55:56 -0700272
273 auto compareSensorHandle = [] (const Sensor* lhs, const Sensor* rhs) {
274 return lhs->getHandle() - rhs->getHandle();
275 };
276 mDynamicSensorList.sort(compareSensorHandle);
Peng Xu2576cb62016-01-20 00:22:09 -0800277 return sensor;
278}
279
280bool SensorService::unregisterDynamicSensor(int handle) {
Peng Xu47e96012016-03-28 17:55:56 -0700281 Mutex::Autolock _l(mSensorsLock);
282
Peng Xu2576cb62016-01-20 00:22:09 -0800283 bool found = false;
284
Peng Xu47e96012016-03-28 17:55:56 -0700285 for (size_t i = 0 ; i < mSensorList.size() ; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800286 if (mSensorList[i].getHandle() == handle) {
287 mSensorList.removeAt(i);
288 found = true;
289 break;
290 }
291 }
292
293 if (found) {
Peng Xu47e96012016-03-28 17:55:56 -0700294 for (size_t i = 0 ; i < mDynamicSensorList.size() ; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800295 if (mDynamicSensorList[i].getHandle() == handle) {
296 mDynamicSensorList.removeAt(i);
297 }
298 }
299
300 mSensorMap.removeItem(handle);
301 mLastEventSeen.removeItem(handle);
302 }
303 return found;
304}
305
Peng Xu47e96012016-03-28 17:55:56 -0700306Sensor SensorService::registerVirtualSensor(SensorInterface* s) {
Mathias Agopian03193062013-05-10 19:32:39 -0700307 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800308 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700309 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800310}
311
Peng Xu47e96012016-03-28 17:55:56 -0700312bool SensorService::isNewHandle(int handle) {
313 Mutex::Autolock _l(mSensorsLock);
314 for (int h : mUsedHandleList) {
315 if (h == handle) {
316 return false;
317 }
318 }
319 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -0700320}
321
Peng Xu47e96012016-03-28 17:55:56 -0700322SensorService::~SensorService() {
323 Mutex::Autolock _l(mSensorsLock);
324 for (size_t i=0 ; i<mSensorMap.size() ; i++) {
325 delete mSensorMap.valueAt(i);
326 }
327}
328
329status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700330 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700331 if (!PermissionCache::checkCallingPermission(sDump)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800332 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700333 IPCThreadState::self()->getCallingPid(),
334 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700335 } else {
Aravind Akella841a5922015-06-29 12:37:48 -0700336 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800337 return INVALID_OPERATION;
338 }
339 Mutex::Autolock _l(mLock);
340 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700341 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700342 // If already in restricted mode. Ignore.
343 if (mCurrentOperatingMode == RESTRICTED) {
344 return status_t(NO_ERROR);
345 }
346 // If in any mode other than normal, ignore.
347 if (mCurrentOperatingMode != NORMAL) {
348 return INVALID_OPERATION;
349 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700350 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800351 dev.disableAllSensors();
352 // Clear all pending flush connections for all active sensors. If one of the active
353 // connections has called flush() and the underlying sensor has been disabled before a
354 // flush complete event is returned, we need to remove the connection from this queue.
355 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
356 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
357 }
Aravind Akella841a5922015-06-29 12:37:48 -0700358 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700359 return status_t(NO_ERROR);
360 } else if (args.size() == 1 && args[0] == String16("enable")) {
361 // If currently in restricted mode, reset back to NORMAL mode else ignore.
362 if (mCurrentOperatingMode == RESTRICTED) {
363 mCurrentOperatingMode = NORMAL;
364 dev.enableAllSensors();
365 }
Aravind Akella841a5922015-06-29 12:37:48 -0700366 if (mCurrentOperatingMode == DATA_INJECTION) {
367 resetToNormalModeLocked();
368 }
369 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700370 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700371 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
372 if (mCurrentOperatingMode == NORMAL) {
373 dev.disableAllSensors();
374 status_t err = dev.setMode(DATA_INJECTION);
375 if (err == NO_ERROR) {
376 mCurrentOperatingMode = DATA_INJECTION;
377 } else {
378 // Re-enable sensors.
379 dev.enableAllSensors();
380 }
381 mWhiteListedPackage.setTo(String8(args[1]));
382 return NO_ERROR;
383 } else if (mCurrentOperatingMode == DATA_INJECTION) {
384 // Already in DATA_INJECTION mode. Treat this as a no_op.
385 return NO_ERROR;
386 } else {
387 // Transition to data injection mode supported only from NORMAL mode.
388 return INVALID_OPERATION;
389 }
Aravind Akellaee155ca2015-06-24 08:31:32 -0700390 } else if (mSensorList.size() == 0) {
391 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700392 } else {
393 // Default dump the sensor list and debugging information.
394 result.append("Sensor List:\n");
Peng Xu47e96012016-03-28 17:55:56 -0700395 Mutex::Autolock _l(mSensorsLock);
Aravind Akella444f2672015-05-07 12:40:52 -0700396 for (size_t i=0 ; i<mSensorList.size() ; i++) {
397 const Sensor& s(mSensorList[i]);
398 result.appendFormat(
399 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
400 s.getName().string(),
401 s.getVendor().string(),
402 s.getVersion(),
403 s.getStringType().string(),
404 s.getHandle(),
405 s.getRequiredPermission().string(),
406 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700407
Aravind Akella444f2672015-05-07 12:40:52 -0700408 const int reportingMode = s.getReportingMode();
409 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
410 result.append(" continuous | ");
411 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
412 result.append(" on-change | ");
413 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
414 result.append(" one-shot | ");
415 } else {
416 result.append(" special-trigger | ");
417 }
418
419 if (s.getMaxDelay() > 0) {
420 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
421 } else {
422 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
423 }
424
425 if (s.getMinDelay() > 0) {
426 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
427 } else {
428 result.appendFormat("minDelay=%dus |", s.getMinDelay());
429 }
430
431 if (s.getFifoMaxEventCount() > 0) {
432 result.appendFormat("FifoMax=%d events | ",
433 s.getFifoMaxEventCount());
434 } else {
435 result.append("no batching | ");
436 }
437
438 if (s.isWakeUpSensor()) {
439 result.appendFormat("wakeUp | ");
440 } else {
441 result.appendFormat("non-wakeUp | ");
442 }
443
Aravind Akella18d6d512015-06-18 14:18:28 -0700444 int bufIndex = mLastEventSeen.indexOfKey(s.getHandle());
445 if (bufIndex >= 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800446 const MostRecentEventLogger* buf = mLastEventSeen.valueAt(bufIndex);
Aravind Akella18d6d512015-06-18 14:18:28 -0700447 if (buf != NULL && s.getRequiredPermission().isEmpty()) {
448 buf->printBuffer(result);
449 } else {
450 result.append("last=<> \n");
451 }
Aravind Akella444f2672015-05-07 12:40:52 -0700452 }
453 result.append("\n");
454 }
455 SensorFusion::getInstance().dump(result);
456 SensorDevice::getInstance().dump(result);
457
458 result.append("Active sensors:\n");
459 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
460 int handle = mActiveSensors.keyAt(i);
461 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
462 getSensorName(handle).string(),
463 handle,
464 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700465 }
466
Andreas Gamped4036b62015-07-28 13:49:04 -0700467 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700468 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700469 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
470 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700471 result.appendFormat("Mode :");
472 switch(mCurrentOperatingMode) {
473 case NORMAL:
474 result.appendFormat(" NORMAL\n");
475 break;
476 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700477 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700478 break;
479 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700480 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700481 }
Aravind Akella444f2672015-05-07 12:40:52 -0700482 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700483
Aravind Akella444f2672015-05-07 12:40:52 -0700484 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
485 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
486 if (connection != 0) {
487 result.appendFormat("Connection Number: %zu \n", i);
488 connection->dump(result);
489 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700490 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700491
492 result.appendFormat("Previous Registrations:\n");
493 // Log in the reverse chronological order.
494 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
495 SENSOR_REGISTRATIONS_BUF_SIZE;
496 const int startIndex = currentIndex;
497 do {
498 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
499 if (SensorRegistrationInfo::isSentinel(reg_info)) {
500 // Ignore sentinel, proceed to next item.
501 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
502 SENSOR_REGISTRATIONS_BUF_SIZE;
503 continue;
504 }
505 if (reg_info.mActivated) {
506 result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x "
507 "samplingRate=%dus maxReportLatency=%dus\n",
508 reg_info.mHour, reg_info.mMin, reg_info.mSec,
509 reg_info.mPackageName.string(), reg_info.mSensorHandle,
510 reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs);
511 } else {
512 result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n",
513 reg_info.mHour, reg_info.mMin, reg_info.mSec,
514 reg_info.mPackageName.string(), reg_info.mSensorHandle);
515 }
516 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
517 SENSOR_REGISTRATIONS_BUF_SIZE;
518 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700519 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700520 }
521 write(fd, result.string(), result.size());
522 return NO_ERROR;
523}
524
Aravind Akella9a844cf2014-02-11 18:58:52 -0800525void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700526 sensors_event_t const* buffer, const int count) {
527 for (int i=0 ; i<count ; i++) {
528 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700529 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
530 handle = buffer[i].meta_data.sensor;
531 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700532 if (connection->hasSensor(handle)) {
Peng Xu47e96012016-03-28 17:55:56 -0700533 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700534 // If this buffer has an event from a one_shot sensor and this connection is registered
535 // for this particular one_shot sensor, try cleaning up the connection.
536 if (sensor != NULL &&
537 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
538 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800539 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700540 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700541
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700542 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700543 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700544}
545
Peng Xu47e96012016-03-28 17:55:56 -0700546bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000547 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700548
Peng Xueb4d6282015-12-10 18:02:41 -0800549 // each virtual sensor could generate an event per "real" event, that's why we need to size
550 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
551 // aggressive, but guaranteed to be enough.
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700552 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
553 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
554
Mathias Agopianf001c922010-11-11 17:58:51 -0800555 SensorDevice& device(SensorDevice::getInstance());
556 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700557
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700558 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700559 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700560 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
561 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000562 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700563 break;
564 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700565
566 // Reset sensors_event_t.flags to zero for all events in the buffer.
567 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700568 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700569 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700570
Peng Xueb4d6282015-12-10 18:02:41 -0800571 // Make a copy of the connection vector as some connections may be removed during the course
572 // of this loop (especially when one-shot sensor events are present in the sensor_event
573 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
574 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
575 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
576 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700577 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700578 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800579
Aravind Akella9a844cf2014-02-11 18:58:52 -0800580 Mutex::Autolock _l(mLock);
581 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
582 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
583 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
584 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
585 // releasing the wakelock.
586 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700587 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700588 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800589 bufferHasWakeUpEvent = true;
590 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700591 }
592 }
593
Aravind Akella9a844cf2014-02-11 18:58:52 -0800594 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700595 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800596 }
Aravind Akella8493b792014-09-08 15:45:47 -0700597 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800598
Mathias Agopianf001c922010-11-11 17:58:51 -0800599 // handle virtual sensors
600 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700601 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800602 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800603 if (activeVirtualSensorCount) {
604 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700605 SensorFusion& fusion(SensorFusion::getInstance());
606 if (fusion.isEnabled()) {
607 for (size_t i=0 ; i<size_t(count) ; i++) {
608 fusion.process(event[i]);
609 }
610 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700611 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800612 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700613 if (count + k >= minBufferSize) {
614 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700615 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700616 count, k, minBufferSize);
617 break;
618 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800619 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800620 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700621 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700622 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800623 k++;
624 }
625 }
626 }
627 if (k) {
628 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700629 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800630 count += k;
631 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700632 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700633 }
634 }
635 }
636
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700637 // handle backward compatibility for RotationVector sensor
638 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
639 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700640 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700641 // All the 4 components of the quaternion should be available
642 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700643 mSensorEventBuffer[i].data[4] = -1;
644 }
645 }
646 }
647
Aravind Akella8493b792014-09-08 15:45:47 -0700648 for (int i = 0; i < count; ++i) {
Peng Xu2576cb62016-01-20 00:22:09 -0800649 // Map flush_complete_events in the buffer to SensorEventConnections which called flush on
650 // the hardware sensor. mapFlushEventsToConnections[i] will be the SensorEventConnection
651 // mapped to the corresponding flush_complete_event in mSensorEventBuffer[i] if such a
652 // mapping exists (NULL otherwise).
Aravind Akella8493b792014-09-08 15:45:47 -0700653 mMapFlushEventsToConnections[i] = NULL;
654 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
655 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
656 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
657 if (rec != NULL) {
658 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
659 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700660 }
661 }
Peng Xu2576cb62016-01-20 00:22:09 -0800662
663 // handle dynamic sensor meta events, process registration and unregistration of dynamic
664 // sensor based on content of event.
665 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
666 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
667 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
668 const sensor_t& dynamicSensor =
669 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
670 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
671 handle, dynamicSensor.type, dynamicSensor.name);
672
Peng Xu47e96012016-03-28 17:55:56 -0700673 if (isNewHandle(handle)) {
674 sensor_t s = dynamicSensor;
675 // make sure the dynamic sensor flag is set
676 s.flags |= DYNAMIC_SENSOR_MASK;
677 // force the handle to be consistent
678 s.handle = handle;
679 SensorInterface *si = new HardwareSensor(s);
Peng Xu2576cb62016-01-20 00:22:09 -0800680
Peng Xu47e96012016-03-28 17:55:56 -0700681 // This will release hold on dynamic sensor meta, so it should be called after
682 // Sensor object is created.
683 device.handleDynamicSensorConnection(handle, true /*connected*/);
684 registerDynamicSensor(si);
685 } else {
686 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
687 }
Peng Xu2576cb62016-01-20 00:22:09 -0800688 } else {
689 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
690 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
691
692 device.handleDynamicSensorConnection(handle, false /*connected*/);
693 if (!unregisterDynamicSensor(handle)) {
694 ALOGE("Dynamic sensor release error.");
695 }
696
697 size_t numConnections = activeConnections.size();
698 for (size_t i=0 ; i < numConnections; ++i) {
699 if (activeConnections[i] != NULL) {
700 activeConnections[i]->removeSensor(handle);
701 }
702 }
703 }
704 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700705 }
706
Peng Xu2576cb62016-01-20 00:22:09 -0800707
Aravind Akella9a844cf2014-02-11 18:58:52 -0800708 // Send our events to clients. Check the state of wake lock for each client and release the
709 // lock if none of the clients need it.
710 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700711 size_t numConnections = activeConnections.size();
712 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700713 if (activeConnections[i] != 0) {
714 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700715 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700716 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700717 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
718 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700719 if (activeConnections[i]->hasOneShotSensors()) {
720 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
721 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700722 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800723 }
724 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700725
Aravind Akella9a844cf2014-02-11 18:58:52 -0800726 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700727 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800728 }
Aravind Akella8493b792014-09-08 15:45:47 -0700729 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700730
Steve Block3c20fbe2012-01-05 23:22:43 +0000731 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800732 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700733 return false;
734}
735
Aravind Akella56ae4262014-07-10 16:01:10 -0700736sp<Looper> SensorService::getLooper() const {
737 return mLooper;
738}
739
Aravind Akellab4373ac2014-10-29 17:55:20 -0700740void SensorService::resetAllWakeLockRefCounts() {
741 SortedVector< sp<SensorEventConnection> > activeConnections;
742 populateActiveConnections(&activeConnections);
743 {
744 Mutex::Autolock _l(mLock);
745 for (size_t i=0 ; i < activeConnections.size(); ++i) {
746 if (activeConnections[i] != 0) {
747 activeConnections[i]->resetWakeLockRefCount();
748 }
749 }
750 setWakeLockAcquiredLocked(false);
751 }
752}
753
754void SensorService::setWakeLockAcquiredLocked(bool acquire) {
755 if (acquire) {
756 if (!mWakeLockAcquired) {
757 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
758 mWakeLockAcquired = true;
759 }
760 mLooper->wake();
761 } else {
762 if (mWakeLockAcquired) {
763 release_wake_lock(WAKE_LOCK_NAME);
764 mWakeLockAcquired = false;
765 }
766 }
767}
768
Aravind Akellab4373ac2014-10-29 17:55:20 -0700769bool SensorService::isWakeLockAcquired() {
770 Mutex::Autolock _l(mLock);
771 return mWakeLockAcquired;
772}
773
Aravind Akella56ae4262014-07-10 16:01:10 -0700774bool SensorService::SensorEventAckReceiver::threadLoop() {
775 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700776 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700777 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700778 bool wakeLockAcquired = mService->isWakeLockAcquired();
779 int timeout = -1;
780 if (wakeLockAcquired) timeout = 5000;
781 int ret = looper->pollOnce(timeout);
782 if (ret == ALOOPER_POLL_TIMEOUT) {
783 mService->resetAllWakeLockRefCounts();
784 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700785 } while(!Thread::exitPending());
786 return false;
787}
788
Aravind Akella9a844cf2014-02-11 18:58:52 -0800789void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800790 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800791 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800792 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
793 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu9e720462016-01-26 18:48:54 -0800794 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO ||
Peng Xu2576cb62016-01-20 00:22:09 -0800795 mLastEventSeen.indexOfKey(buffer[i].sensor) <0 ) {
796 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800797 }
Peng Xu2576cb62016-01-20 00:22:09 -0800798
799 MostRecentEventLogger* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
800 if (circular_buf == NULL) {
801 circular_buf = new MostRecentEventLogger(buffer[i].type);
802 }
803 circular_buf->addEvent(buffer[i]);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800804 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800805}
806
Peng Xu47e96012016-03-28 17:55:56 -0700807void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800808 struct compar {
809 static int cmp(void const* lhs, void const* rhs) {
810 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
811 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700812 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800813 }
814 };
815 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
816}
817
Mathias Agopian5d270722010-07-19 15:20:39 -0700818String8 SensorService::getSensorName(int handle) const {
Peng Xu47e96012016-03-28 17:55:56 -0700819 Mutex::Autolock _l(mSensorsLock);
Mathias Agopian010e4222011-06-08 20:06:50 -0700820 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700821 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700822 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700823 if (sensor.getHandle() == handle) {
824 return sensor.getName();
825 }
826 }
Peng Xu47e96012016-03-28 17:55:56 -0700827 return String8("unknown");
Mathias Agopian5d270722010-07-19 15:20:39 -0700828}
829
Aravind Akellab4099e72013-10-15 15:43:10 -0700830bool SensorService::isVirtualSensor(int handle) const {
Peng Xu47e96012016-03-28 17:55:56 -0700831 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Peng Xu2576cb62016-01-20 00:22:09 -0800832 return sensor != NULL && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700833}
834
Aravind Akella9a844cf2014-02-11 18:58:52 -0800835bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700836 int handle = event.sensor;
837 if (event.type == SENSOR_TYPE_META_DATA) {
838 handle = event.meta_data.sensor;
839 }
Peng Xu47e96012016-03-28 17:55:56 -0700840 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Sean Wan7869e222014-07-14 17:07:33 -0700841 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800842}
843
Aravind Akella6c2664a2014-08-13 12:24:50 -0700844SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
845 return mActiveSensors.valueFor(handle);
846}
847
Peng Xu47e96012016-03-28 17:55:56 -0700848Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
849 Mutex::Autolock _l(mSensorsLock);
850
Mathias Agopian33264862012-06-28 19:46:54 -0700851 char value[PROPERTY_VALUE_MAX];
852 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000853 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
854 mUserSensorListDebug : mUserSensorList;
855 Vector<Sensor> accessibleSensorList;
856 for (size_t i = 0; i < initialSensorList.size(); i++) {
857 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700858 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000859 accessibleSensorList.add(sensor);
860 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700861 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100862 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700863 sensor.getRequiredPermission().string(),
864 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000865 }
Mathias Agopian33264862012-06-28 19:46:54 -0700866 }
Aravind Akella70018042014-04-07 22:52:37 +0000867 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700868}
869
Peng Xu47e96012016-03-28 17:55:56 -0700870Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
871 Mutex::Autolock _l(mSensorsLock);
872
Peng Xu2576cb62016-01-20 00:22:09 -0800873 Vector<Sensor> accessibleSensorList;
874 for (size_t i = 0; i < mDynamicSensorList.size(); i++) {
875 Sensor sensor = mDynamicSensorList[i];
876 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
877 accessibleSensorList.add(sensor);
878 } else {
879 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
880 sensor.getName().string(),
881 sensor.getRequiredPermission().string(),
882 sensor.getRequiredAppOp());
883 }
884 }
885 return accessibleSensorList;
886}
887
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700888sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700889 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700890 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
891 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
892 return NULL;
893 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700894
895 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700896 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
897 // operating in DI mode.
898 if (requestedMode == DATA_INJECTION) {
899 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
900 if (!isWhiteListedPackage(packageName)) return NULL;
901 }
902
Mathias Agopian5307d172012-09-18 17:02:43 -0700903 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700904 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700905 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700906 if (requestedMode == DATA_INJECTION) {
907 if (mActiveConnections.indexOf(result) < 0) {
908 mActiveConnections.add(result);
909 }
910 // Add the associated file descriptor to the Looper for polling whenever there is data to
911 // be injected.
912 result->updateLooperRegistration(mLooper);
913 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700914 return result;
915}
916
Aravind Akella841a5922015-06-29 12:37:48 -0700917int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700918 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700919 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700920}
921
922status_t SensorService::resetToNormalMode() {
923 Mutex::Autolock _l(mLock);
924 return resetToNormalModeLocked();
925}
926
927status_t SensorService::resetToNormalModeLocked() {
928 SensorDevice& dev(SensorDevice::getInstance());
929 dev.enableAllSensors();
930 status_t err = dev.setMode(NORMAL);
931 mCurrentOperatingMode = NORMAL;
932 return err;
933}
934
Peng Xu47e96012016-03-28 17:55:56 -0700935void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700936 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800937 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700938 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700939 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700940 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800941 int handle = mActiveSensors.keyAt(i);
942 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700943 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu47e96012016-03-28 17:55:56 -0700944 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Steve Blockf5a12302012-01-06 19:20:56 +0000945 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800946 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800947 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800948 }
Aravind Akella8a969552014-09-28 17:52:41 -0700949 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800950 }
951 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700952 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000953 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700954 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700955 c, i, handle);
956
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800957 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000958 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700959 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800960 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700961 delete rec;
962 size--;
963 } else {
964 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700965 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700966 }
Aravind Akella8a969552014-09-28 17:52:41 -0700967 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700968 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700969 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800970 if (c->needsWakeLock()) {
971 checkWakeLockStateLocked();
972 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700973}
974
Peng Xu47e96012016-03-28 17:55:56 -0700975SensorInterface* SensorService::getSensorInterfaceFromHandle(int handle) const {
976 Mutex::Autolock _l(mSensorsLock);
977 ssize_t index = mSensorMap.indexOfKey(handle);
978 return index < 0 ? nullptr : mSensorMap.valueAt(index);
979}
980
Aravind Akella70018042014-04-07 22:52:37 +0000981Sensor SensorService::getSensorFromHandle(int handle) const {
Peng Xu47e96012016-03-28 17:55:56 -0700982 SensorInterface* si = getSensorInterfaceFromHandle(handle);
983 return si ? si->getSensor() : Sensor();
Aravind Akella70018042014-04-07 22:52:37 +0000984}
985
Mathias Agopianfc328812010-07-14 23:41:37 -0700986status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700987 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -0700988 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -0700989 if (mInitCheck != NO_ERROR)
990 return mInitCheck;
991
Peng Xu47e96012016-03-28 17:55:56 -0700992 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700993 if (sensor == NULL) {
994 return BAD_VALUE;
995 }
Aravind Akella70018042014-04-07 22:52:37 +0000996
Svetoslavb412f6e2015-04-29 16:50:41 -0700997 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000998 return BAD_VALUE;
999 }
1000
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001001 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -07001002 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
1003 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -08001004 return INVALID_OPERATION;
1005 }
1006
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001007 SensorRecord* rec = mActiveSensors.valueFor(handle);
1008 if (rec == 0) {
1009 rec = new SensorRecord(connection);
1010 mActiveSensors.add(handle, rec);
1011 if (sensor->isVirtual()) {
1012 mActiveVirtualSensors.add(handle, sensor);
1013 }
1014 } else {
1015 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001016 // this sensor is already activated, but we are adding a connection that uses it.
1017 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001018 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -07001019 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001020 // NOTE: The wake_up flag of this event may get set to
1021 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xueb4d6282015-12-10 18:02:41 -08001022 MostRecentEventLogger *circular_buf = mLastEventSeen.valueFor(handle);
Aravind Akella444f2672015-05-07 12:40:52 -07001023 if (circular_buf) {
1024 sensors_event_t event;
1025 memset(&event, 0, sizeof(event));
1026 // It is unlikely that this buffer is empty as the sensor is already active.
1027 // One possible corner case may be two applications activating an on-change
1028 // sensor at the same time.
1029 if(circular_buf->populateLastEvent(&event)) {
1030 event.sensor = handle;
1031 if (event.version == sizeof(sensors_event_t)) {
1032 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1033 setWakeLockAcquiredLocked(true);
1034 }
1035 connection->sendEvents(&event, 1, NULL);
1036 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1037 checkWakeLockStateLocked();
1038 }
1039 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001040 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001041 }
1042 }
1043 }
1044 }
1045
1046 if (connection->addSensor(handle)) {
1047 BatteryService::enableSensor(connection->getUid(), handle);
1048 // the sensor was added (which means it wasn't already there)
1049 // so, see if this connection becomes active
1050 if (mActiveConnections.indexOf(connection) < 0) {
1051 mActiveConnections.add(connection);
1052 }
1053 } else {
1054 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1055 handle, connection.get());
1056 }
1057
Aravind Akella724d91d2013-06-27 12:04:23 -07001058 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1059 if (samplingPeriodNs < minDelayNs) {
1060 samplingPeriodNs = minDelayNs;
1061 }
1062
Aravind Akella6c2664a2014-08-13 12:24:50 -07001063 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1064 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001065 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1066
Aravind Akella4949c502015-02-11 15:54:35 -08001067 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001068 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001069
Peng Xu20483c42015-10-26 15:14:43 -07001070 // Call flush() before calling activate() on the sensor. Wait for a first
1071 // flush complete event before sending events on this connection. Ignore
1072 // one-shot sensors which don't support flush(). Ignore on-change sensors
1073 // to maintain the on-change logic (any on-change events except the initial
1074 // one should be trigger by a change in value). Also if this sensor isn't
1075 // already active, don't call flush().
1076 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001077 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001078 rec->getNumConnections() > 1) {
1079 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001080 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001081 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001082 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001083 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001084 } else {
1085 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001086 }
1087 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001088
1089 if (err == NO_ERROR) {
1090 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1091 err = sensor->activate(connection.get(), true);
1092 }
1093
Aravind Akella8a969552014-09-28 17:52:41 -07001094 if (err == NO_ERROR) {
1095 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -07001096 SensorRegistrationInfo &reg_info =
1097 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1098 reg_info.mSensorHandle = handle;
1099 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
1100 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
1101 reg_info.mActivated = true;
1102 reg_info.mPackageName = connection->getPackageName();
1103 time_t rawtime = time(NULL);
1104 struct tm * timeinfo = localtime(&rawtime);
1105 reg_info.mHour = timeinfo->tm_hour;
1106 reg_info.mMin = timeinfo->tm_min;
1107 reg_info.mSec = timeinfo->tm_sec;
1108 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001109 }
1110
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001111 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001112 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001113 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001114 }
1115 return err;
1116}
1117
Peng Xu47e96012016-03-28 17:55:56 -07001118status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001119 if (mInitCheck != NO_ERROR)
1120 return mInitCheck;
1121
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001122 Mutex::Autolock _l(mLock);
1123 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001124 if (err == NO_ERROR) {
Peng Xu47e96012016-03-28 17:55:56 -07001125 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001126 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001127
1128 }
1129 if (err == NO_ERROR) {
1130 SensorRegistrationInfo &reg_info =
1131 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1132 reg_info.mActivated = false;
1133 reg_info.mPackageName= connection->getPackageName();
1134 reg_info.mSensorHandle = handle;
1135 time_t rawtime = time(NULL);
1136 struct tm * timeinfo = localtime(&rawtime);
1137 reg_info.mHour = timeinfo->tm_hour;
1138 reg_info.mMin = timeinfo->tm_min;
1139 reg_info.mSec = timeinfo->tm_sec;
1140 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001141 }
1142 return err;
1143}
1144
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001145status_t SensorService::cleanupWithoutDisable(
1146 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001147 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001148 return cleanupWithoutDisableLocked(connection, handle);
1149}
1150
1151status_t SensorService::cleanupWithoutDisableLocked(
1152 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001153 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001154 if (rec) {
1155 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001156 if (connection->removeSensor(handle)) {
1157 BatteryService::disableSensor(connection->getUid(), handle);
1158 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001159 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001160 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001161 mActiveConnections.remove(connection);
1162 }
1163 // see if this sensor becomes inactive
1164 if (rec->removeConnection(connection)) {
1165 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001166 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001167 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001168 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001169 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001170 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001171 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001172}
1173
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001174status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001175 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001176 if (mInitCheck != NO_ERROR)
1177 return mInitCheck;
1178
Peng Xu47e96012016-03-28 17:55:56 -07001179 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Mathias Agopianae09d652011-11-01 17:37:49 -07001180 if (!sensor)
1181 return BAD_VALUE;
1182
Svetoslavb412f6e2015-04-29 16:50:41 -07001183 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001184 return BAD_VALUE;
1185 }
1186
Mathias Agopian1cd70002010-07-21 15:59:50 -07001187 if (ns < 0)
1188 return BAD_VALUE;
1189
Mathias Agopian62569ec2011-11-07 21:21:47 -08001190 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1191 if (ns < minDelayNs) {
1192 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001193 }
1194
Mathias Agopianf001c922010-11-11 17:58:51 -08001195 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001196}
1197
Svetoslavb412f6e2015-04-29 16:50:41 -07001198status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1199 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001200 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001201 SensorDevice& dev(SensorDevice::getInstance());
1202 const int halVersion = dev.getHalDeviceVersion();
1203 status_t err(NO_ERROR);
1204 Mutex::Autolock _l(mLock);
1205 // Loop through all sensors for this connection and call flush on each of them.
1206 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1207 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu47e96012016-03-28 17:55:56 -07001208 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001209 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1210 ALOGE("flush called on a one-shot sensor");
1211 err = INVALID_OPERATION;
1212 continue;
1213 }
Aravind Akella8493b792014-09-08 15:45:47 -07001214 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001215 // For older devices just increment pending flush count which will send a trivial
1216 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001217 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001218 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001219 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1220 err = INVALID_OPERATION;
1221 continue;
1222 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001223 status_t err_flush = sensor->flush(connection.get(), handle);
1224 if (err_flush == NO_ERROR) {
1225 SensorRecord* rec = mActiveSensors.valueFor(handle);
1226 if (rec != NULL) rec->addPendingFlushConnection(connection);
1227 }
1228 err = (err_flush != NO_ERROR) ? err_flush : err;
1229 }
Aravind Akella70018042014-04-07 22:52:37 +00001230 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001231 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001232}
Aravind Akella70018042014-04-07 22:52:37 +00001233
Svetoslavb412f6e2015-04-29 16:50:41 -07001234bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1235 const String16& opPackageName) {
1236 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001237
Svetoslavb412f6e2015-04-29 16:50:41 -07001238 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001239 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001240 }
1241
1242 bool hasPermission = false;
1243
1244 // Runtime permissions can't use the cache as they may change.
1245 if (sensor.isRequiredPermissionRuntime()) {
1246 hasPermission = checkPermission(String16(requiredPermission),
1247 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001248 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001249 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1250 }
1251
1252 if (!hasPermission) {
1253 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1254 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001255 return false;
1256 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001257
1258 const int32_t opCode = sensor.getRequiredAppOp();
1259 if (opCode >= 0) {
1260 AppOpsManager appOps;
1261 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1262 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001263 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001264 operation, sensor.getName().string(), opCode);
1265 return false;
1266 }
1267 }
1268
1269 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001270}
1271
Aravind Akella9a844cf2014-02-11 18:58:52 -08001272void SensorService::checkWakeLockState() {
1273 Mutex::Autolock _l(mLock);
1274 checkWakeLockStateLocked();
1275}
1276
1277void SensorService::checkWakeLockStateLocked() {
1278 if (!mWakeLockAcquired) {
1279 return;
1280 }
1281 bool releaseLock = true;
1282 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1283 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1284 if (connection != 0) {
1285 if (connection->needsWakeLock()) {
1286 releaseLock = false;
1287 break;
1288 }
1289 }
1290 }
1291 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001292 setWakeLockAcquiredLocked(false);
1293 }
1294}
1295
1296void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1297 Mutex::Autolock _l(mLock);
1298 connection->writeToSocketFromCache();
1299 if (connection->needsWakeLock()) {
1300 setWakeLockAcquiredLocked(true);
1301 }
1302}
1303
1304void SensorService::populateActiveConnections(
1305 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1306 Mutex::Autolock _l(mLock);
1307 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1308 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1309 if (connection != 0) {
1310 activeConnections->add(connection);
1311 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001312 }
1313}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001314
Aravind Akella4949c502015-02-11 15:54:35 -08001315bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001316 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001317}
1318
Aravind Akella444f2672015-05-07 12:40:52 -07001319int SensorService::getNumEventsForSensorType(int sensor_event_type) {
Nick Vaccaro95f13902016-03-01 15:49:08 -08001320 if (sensor_event_type >= SENSOR_TYPE_DEVICE_PRIVATE_BASE) {
1321 return 16;
1322 }
Aravind Akella444f2672015-05-07 12:40:52 -07001323 switch (sensor_event_type) {
1324 case SENSOR_TYPE_ROTATION_VECTOR:
1325 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1326 return 5;
1327
1328 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1329 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1330 return 6;
1331
1332 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1333 return 4;
1334
1335 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1336 case SENSOR_TYPE_STEP_DETECTOR:
1337 case SENSOR_TYPE_STEP_COUNTER:
1338 return 1;
1339
1340 default:
1341 return 3;
1342 }
1343}
1344
Mathias Agopianfc328812010-07-14 23:41:37 -07001345}; // namespace android
1346