SensorService.cpp revision 90ed3e8d7883d9c80fb8bf11b1c593bd8b2b39d0
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 run("SensorService", PRIORITY_URGENT_DISPLAY); 152 mInitCheck = NO_ERROR; 153 } 154 } 155} 156 157Sensor SensorService::registerSensor(SensorInterface* s) 158{ 159 sensors_event_t event; 160 memset(&event, 0, sizeof(event)); 161 162 const Sensor sensor(s->getSensor()); 163 // add to the sensor list (returned to clients) 164 mSensorList.add(sensor); 165 // add to our handle->SensorInterface mapping 166 mSensorMap.add(sensor.getHandle(), s); 167 // create an entry in the mLastEventSeen array 168 mLastEventSeen.add(sensor.getHandle(), event); 169 170 return sensor; 171} 172 173Sensor SensorService::registerVirtualSensor(SensorInterface* s) 174{ 175 Sensor sensor = registerSensor(s); 176 mVirtualSensorList.add( s ); 177 return sensor; 178} 179 180SensorService::~SensorService() 181{ 182 for (size_t i=0 ; i<mSensorMap.size() ; i++) 183 delete mSensorMap.valueAt(i); 184} 185 186static const String16 sDump("android.permission.DUMP"); 187 188status_t SensorService::dump(int fd, const Vector<String16>& args) 189{ 190 String8 result; 191 if (!PermissionCache::checkCallingPermission(sDump)) { 192 result.appendFormat("Permission Denial: " 193 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", 194 IPCThreadState::self()->getCallingPid(), 195 IPCThreadState::self()->getCallingUid()); 196 } else { 197 Mutex::Autolock _l(mLock); 198 result.append("Sensor List:\n"); 199 for (size_t i=0 ; i<mSensorList.size() ; i++) { 200 const Sensor& s(mSensorList[i]); 201 const sensors_event_t& e(mLastEventSeen.valueFor(s.getHandle())); 202 result.appendFormat( 203 "%-48s| %-32s | 0x%08x | ", 204 s.getName().string(), 205 s.getVendor().string(), 206 s.getHandle()); 207 208 if (s.getMinDelay() > 0) { 209 result.appendFormat( 210 "maxRate=%7.2fHz | ", 1e6f / s.getMinDelay()); 211 } else { 212 result.append(s.getMinDelay() == 0 213 ? "on-demand | " 214 : "one-shot | "); 215 } 216 if (s.getFifoMaxEventCount() > 0) { 217 result.appendFormat("getFifoMaxEventCount=%d events | ", s.getFifoMaxEventCount()); 218 } else { 219 result.append("no batching support | "); 220 } 221 222 switch (s.getType()) { 223 case SENSOR_TYPE_ROTATION_VECTOR: 224 case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR: 225 result.appendFormat( 226 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n", 227 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4]); 228 break; 229 case SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED: 230 case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED: 231 result.appendFormat( 232 "last=<%5.1f,%5.1f,%5.1f,%5.1f,%5.1f,%5.1f>\n", 233 e.data[0], e.data[1], e.data[2], e.data[3], e.data[4], e.data[5]); 234 break; 235 case SENSOR_TYPE_GAME_ROTATION_VECTOR: 236 result.appendFormat( 237 "last=<%5.1f,%5.1f,%5.1f,%5.1f>\n", 238 e.data[0], e.data[1], e.data[2], e.data[3]); 239 break; 240 case SENSOR_TYPE_SIGNIFICANT_MOTION: 241 case SENSOR_TYPE_STEP_DETECTOR: 242 result.appendFormat( "last=<%f>\n", e.data[0]); 243 break; 244 case SENSOR_TYPE_STEP_COUNTER: 245 result.appendFormat( "last=<%llu>\n", e.u64.step_counter); 246 break; 247 default: 248 // default to 3 values 249 result.appendFormat( 250 "last=<%5.1f,%5.1f,%5.1f>\n", 251 e.data[0], e.data[1], e.data[2]); 252 break; 253 } 254 } 255 SensorFusion::getInstance().dump(result); 256 SensorDevice::getInstance().dump(result); 257 258 result.appendFormat("%d active connections\n", mActiveConnections.size()); 259 result.append("Active sensors:\n"); 260 for (size_t i=0 ; i<mActiveSensors.size() ; i++) { 261 int handle = mActiveSensors.keyAt(i); 262 result.appendFormat("%s (handle=0x%08x, connections=%d)\n", 263 getSensorName(handle).string(), 264 handle, 265 mActiveSensors.valueAt(i)->getNumConnections()); 266 } 267 } 268 write(fd, result.string(), result.size()); 269 return NO_ERROR; 270} 271 272void SensorService::cleanupAutoDisabledSensor(const sp<SensorEventConnection>& connection, 273 sensors_event_t const* buffer, const int count) { 274 SensorInterface* sensor; 275 status_t err = NO_ERROR; 276 for (int i=0 ; i<count ; i++) { 277 int handle = buffer[i].sensor; 278 int type = buffer[i].type; 279 if (type == SENSOR_TYPE_SIGNIFICANT_MOTION) { 280 if (connection->hasSensor(handle)) { 281 sensor = mSensorMap.valueFor(handle); 282 if (sensor != NULL) { 283 sensor->autoDisable(connection.get(), handle); 284 } 285 cleanupWithoutDisable(connection, handle); 286 } 287 } 288 } 289} 290 291bool SensorService::threadLoop() 292{ 293 ALOGD("nuSensorService thread starting..."); 294 295 // each virtual sensor could generate an event per "real" event, that's why we need 296 // to size numEventMax much smaller than MAX_RECEIVE_BUFFER_EVENT_COUNT. 297 // in practice, this is too aggressive, but guaranteed to be enough. 298 const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT; 299 const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size()); 300 301 sensors_event_t buffer[minBufferSize]; 302 sensors_event_t scratch[minBufferSize]; 303 SensorDevice& device(SensorDevice::getInstance()); 304 const size_t vcount = mVirtualSensorList.size(); 305 306 ssize_t count; 307 bool wakeLockAcquired = false; 308 const int halVersion = device.getHalDeviceVersion(); 309 do { 310 count = device.poll(buffer, numEventMax); 311 if (count<0) { 312 ALOGE("sensor poll failed (%s)", strerror(-count)); 313 break; 314 } 315 316 // Poll has returned. Hold a wakelock. 317 // Todo(): add a flag to the sensors definitions to indicate 318 // the sensors which can wake up the AP 319 for (int i = 0; i < count; i++) { 320 if (buffer[i].type == SENSOR_TYPE_SIGNIFICANT_MOTION) { 321 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME); 322 wakeLockAcquired = true; 323 break; 324 } 325 } 326 327 recordLastValue(buffer, count); 328 329 // handle virtual sensors 330 if (count && vcount) { 331 sensors_event_t const * const event = buffer; 332 const DefaultKeyedVector<int, SensorInterface*> virtualSensors( 333 getActiveVirtualSensors()); 334 const size_t activeVirtualSensorCount = virtualSensors.size(); 335 if (activeVirtualSensorCount) { 336 size_t k = 0; 337 SensorFusion& fusion(SensorFusion::getInstance()); 338 if (fusion.isEnabled()) { 339 for (size_t i=0 ; i<size_t(count) ; i++) { 340 fusion.process(event[i]); 341 } 342 } 343 for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) { 344 for (size_t j=0 ; j<activeVirtualSensorCount ; j++) { 345 if (count + k >= minBufferSize) { 346 ALOGE("buffer too small to hold all events: " 347 "count=%u, k=%u, size=%u", 348 count, k, minBufferSize); 349 break; 350 } 351 sensors_event_t out; 352 SensorInterface* si = virtualSensors.valueAt(j); 353 if (si->process(&out, event[i])) { 354 buffer[count + k] = out; 355 k++; 356 } 357 } 358 } 359 if (k) { 360 // record the last synthesized values 361 recordLastValue(&buffer[count], k); 362 count += k; 363 // sort the buffer by time-stamps 364 sortEventBuffer(buffer, count); 365 } 366 } 367 } 368 369 // handle backward compatibility for RotationVector sensor 370 if (halVersion < SENSORS_DEVICE_API_VERSION_1_0) { 371 for (int i = 0; i < count; i++) { 372 if (buffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) { 373 // All the 4 components of the quaternion should be available 374 // No heading accuracy. Set it to -1 375 buffer[i].data[4] = -1; 376 } 377 } 378 } 379 380 // send our events to clients... 381 const SortedVector< wp<SensorEventConnection> > activeConnections( 382 getActiveConnections()); 383 size_t numConnections = activeConnections.size(); 384 for (size_t i=0 ; i<numConnections ; i++) { 385 sp<SensorEventConnection> connection( 386 activeConnections[i].promote()); 387 if (connection != 0) { 388 connection->sendEvents(buffer, count, scratch); 389 // Some sensors need to be auto disabled after the trigger 390 cleanupAutoDisabledSensor(connection, buffer, count); 391 } 392 } 393 394 // We have read the data, upper layers should hold the wakelock. 395 if (wakeLockAcquired) release_wake_lock(WAKE_LOCK_NAME); 396 } while (count >= 0 || Thread::exitPending()); 397 398 ALOGW("Exiting SensorService::threadLoop => aborting..."); 399 abort(); 400 return false; 401} 402 403void SensorService::recordLastValue( 404 sensors_event_t const * buffer, size_t count) 405{ 406 Mutex::Autolock _l(mLock); 407 408 // record the last event for each sensor 409 int32_t prev = buffer[0].sensor; 410 for (size_t i=1 ; i<count ; i++) { 411 // record the last event of each sensor type in this buffer 412 int32_t curr = buffer[i].sensor; 413 if (curr != prev) { 414 mLastEventSeen.editValueFor(prev) = buffer[i-1]; 415 prev = curr; 416 } 417 } 418 mLastEventSeen.editValueFor(prev) = buffer[count-1]; 419} 420 421void SensorService::sortEventBuffer(sensors_event_t* buffer, size_t count) 422{ 423 struct compar { 424 static int cmp(void const* lhs, void const* rhs) { 425 sensors_event_t const* l = static_cast<sensors_event_t const*>(lhs); 426 sensors_event_t const* r = static_cast<sensors_event_t const*>(rhs); 427 return l->timestamp - r->timestamp; 428 } 429 }; 430 qsort(buffer, count, sizeof(sensors_event_t), compar::cmp); 431} 432 433SortedVector< wp<SensorService::SensorEventConnection> > 434SensorService::getActiveConnections() const 435{ 436 Mutex::Autolock _l(mLock); 437 return mActiveConnections; 438} 439 440DefaultKeyedVector<int, SensorInterface*> 441SensorService::getActiveVirtualSensors() const 442{ 443 Mutex::Autolock _l(mLock); 444 return mActiveVirtualSensors; 445} 446 447String8 SensorService::getSensorName(int handle) const { 448 size_t count = mUserSensorList.size(); 449 for (size_t i=0 ; i<count ; i++) { 450 const Sensor& sensor(mUserSensorList[i]); 451 if (sensor.getHandle() == handle) { 452 return sensor.getName(); 453 } 454 } 455 String8 result("unknown"); 456 return result; 457} 458 459Vector<Sensor> SensorService::getSensorList() 460{ 461 char value[PROPERTY_VALUE_MAX]; 462 property_get("debug.sensors", value, "0"); 463 if (atoi(value)) { 464 return mUserSensorListDebug; 465 } 466 return mUserSensorList; 467} 468 469sp<ISensorEventConnection> SensorService::createSensorEventConnection() 470{ 471 uid_t uid = IPCThreadState::self()->getCallingUid(); 472 sp<SensorEventConnection> result(new SensorEventConnection(this, uid)); 473 return result; 474} 475 476void SensorService::cleanupConnection(SensorEventConnection* c) 477{ 478 Mutex::Autolock _l(mLock); 479 const wp<SensorEventConnection> connection(c); 480 size_t size = mActiveSensors.size(); 481 ALOGD_IF(DEBUG_CONNECTIONS, "%d active sensors", size); 482 for (size_t i=0 ; i<size ; ) { 483 int handle = mActiveSensors.keyAt(i); 484 if (c->hasSensor(handle)) { 485 ALOGD_IF(DEBUG_CONNECTIONS, "%i: disabling handle=0x%08x", i, handle); 486 SensorInterface* sensor = mSensorMap.valueFor( handle ); 487 ALOGE_IF(!sensor, "mSensorMap[handle=0x%08x] is null!", handle); 488 if (sensor) { 489 sensor->activate(c, false); 490 } 491 } 492 SensorRecord* rec = mActiveSensors.valueAt(i); 493 ALOGE_IF(!rec, "mActiveSensors[%d] is null (handle=0x%08x)!", i, handle); 494 ALOGD_IF(DEBUG_CONNECTIONS, 495 "removing connection %p for sensor[%d].handle=0x%08x", 496 c, i, handle); 497 498 if (rec && rec->removeConnection(connection)) { 499 ALOGD_IF(DEBUG_CONNECTIONS, "... and it was the last connection"); 500 mActiveSensors.removeItemsAt(i, 1); 501 mActiveVirtualSensors.removeItem(handle); 502 delete rec; 503 size--; 504 } else { 505 i++; 506 } 507 } 508 mActiveConnections.remove(connection); 509 BatteryService::cleanup(c->getUid()); 510} 511 512status_t SensorService::enable(const sp<SensorEventConnection>& connection, 513 int handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags) 514{ 515 if (mInitCheck != NO_ERROR) 516 return mInitCheck; 517 518 SensorInterface* sensor = mSensorMap.valueFor(handle); 519 if (sensor == NULL) { 520 return BAD_VALUE; 521 } 522 Mutex::Autolock _l(mLock); 523 SensorRecord* rec = mActiveSensors.valueFor(handle); 524 if (rec == 0) { 525 rec = new SensorRecord(connection); 526 mActiveSensors.add(handle, rec); 527 if (sensor->isVirtual()) { 528 mActiveVirtualSensors.add(handle, sensor); 529 } 530 } else { 531 if (rec->addConnection(connection)) { 532 // this sensor is already activated, but we are adding a 533 // connection that uses it. Immediately send down the last 534 // known value of the requested sensor if it's not a 535 // "continuous" sensor. 536 if (sensor->getSensor().getMinDelay() == 0) { 537 sensors_event_t scratch; 538 sensors_event_t& event(mLastEventSeen.editValueFor(handle)); 539 if (event.version == sizeof(sensors_event_t)) { 540 connection->sendEvents(&event, 1); 541 } 542 } 543 } 544 } 545 546 if (connection->addSensor(handle)) { 547 BatteryService::enableSensor(connection->getUid(), handle); 548 // the sensor was added (which means it wasn't already there) 549 // so, see if this connection becomes active 550 if (mActiveConnections.indexOf(connection) < 0) { 551 mActiveConnections.add(connection); 552 } 553 } else { 554 ALOGW("sensor %08x already enabled in connection %p (ignoring)", 555 handle, connection.get()); 556 } 557 558 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs(); 559 if (samplingPeriodNs < minDelayNs) { 560 samplingPeriodNs = minDelayNs; 561 } 562 563 ALOGD_IF(DEBUG_CONNECTIONS, "Calling batch handle==%d flags=%d rate=%lld timeout== %lld", 564 handle, reservedFlags, samplingPeriodNs, maxBatchReportLatencyNs); 565 566 status_t err = sensor->batch(connection.get(), handle, reservedFlags, samplingPeriodNs, 567 maxBatchReportLatencyNs); 568 569 if (err == NO_ERROR) { 570 ALOGD_IF(DEBUG_CONNECTIONS, "Calling activate on %d", handle); 571 err = sensor->activate(connection.get(), true); 572 } 573 574 if (err != NO_ERROR) { 575 // batch/activate has failed, reset our state. 576 cleanupWithoutDisableLocked(connection, handle); 577 } 578 return err; 579} 580 581status_t SensorService::disable(const sp<SensorEventConnection>& connection, 582 int handle) 583{ 584 if (mInitCheck != NO_ERROR) 585 return mInitCheck; 586 587 Mutex::Autolock _l(mLock); 588 status_t err = cleanupWithoutDisableLocked(connection, handle); 589 if (err == NO_ERROR) { 590 SensorInterface* sensor = mSensorMap.valueFor(handle); 591 err = sensor ? sensor->activate(connection.get(), false) : status_t(BAD_VALUE); 592 } 593 return err; 594} 595 596status_t SensorService::cleanupWithoutDisable( 597 const sp<SensorEventConnection>& connection, int handle) { 598 Mutex::Autolock _l(mLock); 599 return cleanupWithoutDisableLocked(connection, handle); 600} 601 602status_t SensorService::cleanupWithoutDisableLocked( 603 const sp<SensorEventConnection>& connection, int handle) { 604 SensorRecord* rec = mActiveSensors.valueFor(handle); 605 if (rec) { 606 // see if this connection becomes inactive 607 if (connection->removeSensor(handle)) { 608 BatteryService::disableSensor(connection->getUid(), handle); 609 } 610 if (connection->hasAnySensor() == false) { 611 mActiveConnections.remove(connection); 612 } 613 // see if this sensor becomes inactive 614 if (rec->removeConnection(connection)) { 615 mActiveSensors.removeItem(handle); 616 mActiveVirtualSensors.removeItem(handle); 617 delete rec; 618 } 619 return NO_ERROR; 620 } 621 return BAD_VALUE; 622} 623 624status_t SensorService::setEventRate(const sp<SensorEventConnection>& connection, 625 int handle, nsecs_t ns) 626{ 627 if (mInitCheck != NO_ERROR) 628 return mInitCheck; 629 630 SensorInterface* sensor = mSensorMap.valueFor(handle); 631 if (!sensor) 632 return BAD_VALUE; 633 634 if (ns < 0) 635 return BAD_VALUE; 636 637 nsecs_t minDelayNs = sensor->getSensor().getMinDelayNs(); 638 if (ns < minDelayNs) { 639 ns = minDelayNs; 640 } 641 642 return sensor->setDelay(connection.get(), handle, ns); 643} 644 645status_t SensorService::flushSensor(const sp<SensorEventConnection>& connection, 646 int handle) { 647 if (mInitCheck != NO_ERROR) return mInitCheck; 648 SensorInterface* sensor = mSensorMap.valueFor(handle); 649 if (sensor == NULL) { 650 return BAD_VALUE; 651 } 652 return sensor->flush(connection.get(), handle); 653} 654// --------------------------------------------------------------------------- 655 656SensorService::SensorRecord::SensorRecord( 657 const sp<SensorEventConnection>& connection) 658{ 659 mConnections.add(connection); 660} 661 662bool SensorService::SensorRecord::addConnection( 663 const sp<SensorEventConnection>& connection) 664{ 665 if (mConnections.indexOf(connection) < 0) { 666 mConnections.add(connection); 667 return true; 668 } 669 return false; 670} 671 672bool SensorService::SensorRecord::removeConnection( 673 const wp<SensorEventConnection>& connection) 674{ 675 ssize_t index = mConnections.indexOf(connection); 676 if (index >= 0) { 677 mConnections.removeItemsAt(index, 1); 678 } 679 return mConnections.size() ? false : true; 680} 681 682// --------------------------------------------------------------------------- 683 684SensorService::SensorEventConnection::SensorEventConnection( 685 const sp<SensorService>& service, uid_t uid) 686 : mService(service), mChannel(new BitTube()), mUid(uid) 687{ 688} 689 690SensorService::SensorEventConnection::~SensorEventConnection() 691{ 692 ALOGD_IF(DEBUG_CONNECTIONS, "~SensorEventConnection(%p)", this); 693 mService->cleanupConnection(this); 694} 695 696void SensorService::SensorEventConnection::onFirstRef() 697{ 698} 699 700bool SensorService::SensorEventConnection::addSensor(int32_t handle) { 701 Mutex::Autolock _l(mConnectionLock); 702 if (mSensorInfo.indexOf(handle) < 0) { 703 mSensorInfo.add(handle); 704 return true; 705 } 706 return false; 707} 708 709bool SensorService::SensorEventConnection::removeSensor(int32_t handle) { 710 Mutex::Autolock _l(mConnectionLock); 711 if (mSensorInfo.remove(handle) >= 0) { 712 return true; 713 } 714 return false; 715} 716 717bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const { 718 Mutex::Autolock _l(mConnectionLock); 719 return mSensorInfo.indexOf(handle) >= 0; 720} 721 722bool SensorService::SensorEventConnection::hasAnySensor() const { 723 Mutex::Autolock _l(mConnectionLock); 724 return mSensorInfo.size() ? true : false; 725} 726 727status_t SensorService::SensorEventConnection::sendEvents( 728 sensors_event_t const* buffer, size_t numEvents, 729 sensors_event_t* scratch) 730{ 731 // filter out events not for this connection 732 size_t count = 0; 733 if (scratch) { 734 Mutex::Autolock _l(mConnectionLock); 735 size_t i=0; 736 while (i<numEvents) { 737 int32_t curr = buffer[i].sensor; 738 if (buffer[i].type == SENSOR_TYPE_META_DATA) { 739 ALOGD_IF(DEBUG_CONNECTIONS, "flush complete event sensor==%d ", 740 buffer[i].meta_data.sensor); 741 // Setting curr to the correct sensor to ensure the sensor events per connection are 742 // filtered correctly. buffer[i].sensor is zero for meta_data events. 743 curr = buffer[i].meta_data.sensor; 744 } 745 if (mSensorInfo.indexOf(curr) >= 0) { 746 do { 747 scratch[count] = buffer[i]; 748 ++count; ++i; 749 } while ((i<numEvents) && ((buffer[i].sensor == curr) || 750 (buffer[i].type == SENSOR_TYPE_META_DATA && 751 buffer[i].meta_data.sensor == curr))); 752 } else { 753 i++; 754 } 755 } 756 } else { 757 scratch = const_cast<sensors_event_t *>(buffer); 758 count = numEvents; 759 } 760 761 // NOTE: ASensorEvent and sensors_event_t are the same type 762 ssize_t size = SensorEventQueue::write(mChannel, 763 reinterpret_cast<ASensorEvent const*>(scratch), count); 764 if (size == -EAGAIN) { 765 // the destination doesn't accept events anymore, it's probably 766 // full. For now, we just drop the events on the floor. 767 //ALOGW("dropping %d events on the floor", count); 768 return size; 769 } 770 771 return size < 0 ? status_t(size) : status_t(NO_ERROR); 772} 773 774sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const 775{ 776 return mChannel; 777} 778 779status_t SensorService::SensorEventConnection::enableDisable( 780 int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, 781 int reservedFlags) 782{ 783 status_t err; 784 if (enabled) { 785 err = mService->enable(this, handle, samplingPeriodNs, maxBatchReportLatencyNs, 786 reservedFlags); 787 } else { 788 err = mService->disable(this, handle); 789 } 790 return err; 791} 792 793status_t SensorService::SensorEventConnection::setEventRate( 794 int handle, nsecs_t samplingPeriodNs) 795{ 796 return mService->setEventRate(this, handle, samplingPeriodNs); 797} 798 799status_t SensorService::SensorEventConnection::flushSensor(int handle) { 800 return mService->flushSensor(this, handle); 801} 802// --------------------------------------------------------------------------- 803}; // namespace android 804 805