Merge pull request 'First working version' (#2) from gui into main

Reviewed-on: Dandaedre/tiny-wb#2
This commit is contained in:
Dandaedre 2024-09-25 21:41:06 +02:00
commit 7645e8e2c6
7 changed files with 352 additions and 151 deletions

1
.gitignore vendored
View File

@ -20,4 +20,5 @@ Cargo.lock
/target
*.csv
*.log
config.toml

View File

@ -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"

View File

@ -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!();

View File

@ -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
@ -13,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;
@ -52,16 +50,21 @@ 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)
.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();
// *scan_message.lock().unwrap() = "Noo".to_string();
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);
@ -70,22 +73,35 @@ 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);
*scan_message.lock().unwrap() = "Setting up repeat".to_string();
// TODO: Investigate this behaviour
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();
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();
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();
@ -106,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);
@ -114,11 +135,33 @@ 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<String, TinyError> {
// 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",
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(
"Scan frequencies must either be in range (0MHz-240MHz) or (240MHz-960MHz)".to_owned(),
)),
}
}
/// 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<dyn SerialPort>) {
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)
}
@ -143,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);
@ -238,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()))
}

View File

@ -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,19 @@ 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(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)]
@ -72,6 +86,13 @@ 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,
/// Any UI Error
#[error("An error occured while processing the scan request")]
ScanError(#[from] TinyError),
}
// impl TinyUIError {
@ -109,10 +130,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(),
port: arg.port_list.selected_port()?,
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 +147,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,
}

293
src/ui.rs
View File

@ -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,10 @@ 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)),
repeat: UIUsize::new(1, 1, 1000),
error: None,
scan_error: Arc::new(Mutex::new(None)),
}
}
@ -94,7 +98,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;
@ -106,12 +113,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
@ -310,6 +323,77 @@ 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(())
}
/// 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(1),
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_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"));
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);
Ok(())
}
@ -329,117 +413,82 @@ 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 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!(
"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().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",
self.scan_message.lock().unwrap().clone()
))
.centered();
frame.render_widget(status, title_area);
frame.render_widget(footer, footer_area);
}
}
Ok(())
}
@ -477,6 +526,7 @@ impl<'a> AppInfo<'a> {
},
AppState::EndWindow => (),
AppState::Finished => (),
AppState::Error => (),
}
}
@ -503,6 +553,7 @@ impl<'a> AppInfo<'a> {
}
AppState::EndWindow => None,
AppState::Finished => None,
AppState::Error => None,
} {
self.flow_state = s;
}
@ -526,17 +577,28 @@ impl<'a> AppInfo<'a> {
let mmtx = self.scan_info.clone();
let cmtx = self.scan_message.clone();
let rdata = self.return_data.clone();
let port = self.port_list.selected_port();
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;
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,
Err(e) => {
*error.lock().unwrap() = Some(e);
*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();
@ -548,6 +610,9 @@ impl<'a> AppInfo<'a> {
self.flow_state = AppState::EndWindow;
self.init_end()?;
}
AppState::Error => {
self.should_quit = true;
}
}
Ok(())
}

View File

@ -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;
@ -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<Mutex<usize>>,
/// Global initialisation data
@ -51,7 +53,15 @@ pub(crate) struct AppInfo<'a> {
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>>>,
}
#[derive(Debug)]
pub(crate) struct UIUsize {
/// Current value held by the usize
@ -108,6 +118,8 @@ pub(crate) enum AppState {
EndWindow,
/// Save window
Finished,
/// Error window
Error,
}
impl Default for AppState {
@ -286,8 +298,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<String, TinyUIError> {
Ok(self.ports[self.state.selected().ok_or(TinyUIError::NoPortSelected)?].clone())
}
}