Low power bluetooth device
background
The company’s hardware module upgrade, from the original single-mode Bluetooth, to the current dual-mode Bluetooth. Single-mode Bluetooth is used for audio or data transmission via BlueTooth 2.0 traditional Bluetooth. Dual-mode Bluetooth is compatible with traditional Bluetooth, can communicate with traditional Bluetooth, and can communicate with BLE. Google started to support BLE low-power Bluetooth after Android 4.3.
origin
The Bluetooth module used by the company, the corresponding sdk is provided by the supplier. In the code test and development project, the stability of the connection speed is found to be problematic, and the technical staff of other companies are contacted. Negotiation issues should be a time-consuming and laborious task at work, and they may not be resolved in the end. I asked the relevant personnel on the sdk side and said that I can use the system method to debug.
BLE related concepts
UUID
Universally Unique Identifier, unique identifier, UUID of SERVICE, WRITE, NOTIFICATION, etc. will be used in general development.
Generic Attribute Profile (GATT)
GATT is a general specification for sending and receiving. Unlike traditional Bluetooth using sockets, file data transfer between BLEs is based on GATT. The GATT connection is one-to-one, which means that a BLE device intelligently connects to a device. Once the connection is successful, only when the connection is disconnected, otherwise the other devices cannot connect to the current device.
Attribute Protocol (ATT)
GATT is based on ATT. ATT is optimized for BLE devices. It uses as little data as possible in the transmission. Each attribute has a unique UUID and transmission between attributes. Will be transmitted in the form of characteristics and services.
Characteristic
Characteristic feature value, containing one or more values, can be read and written by the character of the character.
Descriptor
attribute for describing feature values
Service
feature worthy collection
development
permissions
For Bluetooth related operations, you need to use Bluetooth permissions to add permissions to the AndroidManifest.xml manifest file.
After android6.0, Bluetooth BLE also needs to obtain location permissions
Initialize the Bluetooth Adapter
Before using Bluetooth for related operations, you need to get the Bluetooth adapter first.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (bluetoothManager != null) mBluetoothAdapter = bluetoothManager.getAdapter();
>
Determine if Bluetooth is available or not, if Bluetooth is off, then turn on Bluetooth
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
>
scanning
During the scanning process, the scan result needs to be recalled, and the scan result is processed in the onLeScan() method.
private BluetoothDevice mDevice;
final BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() @Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord)
Log.d("haha", "onLeScan: " + device.getName() + " : " + rssi); String name = device.getName(); if (name != null) < deviceName.setText(name); if (name.equals("test_ble")) < mDevice = device; mBluetoothAdapter.stopLeScan(mLeScanCallback); >> >
Since Bluetooth scanning consumes time and power, when scanning, pay attention to customize a suitable scanning time, and choose the appropriate time in the actual development and project application process. Define the Bluetooth scan callback, start scanning Bluetooth, scan to the desired Bluetooth, you can stop scanning
private void scanLeDevice(final boolean enable) if (enable) // Stops scanning after a pre-defined scan period.
// Pre-define the time to stop Bluetooth scanning (because Bluetooth scanning requires more power)
mHandler.postDelayed(new Runnable() < @Override public void run() < mScanning = false; mBluetoothAdapter.stopLeScan(mLeScanCallback); >>, 30000); mScanning = true; // Define a callback interface for scanning to end processing mBluetoothAdapter.startLeScan(mLeScanCallback); > else
The Bluetooth scan can be performed by invoking the mLeScanCallback parameter by calling the startBlueScan() of the acquired mBluetoothAdapter.
BluetoothGattCallback implementation
GATT is a general specification for sending and receiving. File data transfer between BLEs is based on GATT, so Gatt interface callbacks are required before making connections.
private String TAG = “haha”;
private boolean isServiceConnected;
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback()
@Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) < super.onConnectionStateChange(gatt, status, newState); Log.d("haha", "onConnectionStateChange: " + newState); if (status != BluetoothGatt.GATT_SUCCESS) < String err = "Cannot connect device with error status: " + status; // Calling the disconnect method when trying to connect fails will not cause this method to callback, so here // Direct callback is fine. gatt.close(); if (mBluetoothGatt != null) < mBluetoothGatt.disconnect(); mBluetoothGatt.close(); mBluetoothGatt = null; >if (mDevice != null) < mBluetoothGatt = mDevice.connectGatt(MainActivity.this, false, mGattCallback); >Log.e(TAG, err); return; > if (newState == BluetoothProfile.STATE_CONNECTED) < //When the Bluetooth device is connected Toast.makeText(MainActivity.this, "Connection Success", Toast.LENGTH_SHORT).show(); Log.i("haha", "Attempting to start service discovery:" + Log.d("haha", "onConnectionStateChange: " + "Connection succeeded"); >else if (newState == BluetoothProfile.STATE_DISCONNECTED)/When the device cannot connect if (mBluetoothGatt != null) < mBluetoothGatt.disconnect(); mBluetoothGatt.close(); mBluetoothGatt = null; > gatt.close(); if (mDevice != null) < mBluetoothGatt = mDevice.connectGatt(MainActivity.this, false, mGattCallback); >>
The current connection is judged by status. When status != BluetoothGatt.GATT_SUCCESS, the Gatt reset operation can be performed to try to reconnect. When newState == BluetoothProfile.STATE_CONNECTED, the connection is successful at this time.
connection
After the Gatt connection is returned, you can connect to Ble Bluetooth.
public void startConnect(View view) if (mDevice != null) if (mBluetoothGatt != null) mBluetoothGatt.disconnect();
mBluetoothGatt.close();
mBluetoothGatt = null;
>
mBluetoothGatt = mDevice.connectGatt(MainActivity.this, false, mGattCallback);
>
>
Precautions
BLE implementation of android 4.3 after google provides support, so Ble project can only run on the phone above API 18; Android 6.0 or above, Ble service also needs to locate permissions, otherwise it can not be used. When not in use, you should also pay attention to turning off or disconnecting the Bluetooth. Since the Ble connection is an exclusive operation, if the device is connected, the other devices cannot perform any operation.
Github
likes or helps you, can follow or like BleDemo
Next Android BLE low-power Bluetooth development minimalist series (2) read and write operations
Author: Muzi biscuits
link:
Source: Short book
The copyright of the book is owned by the author. Any form of reprint should be contacted by the author for authorization and the source.