# Health

> Read heart rate, sleep and activity from the wearer's watch and ring, one series per source.

Source: https://docs.dev.glasslyos.com/app-devs/core-concepts/health/

`session.health` reads the wearer's health history. It has two kinds of
source:

- **The phone's health store.** Apple Health on iOS, Health Connect on
  Android. An Apple Watch and a Wear OS watch reach Glassly through it, as do
  apps that write there, such as WHOOP.
- **Paired Even R1 rings.** The Glassly App copies each ring's history to the
  phone.

The host never merges sources. A query answers one series per source, and your
miniapp decides how to combine them or show them side by side. Access is read
only. There is no live heart rate and there are no workouts.

## Declare the permission

Add `HEALTH` to your [manifest](https://docs.dev.glasslyos.com/app-devs/core-concepts/miniapp-manifest.md#permissions)
and set `minHostVersion` to `0.4.5`. Any miniapp may declare `HEALTH`.

```json miniapp.json
{
  "minHostVersion": "0.4.5",
  "permissions": [
    {"type": "HEALTH", "description": "Shows your heart rate and sleep from your watch and ring"}
  ]
}
```

Declaring it is not enough: the wearer allows each miniapp on its own. When
the wearer launches your miniapp from the phone, the Glassly App asks whether
your miniapp, by name, may read their health data from Apple Health or Health
Connect and from their paired rings. Another miniapp that declares `HEALTH` is
asked about separately.

- **Allow** records the grant, then iOS shows the Apple Health read sheet and
  Android the Health Connect permission screen. The wearer's answer there
  decides only whether store data comes back; ring data comes back either way.
- **Don't Allow** keeps a miniapp that requires `HEALTH` closed and asks again
  at its next launch. With `"required": false` your miniapp launches anyway
  and is not asked again.
- A launch from the glasses or from an action skips the question.
- The wearer can turn the grant on or off on your miniapp's page in the
  Glassly App, under Permissions. It takes effect at once, for a running
  miniapp too, and uninstalling your miniapp removes it.

Without the grant, every call rejects with `PERMISSION_DENIED` and `onChange`
never fires. Without `HEALTH` in the manifest, every call rejects with
`PERMISSION_NOT_DECLARED`. On a Glassly App older than 0.4.5, every call
rejects with `NOT_IMPLEMENTED`.

## Read heart rate

```typescript src/background/index.ts
import { registerMiniapp, type HealthQueryResult, type Rpc } from "@glassly/miniapp/background";

type Channels = {
  heart_rate: Rpc<Record<string, never>, HealthQueryResult>;
  health_changed: { at: number };
};

registerMiniapp<Channels>((session) => {
  session.ui.handle("heart_rate", () => {
    const end = new Date();
    end.setHours(end.getHours() + 1, 0, 0, 0);
    const start = new Date(end);
    start.setDate(start.getDate() - 1);
    return session.health.query({ metric: "heart_rate", start, end, bucket: "hour" });
  });

  session.health.onChange((change) => session.ui.send("health_changed", { at: change.at }));
});
```

Your phone page calls `glassly.request("heart_rate", {})` and draws one line
per entry of `series`. Each series has a `source` and its `points`:

| Field | Notes |
|---|---|
| `source` | `{kind: "store", id, name, device?}` or `{kind: "ring", id, name}`. `device` is `"watch"`, `"phone"`, `"ring"` or `"other"` when the store knows it. |
| `kind` | `"range"` for readings, `"total"` for steps and active energy. |
| `points` | For a range metric, `{start, end, min, avg, max}` per bucket. For a total metric, `{start, end, sum}`. A bucket with no reading is left out. |

`bucket` is `"hour"` (at most 31 days per query) or `"day"` (at most 366).
`hour` buckets start at the local clock hour and `day` buckets at the phone's
local midnight. The range is widened to whole buckets.

## Metrics

| Metric | Unit | Apple Health | Health Connect | Even R1 |
|---|---|---|---|---|
| `heart_rate` | bpm | yes | yes | yes |
| `resting_heart_rate` | bpm | yes | yes | no |
| `hrv_sdnn` | ms | yes | no | no |
| `hrv_rmssd` | ms | no | yes | yes |
| `spo2` | %, from 0 to 100 | yes | yes | yes |
| `respiratory_rate` | breaths/min | yes | yes | no |
| `steps` | count | yes | yes | yes |
| `active_energy` | kcal | yes | yes | yes |

SDNN and RMSSD measure different things, so they are separate metrics. A
source that cannot answer a metric sends no series for it, and neither does a
ring with no reading of it in the range.

## Read sleep

```typescript
const { sessions } = await session.health.sleep({ start, end });
```

`sleep` answers every session that overlaps the range, from every source,
with its `stages` (`awake`, `light`, `deep`, `rem`, `asleep`, `in_bed`). A
ring session also has a `score` and an `efficiency`, each from 0 to 100. The
range covers at most 366 days.

## Sources and ring sync

`session.health.availability()` answers which store the phone has
(`"healthkit"`, `"health_connect"` or `null`) and every paired ring with
`connected`, `lastSyncedAt` and `lastSync`.

The Even R1 keeps about 3 days of history. The Glassly App keeps what it copied
for 400 days and deletes it when the wearer forgets the ring. It keeps the
rings synced while any running miniapp that the wearer allowed holds an
`onChange` subscription. To
keep a full ring history, make your miniapp `"type": "background"` with
`"alwaysOn": true` and subscribe for the whole session.
`session.health.sync()` syncs every paired ring now and answers each ring's
status.

On its own the Glassly App syncs a connected ring at most once every 3 hours.
`sync()` syncs a ring only when its last successful sync is at least 5 minutes
old, or its last attempt ended any other way at least 1 minute ago, and
otherwise answers the status it already holds, so calling it in a loop does not
keep taking the ring's touch away.

The ring hands its history only to a link that holds the phone role, and its
touch input goes to whoever holds its glasses role.

- A ring bound to the glasses keeps them in its glasses role. The Glassly App
  notices this after the ring drops the phone's claim twice in a row, or ten
  times in a row for a ring whose touch has reached the phone directly, then
  connects the ring in the phone role only. Touch keeps coming through the
  glasses, and a sync runs with no swap and no loss of touch. The ring also
  sends its history by itself every 3 hours, which counts as a sync.
- A ring the phone holds in the glasses role (no glasses, or a G2 on Glassly
  CFW that the ring is not bound to) needs a role swap: the Glassly App swaps
  the link's role, syncs, and swaps back. Touch from the ring is gone during
  the swap, an estimated 20 to 30 seconds that nobody has measured on a ring.
  It swaps only while no miniapp other than the dashboard holds a gesture
  claim. When it cannot swap, the ring's `lastSync` is `"refused"`.

A sync waits up to 20 seconds for a ring that is between connections, and
answers `"unreachable"` only when no link comes up.

Ring health has synced on one ring through a phone-role link. The role swap
and the phone-role link for a ring bound to the glasses have not run on a ring
yet.

`onChange` fires with `source: "ring"` when a sync, or history the ring sent
by itself, stored new data, and with
`source: "store"` when the Glassly App comes back to the foreground. It
carries no readings, so query again.

## What to expect

- **Apple Health hides a denied read.** A type the wearer did not allow looks
  the same as no data. Tell the wearer "No data, or access is off" and point
  them to the Health app's settings for Glassly.
- **Apple Health cannot be read while the iPhone is locked.** A query then
  answers ring series only. Query again on the next `onChange`.
- **Health Connect** answers a type the wearer did not grant with no series,
  and answers data from at most 30 days before access was first granted.

## Handle health data with care

Never log a health value. Console output goes into the bug reports a wearer
uploads, so log counts and error codes only.

App Store Review Guideline 5.1.3 applies to what your miniapp does with the
data. Do not use it for advertising or marketing, and do not share it with
anyone, your own server included, without the wearer's consent.

The Glassly App already keeps the history, so query again rather than keep
copies. `session.storage` goes into the wearer's app backups.

## In the simulator

With `HEALTH` declared, `glassly sim` answers from stand-in data: Apple Health
holding an Apple Watch and WHOOP, and a connected Even R1, over the last 35
days. The simulator has no wearer to ask, so a miniapp that declares `HEALTH`
counts as allowed, and `sync()` answers at once on every call.

```bash
glassly sim health          # onChange with source "ring"
glassly sim health --store  # onChange with source "store"
```

The full reference, with every type and error, is
[`sdk/docs/health.md`](https://github.com/tetramo-labs/glassly/blob/dev/sdk/docs/health.md).
