Merge branch 'master' of github.com:thirtythreeforty/neolink into mqtt_cmd
This commit is contained in:
82 files changed
+5108
-1314
No files matched your search
+10
-3
@@ -1,11 +1,18 @@
|
||||
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),
|
||||
setting(AppSettings::UnifiedHelpMessage)
|
||||
)]
|
||||
pub struct Opt {
|
||||
#[structopt(short, long, global(true), parse(from_os_str))]
|
||||
pub config: Option<PathBuf>,
|
||||
#[structopt(subcommand)]
|
||||
pub cmd: Command,
|
||||
pub cmd: Option<Command>,
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -40,11 +41,15 @@ pub(crate) struct Config {
|
||||
}
|
||||
|
||||
#[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: String,
|
||||
pub(crate) camera_addr: Option<String>,
|
||||
|
||||
#[serde(rename = "uid")]
|
||||
pub(crate) camera_uid: Option<String>,
|
||||
|
||||
pub(crate) username: String,
|
||||
pub(crate) password: Option<String>,
|
||||
@@ -114,3 +119,15 @@ fn validate_username(name: &str) -> Result<(), ValidationError> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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(()),
|
||||
}
|
||||
}
|
||||
+33
-11
@@ -7,22 +7,26 @@
|
||||
//! It contains sub commands for running an rtsp proxy which can be used on Reolink cameras
|
||||
//! that do not nativly support RTSP.
|
||||
//!
|
||||
use anyhow::{Context, Result};
|
||||
use env_logger::Env;
|
||||
use log::*;
|
||||
use std::fs;
|
||||
use structopt::StructOpt;
|
||||
use validator::Validate;
|
||||
|
||||
mod cmdline;
|
||||
mod errors;
|
||||
mod config;
|
||||
mod mqtt;
|
||||
mod reboot;
|
||||
mod rtsp;
|
||||
mod statusled;
|
||||
mod talk;
|
||||
mod utils;
|
||||
|
||||
use cmdline::{Command, Opt};
|
||||
use errors::Error;
|
||||
use config::Config;
|
||||
|
||||
fn main() -> Result<(), Error> {
|
||||
fn main() -> Result<()> {
|
||||
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
|
||||
|
||||
info!(
|
||||
@@ -33,18 +37,36 @@ fn main() -> Result<(), Error> {
|
||||
|
||||
let opt = Opt::from_args();
|
||||
|
||||
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 {
|
||||
Command::Rtsp(opts) => {
|
||||
rtsp::main(opts)?;
|
||||
None => {
|
||||
warn!(
|
||||
"Deprecated command line option. Please use: `neolink rtsp --config={:?}`",
|
||||
config
|
||||
);
|
||||
rtsp::main(rtsp::Opt {}, config)?;
|
||||
}
|
||||
Command::StatusLight(opts) => {
|
||||
statusled::main(opts)?;
|
||||
Some(Command::Rtsp(opts)) => {
|
||||
rtsp::main(opts, config)?;
|
||||
}
|
||||
Command::Reboot(opts) => {
|
||||
reboot::main(opts)?;
|
||||
Some(Command::StatusLight(opts)) => {
|
||||
statusled::main(opts, config)?;
|
||||
}
|
||||
Command::Talk(opts) => {
|
||||
talk::main(opts)?;
|
||||
Some(Command::Reboot(opts)) => {
|
||||
reboot::main(opts, config)?;
|
||||
}
|
||||
Some(Command::Talk(opts)) => {
|
||||
talk::main(opts, config)?;
|
||||
}
|
||||
Command::Mqtt(opts) => {
|
||||
mqtt::main(opts)?;
|
||||
|
||||
@@ -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,29 +0,0 @@
|
||||
use serde::Deserialize;
|
||||
use std::clone::Clone;
|
||||
use validator::Validate;
|
||||
use validator_derive::Validate;
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct Config {
|
||||
#[validate]
|
||||
pub(crate) cameras: Vec<CameraConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct CameraConfig {
|
||||
pub(crate) name: String,
|
||||
|
||||
#[serde(rename = "address")]
|
||||
pub(crate) camera_addr: 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
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
+8
-40
@@ -11,54 +11,22 @@
|
||||
/// neolink reboot --config=config.toml CameraName
|
||||
/// ```
|
||||
///
|
||||
use log::*;
|
||||
use neolink_core::bc_protocol::BcCamera;
|
||||
use std::fs;
|
||||
use validator::Validate;
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
mod cmdline;
|
||||
mod config;
|
||||
mod errors;
|
||||
|
||||
use super::config::Config;
|
||||
use crate::utils::find_and_connect;
|
||||
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)?)?;
|
||||
|
||||
config.validate()?;
|
||||
|
||||
let mut cam_found = false;
|
||||
for camera_config in &config.cameras {
|
||||
if opt.camera == camera_config.name {
|
||||
cam_found = true;
|
||||
info!(
|
||||
"{}: Connecting to camera at {}",
|
||||
camera_config.name, camera_config.camera_addr
|
||||
);
|
||||
|
||||
let mut camera =
|
||||
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
|
||||
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera.login(&camera_config.username, camera_config.password.as_deref())?;
|
||||
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
camera.reboot()?;
|
||||
}
|
||||
}
|
||||
|
||||
if !cam_found {
|
||||
error!(
|
||||
"No camera with the name {} was found in the config",
|
||||
opt.camera
|
||||
);
|
||||
}
|
||||
pub(crate) fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
let camera = find_and_connect(&config, &opt.camera)?;
|
||||
|
||||
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 {}
|
||||
@@ -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),
|
||||
}
|
||||
+59
-31
@@ -28,35 +28,28 @@
|
||||
/// 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;
|
||||
use std::time::Duration;
|
||||
use validator::Validate;
|
||||
|
||||
// mod adpcm;
|
||||
/// The command line parameters for this subcommand
|
||||
mod cmdline;
|
||||
mod config;
|
||||
/// The errors this subcommand can raise
|
||||
mod errors;
|
||||
mod gst;
|
||||
|
||||
use super::config::{CameraConfig, Config, UserConfig};
|
||||
use crate::utils::AddressOrUid;
|
||||
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)?)?;
|
||||
|
||||
config.validate()?;
|
||||
|
||||
pub(crate) fn main(_opt: Opt, config: Config) -> Result<()> {
|
||||
let rtsp = &RtspServer::new();
|
||||
|
||||
set_up_tls(&config, rtsp);
|
||||
@@ -83,7 +76,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 +85,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,7 +116,7 @@ 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> {
|
||||
@@ -156,7 +158,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 +209,24 @@ 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 camera_addr =
|
||||
AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap();
|
||||
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
|
||||
)
|
||||
})?;
|
||||
|
||||
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.");
|
||||
@@ -220,31 +234,45 @@ fn camera_main(
|
||||
|
||||
info!(
|
||||
"{}: Connecting to camera at {}",
|
||||
camera_config.name, camera_config.camera_addr
|
||||
camera_config.name, 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,21 +1,20 @@
|
||||
use super::errors::ParseOnOffError;
|
||||
use std::path::PathBuf;
|
||||
use anyhow::{anyhow, Result};
|
||||
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
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,29 +0,0 @@
|
||||
use serde::Deserialize;
|
||||
use std::clone::Clone;
|
||||
use validator::Validate;
|
||||
use validator_derive::Validate;
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct Config {
|
||||
#[validate]
|
||||
pub(crate) cameras: Vec<CameraConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct CameraConfig {
|
||||
pub(crate) name: String,
|
||||
|
||||
#[serde(rename = "address")]
|
||||
pub(crate) camera_addr: 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
|
||||
}
|
||||
@@ -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;
|
||||
+8
-40
@@ -15,54 +15,22 @@
|
||||
/// neolink status-light --config=config.toml CameraName off
|
||||
/// ```
|
||||
///
|
||||
use log::*;
|
||||
use neolink_core::bc_protocol::BcCamera;
|
||||
use std::fs;
|
||||
use validator::Validate;
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
mod cmdline;
|
||||
mod config;
|
||||
mod errors;
|
||||
|
||||
use super::config::Config;
|
||||
use crate::utils::find_and_connect;
|
||||
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)?)?;
|
||||
|
||||
config.validate()?;
|
||||
|
||||
let mut cam_found = false;
|
||||
for camera_config in &config.cameras {
|
||||
if opt.camera == camera_config.name {
|
||||
cam_found = true;
|
||||
info!(
|
||||
"{}: Connecting to camera at {}",
|
||||
camera_config.name, camera_config.camera_addr
|
||||
);
|
||||
|
||||
let mut camera =
|
||||
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
|
||||
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera.login(&camera_config.username, camera_config.password.as_deref())?;
|
||||
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
camera.led_light_set(opt.on)?;
|
||||
}
|
||||
}
|
||||
|
||||
if !cam_found {
|
||||
error!(
|
||||
"No camera with the name {} was found in the config",
|
||||
opt.camera
|
||||
);
|
||||
}
|
||||
pub(crate) fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
let mut camera = find_and_connect(&config, &opt.camera)?;
|
||||
|
||||
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,29 +0,0 @@
|
||||
use serde::Deserialize;
|
||||
use std::clone::Clone;
|
||||
use validator::Validate;
|
||||
use validator_derive::Validate;
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct Config {
|
||||
#[validate]
|
||||
pub(crate) cameras: Vec<CameraConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
pub(crate) struct CameraConfig {
|
||||
pub(crate) name: String,
|
||||
|
||||
#[serde(rename = "address")]
|
||||
pub(crate) camera_addr: 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
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
+23
-20
@@ -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>>) {
|
||||
@@ -106,7 +107,7 @@ fn set_data_channel(appsink: &AppSink, tx: SyncSender<Vec<u8>>) {
|
||||
|
||||
// We know what format the data in the memory region has, since we requested
|
||||
// it by setting the appsink's caps. So what we do here is interpret the
|
||||
// memory region we mapped as an array of signed 16 bit integers.
|
||||
// memory region we mapped as an array of signed 8 bit integers.
|
||||
let samples = map.as_slice_of::<u8>().map_err(|_| {
|
||||
element_error!(
|
||||
appsink,
|
||||
@@ -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)?;
|
||||
|
||||
|
||||
+60
-81
@@ -8,102 +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 log::*;
|
||||
use neolink_core::{bc::xml::TalkConfig, bc_protocol::BcCamera};
|
||||
use std::fs;
|
||||
use validator::Validate;
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use neolink_core::bc::xml::TalkConfig;
|
||||
|
||||
mod cmdline;
|
||||
mod config;
|
||||
mod errors;
|
||||
mod gst;
|
||||
|
||||
use super::config::Config;
|
||||
use crate::utils::{connect_and_login, find_camera_by_name};
|
||||
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(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()?;
|
||||
|
||||
let mut cam_found = false;
|
||||
for camera_config in &config.cameras {
|
||||
if opt.camera == camera_config.name {
|
||||
cam_found = true;
|
||||
info!(
|
||||
"{}: Connecting to camera at {}",
|
||||
camera_config.name, camera_config.camera_addr
|
||||
);
|
||||
|
||||
let mut camera =
|
||||
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
|
||||
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera.login(&camera_config.username, camera_config.password.as_deref())?;
|
||||
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
let talk_ability = camera.talk_ability()?;
|
||||
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);
|
||||
}
|
||||
|
||||
// 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(Error::TalkUnsupported);
|
||||
}
|
||||
|
||||
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,
|
||||
)?,
|
||||
(None, true) => {
|
||||
gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate)?
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
camera.talk_stream(rx, talk_config)?;
|
||||
}
|
||||
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 {
|
||||
error!(
|
||||
"No camera with the name {} was found in the config",
|
||||
opt.camera
|
||||
);
|
||||
// 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(())
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Contains code that is not specific to any of the subcommands
|
||||
//!
|
||||
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};
|
||||
|
||||
pub(crate) enum AddressOrUid {
|
||||
Address(String),
|
||||
Uid(String),
|
||||
}
|
||||
|
||||
impl Display for AddressOrUid {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
|
||||
match self {
|
||||
AddressOrUid::Address(host) => write!(f, "Address: {}", host),
|
||||
AddressOrUid::Uid(host) => write!(f, "UID: {}", host),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressOrUid {
|
||||
// Created by translating the config fields directly
|
||||
pub(crate) fn new(address: &Option<String>, uid: &Option<String>) -> Result<Self, Error> {
|
||||
match (address, uid) {
|
||||
(None, None) => Err(anyhow!("Neither address or uid given")),
|
||||
(Some(_), Some(_)) => Err(anyhow!("Either address or uid should be given not both")),
|
||||
(Some(host), None) => Ok(AddressOrUid::Address(host.clone())),
|
||||
(None, Some(host)) => Ok(AddressOrUid::Uid(host.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
// Convience method to get the BcCamera with the appropiate method
|
||||
pub(crate) fn connect_camera(&self, channel_id: u8) -> Result<BcCamera, Error> {
|
||||
match self {
|
||||
AddressOrUid::Address(host) => Ok(BcCamera::new_with_addr(host, channel_id)?),
|
||||
AddressOrUid::Uid(host) => Ok(BcCamera::new_with_uid(host, channel_id)?),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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