当前位置:   article > 正文

SensorService启动分析_sensorservice::publishandjointhreadpool

sensorservice::publishandjointhreadpool

首先看下sensor的一个整体大概架构图:



4.0中sensor是以一个service 的方式启动的

在base\cmds\sensorservice\main_sensorservice.cpp

  1. #include <binder/BinderService.h>
  2. #include <SensorService.h>
  3. using namespace android;
  4. int main(int argc, char** argv) {
  5. SensorService::publishAndJoinThreadPool();
  6. return 0;
  7. }
  8. static void publishAndJoinThreadPool(bool allowIsolated = false) {
  9. sp<IServiceManager> sm(defaultServiceManager());
  10. sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);
  11. ProcessState::self()->startThreadPool();
  12. IPCThreadState::self()->joinThreadPool();
  13. }

主要是new了一个service并添加到ServiceManager,然后启动线程池

在add service的过程中会调用SensorService的onFirstRef

  1. void SensorService::onFirstRef()
  2. {
  3. ALOGD("nuSensorService starting...");
  4. SensorDevice& dev(SensorDevice::getInstance());//获取sensorSevice实例
  5. if (dev.initCheck() == NO_ERROR) {
  6. sensor_t const* list;
  7. ssize_t count = dev.getSensorList(&list);//获取sensorSevice列表
  8. if (count > 0) {
  9. ssize_t orientationIndex = -1;
  10. bool hasGyro = false;
  11. uint32_t virtualSensorsNeeds =
  12. (1<<SENSOR_TYPE_GRAVITY) |
  13. (1<<SENSOR_TYPE_LINEAR_ACCELERATION) |
  14. (1<<SENSOR_TYPE_ROTATION_VECTOR);
  15. mLastEventSeen.setCapacity(count);
  16. for (ssize_t i=0 ; i<count ; i++) {
  17. registerSensor( new HardwareSensor(list[i]) );//注册各个sensor
  18. switch (list[i].type) {
  19. case SENSOR_TYPE_ORIENTATION:
  20. orientationIndex = i;
  21. break;
  22. case SENSOR_TYPE_GYROSCOPE:
  23. hasGyro = true;
  24. break;
  25. case SENSOR_TYPE_GRAVITY:
  26. case SENSOR_TYPE_LINEAR_ACCELERATION:
  27. case SENSOR_TYPE_ROTATION_VECTOR:
  28. virtualSensorsNeeds &= ~(1<<list[i].type);
  29. break;
  30. }
  31. }
  32. // it's safe to instantiate the SensorFusion object here
  33. // (it wants to be instantiated after h/w sensors have been
  34. // registered)
  35. const SensorFusion& fusion(SensorFusion::getInstance());
  36. if (hasGyro) {//如果有陀螺仪传感器,则虚拟的旋转矢量、重力、线性加速度、方向传感器
  37. // Always instantiate Android's virtual sensors. Since they are
  38. // instantiated behind sensors from the HAL, they won't
  39. // interfere with applications, unless they looks specifically
  40. // for them (by name).
  41. registerVirtualSensor( new RotationVectorSensor() );
  42. registerVirtualSensor( new GravitySensor(list, count) );
  43. registerVirtualSensor( new LinearAccelerationSensor(list, count) );
  44. // these are optional
  45. registerVirtualSensor( new OrientationSensor() );
  46. registerVirtualSensor( new CorrectedGyroSensor(list, count) );
  47. // virtual debugging sensors...
  48. char value[PROPERTY_VALUE_MAX];
  49. property_get("debug.sensors", value, "0");
  50. if (atoi(value)) {
  51. registerVirtualSensor( new GyroDriftSensor() );
  52. }
  53. }
  54. // build the sensor list returned to users
  55. mUserSensorList = mSensorList;
  56. if (hasGyro &&
  57. (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR))) {
  58. // if we have the fancy sensor fusion, and it's not provided by the
  59. // HAL, use our own (fused) orientation sensor by removing the
  60. // HAL supplied one form the user list.
  61. /*if (orientationIndex >= 0) {
  62. mUserSensorList.removeItemsAt(orientationIndex);
  63. }*/
  64. }
  65. run("SensorService", PRIORITY_URGENT_DISPLAY);//启动线程
  66. mInitCheck = NO_ERROR;
  67. }
  68. }
  69. }

onFirstRef主要做了下面三件事:

1构造SensorDevice 

  1. SensorDevice::SensorDevice()
  2. : mSensorDevice(0),
  3. mSensorModule(0)
  4. {
  5. status_t err = hw_get_module(SENSORS_HARDWARE_MODULE_ID,
  6. (hw_module_t const**)&mSensorModule);//获取sensor模块
  7. ALOGE_IF(err, "couldn't load %s module (%s)",
  8. SENSORS_HARDWARE_MODULE_ID, strerror(-err));
  9. if (mSensorModule) {
  10. err = sensors_open(&mSensorModule->common, &mSensorDevice);//打开sensor设备
  11. ALOGE_IF(err, "couldn't open device for module %s (%s)",
  12. SENSORS_HARDWARE_MODULE_ID, strerror(-err));
  13. if (mSensorDevice) {
  14. sensor_t const* list;
  15. ssize_t count = mSensorModule->get_sensors_list(mSensorModule, &list);//获取sensor列表
  16. mActivationCount.setCapacity(count);
  17. Info model;
  18. for (size_t i=0 ; i<size_t(count) ; i++) {
  19. mActivationCount.add(list[i].handle, model);
  20. mSensorDevice->activate(mSensorDevice, list[i].handle, 0);
  21. }
  22. }
  23. }
  24. }

2、获取到sensor之后 ,就是注册sensor,开始注册的都是HardwareSensor类型的sensor

  1. void SensorService::registerSensor(SensorInterface* s)
  2. {
  3. sensors_event_t event;
  4. memset(&event, 0, sizeof(event));
  5. const Sensor sensor(s->getSensor());
  6. // add to the sensor list (returned to clients)
  7. mSensorList.add(sensor);
  8. // add to our handle->SensorInterface mapping
  9. mSensorMap.add(sensor.getHandle(), s);
  10. // create an entry in the mLastEventSeen array
  11. mLastEventSeen.add(sensor.getHandle(), event);
  12. }

注册sensor比较简单,主要是添加到几个list和map中。

还有一个registerVirtualSensor,注册虚拟的sensor

  1. void SensorService::registerVirtualSensor(SensorInterface* s)
  2. {
  3. registerSensor(s);
  4. mVirtualSensorList.add( s );
  5. }

调用registerSensor并添加到mVirtualSensorList链表。

3、run启动threadLoop线程

  1. bool SensorService::threadLoop()
  2. {
  3. ALOGD("nuSensorService thread starting...");
  4. const size_t numEventMax = 16;
  5. const size_t minBufferSize = numEventMax + numEventMax * mVirtualSensorList.size();
  6. sensors_event_t buffer[minBufferSize];
  7. sensors_event_t scratch[minBufferSize];
  8. SensorDevice& device(SensorDevice::getInstance());
  9. const size_t vcount = mVirtualSensorList.size();
  10. ssize_t count;
  11. do {
  12. count = device.poll(buffer, numEventMax);//查看sensor上是否有数据到来
  13. if (count<0) {
  14. ALOGE("sensor poll failed (%s)", strerror(-count));
  15. break;
  16. }
  17. recordLastValue(buffer, count);//记录每个sensor的最后一次事件
  18. // handle virtual sensors
  19. if (count && vcount) {
  20. sensors_event_t const * const event = buffer;
  21. const DefaultKeyedVector<int, SensorInterface*> virtualSensors(
  22. getActiveVirtualSensors());//获取虚拟的sensor
  23. const size_t activeVirtualSensorCount = virtualSensors.size();
  24. if (activeVirtualSensorCount) {
  25. size_t k = 0;
  26. SensorFusion& fusion(SensorFusion::getInstance());
  27. if (fusion.isEnabled()) {//融合传感器使能,则调用它的process对根据event数据对SensorFusion里面的一些变量进行设置,
  28. //后面调用其相应的sensor process的时候会用到
  29. for (size_t i=0 ; i<size_t(count) ; i++) {
  30. fusion.process(event[i]);
  31. }
  32. }
  33. for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
  34. for (size_t j=0 ; j<activeVirtualSensorCount ; j++) {
  35. if (count + k >= minBufferSize) {
  36. ALOGE("buffer too small to hold all events: "
  37. "count=%u, k=%u, size=%u",
  38. count, k, minBufferSize);
  39. break;
  40. }
  41. sensors_event_t out;
  42. SensorInterface* si = virtualSensors.valueAt(j);
  43. if (si->process(&out, event[i])) {//调用模拟sensor的process处理,输出一个event,添加到buffer
  44. buffer[count + k] = out;
  45. k++;
  46. }
  47. }
  48. }
  49. if (k) {
  50. // record the last synthesized values
  51. recordLastValue(&buffer[count], k);//重新记录每个sensor的最后一次事件
  52. count += k;
  53. // sort the buffer by time-stamps
  54. sortEventBuffer(buffer, count);
  55. }
  56. }
  57. }
  58. // send our events to clients...
  59. const SortedVector< wp<SensorEventConnection> > activeConnections(
  60. getActiveConnections());
  61. size_t numConnections = activeConnections.size();
  62. for (size_t i=0 ; i<numConnections ; i++) {
  63. sp<SensorEventConnection> connection(
  64. activeConnections[i].promote());
  65. if (connection != 0) {
  66. connection->sendEvents(buffer, count, scratch);//把收到的数据传上去
  67. }
  68. }
  69. } while (count >= 0 || Thread::exitPending());
  70. ALOGW("Exiting SensorService::threadLoop => aborting...");
  71. abort();
  72. return false;
  73. }

代码中大概注释了各个比较关键地方的函数意义,主要是收到数据后,查看下如果有虚拟的sensor:

1、             如果使能了SensorFusion,调用它的process对数据进行处理(这里应该是每种类型sensor一次poll最多只会上报一次),处理过程中会设置相应的一些成员变量值

2、             两个for循环,对所有的event,针对所有的已使能的virtual sensor调用它的process,这里面会用到一些前面第一步设置的一些值,根据输入的event输出一个event并添加到buffer.

数据处理完成后,获取所有活动的连接,并把数据发给它。看一下sendEvents

  1. status_t SensorService::SensorEventConnection::sendEvents(
  2. sensors_event_t const* buffer, size_t numEvents,
  3. sensors_event_t* scratch)
  4. {
  5. // filter out events not for this connection
  6. size_t count = 0;
  7. if (scratch) {
  8. Mutex::Autolock _l(mConnectionLock);
  9. size_t i=0;
  10. while (i<numEvents) {
  11. const int32_t curr = buffer[i].sensor;
  12. if (mSensorInfo.indexOf(curr) >= 0) {//检查在该连接里面是否存在这个sensor,存在则添加到scratch里面
  13. do {
  14. scratch[count++] = buffer[i++];
  15. } while ((i<numEvents) && (buffer[i].sensor == curr));
  16. } else {
  17. i++;
  18. }
  19. }
  20. } else {
  21. scratch = const_cast<sensors_event_t *>(buffer);
  22. count = numEvents;
  23. }
  24. // NOTE: ASensorEvent and sensors_event_t are the same type
  25. ssize_t size = SensorEventQueue::write(mChannel,//将数据写到一个通道
  26. reinterpret_cast<ASensorEvent const*>(scratch), count);
  27. if (size == -EAGAIN) {
  28. // the destination doesn't accept events anymore, it's probably
  29. // full. For now, we just drop the events on the floor.
  30. //ALOGW("dropping %d events on the floor", count);
  31. return size;
  32. }
  33. return size < 0 ? status_t(size) : status_t(NO_ERROR);
  34. }


这样sensorservice就启动起来了

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/779029
推荐阅读
  

闽ICP备14008679号