diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index 22f3e97..bff80e5 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -8,6 +8,7 @@ use Md5Trunc::*; mod connection; mod errors; +mod keepalive; mod ledstate; mod login; mod logout; @@ -298,6 +299,7 @@ impl BcCamera { logged_in: AtomicBool::new(false), credentials: Credentials::new(username, passwd), }; + me.keepalive().await?; Ok(me) } diff --git a/crates/core/src/bc_protocol/connection/bcconn.rs b/crates/core/src/bc_protocol/connection/bcconn.rs index e7b0d43..b59862a 100644 --- a/crates/core/src/bc_protocol/connection/bcconn.rs +++ b/crates/core/src/bc_protocol/connection/bcconn.rs @@ -11,7 +11,15 @@ use tokio::sync::Mutex; use tokio::{sync::RwLock, task::JoinSet}; -type Subscriber = Arc>>>; +type MsgHandler = Box Option + Send + Sync>; +#[derive(Default)] +struct Subscriber { + /// Subscribers based on their Num + num: RwLock>>, + /// Subscribers based on their ID + id: RwLock>, +} + pub(crate) type BcConnSink = Box + Send + Sync + Unpin>; pub(crate) type BcConnSource = Box> + Send + Sync + Unpin>; @@ -22,19 +30,20 @@ pub(crate) type BcConnSource = Box> + Send + Sync + /// There can be only one subscriber per kind of message at a time. pub struct BcConnection { sink: Arc>, - subscribers: Subscriber, + subscribers: Arc, #[allow(dead_code)] // Not dead we just need to hold a reference to keep it alive rx_thread: JoinSet<()>, } impl BcConnection { pub async fn new(sink: BcConnSink, mut source: BcConnSource) -> Result { - let subscribers: Subscriber = Default::default(); + let subscribers: Arc = Default::default(); + let sink = Arc::new(Mutex::new(sink)); let subs = subscribers.clone(); let mut rx_thread = JoinSet::new(); - + let sink_thread = sink.clone(); rx_thread.spawn(async move { loop { let packet = source.next().await; @@ -47,7 +56,7 @@ impl BcConnection { None => continue, }; - if let Err(e) = Self::poll(bc, &subs).await { + if let Err(e) = Self::poll(bc, &subs, &sink_thread).await { error!("Subscription error: {:?}", e); break; } @@ -55,7 +64,7 @@ impl BcConnection { }); Ok(BcConnection { - sink: Arc::new(Mutex::new(sink)), + sink, subscribers, rx_thread, }) @@ -70,45 +79,72 @@ impl BcConnection { pub async fn subscribe(&self, msg_num: u16) -> Result { let (tx, rx) = channel(100); - match self.subscribers.write().await.entry(msg_num) { - Entry::Vacant(vac_entry) => vac_entry.insert(tx), - Entry::Occupied(_) => return Err(Error::SimultaneousSubscription { msg_num }), + match self.subscribers.num.write().await.entry(msg_num) { + Entry::Vacant(vac_entry) => { + vac_entry.insert(tx); + } + Entry::Occupied(mut occ_entry) => { + if occ_entry.get().is_closed() { + occ_entry.insert(tx); + } else { + return Err(Error::SimultaneousSubscription { msg_num }); + } + } }; - Ok(BcSubscription::new(rx, msg_num, self)) + Ok(BcSubscription::new(rx, msg_num as u32, self)) } - pub fn unsubscribe(&self, msg_num: u16) -> Result<()> { - let subs = self.subscribers.clone(); - tokio::task::spawn(async move { - subs.write().await.remove(&msg_num); - }); - + /// Some messages are initiated by the camera. This creates a handler for them + /// It requires a closure that will be used to handle the message + /// and return either None or Some(Bc) reply + pub async fn handle_msg(&self, msg_id: u32, handler: T) -> Result<()> + where + T: Fn(&Bc) -> Option + Send + Sync + 'static, + { + match self.subscribers.id.write().await.entry(msg_id) { + Entry::Vacant(vac_entry) => { + vac_entry.insert(Box::new(handler)); + } + Entry::Occupied(_) => { + return Err(Error::SimultaneousSubscriptionId { msg_id }); + } + }; Ok(()) } - async fn poll(response: Bc, subscribers: &Subscriber) -> Result<()> { + async fn poll(response: Bc, subscribers: &Subscriber, sink: &Mutex) -> Result<()> { // Don't hold the lock during deserialization so we don't poison the subscribers mutex if // something goes wrong let msg_num = response.meta.msg_num; let msg_id = response.meta.msg_id; - let mut remove_it = false; - match subscribers.read().await.get(&msg_num) { - Some(occ) => { - trace!("occ.full: {}/{}", occ.capacity(), occ.max_capacity()); - if occ.send(response).await.is_err() { - // Exceedingly unlikely, unless you mishandle the subscription object - warn!("Subscriber to ID {} dropped their channel", msg_id); - remove_it = true; + let mut remove_it_num = false; + match ( + subscribers.id.read().await.get(&msg_id), + subscribers.num.read().await.get(&msg_num), + ) { + (Some(occ), _) => { + if let Some(reply) = occ(&response) { + assert!(reply.meta.msg_num == response.meta.msg_num); + sink.lock().await.send(reply).await?; } } - None => { - debug!("Ignoring uninteresting message num {}", msg_id); + (None, Some(occ)) => { + trace!("occ.full: {}/{}", occ.capacity(), occ.max_capacity()); + if occ.send(response).await.is_err() { + remove_it_num = true; + } + } + (None, None) => { + debug!( + "Ignoring uninteresting message id {} (number: {})", + msg_id, msg_num + ); trace!("Contents: {:?}", response); } } - if remove_it { - subscribers.write().await.remove(&msg_num); + if remove_it_num { + subscribers.num.write().await.remove(&msg_num); } Ok(()) diff --git a/crates/core/src/bc_protocol/connection/bcsub.rs b/crates/core/src/bc_protocol/connection/bcsub.rs index 9e54186..cd6696f 100644 --- a/crates/core/src/bc_protocol/connection/bcsub.rs +++ b/crates/core/src/bc_protocol/connection/bcsub.rs @@ -12,7 +12,7 @@ use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt}; pub struct BcSubscription<'a> { rx: ReceiverStream, - msg_num: u16, + msg_num: u32, conn: &'a BcConnection, } @@ -74,7 +74,7 @@ impl<'a> Stream for BcPayloadStream<'a> { pub type BcMediaStream<'b> = FramedRead>>, BcMediaCodex>; impl<'a> BcSubscription<'a> { - pub fn new(rx: Receiver, msg_num: u16, conn: &'a BcConnection) -> BcSubscription<'a> { + pub fn new(rx: Receiver, msg_num: u32, conn: &'a BcConnection) -> BcSubscription<'a> { BcSubscription { rx: ReceiverStream::new(rx), msg_num, @@ -83,14 +83,14 @@ impl<'a> BcSubscription<'a> { } pub async fn send(&self, bc: Bc) -> Result<()> { - assert!(bc.meta.msg_num == self.msg_num); + assert!(bc.meta.msg_num as u32 == self.msg_num); self.conn.send(bc).await?; Ok(()) } pub async fn recv(&mut self) -> Result { let bc = self.rx.next().await.ok_or(Error::DroppedSubscriber)?; - assert!(bc.meta.msg_num == self.msg_num); + assert!(bc.meta.msg_num as u32 == self.msg_num); Ok(bc) } @@ -112,11 +112,3 @@ impl<'a> BcSubscription<'a> { FramedRead::new(async_read, BcMediaCodex::new()) } } - -/// Makes it difficult to avoid unsubscribing when you're finished -impl<'a> Drop for BcSubscription<'a> { - fn drop(&mut self) { - // It's fine if we can't unsubscribe as that means we already have - let _ = self.conn.unsubscribe(self.msg_num); - } -} diff --git a/crates/core/src/bc_protocol/errors.rs b/crates/core/src/bc_protocol/errors.rs index 72db363..4eefd61 100644 --- a/crates/core/src/bc_protocol/errors.rs +++ b/crates/core/src/bc_protocol/errors.rs @@ -63,13 +63,20 @@ pub enum Error { #[error(display = "Cookie GenError")] GenError(#[error(source)] std::sync::Arc), - /// Raised when a connection is subscrbed to more than once + /// Raised when a connection is subscrbed to more than once for msg_num #[error(display = "Simultaneous subscription, {}", _0)] SimultaneousSubscription { /// The message number that was subscribed to msg_num: u16, }, + /// Raised when a connection is subscrbed to more than once for msg_id + #[error(display = "Simultaneous subscription, {}", _0)] + SimultaneousSubscriptionId { + /// The message number that was subscribed to + msg_id: u32, + }, + /// Raised when a new encyrption byte is observed #[error(display = "Unknown encryption: {:x?}", _0)] UnknownEncryption(usize),