From 9cd9737613a9a47f2537a930b6c4ddc6c61bdddc Mon Sep 17 00:00:00 2001 From: Brice Delli Paoli Date: Thu, 10 May 2018 12:28:08 -0400 Subject: [PATCH] add logic to read and write persistent volume --- connect/src/spirc.rs | 12 +++++++++++- src/main.rs | 22 +++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/connect/src/spirc.rs b/connect/src/spirc.rs index d2bac872..4cc86d3a 100644 --- a/connect/src/spirc.rs +++ b/connect/src/spirc.rs @@ -196,7 +196,17 @@ fn calc_logarithmic_volume(volume: u16) -> u16 { val } -fn volume_to_mixer(volume: u16, linear_volume: bool) -> u16 { +// write linear volume (0..100) to file +fn write_volume(volume: u16, filepath: Option) { + let volume = volume as i32 * 100 / 0xFFFF; + let mut file = File::create(filepath.unwrap()).expect("Could not create persistent volume"); + file.write_all(volume.to_string().as_bytes()).expect("Could not write persistent volume"); +} + +fn volume_to_mixer(volume: u16, linear_volume: bool, persist_volume: Option) -> u16 { + if persist_volume.is_some() { + write_volume(volume, persist_volume); + } if linear_volume { debug!("linear volume: {}", volume); volume diff --git a/src/main.rs b/src/main.rs index 7d392160..abf96267 100644 --- a/src/main.rs +++ b/src/main.rs @@ -87,6 +87,19 @@ fn list_backends() { } } +// read linear volume (0..100) from file +// convert to 0..0xFFFF scale +fn read_volume(filepath: String) -> i32 { + let mut data = String::new(); + let mut file = File::open(filepath).expect("Could not open persistent volume"); + file.read_to_string(&mut data).expect("Could not read persistent volume"); + let volume = data.trim().parse::().expect("Persistent volume must be an integer"); + if volume < 0 || volume > 100 { + panic!("Initial volume must be in the range 0-100"); + } + volume * 0xFFFF / 100 +} + #[derive(Clone)] struct Setup { backend: fn(Option) -> Box, @@ -211,7 +224,7 @@ fn setup(args: &[String]) -> Setup { let mixer_name = matches.opt_str("mixer"); let mixer = mixer::find(mixer_name.as_ref()).expect("Invalid mixer"); - let initial_volume = matches + let mut initial_volume = matches .opt_str("initial-volume") .map(|volume| { let volume = volume.parse::().unwrap(); @@ -222,6 +235,13 @@ fn setup(args: &[String]) -> Setup { }) .unwrap_or(0x8000); + // check if user has requested persistent volume + // if the file exists, override initial volume + let persist_volume = matches.opt_str("persist-volume"); + if persist_volume.is_some() && Path::new(&persist_volume.clone().unwrap()).exists() { + initial_volume = read_volume(persist_volume.clone().unwrap()); + } + let zeroconf_port = matches .opt_str("zeroconf-port") .map(|port| port.parse::().unwrap())