├── .cargo └── config.toml ├── .dockerignore ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ ├── build.yml │ ├── docker.yml │ └── style_checks.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── Dockerfile ├── LICENSE ├── README.md ├── build.rs ├── crates └── core │ ├── Cargo.toml │ └── src │ ├── bc │ ├── de.rs │ ├── mod.rs │ ├── model.rs │ ├── samples │ │ ├── EncryptionProtocol02_login.pcapng │ │ ├── battery_enc.bin │ │ ├── e1_firmwareupgrade.pcapng │ │ ├── model_sample_legacy_login.bin │ │ ├── model_sample_modern_login.bin │ │ ├── modern_login_failed.bin │ │ ├── modern_login_success.bin │ │ ├── modern_video_start1.bin │ │ ├── modern_video_start2.bin │ │ ├── xml_crypto_sample1.bin │ │ ├── xml_crypto_sample1_plaintext.bin │ │ ├── xml_externstream_b800.bin │ │ ├── xml_mainstream_b800.bin │ │ └── xml_substream_b800.bin │ ├── ser.rs │ ├── xml.rs │ └── xml_crypto.rs │ ├── bc_protocol.rs │ ├── bc_protocol │ ├── connection │ │ ├── bcconn.rs │ │ ├── bcsource.rs │ │ ├── bcsub.rs │ │ ├── binarysub.rs │ │ ├── filesub.rs │ │ ├── mod.rs │ │ ├── tcpconn.rs │ │ └── udpconn │ │ │ ├── aborthandle.rs │ │ │ ├── discover.rs │ │ │ ├── mod.rs │ │ │ └── transmit.rs │ ├── errors.rs │ ├── ledstate.rs │ ├── login.rs │ ├── logout.rs │ ├── motion.rs │ ├── ping.rs │ ├── pirstate.rs │ ├── reboot.rs │ ├── resolution.rs │ ├── stream.rs │ ├── talk.rs │ ├── time.rs │ └── version.rs │ ├── bcmedia │ ├── de.rs │ ├── mod.rs │ ├── model.rs │ ├── samples │ │ ├── adpcm_0.raw │ │ ├── argus2_iframe_0.raw │ │ ├── argus2_iframe_1.raw │ │ ├── argus2_iframe_2.raw │ │ ├── argus2_iframe_3.raw │ │ ├── argus2_iframe_4.raw │ │ ├── argus2_pframe_0.raw │ │ ├── argus2_pframe_1.raw │ │ ├── argus2_pframe_10.raw │ │ ├── argus2_pframe_11.raw │ │ ├── argus2_pframe_12.raw │ │ ├── argus2_pframe_13.raw │ │ ├── argus2_pframe_14.raw │ │ ├── argus2_pframe_15.raw │ │ ├── argus2_pframe_16.raw │ │ ├── argus2_pframe_17.raw │ │ ├── argus2_pframe_2.raw │ │ ├── argus2_pframe_3.raw │ │ ├── argus2_pframe_4.raw │ │ ├── argus2_pframe_5.raw │ │ ├── argus2_pframe_6.raw │ │ ├── argus2_pframe_7.raw │ │ ├── argus2_pframe_8.raw │ │ ├── argus2_pframe_9.raw │ │ ├── iframe_0.raw │ │ ├── iframe_1.raw │ │ ├── iframe_2.raw │ │ ├── iframe_3.raw │ │ ├── iframe_4.raw │ │ ├── info_v1.raw │ │ ├── pframe_0.raw │ │ ├── pframe_1.raw │ │ ├── video_stream_swan_00.raw │ │ ├── video_stream_swan_01.raw │ │ ├── video_stream_swan_02.raw │ │ ├── video_stream_swan_03.raw │ │ ├── video_stream_swan_04.raw │ │ ├── video_stream_swan_05.raw │ │ ├── video_stream_swan_06.raw │ │ ├── video_stream_swan_07.raw │ │ ├── video_stream_swan_08.raw │ │ └── video_stream_swan_09.raw │ └── ser.rs │ ├── bcudp │ ├── crc.rs │ ├── de.rs │ ├── mod.rs │ ├── model.rs │ ├── samples │ │ ├── udp_ack.bin │ │ ├── udp_data.bin │ │ ├── udp_multi_0.bin │ │ ├── udp_multi_1.bin │ │ ├── udp_multi_2.bin │ │ ├── udp_multi_3.bin │ │ ├── udp_multi_4.bin │ │ ├── udp_multi_5.bin │ │ ├── udp_multi_6.bin │ │ ├── udp_multi_7.bin │ │ ├── udp_multi_8.bin │ │ ├── udp_multi_9.bin │ │ ├── udp_negotiate_camcfm.bin │ │ ├── udp_negotiate_camt.bin │ │ ├── udp_negotiate_clientt.bin │ │ ├── udp_negotiate_disc.bin │ │ ├── xml_crypto_sample1.bin │ │ └── xml_crypto_sample1_plaintext.bin │ ├── ser.rs │ ├── xml.rs │ └── xml_crypto.rs │ └── lib.rs ├── dissector ├── baichuan.lua ├── mediapacket.md ├── messages.md ├── protocol.md └── udp.md ├── docker └── entrypoint.sh ├── docs ├── Setting Up Neolink For Use With Blue Iris.md ├── screenshots │ ├── login_messages.JPG │ ├── new_camera.JPG │ ├── new_camera_config.JPG │ ├── taskfinishwindow.JPG │ └── tasksettingstab.JPG ├── unix_service.md └── unix_setup.md ├── sample_config.toml └── src ├── cmdline.rs ├── config.rs ├── main.rs ├── pir ├── cmdline.rs └── mod.rs ├── reboot ├── cmdline.rs └── mod.rs ├── rtsp ├── adpcm.rs ├── cmdline.rs ├── gst.rs └── mod.rs ├── statusled ├── cmdline.rs └── mod.rs ├── talk ├── cmdline.rs ├── gst.rs └── mod.rs └── utils.rs /.cargo/config.toml: -------------------------------------------------------------------------------- 1 | [target.x86_64-pc-windows-msvc] 2 | rustflags = ["-C", "target-feature=+crt-static"] 3 | 4 | # TODO not good as a default 5 | [target.armv7-unknown-linux-gnueabihf] 6 | linker = "arm-linux-gnueabihf-gcc" 7 | 8 | [target.aarch64-unknown-linux-gnu] 9 | linker = "aarch64-linux-gnu-gcc" 10 | 11 | [target.i686-unknown-linux-gnu] 12 | linker = "i686-linux-gnu-gcc" 13 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | target/ 2 | Dockerfile 3 | .dockerignore 4 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | Cargo.lock binary 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Something isn't working 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior. Example: 15 | 1. Create this configuration file: 16 | 2. Launch Neolink: 17 | 3. Click on ... in Blue Iris 18 | 19 | **Expected behavior** 20 | A clear and concise description of what you expected to happen. 21 | 22 | **Versions** 23 | NVR software: 24 | Neolink software: 25 | Reolink camera model and firmware: 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex: "I'm always frustrated when [...]" 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | pull_request: 6 | schedule: 7 | - cron: "* * * */2 *" 8 | workflow_dispatch: 9 | 10 | jobs: 11 | native: 12 | name: build 13 | runs-on: ${{ matrix.os }} 14 | strategy: 15 | matrix: 16 | os: [ubuntu-20.04, windows-2022, macos-12] 17 | steps: 18 | - uses: actions/checkout@v2 19 | name: Checkout onto ${{ runner.os }} 20 | - if: runner.os == 'Linux' 21 | name: apt install gstreamer 22 | run: | 23 | sudo apt update 24 | sudo apt install -y libgstrtspserver-1.0-dev libgstreamer1.0-dev libgtk2.0-dev 25 | - if: runner.os == 'Windows' 26 | name: Install Gstreamer 27 | run: | 28 | # Gstreamer 29 | choco install -y --no-progress gstreamer --version=1.20.0 30 | choco install -y --no-progress gstreamer-devel --version=1.20.0 31 | $env:GSTREAMER_1_0_ROOT_MSVC_X86_64=$env:SYSTEMDRIVE + '\gstreamer\1.0\msvc_x86_64\' 32 | # Github runners work on both C or D drive and figuring out which was used is difficult 33 | if (-not (Test-Path -Path "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64" -PathType Container)) { 34 | $env:GSTREAMER_1_0_ROOT_MSVC_X86_64='D:\\gstreamer\1.0\msvc_x86_64\' 35 | } 36 | echo "GSTREAMER_1_0_ROOT_MSVC_X86_64=$env:GSTREAMER_1_0_ROOT_MSVC_X86_64" 37 | 38 | # Set github vars 39 | Add-Content -Path $env:GITHUB_ENV -Value "GSTREAMER_1_0_ROOT_MSVC_X86_64=$env:GSTREAMER_1_0_ROOT_MSVC_X86_64" 40 | Add-Content -Path $env:GITHUB_PATH -Value "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64\bin" 41 | Add-Content -Path $env:GITHUB_PATH -Value "%GSTREAMER_1_0_ROOT_MSVC_X86_64%\bin" 42 | 43 | # One last check on directories 44 | dir "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64" 45 | - if: runner.os == 'macOS' 46 | name: Install Gstreamer on macOS 47 | run: | 48 | curl -L 'https://gstreamer.freedesktop.org/data/pkg/osx/1.24.1/gstreamer-1.0-devel-1.24.1-universal.pkg' -o "$(pwd)/gstreamer-devel.pkg" 49 | sudo installer -verbose -pkg "$(pwd)/gstreamer-devel.pkg" -target / 50 | PKG_CONFIG_PATH="/Library/Frameworks/GStreamer.framework/Versions/1.0/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}" 51 | echo "PKG_CONFIG_PATH=${PKG_CONFIG_PATH}" >> "${GITHUB_ENV}" 52 | - name: Cache cargo registry 53 | uses: actions/cache@v1 54 | with: 55 | path: ~/.cargo/registry 56 | key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }} 57 | - name: Cache cargo index 58 | uses: actions/cache@v1 59 | with: 60 | path: ~/.cargo/git 61 | key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }} 62 | - name: Cache cargo build 63 | if: runner.os != 'macOS' # Random missing crates on macOS, unclear why 64 | uses: actions/cache@v1 65 | with: 66 | path: target 67 | key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('**/Cargo.lock') }} 68 | - uses: actions-rs/cargo@v1 69 | with: 70 | command: build 71 | args: --release --all-features 72 | - uses: actions/upload-artifact@v2 73 | with: 74 | name: release-${{ matrix.os }} 75 | path: "target/release/neolink*" 76 | cross: 77 | name: cross 78 | runs-on: ubuntu-latest 79 | container: "node:current-buster-slim" 80 | strategy: 81 | fail-fast: false 82 | matrix: 83 | # Everyone has a slightly different screwball naming scheme; 84 | # Rust uses the target triple, GCC generally targets a family 85 | # with a specific prefix, and dpkg's arch does its own thing 86 | include: 87 | - arch: armhf 88 | target: armv7-unknown-linux-gnueabihf 89 | gcc: arm-linux-gnueabihf 90 | pkgconfig: arm-linux-gnueabihf 91 | - arch: arm64 92 | target: aarch64-unknown-linux-gnu 93 | gcc: aarch64-linux-gnu 94 | pkgconfig: aarch64-linux-gnu 95 | - arch: i386 96 | target: i686-unknown-linux-gnu 97 | gcc: i686-linux-gnu 98 | # on i686, the pkgconfig path doesn't match the prefix! 99 | pkgconfig: i386-linux-gnu 100 | steps: 101 | - uses: actions/checkout@v2 102 | - name: Install basic tools 103 | run: | 104 | apt-get update 105 | apt-get install --assume-yes --no-install-recommends curl ca-certificates 106 | - name: Install ${{ matrix.arch }} cross compiler and gstreamer 107 | id: setup 108 | run: | 109 | dpkg --add-architecture ${{ matrix.arch }} 110 | apt-get update 111 | apt-get install --assume-yes --no-install-recommends \ 112 | build-essential \ 113 | gcc-${{ matrix.gcc }} \ 114 | libgstrtspserver-1.0-dev:${{ matrix.arch }} \ 115 | libgstreamer1.0-dev:${{ matrix.arch }} \ 116 | libgtk2.0-dev:${{ matrix.arch }} \ 117 | libglib2.0-dev:${{ matrix.arch }} 118 | - name: Install ${{ matrix.arch }} Rust toolchain 119 | uses: actions-rs/toolchain@v1 120 | with: 121 | toolchain: stable 122 | override: true 123 | target: ${{ matrix.target }} 124 | profile: minimal 125 | - name: Build 126 | uses: actions-rs/cargo@v1 127 | with: 128 | command: build 129 | args: --release --all-features --target=${{ matrix.target }} 130 | env: 131 | # Retarget pkg-config as described in https://www.freedesktop.org/wiki/Software/pkg-config/CrossCompileProposal/ 132 | PKG_CONFIG_ALLOW_CROSS: 1 133 | PKG_CONFIG_LIBDIR: /usr/lib/${{ matrix.pkgconfig }}/pkgconfig 134 | - uses: actions/upload-artifact@v2 135 | with: 136 | name: release-${{ matrix.arch }}-buster 137 | path: "target/${{ matrix.target }}/release/neolink*" 138 | -------------------------------------------------------------------------------- /.github/workflows/docker.yml: -------------------------------------------------------------------------------- 1 | # A single-shot build-n-pack on Alpine Linux 2 | name: Publish Docker image 3 | on: [push] 4 | 5 | jobs: 6 | push_to_registry: 7 | name: Build Docker image 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Check token is set 11 | id: vars 12 | shell: bash 13 | run: | 14 | unset HAS_SECRET 15 | if [ -n $SECRET ]; then HAS_SECRET='true' ; fi 16 | echo ::set-output name=HAS_SECRET_TOKEN::${HAS_SECRET} 17 | env: 18 | SECRET: "${{ secrets.DOCKER_TOKEN }}" 19 | - name: Check out the repo 20 | uses: actions/checkout@v2 21 | if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }} 22 | - name: Convert username to lower case for docker 23 | id: string_user 24 | uses: ASzc/change-string-case-action@v1 25 | with: 26 | string: ${{ github.repository_owner }} 27 | - name: Convert repo to lower case for docker 28 | id: string_repo 29 | uses: ASzc/change-string-case-action@v1 30 | with: 31 | string: ${{ github.repository }} 32 | - name: Push to Docker Hub 33 | uses: docker/build-push-action@v1 34 | if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }} 35 | with: 36 | username: ${{ steps.string_user.outputs.lowercase }} 37 | password: ${{ secrets.DOCKER_TOKEN }} 38 | registry: docker.io 39 | repository: ${{ steps.string_repo.outputs.lowercase }} 40 | tag_with_ref: true 41 | -------------------------------------------------------------------------------- /.github/workflows/style_checks.yml: -------------------------------------------------------------------------------- 1 | name: Style 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | check_clippy: 7 | name: Clippy 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v1 11 | - name: apt install gstreamer 12 | run: | 13 | sudo apt-get update 14 | sudo apt-get install -y aptitude 15 | sudo aptitude install -y libgstrtspserver-1.0-dev libgstreamer1.0-dev libgtk2.0-dev 16 | - uses: actions-rs/toolchain@v1 17 | with: 18 | toolchain: nightly 19 | components: clippy 20 | override: true 21 | - name: Run clippy action to produce annotations 22 | uses: actions-rs/clippy-check@v1 23 | if: steps.check_permissions.outputs.has-permission 24 | with: 25 | toolchain: nightly 26 | token: ${{ secrets.GITHUB_TOKEN }} 27 | args: --workspace --all-targets --all-features 28 | - name: Run clippy manually without annotations 29 | if: ${{ !steps.check_permissions.outputs.has-permission }} 30 | run: cargo +nightly clippy --workspace --all-targets --all-features 31 | 32 | check_fmt: 33 | name: Rust-fmt 34 | runs-on: ubuntu-latest 35 | steps: 36 | - uses: actions/checkout@v1 37 | - uses: actions-rs/toolchain@v1 38 | with: 39 | toolchain: nightly 40 | components: rustfmt 41 | override: true 42 | - name: rustfmt 43 | run: | 44 | cargo +nightly fmt --all -- --check 45 | 46 | check_lua: 47 | name: Luacheck 48 | runs-on: ubuntu-latest 49 | steps: 50 | - uses: actions/checkout@v1 51 | - name: Run luacheck 52 | uses: nebularg/actions-luacheck@v1 53 | with: 54 | files: "dissector/baichuan.lua" 55 | args: --globals Dissector Proto ProtoField base ByteArray DESEGMENT_ONE_MORE_SEGMENT DissectorTable 56 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/rust 3 | # Edit at https://www.gitignore.io/?templates=rust 4 | 5 | ### Rust ### 6 | # Generated by Cargo 7 | # will have compiled files and executables 8 | /target/ 9 | 10 | # These are backup files generated by rustfmt 11 | **/*.rs.bk 12 | 13 | # End of https://www.gitignore.io/api/rust 14 | 15 | # Committing IntelliJ project files is a violation of intergalactic law 16 | .idea/ 17 | 18 | .vscode/ 19 | .pre-commit-config.yaml -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "neolink" 3 | description = "A standards-compliant bridge to Reolink IP cameras" 4 | version = "0.4.0" 5 | authors = ["George Hilliard "] 6 | edition = "2018" 7 | 8 | [workspace] 9 | members = [ 10 | "crates/*", 11 | ] 12 | 13 | [dependencies] 14 | neolink_core = { path = "crates/core", version = "0.4.0" } 15 | aes = "0.6" 16 | cfb-mode = "0.6" 17 | cookie-factory = "0.3" 18 | crossbeam = "0.8" 19 | err-derive = "0.2" 20 | env_logger = "*" 21 | gstreamer = "0.17" 22 | gstreamer-app = "0.17" 23 | gstreamer-rtsp = "0.17" 24 | gstreamer-rtsp-server = { version = "0.17", features = ["v1_12", "v1_14"]} 25 | lazy_static = "1.4" 26 | log = { version = "0.4" } 27 | itertools = "0.9" 28 | md5 = "0.7" 29 | nom = "6.1.2" 30 | regex = "1" 31 | serde = { version = "1.0", features = ["derive"] } 32 | socket2 = "0.3" 33 | structopt = "0.3" 34 | time = "0.2" 35 | toml = "0.5" 36 | yaserde = "0.3.16" 37 | yaserde_derive = "0.3.16" 38 | xml-rs = "0.8" 39 | validator = "0.10" 40 | validator_derive = "0.10" 41 | byte-slice-cast = "1.0.0" 42 | anyhow = "1.0.42" 43 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Neolink Docker image build scripts 2 | # Copyright (c) 2020 George Hilliard 3 | # SPDX-License-Identifier: AGPL-3.0-only 4 | 5 | FROM docker.io/rust:1-alpine AS build 6 | MAINTAINER thirtythreeforty@gmail.com 7 | 8 | # Until Alpine merges gst-rtsp-server into a release, pull all Gstreamer packages 9 | # from the "testing" release 10 | RUN apk add --no-cache \ 11 | -X http://dl-cdn.alpinelinux.org/alpine/edge/main \ 12 | -X http://dl-cdn.alpinelinux.org/alpine/edge/testing \ 13 | gst-rtsp-server-dev 14 | RUN apk add --no-cache musl-dev gcc 15 | 16 | # Use static linking to work around https://github.com/rust-lang/rust/pull/58575 17 | ENV RUSTFLAGS='-C target-feature=-crt-static' 18 | 19 | WORKDIR /usr/local/src/neolink 20 | 21 | # Build the main program 22 | COPY . /usr/local/src/neolink 23 | RUN cargo build --release 24 | 25 | # Create the release container. Match the base OS used to build 26 | FROM docker.io/alpine:latest 27 | 28 | RUN apk add --no-cache \ 29 | -X http://dl-cdn.alpinelinux.org/alpine/edge/main \ 30 | -X http://dl-cdn.alpinelinux.org/alpine/edge/testing \ 31 | libgcc \ 32 | tzdata \ 33 | gstreamer \ 34 | gst-plugins-base \ 35 | gst-plugins-good \ 36 | gst-plugins-bad \ 37 | gst-plugins-ugly \ 38 | gst-rtsp-server 39 | 40 | COPY --from=build \ 41 | /usr/local/src/neolink/target/release/neolink \ 42 | /usr/local/bin/neolink 43 | COPY docker/entrypoint.sh /entrypoint.sh 44 | 45 | CMD ["/usr/local/bin/neolink", "rtsp", "--config", "/etc/neolink.toml"] 46 | ENTRYPOINT ["/entrypoint.sh"] 47 | EXPOSE 8554 48 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::process::Command; 3 | 4 | fn main() { 5 | build_ver(); 6 | platform_cfg(); 7 | } 8 | 9 | fn build_ver() { 10 | let cargo_ver = env::var("CARGO_PKG_VERSION").unwrap(); 11 | let version = git_ver().unwrap_or(format!("{} (unknown commit)", cargo_ver)); 12 | 13 | println!("cargo:rustc-env=NEOLINK_VERSION={}", version); 14 | println!( 15 | "cargo:rustc-env=NEOLINK_PROFILE={}", 16 | env::var("PROFILE").unwrap() 17 | ); 18 | } 19 | 20 | fn git_ver() -> Option { 21 | github_ver().or_else(git_cmd_ver) 22 | } 23 | 24 | fn git_cmd_ver() -> Option { 25 | let mut git_cmd = Command::new("git"); 26 | git_cmd.args(&["describe", "--tags"]); 27 | 28 | if let Some(true) = git_cmd.status().ok().map(|exit| exit.success()) { 29 | println!("cargo:rerun-if-changed=.git/HEAD"); 30 | git_cmd 31 | .output() 32 | .ok() 33 | .map(|o| String::from_utf8(o.stdout).unwrap()) 34 | } else { 35 | None 36 | } 37 | } 38 | 39 | fn github_ver() -> Option { 40 | if let Ok(sha1) = env::var("GITHUB_SHA") { 41 | println!("cargo:rerun-if-env-changed=GITHUB_SHA"); 42 | Some(sha1) 43 | } else { 44 | None 45 | } 46 | } 47 | 48 | #[cfg(windows)] 49 | fn platform_cfg() { 50 | let gstreamer_dir = env::var_os("GSTREAMER_1_0_ROOT_X86_64") 51 | .and_then(|x| x.into_string().ok()) 52 | .unwrap_or_else(|| { 53 | env::var_os("GSTREAMER_1_0_ROOT_MSVC_X86_64") 54 | .and_then(|x| x.into_string().ok()) 55 | .unwrap_or_else(|| r#"C:\gstreamer\1.0\x86_64\"#.to_string()) 56 | }); 57 | 58 | println!(r"cargo:rustc-link-search=native={}\lib", gstreamer_dir); 59 | } 60 | 61 | #[cfg(not(windows))] 62 | fn platform_cfg() {} 63 | -------------------------------------------------------------------------------- /crates/core/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "neolink_core" 3 | description = "Core services and structure for Reolink IP cameras" 4 | version = "0.4.0" 5 | authors = ["George Hilliard "] 6 | edition = "2018" 7 | 8 | [dependencies] 9 | aes = "0.6" 10 | cfb-mode = "0.6" 11 | cookie-factory = "0.3" 12 | crc32fast = "1.2.1" 13 | crossbeam-channel = "0.5.1" 14 | err-derive = "0.2" 15 | get_if_addrs = "0.5.3" 16 | lazy_static = "1.4" 17 | local-ip-address = "0.4.4" 18 | log = { version = "0.4" } 19 | md5 = "0.7" 20 | nom = { version = "6.1.2", features = ["alloc"] } 21 | rand = "0.8.4" 22 | regex = "1.5.4" 23 | socket2 = "0.3" 24 | time = "0.2" 25 | xml-rs = "0.8" 26 | yaserde = "0.3.16" 27 | yaserde_derive = "0.3.16" 28 | 29 | [dev-dependencies] 30 | assert_matches = "1.5.0" 31 | env_logger = "*" 32 | indoc = "0.3" 33 | -------------------------------------------------------------------------------- /crates/core/src/bc/mod.rs: -------------------------------------------------------------------------------- 1 | //! The Baichuan message format is a 20 byte header, the contents of which vary between legacy and 2 | //! modern messages: 3 | //! 4 | //! 5 | //! 6 | //! This header is followed by the message body. In legacy messages, the bodies are 7 | //! message-specific binary formats. Currently, we only attempt to interpret the legacy login 8 | //! message, as it is all that is needed to upgrade to the modern XML-based messages. Modern 9 | //! messages are either "encrypted" XML (the encryption is a simple XOR routine or AES) 10 | //! or binary data. 11 | //! 12 | //! --- 13 | //! 14 | //! # Payloads 15 | //! Messages contain one-two payloads seperated by the payload_offset in the header 16 | //! 17 | //! ## Extension Payload 18 | //! The first payload prior to the payload_offset is the extension xml 19 | //! 20 | //! This contains meta data on the following payload such as channel_id or content type 21 | //! (xml or binary) 22 | //! 23 | //! ## Payload 24 | //! The second payload which is the primary payload coming after the payload offset 25 | //! depends on the MsgID. 26 | //! 27 | //! It is usually XML except in the case of video and talk MsgIDs 28 | //! which are binary data in the bc media packet format 29 | //! 30 | 31 | /// Contains the structure of the messages such as headers and payloads 32 | pub mod model; 33 | 34 | /// Contains code related to the deserialisation of the bc packets 35 | pub mod de; 36 | /// `Contains code related to the serialisation of the bc packets 37 | pub mod ser; 38 | /// Contains the structs for the know xmls of payloads and extension 39 | pub mod xml; 40 | 41 | mod xml_crypto; 42 | -------------------------------------------------------------------------------- /crates/core/src/bc/samples/EncryptionProtocol02_login.pcapng: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/EncryptionProtocol02_login.pcapng -------------------------------------------------------------------------------- /crates/core/src/bc/samples/battery_enc.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/battery_enc.bin -------------------------------------------------------------------------------- /crates/core/src/bc/samples/e1_firmwareupgrade.pcapng: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/e1_firmwareupgrade.pcapng -------------------------------------------------------------------------------- /crates/core/src/bc/samples/model_sample_legacy_login.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/model_sample_legacy_login.bin -------------------------------------------------------------------------------- /crates/core/src/bc/samples/model_sample_modern_login.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/model_sample_modern_login.bin -------------------------------------------------------------------------------- /crates/core/src/bc/samples/modern_login_failed.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/modern_login_failed.bin -------------------------------------------------------------------------------- /crates/core/src/bc/samples/modern_login_success.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/modern_login_success.bin -------------------------------------------------------------------------------- /crates/core/src/bc/samples/modern_video_start1.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/modern_video_start1.bin -------------------------------------------------------------------------------- /crates/core/src/bc/samples/modern_video_start2.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/modern_video_start2.bin -------------------------------------------------------------------------------- /crates/core/src/bc/samples/xml_crypto_sample1.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/xml_crypto_sample1.bin -------------------------------------------------------------------------------- /crates/core/src/bc/samples/xml_crypto_sample1_plaintext.bin: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | md5 5 | 9E6D1FCB9E69846D 6 | 7 | 8 | -------------------------------------------------------------------------------- /crates/core/src/bc/samples/xml_externstream_b800.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/xml_externstream_b800.bin -------------------------------------------------------------------------------- /crates/core/src/bc/samples/xml_mainstream_b800.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/xml_mainstream_b800.bin -------------------------------------------------------------------------------- /crates/core/src/bc/samples/xml_substream_b800.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bc/samples/xml_substream_b800.bin -------------------------------------------------------------------------------- /crates/core/src/bc/ser.rs: -------------------------------------------------------------------------------- 1 | use super::model::*; 2 | use super::xml::BcPayloads; 3 | use super::xml_crypto; 4 | use cookie_factory::bytes::*; 5 | use cookie_factory::sequence::tuple; 6 | use cookie_factory::{combinator::*, gen}; 7 | use cookie_factory::{GenError, SerializeFn, WriteContext}; 8 | use log::error; 9 | use std::io::Write; 10 | 11 | /// The error types used during serialisation 12 | pub type Error = GenError; 13 | 14 | impl Bc { 15 | pub(crate) fn serialize( 16 | &self, 17 | buf: W, 18 | encryption_protocol: &EncryptionProtocol, 19 | ) -> Result { 20 | // Ideally this would be a combinator, but that would be hairy because we have to 21 | // serialize the XML to have the metadata to build the header 22 | let body_buf; 23 | let payload_offset; 24 | 25 | match &self.body { 26 | BcBody::ModernMsg(ref modern) => { 27 | // First serialize ext 28 | let (temp_buf, ext_len) = gen( 29 | opt_ref(&modern.extension, |ext| { 30 | bc_ext(self.meta.channel_id as u32, ext, encryption_protocol) 31 | }), 32 | vec![], 33 | )?; 34 | 35 | // Now get the offset of the payload 36 | payload_offset = if has_payload_offset(self.meta.class) { 37 | // If we're required to put binary length, put 0 if we have no binary 38 | Some(if modern.extension.is_some() { 39 | ext_len as u32 40 | } else { 41 | 0 42 | }) 43 | } else { 44 | None 45 | }; 46 | 47 | // Now get the payload part of the body and add to ext_buf 48 | let (temp_buf, _) = gen( 49 | opt_ref(&modern.payload, |payload_offset| { 50 | bc_payload( 51 | self.meta.channel_id as u32, 52 | payload_offset, 53 | encryption_protocol, 54 | ) 55 | }), 56 | temp_buf, 57 | )?; 58 | body_buf = temp_buf; 59 | } 60 | 61 | BcBody::LegacyMsg(ref legacy) => { 62 | let (buf, _) = gen(bc_legacy(legacy), vec![]).map_err(|e| { 63 | error!("Send error: {}", e); 64 | e 65 | })?; 66 | body_buf = buf; 67 | payload_offset = None; 68 | } 69 | }; 70 | 71 | // Now have enough info to create the header 72 | let header = BcHeader::from_meta(&self.meta, body_buf.len() as u32, payload_offset); 73 | 74 | let (buf, _n) = gen(tuple((bc_header(&header), slice(body_buf))), buf)?; 75 | 76 | Ok(buf) 77 | } 78 | } 79 | 80 | fn bc_ext( 81 | enc_offset: u32, 82 | xml: &Extension, 83 | encryption_protocol: &EncryptionProtocol, 84 | ) -> impl SerializeFn { 85 | let xml_bytes = xml.serialize(vec![]).unwrap(); 86 | let enc_bytes = xml_crypto::encrypt(enc_offset, &xml_bytes, encryption_protocol); 87 | slice(enc_bytes) 88 | } 89 | 90 | fn bc_payload( 91 | enc_offset: u32, 92 | payload: &BcPayloads, 93 | encryption_protocol: &EncryptionProtocol, 94 | ) -> impl SerializeFn { 95 | let payload_bytes = match payload { 96 | BcPayloads::BcXml(x) => { 97 | let xml_bytes = x.serialize(vec![]).unwrap(); 98 | xml_crypto::encrypt(enc_offset, &xml_bytes, encryption_protocol) 99 | } 100 | BcPayloads::Binary(x) => x.to_owned(), 101 | }; 102 | slice(payload_bytes) 103 | } 104 | 105 | fn bc_header(header: &BcHeader) -> impl SerializeFn { 106 | tuple(( 107 | le_u32(MAGIC_HEADER), 108 | le_u32(header.msg_id), 109 | le_u32(header.body_len), 110 | le_u8(header.channel_id), 111 | le_u8(header.stream_type), 112 | le_u16(header.msg_num), 113 | le_u16(header.response_code), 114 | le_u16(header.class), 115 | opt(header.payload_offset, le_u32), 116 | )) 117 | } 118 | 119 | fn bc_legacy(legacy: &'_ LegacyMsg) -> impl SerializeFn + '_ { 120 | move |out: WriteContext| { 121 | use LegacyMsg::*; 122 | match legacy { 123 | LoginMsg { username, password } => { 124 | if username.len() != 32 || password.len() != 32 { 125 | // Error handling could be improved here... 126 | return Err(GenError::CustomError(0)); 127 | } 128 | tuple(( 129 | slice(username), 130 | slice(password), 131 | // Login messages are 1836 bytes total, username/password 132 | // take up 32 chars each, 1772 zeros follow 133 | slice(&[0u8; 1772][..]), 134 | ))(out) 135 | } 136 | UnknownMsg => { 137 | panic!("Cannot serialize an unknown message!"); 138 | } 139 | } 140 | } 141 | } 142 | 143 | /// Applies the supplied serializer with the Option's interior data if present 144 | fn opt(opt: Option, ser: impl Fn(T) -> F) -> impl SerializeFn 145 | where 146 | F: SerializeFn, 147 | T: Copy, 148 | W: Write, 149 | { 150 | move |buf: WriteContext| { 151 | if let Some(val) = opt { 152 | ser(val)(buf) 153 | } else { 154 | do_nothing()(buf) 155 | } 156 | } 157 | } 158 | 159 | fn opt_ref<'a, W, T, F, S>(opt: &'a Option, ser: S) -> impl SerializeFn + 'a 160 | where 161 | F: SerializeFn, 162 | W: Write, 163 | S: Fn(&'a T) -> F + 'a, 164 | { 165 | move |buf: WriteContext| { 166 | if let Some(ref val) = opt { 167 | ser(&*val)(buf) 168 | } else { 169 | do_nothing()(buf) 170 | } 171 | } 172 | } 173 | 174 | /// A serializer combinator that does nothing with its input 175 | fn do_nothing() -> impl SerializeFn { 176 | move |out: WriteContext| Ok(out) 177 | } 178 | 179 | #[test] 180 | fn test_legacy_login_roundtrip() { 181 | let encryption_protocol = 182 | std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); 183 | let mut context = BcContext::new(encryption_protocol); 184 | 185 | // I don't want to make up a sample message; just load it 186 | let sample = include_bytes!("samples/model_sample_legacy_login.bin"); 187 | let msg = Bc::deserialize::<&[u8]>(&mut context, &sample[..]).unwrap(); 188 | 189 | let ser_buf = msg 190 | .serialize(vec![], &EncryptionProtocol::BCEncrypt) 191 | .unwrap(); 192 | let msg2 = Bc::deserialize::<&[u8]>(&mut context, ser_buf.as_ref()).unwrap(); 193 | assert_eq!(msg, msg2); 194 | assert_eq!(&sample[..], ser_buf.as_slice()); 195 | } 196 | 197 | #[test] 198 | fn test_modern_login_roundtrip() { 199 | let encryption_protocol = 200 | std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); 201 | let mut context = BcContext::new(encryption_protocol); 202 | 203 | // I don't want to make up a sample message; just load it 204 | let sample = include_bytes!("samples/model_sample_modern_login.bin"); 205 | 206 | let msg = Bc::deserialize::<&[u8]>(&mut context, &sample[..]).unwrap(); 207 | 208 | let ser_buf = msg 209 | .serialize(vec![], &EncryptionProtocol::BCEncrypt) 210 | .unwrap(); 211 | let msg2 = Bc::deserialize::<&[u8]>(&mut context, ser_buf.as_ref()).unwrap(); 212 | assert_eq!(msg, msg2); 213 | } 214 | -------------------------------------------------------------------------------- /crates/core/src/bc/xml_crypto.rs: -------------------------------------------------------------------------------- 1 | use super::model::EncryptionProtocol; 2 | use aes::Aes128; 3 | use cfb_mode::cipher::{NewStreamCipher, StreamCipher}; 4 | use cfb_mode::Cfb; 5 | 6 | const XML_KEY: [u8; 8] = [0x1F, 0x2D, 0x3C, 0x4B, 0x5A, 0x69, 0x78, 0xFF]; 7 | const IV: &[u8] = b"0123456789abcdef"; 8 | 9 | pub fn decrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol) -> Vec { 10 | match encryption_protocol { 11 | EncryptionProtocol::Unencrypted => buf.to_vec(), 12 | EncryptionProtocol::BCEncrypt => { 13 | let key_iter = XML_KEY.iter().cycle().skip(offset as usize % 8); 14 | key_iter 15 | .zip(buf) 16 | .map(|(key, i)| *i ^ key ^ (offset as u8)) 17 | .collect() 18 | } 19 | EncryptionProtocol::Aes(key) => { 20 | // AES decryption 21 | if let Some(aeskey) = key { 22 | let mut decrypted = buf.to_vec(); 23 | Cfb::::new(aeskey.into(), IV.into()).decrypt(&mut decrypted); 24 | decrypted 25 | } else { 26 | // Not yet ready to decrypt (still in login phase) 27 | // Use BCEncrypt 28 | decrypt(offset, buf, &EncryptionProtocol::BCEncrypt) 29 | } 30 | } 31 | } 32 | } 33 | 34 | pub fn encrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol) -> Vec { 35 | match encryption_protocol { 36 | EncryptionProtocol::Unencrypted => { 37 | // Encrypt is the same as decrypt 38 | decrypt(offset, buf, encryption_protocol) 39 | } 40 | EncryptionProtocol::BCEncrypt => { 41 | // Encrypt is the same as decrypt 42 | decrypt(offset, buf, encryption_protocol) 43 | } 44 | EncryptionProtocol::Aes(key) => { 45 | // AES encryption 46 | if let Some(aeskey) = key { 47 | let mut encrypted = buf.to_vec(); 48 | Cfb::::new(aeskey.into(), IV.into()).encrypt(&mut encrypted); 49 | encrypted 50 | } else { 51 | // Not yet ready to decrypt (still in login phase) 52 | // Use BCEncrypt 53 | encrypt(offset, buf, &EncryptionProtocol::BCEncrypt) 54 | } 55 | } 56 | } 57 | } 58 | 59 | #[test] 60 | fn test_xml_crypto() { 61 | let sample = include_bytes!("samples/xml_crypto_sample1.bin"); 62 | let should_be = include_bytes!("samples/xml_crypto_sample1_plaintext.bin"); 63 | 64 | let decrypted = decrypt(0, &sample[..], &EncryptionProtocol::BCEncrypt); 65 | assert_eq!(decrypted, &should_be[..]); 66 | } 67 | 68 | #[test] 69 | fn test_xml_crypto_roundtrip() { 70 | let zeros: [u8; 256] = [0; 256]; 71 | 72 | let decrypted = encrypt(0, &zeros[..], &EncryptionProtocol::BCEncrypt); 73 | let encrypted = decrypt(0, &decrypted[..], &EncryptionProtocol::BCEncrypt); 74 | assert_eq!(encrypted, &zeros[..]); 75 | } 76 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/connection/bcconn.rs: -------------------------------------------------------------------------------- 1 | use super::{BcSource, BcSubscription, Error, Result, TcpSource}; 2 | use crate::bc; 3 | use crate::bc::model::*; 4 | use log::*; 5 | use socket2::{Domain, Socket, Type}; 6 | use std::collections::btree_map::Entry; 7 | use std::collections::BTreeMap; 8 | use std::error::Error as StdErr; // Just need the traits 9 | use std::io::{Error as IoError, Read, Write}; 10 | use std::net::{SocketAddr, TcpStream}; 11 | use std::sync::mpsc::{channel, Receiver, Sender}; 12 | use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc, Mutex}; 13 | use std::thread::JoinHandle; 14 | use std::time::{Duration, Instant}; 15 | 16 | /// A shareable connection to a camera. Handles serialization of messages. To send/receive, call 17 | /// .[subscribe()] with a message ID. You can use the BcSubscription to send or receive only 18 | /// messages with that ID; each incoming message is routed to its appropriate subscriber. 19 | /// 20 | /// There can be only one subscriber per kind of message at a time. 21 | pub struct BcConnection { 22 | sink: Arc>, 23 | subscribers: Arc>>>, 24 | rx_thread: Option>, 25 | // Arc> because it is shared between context 26 | // and connection for deserialisation and serialistion respectivly 27 | encryption_protocol: Arc>, 28 | poll_abort: Arc, 29 | keep_alive_msg: Arc>>, 30 | } 31 | 32 | impl BcConnection { 33 | pub fn new(source: BcSource) -> Result { 34 | let subscribers: Arc>>> = Default::default(); 35 | 36 | let mut subs = subscribers.clone(); 37 | 38 | let encryption_protocol = Arc::new(Mutex::new(EncryptionProtocol::Unencrypted)); 39 | let connections_encryption_protocol = encryption_protocol.clone(); 40 | let poll_abort = Arc::new(AtomicBool::new(false)); 41 | let poll_abort_rx = poll_abort.clone(); 42 | let mut conn = source.try_clone()?; 43 | let keep_alive_msg: Arc>> = Arc::new(Mutex::new(None)); 44 | let connections_keep_alive_msg = keep_alive_msg.clone(); 45 | let rx_thread = std::thread::spawn(move || { 46 | let keep_alive_encryption_protocol = connections_encryption_protocol.clone(); 47 | let mut context = BcContext::new(connections_encryption_protocol); 48 | let mut result; 49 | let mut last_keep_alive = Instant::now(); 50 | let keep_alive_time = Duration::from_millis(500); 51 | loop { 52 | result = Self::poll(&mut context, &conn, &mut subs, &connections_keep_alive_msg); 53 | if poll_abort_rx.load(Ordering::Relaxed) { 54 | break; // Poll has been aborted by request usally during disconnect 55 | } 56 | if let Err(e) = result { 57 | error!("Deserialization error: {}", e); 58 | let mut cause = e.source(); 59 | while let Some(e) = cause { 60 | error!("caused by: {}", e); 61 | cause = e.source(); 62 | } 63 | break; 64 | } 65 | // Send a udp keep alive if set 66 | if last_keep_alive.elapsed() > keep_alive_time { 67 | last_keep_alive = Instant::now(); 68 | if let Ok(lock) = connections_keep_alive_msg.try_lock() { 69 | if let Some(keep_alive_msg) = lock.as_ref() { 70 | let _ = keep_alive_msg 71 | .serialize(&conn, &keep_alive_encryption_protocol.lock().unwrap()); 72 | let _ = conn.flush(); 73 | } 74 | } 75 | } 76 | } 77 | }); 78 | 79 | Ok(BcConnection { 80 | sink: Arc::new(Mutex::new(source)), 81 | subscribers, 82 | rx_thread: Some(rx_thread), 83 | encryption_protocol, 84 | poll_abort, 85 | keep_alive_msg, 86 | }) 87 | } 88 | 89 | pub fn stop_polling(&self) { 90 | self.poll_abort.store(true, Ordering::Relaxed); 91 | } 92 | 93 | pub(super) fn send(&self, bc: Bc) -> Result<()> { 94 | bc.serialize(&*self.sink.lock().unwrap(), &self.get_encrypted())?; 95 | let _ = self.sink.lock().unwrap().flush(); 96 | Ok(()) 97 | } 98 | 99 | pub fn subscribe(&self, msg_id: u32) -> Result { 100 | let (tx, rx) = channel(); 101 | match self.subscribers.lock().unwrap().entry(msg_id) { 102 | Entry::Vacant(vac_entry) => vac_entry.insert(tx), 103 | Entry::Occupied(_) => return Err(Error::SimultaneousSubscription { msg_id }), 104 | }; 105 | Ok(BcSubscription::new(rx, msg_id, self)) 106 | } 107 | 108 | pub fn unsubscribe(&self, msg_id: u32) -> Result<()> { 109 | self.subscribers.lock().unwrap().remove(&msg_id); 110 | Ok(()) 111 | } 112 | 113 | pub fn set_keep_alive_msg(&self, msg: Bc) { 114 | *self.keep_alive_msg.lock().unwrap() = Some(msg); 115 | } 116 | 117 | pub fn set_encrypted(&self, value: EncryptionProtocol) { 118 | *(self.encryption_protocol.lock().unwrap()) = value; 119 | } 120 | 121 | pub fn get_encrypted(&self) -> EncryptionProtocol { 122 | (*self.encryption_protocol.lock().unwrap()).clone() 123 | } 124 | 125 | pub fn is_udp(&self) -> bool { 126 | self.sink.lock().unwrap().is_udp() 127 | } 128 | 129 | fn poll( 130 | context: &mut BcContext, 131 | connection: &BcSource, 132 | subscribers: &mut Arc>>>, 133 | connections_keep_alive_msg: &Arc>>, 134 | ) -> Result<()> { 135 | // Don't hold the lock during deserialization so we don't poison the subscribers mutex if 136 | // something goes wrong 137 | let response = Bc::deserialize(context, connection).map_err(|err| { 138 | // If the connection hangs up, hang up on all subscribers 139 | subscribers.lock().unwrap().clear(); 140 | err 141 | })?; 142 | let msg_id = response.meta.msg_id; 143 | 144 | let mut locked_subs = subscribers.lock().unwrap(); 145 | match locked_subs.entry(msg_id) { 146 | Entry::Occupied(mut occ) => { 147 | if occ.get_mut().send(response).is_err() { 148 | // Exceedingly unlikely, unless you mishandle the subscription object 149 | warn!("Subscriber to ID {} dropped their channel", msg_id); 150 | occ.remove(); 151 | } 152 | } 153 | Entry::Vacant(_) => { 154 | if msg_id != MSG_ID_UDP_KEEP_ALIVE { 155 | debug!("Ignoring uninteresting message ID {}", msg_id); 156 | trace!("Contents: {:?}", response); 157 | } else { 158 | // This is a keep alive message let see what the camera says about it 159 | if response.meta.response_code != 200 { 160 | // Camera dosen't support the current keep alive message stop sending them 161 | if let Ok(mut lock) = connections_keep_alive_msg.try_lock() { 162 | *lock = None; 163 | } 164 | } 165 | } 166 | } 167 | } 168 | 169 | Ok(()) 170 | } 171 | } 172 | 173 | impl Drop for BcConnection { 174 | fn drop(&mut self) { 175 | debug!("Shutting down BcConnection..."); 176 | match self 177 | .rx_thread 178 | .take() 179 | .expect("rx_thread join handle should always exist") 180 | .join() 181 | { 182 | Ok(_) => { 183 | debug!("Shutdown finished OK"); 184 | } 185 | Err(e) => { 186 | error!("Receiving thread panicked: {:?}", e); 187 | } 188 | } 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/connection/bcsource.rs: -------------------------------------------------------------------------------- 1 | use super::{Result, TcpSource, UdpSource}; 2 | use std::io::{Error as IoError, ErrorKind, Read, Write}; 3 | use std::net::SocketAddr; 4 | use std::sync::{Arc, Mutex}; 5 | use std::time::Duration; 6 | 7 | type IoResult = std::result::Result; 8 | 9 | pub enum BcSource { 10 | Tcp(Mutex), 11 | Udp(Mutex), 12 | } 13 | 14 | impl BcSource { 15 | pub fn is_udp(&self) -> bool { 16 | matches!(self, BcSource::Udp(_)) 17 | } 18 | 19 | pub fn new_tcp(addr: SocketAddr, timeout: Duration) -> Result { 20 | let source = TcpSource::new(addr, timeout)?; 21 | Ok(BcSource::Tcp(Mutex::new(source))) 22 | } 23 | 24 | pub fn new_udp(uid: &str, timeout: Duration) -> Result { 25 | let source = UdpSource::new(uid, timeout)?; 26 | Ok(BcSource::Udp(Mutex::new(source))) 27 | } 28 | 29 | pub fn try_clone(&self) -> IoResult { 30 | match self { 31 | BcSource::Tcp(source) => match &mut source.try_lock() { 32 | Ok(locked) => Ok(BcSource::Tcp(Mutex::new(locked.try_clone()?))), 33 | Err(_) => Err(IoError::new( 34 | ErrorKind::WouldBlock, 35 | "Unable to lock tcp for clone", 36 | )), 37 | }, 38 | 39 | BcSource::Udp(source) => match &mut source.try_lock() { 40 | Ok(locked) => Ok(BcSource::Udp(Mutex::new(locked.try_clone()?))), 41 | Err(_) => Err(IoError::new( 42 | ErrorKind::WouldBlock, 43 | "Unable to lock udp for clone", 44 | )), 45 | }, 46 | } 47 | } 48 | } 49 | 50 | impl Read for BcSource { 51 | fn read(&mut self, buf: &mut [u8]) -> IoResult { 52 | match self { 53 | BcSource::Tcp(source) => match &mut source.get_mut() { 54 | Ok(locked) => Ok(locked.read(buf)?), 55 | Err(_) => Err(IoError::new( 56 | ErrorKind::WouldBlock, 57 | "Unable to lock tcp for read", 58 | )), 59 | }, 60 | 61 | BcSource::Udp(source) => match &mut source.get_mut() { 62 | Ok(locked) => Ok(locked.read(buf)?), 63 | Err(_) => Err(IoError::new( 64 | ErrorKind::WouldBlock, 65 | "Unable to lock udp for read", 66 | )), 67 | }, 68 | } 69 | } 70 | } 71 | 72 | impl Read for &BcSource { 73 | fn read(&mut self, buf: &mut [u8]) -> IoResult { 74 | match self { 75 | BcSource::Tcp(source) => match &mut source.try_lock() { 76 | Ok(locked) => Ok(locked.read(buf)?), 77 | Err(_) => Err(IoError::new( 78 | ErrorKind::WouldBlock, 79 | "Unable to lock tcp for &read", 80 | )), 81 | }, 82 | 83 | BcSource::Udp(source) => match &mut source.try_lock() { 84 | Ok(locked) => Ok(locked.read(buf)?), 85 | Err(_) => Err(IoError::new( 86 | ErrorKind::WouldBlock, 87 | "Unable to lock udp for &read", 88 | )), 89 | }, 90 | } 91 | } 92 | } 93 | 94 | impl Write for BcSource { 95 | fn write(&mut self, buf: &[u8]) -> IoResult { 96 | match self { 97 | BcSource::Tcp(source) => match &mut source.get_mut() { 98 | Ok(locked) => Ok(locked.write(buf)?), 99 | Err(_) => Err(IoError::new( 100 | ErrorKind::WouldBlock, 101 | "Unable to lock tcp for write", 102 | )), 103 | }, 104 | 105 | BcSource::Udp(source) => match &mut source.get_mut() { 106 | Ok(locked) => Ok(locked.write(buf)?), 107 | Err(_) => Err(IoError::new( 108 | ErrorKind::WouldBlock, 109 | "Unable to lock udp for write", 110 | )), 111 | }, 112 | } 113 | } 114 | 115 | fn flush(&mut self) -> IoResult<()> { 116 | match self { 117 | BcSource::Tcp(source) => match &mut source.get_mut() { 118 | Ok(locked) => Ok(locked.flush()?), 119 | Err(_) => Err(IoError::new( 120 | ErrorKind::WouldBlock, 121 | "Unable to lock tcp for flush", 122 | )), 123 | }, 124 | 125 | BcSource::Udp(source) => match &mut source.get_mut() { 126 | Ok(locked) => Ok(locked.flush()?), 127 | Err(_) => Err(IoError::new( 128 | ErrorKind::WouldBlock, 129 | "Unable to lock tcp udp for flush", 130 | )), 131 | }, 132 | } 133 | } 134 | } 135 | 136 | impl Write for &BcSource { 137 | fn write(&mut self, buf: &[u8]) -> IoResult { 138 | match self { 139 | BcSource::Tcp(source) => match &mut source.try_lock() { 140 | Ok(locked) => Ok(locked.write(buf)?), 141 | Err(_) => Err(IoError::new( 142 | ErrorKind::WouldBlock, 143 | "Unable to lock tcp for write", 144 | )), 145 | }, 146 | 147 | BcSource::Udp(source) => match &mut source.try_lock() { 148 | Ok(locked) => Ok(locked.write(buf)?), 149 | Err(_) => Err(IoError::new( 150 | ErrorKind::WouldBlock, 151 | "Unable to lock udp for write", 152 | )), 153 | }, 154 | } 155 | } 156 | 157 | fn flush(&mut self) -> IoResult<()> { 158 | match self { 159 | BcSource::Tcp(source) => match &mut source.try_lock() { 160 | Ok(locked) => Ok(locked.flush()?), 161 | Err(_) => Err(IoError::new( 162 | ErrorKind::WouldBlock, 163 | "Unable to lock tcp for &flush", 164 | )), 165 | }, 166 | 167 | BcSource::Udp(source) => match &mut source.try_lock() { 168 | Ok(locked) => Ok(locked.flush()?), 169 | Err(_) => Err(IoError::new( 170 | ErrorKind::WouldBlock, 171 | "Unable to lock udp for &flush", 172 | )), 173 | }, 174 | } 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/connection/bcsub.rs: -------------------------------------------------------------------------------- 1 | use super::{BcConnection, Result}; 2 | use crate::bc::model::*; 3 | use std::sync::mpsc::Receiver; 4 | 5 | pub struct BcSubscription<'a> { 6 | pub rx: Receiver, 7 | msg_id: u32, 8 | conn: &'a BcConnection, 9 | } 10 | 11 | impl<'a> BcSubscription<'a> { 12 | pub fn new(rx: Receiver, msg_id: u32, conn: &'a BcConnection) -> BcSubscription<'a> { 13 | BcSubscription { rx, msg_id, conn } 14 | } 15 | 16 | pub fn send(&self, bc: Bc) -> Result<()> { 17 | assert!(bc.meta.msg_id == self.msg_id); 18 | self.conn.send(bc)?; 19 | Ok(()) 20 | } 21 | } 22 | 23 | /// Makes it difficult to avoid unsubscribing when you're finished 24 | impl<'a> Drop for BcSubscription<'a> { 25 | fn drop(&mut self) { 26 | // It's fine if we can't unsubscribe as that means we already have 27 | let _ = self.conn.unsubscribe(self.msg_id); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/connection/binarysub.rs: -------------------------------------------------------------------------------- 1 | use super::{ 2 | super::{connection::BcSubscription, RX_TIMEOUT}, 3 | BcConnection, 4 | }; 5 | use crate::bc::model::*; 6 | use std::{ 7 | io::{BufRead, Error, ErrorKind, Read}, 8 | sync::mpsc::RecvTimeoutError, 9 | }; 10 | 11 | type Result = std::result::Result; 12 | 13 | /// A `BinarySubscriber` is a helper util to read the binary stream 14 | /// of a [`BcSubscription`] 15 | /// 16 | /// Some messgaes like video streams contain a substream in their 17 | /// payload that may be broken at any point into multiple bc packets. 18 | /// This subscriber will create a stream reader for these binary streams. 19 | /// 20 | /// This stream should be accessed via the [`BufRead`] and [`Read`] trait 21 | pub struct BinarySubscriber<'a> { 22 | bc_sub: &'a BcSubscription<'a>, 23 | buffer: Vec, 24 | consumed: usize, 25 | } 26 | 27 | impl<'a> BinarySubscriber<'a> { 28 | /// Creates a binary subsciber from a BcSubscrption. 29 | /// When reading the next packet it will skip over multiple 30 | /// Bc packets to fill the binary buffer so ensure you 31 | /// only want binary packets when calling read 32 | pub fn from_bc_sub<'b>(bc_sub: &'b BcSubscription) -> BinarySubscriber<'b> { 33 | BinarySubscriber { 34 | bc_sub, 35 | buffer: vec![], 36 | consumed: 0, 37 | } 38 | } 39 | } 40 | 41 | impl<'a> Read for BinarySubscriber<'a> { 42 | fn read(&mut self, buf: &mut [u8]) -> Result { 43 | let buffer = self.fill_buf()?; 44 | let amt = std::cmp::min(buf.len(), buffer.len()); 45 | 46 | // First check if the amount of bytes we want to read is small: 47 | // `copy_from_slice` will generally expand to a call to `memcpy`, and 48 | // for a single byte the overhead is significant. 49 | if amt == 1 { 50 | buf[0] = buffer[0]; 51 | } else { 52 | buf[..amt].copy_from_slice(&buffer[..amt]); 53 | } 54 | 55 | self.consume(amt); 56 | 57 | Ok(amt) 58 | } 59 | } 60 | impl<'a> BufRead for BinarySubscriber<'a> { 61 | fn fill_buf(&mut self) -> Result<&[u8]> { 62 | const CLEAR_CONSUMED_AT: usize = 1024; 63 | // This is a trade off between caching too much dead memory 64 | // and calling the drain method too often 65 | if self.consumed > CLEAR_CONSUMED_AT { 66 | let _ = self.buffer.drain(0..self.consumed).collect::>(); 67 | self.consumed = 0; 68 | } 69 | while self.buffer.len() <= self.consumed { 70 | let msg = self 71 | .bc_sub 72 | .rx 73 | .recv_timeout(RX_TIMEOUT) 74 | .map_err(|err| match err { 75 | RecvTimeoutError::Timeout => Error::new(ErrorKind::TimedOut, err), 76 | RecvTimeoutError::Disconnected => Error::new(ErrorKind::ConnectionReset, err), 77 | })?; 78 | if let BcBody::ModernMsg(ModernMsg { 79 | payload: Some(BcPayloads::Binary(binary)), 80 | .. 81 | }) = msg.body 82 | { 83 | // Add the new binary to the buffer and return 84 | self.buffer.extend(binary); 85 | } 86 | } 87 | 88 | Ok(&self.buffer.as_slice()[self.consumed..]) 89 | } 90 | 91 | fn consume(&mut self, amt: usize) { 92 | assert!(self.consumed + amt <= self.buffer.len()); 93 | self.consumed += amt; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/connection/filesub.rs: -------------------------------------------------------------------------------- 1 | // This is a test module so it will appear as unused most of the time 2 | #![allow(dead_code)] 3 | // This module is used to subscribe to raw bytes on disk 4 | // 5 | // It is mostly used for testing 6 | // 7 | use std::{ 8 | fs, 9 | io::{BufRead, Error, Read}, 10 | path::{Path, PathBuf}, 11 | }; 12 | 13 | type Result = std::result::Result; 14 | 15 | /// A `FileSubscriber` is a helper util to read a binary stream 16 | /// from a series of files 17 | /// 18 | /// This stream should be accessed via the [`BufRead`] and [`Read`] trait 19 | #[derive(Debug)] 20 | pub struct FileSubscriber { 21 | files: Vec, 22 | buffer: Vec, 23 | consumed: usize, 24 | } 25 | 26 | impl FileSubscriber { 27 | /// Creates a file subsciber from a list of files 28 | pub fn from_files>(paths: Vec

) -> FileSubscriber { 29 | FileSubscriber { 30 | files: paths 31 | .iter() 32 | .rev() 33 | .map(|p| { 34 | let path: &Path = p.as_ref(); 35 | path.to_path_buf() 36 | }) 37 | .collect(), 38 | buffer: vec![], 39 | consumed: 0, 40 | } 41 | } 42 | } 43 | 44 | impl Read for FileSubscriber { 45 | fn read(&mut self, buf: &mut [u8]) -> Result { 46 | let buffer = self.fill_buf()?; 47 | let amt = std::cmp::min(buf.len(), buffer.len()); 48 | 49 | // First check if the amount of bytes we want to read is small: 50 | // `copy_from_slice` will generally expand to a call to `memcpy`, and 51 | // for a single byte the overhead is significant. 52 | if amt == 1 { 53 | buf[0] = buffer[0]; 54 | } else { 55 | buf[..amt].copy_from_slice(&buffer[..amt]); 56 | } 57 | 58 | self.consume(amt); 59 | 60 | Ok(amt) 61 | } 62 | } 63 | impl BufRead for FileSubscriber { 64 | fn fill_buf(&mut self) -> Result<&[u8]> { 65 | const CLEAR_CONSUMED_AT: usize = 1024; 66 | // This is a trade off between caching too much dead memory 67 | // and calling the drain method too often 68 | if self.consumed > CLEAR_CONSUMED_AT { 69 | let _ = self.buffer.drain(0..self.consumed).collect::>(); 70 | self.consumed = 0; 71 | } 72 | while self.buffer.len() <= self.consumed { 73 | let next_file = self.files.pop(); 74 | if let Some(next_file) = next_file { 75 | let bytes = &fs::read(next_file)?; 76 | self.buffer.extend(bytes); 77 | } else { 78 | break; 79 | } 80 | } 81 | 82 | Ok(&self.buffer.as_slice()[self.consumed..]) 83 | } 84 | 85 | fn consume(&mut self, amt: usize) { 86 | assert!(self.consumed + amt <= self.buffer.len()); 87 | self.consumed += amt; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/connection/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_imports)] 2 | //! This module handles connections and subscribers 3 | //! 4 | //! This includes a tcp and udp connections. As well 5 | //! as subscribers to binary streams that are encoded 6 | //! in the bc packets. 7 | //! 8 | use crate::bc; 9 | use crate::bc::model::*; 10 | use crate::bcudp; 11 | use err_derive::Error; 12 | use log::*; 13 | use socket2::{Domain, Socket, Type}; 14 | use std::collections::btree_map::Entry; 15 | use std::collections::BTreeMap; 16 | use std::error::Error as StdErr; // Just need the traits 17 | use std::net::{SocketAddr, TcpStream}; 18 | use std::sync::mpsc::{channel, Receiver, RecvError, Sender}; 19 | use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc, Mutex}; 20 | 21 | use std::thread::JoinHandle; 22 | use std::time::Duration; 23 | 24 | mod bcconn; 25 | mod bcsource; 26 | mod bcsub; 27 | mod binarysub; 28 | mod filesub; 29 | mod tcpconn; 30 | mod udpconn; 31 | 32 | pub(crate) use self::{ 33 | bcconn::BcConnection, bcsource::BcSource, bcsub::BcSubscription, binarysub::BinarySubscriber, 34 | filesub::FileSubscriber, tcpconn::TcpSource, udpconn::UdpSource, 35 | }; 36 | 37 | #[derive(Debug, Error)] 38 | pub enum Error { 39 | #[error(display = "Communication error")] 40 | Communication(#[error(source)] std::io::Error), 41 | 42 | #[error(display = "Communication Reciever error")] 43 | RecvCommunication(#[error(source)] RecvError), 44 | 45 | #[error(display = "Deserialization error")] 46 | Deserialization(#[error(source)] bc::de::Error), 47 | 48 | #[error(display = "Serialization error")] 49 | Serialization(#[error(source)] bc::ser::Error), 50 | 51 | #[error(display = "UDP Deserialization error")] 52 | UdpDeserialization(#[error(source)] bcudp::de::Error), 53 | 54 | #[error(display = "UDP Serialization error")] 55 | UdpSerialization(#[error(source)] bcudp::ser::Error), 56 | 57 | #[error(display = "Simultaneous subscription")] 58 | SimultaneousSubscription { msg_id: u32 }, 59 | 60 | #[error(display = "Timeout")] 61 | Timeout, 62 | 63 | #[error(display = "This connection type in unsupported")] 64 | UnsupportedConnection, 65 | 66 | #[error(display = "Camera Not Findable")] 67 | ConnectionUnavaliable, 68 | } 69 | 70 | type Result = std::result::Result; 71 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/connection/tcpconn.rs: -------------------------------------------------------------------------------- 1 | use super::{BcSubscription, Error, Result}; 2 | use crate::bc; 3 | use crate::bc::model::*; 4 | use log::*; 5 | use socket2::{Domain, Socket, Type}; 6 | use std::collections::btree_map::Entry; 7 | use std::collections::BTreeMap; 8 | use std::error::Error as StdErr; // Just need the traits 9 | use std::io::{Error as IoError, Read, Write}; 10 | use std::net::{SocketAddr, TcpStream}; 11 | use std::sync::mpsc::{channel, Receiver, Sender}; 12 | use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc, Mutex}; 13 | use std::thread::JoinHandle; 14 | use std::time::Duration; 15 | 16 | type IoResult = std::result::Result; 17 | 18 | pub struct TcpSource { 19 | stream: TcpStream, 20 | } 21 | 22 | impl TcpSource { 23 | pub fn new(addr: SocketAddr, timeout: Duration) -> Result { 24 | let tcp_conn = connect_to(addr, timeout)?; 25 | 26 | Ok(Self { stream: tcp_conn }) 27 | } 28 | 29 | pub fn try_clone(&self) -> IoResult { 30 | Ok(Self { 31 | stream: self.stream.try_clone()?, 32 | }) 33 | } 34 | } 35 | 36 | impl Read for TcpSource { 37 | fn read(&mut self, buf: &mut [u8]) -> IoResult { 38 | self.stream.read(buf) 39 | } 40 | } 41 | 42 | impl Write for TcpSource { 43 | fn write(&mut self, buf: &[u8]) -> IoResult { 44 | self.stream.write(buf) 45 | } 46 | 47 | fn flush(&mut self) -> IoResult<()> { 48 | self.stream.flush() 49 | } 50 | } 51 | 52 | /// Helper to create a TcpStream with a connect timeout 53 | fn connect_to(addr: SocketAddr, timeout: Duration) -> Result { 54 | let socket = match addr { 55 | SocketAddr::V4(_) => Socket::new(Domain::ipv4(), Type::stream(), None)?, 56 | SocketAddr::V6(_) => { 57 | let s = Socket::new(Domain::ipv6(), Type::stream(), None)?; 58 | s.set_only_v6(false)?; 59 | s 60 | } 61 | }; 62 | 63 | socket.set_keepalive(Some(timeout))?; 64 | socket.set_read_timeout(Some(timeout))?; 65 | socket.set_write_timeout(Some(timeout))?; 66 | socket.connect_timeout(&addr.into(), timeout)?; 67 | 68 | Ok(socket.into_tcp_stream()) 69 | } 70 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/connection/udpconn/aborthandle.rs: -------------------------------------------------------------------------------- 1 | use std::sync::{ 2 | atomic::{AtomicBool, Ordering}, 3 | Arc, 4 | }; 5 | 6 | #[derive(Clone)] 7 | pub struct AbortHandle { 8 | aborted: Arc, 9 | } 10 | 11 | impl AbortHandle { 12 | pub fn new() -> Self { 13 | Self { 14 | aborted: Arc::new(AtomicBool::new(false)), 15 | } 16 | } 17 | 18 | pub fn abort(&self) { 19 | self.aborted.store(true, Ordering::Relaxed); 20 | } 21 | 22 | pub fn is_aborted(&self) -> bool { 23 | self.aborted.load(Ordering::Relaxed) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/errors.rs: -------------------------------------------------------------------------------- 1 | use super::bc::model::Bc; 2 | use err_derive::Error; 3 | 4 | /// This is the primary error type of the library 5 | #[derive(Debug, Error)] 6 | #[allow(clippy::large_enum_variant)] 7 | pub enum Error { 8 | /// Error raised when IO fails such as when the connection is lost 9 | #[error(display = "Communication error")] 10 | Communication(#[error(source)] std::io::Error), 11 | 12 | /// Error raised during deserlization 13 | #[error(display = "Deserialization error")] 14 | Deserialization(#[error(source)] super::bc::de::Error), 15 | 16 | /// Error raised during serlization 17 | #[error(display = "Serialization error")] 18 | Serialization(#[error(source)] super::bc::ser::Error), 19 | 20 | /// Error raised during deserlization 21 | #[error(display = "Media Deserialization error")] 22 | MediaDeserialization(#[error(source)] super::bcmedia::de::Error), 23 | 24 | /// Error raised during serlization 25 | #[error(display = "Media Serialization error")] 26 | MediaSerialization(#[error(source)] super::bcmedia::ser::Error), 27 | 28 | /// A connection error such as Simultaneous subscription 29 | #[error(display = "Connection error")] 30 | ConnectionError(#[error(source)] super::connection::Error), 31 | 32 | /// Raised when a Bc reply was not understood 33 | #[error(display = "Communication error")] 34 | UnintelligibleReply { 35 | /// The Bc packet that was not understood 36 | reply: Bc, 37 | /// The message attached to the error 38 | why: &'static str, 39 | }, 40 | 41 | /// Raised when a connection is dropped. 42 | #[error(display = "Dropped connection")] 43 | DroppedConnection(#[error(source)] std::sync::mpsc::RecvError), 44 | 45 | /// Raised when the RX_TIMEOUT is reach 46 | #[error(display = "Timeout")] 47 | Timeout, 48 | 49 | /// Raised when connection is dropped because the timeout is reach 50 | #[error(display = "Dropped connection")] 51 | TimeoutDisconnected, 52 | 53 | /// Raised when failed to login to the camera 54 | #[error(display = "Credential error")] 55 | AuthFailed, 56 | 57 | /// Raised when the given camera url could not be resolved 58 | #[error(display = "Failed to translate camera address")] 59 | AddrResolutionError, 60 | 61 | /// Raised non adpcm data is sent to the talk command 62 | #[error(display = "Talk data is not ADPCM")] 63 | UnknownTalkEncoding, 64 | 65 | /// A generic catch all error 66 | #[error(display = "Other error")] 67 | Other(&'static str), 68 | 69 | /// A generic catch all error 70 | #[error(display = "Other error")] 71 | OtherString(String), 72 | } 73 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/ledstate.rs: -------------------------------------------------------------------------------- 1 | use super::{BcCamera, Error, Result, RX_TIMEOUT}; 2 | use crate::bc::{model::*, xml::*}; 3 | 4 | impl BcCamera { 5 | /// Get the [LedState] xml which contains the LED status of the camera 6 | pub fn get_ledstate(&self) -> Result { 7 | let connection = self 8 | .connection 9 | .as_ref() 10 | .expect("Must be connected to get time"); 11 | let sub_get = connection.subscribe(MSG_ID_GET_LED_STATUS)?; 12 | let get = Bc { 13 | meta: BcMeta { 14 | msg_id: MSG_ID_GET_LED_STATUS, 15 | channel_id: self.channel_id, 16 | msg_num: self.new_message_num(), 17 | response_code: 0, 18 | stream_type: 0, 19 | class: 0x6414, 20 | }, 21 | body: BcBody::ModernMsg(ModernMsg { 22 | extension: Some(Extension { 23 | channel_id: Some(self.channel_id), 24 | ..Default::default() 25 | }), 26 | payload: None, 27 | }), 28 | }; 29 | 30 | sub_get.send(get)?; 31 | let msg = sub_get.rx.recv_timeout(RX_TIMEOUT)?; 32 | 33 | if let BcBody::ModernMsg(ModernMsg { 34 | payload: 35 | Some(BcPayloads::BcXml(BcXml { 36 | led_state: Some(ledstate), 37 | .. 38 | })), 39 | .. 40 | }) = msg.body 41 | { 42 | Ok(ledstate) 43 | } else { 44 | Err(Error::UnintelligibleReply { 45 | reply: msg, 46 | why: "Expected LEDState xml but it was not recieved", 47 | }) 48 | } 49 | } 50 | 51 | /// Set the led lights using the [LedState] xml 52 | pub fn set_ledstate(&self, mut led_state: LedState) -> Result<()> { 53 | let connection = self 54 | .connection 55 | .as_ref() 56 | .expect("Must be connected to get time"); 57 | let sub_set = connection.subscribe(MSG_ID_SET_LED_STATUS)?; 58 | 59 | // led_version is a field recieved from the camera but not sent 60 | // we set to None to ensure we don't send it to the camera 61 | led_state.led_version = None; 62 | let get = Bc { 63 | meta: BcMeta { 64 | msg_id: MSG_ID_SET_LED_STATUS, 65 | channel_id: self.channel_id, 66 | msg_num: self.new_message_num(), 67 | response_code: 0, 68 | stream_type: 0, 69 | class: 0x6414, 70 | }, 71 | body: BcBody::ModernMsg(ModernMsg { 72 | extension: Some(Extension { 73 | channel_id: Some(self.channel_id), 74 | ..Default::default() 75 | }), 76 | payload: Some(BcPayloads::BcXml(BcXml { 77 | led_state: Some(led_state), 78 | ..Default::default() 79 | })), 80 | }), 81 | }; 82 | 83 | sub_set.send(get)?; 84 | let msg = sub_set.rx.recv_timeout(RX_TIMEOUT)?; 85 | 86 | if let BcMeta { 87 | response_code: 200, .. 88 | } = msg.meta 89 | { 90 | Ok(()) 91 | } else { 92 | Err(Error::UnintelligibleReply { 93 | reply: msg, 94 | why: "The camera did not except the LEDState xml", 95 | }) 96 | } 97 | } 98 | 99 | /// This is a convience function to control the IR LED lights 100 | /// 101 | /// This is for the RED IR lights that can come on automaitcally 102 | /// during low light. 103 | pub fn irled_light_set(&self, state: LightState) -> Result<()> { 104 | let mut led_state = self.get_ledstate()?; 105 | led_state.state = match state { 106 | LightState::On => "open".to_string(), 107 | LightState::Off => "close".to_string(), 108 | LightState::Auto => "auto".to_string(), 109 | }; 110 | self.set_ledstate(led_state)?; 111 | Ok(()) 112 | } 113 | 114 | /// This is a convience function to control the LED light 115 | /// True is on and false is off 116 | /// 117 | /// This is for the little blue on light of some camera 118 | pub fn led_light_set(&self, state: bool) -> Result<()> { 119 | let mut led_state = self.get_ledstate()?; 120 | led_state.light_state = match state { 121 | true => "open".to_string(), 122 | false => "close".to_string(), 123 | }; 124 | self.set_ledstate(led_state)?; 125 | Ok(()) 126 | } 127 | } 128 | 129 | /// This is pased to `irled_light_set` to turn it on, off or set it to light based auto 130 | pub enum LightState { 131 | /// Turn the light on 132 | On, 133 | /// Turn the light off 134 | Off, 135 | /// Set the light to light based auto 136 | Auto, 137 | } 138 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/login.rs: -------------------------------------------------------------------------------- 1 | use super::{make_aes_key, md5_string, BcCamera, Error, Result, Truncate, ZeroLast, RX_TIMEOUT}; 2 | use crate::bc::{model::*, xml::*}; 3 | 4 | impl BcCamera { 5 | /// Login to the camera. 6 | /// 7 | /// This should be called before most other commands 8 | pub fn login(&mut self, username: &str, password: Option<&str>) -> Result { 9 | let device_info; 10 | // This { is here due to the connection and set_credentials both requiring a mutable borrow 11 | { 12 | let connection = self 13 | .connection 14 | .as_ref() 15 | .expect("Must be connected to log in"); 16 | let sub_login = connection.subscribe(MSG_ID_LOGIN)?; 17 | 18 | // Login flow is: Send legacy login message, expect back a modern message with Encryption 19 | // details. Then, re-send the login as a modern login message. Expect back a device info 20 | // congratulating us on logging in. 21 | 22 | // In the legacy scheme, username/password are MD5'd if they are encrypted (which they need 23 | // to be to "upgrade" to the modern login flow), then the hex of the MD5 is sent. 24 | // Note: I suspect there may be a buffer overflow opportunity in the firmware since in the 25 | // Baichuan library, these strings are capped at 32 bytes with a null terminator. This 26 | // could also be a mistake in the library, the effect being it only compares 31 chars, not 32. 27 | let md5_username = md5_string(username, ZeroLast); 28 | let md5_password = password 29 | .map(|p| md5_string(p, ZeroLast)) 30 | .unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned()); 31 | 32 | let legacy_login = Bc { 33 | meta: BcMeta { 34 | msg_id: MSG_ID_LOGIN, 35 | channel_id: self.channel_id, 36 | msg_num: self.new_message_num(), 37 | stream_type: 0, 38 | response_code: 0xdc02, 39 | class: 0x6514, 40 | }, 41 | body: BcBody::LegacyMsg(LegacyMsg::LoginMsg { 42 | username: md5_username, 43 | password: md5_password, 44 | }), 45 | }; 46 | 47 | sub_login.send(legacy_login)?; 48 | 49 | let legacy_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; 50 | 51 | let nonce; 52 | match legacy_reply.body { 53 | BcBody::ModernMsg(ModernMsg { 54 | payload: 55 | Some(BcPayloads::BcXml(BcXml { 56 | encryption: Some(encryption), 57 | .. 58 | })), 59 | .. 60 | }) => { 61 | nonce = encryption.nonce; 62 | } 63 | _ => { 64 | return Err(Error::UnintelligibleReply { 65 | reply: legacy_reply, 66 | why: "Expected an Encryption message back", 67 | }) 68 | } 69 | } 70 | 71 | // In the modern login flow, the username/password are concat'd with the server's nonce 72 | // string, then MD5'd, then the hex of this MD5 is sent as the password. This nonce 73 | // prevents replay attacks if the server were to require modern flow, but not rainbow table 74 | // attacks (since the plain user/password MD5s have already been sent). The upshot is that 75 | // you should use a very strong random password that is not found in a rainbow table and 76 | // not feasibly crackable with John the Ripper. 77 | 78 | let modern_password = password.unwrap_or(""); 79 | let concat_username = format!("{}{}", username, nonce); 80 | let concat_password = format!("{}{}", modern_password, nonce); 81 | let md5_username = md5_string(&concat_username, Truncate); 82 | let md5_password = md5_string(&concat_password, Truncate); 83 | 84 | let modern_login = Bc::new_from_xml( 85 | BcMeta { 86 | msg_id: MSG_ID_LOGIN, 87 | channel_id: self.channel_id, 88 | msg_num: self.new_message_num(), 89 | stream_type: 0, 90 | response_code: 0, 91 | class: 0x6414, 92 | }, 93 | BcXml { 94 | login_user: Some(LoginUser { 95 | version: xml_ver(), 96 | user_name: md5_username, 97 | password: md5_password, 98 | user_ver: 1, 99 | }), 100 | login_net: Some(LoginNet::default()), 101 | ..Default::default() 102 | }, 103 | ); 104 | 105 | sub_login.send(modern_login)?; 106 | let modern_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; 107 | 108 | match modern_reply.body { 109 | BcBody::ModernMsg(ModernMsg { 110 | payload: 111 | Some(BcPayloads::BcXml(BcXml { 112 | device_info: Some(info), 113 | .. 114 | })), 115 | .. 116 | }) => { 117 | // Login succeeded! 118 | self.logged_in = true; 119 | device_info = info; 120 | } 121 | BcBody::ModernMsg(ModernMsg { 122 | extension: None, 123 | payload: None, 124 | }) => return Err(Error::AuthFailed), 125 | _ => { 126 | return Err(Error::UnintelligibleReply { 127 | reply: modern_reply, 128 | why: "Expected a DeviceInfo message back from login", 129 | }) 130 | } 131 | } 132 | 133 | if let EncryptionProtocol::Aes(_) = connection.get_encrypted() { 134 | // We setup the data for the AES key now 135 | // as all subsequent communications will use it 136 | let passwd = password.unwrap_or(""); 137 | let full_key = make_aes_key(&nonce, passwd); 138 | connection.set_encrypted(EncryptionProtocol::Aes(Some(full_key))); 139 | } 140 | } 141 | self.set_credentials(username.to_string(), password.map(|s| s.to_string())); 142 | Ok(device_info) 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/logout.rs: -------------------------------------------------------------------------------- 1 | use super::{BcCamera, Result}; 2 | use crate::bc::{model::*, xml::*}; 3 | 4 | impl BcCamera { 5 | /// Logout from the camera 6 | pub fn logout(&mut self) -> Result<()> { 7 | if self.logged_in { 8 | if let Some(credentials) = self.get_credentials() { 9 | let connection = self 10 | .connection 11 | .as_ref() 12 | .expect("Must be connected to log in"); 13 | let sub_logout = connection.subscribe(MSG_ID_LOGOUT)?; 14 | 15 | let username = credentials.username.clone(); 16 | let password = credentials 17 | .password 18 | .as_ref() 19 | .cloned() 20 | .unwrap_or_else(|| "".to_string()); 21 | 22 | let modern_logout = Bc::new_from_xml( 23 | BcMeta { 24 | msg_id: MSG_ID_LOGOUT, 25 | channel_id: self.channel_id, 26 | msg_num: self.new_message_num(), 27 | stream_type: 0, 28 | response_code: 0, 29 | class: 0x6414, 30 | }, 31 | BcXml { 32 | login_user: Some(LoginUser { 33 | version: xml_ver(), 34 | user_name: username, 35 | password, 36 | user_ver: 1, 37 | }), 38 | login_net: Some(LoginNet::default()), 39 | ..Default::default() 40 | }, 41 | ); 42 | 43 | sub_logout.send(modern_logout)?; 44 | } 45 | } 46 | self.clear_credentials(); 47 | self.logged_in = false; 48 | Ok(()) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/motion.rs: -------------------------------------------------------------------------------- 1 | use super::{BcCamera, Error, Result, RX_TIMEOUT}; 2 | use crate::bc::{model::*, xml::*}; 3 | 4 | /// Motion Status that the callback can send 5 | pub enum MotionStatus { 6 | /// Sent when motion is first detected 7 | Start, 8 | /// Sent when motion stops 9 | Stop, 10 | /// Sent when an Alarm about something other than motion was received 11 | NoChange, 12 | } 13 | 14 | /// This is a conveince type for the error of the MotionOutput callback 15 | pub type MotionOutputError = Result; 16 | 17 | /// Trait used as part of [`listen_on_motion`] to send motion messages 18 | pub trait MotionOutput { 19 | /// This is the callback used when motion is received 20 | /// 21 | /// If result is `Ok(true)` more messages will be sent 22 | /// 23 | /// If result if `Ok(false)` then message will be stopped 24 | /// 25 | /// If result is `Err(E)` then motion messages be stopped 26 | /// and an error will be thrown 27 | fn motion_recv(&mut self, motion_status: MotionStatus) -> MotionOutputError; 28 | } 29 | 30 | impl BcCamera { 31 | /// This message tells the camera to send the motion events to us 32 | /// Which are the recieved on msgid 33 33 | fn start_motion_query(&self) -> Result<()> { 34 | let connection = self 35 | .connection 36 | .as_ref() 37 | .expect("Must be connected to listen to messages"); 38 | 39 | let sub = connection.subscribe(MSG_ID_MOTION_REQUEST)?; 40 | let msg = Bc { 41 | meta: BcMeta { 42 | msg_id: MSG_ID_MOTION_REQUEST, 43 | channel_id: self.channel_id, 44 | msg_num: self.new_message_num(), 45 | stream_type: 0, 46 | response_code: 0, 47 | class: 0x6414, 48 | }, 49 | body: BcBody::ModernMsg(ModernMsg { 50 | ..Default::default() 51 | }), 52 | }; 53 | 54 | sub.send(msg)?; 55 | 56 | let msg = sub.rx.recv_timeout(RX_TIMEOUT)?; 57 | 58 | if let BcMeta { 59 | response_code: 200, .. 60 | } = msg.meta 61 | { 62 | Ok(()) 63 | } else { 64 | Err(Error::UnintelligibleReply { 65 | reply: msg, 66 | why: "The camera did not accept the request to start motion", 67 | }) 68 | } 69 | } 70 | 71 | /// This requests that motion messages be listen to and sent to the 72 | /// output struct. 73 | /// 74 | /// The output structure must implement the [`MotionCallback`] trait 75 | pub fn listen_on_motion(&self, data_out: &mut T) -> Result<()> { 76 | self.start_motion_query()?; 77 | 78 | let connection = self 79 | .connection 80 | .as_ref() 81 | .expect("Must be connected to listen to messages"); 82 | 83 | // After start_motion_query (MSG_ID 31) the camera sends motion messages 84 | // when whenever motion is detected. 85 | let sub = connection.subscribe(MSG_ID_MOTION)?; 86 | 87 | loop { 88 | // Mostly ignore when timout is reached because these messages are only 89 | // sent when motion is detected which might means hours between messages 90 | // being received 91 | let msg = sub.rx.recv_timeout(RX_TIMEOUT); 92 | let status = match msg { 93 | Ok(motion_msg) => { 94 | if let BcBody::ModernMsg(ModernMsg { 95 | payload: 96 | Some(BcPayloads::BcXml(BcXml { 97 | alarm_event_list: Some(alarm_event_list), 98 | .. 99 | })), 100 | .. 101 | }) = motion_msg.body 102 | { 103 | let mut result = MotionStatus::NoChange; 104 | for alarm_event in &alarm_event_list.alarm_events { 105 | if alarm_event.channel_id == self.channel_id { 106 | if alarm_event.status == "MD" { 107 | result = MotionStatus::Start; 108 | break; 109 | } else if alarm_event.status == "none" { 110 | result = MotionStatus::Stop; 111 | break; 112 | } 113 | } 114 | } 115 | Ok(result) 116 | } else { 117 | Ok(MotionStatus::NoChange) 118 | } 119 | } 120 | Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Ok(MotionStatus::NoChange), 121 | // On connection drop we stop 122 | Err(e @ std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(e), 123 | }?; 124 | 125 | match data_out.motion_recv(status) { 126 | Ok(true) => {} 127 | Ok(false) => return Ok(()), 128 | Err(e) => return Err(e), 129 | } 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/ping.rs: -------------------------------------------------------------------------------- 1 | use super::{BcCamera, Result, RX_TIMEOUT}; 2 | use crate::bc::model::*; 3 | 4 | impl BcCamera { 5 | /// Ping the camera will either return Ok(()) which means a sucess reply 6 | /// or error 7 | pub fn ping(&self) -> Result<()> { 8 | let connection = self.connection.as_ref().expect("Must be connected to ping"); 9 | let sub_ping = connection.subscribe(MSG_ID_PING)?; 10 | 11 | let ping = Bc { 12 | meta: BcMeta { 13 | msg_id: MSG_ID_PING, 14 | channel_id: self.channel_id, 15 | msg_num: self.new_message_num(), 16 | stream_type: 0, 17 | response_code: 0, 18 | class: 0x6414, 19 | }, 20 | body: BcBody::ModernMsg(ModernMsg { 21 | ..Default::default() 22 | }), 23 | }; 24 | 25 | sub_ping.send(ping)?; 26 | 27 | sub_ping.rx.recv_timeout(RX_TIMEOUT)?; 28 | 29 | Ok(()) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/pirstate.rs: -------------------------------------------------------------------------------- 1 | use super::{BcCamera, Error, Result, RX_TIMEOUT}; 2 | use crate::bc::{model::*, xml::*}; 3 | 4 | impl BcCamera { 5 | /// Get the [RfAlarmCfg] xml which contains the PIR status of the camera 6 | pub fn get_pirstate(&mut self) -> Result { 7 | let connection = self 8 | .connection 9 | .as_ref() 10 | .expect("Must be connected to get time"); 11 | let sub_get = connection.subscribe(MSG_ID_GET_PIR_ALARM)?; 12 | let get = Bc { 13 | meta: BcMeta { 14 | msg_id: MSG_ID_GET_PIR_ALARM, 15 | channel_id: self.channel_id, 16 | msg_num: self.new_message_num(), 17 | response_code: 0, 18 | stream_type: 0, 19 | class: 0x6414, 20 | }, 21 | body: BcBody::ModernMsg(ModernMsg { 22 | extension: Some(Extension { 23 | channel_id: Some(self.channel_id), 24 | ..Default::default() 25 | }), 26 | payload: None, 27 | }), 28 | }; 29 | 30 | sub_get.send(get)?; 31 | let msg = sub_get.rx.recv_timeout(RX_TIMEOUT)?; 32 | 33 | if let BcBody::ModernMsg(ModernMsg { 34 | payload: 35 | Some(BcPayloads::BcXml(BcXml { 36 | rf_alarm_cfg: Some(pirstate), 37 | .. 38 | })), 39 | .. 40 | }) = msg.body 41 | { 42 | Ok(pirstate) 43 | } else { 44 | Err(Error::UnintelligibleReply { 45 | reply: msg, 46 | why: "Expected PirSate xml but it was not recieved", 47 | }) 48 | } 49 | } 50 | 51 | /// Set the PIR sensor using the [RfAlarmCfg] xml 52 | pub fn set_pirstate(&mut self, rf_alarm_cfg: RfAlarmCfg) -> Result<()> { 53 | let connection = self 54 | .connection 55 | .as_ref() 56 | .expect("Must be connected to get time"); 57 | let sub_set = connection.subscribe(MSG_ID_START_PIR_ALARM)?; 58 | 59 | let get = Bc { 60 | meta: BcMeta { 61 | msg_id: MSG_ID_START_PIR_ALARM, 62 | channel_id: self.channel_id, 63 | msg_num: self.new_message_num(), 64 | response_code: 0, 65 | stream_type: 0, 66 | class: 0x6414, 67 | }, 68 | body: BcBody::ModernMsg(ModernMsg { 69 | extension: Some(Extension { 70 | channel_id: Some(self.channel_id), 71 | ..Default::default() 72 | }), 73 | payload: Some(BcPayloads::BcXml(BcXml { 74 | rf_alarm_cfg: Some(rf_alarm_cfg), 75 | ..Default::default() 76 | })), 77 | }), 78 | }; 79 | 80 | sub_set.send(get)?; 81 | let msg = sub_set.rx.recv_timeout(RX_TIMEOUT)?; 82 | 83 | if let BcMeta { 84 | response_code: 200, .. 85 | } = msg.meta 86 | { 87 | Ok(()) 88 | } else { 89 | Err(Error::UnintelligibleReply { 90 | reply: msg, 91 | why: "The camera did not except the RfAlarmCfg xml", 92 | }) 93 | } 94 | } 95 | 96 | /// This is a convience function to control the PIR status 97 | /// True is on and false is off 98 | pub fn pir_set(&mut self, state: bool) -> Result<()> { 99 | let mut pir_state = self.get_pirstate()?; 100 | // println!("{:?}", pir_state); 101 | pir_state.enable = match state { 102 | true => 1, 103 | false => 0, 104 | }; 105 | self.set_pirstate(pir_state)?; 106 | Ok(()) 107 | } 108 | } 109 | 110 | /// Turn PIR ON or OFF 111 | pub enum PirState { 112 | /// Turn the PIR on 113 | On, 114 | /// Turn the PIR off 115 | Off, 116 | } 117 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/reboot.rs: -------------------------------------------------------------------------------- 1 | use super::{BcCamera, Error, Result, RX_TIMEOUT}; 2 | use crate::bc::model::*; 3 | 4 | impl BcCamera { 5 | /// Reboot the camera 6 | pub fn reboot(&self) -> Result<()> { 7 | let connection = self.connection.as_ref().expect("Must be connected to ping"); 8 | let sub = connection.subscribe(MSG_ID_REBOOT)?; 9 | 10 | let msg = Bc { 11 | meta: BcMeta { 12 | msg_id: MSG_ID_REBOOT, 13 | channel_id: self.channel_id, 14 | msg_num: self.new_message_num(), 15 | stream_type: 0, 16 | response_code: 0, 17 | class: 0x6414, 18 | }, 19 | body: BcBody::ModernMsg(ModernMsg { 20 | ..Default::default() 21 | }), 22 | }; 23 | 24 | sub.send(msg)?; 25 | let msg = sub.rx.recv_timeout(RX_TIMEOUT)?; 26 | 27 | if let BcMeta { 28 | response_code: 200, .. 29 | } = msg.meta 30 | { 31 | Ok(()) 32 | } else { 33 | Err(Error::UnintelligibleReply { 34 | reply: msg, 35 | why: "The camera did not accept the reboot command", 36 | }) 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/resolution.rs: -------------------------------------------------------------------------------- 1 | //! This is a helper module to resolve either to a UID or a SockerAddr 2 | 3 | use log::*; 4 | use std::{ 5 | io::Error, 6 | net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}, 7 | }; 8 | 9 | /// Used to return either the SocketAddr or the UID 10 | pub enum SocketAddrOrUid { 11 | /// When the result is a addr it will be this 12 | SocketAddr(SocketAddr), 13 | /// When the result is a UID 14 | Uid(String), 15 | } 16 | 17 | /// An extension of ToSocketAddrs that will also resolve to a camera UID 18 | pub trait ToSocketAddrsOrUid: ToSocketAddrs { 19 | /// The return type of the function 20 | type UidIter: Iterator; 21 | 22 | /// This handles the actual resolution. It should first check the 23 | /// normal [.to_socket_addrs()] and if that fails it should check 24 | /// if it looks like a uid 25 | fn to_socket_addrs_or_uid(&self) -> Result; 26 | } 27 | 28 | impl ToSocketAddrsOrUid for SocketAddr { 29 | type UidIter = std::vec::IntoIter; 30 | 31 | fn to_socket_addrs_or_uid(&self) -> Result { 32 | Ok(self 33 | .to_socket_addrs()? 34 | .map(SocketAddrOrUid::SocketAddr) 35 | .collect::>() 36 | .into_iter()) 37 | } 38 | } 39 | 40 | impl ToSocketAddrsOrUid for str { 41 | type UidIter = std::vec::IntoIter; 42 | 43 | fn to_socket_addrs_or_uid(&self) -> Result { 44 | match self.to_socket_addrs() { 45 | Ok(addrs) => Ok(addrs 46 | .map(SocketAddrOrUid::SocketAddr) 47 | .collect::>() 48 | .into_iter()), 49 | Err(e) => { 50 | debug!("Trying as uid"); 51 | let re = regex::Regex::new(r"^[0-9A-Za-z]+$").unwrap(); 52 | if re.is_match(self) { 53 | Ok(vec![SocketAddrOrUid::Uid(self.to_string())].into_iter()) 54 | } else { 55 | debug!("Regex fails {:?} => {:?} ", re, self); 56 | Err(e) 57 | } 58 | } 59 | } 60 | } 61 | } 62 | 63 | impl ToSocketAddrsOrUid for String { 64 | type UidIter = std::vec::IntoIter; 65 | 66 | fn to_socket_addrs_or_uid(&self) -> Result { 67 | match self.to_socket_addrs() { 68 | Ok(addrs) => Ok(addrs 69 | .map(SocketAddrOrUid::SocketAddr) 70 | .collect::>() 71 | .into_iter()), 72 | Err(e) => { 73 | debug!("Trying as uid"); 74 | let re = regex::Regex::new(r"^[0-9A-Za-z]+$").unwrap(); 75 | if re.is_match(self) { 76 | Ok(vec![SocketAddrOrUid::Uid(self.to_string())].into_iter()) 77 | } else { 78 | debug!("Regex fails {:?} => {:?} ", re, self); 79 | Err(e) 80 | } 81 | } 82 | } 83 | } 84 | } 85 | 86 | impl ToSocketAddrsOrUid for (&str, u16) { 87 | type UidIter = std::vec::IntoIter; 88 | 89 | fn to_socket_addrs_or_uid(&self) -> Result { 90 | Ok(self 91 | .to_socket_addrs()? 92 | .map(SocketAddrOrUid::SocketAddr) 93 | .collect::>() 94 | .into_iter()) 95 | } 96 | } 97 | 98 | impl ToSocketAddrsOrUid for (IpAddr, u16) { 99 | type UidIter = std::vec::IntoIter; 100 | 101 | fn to_socket_addrs_or_uid(&self) -> Result { 102 | Ok(self 103 | .to_socket_addrs()? 104 | .map(SocketAddrOrUid::SocketAddr) 105 | .collect::>() 106 | .into_iter()) 107 | } 108 | } 109 | 110 | impl ToSocketAddrsOrUid for (String, u16) { 111 | type UidIter = std::vec::IntoIter; 112 | 113 | fn to_socket_addrs_or_uid(&self) -> Result { 114 | Ok(self 115 | .to_socket_addrs()? 116 | .map(SocketAddrOrUid::SocketAddr) 117 | .collect::>() 118 | .into_iter()) 119 | } 120 | } 121 | 122 | impl ToSocketAddrsOrUid for (Ipv4Addr, u16) { 123 | type UidIter = std::vec::IntoIter; 124 | 125 | fn to_socket_addrs_or_uid(&self) -> Result { 126 | Ok(self 127 | .to_socket_addrs()? 128 | .map(SocketAddrOrUid::SocketAddr) 129 | .collect::>() 130 | .into_iter()) 131 | } 132 | } 133 | 134 | impl ToSocketAddrsOrUid for (Ipv6Addr, u16) { 135 | type UidIter = std::vec::IntoIter; 136 | 137 | fn to_socket_addrs_or_uid(&self) -> Result { 138 | Ok(self 139 | .to_socket_addrs()? 140 | .map(SocketAddrOrUid::SocketAddr) 141 | .collect::>() 142 | .into_iter()) 143 | } 144 | } 145 | 146 | impl ToSocketAddrsOrUid for SocketAddrV4 { 147 | type UidIter = std::vec::IntoIter; 148 | 149 | fn to_socket_addrs_or_uid(&self) -> Result { 150 | Ok(self 151 | .to_socket_addrs()? 152 | .map(SocketAddrOrUid::SocketAddr) 153 | .collect::>() 154 | .into_iter()) 155 | } 156 | } 157 | 158 | impl ToSocketAddrsOrUid for SocketAddrV6 { 159 | type UidIter = std::vec::IntoIter; 160 | 161 | fn to_socket_addrs_or_uid(&self) -> Result { 162 | Ok(self 163 | .to_socket_addrs()? 164 | .map(SocketAddrOrUid::SocketAddr) 165 | .collect::>() 166 | .into_iter()) 167 | } 168 | } 169 | 170 | impl<'a> ToSocketAddrsOrUid for &'a [SocketAddr] { 171 | type UidIter = std::vec::IntoIter; 172 | 173 | fn to_socket_addrs_or_uid(&self) -> Result { 174 | Ok(self 175 | .to_socket_addrs()? 176 | .map(SocketAddrOrUid::SocketAddr) 177 | .collect::>() 178 | .into_iter()) 179 | } 180 | } 181 | 182 | impl ToSocketAddrsOrUid for &T { 183 | type UidIter = T::UidIter; 184 | fn to_socket_addrs_or_uid(&self) -> Result { 185 | (&**self).to_socket_addrs_or_uid() 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/stream.rs: -------------------------------------------------------------------------------- 1 | use super::{BcCamera, BinarySubscriber, Result}; 2 | use crate::{ 3 | bc::{model::*, xml::*}, 4 | bcmedia::model::*, 5 | }; 6 | 7 | /// Convience type for the error raised by the [StreamOutput] trait 8 | pub type StreamOutputError = Result; 9 | 10 | /// The method [`BcCamera::start_video()`] requires a structure with this trait to pass the 11 | /// audio and video data back to 12 | pub trait StreamOutput { 13 | /// This is the callback raised a complete media packet is received 14 | /// 15 | /// If result is `Ok(true)` more messages will be sent 16 | /// 17 | /// If result if `Ok(false)` then message will be stopped 18 | /// 19 | /// If result is `Err(E)` then messages be stopped 20 | /// and an error will be thrown 21 | fn stream_recv(&mut self, media: BcMedia) -> StreamOutputError; 22 | } 23 | 24 | /// The stream names supported by BC 25 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] 26 | pub enum Stream { 27 | /// This is the HD stream 28 | Main, 29 | /// This is the SD stream 30 | Sub, 31 | /// This stream represents a balance between SD and HD 32 | /// 33 | /// It is only avaliable on some camera. If the camera dosen't 34 | /// support it the stream will be the same as the SD stream 35 | Extern, 36 | } 37 | 38 | impl BcCamera { 39 | /// 40 | /// Starts the video stream 41 | /// 42 | /// # Parameters 43 | /// 44 | /// * `data_outs` - This should be a struct that implements the [`StreamOutput`] trait 45 | /// 46 | /// * `stream_name` - This is a [`Stream`] that controls the stream to request from the camera. 47 | /// Selecting [`Stream::Main`] will select the HD stream. 48 | /// Selecting [`Stream::Sub`] will select the SD stream. 49 | /// Selecting [`Stream::Extern`] will select the medium quality stream (only on some camera) 50 | /// 51 | /// # Returns 52 | /// 53 | /// This will block forever or return an error when the camera connection is dropped 54 | /// 55 | pub fn start_video(&self, data_outs: &mut Outputs, stream: Stream) -> Result<()> 56 | where 57 | Outputs: StreamOutput, 58 | { 59 | let connection = self 60 | .connection 61 | .as_ref() 62 | .expect("Must be connected to start video"); 63 | let sub_video = connection.subscribe(MSG_ID_VIDEO)?; 64 | 65 | // On an E1 and swann cameras: 66 | // - mainStream always has a value of 0 67 | // - subStream always has a value of 1 68 | // - There is no externStram 69 | // On a B800: 70 | // - mainStream is 0 71 | // - subStream is 0 72 | // - externStream is 0 73 | let stream_code = match stream { 74 | Stream::Main => 0, 75 | Stream::Sub => 1, 76 | Stream::Extern => 0, 77 | }; 78 | 79 | // Theses are the numbers used with the offical client 80 | // On an E1 and swann cameras: 81 | // - mainStream always has a value of 0 82 | // - subStream always has a value of 1 83 | // - There is no externStram 84 | // On a B800: 85 | // - mainStream is 0 86 | // - subStream is 256 87 | // - externStram is 1024 88 | let handle = match stream { 89 | Stream::Main => 0, 90 | Stream::Sub => 256, 91 | Stream::Extern => 1024, 92 | }; 93 | 94 | let stream_name = match stream { 95 | Stream::Main => "mainStream", 96 | Stream::Sub => "subStream", 97 | Stream::Extern => "externStream", 98 | } 99 | .to_string(); 100 | 101 | let start_video = Bc::new_from_xml( 102 | BcMeta { 103 | msg_id: MSG_ID_VIDEO, 104 | channel_id: self.channel_id, 105 | msg_num: self.new_message_num(), 106 | stream_type: stream_code, 107 | response_code: 0, 108 | class: 0x6414, // IDK why 109 | }, 110 | BcXml { 111 | preview: Some(Preview { 112 | version: xml_ver(), 113 | channel_id: self.channel_id, 114 | handle, 115 | stream_type: stream_name, 116 | }), 117 | ..Default::default() 118 | }, 119 | ); 120 | 121 | sub_video.send(start_video)?; 122 | 123 | let mut media_sub = BinarySubscriber::from_bc_sub(&sub_video); 124 | 125 | loop { 126 | let bc_media = BcMedia::deserialize(&mut media_sub)?; 127 | // We now have a complete interesting packet. Send it to on the callback 128 | match data_outs.stream_recv(bc_media) { 129 | Ok(true) => {} 130 | Ok(false) => return Ok(()), 131 | Err(e) => return Err(e), 132 | }; 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/time.rs: -------------------------------------------------------------------------------- 1 | use super::{BcCamera, Error, Result, RX_TIMEOUT}; 2 | use crate::bc::{model::*, xml::*}; 3 | use time::{date, Date, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset}; 4 | 5 | impl BcCamera { 6 | /// 7 | /// Get the time from the camera 8 | /// 9 | /// # Returns 10 | /// 11 | /// returns either an error or an option with the offsetted date time 12 | /// 13 | pub fn get_time(&self) -> Result> { 14 | let connection = self 15 | .connection 16 | .as_ref() 17 | .expect("Must be connected to get time"); 18 | let sub_get_general = connection.subscribe(MSG_ID_GET_GENERAL)?; 19 | let get = Bc { 20 | meta: BcMeta { 21 | msg_id: MSG_ID_GET_GENERAL, 22 | channel_id: self.channel_id, 23 | msg_num: self.new_message_num(), 24 | response_code: 0, 25 | stream_type: 0, 26 | class: 0x6414, 27 | }, 28 | body: BcBody::ModernMsg(ModernMsg::default()), 29 | }; 30 | 31 | sub_get_general.send(get)?; 32 | let msg = sub_get_general.rx.recv_timeout(RX_TIMEOUT)?; 33 | 34 | if let BcBody::ModernMsg(ModernMsg { 35 | payload: 36 | Some(BcPayloads::BcXml(BcXml { 37 | system_general: 38 | Some(SystemGeneral { 39 | time_zone: Some(time_zone), 40 | year: Some(year), 41 | month: Some(month), 42 | day: Some(day), 43 | hour: Some(hour), 44 | minute: Some(minute), 45 | second: Some(second), 46 | .. 47 | }), 48 | .. 49 | })), 50 | .. 51 | }) = msg.body 52 | { 53 | let datetime = 54 | match try_build_timestamp(time_zone, year, month, day, hour, minute, second) { 55 | Ok(dt) => dt, 56 | Err(_) => { 57 | return Err(Error::UnintelligibleReply { 58 | reply: msg, 59 | why: "Could not parse date", 60 | }) 61 | } 62 | }; 63 | 64 | // This code was written in 2020; I'm trying to catch all the possible epochs that 65 | // cameras might reset themselves to. My B800 resets to Jan 1, 1999, but I can't 66 | // guarantee that Reolink won't pick some newer date. Therefore, last year ought 67 | // to be new enough, yet still distant enough that it won't interfere with anything 68 | const BOUNDARY: Date = date!(2019 - 01 - 01); 69 | 70 | // detect if no time is actually set, and return Ok(None): that is, operation 71 | // succeeded, and there is no time set 72 | if datetime.date() < BOUNDARY { 73 | Ok(None) 74 | } else { 75 | Ok(Some(datetime)) 76 | } 77 | } else { 78 | Err(Error::UnintelligibleReply { 79 | reply: msg, 80 | why: "Reply did not contain SystemGeneral with all time fields filled out", 81 | }) 82 | } 83 | } 84 | 85 | /// 86 | /// Sets the time of the camera 87 | /// 88 | /// # Parameters 89 | /// 90 | /// * `timestamp` - The time to set the camera to 91 | /// 92 | /// # Returns 93 | /// 94 | /// returns Ok(()) or error 95 | /// 96 | pub fn set_time(&self, timestamp: OffsetDateTime) -> Result<()> { 97 | let connection = self 98 | .connection 99 | .as_ref() 100 | .expect("Must be connected to set time"); 101 | let sub_set_general = connection.subscribe(MSG_ID_SET_GENERAL)?; 102 | let set = Bc::new_from_xml( 103 | BcMeta { 104 | msg_id: MSG_ID_SET_GENERAL, 105 | channel_id: self.channel_id, 106 | msg_num: self.new_message_num(), 107 | response_code: 0, 108 | stream_type: 0, 109 | class: 0x6414, 110 | }, 111 | BcXml { 112 | system_general: Some(SystemGeneral { 113 | version: xml_ver(), 114 | //osd_format: Some("MDY".to_string()), 115 | time_format: Some(0), 116 | // Reolink uses positive seconds to indicate a negative UTC offset: 117 | time_zone: Some(-timestamp.offset().as_seconds()), 118 | year: Some(timestamp.year()), 119 | month: Some(timestamp.month()), 120 | day: Some(timestamp.day()), 121 | hour: Some(timestamp.hour()), 122 | minute: Some(timestamp.minute()), 123 | second: Some(timestamp.second()), 124 | ..Default::default() 125 | }), 126 | ..Default::default() 127 | }, 128 | ); 129 | 130 | sub_set_general.send(set)?; 131 | let _ = sub_set_general.rx.recv_timeout(RX_TIMEOUT)?; 132 | 133 | Ok(()) 134 | } 135 | } 136 | 137 | fn try_build_timestamp( 138 | timezone: i32, 139 | year: i32, 140 | month: u8, 141 | day: u8, 142 | hour: u8, 143 | minute: u8, 144 | second: u8, 145 | ) -> std::result::Result { 146 | let date = Date::try_from_ymd(year, month, day)?; 147 | let time = Time::try_from_hms(hour, minute, second)?; 148 | let offset = if timezone > 0 { 149 | UtcOffset::west_seconds(timezone as u32) 150 | } else { 151 | UtcOffset::east_seconds(-timezone as u32) 152 | }; 153 | 154 | Ok(PrimitiveDateTime::new(date, time).assume_offset(offset)) 155 | } 156 | -------------------------------------------------------------------------------- /crates/core/src/bc_protocol/version.rs: -------------------------------------------------------------------------------- 1 | use super::{BcCamera, Error, Result, RX_TIMEOUT}; 2 | use crate::bc::{model::*, xml::*}; 3 | 4 | impl BcCamera { 5 | /// Request the [VersionInfo] xml 6 | pub fn version(&self) -> Result { 7 | let connection = self 8 | .connection 9 | .as_ref() 10 | .expect("Must be connected to get version info"); 11 | let sub_version = connection.subscribe(MSG_ID_VERSION)?; 12 | 13 | let version = Bc { 14 | meta: BcMeta { 15 | msg_id: MSG_ID_VERSION, 16 | channel_id: self.channel_id, 17 | msg_num: self.new_message_num(), 18 | stream_type: 0, 19 | response_code: 0, 20 | class: 0x6414, // IDK why 21 | }, 22 | body: BcBody::ModernMsg(ModernMsg { 23 | ..Default::default() 24 | }), 25 | }; 26 | 27 | sub_version.send(version)?; 28 | 29 | let modern_reply = sub_version.rx.recv_timeout(RX_TIMEOUT)?; 30 | let version_info; 31 | match modern_reply.body { 32 | BcBody::ModernMsg(ModernMsg { 33 | payload: 34 | Some(BcPayloads::BcXml(BcXml { 35 | version_info: Some(info), 36 | .. 37 | })), 38 | .. 39 | }) => { 40 | version_info = info; 41 | } 42 | _ => { 43 | return Err(Error::UnintelligibleReply { 44 | reply: modern_reply, 45 | why: "Expected a VersionInfo message", 46 | }) 47 | } 48 | } 49 | 50 | Ok(version_info) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /crates/core/src/bcmedia/mod.rs: -------------------------------------------------------------------------------- 1 | /// Deserlizer for BCMedia 2 | pub mod de; 3 | /// Structure model for BCMedia 4 | pub mod model; 5 | /// Serlizer for BCMedia 6 | pub mod ser; 7 | -------------------------------------------------------------------------------- /crates/core/src/bcmedia/model.rs: -------------------------------------------------------------------------------- 1 | /// Video streams encapsulate a stream of BcMedia 2 | #[derive(Debug)] 3 | pub enum BcMedia { 4 | /// Holds info on the stream 5 | InfoV1(BcMediaInfoV1), 6 | /// Holds info on the stream 7 | InfoV2(BcMediaInfoV2), 8 | /// Holds an IFrame either H264 or H265 9 | Iframe(BcMediaIframe), 10 | /// Holds a PFrame either H264 or H265 11 | Pframe(BcMediaPframe), 12 | /// Holds AAC audio 13 | Aac(BcMediaAac), 14 | /// Holds ADPCM audio 15 | Adpcm(BcMediaAdpcm), 16 | } 17 | // 18 | pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V1: u32 = 0x31303031; 19 | 20 | /// The start of a BcMedia stream contains this message 21 | /// which describes the data to follow 22 | #[derive(Debug)] 23 | pub struct BcMediaInfoV1 { 24 | // This is the size of the header so it's actually a fixed value 25 | // The other messages have body size here so maybe that's why 26 | // it's included 27 | // pub header_size: u32, 28 | /// Width of the video 29 | pub video_width: u32, 30 | /// Height of the video 31 | pub video_height: u32, 32 | // pub unknown: u8, 33 | /// Frames per second. On older cameras this seems to be an index of the FPS on a lookup table 34 | pub fps: u8, 35 | /// Start year of the stream 36 | pub start_year: u8, 37 | /// Start month of the stream 38 | pub start_month: u8, 39 | /// Start day of the stream 40 | pub start_day: u8, 41 | /// Start hour of the stream 42 | pub start_hour: u8, 43 | /// Start minute of the stream 44 | pub start_min: u8, 45 | /// Start seconds of the stream 46 | pub start_seconds: u8, 47 | /// End year of the video probably only useful for the recorded files on the SD card 48 | pub end_year: u8, 49 | /// End month of the video probably only useful for the recorded files on the SD card 50 | pub end_month: u8, 51 | /// End day of the video probably only useful for the recorded files on the SD card 52 | pub end_day: u8, 53 | /// End hour of the video probably only useful for the recorded files on the SD card 54 | pub end_hour: u8, 55 | /// End min of the video probably only useful for the recorded files on the SD card 56 | pub end_min: u8, 57 | /// End seconds of the video probably only useful for the recorded files on the SD card 58 | pub end_seconds: u8, 59 | // unknown: u16 60 | } 61 | // 62 | pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V2: u32 = 0x32303031; 63 | 64 | /// The start of a BcMedia stream contains this message 65 | /// which describes the data to follow 66 | #[derive(Debug)] 67 | pub struct BcMediaInfoV2 { 68 | // This is the size of the header so it's actually a fixed value 69 | // The other messages have body size here so maybe that's why 70 | // it's included 71 | // pub header_size: u32, 72 | /// Width of the video 73 | pub video_width: u32, 74 | /// Height of the video 75 | pub video_height: u32, 76 | // pub unknown: u8, 77 | /// Frames per second. On older cameras this seems to be an index of the FPS on a lookup table 78 | pub fps: u8, 79 | /// Start year of the stream 80 | pub start_year: u8, 81 | /// Start month of the stream 82 | pub start_month: u8, 83 | /// Start day of the stream 84 | pub start_day: u8, 85 | /// Start hour of the stream 86 | pub start_hour: u8, 87 | /// Start minute of the stream 88 | pub start_min: u8, 89 | /// Start seconds of the stream 90 | pub start_seconds: u8, 91 | /// End year of the video probably only useful for the recorded files on the SD card 92 | pub end_year: u8, 93 | /// End month of the video probably only useful for the recorded files on the SD card 94 | pub end_month: u8, 95 | /// End day of the video probably only useful for the recorded files on the SD card 96 | pub end_day: u8, 97 | /// End hour of the video probably only useful for the recorded files on the SD card 98 | pub end_hour: u8, 99 | /// End min of the video probably only useful for the recorded files on the SD card 100 | pub end_min: u8, 101 | /// End seconds of the video probably only useful for the recorded files on the SD card 102 | pub end_seconds: u8, 103 | // unknown: u16 104 | } 105 | 106 | // IFrame magics include the channel number in them 107 | pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME: u32 = 0x63643030; 108 | pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME_LAST: u32 = 0x63643039; 109 | 110 | /// Video Types for I/PFrame 111 | #[derive(Debug)] 112 | pub enum VideoType { 113 | /// H264 video data 114 | H264, 115 | /// H265 video data 116 | H265, 117 | } 118 | 119 | /// This is a BcMedia video IFrame. 120 | #[derive(Debug)] 121 | pub struct BcMediaIframe { 122 | /// "H264", or "H265" 123 | pub video_type: VideoType, 124 | // Size of payload after header in bytes 125 | // pub payload_size: u32, 126 | // unknown: u32, // NVR channel count? Known values 1-00/08 2-00 3-00 4-00 127 | /// Timestamp in microseconds 128 | pub microseconds: u32, 129 | // unknown: u32, // Known values 1-00/23/5A 2-00 3-00 4-00 130 | /// POSIX time (seconds since 00:00:00 Jan 1 1970) 131 | pub time: Option, 132 | //unknown: u32, // Known values 1-00/06/29 2-00/01 3-00/C3 4-00 133 | /// Raw IFrame data 134 | pub data: Vec, 135 | } 136 | 137 | // PFrame magics include the channel number in them 138 | pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME: u32 = 0x63643130; 139 | pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME_LAST: u32 = 0x63643139; 140 | 141 | /// This is a BcMedia video PFrame. 142 | #[derive(Debug)] 143 | pub struct BcMediaPframe { 144 | /// "H264", or "H265" 145 | pub video_type: VideoType, 146 | // Size of payload after header in bytes 147 | // pub payload_size: u32, 148 | // unknown: u32, // NVR channel count? Known values 1-00/08 2-00 3-00 4-00 149 | /// Timestamp in microseconds 150 | pub microseconds: u32, 151 | // unknown: u32, // Known values 1-00/23/5A 2-00 3-00 4-00 152 | /// Raw PFrame data 153 | pub data: Vec, 154 | } 155 | 156 | pub(super) const MAGIC_HEADER_BCMEDIA_AAC: u32 = 0x62773530; 157 | 158 | /// This contains BcMedia audio data in AAC format 159 | #[derive(Debug)] 160 | pub struct BcMediaAac { 161 | // Size of payload after header in bytes 162 | // pub payload_size: u16, 163 | // Size of payload after header in bytes exactly the same as before 164 | // pub payload_size_b: u16, 165 | /// Raw AAC data 166 | pub data: Vec, 167 | } 168 | 169 | pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM: u32 = 0x62773130; 170 | 171 | pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM_DATA: u16 = 0x0100; 172 | 173 | /// This contains BcMedia audio data in ADPCM format 174 | #[derive(Debug)] 175 | pub struct BcMediaAdpcm { 176 | // Size of payload after header in bytes 177 | // pub payload_size: u16, 178 | // Size of payload after header in bytes exactly the same as before 179 | // pub payload_size_b: u16, 180 | // more_magic: MAGIC_HEADER_BCMEDIA_ADPCM_DATA 181 | // Adpcm sample_block_size in bytes 182 | // 183 | // These bytes (and the MAGIC_HEADER_BCMEDIA_ADPCM_DATA) are included as 184 | // part of the payload_size. It may be more prudent to sealise them to 185 | // another structure. 186 | // pub sample_block_size: u16, 187 | /// The raw adpcm data in DVI-4 layout. 188 | /// 189 | /// One `data` should contain 4 bytes of the adpcm predictor state then one block 190 | /// of adpcm samples 191 | /// 192 | /// To calculate the block-align size simply remove 4 from the `len()` 193 | pub data: Vec, 194 | } 195 | -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/adpcm_0.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/adpcm_0.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_iframe_0.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_iframe_0.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_iframe_1.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_iframe_1.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_iframe_2.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_iframe_2.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_iframe_3.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_iframe_3.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_iframe_4.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_iframe_4.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_0.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_0.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_1.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_1.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_10.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_10.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_11.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_11.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_12.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_12.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_13.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_13.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_14.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_14.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_15.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_15.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_16.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_16.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_17.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_17.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_2.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_2.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_3.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_3.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_4.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_4.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_5.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_5.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_6.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_6.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_7.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_7.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_8.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_8.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/argus2_pframe_9.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/argus2_pframe_9.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/iframe_0.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/iframe_0.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/iframe_1.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/iframe_1.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/iframe_2.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/iframe_2.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/iframe_3.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/iframe_3.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/iframe_4.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/iframe_4.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/info_v1.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/info_v1.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/pframe_0.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/pframe_0.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/pframe_1.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/pframe_1.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/video_stream_swan_00.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/video_stream_swan_00.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/video_stream_swan_01.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/video_stream_swan_01.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/video_stream_swan_02.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/video_stream_swan_02.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/video_stream_swan_03.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/video_stream_swan_03.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/video_stream_swan_04.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/video_stream_swan_04.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/video_stream_swan_05.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/video_stream_swan_05.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/video_stream_swan_06.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/video_stream_swan_06.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/video_stream_swan_07.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/video_stream_swan_07.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/video_stream_swan_08.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/video_stream_swan_08.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/samples/video_stream_swan_09.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcmedia/samples/video_stream_swan_09.raw -------------------------------------------------------------------------------- /crates/core/src/bcmedia/ser.rs: -------------------------------------------------------------------------------- 1 | use super::model::*; 2 | use cookie_factory::bytes::*; 3 | use cookie_factory::sequence::tuple; 4 | use cookie_factory::{combinator::*, gen}; 5 | use cookie_factory::{GenError, SerializeFn}; 6 | use err_derive::Error; 7 | use log::error; 8 | use std::io::Write; 9 | 10 | // PAD_SIZE: Media packets use 8 byte padding 11 | const PAD_SIZE: u32 = 8; 12 | 13 | /// The error types used during serialisation 14 | #[derive(Debug, Error)] 15 | pub enum Error { 16 | /// A Cookie Factor GenError 17 | #[error(display = "Cookie GenError")] 18 | GenError(#[error(source)] GenError), 19 | } 20 | 21 | impl BcMedia { 22 | pub(crate) fn serialize(&self, buf: W) -> Result { 23 | let (buf, _) = match &self { 24 | BcMedia::InfoV1(payload) => gen(bcmedia_info_v1(payload), buf)?, 25 | BcMedia::InfoV2(payload) => gen(bcmedia_info_v2(payload), buf)?, 26 | BcMedia::Iframe(payload) => { 27 | let pad_size = match payload.data.len() as u32 % PAD_SIZE { 28 | 0 => 0, 29 | n => PAD_SIZE - n, 30 | }; 31 | gen( 32 | tuple(( 33 | bcmedia_iframe(payload), 34 | slice(&payload.data), 35 | slice(&vec![0; pad_size as usize]), 36 | )), 37 | buf, 38 | )? 39 | } 40 | BcMedia::Pframe(payload) => { 41 | let pad_size = match payload.data.len() as u32 % PAD_SIZE { 42 | 0 => 0, 43 | n => PAD_SIZE - n, 44 | }; 45 | gen( 46 | tuple(( 47 | bcmedia_pframe(payload), 48 | slice(&payload.data), 49 | slice(&vec![0; pad_size as usize]), 50 | )), 51 | buf, 52 | )? 53 | } 54 | BcMedia::Aac(payload) => { 55 | let pad_size = match payload.data.len() as u32 % PAD_SIZE { 56 | 0 => 0, 57 | n => PAD_SIZE - n, 58 | }; 59 | gen( 60 | tuple(( 61 | bcmedia_aac(payload), 62 | slice(&payload.data), 63 | slice(&vec![0; pad_size as usize]), 64 | )), 65 | buf, 66 | )? 67 | } 68 | BcMedia::Adpcm(payload) => { 69 | let pad_size = match payload.data.len() as u32 % PAD_SIZE { 70 | 0 => 0, 71 | n => PAD_SIZE - n, 72 | }; 73 | gen( 74 | tuple(( 75 | bcmedia_adpcm(payload), 76 | slice(&payload.data), 77 | slice(&vec![0; pad_size as usize]), 78 | )), 79 | buf, 80 | )? 81 | } 82 | }; 83 | 84 | Ok(buf) 85 | } 86 | } 87 | 88 | fn bcmedia_info_v1(payload: &BcMediaInfoV1) -> impl SerializeFn { 89 | tuple(( 90 | le_u32(MAGIC_HEADER_BCMEDIA_INFO_V1), 91 | le_u32(32), 92 | le_u32(payload.video_width), 93 | le_u32(payload.video_height), 94 | le_u8(0), // unknown. Known values 00/01 95 | le_u8(payload.fps), 96 | le_u8(payload.start_year), 97 | le_u8(payload.start_month), 98 | le_u8(payload.start_day), 99 | le_u8(payload.start_hour), 100 | le_u8(payload.start_min), 101 | le_u8(payload.start_seconds), 102 | le_u8(payload.end_year), 103 | le_u8(payload.end_month), 104 | le_u8(payload.end_day), 105 | le_u8(payload.end_hour), 106 | le_u8(payload.end_min), 107 | le_u8(payload.end_seconds), 108 | le_u8(0), 109 | le_u8(0), 110 | )) 111 | } 112 | 113 | fn bcmedia_info_v2(payload: &BcMediaInfoV2) -> impl SerializeFn { 114 | tuple(( 115 | le_u32(MAGIC_HEADER_BCMEDIA_INFO_V2), 116 | le_u32(32), 117 | le_u32(payload.video_width), 118 | le_u32(payload.video_height), 119 | le_u8(0), // unknown. Known values 00/01 120 | le_u8(payload.fps), 121 | le_u8(payload.start_year), 122 | le_u8(payload.start_month), 123 | le_u8(payload.start_day), 124 | le_u8(payload.start_hour), 125 | le_u8(payload.start_min), 126 | le_u8(payload.start_seconds), 127 | le_u8(payload.end_year), 128 | le_u8(payload.end_month), 129 | le_u8(payload.end_day), 130 | le_u8(payload.end_hour), 131 | le_u8(payload.end_min), 132 | le_u8(payload.end_seconds), 133 | le_u8(0), 134 | le_u8(0), 135 | )) 136 | } 137 | 138 | fn bcmedia_iframe(payload: &BcMediaIframe) -> impl SerializeFn { 139 | // Cookie String needs a static lifetime 140 | let vid_string = match payload.video_type { 141 | VideoType::H264 => "H264", 142 | VideoType::H265 => "H265", 143 | }; 144 | let (extra_header, extra_header_size) = if let Some(payload_time) = payload.time { 145 | let extra_header = slice( 146 | gen(tuple((le_u32(payload_time), le_u32(0))), vec![]) 147 | .unwrap() 148 | .0, 149 | ); 150 | let extra_header_size = 8; 151 | (extra_header, extra_header_size) 152 | } else { 153 | let extra_header = slice(vec![]); 154 | let extra_header_size = 0; 155 | (extra_header, extra_header_size) 156 | }; 157 | tuple(( 158 | le_u32(MAGIC_HEADER_BCMEDIA_IFRAME), 159 | string(vid_string), 160 | le_u32(payload.data.len() as u32), 161 | le_u32(extra_header_size), // unknown. NVR channel count? Known values 1-00/08 2-00 3-00 4-00 162 | le_u32(payload.microseconds), 163 | le_u32(0), // unknown. Known values 1-00/23/5A 2-00 3-00 4-00 164 | extra_header, 165 | )) 166 | } 167 | 168 | fn bcmedia_pframe(payload: &BcMediaPframe) -> impl SerializeFn { 169 | // Cookie String needs a static lifetime 170 | let vid_string = match payload.video_type { 171 | VideoType::H264 => "H264", 172 | VideoType::H265 => "H265", 173 | }; 174 | tuple(( 175 | le_u32(MAGIC_HEADER_BCMEDIA_PFRAME), 176 | string(vid_string), 177 | le_u32(payload.data.len() as u32), 178 | le_u32(0), // unknown. NVR channel count? Known values 1-00/08 2-00 3-00 4-00 179 | le_u32(payload.microseconds), 180 | le_u32(0), // unknown. Known values 1-00/23/5A 2-00 3-00 4-00 181 | )) 182 | } 183 | 184 | fn bcmedia_aac(payload: &BcMediaAac) -> impl SerializeFn { 185 | tuple(( 186 | le_u32(MAGIC_HEADER_BCMEDIA_AAC), 187 | le_u16(payload.data.len() as u16), 188 | le_u16(payload.data.len() as u16), 189 | )) 190 | } 191 | 192 | fn bcmedia_adpcm(payload: &BcMediaAdpcm) -> impl SerializeFn { 193 | tuple(( 194 | le_u32(MAGIC_HEADER_BCMEDIA_ADPCM), 195 | le_u16((payload.data.len() + 4) as u16), // Payload + 2 byte magic + 2byte block size 196 | le_u16((payload.data.len() + 4) as u16), // Payload + 2 byte magic + 2byte block size 197 | le_u16(MAGIC_HEADER_BCMEDIA_ADPCM_DATA), // magic 198 | le_u16(((payload.data.len() - 4) / 2) as u16), // Block size without the header halved 199 | )) 200 | } 201 | -------------------------------------------------------------------------------- /crates/core/src/bcudp/crc.rs: -------------------------------------------------------------------------------- 1 | use crc32fast::Hasher; 2 | 3 | pub(crate) fn calc_crc(payload: &[u8]) -> u32 { 4 | // Bc uses a non standard crc. 5 | // 6 | // It uses the polynomial 0x04c11db7 7 | // It uses the inital value or 0x00000000 8 | // It uses the xorout of 0x00000000 9 | // 10 | // The crc32fast has an odd behavior were it bitwise negates 11 | // the initial value before the loop. In order to have 12 | // an effective initial value of 0x00000000 we need to provide 13 | // the value 0xffffffff 14 | let mut hasher = Hasher::new_with_initial(0xffffffff); 15 | hasher.update(payload); 16 | // crc32fast uses the algorithm CRC-32/ISO-HDLC 17 | // This has an xorout of 0xffffffff 18 | // we must undo this xorout 19 | hasher.finalize() ^ 0xffffffff_u32 20 | } 21 | -------------------------------------------------------------------------------- /crates/core/src/bcudp/mod.rs: -------------------------------------------------------------------------------- 1 | //! This module contains the protocol for dealing with UDP. 2 | //! 3 | //! There are three types of packets 4 | //! 5 | //! - Discovery 6 | //! - Ack 7 | //! - Data 8 | //! 9 | //! --- 10 | //! 11 | //! **Discovery**: Deals with setting up the initial connection and including their 12 | //! connection IDs and the MTU 13 | //! 14 | //! --- 15 | //! 16 | //! **Ack**: Is sent after every packet is recieved 17 | //! 18 | //! --- 19 | //! 20 | //! **Data**: Contains a Bc packet payload. This is a stream and one Bc Packet may 21 | //! be split accross multiple UDP Data packets 22 | //! 23 | 24 | mod crc; 25 | /// Functions to deserialize udp packets 26 | pub mod de; 27 | /// Contains the model describing the top level structures 28 | pub mod model; 29 | /// Functions to serialize udp packets 30 | pub mod ser; 31 | /// Contains the udp related xml payloads 32 | pub mod xml; 33 | // Constains routines to de/encrypt udp xml 34 | mod xml_crypto; 35 | -------------------------------------------------------------------------------- /crates/core/src/bcudp/model.rs: -------------------------------------------------------------------------------- 1 | //! The BcUdp Model 2 | //! 3 | 4 | use super::xml::*; 5 | 6 | /// Top level udp packet 7 | #[derive(Debug, PartialEq, Eq)] 8 | pub enum BcUdp { 9 | /// Packet from the negotiate stage when connection info is exchanged 10 | Discovery(UdpDiscovery), 11 | /// Packet to acknowledge receipt of a data packet 12 | Ack(UdpAck), 13 | /// Packet containing the data (or part of the data) of a Bc packet 14 | Data(UdpData), 15 | } 16 | 17 | /// Magic for the UDP Discovery packet 18 | pub const MAGIC_HEADER_UDP_NEGO: u32 = 0x2a87cf3a; 19 | 20 | /// The Discovery packet is sent and received to init a connection 21 | #[derive(Debug, PartialEq, Eq)] 22 | pub struct UdpDiscovery { 23 | // The packet also contains these header fields not deserialized into this struct: 24 | // 4 Bytes Magic 25 | // 4 Byte payload size 26 | // 4 Bytes unknown always `01000000` 27 | /// The transmission id is unique to a message and used as an encryption key 28 | pub tid: u32, 29 | // The checksum of the payload 30 | // pub checksum: u32, 31 | /// The payload 32 | pub payload: UdpXml, 33 | } 34 | 35 | /// Magic for the UDP Ack packet 36 | pub const MAGIC_HEADER_UDP_ACK: u32 = 0x2a87cf20; 37 | 38 | /// Send to acknoledge a [`UdpData`] packet. If this is not sent then the camera will 39 | /// resend the packet 40 | #[derive(Debug, PartialEq, Eq)] 41 | pub struct UdpAck { 42 | /// The connection ID 43 | /// 44 | /// This is negotiated during [`UdpDiscovery`] as cid for the client and did for the camera 45 | /// 46 | /// When receiving from the camera it will be cid 47 | /// 48 | /// When sending to the camera it should be did 49 | /// 50 | /// We use i32 because when we send the connection id to the reolink 51 | /// register and then download the same connection id from the register_address 52 | /// it comes back in an xml that is encoded as i32 (i.e. can be negative string) 53 | pub connection_id: i32, 54 | // Unknown 4 bytes always 0 55 | /// The ID of the last data packet [`UdpData`] 56 | pub packet_id: u32, 57 | // 2 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000` 58 | // Unknown but seems to change randomly every second 59 | // 2 Bytes size of a payload 60 | // 61 | /// Payload of `00 01 01 01 01` where `01` is added after every repeat 62 | /// 63 | /// This is a truth table of packets after `packet_id` that have not been recieved 64 | pub payload: Vec, 65 | } 66 | 67 | /// Magic for the UDP Data packet 68 | pub const MAGIC_HEADER_UDP_DATA: u32 = 0x2a87cf10; 69 | 70 | /// Contains the data of a [`crate::bc::model::Bc`] packet 71 | #[derive(Debug, PartialEq, Eq)] 72 | pub struct UdpData { 73 | /// The connection ID of the other party 74 | /// 75 | /// This is negotiated during [`UdpDiscovery`] as cid for the client and did for the camera 76 | /// 77 | /// When receiving from the camera it will be cid 78 | /// 79 | /// When sending to the camera it should be did 80 | /// 81 | /// We use i32 because when we send the connection id to the reolink 82 | /// register and then download the same connection id from the register_address 83 | /// it comes back in an xml that is encoded as i32 (i.e. can be negative string) 84 | pub connection_id: i32, 85 | // Unknown 4 bytes always 0 86 | /// The ID of the data packet 87 | pub packet_id: u32, 88 | // Unknown 4 bytes always 0 89 | // 4 Byte payload size 90 | /// The payload 91 | pub payload: Vec, 92 | } 93 | -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_ack.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_ack.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_data.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_data.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_multi_0.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_multi_0.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_multi_1.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_multi_1.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_multi_2.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_multi_2.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_multi_3.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_multi_3.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_multi_4.bin: -------------------------------------------------------------------------------- 1 | χ*P -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_multi_5.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_multi_5.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_multi_6.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_multi_6.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_multi_7.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_multi_7.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_multi_8.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_multi_8.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_multi_9.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_multi_9.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_negotiate_camcfm.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_negotiate_camcfm.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_negotiate_camt.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_negotiate_camt.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_negotiate_clientt.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_negotiate_clientt.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/udp_negotiate_disc.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/udp_negotiate_disc.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/xml_crypto_sample1.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/crates/core/src/bcudp/samples/xml_crypto_sample1.bin -------------------------------------------------------------------------------- /crates/core/src/bcudp/samples/xml_crypto_sample1_plaintext.bin: -------------------------------------------------------------------------------- 1 | 2 | 3 | 62097899 4 | local 5 | 82000 6 | 80 7 | 8 | 9 | -------------------------------------------------------------------------------- /crates/core/src/bcudp/ser.rs: -------------------------------------------------------------------------------- 1 | use super::{crc::calc_crc, model::*, xml_crypto::encrypt}; 2 | use cookie_factory::bytes::*; 3 | use cookie_factory::sequence::tuple; 4 | use cookie_factory::{combinator::*, gen}; 5 | use cookie_factory::{GenError, SerializeFn}; 6 | use err_derive::Error; 7 | use log::error; 8 | use std::io::Write; 9 | 10 | /// The error types used during serialisation 11 | #[derive(Debug, Error)] 12 | pub enum Error { 13 | /// A Cookie Factor GenError 14 | #[error(display = "Cookie GenError")] 15 | GenError(#[error(source)] GenError), 16 | } 17 | 18 | impl BcUdp { 19 | pub(crate) fn serialize(&self, buf: W) -> Result { 20 | let (buf, _) = match &self { 21 | BcUdp::Discovery(payload) => { 22 | let xml_payload = encrypt(payload.tid, &payload.payload.serialize(vec![]).unwrap()); 23 | gen(bcudp_disc(payload, &xml_payload), buf)? 24 | } 25 | BcUdp::Ack(payload) => { 26 | let binary_payload = &payload.payload; 27 | gen(bcudp_ack(payload, binary_payload), buf)? 28 | } 29 | BcUdp::Data(payload) => { 30 | let binary_payload = &payload.payload; 31 | gen(bcudp_data(payload, binary_payload), buf)? 32 | } 33 | }; 34 | 35 | Ok(buf) 36 | } 37 | } 38 | 39 | fn bcudp_disc<'a, W: 'a + Write>( 40 | payload: &'a UdpDiscovery, 41 | xml_payload: &'a [u8], 42 | ) -> impl SerializeFn + 'a { 43 | let checksum = calc_crc(xml_payload); 44 | tuple(( 45 | le_u32(MAGIC_HEADER_UDP_NEGO), 46 | le_u32(xml_payload.len() as u32), 47 | le_u32(1), 48 | le_u32(payload.tid), 49 | le_u32(checksum), 50 | slice(xml_payload), 51 | )) 52 | } 53 | 54 | fn bcudp_ack<'a, W: 'a + Write>( 55 | payload: &'a UdpAck, 56 | binary_payload: &'a [u8], 57 | ) -> impl SerializeFn + 'a { 58 | tuple(( 59 | le_u32(MAGIC_HEADER_UDP_ACK), 60 | le_i32(payload.connection_id), 61 | le_u32(0), 62 | le_u32(0), 63 | le_u32(payload.packet_id), 64 | le_u32(0), 65 | le_u32(binary_payload.len() as u32), 66 | slice(binary_payload), 67 | )) 68 | } 69 | 70 | fn bcudp_data<'a, W: 'a + Write>( 71 | payload: &'a UdpData, 72 | binary_payload: &'a [u8], 73 | ) -> impl SerializeFn + 'a { 74 | tuple(( 75 | le_u32(MAGIC_HEADER_UDP_DATA), 76 | le_i32(payload.connection_id), 77 | le_u32(0), 78 | le_u32(payload.packet_id), 79 | le_u32(binary_payload.len() as u32), 80 | slice(binary_payload), 81 | )) 82 | } 83 | 84 | #[cfg(test)] 85 | mod tests { 86 | use crate::bcudp::model::*; 87 | use env_logger::Env; 88 | 89 | fn init() { 90 | let _ = env_logger::Builder::from_env(Env::default().default_filter_or("info")) 91 | .is_test(true) 92 | .try_init(); 93 | } 94 | 95 | #[test] 96 | // Tests the decoding of a UdpDiscovery with a discovery xml 97 | fn test_nego_disconnect() { 98 | init(); 99 | 100 | let sample = include_bytes!("samples/udp_negotiate_disc.bin"); 101 | 102 | let msg = BcUdp::deserialize(&sample[..]).unwrap(); 103 | let ser_buf = msg.serialize(vec![]).unwrap(); 104 | let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); 105 | assert_eq!(msg, msg2); 106 | // Raw samples don't quite match exactly 107 | // because the yaserde for xml puts spaces and new lines in different places 108 | // then the raw data from the camera so we skip this last assert 109 | //assert_eq!(&sample[..], ser_buf.as_slice()); 110 | } 111 | 112 | #[test] 113 | // Tests the decoding of a UdpDiscovery with a Camera Transmission xml 114 | fn test_nego_cam_transmission() { 115 | init(); 116 | 117 | let sample = include_bytes!("samples/udp_negotiate_camt.bin"); 118 | 119 | let msg = BcUdp::deserialize(&sample[..]).unwrap(); 120 | let ser_buf = msg.serialize(vec![]).unwrap(); 121 | let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); 122 | assert_eq!(msg, msg2); 123 | // Raw samples don't quite match exactly 124 | // because the yaserde for xml puts spaces and new lines in different places 125 | // then the raw data from the camera so we skip this last assert 126 | //assert_eq!(&sample[..], ser_buf.as_slice()); 127 | } 128 | 129 | #[test] 130 | // Tests the decoding of a UdpDiscovery with a Client Transmission xml 131 | fn test_nego_client_transmission() { 132 | init(); 133 | 134 | let sample = include_bytes!("samples/udp_negotiate_clientt.bin"); 135 | 136 | let msg = BcUdp::deserialize(&sample[..]).unwrap(); 137 | let ser_buf = msg.serialize(vec![]).unwrap(); 138 | let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); 139 | assert_eq!(msg, msg2); 140 | // Raw samples don't quite match exactly 141 | // because the yaserde for xml puts spaces and new lines in different places 142 | // then the raw data from the camera so we skip this last assert 143 | //assert_eq!(&sample[..], ser_buf.as_slice()); 144 | } 145 | 146 | #[test] 147 | // Tests the decoding of a UdpDiscovery with a Camera CFM xml 148 | fn test_nego_cfm() { 149 | init(); 150 | 151 | let sample = include_bytes!("samples/udp_negotiate_camcfm.bin"); 152 | 153 | let msg = BcUdp::deserialize(&sample[..]).unwrap(); 154 | let ser_buf = msg.serialize(vec![]).unwrap(); 155 | let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); 156 | assert_eq!(msg, msg2); 157 | // Raw samples don't quite match exactly 158 | // because the yaserde for xml puts spaces and new lines in different places 159 | // then the raw data from the camera so we skip this last assert 160 | //assert_eq!(&sample[..], ser_buf.as_slice()); 161 | } 162 | 163 | #[test] 164 | // Tests the decoding of an acknoledge packet 165 | fn test_ack() { 166 | init(); 167 | 168 | let sample = include_bytes!("samples/udp_ack.bin"); 169 | 170 | let msg = BcUdp::deserialize(&sample[..]).unwrap(); 171 | let ser_buf = msg.serialize(vec![]).unwrap(); 172 | let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); 173 | assert_eq!(msg, msg2); 174 | assert_eq!(&sample[..], ser_buf.as_slice()); 175 | } 176 | 177 | #[test] 178 | // Tests the decoding of an data packet 179 | fn test_data() { 180 | init(); 181 | 182 | let sample = include_bytes!("samples/udp_data.bin"); 183 | 184 | let msg = BcUdp::deserialize(&sample[..]).unwrap(); 185 | let ser_buf = msg.serialize(vec![]).unwrap(); 186 | let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); 187 | assert_eq!(msg, msg2); 188 | assert_eq!(&sample[..], ser_buf.as_slice()); 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /crates/core/src/bcudp/xml.rs: -------------------------------------------------------------------------------- 1 | // YaSerde currently macro-expands names like __type__value from type_ 2 | 3 | use std::io::{Read, Write}; 4 | // YaSerde is currently naming the traits and the derive macros identically 5 | use yaserde::{ser::Config, YaDeserialize, YaSerialize}; 6 | use yaserde_derive::{YaDeserialize, YaSerialize}; 7 | 8 | /// The top level of the UDP xml is P2P 9 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 10 | #[yaserde(rename = "P2P")] 11 | pub struct UdpXml { 12 | /// C2D_S xml Discovery of any client 13 | #[yaserde(rename = "C2D_S")] 14 | pub c2d_s: Option, 15 | /// C2D_S xml Discovery of client with a UID 16 | #[yaserde(rename = "C2D_C")] 17 | pub c2d_c: Option, 18 | /// D2C_C_C xml Reply from discovery 19 | #[yaserde(rename = "D2C_C_R")] 20 | pub d2c_c_r: Option, 21 | /// D2C_T xml 22 | #[yaserde(rename = "D2C_T")] 23 | pub d2c_t: Option, 24 | /// C2D_T xml 25 | #[yaserde(rename = "C2D_T")] 26 | pub c2d_t: Option, 27 | /// D2C_CFM xml 28 | #[yaserde(rename = "D2C_CFM")] 29 | pub d2c_cfm: Option, 30 | /// C2D_DISC xml Disconnect 31 | #[yaserde(rename = "C2D_DISC")] 32 | pub c2d_disc: Option, 33 | /// D2C_DISC xml Disconnect 34 | #[yaserde(rename = "D2C_DISC")] 35 | pub d2c_disc: Option, 36 | /// C2M_Q xml client to middle man query 37 | #[yaserde(rename = "C2M_Q")] 38 | pub c2m_q: Option, 39 | /// M2C_Q_R xml middle man to client query reply 40 | #[yaserde(rename = "M2C_Q_R")] 41 | pub m2c_q_r: Option, 42 | /// C2R_C xml client to register connect 43 | #[yaserde(rename = "C2R_C")] 44 | pub c2r_c: Option, 45 | /// R2C_T xml register to clinet with device ID etc 46 | #[yaserde(rename = "R2C_T")] 47 | pub r2c_t: Option, 48 | /// C2R_CFM xml client to register CFM 49 | #[yaserde(rename = "C2R_CFM")] 50 | pub c2r_cfm: Option, 51 | } 52 | 53 | impl UdpXml { 54 | pub(crate) fn try_parse(s: impl Read) -> Result { 55 | yaserde::de::from_reader(s) 56 | } 57 | pub(crate) fn serialize(&self, w: W) -> Result { 58 | yaserde::ser::serialize_with_writer(self, w, &Config::default()) 59 | } 60 | } 61 | 62 | /// C2D_S xml 63 | /// 64 | /// The camera will send binary data to port 3000 65 | /// to whoever it gets this message from 66 | /// 67 | /// It should be broadcasted to port 2015 68 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 69 | pub struct C2dS { 70 | /// The destination to reply to 71 | pub to: PortList, 72 | } 73 | 74 | /// Port list xml 75 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 76 | pub struct PortList { 77 | /// Port to open udp connections with 78 | pub port: u32, 79 | } 80 | 81 | /// C2D_C xml 82 | /// 83 | /// This will start a connection with any camera that has this UID 84 | /// It should be broadcasted to port 2018 85 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 86 | pub struct C2dC { 87 | /// UID of the camera the client wants to connect with 88 | pub uid: String, 89 | /// Cli contains the udp port to communicate on 90 | pub cli: ClientList, 91 | /// The cid is the client ID 92 | pub cid: i32, 93 | /// Maximum transmission size, 94 | pub mtu: u32, 95 | /// Debug mode. Purpose unknown 96 | pub debug: bool, 97 | /// Os of the machine known values are `"MAC"`, `"WIN"` 98 | #[yaserde(rename = "p")] 99 | pub os: String, 100 | } 101 | 102 | /// Client List xml 103 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 104 | pub struct ClientList { 105 | /// Port to start udp communication with 106 | pub port: u32, 107 | } 108 | 109 | /// D2C_C_R xml 110 | /// 111 | /// This will start a connection with any camera that has this UID 112 | /// It should be broadcasted to port 2018 113 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 114 | pub struct D2cCr { 115 | /// Called timer but not sure what it is a timer of 116 | pub timer: Timer, 117 | /// Unknown 118 | pub rsp: u32, 119 | /// Client ID 120 | pub cid: i32, 121 | /// Camera ID 122 | pub did: i32, 123 | } 124 | 125 | /// Timer provided by D2C_C_R 126 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 127 | pub struct Timer { 128 | /// Unknown 129 | def: u32, 130 | /// Unknown 131 | hb: u32, 132 | /// Unknown 133 | hbt: u32, 134 | } 135 | 136 | /// C2D_DISC xml 137 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 138 | pub struct C2dDisc { 139 | /// The client connection ID 140 | pub cid: i32, 141 | /// The camera connection ID 142 | pub did: i32, 143 | } 144 | 145 | /// D2C_DISC xml 146 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 147 | pub struct D2cDisc { 148 | /// The client connection ID 149 | pub cid: i32, 150 | /// The camera connection ID 151 | pub did: i32, 152 | } 153 | 154 | /// D2C_T xml 155 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 156 | pub struct D2cT { 157 | /// The camera SID 158 | pub sid: u32, 159 | /// Type of connection observed values are `"local"` 160 | pub conn: String, 161 | /// The client connection ID 162 | pub cid: i32, 163 | /// The camera connection ID 164 | pub did: i32, 165 | } 166 | 167 | /// C2D_T xml 168 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 169 | pub struct C2dT { 170 | /// The camera SID 171 | pub sid: u32, 172 | /// Type of connection observed values are `"local"` 173 | pub conn: String, 174 | /// The client connection ID 175 | pub cid: i32, 176 | /// Maximum size in bytes of a transmission 177 | pub mtu: u32, 178 | } 179 | 180 | /// C2M_Q xml 181 | /// 182 | /// This is from client to a reolink middle man server 183 | /// 184 | /// It should be sent to a reolink p2p sever on port 9999 185 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 186 | pub struct C2mQ { 187 | /// UID to look up 188 | pub uid: String, 189 | /// Os of the machine known values are `"MAC"`, `"WIN"` 190 | #[yaserde(rename = "p")] 191 | pub os: String, 192 | } 193 | 194 | /// M2C_Q_R xml 195 | /// 196 | /// This is from middle man reolink server to client 197 | /// 198 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 199 | pub struct M2cQr { 200 | /// The register server location 201 | pub reg: IpPort, 202 | /// The relay server location 203 | pub relay: IpPort, 204 | /// The log server location 205 | pub log: IpPort, 206 | /// The camera location 207 | pub t: IpPort, 208 | } 209 | 210 | /// Used as part of M2C_Q_R to provide the host and port 211 | /// 212 | /// of the register, relay and log servers 213 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 214 | pub struct IpPort { 215 | /// Ip of the service 216 | pub ip: String, 217 | /// Port of the service 218 | pub port: u16, 219 | } 220 | 221 | /// C2R_C xml 222 | /// 223 | /// This is from client to the register reolink server 224 | /// 225 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 226 | pub struct C2rC { 227 | /// The UID to register connecition request with 228 | pub uid: String, 229 | /// The location of the client 230 | pub cli: IpPort, 231 | /// The location of the relay server 232 | pub relay: IpPort, 233 | /// The client id 234 | pub cid: i32, 235 | /// Debug setting. Unknown purpose observed values are `0` 236 | pub debug: bool, 237 | /// Inet family. Observed values `4` 238 | pub family: u8, 239 | /// Os of the machine known values are `"MAC"`, `"WIN"` 240 | #[yaserde(rename = "p")] 241 | pub os: String, 242 | } 243 | 244 | /// R2C_T xml 245 | /// 246 | /// This is from register reolink server to clinet with device ip and did etc 247 | /// 248 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 249 | pub struct R2cT { 250 | /// The location of the camera 251 | pub dev: IpPort, 252 | /// The client id 253 | pub cid: i32, 254 | /// The camera SID 255 | pub sid: u32, 256 | } 257 | 258 | /// D2C_CFM xml 259 | /// 260 | /// Device to client, with connection started from middle man server 261 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 262 | pub struct D2cCfm { 263 | /// The camera SID 264 | pub sid: u32, 265 | /// Type of connection observed values are `"local"` 266 | pub conn: String, 267 | /// Unknown known values are `0` 268 | pub rsp: u32, 269 | /// The client connection ID 270 | pub cid: i32, 271 | /// The camera connection ID 272 | pub did: i32, 273 | /// The time but only value that has been observed is `0 274 | pub time_r: u32, 275 | } 276 | 277 | /// C2R_CFM xml 278 | /// 279 | /// Client to register 280 | #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] 281 | pub struct C2rCfm { 282 | /// The camera SID 283 | pub sid: u32, 284 | /// Type of connection observed values are `"local"` 285 | pub conn: String, 286 | /// Unknown known values are `0` 287 | pub rsp: u32, 288 | /// The client connection ID 289 | pub cid: i32, 290 | /// The camera connection ID 291 | pub did: i32, 292 | } 293 | -------------------------------------------------------------------------------- /crates/core/src/bcudp/xml_crypto.rs: -------------------------------------------------------------------------------- 1 | const XML_KEY: [u32; 8] = [ 2 | 0x1f2d3c4b, 0x5a6c7f8d, 0x38172e4b, 0x8271635a, 0x863f1a2b, 0xa5c6f7d8, 0x8371e1b4, 0x17f2d3a5, 3 | ]; 4 | 5 | pub(crate) fn decrypt(offset: u32, buf: &[u8]) -> Vec { 6 | let key = XML_KEY 7 | .iter() 8 | .map(|i| (i + offset).to_le_bytes()) 9 | .flatten() 10 | .cycle(); 11 | buf.iter().zip(key).map(|(byte, key)| key ^ byte).collect() 12 | } 13 | 14 | pub(crate) fn encrypt(offset: u32, buf: &[u8]) -> Vec { 15 | decrypt(offset, buf) 16 | } 17 | 18 | #[test] 19 | fn test_udp_xml_crypto() { 20 | let sample = include_bytes!("samples/xml_crypto_sample1.bin"); 21 | let should_be = include_bytes!("samples/xml_crypto_sample1_plaintext.bin"); 22 | 23 | let decrypted = decrypt(87, &sample[..]); 24 | assert_eq!(decrypted, &should_be[..]); 25 | } 26 | 27 | #[test] 28 | fn test_udp_xml_crypto_roundtrip() { 29 | let zeros: [u8; 256] = [0; 256]; 30 | 31 | let decrypted = encrypt(0, &zeros[..]); 32 | let encrypted = decrypt(0, &decrypted[..]); 33 | assert_eq!(encrypted, &zeros[..]); 34 | } 35 | -------------------------------------------------------------------------------- /crates/core/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![warn(missing_docs)] 2 | //! # Neolink-Core 3 | //! 4 | //! Neolink-Core is a rust library for interacting with reolink and family cameras. 5 | //! 6 | //! Most high level camera controls are in the [`bc_protocol`] module 7 | //! 8 | //! A camera can be initialised with 9 | //! 10 | //! ```no_run 11 | //! use neolink_core::bc_protocol::BcCamera; 12 | //! let channel_id = 0; // Usually zero but can be non zero if uses a reolink NVR 13 | //! let mut camera = BcCamera::new_with_addr("camera_ip_address", channel_id).unwrap(); 14 | //! ``` 15 | //! 16 | //! After that login can be conducted with 17 | //! 18 | //! ```no_run 19 | //! # use neolink_core::bc_protocol::BcCamera; 20 | //! # let channel_id = 0; 21 | //! # let mut camera = BcCamera::new_with_addr("camera_ip_address", channel_id).unwrap(); 22 | //! camera.login("username", Some("password")); 23 | //! ``` 24 | //! For further commands see the [`bc_protocol::BcCamera`] struct. 25 | //! 26 | 27 | /// Contains low level BC structures and formats 28 | pub mod bc; 29 | /// Contains high level interfaces for the camera 30 | pub mod bc_protocol; 31 | /// Contains low level structures and formats for the media substream 32 | pub mod bcmedia; 33 | /// Contains low level structures and formats for the udpstream 34 | pub mod bcudp; 35 | 36 | /// This is the top level error structure of the library 37 | /// 38 | /// Most commands will either return their `Ok(result)` or this `Err(Error)` 39 | pub use bc_protocol::Error; 40 | 41 | pub(crate) const RX_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); 42 | -------------------------------------------------------------------------------- /dissector/mediapacket.md: -------------------------------------------------------------------------------- 1 | # Media Packets 2 | 3 | This file attempts to document the encapsulated stream that makes up the binary 4 | data of message ID 3. This stream represents the video and audio data. 5 | 6 | The are six types of media packets 7 | 8 | - Info V1 9 | 10 | - Info V2 11 | 12 | - I Frame 13 | 14 | - P Frame 15 | 16 | - AAC 17 | 18 | - ADPCM 19 | 20 | The I and P frames come in two formats H264 and H265. 21 | 22 | The ADPCM is DVI-4 encoded with an extra header that represents the block size. 23 | 24 | ## Magic 25 | 26 | Each packet can be distinguished with the following magic bytes 27 | 28 | - Info V1: 0x31, 0x30, 0x30, 0x31 29 | - Info V2: 0x31, 0x30, 0x30, 0x32 30 | - I Frame: 0x30, 0x30, 0x64, 0x63 31 | - P Frame: 0x30, 0x31, 0x64, 0x63 32 | - AAC: 0x30, 0x35, 0x77, 0x62 33 | - ADPCM: 0x30, 0x31, 0x77, 0x62 34 | 35 | 36 | ## Headers 37 | 38 | The full headers for each of these are as follows: 39 | 40 | Most of this information comes from the work of @twisteddx at his 41 | [site](https://www.wasteofcash.com/BCConvert/BC_fileformat.txt) 42 | 43 | - Info V1/V2: 44 | 45 | - 4 bytes magic 46 | - 4 bytes data size of header itself 47 | - 4 bytes video width 48 | - 4 bytes video height 49 | - 1 byte unknown. Known values 00/01 50 | - 1 byte Frames per second (Reolink=FPS, Swann=Appears to be the index value of the FPS setting) 51 | - 1 byte Start UTC year since 1900 52 | - 1 byte Start UTC month 53 | - 1 byte Start UTC date 54 | - 1 byte Start UTC hour 55 | - 1 byte Start UTC minute 56 | - 1 byte Start UTC seconds 57 | - 1 byte End UTC year since 1900 58 | - 1 byte End UTC month 59 | - 1 byte End UTC date 60 | - 1 byte End UTC hour 61 | - 1 byte End UTC minute 62 | - 1 byte End UTC seconds 63 | - 2 bytes reserved 64 | 65 | - I Frame 66 | 67 | - 4 bytes magic 68 | - 4 bytes video type (ASCII text of either H264 or H265) 69 | - 4 bytes data size of payload after header 70 | - 4 bytes unknown. NVR channel count? Known values 1-00/08 2-00 3-00 4-00 71 | - 4 bytes Microseconds 72 | - 4 bytes unknown. Known values 1-00/23/5A 2-00 3-00 4-00 73 | - 4 bytes POSIX time_t 32bit UTC time (seconds since 00:00:00 Jan 1 1970) 74 | - 4 bytes unknown. Known values 1-00/06/29 2-00/01 3-00/C3 4-00 75 | 76 | - P Frame 77 | - 4 bytes magic 78 | - 4 bytes video type (eg H264 or H265) 79 | - 4 bytes data size of payload after header 80 | - 4 bytes unknown. Known values 1-00 2-00 3-00 4-00 81 | - 4 bytes Microseconds 82 | - 4 bytes unknown. Known values 1-00/5A 2-00 3-00 4-00 83 | 84 | - AAC 85 | 86 | - 4 bytes magic 87 | - 2 bytes data size of payload after header 88 | - 2 bytes data size of payload after header (Same as previous) 89 | 90 | - ADPCM 91 | 92 | - 4 bytes magic 93 | - 2 bytes data size of payload after header 94 | - 2 bytes data size of payload after header 95 | 96 | ### ADPCM 97 | 98 | After the ADPCM header is another header of the form 99 | 100 | - 2 bytes Magic either 0x00 0x01 or 0x00 0x7a 101 | - 2 Bytes DVI-4 Block size divided in bytes. 102 | 103 | After this header the adpcm DVI-4 data follows should be 4+Block size bytes. 104 | 105 | ## Processing 106 | 107 | The data in ID 3 messages represents an encapsulated stream. BC messages may 108 | terminate mid media packet messages. Clients should create a buffer of the 109 | BC ID 3 messages then read the media packet magic and expected length. Once 110 | length is known they should wait for more BC message ID 3 packets until a 111 | complete media packet is received before processing it. 112 | -------------------------------------------------------------------------------- /dissector/udp.md: -------------------------------------------------------------------------------- 1 | # BcUDP 2 | 3 | This document describes the UDP protocol. UDP, unlike TCP, is lossy, there 4 | is no guarantee that all packets sent will be received or that they are received 5 | in the same order. As such the protocol involves sending meta data back and forth 6 | where the camera and client acknowledge packets they have received. 7 | 8 | Additionally the UDP max data size is smaller so packets will be split more 9 | perhaps even several UDP packets per BC message, whereas in TCP the Bc messages were 10 | always in one TCP packet. 11 | 12 | # Packets Types 13 | 14 | There are three types of UDP packets with their own header 15 | 16 | - UDP Discovery: These packets have the magic `3acf872a` and contain encrypted 17 | xml about the connection that will be used 18 | - UDP Ack: These packets have the magic `20cf872a` they are header only and 19 | contain acknowledgement of packets 20 | - UDP Data: These packets contain part of a BC messagse with a special UDP 21 | header that describes the udp message number, to help reassemble 22 | the packets. They have the magic: `10cf872a` 23 | 24 | # UDP Discovery 25 | 26 | These messages are sent as part of the initial connection discovery. 27 | It is a sequence of messages with different xmls. 28 | 29 | If there is no reply is received within 500ms the last message is resent. 30 | 31 | ## Header 20 Bytes 32 | 33 | - 4 Bytes magic: `3acf872a` 34 | - 4 Bytes data size: Size in bytes of payload 35 | - 4 Bytes unknown: Always `01000000` for for UDP Discovery 36 | - 4 Bytes Transmission ID: The unique ID of the transmission, every successful 37 | round trip of Discovery it is incremented. 38 | The number is the same for the same transmission 39 | and may be used to identify repeated messages. 40 | It is also used for the encryption. 41 | - 4 Bytes Checksum: The checksum of the payload encrypted payload 42 | 43 | The checksum can be calculated with a polynomial of `0x04c11db7`, an init value 44 | of `0x00000000` and an xorout of `0x00000000`. 45 | 46 | 47 | ## Payload 48 | 49 | - The XML payloads are encrypted with a simple xor algorithm. See the full 50 | source in neolink for details. 51 | 52 | ## Start Discovery payload 53 | 54 | Client send this packet as a broadcast on 255.255.255.255 on port 2015 55 | to init a connection 56 | 57 | ```xml 58 | 59 | 60 | 61 | 57268 62 | 63 | 64 | 65 | ``` 66 | 67 | It also sends this binary on port 2000 as a broadcast 68 | 69 | ``` 70 | aaaa0000 71 | ``` 72 | 73 | --- 74 | 75 | **Camera Replies with Binary** 76 | 77 | Camera replies with binary data to port 3000 78 | 79 | This data seems to include the 80 | - Camera name 81 | - ip address 82 | - TCP port 83 | - Camera UID 84 | 85 | 86 | **Tcp camera** 87 | 88 | If the camera supports tcp the client will use this binary data to open a 89 | standard tcp bc connection 90 | 91 | **Udp Camera** 92 | 93 | If the camera supports UDP the client will send the following xml packet 94 | as a broadcast on 255.255.255.255 on port 2018/2015 95 | 96 | **Known UID** 97 | 98 | If the UID is already known you can skip to this step. 99 | 100 | ```xml 101 | 102 | 103 | 95270000YGAKNWKJ 104 | 105 | 24862 106 | 107 | 849013 108 | 1350 109 | 0 110 |

MAC

111 | 112 | 113 | ``` 114 | 115 | **Both** 116 | 117 | A camera can do both of the above. In this case it will try to login 118 | to both udp and tcp. Then the udp will disconnect. 119 | 120 | --- 121 | 122 | ## D2C_C_R Payload Camera 123 | 124 | Camera replies with this payload on the port specified in `C2D_C` 125 | 126 | ```xml 127 | 128 | 129 | 130 | 3000 131 | 10000 132 | 60000 133 | 134 | 0 135 | 849013 136 | 192 137 | 138 | 139 | ``` 140 | 141 | - **timer** Unknown timer of some sort` 142 | - **rsp**: Unknown 143 | - **cid**: The connection ID of the client 144 | - **did**: The connection ID of the camera 145 | 146 | 147 | 148 | ## T Payload Client 149 | 150 | Client then replies with this. 151 | 152 | ```xml 153 | 154 | 155 | 62097899 156 | local 157 | 82000 158 | 1350 159 | 160 | 161 | ``` 162 | 163 | - **sid**: ID of the camera 164 | - **conn**: Type of connection only observed `local` value 165 | - **cid**: The connection ID of the client 166 | - **did**: The connection ID of the camera 167 | - **mtu**: The maximum transmission unit of the connection. Which is the 168 | largest packet size in bytes 169 | 170 | 171 | ## T Payload Camera 172 | 173 | Camera replies with this payload on the port specified in `C2D_C` 174 | 175 | ```xml 176 | 177 | 178 | 62097899 179 | local 180 | 82000 181 | 528 182 | 183 | 184 | ``` 185 | **Login** 186 | 187 | The client can now login over UDP 188 | 189 | 190 | ## Dissconnect 191 | 192 | After a message ID 02 (logout) the client send this 193 | 194 | ```xml 195 | 196 | 197 | 82000 198 | 80 199 | 200 | 201 | ``` 202 | 203 | - **cid**: The connection ID of the client 204 | - **did**: The connection ID of the camera 205 | 206 | The camera also send it but with a `D2C_DISC` tag 207 | 208 | ## Other 209 | 210 | Some cameras seem to also send this before login 211 | 212 | ```xml 213 | 214 | 215 | 62097899 216 | local 217 | 0 218 | 82000 219 | 80 220 | 0 221 | 222 | 223 | ``` 224 | 225 | - **sid**: ID of the camera 226 | - **conn**: Type of connection only observed `local` value 227 | - **rsp**: Unknown always 0 228 | - **cid**: The connection ID of the client 229 | - **did**: The connection ID of the camera 230 | - **time_r**: Should be the time but it is always 0 231 | 232 | # UDP Ack 233 | 234 | These messages are sent to acknowledge receipt of message 235 | 236 | ## Header 28 Bytes 237 | 238 | - 4 Bytes magic: `20cf872a` 239 | - 4 Bytes Connection ID: This is the connection ID negotiated during UDP Discovery 240 | - 4 Bytes unknown: Always `00000000` for for UDP Ack 241 | - 4 Bytes unknown: Always `00000000` for for UDP Ack 242 | - 4 Bytes Last Packet ID: Last received packet id 243 | - 4 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000` **NEEDS INFO** 244 | - Payload Size 245 | - Paload 246 | 247 | **To Investigate:** 248 | - Why does the unknown byte change. It starts at zero and remains that way 249 | for a second. Then seems to change and remain at the new value for another second. 250 | This may be some metric such as average ttl for the last second, or some calculation 251 | of the jitter 252 | 253 | Here's an example of a UDP Ack payload (size 203 bytes) 254 | 255 | ```hex 256 | 0000 00 01 01 01 01 01 01 01 01 01 01 01 00 01 01 01 257 | 0010 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 258 | 0020 01 01 01 01 00 01 01 01 01 01 01 01 01 01 01 01 259 | 0030 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 260 | 0040 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 261 | 0050 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 262 | 0060 01 01 01 01 01 01 00 01 01 01 01 01 01 01 01 01 263 | 0070 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 264 | 0080 01 01 01 01 01 01 01 01 01 01 00 01 01 01 01 01 265 | 0090 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 266 | 00a0 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 267 | 00b0 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 268 | 00c0 01 01 01 01 01 01 01 01 01 01 01 01 269 | ``` 270 | 271 | The payload is a truth table. If the packet ID in header is 50 272 | then the first byte corresponds to packet id 51, the second 52 273 | etc etc. If the byte if `00` then the camera will resend that packet 274 | 275 | If this payload is allowed to grow to ~ 205 bytes the camera sends a 276 | disconnect request and drops the connection 277 | 278 | 279 | 280 | # UDP Data 281 | 282 | UDP data packets contain the BC packets with an extra header. 283 | 284 | Whenever a packet is received a UDP Ack is sent. If the sender of the packet 285 | does not get the Ack within 1000ms it resends the packet 286 | 287 | ## Header 20 Bytes 288 | 289 | - 4 Bytes magic: `10cf872a` 290 | - 4 Bytes Connection ID: This is the connection ID negotiated during UDP Discovery 291 | - 4 Bytes unknown: Always `00000000` for for UDP Data 292 | - 4 Bytes Packet ID: The ID of the packet mono-atomically increases for each new packet 293 | - 4 Bytes Payload Size: Size of UDP payload in bytes 294 | 295 | ## Payload 296 | 297 | The payload is a standard Bc Packet 298 | -------------------------------------------------------------------------------- /docker/entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # Allows Ctrl-C, by letting this sh process act as PID 1 4 | exit_func() { 5 | exit 1 6 | } 7 | trap exit_func SIGTERM SIGINT 8 | 9 | "$@" 10 | -------------------------------------------------------------------------------- /docs/screenshots/login_messages.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/docs/screenshots/login_messages.JPG -------------------------------------------------------------------------------- /docs/screenshots/new_camera.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/docs/screenshots/new_camera.JPG -------------------------------------------------------------------------------- /docs/screenshots/new_camera_config.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/docs/screenshots/new_camera_config.JPG -------------------------------------------------------------------------------- /docs/screenshots/taskfinishwindow.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/docs/screenshots/taskfinishwindow.JPG -------------------------------------------------------------------------------- /docs/screenshots/tasksettingstab.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/thirtythreeforty/neolink/186d58046271870ca0f67afca6e18a797696551c/docs/screenshots/tasksettingstab.JPG -------------------------------------------------------------------------------- /docs/unix_service.md: -------------------------------------------------------------------------------- 1 | # Creating a Service for Neolink 2 | 3 | This will guide you through creating a service for neolink that 4 | can be used on linux machines such as ubuntu and debian 5 | buster/stetch or any other os that uses systemd. 6 | 7 | The general steps are: 8 | 9 | 1. Create an unprivileged user to run neolink 10 | 2. Set up neolink somewhere the unprivileged user can run it 11 | 3. Creating the service file 12 | 13 | ## Creating the unprivileged user 14 | 15 | For this I will use the username neolinker. Any unused name would be fine. 16 | 17 | ```bash 18 | sudo adduser --system --no-create-home --shell /bin/false neolinker 19 | ``` 20 | 21 | Depending on your flavour of linux `adduser` may have also created 22 | a group of the same name. If it did not, you can create a group with: 23 | 24 | ```bash 25 | sudo addgroup --system neolinker 26 | ``` 27 | 28 | ## Setting up neolink 29 | 30 | For this we will put neolink in `/usr/local/bin` and the config in `/usr/local/etc` but any directory readable by the `neolinker` user would be fine. 31 | 32 | We will also secure the config file so that only neolinker (and root) can read it. We want to do this because it contains passwords. 33 | 34 | ```bash 35 | sudo cp neolink /usr/local/bin/neolink 36 | sudo cp my_config.toml /usr/local/etc/neolink_config.toml 37 | sudo chmod 755 /usr/local/bin/neolink 38 | sudo chown neolinker:neolinker /usr/local/etc/neolink_config.toml 39 | sudo chmod 600 /usr/local/etc/neolink_config.toml 40 | ``` 41 | 42 | ## Creating the service 43 | 44 | We will create a systemd service. This service will need to point to our files for using neolink and also instruct it to start with our unprivileged user. 45 | 46 | Create a file here `/etc/systemd/system/neolink.service` with the following contents (you will need admin privileges to write to this location): 47 | 48 | ``` 49 | [Install] 50 | WantedBy=multi-user.target 51 | 52 | [Unit] 53 | Description=Neolink service 54 | 55 | [Service] 56 | Type=simple 57 | ExecStart=/usr/local/bin/neolink rtsp --config /usr/local/etc/neolink_config.toml 58 | Restart=on-failure 59 | User=neolinker 60 | Group=neolinker 61 | 62 | ``` 63 | 64 | And that's it 65 | 66 | ## Controlling the Service 67 | 68 | You can now control the service with the usual commands 69 | 70 | To start it use: 71 | 72 | ```bash 73 | systemctl start neolink 74 | ``` 75 | 76 | To stop it use: 77 | 78 | ```bash 79 | systemctl stop neolink 80 | ``` 81 | 82 | To check it's running use: 83 | 84 | ```bash 85 | systemctl status neolink 86 | ``` 87 | 88 | To make it run at startup from now on: 89 | 90 | ```bash 91 | systemctl enable neolink 92 | ``` 93 | 94 | You can check it's log file with 95 | 96 | ```bash 97 | journalctl -xeu neolink 98 | ``` 99 | -------------------------------------------------------------------------------- /docs/unix_setup.md: -------------------------------------------------------------------------------- 1 | # Setting up Neolink on Linux 2 | 3 | This will go through the first steps of adding neolink onto a 4 | linux based computer. 5 | 6 | There are many flavours of linux so the name of some packages 7 | may not exactly match. You are expected to be able to find the 8 | correct names yourselves. 9 | 10 | The general steps we will follow in this guide are as follows: 11 | 12 | 1. Install dependancies 13 | 14 | 2. Download neolink 15 | 16 | 3. Setup the config 17 | 18 | 4. Run neolink 19 | 20 | ## Installing the Dependencies 21 | 22 | The dependencies for neolink include: 23 | 24 | - Gstreamer RTSP server 25 | 26 | - Gstreamer good plugin set 27 | 28 | - Gstreamer bad plugin set 29 | 30 | - glib 2.0 31 | 32 | Glib2.0 is usually already installed on most modern unix flavours. 33 | But the others will likely need to be installed via your package 34 | manager. 35 | 36 | Here are some examples for commands of package managers 37 | 38 | - ubuntu, buster, stretch 39 | 40 | ```bash 41 | sudo apt install \ 42 | libgstrtspserver-1.0-0 \ 43 | libgstreamer1.0-0 \ 44 | libgstreamer-plugins-bad1.0-0 \ 45 | gstreamer1.0-plugins-good \ 46 | gstreamer1.0-plugins-bad 47 | ``` 48 | 49 | - arch, manjaro 50 | 51 | ```bash 52 | sudo pacman -S \ 53 | gstreamer \ 54 | gst-plugins-bad \ 55 | gst-plugins-good \ 56 | 57 | # You will need this from AUR, and therefore need to install 58 | # yay first (see below if you haven't done this yet) 59 | sudo yay -S \ 60 | gst-rtsp-server 61 | ``` 62 | 63 | If your on archlinux or manjaro and you need to install `yay` do this: 64 | 65 | ```bash 66 | git clone https://aur.archlinux.org/yay.git 67 | cd yay 68 | makepkg -si 69 | ``` 70 | 71 | ## Downloading neolink 72 | 73 | You now need to get a copy of neolink. You can get that from this 74 | github [under the CI assets](https://github.com/thirtythreeforty/neolink/actions?query=branch%3Amaster+workflow%3ACI). 75 | 76 | Currently amd64 and armv7 are officially released. 77 | 78 | If you are installing on a raspberry pi, you will need the armv7 build. 79 | 80 | You will get a zip file called `release-ubuntu-18.04.zip`, unzip it with 81 | 82 | ```bash 83 | unzip "release-ubuntu-18.04.zip" 84 | ``` 85 | 86 | This will extract two files called `neolink` and `neolink.d`. These are 87 | the binaries we will be using. 88 | 89 | ## Setting up the Configuration File 90 | 91 | Neolink uses a toml file for configuration. A sample toml can be found in the 92 | source code called `sample_config.toml`. 93 | 94 | You can download it with 95 | 96 | ```bash 97 | curl -LJO 'https://github.com/thirtythreeforty/neolink/raw/master/sample_config.toml' 98 | ``` 99 | 100 | Open up the file in your favourite text editor. 101 | 102 | For the most basic setup you need to change only the parts in `[[ cameras ]]`. 103 | Neolink can connect to any number of supported reolink cameras at once. Each 104 | camera requires its own `[[ cameras ]]` block. Here is an example one: 105 | 106 | ```toml 107 | [[cameras]] 108 | name = "driveway" 109 | username = "admin" 110 | password = "12345678" 111 | address = "192.168.1.187:9000" 112 | ``` 113 | 114 | Set the `name` to any value you want, this will be the name of the rtsp stream. 115 | In this tutorial I will assume you leave it as "driveway". 116 | 117 | The username and passwords are the same ones used in the official reolink app. 118 | 119 | The address is the ip address of the camera. You should set and use a fixed ip 120 | for your camera. There are many ways to get a fixed ip address for your camera 121 | including changing the settings in the reolink app. 122 | Or by assigning a fixed DHCP address from your router. How to do either of 123 | these things is beyond the scope of this tutorial. 124 | 125 | - Note for E1 and Lumus 126 | 127 | If your camera is an E1 or a Lumus you will need to add the `format` line 128 | to your `[[ cameras ]]` block like this: 129 | 130 | ```toml 131 | [[cameras]] 132 | name = "driveway" 133 | username = "admin" 134 | password = "12345678" 135 | address = "192.168.1.187:9000" 136 | format = "h264" 137 | ``` 138 | 139 | This will tell neolink that this camera uses the H264 format for its video. 140 | Future version of neolink will auto detect this. 141 | 142 | Set up as many `[[ cameras ]]` as you want and save the file as `my_config.toml` 143 | 144 | ## Running Neolink 145 | 146 | We are now ready to run neolink. Open up and terminal and navigate to the 147 | folder where `neolink` and `my_config.toml` are. 148 | 149 | Run neolink with: 150 | 151 | ``` 152 | ./neolink rtsp --config my_config.toml 153 | ``` 154 | 155 | You should see messages such as: 156 | 157 | ``` 158 | [DATE TIME INFO neolink] Neolink 0.3.0 (unknown commit) release 159 | [DATE TIME INFO neolink] camera: Connecting to camera at xxx.xxx.xxx.xxx:9000 160 | [DATE TIME INFO neolink] camera: Connecting to camera at xxx.xxx.xxx.xxx:9000 161 | [DATE TIME INFO neolink] camera: Connected to camera, starting video stream mainStream 162 | [DATE TIME INFO neolink] camera: Connected to camera, starting video stream subStream 163 | ``` 164 | 165 | Neolink should now be running :) 166 | 167 | 168 | ## Testing with ffprobe 169 | 170 | To test neolink we will use `ffprobe`. 171 | 172 | If you do not have `ffmpeg` installed yet do it now through your package 173 | manager: 174 | 175 | ```bash 176 | sudo apt install ffmpeg 177 | ``` 178 | 179 | You must leave neolink running at the same time you run ffprobe. Neolink is a 180 | translator and it cannot translate reolink -> rtsp if you close it. The easiest 181 | way to do this is to open two terminals. One with neolink running and the other 182 | for running ffprobe. 183 | 184 | In a new terminal run: 185 | 186 | ```bash 187 | ffprobe rtsp://127.0.0.1:8554/driveway 188 | ``` 189 | 190 | Where you replace `driveway` with the name of your camera. 191 | 192 | A successful run should report something like this at the end: 193 | 194 | ``` 195 | Input #0, rtsp, from 'rtsp://127.0.0.1:8554/driveway': 196 | Metadata: 197 | title : Session streamed with GStreamer 198 | comment : rtsp-server 199 | Duration: N/A, start: 0.114267, bitrate: N/A 200 | Stream #0:0: Video: h264 (High), yuv420p(progressive), 2304x1296, 90k tbr, 90k tbn, 180k tbc 201 | ``` 202 | 203 | You should also test the lower resolution subStream: 204 | 205 | ```bash 206 | ffprobe rtsp://127.0.0.1:8554/driveway/subStream 207 | ``` 208 | 209 | If the mainStream fails but the subStream succeeds you may need to add 210 | `format = "h264"` to your `[[ cameras ]]` section of your config. 211 | 212 | ## Common Errors 213 | 214 | - Missing dependancies 215 | 216 | If when start neolink you get a message such as: 217 | 218 | ``` 219 | libgstrtspserver-1.0.so.0: cannot open shared object file: No such file or directory 220 | ``` 221 | 222 | You have not installed all of the dependencies repeat the `Installing the Dependencies` 223 | section of this guide. 224 | 225 | - Not turned on 226 | 227 | If when using ffprobe to test you get: 228 | 229 | ``` 230 | Connection to tcp://xxx.xxx.xxx.xxx:8554?timeout=0 failed: Connection refused 231 | rtsp://xxx.xxx.xxx.xxx:8554/driveway: Connection refused ``` 232 | ``` 233 | 234 | You have probably closed neolink. You should leave it running in an open 235 | terminal window whenever you want to use it. If you want to run it in the 236 | background, consider following the unix_service guide in the `docs/` folder 237 | of the source code. 238 | 239 | - More advanced debugging required 240 | 241 | For other errors you will need to enable more debugging messages before 242 | running neolink for better diagnoses. To do this stop neolink and restart it 243 | with this command. 244 | 245 | ```bash 246 | GST_DEBUG=3 ./neolink rtsp --config my_config.toml 247 | ``` 248 | 249 | This will print out a lot more information to the terminal. Try to connect 250 | to it with ffprobe and read the error messages it generates. 251 | 252 | - Advanced debugging: Missing plugins 253 | 254 | If while running advanced debugging you get a message like this: 255 | 256 | ``` 257 | GST_ELEMENT_FACTORY gstelementfactory.c:456:gst_element_factory_make: no such element factory "h265parse"! 258 | ``` 259 | 260 | This means that you are missing the gstreamer plugins. You must have both 261 | the good and the bad set of plugins. Please repeat the 262 | `Installing the Dependencies` section of this guide. 263 | 264 | - Advanced debugging: Incorrect video format 265 | 266 | If while running advanced debugging you get a message like this: 267 | 268 | ``` 269 | h265parse gsth265parse.c:1110:gst_h265_parse_handle_frame: broken/invalid nal Type: 48 Invalid, Size: 1073 will be dropped 270 | ``` 271 | 272 | You have not set the format to `h264` in the `[[ cameras ]]` config while 273 | using an E1 or Lumus camera. 274 | 275 | Change the `[[ cameras ]]` config to include `format = "h264"` and restart 276 | neolink 277 | 278 | (If you are using another camera and you need to use h264 please let us 279 | know via an issue so we can update this guide) 280 | 281 | - Something else 282 | 283 | If you still have problems open an issue on github and attach the 284 | neolink log. You can save the log to file with the following command: 285 | 286 | ```bash 287 | GST_DEBUG=3 ./neolink rtsp --config my_config.toml 2>&1 > neolink.log 288 | ``` 289 | -------------------------------------------------------------------------------- /sample_config.toml: -------------------------------------------------------------------------------- 1 | # A bind value of 0.0.0.0 means any network this computer can access 2 | # You can chage this to a specfic network e.g. "192.168.1.101" here 3 | # Or to no networks e.g. this computer only "127.0.0.1" 4 | bind = "0.0.0.0" 5 | 6 | # Default port is 8554 but you can change it by uncommenting the following 7 | # bind_port = 8554 8 | 9 | # Uncomment the following and supply a path to a valid PEM 10 | # to activate TLS encryption. 11 | # The PEM should contain the certificate and the private key 12 | # If TLS is activated you must connect with "rtsps://" and not "rtsp://" 13 | # certificate = "/path/to/pem/with/cert/and/key" 14 | 15 | # Choose if the client is required to provide a certificate signed by the server's CA. 16 | # none|requested|required - default none 17 | # tls_client_auth = "required" 18 | 19 | # You can password protect the rtsp server mount points by adding users 20 | # like the following me and someone. If you do not add [[users]] 21 | # then anyone can connect without a password or username 22 | # To access such a stream try using a url such as "rtsp://me:mepass@192.168.1.101/driveway" 23 | 24 | # [[users]] 25 | # name = "me" 26 | # pass = "mepass" 27 | # 28 | # [[users]] 29 | # name = "someone" 30 | # pass = "someonepass" 31 | 32 | 33 | [[cameras]] 34 | name = "driveway" 35 | username = "admin" 36 | password = "12345678" 37 | address = "192.168.1.187:9000" 38 | # If you use a battery camera: **Instead** of an `address` supply the uid 39 | # as follows 40 | # uid = "ABCD01234567890EFG" 41 | 42 | # By default any of the users can connect (or anyone at all if no users are specfied) 43 | # You can uncomment the following to permit only specfic users 44 | # permitted_users = [ "me" ] 45 | 46 | # By default "both" "mainStream" and "subStream" are connected 47 | # If your device has user connection limits try a single stream instead. 48 | # stream = "mainStream" 49 | 50 | 51 | [[cameras]] 52 | name = "storage shed" 53 | username = "admin" 54 | password = "987654321" 55 | address = "192.168.1.245:9000" 56 | # If you use a battery camera: **Instead** of an `address` supply the uid 57 | # as follows 58 | # uid = "ABCD01234567890EFG" 59 | 60 | # If you use an NVR that relays several camera connections you can choose which 61 | # camera to connect to with by setting the `channel_id` 62 | # 63 | # By default channel_id = 0. Eg the first connected camera on the device 64 | # **Note**: that unlike in the offical client the numbering starts from 0 not 1. 65 | # An 8 channel NVR would have channels 0 through 7 66 | # channel_id = 0 67 | -------------------------------------------------------------------------------- /src/cmdline.rs: -------------------------------------------------------------------------------- 1 | use std::path::PathBuf; 2 | use structopt::{clap::AppSettings, StructOpt}; 3 | 4 | /// A standards-compliant bridge to Reolink IP cameras 5 | /// 6 | /// Neolink is free software released under the GNU AGPL v3. 7 | /// You can find its source code at https://github.com/thirtythreeforty/neolink 8 | #[derive(StructOpt, Debug)] 9 | #[structopt( 10 | name = "neolink", 11 | setting(AppSettings::ArgRequiredElseHelp), 12 | setting(AppSettings::UnifiedHelpMessage) 13 | )] 14 | pub struct Opt { 15 | #[structopt(short, long, global(true), parse(from_os_str))] 16 | pub config: Option, 17 | #[structopt(subcommand)] 18 | pub cmd: Option, 19 | } 20 | 21 | #[derive(StructOpt, Debug)] 22 | pub enum Command { 23 | Rtsp(super::rtsp::Opt), 24 | StatusLight(super::statusled::Opt), 25 | Reboot(super::reboot::Opt), 26 | Pir(super::pir::Opt), 27 | Talk(super::talk::Opt), 28 | } 29 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | use lazy_static::lazy_static; 2 | use regex::Regex; 3 | use serde::Deserialize; 4 | use std::clone::Clone; 5 | use std::time::Duration; 6 | use validator::{Validate, ValidationError}; 7 | use validator_derive::Validate; 8 | 9 | lazy_static! { 10 | static ref RE_STREAM_SRC: Regex = 11 | Regex::new(r"^(mainStream|subStream|externStream|both|all)$").unwrap(); 12 | static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap(); 13 | } 14 | 15 | #[derive(Debug, Deserialize, Validate, Clone)] 16 | pub(crate) struct Config { 17 | #[validate] 18 | pub(crate) cameras: Vec, 19 | 20 | #[serde(rename = "bind", default = "default_bind_addr")] 21 | pub(crate) bind_addr: String, 22 | 23 | #[validate(range(min = 0, max = 65535, message = "Invalid port", code = "bind_port"))] 24 | #[serde(default = "default_bind_port")] 25 | pub(crate) bind_port: u16, 26 | 27 | #[serde(default = "default_certificate")] 28 | pub(crate) certificate: Option, 29 | 30 | #[validate(regex( 31 | path = "RE_TLS_CLIENT_AUTH", 32 | message = "Incorrect tls auth", 33 | code = "tls_client_auth" 34 | ))] 35 | #[serde(default = "default_tls_client_auth")] 36 | pub(crate) tls_client_auth: String, 37 | 38 | #[validate] 39 | #[serde(default)] 40 | pub(crate) users: Vec, 41 | } 42 | 43 | #[derive(Debug, Deserialize, Validate, Clone)] 44 | #[validate(schema(function = "validate_camera_config"))] 45 | pub(crate) struct CameraConfig { 46 | pub(crate) name: String, 47 | 48 | #[serde(rename = "address")] 49 | pub(crate) camera_addr: Option, 50 | 51 | #[serde(rename = "uid")] 52 | pub(crate) camera_uid: Option, 53 | 54 | pub(crate) username: String, 55 | pub(crate) password: Option, 56 | 57 | // no longer used, but still here so we can warn users: 58 | pub(crate) timeout: Option, 59 | 60 | // no longer used, but still here so we can warn users: 61 | pub(crate) format: Option, 62 | 63 | #[validate(regex( 64 | path = "RE_STREAM_SRC", 65 | message = "Incorrect stream source", 66 | code = "stream" 67 | ))] 68 | #[serde(default = "default_stream")] 69 | pub(crate) stream: String, 70 | 71 | pub(crate) permitted_users: Option>, 72 | 73 | #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] 74 | #[serde(default = "default_channel_id")] 75 | pub(crate) channel_id: u8, 76 | } 77 | 78 | #[derive(Debug, Deserialize, Validate, Clone)] 79 | pub(crate) struct UserConfig { 80 | #[validate(custom = "validate_username")] 81 | #[serde(alias = "username")] 82 | pub(crate) name: String, 83 | 84 | #[serde(alias = "password")] 85 | pub(crate) pass: String, 86 | } 87 | 88 | fn default_bind_addr() -> String { 89 | "0.0.0.0".to_string() 90 | } 91 | 92 | fn default_bind_port() -> u16 { 93 | 8554 94 | } 95 | 96 | fn default_stream() -> String { 97 | "both".to_string() 98 | } 99 | 100 | fn default_certificate() -> Option { 101 | None 102 | } 103 | 104 | fn default_tls_client_auth() -> String { 105 | "none".to_string() 106 | } 107 | 108 | fn default_channel_id() -> u8 { 109 | 0 110 | } 111 | 112 | pub(crate) static RESERVED_NAMES: &[&str] = &["anyone", "anonymous"]; 113 | fn validate_username(name: &str) -> Result<(), ValidationError> { 114 | if name.trim().is_empty() { 115 | return Err(ValidationError::new("username cannot be empty")); 116 | } 117 | if RESERVED_NAMES.contains(&name) { 118 | return Err(ValidationError::new("This is a reserved username")); 119 | } 120 | Ok(()) 121 | } 122 | 123 | fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> { 124 | match (&camera_config.camera_addr, &camera_config.camera_uid) { 125 | (None, None) => Err(ValidationError::new( 126 | "Either camera address or uid must be given", 127 | )), 128 | (Some(_), Some(_)) => Err(ValidationError::new( 129 | "Must provide either camera address or uid not both", 130 | )), 131 | _ => Ok(()), 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | #![warn(missing_docs)] 2 | //! 3 | //! # Neolink 4 | //! 5 | //! Neolink is a small program that acts a general contol interface for Reolink IP cameras. 6 | //! 7 | //! It contains sub commands for running an rtsp proxy which can be used on Reolink cameras 8 | //! that do not nativly support RTSP. 9 | //! 10 | //! This program is free software: you can redistribute it and/or modify it under the terms of the 11 | //! GNU General Public License as published by the Free Software Foundation, either version 3 of 12 | //! the License, or (at your option) any later version. 13 | //! 14 | //! This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 15 | //! without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See 16 | //! the GNU General Public License for more details. 17 | //! 18 | //! You should have received a copy of the GNU General Public License along with this program. If 19 | //! not, see . 20 | //! 21 | //! Neolink source code is available online at 22 | //! 23 | use anyhow::{Context, Result}; 24 | use env_logger::Env; 25 | use log::*; 26 | use std::fs; 27 | use structopt::StructOpt; 28 | use validator::Validate; 29 | 30 | mod cmdline; 31 | mod config; 32 | mod pir; 33 | mod reboot; 34 | mod rtsp; 35 | mod statusled; 36 | mod talk; 37 | mod utils; 38 | 39 | use cmdline::{Command, Opt}; 40 | use config::Config; 41 | 42 | fn main() -> Result<()> { 43 | env_logger::Builder::from_env(Env::default().default_filter_or("info")).init(); 44 | 45 | info!( 46 | "Neolink {} {}", 47 | env!("NEOLINK_VERSION"), 48 | env!("NEOLINK_PROFILE") 49 | ); 50 | 51 | let opt = Opt::from_args(); 52 | 53 | let conf_path = opt.config.context("Must supply --config file")?; 54 | let config: Config = toml::from_str( 55 | &fs::read_to_string(&conf_path) 56 | .with_context(|| format!("Failed to read {:?}", conf_path))?, 57 | ) 58 | .with_context(|| format!("Failed to parse the {:?} config file", conf_path))?; 59 | 60 | config 61 | .validate() 62 | .with_context(|| format!("Failed to validate the {:?} config file", conf_path))?; 63 | 64 | match opt.cmd { 65 | None => { 66 | warn!( 67 | "Deprecated command line option. Please use: `neolink rtsp --config={:?}`", 68 | config 69 | ); 70 | rtsp::main(rtsp::Opt {}, config)?; 71 | } 72 | Some(Command::Rtsp(opts)) => { 73 | rtsp::main(opts, config)?; 74 | } 75 | Some(Command::StatusLight(opts)) => { 76 | statusled::main(opts, config)?; 77 | } 78 | Some(Command::Reboot(opts)) => { 79 | reboot::main(opts, config)?; 80 | } 81 | Some(Command::Pir(opts)) => { 82 | pir::main(opts, config)?; 83 | } 84 | Some(Command::Talk(opts)) => { 85 | talk::main(opts, config)?; 86 | } 87 | } 88 | 89 | Ok(()) 90 | } 91 | -------------------------------------------------------------------------------- /src/pir/cmdline.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use structopt::StructOpt; 3 | 4 | fn onoff_parse(src: &str) -> Result { 5 | match src { 6 | "true" | "on" | "yes" => Ok(true), 7 | "false" | "off" | "no" => Ok(false), 8 | _ => Err(anyhow!( 9 | "Could not understand {}, check your input, should be true/false, on/off or yes/no", 10 | src 11 | )), 12 | } 13 | } 14 | 15 | /// The pir command will control the PIR status of the camera 16 | #[derive(StructOpt, Debug)] 17 | pub struct Opt { 18 | /// The name of the camera. Must be a name in the config 19 | pub camera: String, 20 | /// Whether to turn the PIR ON or OFF 21 | #[structopt(parse(try_from_str = onoff_parse), name = "on|off")] 22 | pub on: bool, 23 | } 24 | -------------------------------------------------------------------------------- /src/pir/mod.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// # Neolink PIR 3 | /// 4 | /// This module handles the controls of the pir sensor alarm 5 | /// 6 | /// 7 | /// # Usage 8 | /// 9 | /// ```bash 10 | /// # To turn the pir sensor on 11 | /// neolink pir --config=config.toml CameraName on 12 | /// # Or off 13 | /// neolink pir --config=config.toml CameraName off 14 | /// ``` 15 | /// 16 | use anyhow::{Context, Result}; 17 | 18 | mod cmdline; 19 | 20 | use super::config::Config; 21 | use crate::utils::find_and_connect; 22 | pub(crate) use cmdline::Opt; 23 | 24 | /// Entry point for the pir subcommand 25 | /// 26 | /// Opt is the command line options 27 | pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { 28 | let mut camera = find_and_connect(&config, &opt.camera)?; 29 | 30 | camera 31 | .pir_set(opt.on) 32 | .context("Unable to set camera PIR state")?; 33 | Ok(()) 34 | } 35 | -------------------------------------------------------------------------------- /src/reboot/cmdline.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | 3 | /// The reboot command will reboot the camera 4 | #[derive(StructOpt, Debug)] 5 | pub struct Opt { 6 | /// The name of the camera to change the lights of. Must be a name in the config 7 | pub camera: String, 8 | } 9 | -------------------------------------------------------------------------------- /src/reboot/mod.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// # Neolink Reboot 3 | /// 4 | /// This module handles the reboot subcommand 5 | /// 6 | /// The subcommand attepts to reboot the camera. 7 | /// 8 | /// # Usage 9 | /// 10 | /// ```bash 11 | /// neolink reboot --config=config.toml CameraName 12 | /// ``` 13 | /// 14 | use anyhow::{Context, Result}; 15 | 16 | mod cmdline; 17 | 18 | use super::config::Config; 19 | use crate::utils::find_and_connect; 20 | pub(crate) use cmdline::Opt; 21 | 22 | /// Entry point for the reboot subcommand 23 | /// 24 | /// Opt is the command line options 25 | pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { 26 | let camera = find_and_connect(&config, &opt.camera)?; 27 | 28 | camera 29 | .reboot() 30 | .context("Could not send reboot command to the camera")?; 31 | Ok(()) 32 | } 33 | -------------------------------------------------------------------------------- /src/rtsp/cmdline.rs: -------------------------------------------------------------------------------- 1 | use structopt::StructOpt; 2 | 3 | /// The rtsp command will serve all cameras in the config over the rtsp protocol 4 | #[derive(StructOpt, Debug)] 5 | pub struct Opt {} 6 | -------------------------------------------------------------------------------- /src/statusled/cmdline.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Result}; 2 | use structopt::StructOpt; 3 | 4 | fn onoff_parse(src: &str) -> Result { 5 | match src { 6 | "true" | "on" | "yes" => Ok(true), 7 | "false" | "off" | "no" => Ok(false), 8 | _ => Err(anyhow!( 9 | "Could not understand {}, check your input, should be true/false, on/off or yes/no", 10 | src 11 | )), 12 | } 13 | } 14 | 15 | /// The status-light command will control the blue status light on the camera 16 | #[derive(StructOpt, Debug)] 17 | pub struct Opt { 18 | /// The name of the camera to change the lights of. Must be a name in the config 19 | pub camera: String, 20 | /// Whether to turn the light on or off 21 | #[structopt(parse(try_from_str = onoff_parse), name = "on|off")] 22 | pub on: bool, 23 | } 24 | -------------------------------------------------------------------------------- /src/statusled/mod.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// # Neolink Status LED 3 | /// 4 | /// This module handles the controls of the blue led status light 5 | /// 6 | /// The subcommand attepts to set the LED status light not the IR 7 | /// lights or the flood lights. 8 | /// 9 | /// # Usage 10 | /// 11 | /// ```bash 12 | /// # To turn the light on 13 | /// neolink status-light --config=config.toml CameraName on 14 | /// # Or off 15 | /// neolink status-light --config=config.toml CameraName off 16 | /// ``` 17 | /// 18 | use anyhow::{Context, Result}; 19 | 20 | mod cmdline; 21 | 22 | use super::config::Config; 23 | use crate::utils::find_and_connect; 24 | pub(crate) use cmdline::Opt; 25 | 26 | /// Entry point for the ledstatus subcommand 27 | /// 28 | /// Opt is the command line options 29 | pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { 30 | let mut camera = find_and_connect(&config, &opt.camera)?; 31 | 32 | camera 33 | .led_light_set(opt.on) 34 | .context("Unable to set camera light state")?; 35 | Ok(()) 36 | } 37 | -------------------------------------------------------------------------------- /src/talk/cmdline.rs: -------------------------------------------------------------------------------- 1 | use std::path::PathBuf; 2 | use structopt::StructOpt; 3 | 4 | /// The talk command will send audio for the camera to say 5 | /// 6 | /// This data should be encoded in a way that gstreamer can understand. 7 | /// This should be ok with most common formats. 8 | /// 9 | /// `gst-launch` can be used to prepare this data 10 | #[derive(StructOpt, Debug)] 11 | pub struct Opt { 12 | /// The name of the camera to talk through. Must be a name in the config 13 | pub camera: String, 14 | /// The path to the audio file. 15 | #[structopt(short, long, parse(from_os_str), conflicts_with = "microphone")] 16 | pub file_path: Option, 17 | /// Use the microphone as the source. Defaults to autoaudiosrc - Which microphone depends 18 | /// on [gstreamer](https://gstreamer.freedesktop.org/documentation/autodetect/autoaudiosrc.html?gi-language=c#autoaudiosrc-page) 19 | #[structopt(short, long, conflicts_with = "file_path")] 20 | pub microphone: bool, 21 | /// Use a specific microphone like "alsasrc device=hw:1" 22 | #[structopt( 23 | short, 24 | long, 25 | default_value = "autoaudiosrc", 26 | conflicts_with = "file_path" 27 | )] 28 | pub input_src: String, 29 | /// Use to change the volume of the input 30 | #[structopt(short, long, default_value = "1.0")] 31 | pub volume: f32, 32 | } 33 | -------------------------------------------------------------------------------- /src/talk/gst.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Context, Result}; 2 | use gstreamer::{ 3 | element_error, parse_launch, prelude::*, Caps, ClockTime, FlowError, FlowSuccess, MessageView, 4 | Pipeline, ResourceError, State, 5 | }; 6 | use gstreamer_app::{AppSink, AppSinkCallbacks}; 7 | use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; 8 | 9 | use byte_slice_cast::*; 10 | 11 | pub(super) fn from_input( 12 | input_src: &str, 13 | volume: f32, 14 | block_align: u16, 15 | sample_rate: u16, 16 | ) -> Result>> { 17 | let pipeline = create_pipeline(input_src, volume, block_align, sample_rate)?; 18 | input(pipeline) 19 | } 20 | 21 | fn input(pipeline: Pipeline) -> Result>> { 22 | let appsink = get_sink(&pipeline)?; 23 | let (tx, rx) = sync_channel(30); 24 | 25 | set_data_channel(&appsink, tx); 26 | 27 | std::thread::spawn(move || { 28 | let _ = start_pipeline(pipeline); 29 | }); 30 | 31 | Ok(rx) 32 | } 33 | 34 | fn start_pipeline(pipeline: Pipeline) -> Result<()> { 35 | pipeline.set_state(State::Playing)?; 36 | 37 | let bus = pipeline 38 | .bus() 39 | .expect("Pipeline without bus. Shouldn't happen!"); 40 | 41 | for msg in bus.iter_timed(ClockTime::NONE) { 42 | match msg.view() { 43 | MessageView::Eos(..) => break, 44 | MessageView::Error(err) => { 45 | pipeline 46 | .set_state(State::Null) 47 | .context("Error in gstreamer when setting state to Null")?; 48 | log::warn!( 49 | "Error from gstreamer when setting the play state {:?} setting to Null instead", 50 | err 51 | ); 52 | } 53 | _ => (), 54 | } 55 | } 56 | 57 | pipeline 58 | .set_state(State::Null) 59 | .context("Error in gstreamer when setting state to Null")?; 60 | 61 | Ok(()) 62 | } 63 | 64 | fn get_sink(pipeline: &Pipeline) -> Result { 65 | let sink = pipeline 66 | .by_name("thesink") 67 | .expect("There shoud be a `thesink`"); 68 | sink.dynamic_cast::() 69 | .map_err(|_| anyhow!("Cannot find appsink in gstreamer, check your gstreamer plugins")) 70 | } 71 | 72 | fn set_data_channel(appsink: &AppSink, tx: SyncSender>) { 73 | // Getting data out of the appsink is done by setting callbacks on it. 74 | // The appsink will then call those handlers, as soon as data is available. 75 | appsink.set_callbacks( 76 | AppSinkCallbacks::builder() 77 | // Add a handler to the "new-sample" signal. 78 | .new_sample(move |appsink| { 79 | // Pull the sample in question out of the appsink's buffer. 80 | let sample = appsink.pull_sample().map_err(|_| FlowError::Eos)?; 81 | let buffer = sample.buffer().ok_or_else(|| { 82 | element_error!( 83 | appsink, 84 | ResourceError::Failed, 85 | ("Failed to get buffer from appsink") 86 | ); 87 | 88 | FlowError::Error 89 | })?; 90 | 91 | // At this point, buffer is only a reference to an existing memory region somewhere. 92 | // When we want to access its content, we have to map it while requesting the required 93 | // mode of access (read, read/write). 94 | // This type of abstraction is necessary, because the buffer in question might not be 95 | // on the machine's main memory itself, but rather in the GPU's memory. 96 | // So mapping the buffer makes the underlying memory region accessible to us. 97 | // See: https://gstreamer.freedesktop.org/documentation/plugin-development/advanced/allocation.html 98 | let map = buffer.map_readable().map_err(|_| { 99 | element_error!( 100 | appsink, 101 | ResourceError::Failed, 102 | ("Failed to map buffer readable") 103 | ); 104 | 105 | FlowError::Error 106 | })?; 107 | 108 | // We know what format the data in the memory region has, since we requested 109 | // it by setting the appsink's caps. So what we do here is interpret the 110 | // memory region we mapped as an array of signed 8 bit integers. 111 | let samples = map.as_slice_of::().map_err(|_| { 112 | element_error!( 113 | appsink, 114 | ResourceError::Failed, 115 | ("Failed to interprete buffer as u8 ADPCM") 116 | ); 117 | 118 | FlowError::Error 119 | })?; 120 | 121 | // Ready! 122 | let _ = tx.send(samples.to_vec()); 123 | 124 | Ok(FlowSuccess::Ok) 125 | }) 126 | .build(), 127 | ); 128 | } 129 | 130 | fn create_pipeline( 131 | source: &str, 132 | volume: f32, 133 | block_align: u16, 134 | sample_rate: u16, 135 | ) -> Result { 136 | gstreamer::init() 137 | .context("Unable to start gstreamer ensure it and all plugins are installed")?; 138 | 139 | let launch_str = format!( 140 | "{} \ 141 | ! decodebin \ 142 | ! audioconvert \ 143 | ! audioresample \ 144 | ! audio/x-raw,rate={},channels=1 \ 145 | ! volume volume={:.2} \ 146 | ! queue \ 147 | ! adpcmenc blockalign={} layout=dvi \ 148 | ! appsink name=thesink", 149 | source, sample_rate, volume, block_align 150 | ); 151 | 152 | log::info!("{}", launch_str); 153 | 154 | // Parse the pipeline we want to probe from a static in-line string. 155 | // Here we give our audiotestsrc a name, so we can retrieve that element 156 | // from the resulting pipeline. 157 | let pipeline = parse_launch(&launch_str) 158 | .context("Unable to load gstreamer pipeline ensure all gstramer plugins are installed")?; 159 | let pipeline = pipeline.dynamic_cast::().map_err(|_| { 160 | anyhow!("Unable to create gstreamer pipeline ensure all gstramer plugins are installed") 161 | })?; 162 | 163 | let appsink = get_sink(&pipeline)?; 164 | 165 | // Tell the appsink what format we want. It will then be the audiotestsrc's job to 166 | // provide the format we request. 167 | // This can be set after linking the two objects, because format negotiation between 168 | // both elements will happen during pre-rolling of the pipeline. 169 | appsink.set_caps(Some(&Caps::new_simple( 170 | "audio/x-adpcm", 171 | &[ 172 | ("layout", &"dvi"), 173 | ("block_align", &(block_align as i32)), 174 | ("channels", &(1i32)), 175 | ("rate", &(sample_rate as i32)), 176 | ], 177 | ))); 178 | 179 | Ok(pipeline) 180 | } 181 | -------------------------------------------------------------------------------- /src/talk/mod.rs: -------------------------------------------------------------------------------- 1 | /// 2 | /// # Neolink Talk 3 | /// 4 | /// This module can be used to send adpcm data for the camera to play 5 | /// 6 | /// The adpcm data needs to be in DVI-4 layout 7 | /// 8 | /// # Usage 9 | /// 10 | /// ```bash 11 | /// neolink talk --config=config.toml --adpcm-file=data.adpcm --sample-rate=16000 --block-size=512 CameraName 12 | /// ``` 13 | /// 14 | use anyhow::{anyhow, Context, Result}; 15 | use neolink_core::bc::xml::TalkConfig; 16 | 17 | mod cmdline; 18 | mod gst; 19 | 20 | use super::config::Config; 21 | use crate::utils::{connect_and_login, find_camera_by_name}; 22 | pub(crate) use cmdline::Opt; 23 | 24 | /// Entry point for the talk subcommand 25 | /// 26 | /// Opt is the command line options 27 | pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { 28 | let camera_config = find_camera_by_name(&config, &opt.camera)?; 29 | let camera = connect_and_login(camera_config)?; 30 | 31 | let talk_ability = camera 32 | .talk_ability() 33 | .with_context(|| format!("Camera {} does not support talk", camera_config.name))?; 34 | if talk_ability.duplex_list.is_empty() 35 | || talk_ability.audio_stream_mode_list.is_empty() 36 | || talk_ability.audio_config_list.is_empty() 37 | { 38 | return Err(anyhow!( 39 | "Camera {} does not support talk", 40 | camera_config.name 41 | )); 42 | } 43 | 44 | // Just copy that data from the first talk ability in the config have never seen more 45 | // than one ability 46 | let config = 0; 47 | 48 | let talk_config = TalkConfig { 49 | channel_id: camera_config.channel_id, 50 | duplex: talk_ability.duplex_list[config].duplex.clone(), 51 | audio_stream_mode: talk_ability.audio_stream_mode_list[config] 52 | .audio_stream_mode 53 | .clone(), 54 | audio_config: talk_ability.audio_config_list[config].audio_config.clone(), 55 | ..Default::default() 56 | }; 57 | 58 | let block_size = (talk_config.audio_config.length_per_encoder / 2) + 4; 59 | let sample_rate = talk_config.audio_config.sample_rate; 60 | if block_size == 0 || sample_rate == 0 { 61 | return Err(anyhow!( 62 | "The camera {} does not support talk with adpcm", 63 | camera_config.name 64 | )); 65 | } 66 | 67 | let rx = match (&opt.file_path, &opt.microphone) { 68 | (Some(path), false) => gst::from_input( 69 | &format!( 70 | "filesrc location={}", 71 | path.to_str().expect("File path not UTF8 complient") 72 | ), 73 | opt.volume, 74 | block_size, 75 | sample_rate, 76 | ) 77 | .with_context(|| format!("Failed to setup gst with the file: {:?}", path))?, 78 | (None, true) => gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate) 79 | .context("Failed to setup gst using the microphone")?, 80 | _ => unreachable!(), 81 | }; 82 | 83 | camera 84 | .talk_stream(rx, talk_config) 85 | .context("Talk stream ended early")?; 86 | 87 | Ok(()) 88 | } 89 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | //! Contains code that is not specific to any of the subcommands 2 | //! 3 | use log::*; 4 | 5 | use super::config::{CameraConfig, Config}; 6 | use anyhow::{anyhow, Context, Error, Result}; 7 | use neolink_core::bc_protocol::BcCamera; 8 | use std::fmt::{Display, Error as FmtError, Formatter}; 9 | 10 | pub(crate) enum AddressOrUid { 11 | Address(String), 12 | Uid(String), 13 | } 14 | 15 | impl Display for AddressOrUid { 16 | fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { 17 | match self { 18 | AddressOrUid::Address(host) => write!(f, "Address: {}", host), 19 | AddressOrUid::Uid(host) => write!(f, "UID: {}", host), 20 | } 21 | } 22 | } 23 | 24 | impl AddressOrUid { 25 | // Created by translating the config fields directly 26 | pub(crate) fn new(address: &Option, uid: &Option) -> Result { 27 | match (address, uid) { 28 | (None, None) => Err(anyhow!("Neither address or uid given")), 29 | (Some(_), Some(_)) => Err(anyhow!("Either address or uid should be given not both")), 30 | (Some(host), None) => Ok(AddressOrUid::Address(host.clone())), 31 | (None, Some(host)) => Ok(AddressOrUid::Uid(host.clone())), 32 | } 33 | } 34 | 35 | // Convience method to get the BcCamera with the appropiate method 36 | pub(crate) fn connect_camera(&self, channel_id: u8) -> Result { 37 | match self { 38 | AddressOrUid::Address(host) => Ok(BcCamera::new_with_addr(host, channel_id)?), 39 | AddressOrUid::Uid(host) => Ok(BcCamera::new_with_uid(host, channel_id)?), 40 | } 41 | } 42 | } 43 | 44 | pub(crate) fn find_and_connect(config: &Config, name: &str) -> Result { 45 | let camera_config = find_camera_by_name(config, name)?; 46 | connect_and_login(camera_config) 47 | } 48 | 49 | pub(crate) fn connect_and_login(camera_config: &CameraConfig) -> Result { 50 | let camera_addr = 51 | AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); 52 | info!( 53 | "{}: Connecting to camera at {}", 54 | camera_config.name, camera_addr 55 | ); 56 | 57 | let mut camera = camera_addr 58 | .connect_camera(camera_config.channel_id) 59 | .with_context(|| { 60 | format!( 61 | "Failed to connect to camera {} at {} on channel {}", 62 | camera_config.name, camera_addr, camera_config.channel_id 63 | ) 64 | })?; 65 | 66 | info!("{}: Logging in", camera_config.name); 67 | camera 68 | .login(&camera_config.username, camera_config.password.as_deref()) 69 | .with_context(|| format!("Failed to login to {}", camera_config.name))?; 70 | 71 | info!("{}: Connected and logged in", camera_config.name); 72 | 73 | Ok(camera) 74 | } 75 | 76 | pub(crate) fn find_camera_by_name<'a, 'b>( 77 | config: &'a Config, 78 | name: &'b str, 79 | ) -> Result<&'a CameraConfig> { 80 | config 81 | .cameras 82 | .iter() 83 | .find(|c| c.name == name) 84 | .ok_or_else(|| anyhow!("Camera {} not found in the config file", name)) 85 | } 86 | --------------------------------------------------------------------------------