1
1
package com.juul.kable
2
2
3
3
import com.juul.kable.external.BluetoothDevice
4
+ import js.errors.JsError
5
+ import kotlin.coroutines.coroutineContext
6
+ import kotlinx.coroutines.await
7
+ import kotlinx.coroutines.ensureActive
8
+ import web.errors.DOMException
9
+ import web.errors.DOMException.Companion.SecurityError
4
10
5
11
public actual fun Peripheral (
6
12
advertisement : Advertisement ,
@@ -10,6 +16,32 @@ public actual fun Peripheral(
10
16
return Peripheral (advertisement.bluetoothDevice, builderAction)
11
17
}
12
18
19
+ @Suppress(" FunctionName" ) // Builder function.
20
+ public suspend fun Peripheral (
21
+ identifier : Identifier ,
22
+ builderAction : PeripheralBuilderAction ,
23
+ ): WebBluetoothPeripheral ? {
24
+ val bluetooth = bluetoothOrThrow()
25
+ val devices = try {
26
+ bluetooth.getDevices().await()
27
+ } catch (e: JsError ) {
28
+ coroutineContext.ensureActive()
29
+ throw when {
30
+ // The Web Bluetooth API can only be used in a secure context.
31
+ // https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API#security_considerations
32
+ e is DOMException && e.name == SecurityError ->
33
+ IllegalStateException (" Operation is not permitted in this context due to security concerns" , e)
34
+
35
+ else -> InternalError (" Failed to invoke getDevices request" , e)
36
+ }
37
+ }
38
+ return devices.singleOrNull { bluetoothDevice ->
39
+ bluetoothDevice.id == identifier
40
+ }?.let { bluetoothDevice ->
41
+ Peripheral (bluetoothDevice, builderAction)
42
+ }
43
+ }
44
+
13
45
@Suppress(" FunctionName" ) // Builder function.
14
46
internal fun Peripheral (
15
47
bluetoothDevice : BluetoothDevice ,
0 commit comments