Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
786218a114 | ||
|
|
52ad743bea | ||
|
|
0331945730 | ||
|
|
790807c016 | ||
|
|
45e08e6d7d | ||
|
|
5b3f845c83 | ||
|
|
4d6d5c5ac5 | ||
|
|
5583ea0f9a | ||
|
|
4286e75ca6 | ||
|
|
15880d1b84 | ||
|
|
0aee461156 | ||
|
|
b9969ce9ad | ||
|
|
254a310fe9 | ||
|
|
679cd60ce0 | ||
|
|
f73dbacd26 | ||
|
|
c6505952d5 | ||
|
|
4f0169ef8f | ||
|
|
15bf7cfa49 | ||
|
|
fbbfddaa37 | ||
|
|
f7b5e89ba8 | ||
|
|
c7bd565049 | ||
|
|
83dc6cc90b | ||
|
|
a449666a8c | ||
|
|
56476bc162 | ||
|
|
c30725bc09 | ||
|
|
3467951c5c | ||
|
|
9eb892ae27 | ||
|
|
00f30b8972 | ||
|
|
dba2f24364 | ||
|
|
2b3ae0e522 | ||
|
|
c2e613d68b | ||
|
|
b221fe6961 | ||
|
|
10956e8c8e | ||
|
|
48f385e73a | ||
|
|
5c3cae597f | ||
|
|
b5136ed913 | ||
|
|
2d37807401 | ||
|
|
fd3fffc0a1 | ||
|
|
fc8adf2a5c |
No files matched your search
Generated
+49
-34
@@ -198,9 +198,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.21.0"
|
||||
version = "0.21.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a"
|
||||
checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
@@ -459,9 +459,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "delegate"
|
||||
version = "0.9.0"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d358e0ec5c59a5e1603b933def447096886121660fc680dc1e64a0753981fe3c"
|
||||
checksum = "0ee5df75c70b95bd3aacc8e2fd098797692fb1d54121019c4de481e42f04c8a1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -1251,6 +1251,15 @@ dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.6"
|
||||
@@ -1408,9 +1417,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "neolink"
|
||||
version = "0.5.12"
|
||||
version = "0.5.14"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.21.2",
|
||||
"byte-slice-cast",
|
||||
"clap",
|
||||
"console-subscriber",
|
||||
@@ -1421,14 +1431,16 @@ dependencies = [
|
||||
"gstreamer-app",
|
||||
"gstreamer-rtsp",
|
||||
"gstreamer-rtsp-server",
|
||||
"heck",
|
||||
"is_sorted",
|
||||
"itertools",
|
||||
"itertools 0.11.0",
|
||||
"lazy_static",
|
||||
"log",
|
||||
"neolink_core",
|
||||
"regex",
|
||||
"rumqttc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"time",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
@@ -1440,7 +1452,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "neolink_core"
|
||||
version = "0.5.12"
|
||||
version = "0.5.14"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"assert_matches",
|
||||
@@ -1638,12 +1650,6 @@ version = "0.3.26"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"
|
||||
|
||||
[[package]]
|
||||
name = "pollster"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.17"
|
||||
@@ -1716,7 +1722,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools",
|
||||
"itertools 0.10.5",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 1.0.109",
|
||||
@@ -1857,17 +1863,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rumqttc"
|
||||
version = "0.20.0"
|
||||
version = "0.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b616bf8b706c2a6235604f5d93f9578c37d0c6161e13898b68a1da4af2d812c"
|
||||
checksum = "f2433b134712bc17a6f85a35e06b901e6e8d0bb20b5367e1121e6fedc140c0ac"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"flume",
|
||||
"futures",
|
||||
"log",
|
||||
"pollster",
|
||||
"rustls-native-certs",
|
||||
"rustls-pemfile",
|
||||
"rustls-webpki 0.100.1",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
@@ -1889,14 +1895,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.20.8"
|
||||
version = "0.21.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f"
|
||||
checksum = "79ea77c539259495ce8ca47f53e66ae0330a8819f67e23ac96ca02f50e7b7d36"
|
||||
dependencies = [
|
||||
"log",
|
||||
"ring",
|
||||
"rustls-webpki 0.101.1",
|
||||
"sct",
|
||||
"webpki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1917,7 +1923,27 @@ version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b"
|
||||
dependencies = [
|
||||
"base64 0.21.0",
|
||||
"base64 0.21.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.100.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6207cd5ed3d8dca7816f8f3725513a34609c0c765bf652b8c3cb4cfd87db46b"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.101.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15f36a6828982f422756984e47912a7a51dcbc2a197aa791158f8ca61cd8204e"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2319,13 +2345,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tokio-rustls"
|
||||
version = "0.23.4"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59"
|
||||
checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081"
|
||||
dependencies = [
|
||||
"rustls",
|
||||
"tokio",
|
||||
"webpki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2737,16 +2762,6 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki"
|
||||
version = "0.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.2.8"
|
||||
|
||||
+7
-4
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "neolink"
|
||||
description = "A standards-compliant bridge to Reolink IP cameras"
|
||||
version = "0.5.12"
|
||||
version = "0.5.14"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
@@ -13,6 +13,7 @@ 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"
|
||||
@@ -23,14 +24,16 @@ 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"
|
||||
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.12" }
|
||||
neolink_core = { path = "crates/core", version = "0.5.14" }
|
||||
regex = "1.7.3"
|
||||
rumqttc = "0.20.0"
|
||||
rumqttc = "0.22.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"
|
||||
|
||||
+2
-1
@@ -54,7 +54,8 @@ RUN apt-get update && \
|
||||
gstreamer1.0-x \
|
||||
gstreamer1.0-plugins-base \
|
||||
gstreamer1.0-plugins-good \
|
||||
gstreamer1.0-plugins-bad && \
|
||||
gstreamer1.0-plugins-bad \
|
||||
gstreamer1.0-libav && \
|
||||
apt-get clean -y && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=build \
|
||||
|
||||
@@ -154,6 +154,8 @@ 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:
|
||||
@@ -201,10 +203,13 @@ 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:
|
||||
|
||||
@@ -212,6 +217,53 @@ 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,7 +1,7 @@
|
||||
[package]
|
||||
name = "neolink_core"
|
||||
description = "Core services and structure for Reolink IP cameras"
|
||||
version = "0.5.12"
|
||||
version = "0.5.14"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
@@ -13,7 +13,7 @@ cfb-mode = "0.8.2"
|
||||
cookie-factory = "0.3.2"
|
||||
crc32fast = "1.3.2"
|
||||
crossbeam-channel = "0.5.8"
|
||||
delegate = "0.9.0"
|
||||
delegate = "0.10.0"
|
||||
err-derive = "0.3.1"
|
||||
futures = "0.3.28"
|
||||
get_if_addrs = "0.5.3"
|
||||
|
||||
@@ -197,8 +197,10 @@ 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))(buf)?;
|
||||
let (buf, _magic) = error_context(
|
||||
"Magic invalid",
|
||||
verify(le_u32, |x| *x == MAGIC_HEADER || *x == MAGIC_HEADER_REV),
|
||||
)(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)?;
|
||||
|
||||
@@ -3,7 +3,11 @@ use crate::Credentials;
|
||||
pub use super::xml::{BcPayloads, BcXml, Extension};
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(super) const MAGIC_HEADER: u32 = 0xabcdef0;
|
||||
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;
|
||||
|
||||
/// Login messages have this ID
|
||||
pub const MSG_ID_LOGIN: u32 = 1;
|
||||
@@ -33,6 +37,8 @@ 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
|
||||
|
||||
@@ -97,6 +97,9 @@ 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 {
|
||||
@@ -700,7 +703,37 @@ pub struct AbilityInfoSubModule {
|
||||
pub struct LinkType {
|
||||
#[yaserde(rename = "type")]
|
||||
/// Type of connection known values `"LAN"`
|
||||
link_type: String,
|
||||
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>,
|
||||
}
|
||||
|
||||
/// Convience function to return the xml version used throughout the library
|
||||
|
||||
@@ -27,6 +27,7 @@ mod pirstate;
|
||||
mod ptz;
|
||||
mod reboot;
|
||||
mod resolution;
|
||||
mod snap;
|
||||
mod stream;
|
||||
mod talk;
|
||||
mod time;
|
||||
|
||||
@@ -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_num).await?;
|
||||
let mut sub_get = connection.subscribe(MSG_ID_ABILITY_INFO, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_ABILITY_INFO,
|
||||
|
||||
@@ -83,7 +83,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
let mut sub = connection.subscribe(MSG_ID_BATTERY_INFO, msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
|
||||
@@ -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 Num
|
||||
num: BTreeMap<u16, Sender<Result<Bc>>>,
|
||||
/// Subscribers based on their ID and their num
|
||||
num: BTreeMap<u32, BTreeMap<Option<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_num: u16) -> Result<BcSubscription> {
|
||||
pub async fn subscribe(&self, msg_id: u32, msg_num: u16) -> Result<BcSubscription> {
|
||||
let (tx, rx) = channel(100);
|
||||
self.poll_commander
|
||||
.send(PollCommand::AddSubscriber(msg_num, tx))
|
||||
.send(PollCommand::AddSubscriber(msg_id, Some(msg_num), tx))
|
||||
.await?;
|
||||
Ok(BcSubscription::new(rx, msg_num as u32, self))
|
||||
Ok(BcSubscription::new(rx, Some(msg_num as u32), self))
|
||||
}
|
||||
|
||||
/// Some messages are initiated by the camera. This creates a handler for them
|
||||
@@ -115,6 +115,21 @@ 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 {
|
||||
@@ -138,7 +153,7 @@ enum PollCommand {
|
||||
Bc(Box<Result<Bc>>),
|
||||
AddHandler(u32, Arc<MsgHandler>),
|
||||
RemoveHandler(u32),
|
||||
AddSubscriber(u16, Sender<Result<Bc>>),
|
||||
AddSubscriber(u32, Option<u16>, Sender<Result<Bc>>),
|
||||
}
|
||||
|
||||
struct Poller {
|
||||
@@ -152,66 +167,96 @@ 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;
|
||||
|
||||
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?;
|
||||
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?;
|
||||
}
|
||||
}
|
||||
}
|
||||
(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
|
||||
(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
|
||||
);
|
||||
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);
|
||||
}
|
||||
}
|
||||
if remove_it_num {
|
||||
self.subscribers.num.remove(&msg_num);
|
||||
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);
|
||||
}
|
||||
}
|
||||
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) => {
|
||||
@@ -225,8 +270,14 @@ impl Poller {
|
||||
PollCommand::RemoveHandler(msg_id) => {
|
||||
self.subscribers.id.remove(&msg_id);
|
||||
}
|
||||
PollCommand::AddSubscriber(msg_num, tx) => {
|
||||
match self.subscribers.num.entry(msg_num) {
|
||||
PollCommand::AddSubscriber(msg_id, msg_num, tx) => {
|
||||
match self
|
||||
.subscribers
|
||||
.num
|
||||
.entry(msg_id)
|
||||
.or_default()
|
||||
.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: u32,
|
||||
msg_num: Option<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: u32,
|
||||
msg_num: Option<u32>,
|
||||
conn: &'a BcConnection,
|
||||
) -> BcSubscription<'a> {
|
||||
BcSubscription {
|
||||
@@ -100,7 +100,11 @@ impl<'a> BcSubscription<'a> {
|
||||
}
|
||||
|
||||
pub async fn send(&self, bc: Bc) -> Result<()> {
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
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");
|
||||
}
|
||||
self.conn.send(bc).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -108,7 +112,12 @@ 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 {
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
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);
|
||||
}
|
||||
}
|
||||
bc
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ impl Discoverer {
|
||||
Ok(rx)
|
||||
} else {
|
||||
Err(Error::SimultaneousSubscription {
|
||||
msg_num: (tid as u16),
|
||||
msg_num: Some(tid as u16),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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: u16,
|
||||
msg_num: Option<u16>,
|
||||
},
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once for msg_id
|
||||
|
||||
@@ -45,7 +45,9 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_FLOODLIGHT_MANUAL, msg_num)
|
||||
.await?;
|
||||
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
@@ -77,18 +79,25 @@ impl BcCamera {
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
let msg = sub_set.recv().await?;
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
|
||||
{
|
||||
Ok(())
|
||||
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 {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the Floodlight manual state",
|
||||
})
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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_num).await?;
|
||||
let mut sub_get = connection.subscribe(MSG_ID_GET_LED_STATUS, 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_num).await?;
|
||||
let mut sub_set = connection.subscribe(MSG_ID_SET_LED_STATUS, 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,18 +83,25 @@ impl BcCamera {
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
let msg = sub_set.recv().await?;
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
|
||||
{
|
||||
Ok(())
|
||||
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 except the LEDState xml",
|
||||
})
|
||||
}
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the LEDState xml",
|
||||
})
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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_num).await?;
|
||||
let mut sub_login = connection.subscribe(MSG_ID_LOGIN, 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
|
||||
|
||||
@@ -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_num).await?;
|
||||
let sub_logout = connection.subscribe(MSG_ID_LOGOUT, msg_num).await?;
|
||||
|
||||
let username = credentials.username.clone();
|
||||
let password = credentials.password.as_ref().cloned().unwrap_or_default();
|
||||
|
||||
@@ -167,7 +167,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
let mut sub = connection.subscribe(MSG_ID_MOTION_REQUEST, 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> {
|
||||
let msg_num = self.start_motion_query().await?;
|
||||
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(msg_num).await?;
|
||||
let mut sub = connection.subscribe_to_id(MSG_ID_MOTION).await?;
|
||||
|
||||
loop {
|
||||
tokio::task::yield_now().await;
|
||||
|
||||
@@ -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_num).await?;
|
||||
let mut sub_ping = connection.subscribe(MSG_ID_PING, msg_num).await?;
|
||||
|
||||
let ping = Bc {
|
||||
meta: BcMeta {
|
||||
|
||||
@@ -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_num).await?;
|
||||
let mut sub_get = connection.subscribe(MSG_ID_GET_PIR_ALARM, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_PIR_ALARM,
|
||||
@@ -70,7 +70,9 @@ 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_num).await?;
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_START_PIR_ALARM, msg_num)
|
||||
.await?;
|
||||
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
@@ -94,21 +96,28 @@ impl BcCamera {
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
let msg = sub_set.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
|
||||
{
|
||||
Ok(())
|
||||
let msg = reply?;
|
||||
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 {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the RfAlarmCfg xml",
|
||||
})
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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_num).await?;
|
||||
let mut sub_set = connection.subscribe(MSG_ID_PTZ_CONTROL, 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_num).await?;
|
||||
let mut sub_set = connection.subscribe(MSG_ID_GET_PTZ_PRESET, msg_num).await?;
|
||||
|
||||
let send = Bc {
|
||||
meta: BcMeta {
|
||||
@@ -136,7 +136,9 @@ 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_num).await?;
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_PTZ_CONTROL_PRESET, msg_num)
|
||||
.await?;
|
||||
|
||||
let preset = Preset {
|
||||
id: preset_id,
|
||||
@@ -191,7 +193,9 @@ 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_num).await?;
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_PTZ_CONTROL_PRESET, msg_num)
|
||||
.await?;
|
||||
|
||||
let preset = Preset {
|
||||
id: preset_id,
|
||||
|
||||
@@ -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_num).await?;
|
||||
let mut sub = connection.subscribe(MSG_ID_REBOOT, msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
// 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",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -111,7 +111,7 @@ impl BcCamera {
|
||||
|
||||
let handle = task::spawn(async move {
|
||||
tokio::task::yield_now().await;
|
||||
let mut sub_video = connection.subscribe(msg_num).await?;
|
||||
let mut sub_video = connection.subscribe(MSG_ID_VIDEO, msg_num).await?;
|
||||
|
||||
// On an E1 and swann cameras:
|
||||
// - mainStream always has a value of 0
|
||||
@@ -224,13 +224,14 @@ impl BcCamera {
|
||||
},
|
||||
);
|
||||
// debug!("Stream: Send Stop");
|
||||
sub_video.send(stop_video).await?;
|
||||
let mut sub_stop = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?;
|
||||
sub_stop.send(stop_video).await?;
|
||||
// debug!("Stream: Sent Stop");
|
||||
|
||||
tokio::select! {
|
||||
v = async {
|
||||
loop {
|
||||
let msg = sub_video.recv().await?;
|
||||
let msg = sub_stop.recv().await?;
|
||||
if let BcMeta {
|
||||
response_code: 200,
|
||||
msg_id: MSG_ID_VIDEO_STOP,
|
||||
@@ -268,7 +269,7 @@ impl BcCamera {
|
||||
}
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_video = connection.subscribe(msg_num).await?;
|
||||
let mut sub_video = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?;
|
||||
|
||||
// On an E1 and swann cameras:
|
||||
// - mainStream always has a value of 0
|
||||
|
||||
@@ -17,7 +17,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
let mut sub = connection.subscribe(MSG_ID_TALKRESET, 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_num).await?;
|
||||
let mut sub_get = connection.subscribe(MSG_ID_TALKABILITY, 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_num).await?;
|
||||
let mut sub = connection.subscribe(MSG_ID_TALKCONFIG, 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_num).await?;
|
||||
let sub = connection.subscribe(MSG_ID_TALK, 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_num).await?;
|
||||
let mut sub = connection.subscribe(MSG_ID_TALKCONFIG, 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_num).await?;
|
||||
let sub = connection.subscribe(MSG_ID_TALK, msg_num).await?;
|
||||
|
||||
const BLOCK_PER_PAYLOAD: usize = 1;
|
||||
const BLOCK_HEADER_SIZE: usize = 4;
|
||||
|
||||
@@ -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_num).await?;
|
||||
let mut sub_get_general = connection.subscribe(MSG_ID_GET_GENERAL, 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_num).await?;
|
||||
let mut sub_set_general = connection.subscribe(MSG_ID_SET_GENERAL, msg_num).await?;
|
||||
let set = Bc::new_from_xml(
|
||||
BcMeta {
|
||||
msg_id: MSG_ID_SET_GENERAL,
|
||||
|
||||
@@ -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_num).await?;
|
||||
let mut sub_version = connection.subscribe(MSG_ID_VERSION, msg_num).await?;
|
||||
|
||||
let version = Bc {
|
||||
meta: BcMeta {
|
||||
|
||||
@@ -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(0),
|
||||
le_u32(0xd7160000),
|
||||
le_u32(binary_payload.len() as u32),
|
||||
slice(binary_payload),
|
||||
))
|
||||
|
||||
@@ -38,6 +38,10 @@ 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
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
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;
|
||||
|
||||
@@ -118,6 +120,9 @@ pub(crate) struct CameraConfig {
|
||||
alias = "stretching"
|
||||
)]
|
||||
pub(crate) use_smoothing: bool,
|
||||
|
||||
#[serde(default = "default_true", alias = "splash")]
|
||||
pub(crate) use_splash: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
@@ -146,6 +151,27 @@ 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> {
|
||||
@@ -158,6 +184,10 @@ fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
|
||||
}
|
||||
}
|
||||
|
||||
const fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_mqtt() -> Option<MqttConfig> {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -10,4 +10,9 @@ pub struct Opt {
|
||||
/// The path of the output.
|
||||
#[structopt(short, long, value_parser = PathBuf::from_str)]
|
||||
pub file_path: PathBuf,
|
||||
/// If set then the image will pull from the live stream, if not it will be pulled from the cameras snap feature
|
||||
///
|
||||
/// Using the snap feature, is preffered unless your camera does not support it
|
||||
#[structopt(short, long)]
|
||||
pub use_stream: bool,
|
||||
}
|
||||
+52
-33
@@ -9,9 +9,18 @@
|
||||
/// neolink image --config=config.toml --file-path=filepath CameraName
|
||||
/// ```
|
||||
///
|
||||
/// Cameras that do not support the SNAP command need to use `--use_stream`
|
||||
/// which will make the camera play the stream and transcode the video into a jpeg
|
||||
/// e.g.:
|
||||
///
|
||||
/// ```bash
|
||||
/// neolink image --config=config.toml --use_stream --file-path=filepath CameraName
|
||||
/// ```
|
||||
///
|
||||
use anyhow::{Context, Result};
|
||||
use log::*;
|
||||
use neolink_core::{bc_protocol::*, bcmedia::model::*};
|
||||
use tokio::{fs::File, io::AsyncWriteExt};
|
||||
|
||||
mod cmdline;
|
||||
mod gst;
|
||||
@@ -32,44 +41,54 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
let camera = connect_and_login(camera_config)
|
||||
.await
|
||||
.context("Failed to connect to the camera, check credentials and network")?;
|
||||
let mut stream_data = camera
|
||||
.start_video(StreamKind::Main, 0, camera_config.strict)
|
||||
.await
|
||||
.context("Failed to start video")?;
|
||||
|
||||
// Get one iframe at the start while also getting the the video type
|
||||
let buf;
|
||||
let vid_type;
|
||||
loop {
|
||||
if let BcMedia::Iframe(frame) = stream_data.get_data().await?? {
|
||||
vid_type = frame.video_type;
|
||||
buf = frame.data;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if opt.use_stream {
|
||||
let mut stream_data = camera
|
||||
.start_video(StreamKind::Main, 0, camera_config.strict)
|
||||
.await
|
||||
.context("Failed to start video")?;
|
||||
|
||||
let mut sender = gst::from_input(vid_type, &opt.file_path).await?;
|
||||
sender.send(buf).await?; // Send first iframe
|
||||
|
||||
// Keep sending both IFrame or PFrame until finished
|
||||
while sender.is_finished().await.is_none() {
|
||||
let buf = match stream_data.get_data().await?? {
|
||||
BcMedia::Iframe(frame) => frame.data,
|
||||
BcMedia::Pframe(frame) => frame.data,
|
||||
_ => {
|
||||
continue;
|
||||
// Get one iframe at the start while also getting the the video type
|
||||
let buf;
|
||||
let vid_type;
|
||||
loop {
|
||||
if let BcMedia::Iframe(frame) = stream_data.get_data().await?? {
|
||||
vid_type = frame.video_type;
|
||||
buf = frame.data;
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
debug!("Sending frame data to gstreamer");
|
||||
if sender.send(buf).await.is_err() {
|
||||
// Assume that the sender is closed
|
||||
// because the pipeline is finished
|
||||
break;
|
||||
}
|
||||
|
||||
let mut sender = gst::from_input(vid_type, &opt.file_path).await?;
|
||||
sender.send(buf).await?; // Send first iframe
|
||||
|
||||
// Keep sending both IFrame or PFrame until finished
|
||||
while sender.is_finished().await.is_none() {
|
||||
let buf = match stream_data.get_data().await?? {
|
||||
BcMedia::Iframe(frame) => frame.data,
|
||||
BcMedia::Pframe(frame) => frame.data,
|
||||
_ => {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
debug!("Sending frame data to gstreamer");
|
||||
if sender.send(buf).await.is_err() {
|
||||
// Assume that the sender is closed
|
||||
// because the pipeline is finished
|
||||
break;
|
||||
}
|
||||
}
|
||||
debug!("Sending EOS");
|
||||
let _ = sender.eos().await; // Ignore return because if pipeline is finished this will error
|
||||
} else {
|
||||
// Simply use the snap command
|
||||
debug!("Using the snap command");
|
||||
let file_path = opt.file_path.with_extension("jpeg");
|
||||
let mut buffer = File::create(file_path).await?;
|
||||
let jpeg_data = camera.get_snapshot().await?;
|
||||
buffer.write_all(jpeg_data.as_slice()).await?;
|
||||
}
|
||||
debug!("Sending EOS");
|
||||
let _ = sender.eos().await; // Ignore return because if pipeline is finished this will error
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
//! 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(())
|
||||
}
|
||||
+109
-7
@@ -1,5 +1,5 @@
|
||||
use crate::config::CameraConfig;
|
||||
use crate::utils::AddressOrUid;
|
||||
use crate::utils::{timeout, AddressOrUid};
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use futures::stream::StreamExt;
|
||||
use log::*;
|
||||
@@ -31,6 +31,8 @@ pub(crate) enum Messages {
|
||||
PIROff,
|
||||
PIRQuery,
|
||||
Ptz(Direction),
|
||||
Snap(Vec<u8>),
|
||||
BatteryLevel(u32),
|
||||
Preset(u8),
|
||||
PresetAssign(u8, String),
|
||||
PresetQuery,
|
||||
@@ -191,10 +193,9 @@ impl EventCamThread {
|
||||
"aes" => MaxEncryption::Aes,
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
camera
|
||||
.login_with_maxenc(max_encryption)
|
||||
timeout(camera.login_with_maxenc(max_encryption))
|
||||
.await
|
||||
.context("Failed to login to the camera")?;
|
||||
.context("Failed to login to the camera")??;
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
self.tx.send(Messages::Login).await?;
|
||||
@@ -212,6 +213,16 @@ 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(),
|
||||
};
|
||||
@@ -225,7 +236,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)
|
||||
@@ -237,7 +248,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)
|
||||
@@ -249,7 +260,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)
|
||||
@@ -258,6 +269,30 @@ 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
|
||||
@@ -331,6 +366,73 @@ 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>,
|
||||
}
|
||||
|
||||
+32
-4
@@ -1,3 +1,4 @@
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
|
||||
///
|
||||
/// # Neolink MQTT
|
||||
///
|
||||
@@ -9,6 +10,7 @@
|
||||
///
|
||||
/// 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
|
||||
@@ -60,18 +62,21 @@ 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},
|
||||
};
|
||||
@@ -135,7 +140,8 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
tokio::select! {
|
||||
v = async {
|
||||
// Normal poll operations
|
||||
while let Ok(msg) = mqtt.poll().await {
|
||||
loop {
|
||||
let 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
|
||||
@@ -152,7 +158,6 @@ 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"))),
|
||||
@@ -170,6 +175,10 @@ 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
|
||||
@@ -177,7 +186,7 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish gloodlight on over MQTT for {}",
|
||||
"Failed to publish floodlight on over MQTT for {}",
|
||||
camera_name
|
||||
)
|
||||
})?;
|
||||
@@ -188,7 +197,7 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish gloodlight off over MQTT for {}",
|
||||
"Failed to publish floodlight off over MQTT for {}",
|
||||
camera_name
|
||||
)
|
||||
})?;
|
||||
@@ -209,6 +218,25 @@ 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
|
||||
)
|
||||
})?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
+16
-2
@@ -50,15 +50,16 @@ pub(crate) struct MqttSender {
|
||||
}
|
||||
|
||||
impl MqttSender {
|
||||
pub async fn send_message(
|
||||
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!("neolink/{}/{}", self.name, sub_topic),
|
||||
format!("{}/{}/{}", root_topic, self.name, sub_topic),
|
||||
QoS::AtLeastOnce,
|
||||
retain,
|
||||
message,
|
||||
@@ -67,6 +68,17 @@ impl MqttSender {
|
||||
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)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn subscribe(&self) -> Result<(), ClientError> {
|
||||
self.client
|
||||
.subscribe(format!("neolink/{}/#", self.name), QoS::AtMostOnce)
|
||||
@@ -156,6 +168,8 @@ 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 {
|
||||
|
||||
+54
-46
@@ -41,17 +41,17 @@ glib::wrapper! {
|
||||
|
||||
impl Default for NeoMediaFactory {
|
||||
fn default() -> Self {
|
||||
Self::new(100, true)
|
||||
Self::new(100, true, true)
|
||||
}
|
||||
}
|
||||
|
||||
impl NeoMediaFactory {
|
||||
pub(crate) fn new(buffer_size: usize, use_smoothing: bool) -> Self {
|
||||
pub(crate) fn new(buffer_size: usize, use_smoothing: bool, use_splash: bool) -> Self {
|
||||
let factory = Object::new::<NeoMediaFactory>();
|
||||
factory.set_shared(false);
|
||||
factory.imp().shared.set_buffer_size(buffer_size);
|
||||
factory.imp().shared.set_use_smoothing(use_smoothing);
|
||||
// factory.set_do_retransmission(false); // Can't use as the method is missing on the 32bit docker gst dll
|
||||
factory.imp().shared.set_use_splash(use_splash);
|
||||
factory.set_launch("videotestsrc pattern=\"snow\" ! video/x-raw,width=896,height=512,framerate=25/1 ! textoverlay name=\"inittextoverlay\" text=\"Stream not Ready\" valignment=top halignment=left font-desc=\"Sans, 32\" ! jpegenc ! rtpjpegpay name=pay0");
|
||||
factory.set_suspend_mode(RTSPSuspendMode::None);
|
||||
factory.set_transport_mode(RTSPTransportMode::PLAY);
|
||||
@@ -184,7 +184,7 @@ impl ObjectImpl for NeoMediaFactoryImpl {}
|
||||
impl RTSPMediaFactoryImpl for NeoMediaFactoryImpl {
|
||||
fn create_element(&self, url: &RTSPUrl) -> Option<Element> {
|
||||
self.parent_create_element(url)
|
||||
.map(|orig| self.build_pipeline(orig).expect("Could not build pipeline"))
|
||||
.and_then(|orig| self.build_pipeline(orig).expect("Could not build pipeline"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,18 +239,18 @@ fn make_queue(name: &str) -> AnyResult<Element> {
|
||||
Ok(queue)
|
||||
}
|
||||
|
||||
fn make_queue2(name: &str) -> AnyResult<Element> {
|
||||
let queue = make_element("queue2", name)?;
|
||||
queue.set_property("use-buffering", true);
|
||||
queue.set_property("max-size-bytes", 0u32);
|
||||
queue.set_property("max-size-buffers", 0u32);
|
||||
queue.set_property(
|
||||
"max-size-time",
|
||||
std::convert::TryInto::<u64>::try_into(tokio::time::Duration::from_secs(5).as_nanos())
|
||||
.unwrap_or(0),
|
||||
);
|
||||
Ok(queue)
|
||||
}
|
||||
// fn make_queue2(name: &str) -> AnyResult<Element> {
|
||||
// let queue = make_element("queue2", name)?;
|
||||
// queue.set_property("use-buffering", true);
|
||||
// queue.set_property("max-size-bytes", 0u32);
|
||||
// queue.set_property("max-size-buffers", 0u32);
|
||||
// queue.set_property(
|
||||
// "max-size-time",
|
||||
// std::convert::TryInto::<u64>::try_into(tokio::time::Duration::from_secs(5).as_nanos())
|
||||
// .unwrap_or(0),
|
||||
// );
|
||||
// Ok(queue)
|
||||
// }
|
||||
|
||||
impl NeoMediaFactoryImpl {
|
||||
pub(crate) fn buffer_ready(&self) -> bool {
|
||||
@@ -260,15 +260,17 @@ impl NeoMediaFactoryImpl {
|
||||
self.shared.number_of_clients.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn build_pipeline(&self, media: Element) -> AnyResult<Element> {
|
||||
fn build_pipeline(&self, media: Element) -> AnyResult<Option<Element>> {
|
||||
// debug!("Building PIPELINE");
|
||||
let bin = media
|
||||
.dynamic_cast::<Bin>()
|
||||
.map_err(|_| anyhow!("Media source's element should be a bin"))?;
|
||||
// Clear the autogenerated ones
|
||||
log::debug!("Clearing old elements");
|
||||
for element in bin.iterate_elements().into_iter().flatten() {
|
||||
bin.remove(&element)?;
|
||||
}
|
||||
log::debug!("Cleared");
|
||||
|
||||
let mut client_data = NeoMediaSender::new(
|
||||
self.shared.get_buffer_size(),
|
||||
@@ -281,12 +283,15 @@ impl NeoMediaFactoryImpl {
|
||||
self.shared.buffer_ready.load(Ordering::Relaxed),
|
||||
) {
|
||||
(VidFormats::Unknown, true) | (_, false) => {
|
||||
if !self.shared.get_use_splash() {
|
||||
return Ok(None);
|
||||
}
|
||||
debug!("Building Unknown Pipeline");
|
||||
let source = make_element("videotestsrc", "testvidsrc")?;
|
||||
source.set_property_from_str("pattern", "snow");
|
||||
source.set_property("num-buffers", 500i32); // Send buffers then EOS
|
||||
let queue = make_queue("queue0")?;
|
||||
let queue2 = make_queue2("queue2")?;
|
||||
// let queue2 = make_queue2("queue2")?;
|
||||
let overlay = make_element("textoverlay", "overlay")?;
|
||||
overlay.set_property("text", "Stream not Ready");
|
||||
overlay.set_property_from_str("valignment", "top");
|
||||
@@ -295,7 +300,7 @@ impl NeoMediaFactoryImpl {
|
||||
let encoder = make_element("jpegenc", "encoder")?;
|
||||
let payload = make_element("rtpjpegpay", "pay0")?;
|
||||
|
||||
bin.add_many(&[&source, &queue, &queue2, &overlay, &encoder, &payload])?;
|
||||
bin.add_many(&[&source, &queue, &overlay, &encoder, &payload])?;
|
||||
source.link_filtered(
|
||||
&queue,
|
||||
&Caps::builder("video/x-raw")
|
||||
@@ -306,7 +311,7 @@ impl NeoMediaFactoryImpl {
|
||||
.build(),
|
||||
)?;
|
||||
// source.link(&queue)?;
|
||||
Element::link_many(&[&queue, &queue2, &overlay, &encoder, &payload])?;
|
||||
Element::link_many(&[&queue, &overlay, &encoder, &payload])?;
|
||||
}
|
||||
(VidFormats::H265, true) => {
|
||||
debug!("Building H265 Pipeline");
|
||||
@@ -355,12 +360,12 @@ impl NeoMediaFactoryImpl {
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
let queue = make_queue("source_queue")?;
|
||||
let queue2 = make_queue2("queue2")?;
|
||||
// let queue2 = make_queue2("queue2")?;
|
||||
let parser = make_element("h265parse", "parser")?;
|
||||
// parser.set_property("config-interval", 5i32);
|
||||
let payload = make_element("rtph265pay", "pay0")?;
|
||||
bin.add_many(&[&source, &queue, &queue2, &parser, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &queue2, &parser, &payload])?;
|
||||
bin.add_many(&[&source, &queue, &parser, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &parser, &payload])?;
|
||||
|
||||
let source = source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
@@ -417,7 +422,7 @@ impl NeoMediaFactoryImpl {
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
let queue = make_queue("source_queue")?;
|
||||
let queue2 = make_queue2("queue2")?;
|
||||
// let queue2 = make_queue2("queue2")?;
|
||||
let parser = make_element("h264parse", "parser")?;
|
||||
// parser.set_property("update-timecode", true);
|
||||
let payload = make_element("rtph264pay", "pay0")?;
|
||||
@@ -429,13 +434,13 @@ impl NeoMediaFactoryImpl {
|
||||
|
||||
// payload.set_property("config-interval", 5i32);
|
||||
bin.add_many(&[
|
||||
&source, &queue, &queue2, &parser,
|
||||
&source, &queue, &parser,
|
||||
&payload,
|
||||
// &storage,
|
||||
// &jitter,
|
||||
])?;
|
||||
Element::link_many(&[
|
||||
&source, &queue, &queue2, &parser,
|
||||
&source, &queue, &parser,
|
||||
&payload,
|
||||
// &storage,
|
||||
// &jitter,
|
||||
@@ -488,25 +493,26 @@ impl NeoMediaFactoryImpl {
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
|
||||
let queue = make_queue("audqueue")?;
|
||||
let queue2 = make_queue2("audqueue2")?;
|
||||
// let queue2 = make_queue2("audqueue2")?;
|
||||
let parser = make_element("aacparse", "audparser")?;
|
||||
let decoder = make_element("decodebin", "auddecoder")?;
|
||||
let decoder = match make_element("faad", "auddecoder_faad") {
|
||||
Ok(ele) => Ok(ele),
|
||||
Err(_) => make_element("avdec_aac", "auddecoder_avdec_aac"),
|
||||
}?;
|
||||
let encoder = make_element("audioconvert", "audencoder")?;
|
||||
let payload = make_element("rtpL16pay", "pay1")?;
|
||||
|
||||
bin.add_many(&[
|
||||
&source, &queue, &queue2, &parser, &decoder, &encoder, &payload,
|
||||
])?;
|
||||
Element::link_many(&[&source, &queue, &queue2, &parser, &decoder])?;
|
||||
Element::link_many(&[&encoder, &payload])?;
|
||||
decoder.connect_pad_added(move |_element, pad| {
|
||||
debug!("Linking encoder to decoder: {:?}", pad.caps());
|
||||
let sink_pad = encoder
|
||||
.static_pad("sink")
|
||||
.expect("Encoder is missing its pad");
|
||||
pad.link(&sink_pad)
|
||||
.expect("Failed to link AAC decoder to encoder");
|
||||
});
|
||||
bin.add_many(&[&source, &queue, &parser, &decoder, &encoder, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &parser, &decoder, &encoder, &payload])?;
|
||||
// Element::link_many(&[])?;
|
||||
// decoder.connect_pad_added(move |_element, pad| {
|
||||
// debug!("Linking encoder to decoder: {:?}", pad.caps());
|
||||
// let sink_pad = encoder
|
||||
// .static_pad("sink")
|
||||
// .expect("Encoder is missing its pad");
|
||||
// pad.link(&sink_pad)
|
||||
// .expect("Failed to link AAC decoder to encoder");
|
||||
// });
|
||||
|
||||
let source = source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
@@ -560,13 +566,13 @@ impl NeoMediaFactoryImpl {
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
|
||||
let queue = make_queue("audqueue")?;
|
||||
let queue2 = make_queue2("audqueue2")?;
|
||||
// let queue2 = make_queue2("audqueue2")?;
|
||||
let decoder = make_element("decodebin", "auddecoder")?;
|
||||
let encoder = make_element("audioconvert", "audencoder")?;
|
||||
let payload = make_element("rtpL16pay", "pay1")?;
|
||||
|
||||
bin.add_many(&[&source, &queue, &queue2, &decoder, &encoder, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &queue2, &decoder])?;
|
||||
bin.add_many(&[&source, &queue, &decoder, &encoder, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &decoder])?;
|
||||
Element::link_many(&[&encoder, &payload])?;
|
||||
decoder.connect_pad_added(move |_element, pad| {
|
||||
debug!("Linking encoder to decoder: {:?}", pad.caps());
|
||||
@@ -586,8 +592,10 @@ impl NeoMediaFactoryImpl {
|
||||
|
||||
self.clientsender.blocking_send(client_data)?;
|
||||
// debug!("Pipeline built");
|
||||
bin.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))
|
||||
let element = bin
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
Ok(Some(element))
|
||||
}
|
||||
|
||||
async fn join(&self) -> AnyResult<()> {
|
||||
|
||||
+76
-147
@@ -444,8 +444,8 @@ pub(super) struct NeoMediaSender {
|
||||
start_time: Spring,
|
||||
live_offset: FrameTime,
|
||||
buffer: NeoBuffer,
|
||||
vid: Option<AppSrc>,
|
||||
aud: Option<AppSrc>,
|
||||
vid: Option<Arc<AppSrc>>,
|
||||
aud: Option<Arc<AppSrc>>,
|
||||
command_reciever: Receiver<NeoMediaSenderCommand>,
|
||||
command_sender: Sender<NeoMediaSenderCommand>,
|
||||
inited: bool,
|
||||
@@ -453,6 +453,11 @@ pub(super) struct NeoMediaSender {
|
||||
use_smoothing: bool,
|
||||
}
|
||||
|
||||
enum Buffer {
|
||||
Video(gstreamer::Buffer),
|
||||
Audio(gstreamer::Buffer),
|
||||
}
|
||||
|
||||
impl NeoMediaSender {
|
||||
pub(super) fn new(buffer_size: usize, use_smoothing: bool) -> Self {
|
||||
let (tx, rx) = channel(30);
|
||||
@@ -476,11 +481,11 @@ impl NeoMediaSender {
|
||||
}
|
||||
|
||||
pub(super) fn update_vid(&mut self, source: AppSrc) {
|
||||
self.vid.replace(source);
|
||||
self.vid.replace(Arc::new(source));
|
||||
}
|
||||
|
||||
pub(super) fn update_aud(&mut self, source: AppSrc) {
|
||||
self.aud.replace(source);
|
||||
self.aud.replace(Arc::new(source));
|
||||
}
|
||||
|
||||
pub(super) fn get_commader(&self) -> Sender<NeoMediaSenderCommand> {
|
||||
@@ -615,15 +620,22 @@ impl NeoMediaSender {
|
||||
self.buffer.buf.clear();
|
||||
|
||||
let mut buffer_iter = buffer.buf.iter().cloned();
|
||||
// The prebuffer should starts from an Iframe
|
||||
let preprocess = buffer_iter
|
||||
.take_while_ref(|item| item.time < target_time)
|
||||
.take_while_ref(|item| {
|
||||
item.time < target_time
|
||||
|| !matches!(
|
||||
item.data.first().map(|arc| arc.as_ref()),
|
||||
Some(BcMedia::Iframe(_))
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut buffer = buffer_iter.collect::<Vec<_>>();
|
||||
self.start_time.reset_to(target_time as f64);
|
||||
|
||||
// Send preprocess now
|
||||
self.send_buffers(preprocess.as_slice(), true).await?;
|
||||
trace!("Preprocessed: {}", preprocess.len());
|
||||
debug!("Preprocessed: {}", preprocess.len());
|
||||
// Send these later
|
||||
for frame in buffer.drain(..) {
|
||||
self.buffer.buf.push_back(frame);
|
||||
@@ -717,17 +729,11 @@ impl NeoMediaSender {
|
||||
if medias.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
let mut vid_buffers: Vec<(FrameTime, Vec<u8>)> = vec![];
|
||||
let mut aud_buffers: Vec<(FrameTime, Vec<u8>)> = vec![];
|
||||
let mut buffers: Vec<Buffer> = vec![];
|
||||
|
||||
for media_sets in medias.iter() {
|
||||
tokio::task::yield_now().await;
|
||||
for media in media_sets.data.iter() {
|
||||
let buffer = match media.as_ref() {
|
||||
BcMedia::Iframe(_) | BcMedia::Pframe(_) => Some(&mut vid_buffers),
|
||||
BcMedia::Aac(_) | BcMedia::Adpcm(_) => Some(&mut aud_buffers),
|
||||
_ => None,
|
||||
};
|
||||
let data = match media.as_ref() {
|
||||
BcMedia::Iframe(data) => Some(&data.data),
|
||||
BcMedia::Pframe(data) => Some(&data.data),
|
||||
@@ -735,148 +741,71 @@ impl NeoMediaSender {
|
||||
BcMedia::Adpcm(data) => Some(&data.data),
|
||||
_ => None,
|
||||
};
|
||||
if let (Some(data), Some(buffer)) = (data, buffer) {
|
||||
let next_time = media_sets.time;
|
||||
if let Some(last) = buffer.last_mut() {
|
||||
let last_time = last.0;
|
||||
if next_time == last_time {
|
||||
last.1.extend(data.iter().copied());
|
||||
} else {
|
||||
buffer.push((next_time, data.clone()))
|
||||
if let Some(buf) = data {
|
||||
let time = media_sets.time;
|
||||
let runtime = match (self.get_runtime(), ignore_stamps) {
|
||||
(None, _) | (_, false) => self.buftime_to_runtime(time),
|
||||
(Some(runtime), true) => runtime,
|
||||
};
|
||||
trace!(
|
||||
" - Sending vid frame at time {} ({:?} Expect: {:?})",
|
||||
time,
|
||||
Duration::from_micros(runtime as u64),
|
||||
self.get_runtime().map(|i| Duration::from_micros(i as u64))
|
||||
);
|
||||
|
||||
let gst_buf = {
|
||||
let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
|
||||
let time = ClockTime::from_useconds(runtime.try_into().unwrap());
|
||||
gst_buf_mut.set_dts(time);
|
||||
gst_buf_mut.set_pts(time);
|
||||
let mut gst_buf_data = gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(buf.as_slice());
|
||||
}
|
||||
} else {
|
||||
buffer.push((next_time, data.clone()))
|
||||
gst_buf
|
||||
};
|
||||
match media.as_ref() {
|
||||
BcMedia::Iframe(_) | BcMedia::Pframe(_) => {
|
||||
buffers.push(Buffer::Video(gst_buf));
|
||||
}
|
||||
BcMedia::Aac(_) | BcMedia::Adpcm(_) => {
|
||||
buffers.push(Buffer::Audio(gst_buf));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
tokio::try_join!(
|
||||
async {
|
||||
if !vid_buffers.is_empty() {
|
||||
// debug!("Sending video buffers: {}", vid_buffers.len());
|
||||
if let Some(appsrc) = self.vid.clone() {
|
||||
let buffers = {
|
||||
let mut buffers = gstreamer::BufferList::new_sized(vid_buffers.len());
|
||||
{
|
||||
let buffers_ref = buffers.get_mut().unwrap();
|
||||
for (time, buf) in vid_buffers.drain(..) {
|
||||
tokio::task::yield_now().await;
|
||||
let runtime = match (self.get_runtime(), ignore_stamps) {
|
||||
(None, _) | (_, false) => self.buftime_to_runtime(time),
|
||||
(Some(runtime), true) => runtime,
|
||||
};
|
||||
trace!(
|
||||
" - Sending vid frame at time {} ({:?} Expect: {:?})",
|
||||
time,
|
||||
Duration::from_micros(runtime as u64),
|
||||
self.get_runtime().map(|i| Duration::from_micros(i as u64))
|
||||
);
|
||||
|
||||
let gst_buf = {
|
||||
let mut gst_buf =
|
||||
gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
|
||||
let time = ClockTime::from_useconds(
|
||||
runtime.try_into().unwrap(),
|
||||
);
|
||||
gst_buf_mut.set_dts(time);
|
||||
gst_buf_mut.set_pts(time);
|
||||
let mut gst_buf_data =
|
||||
gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(buf.as_slice());
|
||||
}
|
||||
gst_buf
|
||||
};
|
||||
buffers_ref.add(gst_buf);
|
||||
}
|
||||
}
|
||||
buffers
|
||||
};
|
||||
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
// debug!(" - Pushing buffer: {}", buffers.len());
|
||||
appsrc
|
||||
.push_buffer_list(buffers.copy())
|
||||
.map(|_| ())
|
||||
.map_err(|_| anyhow!("Could not push buffer to appsrc"))
|
||||
})
|
||||
.await;
|
||||
match &res {
|
||||
Err(e) => {
|
||||
debug!("Paniced on send buffer list: {:?}", e);
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
debug!("Failed to send buffer list: {:?}", e);
|
||||
}
|
||||
Ok(Ok(_)) => {}
|
||||
};
|
||||
res??;
|
||||
for buf in buffers.drain(..) {
|
||||
let buf_app = match (buf, self.vid.as_ref(), self.aud.as_ref()) {
|
||||
(Buffer::Video(buf), Some(app), _) => Some((buf, app.clone())),
|
||||
(Buffer::Audio(buf), _, Some(app)) => Some((buf, app.clone())),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((buf, appsrc)) = buf_app {
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
appsrc
|
||||
.push_buffer(buf.copy())
|
||||
.map(|_| ())
|
||||
.map_err(|_| anyhow!("Could not push buffer to appsrc"))
|
||||
})
|
||||
.await;
|
||||
match &res {
|
||||
Err(e) => {
|
||||
debug!("Paniced on send buffer list: {:?}", e);
|
||||
}
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
},
|
||||
async {
|
||||
if !aud_buffers.is_empty() {
|
||||
if let Some(appsrc) = self.aud.clone() {
|
||||
let buffers = {
|
||||
let mut buffers = gstreamer::BufferList::new_sized(aud_buffers.len());
|
||||
{
|
||||
let buffers_ref = buffers.get_mut().unwrap();
|
||||
for (time, buf) in aud_buffers.drain(..) {
|
||||
tokio::task::yield_now().await;
|
||||
let runtime = match (self.get_runtime(), ignore_stamps) {
|
||||
(None, _) | (_, false) => self.buftime_to_runtime(time),
|
||||
(Some(runtime), true) => runtime,
|
||||
};
|
||||
|
||||
let gst_buf = {
|
||||
let mut gst_buf =
|
||||
gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
|
||||
let time = ClockTime::from_useconds(
|
||||
runtime.try_into().unwrap(),
|
||||
);
|
||||
gst_buf_mut.set_dts(time);
|
||||
gst_buf_mut.set_pts(time);
|
||||
let mut gst_buf_data =
|
||||
gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(buf.as_slice());
|
||||
}
|
||||
gst_buf
|
||||
};
|
||||
buffers_ref.add(gst_buf);
|
||||
}
|
||||
}
|
||||
buffers
|
||||
};
|
||||
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
appsrc
|
||||
.push_buffer_list(buffers.copy())
|
||||
.map(|_| ())
|
||||
.map_err(|_| anyhow!("Could not push buffer to appsrc"))
|
||||
})
|
||||
.await;
|
||||
match &res {
|
||||
Err(e) => {
|
||||
debug!("Paniced on send buffer list: {:?}", e);
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
debug!("Failed to send buffer list: {:?}", e);
|
||||
}
|
||||
Ok(Ok(_)) => {}
|
||||
};
|
||||
res??;
|
||||
Ok(Err(e)) => {
|
||||
debug!("Failed to send buffer list: {:?}", e);
|
||||
}
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
Ok(Ok(_)) => {}
|
||||
};
|
||||
res??;
|
||||
}
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -363,7 +363,11 @@ impl NeoRtspServerImpl {
|
||||
match self.medias.write().await.entry(key.clone()) {
|
||||
Entry::Occupied(_occ) => {}
|
||||
Entry::Vacant(vac) => {
|
||||
let media = NeoMediaFactory::new(config.buffer_size, config.use_smoothing);
|
||||
let media = NeoMediaFactory::new(
|
||||
config.buffer_size,
|
||||
config.use_smoothing,
|
||||
config.use_splash,
|
||||
);
|
||||
let thread_media = media.clone();
|
||||
self.threads
|
||||
.write()
|
||||
|
||||
@@ -25,6 +25,7 @@ pub(super) struct NeoMediaShared {
|
||||
pub(super) buffer_ready: AtomicBool,
|
||||
pub(super) buffer_size: AtomicUsize,
|
||||
pub(super) use_smoothing: AtomicBool,
|
||||
pub(super) splash: AtomicBool,
|
||||
}
|
||||
|
||||
impl Default for NeoMediaShared {
|
||||
@@ -36,6 +37,7 @@ impl Default for NeoMediaShared {
|
||||
buffer_ready: AtomicBool::new(false),
|
||||
buffer_size: AtomicUsize::new(100),
|
||||
use_smoothing: AtomicBool::new(false),
|
||||
splash: AtomicBool::new(true),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,4 +58,12 @@ impl NeoMediaShared {
|
||||
pub(super) fn set_use_smoothing(&self, new_value: bool) {
|
||||
self.use_smoothing.store(new_value, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(super) fn get_use_splash(&self) -> bool {
|
||||
self.splash.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(super) fn set_use_splash(&self, new_value: bool) {
|
||||
self.splash.store(new_value, Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
+7
-3
@@ -174,10 +174,14 @@ async fn camera_main(camera: Camera<Disconnected>) -> Result<(), CameraFailureKi
|
||||
.await
|
||||
.with_context(|| format!("{}: Could not login to camera", name))
|
||||
.map_err(|e| {
|
||||
let e_inner = e.downcast_ref::<neolink_core::Error>().unwrap();
|
||||
let e_inner = e.downcast_ref::<neolink_core::Error>();
|
||||
match e_inner {
|
||||
neolink_core::Error::CameraLoginFail => CameraFailureKind::Fatal(e),
|
||||
_ => CameraFailureKind::Retry(e),
|
||||
Some(neolink_core::Error::CameraLoginFail) => CameraFailureKind::Fatal(e),
|
||||
Some(_) => CameraFailureKind::Retry(e),
|
||||
None => {
|
||||
// Timout error usually
|
||||
CameraFailureKind::Retry(e)
|
||||
}
|
||||
}
|
||||
})?;
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// This state has formed the TCP/UDP tunnel
|
||||
// but has not logged in
|
||||
use super::{camera::Camera, disconnected::Disconnected, loggedin::LoggedIn};
|
||||
use crate::utils::timeout;
|
||||
use anyhow::Result;
|
||||
|
||||
use neolink_core::bc_protocol::{BcCamera, MaxEncryption};
|
||||
@@ -28,7 +29,7 @@ impl Camera<Connected> {
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
|
||||
self.state.camera.login_with_maxenc(max_encryption).await?;
|
||||
timeout(self.state.camera.login_with_maxenc(max_encryption)).await??;
|
||||
Ok(Camera {
|
||||
shared: self.shared,
|
||||
state: LoggedIn {
|
||||
|
||||
+9
-3
@@ -13,6 +13,13 @@ use std::{
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
pub(crate) fn timeout<F>(future: F) -> tokio::time::Timeout<F>
|
||||
where
|
||||
F: std::future::Future,
|
||||
{
|
||||
tokio::time::timeout(tokio::time::Duration::from_secs(5), future)
|
||||
}
|
||||
|
||||
pub(crate) enum AddressOrUid {
|
||||
Address(String),
|
||||
Uid(String, DiscoveryMethods),
|
||||
@@ -133,10 +140,9 @@ pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result<Bc
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera
|
||||
.login_with_maxenc(max_encryption)
|
||||
timeout(camera.login_with_maxenc(max_encryption))
|
||||
.await
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))??;
|
||||
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
|
||||
Reference in new issue
Block a user