Cleans up some message and progress workflow

This commit is contained in:
Dandaedre 2024-09-27 01:53:01 -05:00
parent 06f3e2b443
commit 19c8b1c1b7
4 changed files with 74 additions and 61 deletions

View File

@ -16,7 +16,7 @@ use structs::TinyError;
use ui_struct::AppInfo;
use flexi_logger::{FileSpec, Logger, WriteMode};
use log::info;
use log;
fn main() -> Result<(), TinyError> {
let _logger = Logger::try_with_str("info, my::critical::module=trace")
@ -25,7 +25,7 @@ fn main() -> Result<(), TinyError> {
.write_mode(WriteMode::BufferAndFlush)
.start()?;
info!(target:"info","Logging started");
log::info!(target:"info","Logging started");
color_eyre::install()?;
let terminal = ratatui::init();
// setup_panic!();

View File

@ -9,8 +9,8 @@ static LONG_WAIT: u64 = 200;
/// The standard timeout time
static TIMEOUT: u64 = 2000;
use crate::structs::TinyError;
use crate::{info, structs::ConnectionInfo};
use crate::structs::ConnectionInfo;
use crate::structs::{ConnectionStatus, TinyError};
use log::{error, trace, warn};
use memchr::memmem;
use packed_struct::prelude::*;
@ -42,35 +42,29 @@ 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(connection_info: ConnectionInfo) -> Result<(), TinyError> {
info!("Initializying connection: {:#?}", connection_info);
let mode = mode_from(connection_info.start, connection_info.stop)?;
connection_info.update_message("Opening connection");
let port = serialport::new(&connection_info.port, connection_info.baudrate)
.timeout(Duration::from_millis(3000))
.open();
if let Err(e) = port {
error!("Connection error {}", e);
connection_info.set_error(Some(TinyError::PortConnection(e.clone()).into()));
return Err(TinyError::PortConnection(e));
}
let mut port = port?;
let mut port = acquire_port(&connection_info)?;
connection_info.update_message("Initialisation...");
connection_info.update_progress(5);
initialize(&mut port);
connection_info.set_connection_status(ConnectionStatus::Connected);
connection_info.update_progress(15);
connection_info.update_message("Acquiring version & info");
let v = send_cmd(&mut port, "version\r", SHORT_WAIT)?;
let i = send_cmd(&mut port, "info\r", SHORT_WAIT)?;
// let f: String = send_cmd(&mut port, "leveloffset\r", SHORT_WAIT)?;
// TODO : Also add deviceid, vbat, usart_cfg; threads
// TODO: Parse this info in a struct and do a version check
let f = send_cmd(&mut port, "leveloffset\r", SHORT_WAIT)?;
let g = send_cmd(&mut port, "vbat\r", SHORT_WAIT)?;
let h = send_cmd(&mut port, "usart_cfg\r", SHORT_WAIT)?;
let k = send_cmd(&mut port, "threads\r", SHORT_WAIT)?;
log::info!("{f}{g}{h}{k}");
// TODO: have a more thourough version check
// TODO: Parse this info in a struct and do a version check
if v.is_empty() || i.is_empty() {
return Err(TinyError::NoVersionFound);
}
connection_info.update_info(format!("{}{}", v, i));
connection_info.update_info(format!("{v}{i}"));
connection_info.update_message("Setting up repeat");
send_cmd(
@ -108,7 +102,7 @@ pub(crate) fn scan_with_progress(connection_info: ConnectionInfo) -> Result<(),
)?;
connection_info.update_progress(20);
connection_info.update_message("Starting scan...");
connection_info.update_message("Sweeping...");
send_cmd(&mut port, "sweep\r", SHORT_WAIT)?;
send_cmd(
&mut port,
@ -120,17 +114,34 @@ pub(crate) fn scan_with_progress(connection_info: ConnectionInfo) -> Result<(),
)?;
connection_info.update_progress(22);
connection_info.update_message("Starting scan...");
connection_info.set_connection_status(ConnectionStatus::ScanStarted);
connection_info.update_filename(scanraw(&mut port, connection_info.clone())?);
connection_info.update_message("Acquiring version & info");
connection_info.update_message("Scan finished");
send_cmd(&mut port, "resume\r", SHORT_WAIT)?;
// wait_sync(LONG_WAIT);
connection_info.update_progress(100);
connection_info.set_connection_status(ConnectionStatus::ClosedWithSuccess);
Ok(())
}
fn acquire_port(connection_info: &ConnectionInfo) -> Result<Box<dyn SerialPort>, TinyError> {
let port = {
connection_info.update_message("Opening connection");
connection_info.set_connection_status(ConnectionStatus::Initialised);
let port = serialport::new(&connection_info.port, connection_info.baudrate)
.timeout(Duration::from_millis(3000))
.open();
if let Err(e) = port {
connection_info.set_error(Some(TinyError::PortConnection(e.clone()).into()));
return Err(TinyError::PortConnection(e));
}
port
}?;
Ok(port)
}
/// Get the mode of operation from the start & stop scan values
fn mode_from(start: usize, stop: usize) -> Result<String, TinyError> {
if start > stop {
@ -155,8 +166,8 @@ fn initialize(port: &mut Box<dyn SerialPort>) {
wait_sync(SHORT_WAIT);
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());
log::info!(target: "scan", "Pre-init data found");
log::info!(target: "scan", "{:?}", String::from_utf8_lossy(&d).to_string());
}
wait_sync(SHORT_WAIT)
}
@ -286,11 +297,11 @@ pub fn parse_data(
let end_tmp = v.len();
let data = &v[begining + 1..end_tmp]; // -4 since ch>\r will always be ignored
// TODO: Fix weird data
info!(
log::info!(
"The begining looks like :{:?}",
&v[begining - 1..begining + 9]
);
info!("The end looks like :{:?}", &v[end_tmp - 10..end_tmp]);
log::info!("The end looks like :{:?}", &v[end_tmp - 10..end_tmp]);
let mut end = end_tmp;
let chunks_exact = data.chunks_exact(3);
@ -331,7 +342,7 @@ pub fn parse_data(
}
// TODO: Dont return use mutex
// info!("debug",format!("{} {}", data.len(), v.len());
info!(
log::info!(
"End at {end} expected {} and found {} ({:?})",
b'}',
v[end - 1],

View File

@ -7,13 +7,14 @@ use std::{
};
use flexi_logger::FlexiLoggerError;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use log;
use serde;
use thiserror;
use crate::ui_struct::AppInfo;
/// The most common error, exposed to the lib user and end used
#[derive(Error, Debug)]
#[derive(thiserror::Error, Debug)]
pub enum TinyError {
/// An error occured while receiving the raw data and '{' couldn't be found
#[error("Couldn't parse the beggining of the data ({0})")]
@ -69,7 +70,7 @@ pub(crate) enum InputDirection {
}
/// All implementation of errors happening while in the UI
#[derive(Error, Debug)]
#[derive(thiserror::Error, Debug)]
pub enum TinyUIError {
/// An error due to bad menuing implementation
#[error("An error occured while selecting a menu item")]
@ -100,7 +101,7 @@ pub enum TinyUIError {
SerializeError(#[from] toml::ser::Error),
}
#[derive(Serialize, Deserialize, Debug)]
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub(crate) struct SavedConfig {
/// The default com port
pub(crate) port: String,
@ -151,14 +152,15 @@ impl SavedConfig {
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 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,
ScanStarted,
}
type ScanData = Vec<(f64, f64)>;
@ -219,16 +221,19 @@ impl ConnectionInfo {
/// Updates the generic scan message
pub(crate) fn update_message(&self, message: &'static str) {
log::trace!("Message: {message}");
*self.scan_message.lock().unwrap() = message.to_string();
}
/// Updates the scan progress
pub(crate) fn update_progress(&self, progress: usize) {
log::trace!("Progress: {progress}");
*self.progress.lock().unwrap() = progress;
}
/// Update the information of the TinySA
pub(crate) fn update_info(&self, message: String) {
log::info!("Info: {message}");
*self.scan_info.lock().unwrap() = message.to_string();
}
@ -276,13 +281,9 @@ impl ConnectionInfo {
.ok_or(TinyUIError::NoReturnData)
}
/// Updates the connection status
pub(crate) fn update_connection_status(&self, new_status: ConnectionStatus) {
*self.connection_status.lock().unwrap() = new_status
}
/// Set an error
pub(crate) fn set_error(&self, e: Option<TinyUIError>) {
log::error!("Error: {e:?}");
*self.error_raised.lock().unwrap() = e;
}
@ -291,6 +292,12 @@ impl ConnectionInfo {
self.error_raised.lock().unwrap().is_some()
}
/// Manually sets the connections status
pub(crate) fn set_connection_status(&self, status: ConnectionStatus) {
log::info!("Status: {status:?}");
*self.connection_status.lock().unwrap() = status;
}
// pub(crate) fn get_error(&self) -> &Option<TinyError> {
// self.error_raised.lock().as_ref().unwrap()
// }

View File

@ -346,17 +346,18 @@ impl<'a> AppInfo<'a> {
frame.render_widget(status, title_area);
frame.render_widget(message, main_area);
self.menu_items.progress_bar = Some(pb);
// TODO: Use the connection status instead
if self.get_connection_info()?.get_progress() >= 100 {
self.return_data = self.get_connection_info()?.get_return_data()?;
self.next_step()?;
}
let st = self.get_connection_info()?.get_connection_status();
#[allow(clippy::single_match)]
// Change color or some logo ?
match st {
// TODO: Add other failures, skip to draw error ?
ConnectionStatus::ConnectionFailure => self.next_step()?,
_ => (),
ConnectionStatus::Uninitialised
| ConnectionStatus::ScanStarted
| ConnectionStatus::Initialised
| ConnectionStatus::Connected => (),
ConnectionStatus::ClosedWithSuccess => {
self.return_data = self.get_connection_info()?.get_return_data()?;
self.next_step()?;
}
}
Ok(())
}
@ -645,18 +646,12 @@ impl<'a> AppInfo<'a> {
let connection = self.get_connection_info()?.clone();
self.save_config()?;
thread::spawn(move || {
let status = scan::scan_with_progress(co);
match status {
Ok(_) => {
connection.update_connection_status(ConnectionStatus::ClosedWithSuccess)
}
Err(e) => {
info!("An error occured during thread exec: {e}");
if !connection.has_error() {
connection.set_error(Some(e.into()));
}
connection.update_connection_status(ConnectionStatus::ConnectionFailure)
if let Err(status) = scan::scan_with_progress(co) {
log::error!("An error occured during thread exec: {status}");
if !connection.has_error() {
connection.set_error(Some(status.into()));
}
connection.set_connection_status(ConnectionStatus::ConnectionFailure);
}
});
}