SensorService流程分析
来源:互联网 发布:刷网游金币软件 编辑:程序博客网 时间:2024/05/20 19:16
SensorService是用来管理底层sensor的服务;
首先来看下它的启动,在SystemServer中的run()中有:
// Initialize native services. System.loadLibrary("android_servers"); nativeInit();static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz) { char propBuf[PROPERTY_VALUE_MAX]; property_get("system_init.startsensorservice", propBuf, "1"); if (strcmp(propBuf, "1") == 0) { // Start the sensor service 实例化SensorService SensorService::instantiate(); }
在看下SensorService.cpp中的实现:
SensorService::SensorService() : mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED), mWakeLockAcquired(false){}void SensorService::onFirstRef(){ ALOGD("nuSensorService starting..."); //1:sensorDevice的实例化 SensorDevice& dev(SensorDevice::getInstance()); if (dev.initCheck() == NO_ERROR) { sensor_t const* list; //拿到硬件的sensor列表 ssize_t count = dev.getSensorList(&list); if (count > 0) { ssize_t orientationIndex = -1; bool hasGyro = 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++) { //注册sensor registerSensor( new HardwareSensor(list[i]) ); switch (list[i].type) { 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) { 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); } 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); } // 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 (int 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]; mAckReceiver = new SensorEventAckReceiver(this); mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY); mInitCheck = NO_ERROR; run("SensorService", PRIORITY_URGENT_DISPLAY); } }}
首先看下SensorDevice的实例化:
SensorDevice::SensorDevice() : mSensorDevice(0), mSensorModule(0){ //1:加载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) { //2:打开设备 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; //3:得到sensor列表 ssize_t count = mSensorModule->get_sensors_list(mSensorModule, &list); mActivationCount.setCapacity(count); Info model; for (size_t i=0 ; i<size_t(count) ; i++) { mActivationCount.add(list[i].handle, model); //4:激活sensor mSensorDevice->activate( reinterpret_cast<struct sensors_poll_device_t *>(mSensorDevice), list[i].handle, 0); } } }}
再看下sensors_open_1的流程:
static inline int sensors_open_1(const struct hw_module_t* module, sensors_poll_device_1_t** device) { //调用hal中的open方法 return module->methods->open(module, SENSORS_HARDWARE_POLL, (struct hw_device_t**)device);}
以hal层的sensors继续分析:
/** Open a new instance of a sensor device using name */static int open_sensors(const struct hw_module_t* module, const char* id, struct hw_device_t** device){ int status = -EINVAL; //先创建一个sensors_poll_context_t sensors_poll_context_t *dev = new sensors_poll_context_t(); id = id; memset(&dev->device, 0, sizeof(sensors_poll_device_t)); dev->device.common.tag = HARDWARE_DEVICE_TAG; dev->device.common.version = 0; dev->device.common.module = const_cast<hw_module_t*>(module); dev->device.common.close = poll__close; dev->device.activate = poll__activate; dev->device.setDelay = poll__setDelay; dev->device.poll = poll__poll; *device = &dev->device.common; status = 0; return status;}static int sensors__get_sensors_list(struct sensors_module_t* module, struct sensor_t const** list) { module = module; //拿到底层硬件sensor支持列表 *list = sSensorList; return sSensorListNum;}static struct hw_module_methods_t sensors_module_methods = { //指定open方法为open_sensors open: open_sensors};
最后看下激活sensor的流程:
static int poll__activate(struct sensors_poll_device_t *dev, int handle, int enabled) { sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev; return ctx->activate(handle, enabled);}int sensors_poll_context_t::activate(int handle, int enabled) { int err; // Orientation requires accelerometer and magnetic sensor if (handle == ID_O) { mOrientationActive = enabled ? true : false; if (!mAccelActive) { err = real_activate(ID_A, enabled); if (err) return err; } if (!mMagnetActive) { err = real_activate(ID_M, enabled); if (err) return err; } } // Keep track of magnetic and accelerometer use from system else if (handle == ID_A) { mAccelActive = enabled ? true : false; // No need to enable or disable if orientation sensor is active as that will handle it if (mOrientationActive) return 0; } else if (handle == ID_M) { mMagnetActive = enabled ? true : false; // No need to enable or disable if orientation sensor is active as that will handle it if (mOrientationActive) return 0; } return real_activate(handle, enabled);}int sensors_poll_context_t::real_activate(int handle, int enabled) { int index = handleToDriver(handle); if (index < 0) return index; int err = mSensors[index]->enable(handle, enabled); if (enabled && !err) { const char wakeMessage(WAKE_MESSAGE); int result = write(mWritePipeFd, &wakeMessage, 1); ALOGE_IF(result<0, "error sending wake message (%s)", strerror(errno)); } return err;}
如果是AccelerationSensor的类型:对input中对应的节点写1或者0
int AccelerationSensor::enable(int32_t, int en) { ALOGD("AccelerationSensor::~enable(0, %d)", en); int flags = en ? 1 : 0; if (flags != mEnabled) { int fd; strcpy(&input_sysfs_path[input_sysfs_path_len], "enable"); fd = open(input_sysfs_path, O_RDWR); if (fd >= 0) { char buf[2]; int err; buf[1] = 0; if (flags) { buf[0] = '1'; } else { buf[0] = '0'; } err = write(fd, buf, sizeof(buf)); close(fd); mEnabled = flags; //setInitialState(); return 0; } return -1; } return 0;}
启动流程到这里基本完毕了;接下来需要再继续看下数据的传输过程,看底层数据是怎么从底层传递到上层的,在SensorService的looper中,会不断的检测是否有数据
bool SensorService::threadLoop(){... const int halVersion = device.getHalDeviceVersion(); do { //调用底层的poll函数 ssize_t count = device.poll(mSensorEventBuffer, numEventMax); if (count < 0) { ALOGE("sensor poll failed (%s)", strerror(-count)); break; }...ssize_t SensorDevice::poll(sensors_event_t* buffer, size_t count) { if (!mSensorDevice) return NO_INIT; ssize_t c; do { c = mSensorDevice->poll(reinterpret_cast<struct sensors_poll_device_t *> (mSensorDevice), buffer, count); } while (c == -EINTR); return c;}static int poll__poll(struct sensors_poll_device_t *dev, sensors_event_t* data, int count) { sensors_poll_context_t *ctx = (sensors_poll_context_t *)dev; return ctx->pollEvents(data, count);}int sensors_poll_context_t::pollEvents(sensors_event_t* data, int count){ int nbEvents = 0; int n = 0; do { // see if we have some leftover from the last poll() for (int i=0 ; count && i<numSensorDrivers ; i++) { SensorBase* const sensor(mSensors[i]); if (sensor == NULL) { continue; } if ((mPollFds[i].revents & POLLIN) || (sensor->hasPendingEvents())) { //这里回去读驱动上报的数据 int nb = sensor->readEvents(data, count); if (nb < count) { // no more data for this sensor mPollFds[i].revents = 0; } count -= nb; nbEvents += nb; data += nb; } } if (count) { // we still have some room, so try to see if we can get // some events immediately or just wait if we don't have // anything to return do { n = poll(mPollFds, numFds, nbEvents ? 0 : -1); } while (n < 0 && errno == EINTR); if (n<0) { ALOGE("poll() failed (%s)", strerror(errno)); return -errno; } if (mPollFds[wake].revents & POLLIN) { char msg; int result = read(mPollFds[wake].fd, &msg, 1); ALOGE_IF(result<0, "error reading from wake pipe (%s)", strerror(errno)); ALOGE_IF(msg != WAKE_MESSAGE, "unknown message on wake queue (0x%02x)", int(msg)); mPollFds[wake].revents = 0; } } // if we have events and space, go read them } while (n && count); return nbEvents;}
最后在sensor中读取数据:
int AccelerationSensor::readEvents(sensors_event_t* data, int count){ //ALOGD("AccelerationSensor::~readEvents() %d", count); if (count < 1) return -EINVAL; if (mHasPendingEvent) { mHasPendingEvent = false; mPendingEvent.timestamp = getTimestamp(); *data = mPendingEvent; return mEnabled ? 1 : 0; } //首先填充读取数据 ssize_t n = mInputReader.fill(data_fd); if (n < 0) return n; int numEventReceived = 0; input_event const* event; //读取数据 while (count && mInputReader.readEvent(&event)) { if(event == NULL) { ALOGE("llw AccelerationSensor::readEvents() null pointer!!!" ); } else { //解析读到的数据 int type = event->type; if (type == EV_ABS) { float value = event->value; if (event->code == EVENT_TYPE_ACCEL_X) { mPendingEvent.acceleration.x = value * mResolution; } else if (event->code == EVENT_TYPE_ACCEL_Y) { mPendingEvent.acceleration.y = value * mResolution; } else if (event->code == EVENT_TYPE_ACCEL_Z) { mPendingEvent.acceleration.z = value * mResolution; } } else if (type == EV_SYN) { mPendingEvent.timestamp = timevalToNano(event->time); if (mEnabled) { *data++ = mPendingEvent; count--; numEventReceived++; } } else { ALOGE("AccelerationSensor: unknown event (type=%d, code=%d)", type, event->code); } } mInputReader.next(); } //ALOGD("AccelerationSensor::~readEvents() numEventReceived = %d", numEventReceived); return numEventReceived;}
接收到了数据就要发送出去,在哪里发送呢?还是在SensorService::threadLoop()看下:
for (size_t i=0 ; i < numConnections; ++i) { if (activeConnections[i] != 0) { //通过activeConnections的sendEvents来发送数据 activeConnections[i]->sendEvents(mSensorEventBuffer, count, mSensorEventScratch, mMapFlushEventsToConnections); 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);
继续跟踪:
status_t SensorService::SensorEventConnection::sendEvents( sensors_event_t const* buffer, size_t numEvents, sensors_event_t* scratch, SensorEventConnection const * const * mapFlushEventsToConnections) { ... // NOTE: ASensorEvent and sensors_event_t are the same type. ssize_t size = SensorEventQueue::write(mChannel, reinterpret_cast<ASensorEvent const*>(scratch), count); ... }ssize_t SensorEventQueue::write(const sp<BitTube>& tube, ASensorEvent const* events, size_t numEvents) { return BitTube::sendObjects(tube, events, numEvents);}
最终是通过BitTube将数据发送出去
既然数据有发送,必然就会有数据的接收:
1 0
- SensorService流程分析
- SensorService 分析
- SensorService启动分析
- SensorService发生NE分析
- [FAQ14188]SensorService发生NE分析
- Android SensorService源码分析(一)
- Android SensorService源码分析(二)
- Android SensorService启动流程(一)
- Android SensorService启动流程(二)
- Android sensorservice
- Android5.0L中SensorService crash导致的systemserver重启问题分析
- Android5.0L下因sensorservice crash导致systemserver重启的另外一种场景分析
- android SensorService lightSensor
- SensorService architechure’ note
- Android SensorService学习笔记
- sensorservice代码阅读
- LightsService分析 --- 流程分析
- SensorService 初始化(更新中)
- 目标的最后位置
- 支付宝 Android 版使用的开源组件
- 完美字符串 输入一个字符串S(S的长度 <= 10000),S中没有除字母外的其他字符。由你将1-26分配给不同的字母,使得字符串S的完美度最大,输出这个完美度。如dad 77
- 带你一步一步揭开Rxjava2.0的神秘面纱(1)
- eclipse插件下载集合
- SensorService流程分析
- NTU-PLA
- 移动端获取屏幕宽度
- Markdown编辑器基本语法
- squid中https_port中版本SSLv2、SSL3或者TLSv1
- 实现数据开放共享的方法
- 二叉树的操作
- 决策树算法理论部分(一)
- 进程 vs 线程