Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4fcaf4d538 | ||
|
|
70e62170a9 | ||
|
|
92447b63b8 | ||
|
|
1bcf1cfe85 | ||
|
|
aef898c471 | ||
|
|
0bbd334a78 | ||
|
|
80e705bd60 | ||
|
|
19c2031691 | ||
|
|
52c4515e62 | ||
|
|
8d3c0af7af | ||
|
|
f4d7bebbf1 | ||
|
|
e04c2a10f0 | ||
|
|
1dc25da8f2 | ||
|
|
df3b36954c | ||
|
|
d12d17c052 | ||
|
|
c0d0f396b0 | ||
|
|
7fccda4aa7 | ||
|
|
17846c7bfc | ||
|
|
8adae665fb | ||
|
|
a5a3cf9715 | ||
|
|
ac0703dbfd | ||
|
|
fa155df974 | ||
|
|
e7b9aee122 | ||
|
|
4f2a010e33 | ||
|
|
f1c35a1809 | ||
|
|
a2bec57251 | ||
|
|
8ead7ad2fc | ||
|
|
bd2a3b4ebc | ||
|
|
c37cedf183 | ||
|
|
1fe1ce5046 | ||
|
|
7ebe73b226 | ||
|
|
7dae880bb2 | ||
|
|
438d2a71e1 | ||
|
|
0f76622b17 | ||
|
|
9945b02fd9 | ||
|
|
f514733706 | ||
|
|
bd9da2620b | ||
|
|
6d0d290644 | ||
|
|
a3aa3c4556 | ||
|
|
f253100ea7 | ||
|
|
ad5d09045c | ||
|
|
8bd560b04e |
No files matched your search
@@ -183,7 +183,7 @@ jobs:
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
id: tags
|
||||
run: |
|
||||
branch="${GITHUB_REF#refs/heads/}"
|
||||
branch="$(echo "${GITHUB_REF#refs/heads/}" | sed -E 's|[/]|-|g')"
|
||||
tags="${REPO_NAME}:${branch}"
|
||||
if [ "${branch}" == "master" ]; then
|
||||
tags="${tags},${REPO_NAME}:latest"
|
||||
|
||||
@@ -14,3 +14,9 @@
|
||||
|
||||
# Committing IntelliJ project files is a violation of intergalactic law
|
||||
.idea/
|
||||
|
||||
# MacOS
|
||||
.DS_Store
|
||||
._.DS_Store
|
||||
**/.DS_Store
|
||||
**/._.DS_Store
|
||||
Generated
+240
-14
@@ -139,9 +139,9 @@ checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "1.2.1"
|
||||
version = "1.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
|
||||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||
|
||||
[[package]]
|
||||
name = "bitvec"
|
||||
@@ -240,7 +240,7 @@ dependencies = [
|
||||
"atty",
|
||||
"bitflags",
|
||||
"strsim",
|
||||
"textwrap",
|
||||
"textwrap 0.11.0",
|
||||
"unicode-width",
|
||||
"vec_map",
|
||||
]
|
||||
@@ -349,6 +349,31 @@ dependencies = [
|
||||
"lazy_static",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossterm"
|
||||
version = "0.25.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"crossterm_winapi",
|
||||
"libc",
|
||||
"mio",
|
||||
"parking_lot",
|
||||
"signal-hook",
|
||||
"signal-hook-mio",
|
||||
"winapi 0.3.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossterm_winapi"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ae1b35a484aa10e07fe0638d02301c5ad24de82d310ccbd2f3693da5f09bf1c"
|
||||
dependencies = [
|
||||
"winapi 0.3.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "delegate"
|
||||
version = "0.9.0"
|
||||
@@ -399,12 +424,42 @@ dependencies = [
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.2.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1"
|
||||
dependencies = [
|
||||
"errno-dragonfly",
|
||||
"libc",
|
||||
"winapi 0.3.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno-dragonfly"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "event-listener"
|
||||
version = "2.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f7531096570974c3a9dcf9e4b8e1cede1ec26cf5046219fb3b9d897503b9be59"
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "1.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be"
|
||||
dependencies = [
|
||||
"instant",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
@@ -904,6 +959,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hex-string"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "848ec2dd093df965a34b434580d94852197fc83feac5b2c1962399bbf2cb4f0b"
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "0.2.6"
|
||||
@@ -961,6 +1022,25 @@ dependencies = [
|
||||
"unindent",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "instant"
|
||||
version = "0.1.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "io-lifetimes"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1abeb7a0dd0f8181267ff8adc397075586500b81b28a73e8a0208b00fc170fb3"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.45.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.9.0"
|
||||
@@ -1016,6 +1096,12 @@ version = "0.2.139"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f051f77a7c8e6957c0696eac88f26b0117e54f52d3fc682ab19397a8812846a4"
|
||||
|
||||
[[package]]
|
||||
name = "local-ip-address"
|
||||
version = "0.4.4"
|
||||
@@ -1090,7 +1176,7 @@ dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"wasi 0.11.0+wasi-snapshot-preview1",
|
||||
"windows-sys",
|
||||
"windows-sys 0.42.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1120,7 +1206,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "neolink"
|
||||
version = "0.5.2"
|
||||
version = "0.5.5"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"anyhow",
|
||||
@@ -1137,6 +1223,7 @@ dependencies = [
|
||||
"gstreamer-app",
|
||||
"gstreamer-rtsp",
|
||||
"gstreamer-rtsp-server",
|
||||
"hex-string",
|
||||
"itertools",
|
||||
"lazy_static",
|
||||
"log",
|
||||
@@ -1144,6 +1231,7 @@ dependencies = [
|
||||
"neolink_core",
|
||||
"nom",
|
||||
"regex",
|
||||
"requestty",
|
||||
"rumqttc",
|
||||
"serde",
|
||||
"socket2 0.3.19",
|
||||
@@ -1160,7 +1248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "neolink_core"
|
||||
version = "0.5.2"
|
||||
version = "0.5.5"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"assert_matches",
|
||||
@@ -1184,6 +1272,7 @@ dependencies = [
|
||||
"nom",
|
||||
"rand",
|
||||
"regex",
|
||||
"serde",
|
||||
"socket2 0.3.19",
|
||||
"time",
|
||||
"tokio",
|
||||
@@ -1249,9 +1338,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.8.0"
|
||||
version = "1.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56"
|
||||
checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3"
|
||||
|
||||
[[package]]
|
||||
name = "opaque-debug"
|
||||
@@ -1288,7 +1377,7 @@ dependencies = [
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"windows-sys",
|
||||
"windows-sys 0.42.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1469,6 +1558,32 @@ version = "0.6.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b"
|
||||
|
||||
[[package]]
|
||||
name = "requestty"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fa883a1f3e288e65187f653e6ba2e84fdf810fe02f4c8074f9c723d1aa26e2ae"
|
||||
dependencies = [
|
||||
"requestty-ui",
|
||||
"shell-words",
|
||||
"smallvec",
|
||||
"tempfile",
|
||||
"winsplit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "requestty-ui"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7549bab39cf982b629b68e7ec191a5574e85086e95c0ebe514c02d3b42ffe225"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"crossterm",
|
||||
"once_cell",
|
||||
"textwrap 0.15.2",
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.16.20"
|
||||
@@ -1511,6 +1626,20 @@ dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.36.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f43abb88211988493c1abb44a70efa56ff0ce98f233b7b276146f1f3f7ba9644"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"io-lifetimes",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.45.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.19.1"
|
||||
@@ -1604,6 +1733,33 @@ version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2579985fda508104f7587689507983eadd6a6e84dd35d6d115361f530916fa0d"
|
||||
|
||||
[[package]]
|
||||
name = "shell-words"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde"
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook"
|
||||
version = "0.3.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "732768f1176d21d09e076c23a93123d40bba92d50c4058da34d45c8de8e682b9"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"signal-hook-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-mio"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"mio",
|
||||
"signal-hook",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.0"
|
||||
@@ -1628,6 +1784,12 @@ version = "1.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"
|
||||
|
||||
[[package]]
|
||||
name = "smawk"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f67ad224767faa3c7d8b6d91985b78e70a1324408abcb1cfcc2be4c06bc06043"
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.3.19"
|
||||
@@ -1791,6 +1953,19 @@ version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af18f7ae1acd354b992402e9ec5864359d693cd8a79dcbef59f76891701c1e95"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"fastrand",
|
||||
"redox_syscall",
|
||||
"rustix",
|
||||
"windows-sys 0.42.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "termcolor"
|
||||
version = "1.1.2"
|
||||
@@ -1809,6 +1984,17 @@ dependencies = [
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "textwrap"
|
||||
version = "0.15.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b7b3e525a49ec206798b40326a44121291b530c963cfb01018f63e135bac543d"
|
||||
dependencies = [
|
||||
"smawk",
|
||||
"unicode-linebreak",
|
||||
"unicode-width",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.37"
|
||||
@@ -1899,7 +2085,7 @@ dependencies = [
|
||||
"signal-hook-registry",
|
||||
"socket2 0.4.7",
|
||||
"tokio-macros",
|
||||
"windows-sys",
|
||||
"windows-sys 0.42.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2004,6 +2190,16 @@ version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-linebreak"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c5faade31a542b8b35855fff6e8def199853b2da8da256da52f52f1316ee3137"
|
||||
dependencies = [
|
||||
"hashbrown",
|
||||
"regex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-normalization"
|
||||
version = "0.1.19"
|
||||
@@ -2015,15 +2211,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "unicode-segmentation"
|
||||
version = "1.8.0"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8895849a949e7845e06bd6dc1aa51731a103c42707010a5b591c0038fb73385b"
|
||||
checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.1.8"
|
||||
version = "0.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3"
|
||||
checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
@@ -2252,6 +2448,30 @@ dependencies = [
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.45.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
|
||||
dependencies = [
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.42.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e2522491fbfcd58cc84d47aeb2958948c4b8982e9a2d8a2a35bbaed431390e7"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.42.1"
|
||||
@@ -2310,6 +2530,12 @@ version = "0.42.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd"
|
||||
|
||||
[[package]]
|
||||
name = "winsplit"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ab703352da6a72f35c39a533526393725640575bb211f61987a2748323ad956"
|
||||
|
||||
[[package]]
|
||||
name = "wyz"
|
||||
version = "0.2.0"
|
||||
|
||||
+10
-2
@@ -1,17 +1,23 @@
|
||||
[package]
|
||||
name = "neolink"
|
||||
description = "A standards-compliant bridge to Reolink IP cameras"
|
||||
version = "0.5.2"
|
||||
version = "0.5.5"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
default-run = "neolink"
|
||||
|
||||
[workspace]
|
||||
members = [
|
||||
"crates/*",
|
||||
]
|
||||
|
||||
[[bin]]
|
||||
name = "decoder"
|
||||
test = false
|
||||
bench = false
|
||||
|
||||
[dependencies]
|
||||
neolink_core = { path = "crates/core", version = "0.5.2" }
|
||||
neolink_core = { path = "crates/core", version = "0.5.5" }
|
||||
aes = "0.6"
|
||||
cfb-mode = "0.6"
|
||||
cookie-factory = "0.3"
|
||||
@@ -45,3 +51,5 @@ tokio = { version = "1.0", features = ["rt", "macros", "io-util"] }
|
||||
anyhow = "1.0.42"
|
||||
async-trait = "0.1.64"
|
||||
futures = "0.3.26"
|
||||
hex-string = "0.1.0"
|
||||
requestty = "0.5.0"
|
||||
@@ -26,12 +26,15 @@ with additional features not yet in upstream master.
|
||||
- MQTT
|
||||
- Motion Detection
|
||||
- Paused Streams (when no rtsp client or no motion detected)
|
||||
- Save a still image to disk
|
||||
|
||||
**Minor Features**:
|
||||
|
||||
- Improved error messages when your missing gstreamer plugins
|
||||
- Protocol more closely follows offical reolink format
|
||||
- Possibly can handle more simulatenous connections
|
||||
- More ways to connect to the camera. Including Relaying through reolink servers
|
||||
- Camera battery levels can be displayed in the log
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -127,10 +130,10 @@ Control messages:
|
||||
Status Messages:
|
||||
`/status offline` Sent when the neolink goes offline this is a LastWill message
|
||||
`/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` send an XML encoded version of the battery status
|
||||
|
||||
Query Messages:
|
||||
`/query/battery` Request that the camera reports its battery level (Not Yet Implemented)
|
||||
`/query/battery` Request that the camera reports its battery level
|
||||
|
||||
### Pause
|
||||
|
||||
@@ -157,6 +160,19 @@ Then start the rtsp server as usual:
|
||||
./neolink rtsp --config=neolink.toml
|
||||
```
|
||||
|
||||
### Battery Levels
|
||||
|
||||
If you have a battery camera and would like to see the battery messages in the log
|
||||
add the following to your config
|
||||
|
||||
```toml
|
||||
[[cameras]]
|
||||
# Usual camera options like uid etc
|
||||
print_format = "Human"
|
||||
```
|
||||
|
||||
You can also print into xml format with `print_format = "Xml"` which can then be passed
|
||||
by a script for processing.
|
||||
|
||||
### Docker
|
||||
|
||||
@@ -167,6 +183,20 @@ in multiple architectures. The latest tag tracks master while each branch gets i
|
||||
docker pull quantumentangledandy/neolink
|
||||
```
|
||||
|
||||
### Image
|
||||
|
||||
You can write an image from the stream to disk using:
|
||||
|
||||
|
||||
```bash
|
||||
neolink image --config=config.toml --file-path=filepath CameraName
|
||||
```
|
||||
|
||||
Where filepath is the path to save the image to and CameraName is the name of the camera
|
||||
from the config to save the image from.
|
||||
|
||||
File is always jpeg and the extension given in filepath will be added or changed to reflect this.
|
||||
|
||||
## License
|
||||
|
||||
Neolink is free software, released under the GNU Affero General Public License
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "neolink_core"
|
||||
description = "Core services and structure for Reolink IP cameras"
|
||||
version = "0.5.2"
|
||||
version = "0.5.5"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
@@ -25,6 +25,7 @@ md5 = "0.7"
|
||||
nom = { version = "6.1.2", features = ["alloc"] }
|
||||
rand = "0.8.4"
|
||||
regex = "1.5.4"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
socket2 = "0.3"
|
||||
time = "0.2"
|
||||
tokio = { version = "1.24.2", features = ["full"] }
|
||||
|
||||
@@ -27,7 +27,15 @@ impl Encoder<Bc> for BcCodex {
|
||||
fn encode(&mut self, item: Bc, dst: &mut BytesMut) -> Result<()> {
|
||||
// let context = self.context.read().unwrap();
|
||||
let buf: Vec<u8> = Default::default();
|
||||
let buf = item.serialize(buf, self.context.get_encrypted())?;
|
||||
let enc_protocol: EncryptionProtocol = match self.context.get_encrypted() {
|
||||
EncryptionProtocol::Aes(_) if item.meta.msg_id == 1 => {
|
||||
// During login the encyption protocol cannot go higher than BCEncrypt
|
||||
// even if we support AES. (BUt it can go lower i.e. None)
|
||||
EncryptionProtocol::BCEncrypt
|
||||
}
|
||||
n => *n,
|
||||
};
|
||||
let buf = item.serialize(buf, &enc_protocol)?;
|
||||
dst.reserve(buf.len());
|
||||
dst.extend_from_slice(buf.as_slice());
|
||||
Ok(())
|
||||
|
||||
@@ -160,7 +160,13 @@ fn bc_modern_msg<'a>(
|
||||
response_code,
|
||||
..
|
||||
} if (response_code & 0xff) == 0x02 => EncryptionProtocol::BCEncrypt, // This is AES but the first packet with the NONCE is BCEcrypt, since the NONCE in this packet is required to build the AES key
|
||||
_ => context.get_encrypted().clone(),
|
||||
BcHeader { msg_id: 1, .. }
|
||||
if matches!(context.get_encrypted(), EncryptionProtocol::Aes(_)) =>
|
||||
{
|
||||
// Maximum encryption level is BCEncrypt during login... Not sure why Reolink did it like that
|
||||
EncryptionProtocol::BCEncrypt
|
||||
}
|
||||
_ => *context.get_encrypted(),
|
||||
};
|
||||
|
||||
let processed_payload_buf =
|
||||
|
||||
@@ -47,6 +47,10 @@ pub const MSG_ID_GET_LED_STATUS: u32 = 208;
|
||||
pub const MSG_ID_SET_LED_STATUS: u32 = 209;
|
||||
/// UDP Keep alive
|
||||
pub const MSG_ID_UDP_KEEP_ALIVE: u32 = 234;
|
||||
/// Battery message initiaed by the camera
|
||||
pub const MSG_ID_BATTERY_INFO_LIST: u32 = 252;
|
||||
/// Battery message initiaed by the client
|
||||
pub const MSG_ID_BATTERY_INFO: u32 = 253;
|
||||
|
||||
/// An empty password in legacy format
|
||||
pub const EMPTY_LEGACY_PASSWORD: &str =
|
||||
@@ -169,7 +173,7 @@ pub(super) struct BcSendInfo {
|
||||
/// These are the encyption modes supported by the camera
|
||||
///
|
||||
/// The mode is negotiated during login
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum EncryptionProtocol {
|
||||
/// Older camera use no encryption
|
||||
Unencrypted,
|
||||
|
||||
@@ -76,6 +76,12 @@ pub struct BcXml {
|
||||
/// Sent to move the camera
|
||||
#[yaserde(rename = "PtzControl")]
|
||||
pub ptz_control: Option<PtzControl>,
|
||||
/// Recieved on login/low battery events
|
||||
#[yaserde(rename = "BatteryList")]
|
||||
pub battery_list: Option<BatteryList>,
|
||||
/// Recieved on request for battery info
|
||||
#[yaserde(rename = "BatteryInfo")]
|
||||
pub battery_info: Option<BatteryInfo>,
|
||||
}
|
||||
|
||||
impl BcXml {
|
||||
@@ -463,6 +469,47 @@ pub struct PtzControl {
|
||||
pub command: String,
|
||||
}
|
||||
|
||||
/// A list of battery infos. This message is sent from the camera as
|
||||
/// an event
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct BatteryList {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// Battery info items
|
||||
#[yaserde(rename = "BatteryInfo")]
|
||||
pub battery_info: Vec<BatteryInfo>,
|
||||
}
|
||||
|
||||
/// The individual battery info
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct BatteryInfo {
|
||||
/// The channel the for the camera usually 0
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: u8,
|
||||
/// Charge status known values, "chargeComplete", "charging", "none",
|
||||
#[yaserde(rename = "chargeStatus")]
|
||||
pub charge_status: String,
|
||||
/// Status of charging port known values: "solarPanel"
|
||||
#[yaserde(rename = "adapterStatus")]
|
||||
pub adapter_status: String,
|
||||
/// Voltage
|
||||
pub voltage: i32,
|
||||
/// Current
|
||||
pub current: i32,
|
||||
/// Temperture
|
||||
pub temperature: i32,
|
||||
/// % charge from 0-100
|
||||
#[yaserde(rename = "batteryPercent")]
|
||||
pub battery_percent: u32,
|
||||
/// Low power flag. Known values 0, 1 (0=false)
|
||||
#[yaserde(rename = "lowPower")]
|
||||
pub low_power: u32,
|
||||
/// Battery version info: Known values 2
|
||||
#[yaserde(rename = "batteryVersion")]
|
||||
pub battery_version: u32,
|
||||
}
|
||||
|
||||
/// Convience function to return the xml version used throughout the library
|
||||
pub fn xml_ver() -> String {
|
||||
"1.1".to_string()
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
use crate::{bc, Credentials};
|
||||
use crate::bc;
|
||||
use futures::stream::StreamExt;
|
||||
use log::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::ToSocketAddrs;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};
|
||||
|
||||
use Md5Trunc::*;
|
||||
|
||||
mod battery;
|
||||
mod connection;
|
||||
mod credentials;
|
||||
mod errors;
|
||||
mod keepalive;
|
||||
mod ledstate;
|
||||
mod login;
|
||||
mod logout;
|
||||
@@ -23,8 +27,10 @@ mod time;
|
||||
mod version;
|
||||
|
||||
pub(crate) use connection::*;
|
||||
pub(crate) use credentials::*;
|
||||
pub use errors::Error;
|
||||
pub use ledstate::LightState;
|
||||
pub use login::MaxEncryption;
|
||||
pub use motion::{MotionData, MotionStatus};
|
||||
pub use pirstate::PirState;
|
||||
pub use ptz::Direction;
|
||||
@@ -34,15 +40,6 @@ pub use stream::{StreamData, StreamKind};
|
||||
|
||||
pub(crate) type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
impl From<crossbeam_channel::RecvTimeoutError> for Error {
|
||||
fn from(k: crossbeam_channel::RecvTimeoutError) -> Self {
|
||||
match k {
|
||||
crossbeam_channel::RecvTimeoutError::Timeout => Error::Timeout,
|
||||
crossbeam_channel::RecvTimeoutError::Disconnected => Error::TimeoutDisconnected,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// This is the primary struct of this library when interacting with the camera
|
||||
///
|
||||
@@ -55,6 +52,20 @@ pub struct BcCamera {
|
||||
credentials: Credentials,
|
||||
}
|
||||
|
||||
/// Used to choode the print format of various status messages like battery levels
|
||||
///
|
||||
/// Currently this is just the format of battery levels but if we ever got more status
|
||||
/// messages then they will also use this information
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
pub enum PrintFormat {
|
||||
/// None, don't print
|
||||
None,
|
||||
/// A human readable output
|
||||
Human,
|
||||
/// Xml formatted
|
||||
Xml,
|
||||
}
|
||||
|
||||
impl BcCamera {
|
||||
///
|
||||
/// Create a new camera interface with this address and channel ID
|
||||
@@ -74,6 +85,7 @@ impl BcCamera {
|
||||
channel_id: u8,
|
||||
username: V,
|
||||
passwd: Option<W>,
|
||||
aux_info_format: PrintFormat,
|
||||
) -> Result<Self> {
|
||||
let username: String = username.into();
|
||||
let passwd: Option<String> = passwd.map(|t| t.into());
|
||||
@@ -87,6 +99,7 @@ impl BcCamera {
|
||||
channel_id,
|
||||
&username,
|
||||
passwd.as_ref(),
|
||||
aux_info_format,
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -94,7 +107,7 @@ impl BcCamera {
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::Timeout)
|
||||
Err(Error::CannotInitCamera)
|
||||
}
|
||||
|
||||
///
|
||||
@@ -116,12 +129,14 @@ impl BcCamera {
|
||||
username: U,
|
||||
passwd: Option<V>,
|
||||
discovery_method: DiscoveryMethods,
|
||||
aux_info_format: PrintFormat,
|
||||
) -> Result<Self> {
|
||||
Self::new(
|
||||
SocketAddrOrUid::Uid(uid.to_string(), discovery_method),
|
||||
channel_id,
|
||||
username,
|
||||
passwd,
|
||||
aux_info_format,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -151,6 +166,7 @@ impl BcCamera {
|
||||
channel_id: u8,
|
||||
username: V,
|
||||
passwd: Option<W>,
|
||||
aux_info_format: PrintFormat,
|
||||
) -> Result<Self> {
|
||||
let addr_iter = match host.to_socket_addrs_or_uid() {
|
||||
Ok(iter) => iter,
|
||||
@@ -159,12 +175,20 @@ impl BcCamera {
|
||||
let username: String = username.into();
|
||||
let passwd: Option<String> = passwd.map(|t| t.into());
|
||||
for addr_or_uid in addr_iter {
|
||||
if let Ok(cam) = Self::new(addr_or_uid, channel_id, &username, passwd.as_ref()).await {
|
||||
if let Ok(cam) = Self::new(
|
||||
addr_or_uid,
|
||||
channel_id,
|
||||
&username,
|
||||
passwd.as_ref(),
|
||||
aux_info_format,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(cam);
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::Timeout)
|
||||
Err(Error::CannotInitCamera)
|
||||
}
|
||||
|
||||
///
|
||||
@@ -189,26 +213,29 @@ impl BcCamera {
|
||||
channel_id: u8,
|
||||
username: U,
|
||||
passwd: Option<V>,
|
||||
aux_info_format: PrintFormat,
|
||||
) -> Result<Self> {
|
||||
let username: String = username.into();
|
||||
let passwd: Option<String> = passwd.map(|t| t.into());
|
||||
|
||||
let (sink, source): (BcConnSink, BcConnSource) = match addr {
|
||||
SocketAddrOrUid::SocketAddr(addr) => {
|
||||
debug!("Trying address {}", addr);
|
||||
trace!("Trying address {}", addr);
|
||||
let (x, r) = TcpSource::new(addr, &username, passwd.as_ref())
|
||||
.await?
|
||||
.split();
|
||||
(Box::new(x), Box::new(r))
|
||||
}
|
||||
SocketAddrOrUid::Uid(uid, method) => {
|
||||
debug!("Trying uid {}", uid);
|
||||
trace!("Trying uid {}", uid);
|
||||
// TODO Make configurable
|
||||
let (allow_local, allow_remote, allow_relay) = match method {
|
||||
DiscoveryMethods::None => (false, false, false),
|
||||
DiscoveryMethods::Local => (true, false, false),
|
||||
DiscoveryMethods::Remote => (true, true, false),
|
||||
DiscoveryMethods::Relay => (true, true, true),
|
||||
let (allow_local, allow_remote, allow_map, allow_relay) = match method {
|
||||
DiscoveryMethods::None => (false, false, false, false),
|
||||
DiscoveryMethods::Local => (true, false, false, false),
|
||||
DiscoveryMethods::Remote => (true, true, false, false),
|
||||
DiscoveryMethods::Map => (true, true, true, false),
|
||||
DiscoveryMethods::Relay => (true, true, true, true),
|
||||
DiscoveryMethods::Debug => (false, false, false, true),
|
||||
};
|
||||
|
||||
let discovery = {
|
||||
@@ -216,10 +243,10 @@ impl BcCamera {
|
||||
if allow_local {
|
||||
let uid_local = uid.clone();
|
||||
set.spawn(async move {
|
||||
debug!("Starting Local discovery");
|
||||
trace!("Starting Local discovery");
|
||||
let result = Discovery::local(&uid_local).await;
|
||||
if let Ok(disc) = &result {
|
||||
debug!(
|
||||
info!(
|
||||
"Local discovery success {} at {}",
|
||||
uid_local,
|
||||
disc.get_addr()
|
||||
@@ -231,10 +258,10 @@ impl BcCamera {
|
||||
if allow_remote {
|
||||
let uid_remote = uid.clone();
|
||||
set.spawn(async move {
|
||||
debug!("Starting Remote discovery");
|
||||
trace!("Starting Remote discovery");
|
||||
let result = Discovery::remote(&uid_remote).await;
|
||||
if let Ok(disc) = &result {
|
||||
debug!(
|
||||
info!(
|
||||
"Remote discovery success {} at {}",
|
||||
uid_remote,
|
||||
disc.get_addr()
|
||||
@@ -243,13 +270,24 @@ impl BcCamera {
|
||||
result
|
||||
});
|
||||
}
|
||||
if allow_map {
|
||||
let uid_relay = uid.clone();
|
||||
set.spawn(async move {
|
||||
trace!("Starting Map");
|
||||
let result = Discovery::map(&uid_relay).await;
|
||||
if let Ok(disc) = &result {
|
||||
info!("Map success {} at {}", uid_relay, disc.get_addr());
|
||||
}
|
||||
result
|
||||
});
|
||||
}
|
||||
if allow_relay {
|
||||
let uid_relay = uid.clone();
|
||||
set.spawn(async move {
|
||||
debug!("Starting Relay");
|
||||
trace!("Starting Relay");
|
||||
let result = Discovery::relay(&uid_relay).await;
|
||||
if let Ok(disc) = &result {
|
||||
debug!("Relay success {} at {}", uid_relay, disc.get_addr());
|
||||
info!("Relay success {} at {}", uid_relay, disc.get_addr());
|
||||
}
|
||||
result
|
||||
});
|
||||
@@ -289,7 +327,7 @@ impl BcCamera {
|
||||
|
||||
let conn = BcConnection::new(sink, source).await?;
|
||||
|
||||
debug!("Success");
|
||||
trace!("Success");
|
||||
let me = Self {
|
||||
connection: Arc::new(conn),
|
||||
message_num: AtomicU16::new(0),
|
||||
@@ -297,6 +335,8 @@ impl BcCamera {
|
||||
logged_in: AtomicBool::new(false),
|
||||
credentials: Credentials::new(username, passwd),
|
||||
};
|
||||
me.keepalive().await?;
|
||||
me.monitor_battery(aux_info_format).await?;
|
||||
Ok(me)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! Handles battery related messages
|
||||
//!
|
||||
//! There are primarily two messages:
|
||||
//! - BatteryInfoList which the camera sends as part of its login info
|
||||
//! - BatteryInfo which the client can request on demand
|
||||
//!
|
||||
|
||||
use super::{BcCamera, PrintFormat, Result};
|
||||
use crate::{
|
||||
bc::{model::*, xml::BatteryInfo},
|
||||
Error,
|
||||
};
|
||||
|
||||
impl BcCamera {
|
||||
/// Create a handller to respond to battery messages
|
||||
/// These messages are sent by the camera on login and maybe
|
||||
/// also on low battery events
|
||||
pub async fn monitor_battery(&self, format: PrintFormat) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
connection
|
||||
.handle_msg(MSG_ID_BATTERY_INFO_LIST, move |bc| {
|
||||
if let Bc {
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
battery_list: Some(battery_list),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}),
|
||||
..
|
||||
} = bc
|
||||
{
|
||||
for battery in battery_list.battery_info.iter() {
|
||||
match format {
|
||||
PrintFormat::None => {}
|
||||
PrintFormat::Human => {
|
||||
println!(
|
||||
"==Battery==\n\
|
||||
Charge: {}%,\n\
|
||||
Temperature: {}°C,\n\
|
||||
LowPower: {},\n\
|
||||
Adapter: {},\n\
|
||||
ChargeStatus: {},\n\
|
||||
",
|
||||
battery.battery_percent,
|
||||
battery.temperature,
|
||||
if battery.low_power == 1 {
|
||||
"true"
|
||||
} else {
|
||||
"false"
|
||||
},
|
||||
battery.adapter_status,
|
||||
battery.charge_status,
|
||||
);
|
||||
}
|
||||
PrintFormat::Xml => {
|
||||
let bat_ser = String::from_utf8(
|
||||
yaserde::ser::serialize_with_writer(
|
||||
battery,
|
||||
vec![],
|
||||
&Default::default(),
|
||||
)
|
||||
.expect("Should Ser the struct"),
|
||||
)
|
||||
.expect("Should be UTF8");
|
||||
println!("{}", bat_ser);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Requests the current battery status of the camera
|
||||
pub async fn battery_info(&self) -> Result<BatteryInfo> {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_BATTERY_INFO,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub.send(msg).await?;
|
||||
let msg = sub.recv().await?;
|
||||
|
||||
if let Bc {
|
||||
meta: BcMeta {
|
||||
response_code: 200, ..
|
||||
},
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
battery_info: Some(battery_info),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}),
|
||||
} = msg
|
||||
{
|
||||
Ok(battery_info)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the battery info (maybe no battery) command.",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -1,5 +1,5 @@
|
||||
use super::BcSubscription;
|
||||
use crate::{bc::model::*, Error, Result};
|
||||
use crate::{bc::model::*, timeout, Error, Result};
|
||||
use futures::sink::{Sink, SinkExt};
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use log::*;
|
||||
@@ -11,7 +11,15 @@ use tokio::sync::Mutex;
|
||||
|
||||
use tokio::{sync::RwLock, task::JoinSet};
|
||||
|
||||
type Subscriber = Arc<RwLock<BTreeMap<u16, Sender<Bc>>>>;
|
||||
type MsgHandler = Box<dyn Fn(&Bc) -> Option<Bc> + Send + Sync>;
|
||||
#[derive(Default)]
|
||||
struct Subscriber {
|
||||
/// Subscribers based on their Num
|
||||
num: RwLock<BTreeMap<u16, Sender<Result<Bc>>>>,
|
||||
/// Subscribers based on their ID
|
||||
id: RwLock<BTreeMap<u32, MsgHandler>>,
|
||||
}
|
||||
|
||||
pub(crate) type BcConnSink = Box<dyn Sink<Bc, Error = Error> + Send + Sync + Unpin>;
|
||||
pub(crate) type BcConnSource = Box<dyn Stream<Item = Result<Bc>> + Send + Sync + Unpin>;
|
||||
|
||||
@@ -22,32 +30,29 @@ pub(crate) type BcConnSource = Box<dyn Stream<Item = Result<Bc>> + Send + Sync +
|
||||
/// There can be only one subscriber per kind of message at a time.
|
||||
pub struct BcConnection {
|
||||
sink: Arc<Mutex<BcConnSink>>,
|
||||
subscribers: Subscriber,
|
||||
subscribers: Arc<Subscriber>,
|
||||
#[allow(dead_code)] // Not dead we just need to hold a reference to keep it alive
|
||||
rx_thread: JoinSet<()>,
|
||||
}
|
||||
|
||||
impl BcConnection {
|
||||
pub async fn new(sink: BcConnSink, mut source: BcConnSource) -> Result<BcConnection> {
|
||||
let subscribers: Subscriber = Default::default();
|
||||
let subscribers: Arc<Subscriber> = Default::default();
|
||||
let sink = Arc::new(Mutex::new(sink));
|
||||
|
||||
let subs = subscribers.clone();
|
||||
|
||||
let mut rx_thread = JoinSet::new();
|
||||
|
||||
let sink_thread = sink.clone();
|
||||
rx_thread.spawn(async move {
|
||||
loop {
|
||||
let packet = source.next().await;
|
||||
let bc = match packet {
|
||||
Some(Ok(bc)) => bc,
|
||||
Some(Err(e)) => {
|
||||
error!("Deserialization error: {:?}", e);
|
||||
break;
|
||||
}
|
||||
Some(res) => res,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
if let Err(e) = Self::poll(bc, &subs).await {
|
||||
if let Err(e) = Self::poll(bc, &subs, &sink_thread).await {
|
||||
error!("Subscription error: {:?}", e);
|
||||
break;
|
||||
}
|
||||
@@ -55,7 +60,7 @@ impl BcConnection {
|
||||
});
|
||||
|
||||
Ok(BcConnection {
|
||||
sink: Arc::new(Mutex::new(sink)),
|
||||
sink,
|
||||
subscribers,
|
||||
rx_thread,
|
||||
})
|
||||
@@ -63,52 +68,118 @@ impl BcConnection {
|
||||
|
||||
pub(super) async fn send(&self, bc: Bc) -> crate::Result<()> {
|
||||
trace!("send Wait: {:?}", bc);
|
||||
self.sink.lock().await.send(bc).await?;
|
||||
timeout(self.sink.lock().await.send(bc)).await??;
|
||||
trace!("send Complete");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn subscribe(&self, msg_num: u16) -> Result<BcSubscription> {
|
||||
let (tx, rx) = channel(100);
|
||||
match self.subscribers.write().await.entry(msg_num) {
|
||||
Entry::Vacant(vac_entry) => vac_entry.insert(tx),
|
||||
Entry::Occupied(_) => return Err(Error::SimultaneousSubscription { msg_num }),
|
||||
match self.subscribers.num.write().await.entry(msg_num) {
|
||||
Entry::Vacant(vac_entry) => {
|
||||
vac_entry.insert(tx);
|
||||
}
|
||||
Entry::Occupied(mut occ_entry) => {
|
||||
if occ_entry.get().is_closed() {
|
||||
occ_entry.insert(tx);
|
||||
} else {
|
||||
return Err(Error::SimultaneousSubscription { msg_num });
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(BcSubscription::new(rx, msg_num, self))
|
||||
Ok(BcSubscription::new(rx, msg_num as u32, self))
|
||||
}
|
||||
|
||||
pub fn unsubscribe(&self, msg_num: u16) -> Result<()> {
|
||||
let subs = self.subscribers.clone();
|
||||
tokio::task::spawn(async move {
|
||||
subs.write().await.remove(&msg_num);
|
||||
});
|
||||
|
||||
/// Some messages are initiated by the camera. This creates a handler for them
|
||||
/// It requires a closure that will be used to handle the message
|
||||
/// and return either None or Some(Bc) reply
|
||||
pub async fn handle_msg<T>(&self, msg_id: u32, handler: T) -> Result<()>
|
||||
where
|
||||
T: Fn(&Bc) -> Option<Bc> + Send + Sync + 'static,
|
||||
{
|
||||
match self.subscribers.id.write().await.entry(msg_id) {
|
||||
Entry::Vacant(vac_entry) => {
|
||||
vac_entry.insert(Box::new(handler));
|
||||
}
|
||||
Entry::Occupied(_) => {
|
||||
return Err(Error::SimultaneousSubscriptionId { msg_id });
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn poll(response: Bc, subscribers: &Subscriber) -> Result<()> {
|
||||
// Don't hold the lock during deserialization so we don't poison the subscribers mutex if
|
||||
// something goes wrong
|
||||
let msg_num = response.meta.msg_num;
|
||||
let msg_id = response.meta.msg_id;
|
||||
/// Stop a message handler created using [`handle_msg`]
|
||||
#[allow(dead_code)] // Currently unused but added for future use
|
||||
pub async fn unhandle_msg(&self, msg_id: u32) -> Result<()> {
|
||||
self.subscribers.id.write().await.remove(&msg_id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let mut remove_it = false;
|
||||
match subscribers.read().await.get(&msg_num) {
|
||||
Some(occ) => {
|
||||
if occ.send(response).await.is_err() {
|
||||
// Exceedingly unlikely, unless you mishandle the subscription object
|
||||
warn!("Subscriber to ID {} dropped their channel", msg_id);
|
||||
remove_it = true;
|
||||
async fn poll(
|
||||
response: Result<Bc>,
|
||||
subscribers: &Subscriber,
|
||||
sink: &Mutex<BcConnSink>,
|
||||
) -> Result<()> {
|
||||
match response {
|
||||
Ok(response) => {
|
||||
let msg_num = response.meta.msg_num;
|
||||
let msg_id = response.meta.msg_id;
|
||||
|
||||
let mut remove_it_num = false;
|
||||
match (
|
||||
subscribers.id.read().await.get(&msg_id),
|
||||
subscribers.num.read().await.get(&msg_num),
|
||||
) {
|
||||
(Some(occ), _) => {
|
||||
if let Some(reply) = occ(&response) {
|
||||
assert!(reply.meta.msg_num == response.meta.msg_num);
|
||||
sink.lock().await.send(reply).await?;
|
||||
}
|
||||
}
|
||||
(None, Some(occ)) => {
|
||||
if occ.capacity() == 0 {
|
||||
warn!("Reaching limit of channel");
|
||||
warn!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
occ.capacity(),
|
||||
occ.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
} else {
|
||||
trace!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
occ.capacity(),
|
||||
occ.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
}
|
||||
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 {
|
||||
subscribers.num.write().await.remove(&msg_num);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
debug!("Ignoring uninteresting message num {}", msg_id);
|
||||
trace!("Contents: {:?}", response);
|
||||
Err(e) => {
|
||||
for sub in subscribers.num.read().await.values() {
|
||||
let _ = sub.send(Err(e.clone())).await;
|
||||
}
|
||||
subscribers.num.write().await.clear();
|
||||
subscribers.id.write().await.clear();
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
if remove_it {
|
||||
subscribers.write().await.remove(&msg_num);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::BcConnection;
|
||||
use crate::bcmedia::codex::BcMediaCodex;
|
||||
use crate::{bc::model::*, Error, Result};
|
||||
use crate::{bc::model::*, timeout, Error, Result};
|
||||
use futures::stream::{IntoAsyncRead, Stream, StreamExt, TryStreamExt};
|
||||
use std::io::Result as IoResult;
|
||||
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
@@ -11,21 +11,21 @@ use tokio_util::codec::FramedRead;
|
||||
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
|
||||
|
||||
pub struct BcSubscription<'a> {
|
||||
rx: ReceiverStream<Bc>,
|
||||
msg_num: u16,
|
||||
rx: ReceiverStream<Result<Bc>>,
|
||||
msg_num: u32,
|
||||
conn: &'a BcConnection,
|
||||
}
|
||||
|
||||
pub struct BcStream<'a> {
|
||||
rx: &'a mut ReceiverStream<Bc>,
|
||||
rx: &'a mut ReceiverStream<Result<Bc>>,
|
||||
}
|
||||
|
||||
impl<'a> Unpin for BcStream<'a> {}
|
||||
|
||||
impl<'a> Stream for BcStream<'a> {
|
||||
type Item = Bc;
|
||||
type Item = Result<Bc>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Bc>> {
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Bc>>> {
|
||||
let mut this = self.as_mut();
|
||||
match Pin::new(&mut this.rx).poll_next(cx) {
|
||||
Poll::Ready(Some(bc)) => Poll::Ready(Some(bc)),
|
||||
@@ -36,7 +36,7 @@ impl<'a> Stream for BcStream<'a> {
|
||||
}
|
||||
|
||||
pub struct BcPayloadStream<'a> {
|
||||
rx: &'a mut ReceiverStream<Bc>,
|
||||
rx: &'a mut ReceiverStream<Result<Bc>>,
|
||||
}
|
||||
|
||||
impl<'a> Unpin for BcPayloadStream<'a> {}
|
||||
@@ -48,10 +48,9 @@ impl<'a> Stream for BcPayloadStream<'a> {
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<IoResult<Vec<u8>>>> {
|
||||
match Pin::new(&mut self.rx).poll_next(cx) {
|
||||
Poll::Ready(Some(bc)) => {
|
||||
log::info!("Got Bc Packet");
|
||||
match bc {
|
||||
loop {
|
||||
match Pin::new(&mut self.rx).poll_next(cx) {
|
||||
Poll::Ready(Some(Ok(bc))) => match bc {
|
||||
Bc {
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
@@ -59,12 +58,15 @@ impl<'a> Stream for BcPayloadStream<'a> {
|
||||
..
|
||||
}),
|
||||
..
|
||||
} => Poll::Ready(Some(Ok(data))),
|
||||
_ => Poll::Pending,
|
||||
} => return Poll::Ready(Some(Ok(data))),
|
||||
_ => continue,
|
||||
},
|
||||
Poll::Ready(Some(Err(e))) => {
|
||||
return Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e))))
|
||||
}
|
||||
Poll::Ready(None) => return Poll::Ready(None),
|
||||
Poll::Pending => return Poll::Pending,
|
||||
}
|
||||
Poll::Ready(None) => Poll::Ready(None),
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,7 +74,11 @@ impl<'a> Stream for BcPayloadStream<'a> {
|
||||
pub type BcMediaStream<'b> = FramedRead<Compat<IntoAsyncRead<BcPayloadStream<'b>>>, BcMediaCodex>;
|
||||
|
||||
impl<'a> BcSubscription<'a> {
|
||||
pub fn new(rx: Receiver<Bc>, msg_num: u16, conn: &'a BcConnection) -> BcSubscription<'a> {
|
||||
pub fn new(
|
||||
rx: Receiver<Result<Bc>>,
|
||||
msg_num: u32,
|
||||
conn: &'a BcConnection,
|
||||
) -> BcSubscription<'a> {
|
||||
BcSubscription {
|
||||
rx: ReceiverStream::new(rx),
|
||||
msg_num,
|
||||
@@ -81,15 +87,19 @@ impl<'a> BcSubscription<'a> {
|
||||
}
|
||||
|
||||
pub async fn send(&self, bc: Bc) -> Result<()> {
|
||||
assert!(bc.meta.msg_num == self.msg_num);
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
self.conn.send(bc).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn recv(&mut self) -> Result<Bc> {
|
||||
let bc = self.rx.next().await.ok_or(Error::DroppedSubscriber)?;
|
||||
assert!(bc.meta.msg_num == self.msg_num);
|
||||
Ok(bc)
|
||||
let bc = timeout(self.rx.next())
|
||||
.await?
|
||||
.ok_or(Error::DroppedSubscriber)?;
|
||||
if let Ok(bc) = &bc {
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
}
|
||||
bc
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
@@ -103,18 +113,10 @@ impl<'a> BcSubscription<'a> {
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn bcmedia_stream(&'_ mut self) -> BcMediaStream<'_> {
|
||||
pub fn bcmedia_stream(&'_ mut self, strict: bool) -> BcMediaStream<'_> {
|
||||
let async_read = BcPayloadStream { rx: &mut self.rx }
|
||||
.into_async_read()
|
||||
.compat();
|
||||
FramedRead::new(async_read, BcMediaCodex::new())
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes it difficult to avoid unsubscribing when you're finished
|
||||
impl<'a> Drop for BcSubscription<'a> {
|
||||
fn drop(&mut self) {
|
||||
// It's fine if we can't unsubscribe as that means we already have
|
||||
let _ = self.conn.unsubscribe(self.msg_num);
|
||||
FramedRead::new(async_read, BcMediaCodex::new(strict))
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ use tokio::{
|
||||
Mutex, RwLock,
|
||||
},
|
||||
task::JoinSet,
|
||||
time::{interval, timeout, Duration},
|
||||
time::{interval, Duration},
|
||||
};
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::udp::UdpFramed;
|
||||
@@ -33,8 +33,9 @@ use tokio_util::udp::UdpFramed;
|
||||
#[derive(Debug, Clone)]
|
||||
struct RegisterResult {
|
||||
reg: SocketAddr,
|
||||
dmap: Option<SocketAddr>,
|
||||
dev: Option<SocketAddr>,
|
||||
dev: SocketAddr,
|
||||
dmap: SocketAddr,
|
||||
relay: SocketAddr,
|
||||
client_id: i32,
|
||||
sid: u32,
|
||||
}
|
||||
@@ -53,12 +54,6 @@ struct UidLookupResults {
|
||||
relay: SocketAddr,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum ConnectionKind {
|
||||
Local,
|
||||
Relay,
|
||||
}
|
||||
|
||||
pub(crate) struct Discovery {}
|
||||
|
||||
const MTU: u32 = 1030;
|
||||
@@ -216,17 +211,10 @@ impl Discoverer {
|
||||
|
||||
// Get what ever completes first
|
||||
while let Some(result) = set.next().await {
|
||||
match result {
|
||||
Ok(ret) => {
|
||||
// info!("Future pop OK");
|
||||
return Ok(ret);
|
||||
}
|
||||
Err(_e) => {
|
||||
// info!("Future pop Err: {:?}", e);
|
||||
}
|
||||
if let Ok(ret) = result {
|
||||
return Ok(ret);
|
||||
}
|
||||
}
|
||||
// info!("set: empty");
|
||||
Err(Error::DiscoveryTimeout)
|
||||
}
|
||||
|
||||
@@ -246,30 +234,66 @@ impl Discoverer {
|
||||
let mut reply = ReceiverStream::new(self.subscribe(target_tid).await?);
|
||||
let msg = BcUdp::Discovery(disc);
|
||||
|
||||
let mut inter = interval(Duration::from_millis(500));
|
||||
let maximum_wait = Duration::from_secs(60);
|
||||
let resend_wait = Duration::from_millis(500);
|
||||
let mut inter = interval(resend_wait);
|
||||
|
||||
let result = tokio::select! {
|
||||
v = async {
|
||||
// Recv while channel is viable
|
||||
while let Some(msg) = reply.next().await {
|
||||
if let Ok((reply, addr)) = msg {
|
||||
if let Some(result) = map(reply, addr) {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(Error::DroppedConnection)
|
||||
} => {v},
|
||||
v = async {
|
||||
// Send every inter for ever or until channel is no longer viable
|
||||
loop {
|
||||
inter.tick().await;
|
||||
if let Err(e) = self.send(msg.clone(), dest).await {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
} => {Err::<T, Error>(v)},
|
||||
_ = {
|
||||
// Sleep then emit Timeout
|
||||
tokio::time::sleep(maximum_wait)
|
||||
} => {
|
||||
Err::<T, Error>(Error::DiscoveryTimeout)
|
||||
}
|
||||
};
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
async fn send_and_forget(&self, mut disc: UdpDiscovery, dest: SocketAddr) -> Result<()> {
|
||||
if disc.tid == 0 {
|
||||
// If 0 make a random one
|
||||
let target_tid = generate_tid();
|
||||
disc.tid = target_tid;
|
||||
}
|
||||
let mut inter = interval(Duration::from_millis(50));
|
||||
let msg = BcUdp::Discovery(disc);
|
||||
|
||||
for _i in 0..5 {
|
||||
inter.tick().await;
|
||||
|
||||
self.send(msg.clone(), dest).await?;
|
||||
|
||||
if let Ok(Some(Ok((reply, addr)))) =
|
||||
timeout(Duration::from_millis(500), reply.next()).await
|
||||
{
|
||||
if let Some(result) = map(reply, addr) {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(Error::DiscoveryTimeout)
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// This function will contact the p2p relay servers
|
||||
//
|
||||
// It will ask each of the servers for details on a specific UID
|
||||
//
|
||||
// On success it returns the M2cQr that the p2p relay
|
||||
// server has about the UID
|
||||
/// This function will contact the p2p relay servers
|
||||
///
|
||||
/// It will ask each of the servers for details on a specific UID
|
||||
///
|
||||
/// On success it returns the M2cQr that the p2p relay
|
||||
/// server has about the UID
|
||||
async fn uid_loopup(&self, uid: &str) -> Result<UidLookupResults> {
|
||||
let mut addrs = vec![];
|
||||
for p2p_relay in P2P_RELAY_HOSTNAMES.iter() {
|
||||
@@ -310,185 +334,6 @@ impl Discoverer {
|
||||
})
|
||||
}
|
||||
|
||||
async fn send_and_forget(&self, mut disc: UdpDiscovery, dest: SocketAddr) -> Result<()> {
|
||||
if disc.tid == 0 {
|
||||
// If 0 make a random one
|
||||
let target_tid = generate_tid();
|
||||
disc.tid = target_tid;
|
||||
}
|
||||
let mut inter = interval(Duration::from_millis(50));
|
||||
let msg = BcUdp::Discovery(disc);
|
||||
|
||||
for _i in 0..5 {
|
||||
inter.tick().await;
|
||||
|
||||
self.send(msg.clone(), dest).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn device_initiated_connect(
|
||||
&self,
|
||||
client_id: i32,
|
||||
register_result: &RegisterResult,
|
||||
) -> Result<ConnectResult> {
|
||||
let (addr, local_tid, local_did, conn_kind) = self
|
||||
.handle_incoming(|bc, addr| {
|
||||
trace!("bc: {:?}", bc);
|
||||
match (bc, register_result) {
|
||||
(
|
||||
UdpDiscovery {
|
||||
tid,
|
||||
payload:
|
||||
UdpXml {
|
||||
d2c_t: Some(D2cT { sid, cid, did, .. }),
|
||||
..
|
||||
},
|
||||
},
|
||||
RegisterResult {
|
||||
dmap: Some(register_dmap),
|
||||
sid: register_sid,
|
||||
..
|
||||
},
|
||||
) if cid == client_id && &sid == register_sid && &addr == register_dmap => {
|
||||
Some((addr, tid, did, ConnectionKind::Relay))
|
||||
}
|
||||
(
|
||||
UdpDiscovery {
|
||||
tid,
|
||||
payload:
|
||||
UdpXml {
|
||||
d2c_t: Some(D2cT { sid, cid, did, .. }),
|
||||
..
|
||||
},
|
||||
},
|
||||
RegisterResult {
|
||||
dev: Some(register_dev),
|
||||
sid: register_sid,
|
||||
..
|
||||
},
|
||||
) if cid == client_id && &sid == register_sid && &addr == register_dev => {
|
||||
Some((addr, tid, did, ConnectionKind::Local))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
|
||||
let conn = match conn_kind {
|
||||
ConnectionKind::Local => "local",
|
||||
ConnectionKind::Relay => "map",
|
||||
}
|
||||
.to_string();
|
||||
|
||||
let msg = UdpDiscovery {
|
||||
tid: local_tid,
|
||||
payload: UdpXml {
|
||||
c2d_a: Some(C2dA {
|
||||
sid: register_result.sid,
|
||||
conn,
|
||||
cid: client_id,
|
||||
did: local_did,
|
||||
mtu: MTU,
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
// Send and await confirm
|
||||
self.retry_send(msg, addr, |bc, _| {
|
||||
trace!("msg: {:?}", &bc);
|
||||
match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
d2c_cfm: Some(D2cCfm { sid, cid, did, .. }),
|
||||
..
|
||||
},
|
||||
} if sid == register_result.sid && did == local_did && cid == client_id => Some(()),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
|
||||
let result = ConnectResult {
|
||||
addr,
|
||||
client_id,
|
||||
sid: register_result.sid,
|
||||
camera_id: local_did,
|
||||
};
|
||||
|
||||
match conn_kind {
|
||||
ConnectionKind::Local => {
|
||||
self.confirm_map(&result, register_result.reg, result.addr)
|
||||
.await?;
|
||||
}
|
||||
ConnectionKind::Relay => {
|
||||
self.confirm_relay(&result, register_result.reg).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn client_initiated_connect(
|
||||
&self,
|
||||
register_result: &RegisterResult,
|
||||
) -> Result<ConnectResult> {
|
||||
let tid = generate_tid();
|
||||
|
||||
if let RegisterResult {
|
||||
dev: Some(dev_addr),
|
||||
..
|
||||
} = ®ister_result
|
||||
{
|
||||
let msg = UdpDiscovery {
|
||||
tid,
|
||||
payload: UdpXml {
|
||||
c2d_t: Some(C2dT {
|
||||
sid: register_result.sid,
|
||||
cid: register_result.client_id,
|
||||
mtu: MTU,
|
||||
conn: "local".to_string(),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
let (final_addr, local_did) = self
|
||||
.retry_send(msg, *dev_addr, |bc, addr| match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
d2c_cfm: Some(D2cCfm { cid, did, sid, .. }),
|
||||
..
|
||||
},
|
||||
} if cid == register_result.client_id && sid == register_result.sid => {
|
||||
Some((addr, did))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await?;
|
||||
|
||||
let result = ConnectResult {
|
||||
addr: final_addr,
|
||||
client_id: register_result.client_id,
|
||||
sid: register_result.sid,
|
||||
camera_id: local_did,
|
||||
};
|
||||
|
||||
self.confirm_map(&result, register_result.reg, *dev_addr)
|
||||
.await?;
|
||||
|
||||
Ok(result)
|
||||
} else {
|
||||
Err(Error::NoDev)
|
||||
}
|
||||
}
|
||||
|
||||
/// Register our local ip address with the reolink servers
|
||||
/// This will be used for the device to contact us
|
||||
async fn register_address(
|
||||
@@ -527,79 +372,34 @@ impl Discoverer {
|
||||
};
|
||||
|
||||
// Send and await acceptance
|
||||
let (sid, dmap, dev) = self
|
||||
let (sid, dev, dmap, relay) = self
|
||||
.retry_send(msg, lookup.reg, |bc, _| match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
r2c_t:
|
||||
Some(R2cT {
|
||||
dmap: Some(dmap),
|
||||
r2c_c_r:
|
||||
Some(R2cCr {
|
||||
dmap,
|
||||
dev,
|
||||
relay,
|
||||
sid,
|
||||
cid,
|
||||
dev: Some(dev),
|
||||
rsp,
|
||||
..
|
||||
}),
|
||||
..
|
||||
},
|
||||
} if !dmap.ip.is_empty()
|
||||
&& dmap.port > 0
|
||||
&& !dev.ip.is_empty()
|
||||
&& dev.port > 0
|
||||
&& cid == client_id =>
|
||||
{
|
||||
Some(Ok((sid, Some(dmap), Some(dev))))
|
||||
} if !dev.ip.is_empty() && dev.port > 0 && rsp != -1 => {
|
||||
Some(Ok((sid, dev, dmap, relay)))
|
||||
}
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
r2c_t:
|
||||
Some(R2cT {
|
||||
dmap: Some(dmap),
|
||||
sid,
|
||||
cid,
|
||||
dev: None,
|
||||
}),
|
||||
r2c_c_r: Some(R2cCr { dev, rsp, .. }),
|
||||
..
|
||||
},
|
||||
} if !dmap.ip.is_empty() && dmap.port > 0 && cid == client_id => {
|
||||
Some(Ok((sid, Some(dmap), None)))
|
||||
}
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
r2c_t:
|
||||
Some(R2cT {
|
||||
dmap: None,
|
||||
sid,
|
||||
cid,
|
||||
dev: Some(dev),
|
||||
}),
|
||||
..
|
||||
},
|
||||
} if !dev.ip.is_empty() && dev.port > 0 && cid == client_id => {
|
||||
Some(Ok((sid, None, Some(dev))))
|
||||
}
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
r2c_c_r: Some(R2cCr { dmap, sid, rsp, .. }),
|
||||
..
|
||||
},
|
||||
} if !dmap.ip.is_empty() && dmap.port > 0 && rsp != -1 => {
|
||||
Some(Ok((sid, Some(dmap), None)))
|
||||
}
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
r2c_c_r: Some(R2cCr { dmap, rsp, .. }),
|
||||
..
|
||||
},
|
||||
} if !dmap.ip.is_empty() && dmap.port > 0 && rsp == -1 => {
|
||||
} if !dev.ip.is_empty() && dev.port > 0 && rsp == -1 => {
|
||||
Some(Err(Error::RegisterError))
|
||||
}
|
||||
_ => None,
|
||||
@@ -610,25 +410,224 @@ impl Discoverer {
|
||||
reg: lookup.reg,
|
||||
sid,
|
||||
client_id,
|
||||
dmap: dmap.map(|dmap| {
|
||||
SocketAddr::new(dmap.ip.parse().expect("Could not read ip addr"), dmap.port)
|
||||
}),
|
||||
dev: dev.map(|dev| {
|
||||
SocketAddr::new(dev.ip.parse().expect("Could not read ip addr"), dev.port)
|
||||
}),
|
||||
dev: SocketAddr::new(dev.ip.parse()?, dev.port),
|
||||
dmap: SocketAddr::new(dmap.ip.parse()?, dmap.port),
|
||||
relay: SocketAddr::new(relay.ip.parse()?, relay.port),
|
||||
})
|
||||
}
|
||||
|
||||
/// Confirm connection with relay
|
||||
/// This is sent once all data has been found
|
||||
async fn confirm_relay(&self, conn_result: &ConnectResult, reg_addr: SocketAddr) -> Result<()> {
|
||||
async fn device_initiated_dev(
|
||||
&self,
|
||||
register_result: &RegisterResult,
|
||||
) -> Result<ConnectResult> {
|
||||
let (addr, local_tid, local_did) = self
|
||||
.handle_incoming(|bc, addr| {
|
||||
trace!("bc: {:?}", bc);
|
||||
match (bc, register_result) {
|
||||
(
|
||||
UdpDiscovery {
|
||||
tid,
|
||||
payload:
|
||||
UdpXml {
|
||||
d2c_t:
|
||||
Some(D2cT {
|
||||
sid,
|
||||
cid,
|
||||
did,
|
||||
conn,
|
||||
..
|
||||
}),
|
||||
..
|
||||
},
|
||||
},
|
||||
RegisterResult {
|
||||
dmap: register_dmap,
|
||||
sid: register_sid,
|
||||
..
|
||||
},
|
||||
) if cid == register_result.client_id
|
||||
&& &sid == register_sid
|
||||
&& &addr == register_dmap
|
||||
&& &conn == "local" =>
|
||||
{
|
||||
Some((addr, tid, did))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
|
||||
let msg = UdpDiscovery {
|
||||
tid: local_tid,
|
||||
payload: UdpXml {
|
||||
c2d_a: Some(C2dA {
|
||||
sid: register_result.sid,
|
||||
conn: "local".to_string(),
|
||||
cid: register_result.client_id,
|
||||
did: local_did,
|
||||
mtu: MTU,
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
// Send and await confirm
|
||||
self.retry_send(msg, addr, |bc, _| {
|
||||
trace!("msg: {:?}", &bc);
|
||||
match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
d2c_cfm:
|
||||
Some(D2cCfm {
|
||||
sid,
|
||||
cid,
|
||||
did,
|
||||
conn,
|
||||
..
|
||||
}),
|
||||
..
|
||||
},
|
||||
} if sid == register_result.sid
|
||||
&& did == local_did
|
||||
&& cid == register_result.client_id
|
||||
&& &conn == "local" =>
|
||||
{
|
||||
Some(())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
|
||||
let result = ConnectResult {
|
||||
addr,
|
||||
client_id: register_result.client_id,
|
||||
sid: register_result.sid,
|
||||
camera_id: local_did,
|
||||
};
|
||||
|
||||
// Confirm local to register
|
||||
let msg = UdpDiscovery {
|
||||
tid: 0,
|
||||
payload: UdpXml {
|
||||
c2r_cfm: Some(C2rCfm {
|
||||
sid: conn_result.sid,
|
||||
cid: conn_result.client_id,
|
||||
did: conn_result.camera_id,
|
||||
sid: result.sid,
|
||||
cid: result.client_id,
|
||||
did: result.camera_id,
|
||||
rsp: 0,
|
||||
conn: "local".to_string(),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
self.send_and_forget(msg, register_result.reg).await?;
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn device_initiated_map(
|
||||
&self,
|
||||
register_result: &RegisterResult,
|
||||
) -> Result<ConnectResult> {
|
||||
let (addr, local_tid, local_did) = self
|
||||
.handle_incoming(|bc, addr| {
|
||||
trace!("bc: {:?}", bc);
|
||||
match (bc, register_result) {
|
||||
(
|
||||
UdpDiscovery {
|
||||
tid,
|
||||
payload:
|
||||
UdpXml {
|
||||
d2c_t:
|
||||
Some(D2cT {
|
||||
sid,
|
||||
cid,
|
||||
did,
|
||||
conn,
|
||||
..
|
||||
}),
|
||||
..
|
||||
},
|
||||
},
|
||||
RegisterResult {
|
||||
dmap: register_dmap,
|
||||
sid: register_sid,
|
||||
..
|
||||
},
|
||||
) if cid == register_result.client_id
|
||||
&& &sid == register_sid
|
||||
&& &addr == register_dmap
|
||||
&& &conn == "map" =>
|
||||
{
|
||||
Some((addr, tid, did))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
|
||||
let msg = UdpDiscovery {
|
||||
tid: local_tid,
|
||||
payload: UdpXml {
|
||||
c2d_a: Some(C2dA {
|
||||
sid: register_result.sid,
|
||||
conn: "map".to_string(),
|
||||
cid: register_result.client_id,
|
||||
did: local_did,
|
||||
mtu: MTU,
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
// Send and await confirm
|
||||
self.retry_send(msg, addr, |bc, _| {
|
||||
trace!("msg: {:?}", &bc);
|
||||
match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
d2c_cfm:
|
||||
Some(D2cCfm {
|
||||
sid,
|
||||
cid,
|
||||
did,
|
||||
conn,
|
||||
..
|
||||
}),
|
||||
..
|
||||
},
|
||||
} if sid == register_result.sid
|
||||
&& did == local_did
|
||||
&& cid == register_result.client_id
|
||||
&& &conn == "map" =>
|
||||
{
|
||||
Some(())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
|
||||
let result = ConnectResult {
|
||||
addr,
|
||||
client_id: register_result.client_id,
|
||||
sid: register_result.sid,
|
||||
camera_id: local_did,
|
||||
};
|
||||
|
||||
// Confirm map to register
|
||||
let msg = UdpDiscovery {
|
||||
tid: 0,
|
||||
payload: UdpXml {
|
||||
c2r_cfm: Some(C2rCfm {
|
||||
sid: result.sid,
|
||||
cid: result.client_id,
|
||||
did: result.camera_id,
|
||||
rsp: 0,
|
||||
conn: "map".to_string(),
|
||||
}),
|
||||
@@ -636,27 +635,62 @@ impl Discoverer {
|
||||
},
|
||||
};
|
||||
|
||||
self.send_and_forget(msg, reg_addr).await?;
|
||||
self.send_and_forget(msg, register_result.reg).await?;
|
||||
|
||||
Ok(())
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Confirm Map. This is sent if we learned the IP via the relay
|
||||
/// then connected locally. We tell the relay they we are establishing
|
||||
/// a local then tell the camera to connect to us via map
|
||||
async fn confirm_map(
|
||||
async fn client_initiated_dev(
|
||||
&self,
|
||||
conn_result: &ConnectResult,
|
||||
reg_addr: SocketAddr,
|
||||
dev_addr: SocketAddr,
|
||||
) -> Result<()> {
|
||||
register_result: &RegisterResult,
|
||||
) -> Result<ConnectResult> {
|
||||
let tid = generate_tid();
|
||||
|
||||
let dev_addr = register_result.dev;
|
||||
let msg = UdpDiscovery {
|
||||
tid,
|
||||
payload: UdpXml {
|
||||
c2d_t: Some(C2dT {
|
||||
sid: register_result.sid,
|
||||
cid: register_result.client_id,
|
||||
mtu: MTU,
|
||||
conn: "local".to_string(),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
let (final_addr, local_did) = self
|
||||
.retry_send(msg, dev_addr, |bc, addr| match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
d2c_cfm: Some(D2cCfm { cid, did, sid, .. }),
|
||||
..
|
||||
},
|
||||
} if cid == register_result.client_id && sid == register_result.sid => {
|
||||
Some((addr, did))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await?;
|
||||
|
||||
let result = ConnectResult {
|
||||
addr: final_addr,
|
||||
client_id: register_result.client_id,
|
||||
sid: register_result.sid,
|
||||
camera_id: local_did,
|
||||
};
|
||||
|
||||
// Confirm local to register
|
||||
let msg = UdpDiscovery {
|
||||
tid: 0,
|
||||
payload: UdpXml {
|
||||
c2r_cfm: Some(C2rCfm {
|
||||
sid: conn_result.sid,
|
||||
cid: conn_result.client_id,
|
||||
did: conn_result.camera_id,
|
||||
sid: result.sid,
|
||||
cid: result.client_id,
|
||||
did: result.camera_id,
|
||||
conn: "local".to_string(),
|
||||
rsp: 0,
|
||||
}),
|
||||
@@ -664,28 +698,69 @@ impl Discoverer {
|
||||
},
|
||||
};
|
||||
|
||||
self.send_and_forget(msg, reg_addr).await?;
|
||||
self.send_and_forget(msg, register_result.reg).await?;
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn client_initiated_relay(
|
||||
&self,
|
||||
register_result: &RegisterResult,
|
||||
) -> Result<ConnectResult> {
|
||||
let tid = generate_tid();
|
||||
|
||||
let msg = UdpDiscovery {
|
||||
tid: 0,
|
||||
tid,
|
||||
payload: UdpXml {
|
||||
c2d_t: Some(C2dT {
|
||||
sid: conn_result.sid,
|
||||
cid: conn_result.client_id,
|
||||
sid: register_result.sid,
|
||||
cid: register_result.client_id,
|
||||
mtu: MTU,
|
||||
conn: "map".to_string(),
|
||||
conn: "relay".to_string(),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
self.send_and_forget(msg, dev_addr).await?;
|
||||
let (final_addr, local_did) = self
|
||||
.retry_send(msg, register_result.relay, |bc, addr| match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
UdpXml {
|
||||
d2c_cfm:
|
||||
Some(D2cCfm {
|
||||
cid,
|
||||
did,
|
||||
sid,
|
||||
conn,
|
||||
..
|
||||
}),
|
||||
..
|
||||
},
|
||||
} if cid == register_result.client_id
|
||||
&& sid == register_result.sid
|
||||
&& &conn == "relay" =>
|
||||
{
|
||||
Some((addr, did))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
let result = ConnectResult {
|
||||
addr: final_addr,
|
||||
client_id: register_result.client_id,
|
||||
sid: register_result.sid,
|
||||
camera_id: local_did,
|
||||
};
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
impl Discovery {
|
||||
// Perform UDP broadcast lookup and connection
|
||||
pub(crate) async fn local(uid: &str) -> Result<DiscoveryResult> {
|
||||
let discoverer = Discoverer::new().await?;
|
||||
|
||||
@@ -734,14 +809,14 @@ impl Discovery {
|
||||
|
||||
// This will start remote discovery against the reolink p2p servers
|
||||
//
|
||||
// It has the following stages
|
||||
// - Contact the p2p register: This will get the register, relay and log server ip addresses
|
||||
// - Register the client ip address to the register (This can probably be used for NAT holepunching if the camera
|
||||
// tries to connect to us using this data)
|
||||
// - The register will return the camera ip/port and SID
|
||||
// - Connect to the camera using register's provided ip/port and negotiate a cid and did
|
||||
// - Send a message to the reolink log server that we will connect locally
|
||||
// - Send a message to the camera that we could connect remotely
|
||||
// This works by registering our ip and intent to connect with the reolink
|
||||
// servers
|
||||
//
|
||||
// We will then try to connect to the camera local ip address while the camera
|
||||
// will also attempt to connec to ours
|
||||
//
|
||||
// This method is best when broadcasts are not possible but we can contact the camera
|
||||
// directly
|
||||
#[allow(unused)]
|
||||
pub(crate) async fn remote(uid: &str) -> Result<DiscoveryResult> {
|
||||
let mut discoverer = Discoverer::new().await?;
|
||||
@@ -753,9 +828,11 @@ impl Discovery {
|
||||
let relay_addr = lookup.relay;
|
||||
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
|
||||
let dev_addr = reg_result.dev.ok_or(Error::NoDev)?;
|
||||
|
||||
let connect_result = discoverer.client_initiated_connect(®_result).await?;
|
||||
let connect_result = tokio::select! {
|
||||
v = discoverer.client_initiated_dev(®_result) => {v},
|
||||
v = discoverer.device_initiated_dev(®_result) => {v},
|
||||
}?;
|
||||
|
||||
Ok(DiscoveryResult {
|
||||
socket: discoverer.into_socket().await,
|
||||
@@ -765,34 +842,55 @@ impl Discovery {
|
||||
})
|
||||
}
|
||||
|
||||
// This is similar to remote, except that a relay (map) will be established.
|
||||
// This is similar to remote, except that it allows the camera to connect to us
|
||||
// over it's dmap (public) ip address that it has registered with reolink servers.
|
||||
//
|
||||
// All future connections will go VIA the relink servers, this is for
|
||||
// cellular cameras that do not support local connections
|
||||
// This works by registering our ip address and the desire to connect with the
|
||||
// reolink servers. Data however should go to the camera's public ip address
|
||||
//
|
||||
// It is possible that this will also establish a local if the camera attempts that
|
||||
//
|
||||
#[allow(unused)]
|
||||
pub(crate) async fn relay(uid: &str) -> Result<DiscoveryResult> {
|
||||
let mut discoverer = Discoverer::new().await?;
|
||||
let client_id = generate_cid();
|
||||
// This method should be used when the camera is behind a NAT or firewall but we are
|
||||
// reachable
|
||||
pub(crate) async fn map(uid: &str) -> Result<DiscoveryResult> {
|
||||
let discoverer = Discoverer::new().await?;
|
||||
|
||||
let client_id = generate_cid();
|
||||
trace!("client_id: {}", client_id);
|
||||
|
||||
let lookup = discoverer.uid_loopup(uid).await?;
|
||||
trace!("lookup: {:?}", lookup);
|
||||
let reg_addr = lookup.reg;
|
||||
let relay_addr = lookup.relay;
|
||||
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
|
||||
trace!("reg_result: {:?}", reg_result);
|
||||
|
||||
let dmap_addr = reg_result.dmap.ok_or(Error::NoDmap)?;
|
||||
let connect_result = discoverer.device_initiated_map(®_result).await?;
|
||||
trace!("connect_result: {:?}", connect_result);
|
||||
|
||||
let connect_result = discoverer
|
||||
.device_initiated_connect(client_id, ®_result)
|
||||
.await?;
|
||||
Ok(DiscoveryResult {
|
||||
socket: discoverer.into_socket().await,
|
||||
addr: connect_result.addr,
|
||||
client_id,
|
||||
camera_id: connect_result.camera_id,
|
||||
})
|
||||
}
|
||||
|
||||
// This will forward all connections via the reolinks servers
|
||||
//
|
||||
// This method should work if all else fails but it will require
|
||||
// us to trust reolink with our data once more...
|
||||
//
|
||||
pub(crate) async fn relay(uid: &str) -> Result<DiscoveryResult> {
|
||||
let discoverer = Discoverer::new().await?;
|
||||
let client_id = generate_cid();
|
||||
|
||||
trace!("client_id: {}", client_id);
|
||||
|
||||
let lookup = discoverer.uid_loopup(uid).await?;
|
||||
trace!("lookup: {:?}", lookup);
|
||||
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
|
||||
trace!("reg_result: {:?}", reg_result);
|
||||
|
||||
let connect_result = discoverer.client_initiated_relay(®_result).await?;
|
||||
trace!("connect_result: {:?}", connect_result);
|
||||
|
||||
Ok(DiscoveryResult {
|
||||
@@ -1098,4 +1196,32 @@ async fn connect() -> Result<UdpSocket> {
|
||||
</P2P>
|
||||
```
|
||||
|
||||
# Thread 4: Observed when behind a NAT on both ends of the connection
|
||||
|
||||
- C->R
|
||||
```
|
||||
<P2P>
|
||||
<C2D_T>
|
||||
<sid>526020041</sid>
|
||||
<conn>relay</conn>
|
||||
<cid>38000</cid>
|
||||
<mtu>1350</mtu>
|
||||
</C2D_T>
|
||||
</P2P>
|
||||
```
|
||||
|
||||
- R->C
|
||||
```xml
|
||||
<P2P>
|
||||
<D2C_CFM>
|
||||
<sid>526020041</sid>
|
||||
<conn>relay</conn>
|
||||
<rsp>0</rsp>
|
||||
<cid>38000</cid>
|
||||
<did>32</did>
|
||||
<time_r>0</time_r>
|
||||
</D2C_CFM>
|
||||
</P2P>
|
||||
```
|
||||
|
||||
*/
|
||||
@@ -159,7 +159,8 @@ impl BcUdpSource {
|
||||
recieved: Default::default(),
|
||||
state: State::Normal,
|
||||
send_buffer: Default::default(),
|
||||
interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms
|
||||
ack_interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms
|
||||
resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -211,35 +212,42 @@ pub(crate) struct UdpPayloadSource {
|
||||
send_buffer: VecDeque<BcUdp>,
|
||||
/// Offical Client does ack every 10ms if we don't also do this the camera
|
||||
/// seems to think we have a poor connection and will abort
|
||||
/// This `intveral` controls how ofen we do this
|
||||
interval: Interval,
|
||||
/// This `ack_interval` controls how ofen we do this
|
||||
ack_interval: Interval,
|
||||
/// Offical Client does resend every 500ms
|
||||
/// This `resend_interval` controls how ofen we do this
|
||||
resend_interval: Interval,
|
||||
}
|
||||
|
||||
impl UdpPayloadSource {
|
||||
fn build_send_ack(&self) -> UdpAck {
|
||||
assert!(self.packets_want > 0);
|
||||
let start: u32 = self.packets_want - 1;
|
||||
let missing_ids = if let Some(end) = self.recieved.keys().max() {
|
||||
let mut vec = vec![];
|
||||
// From last contiguous packet to last recieved packet
|
||||
// create a payload of `00` (unreceived) and `01` (received)
|
||||
// that can be used to form the `UdpAck` packet
|
||||
for i in (start + 1)..(end + 1) {
|
||||
if self.recieved.contains_key(&i) {
|
||||
vec.push(1)
|
||||
} else {
|
||||
vec.push(0)
|
||||
if self.packets_want > 0 {
|
||||
let start: u32 = self.packets_want - 1;
|
||||
let missing_ids = if let Some(end) = self.recieved.keys().max() {
|
||||
let mut vec = vec![];
|
||||
// From last contiguous packet to last recieved packet
|
||||
// create a payload of `00` (unreceived) and `01` (received)
|
||||
// that can be used to form the `UdpAck` packet
|
||||
for i in (start + 1)..(end + 1) {
|
||||
if self.recieved.contains_key(&i) {
|
||||
vec.push(1)
|
||||
} else {
|
||||
vec.push(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
vec
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
vec
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
|
||||
UdpAck {
|
||||
connection_id: self.camera_id,
|
||||
packet_id: start,
|
||||
payload: missing_ids,
|
||||
UdpAck {
|
||||
connection_id: self.camera_id,
|
||||
packet_id: start,
|
||||
group_id: 0,
|
||||
payload: missing_ids,
|
||||
}
|
||||
} else {
|
||||
UdpAck::empty(self.camera_id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,6 +262,22 @@ impl UdpPayloadSource {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn maintanence(&mut self, cx: &mut Context<'_>) {
|
||||
// Check for periodic resends
|
||||
if self.resend_interval.poll_tick(cx).is_ready() {
|
||||
trace!("UDPSource.RecievedPacket: Resend");
|
||||
for (_, resend) in self.sent.iter() {
|
||||
self.send_buffer.push_back(BcUdp::Data(resend.clone()));
|
||||
}
|
||||
}
|
||||
if self.ack_interval.poll_tick(cx).is_ready() {
|
||||
let ack = BcUdp::Ack(self.build_send_ack());
|
||||
trace!("UDPSource.RecievedPacket: QueueingAck");
|
||||
self.send_buffer.push_back(ack);
|
||||
self.state = State::Flushing;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for UdpPayloadSource {
|
||||
@@ -270,27 +294,12 @@ impl Stream for UdpPayloadSource {
|
||||
if let Some(payload) = this.recieved.remove(&this.packets_want) {
|
||||
trace!("UDPSource.Data: PreReady: {}", this.packets_want);
|
||||
this.packets_want += 1;
|
||||
let ack = BcUdp::Ack(this.build_send_ack());
|
||||
this.send_buffer.push_back(ack);
|
||||
return Poll::Ready(Some(Ok(payload)));
|
||||
}
|
||||
// Check for periodic resends
|
||||
if this.interval.poll_tick(cx).is_ready() {
|
||||
trace!("UDPSource.RecievedPacker: Resend");
|
||||
for (_, resend) in this.sent.iter() {
|
||||
this.send_buffer.push_back(BcUdp::Data(resend.clone()));
|
||||
}
|
||||
if this.packets_want == 0 {
|
||||
// When no packets have been recieved the
|
||||
// ACK is different specifically unknown_b
|
||||
// is set to -1 and packet_id is also set to
|
||||
// -1
|
||||
// TODO Add this style of ACK
|
||||
} else {
|
||||
let ack = BcUdp::Ack(this.build_send_ack());
|
||||
this.send_buffer.push_back(ack);
|
||||
}
|
||||
this.state = State::Flushing;
|
||||
continue;
|
||||
}
|
||||
// Handle resend events
|
||||
this.maintanence(cx);
|
||||
// Normal behaviors
|
||||
match this.inner.poll_next_unpin(cx) {
|
||||
Poll::Ready(Some(Ok((
|
||||
@@ -307,6 +316,8 @@ impl Stream for UdpPayloadSource {
|
||||
if packet_id == this.packets_want {
|
||||
trace!("UDPSource.RecievedPacker: NewData: {}", this.packets_want);
|
||||
this.packets_want += 1;
|
||||
let ack = BcUdp::Ack(this.build_send_ack());
|
||||
this.send_buffer.push_back(ack);
|
||||
return Poll::Ready(Some(Ok(payload)));
|
||||
} else {
|
||||
trace!("UDPSource.RecievedPacker: OtherData");
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! Handles credentials for camera including default reolink password
|
||||
|
||||
use std::convert::TryInto;
|
||||
|
||||
/// Used for caching the credentials
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Credentials {
|
||||
pub(crate) username: String,
|
||||
pub(crate) password: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Credentials {
|
||||
/// Default credentials for some reolink cameras
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
username: "admin".to_string(),
|
||||
password: Some("123456".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Credentials {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"username", &self.username)
|
||||
.entry(&"password", &"******")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Credentials {
|
||||
pub(crate) fn new<T: Into<String>, U: Into<String>>(username: T, password: Option<U>) -> Self {
|
||||
Self {
|
||||
username: username.into(),
|
||||
password: password.map(|t| t.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a convience function to make an AES key from the login password and the NONCE
|
||||
/// negotiated during login
|
||||
pub(crate) fn make_aeskey<T: AsRef<str>>(&self, nonce: T) -> [u8; 16] {
|
||||
let key_phrase = format!(
|
||||
"{}-{}",
|
||||
nonce.as_ref(),
|
||||
self.password.clone().unwrap_or_default()
|
||||
);
|
||||
let key_phrase_hash = format!("{:X}\0", md5::compute(key_phrase))
|
||||
.to_uppercase()
|
||||
.into_bytes();
|
||||
key_phrase_hash[0..16].try_into().unwrap()
|
||||
}
|
||||
}
|
||||
@@ -35,14 +35,22 @@ pub enum Error {
|
||||
#[error(display = "Dropped connection")]
|
||||
BroadcastDroppedConnectionTry(#[error(source)] tokio::sync::broadcast::error::TryRecvError),
|
||||
|
||||
/// Raised when the RX_TIMEOUT is reach
|
||||
/// Raised when the TIMEOUT is reach
|
||||
#[error(display = "Timeout")]
|
||||
Timeout,
|
||||
Timeout(#[error(source)] std::sync::Arc<tokio::time::error::Elapsed>),
|
||||
|
||||
/// Raised when a timeout fails in a non standard way such as timeout during shutdown
|
||||
#[error(display = "TimeoutError")]
|
||||
TimeoutError(#[error(source)] tokio::time::error::Error),
|
||||
|
||||
/// Raised when connection is dropped because the timeout is reach
|
||||
#[error(display = "Dropped connection")]
|
||||
TimeoutDisconnected,
|
||||
|
||||
/// Raised when a camera cannot be connected to ay any of the given addresses
|
||||
#[error(display = "Cannot contact camera at given address")]
|
||||
CannotInitCamera,
|
||||
|
||||
/// Raised when failed to login to the camera
|
||||
#[error(display = "Credential error")]
|
||||
AuthFailed,
|
||||
@@ -63,13 +71,20 @@ pub enum Error {
|
||||
#[error(display = "Cookie GenError")]
|
||||
GenError(#[error(source)] std::sync::Arc<cookie_factory::GenError>),
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once
|
||||
/// Raised when a connection is subscrbed to more than once for msg_num
|
||||
#[error(display = "Simultaneous subscription, {}", _0)]
|
||||
SimultaneousSubscription {
|
||||
/// The message number that was subscribed to
|
||||
msg_num: u16,
|
||||
},
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once for msg_id
|
||||
#[error(display = "Simultaneous subscription, {}", _0)]
|
||||
SimultaneousSubscriptionId {
|
||||
/// The message number that was subscribed to
|
||||
msg_id: u32,
|
||||
},
|
||||
|
||||
/// Raised when a new encyrption byte is observed
|
||||
#[error(display = "Unknown encryption: {:x?}", _0)]
|
||||
UnknownEncryption(usize),
|
||||
@@ -155,6 +170,12 @@ impl From<local_ip_address::Error> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<tokio::time::error::Elapsed> for Error {
|
||||
fn from(k: tokio::time::error::Elapsed) -> Self {
|
||||
Error::Timeout(std::sync::Arc::new(k))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<nom::Err<NomErrorType<'a>>> for Error {
|
||||
fn from(k: nom::Err<NomErrorType<'a>>) -> Self {
|
||||
match k {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
use super::{BcCamera, Result};
|
||||
use crate::bc::model::*;
|
||||
|
||||
impl BcCamera {
|
||||
/// Create a handller to respond to keep alive messages
|
||||
/// These messages are sent by the camera so we listen to
|
||||
/// a message ID rather than setting a message number and
|
||||
/// responding to it
|
||||
pub async fn keepalive(&self) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
connection
|
||||
.handle_msg(MSG_ID_UDP_KEEP_ALIVE, |bc| {
|
||||
Some(Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_UDP_KEEP_ALIVE,
|
||||
channel_id: bc.meta.channel_id,
|
||||
msg_num: bc.meta.msg_num,
|
||||
stream_type: bc.meta.stream_type,
|
||||
response_code: 200,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
..Default::default()
|
||||
}),
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,35 @@ use super::{md5_string, BcCamera, Error, Result, Truncate, ZeroLast};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
/// The requested encryption level to request
|
||||
/// to the camera
|
||||
///
|
||||
/// The camera may use a lower one depending on support
|
||||
///
|
||||
/// Note the reolink camera only encrypt the control messages
|
||||
/// the camera feed is always accessible
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum MaxEncryption {
|
||||
/// No encryption
|
||||
None,
|
||||
/// BCEncrypt is a simple XOR algortirhm with a fixed key
|
||||
/// used in many older models
|
||||
BcEncrypt,
|
||||
/// AES is used in newer model
|
||||
Aes,
|
||||
}
|
||||
|
||||
impl BcCamera {
|
||||
/// Login to the camera.
|
||||
///
|
||||
/// This should be called before most other commands
|
||||
pub async fn login(&self) -> Result<DeviceInfo> {
|
||||
self.login_with_maxenc(MaxEncryption::Aes).await
|
||||
}
|
||||
/// Login to the camera.
|
||||
///
|
||||
/// This should be called before most other commands
|
||||
pub async fn login_with_maxenc(&self, max_encryption: MaxEncryption) -> Result<DeviceInfo> {
|
||||
let device_info;
|
||||
// This { is here due to the connection and set_credentials both requiring a mutable borrow
|
||||
{
|
||||
@@ -31,13 +55,18 @@ impl BcCamera {
|
||||
.map(|p| md5_string(p, ZeroLast))
|
||||
.unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned());
|
||||
|
||||
let enc_byte = match max_encryption {
|
||||
MaxEncryption::None => 0xdc00,
|
||||
MaxEncryption::BcEncrypt => 0xdc01,
|
||||
MaxEncryption::Aes => 0xdc02,
|
||||
};
|
||||
let legacy_login = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_LOGIN,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0xdc02,
|
||||
response_code: enc_byte,
|
||||
class: 0x6514,
|
||||
},
|
||||
body: BcBody::LegacyMsg(LegacyMsg::LoginMsg {
|
||||
|
||||
@@ -22,11 +22,19 @@ pub enum DiscoveryMethods {
|
||||
///
|
||||
/// **This also enabled `Local` discovery**
|
||||
Remote,
|
||||
/// Allow contact with the reolink servers to learn the ip address and relay the connection
|
||||
/// through those servers.
|
||||
/// Allow contact with the reolink servers to learn the ip address and map the connection
|
||||
/// from dev to client through those servers.
|
||||
///
|
||||
/// **This also enabled `Local` and `Remote` discovery**
|
||||
Map,
|
||||
/// Allow contact with the reolink servers to learn the ip address and relay the connection
|
||||
/// client to dev through those servers.
|
||||
///
|
||||
/// **This also enabled `Local`, `Map` and `Remote` discovery**
|
||||
Relay,
|
||||
#[doc(hidden)]
|
||||
/// Used for debugging it is set to whatever the dev is currently testing
|
||||
Debug,
|
||||
}
|
||||
|
||||
/// Used to return either the SocketAddr or the UID
|
||||
|
||||
@@ -31,6 +31,7 @@ pub enum StreamKind {
|
||||
///
|
||||
/// When this object is dropped the streaming is stopped
|
||||
pub struct StreamData {
|
||||
#[allow(dead_code)]
|
||||
handle: Option<JoinHandle<Result<()>>>,
|
||||
rx: Receiver<Result<BcMedia>>,
|
||||
abort_handle: Arc<AtomicBool>,
|
||||
@@ -50,12 +51,6 @@ impl StreamData {
|
||||
impl Drop for StreamData {
|
||||
fn drop(&mut self) {
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
if let Some(h) = self.handle.take() {
|
||||
let backoff = crossbeam::utils::Backoff::new();
|
||||
while !h.is_finished() {
|
||||
backoff.snooze();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,10 +66,13 @@ impl BcCamera {
|
||||
/// The buffer_size represents number of compete messages so 1 would be one complete message
|
||||
/// which may be a single audio frame or a whole video key frame. If 0 a default of 100 is used
|
||||
///
|
||||
/// A value of scrict=true will mean that the stream will error if the underlying stream is not
|
||||
/// as expected
|
||||
pub async fn start_video(
|
||||
&self,
|
||||
stream: StreamKind,
|
||||
mut buffer_size: usize,
|
||||
strict: bool,
|
||||
) -> Result<StreamData> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
@@ -162,7 +160,7 @@ impl BcCamera {
|
||||
}
|
||||
|
||||
{
|
||||
let mut media_sub = sub_video.bcmedia_stream();
|
||||
let mut media_sub = sub_video.bcmedia_stream(strict);
|
||||
|
||||
while !abort_handle_thread.load(Ordering::Relaxed) {
|
||||
if let Some(bc_media) = media_sub.next().await {
|
||||
|
||||
@@ -4,14 +4,19 @@
|
||||
//!
|
||||
use crate::bcmedia::model::*;
|
||||
use crate::{Error, Result};
|
||||
use bytes::BytesMut;
|
||||
use bytes::{Buf, BytesMut};
|
||||
use log::*;
|
||||
use tokio_util::codec::{Decoder, Encoder};
|
||||
|
||||
pub struct BcMediaCodex {}
|
||||
pub struct BcMediaCodex {
|
||||
/// If true we will not search for the start of the next packet
|
||||
/// in the event that the stream appears to be corrupted
|
||||
strict: bool,
|
||||
}
|
||||
|
||||
impl BcMediaCodex {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {}
|
||||
pub(crate) fn new(strict: bool) -> Self {
|
||||
Self { strict }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,10 +37,33 @@ impl Decoder for BcMediaCodex {
|
||||
type Error = Error;
|
||||
|
||||
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||
match { BcMedia::deserialize(src) } {
|
||||
Ok(bc) => Ok(Some(bc)),
|
||||
Err(Error::NomIncomplete(_)) => Ok(None),
|
||||
Err(e) => Err(e),
|
||||
let mut amount_skipped: usize = 0;
|
||||
loop {
|
||||
match { BcMedia::deserialize(src) } {
|
||||
Ok(bc) => {
|
||||
if amount_skipped > 0 {
|
||||
trace!("Amount skipped to restore stream: {}", amount_skipped);
|
||||
}
|
||||
return Ok(Some(bc));
|
||||
}
|
||||
Err(Error::NomIncomplete(_)) => {
|
||||
if amount_skipped > 0 {
|
||||
trace!("Amount skipped to restore stream: {}", amount_skipped);
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
Err(e) => {
|
||||
if self.strict {
|
||||
return Err(e);
|
||||
} else if src.is_empty() {
|
||||
return Ok(None);
|
||||
} else {
|
||||
src.advance(1);
|
||||
amount_skipped += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/// Video streams encapsulate a stream of BcMedia
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum BcMedia {
|
||||
/// Holds info on the stream
|
||||
InfoV1(BcMediaInfoV1),
|
||||
@@ -19,7 +19,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V1: u32 = 0x31303031;
|
||||
|
||||
/// The start of a BcMedia stream contains this message
|
||||
/// which describes the data to follow
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BcMediaInfoV1 {
|
||||
// This is the size of the header so it's actually a fixed value
|
||||
// The other messages have body size here so maybe that's why
|
||||
@@ -63,7 +63,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V2: u32 = 0x32303031;
|
||||
|
||||
/// The start of a BcMedia stream contains this message
|
||||
/// which describes the data to follow
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BcMediaInfoV2 {
|
||||
// This is the size of the header so it's actually a fixed value
|
||||
// The other messages have body size here so maybe that's why
|
||||
@@ -108,7 +108,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME: u32 = 0x63643030;
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME_LAST: u32 = 0x63643039;
|
||||
|
||||
/// Video Types for I/PFrame
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum VideoType {
|
||||
/// H264 video data
|
||||
H264,
|
||||
@@ -117,7 +117,7 @@ pub enum VideoType {
|
||||
}
|
||||
|
||||
/// This is a BcMedia video IFrame.
|
||||
#[derive(Debug)]
|
||||
#[derive(Clone)]
|
||||
pub struct BcMediaIframe {
|
||||
/// "H264", or "H265"
|
||||
pub video_type: VideoType,
|
||||
@@ -134,12 +134,32 @@ pub struct BcMediaIframe {
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for BcMediaIframe {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"video_type", &self.video_type)
|
||||
// .entry(&"payload_size", &self.payload_size)
|
||||
.entry(&"microseconds", &self.microseconds)
|
||||
.entry(&"time", &self.time)
|
||||
.entry(
|
||||
&"data[0..10]",
|
||||
&self.data[0..std::cmp::min(20, self.data.len())].to_vec(),
|
||||
)
|
||||
.entry(
|
||||
&"data[-10..-1]",
|
||||
&self.data[std::cmp::max(0, self.data.len() - 20)..self.data.len()].to_vec(),
|
||||
)
|
||||
.entry(&"data.len()", &self.data.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
// PFrame magics include the channel number in them
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME: u32 = 0x63643130;
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME_LAST: u32 = 0x63643139;
|
||||
|
||||
/// This is a BcMedia video PFrame.
|
||||
#[derive(Debug)]
|
||||
#[derive(Clone)]
|
||||
pub struct BcMediaPframe {
|
||||
/// "H264", or "H265"
|
||||
pub video_type: VideoType,
|
||||
@@ -153,10 +173,29 @@ pub struct BcMediaPframe {
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for BcMediaPframe {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"video_type", &self.video_type)
|
||||
// .entry(&"payload_size", &self.payload_size)
|
||||
.entry(&"microseconds", &self.microseconds)
|
||||
.entry(
|
||||
&"data[0..20]",
|
||||
&self.data[0..std::cmp::min(20, self.data.len())].to_vec(),
|
||||
)
|
||||
.entry(
|
||||
&"data[-20..-1]",
|
||||
&self.data[std::cmp::max(0, self.data.len() - 20)..self.data.len()].to_vec(),
|
||||
)
|
||||
.entry(&"data.len()", &self.data.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_AAC: u32 = 0x62773530;
|
||||
|
||||
/// This contains BcMedia audio data in AAC format
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BcMediaAac {
|
||||
// Size of payload after header in bytes
|
||||
// pub payload_size: u16,
|
||||
@@ -171,7 +210,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM: u32 = 0x62773130;
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM_DATA: u16 = 0x0100;
|
||||
|
||||
/// This contains BcMedia audio data in ADPCM format
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BcMediaAdpcm {
|
||||
// Size of payload after header in bytes
|
||||
// pub payload_size: u16,
|
||||
|
||||
@@ -89,8 +89,10 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> {
|
||||
let (buf, connection_id) = error_context("ACK: Missing connect ID", le_i32)(buf)?;
|
||||
let (buf, _unknown_a) =
|
||||
error_context("ACK: Unable to verify UnknowA", verify(le_u32, |&x| x == 0))(buf)?;
|
||||
let (buf, _unknown_b) =
|
||||
error_context("ACK: Unable to verify UnknowB", verify(le_u32, |&x| x == 0))(buf)?;
|
||||
let (buf, group_id) = error_context(
|
||||
"ACK: Unable to verify UnknowB",
|
||||
verify(le_u32, |&x| x == 0 || x == 0xffffffff),
|
||||
)(buf)?;
|
||||
let (buf, packet_id) = error_context("Missing packet_id", le_u32)(buf)?; // This is the point at which the camera has contigious
|
||||
// packets to
|
||||
let (buf, _unknown) = error_context("ACK: Missing unknown", le_u32)(buf)?;
|
||||
@@ -109,6 +111,7 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> {
|
||||
let data = UdpAck {
|
||||
connection_id,
|
||||
packet_id,
|
||||
group_id,
|
||||
payload,
|
||||
};
|
||||
Ok((buf, data))
|
||||
|
||||
@@ -63,7 +63,9 @@ pub struct UdpAck {
|
||||
/// register and then download the same connection id from the register_address
|
||||
/// it comes back in an xml that is encoded as i32 (i.e. can be negative string)
|
||||
pub connection_id: i32,
|
||||
// Unknown 4 bytes always 0
|
||||
/// Unknown 4 bytes always 0 for normal ack or -1 for signalling no packets received yet
|
||||
/// Tentativly assigned as a kinda group id
|
||||
pub group_id: u32,
|
||||
/// The ID of the last data packet [`UdpData`]
|
||||
pub packet_id: u32,
|
||||
// 2 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000`
|
||||
@@ -76,6 +78,19 @@ pub struct UdpAck {
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl UdpAck {
|
||||
/// Create an empty ack packet to signifiy no packets recieved yet
|
||||
/// These are a little different in that they also set `group_id`
|
||||
pub fn empty(connection_id: i32) -> Self {
|
||||
Self {
|
||||
connection_id,
|
||||
group_id: 0xffffffff,
|
||||
packet_id: 0xffffffff,
|
||||
payload: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Magic for the UDP Data packet
|
||||
pub const MAGIC_HEADER_UDP_DATA: u32 = 0x2a87cf10;
|
||||
|
||||
@@ -107,7 +122,7 @@ impl std::fmt::Debug for UdpData {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"connection_id", &self.connection_id)
|
||||
.entry(&"packet_id", &self.connection_id)
|
||||
.entry(&"packet_id", &self.packet_id)
|
||||
.entry(&"payload_len", &self.payload.len())
|
||||
.finish()
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ fn bcudp_ack<'a, W: 'a + Write>(
|
||||
le_u32(MAGIC_HEADER_UDP_ACK),
|
||||
le_i32(payload.connection_id),
|
||||
le_u32(0),
|
||||
le_u32(0),
|
||||
le_u32(payload.group_id),
|
||||
le_u32(payload.packet_id),
|
||||
le_u32(0),
|
||||
le_u32(binary_payload.len() as u32),
|
||||
|
||||
@@ -283,6 +283,8 @@ pub struct R2cT {
|
||||
///
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
|
||||
pub struct R2cCr {
|
||||
/// Dev camera location (actual local ip)
|
||||
pub dev: IpPort,
|
||||
/// Dmap camera location
|
||||
pub dmap: IpPort,
|
||||
/// The location of the relay
|
||||
|
||||
+14
-47
@@ -38,56 +38,23 @@ pub mod bcudp;
|
||||
/// Most commands will either return their `Ok(result)` or this `Err(Error)`
|
||||
pub use bc_protocol::Error;
|
||||
|
||||
pub(crate) use bc_protocol::Result;
|
||||
pub(crate) use bc_protocol::{Credentials, Result};
|
||||
|
||||
pub(crate) type NomErrorType<'a> = nom::error::VerboseError<&'a [u8]>;
|
||||
|
||||
// Used for caching the credentials
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Credentials {
|
||||
username: String,
|
||||
password: Option<String>,
|
||||
lazy_static::lazy_static! {
|
||||
/// This is a high level tiemout for the app as a whole. Not the lowlevel io ones
|
||||
///
|
||||
/// This is used to timeout when the primary send and receive channels of Bc packets
|
||||
/// is full for too long. This can happen if messages are not pulled from the endpoints
|
||||
/// fast enough or if there is an unexpected bug
|
||||
pub(crate) static ref TIMEOUT: tokio::time::Duration = tokio::time::Duration::from_secs(60);
|
||||
}
|
||||
|
||||
impl Default for Credentials {
|
||||
/// Default credentials for some reolink cameras
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
username: "admin".to_string(),
|
||||
password: Some("123456".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Credentials {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"username", &self.username)
|
||||
.entry(&"password", &"******")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
use std::convert::TryInto;
|
||||
impl Credentials {
|
||||
pub(crate) fn new<T: Into<String>, U: Into<String>>(username: T, password: Option<U>) -> Self {
|
||||
Self {
|
||||
username: username.into(),
|
||||
password: password.map(|t| t.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a convience function to make an AES key from the login password and the NONCE
|
||||
/// negotiated during login
|
||||
pub(crate) fn make_aeskey<T: AsRef<str>>(&self, nonce: T) -> [u8; 16] {
|
||||
let key_phrase = format!(
|
||||
"{}-{}",
|
||||
nonce.as_ref(),
|
||||
self.password.clone().unwrap_or_default()
|
||||
);
|
||||
let key_phrase_hash = format!("{:X}\0", md5::compute(key_phrase))
|
||||
.to_uppercase()
|
||||
.into_bytes();
|
||||
key_phrase_hash[0..16].try_into().unwrap()
|
||||
}
|
||||
/// A convience future to timeout with the default timeout specified in [`TIMEOUT`]
|
||||
pub(crate) fn timeout<F>(future: F) -> tokio::time::Timeout<F>
|
||||
where
|
||||
F: std::future::Future,
|
||||
{
|
||||
tokio::time::timeout(*TIMEOUT, future)
|
||||
}
|
||||
@@ -2,6 +2,20 @@
|
||||
-- Copy/symlink it into ~/.local/lib/wireshark/plugins/ and restart Wireshark; it should
|
||||
-- automatically attempt to decode TCP connections on port 9000.
|
||||
|
||||
-- Copyright (c) the Neolink contributors
|
||||
--
|
||||
-- This program is free software: you can redistribute it and/or modify it
|
||||
-- under the terms of the GNU Affero General Public License, version 3, as
|
||||
-- published by the Free Software Foundation.
|
||||
--
|
||||
-- This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
-- FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
-- more details.
|
||||
--
|
||||
-- You should have received a copy of the GNU General Public License along with
|
||||
-- this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
local bc_protocol = Proto("Baichuan", "Baichuan/Reolink IP Camera Protocol")
|
||||
|
||||
local magic_bytes = ProtoField.int32("baichuan.magic", "magic", base.DEC)
|
||||
@@ -151,6 +165,7 @@ local message_types = {
|
||||
[209]="<LedState> (write)",
|
||||
[210]="<PTOP>",
|
||||
[211]="<PTOP> (write)",
|
||||
[212]="<rfAlarmCfg>",
|
||||
[216]="<EmailTask> (write)",
|
||||
[217]="<EmailTask>",
|
||||
[218]="<PushTask> (write)",
|
||||
@@ -158,6 +173,9 @@ local message_types = {
|
||||
[228]="<Crop>",
|
||||
[229]="<Crop> (write)",
|
||||
[230]="<cropSnap>",
|
||||
[234]="UDP Keep Alive",
|
||||
[252]="<BatteryInfoList>",
|
||||
[253]="<BatteryInfo>",
|
||||
[272]="<findAlarmVideo>",
|
||||
[273]="<alarmVideoInfo>",
|
||||
[274]="<findAlarmVideo>",
|
||||
|
||||
@@ -51,6 +51,30 @@ address = "192.168.1.187:9000"
|
||||
# If your device has user connection limits try a single stream instead.
|
||||
# stream = "mainStream"
|
||||
|
||||
# By default neolink will use any means to connect to the camera
|
||||
# from a UID
|
||||
# This include relaying via reolink servers
|
||||
# This variable `discovery` controls the method of UID discovery
|
||||
# - Possible values
|
||||
# "relay" # Any means including connecting and transmitting through reolink
|
||||
# "map" # Register our local ip address with reolink and ask the camera to connect to us but don't relay data through reolink
|
||||
# "remote" # Register our local ip address with reolink but only permit same network connections (useful if broadcast is not possible)
|
||||
# "local" # Do not contact reolink servers at all. Rely soley on local UDP broadcast based discovery
|
||||
#
|
||||
# discovery = "relay"
|
||||
|
||||
# Certain types of camera emit status messages (such as battery levels)
|
||||
#
|
||||
# By default we hide these status messages from the user but you can instead requst that
|
||||
# they be printed to stdout using print_format
|
||||
#
|
||||
# Valid values are:
|
||||
# - None
|
||||
# - Human
|
||||
# - Xml
|
||||
#
|
||||
# print_format = "None"
|
||||
|
||||
|
||||
[[cameras]]
|
||||
name = "storage shed"
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Use to decode AES packet data
|
||||
use hex_string::HexString;
|
||||
use requestty::Question;
|
||||
use std::convert::TryInto;
|
||||
|
||||
use aes::Aes128;
|
||||
use cfb_mode::cipher::{NewStreamCipher, StreamCipher};
|
||||
use cfb_mode::Cfb;
|
||||
|
||||
const IV: &[u8] = b"0123456789abcdef";
|
||||
|
||||
fn decrypt(buf: &[u8], aeskey: &[u8; 16]) -> Vec<u8> {
|
||||
let mut decrypted = buf.to_vec();
|
||||
Cfb::<Aes128>::new(aeskey.into(), IV.into()).decrypt(&mut decrypted);
|
||||
decrypted
|
||||
}
|
||||
|
||||
fn make_aeskey<T: AsRef<str>>(password: T, nonce: T) -> [u8; 16] {
|
||||
let key_phrase = format!("{}-{}", nonce.as_ref(), password.as_ref(),);
|
||||
let key_phrase_hash = format!("{:X}\0", md5::compute(key_phrase))
|
||||
.to_uppercase()
|
||||
.into_bytes();
|
||||
key_phrase_hash[0..16].try_into().unwrap()
|
||||
}
|
||||
|
||||
fn main() -> Result<(), anyhow::Error> {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
|
||||
let question = Question::input("hex")
|
||||
.message("Enter the hex string to decode")
|
||||
.build();
|
||||
|
||||
let source_str: String = requestty::prompt_one(question)?
|
||||
.as_string()
|
||||
.ok_or_else(|| anyhow::anyhow!("Did not get reply"))?
|
||||
.to_string();
|
||||
|
||||
let question = Question::password("password")
|
||||
.message("Enter Camera Password")
|
||||
.mask('*')
|
||||
.build();
|
||||
let pass = requestty::prompt_one(question)?
|
||||
.as_string()
|
||||
.ok_or_else(|| anyhow::anyhow!("Did not get reply"))?
|
||||
.to_string();
|
||||
|
||||
let question = Question::password("nonce")
|
||||
.message("Enter Login Nonce")
|
||||
.mask('*')
|
||||
.build();
|
||||
let nonce = requestty::prompt_one(question)?
|
||||
.as_string()
|
||||
.ok_or_else(|| anyhow::anyhow!("Did not get reply"))?
|
||||
.to_string();
|
||||
|
||||
let source_hex = HexString::from_string(&source_str).unwrap();
|
||||
|
||||
let decrypted = decrypt(&source_hex.as_bytes(), &make_aeskey(&pass, &nonce));
|
||||
log::info!("Bytes: {:X?}", decrypted);
|
||||
log::info!("Text: {}", String::from_utf8(decrypted)?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -2,6 +2,9 @@ use std::path::PathBuf;
|
||||
use structopt::{clap::AppSettings, StructOpt};
|
||||
|
||||
/// A standards-compliant bridge to Reolink IP cameras
|
||||
///
|
||||
/// Neolink is free software released under the GNU AGPL v3.
|
||||
/// You can find its source code at https://github.com/thirtythreeforty/neolink
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(
|
||||
name = "neolink",
|
||||
@@ -23,4 +26,5 @@ pub enum Command {
|
||||
Pir(super::pir::Opt),
|
||||
Talk(super::talk::Opt),
|
||||
Mqtt(super::mqtt::Opt),
|
||||
Image(super::image::Opt),
|
||||
}
|
||||
+32
-1
@@ -1,4 +1,5 @@
|
||||
use lazy_static::lazy_static;
|
||||
use neolink_core::bc_protocol::PrintFormat;
|
||||
use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
use std::clone::Clone;
|
||||
@@ -10,7 +11,10 @@ lazy_static! {
|
||||
Regex::new(r"^(mainStream|subStream|externStream|both|all)$").unwrap();
|
||||
static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap();
|
||||
static ref RE_PAUSE_MODE: Regex = Regex::new(r"^(black|still|test|none)$").unwrap();
|
||||
static ref RE_DISC_SRC: Regex = Regex::new(r"^([nN]one|[lL]ocal|[rR]emote|[rR]elay)$").unwrap();
|
||||
static ref RE_DISC_SRC: Regex =
|
||||
Regex::new(r"^([nN]one|[lL]ocal|[rR]emote|[Mm]ap|[rR]elay|[Dd]ebug)$").unwrap();
|
||||
static ref RE_MAXENC_SRC: Regex =
|
||||
Regex::new(r"^([nN]one|[Aa][Ee][Ss]|[Bb][Cc][Ee][Nn][Cc][Rr][Yy][Pp][Tt])$").unwrap();
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
@@ -84,6 +88,21 @@ pub(crate) struct CameraConfig {
|
||||
code = "discovery"
|
||||
))]
|
||||
pub(crate) discovery: String,
|
||||
|
||||
#[serde(default = "default_maxenc")]
|
||||
#[validate(regex(
|
||||
path = "RE_MAXENC_SRC",
|
||||
message = "Invalid maximum encryption method",
|
||||
code = "max_encryption"
|
||||
))]
|
||||
pub(crate) max_encryption: String,
|
||||
|
||||
#[serde(default = "default_strict")]
|
||||
/// If strict then the media stream will error in the event that the media packets are not as expected
|
||||
pub(crate) strict: bool,
|
||||
|
||||
#[serde(default = "default_print", alias = "print")]
|
||||
pub(crate) print_format: PrintFormat,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
@@ -128,10 +147,18 @@ fn default_mqtt() -> Option<MqttConfig> {
|
||||
None
|
||||
}
|
||||
|
||||
fn default_print() -> PrintFormat {
|
||||
PrintFormat::None
|
||||
}
|
||||
|
||||
fn default_discovery() -> String {
|
||||
"Relay".to_string()
|
||||
}
|
||||
|
||||
fn default_maxenc() -> String {
|
||||
"Aes".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct PauseConfig {
|
||||
#[serde(default = "default_on_motion")]
|
||||
@@ -192,6 +219,10 @@ fn default_pause_mode() -> String {
|
||||
"none".to_string()
|
||||
}
|
||||
|
||||
fn default_strict() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn default_pause() -> PauseConfig {
|
||||
PauseConfig {
|
||||
on_motion: default_on_motion(),
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
use std::path::PathBuf;
|
||||
use structopt::StructOpt;
|
||||
|
||||
/// The image command will dump a still image from the camera
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct Opt {
|
||||
/// The name of the camera to get the image from. Must be a name in the config
|
||||
pub camera: String,
|
||||
/// The path of the output.
|
||||
#[structopt(short, long, parse(from_os_str))]
|
||||
pub file_path: PathBuf,
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use gstreamer::{parse_launch, prelude::*, ClockTime, MessageView, Pipeline, State};
|
||||
use gstreamer_app::AppSrc;
|
||||
use neolink_core::bcmedia::model::VideoType;
|
||||
use tokio::{
|
||||
sync::{
|
||||
self,
|
||||
mpsc::{channel, Sender},
|
||||
},
|
||||
task::{self, JoinSet},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
enum GstControl {
|
||||
Data(Vec<u8>),
|
||||
Eos,
|
||||
}
|
||||
|
||||
pub(super) struct GstSender {
|
||||
sender: Sender<GstControl>,
|
||||
#[allow(dead_code)] // It is used for its automatic drop
|
||||
set: JoinSet<Result<()>>,
|
||||
finished: sync::oneshot::Receiver<Result<()>>,
|
||||
}
|
||||
|
||||
impl GstSender {
|
||||
pub(super) async fn send(&self, buf: Vec<u8>) -> Result<()> {
|
||||
self.sender
|
||||
.send(GstControl::Data(buf))
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to send buffer: {:?}", e))
|
||||
}
|
||||
|
||||
pub(super) async fn eos(&self) -> Result<()> {
|
||||
self.sender
|
||||
.send(GstControl::Eos)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to send eos: {:?}", e))
|
||||
}
|
||||
|
||||
pub(super) async fn is_finished(&mut self) -> Option<Result<()>> {
|
||||
match self.finished.try_recv() {
|
||||
Ok(res) => Some(res),
|
||||
Err(sync::oneshot::error::TryRecvError::Empty) => None,
|
||||
Err(sync::oneshot::error::TryRecvError::Closed) => {
|
||||
Some(Err(anyhow!("Gstreamer finished channel is closed")))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn from_input<T: AsRef<Path>>(
|
||||
format: VideoType,
|
||||
out_file: T,
|
||||
) -> Result<GstSender> {
|
||||
let pipeline = create_pipeline(format, out_file.as_ref())?;
|
||||
output(pipeline).await
|
||||
}
|
||||
|
||||
async fn output(pipeline: Pipeline) -> Result<GstSender> {
|
||||
let source = get_source(&pipeline)?;
|
||||
let (sender, mut reciever) = channel::<GstControl>(100);
|
||||
let mut set = JoinSet::new();
|
||||
set.spawn(async move {
|
||||
while let Some(control) = reciever.recv().await {
|
||||
match control {
|
||||
GstControl::Data(buf) => {
|
||||
let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
let mut gst_buf_data = gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(&buf);
|
||||
}
|
||||
source.push_buffer(gst_buf)?;
|
||||
}
|
||||
GstControl::Eos => {
|
||||
source.end_of_stream()?;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
let (tx, finished) = sync::oneshot::channel();
|
||||
task::spawn_blocking(move || {
|
||||
let res = start_pipeline(pipeline);
|
||||
if let Err(e) = &res {
|
||||
log::error!("Failed to run pipeline: {:?}", e);
|
||||
}
|
||||
tx.send(res)
|
||||
});
|
||||
|
||||
Ok(GstSender {
|
||||
sender,
|
||||
set,
|
||||
finished,
|
||||
})
|
||||
}
|
||||
|
||||
fn start_pipeline(pipeline: Pipeline) -> Result<()> {
|
||||
pipeline.set_state(State::Playing)?;
|
||||
|
||||
let bus = pipeline
|
||||
.bus()
|
||||
.expect("Pipeline without bus. Shouldn't happen!");
|
||||
|
||||
for msg in bus.iter_timed(ClockTime::NONE) {
|
||||
match msg.view() {
|
||||
MessageView::Eos(..) => break,
|
||||
MessageView::Error(err) => {
|
||||
pipeline
|
||||
.set_state(State::Null)
|
||||
.context("Error in gstreamer when setting state to Null")?;
|
||||
log::warn!(
|
||||
"Error from gstreamer when setting the play state {:?} setting to Null instead",
|
||||
err
|
||||
);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
pipeline
|
||||
.set_state(State::Null)
|
||||
.context("Error in gstreamer when setting state to Null")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_source(pipeline: &Pipeline) -> Result<AppSrc> {
|
||||
let source = pipeline
|
||||
.by_name("thesource")
|
||||
.expect("There shoud be a `thesource`");
|
||||
source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.map_err(|_| anyhow!("Cannot find appsource in gstreamer, check your gstreamer plugins"))
|
||||
}
|
||||
|
||||
fn create_pipeline(format: VideoType, file_path: &Path) -> Result<Pipeline> {
|
||||
gstreamer::init()
|
||||
.context("Unable to start gstreamer ensure it and all plugins are installed")?;
|
||||
let file_path = file_path.with_extension("jpeg");
|
||||
|
||||
let launch_str = match format {
|
||||
VideoType::H264 => {
|
||||
format!(
|
||||
"appsrc name=thesource \
|
||||
! h264parse \
|
||||
! decodebin \
|
||||
! jpegenc snapshot=TRUE
|
||||
! filesink location={}",
|
||||
file_path.display()
|
||||
)
|
||||
}
|
||||
VideoType::H265 => {
|
||||
format!(
|
||||
"appsrc name=thesource \
|
||||
! h265parse \
|
||||
! decodebin \
|
||||
! jpegenc snapshot=TRUE
|
||||
! filesink location={}",
|
||||
file_path.display()
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
log::info!("{}", launch_str);
|
||||
|
||||
// Parse the pipeline we want to probe from a static in-line string.
|
||||
// Here we give our audiotestsrc a name, so we can retrieve that element
|
||||
// from the resulting pipeline.
|
||||
let pipeline = parse_launch(&launch_str)
|
||||
.context("Unable to load gstreamer pipeline ensure all gstramer plugins are installed")?;
|
||||
let pipeline = pipeline.dynamic_cast::<Pipeline>().map_err(|_| {
|
||||
anyhow!("Unable to create gstreamer pipeline ensure all gstramer plugins are installed")
|
||||
})?;
|
||||
|
||||
// let appssource = get_source(&pipeline)?;
|
||||
|
||||
// Tell the appsink what format we produce.
|
||||
// let caps = match format {
|
||||
// VideoType::H264 => Caps::new_simple("video/x-h264", &[("parsed", &false)]),
|
||||
// VideoType::H265 => Caps::new_simple("video/x-h265", &[("parsed", &false)]),
|
||||
// };
|
||||
// appssource.set_caps(Some(&caps));
|
||||
|
||||
Ok(pipeline)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
///
|
||||
/// # Neolink Image
|
||||
///
|
||||
/// This module can be used to dump a still image from the camera
|
||||
///
|
||||
///
|
||||
/// # Usage
|
||||
/// ```bash
|
||||
/// neolink image --config=config.toml --file-path=filepath CameraName
|
||||
/// ```
|
||||
///
|
||||
use anyhow::{Context, Result};
|
||||
use log::*;
|
||||
use neolink_core::{bc_protocol::*, bcmedia::model::*};
|
||||
|
||||
mod cmdline;
|
||||
mod gst;
|
||||
|
||||
use super::config::Config;
|
||||
use crate::utils::{connect_and_login, find_camera_by_name};
|
||||
pub(crate) use cmdline::Opt;
|
||||
|
||||
/// Entry point for the image subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
let camera_config = find_camera_by_name(&config, &opt.camera).context(
|
||||
"failed to load config file or find the camera. Check the path and name of the camera.",
|
||||
)?;
|
||||
|
||||
// Set up camera to recieve the stream
|
||||
let camera = connect_and_login(camera_config)
|
||||
.await
|
||||
.context("Failed to connect to the camera, check credentials and network")?;
|
||||
let mut stream_data = camera
|
||||
.start_video(StreamKind::Main, 0, camera_config.strict)
|
||||
.await
|
||||
.context("Failed to start video")?;
|
||||
|
||||
// Get one iframe at the start while also getting the the video type
|
||||
let buf;
|
||||
let vid_type;
|
||||
loop {
|
||||
if let BcMedia::Iframe(frame) = stream_data.get_data().await?? {
|
||||
vid_type = frame.video_type;
|
||||
buf = frame.data;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let mut sender = gst::from_input(vid_type, &opt.file_path).await?;
|
||||
sender.send(buf).await?; // Send first iframe
|
||||
|
||||
// Keep sending both IFrame or PFrame until finished
|
||||
while sender.is_finished().await.is_none() {
|
||||
let buf = match stream_data.get_data().await?? {
|
||||
BcMedia::Iframe(frame) => frame.data,
|
||||
BcMedia::Pframe(frame) => frame.data,
|
||||
_ => {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
debug!("Sending frame data to gstreamer");
|
||||
if sender.send(buf).await.is_err() {
|
||||
// Assume that the sender is closed
|
||||
// because the pipeline is finished
|
||||
break;
|
||||
}
|
||||
}
|
||||
debug!("Sending EOS");
|
||||
let _ = sender.eos().await; // Ignore return because if pipeline is finished this will error
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+17
@@ -7,6 +7,19 @@
|
||||
//! It contains sub commands for running an rtsp proxy which can be used on Reolink cameras
|
||||
//! that do not nativly support RTSP.
|
||||
//!
|
||||
//! This program is free software: you can redistribute it and/or modify it under the terms of the
|
||||
//! GNU General Public License as published by the Free Software Foundation, either version 3 of
|
||||
//! the License, or (at your option) any later version.
|
||||
//!
|
||||
//! This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
|
||||
//! without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
|
||||
//! the GNU General Public License for more details.
|
||||
//!
|
||||
//! You should have received a copy of the GNU General Public License along with this program. If
|
||||
//! not, see <https://www.gnu.org/licenses/>.
|
||||
//!
|
||||
//! Neolink source code is available online at <https://github.com/thirtythreeforty/neolink>
|
||||
//!
|
||||
use anyhow::{Context, Result};
|
||||
use env_logger::Env;
|
||||
use log::*;
|
||||
@@ -16,6 +29,7 @@ use validator::Validate;
|
||||
|
||||
mod cmdline;
|
||||
mod config;
|
||||
mod image;
|
||||
mod mqtt;
|
||||
mod pir;
|
||||
mod reboot;
|
||||
@@ -76,6 +90,9 @@ async fn main() -> Result<()> {
|
||||
Some(Command::Mqtt(opts)) => {
|
||||
mqtt::main(opts, config).await?;
|
||||
}
|
||||
Some(Command::Image(opts)) => {
|
||||
image::main(opts, config).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
+27
-3
@@ -159,6 +159,7 @@ impl EventCam {
|
||||
camera_config.channel_id,
|
||||
&camera_config.username,
|
||||
camera_config.password.as_ref(),
|
||||
camera_config.print_format,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
@@ -322,9 +323,32 @@ impl MessageHandler {
|
||||
"OK".to_string()
|
||||
}
|
||||
}
|
||||
Messages::Battery => {
|
||||
todo!()
|
||||
}
|
||||
Messages::Battery => match self.camera.battery_info().await {
|
||||
Err(_) => {
|
||||
error!("Failed to get battery status");
|
||||
"FAIL".to_string()
|
||||
}
|
||||
Ok(battery_info) => {
|
||||
let bytes_res = yaserde::ser::serialize_with_writer(
|
||||
&battery_info,
|
||||
vec![],
|
||||
&Default::default(),
|
||||
);
|
||||
match bytes_res {
|
||||
Ok(bytes) => match String::from_utf8(bytes) {
|
||||
Ok(str) => str,
|
||||
Err(_) => {
|
||||
error!("Failed to encode battery status");
|
||||
"FAIL".to_string()
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
error!("Failed to serialise battery status");
|
||||
"FAIL".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Messages::Ptz(direction) => {
|
||||
let (bc_direction, amount) = match direction {
|
||||
Direction::Up(amount) => (BcDirection::Up, amount),
|
||||
|
||||
@@ -218,8 +218,6 @@ impl GstOutputs {
|
||||
// - In the case of PausedSources::None we just pass through without encoding
|
||||
// - In the case of all other pause sources we need to recencode in order
|
||||
// to get smooth streams when the stream is paused/resumed
|
||||
// info!("self.video_format: {:?}", self.video_format);
|
||||
// info!("self.audio_format: {:?}", self.audio_format);
|
||||
let launch_vid_select = match self.when_paused {
|
||||
PausedSources::None => match self.video_format {
|
||||
Some(StreamFormat::H264) => "! rtph264pay name=pay0",
|
||||
|
||||
@@ -15,7 +15,10 @@ pub(crate) struct LoggedIn {}
|
||||
#[async_trait]
|
||||
impl CameraState for LoggedIn {
|
||||
async fn setup(&mut self, shared: &Shared) -> Result<(), anyhow::Error> {
|
||||
shared.camera.login().await?;
|
||||
shared
|
||||
.camera
|
||||
.login_with_maxenc(shared.max_encryption)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+10
-1
@@ -6,7 +6,7 @@ use log::*;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use neolink_core::bc_protocol::{MotionData, StreamKind as Stream};
|
||||
use neolink_core::bc_protocol::{MaxEncryption, MotionData, StreamKind as Stream};
|
||||
|
||||
use crate::config::{CameraConfig, UserConfig};
|
||||
use crate::rtsp::gst::RtspServer;
|
||||
@@ -67,6 +67,7 @@ impl RtspCamera {
|
||||
config.channel_id,
|
||||
&config.username,
|
||||
config.password.as_ref(),
|
||||
config.print_format,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
@@ -111,6 +112,12 @@ impl RtspCamera {
|
||||
None => ["anonymous".to_string()].iter().cloned().collect(),
|
||||
};
|
||||
|
||||
let max_encryption = match config.max_encryption.to_lowercase().as_str() {
|
||||
"none" => MaxEncryption::None,
|
||||
"bcencrypt" => MaxEncryption::BcEncrypt,
|
||||
"aes" => MaxEncryption::Aes,
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
let shared = Shared {
|
||||
camera: Arc::new(camera),
|
||||
addr: camera_addr,
|
||||
@@ -122,6 +129,8 @@ impl RtspCamera {
|
||||
streams,
|
||||
rtsp,
|
||||
permitted_users,
|
||||
max_encryption,
|
||||
strict: config.strict,
|
||||
};
|
||||
|
||||
let mut state: Connected = Default::default();
|
||||
|
||||
@@ -7,7 +7,7 @@ use async_trait::async_trait;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use neolink_core::bc_protocol::{BcCamera, StreamKind as Stream};
|
||||
use neolink_core::bc_protocol::{BcCamera, MaxEncryption, StreamKind as Stream};
|
||||
|
||||
use crate::config::PauseConfig;
|
||||
use crate::rtsp::gst::RtspServer;
|
||||
@@ -25,6 +25,8 @@ pub(crate) struct Shared {
|
||||
pub(super) rtsp: Arc<RtspServer>,
|
||||
pub(super) permitted_users: HashSet<String>,
|
||||
pub(super) pause: PauseConfig,
|
||||
pub(super) max_encryption: MaxEncryption,
|
||||
pub(super) strict: bool,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
|
||||
@@ -93,8 +93,11 @@ impl CameraState for Streaming {
|
||||
let output_thread = output.clone();
|
||||
|
||||
let stream_thead = *stream;
|
||||
let strict_thread = shared.strict;
|
||||
let handle = task::spawn(async move {
|
||||
let mut stream_data = arc_camera.start_video(stream_thead, 0).await?;
|
||||
let mut stream_data = arc_camera
|
||||
.start_video(stream_thead, 0, strict_thread)
|
||||
.await?;
|
||||
while arc_abort_handle.is_live() {
|
||||
let data = stream_data.get_data().await?;
|
||||
let mut locked_output = output_thread.lock().await;
|
||||
|
||||
+25
-6
@@ -4,7 +4,7 @@ use log::*;
|
||||
|
||||
use super::config::{CameraConfig, Config};
|
||||
use anyhow::{anyhow, Context, Error, Result};
|
||||
use neolink_core::bc_protocol::{BcCamera, DiscoveryMethods};
|
||||
use neolink_core::bc_protocol::{BcCamera, DiscoveryMethods, MaxEncryption, PrintFormat};
|
||||
use std::fmt::{Display, Error as FmtError, Formatter};
|
||||
|
||||
pub(crate) enum AddressOrUid {
|
||||
@@ -37,7 +37,9 @@ impl AddressOrUid {
|
||||
"none" => DiscoveryMethods::None,
|
||||
"local" => DiscoveryMethods::Local,
|
||||
"remote" => DiscoveryMethods::Remote,
|
||||
"map" => DiscoveryMethods::Map,
|
||||
"relay" => DiscoveryMethods::Relay,
|
||||
"debug" => DiscoveryMethods::Debug,
|
||||
n => {
|
||||
warn!("Unrecognised discovery method: {}. Using Local", n);
|
||||
DiscoveryMethods::Local
|
||||
@@ -54,14 +56,24 @@ impl AddressOrUid {
|
||||
channel_id: u8,
|
||||
username: T,
|
||||
passwd: Option<U>,
|
||||
aux_print_format: PrintFormat,
|
||||
) -> Result<BcCamera, Error> {
|
||||
match self {
|
||||
AddressOrUid::Address(host) => {
|
||||
Ok(BcCamera::new_with_addr(host, channel_id, username, passwd).await?)
|
||||
}
|
||||
AddressOrUid::Uid(host, method) => {
|
||||
Ok(BcCamera::new_with_uid(host, channel_id, username, passwd, *method).await?)
|
||||
Ok(
|
||||
BcCamera::new_with_addr(host, channel_id, username, passwd, aux_print_format)
|
||||
.await?,
|
||||
)
|
||||
}
|
||||
AddressOrUid::Uid(host, method) => Ok(BcCamera::new_with_uid(
|
||||
host,
|
||||
channel_id,
|
||||
username,
|
||||
passwd,
|
||||
*method,
|
||||
aux_print_format,
|
||||
)
|
||||
.await?),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,6 +100,7 @@ pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result<Bc
|
||||
camera_config.channel_id,
|
||||
&camera_config.username,
|
||||
camera_config.password.as_ref(),
|
||||
camera_config.print_format,
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
@@ -97,9 +110,15 @@ pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result<Bc
|
||||
)
|
||||
})?;
|
||||
|
||||
let max_encryption = match camera_config.max_encryption.to_lowercase().as_str() {
|
||||
"none" => MaxEncryption::None,
|
||||
"bcencrypt" => MaxEncryption::BcEncrypt,
|
||||
"aes" => MaxEncryption::Aes,
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera
|
||||
.login()
|
||||
.login_with_maxenc(max_encryption)
|
||||
.await
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
|
||||
|
||||
|
||||
Reference in new issue
Block a user