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