From f7b5e89ba8c521ad41618b5241dde9425f79a9d7 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Thu, 8 Jun 2023 12:52:53 +0700 Subject: [PATCH] Handle messages and IDs to better replicate offical messaging system --- crates/core/src/bc/de.rs | 6 +- crates/core/src/bc_protocol/abilityinfo.rs | 2 +- crates/core/src/bc_protocol/battery.rs | 2 +- .../core/src/bc_protocol/connection/bcconn.rs | 154 +++++++++++------- .../core/src/bc_protocol/connection/bcsub.rs | 17 +- .../src/bc_protocol/connection/discovery.rs | 2 +- crates/core/src/bc_protocol/errors.rs | 4 +- .../core/src/bc_protocol/floodlight_status.rs | 4 +- crates/core/src/bc_protocol/ledstate.rs | 4 +- crates/core/src/bc_protocol/login.rs | 2 +- crates/core/src/bc_protocol/logout.rs | 2 +- crates/core/src/bc_protocol/motion.rs | 6 +- crates/core/src/bc_protocol/ping.rs | 2 +- crates/core/src/bc_protocol/pirstate.rs | 6 +- crates/core/src/bc_protocol/ptz.rs | 8 +- crates/core/src/bc_protocol/reboot.rs | 2 +- crates/core/src/bc_protocol/snap.rs | 95 +++++++++-- crates/core/src/bc_protocol/stream.rs | 9 +- crates/core/src/bc_protocol/talk.rs | 12 +- crates/core/src/bc_protocol/time.rs | 4 +- crates/core/src/bc_protocol/version.rs | 2 +- src/mqtt/event_cam.rs | 4 +- src/mqtt/mod.rs | 5 +- 23 files changed, 242 insertions(+), 112 deletions(-) diff --git a/crates/core/src/bc/de.rs b/crates/core/src/bc/de.rs index eb22a3e..4bf895b 100644 --- a/crates/core/src/bc/de.rs +++ b/crates/core/src/bc/de.rs @@ -197,8 +197,10 @@ fn bc_modern_msg<'a>( } fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> { - let (buf, _magic) = - error_context("Magic invalid", verify(le_u32, |x| *x == MAGIC_HEADER || *x == MAGIC_HEADER_REV))(buf)?; + let (buf, _magic) = error_context( + "Magic invalid", + verify(le_u32, |x| *x == MAGIC_HEADER || *x == MAGIC_HEADER_REV), + )(buf)?; let (buf, msg_id) = error_context("MsgID missing", le_u32)(buf)?; let (buf, body_len) = error_context("BodyLen missing", le_u32)(buf)?; let (buf, channel_id) = error_context("ChannelID missing", le_u8)(buf)?; diff --git a/crates/core/src/bc_protocol/abilityinfo.rs b/crates/core/src/bc_protocol/abilityinfo.rs index 6a7b99c..b1d2123 100644 --- a/crates/core/src/bc_protocol/abilityinfo.rs +++ b/crates/core/src/bc_protocol/abilityinfo.rs @@ -7,7 +7,7 @@ impl BcCamera { pub async fn get_abilityinfo(&self) -> Result { let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_get = connection.subscribe(msg_num).await?; + let mut sub_get = connection.subscribe(MSG_ID_ABILITY_INFO, msg_num).await?; let get = Bc { meta: BcMeta { msg_id: MSG_ID_ABILITY_INFO, diff --git a/crates/core/src/bc_protocol/battery.rs b/crates/core/src/bc_protocol/battery.rs index ec4a91d..dbcc9ea 100644 --- a/crates/core/src/bc_protocol/battery.rs +++ b/crates/core/src/bc_protocol/battery.rs @@ -83,7 +83,7 @@ impl BcCamera { let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub = connection.subscribe(msg_num).await?; + let mut sub = connection.subscribe(MSG_ID_BATTERY_INFO, msg_num).await?; let msg = Bc { meta: BcMeta { diff --git a/crates/core/src/bc_protocol/connection/bcconn.rs b/crates/core/src/bc_protocol/connection/bcconn.rs index bae0408..2746cb6 100644 --- a/crates/core/src/bc_protocol/connection/bcconn.rs +++ b/crates/core/src/bc_protocol/connection/bcconn.rs @@ -18,8 +18,8 @@ type MsgHandler = dyn 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a #[derive(Default)] struct Subscriber { - /// Subscribers based on their Num - num: BTreeMap>>, + /// Subscribers based on their ID and their num + num: BTreeMap, Sender>>>, /// Subscribers based on their ID id: BTreeMap>, } @@ -85,12 +85,12 @@ impl BcConnection { Ok(()) } - pub async fn subscribe(&self, msg_num: u16) -> Result { + pub async fn subscribe(&self, msg_id: u32, msg_num: u16) -> Result { let (tx, rx) = channel(100); self.poll_commander - .send(PollCommand::AddSubscriber(msg_num, tx)) + .send(PollCommand::AddSubscriber(msg_id, Some(msg_num), tx)) .await?; - Ok(BcSubscription::new(rx, msg_num as u32, self)) + Ok(BcSubscription::new(rx, Some(msg_num as u32), self)) } /// Some messages are initiated by the camera. This creates a handler for them @@ -115,6 +115,21 @@ impl BcConnection { Ok(()) } + /// Some times we want to wait for a reply on a new message ID + /// to do this we wait for the next packet with a certain ID + /// grab it's message ID and then subscribe to that ID + /// + /// The command Snap that grabs a jpeg payload is an example of this + /// + /// This function creates a temporary handle to grab this single message + pub async fn subscribe_to_id(&self, msg_id: u32) -> Result { + let (tx, rx) = channel(100); + self.poll_commander + .send(PollCommand::AddSubscriber(msg_id, None, tx)) + .await?; + Ok(BcSubscription::new(rx, None, self)) + } + 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 { @@ -138,7 +153,7 @@ enum PollCommand { Bc(Box>), AddHandler(u32, Arc), RemoveHandler(u32), - AddSubscriber(u16, Sender>), + AddSubscriber(u32, Option, Sender>), } struct Poller { @@ -152,66 +167,79 @@ impl Poller { while let Some(command) = self.reciever.next().await { yield_now().await; match command { - PollCommand::Bc(boxed_response) => match *boxed_response { - Ok(response) => { - let msg_num = response.meta.msg_num; - let msg_id = response.meta.msg_id; + PollCommand::Bc(boxed_response) => { + match *boxed_response { + Ok(response) => { + let msg_num = response.meta.msg_num; + let msg_id = response.meta.msg_id; - let mut remove_it_num = false; - match ( - self.subscribers.id.get(&msg_id), - self.subscribers.num.get(&msg_num), - ) { - (Some(occ), _) => { - if let Some(reply) = occ(&response).await { - assert!(reply.meta.msg_num == response.meta.msg_num); - self.sink.send(Ok(reply)).await?; + match ( + self.subscribers.id.get(&msg_id), + self.subscribers.num.get_mut(&msg_id), + ) { + (Some(occ), _) => { + if let Some(reply) = occ(&response).await { + assert!(reply.meta.msg_num == response.meta.msg_num); + self.sink.send(Ok(reply)).await?; + } } - } - (None, Some(occ)) => { - if occ.capacity() == 0 { - warn!("Reaching limit of channel"); - warn!( - "Remaining: {} of {} message space for {} (ID: {})", - occ.capacity(), - occ.max_capacity(), - &msg_num, - &msg_id - ); - } else { - trace!( - "Remaining: {} of {} message space for {} (ID: {})", - occ.capacity(), - occ.max_capacity(), - &msg_num, - &msg_id + (None, Some(occ)) => { + let sender = + if let Some(sender) = occ.get(&Some(msg_num)).cloned() { + Some(sender) + } else if let Some(sender) = occ.get(&None).cloned() { + // Upgrade a None to a known MsgID + occ.remove(&None); + occ.insert(Some(msg_num), sender.clone()); + Some(sender) + } else { + None + }; + if let Some(sender) = sender { + if sender.capacity() == 0 { + warn!("Reaching limit of channel"); + warn!( + "Remaining: {} of {} message space for {} (ID: {})", + sender.capacity(), + sender.max_capacity(), + &msg_num, + &msg_id + ); + } else { + trace!( + "Remaining: {} of {} message space for {} (ID: {})", + sender.capacity(), + sender.max_capacity(), + &msg_num, + &msg_id + ); + } + if sender.send(Ok(response)).await.is_err() { + occ.remove(&Some(msg_num)); + } + } + } + (None, None) => { + debug!( + "Ignoring uninteresting message id {} (number: {})", + msg_id, msg_num ); + trace!("Contents: {:?}", response); } - if occ.send(Ok(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_num { - self.subscribers.num.remove(&msg_num); + Err(e) => { + for sub in self.subscribers.num.values() { + for sender in sub.values() { + let _ = sender.send(Err(e.clone())).await; + } + } + self.subscribers.num.clear(); + self.subscribers.id.clear(); + return Err(e); } } - Err(e) => { - for sub in self.subscribers.num.values() { - let _ = sub.send(Err(e.clone())).await; - } - self.subscribers.num.clear(); - self.subscribers.id.clear(); - return Err(e); - } - }, + } PollCommand::AddHandler(msg_id, handler) => { match self.subscribers.id.entry(msg_id) { Entry::Vacant(vac_entry) => { @@ -225,8 +253,14 @@ impl Poller { PollCommand::RemoveHandler(msg_id) => { self.subscribers.id.remove(&msg_id); } - PollCommand::AddSubscriber(msg_num, tx) => { - match self.subscribers.num.entry(msg_num) { + PollCommand::AddSubscriber(msg_id, msg_num, tx) => { + match self + .subscribers + .num + .entry(msg_id) + .or_default() + .entry(msg_num) + { Entry::Vacant(vac_entry) => { vac_entry.insert(tx); } diff --git a/crates/core/src/bc_protocol/connection/bcsub.rs b/crates/core/src/bc_protocol/connection/bcsub.rs index 02c89ac..0ec83d7 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: u32, + msg_num: Option, conn: &'a BcConnection, } @@ -89,7 +89,7 @@ pub type BcMediaStream<'b> = FramedRead impl<'a> BcSubscription<'a> { pub fn new( rx: Receiver>, - msg_num: u32, + msg_num: Option, conn: &'a BcConnection, ) -> BcSubscription<'a> { BcSubscription { @@ -100,7 +100,11 @@ impl<'a> BcSubscription<'a> { } pub async fn send(&self, bc: Bc) -> Result<()> { - assert!(bc.meta.msg_num as u32 == self.msg_num); + if let Some(msg_num) = self.msg_num { + assert!(bc.meta.msg_num as u32 == msg_num); + } else { + log::debug!("Sending message before msg_num has been aquired"); + } self.conn.send(bc).await?; Ok(()) } @@ -108,7 +112,12 @@ impl<'a> BcSubscription<'a> { pub async fn recv(&mut self) -> Result { let bc = self.rx.next().await.ok_or(Error::DroppedSubscriber)?; if let Ok(bc) = &bc { - assert!(bc.meta.msg_num as u32 == self.msg_num); + if let Some(msg_num) = self.msg_num { + assert!(bc.meta.msg_num as u32 == msg_num); + } else { + // Leaning number now + self.msg_num = Some(bc.meta.msg_num as u32); + } } bc } diff --git a/crates/core/src/bc_protocol/connection/discovery.rs b/crates/core/src/bc_protocol/connection/discovery.rs index 741a7e8..0c6433c 100644 --- a/crates/core/src/bc_protocol/connection/discovery.rs +++ b/crates/core/src/bc_protocol/connection/discovery.rs @@ -175,7 +175,7 @@ impl Discoverer { Ok(rx) } else { Err(Error::SimultaneousSubscription { - msg_num: (tid as u16), + msg_num: Some(tid as u16), }) } } diff --git a/crates/core/src/bc_protocol/errors.rs b/crates/core/src/bc_protocol/errors.rs index 5346f7f..fc79734 100644 --- a/crates/core/src/bc_protocol/errors.rs +++ b/crates/core/src/bc_protocol/errors.rs @@ -96,10 +96,10 @@ pub enum Error { GenError(#[error(source)] std::sync::Arc), /// Raised when a connection is subscrbed to more than once for msg_num - #[error(display = "Simultaneous subscription, {}", _0)] + #[error(display = "Simultaneous subscription, {:?}", _0)] SimultaneousSubscription { /// The message number that was subscribed to - msg_num: u16, + msg_num: Option, }, /// Raised when a connection is subscrbed to more than once for msg_id diff --git a/crates/core/src/bc_protocol/floodlight_status.rs b/crates/core/src/bc_protocol/floodlight_status.rs index 27f87ef..4705df0 100644 --- a/crates/core/src/bc_protocol/floodlight_status.rs +++ b/crates/core/src/bc_protocol/floodlight_status.rs @@ -45,7 +45,9 @@ impl BcCamera { let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_set = connection.subscribe(msg_num).await?; + let mut sub_set = connection + .subscribe(MSG_ID_FLOODLIGHT_MANUAL, msg_num) + .await?; let get = Bc { meta: BcMeta { diff --git a/crates/core/src/bc_protocol/ledstate.rs b/crates/core/src/bc_protocol/ledstate.rs index 7acca2e..f1c33c8 100644 --- a/crates/core/src/bc_protocol/ledstate.rs +++ b/crates/core/src/bc_protocol/ledstate.rs @@ -7,7 +7,7 @@ impl BcCamera { self.has_ability_ro("ledState").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_get = connection.subscribe(msg_num).await?; + let mut sub_get = connection.subscribe(MSG_ID_GET_LED_STATUS, msg_num).await?; let get = Bc { meta: BcMeta { msg_id: MSG_ID_GET_LED_STATUS, @@ -56,7 +56,7 @@ impl BcCamera { let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_set = connection.subscribe(msg_num).await?; + let mut sub_set = connection.subscribe(MSG_ID_SET_LED_STATUS, msg_num).await?; // led_version is a field recieved from the camera but not sent // we set to None to ensure we don't send it to the camera diff --git a/crates/core/src/bc_protocol/login.rs b/crates/core/src/bc_protocol/login.rs index ea9a10a..96d8e56 100644 --- a/crates/core/src/bc_protocol/login.rs +++ b/crates/core/src/bc_protocol/login.rs @@ -37,7 +37,7 @@ impl BcCamera { let credentials = self.get_credentials(); let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_login = connection.subscribe(msg_num).await?; + let mut sub_login = connection.subscribe(MSG_ID_LOGIN, msg_num).await?; // Login flow is: Send legacy login message, expect back a modern message with Encryption // details. Then, re-send the login as a modern login message. Expect back a device info diff --git a/crates/core/src/bc_protocol/logout.rs b/crates/core/src/bc_protocol/logout.rs index 2f80f8a..4b580d3 100644 --- a/crates/core/src/bc_protocol/logout.rs +++ b/crates/core/src/bc_protocol/logout.rs @@ -9,7 +9,7 @@ impl BcCamera { let credentials = self.get_credentials(); let connection = self.get_connection(); let msg_num = self.new_message_num(); - let sub_logout = connection.subscribe(msg_num).await?; + let sub_logout = connection.subscribe(MSG_ID_LOGOUT, msg_num).await?; let username = credentials.username.clone(); let password = credentials.password.as_ref().cloned().unwrap_or_default(); diff --git a/crates/core/src/bc_protocol/motion.rs b/crates/core/src/bc_protocol/motion.rs index a8fae78..f61f214 100644 --- a/crates/core/src/bc_protocol/motion.rs +++ b/crates/core/src/bc_protocol/motion.rs @@ -167,7 +167,7 @@ impl BcCamera { let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub = connection.subscribe(msg_num).await?; + let mut sub = connection.subscribe(MSG_ID_MOTION_REQUEST, msg_num).await?; let msg = Bc { meta: BcMeta { msg_id: MSG_ID_MOTION_REQUEST, @@ -202,7 +202,7 @@ impl BcCamera { /// This returns a data structure which can be used to /// query motion events pub async fn listen_on_motion(&self) -> Result { - let msg_num = self.start_motion_query().await?; + self.start_motion_query().await?; let connection = self.get_connection(); @@ -213,7 +213,7 @@ impl BcCamera { let mut set = JoinSet::new(); let channel_id = self.channel_id; set.spawn(async move { - let mut sub = connection.subscribe(msg_num).await?; + let mut sub = connection.subscribe_to_id(MSG_ID_MOTION).await?; loop { tokio::task::yield_now().await; diff --git a/crates/core/src/bc_protocol/ping.rs b/crates/core/src/bc_protocol/ping.rs index 93f388c..6426536 100644 --- a/crates/core/src/bc_protocol/ping.rs +++ b/crates/core/src/bc_protocol/ping.rs @@ -7,7 +7,7 @@ impl BcCamera { pub async fn ping(&self) -> Result<()> { let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_ping = connection.subscribe(msg_num).await?; + let mut sub_ping = connection.subscribe(MSG_ID_PING, msg_num).await?; let ping = Bc { meta: BcMeta { diff --git a/crates/core/src/bc_protocol/pirstate.rs b/crates/core/src/bc_protocol/pirstate.rs index bbd223b..83cd255 100644 --- a/crates/core/src/bc_protocol/pirstate.rs +++ b/crates/core/src/bc_protocol/pirstate.rs @@ -12,7 +12,7 @@ impl BcCamera { loop { retry_interval.tick().await; let msg_num = self.new_message_num(); - let mut sub_get = connection.subscribe(msg_num).await?; + let mut sub_get = connection.subscribe(MSG_ID_GET_PIR_ALARM, msg_num).await?; let get = Bc { meta: BcMeta { msg_id: MSG_ID_GET_PIR_ALARM, @@ -70,7 +70,9 @@ impl BcCamera { self.has_ability_rw("rfAlarm").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_set = connection.subscribe(msg_num).await?; + let mut sub_set = connection + .subscribe(MSG_ID_START_PIR_ALARM, msg_num) + .await?; let get = Bc { meta: BcMeta { diff --git a/crates/core/src/bc_protocol/ptz.rs b/crates/core/src/bc_protocol/ptz.rs index a90fb6e..1586934 100644 --- a/crates/core/src/bc_protocol/ptz.rs +++ b/crates/core/src/bc_protocol/ptz.rs @@ -25,7 +25,7 @@ impl BcCamera { self.has_ability_rw("control").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_set = connection.subscribe(msg_num).await?; + let mut sub_set = connection.subscribe(MSG_ID_PTZ_CONTROL, msg_num).await?; let direction_str = match direction { Direction::Up => "up", @@ -88,7 +88,7 @@ impl BcCamera { self.has_ability_rw("control").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_set = connection.subscribe(msg_num).await?; + let mut sub_set = connection.subscribe(MSG_ID_GET_PTZ_PRESET, msg_num).await?; let send = Bc { meta: BcMeta { @@ -136,7 +136,9 @@ impl BcCamera { self.has_ability_rw("control").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_set = connection.subscribe(msg_num).await?; + let mut sub_set = connection + .subscribe(MSG_ID_PTZ_CONTROL_PRESET, msg_num) + .await?; let command = if name.is_some() { "setPos" } else { "toPos" }; let send = Bc { diff --git a/crates/core/src/bc_protocol/reboot.rs b/crates/core/src/bc_protocol/reboot.rs index 4142679..6e95c0c 100644 --- a/crates/core/src/bc_protocol/reboot.rs +++ b/crates/core/src/bc_protocol/reboot.rs @@ -7,7 +7,7 @@ impl BcCamera { self.has_ability_rw("reboot").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub = connection.subscribe(msg_num).await?; + let mut sub = connection.subscribe(MSG_ID_REBOOT, msg_num).await?; let msg = Bc { meta: BcMeta { diff --git a/crates/core/src/bc_protocol/snap.rs b/crates/core/src/bc_protocol/snap.rs index 45855c7..2a698f1 100644 --- a/crates/core/src/bc_protocol/snap.rs +++ b/crates/core/src/bc_protocol/snap.rs @@ -1,4 +1,4 @@ -use futures::{StreamExt, TryStreamExt}; +// use futures::{StreamExt, TryStreamExt}; use super::{BcCamera, Error, Result}; use crate::bc::{model::*, xml::*}; @@ -8,7 +8,7 @@ impl BcCamera { pub async fn get_snapshot(&self) -> Result> { let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_get = connection.subscribe(msg_num).await?; + let mut sub_get = connection.subscribe(MSG_ID_SNAP, msg_num).await?; let get = Bc { meta: BcMeta { msg_id: MSG_ID_SNAP, @@ -57,17 +57,90 @@ impl BcCamera { .. }) = msg.body { - log::trace!("Got snap {} with size {}", filename, expected_size); + log::debug!("Got snap XML {} with size {}", filename, expected_size); + // Messages are now sent on ID 109 but not with the same message ID + // preumably because the camera considers it to be a new message rather + // than a reply + // + // This means we need to listen for the next 109 grab the message num and + // subscribe to it. This is what `subscribe_to_next` is for + let mut sub_get = connection.subscribe_to_id(MSG_ID_SNAP).await?; let expected_size = expected_size as usize; - let binary_stream = sub_get.payload_stream(); - let result: Vec<_> = binary_stream - .map_ok(|i| tokio_stream::iter(i).map(Result::Ok)) - .try_flatten() - .take(expected_size) - .try_collect() - .await?; - log::trace!("Got whole of the snap: {}", result.len()); + let mut result: Vec<_> = vec![]; + log::debug!("Waiting for packets on {}", msg_num); + let mut msg = sub_get.recv().await?; + + while msg.meta.response_code == 200 { + // sends 200 while more is to come + // 201 when finished + + if let BcBody::ModernMsg(ModernMsg { + extension: + Some(Extension { + binary_data: Some(1), + .. + }), + payload: Some(BcPayloads::Binary(data)), + }) = msg.body + { + result.extend_from_slice(&data); + } else { + return Err(Error::UnintelligibleReply { + reply: std::sync::Arc::new(Box::new(msg)), + why: "Expected binary data but got something else", + }); + } + log::debug!( + "Got packet size is now {} of {}", + result.len(), + expected_size + ); + msg = sub_get.recv().await?; + } + + if msg.meta.response_code == 201 { + // 201 means all binary data sent + if let BcBody::ModernMsg(ModernMsg { + extension: + Some(Extension { + binary_data: Some(1), + .. + }), + payload, + }) = msg.body + { + if let Some(BcPayloads::Binary(data)) = payload { + // Add last data if present (may be zero if preveious packet contained it) + result.extend_from_slice(&data); + } + log::debug!( + "Got all packets size is now {} of {}", + result.len(), + expected_size + ); + if result.len() != expected_size { + log::warn!("Snap did not recieve expected number of byes"); + } + } else { + return Err(Error::UnintelligibleReply { + reply: std::sync::Arc::new(Box::new(msg)), + why: "Expected binary data but got something else", + }); + } + } else { + // anything else is an error + return Err(Error::CameraServiceUnavaliable); + } + + // let binary_stream = sub_get.payload_stream(); + // let result: Vec<_>= binary_stream + // .map_ok(|i| tokio_stream::iter(i).map(Result::Ok)) + // .try_flatten() + // .take(expected_size) + // .try_collect() + // .await?; + log::debug!("Snapshot recieved: {} of {}", result.len(), expected_size); Ok(result) } else { Err(Error::UnintelligibleReply { diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs index 226c309..8dd312c 100644 --- a/crates/core/src/bc_protocol/stream.rs +++ b/crates/core/src/bc_protocol/stream.rs @@ -111,7 +111,7 @@ impl BcCamera { let handle = task::spawn(async move { tokio::task::yield_now().await; - let mut sub_video = connection.subscribe(msg_num).await?; + let mut sub_video = connection.subscribe(MSG_ID_VIDEO, msg_num).await?; // On an E1 and swann cameras: // - mainStream always has a value of 0 @@ -224,13 +224,14 @@ impl BcCamera { }, ); // debug!("Stream: Send Stop"); - sub_video.send(stop_video).await?; + let mut sub_stop = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?; + sub_stop.send(stop_video).await?; // debug!("Stream: Sent Stop"); tokio::select! { v = async { loop { - let msg = sub_video.recv().await?; + let msg = sub_stop.recv().await?; if let BcMeta { response_code: 200, msg_id: MSG_ID_VIDEO_STOP, @@ -268,7 +269,7 @@ impl BcCamera { } let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_video = connection.subscribe(msg_num).await?; + let mut sub_video = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?; // On an E1 and swann cameras: // - mainStream always has a value of 0 diff --git a/crates/core/src/bc_protocol/talk.rs b/crates/core/src/bc_protocol/talk.rs index f4e08c2..df787ab 100644 --- a/crates/core/src/bc_protocol/talk.rs +++ b/crates/core/src/bc_protocol/talk.rs @@ -17,7 +17,7 @@ impl BcCamera { let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub = connection.subscribe(msg_num).await?; + let mut sub = connection.subscribe(MSG_ID_TALKRESET, msg_num).await?; let msg = Bc { meta: BcMeta { @@ -60,7 +60,7 @@ impl BcCamera { pub async fn talk_ability(&self) -> Result { let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_get = connection.subscribe(msg_num).await?; + let mut sub_get = connection.subscribe(MSG_ID_TALKABILITY, msg_num).await?; let get = Bc { meta: BcMeta { msg_id: MSG_ID_TALKABILITY, @@ -120,7 +120,7 @@ impl BcCamera { let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub = connection.subscribe(msg_num).await?; + let mut sub = connection.subscribe(MSG_ID_TALKCONFIG, msg_num).await?; if &talk_config.audio_config.audio_type != "adpcm" { return Err(Error::UnknownTalkEncoding); @@ -182,7 +182,7 @@ impl BcCamera { let full_block_size = block_size + 4; // Block size + predictor state let msg_num = self.new_message_num(); - let sub = connection.subscribe(msg_num).await?; + let sub = connection.subscribe(MSG_ID_TALK, msg_num).await?; const BLOCK_PER_PAYLOAD: usize = 4; const BLOCK_HEADER_SIZE: usize = 4; @@ -261,7 +261,7 @@ impl BcCamera { let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub = connection.subscribe(msg_num).await?; + let mut sub = connection.subscribe(MSG_ID_TALKCONFIG, msg_num).await?; if &talk_config.audio_config.audio_type != "adpcm" { return Err(Error::UnknownTalkEncoding); @@ -323,7 +323,7 @@ impl BcCamera { let full_block_size = block_size + 4; // Block size + predictor state let msg_num = self.new_message_num(); - let sub = connection.subscribe(msg_num).await?; + let sub = connection.subscribe(MSG_ID_TALK, msg_num).await?; const BLOCK_PER_PAYLOAD: usize = 1; const BLOCK_HEADER_SIZE: usize = 4; diff --git a/crates/core/src/bc_protocol/time.rs b/crates/core/src/bc_protocol/time.rs index 593fd71..91aec3e 100644 --- a/crates/core/src/bc_protocol/time.rs +++ b/crates/core/src/bc_protocol/time.rs @@ -17,7 +17,7 @@ impl BcCamera { self.has_ability_ro("general").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_get_general = connection.subscribe(msg_num).await?; + let mut sub_get_general = connection.subscribe(MSG_ID_GET_GENERAL, msg_num).await?; let get = Bc { meta: BcMeta { msg_id: MSG_ID_GET_GENERAL, @@ -102,7 +102,7 @@ impl BcCamera { self.has_ability_rw("general").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_set_general = connection.subscribe(msg_num).await?; + let mut sub_set_general = connection.subscribe(MSG_ID_SET_GENERAL, msg_num).await?; let set = Bc::new_from_xml( BcMeta { msg_id: MSG_ID_SET_GENERAL, diff --git a/crates/core/src/bc_protocol/version.rs b/crates/core/src/bc_protocol/version.rs index b562f5a..df7779b 100644 --- a/crates/core/src/bc_protocol/version.rs +++ b/crates/core/src/bc_protocol/version.rs @@ -7,7 +7,7 @@ impl BcCamera { self.has_ability_ro("version").await?; let connection = self.get_connection(); let msg_num = self.new_message_num(); - let mut sub_version = connection.subscribe(msg_num).await?; + let mut sub_version = connection.subscribe(MSG_ID_VERSION, msg_num).await?; let version = Bc { meta: BcMeta { diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index 7e34d3a..98a195e 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -388,6 +388,7 @@ impl SnapThread { continue; } Err(neolink_core::Error::CameraServiceUnavaliable) => { + log::debug!("Snap not supported"); futures::future::pending().await } Err(e) => return Err(e.into()), @@ -405,7 +406,7 @@ struct BatteryLevelThread { impl BatteryLevelThread { async fn run(&mut self) -> Result<()> { let mut tries = 0; - let base_duration = Duration::from_millis(500); + let base_duration = Duration::from_secs(15); loop { tokio::time::sleep(base_duration.saturating_mul(tries)).await; let battery = match self.camera.battery_info().await { @@ -419,6 +420,7 @@ impl BatteryLevelThread { continue; } Err(neolink_core::Error::CameraServiceUnavaliable) => { + log::debug!("Battery not supported"); futures::future::pending().await } Err(e) => return Err(e.into()), diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index 4c48b28..3d18063 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -228,7 +228,10 @@ async fn listen_on_camera(cam_config: Arc, mqtt_config: &MqttConfi .send_message("status/battery_level", format!("{}", data).as_str(), true) .await .with_context(|| { - format!("Failed to publish battery level over MQTT for {}", camera_name) + format!( + "Failed to publish battery level over MQTT for {}", + camera_name + ) })?; } _ => {}