Vehicle HAL(2)--Vehicle HAL 的启动
目录
1. VehicleService-main 函数分析
2. 构建EmulatedVehicleHal
2.1 EmulatedVehicleHal::EmulatedVehicleHal(xxx)
2.2 EmulatedVehicleHal::initStaticConfig()
2.3 EmulatedVehicleHal::onPropertyValue()
3. 构建VehicleEmulator
4. 构建VehicleHalManager
(1)初始化成员变量SubscriptionManager mSubscriptionManager
(2)调用VehicleHalManager::init()
a. 调用VehicleHal::init()
b. mHal->listProperties() 获取支持的属性
5. 构建WatchdogClient对象,并初始化
6. vhal主线程开启while(true)循环
1. VehicleService-main 函数分析
vhal在VehicleService-main中启动。具体代码如下:
hardware/interfaces/automotive/vehicle/2.0/default/VehicleService.cpp
17 #define LOG_TAG "automotive.vehicle@2.0-service"
18 #include <android/log.h>
19 #include <hidl/HidlTransportSupport.h>
20
21 #include <iostream>
22
23 #include <android/binder_process.h>
24 #include <utils/Looper.h>
25 #include <vhal_v2_0/EmulatedVehicleConnector.h>
26 #include <vhal_v2_0/EmulatedVehicleHal.h>
27 #include <vhal_v2_0/VehicleHalManager.h>
28 #include <vhal_v2_0/WatchdogClient.h>
29
30 using namespace android;
31 using namespace android::hardware;
32 using namespace android::hardware::automotive::vehicle::V2_0;
33
34 int main(int /* argc */, char* /* argv */ []) {
35 auto store = std::make_unique<VehiclePropertyStore>();//新建对象,采用默认构造函数VehiclePropertyStore
36 auto connector = std::make_unique<impl::EmulatedVehicleConnector>();//同上,构建EmulatedVehicleConnector
37 auto hal = std::make_unique<impl::EmulatedVehicleHal>(store.get(), connector.get());//第2章,获取对象的指针,来新建EmulatedVehicleHal
38 auto emulator = std::make_unique<impl::VehicleEmulator>(hal.get());//第3章,新建VehicleEmulator
39 auto service = std::make_unique<VehicleHalManager>(hal.get());//第4章,构建VehicleHalManager,传入hal指针,VehicleHalManager是实现hidl服务的主体
40 connector->setValuePool(hal->getValuePool());//属性池的指针设置给connector
41
42 configureRpcThreadpool(4, false /* callerWillJoin */);
43
44 ALOGI("Registering as service...");
45 status_t status = service->registerAsService();//hidl服务注册
46
47 if (status != OK) {
48 ALOGE("Unable to register vehicle service (%d)", status);
49 return 1;
50 }
51
52 // Setup a binder thread pool to be a car watchdog client.
53 ABinderProcess_setThreadPoolMaxThreadCount(1);
54 ABinderProcess_startThreadPool();
55 sp<Looper> looper(Looper::prepare(0 /* opts */));
56 std::shared_ptr<WatchdogClient> watchdogClient =
57 ndk::SharedRefBase::make<WatchdogClient>(looper, service.get());//第5章,构建WatchdogClient对象,并初始化
58 // The current health check is done in the main thread, so it falls short of capturing the real
59 // situation. Checking through HAL binder thread should be considered.
60 if (!watchdogClient->initialize()) {//初始化
61 ALOGE("Failed to initialize car watchdog client");
62 return 1;
63 }
64 ALOGI("Ready");
65 while (true) {
66 looper->pollAll(-1 /* timeoutMillis */);//第6章,开启while(true)循环
67 }
68
69 return 1;
70 }
71
2. 构建EmulatedVehicleHal
EmulatedVehicleHal实现了vhal中的VehicleHal抽象类。
从下图可以看出继承关系。
android11/hardware/interfaces/automotive/vehicle/2.0/default/impl/vhal_v2_0/EmulatedVehicleHal.h
android11/hardware/interfaces/automotive/vehicle/2.0/default/common/include/vhal_v2_0/VehicleHal.h
获取对象的指针,来新建EmulatedVehicleHal
EmulatedVehicleHal(VehiclePropertyStore* propStore, VehicleHalClient* client,EmulatedUserHal* emulatedUserHal = nullptr); |
EmulatedVehicleHal本身存放了很多静态配置的属性值,构建的时候会传入mPropStore。
2.1 EmulatedVehicleHal::EmulatedVehicleHal(xxx)
EmulatedVehicleHal::EmulatedVehicleHal(VehiclePropertyStore* propStore, VehicleHalClient* client,EmulatedUserHal* emulatedUserHal): mPropStore(propStore),//缓存,属性storemHvacPowerProps(std::begin(kHvacPowerProperties), std::end(kHvacPowerProperties)),mRecurrentTimer(std::bind(&EmulatedVehicleHal::onContinuousPropertyTimer, this,std::placeholders::_1)),mVehicleClient(client),//VehicleHalClient* mVehicleClient; 缓存,多重继承的EmulatedVehicleConnectormEmulatedUserHal(emulatedUserHal) {//初始化为nullinitStaticConfig();//初始化静态配置,里面会调用mPropStore->registerProperty(),有mPropStore的进一步操作for (size_t i = 0; i < arraysize(kVehicleProperties); i++) {mPropStore->registerProperty(kVehicleProperties[i].config);//继续初始化mPropStore,注册一些属性}mVehicleClient->registerPropertyValueCallback(std::bind(&EmulatedVehicleHal::onPropertyValue,//会从mVehicleClient触发回调回来this, std::placeholders::_1,std::placeholders::_2));//关键调用,属性变化之后的回调
}
2.2 EmulatedVehicleHal::initStaticConfig()
EmulatedVehicleHal() > EmulatedVehicleHal::initStaticConfig() > mPropStore->registerProperty()
kVehicleProperties是静态配置好了的。
195 const ConfigDeclaration kVehicleProperties[]
android11/hardware/interfaces/automotive/vehicle/2.0/default/impl/vhal_v2_0/DefaultConfig.h
360 void EmulatedVehicleHal::initStaticConfig() {
361 for (auto&& it = std::begin(kVehicleProperties); it != std::end(kVehicleProperties); ++it) {
362 const auto& cfg = it->config;
363 VehiclePropertyStore::TokenFunction tokenFunction = nullptr;
364
365 switch (cfg.prop) {
366 case OBD2_FREEZE_FRAME: {
367 tokenFunction = [](const VehiclePropValue& propValue) {
368 return propValue.timestamp;
369 };
370 break;
371 }
372 default:
373 break;
374 }
375
376 mPropStore->registerProperty(cfg, tokenFunction);//关键代码
377 }
378 }
38 void VehiclePropertyStore::registerProperty(const VehiclePropConfig& config,
39 VehiclePropertyStore::TokenFunction tokenFunc) {
40 MuxGuard g(mLock);
41 mConfigs.insert({ config.prop, RecordConfig { config, tokenFunc } });//向std::unordered_map中插入
42 }
hardware/interfaces/automotive/vehicle/2.0/default/common/include/vhal_v2_0/VehiclePropertyStore.h 93 std::unordered_map<int32_t /* VehicleProperty */, RecordConfig> mConfigs;
2.3 EmulatedVehicleHal::onPropertyValue()
此为传递属性改变的关键函数
351 void EmulatedVehicleHal::onPropertyValue(const VehiclePropValue& value, bool updateStatus) {
352 VehiclePropValuePtr updatedPropValue = getValuePool()->obtain(value);
353
354 if (mPropStore->writeValue(*updatedPropValue, updateStatus)) {//更新属性
355 getEmulatorOrDie()->doSetValueFromClient(*updatedPropValue);//关键调用,Emulator,client,获取时通过socket走到can的另外一端
356 doHalEvent(std::move(updatedPropValue));//关键调用,返回变化到carservice
357 }
358 }
3. 构建VehicleEmulator
模拟车,做一些通信接口相关的初始化。把消息发给可能存在的ecu。在原生上是通过can给ecu发消息。见上一节EmulatedVehicleHal的onPropertyValue消息处理中有getEmulatorOrDie()->doSetValueFromClient(xxx)。
class VehicleEmulator : public MessageProcessor
用刚才构建的EmulatedVehicleHal来构建VehicleEmulator。VehicleEmulator模拟的vehicle,或者说模拟的car。
/**
* Emulates vehicle by providing controlling interface from host side either through ADB or Pipe.
*/
VehicleEmulator(EmulatedVehicleHalIface* hal);
VehicleEmulator::VehicleEmulator(EmulatedVehicleHalIface* hal) : mHal{hal} {mHal->registerEmulator(this);//把自己注册到EmulatedVehicleHal中,VehicleEmulator和mHal产生关系。mHal可以调用到VehicleEmulator。ALOGI("Starting SocketComm");mSocketComm = std::make_unique<SocketComm>(this);//新建socket通信相关对象mSocketComm->start();if (android::base::GetBoolProperty("ro.kernel.qemu", false)) {ALOGI("Starting PipeComm");mPipeComm = std::make_unique<PipeComm>(this);//pipe相关的mPipeComm->start();}if (android::base::GetBoolProperty("persist.vendor.cansocket", false)) {//enable siengine CanSocketCommALOGI("Starting CanSocketComm");mCanSocketComm = std::make_unique<CanSocketComm>(this);//CanSocketCommmCanSocketComm->start();}
}
4. 构建VehicleHalManager
构建VehicleHalManager的关键过程为有3步。VehicleHalManager实现了IVehiclel接口,hal服务的主体。
VehicleHalManager(VehicleHal* vehicleHal): mHal(vehicleHal),//初始化mHalmSubscriptionManager(std::bind(&VehicleHalManager::onAllClientsUnsubscribed,this, std::placeholders::_1)) {//初始化mSubscriptionManagerinit();//调用自己的init()函数}
(1)初始化成员变量SubscriptionManager mSubscriptionManager
SubscriptionManager 的构造函数
/*** Constructs SubscriptionManager** @param onPropertyUnsubscribed - called when no more clients are subscribed to the property.*/SubscriptionManager(const OnPropertyUnsubscribed& onPropertyUnsubscribed): mOnPropertyUnsubscribed(onPropertyUnsubscribed),//初始化给mOnPropertyUnsubscribedmCallbackDeathRecipient(new DeathRecipient(std::bind(&SubscriptionManager::onCallbackDead, this, std::placeholders::_1))){}
(2)调用VehicleHalManager::init()
hardware/interfaces/automotive/vehicle/2.0/default/common/src/VehicleHalManager.cpp
431 void VehicleHalManager::init() {
432 ALOGI("VehicleHalManager::init");
433
434 mHidlVecOfVehiclePropValuePool.resize(kMaxHidlVecOfVehiclPropValuePoolSize);
435
436
437 mBatchingConsumer.run(&mEventQueue,
438 kHalEventBatchingTimeWindow,
439 std::bind(&VehicleHalManager::onBatchHalEvent,
440 this, _1));//启动mBatchingConsumer
441
442 mHal->init(&mValueObjectPool,
443 std::bind(&VehicleHalManager::onHalEvent, this, _1),
444 std::bind(&VehicleHalManager::onHalPropertySetError, this,
445 _1, _2, _3));//a.调用hal的init函数
446
447 // Initialize index with vehicle configurations received from VehicleHal.
448 auto supportedPropConfigs = mHal->listProperties();//b.获取支持的属性
449 mConfigIndex.reset(new VehiclePropConfigIndex(supportedPropConfigs));//放入mConfigIndex
450
451 std::vector<int32_t> supportedProperties(
452 supportedPropConfigs.size());
453 for (const auto& config : supportedPropConfigs) {
454 supportedProperties.push_back(config.prop);
455 }
456 }
a. 调用VehicleHal::init()
调用hal的init函数:VehicleHal的init函数
93 void init(
94 VehiclePropValuePool* valueObjectPool,
95 const HalEventFunction& onHalEvent,
96 const HalErrorFunction& onHalError) {
97 mValuePool = valueObjectPool;
98 mOnHalEvent = onHalEvent;
99 mOnHalPropertySetError = onHalError;
100
101 onCreate();
102 }
b. mHal->listProperties() 获取支持的属性
hardware/interfaces/automotive/vehicle/2.0/default/impl/vhal_v2_0/EmulatedVehicleHal.cpp
290 std::vector<VehiclePropConfig> EmulatedVehicleHal::listProperties() {
291 return mPropStore->getAllConfigs();
292 }
mHal中mPropStore的来源
hardware/interfaces/automotive/vehicle/2.0/default/impl/vhal_v2_0/EmulatedVehicleHal.cpp
90 EmulatedVehicleHal::EmulatedVehicleHal(VehiclePropertyStore* propStore, VehicleHalClient* client,
91 EmulatedUserHal* emulatedUserHal)
92 : mPropStore(propStore),//mPropStore的来源
93 mHvacPowerProps(std::begin(kHvacPowerProperties), std::end(kHvacPowerProperties)),
94 mRecurrentTimer(std::bind(&EmulatedVehicleHal::onContinuousPropertyTimer, this,
95 std::placeholders::_1)),
96 mVehicleClient(client),
97 mEmulatedUserHal(emulatedUserHal) {
98 initStaticConfig();
99 for (size_t i = 0; i < arraysize(kVehicleProperties); i++) {
100 mPropStore->registerProperty(kVehicleProperties[i].config);
101 }
102 mVehicleClient->registerPropertyValueCallback(std::bind(&EmulatedVehicleHal::onPropertyValue,
103 this, std::placeholders::_1,
104 std::placeholders::_2));
105 }
106
mPropStore->getAllConfigs()的实现:
hardware/interfaces/automotive/vehicle/2.0/default/common/src/VehiclePropertyStore.cpp
124 std::vector<VehiclePropConfig> VehiclePropertyStore::getAllConfigs() const {
125 MuxGuard g(mLock);
126 std::vector<VehiclePropConfig> configs;
127 configs.reserve(mConfigs.size());//从mConfigs来
128 for (auto&& recordConfigIt: mConfigs) {//遍历mConfigs
129 configs.push_back(recordConfigIt.second.propConfig);
130 }
131 return configs;
132 }
5. 构建WatchdogClient对象,并初始化
explicit WatchdogClient(const ::android::sp<::android::Looper>& handlerLooper,
VehicleHalManager* vhalManager);
将自己加入car watchdog的监控。
WatchdogClient::WatchdogClient(const sp<Looper>& handlerLooper, VehicleHalManager* vhalManager): mHandlerLooper(handlerLooper), mVhalManager(vhalManager), mCurrentSessionId(-1) {mMessageHandler = new MessageHandlerImpl(this);//新建内部的handler
}
bool WatchdogClient::initialize() {ndk::SpAIBinder binder(AServiceManager_getService("android.automotive.watchdog.ICarWatchdog/default"));//获取服务if (binder.get() == nullptr) {ALOGE("Failed to get carwatchdog daemon");return false;}std::shared_ptr<ICarWatchdog> server = ICarWatchdog::fromBinder(binder);if (server == nullptr) {ALOGE("Failed to connect to carwatchdog daemon");return false;}mWatchdogServer = server;//保存serverbinder = this->asBinder();if (binder.get() == nullptr) {ALOGE("Failed to get car watchdog client binder object");return false;}std::shared_ptr<ICarWatchdogClient> client = ICarWatchdogClient::fromBinder(binder);if (client == nullptr) {ALOGE("Failed to get ICarWatchdogClient from binder");return false;}mTestClient = client;mWatchdogServer->registerClient(client, TimeoutLength::TIMEOUT_NORMAL);//把自己注册到sever端,类型为TIMEOUT_NORMAL型的checkALOGI("Successfully registered the client to car watchdog server");return true;
}
接收来自sever(carwatchdogd)的回调
ndk::ScopedAStatus WatchdogClient::prepareProcessTermination() {return ndk::ScopedAStatus::ok();
}
6. vhal主线程开启while(true)循环
64 ALOGI("Ready");
65 while (true) {
66 looper->pollAll(-1 /* timeoutMillis */);//开启while(true)循环,主线程一直睡在这里
67 }