Close Menu
  • Articles
    • Learn Electronics
    • Product Review
    • Tech Articles
  • Electronics Circuits
    • 555 Timer Projects
    • Op-Amp Circuits
    • Power Electronics
  • Microcontrollers
    • Arduino Projects
    • STM32 Projects
    • AMB82-Mini IoT AI Camera
    • BLE Projects
  • IoT Projects
    • ESP8266 Projects
    • ESP32 Projects
    • ESP32 MicroPython
    • ESP32-CAM Projects
    • LoRa/LoRaWAN Projects
  • Raspberry Pi
    • Raspberry Pi Projects
    • Raspberry Pi Pico Projects
    • Raspberry Pi Pico W Projects
  • Electronics Calculator
Facebook X (Twitter) Instagram
  • About Us
  • Disclaimer
  • Privacy Policy
  • Contact Us
  • Advertise With Us
Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
How To Electronics
  • Articles
    • Learn Electronics
    • Product Review
    • Tech Articles
  • Electronics Circuits
    • 555 Timer Projects
    • Op-Amp Circuits
    • Power Electronics
  • Microcontrollers
    • Arduino Projects
    • STM32 Projects
    • AMB82-Mini IoT AI Camera
    • BLE Projects
  • IoT Projects
    • ESP8266 Projects
    • ESP32 Projects
    • ESP32 MicroPython
    • ESP32-CAM Projects
    • LoRa/LoRaWAN Projects
  • Raspberry Pi
    • Raspberry Pi Projects
    • Raspberry Pi Pico Projects
    • Raspberry Pi Pico W Projects
  • Electronics Calculator
How To Electronics
Home » ESP32 Patient Health Monitor (ECG, SpO₂, BPM) & Live Dashboard
ESP32 Projects IoT Projects

ESP32 Patient Health Monitor (ECG, SpO₂, BPM) & Live Dashboard

Mamtaz AlamBy Mamtaz Alam13 Mins Read
Share Facebook Twitter LinkedIn Telegram Reddit WhatsApp
ESP32 Patient Health Monitor (ECG, SpO₂, BPM) & Live Dashboard
Share
Facebook Twitter LinkedIn Pinterest Email Reddit Telegram WhatsApp

Overview

In this IoT project, we will learn how to build an ESP32 Patient Health Monitor with Live Web Dashboard using ESP32, AD8232 ECG Sensor, MAX30102 Pulse Oximeter, BME280 Environmental Sensor, ADS1115 ADC, and a 10K NTC thermistor for body temperature measurement. The ESP32 Wi-Fi module connects the system to a local network and hosts a professional medical-style web dashboard directly from the device.

This ESP32-based patient health monitoring system measures and displays heart rate (BPM) from the ECG signal, blood oxygen (SpO₂) from the MAX30102 sensor, body temperature from an NTC thermistor, and room temperature & humidity from the BME280 sensor. The dashboard shows a live scrolling ECG waveform with PQRST-style cardiac trace, animated vitals cards, clinical alerts, patient record management, and data logging with Excel export.

The live web dashboard makes this project more advanced by providing a user-friendly interface for real-time vitals monitoring, ECG waveform viewing, patient details storage, interval-based vitals logging, and clinical alert notifications. This project is a practical and low-cost solution for building a remote patient monitoring system for education, prototyping, and IoT healthcare applications.

You may go through some old projects like:

  • IoT Patient Health Monitor with Arduino & ESP8266
  • IoT Patient Health Monitor with ESP32 Web Server




Components Required

Following are the components required to make the ESP32 Patient Health Monitor with Live Web Dashboard. All these components can be purchased from the given links.

S.N.Components NameQuantityPurchase Link
1ESP32 Board1Amazon | AliExpress
2AD8232 ECG Sensor1Amazon | AliExpress
3MAX30102 Pulse Oximeter1Amazon | AliExpress
4ADS1115 ADC Module1Amazon | AliExpress
5BME280 Sensor1Amazon | AliExpress
610K NTC Thermistor1Amazon | AliExpress
710K Resistor1Amazon | AliExpress
810uF Electrolytic Capacitor1Amazon | AliExpress
90.1uF Ceramic Capacitor5Amazon | AliExpress
10Jumper Wires4Amazon | AliExpress

Block Diagram of ESP32 Patient Health Monitor

Let’s take a look at the block diagram of the ESP32-based Patient Health Monitor with Live Web Dashboard.

Block Diagram ESP32 Patient Health Monitor
Fig: Block Diagram ESP32 Patient Health Monitor

The system is divided into four main sensor paths connected to the ESP32 DevKit v1:

  • ECG path — AD8232 → ADS1115 AIN0 → ESP32 (BPM + waveform)
  • SpO₂ path — MAX30102 → I2C → ESP32 (blood oxygen)
  • Body temperature path — 10K NTC divider → ADS1115 AIN1 → ESP32
  • Environment path — BME280 → I2C → ESP32 (room temp + humidity)

The ESP32 reads all sensor data, calculates BPM from ECG R-peaks, hosts REST APIs, and serves the live dashboard through the built-in web server. Any phone, tablet, or PC on the same Wi-Fi network can open the ESP32 IP address to view real-time vitals and the ECG waveform.


AD8232 ECG Sensor Module

The AD8232 ECG sensor module is a single-lead heart rate monitor front-end used to acquire biopotential signals from the human body. It includes an integrated instrumentation amplifier, filter, and right-leg drive circuitry to produce a clean analog ECG output suitable for microcontroller ADC input. Go through AD8232 Arduino Tutorial for more info.

AD8232 ECG Sensor
Fig: AD8232 ECG Sensor

The module outputs an analog ECG signal that is read by the microcontroller ADC Pin. It also provides lead-off detection (LO+ and LO−) pins, which go HIGH when electrodes lose contact with the skin. This helps the firmware and dashboard show a safe flat-line trace and a “LEADS OFF” warning instead of displaying invalid cardiac data.

Features & Specifications

Feature Specification
Operating Voltage 3.3V (compatible with ESP32)
Output Type Analog ECG signal (ECG_OUT)
Lead Configuration Single-lead (3-electrode: RA, LA, RL)
Lead-Off Detection LO+ and LO− digital outputs
Shutdown Pin SDN (GPIO 5 — HIGH = enable)
Applications Heart rate monitoring, ECG waveform display

Electrode Placement

  • Red (RA) → Right Arm or right wrist
  • Yellow (LA) → Left Arm or left wrist
  • Green (RL) → Right Leg or lower abdomen (driven reference)
Fig: Typical Electrode Placement




MAX30102 Pulse Oximeter Sensor

The MAX30102 is an integrated pulse oximetry sensor module. It uses red and infrared LEDs with a photodetector to measure light absorption through the finger and calculate SpO₂ (blood oxygen saturation). Go through MAX30102 Arduino Tutorial for more info.

Fig: Different MAX30102 Modules

In this project, the MAX30102 communicates with the ESP32 over I2C at address 0x57. It can measure Heart Beat in BPM, Blood Oxygen Concentration in percentage and temperature as well. In this project, the MAX30102 is used to only measure Blood Oxygent Concentration SPO2 (%).

Feature Specification
Interface I2C @ 0x57
Measurement SpO₂ (%), finger detection
Operating Voltage 3.3V (module level)
Normal SpO₂ Range 95% – 100%

BME280 Environmental Sensor

The BME280 is a high-precision digital sensor that combines temperature, humidity, and barometric pressure measurement in a single compact module. In this project, it is used specifically for room environmental monitoring — tracking ambient temperature and relative humidity. Refer to ESP32 BME280 Tutorial for more detailed guide.

Fig: BME280 Environmental Sensor Module

Features & Specifications

Feature Specification
Interface I2C @ 0x76 (ADDR = GND)
Temperature Range −40°C to +85°C
Humidity Range 0% to 100% RH
Accuracy (Temp) ±1°C typical
Library Adafruit BME280 + Adafruit Unified Sensor
Update Rate in Firmware Every 2 seconds




10K NTC Thermistor (Body Temperature Sensor)

Body temperature is measured using a 10K NTC thermistor in a classic voltage divider circuit. Unlike the BME280 which measures room air temperature digitally over I2C, the NTC probe measures skin or body contact temperature through an analog signal read by the ADS1115.

Fig: 10K NTC Thermistor

NTC Voltage Divider Circuit

The thermistor circuit uses:

  • R2 — 10K fixed series resistor to 3.3V
  • R3 — 10K NTC thermistor to GND
  • TEMP_SENSE node → ADC of MCU

As body temperature increases, NTC resistance decreases and the voltage at ADC rises.

Specifications

Parameter Value
ADS1115 Channel AIN1 (not AIN0)
Thermistor 10K NTC @ 25°C
Series Resistor (R2) 10K ohm
Supply Voltage 3.3V
Beta Coefficient 3950
ADS Gain GAIN_ONE (±4.096V)
Typical Skin Reading ~35°C – 37°C with good contact




ADS1115 16-Bit ADC

The ADS1115 is a 16-bit analog-to-digital converter that communicates through the I2C interface. It is commonly used when a microcontroller needs to read analog signals with higher resolution than its built-in ADC. You may follow ADS1115 ESP32 Guide for more information.

ADS1115

  • 16-bit resolution for accurate analog signal measurement
  • I2C interface for easy connection with microcontrollers
  • Four analog input channels: AIN0, AIN1, AIN2, and AIN3
  • Programmable gain amplifier for measuring small voltage signals
  • Configurable data rate for different sampling requirements

The ADS1115 can be used to measure different types of analog signals such as sensor outputs, voltage dividers, battery voltage, pressure sensors, temperature sensors, and other low-voltage signals. Its programmable gain settings make it useful for both general-purpose analog readings and more sensitive signal measurements.


Circuit Diagram

Let’s take a look at the schematic of the ESP32-based Patient Health Monitor project. The schematic is designed in EasyEDA.

Schematic ESP32 Patient Health Monitor
Fig: Schematic ESP32 Patient Health Monitor

Main Circuit Blocks

The schematic (Board1, Version V1.0) contains five functional blocks connected to the ESP32:

Ref Module Role
U1 ESP32 DevKit-v1 Main MCU, Wi-Fi, web server
U3 AD8232 ECG analog front-end
U4 MAX30102 Pulse oximeter (SpO₂)
U5 BME280 Room temperature & humidity
U6 ADS1115 16-bit ADC for ECG + NTC

ESP32 Pin Connections

ESP32 Pin GPIO Connected To
D21 GPIO 21 I2C SDA (shared bus)
D22 GPIO 22 I2C SCL (shared bus)
D5 GPIO 5 AD8232 SDN (sensor enable, HIGH = run)
D18 GPIO 18 AD8232 LO+ (lead-off detect)
D19 GPIO 19 AD8232 LO− (lead-off detect)

I2C Device Addresses

Device I2C Address Bus Pins
ADS1115 (U6) 0x48 SDA / SCL
MAX30102 (U4) 0x57 SDA / SCL
BME280 (U5) 0x76 SDA / SCL (ADDR = GND)

AD8232 ECG Signal Path

  • ECG_OUT → ADS1115 A0 (AIN0)
  • ECG_SDN → ESP32 GPIO 5 (OUTPUT HIGH in setup)
  • LO+ → ESP32 GPIO 18 (INPUT)
  • LO− → ESP32 GPIO 19 (INPUT)
  • 3.3V / GND → AD8232 power with decoupling capacitors

NTC Body Temperature Divider

  • 3.3V → R2 (10K) → TEMP_SENSE node → R3 (10K NTC) → GND
  • TEMP_SENSE → ADS1115 A1 (AIN1)

Power Supply & Decoupling

All modules run from 3.3V. The schematic includes decoupling capacitors on each sensor rail:

  • C1 — 10µF bulk capacitor
  • C2, C4, C5, C6, C7 — 100nF ceramic capacitors near IC power pins

These capacitors reduce power supply noise and help keep the ECG trace clean on the dashboard.




PCB Designing & Gerber Files

The schematic of the ESP32 Patient Health Monitor was created in EasyEDA, and from there it was converted into a compact PCB layout.

Fig: PCB Designing

The board is designed with mostly through-hole components to make assembly easier. You can view the 2D view of the PCB.

Fig: PCB 3D View

All of the critical components, including the ESP32 module, ADS1115, sensor connectors, and power filtering capacitors, are placed on the front side of the PCB, which makes assembly easier and more reliable.

Here are the links of files that you can download for PCB manufacturing and PCB assembly services.

  1. Download: Schematic PDF
  2. Download: Gerber File




PCB Ordering Online & Assembly

The Gerber file for this ESP32 Patient Health Monitor is provided above. You can download the Gerber file and place an order with a PCB manufacturer like AIVON for as low as $1 for a PCB Prototype.

To order the PCB, visit the AIVON Official Website and upload the Gerber file using the Quote Now option. You can then choose your required parameters, such as Material Type, Dimensions, Quantity, Thickness, and Solder Mask Color.

AIVON is making PCB prototyping and assembly more affordable for new users by offering $1 PCB Prototype and $35 PCB Assembly with Shipping fee $30 OFF on your first PCB order. With this promotion, you can enjoy free shipping on your first order and affordable assembly service for your project.

Here is the promotion link: AIVON PCB/PCBA Promotion Offer

Once all the details are filled in, select your country and shipping method. After confirming everything, you can place the order and wait for your boards to arrive.




Assembly of the ESP32 Patient Health Monitor

After I ordered the custom PCB, I received it within just 3 days. The PCB quality was very good, and it looked clean and professional. It is a double-sided PCB, which makes the circuit compact and neat.

PCB for ESP32 Patient Health Monitor
Fig: PCB for ESP32 Patient Health Monitor

Then I started soldering and assembling all the components on the board. For the ESP32 board, ADS1115, MAX30102, BME280, and AD8232 ECG module, I used female header pins where needed. This makes it easy to remove or replace the modules later if required.

I also soldered the required decoupling capacitors (10µF and 100nF) on different parts of the PCB as shown in the schematic. These capacitors help to keep the power supply stable and reduce noise in the ECG signal. For the MAX30102 module and NTC thermistor probe, I used jumper wires to connect them to the PCB terminal blocks.

After soldering all the parts, I connected the ECG electrode cable, SpO₂ sensor, and NTC temperature probe, then completed the final assembly of the IoT ESP32 Patient Health Monitor device.

ESP32 AD8232 MAX30102 Thermistor ADS1115


Source Code / Program

Let us take a look at the programming part of this project.

The code starts by including the required libraries for Wi-Fi, web server, I2C sensors, and the dashboard page stored in PROGMEM. The WiFi and WebServer libraries are used to connect the ESP32 to the local network and host the live patient health dashboard. The Adafruit ADS1X15 library reads ECG and NTC values from the ADS1115. The Adafruit BME280 library reads room temperature and humidity. The SparkFun MAX3010x library with spo2_algorithm.h calculates SpO₂ from MAX30102 data.

In the Wi-Fi section, the SSID and password are added so the ESP32 can connect to the network. After connecting, the ESP32 prints its IP address in the Serial Monitor at 115200 baud. This IP address can be opened in a browser to access the professional web dashboard.

The code is divided into two main parts: the main Patient_Health_Monitor.ino file for ESP32 sensor control and API, and the dashboard_page.h file for the live web dashboard interface.



Main .ino code

Copy the following code and paste it to your Arduino IDE editor window. Create a new sketch folder named Patient_Health_Monitor and save this file as Patient_Health_Monitor.ino.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*
* Patient Health Monitor
*
* I2C (SDA=21, SCL=22): BME280 @0x76, ADS1115 @0x48, MAX30102 @0x57
* ADS1115 AIN0: AD8232 ECG   AIN1: NTC body temp
* ECG_SDN -> D5, LO+ -> D18, LO- -> D19
*/
 
#include <WiFi.h>
#include <WebServer.h>
#include <Wire.h>
#include <math.h>
#include <Adafruit_ADS1X15.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <MAX30105.h>
#include <spo2_algorithm.h>
#include "dashboard_page.h"
 
const char* WIFI_SSID = "****************";
const char* WIFI_PASSWORD = "***************";
 
static const int I2C_SDA_PIN = 21;
static const int I2C_SCL_PIN = 22;
static const int ECG_SDN_PIN = 5;
static const int LO_PLUS_PIN = 18;
static const int LO_MINUS_PIN = 19;
 
static const uint8_t ECG_CHANNEL = 0;
static const uint8_t THERMISTOR_CHANNEL = 1;
static const uint8_t ADS1115_I2C_ADDR = 0x48;
static const uint8_t BME280_I2C_ADDR = 0x76;
 
static const uint16_t SAMPLE_INTERVAL_MS = 8;
static const uint16_t SLOW_SENSOR_MS = 2000;
static const uint8_t ECG_QUEUE_SIZE = 28;
 
static const float SUPPLY_VOLTAGE = 3.3f;
static const float SERIES_RESISTOR_OHMS = 10000.0f;
static const float NTC_NOMINAL_OHMS = 10000.0f;
static const float NTC_NOMINAL_TEMP_C = 25.0f;
static const float NTC_BETA = 3950.0f;
 
static const long FINGER_IR_THRESHOLD = 50000;
static const int32_t SPO2_BUFFER_LENGTH = 100;
static const int32_t SPO2_SHIFT_SAMPLES = 25;
 
WebServer server(80);
Adafruit_ADS1115 ads;
Adafruit_BME280 bme;
MAX30105 particleSensor;
 
bool bmeOk = false;
bool maxOk = false;
 
unsigned long lastSampleMs = 0;
unsigned long lastSlowMs = 0;
unsigned long lastDebugMs = 0;
 
int lastEcgValue = 512;
int lastRawAdc = 0;
float lastVoltage = 0.0f;
bool lastLeadsOff = true;
int lastLoPlus = 0;
int lastLoMinus = 0;
 
int ecgQueue[ECG_QUEUE_SIZE];
volatile uint8_t ecgQWrite = 0;
volatile uint8_t ecgQRead = 0;
 
int ecgBpm = -1;
int32_t ecgBaseline = 512;
int ecgSignalLevel = 0;
bool ecgBeatArmed = true;
unsigned long lastRPeakMs = 0;
 
float roomTempC = 0.0f;
float roomHumidity = 0.0f;
float bodyTempC = -999.0f;
int spo2Pct = -1;
bool fingerDetected = false;
 
uint32_t irBuffer[100];
uint32_t redBuffer[100];
int32_t spo2 = 0;
int8_t validSPO2 = 0;
int32_t maximHeartRate = 0;
int8_t validMaximHeartRate = 0;
 
byte sampleIndex = 0;
bool bufferFilled = false;
 
char jsonBuffer[384];
 
bool leadsOff() {
  lastLoPlus = digitalRead(LO_PLUS_PIN);
  lastLoMinus = digitalRead(LO_MINUS_PIN);
  return (lastLoPlus == HIGH) || (lastLoMinus == HIGH);
}
 
float readChannelVoltage(uint8_t channel) {
  int32_t sum = 0;
  for (uint8_t i = 0; i < 4; i++) {
    sum += ads.readADC_SingleEnded(channel);
    yield();
  }
  return ads.computeVolts((int16_t)(sum / 4));
}
 
float ntcResistanceFromVoltage(float voltage) {
  if (voltage <= 0.001f || voltage >= SUPPLY_VOLTAGE - 0.001f) {
    return NAN;
  }
  return SERIES_RESISTOR_OHMS * voltage / (SUPPLY_VOLTAGE - voltage);
}
 
float ntcResistanceToCelsius(float resistance) {
  if (isnan(resistance) || resistance <= 0.0f) {
    return NAN;
  }
  float steinhart = resistance / NTC_NOMINAL_OHMS;
  steinhart = log(steinhart);
  steinhart /= NTC_BETA;
  steinhart += 1.0f / (NTC_NOMINAL_TEMP_C + 273.15f);
  steinhart = 1.0f / steinhart;
  return steinhart - 273.15f;
}
 
float readBodyTemperatureC() {
  const float voltage = readChannelVoltage(THERMISTOR_CHANNEL);
  const float resistance = ntcResistanceFromVoltage(voltage);
  return ntcResistanceToCelsius(resistance);
}
 
int readEcgValue() {
  lastRawAdc = ads.readADC_SingleEnded(ECG_CHANNEL);
  lastVoltage = ads.computeVolts(lastRawAdc);
  return map(lastRawAdc, 0, 32767, 0, 1023);
}
 
void ecgQueueClear() {
  ecgQRead = 0;
  ecgQWrite = 0;
}
 
void ecgQueuePush(int value) {
  const uint8_t next = (uint8_t)((ecgQWrite + 1) % ECG_QUEUE_SIZE);
  if (next == ecgQRead) {
    ecgQRead = (uint8_t)((ecgQRead + 1) % ECG_QUEUE_SIZE);
  }
  ecgQueue[ecgQWrite] = value;
  ecgQWrite = next;
}
 
uint8_t ecgQueueDrain(int* out, uint8_t maxOut) {
  uint8_t count = 0;
  while (ecgQRead != ecgQWrite && count < maxOut) {
    out[count++] = ecgQueue[ecgQRead];
    ecgQRead = (uint8_t)((ecgQRead + 1) % ECG_QUEUE_SIZE);
  }
  return count;
}
 
void resetEcgBpm() {
  ecgBpm = -1;
  ecgBaseline = 512;
  ecgSignalLevel = 0;
  ecgBeatArmed = true;
  lastRPeakMs = 0;
  ecgQueueClear();
}
 
void updateEcgBpm(int sample) {
  ecgBaseline = (ecgBaseline * 995 + sample * 5) / 1000;
  const int hp = abs(sample - (int)ecgBaseline);
 
  ecgSignalLevel = (ecgSignalLevel * 127 + hp) / 128;
  const int threshold = max(18, (ecgSignalLevel * 3) / 2);
 
  if (hp > threshold && ecgBeatArmed) {
    const unsigned long now = millis();
    if (lastRPeakMs > 0) {
      const unsigned long interval = now - lastRPeakMs;
      if (interval >= 300 && interval <= 2000) {
        const int bpm = (int)(60000UL / interval);
        ecgBpm = (ecgBpm < 0) ? bpm : ((ecgBpm * 3) + bpm) / 4;
      }
    }
    lastRPeakMs = now;
    ecgBeatArmed = false;
  } else if (hp < threshold / 3) {
    ecgBeatArmed = true;
  }
}
 
void updateEcgSample() {
  const unsigned long now = millis();
  if (now - lastSampleMs < SAMPLE_INTERVAL_MS) {
    return;
  }
  lastSampleMs = now;
 
  lastLeadsOff = leadsOff();
  if (lastLeadsOff) {
    resetEcgBpm();
    lastEcgValue = 512;
    ecgQueuePush(512);
  } else {
    lastEcgValue = readEcgValue();
    ecgQueuePush(lastEcgValue);
    updateEcgBpm(lastEcgValue);
  }
}
 
void shiftBuffers() {
  for (byte i = SPO2_SHIFT_SAMPLES; i < SPO2_BUFFER_LENGTH; i++) {
    redBuffer[i - SPO2_SHIFT_SAMPLES] = redBuffer[i];
    irBuffer[i - SPO2_SHIFT_SAMPLES] = irBuffer[i];
  }
  sampleIndex = SPO2_BUFFER_LENGTH - SPO2_SHIFT_SAMPLES;
}
 
void calculateSpO2() {
  maxim_heart_rate_and_oxygen_saturation(
    irBuffer, SPO2_BUFFER_LENGTH, redBuffer,
    &spo2, &validSPO2, &maximHeartRate, &validMaximHeartRate
  );
}
 
void updateSpO2Reading() {
  if (fingerDetected && validSPO2 && spo2 > 0 && spo2 <= 100) {
    spo2Pct = (int)spo2;
  } else {
    spo2Pct = -1;
  }
}
 
void updateMax30102() {
  if (!maxOk) {
    return;
  }
 
  particleSensor.check();
 
  while (particleSensor.available()) {
    const uint32_t irValue = particleSensor.getIR();
    const uint32_t redValue = particleSensor.getRed();
    particleSensor.nextSample();
 
    fingerDetected = (irValue >= FINGER_IR_THRESHOLD);
 
    if (!bufferFilled) {
      redBuffer[sampleIndex] = redValue;
      irBuffer[sampleIndex] = irValue;
      sampleIndex++;
      if (sampleIndex >= SPO2_BUFFER_LENGTH) {
        bufferFilled = true;
        calculateSpO2();
        sampleIndex = SPO2_BUFFER_LENGTH - SPO2_SHIFT_SAMPLES;
        updateSpO2Reading();
        server.handleClient();
      }
    } else {
      redBuffer[sampleIndex] = redValue;
      irBuffer[sampleIndex] = irValue;
      sampleIndex++;
      if (sampleIndex >= SPO2_BUFFER_LENGTH) {
        shiftBuffers();
        calculateSpO2();
        updateSpO2Reading();
        server.handleClient();
      }
    }
 
    yield();
    server.handleClient();
  }
}
 
void updateSlowSensors() {
  const unsigned long now = millis();
  if (now - lastSlowMs < SLOW_SENSOR_MS) {
    return;
  }
  lastSlowMs = now;
 
  if (bmeOk) {
    roomTempC = bme.readTemperature();
    roomHumidity = bme.readHumidity();
  }
 
  const float body = readBodyTemperatureC();
  bodyTempC = isnan(body) ? -999.0f : body;
 
  if (now - lastDebugMs >= 2000) {
    lastDebugMs = now;
    Serial.printf(
      "Room: %.1f C  Hum: %.1f%%  Body: %.1f C  SpO2: %d%% (valid=%d)  Finger: %s\n",
      roomTempC, roomHumidity, bodyTempC, spo2Pct, validSPO2, fingerDetected ? "yes" : "no"
    );
    Serial.printf(
      "ECG plot=%d  raw=%d  %.3fV  bpm=%d  leads=%s\n",
      lastEcgValue, lastRawAdc, lastVoltage, ecgBpm, lastLeadsOff ? "OFF" : "ON"
    );
  }
}
 
void handleRoot() {
  server.send_P(200, "text/html", DASHBOARD_PAGE);
}
 
void handleEcgApi() {
  int samples[ECG_QUEUE_SIZE];
  uint8_t count = ecgQueueDrain(samples, ECG_QUEUE_SIZE);
  if (count == 0) {
    samples[0] = lastEcgValue;
    count = 1;
  }
 
  char* p = jsonBuffer;
  int rem = (int)sizeof(jsonBuffer);
  int n = snprintf(p, rem, "{\"v\":[");
  p += n;
  rem -= n;
 
  for (uint8_t i = 0; i < count && rem > 12; i++) {
    if (i > 0) {
      *p++ = ',';
      rem--;
    }
    n = snprintf(p, rem, "%d", samples[i]);
    p += n;
    rem -= n;
  }
 
  snprintf(
    p, rem,
    "],\"lo\":%d,\"raw\":%d,\"mv\":%d,\"lp\":%d,\"lm\":%d,\"bpm\":%d}",
    lastLeadsOff ? 1 : 0,
    lastRawAdc,
    (int)(lastVoltage * 1000.0f),
    lastLoPlus,
    lastLoMinus,
    ecgBpm
  );
 
  server.sendHeader("Cache-Control", "no-cache");
  server.send(200, "application/json", jsonBuffer);
}
 
void handleVitalsApi() {
  snprintf(
    jsonBuffer, sizeof(jsonBuffer),
    "{\"roomT\":%.1f,\"hum\":%.1f,\"bodyT\":%.1f,\"spo2\":%d,\"spo2Valid\":%d,\"finger\":%d,\"bme\":%d}",
    roomTempC,
    roomHumidity,
    bodyTempC,
    spo2Pct,
    (validSPO2 && fingerDetected) ? 1 : 0,
    fingerDetected ? 1 : 0,
    bmeOk ? 1 : 0
  );
 
  server.sendHeader("Cache-Control", "no-cache");
  server.send(200, "application/json", jsonBuffer);
}
 
void setupWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
 
  Serial.print(F("Connecting to WiFi"));
  uint8_t attempts = 0;
  while (WiFi.status() != WL_CONNECTED && attempts < 40) {
    delay(500);
    Serial.print('.');
    attempts++;
  }
  Serial.println();
 
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println(F("WiFi failed."));
    return;
  }
 
  Serial.print(F("Open: http://"));
  Serial.println(WiFi.localIP());
}
 
void setup() {
  Serial.begin(115200);
  delay(500);
 
  pinMode(ECG_SDN_PIN, OUTPUT);
  digitalWrite(ECG_SDN_PIN, HIGH);
  pinMode(LO_PLUS_PIN, INPUT);
  pinMode(LO_MINUS_PIN, INPUT);
 
  Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN);
 
  if (!ads.begin(ADS1115_I2C_ADDR)) {
    Serial.println(F("ERROR: ADS1115 not found"));
    while (true) {
      delay(1000);
      yield();
    }
  }
  ads.setGain(GAIN_ONE);
  ads.setDataRate(RATE_ADS1115_128SPS);
  Serial.println(F("ADS1115 OK (ECG AIN0, NTC AIN1)"));
 
  bmeOk = bme.begin(BME280_I2C_ADDR);
  Serial.println(bmeOk ? F("BME280 OK") : F("BME280 not found"));
 
  maxOk = particleSensor.begin(Wire, I2C_SPEED_FAST);
  if (maxOk) {
    particleSensor.setup(60, 4, 2, 100, 411, 4096);
    particleSensor.setPulseAmplitudeGreen(0);
    Serial.println(F("MAX30102 OK (SparkFun SpO2 algorithm)"));
  } else {
    Serial.println(F("MAX30102 not found"));
  }
 
  setupWiFi();
 
  server.on("/", handleRoot);
  server.on("/api/ecg", handleEcgApi);
  server.on("/api/vitals", handleVitalsApi);
  server.begin();
 
  Serial.println(F("Patient Health Monitor ready"));
}
 
void loop() {
  server.handleClient();
 
  if (WiFi.status() == WL_CONNECTED) {
    updateEcgSample();
    updateMax30102();
    updateSlowSensors();
    server.handleClient();
  }
 
  yield();
}



dashboard_page.h

The dashboard is stored as a single HTML page inside dashboard_page.h using PROGMEM (DASHBOARD_PAGE string). The ESP32 serves it directly without needing external hosting or SD card storage.

Create a file named dashboard_page.h in the same folder as the sketch and paste the following code:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
#ifndef DASHBOARD_PAGE_H
#define DASHBOARD_PAGE_H
 
const char DASHBOARD_PAGE[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
  <title>Patient Health Monitor</title>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap" rel="stylesheet" />
  <style>
    :root {
      --bg-1: #eef4ff;
      --bg-2: #e8f0fe;
      --sidebar: #0f172a;
      --sidebar-hover: #1e293b;
      --sidebar-active: #2563eb;
      --card: rgba(255,255,255,0.94);
      --text: #0f172a;
      --muted: #64748b;
      --blue: #2563eb;
      --cyan: #06b6d4;
      --green: #16a34a;
      --red: #ef4444;
      --orange: #f59e0b;
      --green-soft: #dcfce7;
      --red-soft: #fee2e2;
      --orange-soft: #fef3c7;
      --blue-soft: #dbeafe;
      --shadow: 0 20px 50px rgba(15,23,42,0.14);
      --radius: 18px;
    }
    * { margin: 0; padding: 0; box-sizing: border-box; }
    html, body { height: 100%; width: 100%; overflow: hidden; }
    body {
      font-family: "Plus Jakarta Sans", "Segoe UI", system-ui, sans-serif;
      color: var(--text);
      background:
        radial-gradient(circle at 8% 10%, rgba(37,99,235,0.18), transparent 30%),
        radial-gradient(circle at 92% 8%, rgba(6,182,212,0.16), transparent 28%),
        linear-gradient(135deg, var(--bg-1), var(--bg-2));
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0;
    }
    .viewport-wrap {
      aspect-ratio: 15 / 9;
      width: min(100vw, calc(100vh * 15 / 9));
      height: min(100vh, calc(100vw * 9 / 15));
    }
    .app-shell {
      width: 100%;
      height: 100%;
      display: flex;
      border-radius: 0;
      overflow: hidden;
      box-shadow: none;
      border: none;
      background: var(--card);
    }
    .sidebar {
      width: 210px;
      flex-shrink: 0;
      background: linear-gradient(180deg, #0b1224 0%, #111827 55%, #0f172a 100%);
      color: #e2e8f0;
      display: flex;
      flex-direction: column;
      padding: 18px 12px;
      border-right: 1px solid rgba(255,255,255,0.06);
    }
    .sidebar-brand {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 8px 10px 20px;
      border-bottom: 1px solid rgba(255,255,255,0.08);
      margin-bottom: 14px;
    }
    .sidebar-logo {
      width: 42px; height: 42px; border-radius: 13px;
      background: linear-gradient(135deg, #f43f5e 0%, #e11d48 50%, #be123c 100%);
      display: grid; place-items: center;
      box-shadow: 0 6px 18px rgba(244,63,94,0.45);
      flex-shrink: 0;
    }
    .sidebar-logo svg {
      width: 24px; height: 24px;
      fill: none; stroke: #fff;
      stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round;
    }
    .sidebar-brand strong {
      display: block; font-size: 0.88rem; letter-spacing: -0.02em;
      background: linear-gradient(90deg, #fff, #fda4af);
      -webkit-background-clip: text; -webkit-text-fill-color: transparent;
      background-clip: text;
    }
    .sidebar-brand span {
      font-size: 0.68rem; color: #94a3b8;
    }
    .nav-label {
      font-size: 0.65rem; text-transform: uppercase;
      letter-spacing: 0.1em; color: #64748b;
      padding: 0 10px; margin-bottom: 8px;
    }
    .nav { flex: 1; display: flex; flex-direction: column; gap: 4px; }
    .nav-item {
      border: none; background: transparent; color: #cbd5e1;
      text-align: left; padding: 10px 12px;
      border-radius: 12px; font-size: 0.84rem; font-weight: 700;
      cursor: pointer; display: flex; align-items: center; gap: 10px;
      transition: background 0.15s, color 0.15s, transform 0.12s;
    }
    .nav-item:hover { background: var(--sidebar-hover); color: #fff; transform: translateX(2px); }
    .nav-item.active {
      background: linear-gradient(90deg, #2563eb, #3b82f6);
      color: #fff;
      box-shadow: 0 8px 22px rgba(37,99,235,0.4);
    }
    .nav-icon-wrap {
      width: 30px; height: 30px; border-radius: 9px;
      display: grid; place-items: center;
      font-size: 14px; flex-shrink: 0;
      background: rgba(255,255,255,0.08);
    }
    .nav-item.active .nav-icon-wrap { background: rgba(255,255,255,0.22); }
    .nav-item[data-page="dashboard"] .nav-icon-wrap { background: rgba(244,63,94,0.2); }
    .nav-item[data-page="patient"] .nav-icon-wrap { background: rgba(59,130,246,0.2); }
    .nav-item[data-page="logging"] .nav-icon-wrap { background: rgba(16,185,129,0.2); }
    .nav-item[data-page="alerts"] .nav-icon-wrap { background: rgba(245,158,11,0.2); }
    .nav-icon { width: auto; text-align: center; opacity: 1; }
    .sidebar-foot {
      padding: 12px 10px 4px;
      border-top: 1px solid rgba(255,255,255,0.08);
      font-size: 0.72rem; color: #94a3b8;
    }
    .live-pill {
      display: flex; align-items: center; gap: 7px;
      margin-bottom: 6px; font-weight: 800; color: #e2e8f0;
    }
    .live-dot {
      width: 8px; height: 8px; border-radius: 50%;
      background: var(--green);
      animation: pulse 1.5s infinite;
    }
    .live-dot.off { background: var(--red); animation: none; }
    @keyframes pulse {
      0% { box-shadow: 0 0 0 0 rgba(22,163,74,0.5); }
      75% { box-shadow: 0 0 0 8px rgba(22,163,74,0); }
      100% { box-shadow: 0 0 0 0 rgba(22,163,74,0); }
    }
    .main {
      flex: 1; min-width: 0;
      display: flex; flex-direction: column;
      background: linear-gradient(180deg, #fafbff, #f1f5f9);
    }
    .topbar {
      flex-shrink: 0;
      padding: 10px 16px;
      display: flex; justify-content: space-between; align-items: center;
      gap: 12px;
      border-bottom: 1px solid rgba(148,163,184,0.15);
      background: linear-gradient(90deg, rgba(255,255,255,0.98), rgba(239,246,255,0.98));
    }
    .topbar h1 {
      font-size: 1.12rem; letter-spacing: -0.03em; font-weight: 800;
    }
    .topbar p { font-size: 0.76rem; color: var(--muted); margin-top: 2px; font-weight: 600; }
    .topbar-actions {
      display: flex; align-items: center; gap: 12px;
      flex-shrink: 0;
    }
    .topbar-meta {
      text-align: right; font-size: 0.72rem; color: var(--muted); font-weight: 700;
    }
    .topbar-meta strong { display: block; color: var(--text); font-size: 0.86rem; font-weight: 800; }
    .sound-toggle {
      width: 36px; height: 36px;
      border-radius: 11px;
      border: 1.5px solid #e2e8f0;
      background: #fff;
      color: #64748b;
      font-size: 16px; line-height: 1;
      cursor: pointer;
      display: grid; place-items: center;
      transition: background 0.15s, border-color 0.15s, color 0.15s, transform 0.12s;
      flex-shrink: 0;
    }
    .sound-toggle:hover { background: #f8fafc; border-color: #cbd5e1; }
    .sound-toggle:active { transform: scale(0.94); }
    .sound-toggle.muted { opacity: 0.5; background: #f1f5f9; }
    .sound-toggle:not(.muted) {
      background: #eff6ff;
      border-color: #93c5fd;
      color: #2563eb;
    }
    .sound-toggle svg {
      width: 18px; height: 18px;
      stroke: currentColor; fill: none;
      stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
    }
    .sound-toggle .sound-off { display: none; }
    .sound-toggle.muted .sound-on { display: none; }
    .sound-toggle.muted .sound-off { display: block; }
    .topbar-actions .sound-toggle + .topbar-meta {
      padding-left: 12px;
      border-left: 1px solid #e2e8f0;
    }
    .page-area {
      flex: 1; min-height: 0;
      overflow: hidden; position: relative;
    }
    .page {
      display: none;
      position: absolute;
      inset: 0;
      overflow-y: auto;
      overflow-x: hidden;
      padding: 14px 18px 16px;
      -webkit-overflow-scrolling: touch;
    }
    .page.active {
      display: block;
      z-index: 1;
    }
    #page-patient.page.active {
      display: flex;
      flex-direction: column;
      overflow: hidden;
      padding: 10px 14px 12px;
      background: linear-gradient(180deg, #f0f4fa 0%, #e8eef6 100%);
    }
    .record-page {
      flex: 1; min-height: 0;
      display: flex; flex-direction: column; gap: 10px;
      overflow: hidden;
    }
    .record-banner {
      flex-shrink: 0;
      position: relative; overflow: hidden;
      border-radius: 18px;
      padding: 0;
    }
    .record-banner-bg {
      position: absolute; inset: 0;
      background: linear-gradient(120deg, #1e3a8a 0%, #2563eb 45%, #0891b2 100%);
    }
    .record-banner-bg::after {
      content: "";
      position: absolute; inset: 0;
      background:
        radial-gradient(circle at 85% 20%, rgba(255,255,255,0.2), transparent 42%),
        radial-gradient(circle at 12% 88%, rgba(255,255,255,0.12), transparent 38%);
    }
    .record-profile {
      position: relative; z-index: 1;
      display: flex; align-items: center; gap: 14px;
      padding: 16px 18px;
      color: #fff;
    }
    .record-avatar-ring {
      padding: 3px;
      border-radius: 20px;
      background: linear-gradient(135deg, rgba(255,255,255,0.95), rgba(255,255,255,0.35));
      flex-shrink: 0;
    }
    .record-profile .patient-avatar {
      width: 68px; height: 68px;
      border-radius: 16px;
      font-size: 1.4rem;
      box-shadow: 0 8px 20px rgba(0,0,0,0.2);
    }
    .record-profile-main { flex: 1; min-width: 0; }
    .record-profile-main h2 {
      margin: 0 0 8px;
      font-size: 1.45rem; font-weight: 900;
      letter-spacing: -0.03em;
      line-height: 1.15;
      word-break: break-word;
    }
    .record-profile .patient-chips {
      display: flex; flex-wrap: wrap; gap: 6px;
    }
    .record-profile .patient-chip {
      font-size: 0.78rem; font-weight: 800;
      padding: 5px 11px;
      border-radius: 999px;
      background: rgba(255,255,255,0.18);
      border: 1px solid rgba(255,255,255,0.35);
      color: #fff;
    }
    .record-profile .patient-chip.loc {
      color: #e0f2fe;
    }
    .btn-glow {
      flex-shrink: 0;
      box-shadow: 0 6px 20px rgba(15,23,42,0.25);
      background: #fff !important;
      color: #1d4ed8 !important;
      font-weight: 900;
      padding: 10px 16px;
      font-size: 0.8rem;
      white-space: nowrap;
    }
    .record-scroll {
      flex: 1; min-height: 0;
      overflow-y: auto;
      overflow-x: hidden;
      -webkit-overflow-scrolling: touch;
      display: flex; flex-direction: column; gap: 10px;
      padding-bottom: 4px;
    }
    .record-section-title {
      font-size: 0.72rem; font-weight: 900;
      text-transform: uppercase; letter-spacing: 0.08em;
      color: var(--muted);
      margin: 0 0 8px 2px;
    }
    .record-stats-row {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 8px;
    }
    .record-stat {
      padding: 14px 10px;
      border-radius: 14px;
      text-align: center;
      display: flex; flex-direction: column; align-items: center; gap: 6px;
    }
    .record-stat-icon {
      width: 40px; height: 40px; border-radius: 12px;
      display: grid; place-items: center;
      font-size: 18px;
    }
    .record-stat.rc-age { background: linear-gradient(180deg, #eff6ff, #fff); border: 1px solid #bfdbfe; }
    .record-stat.rc-age .record-stat-icon { background: #dbeafe; }
    .record-stat.rc-gender { background: linear-gradient(180deg, #fdf2f8, #fff); border: 1px solid #fbcfe8; }
    .record-stat.rc-gender .record-stat-icon { background: #fce7f3; }
    .record-stat.rc-blood { background: linear-gradient(180deg, #fef2f2, #fff); border: 1px solid #fecaca; }
    .record-stat.rc-blood .record-stat-icon { background: #fee2e2; }
    .record-stat-label {
      font-size: 0.65rem; font-weight: 800;
      text-transform: uppercase; letter-spacing: 0.06em;
      color: var(--muted);
    }
    .record-stat-value {
      font-size: 1.05rem; font-weight: 900;
      color: var(--text); line-height: 1.2;
      word-break: break-word;
    }
    .record-contact-row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 8px;
    }
    .record-detail-card {
      padding: 14px 16px;
      border-radius: 14px;
      display: flex; align-items: center; gap: 12px;
    }
    .record-detail-card.rc-phone {
      background: linear-gradient(135deg, #ecfdf5, #fff);
      border: 1px solid #bbf7d0;
    }
    .record-detail-card.rc-id {
      background: linear-gradient(135deg, #f5f3ff, #fff);
      border: 1px solid #ddd6fe;
    }
    .record-detail-card .field-icon {
      width: 38px; height: 38px; font-size: 16px; border-radius: 11px;
      flex-shrink: 0;
    }
    .record-detail-label {
      font-size: 0.65rem; font-weight: 800;
      text-transform: uppercase; letter-spacing: 0.05em;
      color: var(--muted);
    }
    .record-detail-value {
      font-size: 0.95rem; font-weight: 800;
      color: var(--text); margin-top: 2px;
      word-break: break-word;
    }
    .record-notes-card {
      padding: 14px 16px;
      border-radius: 14px;
      background: linear-gradient(180deg, #fffbeb, #ffffff);
      border: 1px solid #fde68a;
    }
    .record-notes-card .record-section-title { margin-bottom: 10px; }
    .record-notes-body {
      padding: 12px 14px;
      background: #fff;
      border-radius: 10px;
      border: 1px solid #fef3c7;
      font-size: 0.92rem; font-weight: 600;
      color: #475569; line-height: 1.55;
      min-height: 88px;
      word-break: break-word;
    }
    #page-logging.page.active,
    #page-alerts.page.active {
      display: flex;
      flex-direction: column;
      overflow: hidden;
      padding: 10px 14px 12px;
      gap: 10px;
      background: linear-gradient(180deg, #f0f4fa 0%, #e8eef6 100%);
    }
    .logging-page, .alerts-page {
      flex: 1; min-height: 0;
      display: flex; flex-direction: column; gap: 10px;
    }
    .logging-toolbar {
      flex-shrink: 0;
      padding: 14px 16px;
      display: flex; align-items: center; justify-content: space-between;
      gap: 12px; flex-wrap: wrap;
      border-radius: 16px;
    }
    .logging-controls {
      display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
    }
    .logging-controls label {
      font-size: 0.72rem; font-weight: 900;
      text-transform: uppercase; letter-spacing: 0.06em;
      color: var(--muted);
    }
    .logging-controls select {
      padding: 9px 12px; border-radius: 10px;
      border: 1px solid #e2e8f0; background: #fff;
      font-size: 0.85rem; font-weight: 700;
      font-family: inherit; color: var(--text);
    }
    .btn-log { padding: 9px 14px; font-size: 0.78rem; }
    .btn-log-start { background: #16a34a; color: #fff; }
    .btn-log-stop { background: #ef4444; color: #fff; }
    .btn-log-export { background: #2563eb; color: #fff; }
    .logging-stats {
      display: flex; align-items: center; gap: 14px;
      font-size: 0.78rem; font-weight: 800; color: var(--muted);
    }
    .log-status-pill {
      padding: 5px 12px; border-radius: 999px;
      font-size: 0.68rem; font-weight: 900;
      letter-spacing: 0.05em; text-transform: uppercase;
    }
    .log-status-pill.stopped { background: #f1f5f9; color: #64748b; }
    .log-status-pill.running { background: #dcfce7; color: #16a34a; }
    .logging-table-wrap {
      flex: 1; min-height: 0;
      overflow: hidden;
      border-radius: 16px;
      display: flex; flex-direction: column;
    }
    .logging-table-head {
      flex-shrink: 0;
      padding: 12px 16px;
      border-bottom: 1px solid #e2e8f0;
      display: flex; justify-content: space-between; align-items: center;
    }
    .logging-table-head h4 {
      font-size: 0.85rem; font-weight: 900;
      display: flex; align-items: center; gap: 8px;
    }
    .logging-table-scroll {
      flex: 1; min-height: 0; overflow: auto;
      -webkit-overflow-scrolling: touch;
    }
    .log-table {
      width: 100%; border-collapse: collapse;
      font-size: 0.78rem;
    }
    .log-table th {
      position: sticky; top: 0; z-index: 1;
      background: #f1f5f9;
      padding: 10px 12px;
      text-align: left; font-weight: 900;
      color: #475569; text-transform: uppercase;
      letter-spacing: 0.05em; font-size: 0.68rem;
      border-bottom: 2px solid #e2e8f0;
    }
    .log-table td {
      padding: 9px 12px;
      border-bottom: 1px solid #f1f5f9;
      font-weight: 600; color: var(--text);
    }
    .log-table tbody tr:nth-child(even) { background: #fafbfc; }
    .log-table tbody tr:hover { background: #eff6ff; }
    .log-empty {
      padding: 40px; text-align: center;
      color: var(--muted); font-weight: 700; font-size: 0.85rem;
    }
    .alerts-hero {
      flex-shrink: 0;
      padding: 14px 16px;
      display: flex; justify-content: space-between; align-items: center;
      gap: 12px;
      border-radius: 16px;
      background: linear-gradient(120deg, #7f1d1d 0%, #dc2626 40%, #ea580c 100%);
      color: #fff;
      box-shadow: 0 8px 28px rgba(220,38,38,0.25);
    }
    .alerts-hero h3 {
      font-size: 1.05rem; font-weight: 900;
      letter-spacing: -0.02em; margin: 0 0 3px;
      color: #fff;
    }
    .alerts-hero p {
      font-size: 0.72rem; color: rgba(255,255,255,0.85); margin: 0;
      font-weight: 600;
    }
    .alerts-status-badge {
      font-size: 0.68rem; font-weight: 900;
      padding: 8px 14px; border-radius: 999px;
      letter-spacing: 0.06em; text-transform: uppercase;
      flex-shrink: 0;
      background: rgba(255,255,255,0.95);
    }
    .alerts-status-badge.good { color: #16a34a; }
    .alerts-status-badge.watch { color: #b45309; }
    .alerts-status-badge.bad { color: #ef4444; }
    .alerts-summary {
      flex-shrink: 0;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 8px;
    }
    .alerts-summary-card {
      padding: 10px 12px;
      border-radius: 12px;
      text-align: center;
      font-size: 0.65rem; font-weight: 800;
      text-transform: uppercase; letter-spacing: 0.05em;
    }
    .alerts-summary-card span {
      display: block;
      font-size: 1.35rem; font-weight: 1000;
      letter-spacing: -0.04em;
      margin-bottom: 2px;
    }
    .alerts-summary-card.warn { background: #fff7ed; border: 1px solid #fdba74; color: #c2410c; }
    .alerts-summary-card.warn span { color: #ea580c; }
    .alerts-summary-card.ok { background: #f0fdf4; border: 1px solid #86efac; color: #15803d; }
    .alerts-summary-card.ok span { color: #16a34a; }
    .alerts-summary-card.info { background: #eff6ff; border: 1px solid #93c5fd; color: #1d4ed8; }
    .alerts-summary-card.info span { color: #2563eb; }
    .alerts-scroll {
      flex: 1; min-height: 0;
      overflow-y: auto;
      overflow-x: hidden;
      -webkit-overflow-scrolling: touch;
      display: flex; flex-direction: column; gap: 12px;
      padding-bottom: 4px;
    }
    .alerts-section-title {
      font-size: 0.7rem; font-weight: 900;
      text-transform: uppercase; letter-spacing: 0.08em;
      color: var(--muted);
      margin: 0 0 8px 2px;
      display: flex; align-items: center; gap: 6px;
    }
    .alert-row {
      display: flex; gap: 12px; align-items: flex-start;
      padding: 12px 14px;
      border-radius: 14px;
      margin-bottom: 8px;
      border: 1px solid #e8eef5;
      background: #fff;
      transition: box-shadow 0.15s;
    }
    .alert-row:last-child { margin-bottom: 0; }
    .alert-row.alert-ok { border-left: 4px solid #22c55e; background: linear-gradient(90deg, #f0fdf4, #fff); }
    .alert-row.alert-warn { border-left: 4px solid #f59e0b; background: linear-gradient(90deg, #fffbeb, #fff); }
    .alert-row.alert-bad { border-left: 4px solid #ef4444; background: linear-gradient(90deg, #fef2f2, #fff); }
    .alert-row.alert-info { border-left: 4px solid #3b82f6; background: linear-gradient(90deg, #eff6ff, #fff); }
    .alert-row-icon {
      width: 42px; height: 42px; flex-shrink: 0;
      border-radius: 12px;
      display: grid; place-items: center;
      font-size: 20px;
    }
    .alert-row.alert-ok .alert-row-icon { background: #dcfce7; }
    .alert-row.alert-warn .alert-row-icon { background: #fef3c7; }
    .alert-row.alert-bad .alert-row-icon { background: #fee2e2; }
    .alert-row.alert-info .alert-row-icon { background: #dbeafe; }
    .alert-row-body { flex: 1; min-width: 0; }
    .alert-row-top {
      display: flex; align-items: flex-start; justify-content: space-between;
      gap: 8px; margin-bottom: 4px;
    }
    .alert-row-top strong {
      font-size: 0.88rem; color: var(--text); line-height: 1.3;
    }
    .alert-pill {
      flex-shrink: 0;
      font-size: 0.58rem; font-weight: 900;
      padding: 3px 8px; border-radius: 999px;
      letter-spacing: 0.05em; text-transform: uppercase;
    }
    .alert-pill.ok { background: #dcfce7; color: #16a34a; }
    .alert-pill.warn { background: #fef3c7; color: #b45309; }
    .alert-pill.bad { background: #fee2e2; color: #ef4444; }
    .alert-pill.info { background: #dbeafe; color: #2563eb; }
    .alert-row-body > p {
      font-size: 0.78rem; color: #475569;
      line-height: 1.4; margin: 0 0 6px; font-weight: 600;
    }
    .alert-tip {
      font-size: 0.72rem; color: #64748b;
      line-height: 1.4; margin: 0;
      padding: 7px 10px;
      background: rgba(255,255,255,0.7);
      border-radius: 8px;
      border: 1px dashed #cbd5e1;
      font-weight: 600;
    }
    .alert-tip::before { content: "💡 "; }
    .alerts-suggestions {
      padding: 14px 16px;
      border-radius: 14px;
      background: linear-gradient(135deg, #eff6ff, #f0fdf4);
      border: 1px solid #bfdbfe;
    }
    .alerts-suggestions .alerts-section-title { color: #1d4ed8; }
    .alert-suggest-list {
      list-style: none; margin: 0; padding: 0;
      display: flex; flex-direction: column; gap: 8px;
    }
    .alert-suggest-list li {
      font-size: 0.78rem; font-weight: 600;
      color: #334155; line-height: 1.45;
      padding: 9px 12px 9px 32px;
      background: #fff;
      border-radius: 10px;
      border: 1px solid #e2e8f0;
      position: relative;
    }
    .alert-suggest-list li::before {
      content: "✓";
      position: absolute; left: 10px; top: 9px;
      width: 18px; height: 18px; border-radius: 50%;
      background: #dbeafe; color: #2563eb;
      font-size: 0.62rem; font-weight: 900;
      display: grid; place-items: center;
    }
    .patient-page {
      flex: 1; min-height: 0;
      display: flex; flex-direction: column;
    }
    .patient-panel {
      flex: 1; min-height: 0;
      display: flex; flex-direction: column;
      overflow: hidden;
      padding: 0;
    }
    .patient-hero {
      flex-shrink: 0;
      padding: 16px 20px;
      background: linear-gradient(120deg, #eff6ff 0%, #ecfeff 45%, #ffffff 100%);
      border-bottom: 1px solid rgba(148, 163, 184, 0.25);
      display: flex; align-items: center; gap: 18px;
    }
    .patient-avatar {
      width: 76px; height: 76px; flex-shrink: 0;
      border-radius: 18px;
      background: linear-gradient(145deg, var(--blue), var(--cyan));
      color: #fff; font-size: 1.55rem; font-weight: 900;
      display: grid; place-items: center;
      box-shadow: 0 10px 24px rgba(37, 99, 235, 0.28);
      letter-spacing: 0.02em;
    }
    .patient-hero-main { flex: 1; min-width: 0; }
    .patient-hero-main h2 {
      margin: 0 0 10px; font-size: 1.65rem; font-weight: 900;
      letter-spacing: -0.03em; line-height: 1.15;
      white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    }
    .patient-chips { display: flex; flex-wrap: wrap; gap: 8px; }
    .patient-chip {
      font-size: 0.88rem; font-weight: 800; padding: 7px 14px;
      border-radius: 999px; background: rgba(255,255,255,0.92);
      border: 1px solid #dbeafe; color: #1d4ed8;
    }
    .patient-chip.loc { border-color: #99f6e4; color: #0f766e; }
    .patient-hero .btn {
      flex-shrink: 0; padding: 12px 20px; font-size: 0.92rem;
    }
    .patient-body {
      flex: 1; min-height: 0;
      display: grid;
      grid-template-columns: 1fr 1fr 1.15fr;
      gap: 12px;
      padding: 12px 14px 14px;
      overflow: hidden;
      align-items: stretch;
    }
    .patient-section {
      background: #f8fafc;
      border: 1px solid #e8eef5;
      border-radius: 14px;
      padding: 16px 18px;
      display: flex; flex-direction: column;
      min-height: 0;
      justify-content: center;
    }
    .patient-section-title {
      font-size: 0.8rem; font-weight: 900; color: var(--muted);
      text-transform: uppercase; letter-spacing: 0.09em;
      margin: 0 0 12px; padding-bottom: 10px;
      border-bottom: 1px solid #e2e8f0;
      flex-shrink: 0;
    }
    .patient-section-rows {
      flex: 1; display: flex; flex-direction: column;
      justify-content: space-evenly; min-height: 0;
    }
    .detail-row {
      display: flex; align-items: center; justify-content: space-between;
      gap: 12px; padding: 11px 0;
      border-bottom: 1px solid rgba(226, 232, 240, 0.7);
    }
    .detail-row:last-child { border-bottom: none; }
    .detail-row .detail-label {
      display: flex; align-items: center; gap: 10px;
      font-size: 0.95rem; color: #64748b; font-weight: 700;
    }
    #page-patient .detail-row .field-icon {
      width: 32px; height: 32px; font-size: 16px; border-radius: 9px;
    }
    .detail-row .detail-value {
      font-size: 1.08rem; font-weight: 800; color: var(--text);
      text-align: right; word-break: break-word;
    }
    .notes-box {
      flex: 1; min-height: 0;
      margin-top: 6px; padding: 14px 16px;
      background: #fff; border-radius: 12px;
      border: 1px solid #e2e8f0;
      font-size: 1rem; font-weight: 600; color: #475569;
      line-height: 1.5; overflow-y: auto;
      display: flex; align-items: flex-start;
    }
    .patient-modal {
      display: none;
      position: fixed; inset: 0; z-index: 200;
      align-items: center; justify-content: center;
      padding: 16px;
    }
    .patient-modal.open { display: flex; }
    .patient-modal-backdrop {
      position: absolute; inset: 0;
      background: rgba(15, 23, 42, 0.5);
    }
    .patient-modal-card {
      position: relative; z-index: 1;
      width: min(580px, 100%);
      max-height: min(92vh, 640px);
      overflow-y: auto;
      padding: 18px 20px 20px;
    }
    .patient-modal-head {
      display: flex; justify-content: space-between; align-items: center;
      margin-bottom: 14px; padding-bottom: 10px;
      border-bottom: 1px solid #e2e8f0;
    }
    .patient-modal-head h3 {
      font-size: 0.98rem; margin: 0;
      display: flex; align-items: center; gap: 8px;
    }
    .btn-icon {
      width: 32px; height: 32px; border-radius: 10px;
      border: 1px solid #e2e8f0; background: #fff;
      color: var(--muted); font-size: 1.1rem; cursor: pointer;
      display: grid; place-items: center; line-height: 1;
    }
    #page-dashboard.page.active {
      display: flex;
      flex-direction: column;
      overflow: hidden;
      padding: 10px 14px 12px;
      gap: 10px;
      z-index: 2;
      background:
        radial-gradient(ellipse 70% 45% at 15% 0%, rgba(244,63,94,0.08), transparent),
        radial-gradient(ellipse 60% 40% at 85% 5%, rgba(37,99,235,0.1), transparent),
        radial-gradient(ellipse 50% 35% at 50% 100%, rgba(6,182,212,0.08), transparent),
        linear-gradient(180deg, #f8faff 0%, #eef2ff 100%);
    }
    .med-dash {
      flex: 1; min-height: 0;
      display: flex; flex-direction: column; gap: 10px;
    }
    .med-status-bar {
      flex-shrink: 0;
      display: flex; align-items: center;
      gap: 8px;
      padding: 8px 10px;
      border-radius: 14px;
      background: #0f172a;
      color: #e2e8f0;
      border: 1px solid #1e293b;
      overflow: hidden;
    }
    .med-status-pill {
      display: flex; align-items: center; gap: 7px;
      padding: 6px 11px;
      border-radius: 999px;
      font-size: 0.68rem; font-weight: 800;
      letter-spacing: 0.05em;
      text-transform: uppercase;
      white-space: nowrap;
      flex-shrink: 0;
    }
    .med-status-pill.live-pill-dash {
      background: rgba(34,197,94,0.15);
      border: 1px solid rgba(34,197,94,0.35);
      color: #86efac;
    }
    .med-status-pill.ward-pill-dash {
      background: rgba(59,130,246,0.12);
      border: 1px solid rgba(59,130,246,0.3);
      color: #93c5fd;
    }
    .med-status-pill.ward-pill-dash svg {
      width: 14px; height: 14px;
      stroke: currentColor; fill: none;
      stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
    }
    .med-status-patient {
      flex: 1; min-width: 0;
      display: flex; align-items: center; gap: 8px;
      margin-left: auto;
      padding: 6px 12px 6px 8px;
      border-radius: 999px;
      background: rgba(255,255,255,0.1);
      border: 1px solid rgba(255,255,255,0.18);
    }
    .med-status-patient .med-chip-icon {
      background: #3b82f6;
      color: #fff;
      font-size: 12px;
    }
    #dashPatientName {
      font-size: 0.78rem; font-weight: 800;
      text-transform: none; letter-spacing: -0.01em;
      color: #fff;
      white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
      min-width: 0;
      flex: 1;
    }
    .med-status-dot {
      width: 8px; height: 8px; border-radius: 50%;
      background: #22c55e;
      animation: statusPulse 2s infinite;
      flex-shrink: 0;
    }
    @keyframes statusPulse {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.5; }
    }
    .med-chip-icon {
      width: 28px; height: 28px; border-radius: 8px;
      background: rgba(255,255,255,0.14);
      display: grid; place-items: center; font-size: 13px;
      flex-shrink: 0;
    }
    .med-chip-icon svg {
      width: 15px; height: 15px;
      stroke: currentColor; fill: none;
      stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
    }
    .med-vitals-grid {
      flex-shrink: 0;
      display: grid;
      grid-template-columns: 1.15fr 1.15fr 0.85fr;
      gap: 10px;
      min-height: 0;
    }
    .med-vital {
      display: flex; align-items: center; gap: 14px;
      padding: 16px 18px;
      border-radius: 16px;
      position: relative;
      min-height: 112px;
      box-shadow: none !important;
      transition: border-color 0.25s ease;
    }
    .med-vital-heart {
      background: #fff1f2;
      border: 1.5px solid #fecdd3;
    }
    .med-vital-spo2 {
      background: #eff6ff;
      border: 1.5px solid #bfdbfe;
    }
    .med-vital-icon-wrap {
      flex-shrink: 0;
      width: 56px;
      display: flex; align-items: center; justify-content: center;
    }
    .vital-icon-box {
      width: 52px; height: 52px;
      border-radius: 14px;
      display: grid; place-items: center;
      transform-origin: center;
      box-shadow: none;
    }
    .vital-icon-heart {
      background: #e11d48;
      color: #fff;
    }
    .vital-icon-heart.beating {
      animation: heartbeat var(--beat-dur, 0.85s) ease-in-out infinite;
      will-change: transform;
    }
    @keyframes heartbeat {
      0%, 100% { transform: scale(1); }
      14% { transform: scale(1.07); }
      28% { transform: scale(1); }
      42% { transform: scale(1.04); }
      56% { transform: scale(1); }
    }
    .vital-icon-heart svg {
      width: 26px; height: 26px;
      fill: currentColor;
    }
    .vital-icon-spo2 {
      background: #2563eb;
      color: #fff;
      animation: o2Breathe 3s ease-in-out infinite;
    }
    @keyframes o2Breathe {
      0%, 100% { transform: scale(1); }
      50% { transform: scale(1.06); }
    }
    .vital-icon-spo2 .spo2-symbol {
      font-size: 1rem; font-weight: 800;
      letter-spacing: -0.03em;
      text-shadow: none;
    }
    .med-vital-body { flex: 1; min-width: 0; }
    .med-vital-top {
      display: flex; justify-content: space-between; align-items: center;
      margin-bottom: 6px; gap: 6px;
    }
    .med-vital-title {
      font-size: 0.7rem; font-weight: 700;
      text-transform: uppercase; letter-spacing: 0.08em;
      color: #64748b;
      display: flex; align-items: center; gap: 6px;
    }
    .vt-ico {
      width: 18px; height: 18px; border-radius: 5px;
      display: grid; place-items: center;
      flex-shrink: 0;
    }
    .vt-ico svg {
      width: 11px; height: 11px;
      stroke: currentColor; fill: none;
      stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round;
    }
    .med-vital-heart .vt-ico { background: #ffe4e6; color: #e11d48; }
    .med-vital-spo2 .vt-ico { background: #dbeafe; color: #2563eb; }
    .dash-section-label {
      font-size: 0.68rem; font-weight: 800;
      text-transform: uppercase; letter-spacing: 0.1em;
      color: #94a3b8;
      padding: 0 2px;
      display: flex; align-items: center; gap: 6px;
    }
    .dash-section-label::before {
      content: "";
      width: 8px; height: 8px; border-radius: 50%;
      background: #22c55e;
      animation: statusPulse 2s infinite;
    }
    .med-vital-value {
      font-size: 2rem; font-weight: 800;
      letter-spacing: -0.04em; line-height: 1;
      margin-bottom: 4px;
      font-variant-numeric: tabular-nums;
      transition: color 0.3s ease;
    }
    #bpm.bpm-pulse {
      animation: bpmGlow 0.55s ease;
    }
    @keyframes bpmGlow {
      0%, 100% { opacity: 1; filter: none; }
      40% { opacity: 0.82; filter: brightness(1.15); }
    }
    .med-vital-value.vital-flash { animation: vitalSoft 0.45s ease; }
    .med-vital-heart .med-vital-value { color: #9f1239; }
    .med-vital-spo2 .med-vital-value { color: #1e40af; }
    .med-unit {
      font-size: 0.75rem; font-weight: 700;
      color: #94a3b8; margin-left: 3px;
      letter-spacing: 0.02em;
    }
    .med-range {
      font-size: 0.65rem; font-weight: 600;
      color: #94a3b8; margin-bottom: 8px;
    }
    .med-bar {
      height: 5px; border-radius: 999px;
      background: rgba(15,23,42,0.06); overflow: hidden;
    }
    .med-vital .bar-fill {
      height: 100%; border-radius: inherit;
      transition: width 0.55s cubic-bezier(0.4, 0, 0.2, 1);
      position: relative;
    }
    .med-vital-heart .bar-fill { background: #f43f5e; }
    .med-vital-spo2 .bar-fill { background: #3b82f6; }
    .med-vitals-side {
      display: flex; flex-direction: column; gap: 8px;
    }
    .med-vital-compact {
      flex: 1;
      display: flex; align-items: center; gap: 12px;
      padding: 12px 14px;
      border-radius: 14px;
      min-height: 0;
      box-shadow: none !important;
      transition: border-color 0.25s ease;
    }
    .med-vital-compact.temp {
      background: #fff7ed;
      border: 1.5px solid #fed7aa;
    }
    .med-vital-compact.room {
      background: #f0fdf4;
      border: 1.5px solid #bbf7d0;
    }
    .med-vital-compact.hum {
      background: #ecfeff;
      border: 1.5px solid #a5f3fc;
    }
    .med-compact-icon {
      width: 38px; height: 38px; flex-shrink: 0;
      border-radius: 11px;
      display: grid; place-items: center;
      box-shadow: none;
    }
    .med-vital-compact.temp .med-compact-icon { background: #ea580c; color: #fff; }
    .med-vital-compact.room .med-compact-icon { background: #16a34a; color: #fff; }
    .med-vital-compact.hum .med-compact-icon { background: #0891b2; color: #fff; }
    .med-compact-icon svg {
      width: 20px; height: 20px;
      stroke: currentColor; fill: none;
      stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
    }
    .med-compact-body { flex: 1; min-width: 0; }
    .med-compact-body .med-vital-title { margin-bottom: 3px; font-size: 0.65rem; }
    .med-compact-value {
      font-size: 1.3rem; font-weight: 800;
      letter-spacing: -0.03em; line-height: 1.1;
      font-variant-numeric: tabular-nums;
    }
    .med-compact-value.vital-flash { animation: vitalSoft 0.45s ease; }
    @keyframes vitalSoft {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.75; }
    }
    .med-vital-compact.temp .med-compact-value { color: #c2410c; }
    .med-vital-compact.room .med-compact-value { color: #15803d; }
    .med-vital-compact.hum .med-compact-value { color: #0e7490; }
    .med-compact-body .med-unit { font-size: 0.65rem; }
    .med-compact-body .med-bar { height: 4px; margin-top: 6px; }
    .med-vital-compact.temp .bar-fill { background: #f97316; }
    .med-vital-compact.room .bar-fill { background: #22c55e; }
    .med-vital-compact.hum .bar-fill { background: #06b6d4; }
    .med-vital .badge, .med-vital-compact .badge {
      position: static;
      font-size: 0.55rem;
      font-weight: 800;
      padding: 3px 8px;
      letter-spacing: 0.04em;
      border-radius: 6px;
    }
    .med-ecg {
      flex: 1 1 auto; min-height: 0;
      padding: 12px 14px 14px;
      background: #f0fdf4;
      border: 1.5px solid #bbf7d0;
      box-shadow: none !important;
    }
    .ecg-icon-wrap {
      width: 36px; height: 36px; border-radius: 10px;
      background: #16a34a;
      display: grid; place-items: center;
      color: #fff;
      box-shadow: none;
    }
    .ecg-icon-wrap svg {
      width: 18px; height: 18px;
      stroke: currentColor; fill: none;
      stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round;
    }
    .ecg-title-block {
      display: flex; align-items: center; gap: 10px;
    }
    .ecg-title-block h3 {
      font-size: 0.92rem; letter-spacing: -0.02em;
      margin: 0;
    }
    .ecg-sub {
      font-size: 0.68rem; color: var(--muted); font-weight: 600;
    }
    .ecg-overlay-labels {
      position: absolute; top: 8px; left: 10px; z-index: 2;
      display: flex; gap: 12px;
      font-size: 0.62rem; font-weight: 800;
      color: rgba(103,232,249,0.55);
      letter-spacing: 0.06em;
      text-transform: uppercase;
      pointer-events: none;
    }
    .glass {
      background: var(--card);
      border: 1px solid rgba(226,232,240,0.9);
      border-radius: var(--radius);
      box-shadow: 0 8px 24px rgba(15,23,42,0.06);
    }
    .vitals-row {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 10px;
      margin-bottom: 10px;
    }
    .vital-card { padding: 12px 14px; position: relative; overflow: hidden; }
    .vital-card .label {
      font-size: 0.68rem; font-weight: 900; color: var(--muted);
      text-transform: uppercase; letter-spacing: 0.06em;
      margin-bottom: 6px;
    }
    .vital-card .value {
      font-size: 1.85rem; font-weight: 1000;
      letter-spacing: -0.06em; line-height: 1;
      margin-bottom: 8px;
    }
    .vital-card .unit { font-size: 0.8rem; color: var(--muted); font-weight: 800; }
    .vital-card .bar {
      height: 6px; border-radius: 999px; background: #e8eef7; overflow: hidden;
    }
    .vital-card .bar-fill {
      height: 100%; border-radius: inherit;
      background: linear-gradient(90deg, var(--blue), var(--cyan));
      transition: width 0.4s ease;
    }
    .badge {
      position: absolute; top: 10px; right: 10px;
      font-size: 0.62rem; font-weight: 900; padding: 4px 8px;
      border-radius: 999px; letter-spacing: 0.05em;
    }
    .badge.good { background: var(--green-soft); color: var(--green); }
    .badge.watch { background: var(--orange-soft); color: #b45309; }
    .badge.live { background: var(--blue-soft); color: var(--blue); }
    .badge.bad { background: var(--red-soft); color: var(--red); }
    #page-dashboard .ecg-wrap {
      flex: 1 1 auto;
      min-height: 0;
      display: flex;
      flex-direction: column;
    }
    .ecg-wrap {
      flex: 1;
      min-height: 0;
      display: flex;
      flex-direction: column;
    }
    #page-dashboard .ecg-head {
      margin-bottom: 8px;
      flex-shrink: 0;
    }
    #page-dashboard .ecg-stage {
      flex: 1 1 auto;
      min-height: 0;
    }
    .ecg-head {
      display: flex; justify-content: space-between; align-items: center;
      margin-bottom: 8px; gap: 10px;
      position: relative;
    }
    .ecg-head .ecg-badge-pill {
      position: static;
      flex-shrink: 0;
      font-size: 0.62rem; font-weight: 900;
      padding: 5px 12px; border-radius: 999px;
      letter-spacing: 0.06em; text-transform: uppercase;
      background: var(--blue-soft); color: var(--blue);
    }
    .ecg-head .ecg-badge-pill.good { background: var(--green-soft); color: var(--green); }
    .ecg-head .ecg-badge-pill.watch { background: var(--orange-soft); color: #b45309; }
    .ecg-head .ecg-badge-pill.bad { background: var(--red-soft); color: var(--red); }
    .ecg-head .ecg-badge-pill.live { background: #dbeafe; color: #2563eb; }
    .ecg-head h3 { font-size: 0.92rem; letter-spacing: -0.02em; }
    .ecg-head span { font-size: 0.72rem; color: var(--muted); }
    .ecg-stage {
      flex: 1;
      min-height: 0;
      border-radius: 14px;
      overflow: hidden;
      position: relative;
      background:
        linear-gradient(rgba(103,232,249,0.06) 1px, transparent 1px),
        linear-gradient(90deg, rgba(103,232,249,0.06) 1px, transparent 1px),
        linear-gradient(180deg, #06101d, #0f172a 62%, #08111f);
      background-size: 24px 24px;
      border: 1px solid rgba(15,23,42,0.1);
    }
    .ecg-stage canvas {
      position: absolute;
      inset: 0;
      width: 100%;
      height: 100%;
      display: block;
    }
    .info-grid {
      display: grid; grid-template-columns: 1fr 1fr;
      gap: 12px;
    }
    .info-card { padding: 16px; }
    .info-card h3 {
      font-size: 0.95rem; margin-bottom: 12px;
      padding-bottom: 8px; border-bottom: 1px solid #e2e8f0;
    }
    .info-row {
      display: flex; justify-content: space-between; gap: 10px;
      padding: 8px 0; border-bottom: 1px solid #f1f5f9;
      font-size: 0.82rem;
    }
    .info-row span:first-child { color: var(--muted); font-weight: 700; }
    .info-row span:last-child { font-weight: 800; text-align: right; }
    .alert-card {
      padding: 14px; margin-bottom: 10px;
      display: grid; grid-template-columns: 36px 1fr; gap: 12px;
      align-items: start;
    }
    .alert-icon {
      width: 36px; height: 36px; border-radius: 12px;
      background: #fff; display: grid; place-items: center;
      border: 1px solid #e2e8f0; font-size: 16px;
    }
    .alert-card strong { display: block; font-size: 0.88rem; margin-bottom: 4px; }
    .alert-card p { font-size: 0.78rem; color: var(--muted); line-height: 1.4; }
    .form-grid {
      display: grid; grid-template-columns: 1fr 1fr; gap: 9px;
    }
    .form-field {
      display: flex; flex-direction: column; gap: 4px;
    }
    .form-field.full { grid-column: span 2; }
    .form-field label {
      display: flex; align-items: center; gap: 6px;
      font-size: 0.68rem; color: var(--muted); font-weight: 800;
      text-transform: uppercase; letter-spacing: 0.06em;
    }
    .field-icon {
      width: 22px; height: 22px; border-radius: 7px;
      display: grid; place-items: center;
      font-size: 12px; line-height: 1; flex-shrink: 0;
    }
    .field-icon.ic-name { background: #dbeafe; color: #2563eb; }
    .field-icon.ic-id { background: #ede9fe; color: #7c3aed; }
    .field-icon.ic-bed { background: #ccfbf1; color: #0d9488; }
    .field-icon.ic-ward { background: #ffedd5; color: #ea580c; }
    .field-icon.ic-age { background: #cffafe; color: #0891b2; }
    .field-icon.ic-blood { background: #fee2e2; color: #dc2626; }
    .field-icon.ic-gender { background: #fce7f3; color: #db2777; }
    .field-icon.ic-contact { background: #dcfce7; color: #16a34a; }
    .field-icon.ic-notes { background: #fef3c7; color: #d97706; }
    .info-label {
      display: flex; align-items: center; gap: 8px;
      color: var(--muted); font-weight: 700;
    }
    .info-label .field-icon { width: 20px; height: 20px; font-size: 11px; border-radius: 6px; }
    #page-patient .info-card h3 {
      display: flex; align-items: center; gap: 8px;
    }
    #page-patient .info-card h3 .field-icon { width: 24px; height: 24px; font-size: 13px; }
    .form-field input, .form-field select, .form-field textarea {
      padding: 9px 11px; border-radius: 10px;
      border: 1px solid #e2e8f0; background: #fff;
      font-size: 0.88rem; font-weight: 600; color: var(--text);
      font-family: inherit;
    }
    .form-field textarea { min-height: 72px; resize: vertical; }
    .form-field input:focus, .form-field select:focus, .form-field textarea:focus {
      outline: none; border-color: var(--blue);
      box-shadow: 0 0 0 3px rgba(37,99,235,0.12);
    }
    .form-actions {
      display: flex; gap: 8px; margin-top: 14px; flex-wrap: wrap;
    }
    .btn {
      padding: 10px 16px; border-radius: 10px; border: none;
      font-size: 0.82rem; font-weight: 800; cursor: pointer;
    }
    .btn-primary { background: var(--blue); color: #fff; }
    .btn-secondary { background: #e2e8f0; color: var(--text); }
    .btn-danger { background: var(--red-soft); color: var(--red); }
    .save-msg {
      font-size: 0.78rem; color: var(--green); font-weight: 800;
      margin-top: 8px; min-height: 1em;
    }
    .patient-head {
      display: flex; justify-content: space-between; align-items: center;
      margin-bottom: 12px;
    }
    .nav-text-short { display: none; }
    .patient-head h3 { font-size: 0.95rem; border: none; padding: 0; margin: 0; }
 
    /* Tablet */
    @media (max-width: 1024px) {
      .med-vitals-grid { grid-template-columns: 1fr 1fr; }
      .med-vitals-side { grid-column: span 2; flex-direction: row; }
      .med-vital-compact { flex: 1; min-width: 0; }
    }
 
    /* Mobile */
    @media (max-width: 768px) {
      body {
        align-items: stretch;
        justify-content: stretch;
      }
      .viewport-wrap {
        width: 100vw;
        width: 100dvw;
        height: 100vh;
        height: 100dvh;
        max-width: none;
        max-height: none;
        aspect-ratio: auto;
      }
      .app-shell {
        flex-direction: column;
      }
      .main {
        flex: 1;
        min-height: 0;
        order: 1;
      }
      .sidebar {
        order: 2;
        width: 100%;
        flex-shrink: 0;
        flex-direction: column;
        padding: 0;
        border-right: none;
        border-top: 1px solid rgba(255,255,255,0.1);
      }
      .sidebar-brand,
      .nav-label { display: none; }
      .sidebar-foot {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 6px 14px;
        border-top: none;
        border-bottom: 1px solid rgba(255,255,255,0.08);
        margin: 0;
      }
      .nav {
        flex-direction: row;
        flex: none;
        gap: 2px;
        padding: 4px 6px;
        padding-bottom: max(6px, env(safe-area-inset-bottom));
      }
      .nav-item {
        flex: 1;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 3px;
        padding: 8px 2px;
        min-height: 54px;
        font-size: 0.58rem;
        text-align: center;
        transform: none;
        border-radius: 10px;
      }
      .nav-item:hover { transform: none; }
      .nav-text-long { display: none; }
      .nav-text-short { display: inline; }
      .nav-icon-wrap {
        width: 32px;
        height: 32px;
        font-size: 15px;
      }
      .topbar {
        padding: 8px 12px;
        gap: 8px;
      }
      .topbar h1 { font-size: 1rem; }
      .topbar p { font-size: 0.7rem; display: none; }
      .topbar-meta { font-size: 0.68rem; }
      .topbar-meta strong { font-size: 0.78rem; }
      .page {
        padding: 10px 10px 12px;
      }
      .page.active {
        overflow-y: auto;
        overflow-x: hidden;
        -webkit-overflow-scrolling: touch;
      }
      #page-dashboard.page.active,
      #page-patient.page.active,
      #page-logging.page.active,
      #page-alerts.page.active {
        overflow-y: auto;
        padding: 8px 10px 10px;
      }
      .med-dash {
        gap: 8px;
        min-height: min-content;
      }
      .med-status-bar {
        flex-wrap: wrap;
        gap: 6px;
        padding: 8px 10px;
      }
      .med-status-patient {
        flex: 1 1 100%;
        max-width: 100%;
        width: 100%;
        justify-content: flex-start;
      }
      .ward-pill-dash { display: none; }
      .topbar-actions { gap: 8px; }
      .sound-toggle { width: 32px; height: 32px; font-size: 14px; }
      .med-vitals-grid {
        grid-template-columns: 1fr;
        gap: 8px;
      }
      .med-vitals-side {
        grid-column: auto;
        flex-direction: column;
        gap: 8px;
      }
      .med-vital {
        min-height: auto;
        padding: 12px 14px;
      }
      .med-vital-value { font-size: 2rem; }
      .med-vital-compact { min-height: auto; }
      #page-dashboard .ecg-wrap {
        flex: none;
        min-height: 0;
      }
      #page-dashboard .ecg-stage {
        flex: none;
        min-height: 200px;
        height: 42vw;
        max-height: 280px;
      }
      .record-stats-row { grid-template-columns: 1fr; }
      .record-stat {
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
        text-align: left;
        padding: 12px 14px;
        gap: 12px;
      }
      .record-stat-label { flex: 1; margin: 0; }
      .record-stat-value { font-size: 1rem; flex-shrink: 0; }
      .record-contact-row { grid-template-columns: 1fr; }
      .record-profile {
        flex-wrap: wrap;
        padding: 14px;
        gap: 12px;
      }
      .record-profile-main { width: calc(100% - 82px); }
      .record-profile-main h2 { font-size: 1.25rem; }
      .record-profile .btn-glow {
        width: 100%;
        margin-top: 2px;
      }
      .record-page { overflow: hidden; }
      #page-patient.page.active { overflow: hidden; }
      #page-alerts.page.active { overflow: hidden; }
      .alerts-summary { grid-template-columns: repeat(3, 1fr); gap: 6px; }
      .alerts-summary-card { padding: 8px 6px; font-size: 0.58rem; }
      .alerts-summary-card span { font-size: 1.15rem; }
      .alerts-hero { flex-wrap: wrap; padding: 12px 14px; }
      .alerts-hero h3 { font-size: 0.95rem; }
      .alert-row { padding: 11px 12px; gap: 10px; }
      .alert-row-icon { width: 38px; height: 38px; font-size: 17px; }
      .alert-row-top strong { font-size: 0.82rem; }
      .alert-tip { font-size: 0.68rem; padding: 6px 8px; }
      .logging-toolbar {
        flex-direction: column;
        align-items: stretch;
        gap: 10px;
      }
      .logging-controls {
        flex-direction: column;
        align-items: stretch;
      }
      .logging-controls select,
      .logging-controls .btn-log {
        width: 100%;
      }
      .logging-stats {
        justify-content: space-between;
        width: 100%;
      }
      .logging-table-scroll {
        overflow-x: auto;
        overflow-y: auto;
      }
      .log-table { min-width: 520px; font-size: 0.72rem; }
      .log-table th, .log-table td { padding: 8px 8px; }
      .form-grid { grid-template-columns: 1fr; }
      .form-field.full { grid-column: span 1; }
      .patient-modal { padding: 10px; align-items: flex-end; }
      .patient-modal-card {
        max-height: 92dvh;
        border-radius: 18px 18px 0 0;
        width: 100%;
      }
      .info-grid { grid-template-columns: 1fr; }
      .vitals-row { grid-template-columns: 1fr; }
    }
 
    /* Small phones */
    @media (max-width: 400px) {
      .med-vital-icon-wrap { width: 52px; }
      .vital-icon-box { width: 46px; height: 46px; }
      .vital-icon-heart svg { width: 22px; height: 22px; }
      .med-vital-value { font-size: 1.75rem; }
      .med-compact-value { font-size: 1.15rem; }
      .nav-item { font-size: 0.52rem; min-height: 50px; }
      .ecg-overlay-labels { font-size: 0.55rem; gap: 8px; }
      #page-dashboard .ecg-stage {
        min-height: 160px;
        height: 38vw;
      }
    }
  </style>
</head>
<body>
  <div class="viewport-wrap">
    <div class="app-shell">
      <aside class="sidebar">
        <div class="sidebar-brand">
          <div class="sidebar-logo">
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <path d="M4 12h2l2-4 3 8 2-5 2 5 3-8 2 4h2"/>
            </svg>
          </div>
          <div>
            <strong>MedMonitor</strong>
            <span>Patient Care IoT</span>
          </div>
        </div>
        <div class="nav-label">Clinical</div>
        <nav class="nav">
          <button class="nav-item active" data-page="dashboard"><span class="nav-icon-wrap"><span class="nav-icon">&#128147;</span></span><span class="nav-text"><span class="nav-text-long">Vitals Monitor</span><span class="nav-text-short">Vitals</span></span></button>
          <button class="nav-item" data-page="patient"><span class="nav-icon-wrap"><span class="nav-icon">&#128100;</span></span><span class="nav-text"><span class="nav-text-long">Patient Record</span><span class="nav-text-short">Patient</span></span></button>
          <button class="nav-item" data-page="logging"><span class="nav-icon-wrap"><span class="nav-icon">&#128202;</span></span><span class="nav-text"><span class="nav-text-long">Data Logging</span><span class="nav-text-short">Logging</span></span></button>
          <button class="nav-item" data-page="alerts"><span class="nav-icon-wrap"><span class="nav-icon">&#128680;</span></span><span class="nav-text"><span class="nav-text-long">Alerts</span><span class="nav-text-short">Alerts</span></span></button>
        </nav>
        <div class="sidebar-foot">
          <div class="live-pill"><span class="live-dot" id="liveDot"></span><span id="connText">Connecting</span></div>
          <span id="clock">--:--:--</span>
        </div>
      </aside>
 
      <div class="main">
        <header class="topbar">
          <div>
            <h1 id="pageTitle">Dashboard</h1>
            <p id="pageSubtitle">Live vitals and ECG waveform</p>
          </div>
          <div class="topbar-actions">
            <button type="button" class="sound-toggle" id="btnSoundToggle" title="Toggle heartbeat sound" aria-label="Toggle heartbeat sound">
              <svg class="sound-on" viewBox="0 0 24 24" aria-hidden="true"><path d="M11 5L6 9H2v6h4l5 4V5z"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg>
              <svg class="sound-off" viewBox="0 0 24 24" aria-hidden="true"><path d="M11 5L6 9H2v6h4l5 4V5z"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/></svg>
            </button>
            <div class="topbar-meta">
              <span>Last update</span>
              <strong id="lastUpdate">--</strong>
            </div>
          </div>
        </header>
 
        <div class="page-area">
          <!-- DASHBOARD -->
          <section class="page active" id="page-dashboard">
            <div class="med-dash">
              <div class="med-status-bar">
                <div class="med-status-pill live-pill-dash">
                  <span class="med-status-dot"></span>
                  <span>Live</span>
                </div>
                <div class="med-status-pill ward-pill-dash">
                  <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 21h18M5 21V7l7-4 7 4v14M9 21v-6h6v6"/></svg>
                  <span>ICU Monitor</span>
                </div>
                <div class="med-status-patient">
                  <span class="med-chip-icon">
                    <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                  </span>
                  <span id="dashPatientName">Patient Monitor</span>
                </div>
              </div>
 
              <div class="dash-section-label">Live Vitals</div>
 
              <div class="med-vitals-grid">
                <div class="med-vital med-vital-heart glass">
                  <div class="med-vital-icon-wrap">
                    <div class="vital-icon-box vital-icon-heart" id="heartIcon">
                      <svg viewBox="0 0 24 24" aria-hidden="true">
                        <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                      </svg>
                    </div>
                  </div>
                  <div class="med-vital-body">
                    <div class="med-vital-top">
                      <span class="med-vital-title"><span class="vt-ico"><svg viewBox="0 0 24 24"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" fill="currentColor" stroke="none"/></svg></span>Heart Rate</span>
                      <span class="badge watch" id="bpmBadge">WAIT</span>
                    </div>
                    <div class="med-vital-value" id="bpmWrap"><span id="bpm">--</span><span class="med-unit">BPM</span></div>
                    <div class="med-range">Normal range: 60 – 100 BPM</div>
                    <div class="bar med-bar"><div class="bar-fill" id="bpmBar" style="width:6%"></div></div>
                  </div>
                </div>
 
                <div class="med-vital med-vital-spo2 glass">
                  <div class="med-vital-icon-wrap">
                    <div class="vital-icon-box vital-icon-spo2">
                      <span class="spo2-symbol">O&#8322;</span>
                    </div>
                  </div>
                  <div class="med-vital-body">
                    <div class="med-vital-top">
                      <span class="med-vital-title"><span class="vt-ico"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M8 12h8M10 9v6M14 9v6"/></svg></span>Blood Oxygen</span>
                      <span class="badge watch" id="spo2Badge">WAIT</span>
                    </div>
                    <div class="med-vital-value" id="spo2Wrap"><span id="spo2">--</span><span class="med-unit">% SpO&#8322;</span></div>
                    <div class="med-range">Normal range: 95 – 100%</div>
                    <div class="bar med-bar"><div class="bar-fill" id="spo2Bar" style="width:6%"></div></div>
                  </div>
                </div>
 
                <div class="med-vitals-side">
                  <div class="med-vital-compact glass temp">
                    <div class="med-compact-icon">
                      <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M14 14.76V3.5a2.5 2.5 0 0 0-5 0v11.26a4.5 4.5 0 1 0 5 0z"/></svg>
                    </div>
                    <div class="med-compact-body">
                      <div class="med-vital-top">
                        <span class="med-vital-title"><span class="vt-ico" style="background:#ffedd5;color:#ea580c"><svg viewBox="0 0 24 24"><path d="M14 14.76V3.5a2.5 2.5 0 0 0-5 0v11.26a4.5 4.5 0 1 0 5 0z" fill="currentColor" stroke="none"/></svg></span>Body Temp</span>
                        <span class="badge watch" id="tempBadge">WAIT</span>
                      </div>
                      <div class="med-compact-value" id="bodyTempWrap"><span id="bodyTemp">--</span><span class="med-unit">&deg;C</span></div>
                      <div class="bar med-bar"><div class="bar-fill" id="bodyTempBar" style="width:6%"></div></div>
                    </div>
                  </div>
                  <div class="med-vital-compact glass room">
                    <div class="med-compact-icon">
                      <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 10.5L12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1v-9.5z"/></svg>
                    </div>
                    <div class="med-compact-body">
                      <div class="med-vital-top">
                        <span class="med-vital-title"><span class="vt-ico" style="background:#dcfce7;color:#16a34a"><svg viewBox="0 0 24 24"><path d="M3 10.5L12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" fill="currentColor" stroke="none"/></svg></span>Room Temp</span>
                        <span class="badge watch" id="roomBadge">WAIT</span>
                      </div>
                      <div class="med-compact-value" id="roomTempWrap"><span id="roomTemp">--</span><span class="med-unit">&deg;C</span></div>
                      <div class="bar med-bar"><div class="bar-fill" id="roomTempBar" style="width:6%"></div></div>
                    </div>
                  </div>
                  <div class="med-vital-compact glass hum">
                    <div class="med-compact-icon">
                      <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"/></svg>
                    </div>
                    <div class="med-compact-body">
                      <div class="med-vital-top">
                        <span class="med-vital-title"><span class="vt-ico" style="background:#cffafe;color:#0891b2"><svg viewBox="0 0 24 24"><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z" fill="currentColor" stroke="none"/></svg></span>Humidity</span>
                        <span class="badge watch" id="humBadge">WAIT</span>
                      </div>
                      <div class="med-compact-value" id="humidityWrap"><span id="humidity">--</span><span class="med-unit">% RH</span></div>
                      <div class="bar med-bar"><div class="bar-fill" id="humBar" style="width:6%"></div></div>
                    </div>
                  </div>
                </div>
              </div>
 
              <div class="dash-section-label" style="margin-top:2px">ECG Waveform</div>
 
              <div class="ecg-wrap glass med-ecg">
                <div class="ecg-head">
                  <div class="ecg-title-block">
                    <div class="ecg-icon-wrap">
                      <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 12h2l2-4 3 8 2-5 2 5 3-8 2 4h2"/></svg>
                    </div>
                    <div>
                      <h3>Electrocardiogram · Lead I</h3>
                    </div>
                  </div>
                  <span class="ecg-badge-pill live" id="ecgBadge">STREAMING</span>
                </div>
                <div class="ecg-stage">
                  <div class="ecg-overlay-labels">
                    <span>1 mV/div</span>
                    <span>25 mm/s</span>
                  </div>
                  <canvas id="ecgCanvas"></canvas>
                </div>
              </div>
            </div>
          </section>
 
          <!-- PATIENT RECORD -->
          <section class="page" id="page-patient">
            <div class="record-page">
              <div class="record-banner glass">
                <div class="record-banner-bg"></div>
                <div class="record-profile">
                  <div class="record-avatar-ring">
                    <div class="patient-avatar" id="viewAvatar">?</div>
                  </div>
                  <div class="record-profile-main">
                    <h2 id="viewName">No patient saved</h2>
                    <div class="patient-chips">
                      <span class="patient-chip" id="viewId">No ID</span>
                      <span class="patient-chip loc">Bed <span id="viewBed">--</span> &middot; Ward <span id="viewWard">--</span></span>
                    </div>
                  </div>
                  <button type="button" class="btn btn-primary btn-glow" id="btnEditPatient">&#9998; Edit</button>
                </div>
              </div>
 
              <div class="record-scroll">
                <div>
                  <h4 class="record-section-title">Personal Information</h4>
                  <div class="record-stats-row">
                    <div class="record-stat glass rc-age">
                      <span class="record-stat-icon">&#127874;</span>
                      <span class="record-stat-label">Age</span>
                      <span class="record-stat-value" id="viewAge">--</span>
                    </div>
                    <div class="record-stat glass rc-gender">
                      <span class="record-stat-icon">&#9895;</span>
                      <span class="record-stat-label">Gender</span>
                      <span class="record-stat-value" id="viewGender">--</span>
                    </div>
                    <div class="record-stat glass rc-blood">
                      <span class="record-stat-icon">&#128167;</span>
                      <span class="record-stat-label">Blood</span>
                      <span class="record-stat-value" id="viewBlood">--</span>
                    </div>
                  </div>
                </div>
 
                <div>
                  <h4 class="record-section-title">Contact &amp; ID</h4>
                  <div class="record-contact-row">
                    <div class="record-detail-card glass rc-phone">
                      <span class="field-icon ic-contact">&#128222;</span>
                      <div>
                        <div class="record-detail-label">Phone</div>
                        <div class="record-detail-value" id="viewContact">--</div>
                      </div>
                    </div>
                    <div class="record-detail-card glass rc-id">
                      <span class="field-icon ic-id">&#127380;</span>
                      <div>
                        <div class="record-detail-label">Patient ID</div>
                        <div class="record-detail-value" id="viewIdDetail">--</div>
                      </div>
                    </div>
                  </div>
                </div>
 
                <div class="record-notes-card glass">
                  <h4 class="record-section-title">&#128221; Clinical Notes</h4>
                  <div class="record-notes-body" id="viewNotes">No notes added.</div>
                </div>
              </div>
            </div>
          </section>
 
          <div class="patient-modal" id="patientModal">
            <div class="patient-modal-backdrop" id="patientModalBackdrop"></div>
            <div class="patient-modal-card glass">
              <div class="patient-modal-head">
                <h3><span class="field-icon ic-name">&#128100;</span>Edit Patient Details</h3>
                <button type="button" class="btn-icon" id="btnClosePatientModal" title="Close">&times;</button>
              </div>
              <form id="patientForm" class="form-grid">
                <div class="form-field">
                  <label for="inpName"><span class="field-icon ic-name">&#128100;</span>Full Name</label>
                  <input type="text" id="inpName" name="name" placeholder="Enter patient name" />
                </div>
                <div class="form-field">
                  <label for="inpId"><span class="field-icon ic-id">&#127380;</span>Patient ID</label>
                  <input type="text" id="inpId" name="patientId" placeholder="e.g. PT-2048" />
                </div>
                <div class="form-field">
                  <label for="inpBed"><span class="field-icon ic-bed">&#128719;</span>Bed</label>
                  <input type="text" id="inpBed" name="bed" placeholder="e.g. 03" />
                </div>
                <div class="form-field">
                  <label for="inpWard"><span class="field-icon ic-ward">&#127973;</span>Ward</label>
                  <input type="text" id="inpWard" name="ward" placeholder="e.g. ICU" />
                </div>
                <div class="form-field">
                  <label for="inpAge"><span class="field-icon ic-age">&#127874;</span>Age</label>
                  <input type="number" id="inpAge" name="age" min="0" max="130" placeholder="Years" />
                </div>
                <div class="form-field">
                  <label for="inpBlood"><span class="field-icon ic-blood">&#128167;</span>Blood Group</label>
                  <select id="inpBlood" name="bloodGroup">
                    <option value="">Select</option>
                    <option value="A+">A+</option>
                    <option value="A-">A-</option>
                    <option value="B+">B+</option>
                    <option value="B-">B-</option>
                    <option value="AB+">AB+</option>
                    <option value="AB-">AB-</option>
                    <option value="O+">O+</option>
                    <option value="O-">O-</option>
                  </select>
                </div>
                <div class="form-field">
                  <label for="inpGender"><span class="field-icon ic-gender">&#9895;</span>Gender</label>
                  <select id="inpGender" name="gender">
                    <option value="">Select</option>
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                    <option value="Other">Other</option>
                  </select>
                </div>
                <div class="form-field">
                  <label for="inpContact"><span class="field-icon ic-contact">&#128222;</span>Contact</label>
                  <input type="text" id="inpContact" name="contact" placeholder="Phone or email" />
                </div>
                <div class="form-field full">
                  <label for="inpNotes"><span class="field-icon ic-notes">&#128221;</span>Notes</label>
                  <textarea id="inpNotes" name="notes" placeholder="Medical notes, allergies, etc."></textarea>
                </div>
              </form>
              <div class="form-actions">
                <button type="button" class="btn btn-primary" id="btnSavePatient">Save Changes</button>
                <button type="button" class="btn btn-secondary" id="btnCancelPatient">Cancel</button>
                <button type="button" class="btn btn-danger" id="btnClearPatient">Clear All</button>
              </div>
              <div class="save-msg" id="saveMsg"></div>
            </div>
          </div>
 
          <!-- DATA LOGGING -->
          <section class="page" id="page-logging">
            <div class="logging-page">
              <div class="logging-toolbar glass">
                <div class="logging-controls">
                  <label for="logInterval">Interval</label>
                  <select id="logInterval">
                    <option value="2000">2 seconds</option>
                    <option value="3000">3 seconds</option>
                    <option value="5000" selected>5 seconds</option>
                    <option value="10000">10 seconds</option>
                    <option value="15000">15 seconds</option>
                    <option value="30000">30 seconds</option>
                    <option value="60000">60 seconds</option>
                  </select>
                  <button type="button" class="btn btn-log btn-log-start" id="btnLogStart">&#9654; Start</button>
                  <button type="button" class="btn btn-log btn-log-stop" id="btnLogStop">&#9632; Stop</button>
                  <button type="button" class="btn btn-log btn-secondary" id="btnLogClear">Clear</button>
                  <button type="button" class="btn btn-log btn-log-export" id="btnLogExport">&#128196; Export Excel</button>
                </div>
                <div class="logging-stats">
                  <span id="logCount">0 records</span>
                  <span class="log-status-pill stopped" id="logStatus">Stopped</span>
                </div>
              </div>
              <div class="logging-table-wrap glass">
                <div class="logging-table-head">
                  <h4>&#128202; Vitals Data Log</h4>
                  <span style="font-size:0.72rem;color:var(--muted);font-weight:700" id="logIntervalLabel">Every 5s</span>
                </div>
                <div class="logging-table-scroll">
                  <table class="log-table">
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>Timestamp</th>
                        <th>BPM</th>
                        <th>SpO&#8322; (%)</th>
                        <th>Body Temp (&deg;C)</th>
                        <th>Room Temp (&deg;C)</th>
                        <th>Humidity (%)</th>
                      </tr>
                    </thead>
                    <tbody id="logTableBody">
                      <tr><td colspan="7" class="log-empty">No data logged yet. Press Start to begin recording.</td></tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </section>
 
          <!-- ALERTS -->
          <section class="page" id="page-alerts">
            <div class="alerts-page">
              <div class="alerts-hero glass">
                <div>
                  <h3>&#128680; Clinical Alert Center</h3>
                  <p>Live sensor status, warnings &amp; care suggestions</p>
                </div>
                <span class="alerts-status-badge good" id="alertBadge">SAFE</span>
              </div>
 
              <div class="alerts-summary">
                <div class="alerts-summary-card warn glass">
                  <span id="alertWarnCount">0</span>Warnings
                </div>
                <div class="alerts-summary-card ok glass">
                  <span id="alertOkCount">0</span>Normal
                </div>
                <div class="alerts-summary-card info glass">
                  <span id="alertInfoCount">0</span>Info
                </div>
              </div>
 
              <div class="alerts-scroll">
                <div class="alerts-section">
                  <h4 class="alerts-section-title">&#10084; Cardiac Monitoring</h4>
                  <div class="alert-row alert-info glass" id="alertRow1">
                    <div class="alert-row-icon" id="alertIcon1">&#10084;</div>
                    <div class="alert-row-body">
                      <div class="alert-row-top">
                        <strong id="alertTitle1">Heart Rate</strong>
                        <span class="alert-pill info" id="alertPill1">INFO</span>
                      </div>
                      <p id="alertMsg1">Waiting for sensor data...</p>
                      <p class="alert-tip" id="alertTip1">Normal resting range: 60–100 BPM.</p>
                    </div>
                  </div>
                  <div class="alert-row alert-info glass" id="alertRow2">
                    <div class="alert-row-icon" id="alertIcon2">&#9889;</div>
                    <div class="alert-row-body">
                      <div class="alert-row-top">
                        <strong id="alertTitle2">ECG Waveform</strong>
                        <span class="alert-pill info" id="alertPill2">INFO</span>
                      </div>
                      <p id="alertMsg2">Checking ECG signal...</p>
                      <p class="alert-tip" id="alertTip2">Ensure RA, LA, and RL electrodes are firmly attached.</p>
                    </div>
                  </div>
                </div>
 
                <div class="alerts-section">
                  <h4 class="alerts-section-title">&#128167; Oxygen &amp; Respiratory</h4>
                  <div class="alert-row alert-info glass" id="alertRow3">
                    <div class="alert-row-icon" id="alertIcon3">O&#8322;</div>
                    <div class="alert-row-body">
                      <div class="alert-row-top">
                        <strong id="alertTitle3">Blood Oxygen (SpO&#8322;)</strong>
                        <span class="alert-pill info" id="alertPill3">INFO</span>
                      </div>
                      <p id="alertMsg3">Place finger on pulse oximeter sensor.</p>
                      <p class="alert-tip" id="alertTip3">Keep hand still; normal SpO&#8322; is 95–100%.</p>
                    </div>
                  </div>
                </div>
 
                <div class="alerts-section">
                  <h4 class="alerts-section-title">&#127777; Temperature &amp; Environment</h4>
                  <div class="alert-row alert-info glass" id="alertRow4">
                    <div class="alert-row-icon" id="alertIcon4">&#127777;</div>
                    <div class="alert-row-body">
                      <div class="alert-row-top">
                        <strong id="alertTitle4">Body Temperature</strong>
                        <span class="alert-pill info" id="alertPill4">INFO</span>
                      </div>
                      <p id="alertMsg4">Monitoring body temperature...</p>
                      <p class="alert-tip" id="alertTip4">Normal body temp: 36.1–37.2 &deg;C.</p>
                    </div>
                  </div>
                  <div class="alert-row alert-info glass" id="alertRow5">
                    <div class="alert-row-icon" id="alertIcon5">&#127968;</div>
                    <div class="alert-row-body">
                      <div class="alert-row-top">
                        <strong id="alertTitle5">Room Environment</strong>
                        <span class="alert-pill info" id="alertPill5">INFO</span>
                      </div>
                      <p id="alertMsg5">Checking room temp and humidity...</p>
                      <p class="alert-tip" id="alertTip5">Ideal room: 20–24 &deg;C, humidity 40–60%.</p>
                    </div>
                  </div>
                </div>
 
                <div class="alerts-section">
                  <h4 class="alerts-section-title">&#128225; System Status</h4>
                  <div class="alert-row alert-info glass" id="alertRow6">
                    <div class="alert-row-icon" id="alertIcon6">&#128246;</div>
                    <div class="alert-row-body">
                      <div class="alert-row-top">
                        <strong id="alertTitle6">Device Connection</strong>
                        <span class="alert-pill info" id="alertPill6">INFO</span>
                      </div>
                      <p id="alertMsg6">Connecting to ESP32 monitor...</p>
                      <p class="alert-tip" id="alertTip6">Ensure ESP32 is powered and on the same WiFi network.</p>
                    </div>
                  </div>
                </div>
 
                <div class="alerts-suggestions glass">
                  <h4 class="alerts-section-title">&#128161; Clinical Suggestions</h4>
                  <ul class="alert-suggest-list" id="alertSuggestions">
                    <li>All systems initializing — suggestions will appear as data arrives.</li>
                  </ul>
                </div>
              </div>
            </div>
          </section>
        </div>
      </div>
    </div>
  </div>
 
  <script>
    const $ = (id) => document.getElementById(id);
    const pages = {
      dashboard: { title: "Vitals Monitor", sub: "Real-time cardiac and physiological monitoring" },
      patient: { title: "Patient Record", sub: "View and edit patient information" },
      logging: { title: "Data Logging", sub: "Record vitals at selected intervals and export" },
      alerts: { title: "Clinical Alerts", sub: "System warnings and sensor status" }
    };
    const ui = {
      clock: $("clock"), lastUpdate: $("lastUpdate"), pageTitle: $("pageTitle"), pageSubtitle: $("pageSubtitle"),
      bpm: $("bpm"), spo2: $("spo2"), bodyTemp: $("bodyTemp"),
      roomTemp: $("roomTemp"), humidity: $("humidity"),
      bpmBar: $("bpmBar"), spo2Bar: $("spo2Bar"), bodyTempBar: $("bodyTempBar"),
      roomTempBar: $("roomTempBar"), humBar: $("humBar"),
      bpmBadge: $("bpmBadge"), spo2Badge: $("spo2Badge"), tempBadge: $("tempBadge"),
      roomBadge: $("roomBadge"), humBadge: $("humBadge"),
      ecgBadge: $("ecgBadge"),
      alertBadge: $("alertBadge"),
      alertWarnCount: $("alertWarnCount"), alertOkCount: $("alertOkCount"), alertInfoCount: $("alertInfoCount"),
      alertSuggestions: $("alertSuggestions"),
      connText: $("connText"), liveDot: $("liveDot"),
      alertTitle1: $("alertTitle1"), alertMsg1: $("alertMsg1"), alertTip1: $("alertTip1"),
      alertIcon1: $("alertIcon1"), alertPill1: $("alertPill1"), alertRow1: $("alertRow1"),
      alertTitle2: $("alertTitle2"), alertMsg2: $("alertMsg2"), alertTip2: $("alertTip2"),
      alertIcon2: $("alertIcon2"), alertPill2: $("alertPill2"), alertRow2: $("alertRow2"),
      alertTitle3: $("alertTitle3"), alertMsg3: $("alertMsg3"), alertTip3: $("alertTip3"),
      alertIcon3: $("alertIcon3"), alertPill3: $("alertPill3"), alertRow3: $("alertRow3"),
      alertTitle4: $("alertTitle4"), alertMsg4: $("alertMsg4"), alertTip4: $("alertTip4"),
      alertIcon4: $("alertIcon4"), alertPill4: $("alertPill4"), alertRow4: $("alertRow4"),
      alertTitle5: $("alertTitle5"), alertMsg5: $("alertMsg5"), alertTip5: $("alertTip5"),
      alertIcon5: $("alertIcon5"), alertPill5: $("alertPill5"), alertRow5: $("alertRow5"),
      alertTitle6: $("alertTitle6"), alertMsg6: $("alertMsg6"), alertTip6: $("alertTip6"),
      alertIcon6: $("alertIcon6"), alertPill6: $("alertPill6"), alertRow6: $("alertRow6"),
      patientForm: $("patientForm"), saveMsg: $("saveMsg"),
      patientModal: $("patientModal"),
      viewAvatar: $("viewAvatar"),
      viewName: $("viewName"), viewId: $("viewId"), viewIdDetail: $("viewIdDetail"),
      viewBed: $("viewBed"), viewWard: $("viewWard"),
      viewAge: $("viewAge"), viewGender: $("viewGender"),
      viewBlood: $("viewBlood"),
      viewContact: $("viewContact"), viewNotes: $("viewNotes"),
      heartIcon: $("heartIcon"), dashPatientName: $("dashPatientName")
    };
 
    const PATIENT_KEY = "phm_patient_v1";
    const defaultPatient = {
      name: "", patientId: "", bed: "", ward: "",
      age: "", bloodGroup: "", gender: "", contact: "", notes: ""
    };
 
    const PLOT_MAX = 1023;
    const ECG_POLL_MS = 25;
    const BPM_UI_MS = 1000;
    const ECG_Y_MARGIN = 24;
    const SCROLL_STEP = 1;
    let ecgFail = 0, vitalsFail = 0;
    let connOnline = false;
    let connFailStreak = 0;
    const CONN_FAIL_LIMIT = 12;
    let canvasW = 0, canvasH = 0;
    let heightOld = 0;
    let traceReady = false;
    let ecgPollBusy = false;
    let leadsOffState = true;
    let lastVitals = { spo2: -1, finger: false, spo2Valid: false, bodyT: -999, roomT: 0, hum: 0, bme: false };
    let heartAudioCtx = null;
    let heartSoundOn = true;
    let heartSoundTimer = null;
    let lastSoundBpm = 0;
    let audioUnlocked = false;
    let latestBpm = 0;
    let displayedBpm = -1;
    let lastBpmUiTick = 0;
    let lastBeatAnimBpm = 0;
    let bpmUiReady = false;
    let prevLeadsOff = true;
    let logData = [];
    let logTimer = null;
    let logRunning = false;
    const LOG_KEY = "phm_log_v1";
    const MAX_LOG_ROWS = 500;
 
    const canvas = $("ecgCanvas");
    const ctx = canvas.getContext("2d");
 
    document.querySelectorAll(".nav-item").forEach((btn) => {
      btn.addEventListener("click", () => {
        const id = btn.dataset.page;
        document.querySelectorAll(".nav-item").forEach((b) => b.classList.remove("active"));
        document.querySelectorAll(".page").forEach((p) => p.classList.remove("active"));
        btn.classList.add("active");
        $("page-" + id).classList.add("active");
        ui.pageTitle.textContent = pages[id].title;
        ui.pageSubtitle.textContent = pages[id].sub;
        const soundBtn = $("btnSoundToggle");
        if (soundBtn) soundBtn.style.display = id === "dashboard" ? "" : "none";
        if (id === "dashboard") requestAnimationFrame(resizeCanvas);
        window.scrollTo(0, 0);
        const activePage = $("page-" + id);
        if (activePage) activePage.scrollTop = 0;
      });
    });
 
    const ecgStage = () => canvas.parentElement;
 
    function resizeCanvas() {
      const stage = ecgStage();
      if (!stage) return;
      const w = stage.clientWidth;
      const h = stage.clientHeight;
      if (w < 10 || h < 10) return;
      if (w === canvasW && h === canvasH) return;
      canvasW = w;
      canvasH = h;
      canvas.width = w;
      canvas.height = h;
      ctx.setTransform(1, 0, 0, 1, 0, 0);
      ctx.clearRect(0, 0, w, h);
      heightOld = h * 0.54;
      traceReady = false;
    }
 
    if (window.ResizeObserver && ecgStage()) {
      const ro = new ResizeObserver(() => resizeCanvas());
      ro.observe(ecgStage());
    }
    window.addEventListener("resize", resizeCanvas);
    window.addEventListener("orientationchange", () => {
      setTimeout(() => {
        resizeCanvas();
      }, 200);
    });
    requestAnimationFrame(() => requestAnimationFrame(resizeCanvas));
 
    function setBar(el, pct) { el.style.width = Math.max(6, Math.min(pct, 100)) + "%"; }
    function flashVital(el) {
      if (!el) return;
      el.classList.remove("vital-flash");
      void el.offsetWidth;
      el.classList.add("vital-flash");
    }
    function pulseBpmValue() {
      const el = ui.bpm;
      if (!el) return;
      el.classList.remove("bpm-pulse");
      void el.offsetWidth;
      el.classList.add("bpm-pulse");
    }
    function setBadge(el, text, kind) {
      el.textContent = text;
      if (el.id === "alertBadge") {
        el.className = "alerts-status-badge " + kind;
      } else if (el.id === "ecgBadge") {
        el.className = "ecg-badge-pill " + kind;
      } else {
        el.className = "badge " + kind;
      }
    }
    function fmtTime() {
      return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
    }
    function touchUpdate() { ui.lastUpdate.textContent = "Just now"; ui.clock.textContent = fmtTime(); }
 
    function setConn(ok) {
      if (connOnline === ok) return;
      connOnline = ok;
      ui.connText.textContent = ok ? "Live" : "Offline";
      ui.liveDot.className = ok ? "live-dot" : "live-dot off";
    }
 
    function markConnSuccess() {
      connFailStreak = 0;
      ecgFail = 0;
      setConn(true);
    }
 
    function markConnFailure() {
      connFailStreak++;
      if (connFailStreak >= CONN_FAIL_LIMIT) {
        setConn(false);
      }
    }
 
    function loadPatientForm(data) {
      $("inpName").value = data.name || "";
      $("inpId").value = data.patientId || "";
      $("inpBed").value = data.bed || "";
      $("inpWard").value = data.ward || "";
      $("inpAge").value = data.age || "";
      $("inpBlood").value = data.bloodGroup || "";
      $("inpGender").value = data.gender || "";
      $("inpContact").value = data.contact || "";
      $("inpNotes").value = data.notes || "";
      updatePatientPreview(data);
    }
 
    function readPatientForm() {
      return {
        name: $("inpName").value.trim(),
        patientId: $("inpId").value.trim(),
        bed: $("inpBed").value.trim(),
        ward: $("inpWard").value.trim(),
        age: $("inpAge").value.trim(),
        bloodGroup: $("inpBlood").value,
        gender: $("inpGender").value,
        contact: $("inpContact").value.trim(),
        notes: $("inpNotes").value.trim()
      };
    }
 
    function patientInitials(name) {
      const parts = (name || "").trim().split(/\s+/).filter(Boolean);
      if (!parts.length) return "?";
      if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
      return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
    }
 
    function updatePatientPreview(data) {
      const hasPatient = !!(data.name || data.patientId);
      ui.viewName.textContent = data.name || "No patient saved";
      ui.viewAvatar.textContent = patientInitials(data.name);
      ui.viewId.textContent = data.patientId || "No ID";
      ui.viewIdDetail.textContent = data.patientId || "--";
      ui.viewBed.textContent = data.bed || "--";
      ui.viewWard.textContent = data.ward || "--";
      ui.viewAge.textContent = data.age ? data.age + " yrs" : "--";
      ui.viewGender.textContent = data.gender || "--";
      ui.viewBlood.textContent = data.bloodGroup || "--";
      ui.viewContact.textContent = data.contact || "--";
      ui.viewNotes.textContent = data.notes || (hasPatient ? "No notes added." : "No notes added.");
      updateDashPatient();
    }
 
    function openPatientModal() {
      let data = defaultPatient;
      try {
        const saved = localStorage.getItem(PATIENT_KEY);
        if (saved) data = { ...defaultPatient, ...JSON.parse(saved) };
      } catch (e) {}
      loadPatientForm(data);
      ui.saveMsg.textContent = "";
      ui.patientModal.classList.add("open");
    }
 
    function closePatientModal() {
      ui.patientModal.classList.remove("open");
      ui.saveMsg.textContent = "";
    }
 
    function savePatient() {
      const data = readPatientForm();
      if (!data.name && !data.patientId) {
        ui.saveMsg.textContent = "Enter at least a name or patient ID.";
        ui.saveMsg.style.color = "#ef4444";
        return;
      }
      try {
        localStorage.setItem(PATIENT_KEY, JSON.stringify(data));
        updatePatientPreview(data);
        ui.saveMsg.textContent = "Patient details saved.";
        ui.saveMsg.style.color = "#16a34a";
        setTimeout(closePatientModal, 400);
      } catch (e) {
        ui.saveMsg.textContent = "Could not save. Browser storage may be full.";
        ui.saveMsg.style.color = "#ef4444";
      }
    }
 
    function clearPatientForm() {
      loadPatientForm(defaultPatient);
      try { localStorage.removeItem(PATIENT_KEY); } catch (e) {}
      ui.saveMsg.textContent = "All patient data cleared.";
      ui.saveMsg.style.color = "#64748b";
      setTimeout(closePatientModal, 500);
    }
 
    function initPatientForm() {
      let data = defaultPatient;
      try {
        const saved = localStorage.getItem(PATIENT_KEY);
        if (saved) data = { ...defaultPatient, ...JSON.parse(saved) };
      } catch (e) {}
      updatePatientPreview(data);
      $("btnEditPatient").addEventListener("click", openPatientModal);
      $("btnClosePatientModal").addEventListener("click", closePatientModal);
      $("btnCancelPatient").addEventListener("click", closePatientModal);
      $("patientModalBackdrop").addEventListener("click", closePatientModal);
      $("btnSavePatient").addEventListener("click", savePatient);
      $("btnClearPatient").addEventListener("click", clearPatientForm);
      ui.patientForm.addEventListener("submit", (e) => { e.preventDefault(); savePatient(); });
    }
    initPatientForm();
 
    function loadPatientData() {
      try {
        const saved = localStorage.getItem(PATIENT_KEY);
        if (saved) return { ...defaultPatient, ...JSON.parse(saved) };
      } catch (e) {}
      return { ...defaultPatient };
    }
 
    function fmtLogTime(d) {
      return d.toLocaleString([], {
        year: "numeric", month: "2-digit", day: "2-digit",
        hour: "2-digit", minute: "2-digit", second: "2-digit"
      });
    }
 
    function captureLogRow() {
      const bpmVal = parseInt(ui.bpm.textContent, 10);
      return {
        ts: fmtLogTime(new Date()),
        bpm: (!isNaN(bpmVal) && ui.bpm.textContent !== "--") ? bpmVal : "",
        spo2: (lastVitals.spo2Valid && lastVitals.spo2 > 0) ? lastVitals.spo2 : "",
        bodyT: (lastVitals.bodyT > -100) ? lastVitals.bodyT.toFixed(1) : "",
        roomT: lastVitals.bme ? lastVitals.roomT.toFixed(1) : "",
        hum: lastVitals.bme ? lastVitals.hum.toFixed(1) : ""
      };
    }
 
    function updateLogTable() {
      const tbody = $("logTableBody");
      if (!logData.length) {
        tbody.innerHTML = '<tr><td colspan="7" class="log-empty">No data logged yet. Press Start to begin recording.</td></tr>';
        $("logCount").textContent = "0 records";
        return;
      }
      $("logCount").textContent = logData.length + " record" + (logData.length === 1 ? "" : "s");
      let html = "";
      const start = Math.max(0, logData.length - 200);
      for (let i = start; i < logData.length; i++) {
        const r = logData[i];
        html += "<tr><td>" + (i + 1) + "</td><td>" + r.ts + "</td><td>" + (r.bpm !== "" ? r.bpm : "--") +
          "</td><td>" + (r.spo2 !== "" ? r.spo2 : "--") + "</td><td>" + (r.bodyT !== "" ? r.bodyT : "--") +
          "</td><td>" + (r.roomT !== "" ? r.roomT : "--") + "</td><td>" + (r.hum !== "" ? r.hum : "--") + "</td></tr>";
      }
      tbody.innerHTML = html;
      const scroll = tbody.closest(".logging-table-scroll");
      if (scroll) scroll.scrollTop = scroll.scrollHeight;
    }
 
    function saveLogData() {
      try { localStorage.setItem(LOG_KEY, JSON.stringify(logData)); } catch (e) {}
    }
 
    function loadLogData() {
      try {
        const saved = localStorage.getItem(LOG_KEY);
        if (saved) logData = JSON.parse(saved);
      } catch (e) { logData = []; }
      updateLogTable();
    }
 
    function addLogEntry() {
      logData.push(captureLogRow());
      if (logData.length > MAX_LOG_ROWS) logData.shift();
      updateLogTable();
      saveLogData();
    }
 
    function getLogIntervalMs() {
      return parseInt($("logInterval").value, 10) || 5000;
    }
 
    function updateLogIntervalLabel() {
      const ms = getLogIntervalMs();
      const sec = ms / 1000;
      $("logIntervalLabel").textContent = "Every " + sec + "s";
    }
 
    function startLogging() {
      if (logRunning) return;
      logRunning = true;
      $("logStatus").textContent = "Recording";
      $("logStatus").className = "log-status-pill running";
      addLogEntry();
      logTimer = setInterval(addLogEntry, getLogIntervalMs());
    }
 
    function stopLogging() {
      logRunning = false;
      if (logTimer) { clearInterval(logTimer); logTimer = null; }
      $("logStatus").textContent = "Stopped";
      $("logStatus").className = "log-status-pill stopped";
    }
 
    function restartLoggingIfActive() {
      if (!logRunning) return;
      stopLogging();
      startLogging();
    }
 
    function clearLogging() {
      stopLogging();
      logData = [];
      try { localStorage.removeItem(LOG_KEY); } catch (e) {}
      updateLogTable();
    }
 
    function csvCell(v) {
      return '"' + String(v == null ? "" : v).replace(/"/g, '""') + '"';
    }
 
    function exportLogExcel() {
      if (!logData.length) {
        alert("No data to export. Start logging first.");
        return;
      }
      const p = loadPatientData();
      const rows = [];
      rows.push(["Patient Health Monitor - Vitals Data Log"]);
      rows.push([]);
      rows.push(["Patient Name", p.name || "N/A"]);
      rows.push(["Patient ID", p.patientId || "N/A"]);
      rows.push(["Bed", p.bed || "N/A"]);
      rows.push(["Ward", p.ward || "N/A"]);
      rows.push(["Age", p.age ? p.age + " years" : "N/A"]);
      rows.push(["Gender", p.gender || "N/A"]);
      rows.push(["Blood Group", p.bloodGroup || "N/A"]);
      rows.push(["Contact", p.contact || "N/A"]);
      rows.push(["Clinical Notes", p.notes || "N/A"]);
      rows.push(["Export Date", fmtLogTime(new Date())]);
      rows.push(["Logging Interval", (getLogIntervalMs() / 1000) + " seconds"]);
      rows.push(["Total Records", logData.length]);
      rows.push([]);
      rows.push(["#", "Timestamp", "BPM", "SpO2 (%)", "Body Temp (C)", "Room Temp (C)", "Humidity (%)"]);
      logData.forEach((r, i) => {
        rows.push([i + 1, r.ts, r.bpm, r.spo2, r.bodyT, r.roomT, r.hum]);
      });
      const csv = rows.map((row) => row.map(csvCell).join(",")).join("\r\n");
      const blob = new Blob(["\ufeff" + csv], { type: "application/vnd.ms-excel;charset=utf-8;" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      const date = new Date().toISOString().slice(0, 10);
      const pname = (p.name || "Patient").replace(/[^a-z0-9]/gi, "_");
      a.href = url;
      a.download = "PHM_Vitals_" + pname + "_" + date + ".xls";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    }
 
    function initLogging() {
      loadLogData();
      updateLogIntervalLabel();
      $("logInterval").addEventListener("change", () => {
        updateLogIntervalLabel();
        restartLoggingIfActive();
      });
      $("btnLogStart").addEventListener("click", startLogging);
      $("btnLogStop").addEventListener("click", stopLogging);
      $("btnLogClear").addEventListener("click", () => {
        if (!logData.length || confirm("Clear all logged data?")) clearLogging();
      });
      $("btnLogExport").addEventListener("click", exportLogExcel);
    }
    initLogging();
 
    function updateRoomUi(roomT, hum, bmeOk) {
      if (bmeOk) {
        ui.roomTemp.textContent = roomT.toFixed(1);
        ui.humidity.textContent = hum.toFixed(1);
        flashVital($("roomTempWrap"));
        flashVital($("humidityWrap"));
        setBar(ui.roomTempBar, Math.min(roomT * 3, 100));
        setBar(ui.humBar, hum);
        setBadge(ui.roomBadge, "NORMAL", "good");
        setBadge(ui.humBadge, "NORMAL", "good");
      } else {
        ui.roomTemp.textContent = "--";
        ui.humidity.textContent = "--";
        setBar(ui.roomTempBar, 6);
        setBar(ui.humBar, 6);
        setBadge(ui.roomBadge, "WAIT", "watch");
        setBadge(ui.humBadge, "WAIT", "watch");
      }
    }
 
    function getHeartAudioCtx() {
      if (!heartAudioCtx) {
        heartAudioCtx = new (window.AudioContext || window.webkitAudioContext)();
      }
      return heartAudioCtx;
    }
 
    async function unlockHeartAudio() {
      try {
        const ctx = getHeartAudioCtx();
        if (ctx.state === "suspended") await ctx.resume();
        const buffer = ctx.createBuffer(1, 1, 22050);
        const source = ctx.createBufferSource();
        source.buffer = buffer;
        source.connect(ctx.destination);
        source.start(0);
        audioUnlocked = true;
        if (heartSoundOn && latestBpm > 0 && !leadsOffState) startHeartSound(latestBpm);
      } catch (e) {}
    }
 
    function playMonitorBeep() {
      if (!heartSoundOn || !audioUnlocked) return;
      try {
        const ctx = getHeartAudioCtx();
        const t = ctx.currentTime;
        const master = ctx.createGain();
        master.gain.setValueAtTime(0.14, t);
        master.connect(ctx.destination);
 
        const osc1 = ctx.createOscillator();
        const g1 = ctx.createGain();
        osc1.type = "sine";
        osc1.frequency.setValueAtTime(920, t);
        osc1.frequency.exponentialRampToValueAtTime(720, t + 0.05);
        g1.gain.setValueAtTime(0, t);
        g1.gain.linearRampToValueAtTime(1, t + 0.006);
        g1.gain.exponentialRampToValueAtTime(0.001, t + 0.065);
        osc1.connect(g1);
        g1.connect(master);
        osc1.start(t);
        osc1.stop(t + 0.07);
 
        const osc2 = ctx.createOscillator();
        const g2 = ctx.createGain();
        osc2.type = "sine";
        osc2.frequency.setValueAtTime(580, t + 0.09);
        g2.gain.setValueAtTime(0, t + 0.09);
        g2.gain.linearRampToValueAtTime(0.55, t + 0.1);
        g2.gain.exponentialRampToValueAtTime(0.001, t + 0.17);
        osc2.connect(g2);
        g2.connect(master);
        osc2.start(t + 0.09);
        osc2.stop(t + 0.18);
      } catch (e) {}
    }
 
    function stopHeartSound() {
      if (heartSoundTimer) {
        clearInterval(heartSoundTimer);
        heartSoundTimer = null;
      }
      lastSoundBpm = 0;
    }
 
    function startHeartSound(bpm) {
      if (!bpm || bpm <= 0 || leadsOffState) {
        stopHeartSound();
        return;
      }
      if (!heartSoundOn) {
        stopHeartSound();
        return;
      }
      if (heartSoundTimer && lastSoundBpm === bpm) return;
      stopHeartSound();
      lastSoundBpm = bpm;
      const interval = 60000 / bpm;
      if (audioUnlocked) playMonitorBeep();
      heartSoundTimer = setInterval(() => {
        if (audioUnlocked) playMonitorBeep();
      }, interval);
    }
 
    function syncSoundToggleBtn() {
      const btn = $("btnSoundToggle");
      if (!btn) return;
      btn.classList.toggle("muted", !heartSoundOn);
      btn.title = heartSoundOn ? "Mute heartbeat sound" : "Enable heartbeat sound";
      btn.setAttribute("aria-label", btn.title);
    }
 
    function initHeartSound() {
      syncSoundToggleBtn();
      const unlockOnce = () => { unlockHeartAudio(); };
      document.addEventListener("click", unlockOnce, { once: true, passive: true, capture: true });
      document.addEventListener("touchstart", unlockOnce, { once: true, passive: true, capture: true });
      $("btnSoundToggle").addEventListener("click", async (e) => {
        e.stopPropagation();
        await unlockHeartAudio();
        heartSoundOn = !heartSoundOn;
        syncSoundToggleBtn();
        if (heartSoundOn) {
          if (latestBpm > 0 && !leadsOffState) startHeartSound(latestBpm);
        } else {
          stopHeartSound();
        }
      });
    }
    initHeartSound();
 
    function updateDashPatient() {
      try {
        const saved = localStorage.getItem(PATIENT_KEY);
        if (saved) {
          const p = JSON.parse(saved);
          if (p.name) {
            ui.dashPatientName.textContent = p.name;
            return;
          }
        }
      } catch (e) {}
      ui.dashPatientName.textContent = "Patient Monitor";
    }
 
    function setHeartBeatAnim(bpm) {
      const el = ui.heartIcon;
      if (!el) return;
      const active = bpm > 0 && !leadsOffState;
      if (!active) {
        el.classList.remove("beating");
        lastBeatAnimBpm = 0;
        stopHeartSound();
        return;
      }
      if (!el.classList.contains("beating")) el.classList.add("beating");
      if (lastBeatAnimBpm !== bpm) {
        lastBeatAnimBpm = bpm;
        el.style.setProperty("--beat-dur", (60 / bpm) + "s");
      }
      startHeartSound(bpm);
    }
 
    function applyBpmUi(bpm) {
      displayedBpm = bpm;
      if (bpm > 0) {
        const changed = ui.bpm.textContent !== String(bpm);
        ui.bpm.textContent = bpm;
        if (changed) pulseBpmValue();
        setBar(ui.bpmBar, bpm);
        setBadge(ui.bpmBadge, bpm >= 60 && bpm <= 100 ? "NORMAL" : "CHECK", bpm >= 60 && bpm <= 100 ? "good" : "watch");
        setHeartBeatAnim(bpm);
      } else {
        ui.bpm.textContent = "--";
        setBar(ui.bpmBar, 6);
        setBadge(ui.bpmBadge, "WAIT", "watch");
        setHeartBeatAnim(0);
      }
    }
 
    function maybeUpdateBpmUi(bpm) {
      latestBpm = bpm;
      const now = Date.now();
      const leadsChanged = prevLeadsOff !== leadsOffState;
      prevLeadsOff = leadsOffState;
      const urgent = bpm <= 0 || leadsOffState || leadsChanged;
      if (urgent) {
        lastBpmUiTick = now;
        bpmUiReady = false;
        applyBpmUi(bpm);
        return;
      }
      if (!bpmUiReady || now - lastBpmUiTick >= BPM_UI_MS) {
        lastBpmUiTick = now;
        bpmUiReady = true;
        applyBpmUi(bpm);
      }
    }
 
    function updateSpo2Ui(spo2, finger, spo2Valid) {
      if (finger && spo2Valid && spo2 > 0) {
        ui.spo2.textContent = spo2;
        flashVital($("spo2Wrap"));
        setBar(ui.spo2Bar, spo2);
        setBadge(ui.spo2Badge, spo2 >= 95 ? "NORMAL" : "LOW", spo2 >= 95 ? "good" : "watch");
      } else {
        ui.spo2.textContent = "--";
        setBar(ui.spo2Bar, 6);
        setBadge(ui.spo2Badge, finger ? "WAIT" : "WAIT", "watch");
      }
    }
 
    function updateBodyUi(temp) {
      if (temp > -100) {
        ui.bodyTemp.textContent = temp.toFixed(1);
        flashVital($("bodyTempWrap"));
        setBar(ui.bodyTempBar, temp * 2);
        const ok = temp >= 36.1 && temp <= 37.2;
        setBadge(ui.tempBadge, ok ? "NORMAL" : "CHECK", ok ? "good" : "watch");
      } else {
        ui.bodyTemp.textContent = "--";
        setBar(ui.bodyTempBar, 6);
        setBadge(ui.tempBadge, "WAIT", "watch");
      }
    }
 
    function setAlertRow(n, cfg) {
      const row = ui["alertRow" + n];
      const pill = ui["alertPill" + n];
      ui["alertTitle" + n].textContent = cfg.title;
      ui["alertMsg" + n].textContent = cfg.msg;
      if (ui["alertTip" + n]) ui["alertTip" + n].textContent = cfg.tip;
      if (ui["alertIcon" + n]) ui["alertIcon" + n].textContent = cfg.icon;
      pill.textContent = cfg.pill;
      pill.className = "alert-pill " + cfg.state;
      row.className = "alert-row alert-" + cfg.state + " glass";
      return cfg.state;
    }
 
    function updateAlerts(leadsOff, bpm, spo2, finger, bodyT) {
      const v = lastVitals;
      let warnN = 0, okN = 0, infoN = 0;
      const suggestions = [];
 
      function countState(s) {
        if (s === "ok") okN++;
        else if (s === "warn" || s === "bad") warnN++;
        else infoN++;
      }
 
      // 1 — Heart rate
      if (leadsOff) {
        countState(setAlertRow(1, {
          title: "Heart Rate — Leads Off",
          msg: "Cannot measure BPM without ECG electrodes.",
          tip: "Attach RA, LA, and RL pads. Clean skin with alcohol wipe first.",
          icon: "\u26A0", pill: "ALERT", state: "bad"
        }));
        suggestions.push("Re-attach all three ECG electrodes and verify cable connections.");
      } else if (bpm > 100) {
        countState(setAlertRow(1, {
          title: "Elevated Heart Rate",
          msg: bpm + " BPM detected — above normal resting range.",
          tip: "Ensure patient is at rest. Recheck in 5 minutes.",
          icon: "\u2764", pill: "CHECK", state: "warn"
        }));
        suggestions.push("Heart rate is elevated — confirm patient is resting and hydrated.");
      } else if (bpm > 0 && bpm < 60) {
        countState(setAlertRow(1, {
          title: "Low Heart Rate",
          msg: bpm + " BPM detected — below normal resting range.",
          tip: "Verify electrode placement. Consult clinician if persistent.",
          icon: "\u2764", pill: "CHECK", state: "warn"
        }));
        suggestions.push("Bradycardia detected — verify sensor contact and patient status.");
      } else if (bpm > 0) {
        countState(setAlertRow(1, {
          title: "Heart Rate Normal",
          msg: bpm + " BPM — within healthy resting range.",
          tip: "Continue routine monitoring every few minutes.",
          icon: "\u2705", pill: "NORMAL", state: "ok"
        }));
      } else {
        countState(setAlertRow(1, {
          title: "Detecting Heartbeat",
          msg: "Leads connected. Waiting for stable BPM reading.",
          tip: "Keep patient still for accurate heart rate detection.",
          icon: "\u23F3", pill: "WAIT", state: "info"
        }));
      }
 
      // 2 — ECG waveform
      if (leadsOff) {
        countState(setAlertRow(2, {
          title: "No ECG Signal",
          msg: "Waveform unavailable — leads disconnected.",
          tip: "Press electrodes firmly. Check LO+ and LO- indicator wires.",
          icon: "\u26A1", pill: "ALERT", state: "bad"
        }));
      } else {
        countState(setAlertRow(2, {
          title: "ECG Streaming Live",
          msg: "PQRST waveform updating in real time on dashboard.",
          tip: "Trace should stay centered. Report unusual spikes to clinician.",
          icon: "\u26A1", pill: "LIVE", state: "ok"
        }));
      }
 
      // 3 — SpO2
      if (!finger) {
        countState(setAlertRow(3, {
          title: "SpO\u2082 — No Finger Detected",
          msg: "Place index finger on the MAX30102 sensor.",
          tip: "Remove nail polish. Warm cold fingers before measuring.",
          icon: "O\u2082", pill: "WAIT", state: "info"
        }));
        suggestions.push("Place finger on SpO\u2082 sensor with light, steady pressure.");
      } else if (spo2 > 0 && spo2 < 90 && v.spo2Valid) {
        countState(setAlertRow(3, {
          title: "Critical Low SpO\u2082",
          msg: spo2 + "% — critically low oxygen saturation.",
          tip: "Seek immediate clinical attention. Check airway and breathing.",
          icon: "\u26A0", pill: "CRITICAL", state: "bad"
        }));
        suggestions.push("URGENT: SpO\u2082 critically low — notify clinical staff immediately.");
      } else if (spo2 > 0 && spo2 < 95 && v.spo2Valid) {
        countState(setAlertRow(3, {
          title: "Low SpO\u2082",
          msg: spo2 + "% — below normal range (95–100%).",
          tip: "Reposition finger. Ensure sensor is clean and finger is warm.",
          icon: "O\u2082", pill: "CHECK", state: "warn"
        }));
        suggestions.push("Reposition finger on oximeter — reading below 95%.");
      } else if (spo2 > 0 && v.spo2Valid) {
        countState(setAlertRow(3, {
          title: "SpO\u2082 Normal",
          msg: "Blood oxygen at " + spo2 + "% — within healthy range.",
          tip: "Maintain steady finger contact for continuous monitoring.",
          icon: "\u2705", pill: "NORMAL", state: "ok"
        }));
      } else {
        countState(setAlertRow(3, {
          title: "Calculating SpO\u2082",
          msg: "Finger detected. Algorithm stabilizing reading...",
          tip: "Hold perfectly still for 10–15 seconds.",
          icon: "O\u2082", pill: "WAIT", state: "info"
        }));
      }
 
      // 4 — Body temperature
      if (bodyT > 37.5) {
        countState(setAlertRow(4, {
          title: "Elevated Body Temperature",
          msg: bodyT.toFixed(1) + " \u00B0C — above normal (fever range).",
          tip: "Monitor for other symptoms. Notify clinician if rising.",
          icon: "\uD83C\uDF21", pill: "CHECK", state: "warn"
        }));
        suggestions.push("Body temperature elevated — monitor closely and log readings.");
      } else if (bodyT > 0 && bodyT < 35.5) {
        countState(setAlertRow(4, {
          title: "Low Body Temperature",
          msg: bodyT.toFixed(1) + " \u00B0C — below normal range.",
          tip: "Check sensor placement on skin. Keep patient warm.",
          icon: "\uD83C\uDF21", pill: "CHECK", state: "warn"
        }));
        suggestions.push("Hypothermia range detected — verify probe contact and warm patient.");
      } else if (bodyT > -100) {
        countState(setAlertRow(4, {
          title: "Body Temperature Normal",
          msg: bodyT.toFixed(1) + " \u00B0C — within normal range.",
          tip: "NTC thermistor reading stable.",
          icon: "\u2705", pill: "NORMAL", state: "ok"
        }));
      } else {
        countState(setAlertRow(4, {
          title: "Body Temp — Waiting",
          msg: "NTC thermistor sensor initializing...",
          tip: "Ensure thermistor has firm skin contact.",
          icon: "\uD83C\uDF21", pill: "WAIT", state: "info"
        }));
      }
 
      // 5 — Room environment
      if (v.bme) {
        let envState = "ok";
        let envPill = "NORMAL";
        let envTitle = "Room Environment Normal";
        let envMsg = "Room " + v.roomT.toFixed(1) + " \u00B0C \u00B7 Humidity " + v.hum.toFixed(1) + "%";
        let envTip = "Conditions within comfortable clinical range.";
        if (v.roomT > 28 || v.roomT < 18) {
          envState = "warn"; envPill = "CHECK";
          envTitle = "Room Temperature Alert";
          envMsg = "Room temp " + v.roomT.toFixed(1) + " \u00B0C — outside ideal 18–28 \u00B0C.";
          envTip = "Adjust HVAC or ventilation for patient comfort.";
          suggestions.push("Room temperature out of range — check ventilation.");
        }
        if (v.hum > 70 || v.hum < 30) {
          envState = "warn"; envPill = "CHECK";
          envTitle = "Humidity Alert";
          envMsg = "Humidity " + v.hum.toFixed(1) + "% — outside ideal 30–70%.";
          envTip = "Use dehumidifier or humidifier as needed.";
          suggestions.push("Room humidity out of range — adjust environmental controls.");
        }
        countState(setAlertRow(5, {
          title: envTitle, msg: envMsg, tip: envTip,
          icon: "\uD83C\uDFE0", pill: envPill, state: envState
        }));
      } else {
        countState(setAlertRow(5, {
          title: "BME280 Sensor Waiting",
          msg: "Room temperature and humidity sensor not ready.",
          tip: "Check BME280 I2C wiring (SDA=21, SCL=22).",
          icon: "\uD83C\uDFE0", pill: "WAIT", state: "info"
        }));
      }
 
      // 6 — Connection
      if (connOnline) {
        countState(setAlertRow(6, {
          title: "Monitor Connected",
          msg: "ESP32 live link active. Data streaming normally.",
          tip: "If readings freeze, refresh browser or check WiFi signal.",
          icon: "\uD83D\uDCF6", pill: "LIVE", state: "ok"
        }));
      } else {
        countState(setAlertRow(6, {
          title: "Monitor Offline",
          msg: "Lost connection to ESP32 health monitor.",
          tip: "Verify ESP32 power, WiFi credentials, and router range.",
          icon: "\u274C", pill: "OFFLINE", state: "bad"
        }));
        suggestions.push("Device offline — check ESP32 power and WiFi connection.");
      }
 
      ui.alertWarnCount.textContent = warnN;
      ui.alertOkCount.textContent = okN;
      ui.alertInfoCount.textContent = infoN;
 
      if (!suggestions.length) {
        suggestions.push("All vitals within normal limits. Continue routine monitoring.");
      }
      ui.alertSuggestions.innerHTML = suggestions.map((s) => "<li>" + s + "</li>").join("");
 
      const overall = warnN > 0 ? "watch" : (okN > 0 ? "good" : "watch");
      setBadge(ui.alertBadge, warnN > 0 ? "CHECK" : "SAFE", overall);
    }
 
    function valueToY(v, h, leadsOff) {
      if (leadsOff) return h * 0.54;
      const plotH = h - ECG_Y_MARGIN * 2;
      const c = Math.max(0, Math.min(PLOT_MAX, v));
      return ECG_Y_MARGIN + plotH * (1 - c / PLOT_MAX);
    }
 
    function drawEcgPoint(v, leadsOff) {
      const w = canvasW;
      const h = canvasH;
      if (w < 8 || h < 8) return;
 
      const y = valueToY(v, h, leadsOff);
 
      if (traceReady) {
        const imageData = ctx.getImageData(SCROLL_STEP, 0, w - SCROLL_STEP, h);
        ctx.putImageData(imageData, 0, 0);
        ctx.clearRect(w - SCROLL_STEP, 0, SCROLL_STEP, h);
      } else {
        traceReady = true;
        heightOld = y;
      }
 
      const x0 = Math.max(0, w - SCROLL_STEP - 1);
      const x1 = w - 1;
      ctx.beginPath();
      ctx.moveTo(x0, heightOld);
      ctx.lineTo(x1, y);
      ctx.strokeStyle = leadsOff ? "#67e8f9" : "#16a34a";
      ctx.lineWidth = 2.2;
      ctx.lineJoin = "round";
      ctx.lineCap = "round";
      ctx.stroke();
      heightOld = y;
    }
 
    function drawEcgSamples(samples, leadsOff) {
      if (!samples || !samples.length) return;
      for (let i = 0; i < samples.length; i++) {
        drawEcgPoint(samples[i], leadsOff);
      }
    }
 
    async function pollEcg() {
      if (ecgPollBusy) return;
      ecgPollBusy = true;
      try {
        const r = await fetch("/api/ecg", { cache: "no-store" });
        if (!r.ok) throw new Error("ecg");
        const d = await r.json();
        markConnSuccess();
        touchUpdate();
        leadsOffState = !!d.lo;
        maybeUpdateBpmUi(d.bpm);
        setBadge(ui.ecgBadge, d.lo ? "LEADS OFF" : "LIVE", d.lo ? "watch" : "live");
        const samples = Array.isArray(d.v) ? d.v : [d.v];
        drawEcgSamples(samples, d.lo);
        updateAlerts(leadsOffState, displayedBpm > 0 ? displayedBpm : d.bpm, lastVitals.spo2, lastVitals.finger, lastVitals.bodyT);
      } catch (e) {
        ecgFail++;
        markConnFailure();
        if (!connOnline) setBadge(ui.ecgBadge, "ERROR", "bad");
      } finally {
        ecgPollBusy = false;
      }
    }
 
    async function pollVitals() {
      try {
        const r = await fetch("/api/vitals", { cache: "no-store" });
        if (!r.ok) throw new Error("vitals");
        const d = await r.json();
        vitalsFail = 0;
        markConnSuccess();
        touchUpdate();
        lastVitals = { spo2: d.spo2, finger: d.finger, bodyT: d.bodyT, roomT: d.roomT, hum: d.hum, bme: d.bme, spo2Valid: !!d.spo2Valid };
        updateSpo2Ui(d.spo2, d.finger, d.spo2Valid);
        updateBodyUi(d.bodyT);
        updateRoomUi(d.roomT, d.hum, d.bme);
        const bpm = displayedBpm > 0 ? displayedBpm : latestBpm;
        updateAlerts(leadsOffState, bpm > 0 ? bpm : -1, d.spo2, d.finger, d.bodyT);
      } catch (e) {
        vitalsFail++;
        markConnFailure();
      }
    }
 
    setInterval(() => { ui.clock.textContent = fmtTime(); }, 1000);
    setInterval(pollEcg, ECG_POLL_MS);
    setInterval(pollVitals, 1500);
    pollEcg();
    pollVitals();
  </script>
</body>
</html>
)rawliteral";
 
#endif




Testing & Demo of ESP32 Patient Health Monitor

After completing the hardware connection and uploading the code, the ESP32 patient health monitor is ready for testing.

ESP32 Patient Health Monitor Sensor Placement on Body
Fig: ESP32 Patient Health Monitor Sensor Placement on Body

When the device is powered on, open the Serial Monitor at 115200 baud. The ESP32 connects to Wi-Fi and prints the local IP address. You should see sensor initialization messages such as ADS1115 OK, BME280 OK, and MAX30102 OK.

The Serial Monitor also prints debug data every 2 seconds: room temperature, humidity, body temperature, SpO₂, ECG plot value, raw ADC, voltage, BPM, and lead status.

Accessing the Dashboard

After the ESP32 connects to the Wi-Fi network, note the IP address from the Serial Monitor. Enter this IP in a web browser on any device connected to the same Wi-Fi network to open the MedMonitor live health dashboard.

ESP32 Patient Health Monitor Dashboard
Fig: ESP32 Patient Health Monitor Dashboard

The Vitals Monitor page shows live heart rate, SpO₂, body temperature, room temperature, humidity, and a scrolling ECG waveform panel. A speaker icon in the top bar toggles synchronized heartbeat monitor sound.

From the left-side menu, we can open Vitals Monitor, Patient Record, Data Logging, and Alerts.



ECG Waveform & Heart Rate

Attach the ECG electrodes (RA, LA, RL) with good skin contact. The dashboard ECG panel shows a live scrolling trace with PQRST-style cardiac complexes when leads are connected.

AD8232 Electrode Placement on Body
Fig: AD8232 Electrode Placement on Body

If electrodes are removed, the LO+ / LO− pins detect lead-off and the dashboard shows “LEADS OFF” with a flat cyan trace. BPM calculation pauses until valid ECG signal returns.

SpO₂ and Temperature Monitoring

Place a finger on the MAX30102 sensor to measure blood oxygen. You may wrap the sensor around the finger. Do not wrap too tightly.

Finger placement on MAX30102
Fig: Finger placement on MAX30102

Body temperature is read from the NTC thermistor probe on ADS1115 AIN1. Attach the thermistor on any part of the body. You may use something to wrap the sensor and fix properly on body.

Temperature Sensor Placement on Body
Fig: Temperature Sensor Placement on Body

Room temperature and humidity are displayed from the BME280.

ESP32 Patient Health Monitor AD8232 MAX30102 Temperature Sensor

Patient Record & Data Logging

The Patient Record page stores patient details.

You may click on Edit details to enter the patient details on this section.

The Data Logging page records vitals at selectable intervals and exports to Excel with patient information at the top.



Clinical Alerts

The Alerts page monitors cardiac rhythm, SpO₂, body temperature, room environment, and Wi-Fi connection with clinical suggestion tips and summary counters.


Applications

  • Remote patient vitals monitoring prototype
  • IoT healthcare and biomedical engineering education
  • Home wellness tracking and fitness experiments
  • Hospital ward environmental + vitals dashboard demo
  • Research projects on ECG signal acquisition and web visualization

Note: This project is intended for educational and prototyping purposes only. It is not a certified medical device and should not be used for clinical diagnosis or treatment decisions.


Video Tutorial & Guide

Share. Facebook Twitter Pinterest LinkedIn Tumblr Email Reddit Telegram WhatsApp
Previous ArticleBuck Converter vs Boost Converter: Working, Differences & Applications

Related Posts

ESP32 Fingerprint Voting Machine with Live Web Dashboard

ESP32 Fingerprint Voting Machine with Live Web Dashboard

Updated:July 12, 2026
ESP32 Fingerprint Attendance System with Live Web Dashboard

ESP32 Fingerprint Attendance System with Live Web Dashboard

Updated:July 6, 20261K
IoT Based PM & Air Quality Monitoring System using ESP32

IoT Based PM & Air Quality Monitoring System using ESP32

Updated:June 14, 20261K
DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

Updated:May 10, 20262K
IoT Activity Tracker with ESP32 & Accelerometer Gyroscope

IoT Activity Tracker with ESP32 & Accelerometer/Gyroscope

Updated:May 2, 2026

ESP32 IoT Vehicle Motion Analyzer with MPU6050 & LIS3MDL

Updated:April 27, 20261K
Add A Comment

CommentsCancel reply

Latest Posts
ESP32 Patient Health Monitor (ECG, SpO₂, BPM) & Live Dashboard

ESP32 Patient Health Monitor (ECG, SpO₂, BPM) & Live Dashboard

July 19, 2026
Buck Converter vs Boost Converter

Buck Converter vs Boost Converter: Working, Differences & Applications

July 16, 2026
ESP32 Fingerprint Voting Machine with Live Web Dashboard

ESP32 Fingerprint Voting Machine with Live Web Dashboard

July 12, 2026
ESP32 Fingerprint Attendance System with Live Web Dashboard

ESP32 Fingerprint Attendance System with Live Web Dashboard

July 6, 2026
IoT Based PM & Air Quality Monitoring System using ESP32

IoT Based PM & Air Quality Monitoring System using ESP32

June 14, 2026
DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

DIY ESP32 MLX90640 IR Thermal Camera with Live Web Display

May 10, 2026
IoT Activity Tracker with ESP32 & Accelerometer Gyroscope

IoT Activity Tracker with ESP32 & Accelerometer/Gyroscope

May 2, 2026
A Guide to Sourcing Obsolete ICs for Vintage Projects

Beyond AliExpress: A Guide to Sourcing Obsolete ICs for Vintage Projects

April 21, 2026
Top Posts & Pages
  • IoT AC Energy Meter with PZEM-004T & ESP32 WebServer
    IoT AC Energy Meter with PZEM-004T & ESP32 WebServer
  • 12V DC to 220V AC Inverter Circuit & PCB
    12V DC to 220V AC Inverter Circuit & PCB
  • Silicon Controlled Rectifier (SCR): Construction, Working & Applications
    Silicon Controlled Rectifier (SCR): Construction, Working & Applications
  • Buck Converter: Basics, Working, Design & Application
    Buck Converter: Basics, Working, Design & Application
  • Designing of MPPT Solar Charge Controller using Arduino
    Designing of MPPT Solar Charge Controller using Arduino
  • How to use INA226 DC Current Sensor with Arduino
    How to use INA226 DC Current Sensor with Arduino
  • MAX30102 & Arduino: Heart Rate + Blood Oxygen Monitoring
    MAX30102 & Arduino: Heart Rate + Blood Oxygen Monitoring
  • DIY Smart Blind Stick using Op-Amp & IR Sensor
    DIY Smart Blind Stick using Op-Amp & IR Sensor
Categories
  • Arduino Projects (197)
  • Articles (61)
    • Learn Electronics (20)
    • Product Review (15)
    • Tech Articles (28)
  • Electronics Circuits (46)
    • 555 Timer Projects (21)
    • Op-Amp Circuits (7)
    • Power Electronics (13)
  • IoT Projects (207)
    • ESP32 MicroPython (7)
    • ESP32 Projects (84)
    • ESP32-CAM Projects (15)
    • ESP8266 Projects (76)
    • LoRa/LoRaWAN Projects (22)
  • Microcontrollers (38)
    • AMB82-Mini IoT AI Camera (4)
    • BLE Projects (18)
    • STM32 Projects (19)
  • Raspberry Pi (93)
    • Raspberry Pi Pico Projects (57)
    • Raspberry Pi Pico W Projects (12)
    • Raspberry Pi Projects (24)
Follow Us
  • Facebook
  • Twitter
  • Pinterest
  • Instagram
  • YouTube
About Us

“‘How to Electronics’ is a vibrant community for electronics enthusiasts and professionals. We deliver latest insights in areas such as Embedded Systems, Power Electronics, AI, IoT, and Robotics. Our goal is to stimulate innovation and provide practical solutions for students, organizations, and industries. Join us to transform learning into a joyful journey of discovery and innovation.

Copyright © How To Electronics. All rights reserved.
  • About Us
  • Disclaimer
  • Privacy Policy
  • Contact Us
  • Advertise With Us

Type above and press Enter to search. Press Esc to cancel.

Ad Blocker Enabled!
Ad Blocker Enabled!
Looks like you're using an ad blocker. Please allow ads on our site. We rely on advertising to help fund our site.