Work on remote/relay connections

Signed-off-by: QuantumEntangledAndy <sheepchaan@gmail.com>
This commit is contained in:
QuantumEntangledAndy authored and Andrew King committed 2023-02-22 09:55:28 +07:00
1 parent 52a4c5a120
commit 25bd29f2a7
29 files changed
+1046 -598

No files matched your search

Vendored
BIN
View File
Binary file not shown.
Generated
+3 -2
View File
@@ -93,9 +93,9 @@ dependencies = [
[[package]]
name = "async-trait"
version = "0.1.63"
version = "0.1.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eff18d764974428cf3a9328e23fc5c986f5fbed46e6cd4cdf42544df5d297ec1"
checksum = "1cd7fce9ba8c3c042128ce72d8b2ddbf3a05747efb67ea0313c635e10bda47a2"
dependencies = [
"proc-macro2",
"quote",
@@ -1124,6 +1124,7 @@ version = "0.5.1"
dependencies = [
"aes",
"anyhow",
"async-trait",
"byte-slice-cast",
"cfb-mode",
"cookie-factory",
+1
View File
@@ -43,3 +43,4 @@ byte-slice-cast = "1.0.0"
rumqttc = "0.8.0"
tokio = { version = "1.0", features = ["rt", "macros", "io-util"] }
anyhow = "1.0.42"
async-trait = "0.1.64"
+19 -2
View File
@@ -134,9 +134,26 @@ fn bc_modern_msg<'a>(
let payload;
if payload_len > 0 {
// Extract remainder of message as binary, if it exists
let encryption_protocol = context.get_encrypted();
let encryption_protocol = match header {
BcHeader {
msg_id: 1,
response_code,
..
} if (response_code & 0xff) == 0x00 => EncryptionProtocol::Unencrypted,
BcHeader {
msg_id: 1,
response_code,
..
} if (response_code & 0xff) == 0x01 => EncryptionProtocol::BCEncrypt,
BcHeader {
msg_id: 1,
response_code,
..
} if (response_code & 0xff) == 0x02 => EncryptionProtocol::Aes(None),
_ => context.get_encrypted().clone(),
};
let processed_payload_buf =
xml_crypto::decrypt(header.channel_id as u32, payload_buf, encryption_protocol);
xml_crypto::decrypt(header.channel_id as u32, payload_buf, &encryption_protocol);
if context.in_bin_mode.contains(&(header.msg_num)) {
payload = Some(BcPayloads::Binary(payload_buf.to_vec()));
} else {
+74 -1
View File
@@ -181,7 +181,80 @@ impl BcCamera {
}
SocketAddrOrUid::Uid(uid) => {
debug!("Trying uid {}", uid);
let discovery = Discovery::local(&uid).await?;
// TODO Make configurable
let allow_local = false;
let allow_remote = false;
let allow_relay = true;
let discovery = {
let mut set = tokio::task::JoinSet::new();
if allow_local {
let uid_local = uid.clone();
set.spawn(async move {
debug!("Starting Local discovery");
let result = Discovery::local(&uid_local).await;
if let Ok(disc) = &result {
debug!(
"Local discovery success {} at {}",
uid_local,
disc.get_addr()
);
}
result
});
}
if allow_remote {
let uid_remote = uid.clone();
set.spawn(async move {
debug!("Starting Remote discovery");
let result = Discovery::remote(&uid_remote).await;
if let Ok(disc) = &result {
debug!(
"Remote discovery success {} at {}",
uid_remote,
disc.get_addr()
);
}
result
});
}
if allow_relay {
let uid_relay = uid.clone();
set.spawn(async move {
debug!("Starting Relay");
let result = Discovery::relay(&uid_relay).await;
if let Ok(disc) = &result {
debug!("Relay success {} at {}", uid_relay, disc.get_addr());
}
result
});
}
let last_result;
loop {
match set.join_next().await {
Some(Ok(Ok(disc))) => {
last_result = Ok(disc);
break;
}
Some(Ok(Err(e))) => {
debug!("Discovery Error: {:?}", e);
}
Some(Err(join_error)) => {
last_result = Err(Error::OtherString(format!(
"Panic while joining Discovery threads: {:?}",
join_error
)));
break;
}
None => {
last_result = Err(Error::DiscoveryTimeout);
break;
}
}
}
last_result
}?;
Box::new(UdpSource::new_from_discovery(discovery).await?)
}
};
@@ -7,16 +7,27 @@ use crate::bcudp::codex::BcUdpCodex;
use crate::bcudp::model::*;
use crate::bcudp::xml::*;
use crate::{Error, Result};
use futures::{sink::SinkExt, stream::StreamExt};
use futures::{
sink::SinkExt,
stream::{FuturesUnordered, SplitSink, StreamExt},
};
use lazy_static::lazy_static;
use local_ip_address::local_ip;
use log::*;
use rand::{thread_rng, Rng};
use rand::{seq::SliceRandom, thread_rng, Rng};
use std::collections::{btree_map::Entry, BTreeMap};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs};
use std::sync::Arc;
use tokio::{
net::UdpSocket,
sync::{
mpsc::{channel, Receiver, Sender},
Mutex, RwLock,
},
task::JoinSet,
time::{interval, timeout, Duration},
};
use tokio_stream::wrappers::ReceiverStream;
use tokio_util::udp::UdpFramed;
pub(crate) struct Discovery {}
@@ -37,15 +48,189 @@ lazy_static! {
];
}
pub(crate) type Discoverer = UdpFramed<BcUdpCodex, UdpSocket>;
type Subscriber = Arc<RwLock<BTreeMap<u32, Sender<Result<(UdpDiscovery, SocketAddr)>>>>>;
type ArcFramedSocket = UdpFramed<BcUdpCodex, Arc<UdpSocket>>;
pub(crate) struct Discoverer {
socket: Arc<UdpSocket>,
handle: JoinSet<()>,
writer: Mutex<SplitSink<ArcFramedSocket, (BcUdp, SocketAddr)>>,
subsribers: Subscriber,
local_addr: SocketAddr,
}
impl Discoverer {
async fn new() -> Result<Discoverer> {
let socket = Arc::new(connect().await?);
let local_addr = socket.local_addr()?;
let inner: ArcFramedSocket = UdpFramed::new(socket.clone(), BcUdpCodex::new());
let (writer, mut reader) = inner.split();
let mut set = JoinSet::new();
let subsribers: Subscriber = Default::default();
let thread_subscriber = subsribers.clone();
set.spawn(async move {
loop {
match reader.next().await {
Some(Ok((BcUdp::Discovery(bcudp), addr))) => {
let tid = bcudp.tid;
let mut needs_removal = false;
if let Some(sender) = thread_subscriber.read().await.get(&tid) {
if sender.send(Ok((bcudp, addr))).await.is_err() {
needs_removal = true;
}
} else {
debug!("Udp Discovery got this unexpected BcUdp {:?}", bcudp);
}
if needs_removal {
thread_subscriber.write().await.remove(&tid);
}
}
Some(Ok(bcudp)) => {
// Only discovery packets should be possible atm
error!("Got non Discovery during discovery: {:?}", bcudp);
unreachable!()
}
Some(Err(e)) => {
let mut locked_sub = thread_subscriber.write().await;
for (_, sub) in locked_sub.iter() {
let _ = sub.send(Err(e.clone())).await;
}
locked_sub.clear();
break;
}
None => break,
}
}
});
Ok(Discoverer {
socket,
handle: set,
writer: Mutex::new(writer),
subsribers,
local_addr,
})
}
async fn into_socket(mut self) -> UdpSocket {
let socket = self.socket.clone();
self.handle.shutdown().await;
drop(self);
Arc::try_unwrap(socket).expect("Should not be shared at this point")
}
async fn subscribe(&self, tid: u32) -> Result<Receiver<Result<(UdpDiscovery, SocketAddr)>>> {
let mut subs = self.subsribers.write().await;
match subs.entry(tid) {
Entry::Vacant(vacant) => {
let (tx, rx) = channel(10);
vacant.insert(tx);
Ok(rx)
}
Entry::Occupied(mut occ) => {
if occ.get().is_closed() {
let (tx, rx) = channel(10);
occ.insert(tx);
Ok(rx)
} else {
Err(Error::SimultaneousSubscription {
msg_num: (tid as u16),
})
}
}
}
}
/// Subsciber others is for messages that we did not initiate and are therefore
/// using an unknown tid
/// In this case we subscribe to tid 0
async fn handle_incoming<T, F>(&self, map: F) -> Result<T>
where
F: Fn(UdpDiscovery, SocketAddr) -> Option<T>,
{
let mut reply = ReceiverStream::new(self.subscribe(0).await?);
loop {
let (reply, addr) = reply.next().await.ok_or(Error::ConnectionUnavaliable)??;
if let Some(result) = map(reply, addr) {
return Ok(result);
}
}
}
async fn send(&self, disc: BcUdp, addr: SocketAddr) -> Result<()> {
self.writer.lock().await.send((disc, addr)).await
}
fn local_addr(&self) -> &SocketAddr {
&self.local_addr
}
async fn retry_send_multi<F, T>(
&self,
disc: UdpDiscovery,
dests: &[SocketAddr],
map: F,
) -> Result<T>
where
F: Fn(UdpDiscovery, SocketAddr) -> Option<T>,
{
let mut set = FuturesUnordered::new();
for dest in dests.iter() {
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;
}
}
Err(Error::DiscoveryTimeout)
}
async fn retry_send<F, T>(&self, mut disc: UdpDiscovery, dest: SocketAddr, map: F) -> Result<T>
where
F: Fn(UdpDiscovery, SocketAddr) -> Option<T>,
{
let target_tid = if disc.tid == 0 {
// If 0 make a random one
let target_tid = generate_tid();
disc.tid = target_tid;
target_tid
} else {
disc.tid
};
let mut reply = ReceiverStream::new(self.subscribe(target_tid).await?);
let msg = BcUdp::Discovery(disc);
let mut inter = interval(Duration::from_millis(500));
for _i in 0..5 {
inter.tick().await;
self.send(msg.clone(), dest).await?;
if let Ok(Some(Ok((reply, addr)))) =
timeout(Duration::from_millis(500), reply.next()).await
{
if let Some(result) = map(reply, addr) {
return Ok(result);
}
}
}
Err(Error::DiscoveryTimeout)
}
}
impl Discovery {
pub(crate) async fn local(uid: &str) -> Result<DiscoveryResult> {
let mut discoverer: UdpFramed<BcUdpCodex, UdpSocket> = make_discoverer().await?;
trace!("Local");
let discoverer = Discoverer::new().await?;
let client_id = generate_cid();
let local_addr = discoverer.get_ref().local_addr()?;
let local_addr = discoverer.local_addr();
let port = local_addr.port();
let msg = UdpDiscovery {
@@ -63,9 +248,10 @@ impl Discovery {
},
};
trace!("Local: Sending Broadcast");
let dests = get_broadcasts(&[2015, 2018])?;
let (camera_address, camera_id) =
retry_send(&mut discoverer, msg, &dests, |bc, addr| match bc {
let (camera_address, camera_id) = discoverer
.retry_send_multi(msg, &dests, |bc, addr| match bc {
UdpDiscovery {
tid: _,
payload:
@@ -78,8 +264,9 @@ impl Discovery {
})
.await?;
trace!("Local: Success");
Ok(DiscoveryResult {
socket: discoverer.into_inner(),
socket: discoverer.into_socket().await,
addr: camera_address,
camera_id,
client_id,
@@ -97,15 +284,18 @@ impl Discovery {
// - Send a message to the reolink log server that we will connect locally
// - Send a message to the camera that we could connect remotely
#[allow(unused)]
async fn remote(uid: &str) -> Result<DiscoveryResult> {
let mut discoverer: UdpFramed<BcUdpCodex, UdpSocket> = make_discoverer().await?;
pub(crate) async fn remote(uid: &str) -> Result<DiscoveryResult> {
trace!("Remote");
let mut discoverer = Discoverer::new().await?;
let client_id = generate_cid();
let local_addr = discoverer.get_ref().local_addr()?;
let local_addr = *discoverer.local_addr();
let local_port = local_addr.port();
let reg_packet = get_register(&mut discoverer, uid).await?;
trace!("Remote: Finding Register");
let reg_packet = get_register(&discoverer, uid).await?;
trace!("Remote: Register Found");
let register_address = reg_packet.reg;
let relay_address = reg_packet.relay;
@@ -115,9 +305,10 @@ impl Discovery {
debug!("Register address found: {:?}", register_address);
debug!("Registering this address: {:?}", default_local_address);
trace!("Remote: Registering local IP");
let local_family = if local_addr.ip().is_ipv4() { 4 } else { 6 };
let msg = UdpDiscovery {
tid: generate_tid(),
tid: 0,
payload: UdpXml {
c2r_c: Some(C2rC {
uid: uid.to_string(),
@@ -137,35 +328,36 @@ impl Discovery {
};
let register_address_ip: IpAddr = register_address.ip.parse()?;
let (device_sid, dev_loc) = retry_send(
&mut discoverer,
msg,
&[SocketAddr::new(register_address_ip, register_address.port)],
|bc, _| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_t:
Some(R2cT {
dev: Some(dev),
cid,
sid,
..
}),
..
},
} if cid == client_id && !dev.ip.is_empty() && dev.port > 0 => Some((sid, dev)),
_ => None,
},
)
.await?;
let (device_sid, dev_loc) = discoverer
.retry_send_multi(
msg,
&[SocketAddr::new(register_address_ip, register_address.port)],
|bc, _| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_t:
Some(R2cT {
dev: Some(dev),
cid,
sid,
..
}),
..
},
} if cid == client_id && !dev.ip.is_empty() && dev.port > 0 => Some((sid, dev)),
_ => None,
},
)
.await?;
debug!("Register revealed address as SID: {:?}", device_sid);
debug!("Register revealed address as IP: {:?}", dev_loc);
trace!("Remote: Aquiring device ID");
let msg = UdpDiscovery {
tid: generate_tid(),
tid: 0,
payload: UdpXml {
c2d_t: Some(C2dT {
sid: device_sid,
@@ -177,36 +369,68 @@ impl Discovery {
},
};
let device_id = retry_send(
&mut discoverer,
msg,
&[SocketAddr::new(dev_loc.ip.parse()?, dev_loc.port)],
|bc, _| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_disc: Some(D2cDisc { cid, did, .. }),
..
},
} if cid == client_id => Some(did),
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_t: Some(D2cT { cid, did, .. }),
..
},
} if cid == client_id => Some(did),
_ => None,
},
)
.await?;
let mut device_addr = SocketAddr::new(dev_loc.ip.parse()?, dev_loc.port);
let device_id = tokio::select! {
v = discoverer
.retry_send(
msg,
device_addr,
|bc, _| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_disc: Some(D2cDisc { cid, did, .. }),
..
},
} if cid == client_id => Some(did),
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_t: Some(D2cT { cid, did, .. }),
..
},
} if cid == client_id => Some(did),
_ => None,
},
) => {v?},
// The camera can observe the registered details above and
// use them to establish it's own connection (hold punching)
// This branch handles those new camera connections
v =
discoverer
.handle_incoming(|bc, addr| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_t:
Some(D2cT {
sid,
cid,
did,
conn,
..
}),
..
},
} if cid == client_id && sid == device_sid => {
Some((did, addr))
}
_ => None,
}) => {
let (result, addr) = v?;
device_addr = addr;
result
}
};
debug!("Got device ID as: {:?}", device_id);
trace!("Remote: Declare local");
let msg = UdpDiscovery {
tid: generate_tid(),
tid: 0,
payload: UdpXml {
c2r_cfm: Some(C2rCfm {
sid: device_sid,
@@ -219,14 +443,15 @@ impl Discovery {
},
};
retry_send(
&mut discoverer,
msg,
&[SocketAddr::new(log_address.ip.parse()?, log_address.port)],
|_, _| Some(()),
)
.await?;
discoverer
.retry_send(
msg,
SocketAddr::new(log_address.ip.parse()?, log_address.port),
|_, _| Some(()),
)
.await?;
trace!("Remote: Declare map");
let msg = UdpDiscovery {
tid: generate_tid(),
payload: UdpXml {
@@ -240,17 +465,14 @@ impl Discovery {
},
};
retry_send(
&mut discoverer,
msg,
&[SocketAddr::new(dev_loc.ip.parse()?, dev_loc.port)],
|_, _| Some(()),
)
.await?;
discoverer
.retry_send(msg, device_addr, |_, _| Some(()))
.await?;
trace!("Remote: Success");
Ok(DiscoveryResult {
socket: discoverer.into_inner(),
addr: SocketAddr::new(dev_loc.ip.parse()?, dev_loc.port),
socket: discoverer.into_socket().await,
addr: device_addr,
client_id,
camera_id: device_id,
})
@@ -262,15 +484,18 @@ impl Discovery {
// cellular cameras that do not support local connections
//
#[allow(unused)]
async fn relay(uid: &str) -> Result<DiscoveryResult> {
let mut discoverer: UdpFramed<BcUdpCodex, UdpSocket> = make_discoverer().await?;
pub(crate) async fn relay(uid: &str) -> Result<DiscoveryResult> {
trace!("Relay");
let mut discoverer = Discoverer::new().await?;
let client_id = generate_cid();
let local_addr = discoverer.get_ref().local_addr()?;
let local_addr = *discoverer.local_addr();
let local_port = local_addr.port();
let reg_packet = get_register(&mut discoverer, uid).await?;
trace!("Relay: Finding Register");
let reg_packet = get_register(&discoverer, uid).await?;
trace!("Relay: Register Found");
let register_address = reg_packet.reg;
let relay_address = reg_packet.relay;
@@ -284,7 +509,7 @@ impl Discovery {
let local_family = if local_addr.ip().is_ipv4() { 4 } else { 6 };
let msg = UdpDiscovery {
tid: generate_tid(),
tid: 0,
payload: UdpXml {
c2r_c: Some(C2rC {
uid: uid.to_string(),
@@ -302,9 +527,10 @@ impl Discovery {
..Default::default()
},
};
trace!("Relay: Declaring Local IP: {}", msg.tid);
let (device_sid, dmap) =
retry_send(&mut discoverer, msg, &[register_socket], |bc, _| match bc {
let (device_sid, dmap, did) = discoverer
.retry_send(msg, register_socket, |bc, _| match bc {
UdpDiscovery {
tid: _,
payload:
@@ -318,7 +544,9 @@ impl Discovery {
}),
..
},
} if !dmap.ip.is_empty() && dmap.port > 0 && cid == client_id => Some((sid, dmap)),
} if !dmap.ip.is_empty() && dmap.port > 0 && cid == client_id => {
Some((sid, Some(dmap), None))
}
UdpDiscovery {
tid: _,
payload:
@@ -326,44 +554,90 @@ impl Discovery {
r2c_c_r: Some(R2cCr { dmap, sid, .. }),
..
},
} if !dmap.ip.is_empty() && dmap.port > 0 => Some((sid, dmap)),
} if !dmap.ip.is_empty() && dmap.port > 0 => Some((sid, Some(dmap), None)),
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_t: Some(D2cT { sid, did, .. }),
..
},
} => Some((sid, None, Some(did))),
_ => None,
})
.await?;
debug!("Register revealed dmap address as SID: {:?}", device_sid);
debug!("Register revealed dmap address as IP: {:?}", dmap);
debug!("Register revealed device ID: {:?}", did);
let msg = UdpDiscovery {
tid: generate_tid(),
payload: UdpXml {
c2d_t: Some(C2dT {
sid: device_sid,
cid: client_id,
mtu: MTU,
conn: "relay".to_string(),
}),
..Default::default()
},
let mut device_addr = register_socket;
let device_id = if let Some(dmap) = dmap {
let msg = UdpDiscovery {
tid: 0,
payload: UdpXml {
c2d_t: Some(C2dT {
sid: device_sid,
cid: client_id,
mtu: MTU,
conn: "relay".to_string(),
}),
..Default::default()
},
};
trace!("Relay: Aquiring Device ID: {}", msg.tid);
tokio::select! {
v = discoverer
.retry_send(msg, device_addr, |bc, _| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_cfm: Some(D2cCfm { cid, did, .. }),
..
},
} if cid == client_id => Some(did),
_ => None,
}) => {v?},
// The camera can observe the registered details above and
// use them to establish it's own connection (hold punching)
// This branch handles those new camera connections
v =
discoverer
.handle_incoming(|bc, addr| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_t:
Some(D2cT {
sid,
cid,
did,
conn,
..
}),
..
},
} if cid == client_id && sid == device_sid => {
Some((did, addr))
}
_ => None,
}) => {
let (result, addr) = v?;
device_addr = addr;
result
}
}
} else {
did.unwrap()
};
let device_id = retry_send(&mut discoverer, msg, &[register_socket], |bc, _| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
d2c_cfm: Some(D2cCfm { cid, did, .. }),
..
},
} if cid == client_id => Some(did),
_ => None,
})
.await?;
debug!("Got device ID as: {:?}", device_id);
let msg = UdpDiscovery {
tid: generate_tid(),
tid: 0,
payload: UdpXml {
c2r_cfm: Some(C2rCfm {
sid: device_sid,
@@ -375,18 +649,20 @@ impl Discovery {
..Default::default()
},
};
trace!("Relay: Declare Relay: {}", msg.tid);
retry_send(
&mut discoverer,
msg,
&[SocketAddr::new(log_address.ip.parse()?, log_address.port)],
|_, _| Some(()),
)
.await?;
discoverer
.retry_send(
msg,
SocketAddr::new(log_address.ip.parse()?, log_address.port),
|_, _| Some(()),
)
.await?;
trace!("Relay: Success");
Ok(DiscoveryResult {
socket: discoverer.into_inner(),
addr: register_socket,
socket: discoverer.into_socket().await,
addr: device_addr,
client_id,
camera_id: device_id,
})
@@ -399,7 +675,7 @@ impl Discovery {
//
// On success it returns the M2cQr that the p2p relay
// server has about the UID
async fn get_register(discoverer: &mut Discoverer, uid: &str) -> Result<M2cQr> {
async fn get_register(discoverer: &Discoverer, uid: &str) -> Result<M2cQr> {
let mut addrs = vec![];
for p2p_relay in P2P_RELAY_HOSTNAMES.iter() {
debug!("Trying register: {}", p2p_relay);
@@ -411,7 +687,7 @@ async fn get_register(discoverer: &mut Discoverer, uid: &str) -> Result<M2cQr> {
);
}
let msg = UdpDiscovery {
tid: generate_tid(),
tid: 0,
payload: UdpXml {
c2m_q: Some(C2mQ {
uid: uid.to_string(),
@@ -420,18 +696,19 @@ async fn get_register(discoverer: &mut Discoverer, uid: &str) -> Result<M2cQr> {
..Default::default()
},
};
let (packet, addr) = retry_send(discoverer, msg, addrs.as_slice(), |bc, addr| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
m2c_q_r: Some(m2c_q_r),
..
},
} if m2c_q_r.reg.port != 0 || !m2c_q_r.reg.ip.is_empty() => Some((m2c_q_r, addr)),
_ => None,
})
.await?;
let (packet, addr) = discoverer
.retry_send_multi(msg, addrs.as_slice(), |bc, addr| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
m2c_q_r: Some(m2c_q_r),
..
},
} if m2c_q_r.reg.port != 0 || !m2c_q_r.reg.ip.is_empty() => Some((m2c_q_r, addr)),
_ => None,
})
.await?;
debug!(
"Registry details found at {:?}: {}:{}",
@@ -475,40 +752,19 @@ fn generate_cid() -> i32 {
rng.gen()
}
async fn make_discoverer() -> Result<Discoverer> {
unimplemented!()
}
async fn retry_send<F, T>(
discoverer: &mut Discoverer,
disc: UdpDiscovery,
dests: &[SocketAddr],
map: F,
) -> Result<T>
where
F: Fn(UdpDiscovery, SocketAddr) -> Option<T>,
{
let target_tid = disc.tid;
let msg = BcUdp::Discovery(disc);
let mut inter = interval(Duration::from_millis(50));
for _i in 0..5 {
inter.tick().await;
for payload in dests.iter().map(|addr| (&msg, *addr)) {
let _ = discoverer.send(payload).await;
}
if let Ok(Some(Ok((reply, addr)))) =
timeout(Duration::from_millis(50), discoverer.next()).await
{
match reply {
BcUdp::Discovery(disc @ UdpDiscovery { tid, .. }) if tid == target_tid => {
if let Some(result) = map(disc, addr) {
return Ok(result);
}
}
smt => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt),
}
}
async fn connect() -> Result<UdpSocket> {
let mut ports: Vec<u16> = (53500..54000).into_iter().collect();
{
let mut rng = thread_rng();
ports.shuffle(&mut rng);
}
Err(Error::DiscoveryTimeout)
let addrs: Vec<_> = ports
.iter()
.map(|&port| SocketAddr::from(([0, 0, 0, 0], port)))
.collect();
let socket = UdpSocket::bind(&addrs[..]).await?;
socket.set_broadcast(true)?;
Ok(socket)
}
@@ -25,3 +25,9 @@ pub(crate) struct DiscoveryResult {
client_id: i32,
camera_id: i32,
}
impl DiscoveryResult {
pub(crate) fn get_addr(&self) -> &SocketAddr {
&self.addr
}
}
@@ -9,6 +9,7 @@ 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;
@@ -16,7 +17,10 @@ use std::io::{Error as IoError, ErrorKind, Result as IoResult};
use std::net::SocketAddr;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::net::UdpSocket;
use tokio::{
net::UdpSocket,
time::{interval, Duration, Interval},
};
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
use tokio_util::{
codec::{Decoder, Encoder, Framed},
@@ -144,6 +148,7 @@ impl BcUdpSource {
recieved: Default::default(),
state: State::Normal,
send_buffer: Default::default(),
interval: interval(Duration::from_millis(500)),
}
}
}
@@ -164,13 +169,13 @@ impl Stream for BcUdpSource {
}
}
impl Sink<(&BcUdp, SocketAddr)> for BcUdpSource {
impl Sink<(BcUdp, SocketAddr)> for BcUdpSource {
type Error = Error;
delegate! {
to Pin::new(&mut self.inner) {
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>>;
fn start_send(mut self: Pin<&mut Self>, item: (&BcUdp, SocketAddr)) -> std::result::Result<(), Self::Error>;
fn start_send(mut self: Pin<&mut Self>, item: (BcUdp, SocketAddr)) -> std::result::Result<(), Self::Error>;
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>>;
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>>;
}
@@ -193,6 +198,7 @@ pub(crate) struct UdpPayloadSource {
recieved: BTreeMap<u32, Vec<u8>>,
state: State,
send_buffer: VecDeque<BcUdp>,
interval: Interval,
}
impl UdpPayloadSource {
@@ -217,7 +223,7 @@ impl UdpPayloadSource {
};
UdpAck {
connection_id: self.client_id,
connection_id: self.camera_id,
packet_id: start,
payload: missing_ids,
}
@@ -245,10 +251,33 @@ impl Stream for UdpPayloadSource {
loop {
match this.state {
State::Normal => {
trace!("UDPSource.State: Normal");
// Data ready to go
if let Some(payload) = this.recieved.remove(&this.packets_want) {
trace!("UDPSource.Data: Ready");
this.packets_want += 1;
return Poll::Ready(Some(Ok(payload)));
}
// Check for periodic resends
if this.interval.poll_tick(cx).is_ready() {
trace!("UDPSource.RecievedPacker: Resend");
for (_, resend) in this.sent.iter() {
this.send_buffer.push_back(BcUdp::Data(resend.clone()));
}
if this.packets_want == 0 {
// When no packets have been recieved the
// ACK is different specifically unknown_b
// is set to -1 and packet_id is also set to
// -1
// TODO Add this style of ACK
} else {
let ack = BcUdp::Ack(this.build_send_ack());
this.send_buffer.push_back(ack);
}
this.state = State::Flushing;
continue;
}
// Normal behaviors
match this.inner.poll_next_unpin(cx) {
Poll::Ready(Some(Ok((
BcUdp::Data(UdpData {
@@ -257,10 +286,11 @@ impl Stream for UdpPayloadSource {
payload,
}),
addr,
)))) if connection_id == this.camera_id
)))) if connection_id == this.client_id
&& addr == camera_addr
&& packet_id >= this.packets_want =>
{
trace!("UDPSource.RecievedPacker: Data");
if packet_id == this.packets_want {
this.packets_want += 1;
return Poll::Ready(Some(Ok(payload)));
@@ -269,13 +299,11 @@ impl Stream for UdpPayloadSource {
}
// Build and queue ack
if this.packets_want == 0 {
// No packets have been received so we cannot build an Ack
// An ack requires the packet 0 to be recived
//
// This seems like an oversight in the Bc protocol
//
// TODO: See if I can replicate in camera as currently there's no way
// to say I have recived packet 1 but not packet 0
// When no packets have been recieved the
// ACK is different specifically unknown_b
// is set to -1 and packet_id is also set to
// -1
// TODO Add this style of ACK
this.state = State::Normal;
} else {
let ack = BcUdp::Ack(this.build_send_ack());
@@ -286,7 +314,8 @@ impl Stream for UdpPayloadSource {
Poll::Ready(Some(Ok((
BcUdp::Ack(ack @ UdpAck { connection_id, .. }),
addr,
)))) if connection_id == this.camera_id && addr == camera_addr => {
)))) if connection_id == this.client_id && addr == camera_addr => {
trace!("UDPSource.RecievedPacker: Ack");
this.handle_ack(ack);
for (_, resend) in this.sent.iter() {
@@ -295,31 +324,44 @@ impl Stream for UdpPayloadSource {
this.state = State::Flushing;
}
Poll::Ready(Some(Err(e))) => {
trace!("UDPSource.RecievedPacker: Error");
return Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e))));
}
Poll::Ready(None) => {
trace!("UDPSource.RecievedPacker: Empty");
return Poll::Ready(None);
}
Poll::Pending => {
return Poll::Pending;
}
_ => {
// Repeat/unintersting packet
Poll::Ready(Some(Ok((bcudp, addr)))) => {
trace!(
"UDPSource.RecievedPacker: UnexpectedData {:?} from {}",
bcudp,
addr
);
} // _ => {
// trace!("UDPSource.RecievedPacker: Other?");
// // Repeat/unintersting packet
// }
}
}
State::Flushing => {
trace!("UDPSource.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::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 => {
trace!("UDPSource.State: Closed");
return Poll::Ready(Some(Err(IoError::from(ErrorKind::ConnectionAborted))));
}
}
@@ -351,7 +393,7 @@ impl Sink<Vec<u8>> for UdpPayloadSource {
let mut this = self.get_mut();
for chunk in item.chunks(MTU - UDPDATA_HEADER_SIZE) {
let udp_data = UdpData {
connection_id: this.client_id,
connection_id: this.camera_id,
packet_id: this.packets_sent,
payload: chunk.to_vec(),
};
@@ -365,7 +407,7 @@ impl Sink<Vec<u8>> for UdpPayloadSource {
}
let addr = this.inner.addr;
Pin::new(&mut this.inner)
.start_send((&first, addr))
.start_send((first, addr))
.map_err(|e| IoError::new(ErrorKind::Other, e))?;
}
Ok(())
@@ -396,7 +438,7 @@ impl Sink<Vec<u8>> for UdpPayloadSource {
let addr = this.inner.addr;
Pin::new(&mut this.inner)
.start_send((&next, addr))
.start_send((next, addr))
.map_err(|e| IoError::new(ErrorKind::Other, e))?;
}
poll => {
+2 -2
View File
@@ -30,10 +30,10 @@ impl BcCamera {
Direction::Left => "left",
Direction::Right => "right",
Direction::In => {
unimplemented!()
todo!()
}
Direction::Out => {
unimplemented!()
todo!()
}
}
.to_string();
+2 -2
View File
@@ -15,10 +15,10 @@ impl BcUdpCodex {
}
}
impl Encoder<&BcUdp> for BcUdpCodex {
impl Encoder<BcUdp> for BcUdpCodex {
type Error = Error;
fn encode(&mut self, item: &BcUdp, dst: &mut BytesMut) -> Result<()> {
fn encode(&mut self, item: BcUdp, dst: &mut BytesMut) -> Result<()> {
let buf: Vec<u8> = Default::default();
let buf = item.serialize(buf)?;
dst.reserve(buf.len());
+2 -2
View File
@@ -4,7 +4,7 @@
use super::xml::*;
/// Top level udp packet
#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum BcUdp {
/// Packet from the negotiate stage when connection info is exchanged
@@ -30,7 +30,7 @@ impl BcUdp {
pub const MAGIC_HEADER_UDP_NEGO: u32 = 0x2a87cf3a;
/// The Discovery packet is sent and received to init a connection
#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct UdpDiscovery {
// The packet also contains these header fields not deserialized into this struct:
// 4 Bytes Magic
+20 -20
View File
@@ -6,7 +6,7 @@ use yaserde::{ser::Config, YaDeserialize, YaSerialize};
use yaserde_derive::{YaDeserialize, YaSerialize};
/// The top level of the UDP xml is P2P
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
#[yaserde(rename = "P2P")]
pub struct UdpXml {
/// C2D_S xml Discovery of any client
@@ -68,14 +68,14 @@ impl UdpXml {
/// to whoever it gets this message from
///
/// It should be broadcasted to port 2015
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct C2dS {
/// The destination to reply to
pub to: PortList,
}
/// Port list xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct PortList {
/// Port to open udp connections with
pub port: u32,
@@ -85,7 +85,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)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct C2dC {
/// UID of the camera the client wants to connect with
pub uid: String,
@@ -103,7 +103,7 @@ pub struct C2dC {
}
/// Client List xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct ClientList {
/// Port to start udp communication with
pub port: u32,
@@ -113,7 +113,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)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct D2cCr {
/// Called timer but not sure what it is a timer of
pub timer: Timer,
@@ -126,7 +126,7 @@ pub struct D2cCr {
}
/// Timer provided by D2C_C_R
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct Timer {
/// Unknown
def: u32,
@@ -137,7 +137,7 @@ pub struct Timer {
}
/// C2D_DISC xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct C2dDisc {
/// The client connection ID
pub cid: i32,
@@ -146,7 +146,7 @@ pub struct C2dDisc {
}
/// D2C_DISC xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct D2cDisc {
/// The client connection ID
pub cid: i32,
@@ -155,11 +155,11 @@ pub struct D2cDisc {
}
/// D2C_T xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct D2cT {
/// The camera SID
pub sid: u32,
/// Type of connection observed values are `"local"`
/// Type of connection observed values are `"local"` `"relay"`, `"map"`
pub conn: String,
/// The client connection ID
pub cid: i32,
@@ -168,7 +168,7 @@ pub struct D2cT {
}
/// C2D_T xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct C2dT {
/// The camera SID
pub sid: u32,
@@ -185,7 +185,7 @@ 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)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct C2mQ {
/// UID to look up
pub uid: String,
@@ -198,7 +198,7 @@ pub struct C2mQ {
///
/// This is from middle man reolink server to client
///
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct M2cQr {
/// The register server location
pub reg: IpPort,
@@ -213,7 +213,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)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct IpPort {
/// Ip of the service
pub ip: String,
@@ -225,7 +225,7 @@ pub struct IpPort {
///
/// This is from client to the register reolink server
///
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct C2rC {
/// The UID to register connecition request with
pub uid: String,
@@ -251,7 +251,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)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct R2cT {
/// The location of the camera
pub dmap: Option<IpPort>,
@@ -268,7 +268,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)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct R2cCr {
/// Dmap camera location
pub dmap: IpPort,
@@ -287,7 +287,7 @@ pub struct R2cCr {
/// D2C_CFM xml
///
/// Device to client, with connection started from middle man server
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct D2cCfm {
/// The camera SID
pub sid: u32,
@@ -306,7 +306,7 @@ pub struct D2cCfm {
/// C2R_CFM xml
///
/// Client to register
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct C2rCfm {
/// The camera SID
pub sid: u32,
+9 -8
View File
@@ -27,7 +27,8 @@ mod utils;
use cmdline::{Command, Opt};
use config::Config;
fn main() -> Result<()> {
#[tokio::main]
async fn main() -> Result<()> {
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
info!(
@@ -55,25 +56,25 @@ fn main() -> Result<()> {
"Deprecated command line option. Please use: `neolink rtsp --config={:?}`",
config
);
rtsp::main(rtsp::Opt {}, config)?;
rtsp::main(rtsp::Opt {}, config).await?;
}
Some(Command::Rtsp(opts)) => {
rtsp::main(opts, config)?;
rtsp::main(opts, config).await?;
}
Some(Command::StatusLight(opts)) => {
statusled::main(opts, config)?;
statusled::main(opts, config).await?;
}
Some(Command::Reboot(opts)) => {
reboot::main(opts, config)?;
reboot::main(opts, config).await?;
}
Some(Command::Pir(opts)) => {
pir::main(opts, config)?;
pir::main(opts, config).await?;
}
Some(Command::Talk(opts)) => {
talk::main(opts, config)?;
talk::main(opts, config).await?;
}
Some(Command::Mqtt(opts)) => {
mqtt::main(opts, config)?;
mqtt::main(opts, config).await?;
}
}
+87 -81
View File
@@ -2,13 +2,17 @@ use super::App;
use crate::config::CameraConfig;
use crate::utils::AddressOrUid;
use anyhow::{anyhow, Context, Result};
use crossbeam_channel::{bounded, unbounded, Receiver, Sender, TryRecvError};
use log::*;
use neolink_core::bc_protocol::{
BcCamera, Direction as BcDirection, Error as BcError, LightState, MotionStatus,
};
use std::sync::{Arc, Mutex};
use std::sync::Arc;
use tokio::sync::{
mpsc::{channel, error::TryRecvError, Receiver, Sender},
Mutex,
};
#[derive(Debug, Copy, Clone)]
pub(crate) enum Messages {
None,
Login,
@@ -24,6 +28,7 @@ pub(crate) enum Messages {
Ptz(Direction),
}
#[derive(Debug, Copy, Clone)]
pub(crate) enum Direction {
Up(f32),
Down(f32),
@@ -33,6 +38,7 @@ pub(crate) enum Direction {
Out(f32),
}
#[derive(Debug)]
enum ToCamera {
Send(Messages),
SendAndReply {
@@ -41,15 +47,15 @@ enum ToCamera {
},
}
pub(crate) struct EventCam<'a> {
config: &'a CameraConfig,
pub(crate) struct EventCam {
config: Arc<CameraConfig>,
app: Arc<App>,
channel_out: Arc<Mutex<Option<Receiver<Messages>>>>,
channel_in: Arc<Mutex<Option<Sender<ToCamera>>>>,
}
impl<'a> EventCam<'a> {
pub(crate) fn new(config: &'a CameraConfig, app: Arc<App>) -> Self {
impl EventCam {
pub(crate) fn new(config: Arc<CameraConfig>, app: Arc<App>) -> Self {
Self {
config,
app,
@@ -58,10 +64,10 @@ impl<'a> EventCam<'a> {
}
}
pub(crate) fn poll(&self) -> Result<Messages> {
pub(crate) async fn poll(&self) -> Result<Messages> {
if let Ok(ref mut channel_out) = self.channel_out.try_lock() {
if let Some(channel_out) = channel_out.as_mut() {
channel_out.recv().context("Camera failed to poll")
channel_out.recv().await.context("Camera failed to poll")
} else {
Ok(Messages::None)
}
@@ -70,37 +76,35 @@ impl<'a> EventCam<'a> {
}
}
pub(crate) fn send_message(&self, msg: Messages) -> Result<()> {
if let Ok(ref mut channel_in) = self.channel_in.lock() {
if let Some(channel_in) = channel_in.as_mut() {
channel_in
.send(ToCamera::Send(msg))
.context("Failed to send message from camera")
} else {
Err(anyhow!("Failed to send camera data over crossbeam"))
}
pub(crate) async fn send_message(&self, msg: Messages) -> Result<()> {
let mut channel_in = self.channel_in.lock().await;
if let Some(channel_in) = channel_in.as_mut() {
channel_in
.send(ToCamera::Send(msg))
.await
.context("Failed to send message from camera")
} else {
Err(anyhow!("Failed to lock"))
Err(anyhow!("Failed to send camera data over crossbeam"))
}
}
pub(crate) fn send_message_with_reply(&self, msg: Messages) -> Result<String> {
if let Ok(ref mut channel_in) = self.channel_in.lock() {
if let Some(channel_in) = channel_in.as_mut() {
let (tx, rx) = bounded(1);
channel_in
.send(ToCamera::SendAndReply {
message: msg,
reply: tx,
})
.context("Failed to send message from camera")?;
rx.recv_timeout(std::time::Duration::from_secs(3))
.context("Failed to recieve reply")
} else {
Err(anyhow!("Failed to send camera data over crossbeam"))
}
pub(crate) async fn send_message_with_reply(&self, msg: Messages) -> Result<String> {
let mut channel_in = self.channel_in.lock().await;
if let Some(channel_in) = channel_in.as_mut() {
let (tx, mut rx) = channel(1);
channel_in
.send(ToCamera::SendAndReply {
message: msg,
reply: tx,
})
.await
.context("Failed to send message from camera")?;
tokio::time::timeout(std::time::Duration::from_secs(3), rx.recv())
.await
.context("Failed to recieve reply Timeout")?
.ok_or_else(|| anyhow!("Failed to recieve reply"))
} else {
Err(anyhow!("Failed to lock"))
Err(anyhow!("Failed to send camera data over crossbeam"))
}
}
@@ -108,31 +112,32 @@ impl<'a> EventCam<'a> {
self.app.abort(&self.config.name);
}
pub(crate) fn start_listening(&self) {
let loop_config = self.config;
pub(crate) async fn start_listening(&self) {
let loop_config = self.config.clone();
// Channels from the camera
let (tx, rx) = unbounded();
let (tx, rx) = channel(40);
let loop_tx = Arc::new(Mutex::new(tx));
*self.channel_out.lock().unwrap() = Some(rx);
*self.channel_out.lock().await = Some(rx);
// Channels to the camera
let (stx, srx) = unbounded();
let (stx, srx) = channel(40);
let loop_rx = Arc::new(Mutex::new(srx));
*self.channel_in.lock().unwrap() = Some(stx);
*self.channel_in.lock().await = Some(stx);
while self.app.running(&self.config.name) {
// Ignore errors and just loop
let _ = Self::cam_run(
loop_config,
&loop_config,
loop_tx.clone(),
loop_rx.clone(),
self.app.clone(),
);
)
.await;
}
}
fn cam_run(
async fn cam_run(
camera_config: &CameraConfig,
tx: Arc<Mutex<Sender<Messages>>>,
rx: Arc<Mutex<Receiver<ToCamera>>>,
@@ -147,6 +152,7 @@ impl<'a> EventCam<'a> {
);
let camera = camera_addr
.connect_camera(camera_config.channel_id)
.await
.with_context(|| {
format!(
"Failed to connect to camera {} at {} on channel {}",
@@ -157,10 +163,11 @@ impl<'a> EventCam<'a> {
info!("{}: Logging in", camera_config.name);
camera
.login(&camera_config.username, camera_config.password.as_deref())
.await
.context("Failed to login to the camera")?;
info!("{}: Connected and logged in", camera_config.name);
(tx.lock().map_err(|_| anyhow!("Failed to lock"))?).send(Messages::Login)?;
(tx.lock().await).send(Messages::Login).await?;
// Shararble cameras
let arc_cam = Arc::new(camera);
@@ -179,20 +186,23 @@ impl<'a> EventCam<'a> {
name: camera_config.name.to_string(),
};
let _ = crossbeam::scope(|s| {
info!("{}: Listening to Camera Motion", camera_config.name);
s.spawn(|_| {
if let Err(e) = motion_thread.run() {
error!("Motion thread aborted: {:?}", e);
}
app.abort(&camera_config.name);
});
info!("{}: Setting up camera actions", camera_config.name);
s.spawn(|_| {
message_handler.listen();
});
let camera_name = camera_config.name.clone();
info!("{}: Listening to Camera Motion", camera_config.name);
let handle_motion = tokio::task::spawn(async move {
if let Err(e) = motion_thread.run().await {
error!("Motion thread aborted: {:?}", e);
}
app.abort(&camera_name);
});
info!("{}: Setting up camera actions", camera_config.name);
let handle_camera = tokio::task::spawn(async move {
message_handler.listen().await;
});
tokio::select! {
val = async {handle_motion.await} => {val},
val = async {handle_camera.await} => {val}
}?;
Ok(())
}
@@ -206,26 +216,22 @@ struct MotionThread {
}
impl MotionThread {
fn run(&mut self) -> Result<()> {
let mut motion_data = self.camera.listen_on_motion()?;
async fn run(&mut self) -> Result<()> {
let mut motion_data = self.camera.listen_on_motion().await?;
while self.app.running(&format!("app:{}", self.name)) {
for motion_status in motion_data.consume_motion_events()?.drain(..) {
match motion_status {
MotionStatus::Start(_) => {
(self
.tx
.lock()
.map_err(|_| BcError::Other("Failed to lock mutex"))?)
.send(Messages::MotionStart)
.map_err(|_| BcError::Other("Failed to send Message"))?;
(self.tx.lock().await)
.send(Messages::MotionStart)
.await
.map_err(|_| BcError::Other("Failed to send Message"))?;
}
MotionStatus::Stop(_) => {
(self
.tx
.lock()
.map_err(|_| BcError::Other("Failed to lock mutex"))?)
.send(Messages::MotionStop)
.map_err(|_| BcError::Other("Failed to send Message"))?;
(self.tx.lock().await)
.send(Messages::MotionStop)
.await
.map_err(|_| BcError::Other("Failed to send Message"))?;
}
_ => {}
}
@@ -243,7 +249,7 @@ struct MessageHandler {
}
impl MessageHandler {
fn listen(&mut self) {
async fn listen(&mut self) {
while self.app.running(&format!("app:{}", self.name)) {
// Try and lock don't worry if not
if let Ok(ref mut channel_out) = self.rx.try_lock() {
@@ -255,7 +261,7 @@ impl MessageHandler {
};
let reply = match message {
Messages::Reboot => {
if self.camera.reboot().is_err() {
if self.camera.reboot().await.is_err() {
error!("Failed to reboot the camera");
self.abort();
"FAIL".to_string()
@@ -264,7 +270,7 @@ impl MessageHandler {
}
}
Messages::StatusLedOn => {
if self.camera.led_light_set(true).is_err() {
if self.camera.led_light_set(true).await.is_err() {
error!("Failed to turn on the status light");
self.abort();
"FAIL".to_string()
@@ -273,7 +279,7 @@ impl MessageHandler {
}
}
Messages::StatusLedOff => {
if self.camera.led_light_set(false).is_err() {
if self.camera.led_light_set(false).await.is_err() {
error!("Failed to turn off the status light");
self.abort();
"FAIL".to_string()
@@ -282,7 +288,7 @@ impl MessageHandler {
}
}
Messages::IRLedOn => {
if self.camera.irled_light_set(LightState::On).is_err() {
if self.camera.irled_light_set(LightState::On).await.is_err() {
error!("Failed to turn on the status light");
self.abort();
"FAIL".to_string()
@@ -291,7 +297,7 @@ impl MessageHandler {
}
}
Messages::IRLedOff => {
if self.camera.irled_light_set(LightState::Off).is_err() {
if self.camera.irled_light_set(LightState::Off).await.is_err() {
error!("Failed to turn on the status light");
self.abort();
"FAIL".to_string()
@@ -300,7 +306,7 @@ impl MessageHandler {
}
}
Messages::IRLedAuto => {
if self.camera.irled_light_set(LightState::Auto).is_err() {
if self.camera.irled_light_set(LightState::Auto).await.is_err() {
error!("Failed to turn on the status light");
self.abort();
"FAIL".to_string()
@@ -309,7 +315,7 @@ impl MessageHandler {
}
}
Messages::Battery => {
unimplemented!()
todo!()
}
Messages::Ptz(direction) => {
let (bc_direction, amount) = match direction {
@@ -320,7 +326,7 @@ impl MessageHandler {
Direction::In(amount) => (BcDirection::In, amount),
Direction::Out(amount) => (BcDirection::Out, amount),
};
if self.camera.send_ptz(bc_direction, amount).is_err() {
if self.camera.send_ptz(bc_direction, amount).await.is_err() {
error!("Failed to turn on the status light");
self.abort();
"FAIL".to_string()
@@ -331,7 +337,7 @@ impl MessageHandler {
_ => "UNKNOWN COMMAND".to_string(),
};
if let Some(replier) = replier {
let _ = replier.send(reply);
let _ = replier.send(reply).await;
}
}
Err(TryRecvError::Empty) => (),
+176 -149
View File
@@ -68,7 +68,7 @@ use mqttc::{Mqtt, MqttReplyRef};
/// Entry point for the mqtt subcommand
///
/// Opt is the command line options
pub(crate) fn main(_: Opt, config: Config) -> Result<()> {
pub(crate) async fn main(_: Opt, config: Config) -> Result<()> {
let app = App::new();
let arc_app = Arc::new(app);
@@ -78,174 +78,201 @@ pub(crate) fn main(_: Opt, config: Config) -> Result<()> {
));
}
let _ = crossbeam::scope(|s| {
for camera_config in &config.cameras {
if let Some(mqtt_config) = camera_config.mqtt.as_ref() {
let loop_arc_app = arc_app.clone();
info!("{}: Setting up mqtt", camera_config.name);
s.spawn(move |_| {
while loop_arc_app.running("app") {
let _ = listen_on_camera(camera_config, mqtt_config, loop_arc_app.clone());
let mut set = tokio::task::JoinSet::new();
for camera_config in config
.cameras
.iter()
.map(|a| Arc::new(a.clone()))
.collect::<Vec<_>>()
{
if let Some(mqtt_config) = camera_config.mqtt.as_ref().map(|a| Arc::new(a.clone())) {
let loop_arc_app = arc_app.clone();
info!("{}: Setting up mqtt", camera_config.name);
set.spawn(async move {
while loop_arc_app.running("app") {
let _ =
listen_on_camera(camera_config.clone(), &mqtt_config, loop_arc_app.clone())
.await;
}
});
}
}
if let Some(result) = set.join_next().await {
result?;
}
Ok(())
}
async fn listen_on_camera(
cam_config: Arc<CameraConfig>,
mqtt_config: &MqttConfig,
arc_app: Arc<App>,
) -> Result<()> {
// Camera thread
let arc_event_cam = Arc::new(EventCam::new(cam_config.clone(), arc_app.clone()));
let arc_mqtt = Mqtt::new(mqtt_config, &cam_config.name, arc_app.clone());
let mut set = tokio::task::JoinSet::new();
// Start listening to camera events
let event_cam = arc_event_cam.clone();
set.spawn(async move {
event_cam.start_listening().await; // Loop forever
event_cam.abort(); // Just to ensure everything aborts
});
// Start listening to mqtt events
let event_cam = arc_event_cam.clone();
let mqtt = arc_mqtt.clone();
set.spawn(async move {
let _ = mqtt.start().is_err();
event_cam.abort();
});
// Listen on camera messages and post on mqtt
let camera_name = cam_config.name.clone();
let event_cam = arc_event_cam.clone();
let mqtt = arc_mqtt.clone();
let app = arc_app.clone();
set.spawn(async move {
while app.running(&format!("app: {}", camera_name)) {
if let Ok(msg) = event_cam.poll().await {
match msg {
Messages::Login => {
if mqtt.send_message("status", "connected", true).is_err() {
error!("Failed to post connect over MQTT for {}", camera_name);
}
}
});
Messages::MotionStop => {
if mqtt.send_message("status/motion", "off", true).is_err() {
error!("Failed to publish motion stop for {}", camera_name);
}
}
Messages::MotionStart => {
if mqtt.send_message("status/motion", "on", true).is_err() {
error!("Failed to publish motion start for {}", camera_name);
}
}
_ => {}
}
}
}
});
Ok(())
}
fn listen_on_camera(
cam_config: &CameraConfig,
mqtt_config: &MqttConfig,
app: Arc<App>,
) -> Result<()> {
// Camera thread
let event_cam = EventCam::new(cam_config, app.clone());
let mqtt = Mqtt::new(mqtt_config, &cam_config.name, app.clone());
let _ = crossbeam::scope(|s| {
// Start listening to camera events
s.spawn(|_| {
event_cam.start_listening(); // Loop forever
event_cam.abort(); // Just to ensure everything aborts
});
// Start listening to mqtt events
s.spawn(|_| {
let _ = mqtt.start().is_err();
event_cam.abort();
});
// Listen on camera messages and post on mqtt
s.spawn(|_| {
while app.running(&format!("app: {}", cam_config.name)) {
if let Ok(msg) = event_cam.poll() {
match msg {
Messages::Login => {
if mqtt.send_message("status", "connected", true).is_err() {
error!("Failed to post connect over MQTT for {}", cam_config.name);
}
// Listen on mqtt messages and post on camera
let event_cam = arc_event_cam.clone();
let mqtt = arc_mqtt.clone();
let app = arc_app.clone();
let camera_name = cam_config.name.clone();
set.spawn(async move {
while app.running(&format!("app: {}", camera_name)) {
if let Ok(msg) = mqtt.poll() {
match msg.as_ref() {
MqttReplyRef {
topic: "control/led",
message: "on",
} => {
if event_cam.send_message(Messages::StatusLedOn).await.is_err() {
error!("Failed to set camera status light on");
}
Messages::MotionStop => {
if mqtt.send_message("status/motion", "off", true).is_err() {
error!("Failed to publish motion stop for {}", cam_config.name);
}
}
Messages::MotionStart => {
if mqtt.send_message("status/motion", "on", true).is_err() {
error!("Failed to publish motion start for {}", cam_config.name);
}
}
_ => {}
}
}
}
});
// Listen on mqtt messages and post on camera
s.spawn(|_| {
while app.running(&format!("app: {}", cam_config.name)) {
if let Ok(msg) = mqtt.poll() {
match msg.as_ref() {
MqttReplyRef {
topic: "control/led",
message: "on",
} => {
if event_cam.send_message(Messages::StatusLedOn).is_err() {
error!("Failed to set camera status light on");
}
MqttReplyRef {
topic: "control/led",
message: "off",
} => {
if event_cam
.send_message(Messages::StatusLedOff)
.await
.is_err()
{
error!("Failed to set camera status light off");
}
MqttReplyRef {
topic: "control/led",
message: "off",
} => {
if event_cam.send_message(Messages::StatusLedOff).is_err() {
error!("Failed to set camera status light off");
}
}
MqttReplyRef {
topic: "control/ir",
message: "on",
} => {
if event_cam.send_message(Messages::IRLedOn).await.is_err() {
error!("Failed to set camera status light off");
}
MqttReplyRef {
topic: "control/ir",
message: "on",
} => {
if event_cam.send_message(Messages::IRLedOn).is_err() {
error!("Failed to set camera status light off");
}
}
MqttReplyRef {
topic: "control/ir",
message: "off",
} => {
if event_cam.send_message(Messages::IRLedOff).await.is_err() {
error!("Failed to set camera status light off");
}
MqttReplyRef {
topic: "control/ir",
message: "off",
} => {
if event_cam.send_message(Messages::IRLedOff).is_err() {
error!("Failed to set camera status light off");
}
}
MqttReplyRef {
topic: "control/ir",
message: "auto",
} => {
if event_cam.send_message(Messages::IRLedAuto).await.is_err() {
error!("Failed to set camera status light off");
}
MqttReplyRef {
topic: "control/ir",
message: "auto",
} => {
if event_cam.send_message(Messages::IRLedAuto).is_err() {
error!("Failed to set camera status light off");
}
}
MqttReplyRef {
topic: "control/reboot",
..
} => {
if event_cam.send_message(Messages::Reboot).await.is_err() {
error!("Failed to set camera status light off");
}
MqttReplyRef {
topic: "control/reboot",
..
} => {
if event_cam.send_message(Messages::Reboot).is_err() {
error!("Failed to set camera status light off");
}
}
MqttReplyRef {
topic: "control/ptz",
message,
} => {
let lowercase_message = message.to_lowercase();
let mut words = lowercase_message.split_whitespace();
if let Some(direction_txt) = words.next() {
let amount = words.next().unwrap_or("32.0");
if let Ok(amount) = amount.parse::<f32>() {
let direction = match direction_txt {
"up" => Direction::Up(amount),
"down" => Direction::Down(amount),
"left" => Direction::Left(amount),
"right" => Direction::Right(amount),
"in" => Direction::In(amount),
"out" => Direction::Out(amount),
_ => {
error!("Unrecongnized PTZ direction");
continue;
}
};
if event_cam.send_message(Messages::Ptz(direction)).is_err() {
error!("Failed to send PTZ");
}
MqttReplyRef {
topic: "control/ptz",
message,
} => {
let lowercase_message = message.to_lowercase();
let mut words = lowercase_message.split_whitespace();
if let Some(direction_txt) = words.next() {
let amount = words.next().unwrap_or("32.0");
if let Ok(amount) = amount.parse::<f32>() {
let direction = match direction_txt {
"up" => Direction::Up(amount),
"down" => Direction::Down(amount),
"left" => Direction::Left(amount),
"right" => Direction::Right(amount),
"in" => Direction::In(amount),
"out" => Direction::Out(amount),
_ => {
error!("Unrecongnized PTZ direction");
continue;
}
} else {
error!("No PTZ direction speed was not a valid number");
};
if event_cam
.send_message(Messages::Ptz(direction))
.await
.is_err()
{
error!("Failed to send PTZ");
}
} else {
error!(
"No PTZ Direction given. Please add up/down/left/right/in/out"
);
error!("No PTZ direction speed was not a valid number");
}
} else {
error!("No PTZ Direction given. Please add up/down/left/right/in/out");
}
}
MqttReplyRef {
topic: "query/battery",
..
} => match event_cam.send_message_with_reply(Messages::Battery).await {
Ok(reply) => {
if mqtt.send_message("status/battery", &reply, false).is_err() {
error!("Failed to send battery status reply");
}
}
MqttReplyRef {
topic: "query/battery",
..
} => match event_cam.send_message_with_reply(Messages::Battery) {
Ok(reply) => {
if mqtt.send_message("status/battery", &reply, false).is_err() {
error!("Failed to send battery status reply");
}
}
Err(_) => error!("Failed to set camera status light off"),
},
_ => {}
}
Err(_) => error!("Failed to set camera status light off"),
},
_ => {}
}
}
});
}
});
while set.join_next().await.is_some() {}
Ok(())
}
+3 -2
View File
@@ -24,11 +24,12 @@ pub(crate) use cmdline::Opt;
/// Entry point for the pir subcommand
///
/// Opt is the command line options
pub(crate) fn main(opt: Opt, config: Config) -> Result<()> {
let camera = find_and_connect(&config, &opt.camera)?;
pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
let camera = find_and_connect(&config, &opt.camera).await?;
camera
.pir_set(opt.on)
.await
.context("Unable to set camera PIR state")?;
Ok(())
}
+3 -2
View File
@@ -22,11 +22,12 @@ pub(crate) use cmdline::Opt;
/// Entry point for the reboot subcommand
///
/// Opt is the command line options
pub(crate) fn main(opt: Opt, config: Config) -> Result<()> {
let camera = find_and_connect(&config, &opt.camera)?;
pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
let camera = find_and_connect(&config, &opt.camera).await?;
camera
.reboot()
.await
.context("Could not send reboot command to the camera")?;
Ok(())
}
+7 -6
View File
@@ -28,13 +28,14 @@ use std::collections::HashSet;
use std::fs;
use std::io;
use std::io::Write;
use std::sync::Arc;
type Result<T> = std::result::Result<T, ()>;
type AnyResult<T> = std::result::Result<T, anyhow::Error>;
pub(crate) struct RtspServer {
server: GstRTSPServer,
main_loop: glib::MainLoop,
main_loop: Arc<glib::MainLoop>,
}
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
@@ -459,7 +460,7 @@ impl RtspServer {
}
Ok(RtspServer {
server: GstRTSPServer::new(),
main_loop: glib::MainLoop::new(None, false),
main_loop: Arc::new(glib::MainLoop::new(None, false)),
})
}
@@ -507,7 +508,7 @@ impl RtspServer {
debug!("RTSP: media was configured");
let bin = media
.element()
.expect("Media should have an element")
// .expect("Media should have an element")
.dynamic_cast::<Bin>()
.expect("Media source's element should be a bin");
let app_src = bin
@@ -631,14 +632,14 @@ impl RtspServer {
Ok(())
}
pub(crate) fn run(&self, bind_addr: &str, bind_port: u16) {
pub(crate) async fn run(&self, bind_addr: &str, bind_port: u16) {
self.server.set_address(bind_addr);
self.server.set_service(&format!("{}", bind_port));
// Attach server to default Glib context
let _ = self.server.attach(None);
let main_loop = self.main_loop.clone();
// Run the Glib main loop.
self.main_loop.run();
let _ = tokio::task::spawn_blocking(move || main_loop.run()).await;
}
#[allow(dead_code)]
+6 -19
View File
@@ -29,36 +29,23 @@ impl MaybeInputSelect {
.static_pad(&format!("sink_{}", path_num))
.ok_or_else(|| anyhow!("Unable to set input pad"))?;
match element.property("active-pad").map(|e| e.get::<'_, Pad>()) {
Ok(Ok(active_pad)) => {
match element.property_value("active-pad").get::<'_, Pad>() {
Ok(active_pad) => {
if active_pad != new_pad {
debug!("Pad need changing");
if let Err(e) = element.set_property("active-pad", new_pad) {
debug!("Element is invalid: {:?}", e);
self.clear();
} else {
debug!("Pad chanaged to {}", path_num);
}
}
}
Ok(Err(e)) => {
debug!("Pad need changing: Active pad invalid: {:?}", e);
if let Err(e) = element.set_property("active-pad", new_pad) {
debug!("Element is invalid: {:?}", e);
self.clear();
} else {
debug!("Pad chanaged to {}", path_num);
element.set_property("active-pad", new_pad);
}
}
Err(e) => {
debug!("Element is invalid: Err({:?})", e);
self.clear();
debug!("Pad need changing: Active pad invalid: {:?}", e);
element.set_property("active-pad", new_pad);
}
}
}
Ok(())
}
#[allow(dead_code)]
pub(crate) fn clear(&mut self) {
self.typefind = None;
}
+53 -43
View File
@@ -73,7 +73,7 @@ use gst::{RtspServer, TlsAuthenticationMode};
/// Entry point for the rtsp subcommand
///
/// Opt is the command line options
pub(crate) fn main(_opt: Opt, mut config: Config) -> Result<()> {
pub(crate) async fn main(_opt: Opt, mut config: Config) -> Result<()> {
let rtsp = Arc::new(RtspServer::new()?);
set_up_tls(&config, &rtsp);
@@ -85,45 +85,51 @@ pub(crate) fn main(_opt: Opt, mut config: Config) -> Result<()> {
"Without a server certificate, usernames and passwords will be exchanged in plaintext!"
)
}
crossbeam::scope(|s| {
let abort = AbortHandle::new();
let mut set = tokio::task::JoinSet::new();
let abort = AbortHandle::new();
let arc_user_config = Arc::new(config.users);
for camera_config in config.cameras.drain(..) {
// Spawn each camera controller in it's own thread
let user_config = arc_user_config.clone();
let arc_rtsp = rtsp.clone();
let abort_handle = abort.clone();
s.spawn(move |_| {
let backoff = Backoff::new();
let arc_user_config = Arc::new(config.users);
for camera_config in config.cameras.drain(..) {
// Spawn each camera controller in it's own thread
let user_config = arc_user_config.clone();
let arc_rtsp = rtsp.clone();
let abort_handle = abort.clone();
set.spawn(async move {
let backoff = Backoff::new();
while abort_handle.is_live() {
let failure =
camera_main(&camera_config, user_config.as_slice(), arc_rtsp.clone());
match failure {
Err(CameraFailureKind::Fatal(e)) => {
error!("{}: Fatal error: {:?}", camera_config.name, e);
break;
}
Err(CameraFailureKind::Retry(e)) => {
warn!("{}: Retryable error: {:?}", camera_config.name, e);
backoff.spin();
}
Ok(()) => {
info!("{}: Shutting down", camera_config.name);
break;
}
while abort_handle.is_live() {
let failure =
camera_main(&camera_config, user_config.as_slice(), arc_rtsp.clone()).await;
match failure {
Err(CameraFailureKind::Fatal(e)) => {
error!("{}: Fatal error: {:?}", camera_config.name, e);
break;
}
Err(CameraFailureKind::Retry(e)) => {
warn!("{}: Retryable error: {:?}", camera_config.name, e);
backoff.spin();
}
Ok(()) => {
info!("{}: Shutting down", camera_config.name);
break;
}
}
});
}
info!(
"Starting RTSP Server at {}:{}",
&config.bind_addr, config.bind_port,
);
rtsp.run(&config.bind_addr, config.bind_port);
})
.map_err(|e| anyhow::anyhow!("Thread panicked: {:?}", e))?;
}
});
}
info!(
"Starting RTSP Server at {}:{}",
&config.bind_addr, config.bind_port,
);
let bind_addr = config.bind_addr.clone();
let bind_port = config.bind_port;
set.spawn(async move { rtsp.run(&bind_addr, bind_port).await });
if let Some(joined) = set.join_next().await {
joined?
}
Ok(())
}
@@ -132,24 +138,27 @@ enum CameraFailureKind {
Retry(anyhow::Error),
}
fn camera_main(
async fn camera_main(
config: &CameraConfig,
user_config: &[UserConfig],
rtsp: Arc<RtspServer>,
) -> Result<(), CameraFailureKind> {
// Connect
let mut camera = RtspCamera::new(config, user_config, rtsp)
.await
.with_context(|| format!("{}: Could not connect camera", config.name))
.map_err(CameraFailureKind::Retry)?;
camera
.login()
.await
.with_context(|| format!("{}: Could not login to camera", config.name))
.map_err(CameraFailureKind::Fatal)?;
let _ = camera.manage();
let _ = camera.manage().await;
camera
.stream()
.await
.with_context(|| format!("{}: Could not start stream", config.name))
.map_err(CameraFailureKind::Retry)?;
@@ -158,6 +167,7 @@ fn camera_main(
Some(
camera
.motion_data()
.await
.with_context(|| {
"Could not initialise motion detection. Is it supported with this camera?"
})
@@ -177,7 +187,7 @@ fn camera_main(
if let Some(false) = camera.client_connected() {
if can_pause {
info!("Pause on disconnect");
camera.pause().map_err(CameraFailureKind::Retry)?;
camera.pause().await.map_err(CameraFailureKind::Retry)?;
} else if !ready_to_pause_print {
ready_to_pause_print = true;
warn!("Not ready to pause");
@@ -194,7 +204,7 @@ fn camera_main(
Some(false) => {
if can_pause {
info!("Pause on motion");
camera.pause().map_err(CameraFailureKind::Retry)?;
camera.pause().await.map_err(CameraFailureKind::Retry)?;
} else if !ready_to_pause_print {
ready_to_pause_print = true;
warn!("Not ready to pause");
@@ -203,7 +213,7 @@ fn camera_main(
None => {
if can_pause {
info!("Pause on motion (start)");
camera.pause().map_err(CameraFailureKind::Retry)?;
camera.pause().await.map_err(CameraFailureKind::Retry)?;
} else if !ready_to_pause_print {
ready_to_pause_print = true;
warn!("Not ready to pause");
@@ -223,7 +233,7 @@ fn camera_main(
if config.pause.on_disconnect {
if let Some(true) = camera.client_connected() {
info!("Resume on disconnect");
camera.stream().map_err(CameraFailureKind::Retry)?;
camera.stream().await.map_err(CameraFailureKind::Retry)?;
}
}
if config.pause.on_motion {
@@ -234,7 +244,7 @@ fn camera_main(
.map_err(CameraFailureKind::Retry)?
{
info!("Resume on motion");
camera.stream().map_err(CameraFailureKind::Retry)?;
camera.stream().await.map_err(CameraFailureKind::Retry)?;
}
}
}
+4 -2
View File
@@ -4,15 +4,17 @@
// but has not logged in
use super::{CameraState, Shared};
use anyhow::{Error, Result};
use async_trait::async_trait;
#[derive(Default)]
pub(crate) struct Connected {}
#[async_trait]
impl CameraState for Connected {
fn setup(&mut self, _shared: &Shared) -> Result<(), Error> {
async fn setup(&mut self, _shared: &Shared) -> Result<(), Error> {
Ok(())
}
fn tear_down(&mut self, _shared: &Shared) -> Result<(), Error> {
async fn tear_down(&mut self, _shared: &Shared) -> Result<(), Error> {
Ok(())
}
}
+7 -4
View File
@@ -7,20 +7,23 @@
use super::{CameraState, Shared};
use anyhow::Result;
use async_trait::async_trait;
#[derive(Default)]
pub(crate) struct LoggedIn {}
#[async_trait]
impl CameraState for LoggedIn {
fn setup(&mut self, shared: &Shared) -> Result<(), anyhow::Error> {
async fn setup(&mut self, shared: &Shared) -> Result<(), anyhow::Error> {
shared
.camera
.login(&shared.username, shared.password.as_deref())?;
.login(&shared.username, shared.password.as_deref())
.await?;
Ok(())
}
fn tear_down(&mut self, shared: &Shared) -> Result<(), anyhow::Error> {
shared.camera.logout()?;
async fn tear_down(&mut self, shared: &Shared) -> Result<(), anyhow::Error> {
shared.camera.logout().await?;
Ok(())
}
}
+26 -24
View File
@@ -47,7 +47,7 @@ pub(crate) struct RtspCamera {
}
impl RtspCamera {
pub(crate) fn new(
pub(crate) async fn new(
config: &CameraConfig,
users: &[UserConfig],
rtsp: Arc<RtspServer>,
@@ -63,6 +63,7 @@ impl RtspCamera {
info!("{}: Connecting to camera at {}", config.name, camera_addr);
let camera = camera_addr
.connect_camera(config.channel_id)
.await
.with_context(|| {
format!(
"Failed to connect to camera {} at {} on channel {}",
@@ -119,7 +120,7 @@ impl RtspCamera {
};
let mut state: Connected = Default::default();
state.setup(&shared)?;
state.setup(&shared).await?;
Ok(Self {
shared,
@@ -135,29 +136,29 @@ impl RtspCamera {
State::Paused(_) => StateInfo::Paused,
}
}
pub(crate) fn login(&mut self) -> Result<()> {
pub(crate) async fn login(&mut self) -> Result<()> {
match &mut self.state {
State::Connected(ref mut connected) => {
info!("{}: Logging in", &self.shared.name);
connected.tear_down(&self.shared)?;
connected.tear_down(&self.shared).await?;
let mut state: LoggedIn = Default::default();
state.setup(&self.shared)?;
state.setup(&self.shared).await?;
self.state = State::LoggedIn(state);
info!("{}: Successfully logged in", &self.shared.name);
}
State::Streaming(ref mut connected) => {
info!("{}: Logging in", &self.shared.name);
connected.tear_down(&self.shared)?;
connected.tear_down(&self.shared).await?;
let mut state: LoggedIn = Default::default();
state.setup(&self.shared)?;
state.setup(&self.shared).await?;
self.state = State::LoggedIn(state);
info!("{}: Successfully stopped straming", &self.shared.name);
}
State::Paused(ref mut connected) => {
info!("{}: Logging in", &self.shared.name);
connected.tear_down(&self.shared)?;
connected.tear_down(&self.shared).await?;
let mut state: LoggedIn = Default::default();
state.setup(&self.shared)?;
state.setup(&self.shared).await?;
self.state = State::LoggedIn(state);
info!(
"{}: Successfully stopped paused streaming",
@@ -171,7 +172,7 @@ impl RtspCamera {
Ok(())
}
pub(crate) fn stream(&mut self) -> Result<()> {
pub(crate) async fn stream(&mut self) -> Result<()> {
match &mut self.state {
State::Connected(_) => {
return Err(anyhow!("{}: Must login first", &self.shared.name));
@@ -183,20 +184,20 @@ impl RtspCamera {
info!("{}: Resuming stream", &self.shared.name);
let outputs = paused.take_outputs()?;
paused.tear_down(&self.shared)?;
paused.tear_down(&self.shared).await?;
let mut state: Streaming = Default::default();
state.insert_outputs(outputs)?;
state.setup(&self.shared)?;
state.setup(&self.shared).await?;
self.state = State::Streaming(state);
info!("{}: Successfully resumed streaming", &self.shared.name);
}
State::LoggedIn(ref mut loggedin) => {
info!("{}: Starting stream", &self.shared.name);
loggedin.tear_down(&self.shared)?;
loggedin.tear_down(&self.shared).await?;
let mut state: Streaming = Default::default();
state.setup(&self.shared)?;
state.setup(&self.shared).await?;
self.state = State::Streaming(state);
info!("{}: Successfully started streaming", &self.shared.name);
}
@@ -204,21 +205,21 @@ impl RtspCamera {
Ok(())
}
pub(crate) fn pause(&mut self) -> Result<()> {
pub(crate) async fn pause(&mut self) -> Result<()> {
match &mut self.state {
State::Connected(_) => {
return Err(anyhow!("{}: Must login first", &self.shared.name));
}
State::Streaming(ref mut old_state) => {
info!("{}: Pausing stream", &self.shared.name);
let outputs = old_state.take_outputs()?;
let outputs = old_state.take_outputs().await?;
old_state.tear_down(&self.shared)?;
old_state.tear_down(&self.shared).await?;
let mut state: Paused = Default::default();
state.insert_outputs(outputs)?;
state.setup(&self.shared)?;
state.setup(&self.shared).await?;
self.state = State::Paused(state);
info!("{}: Successfully paused streaming", &self.shared.name);
}
@@ -243,10 +244,11 @@ impl RtspCamera {
}
}
pub(crate) fn motion_data(&self) -> Result<MotionData> {
pub(crate) async fn motion_data(&self) -> Result<MotionData> {
self.shared
.camera
.listen_on_motion()
.await
.with_context(|| "Cannot get motion data")
}
@@ -265,11 +267,11 @@ impl RtspCamera {
}
}
pub(crate) fn manage(&self) -> Result<()> {
pub(crate) async fn manage(&self) -> Result<()> {
if let State::Connected(_) = self.state {
return Err(anyhow!("Cannot manage a camera that is not logged in"));
}
let cam_time = self.shared.camera.get_time()?;
let cam_time = self.shared.camera.get_time().await?;
if let Some(time) = cam_time {
info!("{}: Camera time is already set: {}", self.shared.name, time);
} else {
@@ -283,8 +285,8 @@ impl RtspCamera {
"{}: Camera has no time set, setting to {}",
self.shared.name, new_time
);
self.shared.camera.set_time(new_time)?;
let cam_time = self.shared.camera.get_time()?;
self.shared.camera.set_time(new_time).await?;
let cam_time = self.shared.camera.get_time().await?;
if let Some(time) = cam_time {
info!("{}: Camera time is now set: {}", self.shared.name, time);
} else {
@@ -299,7 +301,7 @@ impl RtspCamera {
if let Ok(VersionInfo {
firmwareVersion: firmware_version,
..
}) = self.shared.camera.version()
}) = self.shared.camera.version().await
{
info!(
"{}: Camera reports firmware version {}",
+4 -2
View File
@@ -4,6 +4,7 @@
// instead dummy data is sent into the gstreamer source
use anyhow::{anyhow, Error, Result};
use async_trait::async_trait;
use crossbeam::utils::Backoff;
use log::*;
use std::collections::HashMap;
@@ -26,8 +27,9 @@ pub(crate) struct Paused {
abort_handle: AbortHandle,
}
#[async_trait]
impl CameraState for Paused {
fn setup(&mut self, shared: &Shared) -> Result<(), Error> {
async fn setup(&mut self, shared: &Shared) -> Result<(), Error> {
self.abort_handle.reset();
// Create new gst outputs
//
@@ -103,7 +105,7 @@ impl CameraState for Paused {
Ok(())
}
fn tear_down(&mut self, shared: &Shared) -> Result<(), Error> {
async fn tear_down(&mut self, shared: &Shared) -> Result<(), Error> {
self.abort_handle.abort();
if !self.handles.is_empty() {
+4 -2
View File
@@ -3,6 +3,7 @@
//!
//!
use anyhow::{Error, Result};
use async_trait::async_trait;
use std::collections::HashSet;
use std::sync::Arc;
@@ -52,8 +53,9 @@ impl Shared {
}
}
#[async_trait]
pub(crate) trait CameraState: Default {
fn setup(&mut self, shared: &Shared) -> Result<(), Error>;
async fn setup(&mut self, shared: &Shared) -> Result<(), Error>;
fn tear_down(&mut self, shared: &Shared) -> Result<(), Error>;
async fn tear_down(&mut self, shared: &Shared) -> Result<(), Error>;
}
+15 -13
View File
@@ -3,11 +3,12 @@
// Data is streamed into a gstreamer source
use anyhow::{anyhow, Error, Result};
use async_trait::async_trait;
use crossbeam::utils::Backoff;
use log::*;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use tokio::task::{self, JoinHandle};
use neolink_core::bc_protocol::Stream;
@@ -25,8 +26,9 @@ pub(crate) struct Streaming {
abort_handle: AbortHandle,
}
#[async_trait]
impl CameraState for Streaming {
fn setup(&mut self, shared: &Shared) -> Result<(), Error> {
async fn setup(&mut self, shared: &Shared) -> Result<(), Error> {
self.abort_handle.reset();
// Create new gst outputs
//
@@ -89,9 +91,9 @@ impl CameraState for Streaming {
let output_thread = output.clone();
let stream_thead = *stream;
let handle = thread::spawn(move || {
let handle = task::spawn(async move {
let backoff = Backoff::new();
let stream_data = arc_camera.start_video(stream_thead, 0)?;
let mut stream_data = arc_camera.start_video(stream_thead, 0).await?;
while arc_abort_handle.is_live() {
let mut data = stream_data.get_data()?;
@@ -109,7 +111,8 @@ impl CameraState for Streaming {
Ok(())
}
fn tear_down(&mut self, shared: &Shared) -> Result<(), Error> {
async fn tear_down(&mut self, shared: &Shared) -> Result<(), Error> {
self.abort_handle.abort();
if !self.handles.is_empty() {
@@ -120,7 +123,7 @@ impl CameraState for Streaming {
}
for (stream, handle) in self.handles.drain() {
match handle.join() {
match handle.await {
Ok(Err(e)) => return Err(e),
Err(_) => return Err(anyhow!("Panicked while streaming {:?}", stream)),
Ok(Ok(_)) => {}
@@ -136,11 +139,10 @@ impl Drop for Streaming {
fn drop(&mut self) {
self.abort_handle.abort();
for (stream, handle) in self.handles.drain() {
if let Ok(Err(e)) = handle.join() {
warn!("During drop: {:?} did not stop cleanly: {:?}", stream, e);
} else {
warn!("During drop: Panicked while streaming");
for (_, handle) in self.handles.drain() {
let backoff = crossbeam::utils::Backoff::new();
while !handle.is_finished() {
backoff.spin();
}
}
}
@@ -151,10 +153,10 @@ impl Streaming {
self.handles.iter().all(|(_, h)| !h.is_finished()) && self.abort_handle.is_live()
}
pub(crate) fn take_outputs(&mut self) -> Result<HashMap<Stream, GstOutputs>> {
pub(crate) async fn take_outputs(&mut self) -> Result<HashMap<Stream, GstOutputs>> {
self.abort_handle.abort();
for (stream, handle) in self.handles.drain() {
match handle.join() {
match handle.await {
Ok(Err(e)) => return Err(e),
Err(_) => return Err(anyhow!("Panicked while streaming {:?}", stream)),
Ok(Ok(_)) => {}
+3 -2
View File
@@ -26,11 +26,12 @@ pub(crate) use cmdline::Opt;
/// Entry point for the ledstatus subcommand
///
/// Opt is the command line options
pub(crate) fn main(opt: Opt, config: Config) -> Result<()> {
let camera = find_and_connect(&config, &opt.camera)?;
pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
let camera = find_and_connect(&config, &opt.camera).await?;
camera
.led_light_set(opt.on)
.await
.context("Unable to set camera light state")?;
Ok(())
}
+4 -2
View File
@@ -24,12 +24,13 @@ pub(crate) use cmdline::Opt;
/// Entry point for the talk subcommand
///
/// Opt is the command line options
pub(crate) fn main(opt: Opt, config: Config) -> Result<()> {
pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
let camera_config = find_camera_by_name(&config, &opt.camera)?;
let camera = connect_and_login(camera_config)?;
let camera = connect_and_login(camera_config).await?;
let talk_ability = camera
.talk_ability()
.await
.with_context(|| format!("Camera {} does not support talk", camera_config.name))?;
if talk_ability.duplex_list.is_empty()
|| talk_ability.audio_stream_mode_list.is_empty()
@@ -82,6 +83,7 @@ pub(crate) fn main(opt: Opt, config: Config) -> Result<()> {
camera
.talk_stream(rx, talk_config)
.await
.context("Talk stream ended early")?;
Ok(())
+8 -6
View File
@@ -33,20 +33,20 @@ impl AddressOrUid {
}
// Convience method to get the BcCamera with the appropiate method
pub(crate) fn connect_camera(&self, channel_id: u8) -> Result<BcCamera, Error> {
pub(crate) async fn connect_camera(&self, channel_id: u8) -> Result<BcCamera, Error> {
match self {
AddressOrUid::Address(host) => Ok(BcCamera::new_with_addr(host, channel_id)?),
AddressOrUid::Uid(host) => Ok(BcCamera::new_with_uid(host, channel_id)?),
AddressOrUid::Address(host) => Ok(BcCamera::new_with_addr(host, channel_id).await?),
AddressOrUid::Uid(host) => Ok(BcCamera::new_with_uid(host, channel_id).await?),
}
}
}
pub(crate) fn find_and_connect(config: &Config, name: &str) -> Result<BcCamera> {
pub(crate) async fn find_and_connect(config: &Config, name: &str) -> Result<BcCamera> {
let camera_config = find_camera_by_name(config, name)?;
connect_and_login(camera_config)
connect_and_login(camera_config).await
}
pub(crate) fn connect_and_login(camera_config: &CameraConfig) -> Result<BcCamera> {
pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result<BcCamera> {
let camera_addr =
AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap();
info!(
@@ -56,6 +56,7 @@ pub(crate) fn connect_and_login(camera_config: &CameraConfig) -> Result<BcCamera
let camera = camera_addr
.connect_camera(camera_config.channel_id)
.await
.with_context(|| {
format!(
"Failed to connect to camera {} at {} on channel {}",
@@ -66,6 +67,7 @@ pub(crate) fn connect_and_login(camera_config: &CameraConfig) -> Result<BcCamera
info!("{}: Logging in", camera_config.name);
camera
.login(&camera_config.username, camera_config.password.as_deref())
.await
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
info!("{}: Connected and logged in", camera_config.name);