软总线作为系统服务,在系统启动,Init进程加载时,通过解析配置文件softbus_server.rc完成系统服务的启动,软总线服务的加载函数为InitSoftBusServer,其源码如下:
void InitSoftBusServer(void)
{
if (SoftBusTimerInit() != SOFTBUS_OK) {
return;
}
if (LooperInit() != SOFTBUS_OK) {
return;
}
if (ConnServerInit() != SOFTBUS_OK) {
LOG_ERR("softbus conn server init failed.");
goto ERR_EXIT;
}
if (TransServerInit() != SOFTBUS_OK) {
LOG_ERR("softbus trans server init failed.");
goto ERR_EXIT;
}
if (AuthInit() != SOFTBUS_OK) {
LOG_ERR("softbus auth init failed.");
goto ERR_EXIT;
}
if (BusCenterServerInit() != SOFTBUS_OK) {
LOG_ERR("softbus buscenter server init failed.");
goto ERR_EXIT;
}
if (DiscServerInit() != SOFTBUS_OK) {
LOG_ERR("softbus disc server init failed.");
goto ERR_EXIT;
}
return;
ERR_EXIT:
ServerModuleDeinit();
LOG_ERR("softbus server framework init failed.");
return;
}
InitSoftBusServer的代码还是比较简洁的,其主要的功能如下:1.加载定时器;2.加载Looper;3.加载连接服务;4.加载传输服务;5.加载认证服务;6.加载组网服务;7.加载发现服务。下面我们分别介绍这几个处理:
一.加载定时器
SoftBusTimerInit的源码如下:
int32_t SoftBusTimerInit(void)
{
if (g_timerId != NULL) {
return SOFTBUS_OK;
}
g_timerId = SoftBusCreateTimer(&g_timerId, (void *)HandleTimeoutFun, TIMER_TYPE_PERIOD);
if (SoftBusStartTimer(g_timerId, TIMER_TIMEOUT) != SOFTBUS_OK) {
LOG_ERR("start timer failed.");
(void)SoftBusDeleteTimer(g_timerId);
g_timerId = NULL;
return SOFTBUS_ERR;
}
return SOFTBUS_OK;
}
由源码可知,SoftBusTimerInit创建了一个定时器,定时器的值保存在g_timerId中,周期为1S,其处理函数为HandleTimeoutFun。
HandleTimeoutFun的源码如下所示:
static void HandleTimeoutFun(void)
{
int32_t i;
for (i = 0; i < SOFTBUS_MAX_TIMER_FUN_NUM; i++) {
if (g_timerFunList[i] != NULL) {
g_timerFunList[i]();
}
}
}
这是一个很典型的发布/订阅模式,即各个模块将要处理的函数注册到函数指针数组g_timerFunList中,等到定时器周期到达的时候,挨个调用注册的函数。
二.加载Looper
LooperInit源码如下:
int LooperInit(void)
{
SoftBusLooper *looper = CreateNewLooper("Loop-default");
if (!looper) {
LOG_ERR("init looper fail.");
return -1;
}
SetLooper(LOOP_TYPE_DEFAULT, looper);
LOG_INFO("init looper success.");
return 0;
}
即创建一个类型为LOOP_TYPE_DEFAULT的Looper,并将其保存起来。Cre