Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

Android BLE 总结-源码篇(深入理解startAdvertising的注册过程)

$
0
0

在上一篇的BluetoothLeAdvertiser的分析中讲到,startAdvertising的内部具体实现都是IBluetoothGatt的引用来去实现的,这篇文章我们一起来往深的一层去分析。这篇博文我们会弄清楚上文中以下几点:

1.IBluetoothGatt的引用的到底是什么?

2. mClientIf是如何生成的以及作用?

先来看第一个问题——IBluetoothGatt的引用是什么?

这里可以先告诉大家上文中的IBluetoothGatt的引用的是com.android.bluetooth.gatt.GattService的实例。下面带大家看一下如何得出这个结论:
还记得上文中的以下代码吗?
   IBluetoothGatt gatt;           
    try {                
        gatt = mBluetoothManager.getBluetoothGatt();            
    } catch (RemoteException e) {  
         Log.e(TAG, "Failed to get Bluetooth gatt - ", e);                
         postStartFailure(callback, AdvertiseCallback.ADVERTISE_FAILED_INTERNAL_ERROR);                
         return;            
    }          
    AdvertiseCallbackWrapper wrapper = new AdvertiseCallbackWrapper(callback, advertiseData,scanResponse, settings, gatt);            
    wrapper.startRegisteration();

gatt的引用是通过mBluetoothManager.getBluetoothGatt()方法得到的,那么mBluetoothManager(这里可以先告诉大家mBluetoothManager是frameworks/base/services/core/java/com/android/server/BluetoothManagerService.java)又是什么,又是怎么来的?继续看代码:

  1. /**
  2.     * Use BluetoothAdapter.getLeAdvertiser() instead.
  3.     *
  4.     * @param bluetoothManager BluetoothManager that conducts overall Bluetooth Management
  5.     * @hide
  6.     */
  7.    public BluetoothLeAdvertiser(IBluetoothManager bluetoothManager) {
  8.        mBluetoothManager = bluetoothManager;
  9.        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  10.        mHandler = new Handler(Looper.getMainLooper());
  11.    }

这个mBluetoothManager是通过参数传递过来的,但是这个构造函数是隐藏的,因为注解@hide。也就是这方法我们是不能在应用层直接调用的,事实上,我们在写代码时,获得BluetoothLeAdvertiser的实例也不是通过该构造函数,而是通过BluetoothAdapter.getBluetoothLeAdvertiser()。


  1.    /**
  2.     * Returns a {@link BluetoothLeAdvertiser} object for Bluetooth LE Advertising operations.
  3.     * Will return null if Bluetooth is turned off or if Bluetooth LE Advertising is not
  4.     * supported on this device.
  5.     * <p>
  6.     * Use {@link #isMultipleAdvertisementSupported()} to check whether LE Advertising is supported
  7.     * on this device before calling this method.
  8.     */
  9.    public BluetoothLeAdvertiser getBluetoothLeAdvertiser() {
  10.        if (getState() != STATE_ON) {
  11.            return null;
  12.        }
  13.        if (!isMultipleAdvertisementSupported() && !isPeripheralModeSupported()) {
  14.            Log.e(TAG, "bluetooth le advertising not supported");
  15.            return null;
  16.        }
  17.        synchronized(mLock) {
  18.            if (sBluetoothLeAdvertiser == null) {
  19.                sBluetoothLeAdvertiser = new BluetoothLeAdvertiser(mManagerService);
  20.            }
  21.        }
  22.        return sBluetoothLeAdvertiser;
  23.    }

在BluetoothAdapter.getBluetoothLeAdvertiser方法中调用了BluetoothLeAdvertiser的构造函数并且传入了参数mManagerService,这个mManagerService又是怎么得到的呢?


  1. /**BluetoothAdapter的代码
  2.     * Get a handle to the default local Bluetooth adapter.
  3.     * <p>Currently Android only supports one Bluetooth adapter, but the API
  4.     * could be extended to support more. This will always return the default
  5.     * adapter.
  6.     * @return the default local adapter, or null if Bluetooth is not supported
  7.     *         on this hardware platform
  8.     */
  9.    public static synchronized BluetoothAdapter getDefaultAdapter() {
  10.        if (sAdapter == null) {
  11.            IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE);
  12.            if (b != null) {
  13.                IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b);
  14.                sAdapter = new BluetoothAdapter(managerService);
  15.            } else {
  16.                Log.e(TAG, "Bluetooth binder is null");
  17.            }
  18.        }
  19.        return sAdapter;
  20.    }
  21.    /**
  22.     * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance.
  23.     */
  24.    BluetoothAdapter(IBluetoothManager managerService) {
  25.        if (managerService == null) {
  26.            throw new IllegalArgumentException("bluetooth manager service is null");
  27.        }
  28.        try {
  29.            mService = managerService.registerAdapter(mManagerCallback);
  30.        } catch (RemoteException e) {Log.e(TAG, "", e);}
  31.        mManagerService = managerService;
  32.        mLeScanClients = new HashMap<LeScanCallback, ScanCallback>();
  33.    }
  1.  /*

  2. *BluetoothManager的代码

  3.     * @hide
  4.     */
  5.    public BluetoothManager(Context context) {
  6.        context = context.getApplicationContext();
  7.        if (context == null) {
  8.            throw new IllegalArgumentException(
  9.                    "context not associated with any application (using a mock context?)");
  10.        }
  11.        // Legacy api - getDefaultAdapter does not take in the context
  12.        mAdapter = BluetoothAdapter.getDefaultAdapter();
  13.    }
  14.    /**
  15.     * Get the default BLUETOOTH Adapter for this device.
  16.     *
  17.     * @return the default BLUETOOTH Adapter
  18.     */
  19.    public BluetoothAdapter getAdapter() {
  20.        return mAdapter;
  21.    }

我们在应用开发中往往会像下面的代码一样去获取一个BluetoothAdapter的实例.

  1. mBluetoothManager=(BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);//这句代码其实是在ContextImpl里调用了 new BluetoothManager(ctx)。
  2. if(mBluetoothManager==null){
  3. return ;
  4. }
  5. mBluetoothAdapter=mBluetoothManager.getAdapter();
  6. if(mBluetoothAdapter==null){
  7. return ;
  8. }

下面看下mBluetoothManager引用的是什么

   //frameworks/base/core/java/android/app/ContextImpl.java    registerService(BLUETOOTH_SERVICE, new ServiceFetcher() {

  1. public Object createService(ContextImpl ctx) {

  2. return new BluetoothManager(ctx);
  3. }});


也就是说,BluetoothAdapter的实例获得最终还是通过其getDefaultAdapter方法去调用构造函数创建的。BluetoothAdapter的构造函数的函数是通过

 IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE);

来获得的。

  1. //frameworks/base/services/java/com/android/server/SystemServer.java // Skip Bluetooth if we have an emulator kernel

  2. // TODO: Use a more reliable check to see if this product should
  3. // support Bluetooth - see bug 988521
  4. if (isEmulator) {
  5. Slog.i(TAG, "No Bluetooh Service (emulator)");
  6. } else if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
  7. Slog.i(TAG, "No Bluetooth Service (factory test)");
  8. } else if (!context.getPackageManager().hasSystemFeature
  9. (PackageManager.FEATURE_BLUETOOTH)) {
  10. Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
  11. } else if (disableBluetooth) {
  12. Slog.i(TAG, "Bluetooth Service disabled by config");
  13. } else {
  14. Slog.i(TAG, "Bluetooth Manager Service");
  15.               bluetooth = new BluetoothManagerService(context);
  16. ServiceManager.addService(BluetoothAdapter.BLUETOOTH_MANAGER_SERVICE, bluetooth);
  17.           }

看到上面的代码,我们终于找到在BluetoothLeAdvertiser中的

 gatt = mBluetoothManager.getBluetoothGatt();            

mBluetoothManager引用的实例了,那就是BluetoothManagerService的实例。既然找到了mBluetoothManager的实现,那么gatt的引用我们就可以在BluetoothManagerService的实现中去寻找了。


  1. ///frameworks/base/services/core/java/com/android/server/BluetoothManagerService.java
  2.   public IBluetoothGatt getBluetoothGatt() {
  3.        // sync protection
  4.       return mBluetoothGatt;//成员变量
  5.   }
  6. .................................
  7. public void onServiceConnected(ComponentName className, IBinder service) {
  8.            if (DBG) Log.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
  9.            Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
  10.          // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
  11.            if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
  12.                msg.arg1 = SERVICE_IBLUETOOTH;
  13.                // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
  14.            } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
  15.                msg.arg1 = SERVICE_IBLUETOOTHGATT;
  16.            } else {
  17.                Log.e(TAG, "Unknown service connected: " + className.getClassName());
  18.                return;
  19.            }
  20.            msg.obj = service;
  21.            mHandler.sendMessage(msg);
  22.        }
  23. .................................
  24.     case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
  25.                {
  26.                    if (DBG) Log.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
  27.                    IBinder service = (IBinder) msg.obj;
  28.                    synchronized(mConnection) {
  29.                        if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
  30.                           mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);//BluetoothManagerService中只有这里对mBluetoothGatt进行了赋值操作,也就是之前我们一直念叨的gatt引用,结合上面的onServiceConnected的代码,可知引用的是GattService的对象
  31.                            break;
  32.                        } // else must be SERVICE_IBLUETOOTH
  33.                        //Remove timeout
  34.                        mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
  35.                        mBinding = false;
  36.                       mBluetooth = IBluetooth.Stub.asInterface(service);
  37.                        try {
  38.                            boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
  39.                                Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
  40.                            if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
  41.                                Log.e(TAG,"IBluetooth.configHciSnoopLog return false");
  42.                            }
  43.                        } catch (RemoteException e) {
  44.                            Log.e(TAG,"Unable to call configHciSnoopLog", e);
  45.                        }
  46.                       if (mConnection.isGetNameAddressOnly()) {
  47.                            //Request GET NAME AND ADDRESS
  48.                            Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
  49.                            mHandler.sendMessage(getMsg);
  50.                            if (!mEnable) return;
  51.                        }
  52.                        mConnection.setGetNameAddressOnly(false);
  53.                        //Register callback object
  54.                        try {
  55.                            mBluetooth.registerCallback(mBluetoothCallback);
  56.                        } catch (RemoteException re) {
  57.                            Log.e(TAG, "Unable to register BluetoothCallback",re);
  58.                        }
  59.                        //Inform BluetoothAdapter instances that service is up
  60.                        sendBluetoothServiceUpCallback();
  61.                       //Do enable request
  62.                       try {
  63.                           if (mQuietEnable == false) {
  64.                               if(!mBluetooth.enable()) {
  65.                                   Log.e(TAG,"IBluetooth.enable() returned false");
  66.                              }
  67.                            }
  68.                           else
  69.                            {
  70.                                if(!mBluetooth.enableNoAutoConnect()) {
  71.                                    Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
  72.                               }
  73.                            }
  74.                        } catch (RemoteException e) {
  75.                            Log.e(TAG,"Unable to call enable()",e);
  76.                        }
  77.                    }
  78.                    if (!mEnable) {
  79.                        waitForOnOff(true, false);
  80.                        handleDisable();
  81.                        waitForOnOff(false, false);
  82.                    }
  83.                   break;
  84.               }

  85. .................................

说了这么多终于知道了

IBluetoothGatt的引用的是com.android.bluetooth.gatt.GattService的实例

也就是说,上篇文章中的发送和停止广播的行为的具体实现应该是在这个文件里。这里先不对其进行展开。


下面我们来看第二个问题:mClientIf是如何生成的以及作用?

既然上面的分析已经知道,最终的实现在GattService这个类里面,我直接来看一下,GattService的registerClient的方法

  1. //http://androidxref.com/5.1.1_r6/xref/packages/apps/Bluetooth/src/com/android/bluetooth/gatt/GattService.java
  2. void registerClient(UUID uuid, IBluetoothGattCallback callback) {                

  3. enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");

  4.        if (DBG) Log.d(TAG, "registerClient() - UUID=" + uuid);
  5.        mClientMap.add(uuid, callback);
  6.        gattClientRegisterAppNative(uuid.getLeastSignificantBits(),uuid.getMostSignificantBits());//
  7.    }
  8. //可以看到该方法是本地方法,所以我们要去找相应的JNI文件
  9. private native void gattClientRegisterAppNative(long app_uuid_lsb,  long app_uuid_msb);

也就是说AdvertiseCallbackWrapper里面的 mBluetoothGatt.registerClient(new ParcelUuid(uuid), this)最终调用的是gattClientRegisterAppNative方法。

找到对应的JNI文件:http://androidxref.com/5.1.1_r6/xref/packages/apps/Bluetooth/jni/com_android_bluetooth_gatt.cpp

  1. static void gattClientRegisterAppNative(JNIEnv* env, jobject object,jlong app_uuid_lsb, jlong app_uuid_msb )
  2. {
  3.    bt_uuid_t uuid;
  4.    if (!sGattIf) return;
  5.    set_uuid(uuid.uu, app_uuid_msb, app_uuid_lsb);
  6.    sGattIf->client->register_client(&uuid);
  7. }

这时大家可以看到,具体的实现也不在这个方法里,没办法只能继续怼了。看一下sGattIf是什么?

  1. static const btgatt_interface_t *sGattIf = NULL;

sGattIf的类型是btgatt_interface_t,来看一下相应的头,这个结构体是如何定义的,代码位于:http://androidxref.com/5.1.1_r6/xref/hardware/libhardware/include/hardware/bt_gatt.h#57

  1. /** Represents the standard Bluetooth GATT interface. */
  2. typedef struct {
  3.    /** Set to sizeof(btgatt_interface_t) */
  4.    size_t          size;
  5.    /**
  6.     * Initializes the interface and provides callback routines
  7.     */
  8.    bt_status_t (*init)( const btgatt_callbacks_t* callbacks );
  9.    /** Closes the interface */
  10.    void (*cleanup)( void );
  11.   /** Pointer to the GATT client interface methods.*/
  12.    const btgatt_client_interface_t* client;//上面的register_client肯定在这里面了
  13.    /** Pointer to the GATT server interface methods.*/
  14.    const btgatt_server_interface_t* server;
  15. } btgatt_interface_t;

接着继续往下怼,看一下btgatt_client_interface_t,代码位于:http://androidxref.com/5.1.1_r6/xref/hardware/libhardware/include/hardware/bt_gatt_client.h

  1. /** Represents the standard BT-GATT client interface. */
  2. typedef struct {
  3.    /** Registers a GATT client application with the stack */
  4.    bt_status_t (*register_client)( bt_uuid_t *uuid );//** bt_uuid_t------Bluetooth 128-bit UUID,就是之前UUID.random生成的 */
  5.    /** Unregister a client application from the stack */
  6.    bt_status_t (*unregister_client)(int client_if );
  7.    /** Start or stop LE device scanning */
  8.    bt_status_t (*scan)( bool start );
  9.   /** Create a connection to a remote LE or dual-mode device */
  10.    bt_status_t (*connect)( int client_if, const bt_bdaddr_t *bd_addr,
  11.                         bool is_direct, int transport );
  12.    /** Disconnect a remote device or cancel a pending connection */
  13.    bt_status_t (*disconnect)( int client_if, const bt_bdaddr_t *bd_addr,
  14.                    int conn_id);
  15.    /** Start or stop advertisements to listen for incoming connections */
  16.    bt_status_t (*listen)(int client_if, bool start);
  17.    /** Clear the attribute cache for a given device */
  18.    bt_status_t (*refresh)( int client_if, const bt_bdaddr_t *bd_addr );
  19.    /**
  20.     * Enumerate all GATT services on a connected device.
  21.     * Optionally, the results can be filtered for a given UUID.
  22.     */
  23.    bt_status_t (*search_service)(int conn_id, bt_uuid_t *filter_uuid );
  24.    /**
  25.     * Enumerate included services for a given service.
  26.     * Set start_incl_srvc_id to NULL to get the first included service.
  27.     */
  28.    bt_status_t (*get_included_service)( int conn_id, btgatt_srvc_id_t *srvc_id,
  29.                                         btgatt_srvc_id_t *start_incl_srvc_id);
  30.    /**
  31.     * Enumerate characteristics for a given service.
  32.    * Set start_char_id to NULL to get the first characteristic.
  33.     */
  34.   bt_status_t (*get_characteristic)( int conn_id,
  35.                   btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *start_char_id);
  36.    /**
  37.     * Enumerate descriptors for a given characteristic.
  38.     * Set start_descr_id to NULL to get the first descriptor.
  39.     */
  40.    bt_status_t (*get_descriptor)( int conn_id,
  41.                    btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id,
  42.                    btgatt_gatt_id_t *start_descr_id);
  43.    /** Read a characteristic on a remote device */
  44.    bt_status_t (*read_characteristic)( int conn_id,
  45.                   btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id,
  46.                    int auth_req );
  47.    /** Write a remote characteristic */
  48.    bt_status_t (*write_characteristic)(int conn_id,
  49.                   btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id,
  50.                    int write_type, int len, int auth_req,
  51.                    char* p_value);
  52.    /** Read the descriptor for a given characteristic */
  53.    bt_status_t (*read_descriptor)(int conn_id,
  54.                   btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id,
  55.                    btgatt_gatt_id_t *descr_id, int auth_req);
  56.    /** Write a remote descriptor for a given characteristic */
  57.    bt_status_t (*write_descriptor)( int conn_id,
  58.                   btgatt_srvc_id_t *srvc_id, btgatt_gatt_id_t *char_id,
  59.                   btgatt_gatt_id_t *descr_id, int write_type, int len,
  60.                   int auth_req, char* p_value);
  61.    /** Execute a prepared write operation */
  62.    bt_status_t (*execute_write)(int conn_id, int execute);
  63.    /**
  64.    * Register to receive notifications or indications for a given
  65.     * characteristic
  66.     */
  67.    bt_status_t (*register_for_notification)( int client_if,
  68.                   const bt_bdaddr_t *bd_addr, btgatt_srvc_id_t *srvc_id,
  69.                    btgatt_gatt_id_t *char_id);
  70.    /** Deregister a previous request for notifications/indications */
  71.    bt_status_t (*deregister_for_notification)( int client_if,
  72.                    const bt_bdaddr_t *bd_addr, btgatt_srvc_id_t *srvc_id,
  73.                   btgatt_gatt_id_t *char_id);
  74.    /** Request RSSI for a given remote device */
  75.    bt_status_t (*read_remote_rssi)( int client_if, const bt_bdaddr_t *bd_addr);
  76.    /** Setup scan filter params */
  77.    bt_status_t (*scan_filter_param_setup)(int client_if, int action, int filt_index, int feat_seln,
  78.                                      int list_logic_type, int filt_logic_type, int rssi_high_thres,
  79.                                     int rssi_low_thres, int dely_mode, int found_timeout,
  80.                                     int lost_timeout, int found_timeout_cnt);
  81.    /** Configure a scan filter condition  */
  82.    bt_status_t (*scan_filter_add_remove)(int client_if, int action, int filt_type,
  83.                                   int filt_index, int company_id,
  84.                                   int company_id_mask, const bt_uuid_t *p_uuid,
  85.                                   const bt_uuid_t *p_uuid_mask, const bt_bdaddr_t *bd_addr,
  86.                                   char addr_type, int data_len, char* p_data, int mask_len,
  87.                                   char* p_mask);
  88.    /** Clear all scan filter conditions for specific filter index*/
  89.    bt_status_t (*scan_filter_clear)(int client_if, int filt_index);
  90.    /** Enable / disable scan filter feature*/
  91.    bt_status_t (*scan_filter_enable)(int client_if, bool enable);
  92.    /** Determine the type of the remote device (LE, BR/EDR, Dual-mode) */
  93.    int (*get_device_type)( const bt_bdaddr_t *bd_addr );
  94.    /** Set the advertising data or scan response data */
  95.    bt_status_t (*set_adv_data)(int client_if, bool set_scan_rsp, bool include_name,
  96.                   bool include_txpower, int min_interval, int max_interval, int appearance,
  97.                   uint16_t manufacturer_len, char* manufacturer_data,
  98.                   uint16_t service_data_len, char* service_data,
  99.                    uint16_t service_uuid_len, char* service_uuid);
  100.    /** Configure the MTU for a given connection */
  101.    bt_status_t (*configure_mtu)(int conn_id, int mtu);
  102.    /** Request a connection parameter update */
  103.    bt_status_t (*conn_parameter_update)(const bt_bdaddr_t *bd_addr, int min_interval,
  104.                    int max_interval, int latency, int timeout);
  105.    /** Sets the LE scan interval and window in units of N*0.625 msec */
  106.    bt_status_t (*set_scan_parameters)(int scan_interval, int scan_window);
  107.    /* Setup the parameters as per spec, user manual specified values and enable multi ADV */
  108.    bt_status_t (*multi_adv_enable)(int client_if, int min_interval,int max_interval,int adv_type,
  109.                 int chnl_map, int tx_power, int timeout_s);
  110.    /* Update the parameters as per spec, user manual specified values and restart multi ADV */
  111.    bt_status_t (*multi_adv_update)(int client_if, int min_interval,int max_interval,int adv_type,
  112.                 int chnl_map, int tx_power, int timeout_s);
  113.    /* Setup the data for the specified instance */
  114.    bt_status_t (*multi_adv_set_inst_data)(int client_if, bool set_scan_rsp, bool include_name,
  115.                    bool incl_txpower, int appearance, int manufacturer_len,
  116.                    char* manufacturer_data, int service_data_len,
  117.                    char* service_data, int service_uuid_len, char* service_uuid);
  118.    /* Disable the multi adv instance */
  119.    bt_status_t (*multi_adv_disable)(int client_if);
  120.    /* Configure the batchscan storage */
  121.    bt_status_t (*batchscan_cfg_storage)(int client_if, int batch_scan_full_max,
  122.        int batch_scan_trunc_max, int batch_scan_notify_threshold);
  123.    /* Enable batchscan */
  124.    bt_status_t (*batchscan_enb_batch_scan)(int client_if, int scan_mode,
  125.        int scan_interval, int scan_window, int addr_type, int discard_rule);
  126.    /* Disable batchscan */
  127.    bt_status_t (*batchscan_dis_batch_scan)(int client_if);
  128.    /* Read out batchscan reports */
  129.    bt_status_t (*batchscan_read_reports)(int client_if, int scan_mode);
  130.    /** Test mode interface */
  131.    bt_status_t (*test_command)( int command, btgatt_test_params_t* params);
  132. } btgatt_client_interface_t;

关于btgatt_client_interface_t的定义我没有做代码简略,以便大家对客户端接口的方法有个印象。既然我们找到了register_client方法的声明,我们就可以找到其实现。既然btgatt_client_interface_t是代表标准的BT-GATT客户端接口,那么我们就要找BT-GATT客户端接口的实现.几经跳转,终于找到其实现,代码位于:

http://androidxref.com/5.1.1_r6/xref/external/bluetooth/bluedroid/btif/src/btif_gatt_client.c

这里大家会好奇怎么就找到这个文件了呢?别急,听我慢慢到来,首先我们要看谁引用了bt_gatt_client.h

经过搜索发现只有bt_gatt.h引用了bt_gatt_client.h,接着看谁引用了bt_gatt.h,搜索发现有很多个文件都引用了,但是最贴合我们的需求的就是btif_gatt_client.c。

下面看一下其部分代码:

  1. /*******************************************************************************
  2. *
  3. *  Filename:      btif_gatt_client.c
  4. *
  5. *  Description:   GATT client implementation//可以看到这就是我们想要找的实现
  6. *
  7. *******************************************************************************/
  8. /*******************************************************************************
  9. **  Client API Functions
  10. ********************************************************************************/
  11. static bt_status_t btif_gattc_register_app(bt_uuid_t *uuid)//这个就对应registerClient方法
  12. {
  13.    CHECK_BTGATT_INIT();
  14.    btif_gattc_cb_t btif_cb;//该结构体内部有个uuid,也有 uint8_t client_if字段,所以关键在这,浪里个浪
  15.    memcpy(&btif_cb.uuid, uuid, sizeof(bt_uuid_t));
  16.    return btif_transfer_context(btgattc_handle_event, BTIF_GATTC_REGISTER_APP,
  17.                                 (char*) &btif_cb, sizeof(btif_gattc_cb_t), NULL);//这里才是最终实现
  18. }
  19. static bt_status_t btif_gattc_unregister_app(int client_if )
  20. {
  21.    CHECK_BTGATT_INIT();
  22.    btif_gattc_cb_t btif_cb;
  23.    btif_cb.client_if = (uint8_t) client_if;
  24.    return btif_transfer_context(btgattc_handle_event, BTIF_GATTC_UNREGISTER_APP,
  25.                                 (char*) &btif_cb, sizeof(btif_gattc_cb_t), NULL);
  26. }
  27. static bt_status_t btif_gattc_scan( bool start )
  28. {
  29.    CHECK_BTGATT_INIT();
  30.    btif_gattc_cb_t btif_cb;
  31.    return btif_transfer_context(btgattc_handle_event, start ? BTIF_GATTC_SCAN_START : BTIF_GATTC_SCAN_STOP,
  32.                                 (char*) &btif_cb, sizeof(btif_gattc_cb_t), NULL);
  33. }

最终实现还没有怼到,现在移步到http://androidxref.com/5.1.1_r6/xref/external/bluetooth/bluedroid/btif/src/btif_core.c#201看代码:

  1. /*******************************************************************************
  2. **
  3. ** Function         btif_transfer_context
  4. **
  5. ** Description      This function switches context to btif task
  6. **
  7. **                  p_cback   : callback used to process message in btif context
  8. **                  event     : event id of message//上面传入的是BTIF_GATTC_REGISTER_APP,即注册
  9. **                  p_params  : parameter area passed to callback (copied)----> 指上面代码中的btif_cb
  10. **                  param_len : length of parameter area
  11. **                  p_copy_cback : If set this function will be invoked for deep copy
  12. **
  13. ** Returns          void
  14. **
  15. *******************************************************************************/
  16. bt_status_t btif_transfer_context (tBTIF_CBACK *p_cback, UINT16 event, char* p_params, int param_len, tBTIF_COPY_CBACK *p_copy_cback)
  17. {
  18.    tBTIF_CONTEXT_SWITCH_CBACK *p_msg;
  19.    BTIF_TRACE_VERBOSE("btif_transfer_context event %d, len %d", event, param_len);
  20.    /* allocate and send message that will be executed in btif context */
  21.    if ((p_msg = (tBTIF_CONTEXT_SWITCH_CBACK *) GKI_getbuf(sizeof(tBTIF_CONTEXT_SWITCH_CBACK) + param_len)) != NULL)
  22.    {
  23.        p_msg->hdr.event = BT_EVT_CONTEXT_SWITCH_EVT; /* internal event */
  24.        p_msg->p_cb = p_cback;
  25.        p_msg->event = event;                         /* callback event */
  26.        /* check if caller has provided a copy callback to do the deep copy */
  27.        if (p_copy_cback)//上面调用中p_copy_cback传入是null
  28.        {
  29.            p_copy_cback(event, p_msg->p_param, p_params);
  30.        }
  31.        else if (p_params)
  32.        {
  33.            memcpy(p_msg->p_param, p_params, param_len);  /* callback parameter data,这个回调参数,复制p_params到p_msg里的一个字段中 */
  34.        }
  35.        btif_sendmsg(p_msg);//现在可以肯定的是clientif的生成。
  36.        return BT_STATUS_SUCCESS;//这个就是注册成功了,啦啦
  37.    }
  38.    else
  39.    {
  40.        /* let caller deal with a failed allocation */
  41.        return BT_STATUS_NOMEM;
  42.    }
  43. }


看到上面的代码,可以肯定的是client_if的生成肯定是在btif_sendmsg这个函数的一系列调用里面了,我们现在已经怼到了蓝牙协议栈的代码,即bluedroid 。到此为止吧,不怼了,如果大家真想继续怼,Please fuck bluedroid code!

下面我们一起来看看log:


com.android.bluetooth D/HeadsetStateMachine: Disconnected process message: 10, size: 0

com.android.bluetooth D/BtGatt.GattService: registerServer() - UUID=67bc6417-e673-4d91-8a25-28e8792554d0

com.android.bluetooth D/BtGatt.btif: btif_gatts_register_app

com.android.bluetooth D/BtGatt.btif: btgatts_handle_event: Event 2000

com.android.bluetooth E/bt-btif: register application first_unuse rcb_idx = 0

com.android.bluetooth D/BtGatt.btif: btapp_gatts_handle_cback: Event 0

com.android.bluetooth D/BtGatt.GattService: onServerRegistered() - UUID=67bc6417-e673-4d91-8a25-28e8792554d0, serverIf=4

com.android.bluetooth D/BtGatt.GattService: registerClient() - UUID=83edfbde-2553-4a0b-8682-01232ac6600c

com.android.bluetooth D/BtGatt.GattService: onClientRegistered() - UUID=83edfbde-2553-4a0b-8682-01232ac6600c, clientIf=5

com.android.bluetooth D/BtGatt.AdvertiseManager: message : 0

com.android.bluetooth D/BtGatt.AdvertiseManager: starting single advertising

com.android.bluetooth W/hcicmd: to do btsnd_hcic_ble_set_adv_enable 0x1

com.android.bluetooth D/hcicmd: Done btsnd_hcic_ble_set_adv_enable 0x1

com.android.bluetooth E/bt-btif: Listen For All now

com.android.bluetooth D/BtGatt.GattService: onAdvertiseCallback,- clientIf=5, status=0

com.android.bluetooth D/BtGatt.GattService: beginServiceDeclaration() - uuid=0000fee7-0000-1000-8000-00805f9b34fb

com.android.bluetooth D/BtGatt.GattService: addCharacteristic() - uuid=0000fec8-0000-1000-8000-00805f9b34fb

com.android.bluetooth D/BtGatt.GattService: addDescriptor() - uuid=00002902-0000-1000-8000-00805f9b34fb

com.android.bluetooth D/BtGatt.GattService: addCharacteristic() - uuid=0000fec7-0000-1000-8000-00805f9b34fb

com.android.bluetooth D/BtGatt.GattService: addDescriptor() - uuid=00002902-0000-1000-8000-00805f9b34fb

com.android.bluetooth D/BtGatt.GattService: addCharacteristic() - uuid=0000fec9-0000-1000-8000-00805f9b34fb

com.android.bluetooth D/BtGatt.GattService: addDescriptor() - uuid=00002902-0000-1000-8000-00805f9b34fb

com.android.bluetooth D/BtGatt.GattService: endServiceDeclaration()

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - srvcHandle=0

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - next entry type=1

com.android.bluetooth D/BtGatt.btif: btif_gatts_add_service

com.android.bluetooth D/BtGatt.btif: btgatts_handle_event: Event 2004

com.android.bluetooth E/bt-btif: create service rcb_idx = 0

com.android.bluetooth D/BtGatt.btif: btapp_gatts_handle_cback: Event 7

com.android.bluetooth D/BtGatt.GattService: onServiceAdded() UUID=0000fee7-0000-1000-8000-00805f9b34fb, status=0, handle=40

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - srvcHandle=40

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - next entry type=2

com.android.bluetooth D/BtGatt.btif: btif_gatts_add_characteristic

com.android.bluetooth D/BtGatt.btif: btgatts_handle_event: Event 2006

com.android.bluetooth D/BtGatt.btif: btapp_gatts_handle_cback: Event 9

com.android.bluetooth D/BtGatt.GattService: onCharacteristicAdded() UUID=0000fec8-0000-1000-8000-00805f9b34fb, status=0, srvcHandle=40, charHandle=42

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - srvcHandle=40

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - next entry type=3

com.android.bluetooth D/BtGatt.btif: btif_gatts_add_descriptor

com.android.bluetooth D/BtGatt.btif: btgatts_handle_event: Event 2007

com.android.bluetooth D/BtGatt.btif: btapp_gatts_handle_cback: Event 10

com.android.bluetooth D/BtGatt.GattService: onDescriptorAdded() UUID=00002902-0000-1000-8000-00805f9b34fb, status=0, srvcHandle=40, descrHandle=43

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - srvcHandle=40

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - next entry type=2

com.android.bluetooth D/BtGatt.btif: btif_gatts_add_characteristic

com.android.bluetooth D/BtGatt.btif: btgatts_handle_event: Event 2006

com.android.bluetooth D/BtGatt.btif: btapp_gatts_handle_cback: Event 9

com.android.bluetooth D/BtGatt.GattService: onCharacteristicAdded() UUID=0000fec7-0000-1000-8000-00805f9b34fb, status=0, srvcHandle=40, charHandle=45

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - srvcHandle=40

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - next entry type=3

com.android.bluetooth D/BtGatt.btif: btif_gatts_add_descriptor

com.android.bluetooth D/BtGatt.btif: btgatts_handle_event: Event 2007

com.android.bluetooth D/BtGatt.btif: btapp_gatts_handle_cback: Event 10

com.android.bluetooth D/BtGatt.GattService: onDescriptorAdded() UUID=00002902-0000-1000-8000-00805f9b34fb, status=0, srvcHandle=40, descrHandle=46

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - srvcHandle=40

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - next entry type=2

com.android.bluetooth D/BtGatt.btif: btif_gatts_add_characteristic

com.android.bluetooth D/BtGatt.btif: btgatts_handle_event: Event 2006

com.android.bluetooth D/BtGatt.btif: btapp_gatts_handle_cback: Event 9

com.android.bluetooth D/BtGatt.GattService: onCharacteristicAdded() UUID=0000fec9-0000-1000-8000-00805f9b34fb, status=0, srvcHandle=40, charHandle=48

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - srvcHandle=40

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - next entry type=3

com.android.bluetooth D/BtGatt.btif: btif_gatts_add_descriptor

com.android.bluetooth D/BtGatt.btif: btgatts_handle_event: Event 2007

com.android.bluetooth D/BtGatt.btif: btapp_gatts_handle_cback: Event 10

com.android.bluetooth D/BtGatt.GattService: onDescriptorAdded() UUID=00002902-0000-1000-8000-00805f9b34fb, status=0, srvcHandle=40, descrHandle=49

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - srvcHandle=40

com.android.bluetooth D/BtGatt.btif: btif_gatts_start_service

com.android.bluetooth D/BtGatt.GattService: continueServiceDeclaration() - completed.

com.android.bluetooth D/BtGatt.btif: btgatts_handle_event: Event 2008

com.android.bluetooth D/BtGatt.btif: btapp_gatts_handle_cback: Event 12

com.android.bluetooth D/BtGatt.GattService: onServiceStarted() srvcHandle=40, status=0

com.android.bluetooth D/HeadsetStateMachine: Disconnected process message: 10, size: 0

com.android.bluetooth W/hcicmd: to do btsnd_hcic_ble_set_adv_enable 0x0

com.android.bluetooth D/hcicmd: Done btsnd_hcic_ble_set_adv_enable 0x0

com.android.bluetooth W/hcicmd: to do btsnd_hcic_ble_set_adv_enable 0x1

com.android.bluetooth D/hcicmd: Done btsnd_hcic_ble_set_adv_enable 0x1




com.general.testbluegattserverdemo D/BluetoothGattServer: registerCallback()

com.general.testbluegattserverdemo W/art: Suspending all threads took: 21.722ms

com.general.testbluegattserverdemo I/art: Background sticky concurrent mark sweep GC freed 1691(94KB) AllocSpace objects, 0(0B) LOS objects, 19% free, 486KB/605KB, paused 41.943ms total 149.288ms

com.general.testbluegattserverdemo D/BluetoothGattServer: registerCallback() - UUID=67bc6417-e673-4d91-8a25-28e8792554d0

com.general.testbluegattserverdemo I/art: Background partial concurrent mark sweep GC freed 2029(97KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 502KB/1014KB, paused 908us total 115.721ms

com.general.testbluegattserverdemo D/BluetoothGattServer: onServerRegistered() - status=0 serverIf=4

com.general.testbluegattserverdemo D/BluetoothLeAdvertiser: onClientRegistered() - status=0 clientIf=5

com.general.testbluegattserverdemo D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true

com.general.testbluegattserverdemo D/Atlas: Validating map...

com.general.testbluegattserverdemo E/ble: suceess

com.general.testbluegattserverdemo E/ble:  not have wechat service

com.general.testbluegattserverdemo D/BluetoothGattServer: addService() - service: 0000fee7-0000-1000-8000-00805f9b34fb

com.general.testbluegattserverdemo D/BluetoothGattServer: onServiceAdded() - service=0000fee7-0000-1000-8000-00805f9b34fbstatus=0

com.general.testbluegattserverdemo E/Test Ble: status:0uuid:0000fee7-0000-1000-8000-00805f9b34fb

com.general.testbluegattserverdemo I/OpenGLRenderer: Initialized EGL, version 1.4


通过log我们可以看到clientIf是大于0的,上篇文章也说过mClientIf的值的含义,具体看上一篇文章的分析。

到此为止,该篇文章开头的第二个问题,我们简单做一下回答:

mClientIf是如何生成的以及作用?

clientIf的值是在bluedroid蓝牙协议栈的代码里生成的,要知道具体怎么生成的,可以根据该篇文章继续怼。

mClientIf=0——>未注册;mClinetIf=-1——>广播停止或注册超时;mClientIf>0——>已注册并且已经广播成功

至于作用就是根据其值做不同的逻辑业务处理啦。

开篇的两个问题算是回答完了,也即我们怼完了 mBluetoothGatt.registerClient(new ParcelUuid(uuid), this)这个方法,仅仅是注册过程怼完了,还有广播流程没有怼,放到下篇文章里继续怼。

由于源码的复杂性与庞大,这里文字表达的不是非常清晰,请谅解,如果你从该篇文章领悟到怼源码的姿势,那才是最大的收获。

转载请注明出处:http://blog.csdn.net/android_jiangjun/article/details/77982980

作者:gc_gongchao 发表于2017/9/14 17:23:19 原文链接
阅读:61 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>