From 2ae25a1e580230024dad3026408e87bb75e81c96 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 9 Apr 2023 16:42:37 +0700 Subject: [PATCH] Refractor pause state model --- Cargo.lock | 8 +- crates/core/src/bc_protocol.rs | 7 + .../core/src/bc_protocol/connection/bcconn.rs | 27 +- crates/core/src/bc_protocol/errors.rs | 10 + crates/core/src/bc_protocol/motion.rs | 89 +++++- src/rtsp/gst.rs | 1 - src/rtsp/gst/server.rs | 44 ++- src/rtsp/mod.rs | 190 ++++++------- src/rtsp/states/camera.rs | 21 ++ src/rtsp/states/connected.rs | 32 ++- src/rtsp/states/disconnected.rs | 51 ++++ src/rtsp/states/loggedin.rs | 91 +++++- src/rtsp/states/mod.rs | 261 +----------------- src/rtsp/states/shared.rs | 119 ++++++-- src/rtsp/states/streaming.rs | 101 +++---- 15 files changed, 564 insertions(+), 488 deletions(-) create mode 100644 src/rtsp/states/camera.rs create mode 100644 src/rtsp/states/disconnected.rs diff --git a/Cargo.lock b/Cargo.lock index adeca6b..4b83507 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1483,18 +1483,18 @@ checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" [[package]] name = "proc-macro2" -version = "1.0.50" +version = "1.0.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef7d57beacfaf2d8aee5937dab7b7f28de3cb8b1828479bb5de2a7106f2bae2" +checksum = "2b63bdb0cd06f1f4dedf69b254734f9b45af66e4a031e42a7480257d9898b435" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.23" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b" +checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" dependencies = [ "proc-macro2", ] diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index c56d8bd..41fd5d8 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -390,6 +390,13 @@ impl BcCamera { }), } } + + /// Wait for all thread to finish + /// + /// If an error is returned in any thread it will return the first error + pub async fn join(&self) -> Result<()> { + self.connection.join().await + } } /// The Baichuan library has a very peculiar behavior where it always zeros the last byte. I diff --git a/crates/core/src/bc_protocol/connection/bcconn.rs b/crates/core/src/bc_protocol/connection/bcconn.rs index 330010a..10fc550 100644 --- a/crates/core/src/bc_protocol/connection/bcconn.rs +++ b/crates/core/src/bc_protocol/connection/bcconn.rs @@ -32,7 +32,7 @@ pub struct BcConnection { sink: Arc>, subscribers: Arc, #[allow(dead_code)] // Not dead we just need to hold a reference to keep it alive - rx_thread: JoinSet<()>, + rx_thread: RwLock>>, } impl BcConnection { @@ -52,17 +52,14 @@ impl BcConnection { None => continue, }; - if let Err(e) = Self::poll(bc, &subs, &sink_thread).await { - error!("Subscription error: {:?}", e); - break; - } + Self::poll(bc, &subs, &sink_thread).await? } }); Ok(BcConnection { sink, subscribers, - rx_thread, + rx_thread: RwLock::new(rx_thread), }) } @@ -183,4 +180,22 @@ impl BcConnection { Ok(()) } + + pub(crate) async fn join(&self) -> Result<()> { + let mut locked_threads = self.rx_thread.write().await; + while let Some(res) = locked_threads.join_next().await { + match res { + Err(e) => { + locked_threads.abort_all(); + return Err(e.into()); + } + Ok(Err(e)) => { + locked_threads.abort_all(); + return Err(e); + } + Ok(Ok(())) => {} + } + } + Ok(()) + } } diff --git a/crates/core/src/bc_protocol/errors.rs b/crates/core/src/bc_protocol/errors.rs index e616821..bb1e530 100644 --- a/crates/core/src/bc_protocol/errors.rs +++ b/crates/core/src/bc_protocol/errors.rs @@ -159,6 +159,10 @@ pub enum Error { actual: String, }, + /// Raised when a thread panics + #[error(display = "Thread panicked")] + JoinError(#[error(source)] std::sync::Arc), + /// A generic catch all error #[error(display = "Other error: {}", _0)] Other(&'static str), @@ -186,6 +190,12 @@ impl From for Error { } } +impl From for Error { + fn from(k: tokio::task::JoinError) -> Self { + Error::JoinError(std::sync::Arc::new(k)) + } +} + impl From for Error { fn from(k: tokio::time::error::Elapsed) -> Self { Error::Timeout(std::sync::Arc::new(k)) diff --git a/crates/core/src/bc_protocol/motion.rs b/crates/core/src/bc_protocol/motion.rs index 9884bc0..fa57fdf 100644 --- a/crates/core/src/bc_protocol/motion.rs +++ b/crates/core/src/bc_protocol/motion.rs @@ -45,7 +45,7 @@ impl MotionData { pub fn motion_detected_within(&mut self, duration: Duration) -> Result> { self.consume_motion_events()?; Ok(match &self.last_update { - MotionStatus::Start(time) => Some((Instant::now() - *time) < duration), + MotionStatus::Start(_) => Some(true), MotionStatus::Stop(time) => Some((Instant::now() - *time) < duration), MotionStatus::NoChange(_) => None, }) @@ -68,6 +68,93 @@ impl MotionData { } Ok(results) } + + /// Await a new motion event + /// + /// + pub async fn next_motion(&mut self) -> Result { + let motions = self.consume_motion_events()?; + if let Some(last) = motions.last() { + Ok(*last) + } else if let Some(moition) = self.rx.recv().await { + self.last_update = moition; + Ok(moition) + } else { + Err(Error::Other("Motion dropped")) + } + } + + /// Wait for the motion to stop + /// + /// It must be stopped for at least the given duration + pub async fn await_stop(&mut self, duration: Duration) -> Result<()> { + let motions = self.consume_motion_events()?; + let mut last_motion = motions.last().copied(); + loop { + if let Some(MotionStatus::Stop(time)) = last_motion { + // In stop state + if duration.is_zero() || (Instant::now() - time) > duration { + return Ok(()); + } else { + // Schedule a sleep or wait for motion to start + let result = tokio::select! { + _ = tokio::time::sleep(duration - (Instant::now() - time)) => {None}, + v = async { + loop { + match self.next_motion().await { + n @ Ok(MotionStatus::Start(_)) => {return n;}, + n @ Err(_) => {return n;}, + _ => {continue;} + } + } + } => {Some(v)} + }; + if let Some(v) = result { + v?; + } else { + return Ok(()); + } + } + } + last_motion = Some(self.next_motion().await?); + } + } + + /// Wait for the motion to start + /// + /// The motion must have a minimum duration as given + pub async fn await_start(&mut self, duration: Duration) -> Result<()> { + let motions = self.consume_motion_events()?; + let mut last_motion = motions.last().copied(); + loop { + if let Some(MotionStatus::Start(time)) = last_motion { + // In start state + if duration.is_zero() || (Instant::now() - time) > duration { + return Ok(()); + } else { + // Schedule a sleep or wait for motion to stop + let result = tokio::select! { + _ = tokio::time::sleep(duration - (Instant::now() - time)) => {None}, + v = async { + loop { + match self.next_motion().await { + n @ Ok(MotionStatus::Stop(_)) => {return n;}, + n @ Err(_) => {return n;}, + _ => {continue;} + } + } + } => {Some(v)} + }; + if let Some(v) = result { + v?; + } else { + return Ok(()); + } + } + } + last_motion = Some(self.next_motion().await?); + } + } } impl Drop for MotionData { diff --git a/src/rtsp/gst.rs b/src/rtsp/gst.rs index 042275a..f323e38 100644 --- a/src/rtsp/gst.rs +++ b/src/rtsp/gst.rs @@ -9,6 +9,5 @@ mod shared; use factory::*; pub(crate) use self::server::NeoRtspServer; -pub(crate) use gstreamer_rtsp_server::gio::TlsAuthenticationMode; type AnyResult = std::result::Result; diff --git a/src/rtsp/gst/server.rs b/src/rtsp/gst/server.rs index 82634e8..2580727 100644 --- a/src/rtsp/gst/server.rs +++ b/src/rtsp/gst/server.rs @@ -4,6 +4,8 @@ //! expect issues use super::{factory::*, AnyResult}; +use crate::config::*; + use anyhow::{anyhow, Context}; use gstreamer::glib::object_subclass; use gstreamer::glib::subclass::types::ObjectSubclass; @@ -45,17 +47,6 @@ impl NeoRtspServer { self.imp().get_sender(tag).await } - pub(crate) fn set_credentials(&self, credentials: &[(&str, &str)]) -> AnyResult<()> { - self.imp().set_credentials(credentials) - } - pub(crate) fn set_tls( - &self, - cert_file: &str, - client_auth: TlsAuthenticationMode, - ) -> AnyResult<()> { - self.imp().set_tls(cert_file, client_auth) - } - pub(crate) async fn create_stream>(&self, tag: U) -> AnyResult<()> { self.imp().create_stream(tag).await } @@ -101,6 +92,14 @@ impl NeoRtspServer { #[allow(clippy::unit_arg)] tokio::task::spawn_blocking(move || Ok(main_loop.run())).await? } + + pub(crate) fn set_up_tls(&self, config: &Config) { + self.imp().set_up_tls(config) + } + + pub(crate) fn set_up_users(&self, users: &[UserConfig]) { + self.imp().set_up_users(users) + } } unsafe impl Send for NeoRtspServer {} @@ -269,4 +268,27 @@ impl NeoRtspServerImpl { self.obj().set_auth(Some(&auth)); Ok(()) } + + pub(crate) fn set_up_tls(&self, config: &Config) { + let tls_client_auth = match &config.tls_client_auth as &str { + "request" => TlsAuthenticationMode::Requested, + "require" => TlsAuthenticationMode::Required, + "none" => TlsAuthenticationMode::None, + _ => unreachable!(), + }; + if let Some(cert_path) = &config.certificate { + self.set_tls(cert_path, tls_client_auth) + .expect("Failed to set up TLS"); + } + } + + pub(crate) fn set_up_users(&self, users: &[UserConfig]) { + // Setting up users + let credentials: Vec<_> = users + .iter() + .map(|user| (&*user.name, &*user.pass)) + .collect(); + self.set_credentials(&credentials) + .expect("Failed to set up users"); + } } diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs index 8c274ba..f51ee01 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -53,7 +53,6 @@ // - `"none"`: Resends the last iframe the camera. This does not reencode at all. **Most use cases should use this one as it has the least effort on the cpu and gives what you would expect** // use anyhow::{anyhow, Context, Result}; -use crossbeam::utils::Backoff; use log::*; use std::sync::Arc; use std::time::Duration; @@ -62,11 +61,10 @@ mod cmdline; mod gst; mod states; -use states::{RtspCamera, StateInfo}; - -use super::config::{CameraConfig, Config, UserConfig}; +use super::config::Config; pub(crate) use cmdline::Opt; -use gst::{NeoRtspServer, TlsAuthenticationMode}; +use gst::NeoRtspServer; +use states::*; /// Entry point for the rtsp subcommand /// @@ -74,40 +72,39 @@ use gst::{NeoRtspServer, TlsAuthenticationMode}; pub(crate) async fn main(_opt: Opt, mut config: Config) -> Result<()> { let rtsp = Arc::new(NeoRtspServer::new()?); - set_up_tls(&config, &rtsp); + rtsp.set_up_tls(&config); - set_up_users(&config.users, &rtsp); + rtsp.set_up_users(&config.users); if config.certificate.is_none() && !config.users.is_empty() { warn!( "Without a server certificate, usernames and passwords will be exchanged in plaintext!" ) } - let mut set = tokio::task::JoinSet::new(); - - let arc_user_config = Arc::new(config.users); + let mut cameras = vec![]; for camera_config in config.cameras.drain(..) { + cameras + .push(Camera::::new(camera_config, &config.users, rtsp.clone()).await?); + } + + let mut set = tokio::task::JoinSet::new(); + for camera in cameras.drain(..) { // Spawn each camera controller in it's own thread - let user_config = arc_user_config.clone(); - let arc_rtsp = rtsp.clone(); - set.spawn(async move { - let backoff = Backoff::new(); - + let name = camera.get_name(); loop { - let failure = - camera_main(&camera_config, user_config.as_slice(), arc_rtsp.clone()).await; + let failure = camera_main(camera).await; match failure { Err(CameraFailureKind::Fatal(e)) => { - error!("{}: Fatal error: {:?}", camera_config.name, e); + error!("{}: Fatal error: {:?}", name, e); return Err(e); } Err(CameraFailureKind::Retry(e)) => { - warn!("{}: Retryable error: {:X?}", camera_config.name, e); - backoff.spin(); + warn!("{}: Retryable error: {:X?}", name, e); + todo!(); // Do backoff } Ok(()) => { - info!("{}: Shutting down", camera_config.name); + info!("{}: Shutting down", name); break; } } @@ -136,110 +133,83 @@ enum CameraFailureKind { Retry(anyhow::Error), } -async fn camera_main( - config: &CameraConfig, - user_config: &[UserConfig], - rtsp: Arc, -) -> Result<(), CameraFailureKind> { +async fn camera_main(camera: Camera) -> Result<(), CameraFailureKind> { // Connect - let mut camera = RtspCamera::new(config, user_config, rtsp) + let name = camera.get_name(); + let connected = camera + .connect() .await - .with_context(|| format!("{}: Could not connect camera", config.name)) + .with_context(|| format!("{}: Could not connect to camera", name)) .map_err(CameraFailureKind::Retry)?; - camera + + let loggedin = connected .login() .await - .with_context(|| format!("{}: Could not login to camera", config.name)) + .with_context(|| format!("{}: Could not login to camera", name)) .map_err(CameraFailureKind::Fatal)?; - let _ = camera.manage().await; + let _ = loggedin.manage().await; - camera + let mut streaming = loggedin .stream() .await - .with_context(|| format!("{}: Could not start stream", config.name)) + .with_context(|| format!("{}: Could not start stream", name)) .map_err(CameraFailureKind::Retry)?; - let backoff = Backoff::new(); - let mut motion = if config.pause.on_motion { - Some( - camera - .motion_data() - .await - .with_context(|| { - "Could not initialise motion detection. Is it supported with this camera?" - }) - .map_err(CameraFailureKind::Retry)?, - ) - } else { - None - }; + tokio::time::sleep(Duration::from_secs(2)).await; // Wait for a few seconds of video before we allow pausing - let motion_timeout: Duration = Duration::from_secs_f64(config.pause.motion_timeout); loop { - match camera.get_state() { - StateInfo::Streaming => { - if config.pause.on_disconnect { - if let Some(false) = camera.client_connected().await { - info!("Pause on disconnect"); - camera.login().await.map_err(CameraFailureKind::Retry)?; - } - } - if config.pause.on_motion { - if let Some(motion) = motion.as_mut() { - match motion - .motion_detected_within(motion_timeout) - .with_context(|| "Motion detection unexpectedly stopped") - .map_err(CameraFailureKind::Retry)? - { - Some(false) => { - info!("Pause on motion"); - camera.login().await.map_err(CameraFailureKind::Retry)?; - } - None => { - info!("Pause on motion (start)"); - camera.login().await.map_err(CameraFailureKind::Retry)?; - } - _ => {} - } - } - } - if let Err(e) = camera.is_running().await { - return Err(CameraFailureKind::Retry(anyhow!( - "Camera has unexpectanely stopped the streaming state: {:?}", - e - ))); - } - } - _ => { - return Err(CameraFailureKind::Retry(anyhow!( - "Camera has unexpectanely stopped the paused state" - ))); + // Wait for error or reason to pause + tokio::select! { + v = async { + // Wait for error + streaming.join().await + } => v, + v = async { + // Wait for motion stop + let mut motion = streaming.get_camera().listen_on_motion().await?; + motion.await_stop(Duration::from_secs_f64(streaming.get_config().pause.motion_timeout)).await + }, if streaming.get_config().pause.on_motion => { + v.map_err(|e| anyhow!("Error while processing motion messages: {:?}", e)) + }, + v = async { + // Wait for client to disconnect + todo!() + }, if streaming.get_config().pause.on_disconnect => v, + }.with_context(|| format!("{}: Error while streaming", name)) + .map_err(CameraFailureKind::Retry)?; + + let paused = streaming + .stop() + .await + .with_context(|| format!("{}: Could not stop stream", name)) + .map_err(CameraFailureKind::Retry)?; + // Wait for reason to restart + tokio::select! { + v = async { + // Wait for motion start + let mut motion = paused.get_camera().listen_on_motion().await?; + motion.await_start(Duration::ZERO).await + }, if paused.get_config().pause.on_motion => { + v.map_err(|e| anyhow!("Error while processing motion messages: {:?}", e)) + }, + v = async { + // Wait for client to connect + todo!() + }, if paused.get_config().pause.on_disconnect => v, + else => { + // No pause. This means that the stream stopped for some reason + // but not because of an error + Ok(()) } } - backoff.spin(); + .with_context(|| format!("{}: Error while paused", name)) + .map_err(CameraFailureKind::Retry)?; + + streaming = paused + .stream() + .await + .with_context(|| format!("{}: Could not start stream", name)) + .map_err(CameraFailureKind::Retry)?; } } - -fn set_up_tls(config: &Config, rtsp: &NeoRtspServer) { - let tls_client_auth = match &config.tls_client_auth as &str { - "request" => TlsAuthenticationMode::Requested, - "require" => TlsAuthenticationMode::Required, - "none" => TlsAuthenticationMode::None, - _ => unreachable!(), - }; - if let Some(cert_path) = &config.certificate { - rtsp.set_tls(cert_path, tls_client_auth) - .expect("Failed to set up TLS"); - } -} - -fn set_up_users(users: &[UserConfig], rtsp: &NeoRtspServer) { - // Setting up users - let credentials: Vec<_> = users - .iter() - .map(|user| (&*user.name, &*user.pass)) - .collect(); - rtsp.set_credentials(&credentials) - .expect("Failed to set up users"); -} diff --git a/src/rtsp/states/camera.rs b/src/rtsp/states/camera.rs new file mode 100644 index 0000000..13c1108 --- /dev/null +++ b/src/rtsp/states/camera.rs @@ -0,0 +1,21 @@ +//! Generic state +//! +//! This is the base state +use super::shared::Shared; +use crate::config::CameraConfig; +use std::sync::Arc; + +pub(crate) struct Camera { + pub(crate) state: T, + pub(crate) shared: Arc, +} + +impl Camera { + pub(crate) fn get_name(&self) -> String { + self.shared.config.name.clone() + } + + pub(crate) fn get_config(&self) -> &CameraConfig { + &self.shared.config + } +} diff --git a/src/rtsp/states/connected.rs b/src/rtsp/states/connected.rs index 6d24097..e1736bd 100644 --- a/src/rtsp/states/connected.rs +++ b/src/rtsp/states/connected.rs @@ -2,19 +2,29 @@ // // This state has formed the TCP/UDP tunnel // but has not logged in -use super::{CameraState, Shared}; -use anyhow::{Error, Result}; -use async_trait::async_trait; +use super::{camera::Camera, disconnected::Disconnected, loggedin::LoggedIn}; +use anyhow::Result; -#[derive(Default)] -pub(crate) struct Connected {} +use neolink_core::bc_protocol::BcCamera; -#[async_trait] -impl CameraState for Connected { - async fn setup(&mut self, _shared: &Shared) -> Result<(), Error> { - Ok(()) +pub(crate) struct Connected { + pub(crate) camera: BcCamera, +} + +impl Camera { + pub(crate) async fn disconnect(self) -> Result> { + Ok(Camera { + shared: self.shared, + state: Disconnected {}, + }) } - async fn tear_down(&mut self, _shared: &Shared) -> Result<(), Error> { - Ok(()) + + pub(crate) async fn login(self) -> Result> { + Ok(Camera { + shared: self.shared, + state: LoggedIn { + camera: self.state.camera, + }, + }) } } diff --git a/src/rtsp/states/disconnected.rs b/src/rtsp/states/disconnected.rs new file mode 100644 index 0000000..8a1dd8e --- /dev/null +++ b/src/rtsp/states/disconnected.rs @@ -0,0 +1,51 @@ +//! Data for the basic disconnected state +//! +//! This state has NOT formed the TCP/UDP tunnel +//! it has all the data required to connect but +//! has not estabilished the connection +//! +//! This is meant to be used to conserve battery +//! by completely disconnecting +use super::Shared; +use super::{camera::Camera, connected::Connected}; +use crate::config::{CameraConfig, UserConfig}; +use crate::rtsp::gst::NeoRtspServer; +use anyhow::{Context, Result}; +use std::sync::Arc; + +#[derive(Default)] +pub(crate) struct Disconnected {} + +impl Camera { + pub(crate) async fn new( + config: CameraConfig, + users: &[UserConfig], + rtsp: Arc, + ) -> Result> { + Ok(Camera { + state: Disconnected {}, + shared: Arc::new(Shared::new(config, users, rtsp).await?), + }) + } + + pub(crate) async fn connect(self) -> Result> { + let camera = { + let camera_config = &self.shared.config; + self.shared + .addr + .connect_camera(camera_config) + .await + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, self.shared.addr, camera_config.channel_id + ) + }) + }?; + + Ok(Camera { + shared: self.shared, + state: Connected { camera }, + }) + } +} diff --git a/src/rtsp/states/loggedin.rs b/src/rtsp/states/loggedin.rs index eb84f2c..9e12ef1 100644 --- a/src/rtsp/states/loggedin.rs +++ b/src/rtsp/states/loggedin.rs @@ -5,25 +5,88 @@ // // It can be used to alter settings etc -use super::{CameraState, Shared}; +use super::{camera::Camera, connected::Connected, streaming::Streaming}; use anyhow::Result; -use async_trait::async_trait; +use log::*; +use neolink_core::bc_protocol::BcCamera; -#[derive(Default)] -pub(crate) struct LoggedIn {} +pub(crate) struct LoggedIn { + pub(crate) camera: BcCamera, +} + +impl Camera { + pub(crate) async fn logout(self) -> Result> { + self.state.camera.logout().await?; + Ok(Camera { + shared: self.shared, + state: Connected { + camera: self.state.camera, + }, + }) + } + + pub(crate) async fn stream(self) -> Result> { + Camera::::from_login(self).await + } + + pub(crate) async fn manage(&self) -> Result<()> { + let cam_time = self.state.camera.get_time().await?; + if let Some(time) = cam_time { + info!( + "{}: Camera time is already set: {}", + self.shared.config.name, time + ); + } else { + use time::OffsetDateTime; + // We'd like now_local() but it's deprecated - try to get the local time, but if no + // time zone, fall back to UTC. + let new_time = + OffsetDateTime::try_now_local().unwrap_or_else(|_| OffsetDateTime::now_utc()); + + warn!( + "{}: Camera has no time set, setting to {}", + self.shared.config.name, new_time + ); + match self.state.camera.set_time(new_time).await { + Ok(_) => { + let cam_time = self.state.camera.get_time().await?; + if let Some(time) = cam_time { + info!( + "{}: Camera time is now set: {}", + self.shared.config.name, time + ); + } + } + Err(e) => { + error!( + "{}: Camera did not accept new time (is {} an admin?): Error: {:?}", + self.shared.config.name, self.shared.config.username, e + ); + } + } + } + + use neolink_core::bc::xml::VersionInfo; + if let Ok(VersionInfo { + firmwareVersion: firmware_version, + .. + }) = self.state.camera.version().await + { + info!( + "{}: Camera reports firmware version {}", + self.shared.config.name, firmware_version + ); + } else { + info!( + "{}: Could not fetch version information", + self.shared.config.name + ); + } -#[async_trait] -impl CameraState for LoggedIn { - async fn setup(&mut self, shared: &Shared) -> Result<(), anyhow::Error> { - shared - .camera - .login_with_maxenc(shared.max_encryption) - .await?; Ok(()) } - async fn tear_down(&mut self, shared: &Shared) -> Result<(), anyhow::Error> { - shared.camera.logout().await?; - Ok(()) + pub(crate) fn get_camera(&self) -> &BcCamera { + &self.state.camera } } diff --git a/src/rtsp/states/mod.rs b/src/rtsp/states/mod.rs index 01c47f2..cb6847e 100644 --- a/src/rtsp/states/mod.rs +++ b/src/rtsp/states/mod.rs @@ -1,264 +1,13 @@ //! Handles the camera in it's different states //! -use anyhow::{anyhow, Context, Error, Result}; -use log::*; -use std::collections::HashSet; -use std::sync::Arc; - -use neolink_core::bc_protocol::{MaxEncryption, MotionData, StreamKind as Stream}; - -use crate::config::{CameraConfig, UserConfig}; -use crate::rtsp::gst::NeoRtspServer; -use crate::utils::AddressOrUid; - +mod camera; mod connected; +mod disconnected; mod loggedin; mod shared; mod streaming; -pub(crate) use connected::Connected; -pub(crate) use loggedin::LoggedIn; -pub(crate) use shared::{CameraState, Shared}; -pub(crate) use streaming::Streaming; - -pub(crate) enum StateInfo { - Connected, - LoggedIn, - Streaming, -} - -enum State { - Connected(Connected), - LoggedIn(LoggedIn), - Streaming(Streaming), -} - -/// -/// The state machine representation of the camera -/// -pub(crate) struct RtspCamera { - shared: Shared, - state: State, -} - -impl RtspCamera { - pub(crate) async fn new( - config: &CameraConfig, - users: &[UserConfig], - rtsp: Arc, - ) -> Result { - let camera_addr = - 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.connect_camera(config).await.with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - config.name, camera_addr, config.channel_id - ) - })?; - - let mut streams: HashSet = Default::default(); - if ["all", "both", "mainStream", "mainstream"] - .iter() - .any(|&e| e == config.stream) - { - streams.insert(Stream::Main); - } - if ["all", "both", "subStream", "substream"] - .iter() - .any(|&e| e == config.stream) - { - streams.insert(Stream::Sub); - } - if ["all", "externStream", "externstream"] - .iter() - .any(|&e| e == config.stream) - { - streams.insert(Stream::Extern); - } - - // Used to build the list of strings to pass to gtreamer for the allowed users - let all_users_hash = || users.iter().map(|u| u.name.clone()).collect(); - let permitted_users: HashSet = match &config.permitted_users { - // If in the camera config there is the user "anyone", or if none is specified but users - // are defined at all, then we add all users to the camera's allowed list. - Some(p) if p.iter().any(|u| u == "anyone") => all_users_hash(), - None if !users.is_empty() => all_users_hash(), - - // The user specified permitted_users - Some(p) => p.iter().cloned().collect(), - - // The user didn't specify permitted_users, and there are none defined anyway - None => ["anonymous".to_string()].iter().cloned().collect(), - }; - - let max_encryption = match config.max_encryption.to_lowercase().as_str() { - "none" => MaxEncryption::None, - "bcencrypt" => MaxEncryption::BcEncrypt, - "aes" => MaxEncryption::Aes, - _ => MaxEncryption::Aes, - }; - - let shared = Shared { - camera: Arc::new(camera), - addr: camera_addr, - name: config.name.clone(), - channel: config.channel_id, - username: config.username.clone(), - password: config.password.clone(), - pause: config.pause.clone(), - streams, - rtsp, - permitted_users, - max_encryption, - strict: config.strict, - }; - - // Set up streams on the RTSP camera - for stream in shared.streams.iter() { - let tag = shared.get_tag_for_stream(stream); - shared.rtsp.create_stream(&tag).await?; - shared - .rtsp - .add_permitted_roles(&tag, &shared.permitted_users) - .await?; - let paths: Vec = shared.get_paths_for_stream(stream); - debug!("Adding path {:?} for {}", paths, tag); - shared.rtsp.add_path(&tag, &paths).await?; - } - - let mut state: Connected = Default::default(); - state.setup(&shared).await?; - - Ok(Self { - shared, - state: State::Connected(state), - }) - } - - pub(crate) fn get_state(&self) -> StateInfo { - match &self.state { - State::Connected(_) => StateInfo::Connected, - State::LoggedIn(_) => StateInfo::LoggedIn, - State::Streaming(_) => StateInfo::Streaming, - } - } - pub(crate) async fn login(&mut self) -> Result<()> { - match &mut self.state { - State::Connected(ref mut connected) => { - info!("{}: Logging in", &self.shared.name); - connected.tear_down(&self.shared).await?; - let mut state: LoggedIn = Default::default(); - state.setup(&self.shared).await?; - self.state = State::LoggedIn(state); - info!("{}: Successfully logged in", &self.shared.name); - } - State::Streaming(ref mut connected) => { - info!("{}: Logging in", &self.shared.name); - connected.tear_down(&self.shared).await?; - let state: LoggedIn = Default::default(); - // state.setup(&self.shared).await?; - self.state = State::LoggedIn(state); - info!("{}: Successfully stopped straming", &self.shared.name); - } - State::LoggedIn(_) => { - info!("Already logged in"); - } - } - Ok(()) - } - - pub(crate) async fn stream(&mut self) -> Result<()> { - match &mut self.state { - State::Connected(_) => { - return Err(anyhow!("{}: Must login first", &self.shared.name)); - } - State::Streaming(_) => { - info!("{}: Already streaming", &self.shared.name); - } - State::LoggedIn(ref mut _loggedin) => { - info!("{}: Starting stream", &self.shared.name); - // loggedin.tear_down(&self.shared).await?; - let mut state: Streaming = Default::default(); - state.setup(&self.shared).await?; - self.state = State::Streaming(state); - info!("{}: Successfully started streaming", &self.shared.name); - } - } - Ok(()) - } - - pub(crate) async fn client_connected(&self) -> Option { - todo!() - } - - pub(crate) async fn motion_data(&self) -> Result { - self.shared - .camera - .listen_on_motion() - .await - .with_context(|| "Cannot get motion data") - } - - pub(crate) async fn is_running(&mut self) -> Result<()> { - match &mut self.state { - State::Streaming(state) => state.is_running().await, - _ => Ok(()), - } - } - - pub(crate) async fn manage(&self) -> Result<()> { - if let State::Connected(_) = self.state { - return Err(anyhow!("Cannot manage a camera that is not logged in")); - } - let cam_time = self.shared.camera.get_time().await?; - if let Some(time) = cam_time { - info!("{}: Camera time is already set: {}", self.shared.name, time); - } else { - use time::OffsetDateTime; - // We'd like now_local() but it's deprecated - try to get the local time, but if no - // time zone, fall back to UTC. - let new_time = - OffsetDateTime::try_now_local().unwrap_or_else(|_| OffsetDateTime::now_utc()); - - warn!( - "{}: Camera has no time set, setting to {}", - self.shared.name, new_time - ); - self.shared.camera.set_time(new_time).await?; - let cam_time = self.shared.camera.get_time().await?; - if let Some(time) = cam_time { - info!("{}: Camera time is now set: {}", self.shared.name, time); - } else { - error!( - "{}: Camera did not accept new time (is {} an admin?)", - self.shared.name, self.shared.username - ); - } - } - - use neolink_core::bc::xml::VersionInfo; - if let Ok(VersionInfo { - firmwareVersion: firmware_version, - .. - }) = self.shared.camera.version().await - { - info!( - "{}: Camera reports firmware version {}", - self.shared.name, firmware_version - ); - } else { - info!("{}: Could not fetch version information", self.shared.name); - } - - Ok(()) - } -} +pub(crate) use self::{ + camera::*, disconnected::*, loggedin::*, shared::*, +}; diff --git a/src/rtsp/states/shared.rs b/src/rtsp/states/shared.rs index ed1e545..e1abbea 100644 --- a/src/rtsp/states/shared.rs +++ b/src/rtsp/states/shared.rs @@ -2,73 +2,144 @@ //! Shared data between all states //! //! -use anyhow::{Error, Result}; +use anyhow::{Context, Error, Result}; use async_trait::async_trait; use std::collections::HashSet; use std::sync::Arc; +use log::*; -use neolink_core::bc_protocol::{BcCamera, MaxEncryption, StreamKind as Stream}; +use neolink_core::bc_protocol::{StreamKind as Stream}; -use crate::config::PauseConfig; +use crate::config::{CameraConfig, UserConfig}; use crate::rtsp::gst::NeoRtspServer; use crate::utils::AddressOrUid; #[allow(dead_code)] pub(crate) struct Shared { - pub(super) camera: Arc, - pub(super) name: String, - pub(super) channel: u8, pub(super) addr: AddressOrUid, - pub(super) username: String, - pub(super) password: Option, pub(super) streams: HashSet, pub(super) rtsp: Arc, pub(super) permitted_users: HashSet, - pub(super) pause: PauseConfig, - pub(super) max_encryption: MaxEncryption, - pub(super) strict: bool, + pub(super) config: CameraConfig, } impl Shared { + pub(crate) async fn new( + config: CameraConfig, + users: &[UserConfig], + rtsp: Arc, + ) -> Result { + let addr = 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 + ) + })?; + + let mut streams: HashSet = Default::default(); + if ["all", "both", "mainStream", "mainstream"] + .iter() + .any(|&e| e == config.stream) + { + streams.insert(Stream::Main); + } + if ["all", "both", "subStream", "substream"] + .iter() + .any(|&e| e == config.stream) + { + streams.insert(Stream::Sub); + } + if ["all", "externStream", "externstream"] + .iter() + .any(|&e| e == config.stream) + { + streams.insert(Stream::Extern); + } + + let all_users_hash = || users.iter().map(|u| u.name.clone()).collect(); + let permitted_users: HashSet = match &config.permitted_users { + // If in the camera config there is the user "anyone", or if none is specified but users + // are defined at all, then we add all users to the camera's allowed list. + Some(p) if p.iter().any(|u| u == "anyone") => all_users_hash(), + None if !users.is_empty() => all_users_hash(), + + // The user specified permitted_users + Some(p) => p.iter().cloned().collect(), + + // The user didn't specify permitted_users, and there are none defined anyway + None => ["anonymous".to_string()].iter().cloned().collect(), + }; + + let me = Shared { + addr, + streams, + rtsp, + permitted_users, + config, + }; + me.setup_streams().await?; + Ok(me) + } + + // Set up streams on the RTSP camera + pub(crate) async fn setup_streams(&self) -> Result<()> { + for stream in self.streams.iter() { + let tag = self.get_tag_for_stream(stream); + self.rtsp.create_stream(&tag).await?; + self.rtsp + .add_permitted_roles(&tag, &self.permitted_users) + .await?; + let paths: Vec = self.get_paths_for_stream(stream); + debug!("Adding path {:?} for {}", paths, tag); + self.rtsp.add_path(&tag, &paths).await?; + } + Ok(()) + } + pub(crate) fn get_tag_for_stream(&self, stream: &Stream) -> String { - format!("{}::{:?}", self.name, stream) + format!("{}::{:?}", self.config.name, stream) } pub(crate) fn get_paths_for_stream(&self, stream: &Stream) -> Vec { vec![ // Normal case - format!("/{}/{:?}", self.name, stream), - format!("/{}/{:?}Stream", self.name, stream), - format!("/{}/{:?}stream", self.name, stream), + format!("/{}/{:?}", self.config.name, stream), + format!("/{}/{:?}Stream", self.config.name, stream), + format!("/{}/{:?}stream", self.config.name, stream), // Lower case name - format!("/{}/{:?}", self.name.to_lowercase(), stream), - format!("/{}/{:?}Stream", self.name.to_lowercase(), stream), - format!("/{}/{:?}stream", self.name.to_lowercase(), stream), + format!("/{}/{:?}", self.config.name.to_lowercase(), stream), + format!("/{}/{:?}Stream", self.config.name.to_lowercase(), stream), + format!("/{}/{:?}stream", self.config.name.to_lowercase(), stream), // Lower case stream - format!("/{}/{}", self.name, format!("{:?}", stream).to_lowercase()), + format!( + "/{}/{}", + self.config.name, + format!("{:?}", stream).to_lowercase() + ), format!( "/{}/{}Stream", - self.name, + self.config.name, format!("{:?}", stream).to_lowercase() ), format!( "/{}/{}stream", - self.name, + self.config.name, format!("{:?}", stream).to_lowercase() ), // Lower case both format!( "/{}/{}", - self.name.to_lowercase(), + self.config.name.to_lowercase(), format!("{:?}", stream).to_lowercase() ), format!( "/{}/{}Stream", - self.name.to_lowercase(), + self.config.name.to_lowercase(), format!("{:?}", stream).to_lowercase() ), format!( "/{}/{}stream", - self.name.to_lowercase(), + self.config.name.to_lowercase(), format!("{:?}", stream).to_lowercase() ), ] diff --git a/src/rtsp/states/streaming.rs b/src/rtsp/states/streaming.rs index 6643656..f92c0d2 100644 --- a/src/rtsp/states/streaming.rs +++ b/src/rtsp/states/streaming.rs @@ -3,30 +3,32 @@ // Data is streamed into a gstreamer source use anyhow::{anyhow, Error, Result}; -use async_trait::async_trait; -use futures::future::FutureExt; use log::*; -use tokio::task::JoinSet; use tokio::time::{timeout, Duration}; +use tokio::{sync::RwLock, task::JoinSet}; -use neolink_core::{bc_protocol::StreamKind as Stream, bcmedia::model::BcMedia}; +use neolink_core::{ + bc_protocol::{BcCamera, StreamKind as Stream}, + bcmedia::model::BcMedia, +}; -use super::{CameraState, Shared}; +use super::{camera::Camera, LoggedIn}; -#[derive(Default)] pub(crate) struct Streaming { - set: JoinSet>, + pub(crate) camera: BcCamera, + set: RwLock>>, } -#[async_trait] -impl CameraState for Streaming { - async fn setup(&mut self, shared: &Shared) -> Result<(), Error> { +impl Camera { + pub(crate) async fn from_login(loggedin: Camera) -> Result, Error> { // Create new gst outputs // // Otherwise use those already present - for stream in shared.streams.iter() { - let tag = shared.get_tag_for_stream(stream); - let sender = shared + let mut set: JoinSet> = Default::default(); + for stream in loggedin.shared.streams.iter() { + let tag = loggedin.shared.get_tag_for_stream(stream); + let sender = loggedin + .shared .rtsp .get_sender(&tag) .await @@ -39,17 +41,18 @@ impl CameraState for Streaming { }; info!( "{}: Starting video stream {}", - &shared.name, stream_display_name + &loggedin.shared.config.name, stream_display_name ); - let thread_camera = shared.camera.clone(); let stream_thead = *stream; - let strict_thread = shared.strict; + let strict_thread = loggedin.shared.config.strict; let tag_thread = tag.clone(); - self.set.spawn(async move { - let mut stream_data = thread_camera - .start_video(stream_thead, 0, strict_thread) - .await?; + let mut stream_data = loggedin + .state + .camera + .start_video(stream_thead, 0, strict_thread) + .await?; + set.spawn(async move { loop { debug!("{}: BcMediaStreamRecv", &tag_thread); let data = timeout(Duration::from_secs(15), stream_data.get_data()).await??; @@ -67,46 +70,44 @@ impl CameraState for Streaming { }); } - Ok(()) + Ok(Camera { + shared: loggedin.shared, + state: Streaming { + camera: loggedin.state.camera, + set: RwLock::new(set), + }, + }) } - async fn tear_down(&mut self, _shared: &Shared) -> Result<(), Error> { - self.set.shutdown().await; - Ok(()) + pub(crate) async fn stop(self) -> Result> { + self.state.set.into_inner().abort_all(); + Ok(Camera { + shared: self.shared, + state: LoggedIn { + camera: self.state.camera, + }, + }) } -} -impl Drop for Streaming { - fn drop(&mut self) { - self.set.abort_all(); - } -} - -impl Streaming { - pub(crate) async fn is_running(&mut self) -> Result<()> { - if self.set.is_empty() { - return Err(anyhow!("Streaming has no active tasks")); - } - if let Some(res) = self.set.join_next().now_or_never() { + pub(crate) async fn join(&self) -> Result<()> { + let mut locked_threads = self.state.set.write().await; + while let Some(res) = locked_threads.join_next().await { match res { - None => { - return Err(anyhow!("Streaming has no active tasks")); + Err(e) => { + locked_threads.abort_all(); + return Err(e.into()); } - Some(Ok(Ok(()))) => { - unreachable!(); - } - Some(Ok(Err(e))) => { - // Error in tasks - self.set.abort_all(); + Ok(Err(e)) => { + locked_threads.abort_all(); return Err(e); } - Some(Err(e)) => { - // Panic in tasks - self.set.abort_all(); - return Err(anyhow!("Panic in streaming task: {:?}", e)); - } + Ok(Ok(())) => {} } } Ok(()) } + + pub(crate) fn get_camera(&self) -> &BcCamera { + &self.state.camera + } }