Adds better error handling
This commit is contained in:
parent
3c4ec19600
commit
cc8e6de769
163
src/scan.rs
163
src/scan.rs
|
|
@ -9,8 +9,8 @@ static LONG_WAIT: u64 = 200;
|
|||
/// The standard timeout time
|
||||
static TIMEOUT: u64 = 2000;
|
||||
|
||||
use crate::info;
|
||||
use crate::structs::TinyError;
|
||||
use crate::{info, structs::ConnectionInfo};
|
||||
use log::error;
|
||||
use memchr::memmem;
|
||||
use packed_struct::prelude::*;
|
||||
|
|
@ -41,96 +41,91 @@ static EOF: OnceLock<memmem::Finder<'_>> = OnceLock::new();
|
|||
|
||||
/// Scan a specific range and returns the scan result
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn scan_with_progress(
|
||||
progress: Arc<Mutex<usize>>,
|
||||
scan_info: Arc<Mutex<String>>,
|
||||
scan_message: Arc<Mutex<String>>,
|
||||
return_data: Arc<Mutex<Vec<(f64, f64)>>>,
|
||||
port: String,
|
||||
start: usize,
|
||||
stop: usize,
|
||||
points: usize,
|
||||
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)
|
||||
.timeout(Duration::from_millis(5000))
|
||||
.open(); // .expect("Failed to open port");
|
||||
pub(crate) fn scan_with_progress(connection_info: ConnectionInfo) -> Result<(), TinyError> {
|
||||
info!("Initializying connection: {:#?}", connection_info);
|
||||
let mode = mode_from(connection_info.start, connection_info.stop)?;
|
||||
connection_info.update_message("Opening connection");
|
||||
let port = serialport::new(&connection_info.port, connection_info.baudrate)
|
||||
.timeout(Duration::from_millis(3000))
|
||||
.open();
|
||||
if let Err(e) = port {
|
||||
// *scan_message.lock().unwrap() = "Noo".to_string();
|
||||
error!("Connection error {}", e);
|
||||
connection_info.set_error(Some(TinyError::PortConnection(e.clone()).into()));
|
||||
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;
|
||||
connection_info.update_message("Initialisation...");
|
||||
connection_info.update_progress(5);
|
||||
initialize(&mut port);
|
||||
|
||||
*progress.lock().unwrap() = 15;
|
||||
*scan_message.lock().unwrap() = "Acquiring version & info".to_string();
|
||||
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);
|
||||
// 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);
|
||||
connection_info.update_info(format!("{}{}", v, i));
|
||||
|
||||
*scan_message.lock().unwrap() = "Setting up repeat".to_string();
|
||||
connection_info.update_message("Setting up repeat");
|
||||
// TODO: Investigate this behaviour
|
||||
send_cmd(&mut port, &format!("repeat {}\r", repeat), SHORT_WAIT);
|
||||
// TODO: Allow for user configuration
|
||||
send_cmd(&mut port, "calc aver16\r", SHORT_WAIT);
|
||||
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);
|
||||
|
||||
*progress.lock().unwrap() = 16;
|
||||
*scan_message.lock().unwrap() = "Setting zero...".to_string();
|
||||
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);
|
||||
|
||||
*progress.lock().unwrap() = 17;
|
||||
*scan_message.lock().unwrap() = "Setting up marker".to_string();
|
||||
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);
|
||||
|
||||
*progress.lock().unwrap() = 18;
|
||||
*scan_message.lock().unwrap() = "Setting up scan & mode".to_string();
|
||||
connection_info.update_progress(18);
|
||||
connection_info.update_message("Setting up scan & mode");
|
||||
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);
|
||||
connection_info.update_progress(19);
|
||||
connection_info.update_message("Setting up sweep");
|
||||
send_cmd(
|
||||
&mut port,
|
||||
&format!("sweep start {}\r", connection_info.start),
|
||||
SHORT_WAIT,
|
||||
);
|
||||
send_cmd(
|
||||
&mut port,
|
||||
&format!("sweep stop {}\r", connection_info.stop),
|
||||
SHORT_WAIT,
|
||||
);
|
||||
|
||||
*progress.lock().unwrap() = 20;
|
||||
*scan_message.lock().unwrap() = "Starting scan...".to_string();
|
||||
connection_info.update_progress(20);
|
||||
connection_info.update_message("Starting scan...");
|
||||
send_cmd(&mut port, "sweep\r", SHORT_WAIT);
|
||||
send_cmd(
|
||||
&mut port,
|
||||
&format!("scan {} {} 290 101\r", start, stop),
|
||||
&format!(
|
||||
"scan {} {} 290 101\r",
|
||||
connection_info.start, connection_info.stop
|
||||
),
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
*progress.lock().unwrap() = 22;
|
||||
let name = scanraw(
|
||||
&mut port,
|
||||
progress.clone(),
|
||||
return_data.clone(),
|
||||
start,
|
||||
stop,
|
||||
points,
|
||||
)?;
|
||||
connection_info.update_progress(22);
|
||||
connection_info.update_filename(scanraw(&mut port, connection_info.clone())?);
|
||||
|
||||
// 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
|
||||
);
|
||||
connection_info.update_message("Acquiring version & info");
|
||||
connection_info.update_message("Scan finished");
|
||||
send_cmd(&mut port, "resume\r", SHORT_WAIT);
|
||||
|
||||
wait_sync(LONG_WAIT);
|
||||
*progress.lock().unwrap() = 100;
|
||||
// wait_sync(LONG_WAIT);
|
||||
connection_info.update_progress(100);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -172,23 +167,20 @@ fn wait_sync(duration: u64) {
|
|||
/// Scan raw frequencies
|
||||
fn scanraw(
|
||||
port: &mut Box<dyn SerialPort>,
|
||||
progress: Arc<Mutex<usize>>,
|
||||
return_data: Arc<Mutex<Vec<(f64, f64)>>>,
|
||||
start: usize,
|
||||
stop: usize,
|
||||
points: usize,
|
||||
connection_info: ConnectionInfo,
|
||||
) -> Result<String, TinyError> {
|
||||
unsafe { send_raw(port, &format!("scanraw {} {} {}\r", start, stop, points)) }
|
||||
unsafe {
|
||||
send_raw(
|
||||
port,
|
||||
&format!(
|
||||
"scanraw {} {} {}\r",
|
||||
connection_info.start, connection_info.stop, connection_info.points
|
||||
),
|
||||
)
|
||||
}
|
||||
wait_sync(SHORT_WAIT);
|
||||
let (name, val) = read_scanraw(
|
||||
port,
|
||||
progress,
|
||||
points,
|
||||
start,
|
||||
// TODO: Checks that points are always >1
|
||||
(stop - start) as f64 / (points - 1) as f64,
|
||||
)?;
|
||||
*return_data.lock().unwrap() = val;
|
||||
let (name, val) = read_scanraw(port, connection_info.clone())?;
|
||||
connection_info.update_return_data(val);
|
||||
wait_sync(LONG_WAIT);
|
||||
Ok(name)
|
||||
}
|
||||
|
|
@ -224,6 +216,7 @@ fn read_port_with_progress(
|
|||
let mut res = Vec::new();
|
||||
let finder = EOF.get_or_init(|| memmem::Finder::new("ch>"));
|
||||
while let Ok(r) = port.read(serial_buf.as_mut_slice()) {
|
||||
// TODO: Pass the whole object to avoid this unwrap ?
|
||||
*progress.lock().unwrap() = (100usize.saturating_sub(
|
||||
(80 * (expected.saturating_sub(res.len())).clamp(0, expected)) / expected,
|
||||
))
|
||||
|
|
@ -238,6 +231,7 @@ fn read_port_with_progress(
|
|||
}
|
||||
|
||||
/// Read port without updating progress
|
||||
// TODO: Find a way to avoid code duplication
|
||||
fn read_port(port: &mut Box<dyn SerialPort>) -> Vec<u8> {
|
||||
let mut serial_buf: Vec<u8> = vec![0; 256];
|
||||
let mut res = Vec::new();
|
||||
|
|
@ -258,17 +252,24 @@ fn read_port(port: &mut Box<dyn SerialPort>) -> Vec<u8> {
|
|||
/// Returns a struct summerizing the information processed
|
||||
fn read_scanraw(
|
||||
port: &mut Box<dyn SerialPort>,
|
||||
progress: Arc<Mutex<usize>>,
|
||||
points: usize,
|
||||
start: usize,
|
||||
increment: f64,
|
||||
connection_info: ConnectionInfo,
|
||||
) -> Result<(String, Vec<(f64, f64)>), TinyError> {
|
||||
let v = read_port_with_progress(port, points * 3 + 6, progress);
|
||||
// Find the { marking the beggining
|
||||
parse_data(v, points, start, increment)
|
||||
let v = read_port_with_progress(
|
||||
port,
|
||||
connection_info.points * 3 + 6,
|
||||
connection_info.mutex_progress(),
|
||||
);
|
||||
parse_data(
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
/// A utility function used for parsing the raw data of a scan
|
||||
// TODO: Split save data to another function
|
||||
pub fn parse_data(
|
||||
v: Vec<u8>,
|
||||
points: usize,
|
||||
|
|
|
|||
153
src/structs.rs
153
src/structs.rs
|
|
@ -3,13 +3,13 @@
|
|||
use std::{
|
||||
fs::File,
|
||||
io::{Read, Write},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use strum::IntoEnumIterator;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::ui_struct::{AppInfo, BaudRate};
|
||||
use crate::ui_struct::AppInfo;
|
||||
|
||||
/// The most common error, exposed to the lib user and end used
|
||||
#[derive(Error, Debug)]
|
||||
|
|
@ -48,15 +48,8 @@ pub enum TinyError {
|
|||
#[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")]
|
||||
#[error("The given scan frequencies are inccorect ({0})")]
|
||||
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)]
|
||||
|
|
@ -90,9 +83,20 @@ pub enum TinyUIError {
|
|||
// TODO: Expand
|
||||
#[error("No port was selected")]
|
||||
NoPortSelected,
|
||||
/// Any UI Error
|
||||
#[error("An error occured while processing the scan request")]
|
||||
|
||||
/// 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,
|
||||
/// No return data was created or initialized
|
||||
#[error("An error occured while trying to acquire the return data")]
|
||||
NoReturnData,
|
||||
/// No error was generated, this error is a meta error
|
||||
#[error("An unspecified error occured")]
|
||||
NoErrorSpecified,
|
||||
}
|
||||
|
||||
// impl TinyUIError {
|
||||
|
|
@ -106,7 +110,7 @@ pub(crate) struct SavedConfig {
|
|||
/// The default com port
|
||||
pub(crate) port: String,
|
||||
/// The default baudrate
|
||||
pub(crate) baudrate: usize,
|
||||
pub(crate) baudrate: u32,
|
||||
/// The default start frequency
|
||||
pub(crate) start_frequency: usize,
|
||||
/// The default stop frequency
|
||||
|
|
@ -136,9 +140,7 @@ impl SavedConfig {
|
|||
f.write_all(
|
||||
toml::to_string(&Self {
|
||||
port: arg.port_list.selected_port()?,
|
||||
baudrate: BaudRate::iter()
|
||||
.nth(arg.baudrate.state.selected().unwrap())
|
||||
.unwrap() as usize,
|
||||
baudrate: arg.baudrate.selected_baudrate()?,
|
||||
start_frequency: arg.start_frequency.int_to_usize(),
|
||||
stop_frequency: arg.stop_frequency.int_to_usize(),
|
||||
points: arg.points.int_to_usize(),
|
||||
|
|
@ -167,3 +169,122 @@ pub(crate) enum ConnectionStatus {
|
|||
// /// The connection is closed with a failure
|
||||
// ClosedWithError,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
/// All data needed to handle a connection to the TinySA
|
||||
pub(crate) struct ConnectionInfo {
|
||||
pub(crate) points: usize,
|
||||
pub(crate) baudrate: u32,
|
||||
pub(crate) port: String,
|
||||
progress: Arc<Mutex<usize>>,
|
||||
pub(crate) repeat: usize,
|
||||
return_data: Arc<Mutex<Option<Vec<(f64, f64)>>>>,
|
||||
scan_info: Arc<Mutex<String>>,
|
||||
scan_message: Arc<Mutex<String>>,
|
||||
pub(crate) start: usize,
|
||||
pub(crate) stop: usize,
|
||||
file_name: Arc<Mutex<String>>,
|
||||
connection_status: Arc<Mutex<ConnectionStatus>>,
|
||||
pub(crate) error_raised: Arc<Mutex<Option<TinyUIError>>>,
|
||||
}
|
||||
|
||||
impl ConnectionInfo {
|
||||
/// Create a connection
|
||||
pub(crate) fn new(
|
||||
port: String,
|
||||
baudrate: u32,
|
||||
start: usize,
|
||||
stop: usize,
|
||||
points: usize,
|
||||
repeat: usize,
|
||||
) -> Self {
|
||||
Self {
|
||||
points,
|
||||
port,
|
||||
progress: Arc::new(Mutex::new(0)),
|
||||
repeat,
|
||||
return_data: Arc::new(Mutex::new(None)),
|
||||
scan_info: Arc::new(Mutex::new(String::new())),
|
||||
scan_message: Arc::new(Mutex::new(String::new())),
|
||||
start,
|
||||
stop,
|
||||
baudrate,
|
||||
file_name: Arc::new(Mutex::new(String::new())),
|
||||
connection_status: Arc::new(Mutex::new(ConnectionStatus::Uninitialised)),
|
||||
error_raised: Arc::new(Mutex::new(None)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the generic scan message
|
||||
pub(crate) fn update_message(&self, message: &'static str) {
|
||||
*self.scan_message.lock().unwrap() = message.to_string();
|
||||
}
|
||||
|
||||
/// Updates the scan progress
|
||||
pub(crate) fn update_progress(&self, progress: usize) {
|
||||
*self.progress.lock().unwrap() = progress;
|
||||
}
|
||||
|
||||
/// Update the information of the TinySA
|
||||
pub(crate) fn update_info(&self, message: String) {
|
||||
*self.scan_info.lock().unwrap() = message.to_string();
|
||||
}
|
||||
|
||||
/// A clone of the mutex to keep it updated
|
||||
pub(crate) fn mutex_progress(&self) -> Arc<Mutex<usize>> {
|
||||
self.progress.clone()
|
||||
}
|
||||
|
||||
/// Update the return data with the new points
|
||||
pub(crate) fn update_return_data(&self, return_data: Vec<(f64, f64)>) {
|
||||
*self.return_data.lock().unwrap() = Some(return_data);
|
||||
}
|
||||
|
||||
/// Update the filename with the one choosen by the save method
|
||||
pub(crate) fn update_filename(&self, name: String) {
|
||||
*self.file_name.lock().unwrap() = name;
|
||||
}
|
||||
|
||||
/// Get the current progression level
|
||||
pub(crate) fn get_progress(&self) -> usize {
|
||||
*self.progress.lock().unwrap()
|
||||
}
|
||||
|
||||
/// Get the latest scan message
|
||||
pub(crate) fn get_scan_message(&self) -> String {
|
||||
(*self.scan_message.lock().unwrap()).to_string()
|
||||
}
|
||||
|
||||
/// Get the latest tinySA information (There is no guaranty it is initialised or valid)
|
||||
pub(crate) fn get_scan_info(&self) -> String {
|
||||
(*self.scan_info.lock().unwrap()).to_string()
|
||||
}
|
||||
|
||||
/// Get the latest connection status
|
||||
pub(crate) fn get_connection_status(&self) -> ConnectionStatus {
|
||||
*self.connection_status.lock().unwrap()
|
||||
}
|
||||
|
||||
/// Take the return data and leave none in place
|
||||
pub(crate) fn get_return_data(&self) -> Result<Vec<(f64, f64)>, TinyUIError> {
|
||||
self.return_data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.ok_or(TinyUIError::NoReturnData)
|
||||
}
|
||||
|
||||
/// Updates the connection status
|
||||
pub(crate) fn update_connection_status(&self, new_status: ConnectionStatus) {
|
||||
*self.connection_status.lock().unwrap() = new_status
|
||||
}
|
||||
|
||||
/// Set an error
|
||||
pub(crate) fn set_error(&self, e: Option<TinyUIError>) {
|
||||
*self.error_raised.lock().unwrap() = e;
|
||||
}
|
||||
|
||||
// pub(crate) fn get_error(&self) -> &Option<TinyError> {
|
||||
// self.error_raised.lock().as_ref().unwrap()
|
||||
// }
|
||||
}
|
||||
|
|
|
|||
158
src/ui.rs
158
src/ui.rs
|
|
@ -3,6 +3,7 @@
|
|||
use clap::builder::Resettable;
|
||||
use color_eyre::{eyre::Context, owo_colors::OwoColorize, Section};
|
||||
use core::{panic, time};
|
||||
use log::info;
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
crossterm::{
|
||||
|
|
@ -40,7 +41,9 @@ use tui_textarea::{Input, Key, TextArea};
|
|||
|
||||
use crate::{
|
||||
mleft, mright, scan,
|
||||
structs::{ConnectionStatus, InputDirection, SavedConfig, TinyError, TinyUIError},
|
||||
structs::{
|
||||
ConnectionInfo, ConnectionStatus, InputDirection, SavedConfig, TinyError, TinyUIError,
|
||||
},
|
||||
ui_struct::{
|
||||
AppInfo, AppState, BaudRateList, MenuItems, PortList, SelectedConfig, SelectedFinalConfig,
|
||||
UIUsize, SELECTED_COLOR, UNSELECTED_COLOR,
|
||||
|
|
@ -78,14 +81,9 @@ impl<'a> AppInfo<'a> {
|
|||
start_frequency,
|
||||
stop_frequency,
|
||||
points,
|
||||
progress: Arc::new(Mutex::new(0)),
|
||||
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)),
|
||||
repeat,
|
||||
error: None,
|
||||
scan_error: Arc::new(Mutex::new(None)),
|
||||
connection_info: None,
|
||||
return_data: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -101,7 +99,7 @@ impl<'a> AppInfo<'a> {
|
|||
if event::poll(timeout)? {
|
||||
if let Event::Key(key) = event::read()? {
|
||||
if let Err(e) = self.handle_start_keys(key) {
|
||||
self.error = Some(e);
|
||||
self.get_connection_info()?.set_error(Some(e));
|
||||
self.flow_state = AppState::Error;
|
||||
};
|
||||
};
|
||||
|
|
@ -123,7 +121,7 @@ impl<'a> AppInfo<'a> {
|
|||
AppState::Error => self.draw_error(frame),
|
||||
};
|
||||
if let Err(e) = r {
|
||||
self.error = Some(e);
|
||||
self.get_connection_info()?.set_error(Some(e));
|
||||
self.flow_state = AppState::Error;
|
||||
}
|
||||
Ok(())
|
||||
|
|
@ -318,16 +316,14 @@ impl<'a> AppInfo<'a> {
|
|||
])
|
||||
.areas(main_s);
|
||||
let (pb, status, message) = {
|
||||
let status = self.scan_message.try_lock().unwrap();
|
||||
let status = self.get_connection_info()?.get_scan_message();
|
||||
let status = Paragraph::new(status.clone())
|
||||
.block(Block::bordered().title("Operation"))
|
||||
.style(SELECTED_COLOR);
|
||||
let message = self.scan_info.try_lock().unwrap();
|
||||
let message = self.get_connection_info()?.get_scan_info();
|
||||
let message = Paragraph::new(message.clone())
|
||||
.block(Block::bordered().title("TinySA Info"))
|
||||
.style(SELECTED_COLOR);
|
||||
let progress = self.progress.try_lock().unwrap();
|
||||
|
||||
let pb = self
|
||||
.menu_items
|
||||
.progress_bar
|
||||
|
|
@ -337,17 +333,19 @@ impl<'a> AppInfo<'a> {
|
|||
line!(),
|
||||
file!(),
|
||||
))?
|
||||
.ratio(*progress as f64 / 100.);
|
||||
.ratio(self.get_connection_info()?.get_progress() as f64 / 100.);
|
||||
(pb, status, message)
|
||||
};
|
||||
frame.render_widget(pb.clone(), progress_area);
|
||||
frame.render_widget(status, title_area);
|
||||
frame.render_widget(message, main_area);
|
||||
self.menu_items.progress_bar = Some(pb);
|
||||
if *self.progress.lock().unwrap() >= 100 {
|
||||
// TODO: Use the connection status instead
|
||||
if self.connection_info.as_ref().unwrap().get_progress() >= 100 {
|
||||
self.return_data = self.get_connection_info()?.get_return_data()?;
|
||||
self.next_step()?;
|
||||
}
|
||||
let st = *self.connection_status.lock().unwrap();
|
||||
let st = self.get_connection_info()?.get_connection_status();
|
||||
#[allow(clippy::single_match)]
|
||||
match st {
|
||||
// TODO: Add other failures
|
||||
|
|
@ -357,6 +355,13 @@ impl<'a> AppInfo<'a> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Get a reference to the connection info if it exists
|
||||
fn get_connection_info(&self) -> Result<&ConnectionInfo, TinyUIError> {
|
||||
self.connection_info
|
||||
.as_ref()
|
||||
.ok_or(TinyUIError::NoConnectionInfoCreated)
|
||||
}
|
||||
|
||||
/// Draw the last confirmation window
|
||||
fn draw_error(&mut self, frame: &mut Frame) -> Result<(), TinyUIError> {
|
||||
let [_, main_s, _] = Layout::horizontal([
|
||||
|
|
@ -375,42 +380,66 @@ impl<'a> AppInfo<'a> {
|
|||
])
|
||||
.areas(main_s);
|
||||
|
||||
let conn_status = *self.connection_status.lock().unwrap();
|
||||
info!("An error was raised {:#?}", self.get_connection_info()?);
|
||||
let conn_status = self.get_connection_info()?.get_connection_status();
|
||||
let status_message = match self
|
||||
.scan_error
|
||||
.get_connection_info()?
|
||||
.error_raised
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.unwrap_or(&TinyError::NoErrorSpecified)
|
||||
.unwrap_or(&TinyUIError::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!(),
|
||||
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 = 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));
|
||||
if let Some(m) = &self
|
||||
.get_connection_info()?
|
||||
.error_raised
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
{
|
||||
additional.push_str(&format!("Error: {:?} \n => {}\n", m, m));
|
||||
}
|
||||
let error = Paragraph::new(format!(
|
||||
"Last status: {:?}\nLast message: {}\n{}",
|
||||
conn_status,
|
||||
self.scan_message.lock().unwrap().clone(),
|
||||
self.get_connection_info()?.get_scan_message(),
|
||||
additional
|
||||
))
|
||||
.block(Block::bordered().title("Status"));
|
||||
|
|
@ -438,7 +467,7 @@ impl<'a> AppInfo<'a> {
|
|||
])
|
||||
.areas(main_s);
|
||||
|
||||
let status = *self.connection_status.lock().unwrap();
|
||||
let status = self.get_connection_info()?.get_connection_status();
|
||||
match status {
|
||||
// TODO: | ConnectionStatus::ClosedWithError
|
||||
ConnectionStatus::ConnectionFailure => {
|
||||
|
|
@ -468,13 +497,13 @@ impl<'a> AppInfo<'a> {
|
|||
.style(SELECTED_COLOR);
|
||||
|
||||
// TODO: Don't acquire a mutex at 60Hz
|
||||
let binding = self.return_data.lock().unwrap();
|
||||
// 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())
|
||||
.data(&binding)];
|
||||
.data(&self.return_data)];
|
||||
|
||||
let chart =
|
||||
Chart::new(datasets)
|
||||
|
|
@ -506,7 +535,7 @@ impl<'a> AppInfo<'a> {
|
|||
frame.render_widget(chart, graph_area);
|
||||
let footer = Paragraph::new(format!(
|
||||
"{}, press ↲ or q to exit",
|
||||
self.scan_message.lock().unwrap().clone()
|
||||
self.get_connection_info()?.get_scan_message(),
|
||||
))
|
||||
.centered();
|
||||
frame.render_widget(status, title_area);
|
||||
|
|
@ -597,36 +626,37 @@ impl<'a> AppInfo<'a> {
|
|||
self.flow_state = AppState::Finished;
|
||||
self.init_progress()?;
|
||||
// Start the scan
|
||||
// TODO: Have a struct to avoid this clusterfk
|
||||
let pmtx = self.progress.clone();
|
||||
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();
|
||||
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;
|
||||
// let cstatus = self.get_connection_info()?.get_connection_status();
|
||||
// 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(),
|
||||
self.points.int_to_usize(),
|
||||
self.repeat.int_to_usize(),
|
||||
);
|
||||
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(
|
||||
pmtx, mmtx, cmtx, rdata, port, start, stop, points, repeat,
|
||||
);
|
||||
let status = scan::scan_with_progress(connection_info);
|
||||
match status {
|
||||
Ok(_) => *cstatus.lock().unwrap() = ConnectionStatus::ClosedWithSuccess,
|
||||
Ok(_) => {
|
||||
connection.update_connection_status(ConnectionStatus::ClosedWithSuccess)
|
||||
}
|
||||
Err(e) => {
|
||||
*error.lock().unwrap() = Some(e);
|
||||
*cstatus.lock().unwrap() = ConnectionStatus::ConnectionFailure
|
||||
// TODO: Use Error
|
||||
connection.update_connection_status(ConnectionStatus::ConnectionFailure)
|
||||
}
|
||||
}
|
||||
|
||||
// panic!();
|
||||
// TODO: Do something with bad status to avoid false positive
|
||||
});
|
||||
// scan::scan_with_progress(pmtx, mmtx, cmtx, port).unwrap();
|
||||
}
|
||||
AppState::EndWindow => {
|
||||
self.should_quit = true;
|
||||
|
|
|
|||
|
|
@ -7,15 +7,11 @@ use ratatui::{
|
|||
widgets::{Block, LineGauge, List, ListState, Paragraph},
|
||||
};
|
||||
use serialport::SerialPortInfo;
|
||||
use std::{
|
||||
iter::Iterator,
|
||||
ops::Add,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use std::{iter::Iterator, ops::Add};
|
||||
use strum::{EnumCount, EnumIter};
|
||||
use strum::{FromRepr, IntoEnumIterator};
|
||||
|
||||
use crate::structs::{ConnectionStatus, InputDirection, SavedConfig, TinyError, TinyUIError};
|
||||
use crate::structs::{ConnectionInfo, InputDirection, SavedConfig, TinyError, TinyUIError};
|
||||
|
||||
/// Color of a selected border
|
||||
pub(crate) const SELECTED_COLOR: Color = Color::White;
|
||||
|
|
@ -45,21 +41,10 @@ pub(crate) struct AppInfo<'a> {
|
|||
pub(crate) points: UIUsize,
|
||||
/// Number of times to repeat a measure
|
||||
pub(crate) repeat: UIUsize,
|
||||
/// Global progress
|
||||
pub(crate) progress: Arc<Mutex<usize>>,
|
||||
/// Global initialisation data
|
||||
pub(crate) scan_info: Arc<Mutex<String>>,
|
||||
/// Global message
|
||||
pub(crate) scan_message: Arc<Mutex<String>>,
|
||||
/// Return scan data
|
||||
pub(crate) return_data: Arc<Mutex<Vec<(f64, f64)>>>,
|
||||
/// Connection status, allow for a simple mutex bypass
|
||||
pub(crate) connection_status: Arc<Mutex<ConnectionStatus>>,
|
||||
/// The current last error
|
||||
//TODO: Solve this shite
|
||||
pub(crate) error: Option<TinyUIError>,
|
||||
/// A scan error
|
||||
pub(crate) scan_error: Arc<Mutex<Option<TinyError>>>,
|
||||
/// A struct holding all the information needed to handle a connection with a tinySA
|
||||
pub(crate) connection_info: Option<ConnectionInfo>,
|
||||
/// The return data, moved from a mutex to a static place
|
||||
pub(crate) return_data: Vec<(f64, f64)>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
@ -223,7 +208,7 @@ impl BaudRateList {
|
|||
// TODO: Actually load from baudrate
|
||||
if let Ok(c) = loaded_conf {
|
||||
for (i, baud) in BaudRate::iter().enumerate() {
|
||||
if c.baudrate == baud as usize {
|
||||
if c.baudrate == baud as u32 {
|
||||
return Self {
|
||||
state: ListState::default().with_selected(Some(i)),
|
||||
..Default::default()
|
||||
|
|
@ -233,6 +218,13 @@ impl BaudRateList {
|
|||
}
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Returns the final selected baudrate
|
||||
pub(crate) fn selected_baudrate(&self) -> Result<u32, TinyUIError> {
|
||||
Ok(BaudRate::iter()
|
||||
.nth(self.state.selected().unwrap())
|
||||
.unwrap() as u32)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for BaudRateList {
|
||||
|
|
|
|||
Loading…
Reference in New Issue