Sensor系列四 Framework层分析_Service端
来源:互联网 发布:c语言标准库函数 编辑:程序博客网 时间:2024/05/06 18:14
一、Sensor framwork service介绍
在上一节Framework层分析_Client端已经介绍了Sensor在framework中的框架结构,本文主要分析SensorService的启动流程和HAL层的交互工作。其中SensorService中主要包含以下类:
(1)SensorService.cpp
./frameworks/native/service/sensorservice/SensorService.cpp
SensorService是Android Sensor Framework最核心的模块,它实现了主要的Sensor控制流和数据流逻辑,完成Sensor参数的配置,数据分发,Client请求数据处理等功能。
(2)BinderService
./frameworks/native/include/binder/BinderService.h
BinderService是Android Service框架的主要类,它提供了Service的生命周期管理、进程将通信、请求响应处理等功能。Android总的大部分Service都会继承此类。
(3)SensorEventConnect
./framework/native/libs/gui/ISensorEventConnect.cpp
SensorEventConnect是sensor数据传输通道,当Client开始监听某一个Sensor时,一个对应的SensorEventConnect将会被创建,Server端在接收到Sensor数据后,通过写入到SensorEventConnect传输给Client端。
(4)SensorDevice
./framework/native/services/sensorservice/SensorDevice.cpp
该类主要负责与HAL层交互。下面看下程序走向图:
二、SensorService流程分析
在系统启动时,SystemServer中会启动需要开启的服务,系统服务通过调用startSensorService启动sensorService,调用JNI,通过SensorService::instantiate实例化SensorService对象。
SensorService创建之后,将会调用SensorService::onFirstRefs()方法,来完成初始化工作,首先通过SensorDevice::getInstance来创建对象dev,调用dev.getSensorList(&list)获取传感器列表,传入sensor_t类型的list,创建HardwareSensor对象,传递给registerSensor,注册传感器,下面看下SensorService的onFirstRef方法。
void SensorService::onFirstRef(){ ALOGD("nuSensorService starting..."); SensorDevice& dev(SensorDevice::getInstance());//实例化SensorDevice if (dev.initCheck() == NO_ERROR) { sensor_t const* list; ssize_t count = dev.getSensorList(&list);//获取sensorlist if (count > 0) { ssize_t orientationIndex = -1; bool hasGyro = false, hasAccel = false, hasMag = false; uint32_t virtualSensorsNeeds = (1<<SENSOR_TYPE_GRAVITY) | (1<<SENSOR_TYPE_LINEAR_ACCELERATION) | (1<<SENSOR_TYPE_ROTATION_VECTOR); mLastEventSeen.setCapacity(count); for (ssize_t i=0 ; i<count ; i++) { registerSensor( new HardwareSensor(list[i]) );//为每一个sensor注册监听器 switch (list[i].type) { case SENSOR_TYPE_ACCELEROMETER: hasAccel = true; break; case SENSOR_TYPE_MAGNETIC_FIELD: hasMag = true; break; case SENSOR_TYPE_ORIENTATION: orientationIndex = i; break; case SENSOR_TYPE_GYROSCOPE: case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED: hasGyro = true; break; case SENSOR_TYPE_GRAVITY: case SENSOR_TYPE_LINEAR_ACCELERATION: case SENSOR_TYPE_ROTATION_VECTOR: virtualSensorsNeeds &= ~(1<<list[i].type); break; } } // it's safe to instantiate the SensorFusion object here // (it wants to be instantiated after h/w sensors have been // registered) const SensorFusion& fusion(SensorFusion::getInstance()); // build the sensor list returned to users mUserSensorList = mSensorList; if (hasGyro && hasAccel && hasMag) { Sensor aSensor; // Add Android virtual sensors if they're not already // available in the HAL aSensor = registerVirtualSensor( new RotationVectorSensor() );//注册虚拟设备的监听器 if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) { mUserSensorList.add(aSensor); } aSensor = registerVirtualSensor( new GravitySensor(list, count) ); if (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY)) { mUserSensorList.add(aSensor); } aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) ); if (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) { mUserSensorList.add(aSensor); } #if 0 aSensor = registerVirtualSensor( new OrientationSensor() ); if (virtualSensorsNeeds & (1<<SENSOR_TYPE_ROTATION_VECTOR)) { // if we are doing our own rotation-vector, also add // the orientation sensor and remove the HAL provided one. mUserSensorList.replaceAt(aSensor, orientationIndex); } #endif // virtual debugging sensors are not added to mUserSensorList registerVirtualSensor( new CorrectedGyroSensor(list, count) ); registerVirtualSensor( new GyroDriftSensor() ); } // debugging sensor list mUserSensorListDebug = mSensorList; // Check if the device really supports batching by looking at the FIFO event // counts for each sensor. bool batchingSupported = false; for (size_t i = 0; i < mSensorList.size(); ++i) { if (mSensorList[i].getFifoMaxEventCount() > 0) { batchingSupported = true; break; } } if (batchingSupported) { // Increase socket buffer size to a max of 100 KB for batching capabilities. mSocketBufferSize = MAX_SOCKET_BUFFER_SIZE_BATCHED; } else { mSocketBufferSize = SOCKET_BUFFER_SIZE_NON_BATCHED; } // Compare the socketBufferSize value against the system limits and limit // it to maxSystemSocketBufferSize if necessary. FILE *fp = fopen("/proc/sys/net/core/wmem_max", "r"); char line[128]; if (fp != NULL && fgets(line, sizeof(line), fp) != NULL) { line[sizeof(line) - 1] = '\0'; size_t maxSystemSocketBufferSize; sscanf(line, "%zu", &maxSystemSocketBufferSize); if (mSocketBufferSize > maxSystemSocketBufferSize) { mSocketBufferSize = maxSystemSocketBufferSize; } } if (fp) { fclose(fp); } mWakeLockAcquired = false; mLooper = new Looper(false); const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT; mSensorEventBuffer = new sensors_event_t[minBufferSize]; mSensorEventScratch = new sensors_event_t[minBufferSize]; mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize]; mCurrentOperatingMode = NORMAL; mNextSensorRegIndex = 0; for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) { mLastNSensorRegistrations.push(); } mInitCheck = NO_ERROR; mAckReceiver = new SensorEventAckReceiver(this); mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY); run("SensorService", PRIORITY_URGENT_DISPLAY); } }}总结而言,onFirstref主要完成了三项工作:
1、创建SensorDevice实例;
2、调用SensorDevice.getSensorList(),获取Sensor模块所有传感器列表;
3、为每一个传感器注册监听器,还同事注册实现了6个虚拟传感器。
在上面介绍了与HAL层交互的SensorDevice,下面看看方法调用的过程:
SensorDevice::SensorDevice() : mSensorDevice(0), mSensorModule(0){ //根据module_id加载hal层的so库 status_t err = hw_get_module(SENSORS_HARDWARE_MODULE_ID,(hw_module_t const**)&mSensorModule); ALOGE_IF(err, "couldn't load %s module (%s)", SENSORS_HARDWARE_MODULE_ID, strerror(-err)); if (mSensorModule) { err = sensors_open_1(&mSensorModule->common, &mSensorDevice);//打开设备 ALOGE_IF(err, "couldn't open device for module %s (%s)", SENSORS_HARDWARE_MODULE_ID, strerror(-err)); if (mSensorDevice) { if (mSensorDevice->common.version == SENSORS_DEVICE_API_VERSION_1_1 || mSensorDevice->common.version == SENSORS_DEVICE_API_VERSION_1_2) { ALOGE(">>>> WARNING <<< Upgrade sensor HAL to version 1_3"); } sensor_t const* list; ssize_t count = mSensorModule->get_sensors_list(mSensorModule, &list);//获取sensor数目 mActivationCount.setCapacity(count); Info model; for (size_t i=0 ; i<size_t(count) ; i++) { mActivationCount.add(list[i].handle, model, mSensorDevice->activate(//使能每一个sensor reinterpret_cast<struct sensors_poll_device_t *>(mSensorDevice), list[i].handle, 0); } } }}在SensorDevice类中主要封装了HAL层的sensor操作接口,在SensorDevice的构造函数中主要完成了三个工作:
1、调用HAL层的hw_get_module()方法打开设备;
2、调用sensor.h的sensor_open_1方法打开设备;
3、调用sensor_poll_device_1_t->activate模块使能sensor。
sensor使能后,下面分析SensorService层中数据的传输。
三、SensorService数据传输
从下图中可以看出SensorClient和SensorService端各有一个线程用于数据的传输,SensorService端的线程复制从hal层读取数据,并将数据写入到Client端创建的管道中,SensorClient则通过管道读取数据,上报给app层。
其中SensorService数据的读取是在SensorService::threadLoop()方法中实现的:
bool SensorService::threadLoop(){ ALOGD("nuSensorService thread starting..."); const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT; const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size()); SensorDevice& device(SensorDevice::getInstance()); const size_t vcount = mVirtualSensorList.size(); const int halVersion = device.getHalDeviceVersion(); do { ssize_t count = device.poll(mSensorEventBuffer, numEventMax);//调用hal层的 poll__poll获取数据 if (count < 0) { ALOGE("sensor poll failed (%s)", strerror(-count)); break; } // Reset sensors_event_t.flags to zero for all events in the buffer. for (int i = 0; i < count; i++) { mSensorEventBuffer[i].flags = 0; } SortedVector< sp<SensorEventConnection> > activeConnections;//获得传感器连接对象 populateActiveConnections(&activeConnections); Mutex::Autolock _l(mLock); bool bufferHasWakeUpEvent = false; for (int i = 0; i < count; i++) { if (isWakeUpSensorEvent(mSensorEventBuffer[i])) { bufferHasWakeUpEvent = true; break; } } if (bufferHasWakeUpEvent && !mWakeLockAcquired) { setWakeLockAcquiredLocked(true);...... // Map flush_complete_events in the buffer to SensorEventConnections which called // flush on the hardware sensor. mapFlushEventsToConnections[i] will be the // SensorEventConnection mapped to the corresponding flush_complete_event in // mSensorEventBuffer[i] if such a mapping exists (NULL otherwise). for (int i = 0; i < count; ++i) { mMapFlushEventsToConnections[i] = NULL; if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) { const int sensor_handle = mSensorEventBuffer[i].meta_data.sensor; SensorRecord* rec = mActiveSensors.valueFor(sensor_handle); if (rec != NULL) { mMapFlushEventsToConnections[i] = rec->getFirstPendingFlushConnection(); rec->removeFirstPendingFlushConnection(); } } } // Send our events to clients. Check the state of wake lock for each client and release the // lock if none of the clients need it. bool needsWakeLock = false; size_t numConnections = activeConnections.size(); for (size_t i=0 ; i < numConnections; ++i) { if (activeConnections[i] != 0) { activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch, mMapFlushEventsToConnections);//将数据写入指定的sensor管道中,供client端使用 needsWakeLock |= activeConnections[i]->needsWakeLock(); // If the connection has one-shot sensors, it may be cleaned up after first trigger. // Early check for one-shot sensors. if (activeConnections[i]->hasOneShotSensors()) { cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer, count); } } } if (mWakeLockAcquired && !needsWakeLock) { setWakeLockAcquiredLocked(false); } } while (!Thread::exitPending());//判断Thread是否结束 ALOGW("Exiting SensorService::threadLoop => aborting..."); abort(); return false;}其实数据是以一个结构体sensors_event_t的形式从HAL层传到JNI层。看看HAL的sensors_event_t结构体,同时数据以相同的形式传递给Java层使用:
typedef struct sensors_event_t { int32_t version; int32_t sensor; //标识符 int32_t type; //传感器类型 int32_t reserved0; int64_t timestamp; //时间戳 union { float data[16]; sensors_vec_t acceleration; //加速度 sensors_vec_t magnetic; //磁矢量 sensors_vec_t orientation; //方向 sensors_vec_t gyro; //陀螺仪 float temperature; //温度 float distance; //距离 float light; //光照 float pressure; //压力 float relative_humidity; //相对湿度 }; uint32_t reserved1[4];} sensors_event_t;到这里,SensorService的启动及数据传输就已经介绍完毕,由上可以总结,SensorService的主要工作是监听获取HAL层的数据,并将数据传输给SensorClient端,完成数据的传输工作。
作者:frank_zyp
您的支持是对博主最大的鼓励,感谢您的认真阅读。
本文无所谓版权,欢迎转载。
- Sensor系列四 Framework层分析_Service端
- Sensor系列三 Framework层分析_Client端
- Sensor系列二 HAL层分析
- sensor之Application Framework层
- Sensor框架Framework层解读
- Sensor框架Framework层解读
- Android-Framework:Sensor框架Framework层解读
- sensor的FRAMEWORK分析(一)
- PowerManagerService framework层的分析-------由于sensor涉及这个文件所以转过来了
- 【Android】Sensor框架Framework层解读
- <5>Sensor框架Framework层解读
- 【Android】Sensor框架Framework层解读
- Android Sensor HAL层分析
- Android wifi探究四:Wifi P2P framework层源码分析
- Sensor框架HAL层和Framework层解读
- framework层服务分析
- Android从Hal到framework层添加自定义Sensor
- android framework 四层结构图
- spring4+hibernate4+jotm 分布式事务
- iOS UITextField的使用详解
- 2016.12.22:for SQL初学
- 内存碎片产生的原因
- C++ 日志
- Sensor系列四 Framework层分析_Service端
- 计算机网络之基础--运输层
- php 判定变量是否为数字
- LeetCode 337. House Robber III
- Spark Streaming 2.0 runDummySpark Job
- hibernate配置文件hibernate.cfg.xml的详细解释
- Nodebb论坛学习汇总
- Hexagon 680 常用知识
- TCP传输协议