Added logger to GUI.

This commit is contained in:
2025-10-15 18:11:10 +02:00
parent cb7bc2f025
commit 7229d4cd33
10 changed files with 269 additions and 94 deletions

View File

@@ -1,21 +1,25 @@
use log::info;
use log::{info, error};
use core::f32;
use std::f32::consts::PI;
use std::ops::RangeInclusive;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use chrono::Local;
use atomic_float::AtomicF32;
use tokio::{sync::mpsc::{Sender}};
use eframe::egui::{self, Button, CollapsingHeader, Color32, ComboBox, DragValue, Key, Label, Layout, Modifiers};
use eframe::egui::{self, Button, CollapsingHeader, Color32, ComboBox, DragValue, Id, Key, Label, Layout, Modifiers, 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::plot::{TimeSeriesPlot, BodePlot};
use crate::signals::StartStopSignal;
use crate::signals::{LoggingSignal, StartStopSignal};
use crate::icd::{IcdDftNum, MeasurementPointSet};
@@ -42,6 +46,7 @@ pub struct App {
tree: DockState<String>,
tab_viewer: TabViewer,
run_impedancemeter_tx: Sender<StartStopSignal>,
log_tx: Sender<LoggingSignal>,
pub magnitude: Arc<Mutex<f32>>,
pub phase: Arc<Mutex<f32>>,
pub magnitude_series: Arc<Mutex<TimeSeriesPlot>>,
@@ -55,8 +60,9 @@ pub struct App {
pub dft_num: Arc<Mutex<IcdDftNum>>,
pub measurement_points: Arc<Mutex<MeasurementPointSet>>,
pub periods_per_dft: Arc<Mutex<Option<f32>>>,
pub periods_per_dft_multi: Arc<Mutex<(Vec<f32>, Option<Vec<f32>>)>>,
pub periods_per_dft_multi: Arc<Mutex<(Vec<u32>, Option<Vec<f32>>)>>,
pub gui_logging_enabled: Arc<AtomicBool>,
log_filename: String,
}
struct TabViewer {
@@ -70,7 +76,7 @@ struct TabViewer {
dft_num: Arc<Mutex<IcdDftNum>>,
measurement_points: Arc<Mutex<MeasurementPointSet>>,
periods_per_dft: Arc<Mutex<Option<f32>>>,
periods_per_dft_multi: Arc<Mutex<(Vec<f32>, Option<Vec<f32>>)>>,
periods_per_dft_multi: Arc<Mutex<(Vec<u32>, Option<Vec<f32>>)>>,
show_settings: bool,
show_settings_toggle: Option<bool>,
}
@@ -200,17 +206,17 @@ impl TabViewer {
ui.add_enabled_ui(*on, |ui| {
let (freq, periods_per_dft_vec) = self.periods_per_dft_multi.lock().unwrap().clone();
fn format_frequency(freq: f32) -> String {
if freq >= 1_000.0 {
fn format_frequency(freq: u32) -> String {
if freq >= 1_000 {
// kHz
if freq % 1_000.0 == 0.0 {
format!("{}k", (freq / 1_000.0) as u64)
if freq % 1_000 == 0 {
format!("{}k", (freq / 1_000) as u64)
} else {
format!("{:.1}k", freq / 1_000.0)
format!("{:.1}k", freq / 1_000)
}
} else {
// Hz
if freq % 1.0 == 0.0 {
if freq % 1 == 0 {
format!("{}", freq as u64)
} else {
format!("{:.1}", freq)
@@ -413,7 +419,7 @@ impl egui_dock::TabViewer for TabViewer {
}
impl App {
pub fn new(run_impedancemeter_tx: Sender<StartStopSignal>) -> Self {
pub fn new(run_impedancemeter_tx: Sender<StartStopSignal>, log_tx: Sender<LoggingSignal>) -> Self {
// Step 1: Initialize shared fields first
let magnitude = Arc::new(Mutex::new(0.0));
let phase = Arc::new(Mutex::new(0.0));
@@ -450,6 +456,7 @@ impl App {
tree: DockState::new(vec!["Single".to_string(), "Multi".to_string(), "Shortcuts".to_string()]),
tab_viewer,
run_impedancemeter_tx,
log_tx,
magnitude,
phase,
magnitude_series,
@@ -465,6 +472,7 @@ impl App {
periods_per_dft,
periods_per_dft_multi,
gui_logging_enabled: Arc::new(AtomicBool::new(false)),
log_filename: format!("log_{}.csv", Local::now().format("%Y%m%d"))
};
// For testing purposes, populate the Bode plot with a sample low-pass filter response
@@ -493,17 +501,17 @@ impl App {
match (self.tab_active, *self.on.lock().unwrap()) {
(TabActive::Single, true) => {
if let Err(e) = self.run_impedancemeter_tx.try_send(StartStopSignal::StartSingle(*self.single_frequency.lock().unwrap(), *self.dft_num.lock().unwrap())) {
eprintln!("Failed to send start command: {:?}", e);
error!("Failed to send start command: {:?}", e);
}
},
(TabActive::Multi, true) => {
if let Err(e) = self.run_impedancemeter_tx.try_send(StartStopSignal::StartMulti(*self.measurement_points.lock().unwrap())) {
eprintln!("Failed to send start command: {:?}", e);
error!("Failed to send start command: {:?}", e);
}
},
(_, false) => {
if let Err(e) = self.run_impedancemeter_tx.try_send(StartStopSignal::Stop) {
eprintln!("Failed to send stop command: {:?}", e);
error!("Failed to send stop command: {:?}", e);
}
},
(_, _) => {}
@@ -545,8 +553,24 @@ impl eframe::App for App {
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);
}
}
}
ui.separator();
ui.add_enabled_ui(!gui_logging_enabled, |ui| {
ui.label("Log filename:");
TextEdit::singleline(&mut self.log_filename).desired_width(125.0).id(Id::new("file_name_field")).ui(ui);
});
// Spacer to push the LED to the right
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.scope(|ui| {
@@ -619,40 +643,55 @@ impl eframe::App for App {
{
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
// Check if the file name field is focused
// If it is, we don't want to trigger shortcuts
let file_name_field_is_focused = ctx.memory(|memory| memory.has_focus(Id::new("file_name_field")));
if !file_name_field_is_focused {
// Space to start/stop measurement
if ctx.input(|i| i.key_pressed(Key::Space))
{
let value = *self.on.lock().unwrap();
*self.on.lock().unwrap() = !value;
self.update_start_stop();
}
// Space to start/stop measurement
if ctx.input(|i| i.key_pressed(Key::Space))
{
let value = *self.on.lock().unwrap();
*self.on.lock().unwrap() = !value;
self.update_start_stop();
}
// Send stop command when the window is closed
if ctx.input(|i| i.viewport().close_requested()) {
*self.on.lock().unwrap() = false;
self.update_start_stop();
}
// Send stop command when the window is closed
if ctx.input(|i| i.viewport().close_requested()) {
*self.on.lock().unwrap() = false;
self.update_start_stop();
}
// Reset view
if ctx.input(|i| i.key_pressed(Key::R)) {
self.reset_view();
}
// Reset view
if ctx.input(|i| i.key_pressed(Key::R)) {
self.reset_view();
}
// 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);
}
// 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);
}
}
}
// Toggle setttings view
if ctx.input(|i| i.key_pressed(egui::Key::S)) {
self.tab_viewer.show_settings = !self.tab_viewer.show_settings;
if self.tab_viewer.show_settings {
self.tab_viewer.show_settings_toggle = Some(true);
} else {
self.tab_viewer.show_settings_toggle = Some(false);
// Toggle setttings view
if ctx.input(|i| i.key_pressed(egui::Key::S)) {
self.tab_viewer.show_settings = !self.tab_viewer.show_settings;
if self.tab_viewer.show_settings {
self.tab_viewer.show_settings_toggle = Some(true);
} else {
self.tab_viewer.show_settings_toggle = Some(false);
}
}
}