Compare commits

...
Author SHA1 Message Date
QuantumEntangledAndy 786218a114 Make Stream Not Ready splash optional 2023-07-18 14:51:14 +07:00
QuantumEntangledAndy 52ad743bea v0.5.14 2023-07-18 09:16:53 +07:00
Andrew King 0331945730 Merge pull request #116 from QuantumEntangledAndy/fix/streamPrep
Fix Gstreamer Issues with Memory
2023-07-18 09:15:48 +07:00
QuantumEntangledAndy 790807c016 Update deps 2023-07-18 09:10:48 +07:00
QuantumEntangledAndy 45e08e6d7d Trying new buffer push 2023-07-17 09:20:13 +07:00
QuantumEntangledAndy 5b3f845c83 Try process buffers sequentially 2023-07-16 18:30:28 +07:00
QuantumEntangledAndy 4d6d5c5ac5 Single queue 2023-07-16 15:27:06 +07:00
QuantumEntangledAndy 5583ea0f9a Wrapping appsrc in an Arc 2023-07-16 12:27:24 +07:00
Andrew King 4286e75ca6 Merge pull request #106 from QuantumEntangledAndy/feature/image_snap
Use snap command to make jpeg images
2023-07-15 19:09:08 +07:00
QuantumEntangledAndy 15880d1b84 Update image doc 2023-06-19 10:17:48 +07:00
QuantumEntangledAndy 0aee461156 Use tokio file 2023-06-19 10:14:46 +07:00
QuantumEntangledAndy b9969ce9ad Use snap command to make jpeg images 2023-06-15 14:09:15 +07:00
QuantumEntangledAndy 254a310fe9 v0.5.13 2023-06-15 13:53:21 +07:00
Andrew King 679cd60ce0 Merge pull request #95 from kevin-david/discovery
Feature/optional MQTT discovery
2023-06-15 13:48:21 +07:00
QuantumEntangledAndy f73dbacd26 fmt 2023-06-08 16:42:41 +07:00
QuantumEntangledAndy c6505952d5 Add config options for mqtt threads 2023-06-08 16:42:20 +07:00
QuantumEntangledAndy 4f0169ef8f fmt 2023-06-08 13:40:58 +07:00
Andrew 15bf7cfa49 Merge remote-tracking branch 'upstream/master' into discovery 2023-06-08 13:36:29 +07:00
Andrew King 6df5091246 Merge pull request #102 from QuantumEntangledAndy/feature-ptz-preset
Seperate set and assign presets. Also add queury messages to mqtt
2023-06-08 13:25:36 +07:00
QuantumEntangledAndy fbbfddaa37 Handle closing and upgrade message numbers and IDs more cleanly 2023-06-08 13:22:54 +07:00
QuantumEntangledAndy f7b5e89ba8 Handle messages and IDs to better replicate offical messaging system 2023-06-08 12:52:53 +07:00
QuantumEntangledAndy c7bd565049 Handle off byte endian and handle ServieUnavalible in mqtt 2023-06-08 10:13:42 +07:00
QuantumEntangledAndy 83dc6cc90b Add battery sensor to discovery README 2023-06-07 20:58:46 +07:00
QuantumEntangledAndy a449666a8c Add battery sensor to discovery 2023-06-07 20:57:29 +07:00
QuantumEntangledAndy 56476bc162 Add simple battery level 2023-06-07 18:43:39 +07:00
QuantumEntangledAndy c30725bc09 Update readme 2023-06-07 17:56:22 +07:00
QuantumEntangledAndy 3467951c5c Handle message that don't reply on success 2023-06-07 17:36:42 +07:00
QuantumEntangledAndy 9eb892ae27 fmt 2023-06-07 15:59:31 +07:00
QuantumEntangledAndy 00f30b8972 Use enum for config 2023-06-07 15:57:07 +07:00
QuantumEntangledAndy dba2f24364 Add all the mqtt controls to auto discovery 2023-06-07 15:41:10 +07:00
QuantumEntangledAndy 04d15537e4 Update the ptz mod.rs readme 2023-06-07 13:41:01 +07:00
QuantumEntangledAndy b5ae5f2fb5 fmt 2023-06-07 13:39:16 +07:00
Andrew 9267de44c7 Merge remote-tracking branch 'upstream/master' into feature-ptz-preset 2023-06-07 13:35:15 +07:00
QuantumEntangledAndy 2b3ae0e522 Add snap.rs 2023-06-07 13:08:38 +07:00
QuantumEntangledAndy c2e613d68b fmt 2023-06-07 13:06:01 +07:00
QuantumEntangledAndy b221fe6961 Actually add the new .rs 2023-06-07 13:04:34 +07:00
QuantumEntangledAndy 10956e8c8e Add camera preview into mqtt via snap shot command 2023-06-07 13:03:58 +07:00
QuantumEntangledAndy 48f385e73a Add camera preview auto discovery 2023-06-06 15:55:04 +07:00
QuantumEntangledAndy 5c3cae597f Merge branch 'master' of https://github.com/QuantumEntangledAndy/neolink into discovery 2023-06-06 13:25:30 +07:00
Andrew King 4c028bd6de Merge pull request #101 from QuantumEntangledAndy/refractor/buffer
Refractor/buffer
2023-06-06 07:23:01 +01:00
Andrew 1390fa0cf9 Merge branch 'master' into refractor/buffer 2023-06-06 11:47:40 +07:00
QuantumEntangledAndy de0528b1b8 Set pts and dts 2023-06-06 11:39:03 +07:00
QuantumEntangledAndy dee305710c Not on a cron 2023-06-06 11:23:01 +07:00
Andrew 77a33ac86a Merge remote-tracking branch 'upstream/master' 2023-06-06 11:22:18 +07:00
QuantumEntangledAndy a08019bc09 Ensure some buffer for pause before we declare ready 2023-06-06 11:07:43 +07:00
QuantumEntangledAndy 60638441aa Reduce default buffer size 2023-06-06 10:57:39 +07:00
QuantumEntangledAndy 9e981df990 Fixes for zero buffer config 2023-06-06 10:52:45 +07:00
QuantumEntangledAndy 73e828f940 Restore stream timestamp stitching for the pause 2023-06-06 10:45:58 +07:00
Andrew King 017b9cb493 Merge pull request #90 from QuantumEntangledAndy/feature/single_quality_pause
Feature/single quality pause
2023-06-06 04:07:13 +01:00
QuantumEntangledAndy a165377d7a Not smoothing when no buffer 2023-06-05 07:58:16 +07:00
QuantumEntangledAndy f7c16bf5a3 Allow zero buffer and remove buffer refill 2023-06-05 07:53:25 +07:00
Kevin David b5136ed913 Document MQTT Discovery in README.md 2023-06-04 12:53:16 -04:00
Kevin David 2d37807401 Don't get clever trying to reuse device/availability 2023-06-04 12:44:20 -04:00
Kevin David fd3fffc0a1 Attempting to reduce .clone() usage 2023-06-03 12:55:01 -04:00
Kevin David fc8adf2a5c Feature/optional MQTT discovery
Adds config options to enable MQTT Discovery as documented here: https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery

As discussed in https://github.com/QuantumEntangledAndy/neolink/pull/14#issuecomment-1561076262

Unfortinuately, the floodlight/spotlight doesn't show up in the `<AbilityInfo>` returned by the camera: https://github.com/QuantumEntangledAndy/neolink/pull/14#issuecomment-1563728970

Open to other suggestions on how to detect or enable these options.
2023-06-03 12:55:01 -04:00
Andrew King cf67a05dd1 Merge pull request #96 from kevin-david/docker_username
Allow DockerHub username to be specified via `DOCKER_USERNAME` var
2023-06-01 15:20:00 +01:00
Andrew King d961bf36f7 Merge pull request #92 from danielkaiser/feature-ptz-preset 2023-05-29 17:59:03 +01:00
Kevin David a59dafab00 Switch back to distinct DOCKER_PRUNE_TOKEN 2023-05-28 16:41:30 -04:00
Kevin David cf07304bae Allow docker username to be specified, only use one token 2023-05-27 17:04:08 -04:00
QuantumEntangledAndy 9524a1a9f7 Seperate set and assign presets. Also add queury messages to mqtt 2023-05-26 15:09:54 +07:00
QuantumEntangledAndy 4628946514 Use same amount model as in mqtt and add optional speed 2023-05-26 00:55:11 +07:00
QuantumEntangledAndy da3afe228e Use async sleep 2023-05-25 23:55:47 +07:00
Andrew b8dafbb92e Merge remote-tracking branch 'upstream/master' into feature-ptz-preset 2023-05-25 17:44:56 +01:00
Andrew King fdff244f15 Merge pull request #14 from kevin-david/flood_mqtt 2023-05-25 14:59:27 +01:00
Daniel Kaiser 27dc4c2bca Add control/preset command to mqtt 2023-05-24 19:12:24 +02:00
Daniel Kaiser aee14bb411 Add PTZ presets and PTZ command line 2023-05-24 15:19:46 +02:00
Kevin David 5f96b2e7f8 Fix XML deserialization of FloodlightStatusList
The children are `FloodlightStatus`, so that's what we should `yaserde(rename)` to
2023-05-24 08:25:47 -04:00
QuantumEntangledAndy f9975520ab Fmt 2023-05-24 12:33:38 +07:00
QuantumEntangledAndy 864f58d20e Async handle_msg closures 2023-05-24 12:26:27 +07:00
QuantumEntangledAndy f42191973a Seperate quality stream pausing 2023-05-22 13:32:15 +07:00
Kevin David d90f0b1002 Improve MQTT error message 2023-05-19 23:48:10 -04:00
QuantumEntangledAndy 4afa457eff Rework pause to be per stream 2023-05-20 10:31:38 +07:00
QuantumEntangledAndy 1824e061f4 fmt 2023-05-19 13:17:04 +07:00
QuantumEntangledAndy be10aaeed5 Add floodlight status and keep alive pings 2023-05-19 13:15:31 +07:00
Andrew ff9e100ac2 Merge remote-tracking branch 'QuantumEntangledAndy/master' into flood_mqtt 2023-05-19 11:26:14 +07:00
George Hilliard 8c6776607b Autobuild every couple of months if no other activity
Builds expire after 90 days
2023-05-06 07:39:51 -05:00
Kevin David 355cd4846a Remove incorrect code for now 2023-01-25 22:52:45 -05:00
Kevin David 6be7ac2d14 Remove .vscode, improve logging 2023-01-24 23:46:40 -05:00
Kevin David 8cbaf06cde Satisify rustfmt 2023-01-24 23:14:11 -05:00
Kevin David 1f8296dd01 WIP: Add support for floodlight control over MQTT 2023-01-24 22:38:00 -05:00
60 changed files with 2771 additions and 784 deletions

No files matched your search

+22 -4
View File
@@ -1,6 +1,9 @@
name: CI name: CI
on: [push, pull_request, workflow_dispatch] on:
push:
pull_request:
workflow_dispatch:
jobs: jobs:
pre_job: pre_job:
@@ -195,8 +198,23 @@ jobs:
uses: docker/login-action@v2 uses: docker/login-action@v2
with: with:
registry: docker.io registry: docker.io
username: ${{ steps.string_user.outputs.lowercase }} username: ${{ vars.DOCKER_USERNAME || steps.string_user.outputs.lowercase }}
password: ${{ secrets.DOCKER_TOKEN }} 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 - name: Get tag name
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }} if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
id: tags id: tags
@@ -226,7 +244,7 @@ jobs:
echo "TAGS=${tagstr}" echo "TAGS=${tagstr}"
echo "TAGS=${tagstr}" >> "${GITHUB_OUTPUT}" echo "TAGS=${tagstr}" >> "${GITHUB_OUTPUT}"
env: env:
REPO_NAME: ${{ steps.string_repo.outputs.lowercase }} REPO_NAME: ${{ steps.docker_repo.outputs.DOCKER_NWO }}
- name: Install latest rust - name: Install latest rust
run: | run: |
rustup toolchain install stable rustup toolchain install stable
@@ -272,7 +290,7 @@ jobs:
push: true push: true
file: Dockerfile file: Dockerfile
tags: ${{ steps.tags.outputs.TAGS }} tags: ${{ steps.tags.outputs.TAGS }}
build-args: VERSION=${{ steps.toml.outputs.version }}, REPO=${{ github.repository }}, OWNER=${{ github.repository_owner }} build-args: VERSION=${{ steps.toml.outputs.version }}, REPO=${{ github.repository }}, OWNER=${{ vars.DOCKER_USERNAME || github.repository_owner }}
env: env:
DOCKER_BUILDKIT: 1 DOCKER_BUILDKIT: 1
+2 -2
View File
@@ -143,5 +143,5 @@ jobs:
env: env:
DAYS: "100" DAYS: "100"
REPO_NAME: ${{ steps.string_repo.outputs.lowercase }} REPO_NAME: ${{ steps.string_repo.outputs.lowercase }}
OWNER: ${{ steps.string_user.outputs.lowercase }} OWNER: ${{ vars.DOCKER_USERNAME || steps.string_user.outputs.lowercase }}
TOKEN: ${{ secrets.DOCKER_PRUNE__TOKEN }} TOKEN: ${{ secrets.DOCKER_PRUNE_TOKEN }}
+2
View File
@@ -15,6 +15,8 @@
# Committing IntelliJ project files is a violation of intergalactic law # Committing IntelliJ project files is a violation of intergalactic law
.idea/ .idea/
# We prefer to keep .vscode files outside the repo
.vscode/
# MacOS # MacOS
.DS_Store .DS_Store
._.DS_Store ._.DS_Store
Generated
+49 -34
View File
@@ -198,9 +198,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]] [[package]]
name = "base64" name = "base64"
version = "0.21.0" version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a" checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
@@ -459,9 +459,9 @@ dependencies = [
[[package]] [[package]]
name = "delegate" name = "delegate"
version = "0.9.0" version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d358e0ec5c59a5e1603b933def447096886121660fc680dc1e64a0753981fe3c" checksum = "0ee5df75c70b95bd3aacc8e2fd098797692fb1d54121019c4de481e42f04c8a1"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -1251,6 +1251,15 @@ dependencies = [
"either", "either",
] ]
[[package]]
name = "itertools"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
dependencies = [
"either",
]
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.6" version = "1.0.6"
@@ -1408,9 +1417,10 @@ dependencies = [
[[package]] [[package]]
name = "neolink" name = "neolink"
version = "0.5.12" version = "0.5.14"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"base64 0.21.2",
"byte-slice-cast", "byte-slice-cast",
"clap", "clap",
"console-subscriber", "console-subscriber",
@@ -1421,14 +1431,16 @@ dependencies = [
"gstreamer-app", "gstreamer-app",
"gstreamer-rtsp", "gstreamer-rtsp",
"gstreamer-rtsp-server", "gstreamer-rtsp-server",
"heck",
"is_sorted", "is_sorted",
"itertools", "itertools 0.11.0",
"lazy_static", "lazy_static",
"log", "log",
"neolink_core", "neolink_core",
"regex", "regex",
"rumqttc", "rumqttc",
"serde", "serde",
"serde_json",
"time", "time",
"tokio", "tokio",
"tokio-stream", "tokio-stream",
@@ -1440,7 +1452,7 @@ dependencies = [
[[package]] [[package]]
name = "neolink_core" name = "neolink_core"
version = "0.5.12" version = "0.5.14"
dependencies = [ dependencies = [
"aes", "aes",
"assert_matches", "assert_matches",
@@ -1638,12 +1650,6 @@ version = "0.3.26"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160" checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"
[[package]]
name = "pollster"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7"
[[package]] [[package]]
name = "ppv-lite86" name = "ppv-lite86"
version = "0.2.17" version = "0.2.17"
@@ -1716,7 +1722,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4" checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"itertools", "itertools 0.10.5",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 1.0.109", "syn 1.0.109",
@@ -1857,17 +1863,17 @@ dependencies = [
[[package]] [[package]]
name = "rumqttc" name = "rumqttc"
version = "0.20.0" version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b616bf8b706c2a6235604f5d93f9578c37d0c6161e13898b68a1da4af2d812c" checksum = "f2433b134712bc17a6f85a35e06b901e6e8d0bb20b5367e1121e6fedc140c0ac"
dependencies = [ dependencies = [
"bytes", "bytes",
"flume", "flume",
"futures", "futures",
"log", "log",
"pollster",
"rustls-native-certs", "rustls-native-certs",
"rustls-pemfile", "rustls-pemfile",
"rustls-webpki 0.100.1",
"thiserror", "thiserror",
"tokio", "tokio",
"tokio-rustls", "tokio-rustls",
@@ -1889,14 +1895,14 @@ dependencies = [
[[package]] [[package]]
name = "rustls" name = "rustls"
version = "0.20.8" version = "0.21.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f" checksum = "79ea77c539259495ce8ca47f53e66ae0330a8819f67e23ac96ca02f50e7b7d36"
dependencies = [ dependencies = [
"log", "log",
"ring", "ring",
"rustls-webpki 0.101.1",
"sct", "sct",
"webpki",
] ]
[[package]] [[package]]
@@ -1917,7 +1923,27 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b" checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b"
dependencies = [ dependencies = [
"base64 0.21.0", "base64 0.21.2",
]
[[package]]
name = "rustls-webpki"
version = "0.100.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6207cd5ed3d8dca7816f8f3725513a34609c0c765bf652b8c3cb4cfd87db46b"
dependencies = [
"ring",
"untrusted",
]
[[package]]
name = "rustls-webpki"
version = "0.101.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15f36a6828982f422756984e47912a7a51dcbc2a197aa791158f8ca61cd8204e"
dependencies = [
"ring",
"untrusted",
] ]
[[package]] [[package]]
@@ -2319,13 +2345,12 @@ dependencies = [
[[package]] [[package]]
name = "tokio-rustls" name = "tokio-rustls"
version = "0.23.4" version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59" checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081"
dependencies = [ dependencies = [
"rustls", "rustls",
"tokio", "tokio",
"webpki",
] ]
[[package]] [[package]]
@@ -2737,16 +2762,6 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "webpki"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd"
dependencies = [
"ring",
"untrusted",
]
[[package]] [[package]]
name = "winapi" name = "winapi"
version = "0.2.8" version = "0.2.8"
+7 -4
View File
@@ -1,7 +1,7 @@
[package] [package]
name = "neolink" name = "neolink"
description = "A standards-compliant bridge to Reolink IP cameras" description = "A standards-compliant bridge to Reolink IP cameras"
version = "0.5.12" version = "0.5.14"
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"] authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
edition = "2018" edition = "2018"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
@@ -13,6 +13,7 @@ members = [
[dependencies] [dependencies]
anyhow = "1.0.70" anyhow = "1.0.70"
base64 = "0.21.2"
byte-slice-cast = "1.2.2" byte-slice-cast = "1.2.2"
clap = { version = "4.2.2", features = ["derive", "cargo"] } clap = { version = "4.2.2", features = ["derive", "cargo"] }
console-subscriber = "0.1.8" console-subscriber = "0.1.8"
@@ -23,14 +24,16 @@ gstreamer = "0.20.3"
gstreamer-app = "0.20.0" gstreamer-app = "0.20.0"
gstreamer-rtsp = "0.20.0" gstreamer-rtsp = "0.20.0"
gstreamer-rtsp-server = { version = "0.20.3", features = ["v1_16"] } gstreamer-rtsp-server = { version = "0.20.3", features = ["v1_16"] }
heck = "0.4.1"
is_sorted = "0.1.1" is_sorted = "0.1.1"
itertools = "0.10.5" itertools = "0.11.0"
lazy_static = "1.4.0" lazy_static = "1.4.0"
log = { version = "0.4.17", features = [ "release_max_level_debug" ] } log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
neolink_core = { path = "crates/core", version = "0.5.12" } neolink_core = { path = "crates/core", version = "0.5.14" }
regex = "1.7.3" regex = "1.7.3"
rumqttc = "0.20.0" rumqttc = "0.22.0"
serde = { version = "1.0.160", features = ["derive"] } serde = { version = "1.0.160", features = ["derive"] }
serde_json = "1.0.96"
time = "0.3.20" time = "0.3.20"
tokio = { version = "1.27.0", features = ["rt-multi-thread", "macros", "io-util", "tracing"] } tokio = { version = "1.27.0", features = ["rt-multi-thread", "macros", "io-util", "tracing"] }
tokio-stream = "0.1.12" tokio-stream = "0.1.12"
+2 -1
View File
@@ -54,7 +54,8 @@ RUN apt-get update && \
gstreamer1.0-x \ gstreamer1.0-x \
gstreamer1.0-plugins-base \ gstreamer1.0-plugins-base \
gstreamer1.0-plugins-good \ gstreamer1.0-plugins-good \
gstreamer1.0-plugins-bad && \ gstreamer1.0-plugins-bad \
gstreamer1.0-libav && \
apt-get clean -y && rm -rf /var/lib/apt/lists/* apt-get clean -y && rm -rf /var/lib/apt/lists/*
COPY --from=build \ COPY --from=build \
+58 -1
View File
@@ -154,6 +154,8 @@ Cellular cameras should select `"cellular"` which only enables `map` and
discovery = "cellular" discovery = "cellular"
``` ```
See the sample config file for more details.
### MQTT ### MQTT
To use mqtt you will to adjust your config file as such: To use mqtt you will to adjust your config file as such:
@@ -188,8 +190,10 @@ Control messages:
- `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light - `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light
detection detection
- `/control/reboot` Reboot the camera - `/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 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]` - `/control/pir [on|off]`
Status Messages: Status Messages:
@@ -199,13 +203,66 @@ Status Messages:
- `/status disconnected` Sent when the camera goes offline - `/status disconnected` Sent when the camera goes offline
- `/status/battery` Sent in reply to a `/query/battery` an XML encoded version - `/status/battery` Sent in reply to a `/query/battery` an XML encoded version
of the battery status 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 - `/status/pir` Sent in reply to a `/query/pir` an XML encoded version of the
pir status pir status
- `/status/motion` Contains the motion detection alarm status. `on` for motion and `off` for still
- `/status/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 Messages:
- `/query/battery` Request that the camera reports its battery level - `/query/battery` Request that the camera reports its battery level
- `/query/pir` Request that the camera reports its pir status - `/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 ### Pause
+2 -2
View File
@@ -1,7 +1,7 @@
[package] [package]
name = "neolink_core" name = "neolink_core"
description = "Core services and structure for Reolink IP cameras" description = "Core services and structure for Reolink IP cameras"
version = "0.5.12" version = "0.5.14"
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"] authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
edition = "2018" edition = "2018"
license = "AGPL-3.0-or-later" license = "AGPL-3.0-or-later"
@@ -13,7 +13,7 @@ cfb-mode = "0.8.2"
cookie-factory = "0.3.2" cookie-factory = "0.3.2"
crc32fast = "1.3.2" crc32fast = "1.3.2"
crossbeam-channel = "0.5.8" crossbeam-channel = "0.5.8"
delegate = "0.9.0" delegate = "0.10.0"
err-derive = "0.3.1" err-derive = "0.3.1"
futures = "0.3.28" futures = "0.3.28"
get_if_addrs = "0.5.3" get_if_addrs = "0.5.3"
+4 -2
View File
@@ -197,8 +197,10 @@ fn bc_modern_msg<'a>(
} }
fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> { fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> {
let (buf, _magic) = let (buf, _magic) = error_context(
error_context("Magic invalid", verify(le_u32, |x| *x == MAGIC_HEADER))(buf)?; "Magic invalid",
verify(le_u32, |x| *x == MAGIC_HEADER || *x == MAGIC_HEADER_REV),
)(buf)?;
let (buf, msg_id) = error_context("MsgID missing", le_u32)(buf)?; let (buf, msg_id) = error_context("MsgID missing", le_u32)(buf)?;
let (buf, body_len) = error_context("BodyLen 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)?; let (buf, channel_id) = error_context("ChannelID missing", le_u8)(buf)?;
+15 -1
View File
@@ -3,7 +3,11 @@ use crate::Credentials;
pub use super::xml::{BcPayloads, BcXml, Extension}; pub use super::xml::{BcPayloads, BcXml, Extension};
use std::collections::HashSet; use std::collections::HashSet;
pub(super) const MAGIC_HEADER: u32 = 0xabcdef0; pub(super) const MAGIC_HEADER: u32 = 0x0abcdef0;
/// Sometimes will get the BE magic header even though all other numbers are LE?
/// Seems to happens with certain messages like snap that produce jpegs, so perhaps it
/// it is meant to be a hint as to the endianess of the binary payload
pub(super) const MAGIC_HEADER_REV: u32 = 0x0fedcba0;
/// Login messages have this ID /// Login messages have this ID
pub const MSG_ID_LOGIN: u32 = 1; pub const MSG_ID_LOGIN: u32 = 1;
@@ -19,6 +23,8 @@ pub const MSG_ID_TALKABILITY: u32 = 10;
pub const MSG_ID_TALKRESET: u32 = 11; pub const MSG_ID_TALKRESET: u32 = 11;
/// PtzControl messages have this ID /// PtzControl messages have this ID
pub const MSG_ID_PTZ_CONTROL: u32 = 18; 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 /// Reboot messages have this ID
pub const MSG_ID_REBOOT: u32 = 23; pub const MSG_ID_REBOOT: u32 = 23;
/// Request motion detection messages /// Request motion detection messages
@@ -31,10 +37,14 @@ pub const MSG_ID_VERSION: u32 = 80;
pub const MSG_ID_PING: u32 = 93; pub const MSG_ID_PING: u32 = 93;
/// General system info messages have this ID /// General system info messages have this ID
pub const MSG_ID_GET_GENERAL: u32 = 104; 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 /// Used to get the abilities of a user
pub const MSG_ID_ABILITY_INFO: u32 = 151; pub const MSG_ID_ABILITY_INFO: u32 = 151;
/// Setting general system info (clock mostly) messages have this ID /// Setting general system info (clock mostly) messages have this ID
pub const MSG_ID_SET_GENERAL: u32 = 105; pub const MSG_ID_SET_GENERAL: u32 = 105;
/// Get the available PTZ position presets
pub const MSG_ID_GET_PTZ_PRESET: u32 = 190;
/// Will send the talk config for talk back data to follow this msg /// Will send the talk config for talk back data to follow this msg
pub const MSG_ID_TALKCONFIG: u32 = 201; pub const MSG_ID_TALKCONFIG: u32 = 201;
/// Used to send talk back binary data /// Used to send talk back binary data
@@ -53,6 +63,10 @@ pub const MSG_ID_UDP_KEEP_ALIVE: u32 = 234;
pub const MSG_ID_BATTERY_INFO_LIST: u32 = 252; pub const MSG_ID_BATTERY_INFO_LIST: u32 = 252;
/// Battery message initiaed by the client /// Battery message initiaed by the client
pub const MSG_ID_BATTERY_INFO: u32 = 253; 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 /// An empty password in legacy format
pub const EMPTY_LEGACY_PASSWORD: &str = pub const EMPTY_LEGACY_PASSWORD: &str =
+123 -1
View File
@@ -76,6 +76,15 @@ pub struct BcXml {
/// Sent to move the camera /// Sent to move the camera
#[yaserde(rename = "PtzControl")] #[yaserde(rename = "PtzControl")]
pub ptz_control: Option<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 /// Recieved on login/low battery events
#[yaserde(rename = "BatteryList")] #[yaserde(rename = "BatteryList")]
pub battery_list: Option<BatteryList>, pub battery_list: Option<BatteryList>,
@@ -85,6 +94,12 @@ pub struct BcXml {
/// Recieved on request for a users persmissions/capabilitoes /// Recieved on request for a users persmissions/capabilitoes
#[yaserde(rename = "AbilityInfo")] #[yaserde(rename = "AbilityInfo")]
pub ability_info: Option<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>,
} }
impl BcXml { impl BcXml {
@@ -325,6 +340,42 @@ pub struct LedState {
pub light_state: String, 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 /// rfAlarmCfg xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
pub struct RfAlarmCfg { pub struct RfAlarmCfg {
@@ -519,7 +570,40 @@ pub struct PtzControl {
pub channel_id: u8, pub channel_id: u8,
/// The amount of movement to perform /// The amount of movement to perform
pub speed: f32, pub speed: f32,
/// The direction to transverse. Known directions: "right" /// 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"`
pub command: String, pub command: String,
} }
@@ -614,6 +698,44 @@ pub struct AbilityInfoSubModule {
pub ability_value: String, pub ability_value: String,
} }
/// The Link Type contains the type of connection present
#[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>,
}
/// Convience function to return the xml version used throughout the library /// Convience function to return the xml version used throughout the library
pub fn xml_ver() -> String { pub fn xml_ver() -> String {
"1.1".to_string() "1.1".to_string()
+2
View File
@@ -16,6 +16,7 @@ mod battery;
mod connection; mod connection;
mod credentials; mod credentials;
mod errors; mod errors;
mod floodlight_status;
mod keepalive; mod keepalive;
mod ledstate; mod ledstate;
mod login; mod login;
@@ -26,6 +27,7 @@ mod pirstate;
mod ptz; mod ptz;
mod reboot; mod reboot;
mod resolution; mod resolution;
mod snap;
mod stream; mod stream;
mod talk; mod talk;
mod time; mod time;
+1 -1
View File
@@ -7,7 +7,7 @@ impl BcCamera {
pub async fn get_abilityinfo(&self) -> Result<AbilityInfo> { pub async fn get_abilityinfo(&self) -> Result<AbilityInfo> {
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(msg_num).await?; let mut sub_get = connection.subscribe(MSG_ID_ABILITY_INFO, msg_num).await?;
let get = Bc { let get = Bc {
meta: BcMeta { meta: BcMeta {
msg_id: MSG_ID_ABILITY_INFO, msg_id: MSG_ID_ABILITY_INFO,
+45 -43
View File
@@ -19,58 +19,60 @@ impl BcCamera {
let connection = self.get_connection(); let connection = self.get_connection();
connection connection
.handle_msg(MSG_ID_BATTERY_INFO_LIST, move |bc| { .handle_msg(MSG_ID_BATTERY_INFO_LIST, move |bc| {
if let Bc { Box::pin(async move {
body: if let Bc {
BcBody::ModernMsg(ModernMsg { body:
payload: BcBody::ModernMsg(ModernMsg {
Some(BcPayloads::BcXml(BcXml { payload:
battery_list: Some(battery_list), Some(BcPayloads::BcXml(BcXml {
.. battery_list: Some(battery_list),
})), ..
.. })),
}), ..
.. }),
} = bc ..
{ } = bc
for battery in battery_list.battery_info.iter() { {
match format { for battery in battery_list.battery_info.iter() {
PrintFormat::None => {} match format {
PrintFormat::Human => { PrintFormat::None => {}
println!( PrintFormat::Human => {
"==Battery==\n\ println!(
"==Battery==\n\
Charge: {}%,\n\ Charge: {}%,\n\
Temperature: {}°C,\n\ Temperature: {}°C,\n\
LowPower: {},\n\ LowPower: {},\n\
Adapter: {},\n\ Adapter: {},\n\
ChargeStatus: {},\n\ ChargeStatus: {},\n\
", ",
battery.battery_percent, battery.battery_percent,
battery.temperature, battery.temperature,
if battery.low_power == 1 { if battery.low_power == 1 {
"true" "true"
} else { } else {
"false" "false"
}, },
battery.adapter_status, battery.adapter_status,
battery.charge_status, battery.charge_status,
); );
} }
PrintFormat::Xml => { PrintFormat::Xml => {
let bat_ser = String::from_utf8( let bat_ser = String::from_utf8(
yaserde::ser::serialize_with_writer( yaserde::ser::serialize_with_writer(
battery, battery,
vec![], vec![],
&Default::default(), &Default::default(),
)
.expect("Should Ser the struct"),
) )
.expect("Should Ser the struct"), .expect("Should be UTF8");
) println!("{}", bat_ser);
.expect("Should be UTF8"); }
println!("{}", bat_ser);
} }
} }
} }
} Option::<Bc>::None
None })
}) })
.await?; .await?;
Ok(()) Ok(())
@@ -81,7 +83,7 @@ impl BcCamera {
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub = connection.subscribe(msg_num).await?; let mut sub = connection.subscribe(MSG_ID_BATTERY_INFO, msg_num).await?;
let msg = Bc { let msg = Bc {
meta: BcMeta { meta: BcMeta {
+119 -65
View File
@@ -1,10 +1,12 @@
use super::BcSubscription; use super::BcSubscription;
use crate::{bc::model::*, Error, Result}; use crate::{bc::model::*, Error, Result};
use futures::future::BoxFuture;
use futures::sink::{Sink, SinkExt}; use futures::sink::{Sink, SinkExt};
use futures::stream::{Stream, StreamExt}; use futures::stream::{Stream, StreamExt};
use log::*; use log::*;
use std::collections::btree_map::Entry; use std::collections::btree_map::Entry;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::sync::Arc;
use tokio::sync::mpsc::{channel, Sender}; use tokio::sync::mpsc::{channel, Sender};
use tokio::task::yield_now; use tokio::task::yield_now;
use tokio_stream::wrappers::ReceiverStream; use tokio_stream::wrappers::ReceiverStream;
@@ -12,13 +14,14 @@ use tokio_util::sync::PollSender;
use tokio::{sync::RwLock, task::JoinSet}; use tokio::{sync::RwLock, task::JoinSet};
type MsgHandler = Box<dyn Fn(&Bc) -> Option<Bc> + Send + Sync>; type MsgHandler = dyn 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a, Option<Bc>>;
#[derive(Default)] #[derive(Default)]
struct Subscriber { struct Subscriber {
/// Subscribers based on their Num /// Subscribers based on their ID and their num
num: BTreeMap<u16, Sender<Result<Bc>>>, num: BTreeMap<u32, BTreeMap<Option<u16>, Sender<Result<Bc>>>>,
/// Subscribers based on their ID /// Subscribers based on their ID
id: BTreeMap<u32, MsgHandler>, id: BTreeMap<u32, Arc<MsgHandler>>,
} }
pub(crate) type BcConnSink = Box<dyn Sink<Bc, Error = Error> + Send + Sync + Unpin>; pub(crate) type BcConnSink = Box<dyn Sink<Bc, Error = Error> + Send + Sync + Unpin>;
@@ -82,12 +85,12 @@ impl BcConnection {
Ok(()) Ok(())
} }
pub async fn subscribe(&self, msg_num: u16) -> Result<BcSubscription> { pub async fn subscribe(&self, msg_id: u32, msg_num: u16) -> Result<BcSubscription> {
let (tx, rx) = channel(100); let (tx, rx) = channel(100);
self.poll_commander self.poll_commander
.send(PollCommand::AddSubscriber(msg_num, tx)) .send(PollCommand::AddSubscriber(msg_id, Some(msg_num), tx))
.await?; .await?;
Ok(BcSubscription::new(rx, msg_num as u32, self)) Ok(BcSubscription::new(rx, Some(msg_num as u32), self))
} }
/// Some messages are initiated by the camera. This creates a handler for them /// Some messages are initiated by the camera. This creates a handler for them
@@ -95,10 +98,10 @@ impl BcConnection {
/// and return either None or Some(Bc) reply /// and return either None or Some(Bc) reply
pub async fn handle_msg<T>(&self, msg_id: u32, handler: T) -> Result<()> pub async fn handle_msg<T>(&self, msg_id: u32, handler: T) -> Result<()>
where where
T: Fn(&Bc) -> Option<Bc> + Send + Sync + 'static, T: 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a, Option<Bc>>,
{ {
self.poll_commander self.poll_commander
.send(PollCommand::AddHandler(msg_id, Box::new(handler))) .send(PollCommand::AddHandler(msg_id, Arc::new(handler)))
.await?; .await?;
Ok(()) Ok(())
} }
@@ -112,6 +115,21 @@ impl BcConnection {
Ok(()) 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<()> { pub(crate) async fn join(&self) -> Result<()> {
let mut locked_threads = self.rx_thread.write().await; let mut locked_threads = self.rx_thread.write().await;
while let Some(res) = locked_threads.join_next().await { while let Some(res) = locked_threads.join_next().await {
@@ -133,9 +151,9 @@ impl BcConnection {
enum PollCommand { enum PollCommand {
Bc(Box<Result<Bc>>), Bc(Box<Result<Bc>>),
AddHandler(u32, MsgHandler), AddHandler(u32, Arc<MsgHandler>),
RemoveHandler(u32), RemoveHandler(u32),
AddSubscriber(u16, Sender<Result<Bc>>), AddSubscriber(u32, Option<u16>, Sender<Result<Bc>>),
} }
struct Poller { struct Poller {
@@ -149,66 +167,96 @@ impl Poller {
while let Some(command) = self.reciever.next().await { while let Some(command) = self.reciever.next().await {
yield_now().await; yield_now().await;
match command { match command {
PollCommand::Bc(boxed_response) => match *boxed_response { PollCommand::Bc(boxed_response) => {
Ok(response) => { match *boxed_response {
let msg_num = response.meta.msg_num; Ok(response) => {
let msg_id = response.meta.msg_id; let msg_num = response.meta.msg_num;
let msg_id = response.meta.msg_id;
let mut remove_it_num = false; match (
match ( self.subscribers.id.get(&msg_id),
self.subscribers.id.get(&msg_id), self.subscribers.num.get_mut(&msg_id),
self.subscribers.num.get(&msg_num), ) {
) { (Some(occ), _) => {
(Some(occ), _) => { if let Some(reply) = occ(&response).await {
if let Some(reply) = occ(&response) { assert!(reply.meta.msg_num == response.meta.msg_num);
assert!(reply.meta.msg_num == response.meta.msg_num); self.sink.send(Ok(reply)).await?;
self.sink.send(Ok(reply)).await?; }
} }
} (None, Some(occ)) => {
(None, Some(occ)) => { let sender = if let Some(sender) =
if occ.capacity() == 0 { occ.get(&Some(msg_num)).filter(|a| !a.is_closed()).cloned()
warn!("Reaching limit of channel"); {
warn!( // Connection with id exists and is not closed
"Remaining: {} of {} message space for {} (ID: {})", Some(sender)
occ.capacity(), } else if let Some(sender) = occ.get(&None).cloned() {
occ.max_capacity(), // Upgrade a None to a known MsgID
&msg_num, occ.remove(&None);
&msg_id occ.insert(Some(msg_num), sender.clone());
); Some(sender)
} else { } else if occ
trace!( .get(&Some(msg_num))
"Remaining: {} of {} message space for {} (ID: {})", .map(|a| a.is_closed())
occ.capacity(), .unwrap_or(false)
occ.max_capacity(), {
&msg_num, // Connection is closed and there is no None to replace it
&msg_id // Remove it for cleanup and report no sender
occ.remove(&Some(msg_num));
None
} else {
None
};
if let Some(sender) = sender {
if sender.capacity() == 0 {
warn!("Reaching limit of channel");
warn!(
"Remaining: {} of {} message space for {} (ID: {})",
sender.capacity(),
sender.max_capacity(),
&msg_num,
&msg_id
);
} else {
trace!(
"Remaining: {} of {} message space for {} (ID: {})",
sender.capacity(),
sender.max_capacity(),
&msg_num,
&msg_id
);
}
if sender.send(Ok(response)).await.is_err() {
occ.remove(&Some(msg_num));
}
} else {
debug!(
"Ignoring uninteresting message id {} (number: {})",
msg_id, msg_num
);
trace!("Contents: {:?}", response);
}
}
(None, None) => {
debug!(
"Ignoring uninteresting message id {} (number: {})",
msg_id, msg_num
); );
trace!("Contents: {:?}", response);
} }
if occ.send(Ok(response)).await.is_err() {
remove_it_num = true;
}
}
(None, None) => {
debug!(
"Ignoring uninteresting message id {} (number: {})",
msg_id, msg_num
);
trace!("Contents: {:?}", response);
} }
} }
if remove_it_num { Err(e) => {
self.subscribers.num.remove(&msg_num); for sub in self.subscribers.num.values() {
for sender in sub.values() {
let _ = sender.send(Err(e.clone())).await;
}
}
self.subscribers.num.clear();
self.subscribers.id.clear();
return Err(e);
} }
} }
Err(e) => { }
for sub in self.subscribers.num.values() {
let _ = sub.send(Err(e.clone())).await;
}
self.subscribers.num.clear();
self.subscribers.id.clear();
return Err(e);
}
},
PollCommand::AddHandler(msg_id, handler) => { PollCommand::AddHandler(msg_id, handler) => {
match self.subscribers.id.entry(msg_id) { match self.subscribers.id.entry(msg_id) {
Entry::Vacant(vac_entry) => { Entry::Vacant(vac_entry) => {
@@ -222,8 +270,14 @@ impl Poller {
PollCommand::RemoveHandler(msg_id) => { PollCommand::RemoveHandler(msg_id) => {
self.subscribers.id.remove(&msg_id); self.subscribers.id.remove(&msg_id);
} }
PollCommand::AddSubscriber(msg_num, tx) => { PollCommand::AddSubscriber(msg_id, msg_num, tx) => {
match self.subscribers.num.entry(msg_num) { match self
.subscribers
.num
.entry(msg_id)
.or_default()
.entry(msg_num)
{
Entry::Vacant(vac_entry) => { Entry::Vacant(vac_entry) => {
vac_entry.insert(tx); vac_entry.insert(tx);
} }
@@ -12,7 +12,7 @@ use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
pub struct BcSubscription<'a> { pub struct BcSubscription<'a> {
rx: ReceiverStream<Result<Bc>>, rx: ReceiverStream<Result<Bc>>,
msg_num: u32, msg_num: Option<u32>,
conn: &'a BcConnection, conn: &'a BcConnection,
} }
@@ -89,7 +89,7 @@ pub type BcMediaStream<'b> = FramedRead<Compat<IntoAsyncRead<BcPayloadStream<'b>
impl<'a> BcSubscription<'a> { impl<'a> BcSubscription<'a> {
pub fn new( pub fn new(
rx: Receiver<Result<Bc>>, rx: Receiver<Result<Bc>>,
msg_num: u32, msg_num: Option<u32>,
conn: &'a BcConnection, conn: &'a BcConnection,
) -> BcSubscription<'a> { ) -> BcSubscription<'a> {
BcSubscription { BcSubscription {
@@ -100,7 +100,11 @@ impl<'a> BcSubscription<'a> {
} }
pub async fn send(&self, bc: Bc) -> Result<()> { pub async fn send(&self, bc: Bc) -> Result<()> {
assert!(bc.meta.msg_num as u32 == self.msg_num); if let Some(msg_num) = self.msg_num {
assert!(bc.meta.msg_num as u32 == msg_num);
} else {
log::debug!("Sending message before msg_num has been aquired");
}
self.conn.send(bc).await?; self.conn.send(bc).await?;
Ok(()) Ok(())
} }
@@ -108,7 +112,12 @@ impl<'a> BcSubscription<'a> {
pub async fn recv(&mut self) -> Result<Bc> { pub async fn recv(&mut self) -> Result<Bc> {
let bc = self.rx.next().await.ok_or(Error::DroppedSubscriber)?; let bc = self.rx.next().await.ok_or(Error::DroppedSubscriber)?;
if let Ok(bc) = &bc { if let Ok(bc) = &bc {
assert!(bc.meta.msg_num as u32 == self.msg_num); if let Some(msg_num) = self.msg_num {
assert!(bc.meta.msg_num as u32 == msg_num);
} else {
// Leaning number now
self.msg_num = Some(bc.meta.msg_num as u32);
}
} }
bc bc
} }
@@ -175,7 +175,7 @@ impl Discoverer {
Ok(rx) Ok(rx)
} else { } else {
Err(Error::SimultaneousSubscription { Err(Error::SimultaneousSubscription {
msg_num: (tid as u16), msg_num: Some(tid as u16),
}) })
} }
} }
+2 -2
View File
@@ -96,10 +96,10 @@ pub enum Error {
GenError(#[error(source)] std::sync::Arc<cookie_factory::GenError>), GenError(#[error(source)] std::sync::Arc<cookie_factory::GenError>),
/// Raised when a connection is subscrbed to more than once for msg_num /// Raised when a connection is subscrbed to more than once for msg_num
#[error(display = "Simultaneous subscription, {}", _0)] #[error(display = "Simultaneous subscription, {:?}", _0)]
SimultaneousSubscription { SimultaneousSubscription {
/// The message number that was subscribed to /// The message number that was subscribed to
msg_num: u16, msg_num: Option<u16>,
}, },
/// Raised when a connection is subscrbed to more than once for msg_id /// Raised when a connection is subscrbed to more than once for msg_id
@@ -0,0 +1,103 @@
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(())
}
}
}
+14 -12
View File
@@ -10,18 +10,20 @@ impl BcCamera {
let connection = self.get_connection(); let connection = self.get_connection();
connection connection
.handle_msg(MSG_ID_UDP_KEEP_ALIVE, |bc| { .handle_msg(MSG_ID_UDP_KEEP_ALIVE, |bc| {
Some(Bc { Box::pin(async move {
meta: BcMeta { Some(Bc {
msg_id: MSG_ID_UDP_KEEP_ALIVE, meta: BcMeta {
channel_id: bc.meta.channel_id, msg_id: MSG_ID_UDP_KEEP_ALIVE,
msg_num: bc.meta.msg_num, channel_id: bc.meta.channel_id,
stream_type: bc.meta.stream_type, msg_num: bc.meta.msg_num,
response_code: 200, stream_type: bc.meta.stream_type,
class: 0x6414, response_code: 200,
}, class: 0x6414,
body: BcBody::ModernMsg(ModernMsg { },
..Default::default() body: BcBody::ModernMsg(ModernMsg {
}), ..Default::default()
}),
})
}) })
}) })
.await?; .await?;
+19 -12
View File
@@ -7,7 +7,7 @@ impl BcCamera {
self.has_ability_ro("ledState").await?; self.has_ability_ro("ledState").await?;
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(msg_num).await?; let mut sub_get = connection.subscribe(MSG_ID_GET_LED_STATUS, msg_num).await?;
let get = Bc { let get = Bc {
meta: BcMeta { meta: BcMeta {
msg_id: MSG_ID_GET_LED_STATUS, msg_id: MSG_ID_GET_LED_STATUS,
@@ -56,7 +56,7 @@ impl BcCamera {
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_set = connection.subscribe(msg_num).await?; let mut sub_set = connection.subscribe(MSG_ID_SET_LED_STATUS, msg_num).await?;
// led_version is a field recieved from the camera but not sent // 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 // we set to None to ensure we don't send it to the camera
@@ -83,18 +83,25 @@ impl BcCamera {
}; };
sub_set.send(get).await?; sub_set.send(get).await?;
let msg = sub_set.recv().await?; if let Ok(reply) =
tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
if let BcMeta {
response_code: 200, ..
} = msg.meta
{ {
Ok(()) let msg = reply?;
if let BcMeta {
response_code: 200, ..
} = msg.meta
{
Ok(())
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "The camera did not except the LEDState xml",
})
}
} else { } else {
Err(Error::UnintelligibleReply { // Some cameras seem to just not send a reply on success, so after 500ms we return Ok
reply: std::sync::Arc::new(Box::new(msg)), Ok(())
why: "The camera did not except the LEDState xml",
})
} }
} }
+50
View File
@@ -0,0 +1,50 @@
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",
})
}
}
}
+1 -1
View File
@@ -37,7 +37,7 @@ impl BcCamera {
let credentials = self.get_credentials(); let credentials = self.get_credentials();
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_login = connection.subscribe(msg_num).await?; let mut sub_login = connection.subscribe(MSG_ID_LOGIN, msg_num).await?;
// Login flow is: Send legacy login message, expect back a modern message with Encryption // 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 // details. Then, re-send the login as a modern login message. Expect back a device info
+1 -1
View File
@@ -9,7 +9,7 @@ impl BcCamera {
let credentials = self.get_credentials(); let credentials = self.get_credentials();
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let sub_logout = connection.subscribe(msg_num).await?; let sub_logout = connection.subscribe(MSG_ID_LOGOUT, msg_num).await?;
let username = credentials.username.clone(); let username = credentials.username.clone();
let password = credentials.password.as_ref().cloned().unwrap_or_default(); let password = credentials.password.as_ref().cloned().unwrap_or_default();
+3 -3
View File
@@ -167,7 +167,7 @@ impl BcCamera {
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub = connection.subscribe(msg_num).await?; let mut sub = connection.subscribe(MSG_ID_MOTION_REQUEST, msg_num).await?;
let msg = Bc { let msg = Bc {
meta: BcMeta { meta: BcMeta {
msg_id: MSG_ID_MOTION_REQUEST, msg_id: MSG_ID_MOTION_REQUEST,
@@ -202,7 +202,7 @@ impl BcCamera {
/// This returns a data structure which can be used to /// This returns a data structure which can be used to
/// query motion events /// query motion events
pub async fn listen_on_motion(&self) -> Result<MotionData> { pub async fn listen_on_motion(&self) -> Result<MotionData> {
let msg_num = self.start_motion_query().await?; self.start_motion_query().await?;
let connection = self.get_connection(); let connection = self.get_connection();
@@ -213,7 +213,7 @@ impl BcCamera {
let mut set = JoinSet::new(); let mut set = JoinSet::new();
let channel_id = self.channel_id; let channel_id = self.channel_id;
set.spawn(async move { set.spawn(async move {
let mut sub = connection.subscribe(msg_num).await?; let mut sub = connection.subscribe_to_id(MSG_ID_MOTION).await?;
loop { loop {
tokio::task::yield_now().await; tokio::task::yield_now().await;
+1 -1
View File
@@ -7,7 +7,7 @@ impl BcCamera {
pub async fn ping(&self) -> Result<()> { pub async fn ping(&self) -> Result<()> {
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_ping = connection.subscribe(msg_num).await?; let mut sub_ping = connection.subscribe(MSG_ID_PING, msg_num).await?;
let ping = Bc { let ping = Bc {
meta: BcMeta { meta: BcMeta {
+24 -15
View File
@@ -12,7 +12,7 @@ impl BcCamera {
loop { loop {
retry_interval.tick().await; retry_interval.tick().await;
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(msg_num).await?; let mut sub_get = connection.subscribe(MSG_ID_GET_PIR_ALARM, msg_num).await?;
let get = Bc { let get = Bc {
meta: BcMeta { meta: BcMeta {
msg_id: MSG_ID_GET_PIR_ALARM, msg_id: MSG_ID_GET_PIR_ALARM,
@@ -70,7 +70,9 @@ impl BcCamera {
self.has_ability_rw("rfAlarm").await?; self.has_ability_rw("rfAlarm").await?;
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_set = connection.subscribe(msg_num).await?; let mut sub_set = connection
.subscribe(MSG_ID_START_PIR_ALARM, msg_num)
.await?;
let get = Bc { let get = Bc {
meta: BcMeta { meta: BcMeta {
@@ -94,21 +96,28 @@ impl BcCamera {
}; };
sub_set.send(get).await?; sub_set.send(get).await?;
let msg = sub_set.recv().await?; if let Ok(reply) =
if msg.meta.response_code != 200 { tokio::time::timeout(tokio::time::Duration::from_micros(500), sub_set.recv()).await
return Err(Error::CameraServiceUnavaliable);
}
if let BcMeta {
response_code: 200, ..
} = msg.meta
{ {
Ok(()) let msg = reply?;
if msg.meta.response_code != 200 {
return Err(Error::CameraServiceUnavaliable);
}
if let BcMeta {
response_code: 200, ..
} = msg.meta
{
Ok(())
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "The camera did not except the RfAlarmCfg xml",
})
}
} else { } else {
Err(Error::UnintelligibleReply { // Some cameras seem to just not send a reply on success, so after 500ms we return Ok
reply: std::sync::Arc::new(Box::new(msg)), Ok(())
why: "The camera did not except the RfAlarmCfg xml",
})
} }
} }
+163 -1
View File
@@ -25,7 +25,7 @@ impl BcCamera {
self.has_ability_rw("control").await?; self.has_ability_rw("control").await?;
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_set = connection.subscribe(msg_num).await?; let mut sub_set = connection.subscribe(MSG_ID_PTZ_CONTROL, msg_num).await?;
let direction_str = match direction { let direction_str = match direction {
Direction::Up => "up", Direction::Up => "up",
@@ -82,4 +82,166 @@ 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",
})
}
}
} }
+1 -1
View File
@@ -7,7 +7,7 @@ impl BcCamera {
self.has_ability_rw("reboot").await?; self.has_ability_rw("reboot").await?;
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub = connection.subscribe(msg_num).await?; let mut sub = connection.subscribe(MSG_ID_REBOOT, msg_num).await?;
let msg = Bc { let msg = Bc {
meta: BcMeta { meta: BcMeta {
+152
View File
@@ -0,0 +1,152 @@
// use futures::{StreamExt, TryStreamExt};
use super::{BcCamera, Error, Result};
use crate::bc::{model::*, xml::*};
impl BcCamera {
/// Get the snapshot image
pub async fn get_snapshot(&self) -> Result<Vec<u8>> {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(MSG_ID_SNAP, msg_num).await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_SNAP,
channel_id: self.channel_id,
msg_num,
response_code: 0,
stream_type: 0,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
extension: Some(Extension {
channel_id: Some(self.channel_id),
..Default::default()
}),
payload: Some(BcPayloads::BcXml(BcXml {
snap: Some(Snap {
channel_id: self.channel_id,
logic_channel: Some(self.channel_id),
time: 0,
full_frame: Some(0),
stream_type: Some("main".to_string()),
..Default::default()
}),
..Default::default()
})),
}),
};
sub_get.send(get).await?;
let msg = sub_get.recv().await?;
if msg.meta.response_code != 200 {
return Err(Error::CameraServiceUnavaliable);
}
if let BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
snap:
Some(Snap {
file_name: Some(filename),
picture_size: Some(expected_size),
..
}),
..
})),
..
}) = msg.body
{
log::trace!("Got snap XML {} with size {}", filename, expected_size);
// Messages are now sent on ID 109 but not with the same message ID
// preumably because the camera considers it to be a new message rather
// than a reply
//
// This means we need to listen for the next 109 grab the message num and
// subscribe to it. This is what `subscribe_to_next` is for
let mut sub_get = connection.subscribe_to_id(MSG_ID_SNAP).await?;
let expected_size = expected_size as usize;
let mut result: Vec<_> = vec![];
log::trace!("Waiting for packets on {}", msg_num);
let mut msg = sub_get.recv().await?;
while msg.meta.response_code == 200 {
// sends 200 while more is to come
// 201 when finished
if let BcBody::ModernMsg(ModernMsg {
extension:
Some(Extension {
binary_data: Some(1),
..
}),
payload: Some(BcPayloads::Binary(data)),
}) = msg.body
{
result.extend_from_slice(&data);
} else {
return Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "Expected binary data but got something else",
});
}
log::trace!(
"Got packet size is now {} of {}",
result.len(),
expected_size
);
msg = sub_get.recv().await?;
}
if msg.meta.response_code == 201 {
// 201 means all binary data sent
if let BcBody::ModernMsg(ModernMsg {
extension:
Some(Extension {
binary_data: Some(1),
..
}),
payload,
}) = msg.body
{
if let Some(BcPayloads::Binary(data)) = payload {
// Add last data if present (may be zero if preveious packet contained it)
result.extend_from_slice(&data);
}
log::trace!(
"Got all packets size is now {} of {}",
result.len(),
expected_size
);
if result.len() != expected_size {
log::warn!("Snap did not recieve expected number of byes");
}
} else {
return Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "Expected binary data but got something else",
});
}
} else {
// anything else is an error
return Err(Error::CameraServiceUnavaliable);
}
// let binary_stream = sub_get.payload_stream();
// let result: Vec<_>= binary_stream
// .map_ok(|i| tokio_stream::iter(i).map(Result::Ok))
// .try_flatten()
// .take(expected_size)
// .try_collect()
// .await?;
log::trace!("Snapshot recieved: {} of {}", result.len(), expected_size);
Ok(result)
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "Expected Snap xml but it was not recieved",
})
}
}
}
+5 -4
View File
@@ -111,7 +111,7 @@ impl BcCamera {
let handle = task::spawn(async move { let handle = task::spawn(async move {
tokio::task::yield_now().await; tokio::task::yield_now().await;
let mut sub_video = connection.subscribe(msg_num).await?; let mut sub_video = connection.subscribe(MSG_ID_VIDEO, msg_num).await?;
// On an E1 and swann cameras: // On an E1 and swann cameras:
// - mainStream always has a value of 0 // - mainStream always has a value of 0
@@ -224,13 +224,14 @@ impl BcCamera {
}, },
); );
// debug!("Stream: Send Stop"); // debug!("Stream: Send Stop");
sub_video.send(stop_video).await?; let mut sub_stop = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?;
sub_stop.send(stop_video).await?;
// debug!("Stream: Sent Stop"); // debug!("Stream: Sent Stop");
tokio::select! { tokio::select! {
v = async { v = async {
loop { loop {
let msg = sub_video.recv().await?; let msg = sub_stop.recv().await?;
if let BcMeta { if let BcMeta {
response_code: 200, response_code: 200,
msg_id: MSG_ID_VIDEO_STOP, msg_id: MSG_ID_VIDEO_STOP,
@@ -268,7 +269,7 @@ impl BcCamera {
} }
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_video = connection.subscribe(msg_num).await?; let mut sub_video = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?;
// On an E1 and swann cameras: // On an E1 and swann cameras:
// - mainStream always has a value of 0 // - mainStream always has a value of 0
+6 -6
View File
@@ -17,7 +17,7 @@ impl BcCamera {
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub = connection.subscribe(msg_num).await?; let mut sub = connection.subscribe(MSG_ID_TALKRESET, msg_num).await?;
let msg = Bc { let msg = Bc {
meta: BcMeta { meta: BcMeta {
@@ -60,7 +60,7 @@ impl BcCamera {
pub async fn talk_ability(&self) -> Result<TalkAbility> { pub async fn talk_ability(&self) -> Result<TalkAbility> {
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(msg_num).await?; let mut sub_get = connection.subscribe(MSG_ID_TALKABILITY, msg_num).await?;
let get = Bc { let get = Bc {
meta: BcMeta { meta: BcMeta {
msg_id: MSG_ID_TALKABILITY, msg_id: MSG_ID_TALKABILITY,
@@ -120,7 +120,7 @@ impl BcCamera {
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub = connection.subscribe(msg_num).await?; let mut sub = connection.subscribe(MSG_ID_TALKCONFIG, msg_num).await?;
if &talk_config.audio_config.audio_type != "adpcm" { if &talk_config.audio_config.audio_type != "adpcm" {
return Err(Error::UnknownTalkEncoding); return Err(Error::UnknownTalkEncoding);
@@ -182,7 +182,7 @@ impl BcCamera {
let full_block_size = block_size + 4; // Block size + predictor state let full_block_size = block_size + 4; // Block size + predictor state
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let sub = connection.subscribe(msg_num).await?; let sub = connection.subscribe(MSG_ID_TALK, msg_num).await?;
const BLOCK_PER_PAYLOAD: usize = 4; const BLOCK_PER_PAYLOAD: usize = 4;
const BLOCK_HEADER_SIZE: usize = 4; const BLOCK_HEADER_SIZE: usize = 4;
@@ -261,7 +261,7 @@ impl BcCamera {
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub = connection.subscribe(msg_num).await?; let mut sub = connection.subscribe(MSG_ID_TALKCONFIG, msg_num).await?;
if &talk_config.audio_config.audio_type != "adpcm" { if &talk_config.audio_config.audio_type != "adpcm" {
return Err(Error::UnknownTalkEncoding); return Err(Error::UnknownTalkEncoding);
@@ -323,7 +323,7 @@ impl BcCamera {
let full_block_size = block_size + 4; // Block size + predictor state let full_block_size = block_size + 4; // Block size + predictor state
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let sub = connection.subscribe(msg_num).await?; let sub = connection.subscribe(MSG_ID_TALK, msg_num).await?;
const BLOCK_PER_PAYLOAD: usize = 1; const BLOCK_PER_PAYLOAD: usize = 1;
const BLOCK_HEADER_SIZE: usize = 4; const BLOCK_HEADER_SIZE: usize = 4;
+2 -2
View File
@@ -17,7 +17,7 @@ impl BcCamera {
self.has_ability_ro("general").await?; self.has_ability_ro("general").await?;
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_get_general = connection.subscribe(msg_num).await?; let mut sub_get_general = connection.subscribe(MSG_ID_GET_GENERAL, msg_num).await?;
let get = Bc { let get = Bc {
meta: BcMeta { meta: BcMeta {
msg_id: MSG_ID_GET_GENERAL, msg_id: MSG_ID_GET_GENERAL,
@@ -102,7 +102,7 @@ impl BcCamera {
self.has_ability_rw("general").await?; self.has_ability_rw("general").await?;
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_set_general = connection.subscribe(msg_num).await?; let mut sub_set_general = connection.subscribe(MSG_ID_SET_GENERAL, msg_num).await?;
let set = Bc::new_from_xml( let set = Bc::new_from_xml(
BcMeta { BcMeta {
msg_id: MSG_ID_SET_GENERAL, msg_id: MSG_ID_SET_GENERAL,
+1 -1
View File
@@ -7,7 +7,7 @@ impl BcCamera {
self.has_ability_ro("version").await?; self.has_ability_ro("version").await?;
let connection = self.get_connection(); let connection = self.get_connection();
let msg_num = self.new_message_num(); let msg_num = self.new_message_num();
let mut sub_version = connection.subscribe(msg_num).await?; let mut sub_version = connection.subscribe(MSG_ID_VERSION, msg_num).await?;
let version = Bc { let version = Bc {
meta: BcMeta { meta: BcMeta {
+1 -1
View File
@@ -52,7 +52,7 @@ fn bcudp_ack<'a, W: 'a + Write>(
le_u32(0), le_u32(0),
le_u32(payload.group_id), le_u32(payload.group_id),
le_u32(payload.packet_id), le_u32(payload.packet_id),
le_u32(0), le_u32(0xd7160000),
le_u32(binary_payload.len() as u32), le_u32(binary_payload.len() as u32),
slice(binary_payload), slice(binary_payload),
)) ))
+1
View File
@@ -88,6 +88,7 @@ local message_types = {
[15]="<FileInfoList>", [15]="<FileInfoList>",
[16]="<FileInfoList>", [16]="<FileInfoList>",
[18]="<PtzControl>", [18]="<PtzControl>",
[19]="<PtzPreset>",
[23]="Reboot", [23]="Reboot",
[25]="<VideoInput> (write)", [25]="<VideoInput> (write)",
[26]="<VideoInput>", -- <InputAdvanceCfg> [26]="<VideoInput>", -- <InputAdvanceCfg>
+49 -1
View File
@@ -355,6 +355,10 @@ Message have zero to two payloads.
</body> </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 - Camera
- Header - Header
@@ -363,6 +367,45 @@ 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 | | 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` - 23: `Reboot`
- Client - Client
@@ -1987,7 +2030,12 @@ Message have zero to two payloads.
<body> <body>
<PtzPreset version="1.1"> <PtzPreset version="1.1">
<channelId>0</channelId> <channelId>0</channelId>
<presetList /> <presetList>
<preset>
<id>0</id>
<name>Test</name>
</preset>
</presetList>
</PtzPreset> </PtzPreset>
</body> </body>
``` ```
+4
View File
@@ -38,6 +38,10 @@ address = "192.168.1.187:9000"
# mqtt.broker_addr = "192.168.1.122" # mqtt.broker_addr = "192.168.1.122"
# mqtt.port = 1883 # mqtt.port = 1883
# mqtt.credentials = ["mqtt_user", "mqtt_password"] # 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 # If you use a battery camera: **Instead** of an `address` supply the uid
# as follows # as follows
+1
View File
@@ -21,6 +21,7 @@ pub enum Command {
StatusLight(super::statusled::Opt), StatusLight(super::statusled::Opt),
Reboot(super::reboot::Opt), Reboot(super::reboot::Opt),
Pir(super::pir::Opt), Pir(super::pir::Opt),
Ptz(super::ptz::Opt),
Talk(super::talk::Opt), Talk(super::talk::Opt),
Mqtt(super::mqtt::Opt), Mqtt(super::mqtt::Opt),
Image(super::image::Opt), Image(super::image::Opt),
+32 -2
View File
@@ -1,8 +1,10 @@
use crate::mqtt::Discoveries;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use neolink_core::bc_protocol::{DiscoveryMethods, PrintFormat}; use neolink_core::bc_protocol::{DiscoveryMethods, PrintFormat};
use regex::Regex; use regex::Regex;
use serde::Deserialize; use serde::Deserialize;
use std::clone::Clone; use std::clone::Clone;
use std::collections::HashSet;
use validator::{Validate, ValidationError}; use validator::{Validate, ValidationError};
use validator_derive::Validate; use validator_derive::Validate;
@@ -104,7 +106,7 @@ pub(crate) struct CameraConfig {
pub(crate) update_time: bool, pub(crate) update_time: bool,
#[validate(range( #[validate(range(
min = 10, min = 0,
max = 500, max = 500,
message = "Invalid buffer size", message = "Invalid buffer size",
code = "buffer_size" code = "buffer_size"
@@ -118,6 +120,9 @@ pub(crate) struct CameraConfig {
alias = "stretching" alias = "stretching"
)] )]
pub(crate) use_smoothing: bool, pub(crate) use_smoothing: bool,
#[serde(default = "default_true", alias = "splash")]
pub(crate) use_splash: bool,
} }
#[derive(Debug, Deserialize, Validate, Clone)] #[derive(Debug, Deserialize, Validate, Clone)]
@@ -146,6 +151,27 @@ pub(crate) struct MqttConfig {
#[serde(default)] #[serde(default)]
pub(crate) client_auth: Option<(std::path::PathBuf, std::path::PathBuf)>, 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> { fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
@@ -158,6 +184,10 @@ fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
} }
} }
const fn default_true() -> bool {
true
}
fn default_mqtt() -> Option<MqttConfig> { fn default_mqtt() -> Option<MqttConfig> {
None None
} }
@@ -260,7 +290,7 @@ fn default_smoothing() -> bool {
} }
fn default_buffer_size() -> usize { fn default_buffer_size() -> usize {
100 25
} }
pub(crate) static RESERVED_NAMES: &[&str] = &["anyone", "anonymous"]; pub(crate) static RESERVED_NAMES: &[&str] = &["anyone", "anonymous"];
+5
View File
@@ -10,4 +10,9 @@ pub struct Opt {
/// The path of the output. /// The path of the output.
#[structopt(short, long, value_parser = PathBuf::from_str)] #[structopt(short, long, value_parser = PathBuf::from_str)]
pub file_path: PathBuf, pub file_path: PathBuf,
/// If set then the image will pull from the live stream, if not it will be pulled from the cameras snap feature
///
/// Using the snap feature, is preffered unless your camera does not support it
#[structopt(short, long)]
pub use_stream: bool,
} }
+52 -33
View File
@@ -9,9 +9,18 @@
/// neolink image --config=config.toml --file-path=filepath CameraName /// 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 anyhow::{Context, Result};
use log::*; use log::*;
use neolink_core::{bc_protocol::*, bcmedia::model::*}; use neolink_core::{bc_protocol::*, bcmedia::model::*};
use tokio::{fs::File, io::AsyncWriteExt};
mod cmdline; mod cmdline;
mod gst; mod gst;
@@ -32,44 +41,54 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
let camera = connect_and_login(camera_config) let camera = connect_and_login(camera_config)
.await .await
.context("Failed to connect to the camera, check credentials and network")?; .context("Failed to connect to the camera, check credentials and network")?;
let mut stream_data = camera
.start_video(StreamKind::Main, 0, camera_config.strict)
.await
.context("Failed to start video")?;
// Get one iframe at the start while also getting the the video type if opt.use_stream {
let buf; let mut stream_data = camera
let vid_type; .start_video(StreamKind::Main, 0, camera_config.strict)
loop { .await
if let BcMedia::Iframe(frame) = stream_data.get_data().await?? { .context("Failed to start video")?;
vid_type = frame.video_type;
buf = frame.data;
break;
}
}
let mut sender = gst::from_input(vid_type, &opt.file_path).await?; // Get one iframe at the start while also getting the the video type
sender.send(buf).await?; // Send first iframe let buf;
let vid_type;
// Keep sending both IFrame or PFrame until finished loop {
while sender.is_finished().await.is_none() { if let BcMedia::Iframe(frame) = stream_data.get_data().await?? {
let buf = match stream_data.get_data().await?? { vid_type = frame.video_type;
BcMedia::Iframe(frame) => frame.data, buf = frame.data;
BcMedia::Pframe(frame) => frame.data, break;
_ => {
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;
} }
let mut sender = gst::from_input(vid_type, &opt.file_path).await?;
sender.send(buf).await?; // Send first iframe
// Keep sending both IFrame or PFrame until finished
while sender.is_finished().await.is_none() {
let buf = match stream_data.get_data().await?? {
BcMedia::Iframe(frame) => frame.data,
BcMedia::Pframe(frame) => frame.data,
_ => {
continue;
}
};
debug!("Sending frame data to gstreamer");
if sender.send(buf).await.is_err() {
// Assume that the sender is closed
// because the pipeline is finished
break;
}
}
debug!("Sending EOS");
let _ = sender.eos().await; // Ignore return because if pipeline is finished this will error
} else {
// Simply use the snap command
debug!("Using the snap command");
let file_path = opt.file_path.with_extension("jpeg");
let mut buffer = File::create(file_path).await?;
let jpeg_data = camera.get_snapshot().await?;
buffer.write_all(jpeg_data.as_slice()).await?;
} }
debug!("Sending EOS");
let _ = sender.eos().await; // Ignore return because if pipeline is finished this will error
Ok(()) Ok(())
} }
+4
View File
@@ -34,6 +34,7 @@ mod config;
mod image; mod image;
mod mqtt; mod mqtt;
mod pir; mod pir;
mod ptz;
mod reboot; mod reboot;
mod rtsp; mod rtsp;
mod statusled; mod statusled;
@@ -102,6 +103,9 @@ async fn main() -> Result<()> {
Some(Command::Pir(opts)) => { Some(Command::Pir(opts)) => {
pir::main(opts, config).await?; pir::main(opts, config).await?;
} }
Some(Command::Ptz(opts)) => {
ptz::main(opts, config).await?;
}
Some(Command::Talk(opts)) => { Some(Command::Talk(opts)) => {
talk::main(opts, config).await?; talk::main(opts, config).await?;
} }
+570
View File
@@ -0,0 +1,570 @@
//! Enable and configures home assistant MQTTT discovery
//!
//! https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
//!
use anyhow::{Context, Result};
use heck::ToTitleCase;
use log::*;
use std::sync::Arc;
use super::mqttc::MqttSender;
use crate::config::{CameraConfig, MqttDiscoveryConfig};
use serde::{Deserialize, Serialize, Serializer};
#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Copy, Hash)]
pub(crate) enum Discoveries {
#[serde(alias = "floodlight", alias = "light")]
Floodlight,
#[serde(alias = "camera")]
Camera,
#[serde(alias = "motion", alias = "md", alias = "pir")]
Motion,
#[serde(alias = "led")]
Led,
#[serde(alias = "ir")]
Ir,
#[serde(alias = "reboot")]
Reboot,
#[serde(alias = "pt")]
Pt,
#[serde(alias = "battery", alias = "power")]
Battery,
}
#[derive(Debug, Clone)]
struct DiscoveryConnection {
connection_type: String,
connection_id: String,
}
impl Serialize for DiscoveryConnection {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
vec![&self.connection_type, &self.connection_id].serialize(serializer)
}
}
#[derive(Serialize, Debug, Clone)]
struct DiscoveryDevice {
name: String,
connections: Vec<DiscoveryConnection>,
identifiers: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
manufacturer: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
sw_version: Option<String>,
}
#[derive(Serialize, Debug, Clone)]
struct DiscoveryAvaliablity {
topic: String,
#[serde(skip_serializing_if = "Option::is_none")]
payload_available: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
payload_not_available: Option<String>,
}
#[derive(Serialize, Debug)]
struct DiscoveryLight {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// Light specific
#[serde(skip_serializing_if = "Option::is_none")]
state_topic: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
state_value_template: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
command_topic: Option<String>,
payload_on: String,
payload_off: String,
}
#[derive(Serialize, Debug)]
#[allow(dead_code)]
enum Encoding {
None,
#[serde(rename = "b64")]
Base64,
}
impl Encoding {
fn is_none(&self) -> bool {
matches!(self, Self::None)
}
}
#[derive(Serialize, Debug)]
struct DiscoveryCamera {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// Camera specific
topic: String,
#[serde(skip_serializing_if = "Encoding::is_none")]
image_encoding: Encoding,
}
#[derive(Serialize, Debug)]
struct DiscoverySwitch {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// Switch specific
// - Control
command_topic: String,
payload_off: String,
payload_on: String,
// - State
#[serde(skip_serializing_if = "Option::is_none")]
state_topic: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
state_off: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
state_on: Option<String>,
}
#[derive(Serialize, Debug)]
struct DiscoverySelect {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// Switch specific
// - Control
command_topic: String,
options: Vec<String>,
// - State
#[serde(skip_serializing_if = "Option::is_none")]
state_topic: Option<String>,
}
#[derive(Serialize, Debug)]
struct DiscoveryBinarySensor {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// BinarySensor specific
payload_off: String,
payload_on: String,
// - State
state_topic: String,
}
#[derive(Serialize, Debug)]
struct DiscoveryButton {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// Button specific
command_topic: String,
#[serde(skip_serializing_if = "Option::is_none")]
payload_press: Option<String>,
}
#[derive(Serialize, Debug)]
struct DiscoverySensor {
name: String,
unique_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<String>,
device: DiscoveryDevice,
availability: DiscoveryAvaliablity,
// Button specific
state_topic: String,
state_class: String,
unit_of_measurement: String,
}
/// Enables MQTT discovery for a camera. See docs at https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery
pub(crate) async fn enable_discovery(
discovery_config: &MqttDiscoveryConfig,
mqtt_sender: &MqttSender,
cam_config: &Arc<CameraConfig>,
) -> Result<()> {
debug!("Enabling MQTT discovery for {}", cam_config.name);
let mut connections = vec![];
if let Some(addr) = &cam_config.camera_addr {
connections.push(DiscoveryConnection {
connection_type: "camera_addr".to_string(),
connection_id: addr.clone(),
});
}
if let Some(uid) = &cam_config.camera_uid {
connections.push(DiscoveryConnection {
connection_type: "camera_uid".to_string(),
connection_id: uid.clone(),
});
}
if connections.is_empty() {
error!(
"No connections found for camera {}, either addr or UID must be supplied",
cam_config.name
);
return Ok(());
}
let friendly_name = cam_config.name.replace('_', " ").to_title_case();
let device = DiscoveryDevice {
name: friendly_name.clone(),
connections,
identifiers: vec![format!("neolink_{}", cam_config.name)],
manufacturer: Some("Reolink".to_string()),
model: Some("Neolink".to_string()),
sw_version: Some(env!("CARGO_PKG_VERSION").to_string()),
};
let availability = DiscoveryAvaliablity {
topic: format!("neolink/{}/status", cam_config.name),
payload_available: Some("connected".to_string()),
payload_not_available: None,
};
for feature in &discovery_config.features {
match feature {
Discoveries::Floodlight => {
let config_data = DiscoveryLight {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} Floodlight", friendly_name.as_str()),
unique_id: format!("neolink_{}_floodlight", cam_config.name),
// Match native home assistant integration: https://github.com/home-assistant/core/blob/dev/homeassistant/components/reolink/light.py#L49
icon: Some("mdi:spotlight-beam".to_string()),
// State
state_topic: Some(format!("neolink/{}/status/floodlight", cam_config.name)),
state_value_template: Some("{{ value_json.state }}".to_string()),
// Control
command_topic: Some(format!("neolink/{}/control/floodlight", cam_config.name)),
// Lowercase payloads to match neolink convention
payload_on: "on".to_string(),
payload_off: "off".to_string(),
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/light/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery light config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish floodlight auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
Discoveries::Camera => {
let config_data = DiscoveryCamera {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} Camera", friendly_name.as_str()),
unique_id: format!("neolink_{}_camera", cam_config.name),
icon: Some("mdi:camera-iris".to_string()),
// Camera specific
topic: format!("neolink/{}/status/preview", cam_config.name),
image_encoding: Encoding::Base64,
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/camera/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery camera config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish camera auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
Discoveries::Led => {
let config_data = DiscoverySwitch {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} LED", friendly_name.as_str()),
unique_id: format!("neolink_{}_led", cam_config.name),
icon: Some("mdi:led-on".to_string()),
// Switch specific
command_topic: format!("neolink/{}/control/led", cam_config.name),
payload_off: "off".to_string(),
payload_on: "on".to_string(),
state_topic: None,
state_off: None,
state_on: None,
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/switch/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery led config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish led auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
Discoveries::Ir => {
let config_data = DiscoverySelect {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} IR", friendly_name.as_str()),
unique_id: format!("neolink_{}_ir", cam_config.name),
icon: Some("mdi:lightbulb-night".to_string()),
// Switch specific
command_topic: format!("neolink/{}/control/ir", cam_config.name),
options: vec!["on".to_string(), "off".to_string(), "auto".to_string()],
state_topic: None,
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/select/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery led config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish led auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
Discoveries::Motion => {
let config_data = DiscoveryBinarySensor {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} MD", friendly_name.as_str()),
unique_id: format!("neolink_{}_md", cam_config.name),
icon: Some("mdi:motion-sensor".to_string()),
// Switch specific
state_topic: format!("neolink/{}/status/motion", cam_config.name),
payload_off: "off".to_string(),
payload_on: "on".to_string(),
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/binary_sensor/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery motion config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish motion auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
Discoveries::Reboot => {
let config_data = DiscoveryButton {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} Reboot", friendly_name.as_str()),
unique_id: format!("neolink_{}_reboot", cam_config.name),
icon: Some("mdi:restart".to_string()),
// Switch specific
command_topic: format!("neolink/{}/control/reboot", cam_config.name),
payload_press: None,
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/button/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery reboot config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish reboot auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
Discoveries::Pt => {
for dir in ["left", "right", "up", "down"] {
let config_data = DiscoveryButton {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} Pan {}", friendly_name.as_str(), dir),
unique_id: format!("neolink_{}_pan_{}", cam_config.name, dir),
icon: Some(format!("mdi:pan-{}", dir)),
// Switch specific
command_topic: format!("neolink/{}/control/ptz", cam_config.name),
payload_press: Some(dir.to_string()),
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/button/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery pt config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish pt auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
}
Discoveries::Battery => {
let config_data = DiscoverySensor {
// Common across all potential features
device: device.clone(),
availability: availability.clone(),
// Identifiers
name: format!("{} Battery", friendly_name.as_str()),
unique_id: format!("neolink_{}_battery", cam_config.name),
icon: Some("mdi:battery".to_string()),
// Camera specific
state_topic: format!("neolink/{}/status/battery_level", cam_config.name),
state_class: "measurement".to_string(),
unit_of_measurement: "%".to_string(),
};
// Each feature needs to be individually registered
mqtt_sender
.send_message_with_root_topic(
&format!(
"{}/sensor/{}",
discovery_config.topic, &config_data.unique_id
),
"config",
&serde_json::to_string(&config_data).with_context(|| {
"Cound not serialise discovery battery config into json"
})?,
true,
)
.await
.with_context(|| {
format!(
"Failed to publish battery auto-discover data on over MQTT for {}",
cam_config.name
)
})?;
}
}
}
info!(
"Enabled MQTT discovery for {} with friendly name {}",
cam_config.name,
friendly_name.as_str()
);
Ok(())
}
+268 -28
View File
@@ -1,6 +1,7 @@
use crate::config::CameraConfig; use crate::config::CameraConfig;
use crate::utils::AddressOrUid; use crate::utils::{timeout, AddressOrUid};
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use futures::stream::StreamExt;
use log::*; use log::*;
use neolink_core::bc_protocol::{ use neolink_core::bc_protocol::{
BcCamera, Direction as BcDirection, Error as BcError, LightState, MaxEncryption, MotionStatus, BcCamera, Direction as BcDirection, Error as BcError, LightState, MaxEncryption, MotionStatus,
@@ -9,17 +10,17 @@ use std::sync::Arc;
use tokio::{ use tokio::{
sync::mpsc::{channel, Receiver, Sender}, sync::mpsc::{channel, Receiver, Sender},
task::JoinSet, task::JoinSet,
time::sleep, time::{interval, sleep, Duration},
}; };
use core::time::Duration; #[derive(Debug, Clone)]
#[derive(Debug, Copy, Clone)]
pub(crate) enum Messages { pub(crate) enum Messages {
Login, Login,
MotionStop, MotionStop,
MotionStart, MotionStart,
Reboot, Reboot,
FloodlightOn,
FloodlightOff,
StatusLedOn, StatusLedOn,
StatusLedOff, StatusLedOff,
IRLedOn, IRLedOn,
@@ -30,6 +31,11 @@ pub(crate) enum Messages {
PIROff, PIROff,
PIRQuery, PIRQuery,
Ptz(Direction), Ptz(Direction),
Snap(Vec<u8>),
BatteryLevel(u32),
Preset(u8),
PresetAssign(u8, String),
PresetQuery,
} }
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
@@ -187,10 +193,9 @@ impl EventCamThread {
"aes" => MaxEncryption::Aes, "aes" => MaxEncryption::Aes,
_ => MaxEncryption::Aes, _ => MaxEncryption::Aes,
}; };
camera timeout(camera.login_with_maxenc(max_encryption))
.login_with_maxenc(max_encryption)
.await .await
.context("Failed to login to the camera")?; .context("Failed to login to the camera")??;
info!("{}: Connected and logged in", camera_config.name); info!("{}: Connected and logged in", camera_config.name);
self.tx.send(Messages::Login).await?; self.tx.send(Messages::Login).await?;
@@ -203,6 +208,25 @@ impl EventCamThread {
camera: arc_cam.clone(), 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 { let mut message_handler = MessageHandler {
rx: &mut self.rx, rx: &mut self.rx,
camera: arc_cam, camera: arc_cam,
@@ -212,7 +236,7 @@ impl EventCamThread {
val = async { val = async {
info!("{}: Listening to Camera Motion", camera_config.name); info!("{}: Listening to Camera Motion", camera_config.name);
motion_thread.run().await 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 { if let Err(e) = val {
error!("Motion thread aborted: {:?}", e); error!("Motion thread aborted: {:?}", e);
Err(e) Err(e)
@@ -221,6 +245,54 @@ impl EventCamThread {
Ok(()) 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 { val = async {
info!("{}: Setting up camera actions", camera_config.name); info!("{}: Setting up camera actions", camera_config.name);
message_handler.listen().await message_handler.listen().await
@@ -272,6 +344,114 @@ 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> { struct MessageHandler<'a> {
rx: &'a mut Receiver<ToCamera>, rx: &'a mut Receiver<ToCamera>,
camera: Arc<BcCamera>, camera: Arc<BcCamera>,
@@ -297,6 +477,30 @@ impl<'a> MessageHandler<'a> {
"OK".to_string() "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 => { Messages::StatusLedOn => {
if let Err(e) = self.camera.led_light_set(true).await { if let Err(e) = self.camera.led_light_set(true).await {
error = error =
@@ -411,27 +615,23 @@ impl<'a> MessageHandler<'a> {
} }
} }
Messages::Ptz(direction) => { Messages::Ptz(direction) => {
let (bc_direction, amount, seconds) = match direction { let (bc_direction, speed, seconds) = match direction {
Direction::Up(amount, seconds) => { Direction::Up(speed, seconds) => (BcDirection::Up, speed, seconds),
(BcDirection::Up, amount, seconds) Direction::Down(speed, seconds) => {
(BcDirection::Down, speed, seconds)
} }
Direction::Down(amount, seconds) => { Direction::Left(speed, seconds) => {
(BcDirection::Down, amount, seconds) (BcDirection::Left, speed, seconds)
} }
Direction::Left(amount, seconds) => { Direction::Right(speed, seconds) => {
(BcDirection::Left, amount, seconds) (BcDirection::Right, speed, seconds)
} }
Direction::Right(amount, seconds) => { Direction::In(speed, seconds) => (BcDirection::In, speed, seconds),
(BcDirection::Right, amount, seconds) Direction::Out(speed, seconds) => {
} (BcDirection::Out, speed, 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, amount).await { if let Err(e) = self.camera.send_ptz(bc_direction, speed).await {
error = Some(format!("Failed to send PTZ: {:?}", e)); error = Some(format!("Failed to send PTZ: {:?}", e));
"FAIL".to_string() "FAIL".to_string()
} else { } else {
@@ -439,9 +639,7 @@ impl<'a> MessageHandler<'a> {
sleep(Duration::from_secs_f32(seconds)).await; sleep(Duration::from_secs_f32(seconds)).await;
// note that amount is not used in the stop command // note that amount is not used in the stop command
if let Err(e) = if let Err(e) = self.camera.send_ptz(BcDirection::Stop, 0.0).await {
self.camera.send_ptz(BcDirection::Stop, amount).await
{
error = Some(format!("Failed to send PTZ: {:?}", e)); error = Some(format!("Failed to send PTZ: {:?}", e));
"FAIL".to_string() "FAIL".to_string()
} else { } else {
@@ -449,6 +647,48 @@ 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(), _ => "UNKNOWN COMMAND".to_string(),
}; };
if let Some(replier) = replier { if let Some(replier) = replier {
+134 -9
View File
@@ -1,3 +1,4 @@
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
/// ///
/// # Neolink MQTT /// # Neolink MQTT
/// ///
@@ -9,11 +10,14 @@
/// ///
/// Control messages: /// Control messages:
/// ///
/// - `/control/floodlight [on|off]` Turns floodlight (if equipped) on/off
/// - `/control/led [on|off]` Turns status LED on/off /// - `/control/led [on|off]` Turns status LED on/off
/// - `/control/pir [on|off]` Turns PIR 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/ir [on|off|auto]` Turn IR lights on/off or automatically via light detection
/// - `/control/reboot` Reboot the camera /// - `/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` [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: /// Status Messages:
/// ///
@@ -21,11 +25,13 @@
/// `/status disconnected` Sent when the camera goes offline /// `/status disconnected` Sent when the camera goes offline
/// `/status/battery` Sent in reply to a `/query/battery` /// `/status/battery` Sent in reply to a `/query/battery`
/// `/status/pir` Sent in reply to a `/query/pir` /// `/status/pir` Sent in reply to a `/query/pir`
/// `/status/ptz/preset` Sent in reply to a `/query/ptz/preset`
/// ///
/// Query Messages: /// Query Messages:
/// ///
/// `/query/battery` Request that the camera reports its battery level /// `/query/battery` Request that the camera reports its battery level
/// `/query/pir` Request that the camera reports its pir status /// `/query/pir` Request that the camera reports its pir status
/// `/query/ptz/preset` Request that the camera reports the PTZ presets
/// ///
/// ///
/// # Usage /// # Usage
@@ -56,18 +62,21 @@ use std::sync::Arc;
use tokio::time::{sleep, Duration}; use tokio::time::{sleep, Duration};
mod cmdline; mod cmdline;
mod discovery;
mod event_cam; mod event_cam;
mod mqttc; mod mqttc;
use crate::config::{CameraConfig, Config, MqttConfig}; use crate::config::{CameraConfig, Config, MqttConfig};
use anyhow::{anyhow, Context, Error, Result}; use anyhow::{anyhow, Context, Error, Result};
pub(crate) use cmdline::Opt; pub(crate) use cmdline::Opt;
pub(crate) use discovery::Discoveries;
use event_cam::EventCam; use event_cam::EventCam;
pub(crate) use event_cam::{Direction, Messages}; pub(crate) use event_cam::{Direction, Messages};
use log::*; use log::*;
use mqttc::{Mqtt, MqttReplyRef}; use mqttc::{Mqtt, MqttReplyRef};
use self::{ use self::{
discovery::enable_discovery,
event_cam::EventCamSender, event_cam::EventCamSender,
mqttc::{MqttReply, MqttSender}, mqttc::{MqttReply, MqttSender},
}; };
@@ -131,7 +140,8 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
tokio::select! { tokio::select! {
v = async { v = async {
// Normal poll operations // Normal poll operations
while let Ok(msg) = mqtt.poll().await { loop {
let msg = mqtt.poll().await?;
tokio::task::yield_now().await; tokio::task::yield_now().await;
// Put the reply on it's own async thread so we can safely sleep // 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 // and wait for it to reply in it's own time
@@ -148,7 +158,6 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
} }
}); });
} }
Ok(())
} => v, } => v,
// Wait on any error from any of the error channels and if we get it we abort // 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"))), v = error_recv.recv() => v.map(Err).unwrap_or_else(|| Err(anyhow!("Listen on camera error channel closed"))),
@@ -166,6 +175,32 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
.with_context(|| { .with_context(|| {
format!("Failed to post connect over MQTT for {}", camera_name) 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 => { Messages::MotionStop => {
mqtt_sender_cam mqtt_sender_cam
@@ -183,6 +218,25 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
format!("Failed to publish motion start for {}", camera_name) 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
)
})?;
}
_ => {} _ => {}
} }
} }
@@ -214,6 +268,28 @@ async fn handle_mqtt_message(
} => { } => {
// Do nothing for the success/fail replies // 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 { MqttReplyRef {
topic: "control/led", topic: "control/led",
message: "on", message: "on",
@@ -288,9 +364,10 @@ async fn handle_mqtt_message(
let mut words = lowercase_message.split_whitespace(); let mut words = lowercase_message.split_whitespace();
if let Some(direction_txt) = words.next() { if let Some(direction_txt) = words.next() {
// Target amount to move // Target amount to move
let speed = 32f32;
let amount = words.next().unwrap_or("32.0"); let amount = words.next().unwrap_or("32.0");
if let Ok(amount) = amount.parse::<f32>() { if let Ok(amount) = amount.parse::<f32>() {
let seconds = amount / 32f32; let seconds = amount / speed;
// range checking on seconds so that you can't sleep for 3.4E+38 seconds // range checking on seconds so that you can't sleep for 3.4E+38 seconds
match seconds { match seconds {
x if (0.0..10.0).contains(&x) => seconds, x if (0.0..10.0).contains(&x) => seconds,
@@ -301,12 +378,12 @@ async fn handle_mqtt_message(
}; };
let direction = match direction_txt { let direction = match direction_txt {
"up" => Direction::Up(amount, seconds), "up" => Direction::Up(speed, seconds),
"down" => Direction::Down(amount, seconds), "down" => Direction::Down(speed, seconds),
"left" => Direction::Left(amount, seconds), "left" => Direction::Left(speed, seconds),
"right" => Direction::Right(amount, seconds), "right" => Direction::Right(speed, seconds),
"in" => Direction::In(amount, seconds), "in" => Direction::In(speed, seconds),
"out" => Direction::Out(amount, seconds), "out" => Direction::Out(speed, seconds),
_ => { _ => {
error!("Unrecognized PTZ direction \"{}\"", direction_txt); error!("Unrecognized PTZ direction \"{}\"", direction_txt);
return Ok(()); return Ok(());
@@ -325,6 +402,42 @@ async fn handle_mqtt_message(
error!("No PTZ Direction given. Please add up/down/left/right/in/out"); 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 { MqttReplyRef {
topic: "control/pir", topic: "control/pir",
message: "on", message: "on",
@@ -370,6 +483,18 @@ async fn handle_mqtt_message(
); );
reply_topic = Some("status/pir"); 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 { if let Some(reply) = reply {
+26 -8
View File
@@ -50,15 +50,16 @@ pub(crate) struct MqttSender {
} }
impl MqttSender { impl MqttSender {
pub async fn send_message( pub async fn send_message_with_root_topic(
&self, &self,
root_topic: &str,
sub_topic: &str, sub_topic: &str,
message: &str, message: &str,
retain: bool, retain: bool,
) -> Result<(), ClientError> { ) -> Result<(), ClientError> {
self.client self.client
.publish( .publish(
format!("neolink/{}/{}", self.name, sub_topic), format!("{}/{}/{}", root_topic, self.name, sub_topic),
QoS::AtLeastOnce, QoS::AtLeastOnce,
retain, retain,
message, message,
@@ -67,6 +68,17 @@ impl MqttSender {
Ok(()) Ok(())
} }
pub async fn send_message(
&self,
sub_topic: &str,
message: &str,
retain: bool,
) -> Result<(), ClientError> {
self.send_message_with_root_topic("neolink", sub_topic, message, retain)
.await?;
Ok(())
}
async fn subscribe(&self) -> Result<(), ClientError> { async fn subscribe(&self) -> Result<(), ClientError> {
self.client self.client
.subscribe(format!("neolink/{}/#", self.name), QoS::AtMostOnce) .subscribe(format!("neolink/{}/#", self.name), QoS::AtMostOnce)
@@ -156,6 +168,8 @@ impl Mqtt {
&config.broker_addr, &config.broker_addr,
config.port, config.port,
); );
let max_size = 100 * (1024 * 1024);
mqttoptions.set_max_packet_size(max_size, max_size);
// Use TLS if ca path is set // Use TLS if ca path is set
if let Some(ca_path) = &config.ca { if let Some(ca_path) = &config.ca {
@@ -264,12 +278,16 @@ impl Mqtt {
impl Drop for Mqtt { impl Drop for Mqtt {
fn drop(&mut self) { fn drop(&mut self) {
if let Some(drop_message) = self.drop_message.as_ref() { if let Some(drop_message) = self.drop_message.as_ref() {
if self let res = self.get_sender().try_send_message(
.get_sender() &drop_message.topic,
.try_send_message(&drop_message.topic, &drop_message.message, true) &drop_message.message,
.is_err() true,
{ );
error!("Failed to send offline message to mqtt"); if res.is_err() {
error!(
"Failed to send offline message to mqtt: {:?}. Is the MQTT topic name valid?",
res.err().unwrap()
);
} }
} }
self.set.abort_all(); self.set.abort_all();
+40
View File
@@ -0,0 +1,40 @@
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>,
},
}
+94
View File
@@ -0,0 +1,94 @@
///
/// # 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(())
}
+54 -46
View File
@@ -41,17 +41,17 @@ glib::wrapper! {
impl Default for NeoMediaFactory { impl Default for NeoMediaFactory {
fn default() -> Self { fn default() -> Self {
Self::new(100, true) Self::new(100, true, true)
} }
} }
impl NeoMediaFactory { impl NeoMediaFactory {
pub(crate) fn new(buffer_size: usize, use_smoothing: bool) -> Self { pub(crate) fn new(buffer_size: usize, use_smoothing: bool, use_splash: bool) -> Self {
let factory = Object::new::<NeoMediaFactory>(); let factory = Object::new::<NeoMediaFactory>();
factory.set_shared(false); factory.set_shared(false);
factory.imp().shared.set_buffer_size(buffer_size); factory.imp().shared.set_buffer_size(buffer_size);
factory.imp().shared.set_use_smoothing(use_smoothing); factory.imp().shared.set_use_smoothing(use_smoothing);
// factory.set_do_retransmission(false); // Can't use as the method is missing on the 32bit docker gst dll factory.imp().shared.set_use_splash(use_splash);
factory.set_launch("videotestsrc pattern=\"snow\" ! video/x-raw,width=896,height=512,framerate=25/1 ! textoverlay name=\"inittextoverlay\" text=\"Stream not Ready\" valignment=top halignment=left font-desc=\"Sans, 32\" ! jpegenc ! rtpjpegpay name=pay0"); factory.set_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_suspend_mode(RTSPSuspendMode::None);
factory.set_transport_mode(RTSPTransportMode::PLAY); factory.set_transport_mode(RTSPTransportMode::PLAY);
@@ -184,7 +184,7 @@ impl ObjectImpl for NeoMediaFactoryImpl {}
impl RTSPMediaFactoryImpl for NeoMediaFactoryImpl { impl RTSPMediaFactoryImpl for NeoMediaFactoryImpl {
fn create_element(&self, url: &RTSPUrl) -> Option<Element> { fn create_element(&self, url: &RTSPUrl) -> Option<Element> {
self.parent_create_element(url) self.parent_create_element(url)
.map(|orig| self.build_pipeline(orig).expect("Could not build pipeline")) .and_then(|orig| self.build_pipeline(orig).expect("Could not build pipeline"))
} }
} }
@@ -239,18 +239,18 @@ fn make_queue(name: &str) -> AnyResult<Element> {
Ok(queue) Ok(queue)
} }
fn make_queue2(name: &str) -> AnyResult<Element> { // fn make_queue2(name: &str) -> AnyResult<Element> {
let queue = make_element("queue2", name)?; // let queue = make_element("queue2", name)?;
queue.set_property("use-buffering", true); // queue.set_property("use-buffering", true);
queue.set_property("max-size-bytes", 0u32); // queue.set_property("max-size-bytes", 0u32);
queue.set_property("max-size-buffers", 0u32); // queue.set_property("max-size-buffers", 0u32);
queue.set_property( // queue.set_property(
"max-size-time", // "max-size-time",
std::convert::TryInto::<u64>::try_into(tokio::time::Duration::from_secs(5).as_nanos()) // std::convert::TryInto::<u64>::try_into(tokio::time::Duration::from_secs(5).as_nanos())
.unwrap_or(0), // .unwrap_or(0),
); // );
Ok(queue) // Ok(queue)
} // }
impl NeoMediaFactoryImpl { impl NeoMediaFactoryImpl {
pub(crate) fn buffer_ready(&self) -> bool { pub(crate) fn buffer_ready(&self) -> bool {
@@ -260,15 +260,17 @@ impl NeoMediaFactoryImpl {
self.shared.number_of_clients.load(Ordering::Relaxed) self.shared.number_of_clients.load(Ordering::Relaxed)
} }
fn build_pipeline(&self, media: Element) -> AnyResult<Element> { fn build_pipeline(&self, media: Element) -> AnyResult<Option<Element>> {
// debug!("Building PIPELINE"); // debug!("Building PIPELINE");
let bin = media let bin = media
.dynamic_cast::<Bin>() .dynamic_cast::<Bin>()
.map_err(|_| anyhow!("Media source's element should be a bin"))?; .map_err(|_| anyhow!("Media source's element should be a bin"))?;
// Clear the autogenerated ones // Clear the autogenerated ones
log::debug!("Clearing old elements");
for element in bin.iterate_elements().into_iter().flatten() { for element in bin.iterate_elements().into_iter().flatten() {
bin.remove(&element)?; bin.remove(&element)?;
} }
log::debug!("Cleared");
let mut client_data = NeoMediaSender::new( let mut client_data = NeoMediaSender::new(
self.shared.get_buffer_size(), self.shared.get_buffer_size(),
@@ -281,12 +283,15 @@ impl NeoMediaFactoryImpl {
self.shared.buffer_ready.load(Ordering::Relaxed), self.shared.buffer_ready.load(Ordering::Relaxed),
) { ) {
(VidFormats::Unknown, true) | (_, false) => { (VidFormats::Unknown, true) | (_, false) => {
if !self.shared.get_use_splash() {
return Ok(None);
}
debug!("Building Unknown Pipeline"); debug!("Building Unknown Pipeline");
let source = make_element("videotestsrc", "testvidsrc")?; let source = make_element("videotestsrc", "testvidsrc")?;
source.set_property_from_str("pattern", "snow"); source.set_property_from_str("pattern", "snow");
source.set_property("num-buffers", 500i32); // Send buffers then EOS source.set_property("num-buffers", 500i32); // Send buffers then EOS
let queue = make_queue("queue0")?; let queue = make_queue("queue0")?;
let queue2 = make_queue2("queue2")?; // let queue2 = make_queue2("queue2")?;
let overlay = make_element("textoverlay", "overlay")?; let overlay = make_element("textoverlay", "overlay")?;
overlay.set_property("text", "Stream not Ready"); overlay.set_property("text", "Stream not Ready");
overlay.set_property_from_str("valignment", "top"); overlay.set_property_from_str("valignment", "top");
@@ -295,7 +300,7 @@ impl NeoMediaFactoryImpl {
let encoder = make_element("jpegenc", "encoder")?; let encoder = make_element("jpegenc", "encoder")?;
let payload = make_element("rtpjpegpay", "pay0")?; let payload = make_element("rtpjpegpay", "pay0")?;
bin.add_many(&[&source, &queue, &queue2, &overlay, &encoder, &payload])?; bin.add_many(&[&source, &queue, &overlay, &encoder, &payload])?;
source.link_filtered( source.link_filtered(
&queue, &queue,
&Caps::builder("video/x-raw") &Caps::builder("video/x-raw")
@@ -306,7 +311,7 @@ impl NeoMediaFactoryImpl {
.build(), .build(),
)?; )?;
// source.link(&queue)?; // source.link(&queue)?;
Element::link_many(&[&queue, &queue2, &overlay, &encoder, &payload])?; Element::link_many(&[&queue, &overlay, &encoder, &payload])?;
} }
(VidFormats::H265, true) => { (VidFormats::H265, true) => {
debug!("Building H265 Pipeline"); debug!("Building H265 Pipeline");
@@ -355,12 +360,12 @@ impl NeoMediaFactoryImpl {
.dynamic_cast::<Element>() .dynamic_cast::<Element>()
.map_err(|_| anyhow!("Cannot cast back"))?; .map_err(|_| anyhow!("Cannot cast back"))?;
let queue = make_queue("source_queue")?; let queue = make_queue("source_queue")?;
let queue2 = make_queue2("queue2")?; // let queue2 = make_queue2("queue2")?;
let parser = make_element("h265parse", "parser")?; let parser = make_element("h265parse", "parser")?;
// parser.set_property("config-interval", 5i32); // parser.set_property("config-interval", 5i32);
let payload = make_element("rtph265pay", "pay0")?; let payload = make_element("rtph265pay", "pay0")?;
bin.add_many(&[&source, &queue, &queue2, &parser, &payload])?; bin.add_many(&[&source, &queue, &parser, &payload])?;
Element::link_many(&[&source, &queue, &queue2, &parser, &payload])?; Element::link_many(&[&source, &queue, &parser, &payload])?;
let source = source let source = source
.dynamic_cast::<AppSrc>() .dynamic_cast::<AppSrc>()
@@ -417,7 +422,7 @@ impl NeoMediaFactoryImpl {
.dynamic_cast::<Element>() .dynamic_cast::<Element>()
.map_err(|_| anyhow!("Cannot cast back"))?; .map_err(|_| anyhow!("Cannot cast back"))?;
let queue = make_queue("source_queue")?; let queue = make_queue("source_queue")?;
let queue2 = make_queue2("queue2")?; // let queue2 = make_queue2("queue2")?;
let parser = make_element("h264parse", "parser")?; let parser = make_element("h264parse", "parser")?;
// parser.set_property("update-timecode", true); // parser.set_property("update-timecode", true);
let payload = make_element("rtph264pay", "pay0")?; let payload = make_element("rtph264pay", "pay0")?;
@@ -429,13 +434,13 @@ impl NeoMediaFactoryImpl {
// payload.set_property("config-interval", 5i32); // payload.set_property("config-interval", 5i32);
bin.add_many(&[ bin.add_many(&[
&source, &queue, &queue2, &parser, &source, &queue, &parser,
&payload, &payload,
// &storage, // &storage,
// &jitter, // &jitter,
])?; ])?;
Element::link_many(&[ Element::link_many(&[
&source, &queue, &queue2, &parser, &source, &queue, &parser,
&payload, &payload,
// &storage, // &storage,
// &jitter, // &jitter,
@@ -488,25 +493,26 @@ impl NeoMediaFactoryImpl {
.map_err(|_| anyhow!("Cannot cast back"))?; .map_err(|_| anyhow!("Cannot cast back"))?;
let queue = make_queue("audqueue")?; let queue = make_queue("audqueue")?;
let queue2 = make_queue2("audqueue2")?; // let queue2 = make_queue2("audqueue2")?;
let parser = make_element("aacparse", "audparser")?; let parser = make_element("aacparse", "audparser")?;
let decoder = make_element("decodebin", "auddecoder")?; let decoder = match make_element("faad", "auddecoder_faad") {
Ok(ele) => Ok(ele),
Err(_) => make_element("avdec_aac", "auddecoder_avdec_aac"),
}?;
let encoder = make_element("audioconvert", "audencoder")?; let encoder = make_element("audioconvert", "audencoder")?;
let payload = make_element("rtpL16pay", "pay1")?; let payload = make_element("rtpL16pay", "pay1")?;
bin.add_many(&[ bin.add_many(&[&source, &queue, &parser, &decoder, &encoder, &payload])?;
&source, &queue, &queue2, &parser, &decoder, &encoder, &payload, Element::link_many(&[&source, &queue, &parser, &decoder, &encoder, &payload])?;
])?; // Element::link_many(&[])?;
Element::link_many(&[&source, &queue, &queue2, &parser, &decoder])?; // decoder.connect_pad_added(move |_element, pad| {
Element::link_many(&[&encoder, &payload])?; // debug!("Linking encoder to decoder: {:?}", pad.caps());
decoder.connect_pad_added(move |_element, pad| { // let sink_pad = encoder
debug!("Linking encoder to decoder: {:?}", pad.caps()); // .static_pad("sink")
let sink_pad = encoder // .expect("Encoder is missing its pad");
.static_pad("sink") // pad.link(&sink_pad)
.expect("Encoder is missing its pad"); // .expect("Failed to link AAC decoder to encoder");
pad.link(&sink_pad) // });
.expect("Failed to link AAC decoder to encoder");
});
let source = source let source = source
.dynamic_cast::<AppSrc>() .dynamic_cast::<AppSrc>()
@@ -560,13 +566,13 @@ impl NeoMediaFactoryImpl {
.map_err(|_| anyhow!("Cannot cast back"))?; .map_err(|_| anyhow!("Cannot cast back"))?;
let queue = make_queue("audqueue")?; let queue = make_queue("audqueue")?;
let queue2 = make_queue2("audqueue2")?; // let queue2 = make_queue2("audqueue2")?;
let decoder = make_element("decodebin", "auddecoder")?; let decoder = make_element("decodebin", "auddecoder")?;
let encoder = make_element("audioconvert", "audencoder")?; let encoder = make_element("audioconvert", "audencoder")?;
let payload = make_element("rtpL16pay", "pay1")?; let payload = make_element("rtpL16pay", "pay1")?;
bin.add_many(&[&source, &queue, &queue2, &decoder, &encoder, &payload])?; bin.add_many(&[&source, &queue, &decoder, &encoder, &payload])?;
Element::link_many(&[&source, &queue, &queue2, &decoder])?; Element::link_many(&[&source, &queue, &decoder])?;
Element::link_many(&[&encoder, &payload])?; Element::link_many(&[&encoder, &payload])?;
decoder.connect_pad_added(move |_element, pad| { decoder.connect_pad_added(move |_element, pad| {
debug!("Linking encoder to decoder: {:?}", pad.caps()); debug!("Linking encoder to decoder: {:?}", pad.caps());
@@ -586,8 +592,10 @@ impl NeoMediaFactoryImpl {
self.clientsender.blocking_send(client_data)?; self.clientsender.blocking_send(client_data)?;
// debug!("Pipeline built"); // debug!("Pipeline built");
bin.dynamic_cast::<Element>() let element = bin
.map_err(|_| anyhow!("Cannot cast back")) .dynamic_cast::<Element>()
.map_err(|_| anyhow!("Cannot cast back"))?;
Ok(Some(element))
} }
async fn join(&self) -> AnyResult<()> { async fn join(&self) -> AnyResult<()> {
+113 -266
View File
@@ -43,6 +43,12 @@ struct NeoBuffer {
max_size: usize, 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 { impl NeoBuffer {
fn new(max_size: usize) -> Self { fn new(max_size: usize) -> Self {
Self { Self {
@@ -98,65 +104,21 @@ impl NeoBuffer {
last.data.push(media); last.data.push(media);
} }
while self.buf.len() > self.max_size { while self.buf.len() > self.max_size + HISTORICAL_BUFFER_SIZE {
if self.buf.pop_front().is_none() { if self.buf.pop_front().is_none() {
break; break;
} }
} }
} }
fn prep_size(&self) -> usize {
self.max_size * 2 / 3
}
fn live_size(&self) -> usize { fn live_size(&self) -> usize {
self.max_size / 3 self.max_size
} }
pub(crate) fn ready(&self) -> bool { pub(crate) fn ready(&self) -> bool {
self.buf.len() > self.prep_size() self.buf.len() >= self.live_size() + HISTORICAL_BUFFER_SIZE / 2
} }
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> { fn end_time(&self) -> Option<FrameTime> {
let (fronts, backs) = self.buf.as_slices(); let (fronts, backs) = self.buf.as_slices();
backs backs
@@ -166,35 +128,6 @@ impl NeoBuffer {
.map(|frame| frame.time) .map(|frame| frame.time)
.next() .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 { pub(super) struct NeoMediaSenders {
@@ -288,24 +221,30 @@ impl NeoMediaSenders {
async fn handle_new_data(&mut self, data: BcMedia) -> AnyResult<()> { async fn handle_new_data(&mut self, data: BcMedia) -> AnyResult<()> {
// trace!("Handle new data"); // trace!("Handle new data");
self.update_mediatypes(&data).await; self.update_mediatypes(&data).await;
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),
};
let data = Arc::new(data); let data = Arc::new(data);
let end_time = self.buffer.end_time(); let end_time = self.buffer.end_time();
let frame_time = time; let frame_time = match data.as_ref() {
// Ocassionally the camera will make a jump in timestamps of about 15s (on sub 9s on main) BcMedia::Iframe(BcMediaIframe { microseconds, .. }) => *microseconds as FrameTime,
// This could mean that it runs on some fixed sized buffer 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
if let Some(end_time) = end_time { if let Some(end_time) = end_time {
// An approximate fps
let delta_frame = (self.buffer.buf.back().unwrap().time let delta_frame = (self.buffer.buf.back().unwrap().time
- self.buffer.buf.front().unwrap().time) - self.buffer.buf.front().unwrap().time)
/ self.buffer.buf.len() as i64; / 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_time = frame_time - end_time - delta_frame;
let delta_duration = Duration::from_micros(delta_time.unsigned_abs()); 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) { if delta_duration > Duration::from_secs(1) {
trace!( trace!(
"Reschedule buffer due to jump: {:?}, Prev: {}, New: {}", "Reschedule buffer due to jump: {:?}, Prev: {}, New: {}",
@@ -329,6 +268,8 @@ impl NeoMediaSenders {
for frame in client.buffer.buf.iter_mut() { for frame in client.buffer.buf.iter_mut() {
frame.time = frame.time.saturating_add(delta_time); 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); client.start_time.mod_value(delta_time as f64);
} }
} }
@@ -465,9 +406,6 @@ impl NeoMediaSenders {
}, },
FactoryCommand::JumpToLive => { FactoryCommand::JumpToLive => {
for client in self.client_data.values_mut() { 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; let _ = client.jump_to_live().await;
} }
}, },
@@ -506,16 +444,20 @@ pub(super) struct NeoMediaSender {
start_time: Spring, start_time: Spring,
live_offset: FrameTime, live_offset: FrameTime,
buffer: NeoBuffer, buffer: NeoBuffer,
vid: Option<AppSrc>, vid: Option<Arc<AppSrc>>,
aud: Option<AppSrc>, aud: Option<Arc<AppSrc>>,
command_reciever: Receiver<NeoMediaSenderCommand>, command_reciever: Receiver<NeoMediaSenderCommand>,
command_sender: Sender<NeoMediaSenderCommand>, command_sender: Sender<NeoMediaSenderCommand>,
inited: bool, inited: bool,
playing: bool, playing: bool,
refilling: bool,
use_smoothing: bool, use_smoothing: bool,
} }
enum Buffer {
Video(gstreamer::Buffer),
Audio(gstreamer::Buffer),
}
impl NeoMediaSender { impl NeoMediaSender {
pub(super) fn new(buffer_size: usize, use_smoothing: bool) -> Self { pub(super) fn new(buffer_size: usize, use_smoothing: bool) -> Self {
let (tx, rx) = channel(30); let (tx, rx) = channel(30);
@@ -529,8 +471,7 @@ impl NeoMediaSender {
command_sender: tx, command_sender: tx,
inited: false, inited: false,
playing: true, playing: true,
refilling: false, use_smoothing: use_smoothing && buffer_size > 0,
use_smoothing,
} }
} }
@@ -540,11 +481,11 @@ impl NeoMediaSender {
} }
pub(super) fn update_vid(&mut self, source: AppSrc) { pub(super) fn update_vid(&mut self, source: AppSrc) {
self.vid.replace(source); self.vid.replace(Arc::new(source));
} }
pub(super) fn update_aud(&mut self, source: AppSrc) { pub(super) fn update_aud(&mut self, source: AppSrc) {
self.aud.replace(source); self.aud.replace(Arc::new(source));
} }
pub(super) fn get_commader(&self) -> Sender<NeoMediaSenderCommand> { pub(super) fn get_commader(&self) -> Sender<NeoMediaSenderCommand> {
@@ -553,6 +494,10 @@ impl NeoMediaSender {
fn target_live_for(buffer: &NeoBuffer) -> Option<FrameTime> { fn target_live_for(buffer: &NeoBuffer) -> Option<FrameTime> {
let target_idx = buffer.live_size(); 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<_>>(); let stamps = buffer.buf.iter().map(|item| item.time).collect::<Vec<_>>();
if stamps.len() >= target_idx { if stamps.len() >= target_idx {
@@ -568,12 +513,7 @@ impl NeoMediaSender {
} }
} else { } else {
trace!("Not enough timestamps for target live: {:?}", stamps); trace!("Not enough timestamps for target live: {:?}", stamps);
if let Some(st) = stamps.first() { None
trace!("Setting to 1s behind first frame in buffer");
Some(st - Duration::from_secs(1).as_micros() as FrameTime)
} else {
None
}
} }
} }
@@ -680,20 +620,27 @@ impl NeoMediaSender {
self.buffer.buf.clear(); self.buffer.buf.clear();
let mut buffer_iter = buffer.buf.iter().cloned(); let mut buffer_iter = buffer.buf.iter().cloned();
// The prebuffer should starts from an Iframe
let preprocess = buffer_iter let preprocess = buffer_iter
.take_while_ref(|item| item.time < target_time) .take_while_ref(|item| {
item.time < target_time
|| !matches!(
item.data.first().map(|arc| arc.as_ref()),
Some(BcMedia::Iframe(_))
)
})
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let mut buffer = buffer_iter.collect::<Vec<_>>(); let mut buffer = buffer_iter.collect::<Vec<_>>();
self.start_time.reset_to(target_time as f64); self.start_time.reset_to(target_time as f64);
// Send preprocess now // Send preprocess now
self.send_buffers(preprocess.as_slice()).await?; self.send_buffers(preprocess.as_slice(), true).await?;
trace!("Preprocessed"); debug!("Preprocessed: {}", preprocess.len());
// Send these later // Send these later
for frame in buffer.drain(..) { for frame in buffer.drain(..) {
self.buffer.buf.push_back(frame); self.buffer.buf.push_back(frame);
} }
trace!("Buffer filled"); trace!("Buffer filled: {}", self.buffer.buf.len());
self.jump_to_live().await?; self.jump_to_live().await?;
} else { } else {
@@ -737,22 +684,9 @@ impl NeoMediaSender {
} }
async fn update(&mut self) -> AnyResult<()> { async fn update(&mut self) -> AnyResult<()> {
if self.buffer.buf.len() >= self.buffer.max_size * 9 / 10 { if self.inited && self.playing {
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?; self.update_starttime().await?;
let ignore_stamps = self.buffer.live_size() == 0;
// Check app src is live // Check app src is live
if !self if !self
.vid .vid
@@ -763,17 +697,6 @@ impl NeoMediaSender {
return Err(anyhow!("Vid src is closed")); 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 // Send buffers
let mut buffers = vec![]; let mut buffers = vec![];
if let Some(buftime) = self.get_buftime() { if let Some(buftime) = self.get_buftime() {
@@ -785,7 +708,6 @@ impl NeoMediaSender {
.map(|data| data.time <= buftime) .map(|data| data.time <= buftime)
.unwrap_or(false) .unwrap_or(false)
{ {
tokio::task::yield_now().await;
match self.buffer.buf.pop_front() { match self.buffer.buf.pop_front() {
Some(frame) => { Some(frame) => {
buffers.push(frame); buffers.push(frame);
@@ -797,27 +719,21 @@ impl NeoMediaSender {
tokio::task::yield_now().await; tokio::task::yield_now().await;
// collect certain frames // collect certain frames
self.send_buffers(&buffers).await?; self.send_buffers(&buffers, ignore_stamps).await?;
} }
Ok(()) Ok(())
} }
async fn send_buffers(&mut self, medias: &[Stamped]) -> AnyResult<()> { async fn send_buffers(&mut self, medias: &[Stamped], ignore_stamps: bool) -> AnyResult<()> {
if medias.is_empty() { if medias.is_empty() {
return Ok(()); return Ok(());
} }
tokio::task::yield_now().await; let mut buffers: Vec<Buffer> = vec![];
let mut vid_buffers: Vec<(FrameTime, Vec<u8>)> = vec![];
let mut aud_buffers: Vec<(FrameTime, Vec<u8>)> = vec![];
for media_sets in medias.iter() { for media_sets in medias.iter() {
tokio::task::yield_now().await; tokio::task::yield_now().await;
for media in media_sets.data.iter() { 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() { let data = match media.as_ref() {
BcMedia::Iframe(data) => Some(&data.data), BcMedia::Iframe(data) => Some(&data.data),
BcMedia::Pframe(data) => Some(&data.data), BcMedia::Pframe(data) => Some(&data.data),
@@ -825,140 +741,71 @@ impl NeoMediaSender {
BcMedia::Adpcm(data) => Some(&data.data), BcMedia::Adpcm(data) => Some(&data.data),
_ => None, _ => None,
}; };
if let (Some(data), Some(buffer)) = (data, buffer) { if let Some(buf) = data {
let next_time = media_sets.time; let time = media_sets.time;
if let Some(last) = buffer.last_mut() { let runtime = match (self.get_runtime(), ignore_stamps) {
let last_time = last.0; (None, _) | (_, false) => self.buftime_to_runtime(time),
if next_time == last_time { (Some(runtime), true) => runtime,
last.1.extend(data.iter().copied()); };
} else { trace!(
buffer.push((next_time, data.clone())) " - Sending vid frame at time {} ({:?} Expect: {:?})",
time,
Duration::from_micros(runtime as u64),
self.get_runtime().map(|i| Duration::from_micros(i as u64))
);
let gst_buf = {
let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap();
{
let gst_buf_mut = gst_buf.get_mut().unwrap();
let time = ClockTime::from_useconds(runtime.try_into().unwrap());
gst_buf_mut.set_dts(time);
gst_buf_mut.set_pts(time);
let mut gst_buf_data = gst_buf_mut.map_writable().unwrap();
gst_buf_data.copy_from_slice(buf.as_slice());
} }
} else { gst_buf
buffer.push((next_time, data.clone())) };
match media.as_ref() {
BcMedia::Iframe(_) | BcMedia::Pframe(_) => {
buffers.push(Buffer::Video(gst_buf));
}
BcMedia::Aac(_) | BcMedia::Adpcm(_) => {
buffers.push(Buffer::Audio(gst_buf));
}
_ => {}
} }
} }
} }
} }
tokio::task::yield_now().await; tokio::task::yield_now().await;
tokio::try_join!( for buf in buffers.drain(..) {
async { let buf_app = match (buf, self.vid.as_ref(), self.aud.as_ref()) {
if !vid_buffers.is_empty() { (Buffer::Video(buf), Some(app), _) => Some((buf, app.clone())),
// debug!("Sending video buffers: {}", vid_buffers.len()); (Buffer::Audio(buf), _, Some(app)) => Some((buf, app.clone())),
if let Some(appsrc) = self.vid.clone() { _ => None,
let buffers = { };
let mut buffers = gstreamer::BufferList::new_sized(vid_buffers.len()); if let Some((buf, appsrc)) = buf_app {
{ let res = tokio::task::spawn_blocking(move || {
let buffers_ref = buffers.get_mut().unwrap(); appsrc
for (time, buf) in vid_buffers.drain(..) { .push_buffer(buf.copy())
tokio::task::yield_now().await; .map(|_| ())
let runtime = self.buftime_to_runtime(time); .map_err(|_| anyhow!("Could not push buffer to appsrc"))
trace!( })
" - Sending vid frame at time {} ({:?} Expect: {:?})", .await;
time, match &res {
Duration::from_micros(runtime as u64), Err(e) => {
self.get_runtime().map(|i| Duration::from_micros(i as u64)) debug!("Paniced on send buffer list: {:?}", e);
);
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)) => {
AnyResult::Ok(()) debug!("Failed to send buffer list: {:?}", e);
},
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(_)) => {}
AnyResult::Ok(()) };
res??;
} }
)?; }
Ok(()) Ok(())
} }
} }
+5 -1
View File
@@ -363,7 +363,11 @@ impl NeoRtspServerImpl {
match self.medias.write().await.entry(key.clone()) { match self.medias.write().await.entry(key.clone()) {
Entry::Occupied(_occ) => {} Entry::Occupied(_occ) => {}
Entry::Vacant(vac) => { Entry::Vacant(vac) => {
let media = NeoMediaFactory::new(config.buffer_size, config.use_smoothing); let media = NeoMediaFactory::new(
config.buffer_size,
config.use_smoothing,
config.use_splash,
);
let thread_media = media.clone(); let thread_media = media.clone();
self.threads self.threads
.write() .write()
+10
View File
@@ -25,6 +25,7 @@ pub(super) struct NeoMediaShared {
pub(super) buffer_ready: AtomicBool, pub(super) buffer_ready: AtomicBool,
pub(super) buffer_size: AtomicUsize, pub(super) buffer_size: AtomicUsize,
pub(super) use_smoothing: AtomicBool, pub(super) use_smoothing: AtomicBool,
pub(super) splash: AtomicBool,
} }
impl Default for NeoMediaShared { impl Default for NeoMediaShared {
@@ -36,6 +37,7 @@ impl Default for NeoMediaShared {
buffer_ready: AtomicBool::new(false), buffer_ready: AtomicBool::new(false),
buffer_size: AtomicUsize::new(100), buffer_size: AtomicUsize::new(100),
use_smoothing: AtomicBool::new(false), use_smoothing: AtomicBool::new(false),
splash: AtomicBool::new(true),
} }
} }
} }
@@ -56,4 +58,12 @@ impl NeoMediaShared {
pub(super) fn set_use_smoothing(&self, new_value: bool) { pub(super) fn set_use_smoothing(&self, new_value: bool) {
self.use_smoothing.store(new_value, Ordering::Relaxed) 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)
}
} }
+174 -90
View File
@@ -55,6 +55,8 @@
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use futures::stream::FuturesUnordered; use futures::stream::FuturesUnordered;
use log::*; use log::*;
use neolink_core::bc_protocol::{BcCamera, StreamKind};
use std::collections::HashSet;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use tokio_stream::StreamExt; use tokio_stream::StreamExt;
@@ -172,10 +174,14 @@ async fn camera_main(camera: Camera<Disconnected>) -> Result<(), CameraFailureKi
.await .await
.with_context(|| format!("{}: Could not login to camera", name)) .with_context(|| format!("{}: Could not login to camera", name))
.map_err(|e| { .map_err(|e| {
let e_inner = e.downcast_ref::<neolink_core::Error>().unwrap(); let e_inner = e.downcast_ref::<neolink_core::Error>();
match e_inner { match e_inner {
neolink_core::Error::CameraLoginFail => CameraFailureKind::Fatal(e), Some(neolink_core::Error::CameraLoginFail) => CameraFailureKind::Fatal(e),
_ => CameraFailureKind::Retry(e), Some(_) => CameraFailureKind::Retry(e),
None => {
// Timout error usually
CameraFailureKind::Retry(e)
}
} }
})?; })?;
@@ -242,23 +248,153 @@ async fn camera_main(camera: Camera<Disconnected>) -> Result<(), CameraFailureKi
.await; .await;
log::info!("{}: Buffers prepared", name); log::info!("{}: Buffers prepared", name);
let mut active_tags = streaming.shared.get_streams().clone();
let mut motion_pause = false;
loop { loop {
// Wait for error or reason to pause // Wait for error or reason to pause
tokio::select! { let change = tokio::select! {
v = async { v = async {
// Wait for error // Wait for error
streaming.join().await streaming.join().await
} => { }, if ! active_tags.is_empty() => {
info!("Join Pause"); info!("{}: Join Pause", name);
v Ok(StreamChange::StreamError(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 { v = async {
// Wait for motion stop // Wait for motion stop
let mut motion = streaming.get_camera().listen_on_motion().await?; let mut motion = camera.listen_on_motion().await?;
motion.await_stop(Duration::from_secs_f64(streaming.get_config().pause.motion_timeout)).await motion.await_stop(Duration::from_secs_f64(shared.get_config().pause.motion_timeout)).await
}, if streaming.get_config().pause.on_motion => { }, if motion_pause && shared.get_config().pause.on_motion => {
info!("Motion Pause"); info!("{}: Motion Pause", name);
v.map_err(|e| anyhow!("Error while processing motion messages: {:?}", e)) v.map_err(|e| anyhow!("Error while processing motion messages: {:?}", e))?;
Ok(StreamChange::MotionStop)
}, },
v = async { v = async {
// Wait for client to disconnect // Wait for client to disconnect
@@ -266,97 +402,45 @@ async fn camera_main(camera: Camera<Disconnected>) -> Result<(), CameraFailureKi
loop { loop {
inter.tick().await; inter.tick().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; for tag in active_tags.iter() {
// info!("Num clients: {}", total_clients); if rtsp_thread.get_number_of_clients(shared.get_tag_for_stream(tag)).await.map(|n| n == 0).unwrap_or(true) {
if total_clients == 0 { return Result::<_,anyhow::Error>::Ok(StreamChange::ClientStop(*tag))
return Ok(()) }
} }
} }
}, if streaming.get_config().pause.on_disconnect => { }, if shared.get_config().pause.on_disconnect => {
info!("Client Pause"); if let Ok(StreamChange::ClientStop(tag)) = v.as_ref() {
info!("{}: Client Pause:: {:?}", name, tag);
}
v 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 { v = async {
// Wait for motion start // Wait for motion start
let mut motion = paused.get_camera().listen_on_motion().await?; let mut motion = camera.listen_on_motion().await?;
motion.await_start(Duration::ZERO).await motion.await_start(Duration::ZERO).await
}, if paused.get_config().pause.on_motion && !paused.get_config().pause.on_disconnect => { }, if ! motion_pause && shared.get_config().pause.on_motion => {
info!("Motion Resume"); info!("{}: Motion Resume", name);
v.with_context(|| "Error while processing motion messages") v.with_context(|| "Error while processing motion messages")?;
Ok(StreamChange::MotionStart)
}, },
v = async { v = async {
// Wait for client to connect // Wait for client to connect
let mut inter = tokio::time::interval(tokio::time::Duration::from_secs_f32(0.01)); 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 { loop {
inter.tick().await; inter.tick().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; for tag in inactive_tags.iter() {
if total_clients > 0 { if rtsp_thread.get_number_of_clients(shared.get_tag_for_stream(tag)).await.map(|n| n > 0).unwrap_or(false) {
return Ok(()) return Result::<_,anyhow::Error>::Ok(StreamChange::ClientStart(**tag))
}
} }
} }
}, if paused.get_config().pause.on_disconnect && !paused.get_config().pause.on_motion => { }, if shared.get_config().pause.on_disconnect => {
info!("Client Resume"); if let Ok(StreamChange::ClientStart(tag)) = v.as_ref() {
info!("{}: Client Resume:: {:?}", name, tag);
}
v v
}, },
else => { }.with_context(|| format!("{}: Error while streaming", name))
// 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;
}
} }
+1
View File
@@ -15,6 +15,7 @@ impl<T> Camera<T> {
self.shared.config.name.clone() self.shared.config.name.clone()
} }
#[allow(dead_code)]
pub(crate) fn get_config(&self) -> &CameraConfig { pub(crate) fn get_config(&self) -> &CameraConfig {
&self.shared.config &self.shared.config
} }
+2 -1
View File
@@ -3,6 +3,7 @@
// This state has formed the TCP/UDP tunnel // This state has formed the TCP/UDP tunnel
// but has not logged in // but has not logged in
use super::{camera::Camera, disconnected::Disconnected, loggedin::LoggedIn}; use super::{camera::Camera, disconnected::Disconnected, loggedin::LoggedIn};
use crate::utils::timeout;
use anyhow::Result; use anyhow::Result;
use neolink_core::bc_protocol::{BcCamera, MaxEncryption}; use neolink_core::bc_protocol::{BcCamera, MaxEncryption};
@@ -28,7 +29,7 @@ impl Camera<Connected> {
_ => MaxEncryption::Aes, _ => MaxEncryption::Aes,
}; };
self.state.camera.login_with_maxenc(max_encryption).await?; timeout(self.state.camera.login_with_maxenc(max_encryption)).await??;
Ok(Camera { Ok(Camera {
shared: self.shared, shared: self.shared,
state: LoggedIn { state: LoggedIn {
+1
View File
@@ -93,6 +93,7 @@ impl Camera<LoggedIn> {
Ok(()) Ok(())
} }
#[allow(dead_code)]
pub(crate) fn get_camera(&self) -> &BcCamera { pub(crate) fn get_camera(&self) -> &BcCamera {
&self.state.camera &self.state.camera
} }
+6
View File
@@ -102,6 +102,12 @@ impl Shared {
.map(|k| self.get_tag_for_stream(k)) .map(|k| self.get_tag_for_stream(k))
.collect() .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 { pub(crate) fn get_tag_for_stream(&self, stream: &Stream) -> String {
format!("{}::{:?}", self.config.name, stream) format!("{}::{:?}", self.config.name, stream)
} }
+100 -67
View File
@@ -2,11 +2,16 @@
// //
// Data is streamed into a gstreamer source // Data is streamed into a gstreamer source
use std::collections::HashMap;
use futures::stream::{FuturesUnordered, StreamExt};
use anyhow::{anyhow, Context, Error, Result}; use anyhow::{anyhow, Context, Error, Result};
use log::*; use log::*;
use neolink_core::bcmedia::model::BcMedia; use neolink_core::bcmedia::model::BcMedia;
use tokio::sync::RwLock;
use tokio::task::JoinHandle;
use tokio::time::{timeout, Duration}; use tokio::time::{timeout, Duration};
use tokio::{sync::RwLock, task::JoinSet};
use neolink_core::bc_protocol::{BcCamera, StreamKind as Stream}; use neolink_core::bc_protocol::{BcCamera, StreamKind as Stream};
@@ -15,7 +20,7 @@ use crate::rtsp::gst::FactoryCommand;
pub(crate) struct Streaming { pub(crate) struct Streaming {
pub(crate) camera: BcCamera, pub(crate) camera: BcCamera,
set: RwLock<JoinSet<Result<()>>>, stream_handles: RwLock<HashMap<Stream, JoinHandle<Result<()>>>>,
} }
impl Camera<Streaming> { impl Camera<Streaming> {
@@ -23,74 +28,98 @@ impl Camera<Streaming> {
// Create new gst outputs // Create new gst outputs
// //
// Otherwise use those already present // Otherwise use those already present
let mut set: JoinSet<Result<()>> = Default::default(); let mut me = Camera {
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, shared: loggedin.shared,
state: Streaming { state: Streaming {
camera: loggedin.state.camera, camera: loggedin.state.camera,
set: RwLock::new(set), stream_handles: Default::default(),
}, },
}) };
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>> { pub(crate) async fn stop(self) -> Result<Camera<LoggedIn>> {
self.state.set.into_inner().abort_all(); self.state
.stream_handles
.into_inner()
.into_values()
.for_each(|h| h.abort());
Ok(Camera { Ok(Camera {
shared: self.shared, shared: self.shared,
state: LoggedIn { state: LoggedIn {
@@ -102,15 +131,19 @@ impl Camera<Streaming> {
pub(crate) async fn join(&self) -> Result<()> { pub(crate) async fn join(&self) -> Result<()> {
tokio::select! { tokio::select! {
v = async { v = async {
let mut locked_threads = self.state.set.write().await; let mut locked_threads = self.state.stream_handles.write().await;
while let Some(res) = locked_threads.join_next().await { let mut thread_joins = locked_threads.iter_mut().map(|(_, t)| t).collect::<FuturesUnordered::<_>>();
while let Some(res) = thread_joins.next().await {
match res { match res {
Err(e) => { Err(e) => {
locked_threads.abort_all(); drop(thread_joins);
locked_threads.iter_mut().for_each(|(_,h)| h.abort());
return Err(e.into()); return Err(e.into());
} }
Ok(Err(e)) => { Ok(Err(e)) => {
locked_threads.abort_all(); drop(thread_joins);
locked_threads.iter_mut().for_each(|(_,h)| h.abort());
return Err(e); return Err(e);
} }
Ok(Ok(())) => {} Ok(Ok(())) => {}
+9 -3
View File
@@ -13,6 +13,13 @@ use std::{
str::FromStr, 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 { pub(crate) enum AddressOrUid {
Address(String), Address(String),
Uid(String, DiscoveryMethods), Uid(String, DiscoveryMethods),
@@ -133,10 +140,9 @@ pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result<Bc
_ => MaxEncryption::Aes, _ => MaxEncryption::Aes,
}; };
info!("{}: Logging in", camera_config.name); info!("{}: Logging in", camera_config.name);
camera timeout(camera.login_with_maxenc(max_encryption))
.login_with_maxenc(max_encryption)
.await .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); info!("{}: Connected and logged in", camera_config.name);