Add simple timeouts
This commit is contained in:
1 parent
fa155df974
commit
ac0703dbfd
5 files changed
+55
-68
No files matched your search
@@ -1,4 +1,4 @@
|
||||
use crate::{bc, Credentials};
|
||||
use crate::bc;
|
||||
use futures::stream::StreamExt;
|
||||
use log::*;
|
||||
use std::net::ToSocketAddrs;
|
||||
@@ -7,6 +7,7 @@ use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};
|
||||
use Md5Trunc::*;
|
||||
|
||||
mod connection;
|
||||
mod credentials;
|
||||
mod errors;
|
||||
mod keepalive;
|
||||
mod ledstate;
|
||||
@@ -24,6 +25,7 @@ mod time;
|
||||
mod version;
|
||||
|
||||
pub(crate) use connection::*;
|
||||
pub(crate) use credentials::*;
|
||||
pub use errors::Error;
|
||||
pub use ledstate::LightState;
|
||||
pub use login::MaxEncryption;
|
||||
@@ -36,15 +38,6 @@ pub use stream::{StreamData, StreamKind};
|
||||
|
||||
pub(crate) type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
impl From<crossbeam_channel::RecvTimeoutError> for Error {
|
||||
fn from(k: crossbeam_channel::RecvTimeoutError) -> Self {
|
||||
match k {
|
||||
crossbeam_channel::RecvTimeoutError::Timeout => Error::Timeout,
|
||||
crossbeam_channel::RecvTimeoutError::Disconnected => Error::TimeoutDisconnected,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// This is the primary struct of this library when interacting with the camera
|
||||
///
|
||||
@@ -96,7 +89,7 @@ impl BcCamera {
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::Timeout)
|
||||
Err(Error::CannotInitCamera)
|
||||
}
|
||||
|
||||
///
|
||||
@@ -166,7 +159,7 @@ impl BcCamera {
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::Timeout)
|
||||
Err(Error::CannotInitCamera)
|
||||
}
|
||||
|
||||
///
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::BcSubscription;
|
||||
use crate::{bc::model::*, Error, Result};
|
||||
use crate::{bc::model::*, timeout, Error, Result};
|
||||
use futures::sink::{Sink, SinkExt};
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use log::*;
|
||||
@@ -68,7 +68,7 @@ impl BcConnection {
|
||||
|
||||
pub(super) async fn send(&self, bc: Bc) -> crate::Result<()> {
|
||||
trace!("send Wait: {:?}", bc);
|
||||
self.sink.lock().await.send(bc).await?;
|
||||
timeout(self.sink.lock().await.send(bc)).await??;
|
||||
trace!("send Complete");
|
||||
Ok(())
|
||||
}
|
||||
@@ -122,8 +122,6 @@ impl BcConnection {
|
||||
) -> Result<()> {
|
||||
match response {
|
||||
Ok(response) => {
|
||||
// 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;
|
||||
|
||||
@@ -139,7 +137,20 @@ impl BcConnection {
|
||||
}
|
||||
}
|
||||
(None, Some(occ)) => {
|
||||
trace!("occ.full: {}/{}", occ.capacity(), occ.max_capacity());
|
||||
if occ.capacity() == 0 {
|
||||
warn!("Reaching limit of channel.");
|
||||
warn!(
|
||||
"Remaining: {} of {} message space",
|
||||
occ.capacity(),
|
||||
occ.max_capacity()
|
||||
);
|
||||
} else {
|
||||
trace!(
|
||||
"Remaining: {} of {} message space",
|
||||
occ.capacity(),
|
||||
occ.max_capacity()
|
||||
);
|
||||
}
|
||||
if occ.send(Ok(response)).await.is_err() {
|
||||
remove_it_num = true;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::BcConnection;
|
||||
use crate::bcmedia::codex::BcMediaCodex;
|
||||
use crate::{bc::model::*, Error, Result};
|
||||
use crate::{bc::model::*, timeout, Error, Result};
|
||||
use futures::stream::{IntoAsyncRead, Stream, StreamExt, TryStreamExt};
|
||||
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
|
||||
use std::pin::Pin;
|
||||
@@ -94,7 +94,9 @@ impl<'a> BcSubscription<'a> {
|
||||
}
|
||||
|
||||
pub async fn recv(&mut self) -> Result<Bc> {
|
||||
let bc = self.rx.next().await.ok_or(Error::DroppedSubscriber)?;
|
||||
let bc = timeout(self.rx.next())
|
||||
.await?
|
||||
.ok_or(Error::DroppedSubscriber)?;
|
||||
if let Ok(bc) = &bc {
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
}
|
||||
|
||||
@@ -35,14 +35,22 @@ pub enum Error {
|
||||
#[error(display = "Dropped connection")]
|
||||
BroadcastDroppedConnectionTry(#[error(source)] tokio::sync::broadcast::error::TryRecvError),
|
||||
|
||||
/// Raised when the RX_TIMEOUT is reach
|
||||
/// Raised when the TIMEOUT is reach
|
||||
#[error(display = "Timeout")]
|
||||
Timeout,
|
||||
Timeout(#[error(source)] std::sync::Arc<tokio::time::error::Elapsed>),
|
||||
|
||||
/// Raised when a timeout fails in a non standard way such as timeout during shutdown
|
||||
#[error(display = "TimeoutError")]
|
||||
TimeoutError(#[error(source)] tokio::time::error::Error),
|
||||
|
||||
/// Raised when connection is dropped because the timeout is reach
|
||||
#[error(display = "Dropped connection")]
|
||||
TimeoutDisconnected,
|
||||
|
||||
/// Raised when a camera cannot be connected to ay any of the given addresses
|
||||
#[error(display = "Cannot contact camera at given address")]
|
||||
CannotInitCamera,
|
||||
|
||||
/// Raised when failed to login to the camera
|
||||
#[error(display = "Credential error")]
|
||||
AuthFailed,
|
||||
@@ -162,6 +170,12 @@ impl From<local_ip_address::Error> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<tokio::time::error::Elapsed> for Error {
|
||||
fn from(k: tokio::time::error::Elapsed) -> Self {
|
||||
Error::Timeout(std::sync::Arc::new(k))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<nom::Err<NomErrorType<'a>>> for Error {
|
||||
fn from(k: nom::Err<NomErrorType<'a>>) -> Self {
|
||||
match k {
|
||||
|
||||
+14
-47
@@ -38,56 +38,23 @@ pub mod bcudp;
|
||||
/// Most commands will either return their `Ok(result)` or this `Err(Error)`
|
||||
pub use bc_protocol::Error;
|
||||
|
||||
pub(crate) use bc_protocol::Result;
|
||||
pub(crate) use bc_protocol::{Credentials, Result};
|
||||
|
||||
pub(crate) type NomErrorType<'a> = nom::error::VerboseError<&'a [u8]>;
|
||||
|
||||
// Used for caching the credentials
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Credentials {
|
||||
username: String,
|
||||
password: Option<String>,
|
||||
lazy_static::lazy_static! {
|
||||
/// This is a high level tiemout for the app as a whole. Not the lowlevel io ones
|
||||
///
|
||||
/// This is used to timeout when the primary send and receive channels of Bc packets
|
||||
/// is full for too long. This can happen if messages are not pulled from the endpoints
|
||||
/// fast enough or if there is an unexpected bug
|
||||
pub(crate) static ref TIMEOUT: tokio::time::Duration = tokio::time::Duration::from_secs(60);
|
||||
}
|
||||
|
||||
impl Default for Credentials {
|
||||
/// Default credentials for some reolink cameras
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
username: "admin".to_string(),
|
||||
password: Some("123456".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Credentials {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"username", &self.username)
|
||||
.entry(&"password", &"******")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
use std::convert::TryInto;
|
||||
impl Credentials {
|
||||
pub(crate) fn new<T: Into<String>, U: Into<String>>(username: T, password: Option<U>) -> Self {
|
||||
Self {
|
||||
username: username.into(),
|
||||
password: password.map(|t| t.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a convience function to make an AES key from the login password and the NONCE
|
||||
/// negotiated during login
|
||||
pub(crate) fn make_aeskey<T: AsRef<str>>(&self, nonce: T) -> [u8; 16] {
|
||||
let key_phrase = format!(
|
||||
"{}-{}",
|
||||
nonce.as_ref(),
|
||||
self.password.clone().unwrap_or_default()
|
||||
);
|
||||
let key_phrase_hash = format!("{:X}\0", md5::compute(key_phrase))
|
||||
.to_uppercase()
|
||||
.into_bytes();
|
||||
key_phrase_hash[0..16].try_into().unwrap()
|
||||
}
|
||||
/// A convience future to timeout with the default timeout specified in [`TIMEOUT`]
|
||||
pub(crate) fn timeout<F>(future: F) -> tokio::time::Timeout<F>
|
||||
where
|
||||
F: std::future::Future,
|
||||
{
|
||||
tokio::time::timeout(*TIMEOUT, future)
|
||||
}
|
||||
Reference in new issue
Block a user