Skip to content

Commit 6937444

Browse files
committed
Support creating Peripheral from Identifier
1 parent ac964a9 commit 6937444

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

kable-core/src/jsMain/kotlin/Peripheral.kt

+32
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
package com.juul.kable
22

33
import com.juul.kable.external.BluetoothDevice
4+
import js.errors.JsError
5+
import kotlinx.coroutines.await
6+
import kotlinx.coroutines.ensureActive
7+
import web.errors.DOMException
8+
import web.errors.DOMException.Companion.SecurityError
9+
import kotlin.coroutines.coroutineContext
410

511
public actual fun Peripheral(
612
advertisement: Advertisement,
@@ -10,6 +16,32 @@ public actual fun Peripheral(
1016
return Peripheral(advertisement.bluetoothDevice, builderAction)
1117
}
1218

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+
1345
@Suppress("FunctionName") // Builder function.
1446
internal fun Peripheral(
1547
bluetoothDevice: BluetoothDevice,

kable-core/src/jsMain/kotlin/external/Bluetooth.kt

+1
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ internal abstract external class Bluetooth : EventTarget {
88
fun getAvailability(): Promise<Boolean>
99
fun requestDevice(options: RequestDeviceOptions): Promise<BluetoothDevice>
1010
fun requestLEScan(options: BluetoothLEScanOptions): Promise<BluetoothScan>
11+
fun getDevices(): Promise<Array<BluetoothDevice>>
1112
}

0 commit comments

Comments
 (0)