blob: 9f8c21bf04c5bf544d8fb3f6a758592ae158296a [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 ||
758 mLastEventSeen.indexOfKey(buffer[i].sensor) <0 ) {
759 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800760 }
Peng Xu2576cb62016-01-20 00:22:09 -0800761
762 MostRecentEventLogger* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
763 if (circular_buf == NULL) {
764 circular_buf = new MostRecentEventLogger(buffer[i].type);
765 }
766 circular_buf->addEvent(buffer[i]);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800767 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800768}
769
Mathias Agopianf001c922010-11-11 17:58:51 -0800770void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count)
771{
772 struct compar {
773 static int cmp(void const* lhs, void const* rhs) {
774 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
775 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700776 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800777 }
778 };
779 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
780}
781
Mathias Agopian5d270722010-07-19 15:20:39 -0700782String8 SensorService::getSensorName(int handle) const {
Mathias Agopian010e4222011-06-08 20:06:50 -0700783 size_t count = mUserSensorList.size();
Mathias Agopian5d270722010-07-19 15:20:39 -0700784 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian010e4222011-06-08 20:06:50 -0700785 const Sensor& sensor(mUserSensorList[i]);
Mathias Agopian5d270722010-07-19 15:20:39 -0700786 if (sensor.getHandle() == handle) {
787 return sensor.getName();
788 }
789 }
790 String8 result("unknown");
791 return result;
792}
793
Aravind Akellab4099e72013-10-15 15:43:10 -0700794bool SensorService::isVirtualSensor(int handle) const {
795 SensorInterface* sensor = mSensorMap.valueFor(handle);
Peng Xu2576cb62016-01-20 00:22:09 -0800796 return sensor != NULL && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700797}
798
Aravind Akella9a844cf2014-02-11 18:58:52 -0800799bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700800 int handle = event.sensor;
801 if (event.type == SENSOR_TYPE_META_DATA) {
802 handle = event.meta_data.sensor;
803 }
804 SensorInterface* sensor = mSensorMap.valueFor(handle);
805 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800806}
807
Aravind Akella6c2664a2014-08-13 12:24:50 -0700808SensorService::SensorRecord * SensorService::getSensorRecord(int handle) {
809 return mActiveSensors.valueFor(handle);
810}
811
Svetoslavb412f6e2015-04-29 16:50:41 -0700812Vector<Sensor> SensorService::getSensorList(const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700813{
Mathias Agopian33264862012-06-28 19:46:54 -0700814 char value[PROPERTY_VALUE_MAX];
815 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000816 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
817 mUserSensorListDebug : mUserSensorList;
818 Vector<Sensor> accessibleSensorList;
819 for (size_t i = 0; i < initialSensorList.size(); i++) {
820 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700821 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000822 accessibleSensorList.add(sensor);
823 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700824 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100825 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700826 sensor.getRequiredPermission().string(),
827 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000828 }
Mathias Agopian33264862012-06-28 19:46:54 -0700829 }
Aravind Akella70018042014-04-07 22:52:37 +0000830 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700831}
832
Peng Xu2576cb62016-01-20 00:22:09 -0800833Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName)
834{
835 Vector<Sensor> accessibleSensorList;
836 for (size_t i = 0; i < mDynamicSensorList.size(); i++) {
837 Sensor sensor = mDynamicSensorList[i];
838 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
839 accessibleSensorList.add(sensor);
840 } else {
841 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
842 sensor.getName().string(),
843 sensor.getRequiredPermission().string(),
844 sensor.getRequiredAppOp());
845 }
846 }
847 return accessibleSensorList;
848}
849
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700850sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700851 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700852 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
853 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
854 return NULL;
855 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700856
857 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700858 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
859 // operating in DI mode.
860 if (requestedMode == DATA_INJECTION) {
861 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
862 if (!isWhiteListedPackage(packageName)) return NULL;
863 }
864
Mathias Agopian5307d172012-09-18 17:02:43 -0700865 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700866 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700867 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700868 if (requestedMode == DATA_INJECTION) {
869 if (mActiveConnections.indexOf(result) < 0) {
870 mActiveConnections.add(result);
871 }
872 // Add the associated file descriptor to the Looper for polling whenever there is data to
873 // be injected.
874 result->updateLooperRegistration(mLooper);
875 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700876 return result;
877}
878
Aravind Akella841a5922015-06-29 12:37:48 -0700879int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700880 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700881 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700882}
883
884status_t SensorService::resetToNormalMode() {
885 Mutex::Autolock _l(mLock);
886 return resetToNormalModeLocked();
887}
888
889status_t SensorService::resetToNormalModeLocked() {
890 SensorDevice& dev(SensorDevice::getInstance());
891 dev.enableAllSensors();
892 status_t err = dev.setMode(NORMAL);
893 mCurrentOperatingMode = NORMAL;
894 return err;
895}
896
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800897void SensorService::cleanupConnection(SensorEventConnection* c)
Mathias Agopianfc328812010-07-14 23:41:37 -0700898{
899 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800900 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700901 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700902 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700903 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800904 int handle = mActiveSensors.keyAt(i);
905 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700906 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800907 SensorInterface* sensor = mSensorMap.valueFor( handle );
Steve Blockf5a12302012-01-06 19:20:56 +0000908 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800909 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800910 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800911 }
Aravind Akella8a969552014-09-28 17:52:41 -0700912 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800913 }
914 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700915 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000916 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700917 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700918 c, i, handle);
919
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800920 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000921 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700922 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800923 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700924 delete rec;
925 size--;
926 } else {
927 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700928 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700929 }
Aravind Akella8a969552014-09-28 17:52:41 -0700930 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700931 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700932 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800933 if (c->needsWakeLock()) {
934 checkWakeLockStateLocked();
935 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700936}
937
Aravind Akella70018042014-04-07 22:52:37 +0000938Sensor SensorService::getSensorFromHandle(int handle) const {
939 return mSensorMap.valueFor(handle)->getSensor();
940}
941
Mathias Agopianfc328812010-07-14 23:41:37 -0700942status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700943 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
944 const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -0700945{
Mathias Agopian50df2952010-07-19 19:09:10 -0700946 if (mInitCheck != NO_ERROR)
947 return mInitCheck;
948
Mathias Agopianf001c922010-11-11 17:58:51 -0800949 SensorInterface* sensor = mSensorMap.valueFor(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700950 if (sensor == NULL) {
951 return BAD_VALUE;
952 }
Aravind Akella70018042014-04-07 22:52:37 +0000953
Svetoslavb412f6e2015-04-29 16:50:41 -0700954 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000955 return BAD_VALUE;
956 }
957
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700958 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700959 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
960 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800961 return INVALID_OPERATION;
962 }
963
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700964 SensorRecord* rec = mActiveSensors.valueFor(handle);
965 if (rec == 0) {
966 rec = new SensorRecord(connection);
967 mActiveSensors.add(handle, rec);
968 if (sensor->isVirtual()) {
969 mActiveVirtualSensors.add(handle, sensor);
970 }
971 } else {
972 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800973 // this sensor is already activated, but we are adding a connection that uses it.
974 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700975 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700976 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800977 // NOTE: The wake_up flag of this event may get set to
978 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xueb4d6282015-12-10 18:02:41 -0800979 MostRecentEventLogger *circular_buf = mLastEventSeen.valueFor(handle);
Aravind Akella444f2672015-05-07 12:40:52 -0700980 if (circular_buf) {
981 sensors_event_t event;
982 memset(&event, 0, sizeof(event));
983 // It is unlikely that this buffer is empty as the sensor is already active.
984 // One possible corner case may be two applications activating an on-change
985 // sensor at the same time.
986 if(circular_buf->populateLastEvent(&event)) {
987 event.sensor = handle;
988 if (event.version == sizeof(sensors_event_t)) {
989 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
990 setWakeLockAcquiredLocked(true);
991 }
992 connection->sendEvents(&event, 1, NULL);
993 if (!connection->needsWakeLock() && mWakeLockAcquired) {
994 checkWakeLockStateLocked();
995 }
996 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800997 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700998 }
999 }
1000 }
1001 }
1002
1003 if (connection->addSensor(handle)) {
1004 BatteryService::enableSensor(connection->getUid(), handle);
1005 // the sensor was added (which means it wasn't already there)
1006 // so, see if this connection becomes active
1007 if (mActiveConnections.indexOf(connection) < 0) {
1008 mActiveConnections.add(connection);
1009 }
1010 } else {
1011 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
1012 handle, connection.get());
1013 }
1014
Aravind Akella724d91d2013-06-27 12:04:23 -07001015 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1016 if (samplingPeriodNs < minDelayNs) {
1017 samplingPeriodNs = minDelayNs;
1018 }
1019
Aravind Akella6c2664a2014-08-13 12:24:50 -07001020 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
1021 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -07001022 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
1023
Aravind Akella4949c502015-02-11 15:54:35 -08001024 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -07001025 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -07001026
Peng Xu20483c42015-10-26 15:14:43 -07001027 // Call flush() before calling activate() on the sensor. Wait for a first
1028 // flush complete event before sending events on this connection. Ignore
1029 // one-shot sensors which don't support flush(). Ignore on-change sensors
1030 // to maintain the on-change logic (any on-change events except the initial
1031 // one should be trigger by a change in value). Also if this sensor isn't
1032 // already active, don't call flush().
1033 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -08001034 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -07001035 rec->getNumConnections() > 1) {
1036 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001037 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -07001038 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -07001039 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -07001040 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -07001041 } else {
1042 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -07001043 }
1044 }
Aravind Akella724d91d2013-06-27 12:04:23 -07001045
1046 if (err == NO_ERROR) {
1047 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
1048 err = sensor->activate(connection.get(), true);
1049 }
1050
Aravind Akella8a969552014-09-28 17:52:41 -07001051 if (err == NO_ERROR) {
1052 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -07001053 SensorRegistrationInfo &reg_info =
1054 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1055 reg_info.mSensorHandle = handle;
1056 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
1057 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
1058 reg_info.mActivated = true;
1059 reg_info.mPackageName = connection->getPackageName();
1060 time_t rawtime = time(NULL);
1061 struct tm * timeinfo = localtime(&rawtime);
1062 reg_info.mHour = timeinfo->tm_hour;
1063 reg_info.mMin = timeinfo->tm_min;
1064 reg_info.mSec = timeinfo->tm_sec;
1065 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -07001066 }
1067
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001068 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -07001069 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001070 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001071 }
1072 return err;
1073}
1074
1075status_t SensorService::disable(const sp<SensorEventConnection>& connection,
1076 int handle)
1077{
Mathias Agopian50df2952010-07-19 19:09:10 -07001078 if (mInitCheck != NO_ERROR)
1079 return mInitCheck;
1080
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001081 Mutex::Autolock _l(mLock);
1082 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001083 if (err == NO_ERROR) {
1084 SensorInterface* sensor = mSensorMap.valueFor(handle);
1085 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -07001086
1087 }
1088 if (err == NO_ERROR) {
1089 SensorRegistrationInfo &reg_info =
1090 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
1091 reg_info.mActivated = false;
1092 reg_info.mPackageName= connection->getPackageName();
1093 reg_info.mSensorHandle = handle;
1094 time_t rawtime = time(NULL);
1095 struct tm * timeinfo = localtime(&rawtime);
1096 reg_info.mHour = timeinfo->tm_hour;
1097 reg_info.mMin = timeinfo->tm_min;
1098 reg_info.mSec = timeinfo->tm_sec;
1099 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001100 }
1101 return err;
1102}
1103
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001104status_t SensorService::cleanupWithoutDisable(
1105 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001106 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001107 return cleanupWithoutDisableLocked(connection, handle);
1108}
1109
1110status_t SensorService::cleanupWithoutDisableLocked(
1111 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001112 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001113 if (rec) {
1114 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001115 if (connection->removeSensor(handle)) {
1116 BatteryService::disableSensor(connection->getUid(), handle);
1117 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001118 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001119 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001120 mActiveConnections.remove(connection);
1121 }
1122 // see if this sensor becomes inactive
1123 if (rec->removeConnection(connection)) {
1124 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001125 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001126 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001127 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001128 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001129 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001130 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001131}
1132
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001133status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -07001134 int handle, nsecs_t ns, const String16& opPackageName)
Mathias Agopianfc328812010-07-14 23:41:37 -07001135{
Mathias Agopian50df2952010-07-19 19:09:10 -07001136 if (mInitCheck != NO_ERROR)
1137 return mInitCheck;
1138
Mathias Agopianae09d652011-11-01 17:37:49 -07001139 SensorInterface* sensor = mSensorMap.valueFor(handle);
1140 if (!sensor)
1141 return BAD_VALUE;
1142
Svetoslavb412f6e2015-04-29 16:50:41 -07001143 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001144 return BAD_VALUE;
1145 }
1146
Mathias Agopian1cd70002010-07-21 15:59:50 -07001147 if (ns < 0)
1148 return BAD_VALUE;
1149
Mathias Agopian62569ec2011-11-07 21:21:47 -08001150 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1151 if (ns < minDelayNs) {
1152 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001153 }
1154
Mathias Agopianf001c922010-11-11 17:58:51 -08001155 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001156}
1157
Svetoslavb412f6e2015-04-29 16:50:41 -07001158status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1159 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001160 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001161 SensorDevice& dev(SensorDevice::getInstance());
1162 const int halVersion = dev.getHalDeviceVersion();
1163 status_t err(NO_ERROR);
1164 Mutex::Autolock _l(mLock);
1165 // Loop through all sensors for this connection and call flush on each of them.
1166 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1167 const int handle = connection->mSensorInfo.keyAt(i);
1168 SensorInterface* sensor = mSensorMap.valueFor(handle);
1169 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1170 ALOGE("flush called on a one-shot sensor");
1171 err = INVALID_OPERATION;
1172 continue;
1173 }
Aravind Akella8493b792014-09-08 15:45:47 -07001174 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001175 // For older devices just increment pending flush count which will send a trivial
1176 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001177 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001178 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001179 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1180 err = INVALID_OPERATION;
1181 continue;
1182 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001183 status_t err_flush = sensor->flush(connection.get(), handle);
1184 if (err_flush == NO_ERROR) {
1185 SensorRecord* rec = mActiveSensors.valueFor(handle);
1186 if (rec != NULL) rec->addPendingFlushConnection(connection);
1187 }
1188 err = (err_flush != NO_ERROR) ? err_flush : err;
1189 }
Aravind Akella70018042014-04-07 22:52:37 +00001190 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001191 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001192}
Aravind Akella70018042014-04-07 22:52:37 +00001193
Svetoslavb412f6e2015-04-29 16:50:41 -07001194bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1195 const String16& opPackageName) {
1196 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001197
Svetoslavb412f6e2015-04-29 16:50:41 -07001198 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001199 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001200 }
1201
1202 bool hasPermission = false;
1203
1204 // Runtime permissions can't use the cache as they may change.
1205 if (sensor.isRequiredPermissionRuntime()) {
1206 hasPermission = checkPermission(String16(requiredPermission),
1207 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001208 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001209 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1210 }
1211
1212 if (!hasPermission) {
1213 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1214 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001215 return false;
1216 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001217
1218 const int32_t opCode = sensor.getRequiredAppOp();
1219 if (opCode >= 0) {
1220 AppOpsManager appOps;
1221 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1222 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001223 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001224 operation, sensor.getName().string(), opCode);
1225 return false;
1226 }
1227 }
1228
1229 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001230}
1231
Aravind Akella9a844cf2014-02-11 18:58:52 -08001232void SensorService::checkWakeLockState() {
1233 Mutex::Autolock _l(mLock);
1234 checkWakeLockStateLocked();
1235}
1236
1237void SensorService::checkWakeLockStateLocked() {
1238 if (!mWakeLockAcquired) {
1239 return;
1240 }
1241 bool releaseLock = true;
1242 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1243 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1244 if (connection != 0) {
1245 if (connection->needsWakeLock()) {
1246 releaseLock = false;
1247 break;
1248 }
1249 }
1250 }
1251 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001252 setWakeLockAcquiredLocked(false);
1253 }
1254}
1255
1256void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1257 Mutex::Autolock _l(mLock);
1258 connection->writeToSocketFromCache();
1259 if (connection->needsWakeLock()) {
1260 setWakeLockAcquiredLocked(true);
1261 }
1262}
1263
1264void SensorService::populateActiveConnections(
1265 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1266 Mutex::Autolock _l(mLock);
1267 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1268 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1269 if (connection != 0) {
1270 activeConnections->add(connection);
1271 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001272 }
1273}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001274
Aravind Akella4949c502015-02-11 15:54:35 -08001275bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001276 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001277}
1278
Aravind Akella444f2672015-05-07 12:40:52 -07001279int SensorService::getNumEventsForSensorType(int sensor_event_type) {
1280 switch (sensor_event_type) {
1281 case SENSOR_TYPE_ROTATION_VECTOR:
1282 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1283 return 5;
1284
1285 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1286 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1287 return 6;
1288
1289 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1290 return 4;
1291
1292 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1293 case SENSOR_TYPE_STEP_DETECTOR:
1294 case SENSOR_TYPE_STEP_COUNTER:
1295 return 1;
1296
1297 default:
1298 return 3;
1299 }
1300}
1301
Mathias Agopianfc328812010-07-14 23:41:37 -07001302}; // namespace android
1303