More error tracing
Signed-off-by: QuantumEntangledAndy <sheepchaan@gmail.com>
This commit is contained in:
1 parent
c8be843ebc
commit
e4016a8d97
16 files changed
+241
-248
No files matched your search
@@ -86,13 +86,17 @@ impl Decoder for BcCodex {
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
extension:
|
||||
Some(Extension {
|
||||
binary_data: Some(1),
|
||||
binary_data: Some(on_off),
|
||||
..
|
||||
}),
|
||||
..
|
||||
}) = bc.body
|
||||
{
|
||||
self.context.binary_on(bc.meta.msg_num);
|
||||
if on_off == 0 {
|
||||
self.context.binary_off(bc.meta.msg_num);
|
||||
} else {
|
||||
self.context.binary_on(bc.meta.msg_num);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(bc))
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::xml::{BcPayloads, BcXml};
|
||||
use super::xml_crypto;
|
||||
use crate::Error;
|
||||
use bytes::{Buf, BytesMut};
|
||||
use log::*;
|
||||
use nom::{
|
||||
bytes::streaming::take, combinator::*, error::context as error_context, number::streaming::*,
|
||||
sequence::*, Parser,
|
||||
@@ -111,6 +112,7 @@ fn bc_modern_msg<'a>(
|
||||
}
|
||||
};
|
||||
|
||||
let mut in_binary = false;
|
||||
// Now we'll take the buffer that Nom gave a ref to and parse it.
|
||||
let extension = if ext_len > 0 {
|
||||
// Apply the XML parse function, but throw away the reference to decrypted in the Ok and
|
||||
@@ -122,6 +124,14 @@ fn bc_modern_msg<'a>(
|
||||
ErrorKind::MapRes,
|
||||
))
|
||||
})?;
|
||||
if let Extension {
|
||||
binary_data: Some(1),
|
||||
..
|
||||
} = parsed
|
||||
{
|
||||
// In binary so tell the current context that we need to treat the payload as binary
|
||||
in_binary = true;
|
||||
}
|
||||
Some(parsed)
|
||||
} else {
|
||||
None
|
||||
@@ -152,12 +162,19 @@ fn bc_modern_msg<'a>(
|
||||
} if (response_code & 0xff) == 0x02 => EncryptionProtocol::BCEncrypt, // This is AES but the first packet with the NONCE is BCEcrypt, since the NONCE in this packet is required to build the AES key
|
||||
_ => context.get_encrypted().clone(),
|
||||
};
|
||||
|
||||
let processed_payload_buf =
|
||||
xml_crypto::decrypt(header.channel_id as u32, payload_buf, &encryption_protocol);
|
||||
if context.in_bin_mode.contains(&(header.msg_num)) {
|
||||
if context.in_bin_mode.contains(&(header.msg_num)) || in_binary {
|
||||
payload = Some(BcPayloads::Binary(payload_buf.to_vec()));
|
||||
} else {
|
||||
let xml = BcXml::try_parse(processed_payload_buf.as_slice()).map_err(|_| {
|
||||
error!("header.msg_id: {}", header.msg_id);
|
||||
error!(
|
||||
"processed_payload_buf: {:X?}::{:?}",
|
||||
processed_payload_buf,
|
||||
std::str::from_utf8(&processed_payload_buf)
|
||||
);
|
||||
Err::Error(make_error(
|
||||
buf,
|
||||
"Unable to parse Payload XML",
|
||||
|
||||
@@ -55,13 +55,6 @@ pub struct BcCamera {
|
||||
credentials: Credentials,
|
||||
}
|
||||
|
||||
impl Drop for BcCamera {
|
||||
fn drop(&mut self) {
|
||||
debug!("Dropping camera");
|
||||
self.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
impl BcCamera {
|
||||
///
|
||||
/// Create a new camera interface with this address and channel ID
|
||||
@@ -210,9 +203,9 @@ impl BcCamera {
|
||||
SocketAddrOrUid::Uid(uid) => {
|
||||
debug!("Trying uid {}", uid);
|
||||
// TODO Make configurable
|
||||
let allow_local = false;
|
||||
let allow_local = true;
|
||||
let allow_remote = false;
|
||||
let allow_relay = true;
|
||||
let allow_relay = false;
|
||||
|
||||
let discovery = {
|
||||
let mut set = tokio::task::JoinSet::new();
|
||||
@@ -312,15 +305,6 @@ impl BcCamera {
|
||||
self.connection.clone()
|
||||
}
|
||||
|
||||
/// This will drop the connection.
|
||||
pub fn disconnect(&mut self) {
|
||||
// Stop polling now. We don't need it for a disconnect
|
||||
//
|
||||
// It will also ensure that when we drop the connection we don't
|
||||
// get an error for read return zero bytes from the polling thread;
|
||||
self.connection.stop_polling();
|
||||
}
|
||||
|
||||
// Certains commands like logout need the username and password
|
||||
// this command will return
|
||||
// This will only work after login
|
||||
|
||||
@@ -9,10 +9,7 @@ use std::sync::Arc;
|
||||
use tokio::sync::mpsc::{channel, Sender};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use tokio::{
|
||||
sync::RwLock,
|
||||
task::{self, JoinHandle},
|
||||
};
|
||||
use tokio::{sync::RwLock, task::JoinSet};
|
||||
|
||||
type Subscriber = Arc<RwLock<BTreeMap<u16, Sender<Bc>>>>;
|
||||
pub(crate) type BcConnSink = Box<dyn Sink<Bc, Error = Error> + Send + Sync + Unpin>;
|
||||
@@ -26,7 +23,8 @@ pub(crate) type BcConnSource = Box<dyn Stream<Item = Result<Bc>> + Send + Sync +
|
||||
pub struct BcConnection {
|
||||
sink: Arc<Mutex<BcConnSink>>,
|
||||
subscribers: Subscriber,
|
||||
rx_thread: Mutex<Option<JoinHandle<()>>>,
|
||||
#[allow(dead_code)] // Not dead we just need to hold a reference to keep it alive
|
||||
rx_thread: JoinSet<()>,
|
||||
}
|
||||
|
||||
impl BcConnection {
|
||||
@@ -35,7 +33,9 @@ impl BcConnection {
|
||||
|
||||
let subs = subscribers.clone();
|
||||
|
||||
let rx_thread = task::spawn(async move {
|
||||
let mut rx_thread = JoinSet::new();
|
||||
|
||||
rx_thread.spawn(async move {
|
||||
loop {
|
||||
trace!("packet Wait");
|
||||
let packet = source.next().await;
|
||||
@@ -59,16 +59,10 @@ impl BcConnection {
|
||||
Ok(BcConnection {
|
||||
sink: Arc::new(Mutex::new(sink)),
|
||||
subscribers,
|
||||
rx_thread: Mutex::new(Some(rx_thread)),
|
||||
rx_thread,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn stop_polling(&self) {
|
||||
if let Some(t) = self.rx_thread.blocking_lock().take() {
|
||||
t.abort()
|
||||
};
|
||||
}
|
||||
|
||||
pub(super) async fn send(&self, bc: Bc) -> crate::Result<()> {
|
||||
trace!("send Wait: {:?}", bc);
|
||||
self.sink.lock().await.send(bc).await?;
|
||||
@@ -121,12 +115,3 @@ impl BcConnection {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BcConnection {
|
||||
fn drop(&mut self) {
|
||||
debug!("Shutting down BcConnection...");
|
||||
if let Some(t) = self.rx_thread.get_mut().take() {
|
||||
t.abort()
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -30,25 +30,35 @@ use tokio::{
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::udp::UdpFramed;
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
struct RegisterResult {
|
||||
reg: SocketAddr,
|
||||
dmap: Option<SocketAddr>,
|
||||
dev: Option<SocketAddr>,
|
||||
client_id: i32,
|
||||
sid: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
struct ConnectResult {
|
||||
addr: SocketAddr,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
sid: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
struct UidLookupResults {
|
||||
reg: SocketAddr,
|
||||
relay: SocketAddr,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum ConnectionKind {
|
||||
Local,
|
||||
Relay,
|
||||
}
|
||||
|
||||
pub(crate) struct Discovery {}
|
||||
|
||||
const MTU: u32 = 1030;
|
||||
@@ -191,24 +201,33 @@ impl Discoverer {
|
||||
|
||||
async fn retry_send_multi<F, T>(
|
||||
&self,
|
||||
disc: UdpDiscovery,
|
||||
mut disc: UdpDiscovery,
|
||||
dests: &[SocketAddr],
|
||||
map: F,
|
||||
) -> Result<T>
|
||||
where
|
||||
F: Fn(UdpDiscovery, SocketAddr) -> Option<T>,
|
||||
{
|
||||
disc.tid = 0; // Must be random to avoid simulatenous subscription errors
|
||||
let mut set = FuturesUnordered::new();
|
||||
for dest in dests.iter() {
|
||||
info!("Future push: {}", dest);
|
||||
set.push(self.retry_send(disc.clone(), *dest, &map));
|
||||
}
|
||||
|
||||
// Get what ever completes first
|
||||
while let Some(result) = set.next().await {
|
||||
if result.is_ok() {
|
||||
return result;
|
||||
match result {
|
||||
Ok(ret) => {
|
||||
// info!("Future pop OK");
|
||||
return Ok(ret);
|
||||
}
|
||||
Err(_e) => {
|
||||
// info!("Future pop Err: {:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
// info!("set: empty");
|
||||
Err(Error::DiscoveryTimeout)
|
||||
}
|
||||
|
||||
@@ -315,7 +334,7 @@ impl Discoverer {
|
||||
client_id: i32,
|
||||
register_result: &RegisterResult,
|
||||
) -> Result<ConnectResult> {
|
||||
let (addr, local_tid, local_did) = self
|
||||
let (addr, local_tid, local_did, conn_kind) = self
|
||||
.handle_incoming(|bc, addr| {
|
||||
trace!("bc: {:?}", bc);
|
||||
match (bc, register_result) {
|
||||
@@ -334,7 +353,7 @@ impl Discoverer {
|
||||
..
|
||||
},
|
||||
) if cid == client_id && &sid == register_sid && &addr == register_dmap => {
|
||||
Some((addr, tid, did))
|
||||
Some((addr, tid, did, ConnectionKind::Relay))
|
||||
}
|
||||
(
|
||||
UdpDiscovery {
|
||||
@@ -351,19 +370,25 @@ impl Discoverer {
|
||||
..
|
||||
},
|
||||
) if cid == client_id && &sid == register_sid && &addr == register_dev => {
|
||||
Some((addr, tid, did))
|
||||
Some((addr, tid, did, ConnectionKind::Local))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
|
||||
let conn = match conn_kind {
|
||||
ConnectionKind::Local => "local",
|
||||
ConnectionKind::Relay => "map",
|
||||
}
|
||||
.to_string();
|
||||
|
||||
let msg = UdpDiscovery {
|
||||
tid: local_tid,
|
||||
payload: UdpXml {
|
||||
c2d_a: Some(C2dA {
|
||||
sid: register_result.sid,
|
||||
conn: "map".to_string(),
|
||||
conn,
|
||||
cid: client_id,
|
||||
did: local_did,
|
||||
mtu: MTU,
|
||||
@@ -389,51 +414,80 @@ impl Discoverer {
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(ConnectResult {
|
||||
let result = ConnectResult {
|
||||
addr,
|
||||
client_id,
|
||||
sid: register_result.sid,
|
||||
camera_id: local_did,
|
||||
})
|
||||
};
|
||||
|
||||
match conn_kind {
|
||||
ConnectionKind::Local => {
|
||||
self.confirm_map(&result, register_result.reg, result.addr)
|
||||
.await?;
|
||||
}
|
||||
ConnectionKind::Relay => {
|
||||
self.confirm_relay(&result, register_result.reg).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn client_initiated_connect(
|
||||
&self,
|
||||
local_sid: u32,
|
||||
client_id: i32,
|
||||
dev_addr: SocketAddr,
|
||||
register_result: &RegisterResult,
|
||||
) -> Result<ConnectResult> {
|
||||
let tid = generate_tid();
|
||||
|
||||
let msg = UdpDiscovery {
|
||||
tid,
|
||||
payload: UdpXml {
|
||||
c2d_t: Some(C2dT {
|
||||
sid: local_sid,
|
||||
cid: client_id,
|
||||
mtu: MTU,
|
||||
conn: "local".to_string(),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
if let RegisterResult {
|
||||
dev: Some(dev_addr),
|
||||
..
|
||||
} = ®ister_result
|
||||
{
|
||||
let msg = UdpDiscovery {
|
||||
tid,
|
||||
payload: UdpXml {
|
||||
c2d_t: Some(C2dT {
|
||||
sid: register_result.sid,
|
||||
cid: register_result.client_id,
|
||||
mtu: MTU,
|
||||
conn: "local".to_string(),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
let (final_addr, local_did) = self
|
||||
.retry_send(msg, dev_addr, |bc, addr| match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
d2c_cfm: Some(D2cCfm { cid, did, sid, .. }),
|
||||
..
|
||||
},
|
||||
} if cid == client_id && sid == local_sid => Some((addr, did)),
|
||||
_ => None,
|
||||
})
|
||||
.await?;
|
||||
let (final_addr, local_did) = self
|
||||
.retry_send(msg, *dev_addr, |bc, addr| match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
d2c_cfm: Some(D2cCfm { cid, did, sid, .. }),
|
||||
..
|
||||
},
|
||||
} if cid == register_result.client_id && sid == register_result.sid => {
|
||||
Some((addr, did))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(ConnectResult {
|
||||
addr: final_addr,
|
||||
camera_id: local_did,
|
||||
})
|
||||
let result = ConnectResult {
|
||||
addr: final_addr,
|
||||
client_id: register_result.client_id,
|
||||
sid: register_result.sid,
|
||||
camera_id: local_did,
|
||||
};
|
||||
|
||||
self.confirm_map(&result, register_result.reg, *dev_addr)
|
||||
.await?;
|
||||
|
||||
Ok(result)
|
||||
} else {
|
||||
Err(Error::NoDev)
|
||||
}
|
||||
}
|
||||
|
||||
/// Register our local ip address with the reolink servers
|
||||
@@ -442,8 +496,7 @@ impl Discoverer {
|
||||
&self,
|
||||
uid: &str,
|
||||
client_id: i32,
|
||||
reg_addr: SocketAddr,
|
||||
relay_addr: SocketAddr,
|
||||
lookup: &UidLookupResults,
|
||||
) -> Result<RegisterResult> {
|
||||
let tid = generate_tid();
|
||||
let local_addr = SocketAddr::new(local_ip()?, self.local_addr().port());
|
||||
@@ -461,8 +514,8 @@ impl Discoverer {
|
||||
port: local_port,
|
||||
},
|
||||
relay: IpPort {
|
||||
ip: relay_addr.ip().to_string(),
|
||||
port: relay_addr.port(),
|
||||
ip: lookup.relay.ip().to_string(),
|
||||
port: lookup.relay.port(),
|
||||
},
|
||||
cid: client_id,
|
||||
family: local_family,
|
||||
@@ -476,7 +529,7 @@ impl Discoverer {
|
||||
|
||||
// Send and await acceptance
|
||||
let (sid, dmap, dev) = self
|
||||
.retry_send(msg, reg_addr, |bc, _| match bc {
|
||||
.retry_send(msg, lookup.reg, |bc, _| match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
@@ -555,7 +608,9 @@ impl Discoverer {
|
||||
.await??;
|
||||
|
||||
Ok(RegisterResult {
|
||||
reg: lookup.reg,
|
||||
sid,
|
||||
client_id,
|
||||
dmap: dmap.map(|dmap| {
|
||||
SocketAddr::new(dmap.ip.parse().expect("Could not read ip addr"), dmap.port)
|
||||
}),
|
||||
@@ -567,20 +622,14 @@ impl Discoverer {
|
||||
|
||||
/// Confirm connection with relay
|
||||
/// This is sent once all data has been found
|
||||
async fn confirm_relay(
|
||||
&self,
|
||||
client_id: i32,
|
||||
device_id: i32,
|
||||
sid: u32,
|
||||
reg_addr: SocketAddr,
|
||||
) -> Result<()> {
|
||||
async fn confirm_relay(&self, conn_result: &ConnectResult, reg_addr: SocketAddr) -> Result<()> {
|
||||
let msg = UdpDiscovery {
|
||||
tid: 0,
|
||||
payload: UdpXml {
|
||||
c2r_cfm: Some(C2rCfm {
|
||||
sid,
|
||||
cid: client_id,
|
||||
did: device_id,
|
||||
sid: conn_result.sid,
|
||||
cid: conn_result.client_id,
|
||||
did: conn_result.camera_id,
|
||||
rsp: 0,
|
||||
conn: "map".to_string(),
|
||||
}),
|
||||
@@ -598,9 +647,7 @@ impl Discoverer {
|
||||
/// a local then tell the camera to connect to us via map
|
||||
async fn confirm_map(
|
||||
&self,
|
||||
client_id: i32,
|
||||
device_id: i32,
|
||||
sid: u32,
|
||||
conn_result: &ConnectResult,
|
||||
reg_addr: SocketAddr,
|
||||
dev_addr: SocketAddr,
|
||||
) -> Result<()> {
|
||||
@@ -608,9 +655,9 @@ impl Discoverer {
|
||||
tid: 0,
|
||||
payload: UdpXml {
|
||||
c2r_cfm: Some(C2rCfm {
|
||||
sid,
|
||||
cid: client_id,
|
||||
did: device_id,
|
||||
sid: conn_result.sid,
|
||||
cid: conn_result.client_id,
|
||||
did: conn_result.camera_id,
|
||||
conn: "local".to_string(),
|
||||
rsp: 0,
|
||||
}),
|
||||
@@ -624,8 +671,8 @@ impl Discoverer {
|
||||
tid: 0,
|
||||
payload: UdpXml {
|
||||
c2d_t: Some(C2dT {
|
||||
sid,
|
||||
cid: client_id,
|
||||
sid: conn_result.sid,
|
||||
cid: conn_result.client_id,
|
||||
mtu: MTU,
|
||||
conn: "map".to_string(),
|
||||
}),
|
||||
@@ -649,7 +696,7 @@ impl Discovery {
|
||||
let port = local_addr.port();
|
||||
|
||||
let msg = UdpDiscovery {
|
||||
tid: generate_tid(),
|
||||
tid: 0,
|
||||
payload: UdpXml {
|
||||
c2d_c: Some(C2dC {
|
||||
uid: uid.to_string(),
|
||||
@@ -706,24 +753,10 @@ impl Discovery {
|
||||
let reg_addr = lookup.reg;
|
||||
let relay_addr = lookup.relay;
|
||||
|
||||
let reg_result = discoverer
|
||||
.register_address(uid, client_id, lookup.reg, relay_addr)
|
||||
.await?;
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
|
||||
let dev_addr = reg_result.dev.ok_or(Error::NoDev)?;
|
||||
|
||||
let connect_result = discoverer
|
||||
.client_initiated_connect(reg_result.sid, client_id, dev_addr)
|
||||
.await?;
|
||||
|
||||
discoverer
|
||||
.confirm_map(
|
||||
client_id,
|
||||
connect_result.camera_id,
|
||||
reg_result.sid,
|
||||
reg_addr,
|
||||
dev_addr,
|
||||
)
|
||||
.await?;
|
||||
let connect_result = discoverer.client_initiated_connect(®_result).await?;
|
||||
|
||||
Ok(DiscoveryResult {
|
||||
socket: discoverer.into_socket().await,
|
||||
@@ -733,11 +766,13 @@ impl Discovery {
|
||||
})
|
||||
}
|
||||
|
||||
// This is similar to remote, except that a relay will be established.
|
||||
// This is similar to remote, except that a relay (map) will be established.
|
||||
//
|
||||
// All future connections will go VIA the relink servers, this is for
|
||||
// cellular cameras that do not support local connections
|
||||
//
|
||||
// It is possible that this will also establish a local if the camera attempts that
|
||||
//
|
||||
#[allow(unused)]
|
||||
pub(crate) async fn relay(uid: &str) -> Result<DiscoveryResult> {
|
||||
let mut discoverer = Discoverer::new().await?;
|
||||
@@ -751,9 +786,7 @@ impl Discovery {
|
||||
let reg_addr = lookup.reg;
|
||||
let relay_addr = lookup.relay;
|
||||
|
||||
let reg_result = discoverer
|
||||
.register_address(uid, client_id, lookup.reg, relay_addr)
|
||||
.await?;
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
|
||||
trace!("reg_result: {:?}", reg_result);
|
||||
|
||||
let dmap_addr = reg_result.dmap.ok_or(Error::NoDmap)?;
|
||||
@@ -763,17 +796,6 @@ impl Discovery {
|
||||
.await?;
|
||||
trace!("connect_result: {:?}", connect_result);
|
||||
|
||||
discoverer
|
||||
.confirm_relay(
|
||||
client_id,
|
||||
connect_result.camera_id,
|
||||
reg_result.sid,
|
||||
reg_addr,
|
||||
)
|
||||
.await?;
|
||||
|
||||
trace!("confirmed");
|
||||
|
||||
Ok(DiscoveryResult {
|
||||
socket: discoverer.into_socket().await,
|
||||
addr: connect_result.addr,
|
||||
|
||||
@@ -10,7 +10,6 @@ use tokio::net::UdpSocket;
|
||||
mod bcconn;
|
||||
mod bcsub;
|
||||
mod discovery;
|
||||
// mod source;
|
||||
mod tcpsource;
|
||||
mod udpsource;
|
||||
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
//! Trait shared by anything for the camera source.
|
||||
//!
|
||||
//! This trait represents the shared interface between
|
||||
//! TCP and UDP sources
|
||||
//!
|
||||
use super::{TcpSource, UdpSource};
|
||||
use crate::{bc::model::*, Result};
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[async_trait]
|
||||
pub trait Source:
|
||||
futures::stream::Stream<Item = Result<Bc>>
|
||||
+ futures::sink::Sink<Bc, Error = crate::Error>
|
||||
+ Send
|
||||
+ Sync
|
||||
{
|
||||
async fn send(&mut self, bc: Bc) -> Result<()>;
|
||||
async fn recv(&mut self) -> Result<Bc>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Source for TcpSource {
|
||||
async fn send(&mut self, bc: Bc) -> Result<()> {
|
||||
TcpSource::send(self, bc).await
|
||||
}
|
||||
async fn recv(&mut self) -> Result<Bc> {
|
||||
TcpSource::recv(self).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Source for UdpSource {
|
||||
async fn send(&mut self, bc: Bc) -> Result<()> {
|
||||
UdpSource::send(self, bc).await
|
||||
}
|
||||
async fn recv(&mut self) -> Result<Bc> {
|
||||
UdpSource::recv(self).await
|
||||
}
|
||||
}
|
||||
@@ -25,21 +25,15 @@ pub enum Error {
|
||||
|
||||
/// Raised when a connection is dropped.
|
||||
#[error(display = "Dropped connection")]
|
||||
DroppedConnection(#[error(source)] crossbeam_channel::RecvError),
|
||||
|
||||
/// Raised when a connection is dropped during a TryRecv event
|
||||
#[error(display = "Dropped connection")]
|
||||
DroppedConnectionTry(#[error(source)] crossbeam_channel::TryRecvError),
|
||||
DroppedConnection,
|
||||
|
||||
/// Raised when a connection is dropped during a tokio mpsc TryRecv event
|
||||
#[error(display = "Dropped connection")]
|
||||
TokioDroppedConnectionTry(#[error(source)] tokio::sync::mpsc::error::TryRecvError),
|
||||
DroppedConnectionTry(#[error(source)] tokio::sync::mpsc::error::TryRecvError),
|
||||
|
||||
/// Raised when a connection is dropped during a TryRecv event
|
||||
#[error(display = "Dropped connection")]
|
||||
TokioBroadcastDroppedConnectionTry(
|
||||
#[error(source)] tokio::sync::broadcast::error::TryRecvError,
|
||||
),
|
||||
BroadcastDroppedConnectionTry(#[error(source)] tokio::sync::broadcast::error::TryRecvError),
|
||||
|
||||
/// Raised when the RX_TIMEOUT is reach
|
||||
#[error(display = "Timeout")]
|
||||
@@ -118,6 +112,14 @@ pub enum Error {
|
||||
#[error(display = "Register refuses to accept us")]
|
||||
RegisterError,
|
||||
|
||||
/// Raised when a the relay terminates the connection by sending a R2C_DISC
|
||||
#[error(display = "Relay terminated the connection")]
|
||||
RelayTerminate,
|
||||
|
||||
/// Raised when a the camera terminates the connection by sending a D2C_DISC
|
||||
#[error(display = "Camera terminated the connection")]
|
||||
CameraTerminate,
|
||||
|
||||
/// Raised when the stream is not enough to complete a message
|
||||
#[error(display = "Nom Parsing incomplete: {}", _0)]
|
||||
NomIncomplete(usize),
|
||||
|
||||
@@ -4,12 +4,11 @@ use crate::{
|
||||
bcmedia::model::*,
|
||||
};
|
||||
use futures::stream::StreamExt;
|
||||
use log::*;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
use tokio::sync::mpsc::{channel, error::TryRecvError, Receiver};
|
||||
use tokio::sync::mpsc::{channel, Receiver};
|
||||
use tokio::task::{self, JoinHandle};
|
||||
|
||||
/// The stream names supported by BC
|
||||
@@ -40,16 +39,11 @@ pub struct StreamData {
|
||||
impl StreamData {
|
||||
/// Pull data from the camera's buffer
|
||||
/// This returns raw BcMedia packets
|
||||
pub fn get_data(&mut self) -> Result<Vec<Result<BcMedia>>> {
|
||||
let mut results: Vec<_> = vec![];
|
||||
loop {
|
||||
match self.rx.try_recv() {
|
||||
Ok(data) => results.push(data),
|
||||
Err(TryRecvError::Empty) => break,
|
||||
Err(e) => return Err(Error::from(e)),
|
||||
}
|
||||
pub async fn get_data(&mut self) -> Result<Result<BcMedia>> {
|
||||
match self.rx.recv().await {
|
||||
Some(data) => Ok(data),
|
||||
None => Err(Error::DroppedConnection),
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,7 +76,6 @@ impl BcCamera {
|
||||
stream: StreamKind,
|
||||
mut buffer_size: usize,
|
||||
) -> Result<StreamData> {
|
||||
info!("start_video");
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
|
||||
@@ -96,9 +89,7 @@ impl BcCamera {
|
||||
let channel_id = self.channel_id;
|
||||
|
||||
let handle = task::spawn(async move {
|
||||
info!("sub_video");
|
||||
let mut sub_video = connection.subscribe(msg_num).await?;
|
||||
info!("post sub_video");
|
||||
|
||||
// On an E1 and swann cameras:
|
||||
// - mainStream always has a value of 0
|
||||
@@ -156,9 +147,7 @@ impl BcCamera {
|
||||
},
|
||||
);
|
||||
|
||||
info!("Sending stream start");
|
||||
sub_video.send(start_video).await?;
|
||||
info!("Sent stream start");
|
||||
|
||||
let msg = sub_video.recv().await?;
|
||||
if let BcMeta {
|
||||
|
||||
@@ -7,6 +7,8 @@ use crate::{Error, Result};
|
||||
use bytes::BytesMut;
|
||||
use tokio_util::codec::{Decoder, Encoder};
|
||||
|
||||
use super::xml::UdpXml;
|
||||
|
||||
pub(crate) struct BcUdpCodex {}
|
||||
|
||||
impl BcUdpCodex {
|
||||
@@ -33,6 +35,18 @@ impl Decoder for BcUdpCodex {
|
||||
|
||||
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||
match { BcUdp::deserialize(src) } {
|
||||
Ok(BcUdp::Discovery(UdpDiscovery {
|
||||
payload: UdpXml {
|
||||
r2c_disc: Some(_), ..
|
||||
},
|
||||
..
|
||||
})) => Err(Error::RelayTerminate),
|
||||
Ok(BcUdp::Discovery(UdpDiscovery {
|
||||
payload: UdpXml {
|
||||
d2c_disc: Some(_), ..
|
||||
},
|
||||
..
|
||||
})) => Err(Error::CameraTerminate),
|
||||
Ok(bc) => Ok(Some(bc)),
|
||||
Err(Error::NomIncomplete(_)) => Ok(None),
|
||||
Err(e) => Err(e),
|
||||
|
||||
@@ -33,6 +33,9 @@ pub struct UdpXml {
|
||||
/// D2C_DISC xml Disconnect
|
||||
#[yaserde(rename = "D2C_DISC")]
|
||||
pub d2c_disc: Option<D2cDisc>,
|
||||
/// R2C_DISC xml Disconnect
|
||||
#[yaserde(rename = "R2C_DISC")]
|
||||
pub r2c_disc: Option<R2cDisc>,
|
||||
/// C2M_Q xml client to middle man query
|
||||
#[yaserde(rename = "C2M_Q")]
|
||||
pub c2m_q: Option<C2mQ>,
|
||||
@@ -157,6 +160,13 @@ pub struct D2cDisc {
|
||||
pub did: i32,
|
||||
}
|
||||
|
||||
/// R2C_DISC xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
|
||||
pub struct R2cDisc {
|
||||
/// The sid
|
||||
pub sid: u32,
|
||||
}
|
||||
|
||||
/// D2C_T xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
|
||||
pub struct D2cT {
|
||||
|
||||
+2
-2
@@ -218,8 +218,8 @@ impl GstOutputs {
|
||||
// - In the case of PausedSources::None we just pass through without encoding
|
||||
// - In the case of all other pause sources we need to recencode in order
|
||||
// to get smooth streams when the stream is paused/resumed
|
||||
info!("self.video_format: {:?}", self.video_format);
|
||||
info!("self.audio_format: {:?}", self.audio_format);
|
||||
// info!("self.video_format: {:?}", self.video_format);
|
||||
// info!("self.audio_format: {:?}", self.audio_format);
|
||||
let launch_vid_select = match self.when_paused {
|
||||
PausedSources::None => match self.video_format {
|
||||
Some(StreamFormat::H264) => "! rtph264pay name=pay0",
|
||||
|
||||
+7
-5
@@ -106,7 +106,7 @@ pub(crate) async fn main(_opt: Opt, mut config: Config) -> Result<()> {
|
||||
break;
|
||||
}
|
||||
Err(CameraFailureKind::Retry(e)) => {
|
||||
warn!("{}: Retryable error: {:?}", camera_config.name, e);
|
||||
warn!("{}: Retryable error: {:X?}", camera_config.name, e);
|
||||
backoff.spin();
|
||||
}
|
||||
Ok(()) => {
|
||||
@@ -225,9 +225,10 @@ async fn camera_main(
|
||||
}
|
||||
}
|
||||
}
|
||||
if !camera.is_running() {
|
||||
if let Err(e) = camera.is_running().await {
|
||||
return Err(CameraFailureKind::Retry(anyhow!(
|
||||
"Camera has unexpectanely stopped the paused state"
|
||||
"Camera has unexpectanely stopped the streaming state: {:?}",
|
||||
e
|
||||
)));
|
||||
}
|
||||
}
|
||||
@@ -250,9 +251,10 @@ async fn camera_main(
|
||||
}
|
||||
}
|
||||
}
|
||||
if !camera.is_running() {
|
||||
if let Err(e) = camera.is_running().await {
|
||||
return Err(CameraFailureKind::Retry(anyhow!(
|
||||
"Camera has unexpectanely stopped the paused state"
|
||||
"Camera has unexpectanely stopped the paused state: {:?}",
|
||||
e
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ impl RtspCamera {
|
||||
{
|
||||
streams.insert(Stream::Sub);
|
||||
}
|
||||
if ["both", "externStream", "externstream"]
|
||||
if ["all", "externStream", "externstream"]
|
||||
.iter()
|
||||
.any(|&e| e == config.stream)
|
||||
{
|
||||
@@ -256,11 +256,11 @@ impl RtspCamera {
|
||||
.with_context(|| "Cannot get motion data")
|
||||
}
|
||||
|
||||
pub(crate) fn is_running(&self) -> bool {
|
||||
match &self.state {
|
||||
State::Streaming(state) => state.is_running(),
|
||||
State::Paused(state) => state.is_running(),
|
||||
_ => true,
|
||||
pub(crate) async fn is_running(&mut self) -> Result<()> {
|
||||
match &mut self.state {
|
||||
State::Streaming(state) => state.is_running().await,
|
||||
State::Paused(state) => state.is_running().await,
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// Video data is not pulled from the camera
|
||||
// instead dummy data is sent into the gstreamer source
|
||||
|
||||
use anyhow::{anyhow, Error, Result};
|
||||
use anyhow::{anyhow, Error, Result, Context};
|
||||
use async_trait::async_trait;
|
||||
use crossbeam::utils::Backoff;
|
||||
use log::*;
|
||||
@@ -136,18 +136,21 @@ impl CameraState for Paused {
|
||||
impl Drop for Paused {
|
||||
fn drop(&mut self) {
|
||||
self.abort_handle.abort();
|
||||
let backoff = Backoff::new();
|
||||
for (_, handle) in self.handles.drain() {
|
||||
while !handle.is_finished() {
|
||||
backoff.spin();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Paused {
|
||||
pub(crate) fn is_running(&self) -> bool {
|
||||
self.handles.iter().all(|(_, h)| !h.is_finished()) && self.abort_handle.is_live()
|
||||
pub(crate) async fn is_running(&mut self) -> Result<()> {
|
||||
if self.handles.iter().all(|(_, h)| !h.is_finished()) && self.abort_handle.is_live() {
|
||||
return Ok(());
|
||||
}
|
||||
if !self.abort_handle.is_live() {
|
||||
return Err(anyhow!("Stream aborted"));
|
||||
}
|
||||
for (s, h) in self.handles.drain() {
|
||||
h.await?.context(format!("On stream: {:?}", s))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn take_outputs(&mut self) -> Result<HashMap<Stream, GstOutputs>> {
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
//
|
||||
// Data is streamed into a gstreamer source
|
||||
|
||||
use anyhow::{anyhow, Error, Result};
|
||||
use anyhow::{anyhow, Context, Error, Result};
|
||||
use async_trait::async_trait;
|
||||
use crossbeam::utils::Backoff;
|
||||
use log::*;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -95,18 +94,17 @@ impl CameraState for Streaming {
|
||||
|
||||
let stream_thead = *stream;
|
||||
let handle = task::spawn(async move {
|
||||
let backoff = Backoff::new();
|
||||
info!("Pre start_video");
|
||||
let mut stream_data = arc_camera.start_video(stream_thead, 0).await?;
|
||||
info!("Post start_video");
|
||||
while arc_abort_handle.is_live() {
|
||||
let mut data = stream_data.get_data()?;
|
||||
info!("Getting Data");
|
||||
let data = stream_data.get_data().await?;
|
||||
info!("Got Data");
|
||||
let mut locked_output = output_thread.lock().await;
|
||||
for datum in data.drain(..) {
|
||||
locked_output.stream_recv(datum?)?;
|
||||
}
|
||||
backoff.spin();
|
||||
info!("Feed locked");
|
||||
locked_output.stream_recv(data?)?;
|
||||
info!("Data fed");
|
||||
}
|
||||
info!("Aboted");
|
||||
Ok(())
|
||||
});
|
||||
|
||||
@@ -142,22 +140,25 @@ impl CameraState for Streaming {
|
||||
impl Drop for Streaming {
|
||||
fn drop(&mut self) {
|
||||
self.abort_handle.abort();
|
||||
|
||||
for (_, handle) in self.handles.drain() {
|
||||
let backoff = crossbeam::utils::Backoff::new();
|
||||
while !handle.is_finished() {
|
||||
backoff.spin();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Streaming {
|
||||
pub(crate) fn is_running(&self) -> bool {
|
||||
self.handles.iter().all(|(_, h)| !h.is_finished()) && self.abort_handle.is_live()
|
||||
pub(crate) async fn is_running(&mut self) -> Result<()> {
|
||||
if self.handles.iter().all(|(_, h)| !h.is_finished()) && self.abort_handle.is_live() {
|
||||
return Ok(());
|
||||
}
|
||||
if !self.abort_handle.is_live() {
|
||||
return Err(anyhow!("Stream aborted"));
|
||||
}
|
||||
for (s, h) in self.handles.drain() {
|
||||
h.await?.context(format!("On stream: {:?}", s))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn take_outputs(&mut self) -> Result<HashMap<Stream, GstOutputs>> {
|
||||
info!("Streaming take_outputs");
|
||||
self.abort_handle.abort();
|
||||
for (stream, handle) in self.handles.drain() {
|
||||
match handle.await {
|
||||
|
||||
Reference in new issue
Block a user