Compare commits

...
Author SHA1 Message Date
QuantumEntangledAndy eefe3dfa71 Make listen on motion as fire on AIType 2023-08-08 16:26:04 +07:00
QuantumEntangledAndy 6e8fc3ee5b Add battery sub command 2023-08-07 19:03:31 +07:00
QuantumEntangledAndy 17e8ab0f37 Add gracefull shutdown to sub commands 2023-08-07 19:03:06 +07:00
QuantumEntangledAndy 0d2f0c3e6f Also bump man cargo version number 2023-08-07 17:22:14 +07:00
QuantumEntangledAndy 0661aa8853 v0.5.17 2023-08-07 16:35:38 +07:00
Andrew King a380212662 Merge pull request #127 from QuantumEntangledAndy/fix/sim_sub_disc
Fix login on new firmware
2023-08-07 16:33:12 +07:00
QuantumEntangledAndy a45bcf8761 Added enable config option 2023-08-07 10:52:16 +07:00
QuantumEntangledAndy c198f21c92 Add a latency field to the ack packet 2023-08-07 09:01:13 +07:00
QuantumEntangledAndy 5109dbba9e Only decrypt bcmecia packets where encrypt len is set 2023-08-06 19:05:04 +07:00
QuantumEntangledAndy b90d6d7eed Try AES on binary payloads 2023-08-06 17:31:08 +07:00
QuantumEntangledAndy 971c1cddf8 Match on 0x12 inside de.rs too 2023-08-05 10:10:22 +07:00
QuantumEntangledAndy 816797a32b Match both 0x02, 0x12 as the basic AES 2023-08-04 22:27:28 +07:00
QuantumEntangledAndy c3921cbb6c Try with a 0x12 for the login kind 2023-08-04 21:46:03 +07:00
QuantumEntangledAndy e93dc2fe9a Don't send -1 ack packets again 2023-08-04 21:09:56 +07:00
QuantumEntangledAndy af899d3cfd Empty legacy packet 2023-08-04 19:53:02 +07:00
QuantumEntangledAndy 6b60ee6bcc Don't send -1 ack packets 2023-08-04 18:59:14 +07:00
QuantumEntangledAndy 810dd3cdc7 Fix early exit on discovery 2023-08-04 18:53:08 +07:00
Andrew 374b399631 Fix simultaneous discovery subscription 2023-08-04 16:33:39 +07:00
33 changed files with 401 additions and 141 deletions

No files matched your search

Generated
+2 -2
View File
@@ -1425,7 +1425,7 @@ dependencies = [
[[package]]
name = "neolink"
version = "0.5.16"
version = "0.5.17"
dependencies = [
"anyhow",
"base64 0.21.2",
@@ -1460,7 +1460,7 @@ dependencies = [
[[package]]
name = "neolink_core"
version = "0.5.16"
version = "0.5.17"
dependencies = [
"aes",
"assert_matches",
+2 -2
View File
@@ -1,7 +1,7 @@
[package]
name = "neolink"
description = "A standards-compliant bridge to Reolink IP cameras"
version = "0.5.16"
version = "0.5.17"
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
edition = "2018"
license = "AGPL-3.0-or-later"
@@ -29,7 +29,7 @@ is_sorted = "0.1.1"
itertools = "0.11.0"
lazy_static = "1.4.0"
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
neolink_core = { path = "crates/core", version = "0.5.16" }
neolink_core = { path = "crates/core", version = "0.5.17" }
regex = "1.7.3"
rumqttc = "0.22.0"
serde = { version = "1.0.160", features = ["derive"] }
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "neolink_core"
description = "Core services and structure for Reolink IP cameras"
version = "0.5.16"
version = "0.5.17"
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
edition = "2018"
license = "AGPL-3.0-or-later"
+6 -1
View File
@@ -29,7 +29,9 @@ impl Encoder<Bc> for BcCodex {
// let context = self.context.read().unwrap();
let buf: Vec<u8> = Default::default();
let enc_protocol: EncryptionProtocol = match self.context.get_encrypted() {
EncryptionProtocol::Aes(_) if item.meta.msg_id == 1 => {
EncryptionProtocol::Aes(_) | EncryptionProtocol::FullAes(_)
if item.meta.msg_id == 1 =>
{
// During login the encyption protocol cannot go higher than BCEncrypt
// even if we support AES. (BUt it can go lower i.e. None)
EncryptionProtocol::BCEncrypt
@@ -113,6 +115,9 @@ impl Decoder for BcCodex {
0x02 => self.context.set_encrypted(EncryptionProtocol::Aes(
self.context.credentials.make_aeskey(nonce),
)),
0x12 => self.context.set_encrypted(EncryptionProtocol::FullAes(
self.context.credentials.make_aeskey(nonce),
)),
_ => {
return Err(Error::UnknownEncryption(encryption_protocol_byte));
}
+38 -17
View File
@@ -113,8 +113,13 @@ fn bc_modern_msg<'a>(
};
let mut in_binary = false;
let mut encrypted_len = None;
// Now we'll take the buffer that Nom gave a ref to and parse it.
let extension = if ext_len > 0 {
log::trace!(
"Extension Txt: {:?}",
String::from_utf8(processed_ext_buf.to_vec()).unwrap_or("Not Text".to_string())
);
// Apply the XML parse function, but throw away the reference to decrypted in the Ok and
// Err case. This error-error-error thing is the same idiom Nom uses internally.
let parsed = Extension::try_parse(processed_ext_buf).map_err(|_| {
@@ -126,11 +131,13 @@ fn bc_modern_msg<'a>(
})?;
if let Extension {
binary_data: Some(1),
encrypt_len,
..
} = parsed
{
// In binary so tell the current context that we need to treat the payload as binary
in_binary = true;
encrypted_len = encrypt_len;
}
Some(parsed)
} else {
@@ -149,22 +156,23 @@ fn bc_modern_msg<'a>(
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::BCEncrypt, // This is AES but the first packet with the NONCE is BCEcrypt, since the NONCE in this packet is required to build the AES key
BcHeader { msg_id: 1, .. }
if matches!(context.get_encrypted(), EncryptionProtocol::Aes(_)) =>
{
// Maximum encryption level is BCEncrypt during login... Not sure why Reolink did it like that
EncryptionProtocol::BCEncrypt
} if (response_code >> 8) & 0xff == 0xdd => {
// 0xdd means we are setting the encryption method
// Durig login, the max encryption is BcEncrypt since
// the nonce has not been exchanged yet
match response_code & 0xff {
0x00 => EncryptionProtocol::Unencrypted,
_ => EncryptionProtocol::BCEncrypt,
}
}
BcHeader { msg_id: 1, .. } => {
match *context.get_encrypted() {
EncryptionProtocol::Aes(_) | EncryptionProtocol::FullAes(_) => {
// During login max is BcEncrypt
EncryptionProtocol::BCEncrypt
}
n => n,
}
}
_ => *context.get_encrypted(),
};
@@ -172,8 +180,21 @@ fn bc_modern_msg<'a>(
let processed_payload_buf =
xml_crypto::decrypt(header.channel_id as u32, payload_buf, &encryption_protocol);
if context.in_bin_mode.contains(&(header.msg_num)) || in_binary {
payload = Some(BcPayloads::Binary(payload_buf.to_vec()));
payload = match (context.get_encrypted(), encrypted_len) {
(EncryptionProtocol::FullAes(_), Some(encrypted_len)) => {
log::trace!("Binary: {:X?}", &processed_payload_buf[0..30]);
Some(BcPayloads::Binary(
processed_payload_buf[0..(encrypted_len as usize)].to_vec(),
))
}
_ => Some(BcPayloads::Binary(payload_buf.to_vec())),
};
} else {
log::trace!(
"Payload Txt: {:?}",
String::from_utf8(processed_payload_buf.to_vec()).unwrap_or("Not Text".to_string())
);
let xml = BcXml::try_parse(processed_payload_buf.as_slice()).map_err(|_| {
error!("header.msg_id: {}", header.msg_id);
error!(
+5
View File
@@ -128,6 +128,8 @@ pub enum LegacyMsg {
/// Password for a legacy login
password: String,
},
/// Sent to upgrade to modern and not exposed the MD5 username/password
LoginUpgrade,
/// Any other type of legacy message will be collected here
UnknownMsg,
}
@@ -198,6 +200,9 @@ pub enum EncryptionProtocol {
/// Latest cameras/firmwares use Aes with the key derived from
/// the camera's password and the negotiated NONCE
Aes([u8; 16]),
/// Same as Aes but the media stream is also encrypted and not just
/// the control commands
FullAes([u8; 16]),
}
#[derive(Debug)]
+4
View File
@@ -130,6 +130,10 @@ fn bc_legacy<W: Write>(legacy: &'_ LegacyMsg) -> impl SerializeFn<W> + '_ {
slice(&[0u8; 1772][..]),
))(out)
}
LoginUpgrade => {
// Write nothing as it is header only
slice(&[])(out)
}
UnknownMsg => {
panic!("Cannot serialize an unknown message!");
}
+15
View File
@@ -259,6 +259,15 @@ pub struct Extension {
/// The rfID used in the PIR
#[yaserde(rename = "rfId")]
pub rf_id: Option<u8>,
/// Encrypted binary has this to verify successful decryption
#[yaserde(rename = "checkPos")]
pub check_pos: Option<u32>,
/// Encrypted binary has this to verify successful decryption
#[yaserde(rename = "checkValue")]
pub check_value: Option<u32>,
/// Used in newer encrypted payload packets
#[yaserde(rename = "encryptLen")]
pub encrypt_len: Option<u32>,
}
impl Default for Extension {
@@ -270,6 +279,9 @@ impl Default for Extension {
token: None,
channel_id: None,
rf_id: None,
check_pos: None,
check_value: None,
encrypt_len: None,
}
}
}
@@ -552,6 +564,9 @@ pub struct AlarmEvent {
pub channel_id: u8,
/// Motion status. Known values are `"MD"` or `"none"`
pub status: String,
/// AI status. Known values are `"people"` or `"none"`
#[yaserde(rename = "AItype")]
pub ai_type: Option<String>,
/// The recording status. Known values `0` or `1`
pub recording: i32,
/// The timestamp associated with the recording. `0` if not recording
+2 -2
View File
@@ -21,7 +21,7 @@ pub fn decrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol
.map(|(key, i)| *i ^ key ^ (offset as u8))
.collect()
}
EncryptionProtocol::Aes(aeskey) => {
EncryptionProtocol::Aes(aeskey) | EncryptionProtocol::FullAes(aeskey) => {
// AES decryption
let mut decrypted = buf.to_vec();
@@ -41,7 +41,7 @@ pub fn encrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol
// Encrypt is the same as decrypt
decrypt(offset, buf, encryption_protocol)
}
EncryptionProtocol::Aes(aeskey) => {
EncryptionProtocol::Aes(aeskey) | EncryptionProtocol::FullAes(aeskey) => {
// AES encryption
let mut encrypted = buf.to_vec();
Aes128CfbEnc::new(aeskey.into(), IV.into()).encrypt(&mut encrypted);
+22 -16
View File
@@ -85,8 +85,6 @@ pub struct BcCameraOpt {
pub protocol: ConnectionProtocol,
/// Discovery method to allow
pub discovery: DiscoveryMethods,
/// Printing format for auxilaary data such as battery levels
pub aux_printing: PrintFormat,
/// Credentials for login
pub credentials: Credentials,
}
@@ -186,7 +184,7 @@ impl BcCamera {
};
let res = tokio::select! {
v = async {
Ok(v) = async {
let uid_local = uid.clone();
info!("{}: Trying local discovery", options.name);
let result = discovery.local(&uid_local, Some(sockets)).await;
@@ -202,8 +200,9 @@ impl BcCamera {
},
Err(e) => Err(e)
}
}, if allow_local => v,
v = async {
}, if allow_local => Ok(v),
Ok(v) = async {
let mut discovery = Discovery::new().await?;
let reg_result;
// Registration is looped as it seems that reolink
// only updates the registration lazily when someone attempts
@@ -212,17 +211,25 @@ impl BcCamera {
//
// We loop infinitly and allow the caller to timeout at the
// interval they desire
let mut retry = 0;
const MAX_RETRY: usize = 10;
loop {
tokio::task::yield_now().await;
if let Ok(result) = discovery.get_registration(uid).await {
reg_result = result;
break;
}
log::debug!("Registration failed. Retrying");
if retry >= MAX_RETRY {
return Err(Error::DiscoveryTimeout);
}
log::info!("{}: Registration with reolink servers failed. Retrying: {}/{}", options.name, retry + 1, MAX_RETRY);
retry += 1;
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
// New discovery to get new client IDs
discovery = Discovery::new().await?;
};
tokio::select! {
v = async {
Ok(v) = async {
let uid_remote = uid.clone();
info!("{}: Trying remote discovery", options.name);
let result = discovery
@@ -240,8 +247,8 @@ impl BcCamera {
},
Err(e) => Err(e)
}
}, if allow_remote => v,
v = async {
}, if allow_remote => Ok(v),
Ok(v) = async {
let uid_map = uid.clone();
info!("{}: Trying map discovery", options.name);
let result = discovery.map(&reg_result).await;
@@ -257,8 +264,8 @@ impl BcCamera {
},
Err(e) => Err(e),
}
}, if allow_map => v,
v = async {
}, if allow_map => Ok(v),
Ok(v) = async {
let uid_relay = uid.clone();
info!("{}: Trying relay discovery", options.name);
let result = discovery.relay(&reg_result).await;
@@ -274,9 +281,11 @@ impl BcCamera {
},
Err(e) => Err(e),
}
}, if allow_relay => v,
}, if allow_relay => Ok(v),
else => Err(Error::DiscoveryTimeout),
}
}, if allow_remote || allow_map || allow_relay => v,
}, if allow_remote || allow_map || allow_relay => Ok(v),
else => Err(Error::DiscoveryTimeout),
}?;
return Ok(res);
@@ -332,9 +341,6 @@ impl BcCamera {
abilities: Default::default(),
};
me.keepalive().await?;
if let Err(e) = me.monitor_battery(options.aux_printing).await {
warn!("Could not monitor battery: {:?}", e);
}
Ok(me)
}
@@ -295,6 +295,7 @@ impl Poller {
if occ_entry.get().is_closed() {
occ_entry.insert(tx);
} else {
// log::error!("Failed to subscribe in bcconn to {:?} for {:?}", msg_num, msg_id);
let _ = tx
.send(Err(Error::SimultaneousSubscription { msg_num }))
.await;
@@ -78,12 +78,14 @@ lazy_static! {
}
type Subscriber = Arc<RwLock<BTreeMap<u32, Sender<Result<(UdpDiscovery, SocketAddr)>>>>>;
type Handlers = Arc<RwLock<Vec<Sender<Result<(UdpDiscovery, SocketAddr)>>>>>;
type ArcFramedSocket = UdpFramed<BcUdpCodex, Arc<UdpSocket>>;
pub(crate) struct Discoverer {
socket: Arc<UdpSocket>,
handle: RwLock<JoinSet<()>>,
writer: Sender<Result<(BcUdp, SocketAddr)>>,
subsribers: Subscriber,
handlers: Handlers,
local_addr: SocketAddr,
}
@@ -96,26 +98,27 @@ impl Discoverer {
let (mut writer, mut reader) = inner.split();
let mut set = JoinSet::new();
let subsribers: Subscriber = Default::default();
let handlers: Handlers = Default::default();
let thread_subscriber = subsribers.clone();
let thread_handlers = handlers.clone();
set.spawn(async move {
loop {
tokio::task::yield_now().await;
match reader.next().await {
Some(Ok((BcUdp::Discovery(bcudp), addr))) => {
let mut tid = bcudp.tid;
let tid = bcudp.tid;
let mut needs_removal = false;
if let Some(sender) = thread_subscriber.read().await.get(&tid) {
if let (Some(sender), true) =
(thread_subscriber.read().await.get(&tid), tid > 0)
{
if sender.send(Ok((bcudp, addr))).await.is_err() {
needs_removal = true;
}
} else if let Some(any_sender) = thread_subscriber.read().await.get(&0) {
if any_sender.send(Ok((bcudp, addr))).await.is_err() {
tid = 0; // To make is remove 0
needs_removal = true;
}
} else {
trace!("Udp Discovery got this unexpected BcUdp {:?}", bcudp);
for sender in thread_handlers.write().await.iter_mut() {
let _ = sender.send(Ok((bcudp.clone(), addr))).await;
}
}
if needs_removal {
thread_subscriber.write().await.remove(&tid);
@@ -148,6 +151,7 @@ impl Discoverer {
handle: RwLock::new(set),
writer: sinker,
subsribers,
handlers,
local_addr,
})
}
@@ -157,24 +161,33 @@ impl Discoverer {
}
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() {
if tid > 0 {
let mut subs = self.subsribers.write().await;
match subs.entry(tid) {
Entry::Vacant(vacant) => {
let (tx, rx) = channel(10);
occ.insert(tx);
vacant.insert(tx);
Ok(rx)
} else {
Err(Error::SimultaneousSubscription {
msg_num: Some(tid as u16),
})
}
Entry::Occupied(mut occ) => {
if occ.get().is_closed() {
let (tx, rx) = channel(10);
occ.insert(tx);
Ok(rx)
} else {
// log::error!("Failed to subscribe in discovery to {:?}", tid);
Err(Error::SimultaneousSubscription {
msg_num: Some(tid as u16),
})
}
}
}
} else {
// If tid is zero we listen to all!
let mut handlers = self.handlers.write().await;
let (tx, rx) = channel(10);
handlers.push(tx);
Ok(rx)
}
}
@@ -429,69 +442,103 @@ impl Discoverer {
// Send and await acceptance
let (sid, dev, dmap, relay) = self
.retry_send(msg, lookup.reg, |bc, _| match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_c_r:
Some(R2cCr {
dmap,
dev,
relay,
sid,
rsp,
..
}),
..
},
} if (dev
.as_ref()
.map(|d| !d.ip.is_empty() && d.port > 0)
.unwrap_or(false)
|| dmap
.retry_send(msg, lookup.reg, |bc, socket| {
trace!("{}", socket.ip());
match bc {
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_c_r:
Some(R2cCr {
dmap,
dev,
relay,
sid,
rsp,
..
}),
..
},
} if (dev
.as_ref()
.map(|d| !d.ip.is_empty() && d.port > 0)
.unwrap_or(false)
|| relay
.as_ref()
.map(|d| !d.ip.is_empty() && d.port > 0)
.unwrap_or(false))
&& rsp != -1 =>
{
Some(Ok((sid, dev, dmap, relay)))
}
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_c_r:
Some(R2cCr {
dev,
dmap,
relay,
rsp,
..
}),
..
},
} if (dev
.as_ref()
.map(|d| !d.ip.is_empty() && d.port > 0)
.unwrap_or(false)
|| dmap
|| dmap
.as_ref()
.map(|d| !d.ip.is_empty() && d.port > 0)
.unwrap_or(false)
|| relay
.as_ref()
.map(|d| !d.ip.is_empty() && d.port > 0)
.unwrap_or(false))
&& rsp != -1 =>
{
Some(Ok((sid, dev, dmap, relay)))
}
// UdpDiscovery {
// tid: _,
// payload:
// UdpXml {
// r2c_c_r:
// Some(R2cCr {
// dmap,
// dev,
// relay: Some(mut relay),
// sid,
// rsp,
// ..
// }),
// ..
// },
// } if (dev
// .as_ref()
// .map(|d| !d.ip.is_empty() && d.port > 0)
// .unwrap_or(false)
// || dmap
// .as_ref()
// .map(|d| !d.ip.is_empty() && d.port > 0)
// .unwrap_or(false)
// || (relay.ip == format!("{}", socket.ip()) && relay.port == 0))
// && rsp != -1 =>
// {
// // For a relay connection if port is 0 and the ip is the current socker addr
// // we use the current port
// relay.port = socket.port();
// Some(Ok((sid, dev, dmap, Some(relay))))
// }
UdpDiscovery {
tid: _,
payload:
UdpXml {
r2c_c_r:
Some(R2cCr {
dev,
dmap,
relay,
rsp,
..
}),
..
},
} if (dev
.as_ref()
.map(|d| !d.ip.is_empty() && d.port > 0)
.unwrap_or(false)
|| relay
.as_ref()
.map(|d| !d.ip.is_empty() && d.port > 0)
.unwrap_or(false))
&& rsp == -1 =>
{
Some(Err(Error::RegisterError))
|| dmap
.as_ref()
.map(|d| !d.ip.is_empty() && d.port > 0)
.unwrap_or(false)
|| relay
.as_ref()
.map(|d| !d.ip.is_empty() && d.port > 0)
.unwrap_or(false))
&& rsp == -1 =>
{
Some(Err(Error::RegisterError))
}
_ => None,
}
_ => None,
})
.await??;
@@ -20,7 +20,7 @@ use std::sync::Arc;
use std::task::{Context, Poll};
use tokio::{
net::UdpSocket,
time::{interval, Duration, Interval},
time::{interval, Duration, Instant, Interval},
};
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
use tokio_util::{
@@ -164,6 +164,7 @@ impl BcUdpSource {
send_buffer: Default::default(),
ack_interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms
resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms
ack_latency: Default::default(),
}
}
}
@@ -205,6 +206,57 @@ enum State {
YieldNow, // Used to ensure we rest between polling packets so as to not starve the runtime
}
#[derive(Default)]
struct AckLatency {
current_values: Vec<u32>,
last_recieve_time: Option<Instant>,
display_value: u32,
last_display_time: Option<Instant>,
}
impl AckLatency {
/// Used to get the current latency, in thd way that the official
/// client does. This is a value that seems to be updated only every second
/// Observed values are `0`, `54785`, `55062`, `2528`,
fn get_value(&self) -> u32 {
self.display_value
}
/// Used to updaet the average latency calculation
fn feed_ack(&mut self) {
// Update the last recieve time
let now = Instant::now();
if let Some(last_recieve_time) = self.last_recieve_time {
let diff = (now - last_recieve_time).as_micros();
self.current_values.push(diff as u32);
self.last_recieve_time = Some(now);
} else {
self.last_recieve_time = Some(now);
}
// Update the display_value
// this is done only ever 1s
if let Some(last_display_time) = self.last_display_time {
if now - last_display_time > Duration::from_secs(1) {
// A second has passed update this
self.last_display_time = Some(now);
let current_values_count = self.current_values.len() as u32;
let current_value = self
.current_values
.iter()
.fold(0u32, |acc, value| acc + *value / current_values_count);
self.current_values = vec![]; // Reset the average vec
self.display_value = current_value;
}
} else {
// First 1s is a zero value
self.last_display_time = Some(now);
self.display_value = 0;
}
}
}
pub(crate) struct UdpPayloadSource {
inner: BcUdpSource,
client_id: i32,
@@ -222,6 +274,7 @@ pub(crate) struct UdpPayloadSource {
/// Offical Client does resend every 500ms
/// This `resend_interval` controls how ofen we do this
resend_interval: Interval,
ack_latency: AckLatency,
}
impl UdpPayloadSource {
@@ -253,6 +306,7 @@ impl UdpPayloadSource {
connection_id: self.camera_id,
packet_id: first_missing - 1, // Last we actually have is first_missing - 1
group_id: 0,
maybe_latency: self.ack_latency.get_value(),
payload: missing_ids,
}
} else {
@@ -273,6 +327,7 @@ impl UdpPayloadSource {
}
}
}
self.ack_latency.feed_ack();
}
fn maintanence(&mut self, cx: &mut Context<'_>) {
@@ -282,7 +337,9 @@ impl UdpPayloadSource {
self.send_buffer.push_back(BcUdp::Data(resend.clone()));
}
}
if self.ack_interval.poll_tick(cx).is_ready() {
if self.ack_interval.poll_tick(cx).is_ready()
// && self.packets_want > 0
{
let ack = BcUdp::Ack(self.build_send_ack());
self.send_buffer.push_back(ack);
self.state = State::Flushing;
+9 -12
View File
@@ -1,4 +1,4 @@
use super::{md5_string, BcCamera, Error, Result, Truncate, ZeroLast};
use super::{md5_string, BcCamera, Error, Result, Truncate};
use crate::bc::{model::*, xml::*};
use std::sync::atomic::Ordering;
@@ -48,17 +48,17 @@ impl BcCamera {
// Note: I suspect there may be a buffer overflow opportunity in the firmware since in the
// Baichuan library, these strings are capped at 32 bytes with a null terminator. This
// could also be a mistake in the library, the effect being it only compares 31 chars, not 32.
let md5_username = md5_string(&credentials.username, ZeroLast);
let md5_password = credentials
.password
.as_ref()
.map(|p| md5_string(p, ZeroLast))
.unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned());
// let md5_username = md5_string(&credentials.username, ZeroLast);
// let md5_password = credentials
// .password
// .as_ref()
// .map(|p| md5_string(p, ZeroLast))
// .unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned());
let enc_byte = match max_encryption {
MaxEncryption::None => 0xdc00,
MaxEncryption::BcEncrypt => 0xdc01,
MaxEncryption::Aes => 0xdc02,
MaxEncryption::Aes => 0xdc12,
};
let legacy_login = Bc {
meta: BcMeta {
@@ -69,10 +69,7 @@ impl BcCamera {
response_code: enc_byte,
class: 0x6514,
},
body: BcBody::LegacyMsg(LegacyMsg::LoginMsg {
username: md5_username,
password: md5_password,
}),
body: BcBody::LegacyMsg(LegacyMsg::LoginUpgrade),
};
sub_login.send(legacy_login).await?;
+8 -2
View File
@@ -232,10 +232,16 @@ impl BcCamera {
let mut result = MotionStatus::NoChange(Instant::now());
for alarm_event in &alarm_event_list.alarm_events {
if alarm_event.channel_id == channel_id {
if alarm_event.status == "MD" {
if alarm_event.status != "none"
|| alarm_event
.ai_type
.as_ref()
.map(|ai_type| ai_type != "none")
.unwrap_or(false)
{
result = MotionStatus::Start(Instant::now());
break;
} else if alarm_event.status == "none" {
} else {
result = MotionStatus::Stop(Instant::now());
break;
}
+2 -1
View File
@@ -96,7 +96,7 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> {
)(buf)?;
let (buf, packet_id) = error_context("Missing packet_id", le_u32)(buf)?; // This is the point at which the camera has contigious
// packets to
let (buf, _unknown) = error_context("ACK: Missing unknown", le_u32)(buf)?;
let (buf, maybe_latency) = error_context("ACK: Missing Maybe Latency", le_u32)(buf)?;
let (buf, payload_size) = error_context("ACK: Missing payload_size", le_u32)(buf)?;
let (buf, payload) = if payload_size > 0 {
let (buf, t_payload) = take(payload_size)(buf)?; // It is a binary payload of
@@ -113,6 +113,7 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> {
connection_id,
packet_id,
group_id,
maybe_latency,
payload,
};
Ok((buf, data))
+6 -2
View File
@@ -68,8 +68,11 @@ pub struct UdpAck {
pub group_id: u32,
/// The ID of the last data packet [`UdpData`]
pub packet_id: u32,
// 2 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000`
// Unknown but seems to change randomly every second
/// 4 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000`, `09e00000`,
/// `0`, `54785`, `55062`, `2528`,
/// Unknown but seems to change randomly every second
/// Might be a latency for the recieved acknoledge packets
pub maybe_latency: u32,
// 2 Bytes size of a payload
//
/// Payload of `00 01 01 01 01` where `01` is added after every repeat
@@ -86,6 +89,7 @@ impl UdpAck {
connection_id,
group_id: 0xffffffff,
packet_id: 0xffffffff,
maybe_latency: 0x0,
payload: vec![],
}
}
+1 -1
View File
@@ -52,7 +52,7 @@ fn bcudp_ack<'a, W: 'a + Write>(
le_u32(0),
le_u32(payload.group_id),
le_u32(payload.packet_id),
le_u32(0xd7160000),
le_u32(payload.maybe_latency),
le_u32(binary_payload.len() as u32),
slice(binary_payload),
))
+8
View File
@@ -0,0 +1,8 @@
use clap::Parser;
/// The battery command will dump the battery status to XML
#[derive(Parser, Debug)]
pub struct Opt {
/// The name of the camera. Must be a name in the config
pub camera: String,
}
+42
View File
@@ -0,0 +1,42 @@
///
/// # Neolink Battery
///
/// This module handles the printing of the Battery status
/// in xml format
///
/// # Usage
///
/// ```bash
/// neolink battery --config=config.toml CameraName
/// ```
///
use anyhow::{Context, Result};
mod cmdline;
use super::config::Config;
use crate::utils::find_and_connect;
pub(crate) use cmdline::Opt;
/// Entry point for the battery subcommand
///
/// Opt is the command line options
pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
let camera = find_and_connect(&config, &opt.camera).await?;
let state = camera
.battery_info()
.await
.context("Unable to get camera Battery state")?;
let ser = String::from_utf8(
yaserde::ser::serialize_with_writer(&state, vec![], &Default::default())
.expect("Should Ser the struct"),
)
.expect("Should be UTF8");
println!("{}", ser);
let _ = camera.logout().await;
camera.disconnect().await?;
Ok(())
}
+1
View File
@@ -25,4 +25,5 @@ pub enum Command {
Talk(super::talk::Opt),
Mqtt(super::mqtt::Opt),
Image(super::image::Opt),
Battery(super::battery::Opt),
}
+3
View File
@@ -123,6 +123,9 @@ pub(crate) struct CameraConfig {
#[serde(default = "default_true", alias = "splash")]
pub(crate) use_splash: bool,
#[serde(default = "default_true", alias = "enable")]
pub(crate) enabled: bool,
}
#[derive(Debug, Deserialize, Validate, Clone)]
+4
View File
@@ -29,6 +29,7 @@ use log::*;
use std::fs;
use validator::Validate;
mod battery;
mod cmdline;
mod config;
mod image;
@@ -115,6 +116,9 @@ async fn main() -> Result<()> {
Some(Command::Image(opts)) => {
image::main(opts, config).await?;
}
Some(Command::Battery(opts)) => {
battery::main(opts, config).await?;
}
}
Ok(())
+4
View File
@@ -198,6 +198,10 @@ impl EventCamThread {
.context("Failed to login to the camera")??;
info!("{}: Connected and logged in", camera_config.name);
if let Err(e) = camera.monitor_battery(camera_config.print_format).await {
warn!("Could not monitor battery: {:?}", e);
}
self.tx.send(Messages::Login).await?;
// Shararble cameras
+1
View File
@@ -95,6 +95,7 @@ pub(crate) async fn main(_: Opt, config: Config) -> Result<()> {
for camera_config in config
.cameras
.iter()
.filter(|c| c.enabled)
.map(|a| Arc::new(a.clone()))
.collect::<Vec<_>>()
{
+4
View File
@@ -44,5 +44,9 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
.expect("Should be UTF8");
println!("{}", pir_ser);
}
let _ = camera.logout().await;
camera.disconnect().await?;
Ok(())
}
+4
View File
@@ -90,5 +90,9 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
.context("Unable to execute PTZ move command")?;
}
};
let _ = camera.logout().await;
camera.disconnect().await?;
Ok(())
}
+3
View File
@@ -29,5 +29,8 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
.reboot()
.await
.context("Could not send reboot command to the camera")?;
camera.disconnect().await?;
Ok(())
}
+1 -1
View File
@@ -88,7 +88,7 @@ pub(crate) async fn main(_opt: Opt, mut config: Config) -> Result<()> {
)
}
let mut cameras = vec![];
for camera_config in config.cameras.drain(..) {
for camera_config in config.cameras.drain(..).filter(|c| c.enabled) {
cameras
.push(Camera::<Disconnected>::new(camera_config, &config.users, rtsp.clone()).await?);
}
+10
View File
@@ -30,6 +30,16 @@ impl Camera<Connected> {
};
timeout(self.state.camera.login_with_maxenc(max_encryption)).await??;
if let Err(e) = self
.state
.camera
.monitor_battery(self.shared.config.print_format)
.await
{
log::warn!("Could not monitor battery: {:?}", e);
}
Ok(Camera {
shared: self.shared,
state: LoggedIn {
+4
View File
@@ -33,5 +33,9 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
.led_light_set(opt.on)
.await
.context("Unable to set camera light state")?;
let _ = camera.logout().await;
camera.disconnect().await?;
Ok(())
}
+3
View File
@@ -86,5 +86,8 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
.await
.context("Talk stream ended early")?;
let _ = camera.logout().await;
camera.disconnect().await?;
Ok(())
}
+1 -1
View File
@@ -93,7 +93,6 @@ impl AddressOrUid {
uid: camera_config.camera_uid.clone(),
protocol: ConnectionProtocol::TcpUdp,
discovery: camera_config.discovery,
aux_printing: camera_config.print_format,
credentials: Credentials {
username: camera_config.username.clone(),
password: camera_config.password.clone(),
@@ -153,6 +152,7 @@ pub(crate) fn find_camera_by_name<'a>(config: &'a Config, name: &str) -> Result<
config
.cameras
.iter()
.filter(|c| c.enabled)
.find(|c| c.name == name)
.ok_or_else(|| anyhow!("Camera {} not found in the config file", name))
}