diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..128f924 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[build] +rustflags = ["-Clink-arg=-fuse-ld=lld"] diff --git a/.gitignore b/.gitignore index 3c68812..365d39a 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ Cargo.lock /target *.csv +config.toml diff --git a/Cargo.toml b/Cargo.toml index c14dee0..510afda 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,12 +4,39 @@ version = "0.1.0" edition = "2021" [dependencies] -byteorder = "1.5.0" +chrono = "0.4.38" +# byteorder = "1.5.0" clap = { version = "4.5.17", features = ["derive"] } -csv = "1.3.0" -hex = "0.4.3" +color-eyre = "0.6.3" +human-panic = "2.0.1" +# csv = "1.3.0" 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] +opt-level = "z" +strip = true +lto = true +codegen-units = 1 +panic = "abort" + +[profile.dev] +debug = 0 + +[profile.windows] +inherits = "release" +opt-level = "z" +debug = false +strip = true +lto = true +codegen-units = 1 +incremental = false +panic = "abort" diff --git a/README.md b/README.md index 7f5a58b..b3684b7 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,28 @@ Simple tinySA to Workbench converter +# First window +> Selection + +Starts with the most likely com port selected (last used, then usual suspect, then port 0) +Enter selects it (in the validation sense) +Selects the first likely baudrate (same algo) +Enter selects it +Selects the validate text box + +First selection should be enter, then with L/R U/D (or mouse?) you can change the params +(P) to select a port (B) to select a baudrate (Enter) to be put on the selection + +# Second window +> Customisation + +Tab/L/R for navigation, Enter to change a parameter +Starts with selected and either (L/R/U/D) to be put on the fields + +# Third window +> Result + +Show a progress bar, then show a nice message with a prompt to ask where to save, then exits # References diff --git a/src/main.rs b/src/main.rs index 43db167..7a4603d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,14 +4,25 @@ //! and will not offer any scripting capabilities #![warn(missing_docs, clippy::missing_docs_in_private_items)] +// #![allow(dead_code)] mod scan; mod structs; +mod ui; +mod ui_struct; -use crate::scan::scan; - +use color_eyre::Result; +// use human_panic::setup_panic; use structs::TinyError; +use ui_struct::AppInfo; fn main() -> Result<(), TinyError> { - // let args = Args::parse(); - scan() + color_eyre::install()?; + let terminal = ratatui::init(); + // setup_panic!(); + let ports = serialport::available_ports()?; + let app_r = AppInfo::new(ports).run(terminal); + + ratatui::restore(); + + app_r.map_err(TinyError::TUIRuntimeError) } diff --git a/src/scan.rs b/src/scan.rs index a6842d0..1e02dc1 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -1,13 +1,9 @@ //! The "lib" used for all scan related functions /// The default start value for a scan -static START: usize = 240000000; +static START: usize = 240_000_000; /// The default stop value for a scan -static STOP: usize = 959000000; -/// 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 +static STOP: usize = 959_000_000; /// The offset used for sending data static OFFSET: usize = 128; /// The base delay used inbetween commands @@ -24,11 +20,13 @@ use serialport::SerialPort; use std::{ fs::File, io::{BufWriter, Read, Write}, - sync::OnceLock, - thread::sleep, + sync::{Arc, Mutex, OnceLock}, + thread::{self}, 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,62 +42,75 @@ pub struct DataPoint { static EOF: OnceLock> = 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) +#[allow(clippy::too_many_arguments)] +pub(crate) fn scan_with_progress( + progress: Arc>, + scan_info: Arc>, + scan_message: Arc>, + return_data: Arc>>, + port: String, + start: usize, + stop: usize, + points: usize, +) -> Result<(), TinyError> { + *scan_message.lock().unwrap() = "Oppening connection".to_string(); + let port = serialport::new(port, 115_200) .timeout(Duration::from_millis(3000)) - .open() - .expect("Failed to open port"); + .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); - 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); - 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; + let name = scanraw( + &mut port, + progress.clone(), + return_data.clone(), + start, + stop, + points, + )?; + + *scan_message.lock().unwrap() = format!("Scan saved as {}", name); + send_cmd(&mut port, "resume\r", SHORT_WAIT); + wait_sync(LONG_WAIT); + *progress.lock().unwrap() = 100; Ok(()) } @@ -107,32 +118,36 @@ 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) { 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) -> 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]).unwrap(); - // println!("{:?}", v); - // parse_data(v).unwrap(); - unsafe { send_raw(port, &format!("scanraw {} {} {}\r", START, STOP, POINTS)) } +fn scanraw( + port: &mut Box, + progress: Arc>, + return_data: Arc>>, + start: usize, + stop: usize, + points: usize, +) -> Result { + unsafe { send_raw(port, &format!("scanraw {} {} {}\r", start, stop, points)) } wait_sync(SHORT_WAIT); - read_scanraw(port)?; + 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 @@ -148,7 +163,6 @@ fn send_cmd(port: &mut Box, 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, command: &str) { let output = command.as_bytes(); - println!("Sending: {}", command); let _r = port.write(output).expect("Write failed!"); } @@ -158,19 +172,40 @@ fn read_utf8(port: &mut Box) -> String { } /// Reads the serial port until it reaches EOF +fn read_port_with_progress( + port: &mut Box, + expected: usize, + progress: Arc>, +) -> Vec { + let mut serial_buf: Vec = vec![0; 64]; + 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()) { + *progress.lock().unwrap() = (100usize.saturating_sub( + (80 * (expected.saturating_sub(res.len())).clamp(0, expected)) / expected, + )) + .clamp(20, 99); + if let Some(pos) = finder.find(&serial_buf) { + res.extend_from_slice(&serial_buf[..pos]); + break; + } + res.extend_from_slice(&serial_buf[..r]); + } + res +} + +/// Read port without updating progress fn read_port(port: &mut Box) -> Vec { let mut serial_buf: Vec = vec![0; 256]; 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()) { 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,46 +213,46 @@ fn read_port(port: &mut Box) -> Vec { /// Waits the normal start Character '{' and begins treating data as normal /// /// Returns a struct summerizing the information processed -fn read_scanraw(port: &mut Box) -> Result<(), TinyError> { - let v = read_port(port); +fn read_scanraw( + port: &mut Box, + progress: Arc>, + points: usize, + 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) + parse_data(v, points, start, increment) } /// A utility function used for parsing the raw data of a scan -pub fn parse_data(v: Vec) -> Result<(), TinyError> { - let mut values: Vec = Vec::with_capacity(POINTS); - let mut out = BufWriter::new(File::create("test.csv")?); +pub fn parse_data( + v: Vec, + points: usize, + start: usize, + increment: f64, +) -> Result<(String, Vec<(f64, f64)>), TinyError> { + // let mut values: Vec = 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) { 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).unwrap(); - // println!( - // "{} {} {} -> {} : {}", - // x, - // b1, - // b2, - // d.value, - // u16_to_f64(d.value) - // ); - values.push(d.value); - writeln!( - out, - "{},{}", - (i * INCREMENT + START) as f64 / 1000000., - u16_to_f64(d.value) // bytes_to_f64(b1, b2) - )?; + let d = DataPoint::unpack(s)?; + let (pos, val) = ( + (i as f64 * increment + start as f64) / 1000000., + u16_to_f64(d.value), + ); + + csvdata.push((pos, val)); + writeln!(out, "{},{}", pos, val)?; } - 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(()) + // TODO: Dont return use mutex + Ok((name, csvdata)) } else { Err(TinyError::ParseEnd("}".to_owned())) } @@ -230,34 +265,3 @@ pub fn parse_data(v: Vec) -> Result<(), TinyError> { fn u16_to_f64(v: u16) -> f64 { (v as f64) / 32. - OFFSET as f64 } - -// /// The result of a scan -// pub struct ScanResult { -// start: usize, -// stop: usize, -// points: usize, -// status: ScanStatus, -// data: Vec, -// } - -// 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"); -// } diff --git a/src/structs.rs b/src/structs.rs index 853b31a..1d5b8c5 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -1,6 +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 { @@ -16,4 +25,101 @@ pub enum TinyError { /// The given file could't be exported #[error("Couldn't open the given file")] OpenOutput(#[from] std::io::Error), + /// Generic TUI initialization error + #[error("An error occured while creating the TUI")] + TUIInitialization(#[from] color_eyre::Report), + /// 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)] +/// The direction the input was received, usefull for menu where R/L U/D give similar results and implementation +pub(crate) enum InputDirection { + Up, + Down, + Right, + Left, +} + +/// All implementation of errors happening while in the UI +#[derive(Error, Debug)] +pub enum TinyUIError { + /// An error due to bad menuing implementation + #[error("An error occured while selecting a menu item")] + MenuSelectionError, + + /// An error due to bad initialization + #[error("The item list ({0}) wasn't initialyzed ({2}:{1})")] + UninitializedItemList(&'static str, u32, &'static str), + + /// 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 + // #[allow(dead_code)] + // #[error("An error occured while trying to fetch progress")] + // Mutex, +} + +// impl TinyUIError { +// pub(crate) fn uninitialized_item_list_error(list: &'static str) -> Self { +// 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 { + 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(()) + } } diff --git a/src/ui.rs b/src/ui.rs new file mode 100644 index 0000000..6e91b0b --- /dev/null +++ b/src/ui.rs @@ -0,0 +1,554 @@ +//! The (minimal) user interface to control the program +#![allow(unused_imports)] +use clap::builder::Resettable; +use color_eyre::{owo_colors::OwoColorize, Section}; +use core::{panic, time}; +use ratatui::{ + buffer::Buffer, + crossterm::{ + event::{self, Event, KeyCode, KeyEvent, KeyEventKind}, + style::Print, + }, + layout::{Alignment, Constraint, Direction, Layout, Rect}, + prelude::BlockExt, + style::{ + palette::tailwind::{BLUE, GREEN, SLATE}, + Color, Modifier, Style, Styled, Stylize, + }, + symbols::{self, Marker}, + text::Line, + widgets::{ + block::Title, Axis, Block, Borders, Chart, Dataset, GraphType, HighlightSpacing, LineGauge, + List, ListDirection, ListItem, ListState, Padding, Paragraph, ScrollDirection, + StatefulWidget, Widget, Wrap, + }, + DefaultTerminal, Frame, +}; +use serialport::SerialPortInfo; +use std::{ + borrow::{Borrow, BorrowMut}, + cmp::min, + fmt::Pointer, + iter::Iterator, + sync::{Arc, Mutex}, + thread, + time::{Duration, Instant}, +}; +use strum::{EnumCount, EnumIter, EnumProperty}; +use strum::{FromRepr, IntoEnumIterator}; +use tui_textarea::{Input, Key, TextArea}; + +use crate::{ + mleft, mright, scan, + structs::{InputDirection, SavedConfig, TinyError, TinyUIError}, + ui_struct::{ + AppInfo, AppState, BaudRateList, MenuItems, PortList, SelectedConfig, SelectedFinalConfig, + UIUsize, SELECTED_COLOR, UNSELECTED_COLOR, + }, +}; + +impl<'a> AppInfo<'a> { + /// Create a new app with the port info available + pub(crate) fn new(info: Vec) -> 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::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, + 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())), + } + } + + /// Contains the main loop for running the app + pub(crate) fn run( + &mut self, + mut terminal: DefaultTerminal, + ) -> Result<(), color_eyre::eyre::Error> { + self.init_config()?; + loop { + terminal.draw(|v| self.draw(v).inspect_err(|e| panic!("{}", e)).unwrap())?; + 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(()) + } + + /// Generic draw loop method + fn draw(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { + 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), + } + } + + /// Initialisation of the config window + fn init_config(&mut self) -> Result<(), TinyUIError> { + self.menu_items.portlist = Some( + List::new(self.port_list.to_vecstr()) + .block(Block::bordered().title("COM Ports")) + .highlight_style( + Style::default() + .add_modifier(Modifier::ITALIC) + .bg(Color::Blue), + ) + .repeat_highlight_symbol(true), + ); + self.menu_items.baudlist = Some( + List::new(self.baudrate.to_vecstr()) + .block(Block::bordered().title("Baudrates")) + .highlight_style( + Style::default() + .add_modifier(Modifier::ITALIC) + .bg(Color::Blue), + ) + .repeat_highlight_symbol(true), + ); + self.update_color() + } + + /// Initialisation of all the ui element for the final configuration elements + fn init_final_config(&mut self) -> Result<(), TinyUIError> { + self.menu_items.textboxes = vec![Paragraph::new("")]; + self.update_color() + } + + /// Initialisation of all the final ui elements + pub(crate) fn init_end(&self) -> Result<(), TinyUIError> { + Ok(()) + } + + /// Draw the final configuration labels + fn draw_final_config(&mut self, frame: &mut Frame<'_>) -> Result<(), TinyUIError> { + let [title_area, main_area, _, status_area] = Layout::vertical([ + Constraint::Length(2), + Constraint::Length(3), + Constraint::Min(0), + Constraint::Length(1), + ]) + .areas(frame.area()); + let [_, area_minf, area_maxf, area_points, _] = Layout::horizontal([ + Constraint::Min(7), + Constraint::Percentage(30), + Constraint::Percentage(30), + Constraint::Percentage(30), + 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) + } + AppState::FinalConfig(SelectedFinalConfig::FinalFreq) => { + (UNSELECTED_COLOR, SELECTED_COLOR, UNSELECTED_COLOR) + } + AppState::FinalConfig(SelectedFinalConfig::Points) => { + (UNSELECTED_COLOR, UNSELECTED_COLOR, SELECTED_COLOR) + } + _ => unreachable!(), + }; + + // self.status_message = format!("{:?} ", self.flow_state); + frame.render_widget( + Paragraph::new(self.start_frequency.int_to_string()) + .block(Block::bordered().title("Start Frequency")) + .style(mif_color), + area_minf, + ); + frame.render_widget( + Paragraph::new(self.stop_frequency.int_to_string()) + .block(Block::bordered().title("Stop Frequency")) + .style(maf_color), + area_maxf, + ); + frame.render_widget( + Paragraph::new(self.points.int_to_string()) + .block(Block::bordered().title("Points")) + .style(poi_color), + area_points, + ); + + self.update_color()?; + frame.render_widget(Paragraph::new(self.status_message.clone()), title_area); + self.render_footer(frame, status_area); + Ok(()) + } + /// Render the selection footer + fn render_footer(&self, frame: &mut Frame, area: Rect) { + frame.render_widget( + Paragraph::new( + "Use ↓↑ to move, ←→ to change status widget and ↲ to validate configuration.", + ) + .centered(), + area, + ); + } + + /// Initialize the progress window + fn init_progress(&mut self) -> Result<(), TinyUIError> { + self.menu_items.progress_bar = Some( + LineGauge::default() + // .block(title) + .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 config info + fn draw_config(&mut self, frame: &mut Frame) -> Result<(), TinyUIError> { + let [title_area, main_area, status_area] = Layout::vertical([ + Constraint::Length(2), + Constraint::Min(10), + Constraint::Length(1), + ]) + .areas(frame.area()); + let [_, area_ports, area_baud, _] = Layout::horizontal([ + Constraint::Min(7), + Constraint::Percentage(50), + Constraint::Percentage(50), + Constraint::Min(7), + ]) + .areas(main_area); + let list_ports = self + .menu_items + .portlist + .as_ref() + .ok_or(TinyUIError::UninitializedItemList("Port", line!(), file!()))?; + let list_baudrates = self + .menu_items + .baudlist + .as_ref() + .ok_or(TinyUIError::UninitializedItemList("Baud", line!(), file!()))?; + // self.status_message = format!("{:?} ", self.flow_state); + frame.render_stateful_widget(list_ports, area_ports, &mut self.port_list.state); + frame.render_stateful_widget(list_baudrates, area_baud, &mut self.baudrate.state); + frame.render_widget(Paragraph::new(self.status_message.clone()), title_area); + self.render_footer(frame, status_area); + Ok(()) + } + + /// Draw the progress, updates as the progress is being done + fn draw_progress(&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, progress_area, main_area, _, _] = Layout::vertical([ + Constraint::Length(3), + Constraint::Length(1), + Constraint::Min(10), + Constraint::Length(1), + Constraint::Length(1), + ]) + .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 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 { + self.next_step()?; + } + Ok(()) + } + + /// Draw the last confirmation window + fn draw_end_window(&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, graph_area, _, footer_area] = Layout::vertical([ + Constraint::Length(3), + Constraint::Length(1), + Constraint::Min(10), + Constraint::Length(1), + 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))); + + // 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); + Ok(()) + } + + /// Handle keys while in the first menu + fn handle_start_keys(&mut self, key: KeyEvent) -> Result<(), TinyUIError> { + if key.kind != KeyEventKind::Press { + return Ok(()); + } + match key.code { + KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true, + KeyCode::Char('j') | KeyCode::Down => self.change_cursor_position(InputDirection::Down), + KeyCode::Char('k') | KeyCode::Up => self.change_cursor_position(InputDirection::Up), + KeyCode::Char('h') | KeyCode::Left => self.next_menu(InputDirection::Left)?, + KeyCode::Char('l') | KeyCode::Right => self.next_menu(InputDirection::Right)?, + KeyCode::Enter => match self.flow_state { + AppState::Finished => (), + _ => self.next_step()?, + }, + _ => {} + } + Ok(()) + } + + /// A directionnal input was received + fn change_cursor_position(&mut self, direction: InputDirection) { + match self.flow_state { + AppState::InitialConfig(ref selected_menu) => match selected_menu { + SelectedConfig::Baudrate => self.baudrate.change_cursor(direction), + SelectedConfig::Port => self.port_list.change_cursor(direction), + }, + AppState::FinalConfig(ref selected_menu) => match selected_menu { + SelectedFinalConfig::StartFreq => self.start_frequency.change_value(direction), + SelectedFinalConfig::FinalFreq => self.stop_frequency.change_value(direction), + SelectedFinalConfig::Points => self.points.change_value(direction), + }, + AppState::EndWindow => (), + AppState::Finished => (), + } + } + + /// Goes to the next menu depending on the position in the program + fn next_menu(&mut self, direction: InputDirection) -> Result<(), TinyUIError> { + if let Some(s) = match self.flow_state { + AppState::InitialConfig(ref r) => { + let v = *r as usize; + + match direction { + InputDirection::Right => mright!(v, InitialConfig, SelectedConfig), + InputDirection::Left => mleft!(v, InitialConfig, SelectedConfig), + _ => None, + } + } + AppState::FinalConfig(ref r) => { + let v = *r as usize; + + match direction { + InputDirection::Right => mright!(v, FinalConfig, SelectedFinalConfig), + InputDirection::Left => mleft!(v, FinalConfig, SelectedFinalConfig), + _ => None, + } + } + AppState::EndWindow => None, + AppState::Finished => None, + } { + self.flow_state = s; + } + self.update_color()?; + Ok(()) + } + + /// Progress in the flow of the program + fn next_step(&mut self) -> Result<(), TinyUIError> { + match self.flow_state { + AppState::InitialConfig(_) => { + self.flow_state = AppState::FinalConfig(SelectedFinalConfig::default()); + self.init_final_config()?; + } + AppState::FinalConfig(_) => { + 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; + 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 => { + self.should_quit = true; + } + AppState::Finished => { + self.flow_state = AppState::EndWindow; + self.init_end()?; + } + } + Ok(()) + } +} diff --git a/src/ui_struct.rs b/src/ui_struct.rs new file mode 100644 index 0000000..9fa56c0 --- /dev/null +++ b/src/ui_struct.rs @@ -0,0 +1,388 @@ +//! All ui structures and utility functions + +//! The (minimal) user interface to control the program +use color_eyre::Result; +use ratatui::{ + style::{Color, Style}, + widgets::{Block, LineGauge, List, ListState, Paragraph}, +}; +use serialport::SerialPortInfo; +use std::{ + iter::Iterator, + ops::Add, + sync::{Arc, Mutex}, +}; +use strum::{EnumCount, EnumIter}; +use strum::{FromRepr, IntoEnumIterator}; + +use crate::structs::{InputDirection, SavedConfig, TinyError, TinyUIError}; + +/// Color of a selected border +pub(crate) const SELECTED_COLOR: Color = Color::White; +/// Color of an unselected item +pub(crate) const UNSELECTED_COLOR: Color = Color::DarkGray; + +/// This struct holds the current state of the app. +#[derive(Debug)] +pub(crate) struct AppInfo<'a> { + /// Wether the app sould immediately quit + pub(crate) should_quit: bool, + /// The list of baudrates + pub(crate) baudrate: BaudRateList, + /// The list of ports + pub(crate) port_list: PortList, + /// State of the configuration, akin to tab or window + pub(crate) flow_state: AppState, + /// The list of menu item generated + pub(crate) menu_items: MenuItems<'a>, + /// A debug message string + pub(crate) status_message: String, + /// The start frequency + pub(crate) start_frequency: UIUsize, + /// The stop frequency + pub(crate) stop_frequency: UIUsize, + /// The number of points + pub(crate) points: UIUsize, + /// Global progress + pub(crate) progress: Arc>, + /// Global initialisation data + pub(crate) scan_info: Arc>, + /// Global message + pub(crate) scan_message: Arc>, + /// Return scan data + pub(crate) return_data: Arc>>, +} +#[derive(Debug)] +pub(crate) struct UIUsize { + /// Current value held by the usize + value: usize, + /// Increment by witch it can be upped + increment: usize, + /// Max value to clamp it to + clamp: usize, +} + +impl UIUsize { + /// Change the value depending on selection + pub(crate) fn change_value(&mut self, direction: InputDirection) { + match direction { + InputDirection::Up => self.value = self.value.add(self.increment).clamp(0, self.clamp), + InputDirection::Down => self.value = self.value.saturating_sub(self.increment), + _ => (), + } + } + + /// Create a new UIUsize, usefull for TUI manipulation + pub(crate) fn new(value: usize, increment: usize, clamp: usize) -> Self { + Self { + value, + increment, + clamp, + } + } + + /// Convert to a string with the litteral value + pub(crate) fn int_to_string(&self) -> String { + format!("{}", self.value) + } + + /// Convert to mhz multiplying it by 1_000_000 + pub(crate) fn mhz_to_usize(&self) -> usize { + self.value * 1000000 + } + + /// Output inner value + pub(crate) fn int_to_usize(&self) -> usize { + self.value + } +} + +#[derive(Debug)] +/// The inner state of the app, useful for display and keystrokes +pub(crate) enum AppState { + /// Initial config, baudrate and port + InitialConfig(SelectedConfig), + /// Final config, frequencies and points + FinalConfig(SelectedFinalConfig), + /// The end window for confirmation + EndWindow, + /// Save window + Finished, +} + +impl Default for AppState { + fn default() -> Self { + Self::InitialConfig(SelectedConfig::default()) + } +} + +#[macro_export] +/// Shortcut for move right +macro_rules! mright { + ($v:ident, $cname:ident,$fname:ident) => { + Some(AppState::$cname( + $fname::from_repr(min(($v + 1), $fname::COUNT - 1)) + .ok_or(TinyUIError::MenuSelectionError)?, + )) + }; +} + +#[macro_export] +/// Shortcut to move left +macro_rules! mleft { + ($v:ident, $cname:ident,$fname:ident) => { + if $v == 0 { + None + } else { + Some(AppState::$cname( + $fname::from_repr($v - 1).ok_or(TinyUIError::MenuSelectionError)?, + )) + } + }; +} +/// The selected item in the config +#[derive(Debug, EnumCount, FromRepr, Clone, Copy)] +pub(crate) enum SelectedConfig { + /// Selects the ports + Port, + /// Selects the baudrate + Baudrate, + // /// Selects to proceed + // Proceed, +} + +impl Default for SelectedConfig { + fn default() -> Self { + Self::Port + } +} + +/// The selected item in the final menu +#[derive(Debug, EnumCount, FromRepr, Copy, Clone)] +pub(crate) enum SelectedFinalConfig { + /// Selects the start frequency + StartFreq, + /// Selects the final frequency + FinalFreq, + /// Selects the number of points + Points, + // /// Selects to proceed + // Proceed, +} + +impl Default for SelectedFinalConfig { + fn default() -> Self { + Self::StartFreq + } +} + +/// The list of all baudrates selectables +#[derive(Debug)] +pub(crate) struct BaudRateList { + // /// The selected baudrate (default : BAUD1115200) + // pub(crate) selected: usize, + /// The baudrate list + pub(crate) baudrates: Vec, + /// The inner state of the widget + pub(crate) state: ListState, +} +impl BaudRateList { + /// Convert into a vec of strings, this is extremely expensive and shouldn't be done that way + pub(crate) fn to_vecstr(&self) -> Vec { + self.baudrates + .iter() + .map(|i| format!("{}", *i as usize)) + .collect() + } + + /// Change the cursor position on the baudrates + pub(crate) fn change_cursor(&mut self, direction: InputDirection) { + match direction { + InputDirection::Down => self.state.select_next(), + InputDirection::Up => self.state.select_previous(), + _ => (), + } + } + + /// Create a baudrate from a config file + pub(crate) fn from_conf(loaded_conf: &Result) -> 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 { + baudrates: BaudRate::iter().collect::>(), + state: ListState::default().with_selected(Some(3)), + } + } +} + +/// A list of possible baudrates +#[derive(Debug, EnumIter, Copy, Clone)] +pub(crate) enum BaudRate { + BAUD19200 = 19_200, + BAUD38400 = 38_400, + BAUD57600 = 57_600, + BAUD115200 = 115_200, + BAUD230400 = 230_400, + BAUD460800 = 460_800, + BAUD921600 = 921_600, + BAUD1843200 = 1_843_200, + BAUD2000000 = 2_000_000, + BAUD3000000 = 3_000_000, +} + +/// A wrapper over the list of ports +#[derive(Debug)] +pub(crate) struct PortList { + /// The list of found ports + pub(crate) ports: Vec, + // /// 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, + saved_config: &Result, + ) -> Self { + let ports: Vec = info.into_iter().map(|port| port.port_name).collect(); + let selected = find_best_port(&ports, saved_config); + Self { + ports, + // selected, + state: ListState::default().with_selected(Some(selected)), + } + } + + /// Convert the list of ports + pub(crate) fn to_vecstr(&self) -> Vec { + self.ports.clone() + } + + /// Change the selected item + pub(crate) fn change_cursor(&mut self, direction: InputDirection) { + match direction { + InputDirection::Up => self.state.select_previous(), + InputDirection::Down => self.state.select_next(), + _ => (), + } + } + + /// Returns the final selected port + pub(crate) fn selected_port(&self) -> String { + self.ports[self.state.selected().unwrap()].clone() + } +} + +#[derive(Debug, Default)] +/// The static list of all menu items +pub(crate) struct MenuItems<'a> { + /// List of port items + pub(crate) portlist: Option>, + /// List of port items + pub(crate) baudlist: Option>, + /// List of all the textboxes + pub(crate) textboxes: Vec>, + /// The progress bar + pub(crate) progress_bar: Option>, + // /// Controller info + // pub(crate) info: Option>, + // /// The final graph + // pub(crate) graph: Option>, +} + +/// Try to guess the best port to preselect +fn find_best_port(ports: &[String], saved_config: &Result) -> usize { + // TODO: Try to load from disk then save to disk + 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; + } + } + 0 +} + +impl<'a> AppInfo<'a> { + /// Put an item a specified color + pub(crate) fn change_color( + &mut self, + name: &'a str, + list: List<'a>, + color: Color, + ) -> Option> { + Some( + list.block(Block::bordered().title(name).border_style(color)) + .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> { + /// Update all the colors + pub(crate) fn update_color(&mut self) -> Result<(), TinyUIError> { + match self.flow_state { + AppState::InitialConfig(ref c) => { + let (p_c, b_c) = match c { + SelectedConfig::Baudrate => (UNSELECTED_COLOR, SELECTED_COLOR), + SelectedConfig::Port => (SELECTED_COLOR, UNSELECTED_COLOR), + }; + let (p, b) = + ( + self.menu_items.portlist.take().ok_or( + TinyUIError::UninitializedItemList("Port List", line!(), file!()), + )?, + self.menu_items.baudlist.take().ok_or( + TinyUIError::UninitializedItemList("Port List", line!(), file!()), + )?, + ); + // self.status_message = format!("{:?} p:{:?} {:?} {:?}", Instant::now(), p_c, b_c, c); + self.menu_items.portlist = self.change_color("COM Ports", p, p_c); + self.menu_items.baudlist = self.change_color("Baudrate", b, b_c); + } + // TODO: Have all color update here + AppState::FinalConfig(_selected_final_config) => (), + _ => (), + } + 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 +// }}; +// }