First "working" version
This commit is contained in:
parent
8fcf274965
commit
83b78b632c
|
|
@ -20,3 +20,4 @@ Cargo.lock
|
|||
|
||||
/target
|
||||
*.csv
|
||||
config.toml
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ version = "0.1.0"
|
|||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
chrono = "0.4.38"
|
||||
# byteorder = "1.5.0"
|
||||
clap = { version = "4.5.17", features = ["derive"] }
|
||||
color-eyre = "0.6.3"
|
||||
|
|
@ -13,9 +14,11 @@ memchr = "2.7.4"
|
|||
once_cell = "1.19.0"
|
||||
packed_struct = "0.10.1"
|
||||
ratatui = "0.28.1"
|
||||
serde = { version = "1.0.210", features = ["derive"] }
|
||||
serialport = "4.5.0"
|
||||
strum = { version = "0.26.3", features = ["derive"] }
|
||||
thiserror = "1.0.63"
|
||||
toml = "0.8.19"
|
||||
tui-textarea = "0.6.1"
|
||||
|
||||
[profile.release]
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
//! and will not offer any scripting capabilities
|
||||
|
||||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
#![allow(dead_code)]
|
||||
// #![allow(dead_code)]
|
||||
mod scan;
|
||||
mod structs;
|
||||
mod ui;
|
||||
|
|
|
|||
79
src/scan.rs
79
src/scan.rs
|
|
@ -4,10 +4,6 @@
|
|||
static START: usize = 240_000_000;
|
||||
/// The default stop value for a scan
|
||||
static STOP: usize = 959_000_000;
|
||||
/// The default number of points
|
||||
static POINTS: usize = 290; //(STOP - START) * 10;
|
||||
/// The default increment (deduced from the number of points)
|
||||
static INCREMENT: usize = (STOP - START) / POINTS; // 1000/100
|
||||
/// The offset used for sending data
|
||||
static OFFSET: usize = 128;
|
||||
/// The base delay used inbetween commands
|
||||
|
|
@ -29,6 +25,8 @@ use std::{
|
|||
time::Duration,
|
||||
};
|
||||
|
||||
use chrono::Local;
|
||||
|
||||
/// A single datapoint, using a struct might be overkill but msb/lsb could become a problem in the future
|
||||
#[derive(PackedStruct, Debug)]
|
||||
#[packed_struct(endian = "lsb")]
|
||||
|
|
@ -44,20 +42,26 @@ pub struct DataPoint {
|
|||
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,
|
||||
) -> Result<(), TinyError> {
|
||||
*scan_message.lock().unwrap() = "Oppening connection".to_string();
|
||||
let mut port = serialport::new(port, 115_200)
|
||||
let port = serialport::new(port, 115_200)
|
||||
.timeout(Duration::from_millis(3000))
|
||||
.open()
|
||||
.expect("Failed to open port");
|
||||
.open(); // .expect("Failed to open port");
|
||||
if let Err(e) = port {
|
||||
*scan_message.lock().unwrap() = "Noo".to_string();
|
||||
return Err(TinyError::PortConnection(e));
|
||||
}
|
||||
let mut port = port.unwrap();
|
||||
*scan_message.lock().unwrap() = "Initialisation...".to_string();
|
||||
*progress.lock().unwrap() = 5;
|
||||
initialize(&mut port);
|
||||
|
|
@ -93,9 +97,16 @@ pub(crate) fn scan_with_progress(
|
|||
);
|
||||
|
||||
*progress.lock().unwrap() = 22;
|
||||
scanraw(&mut port, progress.clone(), start, stop, points)?;
|
||||
let name = scanraw(
|
||||
&mut port,
|
||||
progress.clone(),
|
||||
return_data.clone(),
|
||||
start,
|
||||
stop,
|
||||
points,
|
||||
)?;
|
||||
|
||||
*scan_message.lock().unwrap() = "Scan finished".to_string();
|
||||
*scan_message.lock().unwrap() = format!("Scan saved as {}", name);
|
||||
send_cmd(&mut port, "resume\r", SHORT_WAIT);
|
||||
|
||||
wait_sync(LONG_WAIT);
|
||||
|
|
@ -120,15 +131,23 @@ fn wait_sync(duration: u64) {
|
|||
fn scanraw(
|
||||
port: &mut Box<dyn SerialPort>,
|
||||
progress: Arc<Mutex<usize>>,
|
||||
return_data: Arc<Mutex<Vec<(f64, f64)>>>,
|
||||
start: usize,
|
||||
stop: usize,
|
||||
points: usize,
|
||||
) -> Result<(), TinyError> {
|
||||
) -> Result<String, TinyError> {
|
||||
unsafe { send_raw(port, &format!("scanraw {} {} {}\r", start, stop, points)) }
|
||||
wait_sync(SHORT_WAIT);
|
||||
read_scanraw(port, progress, points)?;
|
||||
let (name, val) = read_scanraw(
|
||||
port,
|
||||
progress,
|
||||
points,
|
||||
start,
|
||||
(stop - start) as f64 / points as f64,
|
||||
)?;
|
||||
*return_data.lock().unwrap() = val;
|
||||
wait_sync(LONG_WAIT);
|
||||
Ok(())
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// Send a command and reads it to a string
|
||||
|
|
@ -198,16 +217,25 @@ fn read_scanraw(
|
|||
port: &mut Box<dyn SerialPort>,
|
||||
progress: Arc<Mutex<usize>>,
|
||||
points: usize,
|
||||
) -> Result<(), TinyError> {
|
||||
start: usize,
|
||||
increment: f64,
|
||||
) -> 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)
|
||||
parse_data(v, points, start, increment)
|
||||
}
|
||||
|
||||
/// A utility function used for parsing the raw data of a scan
|
||||
pub fn parse_data(v: Vec<u8>, points: usize) -> Result<(), TinyError> {
|
||||
let mut values: Vec<u16> = Vec::with_capacity(points);
|
||||
let mut out = BufWriter::new(File::create("test.csv")?);
|
||||
pub fn parse_data(
|
||||
v: Vec<u8>,
|
||||
points: usize,
|
||||
start: usize,
|
||||
increment: f64,
|
||||
) -> Result<(String, Vec<(f64, f64)>), TinyError> {
|
||||
// let mut values: Vec<u16> = Vec::with_capacity(points);
|
||||
let name = format!("scan_{}.csv", Local::now().format("%Y%m%d %H_%M_%S"));
|
||||
let mut out = BufWriter::new(File::create(&name)?);
|
||||
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) {
|
||||
|
|
@ -215,15 +243,16 @@ pub fn parse_data(v: Vec<u8>, points: usize) -> Result<(), TinyError> {
|
|||
for (i, slice) in data.chunks_exact(3).enumerate() {
|
||||
let s: &[u8; 3] = &[slice[0], slice[1], slice[2]];
|
||||
let d = DataPoint::unpack(s)?;
|
||||
values.push(d.value);
|
||||
writeln!(
|
||||
out,
|
||||
"{},{}",
|
||||
(i * INCREMENT + START) as f64 / 1000000.,
|
||||
u16_to_f64(d.value) // bytes_to_f64(b1, b2)
|
||||
)?;
|
||||
let (pos, val) = (
|
||||
(i as f64 * increment + start as f64) / 1000000.,
|
||||
u16_to_f64(d.value),
|
||||
);
|
||||
|
||||
csvdata.push((pos, val));
|
||||
writeln!(out, "{},{}", pos, val)?;
|
||||
}
|
||||
Ok(())
|
||||
// TODO: Dont return use mutex
|
||||
Ok((name, csvdata))
|
||||
} else {
|
||||
Err(TinyError::ParseEnd("}".to_owned()))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,15 @@
|
|||
//! All the structs used internally
|
||||
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{Read, Write},
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::ui_struct::AppInfo;
|
||||
|
||||
/// The most common error, exposed to the lib user and end used
|
||||
#[derive(Error, Debug)]
|
||||
pub enum TinyError {
|
||||
|
|
@ -23,10 +31,18 @@ pub enum TinyError {
|
|||
/// A runtime error occured
|
||||
#[error("A runtime error occured :\n{0}")]
|
||||
TUIRuntimeError(color_eyre::eyre::Error),
|
||||
|
||||
/// An error occured while trying to parse the result
|
||||
#[error("An error occured while trying to parse the result")]
|
||||
TUIPackingError(#[from] packed_struct::PackingError),
|
||||
/// The config file couldn't be opened
|
||||
#[error("The config file couldn't be opened")]
|
||||
ConfigNotFound,
|
||||
/// The config file couldn't be parsed as a valid toml
|
||||
#[error("The config config.toml couldn't be read")]
|
||||
InvalidConfig(#[from] toml::de::Error),
|
||||
/// 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),
|
||||
}
|
||||
|
||||
#[allow(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
|
|
@ -52,10 +68,10 @@ pub enum TinyUIError {
|
|||
/// An error occured while proccesing the key events
|
||||
#[error("An error occured while proccesing the key events")]
|
||||
KeyPress(#[from] std::io::Error),
|
||||
|
||||
/// Mutex error likely a data race mishandled
|
||||
#[error("An error occured while trying to fetch progress")]
|
||||
Mutex,
|
||||
// /// Mutex error likely a data race mishandled
|
||||
// #[allow(dead_code)]
|
||||
// #[error("An error occured while trying to fetch progress")]
|
||||
// Mutex,
|
||||
}
|
||||
|
||||
// impl TinyUIError {
|
||||
|
|
@ -63,3 +79,47 @@ pub enum TinyUIError {
|
|||
// Self::UninitializedItemList(list, line!(), file!())
|
||||
// }
|
||||
// }
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub(crate) struct SavedConfig {
|
||||
/// The default com port
|
||||
pub(crate) port: String,
|
||||
/// The default baudrate
|
||||
pub(crate) baudrate: usize,
|
||||
/// The default start frequency
|
||||
pub(crate) start_frequency: usize,
|
||||
/// The default stop frequency
|
||||
pub(crate) stop_frequency: usize,
|
||||
/// The default number of points
|
||||
pub(crate) points: usize,
|
||||
}
|
||||
impl SavedConfig {
|
||||
/// Create a config from file or returns an error
|
||||
pub(crate) fn new() -> Result<Self, TinyError> {
|
||||
if let Ok(mut f) = File::open("config.toml") {
|
||||
let mut s = String::new();
|
||||
f.read_to_string(&mut s)?;
|
||||
let c = toml::from_str(&s)?;
|
||||
Ok(c)
|
||||
} else {
|
||||
Err(TinyError::ConfigNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
/// Save the config with all runtime parameters
|
||||
pub(crate) fn save(arg: &AppInfo) -> Result<(), TinyUIError> {
|
||||
let mut f = File::create("config.toml")?;
|
||||
f.write_all(
|
||||
toml::to_string(&Self {
|
||||
port: arg.port_list.selected_port(),
|
||||
baudrate: arg.baudrate.state.selected().unwrap(),
|
||||
start_frequency: arg.start_frequency.int_to_usize(),
|
||||
stop_frequency: arg.stop_frequency.int_to_usize(),
|
||||
points: arg.points.int_to_usize(),
|
||||
})
|
||||
.unwrap()
|
||||
.as_bytes(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
109
src/ui.rs
109
src/ui.rs
|
|
@ -40,7 +40,7 @@ use tui_textarea::{Input, Key, TextArea};
|
|||
|
||||
use crate::{
|
||||
mleft, mright, scan,
|
||||
structs::{InputDirection, TinyError, TinyUIError},
|
||||
structs::{InputDirection, SavedConfig, TinyError, TinyUIError},
|
||||
ui_struct::{
|
||||
AppInfo, AppState, BaudRateList, MenuItems, PortList, SelectedConfig, SelectedFinalConfig,
|
||||
UIUsize, SELECTED_COLOR, UNSELECTED_COLOR,
|
||||
|
|
@ -50,19 +50,36 @@ use crate::{
|
|||
impl<'a> AppInfo<'a> {
|
||||
/// Create a new app with the port info available
|
||||
pub(crate) fn new(info: Vec<SerialPortInfo>) -> Self {
|
||||
let loaded_conf = SavedConfig::new();
|
||||
let (start_frequency, stop_frequency, points) = {
|
||||
if let Ok(c) = &loaded_conf {
|
||||
(
|
||||
UIUsize::new(c.start_frequency, 10, 960),
|
||||
UIUsize::new(c.stop_frequency, 10, 960),
|
||||
UIUsize::new(c.points, 100, 1000000),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
UIUsize::new(240, 10, 960),
|
||||
UIUsize::new(960, 10, 960),
|
||||
UIUsize::new(10000, 100, 1000000),
|
||||
)
|
||||
}
|
||||
};
|
||||
Self {
|
||||
should_quit: false,
|
||||
baudrate: BaudRateList::default(),
|
||||
port_list: PortList::from_serial(info),
|
||||
baudrate: BaudRateList::from_conf(&loaded_conf),
|
||||
port_list: PortList::from_serial(info, &loaded_conf),
|
||||
flow_state: AppState::default(),
|
||||
status_message: String::new(),
|
||||
menu_items: MenuItems::default(),
|
||||
start_frequency: UIUsize::new(240, 10, 960),
|
||||
stop_frequency: UIUsize::new(960, 10, 960),
|
||||
points: UIUsize::new(10000, 100, 1000000),
|
||||
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())),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -94,7 +111,6 @@ impl<'a> AppInfo<'a> {
|
|||
AppState::FinalConfig(_) => self.draw_final_config(frame),
|
||||
AppState::Finished => self.draw_progress(frame),
|
||||
AppState::EndWindow => self.draw_end_window(frame),
|
||||
// _ => unimplemented!(),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -305,9 +321,9 @@ impl<'a> AppInfo<'a> {
|
|||
Constraint::Min(7),
|
||||
])
|
||||
.areas(frame.area());
|
||||
let [title_area, main_area, graph_area, _, footer_area] = Layout::vertical([
|
||||
let [title_area, _main_area, graph_area, _, footer_area] = Layout::vertical([
|
||||
Constraint::Length(3),
|
||||
Constraint::Length(4),
|
||||
Constraint::Length(1),
|
||||
Constraint::Min(10),
|
||||
Constraint::Length(1),
|
||||
Constraint::Length(1),
|
||||
|
|
@ -373,50 +389,55 @@ impl<'a> AppInfo<'a> {
|
|||
// );
|
||||
// // .hidden_legend_constraints((Constraint::Ratio(1, 2), Constraint::Ratio(1, 2)));
|
||||
|
||||
// TODO: Don't acquire a mutex at 60Hz
|
||||
let binding = self.return_data.lock().unwrap();
|
||||
let datasets = vec![Dataset::default()
|
||||
.name("Heavy")
|
||||
// .name("Heavy")
|
||||
.marker(Marker::Dot)
|
||||
.graph_type(GraphType::Scatter)
|
||||
.style(Style::new().yellow())
|
||||
.data(&[
|
||||
(1965., -82.),
|
||||
(1967., -54.),
|
||||
(1981., -65.),
|
||||
(1989., -30.),
|
||||
(1997., -10.),
|
||||
(2004., -11.),
|
||||
(2014., -45.),
|
||||
(2016., -79.),
|
||||
(2018., -15.),
|
||||
])];
|
||||
.data(&binding)];
|
||||
|
||||
let chart = Chart::new(datasets)
|
||||
.block(
|
||||
Block::bordered().title(
|
||||
Title::default()
|
||||
.content("Scatter chart".cyan().bold())
|
||||
.alignment(Alignment::Center),
|
||||
),
|
||||
)
|
||||
// .block(
|
||||
// Block::bordered().title(
|
||||
// Title::default()
|
||||
// .content("Scatter chart".cyan().bold())
|
||||
// .alignment(Alignment::Center),
|
||||
// ),
|
||||
// )
|
||||
.x_axis(
|
||||
Axis::default()
|
||||
.title("Year")
|
||||
.bounds([1960., 2020.])
|
||||
// .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(["1960", "1990", "2020"]),
|
||||
.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")
|
||||
// .title("Cost")
|
||||
.bounds([-128., 0.])
|
||||
.style(Style::default().fg(Color::Gray))
|
||||
.labels(["0", "37 500", "75 000"]),
|
||||
)
|
||||
.hidden_legend_constraints((Constraint::Ratio(1, 2), Constraint::Ratio(1, 2)));
|
||||
.labels(["-128dbm", "-64dbm", "0dbm"]),
|
||||
);
|
||||
frame.render_widget(chart, graph_area);
|
||||
let footer =
|
||||
Paragraph::new("Press ↲ to save the data as a csv or q to exit without saving.")
|
||||
.centered();
|
||||
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(())
|
||||
|
|
@ -500,18 +521,24 @@ 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 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();
|
||||
// BYPASS
|
||||
*self.progress.lock().unwrap() = 100;
|
||||
// thread::spawn(move || {
|
||||
// scan::scan_with_progress(pmtx, mmtx, cmtx, port, start, stop, points).unwrap()
|
||||
// });
|
||||
self.save_config()?;
|
||||
thread::spawn(move || {
|
||||
let status = scan::scan_with_progress(
|
||||
pmtx, mmtx, cmtx, rdata, port, start, stop, points,
|
||||
);
|
||||
// TODO: Do something with bad status to avoid false positive
|
||||
});
|
||||
// scan::scan_with_progress(pmtx, mmtx, cmtx, port).unwrap();
|
||||
}
|
||||
AppState::EndWindow => {
|
||||
|
|
|
|||
106
src/ui_struct.rs
106
src/ui_struct.rs
|
|
@ -1,56 +1,22 @@
|
|||
//! All ui structures and utility functions
|
||||
|
||||
//! The (minimal) user interface to control the program
|
||||
#![allow(unused_imports)]
|
||||
use clap::builder::Resettable;
|
||||
use color_eyre::{owo_colors::OwoColorize, Result};
|
||||
use color_eyre::Result;
|
||||
use ratatui::{
|
||||
buffer::Buffer,
|
||||
crossterm::{
|
||||
event::{self, Event, KeyCode, KeyEvent, KeyEventKind},
|
||||
style::Print,
|
||||
},
|
||||
layout::{Constraint, Direction, Layout, Rect},
|
||||
prelude::BlockExt,
|
||||
style::{
|
||||
palette::tailwind::{BLUE, GREEN, SLATE},
|
||||
Color, Modifier, Style, Styled, Stylize,
|
||||
},
|
||||
symbols,
|
||||
text::Line,
|
||||
widgets::{
|
||||
Block, Borders, Chart, HighlightSpacing, LineGauge, List, ListDirection, ListItem,
|
||||
ListState, Padding, Paragraph, ScrollDirection, StatefulWidget, Widget, Wrap,
|
||||
},
|
||||
DefaultTerminal, Frame,
|
||||
style::{Color, Style},
|
||||
widgets::{Block, LineGauge, List, ListState, Paragraph},
|
||||
};
|
||||
use serialport::SerialPortInfo;
|
||||
use std::{
|
||||
borrow::{Borrow, BorrowMut},
|
||||
cmp::min,
|
||||
fmt::Pointer,
|
||||
iter::Iterator,
|
||||
ops::Add,
|
||||
str::FromStr,
|
||||
sync::{Arc, Mutex},
|
||||
time::Instant,
|
||||
};
|
||||
use strum::{EnumCount, EnumIter, EnumProperty};
|
||||
use strum::{EnumCount, EnumIter};
|
||||
use strum::{FromRepr, IntoEnumIterator};
|
||||
use tui_textarea::{Input, Key, TextArea};
|
||||
|
||||
use crate::structs::{InputDirection, TinyUIError};
|
||||
use crate::structs::{InputDirection, SavedConfig, TinyError, TinyUIError};
|
||||
|
||||
/// The header style
|
||||
const HEADER_STYLE: Style = Style::new().fg(SLATE.c100).bg(BLUE.c800);
|
||||
/// The background color
|
||||
const NORMAL_ROW_BG: Color = SLATE.c950;
|
||||
/// Background color for alternated rows
|
||||
const ALT_ROW_BG_COLOR: Color = SLATE.c900;
|
||||
/// The style applied to the currently selected item
|
||||
const SELECTED_STYLE: Style = Style::new().bg(SLATE.c800).add_modifier(Modifier::BOLD);
|
||||
/// Foreground color
|
||||
const TEXT_FG_COLOR: Color = SLATE.c200;
|
||||
/// Color of a selected border
|
||||
pub(crate) const SELECTED_COLOR: Color = Color::White;
|
||||
/// Color of an unselected item
|
||||
|
|
@ -83,6 +49,8 @@ pub(crate) struct AppInfo<'a> {
|
|||
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)>>>,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct UIUsize {
|
||||
|
|
@ -211,8 +179,8 @@ impl Default for SelectedFinalConfig {
|
|||
/// The list of all baudrates selectables
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct BaudRateList {
|
||||
/// The selected baudrate (default : BAUD1115200)
|
||||
pub(crate) selected: usize,
|
||||
// /// The selected baudrate (default : BAUD1115200)
|
||||
// pub(crate) selected: usize,
|
||||
/// The baudrate list
|
||||
pub(crate) baudrates: Vec<BaudRate>,
|
||||
/// The inner state of the widget
|
||||
|
|
@ -235,12 +203,27 @@ impl BaudRateList {
|
|||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a baudrate from a config file
|
||||
pub(crate) fn from_conf(loaded_conf: &Result<SavedConfig, TinyError>) -> 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 {
|
||||
return Self {
|
||||
state: ListState::default().with_selected(Some(i)),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for BaudRateList {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
selected: 0,
|
||||
baudrates: BaudRate::iter().collect::<Vec<_>>(),
|
||||
state: ListState::default().with_selected(Some(3)),
|
||||
}
|
||||
|
|
@ -267,20 +250,23 @@ pub(crate) enum BaudRate {
|
|||
pub(crate) struct PortList {
|
||||
/// The list of found ports
|
||||
pub(crate) ports: Vec<String>,
|
||||
/// The currently selected port (doing it that way completly avoids the )
|
||||
pub(crate) selected: usize,
|
||||
// /// The currently selected port (doing it that way completly avoids the )
|
||||
// pub(crate) selected: usize,
|
||||
/// The inner state of the widget
|
||||
pub(crate) state: ListState,
|
||||
}
|
||||
|
||||
impl PortList {
|
||||
/// Make a port list from a serial reading
|
||||
pub(crate) fn from_serial(info: Vec<SerialPortInfo>) -> Self {
|
||||
pub(crate) fn from_serial(
|
||||
info: Vec<SerialPortInfo>,
|
||||
saved_config: &Result<SavedConfig, TinyError>,
|
||||
) -> Self {
|
||||
let ports: Vec<String> = info.into_iter().map(|port| port.port_name).collect();
|
||||
let selected = find_best_port(&ports);
|
||||
let selected = find_best_port(&ports, saved_config);
|
||||
Self {
|
||||
ports,
|
||||
selected,
|
||||
// selected,
|
||||
state: ListState::default().with_selected(Some(selected)),
|
||||
}
|
||||
}
|
||||
|
|
@ -316,17 +302,24 @@ pub(crate) struct MenuItems<'a> {
|
|||
pub(crate) textboxes: Vec<Paragraph<'a>>,
|
||||
/// The progress bar
|
||||
pub(crate) progress_bar: Option<LineGauge<'a>>,
|
||||
/// Controller info
|
||||
pub(crate) info: Option<Chart<'a>>,
|
||||
/// The final graph
|
||||
pub(crate) graph: Option<Chart<'a>>,
|
||||
// /// Controller info
|
||||
// pub(crate) info: Option<Chart<'a>>,
|
||||
// /// The final graph
|
||||
// pub(crate) graph: Option<Chart<'a>>,
|
||||
}
|
||||
|
||||
/// Try to guess the best port to preselect
|
||||
fn find_best_port(ports: &[String]) -> usize {
|
||||
fn find_best_port(ports: &[String], saved_config: &Result<SavedConfig, TinyError>) -> usize {
|
||||
// TODO: Try to load from disk then save to disk
|
||||
let best_ports = ["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"];
|
||||
for port in best_ports {
|
||||
let mut best_ports = vec!["/dev/ttyACM0", "COM3", "COM5", "/dev/ttyS16"];
|
||||
let p: Vec<&str> = if let Ok(c) = saved_config {
|
||||
let mut v = vec![&*c.port];
|
||||
v.append(&mut best_ports);
|
||||
v
|
||||
} else {
|
||||
best_ports
|
||||
};
|
||||
for port in p {
|
||||
if let Some(p) = ports.iter().position(|v| v == port) {
|
||||
return p;
|
||||
}
|
||||
|
|
@ -347,6 +340,11 @@ impl<'a> AppInfo<'a> {
|
|||
.style(Style::default().fg(color)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Save the config with the current runtime variables
|
||||
pub(crate) fn save_config(&self) -> Result<(), TinyUIError> {
|
||||
SavedConfig::save(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> AppInfo<'a> {
|
||||
|
|
|
|||
Loading…
Reference in New Issue