Bug and clippy lint squashing

This commit is contained in:
QuantumEntangledAndy committed 2022-01-17 21:02:48 +07:00
1 parent e436b27e63
commit a33897ec2c
20 files changed
+375 -182

No files matched your search

+36
View File
@@ -73,6 +73,10 @@ pub(crate) struct CameraConfig {
#[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))]
#[serde(default = "default_channel_id")]
pub(crate) channel_id: u8,
#[validate]
#[serde(default = "default_mqtt")]
pub(crate) mqtt: Option<MqttConfig>,
}
#[derive(Debug, Deserialize, Validate, Clone)]
@@ -85,6 +89,38 @@ pub(crate) struct UserConfig {
pub(crate) pass: String,
}
#[derive(Debug, Deserialize, Clone, Validate)]
#[validate(schema(function = "validate_mqtt_config", skip_on_field_errors = true))]
pub(crate) struct MqttConfig {
#[serde(alias = "server")]
pub(crate) broker_addr: String,
pub(crate) port: u16,
#[serde(default)]
pub(crate) credentials: Option<(String, String)>,
#[serde(default)]
pub(crate) ca: Option<std::path::PathBuf>,
#[serde(default)]
pub(crate) client_auth: Option<(std::path::PathBuf, std::path::PathBuf)>,
}
fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
if config.ca.is_some() && config.client_auth.is_some() {
Err(ValidationError::new(
"Cannot have both ca and client_auth set",
))
} else {
Ok(())
}
}
fn default_mqtt() -> Option<MqttConfig> {
None
}
fn default_bind_addr() -> String {
"0.0.0.0".to_string()
}
+2 -2
View File
@@ -68,8 +68,8 @@ fn main() -> Result<()> {
Some(Command::Talk(opts)) => {
talk::main(opts, config)?;
}
Command::Mqtt(opts) => {
mqtt::main(opts)?;
Some(Command::Mqtt(opts)) => {
mqtt::main(opts, config)?;
}
}
-65
View File
@@ -1,65 +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)]
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,
#[validate]
#[serde(default = "default_mqtt")]
pub(crate) mqtt: Option<MqttConfig>,
}
#[derive(Debug, Deserialize, Clone, Validate)]
#[validate(schema(function = "validate_mqtt_config", skip_on_field_errors = true))]
pub(crate) struct MqttConfig {
#[serde(alias = "server")]
pub(crate) broker_addr: String,
pub(crate) port: u16,
#[serde(default)]
pub(crate) credentials: Option<(String, String)>,
#[serde(default)]
pub(crate) ca: Option<std::path::PathBuf>,
#[serde(default)]
pub(crate) client_auth: Option<(std::path::PathBuf, std::path::PathBuf)>,
}
fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> {
if config.ca.is_some() && config.client_auth.is_some() {
Err(ValidationError::new(
"Cannot have both ca and client_auth set",
))
} else {
Ok(())
}
}
fn default_mqtt() -> Option<MqttConfig> {
None
}
fn default_channel_id() -> u8 {
0
}
-41
View File
@@ -1,41 +0,0 @@
use err_derive::Error;
use std::convert::From;
use std::sync::{MutexGuard, PoisonError};
/// 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),
/// Raised when crossbeam fails to recv
#[error(display = "Recv data error")]
CrossbeamRecv(#[error(source)] crossbeam_channel::RecvError),
#[error(display = "Send data error")]
CrossbeamSend,
#[error(display = "Unable to lock mutex")]
Lock,
}
impl<M> From<crossbeam_channel::SendError<M>> for Error {
fn from(_: crossbeam_channel::SendError<M>) -> Self {
Error::CrossbeamSend
}
}
impl<'a, M> From<PoisonError<MutexGuard<'a, M>>> for Error {
fn from(_: PoisonError<MutexGuard<'a, M>>) -> Self {
Error::Lock
}
}
+29 -15
View File
@@ -1,5 +1,7 @@
use super::App;
use super::{config::CameraConfig, errors::Error};
use crate::config::CameraConfig;
use crate::utils::AddressOrUid;
use anyhow::{anyhow, Context, Result};
use crossbeam_channel::{unbounded, Receiver, Sender, TryRecvError};
use log::*;
use neolink_core::bc_protocol::{
@@ -37,10 +39,10 @@ impl<'a> EventCam<'a> {
}
}
pub(crate) fn poll(&self) -> Result<Messages, Error> {
pub(crate) fn poll(&self) -> Result<Messages> {
if let Ok(ref mut channel_out) = self.channel_out.try_lock() {
if let Some(channel_out) = channel_out.as_mut() {
channel_out.recv().map_err(|e| e.into())
channel_out.recv().context("Camera failed to poll")
} else {
Ok(Messages::None)
}
@@ -49,15 +51,17 @@ impl<'a> EventCam<'a> {
}
}
pub(crate) fn send_message(&self, msg: Messages) -> Result<(), Error> {
pub(crate) fn send_message(&self, msg: Messages) -> Result<()> {
if let Ok(ref mut channel_in) = self.channel_in.lock() {
if let Some(channel_in) = channel_in.as_mut() {
channel_in.send(msg).map_err(|e| e.into())
channel_in
.send(msg)
.context("Failed to send message from camera")
} else {
Err(Error::CrossbeamSend)
Err(anyhow!("Failed to send camera data over crossbeam"))
}
} else {
Err(Error::Lock)
Err(anyhow!("Failed to lock"))
}
}
@@ -81,7 +85,7 @@ impl<'a> EventCam<'a> {
while self.app.running(&self.config.name) {
// Ignore errors and just loop
let _ = Self::cam_run(
&loop_config,
loop_config,
loop_tx.clone(),
loop_rx.clone(),
self.app.clone(),
@@ -94,20 +98,30 @@ impl<'a> EventCam<'a> {
tx: Arc<Mutex<Sender<Messages>>>,
rx: Arc<Mutex<Receiver<Messages>>>,
app: Arc<App>,
) -> Result<(), Error> {
) -> Result<()> {
let camera_addr =
AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap();
info!(
"{}: Connecting to camera at {}",
camera_config.name, camera_config.camera_addr
camera_config.name, camera_addr
);
let mut camera =
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
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())?;
camera
.login(&camera_config.username, camera_config.password.as_deref())
.context("Failed to login to the camera")?;
info!("{}: Connected and logged in", camera_config.name);
(tx.lock()?).send(Messages::Login)?;
(tx.lock().map_err(|_| anyhow!("Failed to lock"))?).send(Messages::Login)?;
// Shararble cameras
let arc_cam = Arc::new(camera);
+6 -14
View File
@@ -12,21 +12,17 @@ use log::*;
/// neolink reboot --config=config.toml CameraName
/// ```
///
use std::fs;
use std::sync::Arc;
use validator::Validate;
mod app;
mod cmdline;
mod config;
mod errors;
mod event_cam;
mod mqttc;
use crate::config::{CameraConfig, Config, MqttConfig};
use anyhow::Result;
pub(crate) use app::App;
pub(crate) use cmdline::Opt;
use config::{CameraConfig, Config, MqttConfig};
pub(crate) use errors::Error;
use event_cam::EventCam;
pub(crate) use event_cam::Messages;
use mqttc::{Mqtt, MqttReplyRef};
@@ -34,11 +30,7 @@ use mqttc::{Mqtt, MqttReplyRef};
/// 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()?;
pub(crate) fn main(_: Opt, config: Config) -> Result<()> {
let app = App::new();
let arc_app = Arc::new(app);
@@ -63,7 +55,7 @@ fn listen_on_camera(
cam_config: &CameraConfig,
mqtt_config: &MqttConfig,
app: Arc<App>,
) -> Result<(), Error> {
) -> Result<()> {
// Camera thread
let event_cam = EventCam::new(cam_config, app.clone());
let mqtt = Mqtt::new(mqtt_config, &cam_config.name, app.clone());
@@ -83,7 +75,7 @@ fn listen_on_camera(
// Listen on camera messages and post on mqtt
s.spawn(|_| {
while app.running(&format!("app:{}", cam_config.name.to_string())) {
while app.running(&format!("app: {}", cam_config.name)) {
if let Ok(msg) = event_cam.poll() {
match msg {
Messages::Login => {
@@ -109,7 +101,7 @@ fn listen_on_camera(
// Listen on mqtt messages and post on camera
s.spawn(|_| {
while app.running(&format!("app:{}", cam_config.name.to_string())) {
while app.running(&format!("app: {}", cam_config.name)) {
if let Ok(msg) = mqtt.poll() {
match msg.as_ref() {
MqttReplyRef {
+10 -6
View File
@@ -1,4 +1,6 @@
use super::{config::MqttConfig, errors::Error, App};
use super::App;
use crate::config::MqttConfig;
use anyhow::{Context, Result};
use crossbeam_channel::{unbounded, Receiver, RecvError, Sender};
use log::*;
use rumqttc::{
@@ -198,11 +200,13 @@ impl Mqtt {
self.msg_channel.1.clone()
}
pub(crate) fn poll(&self) -> Result<MqttReply, Error> {
self.get_message_listener().recv().map_err(|e| e.into())
pub(crate) fn poll(&self) -> Result<MqttReply> {
self.get_message_listener()
.recv()
.context("Mqtt Polling error")
}
pub(crate) fn start(&self) -> Result<(), ClientError> {
pub(crate) fn start(&self) -> Result<()> {
// This acts as an event loop
let mut connection = self.connection.lock().unwrap();
let (sender, _) = &self.incoming;
@@ -213,9 +217,9 @@ impl Mqtt {
match notification {
Event::Incoming(Incoming::ConnAck(connected)) => {
if ConnectReturnCode::Success == connected.code {
self.update_status()?;
self.update_status().context("Failed to update status")?;
// We succesfully logged in. Now ask for the cameras subscription.
self.subscribe()?;
self.subscribe().context("Failed to subscribe")?;
}
}
Event::Incoming(Incoming::Publish(published_message)) => {
+1 -1
View File
@@ -347,7 +347,7 @@ mod maybe_app_src {
/// owning the AppSrc directly. This function handles either case and returns the AppSrc,
/// or None if the caller has not yet sent one.
fn try_get_src(&mut self) -> Option<&AppSrc> {
while let Some(src) = self.rx.try_recv().ok() {
while let Ok(src) = self.rx.try_recv() {
self.app_src = Some(src);
}
self.app_src.as_ref()
+10 -11
View File
@@ -119,7 +119,7 @@ fn camera_loop(
stream_name: Stream,
outputs: &mut GstOutputs,
manage: bool,
) -> Result<(), Error> {
) -> Result<()> {
let min_backoff = Duration::from_secs(1);
let max_backoff = Duration::from_secs(15);
let mut current_backoff = min_backoff;
@@ -132,20 +132,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);
+1 -1
View File
@@ -27,7 +27,7 @@ pub(crate) use cmdline::Opt;
///
/// Opt is the command line options
pub(crate) fn main(opt: Opt, config: Config) -> Result<()> {
let mut camera = find_and_connect(&config, &opt.camera)?;
let camera = find_and_connect(&config, &opt.camera)?;
camera
.led_light_set(opt.on)