blob: f91dac50ce91b94e5cecc022b80d5b25280db71a [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),
68 mWakeLockAcquired(false)
Mathias Agopianfc328812010-07-14 23:41:37 -070069{
70}
71
72void SensorService::onFirstRef()
73{
Steve Blocka5512372011-12-20 16:23:08 +000074 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -080075 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070076
Mathias Agopianf001c922010-11-11 17:58:51 -080077 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080078 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070079 ssize_t count = dev.getSensorList(&list);
80 if (count > 0) {
81 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -070082 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070083 uint32_t virtualSensorsNeeds =
84 (1<<SENSOR_TYPE_GRAVITY) |
85 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -070086 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
87 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
88 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070089
90 mLastEventSeen.setCapacity(count);
91 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -070092 bool useThisSensor=true;
93
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070094 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -070095 case SENSOR_TYPE_ACCELEROMETER:
96 hasAccel = true;
97 break;
98 case SENSOR_TYPE_MAGNETIC_FIELD:
99 hasMag = true;
100 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700101 case SENSOR_TYPE_ORIENTATION:
102 orientationIndex = i;
103 break;
104 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700105 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700106 hasGyro = true;
107 break;
108 case SENSOR_TYPE_GRAVITY:
109 case SENSOR_TYPE_LINEAR_ACCELERATION:
110 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700111 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
112 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
113 if (IGNORE_HARDWARE_FUSION) {
114 useThisSensor = false;
115 } else {
116 virtualSensorsNeeds &= ~(1<<list[i].type);
117 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700118 break;
119 }
Peng Xuf66684a2015-07-23 11:41:53 -0700120 if (useThisSensor) {
121 registerSensor( new HardwareSensor(list[i]) );
122 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700123 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700124
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700125 // it's safe to instantiate the SensorFusion object here
126 // (it wants to be instantiated after h/w sensors have been
127 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700128 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700129
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700130 // build the sensor list returned to users
131 mUserSensorList = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700132
Aravind Akellaf5047892015-07-20 17:29:33 -0700133 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700134 // Add Android virtual sensors if they're not already
135 // available in the HAL
Peng Xuf66684a2015-07-23 11:41:53 -0700136 Sensor aSensor;
Mathias Agopian03193062013-05-10 19:32:39 -0700137
138 aSensor = registerVirtualSensor( new RotationVectorSensor() );
139 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
140 mUserSensorList.add(aSensor);
141 }
142
Mathias Agopian03193062013-05-10 19:32:39 -0700143 aSensor = registerVirtualSensor( new OrientationSensor() );
144 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) {
145 // if we are doing our own rotation-vector, also add
146 // the orientation sensor and remove the HAL provided one.
147 mUserSensorList.replaceAt(aSensor, orientationIndex);
148 }
149
Peng Xuf66684a2015-07-23 11:41:53 -0700150 aSensor = registerVirtualSensor(
151 new LinearAccelerationSensor(list, count) );
152 if (virtualSensorsNeeds &
153 (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) {
154 mUserSensorList.add(aSensor);
155 }
156
Mathias Agopian33264862012-06-28 19:46:54 -0700157 // virtual debugging sensors are not added to mUserSensorList
Mathias Agopian03193062013-05-10 19:32:39 -0700158 registerVirtualSensor( new CorrectedGyroSensor(list, count) );
Mathias Agopian33264862012-06-28 19:46:54 -0700159 registerVirtualSensor( new GyroDriftSensor() );
160 }
161
Peng Xuf66684a2015-07-23 11:41:53 -0700162 if (hasAccel && hasGyro) {
163 Sensor aSensor;
164
165 aSensor = registerVirtualSensor(
166 new GravitySensor(list, count) );
167 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) {
168 mUserSensorList.add(aSensor);
169 }
170
171 aSensor = registerVirtualSensor(
172 new GameRotationVectorSensor() );
173 if (virtualSensorsNeeds &
174 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) {
175 mUserSensorList.add(aSensor);
176 }
177 }
178
179 if (hasAccel && hasMag) {
180 Sensor aSensor;
181
182 aSensor = registerVirtualSensor(
183 new GeoMagRotationVectorSensor() );
184 if (virtualSensorsNeeds &
185 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) {
186 mUserSensorList.add(aSensor);
187 }
188 }
189
Mathias Agopian33264862012-06-28 19:46:54 -0700190 // debugging sensor list
Mathias Agopian03193062013-05-10 19:32:39 -0700191 mUserSensorListDebug = mSensorList;
Mathias Agopian33264862012-06-28 19:46:54 -0700192
Aravind Akella5466c3d2014-08-22 16:11:10 -0700193 // Check if the device really supports batching by looking at the FIFO event
194 // counts for each sensor.
195 bool batchingSupported = false;
Svetoslavb412f6e2015-04-29 16:50:41 -0700196 for (size_t i = 0; i < mSensorList.size(); ++i) {
Aravind Akella5466c3d2014-08-22 16:11:10 -0700197 if (mSensorList[i].getFifoMaxEventCount() > 0) {
198 batchingSupported = true;
199 break;
200 }
201 }
202
203 if (batchingSupported) {
204 // Increase socket buffer size to a max of 100 KB for batching capabilities.
205 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
206 } else {
207 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
208 }
209
210 // Compare the socketBufferSize value against the system limits and limit
211 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700212 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
213 char line[128];
214 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
215 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700216 size_t maxSystemSocketBufferSize;
217 sscanf(line, "%zu", &maxSystemSocketBufferSize);
218 if (mSocketBufferSize > maxSystemSocketBufferSize) {
219 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700220 }
221 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700222 if (fp) {
223 fclose(fp);
224 }
225
Aravind Akella9a844cf2014-02-11 18:58:52 -0800226 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700227 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700228 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
229 mSensorEventBuffer = new sensors_event_t[minBufferSize];
230 mSensorEventScratch = new sensors_event_t[minBufferSize];
231 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700232 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700233
Aravind Akella18d6d512015-06-18 14:18:28 -0700234 mNextSensorRegIndex = 0;
235 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
236 mLastNSensorRegistrations.push();
237 }
238
239 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700240 mAckReceiver = new SensorEventAckReceiver(this);
241 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700242 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700243 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700244 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700245}
246
Mathias Agopian03193062013-05-10 19:32:39 -0700247Sensor SensorService::registerSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800248{
Mathias Agopianf001c922010-11-11 17:58:51 -0800249 const Sensor sensor(s->getSensor());
250 // 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 Xu2576cb62016-01-20 00:22:09 -0800260Sensor SensorService::registerDynamicSensor(SensorInterface* s)
261{
262 Sensor sensor = registerSensor(s);
263 mDynamicSensorList.add(sensor);
264 return sensor;
265}
266
267bool SensorService::unregisterDynamicSensor(int handle) {
268 bool found = false;
269
270 for (size_t i=0 ; i<mSensorList.size() ; i++) {
271 if (mSensorList[i].getHandle() == handle) {
272 mSensorList.removeAt(i);
273 found = true;
274 break;
275 }
276 }
277
278 if (found) {
279 for (size_t i=0 ; i<mDynamicSensorList.size() ; i++) {
280 if (mDynamicSensorList[i].getHandle() == handle) {
281 mDynamicSensorList.removeAt(i);
282 }
283 }
284
285 mSensorMap.removeItem(handle);
286 mLastEventSeen.removeItem(handle);
287 }
288 return found;
289}
290
Mathias Agopian03193062013-05-10 19:32:39 -0700291Sensor SensorService::registerVirtualSensor(SensorInterface* s)
Mathias Agopianf001c922010-11-11 17:58:51 -0800292{
Mathias Agopian03193062013-05-10 19:32:39 -0700293 Sensor sensor = registerSensor(s);
Mathias Agopianf001c922010-11-11 17:58:51 -0800294 mVirtualSensorList.add( s );
Mathias Agopian03193062013-05-10 19:32:39 -0700295 return sensor;
Mathias Agopianf001c922010-11-11 17:58:51 -0800296}
297
Mathias Agopianfc328812010-07-14 23:41:37 -0700298SensorService::~SensorService()
299{
Mathias Agopianf001c922010-11-11 17:58:51 -0800300 for (size_t i=0 ; i<mSensorMap.size() ; i++)
301 delete mSensorMap.valueAt(i);
Mathias Agopianfc328812010-07-14 23:41:37 -0700302}
303
Aravind Akella4949c502015-02-11 15:54:35 -0800304status_t SensorService::dump(int fd, const Vector<String16>& args)
Mathias Agopianfc328812010-07-14 23:41:37 -0700305{
Mathias Agopianfc328812010-07-14 23:41:37 -0700306 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700307 if (!PermissionCache::checkCallingPermission(sDump)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800308 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700309 IPCThreadState::self()->getCallingPid(),
310 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700311 } else {
Aravind Akella841a5922015-06-29 12:37:48 -0700312 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800313 return INVALID_OPERATION;
314 }
315 Mutex::Autolock _l(mLock);
316 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700317 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700318 // If already in restricted mode. Ignore.
319 if (mCurrentOperatingMode == RESTRICTED) {
320 return status_t(NO_ERROR);
321 }
322 // If in any mode other than normal, ignore.
323 if (mCurrentOperatingMode != NORMAL) {
324 return INVALID_OPERATION;
325 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700326 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800327 dev.disableAllSensors();
328 // Clear all pending flush connections for all active sensors. If one of the active
329 // connections has called flush() and the underlying sensor has been disabled before a
330 // flush complete event is returned, we need to remove the connection from this queue.
331 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
332 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
333 }
Aravind Akella841a5922015-06-29 12:37:48 -0700334 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700335 return status_t(NO_ERROR);
336 } else if (args.size() == 1 && args[0] == String16("enable")) {
337 // If currently in restricted mode, reset back to NORMAL mode else ignore.
338 if (mCurrentOperatingMode == RESTRICTED) {
339 mCurrentOperatingMode = NORMAL;
340 dev.enableAllSensors();
341 }
Aravind Akella841a5922015-06-29 12:37:48 -0700342 if (mCurrentOperatingMode == DATA_INJECTION) {
343 resetToNormalModeLocked();
344 }
345 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700346 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700347 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
348 if (mCurrentOperatingMode == NORMAL) {
349 dev.disableAllSensors();
350 status_t err = dev.setMode(DATA_INJECTION);
351 if (err == NO_ERROR) {
352 mCurrentOperatingMode = DATA_INJECTION;
353 } else {
354 // Re-enable sensors.
355 dev.enableAllSensors();
356 }
357 mWhiteListedPackage.setTo(String8(args[1]));
358 return NO_ERROR;
359 } else if (mCurrentOperatingMode == DATA_INJECTION) {
360 // Already in DATA_INJECTION mode. Treat this as a no_op.
361 return NO_ERROR;
362 } else {
363 // Transition to data injection mode supported only from NORMAL mode.
364 return INVALID_OPERATION;
365 }
Aravind Akellaee155ca2015-06-24 08:31:32 -0700366 } else if (mSensorList.size() == 0) {
367 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700368 } else {
369 // Default dump the sensor list and debugging information.
370 result.append("Sensor List:\n");
371 for (size_t i=0 ; i<mSensorList.size() ; i++) {
372 const Sensor& s(mSensorList[i]);
373 result.appendFormat(
374 "%-15s| %-10s| version=%d |%-20s| 0x%08x | \"%s\" | type=%d |",
375 s.getName().string(),
376 s.getVendor().string(),
377 s.getVersion(),
378 s.getStringType().string(),
379 s.getHandle(),
380 s.getRequiredPermission().string(),
381 s.getType());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700382
Aravind Akella444f2672015-05-07 12:40:52 -0700383 const int reportingMode = s.getReportingMode();
384 if (reportingMode == AREPORTING_MODE_CONTINUOUS) {
385 result.append(" continuous | ");
386 } else if (reportingMode == AREPORTING_MODE_ON_CHANGE) {
387 result.append(" on-change | ");
388 } else if (reportingMode == AREPORTING_MODE_ONE_SHOT) {
389 result.append(" one-shot | ");
390 } else {
391 result.append(" special-trigger | ");
392 }
393
394 if (s.getMaxDelay() > 0) {
395 result.appendFormat("minRate=%.2fHz | ", 1e6f / s.getMaxDelay());
396 } else {
397 result.appendFormat("maxDelay=%dus |", s.getMaxDelay());
398 }
399
400 if (s.getMinDelay() > 0) {
401 result.appendFormat("maxRate=%.2fHz | ", 1e6f / s.getMinDelay());
402 } else {
403 result.appendFormat("minDelay=%dus |", s.getMinDelay());
404 }
405
406 if (s.getFifoMaxEventCount() > 0) {
407 result.appendFormat("FifoMax=%d events | ",
408 s.getFifoMaxEventCount());
409 } else {
410 result.append("no batching | ");
411 }
412
413 if (s.isWakeUpSensor()) {
414 result.appendFormat("wakeUp | ");
415 } else {
416 result.appendFormat("non-wakeUp | ");
417 }
418
Aravind Akella18d6d512015-06-18 14:18:28 -0700419 int bufIndex = mLastEventSeen.indexOfKey(s.getHandle());
420 if (bufIndex >= 0) {
Peng Xueb4d6282015-12-10 18:02:41 -0800421 const MostRecentEventLogger* buf = mLastEventSeen.valueAt(bufIndex);
Aravind Akella18d6d512015-06-18 14:18:28 -0700422 if (buf != NULL && s.getRequiredPermission().isEmpty()) {
423 buf->printBuffer(result);
424 } else {
425 result.append("last=<> \n");
426 }
Aravind Akella444f2672015-05-07 12:40:52 -0700427 }
428 result.append("\n");
429 }
430 SensorFusion::getInstance().dump(result);
431 SensorDevice::getInstance().dump(result);
432
433 result.append("Active sensors:\n");
434 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
435 int handle = mActiveSensors.keyAt(i);
436 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
437 getSensorName(handle).string(),
438 handle,
439 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700440 }
441
Andreas Gamped4036b62015-07-28 13:49:04 -0700442 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700443 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700444 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
445 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700446 result.appendFormat("Mode :");
447 switch(mCurrentOperatingMode) {
448 case NORMAL:
449 result.appendFormat(" NORMAL\n");
450 break;
451 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700452 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700453 break;
454 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700455 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700456 }
Aravind Akella444f2672015-05-07 12:40:52 -0700457 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700458
Aravind Akella444f2672015-05-07 12:40:52 -0700459 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
460 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
461 if (connection != 0) {
462 result.appendFormat("Connection Number: %zu \n", i);
463 connection->dump(result);
464 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700465 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700466
467 result.appendFormat("Previous Registrations:\n");
468 // Log in the reverse chronological order.
469 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
470 SENSOR_REGISTRATIONS_BUF_SIZE;
471 const int startIndex = currentIndex;
472 do {
473 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
474 if (SensorRegistrationInfo::isSentinel(reg_info)) {
475 // Ignore sentinel, proceed to next item.
476 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
477 SENSOR_REGISTRATIONS_BUF_SIZE;
478 continue;
479 }
480 if (reg_info.mActivated) {
481 result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x "
482 "samplingRate=%dus maxReportLatency=%dus\n",
483 reg_info.mHour, reg_info.mMin, reg_info.mSec,
484 reg_info.mPackageName.string(), reg_info.mSensorHandle,
485 reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs);
486 } else {
487 result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n",
488 reg_info.mHour, reg_info.mMin, reg_info.mSec,
489 reg_info.mPackageName.string(), reg_info.mSensorHandle);
490 }
491 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
492 SENSOR_REGISTRATIONS_BUF_SIZE;
493 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700494 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700495 }
496 write(fd, result.string(), result.size());
497 return NO_ERROR;
498}
499
Aravind Akella9a844cf2014-02-11 18:58:52 -0800500void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700501 sensors_event_t const* buffer, const int count) {
502 for (int i=0 ; i<count ; i++) {
503 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700504 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
505 handle = buffer[i].meta_data.sensor;
506 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700507 if (connection->hasSensor(handle)) {
508 SensorInterface* sensor = mSensorMap.valueFor(handle);
509 // If this buffer has an event from a one_shot sensor and this connection is registered
510 // for this particular one_shot sensor, try cleaning up the connection.
511 if (sensor != NULL &&
512 sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
513 sensor->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800514 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700515 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700516
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700517 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700518 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700519}
520
Mathias Agopianfc328812010-07-14 23:41:37 -0700521bool SensorService::threadLoop()
522{
Steve Blocka5512372011-12-20 16:23:08 +0000523 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700524
Peng Xueb4d6282015-12-10 18:02:41 -0800525 // each virtual sensor could generate an event per "real" event, that's why we need to size
526 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
527 // aggressive, but guaranteed to be enough.
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700528 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
529 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
530
Mathias Agopianf001c922010-11-11 17:58:51 -0800531 SensorDevice& device(SensorDevice::getInstance());
532 const size_t vcount = mVirtualSensorList.size();
Mathias Agopianfc328812010-07-14 23:41:37 -0700533
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700534 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700535 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700536 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
537 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000538 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700539 break;
540 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700541
542 // Reset sensors_event_t.flags to zero for all events in the buffer.
543 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700544 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700545 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700546
Peng Xueb4d6282015-12-10 18:02:41 -0800547 // Make a copy of the connection vector as some connections may be removed during the course
548 // of this loop (especially when one-shot sensor events are present in the sensor_event
549 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
550 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
551 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
552 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700553 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700554 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800555
Aravind Akella9a844cf2014-02-11 18:58:52 -0800556 Mutex::Autolock _l(mLock);
557 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
558 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
559 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
560 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
561 // releasing the wakelock.
562 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700563 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700564 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800565 bufferHasWakeUpEvent = true;
566 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700567 }
568 }
569
Aravind Akella9a844cf2014-02-11 18:58:52 -0800570 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700571 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800572 }
Aravind Akella8493b792014-09-08 15:45:47 -0700573 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800574
Mathias Agopianf001c922010-11-11 17:58:51 -0800575 // handle virtual sensors
576 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700577 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800578 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800579 if (activeVirtualSensorCount) {
580 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700581 SensorFusion& fusion(SensorFusion::getInstance());
582 if (fusion.isEnabled()) {
583 for (size_t i=0 ; i<size_t(count) ; i++) {
584 fusion.process(event[i]);
585 }
586 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700587 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800588 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700589 if (count + k >= minBufferSize) {
590 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700591 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700592 count, k, minBufferSize);
593 break;
594 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800595 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800596 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700597 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700598 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800599 k++;
600 }
601 }
602 }
603 if (k) {
604 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700605 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800606 count += k;
607 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700608 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700609 }
610 }
611 }
612
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700613 // handle backward compatibility for RotationVector sensor
614 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
615 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700616 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700617 // All the 4 components of the quaternion should be available
618 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700619 mSensorEventBuffer[i].data[4] = -1;
620 }
621 }
622 }
623
Aravind Akella8493b792014-09-08 15:45:47 -0700624 for (int i = 0; i < count; ++i) {
Peng Xu2576cb62016-01-20 00:22:09 -0800625 // Map flush_complete_events in the buffer to SensorEventConnections which called flush on
626 // the hardware sensor. mapFlushEventsToConnections[i] will be the SensorEventConnection
627 // mapped to the corresponding flush_complete_event in mSensorEventBuffer[i] if such a
628 // mapping exists (NULL otherwise).
Aravind Akella8493b792014-09-08 15:45:47 -0700629 mMapFlushEventsToConnections[i] = NULL;
630 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
631 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
632 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
633 if (rec != NULL) {
634 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
635 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700636 }
637 }
Peng Xu2576cb62016-01-20 00:22:09 -0800638
639 // handle dynamic sensor meta events, process registration and unregistration of dynamic
640 // sensor based on content of event.
641 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
642 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
643 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
644 const sensor_t& dynamicSensor =
645 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
646 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
647 handle, dynamicSensor.type, dynamicSensor.name);
648
649 device.handleDynamicSensorConnection(handle, true /*connected*/);
650 registerDynamicSensor(new HardwareSensor(dynamicSensor));
651
652 } else {
653 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
654 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
655
656 device.handleDynamicSensorConnection(handle, false /*connected*/);
657 if (!unregisterDynamicSensor(handle)) {
658 ALOGE("Dynamic sensor release error.");
659 }
660
661 size_t numConnections = activeConnections.size();
662 for (size_t i=0 ; i < numConnections; ++i) {
663 if (activeConnections[i] != NULL) {
664 activeConnections[i]->removeSensor(handle);
665 }
666 }
667 }
668 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700669 }
670
Peng Xu2576cb62016-01-20 00:22:09 -0800671
Aravind Akella9a844cf2014-02-11 18:58:52 -0800672 // Send our events to clients. Check the state of wake lock for each client and release the
673 // lock if none of the clients need it.
674 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700675 size_t numConnections = activeConnections.size();
676 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700677 if (activeConnections[i] != 0) {
678 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700679 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700680 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700681 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
682 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700683 if (activeConnections[i]->hasOneShotSensors()) {
684 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
685 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700686 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800687 }
688 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700689
Aravind Akella9a844cf2014-02-11 18:58:52 -0800690 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700691 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800692 }
Aravind Akella8493b792014-09-08 15:45:47 -0700693 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700694
Steve Block3c20fbe2012-01-05 23:22:43 +0000695 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800696 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700697 return false;
698}
699
Aravind Akella56ae4262014-07-10 16:01:10 -0700700sp<Looper> SensorService::getLooper() const {
701 return mLooper;
702}
703
Aravind Akellab4373ac2014-10-29 17:55:20 -0700704void SensorService::resetAllWakeLockRefCounts() {
705 SortedVector< sp<SensorEventConnection> > activeConnections;
706 populateActiveConnections(&activeConnections);
707 {
708 Mutex::Autolock _l(mLock);
709 for (size_t i=0 ; i < activeConnections.size(); ++i) {
710 if (activeConnections[i] != 0) {
711 activeConnections[i]->resetWakeLockRefCount();
712 }
713 }
714 setWakeLockAcquiredLocked(false);
715 }
716}
717
718void SensorService::setWakeLockAcquiredLocked(bool acquire) {
719 if (acquire) {
720 if (!mWakeLockAcquired) {
721 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
722 mWakeLockAcquired = true;
723 }
724 mLooper->wake();
725 } else {
726 if (mWakeLockAcquired) {
727 release_wake_lock(WAKE_LOCK_NAME);
728 mWakeLockAcquired = false;
729 }
730 }
731}
732
Aravind Akellab4373ac2014-10-29 17:55:20 -0700733bool SensorService::isWakeLockAcquired() {
734 Mutex::Autolock _l(mLock);
735 return mWakeLockAcquired;
736}
737
Aravind Akella56ae4262014-07-10 16:01:10 -0700738bool SensorService::SensorEventAckReceiver::threadLoop() {
739 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700740 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700741 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700742 bool wakeLockAcquired = mService->isWakeLockAcquired();
743 int timeout = -1;
744 if (wakeLockAcquired) timeout = 5000;
745 int ret = looper->pollOnce(timeout);
746 if (ret == ALOOPER_POLL_TIMEOUT) {
747 mService->resetAllWakeLockRefCounts();
748 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700749 } while(!Thread::exitPending());
750 return false;
751}
752
Aravind Akella9a844cf2014-02-11 18:58:52 -0800753void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800754 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800755 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800756 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
757 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu9e720462016-01-26 18:48:54 -0800758 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO ||
Peng Xu2576cb62016-01-20 00:22:09 -0800759 mLastEventSeen.indexOfKey(buffer[i].sensor) <0 ) {
760 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800761 }
Peng Xu2576cb62016-01-20 00:22:09 -0800762
763 MostRecentEventLogger* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
764 if (circular_buf == NULL) {
765 circular_buf = new MostRecentEventLogger(buffer[i].type);
766 }
767 circular_buf->addEvent(buffer[i]);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800768 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800769}
770
Mathias Agopianf001c922010-11-11 17:58:51 -0800771void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
772{
773 struct compar {
774 static int cmp(void const* lhs, void const* rhs) {
775 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
776 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700777 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800778 }
779 };
780 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
781}
782
Mathias Agopian5d270722010-07-19 15:20:39 -0700783String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700784 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700785 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700786 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700787 if (sensor.getHandle() == handle) {
788 return sensor.getName();
789 }
790 }
791 String8 result("unknown");
792 return result;
793}
794
Aravind Akellab4099e72013-10-15 15:43:10 -0700795bool SensorService::isVirtualSensor(int handle) const {
796 SensorInterface* sensor = mSensorMap.valueFor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -0800797 return sensor != NULL && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700798}
799
Aravind Akella9a844cf2014-02-11 18:58:52 -0800800bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700801 int handle = event.sensor;
802 if (event.type == SENSOR_TYPE_META_DATA) {
803 handle = event.meta_data.sensor;
804 }
805 SensorInterface* sensor = mSensorMap.valueFor(handle);
806 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800807}
808
Aravind Akella6c2664a2014-08-13 12:24:50 -0700809SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
810 return mActiveSensors.valueFor(handle);
811}
812
Svetoslavb412f6e2015-04-29 16:50:41 -0700813Vector<Sensor> SensorService::getSensorList(const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700814{
Mathias Agopian33264862012-06-28 19:46:54 -0700815 char value[PROPERTY_VALUE_MAX];
816 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000817 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
818 mUserSensorListDebug : mUserSensorList;
819 Vector<Sensor> accessibleSensorList;
820 for (size_t i = 0; i < initialSensorList.size(); i++) {
821 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700822 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000823 accessibleSensorList.add(sensor);
824 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700825 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100826 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700827 sensor.getRequiredPermission().string(),
828 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000829 }
Mathias Agopian33264862012-06-28 19:46:54 -0700830 }
Aravind Akella70018042014-04-07 22:52:37 +0000831 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700832}
833
Peng Xu2576cb62016-01-20 00:22:09 -0800834Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName)
835{
836 Vector<Sensor> accessibleSensorList;
837 for (size_t i = 0; i < mDynamicSensorList.size(); i++) {
838 Sensor sensor = mDynamicSensorList[i];
839 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
840 accessibleSensorList.add(sensor);
841 } else {
842 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
843 sensor.getName().string(),
844 sensor.getRequiredPermission().string(),
845 sensor.getRequiredAppOp());
846 }
847 }
848 return accessibleSensorList;
849}
850
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700851sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700852 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700853 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
854 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
855 return NULL;
856 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700857
858 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700859 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
860 // operating in DI mode.
861 if (requestedMode == DATA_INJECTION) {
862 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
863 if (!isWhiteListedPackage(packageName)) return NULL;
864 }
865
Mathias Agopian5307d172012-09-18 17:02:43 -0700866 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700867 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700868 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700869 if (requestedMode == DATA_INJECTION) {
870 if (mActiveConnections.indexOf(result) < 0) {
871 mActiveConnections.add(result);
872 }
873 // Add the associated file descriptor to the Looper for polling whenever there is data to
874 // be injected.
875 result->updateLooperRegistration(mLooper);
876 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700877 return result;
878}
879
Aravind Akella841a5922015-06-29 12:37:48 -0700880int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700881 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700882 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700883}
884
885status_t SensorService::resetToNormalMode() {
886 Mutex::Autolock _l(mLock);
887 return resetToNormalModeLocked();
888}
889
890status_t SensorService::resetToNormalModeLocked() {
891 SensorDevice& dev(SensorDevice::getInstance());
892 dev.enableAllSensors();
893 status_t err = dev.setMode(NORMAL);
894 mCurrentOperatingMode = NORMAL;
895 return err;
896}
897
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800898void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700899{
900 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800901 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700902 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700903 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700904 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800905 int handle = mActiveSensors.keyAt(i);
906 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700907 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800908 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000909 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800910 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800911 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800912 }
Aravind Akella8a969552014-09-28 17:52:41 -0700913 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800914 }
915 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700916 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000917 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700918 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700919 c, i, handle);
920
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800921 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000922 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700923 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800924 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700925 delete rec;
926 size--;
927 } else {
928 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700929 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700930 }
Aravind Akella8a969552014-09-28 17:52:41 -0700931 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700932 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700933 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800934 if (c->needsWakeLock()) {
935 checkWakeLockStateLocked();
936 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700937}
938
Aravind Akella70018042014-04-07 22:52:37 +0000939Sensor SensorService::getSensorFromHandle(int handle) const {
940 return mSensorMap.valueFor(handle)->getSensor();
941}
942
Mathias Agopianfc328812010-07-14 23:41:37 -0700943status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700944 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
945 const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700946{
Mathias Agopian50df2952010-07-19 19:09:10 -0700947 if (mInitCheck != NO_ERROR)
948 return mInitCheck;
949
Mathias Agopianf001c922010-11-11 17:58:51 -0800950 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700951 if (sensor == NULL) {
952 return BAD_VALUE;
953 }
Aravind Akella70018042014-04-07 22:52:37 +0000954
Svetoslavb412f6e2015-04-29 16:50:41 -0700955 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000956 return BAD_VALUE;
957 }
958
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700959 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700960 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
961 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800962 return INVALID_OPERATION;
963 }
964
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700965 SensorRecord* rec = mActiveSensors.valueFor(handle);
966 if (rec == 0) {
967 rec = new SensorRecord(connection);
968 mActiveSensors.add(handle, rec);
969 if (sensor->isVirtual()) {
970 mActiveVirtualSensors.add(handle, sensor);
971 }
972 } else {
973 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800974 // this sensor is already activated, but we are adding a connection that uses it.
975 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700976 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700977 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800978 // NOTE: The wake_up flag of this event may get set to
979 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xueb4d6282015-12-10 18:02:41 -0800980 MostRecentEventLogger *circular_buf = mLastEventSeen.valueFor(handle);
Aravind Akella444f2672015-05-07 12:40:52 -0700981 if (circular_buf) {
982 sensors_event_t event;
983 memset(&event, 0, sizeof(event));
984 // It is unlikely that this buffer is empty as the sensor is already active.
985 // One possible corner case may be two applications activating an on-change
986 // sensor at the same time.
987 if(circular_buf->populateLastEvent(&event)) {
988 event.sensor = handle;
989 if (event.version == sizeof(sensors_event_t)) {
990 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
991 setWakeLockAcquiredLocked(true);
992 }
993 connection->sendEvents(&event, 1, NULL);
994 if (!connection->needsWakeLock() && mWakeLockAcquired) {
995 checkWakeLockStateLocked();
996 }
997 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800998 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700999 }
1000 }
1001 }
1002 }
1003
1004 if (connection->addSensor(handle)) {
1005 BatteryService::enableSensor(connection->getUid(), handle);
1006 // the sensor was added (which means it wasn't already there)
1007 // so, see if this connection becomes active
1008 if (mActiveConnections.indexOf(connection) < 0) {
1009 mActiveConnections.add(connection);
1010 }
1011 } else {
1012 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1013 handle, connection.get());
1014 }
1015
Aravind Akella724d91d2013-06-27 12:04:23 -07001016 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1017 if (samplingPeriodNs < minDelayNs) {
1018 samplingPeriodNs = minDelayNs;
1019 }
1020
Aravind Akella6c2664a2014-08-13 12:24:50 -07001021 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1022 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001023 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1024
Aravind Akella4949c502015-02-11 15:54:35 -08001025 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001026 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001027
Peng Xu20483c42015-10-26 15:14:43 -07001028 // Call flush() before calling activate() on the sensor. Wait for a first
1029 // flush complete event before sending events on this connection. Ignore
1030 // one-shot sensors which don't support flush(). Ignore on-change sensors
1031 // to maintain the on-change logic (any on-change events except the initial
1032 // one should be trigger by a change in value). Also if this sensor isn't
1033 // already active, don't call flush().
1034 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001035 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001036 rec->getNumConnections() > 1) {
1037 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001038 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001039 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001040 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001041 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001042 } else {
1043 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001044 }
1045 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001046
1047 if (err == NO_ERROR) {
1048 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1049 err = sensor->activate(connection.get(), true);
1050 }
1051
Aravind Akella8a969552014-09-28 17:52:41 -07001052 if (err == NO_ERROR) {
1053 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -07001054 SensorRegistrationInfo &reg_info =
1055 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1056 reg_info.mSensorHandle = handle;
1057 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
1058 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
1059 reg_info.mActivated = true;
1060 reg_info.mPackageName = connection->getPackageName();
1061 time_t rawtime = time(NULL);
1062 struct tm * timeinfo = localtime(&rawtime);
1063 reg_info.mHour = timeinfo->tm_hour;
1064 reg_info.mMin = timeinfo->tm_min;
1065 reg_info.mSec = timeinfo->tm_sec;
1066 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001067 }
1068
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001069 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001070 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001071 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001072 }
1073 return err;
1074}
1075
1076status_t SensorService::disable(const sp<SensorEventConnection>& connection,
1077 int handle)
1078{
Mathias Agopian50df2952010-07-19 19:09:10 -07001079 if (mInitCheck != NO_ERROR)
1080 return mInitCheck;
1081
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001082 Mutex::Autolock _l(mLock);
1083 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001084 if (err == NO_ERROR) {
1085 SensorInterface* sensor = mSensorMap.valueFor(handle);
1086 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001087
1088 }
1089 if (err == NO_ERROR) {
1090 SensorRegistrationInfo &reg_info =
1091 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1092 reg_info.mActivated = false;
1093 reg_info.mPackageName= connection->getPackageName();
1094 reg_info.mSensorHandle = handle;
1095 time_t rawtime = time(NULL);
1096 struct tm * timeinfo = localtime(&rawtime);
1097 reg_info.mHour = timeinfo->tm_hour;
1098 reg_info.mMin = timeinfo->tm_min;
1099 reg_info.mSec = timeinfo->tm_sec;
1100 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001101 }
1102 return err;
1103}
1104
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001105status_t SensorService::cleanupWithoutDisable(
1106 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001107 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001108 return cleanupWithoutDisableLocked(connection, handle);
1109}
1110
1111status_t SensorService::cleanupWithoutDisableLocked(
1112 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001113 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001114 if (rec) {
1115 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001116 if (connection->removeSensor(handle)) {
1117 BatteryService::disableSensor(connection->getUid(), handle);
1118 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001119 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001120 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001121 mActiveConnections.remove(connection);
1122 }
1123 // see if this sensor becomes inactive
1124 if (rec->removeConnection(connection)) {
1125 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001126 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001127 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001128 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001129 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001130 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001131 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001132}
1133
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001134status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001135 int handle, nsecs_t ns, const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -07001136{
Mathias Agopian50df2952010-07-19 19:09:10 -07001137 if (mInitCheck != NO_ERROR)
1138 return mInitCheck;
1139
Mathias Agopianae09d652011-11-01 17:37:49 -07001140 SensorInterface* sensor = mSensorMap.valueFor(handle);
1141 if (!sensor)
1142 return BAD_VALUE;
1143
Svetoslavb412f6e2015-04-29 16:50:41 -07001144 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001145 return BAD_VALUE;
1146 }
1147
Mathias Agopian1cd70002010-07-21 15:59:50 -07001148 if (ns < 0)
1149 return BAD_VALUE;
1150
Mathias Agopian62569ec2011-11-07 21:21:47 -08001151 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1152 if (ns < minDelayNs) {
1153 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001154 }
1155
Mathias Agopianf001c922010-11-11 17:58:51 -08001156 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001157}
1158
Svetoslavb412f6e2015-04-29 16:50:41 -07001159status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1160 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001161 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001162 SensorDevice& dev(SensorDevice::getInstance());
1163 const int halVersion = dev.getHalDeviceVersion();
1164 status_t err(NO_ERROR);
1165 Mutex::Autolock _l(mLock);
1166 // Loop through all sensors for this connection and call flush on each of them.
1167 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1168 const int handle = connection->mSensorInfo.keyAt(i);
1169 SensorInterface* sensor = mSensorMap.valueFor(handle);
1170 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1171 ALOGE("flush called on a one-shot sensor");
1172 err = INVALID_OPERATION;
1173 continue;
1174 }
Aravind Akella8493b792014-09-08 15:45:47 -07001175 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001176 // For older devices just increment pending flush count which will send a trivial
1177 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001178 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001179 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001180 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1181 err = INVALID_OPERATION;
1182 continue;
1183 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001184 status_t err_flush = sensor->flush(connection.get(), handle);
1185 if (err_flush == NO_ERROR) {
1186 SensorRecord* rec = mActiveSensors.valueFor(handle);
1187 if (rec != NULL) rec->addPendingFlushConnection(connection);
1188 }
1189 err = (err_flush != NO_ERROR) ? err_flush : err;
1190 }
Aravind Akella70018042014-04-07 22:52:37 +00001191 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001192 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001193}
Aravind Akella70018042014-04-07 22:52:37 +00001194
Svetoslavb412f6e2015-04-29 16:50:41 -07001195bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1196 const String16& opPackageName) {
1197 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001198
Svetoslavb412f6e2015-04-29 16:50:41 -07001199 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001200 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001201 }
1202
1203 bool hasPermission = false;
1204
1205 // Runtime permissions can't use the cache as they may change.
1206 if (sensor.isRequiredPermissionRuntime()) {
1207 hasPermission = checkPermission(String16(requiredPermission),
1208 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001209 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001210 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1211 }
1212
1213 if (!hasPermission) {
1214 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1215 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001216 return false;
1217 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001218
1219 const int32_t opCode = sensor.getRequiredAppOp();
1220 if (opCode >= 0) {
1221 AppOpsManager appOps;
1222 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1223 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001224 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001225 operation, sensor.getName().string(), opCode);
1226 return false;
1227 }
1228 }
1229
1230 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001231}
1232
Aravind Akella9a844cf2014-02-11 18:58:52 -08001233void SensorService::checkWakeLockState() {
1234 Mutex::Autolock _l(mLock);
1235 checkWakeLockStateLocked();
1236}
1237
1238void SensorService::checkWakeLockStateLocked() {
1239 if (!mWakeLockAcquired) {
1240 return;
1241 }
1242 bool releaseLock = true;
1243 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1244 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1245 if (connection != 0) {
1246 if (connection->needsWakeLock()) {
1247 releaseLock = false;
1248 break;
1249 }
1250 }
1251 }
1252 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001253 setWakeLockAcquiredLocked(false);
1254 }
1255}
1256
1257void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1258 Mutex::Autolock _l(mLock);
1259 connection->writeToSocketFromCache();
1260 if (connection->needsWakeLock()) {
1261 setWakeLockAcquiredLocked(true);
1262 }
1263}
1264
1265void SensorService::populateActiveConnections(
1266 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1267 Mutex::Autolock _l(mLock);
1268 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1269 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1270 if (connection != 0) {
1271 activeConnections->add(connection);
1272 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001273 }
1274}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001275
Aravind Akella4949c502015-02-11 15:54:35 -08001276bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001277 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001278}
1279
Aravind Akella444f2672015-05-07 12:40:52 -07001280int SensorService::getNumEventsForSensorType(int sensor_event_type) {
1281 switch (sensor_event_type) {
1282 case SENSOR_TYPE_ROTATION_VECTOR:
1283 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1284 return 5;
1285
1286 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1287 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1288 return 6;
1289
1290 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1291 return 4;
1292
1293 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1294 case SENSOR_TYPE_STEP_DETECTOR:
1295 case SENSOR_TYPE_STEP_COUNTER:
1296 return 1;
1297
1298 default:
1299 return 3;
1300 }
1301}
1302
Mathias Agopianfc328812010-07-14 23:41:37 -07001303}; // namespace android
1304