Android bluedroid (ii): bluedroid Bluetooth Open Process init

Source: Internet
Author: User

Keywords: bluedroid initnative enablenative btif_task btu_taskbt_hc_work_thread set_power preload GKI
xubin341719 (Welcome reprint, please specify the author, please respect copyright, thank you!) )
Welcome to correct mistakes, common learning, common progress!!

first, the Bluetooth open process overview, as shown in: Init, enable

And the general function calls the same, Android upper layer through App-->native-->jni-->bluetoothinterface-->bluetooth hciinterface. The corresponding functions of init, set_power and preload are implemented in HCI interface
The main functions of the INIT and enable functions are:
(1), Created: Btif_task/btif_task
(2), initialize BTE
(3), created: Btu_task/btu_task
(4), initialization of HCI, serial correlation, start HCI work main thread: bt_hc_callback, Chip power, RF parameters initialization, Bluetooth address name related settings;
(5), create: Bt_hc_worker_thread Bluetooth work main thread, send receive command;
(6), initialize the Bluetooth protocol stack;
The realization of the initnative function
This part mainly initiates the corresponding sock, protocol stack initialization, start btif_task, and listens to the Bluetooth interface related status messages. The implementation process is shown below.


1. Apply partial function call (starting from Adatper)
Packages\apps\bluetooth\src\com\android\bluetooth\btservice\ Adapterservice.java

    public void OnCreate () {        super.oncreate ();        if (DBG) debuglog ("OnCreate");        Mbinder = new Adapterservicebinder (this);        Madapterproperties = new Adapterproperties (this);        Madapterstatemachine =  Adapterstate.make (this, madapterproperties);        Mjnicallbacks =  New Jnicallbacks (Madapterstatemachine, madapterproperties);        Initnative ();//Call initnative function;        mnativeavailable=true;        Mcallbacks = new remotecallbacklist<ibluetoothcallback> ();        Load the name and address        getadapterpropertynative (abstractionlayer.bt_property_bdaddr);        Getadapterpropertynative (abstractionlayer.bt_property_bdname);} Private native Boolean initnative ();

2, the implementation of the JNI function, this part is the same as other JNI implementations.
packages\apps\bluetooth\jni\ Com_android_bluetooth_btservice_adapterservice.cpp

Static Jninativemethod smethods[] = {    /* name, signature, funcptr *    /{"Classinitnative", "() V", (void *) Classinit Native},    {"Initnative", "() Z", (void *) initnative},//native function Implementation ...}

Packages\apps\bluetooth\jni\com_android_bluetooth_btservice_adapterservice.cpp
The concrete implementation of the Initnative function is implemented by bt_interface_t the struct, calling to the Init function in C. The sbluetoothcallbacks callback function structure is also passed in. This function structure is more important, and the underlying state changes are implemented by the function in the structure of the callback function.

static const bt_interface_t *sbluetoothinterface = null;static bool Initnative (jnienv* env, Jobject obj) {    Sjnicallba Cksobj = Env->newglobalref (Env->getobjectfield (obj, Sjnicallbacksfield));    if (sbluetoothinterface) {        int ret = Sbluetoothinterface->init (&sbluetoothcallbacks);//The corresponding interface function        called to C if (ret! = bt_status_success) {//error handling,            Aloge ("error while setting the callbacks \ n");            Sbluetoothinterface = NULL;            return jni_false;        }        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;}

3, JNI call C function implementation
C implements the function of the upper call, and finally implements the Java Call C function action. This is the specific step of the Android system to the kernel operation. If it is a beginner, it is recommended to make this part of the content clear, the entire Android system to the bottom of the operation is done in this way.
external\bluetooth\bluedroid\btif\src\bluetooth.c

static const bt_interface_t Bluetoothinterface = {///Bluetooth interface function for function    sizeof (bluetoothinterface),    init,// The implementation of the INIT function in C function;    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,    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};

4. The process of init function implementation in Bluetooth interface function
External\bluetooth\bluedroid\btif\src\bluetooth.c

static int init (bt_callbacks_t* callbacks) {    Alogi ("Init");    /* Sanity Check *    /if (interface_ready () = = TRUE)//check that the interface function is ready;        return bt_status_done;    /* Store reference to user callbacks */    bt_hal_cbacks = callbacks;//The corresponding callback function to save, this is very important, just start to see the code is to ignore this part, We explain in a separate section the implementation and function of this part of the callback function;    /* Add checks for individual callbacks?    //Bt_utils_init ();//The Toolset initializes, initializing a mutex.    /* init btif */btif_init_bluetooth ();//Initialize Bluetooth interface bluetoothinterface    return bt_status_success;}

5, the implementation of Bluetooth interface initialization, Btif_init_bluetooth create btif task, prepare Bluetooth to open the relevant scheduler.
The implementation process is as follows, and we'll explain the code in detail below. The main completed:
(1), Bt_config.xml file, such as Bluetooth name processing;
(2), Gki initialization, this section behind a single section to do detailed analysis;
(3), bluehclibinterface initialization, implementation of power\preload\ functions, bluedreoid log level setting;
(4), Btif_task thread creation, this part is also more important.

External\bluetooth\bluedroid\btif\src\btif_core.c

bt_status_t Btif_init_bluetooth () {    UINT8 status;    Btif_config_init ();//Create sock thread, initialize related data in/data/misc/bluedroid/bt_config.xml,    bte_main_boot_entry ();//(1), BTE chip protocol stack Ingress API, Bluetooth protocol stack/chip initialization, GKI INIT,/* As part of    the INIT, fetch the local BD ADDR *    /memset (&btif_local_bd_a DDR, 0, sizeof (bt_bdaddr_t));//take Bluetooth address to write related files;    btif_fetch_local_bdaddr (&BTIF_LOCAL_BD_ADDR);    /* Start btif Task * *    status = Gki_create_task (Btif_task, Btif_task, Btif_task_str,                (UINT16 *) ((UINT8 *) Btif_tas K_stack + btif_task_stack_size),                sizeof (Btif_task_stack)),//(2), creates BTIF TASK and prepares BT scheduler for Startup  creates the Bluetooth task interface, prepares the    if (status! = gki_success)        return bt_status_fail for the start-up schedule;    return bt_status_success;}

(1), BTE chip protocol stack entry API, Bluetooth protocol stack/chip initialization, GKI init;
External\bluetooth\bluedroid\main\bte_main.c

void Bte_main_boot_entry (void) {/    * Initialize OS */    Gki_init ();//1), Gki initialization, is only called once at initialization time.    bte_main_in_hw_init ();//2), initializing structure static bt_hc_interface_t *bt_hc_if=null;    Bte_load_conf (bte_stack_conf_file);//3), initialize bluedroid debug information level, #if (bttrc_included = TRUE)//initialization of related printing information;/    * Initialize Trace Feature *    /Bttrc_traceinit (Max_trace_ram_size, &bte_tracelogbuf[0], bttrc_method_ram); # endif


1), Gki initialization, only one call at initialization time
Reference Mutual exclusion Lock: http://blog.csdn.net/kingmax26/article/details/5338065;
External\bluetooth\bluedroid\gki\ulinux\gki_ulinux.c

void Gki_init (void) {pthread_mutexattr_t attr;    Tgki_os *p_os;    memset (&AMP;GKI_CB, 0, sizeof (GKI_CB));    Gki_buffer_init (),//1), Gki buffer, buffer pool initialization, gki_timers_init (),//2), Gki timer initialization, gki_cb.com.OSTicks = (UINT32) times (0); Pthread_mutexattr_init (&attr),//3), initialize pthread_mutexattr_t structure; #ifndef __cygwin__ Pthread_mutexattr_settype (    &attr, PTHREAD_MUTEX_RECURSIVE_NP),//4), set Mutex type #endif P_os = &gki_cb.os; Pthread_mutex_init (&p_os->gki_mutex, &attr),//5), initialize mutex Gki_mutex;/* Pthread_mutex_init (&GKI_ Sched_mutex, NULL); */#if (Gki_debug = = TRUE) pthread_mutex_init (&p_os->gki_trace_mutex, NULL),//6), Initialize mutex gki_trace_mutex;# endif/* Pthread_mutex_init (&thread_delay_mutex, NULL); */* Used in Gki_delay *//* Pthread_cond_init (&thread_delay_cond, NULL);     */* initialiase gki_timer_update Suspend variables & mutexes to is in running state. * This works too even if gki_no_tick_stop are defined in Btld.txt */p_os->no_timer_suspend = Gki_timer_tick_run_cond;    Pthread_mutex_init (&p_os->gki_timer_mutex, NULL), 7), initializing mutex Gki_timer_mutex; #ifndef No_gki_run_return Pthread_cond_init (&p_os->gki_timer_cond, NULL); #endif}

2), initialize the structure of static bt_hc_interface_t *bt_hc_if=null;
Bte_main_in_hw_init ();
Assigning Values to bt_hc_if:

static const bt_hc_interface_t Bluetoothhclibinterface = {    sizeof (bt_hc_interface_t),    INIT,//HCI The implementation of the Init function in Lib;    Set_power,    LPM,    preload,    postload,    transmit_buf,    Set_rxflow,    Logging,    cleanup};

3), initialize the Bluedroid debug information level
Bte_load_conf (Bte_stack_conf_file);
Resolves configuration information in the bt_stack.conf file.
(2), create a Bluetooth task interface, ready to do scheduling creates BTIF task and prepares BT scheduler for startup

  Status = Gki_create_task (Btif_task, Btif_task, Btif_task_str,                (UINT16 *) ((UINT8 *) Btif_task_stack + btif_task_ stack_size),                sizeof (btif_task_stack));

6. Btif_task Process Related processing function
External\bluetooth\bluedroid\btif\src\btif_dm.c
Btif_task waits for the corresponding state to be sent by the receiving bta_sys_sendmsg to do the corresponding processing.

static void Btif_task (UINT32 params) {...    .... ..... for (;;) {/        * wait for specified events */        event = gki_wait (0xFFFF, 0);//gki interprocess communication is followed by a single section,        if (event = = Bt_evt_trigger _stack_init)//protocol stack initialization is complete;        .. if (event = = Bt_evt_hardware_init_fail)//Hardware initialization error        .... if (Event & Event_mask (GKI_SHUTDOWN_EVT))//receive the closing information;        if (event & Task_mbox_1_evt_mask) ......}}

Android bluedroid (ii): bluedroid Bluetooth Open Process init

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.