Added config option to control discovery

This commit is contained in:
QuantumEntangledAndy authored and Andrew King committed 2023-02-22 09:55:28 +07:00
1 parent 3949dca1af
commit b49ce87f32
6 files changed
+95 -22

No files matched your search

+9 -5
View File
@@ -115,9 +115,10 @@ impl BcCamera {
channel_id: u8,
username: U,
passwd: Option<V>,
discovery_method: DiscoveryMethods,
) -> Result<Self> {
Self::new(
SocketAddrOrUid::Uid(uid.to_string()),
SocketAddrOrUid::Uid(uid.to_string(), discovery_method),
channel_id,
username,
passwd,
@@ -200,12 +201,15 @@ impl BcCamera {
.split();
(Box::new(x), Box::new(r))
}
SocketAddrOrUid::Uid(uid) => {
SocketAddrOrUid::Uid(uid, method) => {
debug!("Trying uid {}", uid);
// TODO Make configurable
let allow_local = false;
let allow_remote = false;
let allow_relay = true;
let (allow_local, allow_remote, allow_relay) = match method {
DiscoveryMethods::None => (false, false, false),
DiscoveryMethods::Local => (true, false, false),
DiscoveryMethods::Remote => (true, true, false),
DiscoveryMethods::Relay => (true, true, true),
};
let discovery = {
let mut set = tokio::task::JoinSet::new();
+34 -3
View File
@@ -6,12 +6,35 @@ use std::{
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs},
};
/// Select permitted discovery methods
///
/// This is used for UID lookup, it is unused with
/// TPC/known ip address cameras
#[derive(Debug, Copy, Clone)]
pub enum DiscoveryMethods {
/// Forbid all discovery methods. Only TCP connections with known addresses will work
None,
/// Allow local discovery on the local network using broadcasts
/// This method does NOT contact reolink servers
Local,
/// Allow contact with the reolink servers to learn the ip address but DO NOT
/// allow the camera/clinet to communicate through the reolink servers.
///
/// **This also enabled `Local` discovery**
Remote,
/// Allow contact with the reolink servers to learn the ip address and relay the connection
/// through those servers.
///
/// **This also enabled `Local` and `Remote` discovery**
Relay,
}
/// Used to return either the SocketAddr or the UID
pub enum SocketAddrOrUid {
/// When the result is a addr it will be this
SocketAddr(SocketAddr),
/// When the result is a UID
Uid(String),
Uid(String, DiscoveryMethods),
}
/// An extension of ToSocketAddrs that will also resolve to a camera UID
@@ -50,7 +73,11 @@ impl ToSocketAddrsOrUid for str {
debug!("Trying as uid");
let re = regex::Regex::new(r"^[0-9A-Za-z]+$").unwrap();
if re.is_match(self) {
Ok(vec![SocketAddrOrUid::Uid(self.to_string())].into_iter())
Ok(vec![SocketAddrOrUid::Uid(
self.to_string(),
DiscoveryMethods::Local,
)]
.into_iter())
} else {
debug!("Regex fails {:?} => {:?} ", re, self);
Err(e)
@@ -73,7 +100,11 @@ impl ToSocketAddrsOrUid for String {
debug!("Trying as uid");
let re = regex::Regex::new(r"^[0-9A-Za-z]+$").unwrap();
if re.is_match(self) {
Ok(vec![SocketAddrOrUid::Uid(self.to_string())].into_iter())
Ok(vec![SocketAddrOrUid::Uid(
self.to_string(),
DiscoveryMethods::Local,
)]
.into_iter())
} else {
debug!("Regex fails {:?} => {:?} ", re, self);
Err(e)
+13
View File
@@ -10,6 +10,7 @@ lazy_static! {
Regex::new(r"^(mainStream|subStream|externStream|both|all)$").unwrap();
static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap();
static ref RE_PAUSE_MODE: Regex = Regex::new(r"^(black|still|test|none)$").unwrap();
static ref RE_DISC_SRC: Regex = Regex::new(r"^([nN]one|[lL]ocal|[rR]emote|[rR]elay)$").unwrap();
}
#[derive(Debug, Deserialize, Validate, Clone)]
@@ -75,6 +76,14 @@ pub(crate) struct CameraConfig {
#[validate]
#[serde(default = "default_pause")]
pub(crate) pause: PauseConfig,
#[serde(default = "default_discovery")]
#[validate(regex(
path = "RE_DISC_SRC",
message = "Invalid discovery method",
code = "discovery"
))]
pub(crate) discovery: String,
}
#[derive(Debug, Deserialize, Validate, Clone)]
@@ -119,6 +128,10 @@ fn default_mqtt() -> Option<MqttConfig> {
None
}
fn default_discovery() -> String {
"Relay".to_string()
}
#[derive(Debug, Deserialize, Validate, Clone)]
pub(crate) struct PauseConfig {
#[serde(default = "default_on_motion")]
+6 -2
View File
@@ -143,8 +143,12 @@ impl EventCam {
rx: Arc<Mutex<Receiver<ToCamera>>>,
app: Arc<App>,
) -> Result<()> {
let camera_addr =
AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap();
let camera_addr = AddressOrUid::new(
&camera_config.camera_addr,
&camera_config.camera_uid,
&camera_config.discovery,
)
.unwrap();
info!(
"{}: Connecting to camera at {}",
+4 -3
View File
@@ -53,12 +53,13 @@ impl RtspCamera {
rtsp: Arc<RtspServer>,
) -> Result<Self, Error> {
let camera_addr =
AddressOrUid::new(&config.camera_addr, &config.camera_uid).with_context(|| {
format!(
AddressOrUid::new(&config.camera_addr, &config.camera_uid, &config.discovery)
.with_context(|| {
format!(
"Could not connect to camera {}. Please check UUID or IP:Port in the config",
config.name
)
})?;
})?;
info!("{}: Connecting to camera at {}", config.name, camera_addr);
let camera = camera_addr
+29 -9
View File
@@ -4,31 +4,47 @@ use log::*;
use super::config::{CameraConfig, Config};
use anyhow::{anyhow, Context, Error, Result};
use neolink_core::bc_protocol::BcCamera;
use neolink_core::bc_protocol::{BcCamera, DiscoveryMethods};
use std::fmt::{Display, Error as FmtError, Formatter};
pub(crate) enum AddressOrUid {
Address(String),
Uid(String),
Uid(String, DiscoveryMethods),
}
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),
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> {
pub(crate) fn new(
address: &Option<String>,
uid: &Option<String>,
disc_method: &str,
) -> Result<Self, Error> {
match (address, uid) {
(None, None) => Err(anyhow!("Neither address or uid given")),
(Some(_), Some(_)) => Err(anyhow!("Either address or uid should be given not both")),
(Some(host), None) => Ok(AddressOrUid::Address(host.clone())),
(None, Some(host)) => Ok(AddressOrUid::Uid(host.clone())),
(None, Some(host)) => {
let method = match disc_method.to_lowercase().as_str() {
"none" => DiscoveryMethods::None,
"local" => DiscoveryMethods::Local,
"remote" => DiscoveryMethods::Remote,
"relay" => DiscoveryMethods::Relay,
n => {
warn!("Unrecognised discovery method: {}. Using Local", n);
DiscoveryMethods::Local
}
};
Ok(AddressOrUid::Uid(host.clone(), method))
}
}
}
@@ -43,8 +59,8 @@ impl AddressOrUid {
AddressOrUid::Address(host) => {
Ok(BcCamera::new_with_addr(host, channel_id, username, passwd).await?)
}
AddressOrUid::Uid(host) => {
Ok(BcCamera::new_with_uid(host, channel_id, username, passwd).await?)
AddressOrUid::Uid(host, method) => {
Ok(BcCamera::new_with_uid(host, channel_id, username, passwd, *method).await?)
}
}
}
@@ -56,8 +72,12 @@ pub(crate) async fn find_and_connect(config: &Config, name: &str) -> Result<BcCa
}
pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result<BcCamera> {
let camera_addr =
AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap();
let camera_addr = AddressOrUid::new(
&camera_config.camera_addr,
&camera_config.camera_uid,
&camera_config.discovery,
)
.unwrap();
info!(
"{}: Connecting to camera at {}",
camera_config.name, camera_addr