From fdd50f9dc0f56ddaa629f4f36be76a062e2d13af Mon Sep 17 00:00:00 2001 From: George Hilliard Date: Fri, 29 Oct 2021 00:41:15 -0500 Subject: [PATCH] Refactor: move single-camera boilerplate to utils.rs --- src/main.rs | 2 +- src/reboot/mod.rs | 50 ++------------- src/statusled/mod.rs | 51 ++------------- src/talk/mod.rs | 150 ++++++++++++++++--------------------------- src/utils.rs | 48 +++++++++++++- 5 files changed, 119 insertions(+), 182 deletions(-) diff --git a/src/main.rs b/src/main.rs index 6aa14dc..6f033ad 100644 --- a/src/main.rs +++ b/src/main.rs @@ -40,7 +40,7 @@ fn main() -> Result<()> { &fs::read_to_string(&opt.config) .with_context(|| format!("Failed to read {:?}", &opt.config))?, ) - .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; + .with_context(|| format!("Failed to parse the {:?} config file", &opt.config))?; config .validate() diff --git a/src/reboot/mod.rs b/src/reboot/mod.rs index 1521bdc..435cc7f 100644 --- a/src/reboot/mod.rs +++ b/src/reboot/mod.rs @@ -11,58 +11,22 @@ /// neolink reboot --config=config.toml CameraName /// ``` /// -use anyhow::{anyhow, Context, Result}; -use log::*; +use anyhow::{Context, Result}; mod cmdline; use super::config::Config; -use crate::utils::AddressOrUid; +use crate::utils::find_and_connect; pub(crate) use cmdline::Opt; /// Entry point for the reboot subcommand /// /// Opt is the command line options pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { - let mut cam_found = false; - for camera_config in &config.cameras { - if opt.camera == camera_config.name { - cam_found = true; - let camera_addr = - AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); - info!( - "{}: Connecting to camera at {}", - camera_config.name, camera_addr - ); + let camera = find_and_connect(&config, &opt.camera)?; - let mut camera = camera_addr - .connect_camera(camera_config.channel_id) - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_addr, camera_config.channel_id - ) - })?; - - info!("{}: Logging in", camera_config.name); - camera - .login(&camera_config.username, camera_config.password.as_deref()) - .with_context(|| format!("Failed to login to {}", camera_config.name))?; - - info!("{}: Connected and logged in", camera_config.name); - - camera - .reboot() - .context("Could not send reboot command to the camera")?; - } - } - - if !cam_found { - Err(anyhow!( - "Camera {} not found in the config file", - &opt.camera, - )) - } else { - Ok(()) - } + camera + .reboot() + .context("Could not send reboot command to the camera")?; + Ok(()) } diff --git a/src/statusled/mod.rs b/src/statusled/mod.rs index 2ccffe1..ed50013 100644 --- a/src/statusled/mod.rs +++ b/src/statusled/mod.rs @@ -15,59 +15,22 @@ /// neolink status-light --config=config.toml CameraName off /// ``` /// -use anyhow::{anyhow, Context, Result}; -use log::*; +use anyhow::{Context, Result}; mod cmdline; use super::config::Config; -use crate::utils::AddressOrUid; +use crate::utils::find_and_connect; pub(crate) use cmdline::Opt; /// Entry point for the ledstatus subcommand /// /// Opt is the command line options pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { - let mut cam_found = false; - for camera_config in &config.cameras { - if opt.camera == camera_config.name { - cam_found = true; + let mut camera = find_and_connect(&config, &opt.camera)?; - let camera_addr = - AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); - info!( - "{}: Connecting to camera at {}", - camera_config.name, camera_addr - ); - - let mut camera = camera_addr - .connect_camera(camera_config.channel_id) - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_addr, camera_config.channel_id - ) - })?; - - info!("{}: Logging in", camera_config.name); - camera - .login(&camera_config.username, camera_config.password.as_deref()) - .with_context(|| format!("Failed to login to {}", camera_config.name))?; - - info!("{}: Connected and logged in", camera_config.name); - - camera - .led_light_set(opt.on) - .context("Unable to set camera light state")?; - } - } - - if !cam_found { - Err(anyhow!( - "Camera {} not found in the config file", - &opt.camera, - )) - } else { - Ok(()) - } + camera + .led_light_set(opt.on) + .context("Unable to set camera light state")?; + Ok(()) } diff --git a/src/talk/mod.rs b/src/talk/mod.rs index 44b823b..d0af688 100644 --- a/src/talk/mod.rs +++ b/src/talk/mod.rs @@ -12,113 +12,77 @@ /// ``` /// use anyhow::{anyhow, Context, Result}; -use log::*; use neolink_core::bc::xml::TalkConfig; mod cmdline; mod gst; use super::config::Config; -use crate::utils::AddressOrUid; +use crate::utils::{connect_and_login, find_camera_by_name}; pub(crate) use cmdline::Opt; /// Entry point for the talk subcommand /// /// Opt is the command line options pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { - let mut cam_found = false; - for camera_config in &config.cameras { - if opt.camera == camera_config.name { - cam_found = true; - let camera_addr = - AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_addr).unwrap(); - info!( - "{}: Connecting to camera at {}", - camera_config.name, camera_addr - ); + let camera_config = find_camera_by_name(&config, &opt.camera)?; + let camera = connect_and_login(camera_config)?; - let mut camera = camera_addr - .connect_camera(camera_config.channel_id) - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_addr, camera_config.channel_id - ) - })?; - - info!("{}: Logging in", camera_config.name); - camera - .login(&camera_config.username, camera_config.password.as_deref()) - .with_context(|| format!("Failed to login to {}", camera_config.name))?; - - info!("{}: Connected and logged in", camera_config.name); - - let talk_ability = camera - .talk_ability() - .with_context(|| format!("Camera {} does not support talk", camera_config.name))?; - if talk_ability.duplex_list.is_empty() - || talk_ability.audio_stream_mode_list.is_empty() - || talk_ability.audio_config_list.is_empty() - { - return Err(anyhow!( - "Camera {} does not support talk", - camera_config.name - )); - } - - // Just copy that data from the first talk ability in the config have never seen more - // than one ability - let config = 0; - - let talk_config = TalkConfig { - channel_id: camera_config.channel_id, - duplex: talk_ability.duplex_list[config].duplex.clone(), - audio_stream_mode: talk_ability.audio_stream_mode_list[config] - .audio_stream_mode - .clone(), - audio_config: talk_ability.audio_config_list[config].audio_config.clone(), - ..Default::default() - }; - - let block_size = (talk_config.audio_config.length_per_encoder / 2) + 4; - let sample_rate = talk_config.audio_config.sample_rate; - if block_size == 0 || sample_rate == 0 { - return Err(anyhow!( - "The camera {} does not support talk with adpcm", - camera_config.name - )); - } - - let rx = match (&opt.file_path, &opt.microphone) { - (Some(path), false) => gst::from_input( - &format!( - "filesrc location={}", - path.to_str().expect("File path not UTF8 complient") - ), - opt.volume, - block_size, - sample_rate, - ) - .with_context(|| format!("Failed to setup gst with the file: {:?}", path))?, - (None, true) => { - gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate) - .context("Failed to setup gst using the microphone")? - } - _ => unreachable!(), - }; - - camera - .talk_stream(rx, talk_config) - .context("Talk stream ended early")?; - } + let talk_ability = camera + .talk_ability() + .with_context(|| format!("Camera {} does not support talk", camera_config.name))?; + if talk_ability.duplex_list.is_empty() + || talk_ability.audio_stream_mode_list.is_empty() + || talk_ability.audio_config_list.is_empty() + { + return Err(anyhow!( + "Camera {} does not support talk", + camera_config.name + )); } - if !cam_found { - Err(anyhow!( - "Camera {} not found in the config file", - &opt.camera, - )) - } else { - Ok(()) + // Just copy that data from the first talk ability in the config have never seen more + // than one ability + let config = 0; + + let talk_config = TalkConfig { + channel_id: camera_config.channel_id, + duplex: talk_ability.duplex_list[config].duplex.clone(), + audio_stream_mode: talk_ability.audio_stream_mode_list[config] + .audio_stream_mode + .clone(), + audio_config: talk_ability.audio_config_list[config].audio_config.clone(), + ..Default::default() + }; + + let block_size = (talk_config.audio_config.length_per_encoder / 2) + 4; + let sample_rate = talk_config.audio_config.sample_rate; + if block_size == 0 || sample_rate == 0 { + return Err(anyhow!( + "The camera {} does not support talk with adpcm", + camera_config.name + )); } + + let rx = match (&opt.file_path, &opt.microphone) { + (Some(path), false) => gst::from_input( + &format!( + "filesrc location={}", + path.to_str().expect("File path not UTF8 complient") + ), + opt.volume, + block_size, + sample_rate, + ) + .with_context(|| format!("Failed to setup gst with the file: {:?}", path))?, + (None, true) => gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate) + .context("Failed to setup gst using the microphone")?, + _ => unreachable!(), + }; + + camera + .talk_stream(rx, talk_config) + .context("Talk stream ended early")?; + + Ok(()) } diff --git a/src/utils.rs b/src/utils.rs index 8039f9f..cd0e067 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,6 +1,9 @@ //! Contains code that is not specific to any of the subcommands //! -use anyhow::{anyhow, Error}; +use log::*; + +use super::config::{CameraConfig, Config}; +use anyhow::{anyhow, Context, Error, Result}; use neolink_core::bc_protocol::BcCamera; use std::fmt::{Display, Error as FmtError, Formatter}; @@ -37,3 +40,46 @@ impl AddressOrUid { } } } + +pub(crate) fn find_and_connect(config: &Config, name: &str) -> Result { + let camera_config = find_camera_by_name(config, name)?; + connect_and_login(camera_config) +} + +pub(crate) fn connect_and_login(camera_config: &CameraConfig) -> Result { + let camera_addr = + AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); + info!( + "{}: Connecting to camera at {}", + camera_config.name, camera_addr + ); + + let mut camera = camera_addr + .connect_camera(camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_addr, camera_config.channel_id + ) + })?; + + info!("{}: Logging in", camera_config.name); + camera + .login(&camera_config.username, camera_config.password.as_deref()) + .with_context(|| format!("Failed to login to {}", camera_config.name))?; + + info!("{}: Connected and logged in", camera_config.name); + + Ok(camera) +} + +pub(crate) fn find_camera_by_name<'a, 'b>( + config: &'a Config, + name: &'b str, +) -> Result<&'a CameraConfig> { + config + .cameras + .iter() + .find(|c| c.name == name) + .ok_or_else(|| anyhow!("Camera {} not found in the config file", name)) +}