Android Framework SensorService 分析


1 SensorService  的啓動

1.1 SensorService:onFirsrRef()

SensorService 運行在 system_server 裏邊,在
android/frameworks/base/services/core/jni/com_android_server_SystemServer.cpp

通過實例化一個 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<IServiceManager> 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 的初始化工作,(這個調用應該
是 Binder 的一個通用機制,通過重載該 onFirstRef()方法進行一個各自的初始化工作),
 從 onFirstRef()開始啓動,
SensorDevice& dev(SensorDevice::getInstance());

//這邊取得 SensorDevice 實例,to do1:Sensordevice 類是什麼、用來做什麼的後面分析,

1. ssize_t count = dev.getSensorList(&list);
2. for (ssize_t i=0 ; i<count ; i++) {
3. bool useThisSensor=true;
5. switch (list[i].type) {
6. case SENSOR_TYPE_ACCELEROMETER:
7. hasAccel = true;
8. break;
9. case SENSOR_TYPE_MAGNETIC_FIELD:
10. hasMag = true;
11. break;
12. case SENSOR_TYPE_ORIENTATION:
13. orientationIndex = i;
14. break;
15. case SENSOR_TYPE_GYROSCOPE:
16. case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
17. hasGyro = true;
18. break;
19. case SENSOR_TYPE_GRAVITY:
20. case SENSOR_TYPE_LINEAR_ACCELERATION:
21. case SENSOR_TYPE_ROTATION_VECTOR:
22. case SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
23. case SENSOR_TYPE_GAME_ROTATION_VECTOR:
24. if (IGNORE_HARDWARE_FUSION) {
25. useThisSensor = false;
26. } else {
27. virtualSensorsNeeds &= ~(1<<list[i].type);
28. }
29. break;
30. }
31. if (useThisSensor) {
32. registerSensor( new HardwareSensor(list[i]) );
33. }
34. }
遍歷 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_TYPE_ROTATI
ON_VECTOR)) != 0;
5.
6. registerSensor(new RotationVectorSensor(), !needRotationVector, true);
7. registerSensor(new OrientationSensor(), !needRotationVector, true);
8. bool needLinearAcceleration =
9. (virtualSensorsNeeds & (1<<SENSOR_TYPE_LINEAR_ACCELERATION)) != 0;
10. registerSensor(new LinearAccelerationSensor(list, count),
11. !needLinearAcceleration, true);
12. // virtual debugging sensors are not for user
13. registerSensor( new CorrectedGyroSensor(list, count), true, true);
14. registerSensor( new GyroDriftSensor(), true, true);
15. }
16.
17. if (hasAccel && hasGyro) {
18. bool needGravitySensor = (virtualSensorsNeeds & (1<<SENSOR_TYPE_GRAVITY
)) != 0;
19. registerSensor(new GravitySensor(list, count), !needGravitySensor, true);
20.
21. bool needGameRotationVector =
22. (virtualSensorsNeeds & (1<<SENSOR_TYPE_GAME_ROTATION_VECTOR)) != 0;
23. registerSensor(new GameRotationVectorSensor(), !needGameRotationVector, true);
24. }
25.
26. if (hasAccel && hasMag) {
27. bool needGeoMagRotationVector =
28. (virtualSensorsNeeds & (1<<SENSOR_TYPE_GEOMAGNETIC_ROTATION_VECTOR)) != 0;
29. registerSensor(new GeoMagRotationVectorSensor(), !needGeoMagRotation
Vector, true);
30. }

若有對應物理 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> 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 的
通過調用其 pollOnece()方法進行不斷的等待、喚醒。

看 SensorService:threadLoop()

1.2 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 類型的
mSensorEventBuffer 裏邊,返回可讀取 event 的數目。其中 sensors_event_t 類型是在 hal 層定義的。
SensorService 主要是通過 SensorDevice 與 google-hal 的交互
接着看,
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<SensorEventConnection> > 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<size_t(count) ; i++) {
9. fusion.process(event[i]);//這邊做了什麼,目前還沒有弄清楚
10. }
11. }
12. for (size_t i=0 ; i<size_t(count) && k<minBufferSize ; i++) {
13. for (int handle : mActiveVirtualSensors) {
14. if (count + k >= 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<SensorInterface> 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裏邊,
這個 mSensor 對象爲 SensorList 類型。
這樣的話,前邊

sp<SensorInterface> si = mSensors.getInterface(handle);


通過 handle 獲取 SensorInterface,就是將前面裝進去的 HardwareSensor 對象取出來,進而調用其  si->process(&out,
event[i])
函數,那麼看看 HardwareSensor 的 process()方法咯

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 層的數據的嘛,是作爲指針指向底層的一個數組的,再傳給
event,event再轉給這邊的out,饒了一大圈,原來只不過si->process(&out, event[i])是 將hal層的各個sensors_event_t
的 sensor 內容裝到 out 裏邊。

繼續看 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() 將數據發送出去,然後繼續循環,
ssize_t size = SensorEventQueue::write(mChannel,
reinterpret_cast<ASensorEvent const*>(scratch), count);
這邊發送的話最後是通過一個通過 unix socket 發出去的,
這邊接收的就不分析了,估計是 SensorManager 讀取到數據後給應用,取數據的方式設計思想應該和這邊與 hal 層
交互一樣,留到後面分析 SensorManager 再分析。
小總結一下,SensorService 通過 SensorService::onFirstRef() 執行一些初始化後,就在 SensorService::threadLoop()裏

邊不斷通過 poll 從 hal 層取數據然後通過 unix socket 發送出去.



2  主要類分析

2.1 SensorList  類

裏邊的 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<std::mutex> 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

2.2 sensors_event_t

由 google-hal 定義在/android/hardware/libhardware/include/hardware/sensors.h 裏邊

2.3 SensorEventConnection


3  遺留問題分析

/************************************************/
to do1:Sensordevice 類是什麼、用來做什麼的後面分析,
to do2:harwareSensor 類是什麼、用來幹嘛的後面分析,

好了,接下來對前面遺留的疑問做個分析,
3.1 to do1:SensorDevice  類 是什麼、 用來做什麼 的
ans:SensorDevice 主要是獲取到 hal 層的對象 sp<android::hardware::sensors::V1_0::ISensors> mSensors 後,利用
mSensors 通過 hidl 機制調用 hal 層的方法。
該 ISensors 類型定義在 android/hardware/interfaces/sensors/1.0/ISensors.hal

SensorDevice 類
SensorDevice 繼承了 BinderService<SensorService>,BnSensorServer,Thread
先看構造函數

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<android::hardware::sensors::V1_0::ISensors> mSensors,
接着通過 mSensors(sp<android::hardware::sensors::V1_0::ISensors> mSensors)調用 hal 層的 getSensorsList,然後通
過 convertToSensor(list[i], &sensor)獲取 sensor 後裝進 mSensorList 裏邊;
這邊獲取到 hal 層的 sensor 爲 sensor_t 類型,定義在
android/hardware/libhardware/include/hardware/sensors.h
裏邊,

一句話概括構造函數,就是: 通過 connectHidlService ()與 hal 層建立聯繫後獲取 hal 層的 SensorList


3.2 to do2: harwareSensor  類 是什麼、用來幹嘛的

要分析 HardwareSensor 類,首先要去分析
dev.getSensorList(&list)
以及變量類型 sensor_t,
那就要先分析 SensorDevice 了
通過 dev.getSensorList(&list)獲取到的 hal 層的 sensor_t 的變量,用來初始化 HardwareSensor 對象,其實就是對其父
類 BaseSensor 的 mSensor(Sensor mSensor)成員進行初始化,該 Sensor 類我目前估計就是 framework 層的 Sensor
類通用表示了,定義在 frameworks/native/libs/sensor/include/sensor 裏邊,也就是將 hal 層獲取到的 sensor_t 類型
變量轉換層 framework 層的 Sensor 類型變量,

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章