mirror of
https://github.com/hubaldv/bioz-host-rs.git
synced 2025-12-06 05:11:17 +00:00
Included bode plot measurements, including different number of points.
This commit is contained in:
106
src/app.rs
106
src/app.rs
@@ -9,14 +9,15 @@ use atomic_float::AtomicF32;
|
||||
use tokio::{sync::mpsc::{Sender}};
|
||||
|
||||
use eframe::egui::{self, Button, CollapsingHeader, Color32, ComboBox, DragValue, Key, Label, Layout, Modifiers};
|
||||
use egui_plot::{Corner, GridInput, GridMark, Legend, Line, Plot, PlotBounds, PlotPoint, PlotPoints, Points};
|
||||
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::icd::{IcdDftNum, NumberOfPoints};
|
||||
use crate::icd::{IcdDftNum, MeasurementPointSet};
|
||||
|
||||
const DFTNUM_VARIANTS: [IcdDftNum; 13] = [
|
||||
IcdDftNum::Num4, IcdDftNum::Num8, IcdDftNum::Num16, IcdDftNum::Num32,
|
||||
@@ -25,6 +26,11 @@ const DFTNUM_VARIANTS: [IcdDftNum; 13] = [
|
||||
IcdDftNum::Num8192, IcdDftNum::Num16384,
|
||||
];
|
||||
|
||||
const MEASUREMENT_POINTS_VARIANTS: [MeasurementPointSet; 2] = [
|
||||
MeasurementPointSet::Eight,
|
||||
MeasurementPointSet::Eighteen,
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy,Debug, PartialEq, Eq)]
|
||||
enum TabActive {
|
||||
Single,
|
||||
@@ -47,7 +53,9 @@ pub struct App {
|
||||
pub data_frequency: Arc<AtomicF32>,
|
||||
pub single_frequency: Arc<Mutex<u32>>,
|
||||
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>>)>>,
|
||||
}
|
||||
|
||||
struct TabViewer {
|
||||
@@ -59,7 +67,9 @@ struct TabViewer {
|
||||
on: Arc<Mutex<bool>>,
|
||||
single_frequency: Arc<Mutex<u32>>,
|
||||
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>>)>>,
|
||||
show_settings: bool,
|
||||
show_settings_toggle: Option<bool>,
|
||||
}
|
||||
@@ -171,21 +181,76 @@ impl TabViewer {
|
||||
if let Ok(on) = self.on.lock() {
|
||||
ui.add_enabled_ui(!*on, |ui| {
|
||||
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")
|
||||
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, DFTNUM_VARIANTS.len(), |i| {
|
||||
format!("{}", 1 << (2 + i)) // 2^2 = 4, 2^3 = 8, ..., 2^14 = 16384
|
||||
.show_index(ui, &mut index, MEASUREMENT_POINTS_VARIANTS.len(), |i| {
|
||||
format!("{:?}", MEASUREMENT_POINTS_VARIANTS[i].len())
|
||||
});
|
||||
let new_value = DFTNUM_VARIANTS[index];
|
||||
if *dft_num != new_value {
|
||||
*dft_num = new_value;
|
||||
info!("DFTNUM setting changed!");
|
||||
};
|
||||
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_multi.lock().unwrap().clone();
|
||||
|
||||
fn format_frequency(freq: f32) -> String {
|
||||
if freq >= 1_000.0 {
|
||||
// kHz
|
||||
if freq % 1_000.0 == 0.0 {
|
||||
format!("{}k", (freq / 1_000.0) as u64)
|
||||
} else {
|
||||
format!("{:.1}k", freq / 1_000.0)
|
||||
}
|
||||
} else {
|
||||
// Hz
|
||||
if freq % 1.0 == 0.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");
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -355,7 +420,9 @@ impl App {
|
||||
let bode_plot = Arc::new(Mutex::new(BodePlot::new()));
|
||||
let single_frequency = Arc::new(Mutex::new(50000));
|
||||
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_multi = Arc::new(Mutex::new((MeasurementPointSet::Eighteen.values().to_vec(), None)));
|
||||
let on = Arc::new(Mutex::new(true));
|
||||
let tab_active = TabActive::Single;
|
||||
|
||||
@@ -368,7 +435,9 @@ impl App {
|
||||
bode_plot: bode_plot.clone(),
|
||||
single_frequency: single_frequency.clone(),
|
||||
dft_num: dft_num.clone(),
|
||||
measurement_points: measurement_points.clone(),
|
||||
periods_per_dft: periods_per_dft.clone(),
|
||||
periods_per_dft_multi: periods_per_dft_multi.clone(),
|
||||
on: on.clone(),
|
||||
show_settings: false,
|
||||
show_settings_toggle: None,
|
||||
@@ -390,13 +459,15 @@ impl App {
|
||||
data_frequency: Arc::new(AtomicF32::new(0.0)),
|
||||
single_frequency,
|
||||
dft_num,
|
||||
measurement_points,
|
||||
periods_per_dft,
|
||||
periods_per_dft_multi,
|
||||
};
|
||||
|
||||
// For testing purposes, populate the Bode plot with a sample low-pass filter response
|
||||
let fc = 1000.0; // cutoff frequency in Hz
|
||||
|
||||
let freqs = NumberOfPoints::TwentyEight.values().to_vec();
|
||||
let freqs = MeasurementPointSet::Eighteen.values().to_vec();
|
||||
let magnitudes = freqs.iter()
|
||||
.map(|&f| {
|
||||
1.0 / (1.0 + (f / fc).powi(2)).sqrt()
|
||||
@@ -408,9 +479,8 @@ impl App {
|
||||
})
|
||||
.collect::<Vec<f32>>();
|
||||
|
||||
app.bode_plot.lock().unwrap().update_magnitudes(magnitudes);
|
||||
app.bode_plot.lock().unwrap().update_phases(phases);
|
||||
|
||||
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
|
||||
@@ -424,7 +494,7 @@ impl App {
|
||||
}
|
||||
},
|
||||
(TabActive::Multi, true) => {
|
||||
if let Err(e) = self.run_impedancemeter_tx.try_send(StartStopSignal::StartMulti(*self.dft_num.lock().unwrap(), NumberOfPoints::TwentyEight)) {
|
||||
if let Err(e) = self.run_impedancemeter_tx.try_send(StartStopSignal::StartMulti(*self.measurement_points.lock().unwrap())) {
|
||||
eprintln!("Failed to send start command: {:?}", e);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -78,7 +78,7 @@ async fn main() {
|
||||
.subscribe_multi::<icd::SingleImpedanceOutputTopic>(8)
|
||||
.await
|
||||
.unwrap();
|
||||
client.start_impedancemeter_single(freq, bioz_icd_rs::IcdDftNum::Num2048).await.unwrap();
|
||||
client.start_impedancemeter_single(freq, bioz_icd_rs::IcdDftNum::Num2048).await.unwrap().ok();
|
||||
println!("Started with dft_num 2048!");
|
||||
let dur = Duration::from_millis(dur.into());
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ fn main() {
|
||||
let data_frequency_clone = app.data_frequency.clone();
|
||||
|
||||
let periods_per_dft = app.periods_per_dft.clone();
|
||||
let periods_per_dft_multi = app.periods_per_dft_multi.clone();
|
||||
|
||||
// Execute the runtime in its own thread.
|
||||
std::thread::spawn(move || {
|
||||
@@ -48,6 +49,7 @@ fn main() {
|
||||
connected_clone,
|
||||
data_frequency_clone,
|
||||
periods_per_dft,
|
||||
periods_per_dft_multi,
|
||||
));
|
||||
});
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@ use postcard_rpc::{
|
||||
};
|
||||
use std::convert::Infallible;
|
||||
use bioz_icd_rs::{
|
||||
GetUniqueIdEndpoint, InitImpedanceResult, PingEndpoint, SetGreenLedEndpoint, StartMultiImpedance, StartMultiImpedanceEndpoint, StartSingleImpedance, StartSingleImpedanceEndpoint, StopSingleImpedanceEndpoint
|
||||
GetUniqueIdEndpoint, ImpedanceInitResult, MultiImpedanceInitResult, MultiImpedanceStartRequest, PingEndpoint, SetGreenLedEndpoint, SingleImpedanceStartRequest, StartMultiImpedanceEndpoint, StartSingleImpedanceEndpoint, StopSingleImpedanceEndpoint
|
||||
};
|
||||
|
||||
use crate::icd::{IcdDftNum, NumberOfPoints};
|
||||
use crate::icd::{IcdDftNum, MeasurementPointSet};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct WorkbookClient {
|
||||
@@ -66,22 +66,21 @@ impl WorkbookClient {
|
||||
&self,
|
||||
frequency: u32,
|
||||
dft_number: IcdDftNum,
|
||||
) -> Result<InitImpedanceResult, WorkbookError<Infallible>> {
|
||||
) -> Result<ImpedanceInitResult, WorkbookError<Infallible>> {
|
||||
let response = self.client
|
||||
.send_resp::<StartSingleImpedanceEndpoint>(&StartSingleImpedance { update_frequency: 60, sinus_frequency: frequency, dft_number})
|
||||
.send_resp::<StartSingleImpedanceEndpoint>(&SingleImpedanceStartRequest { update_frequency: 60, sinus_frequency: frequency, dft_number})
|
||||
.await?;
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub async fn start_impedancemeter_multi(
|
||||
&self,
|
||||
dft_number: IcdDftNum,
|
||||
number_of_points: NumberOfPoints,
|
||||
) -> Result<(), WorkbookError<Infallible>> {
|
||||
self.client
|
||||
.send_resp::<StartMultiImpedanceEndpoint>(&StartMultiImpedance { dft_number, number_of_points })
|
||||
points: MeasurementPointSet,
|
||||
) -> Result<MultiImpedanceInitResult, WorkbookError<Infallible>> {
|
||||
let response = self.client
|
||||
.send_resp::<StartMultiImpedanceEndpoint>(&MultiImpedanceStartRequest { points })
|
||||
.await?;
|
||||
Ok(())
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub async fn stop_impedancemeter(&self) -> Result<bool, WorkbookError<Infallible>> {
|
||||
|
||||
@@ -8,6 +8,8 @@ use atomic_float::AtomicF32;
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use bioz_icd_rs::MeasurementPointSet;
|
||||
|
||||
use crate::icd;
|
||||
use crate::client::WorkbookClient;
|
||||
|
||||
@@ -26,6 +28,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>>)>>,
|
||||
) {
|
||||
let data_counter = Arc::new(AtomicU32::new(0));
|
||||
let data_counter_clone = data_counter.clone();
|
||||
@@ -88,10 +91,10 @@ pub async fn communicate_with_hardware(
|
||||
info!("SingleImpedanceOutputTopic subscription ended.");
|
||||
});
|
||||
|
||||
// Subscribe to MultiImpedanceOutputTopic28
|
||||
let mut multi_impedance_28_sub = workbook_client
|
||||
// Subscribe to MultiImpedanceOutputTopic8
|
||||
let mut multi_impedance_sub = workbook_client
|
||||
.client
|
||||
.subscribe_multi::<icd::MultiImpedanceOutputTopic28>(8)
|
||||
.subscribe_multi::<icd::MultiImpedanceOutputTopic>(8)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -99,14 +102,25 @@ pub async fn communicate_with_hardware(
|
||||
let data_counter_clone_multi = data_counter_clone.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
while let Ok(val) = multi_impedance_28_sub.recv().await {
|
||||
while let Ok(val) = multi_impedance_sub.recv().await {
|
||||
let mut bode_plot = data.lock().unwrap();
|
||||
|
||||
let magnitudes = val.magnitudes.into_iter().collect::<Vec<f32>>();
|
||||
bode_plot.update_magnitudes(magnitudes);
|
||||
let phases = val.phases.into_iter().collect::<Vec<f32>>();
|
||||
bode_plot.update_phases(phases);
|
||||
match val.points {
|
||||
|
||||
MeasurementPointSet::Eight => {
|
||||
let magnitudes: Vec<f32> = val.magnitudes_8.into_iter().collect();
|
||||
let phases: Vec<f32> = val.phases_8.into_iter().collect();
|
||||
bode_plot.update_magnitudes(MeasurementPointSet::Eight, magnitudes);
|
||||
bode_plot.update_phases(MeasurementPointSet::Eight, phases);
|
||||
},
|
||||
MeasurementPointSet::Eighteen => {
|
||||
let magnitudes: Vec<f32> = val.magnitudes_18.into_iter().collect();
|
||||
let phases: Vec<f32> = val.phases_18.into_iter().collect();
|
||||
bode_plot.update_magnitudes(MeasurementPointSet::Eighteen, magnitudes);
|
||||
bode_plot.update_phases(MeasurementPointSet::Eighteen, phases);
|
||||
},
|
||||
}
|
||||
|
||||
data_counter_clone_multi.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
@@ -132,12 +146,28 @@ pub async fn communicate_with_hardware(
|
||||
}
|
||||
}
|
||||
},
|
||||
StartStopSignal::StartMulti(dft_num, num_points) => {
|
||||
if let Err(e) = workbook_client.start_impedancemeter_multi(dft_num, num_points).await {
|
||||
error!("Failed to start multi-point impedancemeter: {:?}", e);
|
||||
} else {
|
||||
settings.frequency = Some(StartStopSignal::StartMulti(dft_num, num_points));
|
||||
info!("Multi-point Impedancemeter started.");
|
||||
StartStopSignal::StartMulti(num_points) => {
|
||||
match workbook_client.start_impedancemeter_multi(num_points).await {
|
||||
Ok(Ok(periods)) => {
|
||||
settings.frequency = Some(StartStopSignal::StartMulti(num_points));
|
||||
info!("Multi-point Impedancemeter started.");
|
||||
match num_points {
|
||||
MeasurementPointSet::Eight => {
|
||||
*periods_per_dft_multi.lock().unwrap() = (num_points.values().iter().copied().collect(), Some(periods.periods_per_dft_8.into_iter().collect()));
|
||||
},
|
||||
MeasurementPointSet::Eighteen => {
|
||||
*periods_per_dft_multi.lock().unwrap() = (num_points.values().iter().copied().collect(), Some(periods.periods_per_dft_18.into_iter().collect()));
|
||||
},
|
||||
}
|
||||
},
|
||||
Ok(Err(e)) => {
|
||||
error!("Failed to multi-init on hardware: {:?}", e);
|
||||
*periods_per_dft_multi.lock().unwrap() = (num_points.values().iter().copied().collect(), None);
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Communication error when starting impedancemeter: {:?}", e);
|
||||
*periods_per_dft_multi.lock().unwrap() = (num_points.values().iter().copied().collect(), None);
|
||||
}
|
||||
}
|
||||
},
|
||||
StartStopSignal::Stop => {
|
||||
@@ -145,6 +175,9 @@ pub async fn communicate_with_hardware(
|
||||
error!("Failed to stop impedancemeter: {:?}", e);
|
||||
} else {
|
||||
settings.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);
|
||||
info!("Impedancemeter stopped.");
|
||||
}
|
||||
},
|
||||
|
||||
10
src/plot.rs
10
src/plot.rs
@@ -3,7 +3,7 @@ use std::collections::VecDeque;
|
||||
|
||||
use egui_plot::{PlotPoint, PlotPoints};
|
||||
|
||||
use bioz_icd_rs::NumberOfPoints;
|
||||
use bioz_icd_rs::MeasurementPointSet;
|
||||
|
||||
pub struct TimeSeriesPlot {
|
||||
pub values: VecDeque<PlotPoint>,
|
||||
@@ -63,14 +63,14 @@ impl BodePlot {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_magnitudes(&mut self, magnitudes: Vec<f32>) {
|
||||
let freqs = NumberOfPoints::TwentyEight.values().to_vec();
|
||||
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();
|
||||
}
|
||||
|
||||
pub fn update_phases(&mut self, phases: Vec<f32>) {
|
||||
let freqs = NumberOfPoints::TwentyEight.values().to_vec();
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::icd::{IcdDftNum, NumberOfPoints};
|
||||
use crate::icd::{IcdDftNum, MeasurementPointSet};
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub enum StartStopSignal {
|
||||
StartSingle(u32, IcdDftNum), // frequency in Hz, DFT number
|
||||
StartMulti(IcdDftNum, NumberOfPoints), // DFT number, number of points per measurement
|
||||
StartMulti(MeasurementPointSet), // DFT number, number of points per measurement
|
||||
Stop,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user