通过实例化一个 SensorService 对象启动,如下:
1. static void android_server_SystemServer_startSensorService(JNIEnv* /* env */, jobject /* clazz */)
{
2. char propBuf[PROPERTY_VALUE_MAX];
3. property_get("system_init.startsensorservice", propBuf, "1");
4. if (strcmp(propBuf, "1") == 0) {
5. SensorService::instantiate();
6. }
7.
8. }
SensorService 继承关系为:
该 instantiate()方法为 BinderService 的方法,如下:
1. static void instantiate() { publish(); }
2. static status_t publish(bool allowIsolated = false) {
3. sp sm(defaultServiceManager());
4. return sm->addService(
5. String16(SERVICE::getServiceName()),
6. new SERVICE(), allowIsolated);
7. }
即 new 一个 SensorService 后向 ServiceManager 进行注册,
由于 SensorService 是 RefBase 的子类,
1. void RefBase::incStrong(const void* id) const
2. {
3. weakref_impl* const refs = mRefs;
4. refs->incWeak(id);
5.
6. refs->addStrongRef(id);
7. const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
8. ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
9. #if PRINT_REFS
10. ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
11. #endif
12. if (c != INITIAL_STRONG_VALUE) {
13. return;
14. }
15.
16. int32_t old = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE,
17. std::memory_order_relaxed);
18. // A decStrong() must still happen after us.
19. ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
20. refs->mBase->onFirstRef();
21. }
会在类 RefBase 里边调用 SensorService 的 onFirstRef()方法,开始进行 SensorService 的初始化工作,(这个调用应该
//这边取得 SensorDevice 实例,to do1:Sensordevice 类是什麽、用来做什么的后面分析,
1. ssize_t count = dev.getSensorList(&list);
2. for (ssize_t i=0 ; i
遍历 sensorlist ,创建里边每个 sensor 成员对应的一个 HardwareSensor 放到 sensorservice 层的 sensorList,to do2:
HardwareSensor 类是什麽、用来干嘛的后面分析,
1. if (hasGyro && hasAccel && hasMag) {
2. // Add Android virtual sensors if they're not already
3. // available in the HAL
4. bool needRotationVector = (virtualSensorsNeeds & (1<
若有对应物理 sensor 能够支持的虚拟 sensor,注册虚拟 sensor,
1. mLooper = new Looper(false);//ques1:这个 Looper 目前还不知到拿来干嘛
2. mCurrentOperatingMode = NORMAL;
3. mNextSensorRegIndex = 0;
4. for (int i = 0; i < SENSOR_REGISTRATIONS_BUF_SIZE; ++i) {
5. mLastNSensorRegistrations.push();
6. }
7.
8. mInitCheck = NO_ERROR;
9. //创建一个 SensorEventAckReceiver 对象
10. mAckReceiver = new SensorEventAckReceiver(this);//把自己扔进去给对方的
11. mAckReceiver->run("SensorEventAckReceiver", PRIORITY_URGENT_DISPLAY);
12. run("SensorService", PRIORITY_URGENT_DISPLAY);//这边进入 threadLoop
new 了几个对象后,调用 SensorEventAckReceiver:run()以及 SensorService:run(),进入它们各自实现其父类 Thread 的
threadLoop 方法里边,先看 SensorEventAckReceiver:threadLoop(),
1. bool SensorService::SensorEventAckReceiver::threadLoop() {
2. ALOGD("new thread SensorEventAckReceiver");
3. sp looper = mService->getLooper();//获取 SennsorService 的 mLooper
4. do {
5. bool wakeLockAcquired = mService->isWakeLockAcquired();
6. int timeout = -1;
7. if (wakeLockAcquired) timeout = 5000;
8. int ret = looper->pollOnce(timeout);
9. if (ret == ALOOPER_POLL_TIMEOUT) {
10. mService->resetAllWakeLockRefCounts();
11. }
12. } while(!Thread::exitPending());
13. return false;
14. }
这边目前没有看见什么信息,主要是对 SensorService:onFirsrRef()里边创建的 mLooper 的
看 SensorService:threadLoop()
SensorDevice& device(SensorDevice::getInstance());
首先获取一个 SensorDevice 实例,
1. ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
2. if (count < 0) {
3. ALOGE("sensor poll failed (%s)", strerror(-count));
4. break;
5. }
6. // Reset sensors_event_t.flags to zero for all events in the buffer.
7. for (int i = 0; i < count; i++) {
8. mSensorEventBuffer[i].flags = 0;
9. }
SensorDevice::poll() 大致是通过 hidl 调用 google-hal 的 poll 后,将 hal 层数据装到 sensors_event_t 类型的
1. // Make a copy of the connection vector as some connections may be removed during the course
2. // of this loop (especially when one-shot sensor events are present in the sensor_event
3. // buffer). Promote all connections to StrongPointers before the lock is acquired. If the
4. // destructor of the sp gets called when the lock is acquired, it may result in a deadlock
5. // as ~SensorEventConnection() needs to acquire mLock again for cleanup. So copy all the
6. // strongPointers to a vector before the lock is acquired.
7. SortedVector< sp > activeConnections;
8. populateActiveConnections(&activeConnections);
注释已经说了,就是将 mActiveConnections 做一份拷贝,拷贝到 activeConnections 里边,
继续看,
1. // handle virtual sensors
2. if (count && vcount) {
3. sensors_event_t const * const event = mSensorEventBuffer;
4. if (!mActiveVirtualSensors.empty()) {
5. size_t k = 0;
6. SensorFusion& fusion(SensorFusion::getInstance());//获取一个 SensorFusion
7. if (fusion.isEnabled()) {
8. for (size_t i=0 ; i= minBufferSize) {
15. ALOGE("buffer too small to hold all events: "
16. "count=%zd, k=%zu, size=%zu",
17. count, k, minBufferSize);
18. break;
19. }
20. sensors_event_t out;
21. // 根据 handle 获取到在
22. //SensorService::onFirstRef 里边注册的 SensorInterface
23. sp si = mSensors.getInterface(handle);
24. if (si == nullptr) {
25. ALOGE("handle %d is not an valid virtual sensor", handle);
26. continue;
27. }
28. //看看这边做了什么,估计是取数据后存数据
29. //调用对应 SensorInterface 实例的 process 方法
30. if (si->process(&out, event[i])) {
31. mSensorEventBuffer[count + k] = out;
32. k++;
33. }
34. }
35. }
36. if (k) {
37. // record the last synthesized values
38. recordLastValueLocked(&mSensorEventBuffer[count], k);
39. count += k;
40. // sort the buffer by time-stamps
41. sortEventBuffer(mSensorEventBuffer, count);
42. }
43. }
44. }
那么,接下来,先回过头去将 onFirstRef 里边的
registerSensor( new HardwareSensor(list[i]) );
1. const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
2. int handle = s->getSensor().getHandle();
3. int type = s->getSensor().getType();
4. if (mSensors.add(handle, s, isDebug, isVirtual)){
5. mRecentEvent.emplace(handle, new RecentEventLogger(type));
6. return s->getSensor();
7. } else {
8. return mSensors.getNonSensor();
9. }
10. }
,将每个sensor_t类型的sensor初始化一个对应的HardwareSensor对象后和对应的handle一起放到mSensors里边,
sp
1. bool HardwareSensor::process(sensors_event_t* outEvent,
2. const sensors_event_t& event) {
3. *outEvent = event;
4. return true;
5. }
,那么 event[i]呢,看看这东西是在哪儿被赋值的,为
1. ssize_t count = device.poll(mSensorEventBuffer, numEventMax);
2. sensors_event_t const * const event = mSensorEventBuffer;
mSensorEventBuffer 就是在前边通过 device.poll 获取 hal 层的数据的嘛,是作为指针指向底层的一个数组的,再传给
继续看 SensorService:threadLoop()方法,
1. if (si->process(&out, event[i])) {
2. mSensorEventBuffer[count + k] = out;
3. k++;
4. }
又把 out 装到 mSensorEventBuffer 的空余的下一个单元
,
1. // Send our events to clients. Check the state of wake lock for each client and release the
2. // lock if none of the clients need it.
3. bool needsWakeLock = false;
4. size_t numConnections = activeConnections.size();
5. for (size_t i=0 ; i < numConnections; ++i) {
6. if (activeConnections[i] != 0) {
7. activeConnections[i]->sendEvents(mSensorEventBuffer, count,
8. mSensorEventScratch,mMapFlushEventsToConnections);
9. needsWakeLock |= activeConnections[i]->needsWakeLock();
10. // If the connection has one-shot sensors, it may be cleaned up after first trigger.
11. // Early check for one-shot sensors.
12. if (activeConnections[i]->hasOneShotSensors()) {
13. cleanupAutoDisabledSensorLocked(activeConnections[i],
14. mSensorEventBuffer,count);
15. }
16. }
17. }
通过 activeConnections[i]->sendEvents() 将数据发送出去,然后继续循环,
边不断通过 poll 从 hal 层取数据然后通过 unix socket 发送出去.
里边的 mHandleMap 成员为 map 类型,主要是用来装 SensorInterface 和 handle 的,
对于 SensorService::registerSensor()方法,注册一个 sensor,也就是将
从 google-hal 层获取到的 sensor_t 初始化一个 HardwareSensor 对象后,将其与其对应的 handle 添加进一个 map 里
边.
1. const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
2. int handle = s->getSensor().getHandle();
3. int type = s->getSensor().getType();
4. if (mSensors.add(handle, s, isDebug, isVirtual)){
5. mRecentEvent.emplace(handle, new RecentEventLogger(type));
6. return s->getSensor();
7. } else {
8. return mSensors.getNonSensor();
9. }
10. }
11.
12. mSensors 为 SensorList 类型,看其 add()方法,
13. bool SensorList::add(
14. int handle, SensorInterface* si, bool isForDebug, bool isVirtual) {
15. std::lock_guard lk(mLock);
16. if (handle == si->getSensor().getHandle() &&
17. mUsedHandle.insert(handle).second) {
18. // will succeed as the mUsedHandle does not have this handle
19. mHandleMap.emplace(handle, Entry(si, isForDebug, isVirtual));
20. return true;
21. }
22. // handle exist already or handle mismatch
23. return false;
24. }
用 si 初始化一个匿名 Entry 类型后,与 handle 一起添加进 mHandleMap
由 google-hal 定义在/android/hardware/libhardware/include/hardware/sensors.h 里边
/************************************************/
to do1:Sensordevice 类是什麽、用来做什么的后面分析,
to do2:harwareSensor 类是什麽、用来干嘛的后面分析,
好了,接下来对前面遗留的疑问做个分析,
3.1 to do1:SensorDevice 类 是什麽、 用来做什么 的
ans:SensorDevice 主要是获取到 hal 层的对象 sp
mSensors 通过 hidl 机制调用 hal 层的方法。
该 ISensors 类型定义在 android/hardware/interfaces/sensors/1.0/ISensors.hal
SensorDevice 类
SensorDevice 继承了 BinderService
先看构造函数
1. SensorDevice::SensorDevice() : mHidlTransportErrors(20) {
2. if (!connectHidlService()) {
3. return;
4. }
5.
6. float minPowerMa = 0.001; // 1 microAmp
7.
8. checkReturn(mSensors->getSensorsList(
9. [&](const auto &list) {
10. const size_t count = list.size();
11.
12. mActivationCount.setCapacity(count);
13. Info model;
14. for (size_t i=0 ; i < count; i++) {
15. sensor_t sensor;
16. convertToSensor(list[i], &sensor);
17. // Sanity check and clamp power if it is 0 (or close)
18. if (sensor.power < minPowerMa) {
19. ALOGE("Reported power %f not deemed sane, clamping to %f",
20. sensor.power, minPowerMa);
21. sensor.power = minPowerMa;
22. }
23. mSensorList.push_back(sensor);
24.
25. mActivationCount.add(list[i].sensorHandle, model);
26.
27. checkReturn(mSensors->activate(list[i].sensorHandle, 0 /* enabled */));
28. }
29. }));
30.
31. mIsDirectReportSupported =
32. (checkReturn(mSensors->unregisterDirectChannel(-1)) != Result::INVALID_OPERATION);
33. }
对于变量类型 sensor_t,sensor_t 是在 google-hal 里边定义的,
路径: android/hardware/libhardware/include/hardware/sensors.h
先调用 connectHidlService ()方法,在这里边通过 hidl 机制获取 mSensors,
mSensors = ISensors::getService();
//获取 hal 层对象实例,这样的话接下来就能够通过该 mSensors 来调用 hal 层的服务了。
mSensors 类型为 sp
接着通过 mSensors(sp
过 convertToSensor(list[i], &sensor)获取 sensor 后装进 mSensorList 里边;
这边获取到 hal 层的 sensor 为 sensor_t 类型,定义在
android/hardware/libhardware/include/hardware/sensors.h
里边,
一句话概括构造函数,就是: 通过 connectHidlService ()与 hal 层建立联系后获取 hal 层的 SensorList