v0.5.3: add alarm sounds
This commit is contained in:
parent
4eb67a76ec
commit
fcd8c1146f
10 changed files with 1121 additions and 12 deletions
364
patient-monitor-simulation/src/alarm.rs
Normal file
364
patient-monitor-simulation/src/alarm.rs
Normal file
|
|
@ -0,0 +1,364 @@
|
|||
//! Audible teaching alarms. This is not a clinical alarm system.
|
||||
//!
|
||||
//! The decision uses the same available readings, visibility settings and limits
|
||||
//! as the monitor. Sound is played using Fedora's PipeWire command-line player
|
||||
//! (or paplay) without adding a native audio-library dependency to Cargo.
|
||||
|
||||
use std::env;
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
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;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum AlarmLevel {
|
||||
#[default]
|
||||
None,
|
||||
Standard,
|
||||
Critical,
|
||||
}
|
||||
|
||||
fn outside(limits: AlarmLimits, value: Option<i32>) -> bool {
|
||||
limits.evaluate(value) != AlarmState::Normal
|
||||
}
|
||||
|
||||
/// Only parameters actually shown on the monitor contribute audible alarms.
|
||||
/// Missing numeric values do not trigger threshold alarms, but missing SpO2
|
||||
/// readings and disconnected sensors are explicit technical alarms.
|
||||
pub fn level(p: &Parameters, sim: &Simulator) -> AlarmLevel {
|
||||
let mut result = AlarmLevel::None;
|
||||
let hr = (p.ecg_rhythm.has_qrs() && p.heart_rate > 0).then_some(p.heart_rate);
|
||||
let captured = p.ecg_rhythm.can_generate_pulse()
|
||||
&& p.heart_rate > 0
|
||||
&& p.pulse_conduction != PulseConduction::None;
|
||||
let pr = if captured { sim.pulse_rate() } else { None };
|
||||
|
||||
if p.show_ecg {
|
||||
if p.ecg_rhythm.rhythm_alarm().is_some() {
|
||||
return AlarmLevel::Critical;
|
||||
}
|
||||
if outside(p.alarms.hr, hr) {
|
||||
result = AlarmLevel::Standard;
|
||||
}
|
||||
}
|
||||
|
||||
if p.show_spo2 {
|
||||
let status = p.spo2_status_at_quality(pr, sim.poor_signal_lost(), sim.spo2_quality(p));
|
||||
if status != Spo2Status::Available
|
||||
|| outside(p.alarms.spo2, Some(p.spo2))
|
||||
|| outside(p.alarms.pr, pr)
|
||||
{
|
||||
result = AlarmLevel::Standard;
|
||||
}
|
||||
}
|
||||
|
||||
if p.show_art {
|
||||
let (sys, dia, map) = sim.displayed_art_pressures(p, captured);
|
||||
if outside(p.alarms.art_sys, sys)
|
||||
|| outside(p.alarms.art_dia, dia)
|
||||
|| outside(p.alarms.art_map, map)
|
||||
|| outside(p.alarms.ppv, Some(p.pulse_pressure_variation))
|
||||
{
|
||||
result = AlarmLevel::Standard;
|
||||
}
|
||||
}
|
||||
|
||||
if p.show_capno && (outside(p.alarms.etco2, Some(p.etco2))
|
||||
|| outside(p.alarms.rr, Some(p.respiratory_rate)))
|
||||
{
|
||||
result = AlarmLevel::Standard;
|
||||
}
|
||||
|
||||
if p.show_nibp {
|
||||
let reading = sim.nibp().reading();
|
||||
if outside(p.alarms.nibp_sys, reading.map(|r| r.systolic))
|
||||
|| outside(p.alarms.nibp_dia, reading.map(|r| r.diastolic))
|
||||
|| outside(p.alarms.nibp_map, reading.map(|r| r.mean()))
|
||||
{
|
||||
result = AlarmLevel::Standard;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Very short, original synthesized sine beeps; mono PCM16 WAV.
|
||||
fn wav(critical: bool) -> Vec<u8> {
|
||||
const SAMPLE_RATE: u32 = 44_100;
|
||||
let segments: &[(f64, f64)] = if critical {
|
||||
&[(880.0, 0.16), (0.0, 0.09), (880.0, 0.16)]
|
||||
} else {
|
||||
&[(700.0, 0.18)]
|
||||
};
|
||||
let samples: usize = segments.iter()
|
||||
.map(|(_, seconds)| (seconds * f64::from(SAMPLE_RATE)).round() as usize)
|
||||
.sum();
|
||||
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()); // PCM format chunk
|
||||
bytes.extend_from_slice(&1_u16.to_le_bytes()); // PCM
|
||||
bytes.extend_from_slice(&1_u16.to_le_bytes()); // mono
|
||||
bytes.extend_from_slice(&SAMPLE_RATE.to_le_bytes());
|
||||
bytes.extend_from_slice(&(SAMPLE_RATE * 2).to_le_bytes()); // byte rate
|
||||
bytes.extend_from_slice(&2_u16.to_le_bytes()); // block align
|
||||
bytes.extend_from_slice(&16_u16.to_le_bytes()); // bits per sample
|
||||
bytes.extend_from_slice(b"data");
|
||||
bytes.extend_from_slice(&size.to_le_bytes());
|
||||
|
||||
for &(frequency, seconds) in segments {
|
||||
let count = (seconds * f64::from(SAMPLE_RATE)).round() as usize;
|
||||
for i in 0..count {
|
||||
let t = i as f64 / f64::from(SAMPLE_RATE);
|
||||
let remaining = (count - i) as f64 / f64::from(SAMPLE_RATE);
|
||||
let envelope = (t / 0.012).min(1.0).min(remaining / 0.012).max(0.0);
|
||||
let value = if frequency > 0.0 {
|
||||
(2.0 * std::f64::consts::PI * frequency * t).sin() * envelope * 0.17
|
||||
} else { 0.0 };
|
||||
let sample = (value * f64::from(i16::MAX)).round() as i16;
|
||||
bytes.extend_from_slice(&sample.to_le_bytes());
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
struct SoundFiles {
|
||||
standard: PathBuf,
|
||||
critical: PathBuf,
|
||||
}
|
||||
|
||||
impl Drop for SoundFiles {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_file(&self.standard);
|
||||
let _ = fs::remove_file(&self.critical);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_new(path: &Path, content: &[u8]) -> io::Result<()> {
|
||||
let mut out = OpenOptions::new().write(true).create_new(true).open(path)?;
|
||||
out.write_all(content)
|
||||
}
|
||||
|
||||
impl SoundFiles {
|
||||
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-{}-{nonce}", std::process::id());
|
||||
let standard = directory.join(format!("{prefix}-alarm.wav"));
|
||||
let critical = directory.join(format!("{prefix}-critical.wav"));
|
||||
write_new(&standard, &wav(false))?;
|
||||
if let Err(err) = write_new(&critical, &wav(true)) {
|
||||
let _ = fs::remove_file(&standard);
|
||||
return Err(err);
|
||||
}
|
||||
Ok(Self { standard, critical })
|
||||
}
|
||||
|
||||
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 command_on_path(name: &str) -> bool {
|
||||
env::var_os("PATH").is_some_and(|paths| {
|
||||
env::split_paths(&paths).any(|dir| {
|
||||
let candidate = dir.join(name);
|
||||
if !candidate.is_file() { return false; }
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::metadata(&candidate).is_ok_and(|meta| meta.permissions().mode() & 0o111 != 0)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{ true }
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Sound playback runs outside the GTK drawing callback. At most one short
|
||||
/// player process exists at a time; stopping or muting kills an active tone.
|
||||
pub struct AlarmAudio {
|
||||
player: Option<&'static str>,
|
||||
files: Option<SoundFiles>,
|
||||
child: Option<Child>,
|
||||
previous: AlarmLevel,
|
||||
next_at: Instant,
|
||||
error_reported: bool,
|
||||
}
|
||||
|
||||
impl AlarmAudio {
|
||||
pub fn new() -> Self {
|
||||
let player = ["pw-play", "paplay"].into_iter().find(|name| command_on_path(name));
|
||||
let files = if player.is_some() {
|
||||
match SoundFiles::create() {
|
||||
Ok(files) => Some(files),
|
||||
Err(error) => {
|
||||
eprintln!("PaMSim: cannot prepare alarm tones: {error}");
|
||||
None
|
||||
}
|
||||
}
|
||||
} else { None };
|
||||
if player.is_none() {
|
||||
eprintln!("PaMSim: alarm audio unavailable; install pipewire-utils (pw-play) on Fedora.");
|
||||
}
|
||||
Self {
|
||||
player, files, child: None, previous: AlarmLevel::None,
|
||||
next_at: Instant::now(), error_reported: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn available(&self) -> bool {
|
||||
self.player.is_some() && self.files.is_some()
|
||||
}
|
||||
|
||||
fn stop_child(&mut self) {
|
||||
if let Some(mut child) = self.child.take() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn reap(&mut self) {
|
||||
if let Some(child) = self.child.as_mut() {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
self.child = None;
|
||||
if !status.success() && !self.error_reported {
|
||||
eprintln!("PaMSim: alarm sound player exited with {status}; check PipeWire and the output device.");
|
||||
self.error_reported = true;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
self.child = None;
|
||||
if !self.error_reported {
|
||||
eprintln!("PaMSim: could not check alarm playback: {error}");
|
||||
self.error_reported = true;
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn play(&mut self, level: AlarmLevel) {
|
||||
self.reap();
|
||||
if self.child.is_some() { return; }
|
||||
let (Some(player), Some(files)) = (self.player, self.files.as_ref()) else { return; };
|
||||
let filename = if level == AlarmLevel::Critical { &files.critical } else { &files.standard };
|
||||
match Command::new(player).arg(filename)
|
||||
.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()
|
||||
{
|
||||
Ok(child) => self.child = Some(child),
|
||||
Err(error) if !self.error_reported => {
|
||||
eprintln!("PaMSim: alarm sound playback failed: {error}");
|
||||
self.error_reported = true;
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Called from a 100-ms GLib timer, not the 250-Hz waveform simulator.
|
||||
/// Critical rhythms: double tone every 1.5 s; other alarms: single tone
|
||||
/// every 2.5 s. Stop promptly when muted or all alarm states clear.
|
||||
pub fn update(&mut self, level: AlarmLevel, enabled: bool) {
|
||||
self.reap();
|
||||
if !enabled || level == AlarmLevel::None {
|
||||
self.stop_child();
|
||||
self.previous = AlarmLevel::None;
|
||||
return;
|
||||
}
|
||||
let now = Instant::now();
|
||||
if level != self.previous {
|
||||
self.stop_child();
|
||||
self.previous = level;
|
||||
self.next_at = now;
|
||||
}
|
||||
if now >= self.next_at {
|
||||
self.play(level);
|
||||
self.next_at = now + if level == AlarmLevel::Critical {
|
||||
Duration::from_millis(1500)
|
||||
} else { Duration::from_millis(2500) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Manual test is independent of the audible-alarm enable checkbox.
|
||||
pub fn test(&mut self) {
|
||||
self.stop_child();
|
||||
self.play(AlarmLevel::Standard);
|
||||
self.next_at = Instant::now() + Duration::from_millis(2500);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AlarmAudio {
|
||||
fn drop(&mut self) {
|
||||
self.stop_child();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::{AlarmSettings, EcgRhythm};
|
||||
|
||||
#[test]
|
||||
fn valid_wav_files_and_distinct_tone_patterns() {
|
||||
for critical in [false, true] {
|
||||
let bytes = wav(critical);
|
||||
assert_eq!(&bytes[..4], b"RIFF");
|
||||
assert_eq!(&bytes[8..12], b"WAVE");
|
||||
assert_eq!(&bytes[36..40], b"data");
|
||||
assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()) as usize + 8, bytes.len());
|
||||
assert_eq!(u32::from_le_bytes(bytes[40..44].try_into().unwrap()) as usize + 44, bytes.len());
|
||||
}
|
||||
assert!(wav(true).len() > wav(false).len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_signals_are_silent_and_numeric_limit_alarms_beep() {
|
||||
let mut p = Parameters::default();
|
||||
let sim = Simulator::new(&p);
|
||||
assert_eq!(level(&p, &sim), AlarmLevel::None);
|
||||
p.alarms = AlarmSettings::adult();
|
||||
assert_eq!(level(&p, &sim), AlarmLevel::None);
|
||||
p.heart_rate = 110;
|
||||
assert_eq!(level(&p, &sim), AlarmLevel::Standard);
|
||||
p.show_ecg = false;
|
||||
assert_eq!(level(&p, &sim), AlarmLevel::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rhythms_are_critical_and_sensor_issues_are_standard() {
|
||||
let mut p = Parameters::default();
|
||||
p.spo2_sensor_attached = false;
|
||||
let sim = Simulator::new(&p);
|
||||
assert_eq!(level(&p, &sim), AlarmLevel::Standard);
|
||||
p.spo2_sensor_attached = true;
|
||||
p.ecg_rhythm = EcgRhythm::VentricularFibrillation;
|
||||
assert_eq!(level(&p, &sim), AlarmLevel::Critical);
|
||||
p.ecg_rhythm = EcgRhythm::Asystole;
|
||||
assert_eq!(level(&p, &sim), AlarmLevel::Critical);
|
||||
p.show_ecg = false;
|
||||
assert_eq!(level(&p, &sim), AlarmLevel::Standard); // no SpO2 reading
|
||||
p.show_spo2 = false;
|
||||
assert_eq!(level(&p, &sim), AlarmLevel::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_nibp_measurement_does_not_trigger_numeric_alarm() {
|
||||
let mut p = Parameters::default();
|
||||
p.alarms.nibp_sys.lower = Some(120);
|
||||
let sim = Simulator::new(&p);
|
||||
assert!(sim.nibp().reading().is_none());
|
||||
assert_eq!(level(&p, &sim), AlarmLevel::None);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
mod alarm;
|
||||
mod model;
|
||||
mod nibp;
|
||||
mod render;
|
||||
|
|
|
|||
|
|
@ -201,6 +201,7 @@ impl AlarmSettings {
|
|||
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 ecg_rhythm: EcgRhythm,
|
||||
pub heart_rate: i32, // bpm, organized electrical rate; not mechanical pulse rate
|
||||
pub pulse_conduction: PulseConduction,
|
||||
|
|
@ -275,6 +276,7 @@ impl Default for Parameters {
|
|||
Self {
|
||||
patient_name: String::new(),
|
||||
alarms: AlarmSettings::default(),
|
||||
audible_alarms: true,
|
||||
ecg_rhythm: EcgRhythm::Sinus,
|
||||
heart_rate: 75,
|
||||
pulse_conduction: PulseConduction::OneToOne,
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
//! GTK4 Admin and Monitor windows; all callbacks run on the GTK main thread.
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::time::Instant;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use gtk::gdk;
|
||||
use gtk::glib;
|
||||
use gtk::prelude::*;
|
||||
use gtk::{Application, ApplicationWindow, Orientation};
|
||||
|
||||
use crate::alarm::{self, AlarmAudio};
|
||||
use crate::model::{AlarmLimits, AlarmSettings, ArterialShape, CapnoShape, EcgRhythm, Parameters, PulseConduction, Spo2Quality};
|
||||
use crate::render;
|
||||
use crate::simulation::Simulator;
|
||||
|
|
@ -25,8 +26,18 @@ const MONITOR_GREY: AccentColor = (0.80, 0.84, 0.87);
|
|||
pub fn create_windows(app: &Application) {
|
||||
let parameters = Rc::new(RefCell::new(Parameters::default()));
|
||||
let simulator = Rc::new(RefCell::new(Simulator::new(¶meters.borrow())));
|
||||
let audio = Rc::new(RefCell::new(AlarmAudio::new()));
|
||||
let monitor = create_monitor(app, parameters.clone(), simulator.clone());
|
||||
let admin = create_admin(app, parameters, simulator, &monitor);
|
||||
let admin = create_admin(app, parameters.clone(), simulator.clone(), &monitor, audio.clone());
|
||||
|
||||
// Alarm evaluation has its own 100-ms timer; waveform drawing never blocks
|
||||
// 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());
|
||||
audio.borrow_mut().update(current, config.audible_alarms);
|
||||
glib::ControlFlow::Continue
|
||||
});
|
||||
|
||||
// Present monitor first, then leave controls in the foreground.
|
||||
monitor.present();
|
||||
|
|
@ -90,7 +101,8 @@ fn create_monitor(app: &Application, params: SharedParams,
|
|||
|
||||
fn create_admin(app: &Application, params: SharedParams,
|
||||
simulator: Rc<RefCell<Simulator>>,
|
||||
monitor: &ApplicationWindow) -> ApplicationWindow {
|
||||
monitor: &ApplicationWindow,
|
||||
audio: Rc<RefCell<AlarmAudio>>) -> ApplicationWindow {
|
||||
let window = ApplicationWindow::builder()
|
||||
.application(app)
|
||||
.title(concat!("Patient Monitor — Admin v", env!("CARGO_PKG_VERSION")))
|
||||
|
|
@ -131,6 +143,28 @@ fn create_admin(app: &Application, params: SharedParams,
|
|||
preset_row.append(&preset_caption);
|
||||
preset_row.append(&preset_dropdown);
|
||||
controls.append(&preset_row);
|
||||
|
||||
// Sound control is independent of visual alarm limits and of the rhythm.
|
||||
let sound_row = gtk::Box::new(Orientation::Horizontal, 12);
|
||||
let audible = gtk::CheckButton::with_label("Audible alarms");
|
||||
audible.set_active(params.borrow().audible_alarms);
|
||||
audible.connect_toggled({
|
||||
let params = params.clone();
|
||||
move |button| params.borrow_mut().audible_alarms = button.is_active()
|
||||
});
|
||||
sound_row.append(&audible);
|
||||
let test_sound = gtk::Button::with_label("Test tone");
|
||||
test_sound.connect_clicked({
|
||||
let audio = audio.clone();
|
||||
move |_| audio.borrow_mut().test()
|
||||
});
|
||||
sound_row.append(&test_sound);
|
||||
if !audio.borrow().available() {
|
||||
let missing = gtk::Label::new(Some("Audio unavailable — install pipewire-utils"));
|
||||
missing.set_xalign(0.0);
|
||||
sound_row.append(&missing);
|
||||
}
|
||||
controls.append(&sound_row);
|
||||
let updating_preset = Rc::new(Cell::new(false));
|
||||
let mut alarm_editors: Vec<(AlarmEditor, fn(&AlarmSettings) -> AlarmLimits)> = Vec::new();
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue