Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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']
|
||||||
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.16"
|
||||||
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.16" }
|
||||||
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.16"
|
||||||
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"
|
||||||
|
|||||||
+107
-57
@@ -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,101 @@ 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();
|
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 => v,
|
||||||
if let Ok(disc) = result {
|
v = async {
|
||||||
info!(
|
let reg_result;
|
||||||
"{}: Remote discovery success {} at {}",
|
// Registration is looped as it seems that reolink
|
||||||
options.name,
|
// only updates the registration lazily when someone attempts
|
||||||
uid_remote,
|
// to connect. The first few connects fails until the server data
|
||||||
disc.get_addr()
|
// is updated
|
||||||
);
|
//
|
||||||
return Ok(CameraLocation::Udp(disc));
|
// We loop infinitly and allow the caller to timeout at the
|
||||||
}
|
// interval they desire
|
||||||
}
|
loop {
|
||||||
if allow_map {
|
tokio::task::yield_now().await;
|
||||||
let uid_map = uid.clone();
|
if let Ok(result) = discovery.get_registration(uid).await {
|
||||||
info!("{}: Trying map discovery", options.name);
|
reg_result = result;
|
||||||
let result = Discovery::map(&uid_map).await;
|
break;
|
||||||
if let Ok(disc) = result {
|
}
|
||||||
info!(
|
log::debug!("Registration failed. Retrying");
|
||||||
"{}: Map success {} at {}",
|
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
|
||||||
options.name,
|
};
|
||||||
uid_map,
|
tokio::select! {
|
||||||
disc.get_addr()
|
v = async {
|
||||||
);
|
let uid_remote = uid.clone();
|
||||||
return Ok(CameraLocation::Udp(disc));
|
info!("{}: Trying remote discovery", options.name);
|
||||||
}
|
let result = discovery
|
||||||
}
|
.remote(&uid_remote, ®_result)
|
||||||
if allow_relay {
|
.await;
|
||||||
let uid_relay = uid.clone();
|
match result {
|
||||||
info!("{}: Trying relay discovery", options.name);
|
Ok(disc) => {
|
||||||
let result = Discovery::relay(&uid_relay).await;
|
info!(
|
||||||
if let Ok(disc) = result {
|
"{}: Remote discovery success {} at {}",
|
||||||
info!(
|
options.name,
|
||||||
"{}: Relay success {} at {}",
|
uid_remote,
|
||||||
options.name,
|
disc.get_addr()
|
||||||
uid_relay,
|
);
|
||||||
disc.get_addr()
|
Ok(CameraLocation::Udp(disc))
|
||||||
);
|
},
|
||||||
return Ok(CameraLocation::Udp(disc));
|
Err(e) => Err(e)
|
||||||
}
|
}
|
||||||
}
|
}, if allow_remote => v,
|
||||||
|
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 => v,
|
||||||
|
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 => v,
|
||||||
|
}
|
||||||
|
}, if allow_remote || allow_map || allow_relay => v,
|
||||||
|
}?;
|
||||||
|
|
||||||
|
return Ok(res);
|
||||||
}
|
}
|
||||||
|
|
||||||
info!("{}: Discovery failed", options.name);
|
info!("{}: Discovery failed", options.name);
|
||||||
@@ -356,6 +396,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
|
||||||
|
|||||||
@@ -147,6 +147,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 +163,7 @@ 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,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Poller {
|
struct Poller {
|
||||||
@@ -292,6 +302,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] = [
|
||||||
@@ -154,10 +152,8 @@ impl Discoverer {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
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)>>> {
|
||||||
@@ -214,32 +210,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 +327,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 +343,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 +371,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:
|
||||||
@@ -464,9 +445,18 @@ impl Discoverer {
|
|||||||
}),
|
}),
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
} if (dev.as_ref().map(|d| !d.ip.is_empty()).unwrap_or(false)
|
} if (dev
|
||||||
|| dmap.as_ref().map(|d| !d.ip.is_empty()).unwrap_or(false)
|
.as_ref()
|
||||||
|| relay.as_ref().map(|d| !d.ip.is_empty()).unwrap_or(false))
|
.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 =>
|
&& rsp != -1 =>
|
||||||
{
|
{
|
||||||
Some(Ok((sid, dev, dmap, relay)))
|
Some(Ok((sid, dev, dmap, relay)))
|
||||||
@@ -485,9 +475,18 @@ impl Discoverer {
|
|||||||
}),
|
}),
|
||||||
..
|
..
|
||||||
},
|
},
|
||||||
} if (dev.as_ref().map(|d| !d.ip.is_empty()).unwrap_or(false)
|
} if (dev
|
||||||
|| dmap.as_ref().map(|d| !d.ip.is_empty()).unwrap_or(false)
|
.as_ref()
|
||||||
|| relay.as_ref().map(|d| !d.ip.is_empty()).unwrap_or(false))
|
.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 =>
|
&& rsp == -1 =>
|
||||||
{
|
{
|
||||||
Some(Err(Error::RegisterError))
|
Some(Err(Error::RegisterError))
|
||||||
@@ -939,11 +938,49 @@ 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 =
|
||||||
@@ -979,18 +1016,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 +1054,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 +1074,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 +1102,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 +1120,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
|
||||||
|
|||||||
@@ -49,13 +49,12 @@ impl UdpSource {
|
|||||||
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).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>,
|
||||||
) -> 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,
|
||||||
|
|||||||
@@ -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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+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(())
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user