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);
}
}
}

View File

@@ -9,6 +9,7 @@ use bioz_host_rs::communication::communicate_with_hardware;
use tokio::sync::mpsc::{self};
use bioz_host_rs::signals::StartStopSignal;
use bioz_host_rs::logging::log_data;
#[tokio::main]
async fn main() {
@@ -26,9 +27,10 @@ async fn main() {
let run_impedancemeter_tx_clone = run_impedancemeter_tx.clone();
// Logging
let (log_tx, mut log_rx) = mpsc::channel::<LoggingSignal>(10);
let (log_tx, log_rx) = mpsc::channel::<LoggingSignal>(10);
let log_tx_clone = log_tx.clone();
let app = App::new(run_impedancemeter_tx);
let app = App::new(run_impedancemeter_tx, log_tx);
let magnitude_clone = app.magnitude.clone();
let phase_clone = app.phase.clone();
let magnitude_series_clone = app.magnitude_series.clone();
@@ -43,27 +45,8 @@ async fn main() {
let gui_logging_enabled = app.gui_logging_enabled.clone();
// Log thread
tokio::spawn(async move {
loop {
match log_rx.recv().await {
Some(signal) => {
match signal {
LoggingSignal::SingleImpedance(magnitude, phase) => {
info!("Single Impedance - Magnitude: {:.3}, Phase: {:.3}", magnitude, phase);
}
LoggingSignal::MultiImpedance(magnitudes, phases) => {
info!("Multi Impedance - Magnitudes: {:?}, Phases: {:?}", magnitudes, phases);
}
}
}
None => {
// Channel closed
break;
}
}
}
});
// Log thread
tokio::spawn(async move { log_data(log_rx).await });
// Execute the runtime in its own thread.
std::thread::spawn(move || {
@@ -80,7 +63,7 @@ async fn main() {
periods_per_dft,
periods_per_dft_multi,
gui_logging_enabled,
log_tx,
log_tx_clone,
));
});

View File

@@ -1,7 +1,9 @@
use std::time::SystemTime;
use log::{error, info};
use tokio::select;
use tokio::sync::mpsc::{Sender, Receiver};
use tokio::sync::mpsc::{Receiver, Sender};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use atomic_float::AtomicF32;
@@ -28,7 +30,7 @@ pub async fn communicate_with_hardware(
connected: Arc<AtomicBool>,
data_frequency: Arc<AtomicF32>,
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>>)>>,
gui_logging_enabled: Arc<AtomicBool>,
log_tx: Sender<LoggingSignal>,
) {
@@ -42,17 +44,17 @@ pub async fn communicate_with_hardware(
}
});
#[derive(Default)]
#[derive(Default, Clone, Copy)]
struct Settings {
frequency: Option<StartStopSignal>,
}
let mut settings = Settings::default();
let settings = Arc::new(Mutex::new(Settings::default()));
loop {
let workbook_client = match WorkbookClient::new() {
Ok(client) => {
info!("Connected to hardware successfully.");
if let Some(frequency) = settings.frequency {
if let Some(frequency) = settings.lock().unwrap().frequency {
run_impedancemeter_tx.send(frequency).await.unwrap();
}
connected.store(true, Ordering::Relaxed);
@@ -79,6 +81,8 @@ pub async fn communicate_with_hardware(
let gui_logging_enabled_clone = gui_logging_enabled.clone();
let log_tx_clone = log_tx.clone();
let settings_clone = settings.clone();
tokio::spawn(async move {
while let Ok(val) = single_impedance_sub.recv().await {
{
@@ -97,9 +101,20 @@ pub async fn communicate_with_hardware(
}
// Send logging signal
if gui_logging_enabled_clone.load(Ordering::Relaxed) {
if let Err(e) = log_tx_clone.try_send(LoggingSignal::SingleImpedance(val.magnitude, val.phase)) {
error!("Failed to send logging signal: {:?}", e);
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 {
error!("Failed to send logging signal: {:?}", e);
}
},
_ => {
error!("Frequency not set for single impedance logging.");
},
}
// if let Err(e) = log_tx_clone.send(LoggingSignal::SingleImpedance(SystemTime::now(), settings.frequency, val.magnitude, val.phase)).await {
// error!("Failed to send logging signal: {:?}", e);
// }
}
}
info!("SingleImpedanceOutputTopic subscription ended.");
@@ -133,7 +148,7 @@ pub async fn communicate_with_hardware(
bode_plot.update_phases(MeasurementPointSet::Eight, phases.clone());
}
if gui_logging_enabled_clone.load(Ordering::Relaxed) {
if let Err(e) = log_tx_clone.try_send(LoggingSignal::MultiImpedance(magnitudes.clone(), phases.clone())) {
if let Err(e) = log_tx_clone.send(LoggingSignal::MultiImpedance(SystemTime::now(), MeasurementPointSet::Eight.values().to_vec(), magnitudes.clone(), phases.clone())).await {
error!("Failed to send logging signal: {:?}", e);
}
}
@@ -147,7 +162,7 @@ pub async fn communicate_with_hardware(
bode_plot.update_phases(MeasurementPointSet::Eighteen, phases.clone());
}
if gui_logging_enabled_clone.load(Ordering::Relaxed) {
if let Err(e) = log_tx_clone.try_send(LoggingSignal::MultiImpedance(magnitudes.clone(), phases.clone())) {
if let Err(e) = log_tx_clone.send(LoggingSignal::MultiImpedance(SystemTime::now(), MeasurementPointSet::Eighteen.values().to_vec(), magnitudes.clone(), phases.clone())).await {
error!("Failed to send logging signal: {:?}", e);
}
}
@@ -166,7 +181,7 @@ pub async fn communicate_with_hardware(
match workbook_client.start_impedancemeter_single(freq, dft_num).await {
Ok(Ok(periods)) => {
info!("Impedance meter started at frequency: {} with periods per DFT: {}", freq, periods);
settings.frequency = Some(StartStopSignal::StartSingle(freq, dft_num));
settings.lock().unwrap().frequency = Some(StartStopSignal::StartSingle(freq, dft_num));
*periods_per_dft.lock().unwrap() = Some(periods);
},
Ok(Err(e)) => {
@@ -182,7 +197,7 @@ pub async fn communicate_with_hardware(
StartStopSignal::StartMulti(num_points) => {
match workbook_client.start_impedancemeter_multi(num_points).await {
Ok(Ok(periods)) => {
settings.frequency = Some(StartStopSignal::StartMulti(num_points));
settings.lock().unwrap().frequency = Some(StartStopSignal::StartMulti(num_points));
info!("Multi-point Impedancemeter started.");
match num_points {
MeasurementPointSet::Eight => {
@@ -207,7 +222,7 @@ pub async fn communicate_with_hardware(
if let Err(e) = workbook_client.stop_impedancemeter().await {
error!("Failed to stop impedancemeter: {:?}", e);
} else {
settings.frequency = Some(StartStopSignal::Stop);
settings.lock().unwrap().frequency = Some(StartStopSignal::Stop);
*periods_per_dft.lock().unwrap() = None;
let (freq, _) = periods_per_dft_multi.lock().unwrap().clone();
*periods_per_dft_multi.lock().unwrap() = (freq, None);

View File

@@ -5,6 +5,7 @@ pub mod app;
pub mod communication;
pub mod plot;
pub mod signals;
pub mod logging;
pub use bioz_icd_rs as icd;
pub async fn read_line() -> String {

77
src/logging.rs Normal file
View File

@@ -0,0 +1,77 @@
use log::info;
use tokio::sync::mpsc::Receiver;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
use std::path::Path;
use std::time::UNIX_EPOCH;
use crate::signals::LoggingSignal;
pub async fn log_data(mut data: Receiver<LoggingSignal>) {
let mut file: Option<File> = None;
loop {
match data.recv().await {
Some(signal) => {
match signal {
LoggingSignal::SingleImpedance(timestamp, frequency, magnitude, phase) => {
if let Some(f) = file.as_mut() {
let _ = f
.write_all(format!("{},{},{:.3},{:.3}\n", timestamp.duration_since(UNIX_EPOCH).unwrap().as_millis(), frequency, magnitude, phase).as_bytes())
.await;
}
}
LoggingSignal::MultiImpedance(timestamp, frequencies, magnitudes, phases) => {
if let Some(f) = file.as_mut() {
for i in 0..frequencies.len() {
let _ = f.write_all(
format!("{},{},{},{},{}\n",
timestamp.duration_since(UNIX_EPOCH).unwrap().as_millis(),
frequencies[i],
magnitudes[i],
phases[i],
i // optional index
).as_bytes()
).await;
}
}
}
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("");
let mut counter = 0;
let mut new_filename = filename.clone();
while Path::new(&new_filename).exists() {
counter += 1;
new_filename = if ext.is_empty() {
format!("{}_{}", base, counter)
} else {
format!("{}_{}.{}", base, counter, ext)
};
}
match File::create(&new_filename).await {
Ok(f) => {
info!("Started file logging to: {}", new_filename);
file = Some(f);
}
Err(e) => {
info!("Failed to create log file '{}': {}", new_filename, e);
}
}
}
LoggingSignal::StopFileLogging => {
if file.is_some() {
info!("Stopped file logging");
file = None;
}
}
}
}
None => break, // Channel closed
}
}
}

View File

@@ -66,12 +66,12 @@ impl BodePlot {
pub fn update_magnitudes(&mut self, points: MeasurementPointSet, magnitudes: Vec<f32>) {
let freqs = points.values().to_vec();
// self.magnitudes = freqs.into_iter().zip(magnitudes.into_iter()).map(|(f, m)| PlotPoint::new(f.log10(), 20.0 * m.log10() as f32)).collect();
self.magnitudes = freqs.into_iter().zip(magnitudes.into_iter()).map(|(f, m)| PlotPoint::new(f.log10(), m as f32)).collect();
self.magnitudes = freqs.into_iter().zip(magnitudes.into_iter()).map(|(f, m)| PlotPoint::new((f as f32).log10(), m)).collect(); // Convert to f32 first due to rouding errors
}
pub fn update_phases(&mut self, points: MeasurementPointSet, phases: Vec<f32>) {
let freqs = points.values().to_vec();
self.phases = freqs.into_iter().zip(phases.into_iter()).map(|(f, p)| PlotPoint::new(f.log10(), p as f64)).collect();
self.phases = freqs.into_iter().zip(phases.into_iter()).map(|(f, p)| PlotPoint::new((f as f32).log10(), p)).collect(); // Convert to f32 first due to rouding errors
}
pub fn plot_magnitudes(&self) -> PlotPoints {

View File

@@ -1,6 +1,8 @@
use std::time::SystemTime;
use crate::icd::{IcdDftNum, MeasurementPointSet};
#[derive(Copy, Clone)]
#[derive(Copy, Clone, Debug)]
pub enum StartStopSignal {
StartSingle(u32, IcdDftNum), // frequency in Hz, DFT number
StartMulti(MeasurementPointSet), // DFT number, number of points per measurement
@@ -8,6 +10,8 @@ pub enum StartStopSignal {
}
pub enum LoggingSignal {
SingleImpedance(f32, f32), // magnitude, phase
MultiImpedance(Vec<f32>, Vec<f32>), // magnitude, phase
SingleImpedance(SystemTime, u32, f32, f32), // frequency, magnitude, phase
MultiImpedance(SystemTime, Vec<u32>, Vec<f32>, Vec<f32>), // frequency, magnitude, phase
StartFileLogging(String), // e.g. filename
StopFileLogging,
}