Android4.4 之Bluetooth整理

2020年07月26日 阅读数:127
这篇文章主要向大家介绍Android4.4 之Bluetooth整理,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

http://it165.net/pro/html/201405/14307.htmlhtml

 Android Bluetoothjava

Android 4.4上蓝牙协议栈采用的是BRCM和Google共同开发的bluedroid,代替了以前的Bluez.linux

1、 Bluetooth 源码分布 (基于Android 4.4 )android

1.  packages/apps/Settings/src/com/android/settings/bluetoothios

     bluetooth Settings 代码shell

2.  packages/apps/Bluetooth网络

     BT 应用层代码,及BT profile(如:A2dp,gatt,hdp,hfp,hid,map,opp,pan,pbap ...) 上层代码app

     packages/apps/Bluetooth/jniless

3.  frameworks/base/core/java/android/bluetoothasync

     framework 层相关 java 代码与aidl

4.  external/bluetooth/bluedroid      

     BRCM和Google共同开发的官方蓝牙协议栈

5.  linux/kernel/drivers/bluetooth

6.  linux/kernel/net/bluetooth

7. 如下是近期项目intel 平台

hardware/broadcom/libbt

hardware/libhardware

vendor/intel/fw/PRIVATE/bt    厂商bt固件

 2、Bluetooth 经常使用类及相关profile

A2dp: Advanced Audio Distribution Profile 蓝牙音频传输模型协定

 蓝牙立体声,和蓝牙耳机听歌有关那些,另还有个AVRCP--(Audio/Video Remote Control Profile)音频/视频远程控制配置文件,是用来听歌时暂停,上下歌曲选择的

GATT: Generic Attribute Profile   通用属性配置文件

       GATT是基于ATT Protocol的,ATT针对BLE设备作了专门的优化,具体就是在传输过程当中使用尽可能少的数据。每一个属性都有一个惟一的UUID,属性将以characteristics and services的形式传输

       https://developer.bluetooth.org/TechnologyOverview/Pages/GATT.aspx

HDP:Bluetooth Health Device Profile 蓝牙关于医疗方面的应用 

HFP : Hands-free Profile  和电话相关,蓝牙接听、挂断电话 

HID : Human Interface Device  

         定义了蓝牙在人机接口设备中的协议、特征和使用规程。典型的应用包括蓝牙鼠标、蓝牙键盘、蓝牙游戏手柄等。该协议改编自USB HID Protocol

MAP : Message Access Profile

OPP : Object Push Profile

PAN : Personal Area Network Profile

描述了两个或更多个 Bluetooth 设备如何构成一个即时网络,和网络有关的还有串行端口功能(SPP),拨号网络功能(DUN)

PBAP: Phonebook Access Profile 电话号码簿访问协议

3、Enable Bluetooth

1. 服务启动:

frameworks/base/services/java/com/android/server/SystemServer.java

系统启动时在SystemServer中注册蓝牙服务管理BluetoothManagerService服务: 


加载中...
01. 1             // Skip Bluetooth if we have an emulator kernel
02. 2             // TODO: Use a more reliable check to see if this product should
03. 3             // support Bluetooth - see bug 988521
04. 4             if (SystemProperties.get('ro.kernel.qemu').equals('1')) {
05. 5                 Slog.i(TAG, 'No Bluetooh Service (emulator)');
06. 6             else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
07. 7                 Slog.i(TAG, 'No Bluetooth Service (factory test)');
08. 8             else if (!context.getPackageManager().hasSystemFeature
09. 9                        (PackageManager.FEATURE_BLUETOOTH)) {
10. 10                 Slog.i(TAG, 'No Bluetooth Service (Bluetooth Hardware Not Present)');
11. 11             else if (disableBluetooth) {
12. 12                 Slog.i(TAG, 'Bluetooth Service disabled by config');
13. 13             else {
14. 14                 Slog.i(TAG, 'Bluetooth Manager Service');
15. 15                 bluetooth = new BluetoothManagerService(context);
16. 16                 ServiceManager.addService(BluetoothAdapter.BLUETOOTH_MANAGER_SERVICE, bluetooth);
17. 17             }
Bt 服务

 其它进程经过binder机制调用该服务,该服务属于综合服务管理类,包括AdapterService的启动、蓝牙适配器Adapter的管理等。

 2.  BluetoothAdapter 

Android的蓝牙Enable是由BluetoothAdapter提供的。只须要调用BluetoothAdapter.enable()便可启动蓝牙。下面我就分析这一个过程

 frameworks/base/core/java/android/bluetooth/BluetoothAdapter.java


加载中...
01. 1     /**
02. 2      * Turn on the local Bluetooth adapter—do not use without explicit
03. 3      * user action to turn on Bluetooth.
04. 4      * <p>This powers on the underlying Bluetooth hardware, and starts all
05. 5      * Bluetooth system services.
06. 6      * <p class='caution'><strong>Bluetooth should never be enabled without
07. 7      * direct user consent</strong>. If you want to turn on Bluetooth in order
08. 8      * to create a wireless connection, you should use the {@link
09. 9      * #ACTION_REQUEST_ENABLE} Intent, which will raise a dialog that requests
10. 10      * user permission to turn on Bluetooth. The {@link #enable()} method is
11. 11      * provided only for applications that include a user interface for changing
12. 12      * system settings, such as a 'power manager' app.</p>
13. 13      * <p>This is an asynchronous call: it will return immediately, and
14. 14      * clients should listen for {@link #ACTION_STATE_CHANGED}
15. 15      * to be notified of subsequent adapter state changes. If this call returns
16. 16      * true, then the adapter state will immediately transition from {@link
17. 17      * #STATE_OFF} to {@link #STATE_TURNING_ON}, and some time
18. 18      * later transition to either {@link #STATE_OFF} or {@link
19. 19      * #STATE_ON}. If this call returns false then there was an
20. 20      * immediate problem that will prevent the adapter from being turned on -
21. 21      * such as Airplane mode, or the adapter is already turned on.
22. 22      * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
23. 23      * permission
24. 24      *
25. 25      * @return true to indicate adapter startup has begun, or false on
26. 26      *         immediate error
27. 27      */
28. 28     public boolean enable() {
29. 29         if (isEnabled() == true){
30. 30             if (DBG) Log.d(TAG, 'enable(): BT is already enabled..!');
31. 31             return true;
32. 32         }
33. 33         try {
34. 34             return mManagerService.enable(); //
35. 35         catch (RemoteException e) {Log.e(TAG, '', e);}
36. 36         return false;
37. 37     }
mManagerService.enable()

mManagerService其实就是bluetoothAdapter的一个proxy, 


加载中...
01. 1     /**
02. 2      * Get a handle to the default local Bluetooth adapter.
03. 3      * <p>Currently Android only supports one Bluetooth adapter, but the API
04. 4      * could be extended to support more. This will always return the default
05. 5      * adapter.
06. 6      * @return the default local adapter, or null if Bluetooth is not supported
07. 7      *         on this hardware platform
08. 8      */
09. 9     public static synchronized BluetoothAdapter getDefaultAdapter() {
10. 10         if (sAdapter == null) {
11. 11             IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE);
12. 12             if (b != null) {
13. 13                 IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b);
14. 14                 sAdapter = new BluetoothAdapter(managerService);
15. 15             else {
16. 16                 Log.e(TAG, 'Bluetooth binder is null');
17. 17             }
18. 18         }
19. 19         return sAdapter;
20. 20     }
getDefaultAdapter  加载中...
01. 1     /**
02. 2      * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance.
03. 3      */
04. 4     BluetoothAdapter(IBluetoothManager managerService) {
05. 5
06. 6         if (managerService == null) {
07. 7             throw new IllegalArgumentException('bluetooth manager service is null');
08. 8         }
09. 9         try {
10. 10             mService = managerService.registerAdapter(mManagerCallback);
11. 11         catch (RemoteException e) {Log.e(TAG, '', e);}
12. 12         mManagerService = managerService;
13. 13         mLeScanClients = new HashMap<LeScanCallback, GattCallbackWrapper>();
14. 14     }
BluetoothAdapter

 3. BluetoothManagerService

frameworks/base/services/java/com/android/server/BluetoothManagerService.java


加载中...
01. 1     public boolean enable() {
02. 2         if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
03. 3             (!checkIfCallerIsForegroundUser())) {
04. 4             Log.w(TAG,'enable(): not allowed for non-active and non system user');
05. 5             return false;
06. 6         }
07. 7
08. 8         mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
09. 9                                                 'Need BLUETOOTH ADMIN permission');
10. 10         if (DBG) {
11. 11             Log.d(TAG,'enable():  mBluetooth =' + mBluetooth +
12. 12                     ' mBinding = ' + mBinding);
13. 13         }
14. 14
15. 15         synchronized(mReceiver) {
16. 16             mQuietEnableExternal = false;
17. 17             mEnableExternal = true;
18. 18             // waive WRITE_SECURE_SETTINGS permission check
19. 19             long callingIdentity = Binder.clearCallingIdentity();
20. 20             persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
21. 21             Binder.restoreCallingIdentity(callingIdentity);
22. 22             sendEnableMsg(false);
23. 23         }
24. 24         return true;
25. 25     }
BluetoothManagerService:enable()  加载中...
1. 1     private void sendEnableMsg(boolean quietMode) {
2. 2         mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
3. 3                              quietMode ? 1 00));
4. 4     }
sendEnableMsg

sendEnableMsg 交给handleMessage 处理,能够看到case MESSAGE_ENABLE: 里调用了handleEnable


加载中...
01. 1     private void handleEnable(boolean quietMode) {
02. 2         mQuietEnable = quietMode;
03. 3
04. 4         synchronized(mConnection) {
05. 5             if ((mBluetooth == null) && (!mBinding)) {
06. 6                 //Start bind timeout and bind
07. 7                 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
08. 8                 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
09. 9                 mConnection.setGetNameAddressOnly(false);
10. 10                 Intent i = new Intent(IBluetooth.class.getName());
11. 11                 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE, UserHandle.CURRENT)) {
12. 12                     mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
13. 13                 else {
14. 14                     mBinding = true;
15. 15                 }
16. 16             else if (mBluetooth != null) {
17. 17                 if (mConnection.isGetNameAddressOnly()) {
18. 18                     // if GetNameAddressOnly is set, we can clear this flag,
19. 19                     // so the service won't be unbind
20. 20                     // after name and address are saved
21. 21                     mConnection.setGetNameAddressOnly(false);
22. 22                     //Register callback object
23. 23                     try {
24. 24                         mBluetooth.registerCallback(mBluetoothCallback);
25. 25                     catch (RemoteException re) {
26. 26                         Log.e(TAG, 'Unable to register BluetoothCallback',re);
27. 27                     }
28. 28                     //Inform BluetoothAdapter instances that service is up
29. 29                     sendBluetoothServiceUpCallback();
30. 30                 }
31. 31
32. 32                 //Enable bluetooth
33. 33                 try {
34. 34                     if (!mQuietEnable) {
35. 35                         if(!mBluetooth.enable()) {
36. 36                             Log.e(TAG,'IBluetooth.enable() returned false');
37. 37                         }
38. 38                     }
39. 39                     else {
40. 40                         if(!mBluetooth.enableNoAutoConnect()) {
41. 41                             Log.e(TAG,'IBluetooth.enableNoAutoConnect() returned false');
42. 42                         }
43. 43                     }
44. 44                 catch (RemoteException e) {
45. 45                     Log.e(TAG,'Unable to call enable()',e);
46. 46                 }
47. 47             }
48. 48
49. 49             // Inform AudioRouteManager that bluetooth is enabled
50. 50             mAudioManager.setParameters(AUDIO_PARAMETER_KEY_BLUETOOTH_STATE + '=true');
51. 51         }
52. 52     }
handleEnable

能够看到是调用了mBluetooth.enable()

 4. AdapterService,AdapterState

packages/app/Bluetooth/src/com/android/bluetooth/btservice/AdapterService.java


加载中...
01. 1      public synchronized boolean enable(boolean quietMode) {
02. 2          enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
03. 3                                         'Need BLUETOOTH ADMIN permission');
04. 4          if (DBG)debugLog('Enable called with quiet mode status =  ' + mQuietmode);
05. 5          mQuietmode  = quietMode;
06. 6          Message m =
07. 7                  mAdapterStateMachine.obtainMessage(AdapterState.USER_TURN_ON);
08. 8          mAdapterStateMachine.sendMessage(m);
09. 9          return true;
10. 10      }
AdapterService:enable()

此处用了用了StateMachine,它会在AdapterState 里processMessage 处理(StateMachine就是状态机,在不一样的状态下,收到相同的Event,作不一样的事情),直接搜索UER_TURN_ON 能够看到下面:


加载中...
01. 1     private class OffState extends State {
02. 2         @Override
03. 3         public void enter() {
04. 4             infoLog('Entering OffState');
05. 5         }
06. 6
07. 7         @Override
08. 8         public boolean processMessage(Message msg) {
09. 9             AdapterService adapterService = mAdapterService;
10. 10             if (adapterService == null) {
11. 11                 Log.e(TAG,'receive message at OffState after cleanup:' +
12. 12                           msg.what);
13. 13                 return false;
14. 14             }
15. 15             switch(msg.what) {
16. 16                case USER_TURN_ON:
17. 17                    if (DBG) Log.d(TAG,'CURRENT_STATE=OFF, MESSAGE = USER_TURN_ON');
18. 18                    sendCrashToolInfo('ON');
19. 19                    notifyAdapterStateChange(BluetoothAdapter.STATE_TURNING_ON);
20. 20                    mPendingCommandState.setTurningOn(true);
21. 21                    transitionTo(mPendingCommandState);
22. 22                    sendMessageDelayed(START_TIMEOUT, START_TIMEOUT_DELAY);
23. 23                    adapterService.processStart();
24. 24                    break;
25. 25                case USER_TURN_OFF:
26. 26                    if (DBG) Log.d(TAG,'CURRENT_STATE=OFF, MESSAGE = USER_TURN_OFF');
27. 27                    sendCrashToolInfo('OFF');
28. 28                    //TODO: Handle case of service started and stopped without enable
29. 29                    break;
30. 30                default:
31. 31                    if (DBG) Log.d(TAG,'ERROR: UNEXPECTED MESSAGE: CURRENT_STATE=OFF, MESSAGE = ' + msg.what );
32. 32                    return false;
33. 33             }
34. 34             return true;
35. 35         }
36. 36     }
USER_TURN_ON

接下来是调用了adapterService.processStart()


加载中...
01. 1     void processStart() {
02. 2         if (DBG) debugLog('processStart()');
03. 3         Class[] supportedProfileServices = Config.getSupportedProfiles();
04. 4         //Initialize data objects
05. 5         for (int i=0; i < supportedProfileServices.length;i++) {
06. 6             mProfileServicesState.put(supportedProfileServices[i].getName(),BluetoothAdapter.STATE_OFF);
07. 7         }
08. 8         mRemoteDevices = new RemoteDevices(this);
09. 9         mAdapterProperties.init(mRemoteDevices);
10. 10
11. 11         if(mBondStateMachine != null//Avoid resource leakage
12. 12         {
13. 13             mBondStateMachine.doQuit();
14. 14             mBondStateMachine.cleanup();
15. 15         }
16. 16
17. 17         if (DBG) {debugLog('processStart(): Make Bond State Machine');}
18. 18         mBondStateMachine = BondStateMachine.make(this, mAdapterProperties, mRemoteDevices);
19. 19
20. 20         mJniCallbacks.init(mBondStateMachine,mRemoteDevices);
21. 21
22. 22         //FIXME: Set static instance here???
23. 23         setAdapterService(this);
24. 24
25. 25         //Start profile services
26. 26         if (!mProfilesStarted && supportedProfileServices.length >0) {
27. 27             //Startup all profile services
28. 28             setProfileServiceState(supportedProfileServices,BluetoothAdapter.STATE_ON);
29. 29         }else {
30. 30             if (DBG) {debugLog('processStart(): Profile Services alreay started');}
31. 31             mAdapterStateMachine.sendMessage(mAdapterStateMachine.obtainMessage(AdapterState.STARTED));
32. 32         }
33. 33     }
processStart

setProfileServiceState(supportedProfileServices,BluetoothAdapter.STATE_ON); 是用来开启Bluetooth Profile 的,log 中能够看到:        


加载中...
01. 1         BluetoothAdapterService( 1789): Starting service com.android.bluetooth.hfp.HeadsetService
02. 2         BluetoothAdapterService( 1789): Starting service com.android.bluetooth.a2dp.A2dpService
03. 3         BluetoothAdapterService( 1789): Starting service com.android.bluetooth.hid.HidService
04. 4         BluetoothAdapterService( 1789): Starting service com.android.bluetooth.hdp.HealthService
05. 5         BluetoothAdapterService( 1789): Starting service com.android.bluetooth.pan.PanService
06. 6         BluetoothAdapterService( 1789): Starting service com.android.bluetooth.gatt.GattService
07. 7         BluetoothAdapterService( 1789): Starting service com.android.bluetooth.map.BluetoothMapService
08. 8     bluedroid( 1789): get_profile_interface handsfree
09. 9     bluedroid( 1789): get_profile_interface a2dp
10. 10     bluedroid( 1789): get_profile_interface avrcp
11. 11     bluedroid( 1789): get_profile_interface hidhost
12. 12     bluedroid( 1789): get_profile_interface health
13. 13     bluedroid( 1789): get_profile_interface pan
14. 14     bluedroid( 1789): get_profile_interface gatt?
BT Profile log

而后能够看到:mAdapterStateMachine.sendMessage(mAdapterStateMachine.obtainMessage(AdapterState.STARTED)); 

交给了PendingCommandState下的processMessage处理  加载中... 加载中...
01. 1                 case STARTED:   {
02. 2                     if (DBG) Log.d(TAG,'CURRENT_STATE=PENDING, MESSAGE = STARTED, isTurningOn=' + isTurningOn + ', isTurningOff=' + isTurningOff);
03. 3                     //Remove start timeout
04. 4                     removeMessages(START_TIMEOUT);
05. 5
06. 6                     //Enable
07. 7                     boolean ret = adapterService.enableNative();
08. 8                     if (!ret) {
09. 9                         errorLog('Error while turning Bluetooth On');
10. 10                         notifyAdapterStateChange(BluetoothAdapter.STATE_OFF);
11. 11                         transitionTo(mOffState);
12. 12                     else {
13. 13                         sendMessageDelayed(ENABLE_TIMEOUT, ENABLE_TIMEOUT_DELAY);
14. 14                     }
15. 15                 }
case STARTED

由mAdapterService.enableNative(); 能够看到 /*package*/ native boolean enableNative();

 此时就进入了JNI了

 5. JNI 调用

enableNative() 是在 packages/apps/Bluetooth/jni/com_android_bluetooth_btservice_AdapterService.cpp


加载中...
01. 1 static jboolean enableNative(JNIEnv* env, jobject obj) {
02. 2     ALOGV('%s:',__FUNCTION__);
03. 3
04. 4     jboolean result = JNI_FALSE;
05. 5     if (!sBluetoothInterface) return result;
06. 6
07. 7     int ret = sBluetoothInterface->enable();
08. 8     result = (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
09. 9     return result;
10. 10 }
enableNative static const bt_interface_t *sBluetoothInterface = NULL;  加载中...
001. 1 /** NOTE: By default, no profiles are initialized at the time of init/enable.
002. 2  *  Whenever the application invokes the 'init' API of a profile, then one of
003. 3  *  the following shall occur:
004. 4  *
005. 5  *    1.) If Bluetooth is not enabled, then the Bluetooth core shall mark the
006. 6  *        profile as enabled. Subsequently, when the application invokes the
007. 7  *        Bluetooth 'enable', as part of the enable sequence the profile that were
008. 8  *        marked shall be enabled by calling appropriate stack APIs. The
009. 9  *        'adapter_properties_cb' shall return the list of UUIDs of the
010. 10  *        enabled profiles.
011. 11  *
012. 12  *    2.) If Bluetooth is enabled, then the Bluetooth core shall invoke the stack
013. 13  *        profile API to initialize the profile and trigger a
014. 14  *        'adapter_properties_cb' with the current list of UUIDs including the
015. 15  *        newly added profile's UUID.
016. 16  *
017. 17  *   The reverse shall occur whenever the profile 'cleanup' APIs are invoked
018. 18  */
019. 19
020. 20 /** Represents the standard Bluetooth DM interface. */
021. 21 typedef struct {
022. 22     /** set to sizeof(bt_interface_t) */
023. 23     size_t size;
024. 24     /**
025. 25      * Opens the interface and provides the callback routines
026. 26      * to the implemenation of this interface.
027. 27      */
028. 28     int (*init)(bt_callbacks_t* callbacks );
029. 29
030. 30     /** Enable Bluetooth. */
031. 31     int (*enable)(void);
032. 32
033. 33     /** Disable Bluetooth. */
034. 34     int (*disable)(void);
035. 35
036. 36     /** This ensures the chip is Powered ON  to support other radios in the combo chip.
037. 37      * If the chip is OFF it set the chip to ON, if it is already ON it just increases the radio ref count
038. 38      * to keep track when to Power OFF */
039. 39     int (*enableRadio)(void);
040. 40
041. 41     /** This decreases radio ref count  and ensures that chip is Powered OFF
042. 42      * when the radio ref count becomes zero. */
043. 43     int (*disableRadio)(void);
044. 44
045. 45     /** Closes the interface. */
046. 46     void (*cleanup)(void);
047. 47
048. 48     /** Get all Bluetooth Adapter properties at init */
049. 49     int (*get_adapter_properties)(void);
050. 50
051. 51     /** Get Bluetooth Adapter property of 'type' */
052. 52     int (*get_adapter_property)(bt_property_type_t type);
053. 53
054. 54     /** Set Bluetooth Adapter property of 'type' */
055. 55     /* Based on the type, val shall be one of
056. 56      * bt_bdaddr_t or bt_bdname_t or bt_scanmode_t etc
057. 57      */
058. 58     int (*set_adapter_property)(const bt_property_t *property);
059. 59
060. 60     /** Get all Remote Device properties */
061. 61     int (*get_remote_device_properties)(bt_bdaddr_t *remote_addr);
062. 62
063. 63     /** Get Remote Device property of 'type' */
064. 64     int (*get_remote_device_property)(bt_bdaddr_t *remote_addr,
065. 65                                       bt_property_type_t type);
066. 66
067. 67     /** Set Remote Device property of 'type' */
068. 68     int (*set_remote_device_property)(bt_bdaddr_t *remote_addr,
069. 69                                       const bt_property_t *property);
070. 70
071. 71     /** Get Remote Device's service record  for the given UUID */
072. 72     int (*get_remote_service_record)(bt_bdaddr_t *remote_addr,
073. 73                                      bt_uuid_t *uuid);
074. 74
075. 75     /** Start SDP to get remote services */
076. 76     int (*get_remote_services)(bt_bdaddr_t *remote_addr);
077. 77
078. 78     /** Start Discovery */
079. 79     int (*start_discovery)(void);
080. 80
081. 81     /** Cancel Discovery */
082. 82     int (*cancel_discovery)(void);
083. 83
084. 84     /** Create Bluetooth Bonding */
085. 85     int (*create_bond)(const bt_bdaddr_t *bd_addr);
086. 86
087. 87     /** Remove Bond */
088. 88     int (*remove_bond)(const bt_bdaddr_t *bd_addr);
089. 89
090. 90     /** Cancel Bond */
091. 91     int (*cancel_bond)(const bt_bdaddr_t *bd_addr);
092. 92
093. 93     /** BT Legacy PinKey Reply */
094. 94     /** If accept==FALSE, then pin_len and pin_code shall be 0x0 */
095. 95     int (*pin_reply)(const bt_bdaddr_t *bd_addr, uint8_t accept,
096. 96                      uint8_t pin_len, bt_pin_code_t *pin_code);
097. 97
098. 98     /** BT SSP Reply - Just Works, Numeric Comparison and Passkey
099. 99      * passkey shall be zero for BT_SSP_VARIANT_PASSKEY_COMPARISON &
100. 100      * BT_SSP_VARIANT_CONSENT
101. 101      * For BT_SSP_VARIANT_PASSKEY_ENTRY, if accept==FALSE, then passkey
102. 102      * shall be zero */
103. 103     int (*ssp_reply)(const bt_bdaddr_t *bd_addr, bt_ssp_variant_t variant,
104. 104                      uint8_t accept, uint32_t passkey);
105. 105
106. 106     /** Get Bluetooth profile interface */
107. 107     const void* (*get_profile_interface) (const char *profile_id);
108. 108
109. 109     /** Bluetooth Test Mode APIs - Bluetooth must be enabled for these APIs */
110. 110     /* Configure DUT Mode - Use this mode to enter/exit DUT mode */
111. 111     int (*dut_mode_configure)(uint8_t enable);
112. 112
113. 113     /* Send any test HCI (vendor-specific) command to the controller. Must be in DUT Mode */
114. 114     int (*dut_mode_send)(uint16_t opcode, uint8_t *buf, uint8_t len);
115. 115     /** BLE Test Mode APIs */
116. 116     /* opcode MUST be one of: LE_Receiver_Test, LE_Transmitter_Test, LE_Test_End */
117. 117     int (*le_test_mode)(uint16_t opcode, uint8_t *buf, uint8_t len);
118. 118
119. 119     /* enable or disable bluetooth HCI snoop log */
120. 120     int (*config_hci_snoop_log)(uint8_t enable);
121. 121
122. 122     /** Get FM module interface */
123. 123     const void* (*get_fm_interface) ();
124. 124 } bt_interface_t;
bt_interface_t 定义

 bt_interface_t 定义 在hardware/libhardware/include/hardware/bluetooth.h

sBluetoothInterface的初始化在classInitNative(),这个函数大概作了如下的事情: 1)、注册java的回调函数(就是当下层已经打开蓝牙了,而后要通知上层,蓝牙已经打开了,java层就能够发送蓝牙打开的Broadcast了。) 2)、初始化蓝牙模块的HAL接口。 3)、获得sBluetoothInterface  

6. Bluedroid ->bluetooth.c

external/bluetooth/bluedroid/btif/src/bluetooth.c

sBluetoothInterface->enable(); 会调到下方


加载中...
01. 1 static int enable( void )
02. 2 {
03. 3     ALOGI('enable');
04. 4
05. 5     /* sanity check */
06. 6     if (interface_ready() == FALSE)
07. 7         return BT_STATUS_NOT_READY;
08. 8
09. 9     return btif_enable_bluetooth();
10. 10 }
bluetooth:enable()

接下来调用:external/bluetooth/bluedroid/btif/src/Btif_core.c


加载中...
01. 1 /*******************************************************************************
02. 2 **
03. 3 ** Function         btif_enable_bluetooth
04. 4 **
05. 5 ** Description      Performs chip power on and kickstarts OS scheduler
06. 6 **
07. 7 ** Returns          bt_status_t
08. 8 **
09. 9 *******************************************************************************/
10. 10
11. 11 bt_status_t btif_enable_bluetooth(void)
12. 12 {
13. 13     BTIF_TRACE_DEBUG0('BTIF ENABLE BLUETOOTH');
14. 14
15. 15     if (0 == btif_core_radio_ref_count){
16. 16
17. 17         if (btif_core_state != BTIF_CORE_STATE_DISABLED)
18. 18         {
19. 19             ALOGD('not disabled
20. ');
21. 20             return BT_STATUS_DONE;
22. 21         }
23. 22
24. 23         btif_core_state = BTIF_CORE_STATE_ENABLING;
25. 24
26. 25         /* Create the GKI tasks and run them */
27. 26         bte_main_enable();
28. 27         btif_core_radio_ref_count++;
29. 28     }
30. 29     else
31. 30     {
32. 31         btif_core_radio_ref_count++;
33. 32         /*btif core/chip is already enabled so just do other initialisation according to event*/
34. 33         btif_transfer_context(btif_in_generic_evt, BTIF_CORE_BT_STATE_ON, NULL, 0, NULL);
35. 34     }
36. 35
37. 36     return BT_STATUS_SUCCESS;
38. 37 }
btif_enable_bluetooth

 external/bluetooth/bluedroid/main/Bte_main.c


加载中...
01. 1 /******************************************************************************
02. 2 **
03. 3 ** Function         bte_main_enable
04. 4 **
05. 5 ** Description      BTE MAIN API - Creates all the BTE tasks. Should be called
06. 6 **                  part of the Bluetooth stack enable sequence
07. 7 **
08. 8 ** Returns          None
09. 9 **
10. 10 ******************************************************************************/
11. 11 void bte_main_enable()
12. 12 {
13. 13     APPL_TRACE_DEBUG1('%s', __FUNCTION__);
14. 14
15. 15     /* Initialize BTE control block */
16. 16     BTE_Init();
17. 17
18. 18     lpm_enabled = FALSE;
19. 19
20. 20     bte_hci_enable();
21. 21
22. 22     GKI_create_task((TASKPTR)btu_task, BTU_TASK, BTE_BTU_TASK_STR,
23. 23                     (UINT16 *) ((UINT8 *)bte_btu_stack + BTE_BTU_STACK_SIZE),
24. 24                     sizeof(bte_btu_stack));
25. 25
26. 26     GKI_run(0);
27. 27 }
bte_main_enable  加载中...
01. 1 /******************************************************************************
02. 2 **
03. 3 ** Function         bte_hci_enable
04. 4 **
05. 5 ** Description      Enable HCI & Vendor modules
06. 6 **
07. 7 ** Returns          None
08. 8 **
09. 9 ******************************************************************************/
10. 10 static void bte_hci_enable(void)
11. 11 {
12. 12     APPL_TRACE_DEBUG1('%s', __FUNCTION__);
13. 13
14. 14     preload_start_wait_timer();
15. 15
16. 16     if (bt_hc_if)
17. 17     {
18. 18         int result = bt_hc_if->init(&hc_callbacks, btif_local_bd_addr.address);
19. 19         APPL_TRACE_EVENT1('libbt-hci init returns %d', result);
20. 20
21. 21         assert(result == BT_HC_STATUS_SUCCESS);
22. 22
23. 23         if (hci_logging_enabled == TRUE || hci_logging_config == TRUE)
24. 24             bt_hc_if->logging(BT_HC_LOGGING_ON, hci_logfile);
25. 25
26. 26 #if (defined (BT_CLEAN_TURN_ON_DISABLED) && BT_CLEAN_TURN_ON_DISABLED == TRUE)
27. 27         APPL_TRACE_DEBUG1('%s  Not Turninig Off the BT before Turninig ON', __FUNCTION__);
28. 28
29. 29         /* Do not power off the chip before powering on  if BT_CLEAN_TURN_ON_DISABLED flag
30. 30          is defined and set to TRUE to avoid below mentioned issue.
31. 31
32. 32          Wingray kernel driver maintains a combined  counter to keep track of
33.