> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# 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](/guide/native-apps/permissions.md) iOS shows when it asks:

```json title="angular.json"
"options": {
  "permissions": { "bluetooth": "To find your frame and give it your Wi-Fi." }
}
```

What it adds:

- **iOS:** `NSBluetoothAlwaysUsageDescription`, the reason iOS's prompt shows.
- **Android 12 and later:** the "Nearby devices" permissions, `BLUETOOTH_SCAN` and `BLUETOOTH_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_ADMIN` and 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](/guide/native-apps/device-features.md) for every setting.

## Usage

```typescript
const SETUP = '6e400001-b5a3-f393-e0a9-e50e24dcca9e';
const CREDENTIALS = '6e400002-b5a3-f393-e0a9-e50e24dcca9e';
const STATUS = '6e400003-b5a3-f393-e0a9-e50e24dcca9e';

export class SetUpFrame {
  readonly #bluetooth = inject(LynxBluetooth);
  protected readonly found = signal<readonly BluetoothDevice[]>([]);
  protected readonly status = signal('');

  constructor() {
    // Stops by itself when the screen goes.
    void this.#bluetooth.scan({ services: [SETUP] }, (device) =>
      this.found.update((found) => [
        ...found.filter(({ id }) => id !== device.id),
        device,
      ]),
    );
  }

  protected async setUp(
    device: BluetoothDevice,
    sealed: Uint8Array,
  ): Promise<void> {
    const frame = await this.#bluetooth.connect(device.id);
    await frame.subscribe(SETUP, STATUS, (value) =>
      this.status.set(new TextDecoder().decode(value)),
    );
    await frame.write(SETUP, CREDENTIALS, sealed);
  }
}
```

:::warning Check the device before you send a secret
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`

```typescript
@Injectable({ providedIn: 'root' })
class LynxBluetooth {}
```

| Platform                                          | Bluetooth                                                                                                            |
| ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| iOS                                               | Core Bluetooth                                                                                                       |
| Android                                           | `android.bluetooth`                                                                                                  |
| Unit tests with the testing library               | The devices a spec adds with [`addBluetoothDevice()`](/api/testing-library/fakes/connectivity.md#addbluetoothdevice) |
| [Web preview](/guide/glossary.md#web-preview)     | None: `state` is `unsupported` and every call rejects with `unavailable`                                             |
| [Lynx Explorer](/guide/glossary.md#lynx-explorer) | None: `state` is `unsupported` and every call rejects with `unavailable`                                             |

- **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. [`LynxAppState`](/api/angular-lynx/device/app-state.md) says 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`

```typescript
readonly state: Signal<BluetoothState>;

type BluetoothState =
  | 'unknown'
  | 'resetting'
  | 'unsupported'
  | 'unauthorized'
  | 'poweredOff'
  | 'poweredOn';
```

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.

| State          | Meaning                                                                                                                                                                                         |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `unknown`      | Not known yet, including when the person hasn't been asked for permission.                                                                                                                      |
| `resetting`    | The system's Bluetooth service is restarting.                                                                                                                                                   |
| `unsupported`  | No Bluetooth LE here: the iOS Simulator, or a host without the module.                                                                                                                          |
| `unauthorized` | The person refused, or a policy forbids it. Only Settings can change it now: [`openAppSettings()`](/api/angular-lynx/sharing/linking.md#lynxlinkingopenappsettings) opens the app's page there. |
| `poweredOff`   | Bluetooth is off.                                                                                                                                                                               |
| `poweredOn`    | Ready to scan and connect.                                                                                                                                                                      |

### `requestPermission()`

```typescript
requestPermission(): Promise<BluetoothState>;
```

Asks the person for permission, if they haven't been asked, and resolves with the state after they answer.

[`scan()`](#scan) and [`connect()`](#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 `bluetooth` reason 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()`

```typescript
scan(
  options: BluetoothScanOptions,
  onDevice: (device: BluetoothDevice) => void,
  config?: { readonly injector?: Injector },
): Promise<BluetoothScan>;

type BluetoothScanOptions = {
  readonly services?: readonly string[];
  readonly namePrefix?: string;
};
```

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`](#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 `failed` without 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 `injector` to tie it to another one.

```typescript
type BluetoothDevice = {
  readonly id: string;
  readonly name: string | null;
  readonly rssi: number;
  readonly services: readonly string[];
  readonly serviceData: ReadonlyMap<string, Uint8Array>;
  readonly manufacturerData: ReadonlyMap<number, Uint8Array>;
};

type BluetoothScan = {
  readonly scanning: Signal<boolean>;
  readonly error: Signal<BluetoothError | undefined>;
  stop(): Promise<void>;
};
```

- **`id`** is what `connect()` 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.
- **`name`** is the name it advertises, or else the name the phone already has for it, such as from connecting to it before. `namePrefix` matches it.
- **`rssi`** is the signal strength in dBm: closer to 0 is nearer.
- **`manufacturerData`** is 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()`

```typescript
connect(id: string, options?: { readonly timeout?: number }): Promise<BluetoothConnection>;
```

Connects to a device a scan saw, and discovers every service and characteristic before it resolves.

- **It gives up after `timeout` milliseconds,** 10 seconds by default. Neither platform gives up by itself on a device that's gone.
- **A `timeout` that isn't a positive number** rejects with a `RangeError`.
- **Connecting to a device that's connected** resolves with the connection it has.

### `BluetoothConnection`

```typescript
type BluetoothConnection = {
  readonly id: string;
  readonly name: string | null;
  readonly services: readonly BluetoothService[];
  readonly maxWriteLength: number;
  readonly connected: Signal<boolean>;
  read(service: string, characteristic: string): Promise<Uint8Array>;
  write(
    service: string,
    characteristic: string,
    value: Uint8Array,
    options?: { readonly withResponse?: boolean },
  ): Promise<void>;
  subscribe(
    service: string,
    characteristic: string,
    listener: (value: Uint8Array) => void,
  ): Promise<() => Promise<void>>;
  disconnect(): Promise<void>;
};

type BluetoothService = {
  readonly uuid: string;
  readonly characteristics: readonly {
    readonly uuid: string;
    readonly properties: readonly (
      'read' | 'write' | 'writeWithoutResponse' | 'notify' | 'indicate'
    )[];
  }[];
};
```

- **`write()`** waits for the device to confirm by default, and takes up to 512 bytes. With `withResponse: false` it's quicker but carries at most `maxWriteLength` bytes, and a lost write is lost. A longer value rejects with `failed`: split it.
- **`subscribe()`** calls `listener` with 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.
- **`connected`** turns `false` when the device goes out of range or switches off, and after `disconnect()`. A connection that has ended rejects every call with `notConnected`: 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()`

```typescript
function canonicalBluetoothUUID(uuid: string): string;
```

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`

```typescript
class BluetoothError extends Error {
  readonly code: BluetoothErrorCode;
}
```

| Code                                        | Meaning                                                                                                                        |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `unavailable`                               | The host has no Bluetooth module: angular.json's permissions don't list `bluetooth`, or it's Lynx Explorer or the web preview. |
| `unsupported`, `unauthorized`, `poweredOff` | As the [state](#state) of the same name.                                                                                       |
| `notFound`                                  | No device has that id, or the connected device has no such service or characteristic.                                          |
| `notConnected`                              | The connection has ended.                                                                                                      |
| `timeout`                                   | The device didn't answer in time.                                                                                              |
| `busy`                                      | The platform is already doing something it does one at a time.                                                                 |
| `failed`                                    | Anything else. The message has the platform's reason.                                                                          |

## In tests

Under the [testing library](/guide/testing/index.md), the devices in range are the ones a spec adds with [`addBluetoothDevice()`](/api/testing-library/fakes/connectivity.md#addbluetoothdevice). [`setBluetoothState()`](/api/testing-library/fakes/connectivity.md#setbluetoothstate) turns the radio off or refuses permission:

```typescript
const frame = addBluetoothDevice({
  id: 'frame',
  name: 'Blotch - XyZ1',
  services: {
    [SETUP]: {
      [CREDENTIALS]: {
        properties: ['write'],
        onWrite: (_value, device) =>
          device.notify(SETUP, STATUS, new TextEncoder().encode('online')),
      },
      [STATUS]: { properties: ['notify'] },
    },
  },
});
await render(SetUpFrame);

fireEvent.tap(await screen.findByText('Blotch - XyZ1'));
await waitForUpdate();

expect(frame.writes).toHaveLength(1);
expect(await screen.findByText('online')).toBeInTheDocument();
```

## Related

- [Permission reasons](/guide/native-apps/permissions.md): the `bluetooth` reason and the other `permissions`
- [Turn on device features](/guide/native-apps/device-features.md): every opt-in build option
- [`LynxNativeModule`](/api/angular-lynx/host/native-module.md), for the host app's own native code
