Deps and logs

Use quick_xml instead of yaserde

Use thiserror instead of err_derive

Update deps to latest (except fcm), fcm will need to wait for reolink to update their fcm apis first in their app
This commit is contained in:
QuantumEntangledAndy committed 2024-04-04 12:47:36 +07:00
1 parent acae5f95ee
commit 4c17fa9f2b
35 files changed
+1419 -1735

No files matched your search

+3 -4
View File
@@ -13,23 +13,22 @@ cfb-mode = "0.8.2"
cookie-factory = "0.3.2"
crc32fast = "1.3.2"
crossbeam-channel = "0.5.8"
delegate = "0.10.0"
err-derive = "0.3.1"
delegate = "0.12.0"
futures = "0.3.28"
get_if_addrs = "0.5.3"
lazy_static = "1.4.0"
log = "0.4.17"
md5 = "0.7.0"
nom = { version = "7.1.3", features = ["alloc"] }
quick-xml = { version = "0.31.0", features = ["serialize"] }
rand = "0.8.5"
regex = "1.7.3"
serde = { version = "1.0.106", features = ["derive"] }
thiserror = "1.0.58"
time = { version = "0.3.20" , features = [ "macros", "parsing", "local-offset" ]}
tokio = { version = "1.27.0", features = ["full"] }
tokio-stream = { version = "0.1.12", features = ["sync", "time", "net"] }
tokio-util = { version = "0.7.7", features = ["full", "tracing"] }
yaserde = "0.8.0"
yaserde_derive = "0.8.0"
[dev-dependencies]
assert_matches = "1.5.0"
+2 -3
View File
@@ -1,5 +1,4 @@
use super::model::*;
use super::xml::{BcPayloads, BcXml};
use super::xml_crypto;
use crate::Error;
use bytes::{Buf, BytesMut};
@@ -84,10 +83,10 @@ fn bc_modern_msg<'a>(
Err,
};
fn make_error<I, E: ParseError<I>>(input: I, ctx: &'static str, kind: ErrorKind) -> E
fn make_error<I, E>(input: I, ctx: &'static str, kind: ErrorKind) -> E
where
I: std::marker::Copy,
E: ContextError<I>,
E: ParseError<I> + ContextError<I>,
{
E::add_context(input, ctx, E::from_error_kind(input, kind))
}
+2 -3
View File
@@ -1,5 +1,4 @@
use super::model::*;
use super::xml::BcPayloads;
use super::xml_crypto;
use cookie_factory::bytes::*;
use cookie_factory::sequence::tuple;
@@ -79,7 +78,7 @@ fn bc_ext<W: Write>(
xml: &Extension,
encryption_protocol: &EncryptionProtocol,
) -> impl SerializeFn<W> {
let xml_bytes = xml.serialize(vec![]).unwrap();
let xml_bytes = xml.serialize(bytes::BytesMut::new()).unwrap();
let enc_bytes = xml_crypto::encrypt(enc_offset, &xml_bytes, encryption_protocol);
slice(enc_bytes)
}
@@ -91,7 +90,7 @@ fn bc_payload<W: Write>(
) -> impl SerializeFn<W> {
let payload_bytes = match payload {
BcPayloads::BcXml(x) => {
let xml_bytes = x.serialize(vec![]).unwrap();
let xml_bytes = x.serialize(bytes::BytesMut::new()).unwrap();
xml_crypto::encrypt(enc_offset, &xml_bytes, encryption_protocol)
}
BcPayloads::Binary(x) => x.to_owned(),
+318 -331
View File
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -54,8 +54,9 @@ impl BcCamera {
/// Populate ability list of the camera
pub async fn polulate_abilities(&self) -> Result<()> {
let info = self.get_abilityinfo().await?;
let info_res = yaserde::ser::serialize_with_writer(&info, vec![], &Default::default());
if let Ok(Ok(info_str)) = info_res.map(String::from_utf8) {
let mut ser_buf = bytes::BytesMut::new();
let info_res = quick_xml::se::to_writer(&mut ser_buf, &info).map(|_| ser_buf);
if let Ok(Ok(info_str)) = info_res.map(|b| std::str::from_utf8(&b).map(|a| a.to_owned())) {
debug!("Abilities: {}", info_str);
}
+7 -8
View File
@@ -57,14 +57,13 @@ impl BcCamera {
);
}
PrintFormat::Xml => {
let bat_ser = String::from_utf8(
yaserde::ser::serialize_with_writer(
battery,
vec![],
&Default::default(),
)
.expect("Should Ser the struct"),
)
let bat_ser = String::from_utf8({
let mut ser_buf = bytes::BytesMut::new();
let parsed =
quick_xml::se::to_writer(&mut ser_buf, &battery)
.map(|_| ser_buf);
parsed.expect("Could not serialise data").to_vec()
})
.expect("Should be UTF8");
println!("{}", bat_ser);
}
@@ -350,28 +350,21 @@ impl Discoverer {
let port = self.local_addr().port();
let msg = UdpDiscovery {
tid,
payload: UdpXml {
c2d_c: Some(C2dC {
uid: uid.to_string(),
cli: ClientList { port: port as u32 },
cid: client_id,
mtu: MTU,
debug: false,
os: "MAC".to_string(),
}),
..Default::default()
},
payload: UdpXml::C2dC(C2dC {
uid: uid.to_string(),
cli: ClientList { port: port as u32 },
cid: client_id,
mtu: MTU,
debug: false,
os: "MAC".to_string(),
}),
};
let (camera_address, camera_id) = self
.retry_send(msg, addr, |bc, addr| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_c_r: Some(D2cCr { did, cid, .. }),
..
},
payload: UdpXml::D2cCr(D2cCr { did, cid, .. }),
} if cid == client_id => Some((addr, did)),
_ => None,
})
@@ -422,24 +415,17 @@ impl Discoverer {
async fn uid_lookup(&self, uid: &str, addr: SocketAddr) -> Result<UidLookupResults> {
let msg = UdpDiscovery {
tid: 0,
payload: UdpXml {
c2m_q: Some(C2mQ {
uid: uid.to_string(),
os: "MAC".to_string(),
}),
..Default::default()
},
payload: UdpXml::C2mQ(C2mQ {
uid: uid.to_string(),
os: "MAC".to_string(),
}),
};
trace!("Sending look up {:?}", msg);
let (packet, _) = self
.retry_send(msg, addr, |bc, addr| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
m2c_q_r: Some(m2c_q_r),
..
},
payload: UdpXml::M2cQr(m2c_q_r),
} if valid_addr(&m2c_q_r.reg) => Some((m2c_q_r, addr)),
_ => None,
})
@@ -469,28 +455,27 @@ impl Discoverer {
let msg = UdpDiscovery {
tid,
payload: UdpXml {
c2r_c: Some(C2rC {
uid: uid.to_string(),
cli: IpPort {
ip: local_ip.to_string(),
port: local_port,
},
relay: IpPort {
ip: lookup.relay.ip().to_string(),
port: lookup.relay.port(),
},
cid: client_id,
family: local_family,
debug: false,
os: "MAC".to_string(),
revision: Some(3),
}),
..Default::default()
},
payload: UdpXml::C2rC(C2rC {
uid: uid.to_string(),
cli: IpPort {
ip: local_ip.to_string(),
port: local_port,
},
relay: IpPort {
ip: lookup.relay.ip().to_string(),
port: lookup.relay.port(),
},
cid: client_id,
family: local_family,
debug: false,
os: "MAC".to_string(),
revision: Some(3),
}),
};
trace!("Registering: {:?}", msg.payload.c2r_c);
if let UdpXml::C2rC(ref c2r_c) = msg.payload {
trace!("Registering: {:?}", c2r_c);
}
// Send and await acceptance
let (sid, dev, dmap, relay) = self
@@ -500,18 +485,14 @@ impl Discoverer {
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_c_r:
Some(R2cCr {
dmap,
dev,
relay,
sid,
rsp,
..
}),
UdpXml::R2cCr(R2cCr {
dmap,
dev,
relay,
sid,
rsp,
..
},
}),
} if (dev.as_ref().map(valid_addr).unwrap_or(false)
|| dmap.as_ref().map(valid_addr).unwrap_or(false)
|| relay.as_ref().map(valid_addr).unwrap_or(false))
@@ -553,17 +534,13 @@ impl Discoverer {
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_c_r:
Some(R2cCr {
dev,
dmap,
relay,
rsp,
..
}),
UdpXml::R2cCr(R2cCr {
dev,
dmap,
relay,
rsp,
..
},
}),
} if (dev.as_ref().map(valid_addr).unwrap_or(false)
|| dmap.as_ref().map(valid_addr).unwrap_or(false)
|| relay.as_ref().map(valid_addr).unwrap_or(false))
@@ -598,17 +575,13 @@ impl Discoverer {
UdpDiscovery {
tid,
payload:
UdpXml {
d2c_t:
Some(D2cT {
sid,
cid,
did,
conn,
..
}),
UdpXml::D2cT(D2cT {
sid,
cid,
did,
conn,
..
},
}),
},
RegisterResult {
dmap: register_dmap,
@@ -632,16 +605,13 @@ impl Discoverer {
let msg = UdpDiscovery {
tid: local_tid,
payload: UdpXml {
c2d_a: Some(C2dA {
sid: register_result.sid,
conn: "local".to_string(),
cid: register_result.client_id,
did: local_did,
mtu: MTU,
}),
..Default::default()
},
payload: UdpXml::C2dA(C2dA {
sid: register_result.sid,
conn: "local".to_string(),
cid: register_result.client_id,
did: local_did,
mtu: MTU,
}),
};
let permit = self
@@ -657,17 +627,13 @@ impl Discoverer {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_cfm:
Some(D2cCfm {
sid,
cid,
did,
conn,
..
}),
UdpXml::D2cCfm(D2cCfm {
sid,
cid,
did,
conn,
..
},
}),
} if sid == register_result.sid
&& did == local_did
&& cid == register_result.client_id
@@ -690,16 +656,13 @@ impl Discoverer {
// Confirm local to register
let msg = UdpDiscovery {
tid: 0,
payload: UdpXml {
c2r_cfm: Some(C2rCfm {
sid: result.sid,
cid: result.client_id,
did: result.camera_id,
rsp: 0,
conn: "local".to_string(),
}),
..Default::default()
},
payload: UdpXml::C2rCfm(C2rCfm {
sid: result.sid,
cid: result.client_id,
did: result.camera_id,
rsp: 0,
conn: "local".to_string(),
}),
};
self.send_and_forget(msg, register_result.reg).await?;
@@ -723,17 +686,13 @@ impl Discoverer {
UdpDiscovery {
tid,
payload:
UdpXml {
d2c_t:
Some(D2cT {
sid,
cid,
did,
conn,
..
}),
UdpXml::D2cT(D2cT {
sid,
cid,
did,
conn,
..
},
}),
},
RegisterResult {
dmap: register_dmap,
@@ -757,16 +716,13 @@ impl Discoverer {
let msg = UdpDiscovery {
tid: local_tid,
payload: UdpXml {
c2d_a: Some(C2dA {
sid: register_result.sid,
conn: "map".to_string(),
cid: register_result.client_id,
did: local_did,
mtu: MTU,
}),
..Default::default()
},
payload: UdpXml::C2dA(C2dA {
sid: register_result.sid,
conn: "map".to_string(),
cid: register_result.client_id,
did: local_did,
mtu: MTU,
}),
};
let permit = self
@@ -782,17 +738,13 @@ impl Discoverer {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_cfm:
Some(D2cCfm {
sid,
cid,
did,
conn,
..
}),
UdpXml::D2cCfm(D2cCfm {
sid,
cid,
did,
conn,
..
},
}),
} if sid == register_result.sid
&& did == local_did
&& cid == register_result.client_id
@@ -815,16 +767,13 @@ impl Discoverer {
// Confirm map to register
let msg = UdpDiscovery {
tid: 0,
payload: UdpXml {
c2r_cfm: Some(C2rCfm {
sid: result.sid,
cid: result.client_id,
did: result.camera_id,
rsp: 0,
conn: "map".to_string(),
}),
..Default::default()
},
payload: UdpXml::C2rCfm(C2rCfm {
sid: result.sid,
cid: result.client_id,
did: result.camera_id,
rsp: 0,
conn: "map".to_string(),
}),
};
self.send_and_forget(msg, register_result.reg).await?;
@@ -845,26 +794,19 @@ impl Discoverer {
let dev_addr = register_result.dev.ok_or(Error::NoDev)?;
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()
},
payload: UdpXml::C2dT(C2dT {
sid: register_result.sid,
cid: register_result.client_id,
mtu: MTU,
conn: "local".to_string(),
}),
};
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, .. }),
..
},
payload: UdpXml::D2cCfm(D2cCfm { cid, did, sid, .. }),
} if cid == register_result.client_id && sid == register_result.sid => {
Some((addr, did))
}
@@ -888,16 +830,13 @@ impl Discoverer {
// Confirm local to register
let msg = UdpDiscovery {
tid: 0,
payload: UdpXml {
c2r_cfm: Some(C2rCfm {
sid: result.sid,
cid: result.client_id,
did: result.camera_id,
conn: "local".to_string(),
rsp: 0,
}),
..Default::default()
},
payload: UdpXml::C2rCfm(C2rCfm {
sid: result.sid,
cid: result.client_id,
did: result.camera_id,
conn: "local".to_string(),
rsp: 0,
}),
};
self.send_and_forget(msg, register_result.reg).await?;
@@ -918,15 +857,12 @@ impl Discoverer {
let relay_addr = register_result.relay.ok_or(Error::NoDev)?;
let msg = UdpDiscovery {
tid,
payload: UdpXml {
c2d_t: Some(C2dT {
sid: register_result.sid,
cid: register_result.client_id,
mtu: MTU,
conn: "relay".to_string(),
}),
..Default::default()
},
payload: UdpXml::C2dT(C2dT {
sid: register_result.sid,
cid: register_result.client_id,
mtu: MTU,
conn: "relay".to_string(),
}),
};
let permit = self
@@ -940,17 +876,13 @@ impl Discoverer {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_cfm:
Some(D2cCfm {
cid,
did,
sid,
conn,
..
}),
UdpXml::D2cCfm(D2cCfm {
cid,
did,
sid,
conn,
..
},
}),
} if cid == register_result.client_id
&& sid == register_result.sid
&& &conn == "relay" =>
@@ -971,16 +903,13 @@ impl Discoverer {
// Confirm relay to register
let msg = UdpDiscovery {
tid: 0,
payload: UdpXml {
c2r_cfm: Some(C2rCfm {
sid: result.sid,
cid: result.client_id,
did: result.camera_id,
conn: "relay".to_string(),
rsp: 0,
}),
..Default::default()
},
payload: UdpXml::C2rCfm(C2rCfm {
sid: result.sid,
cid: result.client_id,
did: result.camera_id,
conn: "relay".to_string(),
rsp: 0,
}),
};
self.send_and_forget(msg, register_result.reg).await?;
@@ -1009,13 +938,10 @@ impl Discoverer {
interval.tick().await;
let msg = BcUdp::Discovery(UdpDiscovery {
tid,
payload: UdpXml {
c2d_hb: Some(C2dHb {
payload: UdpXml::C2dHb(C2dHb {
cid: client_id,
did: camera_id,
}),
..Default::default()
},
});
if sender.send((msg, addr)).await.is_err() {
break Result::Ok(());
@@ -1044,14 +970,11 @@ impl Discoverer {
interval.tick().await;
let msg = BcUdp::Discovery(UdpDiscovery {
tid,
payload: UdpXml {
c2r_hb: Some(C2rHb {
payload: UdpXml::C2rHb(C2rHb {
sid,
cid: client_id,
did: camera_id,
}),
..Default::default()
},
});
if sender.send((msg, addr)).await.is_err() {
break Result::Ok(());
@@ -1167,7 +1090,7 @@ impl Discovery {
) -> Result<DiscoveryResult> {
let mut dests = get_broadcasts(&[2015, 2018])?;
if let Some(mut optional_addrs) = optional_addrs.take() {
trace!("Also sending to {:?}", optional_addrs);
debug!("Also sending to {:?}", optional_addrs);
dests.append(&mut optional_addrs);
}
let discoverer_ref = &self.discoverer;
@@ -384,13 +384,10 @@ impl UdpPayloadInner {
let mut rng = thread_rng();
(rng.gen::<u8>()) as u32
},
payload: UdpXml {
c2d_hb: Some(C2dHb {
payload: UdpXml::C2dHb(C2dHb {
cid: thread_client_id,
did: thread_camera_id,
}),
..Default::default()
},
});
let _ = tokio::time::timeout(tokio::time::Duration::from_millis(250), inner.send((msg, thread_camera_addr))).await;
}
@@ -449,13 +446,10 @@ impl UdpPayloadInner {
let mut rng = thread_rng();
(rng.gen::<u8>()) as u32
},
payload: UdpXml {
c2d_hb: Some(C2dHb {
payload: UdpXml::C2dHb(C2dHb {
cid: thread_client_id,
did: thread_camera_id,
}),
..Default::default()
},
});
if thread_sender.send(msg).await.is_err() {
break Result::Ok(());
+52 -57
View File
@@ -1,33 +1,33 @@
use super::bc::model::Bc;
use crate::NomErrorType;
use err_derive::Error;
use thiserror::Error;
/// This is the primary error type of the library
#[derive(Debug, Error, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum Error {
/// Underlying IO errors
#[error(display = "IO Error: {:?}", _0)]
Io(#[error(source)] std::sync::Arc<std::io::Error>),
#[error("IO Error: {:?}", _0)]
Io(#[from] std::sync::Arc<std::io::Error>),
/// Raised when fails to parse time from the camera
#[error(display = "Error in time coversion: {:?}", _0)]
TimeRange(#[error(source)] time::error::ComponentRange),
#[error("Error in time coversion: {:?}", _0)]
TimeRange(#[from] time::error::ComponentRange),
/// Raised when fails to parse time from the camera
#[error(display = "Error in time parsing")]
#[error("Error in time parsing")]
TimeParse,
/// Raised when fails to parse time from the camera
#[error(display = "Error in try from NonZeroInt")]
TryFromInt(#[error(source)] std::num::TryFromIntError),
#[error("Error in try from NonZeroInt")]
TryFromInt(#[from] std::num::TryFromIntError),
/// /// Raised when fails to parse time from the camera
#[error(display = "Error in time conversion")]
TimeTryFrom(#[error(source)] time::error::TryFromParsed),
#[error("Error in time conversion")]
TimeTryFrom(#[from] time::error::TryFromParsed),
/// Raised when a Bc reply was not understood
#[error(display = "Communication error")]
#[error("Communication error")]
UnintelligibleReply {
/// The Bc packet that was not understood
reply: std::sync::Arc<Box<Bc>>,
@@ -36,140 +36,135 @@ pub enum Error {
},
/// Raised when the camera responds with a status code over than OK
#[error(display = "Camera responded with Service Unavaliable: {}", _0)]
#[error("Camera responded with Service Unavaliable: {}", _0)]
CameraServiceUnavaliable(u16),
/// Raised when the camera responds with a status code over than OK during login
#[error(display = "Camera responded with Err during login")]
#[error("Camera responded with Err during login")]
CameraLoginFail,
/// Raised when a connection is dropped.
#[error(display = "Dropped connection")]
#[error("Dropped connection")]
DroppedConnection,
/// Raised when a connection is dropped during a tokio mpsc TryRecv event
#[error(display = "Dropped connection (TryRecv)")]
DroppedConnectionTry(#[error(source)] tokio::sync::mpsc::error::TryRecvError),
#[error("Dropped connection (TryRecv)")]
DroppedConnectionTry(#[from] tokio::sync::mpsc::error::TryRecvError),
/// Raised when a connection is dropped during a TryRecv event
#[error(display = "Dropped connection (Broadcast TryRecv)")]
BroadcastDroppedConnectionTry(#[error(source)] tokio::sync::broadcast::error::TryRecvError),
#[error("Dropped connection (Broadcast TryRecv)")]
BroadcastDroppedConnectionTry(#[from] tokio::sync::broadcast::error::TryRecvError),
/// Raised when a connection is dropped during a TryRecv event
#[error(display = "Send Error")]
#[error("Send Error")]
TokioBcSendError,
/// Raised when the TIMEOUT is reach
#[error(display = "Timeout")]
Timeout(#[error(source)] std::sync::Arc<tokio::time::error::Elapsed>),
#[error("Timeout")]
Timeout(#[from] 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),
#[error("TimeoutError")]
TimeoutError(#[from] tokio::time::error::Error),
/// Raised when connection is dropped because the timeout is reach
#[error(display = "Dropped connection (Timeout)")]
#[error("Dropped connection (Timeout)")]
TimeoutDisconnected,
/// Raised when a camera cannot be connected to ay any of the given addresses
#[error(display = "Cannot contact camera at given address")]
#[error("Cannot contact camera at given address")]
CannotInitCamera,
/// Raised when failed to login to the camera
#[error(display = "Credential error")]
#[error("Credential error")]
AuthFailed,
/// Raised when the given camera url could not be resolved
#[error(display = "Failed to translate camera address")]
#[error("Failed to translate camera address")]
AddrResolutionError,
/// Raised non adpcm data is sent to the talk command
#[error(display = "Talk data is not ADPCM")]
#[error("Talk data is not ADPCM")]
UnknownTalkEncoding,
/// Raised when dicovery times out waiting for a reply
#[error(display = "Timed out while waiting for camera reply")]
#[error("Timed out while waiting for camera reply")]
DiscoveryTimeout,
/// Raised during a (de)seralisation error
#[error(display = "Cookie GenError")]
GenError(#[error(source)] std::sync::Arc<cookie_factory::GenError>),
#[error("Cookie GenError")]
GenError(#[from] std::sync::Arc<cookie_factory::GenError>),
/// Raised when a connection is subscrbed to more than once for msg_num
#[error(display = "Simultaneous subscription, {:?}", _0)]
#[error("Simultaneous subscription, {msg_num:?}")]
SimultaneousSubscription {
/// The message number that was subscribed to
msg_num: Option<u16>,
},
/// Raised when a connection is subscrbed to more than once for msg_id
#[error(display = "Simultaneous subscription, {}", _0)]
#[error("Simultaneous subscription, {msg_id}")]
SimultaneousSubscriptionId {
/// The message number that was subscribed to
msg_id: u32,
},
/// Raised when a new encyrption byte is observed
#[error(display = "Unknown encryption: {:x?}", _0)]
#[error("Unknown encryption: {0:x?}")]
UnknownEncryption(usize),
/// Raised when the camera cannot be found
#[error(display = "Camera Not Findable")]
#[error("Camera Not Findable")]
ConnectionUnavaliable,
/// Raised when the subscription id dropped too soon
#[error(display = "Dropped Subscriber")]
#[error("Dropped Subscriber")]
DroppedSubscriber,
/// Raised when a unknown connection ID attempts to connect with us over UDP
#[error(display = "Connection with unknown connectionID: {:?}", _0)]
#[error("Connection with unknown connectionID: {0:?}")]
UnknownConnectionId(i32),
/// Raised when a unknown SocketAddr attempts to connect with us over UDP
#[error(display = "Connection from unknown source: {:?}", _0)]
#[error("Connection from unknown source: {0:?}")]
UnknownSource(std::net::SocketAddr),
/// Raised when the IP/Hostname cannot be understood
#[error(display = "Could not parse as IP")]
AddrParseError(#[error(source)] std::net::AddrParseError),
#[error("Could not parse as IP")]
AddrParseError(#[from] std::net::AddrParseError),
/// Raised when a relay connection is not possible
/// usually happens if the camera has not contacted reolink yet
#[error(display = "Cannot perform relay connection with this camera")]
#[error("Cannot perform relay connection with this camera")]
NoDmap,
/// Raised when a dev connection is not possible
/// usually happens if the camera has not contacted reolink yet
#[error(display = "Cannot perform lookup with this camera against reolink servers")]
#[error("Cannot perform lookup with this camera against reolink servers")]
NoDev,
/// Raised when a discovery fails to be accepted by the register
#[error(display = "Register refuses to accept us")]
#[error("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")]
#[error("Relay terminated the connection")]
RelayTerminate,
/// Raised when a the camera terminates the connection by sending a D2C_DISC
#[error(display = "Camera terminated the connection")]
#[error("Camera terminated the connection")]
CameraTerminate,
/// Raised when the stream is not enough to complete a message
#[error(display = "Nom Parsing incomplete: {}", _0)]
#[error("Nom Parsing incomplete: {0}")]
NomIncomplete(usize),
/// Raised when a stream cannot be decoded
#[error(display = "Nom Parsing error: {}", _0)]
#[error("Nom Parsing error: {0}")]
NomError(String),
/// Raised when a camera/user lacks an ability
#[error(
display = "Missing ability: {} with {} permission has only {}",
name,
requested,
actual
)]
#[error("Missing ability: {name} with {requested} permission has only {actual}")]
MissingAbility {
/// Name of the ability
name: String,
@@ -180,15 +175,15 @@ pub enum Error {
},
/// Raised when a thread panics
#[error(display = "Thread panicked")]
JoinError(#[error(source)] std::sync::Arc<tokio::task::JoinError>),
#[error("Thread panicked")]
JoinError(#[from] std::sync::Arc<tokio::task::JoinError>),
/// A generic catch all error
#[error(display = "Other error: {}", _0)]
#[error("Other error: {0}")]
Other(&'static str),
/// A generic catch all error
#[error(display = "Other error: {}", _0)]
#[error("Other error: {0}")]
OtherString(String),
}
+1 -1
View File
@@ -50,7 +50,7 @@ impl Decoder for BcMediaCodex {
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
loop {
match { BcMedia::deserialize(src) } {
match BcMedia::deserialize(src) {
Ok(bc) => {
if self.amount_skipped > 0 {
debug!("Amount skipped to restore stream: {}", self.amount_skipped);
-1
View File
@@ -1,4 +1,3 @@
use super::model::BcMediaIframe;
use super::model::*;
use crate::Error;
use bytes::{Buf, BytesMut};
+3 -7
View File
@@ -48,20 +48,16 @@ impl Decoder for BcUdpCodex {
if src.is_empty() {
return Ok(None);
}
match { BcUdp::deserialize(src) } {
match BcUdp::deserialize(src) {
Ok(BcUdp::Discovery(UdpDiscovery {
payload: UdpXml {
r2c_disc: Some(_), ..
},
payload: UdpXml::R2cDisc(_),
..
})) => {
log::trace!(" Decoding: Relay terminate");
Err(Error::RelayTerminate)
}
Ok(BcUdp::Discovery(UdpDiscovery {
payload: UdpXml {
d2c_disc: Some(_), ..
},
payload: UdpXml::D2cDisc(_),
..
})) => {
log::trace!(" Decoding:Camera terminate");
+9 -21
View File
@@ -11,10 +11,10 @@ use nom::{
type IResult<I, O, E = nom::error::VerboseError<I>> = Result<(I, O), nom::Err<E>>;
fn make_error<I, E: ParseError<I>>(input: I, ctx: &'static str, kind: ErrorKind) -> E
fn make_error<I, E>(input: I, ctx: &'static str, kind: ErrorKind) -> E
where
I: std::marker::Copy,
E: ContextError<I>,
E: ContextError<I> + ParseError<I>,
{
E::add_context(input, ctx, E::from_error_kind(input, kind))
}
@@ -164,13 +164,10 @@ mod tests {
e,
Ok(BcUdp::Discovery(UdpDiscovery {
tid: 96,
payload: UdpXml {
c2d_disc: Some(C2dDisc {
cid: 82000,
did: 80,
}),
..
},
payload: UdpXml::C2dDisc(C2dDisc {
cid: 82000,
did: 80,
}),
}))
);
}
@@ -187,15 +184,12 @@ mod tests {
e,
Ok(BcUdp::Discovery(UdpDiscovery {
tid: 113,
payload: UdpXml {
d2c_t: Some(D2cT {
payload: UdpXml::D2cT(D2cT {
sid: 62098713,
conn: conn_str,
cid: 82001,
did: 96,
}),
..
},
})) if &conn_str == "local"
);
}
@@ -212,15 +206,12 @@ mod tests {
e,
Ok(BcUdp::Discovery(UdpDiscovery {
tid: 1101,
payload: UdpXml {
c2d_t: Some(C2dT {
payload: UdpXml::C2dT(C2dT {
sid: 62098713,
conn: conn_str,
cid: 82001,
mtu: 1350,
}),
..
},
})) if &conn_str == "local"
);
}
@@ -237,8 +228,7 @@ mod tests {
e,
Ok(BcUdp::Discovery(UdpDiscovery {
tid: 1101,
payload: UdpXml {
d2c_cfm: Some(D2cCfm {
payload: UdpXml::D2cCfm(D2cCfm {
sid: 62098713,
conn: conn_str,
rsp: 0,
@@ -246,8 +236,6 @@ mod tests {
did: 96,
time_r: 0,
}),
..
},
})) if &conn_str == "local"
);
}
+9 -5
View File
@@ -1,5 +1,6 @@
use super::{crc::calc_crc, model::*, xml_crypto::encrypt};
use crate::Error;
use bytes::BytesMut;
use cookie_factory::bytes::*;
use cookie_factory::sequence::tuple;
use cookie_factory::SerializeFn;
@@ -10,7 +11,10 @@ impl BcUdp {
pub(crate) fn serialize<W: Write>(&self, buf: W) -> Result<W, Error> {
let (buf, _) = match &self {
BcUdp::Discovery(payload) => {
let xml_payload = encrypt(payload.tid, &payload.payload.serialize(vec![]).unwrap());
let xml_payload = encrypt(
payload.tid,
&payload.payload.serialize(BytesMut::new()).unwrap(),
);
gen(bcudp_disc(payload, &xml_payload), buf)?
}
BcUdp::Ack(payload) => {
@@ -96,7 +100,7 @@ mod tests {
let msg2 = BcUdp::deserialize(&mut BytesMut::from(ser_buf.as_slice())).unwrap();
assert_eq!(msg, msg2);
// Raw samples don't quite match exactly
// because the yaserde for xml puts spaces and new lines in different places
// because the serde for xml puts spaces and new lines in different places
// then the raw data from the camera so we skip this last assert
//assert_eq!(&sample[..], ser_buf.as_slice());
}
@@ -113,7 +117,7 @@ mod tests {
let msg2 = BcUdp::deserialize(&mut BytesMut::from(ser_buf.as_slice())).unwrap();
assert_eq!(msg, msg2);
// Raw samples don't quite match exactly
// because the yaserde for xml puts spaces and new lines in different places
// because the serde for xml puts spaces and new lines in different places
// then the raw data from the camera so we skip this last assert
//assert_eq!(&sample[..], ser_buf.as_slice());
}
@@ -130,7 +134,7 @@ mod tests {
let msg2 = BcUdp::deserialize(&mut BytesMut::from(ser_buf.as_slice())).unwrap();
assert_eq!(msg, msg2);
// Raw samples don't quite match exactly
// because the yaserde for xml puts spaces and new lines in different places
// because the serde for xml puts spaces and new lines in different places
// then the raw data from the camera so we skip this last assert
//assert_eq!(&sample[..], ser_buf.as_slice());
}
@@ -147,7 +151,7 @@ mod tests {
let msg2 = BcUdp::deserialize(&mut BytesMut::from(ser_buf.as_slice())).unwrap();
assert_eq!(msg, msg2);
// Raw samples don't quite match exactly
// because the yaserde for xml puts spaces and new lines in different places
// because the serde for xml puts spaces and new lines in different places
// then the raw data from the camera so we skip this last assert
//assert_eq!(&sample[..], ser_buf.as_slice());
}
+72 -75
View File
@@ -1,76 +1,73 @@
// YaSerde currently macro-expands names like __type__value from type_
use std::io::{Read, Write};
// YaSerde is currently naming the traits and the derive macros identically
use yaserde::ser::Config;
use yaserde_derive::{YaDeserialize, YaSerialize};
use serde::{Deserialize, Serialize};
use std::fmt::Write;
use std::io::BufRead;
/// The top level of the UDP xml is P2P
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[yaserde(rename = "P2P")]
pub struct UdpXml {
#[derive(PartialEq, Eq, Debug, Deserialize, Serialize, Clone)]
pub enum UdpXml {
/// C2D_S xml Discovery of any client
#[yaserde(rename = "C2D_S")]
pub c2d_s: Option<C2dS>,
#[serde(rename = "C2D_S")]
C2dS(C2dS),
/// C2D_S xml Discovery of client with a UID
#[yaserde(rename = "C2D_C")]
pub c2d_c: Option<C2dC>,
#[serde(rename = "C2D_C")]
C2dC(C2dC),
/// D2C_C_C xml Reply from discovery
#[yaserde(rename = "D2C_C_R")]
pub d2c_c_r: Option<D2cCr>,
#[serde(rename = "D2C_C_R")]
D2cCr(D2cCr),
/// D2C_T xml
#[yaserde(rename = "D2C_T")]
pub d2c_t: Option<D2cT>,
#[serde(rename = "D2C_T")]
D2cT(D2cT),
/// C2D_T xml
#[yaserde(rename = "C2D_T")]
pub c2d_t: Option<C2dT>,
#[serde(rename = "C2D_T")]
C2dT(C2dT),
/// D2C_CFM xml
#[yaserde(rename = "D2C_CFM")]
pub d2c_cfm: Option<D2cCfm>,
#[serde(rename = "D2C_CFM")]
D2cCfm(D2cCfm),
/// C2D_DISC xml Disconnect
#[yaserde(rename = "C2D_DISC")]
pub c2d_disc: Option<C2dDisc>,
#[serde(rename = "C2D_DISC")]
C2dDisc(C2dDisc),
/// D2C_DISC xml Disconnect
#[yaserde(rename = "D2C_DISC")]
pub d2c_disc: Option<D2cDisc>,
#[serde(rename = "D2C_DISC")]
D2cDisc(D2cDisc),
/// R2C_DISC xml Disconnect
#[yaserde(rename = "R2C_DISC")]
pub r2c_disc: Option<R2cDisc>,
#[serde(rename = "R2C_DISC")]
R2cDisc(R2cDisc),
/// C2M_Q xml client to middle man query
#[yaserde(rename = "C2M_Q")]
pub c2m_q: Option<C2mQ>,
#[serde(rename = "C2M_Q")]
C2mQ(C2mQ),
/// M2C_Q_R xml middle man to client query reply
#[yaserde(rename = "M2C_Q_R")]
pub m2c_q_r: Option<M2cQr>,
#[serde(rename = "M2C_Q_R")]
M2cQr(M2cQr),
/// C2R_C xml client to register connect
#[yaserde(rename = "C2R_C")]
pub c2r_c: Option<C2rC>,
#[serde(rename = "C2R_C")]
C2rC(C2rC),
/// R2C_T xml register to clinet with device ID etc
#[yaserde(rename = "R2C_T")]
pub r2c_t: Option<R2cT>,
#[serde(rename = "R2C_T")]
R2cT(R2cT),
/// R2C_T xml register to clinet with device ID etc handled over dmap ONLY
#[yaserde(rename = "R2C_C_R")]
pub r2c_c_r: Option<R2cCr>,
#[serde(rename = "R2C_C_R")]
R2cCr(R2cCr),
/// C2R_CFM xml client to register CFM
#[yaserde(rename = "C2R_CFM")]
pub c2r_cfm: Option<C2rCfm>,
#[serde(rename = "C2R_CFM")]
C2rCfm(C2rCfm),
/// C2D_A xml client to device accept
#[yaserde(rename = "C2D_A")]
pub c2d_a: Option<C2dA>,
#[serde(rename = "C2D_A")]
C2dA(C2dA),
/// C2D_HB xml client to device heartbeat. This is the keep alive
#[yaserde(rename = "C2D_HB")]
pub c2d_hb: Option<C2dHb>,
#[serde(rename = "C2D_HB")]
C2dHb(C2dHb),
/// C2D_HB xml client to device heartbeat. This is the keep alive
#[yaserde(rename = "C2R_HB")]
pub c2r_hb: Option<C2rHb>,
#[serde(rename = "C2R_HB")]
C2rHb(C2rHb),
}
impl UdpXml {
pub(crate) fn try_parse(s: impl Read) -> Result<Self, String> {
yaserde::de::from_reader(s)
pub(crate) fn try_parse(s: impl BufRead) -> Result<Self, quick_xml::de::DeError> {
quick_xml::de::from_reader(s)
}
pub(crate) fn serialize<W: Write>(&self, w: W) -> Result<W, String> {
yaserde::ser::serialize_with_writer(self, w, &Config::default())
pub(crate) fn serialize<W: Write>(&self, mut w: W) -> Result<W, quick_xml::de::DeError> {
quick_xml::se::to_writer(&mut w, self)?;
Ok(w)
}
}
@@ -80,14 +77,14 @@ impl UdpXml {
/// to whoever it gets this message from
///
/// It should be broadcasted to port 2015
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct C2dS {
/// The destination to reply to
pub to: PortList,
}
/// Port list xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct PortList {
/// Port to open udp connections with
pub port: u32,
@@ -97,7 +94,7 @@ pub struct PortList {
///
/// This will start a connection with any camera that has this UID
/// It should be broadcasted to port 2018
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct C2dC {
/// UID of the camera the client wants to connect with
pub uid: String,
@@ -110,12 +107,12 @@ pub struct C2dC {
/// Debug mode. Purpose unknown
pub debug: bool,
/// Os of the machine known values are `"MAC"`, `"WIN"`
#[yaserde(rename = "p")]
#[serde(rename = "p")]
pub os: String,
}
/// Client List xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct ClientList {
/// Port to start udp communication with
pub port: u32,
@@ -125,7 +122,7 @@ pub struct ClientList {
///
/// This will start a connection with any camera that has this UID
/// It should be broadcasted to port 2018
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct D2cCr {
/// Called timer but not sure what it is a timer of
pub timer: Timer,
@@ -138,7 +135,7 @@ pub struct D2cCr {
}
/// Timer provided by D2C_C_R
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct Timer {
/// Unknown
def: u32,
@@ -149,7 +146,7 @@ pub struct Timer {
}
/// C2D_DISC xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct C2dDisc {
/// The client connection ID
pub cid: i32,
@@ -158,7 +155,7 @@ pub struct C2dDisc {
}
/// D2C_DISC xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct D2cDisc {
/// The client connection ID
pub cid: i32,
@@ -167,14 +164,14 @@ pub struct D2cDisc {
}
/// R2C_DISC xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct R2cDisc {
/// The sid
pub sid: u32,
}
/// D2C_T xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct D2cT {
/// The camera SID
pub sid: u32,
@@ -187,7 +184,7 @@ pub struct D2cT {
}
/// C2D_T xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct C2dT {
/// The camera SID
pub sid: u32,
@@ -204,12 +201,12 @@ pub struct C2dT {
/// This is from client to a reolink middle man server
///
/// It should be sent to a reolink p2p sever on port 9999
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct C2mQ {
/// UID to look up
pub uid: String,
/// Os of the machine known values are `"MAC"`, `"WIN"`
#[yaserde(rename = "p")]
#[serde(rename = "p")]
pub os: String,
}
@@ -217,7 +214,7 @@ pub struct C2mQ {
///
/// This is from middle man reolink server to client
///
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct M2cQr {
/// The register server location
pub reg: IpPort,
@@ -232,7 +229,7 @@ pub struct M2cQr {
/// Used as part of M2C_Q_R to provide the host and port
///
/// of the register, relay and log servers
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct IpPort {
/// Ip of the service
pub ip: String,
@@ -255,7 +252,7 @@ impl std::convert::TryFrom<IpPort> for std::net::SocketAddr {
///
/// This is from client to the register reolink server
///
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct C2rC {
/// The UID to register connecition request with
pub uid: String,
@@ -270,10 +267,10 @@ pub struct C2rC {
/// Inet family. Observed values `4`
pub family: u8,
/// Os of the machine known values are `"MAC"`, `"WIN"`
#[yaserde(rename = "p")]
#[serde(rename = "p")]
pub os: String,
/// The revision. Known values None and 3
#[yaserde(rename = "r")]
#[serde(rename = "r")]
pub revision: Option<i32>,
}
@@ -281,7 +278,7 @@ pub struct C2rC {
///
/// This is from register reolink server to clinet with device ip and did etc
///
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct R2cT {
/// The location of the camera
pub dmap: Option<IpPort>,
@@ -298,7 +295,7 @@ pub struct R2cT {
/// This is from register reolink server to clinet with device ip and did etc
/// during a relay
///
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct R2cCr {
/// Dev camera location (actual local ip)
pub dev: Option<IpPort>,
@@ -319,7 +316,7 @@ pub struct R2cCr {
/// D2C_CFM xml
///
/// Device to client, with connection started from middle man server
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct D2cCfm {
/// The camera SID
pub sid: u32,
@@ -338,7 +335,7 @@ pub struct D2cCfm {
/// C2R_CFM xml
///
/// Client to register
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct C2rCfm {
/// The camera SID
pub sid: u32,
@@ -356,7 +353,7 @@ pub struct C2rCfm {
///
/// Client to device accept.
/// Sent it reply to a D2C_T
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct C2dA {
/// The camera SID
pub sid: u32,
@@ -374,7 +371,7 @@ pub struct C2dA {
///
/// Client to device heart beat.
/// Seems to act as a keep alive
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct C2dHb {
/// The client connection ID
pub cid: i32,
@@ -386,7 +383,7 @@ pub struct C2dHb {
///
/// Client to device heart beat.
/// Seems to act as a keep alive
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize, Clone)]
pub struct C2rHb {
/// The connection ID
pub sid: u32,