2026-11-12 14:34:31 +01:00
|
|
|
//! 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;
|
|
|
|
|
|
|
|
|
|
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 {
|
2026-11-12 15:11:04 +01:00
|
|
|
let status = sim.spo2_status(p);
|
2026-11-12 14:34:31 +01:00
|
|
|
if status != Spo2Status::Available
|
|
|
|
|
|| outside(p.alarms.spo2, Some(p.spo2))
|
2026-11-12 15:11:04 +01:00
|
|
|
|| outside(p.alarms.pr, sim.spo2_pulse_rate(p))
|
2026-11-12 14:34:31 +01:00
|
|
|
{
|
|
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
}
|