Merge branch 'refractor/udp_layer'

This commit is contained in:
Andrew committed 2023-08-15 19:00:09 +07:00
commit 95ce97c85e
10 files changed
+260 -241

No files matched your search

+6
View File
@@ -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),
+16 -10
View File
@@ -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!(
+7
View File
@@ -210,6 +210,7 @@ pub(crate) struct BcContext {
pub(crate) credentials: Credentials,
pub(crate) in_bin_mode: HashSet<u16>,
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 {
+11 -5
View File
@@ -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))
}
}
@@ -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<Result<Bc>>,
@@ -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
@@ -18,11 +18,17 @@ impl TcpSource {
addr: SocketAddr,
username: T,
password: Option<U>,
debug: bool,
) -> Result<TcpSource> {
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),
})
}
}
@@ -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},
time::{interval, sleep, Duration, Instant, Interval, Sleep},
};
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,
@@ -43,15 +44,20 @@ impl UdpSource {
camera_id: i32,
username: T,
password: Option<U>,
debug: bool,
) -> Result<Self> {
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<T: Into<String>, U: Into<String>>(
discovery: DiscoveryResult,
username: T,
password: Option<U>,
debug: bool,
) -> Result<Self> {
// Ensure that the discovery keep alive are all stopped here
// We now handle all coms in UdpSource
@@ -62,6 +68,7 @@ impl UdpSource {
discovery.camera_id,
username,
password,
debug,
)
.await
}
@@ -73,14 +80,17 @@ impl UdpSource {
camera_id: i32,
username: T,
password: Option<U>,
debug: bool,
) -> Result<Self> {
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 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 })
}
@@ -151,21 +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(),
}
pub(crate) async fn into_payload_source(
self,
client_id: i32,
camera_id: i32,
) -> UdpPayloadSource {
UdpPayloadSource::new(self, client_id, camera_id).await
}
}
@@ -199,6 +200,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
@@ -258,15 +260,20 @@ impl AckLatency {
}
pub(crate) struct UdpPayloadSource {
inner_stream: ReceiverStream<IoResult<Vec<u8>>>,
inner_sink: PollSender<Vec<u8>>,
}
struct UdpPayloadInner {
inner: BcUdpSource,
thread_stream: PollSender<IoResult<Vec<u8>>>,
thread_sink: ReceiverStream<Vec<u8>>,
client_id: i32,
camera_id: i32,
packets_sent: u32,
packets_want: u32,
sent: BTreeMap<u32, UdpData>,
recieved: BTreeMap<u32, Vec<u8>>,
state: State,
send_buffer: VecDeque<BcUdp>,
/// 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
@@ -275,9 +282,104 @@ pub(crate) struct UdpPayloadSource {
/// 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<Box<Sleep>>,
}
impl UdpPayloadInner {
fn new(
inner: BcUdpSource,
thread_stream: PollSender<IoResult<Vec<u8>>>,
thread_sink: ReceiverStream<Vec<u8>>,
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(),
// 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<()> {
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);
}
}
},
}
}
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) {
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;
@@ -329,20 +431,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
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
{
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),
}
}
}
@@ -350,105 +471,16 @@ impl UdpPayloadSource {
impl Stream for UdpPayloadSource {
type Item = IoResult<Vec<u8>>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let camera_addr = self.inner.addr;
let this = self.get_mut();
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 => 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<Option<Self::Item>>;
}
}
delegate! {
to self.inner_stream {
fn size_hint(&self) -> (usize, Option<usize>);
}
cx.waker().wake_by_ref();
Poll::Pending
}
}
@@ -459,104 +491,35 @@ impl Sink<Vec<u8>> for UdpPayloadSource {
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<std::result::Result<(), Self::Error>> {
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))),
}
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<u8>) -> 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));
}
if let Some(first) = this.send_buffer.pop_front() {
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<std::result::Result<(), Self::Error>> {
let this = self.get_mut();
match this
.inner
self.get_mut()
.inner_sink
.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;
}
}
} else {
return Poll::Ready(Ok(()));
}
}
poll => {
return poll;
}
}
cx.waker().wake_by_ref();
Poll::Pending
}
fn poll_close(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<std::result::Result<(), Self::Error>> {
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))
}
}
+7
View File
@@ -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<MqttConfig> {
None
}
+2 -1
View File
@@ -17,7 +17,7 @@ pub(crate) fn timeout<F>(future: F) -> tokio::time::Timeout<F>
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 {
@@ -97,6 +97,7 @@ impl AddressOrUid {
username: camera_config.username.clone(),
password: camera_config.password.clone(),
},
debug: camera_config.debug,
};
trace!("Camera Info: {:?}", options);