mirror of
https://github.com/hubaldv/bioz-host-rs.git
synced 2026-03-09 22:10:31 +00:00
922 lines
38 KiB
Rust
922 lines
38 KiB
Rust
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, Id, Key, Label, Layout, Modal, 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};
|
|
|
|
use crate::icd::{BioImpedanceLeadMode, IcdDftNum, MeasurementPointSet};
|
|
|
|
const LEAD_MODES: [BioImpedanceLeadMode; 2] = [
|
|
BioImpedanceLeadMode::TwoLead,
|
|
BioImpedanceLeadMode::FourLead,
|
|
];
|
|
|
|
const DFTNUM_VARIANTS: [IcdDftNum; 13] = [
|
|
IcdDftNum::Num4, IcdDftNum::Num8, IcdDftNum::Num16, IcdDftNum::Num32,
|
|
IcdDftNum::Num64, IcdDftNum::Num128, IcdDftNum::Num256, IcdDftNum::Num512,
|
|
IcdDftNum::Num1024, IcdDftNum::Num2048, IcdDftNum::Num4096,
|
|
IcdDftNum::Num8192, IcdDftNum::Num16384,
|
|
];
|
|
|
|
const MEASUREMENT_POINTS_VARIANTS: [MeasurementPointSet; 2] = [
|
|
MeasurementPointSet::Eight,
|
|
MeasurementPointSet::Eighteen,
|
|
];
|
|
|
|
#[derive(Clone, Copy,Debug, PartialEq, Eq)]
|
|
enum TabActive {
|
|
Single,
|
|
Sweep,
|
|
Shortcuts,
|
|
}
|
|
|
|
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>>,
|
|
pub phase_series: Arc<Mutex<TimeSeriesPlot>>,
|
|
pub bode_plot: Arc<Mutex<BodePlot>>,
|
|
pub connected: Arc<AtomicBool>,
|
|
pub on: Arc<Mutex<bool>>,
|
|
tab_active: TabActive,
|
|
pub data_frequency: Arc<AtomicF32>,
|
|
pub single_frequency: Arc<Mutex<u32>>,
|
|
pub lead_mode: Arc<Mutex<BioImpedanceLeadMode>>,
|
|
pub dft_num: Arc<Mutex<IcdDftNum>>,
|
|
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_state: Arc<Mutex<LoggingStates>>,
|
|
log_filename: String,
|
|
log_marker_modal: bool,
|
|
log_marker: String,
|
|
}
|
|
|
|
struct TabViewer {
|
|
magnitude: Arc<Mutex<f32>>,
|
|
phase: Arc<Mutex<f32>>,
|
|
magnitude_series: Arc<Mutex<TimeSeriesPlot>>,
|
|
phase_series: Arc<Mutex<TimeSeriesPlot>>,
|
|
bode_plot: Arc<Mutex<BodePlot>>,
|
|
on: Arc<Mutex<bool>>,
|
|
single_frequency: Arc<Mutex<u32>>,
|
|
lead_mode: Arc<Mutex<BioImpedanceLeadMode>>,
|
|
dft_num: Arc<Mutex<IcdDftNum>>,
|
|
measurement_points: Arc<Mutex<MeasurementPointSet>>,
|
|
periods_per_dft: Arc<Mutex<Option<f32>>>,
|
|
periods_per_dft_sweep: Arc<Mutex<(Vec<u32>, Option<Vec<f32>>)>>,
|
|
show_settings: bool,
|
|
show_settings_toggle: Option<bool>,
|
|
}
|
|
|
|
impl TabViewer {
|
|
fn single_tab(&mut self, ui: &mut egui::Ui) {
|
|
egui::Frame::default().inner_margin(5).show(ui, |ui| {
|
|
let settings = CollapsingHeader::new("Settings")
|
|
.open(self.show_settings_toggle)
|
|
.show(ui, |ui| {
|
|
if let Ok(on) = self.on.lock() {
|
|
ui.add_enabled_ui(!*on, |ui| {
|
|
ui.horizontal(|ui| {
|
|
ui.label("Lead Mode:");
|
|
|
|
let mut lead_mode = self.lead_mode.lock().unwrap();
|
|
|
|
// Map current lead mode to index
|
|
let mut index = LEAD_MODES
|
|
.iter()
|
|
.position(|&m| m == *lead_mode)
|
|
.unwrap_or(0);
|
|
|
|
ComboBox::from_id_salt("LeadMode")
|
|
.width(60.0)
|
|
.show_index(ui, &mut index, LEAD_MODES.len(), |i| {
|
|
match LEAD_MODES[i] {
|
|
BioImpedanceLeadMode::TwoLead => "2-Lead",
|
|
BioImpedanceLeadMode::FourLead => "4-Lead",
|
|
}
|
|
.to_string()
|
|
});
|
|
|
|
// Update lead mode if changed
|
|
if *lead_mode != LEAD_MODES[index] {
|
|
*lead_mode = LEAD_MODES[index];
|
|
info!("Lead Mode setting changed!");
|
|
}
|
|
|
|
// Show lead configuration
|
|
match *lead_mode {
|
|
BioImpedanceLeadMode::TwoLead => ui.label("Drive/sense: Electrode+ (CE0), Electrode- (AIN1)"),
|
|
BioImpedanceLeadMode::FourLead => ui.label("Drive: I+ (CE0), I- (AIN1) | Sense: V+ (AIN2), V- (AIN3)"),
|
|
}
|
|
});
|
|
});
|
|
ui.add_enabled_ui(!*on, |ui| {
|
|
ui.horizontal(|ui| {
|
|
ui.label("Single Frequency:");
|
|
if let Ok(mut freq) = self.single_frequency.lock() {
|
|
ui.add(DragValue::new(&mut *freq).speed(0.1));
|
|
}
|
|
ui.label("Hz");
|
|
});
|
|
ui.horizontal(|ui| {
|
|
ui.label("ADC samples per DFT:");
|
|
let mut dft_num = self.dft_num.lock().unwrap();
|
|
let mut index = DFTNUM_VARIANTS.iter().position(|&x| x == *dft_num).unwrap_or(0);
|
|
ComboBox::from_id_salt("Dftnum")
|
|
.width(75.0)
|
|
.show_index(ui, &mut index, DFTNUM_VARIANTS.len(), |i| {
|
|
format!("{}", 1 << (2 + i)) // 2^2 = 4, 2^3 = 8, ..., 2^14 = 16384
|
|
});
|
|
let new_value = DFTNUM_VARIANTS[index];
|
|
if *dft_num != new_value {
|
|
*dft_num = new_value;
|
|
info!("DFTNUM setting changed!");
|
|
};
|
|
});
|
|
});
|
|
ui.add_enabled_ui(*on, |ui| {
|
|
ui.horizontal(|ui| {
|
|
ui.label("Periods per DFT:");
|
|
match (*on, *self.periods_per_dft.lock().unwrap()) {
|
|
(true, Some(periods)) => {
|
|
ui.add(Label::new(format!("{:.2}", periods)));
|
|
},
|
|
(true, None) => {
|
|
ui.add(Label::new("N/A"));
|
|
},
|
|
(false, _) => {
|
|
ui.add(Label::new("Start to determine!"));
|
|
}
|
|
}
|
|
});
|
|
});
|
|
}
|
|
});
|
|
|
|
self.show_settings_toggle = None;
|
|
self.show_settings = !settings.fully_closed();
|
|
|
|
ui.separator();
|
|
|
|
let available_height = ui.available_height();
|
|
let half_height = available_height / 2.0-2.0;
|
|
|
|
// Plot magnitude
|
|
ui.allocate_ui_with_layout(
|
|
egui::vec2(ui.available_width(), half_height),
|
|
Layout::top_down(egui::Align::Min),
|
|
|ui| {
|
|
// Magnitude
|
|
let magnitude = self.magnitude_series.lock().unwrap();
|
|
Plot::new("magnitude")
|
|
.legend(Legend::default().position(Corner::LeftTop))
|
|
.y_axis_label("Magnitude [Ω]")
|
|
.y_axis_min_width(80.0)
|
|
.show(ui, |plot_ui| {
|
|
plot_ui.line(
|
|
Line::new(format!("Magnitude at {} Hz", self.single_frequency.lock().unwrap()), magnitude.plot_values())
|
|
.color(Color32::BLUE)
|
|
);
|
|
});
|
|
},
|
|
);
|
|
// Plot phase
|
|
ui.allocate_ui_with_layout(
|
|
egui::vec2(ui.available_width(), half_height),
|
|
Layout::top_down(egui::Align::Min),
|
|
|ui| {
|
|
// Phase
|
|
let phase = self.phase_series.lock().unwrap();
|
|
Plot::new("phase")
|
|
.legend(Legend::default().position(Corner::LeftTop))
|
|
.y_axis_label("Phase [rad]")
|
|
.y_axis_min_width(80.0)
|
|
.show(ui, |plot_ui| {
|
|
plot_ui.line(
|
|
Line::new(format!("Phase at {} Hz", self.single_frequency.lock().unwrap()), phase.plot_values())
|
|
.color(Color32::RED)
|
|
);
|
|
});
|
|
},
|
|
);
|
|
});
|
|
}
|
|
|
|
|
|
fn sweep_tab(&mut self, ui: &mut egui::Ui) {
|
|
egui::Frame::default().inner_margin(5).show(ui, |ui| {
|
|
let settings = CollapsingHeader::new("Settings")
|
|
.open(self.show_settings_toggle)
|
|
.show(ui, |ui| {
|
|
if let Ok(on) = self.on.lock() {
|
|
ui.add_enabled_ui(!*on, |ui| {
|
|
ui.horizontal(|ui| {
|
|
ui.label("Lead Mode:");
|
|
|
|
let mut lead_mode = self.lead_mode.lock().unwrap();
|
|
|
|
// Map current lead mode to index
|
|
let mut index = LEAD_MODES
|
|
.iter()
|
|
.position(|&m| m == *lead_mode)
|
|
.unwrap_or(0);
|
|
|
|
ComboBox::from_id_salt("LeadMode")
|
|
.width(60.0)
|
|
.show_index(ui, &mut index, LEAD_MODES.len(), |i| {
|
|
match LEAD_MODES[i] {
|
|
BioImpedanceLeadMode::TwoLead => "2-Lead",
|
|
BioImpedanceLeadMode::FourLead => "4-Lead",
|
|
}
|
|
.to_string()
|
|
});
|
|
|
|
// Update lead mode if changed
|
|
if *lead_mode != LEAD_MODES[index] {
|
|
*lead_mode = LEAD_MODES[index];
|
|
info!("Lead Mode setting changed!");
|
|
}
|
|
|
|
// Show lead configuration
|
|
match *lead_mode {
|
|
BioImpedanceLeadMode::TwoLead => ui.label("Drive/sense: Electrode+ (CE0), Electrode- (AIN1)"),
|
|
BioImpedanceLeadMode::FourLead => ui.label("Drive: I+ (CE0), I- (AIN1) | Sense: V+ (AIN2), V- (AIN3)"),
|
|
}
|
|
});
|
|
});
|
|
ui.add_enabled_ui(!*on, |ui| {
|
|
ui.horizontal(|ui| {
|
|
ui.label("Measurement Points:");
|
|
let mut measurement_points = self.measurement_points.lock().unwrap();
|
|
let mut index = MEASUREMENT_POINTS_VARIANTS.iter().position(|&x| x == *measurement_points).unwrap_or(0);
|
|
ComboBox::from_id_salt("MeasurementPoints")
|
|
.width(75.0)
|
|
.show_index(ui, &mut index, MEASUREMENT_POINTS_VARIANTS.len(), |i| {
|
|
format!("{:?}", MEASUREMENT_POINTS_VARIANTS[i].len())
|
|
});
|
|
let new_value = MEASUREMENT_POINTS_VARIANTS[index];
|
|
if *measurement_points != new_value {
|
|
*measurement_points = new_value;
|
|
info!("Measurement Points setting changed!");
|
|
}
|
|
});
|
|
});
|
|
ui.add_enabled_ui(*on, |ui| {
|
|
let (freq, periods_per_dft_vec) = self.periods_per_dft_sweep.lock().unwrap().clone();
|
|
|
|
fn format_frequency(freq: u32) -> String {
|
|
if freq >= 1_000 {
|
|
// kHz
|
|
if freq % 1_000 == 0 {
|
|
format!("{}k", (freq / 1_000) as u64)
|
|
} else {
|
|
format!("{:.1}k", freq as f32 / 1_000.0)
|
|
}
|
|
} else {
|
|
// Hz
|
|
if freq % 1 == 0 {
|
|
format!("{}", freq as u64)
|
|
} else {
|
|
format!("{:.1}", freq)
|
|
}
|
|
}
|
|
}
|
|
|
|
TableBuilder::new(ui)
|
|
.column(Column::auto())
|
|
.columns(Column::remainder().at_most(30.0), freq.len())
|
|
.header(10.0, |mut header| {
|
|
header.col(|ui| {
|
|
ui.label("Frequency [Hz]:");
|
|
});
|
|
for freq in &freq {
|
|
header.col(|ui| {
|
|
ui.label(format_frequency(*freq));
|
|
});
|
|
}
|
|
})
|
|
.body(|mut body| {
|
|
body.row(5.0, |mut row| {
|
|
row.col(|ui| {
|
|
ui.label("Periods per DFT:");
|
|
});
|
|
if let Some(periods) = periods_per_dft_vec {
|
|
for period in &periods {
|
|
row.col(|ui| {
|
|
ui.label(format!("{:.1}", period));
|
|
});
|
|
}
|
|
} else {
|
|
for _ in &freq {
|
|
row.col(|ui| {
|
|
ui.label("N/A");
|
|
});
|
|
}
|
|
}
|
|
});
|
|
});
|
|
});
|
|
}
|
|
});
|
|
|
|
self.show_settings_toggle = None;
|
|
self.show_settings = !settings.fully_closed();
|
|
|
|
ui.separator();
|
|
|
|
let available_height = ui.available_height();
|
|
let half_height = available_height / 2.0-2.0;
|
|
|
|
// Bodeplot magnitude
|
|
ui.allocate_ui_with_layout(
|
|
egui::vec2(ui.available_width(), half_height),
|
|
Layout::top_down(egui::Align::Min),
|
|
|ui| {
|
|
// Magnitude
|
|
let bode_plot = self.bode_plot.lock().unwrap();
|
|
Plot::new("bode_mag")
|
|
.legend(Legend::default().position(Corner::LeftTop))
|
|
.y_axis_label("Magnitude [Ω]")
|
|
.x_grid_spacer(log10_grid_spacer)
|
|
.x_axis_formatter(log10_axis_formatter)
|
|
// .auto_bounds([true; 2].into())
|
|
.y_axis_min_width(80.0)
|
|
.default_x_bounds(0.0, 200_000_f64.log10())
|
|
.label_formatter(log10x_formatter)
|
|
.show(ui, |plot_ui| {
|
|
plot_ui.line(
|
|
Line::new("Magnitude", bode_plot.plot_magnitudes())
|
|
.color(Color32::LIGHT_BLUE)
|
|
);
|
|
plot_ui.points(
|
|
Points::new("Magnitude measurement", bode_plot.plot_magnitudes())
|
|
.color(Color32::BLUE)
|
|
.radius(1.5)
|
|
);
|
|
});
|
|
},
|
|
);
|
|
|
|
// Bodeplot phase
|
|
ui.allocate_ui_with_layout(
|
|
egui::vec2(ui.available_width(), half_height),
|
|
Layout::top_down(egui::Align::Min),
|
|
|ui| {
|
|
// Phase
|
|
let bode_plot = self.bode_plot.lock().unwrap();
|
|
Plot::new("bode_phase")
|
|
.legend(Legend::default().position(Corner::LeftTop))
|
|
.y_axis_label("Phase [rad]")
|
|
.x_grid_spacer(log10_grid_spacer)
|
|
.x_axis_formatter(log10_axis_formatter)
|
|
// .auto_bounds([true; 2].into())
|
|
.y_axis_min_width(80.0)
|
|
.default_x_bounds(0.0, 200_000_f64.log10())
|
|
.label_formatter(log10x_formatter)
|
|
.show(ui, |plot_ui| {
|
|
plot_ui.line(
|
|
Line::new("Phase", bode_plot.plot_phases())
|
|
.color(Color32::LIGHT_RED)
|
|
);
|
|
plot_ui.points(
|
|
Points::new("Phase measurement", bode_plot.plot_phases())
|
|
.color(Color32::RED)
|
|
.radius(1.5)
|
|
);
|
|
});
|
|
},
|
|
);
|
|
});
|
|
}
|
|
|
|
fn shortcuts(&mut self, ui: &mut egui::Ui) {
|
|
ui.heading("Shortcuts");
|
|
ui.label("Space: Start/Stop measurement");
|
|
ui.label("R: Reset view/plots");
|
|
ui.label("S: Toggle settings");
|
|
ui.label("L: Toggle logging");
|
|
ui.label("A: Add marker (when logging)");
|
|
ui.label("CMD-W: Close window");
|
|
}
|
|
}
|
|
|
|
fn log10_grid_spacer(input: GridInput) -> Vec<GridMark> {
|
|
let base = 10u32;
|
|
assert!(base >= 2);
|
|
let basef = base as f64;
|
|
|
|
let step_size = basef.powi(input.base_step_size.abs().log(basef).ceil() as i32);
|
|
let (min, max) = input.bounds;
|
|
let mut steps = vec![];
|
|
|
|
for step_size in [step_size, step_size * basef, step_size * basef * basef] {
|
|
if step_size == basef.powi(-1) {
|
|
// FIXME: float comparison
|
|
let first = ((min / (step_size * basef)).floor() as i64) * base as i64;
|
|
let last = (max / step_size).ceil() as i64;
|
|
|
|
let mut logs = vec![0.0; base as usize - 2];
|
|
for (i, j) in logs.iter_mut().enumerate() {
|
|
*j = basef * ((i + 2) as f64).log(basef);
|
|
}
|
|
|
|
steps.extend((first..last).step_by(base as usize).flat_map(|j| {
|
|
logs.iter().map(move |i| GridMark {
|
|
value: (j as f64 + i) * step_size,
|
|
step_size,
|
|
})
|
|
}));
|
|
} else {
|
|
let first = (min / step_size).ceil() as i64;
|
|
let last = (max / step_size).ceil() as i64;
|
|
|
|
steps.extend((first..last).map(move |i| GridMark {
|
|
value: (i as f64) * step_size,
|
|
step_size,
|
|
}));
|
|
}
|
|
}
|
|
steps
|
|
}
|
|
|
|
fn log10_axis_formatter(mark: GridMark, _range: &RangeInclusive<f64>) -> String {
|
|
let base = 10u32;
|
|
let basef = base as f64;
|
|
let prec = (-mark.step_size.log10().round()).max(0.0) as usize;
|
|
format!("{:.*e}", prec, basef.powf(mark.value))
|
|
}
|
|
|
|
fn log10x_formatter(name: &str, value: &PlotPoint) -> String {
|
|
let base = 10u32;
|
|
let basef = base as f64;
|
|
format!(
|
|
"{}\nx: {:.d$e}\ny: {:.d$e}",
|
|
name,
|
|
basef.powf(value.x),
|
|
value.y,
|
|
d = 3
|
|
)
|
|
}
|
|
|
|
impl egui_dock::TabViewer for TabViewer {
|
|
type Tab = String;
|
|
|
|
fn title(&mut self, tab: &mut Self::Tab) -> eframe::egui::WidgetText {
|
|
(&*tab).into()
|
|
}
|
|
|
|
fn ui(&mut self, ui: &mut egui::Ui, tab: &mut Self::Tab) {
|
|
match tab.as_str() {
|
|
"Single" => self.single_tab(ui),
|
|
"Sweep" => self.sweep_tab(ui),
|
|
"Shortcuts" => self.shortcuts(ui),
|
|
_ => {
|
|
let _ = ui.label("Unknown tab");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
impl App {
|
|
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));
|
|
let magnitude_series = Arc::new(Mutex::new(TimeSeriesPlot::new()));
|
|
let phase_series = Arc::new(Mutex::new(TimeSeriesPlot::new()));
|
|
let bode_plot = Arc::new(Mutex::new(BodePlot::new()));
|
|
let single_frequency = Arc::new(Mutex::new(50000));
|
|
let lead_mode = Arc::new(Mutex::new(BioImpedanceLeadMode::FourLead));
|
|
let dft_num = Arc::new(Mutex::new(IcdDftNum::Num2048));
|
|
let measurement_points = Arc::new(Mutex::new(MeasurementPointSet::Eighteen));
|
|
let periods_per_dft = Arc::new(Mutex::new(None));
|
|
let periods_per_dft_sweep = Arc::new(Mutex::new((MeasurementPointSet::Eighteen.values().to_vec(), None)));
|
|
let on = Arc::new(Mutex::new(true));
|
|
let tab_active = TabActive::Single;
|
|
|
|
// Step 2: Now we can initialize tab_viewer
|
|
let tab_viewer = TabViewer {
|
|
magnitude: magnitude.clone(),
|
|
phase: phase.clone(),
|
|
magnitude_series: magnitude_series.clone(),
|
|
phase_series: phase_series.clone(),
|
|
bode_plot: bode_plot.clone(),
|
|
single_frequency: single_frequency.clone(),
|
|
lead_mode: lead_mode.clone(),
|
|
dft_num: dft_num.clone(),
|
|
measurement_points: measurement_points.clone(),
|
|
periods_per_dft: periods_per_dft.clone(),
|
|
periods_per_dft_sweep: periods_per_dft_sweep.clone(),
|
|
on: on.clone(),
|
|
show_settings: false,
|
|
show_settings_toggle: None,
|
|
};
|
|
|
|
// Step 3: Construct App
|
|
let app = App {
|
|
tree: DockState::new(vec!["Single".to_string(), "Sweep".to_string(), "Shortcuts".to_string()]),
|
|
tab_viewer,
|
|
run_impedancemeter_tx,
|
|
log_tx,
|
|
magnitude,
|
|
phase,
|
|
magnitude_series,
|
|
phase_series,
|
|
bode_plot,
|
|
connected: Arc::new(AtomicBool::new(false)),
|
|
on,
|
|
tab_active,
|
|
data_frequency: Arc::new(AtomicF32::new(0.0)),
|
|
single_frequency,
|
|
lead_mode,
|
|
dft_num,
|
|
measurement_points,
|
|
periods_per_dft,
|
|
periods_per_dft_sweep,
|
|
gui_logging_state: Arc::new(Mutex::new(LoggingStates::Idle)),
|
|
log_filename: format!("log_{}_single.csv", Local::now().format("%Y%m%d")),
|
|
log_marker_modal: false,
|
|
log_marker: String::new(),
|
|
};
|
|
|
|
// For testing purposes, populate the Bode plot with a sample low-pass filter response
|
|
// let fc = 1000.0; // cutoff frequency in Hz
|
|
|
|
// let freqs = MeasurementPointSet::Eighteen.values().to_vec();
|
|
// let magnitudes = freqs.iter()
|
|
// .map(|&f| {
|
|
// 1.0 / (1.0 + (f / fc).powi(2)).sqrt()
|
|
// })
|
|
// .collect::<Vec<f32>>();
|
|
// let phases = freqs.iter()
|
|
// .map(|&f| {
|
|
// -(f / fc).atan() * 180.0 / PI
|
|
// })
|
|
// .collect::<Vec<f32>>();
|
|
|
|
// app.bode_plot.lock().unwrap().update_magnitudes(MeasurementPointSet::Eighteen, magnitudes);
|
|
// app.bode_plot.lock().unwrap().update_phases(MeasurementPointSet::Eighteen, phases);
|
|
|
|
app.update_start_stop();
|
|
app
|
|
}
|
|
|
|
pub fn update_start_stop(&self) {
|
|
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.lead_mode.lock().unwrap(), *self.dft_num.lock().unwrap())) {
|
|
error!("Failed to send start command: {:?}", e);
|
|
}
|
|
},
|
|
(TabActive::Sweep, true) => {
|
|
if let Err(e) = self.run_impedancemeter_tx.try_send(StartStopSignal::StartSweep(*self.lead_mode.lock().unwrap(), *self.measurement_points.lock().unwrap())) {
|
|
error!("Failed to send start command: {:?}", e);
|
|
}
|
|
},
|
|
(_, false) => {
|
|
if let Err(e) = self.run_impedancemeter_tx.try_send(StartStopSignal::Stop) {
|
|
error!("Failed to send stop command: {:?}", e);
|
|
}
|
|
},
|
|
(_, _) => {}
|
|
}
|
|
}
|
|
|
|
pub fn reset_view(&self) {
|
|
self.magnitude_series.lock().unwrap().clear();
|
|
self.phase_series.lock().unwrap().clear();
|
|
}
|
|
}
|
|
|
|
impl eframe::App for App {
|
|
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
|
// Egui add a top bar
|
|
egui::TopBottomPanel::top("top_bar").show(ctx, |ui| {
|
|
egui::MenuBar::new().ui(ui, |ui| {
|
|
let connected = self.connected.load(Ordering::Relaxed);
|
|
|
|
egui::widgets::global_theme_preference_switch(ui);
|
|
ui.separator();
|
|
|
|
ui.label(format!("Data rate: {} Hz", self.data_frequency.load(Ordering::Relaxed)));
|
|
|
|
ui.separator();
|
|
|
|
let on = *self.on.lock().unwrap();
|
|
|
|
let (color, text) = match on {
|
|
true => (Color32::DARK_RED, "Stop"),
|
|
false => (Color32::DARK_GREEN, "Start"),
|
|
};
|
|
|
|
let start_stop_button = Button::new(
|
|
RichText::new(text)
|
|
.strong()
|
|
.color(Color32::WHITE)
|
|
).fill(color)
|
|
.corner_radius(5.0)
|
|
.min_size(egui::vec2(45.0, 0.0))
|
|
.frame(true);
|
|
|
|
if ui.add_enabled(connected, start_stop_button).clicked() {
|
|
*self.on.lock().unwrap() = !on;
|
|
self.update_start_stop();
|
|
}
|
|
|
|
ui.separator();
|
|
|
|
if ui.add_enabled(connected, Button::new("Reset view")).clicked() {
|
|
self.reset_view();
|
|
}
|
|
|
|
ui.separator();
|
|
|
|
ui.add_enabled(connected, Label::new("Logging:"));
|
|
|
|
let gui_logging_state = *self.gui_logging_state.lock().unwrap();
|
|
|
|
let mut logging_enabled = !matches!(gui_logging_state, LoggingStates::Idle);
|
|
|
|
if ui.add_enabled(connected, toggle_start_stop(&mut logging_enabled)).changed() {
|
|
let signal = match gui_logging_state {
|
|
LoggingStates::Idle => LoggingSignal::StartFileLogging(self.log_filename.clone()),
|
|
LoggingStates::Starting | LoggingStates::Logging => LoggingSignal::StopFileLogging,
|
|
};
|
|
|
|
self.log_tx.try_send(signal).unwrap_or_else(|e| {
|
|
error!("Failed to send logging toggle signal: {:?}", e);
|
|
});
|
|
};
|
|
|
|
ui.separator();
|
|
|
|
ui.add_enabled_ui(on && logging_enabled, |ui| {
|
|
if Button::new("Add marker").corner_radius(5.0).min_size(egui::vec2(20.0, 0.0)).ui(ui).on_hover_text("Add a marker to the current time series plots").clicked() {
|
|
self.log_marker_modal = true;
|
|
}
|
|
});
|
|
|
|
if self.log_marker_modal {
|
|
if Modal::new(Id::new("modal_marker"))
|
|
.show(ctx, |ui| {
|
|
ui.vertical_centered(|ui| {
|
|
ui.heading("Add marker");
|
|
|
|
ui.add_space(16.0);
|
|
|
|
// Input field for marker
|
|
let text_edit_response = TextEdit::singleline(&mut self.log_marker)
|
|
.desired_width(100.0)
|
|
.id(Id::new("marker_field"))
|
|
.hint_text("Marker name")
|
|
.ui(ui);
|
|
|
|
ui.add_space(16.0);
|
|
|
|
// Centered Add button
|
|
let add_clicked = Button::new("Add")
|
|
.corner_radius(5.0)
|
|
.min_size(egui::vec2(80.0, 30.0))
|
|
.ui(ui)
|
|
.clicked();
|
|
|
|
// Check for Enter key in the TextEdit
|
|
let enter_pressed = text_edit_response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
|
|
|
if add_clicked || enter_pressed {
|
|
info!("Adding marker: {}", self.log_marker);
|
|
self.log_tx.try_send(LoggingSignal::AddMarker(self.log_marker.clone())).unwrap_or_else(|e| {
|
|
error!("Failed to send logging marker signal: {:?}", e);
|
|
});
|
|
self.log_marker = String::new();
|
|
ui.close();
|
|
}
|
|
|
|
// Request focus on the text edit when the modal opens
|
|
text_edit_response.request_focus();
|
|
});
|
|
})
|
|
.should_close()
|
|
{
|
|
self.log_marker_modal = false;
|
|
self.log_marker = String::new();
|
|
}
|
|
}
|
|
|
|
ui.separator();
|
|
|
|
ui.add_enabled_ui(gui_logging_state == LoggingStates::Idle, |ui| {
|
|
ui.label("Log filename:");
|
|
TextEdit::singleline(&mut self.log_filename).desired_width(150.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| {
|
|
let is_connected = self.connected.load(Ordering::Relaxed);
|
|
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
|
|
let led_size = egui::Vec2::splat(12.0);
|
|
let (rect, response) = ui.allocate_exact_size(led_size, egui::Sense::hover());
|
|
|
|
// Draw the circle
|
|
let center = rect.center();
|
|
let radius = 5.0;
|
|
ui.painter().circle_filled(center, radius, color);
|
|
|
|
// Tooltip
|
|
if response.hovered() {
|
|
response.on_hover_text(tooltip);
|
|
}
|
|
});
|
|
});
|
|
});
|
|
});
|
|
|
|
egui::CentralPanel::default().show(ctx, |ui| {
|
|
DockArea::new(&mut self.tree)
|
|
.style(Style::from_egui(ctx.style().as_ref()))
|
|
.show_leaf_close_all_buttons(false)
|
|
.show_leaf_collapse_buttons(false)
|
|
.show_close_buttons(false)
|
|
.show_inside(ui, &mut self.tab_viewer);
|
|
});
|
|
|
|
// Do something when a tab is changed
|
|
if let Some((_, tab)) = self.tree.find_active_focused() {
|
|
match tab.as_str() {
|
|
"Single" => {
|
|
if self.tab_active != TabActive::Single {
|
|
self.tab_active = TabActive::Single;
|
|
*self.on.lock().unwrap() = false;
|
|
self.update_start_stop();
|
|
if *self.gui_logging_state.lock().unwrap() == LoggingStates::Logging {
|
|
self.log_tx.try_send(LoggingSignal::StopFileLogging).unwrap_or_else(|e| {
|
|
error!("Failed to send logging logging signal: {:?}", e);
|
|
});
|
|
}
|
|
self.log_filename = format!("log_{}_single.csv", Local::now().format("%Y%m%d"));
|
|
info!("Switched to Single tab");
|
|
}
|
|
}
|
|
"Sweep" => {
|
|
if self.tab_active != TabActive::Sweep {
|
|
self.tab_active = TabActive::Sweep;
|
|
*self.on.lock().unwrap() = false;
|
|
self.update_start_stop();
|
|
if *self.gui_logging_state.lock().unwrap() == LoggingStates::Logging {
|
|
self.log_tx.try_send(LoggingSignal::StopFileLogging).unwrap_or_else(|e| {
|
|
error!("Failed to send logging logging signal: {:?}", e);
|
|
});
|
|
}
|
|
self.log_filename = format!("log_{}_sweep.csv", Local::now().format("%Y%m%d"));
|
|
info!("Switched to Sweep tab");
|
|
}
|
|
}
|
|
"Shortcuts" => {
|
|
// if self.tab_active != TabActive::Shortcuts {
|
|
// self.tab_active = TabActive::Shortcuts;
|
|
// *self.on.lock().unwrap() = false;
|
|
// self.update_start_stop();
|
|
// info!("Switched to Shortcuts tab");
|
|
// }
|
|
}
|
|
_ => {
|
|
}
|
|
}
|
|
}
|
|
|
|
// CMD- or control-W to close window
|
|
if ctx.input(|i| i.modifiers.cmd_ctrl_matches(Modifiers::COMMAND))
|
|
&& ctx.input(|i| i.key_pressed(Key::W))
|
|
{
|
|
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")));
|
|
let marker_field_is_focused = ctx.memory(|memory| memory.has_focus(Id::new("marker_field")));
|
|
if !file_name_field_is_focused && !marker_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();
|
|
}
|
|
|
|
// 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();
|
|
}
|
|
|
|
// Toggle marker modal
|
|
if ctx.input(|i| i.key_pressed(egui::Key::A)) && *self.gui_logging_state.lock().unwrap() == LoggingStates::Logging {
|
|
self.log_marker_modal = !self.log_marker_modal;
|
|
}
|
|
|
|
// Enable/disable GUI logging
|
|
if ctx.input(|i| i.key_pressed(egui::Key::L)) {
|
|
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);
|
|
}
|
|
},
|
|
}
|
|
}
|
|
|
|
// 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);
|
|
}
|
|
}
|
|
}
|
|
|
|
ctx.request_repaint();
|
|
}
|
|
}
|
|
|
|
|
|
fn toggle_ui_start_stop(ui: &mut egui::Ui, on: &mut bool) -> egui::Response {
|
|
let desired_size = ui.spacing().interact_size.y * egui::vec2(2.0, 1.0);
|
|
let (rect, mut response) = ui.allocate_exact_size(desired_size, egui::Sense::click());
|
|
if response.clicked() {
|
|
*on = !*on;
|
|
response.mark_changed();
|
|
}
|
|
response.widget_info(|| {
|
|
egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), *on, "")
|
|
});
|
|
|
|
if ui.is_rect_visible(rect) {
|
|
let how_on = ui.ctx().animate_bool_responsive(response.id, *on);
|
|
let visuals = ui.style().interact_selectable(&response, *on);
|
|
let rect = rect.expand(visuals.expansion);
|
|
let radius = 0.5 * rect.height();
|
|
ui.painter().rect(
|
|
rect,
|
|
radius,
|
|
visuals.bg_fill,
|
|
visuals.bg_stroke,
|
|
egui::StrokeKind::Inside,
|
|
);
|
|
let circle_x = egui::lerp((rect.left() + radius)..=(rect.right() - radius), how_on);
|
|
let center = egui::pos2(circle_x, rect.center().y);
|
|
ui.painter()
|
|
.circle(center, 0.75 * radius, visuals.bg_fill, visuals.fg_stroke);
|
|
}
|
|
|
|
response
|
|
}
|
|
|
|
pub fn toggle_start_stop(on: &mut bool) -> impl egui::Widget + '_ {
|
|
move |ui: &mut egui::Ui| toggle_ui_start_stop(ui, on)
|
|
} |