Merge branch 'master' of github.com:thirtythreeforty/neolink into motion
This commit is contained in:
27 files changed
+875
-605
No files matched your search
+6
-3
@@ -1,11 +1,14 @@
|
||||
use structopt::StructOpt;
|
||||
use std::path::PathBuf;
|
||||
use structopt::{clap::AppSettings, StructOpt};
|
||||
|
||||
/// A standards-compliant bridge to Reolink IP cameras
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(name = "neolink")]
|
||||
#[structopt(name = "neolink", setting(AppSettings::ArgRequiredElseHelp))]
|
||||
pub struct Opt {
|
||||
#[structopt(short, long, parse(from_os_str))]
|
||||
pub config: Option<PathBuf>,
|
||||
#[structopt(subcommand)]
|
||||
pub cmd: Command,
|
||||
pub cmd: Option<Command>,
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
use err_derive::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum Error {
|
||||
#[error(display = "RTSP Error")]
|
||||
Rtsp(#[error(source)] super::rtsp::Error),
|
||||
#[error(display = "Status LED Error")]
|
||||
StatusLight(#[error(source)] super::statusled::Error),
|
||||
#[error(display = "Reboot Error")]
|
||||
Reboot(#[error(source)] super::reboot::Error),
|
||||
#[error(display = "Talk Error")]
|
||||
Talk(#[error(source)] super::talk::Error),
|
||||
}
|
||||
+19
-8
@@ -7,21 +7,20 @@
|
||||
//! 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 env_logger::Env;
|
||||
use log::*;
|
||||
use structopt::StructOpt;
|
||||
|
||||
mod cmdline;
|
||||
mod errors;
|
||||
mod reboot;
|
||||
mod rtsp;
|
||||
mod statusled;
|
||||
mod talk;
|
||||
|
||||
use cmdline::{Command, Opt};
|
||||
use errors::Error;
|
||||
|
||||
fn main() -> Result<(), Error> {
|
||||
fn main() -> Result<()> {
|
||||
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
|
||||
|
||||
info!(
|
||||
@@ -32,17 +31,29 @@ fn main() -> Result<(), Error> {
|
||||
|
||||
let opt = Opt::from_args();
|
||||
|
||||
match opt.cmd {
|
||||
Command::Rtsp(opts) => {
|
||||
match (opt.cmd, opt.config) {
|
||||
(None, None) => {
|
||||
// Should be caught at the clap validation
|
||||
unreachable!();
|
||||
}
|
||||
(None, Some(config)) => {
|
||||
warn!(
|
||||
"Deprecated command line option. Please use: `neolink rtsp --config={:?}`",
|
||||
config
|
||||
);
|
||||
rtsp::main(rtsp::Opt { config })?;
|
||||
}
|
||||
(Some(_), Some(_)) => error!("--config should be given after the subcommand"),
|
||||
(Some(Command::Rtsp(opts)), None) => {
|
||||
rtsp::main(opts)?;
|
||||
}
|
||||
Command::StatusLight(opts) => {
|
||||
(Some(Command::StatusLight(opts)), None) => {
|
||||
statusled::main(opts)?;
|
||||
}
|
||||
Command::Reboot(opts) => {
|
||||
(Some(Command::Reboot(opts)), None) => {
|
||||
reboot::main(opts)?;
|
||||
}
|
||||
Command::Talk(opts) => {
|
||||
(Some(Command::Talk(opts)), None) => {
|
||||
talk::main(opts)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
use err_derive::Error;
|
||||
|
||||
/// The main error for the reboot subcommand
|
||||
#[derive(Debug, Error)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum Error {
|
||||
/// Raised when the config file fails to deserlize
|
||||
#[error(display = "Configuration parsing error")]
|
||||
Config(#[error(source)] toml::de::Error),
|
||||
/// Raised when `neolink_core` raises an error
|
||||
#[error(display = "Communication error")]
|
||||
Protocol(#[error(source)] neolink_core::Error),
|
||||
/// Raised when there is an IO error such as unable to find
|
||||
/// config file
|
||||
#[error(display = "I/O error")]
|
||||
Io(#[error(source)] std::io::Error),
|
||||
/// Raised when the config file fails validataion
|
||||
#[error(display = "Validation error")]
|
||||
Validation(#[error(source)] validator::ValidationErrors),
|
||||
}
|
||||
+30
-14
@@ -11,6 +11,7 @@
|
||||
/// neolink reboot --config=config.toml CameraName
|
||||
/// ```
|
||||
///
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use log::*;
|
||||
use neolink_core::bc_protocol::BcCamera;
|
||||
use std::fs;
|
||||
@@ -18,19 +19,23 @@ use validator::Validate;
|
||||
|
||||
mod cmdline;
|
||||
mod config;
|
||||
mod errors;
|
||||
|
||||
pub(crate) use cmdline::Opt;
|
||||
use config::Config;
|
||||
pub(crate) use errors::Error;
|
||||
|
||||
/// Entry point for the reboot subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?;
|
||||
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()?;
|
||||
config
|
||||
.validate()
|
||||
.with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?;
|
||||
|
||||
let mut cam_found = false;
|
||||
for camera_config in &config.cameras {
|
||||
@@ -42,23 +47,34 @@ pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
);
|
||||
|
||||
let mut camera =
|
||||
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
|
||||
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to connect to camera {} at {} on channel {}",
|
||||
camera_config.name, camera_config.camera_addr, camera_config.channel_id
|
||||
)
|
||||
})?;
|
||||
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera.login(&camera_config.username, camera_config.password.as_deref())?;
|
||||
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()?;
|
||||
camera
|
||||
.reboot()
|
||||
.context("Could not send reboot command to the camera")?;
|
||||
}
|
||||
}
|
||||
|
||||
if !cam_found {
|
||||
error!(
|
||||
"No camera with the name {} was found in the config",
|
||||
opt.camera
|
||||
);
|
||||
Err(anyhow!(
|
||||
"Camera {} was not in the config file {:?}",
|
||||
&opt.camera,
|
||||
&opt.config
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+2
-1
@@ -7,7 +7,8 @@ use validator::{Validate, ValidationError};
|
||||
use validator_derive::Validate;
|
||||
|
||||
lazy_static! {
|
||||
static ref RE_STREAM_SRC: Regex = Regex::new(r"^(mainStream|subStream|both)$").unwrap();
|
||||
static ref RE_STREAM_SRC: Regex =
|
||||
Regex::new(r"^(mainStream|subStream|externStream|both|all)$").unwrap();
|
||||
static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
use err_derive::Error;
|
||||
|
||||
/// The main error for the rtsp subcommand
|
||||
#[derive(Debug, Error)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum Error {
|
||||
/// Raised when the config file fails to deserlize
|
||||
#[error(display = "Configuration parsing error")]
|
||||
Config(#[error(source)] toml::de::Error),
|
||||
/// Raised when `neolink_core` raises an error
|
||||
#[error(display = "Communication error")]
|
||||
Protocol(#[error(source)] neolink_core::Error),
|
||||
/// Raised when there is an IO error such as unable to find
|
||||
/// config file
|
||||
#[error(display = "I/O error")]
|
||||
Io(#[error(source)] std::io::Error),
|
||||
/// Raised when the config file fails validataion
|
||||
#[error(display = "Validation error")]
|
||||
Validation(#[error(source)] validator::ValidationErrors),
|
||||
// Raised when there is an ADPCM decoding error
|
||||
// #[error(display = "ADPCM Decoding Error")]
|
||||
// AdpcmDecoding(&'static str),
|
||||
}
|
||||
+74
-35
@@ -28,8 +28,9 @@
|
||||
/// neolink rtsp --config=config.toml
|
||||
/// ```
|
||||
///
|
||||
use anyhow::{Context, Result};
|
||||
use log::*;
|
||||
use neolink_core::bc_protocol::BcCamera;
|
||||
use neolink_core::bc_protocol::{BcCamera, Stream};
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
@@ -41,21 +42,25 @@ use validator::Validate;
|
||||
mod cmdline;
|
||||
mod config;
|
||||
/// The errors this subcommand can raise
|
||||
mod errors;
|
||||
mod gst;
|
||||
|
||||
pub(crate) use cmdline::Opt;
|
||||
use config::{CameraConfig, Config, UserConfig};
|
||||
pub(crate) use errors::Error;
|
||||
use gst::{GstOutputs, RtspServer, TlsAuthenticationMode};
|
||||
|
||||
/// Entry point for the rtsp subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?;
|
||||
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()?;
|
||||
config
|
||||
.validate()
|
||||
.with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?;
|
||||
|
||||
let rtsp = &RtspServer::new();
|
||||
|
||||
@@ -83,7 +88,7 @@ pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
get_permitted_users(config.users.as_slice(), &arc_cam.permitted_users);
|
||||
|
||||
// Set up each main and substream according to all the RTSP mount paths we support
|
||||
if ["both", "mainStream"].iter().any(|&e| e == arc_cam.stream) {
|
||||
if ["all", "both", "mainStream"].iter().any(|&e| e == arc_cam.stream) {
|
||||
let paths = &[
|
||||
&*format!("/{}", arc_cam.name),
|
||||
&*format!("/{}/mainStream", arc_cam.name),
|
||||
@@ -92,16 +97,25 @@ pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
.add_stream(paths, &permitted_users)
|
||||
.unwrap();
|
||||
let main_camera = arc_cam.clone();
|
||||
s.spawn(move |_| camera_loop(&*main_camera, "mainStream", &mut outputs, true));
|
||||
s.spawn(move |_| camera_loop(&*main_camera, Stream::Main, &mut outputs, true));
|
||||
}
|
||||
if ["both", "subStream"].iter().any(|&e| e == arc_cam.stream) {
|
||||
if ["all", "both", "subStream"].iter().any(|&e| e == arc_cam.stream) {
|
||||
let paths = &[&*format!("/{}/subStream", arc_cam.name)];
|
||||
let mut outputs = rtsp
|
||||
.add_stream(paths, &permitted_users)
|
||||
.unwrap();
|
||||
let sub_camera = arc_cam.clone();
|
||||
let manage = arc_cam.stream == "subStream";
|
||||
s.spawn(move |_| camera_loop(&*sub_camera, "subStream", &mut outputs, manage));
|
||||
s.spawn(move |_| camera_loop(&*sub_camera, Stream::Sub, &mut outputs, manage));
|
||||
}
|
||||
if ["all", "externStream"].iter().any(|&e| e == arc_cam.stream) {
|
||||
let paths = &[&*format!("/{}/externStream", arc_cam.name)];
|
||||
let mut outputs = rtsp
|
||||
.add_stream(paths, &permitted_users)
|
||||
.unwrap();
|
||||
let sub_camera = arc_cam.clone();
|
||||
let manage = arc_cam.stream == "externStream";
|
||||
s.spawn(move |_| camera_loop(&*sub_camera, Stream::Extern, &mut outputs, manage));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,10 +128,10 @@ pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
|
||||
fn camera_loop(
|
||||
camera_config: &CameraConfig,
|
||||
stream_name: &str,
|
||||
stream_name: Stream,
|
||||
outputs: &mut GstOutputs,
|
||||
manage: bool,
|
||||
) -> Result<(), Error> {
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let min_backoff = Duration::from_secs(1);
|
||||
let max_backoff = Duration::from_secs(15);
|
||||
let mut current_backoff = min_backoff;
|
||||
@@ -130,25 +144,26 @@ fn camera_loop(
|
||||
if cam_err.connected {
|
||||
current_backoff = min_backoff;
|
||||
}
|
||||
match cam_err.err {
|
||||
neolink_core::Error::AuthFailed => {
|
||||
error!(
|
||||
"Authentication failed to camera {}, not retrying",
|
||||
camera_config.name
|
||||
);
|
||||
return Err(cam_err.err.into());
|
||||
}
|
||||
_ => error!(
|
||||
if cam_err.login_fail {
|
||||
error!(
|
||||
"Authentication failed to camera {}, not retrying",
|
||||
camera_config.name
|
||||
);
|
||||
return Err(cam_err.err);
|
||||
} else {
|
||||
error!(
|
||||
"Error streaming from camera {}, will retry in {}s: {:?}",
|
||||
camera_config.name,
|
||||
current_backoff.as_secs(),
|
||||
cam_err.err
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
std::thread::sleep(current_backoff);
|
||||
current_backoff = std::cmp::min(max_backoff, current_backoff * 2);
|
||||
} else {
|
||||
// Should not occur because we don't set the callback up
|
||||
// in such a way that it requests graceful shutdown
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
@@ -156,7 +171,8 @@ fn camera_loop(
|
||||
|
||||
struct CameraErr {
|
||||
connected: bool,
|
||||
err: neolink_core::Error,
|
||||
login_fail: bool,
|
||||
err: anyhow::Error,
|
||||
}
|
||||
|
||||
fn set_up_tls(config: &Config, rtsp: &RtspServer) {
|
||||
@@ -206,13 +222,22 @@ fn get_permitted_users<'a>(
|
||||
|
||||
fn camera_main(
|
||||
camera_config: &CameraConfig,
|
||||
stream_name: &str,
|
||||
stream_name: Stream,
|
||||
outputs: &mut GstOutputs,
|
||||
manage: bool,
|
||||
) -> Result<(), CameraErr> {
|
||||
let mut connected = false;
|
||||
let mut login_fail = false;
|
||||
(|| {
|
||||
let mut camera = BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
|
||||
let mut camera =
|
||||
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to connect to camera {} at {} on channel {}",
|
||||
camera_config.name, camera_config.camera_addr, camera_config.channel_id
|
||||
)
|
||||
})?;
|
||||
|
||||
if camera_config.timeout.is_some() {
|
||||
warn!("The undocumented `timeout` config option has been removed and is no longer needed.");
|
||||
warn!("Please update your config file.");
|
||||
@@ -223,28 +248,42 @@ fn camera_main(
|
||||
camera_config.name, camera_config.camera_addr
|
||||
);
|
||||
|
||||
camera.login(&camera_config.username, camera_config.password.as_deref())?;
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera.login(&camera_config.username, camera_config.password.as_deref()).map_err(|e|
|
||||
{
|
||||
if let neolink_core::Error::AuthFailed = e {
|
||||
login_fail = true;
|
||||
}
|
||||
e
|
||||
}
|
||||
).with_context(|| format!("Failed to login to {}", camera_config.name))?;
|
||||
|
||||
connected = true;
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
if manage {
|
||||
do_camera_management(&mut camera, camera_config)?;
|
||||
do_camera_management(&mut camera, camera_config).context("Failed to manage the camera settings")?;
|
||||
}
|
||||
|
||||
let stream_display_name = match stream_name {
|
||||
Stream::Main => "Main Stream (Clear)",
|
||||
Stream::Sub => "Sub Stream (Fluent)",
|
||||
Stream::Extern => "Extern Stream (Balanced)",
|
||||
};
|
||||
|
||||
info!(
|
||||
"{}: Starting video stream {}",
|
||||
camera_config.name, stream_name
|
||||
camera_config.name, stream_display_name
|
||||
);
|
||||
camera.start_video(outputs, stream_name)
|
||||
})()
|
||||
.map_err(|err| CameraErr { connected, err })
|
||||
camera.start_video(outputs, stream_name).with_context(|| format!("Error while streaming {}", camera_config.name))
|
||||
})().map_err(|e| CameraErr{
|
||||
connected,
|
||||
login_fail,
|
||||
err: e,
|
||||
})
|
||||
}
|
||||
|
||||
fn do_camera_management(
|
||||
camera: &mut BcCamera,
|
||||
camera_config: &CameraConfig,
|
||||
) -> Result<(), neolink_core::Error> {
|
||||
fn do_camera_management(camera: &mut BcCamera, camera_config: &CameraConfig) -> Result<()> {
|
||||
let cam_time = camera.get_time()?;
|
||||
if let Some(time) = cam_time {
|
||||
info!(
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
use super::errors::ParseOnOffError;
|
||||
use anyhow::{anyhow, Result};
|
||||
use std::path::PathBuf;
|
||||
use structopt::StructOpt;
|
||||
|
||||
fn onoff_parse(src: &str) -> Result<bool, ParseOnOffError> {
|
||||
fn onoff_parse(src: &str) -> Result<bool> {
|
||||
match src {
|
||||
"true" | "on" | "yes" => Ok(true),
|
||||
"false" | "off" | "no" => Ok(false),
|
||||
_ => Err(ParseOnOffError),
|
||||
_ => Err(anyhow!(
|
||||
"Could not understand {}, check your input, should be true/false, on/off or yes/no",
|
||||
src
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
use err_derive::Error;
|
||||
|
||||
/// The main error for the status-light subcommand
|
||||
#[derive(Debug, Error)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum Error {
|
||||
/// Raised when the config file fails to deserlize
|
||||
#[error(display = "Configuration parsing error")]
|
||||
Config(#[error(source)] toml::de::Error),
|
||||
/// Raised when `neolink_core` raises an error
|
||||
#[error(display = "Communication error")]
|
||||
Protocol(#[error(source)] neolink_core::Error),
|
||||
/// Raised when there is an IO error such as unable to find
|
||||
/// config file
|
||||
#[error(display = "I/O error")]
|
||||
Io(#[error(source)] std::io::Error),
|
||||
/// Raised when the config file fails validataion
|
||||
#[error(display = "Validation error")]
|
||||
Validation(#[error(source)] validator::ValidationErrors),
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
#[error(display = "Failed to parse on/off flag")]
|
||||
pub(super) struct ParseOnOffError;
|
||||
+30
-14
@@ -15,6 +15,7 @@
|
||||
/// neolink status-light --config=config.toml CameraName off
|
||||
/// ```
|
||||
///
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use log::*;
|
||||
use neolink_core::bc_protocol::BcCamera;
|
||||
use std::fs;
|
||||
@@ -22,19 +23,23 @@ use validator::Validate;
|
||||
|
||||
mod cmdline;
|
||||
mod config;
|
||||
mod errors;
|
||||
|
||||
pub(crate) use cmdline::Opt;
|
||||
use config::Config;
|
||||
pub(crate) use errors::Error;
|
||||
|
||||
/// Entry point for the ledstatus subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?;
|
||||
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()?;
|
||||
config
|
||||
.validate()
|
||||
.with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?;
|
||||
|
||||
let mut cam_found = false;
|
||||
for camera_config in &config.cameras {
|
||||
@@ -46,23 +51,34 @@ pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
);
|
||||
|
||||
let mut camera =
|
||||
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
|
||||
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to connect to camera {} at {} on channel {}",
|
||||
camera_config.name, camera_config.camera_addr, camera_config.channel_id
|
||||
)
|
||||
})?;
|
||||
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera.login(&camera_config.username, camera_config.password.as_deref())?;
|
||||
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)?;
|
||||
camera
|
||||
.led_light_set(opt.on)
|
||||
.context("Unable to set camera light state")?;
|
||||
}
|
||||
}
|
||||
|
||||
if !cam_found {
|
||||
error!(
|
||||
"No camera with the name {} was found in the config",
|
||||
opt.camera
|
||||
);
|
||||
Err(anyhow!(
|
||||
"Camera {} was not in the config file {:?}",
|
||||
&opt.camera,
|
||||
&opt.config
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
use err_derive::Error;
|
||||
use gstreamer::glib;
|
||||
|
||||
/// The main error for the status-light subcommand
|
||||
#[derive(Debug, Error)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum Error {
|
||||
/// Raised when the config file fails to deserlize
|
||||
#[error(display = "Configuration parsing error")]
|
||||
Config(#[error(source)] toml::de::Error),
|
||||
/// Raised when `neolink_core` raises an error
|
||||
#[error(display = "Communication error")]
|
||||
Protocol(#[error(source)] neolink_core::Error),
|
||||
/// Raised when there is an IO error such as unable to find
|
||||
/// config file
|
||||
#[error(display = "I/O error")]
|
||||
Io(#[error(source)] std::io::Error),
|
||||
/// Raised when the config file fails validataion
|
||||
#[error(display = "Validation error")]
|
||||
Validation(#[error(source)] validator::ValidationErrors),
|
||||
/// Raised when gstreamer fails to init
|
||||
#[error(display = "Gstreamer init failed")]
|
||||
GstreamerInit(#[error(source)] glib::Error),
|
||||
/// Raised when a needed part of the gsteamer pipeline is not found
|
||||
///
|
||||
/// Usually this means missing pluings
|
||||
#[error(display = "Gstreamer element not supported. Check your gstreamer plugins")]
|
||||
GstreamerElement(gstreamer::Element),
|
||||
/// Raised where there is an issue starting a audio playback in gstraemer
|
||||
#[error(display = "Gstreamer Unable to play the file")]
|
||||
GstreamerPlayback(#[error(source)] gstreamer::StateChangeError),
|
||||
/// Generic gstreamer error
|
||||
#[error(display = "Gstreamer raised an error")]
|
||||
Gstreamer {
|
||||
error: String,
|
||||
debug: Option<String>,
|
||||
},
|
||||
|
||||
/// Raised when talk back is unsupported
|
||||
#[error(display = "This camera does not support talkback")]
|
||||
TalkUnsupported,
|
||||
}
|
||||
+22
-19
@@ -1,3 +1,4 @@
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use gstreamer::{
|
||||
element_error, parse_launch, prelude::*, Caps, ClockTime, FlowError, FlowSuccess, MessageView,
|
||||
Pipeline, ResourceError, State,
|
||||
@@ -5,7 +6,6 @@ use gstreamer::{
|
||||
use gstreamer_app::{AppSink, AppSinkCallbacks};
|
||||
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
|
||||
|
||||
use super::errors::Error;
|
||||
use byte_slice_cast::*;
|
||||
|
||||
pub(super) fn from_input(
|
||||
@@ -13,12 +13,12 @@ pub(super) fn from_input(
|
||||
volume: f32,
|
||||
block_align: u16,
|
||||
sample_rate: u16,
|
||||
) -> Result<Receiver<Vec<u8>>, Error> {
|
||||
) -> Result<Receiver<Vec<u8>>> {
|
||||
let pipeline = create_pipeline(input_src, volume, block_align, sample_rate)?;
|
||||
input(pipeline)
|
||||
}
|
||||
|
||||
fn input(pipeline: Pipeline) -> Result<Receiver<Vec<u8>>, Error> {
|
||||
fn input(pipeline: Pipeline) -> Result<Receiver<Vec<u8>>> {
|
||||
let appsink = get_sink(&pipeline)?;
|
||||
let (tx, rx) = sync_channel(30);
|
||||
|
||||
@@ -31,7 +31,7 @@ fn input(pipeline: Pipeline) -> Result<Receiver<Vec<u8>>, Error> {
|
||||
Ok(rx)
|
||||
}
|
||||
|
||||
fn start_pipeline(pipeline: Pipeline) -> Result<(), Error> {
|
||||
fn start_pipeline(pipeline: Pipeline) -> Result<()> {
|
||||
pipeline.set_state(State::Playing)?;
|
||||
|
||||
let bus = pipeline
|
||||
@@ -42,30 +42,31 @@ fn start_pipeline(pipeline: Pipeline) -> Result<(), Error> {
|
||||
match msg.view() {
|
||||
MessageView::Eos(..) => break,
|
||||
MessageView::Error(err) => {
|
||||
pipeline.set_state(State::Null)?;
|
||||
pipeline
|
||||
.set_state(State::Null)
|
||||
.context("Error in gstreamer when setting state to Null")?;
|
||||
log::warn!(
|
||||
"{:?}",
|
||||
Error::Gstreamer {
|
||||
error: err.error().to_string(),
|
||||
debug: err.debug(),
|
||||
}
|
||||
"Error from gstreamer when setting the play state {:?} setting to Null instead",
|
||||
err
|
||||
);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
pipeline.set_state(State::Null)?;
|
||||
pipeline
|
||||
.set_state(State::Null)
|
||||
.context("Error in gstreamer when setting state to Null")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_sink(pipeline: &Pipeline) -> Result<AppSink, Error> {
|
||||
fn get_sink(pipeline: &Pipeline) -> Result<AppSink> {
|
||||
let sink = pipeline
|
||||
.by_name("thesink")
|
||||
.expect("There shoud be a `thesink`");
|
||||
sink.dynamic_cast::<AppSink>()
|
||||
.map_err(Error::GstreamerElement)
|
||||
.map_err(|_| anyhow!("Cannot find appsink in gstreamer, check your gstreamer plugins"))
|
||||
}
|
||||
|
||||
fn set_data_channel(appsink: &AppSink, tx: SyncSender<Vec<u8>>) {
|
||||
@@ -131,8 +132,9 @@ fn create_pipeline(
|
||||
volume: f32,
|
||||
block_align: u16,
|
||||
sample_rate: u16,
|
||||
) -> Result<Pipeline, Error> {
|
||||
gstreamer::init()?;
|
||||
) -> Result<Pipeline> {
|
||||
gstreamer::init()
|
||||
.context("Unable to start gstreamer ensure it and all plugins are installed")?;
|
||||
|
||||
let launch_str = format!(
|
||||
"{} \
|
||||
@@ -152,10 +154,11 @@ fn create_pipeline(
|
||||
// Parse the pipeline we want to probe from a static in-line string.
|
||||
// Here we give our audiotestsrc a name, so we can retrieve that element
|
||||
// from the resulting pipeline.
|
||||
let pipeline = parse_launch(&launch_str)?;
|
||||
let pipeline = pipeline
|
||||
.dynamic_cast::<Pipeline>()
|
||||
.map_err(Error::GstreamerElement)?;
|
||||
let pipeline = parse_launch(&launch_str)
|
||||
.context("Unable to load gstreamer pipeline ensure all gstramer plugins are installed")?;
|
||||
let pipeline = pipeline.dynamic_cast::<Pipeline>().map_err(|_| {
|
||||
anyhow!("Unable to create gstreamer pipeline ensure all gstramer plugins are installed")
|
||||
})?;
|
||||
|
||||
let appsink = get_sink(&pipeline)?;
|
||||
|
||||
|
||||
+45
-19
@@ -11,6 +11,7 @@
|
||||
/// neolink status-light --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, bc_protocol::BcCamera};
|
||||
use std::fs;
|
||||
@@ -18,20 +19,24 @@ use validator::Validate;
|
||||
|
||||
mod cmdline;
|
||||
mod config;
|
||||
mod errors;
|
||||
mod gst;
|
||||
|
||||
pub(crate) use cmdline::Opt;
|
||||
use config::Config;
|
||||
pub(crate) use errors::Error;
|
||||
|
||||
/// Entry point for the talk subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?;
|
||||
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()?;
|
||||
config
|
||||
.validate()
|
||||
.with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?;
|
||||
|
||||
let mut cam_found = false;
|
||||
for camera_config in &config.cameras {
|
||||
@@ -43,19 +48,32 @@ pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
);
|
||||
|
||||
let mut camera =
|
||||
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
|
||||
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to connect to camera {} at {} on channel {}",
|
||||
camera_config.name, camera_config.camera_addr, camera_config.channel_id
|
||||
)
|
||||
})?;
|
||||
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera.login(&camera_config.username, camera_config.password.as_deref())?;
|
||||
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()?;
|
||||
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(Error::TalkUnsupported);
|
||||
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
|
||||
@@ -75,7 +93,10 @@ pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
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(Error::TalkUnsupported);
|
||||
return Err(anyhow!(
|
||||
"The camera {} does not support talk with adpcm",
|
||||
camera_config.name
|
||||
));
|
||||
}
|
||||
|
||||
let rx = match (&opt.file_path, &opt.microphone) {
|
||||
@@ -87,23 +108,28 @@ pub fn main(opt: Opt) -> Result<(), Error> {
|
||||
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)?
|
||||
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)?;
|
||||
camera
|
||||
.talk_stream(rx, talk_config)
|
||||
.context("Talk stream ended early")?;
|
||||
}
|
||||
}
|
||||
|
||||
if !cam_found {
|
||||
error!(
|
||||
"No camera with the name {} was found in the config",
|
||||
opt.camera
|
||||
);
|
||||
Err(anyhow!(
|
||||
"Camera {} was not in the config file {:?}",
|
||||
&opt.camera,
|
||||
&opt.config
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user