SensorService.cpp revision 701166d9f60a6e1149ff568aec0e03f3f3925292
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 <stdint.h> 18#include <math.h> 19#include <sys/types.h> 20 21#include <cutils/properties.h> 22 23#include <utils/SortedVector.h> 24#include <utils/KeyedVector.h> 25#include <utils/threads.h> 26#include <utils/Atomic.h> 27#include <utils/Errors.h> 28#include <utils/RefBase.h> 29#include <utils/Singleton.h> 30#include <utils/String16.h> 31 32#include <binder/BinderService.h> 33#include <binder/IServiceManager.h> 34#include <binder/PermissionCache.h> 35 36#include <gui/ISensorServer.h> 37#include <gui/ISensorEventConnection.h> 38#include <gui/SensorEventQueue.h> 39 40#include <hardware/sensors.h> 41#include <hardware_legacy/power.h> 42 43#include "BatteryService.h" 44#include "CorrectedGyroSensor.h" 45#include "GravitySensor.h" 46#include "LinearAccelerationSensor.h" 47#include "OrientationSensor.h" 48#include "RotationVectorSensor.h" 49#include "SensorFusion.h" 50#include "SensorService.h" 51 52namespace android { 53// --------------------------------------------------------------------------- 54 55/* 56 * Notes: 57 * 58 * - what about a gyro-corrected magnetic-field sensor? 59 * - run mag sensor from time to time to force calibration 60 * - gravity sensor length is wrong (=> drift in linear-acc sensor) 61 * 62 */ 63 64const char* SensorService::WAKE_LOCK_NAME = "SensorService"; 65 66SensorService::SensorService() 67 : mInitCheck(NO_INIT) 68{ 69} 70 71void SensorService::onFirstRef() 72{ 73 ALOGD("nuSensorService starting..."); 74 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; 83 uint32_t virtualSensorsNeeds = 84 (1<<SENSOR_TYPE_GRAVITY) | 85 (1<<SENSOR_TYPE_LINEAR_ACCELERATION) | 86 (1<<SENSOR_TYPE_ROTATION_VECTOR); 87 88 mLastEventSeen.setCapacity(count); 89 for (ssize_t i=0 ; i<count ; i++) { 90 registerSensor( new HardwareSensor(list[i]) ); 91 switch (list[i].type) { 92 case SENSOR_TYPE_ORIENTATION: 93 orientationIndex = i; 94 break; 95 case SENSOR_TYPE_GYROSCOPE: 96 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED: 97 hasGyro = true; 98 break; 99 case SENSOR_TYPE_GRAVITY: 100 case SENSOR_TYPE_LINEAR_ACCELERATION: 101 case SENSOR_TYPE_ROTATION_VECTOR: 102 virtualSensorsNeeds &= ~(1<<list[i].type); 103 break; 104 } 105 } 106 107 // it's safe to instantiate the SensorFusion object here 108 // (it wants to be instantiated after h/w sensors have been 109 // registered) 110 const SensorFusion& fusion(SensorFusion::getInstance()); 111 112 // build the sensor list returned to users 113 mUserSensorList = mSensorList; 114 115 if (hasGyro) { 116 Sensor aSensor; 117 118 // Add Android virtual sensors if they're not already 119 // available in the HAL 120 121 aSensor = registerVirtualSensor( new RotationVectorSensor() ); 122 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) { 123 mUserSensorList.add(aSensor); 124 } 125 126 aSensor = registerVirtualSensor( new GravitySensor(list, count) ); 127 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) { 128 mUserSensorList.add(aSensor); 129 } 130 131 aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) ); 132 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) { 133 mUserSensorList.add(aSensor); 134 } 135 136 aSensor = registerVirtualSensor( new OrientationSensor() ); 137 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) { 138 // if we are doing our own rotation-vector, also add 139 // the orientation sensor and remove the HAL provided one. 140 mUserSensorList.replaceAt(aSensor, orientationIndex); 141 } 142 143 // virtual debugging sensors are not added to mUserSensorList 144 registerVirtualSensor( new CorrectedGyroSensor(list, count) ); 145 registerVirtualSensor( new GyroDriftSensor() ); 146 } 147 148 // debugging sensor list 149 mUserSensorListDebug = mSensorList; 150 151 mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED; 152 FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r"); 153 char line[128]; 154 if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) { 155 line[sizeof(line) - 1] = '\0'; 156 sscanf(line, "%u", &mSocketBufferSize); 157 if (mSocketBufferSize > MAX_SOCKET_BUFFER_SIZE_BATCHED) { 158 mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED; 159 } 160 } 161 ALOGD("Max socket buffer size %u", mSocketBufferSize); 162 if (fp) { 163 fclose(fp); 164 } 165 166 run("SensorService", PRIORITY_URGENT_DISPLAY); 167 mInitCheck = NO_ERROR; 168 } 169 } 170} 171 172Sensor SensorService::registerSensor(SensorInterface* s) 173{ 174 sensors_event_t event; 175 memset(&event, 0, sizeof(event)); 176 177 const Sensor sensor(s->getSensor()); 178 // add to the sensor list (returned to clients) 179 mSensorList.add(sensor); 180 // add to our handle->SensorInterface mapping 181 mSensorMap.add(sensor.getHandle(), s); 182 // create an entry in the mLastEventSeen array 183 mLastEventSeen.add(sensor.getHandle(), event); 184 185 return sensor; 186} 187 188Sensor SensorService::registerVirtualSensor(SensorInterface* s) 189{ 190 Sensor sensor = registerSensor(s); 191 mVirtualSensorList.add( s ); 192 return sensor; 193} 194 195SensorService::~SensorService() 196{ 197 for (size_t i=0 ; i<mSensorMap.size() ; i++) 198 delete mSensorMap.valueAt(i); 199} 200 201static const String16 sDump("android.permission.DUMP"); 202 203status_t SensorService::dump(int fd, const Vector<String16>& args) 204{ 205 String8 result; 206 if (!PermissionCache::checkCallingPermission(sDump)) { 207 result.appendFormat("Permission Denial: " 208 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", 209 IPCThreadState::self()->getCallingPid(), 210 IPCThreadState::self()->getCallingUid()); 211 } else { 212 Mutex::Autolock _l(mLock); 213 result.append("Sensor List:\n"); 214 for (size_t i=0 ; i<mSensorList.size() ; i++) { 215 const Sensor& s(mSensorList[i]); 216 const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle())); 217 result.appendFormat( 218 "%-48s| %-32s | 0x%08x | ", 219 s.getName().string(), 220 s.getVendor().string(), 221 s.getHandle()); 222 223 if (s.getMinDelay() > 0) { 224 result.appendFormat( 225 "maxRate=%7.2fHz | ", 1e6f / s.getMinDelay()); 226 } else { 227 result.append(s.getMinDelay() == 0 228 ? "on-demand | " 229 : "one-shot | "); 230 } 231 if (s.getFifoMaxEventCount() > 0) { 232 result.appendFormat("getFifoMaxEventCount=%d events | ", s.getFifoMaxEventCount()); 233 } else { 234 result.append("no batching support | "); 235 } 236 237 switch (s.getType()) { 238 case SENSOR_TYPE_ROTATION_VECTOR: 239 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR: 240 result.appendFormat( 241 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n", 242 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4]); 243 break; 244 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED: 245 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED: 246 result.appendFormat( 247 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n", 248 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5]); 249 break; 250 case SENSOR_TYPE_GAME_ROTATION_VECTOR: 251 result.appendFormat( 252 "last=<%5.1f,%5.1f,%5.1f,%5.1f>\n", 253 e.data[0], e.data[1], e.data[2], e.data[3]); 254 break; 255 case SENSOR_TYPE_SIGNIFICANT_MOTION: 256 case SENSOR_TYPE_STEP_DETECTOR: 257 result.appendFormat( "last=<%f>\n", e.data[0]); 258 break; 259 case SENSOR_TYPE_STEP_COUNTER: 260 result.appendFormat( "last=<%llu>\n", e.u64.step_counter); 261 break; 262 default: 263 // default to 3 values 264 result.appendFormat( 265 "last=<%5.1f,%5.1f,%5.1f>\n", 266 e.data[0], e.data[1], e.data[2]); 267 break; 268 } 269 } 270 SensorFusion::getInstance().dump(result); 271 SensorDevice::getInstance().dump(result); 272 273 result.append("Active sensors:\n"); 274 for (size_t i=0 ; i<mActiveSensors.size() ; i++) { 275 int handle = mActiveSensors.keyAt(i); 276 result.appendFormat("%s (handle=0x%08x, connections=%d)\n", 277 getSensorName(handle).string(), 278 handle, 279 mActiveSensors.valueAt(i)->getNumConnections()); 280 } 281 282 result.appendFormat("%u Max Socket Buffer size\n", mSocketBufferSize); 283 result.appendFormat("%d active connections\n", mActiveConnections.size()); 284 285 for (size_t i=0 ; i < mActiveConnections.size() ; i++) { 286 sp<SensorEventConnection> connection(mActiveConnections[i].promote()); 287 if (connection != 0) { 288 result.appendFormat("Connection Number: %d \n", i); 289 connection->dump(result); 290 } 291 } 292 } 293 write(fd, result.string(), result.size()); 294 return NO_ERROR; 295} 296 297void SensorService::cleanupAutoDisabledSensor(const sp<SensorEventConnection>& connection, 298 sensors_event_t const* buffer, const int count) { 299 SensorInterface* sensor; 300 status_t err = NO_ERROR; 301 for (int i=0 ; i<count ; i++) { 302 int handle = buffer[i].sensor; 303 int type = buffer[i].type; 304 if (type == SENSOR_TYPE_SIGNIFICANT_MOTION) { 305 if (connection->hasSensor(handle)) { 306 sensor = mSensorMap.valueFor(handle); 307 if (sensor != NULL) { 308 sensor->autoDisable(connection.get(), handle); 309 } 310 cleanupWithoutDisable(connection, handle); 311 } 312 } 313 } 314} 315 316bool SensorService::threadLoop() 317{ 318 ALOGD("nuSensorService thread starting..."); 319 320 // each virtual sensor could generate an event per "real" event, that's why we need 321 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. 322 // in practice, this is too aggressive, but guaranteed to be enough. 323 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT; 324 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size()); 325 326 sensors_event_t buffer[minBufferSize]; 327 sensors_event_t scratch[minBufferSize]; 328 SensorDevice& device(SensorDevice::getInstance()); 329 const size_t vcount = mVirtualSensorList.size(); 330 331 ssize_t count; 332 bool wakeLockAcquired = false; 333 const int halVersion = device.getHalDeviceVersion(); 334 do { 335 count = device.poll(buffer, numEventMax); 336 if (count<0) { 337 ALOGE("sensor poll failed (%s)", strerror(-count)); 338 break; 339 } 340 341 // Poll has returned. Hold a wakelock. 342 // Todo(): add a flag to the sensors definitions to indicate 343 // the sensors which can wake up the AP 344 for (int i = 0; i < count; i++) { 345 if (buffer[i].type == SENSOR_TYPE_SIGNIFICANT_MOTION) { 346 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME); 347 wakeLockAcquired = true; 348 break; 349 } 350 } 351 352 recordLastValue(buffer, count); 353 354 // handle virtual sensors 355 if (count && vcount) { 356 sensors_event_t const * const event = buffer; 357 const DefaultKeyedVector<int, SensorInterface*> virtualSensors( 358 getActiveVirtualSensors()); 359 const size_t activeVirtualSensorCount = virtualSensors.size(); 360 if (activeVirtualSensorCount) { 361 size_t k = 0; 362 SensorFusion& fusion(SensorFusion::getInstance()); 363 if (fusion.isEnabled()) { 364 for (size_t i=0 ; i<size_t(count) ; i++) { 365 fusion.process(event[i]); 366 } 367 } 368 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) { 369 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) { 370 if (count + k >= minBufferSize) { 371 ALOGE("buffer too small to hold all events: " 372 "count=%u, k=%u, size=%u", 373 count, k, minBufferSize); 374 break; 375 } 376 sensors_event_t out; 377 SensorInterface* si = virtualSensors.valueAt(j); 378 if (si->process(&out, event[i])) { 379 buffer[count + k] = out; 380 k++; 381 } 382 } 383 } 384 if (k) { 385 // record the last synthesized values 386 recordLastValue(&buffer[count], k); 387 count += k; 388 // sort the buffer by time-stamps 389 sortEventBuffer(buffer, count); 390 } 391 } 392 } 393 394 // handle backward compatibility for RotationVector sensor 395 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) { 396 for (int i = 0; i < count; i++) { 397 if (buffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) { 398 // All the 4 components of the quaternion should be available 399 // No heading accuracy. Set it to -1 400 buffer[i].data[4] = -1; 401 } 402 } 403 } 404 405 // send our events to clients... 406 const SortedVector< wp<SensorEventConnection> > activeConnections( 407 getActiveConnections()); 408 size_t numConnections = activeConnections.size(); 409 for (size_t i=0 ; i<numConnections ; i++) { 410 sp<SensorEventConnection> connection( 411 activeConnections[i].promote()); 412 if (connection != 0) { 413 connection->sendEvents(buffer, count, scratch); 414 // Some sensors need to be auto disabled after the trigger 415 cleanupAutoDisabledSensor(connection, buffer, count); 416 } 417 } 418 419 // We have read the data, upper layers should hold the wakelock. 420 if (wakeLockAcquired) release_wake_lock(WAKE_LOCK_NAME); 421 } while (count >= 0 || Thread::exitPending()); 422 423 ALOGW("Exiting SensorService::threadLoop => aborting..."); 424 abort(); 425 return false; 426} 427 428void SensorService::recordLastValue( 429 sensors_event_t const * buffer, size_t count) 430{ 431 Mutex::Autolock _l(mLock); 432 // record the last event for each sensor 433 int32_t prev = buffer[0].sensor; 434 for (size_t i=1 ; i<count ; i++) { 435 // record the last event of each sensor type in this buffer 436 int32_t curr = buffer[i].sensor; 437 if (curr != prev) { 438 mLastEventSeen.editValueFor(prev) = buffer[i-1]; 439 prev = curr; 440 } 441 } 442 mLastEventSeen.editValueFor(prev) = buffer[count-1]; 443} 444 445void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) 446{ 447 struct compar { 448 static int cmp(void const* lhs, void const* rhs) { 449 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs); 450 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs); 451 return l->timestamp - r->timestamp; 452 } 453 }; 454 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp); 455} 456 457SortedVector< wp<SensorService::SensorEventConnection> > 458SensorService::getActiveConnections() const 459{ 460 Mutex::Autolock _l(mLock); 461 return mActiveConnections; 462} 463 464DefaultKeyedVector<int, SensorInterface*> 465SensorService::getActiveVirtualSensors() const 466{ 467 Mutex::Autolock _l(mLock); 468 return mActiveVirtualSensors; 469} 470 471String8 SensorService::getSensorName(int handle) const { 472 size_t count = mUserSensorList.size(); 473 for (size_t i=0 ; i<count ; i++) { 474 const Sensor& sensor(mUserSensorList[i]); 475 if (sensor.getHandle() == handle) { 476 return sensor.getName(); 477 } 478 } 479 String8 result("unknown"); 480 return result; 481} 482 483Vector<Sensor> SensorService::getSensorList() 484{ 485 char value[PROPERTY_VALUE_MAX]; 486 property_get("debug.sensors", value, "0"); 487 if (atoi(value)) { 488 return mUserSensorListDebug; 489 } 490 return mUserSensorList; 491} 492 493sp<ISensorEventConnection> SensorService::createSensorEventConnection() 494{ 495 uid_t uid = IPCThreadState::self()->getCallingUid(); 496 sp<SensorEventConnection> result(new SensorEventConnection(this, uid)); 497 return result; 498} 499 500void SensorService::cleanupConnection(SensorEventConnection* c) 501{ 502 Mutex::Autolock _l(mLock); 503 const wp<SensorEventConnection> connection(c); 504 size_t size = mActiveSensors.size(); 505 ALOGD_IF(DEBUG_CONNECTIONS, "%d active sensors", size); 506 for (size_t i=0 ; i<size ; ) { 507 int handle = mActiveSensors.keyAt(i); 508 if (c->hasSensor(handle)) { 509 ALOGD_IF(DEBUG_CONNECTIONS, "%i: disabling handle=0x%08x", i, handle); 510 SensorInterface* sensor = mSensorMap.valueFor( handle ); 511 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle); 512 if (sensor) { 513 sensor->activate(c, false); 514 } 515 } 516 SensorRecord* rec = mActiveSensors.valueAt(i); 517 ALOGE_IF(!rec, "mActiveSensors[%d] is null (handle=0x%08x)!", i, handle); 518 ALOGD_IF(DEBUG_CONNECTIONS, 519 "removing connection %p for sensor[%d].handle=0x%08x", 520 c, i, handle); 521 522 if (rec && rec->removeConnection(connection)) { 523 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection"); 524 mActiveSensors.removeItemsAt(i, 1); 525 mActiveVirtualSensors.removeItem(handle); 526 delete rec; 527 size--; 528 } else { 529 i++; 530 } 531 } 532 mActiveConnections.remove(connection); 533 BatteryService::cleanup(c->getUid()); 534} 535 536status_t SensorService::enable(const sp<SensorEventConnection>& connection, 537 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags) 538{ 539 if (mInitCheck != NO_ERROR) 540 return mInitCheck; 541 542 SensorInterface* sensor = mSensorMap.valueFor(handle); 543 if (sensor == NULL) { 544 return BAD_VALUE; 545 } 546 Mutex::Autolock _l(mLock); 547 SensorRecord* rec = mActiveSensors.valueFor(handle); 548 if (rec == 0) { 549 rec = new SensorRecord(connection); 550 mActiveSensors.add(handle, rec); 551 if (sensor->isVirtual()) { 552 mActiveVirtualSensors.add(handle, sensor); 553 } 554 } else { 555 if (rec->addConnection(connection)) { 556 // this sensor is already activated, but we are adding a 557 // connection that uses it. Immediately send down the last 558 // known value of the requested sensor if it's not a 559 // "continuous" sensor. 560 if (sensor->getSensor().getMinDelay() == 0) { 561 sensors_event_t scratch; 562 sensors_event_t& event(mLastEventSeen.editValueFor(handle)); 563 if (event.version == sizeof(sensors_event_t)) { 564 connection->sendEvents(&event, 1); 565 } 566 } 567 } 568 } 569 570 if (connection->addSensor(handle)) { 571 BatteryService::enableSensor(connection->getUid(), handle); 572 // the sensor was added (which means it wasn't already there) 573 // so, see if this connection becomes active 574 if (mActiveConnections.indexOf(connection) < 0) { 575 mActiveConnections.add(connection); 576 } 577 } else { 578 ALOGW("sensor %08x already enabled in connection %p (ignoring)", 579 handle, connection.get()); 580 } 581 582 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs(); 583 if (samplingPeriodNs < minDelayNs) { 584 samplingPeriodNs = minDelayNs; 585 } 586 587 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d rate=%lld timeout== %lld", 588 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs); 589 590 status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs, 591 maxBatchReportLatencyNs); 592 if (err == NO_ERROR) { 593 connection->setFirstFlushPending(handle, true); 594 status_t err_flush = sensor->flush(connection.get(), handle); 595 // Flush may return error if the sensor is not activated or the underlying h/w sensor does 596 // not support flush. 597 if (err_flush != NO_ERROR) { 598 connection->setFirstFlushPending(handle, false); 599 } 600 } 601 602 if (err == NO_ERROR) { 603 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle); 604 err = sensor->activate(connection.get(), true); 605 } 606 607 if (err != NO_ERROR) { 608 // batch/activate has failed, reset our state. 609 cleanupWithoutDisableLocked(connection, handle); 610 } 611 return err; 612} 613 614status_t SensorService::disable(const sp<SensorEventConnection>& connection, 615 int handle) 616{ 617 if (mInitCheck != NO_ERROR) 618 return mInitCheck; 619 620 Mutex::Autolock _l(mLock); 621 status_t err = cleanupWithoutDisableLocked(connection, handle); 622 if (err == NO_ERROR) { 623 SensorInterface* sensor = mSensorMap.valueFor(handle); 624 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE); 625 } 626 return err; 627} 628 629status_t SensorService::cleanupWithoutDisable( 630 const sp<SensorEventConnection>& connection, int handle) { 631 Mutex::Autolock _l(mLock); 632 return cleanupWithoutDisableLocked(connection, handle); 633} 634 635status_t SensorService::cleanupWithoutDisableLocked( 636 const sp<SensorEventConnection>& connection, int handle) { 637 SensorRecord* rec = mActiveSensors.valueFor(handle); 638 if (rec) { 639 // see if this connection becomes inactive 640 if (connection->removeSensor(handle)) { 641 BatteryService::disableSensor(connection->getUid(), handle); 642 } 643 if (connection->hasAnySensor() == false) { 644 mActiveConnections.remove(connection); 645 } 646 // see if this sensor becomes inactive 647 if (rec->removeConnection(connection)) { 648 mActiveSensors.removeItem(handle); 649 mActiveVirtualSensors.removeItem(handle); 650 delete rec; 651 } 652 return NO_ERROR; 653 } 654 return BAD_VALUE; 655} 656 657status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection, 658 int handle, nsecs_t ns) 659{ 660 if (mInitCheck != NO_ERROR) 661 return mInitCheck; 662 663 SensorInterface* sensor = mSensorMap.valueFor(handle); 664 if (!sensor) 665 return BAD_VALUE; 666 667 if (ns < 0) 668 return BAD_VALUE; 669 670 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs(); 671 if (ns < minDelayNs) { 672 ns = minDelayNs; 673 } 674 675 return sensor->setDelay(connection.get(), handle, ns); 676} 677 678status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection, 679 int handle) { 680 if (mInitCheck != NO_ERROR) return mInitCheck; 681 SensorInterface* sensor = mSensorMap.valueFor(handle); 682 if (sensor == NULL) { 683 return BAD_VALUE; 684 } 685 if (sensor->getSensor().getType() == SENSOR_TYPE_SIGNIFICANT_MOTION) { 686 ALOGE("flush called on Significant Motion sensor"); 687 return INVALID_OPERATION; 688 } 689 SensorDevice& dev(SensorDevice::getInstance()); 690 691 if (dev.getHalDeviceVersion() < SENSORS_DEVICE_API_VERSION_1_1) { 692 // For older devices increment pending flush count, which will send a trivial flush complete 693 // event for all the connections which are registered for updates on this sensor. 694 const SortedVector< wp<SensorEventConnection> > activeConnections( 695 getActiveConnections()); 696 for (size_t i=0 ; i<activeConnections.size() ; i++) { 697 sp<SensorEventConnection> connection(activeConnections[i].promote()); 698 if (connection != 0) { 699 connection->incrementPendingFlushCount(handle); 700 } 701 } 702 return NO_ERROR; 703 } 704 return sensor->flush(connection.get(), handle); 705} 706// --------------------------------------------------------------------------- 707 708SensorService::SensorRecord::SensorRecord( 709 const sp<SensorEventConnection>& connection) 710{ 711 mConnections.add(connection); 712} 713 714bool SensorService::SensorRecord::addConnection( 715 const sp<SensorEventConnection>& connection) 716{ 717 if (mConnections.indexOf(connection) < 0) { 718 mConnections.add(connection); 719 return true; 720 } 721 return false; 722} 723 724bool SensorService::SensorRecord::removeConnection( 725 const wp<SensorEventConnection>& connection) 726{ 727 ssize_t index = mConnections.indexOf(connection); 728 if (index >= 0) { 729 mConnections.removeItemsAt(index, 1); 730 } 731 return mConnections.size() ? false : true; 732} 733 734// --------------------------------------------------------------------------- 735 736SensorService::SensorEventConnection::SensorEventConnection( 737 const sp<SensorService>& service, uid_t uid) 738 : mService(service), mUid(uid) 739{ 740 const SensorDevice& device(SensorDevice::getInstance()); 741 if (device.getHalDeviceVersion() >= SENSORS_DEVICE_API_VERSION_1_1) { 742 // Increase socket buffer size to 1MB for batching capabilities. 743 mChannel = new BitTube(service->mSocketBufferSize); 744 } else { 745 mChannel = new BitTube(SOCKET_BUFFER_SIZE_NON_BATCHED); 746 } 747} 748 749SensorService::SensorEventConnection::~SensorEventConnection() 750{ 751 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this); 752 mService->cleanupConnection(this); 753} 754 755void SensorService::SensorEventConnection::onFirstRef() 756{ 757} 758 759void SensorService::SensorEventConnection::dump(String8& result) { 760 Mutex::Autolock _l(mConnectionLock); 761 for (size_t i = 0; i < mSensorInfo.size(); ++i) { 762 const FlushInfo& flushInfo = mSensorInfo.valueAt(i); 763 result.appendFormat("\t %s | status: %s | pending flush events %d\n", 764 mService->getSensorName(mSensorInfo.keyAt(i)).string(), 765 flushInfo.mFirstFlushPending ? "First flush pending" : 766 "active", 767 flushInfo.mPendingFlushEventsToSend); 768 } 769} 770 771bool SensorService::SensorEventConnection::addSensor(int32_t handle) { 772 Mutex::Autolock _l(mConnectionLock); 773 if (mSensorInfo.indexOfKey(handle) < 0) { 774 mSensorInfo.add(handle, FlushInfo()); 775 return true; 776 } 777 return false; 778} 779 780bool SensorService::SensorEventConnection::removeSensor(int32_t handle) { 781 Mutex::Autolock _l(mConnectionLock); 782 if (mSensorInfo.removeItem(handle) >= 0) { 783 return true; 784 } 785 return false; 786} 787 788bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const { 789 Mutex::Autolock _l(mConnectionLock); 790 return mSensorInfo.indexOfKey(handle) >= 0; 791} 792 793bool SensorService::SensorEventConnection::hasAnySensor() const { 794 Mutex::Autolock _l(mConnectionLock); 795 return mSensorInfo.size() ? true : false; 796} 797 798void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle, 799 bool value) { 800 Mutex::Autolock _l(mConnectionLock); 801 ssize_t index = mSensorInfo.indexOfKey(handle); 802 if (index >= 0) { 803 FlushInfo& flushInfo = mSensorInfo.editValueAt(index); 804 flushInfo.mFirstFlushPending = value; 805 } 806} 807 808void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) { 809 Mutex::Autolock _l(mConnectionLock); 810 ssize_t index = mSensorInfo.indexOfKey(handle); 811 if (index >= 0) { 812 FlushInfo& flushInfo = mSensorInfo.editValueAt(index); 813 flushInfo.mPendingFlushEventsToSend++; 814 } 815} 816 817status_t SensorService::SensorEventConnection::sendEvents( 818 sensors_event_t const* buffer, size_t numEvents, 819 sensors_event_t* scratch) 820{ 821 // filter out events not for this connection 822 size_t count = 0; 823 824 if (scratch) { 825 Mutex::Autolock _l(mConnectionLock); 826 size_t i=0; 827 while (i<numEvents) { 828 int32_t curr = buffer[i].sensor; 829 if (buffer[i].type == SENSOR_TYPE_META_DATA) { 830 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ", 831 buffer[i].meta_data.sensor); 832 // Setting curr to the correct sensor to ensure the sensor events per connection are 833 // filtered correctly. buffer[i].sensor is zero for meta_data events. 834 curr = buffer[i].meta_data.sensor; 835 } 836 ssize_t index = mSensorInfo.indexOfKey(curr); 837 if (index >= 0 && mSensorInfo[index].mFirstFlushPending == true && 838 buffer[i].type == SENSOR_TYPE_META_DATA) { 839 // This is the first flush before activate is called. Events can now be sent for 840 // this sensor on this connection. 841 ALOGD_IF(DEBUG_CONNECTIONS, "First flush event for sensor==%d ", 842 buffer[i].meta_data.sensor); 843 mSensorInfo.editValueAt(index).mFirstFlushPending = false; 844 } 845 if (index >= 0 && mSensorInfo[index].mFirstFlushPending == false) { 846 do { 847 scratch[count++] = buffer[i++]; 848 } while ((i<numEvents) && ((buffer[i].sensor == curr) || 849 (buffer[i].type == SENSOR_TYPE_META_DATA && 850 buffer[i].meta_data.sensor == curr))); 851 } else { 852 i++; 853 } 854 } 855 } else { 856 scratch = const_cast<sensors_event_t *>(buffer); 857 count = numEvents; 858 } 859 860 // Send pending flush events (if any) before sending events from the cache. 861 { 862 ASensorEvent flushCompleteEvent; 863 flushCompleteEvent.type = SENSOR_TYPE_META_DATA; 864 flushCompleteEvent.sensor = 0; 865 Mutex::Autolock _l(mConnectionLock); 866 // Loop through all the sensors for this connection and check if there are any pending 867 // flush complete events to be sent. 868 for (size_t i = 0; i < mSensorInfo.size(); ++i) { 869 FlushInfo& flushInfo = mSensorInfo.editValueAt(i); 870 while (flushInfo.mPendingFlushEventsToSend > 0) { 871 flushCompleteEvent.meta_data.sensor = mSensorInfo.keyAt(i); 872 ssize_t size = SensorEventQueue::write(mChannel, &flushCompleteEvent, 1); 873 if (size < 0) { 874 // ALOGW("dropping %d events on the floor", count); 875 countFlushCompleteEvents(scratch, count); 876 return size; 877 } 878 ALOGD_IF(DEBUG_CONNECTIONS, "sent dropped flush complete event==%d ", 879 flushCompleteEvent.meta_data.sensor); 880 flushInfo.mPendingFlushEventsToSend--; 881 } 882 } 883 } 884 885 // NOTE: ASensorEvent and sensors_event_t are the same type 886 ssize_t size = SensorEventQueue::write(mChannel, 887 reinterpret_cast<ASensorEvent const*>(scratch), count); 888 if (size == -EAGAIN) { 889 // the destination doesn't accept events anymore, it's probably 890 // full. For now, we just drop the events on the floor. 891 // ALOGW("dropping %d events on the floor", count); 892 countFlushCompleteEvents(scratch, count); 893 return size; 894 } 895 896 return size < 0 ? status_t(size) : status_t(NO_ERROR); 897} 898 899void SensorService::SensorEventConnection::countFlushCompleteEvents( 900 sensors_event_t* scratch, const int numEventsDropped) { 901 ALOGD_IF(DEBUG_CONNECTIONS, "dropping %d events ", numEventsDropped); 902 Mutex::Autolock _l(mConnectionLock); 903 // Count flushComplete events in the events that are about to the dropped. These will be sent 904 // separately before the next batch of events. 905 for (int j = 0; j < numEventsDropped; ++j) { 906 if (scratch[j].type == SENSOR_TYPE_META_DATA) { 907 FlushInfo& flushInfo = mSensorInfo.editValueFor(scratch[j].meta_data.sensor); 908 flushInfo.mPendingFlushEventsToSend++; 909 ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d", 910 flushInfo.mPendingFlushEventsToSend); 911 } 912 } 913 return; 914} 915 916sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const 917{ 918 return mChannel; 919} 920 921status_t SensorService::SensorEventConnection::enableDisable( 922 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, 923 int reservedFlags) 924{ 925 status_t err; 926 if (enabled) { 927 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs, 928 reservedFlags); 929 } else { 930 err = mService->disable(this, handle); 931 } 932 return err; 933} 934 935status_t SensorService::SensorEventConnection::setEventRate( 936 int handle, nsecs_t samplingPeriodNs) 937{ 938 return mService->setEventRate(this, handle, samplingPeriodNs); 939} 940 941status_t SensorService::SensorEventConnection::flush() { 942 Mutex::Autolock _l(mConnectionLock); 943 status_t err(NO_ERROR); 944 for (size_t i = 0; i < mSensorInfo.size(); ++i) { 945 const int handle = mSensorInfo.keyAt(i); 946 status_t err_flush = mService->flushSensor(this, handle); 947 if (err_flush != NO_ERROR) { 948 ALOGE("Flush error handle=%d %s", handle, strerror(-err_flush)); 949 } 950 err = (err_flush != NO_ERROR) ? err_flush : err; 951 } 952 return err; 953} 954 955// --------------------------------------------------------------------------- 956}; // namespace android 957 958