From d068eeefc72119175849b502e6e950b560ced658 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 27 Aug 2023 15:25:35 +0700 Subject: [PATCH] Breakout reactor code to modules --- src/battery/mod.rs | 2 +- src/common/camthread.rs | 144 ++++++++++ src/common/instance.rs | 130 +++++++++ src/common/mod.rs | 12 +- src/common/neocam.rs | 538 ++----------------------------------- src/common/reactor.rs | 156 +++++++++++ src/common/streamthread.rs | 127 +++++++++ src/image/mod.rs | 2 +- src/main.rs | 2 +- src/pir/mod.rs | 2 +- src/reboot/mod.rs | 2 +- src/statusled/mod.rs | 2 +- 12 files changed, 594 insertions(+), 525 deletions(-) create mode 100644 src/common/camthread.rs create mode 100644 src/common/instance.rs create mode 100644 src/common/reactor.rs create mode 100644 src/common/streamthread.rs diff --git a/src/battery/mod.rs b/src/battery/mod.rs index c2e08b1..e185d93 100644 --- a/src/battery/mod.rs +++ b/src/battery/mod.rs @@ -14,7 +14,7 @@ use anyhow::{Context, Result}; mod cmdline; -use crate::common::neocam::NeoReactor; +use crate::common::NeoReactor; use super::config::Config; pub(crate) use cmdline::Opt; diff --git a/src/common/camthread.rs b/src/common/camthread.rs new file mode 100644 index 0000000..5c0f763 --- /dev/null +++ b/src/common/camthread.rs @@ -0,0 +1,144 @@ +use std::sync::{Arc, Weak}; +use tokio::{ + sync::watch::{Receiver as WatchReceiver, Sender as WatchSender}, + time::{interval, sleep, Duration, Instant}, +}; +use tokio_util::sync::CancellationToken; + +use crate::{config::CameraConfig, utils::connect_and_login, Result}; +use neolink_core::bc_protocol::BcCamera; + +pub(crate) struct NeoCamThread { + config: WatchReceiver, + cancel: CancellationToken, + camera_watch: WatchSender>, +} + +impl NeoCamThread { + pub(crate) async fn new( + watch_config_rx: WatchReceiver, + camera_watch_tx: WatchSender>, + cancel: CancellationToken, + ) -> Self { + Self { + config: watch_config_rx, + cancel, + camera_watch: camera_watch_tx, + } + } + async fn run_camera(&mut self, config: &CameraConfig) -> Result<()> { + let camera = Arc::new(connect_and_login(config).await?); + + self.camera_watch.send_replace(Arc::downgrade(&camera)); + + let cancel_check = self.cancel.clone(); + // Now we wait for a disconnect + tokio::select! { + _ = cancel_check.cancelled() => { + Ok(()) + } + v = camera.join() => v, + v = async { + let mut interval = interval(Duration::from_secs(5)); + loop { + interval.tick().await; + match camera.get_linktype().await { + Ok(_) => continue, + Err(neolink_core::Error::UnintelligibleReply { .. }) => { + // Camera does not support pings just wait forever + futures::pending!(); + }, + Err(e) => return Err(e), + } + } + } => v, + }?; + + let _ = camera.logout().await; + let _ = camera.shutdown().await; + + Ok(()) + } + + // Will run and attempt to maintain the connection + // + // A watch sender is used to send the new camera + // whenever it changes + pub(crate) async fn run(&mut self) -> Result<()> { + const MAX_BACKOFF: Duration = Duration::from_secs(5); + const MIN_BACKOFF: Duration = Duration::from_millis(50); + + let mut backoff = MIN_BACKOFF; + + loop { + let mut config_rec = self.config.clone(); + + let config = config_rec.borrow_and_update().clone(); + let now = Instant::now(); + + let res = tokio::select! { + Ok(_) = config_rec.changed() => { + None + } + v = self.run_camera(&config) => { + Some(v) + } + }; + self.camera_watch.send_replace(Weak::new()); + + if res.is_none() { + // If None go back and reload NOW + // + // This occurs if there was a config change + continue; + } + + // Else we see if the result actually was + let result = res.unwrap(); + + if Instant::now() - now > Duration::from_secs(60) { + // Command ran long enough to be considered a success + backoff = MIN_BACKOFF; + } + if backoff > MAX_BACKOFF { + backoff = MAX_BACKOFF; + } + + match result { + Ok(()) => { + // Normal shutdown + log::debug!("Cancel:: NeoCamThread::NormalShutdown"); + self.cancel.cancel(); + return Ok(()); + } + Err(e) => { + // An error + // Check if it is non-retry + let e_inner = e.downcast_ref::(); + match e_inner { + Some(neolink_core::Error::CameraLoginFail) => { + // Fatal + log::error!("Login credentials were not accepted"); + self.cancel.cancel(); + return Err(e); + } + _ => { + // Non fatal + log::warn!("Connection Lost: {:?}", e); + log::info!("Attempt reconnect in {:?}", backoff); + sleep(backoff).await; + backoff *= 2; + } + } + } + } + } + } +} + +impl Drop for NeoCamThread { + fn drop(&mut self) { + log::debug!("Cancel:: NeoCamThread::drop"); + self.cancel.cancel(); + } +} diff --git a/src/common/instance.rs b/src/common/instance.rs new file mode 100644 index 0000000..9de3b96 --- /dev/null +++ b/src/common/instance.rs @@ -0,0 +1,130 @@ +//! The sharable instance +//! +//! This communicaes with the [`NeoCam`] over channels +//! +//! The camera watch is used as an event to be triggered +//! whenever the camera is lost/updated +use anyhow::anyhow; +use std::sync::Weak; +use tokio::sync::{ + mpsc::Sender as MpscSender, oneshot::channel as oneshot, watch::Receiver as WatchReceiver, +}; +use tokio_stream::wrappers::BroadcastStream; +use tokio_util::sync::CancellationToken; + +use super::NeoCamCommand; +use crate::Result; +use neolink_core::{ + bc_protocol::{BcCamera, StreamKind}, + bcmedia::model::BcMedia, +}; + +/// This instance is the primary interface used throughout the app +/// +/// It uses channels to run all tasks on the actual shared `[NeoCam]` +pub(crate) struct NeoInstance { + camera_watch: WatchReceiver>, + camera_control: MpscSender, + cancel: CancellationToken, +} + +impl NeoInstance { + pub(crate) fn new( + camera_watch: WatchReceiver>, + camera_control: MpscSender, + cancel: CancellationToken, + ) -> Result { + Ok(Self { + camera_watch, + camera_control, + cancel, + }) + } + + /// Create a new instance to the same camera + pub(crate) async fn subscribe(&self) -> Result { + let (instance_tx, instance_rx) = oneshot(); + self.camera_control + .send(NeoCamCommand::Instance(instance_tx)) + .await?; + instance_rx.await? + } + + pub(crate) async fn shutdown(&self) { + let _ = self.camera_control.send(NeoCamCommand::HangUp).await; + self.cancel.cancelled().await + } + + /// This is a helpful convience function + /// + /// Given an async task it will: + /// - Run the task with a reference to a BcCamera + /// - If the camera instance is changed: Rerun the task with the new instance + /// - If the camera returns a retryable error, wait for camera instance to change then rerun + /// - else return the result of the function + pub(crate) async fn run_task(&self, task: F) -> Result + where + F: for<'a> Fn( + &'a BcCamera, + ) + -> std::pin::Pin> + Send + 'a>>, + { + let mut camera_watch = self.camera_watch.clone(); + let mut camera = camera_watch.borrow_and_update().upgrade(); + + loop { + let res = tokio::select! { + _ = self.cancel.cancelled() => { + Some(Err(anyhow!("Camera is disconnecting"))) + } + v = camera_watch.changed() => { + // Camera value has changed! + // update and try again + if v.is_ok() { + camera = camera_watch.borrow_and_update().upgrade(); + None + } else { + Some(Err(anyhow!("Camera is disconnecting"))) + } + }, + Some(v) = async { + if let Some(cam) = camera.clone() { + let cam_ref = cam.as_ref(); + Some(task(cam_ref).await) + } else { + None + } + }, if camera.is_some() => { + match v { + // Ok means we are done + Ok(v) => Some(Ok(v)), + // If error we check for retryable errors + Err(e) => { + match e.downcast::() { + // Retry is a None + Ok(neolink_core::Error::DroppedConnection) => { + camera = None; + None + }, + Ok(e) => Some(Err(e.into())), + Err(e) => Some(Err(e)), + } + } + } + }, + }; + + if let Some(res) = res { + return res; + } + } + } + + pub(crate) async fn stream(&self, name: StreamKind) -> Result> { + let (instance_tx, instance_rx) = oneshot(); + self.camera_control + .send(NeoCamCommand::Stream(name, instance_tx)) + .await?; + Ok(instance_rx.await?) + } +} diff --git a/src/common/mod.rs b/src/common/mod.rs index 348ba8a..70849db 100644 --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -1 +1,11 @@ -pub(crate) mod neocam; +mod camthread; +mod instance; +mod neocam; +mod reactor; +mod streamthread; + +pub(crate) use camthread::*; +pub(crate) use instance::*; +pub(crate) use neocam::*; +pub(crate) use reactor::*; +pub(crate) use streamthread::*; diff --git a/src/common/neocam.rs b/src/common/neocam.rs index 5725637..1a88050 100644 --- a/src/common/neocam.rs +++ b/src/common/neocam.rs @@ -3,32 +3,31 @@ //! Features: //! Shared stream BC delivery //! Common restart code -//! Clonable interface to share amongst threads -use crate::{config::CameraConfig, utils::connect_and_login, Result}; -use neolink_core::bc_protocol::{BcCamera, StreamKind}; - -use anyhow::anyhow; +//! Clonable interface to share amongst threadsanyhow::anyhow; use futures::stream::StreamExt; -use neolink_core::bcmedia::model::BcMedia; -use std::collections::{hash_map::Entry, HashMap}; -use std::sync::{Arc, Weak}; +use std::sync::Weak; use tokio::sync::{ - broadcast::{channel as broadcast, Sender as BroadcastSender}, - mpsc::{channel as mpsc, Receiver as MpscReceiver, Sender as MpscSender}, + mpsc::{channel as mpsc, Sender as MpscSender}, oneshot::{channel as oneshot, Sender as OneshotSender}, watch::{channel as watch, Receiver as WatchReceiver, Sender as WatchSender}, }; -use tokio::time::{interval, sleep, Duration, Instant}; use tokio_stream::wrappers::{BroadcastStream, ReceiverStream}; use tokio_util::sync::CancellationToken; -enum NeoCamCommand { +use super::{NeoCamStreamThread, NeoCamThread, NeoInstance, StreamRequest}; +use crate::{config::CameraConfig, Result}; +use neolink_core::{ + bc_protocol::{BcCamera, StreamKind}, + bcmedia::model::BcMedia, +}; + +pub(crate) enum NeoCamCommand { HangUp, Instance(OneshotSender>), Stream(StreamKind, OneshotSender>), } /// The underlying camera binding -struct NeoCam { +pub(crate) struct NeoCam { cancel: CancellationToken, config_watch: WatchSender, commander: MpscSender, @@ -36,7 +35,7 @@ struct NeoCam { } impl NeoCam { - async fn new(config: CameraConfig) -> Result { + pub(crate) async fn new(config: CameraConfig) -> Result { let (commander_tx, commander_rx) = mpsc(100); let (watch_config_tx, watch_config_rx) = watch(config.clone()); let (camera_watch_tx, camera_watch_rx) = watch(Weak::new()); @@ -52,7 +51,7 @@ impl NeoCam { // This thread recieves messages from the instances // and acts on it. // - // This thread must be sta rted first so that we can begin creating instances for the + // This thread must be started first so that we can begin creating instances for the // other threads let sender_cancel = me.cancel.clone(); let mut commander_rx = ReceiverStream::new(commander_rx); @@ -122,7 +121,7 @@ impl NeoCam { Ok(me) } - async fn subscribe(&self) -> Result { + pub(crate) async fn subscribe(&self) -> Result { NeoInstance::new( self.camera_watch.clone(), self.commander.clone(), @@ -130,6 +129,11 @@ impl NeoCam { ) } + pub(crate) async fn update_config(&self, config: CameraConfig) -> Result<()> { + self.config_watch.send(config)?; + Ok(()) + } + pub(crate) async fn shutdown(&self) { let _ = self.commander.send(NeoCamCommand::HangUp).await; self.cancel.cancelled().await @@ -142,505 +146,3 @@ impl Drop for NeoCam { self.cancel.cancel(); } } - -struct NeoCamThread { - config: WatchReceiver, - cancel: CancellationToken, - camera_watch: WatchSender>, -} - -impl NeoCamThread { - async fn new( - watch_config_rx: WatchReceiver, - camera_watch_tx: WatchSender>, - cancel: CancellationToken, - ) -> Self { - Self { - config: watch_config_rx, - cancel, - camera_watch: camera_watch_tx, - } - } - async fn run_camera(&mut self, config: &CameraConfig) -> Result<()> { - let camera = Arc::new(connect_and_login(config).await?); - - self.camera_watch.send_replace(Arc::downgrade(&camera)); - - let cancel_check = self.cancel.clone(); - // Now we wait for a disconnect - tokio::select! { - _ = cancel_check.cancelled() => { - Ok(()) - } - v = camera.join() => v, - v = async { - let mut interval = interval(Duration::from_secs(5)); - loop { - interval.tick().await; - match camera.get_linktype().await { - Ok(_) => continue, - Err(neolink_core::Error::UnintelligibleReply { .. }) => { - // Camera does not support pings just wait forever - futures::pending!(); - }, - Err(e) => return Err(e), - } - } - } => v, - }?; - - let _ = camera.logout().await; - let _ = camera.shutdown().await; - - Ok(()) - } - - // Will run and attempt to maintain the connection - // while also delivering messages - async fn run(&mut self) -> Result<()> { - const MAX_BACKOFF: Duration = Duration::from_secs(5); - const MIN_BACKOFF: Duration = Duration::from_millis(50); - - let mut backoff = MIN_BACKOFF; - - loop { - let mut config_rec = self.config.clone(); - - let config = config_rec.borrow_and_update().clone(); - let now = Instant::now(); - - let res = tokio::select! { - Ok(_) = config_rec.changed() => { - None - } - v = self.run_camera(&config) => { - Some(v) - } - }; - self.camera_watch.send_replace(Weak::new()); - - if res.is_none() { - // If None go back and reload NOW - // - // This occurs if there was a config change - continue; - } - - // Else we see if the result actually was - let result = res.unwrap(); - - if Instant::now() - now > Duration::from_secs(60) { - // Command ran long enough to be considered a success - backoff = MIN_BACKOFF; - } - if backoff > MAX_BACKOFF { - backoff = MAX_BACKOFF; - } - - match result { - Ok(()) => { - // Normal shutdown - log::debug!("Cancel:: NeoCamThread::NormalShutdown"); - self.cancel.cancel(); - return Ok(()); - } - Err(e) => { - // An error - // Check if it is non-retry - let e_inner = e.downcast_ref::(); - match e_inner { - Some(neolink_core::Error::CameraLoginFail) => { - // Fatal - log::error!("Login credentials were not accepted"); - self.cancel.cancel(); - return Err(e); - } - _ => { - // Non fatal - log::warn!("Connection Lost: {:?}", e); - log::info!("Attempt reconnect in {:?}", backoff); - sleep(backoff).await; - backoff *= 2; - } - } - } - } - } - } -} - -impl Drop for NeoCamThread { - fn drop(&mut self) { - log::debug!("Cancel:: NeoCamThread::drop"); - self.cancel.cancel(); - } -} - -struct StreamRequest { - name: StreamKind, - sender: OneshotSender>, - strict: bool, -} - -struct StreamData { - sender: BroadcastSender, - name: StreamKind, - instance: NeoInstance, - strict: bool, - cancel: CancellationToken, -} - -impl StreamData { - async fn run(&self) -> Result<()> { - let thread_stream_tx = self.sender.clone(); - let cancel = self.cancel.clone(); - let instance = self.instance.subscribe().await?; - let name = self.name; - let strict = self.strict; - tokio::task::spawn(async move { - tokio::select! { - _ = cancel.cancelled() => { - Result::<(), anyhow::Error>::Ok(()) - }, - v = async { - loop { - instance.run_task(|camera| { - let stream_tx = thread_stream_tx.clone(); - Box::pin(async move { - let mut stream_data = camera.start_video(name, 0, strict).await?; - loop { - let data = stream_data.get_data().await??; - stream_tx.send(data)?; - } - }) - }).await?; - } - } => v, - } - }); - - Ok(()) - } -} - -impl Drop for StreamData { - fn drop(&mut self) { - log::debug!("Cancel:: StreamData::drop"); - self.cancel.cancel(); - } -} - -/// This thread will start and stop the camera -/// based on the number of listeners to the -/// async streams -struct NeoCamStreamThread { - streams: HashMap, - stream_request_rx: MpscReceiver, - cancel: CancellationToken, - instance: NeoInstance, -} - -impl NeoCamStreamThread { - async fn new( - stream_request_rx: MpscReceiver, - instance: NeoInstance, - cancel: CancellationToken, - ) -> Self { - Self { - streams: Default::default(), - stream_request_rx, - cancel, - instance, - } - } - async fn run(&mut self) -> Result<()> { - let thread_cancel = self.cancel.clone(); - tokio::select! { - _ = thread_cancel.cancelled() => Ok(()), - v = async { - while let Some(request) = self.stream_request_rx.recv().await { - match self.streams.entry(request.name) { - Entry::Occupied(occ) => { - let _ = request - .sender - .send(BroadcastStream::new(occ.get().sender.subscribe())); - } - Entry::Vacant(vac) => { - // Make a new streaming instance - - let (sender, stream_rx) = broadcast(1000); - let data = StreamData { - sender, - name: request.name, - instance: self.instance.subscribe().await?, - strict: request.strict, - cancel: CancellationToken::new(), - }; - data.run().await?; - vac.insert(data); - let _ = request.sender.send(BroadcastStream::new(stream_rx)); - } - } - } - Ok(()) - } => v, - } - } -} - -/// The sharable instance -/// -/// This communicaes with the [`NeoCam`] over channels -/// -/// The camera watch is used as an event to be triggered -/// whenever the camera is lost/updated -pub(crate) struct NeoInstance { - camera_watch: WatchReceiver>, - camera_control: MpscSender, - cancel: CancellationToken, -} - -impl NeoInstance { - fn new( - camera_watch: WatchReceiver>, - camera_control: MpscSender, - cancel: CancellationToken, - ) -> Result { - Ok(Self { - camera_watch, - camera_control, - cancel, - }) - } - - /// Create a new instance to the same camera - pub(crate) async fn subscribe(&self) -> Result { - let (instance_tx, instance_rx) = oneshot(); - self.camera_control - .send(NeoCamCommand::Instance(instance_tx)) - .await?; - instance_rx.await? - } - - pub(crate) async fn shutdown(&self) { - let _ = self.camera_control.send(NeoCamCommand::HangUp).await; - self.cancel.cancelled().await - } - - /// This is a helpful convience function - /// - /// Given an async task it will: - /// - Run the task with a reference to a BcCamera - /// - If the camera instance is changed: Rerun the task with the new instance - /// - If the camera returns a retryable error, wait for camera instance to change then rerun - /// - else return the result of the function - pub(crate) async fn run_task(&self, task: F) -> Result - where - F: for<'a> Fn( - &'a BcCamera, - ) - -> std::pin::Pin> + Send + 'a>>, - { - let mut camera_watch = self.camera_watch.clone(); - let mut camera = camera_watch.borrow_and_update().upgrade(); - - loop { - let res = tokio::select! { - _ = self.cancel.cancelled() => { - Some(Err(anyhow!("Camera is disconnecting"))) - } - v = camera_watch.changed() => { - // Camera value has changed! - // update and try again - if v.is_ok() { - camera = camera_watch.borrow_and_update().upgrade(); - None - } else { - Some(Err(anyhow!("Camera is disconnecting"))) - } - }, - Some(v) = async { - if let Some(cam) = camera.clone() { - let cam_ref = cam.as_ref(); - Some(task(cam_ref).await) - } else { - None - } - }, if camera.is_some() => { - match v { - // Ok means we are done - Ok(v) => Some(Ok(v)), - // If error we check for retryable errors - Err(e) => { - match e.downcast::() { - // Retry is a None - Ok(neolink_core::Error::DroppedConnection) => { - camera = None; - None - }, - Ok(e) => Some(Err(e.into())), - Err(e) => Some(Err(e)), - } - } - } - }, - }; - - if let Some(res) = res { - return res; - } - } - } - - pub(crate) async fn stream(&self, name: StreamKind) -> Result> { - let (instance_tx, instance_rx) = oneshot(); - self.camera_control - .send(NeoCamCommand::Stream(name, instance_tx)) - .await?; - Ok(instance_rx.await?) - } -} - -#[allow(clippy::large_enum_variant)] -enum NeoReactorCommand { - HangUp, - Get(String, OneshotSender>), - GetOrInsert(CameraConfig, OneshotSender>), - UpdateOrInsert(CameraConfig, OneshotSender>), -} - -/// Reactor handles the collection of cameras -#[derive(Clone)] -pub(crate) struct NeoReactor { - cancel: CancellationToken, - commander: MpscSender, -} - -impl NeoReactor { - pub(crate) async fn new() -> Self { - let (commad_tx, mut command_rx) = mpsc(100); - let me = Self { - cancel: CancellationToken::new(), - commander: commad_tx, - }; - - let cancel = me.cancel.clone(); - let cancel2 = me.cancel.clone(); - tokio::task::spawn(async move { - let mut instances: HashMap = Default::default(); - - tokio::select! { - _ = cancel.cancelled() => { - for instance in instances.values() { - instance.shutdown().await; - } - Ok(()) - }, - v = async { - - while let Some(command) = command_rx.recv().await { - match command { - NeoReactorCommand::HangUp => { - for instance in instances.values() { - instance.shutdown().await; - } - log::debug!("Cancel:: NeoReactorCommand::HangUp"); - cancel2.cancel(); - return Result::<(), anyhow::Error>::Ok(()); - } - NeoReactorCommand::Get(name, sender) => { - let new = instances - .get(&name) - .ok_or_else(|| anyhow!("Camera not found")) - .map(|data| data.subscribe())? - .await; - let _ = sender.send(new); - } - NeoReactorCommand::GetOrInsert(config, sender) => { - let name = config.name.clone(); - let new = match instances.entry(name) { - Entry::Occupied(occ) => occ.get().subscribe().await, - Entry::Vacant(vac) => { - log::debug!("Inserting new insance"); - let cam = NeoCam::new(config).await?; - log::debug!("New instance created"); - vac.insert( - cam, - ) - .subscribe() - .await - } - }; - log::debug!("Got instance from reactor"); - let _ = sender.send(new); - }, - NeoReactorCommand::UpdateOrInsert(config, sender) => { - let name = config.name.clone(); - let new = match instances.entry(name) { - Entry::Occupied(occ) => { - occ.get().config_watch.send(config)?; - occ.get().subscribe().await - }, - Entry::Vacant(vac) => { - let cam = NeoCam::new(config).await?; - vac.insert(cam) - .subscribe() - .await - } - }; - let _ = sender.send(new); - } - } - } - Ok(()) - } => v, - } - }); - - me - } - - #[allow(dead_code)] - /// Get camera by name but do not create - pub(crate) async fn get(&self, name: &str) -> Result { - let (sender_tx, sender_rx) = oneshot(); - self.commander - .send(NeoReactorCommand::Get(name.to_string(), sender_tx)) - .await?; - - sender_rx.await? - } - - /// Get or create a camera - pub(crate) async fn get_or_insert(&self, config: CameraConfig) -> Result { - let (sender_tx, sender_rx) = oneshot(); - self.commander - .send(NeoReactorCommand::GetOrInsert(config, sender_tx)) - .await?; - - sender_rx.await? - } - - #[allow(dead_code)] - /// Update a camera to a new config or create a camera - pub(crate) async fn update_or_insert(&self, config: CameraConfig) -> Result { - let (sender_tx, sender_rx) = oneshot(); - self.commander - .send(NeoReactorCommand::UpdateOrInsert(config, sender_tx)) - .await?; - - sender_rx.await? - } - - pub(crate) async fn shutdown(&self) { - let _ = self.commander.send(NeoReactorCommand::HangUp).await; - self.cancel.cancelled().await; - } -} - -impl Drop for NeoReactor { - fn drop(&mut self) { - log::debug!("Cancel:: NeoReactor::drop"); - self.cancel.cancel(); - } -} diff --git a/src/common/reactor.rs b/src/common/reactor.rs new file mode 100644 index 0000000..a5ca135 --- /dev/null +++ b/src/common/reactor.rs @@ -0,0 +1,156 @@ +//! This is the highest level to a camera +//! it represents a collection of managed cameras +use anyhow::anyhow; +use std::collections::{hash_map::Entry, HashMap}; +use tokio::sync::{ + mpsc::{channel as mpsc, Sender as MpscSender}, + oneshot::{channel as oneshot, Sender as OneshotSender}, +}; +use tokio_util::sync::CancellationToken; + +use super::{NeoCam, NeoInstance}; +use crate::{config::CameraConfig, Result}; + +#[allow(clippy::large_enum_variant)] +enum NeoReactorCommand { + HangUp, + Get(String, OneshotSender>), + GetOrInsert(CameraConfig, OneshotSender>), + UpdateOrInsert(CameraConfig, OneshotSender>), +} + +/// Reactor handles the collection of cameras +#[derive(Clone)] +pub(crate) struct NeoReactor { + cancel: CancellationToken, + commander: MpscSender, +} + +impl NeoReactor { + pub(crate) async fn new() -> Self { + let (commad_tx, mut command_rx) = mpsc(100); + let me = Self { + cancel: CancellationToken::new(), + commander: commad_tx, + }; + + let cancel = me.cancel.clone(); + let cancel2 = me.cancel.clone(); + tokio::task::spawn(async move { + let mut instances: HashMap = Default::default(); + + tokio::select! { + _ = cancel.cancelled() => { + for instance in instances.values() { + instance.shutdown().await; + } + Ok(()) + }, + v = async { + + while let Some(command) = command_rx.recv().await { + match command { + NeoReactorCommand::HangUp => { + for instance in instances.values() { + instance.shutdown().await; + } + log::debug!("Cancel:: NeoReactorCommand::HangUp"); + cancel2.cancel(); + return Result::<(), anyhow::Error>::Ok(()); + } + NeoReactorCommand::Get(name, sender) => { + let new = instances + .get(&name) + .ok_or_else(|| anyhow!("Camera not found")) + .map(|data| data.subscribe())? + .await; + let _ = sender.send(new); + } + NeoReactorCommand::GetOrInsert(config, sender) => { + let name = config.name.clone(); + let new = match instances.entry(name) { + Entry::Occupied(occ) => occ.get().subscribe().await, + Entry::Vacant(vac) => { + log::debug!("Inserting new insance"); + let cam = NeoCam::new(config).await?; + log::debug!("New instance created"); + vac.insert( + cam, + ) + .subscribe() + .await + } + }; + log::debug!("Got instance from reactor"); + let _ = sender.send(new); + }, + NeoReactorCommand::UpdateOrInsert(config, sender) => { + let name = config.name.clone(); + let new = match instances.entry(name) { + Entry::Occupied(occ) => { + occ.get().update_config(config).await?; + occ.get().subscribe().await + }, + Entry::Vacant(vac) => { + let cam = NeoCam::new(config).await?; + vac.insert(cam) + .subscribe() + .await + } + }; + let _ = sender.send(new); + } + } + } + Ok(()) + } => v, + } + }); + + me + } + + #[allow(dead_code)] + /// Get camera by name but do not create + pub(crate) async fn get(&self, name: &str) -> Result { + let (sender_tx, sender_rx) = oneshot(); + self.commander + .send(NeoReactorCommand::Get(name.to_string(), sender_tx)) + .await?; + + sender_rx.await? + } + + /// Get or create a camera + pub(crate) async fn get_or_insert(&self, config: CameraConfig) -> Result { + let (sender_tx, sender_rx) = oneshot(); + self.commander + .send(NeoReactorCommand::GetOrInsert(config, sender_tx)) + .await?; + + sender_rx.await? + } + + #[allow(dead_code)] + /// Update a camera to a new config or create a camera + pub(crate) async fn update_or_insert(&self, config: CameraConfig) -> Result { + let (sender_tx, sender_rx) = oneshot(); + self.commander + .send(NeoReactorCommand::UpdateOrInsert(config, sender_tx)) + .await?; + + sender_rx.await? + } + + pub(crate) async fn shutdown(&self) { + let _ = self.commander.send(NeoReactorCommand::HangUp).await; + self.cancel.cancelled().await; + } +} + +impl Drop for NeoReactor { + fn drop(&mut self) { + log::debug!("Cancel:: NeoReactor::drop"); + self.cancel.cancel(); + } +} diff --git a/src/common/streamthread.rs b/src/common/streamthread.rs new file mode 100644 index 0000000..6bba80e --- /dev/null +++ b/src/common/streamthread.rs @@ -0,0 +1,127 @@ +//! This thread will start and stop the camera +//! based on the number of listeners to the +//! async streams + +use std::collections::{hash_map::Entry, HashMap}; +use tokio::sync::{ + broadcast::{channel as broadcast, Sender as BroadcastSender}, + mpsc::Receiver as MpscReceiver, + oneshot::Sender as OneshotSender, +}; +use tokio_stream::wrappers::BroadcastStream; +use tokio_util::sync::CancellationToken; + +use super::NeoInstance; +use crate::Result; +use neolink_core::{bc_protocol::StreamKind, bcmedia::model::BcMedia}; + +pub(crate) struct NeoCamStreamThread { + streams: HashMap, + stream_request_rx: MpscReceiver, + cancel: CancellationToken, + instance: NeoInstance, +} + +impl NeoCamStreamThread { + pub(crate) async fn new( + stream_request_rx: MpscReceiver, + instance: NeoInstance, + cancel: CancellationToken, + ) -> Self { + Self { + streams: Default::default(), + stream_request_rx, + cancel, + instance, + } + } + pub(crate) async fn run(&mut self) -> Result<()> { + let thread_cancel = self.cancel.clone(); + tokio::select! { + _ = thread_cancel.cancelled() => Ok(()), + v = async { + while let Some(request) = self.stream_request_rx.recv().await { + match self.streams.entry(request.name) { + Entry::Occupied(occ) => { + let _ = request + .sender + .send(BroadcastStream::new(occ.get().sender.subscribe())); + } + Entry::Vacant(vac) => { + // Make a new streaming instance + + let (sender, stream_rx) = broadcast(1000); + let data = StreamData { + sender, + name: request.name, + instance: self.instance.subscribe().await?, + strict: request.strict, + cancel: CancellationToken::new(), + }; + data.run().await?; + vac.insert(data); + let _ = request.sender.send(BroadcastStream::new(stream_rx)); + } + } + } + Ok(()) + } => v, + } + } +} + +/// The kind of stream we want a async broadcast of +pub(crate) struct StreamRequest { + pub(crate) name: StreamKind, + pub(crate) sender: OneshotSender>, + pub(crate) strict: bool, +} + +/// The data of a running stream +pub(crate) struct StreamData { + sender: BroadcastSender, + name: StreamKind, + instance: NeoInstance, + strict: bool, + cancel: CancellationToken, +} + +impl StreamData { + async fn run(&self) -> Result<()> { + let thread_stream_tx = self.sender.clone(); + let cancel = self.cancel.clone(); + let instance = self.instance.subscribe().await?; + let name = self.name; + let strict = self.strict; + tokio::task::spawn(async move { + tokio::select! { + _ = cancel.cancelled() => { + Result::<(), anyhow::Error>::Ok(()) + }, + v = async { + loop { + instance.run_task(|camera| { + let stream_tx = thread_stream_tx.clone(); + Box::pin(async move { + let mut stream_data = camera.start_video(name, 0, strict).await?; + loop { + let data = stream_data.get_data().await??; + stream_tx.send(data)?; + } + }) + }).await?; + } + } => v, + } + }); + + Ok(()) + } +} + +impl Drop for StreamData { + fn drop(&mut self) { + log::debug!("Cancel:: StreamData::drop"); + self.cancel.cancel(); + } +} diff --git a/src/image/mod.rs b/src/image/mod.rs index 492fd6e..a04a6c3 100644 --- a/src/image/mod.rs +++ b/src/image/mod.rs @@ -27,7 +27,7 @@ mod cmdline; mod gst; use super::config::Config; -use crate::common::neocam::NeoReactor; +use crate::common::NeoReactor; pub(crate) use cmdline::Opt; /// Entry point for the image subcommand diff --git a/src/main.rs b/src/main.rs index bbdba4a..d1724ac 100644 --- a/src/main.rs +++ b/src/main.rs @@ -44,7 +44,7 @@ mod talk; mod utils; use cmdline::{Command, Opt}; -use common::neocam::NeoReactor; +use common::NeoReactor; use config::Config; use console_subscriber as _; diff --git a/src/pir/mod.rs b/src/pir/mod.rs index 5ff7ce8..f821fe0 100644 --- a/src/pir/mod.rs +++ b/src/pir/mod.rs @@ -18,7 +18,7 @@ use anyhow::{Context, Result}; mod cmdline; use super::config::Config; -use crate::common::neocam::NeoReactor; +use crate::common::NeoReactor; pub(crate) use cmdline::Opt; /// Entry point for the pir subcommand diff --git a/src/reboot/mod.rs b/src/reboot/mod.rs index 26e2c08..55c1c0b 100644 --- a/src/reboot/mod.rs +++ b/src/reboot/mod.rs @@ -16,7 +16,7 @@ use anyhow::{Context, Result}; mod cmdline; use super::config::Config; -use crate::common::neocam::NeoReactor; +use crate::common::NeoReactor; pub(crate) use cmdline::Opt; /// Entry point for the reboot subcommand diff --git a/src/statusled/mod.rs b/src/statusled/mod.rs index b32a9a4..999110d 100644 --- a/src/statusled/mod.rs +++ b/src/statusled/mod.rs @@ -20,7 +20,7 @@ use anyhow::{Context, Result}; mod cmdline; use super::config::Config; -use crate::common::neocam::NeoReactor; +use crate::common::NeoReactor; pub(crate) use cmdline::Opt; /// Entry point for the ledstatus subcommand