Compare commits

...

8 Commits

16 changed files with 1168 additions and 288 deletions

4
.gitignore vendored
View File

@@ -1,2 +1,4 @@
/target
.DS_Store
.DS_Store
log_*
*.icns

20
.vscode/tasks.json vendored
View File

@@ -63,6 +63,26 @@
// "isDefault": true
}
},
{
"label": "cargo bundle - create app release",
"type": "shell",
"command": "~/.cargo/bin/cargo", // note: full path to the cargo
"args": [
"bundle",
"--bin",
"main_gui",
"--release",
// "--target",
// "aarch64-apple-darwin",
// "x86_64-pc-windows-gnu"
// "--",
// "arg1"
],
"group": {
"kind": "build",
// "isDefault": true
}
},
{
"label": "Terminate All Tasks",
"command": "echo ${input:terminate}",

777
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -12,6 +12,8 @@ egui_extras = "0.32.3"
log = "0.4.27"
simple_logger = "5.0.0"
atomic_float = "1.1.0"
chrono = { version = "0.4.42" }
rfd = { version = "0.16.0", features = ["tokio"] }
[dependencies.bioz-icd-rs]
path = "../bioz-icd-rs"
@@ -35,7 +37,17 @@ features = [
"rt-multi-thread",
"macros",
"time",
"fs",
]
[dependencies.tokio-serial]
version = "5.4.4"
[package.metadata.bundle.bin.main_gui]
name = "Bio-Z App"
identifier = "bioz-host-rs"
icon = ["bundle/bio-z.icns"]
version = "0.1.0"
copyright = "Hubald Verzijl"
category = "Developer Tool"
long_description = "App belonging to the Bio-Z setup."

13
bundle/CreateCNS.src Normal file
View File

@@ -0,0 +1,13 @@
mkdir MyIcon.iconset
sips -z 16 16 Icon1024.png --out MyIcon.iconset/icon_16x16.png
sips -z 32 32 Icon1024.png --out MyIcon.iconset/icon_16x16@2x.png
sips -z 32 32 Icon1024.png --out MyIcon.iconset/icon_32x32.png
sips -z 64 64 Icon1024.png --out MyIcon.iconset/icon_32x32@2x.png
sips -z 128 128 Icon1024.png --out MyIcon.iconset/icon_128x128.png
sips -z 256 256 Icon1024.png --out MyIcon.iconset/icon_128x128@2x.png
sips -z 256 256 Icon1024.png --out MyIcon.iconset/icon_256x256.png
sips -z 512 512 Icon1024.png --out MyIcon.iconset/icon_256x256@2x.png
sips -z 512 512 Icon1024.png --out MyIcon.iconset/icon_512x512.png
cp Icon1024.png MyIcon.iconset/icon_512x512@2x.png
iconutil -c icns MyIcon.iconset
rm -R MyIcon.iconset

11
bundle/readme.md Normal file
View File

@@ -0,0 +1,11 @@
### Prepare
- Picture for icon from: https://pubs.acs.org/doi/10.1021/acsmeasuresciau.2c00033
- For packing as OSX-app or Windows, when on OSX, install mingw-w64 first for cross-linking:
`brew install mingw-w64`
### Steps
- Create 1024x1024 picture
- Transform to icon
- Using *Image2Icon app*
- Using terminal: `source CreateCNS.src`
- Adjust path in `tasks.json` use a custom cargo-bundle command

18
readme.md Normal file
View File

@@ -0,0 +1,18 @@
# Bio-Impedance Amplifier | GUI
This repository contains Rust-based software for communicating with a custom-built bio-impedance amplifier. It provides several key features:
- Single-frequency and frequency-sweep measurements
- Real-time visualization of magnitude and phase
- Support for both 2-lead and 4-lead measurements
- Data logging to `.csv` files
- Day and night display modes
- Control via on-screen buttons or keyboard shortcuts
## How to Use This Software
1. Install the Rust toolchain and run the software using:
```bash
cargo run --bin main_gui --release
```
2. Alternatively, a precompiled executable can be used instead of building from source.
3. The software uses the `postcard-rpc` crate to communicate directly with the USB hardware devices endpoints. After connecting the hardware via USB, the device should automatically connect, and the indicator dot in the top-right corner will turn green.
4. Check the **Shortcuts** tab for useful information on available keyboard commands.

View File

@@ -1,23 +1,33 @@
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, 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::StartStopSignal;
use crate::signals::{LoggingSignal, StartStopSignal};
use crate::icd::{IcdDftNum, MeasurementPointSet};
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,
@@ -34,7 +44,7 @@ const MEASUREMENT_POINTS_VARIANTS: [MeasurementPointSet; 2] = [
#[derive(Clone, Copy,Debug, PartialEq, Eq)]
enum TabActive {
Single,
Multi,
Sweep,
Shortcuts,
}
@@ -42,6 +52,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>>,
@@ -52,10 +63,13 @@ pub struct App {
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_multi: Arc<Mutex<(Vec<f32>, Option<Vec<f32>>)>>,
pub periods_per_dft_sweep: Arc<Mutex<(Vec<u32>, Option<Vec<f32>>)>>,
pub gui_logging_state: Arc<Mutex<LoggingStates>>,
log_filename: String,
}
struct TabViewer {
@@ -66,10 +80,11 @@ struct TabViewer {
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_multi: Arc<Mutex<(Vec<f32>, Option<Vec<f32>>)>>,
periods_per_dft_sweep: Arc<Mutex<(Vec<u32>, Option<Vec<f32>>)>>,
show_settings: bool,
show_settings_toggle: Option<bool>,
}
@@ -81,6 +96,35 @@ impl TabViewer {
.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!");
}
});
});
ui.add_enabled_ui(!*on, |ui| {
ui.horizontal(|ui| {
ui.label("Single Frequency:");
@@ -173,12 +217,42 @@ impl TabViewer {
});
}
fn multi_tab(&mut self, ui: &mut egui::Ui) {
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!");
}
});
});
ui.add_enabled_ui(!*on, |ui| {
ui.horizontal(|ui| {
ui.label("Measurement Points:");
@@ -197,19 +271,19 @@ impl TabViewer {
});
});
ui.add_enabled_ui(*on, |ui| {
let (freq, periods_per_dft_vec) = self.periods_per_dft_multi.lock().unwrap().clone();
let (freq, periods_per_dft_vec) = self.periods_per_dft_sweep.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 as f32 / 1_000.0)
}
} else {
// Hz
if freq % 1.0 == 0.0 {
if freq % 1 == 0 {
format!("{}", freq as u64)
} else {
format!("{:.1}", freq)
@@ -327,8 +401,9 @@ impl TabViewer {
fn shortcuts(&mut self, ui: &mut egui::Ui) {
ui.heading("Shortcuts");
ui.label("Space: Start/Stop measurement");
ui.label("C: Clear plots");
ui.label("R: Reset view/plots");
ui.label("S: Toggle settings");
ui.label("L: Toggle logging");
ui.label("CMD-W: Close window");
}
}
@@ -394,14 +469,14 @@ fn log10x_formatter(name: &str, value: &PlotPoint) -> String {
impl egui_dock::TabViewer for TabViewer {
type Tab = String;
fn title(&mut self, tab: &mut Self::Tab) -> egui::WidgetText {
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),
"Multi" => self.multi_tab(ui),
"Sweep" => self.sweep_tab(ui),
"Shortcuts" => self.shortcuts(ui),
_ => {
let _ = ui.label("Unknown tab");
@@ -411,7 +486,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));
@@ -419,10 +494,11 @@ impl App {
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_multi = Arc::new(Mutex::new((MeasurementPointSet::Eighteen.values().to_vec(), 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;
@@ -434,10 +510,11 @@ impl App {
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_multi: periods_per_dft_multi.clone(),
periods_per_dft_sweep: periods_per_dft_sweep.clone(),
on: on.clone(),
show_settings: false,
show_settings_toggle: None,
@@ -445,9 +522,10 @@ impl App {
// Step 3: Construct App
let app = App {
tree: DockState::new(vec!["Single".to_string(), "Multi".to_string(), "Shortcuts".to_string()]),
tree: DockState::new(vec!["Single".to_string(), "Sweep".to_string(), "Shortcuts".to_string()]),
tab_viewer,
run_impedancemeter_tx,
log_tx,
magnitude,
phase,
magnitude_series,
@@ -458,29 +536,32 @@ impl App {
tab_active,
data_frequency: Arc::new(AtomicF32::new(0.0)),
single_frequency,
lead_mode,
dft_num,
measurement_points,
periods_per_dft,
periods_per_dft_multi,
periods_per_dft_sweep,
gui_logging_state: Arc::new(Mutex::new(LoggingStates::Idle)),
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
let fc = 1000.0; // cutoff frequency in Hz
// 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>>();
// 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.bode_plot.lock().unwrap().update_magnitudes(MeasurementPointSet::Eighteen, magnitudes);
// app.bode_plot.lock().unwrap().update_phases(MeasurementPointSet::Eighteen, phases);
app.update_start_stop();
app
@@ -489,18 +570,18 @@ impl 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.dft_num.lock().unwrap())) {
eprintln!("Failed to send start command: {:?}", e);
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::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);
(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) {
eprintln!("Failed to send stop command: {:?}", e);
error!("Failed to send stop command: {:?}", e);
}
},
(_, _) => {}
@@ -537,11 +618,42 @@ impl eframe::App for App {
self.reset_view();
}
ui.separator();
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_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);
});
// 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::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
@@ -582,12 +694,12 @@ impl eframe::App for App {
info!("Switched to Single tab");
}
}
"Multi" => {
if self.tab_active != TabActive::Multi {
self.tab_active = TabActive::Multi;
"Sweep" => {
if self.tab_active != TabActive::Sweep {
self.tab_active = TabActive::Sweep;
*self.on.lock().unwrap() = false;
self.update_start_stop();
info!("Switched to Multi tab");
info!("Switched to Sweep tab");
}
}
"Shortcuts" => {
@@ -609,33 +721,60 @@ 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::C)) {
self.reset_view();
}
// Reset view
if ctx.input(|i| i.key_pressed(Key::R)) {
self.reset_view();
}
// 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);
// 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);
}
}
}

View File

@@ -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().ok();
client.start_impedancemeter_single(freq, bioz_icd_rs::BioImpedanceLeadMode::TwoLead, bioz_icd_rs::IcdDftNum::Num2048).await.unwrap().ok();
println!("Started with dft_num 2048!");
let dur = Duration::from_millis(dur.into());
@@ -97,7 +97,7 @@ async fn main() {
};
match client.start_impedancemeter_single(freq, bioz_icd_rs::IcdDftNum::Num2048).await {
match client.start_impedancemeter_single(freq, bioz_icd_rs::BioImpedanceLeadMode::TwoLead, bioz_icd_rs::IcdDftNum::Num2048).await {
Ok(_) => println!("Started with dft_num 2048!"),
Err(e) => println!("Error starting impedancemeter: {:?}", e),
};

View File

@@ -2,15 +2,17 @@ use simple_logger::SimpleLogger;
use log::info;
use tokio::runtime::Runtime;
use bioz_host_rs::app::App;
use bioz_host_rs::{app::App, signals::LoggingSignal};
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;
fn main() {
#[tokio::main]
async fn main() {
SimpleLogger::new().init().expect("Failed to initialize logger");
log::set_max_level(log::LevelFilter::Info);
info!("Starting Bioz Impedance Visualizer...");
@@ -20,10 +22,15 @@ fn main() {
// Enter the runtime so that `tokio::spawn` is available immediately.
// let _enter = rt.enter();
// Channel to communicate with the communication task.
let (run_impedancemeter_tx, run_impedancemeter_rx) = mpsc::channel::<StartStopSignal>(2);
let run_impedancemeter_tx_clone = run_impedancemeter_tx.clone();
let app = App::new(run_impedancemeter_tx);
// Logging
let (log_tx, log_rx) = mpsc::channel::<LoggingSignal>(10);
let log_tx_clone = log_tx.clone();
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();
@@ -34,7 +41,13 @@ 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();
let periods_per_dft_sweep = app.periods_per_dft_sweep.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, gui_logging_state_1).await });
// Execute the runtime in its own thread.
std::thread::spawn(move || {
@@ -49,7 +62,9 @@ fn main() {
connected_clone,
data_frequency_clone,
periods_per_dft,
periods_per_dft_multi,
periods_per_dft_sweep,
gui_logging_state_2,
log_tx_clone,
));
});

View File

@@ -5,7 +5,7 @@ use postcard_rpc::{
};
use std::convert::Infallible;
use bioz_icd_rs::{
GetUniqueIdEndpoint, ImpedanceInitResult, MultiImpedanceInitResult, MultiImpedanceStartRequest, PingEndpoint, SetGreenLedEndpoint, SingleImpedanceStartRequest, StartMultiImpedanceEndpoint, StartSingleImpedanceEndpoint, StopSingleImpedanceEndpoint
BioImpedanceLeadMode, GetUniqueIdEndpoint, ImpedanceInitResult, SweepImpedanceInitResult, SweepImpedanceStartRequest, PingEndpoint, SetGreenLedEndpoint, SingleImpedanceStartRequest, StartSweepImpedanceEndpoint, StartSingleImpedanceEndpoint, StopImpedanceEndpoint
};
use crate::icd::{IcdDftNum, MeasurementPointSet};
@@ -65,20 +65,22 @@ impl WorkbookClient {
pub async fn start_impedancemeter_single(
&self,
frequency: u32,
lead_mode: BioImpedanceLeadMode,
dft_number: IcdDftNum,
) -> Result<ImpedanceInitResult, WorkbookError<Infallible>> {
let response = self.client
.send_resp::<StartSingleImpedanceEndpoint>(&SingleImpedanceStartRequest { update_frequency: 60, sinus_frequency: frequency, dft_number})
.send_resp::<StartSingleImpedanceEndpoint>(&SingleImpedanceStartRequest { update_frequency: 60, sinus_frequency: frequency, lead_mode, dft_number})
.await?;
Ok(response)
}
pub async fn start_impedancemeter_multi(
pub async fn start_impedancemeter_sweep(
&self,
lead_mode: BioImpedanceLeadMode,
points: MeasurementPointSet,
) -> Result<MultiImpedanceInitResult, WorkbookError<Infallible>> {
) -> Result<SweepImpedanceInitResult, WorkbookError<Infallible>> {
let response = self.client
.send_resp::<StartMultiImpedanceEndpoint>(&MultiImpedanceStartRequest { points })
.send_resp::<StartSweepImpedanceEndpoint>(&SweepImpedanceStartRequest { lead_mode, points })
.await?;
Ok(response)
}
@@ -86,7 +88,7 @@ impl WorkbookClient {
pub async fn stop_impedancemeter(&self) -> Result<bool, WorkbookError<Infallible>> {
let res = self
.client
.send_resp::<StopSingleImpedanceEndpoint>(&())
.send_resp::<StopImpedanceEndpoint>(&())
.await?;
Ok(res)
}

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;
@@ -13,9 +15,10 @@ use bioz_icd_rs::MeasurementPointSet;
use crate::icd;
use crate::client::WorkbookClient;
use crate::logging::LoggingStates;
use crate::plot::{TimeSeriesPlot, BodePlot};
use crate::signals::StartStopSignal;
use crate::signals::{LoggingSignal, StartStopSignal};
pub async fn communicate_with_hardware(
mut run_impedancemeter_rx: Receiver<StartStopSignal>,
@@ -28,7 +31,9 @@ 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_sweep: Arc<Mutex<(Vec<u32>, Option<Vec<f32>>)>>,
gui_logging_state: Arc<Mutex<LoggingStates>>,
log_tx: Sender<LoggingSignal>,
) {
let data_counter = Arc::new(AtomicU32::new(0));
let data_counter_clone = data_counter.clone();
@@ -40,17 +45,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);
@@ -73,55 +78,99 @@ pub async fn communicate_with_hardware(
let data = (magnitude_series.clone(), phase_series.clone(), magnitude.clone(), phase.clone());
let data_counter_clone_single = data_counter_clone.clone();
// Clone log_tx for the task
let gui_logging_state_clone = gui_logging_state.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 {
let mut mag_plot = data.0.lock().unwrap();
let mut phase_plot = data.1.lock().unwrap();
let mut mag_val = data.2.lock().unwrap();
let mut phase_val = data.3.lock().unwrap();
{
let mut mag_plot = data.0.lock().unwrap();
let mut phase_plot = data.1.lock().unwrap();
let mut mag_val = data.2.lock().unwrap();
let mut phase_val = data.3.lock().unwrap();
*mag_val = val.magnitude;
*phase_val = val.phase;
mag_plot.add(val.magnitude as f64);
phase_plot.add(val.phase as f64);
data_counter_clone_single.fetch_add(1, Ordering::Relaxed);
*mag_val = val.magnitude;
*phase_val = val.phase;
mag_plot.add(val.magnitude as f64);
phase_plot.add(val.phase as f64);
data_counter_clone_single.fetch_add(1, Ordering::Relaxed);
}
// Send logging signal
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.try_send(LoggingSignal::SingleImpedance(SystemTime::now(), freq, val.magnitude, val.phase)) {
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.");
});
// Subscribe to MultiImpedanceOutputTopic8
let mut multi_impedance_sub = workbook_client
// Subscribe to SweepImpedanceOutputTopic8
let mut sweep_impedance_sub = workbook_client
.client
.subscribe_multi::<icd::MultiImpedanceOutputTopic>(8)
.subscribe_multi::<icd::SweepImpedanceOutputTopic>(8)
.await
.unwrap();
let data = bode_series.clone();
let data_counter_clone_multi = data_counter_clone.clone();
let data_counter_clone_sweep = data_counter_clone.clone();
// Clone log_tx for the task
let gui_logging_state_clone = gui_logging_state.clone();
let log_tx_clone = log_tx.clone();
tokio::spawn(async move {
while let Ok(val) = multi_impedance_sub.recv().await {
let mut bode_plot = data.lock().unwrap();
while let Ok(val) = sweep_impedance_sub.recv().await {
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);
{
let mut bode_plot = data.lock().unwrap();
bode_plot.update_magnitudes(MeasurementPointSet::Eight, magnitudes.clone());
bode_plot.update_phases(MeasurementPointSet::Eight, phases.clone());
}
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);
}
}
},
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);
{
let mut bode_plot = data.lock().unwrap();
bode_plot.update_magnitudes(MeasurementPointSet::Eighteen, magnitudes.clone());
bode_plot.update_phases(MeasurementPointSet::Eighteen, phases.clone());
}
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);
}
}
},
}
data_counter_clone_multi.fetch_add(1, Ordering::Relaxed);
data_counter_clone_sweep.fetch_add(1, Ordering::Relaxed);
}
});
@@ -129,11 +178,11 @@ pub async fn communicate_with_hardware(
select! {
Some(frequency) = run_impedancemeter_rx.recv() => {
match frequency {
StartStopSignal::StartSingle(freq, dft_num) => {
match workbook_client.start_impedancemeter_single(freq, dft_num).await {
StartStopSignal::StartSingle(freq, lead_mode, dft_num) => {
match workbook_client.start_impedancemeter_single(freq, lead_mode, 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, lead_mode, dft_num));
*periods_per_dft.lock().unwrap() = Some(periods);
},
Ok(Err(e)) => {
@@ -146,27 +195,27 @@ pub async fn communicate_with_hardware(
}
}
},
StartStopSignal::StartMulti(num_points) => {
match workbook_client.start_impedancemeter_multi(num_points).await {
StartStopSignal::StartSweep(lead_mode, num_points) => {
match workbook_client.start_impedancemeter_sweep(lead_mode, num_points).await {
Ok(Ok(periods)) => {
settings.frequency = Some(StartStopSignal::StartMulti(num_points));
info!("Multi-point Impedancemeter started.");
settings.lock().unwrap().frequency = Some(StartStopSignal::StartSweep(lead_mode, num_points));
info!("Sweep 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()));
*periods_per_dft_sweep.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()));
*periods_per_dft_sweep.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);
error!("Failed to sweep-init on hardware: {:?}", e);
*periods_per_dft_sweep.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);
*periods_per_dft_sweep.lock().unwrap() = (num_points.values().iter().copied().collect(), None);
}
}
},
@@ -174,10 +223,10 @@ 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);
let (freq, _) = periods_per_dft_sweep.lock().unwrap().clone();
*periods_per_dft_sweep.lock().unwrap() = (freq, None);
info!("Impedancemeter stopped.");
}
},

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 {

118
src/logging.rs Normal file
View File

@@ -0,0 +1,118 @@
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 rfd::AsyncFileDialog;
use crate::signals::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 {
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::SweepImpedance(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) => {
// 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;
while path.exists() {
counter += 1;
path = if ext.is_empty() {
log_dir.join(format!("{}_{}", base, counter))
} else {
log_dir.join(format!("{}_{}.{}", base, counter, ext))
};
}
// Create the file asynchronously
match File::create(&path).await {
Ok(f) => {
info!("Started file logging to: {}", path.display());
file = Some(f);
}
Err(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;
}
}
}
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,8 +1,17 @@
use crate::icd::{IcdDftNum, MeasurementPointSet};
use std::time::SystemTime;
#[derive(Copy, Clone)]
use crate::icd::{BioImpedanceLeadMode, IcdDftNum, MeasurementPointSet};
#[derive(Copy, Clone, Debug)]
pub enum StartStopSignal {
StartSingle(u32, IcdDftNum), // frequency in Hz, DFT number
StartMulti(MeasurementPointSet), // DFT number, number of points per measurement
StartSingle(u32, BioImpedanceLeadMode, IcdDftNum), // frequency in Hz, lead mode, DFT number
StartSweep(BioImpedanceLeadMode, MeasurementPointSet), // lead mode, number of points per measurement
Stop,
}
pub enum LoggingSignal {
SingleImpedance(SystemTime, u32, f32, f32), // frequency, magnitude, phase
SweepImpedance(SystemTime, Vec<u32>, Vec<f32>, Vec<f32>), // frequency, magnitude, phase
StartFileLogging(String), // e.g. filename
StopFileLogging,
}