LynxBluetooth
Finds Bluetooth LE devices nearby and talks to them, to set up or control an accessory, such as handing a smart device the Wi-Fi password. import { LynxBluetooth, BluetoothError, canonicalBluetoothUUID } from '@blotch/angular-lynx';
Lynx has no navigator.bluetooth. LynxBluetooth is a GATT client: it reads, writes and subscribes to a device's characteristics, the values it groups into services.
Turn it on
Add permissions.bluetooth to the build target's options in angular.json, with the reason iOS shows when it asks:
What it adds:
- iOS:
NSBluetoothAlwaysUsageDescription, the reason iOS's prompt shows. - Android 12 and later: the "Nearby devices" permissions,
BLUETOOTH_SCANandBLUETOOTH_CONNECT, which Android asks for. The scan permission promises the app doesn't work out the phone's location from what it finds, so it needs no location. In return, Android leaves some beacons out of a scan's results. - Android 11 and earlier:
BLUETOOTH,BLUETOOTH_ADMINand fine location, which scanning needed then. - Google Play: Bluetooth LE is declared not required, so Play still offers the app to phones without it.
Without it, the app ships no Bluetooth code at all. App Store Connect flags an app whose code uses Bluetooth without a reason (ITMS-90683), so the build leaves the module out rather than risk it. state is then unsupported, and every call rejects with unavailable.
See Turn on device features for every setting.
Usage
A name or a service in an advertisement doesn't prove which device sent it: anything nearby can advertise the same.
Before writing a secret such as a Wi-Fi password, check that the device holds a key only yours has. Then encrypt the secret so only it can read it. Here sealed is the Wi-Fi password, encrypted that way.
API
LynxBluetooth
- No background mode. In the background, iOS pauses a scan until the app is back. Android carries on scanning, which costs battery: stop a scan the app doesn't need there.
LynxAppStatesays when. - A scan and its connections end when the app closes.
- No pairing call. When a device needs an encrypted link for a characteristic, the system pairs with it by itself, with its own prompt. It does so the first time the app uses that characteristic.
- No advertising. The app can't advertise as a device itself.
state
Where Bluetooth stands, kept up to date as the person turns it on or off or answers the permission prompt, and read again each time the app comes back to the front, since the person can allow it in Settings meanwhile. Reading it never asks for permission.
requestPermission()
Asks the person for permission, if they haven't been asked, and resolves with the state after they answer.
scan() and connect() ask by themselves. Call this first to ask at a moment you choose, such as after a screen that says what Bluetooth is for.
- iOS asks with the
bluetoothreason from angular.json. - Android 12 and later ask for "Nearby devices".
- Android 11 and earlier ask for location instead, which scanning needed then. The app is never given the location.
scan()
Looks for devices advertising nearby. onDevice gets each one the first time it's seen. It then gets it again about once a second while it's in range, with its latest signal strength. Resolves once the scan has started, and rejects with a BluetoothError when it can't.
- Give
services. Without them the scan sees every device advertising nearby, which on a busy street is a lot. - One scan runs at a time. Starting another ends the first. Keep one running rather than restarting it: Android quietly gives an app no results after it starts five scans in 30 seconds.
- Android 11 and earlier also need Location turned on to scan, and the scan rejects with
failedwithout it. - Stop it once you've found the device: scanning drains the battery. Called from an injection context, such as a constructor, the scan stops when the component or service is destroyed. Pass an
injectorto tie it to another one.
idis whatconnect()takes. On iOS it's a UUID the system makes up for the app, the same each time it sees the device. On Android it's the device's Bluetooth address.nameis the name it advertises, or else the name the phone already has for it, such as from connecting to it before.namePrefixmatches it.rssiis the signal strength in dBm: closer to 0 is nearer.manufacturerDatais keyed by the company identifier the Bluetooth SIG assigned. Each value leaves out those two bytes.
A scan's error says why it ended on its own, such as Bluetooth being turned off.
connect()
Connects to a device a scan saw, and discovers every service and characteristic before it resolves.
- It gives up after
timeoutmilliseconds, 10 seconds by default. Neither platform gives up by itself on a device that's gone. - A
timeoutthat isn't a positive number rejects with aRangeError. - Connecting to a device that's connected resolves with the connection it has.
BluetoothConnection
write()waits for the device to confirm by default, and takes up to 512 bytes. WithwithResponse: falseit's quicker but carries at mostmaxWriteLengthbytes, and a lost write is lost. A longer value rejects withfailed: split it.subscribe()callslistenerwith each value the characteristic notifies or indicates. It resolves with a function that stops it. The device stops sending once the last listener of the characteristic stops.connectedturnsfalsewhen the device goes out of range or switches off, and afterdisconnect(). A connection that has ended rejects every call withnotConnected: connect again for a new one.
:::info Reads and notifications mix on iOS iOS reports a read's answer and a notification the same way. So while a characteristic is subscribed on iOS:
- Its listeners also get what a
read()gets. - A
read()can resolve with a notification that arrived first, instead of the read's own answer. That notification can hold an older value. :::
canonicalBluetoothUUID()
Spells a UUID as every call gives it back: 128 bits, lowercase, with hyphens. It throws a TypeError for anything that isn't a UUID.
The Bluetooth specifications give the standard services a 16- or 32-bit UUID, such as '180f' for Battery. That stands for one on the Bluetooth base UUID. Every call takes either spelling, so compare the UUIDs a sighting or a connection gives with this.
BluetoothError
In tests
Under the testing library, the devices in range are the ones a spec adds with addBluetoothDevice(). setBluetoothState() turns the radio off or refuses permission:
Related
- Permission reasons: the
bluetoothreason and the otherpermissions - Turn on device features: every opt-in build option
LynxNativeModule, for the host app's own native code
