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 the copyright. Thank you. )
Welcome to correct mistakes, common learning, common progress!!

first, the Bluetooth open process overview, for example, as seen in: init, enable

Same as the normal function call. Android upper layer via 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. On-chip power, RF parameter 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 seen in the following example.


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 detailed implementation of the Initnative function. By bt_interface_t the struct, call the init function in C to implement. At the same time, pass in the sbluetoothcallbacks callback function structure body. 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);//call to C corresponding interface function        if (ret! = bt_status_success) {//Assume error, 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
The C language implements the function called by the upper layer. Finally, the operation of Java calling C function is realized.

This is the detailed steps of the Android system for the kernel operation.

The assumption is that people who have just started to learn, suggest that this part of the content to be clear, the entire Android system to the bottom of the operation is achieved through 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, save. This is very important, just beginning 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 ();//toolset initialization, initializing a mutually exclusive lock.    /* init btif */btif_init_bluetooth ();//Initialize Bluetooth interface bluetoothinterface    return bt_status_success;}

5, Bluetooth interface initialization detailed implementation, Btif_init_bluetooth create Btif task. Prepare Bluetooth to turn on the relevant scheduler.
The detailed implementation process is seen in the following example. We'll explain the code below. The main finished:
(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. Implement power\preload\ and other 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. Initializes the related data in the/data/misc/bluedroid/bt_config.xml initialization.    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_addr, 0, sizeof (bt_bdaddr_t));//Take the Bluetooth address to write the relevant file.    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. Called only once when the initialization is initialized.    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)//related information print initialization. /    * Initialize trace feature *    / Bttrc_traceinit (Max_trace_ram_size, &bte_tracelogbuf[0], bttrc_method_ram); #endif}


1), Gki initialization. Called only once when the initialization is initialized
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 mutually exclusive lock type #endif P_os = &gki_cb.os; Pthread_mutex_init (&p_os->gki_mutex, &attr),//5), initialization of mutually exclusive amounts Gki_mutex;/* Pthread_mutex_init (&GKI_ Sched_mutex, NULL); */#if (Gki_debug = = TRUE) pthread_mutex_init (&p_os->gki_trace_mutex, NULL),//6), initialization of mutual repulsion 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 is DefiNed in Btld.txt */p_os->no_timer_suspend = Gki_timer_tick_run_cond; Pthread_mutex_init (&p_os->gki_timer_mutex, NULL), 7), initialize the Gki_timer_mutex of mutually exclusive amounts. #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);
Parse the configuration information in the bt_stack.conf file.
(2), create a Bluetooth task interface. Prepare creates BTIF task and prepares BT scheduler for startup to enable scheduling

  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 complete, ...        .. if (event = = Bt_evt_hardware_init_fail)//Hardware initialization error        .... if (Event & Event_mask (GKI_SHUTDOWN_EVT))//Receive shutdown 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.