get to:
- Know Bluetooth
- Learn about Bluetooth 4.0
- How to turn on Bluetooth
- How to scan peripheral Bluetooth devices
- How to Connect Bluetooth Devices
- How the mobile terminal communicates with the ble terminal
5. How to connect Bluetooth devices
We've got the list of Bluetooth devices in the last post, and now we're connecting to the ble terminal
Stop Scanning First
mBluetoothAdapter.stopLeScan(mLeScanCallback);
Then release the connection request and make the next device connection request
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
}
Connecting address is the mac address of the ble terminal
BluetoothDevice device=mBluetoothAdapter.getRemoteDevice(address);
//Connect directly to device incomingfalse
mBluetoothGatt = device.connectGatt(mContext, false, mGattCallback);
mGattCallback is the result of certain operations on a device that has been connected to it.Returns the state of the center and the data provided around it. This abstract class has nine methods.
Do it to your needs
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
//When the connection status with the ble terminal changes
//STATE_DISCONNECTED Disconnect
//In STATE_CONNECTING Connection
//STATE_CONNECTED Connection
//STATE_DISCONNECTING Disconnecting
//Connection Successful
if (newState == BluetoothProfile.STATE_CONNECTED) {
// Searching for service s supported by connected devices requires a connection to enable
gatt.discoverServices();
//Disconnect
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
//Search Service
findService(gatt.getServices());
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
// Read information from Bluetooth devices
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
//After sending instructions successfully
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
{
super.onCharacteristicWrite(gatt, characteristic, status);
//Write Successful
}
};
Here you can connect the ble Terminal successfully. In this onConnectionStateChange method, the connection is determined by the status, the disconnection information, and the communication follows
Next, you need to work with the hardware engineer. Whatever you are doing with a bleTerminal Device, he must have relevant protocols. First, learn about the UUID, which is the unique identification of the bleTerminal service,characteristic,descriptor.
The above search service method requires UUID
public void findService(List<BluetoothGattService> paramList) {
Iterator localIterator1 = paramList.iterator();
while (localIterator1.hasNext()) {
BluetoothGattService localBluetoothGattService = (BluetoothGattService) localIterator1
.next();
//Find the service uuid we need to use based on the unique identity uuid
if (localBluetoothGattService.getUuid().toString()
.equalsIgnoreCase(ConstantUtils.UUID_SERVER)) {
//Get all the features in the service
List localList = localBluetoothGattService.getCharacteristics();
Iterator localIterator2 = localList.iterator();
while (localIterator2.hasNext()) {
BluetoothGattCharacteristic localBluetoothGattCharacteristic = (BluetoothGattCharacteristic) localIterator2
.next();
//Get the Characteristics notification uuid we need based on uuid
if (localBluetoothGattCharacteristic.getUuid().toString()
.equalsIgnoreCase(ConstantUtils.UUID_NOTIFY)) {
bleGattCharacteristic = localBluetoothGattCharacteristic;
break;
}
}
break;
}
}
// Set to true to enable the notification object
mBluetoothGatt.setCharacteristicNotification(bleGattCharacteristic, true);
}
The two UUIDs used above are service and notification, and the other one is write. This is not fixed. Maybe you only have two UUIDs on your protocol. Notification and write are the same uuid.
The next step is to send instructions to the ble terminal. The general protocol stipulates that byte[] should be sent. Data formats should be written strictly according to the protocol, such as encryption/decryption, validation, subcontracting, length, etc.
6. Send instructions to the ble terminal
public boolean write(byte byteArray[]) {
if (mBluetoothGatt == null) {
return false;
}
BluetoothGattCharacteristic writeCharacteristic = getCharcteristic(ConstantUtils.UUID_SERVER, ConstantUtils
.UUID_WRITE); //Written uuid is used here
if (writeCharacteristic == null) {
return false;
}
writeCharacteristic.setValue(byteArray);
return mBluetoothGatt.writeCharacteristic(writeCharacteristic);
}
private BluetoothGattCharacteristic getCharcteristic(String serviceUUID, String characteristicUUID) {
//Get Service Objects
BluetoothGattService service = getService(UUID.fromString(serviceUUID)); //Call the method above to get the service
if (service == null) {
return null;
}
//Get the Characteristic object under this service node
final BluetoothGattCharacteristic gattCharacteristic = service.getCharacteristic(UUID.fromString
(characteristicUUID));
if (gattCharacteristic != null) {
return gattCharacteristic;
} else {
return null;
}
}
//Get it from uuid
public BluetoothGattService getService(UUID uuid) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
return null;
}
return mBluetoothGatt.getService(uuid);
}
Look at the source code for getService
public BluetoothGattService getService(UUID uuid) {
for (BluetoothGattService service : mServices) {
if (service.getDevice().equals(mDevice) &&
service.getUuid().equals(uuid)) {
return service;
}
}
return null;
}
Traversing through this collection of mServices Return to this Bluetooth GattService if the UUID of the service is the same. Look at the source code of getCharacteristic the same way. Get Bluetooth GattCharacteristic from the written uuid. ok can now use Bluetooth GattCharacteristic to send instructions to the ble terminal.
public BluetoothGattCharacteristic getCharacteristic(UUID uuid) {
for(BluetoothGattCharacteristic characteristic : mCharacteristics) {
if (uuid.equals(characteristic.getUuid()))
return characteristic;
}
return null;
}
Send instructions here and write them back to true successfully. Otherwise, if they fail, your uuid may be misused. For example, the uuid you write is read, the data you send has been mentioned before, and according to your protocol, it is unclear to communicate with hardware engineers.
Receive data returned by Bluetooth
Once Bluetooth receives the instructions we send, onCharacteristicChanged receives the data returned by Bluetooth.
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
byte[] arrayOfByte = characteristic
.getValue();
}
Ok, what to do to get this set, what errors I want to point out and learn together