@blotch/angular-lynx-native 22.3.1 → 22.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +41 -15
  2. package/dist/android/project.d.ts +90 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +369 -5
  5. package/dist/eject.d.ts +15 -1
  6. package/dist/eject.d.ts.map +1 -1
  7. package/dist/eject.js +13 -2
  8. package/dist/features.d.ts +70 -0
  9. package/dist/features.d.ts.map +1 -0
  10. package/dist/features.js +115 -0
  11. package/dist/generate.d.ts +17 -1
  12. package/dist/generate.d.ts.map +1 -1
  13. package/dist/generate.js +12 -4
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8 -1
  17. package/dist/ios/build.d.ts.map +1 -1
  18. package/dist/ios/build.js +8 -2
  19. package/dist/ios/frameworks.d.ts +6 -5
  20. package/dist/ios/frameworks.d.ts.map +1 -1
  21. package/dist/ios/frameworks.js +46 -15
  22. package/dist/ios/project.d.ts +173 -11
  23. package/dist/ios/project.d.ts.map +1 -1
  24. package/dist/ios/project.js +767 -33
  25. package/dist/options.d.ts +140 -1
  26. package/dist/options.d.ts.map +1 -1
  27. package/dist/options.js +127 -0
  28. package/dist/permissions.d.ts +18 -1
  29. package/dist/permissions.d.ts.map +1 -1
  30. package/dist/permissions.js +63 -3
  31. package/package.json +1 -1
  32. package/templates/android/README.md +35 -2
  33. package/templates/android/angular-lynx.properties +2 -0
  34. package/templates/android/app/build.gradle.kts +51 -2
  35. package/templates/android/app/src/main/AndroidManifest.xml +14 -3
  36. package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
  37. package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
  38. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
  39. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
  40. package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
  41. package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
  44. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
  45. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
  46. package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
  47. package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
  48. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +376 -6
  49. package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
  50. package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
  51. package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +25 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +168 -0
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +6 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +47 -3
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
  58. package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
  59. package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
  60. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
  61. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
  62. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
  63. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
  64. package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
  65. package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
  66. package/templates/android/app/src/main/res/values/share_target.xml +11 -0
  67. package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
  68. package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
  69. package/templates/android/build.gradle.kts +1 -1
  70. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  71. package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
  72. package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
  73. package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
  74. package/templates/ios/App/AngularLynxVideo.h +37 -0
  75. package/templates/ios/App/AngularLynxVideo.m +435 -0
  76. package/templates/ios/App/AngularLynxWebGL.h +69 -7
  77. package/templates/ios/App/AngularLynxWebGL.m +538 -29
  78. package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
  79. package/templates/ios/App/AppDelegate.swift +34 -2
  80. package/templates/ios/App/AppleSignInButton.swift +106 -0
  81. package/templates/ios/App/AppleSignInModule.swift +222 -0
  82. package/templates/ios/App/BarcodeScannerModule.swift +284 -0
  83. package/templates/ios/App/BiometricsModule.swift +256 -0
  84. package/templates/ios/App/BluetoothModule.swift +1086 -0
  85. package/templates/ios/App/CalendarModule.swift +158 -0
  86. package/templates/ios/App/FilePickerModule.swift +240 -0
  87. package/templates/ios/App/HapticsModule.swift +90 -0
  88. package/templates/ios/App/Info.plist +2 -0
  89. package/templates/ios/App/LynxViewController.swift +210 -6
  90. package/templates/ios/App/MotionModule.swift +430 -0
  91. package/templates/ios/App/NfcModule.swift +346 -0
  92. package/templates/ios/App/PhotoLibraryModule.swift +169 -0
  93. package/templates/ios/App/ShareTargetModule.swift +150 -0
  94. package/templates/ios/App/ShellModule.swift +17 -0
  95. package/templates/ios/App/StoreReviewModule.swift +61 -0
  96. package/templates/ios/App/TrackingModule.swift +121 -0
  97. package/templates/ios/App/WifiModule.swift +237 -0
  98. package/templates/ios/App/XElementRegistry.swift +13 -3
  99. package/templates/ios/ShareExtension/Info.plist +42 -0
  100. package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
@@ -0,0 +1,1288 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.Manifest
4
+ import android.annotation.SuppressLint
5
+ import android.bluetooth.BluetoothAdapter
6
+ import android.bluetooth.BluetoothDevice
7
+ import android.bluetooth.BluetoothGatt
8
+ import android.bluetooth.BluetoothGattCallback
9
+ import android.bluetooth.BluetoothGattCharacteristic
10
+ import android.bluetooth.BluetoothGattConnectionSettings
11
+ import android.bluetooth.BluetoothGattDescriptor
12
+ import android.bluetooth.BluetoothManager
13
+ import android.bluetooth.BluetoothProfile
14
+ import android.bluetooth.BluetoothStatusCodes
15
+ import android.bluetooth.le.ScanCallback
16
+ import android.bluetooth.le.ScanFilter
17
+ import android.bluetooth.le.ScanResult
18
+ import android.bluetooth.le.ScanSettings
19
+ import android.content.BroadcastReceiver
20
+ import android.content.Context
21
+ import android.content.Intent
22
+ import android.content.IntentFilter
23
+ import android.content.pm.PackageManager
24
+ import android.location.LocationManager
25
+ import android.os.Build
26
+ import android.os.Handler
27
+ import android.os.HandlerThread
28
+ import android.os.Looper
29
+ import android.os.ParcelUuid
30
+ import android.os.SystemClock
31
+ import android.util.Base64
32
+ import android.util.Log
33
+ import androidx.annotation.RequiresApi
34
+ import androidx.core.content.ContextCompat
35
+ import androidx.core.location.LocationManagerCompat
36
+ import androidx.core.util.forEach
37
+ import com.lynx.jsbridge.LynxContextModule
38
+ import com.lynx.jsbridge.LynxMethod
39
+ import com.lynx.react.bridge.Callback
40
+ import com.lynx.react.bridge.JavaOnlyArray
41
+ import com.lynx.react.bridge.JavaOnlyMap
42
+ import com.lynx.react.bridge.ReadableMap
43
+ import com.lynx.tasm.behavior.LynxContext
44
+ import java.util.UUID
45
+ import java.util.concurrent.atomic.AtomicBoolean
46
+
47
+ /**
48
+ * The native module behind the runtime's `LynxBluetooth`, which calls it as
49
+ * `NativeModules.AngularLynxBluetooth` (from the background thread, where
50
+ * NativeModules lives): a Bluetooth LE central, which scans for peripherals,
51
+ * connects to them, and reads, writes and subscribes to their
52
+ * characteristics while the app is open.
53
+ *
54
+ * Only an app whose angular.json sets `permissions.bluetooth` has this file.
55
+ * The generator deletes it from every other app, whose manifest then declares
56
+ * no Bluetooth permission either, and MainActivity registers it by name only
57
+ * when it's there, so nothing else may name the class.
58
+ *
59
+ * Each method calls back once: with its result, or with `{ error, message }`,
60
+ * as the iOS module does. The rest arrives as `angularLynxBluetooth` global
61
+ * events, each an object with a `type`: the adapter's `state`, a scanned
62
+ * `device` and a `scanStopped`, each with the `scan` id startScan's options
63
+ * gave it, a `disconnected` the app didn't ask for, and a
64
+ * characteristic's `value` notifications. UUIDs travel as lowercase 128-bit
65
+ * strings (how Java's UUID prints them), bytes as base64, and a device's id
66
+ * is its address, as Android gives it.
67
+ *
68
+ * Android runs one GATT operation at a time on a connection: one started
69
+ * before the last one's callback is refused (the call returns false). So each
70
+ * connection queues its operations, those of connecting included, and starts
71
+ * the next as the last one answers.
72
+ */
73
+ // Lint's MissingPermission check wants every Bluetooth call next to a
74
+ // permission check it can see. Here that check is whenReady(), which each
75
+ // method that scans or connects goes through first (asking for the
76
+ // permissions when they're missing), and lint can't follow it through the
77
+ // callbacks and queued operations that make the calls. A permission revoked
78
+ // anyway surfaces as a SecurityException, which is answered `unauthorized`.
79
+ @SuppressLint("MissingPermission")
80
+ class BluetoothModule : LynxContextModule {
81
+ // Lynx creates a module through whichever of its constructors it finds.
82
+ constructor(context: LynxContext) : super(context)
83
+ constructor(context: LynxContext, param: Any?) : super(context, param)
84
+
85
+ private val appContext: Context = mContext.applicationContext
86
+ private val adapter: BluetoothAdapter? =
87
+ appContext.getSystemService(BluetoothManager::class.java)?.adapter
88
+ private val supported =
89
+ adapter != null && appContext.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)
90
+
91
+ // Every field below is read and written on this one thread. The methods
92
+ // (which Lynx calls from its JavaScript thread), Android's GATT and scan
93
+ // callbacks (from binder threads) and the adapter's broadcasts all post
94
+ // to it, so nothing needs a lock and a callback can't race the call that
95
+ // queued its operation. It's a thread of its own rather than the UI
96
+ // thread, so a fast stream of notifications can't take frames from it.
97
+ private val thread = HandlerThread(TAG).apply { start() }
98
+ private val bluetooth = Handler(thread.looper)
99
+
100
+ // The activity's permission prompt runs on the UI thread.
101
+ private val main = Handler(Looper.getMainLooper())
102
+
103
+ // Set once Lynx destroys the module: nothing is posted or sent after it.
104
+ @Volatile
105
+ private var destroyed = false
106
+
107
+ // What scanning and connecting need at this API level. Android 12 gave
108
+ // Bluetooth permissions of its own; before it, a scan's results counted
109
+ // as the phone's location, so they needed ACCESS_FINE_LOCATION.
110
+ private val permissions: Array<String> =
111
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
112
+ arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT)
113
+ } else {
114
+ arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
115
+ }
116
+
117
+ // Whether the person refused the permissions when requestPermission (or
118
+ // a scan or connection) asked. Android can't tell an app whether a
119
+ // permission it doesn't hold was ever asked for, so until this module has
120
+ // asked, the state is `unknown` rather than `unauthorized`, which tells the
121
+ // app that asking may still work.
122
+ private var refused = false
123
+
124
+ // Who's waiting for the permission prompt this module has open, so a
125
+ // second scan or connection joins it instead of opening another.
126
+ private val askers = mutableListOf<(Answer) -> Unit>()
127
+
128
+ // The state the app last heard, so a `state` event goes out only when it
129
+ // changes.
130
+ private var reportedState: String? = null
131
+
132
+ // The running scan (stopScan, or a new startScan, replaces it), when each
133
+ // device it found was last reported, and the names they advertised, which
134
+ // connect() reports when Android has no name of its own for the device.
135
+ private var scan: ScanListener? = null
136
+
137
+ // The id of the newest startScan. A start still waiting for the
138
+ // permission prompt when a newer one arrives doesn't start: the runtime
139
+ // has replaced its scan already, and the newer one may be running.
140
+ private var newestScan = 0
141
+ private val sightings = HashMap<String, Long>()
142
+ private val advertisedNames = HashMap<String, String>()
143
+
144
+ private val connections = HashMap<String, Connection>()
145
+
146
+ // The adapter turning on and off. It's registered with the module's
147
+ // thread, so it arrives there.
148
+ private val adapterStates = object : BroadcastReceiver() {
149
+ override fun onReceive(context: Context, intent: Intent) {
150
+ guarded {
151
+ when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {
152
+ BluetoothAdapter.STATE_TURNING_OFF, BluetoothAdapter.STATE_OFF -> poweredOff()
153
+ }
154
+ stateChanged()
155
+ }
156
+ }
157
+ }
158
+
159
+ init {
160
+ post {
161
+ reportedState = state()
162
+ // A broadcast only the system sends needs neither
163
+ // RECEIVER_EXPORTED nor RECEIVER_NOT_EXPORTED, which apps
164
+ // targeting Android 14 must otherwise choose between.
165
+ appContext.registerReceiver(
166
+ adapterStates,
167
+ IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED),
168
+ null,
169
+ bluetooth,
170
+ )
171
+ }
172
+ }
173
+
174
+ /** `{ state }`, without asking for anything. */
175
+ @LynxMethod
176
+ fun getState(callback: Callback) = serve(callback) { reply ->
177
+ stateChanged()
178
+ reply.ok(stateResult())
179
+ }
180
+
181
+ /**
182
+ * Asks for the permissions this API level needs, unless they're granted,
183
+ * and answers `{ state }` once the person has chosen.
184
+ */
185
+ @LynxMethod
186
+ fun requestPermission(callback: Callback) = serve(callback) { reply ->
187
+ if (!supported || permitted()) {
188
+ stateChanged()
189
+ return@serve reply.ok(stateResult())
190
+ }
191
+ ask(reply) { answer ->
192
+ when (answer) {
193
+ Answer.ANSWERED -> reply.ok(stateResult())
194
+ Answer.BUSY -> reply.fail(BUSY, PROMPT_OPEN)
195
+ Answer.CLOSED -> reply.fail(FAILED, PAGE_CLOSED)
196
+ }
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Scans for peripherals advertising any of `options.services`, or every
202
+ * one when it's empty, and answers `{}` once the scan runs. Its events
203
+ * carry `options.scan`, so the runtime can tell them from those of the
204
+ * scan it replaced. A scan already running ends first, without a
205
+ * `scanStopped` event, even when this one can't start: the runtime has
206
+ * let go of it. A start that waited for the permission prompt answers
207
+ * `{}` without scanning when a newer one came in meanwhile.
208
+ */
209
+ @LynxMethod
210
+ fun startScan(options: ReadableMap?, callback: Callback) = serve(callback) { reply ->
211
+ stopScanning()
212
+ val id = options?.getDouble("scan", 0.0)?.toInt() ?: 0
213
+ newestScan = id
214
+ val services = try {
215
+ uuids(options?.getArray("services", null)?.let { list -> (0 until list.size()).map { list.getString(it) } })
216
+ } catch (_: IllegalArgumentException) {
217
+ return@serve reply.fail(FAILED, "A service to scan for isn't a UUID.")
218
+ }
219
+ whenReady(reply) { adapter ->
220
+ if (id != newestScan) return@whenReady reply.ok()
221
+ if (locationOff()) return@whenReady reply.fail(FAILED, LOCATION_OFF)
222
+ // Null while the adapter is off, which whenReady() just ruled out,
223
+ // but it can be turning off.
224
+ val scanner = adapter.bluetoothLeScanner ?: return@whenReady reply.fail(POWERED_OFF, POWERED_OFF_MESSAGE)
225
+ // One filter per service, which Android matches in the radio's
226
+ // firmware where it can, so the app isn't woken for the rest.
227
+ val filters = services.map { ScanFilter.Builder().setServiceUuid(ParcelUuid(it)).build() }
228
+ // Low latency: the app scans while the person waits for a device
229
+ // to appear, and only while it's open.
230
+ val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build()
231
+ val listener = ScanListener(id)
232
+ // Android lets an app start about five scans in 30 seconds and
233
+ // silently returns nothing from the ones after that: there's no
234
+ // error to report.
235
+ scanner.startScan(filters.ifEmpty { null }, settings, listener)
236
+ scan = listener
237
+ sightings.clear()
238
+ reply.ok()
239
+ }
240
+ }
241
+
242
+ /** Ends the scan, and answers `{}` whether one was running or not. */
243
+ @LynxMethod
244
+ fun stopScan(callback: Callback) = serve(callback) { reply ->
245
+ stopScanning()
246
+ reply.ok()
247
+ }
248
+
249
+ /**
250
+ * Connects to the device [id], requests the largest MTU, discovers its
251
+ * services and characteristics, and answers with them (see [describe]).
252
+ * `options.timeout` (ms) covers all of it; past it, the connection is
253
+ * canceled and the answer is `timeout`. A device already connected, or
254
+ * connecting, answers when that connection is ready, without a second one.
255
+ */
256
+ @LynxMethod
257
+ fun connect(id: String, options: ReadableMap?, callback: Callback) = serve(callback) { reply ->
258
+ val timeout = options?.getDouble("timeout", 0.0)?.toLong()?.takeIf { it > 0 } ?: DEFAULT_CONNECT_TIMEOUT_MS
259
+ whenReady(reply) { adapter ->
260
+ connections[id]?.let { existing ->
261
+ if (!existing.disconnecting) {
262
+ if (existing.ready) reply.ok(describe(existing)) else existing.connecting += reply
263
+ return@whenReady
264
+ }
265
+ // disconnect() is still waiting for Android to confirm: end
266
+ // that connection now, and start afresh.
267
+ drop(existing, null)
268
+ }
269
+ if (!BluetoothAdapter.checkBluetoothAddress(id)) {
270
+ return@whenReady reply.fail(NOT_FOUND, "There's no Bluetooth device with the id $id.")
271
+ }
272
+ val device = adapter.getRemoteDevice(id)
273
+ val connection = Connection(id, device)
274
+ connection.connecting += reply
275
+ connections[id] = connection
276
+ connection.deadline = later(timeout) {
277
+ drop(connection, Failure(TIMEOUT, "The device didn't connect in time."))
278
+ }
279
+ val gatt = try {
280
+ openGatt(device, GattListener(connection))
281
+ } catch (_: SecurityException) {
282
+ return@whenReady drop(connection, Failure(UNAUTHORIZED, UNAUTHORIZED_MESSAGE))
283
+ }
284
+ if (gatt == null) return@whenReady drop(connection, Failure(FAILED, "Android couldn't start connecting."))
285
+ connection.gatt = gatt
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Ends the connection to [id], answering `{}` once Android says it's
291
+ * closed, or at once when there's none. It sends no `disconnected` event.
292
+ */
293
+ @LynxMethod
294
+ fun disconnect(id: String, callback: Callback) = serve(callback) { reply ->
295
+ val connection = connections[id] ?: return@serve reply.ok()
296
+ connection.disconnects += reply
297
+ if (connection.disconnecting) return@serve
298
+ connection.disconnecting = true
299
+ val gatt = connection.gatt
300
+ // Android may never call back for a connection it hadn't made yet,
301
+ // so that one closes at once.
302
+ if (gatt == null || !connection.linked) return@serve drop(connection, null)
303
+ try {
304
+ gatt.disconnect()
305
+ } catch (_: SecurityException) {
306
+ return@serve drop(connection, null)
307
+ }
308
+ // Closing a GATT client before its disconnection is confirmed can
309
+ // leave the link up for a while, and a reconnection soon after
310
+ // fails. But Android doesn't always confirm, so it doesn't wait long.
311
+ connection.deadline?.let(bluetooth::removeCallbacks)
312
+ connection.deadline = later(DISCONNECT_TIMEOUT_MS) { drop(connection, null) }
313
+ }
314
+
315
+ /** Reads a characteristic and answers `{ value }`. */
316
+ @LynxMethod
317
+ fun read(id: String, service: String, characteristic: String, callback: Callback) = serve(callback) { reply ->
318
+ val (connection, target) = find(id, service, characteristic, reply) ?: return@serve
319
+ if (target.properties and BluetoothGattCharacteristic.PROPERTY_READ == 0) {
320
+ return@serve reply.fail(FAILED, "The characteristic $characteristic can't be read.")
321
+ }
322
+ enqueue(
323
+ connection,
324
+ Op(
325
+ OpKind.READ,
326
+ start = { gatt -> if (gatt.readCharacteristic(target)) null else notStarted("the read") },
327
+ finish = { failure, value ->
328
+ if (failure != null) {
329
+ reply.fail(failure)
330
+ } else {
331
+ reply.ok(JavaOnlyMap().apply { putString("value", base64(value ?: ByteArray(0))) })
332
+ }
333
+ },
334
+ ),
335
+ )
336
+ }
337
+
338
+ /**
339
+ * Writes [value] (base64) to a characteristic, and answers `{}` once the
340
+ * device confirms it ([withResponse]) or once Android has sent it.
341
+ */
342
+ @LynxMethod
343
+ fun write(
344
+ id: String,
345
+ service: String,
346
+ characteristic: String,
347
+ value: String,
348
+ withResponse: Boolean,
349
+ callback: Callback,
350
+ ) = serve(callback) { reply ->
351
+ val bytes = try {
352
+ Base64.decode(value, Base64.DEFAULT)
353
+ } catch (_: IllegalArgumentException) {
354
+ return@serve reply.fail(FAILED, "The value to write isn't base64.")
355
+ }
356
+ val (connection, target) = find(id, service, characteristic, reply) ?: return@serve
357
+ val property = if (withResponse) {
358
+ BluetoothGattCharacteristic.PROPERTY_WRITE
359
+ } else {
360
+ BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE
361
+ }
362
+ if (target.properties and property == 0) {
363
+ val kind = if (withResponse) "writes with a response" else "writes without a response"
364
+ return@serve reply.fail(FAILED, "The characteristic $characteristic doesn't take $kind.")
365
+ }
366
+ // A write with a response can be long (Android splits it), up to an
367
+ // attribute's largest value; one without has to fit in a packet. A
368
+ // longer one would be cut short without a word.
369
+ val limit = if (withResponse) MAX_ATTRIBUTE_LENGTH else maxWriteLength(connection)
370
+ if (bytes.size > limit) {
371
+ return@serve reply.fail(FAILED, "The value is ${bytes.size} bytes, and this write takes at most $limit.")
372
+ }
373
+ val type = if (withResponse) {
374
+ BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
375
+ } else {
376
+ BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
377
+ }
378
+ enqueue(
379
+ connection,
380
+ Op(
381
+ OpKind.WRITE,
382
+ start = { gatt -> writeCharacteristic(gatt, target, bytes, type) },
383
+ finish = { failure, _ -> reply.done(failure) },
384
+ ),
385
+ )
386
+ }
387
+
388
+ /**
389
+ * Subscribes to a characteristic's notifications, or its indications when
390
+ * it has only those, or ends the subscription, and answers `{}` once the
391
+ * device has the new setting. Each one then arrives as a `value` event.
392
+ */
393
+ @LynxMethod
394
+ fun setNotifications(
395
+ id: String,
396
+ service: String,
397
+ characteristic: String,
398
+ enabled: Boolean,
399
+ callback: Callback,
400
+ ) = serve(callback) { reply ->
401
+ val (connection, target) = find(id, service, characteristic, reply) ?: return@serve
402
+ val notifies = target.properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0
403
+ val indicates = target.properties and BluetoothGattCharacteristic.PROPERTY_INDICATE != 0
404
+ if (!notifies && !indicates) {
405
+ return@serve reply.fail(FAILED, "The characteristic $characteristic sends no notifications.")
406
+ }
407
+ // The device sends them once its Client Characteristic Configuration
408
+ // descriptor says so. A device that breaks the spec and has none may
409
+ // send them anyway: Android then only needs to pass them on.
410
+ val descriptor = target.getDescriptor(CLIENT_CONFIGURATION)
411
+ if (descriptor == null) {
412
+ val gatt = connection.gatt ?: return@serve reply.fail(NOT_CONNECTED, "The device $id isn't connected.")
413
+ if (!gatt.setCharacteristicNotification(target, enabled)) {
414
+ return@serve reply.fail(notStarted("the subscription"))
415
+ }
416
+ return@serve reply.ok()
417
+ }
418
+ val setting = when {
419
+ !enabled -> BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE
420
+ notifies -> BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
421
+ else -> BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
422
+ }
423
+ enqueue(
424
+ connection,
425
+ Op(
426
+ OpKind.DESCRIPTOR,
427
+ start = { gatt ->
428
+ // Android passes the characteristic's notifications on only
429
+ // once it's told to, which isn't a GATT operation.
430
+ if (gatt.setCharacteristicNotification(target, enabled)) {
431
+ writeDescriptor(gatt, descriptor, setting)
432
+ } else {
433
+ notStarted("the subscription")
434
+ }
435
+ },
436
+ finish = { failure, _ -> reply.done(failure) },
437
+ ),
438
+ )
439
+ }
440
+
441
+ // Lynx destroys the module with its page (and the debug build's reload):
442
+ // the scan ends, every connection closes, and the thread goes. Nobody's
443
+ // left to hear about it, so there are no events.
444
+ override fun destroy() {
445
+ destroyed = true
446
+ bluetooth.post {
447
+ guarded {
448
+ try {
449
+ appContext.unregisterReceiver(adapterStates)
450
+ } catch (_: IllegalArgumentException) {
451
+ // It wasn't registered: the module went before it started.
452
+ }
453
+ stopScanning()
454
+ connections.values.toList().forEach {
455
+ it.disconnecting = true
456
+ drop(it, Failure(FAILED, PAGE_CLOSED))
457
+ }
458
+ askers.toList().also { askers.clear() }.forEach { it(Answer.CLOSED) }
459
+ }
460
+ }
461
+ // Runs what's posted before it, the teardown above included.
462
+ thread.quitSafely()
463
+ super.destroy()
464
+ }
465
+
466
+ // State
467
+
468
+ private fun permitted() = permissions.all {
469
+ ContextCompat.checkSelfPermission(appContext, it) == PackageManager.PERMISSION_GRANTED
470
+ }
471
+
472
+ private fun state(): String {
473
+ val adapter = adapter
474
+ if (!supported || adapter == null) return "unsupported"
475
+ if (!permitted()) return if (refused) "unauthorized" else "unknown"
476
+ return try {
477
+ // TURNING_ON and TURNING_OFF are off: nothing can scan or connect
478
+ // until it's on.
479
+ if (adapter.state == BluetoothAdapter.STATE_ON) "poweredOn" else "poweredOff"
480
+ } catch (_: SecurityException) {
481
+ "unauthorized"
482
+ }
483
+ }
484
+
485
+ private fun stateResult() = JavaOnlyMap().apply { putString("state", state()) }
486
+
487
+ /** Sends a `state` event when the state isn't what the app last heard. */
488
+ private fun stateChanged() {
489
+ val state = state()
490
+ if (state == reportedState) return
491
+ reportedState = state
492
+ emit("state") { putString("state", state) }
493
+ }
494
+
495
+ /**
496
+ * Runs [action] once the app can scan and connect: on a device with
497
+ * Bluetooth LE, with the permissions granted (asked for first when
498
+ * they're missing), and with the adapter on. Otherwise [reply] answers
499
+ * why not.
500
+ */
501
+ private fun whenReady(reply: Reply, action: (BluetoothAdapter) -> Unit) {
502
+ val adapter = adapter
503
+ if (!supported || adapter == null) return reply.fail(UNSUPPORTED, "This device has no Bluetooth LE.")
504
+ if (!permitted()) {
505
+ return ask(reply) { answer ->
506
+ when {
507
+ answer == Answer.BUSY -> reply.fail(BUSY, PROMPT_OPEN)
508
+ answer == Answer.CLOSED -> reply.fail(FAILED, PAGE_CLOSED)
509
+ permitted() -> whenReady(reply, action)
510
+ else -> reply.fail(UNAUTHORIZED, UNAUTHORIZED_MESSAGE)
511
+ }
512
+ }
513
+ }
514
+ val on = try {
515
+ adapter.isEnabled
516
+ } catch (_: SecurityException) {
517
+ return reply.fail(UNAUTHORIZED, UNAUTHORIZED_MESSAGE)
518
+ }
519
+ if (!on) return reply.fail(POWERED_OFF, POWERED_OFF_MESSAGE)
520
+ action(adapter)
521
+ }
522
+
523
+ /**
524
+ * Shows Android's permission prompt through the activity, and calls
525
+ * [done] on the module's thread once it's answered. While this module's
526
+ * prompt is open, a second call waits for the same answer. [done] carries
527
+ * on the method [reply] answers, so it answers as [serve] would when
528
+ * [done] throws, and the calls waiting after it still get their turn.
529
+ */
530
+ private fun ask(reply: Reply, done: (Answer) -> Unit) {
531
+ askers += { answer -> answering(reply) { done(answer) } }
532
+ if (askers.size > 1) return
533
+ val host = mParam as? PermissionHost
534
+ main.post {
535
+ // The page can close first, unregistering the activity's
536
+ // launcher, which then throws: destroy() has answered the calls
537
+ // waiting already.
538
+ if (destroyed) return@post
539
+ val asked = host?.requestPermissions(permissions) { post { answered(Answer.ANSWERED) } } ?: false
540
+ // No host can't ask, which is as good as refused; another
541
+ // module's prompt being open is only for now.
542
+ if (!asked) post { answered(if (host == null) Answer.ANSWERED else Answer.BUSY) }
543
+ }
544
+ }
545
+
546
+ private fun answered(answer: Answer) {
547
+ if (answer == Answer.ANSWERED) refused = !permitted()
548
+ val waiting = askers.toList()
549
+ askers.clear()
550
+ stateChanged()
551
+ waiting.forEach { it(answer) }
552
+ }
553
+
554
+ // Android 6 to 11 return no scan results while Location is off, and
555
+ // don't say so: the scan just finds nothing. Android 12's BLUETOOTH_SCAN,
556
+ // which the manifest declares as never used for location, ended that.
557
+ private fun locationOff(): Boolean {
558
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) return false
559
+ val manager = appContext.getSystemService(LocationManager::class.java) ?: return false
560
+ return !LocationManagerCompat.isLocationEnabled(manager)
561
+ }
562
+
563
+ /** The adapter is going off: the scan and every connection end with it. */
564
+ private fun poweredOff() {
565
+ val failure = Failure(POWERED_OFF, "Bluetooth was turned off.")
566
+ scan?.let { listener ->
567
+ stopScanning()
568
+ emit("scanStopped") {
569
+ putInt("scan", listener.id)
570
+ putString("error", failure.code)
571
+ putString("message", failure.message)
572
+ }
573
+ }
574
+ // Android usually reports each connection closing as the adapter goes
575
+ // off, but not on every version, so they end here.
576
+ connections.values.toList().forEach { drop(it, failure) }
577
+ }
578
+
579
+ // Scanning
580
+
581
+ private fun stopScanning() {
582
+ val listener = scan ?: return
583
+ scan = null
584
+ try {
585
+ // Null once the adapter is off, which has ended the scan already.
586
+ adapter?.bluetoothLeScanner?.stopScan(listener)
587
+ } catch (_: SecurityException) {
588
+ } catch (_: IllegalStateException) {
589
+ // The adapter went off just now, taking the scan with it.
590
+ }
591
+ }
592
+
593
+ /** A scan's callback, and the id the runtime gave the scan. */
594
+ private inner class ScanListener(val id: Int) : ScanCallback() {
595
+ override fun onScanResult(callbackType: Int, result: ScanResult) = post {
596
+ if (scan === this) sighted(result, id)
597
+ }
598
+
599
+ override fun onBatchScanResults(results: MutableList<ScanResult>) = post {
600
+ if (scan === this) results.forEach { sighted(it, id) }
601
+ }
602
+
603
+ override fun onScanFailed(errorCode: Int) = post {
604
+ if (scan !== this) return@post
605
+ scan = null
606
+ emit("scanStopped") {
607
+ putInt("scan", id)
608
+ putString("error", FAILED)
609
+ putString("message", scanFailure(errorCode))
610
+ }
611
+ }
612
+ }
613
+
614
+ /**
615
+ * Sends a `device` event for [result]: the first time the scan sees the
616
+ * device, then at most once per [SIGHTING_INTERVAL_MS]. A device
617
+ * advertises many times a second, and the app needs only its latest
618
+ * signal strength and data. [scan] is the id of the scan that saw it.
619
+ */
620
+ private fun sighted(result: ScanResult, scan: Int) {
621
+ val device = result.device
622
+ val id = device.address
623
+ val now = SystemClock.elapsedRealtime()
624
+ val last = sightings[id]
625
+ if (last != null && now - last < SIGHTING_INTERVAL_MS) return
626
+ sightings[id] = now
627
+ val record = result.scanRecord
628
+ val name = record?.deviceName ?: deviceName(device)
629
+ if (name != null) advertisedNames[id] = name
630
+ val sighting = JavaOnlyMap().apply {
631
+ putString("id", id)
632
+ putNullableString("name", name)
633
+ putInt("rssi", result.rssi)
634
+ putArray(
635
+ "services",
636
+ JavaOnlyArray().apply { record?.serviceUuids?.forEach { pushString(it.uuid.toString()) } },
637
+ )
638
+ putMap(
639
+ "serviceData",
640
+ JavaOnlyMap().apply {
641
+ record?.serviceData?.forEach { (uuid, bytes) ->
642
+ putString(uuid.uuid.toString(), base64(bytes ?: ByteArray(0)))
643
+ }
644
+ },
645
+ )
646
+ // Keyed by the company's Bluetooth SIG id, which Android has
647
+ // already split off the front of the data.
648
+ putMap(
649
+ "manufacturerData",
650
+ JavaOnlyMap().apply {
651
+ record?.manufacturerSpecificData?.forEach { company, bytes ->
652
+ putString(company.toString(), base64(bytes ?: ByteArray(0)))
653
+ }
654
+ },
655
+ )
656
+ }
657
+ emit("device") {
658
+ putInt("scan", scan)
659
+ putMap("device", sighting)
660
+ }
661
+ }
662
+
663
+ // Connections
664
+
665
+ private inner class Connection(val id: String, val device: BluetoothDevice) {
666
+ var gatt: BluetoothGatt? = null
667
+
668
+ // Android reported the link up; services may still be undiscovered.
669
+ var linked = false
670
+
671
+ // Services discovered: connect() has answered, and the app can use it.
672
+ var ready = false
673
+
674
+ // disconnect() asked for it to end.
675
+ var disconnecting = false
676
+
677
+ // Ended: nothing it posts afterwards counts.
678
+ var closed = false
679
+
680
+ // The ATT MTU, which the default stays at until requestMtu() raises it.
681
+ var mtu = DEFAULT_MTU
682
+
683
+ val connecting = mutableListOf<Reply>()
684
+ val disconnects = mutableListOf<Reply>()
685
+
686
+ // The GATT operation Android is running, and those waiting for it.
687
+ var current: Op? = null
688
+ val queue = ArrayDeque<Op>()
689
+
690
+ // connect()'s timeout, then disconnect()'s, and the running
691
+ // operation's.
692
+ var deadline: Runnable? = null
693
+ var watchdog: Runnable? = null
694
+ }
695
+
696
+ private inner class GattListener(private val connection: Connection) : BluetoothGattCallback() {
697
+ override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) = post {
698
+ linkChanged(connection, status, newState)
699
+ }
700
+
701
+ override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) = post {
702
+ // The device can start an exchange of its own too, which also
703
+ // lands here.
704
+ if (status == BluetoothGatt.GATT_SUCCESS) connection.mtu = mtu
705
+ // A failed exchange leaves the default MTU, which still works.
706
+ finished(connection, OpKind.MTU, null, null)
707
+ }
708
+
709
+ override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) = post {
710
+ finished(connection, OpKind.DISCOVER, gattFailure(status), null)
711
+ }
712
+
713
+ // Android 13 and later: the value comes with the callback.
714
+ override fun onCharacteristicRead(
715
+ gatt: BluetoothGatt,
716
+ characteristic: BluetoothGattCharacteristic,
717
+ value: ByteArray,
718
+ status: Int,
719
+ ) = post {
720
+ finished(connection, OpKind.READ, gattFailure(status), value)
721
+ }
722
+
723
+ // Before Android 13, the value is on the characteristic, which the
724
+ // next read or notification overwrites: copied here, on the binder
725
+ // thread, before anything else can arrive.
726
+ @Suppress("OVERRIDE_DEPRECATION", "DEPRECATION")
727
+ override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {
728
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) return
729
+ val value = characteristic.value?.copyOf()
730
+ post { finished(connection, OpKind.READ, gattFailure(status), value) }
731
+ }
732
+
733
+ override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) =
734
+ post { finished(connection, OpKind.WRITE, gattFailure(status), null) }
735
+
736
+ override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) =
737
+ post { finished(connection, OpKind.DESCRIPTOR, gattFailure(status), null) }
738
+
739
+ override fun onCharacteristicChanged(
740
+ gatt: BluetoothGatt,
741
+ characteristic: BluetoothGattCharacteristic,
742
+ value: ByteArray,
743
+ ) = post {
744
+ notified(connection, characteristic, value)
745
+ }
746
+
747
+ @Suppress("OVERRIDE_DEPRECATION", "DEPRECATION")
748
+ override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
749
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) return
750
+ val value = characteristic.value?.copyOf() ?: return
751
+ post { notified(connection, characteristic, value) }
752
+ }
753
+ }
754
+
755
+ private fun linkChanged(connection: Connection, status: Int, newState: Int) {
756
+ if (connection.closed) return
757
+ if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) {
758
+ if (connection.linked) return
759
+ connection.linked = true
760
+ setUp(connection)
761
+ return
762
+ }
763
+ if (newState == BluetoothProfile.STATE_CONNECTED) {
764
+ // Up, but with an error: Android won't use it.
765
+ return drop(connection, linkFailure(status))
766
+ }
767
+ if (newState != BluetoothProfile.STATE_DISCONNECTED) return
768
+ // A clean disconnection (status 0) the app didn't ask for has no
769
+ // error: another app or the system ended it.
770
+ drop(connection, if (status == BluetoothGatt.GATT_SUCCESS) null else linkFailure(status))
771
+ }
772
+
773
+ /**
774
+ * The link is up: requests the largest MTU, so a write without a
775
+ * response carries more than 20 bytes, then discovers the services,
776
+ * through the queue like any other operation.
777
+ */
778
+ private fun setUp(connection: Connection) {
779
+ enqueue(
780
+ connection,
781
+ Op(
782
+ OpKind.MTU,
783
+ start = { gatt -> if (gatt.requestMtu(MAX_MTU)) null else notStarted("the MTU request") },
784
+ // The default MTU still works, only in smaller packets.
785
+ finish = { _, _ -> },
786
+ ),
787
+ )
788
+ enqueue(
789
+ connection,
790
+ Op(
791
+ OpKind.DISCOVER,
792
+ start = { gatt -> if (gatt.discoverServices()) null else notStarted("service discovery") },
793
+ finish = discovered@{ failure, _ ->
794
+ if (connection.closed) return@discovered
795
+ if (failure != null) return@discovered drop(connection, failure)
796
+ connection.ready = true
797
+ connection.deadline?.let(bluetooth::removeCallbacks)
798
+ connection.deadline = null
799
+ val waiting = connection.connecting.toList()
800
+ connection.connecting.clear()
801
+ waiting.forEach { it.ok(describe(connection)) }
802
+ },
803
+ ),
804
+ )
805
+ }
806
+
807
+ /**
808
+ * Ends [connection]: closes its GATT client (Android allows each app a
809
+ * few, and keeps one open until it's closed, even once its link is
810
+ * gone), fails everything waiting on it, answers disconnect(), and sends
811
+ * a `disconnected` event when connect() had answered and disconnect()
812
+ * didn't ask. [reason] is why it ended, null when nothing went wrong.
813
+ */
814
+ private fun drop(connection: Connection, reason: Failure?) {
815
+ if (connection.closed) return
816
+ connection.closed = true
817
+ if (connections[connection.id] === connection) connections.remove(connection.id)
818
+ connection.deadline?.let(bluetooth::removeCallbacks)
819
+ connection.watchdog?.let(bluetooth::removeCallbacks)
820
+ connection.gatt?.let { gatt ->
821
+ // Separately, so a refused disconnect() still closes the client.
822
+ try {
823
+ gatt.disconnect()
824
+ } catch (_: SecurityException) {
825
+ }
826
+ try {
827
+ gatt.close()
828
+ } catch (_: SecurityException) {
829
+ }
830
+ }
831
+ val operations = listOfNotNull(connection.current) + connection.queue
832
+ connection.current = null
833
+ connection.queue.clear()
834
+ val gone = Failure(NOT_CONNECTED, reason?.message ?: "The device disconnected.")
835
+ operations.forEach { it.finish(gone, null) }
836
+ val unfinished = when {
837
+ reason != null -> reason
838
+ connection.disconnecting -> Failure(FAILED, "disconnect() ended the connection before it was ready.")
839
+ else -> Failure(FAILED, "The device disconnected before it was ready.")
840
+ }
841
+ connection.connecting.forEach { it.fail(unfinished) }
842
+ connection.disconnects.forEach { it.ok() }
843
+ if (connection.ready && !connection.disconnecting) {
844
+ emit("disconnected") {
845
+ putString("id", connection.id)
846
+ if (reason != null) {
847
+ putString("error", reason.code)
848
+ putString("message", reason.message)
849
+ }
850
+ }
851
+ }
852
+ }
853
+
854
+ /**
855
+ * The most bytes a write without response carries: what fits in a packet
856
+ * at the connection's MTU, but never more than an attribute holds, which
857
+ * a large MTU would otherwise allow.
858
+ */
859
+ private fun maxWriteLength(connection: Connection) =
860
+ minOf(connection.mtu - ATT_HEADER_LENGTH, MAX_ATTRIBUTE_LENGTH)
861
+
862
+ /**
863
+ * connect()'s answer: `{ id, name, maxWriteLength, services }`, each
864
+ * service with its characteristics and what each one can do.
865
+ */
866
+ private fun describe(connection: Connection) = JavaOnlyMap().apply {
867
+ putString("id", connection.id)
868
+ // What the scan saw it advertise, as on iOS, else the name Android
869
+ // keeps for the device.
870
+ putNullableString("name", advertisedNames[connection.id] ?: deviceName(connection.device))
871
+ putInt("maxWriteLength", maxWriteLength(connection))
872
+ putArray(
873
+ "services",
874
+ JavaOnlyArray().apply {
875
+ connection.gatt?.services?.forEach { service ->
876
+ pushMap(
877
+ JavaOnlyMap().apply {
878
+ putString("uuid", service.uuid.toString())
879
+ putArray(
880
+ "characteristics",
881
+ JavaOnlyArray().apply {
882
+ service.characteristics.forEach { characteristic ->
883
+ pushMap(
884
+ JavaOnlyMap().apply {
885
+ putString("uuid", characteristic.uuid.toString())
886
+ putArray("properties", properties(characteristic.properties))
887
+ },
888
+ )
889
+ }
890
+ },
891
+ )
892
+ },
893
+ )
894
+ }
895
+ },
896
+ )
897
+ }
898
+
899
+ /**
900
+ * The connection and characteristic a read, write or subscription is
901
+ * for, or null once [reply] has answered why there's none.
902
+ */
903
+ private fun find(
904
+ id: String,
905
+ service: String,
906
+ characteristic: String,
907
+ reply: Reply,
908
+ ): Pair<Connection, BluetoothGattCharacteristic>? {
909
+ val connection = connections[id]?.takeIf { it.ready && !it.disconnecting }
910
+ if (connection == null) {
911
+ reply.fail(NOT_CONNECTED, "The device $id isn't connected.")
912
+ return null
913
+ }
914
+ val (serviceUuid, characteristicUuid) = try {
915
+ UUID.fromString(service) to UUID.fromString(characteristic)
916
+ } catch (_: IllegalArgumentException) {
917
+ reply.fail(FAILED, "$service or $characteristic isn't a UUID.")
918
+ return null
919
+ }
920
+ val found = connection.gatt?.getService(serviceUuid)?.getCharacteristic(characteristicUuid)
921
+ if (found == null) {
922
+ reply.fail(NOT_FOUND, "The device has no characteristic $characteristic in service $service.")
923
+ return null
924
+ }
925
+ return connection to found
926
+ }
927
+
928
+ private fun notified(connection: Connection, characteristic: BluetoothGattCharacteristic, value: ByteArray) {
929
+ if (connection.closed) return
930
+ emit("value") {
931
+ putString("id", connection.id)
932
+ putString("service", characteristic.service?.uuid?.toString() ?: "")
933
+ putString("characteristic", characteristic.uuid.toString())
934
+ putString("value", base64(value))
935
+ }
936
+ }
937
+
938
+ // The GATT queue
939
+
940
+ private enum class OpKind { MTU, DISCOVER, READ, WRITE, DESCRIPTOR }
941
+
942
+ /**
943
+ * A GATT operation: [start] hands it to Android, returning null once
944
+ * Android has it or why it was refused, and [finish] is called once,
945
+ * with what came back or why nothing did.
946
+ */
947
+ private class Op(
948
+ val kind: OpKind,
949
+ val start: (BluetoothGatt) -> Failure?,
950
+ val finish: (Failure?, ByteArray?) -> Unit,
951
+ )
952
+
953
+ private fun enqueue(connection: Connection, op: Op) {
954
+ connection.queue.addLast(op)
955
+ next(connection)
956
+ }
957
+
958
+ /**
959
+ * Starts the next queued operation, unless one is running or the
960
+ * connection is ending: drop() answers those still queued.
961
+ */
962
+ private fun next(connection: Connection) {
963
+ while (!connection.closed && !connection.disconnecting && connection.current == null) {
964
+ val op = connection.queue.removeFirstOrNull() ?: return
965
+ val gatt = connection.gatt ?: return op.finish(Failure(NOT_CONNECTED, "The device isn't connected."), null)
966
+ val rejected = try {
967
+ op.start(gatt)
968
+ } catch (_: SecurityException) {
969
+ Failure(UNAUTHORIZED, UNAUTHORIZED_MESSAGE)
970
+ }
971
+ if (rejected == null) {
972
+ connection.current = op
973
+ connection.watchdog = later(OPERATION_TIMEOUT_MS) {
974
+ if (connection.current === op) {
975
+ // The stuck operation answers `timeout`; the rest,
976
+ // which never started, `notConnected`.
977
+ val failure = Failure(TIMEOUT, "The device stopped answering.")
978
+ connection.current = null
979
+ op.finish(failure, null)
980
+ drop(connection, failure)
981
+ }
982
+ }
983
+ return
984
+ }
985
+ // Refused before it began: the next one can start.
986
+ op.finish(rejected, null)
987
+ }
988
+ }
989
+
990
+ /**
991
+ * Android answered the running operation, if it's of [kind]: one of
992
+ * another kind is a callback nothing here asked for, such as an MTU
993
+ * exchange the device started.
994
+ */
995
+ private fun finished(connection: Connection, kind: OpKind, failure: Failure?, value: ByteArray?) {
996
+ if (connection.closed) return
997
+ val op = connection.current ?: return
998
+ if (op.kind != kind) return
999
+ connection.current = null
1000
+ connection.watchdog?.let(bluetooth::removeCallbacks)
1001
+ connection.watchdog = null
1002
+ op.finish(failure, value)
1003
+ next(connection)
1004
+ }
1005
+
1006
+ /**
1007
+ * Starts connecting to [device]. Not autoConnect, which waits for the
1008
+ * device indefinitely and connects slowly: the app is waiting on this
1009
+ * one. LE transport, as a dual-mode device would otherwise get a classic
1010
+ * link.
1011
+ */
1012
+ @Suppress("DEPRECATION")
1013
+ private fun openGatt(device: BluetoothDevice, listener: BluetoothGattCallback): BluetoothGatt? {
1014
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CINNAMON_BUN) {
1015
+ // Android 17's settings would also start an MTU exchange of their
1016
+ // own; the queue's requestMtu() is the only one, so its answer is
1017
+ // the one it waits for. Callbacks run where Android delivers
1018
+ // them, as before Android 17, and the listener posts them on.
1019
+ val settings = BluetoothGattConnectionSettings.Builder()
1020
+ .setAutoConnectEnabled(false)
1021
+ .setTransport(BluetoothDevice.TRANSPORT_LE)
1022
+ .setAutomaticMtuEnabled(false)
1023
+ .build()
1024
+ return device.connectGatt(settings, Runnable::run, listener)
1025
+ }
1026
+ return device.connectGatt(appContext, false, listener, BluetoothDevice.TRANSPORT_LE)
1027
+ }
1028
+
1029
+ // Android 13 replaced the calls that took the value through the
1030
+ // characteristic or descriptor, which another thread could change in
1031
+ // between, with ones that take it as an argument and say why they refused.
1032
+ @Suppress("DEPRECATION")
1033
+ private fun writeCharacteristic(
1034
+ gatt: BluetoothGatt,
1035
+ characteristic: BluetoothGattCharacteristic,
1036
+ value: ByteArray,
1037
+ type: Int,
1038
+ ): Failure? {
1039
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
1040
+ return statusFailure(gatt.writeCharacteristic(characteristic, value, type), "the write")
1041
+ }
1042
+ characteristic.writeType = type
1043
+ characteristic.setValue(value)
1044
+ return if (gatt.writeCharacteristic(characteristic)) null else notStarted("the write")
1045
+ }
1046
+
1047
+ @Suppress("DEPRECATION")
1048
+ private fun writeDescriptor(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, value: ByteArray): Failure? {
1049
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
1050
+ return statusFailure(gatt.writeDescriptor(descriptor, value), "the subscription")
1051
+ }
1052
+ descriptor.setValue(value)
1053
+ return if (gatt.writeDescriptor(descriptor)) null else notStarted("the subscription")
1054
+ }
1055
+
1056
+ // Threads and events
1057
+
1058
+ private fun post(work: () -> Unit) {
1059
+ if (!destroyed) bluetooth.post { guarded(work) }
1060
+ }
1061
+
1062
+ private fun later(delayMs: Long, work: () -> Unit): Runnable =
1063
+ Runnable { guarded(work) }.also { bluetooth.postDelayed(it, delayMs) }
1064
+
1065
+ /**
1066
+ * Runs [work], logging what it throws instead: an exception on the
1067
+ * module's thread would otherwise end the app.
1068
+ */
1069
+ private fun guarded(work: () -> Unit) {
1070
+ try {
1071
+ work()
1072
+ } catch (error: RuntimeException) {
1073
+ Log.w(TAG, "Bluetooth failed", error)
1074
+ }
1075
+ }
1076
+
1077
+ /**
1078
+ * Runs a method's [work] on the module's thread, with its callback
1079
+ * wrapped so it answers once whatever happens: an exception the work
1080
+ * didn't expect answers `failed` (or `unauthorized`, for a permission
1081
+ * Android says is missing) rather than ending the app.
1082
+ */
1083
+ private fun serve(callback: Callback, work: (Reply) -> Unit) {
1084
+ val reply = Reply(callback)
1085
+ val posted = !destroyed && bluetooth.post { answering(reply) { work(reply) } }
1086
+ if (!posted) reply.fail(FAILED, PAGE_CLOSED)
1087
+ }
1088
+
1089
+ /**
1090
+ * Runs [work] for a method, and answers its [reply] when [work] throws:
1091
+ * `unauthorized` for a permission Android says is missing, `failed` for
1092
+ * anything else, rather than ending the app.
1093
+ */
1094
+ private fun answering(reply: Reply, work: () -> Unit) {
1095
+ try {
1096
+ work()
1097
+ } catch (_: SecurityException) {
1098
+ reply.fail(UNAUTHORIZED, UNAUTHORIZED_MESSAGE)
1099
+ } catch (error: RuntimeException) {
1100
+ Log.w(TAG, "Bluetooth failed", error)
1101
+ reply.fail(FAILED, error.message ?: "Bluetooth failed.")
1102
+ }
1103
+ }
1104
+
1105
+ private fun emit(type: String, fill: JavaOnlyMap.() -> Unit) {
1106
+ if (destroyed) return
1107
+ val payload = JavaOnlyMap().apply {
1108
+ putString("type", type)
1109
+ fill()
1110
+ }
1111
+ mLynxContext.sendGlobalEvent(EVENT, JavaOnlyArray().apply { pushMap(payload) })
1112
+ }
1113
+
1114
+ // The name Android keeps for a device, which needs BLUETOOTH_CONNECT
1115
+ // from Android 12.
1116
+ private fun deviceName(device: BluetoothDevice): String? =
1117
+ try {
1118
+ device.name
1119
+ } catch (_: SecurityException) {
1120
+ null
1121
+ }
1122
+
1123
+ /** A method's callback, which answers once: a second answer is dropped. */
1124
+ private class Reply(private val callback: Callback) {
1125
+ private val answered = AtomicBoolean(false)
1126
+
1127
+ fun ok(result: JavaOnlyMap = JavaOnlyMap()) {
1128
+ if (answered.compareAndSet(false, true)) callback.invoke(result)
1129
+ }
1130
+
1131
+ fun fail(failure: Failure) {
1132
+ if (answered.compareAndSet(false, true)) {
1133
+ callback.invoke(
1134
+ JavaOnlyMap().apply {
1135
+ putString("error", failure.code)
1136
+ putString("message", failure.message)
1137
+ },
1138
+ )
1139
+ }
1140
+ }
1141
+
1142
+ fun fail(code: String, message: String) = fail(Failure(code, message))
1143
+
1144
+ fun done(failure: Failure?) = if (failure == null) ok() else fail(failure)
1145
+ }
1146
+
1147
+ /** One of the contract's error codes, and a sentence for the person. */
1148
+ private class Failure(val code: String, val message: String)
1149
+
1150
+ /** How a permission prompt ended. */
1151
+ private enum class Answer {
1152
+ /** The person chose (or Android chose for them). */
1153
+ ANSWERED,
1154
+
1155
+ /** Another module's prompt is open. */
1156
+ BUSY,
1157
+
1158
+ /** The module was destroyed first. */
1159
+ CLOSED,
1160
+ }
1161
+
1162
+ companion object {
1163
+ const val NAME = "AngularLynxBluetooth"
1164
+
1165
+ private const val TAG = "AngularLynxBluetooth"
1166
+
1167
+ /** The one global event, whose payload's `type` says what happened. */
1168
+ private const val EVENT = "angularLynxBluetooth"
1169
+
1170
+ // The contract's error codes.
1171
+ private const val UNSUPPORTED = "unsupported"
1172
+ private const val UNAUTHORIZED = "unauthorized"
1173
+ private const val POWERED_OFF = "poweredOff"
1174
+ private const val NOT_FOUND = "notFound"
1175
+ private const val NOT_CONNECTED = "notConnected"
1176
+ private const val TIMEOUT = "timeout"
1177
+ private const val BUSY = "busy"
1178
+ private const val FAILED = "failed"
1179
+
1180
+ private const val UNAUTHORIZED_MESSAGE = "The app isn't allowed to use Bluetooth."
1181
+ private const val POWERED_OFF_MESSAGE = "Bluetooth is turned off."
1182
+ private const val PROMPT_OPEN = "Another permission prompt is open."
1183
+ private const val PAGE_CLOSED = "The page closed."
1184
+ private const val LOCATION_OFF = "Location is turned off, and this Android version finds no Bluetooth devices without it."
1185
+
1186
+ /** For a connect() without a timeout, which the runtime always gives. */
1187
+ private const val DEFAULT_CONNECT_TIMEOUT_MS = 10_000L
1188
+
1189
+ /** How long disconnect() waits for Android to confirm before closing anyway. */
1190
+ private const val DISCONNECT_TIMEOUT_MS = 2_000L
1191
+
1192
+ /**
1193
+ * The longest a GATT operation may go unanswered before the
1194
+ * connection is given up. Longer than ATT's own transaction timeout,
1195
+ * on which Android drops the link and says why, so this only fires
1196
+ * when Android never answers at all.
1197
+ */
1198
+ private const val OPERATION_TIMEOUT_MS = 35_000L
1199
+
1200
+ /** How often a scan reports a device it has already reported. */
1201
+ private const val SIGHTING_INTERVAL_MS = 1_000L
1202
+
1203
+ // ATT's MTU before an exchange, and the largest Android negotiates
1204
+ // (an attribute's largest value plus a write's header). A write
1205
+ // without a response carries the MTU less its header.
1206
+ private const val DEFAULT_MTU = 23
1207
+ private const val MAX_MTU = 517
1208
+ private const val ATT_HEADER_LENGTH = 3
1209
+ private const val MAX_ATTRIBUTE_LENGTH = 512
1210
+
1211
+ // The connection statuses Android reports as a link ends, from the
1212
+ // Bluetooth spec's HCI error codes and Android's own.
1213
+ private const val LINK_SUPERVISION_TIMEOUT = 0x08
1214
+ private const val REMOTE_USER_TERMINATED = 0x13
1215
+ private const val LOCAL_HOST_TERMINATED = 0x16
1216
+ private const val FAILED_TO_ESTABLISH = 0x3E
1217
+ private const val GATT_ERROR = 0x85
1218
+ private const val GATT_CONNECTION_TIMEOUT = 0x93
1219
+
1220
+ // ATT's error codes for an operation the device refused.
1221
+ private const val INSUFFICIENT_AUTHORIZATION = 0x08
1222
+
1223
+ // The Client Characteristic Configuration Descriptor, which turns a
1224
+ // characteristic's notifications and indications on and off.
1225
+ private val CLIENT_CONFIGURATION: UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
1226
+
1227
+ private fun uuids(strings: List<String>?): List<UUID> = strings.orEmpty().map(UUID::fromString)
1228
+
1229
+ private fun base64(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP)
1230
+
1231
+ private fun JavaOnlyMap.putNullableString(key: String, value: String?) {
1232
+ if (value != null) putString(key, value) else putNull(key)
1233
+ }
1234
+
1235
+ private fun properties(bits: Int) = JavaOnlyArray().apply {
1236
+ if (bits and BluetoothGattCharacteristic.PROPERTY_READ != 0) pushString("read")
1237
+ if (bits and BluetoothGattCharacteristic.PROPERTY_WRITE != 0) pushString("write")
1238
+ if (bits and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE != 0) pushString("writeWithoutResponse")
1239
+ if (bits and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0) pushString("notify")
1240
+ if (bits and BluetoothGattCharacteristic.PROPERTY_INDICATE != 0) pushString("indicate")
1241
+ }
1242
+
1243
+ private fun notStarted(what: String) = Failure(FAILED, "Android refused to start $what.")
1244
+
1245
+ // What an Android 13 write says when it refuses, in place of false.
1246
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
1247
+ private fun statusFailure(code: Int, what: String): Failure? = when (code) {
1248
+ BluetoothStatusCodes.SUCCESS -> null
1249
+ BluetoothStatusCodes.ERROR_MISSING_BLUETOOTH_CONNECT_PERMISSION -> Failure(UNAUTHORIZED, UNAUTHORIZED_MESSAGE)
1250
+ BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED -> Failure(POWERED_OFF, POWERED_OFF_MESSAGE)
1251
+ else -> Failure(FAILED, "Android refused to start $what (status $code).")
1252
+ }
1253
+
1254
+ /** Why a link ended or never came up. */
1255
+ private fun linkFailure(status: Int) = when (status) {
1256
+ LINK_SUPERVISION_TIMEOUT ->
1257
+ Failure(TIMEOUT, "The connection timed out: the device went out of range or stopped answering.")
1258
+ GATT_CONNECTION_TIMEOUT -> Failure(TIMEOUT, "The device didn't answer the connection.")
1259
+ REMOTE_USER_TERMINATED -> Failure(FAILED, "The device ended the connection.")
1260
+ LOCAL_HOST_TERMINATED -> Failure(FAILED, "Android ended the connection.")
1261
+ FAILED_TO_ESTABLISH -> Failure(FAILED, "The connection couldn't be set up.")
1262
+ GATT_ERROR -> Failure(FAILED, "Android couldn't connect to the device (GATT error 133).")
1263
+ else -> Failure(FAILED, "The connection failed (status $status).")
1264
+ }
1265
+
1266
+ /** Why the device refused a GATT operation, or null when it didn't. */
1267
+ private fun gattFailure(status: Int): Failure? = when (status) {
1268
+ BluetoothGatt.GATT_SUCCESS -> null
1269
+ BluetoothGatt.GATT_READ_NOT_PERMITTED -> Failure(FAILED, "The device doesn't allow reading it.")
1270
+ BluetoothGatt.GATT_WRITE_NOT_PERMITTED -> Failure(FAILED, "The device doesn't allow writing it.")
1271
+ BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION, BluetoothGatt.GATT_INSUFFICIENT_ENCRYPTION ->
1272
+ Failure(FAILED, "The device has to be paired first, and pairing didn't succeed.")
1273
+ INSUFFICIENT_AUTHORIZATION -> Failure(FAILED, "The device didn't authorize it.")
1274
+ BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH -> Failure(FAILED, "The device refused a value of that length.")
1275
+ BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED -> Failure(FAILED, "The device doesn't support it.")
1276
+ else -> Failure(FAILED, "The device answered with GATT status $status.")
1277
+ }
1278
+
1279
+ private fun scanFailure(code: Int) = when (code) {
1280
+ ScanCallback.SCAN_FAILED_ALREADY_STARTED -> "A scan was already running."
1281
+ ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED ->
1282
+ "Android couldn't register the scan, which happens when an app starts too many in a short time."
1283
+ ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED -> "This device can't run that scan."
1284
+ ScanCallback.SCAN_FAILED_INTERNAL_ERROR -> "The scan failed inside Android."
1285
+ else -> "The scan failed (error $code)."
1286
+ }
1287
+ }
1288
+ }