blob: 89c44791bc5fc320cef06ad70ebb46d524938525 [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) {
79 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -070080 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070081 uint32_t virtualSensorsNeeds =
82 (1<<SENSOR_TYPE_GRAVITY) |
83 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -070084 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
85 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
86 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070087
88 mLastEventSeen.setCapacity(count);
89 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -070090 bool useThisSensor=true;
91
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070092 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -070093 case SENSOR_TYPE_ACCELEROMETER:
94 hasAccel = true;
95 break;
96 case SENSOR_TYPE_MAGNETIC_FIELD:
97 hasMag = true;
98 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070099 case SENSOR_TYPE_ORIENTATION:
100 orientationIndex = i;
101 break;
102 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700103 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700104 hasGyro = true;
105 break;
106 case SENSOR_TYPE_GRAVITY:
107 case SENSOR_TYPE_LINEAR_ACCELERATION:
108 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700109 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
110 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
111 if (IGNORE_HARDWARE_FUSION) {
112 useThisSensor = false;
113 } else {
114 virtualSensorsNeeds &= ~(1<<list[i].type);
115 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700116 break;
117 }
Peng Xuf66684a2015-07-23 11:41:53 -0700118 if (useThisSensor) {
119 registerSensor( new HardwareSensor(list[i]) );
120 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700121 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700122
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700123 // it's safe to instantiate the SensorFusion object here
124 // (it wants to be instantiated after h/w sensors have been
125 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700126 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700127
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700128 // build the sensor list returned to users
129 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700130
Aravind Akellaf5047892015-07-20 17:29:33 -0700131 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700132 // Add Android virtual sensors if they're not already
133 // available in the HAL
Peng Xuf66684a2015-07-23 11:41:53 -0700134 Sensor aSensor;
Mathias Agopian03193062013-05-10 19:32:39 -0700135
136 aSensor = registerVirtualSensor( new RotationVectorSensor() );
137 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
138 mUserSensorList.add(aSensor);
139 }
140
Mathias Agopian03193062013-05-10 19:32:39 -0700141 aSensor = registerVirtualSensor( new OrientationSensor() );
142 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
143 // if we are doing our own rotation-vector, also add
144 // the orientation sensor and remove the HAL provided one.
145 mUserSensorList.replaceAt(aSensor, orientationIndex);
146 }
147
Peng Xuf66684a2015-07-23 11:41:53 -0700148 aSensor = registerVirtualSensor(
149 new LinearAccelerationSensor(list, count) );
150 if (virtualSensorsNeeds &
151 (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
152 mUserSensorList.add(aSensor);
153 }
154
Mathias Agopian33264862012-06-28 19:46:54 -0700155 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700156 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700157 registerVirtualSensor( new GyroDriftSensor() );
158 }
159
Peng Xuf66684a2015-07-23 11:41:53 -0700160 if (hasAccel && hasGyro) {
161 Sensor aSensor;
162
163 aSensor = registerVirtualSensor(
164 new GravitySensor(list, count) );
165 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
166 mUserSensorList.add(aSensor);
167 }
168
169 aSensor = registerVirtualSensor(
170 new GameRotationVectorSensor() );
171 if (virtualSensorsNeeds &
172 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) {
173 mUserSensorList.add(aSensor);
174 }
175 }
176
177 if (hasAccel && hasMag) {
178 Sensor aSensor;
179
180 aSensor = registerVirtualSensor(
181 new GeoMagRotationVectorSensor() );
182 if (virtualSensorsNeeds &
183 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) {
184 mUserSensorList.add(aSensor);
185 }
186 }
187
Mathias Agopian33264862012-06-28 19:46:54 -0700188 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700189 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700190
Aravind Akella5466c3d2014-08-22 16:11:10 -0700191 // Check if the device really supports batching by looking at the FIFO event
192 // counts for each sensor.
193 bool batchingSupported = false;
Svetoslavb412f6e2015-04-29 16:50:41 -0700194 for (size_t i = 0; i < mSensorList.size(); ++i) {
Aravind Akella5466c3d2014-08-22 16:11:10 -0700195 if (mSensorList[i].getFifoMaxEventCount() > 0) {
196 batchingSupported = true;
197 break;
198 }
199 }
200
201 if (batchingSupported) {
202 // Increase socket buffer size to a max of 100 KB for batching capabilities.
203 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
204 } else {
205 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
206 }
207
208 // Compare the socketBufferSize value against the system limits and limit
209 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700210 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
211 char line[128];
212 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
213 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700214 size_t maxSystemSocketBufferSize;
215 sscanf(line, "%zu", &maxSystemSocketBufferSize);
216 if (mSocketBufferSize > maxSystemSocketBufferSize) {
217 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700218 }
219 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700220 if (fp) {
221 fclose(fp);
222 }
223
Aravind Akella9a844cf2014-02-11 18:58:52 -0800224 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700225 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700226 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
227 mSensorEventBuffer = new sensors_event_t[minBufferSize];
228 mSensorEventScratch = new sensors_event_t[minBufferSize];
229 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700230 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700231
Aravind Akella18d6d512015-06-18 14:18:28 -0700232 mNextSensorRegIndex = 0;
233 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
234 mLastNSensorRegistrations.push();
235 }
236
237 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700238 mAckReceiver = new SensorEventAckReceiver(this);
239 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700240 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700241 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700242 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700243}
244
Peng Xu47e96012016-03-28 17:55:56 -0700245Sensor SensorService::registerSensor(SensorInterface* s) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800246 const Sensor sensor(s->getSensor());
Peng Xu47e96012016-03-28 17:55:56 -0700247
248 // add handle to used handle list
249 mUsedHandleList.add(sensor.getHandle());
Mathias Agopianf001c922010-11-11 17:58:51 -0800250 // add to the sensor list (returned to clients)
251 mSensorList.add(sensor);
252 // add to our handle->SensorInterface mapping
253 mSensorMap.add(sensor.getHandle(), s);
254 // create an entry in the mLastEventSeen array
Aravind Akella444f2672015-05-07 12:40:52 -0700255 mLastEventSeen.add(sensor.getHandle(), NULL);
Mathias Agopian03193062013-05-10 19:32:39 -0700256
257 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800258}
259
Peng Xu47e96012016-03-28 17:55:56 -0700260Sensor SensorService::registerDynamicSensor(SensorInterface* s) {
Peng Xu2576cb62016-01-20 00:22:09 -0800261 Sensor sensor = registerSensor(s);
262 mDynamicSensorList.add(sensor);
Peng Xu47e96012016-03-28 17:55:56 -0700263
264 auto compareSensorHandle = [] (const Sensor* lhs, const Sensor* rhs) {
265 return lhs->getHandle() - rhs->getHandle();
266 };
267 mDynamicSensorList.sort(compareSensorHandle);
Peng Xu2576cb62016-01-20 00:22:09 -0800268 return sensor;
269}
270
271bool SensorService::unregisterDynamicSensor(int handle) {
272 bool found = false;
273
Peng Xu47e96012016-03-28 17:55:56 -0700274 for (size_t i = 0 ; i < mSensorList.size() ; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800275 if (mSensorList[i].getHandle() == handle) {
276 mSensorList.removeAt(i);
277 found = true;
278 break;
279 }
280 }
281
282 if (found) {
Peng Xu47e96012016-03-28 17:55:56 -0700283 for (size_t i = 0 ; i < mDynamicSensorList.size() ; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800284 if (mDynamicSensorList[i].getHandle() == handle) {
285 mDynamicSensorList.removeAt(i);
286 }
287 }
288
289 mSensorMap.removeItem(handle);
290 mLastEventSeen.removeItem(handle);
291 }
292 return found;
293}
294
Peng Xu47e96012016-03-28 17:55:56 -0700295Sensor SensorService::registerVirtualSensor(SensorInterface* s) {
Mathias Agopian03193062013-05-10 19:32:39 -0700296 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800297 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700298 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800299}
300
Peng Xu47e96012016-03-28 17:55:56 -0700301bool SensorService::isNewHandle(int handle) {
Peng Xu47e96012016-03-28 17:55:56 -0700302 for (int h : mUsedHandleList) {
303 if (h == handle) {
304 return false;
305 }
306 }
307 return true;
Mathias Agopianfc328812010-07-14 23:41:37 -0700308}
309
Peng Xu47e96012016-03-28 17:55:56 -0700310SensorService::~SensorService() {
Peng Xu47e96012016-03-28 17:55:56 -0700311 for (size_t i=0 ; i<mSensorMap.size() ; i++) {
312 delete mSensorMap.valueAt(i);
313 }
314}
315
316status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700317 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700318 if (!PermissionCache::checkCallingPermission(sDump)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800319 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700320 IPCThreadState::self()->getCallingPid(),
321 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700322 } else {
Aravind Akella841a5922015-06-29 12:37:48 -0700323 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800324 return INVALID_OPERATION;
325 }
326 Mutex::Autolock _l(mLock);
327 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700328 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700329 // If already in restricted mode. Ignore.
330 if (mCurrentOperatingMode == RESTRICTED) {
331 return status_t(NO_ERROR);
332 }
333 // If in any mode other than normal, ignore.
334 if (mCurrentOperatingMode != NORMAL) {
335 return INVALID_OPERATION;
336 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700337 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800338 dev.disableAllSensors();
339 // Clear all pending flush connections for all active sensors. If one of the active
340 // connections has called flush() and the underlying sensor has been disabled before a
341 // flush complete event is returned, we need to remove the connection from this queue.
342 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
343 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
344 }
Aravind Akella841a5922015-06-29 12:37:48 -0700345 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700346 return status_t(NO_ERROR);
347 } else if (args.size() == 1 && args[0] == String16("enable")) {
348 // If currently in restricted mode, reset back to NORMAL mode else ignore.
349 if (mCurrentOperatingMode == RESTRICTED) {
350 mCurrentOperatingMode = NORMAL;
351 dev.enableAllSensors();
352 }
Aravind Akella841a5922015-06-29 12:37:48 -0700353 if (mCurrentOperatingMode == DATA_INJECTION) {
354 resetToNormalModeLocked();
355 }
356 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700357 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700358 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
359 if (mCurrentOperatingMode == NORMAL) {
360 dev.disableAllSensors();
361 status_t err = dev.setMode(DATA_INJECTION);
362 if (err == NO_ERROR) {
363 mCurrentOperatingMode = DATA_INJECTION;
364 } else {
365 // Re-enable sensors.
366 dev.enableAllSensors();
367 }
368 mWhiteListedPackage.setTo(String8(args[1]));
369 return NO_ERROR;
370 } else if (mCurrentOperatingMode == DATA_INJECTION) {
371 // Already in DATA_INJECTION mode. Treat this as a no_op.
372 return NO_ERROR;
373 } else {
374 // Transition to data injection mode supported only from NORMAL mode.
375 return INVALID_OPERATION;
376 }
Aravind Akellaee155ca2015-06-24 08:31:32 -0700377 } else if (mSensorList.size() == 0) {
378 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700379 } else {
380 // Default dump the sensor list and debugging information.
381 result.append("Sensor List:\n");
382 for (size_t i=0 ; i<mSensorList.size() ; i++) {
383 const Sensor& s(mSensorList[i]);
384 result.appendFormat(
385 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
386 s.getName().string(),
387 s.getVendor().string(),
388 s.getVersion(),
389 s.getStringType().string(),
390 s.getHandle(),
391 s.getRequiredPermission().string(),
392 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700393
Aravind Akella444f2672015-05-07 12:40:52 -0700394 const int reportingMode = s.getReportingMode();
395 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
396 result.append(" continuous | ");
397 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
398 result.append(" on-change | ");
399 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
400 result.append(" one-shot | ");
401 } else {
402 result.append(" special-trigger | ");
403 }
404
405 if (s.getMaxDelay() > 0) {
406 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
407 } else {
408 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
409 }
410
411 if (s.getMinDelay() > 0) {
412 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
413 } else {
414 result.appendFormat("minDelay=%dus |", s.getMinDelay());
415 }
416
417 if (s.getFifoMaxEventCount() > 0) {
418 result.appendFormat("FifoMax=%d events | ",
419 s.getFifoMaxEventCount());
420 } else {
421 result.append("no batching | ");
422 }
423
424 if (s.isWakeUpSensor()) {
425 result.appendFormat("wakeUp | ");
426 } else {
427 result.appendFormat("non-wakeUp | ");
428 }
429
Aravind Akella18d6d512015-06-18 14:18:28 -0700430 int bufIndex = mLastEventSeen.indexOfKey(s.getHandle());
431 if (bufIndex >= 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800432 const MostRecentEventLogger* buf = mLastEventSeen.valueAt(bufIndex);
Aravind Akella18d6d512015-06-18 14:18:28 -0700433 if (buf != NULL && s.getRequiredPermission().isEmpty()) {
434 buf->printBuffer(result);
435 } else {
436 result.append("last=<> \n");
437 }
Aravind Akella444f2672015-05-07 12:40:52 -0700438 }
439 result.append("\n");
440 }
441 SensorFusion::getInstance().dump(result);
442 SensorDevice::getInstance().dump(result);
443
444 result.append("Active sensors:\n");
445 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
446 int handle = mActiveSensors.keyAt(i);
447 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
448 getSensorName(handle).string(),
449 handle,
450 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700451 }
452
Andreas Gamped4036b62015-07-28 13:49:04 -0700453 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700454 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700455 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
456 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700457 result.appendFormat("Mode :");
458 switch(mCurrentOperatingMode) {
459 case NORMAL:
460 result.appendFormat(" NORMAL\n");
461 break;
462 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700463 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700464 break;
465 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700466 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700467 }
Aravind Akella444f2672015-05-07 12:40:52 -0700468 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700469
Aravind Akella444f2672015-05-07 12:40:52 -0700470 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
471 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
472 if (connection != 0) {
473 result.appendFormat("Connection Number: %zu \n", i);
474 connection->dump(result);
475 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700476 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700477
478 result.appendFormat("Previous Registrations:\n");
479 // Log in the reverse chronological order.
480 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
481 SENSOR_REGISTRATIONS_BUF_SIZE;
482 const int startIndex = currentIndex;
483 do {
484 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
485 if (SensorRegistrationInfo::isSentinel(reg_info)) {
486 // Ignore sentinel, proceed to next item.
487 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
488 SENSOR_REGISTRATIONS_BUF_SIZE;
489 continue;
490 }
491 if (reg_info.mActivated) {
492 result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x "
493 "samplingRate=%dus maxReportLatency=%dus\n",
494 reg_info.mHour, reg_info.mMin, reg_info.mSec,
495 reg_info.mPackageName.string(), reg_info.mSensorHandle,
496 reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs);
497 } else {
498 result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n",
499 reg_info.mHour, reg_info.mMin, reg_info.mSec,
500 reg_info.mPackageName.string(), reg_info.mSensorHandle);
501 }
502 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
503 SENSOR_REGISTRATIONS_BUF_SIZE;
504 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700505 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700506 }
507 write(fd, result.string(), result.size());
508 return NO_ERROR;
509}
510
Aravind Akella9a844cf2014-02-11 18:58:52 -0800511void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700512 sensors_event_t const* buffer, const int count) {
513 for (int i=0 ; i<count ; i++) {
514 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700515 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
516 handle = buffer[i].meta_data.sensor;
517 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700518 if (connection->hasSensor(handle)) {
Peng Xu47e96012016-03-28 17:55:56 -0700519 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700520 // If this buffer has an event from a one_shot sensor and this connection is registered
521 // for this particular one_shot sensor, try cleaning up the connection.
522 if (sensor != NULL &&
523 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
524 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800525 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700526 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700527
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700528 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700529 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700530}
531
Peng Xu47e96012016-03-28 17:55:56 -0700532bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000533 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700534
Peng Xueb4d6282015-12-10 18:02:41 -0800535 // each virtual sensor could generate an event per "real" event, that's why we need to size
536 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
537 // aggressive, but guaranteed to be enough.
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700538 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
539 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
540
Mathias Agopianf001c922010-11-11 17:58:51 -0800541 SensorDevice& device(SensorDevice::getInstance());
542 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700543
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700544 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700545 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700546 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
547 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000548 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700549 break;
550 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700551
552 // Reset sensors_event_t.flags to zero for all events in the buffer.
553 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700554 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700555 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700556
Peng Xueb4d6282015-12-10 18:02:41 -0800557 // Make a copy of the connection vector as some connections may be removed during the course
558 // of this loop (especially when one-shot sensor events are present in the sensor_event
559 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
560 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
561 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
562 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700563 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700564 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800565
Aravind Akella9a844cf2014-02-11 18:58:52 -0800566 Mutex::Autolock _l(mLock);
567 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
568 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
569 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
570 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
571 // releasing the wakelock.
572 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700573 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700574 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800575 bufferHasWakeUpEvent = true;
576 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700577 }
578 }
579
Aravind Akella9a844cf2014-02-11 18:58:52 -0800580 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700581 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800582 }
Aravind Akella8493b792014-09-08 15:45:47 -0700583 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800584
Mathias Agopianf001c922010-11-11 17:58:51 -0800585 // handle virtual sensors
586 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700587 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800588 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800589 if (activeVirtualSensorCount) {
590 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700591 SensorFusion& fusion(SensorFusion::getInstance());
592 if (fusion.isEnabled()) {
593 for (size_t i=0 ; i<size_t(count) ; i++) {
594 fusion.process(event[i]);
595 }
596 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700597 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800598 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700599 if (count + k >= minBufferSize) {
600 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700601 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700602 count, k, minBufferSize);
603 break;
604 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800605 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800606 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700607 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700608 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800609 k++;
610 }
611 }
612 }
613 if (k) {
614 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700615 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800616 count += k;
617 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700618 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700619 }
620 }
621 }
622
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700623 // handle backward compatibility for RotationVector sensor
624 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
625 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700626 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700627 // All the 4 components of the quaternion should be available
628 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700629 mSensorEventBuffer[i].data[4] = -1;
630 }
631 }
632 }
633
Aravind Akella8493b792014-09-08 15:45:47 -0700634 for (int i = 0; i < count; ++i) {
Peng Xu2576cb62016-01-20 00:22:09 -0800635 // Map flush_complete_events in the buffer to SensorEventConnections which called flush on
636 // the hardware sensor. mapFlushEventsToConnections[i] will be the SensorEventConnection
637 // mapped to the corresponding flush_complete_event in mSensorEventBuffer[i] if such a
638 // mapping exists (NULL otherwise).
Aravind Akella8493b792014-09-08 15:45:47 -0700639 mMapFlushEventsToConnections[i] = NULL;
640 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
641 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
642 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
643 if (rec != NULL) {
644 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
645 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700646 }
647 }
Peng Xu2576cb62016-01-20 00:22:09 -0800648
649 // handle dynamic sensor meta events, process registration and unregistration of dynamic
650 // sensor based on content of event.
651 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
652 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
653 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
654 const sensor_t& dynamicSensor =
655 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
656 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
657 handle, dynamicSensor.type, dynamicSensor.name);
658
Peng Xu47e96012016-03-28 17:55:56 -0700659 if (isNewHandle(handle)) {
660 sensor_t s = dynamicSensor;
661 // make sure the dynamic sensor flag is set
662 s.flags |= DYNAMIC_SENSOR_MASK;
663 // force the handle to be consistent
664 s.handle = handle;
665 SensorInterface *si = new HardwareSensor(s);
Peng Xu2576cb62016-01-20 00:22:09 -0800666
Peng Xu47e96012016-03-28 17:55:56 -0700667 // This will release hold on dynamic sensor meta, so it should be called after
668 // Sensor object is created.
669 device.handleDynamicSensorConnection(handle, true /*connected*/);
670 registerDynamicSensor(si);
671 } else {
672 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
673 }
Peng Xu2576cb62016-01-20 00:22:09 -0800674 } else {
675 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
676 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
677
678 device.handleDynamicSensorConnection(handle, false /*connected*/);
679 if (!unregisterDynamicSensor(handle)) {
680 ALOGE("Dynamic sensor release error.");
681 }
682
683 size_t numConnections = activeConnections.size();
684 for (size_t i=0 ; i < numConnections; ++i) {
685 if (activeConnections[i] != NULL) {
686 activeConnections[i]->removeSensor(handle);
687 }
688 }
689 }
690 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700691 }
692
Peng Xu2576cb62016-01-20 00:22:09 -0800693
Aravind Akella9a844cf2014-02-11 18:58:52 -0800694 // Send our events to clients. Check the state of wake lock for each client and release the
695 // lock if none of the clients need it.
696 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700697 size_t numConnections = activeConnections.size();
698 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700699 if (activeConnections[i] != 0) {
700 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700701 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700702 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700703 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
704 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700705 if (activeConnections[i]->hasOneShotSensors()) {
706 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
707 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700708 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800709 }
710 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700711
Aravind Akella9a844cf2014-02-11 18:58:52 -0800712 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700713 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800714 }
Aravind Akella8493b792014-09-08 15:45:47 -0700715 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700716
Steve Block3c20fbe2012-01-05 23:22:43 +0000717 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800718 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700719 return false;
720}
721
Aravind Akella56ae4262014-07-10 16:01:10 -0700722sp<Looper> SensorService::getLooper() const {
723 return mLooper;
724}
725
Aravind Akellab4373ac2014-10-29 17:55:20 -0700726void SensorService::resetAllWakeLockRefCounts() {
727 SortedVector< sp<SensorEventConnection> > activeConnections;
728 populateActiveConnections(&activeConnections);
729 {
730 Mutex::Autolock _l(mLock);
731 for (size_t i=0 ; i < activeConnections.size(); ++i) {
732 if (activeConnections[i] != 0) {
733 activeConnections[i]->resetWakeLockRefCount();
734 }
735 }
736 setWakeLockAcquiredLocked(false);
737 }
738}
739
740void SensorService::setWakeLockAcquiredLocked(bool acquire) {
741 if (acquire) {
742 if (!mWakeLockAcquired) {
743 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
744 mWakeLockAcquired = true;
745 }
746 mLooper->wake();
747 } else {
748 if (mWakeLockAcquired) {
749 release_wake_lock(WAKE_LOCK_NAME);
750 mWakeLockAcquired = false;
751 }
752 }
753}
754
Aravind Akellab4373ac2014-10-29 17:55:20 -0700755bool SensorService::isWakeLockAcquired() {
756 Mutex::Autolock _l(mLock);
757 return mWakeLockAcquired;
758}
759
Aravind Akella56ae4262014-07-10 16:01:10 -0700760bool SensorService::SensorEventAckReceiver::threadLoop() {
761 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700762 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700763 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700764 bool wakeLockAcquired = mService->isWakeLockAcquired();
765 int timeout = -1;
766 if (wakeLockAcquired) timeout = 5000;
767 int ret = looper->pollOnce(timeout);
768 if (ret == ALOOPER_POLL_TIMEOUT) {
769 mService->resetAllWakeLockRefCounts();
770 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700771 } while(!Thread::exitPending());
772 return false;
773}
774
Aravind Akella9a844cf2014-02-11 18:58:52 -0800775void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800776 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800777 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800778 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
779 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu9e720462016-01-26 18:48:54 -0800780 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO ||
Peng Xu2576cb62016-01-20 00:22:09 -0800781 mLastEventSeen.indexOfKey(buffer[i].sensor) <0 ) {
782 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800783 }
Peng Xu2576cb62016-01-20 00:22:09 -0800784
785 MostRecentEventLogger* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
786 if (circular_buf == NULL) {
787 circular_buf = new MostRecentEventLogger(buffer[i].type);
788 }
789 circular_buf->addEvent(buffer[i]);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800790 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800791}
792
Peng Xu47e96012016-03-28 17:55:56 -0700793void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800794 struct compar {
795 static int cmp(void const* lhs, void const* rhs) {
796 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
797 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700798 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800799 }
800 };
801 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
802}
803
Mathias Agopian5d270722010-07-19 15:20:39 -0700804String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700805 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700806 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700807 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700808 if (sensor.getHandle() == handle) {
809 return sensor.getName();
810 }
811 }
Peng Xu47e96012016-03-28 17:55:56 -0700812 return String8("unknown");
Mathias Agopian5d270722010-07-19 15:20:39 -0700813}
814
Aravind Akellab4099e72013-10-15 15:43:10 -0700815bool SensorService::isVirtualSensor(int handle) const {
Peng Xu47e96012016-03-28 17:55:56 -0700816 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Peng Xu2576cb62016-01-20 00:22:09 -0800817 return sensor != NULL && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700818}
819
Aravind Akella9a844cf2014-02-11 18:58:52 -0800820bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700821 int handle = event.sensor;
822 if (event.type == SENSOR_TYPE_META_DATA) {
823 handle = event.meta_data.sensor;
824 }
Peng Xu47e96012016-03-28 17:55:56 -0700825 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Sean Wan7869e222014-07-14 17:07:33 -0700826 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800827}
828
Aravind Akella6c2664a2014-08-13 12:24:50 -0700829SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
830 return mActiveSensors.valueFor(handle);
831}
832
Peng Xu47e96012016-03-28 17:55:56 -0700833Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -0700834 char value[PROPERTY_VALUE_MAX];
835 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000836 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
837 mUserSensorListDebug : mUserSensorList;
838 Vector<Sensor> accessibleSensorList;
839 for (size_t i = 0; i < initialSensorList.size(); i++) {
840 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700841 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000842 accessibleSensorList.add(sensor);
843 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700844 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100845 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700846 sensor.getRequiredPermission().string(),
847 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000848 }
Mathias Agopian33264862012-06-28 19:46:54 -0700849 }
Aravind Akella70018042014-04-07 22:52:37 +0000850 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700851}
852
Peng Xu47e96012016-03-28 17:55:56 -0700853Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -0800854 Vector<Sensor> accessibleSensorList;
855 for (size_t i = 0; i < mDynamicSensorList.size(); i++) {
856 Sensor sensor = mDynamicSensorList[i];
857 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
858 accessibleSensorList.add(sensor);
859 } else {
860 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
861 sensor.getName().string(),
862 sensor.getRequiredPermission().string(),
863 sensor.getRequiredAppOp());
864 }
865 }
866 return accessibleSensorList;
867}
868
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700869sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700870 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700871 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
872 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
873 return NULL;
874 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700875
876 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700877 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
878 // operating in DI mode.
879 if (requestedMode == DATA_INJECTION) {
880 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
881 if (!isWhiteListedPackage(packageName)) return NULL;
882 }
883
Mathias Agopian5307d172012-09-18 17:02:43 -0700884 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700885 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700886 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700887 if (requestedMode == DATA_INJECTION) {
888 if (mActiveConnections.indexOf(result) < 0) {
889 mActiveConnections.add(result);
890 }
891 // Add the associated file descriptor to the Looper for polling whenever there is data to
892 // be injected.
893 result->updateLooperRegistration(mLooper);
894 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700895 return result;
896}
897
Aravind Akella841a5922015-06-29 12:37:48 -0700898int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700899 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700900 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700901}
902
903status_t SensorService::resetToNormalMode() {
904 Mutex::Autolock _l(mLock);
905 return resetToNormalModeLocked();
906}
907
908status_t SensorService::resetToNormalModeLocked() {
909 SensorDevice& dev(SensorDevice::getInstance());
910 dev.enableAllSensors();
911 status_t err = dev.setMode(NORMAL);
912 mCurrentOperatingMode = NORMAL;
913 return err;
914}
915
Peng Xu47e96012016-03-28 17:55:56 -0700916void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700917 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800918 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700919 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700920 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700921 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800922 int handle = mActiveSensors.keyAt(i);
923 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700924 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu47e96012016-03-28 17:55:56 -0700925 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Steve Blockf5a12302012-01-06 19:20:56 +0000926 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800927 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800928 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800929 }
Aravind Akella8a969552014-09-28 17:52:41 -0700930 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800931 }
932 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700933 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000934 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700935 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700936 c, i, handle);
937
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800938 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000939 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700940 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800941 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700942 delete rec;
943 size--;
944 } else {
945 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700946 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700947 }
Aravind Akella8a969552014-09-28 17:52:41 -0700948 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700949 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700950 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800951 if (c->needsWakeLock()) {
952 checkWakeLockStateLocked();
953 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700954}
955
Peng Xu47e96012016-03-28 17:55:56 -0700956SensorInterface* SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu47e96012016-03-28 17:55:56 -0700957 ssize_t index = mSensorMap.indexOfKey(handle);
958 return index < 0 ? nullptr : mSensorMap.valueAt(index);
959}
960
Aravind Akella70018042014-04-07 22:52:37 +0000961Sensor SensorService::getSensorFromHandle(int handle) const {
Peng Xu47e96012016-03-28 17:55:56 -0700962 SensorInterface* si = getSensorInterfaceFromHandle(handle);
963 return si ? si->getSensor() : Sensor();
Aravind Akella70018042014-04-07 22:52:37 +0000964}
965
Mathias Agopianfc328812010-07-14 23:41:37 -0700966status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700967 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -0700968 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -0700969 if (mInitCheck != NO_ERROR)
970 return mInitCheck;
971
Peng Xu47e96012016-03-28 17:55:56 -0700972 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700973 if (sensor == NULL) {
974 return BAD_VALUE;
975 }
Aravind Akella70018042014-04-07 22:52:37 +0000976
Svetoslavb412f6e2015-04-29 16:50:41 -0700977 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000978 return BAD_VALUE;
979 }
980
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700981 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700982 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
983 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800984 return INVALID_OPERATION;
985 }
986
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700987 SensorRecord* rec = mActiveSensors.valueFor(handle);
988 if (rec == 0) {
989 rec = new SensorRecord(connection);
990 mActiveSensors.add(handle, rec);
991 if (sensor->isVirtual()) {
992 mActiveVirtualSensors.add(handle, sensor);
993 }
994 } else {
995 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800996 // this sensor is already activated, but we are adding a connection that uses it.
997 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700998 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700999 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -08001000 // NOTE: The wake_up flag of this event may get set to
1001 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xueb4d6282015-12-10 18:02:41 -08001002 MostRecentEventLogger *circular_buf = mLastEventSeen.valueFor(handle);
Aravind Akella444f2672015-05-07 12:40:52 -07001003 if (circular_buf) {
1004 sensors_event_t event;
1005 memset(&event, 0, sizeof(event));
1006 // It is unlikely that this buffer is empty as the sensor is already active.
1007 // One possible corner case may be two applications activating an on-change
1008 // sensor at the same time.
1009 if(circular_buf->populateLastEvent(&event)) {
1010 event.sensor = handle;
1011 if (event.version == sizeof(sensors_event_t)) {
1012 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
1013 setWakeLockAcquiredLocked(true);
1014 }
1015 connection->sendEvents(&event, 1, NULL);
1016 if (!connection->needsWakeLock() && mWakeLockAcquired) {
1017 checkWakeLockStateLocked();
1018 }
1019 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001020 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001021 }
1022 }
1023 }
1024 }
1025
1026 if (connection->addSensor(handle)) {
1027 BatteryService::enableSensor(connection->getUid(), handle);
1028 // the sensor was added (which means it wasn't already there)
1029 // so, see if this connection becomes active
1030 if (mActiveConnections.indexOf(connection) < 0) {
1031 mActiveConnections.add(connection);
1032 }
1033 } else {
1034 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1035 handle, connection.get());
1036 }
1037
Aravind Akella724d91d2013-06-27 12:04:23 -07001038 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1039 if (samplingPeriodNs < minDelayNs) {
1040 samplingPeriodNs = minDelayNs;
1041 }
1042
Aravind Akella6c2664a2014-08-13 12:24:50 -07001043 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1044 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001045 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1046
Aravind Akella4949c502015-02-11 15:54:35 -08001047 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001048 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001049
Peng Xu20483c42015-10-26 15:14:43 -07001050 // Call flush() before calling activate() on the sensor. Wait for a first
1051 // flush complete event before sending events on this connection. Ignore
1052 // one-shot sensors which don't support flush(). Ignore on-change sensors
1053 // to maintain the on-change logic (any on-change events except the initial
1054 // one should be trigger by a change in value). Also if this sensor isn't
1055 // already active, don't call flush().
1056 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001057 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001058 rec->getNumConnections() > 1) {
1059 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001060 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001061 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001062 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001063 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001064 } else {
1065 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001066 }
1067 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001068
1069 if (err == NO_ERROR) {
1070 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1071 err = sensor->activate(connection.get(), true);
1072 }
1073
Aravind Akella8a969552014-09-28 17:52:41 -07001074 if (err == NO_ERROR) {
1075 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -07001076 SensorRegistrationInfo &reg_info =
1077 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1078 reg_info.mSensorHandle = handle;
1079 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
1080 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
1081 reg_info.mActivated = true;
1082 reg_info.mPackageName = connection->getPackageName();
1083 time_t rawtime = time(NULL);
1084 struct tm * timeinfo = localtime(&rawtime);
1085 reg_info.mHour = timeinfo->tm_hour;
1086 reg_info.mMin = timeinfo->tm_min;
1087 reg_info.mSec = timeinfo->tm_sec;
1088 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001089 }
1090
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001091 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001092 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001093 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001094 }
1095 return err;
1096}
1097
Peng Xu47e96012016-03-28 17:55:56 -07001098status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001099 if (mInitCheck != NO_ERROR)
1100 return mInitCheck;
1101
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001102 Mutex::Autolock _l(mLock);
1103 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001104 if (err == NO_ERROR) {
Peng Xu47e96012016-03-28 17:55:56 -07001105 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001106 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001107
1108 }
1109 if (err == NO_ERROR) {
1110 SensorRegistrationInfo &reg_info =
1111 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1112 reg_info.mActivated = false;
1113 reg_info.mPackageName= connection->getPackageName();
1114 reg_info.mSensorHandle = handle;
1115 time_t rawtime = time(NULL);
1116 struct tm * timeinfo = localtime(&rawtime);
1117 reg_info.mHour = timeinfo->tm_hour;
1118 reg_info.mMin = timeinfo->tm_min;
1119 reg_info.mSec = timeinfo->tm_sec;
1120 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001121 }
1122 return err;
1123}
1124
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001125status_t SensorService::cleanupWithoutDisable(
1126 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001127 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001128 return cleanupWithoutDisableLocked(connection, handle);
1129}
1130
1131status_t SensorService::cleanupWithoutDisableLocked(
1132 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001133 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001134 if (rec) {
1135 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001136 if (connection->removeSensor(handle)) {
1137 BatteryService::disableSensor(connection->getUid(), handle);
1138 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001139 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001140 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001141 mActiveConnections.remove(connection);
1142 }
1143 // see if this sensor becomes inactive
1144 if (rec->removeConnection(connection)) {
1145 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001146 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001147 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001148 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001149 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001150 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001151 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001152}
1153
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001154status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001155 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001156 if (mInitCheck != NO_ERROR)
1157 return mInitCheck;
1158
Peng Xu47e96012016-03-28 17:55:56 -07001159 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Mathias Agopianae09d652011-11-01 17:37:49 -07001160 if (!sensor)
1161 return BAD_VALUE;
1162
Svetoslavb412f6e2015-04-29 16:50:41 -07001163 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001164 return BAD_VALUE;
1165 }
1166
Mathias Agopian1cd70002010-07-21 15:59:50 -07001167 if (ns < 0)
1168 return BAD_VALUE;
1169
Mathias Agopian62569ec2011-11-07 21:21:47 -08001170 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1171 if (ns < minDelayNs) {
1172 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001173 }
1174
Mathias Agopianf001c922010-11-11 17:58:51 -08001175 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001176}
1177
Svetoslavb412f6e2015-04-29 16:50:41 -07001178status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1179 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001180 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001181 SensorDevice& dev(SensorDevice::getInstance());
1182 const int halVersion = dev.getHalDeviceVersion();
1183 status_t err(NO_ERROR);
1184 Mutex::Autolock _l(mLock);
1185 // Loop through all sensors for this connection and call flush on each of them.
1186 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1187 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu47e96012016-03-28 17:55:56 -07001188 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001189 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1190 ALOGE("flush called on a one-shot sensor");
1191 err = INVALID_OPERATION;
1192 continue;
1193 }
Aravind Akella8493b792014-09-08 15:45:47 -07001194 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001195 // For older devices just increment pending flush count which will send a trivial
1196 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001197 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001198 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001199 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1200 err = INVALID_OPERATION;
1201 continue;
1202 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001203 status_t err_flush = sensor->flush(connection.get(), handle);
1204 if (err_flush == NO_ERROR) {
1205 SensorRecord* rec = mActiveSensors.valueFor(handle);
1206 if (rec != NULL) rec->addPendingFlushConnection(connection);
1207 }
1208 err = (err_flush != NO_ERROR) ? err_flush : err;
1209 }
Aravind Akella70018042014-04-07 22:52:37 +00001210 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001211 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001212}
Aravind Akella70018042014-04-07 22:52:37 +00001213
Svetoslavb412f6e2015-04-29 16:50:41 -07001214bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1215 const String16& opPackageName) {
1216 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001217
Svetoslavb412f6e2015-04-29 16:50:41 -07001218 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001219 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001220 }
1221
1222 bool hasPermission = false;
1223
1224 // Runtime permissions can't use the cache as they may change.
1225 if (sensor.isRequiredPermissionRuntime()) {
1226 hasPermission = checkPermission(String16(requiredPermission),
1227 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001228 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001229 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1230 }
1231
1232 if (!hasPermission) {
1233 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1234 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001235 return false;
1236 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001237
1238 const int32_t opCode = sensor.getRequiredAppOp();
1239 if (opCode >= 0) {
1240 AppOpsManager appOps;
1241 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1242 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001243 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001244 operation, sensor.getName().string(), opCode);
1245 return false;
1246 }
1247 }
1248
1249 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001250}
1251
Aravind Akella9a844cf2014-02-11 18:58:52 -08001252void SensorService::checkWakeLockState() {
1253 Mutex::Autolock _l(mLock);
1254 checkWakeLockStateLocked();
1255}
1256
1257void SensorService::checkWakeLockStateLocked() {
1258 if (!mWakeLockAcquired) {
1259 return;
1260 }
1261 bool releaseLock = true;
1262 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1263 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1264 if (connection != 0) {
1265 if (connection->needsWakeLock()) {
1266 releaseLock = false;
1267 break;
1268 }
1269 }
1270 }
1271 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001272 setWakeLockAcquiredLocked(false);
1273 }
1274}
1275
1276void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1277 Mutex::Autolock _l(mLock);
1278 connection->writeToSocketFromCache();
1279 if (connection->needsWakeLock()) {
1280 setWakeLockAcquiredLocked(true);
1281 }
1282}
1283
1284void SensorService::populateActiveConnections(
1285 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1286 Mutex::Autolock _l(mLock);
1287 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1288 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1289 if (connection != 0) {
1290 activeConnections->add(connection);
1291 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001292 }
1293}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001294
Aravind Akella4949c502015-02-11 15:54:35 -08001295bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001296 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001297}
1298
Aravind Akella444f2672015-05-07 12:40:52 -07001299int SensorService::getNumEventsForSensorType(int sensor_event_type) {
Nick Vaccaro95f13902016-03-01 15:49:08 -08001300 if (sensor_event_type >= SENSOR_TYPE_DEVICE_PRIVATE_BASE) {
1301 return 16;
1302 }
Aravind Akella444f2672015-05-07 12:40:52 -07001303 switch (sensor_event_type) {
1304 case SENSOR_TYPE_ROTATION_VECTOR:
1305 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1306 return 5;
1307
1308 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1309 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1310 return 6;
1311
1312 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1313 return 4;
1314
1315 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1316 case SENSOR_TYPE_STEP_DETECTOR:
1317 case SENSOR_TYPE_STEP_COUNTER:
1318 return 1;
1319
1320 default:
1321 return 3;
1322 }
1323}
1324
Mathias Agopianfc328812010-07-14 23:41:37 -07001325}; // namespace android
1326