SensorService.cpp revision 9e72046f399f13dfeb5ed0cb32343ca6697f52f5
1/* 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 17#include <cutils/properties.h> 18 19#include <binder/AppOpsManager.h> 20#include <binder/BinderService.h> 21#include <binder/IServiceManager.h> 22#include <binder/PermissionCache.h> 23 24#include <gui/SensorEventQueue.h> 25 26#include <hardware/sensors.h> 27#include <hardware_legacy/power.h> 28 29#include "BatteryService.h" 30#include "CorrectedGyroSensor.h" 31#include "GravitySensor.h" 32#include "LinearAccelerationSensor.h" 33#include "OrientationSensor.h" 34#include "RotationVectorSensor.h" 35#include "SensorFusion.h" 36 37#include "SensorService.h" 38#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> 49 50namespace android { 51// --------------------------------------------------------------------------- 52 53/* 54 * Notes: 55 * 56 * - what about a gyro-corrected magnetic-field sensor? 57 * - run mag sensor from time to time to force calibration 58 * - gravity sensor length is wrong (=> drift in linear-acc sensor) 59 * 60 */ 61 62const char* SensorService::WAKE_LOCK_NAME = "SensorService_wakelock"; 63// Permissions. 64static const String16 sDump("android.permission.DUMP"); 65 66SensorService::SensorService() 67 : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED), 68 mWakeLockAcquired(false) 69{ 70} 71 72void SensorService::onFirstRef() 73{ 74 ALOGD("nuSensorService starting..."); 75 SensorDevice& dev(SensorDevice::getInstance()); 76 77 if (dev.initCheck() == NO_ERROR) { 78 sensor_t const* list; 79 ssize_t count = dev.getSensorList(&list); 80 if (count > 0) { 81 ssize_t orientationIndex = -1; 82 bool hasGyro = false, hasAccel = false, hasMag = false; 83 uint32_t virtualSensorsNeeds = 84 (1<<SENSOR_TYPE_GRAVITY) | 85 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) | 86 (1<<SENSOR_TYPE_ROTATION_VECTOR) | 87 (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR) | 88 (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR); 89 90 mLastEventSeen.setCapacity(count); 91 for (ssize_t i=0 ; i<count ; i++) { 92 bool useThisSensor=true; 93 94 switch (list[i].type) { 95 case SENSOR_TYPE_ACCELEROMETER: 96 hasAccel = true; 97 break; 98 case SENSOR_TYPE_MAGNETIC_FIELD: 99 hasMag = true; 100 break; 101 case SENSOR_TYPE_ORIENTATION: 102 orientationIndex = i; 103 break; 104 case SENSOR_TYPE_GYROSCOPE: 105 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED: 106 hasGyro = true; 107 break; 108 case SENSOR_TYPE_GRAVITY: 109 case SENSOR_TYPE_LINEAR_ACCELERATION: 110 case SENSOR_TYPE_ROTATION_VECTOR: 111 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 } 118 break; 119 } 120 if (useThisSensor) { 121 registerSensor( new HardwareSensor(list[i]) ); 122 } 123 } 124 125 // it's safe to instantiate the SensorFusion object here 126 // (it wants to be instantiated after h/w sensors have been 127 // registered) 128 SensorFusion::getInstance(); 129 130 // build the sensor list returned to users 131 mUserSensorList = mSensorList; 132 133 if (hasGyro && hasAccel && hasMag) { 134 // Add Android virtual sensors if they're not already 135 // available in the HAL 136 Sensor aSensor; 137 138 aSensor = registerVirtualSensor( new RotationVectorSensor() ); 139 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) { 140 mUserSensorList.add(aSensor); 141 } 142 143 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 150 aSensor = registerVirtualSensor( 151 new LinearAccelerationSensor(list, count) ); 152 if (virtualSensorsNeeds & 153 (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) { 154 mUserSensorList.add(aSensor); 155 } 156 157 // virtual debugging sensors are not added to mUserSensorList 158 registerVirtualSensor( new CorrectedGyroSensor(list, count) ); 159 registerVirtualSensor( new GyroDriftSensor() ); 160 } 161 162 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 190 // debugging sensor list 191 mUserSensorListDebug = mSensorList; 192 193 // Check if the device really supports batching by looking at the FIFO event 194 // counts for each sensor. 195 bool batchingSupported = false; 196 for (size_t i = 0; i < mSensorList.size(); ++i) { 197 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. 212 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'; 216 size_t maxSystemSocketBufferSize; 217 sscanf(line, "%zu", &maxSystemSocketBufferSize); 218 if (mSocketBufferSize > maxSystemSocketBufferSize) { 219 mSocketBufferSize = maxSystemSocketBufferSize; 220 } 221 } 222 if (fp) { 223 fclose(fp); 224 } 225 226 mWakeLockAcquired = false; 227 mLooper = new Looper(false); 228 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]; 232 mCurrentOperatingMode = NORMAL; 233 234 mNextSensorRegIndex = 0; 235 for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) { 236 mLastNSensorRegistrations.push(); 237 } 238 239 mInitCheck = NO_ERROR; 240 mAckReceiver = new SensorEventAckReceiver(this); 241 mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY); 242 run("SensorService", PRIORITY_URGENT_DISPLAY); 243 } 244 } 245} 246 247Sensor SensorService::registerSensor(SensorInterface* s) 248{ 249 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 255 mLastEventSeen.add(sensor.getHandle(), NULL); 256 257 return sensor; 258} 259 260Sensor 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 291Sensor SensorService::registerVirtualSensor(SensorInterface* s) 292{ 293 Sensor sensor = registerSensor(s); 294 mVirtualSensorList.add( s ); 295 return sensor; 296} 297 298SensorService::~SensorService() 299{ 300 for (size_t i=0 ; i<mSensorMap.size() ; i++) 301 delete mSensorMap.valueAt(i); 302} 303 304status_t SensorService::dump(int fd, const Vector<String16>& args) 305{ 306 String8 result; 307 if (!PermissionCache::checkCallingPermission(sDump)) { 308 result.appendFormat("Permission Denial: can't dump SensorService from pid=%d, uid=%d\n", 309 IPCThreadState::self()->getCallingPid(), 310 IPCThreadState::self()->getCallingUid()); 311 } else { 312 if (args.size() > 2) { 313 return INVALID_OPERATION; 314 } 315 Mutex::Autolock _l(mLock); 316 SensorDevice& dev(SensorDevice::getInstance()); 317 if (args.size() == 2 && args[0] == String16("restrict")) { 318 // 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 } 326 mCurrentOperatingMode = RESTRICTED; 327 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 } 334 mWhiteListedPackage.setTo(String8(args[1])); 335 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 } 342 if (mCurrentOperatingMode == DATA_INJECTION) { 343 resetToNormalModeLocked(); 344 } 345 mWhiteListedPackage.clear(); 346 return status_t(NO_ERROR); 347 } 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 } 366 } else if (mSensorList.size() == 0) { 367 result.append("No Sensors on the device\n"); 368 } 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()); 382 383 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 419 int bufIndex = mLastEventSeen.indexOfKey(s.getHandle()); 420 if (bufIndex >= 0) { 421 const MostRecentEventLogger* buf = mLastEventSeen.valueAt(bufIndex); 422 if (buf != NULL && s.getRequiredPermission().isEmpty()) { 423 buf->printBuffer(result); 424 } else { 425 result.append("last=<> \n"); 426 } 427 } 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()); 440 } 441 442 result.appendFormat("Socket Buffer size = %zd events\n", 443 mSocketBufferSize/sizeof(sensors_event_t)); 444 result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : 445 "not held"); 446 result.appendFormat("Mode :"); 447 switch(mCurrentOperatingMode) { 448 case NORMAL: 449 result.appendFormat(" NORMAL\n"); 450 break; 451 case RESTRICTED: 452 result.appendFormat(" RESTRICTED : %s\n", mWhiteListedPackage.string()); 453 break; 454 case DATA_INJECTION: 455 result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string()); 456 } 457 result.appendFormat("%zd active connections\n", mActiveConnections.size()); 458 459 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 } 465 } 466 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); 494 } 495 } 496 write(fd, result.string(), result.size()); 497 return NO_ERROR; 498} 499 500void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection, 501 sensors_event_t const* buffer, const int count) { 502 for (int i=0 ; i<count ; i++) { 503 int handle = buffer[i].sensor; 504 if (buffer[i].type == SENSOR_TYPE_META_DATA) { 505 handle = buffer[i].meta_data.sensor; 506 } 507 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); 514 cleanupWithoutDisableLocked(connection, handle); 515 } 516 517 } 518 } 519} 520 521bool SensorService::threadLoop() 522{ 523 ALOGD("nuSensorService thread starting..."); 524 525 // 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. 528 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT; 529 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size()); 530 531 SensorDevice& device(SensorDevice::getInstance()); 532 const size_t vcount = mVirtualSensorList.size(); 533 534 const int halVersion = device.getHalDeviceVersion(); 535 do { 536 ssize_t count = device.poll(mSensorEventBuffer, numEventMax); 537 if (count < 0) { 538 ALOGE("sensor poll failed (%s)", strerror(-count)); 539 break; 540 } 541 542 // Reset sensors_event_t.flags to zero for all events in the buffer. 543 for (int i = 0; i < count; i++) { 544 mSensorEventBuffer[i].flags = 0; 545 } 546 547 // 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. 553 SortedVector< sp<SensorEventConnection> > activeConnections; 554 populateActiveConnections(&activeConnections); 555 556 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; 563 for (int i = 0; i < count; i++) { 564 if (isWakeUpSensorEvent(mSensorEventBuffer[i])) { 565 bufferHasWakeUpEvent = true; 566 break; 567 } 568 } 569 570 if (bufferHasWakeUpEvent && !mWakeLockAcquired) { 571 setWakeLockAcquiredLocked(true); 572 } 573 recordLastValueLocked(mSensorEventBuffer, count); 574 575 // handle virtual sensors 576 if (count && vcount) { 577 sensors_event_t const * const event = mSensorEventBuffer; 578 const size_t activeVirtualSensorCount = mActiveVirtualSensors.size(); 579 if (activeVirtualSensorCount) { 580 size_t k = 0; 581 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 } 587 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) { 588 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) { 589 if (count + k >= minBufferSize) { 590 ALOGE("buffer too small to hold all events: " 591 "count=%zd, k=%zu, size=%zu", 592 count, k, minBufferSize); 593 break; 594 } 595 sensors_event_t out; 596 SensorInterface* si = mActiveVirtualSensors.valueAt(j); 597 if (si->process(&out, event[i])) { 598 mSensorEventBuffer[count + k] = out; 599 k++; 600 } 601 } 602 } 603 if (k) { 604 // record the last synthesized values 605 recordLastValueLocked(&mSensorEventBuffer[count], k); 606 count += k; 607 // sort the buffer by time-stamps 608 sortEventBuffer(mSensorEventBuffer, count); 609 } 610 } 611 } 612 613 // handle backward compatibility for RotationVector sensor 614 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) { 615 for (int i = 0; i < count; i++) { 616 if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) { 617 // All the 4 components of the quaternion should be available 618 // No heading accuracy. Set it to -1 619 mSensorEventBuffer[i].data[4] = -1; 620 } 621 } 622 } 623 624 for (int i = 0; i < count; ++i) { 625 // 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). 629 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(); 636 } 637 } 638 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 } 669 } 670 671 672 // 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; 675 size_t numConnections = activeConnections.size(); 676 for (size_t i=0 ; i < numConnections; ++i) { 677 if (activeConnections[i] != 0) { 678 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch, 679 mMapFlushEventsToConnections); 680 needsWakeLock |= activeConnections[i]->needsWakeLock(); 681 // If the connection has one-shot sensors, it may be cleaned up after first trigger. 682 // Early check for one-shot sensors. 683 if (activeConnections[i]->hasOneShotSensors()) { 684 cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer, 685 count); 686 } 687 } 688 } 689 690 if (mWakeLockAcquired && !needsWakeLock) { 691 setWakeLockAcquiredLocked(false); 692 } 693 } while (!Thread::exitPending()); 694 695 ALOGW("Exiting SensorService::threadLoop => aborting..."); 696 abort(); 697 return false; 698} 699 700sp<Looper> SensorService::getLooper() const { 701 return mLooper; 702} 703 704void 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 733bool SensorService::isWakeLockAcquired() { 734 Mutex::Autolock _l(mLock); 735 return mWakeLockAcquired; 736} 737 738bool SensorService::SensorEventAckReceiver::threadLoop() { 739 ALOGD("new thread SensorEventAckReceiver"); 740 sp<Looper> looper = mService->getLooper(); 741 do { 742 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 } 749 } while(!Thread::exitPending()); 750 return false; 751} 752 753void SensorService::recordLastValueLocked( 754 const sensors_event_t* buffer, size_t count) { 755 for (size_t i = 0; i < count; i++) { 756 if (buffer[i].type == SENSOR_TYPE_META_DATA || 757 buffer[i].type == SENSOR_TYPE_DYNAMIC_SENSOR_META || 758 buffer[i].type == SENSOR_TYPE_ADDITIONAL_INFO || 759 mLastEventSeen.indexOfKey(buffer[i].sensor) <0 ) { 760 continue; 761 } 762 763 MostRecentEventLogger* &circular_buf = mLastEventSeen.editValueFor(buffer[i].sensor); 764 if (circular_buf == NULL) { 765 circular_buf = new MostRecentEventLogger(buffer[i].type); 766 } 767 circular_buf->addEvent(buffer[i]); 768 } 769} 770 771void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) 772{ 773 struct compar { 774 static int cmp(void const* lhs, void const* rhs) { 775 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs); 776 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs); 777 return l->timestamp - r->timestamp; 778 } 779 }; 780 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp); 781} 782 783String8 SensorService::getSensorName(int handle) const { 784 size_t count = mUserSensorList.size(); 785 for (size_t i=0 ; i<count ; i++) { 786 const Sensor& sensor(mUserSensorList[i]); 787 if (sensor.getHandle() == handle) { 788 return sensor.getName(); 789 } 790 } 791 String8 result("unknown"); 792 return result; 793} 794 795bool SensorService::isVirtualSensor(int handle) const { 796 SensorInterface* sensor = mSensorMap.valueFor(handle); 797 return sensor != NULL && sensor->isVirtual(); 798} 799 800bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const { 801 int handle = event.sensor; 802 if (event.type == SENSOR_TYPE_META_DATA) { 803 handle = event.meta_data.sensor; 804 } 805 SensorInterface* sensor = mSensorMap.valueFor(handle); 806 return sensor != NULL && sensor->getSensor().isWakeUpSensor(); 807} 808 809SensorService::SensorRecord * SensorService::getSensorRecord(int handle) { 810 return mActiveSensors.valueFor(handle); 811} 812 813Vector<Sensor> SensorService::getSensorList(const String16& opPackageName) 814{ 815 char value[PROPERTY_VALUE_MAX]; 816 property_get("debug.sensors", value, "0"); 817 const Vector<Sensor>& initialSensorList = (atoi(value)) ? 818 mUserSensorListDebug : mUserSensorList; 819 Vector<Sensor> accessibleSensorList; 820 for (size_t i = 0; i < initialSensorList.size(); i++) { 821 Sensor sensor = initialSensorList[i]; 822 if (canAccessSensor(sensor, "getSensorList", opPackageName)) { 823 accessibleSensorList.add(sensor); 824 } else { 825 ALOGI("Skipped sensor %s because it requires permission %s and app op %d", 826 sensor.getName().string(), 827 sensor.getRequiredPermission().string(), 828 sensor.getRequiredAppOp()); 829 } 830 } 831 return accessibleSensorList; 832} 833 834Vector<Sensor> SensorService::getDynamicSensorList(const String16& opPackageName) 835{ 836 Vector<Sensor> accessibleSensorList; 837 for (size_t i = 0; i < mDynamicSensorList.size(); i++) { 838 Sensor sensor = mDynamicSensorList[i]; 839 if (canAccessSensor(sensor, "getDynamicSensorList", opPackageName)) { 840 accessibleSensorList.add(sensor); 841 } else { 842 ALOGI("Skipped sensor %s because it requires permission %s and app op %d", 843 sensor.getName().string(), 844 sensor.getRequiredPermission().string(), 845 sensor.getRequiredAppOp()); 846 } 847 } 848 return accessibleSensorList; 849} 850 851sp<ISensorEventConnection> SensorService::createSensorEventConnection(const String8& packageName, 852 int requestedMode, const String16& opPackageName) { 853 // Only 2 modes supported for a SensorEventConnection ... NORMAL and DATA_INJECTION. 854 if (requestedMode != NORMAL && requestedMode != DATA_INJECTION) { 855 return NULL; 856 } 857 858 Mutex::Autolock _l(mLock); 859 // To create a client in DATA_INJECTION mode to inject data, SensorService should already be 860 // operating in DI mode. 861 if (requestedMode == DATA_INJECTION) { 862 if (mCurrentOperatingMode != DATA_INJECTION) return NULL; 863 if (!isWhiteListedPackage(packageName)) return NULL; 864 } 865 866 uid_t uid = IPCThreadState::self()->getCallingUid(); 867 sp<SensorEventConnection> result(new SensorEventConnection(this, uid, packageName, 868 requestedMode == DATA_INJECTION, opPackageName)); 869 if (requestedMode == DATA_INJECTION) { 870 if (mActiveConnections.indexOf(result) < 0) { 871 mActiveConnections.add(result); 872 } 873 // Add the associated file descriptor to the Looper for polling whenever there is data to 874 // be injected. 875 result->updateLooperRegistration(mLooper); 876 } 877 return result; 878} 879 880int SensorService::isDataInjectionEnabled() { 881 Mutex::Autolock _l(mLock); 882 return (mCurrentOperatingMode == DATA_INJECTION); 883} 884 885status_t SensorService::resetToNormalMode() { 886 Mutex::Autolock _l(mLock); 887 return resetToNormalModeLocked(); 888} 889 890status_t SensorService::resetToNormalModeLocked() { 891 SensorDevice& dev(SensorDevice::getInstance()); 892 dev.enableAllSensors(); 893 status_t err = dev.setMode(NORMAL); 894 mCurrentOperatingMode = NORMAL; 895 return err; 896} 897 898void SensorService::cleanupConnection(SensorEventConnection* c) 899{ 900 Mutex::Autolock _l(mLock); 901 const wp<SensorEventConnection> connection(c); 902 size_t size = mActiveSensors.size(); 903 ALOGD_IF(DEBUG_CONNECTIONS, "%zu active sensors", size); 904 for (size_t i=0 ; i<size ; ) { 905 int handle = mActiveSensors.keyAt(i); 906 if (c->hasSensor(handle)) { 907 ALOGD_IF(DEBUG_CONNECTIONS, "%zu: disabling handle=0x%08x", i, handle); 908 SensorInterface* sensor = mSensorMap.valueFor( handle ); 909 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle); 910 if (sensor) { 911 sensor->activate(c, false); 912 } 913 c->removeSensor(handle); 914 } 915 SensorRecord* rec = mActiveSensors.valueAt(i); 916 ALOGE_IF(!rec, "mActiveSensors[%zu] is null (handle=0x%08x)!", i, handle); 917 ALOGD_IF(DEBUG_CONNECTIONS, 918 "removing connection %p for sensor[%zu].handle=0x%08x", 919 c, i, handle); 920 921 if (rec && rec->removeConnection(connection)) { 922 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection"); 923 mActiveSensors.removeItemsAt(i, 1); 924 mActiveVirtualSensors.removeItem(handle); 925 delete rec; 926 size--; 927 } else { 928 i++; 929 } 930 } 931 c->updateLooperRegistration(mLooper); 932 mActiveConnections.remove(connection); 933 BatteryService::cleanup(c->getUid()); 934 if (c->needsWakeLock()) { 935 checkWakeLockStateLocked(); 936 } 937} 938 939Sensor SensorService::getSensorFromHandle(int handle) const { 940 return mSensorMap.valueFor(handle)->getSensor(); 941} 942 943status_t SensorService::enable(const sp<SensorEventConnection>& connection, 944 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags, 945 const String16& opPackageName) 946{ 947 if (mInitCheck != NO_ERROR) 948 return mInitCheck; 949 950 SensorInterface* sensor = mSensorMap.valueFor(handle); 951 if (sensor == NULL) { 952 return BAD_VALUE; 953 } 954 955 if (!canAccessSensor(sensor->getSensor(), "Tried enabling", opPackageName)) { 956 return BAD_VALUE; 957 } 958 959 Mutex::Autolock _l(mLock); 960 if ((mCurrentOperatingMode == RESTRICTED || mCurrentOperatingMode == DATA_INJECTION) 961 && !isWhiteListedPackage(connection->getPackageName())) { 962 return INVALID_OPERATION; 963 } 964 965 SensorRecord* rec = mActiveSensors.valueFor(handle); 966 if (rec == 0) { 967 rec = new SensorRecord(connection); 968 mActiveSensors.add(handle, rec); 969 if (sensor->isVirtual()) { 970 mActiveVirtualSensors.add(handle, sensor); 971 } 972 } else { 973 if (rec->addConnection(connection)) { 974 // this sensor is already activated, but we are adding a connection that uses it. 975 // Immediately send down the last known value of the requested sensor if it's not a 976 // "continuous" sensor. 977 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ON_CHANGE) { 978 // NOTE: The wake_up flag of this event may get set to 979 // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event. 980 MostRecentEventLogger *circular_buf = mLastEventSeen.valueFor(handle); 981 if (circular_buf) { 982 sensors_event_t event; 983 memset(&event, 0, sizeof(event)); 984 // It is unlikely that this buffer is empty as the sensor is already active. 985 // One possible corner case may be two applications activating an on-change 986 // sensor at the same time. 987 if(circular_buf->populateLastEvent(&event)) { 988 event.sensor = handle; 989 if (event.version == sizeof(sensors_event_t)) { 990 if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) { 991 setWakeLockAcquiredLocked(true); 992 } 993 connection->sendEvents(&event, 1, NULL); 994 if (!connection->needsWakeLock() && mWakeLockAcquired) { 995 checkWakeLockStateLocked(); 996 } 997 } 998 } 999 } 1000 } 1001 } 1002 } 1003 1004 if (connection->addSensor(handle)) { 1005 BatteryService::enableSensor(connection->getUid(), handle); 1006 // the sensor was added (which means it wasn't already there) 1007 // so, see if this connection becomes active 1008 if (mActiveConnections.indexOf(connection) < 0) { 1009 mActiveConnections.add(connection); 1010 } 1011 } else { 1012 ALOGW("sensor %08x already enabled in connection %p (ignoring)", 1013 handle, connection.get()); 1014 } 1015 1016 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs(); 1017 if (samplingPeriodNs < minDelayNs) { 1018 samplingPeriodNs = minDelayNs; 1019 } 1020 1021 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d" 1022 "rate=%" PRId64 " timeout== %" PRId64"", 1023 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs); 1024 1025 status_t err = sensor->batch(connection.get(), handle, 0, samplingPeriodNs, 1026 maxBatchReportLatencyNs); 1027 1028 // Call flush() before calling activate() on the sensor. Wait for a first 1029 // flush complete event before sending events on this connection. Ignore 1030 // one-shot sensors which don't support flush(). Ignore on-change sensors 1031 // to maintain the on-change logic (any on-change events except the initial 1032 // one should be trigger by a change in value). Also if this sensor isn't 1033 // already active, don't call flush(). 1034 if (err == NO_ERROR && 1035 sensor->getSensor().getReportingMode() == AREPORTING_MODE_CONTINUOUS && 1036 rec->getNumConnections() > 1) { 1037 connection->setFirstFlushPending(handle, true); 1038 status_t err_flush = sensor->flush(connection.get(), handle); 1039 // Flush may return error if the underlying h/w sensor uses an older HAL. 1040 if (err_flush == NO_ERROR) { 1041 rec->addPendingFlushConnection(connection.get()); 1042 } else { 1043 connection->setFirstFlushPending(handle, false); 1044 } 1045 } 1046 1047 if (err == NO_ERROR) { 1048 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle); 1049 err = sensor->activate(connection.get(), true); 1050 } 1051 1052 if (err == NO_ERROR) { 1053 connection->updateLooperRegistration(mLooper); 1054 SensorRegistrationInfo ®_info = 1055 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex); 1056 reg_info.mSensorHandle = handle; 1057 reg_info.mSamplingRateUs = samplingPeriodNs/1000; 1058 reg_info.mMaxReportLatencyUs = maxBatchReportLatencyNs/1000; 1059 reg_info.mActivated = true; 1060 reg_info.mPackageName = connection->getPackageName(); 1061 time_t rawtime = time(NULL); 1062 struct tm * timeinfo = localtime(&rawtime); 1063 reg_info.mHour = timeinfo->tm_hour; 1064 reg_info.mMin = timeinfo->tm_min; 1065 reg_info.mSec = timeinfo->tm_sec; 1066 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE; 1067 } 1068 1069 if (err != NO_ERROR) { 1070 // batch/activate has failed, reset our state. 1071 cleanupWithoutDisableLocked(connection, handle); 1072 } 1073 return err; 1074} 1075 1076status_t SensorService::disable(const sp<SensorEventConnection>& connection, 1077 int handle) 1078{ 1079 if (mInitCheck != NO_ERROR) 1080 return mInitCheck; 1081 1082 Mutex::Autolock _l(mLock); 1083 status_t err = cleanupWithoutDisableLocked(connection, handle); 1084 if (err == NO_ERROR) { 1085 SensorInterface* sensor = mSensorMap.valueFor(handle); 1086 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE); 1087 1088 } 1089 if (err == NO_ERROR) { 1090 SensorRegistrationInfo ®_info = 1091 mLastNSensorRegistrations.editItemAt(mNextSensorRegIndex); 1092 reg_info.mActivated = false; 1093 reg_info.mPackageName= connection->getPackageName(); 1094 reg_info.mSensorHandle = handle; 1095 time_t rawtime = time(NULL); 1096 struct tm * timeinfo = localtime(&rawtime); 1097 reg_info.mHour = timeinfo->tm_hour; 1098 reg_info.mMin = timeinfo->tm_min; 1099 reg_info.mSec = timeinfo->tm_sec; 1100 mNextSensorRegIndex = (mNextSensorRegIndex + 1) % SENSOR_REGISTRATIONS_BUF_SIZE; 1101 } 1102 return err; 1103} 1104 1105status_t SensorService::cleanupWithoutDisable( 1106 const sp<SensorEventConnection>& connection, int handle) { 1107 Mutex::Autolock _l(mLock); 1108 return cleanupWithoutDisableLocked(connection, handle); 1109} 1110 1111status_t SensorService::cleanupWithoutDisableLocked( 1112 const sp<SensorEventConnection>& connection, int handle) { 1113 SensorRecord* rec = mActiveSensors.valueFor(handle); 1114 if (rec) { 1115 // see if this connection becomes inactive 1116 if (connection->removeSensor(handle)) { 1117 BatteryService::disableSensor(connection->getUid(), handle); 1118 } 1119 if (connection->hasAnySensor() == false) { 1120 connection->updateLooperRegistration(mLooper); 1121 mActiveConnections.remove(connection); 1122 } 1123 // see if this sensor becomes inactive 1124 if (rec->removeConnection(connection)) { 1125 mActiveSensors.removeItem(handle); 1126 mActiveVirtualSensors.removeItem(handle); 1127 delete rec; 1128 } 1129 return NO_ERROR; 1130 } 1131 return BAD_VALUE; 1132} 1133 1134status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection, 1135 int handle, nsecs_t ns, const String16& opPackageName) 1136{ 1137 if (mInitCheck != NO_ERROR) 1138 return mInitCheck; 1139 1140 SensorInterface* sensor = mSensorMap.valueFor(handle); 1141 if (!sensor) 1142 return BAD_VALUE; 1143 1144 if (!canAccessSensor(sensor->getSensor(), "Tried configuring", opPackageName)) { 1145 return BAD_VALUE; 1146 } 1147 1148 if (ns < 0) 1149 return BAD_VALUE; 1150 1151 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs(); 1152 if (ns < minDelayNs) { 1153 ns = minDelayNs; 1154 } 1155 1156 return sensor->setDelay(connection.get(), handle, ns); 1157} 1158 1159status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection, 1160 const String16& opPackageName) { 1161 if (mInitCheck != NO_ERROR) return mInitCheck; 1162 SensorDevice& dev(SensorDevice::getInstance()); 1163 const int halVersion = dev.getHalDeviceVersion(); 1164 status_t err(NO_ERROR); 1165 Mutex::Autolock _l(mLock); 1166 // Loop through all sensors for this connection and call flush on each of them. 1167 for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) { 1168 const int handle = connection->mSensorInfo.keyAt(i); 1169 SensorInterface* sensor = mSensorMap.valueFor(handle); 1170 if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) { 1171 ALOGE("flush called on a one-shot sensor"); 1172 err = INVALID_OPERATION; 1173 continue; 1174 } 1175 if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) { 1176 // For older devices just increment pending flush count which will send a trivial 1177 // flush complete event. 1178 connection->incrementPendingFlushCount(handle); 1179 } else { 1180 if (!canAccessSensor(sensor->getSensor(), "Tried flushing", opPackageName)) { 1181 err = INVALID_OPERATION; 1182 continue; 1183 } 1184 status_t err_flush = sensor->flush(connection.get(), handle); 1185 if (err_flush == NO_ERROR) { 1186 SensorRecord* rec = mActiveSensors.valueFor(handle); 1187 if (rec != NULL) rec->addPendingFlushConnection(connection); 1188 } 1189 err = (err_flush != NO_ERROR) ? err_flush : err; 1190 } 1191 } 1192 return err; 1193} 1194 1195bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation, 1196 const String16& opPackageName) { 1197 const String8& requiredPermission = sensor.getRequiredPermission(); 1198 1199 if (requiredPermission.length() <= 0) { 1200 return true; 1201 } 1202 1203 bool hasPermission = false; 1204 1205 // Runtime permissions can't use the cache as they may change. 1206 if (sensor.isRequiredPermissionRuntime()) { 1207 hasPermission = checkPermission(String16(requiredPermission), 1208 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid()); 1209 } else { 1210 hasPermission = PermissionCache::checkCallingPermission(String16(requiredPermission)); 1211 } 1212 1213 if (!hasPermission) { 1214 ALOGE("%s a sensor (%s) without holding its required permission: %s", 1215 operation, sensor.getName().string(), sensor.getRequiredPermission().string()); 1216 return false; 1217 } 1218 1219 const int32_t opCode = sensor.getRequiredAppOp(); 1220 if (opCode >= 0) { 1221 AppOpsManager appOps; 1222 if (appOps.noteOp(opCode, IPCThreadState::self()->getCallingUid(), opPackageName) 1223 != AppOpsManager::MODE_ALLOWED) { 1224 ALOGE("%s a sensor (%s) without enabled required app op: %d", 1225 operation, sensor.getName().string(), opCode); 1226 return false; 1227 } 1228 } 1229 1230 return true; 1231} 1232 1233void SensorService::checkWakeLockState() { 1234 Mutex::Autolock _l(mLock); 1235 checkWakeLockStateLocked(); 1236} 1237 1238void SensorService::checkWakeLockStateLocked() { 1239 if (!mWakeLockAcquired) { 1240 return; 1241 } 1242 bool releaseLock = true; 1243 for (size_t i=0 ; i<mActiveConnections.size() ; i++) { 1244 sp<SensorEventConnection> connection(mActiveConnections[i].promote()); 1245 if (connection != 0) { 1246 if (connection->needsWakeLock()) { 1247 releaseLock = false; 1248 break; 1249 } 1250 } 1251 } 1252 if (releaseLock) { 1253 setWakeLockAcquiredLocked(false); 1254 } 1255} 1256 1257void SensorService::sendEventsFromCache(const sp<SensorEventConnection>& connection) { 1258 Mutex::Autolock _l(mLock); 1259 connection->writeToSocketFromCache(); 1260 if (connection->needsWakeLock()) { 1261 setWakeLockAcquiredLocked(true); 1262 } 1263} 1264 1265void SensorService::populateActiveConnections( 1266 SortedVector< sp<SensorEventConnection> >* activeConnections) { 1267 Mutex::Autolock _l(mLock); 1268 for (size_t i=0 ; i < mActiveConnections.size(); ++i) { 1269 sp<SensorEventConnection> connection(mActiveConnections[i].promote()); 1270 if (connection != 0) { 1271 activeConnections->add(connection); 1272 } 1273 } 1274} 1275 1276bool SensorService::isWhiteListedPackage(const String8& packageName) { 1277 return (packageName.contains(mWhiteListedPackage.string())); 1278} 1279 1280int SensorService::getNumEventsForSensorType(int sensor_event_type) { 1281 switch (sensor_event_type) { 1282 case SENSOR_TYPE_ROTATION_VECTOR: 1283 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR: 1284 return 5; 1285 1286 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED: 1287 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED: 1288 return 6; 1289 1290 case SENSOR_TYPE_GAME_ROTATION_VECTOR: 1291 return 4; 1292 1293 case SENSOR_TYPE_SIGNIFICANT_MOTION: 1294 case SENSOR_TYPE_STEP_DETECTOR: 1295 case SENSOR_TYPE_STEP_COUNTER: 1296 return 1; 1297 1298 default: 1299 return 3; 1300 } 1301} 1302 1303}; // namespace android 1304 1305