Adds a lot of debugging Qol

This commit is contained in:
Dandaedre 2024-09-25 21:37:15 +02:00
parent e20fa4bd60
commit 222c9cb1db
7 changed files with 143 additions and 49 deletions

1
.gitignore vendored
View File

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

View File

@ -5,11 +5,12 @@ edition = "2021"
[dependencies]
chrono = "0.4.38"
# byteorder = "1.5.0"
clap = { version = "4.5.17", features = ["derive"] }
color-eyre = "0.6.3"
flexi_logger = "0.29.0"
human-panic = "2.0.1"
# csv = "1.3.0"
# log = { version = "0.4.22", features = ["max_level_debug", "release_max_level_error"] }
log = { version = "0.4.22"}
memchr = "2.7.4"
once_cell = "1.19.0"
packed_struct = "0.10.1"

View File

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

View File

@ -9,7 +9,9 @@ static LONG_WAIT: u64 = 200;
/// The standard timeout time
static TIMEOUT: u64 = 2000;
use crate::info;
use crate::structs::TinyError;
use log::error;
use memchr::memmem;
use packed_struct::prelude::*;
use serialport::SerialPort;
@ -48,8 +50,10 @@ pub(crate) fn scan_with_progress(
start: usize,
stop: usize,
points: usize,
// TODO: Add repeat to tui
repeat: usize,
) -> Result<(), TinyError> {
let mode = mode_from(start, stop)?;
// TODO: Pass the connection status mutex to advance it
*scan_message.lock().unwrap() = "Oppening connection".to_string();
let port = serialport::new(port, 115_200)
@ -60,6 +64,7 @@ pub(crate) fn scan_with_progress(
return Err(TinyError::PortConnection(e));
}
let mut port = port.unwrap();
// TODO: Show all unitialised data somewhere
*scan_message.lock().unwrap() = "Initialisation...".to_string();
*progress.lock().unwrap() = 5;
initialize(&mut port);
@ -76,8 +81,9 @@ pub(crate) fn scan_with_progress(
*scan_message.lock().unwrap() = "Setting up repeat".to_string();
// TODO: Investigate this behaviour
send_cmd(&mut port, &format!("repeat {}\r", 4), SHORT_WAIT);
send_cmd(&mut port, &format!("calc aver16\r"), SHORT_WAIT);
send_cmd(&mut port, &format!("repeat {}\r", 5), SHORT_WAIT);
// TODO: Allow for user configuration
send_cmd(&mut port, "calc aver16\r", SHORT_WAIT);
*progress.lock().unwrap() = 16;
*scan_message.lock().unwrap() = "Setting zero...".to_string();
@ -90,7 +96,6 @@ pub(crate) fn scan_with_progress(
*progress.lock().unwrap() = 18;
*scan_message.lock().unwrap() = "Setting up scan & mode".to_string();
let mode = mode_from(start, stop)?;
send_cmd(&mut port, &format!("mode {} input\r", mode), SHORT_WAIT);
*progress.lock().unwrap() = 19;
@ -117,7 +122,12 @@ pub(crate) fn scan_with_progress(
points,
)?;
*scan_message.lock().unwrap() = format!("Scan saved as {}", name);
// TODO: Change this awful thing with a struct with all data
*scan_message.lock().unwrap() = format!(
"Scan of {} points saved as {}",
return_data.lock().unwrap().len(),
name
);
send_cmd(&mut port, "resume\r", SHORT_WAIT);
wait_sync(LONG_WAIT);
@ -129,12 +139,17 @@ pub(crate) fn scan_with_progress(
fn mode_from(start: usize, stop: usize) -> Result<String, TinyError> {
// TODO: Switch to low if possible with another non overlaping pattern
if start > stop {
return Err(TinyError::BadScanFrequencies);
return Err(TinyError::BadScanFrequencies(format!(
"Start frequency {}Hz is higher than stop frequency {}Hz",
start, stop
)));
}
match (start, stop) {
(240_000_000..=960_000_000, 240_000_000..=960_000_000) => Ok("high".to_string()),
(0..240_000_000, 0..240_000_000) => Ok("low".to_string()),
_ => Err(TinyError::BadScanFrequencies),
_ => Err(TinyError::BadScanFrequencies(
"Scan frequencies must either be in range (0MHz-240MHz) or (240MHz-960MHz)".to_owned(),
)),
}
}
@ -142,7 +157,11 @@ fn mode_from(start: usize, stop: usize) -> Result<String, 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);
read_port(port);
let d = read_port(port);
if !d.is_empty() {
info!(target: "scan", "Pre-init data found");
info!(target: "scan", "{:?}", String::from_utf8_lossy(&d).to_string());
}
wait_sync(SHORT_WAIT)
}
@ -167,7 +186,8 @@ fn scanraw(
progress,
points,
start,
(stop - start) as f64 / points as f64,
// TODO: Checks that points are always >1
(stop - start) as f64 / (points - 1) as f64,
)?;
*return_data.lock().unwrap() = val;
wait_sync(LONG_WAIT);
@ -262,24 +282,50 @@ pub fn parse_data(
let mut csvdata = Vec::with_capacity(points);
if let Some(begining) = memchr::memchr(b'{', &v) {
// Finds the } marking the end
if let Some(end) = memchr::memchr(b'}', &v) {
let data = &v[begining + 1..end];
for (i, slice) in data.chunks_exact(3).enumerate() {
let s: &[u8; 3] = &[slice[0], slice[1], slice[2]];
let d = DataPoint::unpack(s)?;
let (pos, val) = (
(i as f64 * increment + start as f64) / 1000000.,
u16_to_f64(d.value),
);
// Assert no bogus data is sent ? just check lenght answer ?
let end_tmp = v.len();
// if let Some(end) = memchr::memchr(b'}', &v) {
let data = &v[begining + 1..end_tmp];
csvdata.push((pos, val));
writeln!(out, "{},{}", pos, val)?;
}
// TODO: Dont return use mutex
Ok((name, csvdata))
} else {
Err(TinyError::ParseEnd("}".to_owned()))
let mut end = end_tmp;
let chunks_exact = data.chunks_exact(3);
if chunks_exact.remainder().is_empty() {
return Err(TinyError::ParseEnd(
"The data received doesn't have a end char (empty)".to_owned(),
));
} else if chunks_exact.remainder()[0] != b'}' {
// No end char, bogus
return Err(TinyError::ParseEnd(
"The returned data doesn't have the right end char".to_owned(),
));
}
for (i, slice) in chunks_exact.enumerate() {
let s: &[u8; 3] = &[slice[0], slice[1], slice[2]];
let d = DataPoint::unpack(s)?;
if d.c == b'}' {
// Found an end and the rest is garbage
end = i * 3;
// TODO: why doesn't it pop ?
info!("Found an end at {end}");
break;
} else if d.c != b'x' {
// The alignment char is wrong
error!("Wrong alignment char");
return Err(TinyError::ParseEnd("Wrong alignement char".to_owned()));
}
let (pos, val) = (
(i as f64 * increment + start as f64) / 1000000.,
u16_to_f64(d.value),
);
info!("{},{},{} : {pos},{val}", i, increment, start);
csvdata.push((pos, val));
writeln!(out, "{},{}", pos, val,)?;
}
// TODO: Dont return use mutex
// info!("debug",format!("{} {}", data.len(), v.len());
info!("End at {end} {}", v[end - 1]);
Ok((name, csvdata))
} else {
Err(TinyError::ParseBeggining("{".to_owned()))
}

View File

@ -50,10 +50,13 @@ pub enum TinyError {
/// The given scan frequencies are incorrect
// TODO: Expand
#[error("The given scan frequencies are inccorect")]
BadScanFrequencies,
/// A ui error happened
#[error("An UI error happened")]
UIError(#[from] TinyUIError),
BadScanFrequencies(String),
/// The error wasn't caused during the scanning process
#[error("Unspecified error")]
NoErrorSpecified,
// /// A ui error happened
// #[error("An UI error happened")]
// UIError(#[from] TinyUIError),
}
#[allow(missing_docs, clippy::missing_docs_in_private_items)]
@ -87,6 +90,9 @@ pub enum TinyUIError {
// TODO: Expand
#[error("No port was selected")]
NoPortSelected,
/// Any UI Error
#[error("An error occured while processing the scan request")]
ScanError(#[from] TinyError),
}
// impl TinyUIError {

View File

@ -83,6 +83,7 @@ impl<'a> AppInfo<'a> {
connection_status: Arc::new(Mutex::new(ConnectionStatus::Uninitialised)),
repeat: UIUsize::new(1, 1, 1000),
error: None,
scan_error: Arc::new(Mutex::new(None)),
}
}
@ -340,7 +341,8 @@ impl<'a> AppInfo<'a> {
Constraint::Min(7),
])
.areas(frame.area());
let [title_area, _main_area, message_area, _, footer_area] = Layout::vertical([
let [_, title_area, _main_area, message_area, _, footer_area] = Layout::vertical([
Constraint::Length(1),
Constraint::Length(3),
Constraint::Length(1),
Constraint::Min(10),
@ -350,24 +352,45 @@ impl<'a> AppInfo<'a> {
.areas(main_s);
let conn_status = *self.connection_status.lock().unwrap();
let status = Paragraph::new(
// TODO: Be more explicit with errors
"The scan couldn't be performed, please check your connection".to_string(),
)
.block(Block::bordered().title("Status"))
.style(Color::Red);
let error = Paragraph::new(
// TODO: Be more explicit with errors
format!(
"Last status: {:?}\nLast message: {}\nError: {:?}",
conn_status,
self.scan_message.lock().unwrap().clone(),
self.error
),
)
let status_message = match self
.scan_error
.lock()
.unwrap()
.as_ref()
.unwrap_or(&TinyError::NoErrorSpecified)
{
TinyError::ParseBeggining(_) => "An error occured while receiving data, the scan never sent back any valid data",
TinyError::ParseEnd(_) => "An error occured while receiving data, scan was interupted before ending properly",
TinyError::PortConnection(_) => "An error occured while trying to connect, check the selected port and baudrate",
TinyError::NoVersionFound => "An error forbid the gathering of the version, check your TinySA is connected and powered on",
TinyError::BadScanFrequencies(_) => "An error occured because the scan frequencies weren't set correctly",
TinyError::NoErrorSpecified => "An error occured while processing the scan",
TinyError::OpenOutput(_) => todo!(),
TinyError::TUIInitialization(_) => todo!(),
TinyError::TUIRuntimeError(_) => todo!(),
TinyError::TUIPackingError(_) => todo!(),
TinyError::ConfigNotFound => todo!(),
TinyError::InvalidConfig(_) => todo!(),
TinyError::InvalidDataForConfig(_) => todo!(),
};
let status = Paragraph::new(status_message)
.block(Block::bordered().title("Status"))
.style(Color::Red);
let mut additional = String::new();
if let Some(m) = &self.error {
additional.push_str(&format!("Error: {:?} => {}\n", m, m));
}
if let Some(m) = &*self.scan_error.lock().unwrap() {
additional.push_str(&format!("Scan Error: {:?} => {}\n", m, m));
}
let error = Paragraph::new(format!(
"Last status: {:?}\nLast message: {}\n{}",
conn_status,
self.scan_message.lock().unwrap().clone(),
additional
))
.block(Block::bordered().title("Status"));
// .style(Color::Red);
let footer = Paragraph::new(format!("Press ↲ or q to exit")).centered();
let footer = Paragraph::new("Press ↲ or q to exit".to_string()).centered();
frame.render_widget(status, title_area);
frame.render_widget(error, message_area);
frame.render_widget(footer, footer_area);
@ -560,6 +583,7 @@ impl<'a> AppInfo<'a> {
let stop = self.stop_frequency.mhz_to_usize();
let points = self.points.int_to_usize();
let repeat = self.repeat.int_to_usize();
let error = self.scan_error.clone();
// BYPASS
*self.progress.lock().unwrap() = 100;
self.save_config()?;
@ -569,7 +593,10 @@ impl<'a> AppInfo<'a> {
);
match status {
Ok(_) => *cstatus.lock().unwrap() = ConnectionStatus::ClosedWithSuccess,
Err(_) => *cstatus.lock().unwrap() = ConnectionStatus::ConnectionFailure,
Err(e) => {
*error.lock().unwrap() = Some(e);
*cstatus.lock().unwrap() = ConnectionStatus::ConnectionFailure
}
}
// panic!();
// TODO: Do something with bad status to avoid false positive

View File

@ -58,6 +58,8 @@ pub(crate) struct AppInfo<'a> {
/// The current last error
//TODO: Solve this shite
pub(crate) error: Option<TinyUIError>,
/// A scan error
pub(crate) scan_error: Arc<Mutex<Option<TinyError>>>,
}
#[derive(Debug)]