Merge branch 'master' of github.com:thirtythreeforty/neolink into motion_stream
This commit is contained in:
20 files changed
+211
-421
No files matched your search
@@ -273,6 +273,47 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
// This is an 0xdd03 encryption from an Argus 2
|
||||
//
|
||||
// It is currently unsupported
|
||||
fn test_03_enc_login() {
|
||||
let sample = include_bytes!("samples/battery_enc.bin");
|
||||
|
||||
let encryption_protocol =
|
||||
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
|
||||
let mut context = BcContext::new(encryption_protocol);
|
||||
|
||||
let (buf, header) = bc_header(&sample[..]).unwrap();
|
||||
assert!(bc_body(&mut context, &header, buf).is_err());
|
||||
// It should error because we don't support it
|
||||
//
|
||||
// The following would be its contents if we
|
||||
// did support it (maybe one day :) left it here
|
||||
// for then)
|
||||
//
|
||||
//
|
||||
// let (_, body) = bc_body(&mut context, &header, buf).unwrap();
|
||||
// assert_eq!(header.msg_id, 1);
|
||||
// assert_eq!(header.body_len, 175);
|
||||
// assert_eq!(header.channel_id, 0);
|
||||
// assert_eq!(header.stream_type, 0);
|
||||
// assert_eq!(header.payload_offset, None);
|
||||
// assert_eq!(header.response_code, 0xdd03);
|
||||
// assert_eq!(header.class, 0x6614);
|
||||
// match body {
|
||||
// BcBody::ModernMsg(ModernMsg {
|
||||
// payload:
|
||||
// Some(BcPayloads::BcXml(BcXml {
|
||||
// encryption: Some(encryption),
|
||||
// ..
|
||||
// })),
|
||||
// ..
|
||||
// }) => assert_eq!(encryption.nonce, "0-AhnEZyUg6eKrJFIWgXPF"),
|
||||
// _ => panic!(),
|
||||
// }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bc_legacy_login() {
|
||||
let sample = include_bytes!("samples/model_sample_legacy_login.bin");
|
||||
|
||||
Binary file not shown.
@@ -35,7 +35,7 @@ impl BcCamera {
|
||||
channel_id: self.channel_id,
|
||||
msg_num: self.new_message_num(),
|
||||
stream_type: 0,
|
||||
response_code: 0xdc03,
|
||||
response_code: 0xdc02,
|
||||
class: 0x6514,
|
||||
},
|
||||
body: BcBody::LegacyMsg(LegacyMsg::LoginMsg {
|
||||
|
||||
@@ -96,8 +96,8 @@ fn bcmedia(buf: &[u8]) -> IResult<&[u8], BcMedia> {
|
||||
*x,
|
||||
MAGIC_HEADER_BCMEDIA_INFO_V1
|
||||
| MAGIC_HEADER_BCMEDIA_INFO_V2
|
||||
| MAGIC_HEADER_BCMEDIA_IFRAME
|
||||
| MAGIC_HEADER_BCMEDIA_PFRAME
|
||||
| MAGIC_HEADER_BCMEDIA_IFRAME..=MAGIC_HEADER_BCMEDIA_IFRAME_LAST
|
||||
| MAGIC_HEADER_BCMEDIA_PFRAME..=MAGIC_HEADER_BCMEDIA_PFRAME_LAST
|
||||
| MAGIC_HEADER_BCMEDIA_AAC
|
||||
| MAGIC_HEADER_BCMEDIA_ADPCM
|
||||
)
|
||||
@@ -112,11 +112,11 @@ fn bcmedia(buf: &[u8]) -> IResult<&[u8], BcMedia> {
|
||||
let (buf, payload) = bcmedia_info_v2(buf)?;
|
||||
Ok((buf, BcMedia::InfoV2(payload)))
|
||||
}
|
||||
MAGIC_HEADER_BCMEDIA_IFRAME => {
|
||||
MAGIC_HEADER_BCMEDIA_IFRAME..=MAGIC_HEADER_BCMEDIA_IFRAME_LAST => {
|
||||
let (buf, payload) = bcmedia_iframe(buf)?;
|
||||
Ok((buf, BcMedia::Iframe(payload)))
|
||||
}
|
||||
MAGIC_HEADER_BCMEDIA_PFRAME => {
|
||||
MAGIC_HEADER_BCMEDIA_PFRAME..=MAGIC_HEADER_BCMEDIA_PFRAME_LAST => {
|
||||
let (buf, payload) = bcmedia_pframe(buf)?;
|
||||
Ok((buf, BcMedia::Pframe(payload)))
|
||||
}
|
||||
|
||||
@@ -103,7 +103,9 @@ pub struct BcMediaInfoV2 {
|
||||
// unknown: u16
|
||||
}
|
||||
|
||||
// IFrame magics include the channel number in them
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME: u32 = 0x63643030;
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME_LAST: u32 = 0x63643039;
|
||||
|
||||
/// Video Types for I/PFrame
|
||||
#[derive(Debug)]
|
||||
@@ -132,7 +134,9 @@ pub struct BcMediaIframe {
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
// PFrame magics include the channel number in them
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME: u32 = 0x63643130;
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME_LAST: u32 = 0x63643139;
|
||||
|
||||
/// This is a BcMedia video PFrame.
|
||||
#[derive(Debug)]
|
||||
|
||||
+6
-2
@@ -3,9 +3,13 @@ use structopt::{clap::AppSettings, StructOpt};
|
||||
|
||||
/// A standards-compliant bridge to Reolink IP cameras
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(name = "neolink", setting(AppSettings::ArgRequiredElseHelp))]
|
||||
#[structopt(
|
||||
name = "neolink",
|
||||
setting(AppSettings::ArgRequiredElseHelp),
|
||||
setting(AppSettings::UnifiedHelpMessage)
|
||||
)]
|
||||
pub struct Opt {
|
||||
#[structopt(short, long, parse(from_os_str))]
|
||||
#[structopt(short, long, global(true), parse(from_os_str))]
|
||||
pub config: Option<PathBuf>,
|
||||
#[structopt(subcommand)]
|
||||
pub cmd: Option<Command>,
|
||||
|
||||
File renamed without changes.
+27
-17
@@ -7,12 +7,15 @@
|
||||
//! It contains sub commands for running an rtsp proxy which can be used on Reolink cameras
|
||||
//! that do not nativly support RTSP.
|
||||
//!
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context, Result};
|
||||
use env_logger::Env;
|
||||
use log::*;
|
||||
use std::fs;
|
||||
use structopt::StructOpt;
|
||||
use validator::Validate;
|
||||
|
||||
mod cmdline;
|
||||
mod config;
|
||||
mod reboot;
|
||||
mod rtsp;
|
||||
mod statusled;
|
||||
@@ -20,6 +23,7 @@ mod talk;
|
||||
mod utils;
|
||||
|
||||
use cmdline::{Command, Opt};
|
||||
use config::Config;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
|
||||
@@ -32,30 +36,36 @@ fn main() -> Result<()> {
|
||||
|
||||
let opt = Opt::from_args();
|
||||
|
||||
match (opt.cmd, opt.config) {
|
||||
(None, None) => {
|
||||
// Should be caught at the clap validation
|
||||
unreachable!();
|
||||
}
|
||||
(None, Some(config)) => {
|
||||
let conf_path = opt.config.context("Must supply --config file")?;
|
||||
let config: Config = toml::from_str(
|
||||
&fs::read_to_string(&conf_path)
|
||||
.with_context(|| format!("Failed to read {:?}", conf_path))?,
|
||||
)
|
||||
.with_context(|| format!("Failed to parse the {:?} config file", conf_path))?;
|
||||
|
||||
config
|
||||
.validate()
|
||||
.with_context(|| format!("Failed to validate the {:?} config file", conf_path))?;
|
||||
|
||||
match opt.cmd {
|
||||
None => {
|
||||
warn!(
|
||||
"Deprecated command line option. Please use: `neolink rtsp --config={:?}`",
|
||||
config
|
||||
);
|
||||
rtsp::main(rtsp::Opt { config })?;
|
||||
rtsp::main(rtsp::Opt {}, config)?;
|
||||
}
|
||||
(Some(_), Some(_)) => error!("--config should be given after the subcommand"),
|
||||
(Some(Command::Rtsp(opts)), None) => {
|
||||
rtsp::main(opts)?;
|
||||
Some(Command::Rtsp(opts)) => {
|
||||
rtsp::main(opts, config)?;
|
||||
}
|
||||
(Some(Command::StatusLight(opts)), None) => {
|
||||
statusled::main(opts)?;
|
||||
Some(Command::StatusLight(opts)) => {
|
||||
statusled::main(opts, config)?;
|
||||
}
|
||||
(Some(Command::Reboot(opts)), None) => {
|
||||
reboot::main(opts)?;
|
||||
Some(Command::Reboot(opts)) => {
|
||||
reboot::main(opts, config)?;
|
||||
}
|
||||
(Some(Command::Talk(opts)), None) => {
|
||||
talk::main(opts)?;
|
||||
Some(Command::Talk(opts)) => {
|
||||
talk::main(opts, config)?;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
use std::path::PathBuf;
|
||||
use structopt::StructOpt;
|
||||
|
||||
/// The reboot command will reboot the camera
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct Opt {
|
||||
/// The path to the config file
|
||||
#[structopt(short, long, parse(from_os_str))]
|
||||
pub config: PathBuf,
|
||||
/// The name of the camera to change the lights of. Must be a name in the config
|
||||
pub camera: String,
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
use serde::Deserialize;
|
||||
use std::clone::Clone;
|
||||
use validator::{Validate, ValidationError};
|
||||
use validator_derive::Validate;
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct Config {
|
||||
#[validate]
|
||||
pub(crate) cameras: Vec<CameraConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
#[validate(schema(function = "validate_camera_config"))]
|
||||
pub(crate) struct CameraConfig {
|
||||
pub(crate) name: String,
|
||||
|
||||
#[serde(rename = "address")]
|
||||
pub(crate) camera_addr: Option<String>,
|
||||
|
||||
#[serde(rename = "uid")]
|
||||
pub(crate) camera_uid: Option<String>,
|
||||
|
||||
pub(crate) username: String,
|
||||
pub(crate) password: Option<String>,
|
||||
|
||||
#[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))]
|
||||
#[serde(default = "default_channel_id")]
|
||||
pub(crate) channel_id: u8,
|
||||
}
|
||||
|
||||
fn default_channel_id() -> u8 {
|
||||
0
|
||||
}
|
||||
|
||||
fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> {
|
||||
match (&camera_config.camera_addr, &camera_config.camera_uid) {
|
||||
(None, None) => Err(ValidationError::new(
|
||||
"Either camera address or uid must be given",
|
||||
)),
|
||||
(Some(_), Some(_)) => Err(ValidationError::new(
|
||||
"Must provide either camera address or uid not both",
|
||||
)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
+9
-59
@@ -11,72 +11,22 @@
|
||||
/// neolink reboot --config=config.toml CameraName
|
||||
/// ```
|
||||
///
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use log::*;
|
||||
use std::fs;
|
||||
use validator::Validate;
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
mod cmdline;
|
||||
mod config;
|
||||
|
||||
use crate::utils::AddressOrUid;
|
||||
use super::config::Config;
|
||||
use crate::utils::find_and_connect;
|
||||
pub(crate) use cmdline::Opt;
|
||||
use config::Config;
|
||||
|
||||
/// Entry point for the reboot subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub fn main(opt: Opt) -> Result<()> {
|
||||
let config: Config = toml::from_str(
|
||||
&fs::read_to_string(&opt.config)
|
||||
.with_context(|| format!("Failed to read {:?}", &opt.config))?,
|
||||
)
|
||||
.with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?;
|
||||
pub(crate) fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
let camera = find_and_connect(&config, &opt.camera)?;
|
||||
|
||||
config
|
||||
.validate()
|
||||
.with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?;
|
||||
|
||||
let mut cam_found = false;
|
||||
for camera_config in &config.cameras {
|
||||
if opt.camera == camera_config.name {
|
||||
cam_found = true;
|
||||
let camera_addr =
|
||||
AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap();
|
||||
info!(
|
||||
"{}: Connecting to camera at {}",
|
||||
camera_config.name, camera_addr
|
||||
);
|
||||
|
||||
let mut camera = camera_addr
|
||||
.connect_camera(camera_config.channel_id)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to connect to camera {} at {} on channel {}",
|
||||
camera_config.name, camera_addr, camera_config.channel_id
|
||||
)
|
||||
})?;
|
||||
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera
|
||||
.login(&camera_config.username, camera_config.password.as_deref())
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
|
||||
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
camera
|
||||
.reboot()
|
||||
.context("Could not send reboot command to the camera")?;
|
||||
}
|
||||
}
|
||||
|
||||
if !cam_found {
|
||||
Err(anyhow!(
|
||||
"Camera {} was not in the config file {:?}",
|
||||
&opt.camera,
|
||||
&opt.config
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
camera
|
||||
.reboot()
|
||||
.context("Could not send reboot command to the camera")?;
|
||||
Ok(())
|
||||
}
|
||||
+1
-6
@@ -1,10 +1,5 @@
|
||||
use std::path::PathBuf;
|
||||
use structopt::StructOpt;
|
||||
|
||||
/// The rtsp command will serve all cameras in the config over the rtsp protocol
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct Opt {
|
||||
/// The path to the config file
|
||||
#[structopt(short, long, parse(from_os_str))]
|
||||
pub config: PathBuf,
|
||||
}
|
||||
pub struct Opt {}
|
||||
+2
-15
@@ -32,21 +32,18 @@ use anyhow::{Context, Result};
|
||||
use log::*;
|
||||
use neolink_core::bc_protocol::{BcCamera, Stream};
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use validator::Validate;
|
||||
|
||||
mod abort;
|
||||
mod cmdline;
|
||||
mod config;
|
||||
mod gst;
|
||||
mod motion;
|
||||
mod state;
|
||||
|
||||
use super::config::{CameraConfig, Config, UserConfig};
|
||||
use crate::utils::AddressOrUid;
|
||||
pub(crate) use cmdline::Opt;
|
||||
use config::{CameraConfig, Config, UserConfig};
|
||||
use gst::{GstOutputs, InputMode, PausedSources, RtspServer, TlsAuthenticationMode};
|
||||
use motion::MotionStream;
|
||||
use state::States;
|
||||
@@ -54,17 +51,7 @@ use state::States;
|
||||
/// Entry point for the rtsp subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub fn main(opt: Opt) -> Result<()> {
|
||||
let config: Config = toml::from_str(
|
||||
&fs::read_to_string(&opt.config)
|
||||
.with_context(|| format!("Failed to read {:?}", &opt.config))?,
|
||||
)
|
||||
.with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?;
|
||||
|
||||
config
|
||||
.validate()
|
||||
.with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?;
|
||||
|
||||
pub(crate) fn main(_opt: Opt, config: Config) -> Result<()> {
|
||||
let rtsp = &RtspServer::new();
|
||||
|
||||
set_up_tls(&config, rtsp);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use std::path::PathBuf;
|
||||
use structopt::StructOpt;
|
||||
|
||||
fn onoff_parse(src: &str) -> Result<bool> {
|
||||
@@ -16,9 +15,6 @@ fn onoff_parse(src: &str) -> Result<bool> {
|
||||
/// The status-light command will control the blue status light on the camera
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct Opt {
|
||||
/// The path to the config file
|
||||
#[structopt(short, long, parse(from_os_str))]
|
||||
pub config: PathBuf,
|
||||
/// The name of the camera to change the lights of. Must be a name in the config
|
||||
pub camera: String,
|
||||
/// Whether to turn the light on or off
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
use serde::Deserialize;
|
||||
use std::clone::Clone;
|
||||
use validator::{Validate, ValidationError};
|
||||
use validator_derive::Validate;
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct Config {
|
||||
#[validate]
|
||||
pub(crate) cameras: Vec<CameraConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
#[validate(schema(function = "validate_camera_config"))]
|
||||
pub(crate) struct CameraConfig {
|
||||
pub(crate) name: String,
|
||||
|
||||
#[serde(rename = "address")]
|
||||
pub(crate) camera_addr: Option<String>,
|
||||
|
||||
#[serde(rename = "uid")]
|
||||
pub(crate) camera_uid: Option<String>,
|
||||
|
||||
pub(crate) username: String,
|
||||
pub(crate) password: Option<String>,
|
||||
|
||||
#[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))]
|
||||
#[serde(default = "default_channel_id")]
|
||||
pub(crate) channel_id: u8,
|
||||
}
|
||||
|
||||
fn default_channel_id() -> u8 {
|
||||
0
|
||||
}
|
||||
|
||||
fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> {
|
||||
match (&camera_config.camera_addr, &camera_config.camera_uid) {
|
||||
(None, None) => Err(ValidationError::new(
|
||||
"Either camera address or uid must be given",
|
||||
)),
|
||||
(Some(_), Some(_)) => Err(ValidationError::new(
|
||||
"Must provide either camera address or uid not both",
|
||||
)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
+9
-60
@@ -15,73 +15,22 @@
|
||||
/// neolink status-light --config=config.toml CameraName off
|
||||
/// ```
|
||||
///
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use log::*;
|
||||
use std::fs;
|
||||
use validator::Validate;
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
mod cmdline;
|
||||
mod config;
|
||||
|
||||
use crate::utils::AddressOrUid;
|
||||
use super::config::Config;
|
||||
use crate::utils::find_and_connect;
|
||||
pub(crate) use cmdline::Opt;
|
||||
use config::Config;
|
||||
|
||||
/// Entry point for the ledstatus subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub fn main(opt: Opt) -> Result<()> {
|
||||
let config: Config = toml::from_str(
|
||||
&fs::read_to_string(&opt.config)
|
||||
.with_context(|| format!("Failed to read {:?}", &opt.config))?,
|
||||
)
|
||||
.with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?;
|
||||
pub(crate) fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
let mut camera = find_and_connect(&config, &opt.camera)?;
|
||||
|
||||
config
|
||||
.validate()
|
||||
.with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?;
|
||||
|
||||
let mut cam_found = false;
|
||||
for camera_config in &config.cameras {
|
||||
if opt.camera == camera_config.name {
|
||||
cam_found = true;
|
||||
|
||||
let camera_addr =
|
||||
AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap();
|
||||
info!(
|
||||
"{}: Connecting to camera at {}",
|
||||
camera_config.name, camera_addr
|
||||
);
|
||||
|
||||
let mut camera = camera_addr
|
||||
.connect_camera(camera_config.channel_id)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to connect to camera {} at {} on channel {}",
|
||||
camera_config.name, camera_addr, camera_config.channel_id
|
||||
)
|
||||
})?;
|
||||
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera
|
||||
.login(&camera_config.username, camera_config.password.as_deref())
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
|
||||
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
camera
|
||||
.led_light_set(opt.on)
|
||||
.context("Unable to set camera light state")?;
|
||||
}
|
||||
}
|
||||
|
||||
if !cam_found {
|
||||
Err(anyhow!(
|
||||
"Camera {} was not in the config file {:?}",
|
||||
&opt.camera,
|
||||
&opt.config
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
camera
|
||||
.led_light_set(opt.on)
|
||||
.context("Unable to set camera light state")?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -9,9 +9,6 @@ use structopt::StructOpt;
|
||||
/// `gst-launch` can be used to prepare this data
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct Opt {
|
||||
/// The path to the config file
|
||||
#[structopt(short, long, parse(from_os_str))]
|
||||
pub config: PathBuf,
|
||||
/// The name of the camera to change the lights of. Must be a name in the config
|
||||
pub camera: String,
|
||||
/// The path to the audio file.
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
use serde::Deserialize;
|
||||
use std::clone::Clone;
|
||||
use validator::{Validate, ValidationError};
|
||||
use validator_derive::Validate;
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct Config {
|
||||
#[validate]
|
||||
pub(crate) cameras: Vec<CameraConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
#[validate(schema(function = "validate_camera_config"))]
|
||||
pub(crate) struct CameraConfig {
|
||||
pub(crate) name: String,
|
||||
|
||||
#[serde(rename = "address")]
|
||||
pub(crate) camera_addr: Option<String>,
|
||||
|
||||
#[serde(rename = "uid")]
|
||||
pub(crate) camera_uid: Option<String>,
|
||||
|
||||
pub(crate) username: String,
|
||||
pub(crate) password: Option<String>,
|
||||
|
||||
#[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))]
|
||||
#[serde(default = "default_channel_id")]
|
||||
pub(crate) channel_id: u8,
|
||||
}
|
||||
|
||||
fn default_channel_id() -> u8 {
|
||||
0
|
||||
}
|
||||
|
||||
fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> {
|
||||
match (&camera_config.camera_addr, &camera_config.camera_uid) {
|
||||
(None, None) => Err(ValidationError::new(
|
||||
"Either camera address or uid must be given",
|
||||
)),
|
||||
(Some(_), Some(_)) => Err(ValidationError::new(
|
||||
"Must provide either camera address or uid not both",
|
||||
)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
+60
-110
@@ -8,131 +8,81 @@
|
||||
/// # Usage
|
||||
///
|
||||
/// ```bash
|
||||
/// neolink status-light --config=config.toml --adpcm-file=data.adpcm --sample-rate=16000 --block-size=512 CameraName
|
||||
/// neolink talk --config=config.toml --adpcm-file=data.adpcm --sample-rate=16000 --block-size=512 CameraName
|
||||
/// ```
|
||||
///
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use log::*;
|
||||
use neolink_core::bc::xml::TalkConfig;
|
||||
use std::fs;
|
||||
use validator::Validate;
|
||||
|
||||
mod cmdline;
|
||||
mod config;
|
||||
mod gst;
|
||||
|
||||
use crate::utils::AddressOrUid;
|
||||
use super::config::Config;
|
||||
use crate::utils::{connect_and_login, find_camera_by_name};
|
||||
pub(crate) use cmdline::Opt;
|
||||
use config::Config;
|
||||
|
||||
/// Entry point for the talk subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub fn main(opt: Opt) -> Result<()> {
|
||||
let config: Config = toml::from_str(
|
||||
&fs::read_to_string(&opt.config)
|
||||
.with_context(|| format!("Failed to read {:?}", &opt.config))?,
|
||||
)
|
||||
.with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?;
|
||||
pub(crate) fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
let camera_config = find_camera_by_name(&config, &opt.camera)?;
|
||||
let camera = connect_and_login(camera_config)?;
|
||||
|
||||
config
|
||||
.validate()
|
||||
.with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?;
|
||||
|
||||
let mut cam_found = false;
|
||||
for camera_config in &config.cameras {
|
||||
if opt.camera == camera_config.name {
|
||||
cam_found = true;
|
||||
let camera_addr =
|
||||
AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_addr).unwrap();
|
||||
info!(
|
||||
"{}: Connecting to camera at {}",
|
||||
camera_config.name, camera_addr
|
||||
);
|
||||
|
||||
let mut camera = camera_addr
|
||||
.connect_camera(camera_config.channel_id)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to connect to camera {} at {} on channel {}",
|
||||
camera_config.name, camera_addr, camera_config.channel_id
|
||||
)
|
||||
})?;
|
||||
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera
|
||||
.login(&camera_config.username, camera_config.password.as_deref())
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
|
||||
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
let talk_ability = camera
|
||||
.talk_ability()
|
||||
.with_context(|| format!("Camera {} does not support talk", camera_config.name))?;
|
||||
if talk_ability.duplex_list.is_empty()
|
||||
|| talk_ability.audio_stream_mode_list.is_empty()
|
||||
|| talk_ability.audio_config_list.is_empty()
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"Camera {} does not support talk",
|
||||
camera_config.name
|
||||
));
|
||||
}
|
||||
|
||||
// Just copy that data from the first talk ability in the config have never seen more
|
||||
// than one ability
|
||||
let config = 0;
|
||||
|
||||
let talk_config = TalkConfig {
|
||||
channel_id: camera_config.channel_id,
|
||||
duplex: talk_ability.duplex_list[config].duplex.clone(),
|
||||
audio_stream_mode: talk_ability.audio_stream_mode_list[config]
|
||||
.audio_stream_mode
|
||||
.clone(),
|
||||
audio_config: talk_ability.audio_config_list[config].audio_config.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let block_size = (talk_config.audio_config.length_per_encoder / 2) + 4;
|
||||
let sample_rate = talk_config.audio_config.sample_rate;
|
||||
if block_size == 0 || sample_rate == 0 {
|
||||
return Err(anyhow!(
|
||||
"The camera {} does not support talk with adpcm",
|
||||
camera_config.name
|
||||
));
|
||||
}
|
||||
|
||||
let rx = match (&opt.file_path, &opt.microphone) {
|
||||
(Some(path), false) => gst::from_input(
|
||||
&format!(
|
||||
"filesrc location={}",
|
||||
path.to_str().expect("File path not UTF8 complient")
|
||||
),
|
||||
opt.volume,
|
||||
block_size,
|
||||
sample_rate,
|
||||
)
|
||||
.with_context(|| format!("Failed to setup gst with the file: {:?}", path))?,
|
||||
(None, true) => {
|
||||
gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate)
|
||||
.context("Failed to setup gst using the microphone")?
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
camera
|
||||
.talk_stream(rx, talk_config)
|
||||
.context("Talk stream ended early")?;
|
||||
}
|
||||
let talk_ability = camera
|
||||
.talk_ability()
|
||||
.with_context(|| format!("Camera {} does not support talk", camera_config.name))?;
|
||||
if talk_ability.duplex_list.is_empty()
|
||||
|| talk_ability.audio_stream_mode_list.is_empty()
|
||||
|| talk_ability.audio_config_list.is_empty()
|
||||
{
|
||||
return Err(anyhow!(
|
||||
"Camera {} does not support talk",
|
||||
camera_config.name
|
||||
));
|
||||
}
|
||||
|
||||
if !cam_found {
|
||||
Err(anyhow!(
|
||||
"Camera {} was not in the config file {:?}",
|
||||
&opt.camera,
|
||||
&opt.config
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
// Just copy that data from the first talk ability in the config have never seen more
|
||||
// than one ability
|
||||
let config = 0;
|
||||
|
||||
let talk_config = TalkConfig {
|
||||
channel_id: camera_config.channel_id,
|
||||
duplex: talk_ability.duplex_list[config].duplex.clone(),
|
||||
audio_stream_mode: talk_ability.audio_stream_mode_list[config]
|
||||
.audio_stream_mode
|
||||
.clone(),
|
||||
audio_config: talk_ability.audio_config_list[config].audio_config.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let block_size = (talk_config.audio_config.length_per_encoder / 2) + 4;
|
||||
let sample_rate = talk_config.audio_config.sample_rate;
|
||||
if block_size == 0 || sample_rate == 0 {
|
||||
return Err(anyhow!(
|
||||
"The camera {} does not support talk with adpcm",
|
||||
camera_config.name
|
||||
));
|
||||
}
|
||||
|
||||
let rx = match (&opt.file_path, &opt.microphone) {
|
||||
(Some(path), false) => gst::from_input(
|
||||
&format!(
|
||||
"filesrc location={}",
|
||||
path.to_str().expect("File path not UTF8 complient")
|
||||
),
|
||||
opt.volume,
|
||||
block_size,
|
||||
sample_rate,
|
||||
)
|
||||
.with_context(|| format!("Failed to setup gst with the file: {:?}", path))?,
|
||||
(None, true) => gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate)
|
||||
.context("Failed to setup gst using the microphone")?,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
camera
|
||||
.talk_stream(rx, talk_config)
|
||||
.context("Talk stream ended early")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+47
-1
@@ -1,6 +1,9 @@
|
||||
//! Contains code that is not specific to any of the subcommands
|
||||
//!
|
||||
use anyhow::{anyhow, Error};
|
||||
use log::*;
|
||||
|
||||
use super::config::{CameraConfig, Config};
|
||||
use anyhow::{anyhow, Context, Error, Result};
|
||||
use neolink_core::bc_protocol::BcCamera;
|
||||
use std::fmt::{Display, Error as FmtError, Formatter};
|
||||
|
||||
@@ -37,3 +40,46 @@ impl AddressOrUid {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn find_and_connect(config: &Config, name: &str) -> Result<BcCamera> {
|
||||
let camera_config = find_camera_by_name(config, name)?;
|
||||
connect_and_login(camera_config)
|
||||
}
|
||||
|
||||
pub(crate) fn connect_and_login(camera_config: &CameraConfig) -> Result<BcCamera> {
|
||||
let camera_addr =
|
||||
AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap();
|
||||
info!(
|
||||
"{}: Connecting to camera at {}",
|
||||
camera_config.name, camera_addr
|
||||
);
|
||||
|
||||
let mut camera = camera_addr
|
||||
.connect_camera(camera_config.channel_id)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to connect to camera {} at {} on channel {}",
|
||||
camera_config.name, camera_addr, camera_config.channel_id
|
||||
)
|
||||
})?;
|
||||
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera
|
||||
.login(&camera_config.username, camera_config.password.as_deref())
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
|
||||
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
Ok(camera)
|
||||
}
|
||||
|
||||
pub(crate) fn find_camera_by_name<'a, 'b>(
|
||||
config: &'a Config,
|
||||
name: &'b str,
|
||||
) -> Result<&'a CameraConfig> {
|
||||
config
|
||||
.cameras
|
||||
.iter()
|
||||
.find(|c| c.name == name)
|
||||
.ok_or_else(|| anyhow!("Camera {} not found in the config file", name))
|
||||
}
|
||||
Reference in new issue
Block a user