Android Bluetooth BLE ideas

Bluetooth BLE Notes

A service contains multiple characteristics

A characteristic contains 1 value

1 value can be described by multiple descriptors

1. BluetoothGatt : BluetoothGatt is our most used and most important class. In order to understand as easily as possible, here we can regard it as a channel for establishing communication between Android mobile phones and BLE terminal devices. Only with this channel , we have the premise of communication.
2. BluetoothGattService : Bluetooth device service, here we compare BluetoothGattService to a class. And Bluetoothdevice, we compare it to a school. There can be many classes in a school, that is to say, each of our BLE terminal devices has multiple services, and the classes (each service) are distinguished by UUID (unique identifier)
​​3, BluetoothGattCharacteristic: The characteristics of Bluetooth devices are the key to exchanging data between mobile phones and BLE terminal devices. Everything we do is to get it. Here we compare it to students. There are many students in a class, that is to say, we have multiple characteristics under each service, and students (each characteristic) are distinguished by UUID (unique identifier).
4. Summary: When we want to use a mobile phone to communicate with a BLE device, it is actually equivalent to communicating with a student. First of all, we need to build a pipeline, that is, we need to obtain aBluetoothGatt , secondly, we need to know which class the student is in and what the student number is, which is what we call serviceUUID and charUUID . Here we also need to pay attention. After finding this student, we do not directly communicate with him. He is like an intermediary, helping the two transmit information between the mobile phone and the BLE terminal device. The data sent by our mobile phone must first go through him. , is passed to the BLE device by him, and the return information on the BLE device is also passed to him first, and then the mobile phone reads it from him.


BLE process

1. Obtain a Bluetooth adapter, the system only has one Bluetooth adapter
2, through the bluetooth adapter can operate the bluetooth
3. Discover Bluetooth
4. Connect to the GATT server on the BLE device
5. Get the device service service and the corresponding characteristic after connecting


// Initialize the Bluetooth adapter   TODO 1
 final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();


// Ensure that Bluetooth can be enabled on the device    TODO 2
 if ( mBluetoothAdapter == null || ! mBluetoothAdapter .isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}


/**
 * TODO 3.1
 * Scan and display available Bluetooth devices . Stop searching after 10 seconds .
 * mBluetoothAdapter.startLeScan(mLeScanCallback);
 * If you only want to scan the specified type of peripherals, you can call startLeScan(UUID[ ], BluetoothAdapter.LeScanCallback)); Need to provide an array of UUID objects of GATT services supported by your app .
*/
 private void scanLeDevice ( final boolean enable) {
     if (enable) {
         // Stop scanning mHandler after a scheduled scan period
 .postDelayed( new Runnable() {
             @Override
 public void run                      () {
                mScanning = false;
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }
        }, SCAN_PERIOD);
        mScanning = true;
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    } else {
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
}


    /**
     * TODO 3.2
     * 扫描的回调
     */
    BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//                    mLeDeviceListAdapter.addDevice(device);   //列表添加扫描到的蓝牙对象
//                    mLeDeviceListAdapter.notifyDataSetChanged();
                }
            });
        }
    };


public void connect(final String address) {
    // TODO 4 连接到BLE设备上的GATT服务器(显示到列表上后,根据选择的BEL设备连接通道)
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
}


/**
 * TODO 4.2
 * 连接状态的回调
 */
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

    //连接状态改变的回调
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                        int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            // 连接成功后启动服务发现
            Log.e("AAAAAAAA", "启动服务发现:" + mBluetoothGatt.discoverServices());
        }
    }

    //发现服务的回调
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.e(TAG, "成功发现服务");
        } else {
            Log.e(TAG, "服务发现失败,错误码为:" + status);
        }
    }

    //写操作的回调
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.e(TAG, "写入成功" + characteristic.getValue());
        }
    }

    //读操作的回调
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.e(TAG, "读取成功" + characteristic.getValue());
        }
    }

    //数据返回的回调(此处接收BLE设备返回数据)
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    }
};

/**
 * TODO 5
 * 连接到设备之后获取设备的服务(Service)和服务对应的Characteristic * 获取到特征之后,找到服务中可以向下位机写指令的特征,向该特征写入指令
 * 写入成功之后,开始读取设备返回来的数据。
 */




Guess you like

Origin blog.csdn.net/l331258747/article/details/55260326