From e093151db6ab37704af07bd5eb21331a3c4b4bab Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Thu, 10 Aug 2023 15:17:12 +0700 Subject: [PATCH 1/5] Add a debug option to the camera config --- crates/core/src/bc/codex.rs | 6 +++++ crates/core/src/bc/de.rs | 26 ++++++++++++------- crates/core/src/bc/model.rs | 7 +++++ crates/core/src/bc_protocol.rs | 16 ++++++++---- .../src/bc_protocol/connection/discovery.rs | 7 +++-- .../src/bc_protocol/connection/tcpsource.rs | 8 +++++- .../src/bc_protocol/connection/udpsource.rs | 19 ++++++++++---- src/config.rs | 7 +++++ src/utils.rs | 1 + 9 files changed, 74 insertions(+), 23 deletions(-) diff --git a/crates/core/src/bc/codex.rs b/crates/core/src/bc/codex.rs index 8c0d3aa..8ee9bc8 100644 --- a/crates/core/src/bc/codex.rs +++ b/crates/core/src/bc/codex.rs @@ -15,6 +15,12 @@ pub(crate) struct BcCodex { } impl BcCodex { + pub(crate) fn new_with_debug(credentials: Credentials) -> Self { + let mut context = BcContext::new(credentials); + + context.debug_on(); + Self { context } + } pub(crate) fn new(credentials: Credentials) -> Self { Self { context: BcContext::new(credentials), diff --git a/crates/core/src/bc/de.rs b/crates/core/src/bc/de.rs index 6014485..515c5c1 100644 --- a/crates/core/src/bc/de.rs +++ b/crates/core/src/bc/de.rs @@ -116,10 +116,12 @@ fn bc_modern_msg<'a>( let mut encrypted_len = None; // Now we'll take the buffer that Nom gave a ref to and parse it. let extension = if ext_len > 0 { - log::trace!( - "Extension Txt: {:?}", - String::from_utf8(processed_ext_buf.to_vec()).unwrap_or("Not Text".to_string()) - ); + if context.debug { + println!( + "Extension Txt: {:?}", + String::from_utf8(processed_ext_buf.to_vec()).unwrap_or("Not Text".to_string()) + ); + } // Apply the XML parse function, but throw away the reference to decrypted in the Ok and // Err case. This error-error-error thing is the same idiom Nom uses internally. let parsed = Extension::try_parse(processed_ext_buf).map_err(|_| { @@ -182,8 +184,9 @@ fn bc_modern_msg<'a>( if context.in_bin_mode.contains(&(header.msg_num)) || in_binary { payload = match (context.get_encrypted(), encrypted_len) { (EncryptionProtocol::FullAes(_), Some(encrypted_len)) => { - log::trace!("Binary: {:X?}", &processed_payload_buf[0..30]); - + // if if context.debug { + // log::trace!("Binary: {:X?}", &processed_payload_buf[0..30]); + // } Some(BcPayloads::Binary( processed_payload_buf[0..(encrypted_len as usize)].to_vec(), )) @@ -191,10 +194,13 @@ fn bc_modern_msg<'a>( _ => Some(BcPayloads::Binary(payload_buf.to_vec())), }; } else { - log::trace!( - "Payload Txt: {:?}", - String::from_utf8(processed_payload_buf.to_vec()).unwrap_or("Not Text".to_string()) - ); + if context.debug { + println!( + "Payload Txt: {:?}", + String::from_utf8(processed_payload_buf.to_vec()) + .unwrap_or("Not Text".to_string()) + ); + } let xml = BcXml::try_parse(processed_payload_buf.as_slice()).map_err(|_| { error!("header.msg_id: {}", header.msg_id); error!( diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index 50e9483..219b1b9 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -210,6 +210,7 @@ pub(crate) struct BcContext { pub(crate) credentials: Credentials, pub(crate) in_bin_mode: HashSet, pub(crate) encryption_protocol: EncryptionProtocol, + pub(crate) debug: bool, } impl Bc { @@ -251,6 +252,7 @@ impl BcContext { credentials, in_bin_mode: HashSet::new(), encryption_protocol: EncryptionProtocol::Unencrypted, + debug: false, } } @@ -260,6 +262,7 @@ impl BcContext { credentials: Default::default(), in_bin_mode: HashSet::new(), encryption_protocol, + debug: false, } } @@ -279,6 +282,10 @@ impl BcContext { pub(crate) fn binary_off(&mut self, msg_id: u16) { self.in_bin_mode.remove(&msg_id); } + + pub(crate) fn debug_on(&mut self) { + self.debug = true; + } } impl BcHeader { diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index 2691c7b..5259e8a 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -87,6 +87,8 @@ pub struct BcCameraOpt { pub discovery: DiscoveryMethods, /// Credentials for login pub credentials: Credentials, + /// Toggle debug print of underlying data + pub debug: bool, } /// Used to choose the print format of various status messages like battery levels @@ -314,16 +316,20 @@ impl BcCamera { let (sink, source): (BcConnSink, BcConnSource) = { match BcCamera::find_camera(options).await? { CameraLocation::Tcp(addr) => { - let (x, r) = TcpSource::new(addr, &username, passwd.as_ref()) + let (x, r) = TcpSource::new(addr, &username, passwd.as_ref(), options.debug) .await? .split(); (Box::new(x), Box::new(r)) } CameraLocation::Udp(discovery) => { - let (x, r) = - UdpSource::new_from_discovery(discovery, &username, passwd.as_ref()) - .await? - .split(); + let (x, r) = UdpSource::new_from_discovery( + discovery, + &username, + passwd.as_ref(), + options.debug, + ) + .await? + .split(); (Box::new(x), Box::new(r)) } } diff --git a/crates/core/src/bc_protocol/connection/discovery.rs b/crates/core/src/bc_protocol/connection/discovery.rs index 8e6d220..b85daab 100644 --- a/crates/core/src/bc_protocol/connection/discovery.rs +++ b/crates/core/src/bc_protocol/connection/discovery.rs @@ -1030,8 +1030,11 @@ impl Discovery { pub(crate) async fn check_tcp(&self, addr: SocketAddr, channel_id: u8) -> Result<()> { let username = "admin"; let password = Some("123456"); - let mut tcp_source = - timeout(*MAXIMUM_WAIT, TcpSource::new(addr, username, password)).await??; + let mut tcp_source = timeout( + *MAXIMUM_WAIT, + TcpSource::new(addr, username, password, false), + ) + .await??; let md5_username = md5_string(username, Md5Trunc::ZeroLast); let md5_password = password diff --git a/crates/core/src/bc_protocol/connection/tcpsource.rs b/crates/core/src/bc_protocol/connection/tcpsource.rs index 96b2cbb..a77262d 100644 --- a/crates/core/src/bc_protocol/connection/tcpsource.rs +++ b/crates/core/src/bc_protocol/connection/tcpsource.rs @@ -18,11 +18,17 @@ impl TcpSource { addr: SocketAddr, username: T, password: Option, + debug: bool, ) -> Result { let stream = connect_to(addr).await?; + let codex = if debug { + BcCodex::new_with_debug(Credentials::new(username, password)) + } else { + BcCodex::new(Credentials::new(username, password)) + }; Ok(Self { - inner: Framed::new(stream, BcCodex::new(Credentials::new(username, password))), + inner: Framed::new(stream, codex), }) } } diff --git a/crates/core/src/bc_protocol/connection/udpsource.rs b/crates/core/src/bc_protocol/connection/udpsource.rs index d87ecb7..f9feaff 100644 --- a/crates/core/src/bc_protocol/connection/udpsource.rs +++ b/crates/core/src/bc_protocol/connection/udpsource.rs @@ -43,15 +43,20 @@ impl UdpSource { camera_id: i32, username: T, password: Option, + debug: bool, ) -> Result { let stream = Arc::new(connect().await?); - Self::new_from_socket(stream, addr, client_id, camera_id, username, password).await + Self::new_from_socket( + stream, addr, client_id, camera_id, username, password, debug, + ) + .await } pub(crate) async fn new_from_discovery, U: Into>( discovery: DiscoveryResult, username: T, password: Option, + debug: bool, ) -> Result { // Ensure that the discovery keep alive are all stopped here // We now handle all coms in UdpSource @@ -62,6 +67,7 @@ impl UdpSource { discovery.camera_id, username, password, + debug, ) .await } @@ -73,14 +79,17 @@ impl UdpSource { camera_id: i32, username: T, password: Option, + debug: bool, ) -> Result { let bcudp_source = BcUdpSource::new_from_socket(stream, addr).await?; let payload_source = bcudp_source.into_payload_source(client_id, camera_id); let async_read = payload_source.into_async_read().compat(); - let framed = Framed::new( - async_read, - BcCodex::new(Credentials::new(username, password)), - ); + let codex = if debug { + BcCodex::new_with_debug(Credentials::new(username, password)) + } else { + BcCodex::new(Credentials::new(username, password)) + }; + let framed = Framed::new(async_read, codex); Ok(Self { inner: framed }) } diff --git a/src/config.rs b/src/config.rs index aa8d075..95ed506 100644 --- a/src/config.rs +++ b/src/config.rs @@ -126,6 +126,9 @@ pub(crate) struct CameraConfig { #[serde(default = "default_true", alias = "enable")] pub(crate) enabled: bool, + + #[serde(default = "default_false", alias = "verbose")] + pub(crate) debug: bool, } #[derive(Debug, Deserialize, Validate, Clone)] @@ -191,6 +194,10 @@ const fn default_true() -> bool { true } +const fn default_false() -> bool { + true +} + fn default_mqtt() -> Option { None } diff --git a/src/utils.rs b/src/utils.rs index 9cd2d4e..c7808fa 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -97,6 +97,7 @@ impl AddressOrUid { username: camera_config.username.clone(), password: camera_config.password.clone(), }, + debug: camera_config.debug, }; trace!("Camera Info: {:?}", options); From 623fcb3fd12f14ff3120ac8855d955ed699a596a Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sat, 12 Aug 2023 11:06:28 +0700 Subject: [PATCH 2/5] Optimisation of the UDP acknoledgment flushing --- .../src/bc_protocol/connection/udpsource.rs | 119 ++++++++++-------- src/rtsp/states/streaming.rs | 2 +- 2 files changed, 66 insertions(+), 55 deletions(-) diff --git a/crates/core/src/bc_protocol/connection/udpsource.rs b/crates/core/src/bc_protocol/connection/udpsource.rs index f9feaff..47b83e1 100644 --- a/crates/core/src/bc_protocol/connection/udpsource.rs +++ b/crates/core/src/bc_protocol/connection/udpsource.rs @@ -174,6 +174,7 @@ impl BcUdpSource { ack_interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms ack_latency: Default::default(), + flush_state: FlushState::Ready, } } } @@ -208,6 +209,7 @@ impl Sink<(BcUdp, SocketAddr)> for BcUdpSource { } #[allow(dead_code)] +#[derive(Debug)] enum State { Normal, // Normal recieve Flushing, // Used to send ack packets and things in the buffer @@ -266,6 +268,11 @@ impl AckLatency { } } +enum FlushState { + Ready, + Flush, +} + pub(crate) struct UdpPayloadSource { inner: BcUdpSource, client_id: i32, @@ -284,6 +291,7 @@ pub(crate) struct UdpPayloadSource { /// This `resend_interval` controls how ofen we do this resend_interval: Interval, ack_latency: AckLatency, + flush_state: FlushState, } impl UdpPayloadSource { @@ -341,6 +349,7 @@ impl UdpPayloadSource { fn maintanence(&mut self, cx: &mut Context<'_>) { // Check for periodic resends + log::info!("Maintaince"); if self.resend_interval.poll_tick(cx).is_ready() { for (_, resend) in self.sent.iter() { self.send_buffer.push_back(BcUdp::Data(resend.clone())); @@ -349,6 +358,7 @@ impl UdpPayloadSource { if self.ack_interval.poll_tick(cx).is_ready() // && self.packets_want > 0 { + log::info!("Pushing Ack"); let ack = BcUdp::Ack(self.build_send_ack()); self.send_buffer.push_back(ack); self.state = State::Flushing; @@ -362,6 +372,7 @@ impl Stream for UdpPayloadSource { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let camera_addr = self.inner.addr; let this = self.get_mut(); + log::info!("this.state: {:?}", this.state); match this.state { State::Normal => { // this.state = State::YieldNow; @@ -438,17 +449,24 @@ impl Stream for UdpPayloadSource { // } } } - State::Flushing => match this.poll_flush_unpin(cx) { - Poll::Ready(Ok(())) => { + State::Flushing => { + log::info!("Fushing: {}", this.send_buffer.len()); + if this.send_buffer.is_empty() { this.state = State::Normal; + } else { + match this.poll_flush_unpin(cx) { + Poll::Ready(Ok(())) => { + this.state = State::Normal; + } + Poll::Ready(Err(e)) => { + return Poll::Ready(Some(Err(e))); + } + Poll::Pending => { + return Poll::Pending; + } + } } - Poll::Ready(Err(e)) => { - return Poll::Ready(Some(Err(e))); - } - Poll::Pending => { - return Poll::Pending; - } - }, + } State::Closed => { return Poll::Ready(Some(Err(IoError::from(ErrorKind::ConnectionAborted)))); } @@ -469,17 +487,9 @@ impl Sink> for UdpPayloadSource { cx: &mut Context<'_>, ) -> Poll> { let this = self.get_mut(); - match this.state { - State::Normal | State::YieldNow => this - .inner - .poll_ready_unpin(cx) - .map_err(|e| IoError::new(ErrorKind::Other, e)), - State::Flushing => this - .inner - .poll_flush_unpin(cx) - .map_err(|e| IoError::new(ErrorKind::Other, e)), - State::Closed => Poll::Ready(Err(IoError::from(ErrorKind::ConnectionAborted))), - } + this.inner + .poll_ready_unpin(cx) + .map_err(|e| IoError::new(ErrorKind::Other, e)) } fn start_send(self: Pin<&mut Self>, item: Vec) -> std::result::Result<(), Self::Error> { let this = self.get_mut(); @@ -492,7 +502,8 @@ impl Sink> for UdpPayloadSource { this.packets_sent += 1; this.send_buffer.push_back(BcUdp::Data(udp_data)); } - if let Some(first) = this.send_buffer.pop_front() { + // Push through whats on the buffer + for first in this.send_buffer.drain(..) { if let BcUdp::Data(data) = &first { let id = data.packet_id; this.sent.insert(id, data.clone()); @@ -508,44 +519,44 @@ impl Sink> for UdpPayloadSource { self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll> { + log::info!("poll_flush"); let this = self.get_mut(); - match this - .inner - .poll_flush_unpin(cx) - .map_err(|e| IoError::new(ErrorKind::Other, e)) - { - Poll::Ready(Ok(())) => { - if let Some(next) = this.send_buffer.pop_front() { - match this - .inner - .poll_ready_unpin(cx) - .map_err(|e| IoError::new(ErrorKind::Other, e)) - { - Poll::Ready(Ok(())) => { - if let BcUdp::Data(data) = &next { - let id = data.packet_id; - this.sent.insert(id, data.clone()); - } - - let addr = this.inner.addr; - Pin::new(&mut this.inner) - .start_send((next, addr)) - .map_err(|e| IoError::new(ErrorKind::Other, e))?; - } - poll => { - return poll; + let res = match this.flush_state { + FlushState::Ready => match this.poll_ready_unpin(cx) { + Poll::Ready(Ok(())) => { + for first in this.send_buffer.drain(..) { + if let BcUdp::Data(data) = &first { + let id = data.packet_id; + this.sent.insert(id, data.clone()); } + let addr = this.inner.addr; + Pin::new(&mut this.inner) + .start_send((first, addr)) + .map_err(|e| IoError::new(ErrorKind::Other, e))?; } - } else { - return Poll::Ready(Ok(())); + this.flush_state = FlushState::Flush; + cx.waker().wake_by_ref(); + Poll::Pending + } + poll => poll, + }, + FlushState::Flush => { + match this + .inner + .poll_flush_unpin(cx) + .map_err(|e| IoError::new(ErrorKind::Other, e)) + { + Poll::Ready(Ok(())) => { + this.flush_state = FlushState::Ready; + Poll::Ready(Ok(())) + } + poll => poll, } } - poll => { - return poll; - } - } - cx.waker().wake_by_ref(); - Poll::Pending + }; + + log::info!("poll_flush end: {:?}", res); + res } fn poll_close( diff --git a/src/rtsp/states/streaming.rs b/src/rtsp/states/streaming.rs index 01dbf11..2f6f600 100644 --- a/src/rtsp/states/streaming.rs +++ b/src/rtsp/states/streaming.rs @@ -79,7 +79,7 @@ impl Camera { loop { tokio::task::yield_now().await; // debug!("Straming: Get"); - let data = timeout(Duration::from_secs(15), stream_data.get_data()) + let data = timeout(Duration::from_secs(90), stream_data.get_data()) .await .with_context(|| "Timed out waiting for new Media Frame")??; // debug!("Straming: Got"); From f23f28c12e6d88e6273f556282d3577616e12286 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sat, 12 Aug 2023 11:11:01 +0700 Subject: [PATCH 3/5] Log cleanup --- crates/core/src/bc_protocol/connection/udpsource.rs | 12 ++++++------ src/rtsp/states/streaming.rs | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/core/src/bc_protocol/connection/udpsource.rs b/crates/core/src/bc_protocol/connection/udpsource.rs index 47b83e1..2583b16 100644 --- a/crates/core/src/bc_protocol/connection/udpsource.rs +++ b/crates/core/src/bc_protocol/connection/udpsource.rs @@ -349,7 +349,7 @@ impl UdpPayloadSource { fn maintanence(&mut self, cx: &mut Context<'_>) { // Check for periodic resends - log::info!("Maintaince"); + // log::info!("Maintaince"); if self.resend_interval.poll_tick(cx).is_ready() { for (_, resend) in self.sent.iter() { self.send_buffer.push_back(BcUdp::Data(resend.clone())); @@ -358,7 +358,7 @@ impl UdpPayloadSource { if self.ack_interval.poll_tick(cx).is_ready() // && self.packets_want > 0 { - log::info!("Pushing Ack"); + // log::info!("Pushing Ack"); let ack = BcUdp::Ack(self.build_send_ack()); self.send_buffer.push_back(ack); self.state = State::Flushing; @@ -372,7 +372,7 @@ impl Stream for UdpPayloadSource { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let camera_addr = self.inner.addr; let this = self.get_mut(); - log::info!("this.state: {:?}", this.state); + // log::info!("this.state: {:?}", this.state); match this.state { State::Normal => { // this.state = State::YieldNow; @@ -450,7 +450,7 @@ impl Stream for UdpPayloadSource { } } State::Flushing => { - log::info!("Fushing: {}", this.send_buffer.len()); + // log::info!("Fushing: {}", this.send_buffer.len()); if this.send_buffer.is_empty() { this.state = State::Normal; } else { @@ -519,7 +519,7 @@ impl Sink> for UdpPayloadSource { self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll> { - log::info!("poll_flush"); + // log::info!("poll_flush"); let this = self.get_mut(); let res = match this.flush_state { FlushState::Ready => match this.poll_ready_unpin(cx) { @@ -555,7 +555,7 @@ impl Sink> for UdpPayloadSource { } }; - log::info!("poll_flush end: {:?}", res); + log::trace!("poll_flush end: {:?}", res); res } diff --git a/src/rtsp/states/streaming.rs b/src/rtsp/states/streaming.rs index 2f6f600..01dbf11 100644 --- a/src/rtsp/states/streaming.rs +++ b/src/rtsp/states/streaming.rs @@ -79,7 +79,7 @@ impl Camera { loop { tokio::task::yield_now().await; // debug!("Straming: Get"); - let data = timeout(Duration::from_secs(90), stream_data.get_data()) + let data = timeout(Duration::from_secs(15), stream_data.get_data()) .await .with_context(|| "Timed out waiting for new Media Frame")??; // debug!("Straming: Got"); From a8a306301bf0e763d86797574785249ebd5c8020 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 14 Aug 2023 11:52:18 +0700 Subject: [PATCH 4/5] Rework low level UDP layer --- .../core/src/bc_protocol/connection/bcconn.rs | 18 +- .../src/bc_protocol/connection/udpsource.rs | 380 ++++++++---------- src/utils.rs | 2 +- 3 files changed, 174 insertions(+), 226 deletions(-) diff --git a/crates/core/src/bc_protocol/connection/bcconn.rs b/crates/core/src/bc_protocol/connection/bcconn.rs index 29b549d..08270cb 100644 --- a/crates/core/src/bc_protocol/connection/bcconn.rs +++ b/crates/core/src/bc_protocol/connection/bcconn.rs @@ -55,10 +55,12 @@ impl BcConnection { let runtime = tokio::runtime::Builder::new_current_thread() .build() .unwrap(); - runtime.block_on( + let result = runtime.block_on( PollSender::new(thread_poll_commander) .send_all(&mut source.map(|bc| Ok(PollCommand::Bc(Box::new(bc))))), - ) + ); + log::info!("PollSender Bc {:?}", result); + result }); rx_thread.spawn(async move { handle.await??; @@ -166,6 +168,18 @@ enum PollCommand { Disconnect, } +impl std::fmt::Debug for PollCommand { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PollCommand::Bc(_) => f.write_str("PollCommand::Bc"), + PollCommand::AddHandler(_, _) => f.write_str("PollCommand::AddHandler"), + PollCommand::RemoveHandler(_) => f.write_str("PollCommand::RemoveHandler"), + PollCommand::AddSubscriber(_, _, _) => f.write_str("PollCommand::AddSubscriber"), + PollCommand::Disconnect => f.write_str("PollCommand::Disconnect"), + } + } +} + struct Poller { subscribers: Subscriber, sink: Sender>, diff --git a/crates/core/src/bc_protocol/connection/udpsource.rs b/crates/core/src/bc_protocol/connection/udpsource.rs index 2583b16..2fdebcf 100644 --- a/crates/core/src/bc_protocol/connection/udpsource.rs +++ b/crates/core/src/bc_protocol/connection/udpsource.rs @@ -9,20 +9,21 @@ use futures::{ sink::{Sink, SinkExt}, stream::{IntoAsyncRead, Stream, StreamExt, TryStreamExt}, }; -use log::*; use rand::{seq::SliceRandom, thread_rng}; use std::collections::BTreeMap; -use std::collections::VecDeque; use std::io::{Error as IoError, ErrorKind, Result as IoResult}; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; +use tokio::sync::mpsc::channel; use tokio::{ net::UdpSocket, time::{interval, Duration, Instant, Interval}, }; +use tokio_stream::wrappers::ReceiverStream; use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt}; +use tokio_util::sync::PollSender; use tokio_util::{ codec::{Decoder, Encoder, Framed}, udp::UdpFramed, @@ -82,7 +83,7 @@ impl UdpSource { debug: bool, ) -> Result { let bcudp_source = BcUdpSource::new_from_socket(stream, addr).await?; - let payload_source = bcudp_source.into_payload_source(client_id, camera_id); + let payload_source = bcudp_source.into_payload_source(client_id, camera_id).await; let async_read = payload_source.into_async_read().compat(); let codex = if debug { BcCodex::new_with_debug(Credentials::new(username, password)) @@ -160,22 +161,12 @@ impl BcUdpSource { }) } - pub(crate) fn into_payload_source(self, client_id: i32, camera_id: i32) -> UdpPayloadSource { - UdpPayloadSource { - inner: self, - client_id, - camera_id, - packets_sent: 0, - packets_want: 0, - sent: Default::default(), - recieved: Default::default(), - state: State::Normal, - send_buffer: Default::default(), - ack_interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms - resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms - ack_latency: Default::default(), - flush_state: FlushState::Ready, - } + pub(crate) async fn into_payload_source( + self, + client_id: i32, + camera_id: i32, + ) -> UdpPayloadSource { + UdpPayloadSource::new(self, client_id, camera_id).await } } @@ -268,21 +259,21 @@ impl AckLatency { } } -enum FlushState { - Ready, - Flush, +pub(crate) struct UdpPayloadSource { + inner_stream: ReceiverStream>>, + inner_sink: PollSender>, } -pub(crate) struct UdpPayloadSource { +struct UdpPayloadInner { inner: BcUdpSource, + thread_stream: PollSender>>, + thread_sink: ReceiverStream>, client_id: i32, camera_id: i32, packets_sent: u32, packets_want: u32, sent: BTreeMap, recieved: BTreeMap>, - state: State, - send_buffer: VecDeque, /// Offical Client does ack every 10ms if we don't also do this the camera /// seems to think we have a poor connection and will abort /// This `ack_interval` controls how ofen we do this @@ -291,10 +282,95 @@ pub(crate) struct UdpPayloadSource { /// This `resend_interval` controls how ofen we do this resend_interval: Interval, ack_latency: AckLatency, - flush_state: FlushState, } +impl UdpPayloadInner { + fn new( + inner: BcUdpSource, + thread_stream: PollSender>>, + thread_sink: ReceiverStream>, + client_id: i32, + camera_id: i32, + ) -> Self { + Self { + inner, + thread_stream, + thread_sink, + client_id, + camera_id, + packets_sent: 0, + packets_want: 0, + sent: Default::default(), + recieved: Default::default(), + ack_interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms + resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms + ack_latency: Default::default(), + } + } + async fn run(&mut self) -> Result<()> { + let camera_addr = self.inner.addr; + tokio::select! { + _ = self.ack_interval.tick() => { + let ack = BcUdp::Ack(self.build_send_ack()); + self.inner.feed((ack, camera_addr)).await?; + Result::Ok(()) + }, + _ = self.resend_interval.tick() => { + for (_, resend) in self.sent.iter() { + self.inner.feed((BcUdp::Data(resend.clone()), camera_addr)).await?; + } + Ok(()) + }, + v = self.thread_sink.next() => { + // Incomming from application + // Outgoing on socket + let item = v.ok_or(Error::DroppedConnection)?; + + for chunk in item.chunks(MTU - UDPDATA_HEADER_SIZE) { + let udp_data = UdpData { + connection_id: self.camera_id, + packet_id: self.packets_sent, + payload: chunk.to_vec(), + }; + self.packets_sent += 1; + self.sent.insert(udp_data.packet_id, udp_data.clone()); + self.inner.feed((BcUdp::Data(udp_data), camera_addr)).await?; + } + Ok(()) + } + v = self.inner.next() => { + // Incomming from socket + // Outgoing to application + let (item, addr) = v.ok_or(Error::DroppedConnection)??; + if addr == camera_addr { + match item { + BcUdp::Discovery(_disc) => {}, + BcUdp::Ack(ack) => { + if ack.connection_id == self.client_id { + self.handle_ack(ack); + } + }, + BcUdp::Data(data) => { + if data.connection_id == self.client_id { + let packet_id = data.packet_id; + if packet_id >= self.packets_want { + // error!("packets_want: {}", this.packets_want); + self.recieved.insert(packet_id, data.payload); + } + } + }, + } + } + Ok(()) + } + }?; + while let Some(payload) = self.recieved.remove(&self.packets_want) { + self.packets_want += 1; + self.thread_stream.send(Ok(payload)).await?; + } + self.inner.flush().await?; + Ok(()) + } -impl UdpPayloadSource { fn build_send_ack(&self) -> UdpAck { if self.packets_want > 0 { let mut first_missing: u32 = self.packets_want; @@ -346,22 +422,39 @@ impl UdpPayloadSource { } self.ack_latency.feed_ack(); } +} +impl UdpPayloadSource { + async fn new(inner: BcUdpSource, client_id: i32, camera_id: i32) -> Self { + let (inner_sink, thread_sink) = channel(100); + let (thread_stream, inner_stream) = channel(100); - fn maintanence(&mut self, cx: &mut Context<'_>) { - // Check for periodic resends - // log::info!("Maintaince"); - if self.resend_interval.poll_tick(cx).is_ready() { - for (_, resend) in self.sent.iter() { - self.send_buffer.push_back(BcUdp::Data(resend.clone())); + let mut payload_inner = UdpPayloadInner::new( + inner, + PollSender::new(thread_stream), + ReceiverStream::new(thread_sink), + client_id, + camera_id, + ); + tokio::task::spawn(async move { + loop { + match payload_inner.run().await { + Ok(()) => {} + Err(e) => { + // log::error!("payload_inner: {:?}", e); + // Pass error up + let _ = payload_inner + .thread_stream + .send(Err(IoError::new(ErrorKind::Other, e.clone()))) + .await; + return Result::<()>::Err(e); + } + } } - } - if self.ack_interval.poll_tick(cx).is_ready() - // && self.packets_want > 0 - { - // log::info!("Pushing Ack"); - let ack = BcUdp::Ack(self.build_send_ack()); - self.send_buffer.push_back(ack); - self.state = State::Flushing; + }); + + UdpPayloadSource { + inner_stream: ReceiverStream::new(inner_stream), + inner_sink: PollSender::new(inner_sink), } } } @@ -369,113 +462,16 @@ impl UdpPayloadSource { impl Stream for UdpPayloadSource { type Item = IoResult>; - fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - let camera_addr = self.inner.addr; - let this = self.get_mut(); - // log::info!("this.state: {:?}", this.state); - match this.state { - State::Normal => { - // this.state = State::YieldNow; - // Handle resend events - this.maintanence(cx); - // Data ready to go - if let Some(payload) = this.recieved.remove(&this.packets_want) { - this.packets_want += 1; - // error!("packets_want: {}", this.packets_want); - return Poll::Ready(Some(Ok(payload))); - } - // Normal behaviors - match this.inner.poll_next_unpin(cx) { - Poll::Ready(Some(Ok(( - BcUdp::Data(UdpData { - connection_id, - packet_id, - payload, - }), - addr, - )))) if connection_id == this.client_id - && addr == camera_addr - && packet_id >= this.packets_want => - { - if packet_id == this.packets_want { - this.packets_want += 1; - // error!("packets_want: {}", this.packets_want); - let ack = BcUdp::Ack(this.build_send_ack()); - this.send_buffer.push_back(ack); - return Poll::Ready(Some(Ok(payload))); - } else { - this.recieved.insert(packet_id, payload); - } - } - Poll::Ready(Some(Ok(( - BcUdp::Data(UdpData { - connection_id, - packet_id, - .. - }), - addr, - )))) if connection_id == this.client_id - && addr == camera_addr - && packet_id < this.packets_want => - { - trace!("UdpPayloadSource.RecievedPacket: Old data: {}", packet_id); - } - Poll::Ready(Some(Ok(( - BcUdp::Ack(ack @ UdpAck { connection_id, .. }), - addr, - )))) if connection_id == this.client_id && addr == camera_addr => { - this.handle_ack(ack); - // Rather then immediatly flush wait for the next call - // this.state = State::Flushing; - } - Poll::Ready(Some(Err(e))) => { - return Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e)))); - } - Poll::Ready(None) => { - return Poll::Ready(None); - } - Poll::Pending => { - return Poll::Pending; - } - Poll::Ready(Some(Ok((bcudp, addr)))) => { - trace!( - "UdpPayloadSource.RecievedPacker: UnexpectedData {:?} from {}", - bcudp, - addr - ); - } // _ => { - // trace!("UDPSource.RecievedPacker: Other?"); - // // Repeat/unintersting packet - // } - } - } - State::Flushing => { - // log::info!("Fushing: {}", this.send_buffer.len()); - if this.send_buffer.is_empty() { - this.state = State::Normal; - } else { - match this.poll_flush_unpin(cx) { - Poll::Ready(Ok(())) => { - this.state = State::Normal; - } - Poll::Ready(Err(e)) => { - return Poll::Ready(Some(Err(e))); - } - Poll::Pending => { - return Poll::Pending; - } - } - } - } - State::Closed => { - return Poll::Ready(Some(Err(IoError::from(ErrorKind::ConnectionAborted)))); - } - State::YieldNow => { - this.state = State::Normal; - } + delegate! { + to Pin::new(&mut self.inner_stream) { + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll>; + } + } + + delegate! { + to self.inner_stream { + fn size_hint(&self) -> (usize, Option); } - cx.waker().wake_by_ref(); - Poll::Pending } } @@ -486,97 +482,35 @@ impl Sink> for UdpPayloadSource { self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll> { - let this = self.get_mut(); - this.inner + self.get_mut() + .inner_sink .poll_ready_unpin(cx) .map_err(|e| IoError::new(ErrorKind::Other, e)) } fn start_send(self: Pin<&mut Self>, item: Vec) -> std::result::Result<(), Self::Error> { - let this = self.get_mut(); - for chunk in item.chunks(MTU - UDPDATA_HEADER_SIZE) { - let udp_data = UdpData { - connection_id: this.camera_id, - packet_id: this.packets_sent, - payload: chunk.to_vec(), - }; - this.packets_sent += 1; - this.send_buffer.push_back(BcUdp::Data(udp_data)); - } - // Push through whats on the buffer - for first in this.send_buffer.drain(..) { - if let BcUdp::Data(data) = &first { - let id = data.packet_id; - this.sent.insert(id, data.clone()); - } - let addr = this.inner.addr; - Pin::new(&mut this.inner) - .start_send((first, addr)) - .map_err(|e| IoError::new(ErrorKind::Other, e))?; - } - Ok(()) + self.get_mut() + .inner_sink + .start_send_unpin(item) + .map_err(|e| IoError::new(ErrorKind::Other, e)) } fn poll_flush( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll> { - // log::info!("poll_flush"); - let this = self.get_mut(); - let res = match this.flush_state { - FlushState::Ready => match this.poll_ready_unpin(cx) { - Poll::Ready(Ok(())) => { - for first in this.send_buffer.drain(..) { - if let BcUdp::Data(data) = &first { - let id = data.packet_id; - this.sent.insert(id, data.clone()); - } - let addr = this.inner.addr; - Pin::new(&mut this.inner) - .start_send((first, addr)) - .map_err(|e| IoError::new(ErrorKind::Other, e))?; - } - this.flush_state = FlushState::Flush; - cx.waker().wake_by_ref(); - Poll::Pending - } - poll => poll, - }, - FlushState::Flush => { - match this - .inner - .poll_flush_unpin(cx) - .map_err(|e| IoError::new(ErrorKind::Other, e)) - { - Poll::Ready(Ok(())) => { - this.flush_state = FlushState::Ready; - Poll::Ready(Ok(())) - } - poll => poll, - } - } - }; - - log::trace!("poll_flush end: {:?}", res); - res + self.get_mut() + .inner_sink + .poll_flush_unpin(cx) + .map_err(|e| IoError::new(ErrorKind::Other, e)) } fn poll_close( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll> { - let this = self.get_mut(); - if let State::Closed = this.state { - return Poll::Ready(Ok(())); - } - - match this.poll_flush_unpin(cx) { - Poll::Ready(Ok(())) => { - this.state = State::Closed; - this.inner - .poll_close_unpin(cx) - .map_err(|e| IoError::new(ErrorKind::Other, e)) - } - poll => poll, - } + self.get_mut() + .inner_sink + .poll_close_unpin(cx) + .map_err(|e| IoError::new(ErrorKind::Other, e)) } } diff --git a/src/utils.rs b/src/utils.rs index c7808fa..6d9add7 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -17,7 +17,7 @@ pub(crate) fn timeout(future: F) -> tokio::time::Timeout where F: std::future::Future, { - tokio::time::timeout(tokio::time::Duration::from_secs(5), future) + tokio::time::timeout(tokio::time::Duration::from_secs(15), future) } pub(crate) enum AddressOrUid { From d0c85419eb11fdc6713ec1b33a2a0e0e2e11d6e4 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 14 Aug 2023 13:05:21 +0700 Subject: [PATCH 5/5] Low level UDP timeout --- crates/core/src/bc_protocol/connection/udpsource.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/core/src/bc_protocol/connection/udpsource.rs b/crates/core/src/bc_protocol/connection/udpsource.rs index 2fdebcf..141316f 100644 --- a/crates/core/src/bc_protocol/connection/udpsource.rs +++ b/crates/core/src/bc_protocol/connection/udpsource.rs @@ -19,7 +19,7 @@ use std::task::{Context, Poll}; use tokio::sync::mpsc::channel; use tokio::{ net::UdpSocket, - time::{interval, Duration, Instant, Interval}, + time::{interval, sleep, Duration, Instant, Interval, Sleep}, }; use tokio_stream::wrappers::ReceiverStream; use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt}; @@ -282,6 +282,8 @@ struct UdpPayloadInner { /// This `resend_interval` controls how ofen we do this resend_interval: Interval, ack_latency: AckLatency, + // Tracks the timeout of recieving ANY packet + recv_timeout: Pin>, } impl UdpPayloadInner { fn new( @@ -304,6 +306,9 @@ impl UdpPayloadInner { ack_interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms ack_latency: Default::default(), + // A packet of ANY kind must be recieved in the last second + // since there are 10 acks a second 3s should be fine + recv_timeout: Box::pin(sleep(Duration::from_secs(3))), } } async fn run(&mut self) -> Result<()> { @@ -360,7 +365,11 @@ impl UdpPayloadInner { }, } } + self.recv_timeout.as_mut().reset(Instant::now() + Duration::from_secs(3)); Ok(()) + }, + _ = self.recv_timeout.as_mut() => { + Err(Error::DroppedConnection) } }?; while let Some(payload) = self.recieved.remove(&self.packets_want) {