Finished most of the gui

This commit is contained in:
Dandaedre 2024-09-24 04:20:28 +02:00
parent 90676d7c5d
commit c88ef356b1
4 changed files with 210 additions and 186 deletions

View File

@ -24,8 +24,8 @@ use serialport::SerialPort;
use std::{
fs::File,
io::{BufWriter, Read, Write},
sync::OnceLock,
thread::sleep,
sync::{Arc, Mutex, OnceLock},
thread::{self},
time::Duration,
};
@ -44,61 +44,64 @@ pub struct DataPoint {
static EOF: OnceLock<memmem::Finder<'_>> = OnceLock::new();
/// Scan a specific range and returns the scan result
pub(crate) fn scan() -> Result<(), TinyError> {
let ports = serialport::available_ports()?;
for p in ports {
println!("{}", p.port_name);
}
let mut port = serialport::new("/dev/ttyACM0", 115_200)
pub(crate) fn scan_with_progress(
progress: Arc<Mutex<f64>>,
scan_info: Arc<Mutex<String>>,
scan_message: Arc<Mutex<String>>,
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)
.timeout(Duration::from_millis(3000))
.open()
.expect("Failed to open port");
*scan_message.lock().unwrap() = "Initialisation...".to_string();
*progress.lock().unwrap() = 5.;
initialize(&mut port);
println!("{}", send_cmd(&mut port, "help\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "version\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "info\r", SHORT_WAIT));
println!(
"{}",
send_cmd(&mut port, &format!("zero {}\r", OFFSET), SHORT_WAIT)
);
println!("{}", send_cmd(&mut port, "leveloffset\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "deviceid\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "vbat offset\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "vbat\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "usart_cfg\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "marker\r", SHORT_WAIT));
*progress.lock().unwrap() = 15.;
*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);
*scan_info.lock().unwrap() = format!("{}{}", v, i);
println!("{}", send_cmd(&mut port, "sweep\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "mode\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "lna\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);
// ("{}", send_cmd(&mut port, "leveloffset\r", SHORT_WAIT));
// ("{}", send_cmd(&mut port, "deviceid\r", SHORT_WAIT));
// ("{}", send_cmd(&mut port, "usart_cfg\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "pause\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "vbat\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "marker\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "sweep\r", SHORT_WAIT));
println!("{}", send_cmd(&mut port, "mode high input\r", SHORT_WAIT));
*progress.lock().unwrap() = 17.;
*scan_message.lock().unwrap() = "Setting up scan & mode".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);
println!("{}", send_cmd(&mut port, "sweep\r", SHORT_WAIT));
println!(
"{}",
send_cmd(&mut port, &format!("sweep start {}\r", START), SHORT_WAIT)
*progress.lock().unwrap() = 18.;
*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);
*progress.lock().unwrap() = 20.;
*scan_message.lock().unwrap() = "Starting scan...".to_string();
send_cmd(&mut port, "sweep\r", SHORT_WAIT);
send_cmd(
&mut port,
&format!("scan {} {} 290 101\r", start, stop),
TIMEOUT,
);
println!(
"{}",
send_cmd(&mut port, &format!("sweep stop {}\r", STOP), SHORT_WAIT)
);
println!("{}", send_cmd(&mut port, "sweep\r", SHORT_WAIT));
println!(
"{}",
send_cmd(&mut port, "scan 240000000 959000000 290 101\r", TIMEOUT)
);
// println!(
// "{}",
// send_cmd(&mut port, &format!("scan {} {} 100 101\r", START, STOP), 50)
// );
println!("{:?}", scanraw(&mut port));
println!("{}", send_cmd(&mut port, "resume\r", SHORT_WAIT));
*progress.lock().unwrap() = 22.;
scanraw(&mut port, progress.clone(), start, stop, points)?;
*scan_message.lock().unwrap() = "Scan finished".to_string();
send_cmd(&mut port, "resume\r", SHORT_WAIT);
*progress.lock().unwrap() = 100.;
wait_sync(LONG_WAIT);
Ok(())
}
@ -107,30 +110,26 @@ pub(crate) fn scan() -> Result<(), TinyError> {
/// 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);
println!(
"Initializing ... \nUninialized bytes: {:?}",
read_port(port)
);
read_port(port);
wait_sync(SHORT_WAIT)
}
/// Bad synchronisation method to ensure data is truthfully sent/received
fn wait_sync(duration: u64) {
sleep(Duration::from_millis(duration));
thread::sleep(Duration::from_millis(duration));
}
/// Scan raw frequencies
fn scanraw(port: &mut Box<dyn SerialPort>) -> Result<(), TinyError> {
// let mut f = File::open("b.txt")?;
// let mut s = String::new();
// let d = f.read_to_string(&mut s)?;
// println!("{}", s);
// let v = hex::decode(&s[..s.len() - 1]).?();
// println!("{:?}", v);
// parse_data(v)?;
unsafe { send_raw(port, &format!("scanraw {} {} {}\r", START, STOP, POINTS)) }
fn scanraw(
port: &mut Box<dyn SerialPort>,
progress: Arc<Mutex<f64>>,
start: usize,
stop: usize,
points: usize,
) -> Result<(), TinyError> {
unsafe { send_raw(port, &format!("scanraw {} {} {}\r", start, stop, points)) }
wait_sync(SHORT_WAIT);
read_scanraw(port)?;
read_scanraw(port, progress, points)?;
wait_sync(LONG_WAIT);
Ok(())
}
@ -148,7 +147,6 @@ fn send_cmd(port: &mut Box<dyn SerialPort>, command: &str, wait: u64) -> String
/// This command will produce unknown results if the output buffer is never read
unsafe fn send_raw(port: &mut Box<dyn SerialPort>, command: &str) {
let output = command.as_bytes();
println!("Sending: {}", command);
let _r = port.write(output).expect("Write failed!");
}
@ -164,13 +162,11 @@ fn read_port(port: &mut Box<dyn SerialPort>) -> Vec<u8> {
let finder = EOF.get_or_init(|| memmem::Finder::new("ch>"));
while let Ok(r) = port.read(serial_buf.as_mut_slice()) {
if let Some(pos) = finder.find(&serial_buf) {
// println!("{:?}", serial_buf);
res.extend_from_slice(&serial_buf[..pos]);
break;
}
res.extend_from_slice(&serial_buf[..r]);
}
// println!("{:?}", res);
res
}
@ -178,15 +174,19 @@ fn read_port(port: &mut Box<dyn SerialPort>) -> Vec<u8> {
/// Waits the normal start Character '{' and begins treating data as normal
///
/// Returns a struct summerizing the information processed
fn read_scanraw(port: &mut Box<dyn SerialPort>) -> Result<(), TinyError> {
fn read_scanraw(
port: &mut Box<dyn SerialPort>,
progress: Arc<Mutex<f64>>,
points: usize,
) -> Result<(), TinyError> {
let v = read_port(port);
// Find the { marking the beggining
parse_data(v)
parse_data(v, progress, points)
}
/// A utility function used for parsing the raw data of a scan
pub fn parse_data(v: Vec<u8>) -> Result<(), TinyError> {
let mut values: Vec<u16> = Vec::with_capacity(POINTS);
pub fn parse_data(v: Vec<u8>, progress: Arc<Mutex<f64>>, points: usize) -> Result<(), TinyError> {
let mut values: Vec<u16> = Vec::with_capacity(points);
let mut out = BufWriter::new(File::create("test.csv")?);
if let Some(begining) = memchr::memchr(b'{', &v) {
// Finds the } marking the end
@ -195,14 +195,6 @@ pub fn parse_data(v: Vec<u8>) -> 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)?;
// println!(
// "{} {} {} -> {} : {}",
// x,
// b1,
// b2,
// d.value,
// u16_to_f64(d.value)
// );
values.push(d.value);
writeln!(
out,
@ -211,12 +203,6 @@ pub fn parse_data(v: Vec<u8>) -> Result<(), TinyError> {
u16_to_f64(d.value) // bytes_to_f64(b1, b2)
)?;
}
println!(
"Found {} values, min: {:?}, max: {:?}",
values.len(),
u16_to_f64(*values.iter().min().unwrap_or(&0)),
u16_to_f64(*values.iter().max().unwrap_or(&0)),
);
Ok(())
} else {
Err(TinyError::ParseEnd("}".to_owned()))
@ -239,25 +225,3 @@ fn u16_to_f64(v: u16) -> f64 {
// status: ScanStatus,
// data: Vec<f64>,
// }
// pub enum ScanStatus {
// Success,
// Failure,
// Interrupted,
// }
// loop {
// // println!("{}", send_cmd(&mut port, "0\r"));
// print!("ch> ");
// io::stdout().flush().expect("IO error");
// let mut input = String::new();
// match io::stdin().read_line(&mut input) {
// Ok(_) => {
// println!("{}", send_cmd(&mut port, &format!("{}\r", input)));
// }
// Err(e) => println!("Error {}", e),
// }
// // println!("{}", send_cmd(&mut port, "scan 240m 960m 240 11\r"));
// // println!("{}", send_cmd(&mut port, "scanraw 240m 960m 10000\r"));
// // // println!("{}", send_cmd(&mut port, "scanraw 240m 960m 1000\r"));
// // send_cmd(&mut port, "resume\r");
// }

View File

@ -1,4 +1,5 @@
//! All the structs used internally
use thiserror::Error;
/// The most common error, exposed to the lib user and end used
@ -51,6 +52,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,
}
// impl TinyUIError {

133
src/ui.rs
View File

@ -1,7 +1,8 @@
//! The (minimal) user interface to control the program
#![allow(unused_imports)]
use clap::builder::Resettable;
use color_eyre::owo_colors::OwoColorize;
use color_eyre::{owo_colors::OwoColorize, Section};
use core::time;
use ratatui::{
buffer::Buffer,
crossterm::{
@ -29,14 +30,15 @@ use std::{
fmt::Pointer,
iter::Iterator,
sync::{Arc, Mutex},
time::Instant,
thread,
time::{Duration, Instant},
};
use strum::{EnumCount, EnumIter, EnumProperty};
use strum::{FromRepr, IntoEnumIterator};
use tui_textarea::{Input, Key, TextArea};
use crate::{
mleft, mright,
mleft, mright, scan,
structs::{InputDirection, TinyError, TinyUIError},
ui_struct::{
AppInfo, AppState, BaudRateList, MenuItems, PortList, SelectedConfig, SelectedFinalConfig,
@ -57,7 +59,9 @@ impl<'a> AppInfo<'a> {
start_frequency: UIUsize::new(240, 10, 960),
stop_frequency: UIUsize::new(960, 10, 960),
points: UIUsize::new(10000, 100, 1000000),
progress: Arc::new(Mutex::new(0)),
progress: Arc::new(Mutex::new(0.)),
scan_info: Arc::new(Mutex::new(String::new())),
scan_message: Arc::new(Mutex::new(String::new())),
}
}
@ -69,11 +73,14 @@ impl<'a> AppInfo<'a> {
self.init_config()?;
loop {
terminal.draw(|v| self.draw(v).inspect_err(|e| panic!("{}", e)).unwrap())?;
if let Event::Key(key) = event::read()? {
self.handle_start_keys(key)?;
};
if self.should_quit {
break;
let timeout = Duration::from_millis(16);
if event::poll(timeout)? {
if let Event::Key(key) = event::read()? {
self.handle_start_keys(key)?;
};
if self.should_quit {
break;
}
}
}
Ok(())
@ -117,21 +124,7 @@ impl<'a> AppInfo<'a> {
/// Initialisation of all the ui element for the final configuration elements
fn init_final_config(&mut self) -> Result<(), TinyUIError> {
// /// Create a textbox with a custom title
// macro_rules! text_with_title {
// ($name:expr) => {{
// let mut texta = TextArea::default();
// let block = Block::default().title($name);
// texta.set_block(block);
// texta
// }};
// }
self.menu_items.textboxes = vec![
// text_with_title!("Start Frequency"),
TextArea::default(),
TextArea::default(),
TextArea::default(),
];
self.menu_items.textboxes = vec![Paragraph::new("")];
self.update_color()
}
@ -152,6 +145,7 @@ impl<'a> AppInfo<'a> {
Constraint::Min(7),
])
.areas(main_area);
// TODO: Move this in the color update
let (mif_color, maf_color, poi_color) = match self.flow_state {
AppState::FinalConfig(SelectedFinalConfig::StartFreq) => {
(SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR)
@ -185,6 +179,7 @@ impl<'a> AppInfo<'a> {
area_points,
);
self.update_color()?;
frame.render_widget(Paragraph::new(self.status_message.clone()), title_area);
self.render_footer(frame, status_area);
Ok(())
@ -205,38 +200,67 @@ impl<'a> AppInfo<'a> {
self.menu_items.progress_bar = Some(
LineGauge::default()
// .block(title)
.filled_style(Style::default().fg(Color::Blue).bg(Color::Blue))
.unfilled_style(Style::default().fg(Color::Red).bg(Color::Red))
.label("Background:"),
.filled_style(Style::default().fg(Color::Blue))
.unfilled_style(Style::default().fg(Color::Red))
// .filled_style(Style::default().fg(Color::Blue).bg(Color::Blue))
// .unfilled_style(Style::default().fg(Color::Red).bg(Color::Red))
.label("Progress:"),
);
Ok(())
}
/// Draw the progress, updates as the progress is being done
fn draw_progress(&self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> {
fn draw_progress(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> {
// let title = title_block("Blue / red only background");
let [title_area, main_area, status_area] = Layout::vertical([
Constraint::Length(2),
Constraint::Min(10),
Constraint::Length(1),
let [_, main_s, _] = Layout::horizontal([
Constraint::Min(7),
Constraint::Percentage(90),
Constraint::Min(7),
])
.areas(frame.area());
let [_, area_ports, area_baud, _] = Layout::horizontal([
Constraint::Min(7),
Constraint::Percentage(50),
Constraint::Percentage(50),
Constraint::Min(7),
let [title_area, _, main_area, _, progress_area] = Layout::vertical([
Constraint::Length(3),
// Constraint::Length(1),
Constraint::Length(1),
// Constraint::Length(1),
Constraint::Min(10),
Constraint::Length(1),
Constraint::Length(1),
])
.areas(main_area);
// frame.render_widget(
// Paragraph::new(self.points.int_to_string())
// .block(Block::bordered())
// .style(poi_color),
// area_points,
// );
.areas(main_s);
let (pb, status, message) = {
let status = self.scan_message.try_lock().unwrap();
let status = Paragraph::new(status.clone())
.block(Block::bordered().title("Operation"))
.style(SELECTED_COLOR);
let message = self.scan_info.try_lock().unwrap();
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
.take()
.ok_or(TinyUIError::UninitializedItemList(
"ProgressBar",
line!(),
file!(),
))?
.ratio(*progress / 100.);
(pb, status, message)
};
// let self= pb.clone
frame.render_widget(pb.clone(), progress_area);
frame.render_widget(status, title_area);
frame.render_widget(message, main_area);
// frame.render_widget(Paragraph::new(format!("{:?}", Instant::now())), main_area);
// thread::sleep(Duration::from_millis(100));
self.menu_items.progress_bar = Some(pb);
// TODO: If progress = 100 move to final step and show S / enter to save G for graph
Ok(())
// .ratio(self.progress);
// .render(area, buf);
}
/// Draw the config info
@ -358,7 +382,22 @@ impl<'a> AppInfo<'a> {
self.flow_state = AppState::FinalConfig(SelectedFinalConfig::default());
self.init_final_config()?;
}
AppState::FinalConfig(_) => self.flow_state = AppState::Finished,
AppState::FinalConfig(_) => {
self.flow_state = AppState::Finished;
self.init_progress()?;
// Start the scan
let pmtx = self.progress.clone();
let mmtx = self.scan_info.clone();
let cmtx = self.scan_message.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();
thread::spawn(move || {
scan::scan_with_progress(pmtx, mmtx, cmtx, port, start, stop, points).unwrap()
});
// scan::scan_with_progress(pmtx, mmtx, cmtx, port).unwrap();
}
AppState::Popup => todo!(),
AppState::Finished => todo!(),
}

View File

@ -31,6 +31,7 @@ use std::{
fmt::Pointer,
iter::Iterator,
ops::Add,
str::FromStr,
sync::{Arc, Mutex},
time::Instant,
};
@ -77,9 +78,12 @@ pub(crate) struct AppInfo<'a> {
/// The number of points
pub(crate) points: UIUsize,
/// Global progress
pub(crate) progress: Arc<Mutex<usize>>,
pub(crate) progress: Arc<Mutex<f64>>,
/// Global initialisation data
pub(crate) scan_info: Arc<Mutex<String>>,
/// Global message
pub(crate) scan_message: Arc<Mutex<String>>,
}
#[derive(Debug)]
pub(crate) struct UIUsize {
/// Current value held by the usize
@ -115,8 +119,13 @@ impl UIUsize {
}
/// Convert to mhz multiplying it by 1_000_000
pub(crate) fn mhz_to_string(&self) -> String {
format!("{}", self.value * 1000000)
pub(crate) fn mhz_to_usize(&self) -> usize {
self.value * 1000000
}
/// Output inner value
pub(crate) fn int_to_usize(&self) -> usize {
self.value
}
}
@ -289,6 +298,11 @@ impl PortList {
_ => (),
}
}
/// Returns the final selected port
pub(crate) fn selected_port(&self) -> String {
self.ports[self.state.selected().unwrap()].clone()
}
}
#[derive(Debug, Default)]
@ -299,7 +313,7 @@ pub(crate) struct MenuItems<'a> {
/// List of port items
pub(crate) baudlist: Option<List<'a>>,
/// List of all the textboxes
pub(crate) textboxes: Vec<TextArea<'a>>,
pub(crate) textboxes: Vec<Paragraph<'a>>,
/// The progress bar
pub(crate) progress_bar: Option<LineGauge<'a>>,
/// Controller info
@ -318,14 +332,7 @@ fn find_best_port(ports: &[String]) -> usize {
}
0
}
// #[allow(clippy::missing_docs_in_private_items)]
// const fn alternate_colors(i: usize) -> Color {
// if i % 2 == 0 {
// NORMAL_ROW_BG
// } else {
// ALT_ROW_BG_COLOR
// }
// }
impl<'a> AppInfo<'a> {
/// Put an item a specified color
pub(crate) fn change_color(
@ -363,27 +370,26 @@ impl<'a> AppInfo<'a> {
self.menu_items.baudlist = self.change_color("Baudrate", b, b_c);
}
AppState::FinalConfig(ref c) => {
// let (mif_color, maf_color, poi_color) = match self.flow_state {
let colorlist = match c {
SelectedFinalConfig::StartFreq => {
[SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR]
}
SelectedFinalConfig::FinalFreq => {
[UNSELECTED_COLOR, SELECTED_COLOR, UNSELECTED_COLOR]
}
SelectedFinalConfig::Points => {
[UNSELECTED_COLOR, UNSELECTED_COLOR, SELECTED_COLOR]
}
};
// self.status_message = format!("Moo");
// let colorlist = match c {
// SelectedFinalConfig::StartFreq => {
// [SELECTED_COLOR, UNSELECTED_COLOR, UNSELECTED_COLOR]
// }
// SelectedFinalConfig::FinalFreq => {
// [UNSELECTED_COLOR, SELECTED_COLOR, UNSELECTED_COLOR]
// }
// SelectedFinalConfig::Points => {
// [UNSELECTED_COLOR, UNSELECTED_COLOR, SELECTED_COLOR]
// }
// };
for (area, color) in self.menu_items.textboxes.iter_mut().zip(colorlist) {
area.set_block(
Block::default()
.borders(Borders::ALL)
.style(Style::default().fg(color))
.title(" Inactive (^X to switch) "),
)
}
// for (area, color) in self.menu_items.textboxes.iter_mut().zip(colorlist) {
// .block(
// Block::default()
// // .borders(Borders::ALL)
// .style(Style::default().fg(Color::Blue)), // .title(" Inactive (^X to switch) "),
// )
// }
}
AppState::Popup => todo!(),
AppState::Finished => todo!(),
@ -391,3 +397,13 @@ impl<'a> AppInfo<'a> {
Ok(())
}
}
// /// Create a textbox with a custom title
// macro_rules! text_with_title {
// ($name:expr) => {{
// let mut texta = TextArea::default();
// let block = Block::default().title($name);
// texta.set_block(block);
// texta
// }};
// }