From c4e0538a63dd41acf321329dc88c2ab451e7773c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 25 Sep 2024 00:39:23 +0200 Subject: [PATCH 1/4] First working version --- src/scan.rs | 30 +++++++- src/structs.rs | 32 +++++++- src/ui.rs | 197 +++++++++++++++++++++-------------------------- src/ui_struct.rs | 5 +- 4 files changed, 148 insertions(+), 116 deletions(-) diff --git a/src/scan.rs b/src/scan.rs index 1e02dc1..64b1088 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -53,12 +53,13 @@ pub(crate) fn scan_with_progress( stop: usize, points: usize, ) -> Result<(), TinyError> { + // TODO: Pass the connection status mutex to advance it *scan_message.lock().unwrap() = "Oppening connection".to_string(); let port = serialport::new(port, 115_200) .timeout(Duration::from_millis(3000)) .open(); // .expect("Failed to open port"); if let Err(e) = port { - *scan_message.lock().unwrap() = "Noo".to_string(); + // *scan_message.lock().unwrap() = "Noo".to_string(); return Err(TinyError::PortConnection(e)); } let mut port = port.unwrap(); @@ -70,6 +71,10 @@ pub(crate) fn scan_with_progress( *scan_message.lock().unwrap() = "Acquiring version & info".to_string(); 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); + } *scan_info.lock().unwrap() = format!("{}{}", v, i); *progress.lock().unwrap() = 16; @@ -77,12 +82,18 @@ pub(crate) fn scan_with_progress( send_cmd(&mut port, &format!("zero {}\r", OFFSET), SHORT_WAIT); *progress.lock().unwrap() = 17; - *scan_message.lock().unwrap() = "Setting up scan & mode".to_string(); + *scan_message.lock().unwrap() = "Setting up marker".to_string(); send_cmd(&mut port, "marker\r", SHORT_WAIT); send_cmd(&mut port, "pause\r", SHORT_WAIT); - send_cmd(&mut port, "mode high input\r", SHORT_WAIT); *progress.lock().unwrap() = 18; + *scan_message.lock().unwrap() = "Setting up scan & mode".to_string(); + // return Err(TinyError::ConfigNotFound); + // panic!(); + let mode = mode_from(start, stop)?; + send_cmd(&mut port, &format!("mode {} input\r", mode), SHORT_WAIT); + + *progress.lock().unwrap() = 19; *scan_message.lock().unwrap() = "Setting up sweep".to_string(); send_cmd(&mut port, &format!("sweep start {}\r", START), SHORT_WAIT); send_cmd(&mut port, &format!("sweep stop {}\r", STOP), SHORT_WAIT); @@ -114,6 +125,19 @@ pub(crate) fn scan_with_progress( Ok(()) } +/// 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); + } + 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()), + _ => Err(TinyError::BadScanFrequencies), + } +} + /// A (lame) function used for initialisation: /// Wait's for a whole timeout for data stuck in the buffer and dumps it fn initialize(port: &mut Box) { diff --git a/src/structs.rs b/src/structs.rs index 1d5b8c5..2fe1748 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -6,9 +6,10 @@ use std::{ }; use serde::{Deserialize, Serialize}; +use strum::IntoEnumIterator; use thiserror::Error; -use crate::ui_struct::AppInfo; +use crate::ui_struct::{AppInfo, BaudRate}; /// The most common error, exposed to the lib user and end used #[derive(Error, Debug)] @@ -43,6 +44,13 @@ pub enum TinyError { /// The config file couldn't be parsed as a valid toml #[error("The config config.toml couldn't be written")] InvalidDataForConfig(#[from] toml::ser::Error), + /// The version couldn't be acquired, likely a bogus connection + #[error("Couldn't acquire the version of the device connected to the specified port")] + NoVersionFound, + /// The given scan frequencies are incorrect + // TODO: Expand + #[error("The given scan frequencies are inccorect")] + BadScanFrequencies, } #[allow(missing_docs, clippy::missing_docs_in_private_items)] @@ -109,10 +117,13 @@ 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(), - baudrate: arg.baudrate.state.selected().unwrap(), + baudrate: BaudRate::iter() + .nth(arg.baudrate.state.selected().unwrap()) + .unwrap() as usize, start_frequency: arg.start_frequency.int_to_usize(), stop_frequency: arg.stop_frequency.int_to_usize(), points: arg.points.int_to_usize(), @@ -123,3 +134,20 @@ impl SavedConfig { Ok(()) } } + +/// The various status the connection can take +#[derive(Debug, Clone, Copy)] +pub(crate) enum ConnectionStatus { + /// The connection was created with no initialisation data + Uninitialised, + // /// The connection has initialisation data but wasn't established + // Initialised, + // /// The connection was established + // Connected, + /// The connection coudn't be done, with a string explaining the error + ConnectionFailure, + /// The connection is closed and the connection was a succes + ClosedWithSuccess, + // /// The connection is closed with a failure + // ClosedWithError, +} diff --git a/src/ui.rs b/src/ui.rs index 6e91b0b..b3bce1a 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -1,7 +1,7 @@ //! The (minimal) user interface to control the program #![allow(unused_imports)] use clap::builder::Resettable; -use color_eyre::{owo_colors::OwoColorize, Section}; +use color_eyre::{eyre::Context, owo_colors::OwoColorize, Section}; use core::{panic, time}; use ratatui::{ buffer::Buffer, @@ -40,7 +40,7 @@ use tui_textarea::{Input, Key, TextArea}; use crate::{ mleft, mright, scan, - structs::{InputDirection, SavedConfig, TinyError, TinyUIError}, + structs::{ConnectionStatus, InputDirection, SavedConfig, TinyError, TinyUIError}, ui_struct::{ AppInfo, AppState, BaudRateList, MenuItems, PortList, SelectedConfig, SelectedFinalConfig, UIUsize, SELECTED_COLOR, UNSELECTED_COLOR, @@ -80,6 +80,7 @@ impl<'a> AppInfo<'a> { scan_info: Arc::new(Mutex::new(String::new())), scan_message: Arc::new(Mutex::new(String::new())), return_data: Arc::new(Mutex::new(Vec::new())), + connection_status: Arc::new(Mutex::new(ConnectionStatus::Uninitialised)), } } @@ -310,6 +311,13 @@ impl<'a> AppInfo<'a> { if *self.progress.lock().unwrap() >= 100 { self.next_step()?; } + let st = *self.connection_status.lock().unwrap(); + #[allow(clippy::single_match)] + match st { + // TODO: Add other failures + ConnectionStatus::ConnectionFailure => self.next_step()?, + _ => (), + } Ok(()) } @@ -329,117 +337,80 @@ impl<'a> AppInfo<'a> { Constraint::Length(1), ]) .areas(main_s); - let status = Paragraph::new(format!( - "The scan ({}Mhz - {}Mhz) of {} points finished sucessfuly", - self.start_frequency.int_to_usize(), - self.stop_frequency.int_to_usize(), - self.points.int_to_usize() - )) - .block(Block::bordered().title("Status")) - .style(SELECTED_COLOR); - // let dataset = Dataset::default() - // .marker(symbols::Marker::HalfBlock) - // .style(Style::new().fg(Color::Blue)) - // .graph_type(GraphType::Bar) - // // a bell curve - // .data(&[ - // (250., -2.9), - // (260., -13.5), - // (270., -41.1), - // (280., -80.1), - // (390., -100.0), - // (500., -80.1), - // (610., -41.1), - // (720., -13.5), - // (830., -2.9), - // (930., -2.9), - // ]); - // let chart = Chart::new(vec![dataset]) - // .block( - // Block::bordered().title( - // Title::default() - // .content("Bar chart".cyan().bold()) - // .alignment(Alignment::Center), - // ), - // ) - // .x_axis( - // Axis::default() - // .style(Style::default().gray()) - // .bounds([ - // self.start_frequency.mhz_to_usize() as f64, - // self.stop_frequency.mhz_to_usize() as f64, - // ]) - // .labels([ - // self.start_frequency.int_to_string().bold(), - // format!( - // "{}", - // (self.stop_frequency.int_to_usize() - // - self.start_frequency.int_to_usize() / 2) - // ) - // .into(), - // self.stop_frequency.int_to_string().bold(), - // ]), - // ) - // .y_axis( - // Axis::default() - // .style(Style::default().gray()) - // .bounds([-128.0, 0.]) - // .labels(["-128".bold(), "-64".into(), "0".bold()]), - // ); - // // .hidden_legend_constraints((Constraint::Ratio(1, 2), Constraint::Ratio(1, 2))); + let status = *self.connection_status.lock().unwrap(); + match status { + // TODO: | ConnectionStatus::ClosedWithError + ConnectionStatus::ConnectionFailure => { + let status = Paragraph::new( + // TODO: Be more explicit with errors + "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); + } + _ => { + let status = Paragraph::new(format!( + "The scan of {} points in the range ({}Mhz - {}Mhz) finished sucessfuly", + self.points.int_to_usize(), + self.start_frequency.int_to_usize(), + self.stop_frequency.int_to_usize(), + )) + .block(Block::bordered().title("Status")) + .style(SELECTED_COLOR); - // TODO: Don't acquire a mutex at 60Hz - let binding = self.return_data.lock().unwrap(); - let datasets = vec![Dataset::default() - // .name("Heavy") - .marker(Marker::Dot) - .graph_type(GraphType::Scatter) - .style(Style::new().yellow()) - .data(&binding)]; + // TODO: Don't acquire a mutex at 60Hz + let binding = self.return_data.lock().unwrap(); + let datasets = vec![Dataset::default() + // .name("Heavy") + .marker(Marker::Dot) + .graph_type(GraphType::Scatter) + .style(Style::new().yellow()) + .data(&binding)]; - let chart = Chart::new(datasets) - // .block( - // Block::bordered().title( - // Title::default() - // .content("Scatter chart".cyan().bold()) - // .alignment(Alignment::Center), - // ), - // ) - .x_axis( - Axis::default() - // .title("Year") - .bounds([ - self.start_frequency.int_to_usize() as f64, - self.stop_frequency.int_to_usize() as f64, - ]) - .style(Style::default().fg(Color::Gray)) - .labels([ - self.start_frequency.int_to_string(), - format!( - "{}", - (self.stop_frequency.int_to_usize() - - self.start_frequency.int_to_usize()) - / 2 - ), - self.stop_frequency.int_to_string(), - ]), - ) - .y_axis( - Axis::default() - // .title("Cost") - .bounds([-128., 0.]) - .style(Style::default().fg(Color::Gray)) - .labels(["-128dbm", "-64dbm", "0dbm"]), - ); - frame.render_widget(chart, graph_area); - 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); + let chart = Chart::new(datasets) + .x_axis( + Axis::default() + .bounds([ + self.start_frequency.int_to_usize() as f64, + self.stop_frequency.int_to_usize() as f64, + ]) + .style(Style::default().fg(Color::Gray)) + .labels([ + format!("{}MHz", self.start_frequency.int_to_string()), + format!( + "{}MHz", + self.start_frequency.int_to_usize() + + (self.stop_frequency.int_to_usize() + - self.start_frequency.int_to_usize()) + / 2 + ), + format!("{}MHz", self.stop_frequency.int_to_string()), + ]), + ) + .y_axis( + Axis::default() + .bounds([-128., 0.]) + .style(Style::default().fg(Color::Gray)) + .labels(["-128dbm", "-64dbm", "0dbm"]), + ); + frame.render_widget(chart, graph_area); + 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); + } + } Ok(()) } @@ -526,6 +497,7 @@ impl<'a> AppInfo<'a> { let mmtx = self.scan_info.clone(); let cmtx = self.scan_message.clone(); let rdata = self.return_data.clone(); + let cstatus = self.connection_status.clone(); let port = self.port_list.selected_port(); let start = self.start_frequency.mhz_to_usize(); let stop = self.stop_frequency.mhz_to_usize(); @@ -537,6 +509,11 @@ impl<'a> AppInfo<'a> { let status = scan::scan_with_progress( pmtx, mmtx, cmtx, rdata, port, start, stop, points, ); + match status { + Ok(_) => *cstatus.lock().unwrap() = ConnectionStatus::ClosedWithSuccess, + Err(_) => *cstatus.lock().unwrap() = ConnectionStatus::ConnectionFailure, + } + // panic!(); // TODO: Do something with bad status to avoid false positive }); // scan::scan_with_progress(pmtx, mmtx, cmtx, port).unwrap(); diff --git a/src/ui_struct.rs b/src/ui_struct.rs index 9fa56c0..5218752 100644 --- a/src/ui_struct.rs +++ b/src/ui_struct.rs @@ -15,7 +15,7 @@ use std::{ use strum::{EnumCount, EnumIter}; use strum::{FromRepr, IntoEnumIterator}; -use crate::structs::{InputDirection, SavedConfig, TinyError, TinyUIError}; +use crate::structs::{ConnectionStatus, InputDirection, SavedConfig, TinyError, TinyUIError}; /// Color of a selected border pub(crate) const SELECTED_COLOR: Color = Color::White; @@ -51,7 +51,10 @@ pub(crate) struct AppInfo<'a> { pub(crate) scan_message: Arc>, /// Return scan data pub(crate) return_data: Arc>>, + /// Connection status, allow for a simple mutex bypass + pub(crate) connection_status: Arc>, } + #[derive(Debug)] pub(crate) struct UIUsize { /// Current value held by the usize From 7606cf967fbc21f75afcf57f9beebe998c7a009e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 25 Sep 2024 06:13:42 -0500 Subject: [PATCH 2/4] Fixes a repeat issue --- src/scan.rs | 18 +++++++++--------- src/ui.rs | 4 +++- src/ui_struct.rs | 2 ++ 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/scan.rs b/src/scan.rs index 64b1088..5ecb42f 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -1,9 +1,5 @@ //! The "lib" used for all scan related functions -/// The default start value for a scan -static START: usize = 240_000_000; -/// The default stop value for a scan -static STOP: usize = 959_000_000; /// The offset used for sending data static OFFSET: usize = 128; /// The base delay used inbetween commands @@ -52,11 +48,12 @@ pub(crate) fn scan_with_progress( start: usize, stop: usize, points: usize, + repeat: usize, ) -> Result<(), TinyError> { // TODO: Pass the connection status mutex to advance it *scan_message.lock().unwrap() = "Oppening connection".to_string(); let port = serialport::new(port, 115_200) - .timeout(Duration::from_millis(3000)) + .timeout(Duration::from_millis(5000)) .open(); // .expect("Failed to open port"); if let Err(e) = port { // *scan_message.lock().unwrap() = "Noo".to_string(); @@ -77,6 +74,11 @@ pub(crate) fn scan_with_progress( } *scan_info.lock().unwrap() = format!("{}{}", v, i); + *scan_message.lock().unwrap() = "Setting up repeat".to_string(); + // TODO: Investigate this behaviour + send_cmd(&mut port, &format!("repeat {}\r", 4), SHORT_WAIT); + send_cmd(&mut port, &format!("calc aver16\r"), SHORT_WAIT); + *progress.lock().unwrap() = 16; *scan_message.lock().unwrap() = "Setting zero...".to_string(); send_cmd(&mut port, &format!("zero {}\r", OFFSET), SHORT_WAIT); @@ -88,15 +90,13 @@ pub(crate) fn scan_with_progress( *progress.lock().unwrap() = 18; *scan_message.lock().unwrap() = "Setting up scan & mode".to_string(); - // return Err(TinyError::ConfigNotFound); - // panic!(); let mode = mode_from(start, stop)?; send_cmd(&mut port, &format!("mode {} input\r", mode), SHORT_WAIT); *progress.lock().unwrap() = 19; *scan_message.lock().unwrap() = "Setting up sweep".to_string(); - send_cmd(&mut port, &format!("sweep start {}\r", START), SHORT_WAIT); - send_cmd(&mut port, &format!("sweep stop {}\r", STOP), SHORT_WAIT); + send_cmd(&mut port, &format!("sweep start {}\r", start), SHORT_WAIT); + send_cmd(&mut port, &format!("sweep stop {}\r", stop), SHORT_WAIT); *progress.lock().unwrap() = 20; *scan_message.lock().unwrap() = "Starting scan...".to_string(); diff --git a/src/ui.rs b/src/ui.rs index b3bce1a..538a606 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -81,6 +81,7 @@ impl<'a> AppInfo<'a> { scan_message: Arc::new(Mutex::new(String::new())), return_data: Arc::new(Mutex::new(Vec::new())), connection_status: Arc::new(Mutex::new(ConnectionStatus::Uninitialised)), + repeat: UIUsize::new(1, 1, 1000), } } @@ -502,12 +503,13 @@ impl<'a> AppInfo<'a> { let start = self.start_frequency.mhz_to_usize(); let stop = self.stop_frequency.mhz_to_usize(); let points = self.points.int_to_usize(); + let repeat = self.repeat.int_to_usize(); // BYPASS *self.progress.lock().unwrap() = 100; self.save_config()?; thread::spawn(move || { let status = scan::scan_with_progress( - pmtx, mmtx, cmtx, rdata, port, start, stop, points, + pmtx, mmtx, cmtx, rdata, port, start, stop, points, repeat, ); match status { Ok(_) => *cstatus.lock().unwrap() = ConnectionStatus::ClosedWithSuccess, diff --git a/src/ui_struct.rs b/src/ui_struct.rs index 5218752..fac823f 100644 --- a/src/ui_struct.rs +++ b/src/ui_struct.rs @@ -43,6 +43,8 @@ pub(crate) struct AppInfo<'a> { pub(crate) stop_frequency: UIUsize, /// The number of points pub(crate) points: UIUsize, + /// Number of times to repeat a measure + pub(crate) repeat: UIUsize, /// Global progress pub(crate) progress: Arc>, /// Global initialisation data From e20fa4bd60ad625e2bf84667ebf60de8059c3e93 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 25 Sep 2024 08:27:40 -0500 Subject: [PATCH 3/4] Adds some error handling --- src/structs.rs | 9 ++- src/ui.rs | 143 +++++++++++++++++++++++++++++++++-------------- src/ui_struct.rs | 9 ++- 3 files changed, 116 insertions(+), 45 deletions(-) diff --git a/src/structs.rs b/src/structs.rs index 2fe1748..c39aed2 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -51,6 +51,9 @@ pub enum TinyError { // TODO: Expand #[error("The given scan frequencies are inccorect")] BadScanFrequencies, + /// A ui error happened + #[error("An UI error happened")] + UIError(#[from] TinyUIError), } #[allow(missing_docs, clippy::missing_docs_in_private_items)] @@ -80,6 +83,10 @@ pub enum TinyUIError { // #[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, } // impl TinyUIError { @@ -120,7 +127,7 @@ impl SavedConfig { // TODO: Prone to failure f.write_all( toml::to_string(&Self { - port: arg.port_list.selected_port(), + port: arg.port_list.selected_port()?, baudrate: BaudRate::iter() .nth(arg.baudrate.state.selected().unwrap()) .unwrap() as usize, diff --git a/src/ui.rs b/src/ui.rs index 538a606..52fd7a3 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -82,6 +82,7 @@ impl<'a> AppInfo<'a> { return_data: Arc::new(Mutex::new(Vec::new())), connection_status: Arc::new(Mutex::new(ConnectionStatus::Uninitialised)), repeat: UIUsize::new(1, 1, 1000), + error: None, } } @@ -96,7 +97,10 @@ impl<'a> AppInfo<'a> { let timeout = Duration::from_millis(16); if event::poll(timeout)? { if let Event::Key(key) = event::read()? { - self.handle_start_keys(key)?; + if let Err(e) = self.handle_start_keys(key) { + self.error = Some(e); + self.flow_state = AppState::Error; + }; }; if self.should_quit { break; @@ -108,12 +112,18 @@ impl<'a> AppInfo<'a> { /// Generic draw loop method fn draw(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { - match self.flow_state { + let r = match self.flow_state { AppState::InitialConfig(_) => self.draw_config(frame), AppState::FinalConfig(_) => self.draw_final_config(frame), AppState::Finished => self.draw_progress(frame), AppState::EndWindow => self.draw_end_window(frame), + AppState::Error => self.draw_error(frame), + }; + if let Err(e) = r { + self.error = Some(e); + self.flow_state = AppState::Error; } + Ok(()) } /// Initialisation of the config window @@ -322,6 +332,48 @@ impl<'a> AppInfo<'a> { Ok(()) } + /// Draw the last confirmation window + fn draw_error(&mut self, frame: &mut Frame) -> Result<(), TinyUIError> { + let [_, main_s, _] = Layout::horizontal([ + Constraint::Min(7), + Constraint::Percentage(90), + Constraint::Min(7), + ]) + .areas(frame.area()); + let [title_area, _main_area, message_area, _, footer_area] = Layout::vertical([ + Constraint::Length(3), + Constraint::Length(1), + Constraint::Min(10), + Constraint::Length(1), + Constraint::Length(1), + ]) + .areas(main_s); + + let conn_status = *self.connection_status.lock().unwrap(); + let status = Paragraph::new( + // TODO: Be more explicit with errors + "The scan couldn't be performed, please check your connection".to_string(), + ) + .block(Block::bordered().title("Status")) + .style(Color::Red); + let error = Paragraph::new( + // TODO: Be more explicit with errors + format!( + "Last status: {:?}\nLast message: {}\nError: {:?}", + conn_status, + self.scan_message.lock().unwrap().clone(), + self.error + ), + ) + .block(Block::bordered().title("Status")); + // .style(Color::Red); + let footer = Paragraph::new(format!("Press ↲ or q to exit")).centered(); + frame.render_widget(status, title_area); + frame.render_widget(error, message_area); + frame.render_widget(footer, footer_area); + Ok(()) + } + /// Draw the last confirmation window fn draw_end_window(&mut self, frame: &mut Frame) -> Result<(), TinyUIError> { let [_, main_s, _] = Layout::horizontal([ @@ -343,19 +395,20 @@ impl<'a> AppInfo<'a> { match status { // TODO: | ConnectionStatus::ClosedWithError ConnectionStatus::ConnectionFailure => { - let status = Paragraph::new( - // TODO: Be more explicit with errors - "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); + // 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; } _ => { let status = Paragraph::new(format!( @@ -376,32 +429,33 @@ impl<'a> AppInfo<'a> { .style(Style::new().yellow()) .data(&binding)]; - let chart = Chart::new(datasets) - .x_axis( - Axis::default() - .bounds([ - self.start_frequency.int_to_usize() as f64, - self.stop_frequency.int_to_usize() as f64, - ]) - .style(Style::default().fg(Color::Gray)) - .labels([ - format!("{}MHz", self.start_frequency.int_to_string()), - format!( - "{}MHz", - self.start_frequency.int_to_usize() - + (self.stop_frequency.int_to_usize() - - self.start_frequency.int_to_usize()) - / 2 - ), - format!("{}MHz", self.stop_frequency.int_to_string()), - ]), - ) - .y_axis( - Axis::default() - .bounds([-128., 0.]) - .style(Style::default().fg(Color::Gray)) - .labels(["-128dbm", "-64dbm", "0dbm"]), - ); + let chart = + Chart::new(datasets) + .x_axis( + Axis::default() + .bounds([ + self.start_frequency.int_to_usize() as f64, + self.stop_frequency.int_to_usize() as f64, + ]) + .style(Style::default().fg(Color::Gray)) + .labels([ + format!("{}MHz", self.start_frequency.int_to_string()), + format!( + "{}MHz", + self.start_frequency.int_to_usize() + + (self.stop_frequency.int_to_usize().saturating_sub( + self.start_frequency.int_to_usize() + )) / 2 + ), + format!("{}MHz", self.stop_frequency.int_to_string()), + ]), + ) + .y_axis( + Axis::default() + .bounds([-128., 0.]) + .style(Style::default().fg(Color::Gray)) + .labels(["-128dbm", "-64dbm", "0dbm"]), + ); frame.render_widget(chart, graph_area); let footer = Paragraph::new(format!( "{}, press ↲ or q to exit", @@ -449,6 +503,7 @@ impl<'a> AppInfo<'a> { }, AppState::EndWindow => (), AppState::Finished => (), + AppState::Error => (), } } @@ -475,6 +530,7 @@ impl<'a> AppInfo<'a> { } AppState::EndWindow => None, AppState::Finished => None, + AppState::Error => None, } { self.flow_state = s; } @@ -499,7 +555,7 @@ impl<'a> AppInfo<'a> { let cmtx = self.scan_message.clone(); let rdata = self.return_data.clone(); let cstatus = self.connection_status.clone(); - let port = self.port_list.selected_port(); + let port = self.port_list.selected_port()?; let start = self.start_frequency.mhz_to_usize(); let stop = self.stop_frequency.mhz_to_usize(); let points = self.points.int_to_usize(); @@ -527,6 +583,9 @@ impl<'a> AppInfo<'a> { self.flow_state = AppState::EndWindow; self.init_end()?; } + AppState::Error => { + self.should_quit = true; + } } Ok(()) } diff --git a/src/ui_struct.rs b/src/ui_struct.rs index fac823f..18e9bb5 100644 --- a/src/ui_struct.rs +++ b/src/ui_struct.rs @@ -55,6 +55,9 @@ pub(crate) struct AppInfo<'a> { pub(crate) return_data: Arc>>, /// Connection status, allow for a simple mutex bypass pub(crate) connection_status: Arc>, + /// The current last error + //TODO: Solve this shite + pub(crate) error: Option, } #[derive(Debug)] @@ -113,6 +116,8 @@ pub(crate) enum AppState { EndWindow, /// Save window Finished, + /// Error window + Error, } impl Default for AppState { @@ -291,8 +296,8 @@ impl PortList { } /// Returns the final selected port - pub(crate) fn selected_port(&self) -> String { - self.ports[self.state.selected().unwrap()].clone() + pub(crate) fn selected_port(&self) -> Result { + Ok(self.ports[self.state.selected().ok_or(TinyUIError::NoPortSelected)?].clone()) } } From 222c9cb1dbc603728794e52467e68ada040a5d75 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 25 Sep 2024 21:37:15 +0200 Subject: [PATCH 4/4] Adds a lot of debugging Qol --- .gitignore | 1 + Cargo.toml | 5 +-- src/main.rs | 11 ++++++ src/scan.rs | 94 +++++++++++++++++++++++++++++++++++------------- src/structs.rs | 14 +++++--- src/ui.rs | 65 +++++++++++++++++++++++---------- src/ui_struct.rs | 2 ++ 7 files changed, 143 insertions(+), 49 deletions(-) diff --git a/.gitignore b/.gitignore index 365d39a..54b2c93 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,5 @@ Cargo.lock /target *.csv +*.log config.toml diff --git a/Cargo.toml b/Cargo.toml index 510afda..5001917 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,11 +5,12 @@ edition = "2021" [dependencies] chrono = "0.4.38" -# byteorder = "1.5.0" clap = { version = "4.5.17", features = ["derive"] } color-eyre = "0.6.3" +flexi_logger = "0.29.0" human-panic = "2.0.1" -# csv = "1.3.0" +# log = { version = "0.4.22", features = ["max_level_debug", "release_max_level_error"] } +log = { version = "0.4.22"} memchr = "2.7.4" once_cell = "1.19.0" packed_struct = "0.10.1" diff --git a/src/main.rs b/src/main.rs index 7a4603d..6815130 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,18 @@ use color_eyre::Result; use structs::TinyError; use ui_struct::AppInfo; +use flexi_logger::{FileSpec, Logger, WriteMode}; +use log::info; + fn main() -> Result<(), TinyError> { + let _logger = Logger::try_with_str("info, my::critical::module=trace") + .unwrap() + .log_to_file(FileSpec::default()) + .write_mode(WriteMode::BufferAndFlush) + .start() + .unwrap(); + + info!(target:"info","Logging started"); color_eyre::install()?; let terminal = ratatui::init(); // setup_panic!(); diff --git a/src/scan.rs b/src/scan.rs index 5ecb42f..a02a225 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -9,7 +9,9 @@ static LONG_WAIT: u64 = 200; /// The standard timeout time static TIMEOUT: u64 = 2000; +use crate::info; use crate::structs::TinyError; +use log::error; use memchr::memmem; use packed_struct::prelude::*; use serialport::SerialPort; @@ -48,8 +50,10 @@ pub(crate) fn scan_with_progress( start: usize, stop: usize, points: usize, + // TODO: Add repeat to tui repeat: usize, ) -> Result<(), TinyError> { + let mode = mode_from(start, stop)?; // TODO: Pass the connection status mutex to advance it *scan_message.lock().unwrap() = "Oppening connection".to_string(); let port = serialport::new(port, 115_200) @@ -60,6 +64,7 @@ pub(crate) fn scan_with_progress( return Err(TinyError::PortConnection(e)); } let mut port = port.unwrap(); + // TODO: Show all unitialised data somewhere *scan_message.lock().unwrap() = "Initialisation...".to_string(); *progress.lock().unwrap() = 5; initialize(&mut port); @@ -76,8 +81,9 @@ pub(crate) fn scan_with_progress( *scan_message.lock().unwrap() = "Setting up repeat".to_string(); // TODO: Investigate this behaviour - send_cmd(&mut port, &format!("repeat {}\r", 4), SHORT_WAIT); - send_cmd(&mut port, &format!("calc aver16\r"), SHORT_WAIT); + send_cmd(&mut port, &format!("repeat {}\r", 5), SHORT_WAIT); + // TODO: Allow for user configuration + send_cmd(&mut port, "calc aver16\r", SHORT_WAIT); *progress.lock().unwrap() = 16; *scan_message.lock().unwrap() = "Setting zero...".to_string(); @@ -90,7 +96,6 @@ pub(crate) fn scan_with_progress( *progress.lock().unwrap() = 18; *scan_message.lock().unwrap() = "Setting up scan & mode".to_string(); - let mode = mode_from(start, stop)?; send_cmd(&mut port, &format!("mode {} input\r", mode), SHORT_WAIT); *progress.lock().unwrap() = 19; @@ -117,7 +122,12 @@ pub(crate) fn scan_with_progress( points, )?; - *scan_message.lock().unwrap() = format!("Scan saved as {}", name); + // TODO: Change this awful thing with a struct with all data + *scan_message.lock().unwrap() = format!( + "Scan of {} points saved as {}", + return_data.lock().unwrap().len(), + name + ); send_cmd(&mut port, "resume\r", SHORT_WAIT); wait_sync(LONG_WAIT); @@ -129,12 +139,17 @@ pub(crate) fn scan_with_progress( 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); + return Err(TinyError::BadScanFrequencies(format!( + "Start frequency {}Hz is higher than stop frequency {}Hz", + start, stop + ))); } 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()), - _ => Err(TinyError::BadScanFrequencies), + _ => Err(TinyError::BadScanFrequencies( + "Scan frequencies must either be in range (0MHz-240MHz) or (240MHz-960MHz)".to_owned(), + )), } } @@ -142,7 +157,11 @@ fn mode_from(start: usize, stop: usize) -> Result { /// Wait's for a whole timeout for data stuck in the buffer and dumps it fn initialize(port: &mut Box) { wait_sync(SHORT_WAIT); - read_port(port); + let d = read_port(port); + if !d.is_empty() { + info!(target: "scan", "Pre-init data found"); + info!(target: "scan", "{:?}", String::from_utf8_lossy(&d).to_string()); + } wait_sync(SHORT_WAIT) } @@ -167,7 +186,8 @@ fn scanraw( progress, points, start, - (stop - start) as f64 / points as f64, + // TODO: Checks that points are always >1 + (stop - start) as f64 / (points - 1) as f64, )?; *return_data.lock().unwrap() = val; wait_sync(LONG_WAIT); @@ -262,24 +282,50 @@ pub fn parse_data( let mut csvdata = Vec::with_capacity(points); if let Some(begining) = memchr::memchr(b'{', &v) { // Finds the } marking the end - if let Some(end) = memchr::memchr(b'}', &v) { - let data = &v[begining + 1..end]; - for (i, slice) in data.chunks_exact(3).enumerate() { - let s: &[u8; 3] = &[slice[0], slice[1], slice[2]]; - let d = DataPoint::unpack(s)?; - let (pos, val) = ( - (i as f64 * increment + start as f64) / 1000000., - u16_to_f64(d.value), - ); + // Assert no bogus data is sent ? just check lenght answer ? + let end_tmp = v.len(); + // if let Some(end) = memchr::memchr(b'}', &v) { + let data = &v[begining + 1..end_tmp]; - csvdata.push((pos, val)); - writeln!(out, "{},{}", pos, val)?; - } - // TODO: Dont return use mutex - Ok((name, csvdata)) - } else { - Err(TinyError::ParseEnd("}".to_owned())) + let mut end = end_tmp; + let chunks_exact = data.chunks_exact(3); + if chunks_exact.remainder().is_empty() { + return Err(TinyError::ParseEnd( + "The data received doesn't have a end char (empty)".to_owned(), + )); + } else if chunks_exact.remainder()[0] != b'}' { + // No end char, bogus + return Err(TinyError::ParseEnd( + "The returned data doesn't have the right end char".to_owned(), + )); } + for (i, slice) in chunks_exact.enumerate() { + let s: &[u8; 3] = &[slice[0], slice[1], slice[2]]; + let d = DataPoint::unpack(s)?; + if d.c == b'}' { + // Found an end and the rest is garbage + end = i * 3; + // TODO: why doesn't it pop ? + info!("Found an end at {end}"); + break; + } else if d.c != b'x' { + // The alignment char is wrong + error!("Wrong alignment char"); + return Err(TinyError::ParseEnd("Wrong alignement char".to_owned())); + } + let (pos, val) = ( + (i as f64 * increment + start as f64) / 1000000., + u16_to_f64(d.value), + ); + info!("{},{},{} : {pos},{val}", i, increment, start); + + csvdata.push((pos, val)); + writeln!(out, "{},{}", pos, val,)?; + } + // TODO: Dont return use mutex + // info!("debug",format!("{} {}", data.len(), v.len()); + info!("End at {end} {}", v[end - 1]); + Ok((name, csvdata)) } else { Err(TinyError::ParseBeggining("{".to_owned())) } diff --git a/src/structs.rs b/src/structs.rs index c39aed2..04170e7 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -50,10 +50,13 @@ pub enum TinyError { /// The given scan frequencies are incorrect // TODO: Expand #[error("The given scan frequencies are inccorect")] - BadScanFrequencies, - /// A ui error happened - #[error("An UI error happened")] - UIError(#[from] TinyUIError), + BadScanFrequencies(String), + /// The error wasn't caused during the scanning process + #[error("Unspecified error")] + NoErrorSpecified, + // /// A ui error happened + // #[error("An UI error happened")] + // UIError(#[from] TinyUIError), } #[allow(missing_docs, clippy::missing_docs_in_private_items)] @@ -87,6 +90,9 @@ pub enum TinyUIError { // TODO: Expand #[error("No port was selected")] NoPortSelected, + /// Any UI Error + #[error("An error occured while processing the scan request")] + ScanError(#[from] TinyError), } // impl TinyUIError { diff --git a/src/ui.rs b/src/ui.rs index 52fd7a3..5bd28c3 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -83,6 +83,7 @@ impl<'a> AppInfo<'a> { connection_status: Arc::new(Mutex::new(ConnectionStatus::Uninitialised)), repeat: UIUsize::new(1, 1, 1000), error: None, + scan_error: Arc::new(Mutex::new(None)), } } @@ -340,7 +341,8 @@ impl<'a> AppInfo<'a> { Constraint::Min(7), ]) .areas(frame.area()); - let [title_area, _main_area, message_area, _, footer_area] = Layout::vertical([ + let [_, title_area, _main_area, message_area, _, footer_area] = Layout::vertical([ + Constraint::Length(1), Constraint::Length(3), Constraint::Length(1), Constraint::Min(10), @@ -350,24 +352,45 @@ impl<'a> AppInfo<'a> { .areas(main_s); let conn_status = *self.connection_status.lock().unwrap(); - let status = Paragraph::new( - // TODO: Be more explicit with errors - "The scan couldn't be performed, please check your connection".to_string(), - ) - .block(Block::bordered().title("Status")) - .style(Color::Red); - let error = Paragraph::new( - // TODO: Be more explicit with errors - format!( - "Last status: {:?}\nLast message: {}\nError: {:?}", - conn_status, - self.scan_message.lock().unwrap().clone(), - self.error - ), - ) + let status_message = match self + .scan_error + .lock() + .unwrap() + .as_ref() + .unwrap_or(&TinyError::NoErrorSpecified) + { + TinyError::ParseBeggining(_) => "An error occured while receiving data, the scan never sent back any valid data", + TinyError::ParseEnd(_) => "An error occured while receiving data, scan was interupted before ending properly", + TinyError::PortConnection(_) => "An error occured while trying to connect, check the selected port and baudrate", + TinyError::NoVersionFound => "An error forbid the gathering of the version, check your TinySA is connected and powered on", + TinyError::BadScanFrequencies(_) => "An error occured because the scan frequencies weren't set correctly", + TinyError::NoErrorSpecified => "An error occured while processing the scan", + TinyError::OpenOutput(_) => todo!(), + TinyError::TUIInitialization(_) => todo!(), + TinyError::TUIRuntimeError(_) => todo!(), + TinyError::TUIPackingError(_) => todo!(), + TinyError::ConfigNotFound => todo!(), + TinyError::InvalidConfig(_) => todo!(), + TinyError::InvalidDataForConfig(_) => todo!(), + }; + let status = Paragraph::new(status_message) + .block(Block::bordered().title("Status")) + .style(Color::Red); + let mut additional = String::new(); + if let Some(m) = &self.error { + additional.push_str(&format!("Error: {:?} => {}\n", m, m)); + } + if let Some(m) = &*self.scan_error.lock().unwrap() { + additional.push_str(&format!("Scan Error: {:?} => {}\n", m, m)); + } + let error = Paragraph::new(format!( + "Last status: {:?}\nLast message: {}\n{}", + conn_status, + self.scan_message.lock().unwrap().clone(), + additional + )) .block(Block::bordered().title("Status")); - // .style(Color::Red); - let footer = Paragraph::new(format!("Press ↲ or q to exit")).centered(); + let footer = Paragraph::new("Press ↲ or q to exit".to_string()).centered(); frame.render_widget(status, title_area); frame.render_widget(error, message_area); frame.render_widget(footer, footer_area); @@ -560,6 +583,7 @@ impl<'a> AppInfo<'a> { let stop = self.stop_frequency.mhz_to_usize(); let points = self.points.int_to_usize(); let repeat = self.repeat.int_to_usize(); + let error = self.scan_error.clone(); // BYPASS *self.progress.lock().unwrap() = 100; self.save_config()?; @@ -569,7 +593,10 @@ impl<'a> AppInfo<'a> { ); match status { Ok(_) => *cstatus.lock().unwrap() = ConnectionStatus::ClosedWithSuccess, - Err(_) => *cstatus.lock().unwrap() = ConnectionStatus::ConnectionFailure, + Err(e) => { + *error.lock().unwrap() = Some(e); + *cstatus.lock().unwrap() = ConnectionStatus::ConnectionFailure + } } // panic!(); // TODO: Do something with bad status to avoid false positive diff --git a/src/ui_struct.rs b/src/ui_struct.rs index 18e9bb5..dd9074c 100644 --- a/src/ui_struct.rs +++ b/src/ui_struct.rs @@ -58,6 +58,8 @@ pub(crate) struct AppInfo<'a> { /// The current last error //TODO: Solve this shite pub(crate) error: Option, + /// A scan error + pub(crate) scan_error: Arc>>, } #[derive(Debug)]