From de39e7ed2a771c374d24a83d2f5486c9adfa4845 Mon Sep 17 00:00:00 2001 From: George Hilliard Date: Fri, 29 Oct 2021 00:25:54 -0500 Subject: [PATCH 1/3] Re-unify configuration files Unfortunately the grammar of the --config parameter is a bit of a football right now; previously you were allowed to specify it anywhere because there wasn't much in the way of a CLI, then when subcommands were added it became required to specify it after the subcommand. This change makes it so that it must be specified *before* the subcommand. Ideally it would just be required *somewhere* in the command line but clap doesn't support "global" for required arguments (and it is indeed required). On the whole, I'm okay with the change - the net win of having a unified config struct makes up for the ergonomics hit in my opinion, and it unlocks some further refactoring I will do next. --- src/cmdline.rs | 2 +- src/{rtsp => }/config.rs | 0 src/main.rs | 43 +++++++++++++++++++++++--------------- src/reboot/cmdline.rs | 4 ---- src/reboot/config.rs | 45 ---------------------------------------- src/reboot/mod.rs | 20 +++--------------- src/rtsp/cmdline.rs | 7 +------ src/rtsp/mod.rs | 17 ++------------- src/statusled/cmdline.rs | 4 ---- src/statusled/config.rs | 45 ---------------------------------------- src/statusled/mod.rs | 20 +++--------------- src/talk/cmdline.rs | 3 --- src/talk/config.rs | 45 ---------------------------------------- src/talk/mod.rs | 22 ++++---------------- 14 files changed, 40 insertions(+), 237 deletions(-) rename src/{rtsp => }/config.rs (100%) delete mode 100644 src/reboot/config.rs delete mode 100644 src/statusled/config.rs delete mode 100644 src/talk/config.rs diff --git a/src/cmdline.rs b/src/cmdline.rs index 6136dce..1b4d3a6 100644 --- a/src/cmdline.rs +++ b/src/cmdline.rs @@ -6,7 +6,7 @@ use structopt::{clap::AppSettings, StructOpt}; #[structopt(name = "neolink", setting(AppSettings::ArgRequiredElseHelp))] pub struct Opt { #[structopt(short, long, parse(from_os_str))] - pub config: Option, + pub config: PathBuf, #[structopt(subcommand)] pub cmd: Option, } diff --git a/src/rtsp/config.rs b/src/config.rs similarity index 100% rename from src/rtsp/config.rs rename to src/config.rs diff --git a/src/main.rs b/src/main.rs index 4bfcfe9..6aa14dc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,12 +7,15 @@ //! It contains sub commands for running an rtsp proxy which can be used on Reolink cameras //! that do not nativly support RTSP. //! -use anyhow::Result; +use anyhow::{Context, Result}; use env_logger::Env; use log::*; +use std::fs; use structopt::StructOpt; +use validator::Validate; mod cmdline; +mod config; mod reboot; mod rtsp; mod statusled; @@ -20,6 +23,7 @@ mod talk; mod utils; use cmdline::{Command, Opt}; +use config::Config; fn main() -> Result<()> { env_logger::Builder::from_env(Env::default().default_filter_or("info")).init(); @@ -32,30 +36,35 @@ fn main() -> Result<()> { let opt = Opt::from_args(); - match (opt.cmd, opt.config) { - (None, None) => { - // Should be caught at the clap validation - unreachable!(); - } - (None, Some(config)) => { + let config: Config = toml::from_str( + &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))?; + + config + .validate() + .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; + + match opt.cmd { + None => { warn!( "Deprecated command line option. Please use: `neolink rtsp --config={:?}`", config ); - rtsp::main(rtsp::Opt { config })?; + rtsp::main(rtsp::Opt {}, config)?; } - (Some(_), Some(_)) => error!("--config should be given after the subcommand"), - (Some(Command::Rtsp(opts)), None) => { - rtsp::main(opts)?; + Some(Command::Rtsp(opts)) => { + rtsp::main(opts, config)?; } - (Some(Command::StatusLight(opts)), None) => { - statusled::main(opts)?; + Some(Command::StatusLight(opts)) => { + statusled::main(opts, config)?; } - (Some(Command::Reboot(opts)), None) => { - reboot::main(opts)?; + Some(Command::Reboot(opts)) => { + reboot::main(opts, config)?; } - (Some(Command::Talk(opts)), None) => { - talk::main(opts)?; + Some(Command::Talk(opts)) => { + talk::main(opts, config)?; } } diff --git a/src/reboot/cmdline.rs b/src/reboot/cmdline.rs index 8c94ee1..1f6cd91 100644 --- a/src/reboot/cmdline.rs +++ b/src/reboot/cmdline.rs @@ -1,12 +1,8 @@ -use std::path::PathBuf; use structopt::StructOpt; /// The reboot command will reboot the camera #[derive(StructOpt, Debug)] pub struct Opt { - /// The path to the config file - #[structopt(short, long, parse(from_os_str))] - pub config: PathBuf, /// The name of the camera to change the lights of. Must be a name in the config pub camera: String, } diff --git a/src/reboot/config.rs b/src/reboot/config.rs deleted file mode 100644 index 3000f65..0000000 --- a/src/reboot/config.rs +++ /dev/null @@ -1,45 +0,0 @@ -use serde::Deserialize; -use std::clone::Clone; -use validator::{Validate, ValidationError}; -use validator_derive::Validate; - -#[derive(Debug, Deserialize, Validate, Clone)] -pub(crate) struct Config { - #[validate] - pub(crate) cameras: Vec, -} - -#[derive(Debug, Deserialize, Validate, Clone)] -#[validate(schema(function = "validate_camera_config"))] -pub(crate) struct CameraConfig { - pub(crate) name: String, - - #[serde(rename = "address")] - pub(crate) camera_addr: Option, - - #[serde(rename = "uid")] - pub(crate) camera_uid: Option, - - pub(crate) username: String, - pub(crate) password: Option, - - #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] - #[serde(default = "default_channel_id")] - pub(crate) channel_id: u8, -} - -fn default_channel_id() -> u8 { - 0 -} - -fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> { - match (&camera_config.camera_addr, &camera_config.camera_uid) { - (None, None) => Err(ValidationError::new( - "Either camera address or uid must be given", - )), - (Some(_), Some(_)) => Err(ValidationError::new( - "Must provide either camera address or uid not both", - )), - _ => Ok(()), - } -} diff --git a/src/reboot/mod.rs b/src/reboot/mod.rs index d7187c0..1521bdc 100644 --- a/src/reboot/mod.rs +++ b/src/reboot/mod.rs @@ -13,30 +13,17 @@ /// use anyhow::{anyhow, Context, Result}; use log::*; -use std::fs; -use validator::Validate; mod cmdline; -mod config; +use super::config::Config; use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; -use config::Config; /// Entry point for the reboot subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<()> { - let config: Config = toml::from_str( - &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))?; - - config - .validate() - .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; - +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 { @@ -72,9 +59,8 @@ pub fn main(opt: Opt) -> Result<()> { if !cam_found { Err(anyhow!( - "Camera {} was not in the config file {:?}", + "Camera {} not found in the config file", &opt.camera, - &opt.config )) } else { Ok(()) diff --git a/src/rtsp/cmdline.rs b/src/rtsp/cmdline.rs index 2a7092b..baedb75 100644 --- a/src/rtsp/cmdline.rs +++ b/src/rtsp/cmdline.rs @@ -1,10 +1,5 @@ -use std::path::PathBuf; use structopt::StructOpt; /// The rtsp command will serve all cameras in the config over the rtsp protocol #[derive(StructOpt, Debug)] -pub struct Opt { - /// The path to the config file - #[structopt(short, long, parse(from_os_str))] - pub config: PathBuf, -} +pub struct Opt {} diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs index d055f14..6c11129 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -33,37 +33,24 @@ use log::*; use neolink_core::bc_protocol::{BcCamera, Stream}; use neolink_core::Never; use std::collections::HashSet; -use std::fs; use std::sync::Arc; use std::time::Duration; -use validator::Validate; // mod adpcm; /// The command line parameters for this subcommand mod cmdline; -mod config; /// The errors this subcommand can raise mod gst; +use super::config::{CameraConfig, Config, UserConfig}; use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; -use config::{CameraConfig, Config, UserConfig}; use gst::{GstOutputs, RtspServer, TlsAuthenticationMode}; /// Entry point for the rtsp subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<()> { - let config: Config = toml::from_str( - &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))?; - - config - .validate() - .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; - +pub(crate) fn main(_opt: Opt, config: Config) -> Result<()> { let rtsp = &RtspServer::new(); set_up_tls(&config, rtsp); diff --git a/src/statusled/cmdline.rs b/src/statusled/cmdline.rs index e0c448d..1a47514 100644 --- a/src/statusled/cmdline.rs +++ b/src/statusled/cmdline.rs @@ -1,5 +1,4 @@ use anyhow::{anyhow, Result}; -use std::path::PathBuf; use structopt::StructOpt; fn onoff_parse(src: &str) -> Result { @@ -16,9 +15,6 @@ fn onoff_parse(src: &str) -> Result { /// The status-light command will control the blue status light on the camera #[derive(StructOpt, Debug)] pub struct Opt { - /// The path to the config file - #[structopt(short, long, parse(from_os_str))] - pub config: PathBuf, /// The name of the camera to change the lights of. Must be a name in the config pub camera: String, /// Whether to turn the light on or off diff --git a/src/statusled/config.rs b/src/statusled/config.rs deleted file mode 100644 index 3000f65..0000000 --- a/src/statusled/config.rs +++ /dev/null @@ -1,45 +0,0 @@ -use serde::Deserialize; -use std::clone::Clone; -use validator::{Validate, ValidationError}; -use validator_derive::Validate; - -#[derive(Debug, Deserialize, Validate, Clone)] -pub(crate) struct Config { - #[validate] - pub(crate) cameras: Vec, -} - -#[derive(Debug, Deserialize, Validate, Clone)] -#[validate(schema(function = "validate_camera_config"))] -pub(crate) struct CameraConfig { - pub(crate) name: String, - - #[serde(rename = "address")] - pub(crate) camera_addr: Option, - - #[serde(rename = "uid")] - pub(crate) camera_uid: Option, - - pub(crate) username: String, - pub(crate) password: Option, - - #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] - #[serde(default = "default_channel_id")] - pub(crate) channel_id: u8, -} - -fn default_channel_id() -> u8 { - 0 -} - -fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> { - match (&camera_config.camera_addr, &camera_config.camera_uid) { - (None, None) => Err(ValidationError::new( - "Either camera address or uid must be given", - )), - (Some(_), Some(_)) => Err(ValidationError::new( - "Must provide either camera address or uid not both", - )), - _ => Ok(()), - } -} diff --git a/src/statusled/mod.rs b/src/statusled/mod.rs index 5f3769f..2ccffe1 100644 --- a/src/statusled/mod.rs +++ b/src/statusled/mod.rs @@ -17,30 +17,17 @@ /// use anyhow::{anyhow, Context, Result}; use log::*; -use std::fs; -use validator::Validate; mod cmdline; -mod config; +use super::config::Config; use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; -use config::Config; /// Entry point for the ledstatus subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<()> { - let config: Config = toml::from_str( - &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))?; - - config - .validate() - .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; - +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 { @@ -77,9 +64,8 @@ pub fn main(opt: Opt) -> Result<()> { if !cam_found { Err(anyhow!( - "Camera {} was not in the config file {:?}", + "Camera {} not found in the config file", &opt.camera, - &opt.config )) } else { Ok(()) diff --git a/src/talk/cmdline.rs b/src/talk/cmdline.rs index bd16704..675e574 100644 --- a/src/talk/cmdline.rs +++ b/src/talk/cmdline.rs @@ -9,9 +9,6 @@ use structopt::StructOpt; /// `gst-launch` can be used to prepare this data #[derive(StructOpt, Debug)] pub struct Opt { - /// The path to the config file - #[structopt(short, long, parse(from_os_str))] - pub config: PathBuf, /// The name of the camera to change the lights of. Must be a name in the config pub camera: String, /// The path to the audio file. diff --git a/src/talk/config.rs b/src/talk/config.rs deleted file mode 100644 index 3000f65..0000000 --- a/src/talk/config.rs +++ /dev/null @@ -1,45 +0,0 @@ -use serde::Deserialize; -use std::clone::Clone; -use validator::{Validate, ValidationError}; -use validator_derive::Validate; - -#[derive(Debug, Deserialize, Validate, Clone)] -pub(crate) struct Config { - #[validate] - pub(crate) cameras: Vec, -} - -#[derive(Debug, Deserialize, Validate, Clone)] -#[validate(schema(function = "validate_camera_config"))] -pub(crate) struct CameraConfig { - pub(crate) name: String, - - #[serde(rename = "address")] - pub(crate) camera_addr: Option, - - #[serde(rename = "uid")] - pub(crate) camera_uid: Option, - - pub(crate) username: String, - pub(crate) password: Option, - - #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] - #[serde(default = "default_channel_id")] - pub(crate) channel_id: u8, -} - -fn default_channel_id() -> u8 { - 0 -} - -fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> { - match (&camera_config.camera_addr, &camera_config.camera_uid) { - (None, None) => Err(ValidationError::new( - "Either camera address or uid must be given", - )), - (Some(_), Some(_)) => Err(ValidationError::new( - "Must provide either camera address or uid not both", - )), - _ => Ok(()), - } -} diff --git a/src/talk/mod.rs b/src/talk/mod.rs index c9a569f..44b823b 100644 --- a/src/talk/mod.rs +++ b/src/talk/mod.rs @@ -8,37 +8,24 @@ /// # Usage /// /// ```bash -/// neolink status-light --config=config.toml --adpcm-file=data.adpcm --sample-rate=16000 --block-size=512 CameraName +/// neolink talk --config=config.toml --adpcm-file=data.adpcm --sample-rate=16000 --block-size=512 CameraName /// ``` /// use anyhow::{anyhow, Context, Result}; use log::*; use neolink_core::bc::xml::TalkConfig; -use std::fs; -use validator::Validate; mod cmdline; -mod config; mod gst; +use super::config::Config; use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; -use config::Config; /// Entry point for the talk subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<()> { - let config: Config = toml::from_str( - &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))?; - - config - .validate() - .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; - +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 { @@ -128,9 +115,8 @@ pub fn main(opt: Opt) -> Result<()> { if !cam_found { Err(anyhow!( - "Camera {} was not in the config file {:?}", + "Camera {} not found in the config file", &opt.camera, - &opt.config )) } else { Ok(()) From fdd50f9dc0f56ddaa629f4f36be76a062e2d13af Mon Sep 17 00:00:00 2001 From: George Hilliard Date: Fri, 29 Oct 2021 00:41:15 -0500 Subject: [PATCH 2/3] 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)) +} From 81b148f6cd9ea65f98392c7094304bd70ce51994 Mon Sep 17 00:00:00 2001 From: George Hilliard Date: Fri, 29 Oct 2021 01:24:02 -0500 Subject: [PATCH 3/3] Allow --config anywhere in CLI Since clap doesn't support required + global, do our own insisting. --- src/cmdline.rs | 10 +++++++--- src/main.rs | 9 +++++---- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/cmdline.rs b/src/cmdline.rs index 1b4d3a6..1fb1f18 100644 --- a/src/cmdline.rs +++ b/src/cmdline.rs @@ -3,10 +3,14 @@ use structopt::{clap::AppSettings, StructOpt}; /// A standards-compliant bridge to Reolink IP cameras #[derive(StructOpt, Debug)] -#[structopt(name = "neolink", setting(AppSettings::ArgRequiredElseHelp))] +#[structopt( + name = "neolink", + setting(AppSettings::ArgRequiredElseHelp), + setting(AppSettings::UnifiedHelpMessage) +)] pub struct Opt { - #[structopt(short, long, parse(from_os_str))] - pub config: PathBuf, + #[structopt(short, long, global(true), parse(from_os_str))] + pub config: Option, #[structopt(subcommand)] pub cmd: Option, } diff --git a/src/main.rs b/src/main.rs index 6f033ad..ff6a0fb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,15 +36,16 @@ fn main() -> Result<()> { let opt = Opt::from_args(); + let conf_path = opt.config.context("Must supply --config file")?; let config: Config = toml::from_str( - &fs::read_to_string(&opt.config) - .with_context(|| format!("Failed to read {:?}", &opt.config))?, + &fs::read_to_string(&conf_path) + .with_context(|| format!("Failed to read {:?}", conf_path))?, ) - .with_context(|| format!("Failed to parse the {:?} config file", &opt.config))?; + .with_context(|| format!("Failed to parse the {:?} config file", conf_path))?; config .validate() - .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; + .with_context(|| format!("Failed to validate the {:?} config file", conf_path))?; match opt.cmd { None => {