Compare commits

..
Author SHA1 Message Date
QuantumEntangledAndy 78a6401b16 Begin documenting SD reading 2023-06-09 12:49:05 +07:00
35 changed files with 177 additions and 1245 deletions

No files matched your search

Generated
+4 -7
View File
@@ -198,9 +198,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]]
name = "base64"
version = "0.21.2"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d"
checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a"
[[package]]
name = "bitflags"
@@ -1411,7 +1411,6 @@ name = "neolink"
version = "0.5.12"
dependencies = [
"anyhow",
"base64 0.21.2",
"byte-slice-cast",
"clap",
"console-subscriber",
@@ -1422,7 +1421,6 @@ dependencies = [
"gstreamer-app",
"gstreamer-rtsp",
"gstreamer-rtsp-server",
"heck",
"is_sorted",
"itertools",
"lazy_static",
@@ -1431,7 +1429,6 @@ dependencies = [
"regex",
"rumqttc",
"serde",
"serde_json",
"time",
"tokio",
"tokio-stream",
@@ -1443,7 +1440,7 @@ dependencies = [
[[package]]
name = "neolink_core"
version = "0.5.13"
version = "0.5.12"
dependencies = [
"aes",
"assert_matches",
@@ -1920,7 +1917,7 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b"
dependencies = [
"base64 0.21.2",
"base64 0.21.0",
]
[[package]]
+2 -5
View File
@@ -1,7 +1,7 @@
[package]
name = "neolink"
description = "A standards-compliant bridge to Reolink IP cameras"
version = "0.5.13"
version = "0.5.12"
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
edition = "2018"
license = "AGPL-3.0-or-later"
@@ -13,7 +13,6 @@ members = [
[dependencies]
anyhow = "1.0.70"
base64 = "0.21.2"
byte-slice-cast = "1.2.2"
clap = { version = "4.2.2", features = ["derive", "cargo"] }
console-subscriber = "0.1.8"
@@ -24,16 +23,14 @@ gstreamer = "0.20.3"
gstreamer-app = "0.20.0"
gstreamer-rtsp = "0.20.0"
gstreamer-rtsp-server = { version = "0.20.3", features = ["v1_16"] }
heck = "0.4.1"
is_sorted = "0.1.1"
itertools = "0.10.5"
lazy_static = "1.4.0"
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
neolink_core = { path = "crates/core", version = "0.5.13" }
neolink_core = { path = "crates/core", version = "0.5.12" }
regex = "1.7.3"
rumqttc = "0.20.0"
serde = { version = "1.0.160", features = ["derive"] }
serde_json = "1.0.96"
time = "0.3.20"
tokio = { version = "1.27.0", features = ["rt-multi-thread", "macros", "io-util", "tracing"] }
tokio-stream = "0.1.12"
-52
View File
@@ -154,8 +154,6 @@ Cellular cameras should select `"cellular"` which only enables `map` and
discovery = "cellular"
```
See the sample config file for more details.
### MQTT
To use mqtt you will to adjust your config file as such:
@@ -203,13 +201,10 @@ Status Messages:
- `/status disconnected` Sent when the camera goes offline
- `/status/battery` Sent in reply to a `/query/battery` an XML encoded version
of the battery status
- `/status/battery_level` A simple % value of current battery level
- `/status/pir` Sent in reply to a `/query/pir` an XML encoded version of the
pir status
- `/status/motion` Contains the motion detection alarm status. `on` for motion and `off` for still
- `/status/ptz/preset` Sent in reply to a `/query/ptz/preset` an XML encoded version of the
PTZ presets
- `/status/preview` a base64 encoded camera image updated every 0.5s
Query Messages:
@@ -217,53 +212,6 @@ Query Messages:
- `/query/pir` Request that the camera reports its pir status
- `/query/ptz/preset` Request that the camera reports its PTZ presets
### MQTT Disable Features
Certain features like preview and motion detection may not be desired
you can disable them by them with the following config options.
Disabling these may help to conserve battery
```toml
enable_motion = false # motion detection
# (limited battery drain since it
# is a passive listening connection)
enable_pings = false # keep alive pings that keep the camera connected
enable_light = false # flood lights only avaliable on some camera
# (limited battery drain since it
# is a passive listening connection)
enable_battery = false # battery updates in `/status/battery_level`
enable_preview = false # preview image in `/status/preview`
```
#### MQTT Discovery
[MQTT Discovery](https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery) is partially supported.
Currently, discovery is opt-in and camera features must be manually specified.
```toml
[cameras.mqtt]
# <see above>
[cameras.mqtt.discovery]
topic = "homeassistant"
features = ["floodlight"]
```
Avaliable features are:
- `floodlight`: This adds a light control to home assistant
- `camera`: This adds a camera preview to home assistant. It is only updated every 0.5s and cannot be much more than that since it is updated over mqtt not over RTSP
- `led`: This adds a switch to chage the LED status light on/off to home assistant
- `ir`: This adds a selection switch to chage the IR light on/off/auto to home assistant
- `motion`: This adds a motion detection binary sensor to home assistant
- `reboot`: This adds a reboot button to home assistant
- `pt`: This adds a selection of buttons to control the pan and tilt of the camera
- `battery`: This adds a battery level sensor to home assistant
### Pause
To use the pause feature you will need to adjust your config file as such:
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "neolink_core"
description = "Core services and structure for Reolink IP cameras"
version = "0.5.13"
version = "0.5.12"
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
edition = "2018"
license = "AGPL-3.0-or-later"
+2 -4
View File
@@ -197,10 +197,8 @@ fn bc_modern_msg<'a>(
}
fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> {
let (buf, _magic) = error_context(
"Magic invalid",
verify(le_u32, |x| *x == MAGIC_HEADER || *x == MAGIC_HEADER_REV),
)(buf)?;
let (buf, _magic) =
error_context("Magic invalid", verify(le_u32, |x| *x == MAGIC_HEADER))(buf)?;
let (buf, msg_id) = error_context("MsgID missing", le_u32)(buf)?;
let (buf, body_len) = error_context("BodyLen missing", le_u32)(buf)?;
let (buf, channel_id) = error_context("ChannelID missing", le_u8)(buf)?;
+1 -7
View File
@@ -3,11 +3,7 @@ use crate::Credentials;
pub use super::xml::{BcPayloads, BcXml, Extension};
use std::collections::HashSet;
pub(super) const MAGIC_HEADER: u32 = 0x0abcdef0;
/// Sometimes will get the BE magic header even though all other numbers are LE?
/// Seems to happens with certain messages like snap that produce jpegs, so perhaps it
/// it is meant to be a hint as to the endianess of the binary payload
pub(super) const MAGIC_HEADER_REV: u32 = 0x0fedcba0;
pub(super) const MAGIC_HEADER: u32 = 0xabcdef0;
/// Login messages have this ID
pub const MSG_ID_LOGIN: u32 = 1;
@@ -37,8 +33,6 @@ pub const MSG_ID_VERSION: u32 = 80;
pub const MSG_ID_PING: u32 = 93;
/// General system info messages have this ID
pub const MSG_ID_GET_GENERAL: u32 = 104;
/// Snapshot to get a jpeg image
pub const MSG_ID_SNAP: u32 = 109;
/// Used to get the abilities of a user
pub const MSG_ID_ABILITY_INFO: u32 = 151;
/// Setting general system info (clock mostly) messages have this ID
+1 -34
View File
@@ -97,9 +97,6 @@ pub struct BcXml {
/// Recieved on request for a link type
#[yaserde(rename = "LinkType")]
pub link_type: Option<LinkType>,
/// Recieved AND send for the snap message
#[yaserde(rename = "Snap")]
pub snap: Option<Snap>,
}
impl BcXml {
@@ -703,37 +700,7 @@ pub struct AbilityInfoSubModule {
pub struct LinkType {
#[yaserde(rename = "type")]
/// Type of connection known values `"LAN"`
pub link_type: String,
}
/// The Link Type contains the type of connection present
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
pub struct Snap {
#[yaserde(rename = "channelId")]
/// The channel id to get the snapshot from
pub channel_id: u8,
/// Unknown, observed values: 0
/// value is only set on request
#[yaserde(rename = "logicChannel")]
pub logic_channel: Option<u8>,
/// Time of snapshot, zero when requesting
pub time: u32,
/// Request a full frame, observed values: 0
/// value is only set on request
#[yaserde(rename = "fullFrame")]
pub full_frame: Option<u32>,
/// Stream name, observed values: `main`, `sub`
/// value is only set on request
#[yaserde(rename = "streamType")]
pub stream_type: Option<String>,
/// File name, usually of the form `01_20230518140240.jpg`
/// value is only set on recieve
#[yaserde(rename = "fileName")]
pub file_name: Option<String>,
/// Size in bytes of the picture
/// value is only set on recieve
#[yaserde(rename = "pictureSize")]
pub picture_size: Option<u32>,
link_type: String,
}
/// Convience function to return the xml version used throughout the library
-1
View File
@@ -27,7 +27,6 @@ mod pirstate;
mod ptz;
mod reboot;
mod resolution;
mod snap;
mod stream;
mod talk;
mod time;
+1 -1
View File
@@ -7,7 +7,7 @@ impl BcCamera {
pub async fn get_abilityinfo(&self) -> Result<AbilityInfo> {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(MSG_ID_ABILITY_INFO, msg_num).await?;
let mut sub_get = connection.subscribe(msg_num).await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_ABILITY_INFO,
+1 -1
View File
@@ -83,7 +83,7 @@ impl BcCamera {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub = connection.subscribe(MSG_ID_BATTERY_INFO, msg_num).await?;
let mut sub = connection.subscribe(msg_num).await?;
let msg = Bc {
meta: BcMeta {
+60 -111
View File
@@ -18,8 +18,8 @@ type MsgHandler = dyn 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a
#[derive(Default)]
struct Subscriber {
/// Subscribers based on their ID and their num
num: BTreeMap<u32, BTreeMap<Option<u16>, Sender<Result<Bc>>>>,
/// Subscribers based on their Num
num: BTreeMap<u16, Sender<Result<Bc>>>,
/// Subscribers based on their ID
id: BTreeMap<u32, Arc<MsgHandler>>,
}
@@ -85,12 +85,12 @@ impl BcConnection {
Ok(())
}
pub async fn subscribe(&self, msg_id: u32, msg_num: u16) -> Result<BcSubscription> {
pub async fn subscribe(&self, msg_num: u16) -> Result<BcSubscription> {
let (tx, rx) = channel(100);
self.poll_commander
.send(PollCommand::AddSubscriber(msg_id, Some(msg_num), tx))
.send(PollCommand::AddSubscriber(msg_num, tx))
.await?;
Ok(BcSubscription::new(rx, Some(msg_num as u32), self))
Ok(BcSubscription::new(rx, msg_num as u32, self))
}
/// Some messages are initiated by the camera. This creates a handler for them
@@ -115,21 +115,6 @@ impl BcConnection {
Ok(())
}
/// Some times we want to wait for a reply on a new message ID
/// to do this we wait for the next packet with a certain ID
/// grab it's message ID and then subscribe to that ID
///
/// The command Snap that grabs a jpeg payload is an example of this
///
/// This function creates a temporary handle to grab this single message
pub async fn subscribe_to_id(&self, msg_id: u32) -> Result<BcSubscription> {
let (tx, rx) = channel(100);
self.poll_commander
.send(PollCommand::AddSubscriber(msg_id, None, tx))
.await?;
Ok(BcSubscription::new(rx, None, self))
}
pub(crate) async fn join(&self) -> Result<()> {
let mut locked_threads = self.rx_thread.write().await;
while let Some(res) = locked_threads.join_next().await {
@@ -153,7 +138,7 @@ enum PollCommand {
Bc(Box<Result<Bc>>),
AddHandler(u32, Arc<MsgHandler>),
RemoveHandler(u32),
AddSubscriber(u32, Option<u16>, Sender<Result<Bc>>),
AddSubscriber(u16, Sender<Result<Bc>>),
}
struct Poller {
@@ -167,96 +152,66 @@ impl Poller {
while let Some(command) = self.reciever.next().await {
yield_now().await;
match command {
PollCommand::Bc(boxed_response) => {
match *boxed_response {
Ok(response) => {
let msg_num = response.meta.msg_num;
let msg_id = response.meta.msg_id;
PollCommand::Bc(boxed_response) => match *boxed_response {
Ok(response) => {
let msg_num = response.meta.msg_num;
let msg_id = response.meta.msg_id;
match (
self.subscribers.id.get(&msg_id),
self.subscribers.num.get_mut(&msg_id),
) {
(Some(occ), _) => {
if let Some(reply) = occ(&response).await {
assert!(reply.meta.msg_num == response.meta.msg_num);
self.sink.send(Ok(reply)).await?;
}
let mut remove_it_num = false;
match (
self.subscribers.id.get(&msg_id),
self.subscribers.num.get(&msg_num),
) {
(Some(occ), _) => {
if let Some(reply) = occ(&response).await {
assert!(reply.meta.msg_num == response.meta.msg_num);
self.sink.send(Ok(reply)).await?;
}
(None, Some(occ)) => {
let sender = if let Some(sender) =
occ.get(&Some(msg_num)).filter(|a| !a.is_closed()).cloned()
{
// Connection with id exists and is not closed
Some(sender)
} else if let Some(sender) = occ.get(&None).cloned() {
// Upgrade a None to a known MsgID
occ.remove(&None);
occ.insert(Some(msg_num), sender.clone());
Some(sender)
} else if occ
.get(&Some(msg_num))
.map(|a| a.is_closed())
.unwrap_or(false)
{
// Connection is closed and there is no None to replace it
// Remove it for cleanup and report no sender
occ.remove(&Some(msg_num));
None
} else {
None
};
if let Some(sender) = sender {
if sender.capacity() == 0 {
warn!("Reaching limit of channel");
warn!(
"Remaining: {} of {} message space for {} (ID: {})",
sender.capacity(),
sender.max_capacity(),
&msg_num,
&msg_id
);
} else {
trace!(
"Remaining: {} of {} message space for {} (ID: {})",
sender.capacity(),
sender.max_capacity(),
&msg_num,
&msg_id
);
}
if sender.send(Ok(response)).await.is_err() {
occ.remove(&Some(msg_num));
}
} else {
debug!(
"Ignoring uninteresting message id {} (number: {})",
msg_id, msg_num
);
trace!("Contents: {:?}", response);
}
}
(None, None) => {
debug!(
"Ignoring uninteresting message id {} (number: {})",
msg_id, msg_num
}
(None, Some(occ)) => {
if occ.capacity() == 0 {
warn!("Reaching limit of channel");
warn!(
"Remaining: {} of {} message space for {} (ID: {})",
occ.capacity(),
occ.max_capacity(),
&msg_num,
&msg_id
);
} else {
trace!(
"Remaining: {} of {} message space for {} (ID: {})",
occ.capacity(),
occ.max_capacity(),
&msg_num,
&msg_id
);
trace!("Contents: {:?}", response);
}
if occ.send(Ok(response)).await.is_err() {
remove_it_num = true;
}
}
(None, None) => {
debug!(
"Ignoring uninteresting message id {} (number: {})",
msg_id, msg_num
);
trace!("Contents: {:?}", response);
}
}
Err(e) => {
for sub in self.subscribers.num.values() {
for sender in sub.values() {
let _ = sender.send(Err(e.clone())).await;
}
}
self.subscribers.num.clear();
self.subscribers.id.clear();
return Err(e);
if remove_it_num {
self.subscribers.num.remove(&msg_num);
}
}
}
Err(e) => {
for sub in self.subscribers.num.values() {
let _ = sub.send(Err(e.clone())).await;
}
self.subscribers.num.clear();
self.subscribers.id.clear();
return Err(e);
}
},
PollCommand::AddHandler(msg_id, handler) => {
match self.subscribers.id.entry(msg_id) {
Entry::Vacant(vac_entry) => {
@@ -270,14 +225,8 @@ impl Poller {
PollCommand::RemoveHandler(msg_id) => {
self.subscribers.id.remove(&msg_id);
}
PollCommand::AddSubscriber(msg_id, msg_num, tx) => {
match self
.subscribers
.num
.entry(msg_id)
.or_default()
.entry(msg_num)
{
PollCommand::AddSubscriber(msg_num, tx) => {
match self.subscribers.num.entry(msg_num) {
Entry::Vacant(vac_entry) => {
vac_entry.insert(tx);
}
@@ -12,7 +12,7 @@ use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
pub struct BcSubscription<'a> {
rx: ReceiverStream<Result<Bc>>,
msg_num: Option<u32>,
msg_num: u32,
conn: &'a BcConnection,
}
@@ -89,7 +89,7 @@ pub type BcMediaStream<'b> = FramedRead<Compat<IntoAsyncRead<BcPayloadStream<'b>
impl<'a> BcSubscription<'a> {
pub fn new(
rx: Receiver<Result<Bc>>,
msg_num: Option<u32>,
msg_num: u32,
conn: &'a BcConnection,
) -> BcSubscription<'a> {
BcSubscription {
@@ -100,11 +100,7 @@ impl<'a> BcSubscription<'a> {
}
pub async fn send(&self, bc: Bc) -> Result<()> {
if let Some(msg_num) = self.msg_num {
assert!(bc.meta.msg_num as u32 == msg_num);
} else {
log::debug!("Sending message before msg_num has been aquired");
}
assert!(bc.meta.msg_num as u32 == self.msg_num);
self.conn.send(bc).await?;
Ok(())
}
@@ -112,12 +108,7 @@ impl<'a> BcSubscription<'a> {
pub async fn recv(&mut self) -> Result<Bc> {
let bc = self.rx.next().await.ok_or(Error::DroppedSubscriber)?;
if let Ok(bc) = &bc {
if let Some(msg_num) = self.msg_num {
assert!(bc.meta.msg_num as u32 == msg_num);
} else {
// Leaning number now
self.msg_num = Some(bc.meta.msg_num as u32);
}
assert!(bc.meta.msg_num as u32 == self.msg_num);
}
bc
}
@@ -175,7 +175,7 @@ impl Discoverer {
Ok(rx)
} else {
Err(Error::SimultaneousSubscription {
msg_num: Some(tid as u16),
msg_num: (tid as u16),
})
}
}
+2 -2
View File
@@ -96,10 +96,10 @@ pub enum Error {
GenError(#[error(source)] std::sync::Arc<cookie_factory::GenError>),
/// Raised when a connection is subscrbed to more than once for msg_num
#[error(display = "Simultaneous subscription, {:?}", _0)]
#[error(display = "Simultaneous subscription, {}", _0)]
SimultaneousSubscription {
/// The message number that was subscribed to
msg_num: Option<u16>,
msg_num: u16,
},
/// Raised when a connection is subscrbed to more than once for msg_id
@@ -45,9 +45,7 @@ impl BcCamera {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection
.subscribe(MSG_ID_FLOODLIGHT_MANUAL, msg_num)
.await?;
let mut sub_set = connection.subscribe(msg_num).await?;
let get = Bc {
meta: BcMeta {
@@ -79,25 +77,18 @@ impl BcCamera {
};
sub_set.send(get).await?;
let msg = sub_set.recv().await?;
if let Ok(reply) =
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
if let BcMeta {
response_code: 200, ..
} = msg.meta
{
let msg = reply?;
if let BcMeta {
response_code: 200, ..
} = msg.meta
{
Ok(())
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "The camera did not accept the Floodlight manual state",
})
}
} else {
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
Ok(())
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "The camera did not accept the Floodlight manual state",
})
}
}
}
+12 -19
View File
@@ -7,7 +7,7 @@ impl BcCamera {
self.has_ability_ro("ledState").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(MSG_ID_GET_LED_STATUS, msg_num).await?;
let mut sub_get = connection.subscribe(msg_num).await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_GET_LED_STATUS,
@@ -56,7 +56,7 @@ impl BcCamera {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection.subscribe(MSG_ID_SET_LED_STATUS, msg_num).await?;
let mut sub_set = connection.subscribe(msg_num).await?;
// led_version is a field recieved from the camera but not sent
// we set to None to ensure we don't send it to the camera
@@ -83,25 +83,18 @@ impl BcCamera {
};
sub_set.send(get).await?;
if let Ok(reply) =
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
{
let msg = reply?;
let msg = sub_set.recv().await?;
if let BcMeta {
response_code: 200, ..
} = msg.meta
{
Ok(())
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "The camera did not except the LEDState xml",
})
}
} else {
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
if let BcMeta {
response_code: 200, ..
} = msg.meta
{
Ok(())
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "The camera did not except the LEDState xml",
})
}
}
+1 -1
View File
@@ -37,7 +37,7 @@ impl BcCamera {
let credentials = self.get_credentials();
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_login = connection.subscribe(MSG_ID_LOGIN, msg_num).await?;
let mut sub_login = connection.subscribe(msg_num).await?;
// Login flow is: Send legacy login message, expect back a modern message with Encryption
// details. Then, re-send the login as a modern login message. Expect back a device info
+1 -1
View File
@@ -9,7 +9,7 @@ impl BcCamera {
let credentials = self.get_credentials();
let connection = self.get_connection();
let msg_num = self.new_message_num();
let sub_logout = connection.subscribe(MSG_ID_LOGOUT, msg_num).await?;
let sub_logout = connection.subscribe(msg_num).await?;
let username = credentials.username.clone();
let password = credentials.password.as_ref().cloned().unwrap_or_default();
+3 -3
View File
@@ -167,7 +167,7 @@ impl BcCamera {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub = connection.subscribe(MSG_ID_MOTION_REQUEST, msg_num).await?;
let mut sub = connection.subscribe(msg_num).await?;
let msg = Bc {
meta: BcMeta {
msg_id: MSG_ID_MOTION_REQUEST,
@@ -202,7 +202,7 @@ impl BcCamera {
/// This returns a data structure which can be used to
/// query motion events
pub async fn listen_on_motion(&self) -> Result<MotionData> {
self.start_motion_query().await?;
let msg_num = self.start_motion_query().await?;
let connection = self.get_connection();
@@ -213,7 +213,7 @@ impl BcCamera {
let mut set = JoinSet::new();
let channel_id = self.channel_id;
set.spawn(async move {
let mut sub = connection.subscribe_to_id(MSG_ID_MOTION).await?;
let mut sub = connection.subscribe(msg_num).await?;
loop {
tokio::task::yield_now().await;
+1 -1
View File
@@ -7,7 +7,7 @@ impl BcCamera {
pub async fn ping(&self) -> Result<()> {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_ping = connection.subscribe(MSG_ID_PING, msg_num).await?;
let mut sub_ping = connection.subscribe(msg_num).await?;
let ping = Bc {
meta: BcMeta {
+15 -24
View File
@@ -12,7 +12,7 @@ impl BcCamera {
loop {
retry_interval.tick().await;
let msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(MSG_ID_GET_PIR_ALARM, msg_num).await?;
let mut sub_get = connection.subscribe(msg_num).await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_GET_PIR_ALARM,
@@ -70,9 +70,7 @@ impl BcCamera {
self.has_ability_rw("rfAlarm").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection
.subscribe(MSG_ID_START_PIR_ALARM, msg_num)
.await?;
let mut sub_set = connection.subscribe(msg_num).await?;
let get = Bc {
meta: BcMeta {
@@ -96,28 +94,21 @@ impl BcCamera {
};
sub_set.send(get).await?;
if let Ok(reply) =
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
{
let msg = reply?;
if msg.meta.response_code != 200 {
return Err(Error::CameraServiceUnavaliable);
}
let msg = sub_set.recv().await?;
if msg.meta.response_code != 200 {
return Err(Error::CameraServiceUnavaliable);
}
if let BcMeta {
response_code: 200, ..
} = msg.meta
{
Ok(())
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "The camera did not except the RfAlarmCfg xml",
})
}
} else {
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
if let BcMeta {
response_code: 200, ..
} = msg.meta
{
Ok(())
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "The camera did not except the RfAlarmCfg xml",
})
}
}
+4 -8
View File
@@ -25,7 +25,7 @@ impl BcCamera {
self.has_ability_rw("control").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection.subscribe(MSG_ID_PTZ_CONTROL, msg_num).await?;
let mut sub_set = connection.subscribe(msg_num).await?;
let direction_str = match direction {
Direction::Up => "up",
@@ -88,7 +88,7 @@ impl BcCamera {
self.has_ability_rw("control").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection.subscribe(MSG_ID_GET_PTZ_PRESET, msg_num).await?;
let mut sub_set = connection.subscribe(msg_num).await?;
let send = Bc {
meta: BcMeta {
@@ -136,9 +136,7 @@ impl BcCamera {
self.has_ability_rw("control").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection
.subscribe(MSG_ID_PTZ_CONTROL_PRESET, msg_num)
.await?;
let mut sub_set = connection.subscribe(msg_num).await?;
let preset = Preset {
id: preset_id,
@@ -193,9 +191,7 @@ impl BcCamera {
self.has_ability_rw("control").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection
.subscribe(MSG_ID_PTZ_CONTROL_PRESET, msg_num)
.await?;
let mut sub_set = connection.subscribe(msg_num).await?;
let preset = Preset {
id: preset_id,
+1 -1
View File
@@ -7,7 +7,7 @@ impl BcCamera {
self.has_ability_rw("reboot").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub = connection.subscribe(MSG_ID_REBOOT, msg_num).await?;
let mut sub = connection.subscribe(msg_num).await?;
let msg = Bc {
meta: BcMeta {
-152
View File
@@ -1,152 +0,0 @@
// use futures::{StreamExt, TryStreamExt};
use super::{BcCamera, Error, Result};
use crate::bc::{model::*, xml::*};
impl BcCamera {
/// Get the snapshot image
pub async fn get_snapshot(&self) -> Result<Vec<u8>> {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(MSG_ID_SNAP, msg_num).await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_SNAP,
channel_id: self.channel_id,
msg_num,
response_code: 0,
stream_type: 0,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
extension: Some(Extension {
channel_id: Some(self.channel_id),
..Default::default()
}),
payload: Some(BcPayloads::BcXml(BcXml {
snap: Some(Snap {
channel_id: self.channel_id,
logic_channel: Some(self.channel_id),
time: 0,
full_frame: Some(0),
stream_type: Some("main".to_string()),
..Default::default()
}),
..Default::default()
})),
}),
};
sub_get.send(get).await?;
let msg = sub_get.recv().await?;
if msg.meta.response_code != 200 {
return Err(Error::CameraServiceUnavaliable);
}
if let BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
snap:
Some(Snap {
file_name: Some(filename),
picture_size: Some(expected_size),
..
}),
..
})),
..
}) = msg.body
{
log::trace!("Got snap XML {} with size {}", filename, expected_size);
// Messages are now sent on ID 109 but not with the same message ID
// preumably because the camera considers it to be a new message rather
// than a reply
//
// This means we need to listen for the next 109 grab the message num and
// subscribe to it. This is what `subscribe_to_next` is for
let mut sub_get = connection.subscribe_to_id(MSG_ID_SNAP).await?;
let expected_size = expected_size as usize;
let mut result: Vec<_> = vec![];
log::trace!("Waiting for packets on {}", msg_num);
let mut msg = sub_get.recv().await?;
while msg.meta.response_code == 200 {
// sends 200 while more is to come
// 201 when finished
if let BcBody::ModernMsg(ModernMsg {
extension:
Some(Extension {
binary_data: Some(1),
..
}),
payload: Some(BcPayloads::Binary(data)),
}) = msg.body
{
result.extend_from_slice(&data);
} else {
return Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "Expected binary data but got something else",
});
}
log::trace!(
"Got packet size is now {} of {}",
result.len(),
expected_size
);
msg = sub_get.recv().await?;
}
if msg.meta.response_code == 201 {
// 201 means all binary data sent
if let BcBody::ModernMsg(ModernMsg {
extension:
Some(Extension {
binary_data: Some(1),
..
}),
payload,
}) = msg.body
{
if let Some(BcPayloads::Binary(data)) = payload {
// Add last data if present (may be zero if preveious packet contained it)
result.extend_from_slice(&data);
}
log::trace!(
"Got all packets size is now {} of {}",
result.len(),
expected_size
);
if result.len() != expected_size {
log::warn!("Snap did not recieve expected number of byes");
}
} else {
return Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "Expected binary data but got something else",
});
}
} else {
// anything else is an error
return Err(Error::CameraServiceUnavaliable);
}
// let binary_stream = sub_get.payload_stream();
// let result: Vec<_>= binary_stream
// .map_ok(|i| tokio_stream::iter(i).map(Result::Ok))
// .try_flatten()
// .take(expected_size)
// .try_collect()
// .await?;
log::trace!("Snapshot recieved: {} of {}", result.len(), expected_size);
Ok(result)
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "Expected Snap xml but it was not recieved",
})
}
}
}
+4 -5
View File
@@ -111,7 +111,7 @@ impl BcCamera {
let handle = task::spawn(async move {
tokio::task::yield_now().await;
let mut sub_video = connection.subscribe(MSG_ID_VIDEO, msg_num).await?;
let mut sub_video = connection.subscribe(msg_num).await?;
// On an E1 and swann cameras:
// - mainStream always has a value of 0
@@ -224,14 +224,13 @@ impl BcCamera {
},
);
// debug!("Stream: Send Stop");
let mut sub_stop = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?;
sub_stop.send(stop_video).await?;
sub_video.send(stop_video).await?;
// debug!("Stream: Sent Stop");
tokio::select! {
v = async {
loop {
let msg = sub_stop.recv().await?;
let msg = sub_video.recv().await?;
if let BcMeta {
response_code: 200,
msg_id: MSG_ID_VIDEO_STOP,
@@ -269,7 +268,7 @@ impl BcCamera {
}
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_video = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?;
let mut sub_video = connection.subscribe(msg_num).await?;
// On an E1 and swann cameras:
// - mainStream always has a value of 0
+6 -6
View File
@@ -17,7 +17,7 @@ impl BcCamera {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub = connection.subscribe(MSG_ID_TALKRESET, msg_num).await?;
let mut sub = connection.subscribe(msg_num).await?;
let msg = Bc {
meta: BcMeta {
@@ -60,7 +60,7 @@ impl BcCamera {
pub async fn talk_ability(&self) -> Result<TalkAbility> {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(MSG_ID_TALKABILITY, msg_num).await?;
let mut sub_get = connection.subscribe(msg_num).await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_TALKABILITY,
@@ -120,7 +120,7 @@ impl BcCamera {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub = connection.subscribe(MSG_ID_TALKCONFIG, msg_num).await?;
let mut sub = connection.subscribe(msg_num).await?;
if &talk_config.audio_config.audio_type != "adpcm" {
return Err(Error::UnknownTalkEncoding);
@@ -182,7 +182,7 @@ impl BcCamera {
let full_block_size = block_size + 4; // Block size + predictor state
let msg_num = self.new_message_num();
let sub = connection.subscribe(MSG_ID_TALK, msg_num).await?;
let sub = connection.subscribe(msg_num).await?;
const BLOCK_PER_PAYLOAD: usize = 4;
const BLOCK_HEADER_SIZE: usize = 4;
@@ -261,7 +261,7 @@ impl BcCamera {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub = connection.subscribe(MSG_ID_TALKCONFIG, msg_num).await?;
let mut sub = connection.subscribe(msg_num).await?;
if &talk_config.audio_config.audio_type != "adpcm" {
return Err(Error::UnknownTalkEncoding);
@@ -323,7 +323,7 @@ impl BcCamera {
let full_block_size = block_size + 4; // Block size + predictor state
let msg_num = self.new_message_num();
let sub = connection.subscribe(MSG_ID_TALK, msg_num).await?;
let sub = connection.subscribe(msg_num).await?;
const BLOCK_PER_PAYLOAD: usize = 1;
const BLOCK_HEADER_SIZE: usize = 4;
+2 -2
View File
@@ -17,7 +17,7 @@ impl BcCamera {
self.has_ability_ro("general").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_get_general = connection.subscribe(MSG_ID_GET_GENERAL, msg_num).await?;
let mut sub_get_general = connection.subscribe(msg_num).await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_GET_GENERAL,
@@ -102,7 +102,7 @@ impl BcCamera {
self.has_ability_rw("general").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set_general = connection.subscribe(MSG_ID_SET_GENERAL, msg_num).await?;
let mut sub_set_general = connection.subscribe(msg_num).await?;
let set = Bc::new_from_xml(
BcMeta {
msg_id: MSG_ID_SET_GENERAL,
+1 -1
View File
@@ -7,7 +7,7 @@ impl BcCamera {
self.has_ability_ro("version").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_version = connection.subscribe(MSG_ID_VERSION, msg_num).await?;
let mut sub_version = connection.subscribe(msg_num).await?;
let version = Bc {
meta: BcMeta {
+22 -2
View File
@@ -354,7 +354,7 @@ Message have zero to two payloads.
</PtzControl>
</body>
```
- **Notes** : The known movement commands are `"left"`, `"right"`, `"up"`, `"down"`, `"leftUp"`,
`"leftDown"`, `"rightUp"`, `"rightDown"` and `"stop"` although the diagonal movement
does not seem to work.
@@ -394,7 +394,7 @@ Message have zero to two payloads.
</PtzPreset>
</body>
```
- **Notes** : The known values for command are `"setPos"` and `"toPos"`
- Camera
@@ -1655,6 +1655,8 @@ Message have zero to two payloads.
- Payload
If no SD Card:
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<body>
@@ -1662,6 +1664,24 @@ Message have zero to two payloads.
</body>
```
If there is a SD Card
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<body>
<HddInfoList version="1.1">
<HddInfo>
<number>0</number>
<capacity>30</capacity>
<format>1</format>
<mount>1</mount>
<remainSize>29</remainSize>
<remainSizeM>551</remainSizeM>
</HddInfo>
</HddInfoList>
</body>
```
- 104: `<SystemGeneral>`
- Client
-4
View File
@@ -38,10 +38,6 @@ address = "192.168.1.187:9000"
# mqtt.broker_addr = "192.168.1.122"
# mqtt.port = 1883
# mqtt.credentials = ["mqtt_user", "mqtt_password"]
# MQTT Discovery: https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
# mqtt.discovery.topic = "homeassistant" # Uncomment to enable
# If using discovery, _ characters are replaced with spaces in the name and title case is applied
# mqtt.discovery.features = ["floodlight"] # Uncomment if this camera has a spotlight/floodlight
# If you use a battery camera: **Instead** of an `address` supply the uid
# as follows
-27
View File
@@ -1,10 +1,8 @@
use crate::mqtt::Discoveries;
use lazy_static::lazy_static;
use neolink_core::bc_protocol::{DiscoveryMethods, PrintFormat};
use regex::Regex;
use serde::Deserialize;
use std::clone::Clone;
use std::collections::HashSet;
use validator::{Validate, ValidationError};
use validator_derive::Validate;
@@ -148,27 +146,6 @@ pub(crate) struct MqttConfig {
#[serde(default)]
pub(crate) client_auth: Option<(std::path::PathBuf, std::path::PathBuf)>,
#[serde(default = "default_true")]
pub(crate) enable_motion: bool,
#[serde(default = "default_true")]
pub(crate) enable_pings: bool,
#[serde(default = "default_true")]
pub(crate) enable_light: bool,
#[serde(default = "default_true")]
pub(crate) enable_battery: bool,
#[serde(default = "default_true")]
pub(crate) enable_preview: bool,
#[serde(default)]
pub(crate) discovery: Option<MqttDiscoveryConfig>,
}
#[derive(Debug, Deserialize, Clone, Validate)]
pub(crate) struct MqttDiscoveryConfig {
pub(crate) topic: String,
pub(crate) features: HashSet<Discoveries>,
}
fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
@@ -181,10 +158,6 @@ fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
}
}
const fn default_true() -> bool {
true
}
fn default_mqtt() -> Option<MqttConfig> {
None
}
-570
View File
@@ -1,570 +0,0 @@
//! Enable and configures home assistant MQTTT discovery
//!
//! https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
//!
use anyhow::{Context, Result};
use heck::ToTitleCase;
use log::*;
use std::sync::Arc;
use super::mqttc::MqttSender;
use crate::config::{CameraConfig, MqttDiscoveryConfig};
use serde::{Deserialize, Serialize, Serializer};
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Copy, Hash)]
pub(crate) enum Discoveries {
#[serde(alias = "floodlight", alias = "light")]
Floodlight,
#[serde(alias = "camera")]
Camera,
#[serde(alias = "motion", alias = "md", alias = "pir")]
Motion,
#[serde(alias = "led")]
Led,
#[serde(alias = "ir")]
Ir,
#[serde(alias = "reboot")]
Reboot,
#[serde(alias = "pt")]
Pt,
#[serde(alias = "battery", alias = "power")]
Battery,
}
#[derive(Debug, Clone)]
struct DiscoveryConnection {
connection_type: String,
connection_id: String,
}
impl Serialize for DiscoveryConnection {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
vec![&self.connection_type, &self.connection_id].serialize(serializer)
}
}
#[derive(Serialize, Debug, Clone)]
struct DiscoveryDevice {
name: String,
connections: Vec<DiscoveryConnection>,
identifiers: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
manufacturer: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
sw_version: Option<String>,
}
#[derive(Serialize, Debug, Clone)]
struct DiscoveryAvaliablity {
topic: String,
#[serde(skip_serializing_if = "Option::is_none")]
payload_available: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
payload_not_available: Option<String>,
}
#[derive(Serialize, Debug)]
struct DiscoveryLight {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// Light specific
#[serde(skip_serializing_if = "Option::is_none")]
state_topic: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
state_value_template: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
command_topic: Option<String>,
payload_on: String,
payload_off: String,
}
#[derive(Serialize, Debug)]
#[allow(dead_code)]
enum Encoding {
None,
#[serde(rename = "b64")]
Base64,
}
impl Encoding {
fn is_none(&self) -> bool {
matches!(self, Self::None)
}
}
#[derive(Serialize, Debug)]
struct DiscoveryCamera {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// Camera specific
topic: String,
#[serde(skip_serializing_if = "Encoding::is_none")]
image_encoding: Encoding,
}
#[derive(Serialize, Debug)]
struct DiscoverySwitch {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// Switch specific
// - Control
command_topic: String,
payload_off: String,
payload_on: String,
// - State
#[serde(skip_serializing_if = "Option::is_none")]
state_topic: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
state_off: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
state_on: Option<String>,
}
#[derive(Serialize, Debug)]
struct DiscoverySelect {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// Switch specific
// - Control
command_topic: String,
options: Vec<String>,
// - State
#[serde(skip_serializing_if = "Option::is_none")]
state_topic: Option<String>,
}
#[derive(Serialize, Debug)]
struct DiscoveryBinarySensor {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// BinarySensor specific
payload_off: String,
payload_on: String,
// - State
state_topic: String,
}
#[derive(Serialize, Debug)]
struct DiscoveryButton {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// Button specific
command_topic: String,
#[serde(skip_serializing_if = "Option::is_none")]
payload_press: Option<String>,
}
#[derive(Serialize, Debug)]
struct DiscoverySensor {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// Button specific
state_topic: String,
state_class: String,
unit_of_measurement: String,
}
/// Enables MQTT discovery for a camera. See docs at https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
pub(crate) async fn enable_discovery(
discovery_config: &MqttDiscoveryConfig,
mqtt_sender: &MqttSender,
cam_config: &Arc<CameraConfig>,
) -> Result<()> {
debug!("Enabling MQTT discovery for {}", cam_config.name);
let mut connections = vec![];
if let Some(addr) = &cam_config.camera_addr {
connections.push(DiscoveryConnection {
connection_type: "camera_addr".to_string(),
connection_id: addr.clone(),
});
}
if let Some(uid) = &cam_config.camera_uid {
connections.push(DiscoveryConnection {
connection_type: "camera_uid".to_string(),
connection_id: uid.clone(),
});
}
if connections.is_empty() {
error!(
"No connections found for camera {}, either addr or UID must be supplied",
cam_config.name
);
return Ok(());
}
let friendly_name = cam_config.name.replace('_', " ").to_title_case();
let device = DiscoveryDevice {
name: friendly_name.clone(),
connections,
identifiers: vec![format!("neolink_{}", cam_config.name)],
manufacturer: Some("Reolink".to_string()),
model: Some("Neolink".to_string()),
sw_version: Some(env!("CARGO_PKG_VERSION").to_string()),
};
let availability = DiscoveryAvaliablity {
topic: format!("neolink/{}/status", cam_config.name),
payload_available: Some("connected".to_string()),
payload_not_available: None,
};
for feature in &discovery_config.features {
match feature {
Discoveries::Floodlight => {
let config_data = DiscoveryLight {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} Floodlight", friendly_name.as_str()),
unique_id: format!("neolink_{}_floodlight", cam_config.name),
// Match native home assistant integration: https://github.com/home-assistant/core/blob/dev/homeassistant/components/reolink/light.py#L49
icon: Some("mdi:spotlight-beam".to_string()),
// State
state_topic: Some(format!("neolink/{}/status/floodlight", cam_config.name)),
state_value_template: Some("{{ value_json.state }}".to_string()),
// Control
command_topic: Some(format!("neolink/{}/control/floodlight", cam_config.name)),
// Lowercase payloads to match neolink convention
payload_on: "on".to_string(),
payload_off: "off".to_string(),
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/light/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery light config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish floodlight auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
Discoveries::Camera => {
let config_data = DiscoveryCamera {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} Camera", friendly_name.as_str()),
unique_id: format!("neolink_{}_camera", cam_config.name),
icon: Some("mdi:camera-iris".to_string()),
// Camera specific
topic: format!("neolink/{}/status/preview", cam_config.name),
image_encoding: Encoding::Base64,
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/camera/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery camera config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish camera auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
Discoveries::Led => {
let config_data = DiscoverySwitch {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} LED", friendly_name.as_str()),
unique_id: format!("neolink_{}_led", cam_config.name),
icon: Some("mdi:led-on".to_string()),
// Switch specific
command_topic: format!("neolink/{}/control/led", cam_config.name),
payload_off: "off".to_string(),
payload_on: "on".to_string(),
state_topic: None,
state_off: None,
state_on: None,
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/switch/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery led config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish led auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
Discoveries::Ir => {
let config_data = DiscoverySelect {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} IR", friendly_name.as_str()),
unique_id: format!("neolink_{}_ir", cam_config.name),
icon: Some("mdi:lightbulb-night".to_string()),
// Switch specific
command_topic: format!("neolink/{}/control/ir", cam_config.name),
options: vec!["on".to_string(), "off".to_string(), "auto".to_string()],
state_topic: None,
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/select/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery led config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish led auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
Discoveries::Motion => {
let config_data = DiscoveryBinarySensor {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} MD", friendly_name.as_str()),
unique_id: format!("neolink_{}_md", cam_config.name),
icon: Some("mdi:motion-sensor".to_string()),
// Switch specific
state_topic: format!("neolink/{}/status/motion", cam_config.name),
payload_off: "off".to_string(),
payload_on: "on".to_string(),
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/binary_sensor/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery motion config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish motion auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
Discoveries::Reboot => {
let config_data = DiscoveryButton {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} Reboot", friendly_name.as_str()),
unique_id: format!("neolink_{}_reboot", cam_config.name),
icon: Some("mdi:restart".to_string()),
// Switch specific
command_topic: format!("neolink/{}/control/reboot", cam_config.name),
payload_press: None,
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/button/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery reboot config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish reboot auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
Discoveries::Pt => {
for dir in ["left", "right", "up", "down"] {
let config_data = DiscoveryButton {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} Pan {}", friendly_name.as_str(), dir),
unique_id: format!("neolink_{}_pan_{}", cam_config.name, dir),
icon: Some(format!("mdi:pan-{}", dir)),
// Switch specific
command_topic: format!("neolink/{}/control/ptz", cam_config.name),
payload_press: Some(dir.to_string()),
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/button/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery pt config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish pt auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
}
Discoveries::Battery => {
let config_data = DiscoverySensor {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} Battery", friendly_name.as_str()),
unique_id: format!("neolink_{}_battery", cam_config.name),
icon: Some("mdi:battery".to_string()),
// Camera specific
state_topic: format!("neolink/{}/status/battery_level", cam_config.name),
state_class: "measurement".to_string(),
unit_of_measurement: "%".to_string(),
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/sensor/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery battery config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish battery auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
}
}
info!(
"Enabled MQTT discovery for {} with friendly name {}",
cam_config.name,
friendly_name.as_str()
);
Ok(())
}
+3 -106
View File
@@ -31,8 +31,6 @@ pub(crate) enum Messages {
PIROff,
PIRQuery,
Ptz(Direction),
Snap(Vec<u8>),
BatteryLevel(u32),
Preset(u8),
PresetAssign(u8, String),
PresetQuery,
@@ -214,16 +212,6 @@ impl EventCamThread {
camera: arc_cam.clone(),
};
let mut snap_thread = SnapThread {
tx: self.tx.clone(),
camera: arc_cam.clone(),
};
let mut battery_thread = BatteryLevelThread {
tx: self.tx.clone(),
camera: arc_cam.clone(),
};
let mut keepalive_thread = KeepaliveThread {
camera: arc_cam.clone(),
};
@@ -237,7 +225,7 @@ impl EventCamThread {
val = async {
info!("{}: Listening to Camera Motion", camera_config.name);
motion_thread.run().await
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_motion => {
} => {
if let Err(e) = val {
error!("Motion thread aborted: {:?}", e);
Err(e)
@@ -249,7 +237,7 @@ impl EventCamThread {
val = async {
debug!("{}: Starting Pings", camera_config.name);
keepalive_thread.run().await
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_pings => {
} => {
if let Err(e) = val {
debug!("Ping thread aborted: {:?}", e);
Err(e)
@@ -261,7 +249,7 @@ impl EventCamThread {
val = async {
info!("{}: Listening to FloodLight Status", camera_config.name);
flight_thread.run().await
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_light => {
} => {
if let Err(e) = val {
error!("FloodLight thread aborted: {:?}", e);
Err(e)
@@ -270,30 +258,6 @@ impl EventCamThread {
Ok(())
}
},
val = async {
info!("{}: Updating Preview", camera_config.name);
snap_thread.run().await
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_preview => {
if let Err(e) = val {
error!("Snap thread aborted: {:?}", e);
Err(e)
} else {
debug!("Normal finish on Snap thread");
Ok(())
}
},
val = async {
info!("{}: Updating Battery Level", camera_config.name);
battery_thread.run().await
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_battery => {
if let Err(e) = val {
error!("Battery thread aborted: {:?}", e);
Err(e)
} else {
debug!("Normal finish on Battery thread");
Ok(())
}
},
val = async {
info!("{}: Setting up camera actions", camera_config.name);
message_handler.listen().await
@@ -367,73 +331,6 @@ impl FloodlightThread {
}
}
struct SnapThread {
tx: Sender<Messages>,
camera: Arc<BcCamera>,
}
impl SnapThread {
async fn run(&mut self) -> Result<()> {
let mut tries = 0;
let base_duration = Duration::from_millis(500);
loop {
tokio::time::sleep(base_duration.saturating_mul(tries)).await;
let snapshot = match self.camera.get_snapshot().await {
Ok(info) => {
tries = 1;
info
}
Err(neolink_core::Error::UnintelligibleReply { reply, why }) => {
log::debug!("Reply: {:?}, why: {:?}", reply, why);
// Try again later
tries += 1;
continue;
}
Err(neolink_core::Error::CameraServiceUnavaliable) => {
log::debug!("Snap not supported");
futures::future::pending().await
}
Err(e) => return Err(e.into()),
};
self.tx.send(Messages::Snap(snapshot)).await?;
}
}
}
struct BatteryLevelThread {
tx: Sender<Messages>,
camera: Arc<BcCamera>,
}
impl BatteryLevelThread {
async fn run(&mut self) -> Result<()> {
let mut tries = 0;
let base_duration = Duration::from_secs(15);
loop {
tokio::time::sleep(base_duration.saturating_mul(tries)).await;
let battery = match self.camera.battery_info().await {
Ok(info) => {
tries = 1;
info
}
Err(neolink_core::Error::UnintelligibleReply { .. }) => {
// Try again later
tries += 1;
continue;
}
Err(neolink_core::Error::CameraServiceUnavaliable) => {
log::debug!("Battery not supported");
futures::future::pending().await
}
Err(e) => return Err(e.into()),
};
self.tx
.send(Messages::BatteryLevel(battery.battery_percent))
.await?;
}
}
}
struct KeepaliveThread {
camera: Arc<BcCamera>,
}
+4 -32
View File
@@ -1,4 +1,3 @@
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
///
/// # Neolink MQTT
///
@@ -10,7 +9,6 @@ use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
///
/// Control messages:
///
/// - `/control/floodlight [on|off]` Turns floodlight (if equipped) on/off
/// - `/control/led [on|off]` Turns status LED on/off
/// - `/control/pir [on|off]` Turns PIR on/off
/// - `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light detection
@@ -62,21 +60,18 @@ use std::sync::Arc;
use tokio::time::{sleep, Duration};
mod cmdline;
mod discovery;
mod event_cam;
mod mqttc;
use crate::config::{CameraConfig, Config, MqttConfig};
use anyhow::{anyhow, Context, Error, Result};
pub(crate) use cmdline::Opt;
pub(crate) use discovery::Discoveries;
use event_cam::EventCam;
pub(crate) use event_cam::{Direction, Messages};
use log::*;
use mqttc::{Mqtt, MqttReplyRef};
use self::{
discovery::enable_discovery,
event_cam::EventCamSender,
mqttc::{MqttReply, MqttSender},
};
@@ -140,8 +135,7 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
tokio::select! {
v = async {
// Normal poll operations
loop {
let msg = mqtt.poll().await?;
while let Ok(msg) = mqtt.poll().await {
tokio::task::yield_now().await;
// Put the reply on it's own async thread so we can safely sleep
// and wait for it to reply in it's own time
@@ -158,6 +152,7 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
}
});
}
Ok(())
} => v,
// Wait on any error from any of the error channels and if we get it we abort
v = error_recv.recv() => v.map(Err).unwrap_or_else(|| Err(anyhow!("Listen on camera error channel closed"))),
@@ -175,10 +170,6 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
.with_context(|| {
format!("Failed to post connect over MQTT for {}", camera_name)
})?;
if let Some(discovery_config) = &mqtt_config.discovery {
enable_discovery(discovery_config, &mqtt_sender_cam, &cam_config).await?;
}
}
Messages::FloodlightOn => {
mqtt_sender_cam
@@ -186,7 +177,7 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
.await
.with_context(|| {
format!(
"Failed to publish floodlight on over MQTT for {}",
"Failed to publish gloodlight on over MQTT for {}",
camera_name
)
})?;
@@ -197,7 +188,7 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
.await
.with_context(|| {
format!(
"Failed to publish floodlight off over MQTT for {}",
"Failed to publish gloodlight off over MQTT for {}",
camera_name
)
})?;
@@ -218,25 +209,6 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
format!("Failed to publish motion start for {}", camera_name)
})?;
}
Messages::Snap(data) => {
mqtt_sender_cam
.send_message("status/preview", BASE64.encode(data).as_str(), true)
.await
.with_context(|| {
format!("Failed to publish preview over MQTT for {}", camera_name)
})?;
}
Messages::BatteryLevel(data) => {
mqtt_sender_cam
.send_message("status/battery_level", format!("{}", data).as_str(), true)
.await
.with_context(|| {
format!(
"Failed to publish battery level over MQTT for {}",
camera_name
)
})?;
}
_ => {}
}
}
+7 -21
View File
@@ -50,31 +50,19 @@ pub(crate) struct MqttSender {
}
impl MqttSender {
pub async fn send_message_with_root_topic(
&self,
root_topic: &str,
sub_topic: &str,
message: &str,
retain: bool,
) -> Result<(), ClientError> {
self.client
.publish(
format!("{}/{}/{}", root_topic, self.name, sub_topic),
QoS::AtLeastOnce,
retain,
message,
)
.await?;
Ok(())
}
pub async fn send_message(
&self,
sub_topic: &str,
message: &str,
retain: bool,
) -> Result<(), ClientError> {
self.send_message_with_root_topic("neolink", sub_topic, message, retain)
self.client
.publish(
format!("neolink/{}/{}", self.name, sub_topic),
QoS::AtLeastOnce,
retain,
message,
)
.await?;
Ok(())
}
@@ -168,8 +156,6 @@ impl Mqtt {
&config.broker_addr,
config.port,
);
let max_size = 100 * (1024 * 1024);
mqttoptions.set_max_packet_size(max_size, max_size);
// Use TLS if ca path is set
if let Some(ca_path) = &config.ca {