diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index bc2536e..626c8b1 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -191,64 +191,80 @@ impl BcCamera { None }; - if allow_local { - let uid_local = uid.clone(); - info!("{}: Trying local discovery", options.name); - let result = discovery.local(&uid_local, Some(sockets)).await; - if let Ok(disc) = result { - info!( - "{}: Local discovery success {} at {}", - options.name, - uid_local, - disc.get_addr() - ); - return Ok(CameraLocation::Udp(disc)); - } - } - if allow_remote { - let uid_remote = uid.clone(); - info!("{}: Trying remote discovery", options.name); - let result = discovery - .remote(&uid_remote, reg_result.as_ref().unwrap()) - .await; - if let Ok(disc) = result { - info!( - "{}: Remote discovery success {} at {}", - options.name, - uid_remote, - disc.get_addr() - ); - return Ok(CameraLocation::Udp(disc)); - } - } - if allow_map { - let uid_map = uid.clone(); - info!("{}: Trying map discovery", options.name); - let result = discovery.map(reg_result.as_ref().unwrap()).await; - if let Ok(disc) = result { - info!( - "{}: Map success {} at {}", - options.name, - uid_map, - disc.get_addr() - ); - return Ok(CameraLocation::Udp(disc)); - } - } - if allow_relay { - let uid_relay = uid.clone(); - info!("{}: Trying relay discovery", options.name); - let result = discovery.relay(reg_result.as_ref().unwrap()).await; - if let Ok(disc) = result { - info!( - "{}: Relay success {} at {}", - options.name, - uid_relay, - disc.get_addr() - ); - return Ok(CameraLocation::Udp(disc)); - } - } + let res = tokio::select! { + v = async { + let uid_local = uid.clone(); + info!("{}: Trying local discovery", options.name); + let result = discovery.local(&uid_local, Some(sockets)).await; + match result { + Ok(disc) => { + info!( + "{}: Local discovery success {} at {}", + options.name, + uid_local, + disc.get_addr() + ); + Ok(CameraLocation::Udp(disc)) + }, + Err(e) => Err(e) + } + }, if allow_local => v, + v = async { + let uid_remote = uid.clone(); + info!("{}: Trying remote discovery", options.name); + let result = discovery + .remote(&uid_remote, reg_result.as_ref().unwrap()) + .await; + match result { + Ok(disc) => { + info!( + "{}: Remote discovery success {} at {}", + options.name, + uid_remote, + disc.get_addr() + ); + Ok(CameraLocation::Udp(disc)) + }, + Err(e) => Err(e) + } + }, if allow_remote => v, + v = async { + let uid_map = uid.clone(); + info!("{}: Trying map discovery", options.name); + let result = discovery.map(reg_result.as_ref().unwrap()).await; + match result { + Ok(disc) => { + info!( + "{}: Map success {} at {}", + options.name, + uid_map, + disc.get_addr() + ); + Ok(CameraLocation::Udp(disc)) + }, + Err(e) => Err(e), + } + }, if allow_map => v, + v = async { + let uid_relay = uid.clone(); + info!("{}: Trying relay discovery", options.name); + let result = discovery.relay(reg_result.as_ref().unwrap()).await; + match result { + Ok(disc) => { + info!( + "{}: Relay success {} at {}", + options.name, + uid_relay, + disc.get_addr() + ); + Ok(CameraLocation::Udp(disc)) + }, + Err(e) => Err(e), + } + }, if allow_relay => v, + }?; + + return Ok(res); } info!("{}: Discovery failed", options.name); @@ -365,6 +381,16 @@ impl BcCamera { pub async fn join(&self) -> Result<()> { self.connection.join().await } + + /// Disconnect from the camera. This is done by dropping the reciever + /// so further communications are not possible. + pub async fn disconnect(self) -> Result<()> { + let connection = Arc::try_unwrap(self.connection) + .map_err(|_| Error::Other("Connection still active"))?; + connection.disconnect().await?; + + Ok(()) + } } /// 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 5e0f71a..a6756e9 100644 --- a/crates/core/src/bc_protocol/connection/bcconn.rs +++ b/crates/core/src/bc_protocol/connection/bcconn.rs @@ -147,6 +147,15 @@ impl BcConnection { } Ok(()) } + + pub async fn disconnect(mut self) -> Result<()> { + self.poll_commander.send(PollCommand::Disconnect).await?; + drop(self.sink); + drop(self.poll_commander); + let locked_threads = self.rx_thread.get_mut(); + while locked_threads.join_next().await.is_some() {} + Ok(()) + } } enum PollCommand { @@ -154,6 +163,7 @@ enum PollCommand { AddHandler(u32, Arc), RemoveHandler(u32), AddSubscriber(u32, Option, Sender>), + Disconnect, } struct Poller { @@ -292,6 +302,9 @@ impl Poller { } }; } + PollCommand::Disconnect => { + return Err(Error::DroppedConnection); + } } } Ok(()) diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs index 8dd312c..48b3da1 100644 --- a/crates/core/src/bc_protocol/stream.rs +++ b/crates/core/src/bc_protocol/stream.rs @@ -4,12 +4,9 @@ use crate::{ bcmedia::model::*, }; use futures::stream::StreamExt; -use std::sync::{ - atomic::{AtomicBool, Ordering}, - Arc, -}; use tokio::sync::mpsc::{channel, Receiver}; use tokio::task::{self, JoinHandle}; +use tokio_util::sync::CancellationToken; /// The stream names supported by BC #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] @@ -33,7 +30,7 @@ pub enum StreamKind { pub struct StreamData { handle: Option>>, rx: Receiver>, - abort_handle: Arc, + abort_handle: CancellationToken, } impl StreamData { @@ -42,12 +39,12 @@ impl StreamData { pub async fn get_data(&mut self) -> Result> { if let Some(handle) = self.handle.as_mut() { if handle.is_finished() { - self.abort_handle.store(true, Ordering::Relaxed); + self.abort_handle.cancel(); handle.await??; return Err(Error::DroppedConnection); } } else { - self.abort_handle.store(true, Ordering::Relaxed); + self.abort_handle.cancel(); return Err(Error::DroppedConnection); } // debug!("StreamData: Get"); @@ -58,16 +55,26 @@ impl StreamData { } None => { // debug!("StreamData: Drop"); - self.abort_handle.store(true, Ordering::Relaxed); + self.abort_handle.cancel(); Err(Error::DroppedConnection) } } } + + /// Attempts to gracefully shutdown this will cancel the background task and send + /// the Stop command to the camera + pub async fn shutdown(&mut self) -> Result<()> { + self.abort_handle.cancel(); + if let Some(handle) = self.handle.take() { + let _ = handle.await?; + } + Ok(()) + } } impl Drop for StreamData { fn drop(&mut self) { - self.abort_handle.store(true, Ordering::Relaxed); + self.abort_handle.cancel(); } } @@ -100,7 +107,7 @@ impl BcCamera { let connection = self.get_connection(); let msg_num = self.new_message_num(); - let abort_handle = Arc::new(AtomicBool::new(false)); + let abort_handle = CancellationToken::new(); let abort_handle_thread = abort_handle.clone(); if buffer_size == 0 { @@ -186,20 +193,20 @@ impl BcCamera { { let mut media_sub = sub_video.bcmedia_stream(strict); - while !abort_handle_thread.load(Ordering::Relaxed) { - // debug!("Stream: Get"); - if let Some(bc_media) = media_sub.next().await { - // debug!("Stream: Got"); - // We now have a complete interesting packet. Send it to on the callback - // debug!("Stream: Send"); - if tx.send(bc_media).await.is_err() { - // debug!("Stream: Dropped"); - break; // Connection dropped + tokio::select! { + _ = abort_handle_thread.cancelled() => {}, + _ = async { + while let Some(bc_media) = media_sub.next().await { + // debug!("Stream: Got"); + // We now have a complete interesting packet. Send it to on the callback + // debug!("Stream: Send"); + if tx.send(bc_media).await.is_err() { + // debug!("Stream: Dropped"); + break; // Connection dropped + } + // debug!("Stream: Sent"); } - // debug!("Stream: Sent"); - } else { - break; - } + } => {} } } diff --git a/src/image/gst.rs b/src/image/gst.rs index 1ef6e43..b95f01d 100644 --- a/src/image/gst.rs +++ b/src/image/gst.rs @@ -20,7 +20,6 @@ enum GstControl { pub(super) struct GstSender { sender: Sender, - #[allow(dead_code)] // It is used for its automatic drop set: JoinSet>, finished: sync::oneshot::Receiver>, } @@ -49,6 +48,11 @@ impl GstSender { } } } + + pub(super) async fn join(mut self) -> Result<()> { + while self.set.join_next().await.is_some() {} + Ok(()) + } } pub(super) async fn from_input>( diff --git a/src/image/mod.rs b/src/image/mod.rs index d90fac0..8b88f3e 100644 --- a/src/image/mod.rs +++ b/src/image/mod.rs @@ -81,6 +81,9 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> { } debug!("Sending EOS"); let _ = sender.eos().await; // Ignore return because if pipeline is finished this will error + let _ = sender.join().await; + + let _ = stream_data.shutdown().await; } else { // Simply use the snap command debug!("Using the snap command"); @@ -90,5 +93,8 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> { buffer.write_all(jpeg_data.as_slice()).await?; } + let _ = camera.logout().await; + camera.disconnect().await?; + Ok(()) }