Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e7a244a1ab | ||
|
|
b978809a59 | ||
|
|
6b35db8fbe | ||
|
|
c3f3ecdb83 | ||
|
|
f99df6e5e7 | ||
|
|
e09d9d30dc | ||
|
|
c2f0b5b2d9 | ||
|
|
472eda9f06 |
No files matched your search
@@ -1,9 +1,6 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
on: [push, pull_request, workflow_dispatch]
|
||||
|
||||
jobs:
|
||||
pre_job:
|
||||
@@ -198,23 +195,8 @@ jobs:
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
registry: docker.io
|
||||
username: ${{ vars.DOCKER_USERNAME || steps.string_user.outputs.lowercase }}
|
||||
username: ${{ steps.string_user.outputs.lowercase }}
|
||||
password: ${{ secrets.DOCKER_TOKEN }}
|
||||
- name: Set Docker name with owner (package name) depending on if DOCKER_USERNAME is set
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
id: docker_repo
|
||||
shell: bash
|
||||
run: |
|
||||
if [ -z $DOCKER_USERNAME ]; then
|
||||
echo "DOCKER_NWO=${GITHUB_NWO}" >> $GITHUB_OUTPUT
|
||||
else
|
||||
IFS='/' read -ra NWO_SPLIT <<< "$GITHUB_NWO"
|
||||
REPO_NAME=${NWO_SPLIT[1]}
|
||||
echo "DOCKER_NWO=${DOCKER_USERNAME}/${REPO_NAME}" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
env:
|
||||
DOCKER_USERNAME: ${{ vars.DOCKER_USERNAME }}
|
||||
GITHUB_NWO: ${{ steps.string_repo.outputs.lowercase }}
|
||||
- name: Get tag name
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
id: tags
|
||||
@@ -244,7 +226,7 @@ jobs:
|
||||
echo "TAGS=${tagstr}"
|
||||
echo "TAGS=${tagstr}" >> "${GITHUB_OUTPUT}"
|
||||
env:
|
||||
REPO_NAME: ${{ steps.docker_repo.outputs.DOCKER_NWO }}
|
||||
REPO_NAME: ${{ steps.string_repo.outputs.lowercase }}
|
||||
- name: Install latest rust
|
||||
run: |
|
||||
rustup toolchain install stable
|
||||
@@ -290,7 +272,7 @@ jobs:
|
||||
push: true
|
||||
file: Dockerfile
|
||||
tags: ${{ steps.tags.outputs.TAGS }}
|
||||
build-args: VERSION=${{ steps.toml.outputs.version }}, REPO=${{ github.repository }}, OWNER=${{ vars.DOCKER_USERNAME || github.repository_owner }}
|
||||
build-args: VERSION=${{ steps.toml.outputs.version }}, REPO=${{ github.repository }}, OWNER=${{ github.repository_owner }}
|
||||
env:
|
||||
DOCKER_BUILDKIT: 1
|
||||
|
||||
|
||||
@@ -143,5 +143,5 @@ jobs:
|
||||
env:
|
||||
DAYS: "100"
|
||||
REPO_NAME: ${{ steps.string_repo.outputs.lowercase }}
|
||||
OWNER: ${{ vars.DOCKER_USERNAME || steps.string_user.outputs.lowercase }}
|
||||
TOKEN: ${{ secrets.DOCKER_PRUNE_TOKEN }}
|
||||
OWNER: ${{ steps.string_user.outputs.lowercase }}
|
||||
TOKEN: ${{ secrets.DOCKER_PRUNE__TOKEN }}
|
||||
@@ -24,11 +24,11 @@ jobs:
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: apt install gstreamer
|
||||
- name: apt install gstreamer and deps
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y aptitude
|
||||
sudo aptitude install -y libgstrtspserver-1.0-dev libgstreamer1.0-dev libgtk2.0-dev
|
||||
sudo aptitude install -y libgstrtspserver-1.0-dev libgstreamer1.0-dev libgtk2.0-dev protobuf-compiler
|
||||
- name: Install nightly rust
|
||||
run: |
|
||||
rustup toolchain install nightly --component clippy
|
||||
|
||||
@@ -15,8 +15,6 @@
|
||||
# Committing IntelliJ project files is a violation of intergalactic law
|
||||
.idea/
|
||||
|
||||
# We prefer to keep .vscode files outside the repo
|
||||
.vscode/
|
||||
# MacOS
|
||||
.DS_Store
|
||||
._.DS_Store
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
MD013:
|
||||
code_blocks: false
|
||||
@@ -16,4 +16,5 @@ repos:
|
||||
hooks:
|
||||
- id: markdownlint-fix
|
||||
files: README.md
|
||||
args: [--disable, MD041, --]
|
||||
|
||||
Generated
+587
-72
File diff suppressed because it is too large.
Load diff
+4
-7
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "neolink"
|
||||
description = "A standards-compliant bridge to Reolink IP cameras"
|
||||
version = "0.5.14"
|
||||
version = "0.5.11"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
@@ -13,7 +13,6 @@ members = [
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.70"
|
||||
base64 = "0.21.2"
|
||||
byte-slice-cast = "1.2.2"
|
||||
clap = { version = "4.2.2", features = ["derive", "cargo"] }
|
||||
console-subscriber = "0.1.8"
|
||||
@@ -24,16 +23,14 @@ gstreamer = "0.20.3"
|
||||
gstreamer-app = "0.20.0"
|
||||
gstreamer-rtsp = "0.20.0"
|
||||
gstreamer-rtsp-server = { version = "0.20.3", features = ["v1_16"] }
|
||||
heck = "0.4.1"
|
||||
is_sorted = "0.1.1"
|
||||
itertools = "0.11.0"
|
||||
itertools = "0.10.5"
|
||||
lazy_static = "1.4.0"
|
||||
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
|
||||
neolink_core = { path = "crates/core", version = "0.5.14" }
|
||||
neolink_core = { path = "crates/core", version = "0.5.11" }
|
||||
regex = "1.7.3"
|
||||
rumqttc = "0.22.0"
|
||||
rumqttc = "0.20.0"
|
||||
serde = { version = "1.0.160", features = ["derive"] }
|
||||
serde_json = "1.0.96"
|
||||
time = "0.3.20"
|
||||
tokio = { version = "1.27.0", features = ["rt-multi-thread", "macros", "io-util", "tracing"] }
|
||||
tokio-stream = "0.1.12"
|
||||
|
||||
+1
-2
@@ -54,8 +54,7 @@ RUN apt-get update && \
|
||||
gstreamer1.0-x \
|
||||
gstreamer1.0-plugins-base \
|
||||
gstreamer1.0-plugins-good \
|
||||
gstreamer1.0-plugins-bad \
|
||||
gstreamer1.0-libav && \
|
||||
gstreamer1.0-plugins-bad && \
|
||||
apt-get clean -y && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=build \
|
||||
|
||||
@@ -145,17 +145,6 @@ In the `[[cameras]]` section of the toml.
|
||||
Possible values are `local`, `remote`, `map`, `relay` later values implictly
|
||||
enable prior methods.
|
||||
|
||||
#### Cellular
|
||||
|
||||
Cellular cameras should select `"cellular"` which only enables `map` and
|
||||
`relay` since `local` and `remote` will always fail
|
||||
|
||||
```toml
|
||||
discovery = "cellular"
|
||||
```
|
||||
|
||||
See the sample config file for more details.
|
||||
|
||||
### MQTT
|
||||
|
||||
To use mqtt you will to adjust your config file as such:
|
||||
@@ -190,10 +179,8 @@ Control messages:
|
||||
- `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light
|
||||
detection
|
||||
- `/control/reboot` Reboot the camera
|
||||
- `/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
|
||||
- `/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/pir [on|off]`
|
||||
|
||||
Status Messages:
|
||||
@@ -203,66 +190,13 @@ Status Messages:
|
||||
- `/status disconnected` Sent when the camera goes offline
|
||||
- `/status/battery` Sent in reply to a `/query/battery` an XML encoded version
|
||||
of the battery status
|
||||
- `/status/battery_level` A simple % value of current battery level
|
||||
- `/status/pir` Sent in reply to a `/query/pir` an XML encoded version of the
|
||||
pir status
|
||||
- `/status/motion` Contains the motion detection alarm status. `on` for motion and `off` for still
|
||||
- `/status/ptz/preset` Sent in reply to a `/query/ptz/preset` an XML encoded version of the
|
||||
PTZ presets
|
||||
- `/status/preview` a base64 encoded camera image updated every 0.5s
|
||||
|
||||
Query Messages:
|
||||
|
||||
- `/query/battery` Request that the camera reports its battery level
|
||||
- `/query/pir` Request that the camera reports its pir status
|
||||
- `/query/ptz/preset` Request that the camera reports its PTZ presets
|
||||
|
||||
### MQTT Disable Features
|
||||
|
||||
Certain features like preview and motion detection may not be desired
|
||||
you can disable them by them with the following config options.
|
||||
Disabling these may help to conserve battery
|
||||
|
||||
```toml
|
||||
enable_motion = false # motion detection
|
||||
# (limited battery drain since it
|
||||
# is a passive listening connection)
|
||||
|
||||
enable_pings = false # keep alive pings that keep the camera connected
|
||||
|
||||
enable_light = false # flood lights only avaliable on some camera
|
||||
# (limited battery drain since it
|
||||
# is a passive listening connection)
|
||||
|
||||
enable_battery = false # battery updates in `/status/battery_level`
|
||||
|
||||
enable_preview = false # preview image in `/status/preview`
|
||||
```
|
||||
|
||||
#### MQTT Discovery
|
||||
|
||||
[MQTT Discovery](https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery) is partially supported.
|
||||
Currently, discovery is opt-in and camera features must be manually specified.
|
||||
|
||||
```toml
|
||||
[cameras.mqtt]
|
||||
# <see above>
|
||||
[cameras.mqtt.discovery]
|
||||
topic = "homeassistant"
|
||||
features = ["floodlight"]
|
||||
```
|
||||
|
||||
Avaliable features are:
|
||||
|
||||
- `floodlight`: This adds a light control to home assistant
|
||||
- `camera`: This adds a camera preview to home assistant. It is only updated every 0.5s and cannot be much more than that since it is updated over mqtt not over RTSP
|
||||
- `led`: This adds a switch to chage the LED status light on/off to home assistant
|
||||
- `ir`: This adds a selection switch to chage the IR light on/off/auto to home assistant
|
||||
- `motion`: This adds a motion detection binary sensor to home assistant
|
||||
- `reboot`: This adds a reboot button to home assistant
|
||||
- `pt`: This adds a selection of buttons to control the pan and tilt of the camera
|
||||
- `battery`: This adds a battery level sensor to home assistant
|
||||
|
||||
|
||||
### Pause
|
||||
|
||||
@@ -306,18 +240,11 @@ passed by a script for processing.
|
||||
|
||||
[Docker](https://hub.docker.com/r/quantumentangledandy/neolink) builds are also
|
||||
provided in multiple architectures. The latest tag tracks master while each
|
||||
|
||||
branch gets it's own tag.
|
||||
|
||||
```bash
|
||||
docker pull quantumentangledandy/neolink
|
||||
|
||||
# Add `-e "RUST_LOG=debug"` to run with debug logs
|
||||
#
|
||||
# --network host is only needed if you require to connect
|
||||
# via local broadcasts. If you can connect via any other
|
||||
# method then normal bridge mode should work fine
|
||||
# and you can ommit this option
|
||||
docker run --network host --volume=$PWD/config.toml:/etc/neolink.toml quantumentangledandy/neolink
|
||||
```
|
||||
|
||||
### Image
|
||||
@@ -328,10 +255,11 @@ You can write an image from the stream to disk using:
|
||||
neolink image --config=config.toml --file-path=filepath CameraName
|
||||
```
|
||||
|
||||
Where filepath is the path to save the image to and CameraName is the name of
|
||||
Where filepath is the path to save the image to and CameraName is the name o
|
||||
the camera from the config to save the image from.
|
||||
|
||||
File is always jpeg and the extension given in filepath will be added or changed
|
||||
|
||||
to reflect this.
|
||||
|
||||
## License
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "neolink_core"
|
||||
description = "Core services and structure for Reolink IP cameras"
|
||||
version = "0.5.14"
|
||||
version = "0.5.11"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
@@ -13,7 +13,7 @@ cfb-mode = "0.8.2"
|
||||
cookie-factory = "0.3.2"
|
||||
crc32fast = "1.3.2"
|
||||
crossbeam-channel = "0.5.8"
|
||||
delegate = "0.10.0"
|
||||
delegate = "0.9.0"
|
||||
err-derive = "0.3.1"
|
||||
futures = "0.3.28"
|
||||
get_if_addrs = "0.5.3"
|
||||
|
||||
@@ -197,10 +197,8 @@ fn bc_modern_msg<'a>(
|
||||
}
|
||||
|
||||
fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> {
|
||||
let (buf, _magic) = error_context(
|
||||
"Magic invalid",
|
||||
verify(le_u32, |x| *x == MAGIC_HEADER || *x == MAGIC_HEADER_REV),
|
||||
)(buf)?;
|
||||
let (buf, _magic) =
|
||||
error_context("Magic invalid", verify(le_u32, |x| *x == MAGIC_HEADER))(buf)?;
|
||||
let (buf, msg_id) = error_context("MsgID missing", le_u32)(buf)?;
|
||||
let (buf, body_len) = error_context("BodyLen missing", le_u32)(buf)?;
|
||||
let (buf, channel_id) = error_context("ChannelID missing", le_u8)(buf)?;
|
||||
|
||||
@@ -3,11 +3,7 @@ use crate::Credentials;
|
||||
pub use super::xml::{BcPayloads, BcXml, Extension};
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(super) const MAGIC_HEADER: u32 = 0x0abcdef0;
|
||||
/// Sometimes will get the BE magic header even though all other numbers are LE?
|
||||
/// Seems to happens with certain messages like snap that produce jpegs, so perhaps it
|
||||
/// it is meant to be a hint as to the endianess of the binary payload
|
||||
pub(super) const MAGIC_HEADER_REV: u32 = 0x0fedcba0;
|
||||
pub(super) const MAGIC_HEADER: u32 = 0xabcdef0;
|
||||
|
||||
/// Login messages have this ID
|
||||
pub const MSG_ID_LOGIN: u32 = 1;
|
||||
@@ -23,8 +19,6 @@ pub const MSG_ID_TALKABILITY: u32 = 10;
|
||||
pub const MSG_ID_TALKRESET: u32 = 11;
|
||||
/// PtzControl messages have this ID
|
||||
pub const MSG_ID_PTZ_CONTROL: u32 = 18;
|
||||
/// PTZ goto preset position
|
||||
pub const MSG_ID_PTZ_CONTROL_PRESET: u32 = 19;
|
||||
/// Reboot messages have this ID
|
||||
pub const MSG_ID_REBOOT: u32 = 23;
|
||||
/// Request motion detection messages
|
||||
@@ -37,14 +31,12 @@ pub const MSG_ID_VERSION: u32 = 80;
|
||||
pub const MSG_ID_PING: u32 = 93;
|
||||
/// General system info messages have this ID
|
||||
pub const MSG_ID_GET_GENERAL: u32 = 104;
|
||||
/// Snapshot to get a jpeg image
|
||||
pub const MSG_ID_SNAP: u32 = 109;
|
||||
/// Used to get the abilities of a user
|
||||
pub const MSG_ID_ABILITY_INFO: u32 = 151;
|
||||
/// Setting general system info (clock mostly) messages have this ID
|
||||
pub const MSG_ID_SET_GENERAL: u32 = 105;
|
||||
/// Get the available PTZ position presets
|
||||
pub const MSG_ID_GET_PTZ_PRESET: u32 = 190;
|
||||
/// Used to pass the token and client ID for push notifications
|
||||
pub const MSG_ID_PUSH_INFO: u32 = 124;
|
||||
/// Will send the talk config for talk back data to follow this msg
|
||||
pub const MSG_ID_TALKCONFIG: u32 = 201;
|
||||
/// Used to send talk back binary data
|
||||
@@ -63,10 +55,6 @@ pub const MSG_ID_UDP_KEEP_ALIVE: u32 = 234;
|
||||
pub const MSG_ID_BATTERY_INFO_LIST: u32 = 252;
|
||||
/// Battery message initiaed by the client
|
||||
pub const MSG_ID_BATTERY_INFO: u32 = 253;
|
||||
/// Manual Floodlight Control
|
||||
pub const MSG_ID_FLOODLIGHT_MANUAL: u32 = 288;
|
||||
/// Floodlight status report from the camera
|
||||
pub const MSG_ID_FLOODLIGHT_STATUS_LIST: u32 = 291;
|
||||
|
||||
/// An empty password in legacy format
|
||||
pub const EMPTY_LEGACY_PASSWORD: &str =
|
||||
|
||||
+14
-120
@@ -76,15 +76,6 @@ pub struct BcXml {
|
||||
/// Sent to move the camera
|
||||
#[yaserde(rename = "PtzControl")]
|
||||
pub ptz_control: Option<PtzControl>,
|
||||
/// Sent to manually control the floodlight
|
||||
#[yaserde(rename = "FloodlightManual")]
|
||||
pub floodlight_manual: Option<FloodlightManual>,
|
||||
/// Received when the floodlight status is updated
|
||||
#[yaserde(rename = "FloodlightStatusList")]
|
||||
pub floodlight_status_list: Option<FloodlightStatusList>,
|
||||
/// Sent or received for the PTZ preset functionality
|
||||
#[yaserde(rename = "PtzPreset")]
|
||||
pub ptz_preset: Option<PtzPreset>,
|
||||
/// Recieved on login/low battery events
|
||||
#[yaserde(rename = "BatteryList")]
|
||||
pub battery_list: Option<BatteryList>,
|
||||
@@ -94,12 +85,9 @@ pub struct BcXml {
|
||||
/// Recieved on request for a users persmissions/capabilitoes
|
||||
#[yaserde(rename = "AbilityInfo")]
|
||||
pub ability_info: Option<AbilityInfo>,
|
||||
/// Recieved on request for a link type
|
||||
#[yaserde(rename = "LinkType")]
|
||||
pub link_type: Option<LinkType>,
|
||||
/// Recieved AND send for the snap message
|
||||
#[yaserde(rename = "Snap")]
|
||||
pub snap: Option<Snap>,
|
||||
/// Recieved on request for a users persmissions/capabilitoes
|
||||
#[yaserde(rename = "PushInfo")]
|
||||
pub push_info: Option<PushInfo>,
|
||||
}
|
||||
|
||||
impl BcXml {
|
||||
@@ -340,42 +328,6 @@ pub struct LedState {
|
||||
pub light_state: String,
|
||||
}
|
||||
|
||||
/// FloodlightStatus xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
|
||||
pub struct FloodlightStatus {
|
||||
/// Channel ID of floodlight
|
||||
#[yaserde(rename = "channel")]
|
||||
pub channel_id: u8,
|
||||
/// On or off
|
||||
pub status: u8,
|
||||
}
|
||||
|
||||
/// FloodlightStatusList xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
|
||||
pub struct FloodlightStatusList {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// List of events
|
||||
#[yaserde(rename = "FloodlightStatus")]
|
||||
pub floodlight_status_list: Vec<FloodlightStatus>,
|
||||
}
|
||||
|
||||
/// FloodlightManual xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct FloodlightManual {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// Channel ID of floodlight
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: u8,
|
||||
/// On or off
|
||||
pub status: u8,
|
||||
/// How long the manual control should apply for
|
||||
pub duration: u16,
|
||||
}
|
||||
|
||||
/// rfAlarmCfg xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct RfAlarmCfg {
|
||||
@@ -570,40 +522,7 @@ pub struct PtzControl {
|
||||
pub channel_id: u8,
|
||||
/// The amount of movement to perform
|
||||
pub speed: f32,
|
||||
/// The direction to transverse. Known values are `"left"`, `"right"`, `"up"`, `"down"`,
|
||||
/// `"leftUp"`, `"leftDown"`, `"rightUp"`, `"rightDown"` and `"stop"`
|
||||
pub command: String,
|
||||
}
|
||||
|
||||
/// An XML that describes a list of available PTZ presets
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct PtzPreset {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// The channel ID. Usually zero unless from an NVR
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: u8,
|
||||
/// List of presets
|
||||
#[yaserde(rename = "presetList")]
|
||||
pub preset_list: PresetList,
|
||||
}
|
||||
|
||||
/// A preset list
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct PresetList {
|
||||
/// List of Presets
|
||||
pub preset: Vec<Preset>,
|
||||
}
|
||||
|
||||
/// A preset. Either contains the ID and the name or the ID and the command
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct Preset {
|
||||
/// The ID of the preset
|
||||
pub id: u8,
|
||||
/// The preset name
|
||||
pub name: Option<String>,
|
||||
/// Command: Known values: `"toPos"` and `"setPos"`
|
||||
/// The direction to transverse. Known directions: "right"
|
||||
pub command: String,
|
||||
}
|
||||
|
||||
@@ -698,42 +617,17 @@ pub struct AbilityInfoSubModule {
|
||||
pub ability_value: String,
|
||||
}
|
||||
|
||||
/// The Link Type contains the type of connection present
|
||||
/// PushInfo XML
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct LinkType {
|
||||
#[yaserde(rename = "type")]
|
||||
/// Type of connection known values `"LAN"`
|
||||
pub link_type: String,
|
||||
}
|
||||
|
||||
/// The Link Type contains the type of connection present
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct Snap {
|
||||
#[yaserde(rename = "channelId")]
|
||||
/// The channel id to get the snapshot from
|
||||
pub channel_id: u8,
|
||||
/// Unknown, observed values: 0
|
||||
/// value is only set on request
|
||||
#[yaserde(rename = "logicChannel")]
|
||||
pub logic_channel: Option<u8>,
|
||||
/// Time of snapshot, zero when requesting
|
||||
pub time: u32,
|
||||
/// Request a full frame, observed values: 0
|
||||
/// value is only set on request
|
||||
#[yaserde(rename = "fullFrame")]
|
||||
pub full_frame: Option<u32>,
|
||||
/// Stream name, observed values: `main`, `sub`
|
||||
/// value is only set on request
|
||||
#[yaserde(rename = "streamType")]
|
||||
pub stream_type: Option<String>,
|
||||
/// File name, usually of the form `01_20230518140240.jpg`
|
||||
/// value is only set on recieve
|
||||
#[yaserde(rename = "fileName")]
|
||||
pub file_name: Option<String>,
|
||||
/// Size in bytes of the picture
|
||||
/// value is only set on recieve
|
||||
#[yaserde(rename = "pictureSize")]
|
||||
pub picture_size: Option<u32>,
|
||||
pub struct PushInfo {
|
||||
/// The token from FCM registration
|
||||
pub token: String,
|
||||
/// The phone type, known values: `reo_iphone`
|
||||
#[yaserde(rename = "phoneType")]
|
||||
pub phone_type: String,
|
||||
/// A client ID, seems to be an all CAPS MD5 hash of something
|
||||
#[yaserde(rename = "clientID")]
|
||||
pub client_id: String,
|
||||
}
|
||||
|
||||
/// Convience function to return the xml version used throughout the library
|
||||
|
||||
@@ -16,7 +16,6 @@ mod battery;
|
||||
mod connection;
|
||||
mod credentials;
|
||||
mod errors;
|
||||
mod floodlight_status;
|
||||
mod keepalive;
|
||||
mod ledstate;
|
||||
mod login;
|
||||
@@ -25,9 +24,9 @@ mod motion;
|
||||
mod ping;
|
||||
mod pirstate;
|
||||
mod ptz;
|
||||
mod pushinfo;
|
||||
mod reboot;
|
||||
mod resolution;
|
||||
mod snap;
|
||||
mod stream;
|
||||
mod talk;
|
||||
mod time;
|
||||
@@ -41,6 +40,7 @@ pub use login::MaxEncryption;
|
||||
pub use motion::{MotionData, MotionStatus};
|
||||
pub use pirstate::PirState;
|
||||
pub use ptz::Direction;
|
||||
pub use pushinfo::PhoneType;
|
||||
pub use resolution::*;
|
||||
use std::sync::Arc;
|
||||
pub use stream::{StreamData, StreamKind};
|
||||
@@ -141,16 +141,14 @@ impl BcCamera {
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sockets.is_empty() {
|
||||
info!("{}: Trying TCP discovery", options.name);
|
||||
for socket in sockets.drain(..) {
|
||||
let channel_id: u8 = options.channel_id;
|
||||
if let Ok(addr) = Discovery::check_tcp(socket, channel_id).await.map(|_| {
|
||||
info!("{}: TCP Discovery success at {:?}", options.name, &socket);
|
||||
socket
|
||||
}) {
|
||||
return Ok(CameraLocation::Tcp(addr));
|
||||
}
|
||||
info!("{}: Trying TCP discovery", options.name);
|
||||
for socket in sockets.drain(..) {
|
||||
let channel_id: u8 = options.channel_id;
|
||||
if let Ok(addr) = Discovery::check_tcp(socket, channel_id).await.map(|_| {
|
||||
info!("{}: TCP Discovery success at {:?}", options.name, &socket);
|
||||
socket
|
||||
}) {
|
||||
return Ok(CameraLocation::Tcp(addr));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -180,7 +178,6 @@ impl BcCamera {
|
||||
DiscoveryMethods::Remote => (true, true, false, false),
|
||||
DiscoveryMethods::Map => (true, true, true, false),
|
||||
DiscoveryMethods::Relay => (true, true, true, true),
|
||||
DiscoveryMethods::Cellular => (false, false, true, true),
|
||||
DiscoveryMethods::Debug => (false, false, false, true),
|
||||
};
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ impl BcCamera {
|
||||
pub async fn get_abilityinfo(&self) -> Result<AbilityInfo> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_ABILITY_INFO, msg_num).await?;
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_ABILITY_INFO,
|
||||
|
||||
@@ -19,60 +19,58 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
connection
|
||||
.handle_msg(MSG_ID_BATTERY_INFO_LIST, move |bc| {
|
||||
Box::pin(async move {
|
||||
if let Bc {
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
battery_list: Some(battery_list),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}),
|
||||
..
|
||||
} = bc
|
||||
{
|
||||
for battery in battery_list.battery_info.iter() {
|
||||
match format {
|
||||
PrintFormat::None => {}
|
||||
PrintFormat::Human => {
|
||||
println!(
|
||||
"==Battery==\n\
|
||||
if let Bc {
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
battery_list: Some(battery_list),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}),
|
||||
..
|
||||
} = bc
|
||||
{
|
||||
for battery in battery_list.battery_info.iter() {
|
||||
match format {
|
||||
PrintFormat::None => {}
|
||||
PrintFormat::Human => {
|
||||
println!(
|
||||
"==Battery==\n\
|
||||
Charge: {}%,\n\
|
||||
Temperature: {}°C,\n\
|
||||
LowPower: {},\n\
|
||||
Adapter: {},\n\
|
||||
ChargeStatus: {},\n\
|
||||
",
|
||||
battery.battery_percent,
|
||||
battery.temperature,
|
||||
if battery.low_power == 1 {
|
||||
"true"
|
||||
} else {
|
||||
"false"
|
||||
},
|
||||
battery.adapter_status,
|
||||
battery.charge_status,
|
||||
);
|
||||
}
|
||||
PrintFormat::Xml => {
|
||||
let bat_ser = String::from_utf8(
|
||||
yaserde::ser::serialize_with_writer(
|
||||
battery,
|
||||
vec![],
|
||||
&Default::default(),
|
||||
)
|
||||
.expect("Should Ser the struct"),
|
||||
battery.battery_percent,
|
||||
battery.temperature,
|
||||
if battery.low_power == 1 {
|
||||
"true"
|
||||
} else {
|
||||
"false"
|
||||
},
|
||||
battery.adapter_status,
|
||||
battery.charge_status,
|
||||
);
|
||||
}
|
||||
PrintFormat::Xml => {
|
||||
let bat_ser = String::from_utf8(
|
||||
yaserde::ser::serialize_with_writer(
|
||||
battery,
|
||||
vec![],
|
||||
&Default::default(),
|
||||
)
|
||||
.expect("Should be UTF8");
|
||||
println!("{}", bat_ser);
|
||||
}
|
||||
.expect("Should Ser the struct"),
|
||||
)
|
||||
.expect("Should be UTF8");
|
||||
println!("{}", bat_ser);
|
||||
}
|
||||
}
|
||||
}
|
||||
Option::<Bc>::None
|
||||
})
|
||||
}
|
||||
None
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
@@ -83,7 +81,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(MSG_ID_BATTERY_INFO, msg_num).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
use super::BcSubscription;
|
||||
use crate::{bc::model::*, Error, Result};
|
||||
use futures::future::BoxFuture;
|
||||
use futures::sink::{Sink, SinkExt};
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use log::*;
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc::{channel, Sender};
|
||||
use tokio::task::yield_now;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
@@ -14,14 +12,13 @@ use tokio_util::sync::PollSender;
|
||||
|
||||
use tokio::{sync::RwLock, task::JoinSet};
|
||||
|
||||
type MsgHandler = dyn 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a, Option<Bc>>;
|
||||
|
||||
type MsgHandler = Box<dyn Fn(&Bc) -> Option<Bc> + Send + Sync>;
|
||||
#[derive(Default)]
|
||||
struct Subscriber {
|
||||
/// Subscribers based on their ID and their num
|
||||
num: BTreeMap<u32, BTreeMap<Option<u16>, Sender<Result<Bc>>>>,
|
||||
/// Subscribers based on their Num
|
||||
num: BTreeMap<u16, Sender<Result<Bc>>>,
|
||||
/// Subscribers based on their ID
|
||||
id: BTreeMap<u32, Arc<MsgHandler>>,
|
||||
id: BTreeMap<u32, MsgHandler>,
|
||||
}
|
||||
|
||||
pub(crate) type BcConnSink = Box<dyn Sink<Bc, Error = Error> + Send + Sync + Unpin>;
|
||||
@@ -85,12 +82,12 @@ impl BcConnection {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn subscribe(&self, msg_id: u32, msg_num: u16) -> Result<BcSubscription> {
|
||||
pub async fn subscribe(&self, msg_num: u16) -> Result<BcSubscription> {
|
||||
let (tx, rx) = channel(100);
|
||||
self.poll_commander
|
||||
.send(PollCommand::AddSubscriber(msg_id, Some(msg_num), tx))
|
||||
.send(PollCommand::AddSubscriber(msg_num, tx))
|
||||
.await?;
|
||||
Ok(BcSubscription::new(rx, Some(msg_num as u32), self))
|
||||
Ok(BcSubscription::new(rx, msg_num as u32, self))
|
||||
}
|
||||
|
||||
/// Some messages are initiated by the camera. This creates a handler for them
|
||||
@@ -98,10 +95,10 @@ impl BcConnection {
|
||||
/// and return either None or Some(Bc) reply
|
||||
pub async fn handle_msg<T>(&self, msg_id: u32, handler: T) -> Result<()>
|
||||
where
|
||||
T: 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a, Option<Bc>>,
|
||||
T: Fn(&Bc) -> Option<Bc> + Send + Sync + 'static,
|
||||
{
|
||||
self.poll_commander
|
||||
.send(PollCommand::AddHandler(msg_id, Arc::new(handler)))
|
||||
.send(PollCommand::AddHandler(msg_id, Box::new(handler)))
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -115,21 +112,6 @@ impl BcConnection {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Some times we want to wait for a reply on a new message ID
|
||||
/// to do this we wait for the next packet with a certain ID
|
||||
/// grab it's message ID and then subscribe to that ID
|
||||
///
|
||||
/// The command Snap that grabs a jpeg payload is an example of this
|
||||
///
|
||||
/// This function creates a temporary handle to grab this single message
|
||||
pub async fn subscribe_to_id(&self, msg_id: u32) -> Result<BcSubscription> {
|
||||
let (tx, rx) = channel(100);
|
||||
self.poll_commander
|
||||
.send(PollCommand::AddSubscriber(msg_id, None, tx))
|
||||
.await?;
|
||||
Ok(BcSubscription::new(rx, None, self))
|
||||
}
|
||||
|
||||
pub(crate) async fn join(&self) -> Result<()> {
|
||||
let mut locked_threads = self.rx_thread.write().await;
|
||||
while let Some(res) = locked_threads.join_next().await {
|
||||
@@ -151,9 +133,9 @@ impl BcConnection {
|
||||
|
||||
enum PollCommand {
|
||||
Bc(Box<Result<Bc>>),
|
||||
AddHandler(u32, Arc<MsgHandler>),
|
||||
AddHandler(u32, MsgHandler),
|
||||
RemoveHandler(u32),
|
||||
AddSubscriber(u32, Option<u16>, Sender<Result<Bc>>),
|
||||
AddSubscriber(u16, Sender<Result<Bc>>),
|
||||
}
|
||||
|
||||
struct Poller {
|
||||
@@ -167,96 +149,66 @@ impl Poller {
|
||||
while let Some(command) = self.reciever.next().await {
|
||||
yield_now().await;
|
||||
match command {
|
||||
PollCommand::Bc(boxed_response) => {
|
||||
match *boxed_response {
|
||||
Ok(response) => {
|
||||
let msg_num = response.meta.msg_num;
|
||||
let msg_id = response.meta.msg_id;
|
||||
PollCommand::Bc(boxed_response) => match *boxed_response {
|
||||
Ok(response) => {
|
||||
let msg_num = response.meta.msg_num;
|
||||
let msg_id = response.meta.msg_id;
|
||||
|
||||
match (
|
||||
self.subscribers.id.get(&msg_id),
|
||||
self.subscribers.num.get_mut(&msg_id),
|
||||
) {
|
||||
(Some(occ), _) => {
|
||||
if let Some(reply) = occ(&response).await {
|
||||
assert!(reply.meta.msg_num == response.meta.msg_num);
|
||||
self.sink.send(Ok(reply)).await?;
|
||||
}
|
||||
let mut remove_it_num = false;
|
||||
match (
|
||||
self.subscribers.id.get(&msg_id),
|
||||
self.subscribers.num.get(&msg_num),
|
||||
) {
|
||||
(Some(occ), _) => {
|
||||
if let Some(reply) = occ(&response) {
|
||||
assert!(reply.meta.msg_num == response.meta.msg_num);
|
||||
self.sink.send(Ok(reply)).await?;
|
||||
}
|
||||
(None, Some(occ)) => {
|
||||
let sender = if let Some(sender) =
|
||||
occ.get(&Some(msg_num)).filter(|a| !a.is_closed()).cloned()
|
||||
{
|
||||
// Connection with id exists and is not closed
|
||||
Some(sender)
|
||||
} else if let Some(sender) = occ.get(&None).cloned() {
|
||||
// Upgrade a None to a known MsgID
|
||||
occ.remove(&None);
|
||||
occ.insert(Some(msg_num), sender.clone());
|
||||
Some(sender)
|
||||
} else if occ
|
||||
.get(&Some(msg_num))
|
||||
.map(|a| a.is_closed())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
// Connection is closed and there is no None to replace it
|
||||
// Remove it for cleanup and report no sender
|
||||
occ.remove(&Some(msg_num));
|
||||
None
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(sender) = sender {
|
||||
if sender.capacity() == 0 {
|
||||
warn!("Reaching limit of channel");
|
||||
warn!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
sender.capacity(),
|
||||
sender.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
} else {
|
||||
trace!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
sender.capacity(),
|
||||
sender.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
}
|
||||
if sender.send(Ok(response)).await.is_err() {
|
||||
occ.remove(&Some(msg_num));
|
||||
}
|
||||
} else {
|
||||
debug!(
|
||||
"Ignoring uninteresting message id {} (number: {})",
|
||||
msg_id, msg_num
|
||||
);
|
||||
trace!("Contents: {:?}", response);
|
||||
}
|
||||
}
|
||||
(None, None) => {
|
||||
debug!(
|
||||
"Ignoring uninteresting message id {} (number: {})",
|
||||
msg_id, msg_num
|
||||
}
|
||||
(None, Some(occ)) => {
|
||||
if occ.capacity() == 0 {
|
||||
warn!("Reaching limit of channel");
|
||||
warn!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
occ.capacity(),
|
||||
occ.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
} else {
|
||||
trace!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
occ.capacity(),
|
||||
occ.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
trace!("Contents: {:?}", response);
|
||||
}
|
||||
if occ.send(Ok(response)).await.is_err() {
|
||||
remove_it_num = true;
|
||||
}
|
||||
}
|
||||
(None, None) => {
|
||||
debug!(
|
||||
"Ignoring uninteresting message id {} (number: {})",
|
||||
msg_id, msg_num
|
||||
);
|
||||
trace!("Contents: {:?}", response);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
for sub in self.subscribers.num.values() {
|
||||
for sender in sub.values() {
|
||||
let _ = sender.send(Err(e.clone())).await;
|
||||
}
|
||||
}
|
||||
self.subscribers.num.clear();
|
||||
self.subscribers.id.clear();
|
||||
return Err(e);
|
||||
if remove_it_num {
|
||||
self.subscribers.num.remove(&msg_num);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
for sub in self.subscribers.num.values() {
|
||||
let _ = sub.send(Err(e.clone())).await;
|
||||
}
|
||||
self.subscribers.num.clear();
|
||||
self.subscribers.id.clear();
|
||||
return Err(e);
|
||||
}
|
||||
},
|
||||
PollCommand::AddHandler(msg_id, handler) => {
|
||||
match self.subscribers.id.entry(msg_id) {
|
||||
Entry::Vacant(vac_entry) => {
|
||||
@@ -270,14 +222,8 @@ impl Poller {
|
||||
PollCommand::RemoveHandler(msg_id) => {
|
||||
self.subscribers.id.remove(&msg_id);
|
||||
}
|
||||
PollCommand::AddSubscriber(msg_id, msg_num, tx) => {
|
||||
match self
|
||||
.subscribers
|
||||
.num
|
||||
.entry(msg_id)
|
||||
.or_default()
|
||||
.entry(msg_num)
|
||||
{
|
||||
PollCommand::AddSubscriber(msg_num, tx) => {
|
||||
match self.subscribers.num.entry(msg_num) {
|
||||
Entry::Vacant(vac_entry) => {
|
||||
vac_entry.insert(tx);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
|
||||
|
||||
pub struct BcSubscription<'a> {
|
||||
rx: ReceiverStream<Result<Bc>>,
|
||||
msg_num: Option<u32>,
|
||||
msg_num: u32,
|
||||
conn: &'a BcConnection,
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ pub type BcMediaStream<'b> = FramedRead<Compat<IntoAsyncRead<BcPayloadStream<'b>
|
||||
impl<'a> BcSubscription<'a> {
|
||||
pub fn new(
|
||||
rx: Receiver<Result<Bc>>,
|
||||
msg_num: Option<u32>,
|
||||
msg_num: u32,
|
||||
conn: &'a BcConnection,
|
||||
) -> BcSubscription<'a> {
|
||||
BcSubscription {
|
||||
@@ -100,11 +100,7 @@ impl<'a> BcSubscription<'a> {
|
||||
}
|
||||
|
||||
pub async fn send(&self, bc: Bc) -> Result<()> {
|
||||
if let Some(msg_num) = self.msg_num {
|
||||
assert!(bc.meta.msg_num as u32 == msg_num);
|
||||
} else {
|
||||
log::debug!("Sending message before msg_num has been aquired");
|
||||
}
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
self.conn.send(bc).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -112,12 +108,7 @@ impl<'a> BcSubscription<'a> {
|
||||
pub async fn recv(&mut self) -> Result<Bc> {
|
||||
let bc = self.rx.next().await.ok_or(Error::DroppedSubscriber)?;
|
||||
if let Ok(bc) = &bc {
|
||||
if let Some(msg_num) = self.msg_num {
|
||||
assert!(bc.meta.msg_num as u32 == msg_num);
|
||||
} else {
|
||||
// Leaning number now
|
||||
self.msg_num = Some(bc.meta.msg_num as u32);
|
||||
}
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
}
|
||||
bc
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ use local_ip_address::local_ip;
|
||||
use log::*;
|
||||
use rand::{seq::SliceRandom, thread_rng, Rng};
|
||||
use std::collections::{btree_map::Entry, BTreeMap};
|
||||
use std::convert::TryInto;
|
||||
use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs};
|
||||
use std::sync::Arc;
|
||||
use tokio::{
|
||||
@@ -36,9 +35,9 @@ use tokio_util::udp::UdpFramed;
|
||||
#[derive(Debug, Clone)]
|
||||
struct RegisterResult {
|
||||
reg: SocketAddr,
|
||||
dev: Option<SocketAddr>,
|
||||
dmap: Option<SocketAddr>,
|
||||
relay: Option<SocketAddr>,
|
||||
dev: SocketAddr,
|
||||
dmap: SocketAddr,
|
||||
relay: SocketAddr,
|
||||
client_id: i32,
|
||||
sid: u32,
|
||||
}
|
||||
@@ -175,7 +174,7 @@ impl Discoverer {
|
||||
Ok(rx)
|
||||
} else {
|
||||
Err(Error::SimultaneousSubscription {
|
||||
msg_num: Some(tid as u16),
|
||||
msg_num: (tid as u16),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -446,6 +445,8 @@ impl Discoverer {
|
||||
},
|
||||
};
|
||||
|
||||
trace!("Registering: {:?}", msg.payload.c2r_c);
|
||||
|
||||
// Send and await acceptance
|
||||
let (sid, dev, dmap, relay) = self
|
||||
.retry_send(msg, lookup.reg, |bc, _| match bc {
|
||||
@@ -464,32 +465,17 @@ impl Discoverer {
|
||||
}),
|
||||
..
|
||||
},
|
||||
} 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 =>
|
||||
{
|
||||
} if !dev.ip.is_empty() && dev.port > 0 && rsp != -1 => {
|
||||
Some(Ok((sid, dev, dmap, relay)))
|
||||
}
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
r2c_c_r:
|
||||
Some(R2cCr {
|
||||
dev,
|
||||
dmap,
|
||||
relay,
|
||||
rsp,
|
||||
..
|
||||
}),
|
||||
r2c_c_r: Some(R2cCr { dev, 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 =>
|
||||
{
|
||||
} if !dev.ip.is_empty() && dev.port > 0 && rsp == -1 => {
|
||||
Some(Err(Error::RegisterError))
|
||||
}
|
||||
_ => None,
|
||||
@@ -500,9 +486,9 @@ impl Discoverer {
|
||||
reg: lookup.reg,
|
||||
sid,
|
||||
client_id,
|
||||
dev: dev.and_then(|d| d.try_into().ok()),
|
||||
dmap: dmap.and_then(|d| d.try_into().ok()),
|
||||
relay: relay.and_then(|d| d.try_into().ok()),
|
||||
dev: SocketAddr::new(dev.ip.parse()?, dev.port),
|
||||
dmap: SocketAddr::new(dmap.ip.parse()?, dmap.port),
|
||||
relay: SocketAddr::new(relay.ip.parse()?, relay.port),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -537,10 +523,7 @@ impl Discoverer {
|
||||
},
|
||||
) if cid == register_result.client_id
|
||||
&& &sid == register_sid
|
||||
&& register_dmap
|
||||
.as_ref()
|
||||
.map(|dmap| &addr == dmap)
|
||||
.unwrap_or(false)
|
||||
&& &addr == register_dmap
|
||||
&& &conn == "local" =>
|
||||
{
|
||||
Some((addr, tid, did))
|
||||
@@ -654,10 +637,7 @@ impl Discoverer {
|
||||
},
|
||||
) if cid == register_result.client_id
|
||||
&& &sid == register_sid
|
||||
&& register_dmap
|
||||
.as_ref()
|
||||
.map(|dmap| &addr == dmap)
|
||||
.unwrap_or(false)
|
||||
&& &addr == register_dmap
|
||||
&& &conn == "map" =>
|
||||
{
|
||||
Some((addr, tid, did))
|
||||
@@ -746,7 +726,7 @@ impl Discoverer {
|
||||
) -> Result<ConnectResult> {
|
||||
let tid = generate_tid();
|
||||
|
||||
let dev_addr = register_result.dev.ok_or(Error::NoDev)?;
|
||||
let dev_addr = register_result.dev;
|
||||
let msg = UdpDiscovery {
|
||||
tid,
|
||||
payload: UdpXml {
|
||||
@@ -811,7 +791,6 @@ impl Discoverer {
|
||||
) -> Result<ConnectResult> {
|
||||
let tid = generate_tid();
|
||||
|
||||
let relay_addr = register_result.relay.ok_or(Error::NoDev)?;
|
||||
let msg = UdpDiscovery {
|
||||
tid,
|
||||
payload: UdpXml {
|
||||
@@ -826,7 +805,7 @@ impl Discoverer {
|
||||
};
|
||||
|
||||
let (final_addr, local_did) = self
|
||||
.retry_send(msg, relay_addr, |bc, addr| match bc {
|
||||
.retry_send(msg, register_result.relay, |bc, addr| match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
|
||||
@@ -96,10 +96,10 @@ pub enum Error {
|
||||
GenError(#[error(source)] std::sync::Arc<cookie_factory::GenError>),
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once for msg_num
|
||||
#[error(display = "Simultaneous subscription, {:?}", _0)]
|
||||
#[error(display = "Simultaneous subscription, {}", _0)]
|
||||
SimultaneousSubscription {
|
||||
/// The message number that was subscribed to
|
||||
msg_num: Option<u16>,
|
||||
msg_num: u16,
|
||||
},
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once for msg_id
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
use tokio::sync::mpsc::{channel, Receiver};
|
||||
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Listen on the flood light update messages and return their XMLs
|
||||
pub async fn listen_on_flightlight(&self) -> Result<Receiver<FloodlightStatusList>> {
|
||||
let (tx, rx) = channel(3);
|
||||
let connection = self.get_connection();
|
||||
connection
|
||||
.handle_msg(MSG_ID_FLOODLIGHT_STATUS_LIST, move |bc| {
|
||||
let tx = tx.clone();
|
||||
Box::pin(async move {
|
||||
if let Bc {
|
||||
meta:
|
||||
BcMeta {
|
||||
msg_id: MSG_ID_FLOODLIGHT_STATUS_LIST,
|
||||
..
|
||||
},
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
floodlight_status_list: Some(list),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}),
|
||||
} = bc
|
||||
{
|
||||
let send_this: FloodlightStatusList = list.clone();
|
||||
let _ = tx.send(send_this).await;
|
||||
}
|
||||
None
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(rx)
|
||||
}
|
||||
|
||||
/// Set the floodlight status using the [FloodlightManual] xml
|
||||
pub async fn set_floodlight_manual(&self, state: bool, duration: u16) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_FLOODLIGHT_MANUAL, msg_num)
|
||||
.await?;
|
||||
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_FLOODLIGHT_MANUAL,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
floodlight_manual: Some(FloodlightManual {
|
||||
version: "1".to_string(),
|
||||
channel_id: self.channel_id,
|
||||
status: match state {
|
||||
true => 1,
|
||||
false => 0,
|
||||
},
|
||||
duration,
|
||||
}),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
|
||||
{
|
||||
let msg = reply?;
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the Floodlight manual state",
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,20 +10,18 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
connection
|
||||
.handle_msg(MSG_ID_UDP_KEEP_ALIVE, |bc| {
|
||||
Box::pin(async move {
|
||||
Some(Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_UDP_KEEP_ALIVE,
|
||||
channel_id: bc.meta.channel_id,
|
||||
msg_num: bc.meta.msg_num,
|
||||
stream_type: bc.meta.stream_type,
|
||||
response_code: 200,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
..Default::default()
|
||||
}),
|
||||
})
|
||||
Some(Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_UDP_KEEP_ALIVE,
|
||||
channel_id: bc.meta.channel_id,
|
||||
msg_num: bc.meta.msg_num,
|
||||
stream_type: bc.meta.stream_type,
|
||||
response_code: 200,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
..Default::default()
|
||||
}),
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
|
||||
@@ -7,7 +7,7 @@ impl BcCamera {
|
||||
self.has_ability_ro("ledState").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_GET_LED_STATUS, msg_num).await?;
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_LED_STATUS,
|
||||
@@ -56,7 +56,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection.subscribe(MSG_ID_SET_LED_STATUS, msg_num).await?;
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
// led_version is a field recieved from the camera but not sent
|
||||
// we set to None to ensure we don't send it to the camera
|
||||
@@ -83,25 +83,18 @@ impl BcCamera {
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
|
||||
{
|
||||
let msg = reply?;
|
||||
let msg = sub_set.recv().await?;
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the LEDState xml",
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the LEDState xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the [LinkType] xml which contains the connection status of the camera
|
||||
///
|
||||
/// This is the same as `ping()` but with the return type
|
||||
pub async fn get_linktype(&self) -> Result<LinkType> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_PING,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
link_type: Some(link_type),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(link_type)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected LinkType xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,7 @@ impl BcCamera {
|
||||
let credentials = self.get_credentials();
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_login = connection.subscribe(MSG_ID_LOGIN, msg_num).await?;
|
||||
let mut sub_login = connection.subscribe(msg_num).await?;
|
||||
|
||||
// Login flow is: Send legacy login message, expect back a modern message with Encryption
|
||||
// details. Then, re-send the login as a modern login message. Expect back a device info
|
||||
|
||||
@@ -9,7 +9,7 @@ impl BcCamera {
|
||||
let credentials = self.get_credentials();
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let sub_logout = connection.subscribe(MSG_ID_LOGOUT, msg_num).await?;
|
||||
let sub_logout = connection.subscribe(msg_num).await?;
|
||||
|
||||
let username = credentials.username.clone();
|
||||
let password = credentials.password.as_ref().cloned().unwrap_or_default();
|
||||
|
||||
@@ -167,7 +167,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(MSG_ID_MOTION_REQUEST, msg_num).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_MOTION_REQUEST,
|
||||
@@ -202,7 +202,7 @@ impl BcCamera {
|
||||
/// This returns a data structure which can be used to
|
||||
/// query motion events
|
||||
pub async fn listen_on_motion(&self) -> Result<MotionData> {
|
||||
self.start_motion_query().await?;
|
||||
let msg_num = self.start_motion_query().await?;
|
||||
|
||||
let connection = self.get_connection();
|
||||
|
||||
@@ -213,7 +213,7 @@ impl BcCamera {
|
||||
let mut set = JoinSet::new();
|
||||
let channel_id = self.channel_id;
|
||||
set.spawn(async move {
|
||||
let mut sub = connection.subscribe_to_id(MSG_ID_MOTION).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
loop {
|
||||
tokio::task::yield_now().await;
|
||||
|
||||
@@ -7,7 +7,7 @@ impl BcCamera {
|
||||
pub async fn ping(&self) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_ping = connection.subscribe(MSG_ID_PING, msg_num).await?;
|
||||
let mut sub_ping = connection.subscribe(msg_num).await?;
|
||||
|
||||
let ping = Bc {
|
||||
meta: BcMeta {
|
||||
|
||||
@@ -12,7 +12,7 @@ impl BcCamera {
|
||||
loop {
|
||||
retry_interval.tick().await;
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_GET_PIR_ALARM, msg_num).await?;
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_PIR_ALARM,
|
||||
@@ -70,9 +70,7 @@ impl BcCamera {
|
||||
self.has_ability_rw("rfAlarm").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_START_PIR_ALARM, msg_num)
|
||||
.await?;
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
@@ -96,28 +94,21 @@ impl BcCamera {
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
|
||||
{
|
||||
let msg = reply?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
let msg = sub_set.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the RfAlarmCfg xml",
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the RfAlarmCfg xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ impl BcCamera {
|
||||
self.has_ability_rw("control").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection.subscribe(MSG_ID_PTZ_CONTROL, msg_num).await?;
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
let direction_str = match direction {
|
||||
Direction::Up => "up",
|
||||
@@ -82,166 +82,4 @@ impl BcCamera {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the [PtzPreset] XML which contains the list of the preset positions known to the camera
|
||||
pub async fn get_ptz_preset(&self) -> Result<PtzPreset> {
|
||||
self.has_ability_rw("control").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection.subscribe(MSG_ID_GET_PTZ_PRESET, msg_num).await?;
|
||||
|
||||
let send = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_PTZ_PRESET,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_set.send(send).await?;
|
||||
let msg = sub_set.recv().await?;
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
ptz_preset: Some(ptz_preset),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(ptz_preset)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not return a valid PtzPreset xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a PTZ preset.
|
||||
///
|
||||
/// The current position will be saved as a preset with the given [preset_id] and [name]
|
||||
pub async fn set_ptz_preset(&self, preset_id: u8, name: String) -> Result<()> {
|
||||
self.has_ability_rw("control").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_PTZ_CONTROL_PRESET, msg_num)
|
||||
.await?;
|
||||
|
||||
let preset = Preset {
|
||||
id: preset_id,
|
||||
name: Some(name),
|
||||
command: "setPos".to_owned(),
|
||||
};
|
||||
let send = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_PTZ_CONTROL_PRESET,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
ptz_preset: Some(PtzPreset {
|
||||
preset_list: PresetList {
|
||||
preset: vec![preset],
|
||||
},
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_set.send(send).await?;
|
||||
let msg = sub_set.recv().await?;
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the PtzPreset xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The camera will attempt to move to the preset with the given ID.
|
||||
pub async fn moveto_ptz_preset(&self, preset_id: u8) -> Result<()> {
|
||||
self.has_ability_rw("control").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_PTZ_CONTROL_PRESET, msg_num)
|
||||
.await?;
|
||||
|
||||
let preset = Preset {
|
||||
id: preset_id,
|
||||
name: None,
|
||||
command: "toPos".to_owned(),
|
||||
};
|
||||
let send = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_PTZ_CONTROL_PRESET,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
ptz_preset: Some(PtzPreset {
|
||||
preset_list: PresetList {
|
||||
preset: vec![preset],
|
||||
},
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_set.send(send).await?;
|
||||
let msg = sub_set.recv().await?;
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the PtzPreset xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
/// Specifies the phone type for the push notification
|
||||
pub enum PhoneType {
|
||||
/// Specify that this is an ios push notfication
|
||||
///
|
||||
/// In this case the token must be the APNS
|
||||
Ios,
|
||||
/// Specify that this is an andriod push notfication
|
||||
///
|
||||
/// In this case the token must firebase cloud messaging token
|
||||
Android,
|
||||
}
|
||||
|
||||
impl BcCamera {
|
||||
/// Convenience method for andriod of `[send_pushinfo]`
|
||||
pub async fn send_pushinfo_android(&self, token: &str, client_id: &str) -> Result<()> {
|
||||
self.send_pushinfo(token, client_id, PhoneType::Android)
|
||||
.await
|
||||
}
|
||||
/// Convenience method for andriod of `[send_pushinfo]`
|
||||
pub async fn send_pushinfo_ios(&self, token: &str, client_id: &str) -> Result<()> {
|
||||
self.send_pushinfo(token, client_id, PhoneType::Ios).await
|
||||
}
|
||||
/// Send the push info to regsiter for push notfications
|
||||
pub async fn send_pushinfo(
|
||||
&self,
|
||||
token: &str,
|
||||
client_id: &str,
|
||||
phone_type: PhoneType,
|
||||
) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let phone_type_str = match phone_type {
|
||||
PhoneType::Ios => "reo_iphone",
|
||||
PhoneType::Android => "reo_fcm",
|
||||
};
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_PUSH_INFO,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
push_info: Some(PushInfo {
|
||||
token: token.to_owned(),
|
||||
phone_type: phone_type_str.to_owned(),
|
||||
client_id: client_id.to_owned(),
|
||||
}),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub.send(msg).await?;
|
||||
let msg = sub.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ impl BcCamera {
|
||||
self.has_ability_rw("reboot").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(MSG_ID_REBOOT, msg_num).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
|
||||
@@ -38,10 +38,6 @@ pub enum DiscoveryMethods {
|
||||
/// **This also enabled `Local`, `Map` and `Remote` discovery**
|
||||
#[serde(alias = "relay")]
|
||||
Relay,
|
||||
/// Cellular camera only support relay and map, by choosing this option
|
||||
/// only those are tried
|
||||
#[serde(alias = "cellular")]
|
||||
Cellular,
|
||||
#[doc(hidden)]
|
||||
#[serde(alias = "debug")]
|
||||
/// Used for debugging it is set to whatever the dev is currently testing
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
// use futures::{StreamExt, TryStreamExt};
|
||||
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the snapshot image
|
||||
pub async fn get_snapshot(&self) -> Result<Vec<u8>> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_SNAP, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_SNAP,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
snap: Some(Snap {
|
||||
channel_id: self.channel_id,
|
||||
logic_channel: Some(self.channel_id),
|
||||
time: 0,
|
||||
full_frame: Some(0),
|
||||
stream_type: Some("main".to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
snap:
|
||||
Some(Snap {
|
||||
file_name: Some(filename),
|
||||
picture_size: Some(expected_size),
|
||||
..
|
||||
}),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
log::trace!("Got snap XML {} with size {}", filename, expected_size);
|
||||
// Messages are now sent on ID 109 but not with the same message ID
|
||||
// preumably because the camera considers it to be a new message rather
|
||||
// than a reply
|
||||
//
|
||||
// This means we need to listen for the next 109 grab the message num and
|
||||
// subscribe to it. This is what `subscribe_to_next` is for
|
||||
let mut sub_get = connection.subscribe_to_id(MSG_ID_SNAP).await?;
|
||||
let expected_size = expected_size as usize;
|
||||
|
||||
let mut result: Vec<_> = vec![];
|
||||
log::trace!("Waiting for packets on {}", msg_num);
|
||||
let mut msg = sub_get.recv().await?;
|
||||
|
||||
while msg.meta.response_code == 200 {
|
||||
// sends 200 while more is to come
|
||||
// 201 when finished
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
extension:
|
||||
Some(Extension {
|
||||
binary_data: Some(1),
|
||||
..
|
||||
}),
|
||||
payload: Some(BcPayloads::Binary(data)),
|
||||
}) = msg.body
|
||||
{
|
||||
result.extend_from_slice(&data);
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected binary data but got something else",
|
||||
});
|
||||
}
|
||||
log::trace!(
|
||||
"Got packet size is now {} of {}",
|
||||
result.len(),
|
||||
expected_size
|
||||
);
|
||||
msg = sub_get.recv().await?;
|
||||
}
|
||||
|
||||
if msg.meta.response_code == 201 {
|
||||
// 201 means all binary data sent
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
extension:
|
||||
Some(Extension {
|
||||
binary_data: Some(1),
|
||||
..
|
||||
}),
|
||||
payload,
|
||||
}) = msg.body
|
||||
{
|
||||
if let Some(BcPayloads::Binary(data)) = payload {
|
||||
// Add last data if present (may be zero if preveious packet contained it)
|
||||
result.extend_from_slice(&data);
|
||||
}
|
||||
log::trace!(
|
||||
"Got all packets size is now {} of {}",
|
||||
result.len(),
|
||||
expected_size
|
||||
);
|
||||
if result.len() != expected_size {
|
||||
log::warn!("Snap did not recieve expected number of byes");
|
||||
}
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected binary data but got something else",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// anything else is an error
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
// let binary_stream = sub_get.payload_stream();
|
||||
// let result: Vec<_>= binary_stream
|
||||
// .map_ok(|i| tokio_stream::iter(i).map(Result::Ok))
|
||||
// .try_flatten()
|
||||
// .take(expected_size)
|
||||
// .try_collect()
|
||||
// .await?;
|
||||
log::trace!("Snapshot recieved: {} of {}", result.len(), expected_size);
|
||||
Ok(result)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected Snap xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,12 +91,7 @@ impl BcCamera {
|
||||
mut buffer_size: usize,
|
||||
strict: bool,
|
||||
) -> Result<StreamData> {
|
||||
if let Err(e) = self.has_ability_rw("preview").await {
|
||||
if self.has_ability_ro("streamTable").await.is_err() {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
self.has_ability_rw("preview").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
|
||||
@@ -111,7 +106,7 @@ impl BcCamera {
|
||||
|
||||
let handle = task::spawn(async move {
|
||||
tokio::task::yield_now().await;
|
||||
let mut sub_video = connection.subscribe(MSG_ID_VIDEO, msg_num).await?;
|
||||
let mut sub_video = connection.subscribe(msg_num).await?;
|
||||
|
||||
// On an E1 and swann cameras:
|
||||
// - mainStream always has a value of 0
|
||||
@@ -224,14 +219,13 @@ impl BcCamera {
|
||||
},
|
||||
);
|
||||
// debug!("Stream: Send Stop");
|
||||
let mut sub_stop = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?;
|
||||
sub_stop.send(stop_video).await?;
|
||||
sub_video.send(stop_video).await?;
|
||||
// debug!("Stream: Sent Stop");
|
||||
|
||||
tokio::select! {
|
||||
v = async {
|
||||
loop {
|
||||
let msg = sub_stop.recv().await?;
|
||||
let msg = sub_video.recv().await?;
|
||||
if let BcMeta {
|
||||
response_code: 200,
|
||||
msg_id: MSG_ID_VIDEO_STOP,
|
||||
@@ -262,14 +256,10 @@ impl BcCamera {
|
||||
|
||||
/// Stop a camera from sending more stream data.
|
||||
pub async fn stop_video(&self, stream: StreamKind) -> Result<()> {
|
||||
if let Err(e) = self.has_ability_rw("preview").await {
|
||||
if self.has_ability_ro("streamTable").await.is_err() {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
self.has_ability_rw("preview").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_video = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?;
|
||||
let mut sub_video = connection.subscribe(msg_num).await?;
|
||||
|
||||
// On an E1 and swann cameras:
|
||||
// - mainStream always has a value of 0
|
||||
|
||||
@@ -17,7 +17,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(MSG_ID_TALKRESET, msg_num).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
@@ -60,7 +60,7 @@ impl BcCamera {
|
||||
pub async fn talk_ability(&self) -> Result<TalkAbility> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_TALKABILITY, msg_num).await?;
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_TALKABILITY,
|
||||
@@ -120,7 +120,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(MSG_ID_TALKCONFIG, msg_num).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
if &talk_config.audio_config.audio_type != "adpcm" {
|
||||
return Err(Error::UnknownTalkEncoding);
|
||||
@@ -182,7 +182,7 @@ impl BcCamera {
|
||||
|
||||
let full_block_size = block_size + 4; // Block size + predictor state
|
||||
let msg_num = self.new_message_num();
|
||||
let sub = connection.subscribe(MSG_ID_TALK, msg_num).await?;
|
||||
let sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
const BLOCK_PER_PAYLOAD: usize = 4;
|
||||
const BLOCK_HEADER_SIZE: usize = 4;
|
||||
@@ -261,7 +261,7 @@ impl BcCamera {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(MSG_ID_TALKCONFIG, msg_num).await?;
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
if &talk_config.audio_config.audio_type != "adpcm" {
|
||||
return Err(Error::UnknownTalkEncoding);
|
||||
@@ -323,7 +323,7 @@ impl BcCamera {
|
||||
|
||||
let full_block_size = block_size + 4; // Block size + predictor state
|
||||
let msg_num = self.new_message_num();
|
||||
let sub = connection.subscribe(MSG_ID_TALK, msg_num).await?;
|
||||
let sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
const BLOCK_PER_PAYLOAD: usize = 1;
|
||||
const BLOCK_HEADER_SIZE: usize = 4;
|
||||
|
||||
@@ -17,7 +17,7 @@ impl BcCamera {
|
||||
self.has_ability_ro("general").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get_general = connection.subscribe(MSG_ID_GET_GENERAL, msg_num).await?;
|
||||
let mut sub_get_general = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_GENERAL,
|
||||
@@ -102,7 +102,7 @@ impl BcCamera {
|
||||
self.has_ability_rw("general").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set_general = connection.subscribe(MSG_ID_SET_GENERAL, msg_num).await?;
|
||||
let mut sub_set_general = connection.subscribe(msg_num).await?;
|
||||
let set = Bc::new_from_xml(
|
||||
BcMeta {
|
||||
msg_id: MSG_ID_SET_GENERAL,
|
||||
|
||||
@@ -7,7 +7,7 @@ impl BcCamera {
|
||||
self.has_ability_ro("version").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_version = connection.subscribe(MSG_ID_VERSION, msg_num).await?;
|
||||
let mut sub_version = connection.subscribe(msg_num).await?;
|
||||
|
||||
let version = Bc {
|
||||
meta: BcMeta {
|
||||
|
||||
@@ -52,7 +52,7 @@ fn bcudp_ack<'a, W: 'a + Write>(
|
||||
le_u32(0),
|
||||
le_u32(payload.group_id),
|
||||
le_u32(payload.packet_id),
|
||||
le_u32(0xd7160000),
|
||||
le_u32(0),
|
||||
le_u32(binary_payload.len() as u32),
|
||||
slice(binary_payload),
|
||||
))
|
||||
|
||||
@@ -240,17 +240,6 @@ pub struct IpPort {
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
impl std::convert::TryFrom<IpPort> for std::net::SocketAddr {
|
||||
type Error = crate::Error;
|
||||
|
||||
fn try_from(src: IpPort) -> Result<Self, Self::Error> {
|
||||
Ok(src
|
||||
.ip
|
||||
.parse::<std::net::IpAddr>()
|
||||
.map(|ip| std::net::SocketAddr::new(ip, src.port))?)
|
||||
}
|
||||
}
|
||||
|
||||
/// C2R_C xml
|
||||
///
|
||||
/// This is from client to the register reolink server
|
||||
@@ -301,11 +290,11 @@ pub struct R2cT {
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
|
||||
pub struct R2cCr {
|
||||
/// Dev camera location (actual local ip)
|
||||
pub dev: Option<IpPort>,
|
||||
pub dev: IpPort,
|
||||
/// Dmap camera location
|
||||
pub dmap: Option<IpPort>,
|
||||
pub dmap: IpPort,
|
||||
/// The location of the relay
|
||||
pub relay: Option<IpPort>,
|
||||
pub relay: IpPort,
|
||||
/// The nat type. Known values `"NULL"`
|
||||
pub nat: String,
|
||||
/// The camera SID
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "pushnoti"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.71"
|
||||
clap = { version = "4.2.2", features = ["derive", "cargo"] }
|
||||
env_logger = "0.10.0"
|
||||
fcm-push-listener = "2.0.1"
|
||||
lazy_static = "1.4.0"
|
||||
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
|
||||
neolink_core = { path = "../core", version = "0.5" }
|
||||
regex = "1.8.1"
|
||||
serde = "1.0.163"
|
||||
tokio = { version = "1.28.1", features = ["full"] }
|
||||
toml = "0.7.3"
|
||||
validator = "0.16.0"
|
||||
validator_derive = "0.16.0"
|
||||
@@ -0,0 +1,273 @@
|
||||
# Reolink Push Notifications
|
||||
|
||||
This is the test crate to experiment with RE-ing the push notifications for a
|
||||
camera
|
||||
|
||||
The goal here is to connect to Google's firebase cloud messaging system (FCM)
|
||||
and recieve push notificaions for motion updates. This way we can get motion
|
||||
notifications without being logged in to the camera and this will let us
|
||||
disconnect from battery cameras and save power.
|
||||
|
||||
The following is the reolink data for google extracted from ios.
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>AD_UNIT_ID_FOR_BANNER_TEST</key>
|
||||
<string>ca-app-pub-3940256099942544/2934735716</string>
|
||||
<key>AD_UNIT_ID_FOR_INTERSTITIAL_TEST</key>
|
||||
<string>ca-app-pub-3940256099942544/4411468910</string>
|
||||
<key>API_KEY</key>
|
||||
<string>AIzaSyAV5l5DbbAkYB5X61wgn81Lb2f7s1h-ANE</string>
|
||||
<key>BUNDLE_ID</key>
|
||||
<string>com.reo.link</string>
|
||||
<key>CLIENT_ID</key>
|
||||
<string>696841269229-mfqfluqdkb0s2raassbsul48h09l2eiv.apps.googleusercontent.com</string>
|
||||
<key>DATABASE_URL</key>
|
||||
<string>https://reolink-for-ios.firebaseio.com</string>
|
||||
<key>GCM_SENDER_ID</key>
|
||||
<string>696841269229</string>
|
||||
<key>GOOGLE_APP_ID</key>
|
||||
<string>1:696841269229:ios:690529b18debb2e3</string>
|
||||
<key>IS_ADS_ENABLED</key>
|
||||
<false/>
|
||||
<key>IS_ANALYTICS_ENABLED</key>
|
||||
<false/>
|
||||
<key>IS_APPINVITE_ENABLED</key>
|
||||
<false/>
|
||||
<key>IS_GCM_ENABLED</key>
|
||||
<false/>
|
||||
<key>IS_SIGNIN_ENABLED</key>
|
||||
<false/>
|
||||
<key>PLIST_VERSION</key>
|
||||
<string>1</string>
|
||||
<key>PROJECT_ID</key>
|
||||
<string>reolink-for-ios</string>
|
||||
<key>REVERSED_CLIENT_ID</key>
|
||||
<string>com.googleusercontent.apps.696841269229-mfqfluqdkb0s2raassbsul48h09l2eiv</string>
|
||||
<key>STORAGE_BUCKET</key>
|
||||
<string>reolink-for-ios.appspot.com</string>
|
||||
</dict>
|
||||
</plist>
|
||||
```
|
||||
|
||||
Key information from this is
|
||||
|
||||
```xml
|
||||
<key>GCM_SENDER_ID</key>
|
||||
<string>696841269229</string>
|
||||
```
|
||||
|
||||
Which we use to register for FCM
|
||||
|
||||
---
|
||||
|
||||
p.s. maybe some one can do something fun with the API
|
||||
key not sure what thats doing there since anyone can
|
||||
extract that.
|
||||
|
||||
```xml
|
||||
<key>API_KEY</key>
|
||||
<string>AIzaSyAV5l5DbbAkYB5X61wgn81Lb2f7s1h-ANE</string>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
On android the details are little harder for me to extract (ios here). By
|
||||
extracting the apk with apktook I found the following:
|
||||
|
||||
```xml
|
||||
<string name="gcm_defaultSenderId">743639030586</string>
|
||||
<string name="google_api_key">AIzaSyBEUIuWHnnOEwFahxWgQB4Yt4NsgOmkPyE</string>
|
||||
<string name="google_app_id">1:743639030586:android:86f60a4fb7143876</string>
|
||||
<string name="google_client_id">743639030586-ove5uqrausoqtjjkev4b1tk4vjdfpt4l.apps.googleusercontent.com</string>
|
||||
```
|
||||
|
||||
Where the key we need is `743639030586`
|
||||
|
||||
To emulate the push recievier we use the `fcm-push-listener` crate. Which
|
||||
is a rust implementation of the good
|
||||
[RE work of Matthieu Lemoine.](https://medium.com/@MatthieuLemoine/my-journey-to-bring-web-push-support-to-node-and-electron-ce70eea1c0b0)
|
||||
hats off to you.
|
||||
|
||||
We also need to send the PushInfo command to the camera with the token we get
|
||||
from FCM and some client ID. On IOS the token is the APNS number.
|
||||
|
||||
The client ID is an all CAPS UID of hexadecimal of 33 chars. Not sure how
|
||||
these are generated but they seem to be unique to the device, perhaps a MD5 of
|
||||
something or some generated UID on app initial login.
|
||||
|
||||
To experiment I did a data wipe on the reolink app and found it generates a new UID.
|
||||
I also found out that if you do this while you have Push Notifications turned on
|
||||
then you cannot turn them off anymore. To disable the push notifications you need
|
||||
the UID which I just wiped.... Fortunatly I saved before I wiped it so I could restore.
|
||||
p.d. If you every wipe your reolink data and need to stop the push notifications
|
||||
you can try doing manually using the API listed at the end.
|
||||
|
||||
This is the data of the `PushInfo` command that is sent to the camera:
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<PushInfo version="1.1">
|
||||
<token>TOKEN_FROM_FCM_OR_APNS</token>
|
||||
<phoneType>reo_iphone</phoneType>
|
||||
<clientID>SOMEID</clientID>
|
||||
</PushInfo>
|
||||
</body>
|
||||
```
|
||||
|
||||
For ios the phonetype is `reo_iphone` which I observed live but for android
|
||||
no such luck.
|
||||
|
||||
First I just tried `reo_android` but the camera replied with an error code.
|
||||
Which at least told me that I can test other string quickly and see if it
|
||||
returns the error code.
|
||||
|
||||
Next thing to do was dumping the binaries from the apk and searching for a string
|
||||
like `reo_`
|
||||
|
||||
```bash
|
||||
grep -Ria "reo_" .
|
||||
./lib/armeabi-v7a/libavcodec.so:stereo_modeError splitting the input into NAL units.
|
||||
./lib/arm64-v8a/libavcodec.so:stereo_modeError splitting the input into NAL units.
|
||||
./smali_classes2/com/google/android/exoplayer2/extractor/mkv/MatroskaExtractor.smali:.field private static final ID_STEREO_MODE:I = 0x53b8
|
||||
./smali_classes2/com/google/android/exoplayer2/C.smali:.field public static final STEREO_MODE_LEFT_RIGHT:I = 0x2
|
||||
./smali_classes2/com/google/android/exoplayer2/C.smali:.field public static final STEREO_MODE_MONO:I = 0x0
|
||||
./smali_classes2/com/google/android/exoplayer2/C.smali:.field public static final STEREO_MODE_STEREO_MESH:I = 0x3
|
||||
./smali_classes2/com/google/android/exoplayer2/C.smali:.field public static final STEREO_MODE_TOP_BOTTOM:I = 0x1
|
||||
./smali_classes2/com/android/bc/util/DeviceIdUtil$UpdatePushClientIdRequest.smali: const-string v2, "reo_fcm"
|
||||
./smali_classes2/com/android/bc/pushmanager/MyPushAdapterImpl.smali: const-string v0, "reo_fcm"
|
||||
./smali/androidx/core/text/BidiFormatter.smali:.field private static final FLAG_STEREO_RESET:I = 0x2
|
||||
./smali/com/android/bc/component/BaseWebViewFragment.smali: const-string v2, "REO_LANGUAGE="
|
||||
```
|
||||
|
||||
The interesting one was `MyPushAdapterImpl.smali: const-string v0, "reo_fcm"`
|
||||
which suggested that it is `reo_fcm` stuck that in and voilla
|
||||
no error messages from the camera.
|
||||
|
||||
Now to compile the test app with all this info
|
||||
wait patiently for a motion event and...
|
||||
|
||||
viola!
|
||||
|
||||
Reolink was kinda enough to send this to my test app:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"SRVTIME": "2023-05-19T08:07:03.566Z",
|
||||
"ALMNAME": "Motion Alert from Cam01",
|
||||
"sound": "push.wav",
|
||||
"CHNAME": "Cam0",
|
||||
"messageType": "alarm",
|
||||
"DEVNAME": "Cam01",
|
||||
"pushVersion": "v1.1",
|
||||
"UID": "REDACTED",
|
||||
"ALMTYPE": "MD",
|
||||
"ALMCHN": "1",
|
||||
"alert": "Motion Alert from Cam01",
|
||||
"title": "Camera Alert"
|
||||
},
|
||||
"from": "743639030586",
|
||||
"priority": "normal",
|
||||
"notification": { "title": "Camera Alert", "body": "Motion Alert from Cam01" },
|
||||
"fcmMessageId": "REDACTED"
|
||||
}
|
||||
```
|
||||
|
||||
There's no push notifiation for motion stop event but I can wait for this message
|
||||
then login and use normal motion detection to tell when it stops.
|
||||
|
||||
Yay.... now to just add all this to actual neolink so we can save battery.....
|
||||
|
||||
---
|
||||
|
||||
While experimenting with the ios app, in addition to observing all the
|
||||
data send to the camera, I also looked at all https calls the app was making
|
||||
(mitmproxy). This showed a set of APIs that could be useful. Including the api
|
||||
for deleting a push notification.
|
||||
|
||||
---
|
||||
|
||||
To disable a PUSH request the following is done:
|
||||
|
||||
```bash
|
||||
curl -v -X DELETE 'https://pushx.reolink.com/devices/<CAMERA_UID>/notifications/listeners/<clientID_FROM_PushInfo>' -H 'Cookie:'
|
||||
```
|
||||
|
||||
Reply is:
|
||||
|
||||
```json
|
||||
{
|
||||
"status" : {
|
||||
"detail" : "OK",
|
||||
"code" : 0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Nothing seems to be sent to the camera just this to the reolink api
|
||||
|
||||
---
|
||||
|
||||
On ios application start reolink send this:
|
||||
|
||||
```bash
|
||||
curl -v -X GET 'https://pushx.reolink.com/listeners/<clientID_FROM_PushInfo>/devices' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept: */*' -H 'Accept-Language: en-GB,en;q=0.9' -H 'Cookie:'
|
||||
```
|
||||
|
||||
Which resonds with this json which contains a list of all currently
|
||||
enabled push notification camera UIDs for this client
|
||||
|
||||
```json
|
||||
{
|
||||
"status" : {
|
||||
"detail" : "OK",
|
||||
"code" : 0
|
||||
},
|
||||
"data" : [
|
||||
{
|
||||
"uid" : "<CAMERA_UID>",
|
||||
"secret" : ""
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
You can also confirm a device has a listener with
|
||||
|
||||
```bash
|
||||
curl -v -X GET 'https://pushx.reolink.com/devices/<CAMERA_UID>/listeners/<clientID_FROM_PushInfo>/config' -H 'Cookie:'
|
||||
```
|
||||
|
||||
Which returns
|
||||
|
||||
```json
|
||||
{
|
||||
"status": {
|
||||
"code":0,
|
||||
"detail":"OK"
|
||||
},
|
||||
"data": {
|
||||
"sound": {
|
||||
"soundType":0,
|
||||
"soundName":"",
|
||||
"soundVolume":0
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
There's also a profile one that the app does when a new camera is added
|
||||
but I forgot to save the details of it.
|
||||
|
||||
It reports all the capabilities of the camera, such as it's model
|
||||
and its resolution etc. Could be useful to test if a UID is valid
|
||||
quickly
|
||||
@@ -0,0 +1,80 @@
|
||||
use lazy_static::lazy_static;
|
||||
use neolink_core::bc_protocol::{DiscoveryMethods, PrintFormat};
|
||||
use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
use std::clone::Clone;
|
||||
use validator::{Validate, ValidationError};
|
||||
use validator_derive::Validate;
|
||||
|
||||
lazy_static! {
|
||||
static ref RE_STREAM_SRC: Regex =
|
||||
Regex::new(r"^(mainStream|subStream|externStream|both|all)$").unwrap();
|
||||
static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap();
|
||||
static ref RE_PAUSE_MODE: Regex = Regex::new(r"^(black|still|test|none)$").unwrap();
|
||||
static ref RE_MAXENC_SRC: Regex =
|
||||
Regex::new(r"^([nN]one|[Aa][Ee][Ss]|[Bb][Cc][Ee][Nn][Cc][Rr][Yy][Pp][Tt])$").unwrap();
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct Config {
|
||||
#[validate]
|
||||
pub(crate) cameras: Vec<CameraConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
#[validate(schema(function = "validate_camera_config"))]
|
||||
pub(crate) struct CameraConfig {
|
||||
pub(crate) name: String,
|
||||
|
||||
#[serde(rename = "address")]
|
||||
pub(crate) camera_addr: Option<String>,
|
||||
|
||||
#[serde(rename = "uid")]
|
||||
pub(crate) camera_uid: Option<String>,
|
||||
|
||||
pub(crate) username: String,
|
||||
pub(crate) password: Option<String>,
|
||||
|
||||
#[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))]
|
||||
#[serde(default = "default_channel_id")]
|
||||
pub(crate) channel_id: u8,
|
||||
|
||||
#[serde(default = "default_discovery")]
|
||||
pub(crate) discovery: DiscoveryMethods,
|
||||
|
||||
#[serde(default = "default_maxenc")]
|
||||
#[validate(regex(
|
||||
path = "RE_MAXENC_SRC",
|
||||
message = "Invalid maximum encryption method",
|
||||
code = "max_encryption"
|
||||
))]
|
||||
pub(crate) max_encryption: String,
|
||||
|
||||
#[serde(default = "default_print", alias = "print")]
|
||||
pub(crate) print_format: PrintFormat,
|
||||
}
|
||||
|
||||
fn default_print() -> PrintFormat {
|
||||
PrintFormat::None
|
||||
}
|
||||
|
||||
fn default_discovery() -> DiscoveryMethods {
|
||||
DiscoveryMethods::Relay
|
||||
}
|
||||
|
||||
fn default_maxenc() -> String {
|
||||
"Aes".to_string()
|
||||
}
|
||||
|
||||
fn default_channel_id() -> u8 {
|
||||
0
|
||||
}
|
||||
|
||||
fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> {
|
||||
match (&camera_config.camera_addr, &camera_config.camera_uid) {
|
||||
(None, None) => Err(ValidationError::new(
|
||||
"Either camera address or uid must be given",
|
||||
)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use fcm_push_listener::*;
|
||||
use log::*;
|
||||
use std::{fs, path::PathBuf};
|
||||
use validator::Validate;
|
||||
|
||||
mod config;
|
||||
mod opt;
|
||||
mod utils;
|
||||
|
||||
use config::Config;
|
||||
use opt::Opt;
|
||||
use utils::find_and_connect;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
|
||||
let opt = Opt::parse();
|
||||
|
||||
let conf_path = opt.config.context("Must supply --config file")?;
|
||||
let config: Config = toml::from_str(
|
||||
&fs::read_to_string(&conf_path)
|
||||
.with_context(|| format!("Failed to read {:?}", conf_path))?,
|
||||
)
|
||||
.with_context(|| format!("Failed to parse the {:?} config file", conf_path))?;
|
||||
|
||||
config
|
||||
.validate()
|
||||
.with_context(|| format!("Failed to validate the {:?} config file", conf_path))?;
|
||||
|
||||
let camera = find_and_connect(&config, &opt.camera).await?;
|
||||
|
||||
// 696841269229 is the reo_iphone FCM Sender_ID
|
||||
// let registration = fcm_push_listener::register("696841269229").await?;
|
||||
// 743639030586 is the reo_fcm FCM Sender_ID
|
||||
// 263684512460 is my test Sender_ID
|
||||
// let registration = fcm_push_listener::register("743639030586").await?
|
||||
// I have confirmed that I can recieve test messages with this SenderID
|
||||
// into this program
|
||||
// let registration = fcm_push_listener::register("263684512460").await?;
|
||||
|
||||
let sender_id = "743639030586"; // andriod
|
||||
|
||||
// let sender_id = "696841269229"; // ios
|
||||
|
||||
// let sender_id = "263684512460"; // test
|
||||
|
||||
let token_path = PathBuf::from("./token.toml");
|
||||
let registration = if let Ok(Ok(registration)) =
|
||||
fs::read_to_string(&token_path).map(|v| toml::from_str::<Registration>(&v))
|
||||
{
|
||||
info!("Loaded token");
|
||||
registration
|
||||
} else {
|
||||
info!("Registering new token");
|
||||
let registration = fcm_push_listener::register(sender_id).await?;
|
||||
let new_token = toml::to_string(®istration)?;
|
||||
fs::write(token_path, new_token)?;
|
||||
registration
|
||||
};
|
||||
|
||||
// Send registration.fcm_token to the server to allow it to send push messages to you.
|
||||
info!("registration.fcm_token: {}", registration.fcm_token);
|
||||
let uid = "6A5443E486511B0D828543445DC55A7D"; // MD5 Hash of "WHY_REOLINK"
|
||||
camera
|
||||
.send_pushinfo_android(®istration.fcm_token, uid)
|
||||
.await?;
|
||||
|
||||
info!("Listening");
|
||||
let mut listener = FcmPushListener::create(
|
||||
registration,
|
||||
|message: FcmMessage| {
|
||||
info!("Message JSON: {}", message.payload_json);
|
||||
info!("Persistent ID: {:?}", message.persistent_id);
|
||||
},
|
||||
vec![],
|
||||
);
|
||||
listener.connect().await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
use clap::{crate_authors, crate_version, Parser};
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// A standards-compliant bridge to Reolink IP cameras
|
||||
///
|
||||
/// Neolink is free software released under the GNU AGPL v3.
|
||||
/// You can find its source code at https://github.com/thirtythreeforty/neolink
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "pushnoti", arg_required_else_help = true, version = crate_version!(), author = crate_authors!("\n"))]
|
||||
pub struct Opt {
|
||||
#[arg(short, long, value_parser = PathBuf::from_str)]
|
||||
pub config: Option<PathBuf>,
|
||||
/// The name of the camera. Must be a name in the config
|
||||
pub camera: String,
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Contains code that is not specific to any of the subcommands
|
||||
//!
|
||||
use log::*;
|
||||
|
||||
use super::config::{CameraConfig, Config};
|
||||
use anyhow::{anyhow, Context, Error, Result};
|
||||
use neolink_core::bc_protocol::{
|
||||
BcCamera, BcCameraOpt, ConnectionProtocol, Credentials, DiscoveryMethods, MaxEncryption,
|
||||
};
|
||||
use std::{
|
||||
fmt::{Display, Error as FmtError, Formatter},
|
||||
net::{IpAddr, ToSocketAddrs},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
pub(crate) enum AddressOrUid {
|
||||
Address(String),
|
||||
Uid(String, DiscoveryMethods),
|
||||
AddressWithUid(String, String, DiscoveryMethods),
|
||||
}
|
||||
|
||||
impl Display for AddressOrUid {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
|
||||
match self {
|
||||
AddressOrUid::AddressWithUid(addr, uid, _) => {
|
||||
write!(f, "Address: {}, UID: {}", addr, uid)
|
||||
}
|
||||
AddressOrUid::Address(host) => write!(f, "Address: {}", host),
|
||||
AddressOrUid::Uid(host, _) => write!(f, "UID: {}", host),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressOrUid {
|
||||
// Created by translating the config fields directly
|
||||
pub(crate) fn new(
|
||||
address: &Option<String>,
|
||||
uid: &Option<String>,
|
||||
method: &DiscoveryMethods,
|
||||
) -> Result<Self, Error> {
|
||||
match (address, uid) {
|
||||
(None, None) => Err(anyhow!("Neither address or uid given")),
|
||||
(Some(host), Some(uid)) => Ok(AddressOrUid::AddressWithUid(
|
||||
host.clone(),
|
||||
uid.clone(),
|
||||
*method,
|
||||
)),
|
||||
(Some(host), None) => Ok(AddressOrUid::Address(host.clone())),
|
||||
(None, Some(host)) => Ok(AddressOrUid::Uid(host.clone(), *method)),
|
||||
}
|
||||
}
|
||||
|
||||
// Convience method to get the BcCamera with the appropiate method
|
||||
// from a camera_config
|
||||
pub(crate) async fn connect_camera(
|
||||
&self,
|
||||
camera_config: &CameraConfig,
|
||||
) -> Result<BcCamera, Error> {
|
||||
let (port, addrs) = {
|
||||
if let Some(addr_str) = camera_config.camera_addr.as_ref() {
|
||||
match addr_str.to_socket_addrs() {
|
||||
Ok(addr_iter) => {
|
||||
let mut port = None;
|
||||
let mut ipaddrs = vec![];
|
||||
for addr in addr_iter {
|
||||
port = Some(addr.port());
|
||||
ipaddrs.push(addr.ip());
|
||||
}
|
||||
Ok((port, ipaddrs))
|
||||
}
|
||||
Err(_) => match IpAddr::from_str(addr_str) {
|
||||
Ok(ip) => Ok((None, vec![ip])),
|
||||
Err(_) => Err(anyhow!("Could not parse address in config")),
|
||||
},
|
||||
}
|
||||
} else {
|
||||
Ok((None, vec![]))
|
||||
}
|
||||
}?;
|
||||
|
||||
let options = BcCameraOpt {
|
||||
name: camera_config.name.clone(),
|
||||
channel_id: camera_config.channel_id,
|
||||
addrs,
|
||||
port,
|
||||
uid: camera_config.camera_uid.clone(),
|
||||
protocol: ConnectionProtocol::TcpUdp,
|
||||
discovery: camera_config.discovery,
|
||||
aux_printing: camera_config.print_format,
|
||||
credentials: Credentials {
|
||||
username: camera_config.username.clone(),
|
||||
password: camera_config.password.clone(),
|
||||
},
|
||||
};
|
||||
|
||||
trace!("Camera Info: {:?}", options);
|
||||
|
||||
Ok(BcCamera::new(&options).await?)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn find_and_connect(config: &Config, name: &str) -> Result<BcCamera> {
|
||||
let camera_config = find_camera_by_name(config, name)?;
|
||||
connect_and_login(camera_config).await
|
||||
}
|
||||
|
||||
pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result<BcCamera> {
|
||||
let camera_addr = AddressOrUid::new(
|
||||
&camera_config.camera_addr,
|
||||
&camera_config.camera_uid,
|
||||
&camera_config.discovery,
|
||||
)
|
||||
.unwrap();
|
||||
info!(
|
||||
"{}: Connecting to camera at {}",
|
||||
camera_config.name, camera_addr
|
||||
);
|
||||
|
||||
let camera = camera_addr
|
||||
.connect_camera(camera_config)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to connect to camera {} at {} on channel {}",
|
||||
camera_config.name, camera_addr, camera_config.channel_id
|
||||
)
|
||||
})?;
|
||||
|
||||
let max_encryption = match camera_config.max_encryption.to_lowercase().as_str() {
|
||||
"none" => MaxEncryption::None,
|
||||
"bcencrypt" => MaxEncryption::BcEncrypt,
|
||||
"aes" => MaxEncryption::Aes,
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera
|
||||
.login_with_maxenc(max_encryption)
|
||||
.await
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
|
||||
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
Ok(camera)
|
||||
}
|
||||
|
||||
pub(crate) fn find_camera_by_name<'a>(config: &'a Config, name: &str) -> Result<&'a CameraConfig> {
|
||||
config
|
||||
.cameras
|
||||
.iter()
|
||||
.find(|c| c.name == name)
|
||||
.ok_or_else(|| anyhow!("Camera {} not found in the config file", name))
|
||||
}
|
||||
@@ -88,7 +88,6 @@ local message_types = {
|
||||
[15]="<FileInfoList>",
|
||||
[16]="<FileInfoList>",
|
||||
[18]="<PtzControl>",
|
||||
[19]="<PtzPreset>",
|
||||
[23]="Reboot",
|
||||
[25]="<VideoInput> (write)",
|
||||
[26]="<VideoInput>", -- <InputAdvanceCfg>
|
||||
@@ -147,11 +146,14 @@ local message_types = {
|
||||
[106]="<Dst>",
|
||||
[107]="<Dst> (write)",
|
||||
[108]="<ConfigFileInfo> (log)",
|
||||
[109]="<Snap>",
|
||||
[114]="<Uid>",
|
||||
[115]="<WifiSignal>",
|
||||
[116]="<Wifi>",
|
||||
[120]="<OnlineUserList>",
|
||||
[122]="<PerformanceInfo>",
|
||||
[123]="<ReplaySeek>",
|
||||
[124]="<PushInfo>",
|
||||
[132]="<VideoInput>", -- <InputAdvanceCfg>
|
||||
[133]="<RfAlarm>",
|
||||
[141]="<Email> (test)",
|
||||
@@ -161,6 +163,7 @@ local message_types = {
|
||||
[151]="<AbilityInfo>",
|
||||
[190]="PTZ Preset",
|
||||
[194]="<Ftp> (test)",
|
||||
[195]="<AutoUpdate>",
|
||||
[199]="<Support>",
|
||||
[208]="<LedState>",
|
||||
[209]="<LedState> (write)",
|
||||
@@ -175,9 +178,13 @@ local message_types = {
|
||||
[228]="<Crop>",
|
||||
[229]="<Crop> (write)",
|
||||
[230]="<cropSnap>",
|
||||
[232]="<AudioTask>",
|
||||
[234]="UDP Keep Alive",
|
||||
[252]="<BatteryInfoList>",
|
||||
[253]="<BatteryInfo>",
|
||||
[268]="<CloudBindInfo>",
|
||||
[282]="<CloudLoginKey>",
|
||||
[287]="<TimeCfg>",
|
||||
[272]="<findAlarmVideo>",
|
||||
[273]="<alarmVideoInfo>",
|
||||
[274]="<findAlarmVideo>",
|
||||
|
||||
+316
-49
@@ -354,10 +354,6 @@ Message have zero to two payloads.
|
||||
</PtzControl>
|
||||
</body>
|
||||
```
|
||||
|
||||
- **Notes** : The known movement commands are `"left"`, `"right"`, `"up"`, `"down"`, `"leftUp"`,
|
||||
`"leftDown"`, `"rightUp"`, `"rightDown"` and `"stop"` although the diagonal movement
|
||||
does not seem to work.
|
||||
|
||||
- Camera
|
||||
|
||||
@@ -367,45 +363,6 @@ Message have zero to two payloads.
|
||||
|--------------|--------------|----------------|-------------------|-------------------|---------------|---------------|
|
||||
| 0a bc de f0 | 00 00 00 12 | 00 00 00 00 | 1e 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
|
||||
|
||||
- 19: `<PtzPreset>`
|
||||
|
||||
- Client
|
||||
|
||||
- Header
|
||||
|
||||
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|
||||
|--------------|-------------|----------------|-------------------|-------------------|---------------|---------------|
|
||||
| 0a bc de f0 | 00 00 00 13 | 00 00 01 44 | 1e 00 00 00 | 00 00 | 64 14 | 00 00 00 00 |
|
||||
|
||||
- Payload
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<PtzPreset version="1.1">
|
||||
<channelId>0</channelId>
|
||||
<presetList>
|
||||
<preset>
|
||||
<id>0</id>
|
||||
<command>setPos</command>
|
||||
<name>Test</name>
|
||||
</preset>
|
||||
</presetList>
|
||||
</PtzPreset>
|
||||
</body>
|
||||
```
|
||||
|
||||
- **Notes** : The known values for command are `"setPos"` and `"toPos"`
|
||||
|
||||
- Camera
|
||||
|
||||
- Header
|
||||
|
||||
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|
||||
|--------------|-------------|----------------|-------------------|-------------------|---------------|---------------|
|
||||
| 0a bc de f0 | 00 00 00 13 | 00 00 00 00 | 1e 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
|
||||
|
||||
|
||||
- 23: `Reboot`
|
||||
|
||||
- Client
|
||||
@@ -1705,6 +1662,64 @@ Message have zero to two payloads.
|
||||
</body>
|
||||
```
|
||||
|
||||
- 109: `<Snap>`
|
||||
|
||||
- Client:
|
||||
Usual header
|
||||
|
||||
- Meta:
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<Extension version="1.1">
|
||||
<channelId>0</channelId>
|
||||
</Extension>
|
||||
```
|
||||
|
||||
- Main:
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<Snap version="1.1">
|
||||
<channelId>0</channelId>
|
||||
<logicChannel>0</logicChannel>
|
||||
<time>0</time>
|
||||
<fullFrame>0</fullFrame>
|
||||
<streamType>main</streamType>
|
||||
</Snap>
|
||||
</body>
|
||||
```
|
||||
|
||||
- Camera:
|
||||
|
||||
**Notes:** XML & Binary reply over mutliple packets:
|
||||
- Reply 1:
|
||||
- Main:
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<Snap version="1.1">
|
||||
<channelId>0</channelId>
|
||||
<fileName>01_20230518140240.jpg</fileName>
|
||||
<time>0</time>
|
||||
<pictureSize>23644</pictureSize>
|
||||
</Snap>
|
||||
</body>
|
||||
```
|
||||
|
||||
- Reply 2:
|
||||
- Meta:
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<Extension version="1.1">
|
||||
<binaryData>1</binaryData>
|
||||
</Extension>
|
||||
```
|
||||
- Main:
|
||||
**Binary data containing the file may be broken over multiple packets**
|
||||
|
||||
|
||||
- 115: `<WifiSignal>`
|
||||
|
||||
- Client
|
||||
@@ -1734,6 +1749,35 @@ Message have zero to two payloads.
|
||||
</body>
|
||||
```
|
||||
|
||||
- 116: `<Wifi>`
|
||||
|
||||
- Client:
|
||||
Usual header
|
||||
|
||||
- Camera:
|
||||
Payload:
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<Wifi version="1.1">
|
||||
<mode>station</mode>
|
||||
<authMode>wpa2psk</authMode>
|
||||
<encryptType>aes</encryptType>
|
||||
<udidList>
|
||||
<udid>
|
||||
<name>WIFINAME</name>
|
||||
<signal>NUMBER</signal>
|
||||
<encrypt>ONE_OR_ZERO</encrypt>
|
||||
</udid>
|
||||
# Repeats for ALL wifi in range
|
||||
</udidList>
|
||||
<ssid>YOUR_CURRENT_WIFI</ssid>
|
||||
<key>YOUR_CURRENT_WIFI_PASSWORD_UNENCRYPTED</key>
|
||||
<channel>YOUR_CURRENT_WIFI_CHANNEL</channel>
|
||||
</Wifi>
|
||||
</body>
|
||||
```
|
||||
|
||||
- 132: `<VideoInput>`
|
||||
|
||||
- Client
|
||||
@@ -1846,6 +1890,37 @@ Message have zero to two payloads.
|
||||
</body>
|
||||
```
|
||||
|
||||
- 124: `<PushInfo>`
|
||||
|
||||
- Client
|
||||
- Payload:
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<PushInfo version="1.1">
|
||||
<token>A_PUSH_NOTIFICATION_TOKEN</token>
|
||||
<phoneType>reo_iphone</phoneType>
|
||||
<clientID>A_PUSH_NOTIFICATION_CLIENTID</clientID>
|
||||
</PushInfo>
|
||||
</body>
|
||||
```
|
||||
|
||||
- Camera
|
||||
- Payload
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<PushRspInfo version="1.1">
|
||||
<registerHandle>-1</registerHandle>
|
||||
<uid>CAMERA_UID</uid>
|
||||
<uidKey>A_4_CHAR_STRING</uidKey>
|
||||
</PushRspInfo>
|
||||
</body>
|
||||
```
|
||||
|
||||
|
||||
- 133: `<RfAlarm>`
|
||||
|
||||
- Client
|
||||
@@ -2030,12 +2105,7 @@ Message have zero to two payloads.
|
||||
<body>
|
||||
<PtzPreset version="1.1">
|
||||
<channelId>0</channelId>
|
||||
<presetList>
|
||||
<preset>
|
||||
<id>0</id>
|
||||
<name>Test</name>
|
||||
</preset>
|
||||
</presetList>
|
||||
<presetList />
|
||||
</PtzPreset>
|
||||
</body>
|
||||
```
|
||||
@@ -2386,6 +2456,154 @@ Message have zero to two payloads.
|
||||
|--------------|--------------|----------------|-------------------|-------------------|---------------|---------------|
|
||||
| 0a bc de f0 | 00 00 00 d1 | 00 00 00 00 | 85 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
|
||||
|
||||
- 219: `<PushTask>`
|
||||
- Client
|
||||
Usual header
|
||||
|
||||
- Meta:
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<Extension version="1.1">
|
||||
<channelId>0</channelId>
|
||||
</Extension>
|
||||
```
|
||||
- Camera
|
||||
Usual header
|
||||
|
||||
- Payload:
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<PushTask version="1.1">
|
||||
<channelId>0</channelId>
|
||||
<enable>1</enable>
|
||||
<ScheduleList>
|
||||
<Schedule>
|
||||
<alarmType>MD</alarmType>
|
||||
<timeBlockList>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Sunday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Monday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Tuesday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Wednesday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Thursday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Friday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Saturday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
</timeBlockList>
|
||||
</Schedule>
|
||||
</ScheduleList>
|
||||
</PushTask>
|
||||
</body>
|
||||
```
|
||||
|
||||
|
||||
- 232: `<AudioTask>`
|
||||
- Client
|
||||
Usual header
|
||||
|
||||
- Meta:
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<Extension version="1.1">
|
||||
<channelId>0</channelId>
|
||||
</Extension>
|
||||
```
|
||||
- Camera
|
||||
Usual header
|
||||
|
||||
- Payload:
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<AudioTask version="1.1">
|
||||
<channelId>0</channelId>
|
||||
<enable>0</enable>
|
||||
<ScheduleList>
|
||||
<Schedule>
|
||||
<alarmType>MD</alarmType>
|
||||
<timeBlockList>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Sunday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Monday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Tuesday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Wednesday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Thursday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Friday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
<timeBlock>
|
||||
<enable>1</enable>
|
||||
<weekDay>Saturday</weekDay>
|
||||
<beginHour>0</beginHour>
|
||||
<endHour>23</endHour>
|
||||
</timeBlock>
|
||||
</timeBlockList>
|
||||
</Schedule>
|
||||
</ScheduleList>
|
||||
</AudioTask>
|
||||
</body>
|
||||
```
|
||||
|
||||
- 264: `<audioCfg>` (write)
|
||||
|
||||
@@ -2421,6 +2639,55 @@ Message have zero to two payloads.
|
||||
</body>
|
||||
```
|
||||
|
||||
- 268: `CloudBindInfo`
|
||||
- Client:
|
||||
Usual header only packet
|
||||
|
||||
- Camera
|
||||
|
||||
- Payload
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<CloudBindInfo version="1.1">
|
||||
<binded>1</binded>
|
||||
</CloudBindInfo>
|
||||
</body>
|
||||
```
|
||||
|
||||
- 282: `CloudLoginKey`
|
||||
|
||||
- Client:
|
||||
Usual header only packet
|
||||
|
||||
- Camera
|
||||
- Payload
|
||||
|
||||
```xml
|
||||
<body>
|
||||
<CloudLoginKey version="1.1">
|
||||
<enable>0</enable>
|
||||
</CloudLoginKey>
|
||||
</body>
|
||||
```
|
||||
|
||||
- 287: `<TimeCfg>`
|
||||
- Client:
|
||||
- Payload
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<TimeCfg version="1.1">
|
||||
<realTime>1684393362</realTime>
|
||||
</TimeCfg>
|
||||
</body>
|
||||
```
|
||||
|
||||
- Camera
|
||||
Header only 200 Ok reply
|
||||
|
||||
- 288: `<FloodlightManual>` (write)
|
||||
|
||||
- Client
|
||||
|
||||
@@ -38,10 +38,6 @@ address = "192.168.1.187:9000"
|
||||
# mqtt.broker_addr = "192.168.1.122"
|
||||
# mqtt.port = 1883
|
||||
# mqtt.credentials = ["mqtt_user", "mqtt_password"]
|
||||
# MQTT Discovery: https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
|
||||
# mqtt.discovery.topic = "homeassistant" # Uncomment to enable
|
||||
# If using discovery, _ characters are replaced with spaces in the name and title case is applied
|
||||
# mqtt.discovery.features = ["floodlight"] # Uncomment if this camera has a spotlight/floodlight
|
||||
|
||||
# If you use a battery camera: **Instead** of an `address` supply the uid
|
||||
# as follows
|
||||
@@ -65,8 +61,6 @@ address = "192.168.1.187:9000"
|
||||
# "remote" # Register our local ip address with reolink but only permit same network connections (useful if broadcast is not possible)
|
||||
# "local" # Do not contact reolink servers at all. Rely soley on local UDP broadcast based discovery
|
||||
#
|
||||
# "cellular" # Cellular camera only support Relay and Map to speed up connecting to them this option will skip the local/remote
|
||||
#
|
||||
# discovery = "relay"
|
||||
|
||||
# Certain types of camera emit status messages (such as battery levels)
|
||||
|
||||
@@ -21,7 +21,6 @@ pub enum Command {
|
||||
StatusLight(super::statusled::Opt),
|
||||
Reboot(super::reboot::Opt),
|
||||
Pir(super::pir::Opt),
|
||||
Ptz(super::ptz::Opt),
|
||||
Talk(super::talk::Opt),
|
||||
Mqtt(super::mqtt::Opt),
|
||||
Image(super::image::Opt),
|
||||
|
||||
+2
-32
@@ -1,10 +1,8 @@
|
||||
use crate::mqtt::Discoveries;
|
||||
use lazy_static::lazy_static;
|
||||
use neolink_core::bc_protocol::{DiscoveryMethods, PrintFormat};
|
||||
use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
use std::clone::Clone;
|
||||
use std::collections::HashSet;
|
||||
use validator::{Validate, ValidationError};
|
||||
use validator_derive::Validate;
|
||||
|
||||
@@ -106,7 +104,7 @@ pub(crate) struct CameraConfig {
|
||||
pub(crate) update_time: bool,
|
||||
|
||||
#[validate(range(
|
||||
min = 0,
|
||||
min = 10,
|
||||
max = 500,
|
||||
message = "Invalid buffer size",
|
||||
code = "buffer_size"
|
||||
@@ -120,9 +118,6 @@ pub(crate) struct CameraConfig {
|
||||
alias = "stretching"
|
||||
)]
|
||||
pub(crate) use_smoothing: bool,
|
||||
|
||||
#[serde(default = "default_true", alias = "splash")]
|
||||
pub(crate) use_splash: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
@@ -151,27 +146,6 @@ pub(crate) struct MqttConfig {
|
||||
|
||||
#[serde(default)]
|
||||
pub(crate) client_auth: Option<(std::path::PathBuf, std::path::PathBuf)>,
|
||||
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_motion: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_pings: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_light: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_battery: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_preview: bool,
|
||||
|
||||
#[serde(default)]
|
||||
pub(crate) discovery: Option<MqttDiscoveryConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Clone, Validate)]
|
||||
pub(crate) struct MqttDiscoveryConfig {
|
||||
pub(crate) topic: String,
|
||||
|
||||
pub(crate) features: HashSet<Discoveries>,
|
||||
}
|
||||
|
||||
fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
|
||||
@@ -184,10 +158,6 @@ fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
|
||||
}
|
||||
}
|
||||
|
||||
const fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_mqtt() -> Option<MqttConfig> {
|
||||
None
|
||||
}
|
||||
@@ -290,7 +260,7 @@ fn default_smoothing() -> bool {
|
||||
}
|
||||
|
||||
fn default_buffer_size() -> usize {
|
||||
25
|
||||
100
|
||||
}
|
||||
|
||||
pub(crate) static RESERVED_NAMES: &[&str] = &["anyone", "anonymous"];
|
||||
|
||||
@@ -10,9 +10,4 @@ pub struct Opt {
|
||||
/// The path of the output.
|
||||
#[structopt(short, long, value_parser = PathBuf::from_str)]
|
||||
pub file_path: PathBuf,
|
||||
/// If set then the image will pull from the live stream, if not it will be pulled from the cameras snap feature
|
||||
///
|
||||
/// Using the snap feature, is preffered unless your camera does not support it
|
||||
#[structopt(short, long)]
|
||||
pub use_stream: bool,
|
||||
}
|
||||
+35
-54
@@ -9,18 +9,9 @@
|
||||
/// neolink image --config=config.toml --file-path=filepath CameraName
|
||||
/// ```
|
||||
///
|
||||
/// Cameras that do not support the SNAP command need to use `--use_stream`
|
||||
/// which will make the camera play the stream and transcode the video into a jpeg
|
||||
/// e.g.:
|
||||
///
|
||||
/// ```bash
|
||||
/// neolink image --config=config.toml --use_stream --file-path=filepath CameraName
|
||||
/// ```
|
||||
///
|
||||
use anyhow::{Context, Result};
|
||||
use log::*;
|
||||
use neolink_core::{bc_protocol::*, bcmedia::model::*};
|
||||
use tokio::{fs::File, io::AsyncWriteExt};
|
||||
|
||||
mod cmdline;
|
||||
mod gst;
|
||||
@@ -41,54 +32,44 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
let camera = connect_and_login(camera_config)
|
||||
.await
|
||||
.context("Failed to connect to the camera, check credentials and network")?;
|
||||
let mut stream_data = camera
|
||||
.start_video(StreamKind::Main, 0, camera_config.strict)
|
||||
.await
|
||||
.context("Failed to start video")?;
|
||||
|
||||
if opt.use_stream {
|
||||
let mut stream_data = camera
|
||||
.start_video(StreamKind::Main, 0, camera_config.strict)
|
||||
.await
|
||||
.context("Failed to start video")?;
|
||||
|
||||
// Get one iframe at the start while also getting the the video type
|
||||
let buf;
|
||||
let vid_type;
|
||||
loop {
|
||||
if let BcMedia::Iframe(frame) = stream_data.get_data().await?? {
|
||||
vid_type = frame.video_type;
|
||||
buf = frame.data;
|
||||
break;
|
||||
}
|
||||
// Get one iframe at the start while also getting the the video type
|
||||
let buf;
|
||||
let vid_type;
|
||||
loop {
|
||||
if let BcMedia::Iframe(frame) = stream_data.get_data().await?? {
|
||||
vid_type = frame.video_type;
|
||||
buf = frame.data;
|
||||
break;
|
||||
}
|
||||
|
||||
let mut sender = gst::from_input(vid_type, &opt.file_path).await?;
|
||||
sender.send(buf).await?; // Send first iframe
|
||||
|
||||
// Keep sending both IFrame or PFrame until finished
|
||||
while sender.is_finished().await.is_none() {
|
||||
let buf = match stream_data.get_data().await?? {
|
||||
BcMedia::Iframe(frame) => frame.data,
|
||||
BcMedia::Pframe(frame) => frame.data,
|
||||
_ => {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
debug!("Sending frame data to gstreamer");
|
||||
if sender.send(buf).await.is_err() {
|
||||
// Assume that the sender is closed
|
||||
// because the pipeline is finished
|
||||
break;
|
||||
}
|
||||
}
|
||||
debug!("Sending EOS");
|
||||
let _ = sender.eos().await; // Ignore return because if pipeline is finished this will error
|
||||
} else {
|
||||
// Simply use the snap command
|
||||
debug!("Using the snap command");
|
||||
let file_path = opt.file_path.with_extension("jpeg");
|
||||
let mut buffer = File::create(file_path).await?;
|
||||
let jpeg_data = camera.get_snapshot().await?;
|
||||
buffer.write_all(jpeg_data.as_slice()).await?;
|
||||
}
|
||||
|
||||
let mut sender = gst::from_input(vid_type, &opt.file_path).await?;
|
||||
sender.send(buf).await?; // Send first iframe
|
||||
|
||||
// Keep sending both IFrame or PFrame until finished
|
||||
while sender.is_finished().await.is_none() {
|
||||
let buf = match stream_data.get_data().await?? {
|
||||
BcMedia::Iframe(frame) => frame.data,
|
||||
BcMedia::Pframe(frame) => frame.data,
|
||||
_ => {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
debug!("Sending frame data to gstreamer");
|
||||
if sender.send(buf).await.is_err() {
|
||||
// Assume that the sender is closed
|
||||
// because the pipeline is finished
|
||||
break;
|
||||
}
|
||||
}
|
||||
debug!("Sending EOS");
|
||||
let _ = sender.eos().await; // Ignore return because if pipeline is finished this will error
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -34,7 +34,6 @@ mod config;
|
||||
mod image;
|
||||
mod mqtt;
|
||||
mod pir;
|
||||
mod ptz;
|
||||
mod reboot;
|
||||
mod rtsp;
|
||||
mod statusled;
|
||||
@@ -103,9 +102,6 @@ async fn main() -> Result<()> {
|
||||
Some(Command::Pir(opts)) => {
|
||||
pir::main(opts, config).await?;
|
||||
}
|
||||
Some(Command::Ptz(opts)) => {
|
||||
ptz::main(opts, config).await?;
|
||||
}
|
||||
Some(Command::Talk(opts)) => {
|
||||
talk::main(opts, config).await?;
|
||||
}
|
||||
|
||||
@@ -1,570 +0,0 @@
|
||||
//! Enable and configures home assistant MQTTT discovery
|
||||
//!
|
||||
//! https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
|
||||
//!
|
||||
use anyhow::{Context, Result};
|
||||
use heck::ToTitleCase;
|
||||
use log::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::mqttc::MqttSender;
|
||||
use crate::config::{CameraConfig, MqttDiscoveryConfig};
|
||||
use serde::{Deserialize, Serialize, Serializer};
|
||||
|
||||
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Copy, Hash)]
|
||||
pub(crate) enum Discoveries {
|
||||
#[serde(alias = "floodlight", alias = "light")]
|
||||
Floodlight,
|
||||
#[serde(alias = "camera")]
|
||||
Camera,
|
||||
#[serde(alias = "motion", alias = "md", alias = "pir")]
|
||||
Motion,
|
||||
#[serde(alias = "led")]
|
||||
Led,
|
||||
#[serde(alias = "ir")]
|
||||
Ir,
|
||||
#[serde(alias = "reboot")]
|
||||
Reboot,
|
||||
#[serde(alias = "pt")]
|
||||
Pt,
|
||||
#[serde(alias = "battery", alias = "power")]
|
||||
Battery,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct DiscoveryConnection {
|
||||
connection_type: String,
|
||||
connection_id: String,
|
||||
}
|
||||
|
||||
impl Serialize for DiscoveryConnection {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
vec![&self.connection_type, &self.connection_id].serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, Clone)]
|
||||
struct DiscoveryDevice {
|
||||
name: String,
|
||||
connections: Vec<DiscoveryConnection>,
|
||||
identifiers: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
manufacturer: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
model: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
sw_version: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, Clone)]
|
||||
struct DiscoveryAvaliablity {
|
||||
topic: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
payload_available: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
payload_not_available: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoveryLight {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// Light specific
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
state_topic: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
state_value_template: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
command_topic: Option<String>,
|
||||
payload_on: String,
|
||||
payload_off: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
#[allow(dead_code)]
|
||||
enum Encoding {
|
||||
None,
|
||||
#[serde(rename = "b64")]
|
||||
Base64,
|
||||
}
|
||||
|
||||
impl Encoding {
|
||||
fn is_none(&self) -> bool {
|
||||
matches!(self, Self::None)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoveryCamera {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// Camera specific
|
||||
topic: String,
|
||||
#[serde(skip_serializing_if = "Encoding::is_none")]
|
||||
image_encoding: Encoding,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoverySwitch {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// Switch specific
|
||||
// - Control
|
||||
command_topic: String,
|
||||
payload_off: String,
|
||||
payload_on: String,
|
||||
// - State
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
state_topic: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
state_off: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
state_on: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoverySelect {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// Switch specific
|
||||
// - Control
|
||||
command_topic: String,
|
||||
options: Vec<String>,
|
||||
// - State
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
state_topic: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoveryBinarySensor {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// BinarySensor specific
|
||||
payload_off: String,
|
||||
payload_on: String,
|
||||
// - State
|
||||
state_topic: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoveryButton {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// Button specific
|
||||
command_topic: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
payload_press: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct DiscoverySensor {
|
||||
name: String,
|
||||
unique_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
device: DiscoveryDevice,
|
||||
availability: DiscoveryAvaliablity,
|
||||
// Button specific
|
||||
state_topic: String,
|
||||
state_class: String,
|
||||
unit_of_measurement: String,
|
||||
}
|
||||
|
||||
/// Enables MQTT discovery for a camera. See docs at https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
|
||||
pub(crate) async fn enable_discovery(
|
||||
discovery_config: &MqttDiscoveryConfig,
|
||||
mqtt_sender: &MqttSender,
|
||||
cam_config: &Arc<CameraConfig>,
|
||||
) -> Result<()> {
|
||||
debug!("Enabling MQTT discovery for {}", cam_config.name);
|
||||
|
||||
let mut connections = vec![];
|
||||
if let Some(addr) = &cam_config.camera_addr {
|
||||
connections.push(DiscoveryConnection {
|
||||
connection_type: "camera_addr".to_string(),
|
||||
connection_id: addr.clone(),
|
||||
});
|
||||
}
|
||||
if let Some(uid) = &cam_config.camera_uid {
|
||||
connections.push(DiscoveryConnection {
|
||||
connection_type: "camera_uid".to_string(),
|
||||
connection_id: uid.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
if connections.is_empty() {
|
||||
error!(
|
||||
"No connections found for camera {}, either addr or UID must be supplied",
|
||||
cam_config.name
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let friendly_name = cam_config.name.replace('_', " ").to_title_case();
|
||||
let device = DiscoveryDevice {
|
||||
name: friendly_name.clone(),
|
||||
connections,
|
||||
identifiers: vec![format!("neolink_{}", cam_config.name)],
|
||||
manufacturer: Some("Reolink".to_string()),
|
||||
model: Some("Neolink".to_string()),
|
||||
sw_version: Some(env!("CARGO_PKG_VERSION").to_string()),
|
||||
};
|
||||
|
||||
let availability = DiscoveryAvaliablity {
|
||||
topic: format!("neolink/{}/status", cam_config.name),
|
||||
payload_available: Some("connected".to_string()),
|
||||
payload_not_available: None,
|
||||
};
|
||||
|
||||
for feature in &discovery_config.features {
|
||||
match feature {
|
||||
Discoveries::Floodlight => {
|
||||
let config_data = DiscoveryLight {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} Floodlight", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_floodlight", cam_config.name),
|
||||
// Match native home assistant integration: https://github.com/home-assistant/core/blob/dev/homeassistant/components/reolink/light.py#L49
|
||||
icon: Some("mdi:spotlight-beam".to_string()),
|
||||
|
||||
// State
|
||||
state_topic: Some(format!("neolink/{}/status/floodlight", cam_config.name)),
|
||||
state_value_template: Some("{{ value_json.state }}".to_string()),
|
||||
|
||||
// Control
|
||||
command_topic: Some(format!("neolink/{}/control/floodlight", cam_config.name)),
|
||||
// Lowercase payloads to match neolink convention
|
||||
payload_on: "on".to_string(),
|
||||
payload_off: "off".to_string(),
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/light/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery light config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish floodlight auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Discoveries::Camera => {
|
||||
let config_data = DiscoveryCamera {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} Camera", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_camera", cam_config.name),
|
||||
icon: Some("mdi:camera-iris".to_string()),
|
||||
|
||||
// Camera specific
|
||||
topic: format!("neolink/{}/status/preview", cam_config.name),
|
||||
image_encoding: Encoding::Base64,
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/camera/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery camera config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish camera auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Discoveries::Led => {
|
||||
let config_data = DiscoverySwitch {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} LED", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_led", cam_config.name),
|
||||
icon: Some("mdi:led-on".to_string()),
|
||||
|
||||
// Switch specific
|
||||
command_topic: format!("neolink/{}/control/led", cam_config.name),
|
||||
payload_off: "off".to_string(),
|
||||
payload_on: "on".to_string(),
|
||||
state_topic: None,
|
||||
state_off: None,
|
||||
state_on: None,
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/switch/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery led config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish led auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Discoveries::Ir => {
|
||||
let config_data = DiscoverySelect {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} IR", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_ir", cam_config.name),
|
||||
icon: Some("mdi:lightbulb-night".to_string()),
|
||||
|
||||
// Switch specific
|
||||
command_topic: format!("neolink/{}/control/ir", cam_config.name),
|
||||
options: vec!["on".to_string(), "off".to_string(), "auto".to_string()],
|
||||
state_topic: None,
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/select/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery led config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish led auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Discoveries::Motion => {
|
||||
let config_data = DiscoveryBinarySensor {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} MD", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_md", cam_config.name),
|
||||
icon: Some("mdi:motion-sensor".to_string()),
|
||||
|
||||
// Switch specific
|
||||
state_topic: format!("neolink/{}/status/motion", cam_config.name),
|
||||
payload_off: "off".to_string(),
|
||||
payload_on: "on".to_string(),
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/binary_sensor/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery motion config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish motion auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Discoveries::Reboot => {
|
||||
let config_data = DiscoveryButton {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} Reboot", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_reboot", cam_config.name),
|
||||
icon: Some("mdi:restart".to_string()),
|
||||
|
||||
// Switch specific
|
||||
command_topic: format!("neolink/{}/control/reboot", cam_config.name),
|
||||
payload_press: None,
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/button/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery reboot config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish reboot auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Discoveries::Pt => {
|
||||
for dir in ["left", "right", "up", "down"] {
|
||||
let config_data = DiscoveryButton {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} Pan {}", friendly_name.as_str(), dir),
|
||||
unique_id: format!("neolink_{}_pan_{}", cam_config.name, dir),
|
||||
icon: Some(format!("mdi:pan-{}", dir)),
|
||||
|
||||
// Switch specific
|
||||
command_topic: format!("neolink/{}/control/ptz", cam_config.name),
|
||||
payload_press: Some(dir.to_string()),
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/button/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery pt config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish pt auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Discoveries::Battery => {
|
||||
let config_data = DiscoverySensor {
|
||||
// Common across all potential features
|
||||
device: device.clone(),
|
||||
availability: availability.clone(),
|
||||
|
||||
// Identifiers
|
||||
name: format!("{} Battery", friendly_name.as_str()),
|
||||
unique_id: format!("neolink_{}_battery", cam_config.name),
|
||||
icon: Some("mdi:battery".to_string()),
|
||||
|
||||
// Camera specific
|
||||
state_topic: format!("neolink/{}/status/battery_level", cam_config.name),
|
||||
state_class: "measurement".to_string(),
|
||||
unit_of_measurement: "%".to_string(),
|
||||
};
|
||||
|
||||
// Each feature needs to be individually registered
|
||||
mqtt_sender
|
||||
.send_message_with_root_topic(
|
||||
&format!(
|
||||
"{}/sensor/{}",
|
||||
discovery_config.topic, &config_data.unique_id
|
||||
),
|
||||
"config",
|
||||
&serde_json::to_string(&config_data).with_context(|| {
|
||||
"Cound not serialise discovery battery config into json"
|
||||
})?,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish battery auto-discover data on over MQTT for {}",
|
||||
cam_config.name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info!(
|
||||
"Enabled MQTT discovery for {} with friendly name {}",
|
||||
cam_config.name,
|
||||
friendly_name.as_str()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+28
-268
@@ -1,7 +1,6 @@
|
||||
use crate::config::CameraConfig;
|
||||
use crate::utils::{timeout, AddressOrUid};
|
||||
use crate::utils::AddressOrUid;
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use futures::stream::StreamExt;
|
||||
use log::*;
|
||||
use neolink_core::bc_protocol::{
|
||||
BcCamera, Direction as BcDirection, Error as BcError, LightState, MaxEncryption, MotionStatus,
|
||||
@@ -10,17 +9,17 @@ use std::sync::Arc;
|
||||
use tokio::{
|
||||
sync::mpsc::{channel, Receiver, Sender},
|
||||
task::JoinSet,
|
||||
time::{interval, sleep, Duration},
|
||||
time::sleep,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
use core::time::Duration;
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub(crate) enum Messages {
|
||||
Login,
|
||||
MotionStop,
|
||||
MotionStart,
|
||||
Reboot,
|
||||
FloodlightOn,
|
||||
FloodlightOff,
|
||||
StatusLedOn,
|
||||
StatusLedOff,
|
||||
IRLedOn,
|
||||
@@ -31,11 +30,6 @@ pub(crate) enum Messages {
|
||||
PIROff,
|
||||
PIRQuery,
|
||||
Ptz(Direction),
|
||||
Snap(Vec<u8>),
|
||||
BatteryLevel(u32),
|
||||
Preset(u8),
|
||||
PresetAssign(u8, String),
|
||||
PresetQuery,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
@@ -193,9 +187,10 @@ impl EventCamThread {
|
||||
"aes" => MaxEncryption::Aes,
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
timeout(camera.login_with_maxenc(max_encryption))
|
||||
camera
|
||||
.login_with_maxenc(max_encryption)
|
||||
.await
|
||||
.context("Failed to login to the camera")??;
|
||||
.context("Failed to login to the camera")?;
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
self.tx.send(Messages::Login).await?;
|
||||
@@ -208,25 +203,6 @@ impl EventCamThread {
|
||||
camera: arc_cam.clone(),
|
||||
};
|
||||
|
||||
let mut flight_thread = FloodlightThread {
|
||||
tx: self.tx.clone(),
|
||||
camera: arc_cam.clone(),
|
||||
};
|
||||
|
||||
let mut snap_thread = SnapThread {
|
||||
tx: self.tx.clone(),
|
||||
camera: arc_cam.clone(),
|
||||
};
|
||||
|
||||
let mut battery_thread = BatteryLevelThread {
|
||||
tx: self.tx.clone(),
|
||||
camera: arc_cam.clone(),
|
||||
};
|
||||
|
||||
let mut keepalive_thread = KeepaliveThread {
|
||||
camera: arc_cam.clone(),
|
||||
};
|
||||
|
||||
let mut message_handler = MessageHandler {
|
||||
rx: &mut self.rx,
|
||||
camera: arc_cam,
|
||||
@@ -236,7 +212,7 @@ impl EventCamThread {
|
||||
val = async {
|
||||
info!("{}: Listening to Camera Motion", camera_config.name);
|
||||
motion_thread.run().await
|
||||
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_motion => {
|
||||
} => {
|
||||
if let Err(e) = val {
|
||||
error!("Motion thread aborted: {:?}", e);
|
||||
Err(e)
|
||||
@@ -245,54 +221,6 @@ impl EventCamThread {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
val = async {
|
||||
debug!("{}: Starting Pings", camera_config.name);
|
||||
keepalive_thread.run().await
|
||||
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_pings => {
|
||||
if let Err(e) = val {
|
||||
debug!("Ping thread aborted: {:?}", e);
|
||||
Err(e)
|
||||
} else {
|
||||
debug!("Normal finish on Ping thread");
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
val = async {
|
||||
info!("{}: Listening to FloodLight Status", camera_config.name);
|
||||
flight_thread.run().await
|
||||
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_light => {
|
||||
if let Err(e) = val {
|
||||
error!("FloodLight thread aborted: {:?}", e);
|
||||
Err(e)
|
||||
} else {
|
||||
debug!("Normal finish on FloodLight thread");
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
val = async {
|
||||
info!("{}: Updating Preview", camera_config.name);
|
||||
snap_thread.run().await
|
||||
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_preview => {
|
||||
if let Err(e) = val {
|
||||
error!("Snap thread aborted: {:?}", e);
|
||||
Err(e)
|
||||
} else {
|
||||
debug!("Normal finish on Snap thread");
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
val = async {
|
||||
info!("{}: Updating Battery Level", camera_config.name);
|
||||
battery_thread.run().await
|
||||
}, if camera_config.mqtt.as_ref().expect("Should have an mqtt config at this point").enable_battery => {
|
||||
if let Err(e) = val {
|
||||
error!("Battery thread aborted: {:?}", e);
|
||||
Err(e)
|
||||
} else {
|
||||
debug!("Normal finish on Battery thread");
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
val = async {
|
||||
info!("{}: Setting up camera actions", camera_config.name);
|
||||
message_handler.listen().await
|
||||
@@ -344,114 +272,6 @@ impl MotionThread {
|
||||
}
|
||||
}
|
||||
|
||||
struct FloodlightThread {
|
||||
tx: Sender<Messages>,
|
||||
camera: Arc<BcCamera>,
|
||||
}
|
||||
|
||||
impl FloodlightThread {
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
let mut reciever =
|
||||
tokio_stream::wrappers::ReceiverStream::new(self.camera.listen_on_flightlight().await?);
|
||||
while let Some(flights) = reciever.next().await {
|
||||
for flight in flights.floodlight_status_list.iter() {
|
||||
if flight.status == 0 {
|
||||
self.tx.send(Messages::FloodlightOff).await?;
|
||||
} else {
|
||||
self.tx.send(Messages::FloodlightOn).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct SnapThread {
|
||||
tx: Sender<Messages>,
|
||||
camera: Arc<BcCamera>,
|
||||
}
|
||||
|
||||
impl SnapThread {
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
let mut tries = 0;
|
||||
let base_duration = Duration::from_millis(500);
|
||||
loop {
|
||||
tokio::time::sleep(base_duration.saturating_mul(tries)).await;
|
||||
let snapshot = match self.camera.get_snapshot().await {
|
||||
Ok(info) => {
|
||||
tries = 1;
|
||||
info
|
||||
}
|
||||
Err(neolink_core::Error::UnintelligibleReply { reply, why }) => {
|
||||
log::debug!("Reply: {:?}, why: {:?}", reply, why);
|
||||
// Try again later
|
||||
tries += 1;
|
||||
continue;
|
||||
}
|
||||
Err(neolink_core::Error::CameraServiceUnavaliable) => {
|
||||
log::debug!("Snap not supported");
|
||||
futures::future::pending().await
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
self.tx.send(Messages::Snap(snapshot)).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BatteryLevelThread {
|
||||
tx: Sender<Messages>,
|
||||
camera: Arc<BcCamera>,
|
||||
}
|
||||
|
||||
impl BatteryLevelThread {
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
let mut tries = 0;
|
||||
let base_duration = Duration::from_secs(15);
|
||||
loop {
|
||||
tokio::time::sleep(base_duration.saturating_mul(tries)).await;
|
||||
let battery = match self.camera.battery_info().await {
|
||||
Ok(info) => {
|
||||
tries = 1;
|
||||
info
|
||||
}
|
||||
Err(neolink_core::Error::UnintelligibleReply { .. }) => {
|
||||
// Try again later
|
||||
tries += 1;
|
||||
continue;
|
||||
}
|
||||
Err(neolink_core::Error::CameraServiceUnavaliable) => {
|
||||
log::debug!("Battery not supported");
|
||||
futures::future::pending().await
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
self.tx
|
||||
.send(Messages::BatteryLevel(battery.battery_percent))
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct KeepaliveThread {
|
||||
camera: Arc<BcCamera>,
|
||||
}
|
||||
|
||||
impl KeepaliveThread {
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
let mut interval =
|
||||
tokio_stream::wrappers::IntervalStream::new(interval(Duration::from_secs(5)));
|
||||
while let Some(_update) = interval.next().await {
|
||||
if self.camera.ping().await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
futures::pending!(); // Never actually finish, has to be aborted
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct MessageHandler<'a> {
|
||||
rx: &'a mut Receiver<ToCamera>,
|
||||
camera: Arc<BcCamera>,
|
||||
@@ -477,30 +297,6 @@ impl<'a> MessageHandler<'a> {
|
||||
"OK".to_string()
|
||||
}
|
||||
}
|
||||
Messages::FloodlightOn => {
|
||||
let res = self.camera.set_floodlight_manual(true, 180).await;
|
||||
if res.is_err() {
|
||||
error = Some(format!(
|
||||
"Failed to turn on the floodlight light: {:?}",
|
||||
res.err()
|
||||
));
|
||||
"FAIL".to_string()
|
||||
} else {
|
||||
"OK".to_string()
|
||||
}
|
||||
}
|
||||
Messages::FloodlightOff => {
|
||||
let res = self.camera.set_floodlight_manual(false, 180).await;
|
||||
if res.is_err() {
|
||||
error = Some(format!(
|
||||
"Failed to turn off the floodlight light: {:?}",
|
||||
res.err()
|
||||
));
|
||||
"FAIL".to_string()
|
||||
} else {
|
||||
"OK".to_string()
|
||||
}
|
||||
}
|
||||
Messages::StatusLedOn => {
|
||||
if let Err(e) = self.camera.led_light_set(true).await {
|
||||
error =
|
||||
@@ -615,23 +411,27 @@ impl<'a> MessageHandler<'a> {
|
||||
}
|
||||
}
|
||||
Messages::Ptz(direction) => {
|
||||
let (bc_direction, speed, seconds) = match direction {
|
||||
Direction::Up(speed, seconds) => (BcDirection::Up, speed, seconds),
|
||||
Direction::Down(speed, seconds) => {
|
||||
(BcDirection::Down, speed, seconds)
|
||||
let (bc_direction, amount, seconds) = match direction {
|
||||
Direction::Up(amount, seconds) => {
|
||||
(BcDirection::Up, amount, seconds)
|
||||
}
|
||||
Direction::Left(speed, seconds) => {
|
||||
(BcDirection::Left, speed, seconds)
|
||||
Direction::Down(amount, seconds) => {
|
||||
(BcDirection::Down, amount, seconds)
|
||||
}
|
||||
Direction::Right(speed, seconds) => {
|
||||
(BcDirection::Right, speed, seconds)
|
||||
Direction::Left(amount, seconds) => {
|
||||
(BcDirection::Left, amount, seconds)
|
||||
}
|
||||
Direction::In(speed, seconds) => (BcDirection::In, speed, seconds),
|
||||
Direction::Out(speed, seconds) => {
|
||||
(BcDirection::Out, speed, seconds)
|
||||
Direction::Right(amount, seconds) => {
|
||||
(BcDirection::Right, amount, seconds)
|
||||
}
|
||||
Direction::In(amount, seconds) => {
|
||||
(BcDirection::In, amount, seconds)
|
||||
}
|
||||
Direction::Out(amount, seconds) => {
|
||||
(BcDirection::Out, amount, seconds)
|
||||
}
|
||||
};
|
||||
if let Err(e) = self.camera.send_ptz(bc_direction, speed).await {
|
||||
if let Err(e) = self.camera.send_ptz(bc_direction, amount).await {
|
||||
error = Some(format!("Failed to send PTZ: {:?}", e));
|
||||
"FAIL".to_string()
|
||||
} else {
|
||||
@@ -639,7 +439,9 @@ impl<'a> MessageHandler<'a> {
|
||||
sleep(Duration::from_secs_f32(seconds)).await;
|
||||
|
||||
// note that amount is not used in the stop command
|
||||
if let Err(e) = self.camera.send_ptz(BcDirection::Stop, 0.0).await {
|
||||
if let Err(e) =
|
||||
self.camera.send_ptz(BcDirection::Stop, amount).await
|
||||
{
|
||||
error = Some(format!("Failed to send PTZ: {:?}", e));
|
||||
"FAIL".to_string()
|
||||
} else {
|
||||
@@ -647,48 +449,6 @@ impl<'a> MessageHandler<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Messages::Preset(id) => {
|
||||
if let Err(e) = self.camera.moveto_ptz_preset(id).await {
|
||||
error = Some(format!("Failed to send PTZ preset: {:?}", e));
|
||||
"FAIL".to_string()
|
||||
} else {
|
||||
"OK".to_string()
|
||||
}
|
||||
}
|
||||
Messages::PresetAssign(id, name) => {
|
||||
if let Err(e) = self.camera.set_ptz_preset(id, name).await {
|
||||
error = Some(format!("Failed to send PTZ preset: {:?}", e));
|
||||
"FAIL".to_string()
|
||||
} else {
|
||||
"OK".to_string()
|
||||
}
|
||||
}
|
||||
Messages::PresetQuery => match self.camera.get_ptz_preset().await {
|
||||
Err(e) => {
|
||||
error!("Failed to get PTZ preset status: {:?}", e);
|
||||
"FAIL".to_string()
|
||||
}
|
||||
Ok(ptz_info) => {
|
||||
let bytes_res = yaserde::ser::serialize_with_writer(
|
||||
&ptz_info,
|
||||
vec![],
|
||||
&Default::default(),
|
||||
);
|
||||
match bytes_res {
|
||||
Ok(bytes) => match String::from_utf8(bytes) {
|
||||
Ok(str) => str,
|
||||
Err(_) => {
|
||||
error!("Failed to encode PTZ preset status");
|
||||
"FAIL".to_string()
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
error!("Failed to serialise PTZ preset status");
|
||||
"FAIL".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => "UNKNOWN COMMAND".to_string(),
|
||||
};
|
||||
if let Some(replier) = replier {
|
||||
|
||||
+9
-134
@@ -1,4 +1,3 @@
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
|
||||
///
|
||||
/// # Neolink MQTT
|
||||
///
|
||||
@@ -10,14 +9,11 @@ use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
|
||||
///
|
||||
/// Control messages:
|
||||
///
|
||||
/// - `/control/floodlight [on|off]` Turns floodlight (if equipped) on/off
|
||||
/// - `/control/led [on|off]` Turns status LED on/off
|
||||
/// - `/control/pir [on|off]` Turns PIR on/off
|
||||
/// - `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light detection
|
||||
/// - `/control/reboot` Reboot the camera
|
||||
/// - `/control/ptz` [up|down|left|right|in|out] (amount) Control the PTZ movements, amount defaults to 32.0
|
||||
/// - `/control/ptz/preset` [id] Move the camera to a known preset
|
||||
/// - `/control/ptz/assign` [id] [name] Assign the current ptz position to an ID and name
|
||||
///
|
||||
/// Status Messages:
|
||||
///
|
||||
@@ -25,13 +21,11 @@ use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
|
||||
/// `/status disconnected` Sent when the camera goes offline
|
||||
/// `/status/battery` Sent in reply to a `/query/battery`
|
||||
/// `/status/pir` Sent in reply to a `/query/pir`
|
||||
/// `/status/ptz/preset` Sent in reply to a `/query/ptz/preset`
|
||||
///
|
||||
/// Query Messages:
|
||||
///
|
||||
/// `/query/battery` Request that the camera reports its battery level
|
||||
/// `/query/pir` Request that the camera reports its pir status
|
||||
/// `/query/ptz/preset` Request that the camera reports the PTZ presets
|
||||
///
|
||||
///
|
||||
/// # Usage
|
||||
@@ -62,21 +56,18 @@ use std::sync::Arc;
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
mod cmdline;
|
||||
mod discovery;
|
||||
mod event_cam;
|
||||
mod mqttc;
|
||||
|
||||
use crate::config::{CameraConfig, Config, MqttConfig};
|
||||
use anyhow::{anyhow, Context, Error, Result};
|
||||
pub(crate) use cmdline::Opt;
|
||||
pub(crate) use discovery::Discoveries;
|
||||
use event_cam::EventCam;
|
||||
pub(crate) use event_cam::{Direction, Messages};
|
||||
use log::*;
|
||||
use mqttc::{Mqtt, MqttReplyRef};
|
||||
|
||||
use self::{
|
||||
discovery::enable_discovery,
|
||||
event_cam::EventCamSender,
|
||||
mqttc::{MqttReply, MqttSender},
|
||||
};
|
||||
@@ -140,8 +131,7 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
tokio::select! {
|
||||
v = async {
|
||||
// Normal poll operations
|
||||
loop {
|
||||
let msg = mqtt.poll().await?;
|
||||
while let Ok(msg) = mqtt.poll().await {
|
||||
tokio::task::yield_now().await;
|
||||
// Put the reply on it's own async thread so we can safely sleep
|
||||
// and wait for it to reply in it's own time
|
||||
@@ -158,6 +148,7 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
} => v,
|
||||
// Wait on any error from any of the error channels and if we get it we abort
|
||||
v = error_recv.recv() => v.map(Err).unwrap_or_else(|| Err(anyhow!("Listen on camera error channel closed"))),
|
||||
@@ -175,32 +166,6 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
.with_context(|| {
|
||||
format!("Failed to post connect over MQTT for {}", camera_name)
|
||||
})?;
|
||||
|
||||
if let Some(discovery_config) = &mqtt_config.discovery {
|
||||
enable_discovery(discovery_config, &mqtt_sender_cam, &cam_config).await?;
|
||||
}
|
||||
}
|
||||
Messages::FloodlightOn => {
|
||||
mqtt_sender_cam
|
||||
.send_message("status/floodlight", "on", true)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish floodlight on over MQTT for {}",
|
||||
camera_name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Messages::FloodlightOff => {
|
||||
mqtt_sender_cam
|
||||
.send_message("status/floodlight", "off", true)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish floodlight off over MQTT for {}",
|
||||
camera_name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Messages::MotionStop => {
|
||||
mqtt_sender_cam
|
||||
@@ -218,25 +183,6 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
|
||||
format!("Failed to publish motion start for {}", camera_name)
|
||||
})?;
|
||||
}
|
||||
Messages::Snap(data) => {
|
||||
mqtt_sender_cam
|
||||
.send_message("status/preview", BASE64.encode(data).as_str(), true)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("Failed to publish preview over MQTT for {}", camera_name)
|
||||
})?;
|
||||
}
|
||||
Messages::BatteryLevel(data) => {
|
||||
mqtt_sender_cam
|
||||
.send_message("status/battery_level", format!("{}", data).as_str(), true)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to publish battery level over MQTT for {}",
|
||||
camera_name
|
||||
)
|
||||
})?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -268,28 +214,6 @@ async fn handle_mqtt_message(
|
||||
} => {
|
||||
// Do nothing for the success/fail replies
|
||||
}
|
||||
MqttReplyRef {
|
||||
topic: "control/floodlight",
|
||||
message: "on",
|
||||
} => {
|
||||
reply = Some(
|
||||
event_cam_sender
|
||||
.send_message_with_reply(Messages::FloodlightOn)
|
||||
.await
|
||||
.with_context(|| "Failed to set camera status light on")?,
|
||||
);
|
||||
}
|
||||
MqttReplyRef {
|
||||
topic: "control/floodlight",
|
||||
message: "off",
|
||||
} => {
|
||||
reply = Some(
|
||||
event_cam_sender
|
||||
.send_message_with_reply(Messages::FloodlightOff)
|
||||
.await
|
||||
.with_context(|| "Failed to set camera status light off")?,
|
||||
);
|
||||
}
|
||||
MqttReplyRef {
|
||||
topic: "control/led",
|
||||
message: "on",
|
||||
@@ -364,10 +288,9 @@ async fn handle_mqtt_message(
|
||||
let mut words = lowercase_message.split_whitespace();
|
||||
if let Some(direction_txt) = words.next() {
|
||||
// Target amount to move
|
||||
let speed = 32f32;
|
||||
let amount = words.next().unwrap_or("32.0");
|
||||
if let Ok(amount) = amount.parse::<f32>() {
|
||||
let seconds = amount / speed;
|
||||
let seconds = amount / 32f32;
|
||||
// range checking on seconds so that you can't sleep for 3.4E+38 seconds
|
||||
match seconds {
|
||||
x if (0.0..10.0).contains(&x) => seconds,
|
||||
@@ -378,12 +301,12 @@ async fn handle_mqtt_message(
|
||||
};
|
||||
|
||||
let direction = match direction_txt {
|
||||
"up" => Direction::Up(speed, seconds),
|
||||
"down" => Direction::Down(speed, seconds),
|
||||
"left" => Direction::Left(speed, seconds),
|
||||
"right" => Direction::Right(speed, seconds),
|
||||
"in" => Direction::In(speed, seconds),
|
||||
"out" => Direction::Out(speed, seconds),
|
||||
"up" => Direction::Up(amount, seconds),
|
||||
"down" => Direction::Down(amount, seconds),
|
||||
"left" => Direction::Left(amount, seconds),
|
||||
"right" => Direction::Right(amount, seconds),
|
||||
"in" => Direction::In(amount, seconds),
|
||||
"out" => Direction::Out(amount, seconds),
|
||||
_ => {
|
||||
error!("Unrecognized PTZ direction \"{}\"", direction_txt);
|
||||
return Ok(());
|
||||
@@ -402,42 +325,6 @@ async fn handle_mqtt_message(
|
||||
error!("No PTZ Direction given. Please add up/down/left/right/in/out");
|
||||
}
|
||||
}
|
||||
MqttReplyRef {
|
||||
topic: "control/ptz/preset",
|
||||
message,
|
||||
} => {
|
||||
if let Ok(id) = message.parse::<u8>() {
|
||||
reply = Some(
|
||||
event_cam_sender
|
||||
.send_message_with_reply(Messages::Preset(id))
|
||||
.await
|
||||
.with_context(|| "Failed to send PTZ preset")?,
|
||||
);
|
||||
} else {
|
||||
error!("PTZ preset was not a valid number");
|
||||
}
|
||||
}
|
||||
MqttReplyRef {
|
||||
topic: "control/ptz/assign",
|
||||
message,
|
||||
} => {
|
||||
let mut words = message.split_whitespace();
|
||||
let id = words.next();
|
||||
let name = words.next();
|
||||
|
||||
if let (Some(Ok(id)), Some(name)) = (id.map(|id| id.parse::<u8>()), name) {
|
||||
reply = Some(
|
||||
event_cam_sender
|
||||
.send_message_with_reply(Messages::PresetAssign(id, name.to_owned()))
|
||||
.await
|
||||
.with_context(|| "Failed to send PTZ preset assign")?,
|
||||
);
|
||||
} else if let (Some(Err(_)), _) = (id.map(|id| id.parse::<u8>()), name) {
|
||||
error!("PTZ preset was not a valid number");
|
||||
} else if let (_, None) = (id.map(|id| id.parse::<u8>()), name) {
|
||||
error!("PTZ preset was not given a name");
|
||||
}
|
||||
}
|
||||
MqttReplyRef {
|
||||
topic: "control/pir",
|
||||
message: "on",
|
||||
@@ -483,18 +370,6 @@ async fn handle_mqtt_message(
|
||||
);
|
||||
reply_topic = Some("status/pir");
|
||||
}
|
||||
MqttReplyRef {
|
||||
topic: "query/ptz/preset",
|
||||
..
|
||||
} => {
|
||||
reply = Some(
|
||||
event_cam_sender
|
||||
.send_message_with_reply(Messages::PresetQuery)
|
||||
.await
|
||||
.with_context(|| "Failed to get prz preset status")?,
|
||||
);
|
||||
reply_topic = Some("status/ptz/preset");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(reply) = reply {
|
||||
|
||||
+13
-31
@@ -50,31 +50,19 @@ pub(crate) struct MqttSender {
|
||||
}
|
||||
|
||||
impl MqttSender {
|
||||
pub async fn send_message_with_root_topic(
|
||||
&self,
|
||||
root_topic: &str,
|
||||
sub_topic: &str,
|
||||
message: &str,
|
||||
retain: bool,
|
||||
) -> Result<(), ClientError> {
|
||||
self.client
|
||||
.publish(
|
||||
format!("{}/{}/{}", root_topic, self.name, sub_topic),
|
||||
QoS::AtLeastOnce,
|
||||
retain,
|
||||
message,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_message(
|
||||
&self,
|
||||
sub_topic: &str,
|
||||
message: &str,
|
||||
retain: bool,
|
||||
) -> Result<(), ClientError> {
|
||||
self.send_message_with_root_topic("neolink", sub_topic, message, retain)
|
||||
self.client
|
||||
.publish(
|
||||
format!("neolink/{}/{}", self.name, sub_topic),
|
||||
QoS::AtLeastOnce,
|
||||
retain,
|
||||
message,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -168,8 +156,6 @@ impl Mqtt {
|
||||
&config.broker_addr,
|
||||
config.port,
|
||||
);
|
||||
let max_size = 100 * (1024 * 1024);
|
||||
mqttoptions.set_max_packet_size(max_size, max_size);
|
||||
|
||||
// Use TLS if ca path is set
|
||||
if let Some(ca_path) = &config.ca {
|
||||
@@ -278,16 +264,12 @@ impl Mqtt {
|
||||
impl Drop for Mqtt {
|
||||
fn drop(&mut self) {
|
||||
if let Some(drop_message) = self.drop_message.as_ref() {
|
||||
let res = self.get_sender().try_send_message(
|
||||
&drop_message.topic,
|
||||
&drop_message.message,
|
||||
true,
|
||||
);
|
||||
if res.is_err() {
|
||||
error!(
|
||||
"Failed to send offline message to mqtt: {:?}. Is the MQTT topic name valid?",
|
||||
res.err().unwrap()
|
||||
);
|
||||
if self
|
||||
.get_sender()
|
||||
.try_send_message(&drop_message.topic, &drop_message.message, true)
|
||||
.is_err()
|
||||
{
|
||||
error!("Failed to send offline message to mqtt");
|
||||
}
|
||||
}
|
||||
self.set.abort_all();
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
use clap::Parser;
|
||||
|
||||
#[derive(clap::ValueEnum, Clone, Debug)]
|
||||
pub enum CmdDirection {
|
||||
Left,
|
||||
Right,
|
||||
Up,
|
||||
Down,
|
||||
In,
|
||||
Out,
|
||||
Stop,
|
||||
}
|
||||
|
||||
/// The ptz command will control the positioning of the camera
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct Opt {
|
||||
/// The name of the camera to change the lights of. Must be a name in the config
|
||||
pub camera: String,
|
||||
|
||||
#[command(subcommand)]
|
||||
pub cmd: PtzCommand,
|
||||
}
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
pub enum PtzCommand {
|
||||
/// Move to a stored preset
|
||||
Preset { preset_id: Option<u8> },
|
||||
/// Assign the current position to a preset with a given name
|
||||
Assign { preset_id: u8, name: String },
|
||||
/// Performs a movement in the given direction
|
||||
Control {
|
||||
/// The amount to move
|
||||
amount: u32,
|
||||
/// The direction command
|
||||
#[clap(value_enum)]
|
||||
command: CmdDirection,
|
||||
/// The speed to move at
|
||||
speed: Option<u32>,
|
||||
},
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
///
|
||||
/// # Neolink PTZ Control
|
||||
///
|
||||
/// This module handles the controls of the PTZ commands
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
/// ```bash
|
||||
/// # Rotate left by 32
|
||||
/// neolink ptz --config=config.toml CameraName control 32 left
|
||||
/// # Rotate left by 32 at speed 10 (speed not supported on most camera)
|
||||
/// neolink ptz --config=config.toml CameraName control 32 left 10
|
||||
/// # Print the list of preset positions
|
||||
/// neolink ptz --config=config.toml CameraName preset
|
||||
/// # Move the camera to preset ID 0
|
||||
/// neolink ptz --config=config.toml CameraName preset 0
|
||||
/// # Save the current position as preset ID 0 with name PresetName
|
||||
/// neolink ptz --config=config.toml CameraName assign 0 PresetName
|
||||
/// ```
|
||||
///
|
||||
use anyhow::{Context, Result};
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
mod cmdline;
|
||||
|
||||
use super::config::Config;
|
||||
use crate::ptz::cmdline::CmdDirection;
|
||||
use crate::ptz::cmdline::PtzCommand;
|
||||
use crate::utils::find_and_connect;
|
||||
pub(crate) use cmdline::Opt;
|
||||
use neolink_core::bc_protocol::Direction;
|
||||
|
||||
/// Entry point for the ptz 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?;
|
||||
|
||||
match opt.cmd {
|
||||
PtzCommand::Preset { preset_id } => {
|
||||
if let Some(preset_id) = preset_id {
|
||||
camera
|
||||
.moveto_ptz_preset(preset_id)
|
||||
.await
|
||||
.context("Unable to set PTZ preset")
|
||||
.expect("TODO: panic message");
|
||||
} else {
|
||||
let preset_list = camera
|
||||
.get_ptz_preset()
|
||||
.await
|
||||
.context("Unable to get PTZ presets")?;
|
||||
println!("Available presets:\nID Name");
|
||||
for preset in preset_list.preset_list.preset {
|
||||
println!("{:<2} {:?}", preset.id, preset.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
PtzCommand::Assign { preset_id, name } => {
|
||||
camera
|
||||
.set_ptz_preset(preset_id, name)
|
||||
.await
|
||||
.context("Unable to set PTZ preset")
|
||||
.expect("TODO: panic message");
|
||||
}
|
||||
PtzCommand::Control {
|
||||
amount,
|
||||
command,
|
||||
speed,
|
||||
} => {
|
||||
let direction = match command {
|
||||
CmdDirection::Left => Direction::Left,
|
||||
CmdDirection::Right => Direction::Right,
|
||||
CmdDirection::Up => Direction::Up,
|
||||
CmdDirection::Down => Direction::Down,
|
||||
CmdDirection::In => Direction::In,
|
||||
CmdDirection::Out => Direction::Out,
|
||||
CmdDirection::Stop => Direction::Stop,
|
||||
};
|
||||
let speed = speed.unwrap_or(32) as f32;
|
||||
let seconds = amount as f32 / speed;
|
||||
let duration = Duration::from_secs_f32(seconds);
|
||||
camera
|
||||
.send_ptz(direction, speed)
|
||||
.await
|
||||
.context("Unable to execute PTZ move command")?;
|
||||
sleep(duration).await;
|
||||
camera
|
||||
.send_ptz(Direction::Stop, 0_f32)
|
||||
.await
|
||||
.context("Unable to execute PTZ move command")?;
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
+46
-54
@@ -41,17 +41,17 @@ glib::wrapper! {
|
||||
|
||||
impl Default for NeoMediaFactory {
|
||||
fn default() -> Self {
|
||||
Self::new(100, true, true)
|
||||
Self::new(100, true)
|
||||
}
|
||||
}
|
||||
|
||||
impl NeoMediaFactory {
|
||||
pub(crate) fn new(buffer_size: usize, use_smoothing: bool, use_splash: bool) -> Self {
|
||||
pub(crate) fn new(buffer_size: usize, use_smoothing: bool) -> Self {
|
||||
let factory = Object::new::<NeoMediaFactory>();
|
||||
factory.set_shared(false);
|
||||
factory.imp().shared.set_buffer_size(buffer_size);
|
||||
factory.imp().shared.set_use_smoothing(use_smoothing);
|
||||
factory.imp().shared.set_use_splash(use_splash);
|
||||
// factory.set_do_retransmission(false); // Can't use as the method is missing on the 32bit docker gst dll
|
||||
factory.set_launch("videotestsrc pattern=\"snow\" ! video/x-raw,width=896,height=512,framerate=25/1 ! textoverlay name=\"inittextoverlay\" text=\"Stream not Ready\" valignment=top halignment=left font-desc=\"Sans, 32\" ! jpegenc ! rtpjpegpay name=pay0");
|
||||
factory.set_suspend_mode(RTSPSuspendMode::None);
|
||||
factory.set_transport_mode(RTSPTransportMode::PLAY);
|
||||
@@ -184,7 +184,7 @@ impl ObjectImpl for NeoMediaFactoryImpl {}
|
||||
impl RTSPMediaFactoryImpl for NeoMediaFactoryImpl {
|
||||
fn create_element(&self, url: &RTSPUrl) -> Option<Element> {
|
||||
self.parent_create_element(url)
|
||||
.and_then(|orig| self.build_pipeline(orig).expect("Could not build pipeline"))
|
||||
.map(|orig| self.build_pipeline(orig).expect("Could not build pipeline"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,18 +239,18 @@ fn make_queue(name: &str) -> AnyResult<Element> {
|
||||
Ok(queue)
|
||||
}
|
||||
|
||||
// fn make_queue2(name: &str) -> AnyResult<Element> {
|
||||
// let queue = make_element("queue2", name)?;
|
||||
// queue.set_property("use-buffering", true);
|
||||
// queue.set_property("max-size-bytes", 0u32);
|
||||
// queue.set_property("max-size-buffers", 0u32);
|
||||
// queue.set_property(
|
||||
// "max-size-time",
|
||||
// std::convert::TryInto::<u64>::try_into(tokio::time::Duration::from_secs(5).as_nanos())
|
||||
// .unwrap_or(0),
|
||||
// );
|
||||
// Ok(queue)
|
||||
// }
|
||||
fn make_queue2(name: &str) -> AnyResult<Element> {
|
||||
let queue = make_element("queue2", name)?;
|
||||
queue.set_property("use-buffering", true);
|
||||
queue.set_property("max-size-bytes", 0u32);
|
||||
queue.set_property("max-size-buffers", 0u32);
|
||||
queue.set_property(
|
||||
"max-size-time",
|
||||
std::convert::TryInto::<u64>::try_into(tokio::time::Duration::from_secs(5).as_nanos())
|
||||
.unwrap_or(0),
|
||||
);
|
||||
Ok(queue)
|
||||
}
|
||||
|
||||
impl NeoMediaFactoryImpl {
|
||||
pub(crate) fn buffer_ready(&self) -> bool {
|
||||
@@ -260,17 +260,15 @@ impl NeoMediaFactoryImpl {
|
||||
self.shared.number_of_clients.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn build_pipeline(&self, media: Element) -> AnyResult<Option<Element>> {
|
||||
fn build_pipeline(&self, media: Element) -> AnyResult<Element> {
|
||||
// debug!("Building PIPELINE");
|
||||
let bin = media
|
||||
.dynamic_cast::<Bin>()
|
||||
.map_err(|_| anyhow!("Media source's element should be a bin"))?;
|
||||
// Clear the autogenerated ones
|
||||
log::debug!("Clearing old elements");
|
||||
for element in bin.iterate_elements().into_iter().flatten() {
|
||||
bin.remove(&element)?;
|
||||
}
|
||||
log::debug!("Cleared");
|
||||
|
||||
let mut client_data = NeoMediaSender::new(
|
||||
self.shared.get_buffer_size(),
|
||||
@@ -283,15 +281,12 @@ impl NeoMediaFactoryImpl {
|
||||
self.shared.buffer_ready.load(Ordering::Relaxed),
|
||||
) {
|
||||
(VidFormats::Unknown, true) | (_, false) => {
|
||||
if !self.shared.get_use_splash() {
|
||||
return Ok(None);
|
||||
}
|
||||
debug!("Building Unknown Pipeline");
|
||||
let source = make_element("videotestsrc", "testvidsrc")?;
|
||||
source.set_property_from_str("pattern", "snow");
|
||||
source.set_property("num-buffers", 500i32); // Send buffers then EOS
|
||||
let queue = make_queue("queue0")?;
|
||||
// let queue2 = make_queue2("queue2")?;
|
||||
let queue2 = make_queue2("queue2")?;
|
||||
let overlay = make_element("textoverlay", "overlay")?;
|
||||
overlay.set_property("text", "Stream not Ready");
|
||||
overlay.set_property_from_str("valignment", "top");
|
||||
@@ -300,7 +295,7 @@ impl NeoMediaFactoryImpl {
|
||||
let encoder = make_element("jpegenc", "encoder")?;
|
||||
let payload = make_element("rtpjpegpay", "pay0")?;
|
||||
|
||||
bin.add_many(&[&source, &queue, &overlay, &encoder, &payload])?;
|
||||
bin.add_many(&[&source, &queue, &queue2, &overlay, &encoder, &payload])?;
|
||||
source.link_filtered(
|
||||
&queue,
|
||||
&Caps::builder("video/x-raw")
|
||||
@@ -311,7 +306,7 @@ impl NeoMediaFactoryImpl {
|
||||
.build(),
|
||||
)?;
|
||||
// source.link(&queue)?;
|
||||
Element::link_many(&[&queue, &overlay, &encoder, &payload])?;
|
||||
Element::link_many(&[&queue, &queue2, &overlay, &encoder, &payload])?;
|
||||
}
|
||||
(VidFormats::H265, true) => {
|
||||
debug!("Building H265 Pipeline");
|
||||
@@ -360,12 +355,12 @@ impl NeoMediaFactoryImpl {
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
let queue = make_queue("source_queue")?;
|
||||
// let queue2 = make_queue2("queue2")?;
|
||||
let queue2 = make_queue2("queue2")?;
|
||||
let parser = make_element("h265parse", "parser")?;
|
||||
// parser.set_property("config-interval", 5i32);
|
||||
let payload = make_element("rtph265pay", "pay0")?;
|
||||
bin.add_many(&[&source, &queue, &parser, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &parser, &payload])?;
|
||||
bin.add_many(&[&source, &queue, &queue2, &parser, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &queue2, &parser, &payload])?;
|
||||
|
||||
let source = source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
@@ -422,7 +417,7 @@ impl NeoMediaFactoryImpl {
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
let queue = make_queue("source_queue")?;
|
||||
// let queue2 = make_queue2("queue2")?;
|
||||
let queue2 = make_queue2("queue2")?;
|
||||
let parser = make_element("h264parse", "parser")?;
|
||||
// parser.set_property("update-timecode", true);
|
||||
let payload = make_element("rtph264pay", "pay0")?;
|
||||
@@ -434,13 +429,13 @@ impl NeoMediaFactoryImpl {
|
||||
|
||||
// payload.set_property("config-interval", 5i32);
|
||||
bin.add_many(&[
|
||||
&source, &queue, &parser,
|
||||
&source, &queue, &queue2, &parser,
|
||||
&payload,
|
||||
// &storage,
|
||||
// &jitter,
|
||||
])?;
|
||||
Element::link_many(&[
|
||||
&source, &queue, &parser,
|
||||
&source, &queue, &queue2, &parser,
|
||||
&payload,
|
||||
// &storage,
|
||||
// &jitter,
|
||||
@@ -493,26 +488,25 @@ impl NeoMediaFactoryImpl {
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
|
||||
let queue = make_queue("audqueue")?;
|
||||
// let queue2 = make_queue2("audqueue2")?;
|
||||
let queue2 = make_queue2("audqueue2")?;
|
||||
let parser = make_element("aacparse", "audparser")?;
|
||||
let decoder = match make_element("faad", "auddecoder_faad") {
|
||||
Ok(ele) => Ok(ele),
|
||||
Err(_) => make_element("avdec_aac", "auddecoder_avdec_aac"),
|
||||
}?;
|
||||
let decoder = make_element("decodebin", "auddecoder")?;
|
||||
let encoder = make_element("audioconvert", "audencoder")?;
|
||||
let payload = make_element("rtpL16pay", "pay1")?;
|
||||
|
||||
bin.add_many(&[&source, &queue, &parser, &decoder, &encoder, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &parser, &decoder, &encoder, &payload])?;
|
||||
// Element::link_many(&[])?;
|
||||
// decoder.connect_pad_added(move |_element, pad| {
|
||||
// debug!("Linking encoder to decoder: {:?}", pad.caps());
|
||||
// let sink_pad = encoder
|
||||
// .static_pad("sink")
|
||||
// .expect("Encoder is missing its pad");
|
||||
// pad.link(&sink_pad)
|
||||
// .expect("Failed to link AAC decoder to encoder");
|
||||
// });
|
||||
bin.add_many(&[
|
||||
&source, &queue, &queue2, &parser, &decoder, &encoder, &payload,
|
||||
])?;
|
||||
Element::link_many(&[&source, &queue, &queue2, &parser, &decoder])?;
|
||||
Element::link_many(&[&encoder, &payload])?;
|
||||
decoder.connect_pad_added(move |_element, pad| {
|
||||
debug!("Linking encoder to decoder: {:?}", pad.caps());
|
||||
let sink_pad = encoder
|
||||
.static_pad("sink")
|
||||
.expect("Encoder is missing its pad");
|
||||
pad.link(&sink_pad)
|
||||
.expect("Failed to link AAC decoder to encoder");
|
||||
});
|
||||
|
||||
let source = source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
@@ -566,13 +560,13 @@ impl NeoMediaFactoryImpl {
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
|
||||
let queue = make_queue("audqueue")?;
|
||||
// let queue2 = make_queue2("audqueue2")?;
|
||||
let queue2 = make_queue2("audqueue2")?;
|
||||
let decoder = make_element("decodebin", "auddecoder")?;
|
||||
let encoder = make_element("audioconvert", "audencoder")?;
|
||||
let payload = make_element("rtpL16pay", "pay1")?;
|
||||
|
||||
bin.add_many(&[&source, &queue, &decoder, &encoder, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &decoder])?;
|
||||
bin.add_many(&[&source, &queue, &queue2, &decoder, &encoder, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &queue2, &decoder])?;
|
||||
Element::link_many(&[&encoder, &payload])?;
|
||||
decoder.connect_pad_added(move |_element, pad| {
|
||||
debug!("Linking encoder to decoder: {:?}", pad.caps());
|
||||
@@ -592,10 +586,8 @@ impl NeoMediaFactoryImpl {
|
||||
|
||||
self.clientsender.blocking_send(client_data)?;
|
||||
// debug!("Pipeline built");
|
||||
let element = bin
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
Ok(Some(element))
|
||||
bin.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))
|
||||
}
|
||||
|
||||
async fn join(&self) -> AnyResult<()> {
|
||||
|
||||
+284
-124
@@ -43,12 +43,6 @@ struct NeoBuffer {
|
||||
max_size: usize,
|
||||
}
|
||||
|
||||
/// The historical buffer is how much we keep extra after live.
|
||||
///
|
||||
/// This represents the upper limit we keep in storage after live
|
||||
/// while waiting for the time to play arrives
|
||||
const HISTORICAL_BUFFER_SIZE: usize = 100;
|
||||
|
||||
impl NeoBuffer {
|
||||
fn new(max_size: usize) -> Self {
|
||||
Self {
|
||||
@@ -104,21 +98,65 @@ impl NeoBuffer {
|
||||
last.data.push(media);
|
||||
}
|
||||
|
||||
while self.buf.len() > self.max_size + HISTORICAL_BUFFER_SIZE {
|
||||
while self.buf.len() > self.max_size {
|
||||
if self.buf.pop_front().is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prep_size(&self) -> usize {
|
||||
self.max_size * 2 / 3
|
||||
}
|
||||
|
||||
fn live_size(&self) -> usize {
|
||||
self.max_size
|
||||
self.max_size / 3
|
||||
}
|
||||
|
||||
pub(crate) fn ready(&self) -> bool {
|
||||
self.buf.len() >= self.live_size() + HISTORICAL_BUFFER_SIZE / 2
|
||||
self.buf.len() > self.prep_size()
|
||||
}
|
||||
|
||||
pub(crate) fn ready_play(&self) -> bool {
|
||||
self.buf.len() > self.live_size()
|
||||
}
|
||||
|
||||
// fn last_iframe_time(&self) -> Option<FrameTime> {
|
||||
// let (fronts, backs) = self.buf.as_slices();
|
||||
// backs
|
||||
// .iter()
|
||||
// .rev()
|
||||
// .chain(&mut fronts.iter().rev())
|
||||
// .flat_map(|frame| match frame {
|
||||
// BcMedia::Iframe(BcMediaIframe { microseconds, .. }) => Some(*microseconds),
|
||||
// _ => None,
|
||||
// })
|
||||
// .next()
|
||||
// .map(|i| i as FrameTime)
|
||||
// }
|
||||
|
||||
// fn first_iframe_time(&self) -> Option<FrameTime> {
|
||||
// let (fronts, backs) = self.buf.as_slices();
|
||||
// fronts
|
||||
// .iter()
|
||||
// .chain(&mut backs.iter())
|
||||
// .flat_map(|frame| match frame {
|
||||
// BcMedia::Iframe(BcMediaIframe { microseconds, .. }) => Some(*microseconds),
|
||||
// _ => None,
|
||||
// })
|
||||
// .next()
|
||||
// .map(|i| i as FrameTime)
|
||||
// }
|
||||
|
||||
// fn start_time(&self) -> Option<FrameTime> {
|
||||
// let (fronts, backs) = self.buf.as_slices();
|
||||
// fronts
|
||||
// .iter()
|
||||
// .chain(&mut backs.iter())
|
||||
// .map(|frame| frame.time)
|
||||
// .next()
|
||||
// }
|
||||
|
||||
fn end_time(&self) -> Option<FrameTime> {
|
||||
let (fronts, backs) = self.buf.as_slices();
|
||||
backs
|
||||
@@ -128,6 +166,35 @@ impl NeoBuffer {
|
||||
.map(|frame| frame.time)
|
||||
.next()
|
||||
}
|
||||
|
||||
// fn min_time(&self) -> Option<FrameTime> {
|
||||
// let (fronts, backs) = self.buf.as_slices();
|
||||
// fronts
|
||||
// .iter()
|
||||
// .chain(&mut backs.iter())
|
||||
// .flat_map(|frame| match Arc::as_ref(frame) {
|
||||
// BcMedia::Iframe(BcMediaIframe { microseconds, .. }) => Some(*microseconds),
|
||||
// BcMedia::Pframe(BcMediaPframe { microseconds, .. }) => Some(*microseconds),
|
||||
// _ => None,
|
||||
// })
|
||||
// .min()
|
||||
// .map(|i| i as FrameTime)
|
||||
// }
|
||||
|
||||
// fn max_time(&self) -> Option<FrameTime> {
|
||||
// let (fronts, backs) = self.buf.as_slices();
|
||||
// backs
|
||||
// .iter()
|
||||
// .rev()
|
||||
// .chain(&mut fronts.iter().rev())
|
||||
// .flat_map(|frame| match Arc::as_ref(frame) {
|
||||
// BcMedia::Iframe(BcMediaIframe { microseconds, .. }) => Some(*microseconds),
|
||||
// BcMedia::Pframe(BcMediaPframe { microseconds, .. }) => Some(*microseconds),
|
||||
// _ => None,
|
||||
// })
|
||||
// .max()
|
||||
// .map(|i| i as FrameTime)
|
||||
// }
|
||||
}
|
||||
|
||||
pub(super) struct NeoMediaSenders {
|
||||
@@ -221,30 +288,24 @@ impl NeoMediaSenders {
|
||||
async fn handle_new_data(&mut self, data: BcMedia) -> AnyResult<()> {
|
||||
// trace!("Handle new data");
|
||||
self.update_mediatypes(&data).await;
|
||||
|
||||
let data = Arc::new(data);
|
||||
|
||||
let end_time = self.buffer.end_time();
|
||||
let frame_time = match data.as_ref() {
|
||||
let time = match &data {
|
||||
BcMedia::Iframe(BcMediaIframe { microseconds, .. }) => *microseconds as FrameTime,
|
||||
BcMedia::Pframe(BcMediaPframe { microseconds, .. }) => *microseconds as FrameTime,
|
||||
_ => self.buffer.end_time().unwrap_or(0),
|
||||
};
|
||||
// If there is a jump in the time stamps for any reason
|
||||
// (including a resume from a pause)
|
||||
// Then we stitch the old and new frames together without
|
||||
// waiting for the time to elapse
|
||||
|
||||
let data = Arc::new(data);
|
||||
|
||||
let end_time = self.buffer.end_time();
|
||||
let frame_time = time;
|
||||
// Ocassionally the camera will make a jump in timestamps of about 15s (on sub 9s on main)
|
||||
// This could mean that it runs on some fixed sized buffer
|
||||
if let Some(end_time) = end_time {
|
||||
// An approximate fps
|
||||
let delta_frame = (self.buffer.buf.back().unwrap().time
|
||||
- self.buffer.buf.front().unwrap().time)
|
||||
/ self.buffer.buf.len() as i64;
|
||||
|
||||
// Shift current frames backwards from the new start - approx fps
|
||||
let delta_time = frame_time - end_time - delta_frame;
|
||||
let delta_duration = Duration::from_micros(delta_time.unsigned_abs());
|
||||
|
||||
// If that shift >1s then we stitch it together
|
||||
if delta_duration > Duration::from_secs(1) {
|
||||
trace!(
|
||||
"Reschedule buffer due to jump: {:?}, Prev: {}, New: {}",
|
||||
@@ -268,8 +329,6 @@ impl NeoMediaSenders {
|
||||
for frame in client.buffer.buf.iter_mut() {
|
||||
frame.time = frame.time.saturating_add(delta_time);
|
||||
}
|
||||
// We also move the start time up so that the new frames will play
|
||||
// with the stiching
|
||||
client.start_time.mod_value(delta_time as f64);
|
||||
}
|
||||
}
|
||||
@@ -406,6 +465,9 @@ impl NeoMediaSenders {
|
||||
},
|
||||
FactoryCommand::JumpToLive => {
|
||||
for client in self.client_data.values_mut() {
|
||||
// Set them into the non init state
|
||||
// This will make them wait for the
|
||||
// buffer to be enough then jump to live
|
||||
let _ = client.jump_to_live().await;
|
||||
}
|
||||
},
|
||||
@@ -444,20 +506,16 @@ pub(super) struct NeoMediaSender {
|
||||
start_time: Spring,
|
||||
live_offset: FrameTime,
|
||||
buffer: NeoBuffer,
|
||||
vid: Option<Arc<AppSrc>>,
|
||||
aud: Option<Arc<AppSrc>>,
|
||||
vid: Option<AppSrc>,
|
||||
aud: Option<AppSrc>,
|
||||
command_reciever: Receiver<NeoMediaSenderCommand>,
|
||||
command_sender: Sender<NeoMediaSenderCommand>,
|
||||
inited: bool,
|
||||
playing: bool,
|
||||
refilling: bool,
|
||||
use_smoothing: bool,
|
||||
}
|
||||
|
||||
enum Buffer {
|
||||
Video(gstreamer::Buffer),
|
||||
Audio(gstreamer::Buffer),
|
||||
}
|
||||
|
||||
impl NeoMediaSender {
|
||||
pub(super) fn new(buffer_size: usize, use_smoothing: bool) -> Self {
|
||||
let (tx, rx) = channel(30);
|
||||
@@ -471,7 +529,8 @@ impl NeoMediaSender {
|
||||
command_sender: tx,
|
||||
inited: false,
|
||||
playing: true,
|
||||
use_smoothing: use_smoothing && buffer_size > 0,
|
||||
refilling: false,
|
||||
use_smoothing,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -481,11 +540,11 @@ impl NeoMediaSender {
|
||||
}
|
||||
|
||||
pub(super) fn update_vid(&mut self, source: AppSrc) {
|
||||
self.vid.replace(Arc::new(source));
|
||||
self.vid.replace(source);
|
||||
}
|
||||
|
||||
pub(super) fn update_aud(&mut self, source: AppSrc) {
|
||||
self.aud.replace(Arc::new(source));
|
||||
self.aud.replace(source);
|
||||
}
|
||||
|
||||
pub(super) fn get_commader(&self) -> Sender<NeoMediaSenderCommand> {
|
||||
@@ -494,10 +553,6 @@ impl NeoMediaSender {
|
||||
|
||||
fn target_live_for(buffer: &NeoBuffer) -> Option<FrameTime> {
|
||||
let target_idx = buffer.live_size();
|
||||
if target_idx == 0 {
|
||||
// No buffer needed grab the last
|
||||
return buffer.buf.back().map(|item| item.time);
|
||||
}
|
||||
let stamps = buffer.buf.iter().map(|item| item.time).collect::<Vec<_>>();
|
||||
|
||||
if stamps.len() >= target_idx {
|
||||
@@ -513,7 +568,12 @@ impl NeoMediaSender {
|
||||
}
|
||||
} else {
|
||||
trace!("Not enough timestamps for target live: {:?}", stamps);
|
||||
None
|
||||
if let Some(st) = stamps.first() {
|
||||
trace!("Setting to 1s behind first frame in buffer");
|
||||
Some(st - Duration::from_secs(1).as_micros() as FrameTime)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -575,12 +635,9 @@ impl NeoMediaSender {
|
||||
async fn seek(
|
||||
&mut self,
|
||||
_original_runtime: Option<FrameTime>,
|
||||
target_runtime: FrameTime,
|
||||
_target_runtime: FrameTime,
|
||||
_master_buffer: &NeoBuffer,
|
||||
) -> AnyResult<()> {
|
||||
if let Some(runtime) = self.get_raw_runtime() {
|
||||
self.live_offset = target_runtime - runtime;
|
||||
}
|
||||
self.jump_to_live().await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -620,27 +677,20 @@ impl NeoMediaSender {
|
||||
self.buffer.buf.clear();
|
||||
|
||||
let mut buffer_iter = buffer.buf.iter().cloned();
|
||||
// The prebuffer should starts from an Iframe
|
||||
let preprocess = buffer_iter
|
||||
.take_while_ref(|item| {
|
||||
item.time < target_time
|
||||
|| !matches!(
|
||||
item.data.first().map(|arc| arc.as_ref()),
|
||||
Some(BcMedia::Iframe(_))
|
||||
)
|
||||
})
|
||||
.take_while_ref(|item| item.time < target_time)
|
||||
.collect::<Vec<_>>();
|
||||
let mut buffer = buffer_iter.collect::<Vec<_>>();
|
||||
self.start_time.reset_to(target_time as f64);
|
||||
|
||||
// Send preprocess now
|
||||
self.send_buffers(preprocess.as_slice(), true).await?;
|
||||
debug!("Preprocessed: {}", preprocess.len());
|
||||
self.send_buffers(preprocess.as_slice()).await?;
|
||||
trace!("Preprocessed");
|
||||
// Send these later
|
||||
for frame in buffer.drain(..) {
|
||||
self.buffer.buf.push_back(frame);
|
||||
}
|
||||
trace!("Buffer filled: {}", self.buffer.buf.len());
|
||||
trace!("Buffer filled");
|
||||
|
||||
self.jump_to_live().await?;
|
||||
} else {
|
||||
@@ -652,13 +702,28 @@ impl NeoMediaSender {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_raw_runtime(&self) -> Option<FrameTime> {
|
||||
fn get_runtime(&self) -> Option<FrameTime> {
|
||||
if let Some(appsrc) = self.vid.as_ref() {
|
||||
if let Some(clock) = appsrc.clock() {
|
||||
if let Some(time) = clock.time() {
|
||||
if let Some(base_time) = appsrc.base_time() {
|
||||
let runtime = time.saturating_sub(base_time);
|
||||
return Some(runtime.useconds() as FrameTime);
|
||||
let res = Some(
|
||||
(runtime.useconds() as FrameTime)
|
||||
.saturating_add(self.live_offset)
|
||||
.max(0),
|
||||
);
|
||||
// debug!("base_time: {:?}", base_time);
|
||||
// debug!("time: {:?}", time);
|
||||
// debug!("runtime: {:?}", runtime);
|
||||
// debug!("Final runtime: {:?}", res);
|
||||
trace!(
|
||||
"Runtime: {:?}, Offset: {:?}, Offseted Runtime: {:?}",
|
||||
runtime,
|
||||
self.live_offset,
|
||||
res
|
||||
);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -666,11 +731,6 @@ impl NeoMediaSender {
|
||||
None
|
||||
}
|
||||
|
||||
fn get_runtime(&self) -> Option<FrameTime> {
|
||||
self.get_raw_runtime()
|
||||
.map(|runtime| runtime.saturating_add(self.live_offset).max(0))
|
||||
}
|
||||
|
||||
fn get_buftime(&self) -> Option<FrameTime> {
|
||||
self.get_runtime().map(|time| self.runtime_to_buftime(time))
|
||||
}
|
||||
@@ -684,9 +744,22 @@ impl NeoMediaSender {
|
||||
}
|
||||
|
||||
async fn update(&mut self) -> AnyResult<()> {
|
||||
if self.inited && self.playing {
|
||||
if self.buffer.buf.len() >= self.buffer.max_size * 9 / 10 {
|
||||
debug!("Buffer overfull");
|
||||
self.jump_to_live().await?;
|
||||
}
|
||||
if self.refilling && self.buffer.ready_play() {
|
||||
self.refilling = false;
|
||||
self.jump_to_live().await?;
|
||||
} else if self.refilling {
|
||||
trace!(
|
||||
"Refilling: {}/{} ({:.2}%)",
|
||||
self.buffer.buf.len(),
|
||||
self.buffer.live_size(),
|
||||
self.buffer.buf.len() as f32 / (self.buffer.live_size()) as f32 * 100.0
|
||||
);
|
||||
} else if !self.refilling && self.inited && self.playing {
|
||||
self.update_starttime().await?;
|
||||
let ignore_stamps = self.buffer.live_size() == 0;
|
||||
// Check app src is live
|
||||
if !self
|
||||
.vid
|
||||
@@ -697,6 +770,17 @@ impl NeoMediaSender {
|
||||
return Err(anyhow!("Vid src is closed"));
|
||||
}
|
||||
|
||||
// Check if buffers are ok
|
||||
if self.buffer.buf.len() <= self.buffer.max_size / 10 {
|
||||
warn!(
|
||||
"Buffer exhausted. Not enough data from Camera. Pausing RTSP until refilled."
|
||||
);
|
||||
info!("Try reducing your Max Bitrate using the offical app");
|
||||
self.refilling = true;
|
||||
} else {
|
||||
trace!("Buffer size: {}", self.buffer.buf.len());
|
||||
}
|
||||
|
||||
// Send buffers
|
||||
let mut buffers = vec![];
|
||||
if let Some(buftime) = self.get_buftime() {
|
||||
@@ -708,6 +792,7 @@ impl NeoMediaSender {
|
||||
.map(|data| data.time <= buftime)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
tokio::task::yield_now().await;
|
||||
match self.buffer.buf.pop_front() {
|
||||
Some(frame) => {
|
||||
buffers.push(frame);
|
||||
@@ -719,21 +804,27 @@ impl NeoMediaSender {
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
// collect certain frames
|
||||
self.send_buffers(&buffers, ignore_stamps).await?;
|
||||
self.send_buffers(&buffers).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_buffers(&mut self, medias: &[Stamped], ignore_stamps: bool) -> AnyResult<()> {
|
||||
async fn send_buffers(&mut self, medias: &[Stamped]) -> AnyResult<()> {
|
||||
if medias.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut buffers: Vec<Buffer> = vec![];
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
let mut vid_buffers: Vec<(FrameTime, Vec<u8>)> = vec![];
|
||||
let mut aud_buffers: Vec<(FrameTime, Vec<u8>)> = vec![];
|
||||
for media_sets in medias.iter() {
|
||||
tokio::task::yield_now().await;
|
||||
for media in media_sets.data.iter() {
|
||||
let buffer = match media.as_ref() {
|
||||
BcMedia::Iframe(_) | BcMedia::Pframe(_) => Some(&mut vid_buffers),
|
||||
BcMedia::Aac(_) | BcMedia::Adpcm(_) => Some(&mut aud_buffers),
|
||||
_ => None,
|
||||
};
|
||||
let data = match media.as_ref() {
|
||||
BcMedia::Iframe(data) => Some(&data.data),
|
||||
BcMedia::Pframe(data) => Some(&data.data),
|
||||
@@ -741,71 +832,140 @@ impl NeoMediaSender {
|
||||
BcMedia::Adpcm(data) => Some(&data.data),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(buf) = data {
|
||||
let time = media_sets.time;
|
||||
let runtime = match (self.get_runtime(), ignore_stamps) {
|
||||
(None, _) | (_, false) => self.buftime_to_runtime(time),
|
||||
(Some(runtime), true) => runtime,
|
||||
};
|
||||
trace!(
|
||||
" - Sending vid frame at time {} ({:?} Expect: {:?})",
|
||||
time,
|
||||
Duration::from_micros(runtime as u64),
|
||||
self.get_runtime().map(|i| Duration::from_micros(i as u64))
|
||||
);
|
||||
|
||||
let gst_buf = {
|
||||
let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
|
||||
let time = ClockTime::from_useconds(runtime.try_into().unwrap());
|
||||
gst_buf_mut.set_dts(time);
|
||||
gst_buf_mut.set_pts(time);
|
||||
let mut gst_buf_data = gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(buf.as_slice());
|
||||
if let (Some(data), Some(buffer)) = (data, buffer) {
|
||||
let next_time = media_sets.time;
|
||||
if let Some(last) = buffer.last_mut() {
|
||||
let last_time = last.0;
|
||||
if next_time == last_time {
|
||||
last.1.extend(data.iter().copied());
|
||||
} else {
|
||||
buffer.push((next_time, data.clone()))
|
||||
}
|
||||
gst_buf
|
||||
};
|
||||
match media.as_ref() {
|
||||
BcMedia::Iframe(_) | BcMedia::Pframe(_) => {
|
||||
buffers.push(Buffer::Video(gst_buf));
|
||||
}
|
||||
BcMedia::Aac(_) | BcMedia::Adpcm(_) => {
|
||||
buffers.push(Buffer::Audio(gst_buf));
|
||||
}
|
||||
_ => {}
|
||||
} else {
|
||||
buffer.push((next_time, data.clone()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
for buf in buffers.drain(..) {
|
||||
let buf_app = match (buf, self.vid.as_ref(), self.aud.as_ref()) {
|
||||
(Buffer::Video(buf), Some(app), _) => Some((buf, app.clone())),
|
||||
(Buffer::Audio(buf), _, Some(app)) => Some((buf, app.clone())),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((buf, appsrc)) = buf_app {
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
appsrc
|
||||
.push_buffer(buf.copy())
|
||||
.map(|_| ())
|
||||
.map_err(|_| anyhow!("Could not push buffer to appsrc"))
|
||||
})
|
||||
.await;
|
||||
match &res {
|
||||
Err(e) => {
|
||||
debug!("Paniced on send buffer list: {:?}", e);
|
||||
tokio::try_join!(
|
||||
async {
|
||||
if !vid_buffers.is_empty() {
|
||||
// debug!("Sending video buffers: {}", vid_buffers.len());
|
||||
if let Some(appsrc) = self.vid.clone() {
|
||||
let buffers = {
|
||||
let mut buffers = gstreamer::BufferList::new_sized(vid_buffers.len());
|
||||
{
|
||||
let buffers_ref = buffers.get_mut().unwrap();
|
||||
for (time, buf) in vid_buffers.drain(..) {
|
||||
tokio::task::yield_now().await;
|
||||
let runtime = self.buftime_to_runtime(time);
|
||||
trace!(
|
||||
" - Sending vid frame at time {} ({:?} Expect: {:?})",
|
||||
time,
|
||||
Duration::from_micros(runtime as u64),
|
||||
self.get_runtime().map(|i| Duration::from_micros(i as u64))
|
||||
);
|
||||
|
||||
let gst_buf = {
|
||||
let mut gst_buf =
|
||||
gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
|
||||
let time = ClockTime::from_useconds(
|
||||
runtime.try_into().unwrap(),
|
||||
);
|
||||
gst_buf_mut.set_dts(time);
|
||||
let mut gst_buf_data =
|
||||
gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(buf.as_slice());
|
||||
}
|
||||
gst_buf
|
||||
};
|
||||
buffers_ref.add(gst_buf);
|
||||
}
|
||||
}
|
||||
buffers
|
||||
};
|
||||
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
// debug!(" - Pushing buffer: {}", buffers.len());
|
||||
appsrc
|
||||
.push_buffer_list(buffers.copy())
|
||||
.map(|_| ())
|
||||
.map_err(|_| anyhow!("Could not push buffer to appsrc"))
|
||||
})
|
||||
.await;
|
||||
match &res {
|
||||
Err(e) => {
|
||||
debug!("Paniced on send buffer list: {:?}", e);
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
debug!("Failed to send buffer list: {:?}", e);
|
||||
}
|
||||
Ok(Ok(_)) => {}
|
||||
};
|
||||
res??;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
debug!("Failed to send buffer list: {:?}", e);
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
},
|
||||
async {
|
||||
if !aud_buffers.is_empty() {
|
||||
if let Some(appsrc) = self.aud.clone() {
|
||||
let buffers = {
|
||||
let mut buffers = gstreamer::BufferList::new_sized(aud_buffers.len());
|
||||
{
|
||||
let buffers_ref = buffers.get_mut().unwrap();
|
||||
for (time, buf) in aud_buffers.drain(..) {
|
||||
tokio::task::yield_now().await;
|
||||
let runtime = self.buftime_to_runtime(time);
|
||||
|
||||
let gst_buf = {
|
||||
let mut gst_buf =
|
||||
gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
|
||||
let time = ClockTime::from_useconds(
|
||||
runtime.try_into().unwrap(),
|
||||
);
|
||||
gst_buf_mut.set_dts(time);
|
||||
let mut gst_buf_data =
|
||||
gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(buf.as_slice());
|
||||
}
|
||||
gst_buf
|
||||
};
|
||||
buffers_ref.add(gst_buf);
|
||||
}
|
||||
}
|
||||
buffers
|
||||
};
|
||||
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
appsrc
|
||||
.push_buffer_list(buffers.copy())
|
||||
.map(|_| ())
|
||||
.map_err(|_| anyhow!("Could not push buffer to appsrc"))
|
||||
})
|
||||
.await;
|
||||
match &res {
|
||||
Err(e) => {
|
||||
debug!("Paniced on send buffer list: {:?}", e);
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
debug!("Failed to send buffer list: {:?}", e);
|
||||
}
|
||||
Ok(Ok(_)) => {}
|
||||
};
|
||||
res??;
|
||||
}
|
||||
Ok(Ok(_)) => {}
|
||||
};
|
||||
res??;
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
}
|
||||
}
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -363,11 +363,7 @@ impl NeoRtspServerImpl {
|
||||
match self.medias.write().await.entry(key.clone()) {
|
||||
Entry::Occupied(_occ) => {}
|
||||
Entry::Vacant(vac) => {
|
||||
let media = NeoMediaFactory::new(
|
||||
config.buffer_size,
|
||||
config.use_smoothing,
|
||||
config.use_splash,
|
||||
);
|
||||
let media = NeoMediaFactory::new(config.buffer_size, config.use_smoothing);
|
||||
let thread_media = media.clone();
|
||||
self.threads
|
||||
.write()
|
||||
|
||||
@@ -25,7 +25,6 @@ pub(super) struct NeoMediaShared {
|
||||
pub(super) buffer_ready: AtomicBool,
|
||||
pub(super) buffer_size: AtomicUsize,
|
||||
pub(super) use_smoothing: AtomicBool,
|
||||
pub(super) splash: AtomicBool,
|
||||
}
|
||||
|
||||
impl Default for NeoMediaShared {
|
||||
@@ -37,7 +36,6 @@ impl Default for NeoMediaShared {
|
||||
buffer_ready: AtomicBool::new(false),
|
||||
buffer_size: AtomicUsize::new(100),
|
||||
use_smoothing: AtomicBool::new(false),
|
||||
splash: AtomicBool::new(true),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,12 +56,4 @@ impl NeoMediaShared {
|
||||
pub(super) fn set_use_smoothing(&self, new_value: bool) {
|
||||
self.use_smoothing.store(new_value, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(super) fn get_use_splash(&self) -> bool {
|
||||
self.splash.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(super) fn set_use_splash(&self, new_value: bool) {
|
||||
self.splash.store(new_value, Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
+90
-174
@@ -55,8 +55,6 @@
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use futures::stream::FuturesUnordered;
|
||||
use log::*;
|
||||
use neolink_core::bc_protocol::{BcCamera, StreamKind};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio_stream::StreamExt;
|
||||
@@ -174,14 +172,10 @@ async fn camera_main(camera: Camera<Disconnected>) -> Result<(), CameraFailureKi
|
||||
.await
|
||||
.with_context(|| format!("{}: Could not login to camera", name))
|
||||
.map_err(|e| {
|
||||
let e_inner = e.downcast_ref::<neolink_core::Error>();
|
||||
let e_inner = e.downcast_ref::<neolink_core::Error>().unwrap();
|
||||
match e_inner {
|
||||
Some(neolink_core::Error::CameraLoginFail) => CameraFailureKind::Fatal(e),
|
||||
Some(_) => CameraFailureKind::Retry(e),
|
||||
None => {
|
||||
// Timout error usually
|
||||
CameraFailureKind::Retry(e)
|
||||
}
|
||||
neolink_core::Error::CameraLoginFail => CameraFailureKind::Fatal(e),
|
||||
_ => CameraFailureKind::Retry(e),
|
||||
}
|
||||
})?;
|
||||
|
||||
@@ -248,153 +242,23 @@ async fn camera_main(camera: Camera<Disconnected>) -> Result<(), CameraFailureKi
|
||||
.await;
|
||||
log::info!("{}: Buffers prepared", name);
|
||||
|
||||
let mut active_tags = streaming.shared.get_streams().clone();
|
||||
let mut motion_pause = false;
|
||||
loop {
|
||||
// Wait for error or reason to pause
|
||||
let change = tokio::select! {
|
||||
tokio::select! {
|
||||
v = async {
|
||||
// Wait for error
|
||||
streaming.join().await
|
||||
}, if ! active_tags.is_empty() => {
|
||||
info!("{}: Join Pause", name);
|
||||
Ok(StreamChange::StreamError(v))
|
||||
// Wait for error
|
||||
streaming.join().await
|
||||
} => {
|
||||
info!("Join Pause");
|
||||
v
|
||||
},
|
||||
v = await_change(
|
||||
streaming.get_camera(),
|
||||
&streaming.shared,
|
||||
&rtsp_thread,
|
||||
&active_tags,
|
||||
motion_pause,
|
||||
&name,
|
||||
), if streaming.shared.get_config().pause.on_motion || streaming.shared.get_config().pause.on_disconnect => {
|
||||
v.with_context(|| format!("{}: Error updating pause state", name))
|
||||
.map_err(CameraFailureKind::Retry)
|
||||
}
|
||||
}?;
|
||||
|
||||
match change {
|
||||
StreamChange::StreamError(res) => {
|
||||
res.map_err(CameraFailureKind::Retry)?;
|
||||
}
|
||||
StreamChange::MotionStart => {
|
||||
motion_pause = false;
|
||||
let inactive_streams = streaming
|
||||
.shared
|
||||
.get_streams()
|
||||
.iter()
|
||||
.filter(|i| !active_tags.contains(i))
|
||||
.copied()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if streaming.shared.get_config().pause.on_disconnect {
|
||||
// Pause on client is also on
|
||||
//
|
||||
// Only resume clients with active connections
|
||||
for stream in inactive_streams.iter() {
|
||||
if rtsp_thread
|
||||
.get_number_of_clients(streaming.shared.get_tag_for_stream(stream))
|
||||
.await
|
||||
.map(|n| n > 0)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
streaming
|
||||
.start_stream(*stream)
|
||||
.await
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
active_tags.insert(*stream);
|
||||
rtsp_thread
|
||||
.resume(streaming.shared.get_tag_for_stream(stream))
|
||||
.await
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Pause on client is not on
|
||||
//
|
||||
// Resume all
|
||||
for stream in inactive_streams.iter() {
|
||||
streaming
|
||||
.start_stream(*stream)
|
||||
.await
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
active_tags.insert(*stream);
|
||||
rtsp_thread
|
||||
.resume(streaming.shared.get_tag_for_stream(stream))
|
||||
.await
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
StreamChange::MotionStop => {
|
||||
motion_pause = true;
|
||||
// Clear all streams
|
||||
for stream in active_tags.drain() {
|
||||
rtsp_thread
|
||||
.pause(streaming.shared.get_tag_for_stream(&stream))
|
||||
.await
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
streaming
|
||||
.stop_stream(stream)
|
||||
.await
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
}
|
||||
}
|
||||
StreamChange::ClientStart(stream) => {
|
||||
if !streaming.shared.get_config().pause.on_motion || !motion_pause {
|
||||
streaming
|
||||
.start_stream(stream)
|
||||
.await
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
active_tags.insert(stream);
|
||||
rtsp_thread
|
||||
.resume(streaming.shared.get_tag_for_stream(&stream))
|
||||
.await
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
}
|
||||
}
|
||||
StreamChange::ClientStop(stream) => {
|
||||
if !streaming.shared.get_config().pause.on_motion || !motion_pause {
|
||||
rtsp_thread
|
||||
.pause(streaming.shared.get_tag_for_stream(&stream))
|
||||
.await
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
streaming
|
||||
.stop_stream(stream)
|
||||
.await
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
active_tags.remove(&stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Ok(())
|
||||
}
|
||||
|
||||
enum StreamChange {
|
||||
StreamError(Result<()>),
|
||||
MotionStart,
|
||||
MotionStop,
|
||||
ClientStart(StreamKind),
|
||||
ClientStop(StreamKind),
|
||||
}
|
||||
async fn await_change(
|
||||
camera: &BcCamera,
|
||||
shared: &Shared,
|
||||
rtsp_thread: &NeoRtspServer,
|
||||
active_tags: &HashSet<StreamKind>,
|
||||
motion_pause: bool,
|
||||
name: &str,
|
||||
) -> Result<StreamChange> {
|
||||
tokio::select! {
|
||||
v = async {
|
||||
// Wait for motion stop
|
||||
let mut motion = camera.listen_on_motion().await?;
|
||||
motion.await_stop(Duration::from_secs_f64(shared.get_config().pause.motion_timeout)).await
|
||||
}, if motion_pause && shared.get_config().pause.on_motion => {
|
||||
info!("{}: Motion Pause", name);
|
||||
v.map_err(|e| anyhow!("Error while processing motion messages: {:?}", e))?;
|
||||
Ok(StreamChange::MotionStop)
|
||||
let mut motion = streaming.get_camera().listen_on_motion().await?;
|
||||
motion.await_stop(Duration::from_secs_f64(streaming.get_config().pause.motion_timeout)).await
|
||||
}, if streaming.get_config().pause.on_motion => {
|
||||
info!("Motion Pause");
|
||||
v.map_err(|e| anyhow!("Error while processing motion messages: {:?}", e))
|
||||
},
|
||||
v = async {
|
||||
// Wait for client to disconnect
|
||||
@@ -402,45 +266,97 @@ async fn await_change(
|
||||
|
||||
loop {
|
||||
inter.tick().await;
|
||||
for tag in active_tags.iter() {
|
||||
if rtsp_thread.get_number_of_clients(shared.get_tag_for_stream(tag)).await.map(|n| n == 0).unwrap_or(true) {
|
||||
return Result::<_,anyhow::Error>::Ok(StreamChange::ClientStop(*tag))
|
||||
}
|
||||
let total_clients = tags.iter().map(|tag| rtsp_thread.get_number_of_clients(tag)).collect::<FuturesUnordered<_>>().fold(0usize, |acc, f| acc + f.unwrap_or(0usize)).await;
|
||||
// info!("Num clients: {}", total_clients);
|
||||
if total_clients == 0 {
|
||||
return Ok(())
|
||||
}
|
||||
}
|
||||
}, if shared.get_config().pause.on_disconnect => {
|
||||
if let Ok(StreamChange::ClientStop(tag)) = v.as_ref() {
|
||||
info!("{}: Client Pause:: {:?}", name, tag);
|
||||
}
|
||||
}, if streaming.get_config().pause.on_disconnect => {
|
||||
info!("Client Pause");
|
||||
v
|
||||
},
|
||||
}.with_context(|| format!("{}: Error while streaming", name))
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
|
||||
tags.iter()
|
||||
.map(|tag| rtsp_thread.pause(tag))
|
||||
.collect::<FuturesUnordered<_>>()
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
|
||||
let paused = streaming
|
||||
.stop()
|
||||
.await
|
||||
.with_context(|| format!("{}: Could not stop stream", name))
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
// Wait for reason to restart
|
||||
tokio::select! {
|
||||
v = async {
|
||||
// Wait for motion start and client for start
|
||||
let mut motion = paused.get_camera().listen_on_motion().await?;
|
||||
let mut inter = tokio::time::interval(tokio::time::Duration::from_secs_f32(0.01));
|
||||
loop {
|
||||
motion.await_start(Duration::ZERO).await?;
|
||||
let total_clients = tags.iter().map(|tag| rtsp_thread.get_number_of_clients(tag)).collect::<FuturesUnordered<_>>().fold(0usize, |acc, f| acc + f.unwrap_or(0usize)).await;
|
||||
if total_clients > 0 {
|
||||
return Result::<()>::Ok(());
|
||||
}
|
||||
inter.tick().await;
|
||||
}
|
||||
}, if paused.get_config().pause.on_motion && paused.get_config().pause.on_disconnect => {
|
||||
info!("Motion and Client Resume");
|
||||
v.with_context(|| "Error while processing motion/client messages")
|
||||
},
|
||||
v = async {
|
||||
// Wait for motion start
|
||||
let mut motion = camera.listen_on_motion().await?;
|
||||
let mut motion = paused.get_camera().listen_on_motion().await?;
|
||||
motion.await_start(Duration::ZERO).await
|
||||
}, if ! motion_pause && shared.get_config().pause.on_motion => {
|
||||
info!("{}: Motion Resume", name);
|
||||
v.with_context(|| "Error while processing motion messages")?;
|
||||
Ok(StreamChange::MotionStart)
|
||||
}, if paused.get_config().pause.on_motion && !paused.get_config().pause.on_disconnect => {
|
||||
info!("Motion Resume");
|
||||
v.with_context(|| "Error while processing motion messages")
|
||||
},
|
||||
v = async {
|
||||
// Wait for client to connect
|
||||
let mut inter = tokio::time::interval(tokio::time::Duration::from_secs_f32(0.01));
|
||||
let inactive_tags = shared.get_streams().iter().filter(|i| !active_tags.contains(i)).collect::<Vec<_>>();
|
||||
trace!("inactive_tags: {:?}", inactive_tags);
|
||||
|
||||
loop {
|
||||
inter.tick().await;
|
||||
for tag in inactive_tags.iter() {
|
||||
if rtsp_thread.get_number_of_clients(shared.get_tag_for_stream(tag)).await.map(|n| n > 0).unwrap_or(false) {
|
||||
return Result::<_,anyhow::Error>::Ok(StreamChange::ClientStart(**tag))
|
||||
}
|
||||
let total_clients = tags.iter().map(|tag| rtsp_thread.get_number_of_clients(tag)).collect::<FuturesUnordered<_>>().fold(0usize, |acc, f| acc + f.unwrap_or(0usize)).await;
|
||||
if total_clients > 0 {
|
||||
return Ok(())
|
||||
}
|
||||
}
|
||||
}, if shared.get_config().pause.on_disconnect => {
|
||||
if let Ok(StreamChange::ClientStart(tag)) = v.as_ref() {
|
||||
info!("{}: Client Resume:: {:?}", name, tag);
|
||||
}
|
||||
}, if paused.get_config().pause.on_disconnect && !paused.get_config().pause.on_motion => {
|
||||
info!("Client Resume");
|
||||
v
|
||||
},
|
||||
}.with_context(|| format!("{}: Error while streaming", name))
|
||||
else => {
|
||||
// No pause. This means that the stream stopped for some reason
|
||||
// but not because of an error
|
||||
info!("Generic Resume");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
.with_context(|| format!("{}: Error while paused", name))
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
|
||||
tags.iter()
|
||||
.map(|tag| rtsp_thread.jump_to_live(tag))
|
||||
.collect::<FuturesUnordered<_>>()
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
|
||||
streaming = paused
|
||||
.stream()
|
||||
.await
|
||||
.with_context(|| format!("{}: Could not start stream", name))
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
|
||||
tags.iter()
|
||||
.map(|tag| rtsp_thread.resume(tag))
|
||||
.collect::<FuturesUnordered<_>>()
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,6 @@ impl<T> Camera<T> {
|
||||
self.shared.config.name.clone()
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn get_config(&self) -> &CameraConfig {
|
||||
&self.shared.config
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
// This state has formed the TCP/UDP tunnel
|
||||
// but has not logged in
|
||||
use super::{camera::Camera, disconnected::Disconnected, loggedin::LoggedIn};
|
||||
use crate::utils::timeout;
|
||||
use anyhow::Result;
|
||||
|
||||
use neolink_core::bc_protocol::{BcCamera, MaxEncryption};
|
||||
@@ -29,7 +28,7 @@ impl Camera<Connected> {
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
|
||||
timeout(self.state.camera.login_with_maxenc(max_encryption)).await??;
|
||||
self.state.camera.login_with_maxenc(max_encryption).await?;
|
||||
Ok(Camera {
|
||||
shared: self.shared,
|
||||
state: LoggedIn {
|
||||
|
||||
@@ -93,7 +93,6 @@ impl Camera<LoggedIn> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn get_camera(&self) -> &BcCamera {
|
||||
&self.state.camera
|
||||
}
|
||||
|
||||
@@ -102,12 +102,6 @@ impl Shared {
|
||||
.map(|k| self.get_tag_for_stream(k))
|
||||
.collect()
|
||||
}
|
||||
pub(crate) fn get_streams(&self) -> &HashSet<Stream> {
|
||||
&self.streams
|
||||
}
|
||||
pub(crate) fn get_config(&self) -> &CameraConfig {
|
||||
&self.config
|
||||
}
|
||||
pub(crate) fn get_tag_for_stream(&self, stream: &Stream) -> String {
|
||||
format!("{}::{:?}", self.config.name, stream)
|
||||
}
|
||||
|
||||
+67
-100
@@ -2,16 +2,11 @@
|
||||
//
|
||||
// Data is streamed into a gstreamer source
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
|
||||
use anyhow::{anyhow, Context, Error, Result};
|
||||
use log::*;
|
||||
use neolink_core::bcmedia::model::BcMedia;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::{timeout, Duration};
|
||||
use tokio::{sync::RwLock, task::JoinSet};
|
||||
|
||||
use neolink_core::bc_protocol::{BcCamera, StreamKind as Stream};
|
||||
|
||||
@@ -20,7 +15,7 @@ use crate::rtsp::gst::FactoryCommand;
|
||||
|
||||
pub(crate) struct Streaming {
|
||||
pub(crate) camera: BcCamera,
|
||||
stream_handles: RwLock<HashMap<Stream, JoinHandle<Result<()>>>>,
|
||||
set: RwLock<JoinSet<Result<()>>>,
|
||||
}
|
||||
|
||||
impl Camera<Streaming> {
|
||||
@@ -28,98 +23,74 @@ impl Camera<Streaming> {
|
||||
// Create new gst outputs
|
||||
//
|
||||
// Otherwise use those already present
|
||||
let mut me = Camera {
|
||||
let mut set: JoinSet<Result<()>> = Default::default();
|
||||
for stream in loggedin.shared.streams.iter() {
|
||||
let tag = loggedin.shared.get_tag_for_stream(stream);
|
||||
let sender = loggedin
|
||||
.shared
|
||||
.rtsp
|
||||
.get_sender(&tag)
|
||||
.await
|
||||
.ok_or_else(|| anyhow!("Stream has not been created"))?;
|
||||
|
||||
let stream_display_name = match stream {
|
||||
Stream::Main => "Main Stream (Clear)",
|
||||
Stream::Sub => "Sub Stream (Fluent)",
|
||||
Stream::Extern => "Extern Stream (Balanced)",
|
||||
};
|
||||
info!(
|
||||
"{}: Starting video stream {}",
|
||||
&loggedin.shared.config.name, stream_display_name
|
||||
);
|
||||
|
||||
let stream_thead = *stream;
|
||||
let strict_thread = loggedin.shared.config.strict;
|
||||
let tag_thread = tag.clone();
|
||||
let mut stream_data = loggedin
|
||||
.state
|
||||
.camera
|
||||
.start_video(stream_thead, 0, strict_thread)
|
||||
.await?;
|
||||
set.spawn(async move {
|
||||
loop {
|
||||
tokio::task::yield_now().await;
|
||||
// debug!("Straming: Get");
|
||||
let data = timeout(Duration::from_secs(15), stream_data.get_data())
|
||||
.await
|
||||
.with_context(|| "Timed out waiting for new Media Frame")??;
|
||||
// debug!("Straming: Got");
|
||||
match &data {
|
||||
Ok(BcMedia::InfoV1(_)) => trace!("{}: - InfoV1", &tag_thread),
|
||||
Ok(BcMedia::InfoV2(_)) => trace!("{}: - InfoV2", &tag_thread),
|
||||
Ok(BcMedia::Iframe(_)) => trace!("{}: - Iframe", &tag_thread),
|
||||
Ok(BcMedia::Pframe(_)) => trace!("{}: - Pframe", &tag_thread),
|
||||
Ok(BcMedia::Aac(_)) => trace!("{}: - Aac", &tag_thread),
|
||||
Ok(BcMedia::Adpcm(_)) => trace!("{}: - Adpcm", &tag_thread),
|
||||
Err(_) => trace!(" - Error"),
|
||||
}
|
||||
// debug!("Straming: Send");
|
||||
timeout(
|
||||
Duration::from_secs(15),
|
||||
sender.send(FactoryCommand::BcMedia(data?)),
|
||||
)
|
||||
.await
|
||||
.with_context(|| "Timed out waiting to send Media Frame")??;
|
||||
// debug!("Straming: Sent");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Ok(Camera {
|
||||
shared: loggedin.shared,
|
||||
state: Streaming {
|
||||
camera: loggedin.state.camera,
|
||||
stream_handles: Default::default(),
|
||||
set: RwLock::new(set),
|
||||
},
|
||||
};
|
||||
|
||||
for stream in me.shared.streams.iter().copied().collect::<Vec<_>>() {
|
||||
me.start_stream(stream).await?;
|
||||
}
|
||||
|
||||
Ok(me)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn start_stream(&mut self, stream: Stream) -> Result<()> {
|
||||
if let Some(handle) = self.state.stream_handles.get_mut().get(&stream) {
|
||||
if !handle.is_finished() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let tag = self.shared.get_tag_for_stream(&stream);
|
||||
let sender = self
|
||||
.shared
|
||||
.rtsp
|
||||
.get_sender(&tag)
|
||||
.await
|
||||
.ok_or_else(|| anyhow!("Stream has not been created"))?;
|
||||
|
||||
let stream_display_name = match stream {
|
||||
Stream::Main => "Main Stream (Clear)",
|
||||
Stream::Sub => "Sub Stream (Fluent)",
|
||||
Stream::Extern => "Extern Stream (Balanced)",
|
||||
};
|
||||
info!(
|
||||
"{}: Starting video stream {}",
|
||||
&self.shared.config.name, stream_display_name
|
||||
);
|
||||
|
||||
let stream_thead = stream;
|
||||
let strict_thread = self.shared.config.strict;
|
||||
let tag_thread = tag.clone();
|
||||
let mut stream_data = self
|
||||
.state
|
||||
.camera
|
||||
.start_video(stream_thead, 0, strict_thread)
|
||||
.await?;
|
||||
let handle = tokio::task::spawn(async move {
|
||||
loop {
|
||||
tokio::task::yield_now().await;
|
||||
// debug!("Straming: Get");
|
||||
let data = timeout(Duration::from_secs(15), stream_data.get_data())
|
||||
.await
|
||||
.with_context(|| "Timed out waiting for new Media Frame")??;
|
||||
// debug!("Straming: Got");
|
||||
match &data {
|
||||
Ok(BcMedia::InfoV1(_)) => trace!("{}: - InfoV1", &tag_thread),
|
||||
Ok(BcMedia::InfoV2(_)) => trace!("{}: - InfoV2", &tag_thread),
|
||||
Ok(BcMedia::Iframe(_)) => trace!("{}: - Iframe", &tag_thread),
|
||||
Ok(BcMedia::Pframe(_)) => trace!("{}: - Pframe", &tag_thread),
|
||||
Ok(BcMedia::Aac(_)) => trace!("{}: - Aac", &tag_thread),
|
||||
Ok(BcMedia::Adpcm(_)) => trace!("{}: - Adpcm", &tag_thread),
|
||||
Err(_) => trace!(" - Error"),
|
||||
}
|
||||
// debug!("Straming: Send");
|
||||
timeout(
|
||||
Duration::from_secs(15),
|
||||
sender.send(FactoryCommand::BcMedia(data?)),
|
||||
)
|
||||
.await
|
||||
.with_context(|| "Timed out waiting to send Media Frame")??;
|
||||
// debug!("Straming: Sent");
|
||||
}
|
||||
});
|
||||
self.state.stream_handles.get_mut().insert(stream, handle);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn stop_stream(&mut self, stream: Stream) -> Result<()> {
|
||||
if let Some(handle) = self.state.stream_handles.get_mut().remove(&stream) {
|
||||
handle.abort();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) async fn stop(self) -> Result<Camera<LoggedIn>> {
|
||||
self.state
|
||||
.stream_handles
|
||||
.into_inner()
|
||||
.into_values()
|
||||
.for_each(|h| h.abort());
|
||||
self.state.set.into_inner().abort_all();
|
||||
Ok(Camera {
|
||||
shared: self.shared,
|
||||
state: LoggedIn {
|
||||
@@ -131,19 +102,15 @@ impl Camera<Streaming> {
|
||||
pub(crate) async fn join(&self) -> Result<()> {
|
||||
tokio::select! {
|
||||
v = async {
|
||||
let mut locked_threads = self.state.stream_handles.write().await;
|
||||
let mut thread_joins = locked_threads.iter_mut().map(|(_, t)| t).collect::<FuturesUnordered::<_>>();
|
||||
|
||||
while let Some(res) = thread_joins.next().await {
|
||||
let mut locked_threads = self.state.set.write().await;
|
||||
while let Some(res) = locked_threads.join_next().await {
|
||||
match res {
|
||||
Err(e) => {
|
||||
drop(thread_joins);
|
||||
locked_threads.iter_mut().for_each(|(_,h)| h.abort());
|
||||
locked_threads.abort_all();
|
||||
return Err(e.into());
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
drop(thread_joins);
|
||||
locked_threads.iter_mut().for_each(|(_,h)| h.abort());
|
||||
locked_threads.abort_all();
|
||||
return Err(e);
|
||||
}
|
||||
Ok(Ok(())) => {}
|
||||
|
||||
+3
-9
@@ -13,13 +13,6 @@ use std::{
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
pub(crate) fn timeout<F>(future: F) -> tokio::time::Timeout<F>
|
||||
where
|
||||
F: std::future::Future,
|
||||
{
|
||||
tokio::time::timeout(tokio::time::Duration::from_secs(5), future)
|
||||
}
|
||||
|
||||
pub(crate) enum AddressOrUid {
|
||||
Address(String),
|
||||
Uid(String, DiscoveryMethods),
|
||||
@@ -140,9 +133,10 @@ pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result<Bc
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
timeout(camera.login_with_maxenc(max_encryption))
|
||||
camera
|
||||
.login_with_maxenc(max_encryption)
|
||||
.await
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))??;
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
|
||||
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
|
||||
Reference in new issue
Block a user