v0.6.6 — Optional QRS/pulse beep

Added a separate **QRS tone** checkbox (enabled by default). An 85 ms
single-note beep follows actual ECG or mechanical beat events. With a valid
SpO₂ reading, the delayed pleth pulse determines the timing and the oxygen
saturation determines the pitch in eleven steps from 740 to 87 Hz; otherwise
ECG QRS or ART pulses trigger a fixed 500 Hz tone. The two-tone alarm sounds
remain unchanged. Added regression tests for band boundaries, event selection
and single-tone WAV output.
This commit is contained in:
GABRIEL Sebastian 2026-11-12 22:36:24 +01:00
commit f98fc7412f
11 changed files with 1247 additions and 34 deletions

View file

@ -0,0 +1,749 @@
diff --git a/Cargo.toml b/Cargo.toml
index 8087e1c..f3abff3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "patient-monitor-simulation"
-version = "0.6.5"
+version = "0.6.6"
edition = "2021"
license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"
diff --git a/README.de.md b/README.de.md
index 3a42b91..605a34f 100644
--- a/README.de.md
+++ b/README.de.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.5
+# Patient Monitor Simulation (PaMSim) — v0.6.6
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -175,7 +175,7 @@ Mit **F11** wird der Vollbildmodus aktiviert bzw. umgeschaltet, mit **Esc** wird
Unter Wayland sollte das Fenster vor dem Wechsel in den Vollbildmodus auf den gewünschten Präsentationsbildschirm verschoben werden.
Der Vollbildmodus sperrt den Computer nicht gegen andere Eingaben.
-## Akustische Alarme (aktualisiert v0.6.5)
+## Akustische Alarme und QRS-Ton (aktualisiert v0.6.6)
Die akustische Alarmierung ist **standardmäßig eingeschaltet**. Im
Admin-Fenster lässt sie sich mit **Audible alarms** aktivieren bzw. stummschalten.
@@ -188,9 +188,10 @@ werden. Die optischen Alarme blinken bei stummgeschalteter Tonausgabe weiterhin.
- **Numerische und technische Alarme:** Grenzwertüberschreitungen sowie
**NO SENSOR** und **NO READING** lösen ebenfalls einen **Zweitonalarm** aus
(700 Hz gefolgt von 950 Hz), der ungefähr alle 2,5 Sekunden wiederholt wird.
-- Zwischen beiden Tönen liegt jeweils eine kurze Pause. Ein einzelner
- **QRS-Piepton** ist für eine spätere Version vorgesehen und wird derzeit
- noch nicht ausgegeben.
+- Zwischen beiden Tönen liegt jeweils eine kurze Pause. Zusätzlich gibt es
+ einen separaten, kurzen **QRS-/Pulston**, der im Admin-Fenster über
+ **QRS tone** unabhängig von **Audible alarms** ein- und ausgeschaltet wird
+ (standardmäßig eingeschaltet).
- Kritische Alarme haben Vorrang. Auch bei mehreren gleichzeitig aktiven
Alarmen wird nur eine Tonfolge ausgegeben. Bei behobenem Alarm oder
Stummschaltung verstummt die Ausgabe. Ausgeblendete Monitorbereiche
@@ -200,6 +201,42 @@ werden. Die optischen Alarme blinken bei stummgeschalteter Tonausgabe weiterhin.
selbst ist kein Alarm. Die Audioausgabe wird unabhängig von der Darstellung
der Kurven verarbeitet.
+### Synchroner QRS-/Pulston
+
+**QRS tone** ist unabhängig von **Audible alarms** schaltbar. Jeder kurze
+Piepton (85 ms) wird durch ein tatsächliches simuliertes elektrisches oder
+mechanisches Ereignis ausgelöst, nicht durch einen eigenen Taktgeber:
+
+- **SpO₂-Messwert vorhanden:** Auslösung beim verzögerten Pleth-Puls.
+ Die Frequenz richtet sich nach der angezeigten Sauerstoffsättigung.
+ Nicht übergeleitete mechanische Pulse erzeugen keinen Pleth-Piepton.
+- **Kein SpO₂-Messwert:** fester Ton mit **500 Hz** bei einem sichtbaren,
+ organisierten EKG-QRS; andernfalls bei einem dargestellten arteriellen
+ Pulsschlag. Bei gleichzeitig sichtbarem EKG und ART wird ein Herzschlag
+ nicht doppelt vertont.
+- **Kammerflimmern/Asystolie ohne wirksame Herzdruckmassage:** kein
+ Pulston. Bei Herzdruckmassage können ART-Pulse einen 500-Hz-Ton auslösen;
+ bei guter Kompressionsqualität und gültigem SpO₂-Messwert wird die
+ sättigungsabhängige Tonhöhe verwendet.
+
+| SpO₂ (%) | Frequenz (Hz) |
+| --- | ---: |
+| 97–100 | 740 |
+| 94–96 | 675 |
+| 90–93 | 609 |
+| 80–89 | 544 |
+| 70–79 | 479 |
+| 60–69 | 413 |
+| 50–59 | 348 |
+| 40–49 | 283 |
+| 30–39 | 218 |
+| 20–29 | 152 |
+| 0–19 | 87 |
+
+Die Frequenzen sind ausschließlich didaktische Simulationen, keine
+kalibrierten Töne eines klinischen Pulsoxymeters. QRS-/Pulston und
+Zweitonalarm können unabhängig voneinander erklingen.
+
Unter Fedora wird **`pw-play`** aus dem Paket `pipewire-utils` verwendet,
alternativ **`paplay`**. Es sind weder zusätzliche Rust-Bibliotheken noch
mitzuliefernde Audiodateien notwendig: Das Programm erzeugt seine WAV-Töne
@@ -632,3 +669,14 @@ Die Priorisierung und die Wiederholungsintervalle bleiben unverändert.
**Test tone** spielt den Standard-Zweitonalarm. Ein einzelner QRS-Piepton
ist für eine spätere Erweiterung reserviert. Optische Alarme und
Simulationsverhalten wurden nicht verändert.
+
+
+### v0.6.6 – Schaltbarer QRS-/Pulston
+
+Ein neuer Admin-Schalter **QRS tone** aktiviert oder deaktiviert den
+kurzen, beat-synchronen Einzelton unabhängig von den Zweitonalarmen.
+Bei vorhandenem SpO₂-Messwert richtet sich die Tonhöhe in elf Stufen
+zwischen 740 und 87 Hz nach der Sauerstoffsättigung; ohne SpO₂-Messwert
+erfolgt bei EKG-QRS oder arteriellem Puls ein 500-Hz-Ton. Die bisherigen
+Zweitonalarme bleiben unverändert. Zusätzliche Tests prüfen die
+Frequenzbereiche, Ereigniszuordnung und WAV-Ausgabe.
diff --git a/README.md b/README.md
index f413723..250b938 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.5
+# Patient Monitor Simulation (PaMSim) — v0.6.6
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@@ -166,7 +166,7 @@ The monitor can be resized and toggled fullscreen with **F11**; **Esc** exits
fullscreen. On Wayland, move the monitor to the presentation screen before
activating fullscreen. Fullscreen does not lock down the computer.
-## Audible alarms (updated v0.6.5)
+## Audible alarms and QRS tone (updated v0.6.6)
Sound is **enabled by default**. The Admin window has an **Audible alarms**
checkbox for muting and a **Test tone** button (works even while muted).
@@ -179,8 +179,8 @@ Visual alarms keep blinking normally when sound is off.
and **NO READING** produce a lower-pitched **two-tone** alert
(700 Hz followed by 950 Hz), repeated approximately every 2.5 seconds.
- Both alarm signals use two **different successive pitches**, separated by
- a brief silence. A distinct **single QRS beep is reserved for future work**;
- QRS-related audio is not yet implemented.
+ a brief silence. The single QRS/pulse beep is independent and configurable
+ using the new **QRS tone** checkbox in Admin (ON by default).
- Critical alarms have priority: only one tone pattern is played even if
multiple alarms are active. The sound stops when all alarms clear or when
the checkbox is unchecked. Alarms on hidden monitor channels are excluded.
@@ -188,6 +188,41 @@ Visual alarms keep blinking normally when sound is off.
trigger numerical limit alarms. The cuff measurement cycle by itself is not
an alarm. Audio playback is separate from waveform rendering and simulation.
+### Beat-synchronous QRS/pulse tone
+
+The **QRS tone** checkbox is independent of **Audible alarms**; turning off
+one does not mute the other. Each brief (85 ms), **single-frequency** beep
+follows an actual simulated beat event, not a separate rate timer:
+
+- **SpO₂ reading available:** beep on the delayed peripheral pleth pulse;
+ the pitch follows the *displayed* saturation (including during effective
+ good-quality chest compressions). Missed mechanical captures produce no
+ peripheral beep.
+- **SpO₂ reading unavailable:** a fixed **500 Hz** beep follows an organized
+ ECG QRS if ECG is displayed; otherwise it follows an arterial pulse if
+ ART is displayed. ECG and ART together do not cause duplicate beeps.
+- **VF/asystole without effective CPR:** no beat beep is generated. ART pulses
+ created by CPR can generate the fallback tone, while good CPR with a valid
+ SpO₂ reading uses the saturation-dependent tone.
+
+| SpO₂ (%) | Tone (Hz) |
+| --- | ---: |
+| 97–100 | 740 |
+| 94–96 | 675 |
+| 90–93 | 609 |
+| 80–89 | 544 |
+| 70–79 | 479 |
+| 60–69 | 413 |
+| 50–59 | 348 |
+| 40–49 | 283 |
+| 30–39 | 218 |
+| 20–29 | 152 |
+| 0–19 | 87 |
+
+Saturation tone pitches are deliberately simplified teaching tones, not
+calibrated clinical pulse-oximeter sounds. The QRS beep and two-tone alarm can
+sound independently; no alarm priority or visual alarm logic was changed.
+
On Fedora, sound is played through **`pw-play`** from `pipewire-utils`, with
**`paplay`** as a fallback. No additional Rust crates or sound files are needed:
the application creates its own short WAV tones at runtime. If neither player
@@ -647,3 +682,14 @@ successive pitches. Critical alarms retain their priority and faster repeat
interval; standard alarms retain their slower cadence. The Admin test button
plays the standard two-tone alert. A single QRS beep is reserved for a later
release and is not generated yet. No visual alarm or simulation logic changed.
+
+
+### v0.6.6 — Optional QRS/pulse beep
+
+Added a separate **QRS tone** checkbox (enabled by default). An 85 ms
+single-note beep follows actual ECG or mechanical beat events. With a valid
+SpO₂ reading, the delayed pleth pulse determines the timing and the oxygen
+saturation determines the pitch in eleven steps from 740 to 87 Hz; otherwise
+ECG QRS or ART pulses trigger a fixed 500 Hz tone. The two-tone alarm sounds
+remain unchanged. Added regression tests for band boundaries, event selection
+and single-tone WAV output.
diff --git a/src/alarm.rs b/src/alarm.rs
index 6e0b1af..89814d6 100644
--- a/src/alarm.rs
+++ b/src/alarm.rs
@@ -12,7 +12,7 @@ use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use crate::model::{AlarmLimits, AlarmState, Parameters, PulseConduction, Spo2Status};
-use crate::simulation::Simulator;
+use crate::simulation::{BeatEvent, BeatSource, Simulator};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum AlarmLevel {
@@ -84,6 +84,88 @@ pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel {
result
}
+/// Single-note QRS/pulse beep. The oximeter is the source when it has a
+/// reading; otherwise use an ECG QRS or an available arterial pulse.
+/// Mid is the fixed pitch used when no SpO2 reading is present.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum QrsTone { Mid, Saturation(usize) }
+
+const QRS_MID_HZ: f64 = 500.0;
+const QRS_SPO2_HZ: [f64; 11] = [
+ 740.0, 675.0, 609.0, 544.0, 479.0, 413.0,
+ 348.0, 283.0, 218.0, 152.0, 87.0,
+];
+
+/// Stepwise saturation-to-pitch mapping: 100–97, 96–94, 93–90,
+/// then 89–80, 79–70, ..., 19–10%. 10% or less always gives 87 Hz.
+fn spo2_tone_index(saturation: i32) -> usize {
+ match saturation.clamp(0, 100) {
+ 97..=100 => 0,
+ 94..=96 => 1,
+ 90..=93 => 2,
+ 80..=89 => 3,
+ 70..=79 => 4,
+ 60..=69 => 5,
+ 50..=59 => 6,
+ 40..=49 => 7,
+ 30..=39 => 8,
+ 20..=29 => 9,
+ _ => 10,
+ }
+}
+
+pub fn qrs_tone(p: &Parameters, sim: &Simulator, events: &[BeatEvent]) -> Option<QrsTone> {
+ if p.show_spo2 && sim.spo2_status(p) == Spo2Status::Available {
+ // Actual peripheral pulses, not an independent HR metronome. This
+ // respects mechanical capture ratios and good-quality CPR.
+ return events.iter().any(|event| event.source == BeatSource::Pleth
+ && sim.time() - event.time <= 0.25)
+ .then_some(QrsTone::Saturation(spo2_tone_index(p.spo2)));
+ }
+ // ECG takes precedence over the delayed arterial signal: never beep twice
+ // for the same QRS when both monitor channels are visible.
+ if p.show_ecg && p.ecg_rhythm.has_qrs() && p.heart_rate > 0 {
+ return events.iter().any(|event| event.source == BeatSource::Ecg
+ && sim.time() - event.time <= 0.25)
+ .then_some(QrsTone::Mid);
+ }
+ if p.show_art {
+ return events.iter().any(|event| event.source == BeatSource::Art
+ && sim.time() - event.time <= 0.25)
+ .then_some(QrsTone::Mid);
+ }
+ None
+}
+
+/// Original, brief PCM16 sine wave with smooth fades to avoid clicks.
+fn single_beep_wav(frequency: f64) -> Vec<u8> {
+ const SAMPLE_RATE: u32 = 44_100;
+ const DURATION: f64 = 0.085;
+ let samples = (DURATION * f64::from(SAMPLE_RATE)).round() as usize;
+ let size = (samples * 2) as u32;
+ let mut bytes = Vec::with_capacity(44 + size as usize);
+ bytes.extend_from_slice(b"RIFF");
+ bytes.extend_from_slice(&(size + 36).to_le_bytes());
+ bytes.extend_from_slice(b"WAVEfmt ");
+ bytes.extend_from_slice(&16_u32.to_le_bytes());
+ bytes.extend_from_slice(&1_u16.to_le_bytes());
+ bytes.extend_from_slice(&1_u16.to_le_bytes());
+ bytes.extend_from_slice(&SAMPLE_RATE.to_le_bytes());
+ bytes.extend_from_slice(&(SAMPLE_RATE * 2).to_le_bytes());
+ bytes.extend_from_slice(&2_u16.to_le_bytes());
+ bytes.extend_from_slice(&16_u16.to_le_bytes());
+ bytes.extend_from_slice(b"data");
+ bytes.extend_from_slice(&size.to_le_bytes());
+ for i in 0..samples {
+ let t = i as f64 / f64::from(SAMPLE_RATE);
+ let remaining = (samples - i) as f64 / f64::from(SAMPLE_RATE);
+ let envelope = (t / 0.010).min(1.0).min(remaining / 0.016).max(0.0);
+ let value = (std::f64::consts::TAU * frequency * t).sin() * envelope * 0.13;
+ bytes.extend_from_slice(&((value * f64::from(i16::MAX)).round() as i16).to_le_bytes());
+ }
+ bytes
+}
+
/// Both alarm priorities sound as two successive, different pitches.
/// A future QRS beep will be a separate, single-tone signal.
/// Zero-frequency segments are short silences between the notes.
@@ -175,6 +257,115 @@ impl SoundFiles {
}
}
+/// Prepared once on startup. Reuse the same playback utility as the alarms,
+/// but use an independent child so the two-tone alarm is never interrupted by
+/// single QRS/pulse beeps.
+struct QrsSoundFiles {
+ mid: PathBuf,
+ saturations: Vec<PathBuf>,
+}
+
+impl Drop for QrsSoundFiles {
+ fn drop(&mut self) {
+ let _ = fs::remove_file(&self.mid);
+ for file in &self.saturations { let _ = fs::remove_file(file); }
+ }
+}
+
+impl QrsSoundFiles {
+ fn create_in(directory: &Path) -> io::Result<Self> {
+ let nonce = SystemTime::now().duration_since(UNIX_EPOCH)
+ .unwrap_or_default().as_nanos();
+ let prefix = format!("pamsim-qrs-{}-{nonce}", std::process::id());
+ let mid = directory.join(format!("{prefix}-mid.wav"));
+ write_new(&mid, &single_beep_wav(QRS_MID_HZ))?;
+ let mut files = Self { mid, saturations: Vec::new() };
+ for (i, &frequency) in QRS_SPO2_HZ.iter().enumerate() {
+ let path = directory.join(format!("{prefix}-spo2-{i}.wav"));
+ write_new(&path, &single_beep_wav(frequency))?;
+ files.saturations.push(path);
+ }
+ Ok(files)
+ }
+
+ fn create() -> io::Result<Self> {
+ if let Some(runtime) = env::var_os("XDG_RUNTIME_DIR") {
+ if let Ok(files) = Self::create_in(Path::new(&runtime)) {
+ return Ok(files);
+ }
+ }
+ Self::create_in(&env::temp_dir())
+ }
+
+ fn path(&self, tone: QrsTone) -> &Path {
+ match tone {
+ QrsTone::Mid => &self.mid,
+ QrsTone::Saturation(index) => &self.saturations[index.min(self.saturations.len() - 1)],
+ }
+ }
+}
+
+pub struct QrsAudio {
+ player: Option<&'static str>,
+ files: Option<QrsSoundFiles>,
+ child: Option<Child>,
+ error_reported: bool,
+}
+
+impl QrsAudio {
+ pub fn new() -> Self {
+ let player = ["pw-play", "paplay"].into_iter().find(|name| command_on_path(name));
+ let files = if player.is_some() {
+ match QrsSoundFiles::create() {
+ Ok(files) => Some(files),
+ Err(error) => {
+ eprintln!("PaMSim: cannot prepare QRS beeps: {error}");
+ None
+ }
+ }
+ } else { None };
+ Self { player, files, child: None, error_reported: false }
+ }
+
+ fn stop_child(&mut self) {
+ if let Some(mut child) = self.child.take() {
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ }
+
+ /// The audio timer delivers at most one beat in a 100-ms tick. Do not
+ /// replay events after disabling sound; do not restart an active beep.
+ pub fn update(&mut self, tone: Option<QrsTone>, enabled: bool) {
+ if !enabled {
+ self.stop_child();
+ return;
+ }
+ if let Some(child) = self.child.as_mut() {
+ match child.try_wait() {
+ Ok(Some(_)) | Err(_) => self.child = None,
+ Ok(None) => return,
+ }
+ }
+ let (Some(tone), Some(player), Some(files)) = (tone, self.player, self.files.as_ref())
+ else { return; };
+ match Command::new(player).arg(files.path(tone))
+ .stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()
+ {
+ Ok(child) => self.child = Some(child),
+ Err(error) if !self.error_reported => {
+ eprintln!("PaMSim: QRS sound playback failed: {error}");
+ self.error_reported = true;
+ }
+ Err(_) => {}
+ }
+ }
+}
+
+impl Drop for QrsAudio {
+ fn drop(&mut self) { self.stop_child(); }
+}
+
fn command_on_path(name: &str) -> bool {
env::var_os("PATH").is_some_and(|paths| {
env::split_paths(&paths).any(|dir| {
@@ -317,6 +508,59 @@ mod tests {
use super::*;
use crate::model::{AlarmSettings, EcgRhythm};
+ #[test]
+ fn saturation_pitches_follow_exact_bands_and_decrease_to_87_hz() {
+ assert_eq!(QRS_SPO2_HZ.first(), Some(&740.0));
+ assert_eq!(QRS_SPO2_HZ.last(), Some(&87.0));
+ for (saturation, expected) in [
+ (100, 0), (97, 0), (96, 1), (94, 1), (93, 2), (90, 2),
+ (89, 3), (80, 3), (79, 4), (70, 4), (69, 5), (60, 5),
+ (59, 6), (50, 6), (49, 7), (40, 7), (39, 8), (30, 8),
+ (29, 9), (20, 9), (19, 10), (10, 10), (0, 10),
+ ] {
+ assert_eq!(spo2_tone_index(saturation), expected, "SpO2 {saturation}%");
+ }
+ assert!(QRS_SPO2_HZ.windows(2).all(|hz| hz[0] > hz[1]));
+ assert_eq!(QRS_MID_HZ, 500.0);
+ }
+
+ #[test]
+ fn qrs_audio_uses_pleth_when_available_and_electrical_fallback_without_reading() {
+ let mut p = Parameters::default();
+ let mut sim = Simulator::new(&p);
+ let mut events = Vec::new();
+ for _ in 0..40 {
+ sim.advance(0.05, &p);
+ let current = sim.take_audio_events();
+ if current.iter().any(|e| e.source == BeatSource::Pleth
+ && sim.time() - e.time <= 0.25) {
+ events = current;
+ break;
+ }
+ }
+ assert!(events.iter().any(|e| e.source == BeatSource::Pleth));
+ assert_eq!(qrs_tone(&p, &sim, &events), Some(QrsTone::Saturation(0)));
+ p.spo2_sensor_attached = false;
+ let fallback = [BeatEvent { source: BeatSource::Ecg, time: sim.time() },
+ BeatEvent { source: BeatSource::Art, time: sim.time() }];
+ assert_eq!(qrs_tone(&p, &sim, &fallback), Some(QrsTone::Mid));
+ p.show_ecg = false;
+ assert_eq!(qrs_tone(&p, &sim, &fallback), Some(QrsTone::Mid));
+ p.show_art = false;
+ assert_eq!(qrs_tone(&p, &sim, &fallback), None);
+ }
+
+ #[test]
+ fn single_beep_is_valid_wav_independent_of_two_tone_alarm() {
+ for hz in QRS_SPO2_HZ.iter().copied().chain([QRS_MID_HZ]) {
+ let bytes = single_beep_wav(hz);
+ assert_eq!(&bytes[..4], b"RIFF");
+ assert_eq!(&bytes[8..12], b"WAVE");
+ assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize + 8, bytes.len());
+ }
+ assert_ne!(single_beep_wav(740.0), single_beep_wav(87.0));
+ }
+
#[test]
fn valid_wav_files_and_distinct_tone_patterns() {
for critical in [false, true] {
diff --git a/src/model.rs b/src/model.rs
index b01a854..dcd82bb 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -267,6 +267,7 @@ pub struct Parameters {
pub patient_name: String, // displayed in the monitor header, blank = generic title
pub alarms: AlarmSettings,
pub audible_alarms: bool, // mute only the sound, never the visual alarms
+ pub qrs_tone_enabled: bool, // beat-synchronous single beep; separate from two-tone alarms
pub chest_compressions_active: bool,
pub chest_compression_quality: ChestCompressionQuality,
pub ecg_rhythm: EcgRhythm,
@@ -346,6 +347,7 @@ impl Default for Parameters {
patient_name: String::new(),
alarms: AlarmSettings::default(),
audible_alarms: true,
+ qrs_tone_enabled: true,
chest_compressions_active: false,
chest_compression_quality: ChestCompressionQuality::Adequate,
ecg_rhythm: EcgRhythm::Sinus,
diff --git a/src/simulation.rs b/src/simulation.rs
index 61ca53e..ec88a5a 100644
--- a/src/simulation.rs
+++ b/src/simulation.rs
@@ -29,6 +29,18 @@ fn ppv_multiplier(ppv_percent: i32, respiratory_phase: f64) -> f64 {
* (std::f64::consts::TAU * respiratory_phase).sin()
}
+/// One distinct electrical or mechanical beat event for the optional beep.
+/// Electrical QRS, arterial and peripheral pulses are generated at their
+/// respective physiological simulation times, not at the audio-timer rate.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum BeatSource { Ecg, Art, Pleth }
+
+#[derive(Clone, Copy, Debug)]
+pub struct BeatEvent {
+ pub time: f64,
+ pub source: BeatSource,
+}
+
#[derive(Clone, Copy, Debug)]
pub struct Sample {
pub time: f64,
@@ -121,12 +133,12 @@ impl ChestCompressions {
};
}
- fn update(&mut self, enabled: bool, quality: ChestCompressionQuality) {
+ fn update(&mut self, enabled: bool, quality: ChestCompressionQuality) -> bool {
if !enabled {
self.active = false;
self.phase = 0.0;
self.peak_pressure = 0.0;
- return;
+ return false;
}
if !self.active {
self.active = true;
@@ -143,7 +155,9 @@ impl ChestCompressions {
self.phase = self.phase.fract();
self.rate_bpm = 90.0 + self.random_unit() * 20.0;
self.choose_peak();
+ return true;
}
+ false
}
fn pressure_wave(&self) -> f64 {
@@ -184,6 +198,7 @@ pub struct Simulator {
ecg_beat_number: u64,
conducted_qrs: VecDeque<ConductedBeat>, // captured QRS with respiratory beat amplitude
rate_qrs: VecDeque<f64>, // captured beats for measured PR; reset after rate changes
+ audio_events: VecDeque<BeatEvent>, // consumed by the 100-ms UI audio timer
filtered_pleth: f64,
previous_rhythm: EcgRhythm,
previous_conduction: PulseConduction,
@@ -205,6 +220,7 @@ impl Simulator {
ecg_beat_number: 0,
conducted_qrs: VecDeque::new(),
rate_qrs: VecDeque::new(),
+ audio_events: VecDeque::new(),
filtered_pleth: 0.0,
previous_rhythm: params.ecg_rhythm,
previous_conduction: params.pulse_conduction,
@@ -219,6 +235,8 @@ impl Simulator {
for _ in 0..(8.0 / SAMPLE_STEP) as usize {
sim.step(params);
}
+ // Initial history is visual-only; never replay warmup beats as sound.
+ sim.audio_events.clear();
sim
}
@@ -336,6 +354,18 @@ impl Simulator {
&self.samples
}
+ /// Drain beat events since the previous sound callback. Kept bounded so
+ /// a suspended window cannot replay a long backlog of old beats.
+ pub fn take_audio_events(&mut self) -> Vec<BeatEvent> {
+ self.audio_events.drain(..).collect()
+ }
+
+ fn emit_beat(&mut self, source: BeatSource, time: f64) {
+ if time < 0.0 { return; } // no audio events from history warmup
+ if self.audio_events.len() >= 32 { self.audio_events.pop_front(); }
+ self.audio_events.push_back(BeatEvent { source, time });
+ }
+
/// Average of recent *mechanically captured* beat intervals, not an independent setting.
pub fn pulse_rate(&self) -> Option<i32> {
if self.rate_qrs.len() < 2 {
@@ -355,8 +385,18 @@ impl Simulator {
fn step(&mut self, params: &Parameters) {
self.time += SAMPLE_STEP;
- self.compressions.update(params.chest_compressions_active,
+ let compression_event = self.compressions.update(params.chest_compressions_active,
params.chest_compression_quality);
+ if compression_event {
+ // Good CPR generates a pleth beat. Any effective CPR generates
+ // an arterial beat, even without underlying organized ECG.
+ if self.compressions.peak_pressure > 0.0 {
+ self.emit_beat(BeatSource::Art, self.time);
+ }
+ if params.chest_compression_quality == ChestCompressionQuality::Good {
+ self.emit_beat(BeatSource::Pleth, self.time);
+ }
+ }
self.poor_signal_outages.update(self.time,
!params.chest_compressions_active && params.spo2_quality == Spo2Quality::Poor
&& params.spo2_sensor_attached);
@@ -413,6 +453,7 @@ impl Simulator {
// Interpolate within the 4 ms sample so mechanical onsets stay aligned.
let qrs_time = self.time - SAMPLE_STEP * (next_phase - QRS_PHASE) / increment;
self.ecg_beat_number += 1;
+ self.emit_beat(BeatSource::Ecg, qrs_time);
if params.ecg_rhythm.can_generate_pulse()
&& params.pulse_conduction.conducts(self.ecg_beat_number) {
let pulse_pressure_scale = if params.respiratory_rate > 0 {
@@ -429,6 +470,29 @@ impl Simulator {
self.ecg_phase = 0.0;
}
+ // Schedule single beeps at the delayed mechanical onsets. During CPR,
+ // the compression clock replaces the intrinsic ART/pleth sound source
+ // except for a perfusing native arterial pulse under ineffective CPR.
+ let mut mechanical_events = Vec::new();
+ for beat in &self.conducted_qrs {
+ let art_time = beat.qrs_time + ART_DELAY;
+ let pleth_time = beat.qrs_time + PLETH_DELAY;
+ if art_time > self.time - SAMPLE_STEP && art_time <= self.time
+ && (!params.chest_compressions_active
+ || params.chest_compression_quality == ChestCompressionQuality::Bad)
+ {
+ mechanical_events.push((BeatSource::Art, art_time));
+ }
+ if pleth_time > self.time - SAMPLE_STEP && pleth_time <= self.time
+ && !params.chest_compressions_active
+ {
+ mechanical_events.push((BeatSource::Pleth, pleth_time));
+ }
+ }
+ for (source, time) in mechanical_events {
+ self.emit_beat(source, time);
+ }
+
// Preserve up to 30s of delivered events for stable derived PR calculations.
while self.conducted_qrs.front().is_some_and(|beat| beat.qrs_time < self.time - 30.0) {
self.conducted_qrs.pop_front();
@@ -709,6 +773,60 @@ mod tests {
sim
}
+ #[test]
+ fn audio_events_follow_actual_qrs_and_delayed_mechanical_pulses() {
+ let p = Parameters::default();
+ let mut sim = Simulator::new(&p);
+ for _ in 0..30 { sim.advance(0.1, &p); }
+ let events = sim.take_audio_events();
+ let qrs = events.iter().find(|e| e.source == BeatSource::Ecg).unwrap().time;
+ assert!(events.iter().any(|e| e.source == BeatSource::Art
+ && ((e.time - qrs) - ART_DELAY).abs() <= SAMPLE_STEP));
+ assert!(events.iter().any(|e| e.source == BeatSource::Pleth
+ && ((e.time - qrs) - PLETH_DELAY).abs() <= SAMPLE_STEP));
+ assert!(sim.take_audio_events().is_empty(), "events must be consumed once");
+ }
+
+ #[test]
+ fn two_to_one_capture_has_half_as_many_peripheral_audio_beats() {
+ let p = Parameters { pulse_conduction: PulseConduction::TwoToOne,
+ ..Parameters::default() };
+ let mut sim = Simulator::new(&p);
+ let mut qrs = 0;
+ let mut pleth = 0;
+ for _ in 0..100 {
+ sim.advance(0.1, &p);
+ for event in sim.take_audio_events() {
+ match event.source {
+ BeatSource::Ecg => qrs += 1,
+ BeatSource::Pleth => pleth += 1,
+ BeatSource::Art => {}
+ }
+ }
+ }
+ assert!(qrs >= 10);
+ assert!((2 * pleth as i32 - qrs as i32).abs() <= 2,
+ "2:1 capture: {qrs} QRS events, {pleth} peripheral events");
+ }
+
+ #[test]
+ fn vf_generates_no_beats_without_cpr_but_compressions_generate_art_events() {
+ let mut p = Parameters { ecg_rhythm: EcgRhythm::VentricularFibrillation,
+ ..Parameters::default() };
+ let mut sim = Simulator::new(&p);
+ for _ in 0..20 { sim.advance(0.1, &p); }
+ assert!(sim.take_audio_events().is_empty());
+ p.chest_compressions_active = true;
+ p.chest_compression_quality = ChestCompressionQuality::Adequate;
+ for _ in 0..20 { sim.advance(0.1, &p); }
+ let events = sim.take_audio_events();
+ assert!(events.iter().any(|e| e.source == BeatSource::Art));
+ assert!(!events.iter().any(|e| e.source == BeatSource::Pleth));
+ p.chest_compression_quality = ChestCompressionQuality::Good;
+ for _ in 0..20 { sim.advance(0.1, &p); }
+ assert!(sim.take_audio_events().iter().any(|e| e.source == BeatSource::Pleth));
+ }
+
#[test]
fn compression_rate_varies_only_between_90_and_110_bpm() {
let mut cpr = ChestCompressions::new();
diff --git a/src/ui.rs b/src/ui.rs
index 98e35c2..0c02b36 100644
--- a/src/ui.rs
+++ b/src/ui.rs
@@ -8,7 +8,7 @@ use gtk::glib;
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Orientation};
-use crate::alarm::{self, AlarmAudio};
+use crate::alarm::{self, AlarmAudio, QrsAudio};
use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape,
ChestCompressionQuality, EcgLead, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render;
@@ -33,6 +33,7 @@ pub fn create_windows(app: &Application) {
let parameters = Rc::new(RefCell::new(Parameters::default()));
let simulator = Rc::new(RefCell::new(Simulator::new(&parameters.borrow())));
let audio = Rc::new(RefCell::new(AlarmAudio::new()));
+ let qrs_audio = Rc::new(RefCell::new(QrsAudio::new()));
install_ecg_menu_style(); // neutral style shared by all parameter panels
let admin_changed: AdminChanged = Rc::new(RefCell::new(None));
let monitor = create_monitor(app, parameters.clone(), simulator.clone(),
@@ -44,8 +45,13 @@ pub fn create_windows(app: &Application) {
// on sound playback. Audio also continues if the monitor is not mapped.
glib::timeout_add_local(Duration::from_millis(100), move || {
let config = parameters.borrow();
- let current = alarm::level(&config, &simulator.borrow());
+ let mut sim = simulator.borrow_mut();
+ let events = sim.take_audio_events();
+ let current = alarm::level(&config, &sim);
+ let beat_tone = alarm::qrs_tone(&config, &sim, &events);
+ drop(sim);
audio.borrow_mut().update(current, config.audible_alarms);
+ qrs_audio.borrow_mut().update(beat_tone, config.qrs_tone_enabled);
glib::ControlFlow::Continue
});
@@ -210,6 +216,13 @@ fn create_admin(app: &Application, params: SharedParams,
move |button| params.borrow_mut().audible_alarms = button.is_active()
});
sound_row.append(&audible);
+ let qrs_enabled = gtk::CheckButton::with_label("QRS tone");
+ qrs_enabled.set_active(params.borrow().qrs_tone_enabled);
+ qrs_enabled.connect_toggled({
+ let params = params.clone();
+ move |button| params.borrow_mut().qrs_tone_enabled = button.is_active()
+ });
+ sound_row.append(&qrs_enabled);
let test_sound = gtk::Button::with_label("Test tone");
test_sound.connect_clicked({
let audio = audio.clone();

View file

@ -438,7 +438,7 @@ dependencies = [
[[package]] [[package]]
name = "patient-monitor-simulation" name = "patient-monitor-simulation"
version = "0.6.5" version = "0.6.6"
dependencies = [ dependencies = [
"gtk4", "gtk4",
] ]

View file

@ -1,6 +1,6 @@
[package] [package]
name = "patient-monitor-simulation" name = "patient-monitor-simulation"
version = "0.6.5" version = "0.6.6"
edition = "2021" edition = "2021"
license = "MIT" license = "MIT"
description = "Synthetic patient-monitor simulation for teaching (not for clinical use)" description = "Synthetic patient-monitor simulation for teaching (not for clinical use)"

View file

@ -172,7 +172,7 @@ Mit **F11** wird der Vollbildmodus aktiviert bzw. umgeschaltet, mit **Esc** wird
Unter Wayland sollte das Fenster vor dem Wechsel in den Vollbildmodus auf den gewünschten Präsentationsbildschirm verschoben werden. Unter Wayland sollte das Fenster vor dem Wechsel in den Vollbildmodus auf den gewünschten Präsentationsbildschirm verschoben werden.
Der Vollbildmodus sperrt den Computer nicht gegen andere Eingaben. Der Vollbildmodus sperrt den Computer nicht gegen andere Eingaben.
## Akustische Alarme (aktualisiert v0.6.5) ## Akustische Alarme und QRS-Ton (aktualisiert v0.6.6)
Die akustische Alarmierung ist **standardmäßig eingeschaltet**. Im Die akustische Alarmierung ist **standardmäßig eingeschaltet**. Im
Admin-Fenster lässt sie sich mit **Audible alarms** aktivieren bzw. stummschalten. Admin-Fenster lässt sie sich mit **Audible alarms** aktivieren bzw. stummschalten.
@ -185,9 +185,10 @@ werden. Die optischen Alarme blinken bei stummgeschalteter Tonausgabe weiterhin.
- **Numerische und technische Alarme:** Grenzwertüberschreitungen sowie - **Numerische und technische Alarme:** Grenzwertüberschreitungen sowie
**NO SENSOR** und **NO READING** lösen ebenfalls einen **Zweitonalarm** aus **NO SENSOR** und **NO READING** lösen ebenfalls einen **Zweitonalarm** aus
(700 Hz gefolgt von 950 Hz), der ungefähr alle 2,5 Sekunden wiederholt wird. (700 Hz gefolgt von 950 Hz), der ungefähr alle 2,5 Sekunden wiederholt wird.
- Zwischen beiden Tönen liegt jeweils eine kurze Pause. Ein einzelner - Zwischen beiden Tönen liegt jeweils eine kurze Pause. Zusätzlich gibt es
**QRS-Piepton** ist für eine spätere Version vorgesehen und wird derzeit einen separaten, kurzen **QRS-/Pulston**, der im Admin-Fenster über
noch nicht ausgegeben. **QRS tone** unabhängig von **Audible alarms** ein- und ausgeschaltet wird
(standardmäßig eingeschaltet).
- Kritische Alarme haben Vorrang. Auch bei mehreren gleichzeitig aktiven - Kritische Alarme haben Vorrang. Auch bei mehreren gleichzeitig aktiven
Alarmen wird nur eine Tonfolge ausgegeben. Bei behobenem Alarm oder Alarmen wird nur eine Tonfolge ausgegeben. Bei behobenem Alarm oder
Stummschaltung verstummt die Ausgabe. Ausgeblendete Monitorbereiche Stummschaltung verstummt die Ausgabe. Ausgeblendete Monitorbereiche
@ -197,6 +198,42 @@ werden. Die optischen Alarme blinken bei stummgeschalteter Tonausgabe weiterhin.
selbst ist kein Alarm. Die Audioausgabe wird unabhängig von der Darstellung selbst ist kein Alarm. Die Audioausgabe wird unabhängig von der Darstellung
der Kurven verarbeitet. der Kurven verarbeitet.
### Synchroner QRS-/Pulston
**QRS tone** ist unabhängig von **Audible alarms** schaltbar. Jeder kurze
Piepton (85 ms) wird durch ein tatsächliches simuliertes elektrisches oder
mechanisches Ereignis ausgelöst, nicht durch einen eigenen Taktgeber:
- **SpO₂-Messwert vorhanden:** Auslösung beim verzögerten Pleth-Puls.
Die Frequenz richtet sich nach der angezeigten Sauerstoffsättigung.
Nicht übergeleitete mechanische Pulse erzeugen keinen Pleth-Piepton.
- **Kein SpO₂-Messwert:** fester Ton mit **500 Hz** bei einem sichtbaren,
organisierten EKG-QRS; andernfalls bei einem dargestellten arteriellen
Pulsschlag. Bei gleichzeitig sichtbarem EKG und ART wird ein Herzschlag
nicht doppelt vertont.
- **Kammerflimmern/Asystolie ohne wirksame Herzdruckmassage:** kein
Pulston. Bei Herzdruckmassage können ART-Pulse einen 500-Hz-Ton auslösen;
bei guter Kompressionsqualität und gültigem SpO₂-Messwert wird die
sättigungsabhängige Tonhöhe verwendet.
| SpO₂ (%) | Frequenz (Hz) |
| --- | ---: |
| 97–100 | 740 |
| 94–96 | 675 |
| 90–93 | 609 |
| 80–89 | 544 |
| 70–79 | 479 |
| 60–69 | 413 |
| 50–59 | 348 |
| 40–49 | 283 |
| 30–39 | 218 |
| 20–29 | 152 |
| 0–19 | 87 |
Die Frequenzen sind ausschließlich didaktische Simulationen, keine
kalibrierten Töne eines klinischen Pulsoxymeters. QRS-/Pulston und
Zweitonalarm können unabhängig voneinander erklingen.
Unter Fedora wird **`pw-play`** aus dem Paket `pipewire-utils` verwendet, Unter Fedora wird **`pw-play`** aus dem Paket `pipewire-utils` verwendet,
alternativ **`paplay`**. Es sind weder zusätzliche Rust-Bibliotheken noch alternativ **`paplay`**. Es sind weder zusätzliche Rust-Bibliotheken noch
mitzuliefernde Audiodateien notwendig: Das Programm erzeugt seine WAV-Töne mitzuliefernde Audiodateien notwendig: Das Programm erzeugt seine WAV-Töne

View file

@ -172,7 +172,7 @@ Mit **F11** wird der Vollbildmodus aktiviert bzw. umgeschaltet, mit **Esc** wird
Unter Wayland sollte das Fenster vor dem Wechsel in den Vollbildmodus auf den gewünschten Präsentationsbildschirm verschoben werden. Unter Wayland sollte das Fenster vor dem Wechsel in den Vollbildmodus auf den gewünschten Präsentationsbildschirm verschoben werden.
Der Vollbildmodus sperrt den Computer nicht gegen andere Eingaben. Der Vollbildmodus sperrt den Computer nicht gegen andere Eingaben.
## Akustische Alarme (v0.5.3) ## Akustische Alarme (aktualisiert v0.6.5)
Die akustische Alarmierung ist **standardmäßig eingeschaltet**. Im Die akustische Alarmierung ist **standardmäßig eingeschaltet**. Im
Admin-Fenster lässt sie sich mit **Audible alarms** aktivieren bzw. stummschalten. Admin-Fenster lässt sie sich mit **Audible alarms** aktivieren bzw. stummschalten.
@ -180,11 +180,14 @@ Mit **Test tone** kann die Tonausgabe unabhängig von der Stummschaltung geprüf
werden. Die optischen Alarme blinken bei stummgeschalteter Tonausgabe weiterhin. werden. Die optischen Alarme blinken bei stummgeschalteter Tonausgabe weiterhin.
- **Kritische Rhythmusalarme:** VT, PVT, Kammerflimmern und Asystolie lösen - **Kritische Rhythmusalarme:** VT, PVT, Kammerflimmern und Asystolie lösen
einen Doppelton aus (zweimal kurz 880 Hz), der ungefähr alle 1,5 Sekunden einen **Zweiklang aus aufeinanderfolgenden, unterschiedlichen Tönen** aus
wiederholt wird. (880 Hz gefolgt von 1160 Hz), der ungefähr alle 1,5 Sekunden wiederholt wird.
- **Numerische und technische Alarme:** Grenzwertüberschreitungen sowie - **Numerische und technische Alarme:** Grenzwertüberschreitungen sowie
**NO SENSOR** und **NO READING** lösen einen kurzen Ton mit 700 Hz aus, **NO SENSOR** und **NO READING** lösen ebenfalls einen **Zweitonalarm** aus
der ungefähr alle 2,5 Sekunden wiederholt wird. (700 Hz gefolgt von 950 Hz), der ungefähr alle 2,5 Sekunden wiederholt wird.
- Zwischen beiden Tönen liegt jeweils eine kurze Pause. Ein einzelner
**QRS-Piepton** ist für eine spätere Version vorgesehen und wird derzeit
noch nicht ausgegeben.
- Kritische Alarme haben Vorrang. Auch bei mehreren gleichzeitig aktiven - Kritische Alarme haben Vorrang. Auch bei mehreren gleichzeitig aktiven
Alarmen wird nur eine Tonfolge ausgegeben. Bei behobenem Alarm oder Alarmen wird nur eine Tonfolge ausgegeben. Bei behobenem Alarm oder
Stummschaltung verstummt die Ausgabe. Ausgeblendete Monitorbereiche Stummschaltung verstummt die Ausgabe. Ausgeblendete Monitorbereiche

View file

@ -1,22 +1,23 @@
--- README.de.md --- README.de.md
+++ README.de.md +++ README.de.md
@@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
-# Patient Monitor Simulation (PaMSim) — v0.6.4 -# Patient Monitor Simulation (PaMSim) — v0.6.5
+# Patient Monitor Simulation (PaMSim) — v0.6.5 +# Patient Monitor Simulation (PaMSim) — v0.6.6
Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux. Ein mit Rust und GTK4 entwickelter Patient*innenmonitor-Simulator mit zwei Fenstern für die Lehre unter Fedora Linux.
@@ -622,3 +625,13 @@ mit **Apply** gespeichert; **Measure now** startet unmittelbar einen Messzyklus, @@ -669,3 +706,14 @@ Die Priorisierung und die Wiederholungsintervalle bleiben unverändert.
auch wenn die Automatik ausgeschaltet ist. Die Admin-Oberfläche wird **Test tone** spielt den Standard-Zweitonalarm. Ein einzelner QRS-Piepton
synchronisiert. Die anderen Parametermenüs bleiben auf Alarmgrenzen beschränkt. ist für eine spätere Erweiterung reserviert. Optische Alarme und
Manschettenzuordnung und simulierter Messausfall verbleiben im Admin-Fenster. Simulationsverhalten wurden nicht verändert.
+ +
+ +
+### v0.6.5 – Zweitonige akustische Alarme +### v0.6.6 – Schaltbarer QRS-/Pulston
+ +
+Sowohl Standard- und technische Alarme als auch kritische Rhythmusalarme +Ein neuer Admin-Schalter **QRS tone** aktiviert oder deaktiviert den
+bestehen nun aus zwei aufeinanderfolgenden Tönen unterschiedlicher Frequenz. +kurzen, beat-synchronen Einzelton unabhängig von den Zweitonalarmen.
+Die Priorisierung und die Wiederholungsintervalle bleiben unverändert. +Bei vorhandenem SpO₂-Messwert richtet sich die Tonhöhe in elf Stufen
+**Test tone** spielt den Standard-Zweitonalarm. Ein einzelner QRS-Piepton +zwischen 740 und 87 Hz nach der Sauerstoffsättigung; ohne SpO₂-Messwert
+ist für eine spätere Erweiterung reserviert. Optische Alarme und +erfolgt bei EKG-QRS oder arteriellem Puls ein 500-Hz-Ton. Die bisherigen
+Simulationsverhalten wurden nicht verändert. +Zweitonalarme bleiben unverändert. Zusätzliche Tests prüfen die
+Frequenzbereiche, Ereigniszuordnung und WAV-Ausgabe.

View file

@ -1,4 +1,4 @@
# Patient Monitor Simulation (PaMSim) — v0.6.5 # Patient Monitor Simulation (PaMSim) — v0.6.6
A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux. A Rust/GTK4 patient-monitor simulator with two main windows for teaching on Fedora Linux.
@ -166,7 +166,7 @@ The monitor can be resized and toggled fullscreen with **F11**; **Esc** exits
fullscreen. On Wayland, move the monitor to the presentation screen before fullscreen. On Wayland, move the monitor to the presentation screen before
activating fullscreen. Fullscreen does not lock down the computer. activating fullscreen. Fullscreen does not lock down the computer.
## Audible alarms (updated v0.6.5) ## Audible alarms and QRS tone (updated v0.6.6)
Sound is **enabled by default**. The Admin window has an **Audible alarms** Sound is **enabled by default**. The Admin window has an **Audible alarms**
checkbox for muting and a **Test tone** button (works even while muted). checkbox for muting and a **Test tone** button (works even while muted).
@ -179,8 +179,8 @@ Visual alarms keep blinking normally when sound is off.
and **NO READING** produce a lower-pitched **two-tone** alert and **NO READING** produce a lower-pitched **two-tone** alert
(700 Hz followed by 950 Hz), repeated approximately every 2.5 seconds. (700 Hz followed by 950 Hz), repeated approximately every 2.5 seconds.
- Both alarm signals use two **different successive pitches**, separated by - Both alarm signals use two **different successive pitches**, separated by
a brief silence. A distinct **single QRS beep is reserved for future work**; a brief silence. The single QRS/pulse beep is independent and configurable
QRS-related audio is not yet implemented. using the new **QRS tone** checkbox in Admin (ON by default).
- Critical alarms have priority: only one tone pattern is played even if - Critical alarms have priority: only one tone pattern is played even if
multiple alarms are active. The sound stops when all alarms clear or when multiple alarms are active. The sound stops when all alarms clear or when
the checkbox is unchecked. Alarms on hidden monitor channels are excluded. the checkbox is unchecked. Alarms on hidden monitor channels are excluded.
@ -188,6 +188,41 @@ Visual alarms keep blinking normally when sound is off.
trigger numerical limit alarms. The cuff measurement cycle by itself is not trigger numerical limit alarms. The cuff measurement cycle by itself is not
an alarm. Audio playback is separate from waveform rendering and simulation. an alarm. Audio playback is separate from waveform rendering and simulation.
### Beat-synchronous QRS/pulse tone
The **QRS tone** checkbox is independent of **Audible alarms**; turning off
one does not mute the other. Each brief (85 ms), **single-frequency** beep
follows an actual simulated beat event, not a separate rate timer:
- **SpO₂ reading available:** beep on the delayed peripheral pleth pulse;
the pitch follows the *displayed* saturation (including during effective
good-quality chest compressions). Missed mechanical captures produce no
peripheral beep.
- **SpO₂ reading unavailable:** a fixed **500 Hz** beep follows an organized
ECG QRS if ECG is displayed; otherwise it follows an arterial pulse if
ART is displayed. ECG and ART together do not cause duplicate beeps.
- **VF/asystole without effective CPR:** no beat beep is generated. ART pulses
created by CPR can generate the fallback tone, while good CPR with a valid
SpO₂ reading uses the saturation-dependent tone.
| SpO₂ (%) | Tone (Hz) |
| --- | ---: |
| 97–100 | 740 |
| 94–96 | 675 |
| 90–93 | 609 |
| 80–89 | 544 |
| 70–79 | 479 |
| 60–69 | 413 |
| 50–59 | 348 |
| 40–49 | 283 |
| 30–39 | 218 |
| 20–29 | 152 |
| 0–19 | 87 |
Saturation tone pitches are deliberately simplified teaching tones, not
calibrated clinical pulse-oximeter sounds. The QRS beep and two-tone alarm can
sound independently; no alarm priority or visual alarm logic was changed.
On Fedora, sound is played through **`pw-play`** from `pipewire-utils`, with On Fedora, sound is played through **`pw-play`** from `pipewire-utils`, with
**`paplay`** as a fallback. No additional Rust crates or sound files are needed: **`paplay`** as a fallback. No additional Rust crates or sound files are needed:
the application creates its own short WAV tones at runtime. If neither player the application creates its own short WAV tones at runtime. If neither player
@ -647,3 +682,14 @@ successive pitches. Critical alarms retain their priority and faster repeat
interval; standard alarms retain their slower cadence. The Admin test button interval; standard alarms retain their slower cadence. The Admin test button
plays the standard two-tone alert. A single QRS beep is reserved for a later plays the standard two-tone alert. A single QRS beep is reserved for a later
release and is not generated yet. No visual alarm or simulation logic changed. release and is not generated yet. No visual alarm or simulation logic changed.
### v0.6.6 — Optional QRS/pulse beep
Added a separate **QRS tone** checkbox (enabled by default). An 85 ms
single-note beep follows actual ECG or mechanical beat events. With a valid
SpO₂ reading, the delayed pleth pulse determines the timing and the oxygen
saturation determines the pitch in eleven steps from 740 to 87 Hz; otherwise
ECG QRS or ART pulses trigger a fixed 500 Hz tone. The two-tone alarm sounds
remain unchanged. Added regression tests for band boundaries, event selection
and single-tone WAV output.

View file

@ -12,7 +12,7 @@ use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use crate::model::{AlarmLimits, AlarmState, Parameters, PulseConduction, Spo2Status}; use crate::model::{AlarmLimits, AlarmState, Parameters, PulseConduction, Spo2Status};
use crate::simulation::Simulator; use crate::simulation::{BeatEvent, BeatSource, Simulator};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum AlarmLevel { pub enum AlarmLevel {
@ -84,6 +84,88 @@ pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel {
result result
} }
/// Single-note QRS/pulse beep. The oximeter is the source when it has a
/// reading; otherwise use an ECG QRS or an available arterial pulse.
/// Mid is the fixed pitch used when no SpO2 reading is present.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QrsTone { Mid, Saturation(usize) }
const QRS_MID_HZ: f64 = 500.0;
const QRS_SPO2_HZ: [f64; 11] = [
740.0, 675.0, 609.0, 544.0, 479.0, 413.0,
348.0, 283.0, 218.0, 152.0, 87.0,
];
/// Stepwise saturation-to-pitch mapping: 100–97, 96–94, 93–90,
/// then 89–80, 79–70, ..., 19–10%. 10% or less always gives 87 Hz.
fn spo2_tone_index(saturation: i32) -> usize {
match saturation.clamp(0, 100) {
97..=100 => 0,
94..=96 => 1,
90..=93 => 2,
80..=89 => 3,
70..=79 => 4,
60..=69 => 5,
50..=59 => 6,
40..=49 => 7,
30..=39 => 8,
20..=29 => 9,
_ => 10,
}
}
pub fn qrs_tone(p: &Parameters, sim: &Simulator, events: &[BeatEvent]) -> Option<QrsTone> {
if p.show_spo2 && sim.spo2_status(p) == Spo2Status::Available {
// Actual peripheral pulses, not an independent HR metronome. This
// respects mechanical capture ratios and good-quality CPR.
return events.iter().any(|event| event.source == BeatSource::Pleth
&& sim.time() - event.time <= 0.25)
.then_some(QrsTone::Saturation(spo2_tone_index(p.spo2)));
}
// ECG takes precedence over the delayed arterial signal: never beep twice
// for the same QRS when both monitor channels are visible.
if p.show_ecg && p.ecg_rhythm.has_qrs() && p.heart_rate > 0 {
return events.iter().any(|event| event.source == BeatSource::Ecg
&& sim.time() - event.time <= 0.25)
.then_some(QrsTone::Mid);
}
if p.show_art {
return events.iter().any(|event| event.source == BeatSource::Art
&& sim.time() - event.time <= 0.25)
.then_some(QrsTone::Mid);
}
None
}
/// Original, brief PCM16 sine wave with smooth fades to avoid clicks.
fn single_beep_wav(frequency: f64) -> Vec<u8> {
const SAMPLE_RATE: u32 = 44_100;
const DURATION: f64 = 0.085;
let samples = (DURATION * f64::from(SAMPLE_RATE)).round() as usize;
let size = (samples * 2) as u32;
let mut bytes = Vec::with_capacity(44 + size as usize);
bytes.extend_from_slice(b"RIFF");
bytes.extend_from_slice(&(size + 36).to_le_bytes());
bytes.extend_from_slice(b"WAVEfmt ");
bytes.extend_from_slice(&16_u32.to_le_bytes());
bytes.extend_from_slice(&1_u16.to_le_bytes());
bytes.extend_from_slice(&1_u16.to_le_bytes());
bytes.extend_from_slice(&SAMPLE_RATE.to_le_bytes());
bytes.extend_from_slice(&(SAMPLE_RATE * 2).to_le_bytes());
bytes.extend_from_slice(&2_u16.to_le_bytes());
bytes.extend_from_slice(&16_u16.to_le_bytes());
bytes.extend_from_slice(b"data");
bytes.extend_from_slice(&size.to_le_bytes());
for i in 0..samples {
let t = i as f64 / f64::from(SAMPLE_RATE);
let remaining = (samples - i) as f64 / f64::from(SAMPLE_RATE);
let envelope = (t / 0.010).min(1.0).min(remaining / 0.016).max(0.0);
let value = (std::f64::consts::TAU * frequency * t).sin() * envelope * 0.13;
bytes.extend_from_slice(&((value * f64::from(i16::MAX)).round() as i16).to_le_bytes());
}
bytes
}
/// Both alarm priorities sound as two successive, different pitches. /// Both alarm priorities sound as two successive, different pitches.
/// A future QRS beep will be a separate, single-tone signal. /// A future QRS beep will be a separate, single-tone signal.
/// Zero-frequency segments are short silences between the notes. /// Zero-frequency segments are short silences between the notes.
@ -175,6 +257,115 @@ impl SoundFiles {
} }
} }
/// Prepared once on startup. Reuse the same playback utility as the alarms,
/// but use an independent child so the two-tone alarm is never interrupted by
/// single QRS/pulse beeps.
struct QrsSoundFiles {
mid: PathBuf,
saturations: Vec<PathBuf>,
}
impl Drop for QrsSoundFiles {
fn drop(&mut self) {
let _ = fs::remove_file(&self.mid);
for file in &self.saturations { let _ = fs::remove_file(file); }
}
}
impl QrsSoundFiles {
fn create_in(directory: &Path) -> io::Result<Self> {
let nonce = SystemTime::now().duration_since(UNIX_EPOCH)
.unwrap_or_default().as_nanos();
let prefix = format!("pamsim-qrs-{}-{nonce}", std::process::id());
let mid = directory.join(format!("{prefix}-mid.wav"));
write_new(&mid, &single_beep_wav(QRS_MID_HZ))?;
let mut files = Self { mid, saturations: Vec::new() };
for (i, &frequency) in QRS_SPO2_HZ.iter().enumerate() {
let path = directory.join(format!("{prefix}-spo2-{i}.wav"));
write_new(&path, &single_beep_wav(frequency))?;
files.saturations.push(path);
}
Ok(files)
}
fn create() -> io::Result<Self> {
if let Some(runtime) = env::var_os("XDG_RUNTIME_DIR") {
if let Ok(files) = Self::create_in(Path::new(&runtime)) {
return Ok(files);
}
}
Self::create_in(&env::temp_dir())
}
fn path(&self, tone: QrsTone) -> &Path {
match tone {
QrsTone::Mid => &self.mid,
QrsTone::Saturation(index) => &self.saturations[index.min(self.saturations.len() - 1)],
}
}
}
pub struct QrsAudio {
player: Option<&'static str>,
files: Option<QrsSoundFiles>,
child: Option<Child>,
error_reported: bool,
}
impl QrsAudio {
pub fn new() -> Self {
let player = ["pw-play", "paplay"].into_iter().find(|name| command_on_path(name));
let files = if player.is_some() {
match QrsSoundFiles::create() {
Ok(files) => Some(files),
Err(error) => {
eprintln!("PaMSim: cannot prepare QRS beeps: {error}");
None
}
}
} else { None };
Self { player, files, child: None, error_reported: false }
}
fn stop_child(&mut self) {
if let Some(mut child) = self.child.take() {
let _ = child.kill();
let _ = child.wait();
}
}
/// The audio timer delivers at most one beat in a 100-ms tick. Do not
/// replay events after disabling sound; do not restart an active beep.
pub fn update(&mut self, tone: Option<QrsTone>, enabled: bool) {
if !enabled {
self.stop_child();
return;
}
if let Some(child) = self.child.as_mut() {
match child.try_wait() {
Ok(Some(_)) | Err(_) => self.child = None,
Ok(None) => return,
}
}
let (Some(tone), Some(player), Some(files)) = (tone, self.player, self.files.as_ref())
else { return; };
match Command::new(player).arg(files.path(tone))
.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()
{
Ok(child) => self.child = Some(child),
Err(error) if !self.error_reported => {
eprintln!("PaMSim: QRS sound playback failed: {error}");
self.error_reported = true;
}
Err(_) => {}
}
}
}
impl Drop for QrsAudio {
fn drop(&mut self) { self.stop_child(); }
}
fn command_on_path(name: &str) -> bool { fn command_on_path(name: &str) -> bool {
env::var_os("PATH").is_some_and(|paths| { env::var_os("PATH").is_some_and(|paths| {
env::split_paths(&paths).any(|dir| { env::split_paths(&paths).any(|dir| {
@ -317,6 +508,59 @@ mod tests {
use super::*; use super::*;
use crate::model::{AlarmSettings, EcgRhythm}; use crate::model::{AlarmSettings, EcgRhythm};
#[test]
fn saturation_pitches_follow_exact_bands_and_decrease_to_87_hz() {
assert_eq!(QRS_SPO2_HZ.first(), Some(&740.0));
assert_eq!(QRS_SPO2_HZ.last(), Some(&87.0));
for (saturation, expected) in [
(100, 0), (97, 0), (96, 1), (94, 1), (93, 2), (90, 2),
(89, 3), (80, 3), (79, 4), (70, 4), (69, 5), (60, 5),
(59, 6), (50, 6), (49, 7), (40, 7), (39, 8), (30, 8),
(29, 9), (20, 9), (19, 10), (10, 10), (0, 10),
] {
assert_eq!(spo2_tone_index(saturation), expected, "SpO2 {saturation}%");
}
assert!(QRS_SPO2_HZ.windows(2).all(|hz| hz[0] > hz[1]));
assert_eq!(QRS_MID_HZ, 500.0);
}
#[test]
fn qrs_audio_uses_pleth_when_available_and_electrical_fallback_without_reading() {
let mut p = Parameters::default();
let mut sim = Simulator::new(&p);
let mut events = Vec::new();
for _ in 0..40 {
sim.advance(0.05, &p);
let current = sim.take_audio_events();
if current.iter().any(|e| e.source == BeatSource::Pleth
&& sim.time() - e.time <= 0.25) {
events = current;
break;
}
}
assert!(events.iter().any(|e| e.source == BeatSource::Pleth));
assert_eq!(qrs_tone(&p, &sim, &events), Some(QrsTone::Saturation(0)));
p.spo2_sensor_attached = false;
let fallback = [BeatEvent { source: BeatSource::Ecg, time: sim.time() },
BeatEvent { source: BeatSource::Art, time: sim.time() }];
assert_eq!(qrs_tone(&p, &sim, &fallback), Some(QrsTone::Mid));
p.show_ecg = false;
assert_eq!(qrs_tone(&p, &sim, &fallback), Some(QrsTone::Mid));
p.show_art = false;
assert_eq!(qrs_tone(&p, &sim, &fallback), None);
}
#[test]
fn single_beep_is_valid_wav_independent_of_two_tone_alarm() {
for hz in QRS_SPO2_HZ.iter().copied().chain([QRS_MID_HZ]) {
let bytes = single_beep_wav(hz);
assert_eq!(&bytes[..4], b"RIFF");
assert_eq!(&bytes[8..12], b"WAVE");
assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize + 8, bytes.len());
}
assert_ne!(single_beep_wav(740.0), single_beep_wav(87.0));
}
#[test] #[test]
fn valid_wav_files_and_distinct_tone_patterns() { fn valid_wav_files_and_distinct_tone_patterns() {
for critical in [false, true] { for critical in [false, true] {

View file

@ -267,6 +267,7 @@ pub struct Parameters {
pub patient_name: String, // displayed in the monitor header, blank = generic title pub patient_name: String, // displayed in the monitor header, blank = generic title
pub alarms: AlarmSettings, pub alarms: AlarmSettings,
pub audible_alarms: bool, // mute only the sound, never the visual alarms pub audible_alarms: bool, // mute only the sound, never the visual alarms
pub qrs_tone_enabled: bool, // beat-synchronous single beep; separate from two-tone alarms
pub chest_compressions_active: bool, pub chest_compressions_active: bool,
pub chest_compression_quality: ChestCompressionQuality, pub chest_compression_quality: ChestCompressionQuality,
pub ecg_rhythm: EcgRhythm, pub ecg_rhythm: EcgRhythm,
@ -346,6 +347,7 @@ impl Default for Parameters {
patient_name: String::new(), patient_name: String::new(),
alarms: AlarmSettings::default(), alarms: AlarmSettings::default(),
audible_alarms: true, audible_alarms: true,
qrs_tone_enabled: true,
chest_compressions_active: false, chest_compressions_active: false,
chest_compression_quality: ChestCompressionQuality::Adequate, chest_compression_quality: ChestCompressionQuality::Adequate,
ecg_rhythm: EcgRhythm::Sinus, ecg_rhythm: EcgRhythm::Sinus,

View file

@ -29,6 +29,18 @@ fn ppv_multiplier(ppv_percent: i32, respiratory_phase: f64) -> f64 {
* (std::f64::consts::TAU * respiratory_phase).sin() * (std::f64::consts::TAU * respiratory_phase).sin()
} }
/// One distinct electrical or mechanical beat event for the optional beep.
/// Electrical QRS, arterial and peripheral pulses are generated at their
/// respective physiological simulation times, not at the audio-timer rate.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BeatSource { Ecg, Art, Pleth }
#[derive(Clone, Copy, Debug)]
pub struct BeatEvent {
pub time: f64,
pub source: BeatSource,
}
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
pub struct Sample { pub struct Sample {
pub time: f64, pub time: f64,
@ -121,12 +133,12 @@ impl ChestCompressions {
}; };
} }
fn update(&mut self, enabled: bool, quality: ChestCompressionQuality) { fn update(&mut self, enabled: bool, quality: ChestCompressionQuality) -> bool {
if !enabled { if !enabled {
self.active = false; self.active = false;
self.phase = 0.0; self.phase = 0.0;
self.peak_pressure = 0.0; self.peak_pressure = 0.0;
return; return false;
} }
if !self.active { if !self.active {
self.active = true; self.active = true;
@ -143,7 +155,9 @@ impl ChestCompressions {
self.phase = self.phase.fract(); self.phase = self.phase.fract();
self.rate_bpm = 90.0 + self.random_unit() * 20.0; self.rate_bpm = 90.0 + self.random_unit() * 20.0;
self.choose_peak(); self.choose_peak();
return true;
} }
false
} }
fn pressure_wave(&self) -> f64 { fn pressure_wave(&self) -> f64 {
@ -184,6 +198,7 @@ pub struct Simulator {
ecg_beat_number: u64, ecg_beat_number: u64,
conducted_qrs: VecDeque<ConductedBeat>, // captured QRS with respiratory beat amplitude conducted_qrs: VecDeque<ConductedBeat>, // captured QRS with respiratory beat amplitude
rate_qrs: VecDeque<f64>, // captured beats for measured PR; reset after rate changes rate_qrs: VecDeque<f64>, // captured beats for measured PR; reset after rate changes
audio_events: VecDeque<BeatEvent>, // consumed by the 100-ms UI audio timer
filtered_pleth: f64, filtered_pleth: f64,
previous_rhythm: EcgRhythm, previous_rhythm: EcgRhythm,
previous_conduction: PulseConduction, previous_conduction: PulseConduction,
@ -205,6 +220,7 @@ impl Simulator {
ecg_beat_number: 0, ecg_beat_number: 0,
conducted_qrs: VecDeque::new(), conducted_qrs: VecDeque::new(),
rate_qrs: VecDeque::new(), rate_qrs: VecDeque::new(),
audio_events: VecDeque::new(),
filtered_pleth: 0.0, filtered_pleth: 0.0,
previous_rhythm: params.ecg_rhythm, previous_rhythm: params.ecg_rhythm,
previous_conduction: params.pulse_conduction, previous_conduction: params.pulse_conduction,
@ -219,6 +235,8 @@ impl Simulator {
for _ in 0..(8.0 / SAMPLE_STEP) as usize { for _ in 0..(8.0 / SAMPLE_STEP) as usize {
sim.step(params); sim.step(params);
} }
// Initial history is visual-only; never replay warmup beats as sound.
sim.audio_events.clear();
sim sim
} }
@ -336,6 +354,18 @@ impl Simulator {
&self.samples &self.samples
} }
/// Drain beat events since the previous sound callback. Kept bounded so
/// a suspended window cannot replay a long backlog of old beats.
pub fn take_audio_events(&mut self) -> Vec<BeatEvent> {
self.audio_events.drain(..).collect()
}
fn emit_beat(&mut self, source: BeatSource, time: f64) {
if time < 0.0 { return; } // no audio events from history warmup
if self.audio_events.len() >= 32 { self.audio_events.pop_front(); }
self.audio_events.push_back(BeatEvent { source, time });
}
/// Average of recent *mechanically captured* beat intervals, not an independent setting. /// Average of recent *mechanically captured* beat intervals, not an independent setting.
pub fn pulse_rate(&self) -> Option<i32> { pub fn pulse_rate(&self) -> Option<i32> {
if self.rate_qrs.len() < 2 { if self.rate_qrs.len() < 2 {
@ -355,8 +385,18 @@ impl Simulator {
fn step(&mut self, params: &Parameters) { fn step(&mut self, params: &Parameters) {
self.time += SAMPLE_STEP; self.time += SAMPLE_STEP;
self.compressions.update(params.chest_compressions_active, let compression_event = self.compressions.update(params.chest_compressions_active,
params.chest_compression_quality); params.chest_compression_quality);
if compression_event {
// Good CPR generates a pleth beat. Any effective CPR generates
// an arterial beat, even without underlying organized ECG.
if self.compressions.peak_pressure > 0.0 {
self.emit_beat(BeatSource::Art, self.time);
}
if params.chest_compression_quality == ChestCompressionQuality::Good {
self.emit_beat(BeatSource::Pleth, self.time);
}
}
self.poor_signal_outages.update(self.time, self.poor_signal_outages.update(self.time,
!params.chest_compressions_active && params.spo2_quality == Spo2Quality::Poor !params.chest_compressions_active && params.spo2_quality == Spo2Quality::Poor
&& params.spo2_sensor_attached); && params.spo2_sensor_attached);
@ -413,6 +453,7 @@ impl Simulator {
// Interpolate within the 4 ms sample so mechanical onsets stay aligned. // Interpolate within the 4 ms sample so mechanical onsets stay aligned.
let qrs_time = self.time - SAMPLE_STEP * (next_phase - QRS_PHASE) / increment; let qrs_time = self.time - SAMPLE_STEP * (next_phase - QRS_PHASE) / increment;
self.ecg_beat_number += 1; self.ecg_beat_number += 1;
self.emit_beat(BeatSource::Ecg, qrs_time);
if params.ecg_rhythm.can_generate_pulse() if params.ecg_rhythm.can_generate_pulse()
&& params.pulse_conduction.conducts(self.ecg_beat_number) { && params.pulse_conduction.conducts(self.ecg_beat_number) {
let pulse_pressure_scale = if params.respiratory_rate > 0 { let pulse_pressure_scale = if params.respiratory_rate > 0 {
@ -429,6 +470,29 @@ impl Simulator {
self.ecg_phase = 0.0; self.ecg_phase = 0.0;
} }
// Schedule single beeps at the delayed mechanical onsets. During CPR,
// the compression clock replaces the intrinsic ART/pleth sound source
// except for a perfusing native arterial pulse under ineffective CPR.
let mut mechanical_events = Vec::new();
for beat in &self.conducted_qrs {
let art_time = beat.qrs_time + ART_DELAY;
let pleth_time = beat.qrs_time + PLETH_DELAY;
if art_time > self.time - SAMPLE_STEP && art_time <= self.time
&& (!params.chest_compressions_active
|| params.chest_compression_quality == ChestCompressionQuality::Bad)
{
mechanical_events.push((BeatSource::Art, art_time));
}
if pleth_time > self.time - SAMPLE_STEP && pleth_time <= self.time
&& !params.chest_compressions_active
{
mechanical_events.push((BeatSource::Pleth, pleth_time));
}
}
for (source, time) in mechanical_events {
self.emit_beat(source, time);
}
// Preserve up to 30s of delivered events for stable derived PR calculations. // Preserve up to 30s of delivered events for stable derived PR calculations.
while self.conducted_qrs.front().is_some_and(|beat| beat.qrs_time < self.time - 30.0) { while self.conducted_qrs.front().is_some_and(|beat| beat.qrs_time < self.time - 30.0) {
self.conducted_qrs.pop_front(); self.conducted_qrs.pop_front();
@ -709,6 +773,60 @@ mod tests {
sim sim
} }
#[test]
fn audio_events_follow_actual_qrs_and_delayed_mechanical_pulses() {
let p = Parameters::default();
let mut sim = Simulator::new(&p);
for _ in 0..30 { sim.advance(0.1, &p); }
let events = sim.take_audio_events();
let qrs = events.iter().find(|e| e.source == BeatSource::Ecg).unwrap().time;
assert!(events.iter().any(|e| e.source == BeatSource::Art
&& ((e.time - qrs) - ART_DELAY).abs() <= SAMPLE_STEP));
assert!(events.iter().any(|e| e.source == BeatSource::Pleth
&& ((e.time - qrs) - PLETH_DELAY).abs() <= SAMPLE_STEP));
assert!(sim.take_audio_events().is_empty(), "events must be consumed once");
}
#[test]
fn two_to_one_capture_has_half_as_many_peripheral_audio_beats() {
let p = Parameters { pulse_conduction: PulseConduction::TwoToOne,
..Parameters::default() };
let mut sim = Simulator::new(&p);
let mut qrs = 0;
let mut pleth = 0;
for _ in 0..100 {
sim.advance(0.1, &p);
for event in sim.take_audio_events() {
match event.source {
BeatSource::Ecg => qrs += 1,
BeatSource::Pleth => pleth += 1,
BeatSource::Art => {}
}
}
}
assert!(qrs >= 10);
assert!((2 * pleth as i32 - qrs as i32).abs() <= 2,
"2:1 capture: {qrs} QRS events, {pleth} peripheral events");
}
#[test]
fn vf_generates_no_beats_without_cpr_but_compressions_generate_art_events() {
let mut p = Parameters { ecg_rhythm: EcgRhythm::VentricularFibrillation,
..Parameters::default() };
let mut sim = Simulator::new(&p);
for _ in 0..20 { sim.advance(0.1, &p); }
assert!(sim.take_audio_events().is_empty());
p.chest_compressions_active = true;
p.chest_compression_quality = ChestCompressionQuality::Adequate;
for _ in 0..20 { sim.advance(0.1, &p); }
let events = sim.take_audio_events();
assert!(events.iter().any(|e| e.source == BeatSource::Art));
assert!(!events.iter().any(|e| e.source == BeatSource::Pleth));
p.chest_compression_quality = ChestCompressionQuality::Good;
for _ in 0..20 { sim.advance(0.1, &p); }
assert!(sim.take_audio_events().iter().any(|e| e.source == BeatSource::Pleth));
}
#[test] #[test]
fn compression_rate_varies_only_between_90_and_110_bpm() { fn compression_rate_varies_only_between_90_and_110_bpm() {
let mut cpr = ChestCompressions::new(); let mut cpr = ChestCompressions::new();

View file

@ -8,7 +8,7 @@ use gtk::glib;
use gtk::prelude::*; use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Orientation}; use gtk::{Application, ApplicationWindow, Orientation};
use crate::alarm::{self, AlarmAudio}; use crate::alarm::{self, AlarmAudio, QrsAudio};
use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape, use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape,
ChestCompressionQuality, EcgLead, EcgRhythm, Parameters, PulseConduction, Spo2Quality}; ChestCompressionQuality, EcgLead, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
use crate::render; use crate::render;
@ -33,6 +33,7 @@ pub fn create_windows(app: &Application) {
let parameters = Rc::new(RefCell::new(Parameters::default())); let parameters = Rc::new(RefCell::new(Parameters::default()));
let simulator = Rc::new(RefCell::new(Simulator::new(&parameters.borrow()))); let simulator = Rc::new(RefCell::new(Simulator::new(&parameters.borrow())));
let audio = Rc::new(RefCell::new(AlarmAudio::new())); let audio = Rc::new(RefCell::new(AlarmAudio::new()));
let qrs_audio = Rc::new(RefCell::new(QrsAudio::new()));
install_ecg_menu_style(); // neutral style shared by all parameter panels install_ecg_menu_style(); // neutral style shared by all parameter panels
let admin_changed: AdminChanged = Rc::new(RefCell::new(None)); let admin_changed: AdminChanged = Rc::new(RefCell::new(None));
let monitor = create_monitor(app, parameters.clone(), simulator.clone(), let monitor = create_monitor(app, parameters.clone(), simulator.clone(),
@ -44,8 +45,13 @@ pub fn create_windows(app: &Application) {
// on sound playback. Audio also continues if the monitor is not mapped. // on sound playback. Audio also continues if the monitor is not mapped.
glib::timeout_add_local(Duration::from_millis(100), move || { glib::timeout_add_local(Duration::from_millis(100), move || {
let config = parameters.borrow(); let config = parameters.borrow();
let current = alarm::level(&config, &simulator.borrow()); let mut sim = simulator.borrow_mut();
let events = sim.take_audio_events();
let current = alarm::level(&config, &sim);
let beat_tone = alarm::qrs_tone(&config, &sim, &events);
drop(sim);
audio.borrow_mut().update(current, config.audible_alarms); audio.borrow_mut().update(current, config.audible_alarms);
qrs_audio.borrow_mut().update(beat_tone, config.qrs_tone_enabled);
glib::ControlFlow::Continue glib::ControlFlow::Continue
}); });
@ -210,6 +216,13 @@ fn create_admin(app: &Application, params: SharedParams,
move |button| params.borrow_mut().audible_alarms = button.is_active() move |button| params.borrow_mut().audible_alarms = button.is_active()
}); });
sound_row.append(&audible); sound_row.append(&audible);
let qrs_enabled = gtk::CheckButton::with_label("QRS tone");
qrs_enabled.set_active(params.borrow().qrs_tone_enabled);
qrs_enabled.connect_toggled({
let params = params.clone();
move |button| params.borrow_mut().qrs_tone_enabled = button.is_active()
});
sound_row.append(&qrs_enabled);
let test_sound = gtk::Button::with_label("Test tone"); let test_sound = gtk::Button::with_label("Test tone");
test_sound.connect_clicked({ test_sound.connect_clicked({
let audio = audio.clone(); let audio = audio.clone();