Add Uid as a seperate field into the config

This commit is contained in:
QuantumEntangledAndy committed 2021-09-08 11:45:37 +07:00
1 parent 8327a8348b
commit 9b23d8dbfc
11 files changed
+269 -93

No files matched your search

+114 -53
View File
@@ -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<T: ToSocketAddrsOrUid>(host: T, channel_id: u8) -> Result<Self> {
pub fn new_with_addr<T: ToSocketAddrs>(host: T, channel_id: u8) -> Result<Self> {
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> {
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<T: ToSocketAddrsOrUid>(host: T, channel_id: u8) -> Result<Self> {
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<Self> {
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)
+1
View File
@@ -17,6 +17,7 @@ mod reboot;
mod rtsp;
mod statusled;
mod talk;
mod utils;
use cmdline::{Command, Opt};
+18 -2
View File
@@ -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<String>,
#[serde(rename = "uid")]
pub(crate) camera_uid: Option<String>,
pub(crate) username: String,
pub(crate) password: Option<String>,
@@ -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(()),
}
}
+12 -10
View File
@@ -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
+17 -1
View File
@@ -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<String>,
#[serde(rename = "uid")]
pub(crate) camera_uid: Option<String>,
pub(crate) username: String,
pub(crate) password: Option<String>,
@@ -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(()),
}
}
+6 -3
View File
@@ -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);
+18 -2
View File
@@ -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<String>,
#[serde(rename = "uid")]
pub(crate) camera_uid: Option<String>,
pub(crate) username: String,
pub(crate) password: Option<String>,
@@ -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(()),
}
}
+13 -10
View File
@@ -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
+18 -2
View File
@@ -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<String>,
#[serde(rename = "uid")]
pub(crate) camera_uid: Option<String>,
pub(crate) username: String,
pub(crate) password: Option<String>,
@@ -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(()),
}
}
+13 -10
View File
@@ -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
+39
View File
@@ -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<String>, uid: &Option<String>) -> Result<Self, Error> {
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<BcCamera, Error> {
match self {
AddressOrUid::Address(host) => Ok(BcCamera::new_with_addr(host, channel_id)?),
AddressOrUid::Uid(host) => Ok(BcCamera::new_with_uid(host, channel_id)?),
}
}
}