# CarePulse IoT — Device Adapter API v1

For device manufacturers, the CarePulse Connect app, hospital edge gateways and any system that sends readings.

## Authentication
Each hospital creates an **API key** (Gateways & apps → Add gateway → *API key*). Send it on every call:

    Authorization: Bearer cpg_<HOSPITALCODE>_<key>

Keys are per hospital, can be revoked any time and are shown only once. Rate limit: 600 calls/minute per key.

## POST /api/v1/readings

```json
{
  "device":  { "mac": "AA:BB:CC:DD:EE:FF", "serial": "SN123", "manufacturer": "Acme", "model": "BP-200",
               "ble_service": "1810", "battery": 82, "firmware": "1.4.2" },
  "patient": { "uhid": "UH240104" },
  "readings": [
    { "param": "bp_sys", "value": 132, "unit": "mmHg", "measured_at": "2026-11-17T08:10:00+05:30" },
    { "param": "bp_dia", "value": 84,  "unit": "mmHg", "measured_at": "2026-11-17T08:10:00+05:30" },
    { "param": "pulse",  "value": 72 }
  ]
}
```

* `device` — identify by `mac` and/or `serial`. Unknown devices are auto-registered (hospital setting) and appear in the device registry.
* `location` — optional. Bedside: `{ "ward_code": "ICU", "bed_code": "ICU-3", "candidates": ["ICU-3","3"] }` → patient admitted in that bed. Fridge / room sensors: `{ "name": "Blood bank fridge 1" }` → that monitored location (device is linked automatically).
* `patient` — optional. `{ "id" }`, `{ "uhid" }` or `{ "mobile" }`. If omitted, the reading goes to the patient the device is bound to; if none, it waits in **Readings to confirm** for staff.
* `measured_at` — ISO-8601, or epoch seconds / milliseconds. Missing = time received. Future (> 5 min) and > 400 days old are rejected.
* Offline upload: send `{ "batches": [ {device, patient, readings, batch_id}, ... ] }` (max 200 batches, 500 readings each).
* Duplicates (same device + parameter + time) are ignored and counted in `duplicates`.
* A patient without active consent is refused (`patient consent not on record`).

Response:
```json
{ "ok": true, "patient_assigned": true, "device_id": 38, "saved": 3, "duplicates": 0, "rejected": {},
  "alerts": [ { "id": 130, "severity": "critical", "message": "Ramesh K: Systolic BP 192 mmHg (critical high, limit 180)" } ] }
```

## Parameters (GET /api/v1/parameters)

| code | name | canonical unit | also accepted |
|---|---|---|---|
| bp_sys / bp_dia / bp_map | Blood pressure | mmHg | kPa |
| pulse, hr | Pulse / heart rate | /min | |
| spo2 | SpO₂ | % | |
| pi | Perfusion index | % | |
| temp | Temperature | Cel | F, [degF] |
| rr | Respiratory rate | /min | |
| glucose | Blood glucose | mg/dL | mmol/L |
| weight | Weight | kg | lb, [lb_av], g |
| bmi, body_fat | BMI, body fat | kg/m2, % | |
| etco2 | EtCO₂ | mmHg | |
| fridge_temp, room_temp, humidity, pressure_diff | Environment | Cel, %, Pa | |

Aliases such as `systolic`, `sys`, `heart_rate`, `temperature`, `sugar` are accepted. Values outside physiological range are rejected.

## Gateway endpoints (CarePulse Connect / edge gateway)
* `POST /api/v1/gateway/pair` `{code:"SHIVA-123456", device_info, app_version, platform}` → `{token, client, patient, schedule, limits, device_models}`
* `GET /api/v1/gateway/config` — patient, schedule, limits, known devices
* `POST /api/v1/gateway/heartbeat` `{battery, app_version, push_token, devices:[{mac, battery}]}`
* `GET /api/v1/device-models` — the Caresoft device library
* `GET /api/v1/health` — service status

## Edge gateway endpoints (Phase 2)
* `POST /api/v1/gateway/adt` — HL7 ADT relayed as JSON (same body as `/api/v1/his/adt`). Edge gateways only.
* `GET /api/v1/gateway/beds` — beds with the admitted patient (for ADT to monitor central stations).
* `POST /api/v1/documents` — multipart: `file` (PDF/XML/SCP/DICOM/PNG/JPG, ≤ 20 MB) + `meta` JSON `{doc_type:"ecg", title, patient:{uhid}, location:{bed_code}, device:{serial}, measured_at, values:{hr:96}}`. Unmatched documents wait in **ECG & documents** for staff to assign.
* Readings from edge gateways for admitted patients are accepted under the hospital admission consent (setting), and wait for nurse charting before going to the HIS.

## Phase 3 additions

### Context and history on readings
- `context` on a reading: `fasting`, `post_meal` … for glucose; `cgm` for continuous glucose; `wearable` for watch / Health Connect / HealthKit data.
  CGM and wearable streams are never auto-charted to the HIS.
- `"history": true` on a batch (phone back-fill, CSV-style uploads): values older than 2 hours are saved and flagged but do **not** raise alerts.

### Therapy state on a reading batch
```json
{"device":{"serial":"BB-SP-5531"},"patient":{"uhid":"IP880102"},
 "therapy":{"kind":"infusion","label":"Noradrenaline 8 mg in 50 mL","details":{"prescribed_rate":"6"}},
 "readings":[{"param":"infusion_rate","value":6,"unit":"mL/h"},{"param":"vtbi","value":14}]}
```
`kind`: `ventilation | anaesthesia | infusion | dialysis | ctg | oxygen`. Same label = same running session; a new label ends the old one;
`"state":"ended"` ends it. New parameters: `peep ppeak pplat vt mv fio2` (ventilator), `mac et_agent fgf bis` (anaesthesia),
`infusion_rate vtbi volume_infused` (pumps), `blood_flow uf_rate uf_volume venous_pressure arterial_pressure tmp dialysate_cond ktv` (dialysis),
`fhr mhr uc` (CTG), `resting_hr hrv hrv_rmssd active_energy` (wearables). Full list: `GET /api/v1/parameters`.

### POST /api/v1/waveforms
```json
{"device":{"serial":"MR-BV-1001"},"location":{"ward_code":"ICU","bed_code":"ICU-1"},
 "waveforms":[
   {"channel":"ecg_ii","sample_rate":250,"unit":"mV","start":"2026-11-18T10:00:00.000+05:30","samples":[0.01,0.02,0.9]},
   {"channel":"pleth","sample_rate":125,"start":1794990000000,"data_b64":"<int16 LE>","scale":0.01,"offset":0}]}
```
Channels: `ecg_i ecg_ii ecg_iii ecg_avr ecg_avl ecg_avf ecg_v ecg_v1 ecg_v5 pleth resp co2 art cvp pap paw flow volume ctg_fhr ctg_fhr2 ctg_mhr ctg_toco`.
Max 60 s per chunk, 40 chunks per batch, 50 batches per call (`{"batches":[…]}`). `start` = ISO time with milliseconds or epoch ms.
A resend of the same device + channel + start is ignored. Needs a patient (or a bed with an admitted patient).
Monitor waveforms are kept `waveform_retention_hours` (default 72); CTG is kept unless `ctg_retention_hours` is set; saved strips are kept.
Recommended chunk size: 1 s for live monitors, 5–60 s for CTG and patches.

### POST /api/v1/alarms
```json
{"device":{"serial":"BB-SP-5532"},"patient":{"uhid":"IP880103"},
 "alarms":[{"code":"OCCLUSION","text":"Downstream occlusion","priority":"high","state":"active","at":"2026-11-18T10:35:00+05:30"}]}
```
`priority`: high → critical alert, medium → warning, low → info (logged, nobody paged). One open alert per device + code + patient;
repeats count up; `"state":"ended"` closes it ("cleared at the device") and stops escalation.

### Documents: stethoscope and CTG
`POST /api/v1/documents` (multipart) now accepts WAV / MP3 / M4A with `meta.doc_type = "audio"` and `meta.site`
(`aortic pulmonic tricuspid mitral lung_ul lung_ur lung_ll lung_lr lung_post abdomen carotid other`), and `doc_type = "ctg"` for CTG PDFs.

### Voice call callbacks (provider → CarePulse)
`/api/v1/voice/{client}/{token}/say | digits | status` and, for Exotel flows, `/api/v1/voice/{client}/exotel/say | digits?CustomField={token}`.
See ESCALATION_VOICE.md.

## Phase 4 additions

### POST /api/v1/rtls/sightings — BLE location (gateway token)
```json
{"sightings": [
  {"tag": "AC:23:3F:00:01:01", "anchor": "GW-ICU1", "rssi": -58, "battery": 87},
  {"tag": "AC233F000101",      "anchor": "GW-ICU2", "rssi": -71},
  {"tag": "AC:23:3F:00:02:02", "anchor": "GW-MATERNITYW", "rssi": -60, "tamper": true},
  {"tag": "AC:23:3F:00:01:03", "anchor": "GW-CORRIDOR", "rssi": -55, "button": 1, "at": "2026-11-18T10:15:02+05:30"}
]}
```
→ `{"ok": true, "tags": 3, "moved": 1, "unknown_tags": 0, "unknown_anchors": 0, "alerts": 1}`. Up to 5000 sightings per call.
`tag` / `anchor` may also be sent as `mac` / `gateway`; MACs in any separator style are normalised. Send every 1–5 s per gateway
(strongest RSSI per tag + gateway). Unknown tags / gateways are counted and ignored — register them in *Floor maps*. Room logic,
hysteresis and alert rules: RTLS_SETUP.md.

### POST /api/v1/nurse-calls — nurse call, bed exit, call buttons (gateway token)
```json
{"location": {"ward_code": "W3", "bed_code": "W3-4"}, "type": "bathroom", "state": "call", "source": "Ascom", "at": "…"}
```
`type`: normal, bathroom, staff_assist, code_blue, bed_exit, pain, other · `state`: call | presence | cancel · location by bed
(`ward_code` + `bed_code`) or `{"zone": "<room name on floor map>"}`. Single event → `{"ok": true, "id": 812, "new": true}`;
`{"events": [...]}` (≤ 200) → `{"ok": true, "results": [...]}`; unknown location → `{"ok": false, "error": "bed or zone not found"}`.
Details: NURSE_CALL.md.

### Utilities through /api/v1/readings
Gas, LMO, power, water and HVAC monitoring points use the normal readings call with `"location": {"name": "Oxygen manifold – main plant room"}`
(or `"env_id"`). New parameter codes: `o2_pressure`, `air_pressure`, `n2o_pressure` (bar; psi/kPa/MPa accepted), `vacuum` (kPa),
`cylinder_bank` (bar), `lmo_level` (%), `o2_purity` (%), `voltage` (V), `power_kw`, `ups_battery` (%), `dg_fuel` (%),
`water_level` (%), `chiller_temp` (°C), `co2_ppm`.

## Phase 5 additions

### POST /api/v1/doses — smart pill dispensers, inhaler sensors, adherence apps
`{"device":{"serial":"HERO-77812"},"patient":{"uhid":"…"},"events":[{"type":"dispensed|taken|missed|skipped|puff|refill_low","at":"…","slot":"A1","medication":"Metformin","medication_id":12,"puffs":2}]}`
→ `{"ok":true,"patient_id":12,"results":[{"ok":true,"medication_id":4,"id":901,"status":"taken|late|extra|puff|missed|skipped","scheduled_at":"…"}]}`. Details: MEDICATION_DEVICES.md.

### GET /api/v1/medications — patient-app token only
Today's doses for the paired patient: `{"ok":true,"date":"2026-11-18","doses":[{"medication_id":4,"name":"Metformin","dose":"500 mg","kind":"tablet","slot":"08:30","status":"taken"|null}]}`.

### GET /api/v1/health — uptime monitors
Public: `{"ok":true,"service":"CarePulse IoT","version":"5.0","time":"…"}` (HTTP 503 with `failing` when the database, worker, disk or message queue fails).
With `?key=<monitor key from Level 1 → System health>`: every check with status and detail.

### AI model hook (outbound, optional)
If a hospital sets its own risk model URL, CarePulse POSTs `{"model_input":"carepulse-risk-features-v1","features":{…},"builtin":{…}}` and
expects `{"score":0-100,"model":"…","factors":[…]}` within 5 s. See AI_MODEL_CARD.md.

## Certification
See DEVICE_CERTIFICATION.md. Certified models show a ✓ in every hospital's device library.
