Use anyhow for application level error

This commit is contained in:
QuantumEntangledAndy committed 2021-08-19 10:00:12 +07:00
1 parent 0dd2eb744d
commit 8f1c3ece9d
14 files changed
+186 -222

No files matched your search

Generated
+1
View File
@@ -832,6 +832,7 @@ name = "neolink"
version = "0.4.0"
dependencies = [
"aes",
"anyhow",
"byte-slice-cast",
"cfb-mode",
"cookie-factory",
+1
View File
@@ -39,3 +39,4 @@ xml-rs = "0.8"
validator = "0.10"
validator_derive = "0.10"
byte-slice-cast = "1.0.0"
anyhow = "1.0.42"
-14
View File
@@ -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),
}
+2 -3
View File
@@ -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!(
-20
View File
@@ -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
View File
@@ -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(())
}
-23
View File
@@ -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),
}
+49 -27
View File
@@ -28,6 +28,7 @@
/// neolink rtsp --config=config.toml
/// ```
///
use anyhow::{Context, Result};
use log::*;
use neolink_core::bc_protocol::BcCamera;
use neolink_core::Never;
@@ -42,21 +43,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();
@@ -118,7 +123,7 @@ fn camera_loop(
stream_name: &str,
outputs: &mut GstOutputs,
manage: bool,
) -> Result<Never, Error> {
) -> Result<Never> {
let min_backoff = Duration::from_secs(1);
let max_backoff = Duration::from_secs(15);
let mut current_backoff = min_backoff;
@@ -131,20 +136,19 @@ 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);
@@ -154,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) {
@@ -209,8 +214,17 @@ fn camera_main(
manage: bool,
) -> Result<Never, 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.");
@@ -221,28 +235,36 @@ 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")?;
}
info!(
"{}: Starting video stream {}",
camera_config.name, stream_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!(
+6 -3
View File
@@ -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
)),
}
}
-24
View File
@@ -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
View File
@@ -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(())
}
-42
View File
@@ -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
View File
@@ -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
View File
@@ -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(())
}