# CarePulse Edge — hospital gateway (Phase 2)

A small Python service on a Linux mini-PC / VM inside the hospital network. It speaks to devices on the LAN and forwards everything securely (HTTPS, store-and-forward) to the hospital's CarePulse workspace.

| Input | How | Result in CarePulse |
|---|---|---|
| Bedside monitors / central stations | HL7 v2 **ORU^R01** over MLLP (IHE PCD-01), port 2575 | Vitals per bed → patient admitted in that bed (or PID UHID) · station · NEWS2 · charting |
| HIS admissions | HL7 v2 **ADT^A01/A02/A03/A04/A08** over MLLP | Patients, admissions, transfers, discharges, bedside-device binding |
| Monitor central station | Edge **sends ADT^A01/A03** when beds change | Patient name/UHID shown on the monitor |
| Fridge / room / gas sensors | **Modbus TCP** polling (fn 3/4; int16/uint16/int32/float32) or **MQTT** | Cold chain & environment locations, excursion alerts |
| ECG machines | **Folder watch** (PDF / XML / SCP / DICOM) | ECG documents; XML heart rate + patient ID extracted |

Python 3.9+ standard library only (MQTT needs `paho-mqtt`). Unit tests: `python3 -m unittest tests.test_hl7`.

## Install (10 minutes)
1. CarePulse → **Gateways & apps → Add gateway → Hospital edge gateway** (choose the ward if the edge serves one ward) → note the pairing code.
2. On the mini-PC (Ubuntu 22.04/24.04): copy the `edge/` folder, then
   `sudo ./install.sh SHIVA-123456 https://monitor.yourhospital.com`
3. Edit `/etc/carepulse/edge.json` (see `edge.sample.json`), then `sudo systemctl restart carepulse-edge`. Logs: `journalctl -u carepulse-edge -f`.
4. Firewall: allow inbound TCP 2575 from the monitor gateway / HIS interface engine only; outbound HTTPS 443 to CarePulse.

Edge appears online in Gateways & apps; if it stops sending for 15 minutes a critical "edge gateway offline" alert goes to biomedical / admin.

## Key settings (`edge.json`)
* `timezone` — e.g. `"+05:30"`; used when devices send times without an offset.
* `sample_seconds` — forward continuous vitals at most once per bed+parameter per N seconds (NIBP always forwarded). Default 60.
* `match_patient_id` — use PID-3 (MRN/UHID) to match patients; otherwise bed from PV1-3.
* `code_map` — site-specific overrides: `{"VENDOR_CODE_OR_TEXT": "spo2"}`; map to `""` to ignore a code. Unmapped codes are listed in the log every minute.
* `adt_out` — `host`/`port` of the monitor central station's HL7 ADT input.
* `modbus`, `folders`, `mqtt` — see the sample file.

## Vendor checklist (done with the vendor's service engineer)
* **Mindray** — enable HL7 output on BeneVision CMS / eGateway to the edge IP:2575 (IHE PCD-01, ORU^R01, interval 60 s). Bed labels in PV1-3 must match CarePulse bed numbers or HIS bed codes (Admin → Wards & beds).
* **Philips IntelliVue** — Information Center iX / IntelliBridge Enterprise HL7 outbound to edge:2575. Philips text labels (HR, SpO2, NBPs, NBPd, awRR, Temp) are mapped automatically.
* **GE CARESCAPE** — CARESCAPE Gateway HL7 outbound to edge:2575.
* **Indian / value monitors** — HL7 where available; otherwise share the serial/LAN protocol document so a driver can be added.
* Record each monitor model in the device library and run `docs/DEVICE_CERTIFICATION.md` before go-live.

## Bed & patient matching
Edge sends the HL7 location with several spellings (`ICU-3`, `3`, `ICU3`, `room-bed`). CarePulse matches `beds.his_bed_code` or `beds.bed_no` (within the ward when `his_ward_code` matches). The monitor is auto-registered and fixed to that bed, so later readings follow whoever is admitted in the bed. With HIS ADT flowing, bed assignments always follow the HIS.

## Clinical safety notes
* Monitor vitals are **not** charted to the HIS until a nurse confirms them on **Chart vitals**; corrected values keep the original for audit.
* The central station supports and does not replace bedside monitor alarms.
* NEWS2 is for non-pregnant adults; scale 2 SpO₂ only for confirmed hypercapnic respiratory failure (set per admission).


## Phase 3: waveforms, therapy devices and device alarms (edge 3.0)

| Feature | edge.json | Notes |
|---|---|---|
| Waveforms | `"waveforms": true`, `"waveform_channels": [...]`, `"waveform_rates": {"ecg":250,...}` | HL7 OBX value type **NA** (numeric array). Sample rate from an `MDC_ATTR_SAMP_RATE` OBX in the same message, else `waveform_rates`. Off by default: needs the vendor's waveform export licence/interface on the monitor gateway. Waveforms older than 10 minutes in the local queue are dropped after an outage (live data). |
| Ventilators, anaesthesia, pumps, dialysis, CTG | none – mapped automatically | MDC reference IDs as text (e.g. `MDC_PRESS_AWAY_END_EXP_POS` → PEEP, `MDC_FLOW_FLUID_PUMP` → infusion rate, `MDC_CONC_AWAY_SEVOFL_ET` → end-tidal agent). Vendor-specific labels go in `code_map`. String OBX values with DRUG / MODE in the identifier (drug name, vent mode) become the therapy label. |
| Device alarms | none | `ORU^R40` (IHE PCD Alert Communication Management): alarm OBX with priority in OBX-8 (`PH`/`PM`/`PL`) and an `ALERT_STATE` OBX (`start`/`continue`/`end`). Posted to `/api/v1/alarms`. **Verify the exact segment layout with each vendor before go-live** – alarm messages vary more than numerics. |
| Waveform channel override | `"code_map": {"WAVE:MY_ECG_LEAD_2": "ecg_ii"}` | Prefix waveform overrides with `WAVE:`. Unmapped channels appear in the heartbeat log. |
| MQTT devices | publish `{"device":..,"patient":..,"waveforms":[...]}` or `{"alarms":[...]}` | Forwarded as-is to the waveform / alarm API. |

Vendor checklist additions:
- **Mindray**: eGateway "real-time waveform" output (separate licence on some versions); BeneLink for ventilators (SV series) and anaesthesia (WATO / A-series) into the monitor network.
- **Philips**: IntelliBridge Enterprise or PIC iX HL7 waveform export; IntelliSpace Perinatal for CTG.
- **GE**: CARESCAPE Gateway waveform option; Aisys data through the same gateway.
- **Pumps**: B. Braun OneView / SpaceCom, Fresenius Vigilant Centerium, BD Alaris Systems Manager – ask for IHE PCD-01 (numerics) **and** ACM (alarms).
- **Dialysis**: Fresenius TDMS / Therapy Monitor HL7 or CSV export into an edge folder watch.

Clinical safety: waveforms and forwarded alarms are for review, teleconsult and escalation only. The bedside device and the bedside team
remain the primary alarm system. Do not market alarm forwarding as a primary alarm system without CDSCO and clinical-risk sign-off.

## Phase 4: BLE location gateways and nurse call inputs (edge 4.0)

| Feature | edge.json | Notes |
|---|---|---|
| BLE RTLS | `"rtls": {"interval": 2, "http_port": 8088, "http_host": "0.0.0.0", "topics": ["ble/gw/#"], "tag_prefixes": ["AC:23:3F"]}` | Gateways POST scans to `http://<edge>:8088/?gw=<id>` or publish on MQTT `ble/gw/<id>`. Strongest RSSI per tag + gateway per interval; button / tamper flags kept; batches older than 60 s dropped after an outage. Only MACs starting with `tag_prefixes` are uploaded (leave empty to upload all). See RTLS_SETUP.md. |
| Nurse call / bed exit via Modbus I/O | on a Modbus point: `"mask": 1, "nurse_call": {"ward_code": "W3", "bed_code": "W3-4", "type": "bed_exit"}` (or `"zone": "Room 12"`) | Edge-triggered: bit on → call, bit off → cancel; first poll only learns the state. Poll every 1 s. See NURSE_CALL.md. |

Firewall: open the RTLS HTTP port only to the BLE gateway VLAN.
