-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBluetoothConnectionManager.kt
387 lines (360 loc) · 15.6 KB
/
BluetoothConnectionManager.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package com.weatherxm.data.bluetooth
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.IntentFilter.SYSTEM_HIGH_PRIORITY
import android.os.Build
import arrow.core.Either
import com.juul.kable.BluetoothDisabledException
import com.juul.kable.Characteristic
import com.juul.kable.ConnectionLostException
import com.juul.kable.ConnectionRejectedException
import com.juul.kable.Descriptor
import com.juul.kable.GattRequestRejectedException
import com.juul.kable.GattStatusException
import com.juul.kable.GattWriteException
import com.juul.kable.NotConnectedException
import com.juul.kable.NotReadyException
import com.juul.kable.Peripheral
import com.juul.kable.peripheral
import com.weatherxm.data.BluetoothError
import com.weatherxm.data.Failure
import com.weatherxm.ui.common.empty
import com.weatherxm.ui.common.parcelable
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.cancellable
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.util.concurrent.TimeUnit
import kotlin.coroutines.coroutineContext
@Suppress("TooManyFunctions")
class BluetoothConnectionManager(
private val context: Context, private val bluetoothAdapter: BluetoothAdapter?
) {
companion object {
const val READ_CHARACTERISTIC_UUID = "49616"
const val WRITE_CHARACTERISTIC_UUID = "34729"
const val AT_CLAIMING_KEY_COMMAND = "AT+CLAIM_KEY=?\r\n"
const val AT_DEV_EUI_COMMAND = "AT+DEUI=?\r\n"
const val AT_SET_FREQUENCY_COMMAND = "AT+BAND="
const val AT_SET_INTERVAL_COMMAND = "AT+INTERVAL=3\r\n"
const val AT_REBOOT_COMMAND = "ATZ\r\n"
val DELAY_BEFORE_CHARACTERISTICS_SETUP = TimeUnit.SECONDS.toMillis(1L)
}
private lateinit var bondStateChangedReceiver: BroadcastReceiver
private lateinit var peripheral: Peripheral
private var macAddress: String = String.empty()
private var readCharacteristic: Characteristic? = null
private var writeCharacteristic: Characteristic? = null
private var isSettingCharacteristics: Boolean = false
private val bondStateChangedFilter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
private val bondStatus = MutableSharedFlow<Int>(
replay = 1, onBufferOverflow = BufferOverflow.DROP_LATEST
)
@OptIn(ExperimentalCoroutinesApi::class)
fun onBondStatus(): Flow<Int> {
bondStatus.resetReplayCache()
return bondStatus
}
/**
* Suppress MissingPermission as we will call this function only after we have it granted
*/
@SuppressLint("MissingPermission")
fun getPairedDevices(): List<BluetoothDevice> {
return bluetoothAdapter?.bondedDevices?.filter {
it?.name != null && it.name.contains("WeatherXM")
} ?: mutableListOf()
}
/*
* This broadcast receiver is a necessity in order to know when our device is BONDED and we can
* start communicating with it and working on its data
*/
private fun initBondStateChangeReceiver(scope: CoroutineScope) {
bondStateChangedReceiver = object : BroadcastReceiver() {
@SuppressLint("MissingPermission")
override fun onReceive(context: Context?, intent: Intent) {
if (intent.action == BluetoothDevice.ACTION_BOND_STATE_CHANGED) {
val bluetoothDevice =
intent.parcelable<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
when (bluetoothDevice?.bondState) {
BluetoothDevice.BOND_BONDED -> {
Timber.d("[BLE Communication]: Bonded.")
tryToSetCharacteristics(scope)
bondStatus.tryEmit(BluetoothDevice.BOND_BONDED)
}
BluetoothDevice.BOND_BONDING -> {
Timber.d("[BLE Communication]: Bonding...")
bondStatus.tryEmit(BluetoothDevice.BOND_BONDING)
}
BluetoothDevice.BOND_NONE -> {
Timber.d("[BLE Communication]: Bonding NONE...")
bondStatus.tryEmit(BluetoothDevice.BOND_NONE)
}
}
}
}
}
}
suspend fun setPeripheral(address: String): Either<Failure, Unit> {
return try {
macAddress = address
initBondStateChangeReceiver(CoroutineScope(coroutineContext))
peripheral = CoroutineScope(coroutineContext).peripheral(address)
Either.Right(Unit)
} catch (e: IllegalArgumentException) {
Timber.w(e, "Creation of peripheral failed: $address")
Either.Left(BluetoothError.PeripheralCreationError())
}
}
private fun tryToSetCharacteristics(scope: CoroutineScope) {
scope.launch {
isSettingCharacteristics = true
delay(DELAY_BEFORE_CHARACTERISTICS_SETUP)
setReadWriteCharacteristic()
}
}
fun getPeripheral(): Peripheral {
return peripheral
}
suspend fun disconnectFromPeripheral() {
try {
Timber.d("[BLE Communication]: Disconnecting from peripheral...")
readCharacteristic = null
writeCharacteristic = null
peripheral.disconnect()
} catch (e: UninitializedPropertyAccessException) {
Timber.d(e, "Could not disconnect peripheral.")
} catch (e: NotConnectedException) {
Timber.d(e, "Could not disconnect peripheral.")
} catch (e: ConnectionLostException) {
Timber.d(e, "Could not disconnect peripheral.")
}
}
/**
* Suppress MissingPermission as we will call this function only after we have it granted
*/
@SuppressLint("MissingPermission")
suspend fun connectToPeripheral(): Either<Failure, Unit> {
return try {
/*
* Register the receivers BEFORE trying to connect
*/
Timber.d("[BLE Communication]: Connecting to peripheral...")
bondStateChangedFilter.priority = SYSTEM_HIGH_PRIORITY
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.registerReceiver(
bondStateChangedReceiver, bondStateChangedFilter, Context.RECEIVER_EXPORTED
)
} else {
context.registerReceiver(bondStateChangedReceiver, bondStateChangedFilter)
}
peripheral.connect()
if (getPairedDevices().any { it.address == macAddress }) {
tryToSetCharacteristics(CoroutineScope(coroutineContext))
}
Either.Right(Unit)
} catch (e: ConnectionRejectedException) {
Timber.w(e, "Connection to peripheral failed with ConnectionRejectedException")
Either.Left(BluetoothError.ConnectionRejectedError())
} catch (e: CancellationException) {
Timber.w(e, "Connection to peripheral failed with CancellationException")
Either.Left(BluetoothError.CancellationError())
} catch (e: BluetoothDisabledException) {
Timber.w(e, "Connection to peripheral failed with BluetoothDisabledException")
Either.Left(BluetoothError.BluetoothDisabledException())
} catch (e: ConnectionLostException) {
Timber.w(e, "Connection to peripheral failed with ConnectionLostException")
Either.Left(BluetoothError.ConnectionLostException())
} catch (e: GattRequestRejectedException) {
Timber.w(e, "Connection to peripheral failed with GattRequestRejectedException")
Either.Left(BluetoothError.GattRequestRejectedException())
} catch (e: GattStatusException) {
Timber.w(e, "[enable descriptor notification] failed: GattStatusException")
Either.Left(BluetoothError.GattRequestRejectedException())
}
}
private suspend fun setReadWriteCharacteristic() {
if (readCharacteristic != null && writeCharacteristic != null) {
isSettingCharacteristics = false
return
}
Timber.d("[BLE Communication]: Setting read & write characteristics...")
peripheral.services?.forEach { service ->
service.characteristics.forEach {
if (it.characteristicUuid.toString().contains(WRITE_CHARACTERISTIC_UUID)) {
writeCharacteristic = it
} else if (it.characteristicUuid.toString().contains(READ_CHARACTERISTIC_UUID)) {
enableDescriptorNotification(it.descriptors[0])
readCharacteristic = it
}
}
}
isSettingCharacteristics = false
/**
* When we get here it means that we are at the equivalent of BLE `onConnected`
* so we need to run this to set the interval of the weather station.
*/
setInterval()
}
private suspend fun enableDescriptorNotification(descriptor: Descriptor) {
try {
peripheral.write(descriptor, ENABLE_NOTIFICATION_VALUE)
} catch (e: GattWriteException) {
Timber.w(
e,
"[enable descriptor notification]: " +
"GattWriteException - Result: ${e.result}, Name: ${e.result.name}"
)
} catch (e: GattRequestRejectedException) {
Timber.w(e, "[enable descriptor notification]: GattRequestRejectedException")
} catch (e: ConnectionLostException) {
Timber.w(e, "[enable descriptor notification]: ConnectionLostException")
} catch (e: NotReadyException) {
Timber.w(e, "[enable descriptor notification]: NotReadyException")
} catch (e: GattStatusException) {
Timber.w(e, "[enable descriptor notification]: GattStatusException")
}
}
private suspend fun setInterval() {
setATCommand(AT_SET_INTERVAL_COMMAND) {
it.onRight {
Timber.d("[BLE Communication] Set Interval success")
}.onLeft { failure ->
Timber.e("[BLE Communication] ERROR: At set interval $failure")
}
}
}
suspend fun write(command: String): Boolean {
if (isSettingCharacteristics) {
/**
* If we are still in the process of setting characteristics, delay a bit
* to ensure they are correctly set
*/
delay(DELAY_BEFORE_CHARACTERISTICS_SETUP * 2)
}
Timber.d("[BLE Communication]: $command")
return writeCharacteristic?.let {
try {
peripheral.write(it, command.toByteArray())
true
} catch (e: GattWriteException) {
Timber.w(
e,
"[$command]: GattWriteException - Result: ${e.result}, Name: ${e.result.name}"
)
false
} catch (e: GattRequestRejectedException) {
Timber.w(e, "[$command] failed: GattRequestRejectedException")
false
} catch (e: ConnectionLostException) {
Timber.w(e, "[$command] failed: ConnectionLostException")
false
} catch (e: GattStatusException) {
Timber.w(e, "[$command] failed: GattStatusException")
false
} catch (e: NotReadyException) {
Timber.w(e, "[$command] failed: NotReadyException")
false
}
} ?: false
}
suspend fun fetchATCommand(command: String, listener: (Either<Failure, String>) -> Unit) {
if (!write(command)) {
listener.invoke(Either.Left(BluetoothError.ConnectionRejectedError()))
return
}
readCharacteristic?.let { characteristic ->
var failed = false
var fullResponse = String.empty()
peripheral.observe(characteristic).takeWhile {
val currentResponse =
String(it).replace("\r", String.empty()).replace("\n", String.empty())
Timber.d("[BLE Communication] Response: $currentResponse")
if (currentResponse.contains("ERROR")) {
Timber.e("[BLE Communication] ERROR: $currentResponse")
failed = true
return@takeWhile false
}
currentResponse != "OK"
}.onCompletion {
Timber.d("[BLE Communication] Full Response: $fullResponse")
if (failed) {
listener.invoke(Either.Left(BluetoothError.ATCommandError()))
} else {
listener.invoke(Either.Right(fullResponse))
}
}.collect {
fullResponse += String(it).replace("'", String.empty())
}
}
}
suspend fun setATCommand(command: String, listener: (Either<Failure, Unit>) -> Unit) {
if (!write(command)) {
listener.invoke(Either.Left(BluetoothError.ConnectionRejectedError()))
return
}
readCharacteristic?.let { characteristic ->
var isSuccess = false
peripheral.observe(characteristic).cancellable().takeWhile {
val currentResponse =
String(it).replace("\r", String.empty()).replace("\n", String.empty())
if (currentResponse.contains("ERROR")) {
Timber.e("[BLE Communication] ERROR: $currentResponse")
isSuccess = false
return@takeWhile false
} else if (currentResponse == "OK") {
isSuccess = true
return@takeWhile false
}
true
}.onCompletion {
Timber.d("[BLE Communication]: Success: $isSuccess")
if (isSuccess) {
listener.invoke(Either.Right(Unit))
} else {
listener.invoke(Either.Left(BluetoothError.ATCommandError()))
}
}.catch {
Timber.e(it)
listener.invoke(Either.Left(BluetoothError.ATCommandError()))
}.collect()
}
}
suspend fun reboot(command: String, listener: (Either<Failure, Unit>) -> Unit) {
if (!write(command)) {
listener.invoke(Either.Left(BluetoothError.ConnectionRejectedError()))
return
}
readCharacteristic?.let { characteristic ->
coroutineScope {
// TODO: Reboot command doesn't seem to do something.
val job = launch {
peripheral.observe(characteristic).cancellable().collect()
}
withContext(coroutineContext) {
if (command == AT_REBOOT_COMMAND) {
job.cancel()
listener.invoke(Either.Right(Unit))
}
}
}
}
}
}