mirror of
https://github.com/hubaldv/bioz-host-rs.git
synced 2025-12-06 05:11:17 +00:00
Updated logging to be able to select output folder.
This commit is contained in:
70
src/app.rs
70
src/app.rs
@@ -12,11 +12,12 @@ use chrono::Local;
|
||||
use atomic_float::AtomicF32;
|
||||
use tokio::{sync::mpsc::{Sender}};
|
||||
|
||||
use eframe::egui::{self, Button, CollapsingHeader, Color32, ComboBox, DragValue, Id, Key, Label, Layout, Modifiers, TextEdit, Widget};
|
||||
use eframe::egui::{self, Button, CollapsingHeader, Color32, ComboBox, DragValue, Id, Key, Label, Layout, Modifiers, RichText, TextEdit, Widget};
|
||||
use egui_plot::{Corner, GridInput, GridMark, Legend, Line, Plot, PlotPoint, Points};
|
||||
use egui_dock::{DockArea, DockState, Style};
|
||||
use egui_extras::{TableBuilder, Column};
|
||||
|
||||
use crate::logging::LoggingStates;
|
||||
use crate::plot::{TimeSeriesPlot, BodePlot};
|
||||
|
||||
use crate::signals::{LoggingSignal, StartStopSignal};
|
||||
@@ -67,7 +68,7 @@ pub struct App {
|
||||
pub measurement_points: Arc<Mutex<MeasurementPointSet>>,
|
||||
pub periods_per_dft: Arc<Mutex<Option<f32>>>,
|
||||
pub periods_per_dft_sweep: Arc<Mutex<(Vec<u32>, Option<Vec<f32>>)>>,
|
||||
pub gui_logging_enabled: Arc<AtomicBool>,
|
||||
pub gui_logging_state: Arc<Mutex<LoggingStates>>,
|
||||
log_filename: String,
|
||||
}
|
||||
|
||||
@@ -540,7 +541,7 @@ impl App {
|
||||
measurement_points,
|
||||
periods_per_dft,
|
||||
periods_per_dft_sweep,
|
||||
gui_logging_enabled: Arc::new(AtomicBool::new(false)),
|
||||
gui_logging_state: Arc::new(Mutex::new(LoggingStates::Idle)),
|
||||
log_filename: format!("log_{}.csv", Local::now().format("%Y%m%d"))
|
||||
};
|
||||
|
||||
@@ -619,23 +620,31 @@ impl eframe::App for App {
|
||||
|
||||
ui.separator();
|
||||
|
||||
let mut gui_logging_enabled = self.gui_logging_enabled.load(Ordering::Relaxed);
|
||||
if ui.add(egui::Checkbox::new(&mut gui_logging_enabled, "Logging")).changed() {
|
||||
self.gui_logging_enabled.store(gui_logging_enabled, Ordering::Relaxed);
|
||||
if gui_logging_enabled {
|
||||
if let Err(e) = self.log_tx.try_send(LoggingSignal::StartFileLogging(self.log_filename.clone())) {
|
||||
error!("Failed to send logging signal: {:?}", e);
|
||||
}
|
||||
} else {
|
||||
if let Err(e) = self.log_tx.try_send(LoggingSignal::StopFileLogging) {
|
||||
error!("Failed to send logging signal: {:?}", e);
|
||||
}
|
||||
}
|
||||
let gui_logging_state = *self.gui_logging_state.lock().unwrap();
|
||||
|
||||
let (color, signal) = match gui_logging_state {
|
||||
LoggingStates::Idle => (Color32::DARK_RED, LoggingSignal::StartFileLogging(self.log_filename.clone())),
|
||||
LoggingStates::Starting => (Color32::from_rgb(204, 153, 0), LoggingSignal::StopFileLogging),
|
||||
LoggingStates::Logging => (Color32::DARK_GREEN, LoggingSignal::StopFileLogging),
|
||||
};
|
||||
|
||||
let button = Button::new(
|
||||
RichText::new("Logging")
|
||||
.strong()
|
||||
.color(Color32::WHITE)
|
||||
).fill(color)
|
||||
.corner_radius(5.0)
|
||||
.frame(true);
|
||||
|
||||
if ui.add(button).clicked() {
|
||||
self.log_tx.try_send(signal).unwrap_or_else(|e| {
|
||||
error!("Failed to send logging toggle signal: {:?}", e);
|
||||
});
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
|
||||
ui.add_enabled_ui(!gui_logging_enabled, |ui| {
|
||||
ui.add_enabled_ui(gui_logging_state == LoggingStates::Idle, |ui| {
|
||||
ui.label("Log filename:");
|
||||
TextEdit::singleline(&mut self.log_filename).desired_width(125.0).id(Id::new("file_name_field")).ui(ui);
|
||||
});
|
||||
@@ -644,7 +653,7 @@ impl eframe::App for App {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.scope(|ui| {
|
||||
let is_connected = self.connected.load(Ordering::Relaxed);
|
||||
let color = if is_connected { Color32::GREEN } else { Color32::RED };
|
||||
let color = if is_connected { Color32::DARK_GREEN } else { Color32::DARK_RED };
|
||||
let tooltip = if is_connected { "Connected" } else { "Disconnected" };
|
||||
|
||||
// Allocate a fixed-size rectangle for the LED
|
||||
@@ -739,17 +748,22 @@ impl eframe::App for App {
|
||||
|
||||
// Enable/disable GUI logging
|
||||
if ctx.input(|i| i.key_pressed(egui::Key::L)) {
|
||||
let mut gui_logging_enabled = self.gui_logging_enabled.load(Ordering::Relaxed);
|
||||
gui_logging_enabled = !gui_logging_enabled;
|
||||
self.gui_logging_enabled.store(gui_logging_enabled, Ordering::Relaxed);
|
||||
if gui_logging_enabled {
|
||||
if let Err(e) = self.log_tx.try_send(LoggingSignal::StartFileLogging(self.log_filename.clone())) {
|
||||
error!("Failed to send logging signal: {:?}", e);
|
||||
}
|
||||
} else {
|
||||
if let Err(e) = self.log_tx.try_send(LoggingSignal::StopFileLogging) {
|
||||
error!("Failed to send logging signal: {:?}", e);
|
||||
}
|
||||
let gui_logging_enabled = *self.gui_logging_state.lock().unwrap();
|
||||
match gui_logging_enabled {
|
||||
LoggingStates::Starting => {
|
||||
// If currently starting, do nothing
|
||||
return;
|
||||
},
|
||||
LoggingStates::Logging => {
|
||||
if let Err(e) = self.log_tx.try_send(LoggingSignal::StopFileLogging) {
|
||||
error!("Failed to send logging signal: {:?}", e);
|
||||
}
|
||||
},
|
||||
LoggingStates::Idle => {
|
||||
if let Err(e) = self.log_tx.try_send(LoggingSignal::StartFileLogging(self.log_filename.clone())) {
|
||||
error!("Failed to send logging signal: {:?}", e);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -43,10 +43,11 @@ async fn main() {
|
||||
let periods_per_dft = app.periods_per_dft.clone();
|
||||
let periods_per_dft_sweep = app.periods_per_dft_sweep.clone();
|
||||
|
||||
let gui_logging_enabled = app.gui_logging_enabled.clone();
|
||||
let gui_logging_state_1 = app.gui_logging_state.clone();
|
||||
let gui_logging_state_2 = app.gui_logging_state.clone();
|
||||
|
||||
// Log thread
|
||||
tokio::spawn(async move { log_data(log_rx).await });
|
||||
tokio::spawn(async move { log_data(log_rx, gui_logging_state_1).await });
|
||||
|
||||
// Execute the runtime in its own thread.
|
||||
std::thread::spawn(move || {
|
||||
@@ -62,7 +63,7 @@ async fn main() {
|
||||
data_frequency_clone,
|
||||
periods_per_dft,
|
||||
periods_per_dft_sweep,
|
||||
gui_logging_enabled,
|
||||
gui_logging_state_2,
|
||||
log_tx_clone,
|
||||
));
|
||||
});
|
||||
|
||||
@@ -15,6 +15,7 @@ use bioz_icd_rs::MeasurementPointSet;
|
||||
use crate::icd;
|
||||
use crate::client::WorkbookClient;
|
||||
|
||||
use crate::logging::LoggingStates;
|
||||
use crate::plot::{TimeSeriesPlot, BodePlot};
|
||||
|
||||
use crate::signals::{LoggingSignal, StartStopSignal};
|
||||
@@ -31,7 +32,7 @@ pub async fn communicate_with_hardware(
|
||||
data_frequency: Arc<AtomicF32>,
|
||||
periods_per_dft: Arc<Mutex<Option<f32>>>,
|
||||
periods_per_dft_sweep: Arc<Mutex<(Vec<u32>, Option<Vec<f32>>)>>,
|
||||
gui_logging_enabled: Arc<AtomicBool>,
|
||||
gui_logging_state: Arc<Mutex<LoggingStates>>,
|
||||
log_tx: Sender<LoggingSignal>,
|
||||
) {
|
||||
let data_counter = Arc::new(AtomicU32::new(0));
|
||||
@@ -78,7 +79,7 @@ pub async fn communicate_with_hardware(
|
||||
let data_counter_clone_single = data_counter_clone.clone();
|
||||
|
||||
// Clone log_tx for the task
|
||||
let gui_logging_enabled_clone = gui_logging_enabled.clone();
|
||||
let gui_logging_state_clone = gui_logging_state.clone();
|
||||
let log_tx_clone = log_tx.clone();
|
||||
|
||||
let settings_clone = settings.clone();
|
||||
@@ -91,7 +92,7 @@ pub async fn communicate_with_hardware(
|
||||
let mut mag_val = data.2.lock().unwrap();
|
||||
let mut phase_val = data.3.lock().unwrap();
|
||||
|
||||
*mag_val = val.magnitude;
|
||||
*mag_val = val.magnitude;
|
||||
*phase_val = val.phase;
|
||||
|
||||
mag_plot.add(val.magnitude as f64);
|
||||
@@ -100,11 +101,11 @@ pub async fn communicate_with_hardware(
|
||||
data_counter_clone_single.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
// Send logging signal
|
||||
if gui_logging_enabled_clone.load(Ordering::Relaxed) {
|
||||
if *gui_logging_state_clone.lock().unwrap() == LoggingStates::Logging {
|
||||
let settings = *settings_clone.lock().unwrap();
|
||||
match settings.frequency {
|
||||
Some(StartStopSignal::StartSingle(freq, _, _)) => {
|
||||
if let Err(e) = log_tx_clone.send(LoggingSignal::SingleImpedance(SystemTime::now(), freq, val.magnitude, val.phase)).await {
|
||||
if let Err(e) = log_tx_clone.try_send(LoggingSignal::SingleImpedance(SystemTime::now(), freq, val.magnitude, val.phase)) {
|
||||
error!("Failed to send logging signal: {:?}", e);
|
||||
}
|
||||
},
|
||||
@@ -131,7 +132,7 @@ pub async fn communicate_with_hardware(
|
||||
let data_counter_clone_sweep = data_counter_clone.clone();
|
||||
|
||||
// Clone log_tx for the task
|
||||
let gui_logging_enabled_clone = gui_logging_enabled.clone();
|
||||
let gui_logging_state_clone = gui_logging_state.clone();
|
||||
let log_tx_clone = log_tx.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
@@ -147,7 +148,7 @@ pub async fn communicate_with_hardware(
|
||||
bode_plot.update_magnitudes(MeasurementPointSet::Eight, magnitudes.clone());
|
||||
bode_plot.update_phases(MeasurementPointSet::Eight, phases.clone());
|
||||
}
|
||||
if gui_logging_enabled_clone.load(Ordering::Relaxed) {
|
||||
if *gui_logging_state_clone.lock().unwrap() == LoggingStates::Logging {
|
||||
if let Err(e) = log_tx_clone.send(LoggingSignal::SweepImpedance(SystemTime::now(), MeasurementPointSet::Eight.values().to_vec(), magnitudes.clone(), phases.clone())).await {
|
||||
error!("Failed to send logging signal: {:?}", e);
|
||||
}
|
||||
@@ -161,7 +162,7 @@ pub async fn communicate_with_hardware(
|
||||
bode_plot.update_magnitudes(MeasurementPointSet::Eighteen, magnitudes.clone());
|
||||
bode_plot.update_phases(MeasurementPointSet::Eighteen, phases.clone());
|
||||
}
|
||||
if gui_logging_enabled_clone.load(Ordering::Relaxed) {
|
||||
if *gui_logging_state_clone.lock().unwrap() == LoggingStates::Logging {
|
||||
if let Err(e) = log_tx_clone.send(LoggingSignal::SweepImpedance(SystemTime::now(), MeasurementPointSet::Eighteen.values().to_vec(), magnitudes.clone(), phases.clone())).await {
|
||||
error!("Failed to send logging signal: {:?}", e);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,27 @@
|
||||
use log::info;
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
use tokio::fs::File;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use std::path::Path;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use rfd::AsyncFileDialog;
|
||||
|
||||
use crate::signals::LoggingSignal;
|
||||
|
||||
pub async fn log_data(mut data: Receiver<LoggingSignal>) {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LoggingStates {
|
||||
Idle,
|
||||
Starting,
|
||||
Logging,
|
||||
}
|
||||
|
||||
pub async fn log_data(
|
||||
mut data: Receiver<LoggingSignal>,
|
||||
gui_logging_state: Arc<Mutex<LoggingStates>>,
|
||||
) {
|
||||
let mut file: Option<File> = None;
|
||||
|
||||
loop {
|
||||
@@ -38,36 +51,64 @@ pub async fn log_data(mut data: Receiver<LoggingSignal>) {
|
||||
}
|
||||
}
|
||||
LoggingSignal::StartFileLogging(filename) => {
|
||||
let path = Path::new(&filename);
|
||||
let base = path.file_stem().and_then(|s| s.to_str()).unwrap_or("log");
|
||||
let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");
|
||||
// Update global logging state
|
||||
*gui_logging_state.lock().unwrap() = LoggingStates::Starting;
|
||||
|
||||
// Open a folder picker for the user
|
||||
let folder = match AsyncFileDialog::new()
|
||||
.set_title("Select Folder for Logs")
|
||||
.pick_folder()
|
||||
.await {
|
||||
Some(f) => f,
|
||||
None => {
|
||||
info!("File logging cancelled by user");
|
||||
*gui_logging_state.lock().unwrap() = LoggingStates::Idle;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let log_dir = folder.path();
|
||||
|
||||
// Ensure the directory exists
|
||||
std::fs::create_dir_all(&log_dir).ok();
|
||||
|
||||
// Build initial file path
|
||||
let mut path = log_dir.join(&filename);
|
||||
let base = path.file_stem().and_then(|s| s.to_str()).unwrap_or("log").to_string();
|
||||
let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("").to_string();
|
||||
|
||||
// Avoid overwriting existing files
|
||||
let mut counter = 0;
|
||||
let mut new_filename = filename.clone();
|
||||
while Path::new(&new_filename).exists() {
|
||||
while path.exists() {
|
||||
counter += 1;
|
||||
new_filename = if ext.is_empty() {
|
||||
format!("{}_{}", base, counter)
|
||||
path = if ext.is_empty() {
|
||||
log_dir.join(format!("{}_{}", base, counter))
|
||||
} else {
|
||||
format!("{}_{}.{}", base, counter, ext)
|
||||
log_dir.join(format!("{}_{}.{}", base, counter, ext))
|
||||
};
|
||||
}
|
||||
|
||||
match File::create(&new_filename).await {
|
||||
// Create the file asynchronously
|
||||
match File::create(&path).await {
|
||||
Ok(f) => {
|
||||
info!("Started file logging to: {}", new_filename);
|
||||
info!("Started file logging to: {}", path.display());
|
||||
file = Some(f);
|
||||
}
|
||||
Err(e) => {
|
||||
info!("Failed to create log file '{}': {}", new_filename, e);
|
||||
info!("Failed to create log file '{}': {}", path.display(), e);
|
||||
}
|
||||
}
|
||||
|
||||
// Update global logging state
|
||||
*gui_logging_state.lock().unwrap() = LoggingStates::Logging;
|
||||
}
|
||||
LoggingSignal::StopFileLogging => {
|
||||
if file.is_some() {
|
||||
info!("Stopped file logging");
|
||||
file = None;
|
||||
}
|
||||
// Update global logging state
|
||||
*gui_logging_state.lock().unwrap() = LoggingStates::Idle;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user