# Guide 4: A HEART-Embedded pacemaker system

**A case study.** A maker of cardiac pacemakers wants its products to be HEART-embedded systems: each system should know when it is unwell, say so in one standard language, tell the right person, and never leak anything it should not. This guide goes step by step from day 1 to a system that can claim **HEART Basic, Autonomy Level A1**, and shows how an owner registers it and watches it on HEART Hub.

A working demo comes with it: [`pacemakerSimulator/`](../pacemakerSimulator/README.md), one Python file that simulates a patient, an implant and its HEART, and reports to `https://heartcortex.ai`.

> **Status.** A design case study with a simulator. No real implant, transmitter or patient was involved, and nothing here is medical advice or a regulatory route. A real pacemaker is a life-sustaining device, regulated as such everywhere.

---

## Before you start: HEART never touches pacing

A pacemaker's job, sensing each heartbeat and pacing when the heart is too slow, is **therapy**. It sits in the safety chain, it is certified, and it must never depend on anything else. HEART stays out of it completely.

| Stays in the implant and its certified software | Goes to HEART |
|---|---|
| Sensing, pacing, rate response, mode switching | Knowing whether pacing is working (capture) |
| Every programmed setting (rates, output, modes) | Watching battery, lead, threshold and sensing |
| Programming, which only a clinician's programmer may do | Raising alerts with standard fault codes |
| Safety modes (magnet mode, noise reversion, back-up pacing) | Telling the clinic, even with no internet |
| Anything an implant standard covers | Answering "how is the system?" in one standard format |

This is the general rule of the standard (Part 6: HEART stays out of the safety chain and out of real-time control loops) at its strictest. **This HEART has no commands at all.** It cannot change a setting, not even with approval, because a person approving on a phone is not a clinician at a programmer.

---

## Step 1: Decide where HEART runs

An implant has a battery that must last ten years and almost no spare power, memory or radio time. It must not carry a HEART. The usual system around it does have room:

```
implant ──(short-range telemetry)──► home transmitter ──(internet)──► clinic and HEART Hub
 therapy only                          HEART runs here
```

| Part | What it does | HEART's place |
|---|---|---|
| **Implant** | Paces; stores its own measurements and episodes | None. Read only, through its existing telemetry |
| **Home transmitter** (bedside unit, or the patient's phone app) | Reads the implant each night and on alerts | **Runs the HEART** (class Core-M, embedded Linux; or the Python or ESP32 starter for a smaller unit) |
| **Clinic system** | Reviews transmissions | Reads the HEART API; receives escalations |

So the HEART-embedded system is the **pair**: the implant, as seen by its transmitter. The transmitter knows the implant only through telemetry it already receives, and adds no new path into the implant.

---

## Step 2: Give the system an identity

The transmitter's HEART serves a Card at `/.well-known/heart-card.json`:

```json
{ "system": { "id": "com.example.cardio.pacing-system", "name": "Example pacing system", "version": "1.0.0" },
  "level": "basic", "bindings": ["http-server"], "pulse": { "intervalSec": 30 },
  "modules": ["properties"], "shares": { "pulse": "public", "arrhythmia": "public", "property": "private" },
  "autonomy": { "level": 1 }, "template": "heart/embeddedstandard/python/v1.2611.2" }
```

The system ID names the product, never the patient. The device ID used by HEART Hub (Step 8) is random, and nothing links it to a person except the owner's own registration.

---

## Step 3: List what the system knows, and how private each item is

Health data is special: most laws treat it as a protected category (for example GDPR Article 9, HIPAA). Decide every value's privacy level **before** writing code.

| Value | Source | Privacy | Why |
|---|---|---|---|
| Healthy or not; open fault codes | Derived by HEART | `public` | The only things HEART Hub ever receives (Step 8) |
| Battery status: ok, replace soon, end of life | Implant telemetry | `public` | Needed to act; reveals nothing more than the alert does |
| Battery months left, voltage | Implant | `internal` | For the clinic |
| Lead impedance, capture threshold, R-wave amplitude | Implant | `internal` | Device integrity, for the clinic |
| Percentage paced | Implant | `internal` | |
| Heart rate, the patient's own rate | Implant | `private` | Physiology: the patient's own data |
| Movement, temperature | Implant sensors | `private` | Reveals daily life |
| Rhythm episodes (atrial fibrillation, slow-heart pauses) | Implant | `private` | Diagnoses |
| Name, date of birth, clinic patient number | Clinic system | **not on the transmitter** | The HEART does not need them, so it never has them |

Note what is **not** an alert: an atrial fibrillation episode is a fact about the patient, not a fault of the system. It is recorded as a `private` Rhythm event for the clinic, and never becomes a public alert.

---

## Step 4: Say what "doing its main job" means

The main job of a pacing system is: **when the heart needs pacing, every paced beat captures it.** The transmitter's HEART checks this from telemetry:

```python
def check_main_function():
    """CHANGE: return (True, "") if pacing works, else (False, "what is wrong, in plain words")."""
    t = telemetry.latest()
    if t.pacing_needed and not t.capture_confirmed:
        return False, "Pacing is not capturing the heart. Contact the clinic now."
    return True, ""
```

A condition must hold for a few seconds before it is raised, because one odd reading is not a fault.

---

## Step 5: The faults it recognises

Every alert carries a fault code from Part 3, so the transmitter, the clinic system and any monitor site read it the same way.

| What happens | Fault code | Severity | Status of the system |
|---|---|---|---|
| Pacing needed but not capturing | `system.main-function-lost` | critical | failing |
| Capture threshold above half the output (safety margin below 2:1) | `system.main-function-degraded` | warning | degraded |
| Lead impedance outside 200 to 2000 ohms (possible fracture or insulation break) | `sensors.out-of-range` | error | degraded |
| Electrical noise sensed as heartbeats | `sensors.noisy` | warning | degraded |
| Battery at its elective replacement point | `power.battery-low` | error | degraded |
| Battery at end of life | `power.battery-failing` | critical | failing |
| Transmitter cannot reach the implant | `connectivity.link-lost` | warning | degraded |
| Transmitter silent for three Pulse intervals | `system.flatline` | | raised by HEART Hub |

The thresholds here are illustrations. A real product takes them from the implant's own specification.

---

## Step 6: No commands, and why there is no Stop button

The HEART has **no capabilities**: the Card lists none, and every `PUT`, `POST`, `PATCH` or `DELETE` is refused with `403 capability-not-allowed`. Programming stays where it is regulated: the clinician's programmer.

The standard requires a Stop control only from Autonomy Level A3 up, because A1 and A2 take no action and so have nothing to stop. This HEART takes no action at any level.

---

## Step 7: Tell a person

Autonomy Level A1 needs an escalation route. For a pacing system there are two, and both are needed:

1. **The clinic's own route**, as the transmitter already has: a flagged transmission, a call from the clinic.
2. **Locally, with no internet**: the transmitter's light or sound, so the patient knows to call.

Change `escalate()` to use them. HEART Hub (Step 8) adds a third: an email when the system goes silent.

---

## Step 8: Register and watch it on HEART Hub

HEART Hub lets an owner see a device's health from anywhere, on a private page.

1. **First start.** The transmitter makes a random device ID, claim code and key, keeps them, and shows the claim code only to the person holding it: on a label in the box, or on its screen.
2. **Sign in.** The owner opens `https://heartcortex.ai/login` and enters an email address. A 6-digit code arrives; there are no passwords.
3. **Register.** At `https://heartcortex.ai/register?id=<device ID>` (a QR code on the label can open it), the owner enters the claim code. Holding the device is the proof of ownership.
4. **Watch.** The device's page, `https://heartcortex.ai/device/<device ID>`, shows its status and open alerts, private to the owner until they share it. Their list of devices is at `https://heartcortex.ai/devices`.
5. **Silence.** If no report arrives for three Pulse intervals, the page shows a Flatline and the owner gets one email.

Only the public Pulse and public alerts are sent, and the site keeps only the status, timing and fault codes: never a reading, a heart rate or an episode.

**Privacy warning for a real product.** Even "this person's pacing system has a lead problem" is health information. A maker should run **its own** monitor site (the code is open, in `heart-monitor/`), under its own data-protection duties, rather than send patients' alerts to a public site. `heartcortex.ai` is right for the simulator and for trials, not for patients.

---

## Step 9: Try it with the simulator

```sh
python3 pacemakerSimulator/pacemakerSimulator.py --scenario all
```

It prints a device ID and claim code; register them as in Step 8 and watch the page while it stages each fault in turn: noise, a lost transmitter link (and so a gap in reports), a lead fracture, a loss of capture and a battery reaching its replacement point. Each fault is "fixed at the clinic" a few minutes later, so you can watch alerts open, escalate and resolve. Details and every option are in [`pacemakerSimulator/README.md`](../pacemakerSimulator/README.md).

---

## Step 10: Test it, rate it and claim only what passed

1. Run the **HEART-Rating client** (`heart-rating/client/heart_rating.py`) against the transmitter, and the hands-on tests of Part 9: cause each fault in the table of Step 5 with an implant simulator, cut the internet, cut the telemetry.
2. Publish a **Declaration** with every result.
3. Claim **HEART Basic, Autonomy Level A1**.

| Level | Fits a pacing system? |
|---|---|
| **A1** (notices and tells a person) | Yes: this guide |
| **A2** (says why, with a confidence) | Yes, on a transmitter at HEART Connected: "lead impedance rose from 550 to 3300 ohms in one night: likely fracture, confidence medium" |
| **A3 and above** (suggests or makes a fix) | **No**, for therapy. Changing a pacemaker is a clinical decision. A3 could only ever apply to the transmitter itself, for example restarting its own radio |

HEART conformance says nothing about medical-device approval. The implant and its transmitter still need their own (for example IEC 62304 for software, ISO 14971 for risk, ISO 14708 for active implants, and the regulator's route in each market).

---

## What the case study shows

- **Where HEART lives is a design decision.** For a device with no spare power, HEART lives one step away, in the unit that already reads it, and adds no new path into it.
- **A HEART with no commands is still useful.** Most of the value is noticing, explaining and telling the right person in a standard way.
- **"Public" must be decided per product.** For most devices a fault code is harmless. For an implant, even a fault code is health information, which is why the standard lets anyone run their own monitor site.
- **A patient's condition is not a device fault.** Keeping episodes as private events, and only system problems as alerts, keeps the two apart.
