Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e08bb66891 | ||
|
|
173c994530 | ||
|
|
95ce97c85e | ||
|
|
9087169873 | ||
|
|
d08a5fe4aa | ||
|
|
6a4468c8f6 | ||
|
|
d084a13eb0 | ||
|
|
1cde5ec3e5 | ||
|
|
97703bdb38 | ||
|
|
d0c85419eb | ||
|
|
a8a306301b | ||
|
|
f23f28c12e | ||
|
|
623fcb3fd1 | ||
|
|
e093151db6 | ||
|
|
eefe3dfa71 | ||
|
|
6e8fc3ee5b | ||
|
|
17e8ab0f37 | ||
|
|
0d2f0c3e6f | ||
|
|
0661aa8853 | ||
|
|
a380212662 | ||
|
|
a45bcf8761 | ||
|
|
c198f21c92 | ||
|
|
5109dbba9e | ||
|
|
b90d6d7eed | ||
|
|
971c1cddf8 | ||
|
|
816797a32b | ||
|
|
c3921cbb6c | ||
|
|
e93dc2fe9a | ||
|
|
af899d3cfd | ||
|
|
6b60ee6bcc | ||
|
|
810dd3cdc7 | ||
|
|
374b399631 | ||
|
|
2484b8753b | ||
|
|
9730114172 | ||
|
|
c45a5033b9 | ||
|
|
b2e43c605e | ||
|
|
e3b057f915 | ||
|
|
2f557f777d | ||
|
|
42ee790512 | ||
|
|
ae9d204718 | ||
|
|
5c7de6181c | ||
|
|
268303a0a2 | ||
|
|
acc063e325 | ||
|
|
e384fb6153 | ||
|
|
f6085cff1f | ||
|
|
94ffc54325 | ||
|
|
ce89a6dfbc | ||
|
|
6925736030 | ||
|
|
edfacc7eba |
No files matched your search
@@ -0,0 +1,13 @@
|
|||||||
|
# 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
|
uses: nebularg/actions-luacheck@v1
|
||||||
with:
|
with:
|
||||||
files: 'dissector/baichuan.lua'
|
files: 'dissector/baichuan.lua'
|
||||||
args: --globals Dissector Proto ProtoField base ByteArray DESEGMENT_ONE_MORE_SEGMENT DissectorTable
|
args: --globals Dissector Proto ProtoField base ByteArray DESEGMENT_ONE_MORE_SEGMENT DissectorTable Pref
|
||||||
Generated
+421
-482
File diff suppressed because it is too large.
Load diff
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "neolink"
|
name = "neolink"
|
||||||
description = "A standards-compliant bridge to Reolink IP cameras"
|
description = "A standards-compliant bridge to Reolink IP cameras"
|
||||||
version = "0.5.14"
|
version = "0.5.18"
|
||||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
@@ -29,7 +29,7 @@ is_sorted = "0.1.1"
|
|||||||
itertools = "0.11.0"
|
itertools = "0.11.0"
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
|
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
|
||||||
neolink_core = { path = "crates/core", version = "0.5.14" }
|
neolink_core = { path = "crates/core", version = "0.5.18" }
|
||||||
regex = "1.7.3"
|
regex = "1.7.3"
|
||||||
rumqttc = "0.22.0"
|
rumqttc = "0.22.0"
|
||||||
serde = { version = "1.0.160", features = ["derive"] }
|
serde = { version = "1.0.160", features = ["derive"] }
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
# Neolink
|
# Neolink
|
||||||
|
|
||||||

|

|
||||||
|
[](https://deps.rs/repo/github/QuantumEntangledAndy/neolink)
|
||||||
|
|
||||||
Neolink is a small program that acts as a proxy between Reolink IP cameras and
|
Neolink is a small program that acts as a proxy between Reolink IP cameras and
|
||||||
normal RTSP clients.
|
normal RTSP clients.
|
||||||
@@ -31,7 +32,7 @@ features not yet in upstream master.
|
|||||||
|
|
||||||
**Minor Features**:
|
**Minor Features**:
|
||||||
|
|
||||||
- Improved error messages when your missing gstreamer plugins
|
- Improved error messages when missing gstreamer plugins
|
||||||
- Protocol more closely follows offical reolink format
|
- Protocol more closely follows offical reolink format
|
||||||
- Possibly can handle more simulatenous connections
|
- Possibly can handle more simulatenous connections
|
||||||
- More ways to connect to the camera. Including Relaying through reolink
|
- More ways to connect to the camera. Including Relaying through reolink
|
||||||
@@ -93,7 +94,7 @@ uid = "BCDEF0123456789A"
|
|||||||
address = "192.168.1.10"
|
address = "192.168.1.10"
|
||||||
```
|
```
|
||||||
|
|
||||||
Create a text file with called `neolink.toml` in the same folder as the
|
Create a text file called `neolink.toml` in the same folder as the
|
||||||
neolink binary. With your config options.
|
neolink binary. With your config options.
|
||||||
|
|
||||||
When ready start `neolink` with the following command
|
When ready start `neolink` with the following command
|
||||||
@@ -114,20 +115,20 @@ The IP is discovered with four methods
|
|||||||
the local network if there is a camera with this UID. This only works if
|
the local network if there is a camera with this UID. This only works if
|
||||||
the network supports broadcasts
|
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
|
config and attempt a direct connection without broadcasts. This requires a
|
||||||
route from neolink to the camera.
|
route from neolink to the camera.
|
||||||
|
|
||||||
2. Remote discovery: Here a ask the reolink servers what the IP address is.
|
2. Remote discovery: Here we ask the reolink servers what the IP address is.
|
||||||
This requires that we contact reolink and provide some basic information
|
This requires that we contact reolink and provide some basic information
|
||||||
like the UID. Once we have this information we connect directly to the
|
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
|
local IP address. This requires a route from neolink to the camera and
|
||||||
for the camera to be able to contact the reolink IPs.
|
for the camera to be able to contact reolink.
|
||||||
|
|
||||||
3. Map discovery: In this case we register our IP address with reolink and ask
|
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/recives a connect
|
the camera to connect to us. Once the camera either polls/recieves a connect
|
||||||
request from the reolink servers the camera will then initiate a connect
|
request from the reolink servers the camera will initiate a connection
|
||||||
to neolink. This requires that our IP and the reolink IPs are reacable from
|
to neolink. This requires that our IP and reolink are reachable from
|
||||||
the camera.
|
the camera.
|
||||||
|
|
||||||
4. Relay: In this case we request that reolink relay our connection. Neolink
|
4. Relay: In this case we request that reolink relay our connection. Neolink
|
||||||
@@ -158,7 +159,7 @@ See the sample config file for more details.
|
|||||||
|
|
||||||
### MQTT
|
### MQTT
|
||||||
|
|
||||||
To use mqtt you will to adjust your config file as such:
|
To use mqtt you will need to adjust your config file as such:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
bind = "0.0.0.0"
|
bind = "0.0.0.0"
|
||||||
@@ -193,7 +194,8 @@ Control messages:
|
|||||||
- `/control/ptz [up|down|left|right|in|out] (amount)` Control the PTZ
|
- `/control/ptz [up|down|left|right|in|out] (amount)` Control the PTZ
|
||||||
movements, amount defaults to 32.0
|
movements, amount defaults to 32.0
|
||||||
- `/control/ptz/preset [id]` Move the camera to a PTZ preset
|
- `/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]`
|
- `/control/pir [on|off]`
|
||||||
|
|
||||||
Status Messages:
|
Status Messages:
|
||||||
@@ -206,10 +208,13 @@ Status Messages:
|
|||||||
- `/status/battery_level` A simple % value of current battery level
|
- `/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
|
- `/status/pir` Sent in reply to a `/query/pir` an XML encoded version of the
|
||||||
pir status
|
pir status
|
||||||
- `/status/motion` Contains the motion detection alarm status. `on` for motion and `off` for still
|
- `/status/motion` Contains the motion detection alarm status. `on` for motion
|
||||||
- `/status/ptz/preset` Sent in reply to a `/query/ptz/preset` an XML encoded version of the
|
and `off` for still
|
||||||
PTZ presets
|
- `/status/ptz/preset` Sent in reply to a `/query/ptz/preset` an XML encoded
|
||||||
- `/status/preview` a base64 encoded camera image updated every 0.5s
|
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.
|
||||||
|
|
||||||
Query Messages:
|
Query Messages:
|
||||||
|
|
||||||
@@ -220,7 +225,7 @@ Query Messages:
|
|||||||
### MQTT Disable Features
|
### MQTT Disable Features
|
||||||
|
|
||||||
Certain features like preview and motion detection may not be desired
|
Certain features like preview and motion detection may not be desired
|
||||||
you can disable them by them with the following config options.
|
you can disable them with the following config options.
|
||||||
Disabling these may help to conserve battery
|
Disabling these may help to conserve battery
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
@@ -241,8 +246,9 @@ enable_preview = false # preview image in `/status/preview`
|
|||||||
|
|
||||||
#### MQTT Discovery
|
#### MQTT Discovery
|
||||||
|
|
||||||
[MQTT Discovery](https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery) is partially supported.
|
[MQTT Discovery](https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery)
|
||||||
Currently, discovery is opt-in and camera features must be manually specified.
|
is partially supported. Currently, discovery is opt-in and camera features
|
||||||
|
must be manually specified.
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[cameras.mqtt]
|
[cameras.mqtt]
|
||||||
@@ -255,15 +261,20 @@ Currently, discovery is opt-in and camera features must be manually specified.
|
|||||||
Avaliable features are:
|
Avaliable features are:
|
||||||
|
|
||||||
- `floodlight`: This adds a light control to home assistant
|
- `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
|
- `camera`: This adds a camera preview to home assistant. It is only updated
|
||||||
- `led`: This adds a switch to chage the LED status light on/off to home assistant
|
every 0.5s and cannot be much more than that since it is updated over mqtt
|
||||||
- `ir`: This adds a selection switch to chage the IR light on/off/auto to home assistant
|
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
|
- `motion`: This adds a motion detection binary sensor to home assistant
|
||||||
- `reboot`: This adds a reboot button 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
|
- `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
|
- `battery`: This adds a battery level sensor to home assistant
|
||||||
|
|
||||||
|
|
||||||
### Pause
|
### Pause
|
||||||
|
|
||||||
To use the pause feature you will need to adjust your config file as such:
|
To use the pause feature you will need to adjust your config file as such:
|
||||||
@@ -290,8 +301,8 @@ Then start the rtsp server as usual:
|
|||||||
|
|
||||||
### Battery Levels
|
### Battery Levels
|
||||||
|
|
||||||
If you have a battery camera and would like to see the battery messages in th
|
If you have a battery camera and would like to see the battery messages in the
|
||||||
log add the following to your config
|
log, add the following to your config
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[[cameras]]
|
[[cameras]]
|
||||||
@@ -299,8 +310,8 @@ log add the following to your config
|
|||||||
print_format = "Human"
|
print_format = "Human"
|
||||||
```
|
```
|
||||||
|
|
||||||
You can also print into xml format with `print_format = "Xml"` which can then b
|
You can also print into xml format with `print_format = "Xml"` which can then
|
||||||
passed by a script for processing.
|
be passed by a script for processing.
|
||||||
|
|
||||||
### Docker
|
### Docker
|
||||||
|
|
||||||
@@ -316,7 +327,8 @@ docker pull quantumentangledandy/neolink
|
|||||||
# --network host is only needed if you require to connect
|
# --network host is only needed if you require to connect
|
||||||
# via local broadcasts. If you can connect via any other
|
# via local broadcasts. If you can connect via any other
|
||||||
# method then normal bridge mode should work fine
|
# method then normal bridge mode should work fine
|
||||||
# and you can ommit this option
|
# and you can ommit this option. Not all OSes support
|
||||||
|
# network=host, notably macos lacks this option.
|
||||||
docker run --network host --volume=$PWD/config.toml:/etc/neolink.toml quantumentangledandy/neolink
|
docker run --network host --volume=$PWD/config.toml:/etc/neolink.toml quantumentangledandy/neolink
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -334,6 +346,11 @@ 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
|
File is always jpeg and the extension given in filepath will be added or changed
|
||||||
to reflect this.
|
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
|
## License
|
||||||
|
|
||||||
Neolink is free software, released under the GNU Affero General Public License
|
Neolink is free software, released under the GNU Affero General Public License
|
||||||
@@ -341,3 +358,9 @@ v3.
|
|||||||
|
|
||||||
This means that if you incorporate it into a piece of software available over
|
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.
|
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]
|
[package]
|
||||||
name = "neolink_core"
|
name = "neolink_core"
|
||||||
description = "Core services and structure for Reolink IP cameras"
|
description = "Core services and structure for Reolink IP cameras"
|
||||||
version = "0.5.14"
|
version = "0.5.18"
|
||||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
|
|||||||
@@ -15,6 +15,12 @@ pub(crate) struct BcCodex {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl 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 {
|
pub(crate) fn new(credentials: Credentials) -> Self {
|
||||||
Self {
|
Self {
|
||||||
context: BcContext::new(credentials),
|
context: BcContext::new(credentials),
|
||||||
@@ -29,7 +35,9 @@ impl Encoder<Bc> for BcCodex {
|
|||||||
// let context = self.context.read().unwrap();
|
// let context = self.context.read().unwrap();
|
||||||
let buf: Vec<u8> = Default::default();
|
let buf: Vec<u8> = Default::default();
|
||||||
let enc_protocol: EncryptionProtocol = match self.context.get_encrypted() {
|
let enc_protocol: EncryptionProtocol = match self.context.get_encrypted() {
|
||||||
EncryptionProtocol::Aes(_) if item.meta.msg_id == 1 => {
|
EncryptionProtocol::Aes(_) | EncryptionProtocol::FullAes(_)
|
||||||
|
if item.meta.msg_id == 1 =>
|
||||||
|
{
|
||||||
// During login the encyption protocol cannot go higher than BCEncrypt
|
// During login the encyption protocol cannot go higher than BCEncrypt
|
||||||
// even if we support AES. (BUt it can go lower i.e. None)
|
// even if we support AES. (BUt it can go lower i.e. None)
|
||||||
EncryptionProtocol::BCEncrypt
|
EncryptionProtocol::BCEncrypt
|
||||||
@@ -113,6 +121,9 @@ impl Decoder for BcCodex {
|
|||||||
0x02 => self.context.set_encrypted(EncryptionProtocol::Aes(
|
0x02 => self.context.set_encrypted(EncryptionProtocol::Aes(
|
||||||
self.context.credentials.make_aeskey(nonce),
|
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));
|
return Err(Error::UnknownEncryption(encryption_protocol_byte));
|
||||||
}
|
}
|
||||||
|
|||||||
+44
-17
@@ -113,8 +113,15 @@ fn bc_modern_msg<'a>(
|
|||||||
};
|
};
|
||||||
|
|
||||||
let mut in_binary = false;
|
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.
|
// Now we'll take the buffer that Nom gave a ref to and parse it.
|
||||||
let extension = if ext_len > 0 {
|
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
|
// 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.
|
// Err case. This error-error-error thing is the same idiom Nom uses internally.
|
||||||
let parsed = Extension::try_parse(processed_ext_buf).map_err(|_| {
|
let parsed = Extension::try_parse(processed_ext_buf).map_err(|_| {
|
||||||
@@ -126,11 +133,13 @@ fn bc_modern_msg<'a>(
|
|||||||
})?;
|
})?;
|
||||||
if let Extension {
|
if let Extension {
|
||||||
binary_data: Some(1),
|
binary_data: Some(1),
|
||||||
|
encrypt_len,
|
||||||
..
|
..
|
||||||
} = parsed
|
} = parsed
|
||||||
{
|
{
|
||||||
// In binary so tell the current context that we need to treat the payload as binary
|
// In binary so tell the current context that we need to treat the payload as binary
|
||||||
in_binary = true;
|
in_binary = true;
|
||||||
|
encrypted_len = encrypt_len;
|
||||||
}
|
}
|
||||||
Some(parsed)
|
Some(parsed)
|
||||||
} else {
|
} else {
|
||||||
@@ -149,22 +158,23 @@ fn bc_modern_msg<'a>(
|
|||||||
msg_id: 1,
|
msg_id: 1,
|
||||||
response_code,
|
response_code,
|
||||||
..
|
..
|
||||||
} if (response_code & 0xff) == 0x00 => EncryptionProtocol::Unencrypted,
|
} if (response_code >> 8) & 0xff == 0xdd => {
|
||||||
BcHeader {
|
// 0xdd means we are setting the encryption method
|
||||||
msg_id: 1,
|
// Durig login, the max encryption is BcEncrypt since
|
||||||
response_code,
|
// the nonce has not been exchanged yet
|
||||||
..
|
match response_code & 0xff {
|
||||||
} if (response_code & 0xff) == 0x01 => EncryptionProtocol::BCEncrypt,
|
0x00 => EncryptionProtocol::Unencrypted,
|
||||||
BcHeader {
|
_ => EncryptionProtocol::BCEncrypt,
|
||||||
msg_id: 1,
|
}
|
||||||
response_code,
|
}
|
||||||
..
|
BcHeader { msg_id: 1, .. } => {
|
||||||
} 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
|
match *context.get_encrypted() {
|
||||||
BcHeader { msg_id: 1, .. }
|
EncryptionProtocol::Aes(_) | EncryptionProtocol::FullAes(_) => {
|
||||||
if matches!(context.get_encrypted(), EncryptionProtocol::Aes(_)) =>
|
// During login max is BcEncrypt
|
||||||
{
|
EncryptionProtocol::BCEncrypt
|
||||||
// Maximum encryption level is BCEncrypt during login... Not sure why Reolink did it like that
|
}
|
||||||
EncryptionProtocol::BCEncrypt
|
n => n,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_ => *context.get_encrypted(),
|
_ => *context.get_encrypted(),
|
||||||
};
|
};
|
||||||
@@ -172,8 +182,25 @@ fn bc_modern_msg<'a>(
|
|||||||
let processed_payload_buf =
|
let processed_payload_buf =
|
||||||
xml_crypto::decrypt(header.channel_id as u32, payload_buf, &encryption_protocol);
|
xml_crypto::decrypt(header.channel_id as u32, payload_buf, &encryption_protocol);
|
||||||
if context.in_bin_mode.contains(&(header.msg_num)) || in_binary {
|
if context.in_bin_mode.contains(&(header.msg_num)) || in_binary {
|
||||||
payload = Some(BcPayloads::Binary(payload_buf.to_vec()));
|
payload = match (context.get_encrypted(), encrypted_len) {
|
||||||
|
(EncryptionProtocol::FullAes(_), Some(encrypted_len)) => {
|
||||||
|
// 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())),
|
||||||
|
};
|
||||||
} else {
|
} 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(|_| {
|
let xml = BcXml::try_parse(processed_payload_buf.as_slice()).map_err(|_| {
|
||||||
error!("header.msg_id: {}", header.msg_id);
|
error!("header.msg_id: {}", header.msg_id);
|
||||||
error!(
|
error!(
|
||||||
|
|||||||
@@ -128,6 +128,8 @@ pub enum LegacyMsg {
|
|||||||
/// Password for a legacy login
|
/// Password for a legacy login
|
||||||
password: String,
|
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
|
/// Any other type of legacy message will be collected here
|
||||||
UnknownMsg,
|
UnknownMsg,
|
||||||
}
|
}
|
||||||
@@ -198,6 +200,9 @@ pub enum EncryptionProtocol {
|
|||||||
/// Latest cameras/firmwares use Aes with the key derived from
|
/// Latest cameras/firmwares use Aes with the key derived from
|
||||||
/// the camera's password and the negotiated NONCE
|
/// the camera's password and the negotiated NONCE
|
||||||
Aes([u8; 16]),
|
Aes([u8; 16]),
|
||||||
|
/// Same as Aes but the media stream is also encrypted and not just
|
||||||
|
/// the control commands
|
||||||
|
FullAes([u8; 16]),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -205,6 +210,7 @@ pub(crate) struct BcContext {
|
|||||||
pub(crate) credentials: Credentials,
|
pub(crate) credentials: Credentials,
|
||||||
pub(crate) in_bin_mode: HashSet<u16>,
|
pub(crate) in_bin_mode: HashSet<u16>,
|
||||||
pub(crate) encryption_protocol: EncryptionProtocol,
|
pub(crate) encryption_protocol: EncryptionProtocol,
|
||||||
|
pub(crate) debug: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Bc {
|
impl Bc {
|
||||||
@@ -246,6 +252,7 @@ impl BcContext {
|
|||||||
credentials,
|
credentials,
|
||||||
in_bin_mode: HashSet::new(),
|
in_bin_mode: HashSet::new(),
|
||||||
encryption_protocol: EncryptionProtocol::Unencrypted,
|
encryption_protocol: EncryptionProtocol::Unencrypted,
|
||||||
|
debug: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -255,6 +262,7 @@ impl BcContext {
|
|||||||
credentials: Default::default(),
|
credentials: Default::default(),
|
||||||
in_bin_mode: HashSet::new(),
|
in_bin_mode: HashSet::new(),
|
||||||
encryption_protocol,
|
encryption_protocol,
|
||||||
|
debug: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -274,6 +282,10 @@ impl BcContext {
|
|||||||
pub(crate) fn binary_off(&mut self, msg_id: u16) {
|
pub(crate) fn binary_off(&mut self, msg_id: u16) {
|
||||||
self.in_bin_mode.remove(&msg_id);
|
self.in_bin_mode.remove(&msg_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn debug_on(&mut self) {
|
||||||
|
self.debug = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BcHeader {
|
impl BcHeader {
|
||||||
|
|||||||
@@ -130,6 +130,10 @@ fn bc_legacy<W: Write>(legacy: &'_ LegacyMsg) -> impl SerializeFn<W> + '_ {
|
|||||||
slice(&[0u8; 1772][..]),
|
slice(&[0u8; 1772][..]),
|
||||||
))(out)
|
))(out)
|
||||||
}
|
}
|
||||||
|
LoginUpgrade => {
|
||||||
|
// Write nothing as it is header only
|
||||||
|
slice(&[])(out)
|
||||||
|
}
|
||||||
UnknownMsg => {
|
UnknownMsg => {
|
||||||
panic!("Cannot serialize an unknown message!");
|
panic!("Cannot serialize an unknown message!");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -259,6 +259,15 @@ pub struct Extension {
|
|||||||
/// The rfID used in the PIR
|
/// The rfID used in the PIR
|
||||||
#[yaserde(rename = "rfId")]
|
#[yaserde(rename = "rfId")]
|
||||||
pub rf_id: Option<u8>,
|
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 {
|
impl Default for Extension {
|
||||||
@@ -270,6 +279,9 @@ impl Default for Extension {
|
|||||||
token: None,
|
token: None,
|
||||||
channel_id: None,
|
channel_id: None,
|
||||||
rf_id: None,
|
rf_id: None,
|
||||||
|
check_pos: None,
|
||||||
|
check_value: None,
|
||||||
|
encrypt_len: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -552,6 +564,9 @@ pub struct AlarmEvent {
|
|||||||
pub channel_id: u8,
|
pub channel_id: u8,
|
||||||
/// Motion status. Known values are `"MD"` or `"none"`
|
/// Motion status. Known values are `"MD"` or `"none"`
|
||||||
pub status: String,
|
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`
|
/// The recording status. Known values `0` or `1`
|
||||||
pub recording: i32,
|
pub recording: i32,
|
||||||
/// The timestamp associated with the recording. `0` if not recording
|
/// The timestamp associated with the recording. `0` if not recording
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ pub fn decrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol
|
|||||||
.map(|(key, i)| *i ^ key ^ (offset as u8))
|
.map(|(key, i)| *i ^ key ^ (offset as u8))
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
EncryptionProtocol::Aes(aeskey) => {
|
EncryptionProtocol::Aes(aeskey) | EncryptionProtocol::FullAes(aeskey) => {
|
||||||
// AES decryption
|
// AES decryption
|
||||||
|
|
||||||
let mut decrypted = buf.to_vec();
|
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
|
// Encrypt is the same as decrypt
|
||||||
decrypt(offset, buf, encryption_protocol)
|
decrypt(offset, buf, encryption_protocol)
|
||||||
}
|
}
|
||||||
EncryptionProtocol::Aes(aeskey) => {
|
EncryptionProtocol::Aes(aeskey) | EncryptionProtocol::FullAes(aeskey) => {
|
||||||
// AES encryption
|
// AES encryption
|
||||||
let mut encrypted = buf.to_vec();
|
let mut encrypted = buf.to_vec();
|
||||||
Aes128CfbEnc::new(aeskey.into(), IV.into()).encrypt(&mut encrypted);
|
Aes128CfbEnc::new(aeskey.into(), IV.into()).encrypt(&mut encrypted);
|
||||||
|
|||||||
+129
-67
@@ -85,10 +85,10 @@ pub struct BcCameraOpt {
|
|||||||
pub protocol: ConnectionProtocol,
|
pub protocol: ConnectionProtocol,
|
||||||
/// Discovery method to allow
|
/// Discovery method to allow
|
||||||
pub discovery: DiscoveryMethods,
|
pub discovery: DiscoveryMethods,
|
||||||
/// Printing format for auxilaary data such as battery levels
|
|
||||||
pub aux_printing: PrintFormat,
|
|
||||||
/// Credentials for login
|
/// Credentials for login
|
||||||
pub credentials: Credentials,
|
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
|
/// Used to choose the print format of various status messages like battery levels
|
||||||
@@ -126,6 +126,7 @@ impl BcCamera {
|
|||||||
/// Try to connect to the camera via appropaite methods and return
|
/// Try to connect to the camera via appropaite methods and return
|
||||||
/// the location that should be used
|
/// the location that should be used
|
||||||
async fn find_camera(options: &BcCameraOpt) -> Result<CameraLocation> {
|
async fn find_camera(options: &BcCameraOpt) -> Result<CameraLocation> {
|
||||||
|
let discovery = Discovery::new().await?;
|
||||||
if let ConnectionProtocol::Tcp | ConnectionProtocol::TcpUdp = options.protocol {
|
if let ConnectionProtocol::Tcp | ConnectionProtocol::TcpUdp = options.protocol {
|
||||||
let mut sockets = vec![];
|
let mut sockets = vec![];
|
||||||
match options.port {
|
match options.port {
|
||||||
@@ -145,7 +146,7 @@ impl BcCamera {
|
|||||||
info!("{}: Trying TCP discovery", options.name);
|
info!("{}: Trying TCP discovery", options.name);
|
||||||
for socket in sockets.drain(..) {
|
for socket in sockets.drain(..) {
|
||||||
let channel_id: u8 = options.channel_id;
|
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);
|
info!("{}: TCP Discovery success at {:?}", options.name, &socket);
|
||||||
socket
|
socket
|
||||||
}) {
|
}) {
|
||||||
@@ -184,62 +185,112 @@ impl BcCamera {
|
|||||||
DiscoveryMethods::Debug => (false, false, false, true),
|
DiscoveryMethods::Debug => (false, false, false, true),
|
||||||
};
|
};
|
||||||
|
|
||||||
if allow_local {
|
let res = tokio::select! {
|
||||||
let uid_local = uid.clone();
|
Ok(v) = async {
|
||||||
info!("{}: Trying local discovery", options.name);
|
let uid_local = uid.clone();
|
||||||
let result = Discovery::local(&uid_local, Some(sockets)).await;
|
info!("{}: Trying local discovery", options.name);
|
||||||
if let Ok(disc) = result {
|
let result = discovery.local(&uid_local, Some(sockets)).await;
|
||||||
info!(
|
match result {
|
||||||
"{}: Local discovery success {} at {}",
|
Ok(disc) => {
|
||||||
options.name,
|
info!(
|
||||||
uid_local,
|
"{}: Local discovery success {} at {}",
|
||||||
disc.get_addr()
|
options.name,
|
||||||
);
|
uid_local,
|
||||||
return Ok(CameraLocation::Udp(disc));
|
disc.get_addr()
|
||||||
}
|
);
|
||||||
}
|
Ok(CameraLocation::Udp(disc))
|
||||||
if allow_remote {
|
},
|
||||||
let uid_remote = uid.clone();
|
Err(e) => Err(e)
|
||||||
info!("{}: Trying remote discovery", options.name);
|
}
|
||||||
let result = Discovery::remote(&uid_remote).await;
|
}, if allow_local => Ok(v),
|
||||||
if let Ok(disc) = result {
|
Ok(v) = async {
|
||||||
info!(
|
let mut discovery = Discovery::new().await?;
|
||||||
"{}: Remote discovery success {} at {}",
|
let reg_result;
|
||||||
options.name,
|
// Registration is looped as it seems that reolink
|
||||||
uid_remote,
|
// only updates the registration lazily when someone attempts
|
||||||
disc.get_addr()
|
// to connect. The first few connects fails until the server data
|
||||||
);
|
// is updated
|
||||||
return Ok(CameraLocation::Udp(disc));
|
//
|
||||||
}
|
// We loop infinitly and allow the caller to timeout at the
|
||||||
}
|
// interval they desire
|
||||||
if allow_map {
|
let mut retry = 0;
|
||||||
let uid_map = uid.clone();
|
const MAX_RETRY: usize = 10;
|
||||||
info!("{}: Trying map discovery", options.name);
|
loop {
|
||||||
let result = Discovery::map(&uid_map).await;
|
tokio::task::yield_now().await;
|
||||||
if let Ok(disc) = result {
|
if let Ok(result) = discovery.get_registration(uid).await {
|
||||||
info!(
|
reg_result = result;
|
||||||
"{}: Map success {} at {}",
|
break;
|
||||||
options.name,
|
}
|
||||||
uid_map,
|
if retry >= MAX_RETRY {
|
||||||
disc.get_addr()
|
return Err(Error::DiscoveryTimeout);
|
||||||
);
|
}
|
||||||
return Ok(CameraLocation::Udp(disc));
|
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;
|
||||||
if allow_relay {
|
// New discovery to get new client IDs
|
||||||
let uid_relay = uid.clone();
|
discovery = Discovery::new().await?;
|
||||||
info!("{}: Trying relay discovery", options.name);
|
};
|
||||||
let result = Discovery::relay(&uid_relay).await;
|
tokio::select! {
|
||||||
if let Ok(disc) = result {
|
Ok(v) = async {
|
||||||
info!(
|
let uid_remote = uid.clone();
|
||||||
"{}: Relay success {} at {}",
|
info!("{}: Trying remote discovery", options.name);
|
||||||
options.name,
|
let result = discovery
|
||||||
uid_relay,
|
.remote(&uid_remote, ®_result)
|
||||||
disc.get_addr()
|
.await;
|
||||||
);
|
match result {
|
||||||
return Ok(CameraLocation::Udp(disc));
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("{}: Discovery failed", options.name);
|
info!("{}: Discovery failed", options.name);
|
||||||
@@ -265,16 +316,20 @@ impl BcCamera {
|
|||||||
let (sink, source): (BcConnSink, BcConnSource) = {
|
let (sink, source): (BcConnSink, BcConnSource) = {
|
||||||
match BcCamera::find_camera(options).await? {
|
match BcCamera::find_camera(options).await? {
|
||||||
CameraLocation::Tcp(addr) => {
|
CameraLocation::Tcp(addr) => {
|
||||||
let (x, r) = TcpSource::new(addr, &username, passwd.as_ref())
|
let (x, r) = TcpSource::new(addr, &username, passwd.as_ref(), options.debug)
|
||||||
.await?
|
.await?
|
||||||
.split();
|
.split();
|
||||||
(Box::new(x), Box::new(r))
|
(Box::new(x), Box::new(r))
|
||||||
}
|
}
|
||||||
CameraLocation::Udp(discovery) => {
|
CameraLocation::Udp(discovery) => {
|
||||||
let (x, r) =
|
let (x, r) = UdpSource::new_from_discovery(
|
||||||
UdpSource::new_from_discovery(discovery, &username, passwd.as_ref())
|
discovery,
|
||||||
.await?
|
&username,
|
||||||
.split();
|
passwd.as_ref(),
|
||||||
|
options.debug,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
.split();
|
||||||
(Box::new(x), Box::new(r))
|
(Box::new(x), Box::new(r))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -292,9 +347,6 @@ impl BcCamera {
|
|||||||
abilities: Default::default(),
|
abilities: Default::default(),
|
||||||
};
|
};
|
||||||
me.keepalive().await?;
|
me.keepalive().await?;
|
||||||
if let Err(e) = me.monitor_battery(options.aux_printing).await {
|
|
||||||
warn!("Could not monitor battery: {:?}", e);
|
|
||||||
}
|
|
||||||
Ok(me)
|
Ok(me)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -356,6 +408,16 @@ impl BcCamera {
|
|||||||
pub async fn join(&self) -> Result<()> {
|
pub async fn join(&self) -> Result<()> {
|
||||||
self.connection.join().await
|
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
|
/// The Baichuan library has a very peculiar behavior where it always zeros the last byte. I
|
||||||
|
|||||||
@@ -19,6 +19,9 @@ type MsgHandler = dyn 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct Subscriber {
|
struct Subscriber {
|
||||||
/// Subscribers based on their ID and their num
|
/// 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>>>>,
|
num: BTreeMap<u32, BTreeMap<Option<u16>, Sender<Result<Bc>>>>,
|
||||||
/// Subscribers based on their ID
|
/// Subscribers based on their ID
|
||||||
id: BTreeMap<u32, Arc<MsgHandler>>,
|
id: BTreeMap<u32, Arc<MsgHandler>>,
|
||||||
@@ -55,10 +58,12 @@ impl BcConnection {
|
|||||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
.build()
|
.build()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
runtime.block_on(
|
let result = runtime.block_on(
|
||||||
PollSender::new(thread_poll_commander)
|
PollSender::new(thread_poll_commander)
|
||||||
.send_all(&mut source.map(|bc| Ok(PollCommand::Bc(Box::new(bc))))),
|
.send_all(&mut source.map(|bc| Ok(PollCommand::Bc(Box::new(bc))))),
|
||||||
)
|
);
|
||||||
|
log::info!("PollSender Bc {:?}", result);
|
||||||
|
result
|
||||||
});
|
});
|
||||||
rx_thread.spawn(async move {
|
rx_thread.spawn(async move {
|
||||||
handle.await??;
|
handle.await??;
|
||||||
@@ -147,6 +152,15 @@ impl BcConnection {
|
|||||||
}
|
}
|
||||||
Ok(())
|
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 {
|
enum PollCommand {
|
||||||
@@ -154,6 +168,19 @@ enum PollCommand {
|
|||||||
AddHandler(u32, Arc<MsgHandler>),
|
AddHandler(u32, Arc<MsgHandler>),
|
||||||
RemoveHandler(u32),
|
RemoveHandler(u32),
|
||||||
AddSubscriber(u32, Option<u16>, Sender<Result<Bc>>),
|
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"),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Poller {
|
struct Poller {
|
||||||
@@ -166,16 +193,35 @@ impl Poller {
|
|||||||
async fn run(&mut self) -> Result<()> {
|
async fn run(&mut self) -> Result<()> {
|
||||||
while let Some(command) = self.reciever.next().await {
|
while let Some(command) = self.reciever.next().await {
|
||||||
yield_now().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 {
|
match command {
|
||||||
PollCommand::Bc(boxed_response) => {
|
PollCommand::Bc(boxed_response) => {
|
||||||
match *boxed_response {
|
match *boxed_response {
|
||||||
Ok(response) => {
|
Ok(response) => {
|
||||||
let msg_num = response.meta.msg_num;
|
|
||||||
let msg_id = response.meta.msg_id;
|
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 (
|
match (
|
||||||
self.subscribers.id.get(&msg_id),
|
self.subscribers.id.get(&msg_id),
|
||||||
self.subscribers.num.get_mut(&msg_id),
|
self.subscribers.num.get_mut(&msg_id), // Both filter first on ID
|
||||||
) {
|
) {
|
||||||
(Some(occ), _) => {
|
(Some(occ), _) => {
|
||||||
if let Some(reply) = occ(&response).await {
|
if let Some(reply) = occ(&response).await {
|
||||||
@@ -285,6 +331,7 @@ impl Poller {
|
|||||||
if occ_entry.get().is_closed() {
|
if occ_entry.get().is_closed() {
|
||||||
occ_entry.insert(tx);
|
occ_entry.insert(tx);
|
||||||
} else {
|
} else {
|
||||||
|
// log::error!("Failed to subscribe in bcconn to {:?} for {:?}", msg_num, msg_id);
|
||||||
let _ = tx
|
let _ = tx
|
||||||
.send(Err(Error::SimultaneousSubscription { msg_num }))
|
.send(Err(Error::SimultaneousSubscription { msg_num }))
|
||||||
.await;
|
.await;
|
||||||
@@ -292,6 +339,9 @@ impl Poller {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
PollCommand::Disconnect => {
|
||||||
|
return Err(Error::DroppedConnection);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use crate::bcudp::xml::*;
|
|||||||
use crate::{Error, Result};
|
use crate::{Error, Result};
|
||||||
use futures::{
|
use futures::{
|
||||||
sink::SinkExt,
|
sink::SinkExt,
|
||||||
stream::{FuturesUnordered, StreamExt},
|
stream::{FuturesUnordered, Stream, StreamExt},
|
||||||
};
|
};
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use local_ip_address::local_ip;
|
use local_ip_address::local_ip;
|
||||||
@@ -34,7 +34,7 @@ use tokio_stream::wrappers::ReceiverStream;
|
|||||||
use tokio_util::udp::UdpFramed;
|
use tokio_util::udp::UdpFramed;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
struct RegisterResult {
|
pub(crate) struct RegisterResult {
|
||||||
reg: SocketAddr,
|
reg: SocketAddr,
|
||||||
dev: Option<SocketAddr>,
|
dev: Option<SocketAddr>,
|
||||||
dmap: Option<SocketAddr>,
|
dmap: Option<SocketAddr>,
|
||||||
@@ -57,8 +57,6 @@ struct UidLookupResults {
|
|||||||
relay: SocketAddr,
|
relay: SocketAddr,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) struct Discovery {}
|
|
||||||
|
|
||||||
const MTU: u32 = 1350;
|
const MTU: u32 = 1350;
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref P2P_RELAY_HOSTNAMES: [&'static str; 10] = [
|
static ref P2P_RELAY_HOSTNAMES: [&'static str; 10] = [
|
||||||
@@ -80,12 +78,14 @@ lazy_static! {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Subscriber = Arc<RwLock<BTreeMap<u32, Sender<Result<(UdpDiscovery, SocketAddr)>>>>>;
|
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>>;
|
type ArcFramedSocket = UdpFramed<BcUdpCodex, Arc<UdpSocket>>;
|
||||||
pub(crate) struct Discoverer {
|
pub(crate) struct Discoverer {
|
||||||
socket: Arc<UdpSocket>,
|
socket: Arc<UdpSocket>,
|
||||||
handle: RwLock<JoinSet<()>>,
|
handle: RwLock<JoinSet<()>>,
|
||||||
writer: Sender<Result<(BcUdp, SocketAddr)>>,
|
writer: Sender<Result<(BcUdp, SocketAddr)>>,
|
||||||
subsribers: Subscriber,
|
subsribers: Subscriber,
|
||||||
|
handlers: Handlers,
|
||||||
local_addr: SocketAddr,
|
local_addr: SocketAddr,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,26 +98,27 @@ impl Discoverer {
|
|||||||
let (mut writer, mut reader) = inner.split();
|
let (mut writer, mut reader) = inner.split();
|
||||||
let mut set = JoinSet::new();
|
let mut set = JoinSet::new();
|
||||||
let subsribers: Subscriber = Default::default();
|
let subsribers: Subscriber = Default::default();
|
||||||
|
let handlers: Handlers = Default::default();
|
||||||
|
|
||||||
let thread_subscriber = subsribers.clone();
|
let thread_subscriber = subsribers.clone();
|
||||||
|
let thread_handlers = handlers.clone();
|
||||||
set.spawn(async move {
|
set.spawn(async move {
|
||||||
loop {
|
loop {
|
||||||
tokio::task::yield_now().await;
|
tokio::task::yield_now().await;
|
||||||
match reader.next().await {
|
match reader.next().await {
|
||||||
Some(Ok((BcUdp::Discovery(bcudp), addr))) => {
|
Some(Ok((BcUdp::Discovery(bcudp), addr))) => {
|
||||||
let mut tid = bcudp.tid;
|
let tid = bcudp.tid;
|
||||||
let mut needs_removal = false;
|
let mut needs_removal = false;
|
||||||
if let Some(sender) = thread_subscriber.read().await.get(&tid) {
|
if let (Some(sender), true) =
|
||||||
|
(thread_subscriber.read().await.get(&tid), tid > 0)
|
||||||
|
{
|
||||||
if sender.send(Ok((bcudp, addr))).await.is_err() {
|
if sender.send(Ok((bcudp, addr))).await.is_err() {
|
||||||
needs_removal = true;
|
needs_removal = true;
|
||||||
}
|
}
|
||||||
} else if let Some(any_sender) = thread_subscriber.read().await.get(&0) {
|
|
||||||
if any_sender.send(Ok((bcudp, addr))).await.is_err() {
|
|
||||||
tid = 0; // To make is remove 0
|
|
||||||
needs_removal = true;
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
trace!("Udp Discovery got this unexpected BcUdp {:?}", bcudp);
|
for sender in thread_handlers.write().await.iter_mut() {
|
||||||
|
let _ = sender.send(Ok((bcudp.clone(), addr))).await;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if needs_removal {
|
if needs_removal {
|
||||||
thread_subscriber.write().await.remove(&tid);
|
thread_subscriber.write().await.remove(&tid);
|
||||||
@@ -150,35 +151,43 @@ impl Discoverer {
|
|||||||
handle: RwLock::new(set),
|
handle: RwLock::new(set),
|
||||||
writer: sinker,
|
writer: sinker,
|
||||||
subsribers,
|
subsribers,
|
||||||
|
handlers,
|
||||||
local_addr,
|
local_addr,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn into_socket(self) -> (Arc<UdpSocket>, JoinSet<()>) {
|
async fn get_socket(&self) -> Arc<UdpSocket> {
|
||||||
let socket = self.socket.clone();
|
self.socket.clone()
|
||||||
let handle = self.handle.into_inner();
|
|
||||||
(socket, handle)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn subscribe(&self, tid: u32) -> Result<Receiver<Result<(UdpDiscovery, SocketAddr)>>> {
|
async fn subscribe(&self, tid: u32) -> Result<Receiver<Result<(UdpDiscovery, SocketAddr)>>> {
|
||||||
let mut subs = self.subsribers.write().await;
|
if tid > 0 {
|
||||||
match subs.entry(tid) {
|
let mut subs = self.subsribers.write().await;
|
||||||
Entry::Vacant(vacant) => {
|
match subs.entry(tid) {
|
||||||
let (tx, rx) = channel(10);
|
Entry::Vacant(vacant) => {
|
||||||
vacant.insert(tx);
|
|
||||||
Ok(rx)
|
|
||||||
}
|
|
||||||
Entry::Occupied(mut occ) => {
|
|
||||||
if occ.get().is_closed() {
|
|
||||||
let (tx, rx) = channel(10);
|
let (tx, rx) = channel(10);
|
||||||
occ.insert(tx);
|
vacant.insert(tx);
|
||||||
Ok(rx)
|
Ok(rx)
|
||||||
} else {
|
}
|
||||||
Err(Error::SimultaneousSubscription {
|
Entry::Occupied(mut occ) => {
|
||||||
msg_num: Some(tid as u16),
|
if occ.get().is_closed() {
|
||||||
})
|
let (tx, rx) = channel(10);
|
||||||
|
occ.insert(tx);
|
||||||
|
Ok(rx)
|
||||||
|
} else {
|
||||||
|
// log::error!("Failed to subscribe in discovery to {:?}", tid);
|
||||||
|
Err(Error::SimultaneousSubscription {
|
||||||
|
msg_num: Some(tid as u16),
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
// If tid is zero we listen to all!
|
||||||
|
let mut handlers = self.handlers.write().await;
|
||||||
|
let (tx, rx) = channel(10);
|
||||||
|
handlers.push(tx);
|
||||||
|
Ok(rx)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -214,32 +223,6 @@ impl Discoverer {
|
|||||||
&self.local_addr
|
&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>
|
async fn retry_send<F, T>(&self, mut disc: UdpDiscovery, dest: SocketAddr, map: F) -> Result<T>
|
||||||
where
|
where
|
||||||
F: Fn(UdpDiscovery, SocketAddr) -> Option<T>,
|
F: Fn(UdpDiscovery, SocketAddr) -> Option<T>,
|
||||||
@@ -357,13 +340,10 @@ impl Discoverer {
|
|||||||
Ok(result)
|
Ok(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This function will contact the p2p relay servers
|
async fn uid_lookup_all<'a>(
|
||||||
///
|
&'a self,
|
||||||
/// It will ask each of the servers for details on a specific UID
|
uid: &'a str,
|
||||||
///
|
) -> Result<impl Stream<Item = UidLookupResults> + 'a> {
|
||||||
/// 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 task = tokio::task::spawn_blocking(move || {
|
||||||
let mut addrs = vec![];
|
let mut addrs = vec![];
|
||||||
for p2p_relay in P2P_RELAY_HOSTNAMES.iter() {
|
for p2p_relay in P2P_RELAY_HOSTNAMES.iter() {
|
||||||
@@ -376,8 +356,22 @@ impl Discoverer {
|
|||||||
}
|
}
|
||||||
addrs
|
addrs
|
||||||
});
|
});
|
||||||
let addrs = timeout(*MAXIMUM_WAIT, task).await??;
|
let mut addrs = timeout(*MAXIMUM_WAIT, task).await??;
|
||||||
trace!("Uid lookup to: {:?}", addrs);
|
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 {
|
let msg = UdpDiscovery {
|
||||||
tid: 0,
|
tid: 0,
|
||||||
payload: UdpXml {
|
payload: UdpXml {
|
||||||
@@ -390,7 +384,7 @@ impl Discoverer {
|
|||||||
};
|
};
|
||||||
trace!("Sending look up {:?}", msg);
|
trace!("Sending look up {:?}", msg);
|
||||||
let (packet, _) = self
|
let (packet, _) = self
|
||||||
.retry_send_multi(msg, addrs.as_slice(), |bc, addr| match bc {
|
.retry_send(msg, addr, |bc, addr| match bc {
|
||||||
UdpDiscovery {
|
UdpDiscovery {
|
||||||
tid: _,
|
tid: _,
|
||||||
payload:
|
payload:
|
||||||
@@ -448,51 +442,103 @@ impl Discoverer {
|
|||||||
|
|
||||||
// Send and await acceptance
|
// Send and await acceptance
|
||||||
let (sid, dev, dmap, relay) = self
|
let (sid, dev, dmap, relay) = self
|
||||||
.retry_send(msg, lookup.reg, |bc, _| match bc {
|
.retry_send(msg, lookup.reg, |bc, socket| {
|
||||||
UdpDiscovery {
|
trace!("{}", socket.ip());
|
||||||
tid: _,
|
match bc {
|
||||||
payload:
|
UdpDiscovery {
|
||||||
UdpXml {
|
tid: _,
|
||||||
r2c_c_r:
|
payload:
|
||||||
Some(R2cCr {
|
UdpXml {
|
||||||
dmap,
|
r2c_c_r:
|
||||||
dev,
|
Some(R2cCr {
|
||||||
relay,
|
dmap,
|
||||||
sid,
|
dev,
|
||||||
rsp,
|
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))
|
} if (dev
|
||||||
&& rsp != -1 =>
|
.as_ref()
|
||||||
{
|
.map(|d| !d.ip.is_empty() && d.port > 0)
|
||||||
Some(Ok((sid, dev, dmap, relay)))
|
.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,
|
||||||
}
|
}
|
||||||
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??;
|
.await??;
|
||||||
|
|
||||||
@@ -939,15 +985,56 @@ impl Discoverer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Discovery {
|
||||||
|
discoverer: Discoverer,
|
||||||
|
client_id: i32,
|
||||||
|
}
|
||||||
|
|
||||||
impl Discovery {
|
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
|
// Check if TCP is possible
|
||||||
//
|
//
|
||||||
// To do this we send a dummy login and see if it replies with any BC packet
|
// To do this we send a dummy login and see if it replies with any BC packet
|
||||||
pub(crate) async fn check_tcp(addr: SocketAddr, channel_id: u8) -> Result<()> {
|
pub(crate) async fn check_tcp(&self, addr: SocketAddr, channel_id: u8) -> Result<()> {
|
||||||
let username = "admin";
|
let username = "admin";
|
||||||
let password = Some("123456");
|
let password = Some("123456");
|
||||||
let mut tcp_source =
|
let mut tcp_source = timeout(
|
||||||
timeout(*MAXIMUM_WAIT, TcpSource::new(addr, username, password)).await??;
|
*MAXIMUM_WAIT,
|
||||||
|
TcpSource::new(addr, username, password, false),
|
||||||
|
)
|
||||||
|
.await??;
|
||||||
|
|
||||||
let md5_username = md5_string(username, Md5Trunc::ZeroLast);
|
let md5_username = md5_string(username, Md5Trunc::ZeroLast);
|
||||||
let md5_password = password
|
let md5_password = password
|
||||||
@@ -979,18 +1066,17 @@ impl Discovery {
|
|||||||
|
|
||||||
// Perform UDP broadcast lookup and connection
|
// Perform UDP broadcast lookup and connection
|
||||||
pub(crate) async fn local(
|
pub(crate) async fn local(
|
||||||
|
&self,
|
||||||
uid: &str,
|
uid: &str,
|
||||||
mut optional_addrs: Option<Vec<SocketAddr>>,
|
mut optional_addrs: Option<Vec<SocketAddr>>,
|
||||||
) -> Result<DiscoveryResult> {
|
) -> Result<DiscoveryResult> {
|
||||||
let discoverer = Discoverer::new().await?;
|
|
||||||
|
|
||||||
let client_id = generate_cid();
|
|
||||||
let mut dests = get_broadcasts(&[2015, 2018])?;
|
let mut dests = get_broadcasts(&[2015, 2018])?;
|
||||||
if let Some(mut optional_addrs) = optional_addrs.take() {
|
if let Some(mut optional_addrs) = optional_addrs.take() {
|
||||||
trace!("Also sending to {:?}", optional_addrs);
|
trace!("Also sending to {:?}", optional_addrs);
|
||||||
dests.append(&mut optional_addrs);
|
dests.append(&mut optional_addrs);
|
||||||
}
|
}
|
||||||
let discoverer_ref = &discoverer;
|
let discoverer_ref = &self.discoverer;
|
||||||
|
let client_id = self.client_id;
|
||||||
let mut futures = FuturesUnordered::new();
|
let mut futures = FuturesUnordered::new();
|
||||||
for addr in dests.iter().copied() {
|
for addr in dests.iter().copied() {
|
||||||
futures.push(async move {
|
futures.push(async move {
|
||||||
@@ -1018,10 +1104,9 @@ impl Discovery {
|
|||||||
drop(futures);
|
drop(futures);
|
||||||
// drop(discoverer_ref);
|
// drop(discoverer_ref);
|
||||||
|
|
||||||
let (socket, keep_alive_tasks) = discoverer.into_socket().await;
|
let socket = self.discoverer.get_socket().await;
|
||||||
Ok(DiscoveryResult {
|
Ok(DiscoveryResult {
|
||||||
socket,
|
socket,
|
||||||
keep_alive_tasks,
|
|
||||||
addr: connect_result.addr,
|
addr: connect_result.addr,
|
||||||
camera_id: connect_result.camera_id,
|
camera_id: connect_result.camera_id,
|
||||||
client_id: connect_result.client_id,
|
client_id: connect_result.client_id,
|
||||||
@@ -1039,33 +1124,22 @@ impl Discovery {
|
|||||||
// This method is best when broadcasts are not possible but we can contact the camera
|
// This method is best when broadcasts are not possible but we can contact the camera
|
||||||
// directly
|
// directly
|
||||||
#[allow(unused)]
|
#[allow(unused)]
|
||||||
pub(crate) async fn remote(uid: &str) -> Result<DiscoveryResult> {
|
pub(crate) async fn remote(
|
||||||
|
&self,
|
||||||
|
uid: &str,
|
||||||
|
reg_result: &RegisterResult,
|
||||||
|
) -> Result<DiscoveryResult> {
|
||||||
trace!("Start remote");
|
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! {
|
let connect_result = tokio::select! {
|
||||||
v = discoverer.client_initiated_dev(®_result) => {v},
|
v = self.discoverer.client_initiated_dev(reg_result) => {v},
|
||||||
v = discoverer.device_initiated_dev(®_result) => {v},
|
v = self.discoverer.device_initiated_dev(reg_result) => {v},
|
||||||
}?;
|
}?;
|
||||||
trace!("connect_result: {:?}", connect_result);
|
trace!("connect_result: {:?}", connect_result);
|
||||||
|
let socket = self.discoverer.get_socket().await;
|
||||||
let (socket, keep_alive_tasks) = discoverer.into_socket().await;
|
|
||||||
Ok(DiscoveryResult {
|
Ok(DiscoveryResult {
|
||||||
socket,
|
socket,
|
||||||
keep_alive_tasks,
|
|
||||||
addr: connect_result.addr,
|
addr: connect_result.addr,
|
||||||
client_id,
|
client_id: self.client_id,
|
||||||
camera_id: connect_result.camera_id,
|
camera_id: connect_result.camera_id,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1078,27 +1152,15 @@ impl Discovery {
|
|||||||
//
|
//
|
||||||
// This method should be used when the camera is behind a NAT or firewall but we are
|
// This method should be used when the camera is behind a NAT or firewall but we are
|
||||||
// reachable
|
// reachable
|
||||||
pub(crate) async fn map(uid: &str) -> Result<DiscoveryResult> {
|
pub(crate) async fn map(&self, reg_result: &RegisterResult) -> Result<DiscoveryResult> {
|
||||||
let discoverer = Discoverer::new().await?;
|
let connect_result = self.discoverer.device_initiated_map(reg_result).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);
|
trace!("connect_result: {:?}", connect_result);
|
||||||
|
|
||||||
let (socket, keep_alive_tasks) = discoverer.into_socket().await;
|
let socket = self.discoverer.get_socket().await;
|
||||||
Ok(DiscoveryResult {
|
Ok(DiscoveryResult {
|
||||||
socket,
|
socket,
|
||||||
keep_alive_tasks,
|
|
||||||
addr: connect_result.addr,
|
addr: connect_result.addr,
|
||||||
client_id,
|
client_id: self.client_id,
|
||||||
camera_id: connect_result.camera_id,
|
camera_id: connect_result.camera_id,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1108,27 +1170,15 @@ impl Discovery {
|
|||||||
// This method should work if all else fails but it will require
|
// This method should work if all else fails but it will require
|
||||||
// us to trust reolink with our data once more...
|
// us to trust reolink with our data once more...
|
||||||
//
|
//
|
||||||
pub(crate) async fn relay(uid: &str) -> Result<DiscoveryResult> {
|
pub(crate) async fn relay(&self, reg_result: &RegisterResult) -> Result<DiscoveryResult> {
|
||||||
let discoverer = Discoverer::new().await?;
|
let connect_result = self.discoverer.client_initiated_relay(reg_result).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);
|
trace!("connect_result: {:?}", connect_result);
|
||||||
|
|
||||||
let (socket, keep_alive_tasks) = discoverer.into_socket().await;
|
let socket = self.discoverer.get_socket().await;
|
||||||
Ok(DiscoveryResult {
|
Ok(DiscoveryResult {
|
||||||
socket,
|
socket,
|
||||||
keep_alive_tasks,
|
|
||||||
addr: connect_result.addr,
|
addr: connect_result.addr,
|
||||||
client_id,
|
client_id: self.client_id,
|
||||||
camera_id: connect_result.camera_id,
|
camera_id: connect_result.camera_id,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
//!
|
//!
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::{net::UdpSocket, task::JoinSet};
|
use tokio::net::UdpSocket;
|
||||||
|
|
||||||
mod bcconn;
|
mod bcconn;
|
||||||
mod bcsub;
|
mod bcsub;
|
||||||
@@ -22,16 +22,11 @@ pub(crate) use self::{
|
|||||||
pub(crate) struct DiscoveryResult {
|
pub(crate) struct DiscoveryResult {
|
||||||
socket: Arc<UdpSocket>,
|
socket: Arc<UdpSocket>,
|
||||||
addr: SocketAddr,
|
addr: SocketAddr,
|
||||||
keep_alive_tasks: JoinSet<()>,
|
|
||||||
client_id: i32,
|
client_id: i32,
|
||||||
camera_id: i32,
|
camera_id: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DiscoveryResult {
|
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
|
/// Get the address discovered
|
||||||
pub(crate) fn get_addr(&self) -> &SocketAddr {
|
pub(crate) fn get_addr(&self) -> &SocketAddr {
|
||||||
&self.addr
|
&self.addr
|
||||||
|
|||||||
@@ -18,11 +18,17 @@ impl TcpSource {
|
|||||||
addr: SocketAddr,
|
addr: SocketAddr,
|
||||||
username: T,
|
username: T,
|
||||||
password: Option<U>,
|
password: Option<U>,
|
||||||
|
debug: bool,
|
||||||
) -> Result<TcpSource> {
|
) -> Result<TcpSource> {
|
||||||
let stream = connect_to(addr).await?;
|
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 {
|
Ok(Self {
|
||||||
inner: Framed::new(stream, BcCodex::new(Credentials::new(username, password))),
|
inner: Framed::new(stream, codex),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,20 +9,21 @@ use futures::{
|
|||||||
sink::{Sink, SinkExt},
|
sink::{Sink, SinkExt},
|
||||||
stream::{IntoAsyncRead, Stream, StreamExt, TryStreamExt},
|
stream::{IntoAsyncRead, Stream, StreamExt, TryStreamExt},
|
||||||
};
|
};
|
||||||
use log::*;
|
|
||||||
use rand::{seq::SliceRandom, thread_rng};
|
use rand::{seq::SliceRandom, thread_rng};
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::collections::VecDeque;
|
|
||||||
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
|
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
use tokio::sync::mpsc::channel;
|
||||||
use tokio::{
|
use tokio::{
|
||||||
net::UdpSocket,
|
net::UdpSocket,
|
||||||
time::{interval, Duration, Interval},
|
time::{interval, sleep, Duration, Instant, Interval, Sleep},
|
||||||
};
|
};
|
||||||
|
use tokio_stream::wrappers::ReceiverStream;
|
||||||
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
|
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
|
||||||
|
use tokio_util::sync::PollSender;
|
||||||
use tokio_util::{
|
use tokio_util::{
|
||||||
codec::{Decoder, Encoder, Framed},
|
codec::{Decoder, Encoder, Framed},
|
||||||
udp::UdpFramed,
|
udp::UdpFramed,
|
||||||
@@ -43,19 +44,23 @@ impl UdpSource {
|
|||||||
camera_id: i32,
|
camera_id: i32,
|
||||||
username: T,
|
username: T,
|
||||||
password: Option<U>,
|
password: Option<U>,
|
||||||
|
debug: bool,
|
||||||
) -> Result<Self> {
|
) -> Result<Self> {
|
||||||
let stream = Arc::new(connect().await?);
|
let stream = Arc::new(connect().await?);
|
||||||
|
|
||||||
Self::new_from_socket(stream, addr, client_id, camera_id, username, password).await
|
Self::new_from_socket(
|
||||||
|
stream, addr, client_id, camera_id, username, password, debug,
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
pub(crate) async fn new_from_discovery<T: Into<String>, U: Into<String>>(
|
pub(crate) async fn new_from_discovery<T: Into<String>, U: Into<String>>(
|
||||||
mut discovery: DiscoveryResult,
|
discovery: DiscoveryResult,
|
||||||
username: T,
|
username: T,
|
||||||
password: Option<U>,
|
password: Option<U>,
|
||||||
|
debug: bool,
|
||||||
) -> Result<Self> {
|
) -> Result<Self> {
|
||||||
// Ensure that the discovery keep alive are all stopped here
|
// Ensure that the discovery keep alive are all stopped here
|
||||||
// We now handle all coms in UdpSource
|
// We now handle all coms in UdpSource
|
||||||
discovery.shutdown().await;
|
|
||||||
Self::new_from_socket(
|
Self::new_from_socket(
|
||||||
discovery.socket,
|
discovery.socket,
|
||||||
discovery.addr,
|
discovery.addr,
|
||||||
@@ -63,6 +68,7 @@ impl UdpSource {
|
|||||||
discovery.camera_id,
|
discovery.camera_id,
|
||||||
username,
|
username,
|
||||||
password,
|
password,
|
||||||
|
debug,
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@@ -74,14 +80,17 @@ impl UdpSource {
|
|||||||
camera_id: i32,
|
camera_id: i32,
|
||||||
username: T,
|
username: T,
|
||||||
password: Option<U>,
|
password: Option<U>,
|
||||||
|
debug: bool,
|
||||||
) -> Result<Self> {
|
) -> Result<Self> {
|
||||||
let bcudp_source = BcUdpSource::new_from_socket(stream, addr).await?;
|
let bcudp_source = BcUdpSource::new_from_socket(stream, addr).await?;
|
||||||
let payload_source = bcudp_source.into_payload_source(client_id, camera_id);
|
let payload_source = bcudp_source.into_payload_source(client_id, camera_id).await;
|
||||||
let async_read = payload_source.into_async_read().compat();
|
let async_read = payload_source.into_async_read().compat();
|
||||||
let framed = Framed::new(
|
let codex = if debug {
|
||||||
async_read,
|
BcCodex::new_with_debug(Credentials::new(username, password))
|
||||||
BcCodex::new(Credentials::new(username, password)),
|
} else {
|
||||||
);
|
BcCodex::new(Credentials::new(username, password))
|
||||||
|
};
|
||||||
|
let framed = Framed::new(async_read, codex);
|
||||||
|
|
||||||
Ok(Self { inner: framed })
|
Ok(Self { inner: framed })
|
||||||
}
|
}
|
||||||
@@ -152,20 +161,12 @@ impl BcUdpSource {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn into_payload_source(self, client_id: i32, camera_id: i32) -> UdpPayloadSource {
|
pub(crate) async fn into_payload_source(
|
||||||
UdpPayloadSource {
|
self,
|
||||||
inner: self,
|
client_id: i32,
|
||||||
client_id,
|
camera_id: i32,
|
||||||
camera_id,
|
) -> UdpPayloadSource {
|
||||||
packets_sent: 0,
|
UdpPayloadSource::new(self, client_id, camera_id).await
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,6 +200,7 @@ impl Sink<(BcUdp, SocketAddr)> for BcUdpSource {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
|
#[derive(Debug)]
|
||||||
enum State {
|
enum State {
|
||||||
Normal, // Normal recieve
|
Normal, // Normal recieve
|
||||||
Flushing, // Used to send ack packets and things in the buffer
|
Flushing, // Used to send ack packets and things in the buffer
|
||||||
@@ -206,16 +208,72 @@ enum State {
|
|||||||
YieldNow, // Used to ensure we rest between polling packets so as to not starve the runtime
|
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 {
|
pub(crate) struct UdpPayloadSource {
|
||||||
|
inner_stream: ReceiverStream<IoResult<Vec<u8>>>,
|
||||||
|
inner_sink: PollSender<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct UdpPayloadInner {
|
||||||
inner: BcUdpSource,
|
inner: BcUdpSource,
|
||||||
|
thread_stream: PollSender<IoResult<Vec<u8>>>,
|
||||||
|
thread_sink: ReceiverStream<Vec<u8>>,
|
||||||
client_id: i32,
|
client_id: i32,
|
||||||
camera_id: i32,
|
camera_id: i32,
|
||||||
packets_sent: u32,
|
packets_sent: u32,
|
||||||
packets_want: u32,
|
packets_want: u32,
|
||||||
sent: BTreeMap<u32, UdpData>,
|
sent: BTreeMap<u32, UdpData>,
|
||||||
recieved: BTreeMap<u32, Vec<u8>>,
|
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
|
/// 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
|
/// seems to think we have a poor connection and will abort
|
||||||
/// This `ack_interval` controls how ofen we do this
|
/// This `ack_interval` controls how ofen we do this
|
||||||
@@ -223,9 +281,105 @@ pub(crate) struct UdpPayloadSource {
|
|||||||
/// Offical Client does resend every 500ms
|
/// Offical Client does resend every 500ms
|
||||||
/// This `resend_interval` controls how ofen we do this
|
/// This `resend_interval` controls how ofen we do this
|
||||||
resend_interval: Interval,
|
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 {
|
fn build_send_ack(&self) -> UdpAck {
|
||||||
if self.packets_want > 0 {
|
if self.packets_want > 0 {
|
||||||
let mut first_missing: u32 = self.packets_want;
|
let mut first_missing: u32 = self.packets_want;
|
||||||
@@ -254,6 +408,7 @@ impl UdpPayloadSource {
|
|||||||
connection_id: self.camera_id,
|
connection_id: self.camera_id,
|
||||||
packet_id: first_missing - 1, // Last we actually have is first_missing - 1
|
packet_id: first_missing - 1, // Last we actually have is first_missing - 1
|
||||||
group_id: 0,
|
group_id: 0,
|
||||||
|
maybe_latency: self.ack_latency.get_value(),
|
||||||
payload: missing_ids,
|
payload: missing_ids,
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -274,19 +429,41 @@ impl UdpPayloadSource {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
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);
|
||||||
|
|
||||||
fn maintanence(&mut self, cx: &mut Context<'_>) {
|
let mut payload_inner = UdpPayloadInner::new(
|
||||||
// Check for periodic resends
|
inner,
|
||||||
if self.resend_interval.poll_tick(cx).is_ready() {
|
PollSender::new(thread_stream),
|
||||||
for (_, resend) in self.sent.iter() {
|
ReceiverStream::new(thread_sink),
|
||||||
self.send_buffer.push_back(BcUdp::Data(resend.clone()));
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
if self.ack_interval.poll_tick(cx).is_ready() {
|
|
||||||
let ack = BcUdp::Ack(self.build_send_ack());
|
UdpPayloadSource {
|
||||||
self.send_buffer.push_back(ack);
|
inner_stream: ReceiverStream::new(inner_stream),
|
||||||
self.state = State::Flushing;
|
inner_sink: PollSender::new(inner_sink),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -294,105 +471,16 @@ impl UdpPayloadSource {
|
|||||||
impl Stream for UdpPayloadSource {
|
impl Stream for UdpPayloadSource {
|
||||||
type Item = IoResult<Vec<u8>>;
|
type Item = IoResult<Vec<u8>>;
|
||||||
|
|
||||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
delegate! {
|
||||||
let camera_addr = self.inner.addr;
|
to Pin::new(&mut self.inner_stream) {
|
||||||
let this = self.get_mut();
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
|
||||||
match this.state {
|
}
|
||||||
State::Normal => {
|
}
|
||||||
// this.state = State::YieldNow;
|
|
||||||
// Handle resend events
|
delegate! {
|
||||||
this.maintanence(cx);
|
to self.inner_stream {
|
||||||
// Data ready to go
|
fn size_hint(&self) -> (usize, Option<usize>);
|
||||||
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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -403,104 +491,35 @@ impl Sink<Vec<u8>> for UdpPayloadSource {
|
|||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||||
let this = self.get_mut();
|
self.get_mut()
|
||||||
match this.state {
|
.inner_sink
|
||||||
State::Normal | State::YieldNow => this
|
.poll_ready_unpin(cx)
|
||||||
.inner
|
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||||
.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> {
|
fn start_send(self: Pin<&mut Self>, item: Vec<u8>) -> std::result::Result<(), Self::Error> {
|
||||||
let this = self.get_mut();
|
self.get_mut()
|
||||||
for chunk in item.chunks(MTU - UDPDATA_HEADER_SIZE) {
|
.inner_sink
|
||||||
let udp_data = UdpData {
|
.start_send_unpin(item)
|
||||||
connection_id: this.camera_id,
|
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||||
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(
|
fn poll_flush(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||||
let this = self.get_mut();
|
self.get_mut()
|
||||||
match this
|
.inner_sink
|
||||||
.inner
|
|
||||||
.poll_flush_unpin(cx)
|
.poll_flush_unpin(cx)
|
||||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
.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(
|
fn poll_close(
|
||||||
self: Pin<&mut Self>,
|
self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||||
let this = self.get_mut();
|
self.get_mut()
|
||||||
if let State::Closed = this.state {
|
.inner_sink
|
||||||
return Poll::Ready(Ok(()));
|
.poll_close_unpin(cx)
|
||||||
}
|
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||||
|
|
||||||
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,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use super::{md5_string, BcCamera, Error, Result, Truncate, ZeroLast};
|
use super::{md5_string, BcCamera, Error, Result, Truncate};
|
||||||
use crate::bc::{model::*, xml::*};
|
use crate::bc::{model::*, xml::*};
|
||||||
use std::sync::atomic::Ordering;
|
use std::sync::atomic::Ordering;
|
||||||
|
|
||||||
@@ -48,17 +48,17 @@ impl BcCamera {
|
|||||||
// Note: I suspect there may be a buffer overflow opportunity in the firmware since in the
|
// 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
|
// 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.
|
// 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_username = md5_string(&credentials.username, ZeroLast);
|
||||||
let md5_password = credentials
|
// let md5_password = credentials
|
||||||
.password
|
// .password
|
||||||
.as_ref()
|
// .as_ref()
|
||||||
.map(|p| md5_string(p, ZeroLast))
|
// .map(|p| md5_string(p, ZeroLast))
|
||||||
.unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned());
|
// .unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned());
|
||||||
|
|
||||||
let enc_byte = match max_encryption {
|
let enc_byte = match max_encryption {
|
||||||
MaxEncryption::None => 0xdc00,
|
MaxEncryption::None => 0xdc00,
|
||||||
MaxEncryption::BcEncrypt => 0xdc01,
|
MaxEncryption::BcEncrypt => 0xdc01,
|
||||||
MaxEncryption::Aes => 0xdc02,
|
MaxEncryption::Aes => 0xdc12,
|
||||||
};
|
};
|
||||||
let legacy_login = Bc {
|
let legacy_login = Bc {
|
||||||
meta: BcMeta {
|
meta: BcMeta {
|
||||||
@@ -69,10 +69,7 @@ impl BcCamera {
|
|||||||
response_code: enc_byte,
|
response_code: enc_byte,
|
||||||
class: 0x6514,
|
class: 0x6514,
|
||||||
},
|
},
|
||||||
body: BcBody::LegacyMsg(LegacyMsg::LoginMsg {
|
body: BcBody::LegacyMsg(LegacyMsg::LoginUpgrade),
|
||||||
username: md5_username,
|
|
||||||
password: md5_password,
|
|
||||||
}),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
sub_login.send(legacy_login).await?;
|
sub_login.send(legacy_login).await?;
|
||||||
|
|||||||
@@ -232,10 +232,16 @@ impl BcCamera {
|
|||||||
let mut result = MotionStatus::NoChange(Instant::now());
|
let mut result = MotionStatus::NoChange(Instant::now());
|
||||||
for alarm_event in &alarm_event_list.alarm_events {
|
for alarm_event in &alarm_event_list.alarm_events {
|
||||||
if alarm_event.channel_id == channel_id {
|
if alarm_event.channel_id == channel_id {
|
||||||
if alarm_event.status == "MD" {
|
if alarm_event.status != "none"
|
||||||
|
|| alarm_event
|
||||||
|
.ai_type
|
||||||
|
.as_ref()
|
||||||
|
.map(|ai_type| ai_type != "none")
|
||||||
|
.unwrap_or(false)
|
||||||
|
{
|
||||||
result = MotionStatus::Start(Instant::now());
|
result = MotionStatus::Start(Instant::now());
|
||||||
break;
|
break;
|
||||||
} else if alarm_event.status == "none" {
|
} else {
|
||||||
result = MotionStatus::Stop(Instant::now());
|
result = MotionStatus::Stop(Instant::now());
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ impl BcCamera {
|
|||||||
|
|
||||||
sub_ping.recv().await?;
|
sub_ping.recv().await?;
|
||||||
|
|
||||||
|
log::trace!("Ping complete");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -57,6 +57,7 @@ impl BcCamera {
|
|||||||
..
|
..
|
||||||
}) = msg.body
|
}) = 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);
|
log::trace!("Got snap XML {} with size {}", filename, expected_size);
|
||||||
// Messages are now sent on ID 109 but not with the same message ID
|
// 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
|
// preumably because the camera considers it to be a new message rather
|
||||||
|
|||||||
@@ -4,12 +4,9 @@ use crate::{
|
|||||||
bcmedia::model::*,
|
bcmedia::model::*,
|
||||||
};
|
};
|
||||||
use futures::stream::StreamExt;
|
use futures::stream::StreamExt;
|
||||||
use std::sync::{
|
|
||||||
atomic::{AtomicBool, Ordering},
|
|
||||||
Arc,
|
|
||||||
};
|
|
||||||
use tokio::sync::mpsc::{channel, Receiver};
|
use tokio::sync::mpsc::{channel, Receiver};
|
||||||
use tokio::task::{self, JoinHandle};
|
use tokio::task::{self, JoinHandle};
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
/// The stream names supported by BC
|
/// The stream names supported by BC
|
||||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||||
@@ -33,7 +30,7 @@ pub enum StreamKind {
|
|||||||
pub struct StreamData {
|
pub struct StreamData {
|
||||||
handle: Option<JoinHandle<Result<()>>>,
|
handle: Option<JoinHandle<Result<()>>>,
|
||||||
rx: Receiver<Result<BcMedia>>,
|
rx: Receiver<Result<BcMedia>>,
|
||||||
abort_handle: Arc<AtomicBool>,
|
abort_handle: CancellationToken,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl StreamData {
|
impl StreamData {
|
||||||
@@ -42,12 +39,12 @@ impl StreamData {
|
|||||||
pub async fn get_data(&mut self) -> Result<Result<BcMedia>> {
|
pub async fn get_data(&mut self) -> Result<Result<BcMedia>> {
|
||||||
if let Some(handle) = self.handle.as_mut() {
|
if let Some(handle) = self.handle.as_mut() {
|
||||||
if handle.is_finished() {
|
if handle.is_finished() {
|
||||||
self.abort_handle.store(true, Ordering::Relaxed);
|
self.abort_handle.cancel();
|
||||||
handle.await??;
|
handle.await??;
|
||||||
return Err(Error::DroppedConnection);
|
return Err(Error::DroppedConnection);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
self.abort_handle.store(true, Ordering::Relaxed);
|
self.abort_handle.cancel();
|
||||||
return Err(Error::DroppedConnection);
|
return Err(Error::DroppedConnection);
|
||||||
}
|
}
|
||||||
// debug!("StreamData: Get");
|
// debug!("StreamData: Get");
|
||||||
@@ -58,16 +55,26 @@ impl StreamData {
|
|||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
// debug!("StreamData: Drop");
|
// debug!("StreamData: Drop");
|
||||||
self.abort_handle.store(true, Ordering::Relaxed);
|
self.abort_handle.cancel();
|
||||||
Err(Error::DroppedConnection)
|
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 {
|
impl Drop for StreamData {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.abort_handle.store(true, Ordering::Relaxed);
|
self.abort_handle.cancel();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,7 +107,7 @@ impl BcCamera {
|
|||||||
let connection = self.get_connection();
|
let connection = self.get_connection();
|
||||||
let msg_num = self.new_message_num();
|
let msg_num = self.new_message_num();
|
||||||
|
|
||||||
let abort_handle = Arc::new(AtomicBool::new(false));
|
let abort_handle = CancellationToken::new();
|
||||||
let abort_handle_thread = abort_handle.clone();
|
let abort_handle_thread = abort_handle.clone();
|
||||||
|
|
||||||
if buffer_size == 0 {
|
if buffer_size == 0 {
|
||||||
@@ -186,20 +193,20 @@ impl BcCamera {
|
|||||||
{
|
{
|
||||||
let mut media_sub = sub_video.bcmedia_stream(strict);
|
let mut media_sub = sub_video.bcmedia_stream(strict);
|
||||||
|
|
||||||
while !abort_handle_thread.load(Ordering::Relaxed) {
|
tokio::select! {
|
||||||
// debug!("Stream: Get");
|
_ = abort_handle_thread.cancelled() => {},
|
||||||
if let Some(bc_media) = media_sub.next().await {
|
_ = async {
|
||||||
// debug!("Stream: Got");
|
while let Some(bc_media) = media_sub.next().await {
|
||||||
// We now have a complete interesting packet. Send it to on the callback
|
// debug!("Stream: Got");
|
||||||
// debug!("Stream: Send");
|
// We now have a complete interesting packet. Send it to on the callback
|
||||||
if tx.send(bc_media).await.is_err() {
|
// debug!("Stream: Send");
|
||||||
// debug!("Stream: Dropped");
|
if tx.send(bc_media).await.is_err() {
|
||||||
break; // Connection dropped
|
// debug!("Stream: Dropped");
|
||||||
|
break; // Connection dropped
|
||||||
|
}
|
||||||
|
// debug!("Stream: Sent");
|
||||||
}
|
}
|
||||||
// debug!("Stream: Sent");
|
} => {}
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> {
|
|||||||
)(buf)?;
|
)(buf)?;
|
||||||
let (buf, packet_id) = error_context("Missing packet_id", le_u32)(buf)?; // This is the point at which the camera has contigious
|
let (buf, packet_id) = error_context("Missing packet_id", le_u32)(buf)?; // This is the point at which the camera has contigious
|
||||||
// packets to
|
// packets to
|
||||||
let (buf, _unknown) = error_context("ACK: Missing unknown", le_u32)(buf)?;
|
let (buf, maybe_latency) = error_context("ACK: Missing Maybe Latency", le_u32)(buf)?;
|
||||||
let (buf, payload_size) = error_context("ACK: Missing payload_size", le_u32)(buf)?;
|
let (buf, payload_size) = error_context("ACK: Missing payload_size", le_u32)(buf)?;
|
||||||
let (buf, payload) = if payload_size > 0 {
|
let (buf, payload) = if payload_size > 0 {
|
||||||
let (buf, t_payload) = take(payload_size)(buf)?; // It is a binary payload of
|
let (buf, t_payload) = take(payload_size)(buf)?; // It is a binary payload of
|
||||||
@@ -113,6 +113,7 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> {
|
|||||||
connection_id,
|
connection_id,
|
||||||
packet_id,
|
packet_id,
|
||||||
group_id,
|
group_id,
|
||||||
|
maybe_latency,
|
||||||
payload,
|
payload,
|
||||||
};
|
};
|
||||||
Ok((buf, data))
|
Ok((buf, data))
|
||||||
|
|||||||
@@ -68,8 +68,11 @@ pub struct UdpAck {
|
|||||||
pub group_id: u32,
|
pub group_id: u32,
|
||||||
/// The ID of the last data packet [`UdpData`]
|
/// The ID of the last data packet [`UdpData`]
|
||||||
pub packet_id: u32,
|
pub packet_id: u32,
|
||||||
// 2 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000`
|
/// 4 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000`, `09e00000`,
|
||||||
// Unknown but seems to change randomly every second
|
/// `0`, `54785`, `55062`, `2528`,
|
||||||
|
/// Unknown but seems to change randomly every second
|
||||||
|
/// Might be a latency for the recieved acknoledge packets
|
||||||
|
pub maybe_latency: u32,
|
||||||
// 2 Bytes size of a payload
|
// 2 Bytes size of a payload
|
||||||
//
|
//
|
||||||
/// Payload of `00 01 01 01 01` where `01` is added after every repeat
|
/// Payload of `00 01 01 01 01` where `01` is added after every repeat
|
||||||
@@ -86,6 +89,7 @@ impl UdpAck {
|
|||||||
connection_id,
|
connection_id,
|
||||||
group_id: 0xffffffff,
|
group_id: 0xffffffff,
|
||||||
packet_id: 0xffffffff,
|
packet_id: 0xffffffff,
|
||||||
|
maybe_latency: 0x0,
|
||||||
payload: vec![],
|
payload: vec![],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ fn bcudp_ack<'a, W: 'a + Write>(
|
|||||||
le_u32(0),
|
le_u32(0),
|
||||||
le_u32(payload.group_id),
|
le_u32(payload.group_id),
|
||||||
le_u32(payload.packet_id),
|
le_u32(payload.packet_id),
|
||||||
le_u32(0xd7160000),
|
le_u32(payload.maybe_latency),
|
||||||
le_u32(binary_payload.len() as u32),
|
le_u32(binary_payload.len() as u32),
|
||||||
slice(binary_payload),
|
slice(binary_payload),
|
||||||
))
|
))
|
||||||
|
|||||||
+61
-10
@@ -147,11 +147,14 @@ local message_types = {
|
|||||||
[106]="<Dst>",
|
[106]="<Dst>",
|
||||||
[107]="<Dst> (write)",
|
[107]="<Dst> (write)",
|
||||||
[108]="<ConfigFileInfo> (log)",
|
[108]="<ConfigFileInfo> (log)",
|
||||||
|
[109]="<Snap>",
|
||||||
[114]="<Uid>",
|
[114]="<Uid>",
|
||||||
[115]="<WifiSignal>",
|
[115]="<WifiSignal>",
|
||||||
|
[116]="<Wifi>",
|
||||||
[120]="<OnlineUserList>",
|
[120]="<OnlineUserList>",
|
||||||
[122]="<PerformanceInfo>",
|
[122]="<PerformanceInfo>",
|
||||||
[123]="<ReplaySeek>",
|
[123]="<ReplaySeek>",
|
||||||
|
[124]="<PushInfo>",
|
||||||
[132]="<VideoInput>", -- <InputAdvanceCfg>
|
[132]="<VideoInput>", -- <InputAdvanceCfg>
|
||||||
[133]="<RfAlarm>",
|
[133]="<RfAlarm>",
|
||||||
[141]="<Email> (test)",
|
[141]="<Email> (test)",
|
||||||
@@ -161,6 +164,7 @@ local message_types = {
|
|||||||
[151]="<AbilityInfo>",
|
[151]="<AbilityInfo>",
|
||||||
[190]="PTZ Preset",
|
[190]="PTZ Preset",
|
||||||
[194]="<Ftp> (test)",
|
[194]="<Ftp> (test)",
|
||||||
|
[195]="<AutoUpdate>",
|
||||||
[199]="<Support>",
|
[199]="<Support>",
|
||||||
[208]="<LedState>",
|
[208]="<LedState>",
|
||||||
[209]="<LedState> (write)",
|
[209]="<LedState> (write)",
|
||||||
@@ -175,9 +179,13 @@ local message_types = {
|
|||||||
[228]="<Crop>",
|
[228]="<Crop>",
|
||||||
[229]="<Crop> (write)",
|
[229]="<Crop> (write)",
|
||||||
[230]="<cropSnap>",
|
[230]="<cropSnap>",
|
||||||
|
[232]="<AudioTask>",
|
||||||
[234]="UDP Keep Alive",
|
[234]="UDP Keep Alive",
|
||||||
[252]="<BatteryInfoList>",
|
[252]="<BatteryInfoList>",
|
||||||
[253]="<BatteryInfo>",
|
[253]="<BatteryInfo>",
|
||||||
|
[268]="<CloudBindInfo>",
|
||||||
|
[282]="<CloudLoginKey>",
|
||||||
|
[287]="<TimeCfg>",
|
||||||
[272]="<findAlarmVideo>",
|
[272]="<findAlarmVideo>",
|
||||||
[273]="<alarmVideoInfo>",
|
[273]="<alarmVideoInfo>",
|
||||||
[274]="<findAlarmVideo>",
|
[274]="<findAlarmVideo>",
|
||||||
@@ -189,6 +197,7 @@ local message_classes = {
|
|||||||
[0x6514]="legacy",
|
[0x6514]="legacy",
|
||||||
[0x6614]="modern",
|
[0x6614]="modern",
|
||||||
[0x6414]="modern",
|
[0x6414]="modern",
|
||||||
|
[0x6482]="modern (file download)",
|
||||||
[0x0000]="modern",
|
[0x0000]="modern",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,9 +205,37 @@ local header_lengths = {
|
|||||||
[0x6514]=20,
|
[0x6514]=20,
|
||||||
[0x6614]=20,
|
[0x6614]=20,
|
||||||
[0x6414]=24,
|
[0x6414]=24,
|
||||||
|
[0x6482]=24,
|
||||||
[0x0000]=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 function xml_decrypt(ba, offset)
|
||||||
local key = "\031\045\060\075\090\105\120\255" -- 1f, 2d, 3c, 4b, 5a, 69, 78 ,ff
|
local key = "\031\045\060\075\090\105\120\255" -- 1f, 2d, 3c, 4b, 5a, 69, 78 ,ff
|
||||||
local e = ByteArray.new()
|
local e = ByteArray.new()
|
||||||
@@ -216,12 +253,14 @@ local function get_header_len(buffer)
|
|||||||
return -1 -- No header found
|
return -1 -- No header found
|
||||||
end
|
end
|
||||||
local header_len = header_lengths[buffer(18, 2):le_uint()]
|
local header_len = header_lengths[buffer(18, 2):le_uint()]
|
||||||
|
if (not header_len) then
|
||||||
|
return 20
|
||||||
|
end
|
||||||
return header_len
|
return header_len
|
||||||
end
|
end
|
||||||
|
|
||||||
local function get_header(buffer)
|
local function get_header(buffer)
|
||||||
-- bin_offset is either nil (no binary data) or nonzero
|
-- bin_offset is either nil (no binary data) or nonzero
|
||||||
-- TODO: bin_offset is actually stateful!
|
|
||||||
local bin_offset = nil
|
local bin_offset = nil
|
||||||
local return_code = nil
|
local return_code = nil
|
||||||
local encr_xml = nil
|
local encr_xml = nil
|
||||||
@@ -246,12 +285,11 @@ local function get_header(buffer)
|
|||||||
channel_id = buffer(12, 1):le_uint(),
|
channel_id = buffer(12, 1):le_uint(),
|
||||||
enc_offset = buffer(12, 1):le_uint(),
|
enc_offset = buffer(12, 1):le_uint(),
|
||||||
stream_type = stream_text,
|
stream_type = stream_text,
|
||||||
unknown = buffer(14, 1):le_uint(),
|
msg_handle = buffer(14, 2):le_uint(),
|
||||||
msg_handle = buffer(15, 1):le_uint(),
|
|
||||||
msg_cls = buffer(18, 2):le_uint(),
|
msg_cls = buffer(18, 2):le_uint(),
|
||||||
status_code = return_code,
|
status_code = return_code,
|
||||||
class = message_classes[buffer(18, 2):le_uint()],
|
class = message_classes[buffer(18, 2):le_uint()] or "unknown",
|
||||||
header_len = header_lengths[buffer(18, 2):le_uint()],
|
header_len = get_header_len(buffer(0, nil)),
|
||||||
bin_offset = bin_offset,
|
bin_offset = bin_offset,
|
||||||
}
|
}
|
||||||
end
|
end
|
||||||
@@ -275,8 +313,7 @@ local function process_header(buffer, headers_tree)
|
|||||||
header:add_le(channel_id, buffer(12, 1))
|
header:add_le(channel_id, buffer(12, 1))
|
||||||
header:add_le(stream_id, buffer(13, 1))
|
header:add_le(stream_id, buffer(13, 1))
|
||||||
:append_text(stream_text)
|
:append_text(stream_text)
|
||||||
header:add_le(unknown, buffer(14, 1))
|
header:add_le(msg_handle, buffer(14, 2))
|
||||||
header:add_le(msg_handle, buffer(15, 1))
|
|
||||||
|
|
||||||
header:add_le(message_class, buffer(18, 2)):append_text(" (" .. header_data.class .. ")")
|
header:add_le(message_class, buffer(18, 2)):append_text(" (" .. header_data.class .. ")")
|
||||||
|
|
||||||
@@ -312,7 +349,14 @@ local function process_body(header, body_buffer, bc_subtree, pinfo)
|
|||||||
local body_tvb = xml_buffer:tvb("Meta Payload")
|
local body_tvb = xml_buffer:tvb("Meta Payload")
|
||||||
body:add(body_tvb(), "Meta Payload")
|
body:add(body_tvb(), "Meta Payload")
|
||||||
if xml_len >= 4 then
|
if xml_len >= 4 then
|
||||||
if xml_decrypt(xml_buffer(0,5):bytes(), header.enc_offset):raw() == "<?xml" then -- Encrypted xml found
|
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
|
||||||
local ba = xml_buffer:bytes()
|
local ba = xml_buffer:bytes()
|
||||||
local decrypted = xml_decrypt(ba, header.enc_offset)
|
local decrypted = xml_decrypt(ba, header.enc_offset)
|
||||||
body_tvb = decrypted:tvb("Decrypted XML (in Meta Payload)")
|
body_tvb = decrypted:tvb("Decrypted XML (in Meta Payload)")
|
||||||
@@ -335,7 +379,14 @@ local function process_body(header, body_buffer, bc_subtree, pinfo)
|
|||||||
local body_tvb = binary_buffer:tvb("Main Payload");
|
local body_tvb = binary_buffer:tvb("Main Payload");
|
||||||
body:add(body_tvb(), "Main Payload")
|
body:add(body_tvb(), "Main Payload")
|
||||||
if bin_len > 4 then
|
if bin_len > 4 then
|
||||||
if xml_decrypt(binary_buffer(0,5):bytes(), header.enc_offset):raw() == "<?xml" then -- Encrypted xml found
|
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
|
||||||
local decrypted = xml_decrypt(binary_buffer:bytes(), header.enc_offset)
|
local decrypted = xml_decrypt(binary_buffer:bytes(), header.enc_offset)
|
||||||
body_tvb = decrypted:tvb("Decrypted XML (in Main Payload)")
|
body_tvb = decrypted:tvb("Decrypted XML (in Main Payload)")
|
||||||
-- Create a tree item that, when clicked, automatically shows the tab we just created
|
-- Create a tree item that, when clicked, automatically shows the tab we just created
|
||||||
@@ -643,7 +694,7 @@ local function udp_reassemple(udp_header, subbuffer, more, pinfo, tree)
|
|||||||
local needed = start_fragment.result
|
local needed = start_fragment.result
|
||||||
if needed == "DONE" then
|
if needed == "DONE" then
|
||||||
if start_fragment.message_id == udp_header.packet_count then
|
if start_fragment.message_id == udp_header.packet_count then
|
||||||
process_bc_message(start_fragment.buffer:tvb(), pinfo, tree)
|
process_bc_message(start_fragment.buffer:tvb("UDP Reassemble"), pinfo, tree)
|
||||||
end
|
end
|
||||||
elseif needed == "+1" then
|
elseif needed == "+1" then
|
||||||
-- Cannot handle in UDP...
|
-- Cannot handle in UDP...
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
use clap::Parser;
|
||||||
|
|
||||||
|
/// The battery command will dump the battery status to XML
|
||||||
|
#[derive(Parser, Debug)]
|
||||||
|
pub struct Opt {
|
||||||
|
/// The name of the camera. Must be a name in the config
|
||||||
|
pub camera: String,
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
///
|
||||||
|
/// # Neolink Battery
|
||||||
|
///
|
||||||
|
/// This module handles the printing of the Battery status
|
||||||
|
/// in xml format
|
||||||
|
///
|
||||||
|
/// # Usage
|
||||||
|
///
|
||||||
|
/// ```bash
|
||||||
|
/// neolink battery --config=config.toml CameraName
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
|
||||||
|
mod cmdline;
|
||||||
|
|
||||||
|
use super::config::Config;
|
||||||
|
use crate::utils::find_and_connect;
|
||||||
|
pub(crate) use cmdline::Opt;
|
||||||
|
|
||||||
|
/// Entry point for the battery subcommand
|
||||||
|
///
|
||||||
|
/// Opt is the command line options
|
||||||
|
pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||||
|
let camera = find_and_connect(&config, &opt.camera).await?;
|
||||||
|
|
||||||
|
let state = camera
|
||||||
|
.battery_info()
|
||||||
|
.await
|
||||||
|
.context("Unable to get camera Battery state")?;
|
||||||
|
let ser = String::from_utf8(
|
||||||
|
yaserde::ser::serialize_with_writer(&state, vec![], &Default::default())
|
||||||
|
.expect("Should Ser the struct"),
|
||||||
|
)
|
||||||
|
.expect("Should be UTF8");
|
||||||
|
println!("{}", ser);
|
||||||
|
|
||||||
|
let _ = camera.logout().await;
|
||||||
|
camera.disconnect().await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -25,4 +25,5 @@ pub enum Command {
|
|||||||
Talk(super::talk::Opt),
|
Talk(super::talk::Opt),
|
||||||
Mqtt(super::mqtt::Opt),
|
Mqtt(super::mqtt::Opt),
|
||||||
Image(super::image::Opt),
|
Image(super::image::Opt),
|
||||||
|
Battery(super::battery::Opt),
|
||||||
}
|
}
|
||||||
@@ -123,6 +123,12 @@ pub(crate) struct CameraConfig {
|
|||||||
|
|
||||||
#[serde(default = "default_true", alias = "splash")]
|
#[serde(default = "default_true", alias = "splash")]
|
||||||
pub(crate) use_splash: bool,
|
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)]
|
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||||
@@ -188,6 +194,10 @@ const fn default_true() -> bool {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const fn default_false() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
fn default_mqtt() -> Option<MqttConfig> {
|
fn default_mqtt() -> Option<MqttConfig> {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-1
@@ -20,7 +20,6 @@ enum GstControl {
|
|||||||
|
|
||||||
pub(super) struct GstSender {
|
pub(super) struct GstSender {
|
||||||
sender: Sender<GstControl>,
|
sender: Sender<GstControl>,
|
||||||
#[allow(dead_code)] // It is used for its automatic drop
|
|
||||||
set: JoinSet<Result<()>>,
|
set: JoinSet<Result<()>>,
|
||||||
finished: sync::oneshot::Receiver<Result<()>>,
|
finished: sync::oneshot::Receiver<Result<()>>,
|
||||||
}
|
}
|
||||||
@@ -49,6 +48,11 @@ 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>>(
|
pub(super) async fn from_input<T: AsRef<Path>>(
|
||||||
|
|||||||
@@ -81,6 +81,9 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
|||||||
}
|
}
|
||||||
debug!("Sending EOS");
|
debug!("Sending EOS");
|
||||||
let _ = sender.eos().await; // Ignore return because if pipeline is finished this will error
|
let _ = sender.eos().await; // Ignore return because if pipeline is finished this will error
|
||||||
|
let _ = sender.join().await;
|
||||||
|
|
||||||
|
let _ = stream_data.shutdown().await;
|
||||||
} else {
|
} else {
|
||||||
// Simply use the snap command
|
// Simply use the snap command
|
||||||
debug!("Using the snap command");
|
debug!("Using the snap command");
|
||||||
@@ -90,5 +93,8 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
|||||||
buffer.write_all(jpeg_data.as_slice()).await?;
|
buffer.write_all(jpeg_data.as_slice()).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let _ = camera.logout().await;
|
||||||
|
camera.disconnect().await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -29,6 +29,7 @@ use log::*;
|
|||||||
use std::fs;
|
use std::fs;
|
||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
|
|
||||||
|
mod battery;
|
||||||
mod cmdline;
|
mod cmdline;
|
||||||
mod config;
|
mod config;
|
||||||
mod image;
|
mod image;
|
||||||
@@ -115,6 +116,9 @@ async fn main() -> Result<()> {
|
|||||||
Some(Command::Image(opts)) => {
|
Some(Command::Image(opts)) => {
|
||||||
image::main(opts, config).await?;
|
image::main(opts, config).await?;
|
||||||
}
|
}
|
||||||
|
Some(Command::Battery(opts)) => {
|
||||||
|
battery::main(opts, config).await?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -198,6 +198,10 @@ impl EventCamThread {
|
|||||||
.context("Failed to login to the camera")??;
|
.context("Failed to login to the camera")??;
|
||||||
info!("{}: Connected and logged in", camera_config.name);
|
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?;
|
self.tx.send(Messages::Login).await?;
|
||||||
|
|
||||||
// Shararble cameras
|
// Shararble cameras
|
||||||
|
|||||||
@@ -95,6 +95,7 @@ pub(crate) async fn main(_: Opt, config: Config) -> Result<()> {
|
|||||||
for camera_config in config
|
for camera_config in config
|
||||||
.cameras
|
.cameras
|
||||||
.iter()
|
.iter()
|
||||||
|
.filter(|c| c.enabled)
|
||||||
.map(|a| Arc::new(a.clone()))
|
.map(|a| Arc::new(a.clone()))
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -44,5 +44,9 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
|||||||
.expect("Should be UTF8");
|
.expect("Should be UTF8");
|
||||||
println!("{}", pir_ser);
|
println!("{}", pir_ser);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let _ = camera.logout().await;
|
||||||
|
camera.disconnect().await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -90,5 +90,9 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
|||||||
.context("Unable to execute PTZ move command")?;
|
.context("Unable to execute PTZ move command")?;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let _ = camera.logout().await;
|
||||||
|
camera.disconnect().await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -29,5 +29,8 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
|||||||
.reboot()
|
.reboot()
|
||||||
.await
|
.await
|
||||||
.context("Could not send reboot command to the camera")?;
|
.context("Could not send reboot command to the camera")?;
|
||||||
|
|
||||||
|
camera.disconnect().await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
+1
-1
@@ -88,7 +88,7 @@ pub(crate) async fn main(_opt: Opt, mut config: Config) -> Result<()> {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
let mut cameras = vec![];
|
let mut cameras = vec![];
|
||||||
for camera_config in config.cameras.drain(..) {
|
for camera_config in config.cameras.drain(..).filter(|c| c.enabled) {
|
||||||
cameras
|
cameras
|
||||||
.push(Camera::<Disconnected>::new(camera_config, &config.users, rtsp.clone()).await?);
|
.push(Camera::<Disconnected>::new(camera_config, &config.users, rtsp.clone()).await?);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,6 +30,16 @@ impl Camera<Connected> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
timeout(self.state.camera.login_with_maxenc(max_encryption)).await??;
|
timeout(self.state.camera.login_with_maxenc(max_encryption)).await??;
|
||||||
|
|
||||||
|
if let Err(e) = self
|
||||||
|
.state
|
||||||
|
.camera
|
||||||
|
.monitor_battery(self.shared.config.print_format)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
log::warn!("Could not monitor battery: {:?}", e);
|
||||||
|
}
|
||||||
|
|
||||||
Ok(Camera {
|
Ok(Camera {
|
||||||
shared: self.shared,
|
shared: self.shared,
|
||||||
state: LoggedIn {
|
state: LoggedIn {
|
||||||
|
|||||||
@@ -33,5 +33,9 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
|||||||
.led_light_set(opt.on)
|
.led_light_set(opt.on)
|
||||||
.await
|
.await
|
||||||
.context("Unable to set camera light state")?;
|
.context("Unable to set camera light state")?;
|
||||||
|
|
||||||
|
let _ = camera.logout().await;
|
||||||
|
camera.disconnect().await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -86,5 +86,8 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
|||||||
.await
|
.await
|
||||||
.context("Talk stream ended early")?;
|
.context("Talk stream ended early")?;
|
||||||
|
|
||||||
|
let _ = camera.logout().await;
|
||||||
|
camera.disconnect().await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
+3
-2
@@ -17,7 +17,7 @@ pub(crate) fn timeout<F>(future: F) -> tokio::time::Timeout<F>
|
|||||||
where
|
where
|
||||||
F: std::future::Future,
|
F: std::future::Future,
|
||||||
{
|
{
|
||||||
tokio::time::timeout(tokio::time::Duration::from_secs(5), future)
|
tokio::time::timeout(tokio::time::Duration::from_secs(15), future)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) enum AddressOrUid {
|
pub(crate) enum AddressOrUid {
|
||||||
@@ -93,11 +93,11 @@ impl AddressOrUid {
|
|||||||
uid: camera_config.camera_uid.clone(),
|
uid: camera_config.camera_uid.clone(),
|
||||||
protocol: ConnectionProtocol::TcpUdp,
|
protocol: ConnectionProtocol::TcpUdp,
|
||||||
discovery: camera_config.discovery,
|
discovery: camera_config.discovery,
|
||||||
aux_printing: camera_config.print_format,
|
|
||||||
credentials: Credentials {
|
credentials: Credentials {
|
||||||
username: camera_config.username.clone(),
|
username: camera_config.username.clone(),
|
||||||
password: camera_config.password.clone(),
|
password: camera_config.password.clone(),
|
||||||
},
|
},
|
||||||
|
debug: camera_config.debug,
|
||||||
};
|
};
|
||||||
|
|
||||||
trace!("Camera Info: {:?}", options);
|
trace!("Camera Info: {:?}", options);
|
||||||
@@ -153,6 +153,7 @@ pub(crate) fn find_camera_by_name<'a>(config: &'a Config, name: &str) -> Result<
|
|||||||
config
|
config
|
||||||
.cameras
|
.cameras
|
||||||
.iter()
|
.iter()
|
||||||
|
.filter(|c| c.enabled)
|
||||||
.find(|c| c.name == name)
|
.find(|c| c.name == name)
|
||||||
.ok_or_else(|| anyhow!("Camera {} not found in the config file", name))
|
.ok_or_else(|| anyhow!("Camera {} not found in the config file", name))
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user