# Bluetooth on the Ovok client

Canonical page: https://docs.ovok.com/native-sdk/guide/modules/bluetooth

`@ovok/native/bluetooth` finds supported Bluetooth devices, pairs them, and gives you one `Device` handle per paired device. Every action is one method on that handle: syncing, listing a device's records, fetching one record, streaming live values and setting its clock all run on the same link. The handle opens the link when an action needs it and reconnects without the caller noticing, so a button never needs a connection step of its own. Readings are saved through the [next `Ovok` client](./next.md). The Flutter SDK follows this contract, so its names match.

It is built in layers, each depending only on the ones below it:

| Layer | What it is |
|---|---|
| Core | `Bluetooth`, `Device`, `Discovery` and `Catalog`: identification, pairing, the action queue on each link, and saving, in plain TypeScript with no React and no BLE library. |
| Ports | `BleCentral` and `GattLink` (the radio), `PairedDeviceStore`, `ReadingSink`, `BluetoothPermissions` and `Logger`. |
| Families | `DeviceProtocol`s with their `DeviceModel` rows: Viatom file transfer (BP2, DuoEK, ER2-S) and the Bluetooth SIG heart-rate profile. A new device on a known protocol is one more model row. |
| Adapters | `blePlxCentral`, `osBluetoothPermissions`, `storagePairedDevices`, `ovokReadingSink` and `createBluetooth`. In browsers, `@ovok/native/bluetooth/web` has `createWebBluetooth` over Web Bluetooth. |
| Hooks | `useDiscovery`, `usePairedDevices`, `useDevice`, `useLiveValues`, `useWaveform`, `useReadings`, `useCatalog` and `useBluetoothAdapter`. |

## Find, pair, sync [#find-pair-sync]

```tsx
import { Button, Text } from 'react-native';
import { BluetoothProvider, createBluetooth, useBluetooth, useDevice, useDiscovery, usePairedDevices } from '@ovok/native/bluetooth';
import { ovok, storage } from './ovok'; // the `Ovok` client, signed in, and its storage

const bluetooth = createBluetooth({ ovok, storage });

export const App = () => <BluetoothProvider bluetooth={bluetooth}><Devices /></BluetoothProvider>;

const Devices = () => {
  const bt = useBluetooth();
  const { found } = useDiscovery({ vendor: 'viatom' });
  const paired = usePairedDevices();

  return (
    <>
      {paired.map(({ address }) => <DeviceCard key={address} address={address} />)}
      {found.filter(({ match }) => match.kind === 'supported').map((device) => (
        <Button key={device.address} title={`Pair ${device.name}`} onPress={() => bt.pair(device)} />
      ))}
    </>
  );
};

const DeviceCard = ({ address }: { address: string }) => {
  const { snapshot, device } = useDevice(address);

  if (!snapshot || !device) return null;

  return (
    <>
      <Text>{snapshot.name} · {snapshot.connection} · {snapshot.battery?.percent ?? '–'}%</Text>
      {snapshot.actions.includes('sync') && <Button title="Sync" disabled={snapshot.activity !== null} onPress={device.sync} />}
      {snapshot.lastError && <Text>{snapshot.lastError.code}</Text>}
    </>
  );
};
```

Pairing connects once and sets the device's clock. A protocol can ask for more: blood pressure monitors that take the time only while they pair (such as the Veroval compact + BPU 26) keep that link for five seconds after the time is written, and it closes before the first sync.

Synced readings are saved through the `ReadingSink` (by default the Ovok measurements API, which queues them offline). Once a reading is saved or queued, the device's cursor moves past it, so the next sync reads only newer records; a reading whose save failed is read again on the next sync.

## The device snapshot [#the-device-snapshot]

`device.snapshot()` (and `useDevice`) has the same keys for every model; a value is `null` until it happens or when the device cannot report it:

| Group | Fields |
|---|---|
| Who it is | `address`, `model` (`id`, `vendor`, `name`), `name`, `pairedAt` |
| What it is doing | `connection`, `activity`, `live`, `measuringSince`, `progress`, `actions`, `lastSeenAt`, `rssi`, `lastError` |
| History (kept across restarts) | `lastConnectedAt`, `lastSyncedAt`, `lastSyncOutcome`, `lastReadingAt`, `unacknowledged` |
| What the device reports | `battery`, `identity`, `deviceStatus`, `deviceState` (a hearing aid's ears, volume and mode while live) |
| Settings (kept across restarts) | `autoSync`, `keepInBackground`, `record` |

`measuringSince` is set by the first live frame that measures and cleared after 5 seconds without one, when the stream stops, or as soon as the device reports it is not measuring. A frame measures when the device says so (for example a Viatom run status of recording or checking leads), or, from a device that reports no such state, when it carries numbers or samples. So any streaming device can show that it is measuring, and a connected device lying idle does not.

Device flags in readings and the snapshot are the device's own bits, kept raw; the SDK never classifies a reading.

## Discovery [#discovery]

`bt.discover(selector)` and `useDiscovery(selector)` take `{ vendor, model, type }`, each one value or a list. Identification runs against the whole catalog first and the selector filters afterwards, so a device another vendor's model claims never shows up as yours. Devices never advertise their vendor: Viatom devices advertise names such as `BP2 1234` or `DuoEK 0001`, and the catalog maps those names to models.

Two names can match more than one model (`DuoEK*` is both DuoEK and DuoEK-S). Such a row's `match.variants` lists them all, with the default first; pass `{ model }` to `bt.pair` to pick another.

## Live values and waveforms [#live-values-and-waveforms]

A device whose protocol streams has a `live` action. `device.startLive()` streams `live` events (numbers such as heart rate) and `waveform` events (samples such as ECG) on the same link; `device.stopLive()` stops the device's stream. `useLiveValues(address)` gives the newest values and `useWaveform(address, { seconds })` a buffer per channel that re-renders at most once per animation frame.

While a device's `record` setting is on (the default), what it streams while it is measuring (`measuringSince` is set) is also saved, the same way for every device. A result the device keeps showing once it stopped measuring is shown but not saved as live data:

- numbers go into 1-second slots, one series per metric. The open series is saved every 60 seconds under a stable identifier, so the outbox replaces its waiting copy. It closes after an hour of slots or a minute without data;
- a stream that stops and starts again within that minute (a screen closing, the app going to the background, a dropped link) carries on the same series, with the gap left empty, and saves it under the same identifier, so one measurement stays one series. A gap of a minute or more starts a new series;
- waveforms are saved per channel in segments of at most 5 minutes, when full, after a gap and when the stream ends;
- when a device later delivers a stored record covering time already recorded live, the record is saved and the live items inside its span are deleted; a live series replaced this way is never carried on.

## Offline queue [#offline-queue]

Readings go through `@ovok/core`'s outbox, which keeps each one on the device until the server accepts it. The native Ovok client keeps the outbox in SQLite and sends when the network returns and when the app comes to the foreground; see [Unsent measurements](./next.md#unsent-measurements). `@ovok/native/bluetooth/sqlite` exports the same store for an app that builds its own, such as one with another database name. In a browser, use `@ovok/core`'s IndexedDB store instead.

The reading log follows the outbox, so a reading moves from `queued` to `saved` (or `rejected`) as it is sent, and `useOutbox()` gives the outbox's counts. On Android the connected-device notification shows how many readings are waiting to upload.

### Readings without an account [#readings-without-an-account]

Bluetooth also works while nobody is signed in. The sink saves every reading, series included, for the guest: it stays `queued` in the outbox on the device and is never sent, and the Android notification does not count it as waiting to upload. Once someone signs up or signs in, hand the readings to them; they keep their outbox ids, so the reading log sees them sent:

```ts
await ovok.outbox.adopt();
```

A stored record that replaces a guest's live recording only drops the live copy: the server never had it.

## Syncing by itself [#syncing-by-itself]

A paired device that can sync also syncs without a press, through the same `device.sync()` as the button:

- **In the foreground**, a scan looks for paired devices in 30-second windows with 5-second rests, and a device it sees is synced. A device synced or tried less than 15 seconds ago, or paired less than a second ago, is left alone. The scan pauses while a discovery the app started runs, and that discovery's sightings count too.
- **Links:** an idle link closes 30 seconds after its last action, so the next press reuses it. When the app goes to the background, idle links close at once.
- **In the background**, only devices set to stay connected sync. Such a device is synced when the app leaves the foreground, its link stays open, and it is reconnected as soon as it drops. It reconnects by its stored address, not by scanning, so name-only models work too. The connect waits for the radio to be on and then never times out, so it stays pending until the device is back; on iOS, that is what wakes a suspended app. A failed try is retried 10 seconds later while the app runs.
- **Streaming while kept:** a device set to stay connected that also records and can stream (`keepInBackground` and `record` on, a `live` action) starts its stream each time it connects, with or without the app on screen, so what it streams is saved while the app is closed. Turning `keepInBackground` or `record` off stops a stream started this way; a stream the user stops stays stopped until the next connection. Leave such a device's stream running when a screen that showed it closes; calling `stopLive()` there would stop the recording.
- **After a live measurement**, a device that streams and keeps records, such as a Viatom BP2 or ER1, is synced 3 seconds after a measurement ends while its stream still runs, so the record it has just stored arrives without a press. This needs no scan, so only the device's own `autoSync` setting turns it off.

Each device has two settings, stored with it and shown in its snapshot:

```ts
await device.configure({ autoSync: false });        // on by default
await device.configure({ keepInBackground: true }); // off by default
```

Background sync needs the config plugin's `bluetooth.background` option, `["@ovok/native", { bluetooth: { background: true } }]`. On iOS it adds the `bluetooth-central` background mode. On Android it declares the SDK's connected-device foreground service, which runs while a link is open or a device is set to stay connected, and shows a notification. Pass `autoSync: false` to `createBluetooth` to turn off the scan and background syncing for every device.

## Browsers [#browsers]

```ts
import { createWebBluetooth } from '@ovok/native/bluetooth/web';
```

Chrome and Edge on desktop and Android run the same families over Web Bluetooth. There is no passive scan. `useDiscovery(selector)` lists the devices the site may already use (`navigator.bluetooth.getDevices()`, which Chrome still keeps behind `chrome://flags/#enable-experimental-web-platform-features`), and `start()` from a press handler opens the browser's own chooser, which the browser allows only from a click. The chooser shows only the selector's models: by name prefix, by advertised service, or, for a name matched anywhere, by the text after its leading `*`, since Web Bluetooth filters names only by how they start. For the same reason, devices do not sync by themselves in a browser.

## Replace a port [#replace-a-port]

Every port can be swapped by passing it to `createBluetooth` (for example a custom `sink`, `store` or `logger`), or by building `new Bluetooth({ … })` with your own adapters.

## Platform notes [#platform-notes]

- **Permissions:** Android 12 and later asks for Bluetooth scan and connect; earlier Android asks for fine location. iOS asks for Bluetooth. `useBluetoothAdapter()` reports both and requests the permission.
- **Background discovery:** only models that advertise a service UUID can be found by a background scan; name-only models (all Viatom models) are found in the foreground, and paired devices reconnect by their stored address.
- **Android, app swiped away:** the foreground service is declared with `stopWithTask="false"`, so it outlives the app's task being swiped away; while the app's process runs, kept devices stay connected and keep recording.
- **Android notification:** Android 13 and later shows the foreground service's notification only after the app is granted notification permission; the service runs either way.
- **iOS addresses:** iOS gives each device a per-install identifier instead of its MAC, so a reinstall needs pairing again.
- **iOS relaunch:** `createBluetooth` turns on CoreBluetooth state restoration. When iOS ends a suspended app, it keeps the pending connects and relaunches the app in the background once a device connects; the device then syncs as above, and `bluetooth.state-restored` is logged. iOS gives a relaunched app about 10 seconds, so call `createBluetooth` as soon as the app starts, without waiting on the network. Swiping the app away in the app switcher turns this off until the app is opened again.

## See also [#see-also]

Every export, with signatures and types, is in the [`bluetooth` API reference](../../reference/bluetooth.mdx).
