1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
|
import os
import sys
from typing import Any, Dict, Optional
from loguru import logger
from PyQt5.QtCore import QObject, QSettings, QThread, pyqtSignal, pyqtSlot, Qt
from PyQt5.QtGui import QCloseEvent
from PyQt5.QtWidgets import (
QApplication,
QCheckBox,
QComboBox,
QDoubleSpinBox,
QFileDialog,
QFormLayout,
QHBoxLayout,
QLabel,
QLineEdit,
QMainWindow,
QPushButton,
QSpinBox,
QVBoxLayout,
QWidget,
)
from picostream.cli import Streamer, VOLTAGE_RANGE_MAP
from picostream.dfplot import HDF5LivePlotter
class StreamerWorker(QObject):
"""Worker to run the data acquisition in a background thread."""
finished = pyqtSignal()
error = pyqtSignal(str)
stopRequested = pyqtSignal()
def __init__(self, settings: Dict[str, Any]) -> None:
"""Initialise the worker."""
super().__init__()
self.streamer: Optional[Streamer] = None
self.settings = settings
def run(self) -> None:
"""Run the data acquisition."""
try:
self.streamer = Streamer(**self.settings)
self.streamer.run()
except Exception as e:
self.error.emit(str(e))
self.finished.emit()
@pyqtSlot()
def stop(self) -> None:
"""Signal the acquisition to stop."""
if self.streamer:
self.streamer.shutdown()
self.finished.emit()
class PicoStreamMainWindow(QMainWindow):
"""The main window for the PicoStream GUI application."""
def __init__(self) -> None:
"""Initialise the main window."""
super().__init__()
self.setWindowTitle("PicoStream")
self.setGeometry(100, 100, 1200, 600)
self.settings = QSettings("picostream", "PicoStream")
self.thread: Optional[QThread] = None
self.worker: Optional[StreamerWorker] = None
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QHBoxLayout(central_widget)
# Left panel for settings
settings_panel = QWidget()
settings_panel.setFixedWidth(350)
settings_layout = QVBoxLayout(settings_panel)
form_layout = QFormLayout()
self.sample_rate_input = QDoubleSpinBox()
self.sample_rate_input.setRange(1, 125)
self.sample_rate_input.setValue(62.5)
self.sample_rate_input.setSuffix(" MS/s")
form_layout.addRow("Sample Rate:", self.sample_rate_input)
self.resolution_input = QComboBox()
self.resolution_input.addItems(["12", "14", "15", "16", "8"])
form_layout.addRow("Resolution (bits):", self.resolution_input)
self.voltage_range_input = QComboBox()
self.voltage_range_input.addItems(VOLTAGE_RANGE_MAP.values())
form_layout.addRow("Voltage Range:", self.voltage_range_input)
self.output_file_input = QLineEdit()
self.output_file_input.setText("output.hdf5")
file_browse_button = QPushButton("Browse...")
file_browse_button.clicked.connect(self.select_output_file)
file_layout = QHBoxLayout()
file_layout.addWidget(self.output_file_input)
file_layout.addWidget(file_browse_button)
form_layout.addRow("Output File:", file_layout)
self.hw_downsample_input = QSpinBox()
self.hw_downsample_input.setRange(1, 1000)
form_layout.addRow("HW Downsample:", self.hw_downsample_input)
self.downsample_mode_input = QComboBox()
self.downsample_mode_input.addItems(["average", "aggregate"])
form_layout.addRow("Downsample Mode:", self.downsample_mode_input)
self.offset_v_input = QDoubleSpinBox()
self.offset_v_input.setRange(-1.0, 1.0)
self.offset_v_input.setSingleStep(0.01)
self.offset_v_input.setDecimals(3)
self.offset_v_input.setSuffix(" V")
form_layout.addRow("Offset:", self.offset_v_input)
self.live_only_checkbox = QCheckBox("Live-only (overwrite buffer)")
self.max_buffer_input = QDoubleSpinBox()
self.max_buffer_input.setRange(0.1, 60.0)
self.max_buffer_input.setValue(1.0)
self.max_buffer_input.setSuffix(" s")
self.live_only_checkbox.stateChanged.connect(
lambda state: self.max_buffer_input.setEnabled(state > 0)
)
form_layout.addRow(self.live_only_checkbox, self.max_buffer_input)
settings_layout.addLayout(form_layout)
self.start_button = QPushButton("Start Acquisition")
self.stop_button = QPushButton("Stop Acquisition")
self.stop_button.setEnabled(False)
settings_layout.addWidget(self.start_button)
settings_layout.addWidget(self.stop_button)
settings_layout.addStretch()
# Right panel for the plot
self.plotter = HDF5LivePlotter(hdf5_path=self.output_file_input.text())
main_layout.addWidget(settings_panel)
main_layout.addWidget(self.plotter, 1)
# Connect signals
self.start_button.clicked.connect(self.start_acquisition)
self.stop_button.clicked.connect(self.stop_acquisition)
self.output_file_input.textChanged.connect(self.plotter.set_hdf5_path)
self.load_settings()
def select_output_file(self) -> None:
"""Open a dialog to select the output HDF5 file."""
file_name, _ = QFileDialog.getSaveFileName(
self, "Select Output File", self.output_file_input.text(), "HDF5 Files (*.hdf5)"
)
if file_name:
self.output_file_input.setText(file_name)
def start_acquisition(self) -> None:
"""Start the background data acquisition."""
self.start_button.setEnabled(False)
self.stop_button.setEnabled(True)
output_file = self.output_file_input.text()
# Reset plotter state and ensure a clean file for the new acquisition.
self.plotter.set_hdf5_path(output_file)
if os.path.exists(output_file):
try:
os.remove(output_file)
except OSError as e:
self.on_acquisition_error(f"Failed to remove old file: {e}")
self.on_acquisition_finished() # Reset UI state
return
settings = {
"sample_rate_msps": self.sample_rate_input.value(),
"resolution_bits": int(self.resolution_input.currentText()),
"channel_range_str": self.voltage_range_input.currentText(),
"output_file": output_file,
"hardware_downsample": self.hw_downsample_input.value(),
"downsample_mode": self.downsample_mode_input.currentText(),
"offset_v": self.offset_v_input.value(),
"max_buffer_seconds": self.max_buffer_input.value()
if self.live_only_checkbox.isChecked()
else None,
"enable_live_plot": False,
"is_gui_mode": True,
}
self.thread = QThread()
self.worker = StreamerWorker(settings)
self.worker.moveToThread(self.thread)
self.worker.stopRequested.connect(self.worker.stop, Qt.QueuedConnection)
self.thread.started.connect(self.worker.run)
self.worker.finished.connect(self.thread.quit)
self.worker.finished.connect(self.worker.deleteLater)
self.thread.finished.connect(self.thread.deleteLater)
self.worker.finished.connect(self.on_acquisition_finished)
self.worker.error.connect(self.on_acquisition_error)
self.thread.start()
self.plotter.start_updates()
def stop_acquisition(self) -> None:
"""Stop the background data acquisition."""
self.plotter.stop_updates()
if self.worker:
self.worker.stopRequested.emit()
self.stop_button.setEnabled(False)
def on_acquisition_finished(self) -> None:
"""Handle acquisition completion (both success and failure)."""
logger.info("Acquisition finished.")
self.plotter.stop_updates()
self.start_button.setEnabled(True)
self.stop_button.setEnabled(False)
self.thread = None
self.worker = None
def on_acquisition_error(self, err_msg: str) -> None:
"""Handle acquisition error."""
logger.error(f"Acquisition error: {err_msg}")
# In a real app, this would show a QMessageBox.
# The UI state is reset in on_acquisition_finished.
def closeEvent(self, event: QCloseEvent) -> None:
"""Handle window close event."""
self.save_settings()
if self.thread and self.thread.isRunning():
self.stop_acquisition()
self.thread.wait() # Wait for the thread to finish
event.accept()
def save_settings(self) -> None:
"""Save current settings."""
self.settings.setValue("sample_rate", self.sample_rate_input.value())
self.settings.setValue("resolution", self.resolution_input.currentText())
self.settings.setValue("voltage_range", self.voltage_range_input.currentText())
self.settings.setValue("output_file", self.output_file_input.text())
self.settings.setValue("hw_downsample", self.hw_downsample_input.value())
self.settings.setValue("downsample_mode", self.downsample_mode_input.currentText())
self.settings.setValue("offset_v", self.offset_v_input.value())
self.settings.setValue("live_only_mode", self.live_only_checkbox.isChecked())
self.settings.setValue("max_buffer_seconds", self.max_buffer_input.value())
def load_settings(self) -> None:
"""Load settings."""
self.sample_rate_input.setValue(self.settings.value("sample_rate", 62.5, type=float))
self.resolution_input.setCurrentText(self.settings.value("resolution", "12"))
self.voltage_range_input.setCurrentText(
self.settings.value("voltage_range", "PS5000A_20V")
)
self.output_file_input.setText(self.settings.value("output_file", "output.hdf5"))
self.hw_downsample_input.setValue(self.settings.value("hw_downsample", 1, type=int))
self.downsample_mode_input.setCurrentText(
self.settings.value("downsample_mode", "average")
)
self.offset_v_input.setValue(self.settings.value("offset_v", 0.0, type=float))
live_only = self.settings.value("live_only_mode", False, type=bool)
self.live_only_checkbox.setChecked(live_only)
self.max_buffer_input.setValue(
self.settings.value("max_buffer_seconds", 1.0, type=float)
)
self.max_buffer_input.setEnabled(live_only)
def main() -> None:
"""GUI entry point."""
logger.remove()
logger.add(sys.stderr, level="INFO")
app = QApplication(sys.argv)
main_win = PicoStreamMainWindow()
main_win.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
|