-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathPeripheral.kt
379 lines (325 loc) · 13.8 KB
/
Peripheral.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
package com.juul.kable
import android.bluetooth.BluetoothAdapter.STATE_OFF
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic.PROPERTY_INDICATE
import android.bluetooth.BluetoothGattCharacteristic.PROPERTY_NOTIFY
import android.bluetooth.BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
import android.bluetooth.BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE
import android.bluetooth.BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
import android.bluetooth.BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
import android.util.Log
import com.benasher44.uuid.uuidFrom
import com.juul.kable.WriteType.WithResponse
import com.juul.kable.WriteType.WithoutResponse
import com.juul.kable.external.CLIENT_CHARACTERISTIC_CONFIG_UUID
import com.juul.kable.gatt.Response.OnCharacteristicRead
import com.juul.kable.gatt.Response.OnCharacteristicWrite
import com.juul.kable.gatt.Response.OnDescriptorRead
import com.juul.kable.gatt.Response.OnDescriptorWrite
import com.juul.kable.gatt.Response.OnMtuChanged
import com.juul.kable.gatt.Response.OnReadRemoteRssi
import com.juul.kable.gatt.Response.OnServicesDiscovered
import kotlinx.atomicfu.atomic
import kotlinx.atomicfu.updateAndGet
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart.LAZY
import kotlinx.coroutines.CoroutineStart.UNDISPATCHED
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.onEach
import kotlin.coroutines.CoroutineContext
private val clientCharacteristicConfigUuid = uuidFrom(CLIENT_CHARACTERISTIC_CONFIG_UUID)
@Deprecated(
message = "'writeObserveDescriptor' parameter is no longer used and is handled automatically by 'observe' function. 'writeObserveDescriptor' argument will be removed in a future release.",
replaceWith = ReplaceWith("peripheral(advertisement)"),
level = DeprecationLevel.ERROR,
)
public fun CoroutineScope.peripheral(
bluetoothDevice: BluetoothDevice,
writeObserveDescriptor: WriteNotificationDescriptor,
): Peripheral = throw UnsupportedOperationException()
@Deprecated(
message = "'writeObserveDescriptor' parameter is no longer used and is handled automatically by 'observe' function. 'writeObserveDescriptor' argument will be removed in a future release.",
replaceWith = ReplaceWith("peripheral(advertisement)"),
level = DeprecationLevel.ERROR,
)
public fun CoroutineScope.peripheral(
advertisement: Advertisement,
writeObserveDescriptor: WriteNotificationDescriptor,
): Peripheral = throw UnsupportedOperationException()
/**
* @param transport preferred transport for GATT connections to remote dual-mode devices.
* @param phy preferred PHY for connections to remote LE device.
*/
@Deprecated(message = "Use builder lambda.")
public fun CoroutineScope.peripheral(
advertisement: Advertisement,
transport: Transport,
phy: Phy = Phy.Le1M,
): Peripheral = peripheral(advertisement) {
this.transport = transport
this.phy = phy
}
/**
* @param transport preferred transport for GATT connections to remote dual-mode devices.
* @param phy preferred PHY for connections to remote LE device.
*/
@Deprecated(message = "Use builder lambda.")
public fun CoroutineScope.peripheral(
bluetoothDevice: BluetoothDevice,
transport: Transport,
phy: Phy = Phy.Le1M,
): Peripheral = peripheral(bluetoothDevice) {
this.transport = transport
this.phy = phy
}
public actual fun CoroutineScope.peripheral(
advertisement: Advertisement,
builderAction: PeripheralBuilderAction,
): Peripheral = peripheral(advertisement.bluetoothDevice, builderAction)
public fun CoroutineScope.peripheral(
bluetoothDevice: BluetoothDevice,
builderAction: PeripheralBuilderAction = {},
): Peripheral {
val builder = PeripheralBuilder()
builder.builderAction()
return AndroidPeripheral(coroutineContext, bluetoothDevice, builder.transport, builder.phy, builder.onServicesDiscovered)
}
public enum class Priority { Low, Balanced, High }
public class AndroidPeripheral internal constructor(
parentCoroutineContext: CoroutineContext,
private val bluetoothDevice: BluetoothDevice,
private val transport: Transport,
private val phy: Phy,
private val onServicesDiscovered: ServicesDiscoveredAction,
) : Peripheral {
private val receiver = registerBluetoothStateBroadcastReceiver { state ->
if (state == STATE_OFF) {
closeConnection()
_state.value = State.Disconnected()
}
}
private val job = SupervisorJob(parentCoroutineContext[Job]).apply {
invokeOnCompletion {
applicationContext.unregisterReceiver(receiver)
closeConnection()
}
}
private val scope = CoroutineScope(parentCoroutineContext + job)
private val _state = MutableStateFlow<State>(State.Disconnected())
public override val state: Flow<State> = _state.asStateFlow()
private val observers = Observers(this)
@Volatile
private var _platformServices: List<PlatformService>? = null
private val platformServices: List<PlatformService>
get() = checkNotNull(_platformServices) { "Services have not been discovered for $this" }
public override val services: List<DiscoveredService>?
get() = _platformServices?.map { it.toDiscoveredService() }
@Volatile
private var _connection: Connection? = null
private val connection: Connection
inline get() = _connection ?: throw NotReadyException(toString())
private val connectJob = atomic<Deferred<Unit>?>(null)
private val ready = MutableStateFlow(false)
internal suspend fun suspendUntilReady() {
// fast path
if (ready.value && _state.value == State.Connected) return
// slow path
combine(ready, state) { ready, state -> ready && state == State.Connected }.first { it }
}
private fun establishConnection(): Connection =
bluetoothDevice.connect(
applicationContext,
transport,
phy,
_state,
invokeOnClose = { connectJob.value = null }
) ?: throw ConnectionRejectedException()
/** Creates a connect [Job] that completes when connection is established, or failure occurs. */
private fun connectAsync() = scope.async(start = LAZY) {
ready.value = false
val connection = establishConnection().also { _connection = it }
connection
.characteristicChanges
.onEach(observers.characteristicChanges::emit)
.launchIn(scope, start = UNDISPATCHED)
try {
suspendUntilConnected()
discoverServices()
onServicesDiscovered(ServicesDiscoveredPeripheral(this@AndroidPeripheral))
observers.rewire()
} catch (t: Throwable) {
closeConnection()
throw t
}
ready.value = true
}
private fun closeConnection() {
_connection?.close()
_connection = null
}
public override suspend fun connect() {
check(job.isNotCancelled) { "Cannot connect, scope is cancelled for $this" }
connectJob.updateAndGet { it ?: connectAsync() }!!.await()
}
public override suspend fun disconnect() {
try {
_connection?.apply {
bluetoothGatt.disconnect()
suspendUntilDisconnected()
}
} finally {
closeConnection()
}
}
public fun requestConnectionPriority(priority: Priority): Boolean =
connection.bluetoothGatt.requestConnectionPriority(priority.intValue)
public override suspend fun rssi(): Int = connection.execute<OnReadRemoteRssi> {
readRemoteRssi()
}.rssi
private suspend fun discoverServices() {
connection.execute<OnServicesDiscovered> {
discoverServices()
}
_platformServices = connection.bluetoothGatt
.services
.map { it.toPlatformService() }
}
/** @throws NotReadyException if invoked without an established [connection][Peripheral.connect]. */
public suspend fun requestMtu(mtu: Int) {
connection.execute<OnMtuChanged> {
this@execute.requestMtu(mtu)
}
}
public override suspend fun write(
characteristic: Characteristic,
data: ByteArray,
writeType: WriteType,
) {
val bluetoothGattCharacteristic = bluetoothGattCharacteristicFrom(characteristic)
connection.execute<OnCharacteristicWrite> {
bluetoothGattCharacteristic.value = data
bluetoothGattCharacteristic.writeType = writeType.intValue
writeCharacteristic(bluetoothGattCharacteristic)
}
}
public override suspend fun read(
characteristic: Characteristic,
): ByteArray {
val bluetoothGattCharacteristic = bluetoothGattCharacteristicFrom(characteristic)
return connection.execute<OnCharacteristicRead> {
readCharacteristic(bluetoothGattCharacteristic)
}.value!!
}
public override suspend fun write(
descriptor: Descriptor,
data: ByteArray,
) {
write(bluetoothGattDescriptorFrom(descriptor), data)
}
private suspend fun write(
bluetoothGattDescriptor: BluetoothGattDescriptor,
data: ByteArray,
) {
connection.execute<OnDescriptorWrite> {
bluetoothGattDescriptor.value = data
writeDescriptor(bluetoothGattDescriptor)
}
}
public override suspend fun read(
descriptor: Descriptor,
): ByteArray {
val bluetoothGattDescriptor = bluetoothGattDescriptorFrom(descriptor)
return connection.execute<OnDescriptorRead> {
readDescriptor(bluetoothGattDescriptor)
}.value!!
}
public override fun observe(
characteristic: Characteristic,
onSubscription: OnSubscriptionAction,
): Flow<ByteArray> = observers.acquire(characteristic, onSubscription)
internal suspend fun startObservation(characteristic: Characteristic) {
val platformCharacteristic = platformServices.findCharacteristic(characteristic)
connection
.bluetoothGatt
.setCharacteristicNotification(platformCharacteristic, true)
setConfigDescriptor(platformCharacteristic, enable = true)
}
internal suspend fun stopObservation(characteristic: Characteristic) {
val platformCharacteristic = platformServices.findCharacteristic(characteristic)
try {
setConfigDescriptor(platformCharacteristic, enable = false)
} finally {
connection
.bluetoothGatt
.setCharacteristicNotification(platformCharacteristic, false)
}
}
private suspend fun setConfigDescriptor(
characteristic: PlatformCharacteristic,
enable: Boolean,
) {
val configDescriptor = characteristic.configDescriptor
if (configDescriptor != null) {
val bluetoothGattDescriptor = configDescriptor.bluetoothGattDescriptor
if (enable) {
when {
characteristic.supportsNotify -> write(bluetoothGattDescriptor, ENABLE_NOTIFICATION_VALUE)
characteristic.supportsIndicate -> write(bluetoothGattDescriptor, ENABLE_INDICATION_VALUE)
else -> Log.w(TAG, "Characteristic ${characteristic.characteristicUuid} supports neither notification nor indication")
}
} else {
if (characteristic.supportsNotify || characteristic.supportsIndicate)
write(bluetoothGattDescriptor, DISABLE_NOTIFICATION_VALUE)
}
} else {
Log.w(TAG, "Characteristic ${characteristic.characteristicUuid} is missing config descriptor.")
}
}
private fun bluetoothGattCharacteristicFrom(
characteristic: Characteristic
) = platformServices.findCharacteristic(characteristic).bluetoothGattCharacteristic
private fun bluetoothGattDescriptorFrom(
descriptor: Descriptor
) = platformServices.findDescriptor(descriptor).bluetoothGattDescriptor
override fun toString(): String = "Peripheral(bluetoothDevice=$bluetoothDevice)"
}
private suspend fun Peripheral.suspendUntilConnected() {
state
.onEach { if (it is State.Disconnected) throw ConnectionLostException() }
.first { it == State.Connected }
}
private suspend fun Peripheral.suspendUntilDisconnected() {
state.first { it is State.Disconnected }
}
private val WriteType.intValue: Int
get() = when (this) {
WithResponse -> WRITE_TYPE_DEFAULT
WithoutResponse -> WRITE_TYPE_NO_RESPONSE
}
private val Priority.intValue: Int
get() = when (this) {
Priority.Low -> BluetoothGatt.CONNECTION_PRIORITY_LOW_POWER
Priority.Balanced -> BluetoothGatt.CONNECTION_PRIORITY_BALANCED
Priority.High -> BluetoothGatt.CONNECTION_PRIORITY_HIGH
}
private fun BluetoothGatt.setCharacteristicNotification(
characteristic: PlatformCharacteristic,
enable: Boolean,
) = setCharacteristicNotification(characteristic.bluetoothGattCharacteristic, enable)
private val PlatformCharacteristic.configDescriptor: PlatformDescriptor?
get() = descriptors.firstOrNull(clientCharacteristicConfigUuid)
private val PlatformCharacteristic.supportsNotify: Boolean
get() = bluetoothGattCharacteristic.properties and PROPERTY_NOTIFY != 0
private val PlatformCharacteristic.supportsIndicate: Boolean
get() = bluetoothGattCharacteristic.properties and PROPERTY_INDICATE != 0