diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index 9c81700..b058622 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -1,6 +1,7 @@ use crate::{bc, bcmedia}; use log::*; use std::convert::TryInto; +use std::net::ToSocketAddrs; use std::sync::atomic::{AtomicU16, Ordering}; use Md5Trunc::*; @@ -75,7 +76,7 @@ impl BcCamera { /// /// # Parameters /// - /// * `host` - The address of the camera either ip address, hostname string, or uid is ok + /// * `host` - The address of the camera either ip address, hostname string /// /// * `channel_id` - The channel ID this is usually zero unless using a NVR /// @@ -83,68 +84,128 @@ impl BcCamera { /// /// returns either an error or the camera /// - pub fn new_with_addr(host: T, channel_id: u8) -> Result { + pub fn new_with_addr(host: T, channel_id: u8) -> Result { + let addr_iter = match host.to_socket_addrs() { + Ok(iter) => iter, + Err(_) => return Err(Error::AddrResolutionError), + }; + for addr in addr_iter { + if let Ok(cam) = Self::new(SocketAddrOrUid::SocketAddr(addr), channel_id) { + return Ok(cam); + } + } + + Err(Error::Timeout) + } + + /// + /// Create a new camera interface with this uid and channel ID + /// + /// # Parameters + /// + /// * `uid` - The uid of the camera + /// + /// * `channel_id` - The channel ID this is usually zero unless using a NVR + /// + /// # Returns + /// + /// returns either an error or the camera + /// + pub fn new_with_uid(uid: &str, channel_id: u8) -> Result { + Self::new(SocketAddrOrUid::Uid(uid.to_string()), channel_id) + } + + /// + /// Create a new camera interface with this address/uid and channel ID + /// + /// This method will first perform hostname resolution on the address + /// then fallback to uid if that resolution fails. + /// + /// Be aware that it is possible (although unlikely) that there is + /// a dns entry with the same address as the uid. If uncertain use + /// one of the other methods. + /// + /// # Parameters + /// + /// * `host` - The address of the camera either ip address, hostname string, or uid + /// + /// * `channel_id` - The channel ID this is usually zero unless using a NVR + /// + /// # Returns + /// + /// returns either an error or the camera + /// + pub fn new_with_addr_or_uid(host: T, channel_id: u8) -> Result { let addr_iter = match host.to_socket_addrs_or_uid() { Ok(iter) => iter, Err(_) => return Err(Error::AddrResolutionError), }; - - for addr in addr_iter { - let source = match addr { - SocketAddrOrUid::SocketAddr(addr) => { - debug!("Trying address {}", addr); - BcSource::new_tcp(addr, RX_TIMEOUT)? - } - SocketAddrOrUid::Uid(uid) => { - debug!("Trying uid {}", uid); - BcSource::new_udp(&uid, RX_TIMEOUT)? - } - }; - - let conn = match BcConnection::new(source) { - Ok(conn) => conn, - Err(err) => match err { - connection::Error::Communication(ref err) => { - debug!("Assuming timeout from {}", err); - continue; - } - err => return Err(err.into()), - }, - }; - - debug!("Success"); - let me = Self { - connection: Some(conn), - message_num: AtomicU16::new(0), - channel_id, - logged_in: false, - credentials: None, - }; - - if let Some(conn) = &me.connection { - let keep_alive_msg = Bc { - meta: BcMeta { - msg_id: MSG_ID_UDP_KEEP_ALIVE, - channel_id: me.channel_id, - msg_num: me.new_message_num(), - stream_type: 0, - response_code: 0, - class: 0x6414, - }, - body: BcBody::ModernMsg(ModernMsg { - ..Default::default() - }), - }; - - conn.set_keep_alive_msg(keep_alive_msg); + for addr_or_uid in addr_iter { + if let Ok(cam) = Self::new(addr_or_uid, channel_id) { + return Ok(cam); } - - return Ok(me); } Err(Error::Timeout) } + /// + /// Create a new camera interface with this address/uid and channel ID + /// + /// # Parameters + /// + /// * `addr` - An enum of [`SocketAddrOrUid`] that contains the address + /// + /// * `channel_id` - The channel ID this is usually zero unless using a NVR + /// + /// # Returns + /// + /// returns either an error or the camera + /// + pub fn new(addr: SocketAddrOrUid, channel_id: u8) -> Result { + let source = match addr { + SocketAddrOrUid::SocketAddr(addr) => { + debug!("Trying address {}", addr); + BcSource::new_tcp(addr, RX_TIMEOUT)? + } + SocketAddrOrUid::Uid(uid) => { + debug!("Trying uid {}", uid); + BcSource::new_udp(&uid, RX_TIMEOUT)? + } + }; + + let conn = BcConnection::new(source)?; + + debug!("Success"); + let me = Self { + connection: Some(conn), + message_num: AtomicU16::new(0), + channel_id, + logged_in: false, + credentials: None, + }; + + if let Some(conn) = &me.connection { + let keep_alive_msg = Bc { + meta: BcMeta { + msg_id: MSG_ID_UDP_KEEP_ALIVE, + channel_id: me.channel_id, + msg_num: me.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + ..Default::default() + }), + }; + + conn.set_keep_alive_msg(keep_alive_msg); + } + + Ok(me) + } + /// This method will get a new message number and increment the message count atomically pub fn new_message_num(&self) -> u16 { self.message_num.fetch_add(1, Ordering::Relaxed) diff --git a/src/main.rs b/src/main.rs index 64f1f63..4bfcfe9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,6 +17,7 @@ mod reboot; mod rtsp; mod statusled; mod talk; +mod utils; use cmdline::{Command, Opt}; diff --git a/src/reboot/config.rs b/src/reboot/config.rs index de60ef2..3000f65 100644 --- a/src/reboot/config.rs +++ b/src/reboot/config.rs @@ -1,6 +1,6 @@ use serde::Deserialize; use std::clone::Clone; -use validator::Validate; +use validator::{Validate, ValidationError}; use validator_derive::Validate; #[derive(Debug, Deserialize, Validate, Clone)] @@ -10,11 +10,15 @@ pub(crate) struct Config { } #[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: String, + pub(crate) camera_addr: Option, + + #[serde(rename = "uid")] + pub(crate) camera_uid: Option, pub(crate) username: String, pub(crate) password: Option, @@ -27,3 +31,15 @@ pub(crate) struct CameraConfig { 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 9219e45..d7187c0 100644 --- a/src/reboot/mod.rs +++ b/src/reboot/mod.rs @@ -13,13 +13,13 @@ /// use anyhow::{anyhow, Context, Result}; use log::*; -use neolink_core::bc_protocol::BcCamera; use std::fs; use validator::Validate; mod cmdline; mod config; +use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; use config::Config; @@ -41,19 +41,21 @@ pub fn main(opt: Opt) -> Result<()> { 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_config.camera_addr + camera_config.name, camera_addr ); - let mut camera = - BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_config.camera_addr, camera_config.channel_id - ) - })?; + 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 diff --git a/src/rtsp/config.rs b/src/rtsp/config.rs index fb2ead6..013c3de 100644 --- a/src/rtsp/config.rs +++ b/src/rtsp/config.rs @@ -41,11 +41,15 @@ pub(crate) struct Config { } #[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: String, + pub(crate) camera_addr: Option, + + #[serde(rename = "uid")] + pub(crate) camera_uid: Option, pub(crate) username: String, pub(crate) password: Option, @@ -115,3 +119,15 @@ fn validate_username(name: &str) -> Result<(), ValidationError> { } Ok(()) } + +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/rtsp/mod.rs b/src/rtsp/mod.rs index 0c45298..d055f14 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -45,6 +45,7 @@ mod config; /// The errors this subcommand can raise mod gst; +use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; use config::{CameraConfig, Config, UserConfig}; use gst::{GstOutputs, RtspServer, TlsAuthenticationMode}; @@ -225,12 +226,14 @@ fn camera_main( let mut connected = false; let mut login_fail = false; (|| { + let camera_addr = + AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); let mut camera = - BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) + camera_addr.connect_camera(camera_config.channel_id) .with_context(|| { format!( "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_config.camera_addr, camera_config.channel_id + camera_config.name, camera_addr, camera_config.channel_id ) })?; @@ -241,7 +244,7 @@ fn camera_main( info!( "{}: Connecting to camera at {}", - camera_config.name, camera_config.camera_addr + camera_config.name, camera_addr ); info!("{}: Logging in", camera_config.name); diff --git a/src/statusled/config.rs b/src/statusled/config.rs index de60ef2..3000f65 100644 --- a/src/statusled/config.rs +++ b/src/statusled/config.rs @@ -1,6 +1,6 @@ use serde::Deserialize; use std::clone::Clone; -use validator::Validate; +use validator::{Validate, ValidationError}; use validator_derive::Validate; #[derive(Debug, Deserialize, Validate, Clone)] @@ -10,11 +10,15 @@ pub(crate) struct Config { } #[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: String, + pub(crate) camera_addr: Option, + + #[serde(rename = "uid")] + pub(crate) camera_uid: Option, pub(crate) username: String, pub(crate) password: Option, @@ -27,3 +31,15 @@ pub(crate) struct CameraConfig { 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 6f32b2a..5f3769f 100644 --- a/src/statusled/mod.rs +++ b/src/statusled/mod.rs @@ -17,13 +17,13 @@ /// use anyhow::{anyhow, Context, Result}; use log::*; -use neolink_core::bc_protocol::BcCamera; use std::fs; use validator::Validate; mod cmdline; mod config; +use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; use config::Config; @@ -45,19 +45,22 @@ pub fn main(opt: Opt) -> Result<()> { 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_config.camera_addr + camera_config.name, camera_addr ); - let mut camera = - BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_config.camera_addr, camera_config.channel_id - ) - })?; + 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 diff --git a/src/talk/config.rs b/src/talk/config.rs index de60ef2..3000f65 100644 --- a/src/talk/config.rs +++ b/src/talk/config.rs @@ -1,6 +1,6 @@ use serde::Deserialize; use std::clone::Clone; -use validator::Validate; +use validator::{Validate, ValidationError}; use validator_derive::Validate; #[derive(Debug, Deserialize, Validate, Clone)] @@ -10,11 +10,15 @@ pub(crate) struct Config { } #[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: String, + pub(crate) camera_addr: Option, + + #[serde(rename = "uid")] + pub(crate) camera_uid: Option, pub(crate) username: String, pub(crate) password: Option, @@ -27,3 +31,15 @@ pub(crate) struct CameraConfig { 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 a2a032a..c9a569f 100644 --- a/src/talk/mod.rs +++ b/src/talk/mod.rs @@ -13,7 +13,7 @@ /// use anyhow::{anyhow, Context, Result}; use log::*; -use neolink_core::{bc::xml::TalkConfig, bc_protocol::BcCamera}; +use neolink_core::bc::xml::TalkConfig; use std::fs; use validator::Validate; @@ -21,6 +21,7 @@ mod cmdline; mod config; mod gst; +use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; use config::Config; @@ -42,19 +43,21 @@ pub fn main(opt: Opt) -> Result<()> { 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_config.camera_addr + camera_config.name, camera_addr ); - let mut camera = - BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_config.camera_addr, camera_config.channel_id - ) - })?; + 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 diff --git a/src/utils.rs b/src/utils.rs new file mode 100644 index 0000000..7f1f8e5 --- /dev/null +++ b/src/utils.rs @@ -0,0 +1,39 @@ +//! Contains code that is not specific to any of the subcommands +//! +use anyhow::{anyhow, Error}; +use neolink_core::bc_protocol::BcCamera; +use std::fmt::{Display, Error as FmtError, Formatter}; + +pub(crate) enum AddressOrUid { + Address(String), + Uid(String), +} + +impl Display for AddressOrUid { + fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { + match self { + AddressOrUid::Address(host) => write!(f, "Address: {}", host), + AddressOrUid::Uid(host) => write!(f, "UID: {}", host), + } + } +} + +impl AddressOrUid { + // Created by translating the config fields directly + pub(crate) fn new(address: &Option, uid: &Option) -> Result { + match (address, uid) { + (None, None) => Err(anyhow!("Neither address or uid given")), + (Some(_), Some(_)) => Err(anyhow!("Either address of uid should be given not both")), + (Some(host), None) => Ok(AddressOrUid::Address(host.clone())), + (None, Some(host)) => Ok(AddressOrUid::Uid(host.clone())), + } + } + + // Convience method to get the BcCamera with the appropiate method + pub(crate) fn connect_camera(&self, channel_id: u8) -> Result { + match self { + AddressOrUid::Address(host) => Ok(BcCamera::new_with_addr(host, channel_id)?), + AddressOrUid::Uid(host) => Ok(BcCamera::new_with_uid(host, channel_id)?), + } + } +}