diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..6505be8 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,9 @@ +indent_style = "Block" +reorder_imports = true +imports_granularity = "crate" + +wrap_comments = true +format_code_in_doc_comments = true + +# max_width = 120 +# imports_layout = "Vertical" diff --git a/src/main.rs b/src/main.rs index 6815130..745bfcd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -23,8 +23,7 @@ fn main() -> Result<(), TinyError> { .unwrap() .log_to_file(FileSpec::default()) .write_mode(WriteMode::BufferAndFlush) - .start() - .unwrap(); + .start()?; info!(target:"info","Logging started"); color_eyre::install()?; diff --git a/src/scan.rs b/src/scan.rs index 4729b87..6bdddd4 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -53,15 +53,15 @@ pub(crate) fn scan_with_progress(connection_info: ConnectionInfo) -> Result<(), connection_info.set_error(Some(TinyError::PortConnection(e.clone()).into())); return Err(TinyError::PortConnection(e)); } - let mut port = port.unwrap(); + let mut port = port?; connection_info.update_message("Initialisation..."); connection_info.update_progress(5); initialize(&mut port); connection_info.update_progress(15); connection_info.update_message("Acquiring version & info"); - let v = send_cmd(&mut port, "version\r", SHORT_WAIT); - let i = send_cmd(&mut port, "info\r", SHORT_WAIT); + let v = send_cmd(&mut port, "version\r", SHORT_WAIT)?; + let i = send_cmd(&mut port, "info\r", SHORT_WAIT)?; // TODO: have a more thourough version check if v.is_empty() || i.is_empty() { return Err(TinyError::NoVersionFound); @@ -69,28 +69,26 @@ pub(crate) fn scan_with_progress(connection_info: ConnectionInfo) -> Result<(), connection_info.update_info(format!("{}{}", v, i)); connection_info.update_message("Setting up repeat"); - // TODO: Investigate this behaviour send_cmd( &mut port, &format!("repeat {}\r", connection_info.repeat), SHORT_WAIT, - ); + )?; // // TODO: Allow for user configuration // send_cmd(&mut port, "calc aver16\r", SHORT_WAIT); connection_info.update_progress(16); connection_info.update_message("Setting zero..."); - // TODO: Allow for user configuration - send_cmd(&mut port, &format!("zero {}\r", OFFSET), SHORT_WAIT); + send_cmd(&mut port, &format!("zero {}\r", OFFSET), SHORT_WAIT)?; connection_info.update_progress(17); connection_info.update_message("Setting up marker"); - send_cmd(&mut port, "marker\r", SHORT_WAIT); - send_cmd(&mut port, "pause\r", SHORT_WAIT); + send_cmd(&mut port, "marker\r", SHORT_WAIT)?; + send_cmd(&mut port, "pause\r", SHORT_WAIT)?; connection_info.update_progress(18); connection_info.update_message("Setting up scan & mode"); - send_cmd(&mut port, &format!("mode {} input\r", mode), SHORT_WAIT); + send_cmd(&mut port, &format!("mode {} input\r", mode), SHORT_WAIT)?; connection_info.update_progress(19); connection_info.update_message("Setting up sweep"); @@ -98,16 +96,16 @@ pub(crate) fn scan_with_progress(connection_info: ConnectionInfo) -> Result<(), &mut port, &format!("sweep start {}\r", connection_info.start), SHORT_WAIT, - ); + )?; send_cmd( &mut port, &format!("sweep stop {}\r", connection_info.stop), SHORT_WAIT, - ); + )?; connection_info.update_progress(20); connection_info.update_message("Starting scan..."); - send_cmd(&mut port, "sweep\r", SHORT_WAIT); + send_cmd(&mut port, "sweep\r", SHORT_WAIT)?; send_cmd( &mut port, &format!( @@ -115,14 +113,14 @@ pub(crate) fn scan_with_progress(connection_info: ConnectionInfo) -> Result<(), connection_info.start, connection_info.stop ), TIMEOUT, - ); + )?; connection_info.update_progress(22); connection_info.update_filename(scanraw(&mut port, connection_info.clone())?); connection_info.update_message("Acquiring version & info"); connection_info.update_message("Scan finished"); - send_cmd(&mut port, "resume\r", SHORT_WAIT); + send_cmd(&mut port, "resume\r", SHORT_WAIT)?; // wait_sync(LONG_WAIT); connection_info.update_progress(100); @@ -131,7 +129,6 @@ pub(crate) fn scan_with_progress(connection_info: ConnectionInfo) -> Result<(), /// Get the mode of operation from the start & stop scan values fn mode_from(start: usize, stop: usize) -> Result { - // TODO: Switch to low if possible with another non overlaping pattern if start > stop { return Err(TinyError::BadScanFrequencies(format!( "Start frequency {}Hz is higher than stop frequency {}Hz", @@ -139,8 +136,9 @@ fn mode_from(start: usize, stop: usize) -> Result { ))); } match (start, stop) { - (240_000_000..=960_000_000, 240_000_000..=960_000_000) => Ok("high".to_string()), - (0..240_000_000, 0..240_000_000) => Ok("low".to_string()), + (350_000_000..=960_000_000, 350_000_000..=960_000_000) => Ok("high".to_string()), + (0..350_000_000, 0..350_000_000) => Ok("low".to_string()), + (240_000_000..350_000_000, 350_000_000..=960_000_000) => Ok("high".to_string()), _ => Err(TinyError::BadScanFrequencies( "Scan frequencies must either be in range (0MHz-240MHz) or (240MHz-960MHz)".to_owned(), )), @@ -176,7 +174,7 @@ fn scanraw( "scanraw {} {} {}\r", connection_info.start, connection_info.stop, connection_info.points ), - ) + )? } wait_sync(SHORT_WAIT); let (name, val) = read_scanraw(port, connection_info.clone())?; @@ -186,19 +184,20 @@ fn scanraw( } /// Send a command and reads it to a string -fn send_cmd(port: &mut Box, command: &str, wait: u64) -> String { - unsafe { send_raw(port, command) } +fn send_cmd(port: &mut Box, command: &str, wait: u64) -> Result { + unsafe { send_raw(port, command)? } wait_sync(wait); let r = read_utf8(port); wait_sync(LONG_WAIT); - r + Ok(r) } /// Send a command without reading the output buffer /// This command will produce unknown results if the output buffer is never read -unsafe fn send_raw(port: &mut Box, command: &str) { +unsafe fn send_raw(port: &mut Box, command: &str) -> Result<(), TinyError> { let output = command.as_bytes(); - let _r = port.write(output).expect("Write failed!"); + let _r = port.write(output).map_err(|e| TinyError::SendError(e))?; + Ok(()) } /// Reads from port and tries to convert it to string with loss @@ -263,7 +262,6 @@ fn read_scanraw( v, connection_info.points, connection_info.start, - // TODO: Checks that points are always > 1 (connection_info.stop - connection_info.start) as f64 / (connection_info.points - 1) as f64, ) } diff --git a/src/structs.rs b/src/structs.rs index e270763..532b175 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -6,6 +6,7 @@ use std::{ sync::{Arc, Mutex}, }; +use flexi_logger::FlexiLoggerError; use serde::{Deserialize, Serialize}; use thiserror::Error; @@ -50,6 +51,12 @@ pub enum TinyError { /// The given scan frequencies are incorrect #[error("The given scan frequencies are inccorect ({0})")] BadScanFrequencies(String), + /// Couldn't initialize the logging modure + #[error("Couldn't initialize the logging modure")] + LoggerError(#[from] FlexiLoggerError), + /// Couldn't send data + #[error("Couldn't write to the TinySA, connection lost")] + SendError(std::io::Error), } #[allow(missing_docs, clippy::missing_docs_in_private_items)] @@ -67,27 +74,18 @@ pub enum TinyUIError { /// An error due to bad menuing implementation #[error("An error occured while selecting a menu item")] MenuSelectionError, - /// An error due to bad initialization #[error("The item list ({0}) wasn't initialyzed ({2}:{1})")] UninitializedItemList(&'static str, u32, &'static str), - /// An error occured while proccesing the key events #[error("An error occured while proccesing the key events")] KeyPress(#[from] std::io::Error), - // /// Mutex error likely a data race mishandled - // #[allow(dead_code)] - // #[error("An error occured while trying to fetch progress")] - // Mutex, /// Couldn't get a port from the selection - // TODO: Expand #[error("No port was selected")] NoPortSelected, - /// Any Scan Error #[error("An error occured while trying to scan: {0}")] ScanError(#[from] TinyError), - /// No connection object was created #[error("An error occured while trying to acquire the connection info structure")] NoConnectionInfoCreated, @@ -97,14 +95,11 @@ pub enum TinyUIError { /// No error was generated, this error is a meta error #[error("An unspecified error occured")] NoErrorSpecified, + /// Error occured while tring to serialize the config to file + #[error("Couldn't serialize the error to file")] + SerializeError(#[from] toml::ser::Error), } -// impl TinyUIError { -// pub(crate) fn uninitialized_item_list_error(list: &'static str) -> Self { -// Self::UninitializedItemList(list, line!(), file!()) -// } -// } - #[derive(Serialize, Deserialize, Debug)] pub(crate) struct SavedConfig { /// The default com port @@ -136,7 +131,6 @@ impl SavedConfig { /// Save the config with all runtime parameters pub(crate) fn save(arg: &AppInfo) -> Result<(), TinyUIError> { let mut f = File::create("config.toml")?; - // TODO: Prone to failure f.write_all( toml::to_string(&Self { port: arg.port_list.selected_port()?, @@ -145,8 +139,7 @@ impl SavedConfig { stop_frequency: arg.stop_frequency.int_to_usize(), points: arg.points.int_to_usize(), repeat: arg.repeat.int_to_usize(), - }) - .unwrap() + })? .as_bytes(), )?; Ok(()) @@ -166,8 +159,6 @@ pub(crate) enum ConnectionStatus { ConnectionFailure, /// The connection is closed and the connection was a succes ClosedWithSuccess, - // /// The connection is closed with a failure - // ClosedWithError, } #[derive(Debug, Clone)] @@ -284,6 +275,11 @@ impl ConnectionInfo { *self.error_raised.lock().unwrap() = e; } + /// Wether an error has been raised + pub(crate) fn has_error(&self) -> bool { + self.error_raised.lock().unwrap().is_some() + } + // pub(crate) fn get_error(&self) -> &Option { // self.error_raised.lock().as_ref().unwrap() // } diff --git a/src/ui.rs b/src/ui.rs index 4b406fc..cb51f2d 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -57,17 +57,17 @@ impl<'a> AppInfo<'a> { let (start_frequency, stop_frequency, points, repeat) = { if let Ok(c) = &loaded_conf { ( - UIUsize::new(c.start_frequency, 10, 960), - UIUsize::new(c.stop_frequency, 10, 960), - UIUsize::new(c.points, 100, 1000000), - UIUsize::new(c.repeat, 1, 1000), + UIUsize::new(c.start_frequency, 10, 0, 960), + UIUsize::new(c.stop_frequency, 10, 10, 960), + UIUsize::new(c.points, 100, 101, 1000001), + UIUsize::new(c.repeat, 1, 1, 1000), ) } else { ( - UIUsize::new(240, 10, 960), - UIUsize::new(960, 10, 960), - UIUsize::new(10000, 100, 1000000), - UIUsize::new(1, 1, 1000), + UIUsize::new(240, 10, 0, 960), + UIUsize::new(960, 10, 10, 960), + UIUsize::new(10001, 100, 101, 1000001), + UIUsize::new(1, 1, 1, 1000), ) } }; @@ -84,6 +84,7 @@ impl<'a> AppInfo<'a> { repeat, connection_info: None, return_data: Vec::new(), + logged_message: false, } } @@ -301,6 +302,10 @@ impl<'a> AppInfo<'a> { /// Draw the progress, updates as the progress is being done fn draw_progress(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { + if !self.logged_message { + info!("An error was raised {:#?}", self.get_connection_info()?); + self.logged_message = true; + } let [_, main_s, _] = Layout::horizontal([ Constraint::Min(7), Constraint::Percentage(90), @@ -341,14 +346,14 @@ impl<'a> AppInfo<'a> { frame.render_widget(message, main_area); self.menu_items.progress_bar = Some(pb); // TODO: Use the connection status instead - if self.connection_info.as_ref().unwrap().get_progress() >= 100 { + if self.get_connection_info()?.get_progress() >= 100 { self.return_data = self.get_connection_info()?.get_return_data()?; self.next_step()?; } let st = self.get_connection_info()?.get_connection_status(); #[allow(clippy::single_match)] match st { - // TODO: Add other failures + // TODO: Add other failures, skip to draw error ? ConnectionStatus::ConnectionFailure => self.next_step()?, _ => (), } @@ -380,49 +385,8 @@ impl<'a> AppInfo<'a> { ]) .areas(main_s); - info!("An error was raised {:#?}", self.get_connection_info()?); let conn_status = self.get_connection_info()?.get_connection_status(); - let status_message = match self - .get_connection_info()? - .error_raised - .lock() - .unwrap() - .as_ref() - .unwrap_or(&TinyUIError::NoErrorSpecified) - { - TinyUIError::MenuSelectionError => { - "An error occured while trying to select a menu item" - } - - TinyUIError::UninitializedItemList(i, _l,_ff) => { - &format!("The item {i} was left uninitialized") - } - TinyUIError::KeyPress(_) => "An error occured while processing key events", - TinyUIError::NoPortSelected => "No connection port was selected", - TinyUIError::NoConnectionInfoCreated => { - "An error occured when tring to acquire connection info with the TinySA" - } - TinyUIError::NoReturnData => { - "An error occured when trying to acquire the return data with the TinySA" - } - TinyUIError::NoErrorSpecified => "An unspecified error occured", - TinyUIError::ScanError(TinyError::ParseBeggining(_)) => { - "An error occured while receiving data, the scan never sent back any valid data" - } - TinyUIError::ScanError(TinyError::ParseEnd(_)) => "An error occured while receiving data, scan was interupted before ending properly", - TinyUIError::ScanError(TinyError::PortConnection(_)) => { - "An error occured while trying to connect, check the selected port and baudrate" - } - TinyUIError::ScanError(TinyError::NoVersionFound) => "An error forbid the gathering of the version, check your TinySA is connected and powered on", - TinyUIError::ScanError(TinyError::BadScanFrequencies(_)) => "An error occured because the scan frequencies weren't set correctly", - TinyUIError::ScanError(TinyError::OpenOutput(_)) => "", - TinyUIError::ScanError(TinyError::TUIInitialization(_)) => "", - TinyUIError::ScanError(TinyError::TUIRuntimeError(_)) => "", - TinyUIError::ScanError(TinyError::TUIPackingError(_)) => "", - TinyUIError::ScanError(TinyError::ConfigNotFound) => "", - TinyUIError::ScanError(TinyError::InvalidConfig(_)) => "", - TinyUIError::ScanError(TinyError::InvalidDataForConfig(_)) => "", - }; + let status_message = self.error_message_from_current_error()?; let status = Paragraph::new(status_message) .block(Block::bordered().title("Status")) .style(Color::Red); @@ -450,6 +414,61 @@ impl<'a> AppInfo<'a> { Ok(()) } + fn error_message_from_current_error(&self) -> Result { + let status_message = match self + .get_connection_info()? + .error_raised + .lock() + .unwrap() + .as_ref() + .unwrap_or(&TinyUIError::NoErrorSpecified) + { + TinyUIError::MenuSelectionError => "An error occured while trying to select a menu item", + TinyUIError::UninitializedItemList(i, _l, _ff) => &format!("The item {i} was left uninitialized"), + TinyUIError::KeyPress(_) => "An error occured while processing key events", + TinyUIError::NoPortSelected => "No connection port was selected", + TinyUIError::NoConnectionInfoCreated => { + "An error occured when tring to acquire connection info with the TinySA" + } + TinyUIError::NoReturnData => "An error occured when trying to acquire the return data with the TinySA", + TinyUIError::NoErrorSpecified => "An unspecified error occured", + TinyUIError::ScanError(TinyError::ParseBeggining(_)) => { + "An error occured while receiving data, the scan never sent back any valid data" + } + TinyUIError::ScanError(TinyError::ParseEnd(_)) => { + "An error occured while receiving data, scan was interupted before ending properly" + } + TinyUIError::ScanError(TinyError::PortConnection(_)) => { + "An error occured while trying to connect, check the selected port and baudrate" + } + TinyUIError::ScanError(TinyError::NoVersionFound) => { + "An error forbid the gathering of the version, check your TinySA is connected and powered on" + } + TinyUIError::ScanError(TinyError::BadScanFrequencies(_)) => { + "An error occured because the scan frequencies weren't set correctly" + } + TinyUIError::ScanError(TinyError::OpenOutput(_)) => "An error occured while trying to export the scan", + TinyUIError::ScanError(TinyError::TUIInitialization(_)) => { + "An error occured while trying to create the TUI" + } + TinyUIError::ScanError(TinyError::TUIRuntimeError(_)) => "An error occured during runtime", + TinyUIError::ScanError(TinyError::TUIPackingError(_)) => { + "An error occured while trying to parse the data points" + } + TinyUIError::ScanError(TinyError::ConfigNotFound) => { + "An error occured while trying to open the config file" + } + TinyUIError::ScanError(TinyError::InvalidConfig(_)) => { + "An error forbid to read the config as it seems invalid, please delete config.toml and retry" + } + TinyUIError::ScanError(TinyError::InvalidDataForConfig(_)) => "An error forbit to write the config", + TinyUIError::ScanError(TinyError::LoggerError(_))=> "Couldn't initialize the error logger", + TinyUIError::ScanError(TinyError::SendError(_))=> "Couldn't finish sending data to TinySA", + TinyUIError::SerializeError(_) => "An error occured while tring to save the current config", + }; + Ok(status_message.to_owned()) + } + /// Draw the last confirmation window fn draw_end_window(&mut self, frame: &mut Frame) -> Result<(), TinyUIError> { let [_, main_s, _] = Layout::horizontal([ @@ -469,21 +488,7 @@ impl<'a> AppInfo<'a> { let status = self.get_connection_info()?.get_connection_status(); match status { - // TODO: | ConnectionStatus::ClosedWithError ConnectionStatus::ConnectionFailure => { - // let status = Paragraph::new( - // // TODO: Be more explicit with errors and use the error status - // "The scan couldn't be performed, please check your connection".to_string(), - // ) - // .block(Block::bordered().title("Status")) - // .style(Color::Red); - // let footer = Paragraph::new(format!( - // "{}, press ↲ or q to exit", - // self.scan_message.lock().unwrap().clone() - // )) - // .centered(); - // frame.render_widget(status, title_area); - // frame.render_widget(footer, footer_area); self.flow_state = AppState::Error; } _ => { @@ -496,10 +501,7 @@ impl<'a> AppInfo<'a> { .block(Block::bordered().title("Status")) .style(SELECTED_COLOR); - // TODO: Don't acquire a mutex at 60Hz - // let binding = self.get_connection_info()?.get_return_data()?; let datasets = vec![Dataset::default() - // .name("Heavy") .marker(Marker::Dot) .graph_type(GraphType::Scatter) .style(Style::new().yellow()) @@ -630,7 +632,6 @@ impl<'a> AppInfo<'a> { // let error = self.scan_error.clone(); let connection_info = ConnectionInfo::new( self.port_list.selected_port()?, - // TODO: dont have this sht self.baudrate.selected_baudrate()?, self.start_frequency.mhz_to_usize(), self.stop_frequency.mhz_to_usize(), @@ -639,8 +640,6 @@ impl<'a> AppInfo<'a> { ); self.connection_info = Some(connection_info.clone()); let connection = self.get_connection_info()?.clone(); - // TODO: check wtf BYPASS - // *self.progress.lock().unwrap() = 100; self.save_config()?; thread::spawn(move || { let status = scan::scan_with_progress(connection_info); @@ -649,13 +648,13 @@ impl<'a> AppInfo<'a> { connection.update_connection_status(ConnectionStatus::ClosedWithSuccess) } Err(e) => { - // TODO: Use Error + info!("An error occured during thread exec: {e}"); + if !connection.has_error() { + connection.set_error(Some(e.into())); + } connection.update_connection_status(ConnectionStatus::ConnectionFailure) } } - - // panic!(); - // TODO: Do something with bad status to avoid false positive }); } AppState::EndWindow => { diff --git a/src/ui_struct.rs b/src/ui_struct.rs index 663f1bd..e09c3a5 100644 --- a/src/ui_struct.rs +++ b/src/ui_struct.rs @@ -45,6 +45,8 @@ pub(crate) struct AppInfo<'a> { pub(crate) connection_info: Option, /// The return data, moved from a mutex to a static place pub(crate) return_data: Vec<(f64, f64)>, + /// Whether an unrecoverable error has been logged (and therefore stop logging it) + pub(crate) logged_message: bool, } #[derive(Debug)] @@ -53,26 +55,39 @@ pub(crate) struct UIUsize { value: usize, /// Increment by witch it can be upped increment: usize, + /// Min value to clamp it to + min_clamp: usize, /// Max value to clamp it to - clamp: usize, + max_clamp: usize, } impl UIUsize { /// Change the value depending on selection pub(crate) fn change_value(&mut self, direction: InputDirection) { match direction { - InputDirection::Up => self.value = self.value.add(self.increment).clamp(0, self.clamp), - InputDirection::Down => self.value = self.value.saturating_sub(self.increment), + InputDirection::Up => { + self.value = self + .value + .add(self.increment) + .clamp(self.min_clamp, self.max_clamp) + } + InputDirection::Down => { + self.value = self + .value + .saturating_sub(self.increment) + .clamp(self.min_clamp, self.max_clamp) + } _ => (), } } /// Create a new UIUsize, usefull for TUI manipulation - pub(crate) fn new(value: usize, increment: usize, clamp: usize) -> Self { + pub(crate) fn new(value: usize, increment: usize, min_clamp: usize, max_clamp: usize) -> Self { Self { value, increment, - clamp, + max_clamp, + min_clamp, } } @@ -205,7 +220,6 @@ impl BaudRateList { /// Create a baudrate from a config file pub(crate) fn from_conf(loaded_conf: &Result) -> BaudRateList { - // TODO: Actually load from baudrate if let Ok(c) = loaded_conf { for (i, baud) in BaudRate::iter().enumerate() { if c.baudrate == baud as u32 { @@ -222,8 +236,16 @@ impl BaudRateList { /// Returns the final selected baudrate pub(crate) fn selected_baudrate(&self) -> Result { Ok(BaudRate::iter() - .nth(self.state.selected().unwrap()) - .unwrap() as u32) + .nth( + self.state + .selected() + .ok_or(TinyUIError::UninitializedItemList( + "Baudrate", + line!(), + file!(), + ))?, + ) + .ok_or(TinyUIError::MenuSelectionError)? as u32) } } @@ -316,7 +338,6 @@ pub(crate) struct MenuItems<'a> { /// Try to guess the best port to preselect fn find_best_port(ports: &[String], saved_config: &Result) -> usize { - // TODO: Try to load from disk then save to disk let mut best_ports = vec!["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"]; let p: Vec<&str> = if let Ok(c) = saved_config { let mut v = vec![&*c.port];