首先来讲讲蓝牙协议栈的打开,从上层到底层,上层注册好callback后,底层再通过调用的注册的函数,向上层反馈底层消息。从上层开始平台各种类初始化,到调用到com_android_bluetooth_btservice_AdapterService的函数时,到此开始加载bluetooth.default.so模块,
static void classInitNative(JNIEnv* env, jclass clazz) {
int err;
hw_module_t* module;
err = hw_get_module(id, (hw_module_t const**)&module);/*加载蓝牙协议栈,bluetooth.default.so*/
if (err == 0) {
hw_device_t* abstraction;
err = module->methods->open(module, id, &abstraction);
if (err == 0) {
bluetooth_module_t* btStack = (bluetooth_module_t *)abstraction;
sBluetoothInterface = btStack->get_bluetooth_interface();/*获取蓝牙句柄*/
} else {
ALOGE("Error while opening Bluetooth library");
}
} else {
ALOGE("No Bluetooth Library found");
}
}
其中static const bt_interface_t *sBluetoothInterface = NULL;
与协议栈的数据结构一致
const bt_interface_t* bluetooth__get_bluetooth_interface ()
{
/* fixme -- add property to disable bt interface ? */
return &bluetoothInterface;
}
其中函数如下,即这部是获取函数句柄,通过这些句柄,上层直接call到底层,从而实现相应的操作调用
static const bt_interface_t bluetoothInterface = {
sizeof(bluetoothInterface),
init,
enable,
disable,
cleanup,
get_adapter_properties,
get_adapter_property,
set_adapter_property,
get_remote_device_properties,
get_remote_device_property,
set_remote_device_property,
get_remote_service_record,
get_remote_services,
start_discovery,
cancel_discovery,
create_bond,
remove_bond,
cancel_bond,
get_connection_state,
pin_reply,
ssp_reply,
get_profile_interface,
dut_mode_configure,
dut_mode_send,
#if BLE_INCLUDED == TRUE
le_test_mode,
#else
NULL,
#endif
config_hci_snoop_log,
set_os_callouts,
read_energy_info,
dump,
config_clear
}
蓝牙adapterservice创建时,初始化即调用jni接口
public void onCreate() {
super.onCreate();
debugLog("onCreate()");
mBinder = new AdapterServiceBinder(this);
mAdapterProperties = new AdapterProperties(this);
mAdapterStateMachine = AdapterState.make(this, mAdapterProperties);
mJniCallbacks = new JniCallbacks(mAdapterStateMachine, mAdapterProperties);
initNative();
mNativeAvailable=true;
static bool initNative(JNIEnv* env, jobject obj) {
ALOGV("%s:",__FUNCTION__);
sJniAdapterServiceObj = env->NewGlobalRef(obj);
sJniCallbacksObj = env->NewGlobalRef(env->GetObjectField(obj, sJniCallbacksField));
if (sBluetoothInterface) {
/*注册 callback -->sBluetoothCallbacks*/
int ret = sBluetoothInterface->init(&sBluetoothCallbacks);
if (ret != BT_STATUS_SUCCESS) {
ALOGE("Error while setting the callbacks: %d\n", ret);
sBluetoothInterface = NULL;
return JNI_FALSE;
}
ret = sBluetoothInterface->set_os_callouts(&sBluetoothOsCallouts);
if (ret != BT_STATUS_SUCCESS) {
ALOGE("Error while setting Bluetooth callouts: %d\n", ret);
sBluetoothInterface->cleanup();
sBluetoothInterface = NULL;
return JNI_FALSE;
}
/*获取蓝牙BT_PROFILE_SOCKETS_ID的句柄*/
if ( (sBluetoothSocketInterface = (btsock_interface_t *)
sBluetoothInterface->get_profile_interface(BT_PROFILE_SOCKETS_ID)) == NULL) {
ALOGE("Error getting socket interface");
}
return JNI_TRUE;
}
return JNI_FALSE;
}
其中以上的callback为:底层通过这些注册的callback从而来实现将底层的消息反馈给上层,如发现新设备,设备属性变化,绑定状态,连接状态等
static bt_callbacks_t **sBluetoothCallbacks** = {
sizeof(sBluetoothCallbacks),
adapter_state_change_callback,
adapter_properties_callback,
remote_device_properties_callback,
device_found_callback,
discovery_state_changed_callback,
pin_request_callback,
ssp_request_callback,
bond_state_changed_callback,
acl_state_changed_callback,
callback_thread_event,
dut_mode_recv_callback,
le_test_mode_recv_callback,
energy_info_recv_callback
}
/*初始化协议栈,*/
static int init(bt_callbacks_t *callbacks) {
LOG_INFO("%s", __func__);
if (interface_ready())/*检测是否已经初始化过一次,第一次初化始bt_hal_cbacks为null则走下去接下来的流程*/
return BT_STATUS_DONE;
#ifdef BLUEDROID_DEBUG
allocation_tracker_init();
#endif
bt_hal_cbacks = callbacks;/*将回调函数赋值给协议栈的全局变量,用于后面调用反馈设备状态信息*/
stack_manager_get_interface()->init_stack();
btif_debug_init();//好像是申请btsnoop内存,用于存储debug信息
/*其中
const stack_manager_t *stack_manager_get_interface() {
ensure_manager_initialized();
return &interface;
}
static void ensure_manager_initialized(void) {
if (management_thread) //第一次来都没有初始化,因此走到下面的流程
return;
management_thread = thread_new("stack_manager");//创建一个管理线程,供后面调用,也表明管理类已初始化完成stack_manager
if (!management_thread) {
LOG_ERROR("%s unable to create stack management thread.", __func__);
return;
}
}
上面返回的接口中
static const stack_manager_t interface = {
init_stack,
start_up_stack_async,
shut_down_stack_async,
clean_up_stack_async,
get_stack_is_running
};
调用init_stack函数
*/
btif_debug_init();
return BT_STATUS_SUCCESS;
}
static void init_stack(void) {
// This is a synchronous process. Post it to the thread though, so
// state modification only happens there.
semaphore_t *semaphore = semaphore_new(0);
thread_post(management_thread, event_init_stack, semaphore);/*接下来执行event_init_stack这个func*/
semaphore_wait(semaphore);
semaphore_free(semaphore);
}
// Synchronous function to initialize the stack
static void event_init_stack(void *context) {
semaphore_t *semaphore = (semaphore_t *)context;
if (!stack_is_initialized) {/*第一次进入里面*/
module_management_start();/*创建一些hash表指针之类的*/
module_init(get_module(BT_UTILS_MODULE));/*执行BT_UTILS_MODULE、BTIF_CONFIG_MODULE模块的init函数*/
module_init(get_module(BTIF_CONFIG_MODULE));
btif_init_bluetooth();/*初始化btif*/
// stack init is synchronous, so no waiting necessary here
stack_is_initialized = true;/*表明已初始化过*/
}
if (semaphore)
semaphore_post(semaphore);
}
上面的模块中BT_UTILS_MODULE、BTIF_CONFIG_MODULE
BT_UTILS_MODULE这个用法不清楚是做什么的,好像是信号量之类的
BTIF_CONFIG_MODULE中的init函数如下:
---------------------------------------------------------------------------------------------------------------------
static future_t *init(void) {
pthread_mutex_init(&lock, NULL);
config = config_new(CONFIG_FILE_PATH);/*static const char *CONFIG_FILE_PATH = "/data/misc/bluedroid/bt_config.conf";
打开这个配置文件*/
if (!config) {
LOG_WARN("%s unable to load config file; attempting to transcode legacy file.", __func__);
config = btif_config_transcode(LEGACY_CONFIG_FILE_PATH);/*打开失败则去打开这个配置文件static const char *LEGACY_CONFIG_FILE_PATH = "/data/misc/bluedroid/bt_config.xml";
*/
if (!config) {
LOG_WARN("%s unable to transcode legacy file, starting unconfigured.", __func__);
config = config_new_empty();/*创建一个文件并保存*/
if (!config) {
LOG_ERROR("%s unable to allocate a config object.", __func__);
goto error;
}
}
if (config_save(config, CONFIG_FILE_PATH))/*创建一个文件并保存*/
unlink(LEGACY_CONFIG_FILE_PATH);
}
btif_config_remove_unpaired(config);/*删除掉解配对key的配置文件,将保存在cache中*/
// Cleanup temporary pairings if we have left guest mode
if (!is_restricted_mode())
btif_config_remove_restricted(config);
// TODO(sharvil): use a non-wake alarm for this once we have
// API support for it. There's no need to wake the system to
// write back to disk.
alarm_timer = alarm_new();/*申请时钟,暂不知道做什么的*/
if (!alarm_timer) {
LOG_ERROR("%s unable to create alarm.", __func__);
goto error;
}
return future_new_immediate(FUTURE_SUCCESS);
error:;
alarm_free(alarm_timer);
config_free(config);
pthread_mutex_destroy(&lock);
alarm_timer = NULL;
config = NULL;
return future_new_immediate(FUTURE_FAIL);
}
下面来看看最后一个函数btif_init_bluetooth
-----------------------------------------------------
/*******************************************************************************
**
** Function btif_init_bluetooth
**
** Description Creates BTIF task and prepares BT scheduler for startup
**
** Returns bt_status_t
**
*******************************************************************************/
bt_status_t btif_init_bluetooth() {
bte_main_boot_entry();/*初始化bte*/
/* As part of the init, fetch the local BD ADDR */
memset(&btif_local_bd_addr, 0, sizeof(bt_bdaddr_t));
btif_fetch_local_bdaddr(&btif_local_bd_addr);/*获取模组MAC地址*/
bt_jni_workqueue_thread = thread_new(BT_JNI_WORKQUEUE_NAME);
if (bt_jni_workqueue_thread == NULL) {
LOG_ERROR("%s Unable to create thread %s", __func__, BT_JNI_WORKQUEUE_NAME);
goto error_exit;
}
// Associate this workqueue thread with jni.
btif_transfer_context(btif_jni_associate, 0, NULL, 0, NULL);
return BT_STATUS_SUCCESS;
error_exit:;
thread_free(bt_jni_workqueue_thread);
bt_jni_workqueue_thread = NULL;
return BT_STATUS_FAIL;
}
首先看初始化bte的部分:
bte_main_boot_entry
----------------------------------------------------bte_main_boot_entry----------------------------------------------------------
/******************************************************************************
**
** Function bte_main_boot_entry
**
** Description BTE MAIN API - Entry point for BTE chip/stack initialization
**
** Returns None
**
******************************************************************************/
void bte_main_boot_entry(void)
{
module_init(get_module(GKI_MODULE));
module_init(get_module(COUNTER_MODULE));
hci = hci_layer_get_interface();/*获取hci接口,static const hci_t *hci;*/
if (!hci)
LOG_ERROR("%s could not get hci layer interface.", __func__);
btu_hci_msg_queue = fixed_queue_new(SIZE_MAX);/*创建btu线程*/
if (btu_hci_msg_queue == NULL) {
LOG_ERROR("%s unable to allocate hci message queue.", __func__);
return;
}
data_dispatcher_register_default(hci->event_dispatcher, btu_hci_msg_queue);
hci->set_data_queue(btu_hci_msg_queue);/*upwards_data_queue =btu_hci_msg_queue( 指向interface.event_dispatcher = data_dispatcher_new("hci_layer");) */
#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
bte_load_ble_conf(BTE_BLE_STACK_CONF_FILE);/*加载并解析/etc/bluetooth/ble_stack.conf配置文件*/
#endif
module_init(get_module(STACK_CONFIG_MODULE));/*加载并解析/etc/bluetooth/bt_stack.conf配置文件*/
}
----------------------------各种接口获取-------------------------
const hci_t *hci_layer_get_interface() {
buffer_allocator = buffer_allocator_get_interface();
hal = hci_hal_get_interface();
btsnoop = btsnoop_get_interface();
hci_inject = hci_inject_get_interface();
packet_fragmenter = packet_fragmenter_get_interface();
vendor = vendor_get_interface();
low_power_manager = low_power_manager_get_interface();/*低功耗管理接口*/
init_layer_interface();
return &interface;
}
static void init_layer_interface() {
if (!interface_created) {/*第一次到里面*/
interface.send_low_power_command = low_power_manager->post_command;
interface.do_postload = do_postload;
// It's probably ok for this to live forever. It's small and
// there's only one instance of the hci interface.
interface.event_dispatcher = data_dispatcher_new("hci_layer");
if (!interface.event_dispatcher) {
LOG_ERROR("%s could not create upward dispatcher.", __func__);
return;
}
interface.set_data_queue = set_data_queue;
interface.transmit_command = transmit_command;
interface.transmit_command_futured = transmit_command_futured;
interface.transmit_downward = transmit_downward;
interface_created = true;
}
}
到这里就初始化完毕