blob: f334e29950d328a93f406548d2ad81c55fa9fdd8 [file] [log] [blame]
Mathias Agopianfc328812010-07-14 23:41:37 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mathias Agopian33015422011-05-27 18:18:13 -070017#include <cutils/properties.h>
18
Svetoslavb412f6e2015-04-29 16:50:41 -070019#include <binder/AppOpsManager.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070020#include <binder/BinderService.h>
Mathias Agopian451beee2010-07-19 15:03:55 -070021#include <binder/IServiceManager.h>
Mathias Agopian1cb13462011-06-27 16:05:52 -070022#include <binder/PermissionCache.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070023
Mathias Agopian907103b2012-04-02 18:38:02 -070024#include <gui/SensorEventQueue.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070025
26#include <hardware/sensors.h>
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070027#include <hardware_legacy/power.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070028
Mathias Agopian787ac1b2012-09-18 18:49:18 -070029#include "BatteryService.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070030#include "CorrectedGyroSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080031#include "GravitySensor.h"
32#include "LinearAccelerationSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070033#include "OrientationSensor.h"
Mathias Agopianf001c922010-11-11 17:58:51 -080034#include "RotationVectorSensor.h"
Mathias Agopian984826c2011-05-17 22:54:42 -070035#include "SensorFusion.h"
Peng Xueb4d6282015-12-10 18:02:41 -080036
Mathias Agopian984826c2011-05-17 22:54:42 -070037#include "SensorService.h"
Peng Xueb4d6282015-12-10 18:02:41 -080038#include "SensorEventConnection.h"
39#include "SensorEventAckReceiver.h"
40#include "SensorRecord.h"
41#include "SensorRegistrationInfo.h"
42#include "MostRecentEventLogger.h"
43
44#include <inttypes.h>
45#include <math.h>
46#include <stdint.h>
47#include <sys/types.h>
48#include <sys/socket.h>
Mathias Agopianfc328812010-07-14 23:41:37 -070049
50namespace android {
51// ---------------------------------------------------------------------------
52
Mathias Agopian33015422011-05-27 18:18:13 -070053/*
54 * Notes:
55 *
56 * - what about a gyro-corrected magnetic-field sensor?
Mathias Agopian33015422011-05-27 18:18:13 -070057 * - run mag sensor from time to time to force calibration
58 * - gravity sensor length is wrong (=> drift in linear-acc sensor)
59 *
60 */
61
Aravind Akella8ef3c892015-07-10 11:24:28 -070062const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock";
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070063// Permissions.
Aravind Akellaa9e6cc32015-04-16 18:57:31 -070064static const String16 sDump("android.permission.DUMP");
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -070065
Mathias Agopianfc328812010-07-14 23:41:37 -070066SensorService::SensorService()
Aravind Akella8a969552014-09-28 17:52:41 -070067 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
Peng Xu47e96012016-03-28 17:55:56 -070068 mWakeLockAcquired(false) {
Mathias Agopianfc328812010-07-14 23:41:37 -070069}
70
Peng Xu47e96012016-03-28 17:55:56 -070071void SensorService::onFirstRef() {
Steve Blocka5512372011-12-20 16:23:08 +000072 ALOGD("nuSensorService starting...");
Mathias Agopianf001c922010-11-11 17:58:51 -080073 SensorDevice& dev(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -070074
Mathias Agopianf001c922010-11-11 17:58:51 -080075 if (dev.initCheck() == NO_ERROR) {
Mathias Agopianf001c922010-11-11 17:58:51 -080076 sensor_t const* list;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070077 ssize_t count = dev.getSensorList(&list);
78 if (count > 0) {
79 ssize_t orientationIndex = -1;
Aravind Akellaf5047892015-07-20 17:29:33 -070080 bool hasGyro = false, hasAccel = false, hasMag = false;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070081 uint32_t virtualSensorsNeeds =
82 (1<<SENSOR_TYPE_GRAVITY) |
83 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
Peng Xuf66684a2015-07-23 11:41:53 -070084 (1<<SENSOR_TYPE_ROTATION_VECTOR) |
85 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) |
86 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070087
88 mLastEventSeen.setCapacity(count);
89 for (ssize_t i=0 ; i<count ; i++) {
Peng Xuf66684a2015-07-23 11:41:53 -070090 bool useThisSensor=true;
91
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070092 switch (list[i].type) {
Aravind Akellaf5047892015-07-20 17:29:33 -070093 case SENSOR_TYPE_ACCELEROMETER:
94 hasAccel = true;
95 break;
96 case SENSOR_TYPE_MAGNETIC_FIELD:
97 hasMag = true;
98 break;
Mathias Agopian7b2b32f2011-07-14 16:39:46 -070099 case SENSOR_TYPE_ORIENTATION:
100 orientationIndex = i;
101 break;
102 case SENSOR_TYPE_GYROSCOPE:
Mathias Agopian03193062013-05-10 19:32:39 -0700103 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700104 hasGyro = true;
105 break;
106 case SENSOR_TYPE_GRAVITY:
107 case SENSOR_TYPE_LINEAR_ACCELERATION:
108 case SENSOR_TYPE_ROTATION_VECTOR:
Peng Xuf66684a2015-07-23 11:41:53 -0700109 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
110 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
111 if (IGNORE_HARDWARE_FUSION) {
112 useThisSensor = false;
113 } else {
114 virtualSensorsNeeds &= ~(1<<list[i].type);
115 }
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700116 break;
117 }
Peng Xuf66684a2015-07-23 11:41:53 -0700118 if (useThisSensor) {
119 registerSensor( new HardwareSensor(list[i]) );
120 }
Mathias Agopian50df2952010-07-19 19:09:10 -0700121 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700122
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700123 // it's safe to instantiate the SensorFusion object here
124 // (it wants to be instantiated after h/w sensors have been
125 // registered)
Andreas Gamped4036b62015-07-28 13:49:04 -0700126 SensorFusion::getInstance();
Mathias Agopian984826c2011-05-17 22:54:42 -0700127
Aravind Akellaf5047892015-07-20 17:29:33 -0700128 if (hasGyro && hasAccel && hasMag) {
Mathias Agopian03193062013-05-10 19:32:39 -0700129 // Add Android virtual sensors if they're not already
130 // available in the HAL
Peng Xu0cc8f802016-04-05 23:46:03 -0700131 bool needRotationVector =
132 (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700133
Peng Xu0cc8f802016-04-05 23:46:03 -0700134 registerSensor(new RotationVectorSensor(), !needRotationVector, true);
135 registerSensor(new OrientationSensor(), !needRotationVector, true);
Mathias Agopian03193062013-05-10 19:32:39 -0700136
Peng Xu0cc8f802016-04-05 23:46:03 -0700137 bool needLinearAcceleration =
138 (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
Mathias Agopian03193062013-05-10 19:32:39 -0700139
Peng Xu0cc8f802016-04-05 23:46:03 -0700140 registerSensor(new LinearAccelerationSensor(list, count),
141 !needLinearAcceleration, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700142
Peng Xu0cc8f802016-04-05 23:46:03 -0700143 // virtual debugging sensors are not for user
144 registerSensor( new CorrectedGyroSensor(list, count), false, true);
145 registerSensor( new GyroDriftSensor(), false, true);
Mathias Agopian33264862012-06-28 19:46:54 -0700146 }
147
Peng Xuf66684a2015-07-23 11:41:53 -0700148 if (hasAccel && hasGyro) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700149 bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) != 0;
150 registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700151
Peng Xu0cc8f802016-04-05 23:46:03 -0700152 bool needGameRotationVector =
153 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
154 registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700155 }
156
157 if (hasAccel && hasMag) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700158 bool needGeoMagRotationVector =
159 (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
160 registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotationVector, true);
Peng Xuf66684a2015-07-23 11:41:53 -0700161 }
162
Aravind Akella5466c3d2014-08-22 16:11:10 -0700163 // Check if the device really supports batching by looking at the FIFO event
164 // counts for each sensor.
165 bool batchingSupported = false;
Peng Xu0cc8f802016-04-05 23:46:03 -0700166 mSensors.forEachSensor(
167 [&batchingSupported] (const Sensor& s) -> bool {
168 if (s.getFifoMaxEventCount() > 0) {
169 batchingSupported = true;
170 }
171 return !batchingSupported;
172 });
Aravind Akella5466c3d2014-08-22 16:11:10 -0700173
174 if (batchingSupported) {
175 // Increase socket buffer size to a max of 100 KB for batching capabilities.
176 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED;
177 } else {
178 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED;
179 }
180
181 // Compare the socketBufferSize value against the system limits and limit
182 // it to maxSystemSocketBufferSize if necessary.
Aravind Akella4c8b9512013-09-05 17:03:38 -0700183 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r");
184 char line[128];
185 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) {
186 line[sizeof(line) - 1] = '\0';
Aravind Akella5466c3d2014-08-22 16:11:10 -0700187 size_t maxSystemSocketBufferSize;
188 sscanf(line, "%zu", &maxSystemSocketBufferSize);
189 if (mSocketBufferSize > maxSystemSocketBufferSize) {
190 mSocketBufferSize = maxSystemSocketBufferSize;
Aravind Akella4c8b9512013-09-05 17:03:38 -0700191 }
192 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700193 if (fp) {
194 fclose(fp);
195 }
196
Aravind Akella9a844cf2014-02-11 18:58:52 -0800197 mWakeLockAcquired = false;
Aravind Akella56ae4262014-07-10 16:01:10 -0700198 mLooper = new Looper(false);
Aravind Akella8493b792014-09-08 15:45:47 -0700199 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
200 mSensorEventBuffer = new sensors_event_t[minBufferSize];
201 mSensorEventScratch = new sensors_event_t[minBufferSize];
202 mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700203 mCurrentOperatingMode = NORMAL;
Aravind Akella7830ef32014-10-07 14:13:12 -0700204
Aravind Akella18d6d512015-06-18 14:18:28 -0700205 mNextSensorRegIndex = 0;
206 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
207 mLastNSensorRegistrations.push();
208 }
209
210 mInitCheck = NO_ERROR;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700211 mAckReceiver = new SensorEventAckReceiver(this);
212 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
Aravind Akella7830ef32014-10-07 14:13:12 -0700213 run("SensorService", PRIORITY_URGENT_DISPLAY);
Mathias Agopian7b2b32f2011-07-14 16:39:46 -0700214 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700215 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700216}
217
Peng Xu0cc8f802016-04-05 23:46:03 -0700218const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
219 int handle = s->getSensor().getHandle();
220 if (mSensors.add(handle, s, isDebug, isVirtual)){
221 mLastEventSeen.add(handle, nullptr);
222 return s->getSensor();
223 } else {
224 return mSensors.getNonSensor();
225 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800226}
227
Peng Xu0cc8f802016-04-05 23:46:03 -0700228const Sensor& SensorService::registerDynamicSensor(SensorInterface* s, bool isDebug) {
229 return registerSensor(s, isDebug);
Peng Xu2576cb62016-01-20 00:22:09 -0800230}
231
232bool SensorService::unregisterDynamicSensor(int handle) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700233 bool ret = mSensors.remove(handle);
234 MostRecentEventLogger *buf = mLastEventSeen.valueFor(handle);
235 if (buf) {
236 delete buf;
Peng Xu2576cb62016-01-20 00:22:09 -0800237 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700238 mLastEventSeen.removeItem(handle);
239 return ret;
Peng Xu2576cb62016-01-20 00:22:09 -0800240}
241
Peng Xu0cc8f802016-04-05 23:46:03 -0700242const Sensor& SensorService::registerVirtualSensor(SensorInterface* s, bool isDebug) {
243 return registerSensor(s, isDebug, true);
Mathias Agopianfc328812010-07-14 23:41:37 -0700244}
245
Peng Xu47e96012016-03-28 17:55:56 -0700246SensorService::~SensorService() {
Peng Xu47e96012016-03-28 17:55:56 -0700247}
248
249status_t SensorService::dump(int fd, const Vector<String16>& args) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700250 String8 result;
Mathias Agopian1cb13462011-06-27 16:05:52 -0700251 if (!PermissionCache::checkCallingPermission(sDump)) {
Peng Xueb4d6282015-12-10 18:02:41 -0800252 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n",
Mathias Agopianfc328812010-07-14 23:41:37 -0700253 IPCThreadState::self()->getCallingPid(),
254 IPCThreadState::self()->getCallingUid());
Aravind Akella444f2672015-05-07 12:40:52 -0700255 } else {
Aravind Akella841a5922015-06-29 12:37:48 -0700256 if (args.size() > 2) {
Aravind Akella4949c502015-02-11 15:54:35 -0800257 return INVALID_OPERATION;
258 }
259 Mutex::Autolock _l(mLock);
260 SensorDevice& dev(SensorDevice::getInstance());
Aravind Akella841a5922015-06-29 12:37:48 -0700261 if (args.size() == 2 && args[0] == String16("restrict")) {
Aravind Akella444f2672015-05-07 12:40:52 -0700262 // If already in restricted mode. Ignore.
263 if (mCurrentOperatingMode == RESTRICTED) {
264 return status_t(NO_ERROR);
265 }
266 // If in any mode other than normal, ignore.
267 if (mCurrentOperatingMode != NORMAL) {
268 return INVALID_OPERATION;
269 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700270 mCurrentOperatingMode = RESTRICTED;
Aravind Akella4949c502015-02-11 15:54:35 -0800271 dev.disableAllSensors();
272 // Clear all pending flush connections for all active sensors. If one of the active
273 // connections has called flush() and the underlying sensor has been disabled before a
274 // flush complete event is returned, we need to remove the connection from this queue.
275 for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
276 mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
277 }
Aravind Akella841a5922015-06-29 12:37:48 -0700278 mWhiteListedPackage.setTo(String8(args[1]));
Aravind Akella444f2672015-05-07 12:40:52 -0700279 return status_t(NO_ERROR);
280 } else if (args.size() == 1 && args[0] == String16("enable")) {
281 // If currently in restricted mode, reset back to NORMAL mode else ignore.
282 if (mCurrentOperatingMode == RESTRICTED) {
283 mCurrentOperatingMode = NORMAL;
284 dev.enableAllSensors();
285 }
Aravind Akella841a5922015-06-29 12:37:48 -0700286 if (mCurrentOperatingMode == DATA_INJECTION) {
287 resetToNormalModeLocked();
288 }
289 mWhiteListedPackage.clear();
Aravind Akella444f2672015-05-07 12:40:52 -0700290 return status_t(NO_ERROR);
Aravind Akella841a5922015-06-29 12:37:48 -0700291 } else if (args.size() == 2 && args[0] == String16("data_injection")) {
292 if (mCurrentOperatingMode == NORMAL) {
293 dev.disableAllSensors();
294 status_t err = dev.setMode(DATA_INJECTION);
295 if (err == NO_ERROR) {
296 mCurrentOperatingMode = DATA_INJECTION;
297 } else {
298 // Re-enable sensors.
299 dev.enableAllSensors();
300 }
301 mWhiteListedPackage.setTo(String8(args[1]));
302 return NO_ERROR;
303 } else if (mCurrentOperatingMode == DATA_INJECTION) {
304 // Already in DATA_INJECTION mode. Treat this as a no_op.
305 return NO_ERROR;
306 } else {
307 // Transition to data injection mode supported only from NORMAL mode.
308 return INVALID_OPERATION;
309 }
Peng Xu0cc8f802016-04-05 23:46:03 -0700310 } else if (!mSensors.hasAnySensor()) {
Aravind Akellaee155ca2015-06-24 08:31:32 -0700311 result.append("No Sensors on the device\n");
Aravind Akella444f2672015-05-07 12:40:52 -0700312 } else {
313 // Default dump the sensor list and debugging information.
Peng Xu0cc8f802016-04-05 23:46:03 -0700314 //
315 result.append(mSensors.dump().c_str());
Mathias Agopian3560fb22010-07-22 21:24:39 -0700316
Aravind Akella444f2672015-05-07 12:40:52 -0700317 SensorFusion::getInstance().dump(result);
318 SensorDevice::getInstance().dump(result);
319
Peng Xu0cc8f802016-04-05 23:46:03 -0700320 result.append("Recent Sensor events:\n");
321 auto& lastEvents = mLastEventSeen;
322 mSensors.forEachSensor([&result, &lastEvents] (const Sensor& s) -> bool {
323 int bufIndex = lastEvents.indexOfKey(s.getHandle());
324 if (bufIndex >= 0) {
325 const MostRecentEventLogger* buf = lastEvents.valueAt(bufIndex);
326 if (buf != nullptr && s.getRequiredPermission().isEmpty()) {
327 result.appendFormat("%s (handle:0x%08x): ",
328 s.getName().string(), s.getHandle());
329 buf->printBuffer(result);
330 }
331 }
332 return true;
333 });
334
Aravind Akella444f2672015-05-07 12:40:52 -0700335 result.append("Active sensors:\n");
336 for (size_t i=0 ; i<mActiveSensors.size() ; i++) {
337 int handle = mActiveSensors.keyAt(i);
338 result.appendFormat("%s (handle=0x%08x, connections=%zu)\n",
339 getSensorName(handle).string(),
340 handle,
341 mActiveSensors.valueAt(i)->getNumConnections());
Aravind Akella6c2664a2014-08-13 12:24:50 -0700342 }
343
Andreas Gamped4036b62015-07-28 13:49:04 -0700344 result.appendFormat("Socket Buffer size = %zd events\n",
Aravind Akella444f2672015-05-07 12:40:52 -0700345 mSocketBufferSize/sizeof(sensors_event_t));
Aravind Akella18d6d512015-06-18 14:18:28 -0700346 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" :
347 "not held");
Aravind Akella444f2672015-05-07 12:40:52 -0700348 result.appendFormat("Mode :");
349 switch(mCurrentOperatingMode) {
350 case NORMAL:
351 result.appendFormat(" NORMAL\n");
352 break;
353 case RESTRICTED:
Aravind Akella841a5922015-06-29 12:37:48 -0700354 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string());
Aravind Akella444f2672015-05-07 12:40:52 -0700355 break;
356 case DATA_INJECTION:
Aravind Akella841a5922015-06-29 12:37:48 -0700357 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
Mathias Agopianba02cd22013-07-03 16:20:57 -0700358 }
Aravind Akella444f2672015-05-07 12:40:52 -0700359 result.appendFormat("%zd active connections\n", mActiveConnections.size());
Aravind Akella0e025c52014-06-03 19:19:57 -0700360
Aravind Akella444f2672015-05-07 12:40:52 -0700361 for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
362 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
363 if (connection != 0) {
364 result.appendFormat("Connection Number: %zu \n", i);
365 connection->dump(result);
366 }
Aravind Akella4c8b9512013-09-05 17:03:38 -0700367 }
Aravind Akella18d6d512015-06-18 14:18:28 -0700368
369 result.appendFormat("Previous Registrations:\n");
370 // Log in the reverse chronological order.
371 int currentIndex = (mNextSensorRegIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
372 SENSOR_REGISTRATIONS_BUF_SIZE;
373 const int startIndex = currentIndex;
374 do {
375 const SensorRegistrationInfo& reg_info = mLastNSensorRegistrations[currentIndex];
376 if (SensorRegistrationInfo::isSentinel(reg_info)) {
377 // Ignore sentinel, proceed to next item.
378 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
379 SENSOR_REGISTRATIONS_BUF_SIZE;
380 continue;
381 }
382 if (reg_info.mActivated) {
383 result.appendFormat("%02d:%02d:%02d activated package=%s handle=0x%08x "
384 "samplingRate=%dus maxReportLatency=%dus\n",
385 reg_info.mHour, reg_info.mMin, reg_info.mSec,
386 reg_info.mPackageName.string(), reg_info.mSensorHandle,
387 reg_info.mSamplingRateUs, reg_info.mMaxReportLatencyUs);
388 } else {
389 result.appendFormat("%02d:%02d:%02d de-activated package=%s handle=0x%08x\n",
390 reg_info.mHour, reg_info.mMin, reg_info.mSec,
391 reg_info.mPackageName.string(), reg_info.mSensorHandle);
392 }
393 currentIndex = (currentIndex - 1 + SENSOR_REGISTRATIONS_BUF_SIZE) %
394 SENSOR_REGISTRATIONS_BUF_SIZE;
395 } while(startIndex != currentIndex);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700396 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700397 }
398 write(fd, result.string(), result.size());
399 return NO_ERROR;
400}
401
Peng Xu0cc8f802016-04-05 23:46:03 -0700402//TODO: move to SensorEventConnection later
Aravind Akella9a844cf2014-02-11 18:58:52 -0800403void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700404 sensors_event_t const* buffer, const int count) {
405 for (int i=0 ; i<count ; i++) {
406 int handle = buffer[i].sensor;
Aravind Akella8493b792014-09-08 15:45:47 -0700407 if (buffer[i].type == SENSOR_TYPE_META_DATA) {
408 handle = buffer[i].meta_data.sensor;
409 }
Aravind Akella0e025c52014-06-03 19:19:57 -0700410 if (connection->hasSensor(handle)) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700411 SensorInterface* si = mSensors.getInterface(handle);
Aravind Akella0e025c52014-06-03 19:19:57 -0700412 // If this buffer has an event from a one_shot sensor and this connection is registered
413 // for this particular one_shot sensor, try cleaning up the connection.
Peng Xu0cc8f802016-04-05 23:46:03 -0700414 if (si != NULL &&
415 si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
416 si->autoDisable(connection.get(), handle);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800417 cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700418 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700419
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700420 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700421 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700422}
423
Peng Xu47e96012016-03-28 17:55:56 -0700424bool SensorService::threadLoop() {
Steve Blocka5512372011-12-20 16:23:08 +0000425 ALOGD("nuSensorService thread starting...");
Mathias Agopianfc328812010-07-14 23:41:37 -0700426
Peng Xueb4d6282015-12-10 18:02:41 -0800427 // each virtual sensor could generate an event per "real" event, that's why we need to size
428 // numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. in practice, this is too
429 // aggressive, but guaranteed to be enough.
Peng Xu0cc8f802016-04-05 23:46:03 -0700430 const size_t vcount = mSensors.getVirtualSensors().size();
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700431 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
Peng Xu0cc8f802016-04-05 23:46:03 -0700432 const size_t numEventMax = minBufferSize / (1 + vcount);
Mathias Agopian90ed3e82013-09-09 23:36:25 -0700433
Mathias Agopianf001c922010-11-11 17:58:51 -0800434 SensorDevice& device(SensorDevice::getInstance());
Mathias Agopianfc328812010-07-14 23:41:37 -0700435
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700436 const int halVersion = device.getHalDeviceVersion();
Mathias Agopianfc328812010-07-14 23:41:37 -0700437 do {
Aravind Akella8493b792014-09-08 15:45:47 -0700438 ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
439 if (count < 0) {
Steve Blockf5a12302012-01-06 19:20:56 +0000440 ALOGE("sensor poll failed (%s)", strerror(-count));
Mathias Agopianfc328812010-07-14 23:41:37 -0700441 break;
442 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700443
444 // Reset sensors_event_t.flags to zero for all events in the buffer.
445 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700446 mSensorEventBuffer[i].flags = 0;
Aravind Akella56ae4262014-07-10 16:01:10 -0700447 }
Aravind Akellae148bc22014-09-24 22:12:58 -0700448
Peng Xueb4d6282015-12-10 18:02:41 -0800449 // Make a copy of the connection vector as some connections may be removed during the course
450 // of this loop (especially when one-shot sensor events are present in the sensor_event
451 // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
452 // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
453 // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
454 // strongPointers to a vector before the lock is acquired.
Aravind Akellae148bc22014-09-24 22:12:58 -0700455 SortedVector< sp<SensorEventConnection> > activeConnections;
Aravind Akellab4373ac2014-10-29 17:55:20 -0700456 populateActiveConnections(&activeConnections);
Peng Xueb4d6282015-12-10 18:02:41 -0800457
Aravind Akella9a844cf2014-02-11 18:58:52 -0800458 Mutex::Autolock _l(mLock);
459 // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
460 // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
461 // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
462 // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
463 // releasing the wakelock.
464 bool bufferHasWakeUpEvent = false;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700465 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700466 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800467 bufferHasWakeUpEvent = true;
468 break;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700469 }
470 }
471
Aravind Akella9a844cf2014-02-11 18:58:52 -0800472 if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700473 setWakeLockAcquiredLocked(true);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800474 }
Aravind Akella8493b792014-09-08 15:45:47 -0700475 recordLastValueLocked(mSensorEventBuffer, count);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800476
Mathias Agopianf001c922010-11-11 17:58:51 -0800477 // handle virtual sensors
478 if (count && vcount) {
Aravind Akella8493b792014-09-08 15:45:47 -0700479 sensors_event_t const * const event = mSensorEventBuffer;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800480 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
Mathias Agopianf001c922010-11-11 17:58:51 -0800481 if (activeVirtualSensorCount) {
482 size_t k = 0;
Mathias Agopian984826c2011-05-17 22:54:42 -0700483 SensorFusion& fusion(SensorFusion::getInstance());
484 if (fusion.isEnabled()) {
485 for (size_t i=0 ; i<size_t(count) ; i++) {
486 fusion.process(event[i]);
487 }
488 }
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700489 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800490 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700491 if (count + k >= minBufferSize) {
492 ALOGE("buffer too small to hold all events: "
Mark Salyzyndb458612014-06-10 14:50:02 -0700493 "count=%zd, k=%zu, size=%zu",
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700494 count, k, minBufferSize);
495 break;
496 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800497 sensors_event_t out;
Aravind Akella9a844cf2014-02-11 18:58:52 -0800498 SensorInterface* si = mActiveVirtualSensors.valueAt(j);
Mathias Agopiand1920ff2012-05-29 19:46:14 -0700499 if (si->process(&out, event[i])) {
Aravind Akella8493b792014-09-08 15:45:47 -0700500 mSensorEventBuffer[count + k] = out;
Mathias Agopianf001c922010-11-11 17:58:51 -0800501 k++;
502 }
503 }
504 }
505 if (k) {
506 // record the last synthesized values
Aravind Akella8493b792014-09-08 15:45:47 -0700507 recordLastValueLocked(&mSensorEventBuffer[count], k);
Mathias Agopianf001c922010-11-11 17:58:51 -0800508 count += k;
509 // sort the buffer by time-stamps
Aravind Akella8493b792014-09-08 15:45:47 -0700510 sortEventBuffer(mSensorEventBuffer, count);
Mathias Agopianfc328812010-07-14 23:41:37 -0700511 }
512 }
513 }
514
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700515 // handle backward compatibility for RotationVector sensor
516 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) {
517 for (int i = 0; i < count; i++) {
Aravind Akella8493b792014-09-08 15:45:47 -0700518 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700519 // All the 4 components of the quaternion should be available
520 // No heading accuracy. Set it to -1
Aravind Akella8493b792014-09-08 15:45:47 -0700521 mSensorEventBuffer[i].data[4] = -1;
522 }
523 }
524 }
525
Aravind Akella8493b792014-09-08 15:45:47 -0700526 for (int i = 0; i < count; ++i) {
Peng Xu0cc8f802016-04-05 23:46:03 -0700527 // Map flush_complete_events in the buffer to SensorEventConnections which called flush
528 // on the hardware sensor. mapFlushEventsToConnections[i] will be the
529 // SensorEventConnection mapped to the corresponding flush_complete_event in
530 // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise).
Aravind Akella8493b792014-09-08 15:45:47 -0700531 mMapFlushEventsToConnections[i] = NULL;
532 if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
533 const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor;
534 SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
535 if (rec != NULL) {
536 mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection();
537 rec->removeFirstPendingFlushConnection();
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700538 }
539 }
Peng Xu2576cb62016-01-20 00:22:09 -0800540
541 // handle dynamic sensor meta events, process registration and unregistration of dynamic
542 // sensor based on content of event.
543 if (mSensorEventBuffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META) {
544 if (mSensorEventBuffer[i].dynamic_sensor_meta.connected) {
545 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
546 const sensor_t& dynamicSensor =
547 *(mSensorEventBuffer[i].dynamic_sensor_meta.sensor);
548 ALOGI("Dynamic sensor handle 0x%x connected, type %d, name %s",
549 handle, dynamicSensor.type, dynamicSensor.name);
550
Peng Xu0cc8f802016-04-05 23:46:03 -0700551 if (mSensors.isNewHandle(handle)) {
Peng Xu47e96012016-03-28 17:55:56 -0700552 sensor_t s = dynamicSensor;
553 // make sure the dynamic sensor flag is set
554 s.flags |= DYNAMIC_SENSOR_MASK;
555 // force the handle to be consistent
556 s.handle = handle;
557 SensorInterface *si = new HardwareSensor(s);
Peng Xu2576cb62016-01-20 00:22:09 -0800558
Peng Xu0cc8f802016-04-05 23:46:03 -0700559 // This will release hold on dynamic sensor meta, so it should be called
560 // after Sensor object is created.
Peng Xu47e96012016-03-28 17:55:56 -0700561 device.handleDynamicSensorConnection(handle, true /*connected*/);
562 registerDynamicSensor(si);
563 } else {
564 ALOGE("Handle %d has been used, cannot use again before reboot.", handle);
565 }
Peng Xu2576cb62016-01-20 00:22:09 -0800566 } else {
567 int handle = mSensorEventBuffer[i].dynamic_sensor_meta.handle;
568 ALOGI("Dynamic sensor handle 0x%x disconnected", handle);
569
570 device.handleDynamicSensorConnection(handle, false /*connected*/);
571 if (!unregisterDynamicSensor(handle)) {
572 ALOGE("Dynamic sensor release error.");
573 }
574
575 size_t numConnections = activeConnections.size();
576 for (size_t i=0 ; i < numConnections; ++i) {
577 if (activeConnections[i] != NULL) {
578 activeConnections[i]->removeSensor(handle);
579 }
580 }
581 }
582 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700583 }
584
Peng Xu2576cb62016-01-20 00:22:09 -0800585
Aravind Akella9a844cf2014-02-11 18:58:52 -0800586 // Send our events to clients. Check the state of wake lock for each client and release the
587 // lock if none of the clients need it.
588 bool needsWakeLock = false;
Aravind Akella8493b792014-09-08 15:45:47 -0700589 size_t numConnections = activeConnections.size();
590 for (size_t i=0 ; i < numConnections; ++i) {
Aravind Akellae148bc22014-09-24 22:12:58 -0700591 if (activeConnections[i] != 0) {
592 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
Aravind Akella8493b792014-09-08 15:45:47 -0700593 mMapFlushEventsToConnections);
Aravind Akellae148bc22014-09-24 22:12:58 -0700594 needsWakeLock |= activeConnections[i]->needsWakeLock();
Aravind Akella8493b792014-09-08 15:45:47 -0700595 // If the connection has one-shot sensors, it may be cleaned up after first trigger.
596 // Early check for one-shot sensors.
Aravind Akellae148bc22014-09-24 22:12:58 -0700597 if (activeConnections[i]->hasOneShotSensors()) {
598 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
599 count);
Aravind Akella8493b792014-09-08 15:45:47 -0700600 }
Mathias Agopianf001c922010-11-11 17:58:51 -0800601 }
602 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700603
Aravind Akella9a844cf2014-02-11 18:58:52 -0800604 if (mWakeLockAcquired && !needsWakeLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700605 setWakeLockAcquiredLocked(false);
Aravind Akella9a844cf2014-02-11 18:58:52 -0800606 }
Aravind Akella8493b792014-09-08 15:45:47 -0700607 } while (!Thread::exitPending());
Mathias Agopianfc328812010-07-14 23:41:37 -0700608
Steve Block3c20fbe2012-01-05 23:22:43 +0000609 ALOGW("Exiting SensorService::threadLoop => aborting...");
Mathias Agopian1a623012011-11-09 17:50:15 -0800610 abort();
Mathias Agopianfc328812010-07-14 23:41:37 -0700611 return false;
612}
613
Aravind Akella56ae4262014-07-10 16:01:10 -0700614sp<Looper> SensorService::getLooper() const {
615 return mLooper;
616}
617
Aravind Akellab4373ac2014-10-29 17:55:20 -0700618void SensorService::resetAllWakeLockRefCounts() {
619 SortedVector< sp<SensorEventConnection> > activeConnections;
620 populateActiveConnections(&activeConnections);
621 {
622 Mutex::Autolock _l(mLock);
623 for (size_t i=0 ; i < activeConnections.size(); ++i) {
624 if (activeConnections[i] != 0) {
625 activeConnections[i]->resetWakeLockRefCount();
626 }
627 }
628 setWakeLockAcquiredLocked(false);
629 }
630}
631
632void SensorService::setWakeLockAcquiredLocked(bool acquire) {
633 if (acquire) {
634 if (!mWakeLockAcquired) {
635 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
636 mWakeLockAcquired = true;
637 }
638 mLooper->wake();
639 } else {
640 if (mWakeLockAcquired) {
641 release_wake_lock(WAKE_LOCK_NAME);
642 mWakeLockAcquired = false;
643 }
644 }
645}
646
Aravind Akellab4373ac2014-10-29 17:55:20 -0700647bool SensorService::isWakeLockAcquired() {
648 Mutex::Autolock _l(mLock);
649 return mWakeLockAcquired;
650}
651
Aravind Akella56ae4262014-07-10 16:01:10 -0700652bool SensorService::SensorEventAckReceiver::threadLoop() {
653 ALOGD("new thread SensorEventAckReceiver");
Aravind Akellab4373ac2014-10-29 17:55:20 -0700654 sp<Looper> looper = mService->getLooper();
Aravind Akella56ae4262014-07-10 16:01:10 -0700655 do {
Aravind Akellab4373ac2014-10-29 17:55:20 -0700656 bool wakeLockAcquired = mService->isWakeLockAcquired();
657 int timeout = -1;
658 if (wakeLockAcquired) timeout = 5000;
659 int ret = looper->pollOnce(timeout);
660 if (ret == ALOOPER_POLL_TIMEOUT) {
661 mService->resetAllWakeLockRefCounts();
662 }
Aravind Akella56ae4262014-07-10 16:01:10 -0700663 } while(!Thread::exitPending());
664 return false;
665}
666
Aravind Akella9a844cf2014-02-11 18:58:52 -0800667void SensorService::recordLastValueLocked(
Aravind Akella4b847042014-03-03 19:02:46 -0800668 const sensors_event_t* buffer, size_t count) {
Aravind Akella4b847042014-03-03 19:02:46 -0800669 for (size_t i = 0; i < count; i++) {
Peng Xu2576cb62016-01-20 00:22:09 -0800670 if (buffer[i].type == SENSOR_TYPE_META_DATA ||
671 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META ||
Peng Xu9e720462016-01-26 18:48:54 -0800672 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO ||
Peng Xu2576cb62016-01-20 00:22:09 -0800673 mLastEventSeen.indexOfKey(buffer[i].sensor) <0 ) {
674 continue;
Mathias Agopian94e8f682010-11-10 17:50:28 -0800675 }
Peng Xu2576cb62016-01-20 00:22:09 -0800676
677 MostRecentEventLogger* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor);
678 if (circular_buf == NULL) {
679 circular_buf = new MostRecentEventLogger(buffer[i].type);
680 }
681 circular_buf->addEvent(buffer[i]);
Mathias Agopian94e8f682010-11-10 17:50:28 -0800682 }
Mathias Agopian94e8f682010-11-10 17:50:28 -0800683}
684
Peng Xu47e96012016-03-28 17:55:56 -0700685void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) {
Mathias Agopianf001c922010-11-11 17:58:51 -0800686 struct compar {
687 static int cmp(void const* lhs, void const* rhs) {
688 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs);
689 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs);
Mathias Agopiana5c106a2012-04-19 18:18:24 -0700690 return l->timestamp - r->timestamp;
Mathias Agopianf001c922010-11-11 17:58:51 -0800691 }
692 };
693 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
694}
695
Mathias Agopian5d270722010-07-19 15:20:39 -0700696String8 SensorService::getSensorName(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700697 return mSensors.getName(handle);
Mathias Agopian5d270722010-07-19 15:20:39 -0700698}
699
Aravind Akellab4099e72013-10-15 15:43:10 -0700700bool SensorService::isVirtualSensor(int handle) const {
Peng Xu47e96012016-03-28 17:55:56 -0700701 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Peng Xu2576cb62016-01-20 00:22:09 -0800702 return sensor != NULL && sensor->isVirtual();
Aravind Akellab4099e72013-10-15 15:43:10 -0700703}
704
Aravind Akella9a844cf2014-02-11 18:58:52 -0800705bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
Sean Wan7869e222014-07-14 17:07:33 -0700706 int handle = event.sensor;
707 if (event.type == SENSOR_TYPE_META_DATA) {
708 handle = event.meta_data.sensor;
709 }
Peng Xu47e96012016-03-28 17:55:56 -0700710 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Sean Wan7869e222014-07-14 17:07:33 -0700711 return sensor != NULL && sensor->getSensor().isWakeUpSensor();
Aravind Akella9a844cf2014-02-11 18:58:52 -0800712}
713
Peng Xu47e96012016-03-28 17:55:56 -0700714Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) {
Mathias Agopian33264862012-06-28 19:46:54 -0700715 char value[PROPERTY_VALUE_MAX];
716 property_get("debug.sensors", value, "0");
Aravind Akella70018042014-04-07 22:52:37 +0000717 const Vector<Sensor>& initialSensorList = (atoi(value)) ?
Peng Xu0cc8f802016-04-05 23:46:03 -0700718 mSensors.getUserDebugSensors() : mSensors.getUserSensors();
Aravind Akella70018042014-04-07 22:52:37 +0000719 Vector<Sensor> accessibleSensorList;
720 for (size_t i = 0; i < initialSensorList.size(); i++) {
721 Sensor sensor = initialSensorList[i];
Svetoslavb412f6e2015-04-29 16:50:41 -0700722 if (canAccessSensor(sensor, "getSensorList", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000723 accessibleSensorList.add(sensor);
724 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -0700725 ALOGI("Skipped sensor %s because it requires permission %s and app op %d",
Bernhard Rosenkränzer5f619932014-11-17 21:06:20 +0100726 sensor.getName().string(),
Svetoslavb412f6e2015-04-29 16:50:41 -0700727 sensor.getRequiredPermission().string(),
728 sensor.getRequiredAppOp());
Aravind Akella70018042014-04-07 22:52:37 +0000729 }
Mathias Agopian33264862012-06-28 19:46:54 -0700730 }
Aravind Akella70018042014-04-07 22:52:37 +0000731 return accessibleSensorList;
Mathias Agopianfc328812010-07-14 23:41:37 -0700732}
733
Peng Xu47e96012016-03-28 17:55:56 -0700734Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) {
Peng Xu2576cb62016-01-20 00:22:09 -0800735 Vector<Sensor> accessibleSensorList;
Peng Xu0cc8f802016-04-05 23:46:03 -0700736 mSensors.forEachSensor(
737 [&opPackageName, &accessibleSensorList] (const Sensor& sensor) -> bool {
738 if (sensor.isDynamicSensor() &&
739 canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) {
740 accessibleSensorList.add(sensor);
741 } else {
742 ALOGI("Skipped sensor %s because it requires permission %s and app op %" PRId32,
743 sensor.getName().string(),
744 sensor.getRequiredPermission().string(),
745 sensor.getRequiredAppOp());
746 }
747 return true;
748 });
Peng Xu2576cb62016-01-20 00:22:09 -0800749 return accessibleSensorList;
750}
751
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700752sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700753 int requestedMode, const String16& opPackageName) {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700754 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION.
755 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) {
756 return NULL;
757 }
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700758
759 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700760 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be
761 // operating in DI mode.
762 if (requestedMode == DATA_INJECTION) {
763 if (mCurrentOperatingMode != DATA_INJECTION) return NULL;
764 if (!isWhiteListedPackage(packageName)) return NULL;
765 }
766
Mathias Agopian5307d172012-09-18 17:02:43 -0700767 uid_t uid = IPCThreadState::self()->getCallingUid();
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700768 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName,
Svetoslavb412f6e2015-04-29 16:50:41 -0700769 requestedMode == DATA_INJECTION, opPackageName));
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700770 if (requestedMode == DATA_INJECTION) {
771 if (mActiveConnections.indexOf(result) < 0) {
772 mActiveConnections.add(result);
773 }
774 // Add the associated file descriptor to the Looper for polling whenever there is data to
775 // be injected.
776 result->updateLooperRegistration(mLooper);
777 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700778 return result;
779}
780
Aravind Akella841a5922015-06-29 12:37:48 -0700781int SensorService::isDataInjectionEnabled() {
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700782 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700783 return (mCurrentOperatingMode == DATA_INJECTION);
Aravind Akellaa9e6cc32015-04-16 18:57:31 -0700784}
785
786status_t SensorService::resetToNormalMode() {
787 Mutex::Autolock _l(mLock);
788 return resetToNormalModeLocked();
789}
790
791status_t SensorService::resetToNormalModeLocked() {
792 SensorDevice& dev(SensorDevice::getInstance());
793 dev.enableAllSensors();
794 status_t err = dev.setMode(NORMAL);
795 mCurrentOperatingMode = NORMAL;
796 return err;
797}
798
Peng Xu47e96012016-03-28 17:55:56 -0700799void SensorService::cleanupConnection(SensorEventConnection* c) {
Mathias Agopianfc328812010-07-14 23:41:37 -0700800 Mutex::Autolock _l(mLock);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800801 const wp<SensorEventConnection> connection(c);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700802 size_t size = mActiveSensors.size();
Mark Salyzyndb458612014-06-10 14:50:02 -0700803 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700804 for (size_t i=0 ; i<size ; ) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800805 int handle = mActiveSensors.keyAt(i);
806 if (c->hasSensor(handle)) {
Mark Salyzyndb458612014-06-10 14:50:02 -0700807 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle);
Peng Xu47e96012016-03-28 17:55:56 -0700808 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Steve Blockf5a12302012-01-06 19:20:56 +0000809 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle);
Mathias Agopianf001c922010-11-11 17:58:51 -0800810 if (sensor) {
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800811 sensor->activate(c, false);
Mathias Agopianf001c922010-11-11 17:58:51 -0800812 }
Aravind Akella8a969552014-09-28 17:52:41 -0700813 c->removeSensor(handle);
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800814 }
815 SensorRecord* rec = mActiveSensors.valueAt(i);
Mark Salyzyndb458612014-06-10 14:50:02 -0700816 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle);
Steve Blocka5512372011-12-20 16:23:08 +0000817 ALOGD_IF(DEBUG_CONNECTIONS,
Mark Salyzyndb458612014-06-10 14:50:02 -0700818 "removing connection %p for sensor[%zu].handle=0x%08x",
Mathias Agopiana1b7db92011-05-27 16:23:58 -0700819 c, i, handle);
820
Mathias Agopiandb5b4bc2011-02-03 14:52:47 -0800821 if (rec && rec->removeConnection(connection)) {
Steve Blocka5512372011-12-20 16:23:08 +0000822 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection");
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700823 mActiveSensors.removeItemsAt(i, 1);
Mathias Agopianf001c922010-11-11 17:58:51 -0800824 mActiveVirtualSensors.removeItem(handle);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700825 delete rec;
826 size--;
827 } else {
828 i++;
Mathias Agopianfc328812010-07-14 23:41:37 -0700829 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700830 }
Aravind Akella8a969552014-09-28 17:52:41 -0700831 c->updateLooperRegistration(mLooper);
Mathias Agopian7c1c5312010-07-21 15:59:50 -0700832 mActiveConnections.remove(connection);
Mathias Agopian787ac1b2012-09-18 18:49:18 -0700833 BatteryService::cleanup(c->getUid());
Aravind Akella9a844cf2014-02-11 18:58:52 -0800834 if (c->needsWakeLock()) {
835 checkWakeLockStateLocked();
836 }
Mathias Agopianfc328812010-07-14 23:41:37 -0700837}
838
Peng Xu47e96012016-03-28 17:55:56 -0700839SensorInterface* SensorService::getSensorInterfaceFromHandle(int handle) const {
Peng Xu0cc8f802016-04-05 23:46:03 -0700840 return mSensors.getInterface(handle);
Peng Xu47e96012016-03-28 17:55:56 -0700841}
842
Peng Xu0cc8f802016-04-05 23:46:03 -0700843const Sensor& SensorService::getSensorFromHandle(int handle) const {
844 return mSensors.get(handle);
Aravind Akella70018042014-04-07 22:52:37 +0000845}
846
Mathias Agopianfc328812010-07-14 23:41:37 -0700847status_t SensorService::enable(const sp<SensorEventConnection>& connection,
Svetoslavb412f6e2015-04-29 16:50:41 -0700848 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags,
Peng Xu47e96012016-03-28 17:55:56 -0700849 const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -0700850 if (mInitCheck != NO_ERROR)
851 return mInitCheck;
852
Peng Xu47e96012016-03-28 17:55:56 -0700853 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700854 if (sensor == NULL) {
855 return BAD_VALUE;
856 }
Aravind Akella70018042014-04-07 22:52:37 +0000857
Svetoslavb412f6e2015-04-29 16:50:41 -0700858 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +0000859 return BAD_VALUE;
860 }
861
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700862 Mutex::Autolock _l(mLock);
Aravind Akella841a5922015-06-29 12:37:48 -0700863 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION)
864 && !isWhiteListedPackage(connection->getPackageName())) {
Aravind Akella4949c502015-02-11 15:54:35 -0800865 return INVALID_OPERATION;
866 }
867
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700868 SensorRecord* rec = mActiveSensors.valueFor(handle);
869 if (rec == 0) {
870 rec = new SensorRecord(connection);
871 mActiveSensors.add(handle, rec);
872 if (sensor->isVirtual()) {
873 mActiveVirtualSensors.add(handle, sensor);
874 }
875 } else {
876 if (rec->addConnection(connection)) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800877 // this sensor is already activated, but we are adding a connection that uses it.
878 // Immediately send down the last known value of the requested sensor if it's not a
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700879 // "continuous" sensor.
Aravind Akella0e025c52014-06-03 19:19:57 -0700880 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) {
Aravind Akella9a844cf2014-02-11 18:58:52 -0800881 // NOTE: The wake_up flag of this event may get set to
882 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
Peng Xueb4d6282015-12-10 18:02:41 -0800883 MostRecentEventLogger *circular_buf = mLastEventSeen.valueFor(handle);
Aravind Akella444f2672015-05-07 12:40:52 -0700884 if (circular_buf) {
885 sensors_event_t event;
886 memset(&event, 0, sizeof(event));
887 // It is unlikely that this buffer is empty as the sensor is already active.
888 // One possible corner case may be two applications activating an on-change
889 // sensor at the same time.
890 if(circular_buf->populateLastEvent(&event)) {
891 event.sensor = handle;
892 if (event.version == sizeof(sensors_event_t)) {
893 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
894 setWakeLockAcquiredLocked(true);
895 }
896 connection->sendEvents(&event, 1, NULL);
897 if (!connection->needsWakeLock() && mWakeLockAcquired) {
898 checkWakeLockStateLocked();
899 }
900 }
Aravind Akella9a844cf2014-02-11 18:58:52 -0800901 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700902 }
903 }
904 }
905 }
906
907 if (connection->addSensor(handle)) {
908 BatteryService::enableSensor(connection->getUid(), handle);
909 // the sensor was added (which means it wasn't already there)
910 // so, see if this connection becomes active
911 if (mActiveConnections.indexOf(connection) < 0) {
912 mActiveConnections.add(connection);
913 }
914 } else {
915 ALOGW("sensor %08x already enabled in connection %p (ignoring)",
916 handle, connection.get());
917 }
918
Aravind Akella724d91d2013-06-27 12:04:23 -0700919 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
920 if (samplingPeriodNs < minDelayNs) {
921 samplingPeriodNs = minDelayNs;
922 }
923
Aravind Akella6c2664a2014-08-13 12:24:50 -0700924 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d"
925 "rate=%" PRId64 " timeout== %" PRId64"",
Aravind Akella724d91d2013-06-27 12:04:23 -0700926 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs);
927
Aravind Akella4949c502015-02-11 15:54:35 -0800928 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs,
Aravind Akella724d91d2013-06-27 12:04:23 -0700929 maxBatchReportLatencyNs);
Aravind Akella6c2664a2014-08-13 12:24:50 -0700930
Peng Xu20483c42015-10-26 15:14:43 -0700931 // Call flush() before calling activate() on the sensor. Wait for a first
932 // flush complete event before sending events on this connection. Ignore
933 // one-shot sensors which don't support flush(). Ignore on-change sensors
934 // to maintain the on-change logic (any on-change events except the initial
935 // one should be trigger by a change in value). Also if this sensor isn't
936 // already active, don't call flush().
937 if (err == NO_ERROR &&
Peng Xu2576cb62016-01-20 00:22:09 -0800938 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS &&
Aravind Akella5466c3d2014-08-22 16:11:10 -0700939 rec->getNumConnections() > 1) {
940 connection->setFirstFlushPending(handle, true);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700941 status_t err_flush = sensor->flush(connection.get(), handle);
Aravind Akella5466c3d2014-08-22 16:11:10 -0700942 // Flush may return error if the underlying h/w sensor uses an older HAL.
Aravind Akella6c2664a2014-08-13 12:24:50 -0700943 if (err_flush == NO_ERROR) {
Aravind Akella6c2664a2014-08-13 12:24:50 -0700944 rec->addPendingFlushConnection(connection.get());
Aravind Akella5466c3d2014-08-22 16:11:10 -0700945 } else {
946 connection->setFirstFlushPending(handle, false);
Aravind Akella4c8b9512013-09-05 17:03:38 -0700947 }
948 }
Aravind Akella724d91d2013-06-27 12:04:23 -0700949
950 if (err == NO_ERROR) {
951 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle);
952 err = sensor->activate(connection.get(), true);
953 }
954
Aravind Akella8a969552014-09-28 17:52:41 -0700955 if (err == NO_ERROR) {
956 connection->updateLooperRegistration(mLooper);
Aravind Akella18d6d512015-06-18 14:18:28 -0700957 SensorRegistrationInfo &reg_info =
958 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
959 reg_info.mSensorHandle = handle;
960 reg_info.mSamplingRateUs = samplingPeriodNs/1000;
961 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000;
962 reg_info.mActivated = true;
963 reg_info.mPackageName = connection->getPackageName();
964 time_t rawtime = time(NULL);
965 struct tm * timeinfo = localtime(&rawtime);
966 reg_info.mHour = timeinfo->tm_hour;
967 reg_info.mMin = timeinfo->tm_min;
968 reg_info.mSec = timeinfo->tm_sec;
969 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Aravind Akella56ae4262014-07-10 16:01:10 -0700970 }
971
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700972 if (err != NO_ERROR) {
Aravind Akella724d91d2013-06-27 12:04:23 -0700973 // batch/activate has failed, reset our state.
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700974 cleanupWithoutDisableLocked(connection, handle);
Mathias Agopianfc328812010-07-14 23:41:37 -0700975 }
976 return err;
977}
978
Peng Xu47e96012016-03-28 17:55:56 -0700979status_t SensorService::disable(const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopian50df2952010-07-19 19:09:10 -0700980 if (mInitCheck != NO_ERROR)
981 return mInitCheck;
982
Mathias Agopianac9a96d2013-07-12 02:01:16 -0700983 Mutex::Autolock _l(mLock);
984 status_t err = cleanupWithoutDisableLocked(connection, handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700985 if (err == NO_ERROR) {
Peng Xu47e96012016-03-28 17:55:56 -0700986 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -0700987 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE);
Aravind Akella18d6d512015-06-18 14:18:28 -0700988
989 }
990 if (err == NO_ERROR) {
991 SensorRegistrationInfo &reg_info =
992 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex);
993 reg_info.mActivated = false;
994 reg_info.mPackageName= connection->getPackageName();
995 reg_info.mSensorHandle = handle;
996 time_t rawtime = time(NULL);
997 struct tm * timeinfo = localtime(&rawtime);
998 reg_info.mHour = timeinfo->tm_hour;
999 reg_info.mMin = timeinfo->tm_min;
1000 reg_info.mSec = timeinfo->tm_sec;
1001 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE;
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001002 }
1003 return err;
1004}
1005
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001006status_t SensorService::cleanupWithoutDisable(
1007 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001008 Mutex::Autolock _l(mLock);
Mathias Agopianac9a96d2013-07-12 02:01:16 -07001009 return cleanupWithoutDisableLocked(connection, handle);
1010}
1011
1012status_t SensorService::cleanupWithoutDisableLocked(
1013 const sp<SensorEventConnection>& connection, int handle) {
Mathias Agopianfc328812010-07-14 23:41:37 -07001014 SensorRecord* rec = mActiveSensors.valueFor(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001015 if (rec) {
1016 // see if this connection becomes inactive
Mathias Agopian787ac1b2012-09-18 18:49:18 -07001017 if (connection->removeSensor(handle)) {
1018 BatteryService::disableSensor(connection->getUid(), handle);
1019 }
Mathias Agopianfc328812010-07-14 23:41:37 -07001020 if (connection->hasAnySensor() == false) {
Aravind Akella8a969552014-09-28 17:52:41 -07001021 connection->updateLooperRegistration(mLooper);
Mathias Agopianfc328812010-07-14 23:41:37 -07001022 mActiveConnections.remove(connection);
1023 }
1024 // see if this sensor becomes inactive
1025 if (rec->removeConnection(connection)) {
1026 mActiveSensors.removeItem(handle);
Mathias Agopianf001c922010-11-11 17:58:51 -08001027 mActiveVirtualSensors.removeItem(handle);
Mathias Agopianfc328812010-07-14 23:41:37 -07001028 delete rec;
Mathias Agopianfc328812010-07-14 23:41:37 -07001029 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001030 return NO_ERROR;
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001031 }
Jaikumar Ganesh4342fdf2013-04-08 16:43:12 -07001032 return BAD_VALUE;
Mathias Agopianfc328812010-07-14 23:41:37 -07001033}
1034
Mathias Agopian7c1c5312010-07-21 15:59:50 -07001035status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection,
Peng Xu47e96012016-03-28 17:55:56 -07001036 int handle, nsecs_t ns, const String16& opPackageName) {
Mathias Agopian50df2952010-07-19 19:09:10 -07001037 if (mInitCheck != NO_ERROR)
1038 return mInitCheck;
1039
Peng Xu47e96012016-03-28 17:55:56 -07001040 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Mathias Agopianae09d652011-11-01 17:37:49 -07001041 if (!sensor)
1042 return BAD_VALUE;
1043
Svetoslavb412f6e2015-04-29 16:50:41 -07001044 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) {
Aravind Akella70018042014-04-07 22:52:37 +00001045 return BAD_VALUE;
1046 }
1047
Mathias Agopian1cd70002010-07-21 15:59:50 -07001048 if (ns < 0)
1049 return BAD_VALUE;
1050
Mathias Agopian62569ec2011-11-07 21:21:47 -08001051 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs();
1052 if (ns < minDelayNs) {
1053 ns = minDelayNs;
Mathias Agopianae09d652011-11-01 17:37:49 -07001054 }
1055
Mathias Agopianf001c922010-11-11 17:58:51 -08001056 return sensor->setDelay(connection.get(), handle, ns);
Mathias Agopianfc328812010-07-14 23:41:37 -07001057}
1058
Svetoslavb412f6e2015-04-29 16:50:41 -07001059status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection,
1060 const String16& opPackageName) {
Aravind Akella70018042014-04-07 22:52:37 +00001061 if (mInitCheck != NO_ERROR) return mInitCheck;
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001062 SensorDevice& dev(SensorDevice::getInstance());
1063 const int halVersion = dev.getHalDeviceVersion();
1064 status_t err(NO_ERROR);
1065 Mutex::Autolock _l(mLock);
1066 // Loop through all sensors for this connection and call flush on each of them.
1067 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
1068 const int handle = connection->mSensorInfo.keyAt(i);
Peng Xu47e96012016-03-28 17:55:56 -07001069 SensorInterface* sensor = getSensorInterfaceFromHandle(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001070 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
1071 ALOGE("flush called on a one-shot sensor");
1072 err = INVALID_OPERATION;
1073 continue;
1074 }
Aravind Akella8493b792014-09-08 15:45:47 -07001075 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001076 // For older devices just increment pending flush count which will send a trivial
1077 // flush complete event.
Aravind Akella8a969552014-09-28 17:52:41 -07001078 connection->incrementPendingFlushCount(handle);
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001079 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001080 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) {
1081 err = INVALID_OPERATION;
1082 continue;
1083 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001084 status_t err_flush = sensor->flush(connection.get(), handle);
1085 if (err_flush == NO_ERROR) {
1086 SensorRecord* rec = mActiveSensors.valueFor(handle);
1087 if (rec != NULL) rec->addPendingFlushConnection(connection);
1088 }
1089 err = (err_flush != NO_ERROR) ? err_flush : err;
1090 }
Aravind Akella70018042014-04-07 22:52:37 +00001091 }
Aravind Akella9e3adfc2014-09-03 15:48:05 -07001092 return err;
Aravind Akella724d91d2013-06-27 12:04:23 -07001093}
Aravind Akella70018042014-04-07 22:52:37 +00001094
Svetoslavb412f6e2015-04-29 16:50:41 -07001095bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
1096 const String16& opPackageName) {
1097 const String8& requiredPermission = sensor.getRequiredPermission();
Aravind Akella70018042014-04-07 22:52:37 +00001098
Svetoslavb412f6e2015-04-29 16:50:41 -07001099 if (requiredPermission.length() <= 0) {
Aravind Akella70018042014-04-07 22:52:37 +00001100 return true;
Svetoslavb412f6e2015-04-29 16:50:41 -07001101 }
1102
1103 bool hasPermission = false;
1104
1105 // Runtime permissions can't use the cache as they may change.
1106 if (sensor.isRequiredPermissionRuntime()) {
1107 hasPermission = checkPermission(String16(requiredPermission),
1108 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
Aravind Akella70018042014-04-07 22:52:37 +00001109 } else {
Svetoslavb412f6e2015-04-29 16:50:41 -07001110 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission));
1111 }
1112
1113 if (!hasPermission) {
1114 ALOGE("%s a sensor (%s) without holding its required permission: %s",
1115 operation, sensor.getName().string(), sensor.getRequiredPermission().string());
Aravind Akella70018042014-04-07 22:52:37 +00001116 return false;
1117 }
Svetoslavb412f6e2015-04-29 16:50:41 -07001118
1119 const int32_t opCode = sensor.getRequiredAppOp();
1120 if (opCode >= 0) {
1121 AppOpsManager appOps;
1122 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName)
1123 != AppOpsManager::MODE_ALLOWED) {
Andreas Gamped4036b62015-07-28 13:49:04 -07001124 ALOGE("%s a sensor (%s) without enabled required app op: %d",
Svetoslavb412f6e2015-04-29 16:50:41 -07001125 operation, sensor.getName().string(), opCode);
1126 return false;
1127 }
1128 }
1129
1130 return true;
Aravind Akella70018042014-04-07 22:52:37 +00001131}
1132
Aravind Akella9a844cf2014-02-11 18:58:52 -08001133void SensorService::checkWakeLockState() {
1134 Mutex::Autolock _l(mLock);
1135 checkWakeLockStateLocked();
1136}
1137
1138void SensorService::checkWakeLockStateLocked() {
1139 if (!mWakeLockAcquired) {
1140 return;
1141 }
1142 bool releaseLock = true;
1143 for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
1144 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1145 if (connection != 0) {
1146 if (connection->needsWakeLock()) {
1147 releaseLock = false;
1148 break;
1149 }
1150 }
1151 }
1152 if (releaseLock) {
Aravind Akellab4373ac2014-10-29 17:55:20 -07001153 setWakeLockAcquiredLocked(false);
1154 }
1155}
1156
1157void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) {
1158 Mutex::Autolock _l(mLock);
1159 connection->writeToSocketFromCache();
1160 if (connection->needsWakeLock()) {
1161 setWakeLockAcquiredLocked(true);
1162 }
1163}
1164
1165void SensorService::populateActiveConnections(
1166 SortedVector< sp<SensorEventConnection> >* activeConnections) {
1167 Mutex::Autolock _l(mLock);
1168 for (size_t i=0 ; i < mActiveConnections.size(); ++i) {
1169 sp<SensorEventConnection> connection(mActiveConnections[i].promote());
1170 if (connection != 0) {
1171 activeConnections->add(connection);
1172 }
Aravind Akella9a844cf2014-02-11 18:58:52 -08001173 }
1174}
Aravind Akella6c2664a2014-08-13 12:24:50 -07001175
Aravind Akella4949c502015-02-11 15:54:35 -08001176bool SensorService::isWhiteListedPackage(const String8& packageName) {
Aravind Akella841a5922015-06-29 12:37:48 -07001177 return (packageName.contains(mWhiteListedPackage.string()));
Aravind Akella4949c502015-02-11 15:54:35 -08001178}
1179
Aravind Akella444f2672015-05-07 12:40:52 -07001180int SensorService::getNumEventsForSensorType(int sensor_event_type) {
Nick Vaccaro95f13902016-03-01 15:49:08 -08001181 if (sensor_event_type >= SENSOR_TYPE_DEVICE_PRIVATE_BASE) {
1182 return 16;
1183 }
Aravind Akella444f2672015-05-07 12:40:52 -07001184 switch (sensor_event_type) {
1185 case SENSOR_TYPE_ROTATION_VECTOR:
1186 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
1187 return 5;
1188
1189 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
1190 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
1191 return 6;
1192
1193 case SENSOR_TYPE_GAME_ROTATION_VECTOR:
1194 return 4;
1195
1196 case SENSOR_TYPE_SIGNIFICANT_MOTION:
1197 case SENSOR_TYPE_STEP_DETECTOR:
1198 case SENSOR_TYPE_STEP_COUNTER:
1199 return 1;
1200
1201 default:
1202 return 3;
1203 }
1204}
1205
Mathias Agopianfc328812010-07-14 23:41:37 -07001206}; // namespace android
1207