BLE device gets the data when it is disconnected from the gatt server.
I am trying to send data to the BLE device through the GATT server. When I try to send data which is command (string) to the BLE device, gattscancallback is called and it says write successful but nothing happens to the BLE device. But when I exit the application, the BLE device gets the data. I found that BLE device gets the data when it is disconnected to the gatt server. How do I solve this problem?
this is my GattCallback
private val gattCallback: BluetoothGattCallback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
super.onConnectionStateChange(gatt, status, newState)
if( status == BluetoothGatt.GATT_FAILURE ) {
disconnect()
return
} else if( status != BluetoothGatt.GATT_SUCCESS ) {
disconnect()
return
}
if( newState == BluetoothProfile.STATE_CONNECTED ) {
// update the connection status message
Log.d(TAG, "Connected to the GATT server")
gatt.discoverServices()
} else if ( newState == BluetoothProfile.STATE_DISCONNECTED ) {
disconnect()
}
}
override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
super.onServicesDiscovered(gatt, status)
// check if the discovery failed
if (status != BluetoothGatt.GATT_SUCCESS) {
Log.e(TAG, "Device service discovery failed, status: $status")
return
}
// log for successful discovery
Log.d(TAG, "Services discovery is successful")
isStatuschanged = "connected"
// find command characteristics from the GATT server
val respCharacteristic = gatt?.let { BluetoothUtils.findResponseCharacteristic(it) }
// disconnect if the characteristic is not found
if( respCharacteristic == null ) {
Log.e(TAG, "Unable to find cmd characteristic")
disconnect()
return
}
gatt.setCharacteristicNotification(respCharacteristic, true)
// UUID for notification
val descriptor: BluetoothGattDescriptor = respCharacteristic.getDescriptor(
UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG)
)
descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
gatt.writeDescriptor(descriptor)
}
override fun onCharacteristicChanged(
gatt: BluetoothGatt?,
characteristic: BluetoothGattCharacteristic
) {
super.onCharacteristicChanged(gatt, characteristic)
//Log.d(TAG, "characteristic changed: " + characteristic.uuid.toString())
readCharacteristic(characteristic)
}
override fun onCharacteristicWrite(
gatt: BluetoothGatt?,
characteristic: BluetoothGattCharacteristic?,
status: Int
) {
super.onCharacteristicWrite(gatt, characteristic, status)
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.d(TAG, "Characteristic written successfully")
} else {
Log.e(TAG, "Characteristic write unsuccessful, status: $status")
disconnect()
}
}
override fun onCharacteristicRead(
gatt: BluetoothGatt?,
characteristic: BluetoothGattCharacteristic,
status: Int
) {
super.onCharacteristicRead(gatt, characteristic, status)
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.d(TAG, "Characteristic read successfully")
readCharacteristic(characteristic)
} else {
Log.e(TAG, "Characteristic read unsuccessful, status: $status")
// Trying to read from the Time Characteristic? It doesnt have the property or permissions
// set to allow this. Normally this would be an error and you would want to:
// disconnectGattServer()
}
}
/**
* Log the value of the characteristic
* #param characteristic
*/
}
this is my write function
fun write(message: String) {
val cmdCharacteristic = BluetoothUtils.findCommandCharacteristic(bluetoothGatt!!)
if (cmdCharacteristic == null) {
Log.e(TAG, "Unable to find cmd characteristic")
disconnect()
return
}
cmdCharacteristic?.value = message.toByteArray()
//bluetoothGatt!!.writeCharacteristic(cmdCharacteristic)
val success: Boolean = bluetoothGatt!!.writeCharacteristic(cmdCharacteristic)
if (!success) {
Log.d("jay", "failed to write command")
}
Log.d("jay", "write succesful")
//disconnect()
}
this is my disconnect function
fun disconnect() {
Log.d("jay", "disconnect: bluetoothGatt is null? ${bluetoothGatt == null}")
bluetoothDeviceAddress = null
bluetoothGatt?.disconnect()
isStatuschanged = "disconnected"
bluetoothGatt = null
}
Can you show the disconnect() method? Because if you wrote that your central device sends data to the ble device when the application closes, it means that gattCallback's onConnectionState is triggered with a call to newState == BluetoothProfile.STATE_DISCONNECTED and a call to the disconnet() method.
Perhaps the problem is that you explicitly need to specify the record type for the characteristic for example: BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT or BluetoothGattCharacteristic.WRITE_TYPE_WITHOUT_RESPONSE.
Also, there may be an error in the calling code, for example, if you use coroutines and manage them incorrectly
I recently had a similar problem when I solved it by specifying the feature write type and adding the setCharacteristicNotification() method
I had a similar problem recently, but I solved it by specifying the feature record type, and adding the setCharacteristicNotification method
Related
The function onCharacteristicChanged is called just one time every time i call a writecharacteristic. What i expect to happen is onCharacteristicChanged to be called everytime something actually change. For exemple the device I'm using have a characteristic that gets the time of the system, so this characteristic change every second but onCharacteristicChanged doesn't notify me that this change is happening if I don't call the writecharacteristic method
override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
with(characteristic) {
addGlog("\uD83D\uDCE2 BluetoothGattCallback: Characteristic $uuid changed | value: ${value.toHexString()}")
}
}
#SuppressLint("MissingPermission")
fun writeDescriptor(descriptor: BluetoothGattDescriptor, payload: ByteArray) {
actual_gatt?.let { gatt ->
descriptor.value = payload
gatt.writeDescriptor(descriptor)
} ?: addGlog("Not connected to a BLE device!")
}
#SuppressLint("MissingPermission")
fun enableNotifications(characteristic: BluetoothGattCharacteristic) { //nuova versione il meno invasiva possibile
var cccdUuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") //valore temporaneo
addGlog("BluetoothGattDescriptor for ${characteristic.uuid.toString()}")
for (descriptor in characteristic.descriptors) {
addGlog("> " + descriptor.uuid.toString())
cccdUuid = descriptor.uuid
}
val payload = when {
characteristic.isIndicatable() -> BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
characteristic.isNotifiable() -> BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
else -> {
addGlog("ConnectionManager: ${characteristic.uuid} doesn't support notifications/indications")
return
}
}
characteristic.getDescriptor(cccdUuid)?.let { cccDescriptor ->
if (actual_gatt?.setCharacteristicNotification(characteristic, true) == false) {
addGlog("ConnectionManager: setCharacteristicNotification failed for ${characteristic.uuid}")
return
}
writeDescriptor(cccDescriptor, payload)
addGlog("\uD83D\uDD14 enableNotification with cccDescriptor: ${cccDescriptor.toString()} and cccdUuid ${cccdUuid.toString()} completed")
} ?: addGlog("ConnectionManager: ${characteristic.uuid} doesn't contain the CCC descriptor!")
}
I have an android app which scans and connects to a predefined device name. My peripheral is an nRF module which is sending an incrementing data at 1Hz.
However, when I launch the app, it scans and logs multiple connections to the same device and consequently the values received duplicated values. So if there is a log for 3 connections then I get 3 duplicate values and 2 duplicates if there are 2 connections.
D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=14 device=FD:72:38:AA:1A:E7
I/BLE log: Connected to device FD:72:38:AA:1A:E7
D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=15 device=FD:72:38:AA:1A:E7
I/BLE log: Connected to device FD:72:38:AA:1A:E7
Here is my code:
Scanning:
private fun bleScan() {
val scanFilter = ScanFilter.Builder()
.setDeviceName("VEGA-TEST")
.build()
val scanSettings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build()
bleScanner.startScan(mutableListOf(scanFilter), scanSettings, object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result)
with(result.device) {
Log.i("BLE log", "Found device $address")
connectGatt(this#BluetoothService, false ,gattCallback)
}
}
})
}
GATT Connections
private val gattCallback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
super.onConnectionStateChange(gatt, status, newState)
val deviceAddr = gatt.device.address
if(status == BluetoothGatt.GATT_SUCCESS) {
when(newState) {
BluetoothProfile.STATE_CONNECTED -> {
Log.i("BLE log", "Connected to device $deviceAddr")
bleStopScan()
Handler(Looper.getMainLooper()).post {
gatt.discoverServices()
}
}
BluetoothProfile.STATE_DISCONNECTED -> {
Log.i("BLE log", "Disconnected from device $deviceAddr")
}
else -> {
Log.i("BLE log", "Hit event $newState")
}
}
} else {
Log.e("BLE log", "BLE error $status for $deviceAddr")
}
}
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
super.onServicesDiscovered(gatt, status)
with(gatt) {
Log.i("BLE log","Discovered ${services.size} services for ${device.address}")
printGattTable()
enableNotification(gatt)
}
}
}
On the NRF Side i am sending data using a timer
static void txTimer_hander(void *p_context){
//TODO: Handle timeout
// SEND data to Device
//NRF_LOG_INFO("Timer : %d", tx_Data);
memset(val, 0, 7);
if(tx_Data < 50){
// SEND this Data
uint16_t now_data = tx_Data;
val[0] = 0xFF;
val[5] = now_data;
//memcpy(&val[0], (uint16_t*)0xFF, 1);
//memcpy(&val[6], &now_data, 2);
//val[0] = now_data;
//
tx_Data++;
}else{
tx_Data = 0;
// SEND this Data
uint16_t now_data = tx_Data;
//memcpy(&val[0], (uint16_t*)0xFF, 1);
val[0] = 0xFF;
val[5] = now_data;
//memcpy(&val[6], &now_data, 2);
//
tx_Data++;
}
NRF_LOG_INFO("Sending %d", tx_Data);
send_nus_data(val, 7);
}
NOTE I am using Android 12 and testing using Android Studio
I would appreciate any help!
Thanks
If your phone catches two advertisement packets, it will create two logical connections. You should check before you call connectGatt if you have already called connectGatt, and if so don't connect again. You should also stop the scan if you don't need the scan to continue when you have already found a device.
I have an application that sends and receives data using BLE. Originally it was classical bluetooth but I was tasked with changing the project to BLE.
So far I have succeeded in sending data but not receiving it. The main activity contains multiple fragments. On of those is responsible for sending data where as the other sends a request and then receives a response with the data from the BLE device.
one fragment is called Parameter and the other Memory. Each fragment has a viewmodel and repository as the architecture is based on MVVM. the flow is as follows:
Parameter fragment -> View model -> repository -> DataStore class -> DataStore uses instance from BLEConnectionManager class to send the data of the corresponding parameter. Example of a function in DataStore:
fun sendToolAddressParam(data: Int){
toolAddress = data
var value = Integer.toHexString(data)
if (value.length == 1) value = "0$value"
val message = WriteCommandCodes.TOOL_ADDRESS.value + " " + value + " " + WriteCommandCodes.EXTRA2.value
BleConnectionManager.sendMessage(message)
Timber.i("Payload: $message")
}
There are also functions that request data:
fun requestToolAddress(){
BleConnectionManager.requestReadValues(ReadRequestCodes.TOOL_ADDRESS.value)
}
in the BLE class the functions are written as the following:
fun write(message:String){
val bytes = BigInteger(message.replace("\\s".toRegex(), ""), 16).toByteArray()
Timber.i("Bytes value ---> ${bytes.toHexString()}")
val device = getBleDevice()
// val characteristicRX = getBleCharacteristic()
val characteristicRX = bluetoothGattRef.getService(XpressStreamingServiceUUID).getCharacteristic(
peripheralRX)
writeCharacteristic(device, characteristicRX, bytes)
}
fun requestReadValues(requestCode:String){
if(isConnected.value!!){
write(requestCode)
}else{
Timber.e("Make sure that you connected and paired with the desired device.")
}
}
fun sendMessage(message:String){
Timber.i("Check if isConnected = true --> ${isConnected.value}")
if(isConnected.value == true){
write(message)
}else{
Timber.e("Make sure that you connected and paired with the desired device.")
}
}
Now here is my issue I want to receive data from the BLE device after I send the request, the device's documentation when it comes to BLE data exchange is here: https://docs.silabs.com/gecko-os/1/bgx/latest/ble-services
Now I have a function that supposedly receives the incoming messages but this was when classical bluetooth was used.
fun readIncomingMessages(message: String){
when{
message.startsWith(com.brainsocket.milink.data.bluetooth.ReadResponseCodes.KEY_ADDRESS.value) ->{
EventBus.getDefault().post(
ReadKeyAddressEvent(message.substring(com.brainsocket.milink.data.bluetooth.ReadResponseCodes.KEY_ADDRESS.value.length+1, com.brainsocket.milink.data.bluetooth.ReadResponseCodes.KEY_ADDRESS.value.length+3))
)
Timber.i("Message received: $message")
}
message.startsWith(com.brainsocket.milink.data.bluetooth.ReadResponseCodes.TOOL_ADDRESS.value) ->{
EventBus.getDefault().post(
ReadToolAddressEvent(message.substring(com.brainsocket.milink.data.bluetooth.ReadResponseCodes.TOOL_ADDRESS.value.length+1, com.brainsocket.milink.data.bluetooth.ReadResponseCodes.TOOL_ADDRESS.value.length+3))
)
Timber.i("Message received: $message")}
message.startsWith(com.brainsocket.milink.data.bluetooth.ReadResponseCodes.RPM_THRESHOLD.value) ->{
EventBus.getDefault().post(
ReadRPMThresholdEvent(message.substring(com.brainsocket.milink.data.bluetooth.ReadResponseCodes.RPM_THRESHOLD.value.length+1, com.brainsocket.milink.data.bluetooth.ReadResponseCodes.RPM_THRESHOLD.value.length+3))
)
Timber.i("Message received: $message")}
message.startsWith(com.brainsocket.milink.data.bluetooth.ReadResponseCodes.BACKLASH.value) ->{
EventBus.getDefault().post(
ReadBacklashEvent(message.substring(com.brainsocket.milink.data.bluetooth.ReadResponseCodes.BACKLASH.value.length+1, com.brainsocket.milink.data.bluetooth.ReadResponseCodes.BACKLASH.value.length+6))
)
Timber.i("Message received: $message")}
As you can see the Event Bus is used here, it is also used here in the DataStore:
#Subscribe(threadMode = ThreadMode.MAIN)
fun onKeyAddressEvent(event: ReadKeyAddressEvent) {
Timber.i("onKeyAddressEvent: data:${event.data}")
keyAddress = Integer.parseInt(event.data , 16)
EventBus.getDefault().post(ReadMemoryItemsEvent())
}
#Subscribe(threadMode = ThreadMode.MAIN)
fun onToolAddressEvent(event: ReadToolAddressEvent) {
Log.d(LOG_TAG, "onToolAddressEvent: data:${event.data}")
when(Integer.parseInt(event.data , 16)){
0 -> toolAddress = 1
1 -> toolAddress = 2
}
EventBus.getDefault().post(ReadMemoryItemsEvent())
}
#Subscribe(threadMode = ThreadMode.MAIN)
fun onRPMThresholdEvent(event: ReadRPMThresholdEvent) {
Log.d(LOG_TAG, "onRPMThresholdEvent: data:${event.data}")
rpmThreshold = Integer.parseInt(event.data , 16)
EventBus.getDefault().post(ReadMemoryItemsEvent())
}
#Subscribe(threadMode = ThreadMode.MAIN)
fun onReadBacklashEvent(event: ReadBacklashEvent) {
Log.d(LOG_TAG, "onReadBacklashEvent: data:${event.data}")
val data = event.data
backlash = parseGotoPos(data)
EventBus.getDefault().post(ReadMemoryItemsEvent())
}
This is in the repository:
fun getMemoryItems() : List<ModesPosItem> = listOf(
ModesPosItem(value = btDataStore.keyAddress, title = context.getString(R.string.key_address_string)),
ModesPosItem(value = btDataStore.toolAddress, title = context.getString(R.string.tool_address_string)),
ModesPosItem(value = btDataStore.rpmThreshold, title = context.getString(R.string.rpm_threshold_string)),
ModesPosItem(value = btDataStore.backlash, title = context.getString(R.string.backlash_string))
)
This is in the viewmodel:
#Subscribe(threadMode = ThreadMode.MAIN)
fun onReadMemoryItemsEvent(event: ReadMemoryItemsEvent) {
memoryItems.value = repository.getMemoryItems()
Timber.i("Memory Items [tool address, keyAddress, RPM threshold, backlash]: ${memoryItems.value.toString()}")
}
This is in the fragment:
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onStop() {
EventBus.getDefault().unregister(this)
super.onStop()
}
What exactly am I supposed to do to acquire the data from the BLE device?
I made an app that write and read continous stream data throw BLE connection from a bluetooth device.
The Flow i follow is the following:
Connect Gatt;
Discover Services;
Write To Characteristic;
Subscribe to Notification;
Read Characteristic from notification --> Here the EventBus post() with your data package;
Going deeper into the connection and using some code:
After you connect to the GATT you call onConnectionStateChange to listen for changes in the gatt connection:
private val gattCallback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
val deviceAddress = gatt.device.address
if (status == BluetoothGatt.GATT_SUCCESS) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.w("BluetoothGattCallback", "Successfully connected to $deviceAddress")
// NOW DISCOVER SERVICES
gatt.discoverServices()
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.w("BluetoothGattCallback", "Successfully disconnected from $deviceAddress")
}
} else {
Log.w(
"BluetoothGattCallback",
"Error $status encountered for $deviceAddress! Disconnecting..."
)
}
If the GATT is connected succesfully it will discover services.
At this step you can write to the characteristic as follow:
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
with(gatt) {
Log.w(
"BluetoothGattCallback",
"Discovered ${services.size} services for ${device.address}"
)
val msg = byteArrayOf(0x00.toByte())
val newcharacteristic = gatt!!.getService(dataUUID_service).getCharacteristic(
dataUUID_characteristic
)
newcharacteristic!!.value = msg
gatt!!.writeCharacteristic(newcharacteristic)
}
}
This will let you go on the next step, the onCharacteristicWrite listener:
override fun onCharacteristicWrite(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
status: Int
) {
val characteristic = gatt.getService(dataUUID_service).getCharacteristic(
dataUUID_characteristic
)
gatt.setCharacteristicNotification(characteristic, true)
val descriptor = characteristic!!.getDescriptor(descriptor_UUID)
descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
if (descriptor != null) {
descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
gatt.writeDescriptor(descriptor)
}
}
Writing the characteristic will let you go into the onCharacteristicChanged listener that will give you back the data from the ble device and in which you can use the event bus to use your data.
override fun onCharacteristicChanged(
gatt: BluetoothGatt,
charac: BluetoothGattCharacteristic
) {
super.onCharacteristicChanged(gatt, charac)
// Log.d("CHARAC", "Characteristic Changed")
onCharacteristicRead(gatt, charac, BluetoothGatt.GATT_SUCCESS)
}
Where onCharacteristicRead should look like:
override fun onCharacteristicRead(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
status: Int
) {
with(characteristic) {
when (status) {
BluetoothGatt.GATT_SUCCESS -> {
Log.i("BluetoothGattCallback","Read characteristic $uuid:\n${value.toHexString()}" )
// value is the read value from ble device
// HERE YOU HANDE YOUR EVENT BUS, example:
val eventData: deviceListener = deviceListener(value)
EventBus.getDefault().post(eventData)
}
BluetoothGatt.GATT_READ_NOT_PERMITTED -> {
Log.e("BluetoothGattCallback", "Read not permitted for $uuid!")
}
else -> {
Log.e(
"BluetoothGattCallback",
"Characteristic read failed for $uuid, error: $status"
)
}
}
}
}
Maybe it is not the most efficent way and not the clearest code but it works like a charm.
I notice that if i write fast and continuously a characteristic value the gatt server disconnect.
I know that I have to wait until onCharacteristicWrite callback, so that's not the problem I think.
This my queue implementation, I'm using a kotlin Channel to syncronize write and read.
private var continuation: CancellableContinuation<BluetoothGattCharacteristic>? = null
private val channel = Channel<WriteOp>(1)
private suspend fun processBluetoothWrite() {
do {
val writeOp = channel.receiveOrNull()
writeOp?.apply {
try {
suspendCancellableCoroutine<BluetoothGattCharacteristic> { cont ->
continuation = cont
characteristic.value = writeOp?.value
Log.d(TAG, "Write to ${characteristic?.uuid} value ${writeOp?.value?.toHexString()}...")
if (gatt?.writeCharacteristic(characteristic) == false) {
cont.resumeWithException(Exception("Write to ${characteristic?.uuid} fails."))
}
}
} catch (ex: Exception) {
Log.e(TAG, ex.message, ex)
}
}
} while (writeOp != null)
}
override fun onCharacteristicWrite(
gatt: BluetoothGatt?,
characteristic: BluetoothGattCharacteristic?,
status: Int
) {
Log.d(TAG, "Write to ${characteristic?.uuid} value ${characteristic?.value?.toHexString()} | ${status}")
characteristic?.apply {
if (status == BluetoothGatt.GATT_SUCCESS) {
continuation?.resume(this)
} else {
continuation?.resumeWithException(Exception("Write to ${characteristic?.uuid} value ${characteristic?.value?.toHexString()} | ${status}"))
}
}
}
I need to add a delay of about 100ms in the queue processing to avoid disconnection.
UPDATE
After setting writeType as default, it seems that onCharacteristicWrite is more realistic (I used to get GATT_SUCCESS even when the device stopped communicating, so I guess it was a "virtual" state), now when the device stopped communicating it didn't get the onCharacteristicWrite callback, though after a while it is fired with status = 133.
characteristic.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
What does it mean?
I am working with BLE enabled hardware and communicating with the hardware using Foreground Service of the Android.
Foreground service is responsible for handling the BLE related events and it works quite good as per requirements for a while but somehow if the Foreground service is got killed or BLE connection is broken due to any reason then app tries to reconnect to the BLE again and then BLE callbacks start getting duplicate events from the BluetoothGattCallback, that is even though hardware sends a single event to Bluetooth but Android BluetoothGattCallback receives multiple callbacks for the same which leads to a lot of errors in our implementations.
For reference please go through Logs as follows,
Following are methods and callbacks from my foreground service,
BLEManagerService: *****onDescriptorWrite: 0*****<br>
BLEManagerService: *****onDescriptorWrite: 0*****<br>
BLEManagerService: *****onDescriptorWrite: 0*****<br>
BLEManagerService: Firmware: onCharacteristicRead true<br>
BLEManagerService: *****onDescriptorWrite: 0*****<br>
BLEManagerService: Firmware: onCharacteristicRead true<br>
BLEManagerService: *****onCharacteristicRead: 0*****<br>
BLEManagerService: *****onCharacteristicRead: 0*****<br>
override fun onCreate() {
super.onCreate()
mBluetoothGatt?.let { refreshDeviceCache(it) }
registerReceiver(btStateBroadcastReceiver, IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED))
}
/**
* Start BLE scan
*/
private fun scanLeDevice(enable: Boolean) {
if (enable && bleConnectionState == DISCONNECTED) {
//initialize scanning BLE
startScan()
scanTimer = scanTimer()
} else {
stopScan("scanLeDevice: (Enable: $enable)")
}
}
private fun scanTimer(): CountDownTimer {
return object : CountDownTimer(SCAN_PERIOD, 1000) {
override fun onTick(millisUntilFinished: Long) {
//Nothing to do
}
override fun onFinish() {
if (SCAN_PERIOD > 10000 && bleConnectionState == DISCONNECTED) {
stopScan("restart scanTimer")
Thread.sleep(200)
scanLeDevice(true)
SCAN_PERIOD -= 5000
if (null != scanTimer) {
scanTimer!!.cancel()
scanTimer = null
}
scanTimer = scanTimer()
} else {
stopScan("stop scanTimer")
SCAN_PERIOD = 60000
}
}
}
}
//Scan callbacks for more that LOLLIPOP versions
private val mScanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
val btDevice = result.device
if (null != btDevice) {
val scannedDeviceName: String? = btDevice.name
scannedDeviceName?.let {
if (it == mBluetoothFemurDeviceName) {
stopScan("ScanCallback: Found device")
//Disconnect from current connection if any
mBluetoothGatt?.let {it1 ->
it1.close()
mBluetoothGatt = null
}
connectToDevice(btDevice)
}
}
}
}
override fun onBatchScanResults(results: List<ScanResult>) {
//Not Required
}
override fun onScanFailed(errorCode: Int) {
Log.e(TAG, "*****onScanFailed->Error Code: $errorCode*****")
}
}
/**
* Connect to BLE device
* #param device
*/
fun connectToDevice(device: BluetoothDevice) {
scanLeDevice(false)// will stop after first device detection
//Stop Scanning before connect attempt
try {
if (null != scanTimer) {
scanTimer!!.cancel()
}
} catch (e: Exception) {
//Just handle exception if something
// goes wrong while canceling the scan timer
}
//Stop scan if still BLE scanner is running
stopScan("connectToDevice")
if (mBluetoothGatt == null) {
connectedDevice = device
if (Build.VERSION.SDK_INT >= 26)
connectedDevice?.connectGatt(this, false, mGattCallback)
}else{
disconnectDevice()
connectedDevice = device
connectedDevice?.connectGatt(this, false, mGattCallback)
}
}
/**
* Disconnect from BLE device
*/
private fun disconnectDevice() {
mBluetoothGatt?.close()
mBluetoothGatt = null
bleConnectionState = DISCONNECTED
mBluetoothManager = null
mBluetoothAdapter = null
mBluetoothFemurDeviceName = null
mBluetoothTibiaDeviceName = null
connectedDevice = null
}
/****************************************
* BLE Related Callbacks starts *
* Implements callback methods for GATT *
****************************************/
// Implements callback methods for GATT events that the app cares about. For example,
// connection change and services discovered.
private val mGattCallback = object : BluetoothGattCallback() {
/**
* Connection state changed callback
*/
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
mBluetoothGatt = gatt
//Stop Scanning before connect attempt
try {
if (null != scanTimer) {
scanTimer!!.cancel()
}
} catch (e: Exception) {
//Just handle exception if something
// goes wrong while canceling the scan timer
}
stopScan("onConnectionStateChange")// will stop after first device detection
} else if (newState == BluetoothProfile.STATE_DISCONNECTED || status == 8) {
disconnectDevice()
Handler(Looper.getMainLooper()).postDelayed({
initialize()
}, 500)
}
}
/**
* On services discovered
* #param gatt
* #param status
*/
override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
super.onServicesDiscovered(gatt, status)
}
override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
super.onDescriptorWrite(gatt, descriptor, status)
}
/**
* On characteristic read operation complete
* #param gatt
* #param characteristic
* #param status
*/
override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
super.onCharacteristicRead(gatt, characteristic, status)
}
/**
* On characteristic write operation complete
* #param gatt
* #param characteristic
* #param status
*/
override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
super.onCharacteristicWrite(gatt, characteristic, status)
val data = characteristic.value
val dataHex = byteToHexStringJava(data)
}
/**
* On Notification/Data received from the characteristic
* #param gatt
* #param characteristic
*/
override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
super.onCharacteristicChanged(gatt, characteristic)
val data = characteristic.value
val dataHex = byteToHexStringJava(data)
}
override fun onReadRemoteRssi(gatt: BluetoothGatt, rssi: Int, status: Int) {
super.onReadRemoteRssi(gatt, rssi, status)
val b = Bundle()
b.putInt(BT_RSSI_VALUE_READ, rssi)
receiver?.send(APP_RESULT_CODE_BT_RSSI, b)
}
}
/**
* Bluetooth state receiver to handle the ON/OFF states
*/
private val btStateBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)
when (state) {
BluetoothAdapter.STATE_OFF -> {
//STATE OFF
}
BluetoothAdapter.STATE_ON -> {
//STATE ON
btState = BT_ON
val b = Bundle()
receiver?.send(APP_RESULT_CODE_BT_ON, b)
initialize()
}
BluetoothAdapter.STATE_TURNING_OFF -> {
//Not Required
}
BluetoothAdapter.STATE_TURNING_ON -> {
//Not Required
}
}
}
}
private fun handleBleDisconnectedState() {
mBluetoothGatt?.let {
it.close()
receiver?.send(DISCONNECTED, b)
Handler(Looper.getMainLooper()).postDelayed({
mBluetoothManager = null
mBluetoothAdapter = null
mBluetoothFemurDeviceName = null
mBluetoothTibiaDeviceName = null
mBluetoothGatt = null
}, 1000)
}
}
/****************************************
* BLE Related Callbacks End ***
****************************************/
/****************************************************
* Register Receivers to handle calbacks to UI ***
****************************************************/
override fun onDestroy() {
super.onDestroy()
try {
mBluetoothGatt?.let {
it.close()
mBluetoothGatt = null
}
unregisterReceivers()
scanTimer?.cancel()
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
Log.e(TAG, "onTaskRemoved")
stopSelf()
}
/**
* Unregister the receivers before destroying the service
*/
private fun unregisterReceivers() {
unregisterReceiver(btStateBroadcastReceiver)
}
companion object {
private val TAG = BLEManagerService::class.java.simpleName
private var mBluetoothGatt: BluetoothGatt? = null
var bleConnectionState: Int = DISCONNECTED
}
}
Don't set mBluetoothGatt = gatt in onConnectionStateChange. Instead set it from the return value of connectGatt. Otherwise you might create multiple BluetoothGatt objects without closing previous ones and therefore get multiple callbacks.