11package com.juul.kable
22
3+ import com.juul.kable.Options.Filter.Name
4+ import com.juul.kable.Options.Filter.NamePrefix
5+ import com.juul.kable.Options.Filter.Services
36import com.juul.kable.external.Bluetooth
7+ import kotlinext.js.jsObject
48import kotlinx.coroutines.CoroutineScope
59import kotlin.js.Promise
610
@@ -14,14 +18,40 @@ public fun CoroutineScope.requestPeripheral(
1418 .requestDevice(options.toDynamic())
1519 .then { device -> peripheral(device, builderAction) }
1620
21+ /* *
22+ * Converts [Options] to JavaScript friendly object.
23+ *
24+ * According to the `requestDevice`
25+ * [example](https://developer.mozilla.org/en-US/docs/Web/API/Bluetooth/requestDevice#example), the form of the
26+ * JavaScript object should be similar to:
27+ * ```
28+ * let options = {
29+ * filters: [
30+ * {services: ['heart_rate']},
31+ * {services: [0x1802, 0x1803]},
32+ * {services: ['c48e6067-5295-48d3-8d5c-0395f61792b1']},
33+ * {name: 'ExampleName'},
34+ * {namePrefix: 'Prefix'}
35+ * ],
36+ * optionalServices: ['battery_service']
37+ * }
38+ * ```
39+ */
1740private fun Options.toDynamic (): dynamic = if (filters == null ) {
18- object {
19- val acceptAllDevices = true
20- val optionalServices = this @toDynamic. optionalServices
41+ jsObject {
42+ this . acceptAllDevices = true
43+ this . optionalServices = optionalServices
2144 }
2245} else {
23- object {
24- val optionalServices = this @toDynamic. optionalServices
25- val filters = this @ toDynamic.filters
46+ jsObject {
47+ this . optionalServices = optionalServices
48+ this . filters = filters.map { it. toDynamic() }.toTypedArray()
2649 }
2750}
51+
52+ private fun Options.Filter.toDynamic (): dynamic =
53+ when (this ) {
54+ is Name -> jsObject { this .name = name }
55+ is NamePrefix -> jsObject { this .namePrefix = namePrefix }
56+ is Services -> jsObject { this .services = services }
57+ }
0 commit comments