Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78a6401b16 |
No files matched your search
@@ -1,13 +0,0 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: qesoul
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -62,4 +62,4 @@ jobs:
|
||||
uses: nebularg/actions-luacheck@v1
|
||||
with:
|
||||
files: 'dissector/baichuan.lua'
|
||||
args: --globals Dissector Proto ProtoField base ByteArray DESEGMENT_ONE_MORE_SEGMENT DissectorTable Pref
|
||||
args: --globals Dissector Proto ProtoField base ByteArray DESEGMENT_ONE_MORE_SEGMENT DissectorTable
|
||||
Generated
+506
-460
File diff suppressed because it is too large.
Load diff
+4
-7
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "neolink"
|
||||
description = "A standards-compliant bridge to Reolink IP cameras"
|
||||
version = "0.5.18"
|
||||
version = "0.5.12"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
@@ -13,7 +13,6 @@ members = [
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.70"
|
||||
base64 = "0.21.2"
|
||||
byte-slice-cast = "1.2.2"
|
||||
clap = { version = "4.2.2", features = ["derive", "cargo"] }
|
||||
console-subscriber = "0.1.8"
|
||||
@@ -24,16 +23,14 @@ gstreamer = "0.20.3"
|
||||
gstreamer-app = "0.20.0"
|
||||
gstreamer-rtsp = "0.20.0"
|
||||
gstreamer-rtsp-server = { version = "0.20.3", features = ["v1_16"] }
|
||||
heck = "0.4.1"
|
||||
is_sorted = "0.1.1"
|
||||
itertools = "0.11.0"
|
||||
itertools = "0.10.5"
|
||||
lazy_static = "1.4.0"
|
||||
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
|
||||
neolink_core = { path = "crates/core", version = "0.5.18" }
|
||||
neolink_core = { path = "crates/core", version = "0.5.12" }
|
||||
regex = "1.7.3"
|
||||
rumqttc = "0.22.0"
|
||||
rumqttc = "0.20.0"
|
||||
serde = { version = "1.0.160", features = ["derive"] }
|
||||
serde_json = "1.0.96"
|
||||
time = "0.3.20"
|
||||
tokio = { version = "1.27.0", features = ["rt-multi-thread", "macros", "io-util", "tracing"] }
|
||||
tokio-stream = "0.1.12"
|
||||
|
||||
+1
-2
@@ -54,8 +54,7 @@ RUN apt-get update && \
|
||||
gstreamer1.0-x \
|
||||
gstreamer1.0-plugins-base \
|
||||
gstreamer1.0-plugins-good \
|
||||
gstreamer1.0-plugins-bad \
|
||||
gstreamer1.0-libav && \
|
||||
gstreamer1.0-plugins-bad && \
|
||||
apt-get clean -y && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=build \
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# Neolink
|
||||
|
||||

|
||||
[](https://deps.rs/repo/github/QuantumEntangledAndy/neolink)
|
||||
|
||||
Neolink is a small program that acts as a proxy between Reolink IP cameras and
|
||||
normal RTSP clients.
|
||||
@@ -32,7 +31,7 @@ features not yet in upstream master.
|
||||
|
||||
**Minor Features**:
|
||||
|
||||
- Improved error messages when missing gstreamer plugins
|
||||
- Improved error messages when your missing gstreamer plugins
|
||||
- Protocol more closely follows offical reolink format
|
||||
- Possibly can handle more simulatenous connections
|
||||
- More ways to connect to the camera. Including Relaying through reolink
|
||||
@@ -94,7 +93,7 @@ uid = "BCDEF0123456789A"
|
||||
address = "192.168.1.10"
|
||||
```
|
||||
|
||||
Create a text file called `neolink.toml` in the same folder as the
|
||||
Create a text file with called `neolink.toml` in the same folder as the
|
||||
neolink binary. With your config options.
|
||||
|
||||
When ready start `neolink` with the following command
|
||||
@@ -115,20 +114,20 @@ The IP is discovered with four methods
|
||||
the local network if there is a camera with this UID. This only works if
|
||||
the network supports broadcasts
|
||||
|
||||
If you know the ip address you can put it into the `address` field of the
|
||||
If you know the ip address you can put it into the `address` field of the
|
||||
config and attempt a direct connection without broadcasts. This requires a
|
||||
route from neolink to the camera.
|
||||
|
||||
2. Remote discovery: Here we ask the reolink servers what the IP address is.
|
||||
2. Remote discovery: Here a ask the reolink servers what the IP address is.
|
||||
This requires that we contact reolink and provide some basic information
|
||||
like the UID. Once we have this information we connect directly to the
|
||||
local IP address. This requires a route from neolink to the camera and
|
||||
for the camera to be able to contact reolink.
|
||||
for the camera to be able to contact the reolink IPs.
|
||||
|
||||
3. Map discovery: In this case we register our IP address with reolink and ask
|
||||
the camera to connect to us. Once the camera either polls/recieves a connect
|
||||
request from the reolink servers the camera will initiate a connection
|
||||
to neolink. This requires that our IP and reolink are reachable from
|
||||
the camera to connect to us. Once the camera either polls/recives a connect
|
||||
request from the reolink servers the camera will then initiate a connect
|
||||
to neolink. This requires that our IP and the reolink IPs are reacable from
|
||||
the camera.
|
||||
|
||||
4. Relay: In this case we request that reolink relay our connection. Neolink
|
||||
@@ -155,11 +154,9 @@ 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 need to adjust your config file as such:
|
||||
To use mqtt you will to adjust your config file as such:
|
||||
|
||||
```toml
|
||||
bind = "0.0.0.0"
|
||||
@@ -194,8 +191,7 @@ Control messages:
|
||||
- `/control/ptz [up|down|left|right|in|out] (amount)` Control the PTZ
|
||||
movements, amount defaults to 32.0
|
||||
- `/control/ptz/preset [id]` Move the camera to a PTZ preset
|
||||
- `/control/ptz/assign [id] [name]` Set the current PTZ position to a preset ID
|
||||
and name
|
||||
- `/control/ptz/assign [id] [name]` Set the current PTZ position to a preset ID and name
|
||||
- `/control/pir [on|off]`
|
||||
|
||||
Status Messages:
|
||||
@@ -205,16 +201,10 @@ Status Messages:
|
||||
- `/status disconnected` Sent when the camera goes offline
|
||||
- `/status/battery` Sent in reply to a `/query/battery` an XML encoded version
|
||||
of the battery status
|
||||
- `/status/battery_level` A simple % value of current battery level
|
||||
- `/status/pir` Sent in reply to a `/query/pir` an XML encoded version of the
|
||||
pir status
|
||||
- `/status/motion` Contains the motion detection alarm status. `on` for motion
|
||||
and `off` for still
|
||||
- `/status/ptz/preset` Sent in reply to a `/query/ptz/preset` an XML encoded
|
||||
version of the PTZ presets
|
||||
- `/status/preview` a base64 encoded camera image updated every 0.5s. Not
|
||||
every camera supports the snapshot command needed for this. In such cases
|
||||
there will be no `/status/preview` message.
|
||||
- `/status/ptz/preset` Sent in reply to a `/query/ptz/preset` an XML encoded version of the
|
||||
PTZ presets
|
||||
|
||||
Query Messages:
|
||||
|
||||
@@ -222,59 +212,6 @@ Query Messages:
|
||||
- `/query/pir` Request that the camera reports its pir status
|
||||
- `/query/ptz/preset` Request that the camera reports its PTZ presets
|
||||
|
||||
### MQTT Disable Features
|
||||
|
||||
Certain features like preview and motion detection may not be desired
|
||||
you can disable them 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. Not every camera supports the snapshot command needed for
|
||||
this. In such cases there will be no `/status/preview` message.
|
||||
- `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:
|
||||
@@ -301,8 +238,8 @@ Then start the rtsp server as usual:
|
||||
|
||||
### Battery Levels
|
||||
|
||||
If you have a battery camera and would like to see the battery messages in the
|
||||
log, add the following to your config
|
||||
If you have a battery camera and would like to see the battery messages in th
|
||||
log add the following to your config
|
||||
|
||||
```toml
|
||||
[[cameras]]
|
||||
@@ -310,8 +247,8 @@ log, add the following to your config
|
||||
print_format = "Human"
|
||||
```
|
||||
|
||||
You can also print into xml format with `print_format = "Xml"` which can then
|
||||
be passed by a script for processing.
|
||||
You can also print into xml format with `print_format = "Xml"` which can then b
|
||||
passed by a script for processing.
|
||||
|
||||
### Docker
|
||||
|
||||
@@ -327,8 +264,7 @@ docker pull quantumentangledandy/neolink
|
||||
# --network host is only needed if you require to connect
|
||||
# via local broadcasts. If you can connect via any other
|
||||
# method then normal bridge mode should work fine
|
||||
# and you can ommit this option. Not all OSes support
|
||||
# network=host, notably macos lacks this option.
|
||||
# and you can ommit this option
|
||||
docker run --network host --volume=$PWD/config.toml:/etc/neolink.toml quantumentangledandy/neolink
|
||||
```
|
||||
|
||||
@@ -346,11 +282,6 @@ the camera from the config to save the image from.
|
||||
File is always jpeg and the extension given in filepath will be added or changed
|
||||
to reflect this.
|
||||
|
||||
Some cameras do not support the SNAP command that is used to generate the image
|
||||
on the camera. If this is the case with your camera you can try the
|
||||
`--use-stream` option which will instead create a jpeg by transcoding the video
|
||||
stream.
|
||||
|
||||
## License
|
||||
|
||||
Neolink is free software, released under the GNU Affero General Public License
|
||||
@@ -358,9 +289,3 @@ v3.
|
||||
|
||||
This means that if you incorporate it into a piece of software available over
|
||||
the network, you must offer that software's source code to your users.
|
||||
|
||||
# Donations
|
||||
|
||||
If you find this code helpful please consider supporting development.
|
||||
|
||||
[](https://ko-fi.com/G2G5HOYIZ)
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "neolink_core"
|
||||
description = "Core services and structure for Reolink IP cameras"
|
||||
version = "0.5.18"
|
||||
version = "0.5.12"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
@@ -13,7 +13,7 @@ cfb-mode = "0.8.2"
|
||||
cookie-factory = "0.3.2"
|
||||
crc32fast = "1.3.2"
|
||||
crossbeam-channel = "0.5.8"
|
||||
delegate = "0.10.0"
|
||||
delegate = "0.9.0"
|
||||
err-derive = "0.3.1"
|
||||
futures = "0.3.28"
|
||||
get_if_addrs = "0.5.3"
|
||||
|
||||
@@ -15,12 +15,6 @@ pub(crate) struct BcCodex {
|
||||
}
|
||||
|
||||
impl BcCodex {
|
||||
pub(crate) fn new_with_debug(credentials: Credentials) -> Self {
|
||||
let mut context = BcContext::new(credentials);
|
||||
|
||||
context.debug_on();
|
||||
Self { context }
|
||||
}
|
||||
pub(crate) fn new(credentials: Credentials) -> Self {
|
||||
Self {
|
||||
context: BcContext::new(credentials),
|
||||
@@ -35,9 +29,7 @@ impl Encoder<Bc> for BcCodex {
|
||||
// let context = self.context.read().unwrap();
|
||||
let buf: Vec<u8> = Default::default();
|
||||
let enc_protocol: EncryptionProtocol = match self.context.get_encrypted() {
|
||||
EncryptionProtocol::Aes(_) | EncryptionProtocol::FullAes(_)
|
||||
if item.meta.msg_id == 1 =>
|
||||
{
|
||||
EncryptionProtocol::Aes(_) if item.meta.msg_id == 1 => {
|
||||
// During login the encyption protocol cannot go higher than BCEncrypt
|
||||
// even if we support AES. (BUt it can go lower i.e. None)
|
||||
EncryptionProtocol::BCEncrypt
|
||||
@@ -121,9 +113,6 @@ impl Decoder for BcCodex {
|
||||
0x02 => self.context.set_encrypted(EncryptionProtocol::Aes(
|
||||
self.context.credentials.make_aeskey(nonce),
|
||||
)),
|
||||
0x12 => self.context.set_encrypted(EncryptionProtocol::FullAes(
|
||||
self.context.credentials.make_aeskey(nonce),
|
||||
)),
|
||||
_ => {
|
||||
return Err(Error::UnknownEncryption(encryption_protocol_byte));
|
||||
}
|
||||
|
||||
+19
-48
@@ -113,15 +113,8 @@ fn bc_modern_msg<'a>(
|
||||
};
|
||||
|
||||
let mut in_binary = false;
|
||||
let mut encrypted_len = None;
|
||||
// Now we'll take the buffer that Nom gave a ref to and parse it.
|
||||
let extension = if ext_len > 0 {
|
||||
if context.debug {
|
||||
println!(
|
||||
"Extension Txt: {:?}",
|
||||
String::from_utf8(processed_ext_buf.to_vec()).unwrap_or("Not Text".to_string())
|
||||
);
|
||||
}
|
||||
// Apply the XML parse function, but throw away the reference to decrypted in the Ok and
|
||||
// Err case. This error-error-error thing is the same idiom Nom uses internally.
|
||||
let parsed = Extension::try_parse(processed_ext_buf).map_err(|_| {
|
||||
@@ -133,13 +126,11 @@ fn bc_modern_msg<'a>(
|
||||
})?;
|
||||
if let Extension {
|
||||
binary_data: Some(1),
|
||||
encrypt_len,
|
||||
..
|
||||
} = parsed
|
||||
{
|
||||
// In binary so tell the current context that we need to treat the payload as binary
|
||||
in_binary = true;
|
||||
encrypted_len = encrypt_len;
|
||||
}
|
||||
Some(parsed)
|
||||
} else {
|
||||
@@ -158,23 +149,22 @@ fn bc_modern_msg<'a>(
|
||||
msg_id: 1,
|
||||
response_code,
|
||||
..
|
||||
} if (response_code >> 8) & 0xff == 0xdd => {
|
||||
// 0xdd means we are setting the encryption method
|
||||
// Durig login, the max encryption is BcEncrypt since
|
||||
// the nonce has not been exchanged yet
|
||||
match response_code & 0xff {
|
||||
0x00 => EncryptionProtocol::Unencrypted,
|
||||
_ => EncryptionProtocol::BCEncrypt,
|
||||
}
|
||||
}
|
||||
BcHeader { msg_id: 1, .. } => {
|
||||
match *context.get_encrypted() {
|
||||
EncryptionProtocol::Aes(_) | EncryptionProtocol::FullAes(_) => {
|
||||
// During login max is BcEncrypt
|
||||
EncryptionProtocol::BCEncrypt
|
||||
}
|
||||
n => n,
|
||||
}
|
||||
} if (response_code & 0xff) == 0x00 => EncryptionProtocol::Unencrypted,
|
||||
BcHeader {
|
||||
msg_id: 1,
|
||||
response_code,
|
||||
..
|
||||
} if (response_code & 0xff) == 0x01 => EncryptionProtocol::BCEncrypt,
|
||||
BcHeader {
|
||||
msg_id: 1,
|
||||
response_code,
|
||||
..
|
||||
} if (response_code & 0xff) == 0x02 => EncryptionProtocol::BCEncrypt, // This is AES but the first packet with the NONCE is BCEcrypt, since the NONCE in this packet is required to build the AES key
|
||||
BcHeader { msg_id: 1, .. }
|
||||
if matches!(context.get_encrypted(), EncryptionProtocol::Aes(_)) =>
|
||||
{
|
||||
// Maximum encryption level is BCEncrypt during login... Not sure why Reolink did it like that
|
||||
EncryptionProtocol::BCEncrypt
|
||||
}
|
||||
_ => *context.get_encrypted(),
|
||||
};
|
||||
@@ -182,25 +172,8 @@ fn bc_modern_msg<'a>(
|
||||
let processed_payload_buf =
|
||||
xml_crypto::decrypt(header.channel_id as u32, payload_buf, &encryption_protocol);
|
||||
if context.in_bin_mode.contains(&(header.msg_num)) || in_binary {
|
||||
payload = match (context.get_encrypted(), encrypted_len) {
|
||||
(EncryptionProtocol::FullAes(_), Some(encrypted_len)) => {
|
||||
// if if context.debug {
|
||||
// log::trace!("Binary: {:X?}", &processed_payload_buf[0..30]);
|
||||
// }
|
||||
Some(BcPayloads::Binary(
|
||||
processed_payload_buf[0..(encrypted_len as usize)].to_vec(),
|
||||
))
|
||||
}
|
||||
_ => Some(BcPayloads::Binary(payload_buf.to_vec())),
|
||||
};
|
||||
payload = Some(BcPayloads::Binary(payload_buf.to_vec()));
|
||||
} else {
|
||||
if context.debug {
|
||||
println!(
|
||||
"Payload Txt: {:?}",
|
||||
String::from_utf8(processed_payload_buf.to_vec())
|
||||
.unwrap_or("Not Text".to_string())
|
||||
);
|
||||
}
|
||||
let xml = BcXml::try_parse(processed_payload_buf.as_slice()).map_err(|_| {
|
||||
error!("header.msg_id: {}", header.msg_id);
|
||||
error!(
|
||||
@@ -224,10 +197,8 @@ fn bc_modern_msg<'a>(
|
||||
}
|
||||
|
||||
fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> {
|
||||
let (buf, _magic) = error_context(
|
||||
"Magic invalid",
|
||||
verify(le_u32, |x| *x == MAGIC_HEADER || *x == MAGIC_HEADER_REV),
|
||||
)(buf)?;
|
||||
let (buf, _magic) =
|
||||
error_context("Magic invalid", verify(le_u32, |x| *x == MAGIC_HEADER))(buf)?;
|
||||
let (buf, msg_id) = error_context("MsgID missing", le_u32)(buf)?;
|
||||
let (buf, body_len) = error_context("BodyLen missing", le_u32)(buf)?;
|
||||
let (buf, channel_id) = error_context("ChannelID missing", le_u8)(buf)?;
|
||||
|
||||
@@ -3,11 +3,7 @@ use crate::Credentials;
|
||||
pub use super::xml::{BcPayloads, BcXml, Extension};
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(super) const MAGIC_HEADER: u32 = 0x0abcdef0;
|
||||
/// Sometimes will get the BE magic header even though all other numbers are LE?
|
||||
/// Seems to happens with certain messages like snap that produce jpegs, so perhaps it
|
||||
/// it is meant to be a hint as to the endianess of the binary payload
|
||||
pub(super) const MAGIC_HEADER_REV: u32 = 0x0fedcba0;
|
||||
pub(super) const MAGIC_HEADER: u32 = 0xabcdef0;
|
||||
|
||||
/// Login messages have this ID
|
||||
pub const MSG_ID_LOGIN: u32 = 1;
|
||||
@@ -37,8 +33,6 @@ pub const MSG_ID_VERSION: u32 = 80;
|
||||
pub const MSG_ID_PING: u32 = 93;
|
||||
/// General system info messages have this ID
|
||||
pub const MSG_ID_GET_GENERAL: u32 = 104;
|
||||
/// Snapshot to get a jpeg image
|
||||
pub const MSG_ID_SNAP: u32 = 109;
|
||||
/// Used to get the abilities of a user
|
||||
pub const MSG_ID_ABILITY_INFO: u32 = 151;
|
||||
/// Setting general system info (clock mostly) messages have this ID
|
||||
@@ -128,8 +122,6 @@ pub enum LegacyMsg {
|
||||
/// Password for a legacy login
|
||||
password: String,
|
||||
},
|
||||
/// Sent to upgrade to modern and not exposed the MD5 username/password
|
||||
LoginUpgrade,
|
||||
/// Any other type of legacy message will be collected here
|
||||
UnknownMsg,
|
||||
}
|
||||
@@ -200,9 +192,6 @@ pub enum EncryptionProtocol {
|
||||
/// Latest cameras/firmwares use Aes with the key derived from
|
||||
/// the camera's password and the negotiated NONCE
|
||||
Aes([u8; 16]),
|
||||
/// Same as Aes but the media stream is also encrypted and not just
|
||||
/// the control commands
|
||||
FullAes([u8; 16]),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -210,7 +199,6 @@ pub(crate) struct BcContext {
|
||||
pub(crate) credentials: Credentials,
|
||||
pub(crate) in_bin_mode: HashSet<u16>,
|
||||
pub(crate) encryption_protocol: EncryptionProtocol,
|
||||
pub(crate) debug: bool,
|
||||
}
|
||||
|
||||
impl Bc {
|
||||
@@ -252,7 +240,6 @@ impl BcContext {
|
||||
credentials,
|
||||
in_bin_mode: HashSet::new(),
|
||||
encryption_protocol: EncryptionProtocol::Unencrypted,
|
||||
debug: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,7 +249,6 @@ impl BcContext {
|
||||
credentials: Default::default(),
|
||||
in_bin_mode: HashSet::new(),
|
||||
encryption_protocol,
|
||||
debug: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,10 +268,6 @@ impl BcContext {
|
||||
pub(crate) fn binary_off(&mut self, msg_id: u16) {
|
||||
self.in_bin_mode.remove(&msg_id);
|
||||
}
|
||||
|
||||
pub(crate) fn debug_on(&mut self) {
|
||||
self.debug = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl BcHeader {
|
||||
|
||||
@@ -130,10 +130,6 @@ fn bc_legacy<W: Write>(legacy: &'_ LegacyMsg) -> impl SerializeFn<W> + '_ {
|
||||
slice(&[0u8; 1772][..]),
|
||||
))(out)
|
||||
}
|
||||
LoginUpgrade => {
|
||||
// Write nothing as it is header only
|
||||
slice(&[])(out)
|
||||
}
|
||||
UnknownMsg => {
|
||||
panic!("Cannot serialize an unknown message!");
|
||||
}
|
||||
|
||||
@@ -97,9 +97,6 @@ pub struct BcXml {
|
||||
/// Recieved on request for a link type
|
||||
#[yaserde(rename = "LinkType")]
|
||||
pub link_type: Option<LinkType>,
|
||||
/// Recieved AND send for the snap message
|
||||
#[yaserde(rename = "Snap")]
|
||||
pub snap: Option<Snap>,
|
||||
}
|
||||
|
||||
impl BcXml {
|
||||
@@ -259,15 +256,6 @@ pub struct Extension {
|
||||
/// The rfID used in the PIR
|
||||
#[yaserde(rename = "rfId")]
|
||||
pub rf_id: Option<u8>,
|
||||
/// Encrypted binary has this to verify successful decryption
|
||||
#[yaserde(rename = "checkPos")]
|
||||
pub check_pos: Option<u32>,
|
||||
/// Encrypted binary has this to verify successful decryption
|
||||
#[yaserde(rename = "checkValue")]
|
||||
pub check_value: Option<u32>,
|
||||
/// Used in newer encrypted payload packets
|
||||
#[yaserde(rename = "encryptLen")]
|
||||
pub encrypt_len: Option<u32>,
|
||||
}
|
||||
|
||||
impl Default for Extension {
|
||||
@@ -279,9 +267,6 @@ impl Default for Extension {
|
||||
token: None,
|
||||
channel_id: None,
|
||||
rf_id: None,
|
||||
check_pos: None,
|
||||
check_value: None,
|
||||
encrypt_len: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -564,9 +549,6 @@ pub struct AlarmEvent {
|
||||
pub channel_id: u8,
|
||||
/// Motion status. Known values are `"MD"` or `"none"`
|
||||
pub status: String,
|
||||
/// AI status. Known values are `"people"` or `"none"`
|
||||
#[yaserde(rename = "AItype")]
|
||||
pub ai_type: Option<String>,
|
||||
/// The recording status. Known values `0` or `1`
|
||||
pub recording: i32,
|
||||
/// The timestamp associated with the recording. `0` if not recording
|
||||
@@ -718,37 +700,7 @@ pub struct AbilityInfoSubModule {
|
||||
pub struct LinkType {
|
||||
#[yaserde(rename = "type")]
|
||||
/// Type of connection known values `"LAN"`
|
||||
pub link_type: String,
|
||||
}
|
||||
|
||||
/// The Link Type contains the type of connection present
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct Snap {
|
||||
#[yaserde(rename = "channelId")]
|
||||
/// The channel id to get the snapshot from
|
||||
pub channel_id: u8,
|
||||
/// Unknown, observed values: 0
|
||||
/// value is only set on request
|
||||
#[yaserde(rename = "logicChannel")]
|
||||
pub logic_channel: Option<u8>,
|
||||
/// Time of snapshot, zero when requesting
|
||||
pub time: u32,
|
||||
/// Request a full frame, observed values: 0
|
||||
/// value is only set on request
|
||||
#[yaserde(rename = "fullFrame")]
|
||||
pub full_frame: Option<u32>,
|
||||
/// Stream name, observed values: `main`, `sub`
|
||||
/// value is only set on request
|
||||
#[yaserde(rename = "streamType")]
|
||||
pub stream_type: Option<String>,
|
||||
/// File name, usually of the form `01_20230518140240.jpg`
|
||||
/// value is only set on recieve
|
||||
#[yaserde(rename = "fileName")]
|
||||
pub file_name: Option<String>,
|
||||
/// Size in bytes of the picture
|
||||
/// value is only set on recieve
|
||||
#[yaserde(rename = "pictureSize")]
|
||||
pub picture_size: Option<u32>,
|
||||
link_type: String,
|
||||
}
|
||||
|
||||
/// Convience function to return the xml version used throughout the library
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn decrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol
|
||||
.map(|(key, i)| *i ^ key ^ (offset as u8))
|
||||
.collect()
|
||||
}
|
||||
EncryptionProtocol::Aes(aeskey) | EncryptionProtocol::FullAes(aeskey) => {
|
||||
EncryptionProtocol::Aes(aeskey) => {
|
||||
// AES decryption
|
||||
|
||||
let mut decrypted = buf.to_vec();
|
||||
@@ -41,7 +41,7 @@ pub fn encrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol
|
||||
// Encrypt is the same as decrypt
|
||||
decrypt(offset, buf, encryption_protocol)
|
||||
}
|
||||
EncryptionProtocol::Aes(aeskey) | EncryptionProtocol::FullAes(aeskey) => {
|
||||
EncryptionProtocol::Aes(aeskey) => {
|
||||
// AES encryption
|
||||
let mut encrypted = buf.to_vec();
|
||||
Aes128CfbEnc::new(aeskey.into(), IV.into()).encrypt(&mut encrypted);
|
||||
|
||||
+67
-130
@@ -27,7 +27,6 @@ mod pirstate;
|
||||
mod ptz;
|
||||
mod reboot;
|
||||
mod resolution;
|
||||
mod snap;
|
||||
mod stream;
|
||||
mod talk;
|
||||
mod time;
|
||||
@@ -85,10 +84,10 @@ pub struct BcCameraOpt {
|
||||
pub protocol: ConnectionProtocol,
|
||||
/// Discovery method to allow
|
||||
pub discovery: DiscoveryMethods,
|
||||
/// Printing format for auxilaary data such as battery levels
|
||||
pub aux_printing: PrintFormat,
|
||||
/// Credentials for login
|
||||
pub credentials: Credentials,
|
||||
/// Toggle debug print of underlying data
|
||||
pub debug: bool,
|
||||
}
|
||||
|
||||
/// Used to choose the print format of various status messages like battery levels
|
||||
@@ -126,7 +125,6 @@ impl BcCamera {
|
||||
/// Try to connect to the camera via appropaite methods and return
|
||||
/// the location that should be used
|
||||
async fn find_camera(options: &BcCameraOpt) -> Result<CameraLocation> {
|
||||
let discovery = Discovery::new().await?;
|
||||
if let ConnectionProtocol::Tcp | ConnectionProtocol::TcpUdp = options.protocol {
|
||||
let mut sockets = vec![];
|
||||
match options.port {
|
||||
@@ -146,7 +144,7 @@ impl BcCamera {
|
||||
info!("{}: Trying TCP discovery", options.name);
|
||||
for socket in sockets.drain(..) {
|
||||
let channel_id: u8 = options.channel_id;
|
||||
if let Ok(addr) = discovery.check_tcp(socket, channel_id).await.map(|_| {
|
||||
if let Ok(addr) = Discovery::check_tcp(socket, channel_id).await.map(|_| {
|
||||
info!("{}: TCP Discovery success at {:?}", options.name, &socket);
|
||||
socket
|
||||
}) {
|
||||
@@ -185,112 +183,62 @@ impl BcCamera {
|
||||
DiscoveryMethods::Debug => (false, false, false, true),
|
||||
};
|
||||
|
||||
let res = tokio::select! {
|
||||
Ok(v) = async {
|
||||
let uid_local = uid.clone();
|
||||
info!("{}: Trying local discovery", options.name);
|
||||
let result = discovery.local(&uid_local, Some(sockets)).await;
|
||||
match result {
|
||||
Ok(disc) => {
|
||||
info!(
|
||||
"{}: Local discovery success {} at {}",
|
||||
options.name,
|
||||
uid_local,
|
||||
disc.get_addr()
|
||||
);
|
||||
Ok(CameraLocation::Udp(disc))
|
||||
},
|
||||
Err(e) => Err(e)
|
||||
}
|
||||
}, if allow_local => Ok(v),
|
||||
Ok(v) = async {
|
||||
let mut discovery = Discovery::new().await?;
|
||||
let reg_result;
|
||||
// Registration is looped as it seems that reolink
|
||||
// only updates the registration lazily when someone attempts
|
||||
// to connect. The first few connects fails until the server data
|
||||
// is updated
|
||||
//
|
||||
// We loop infinitly and allow the caller to timeout at the
|
||||
// interval they desire
|
||||
let mut retry = 0;
|
||||
const MAX_RETRY: usize = 10;
|
||||
loop {
|
||||
tokio::task::yield_now().await;
|
||||
if let Ok(result) = discovery.get_registration(uid).await {
|
||||
reg_result = result;
|
||||
break;
|
||||
}
|
||||
if retry >= MAX_RETRY {
|
||||
return Err(Error::DiscoveryTimeout);
|
||||
}
|
||||
log::info!("{}: Registration with reolink servers failed. Retrying: {}/{}", options.name, retry + 1, MAX_RETRY);
|
||||
retry += 1;
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
|
||||
// New discovery to get new client IDs
|
||||
discovery = Discovery::new().await?;
|
||||
};
|
||||
tokio::select! {
|
||||
Ok(v) = async {
|
||||
let uid_remote = uid.clone();
|
||||
info!("{}: Trying remote discovery", options.name);
|
||||
let result = discovery
|
||||
.remote(&uid_remote, ®_result)
|
||||
.await;
|
||||
match result {
|
||||
Ok(disc) => {
|
||||
info!(
|
||||
"{}: Remote discovery success {} at {}",
|
||||
options.name,
|
||||
uid_remote,
|
||||
disc.get_addr()
|
||||
);
|
||||
Ok(CameraLocation::Udp(disc))
|
||||
},
|
||||
Err(e) => Err(e)
|
||||
}
|
||||
}, if allow_remote => Ok(v),
|
||||
Ok(v) = async {
|
||||
let uid_map = uid.clone();
|
||||
info!("{}: Trying map discovery", options.name);
|
||||
let result = discovery.map(®_result).await;
|
||||
match result {
|
||||
Ok(disc) => {
|
||||
info!(
|
||||
"{}: Map success {} at {}",
|
||||
options.name,
|
||||
uid_map,
|
||||
disc.get_addr()
|
||||
);
|
||||
Ok(CameraLocation::Udp(disc))
|
||||
},
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}, if allow_map => Ok(v),
|
||||
Ok(v) = async {
|
||||
let uid_relay = uid.clone();
|
||||
info!("{}: Trying relay discovery", options.name);
|
||||
let result = discovery.relay(®_result).await;
|
||||
match result {
|
||||
Ok(disc) => {
|
||||
info!(
|
||||
"{}: Relay success {} at {}",
|
||||
options.name,
|
||||
uid_relay,
|
||||
disc.get_addr()
|
||||
);
|
||||
Ok(CameraLocation::Udp(disc))
|
||||
},
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}, if allow_relay => Ok(v),
|
||||
else => Err(Error::DiscoveryTimeout),
|
||||
}
|
||||
}, if allow_remote || allow_map || allow_relay => Ok(v),
|
||||
else => Err(Error::DiscoveryTimeout),
|
||||
}?;
|
||||
|
||||
return Ok(res);
|
||||
if allow_local {
|
||||
let uid_local = uid.clone();
|
||||
info!("{}: Trying local discovery", options.name);
|
||||
let result = Discovery::local(&uid_local, Some(sockets)).await;
|
||||
if let Ok(disc) = result {
|
||||
info!(
|
||||
"{}: Local discovery success {} at {}",
|
||||
options.name,
|
||||
uid_local,
|
||||
disc.get_addr()
|
||||
);
|
||||
return Ok(CameraLocation::Udp(disc));
|
||||
}
|
||||
}
|
||||
if allow_remote {
|
||||
let uid_remote = uid.clone();
|
||||
info!("{}: Trying remote discovery", options.name);
|
||||
let result = Discovery::remote(&uid_remote).await;
|
||||
if let Ok(disc) = result {
|
||||
info!(
|
||||
"{}: Remote discovery success {} at {}",
|
||||
options.name,
|
||||
uid_remote,
|
||||
disc.get_addr()
|
||||
);
|
||||
return Ok(CameraLocation::Udp(disc));
|
||||
}
|
||||
}
|
||||
if allow_map {
|
||||
let uid_map = uid.clone();
|
||||
info!("{}: Trying map discovery", options.name);
|
||||
let result = Discovery::map(&uid_map).await;
|
||||
if let Ok(disc) = result {
|
||||
info!(
|
||||
"{}: Map success {} at {}",
|
||||
options.name,
|
||||
uid_map,
|
||||
disc.get_addr()
|
||||
);
|
||||
return Ok(CameraLocation::Udp(disc));
|
||||
}
|
||||
}
|
||||
if allow_relay {
|
||||
let uid_relay = uid.clone();
|
||||
info!("{}: Trying relay discovery", options.name);
|
||||
let result = Discovery::relay(&uid_relay).await;
|
||||
if let Ok(disc) = result {
|
||||
info!(
|
||||
"{}: Relay success {} at {}",
|
||||
options.name,
|
||||
uid_relay,
|
||||
disc.get_addr()
|
||||
);
|
||||
return Ok(CameraLocation::Udp(disc));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info!("{}: Discovery failed", options.name);
|
||||
@@ -316,20 +264,16 @@ impl BcCamera {
|
||||
let (sink, source): (BcConnSink, BcConnSource) = {
|
||||
match BcCamera::find_camera(options).await? {
|
||||
CameraLocation::Tcp(addr) => {
|
||||
let (x, r) = TcpSource::new(addr, &username, passwd.as_ref(), options.debug)
|
||||
let (x, r) = TcpSource::new(addr, &username, passwd.as_ref())
|
||||
.await?
|
||||
.split();
|
||||
(Box::new(x), Box::new(r))
|
||||
}
|
||||
CameraLocation::Udp(discovery) => {
|
||||
let (x, r) = UdpSource::new_from_discovery(
|
||||
discovery,
|
||||
&username,
|
||||
passwd.as_ref(),
|
||||
options.debug,
|
||||
)
|
||||
.await?
|
||||
.split();
|
||||
let (x, r) =
|
||||
UdpSource::new_from_discovery(discovery, &username, passwd.as_ref())
|
||||
.await?
|
||||
.split();
|
||||
(Box::new(x), Box::new(r))
|
||||
}
|
||||
}
|
||||
@@ -347,6 +291,9 @@ impl BcCamera {
|
||||
abilities: Default::default(),
|
||||
};
|
||||
me.keepalive().await?;
|
||||
if let Err(e) = me.monitor_battery(options.aux_printing).await {
|
||||
warn!("Could not monitor battery: {:?}", e);
|
||||
}
|
||||
Ok(me)
|
||||
}
|
||||
|
||||
@@ -408,16 +355,6 @@ impl BcCamera {
|
||||
pub async fn join(&self) -> Result<()> {
|
||||
self.connection.join().await
|
||||
}
|
||||
|
||||
/// Disconnect from the camera. This is done by dropping the reciever
|
||||
/// so further communications are not possible.
|
||||
pub async fn disconnect(self) -> Result<()> {
|
||||
let connection = Arc::try_unwrap(self.connection)
|
||||
.map_err(|_| Error::Other("Connection still active"))?;
|
||||
connection.disconnect().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The Baichuan library has a very peculiar behavior where it always zeros the last byte. I
|
||||
|
||||
@@ -7,7 +7,7 @@ impl BcCamera {
|
||||
pub async fn get_abilityinfo(&self) -> Result<AbilityInfo> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_ABILITY_INFO, msg_num).await?;
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_ABILITY_INFO,
|
||||
|
||||
@@ -83,7 +83,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(MSG_ID_BATTERY_INFO, msg_num).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
|
||||
@@ -18,11 +18,8 @@ type MsgHandler = dyn 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a
|
||||
|
||||
#[derive(Default)]
|
||||
struct Subscriber {
|
||||
/// Subscribers based on their ID and their num
|
||||
/// First filtered by ID then number
|
||||
/// If num is None it will be upgraded to a Some based on the number the
|
||||
/// camera assigns
|
||||
num: BTreeMap<u32, BTreeMap<Option<u16>, Sender<Result<Bc>>>>,
|
||||
/// Subscribers based on their Num
|
||||
num: BTreeMap<u16, Sender<Result<Bc>>>,
|
||||
/// Subscribers based on their ID
|
||||
id: BTreeMap<u32, Arc<MsgHandler>>,
|
||||
}
|
||||
@@ -58,12 +55,10 @@ impl BcConnection {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.build()
|
||||
.unwrap();
|
||||
let result = runtime.block_on(
|
||||
runtime.block_on(
|
||||
PollSender::new(thread_poll_commander)
|
||||
.send_all(&mut source.map(|bc| Ok(PollCommand::Bc(Box::new(bc))))),
|
||||
);
|
||||
log::info!("PollSender Bc {:?}", result);
|
||||
result
|
||||
)
|
||||
});
|
||||
rx_thread.spawn(async move {
|
||||
handle.await??;
|
||||
@@ -90,12 +85,12 @@ impl BcConnection {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn subscribe(&self, msg_id: u32, msg_num: u16) -> Result<BcSubscription> {
|
||||
pub async fn subscribe(&self, msg_num: u16) -> Result<BcSubscription> {
|
||||
let (tx, rx) = channel(100);
|
||||
self.poll_commander
|
||||
.send(PollCommand::AddSubscriber(msg_id, Some(msg_num), tx))
|
||||
.send(PollCommand::AddSubscriber(msg_num, tx))
|
||||
.await?;
|
||||
Ok(BcSubscription::new(rx, Some(msg_num as u32), self))
|
||||
Ok(BcSubscription::new(rx, msg_num as u32, self))
|
||||
}
|
||||
|
||||
/// Some messages are initiated by the camera. This creates a handler for them
|
||||
@@ -120,21 +115,6 @@ impl BcConnection {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Some times we want to wait for a reply on a new message ID
|
||||
/// to do this we wait for the next packet with a certain ID
|
||||
/// grab it's message ID and then subscribe to that ID
|
||||
///
|
||||
/// The command Snap that grabs a jpeg payload is an example of this
|
||||
///
|
||||
/// This function creates a temporary handle to grab this single message
|
||||
pub async fn subscribe_to_id(&self, msg_id: u32) -> Result<BcSubscription> {
|
||||
let (tx, rx) = channel(100);
|
||||
self.poll_commander
|
||||
.send(PollCommand::AddSubscriber(msg_id, None, tx))
|
||||
.await?;
|
||||
Ok(BcSubscription::new(rx, None, self))
|
||||
}
|
||||
|
||||
pub(crate) async fn join(&self) -> Result<()> {
|
||||
let mut locked_threads = self.rx_thread.write().await;
|
||||
while let Some(res) = locked_threads.join_next().await {
|
||||
@@ -152,35 +132,13 @@ impl BcConnection {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn disconnect(mut self) -> Result<()> {
|
||||
self.poll_commander.send(PollCommand::Disconnect).await?;
|
||||
drop(self.sink);
|
||||
drop(self.poll_commander);
|
||||
let locked_threads = self.rx_thread.get_mut();
|
||||
while locked_threads.join_next().await.is_some() {}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
enum PollCommand {
|
||||
Bc(Box<Result<Bc>>),
|
||||
AddHandler(u32, Arc<MsgHandler>),
|
||||
RemoveHandler(u32),
|
||||
AddSubscriber(u32, Option<u16>, Sender<Result<Bc>>),
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PollCommand {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
PollCommand::Bc(_) => f.write_str("PollCommand::Bc"),
|
||||
PollCommand::AddHandler(_, _) => f.write_str("PollCommand::AddHandler"),
|
||||
PollCommand::RemoveHandler(_) => f.write_str("PollCommand::RemoveHandler"),
|
||||
PollCommand::AddSubscriber(_, _, _) => f.write_str("PollCommand::AddSubscriber"),
|
||||
PollCommand::Disconnect => f.write_str("PollCommand::Disconnect"),
|
||||
}
|
||||
}
|
||||
AddSubscriber(u16, Sender<Result<Bc>>),
|
||||
}
|
||||
|
||||
struct Poller {
|
||||
@@ -193,116 +151,67 @@ impl Poller {
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
while let Some(command) = self.reciever.next().await {
|
||||
yield_now().await;
|
||||
// Clean Up subscribers
|
||||
self.subscribers
|
||||
.num
|
||||
.iter_mut()
|
||||
.for_each(|(_, channels)| channels.retain(|_, channel| !channel.is_closed()));
|
||||
self.subscribers
|
||||
.num
|
||||
.retain(|_, channels| !channels.is_empty());
|
||||
// Handle the command
|
||||
match command {
|
||||
PollCommand::Bc(boxed_response) => {
|
||||
match *boxed_response {
|
||||
Ok(response) => {
|
||||
let msg_id = response.meta.msg_id;
|
||||
let msg_num = response.meta.msg_num;
|
||||
log::trace!(
|
||||
"Looking for ID: {} with num: {}, in {:?} and {:?}",
|
||||
msg_id,
|
||||
msg_num,
|
||||
self.subscribers.id.keys().to_owned(),
|
||||
self.subscribers
|
||||
.num
|
||||
.iter()
|
||||
.map(|(k, v)| (k, v.keys()))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
match (
|
||||
self.subscribers.id.get(&msg_id),
|
||||
self.subscribers.num.get_mut(&msg_id), // Both filter first on 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?;
|
||||
}
|
||||
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?;
|
||||
}
|
||||
(None, Some(occ)) => {
|
||||
let sender = if let Some(sender) =
|
||||
occ.get(&Some(msg_num)).filter(|a| !a.is_closed()).cloned()
|
||||
{
|
||||
// Connection with id exists and is not closed
|
||||
Some(sender)
|
||||
} else if let Some(sender) = occ.get(&None).cloned() {
|
||||
// Upgrade a None to a known MsgID
|
||||
occ.remove(&None);
|
||||
occ.insert(Some(msg_num), sender.clone());
|
||||
Some(sender)
|
||||
} else if occ
|
||||
.get(&Some(msg_num))
|
||||
.map(|a| a.is_closed())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
// Connection is closed and there is no None to replace it
|
||||
// Remove it for cleanup and report no sender
|
||||
occ.remove(&Some(msg_num));
|
||||
None
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(sender) = sender {
|
||||
if sender.capacity() == 0 {
|
||||
warn!("Reaching limit of channel");
|
||||
warn!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
sender.capacity(),
|
||||
sender.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
} else {
|
||||
trace!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
sender.capacity(),
|
||||
sender.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
}
|
||||
if sender.send(Ok(response)).await.is_err() {
|
||||
occ.remove(&Some(msg_num));
|
||||
}
|
||||
} else {
|
||||
debug!(
|
||||
"Ignoring uninteresting message id {} (number: {})",
|
||||
msg_id, msg_num
|
||||
);
|
||||
trace!("Contents: {:?}", response);
|
||||
}
|
||||
}
|
||||
(None, None) => {
|
||||
debug!(
|
||||
"Ignoring uninteresting message id {} (number: {})",
|
||||
msg_id, msg_num
|
||||
}
|
||||
(None, Some(occ)) => {
|
||||
if occ.capacity() == 0 {
|
||||
warn!("Reaching limit of channel");
|
||||
warn!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
occ.capacity(),
|
||||
occ.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
} else {
|
||||
trace!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
occ.capacity(),
|
||||
occ.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
trace!("Contents: {:?}", response);
|
||||
}
|
||||
if occ.send(Ok(response)).await.is_err() {
|
||||
remove_it_num = true;
|
||||
}
|
||||
}
|
||||
(None, None) => {
|
||||
debug!(
|
||||
"Ignoring uninteresting message id {} (number: {})",
|
||||
msg_id, msg_num
|
||||
);
|
||||
trace!("Contents: {:?}", response);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
for sub in self.subscribers.num.values() {
|
||||
for sender in sub.values() {
|
||||
let _ = sender.send(Err(e.clone())).await;
|
||||
}
|
||||
}
|
||||
self.subscribers.num.clear();
|
||||
self.subscribers.id.clear();
|
||||
return Err(e);
|
||||
if remove_it_num {
|
||||
self.subscribers.num.remove(&msg_num);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
for sub in self.subscribers.num.values() {
|
||||
let _ = sub.send(Err(e.clone())).await;
|
||||
}
|
||||
self.subscribers.num.clear();
|
||||
self.subscribers.id.clear();
|
||||
return Err(e);
|
||||
}
|
||||
},
|
||||
PollCommand::AddHandler(msg_id, handler) => {
|
||||
match self.subscribers.id.entry(msg_id) {
|
||||
Entry::Vacant(vac_entry) => {
|
||||
@@ -316,14 +225,8 @@ impl Poller {
|
||||
PollCommand::RemoveHandler(msg_id) => {
|
||||
self.subscribers.id.remove(&msg_id);
|
||||
}
|
||||
PollCommand::AddSubscriber(msg_id, msg_num, tx) => {
|
||||
match self
|
||||
.subscribers
|
||||
.num
|
||||
.entry(msg_id)
|
||||
.or_default()
|
||||
.entry(msg_num)
|
||||
{
|
||||
PollCommand::AddSubscriber(msg_num, tx) => {
|
||||
match self.subscribers.num.entry(msg_num) {
|
||||
Entry::Vacant(vac_entry) => {
|
||||
vac_entry.insert(tx);
|
||||
}
|
||||
@@ -331,7 +234,6 @@ impl Poller {
|
||||
if occ_entry.get().is_closed() {
|
||||
occ_entry.insert(tx);
|
||||
} else {
|
||||
// log::error!("Failed to subscribe in bcconn to {:?} for {:?}", msg_num, msg_id);
|
||||
let _ = tx
|
||||
.send(Err(Error::SimultaneousSubscription { msg_num }))
|
||||
.await;
|
||||
@@ -339,9 +241,6 @@ impl Poller {
|
||||
}
|
||||
};
|
||||
}
|
||||
PollCommand::Disconnect => {
|
||||
return Err(Error::DroppedConnection);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -12,7 +12,7 @@ use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
|
||||
|
||||
pub struct BcSubscription<'a> {
|
||||
rx: ReceiverStream<Result<Bc>>,
|
||||
msg_num: Option<u32>,
|
||||
msg_num: u32,
|
||||
conn: &'a BcConnection,
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ pub type BcMediaStream<'b> = FramedRead<Compat<IntoAsyncRead<BcPayloadStream<'b>
|
||||
impl<'a> BcSubscription<'a> {
|
||||
pub fn new(
|
||||
rx: Receiver<Result<Bc>>,
|
||||
msg_num: Option<u32>,
|
||||
msg_num: u32,
|
||||
conn: &'a BcConnection,
|
||||
) -> BcSubscription<'a> {
|
||||
BcSubscription {
|
||||
@@ -100,11 +100,7 @@ impl<'a> BcSubscription<'a> {
|
||||
}
|
||||
|
||||
pub async fn send(&self, bc: Bc) -> Result<()> {
|
||||
if let Some(msg_num) = self.msg_num {
|
||||
assert!(bc.meta.msg_num as u32 == msg_num);
|
||||
} else {
|
||||
log::debug!("Sending message before msg_num has been aquired");
|
||||
}
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
self.conn.send(bc).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -112,12 +108,7 @@ impl<'a> BcSubscription<'a> {
|
||||
pub async fn recv(&mut self) -> Result<Bc> {
|
||||
let bc = self.rx.next().await.ok_or(Error::DroppedSubscriber)?;
|
||||
if let Ok(bc) = &bc {
|
||||
if let Some(msg_num) = self.msg_num {
|
||||
assert!(bc.meta.msg_num as u32 == msg_num);
|
||||
} else {
|
||||
// Leaning number now
|
||||
self.msg_num = Some(bc.meta.msg_num as u32);
|
||||
}
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
}
|
||||
bc
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::bcudp::xml::*;
|
||||
use crate::{Error, Result};
|
||||
use futures::{
|
||||
sink::SinkExt,
|
||||
stream::{FuturesUnordered, Stream, StreamExt},
|
||||
stream::{FuturesUnordered, StreamExt},
|
||||
};
|
||||
use lazy_static::lazy_static;
|
||||
use local_ip_address::local_ip;
|
||||
@@ -34,7 +34,7 @@ use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::udp::UdpFramed;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct RegisterResult {
|
||||
struct RegisterResult {
|
||||
reg: SocketAddr,
|
||||
dev: Option<SocketAddr>,
|
||||
dmap: Option<SocketAddr>,
|
||||
@@ -57,6 +57,8 @@ struct UidLookupResults {
|
||||
relay: SocketAddr,
|
||||
}
|
||||
|
||||
pub(crate) struct Discovery {}
|
||||
|
||||
const MTU: u32 = 1350;
|
||||
lazy_static! {
|
||||
static ref P2P_RELAY_HOSTNAMES: [&'static str; 10] = [
|
||||
@@ -78,14 +80,12 @@ lazy_static! {
|
||||
}
|
||||
|
||||
type Subscriber = Arc<RwLock<BTreeMap<u32, Sender<Result<(UdpDiscovery, SocketAddr)>>>>>;
|
||||
type Handlers = Arc<RwLock<Vec<Sender<Result<(UdpDiscovery, SocketAddr)>>>>>;
|
||||
type ArcFramedSocket = UdpFramed<BcUdpCodex, Arc<UdpSocket>>;
|
||||
pub(crate) struct Discoverer {
|
||||
socket: Arc<UdpSocket>,
|
||||
handle: RwLock<JoinSet<()>>,
|
||||
writer: Sender<Result<(BcUdp, SocketAddr)>>,
|
||||
subsribers: Subscriber,
|
||||
handlers: Handlers,
|
||||
local_addr: SocketAddr,
|
||||
}
|
||||
|
||||
@@ -98,27 +98,26 @@ impl Discoverer {
|
||||
let (mut writer, mut reader) = inner.split();
|
||||
let mut set = JoinSet::new();
|
||||
let subsribers: Subscriber = Default::default();
|
||||
let handlers: Handlers = Default::default();
|
||||
|
||||
let thread_subscriber = subsribers.clone();
|
||||
let thread_handlers = handlers.clone();
|
||||
set.spawn(async move {
|
||||
loop {
|
||||
tokio::task::yield_now().await;
|
||||
match reader.next().await {
|
||||
Some(Ok((BcUdp::Discovery(bcudp), addr))) => {
|
||||
let tid = bcudp.tid;
|
||||
let mut tid = bcudp.tid;
|
||||
let mut needs_removal = false;
|
||||
if let (Some(sender), true) =
|
||||
(thread_subscriber.read().await.get(&tid), tid > 0)
|
||||
{
|
||||
if let Some(sender) = thread_subscriber.read().await.get(&tid) {
|
||||
if sender.send(Ok((bcudp, addr))).await.is_err() {
|
||||
needs_removal = true;
|
||||
}
|
||||
} else {
|
||||
for sender in thread_handlers.write().await.iter_mut() {
|
||||
let _ = sender.send(Ok((bcudp.clone(), addr))).await;
|
||||
} else if let Some(any_sender) = thread_subscriber.read().await.get(&0) {
|
||||
if any_sender.send(Ok((bcudp, addr))).await.is_err() {
|
||||
tid = 0; // To make is remove 0
|
||||
needs_removal = true;
|
||||
}
|
||||
} else {
|
||||
trace!("Udp Discovery got this unexpected BcUdp {:?}", bcudp);
|
||||
}
|
||||
if needs_removal {
|
||||
thread_subscriber.write().await.remove(&tid);
|
||||
@@ -151,43 +150,35 @@ impl Discoverer {
|
||||
handle: RwLock::new(set),
|
||||
writer: sinker,
|
||||
subsribers,
|
||||
handlers,
|
||||
local_addr,
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_socket(&self) -> Arc<UdpSocket> {
|
||||
self.socket.clone()
|
||||
async fn into_socket(self) -> (Arc<UdpSocket>, JoinSet<()>) {
|
||||
let socket = self.socket.clone();
|
||||
let handle = self.handle.into_inner();
|
||||
(socket, handle)
|
||||
}
|
||||
|
||||
async fn subscribe(&self, tid: u32) -> Result<Receiver<Result<(UdpDiscovery, SocketAddr)>>> {
|
||||
if tid > 0 {
|
||||
let mut subs = self.subsribers.write().await;
|
||||
match subs.entry(tid) {
|
||||
Entry::Vacant(vacant) => {
|
||||
let mut subs = self.subsribers.write().await;
|
||||
match subs.entry(tid) {
|
||||
Entry::Vacant(vacant) => {
|
||||
let (tx, rx) = channel(10);
|
||||
vacant.insert(tx);
|
||||
Ok(rx)
|
||||
}
|
||||
Entry::Occupied(mut occ) => {
|
||||
if occ.get().is_closed() {
|
||||
let (tx, rx) = channel(10);
|
||||
vacant.insert(tx);
|
||||
occ.insert(tx);
|
||||
Ok(rx)
|
||||
}
|
||||
Entry::Occupied(mut occ) => {
|
||||
if occ.get().is_closed() {
|
||||
let (tx, rx) = channel(10);
|
||||
occ.insert(tx);
|
||||
Ok(rx)
|
||||
} else {
|
||||
// log::error!("Failed to subscribe in discovery to {:?}", tid);
|
||||
Err(Error::SimultaneousSubscription {
|
||||
msg_num: Some(tid as u16),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
Err(Error::SimultaneousSubscription {
|
||||
msg_num: (tid as u16),
|
||||
})
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// If tid is zero we listen to all!
|
||||
let mut handlers = self.handlers.write().await;
|
||||
let (tx, rx) = channel(10);
|
||||
handlers.push(tx);
|
||||
Ok(rx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,6 +214,32 @@ impl Discoverer {
|
||||
&self.local_addr
|
||||
}
|
||||
|
||||
async fn retry_send_multi<F, T>(
|
||||
&self,
|
||||
mut disc: UdpDiscovery,
|
||||
dests: &[SocketAddr],
|
||||
map: F,
|
||||
) -> Result<T>
|
||||
where
|
||||
F: Fn(UdpDiscovery, SocketAddr) -> Option<T>,
|
||||
{
|
||||
trace!("Retrying send");
|
||||
disc.tid = 0; // Must be random to avoid simulatenous subscription errors
|
||||
let mut set = FuturesUnordered::new();
|
||||
for dest in dests.iter() {
|
||||
set.push(self.retry_send(disc.clone(), *dest, &map));
|
||||
}
|
||||
|
||||
// Get what ever completes first
|
||||
while let Some(result) = set.next().await {
|
||||
trace!("Result: {}", result.is_ok());
|
||||
if let Ok(ret) = result {
|
||||
return Ok(ret);
|
||||
}
|
||||
}
|
||||
Err(Error::DiscoveryTimeout)
|
||||
}
|
||||
|
||||
async fn retry_send<F, T>(&self, mut disc: UdpDiscovery, dest: SocketAddr, map: F) -> Result<T>
|
||||
where
|
||||
F: Fn(UdpDiscovery, SocketAddr) -> Option<T>,
|
||||
@@ -340,10 +357,13 @@ impl Discoverer {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn uid_lookup_all<'a>(
|
||||
&'a self,
|
||||
uid: &'a str,
|
||||
) -> Result<impl Stream<Item = UidLookupResults> + 'a> {
|
||||
/// This function will contact the p2p relay servers
|
||||
///
|
||||
/// It will ask each of the servers for details on a specific UID
|
||||
///
|
||||
/// On success it returns the M2cQr that the p2p relay
|
||||
/// server has about the UID
|
||||
async fn uid_loopup(&self, uid: &str) -> Result<UidLookupResults> {
|
||||
let task = tokio::task::spawn_blocking(move || {
|
||||
let mut addrs = vec![];
|
||||
for p2p_relay in P2P_RELAY_HOSTNAMES.iter() {
|
||||
@@ -356,22 +376,8 @@ impl Discoverer {
|
||||
}
|
||||
addrs
|
||||
});
|
||||
let mut addrs = timeout(*MAXIMUM_WAIT, task).await??;
|
||||
let addrs = timeout(*MAXIMUM_WAIT, task).await??;
|
||||
trace!("Uid lookup to: {:?}", addrs);
|
||||
|
||||
Ok(addrs
|
||||
.drain(..)
|
||||
.map(|addr| self.uid_lookup(uid, addr))
|
||||
.collect::<FuturesUnordered<_>>()
|
||||
.filter_map(|f| async { f.ok() }))
|
||||
}
|
||||
/// This function will contact the p2p relay servers
|
||||
///
|
||||
/// It will ask each of the servers for details on a specific UID
|
||||
///
|
||||
/// On success it will returns an async iter that yields the M2cQr that the p2p relay
|
||||
/// server has about the UID
|
||||
async fn uid_lookup(&self, uid: &str, addr: SocketAddr) -> Result<UidLookupResults> {
|
||||
let msg = UdpDiscovery {
|
||||
tid: 0,
|
||||
payload: UdpXml {
|
||||
@@ -384,7 +390,7 @@ impl Discoverer {
|
||||
};
|
||||
trace!("Sending look up {:?}", msg);
|
||||
let (packet, _) = self
|
||||
.retry_send(msg, addr, |bc, addr| match bc {
|
||||
.retry_send_multi(msg, addrs.as_slice(), |bc, addr| match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
@@ -442,103 +448,51 @@ impl Discoverer {
|
||||
|
||||
// Send and await acceptance
|
||||
let (sid, dev, dmap, relay) = self
|
||||
.retry_send(msg, lookup.reg, |bc, socket| {
|
||||
trace!("{}", socket.ip());
|
||||
match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
r2c_c_r:
|
||||
Some(R2cCr {
|
||||
dmap,
|
||||
dev,
|
||||
relay,
|
||||
sid,
|
||||
rsp,
|
||||
..
|
||||
}),
|
||||
..
|
||||
},
|
||||
} if (dev
|
||||
.as_ref()
|
||||
.map(|d| !d.ip.is_empty() && d.port > 0)
|
||||
.unwrap_or(false)
|
||||
|| dmap
|
||||
.as_ref()
|
||||
.map(|d| !d.ip.is_empty() && d.port > 0)
|
||||
.unwrap_or(false)
|
||||
|| relay
|
||||
.as_ref()
|
||||
.map(|d| !d.ip.is_empty() && d.port > 0)
|
||||
.unwrap_or(false))
|
||||
&& rsp != -1 =>
|
||||
{
|
||||
Some(Ok((sid, dev, dmap, relay)))
|
||||
}
|
||||
// UdpDiscovery {
|
||||
// tid: _,
|
||||
// payload:
|
||||
// UdpXml {
|
||||
// r2c_c_r:
|
||||
// Some(R2cCr {
|
||||
// dmap,
|
||||
// dev,
|
||||
// relay: Some(mut relay),
|
||||
// sid,
|
||||
// rsp,
|
||||
// ..
|
||||
// }),
|
||||
// ..
|
||||
// },
|
||||
// } if (dev
|
||||
// .as_ref()
|
||||
// .map(|d| !d.ip.is_empty() && d.port > 0)
|
||||
// .unwrap_or(false)
|
||||
// || dmap
|
||||
// .as_ref()
|
||||
// .map(|d| !d.ip.is_empty() && d.port > 0)
|
||||
// .unwrap_or(false)
|
||||
// || (relay.ip == format!("{}", socket.ip()) && relay.port == 0))
|
||||
// && rsp != -1 =>
|
||||
// {
|
||||
// // For a relay connection if port is 0 and the ip is the current socker addr
|
||||
// // we use the current port
|
||||
// relay.port = socket.port();
|
||||
// Some(Ok((sid, dev, dmap, Some(relay))))
|
||||
// }
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
r2c_c_r:
|
||||
Some(R2cCr {
|
||||
dev,
|
||||
dmap,
|
||||
relay,
|
||||
rsp,
|
||||
..
|
||||
}),
|
||||
..
|
||||
},
|
||||
} if (dev
|
||||
.as_ref()
|
||||
.map(|d| !d.ip.is_empty() && d.port > 0)
|
||||
.unwrap_or(false)
|
||||
|| dmap
|
||||
.as_ref()
|
||||
.map(|d| !d.ip.is_empty() && d.port > 0)
|
||||
.unwrap_or(false)
|
||||
|| relay
|
||||
.as_ref()
|
||||
.map(|d| !d.ip.is_empty() && d.port > 0)
|
||||
.unwrap_or(false))
|
||||
&& rsp == -1 =>
|
||||
{
|
||||
Some(Err(Error::RegisterError))
|
||||
}
|
||||
_ => None,
|
||||
.retry_send(msg, lookup.reg, |bc, _| match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
r2c_c_r:
|
||||
Some(R2cCr {
|
||||
dmap,
|
||||
dev,
|
||||
relay,
|
||||
sid,
|
||||
rsp,
|
||||
..
|
||||
}),
|
||||
..
|
||||
},
|
||||
} if (dev.as_ref().map(|d| !d.ip.is_empty()).unwrap_or(false)
|
||||
|| dmap.as_ref().map(|d| !d.ip.is_empty()).unwrap_or(false)
|
||||
|| relay.as_ref().map(|d| !d.ip.is_empty()).unwrap_or(false))
|
||||
&& rsp != -1 =>
|
||||
{
|
||||
Some(Ok((sid, dev, dmap, relay)))
|
||||
}
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
r2c_c_r:
|
||||
Some(R2cCr {
|
||||
dev,
|
||||
dmap,
|
||||
relay,
|
||||
rsp,
|
||||
..
|
||||
}),
|
||||
..
|
||||
},
|
||||
} if (dev.as_ref().map(|d| !d.ip.is_empty()).unwrap_or(false)
|
||||
|| dmap.as_ref().map(|d| !d.ip.is_empty()).unwrap_or(false)
|
||||
|| relay.as_ref().map(|d| !d.ip.is_empty()).unwrap_or(false))
|
||||
&& rsp == -1 =>
|
||||
{
|
||||
Some(Err(Error::RegisterError))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await??;
|
||||
|
||||
@@ -985,56 +939,15 @@ impl Discoverer {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Discovery {
|
||||
discoverer: Discoverer,
|
||||
client_id: i32,
|
||||
}
|
||||
|
||||
impl Discovery {
|
||||
pub(crate) async fn new() -> Result<Self> {
|
||||
Ok(Self {
|
||||
discoverer: Discoverer::new().await?,
|
||||
client_id: generate_cid(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn get_registration(&self, uid: &str) -> Result<RegisterResult> {
|
||||
let lookups = self.discoverer.uid_lookup_all(uid).await?;
|
||||
|
||||
let reg_result = Box::pin(
|
||||
lookups
|
||||
.then(|lookup| {
|
||||
let discoverer = &self.discoverer;
|
||||
let client_id = self.client_id;
|
||||
async move {
|
||||
trace!("lookup: {:?}", lookup);
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await;
|
||||
trace!("reg_result: {:?}", reg_result);
|
||||
reg_result
|
||||
}
|
||||
})
|
||||
.filter_map(|f| async { f.ok() }),
|
||||
)
|
||||
.next()
|
||||
.await
|
||||
.ok_or(Error::Other(
|
||||
"No reolink registers returned valid device data.",
|
||||
))?;
|
||||
|
||||
Ok(reg_result)
|
||||
}
|
||||
|
||||
// Check if TCP is possible
|
||||
//
|
||||
// To do this we send a dummy login and see if it replies with any BC packet
|
||||
pub(crate) async fn check_tcp(&self, addr: SocketAddr, channel_id: u8) -> Result<()> {
|
||||
pub(crate) async fn check_tcp(addr: SocketAddr, channel_id: u8) -> Result<()> {
|
||||
let username = "admin";
|
||||
let password = Some("123456");
|
||||
let mut tcp_source = timeout(
|
||||
*MAXIMUM_WAIT,
|
||||
TcpSource::new(addr, username, password, false),
|
||||
)
|
||||
.await??;
|
||||
let mut tcp_source =
|
||||
timeout(*MAXIMUM_WAIT, TcpSource::new(addr, username, password)).await??;
|
||||
|
||||
let md5_username = md5_string(username, Md5Trunc::ZeroLast);
|
||||
let md5_password = password
|
||||
@@ -1066,17 +979,18 @@ impl Discovery {
|
||||
|
||||
// Perform UDP broadcast lookup and connection
|
||||
pub(crate) async fn local(
|
||||
&self,
|
||||
uid: &str,
|
||||
mut optional_addrs: Option<Vec<SocketAddr>>,
|
||||
) -> Result<DiscoveryResult> {
|
||||
let discoverer = Discoverer::new().await?;
|
||||
|
||||
let client_id = generate_cid();
|
||||
let mut dests = get_broadcasts(&[2015, 2018])?;
|
||||
if let Some(mut optional_addrs) = optional_addrs.take() {
|
||||
trace!("Also sending to {:?}", optional_addrs);
|
||||
dests.append(&mut optional_addrs);
|
||||
}
|
||||
let discoverer_ref = &self.discoverer;
|
||||
let client_id = self.client_id;
|
||||
let discoverer_ref = &discoverer;
|
||||
let mut futures = FuturesUnordered::new();
|
||||
for addr in dests.iter().copied() {
|
||||
futures.push(async move {
|
||||
@@ -1104,9 +1018,10 @@ impl Discovery {
|
||||
drop(futures);
|
||||
// drop(discoverer_ref);
|
||||
|
||||
let socket = self.discoverer.get_socket().await;
|
||||
let (socket, keep_alive_tasks) = discoverer.into_socket().await;
|
||||
Ok(DiscoveryResult {
|
||||
socket,
|
||||
keep_alive_tasks,
|
||||
addr: connect_result.addr,
|
||||
camera_id: connect_result.camera_id,
|
||||
client_id: connect_result.client_id,
|
||||
@@ -1124,22 +1039,33 @@ impl Discovery {
|
||||
// This method is best when broadcasts are not possible but we can contact the camera
|
||||
// directly
|
||||
#[allow(unused)]
|
||||
pub(crate) async fn remote(
|
||||
&self,
|
||||
uid: &str,
|
||||
reg_result: &RegisterResult,
|
||||
) -> Result<DiscoveryResult> {
|
||||
pub(crate) async fn remote(uid: &str) -> Result<DiscoveryResult> {
|
||||
trace!("Start remote");
|
||||
let mut discoverer = Discoverer::new().await?;
|
||||
|
||||
let client_id = generate_cid();
|
||||
trace!("client_id: {}", client_id);
|
||||
|
||||
let lookup = discoverer.uid_loopup(uid).await?;
|
||||
trace!("lookup: {:?}", lookup);
|
||||
let reg_addr = lookup.reg;
|
||||
let relay_addr = lookup.relay;
|
||||
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
|
||||
trace!("reg_result: {:?}", reg_result);
|
||||
|
||||
let connect_result = tokio::select! {
|
||||
v = self.discoverer.client_initiated_dev(reg_result) => {v},
|
||||
v = self.discoverer.device_initiated_dev(reg_result) => {v},
|
||||
v = discoverer.client_initiated_dev(®_result) => {v},
|
||||
v = discoverer.device_initiated_dev(®_result) => {v},
|
||||
}?;
|
||||
trace!("connect_result: {:?}", connect_result);
|
||||
let socket = self.discoverer.get_socket().await;
|
||||
|
||||
let (socket, keep_alive_tasks) = discoverer.into_socket().await;
|
||||
Ok(DiscoveryResult {
|
||||
socket,
|
||||
keep_alive_tasks,
|
||||
addr: connect_result.addr,
|
||||
client_id: self.client_id,
|
||||
client_id,
|
||||
camera_id: connect_result.camera_id,
|
||||
})
|
||||
}
|
||||
@@ -1152,15 +1078,27 @@ impl Discovery {
|
||||
//
|
||||
// This method should be used when the camera is behind a NAT or firewall but we are
|
||||
// reachable
|
||||
pub(crate) async fn map(&self, reg_result: &RegisterResult) -> Result<DiscoveryResult> {
|
||||
let connect_result = self.discoverer.device_initiated_map(reg_result).await?;
|
||||
pub(crate) async fn map(uid: &str) -> Result<DiscoveryResult> {
|
||||
let discoverer = Discoverer::new().await?;
|
||||
|
||||
let client_id = generate_cid();
|
||||
trace!("client_id: {}", client_id);
|
||||
|
||||
let lookup = discoverer.uid_loopup(uid).await?;
|
||||
trace!("lookup: {:?}", lookup);
|
||||
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
|
||||
trace!("reg_result: {:?}", reg_result);
|
||||
|
||||
let connect_result = discoverer.device_initiated_map(®_result).await?;
|
||||
trace!("connect_result: {:?}", connect_result);
|
||||
|
||||
let socket = self.discoverer.get_socket().await;
|
||||
let (socket, keep_alive_tasks) = discoverer.into_socket().await;
|
||||
Ok(DiscoveryResult {
|
||||
socket,
|
||||
keep_alive_tasks,
|
||||
addr: connect_result.addr,
|
||||
client_id: self.client_id,
|
||||
client_id,
|
||||
camera_id: connect_result.camera_id,
|
||||
})
|
||||
}
|
||||
@@ -1170,15 +1108,27 @@ impl Discovery {
|
||||
// This method should work if all else fails but it will require
|
||||
// us to trust reolink with our data once more...
|
||||
//
|
||||
pub(crate) async fn relay(&self, reg_result: &RegisterResult) -> Result<DiscoveryResult> {
|
||||
let connect_result = self.discoverer.client_initiated_relay(reg_result).await?;
|
||||
pub(crate) async fn relay(uid: &str) -> Result<DiscoveryResult> {
|
||||
let discoverer = Discoverer::new().await?;
|
||||
let client_id = generate_cid();
|
||||
|
||||
trace!("client_id: {}", client_id);
|
||||
|
||||
let lookup = discoverer.uid_loopup(uid).await?;
|
||||
trace!("lookup: {:?}", lookup);
|
||||
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
|
||||
trace!("reg_result: {:?}", reg_result);
|
||||
|
||||
let connect_result = discoverer.client_initiated_relay(®_result).await?;
|
||||
trace!("connect_result: {:?}", connect_result);
|
||||
|
||||
let socket = self.discoverer.get_socket().await;
|
||||
let (socket, keep_alive_tasks) = discoverer.into_socket().await;
|
||||
Ok(DiscoveryResult {
|
||||
socket,
|
||||
keep_alive_tasks,
|
||||
addr: connect_result.addr,
|
||||
client_id: self.client_id,
|
||||
client_id,
|
||||
camera_id: connect_result.camera_id,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//!
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::{net::UdpSocket, task::JoinSet};
|
||||
|
||||
mod bcconn;
|
||||
mod bcsub;
|
||||
@@ -22,11 +22,16 @@ pub(crate) use self::{
|
||||
pub(crate) struct DiscoveryResult {
|
||||
socket: Arc<UdpSocket>,
|
||||
addr: SocketAddr,
|
||||
keep_alive_tasks: JoinSet<()>,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
}
|
||||
|
||||
impl DiscoveryResult {
|
||||
/// Stop all keep alive and any remaining tasks that the discover is managing
|
||||
pub(crate) async fn shutdown(&mut self) {
|
||||
self.keep_alive_tasks.shutdown().await;
|
||||
}
|
||||
/// Get the address discovered
|
||||
pub(crate) fn get_addr(&self) -> &SocketAddr {
|
||||
&self.addr
|
||||
|
||||
@@ -18,17 +18,11 @@ impl TcpSource {
|
||||
addr: SocketAddr,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
debug: bool,
|
||||
) -> Result<TcpSource> {
|
||||
let stream = connect_to(addr).await?;
|
||||
|
||||
let codex = if debug {
|
||||
BcCodex::new_with_debug(Credentials::new(username, password))
|
||||
} else {
|
||||
BcCodex::new(Credentials::new(username, password))
|
||||
};
|
||||
Ok(Self {
|
||||
inner: Framed::new(stream, codex),
|
||||
inner: Framed::new(stream, BcCodex::new(Credentials::new(username, password))),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,21 +9,20 @@ use futures::{
|
||||
sink::{Sink, SinkExt},
|
||||
stream::{IntoAsyncRead, Stream, StreamExt, TryStreamExt},
|
||||
};
|
||||
use log::*;
|
||||
use rand::{seq::SliceRandom, thread_rng};
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::VecDeque;
|
||||
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::sync::mpsc::channel;
|
||||
use tokio::{
|
||||
net::UdpSocket,
|
||||
time::{interval, sleep, Duration, Instant, Interval, Sleep},
|
||||
time::{interval, Duration, Interval},
|
||||
};
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
|
||||
use tokio_util::sync::PollSender;
|
||||
use tokio_util::{
|
||||
codec::{Decoder, Encoder, Framed},
|
||||
udp::UdpFramed,
|
||||
@@ -44,23 +43,19 @@ impl UdpSource {
|
||||
camera_id: i32,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
debug: bool,
|
||||
) -> Result<Self> {
|
||||
let stream = Arc::new(connect().await?);
|
||||
|
||||
Self::new_from_socket(
|
||||
stream, addr, client_id, camera_id, username, password, debug,
|
||||
)
|
||||
.await
|
||||
Self::new_from_socket(stream, addr, client_id, camera_id, username, password).await
|
||||
}
|
||||
pub(crate) async fn new_from_discovery<T: Into<String>, U: Into<String>>(
|
||||
discovery: DiscoveryResult,
|
||||
mut discovery: DiscoveryResult,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
debug: bool,
|
||||
) -> Result<Self> {
|
||||
// Ensure that the discovery keep alive are all stopped here
|
||||
// We now handle all coms in UdpSource
|
||||
discovery.shutdown().await;
|
||||
Self::new_from_socket(
|
||||
discovery.socket,
|
||||
discovery.addr,
|
||||
@@ -68,7 +63,6 @@ impl UdpSource {
|
||||
discovery.camera_id,
|
||||
username,
|
||||
password,
|
||||
debug,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -80,17 +74,14 @@ impl UdpSource {
|
||||
camera_id: i32,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
debug: bool,
|
||||
) -> Result<Self> {
|
||||
let bcudp_source = BcUdpSource::new_from_socket(stream, addr).await?;
|
||||
let payload_source = bcudp_source.into_payload_source(client_id, camera_id).await;
|
||||
let payload_source = bcudp_source.into_payload_source(client_id, camera_id);
|
||||
let async_read = payload_source.into_async_read().compat();
|
||||
let codex = if debug {
|
||||
BcCodex::new_with_debug(Credentials::new(username, password))
|
||||
} else {
|
||||
BcCodex::new(Credentials::new(username, password))
|
||||
};
|
||||
let framed = Framed::new(async_read, codex);
|
||||
let framed = Framed::new(
|
||||
async_read,
|
||||
BcCodex::new(Credentials::new(username, password)),
|
||||
);
|
||||
|
||||
Ok(Self { inner: framed })
|
||||
}
|
||||
@@ -161,12 +152,20 @@ impl BcUdpSource {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn into_payload_source(
|
||||
self,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
) -> UdpPayloadSource {
|
||||
UdpPayloadSource::new(self, client_id, camera_id).await
|
||||
pub(crate) fn into_payload_source(self, client_id: i32, camera_id: i32) -> UdpPayloadSource {
|
||||
UdpPayloadSource {
|
||||
inner: self,
|
||||
client_id,
|
||||
camera_id,
|
||||
packets_sent: 0,
|
||||
packets_want: 0,
|
||||
sent: Default::default(),
|
||||
recieved: Default::default(),
|
||||
state: State::Normal,
|
||||
send_buffer: Default::default(),
|
||||
ack_interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms
|
||||
resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,7 +199,6 @@ impl Sink<(BcUdp, SocketAddr)> for BcUdpSource {
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
enum State {
|
||||
Normal, // Normal recieve
|
||||
Flushing, // Used to send ack packets and things in the buffer
|
||||
@@ -208,72 +206,16 @@ enum State {
|
||||
YieldNow, // Used to ensure we rest between polling packets so as to not starve the runtime
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct AckLatency {
|
||||
current_values: Vec<u32>,
|
||||
last_recieve_time: Option<Instant>,
|
||||
display_value: u32,
|
||||
last_display_time: Option<Instant>,
|
||||
}
|
||||
|
||||
impl AckLatency {
|
||||
/// Used to get the current latency, in thd way that the official
|
||||
/// client does. This is a value that seems to be updated only every second
|
||||
/// Observed values are `0`, `54785`, `55062`, `2528`,
|
||||
fn get_value(&self) -> u32 {
|
||||
self.display_value
|
||||
}
|
||||
|
||||
/// Used to updaet the average latency calculation
|
||||
fn feed_ack(&mut self) {
|
||||
// Update the last recieve time
|
||||
let now = Instant::now();
|
||||
if let Some(last_recieve_time) = self.last_recieve_time {
|
||||
let diff = (now - last_recieve_time).as_micros();
|
||||
self.current_values.push(diff as u32);
|
||||
self.last_recieve_time = Some(now);
|
||||
} else {
|
||||
self.last_recieve_time = Some(now);
|
||||
}
|
||||
|
||||
// Update the display_value
|
||||
// this is done only ever 1s
|
||||
if let Some(last_display_time) = self.last_display_time {
|
||||
if now - last_display_time > Duration::from_secs(1) {
|
||||
// A second has passed update this
|
||||
self.last_display_time = Some(now);
|
||||
let current_values_count = self.current_values.len() as u32;
|
||||
let current_value = self
|
||||
.current_values
|
||||
.iter()
|
||||
.fold(0u32, |acc, value| acc + *value / current_values_count);
|
||||
self.current_values = vec![]; // Reset the average vec
|
||||
|
||||
self.display_value = current_value;
|
||||
}
|
||||
} else {
|
||||
// First 1s is a zero value
|
||||
self.last_display_time = Some(now);
|
||||
self.display_value = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct UdpPayloadSource {
|
||||
inner_stream: ReceiverStream<IoResult<Vec<u8>>>,
|
||||
inner_sink: PollSender<Vec<u8>>,
|
||||
}
|
||||
|
||||
struct UdpPayloadInner {
|
||||
inner: BcUdpSource,
|
||||
thread_stream: PollSender<IoResult<Vec<u8>>>,
|
||||
thread_sink: ReceiverStream<Vec<u8>>,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
packets_sent: u32,
|
||||
packets_want: u32,
|
||||
sent: BTreeMap<u32, UdpData>,
|
||||
recieved: BTreeMap<u32, Vec<u8>>,
|
||||
state: State,
|
||||
send_buffer: VecDeque<BcUdp>,
|
||||
/// Offical Client does ack every 10ms if we don't also do this the camera
|
||||
/// seems to think we have a poor connection and will abort
|
||||
/// This `ack_interval` controls how ofen we do this
|
||||
@@ -281,105 +223,9 @@ struct UdpPayloadInner {
|
||||
/// Offical Client does resend every 500ms
|
||||
/// This `resend_interval` controls how ofen we do this
|
||||
resend_interval: Interval,
|
||||
ack_latency: AckLatency,
|
||||
// Tracks the timeout of recieving ANY packet
|
||||
recv_timeout: Pin<Box<Sleep>>,
|
||||
}
|
||||
impl UdpPayloadInner {
|
||||
fn new(
|
||||
inner: BcUdpSource,
|
||||
thread_stream: PollSender<IoResult<Vec<u8>>>,
|
||||
thread_sink: ReceiverStream<Vec<u8>>,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
thread_stream,
|
||||
thread_sink,
|
||||
client_id,
|
||||
camera_id,
|
||||
packets_sent: 0,
|
||||
packets_want: 0,
|
||||
sent: Default::default(),
|
||||
recieved: Default::default(),
|
||||
ack_interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms
|
||||
resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms
|
||||
ack_latency: Default::default(),
|
||||
// A packet of ANY kind must be recieved in the last second
|
||||
// since there are 10 acks a second 3s should be fine
|
||||
recv_timeout: Box::pin(sleep(Duration::from_secs(3))),
|
||||
}
|
||||
}
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
let camera_addr = self.inner.addr;
|
||||
tokio::select! {
|
||||
_ = self.ack_interval.tick() => {
|
||||
let ack = BcUdp::Ack(self.build_send_ack());
|
||||
self.inner.feed((ack, camera_addr)).await?;
|
||||
Result::Ok(())
|
||||
},
|
||||
_ = self.resend_interval.tick() => {
|
||||
for (_, resend) in self.sent.iter() {
|
||||
self.inner.feed((BcUdp::Data(resend.clone()), camera_addr)).await?;
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
v = self.thread_sink.next() => {
|
||||
// Incomming from application
|
||||
// Outgoing on socket
|
||||
let item = v.ok_or(Error::DroppedConnection)?;
|
||||
|
||||
for chunk in item.chunks(MTU - UDPDATA_HEADER_SIZE) {
|
||||
let udp_data = UdpData {
|
||||
connection_id: self.camera_id,
|
||||
packet_id: self.packets_sent,
|
||||
payload: chunk.to_vec(),
|
||||
};
|
||||
self.packets_sent += 1;
|
||||
self.sent.insert(udp_data.packet_id, udp_data.clone());
|
||||
self.inner.feed((BcUdp::Data(udp_data), camera_addr)).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
v = self.inner.next() => {
|
||||
// Incomming from socket
|
||||
// Outgoing to application
|
||||
let (item, addr) = v.ok_or(Error::DroppedConnection)??;
|
||||
if addr == camera_addr {
|
||||
match item {
|
||||
BcUdp::Discovery(_disc) => {},
|
||||
BcUdp::Ack(ack) => {
|
||||
if ack.connection_id == self.client_id {
|
||||
self.handle_ack(ack);
|
||||
}
|
||||
},
|
||||
BcUdp::Data(data) => {
|
||||
if data.connection_id == self.client_id {
|
||||
let packet_id = data.packet_id;
|
||||
if packet_id >= self.packets_want {
|
||||
// error!("packets_want: {}", this.packets_want);
|
||||
self.recieved.insert(packet_id, data.payload);
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
self.recv_timeout.as_mut().reset(Instant::now() + Duration::from_secs(3));
|
||||
Ok(())
|
||||
},
|
||||
_ = self.recv_timeout.as_mut() => {
|
||||
Err(Error::DroppedConnection)
|
||||
}
|
||||
}?;
|
||||
while let Some(payload) = self.recieved.remove(&self.packets_want) {
|
||||
self.packets_want += 1;
|
||||
self.thread_stream.send(Ok(payload)).await?;
|
||||
}
|
||||
self.inner.flush().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl UdpPayloadSource {
|
||||
fn build_send_ack(&self) -> UdpAck {
|
||||
if self.packets_want > 0 {
|
||||
let mut first_missing: u32 = self.packets_want;
|
||||
@@ -408,7 +254,6 @@ impl UdpPayloadInner {
|
||||
connection_id: self.camera_id,
|
||||
packet_id: first_missing - 1, // Last we actually have is first_missing - 1
|
||||
group_id: 0,
|
||||
maybe_latency: self.ack_latency.get_value(),
|
||||
payload: missing_ids,
|
||||
}
|
||||
} else {
|
||||
@@ -429,41 +274,19 @@ impl UdpPayloadInner {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.ack_latency.feed_ack();
|
||||
}
|
||||
}
|
||||
impl UdpPayloadSource {
|
||||
async fn new(inner: BcUdpSource, client_id: i32, camera_id: i32) -> Self {
|
||||
let (inner_sink, thread_sink) = channel(100);
|
||||
let (thread_stream, inner_stream) = channel(100);
|
||||
|
||||
let mut payload_inner = UdpPayloadInner::new(
|
||||
inner,
|
||||
PollSender::new(thread_stream),
|
||||
ReceiverStream::new(thread_sink),
|
||||
client_id,
|
||||
camera_id,
|
||||
);
|
||||
tokio::task::spawn(async move {
|
||||
loop {
|
||||
match payload_inner.run().await {
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
// log::error!("payload_inner: {:?}", e);
|
||||
// Pass error up
|
||||
let _ = payload_inner
|
||||
.thread_stream
|
||||
.send(Err(IoError::new(ErrorKind::Other, e.clone())))
|
||||
.await;
|
||||
return Result::<()>::Err(e);
|
||||
}
|
||||
}
|
||||
fn maintanence(&mut self, cx: &mut Context<'_>) {
|
||||
// Check for periodic resends
|
||||
if self.resend_interval.poll_tick(cx).is_ready() {
|
||||
for (_, resend) in self.sent.iter() {
|
||||
self.send_buffer.push_back(BcUdp::Data(resend.clone()));
|
||||
}
|
||||
});
|
||||
|
||||
UdpPayloadSource {
|
||||
inner_stream: ReceiverStream::new(inner_stream),
|
||||
inner_sink: PollSender::new(inner_sink),
|
||||
}
|
||||
if self.ack_interval.poll_tick(cx).is_ready() {
|
||||
let ack = BcUdp::Ack(self.build_send_ack());
|
||||
self.send_buffer.push_back(ack);
|
||||
self.state = State::Flushing;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -471,16 +294,105 @@ impl UdpPayloadSource {
|
||||
impl Stream for UdpPayloadSource {
|
||||
type Item = IoResult<Vec<u8>>;
|
||||
|
||||
delegate! {
|
||||
to Pin::new(&mut self.inner_stream) {
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
|
||||
}
|
||||
}
|
||||
|
||||
delegate! {
|
||||
to self.inner_stream {
|
||||
fn size_hint(&self) -> (usize, Option<usize>);
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let camera_addr = self.inner.addr;
|
||||
let this = self.get_mut();
|
||||
match this.state {
|
||||
State::Normal => {
|
||||
// this.state = State::YieldNow;
|
||||
// Handle resend events
|
||||
this.maintanence(cx);
|
||||
// Data ready to go
|
||||
if let Some(payload) = this.recieved.remove(&this.packets_want) {
|
||||
this.packets_want += 1;
|
||||
// error!("packets_want: {}", this.packets_want);
|
||||
return Poll::Ready(Some(Ok(payload)));
|
||||
}
|
||||
// Normal behaviors
|
||||
match this.inner.poll_next_unpin(cx) {
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Data(UdpData {
|
||||
connection_id,
|
||||
packet_id,
|
||||
payload,
|
||||
}),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id
|
||||
&& addr == camera_addr
|
||||
&& packet_id >= this.packets_want =>
|
||||
{
|
||||
if packet_id == this.packets_want {
|
||||
this.packets_want += 1;
|
||||
// error!("packets_want: {}", this.packets_want);
|
||||
let ack = BcUdp::Ack(this.build_send_ack());
|
||||
this.send_buffer.push_back(ack);
|
||||
return Poll::Ready(Some(Ok(payload)));
|
||||
} else {
|
||||
this.recieved.insert(packet_id, payload);
|
||||
}
|
||||
}
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Data(UdpData {
|
||||
connection_id,
|
||||
packet_id,
|
||||
..
|
||||
}),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id
|
||||
&& addr == camera_addr
|
||||
&& packet_id < this.packets_want =>
|
||||
{
|
||||
trace!("UdpPayloadSource.RecievedPacket: Old data: {}", packet_id);
|
||||
}
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Ack(ack @ UdpAck { connection_id, .. }),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id && addr == camera_addr => {
|
||||
this.handle_ack(ack);
|
||||
// Rather then immediatly flush wait for the next call
|
||||
// this.state = State::Flushing;
|
||||
}
|
||||
Poll::Ready(Some(Err(e))) => {
|
||||
return Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e))));
|
||||
}
|
||||
Poll::Ready(None) => {
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
Poll::Pending => {
|
||||
return Poll::Pending;
|
||||
}
|
||||
Poll::Ready(Some(Ok((bcudp, addr)))) => {
|
||||
trace!(
|
||||
"UdpPayloadSource.RecievedPacker: UnexpectedData {:?} from {}",
|
||||
bcudp,
|
||||
addr
|
||||
);
|
||||
} // _ => {
|
||||
// trace!("UDPSource.RecievedPacker: Other?");
|
||||
// // Repeat/unintersting packet
|
||||
// }
|
||||
}
|
||||
}
|
||||
State::Flushing => match this.poll_flush_unpin(cx) {
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = State::Normal;
|
||||
}
|
||||
Poll::Ready(Err(e)) => {
|
||||
return Poll::Ready(Some(Err(e)));
|
||||
}
|
||||
Poll::Pending => {
|
||||
return Poll::Pending;
|
||||
}
|
||||
},
|
||||
State::Closed => {
|
||||
return Poll::Ready(Some(Err(IoError::from(ErrorKind::ConnectionAborted))));
|
||||
}
|
||||
State::YieldNow => {
|
||||
this.state = State::Normal;
|
||||
}
|
||||
}
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
@@ -491,35 +403,104 @@ impl Sink<Vec<u8>> for UdpPayloadSource {
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
self.get_mut()
|
||||
.inner_sink
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
let this = self.get_mut();
|
||||
match this.state {
|
||||
State::Normal | State::YieldNow => this
|
||||
.inner
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e)),
|
||||
State::Flushing => this
|
||||
.inner
|
||||
.poll_flush_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e)),
|
||||
State::Closed => Poll::Ready(Err(IoError::from(ErrorKind::ConnectionAborted))),
|
||||
}
|
||||
}
|
||||
fn start_send(self: Pin<&mut Self>, item: Vec<u8>) -> std::result::Result<(), Self::Error> {
|
||||
self.get_mut()
|
||||
.inner_sink
|
||||
.start_send_unpin(item)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
let this = self.get_mut();
|
||||
for chunk in item.chunks(MTU - UDPDATA_HEADER_SIZE) {
|
||||
let udp_data = UdpData {
|
||||
connection_id: this.camera_id,
|
||||
packet_id: this.packets_sent,
|
||||
payload: chunk.to_vec(),
|
||||
};
|
||||
this.packets_sent += 1;
|
||||
this.send_buffer.push_back(BcUdp::Data(udp_data));
|
||||
}
|
||||
if let Some(first) = this.send_buffer.pop_front() {
|
||||
if let BcUdp::Data(data) = &first {
|
||||
let id = data.packet_id;
|
||||
this.sent.insert(id, data.clone());
|
||||
}
|
||||
let addr = this.inner.addr;
|
||||
Pin::new(&mut this.inner)
|
||||
.start_send((first, addr))
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn poll_flush(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
self.get_mut()
|
||||
.inner_sink
|
||||
let this = self.get_mut();
|
||||
match this
|
||||
.inner
|
||||
.poll_flush_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
{
|
||||
Poll::Ready(Ok(())) => {
|
||||
if let Some(next) = this.send_buffer.pop_front() {
|
||||
match this
|
||||
.inner
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
{
|
||||
Poll::Ready(Ok(())) => {
|
||||
if let BcUdp::Data(data) = &next {
|
||||
let id = data.packet_id;
|
||||
this.sent.insert(id, data.clone());
|
||||
}
|
||||
|
||||
let addr = this.inner.addr;
|
||||
Pin::new(&mut this.inner)
|
||||
.start_send((next, addr))
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))?;
|
||||
}
|
||||
poll => {
|
||||
return poll;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
}
|
||||
poll => {
|
||||
return poll;
|
||||
}
|
||||
}
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
|
||||
fn poll_close(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
self.get_mut()
|
||||
.inner_sink
|
||||
.poll_close_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
let this = self.get_mut();
|
||||
if let State::Closed = this.state {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
match this.poll_flush_unpin(cx) {
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = State::Closed;
|
||||
this.inner
|
||||
.poll_close_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
}
|
||||
poll => poll,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -96,10 +96,10 @@ pub enum Error {
|
||||
GenError(#[error(source)] std::sync::Arc<cookie_factory::GenError>),
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once for msg_num
|
||||
#[error(display = "Simultaneous subscription, {:?}", _0)]
|
||||
#[error(display = "Simultaneous subscription, {}", _0)]
|
||||
SimultaneousSubscription {
|
||||
/// The message number that was subscribed to
|
||||
msg_num: Option<u16>,
|
||||
msg_num: u16,
|
||||
},
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once for msg_id
|
||||
|
||||
@@ -45,9 +45,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_FLOODLIGHT_MANUAL, msg_num)
|
||||
.await?;
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
@@ -79,25 +77,18 @@ impl BcCamera {
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
let msg = sub_set.recv().await?;
|
||||
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
let msg = reply?;
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the Floodlight manual state",
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the Floodlight manual state",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ impl BcCamera {
|
||||
self.has_ability_ro("ledState").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_GET_LED_STATUS, msg_num).await?;
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_LED_STATUS,
|
||||
@@ -56,7 +56,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection.subscribe(MSG_ID_SET_LED_STATUS, msg_num).await?;
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
// led_version is a field recieved from the camera but not sent
|
||||
// we set to None to ensure we don't send it to the camera
|
||||
@@ -83,25 +83,18 @@ impl BcCamera {
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
|
||||
{
|
||||
let msg = reply?;
|
||||
let msg = sub_set.recv().await?;
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the LEDState xml",
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the LEDState xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{md5_string, BcCamera, Error, Result, Truncate};
|
||||
use super::{md5_string, BcCamera, Error, Result, Truncate, ZeroLast};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
@@ -37,7 +37,7 @@ impl BcCamera {
|
||||
let credentials = self.get_credentials();
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_login = connection.subscribe(MSG_ID_LOGIN, msg_num).await?;
|
||||
let mut sub_login = connection.subscribe(msg_num).await?;
|
||||
|
||||
// Login flow is: Send legacy login message, expect back a modern message with Encryption
|
||||
// details. Then, re-send the login as a modern login message. Expect back a device info
|
||||
@@ -48,17 +48,17 @@ impl BcCamera {
|
||||
// Note: I suspect there may be a buffer overflow opportunity in the firmware since in the
|
||||
// Baichuan library, these strings are capped at 32 bytes with a null terminator. This
|
||||
// could also be a mistake in the library, the effect being it only compares 31 chars, not 32.
|
||||
// let md5_username = md5_string(&credentials.username, ZeroLast);
|
||||
// let md5_password = credentials
|
||||
// .password
|
||||
// .as_ref()
|
||||
// .map(|p| md5_string(p, ZeroLast))
|
||||
// .unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned());
|
||||
let md5_username = md5_string(&credentials.username, ZeroLast);
|
||||
let md5_password = credentials
|
||||
.password
|
||||
.as_ref()
|
||||
.map(|p| md5_string(p, ZeroLast))
|
||||
.unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned());
|
||||
|
||||
let enc_byte = match max_encryption {
|
||||
MaxEncryption::None => 0xdc00,
|
||||
MaxEncryption::BcEncrypt => 0xdc01,
|
||||
MaxEncryption::Aes => 0xdc12,
|
||||
MaxEncryption::Aes => 0xdc02,
|
||||
};
|
||||
let legacy_login = Bc {
|
||||
meta: BcMeta {
|
||||
@@ -69,7 +69,10 @@ impl BcCamera {
|
||||
response_code: enc_byte,
|
||||
class: 0x6514,
|
||||
},
|
||||
body: BcBody::LegacyMsg(LegacyMsg::LoginUpgrade),
|
||||
body: BcBody::LegacyMsg(LegacyMsg::LoginMsg {
|
||||
username: md5_username,
|
||||
password: md5_password,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_login.send(legacy_login).await?;
|
||||
|
||||
@@ -9,7 +9,7 @@ impl BcCamera {
|
||||
let credentials = self.get_credentials();
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let sub_logout = connection.subscribe(MSG_ID_LOGOUT, msg_num).await?;
|
||||
let sub_logout = connection.subscribe(msg_num).await?;
|
||||
|
||||
let username = credentials.username.clone();
|
||||
let password = credentials.password.as_ref().cloned().unwrap_or_default();
|
||||
|
||||
@@ -167,7 +167,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(MSG_ID_MOTION_REQUEST, msg_num).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_MOTION_REQUEST,
|
||||
@@ -202,7 +202,7 @@ impl BcCamera {
|
||||
/// This returns a data structure which can be used to
|
||||
/// query motion events
|
||||
pub async fn listen_on_motion(&self) -> Result<MotionData> {
|
||||
self.start_motion_query().await?;
|
||||
let msg_num = self.start_motion_query().await?;
|
||||
|
||||
let connection = self.get_connection();
|
||||
|
||||
@@ -213,7 +213,7 @@ impl BcCamera {
|
||||
let mut set = JoinSet::new();
|
||||
let channel_id = self.channel_id;
|
||||
set.spawn(async move {
|
||||
let mut sub = connection.subscribe_to_id(MSG_ID_MOTION).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
loop {
|
||||
tokio::task::yield_now().await;
|
||||
@@ -232,16 +232,10 @@ impl BcCamera {
|
||||
let mut result = MotionStatus::NoChange(Instant::now());
|
||||
for alarm_event in &alarm_event_list.alarm_events {
|
||||
if alarm_event.channel_id == channel_id {
|
||||
if alarm_event.status != "none"
|
||||
|| alarm_event
|
||||
.ai_type
|
||||
.as_ref()
|
||||
.map(|ai_type| ai_type != "none")
|
||||
.unwrap_or(false)
|
||||
{
|
||||
if alarm_event.status == "MD" {
|
||||
result = MotionStatus::Start(Instant::now());
|
||||
break;
|
||||
} else {
|
||||
} else if alarm_event.status == "none" {
|
||||
result = MotionStatus::Stop(Instant::now());
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ impl BcCamera {
|
||||
pub async fn ping(&self) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_ping = connection.subscribe(MSG_ID_PING, msg_num).await?;
|
||||
let mut sub_ping = connection.subscribe(msg_num).await?;
|
||||
|
||||
let ping = Bc {
|
||||
meta: BcMeta {
|
||||
@@ -27,7 +27,6 @@ impl BcCamera {
|
||||
|
||||
sub_ping.recv().await?;
|
||||
|
||||
log::trace!("Ping complete");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ impl BcCamera {
|
||||
loop {
|
||||
retry_interval.tick().await;
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_GET_PIR_ALARM, msg_num).await?;
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_PIR_ALARM,
|
||||
@@ -70,9 +70,7 @@ impl BcCamera {
|
||||
self.has_ability_rw("rfAlarm").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_START_PIR_ALARM, msg_num)
|
||||
.await?;
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
@@ -96,28 +94,21 @@ impl BcCamera {
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
|
||||
{
|
||||
let msg = reply?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
let msg = sub_set.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the RfAlarmCfg xml",
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the RfAlarmCfg xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ impl BcCamera {
|
||||
self.has_ability_rw("control").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection.subscribe(MSG_ID_PTZ_CONTROL, msg_num).await?;
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
let direction_str = match direction {
|
||||
Direction::Up => "up",
|
||||
@@ -88,7 +88,7 @@ impl BcCamera {
|
||||
self.has_ability_rw("control").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection.subscribe(MSG_ID_GET_PTZ_PRESET, msg_num).await?;
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
let send = Bc {
|
||||
meta: BcMeta {
|
||||
@@ -136,9 +136,7 @@ impl BcCamera {
|
||||
self.has_ability_rw("control").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_PTZ_CONTROL_PRESET, msg_num)
|
||||
.await?;
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
let preset = Preset {
|
||||
id: preset_id,
|
||||
@@ -193,9 +191,7 @@ impl BcCamera {
|
||||
self.has_ability_rw("control").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_PTZ_CONTROL_PRESET, msg_num)
|
||||
.await?;
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
let preset = Preset {
|
||||
id: preset_id,
|
||||
|
||||
@@ -7,7 +7,7 @@ impl BcCamera {
|
||||
self.has_ability_rw("reboot").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(MSG_ID_REBOOT, msg_num).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
|
||||
@@ -1,153 +0,0 @@
|
||||
// use futures::{StreamExt, TryStreamExt};
|
||||
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the snapshot image
|
||||
pub async fn get_snapshot(&self) -> Result<Vec<u8>> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_SNAP, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_SNAP,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
snap: Some(Snap {
|
||||
channel_id: self.channel_id,
|
||||
logic_channel: Some(self.channel_id),
|
||||
time: 0,
|
||||
full_frame: Some(0),
|
||||
stream_type: Some("main".to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
snap:
|
||||
Some(Snap {
|
||||
file_name: Some(filename),
|
||||
picture_size: Some(expected_size),
|
||||
..
|
||||
}),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
drop(sub_get); // Ensure that we are NOT listening on that msgnum as the reply can come on ANY msgnum
|
||||
log::trace!("Got snap XML {} with size {}", filename, expected_size);
|
||||
// Messages are now sent on ID 109 but not with the same message ID
|
||||
// preumably because the camera considers it to be a new message rather
|
||||
// than a reply
|
||||
//
|
||||
// This means we need to listen for the next 109 grab the message num and
|
||||
// subscribe to it. This is what `subscribe_to_next` is for
|
||||
let mut sub_get = connection.subscribe_to_id(MSG_ID_SNAP).await?;
|
||||
let expected_size = expected_size as usize;
|
||||
|
||||
let mut result: Vec<_> = vec![];
|
||||
log::trace!("Waiting for packets on {}", msg_num);
|
||||
let mut msg = sub_get.recv().await?;
|
||||
|
||||
while msg.meta.response_code == 200 {
|
||||
// sends 200 while more is to come
|
||||
// 201 when finished
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
extension:
|
||||
Some(Extension {
|
||||
binary_data: Some(1),
|
||||
..
|
||||
}),
|
||||
payload: Some(BcPayloads::Binary(data)),
|
||||
}) = msg.body
|
||||
{
|
||||
result.extend_from_slice(&data);
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected binary data but got something else",
|
||||
});
|
||||
}
|
||||
log::trace!(
|
||||
"Got packet size is now {} of {}",
|
||||
result.len(),
|
||||
expected_size
|
||||
);
|
||||
msg = sub_get.recv().await?;
|
||||
}
|
||||
|
||||
if msg.meta.response_code == 201 {
|
||||
// 201 means all binary data sent
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
extension:
|
||||
Some(Extension {
|
||||
binary_data: Some(1),
|
||||
..
|
||||
}),
|
||||
payload,
|
||||
}) = msg.body
|
||||
{
|
||||
if let Some(BcPayloads::Binary(data)) = payload {
|
||||
// Add last data if present (may be zero if preveious packet contained it)
|
||||
result.extend_from_slice(&data);
|
||||
}
|
||||
log::trace!(
|
||||
"Got all packets size is now {} of {}",
|
||||
result.len(),
|
||||
expected_size
|
||||
);
|
||||
if result.len() != expected_size {
|
||||
log::warn!("Snap did not recieve expected number of byes");
|
||||
}
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected binary data but got something else",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// anything else is an error
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
// let binary_stream = sub_get.payload_stream();
|
||||
// let result: Vec<_>= binary_stream
|
||||
// .map_ok(|i| tokio_stream::iter(i).map(Result::Ok))
|
||||
// .try_flatten()
|
||||
// .take(expected_size)
|
||||
// .try_collect()
|
||||
// .await?;
|
||||
log::trace!("Snapshot recieved: {} of {}", result.len(), expected_size);
|
||||
Ok(result)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected Snap xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,12 @@ use crate::{
|
||||
bcmedia::model::*,
|
||||
};
|
||||
use futures::stream::StreamExt;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
use tokio::sync::mpsc::{channel, Receiver};
|
||||
use tokio::task::{self, JoinHandle};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// The stream names supported by BC
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
@@ -30,7 +33,7 @@ pub enum StreamKind {
|
||||
pub struct StreamData {
|
||||
handle: Option<JoinHandle<Result<()>>>,
|
||||
rx: Receiver<Result<BcMedia>>,
|
||||
abort_handle: CancellationToken,
|
||||
abort_handle: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl StreamData {
|
||||
@@ -39,12 +42,12 @@ impl StreamData {
|
||||
pub async fn get_data(&mut self) -> Result<Result<BcMedia>> {
|
||||
if let Some(handle) = self.handle.as_mut() {
|
||||
if handle.is_finished() {
|
||||
self.abort_handle.cancel();
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
handle.await??;
|
||||
return Err(Error::DroppedConnection);
|
||||
}
|
||||
} else {
|
||||
self.abort_handle.cancel();
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
return Err(Error::DroppedConnection);
|
||||
}
|
||||
// debug!("StreamData: Get");
|
||||
@@ -55,26 +58,16 @@ impl StreamData {
|
||||
}
|
||||
None => {
|
||||
// debug!("StreamData: Drop");
|
||||
self.abort_handle.cancel();
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
Err(Error::DroppedConnection)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to gracefully shutdown this will cancel the background task and send
|
||||
/// the Stop command to the camera
|
||||
pub async fn shutdown(&mut self) -> Result<()> {
|
||||
self.abort_handle.cancel();
|
||||
if let Some(handle) = self.handle.take() {
|
||||
let _ = handle.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StreamData {
|
||||
fn drop(&mut self) {
|
||||
self.abort_handle.cancel();
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,7 +100,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
|
||||
let abort_handle = CancellationToken::new();
|
||||
let abort_handle = Arc::new(AtomicBool::new(false));
|
||||
let abort_handle_thread = abort_handle.clone();
|
||||
|
||||
if buffer_size == 0 {
|
||||
@@ -118,7 +111,7 @@ impl BcCamera {
|
||||
|
||||
let handle = task::spawn(async move {
|
||||
tokio::task::yield_now().await;
|
||||
let mut sub_video = connection.subscribe(MSG_ID_VIDEO, msg_num).await?;
|
||||
let mut sub_video = connection.subscribe(msg_num).await?;
|
||||
|
||||
// On an E1 and swann cameras:
|
||||
// - mainStream always has a value of 0
|
||||
@@ -193,20 +186,20 @@ impl BcCamera {
|
||||
{
|
||||
let mut media_sub = sub_video.bcmedia_stream(strict);
|
||||
|
||||
tokio::select! {
|
||||
_ = abort_handle_thread.cancelled() => {},
|
||||
_ = async {
|
||||
while let Some(bc_media) = media_sub.next().await {
|
||||
// debug!("Stream: Got");
|
||||
// We now have a complete interesting packet. Send it to on the callback
|
||||
// debug!("Stream: Send");
|
||||
if tx.send(bc_media).await.is_err() {
|
||||
// debug!("Stream: Dropped");
|
||||
break; // Connection dropped
|
||||
}
|
||||
// debug!("Stream: Sent");
|
||||
while !abort_handle_thread.load(Ordering::Relaxed) {
|
||||
// debug!("Stream: Get");
|
||||
if let Some(bc_media) = media_sub.next().await {
|
||||
// debug!("Stream: Got");
|
||||
// We now have a complete interesting packet. Send it to on the callback
|
||||
// debug!("Stream: Send");
|
||||
if tx.send(bc_media).await.is_err() {
|
||||
// debug!("Stream: Dropped");
|
||||
break; // Connection dropped
|
||||
}
|
||||
} => {}
|
||||
// debug!("Stream: Sent");
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,14 +224,13 @@ impl BcCamera {
|
||||
},
|
||||
);
|
||||
// debug!("Stream: Send Stop");
|
||||
let mut sub_stop = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?;
|
||||
sub_stop.send(stop_video).await?;
|
||||
sub_video.send(stop_video).await?;
|
||||
// debug!("Stream: Sent Stop");
|
||||
|
||||
tokio::select! {
|
||||
v = async {
|
||||
loop {
|
||||
let msg = sub_stop.recv().await?;
|
||||
let msg = sub_video.recv().await?;
|
||||
if let BcMeta {
|
||||
response_code: 200,
|
||||
msg_id: MSG_ID_VIDEO_STOP,
|
||||
@@ -276,7 +268,7 @@ impl BcCamera {
|
||||
}
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_video = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?;
|
||||
let mut sub_video = connection.subscribe(msg_num).await?;
|
||||
|
||||
// On an E1 and swann cameras:
|
||||
// - mainStream always has a value of 0
|
||||
|
||||
@@ -17,7 +17,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(MSG_ID_TALKRESET, msg_num).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
@@ -60,7 +60,7 @@ impl BcCamera {
|
||||
pub async fn talk_ability(&self) -> Result<TalkAbility> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_TALKABILITY, msg_num).await?;
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_TALKABILITY,
|
||||
@@ -120,7 +120,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(MSG_ID_TALKCONFIG, msg_num).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
if &talk_config.audio_config.audio_type != "adpcm" {
|
||||
return Err(Error::UnknownTalkEncoding);
|
||||
@@ -182,7 +182,7 @@ impl BcCamera {
|
||||
|
||||
let full_block_size = block_size + 4; // Block size + predictor state
|
||||
let msg_num = self.new_message_num();
|
||||
let sub = connection.subscribe(MSG_ID_TALK, msg_num).await?;
|
||||
let sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
const BLOCK_PER_PAYLOAD: usize = 4;
|
||||
const BLOCK_HEADER_SIZE: usize = 4;
|
||||
@@ -261,7 +261,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(MSG_ID_TALKCONFIG, msg_num).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
if &talk_config.audio_config.audio_type != "adpcm" {
|
||||
return Err(Error::UnknownTalkEncoding);
|
||||
@@ -323,7 +323,7 @@ impl BcCamera {
|
||||
|
||||
let full_block_size = block_size + 4; // Block size + predictor state
|
||||
let msg_num = self.new_message_num();
|
||||
let sub = connection.subscribe(MSG_ID_TALK, msg_num).await?;
|
||||
let sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
const BLOCK_PER_PAYLOAD: usize = 1;
|
||||
const BLOCK_HEADER_SIZE: usize = 4;
|
||||
|
||||
@@ -17,7 +17,7 @@ impl BcCamera {
|
||||
self.has_ability_ro("general").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get_general = connection.subscribe(MSG_ID_GET_GENERAL, msg_num).await?;
|
||||
let mut sub_get_general = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_GENERAL,
|
||||
@@ -102,7 +102,7 @@ impl BcCamera {
|
||||
self.has_ability_rw("general").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set_general = connection.subscribe(MSG_ID_SET_GENERAL, msg_num).await?;
|
||||
let mut sub_set_general = connection.subscribe(msg_num).await?;
|
||||
let set = Bc::new_from_xml(
|
||||
BcMeta {
|
||||
msg_id: MSG_ID_SET_GENERAL,
|
||||
|
||||
@@ -7,7 +7,7 @@ impl BcCamera {
|
||||
self.has_ability_ro("version").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_version = connection.subscribe(MSG_ID_VERSION, msg_num).await?;
|
||||
let mut sub_version = connection.subscribe(msg_num).await?;
|
||||
|
||||
let version = Bc {
|
||||
meta: BcMeta {
|
||||
|
||||
@@ -96,7 +96,7 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> {
|
||||
)(buf)?;
|
||||
let (buf, packet_id) = error_context("Missing packet_id", le_u32)(buf)?; // This is the point at which the camera has contigious
|
||||
// packets to
|
||||
let (buf, maybe_latency) = error_context("ACK: Missing Maybe Latency", le_u32)(buf)?;
|
||||
let (buf, _unknown) = error_context("ACK: Missing unknown", le_u32)(buf)?;
|
||||
let (buf, payload_size) = error_context("ACK: Missing payload_size", le_u32)(buf)?;
|
||||
let (buf, payload) = if payload_size > 0 {
|
||||
let (buf, t_payload) = take(payload_size)(buf)?; // It is a binary payload of
|
||||
@@ -113,7 +113,6 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> {
|
||||
connection_id,
|
||||
packet_id,
|
||||
group_id,
|
||||
maybe_latency,
|
||||
payload,
|
||||
};
|
||||
Ok((buf, data))
|
||||
|
||||
@@ -68,11 +68,8 @@ pub struct UdpAck {
|
||||
pub group_id: u32,
|
||||
/// The ID of the last data packet [`UdpData`]
|
||||
pub packet_id: u32,
|
||||
/// 4 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000`, `09e00000`,
|
||||
/// `0`, `54785`, `55062`, `2528`,
|
||||
/// Unknown but seems to change randomly every second
|
||||
/// Might be a latency for the recieved acknoledge packets
|
||||
pub maybe_latency: u32,
|
||||
// 2 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000`
|
||||
// Unknown but seems to change randomly every second
|
||||
// 2 Bytes size of a payload
|
||||
//
|
||||
/// Payload of `00 01 01 01 01` where `01` is added after every repeat
|
||||
@@ -89,7 +86,6 @@ impl UdpAck {
|
||||
connection_id,
|
||||
group_id: 0xffffffff,
|
||||
packet_id: 0xffffffff,
|
||||
maybe_latency: 0x0,
|
||||
payload: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(payload.maybe_latency),
|
||||
le_u32(0),
|
||||
le_u32(binary_payload.len() as u32),
|
||||
slice(binary_payload),
|
||||
))
|
||||
|
||||
+10
-61
@@ -147,14 +147,11 @@ local message_types = {
|
||||
[106]="<Dst>",
|
||||
[107]="<Dst> (write)",
|
||||
[108]="<ConfigFileInfo> (log)",
|
||||
[109]="<Snap>",
|
||||
[114]="<Uid>",
|
||||
[115]="<WifiSignal>",
|
||||
[116]="<Wifi>",
|
||||
[120]="<OnlineUserList>",
|
||||
[122]="<PerformanceInfo>",
|
||||
[123]="<ReplaySeek>",
|
||||
[124]="<PushInfo>",
|
||||
[132]="<VideoInput>", -- <InputAdvanceCfg>
|
||||
[133]="<RfAlarm>",
|
||||
[141]="<Email> (test)",
|
||||
@@ -164,7 +161,6 @@ local message_types = {
|
||||
[151]="<AbilityInfo>",
|
||||
[190]="PTZ Preset",
|
||||
[194]="<Ftp> (test)",
|
||||
[195]="<AutoUpdate>",
|
||||
[199]="<Support>",
|
||||
[208]="<LedState>",
|
||||
[209]="<LedState> (write)",
|
||||
@@ -179,13 +175,9 @@ local message_types = {
|
||||
[228]="<Crop>",
|
||||
[229]="<Crop> (write)",
|
||||
[230]="<cropSnap>",
|
||||
[232]="<AudioTask>",
|
||||
[234]="UDP Keep Alive",
|
||||
[252]="<BatteryInfoList>",
|
||||
[253]="<BatteryInfo>",
|
||||
[268]="<CloudBindInfo>",
|
||||
[282]="<CloudLoginKey>",
|
||||
[287]="<TimeCfg>",
|
||||
[272]="<findAlarmVideo>",
|
||||
[273]="<alarmVideoInfo>",
|
||||
[274]="<findAlarmVideo>",
|
||||
@@ -197,7 +189,6 @@ local message_classes = {
|
||||
[0x6514]="legacy",
|
||||
[0x6614]="modern",
|
||||
[0x6414]="modern",
|
||||
[0x6482]="modern (file download)",
|
||||
[0x0000]="modern",
|
||||
}
|
||||
|
||||
@@ -205,37 +196,9 @@ local header_lengths = {
|
||||
[0x6514]=20,
|
||||
[0x6614]=20,
|
||||
[0x6414]=24,
|
||||
[0x6482]=24,
|
||||
[0x0000]=24,
|
||||
}
|
||||
|
||||
-----
|
||||
-- Decryption routine.
|
||||
-----
|
||||
-- For other locations, use: LUA_CPATH=.../luagcrypt/?.so
|
||||
bc_protocol.prefs.key = Pref.string("Decryption key", "",
|
||||
"Passphrase used for the camera. Required to decrypt the AES packets")
|
||||
bc_protocol.prefs.nonce = Pref.string("Nonce key", "",
|
||||
"Nonce negotiate during login. You can find this in the msg_id == 1 packets.")
|
||||
local function hexencode(str)
|
||||
return (str:gsub(".", function(char) return string.format("%02X", char:byte()) end))
|
||||
end
|
||||
local gcrypt = require("luagcrypt")
|
||||
local function aes_decrypt(data)
|
||||
local raw_key = bc_protocol.prefs.nonce .. "-" .. bc_protocol.prefs.key
|
||||
local iv = "0123456789abcdef"
|
||||
local hasher = gcrypt.Hash(gcrypt.MD_MD5)
|
||||
hasher:write(raw_key)
|
||||
local key = string.sub(hexencode(hasher:read()),0,16)
|
||||
local ciphertext = data
|
||||
local cipher = gcrypt.Cipher(gcrypt.CIPHER_AES256, gcrypt.CIPHER_MODE_CFB)
|
||||
cipher:setkey(key)
|
||||
cipher:setiv(iv)
|
||||
local decrypted = cipher:decrypt(ciphertext)
|
||||
local result = ByteArray.new(decrypted, true)
|
||||
return result
|
||||
end
|
||||
|
||||
local function xml_decrypt(ba, offset)
|
||||
local key = "\031\045\060\075\090\105\120\255" -- 1f, 2d, 3c, 4b, 5a, 69, 78 ,ff
|
||||
local e = ByteArray.new()
|
||||
@@ -253,14 +216,12 @@ local function get_header_len(buffer)
|
||||
return -1 -- No header found
|
||||
end
|
||||
local header_len = header_lengths[buffer(18, 2):le_uint()]
|
||||
if (not header_len) then
|
||||
return 20
|
||||
end
|
||||
return header_len
|
||||
end
|
||||
|
||||
local function get_header(buffer)
|
||||
-- bin_offset is either nil (no binary data) or nonzero
|
||||
-- TODO: bin_offset is actually stateful!
|
||||
local bin_offset = nil
|
||||
local return_code = nil
|
||||
local encr_xml = nil
|
||||
@@ -285,11 +246,12 @@ local function get_header(buffer)
|
||||
channel_id = buffer(12, 1):le_uint(),
|
||||
enc_offset = buffer(12, 1):le_uint(),
|
||||
stream_type = stream_text,
|
||||
msg_handle = buffer(14, 2):le_uint(),
|
||||
unknown = buffer(14, 1):le_uint(),
|
||||
msg_handle = buffer(15, 1):le_uint(),
|
||||
msg_cls = buffer(18, 2):le_uint(),
|
||||
status_code = return_code,
|
||||
class = message_classes[buffer(18, 2):le_uint()] or "unknown",
|
||||
header_len = get_header_len(buffer(0, nil)),
|
||||
class = message_classes[buffer(18, 2):le_uint()],
|
||||
header_len = header_lengths[buffer(18, 2):le_uint()],
|
||||
bin_offset = bin_offset,
|
||||
}
|
||||
end
|
||||
@@ -313,7 +275,8 @@ local function process_header(buffer, headers_tree)
|
||||
header:add_le(channel_id, buffer(12, 1))
|
||||
header:add_le(stream_id, buffer(13, 1))
|
||||
:append_text(stream_text)
|
||||
header:add_le(msg_handle, buffer(14, 2))
|
||||
header:add_le(unknown, buffer(14, 1))
|
||||
header:add_le(msg_handle, buffer(15, 1))
|
||||
|
||||
header:add_le(message_class, buffer(18, 2)):append_text(" (" .. header_data.class .. ")")
|
||||
|
||||
@@ -349,14 +312,7 @@ local function process_body(header, body_buffer, bc_subtree, pinfo)
|
||||
local body_tvb = xml_buffer:tvb("Meta Payload")
|
||||
body:add(body_tvb(), "Meta Payload")
|
||||
if xml_len >= 4 then
|
||||
if aes_decrypt(xml_buffer:raw(0,5)):raw() == "<?xml" then -- AES encrypted
|
||||
local ba = xml_buffer:bytes()
|
||||
local decrypted = aes_decrypt(ba:raw())
|
||||
body_tvb = decrypted:tvb("Decrypted XML (in Meta Payload)")
|
||||
-- Create a tree item that, when clicked, automatically shows the tab we just created
|
||||
body:add(body_tvb(), "Decrypted XML (in Meta Payload)")
|
||||
Dissector.get("xml"):call(body_tvb, pinfo, body)
|
||||
elseif xml_decrypt(xml_buffer(0,5):bytes(), header.enc_offset):raw() == "<?xml" then -- Encrypted xml found
|
||||
if xml_decrypt(xml_buffer(0,5):bytes(), header.enc_offset):raw() == "<?xml" then -- Encrypted xml found
|
||||
local ba = xml_buffer:bytes()
|
||||
local decrypted = xml_decrypt(ba, header.enc_offset)
|
||||
body_tvb = decrypted:tvb("Decrypted XML (in Meta Payload)")
|
||||
@@ -379,14 +335,7 @@ local function process_body(header, body_buffer, bc_subtree, pinfo)
|
||||
local body_tvb = binary_buffer:tvb("Main Payload");
|
||||
body:add(body_tvb(), "Main Payload")
|
||||
if bin_len > 4 then
|
||||
if aes_decrypt(binary_buffer:raw(0,5)):raw() == "<?xml" then -- AES encrypted
|
||||
local ba = binary_buffer:bytes()
|
||||
local decrypted = aes_decrypt(ba:raw())
|
||||
body_tvb = decrypted:tvb("Decrypted XML (in Binary Payload)")
|
||||
-- Create a tree item that, when clicked, automatically shows the tab we just created
|
||||
body:add(body_tvb(), "Decrypted XML (in Binary Payload)")
|
||||
Dissector.get("xml"):call(body_tvb, pinfo, body)
|
||||
elseif xml_decrypt(binary_buffer(0,5):bytes(), header.enc_offset):raw() == "<?xml" then -- Encrypted xml found
|
||||
if xml_decrypt(binary_buffer(0,5):bytes(), header.enc_offset):raw() == "<?xml" then -- Encrypted xml found
|
||||
local decrypted = xml_decrypt(binary_buffer:bytes(), header.enc_offset)
|
||||
body_tvb = decrypted:tvb("Decrypted XML (in Main Payload)")
|
||||
-- Create a tree item that, when clicked, automatically shows the tab we just created
|
||||
@@ -694,7 +643,7 @@ local function udp_reassemple(udp_header, subbuffer, more, pinfo, tree)
|
||||
local needed = start_fragment.result
|
||||
if needed == "DONE" then
|
||||
if start_fragment.message_id == udp_header.packet_count then
|
||||
process_bc_message(start_fragment.buffer:tvb("UDP Reassemble"), pinfo, tree)
|
||||
process_bc_message(start_fragment.buffer:tvb(), pinfo, tree)
|
||||
end
|
||||
elseif needed == "+1" then
|
||||
-- Cannot handle in UDP...
|
||||
|
||||
+22
-2
@@ -354,7 +354,7 @@ Message have zero to two payloads.
|
||||
</PtzControl>
|
||||
</body>
|
||||
```
|
||||
|
||||
|
||||
- **Notes** : The known movement commands are `"left"`, `"right"`, `"up"`, `"down"`, `"leftUp"`,
|
||||
`"leftDown"`, `"rightUp"`, `"rightDown"` and `"stop"` although the diagonal movement
|
||||
does not seem to work.
|
||||
@@ -394,7 +394,7 @@ Message have zero to two payloads.
|
||||
</PtzPreset>
|
||||
</body>
|
||||
```
|
||||
|
||||
|
||||
- **Notes** : The known values for command are `"setPos"` and `"toPos"`
|
||||
|
||||
- Camera
|
||||
@@ -1655,6 +1655,8 @@ Message have zero to two payloads.
|
||||
|
||||
- Payload
|
||||
|
||||
If no SD Card:
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
@@ -1662,6 +1664,24 @@ Message have zero to two payloads.
|
||||
</body>
|
||||
```
|
||||
|
||||
If there is a SD Card
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<HddInfoList version="1.1">
|
||||
<HddInfo>
|
||||
<number>0</number>
|
||||
<capacity>30</capacity>
|
||||
<format>1</format>
|
||||
<mount>1</mount>
|
||||
<remainSize>29</remainSize>
|
||||
<remainSizeM>551</remainSizeM>
|
||||
</HddInfo>
|
||||
</HddInfoList>
|
||||
</body>
|
||||
```
|
||||
|
||||
- 104: `<SystemGeneral>`
|
||||
|
||||
- Client
|
||||
|
||||
@@ -38,10 +38,6 @@ address = "192.168.1.187:9000"
|
||||
# mqtt.broker_addr = "192.168.1.122"
|
||||
# mqtt.port = 1883
|
||||
# mqtt.credentials = ["mqtt_user", "mqtt_password"]
|
||||
# MQTT Discovery: https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
|
||||
# mqtt.discovery.topic = "homeassistant" # Uncomment to enable
|
||||
# If using discovery, _ characters are replaced with spaces in the name and title case is applied
|
||||
# mqtt.discovery.features = ["floodlight"] # Uncomment if this camera has a spotlight/floodlight
|
||||
|
||||
# If you use a battery camera: **Instead** of an `address` supply the uid
|
||||
# as follows
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
use clap::Parser;
|
||||
|
||||
/// The battery command will dump the battery status to XML
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct Opt {
|
||||
/// The name of the camera. Must be a name in the config
|
||||
pub camera: String,
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
///
|
||||
/// # Neolink Battery
|
||||
///
|
||||
/// This module handles the printing of the Battery status
|
||||
/// in xml format
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
/// ```bash
|
||||
/// neolink battery --config=config.toml CameraName
|
||||
/// ```
|
||||
///
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
mod cmdline;
|
||||
|
||||
use super::config::Config;
|
||||
use crate::utils::find_and_connect;
|
||||
pub(crate) use cmdline::Opt;
|
||||
|
||||
/// Entry point for the battery subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
let camera = find_and_connect(&config, &opt.camera).await?;
|
||||
|
||||
let state = camera
|
||||
.battery_info()
|
||||
.await
|
||||
.context("Unable to get camera Battery state")?;
|
||||
let ser = String::from_utf8(
|
||||
yaserde::ser::serialize_with_writer(&state, vec![], &Default::default())
|
||||
.expect("Should Ser the struct"),
|
||||
)
|
||||
.expect("Should be UTF8");
|
||||
println!("{}", ser);
|
||||
|
||||
let _ = camera.logout().await;
|
||||
camera.disconnect().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -25,5 +25,4 @@ pub enum Command {
|
||||
Talk(super::talk::Opt),
|
||||
Mqtt(super::mqtt::Opt),
|
||||
Image(super::image::Opt),
|
||||
Battery(super::battery::Opt),
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
use crate::mqtt::Discoveries;
|
||||
use lazy_static::lazy_static;
|
||||
use neolink_core::bc_protocol::{DiscoveryMethods, PrintFormat};
|
||||
use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
use std::clone::Clone;
|
||||
use std::collections::HashSet;
|
||||
use validator::{Validate, ValidationError};
|
||||
use validator_derive::Validate;
|
||||
|
||||
@@ -120,15 +118,6 @@ pub(crate) struct CameraConfig {
|
||||
alias = "stretching"
|
||||
)]
|
||||
pub(crate) use_smoothing: bool,
|
||||
|
||||
#[serde(default = "default_true", alias = "splash")]
|
||||
pub(crate) use_splash: bool,
|
||||
|
||||
#[serde(default = "default_true", alias = "enable")]
|
||||
pub(crate) enabled: bool,
|
||||
|
||||
#[serde(default = "default_false", alias = "verbose")]
|
||||
pub(crate) debug: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
@@ -157,27 +146,6 @@ pub(crate) struct MqttConfig {
|
||||
|
||||
#[serde(default)]
|
||||
pub(crate) client_auth: Option<(std::path::PathBuf, std::path::PathBuf)>,
|
||||
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_motion: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_pings: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_light: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_battery: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_preview: bool,
|
||||
|
||||
#[serde(default)]
|
||||
pub(crate) discovery: Option<MqttDiscoveryConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Clone, Validate)]
|
||||
pub(crate) struct MqttDiscoveryConfig {
|
||||
pub(crate) topic: String,
|
||||
|
||||
pub(crate) features: HashSet<Discoveries>,
|
||||
}
|
||||
|
||||
fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
|
||||
@@ -190,14 +158,6 @@ fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
|
||||
}
|
||||
}
|
||||
|
||||
const fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
const fn default_false() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_mqtt() -> Option<MqttConfig> {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -10,9 +10,4 @@ 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,
|
||||
}
|
||||
+1
-5
@@ -20,6 +20,7 @@ enum GstControl {
|
||||
|
||||
pub(super) struct GstSender {
|
||||
sender: Sender<GstControl>,
|
||||
#[allow(dead_code)] // It is used for its automatic drop
|
||||
set: JoinSet<Result<()>>,
|
||||
finished: sync::oneshot::Receiver<Result<()>>,
|
||||
}
|
||||
@@ -48,11 +49,6 @@ impl GstSender {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn join(mut self) -> Result<()> {
|
||||
while self.set.join_next().await.is_some() {}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn from_input<T: AsRef<Path>>(
|
||||
|
||||
+34
-59
@@ -9,18 +9,9 @@
|
||||
/// 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;
|
||||
@@ -41,60 +32,44 @@ 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")?;
|
||||
|
||||
if opt.use_stream {
|
||||
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;
|
||||
}
|
||||
// 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;
|
||||
}
|
||||
|
||||
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
|
||||
let _ = sender.join().await;
|
||||
|
||||
let _ = stream_data.shutdown().await;
|
||||
} 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?;
|
||||
}
|
||||
|
||||
let _ = camera.logout().await;
|
||||
camera.disconnect().await?;
|
||||
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
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -29,7 +29,6 @@ use log::*;
|
||||
use std::fs;
|
||||
use validator::Validate;
|
||||
|
||||
mod battery;
|
||||
mod cmdline;
|
||||
mod config;
|
||||
mod image;
|
||||
@@ -116,9 +115,6 @@ async fn main() -> Result<()> {
|
||||
Some(Command::Image(opts)) => {
|
||||
image::main(opts, config).await?;
|
||||
}
|
||||
Some(Command::Battery(opts)) => {
|
||||
battery::main(opts, config).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -1,570 +0,0 @@
|
||||
//! Enable and configures home assistant MQTTT discovery
|
||||
//!
|
||||
//! https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
|
||||
//!
|
||||
use anyhow::{Context, Result};
|
||||
use heck::ToTitleCase;
|
||||
use log::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::mqttc::MqttSender;
|
||||
use crate::config::{CameraConfig, MqttDiscoveryConfig};
|
||||
use serde::{Deserialize, Serialize, Serializer};
|
||||
|
||||
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Copy, Hash)]
|
||||
pub(crate) enum Discoveries {
|
||||
#[serde(alias = "floodlight", alias = "light")]
|
||||
Floodlight,
|
||||
#[serde(alias = "camera")]
|
||||
Camera,
|
||||
#[serde(alias = "motion", alias = "md", alias = "pir")]
|
||||
Motion,
|
||||
#[serde(alias = "led")]
|
||||
Led,
|
||||
#[serde(alias = "ir")]
|
||||
Ir,
|
||||
#[serde(alias = "reboot")]
|
||||
Reboot,
|
||||
#[serde(alias = "pt")]
|
||||
Pt,
|
||||
#[serde(alias = "battery", alias = "power")]
|
||||
Battery,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct DiscoveryConnection {
|
||||
connection_type: String,
|
||||
connection_id: String,
|
||||
}
|
||||
|
||||
impl Serialize for DiscoveryConnection {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
vec![&self.connection_type, &self.connection_id].serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, Clone)]
|
||||
struct DiscoveryDevice {
|
||||
name: String,
|
||||
connections: Vec<DiscoveryConnection>,
|
||||
identifiers: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
manufacturer: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
model: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
sw_version: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, Clone)]
|
||||
struct DiscoveryAvaliablity {
|
||||
topic: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
payload_available: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
payload_not_available: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoveryLight {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// Light specific
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
state_topic: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
state_value_template: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
command_topic: Option<String>,
|
||||
payload_on: String,
|
||||
payload_off: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
#[allow(dead_code)]
|
||||
enum Encoding {
|
||||
None,
|
||||
#[serde(rename = "b64")]
|
||||
Base64,
|
||||
}
|
||||
|
||||
impl Encoding {
|
||||
fn is_none(&self) -> bool {
|
||||
matches!(self, Self::None)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoveryCamera {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// Camera specific
|
||||
topic: String,
|
||||
#[serde(skip_serializing_if = "Encoding::is_none")]
|
||||
image_encoding: Encoding,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoverySwitch {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// Switch specific
|
||||
// - Control
|
||||
command_topic: String,
|
||||
payload_off: String,
|
||||
payload_on: String,
|
||||
// - State
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
state_topic: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
state_off: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
state_on: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoverySelect {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// Switch specific
|
||||
// - Control
|
||||
command_topic: String,
|
||||
options: Vec<String>,
|
||||
// - State
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
state_topic: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoveryBinarySensor {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// BinarySensor specific
|
||||
payload_off: String,
|
||||
payload_on: String,
|
||||
// - State
|
||||
state_topic: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoveryButton {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// Button specific
|
||||
command_topic: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
payload_press: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoverySensor {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// Button specific
|
||||
state_topic: String,
|
||||
state_class: String,
|
||||
unit_of_measurement: String,
|
||||
}
|
||||
|
||||
/// Enables MQTT discovery for a camera. See docs at https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
|
||||
pub(crate) async fn enable_discovery(
|
||||
discovery_config: &MqttDiscoveryConfig,
|
||||
mqtt_sender: &MqttSender,
|
||||
cam_config: &Arc<CameraConfig>,
|
||||
) -> Result<()> {
|
||||
debug!("Enabling MQTT discovery for {}", cam_config.name);
|
||||
|
||||
let mut connections = vec![];
|
||||
if let Some(addr) = &cam_config.camera_addr {
|
||||
connections.push(DiscoveryConnection {
|
||||
connection_type: "camera_addr".to_string(),
|
||||
connection_id: addr.clone(),
|
||||
});
|
||||
}
|
||||
if let Some(uid) = &cam_config.camera_uid {
|
||||
connections.push(DiscoveryConnection {
|
||||
connection_type: "camera_uid".to_string(),
|
||||
connection_id: uid.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
if connections.is_empty() {
|
||||
error!(
|
||||
"No connections found for camera {}, either addr or UID must be supplied",
|
||||
cam_config.name
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let friendly_name = cam_config.name.replace('_', " ").to_title_case();
|
||||
let device = DiscoveryDevice {
|
||||
name: friendly_name.clone(),
|
||||
connections,
|
||||
identifiers: vec![format!("neolink_{}", cam_config.name)],
|
||||
manufacturer: Some("Reolink".to_string()),
|
||||
model: Some("Neolink".to_string()),
|
||||
sw_version: Some(env!("CARGO_PKG_VERSION").to_string()),
|
||||
};
|
||||
|
||||
let availability = DiscoveryAvaliablity {
|
||||
topic: format!("neolink/{}/status", cam_config.name),
|
||||
payload_available: Some("connected".to_string()),
|
||||
payload_not_available: None,
|
||||
};
|
||||
|
||||
for feature in &discovery_config.features {
|
||||
match feature {
|
||||
Discoveries::Floodlight => {
|
||||
let config_data = DiscoveryLight {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} Floodlight", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_floodlight", cam_config.name),
|
||||
// Match native home assistant integration: https://github.com/home-assistant/core/blob/dev/homeassistant/components/reolink/light.py#L49
|
||||
icon: Some("mdi:spotlight-beam".to_string()),
|
||||
|
||||
// State
|
||||
state_topic: Some(format!("neolink/{}/status/floodlight", cam_config.name)),
|
||||
state_value_template: Some("{{ value_json.state }}".to_string()),
|
||||
|
||||
// Control
|
||||
command_topic: Some(format!("neolink/{}/control/floodlight", cam_config.name)),
|
||||
// Lowercase payloads to match neolink convention
|
||||
payload_on: "on".to_string(),
|
||||
payload_off: "off".to_string(),
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/light/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery light config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish floodlight auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Discoveries::Camera => {
|
||||
let config_data = DiscoveryCamera {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} Camera", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_camera", cam_config.name),
|
||||
icon: Some("mdi:camera-iris".to_string()),
|
||||
|
||||
// Camera specific
|
||||
topic: format!("neolink/{}/status/preview", cam_config.name),
|
||||
image_encoding: Encoding::Base64,
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/camera/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery camera config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish camera auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Discoveries::Led => {
|
||||
let config_data = DiscoverySwitch {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} LED", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_led", cam_config.name),
|
||||
icon: Some("mdi:led-on".to_string()),
|
||||
|
||||
// Switch specific
|
||||
command_topic: format!("neolink/{}/control/led", cam_config.name),
|
||||
payload_off: "off".to_string(),
|
||||
payload_on: "on".to_string(),
|
||||
state_topic: None,
|
||||
state_off: None,
|
||||
state_on: None,
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/switch/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery led config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish led auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Discoveries::Ir => {
|
||||
let config_data = DiscoverySelect {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} IR", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_ir", cam_config.name),
|
||||
icon: Some("mdi:lightbulb-night".to_string()),
|
||||
|
||||
// Switch specific
|
||||
command_topic: format!("neolink/{}/control/ir", cam_config.name),
|
||||
options: vec!["on".to_string(), "off".to_string(), "auto".to_string()],
|
||||
state_topic: None,
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/select/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery led config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish led auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Discoveries::Motion => {
|
||||
let config_data = DiscoveryBinarySensor {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} MD", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_md", cam_config.name),
|
||||
icon: Some("mdi:motion-sensor".to_string()),
|
||||
|
||||
// Switch specific
|
||||
state_topic: format!("neolink/{}/status/motion", cam_config.name),
|
||||
payload_off: "off".to_string(),
|
||||
payload_on: "on".to_string(),
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/binary_sensor/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery motion config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish motion auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Discoveries::Reboot => {
|
||||
let config_data = DiscoveryButton {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} Reboot", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_reboot", cam_config.name),
|
||||
icon: Some("mdi:restart".to_string()),
|
||||
|
||||
// Switch specific
|
||||
command_topic: format!("neolink/{}/control/reboot", cam_config.name),
|
||||
payload_press: None,
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/button/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery reboot config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish reboot auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Discoveries::Pt => {
|
||||
for dir in ["left", "right", "up", "down"] {
|
||||
let config_data = DiscoveryButton {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} Pan {}", friendly_name.as_str(), dir),
|
||||
unique_id: format!("neolink_{}_pan_{}", cam_config.name, dir),
|
||||
icon: Some(format!("mdi:pan-{}", dir)),
|
||||
|
||||
// Switch specific
|
||||
command_topic: format!("neolink/{}/control/ptz", cam_config.name),
|
||||
payload_press: Some(dir.to_string()),
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/button/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery pt config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish pt auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Discoveries::Battery => {
|
||||
let config_data = DiscoverySensor {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} Battery", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_battery", cam_config.name),
|
||||
icon: Some("mdi:battery".to_string()),
|
||||
|
||||
// Camera specific
|
||||
state_topic: format!("neolink/{}/status/battery_level", cam_config.name),
|
||||
state_class: "measurement".to_string(),
|
||||
unit_of_measurement: "%".to_string(),
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/sensor/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery battery config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish battery auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info!(
|
||||
"Enabled MQTT discovery for {} with friendly name {}",
|
||||
cam_config.name,
|
||||
friendly_name.as_str()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+7
-113
@@ -1,5 +1,5 @@
|
||||
use crate::config::CameraConfig;
|
||||
use crate::utils::{timeout, AddressOrUid};
|
||||
use crate::utils::AddressOrUid;
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use futures::stream::StreamExt;
|
||||
use log::*;
|
||||
@@ -31,8 +31,6 @@ pub(crate) enum Messages {
|
||||
PIROff,
|
||||
PIRQuery,
|
||||
Ptz(Direction),
|
||||
Snap(Vec<u8>),
|
||||
BatteryLevel(u32),
|
||||
Preset(u8),
|
||||
PresetAssign(u8, String),
|
||||
PresetQuery,
|
||||
@@ -193,15 +191,12 @@ impl EventCamThread {
|
||||
"aes" => MaxEncryption::Aes,
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
timeout(camera.login_with_maxenc(max_encryption))
|
||||
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);
|
||||
|
||||
if let Err(e) = camera.monitor_battery(camera_config.print_format).await {
|
||||
warn!("Could not monitor battery: {:?}", e);
|
||||
}
|
||||
|
||||
self.tx.send(Messages::Login).await?;
|
||||
|
||||
// Shararble cameras
|
||||
@@ -217,16 +212,6 @@ impl EventCamThread {
|
||||
camera: arc_cam.clone(),
|
||||
};
|
||||
|
||||
let mut snap_thread = SnapThread {
|
||||
tx: self.tx.clone(),
|
||||
camera: arc_cam.clone(),
|
||||
};
|
||||
|
||||
let mut battery_thread = BatteryLevelThread {
|
||||
tx: self.tx.clone(),
|
||||
camera: arc_cam.clone(),
|
||||
};
|
||||
|
||||
let mut keepalive_thread = KeepaliveThread {
|
||||
camera: arc_cam.clone(),
|
||||
};
|
||||
@@ -240,7 +225,7 @@ impl EventCamThread {
|
||||
val = async {
|
||||
info!("{}: Listening to Camera Motion", camera_config.name);
|
||||
motion_thread.run().await
|
||||
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_motion => {
|
||||
} => {
|
||||
if let Err(e) = val {
|
||||
error!("Motion thread aborted: {:?}", e);
|
||||
Err(e)
|
||||
@@ -252,7 +237,7 @@ impl EventCamThread {
|
||||
val = async {
|
||||
debug!("{}: Starting Pings", camera_config.name);
|
||||
keepalive_thread.run().await
|
||||
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_pings => {
|
||||
} => {
|
||||
if let Err(e) = val {
|
||||
debug!("Ping thread aborted: {:?}", e);
|
||||
Err(e)
|
||||
@@ -264,7 +249,7 @@ impl EventCamThread {
|
||||
val = async {
|
||||
info!("{}: Listening to FloodLight Status", camera_config.name);
|
||||
flight_thread.run().await
|
||||
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_light => {
|
||||
} => {
|
||||
if let Err(e) = val {
|
||||
error!("FloodLight thread aborted: {:?}", e);
|
||||
Err(e)
|
||||
@@ -273,30 +258,6 @@ impl EventCamThread {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
val = async {
|
||||
info!("{}: Updating Preview", camera_config.name);
|
||||
snap_thread.run().await
|
||||
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_preview => {
|
||||
if let Err(e) = val {
|
||||
error!("Snap thread aborted: {:?}", e);
|
||||
Err(e)
|
||||
} else {
|
||||
debug!("Normal finish on Snap thread");
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
val = async {
|
||||
info!("{}: Updating Battery Level", camera_config.name);
|
||||
battery_thread.run().await
|
||||
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_battery => {
|
||||
if let Err(e) = val {
|
||||
error!("Battery thread aborted: {:?}", e);
|
||||
Err(e)
|
||||
} else {
|
||||
debug!("Normal finish on Battery thread");
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
val = async {
|
||||
info!("{}: Setting up camera actions", camera_config.name);
|
||||
message_handler.listen().await
|
||||
@@ -370,73 +331,6 @@ impl FloodlightThread {
|
||||
}
|
||||
}
|
||||
|
||||
struct SnapThread {
|
||||
tx: Sender<Messages>,
|
||||
camera: Arc<BcCamera>,
|
||||
}
|
||||
|
||||
impl SnapThread {
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
let mut tries = 0;
|
||||
let base_duration = Duration::from_millis(500);
|
||||
loop {
|
||||
tokio::time::sleep(base_duration.saturating_mul(tries)).await;
|
||||
let snapshot = match self.camera.get_snapshot().await {
|
||||
Ok(info) => {
|
||||
tries = 1;
|
||||
info
|
||||
}
|
||||
Err(neolink_core::Error::UnintelligibleReply { reply, why }) => {
|
||||
log::debug!("Reply: {:?}, why: {:?}", reply, why);
|
||||
// Try again later
|
||||
tries += 1;
|
||||
continue;
|
||||
}
|
||||
Err(neolink_core::Error::CameraServiceUnavaliable) => {
|
||||
log::debug!("Snap not supported");
|
||||
futures::future::pending().await
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
self.tx.send(Messages::Snap(snapshot)).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BatteryLevelThread {
|
||||
tx: Sender<Messages>,
|
||||
camera: Arc<BcCamera>,
|
||||
}
|
||||
|
||||
impl BatteryLevelThread {
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
let mut tries = 0;
|
||||
let base_duration = Duration::from_secs(15);
|
||||
loop {
|
||||
tokio::time::sleep(base_duration.saturating_mul(tries)).await;
|
||||
let battery = match self.camera.battery_info().await {
|
||||
Ok(info) => {
|
||||
tries = 1;
|
||||
info
|
||||
}
|
||||
Err(neolink_core::Error::UnintelligibleReply { .. }) => {
|
||||
// Try again later
|
||||
tries += 1;
|
||||
continue;
|
||||
}
|
||||
Err(neolink_core::Error::CameraServiceUnavaliable) => {
|
||||
log::debug!("Battery not supported");
|
||||
futures::future::pending().await
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
self.tx
|
||||
.send(Messages::BatteryLevel(battery.battery_percent))
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct KeepaliveThread {
|
||||
camera: Arc<BcCamera>,
|
||||
}
|
||||
|
||||
+4
-33
@@ -1,4 +1,3 @@
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
|
||||
///
|
||||
/// # Neolink MQTT
|
||||
///
|
||||
@@ -10,7 +9,6 @@ use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
|
||||
///
|
||||
/// Control messages:
|
||||
///
|
||||
/// - `/control/floodlight [on|off]` Turns floodlight (if equipped) on/off
|
||||
/// - `/control/led [on|off]` Turns status LED on/off
|
||||
/// - `/control/pir [on|off]` Turns PIR on/off
|
||||
/// - `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light detection
|
||||
@@ -62,21 +60,18 @@ use std::sync::Arc;
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
mod cmdline;
|
||||
mod discovery;
|
||||
mod event_cam;
|
||||
mod mqttc;
|
||||
|
||||
use crate::config::{CameraConfig, Config, MqttConfig};
|
||||
use anyhow::{anyhow, Context, Error, Result};
|
||||
pub(crate) use cmdline::Opt;
|
||||
pub(crate) use discovery::Discoveries;
|
||||
use event_cam::EventCam;
|
||||
pub(crate) use event_cam::{Direction, Messages};
|
||||
use log::*;
|
||||
use mqttc::{Mqtt, MqttReplyRef};
|
||||
|
||||
use self::{
|
||||
discovery::enable_discovery,
|
||||
event_cam::EventCamSender,
|
||||
mqttc::{MqttReply, MqttSender},
|
||||
};
|
||||
@@ -95,7 +90,6 @@ pub(crate) async fn main(_: Opt, config: Config) -> Result<()> {
|
||||
for camera_config in config
|
||||
.cameras
|
||||
.iter()
|
||||
.filter(|c| c.enabled)
|
||||
.map(|a| Arc::new(a.clone()))
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
@@ -141,8 +135,7 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
tokio::select! {
|
||||
v = async {
|
||||
// Normal poll operations
|
||||
loop {
|
||||
let msg = mqtt.poll().await?;
|
||||
while let Ok(msg) = mqtt.poll().await {
|
||||
tokio::task::yield_now().await;
|
||||
// Put the reply on it's own async thread so we can safely sleep
|
||||
// and wait for it to reply in it's own time
|
||||
@@ -159,6 +152,7 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
} => v,
|
||||
// Wait on any error from any of the error channels and if we get it we abort
|
||||
v = error_recv.recv() => v.map(Err).unwrap_or_else(|| Err(anyhow!("Listen on camera error channel closed"))),
|
||||
@@ -176,10 +170,6 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
.with_context(|| {
|
||||
format!("Failed to post connect over MQTT for {}", camera_name)
|
||||
})?;
|
||||
|
||||
if let Some(discovery_config) = &mqtt_config.discovery {
|
||||
enable_discovery(discovery_config, &mqtt_sender_cam, &cam_config).await?;
|
||||
}
|
||||
}
|
||||
Messages::FloodlightOn => {
|
||||
mqtt_sender_cam
|
||||
@@ -187,7 +177,7 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish floodlight on over MQTT for {}",
|
||||
"Failed to publish gloodlight on over MQTT for {}",
|
||||
camera_name
|
||||
)
|
||||
})?;
|
||||
@@ -198,7 +188,7 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish floodlight off over MQTT for {}",
|
||||
"Failed to publish gloodlight off over MQTT for {}",
|
||||
camera_name
|
||||
)
|
||||
})?;
|
||||
@@ -219,25 +209,6 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
format!("Failed to publish motion start for {}", camera_name)
|
||||
})?;
|
||||
}
|
||||
Messages::Snap(data) => {
|
||||
mqtt_sender_cam
|
||||
.send_message("status/preview", BASE64.encode(data).as_str(), true)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("Failed to publish preview over MQTT for {}", camera_name)
|
||||
})?;
|
||||
}
|
||||
Messages::BatteryLevel(data) => {
|
||||
mqtt_sender_cam
|
||||
.send_message("status/battery_level", format!("{}", data).as_str(), true)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish battery level over MQTT for {}",
|
||||
camera_name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
+7
-21
@@ -50,31 +50,19 @@ pub(crate) struct MqttSender {
|
||||
}
|
||||
|
||||
impl MqttSender {
|
||||
pub async fn send_message_with_root_topic(
|
||||
&self,
|
||||
root_topic: &str,
|
||||
sub_topic: &str,
|
||||
message: &str,
|
||||
retain: bool,
|
||||
) -> Result<(), ClientError> {
|
||||
self.client
|
||||
.publish(
|
||||
format!("{}/{}/{}", root_topic, self.name, sub_topic),
|
||||
QoS::AtLeastOnce,
|
||||
retain,
|
||||
message,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_message(
|
||||
&self,
|
||||
sub_topic: &str,
|
||||
message: &str,
|
||||
retain: bool,
|
||||
) -> Result<(), ClientError> {
|
||||
self.send_message_with_root_topic("neolink", sub_topic, message, retain)
|
||||
self.client
|
||||
.publish(
|
||||
format!("neolink/{}/{}", self.name, sub_topic),
|
||||
QoS::AtLeastOnce,
|
||||
retain,
|
||||
message,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -168,8 +156,6 @@ impl Mqtt {
|
||||
&config.broker_addr,
|
||||
config.port,
|
||||
);
|
||||
let max_size = 100 * (1024 * 1024);
|
||||
mqttoptions.set_max_packet_size(max_size, max_size);
|
||||
|
||||
// Use TLS if ca path is set
|
||||
if let Some(ca_path) = &config.ca {
|
||||
|
||||
@@ -44,9 +44,5 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
.expect("Should be UTF8");
|
||||
println!("{}", pir_ser);
|
||||
}
|
||||
|
||||
let _ = camera.logout().await;
|
||||
camera.disconnect().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -90,9 +90,5 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
.context("Unable to execute PTZ move command")?;
|
||||
}
|
||||
};
|
||||
|
||||
let _ = camera.logout().await;
|
||||
camera.disconnect().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -29,8 +29,5 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
.reboot()
|
||||
.await
|
||||
.context("Could not send reboot command to the camera")?;
|
||||
|
||||
camera.disconnect().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+46
-54
@@ -41,17 +41,17 @@ glib::wrapper! {
|
||||
|
||||
impl Default for NeoMediaFactory {
|
||||
fn default() -> Self {
|
||||
Self::new(100, true, true)
|
||||
Self::new(100, true)
|
||||
}
|
||||
}
|
||||
|
||||
impl NeoMediaFactory {
|
||||
pub(crate) fn new(buffer_size: usize, use_smoothing: bool, use_splash: bool) -> Self {
|
||||
pub(crate) fn new(buffer_size: usize, use_smoothing: 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.imp().shared.set_use_splash(use_splash);
|
||||
// factory.set_do_retransmission(false); // Can't use as the method is missing on the 32bit docker gst dll
|
||||
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)
|
||||
.and_then(|orig| self.build_pipeline(orig).expect("Could not build pipeline"))
|
||||
.map(|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,17 +260,15 @@ impl NeoMediaFactoryImpl {
|
||||
self.shared.number_of_clients.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn build_pipeline(&self, media: Element) -> AnyResult<Option<Element>> {
|
||||
fn build_pipeline(&self, media: Element) -> AnyResult<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(),
|
||||
@@ -283,15 +281,12 @@ 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");
|
||||
@@ -300,7 +295,7 @@ impl NeoMediaFactoryImpl {
|
||||
let encoder = make_element("jpegenc", "encoder")?;
|
||||
let payload = make_element("rtpjpegpay", "pay0")?;
|
||||
|
||||
bin.add_many(&[&source, &queue, &overlay, &encoder, &payload])?;
|
||||
bin.add_many(&[&source, &queue, &queue2, &overlay, &encoder, &payload])?;
|
||||
source.link_filtered(
|
||||
&queue,
|
||||
&Caps::builder("video/x-raw")
|
||||
@@ -311,7 +306,7 @@ impl NeoMediaFactoryImpl {
|
||||
.build(),
|
||||
)?;
|
||||
// source.link(&queue)?;
|
||||
Element::link_many(&[&queue, &overlay, &encoder, &payload])?;
|
||||
Element::link_many(&[&queue, &queue2, &overlay, &encoder, &payload])?;
|
||||
}
|
||||
(VidFormats::H265, true) => {
|
||||
debug!("Building H265 Pipeline");
|
||||
@@ -360,12 +355,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, &parser, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &parser, &payload])?;
|
||||
bin.add_many(&[&source, &queue, &queue2, &parser, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &queue2, &parser, &payload])?;
|
||||
|
||||
let source = source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
@@ -422,7 +417,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")?;
|
||||
@@ -434,13 +429,13 @@ impl NeoMediaFactoryImpl {
|
||||
|
||||
// payload.set_property("config-interval", 5i32);
|
||||
bin.add_many(&[
|
||||
&source, &queue, &parser,
|
||||
&source, &queue, &queue2, &parser,
|
||||
&payload,
|
||||
// &storage,
|
||||
// &jitter,
|
||||
])?;
|
||||
Element::link_many(&[
|
||||
&source, &queue, &parser,
|
||||
&source, &queue, &queue2, &parser,
|
||||
&payload,
|
||||
// &storage,
|
||||
// &jitter,
|
||||
@@ -493,26 +488,25 @@ 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 = match make_element("faad", "auddecoder_faad") {
|
||||
Ok(ele) => Ok(ele),
|
||||
Err(_) => make_element("avdec_aac", "auddecoder_avdec_aac"),
|
||||
}?;
|
||||
let decoder = make_element("decodebin", "auddecoder")?;
|
||||
let encoder = make_element("audioconvert", "audencoder")?;
|
||||
let payload = make_element("rtpL16pay", "pay1")?;
|
||||
|
||||
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");
|
||||
// });
|
||||
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");
|
||||
});
|
||||
|
||||
let source = source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
@@ -566,13 +560,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, &decoder, &encoder, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &decoder])?;
|
||||
bin.add_many(&[&source, &queue, &queue2, &decoder, &encoder, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &queue2, &decoder])?;
|
||||
Element::link_many(&[&encoder, &payload])?;
|
||||
decoder.connect_pad_added(move |_element, pad| {
|
||||
debug!("Linking encoder to decoder: {:?}", pad.caps());
|
||||
@@ -592,10 +586,8 @@ impl NeoMediaFactoryImpl {
|
||||
|
||||
self.clientsender.blocking_send(client_data)?;
|
||||
// debug!("Pipeline built");
|
||||
let element = bin
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
Ok(Some(element))
|
||||
bin.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))
|
||||
}
|
||||
|
||||
async fn join(&self) -> AnyResult<()> {
|
||||
|
||||
+147
-76
@@ -444,8 +444,8 @@ pub(super) struct NeoMediaSender {
|
||||
start_time: Spring,
|
||||
live_offset: FrameTime,
|
||||
buffer: NeoBuffer,
|
||||
vid: Option<Arc<AppSrc>>,
|
||||
aud: Option<Arc<AppSrc>>,
|
||||
vid: Option<AppSrc>,
|
||||
aud: Option<AppSrc>,
|
||||
command_reciever: Receiver<NeoMediaSenderCommand>,
|
||||
command_sender: Sender<NeoMediaSenderCommand>,
|
||||
inited: bool,
|
||||
@@ -453,11 +453,6 @@ 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);
|
||||
@@ -481,11 +476,11 @@ impl NeoMediaSender {
|
||||
}
|
||||
|
||||
pub(super) fn update_vid(&mut self, source: AppSrc) {
|
||||
self.vid.replace(Arc::new(source));
|
||||
self.vid.replace(source);
|
||||
}
|
||||
|
||||
pub(super) fn update_aud(&mut self, source: AppSrc) {
|
||||
self.aud.replace(Arc::new(source));
|
||||
self.aud.replace(source);
|
||||
}
|
||||
|
||||
pub(super) fn get_commader(&self) -> Sender<NeoMediaSenderCommand> {
|
||||
@@ -620,22 +615,15 @@ 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
|
||||
|| !matches!(
|
||||
item.data.first().map(|arc| arc.as_ref()),
|
||||
Some(BcMedia::Iframe(_))
|
||||
)
|
||||
})
|
||||
.take_while_ref(|item| item.time < target_time)
|
||||
.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?;
|
||||
debug!("Preprocessed: {}", preprocess.len());
|
||||
trace!("Preprocessed: {}", preprocess.len());
|
||||
// Send these later
|
||||
for frame in buffer.drain(..) {
|
||||
self.buffer.buf.push_back(frame);
|
||||
@@ -729,11 +717,17 @@ impl NeoMediaSender {
|
||||
if medias.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut buffers: Vec<Buffer> = vec![];
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
let mut vid_buffers: Vec<(FrameTime, Vec<u8>)> = vec![];
|
||||
let mut aud_buffers: Vec<(FrameTime, Vec<u8>)> = 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),
|
||||
@@ -741,71 +735,148 @@ impl NeoMediaSender {
|
||||
BcMedia::Adpcm(data) => Some(&data.data),
|
||||
_ => None,
|
||||
};
|
||||
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());
|
||||
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()))
|
||||
}
|
||||
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));
|
||||
}
|
||||
_ => {}
|
||||
} else {
|
||||
buffer.push((next_time, data.clone()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
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);
|
||||
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??;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
debug!("Failed to 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(Ok(_)) => {}
|
||||
};
|
||||
res??;
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
}
|
||||
}
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -363,11 +363,7 @@ 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,
|
||||
config.use_splash,
|
||||
);
|
||||
let media = NeoMediaFactory::new(config.buffer_size, config.use_smoothing);
|
||||
let thread_media = media.clone();
|
||||
self.threads
|
||||
.write()
|
||||
|
||||
@@ -25,7 +25,6 @@ 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 {
|
||||
@@ -37,7 +36,6 @@ impl Default for NeoMediaShared {
|
||||
buffer_ready: AtomicBool::new(false),
|
||||
buffer_size: AtomicUsize::new(100),
|
||||
use_smoothing: AtomicBool::new(false),
|
||||
splash: AtomicBool::new(true),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,12 +56,4 @@ 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)
|
||||
}
|
||||
}
|
||||
+4
-8
@@ -88,7 +88,7 @@ pub(crate) async fn main(_opt: Opt, mut config: Config) -> Result<()> {
|
||||
)
|
||||
}
|
||||
let mut cameras = vec![];
|
||||
for camera_config in config.cameras.drain(..).filter(|c| c.enabled) {
|
||||
for camera_config in config.cameras.drain(..) {
|
||||
cameras
|
||||
.push(Camera::<Disconnected>::new(camera_config, &config.users, rtsp.clone()).await?);
|
||||
}
|
||||
@@ -174,14 +174,10 @@ 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>();
|
||||
let e_inner = e.downcast_ref::<neolink_core::Error>().unwrap();
|
||||
match e_inner {
|
||||
Some(neolink_core::Error::CameraLoginFail) => CameraFailureKind::Fatal(e),
|
||||
Some(_) => CameraFailureKind::Retry(e),
|
||||
None => {
|
||||
// Timout error usually
|
||||
CameraFailureKind::Retry(e)
|
||||
}
|
||||
neolink_core::Error::CameraLoginFail => CameraFailureKind::Fatal(e),
|
||||
_ => CameraFailureKind::Retry(e),
|
||||
}
|
||||
})?;
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
// 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};
|
||||
@@ -29,17 +28,7 @@ impl Camera<Connected> {
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
|
||||
timeout(self.state.camera.login_with_maxenc(max_encryption)).await??;
|
||||
|
||||
if let Err(e) = self
|
||||
.state
|
||||
.camera
|
||||
.monitor_battery(self.shared.config.print_format)
|
||||
.await
|
||||
{
|
||||
log::warn!("Could not monitor battery: {:?}", e);
|
||||
}
|
||||
|
||||
self.state.camera.login_with_maxenc(max_encryption).await?;
|
||||
Ok(Camera {
|
||||
shared: self.shared,
|
||||
state: LoggedIn {
|
||||
|
||||
@@ -33,9 +33,5 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
.led_light_set(opt.on)
|
||||
.await
|
||||
.context("Unable to set camera light state")?;
|
||||
|
||||
let _ = camera.logout().await;
|
||||
camera.disconnect().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -86,8 +86,5 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
.await
|
||||
.context("Talk stream ended early")?;
|
||||
|
||||
let _ = camera.logout().await;
|
||||
camera.disconnect().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+4
-11
@@ -13,13 +13,6 @@ 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(15), future)
|
||||
}
|
||||
|
||||
pub(crate) enum AddressOrUid {
|
||||
Address(String),
|
||||
Uid(String, DiscoveryMethods),
|
||||
@@ -93,11 +86,11 @@ impl AddressOrUid {
|
||||
uid: camera_config.camera_uid.clone(),
|
||||
protocol: ConnectionProtocol::TcpUdp,
|
||||
discovery: camera_config.discovery,
|
||||
aux_printing: camera_config.print_format,
|
||||
credentials: Credentials {
|
||||
username: camera_config.username.clone(),
|
||||
password: camera_config.password.clone(),
|
||||
},
|
||||
debug: camera_config.debug,
|
||||
};
|
||||
|
||||
trace!("Camera Info: {:?}", options);
|
||||
@@ -140,9 +133,10 @@ pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result<Bc
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
timeout(camera.login_with_maxenc(max_encryption))
|
||||
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);
|
||||
|
||||
@@ -153,7 +147,6 @@ pub(crate) fn find_camera_by_name<'a>(config: &'a Config, name: &str) -> Result<
|
||||
config
|
||||
.cameras
|
||||
.iter()
|
||||
.filter(|c| c.enabled)
|
||||
.find(|c| c.name == name)
|
||||
.ok_or_else(|| anyhow!("Camera {} not found in the config file", name))
|
||||
}
|
||||
Reference in new issue
Block a user