Skip to content

Commit 0b3a3fb

Browse files
Added perform_DAQ() into Arduino class. Ditched current_date_time_strings()
1 parent 9e5ad7b commit 0b3a3fb

File tree

6 files changed

+141
-179
lines changed

6 files changed

+141
-179
lines changed

WaveGeneratorArduino.py

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@
99
__version__ = "9.0"
1010

1111
import time
12+
import datetime
1213

1314
from qtpy import QtCore
1415
import numpy as np
1516

17+
from dvg_debug_functions import dprint, print_fancy_traceback as pft
1618
from dvg_devices.Arduino_protocol_serial import Arduino
1719

1820
# ------------------------------------------------------------------------------
@@ -65,6 +67,35 @@ def set_waveform_to_sawtooth(self):
6567
"""Send the instruction to the Arduino to change to a sawtooth wave."""
6668
self.write("sawtooth")
6769

70+
def perform_DAQ(self) -> bool:
71+
"""Query the Arduino for new readings, parse them and update the
72+
corresponding variables of its `state` member.
73+
74+
Returns: True if successful, False otherwise.
75+
"""
76+
# Query the Arduino for its state
77+
success, reply = self.query_ascii_values("?", delimiter="\t")
78+
if not success:
79+
dprint(
80+
f"'{self.name}' reports IOError @ "
81+
f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
82+
)
83+
return False
84+
85+
# Parse readings into separate state variables
86+
try:
87+
self.state.time, self.state.reading_1 = reply
88+
self.state.time /= 1000
89+
except Exception as err: # pylint: disable=broad-except
90+
pft(err, 3)
91+
dprint(
92+
f"'{self.name}' reports IOError @ "
93+
f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
94+
)
95+
return False
96+
97+
return True
98+
6899

69100
# ------------------------------------------------------------------------------
70101
# FakeWaveGeneratorArduino
@@ -114,23 +145,25 @@ def set_waveform_to_sawtooth(self):
114145
"""Send the instruction to the Arduino to change to a sine wave."""
115146
self.wave_type = "sawtooth"
116147

117-
def query_ascii_values(self, *args, **kwargs):
118-
"""Query the Arduino for new readings and return them as a list."""
148+
def perform_DAQ(self) -> bool:
149+
"""Query the Arduino for new readings, parse them and update the
150+
corresponding variables of its `state` member.
151+
152+
Returns: True if successful, False otherwise.
153+
"""
119154
t = time.perf_counter()
120155

121156
if self.wave_type == "sine":
122157
value = np.sin(2 * np.pi * self.wave_freq * t)
123-
124158
elif self.wave_type == "square":
125159
value = 1 if np.mod(self.wave_freq * t, 1.0) > 0.5 else -1
126-
127160
elif self.wave_type == "sawtooth":
128161
value = 2 * np.mod(self.wave_freq * t, 1.0) - 1
129162

130-
success = True
131-
readings = [t * 1000, value]
163+
self.state.time = t * 1000
164+
self.state.reading_1 = value
132165

133-
return success, readings
166+
return True
134167

135168
def close(self):
136169
"""Close the serial connection to the Arduino."""

demo_A_GUI_full.py

Lines changed: 17 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import os
1414
import sys
1515
import time
16+
import datetime
1617

1718
import qtpy
1819
from qtpy import QtCore, QtGui, QtWidgets as QtWid
@@ -21,7 +22,7 @@
2122
import psutil
2223
import pyqtgraph as pg
2324

24-
from dvg_debug_functions import tprint, dprint, print_fancy_traceback as pft
25+
from dvg_debug_functions import tprint
2526
from dvg_pyqtgraph_threadsafe import HistoryChartCurve, PlotManager
2627
from dvg_pyqt_filelogger import FileLogger
2728
import dvg_pyqt_controls as controls
@@ -72,19 +73,6 @@
7273
# pg.setConfigOptions(leftButtonPan=False)
7374
pg.setConfigOption("foreground", "#EEE")
7475

75-
# ------------------------------------------------------------------------------
76-
# current_date_time_strings
77-
# ------------------------------------------------------------------------------
78-
79-
80-
def current_date_time_strings():
81-
cur_date_time = QtCore.QDateTime.currentDateTime()
82-
return (
83-
cur_date_time.toString("dd-MM-yyyy"), # Date
84-
cur_date_time.toString("HH:mm:ss"), # Time
85-
)
86-
87-
8876
# ------------------------------------------------------------------------------
8977
# MainWindow
9078
# ------------------------------------------------------------------------------
@@ -354,10 +342,11 @@ def process_qpbt_running(self, state: bool):
354342

355343
@Slot()
356344
def update_GUI(self):
357-
str_cur_date, str_cur_time = current_date_time_strings()
358345
state = self.qdev.dev.state # Shorthand
359346

360-
self.qlbl_cur_date_time.setText(f"{str_cur_date} {str_cur_time}")
347+
self.qlbl_cur_date_time.setText(
348+
f"{datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S')}"
349+
)
361350
self.qlbl_update_counter.setText(f"{self.qdev.update_counter_DAQ}")
362351
self.qlbl_DAQ_rate.setText(
363352
f"DAQ: {self.qdev.obtained_DAQ_rate_Hz:.1f} Hz"
@@ -435,27 +424,14 @@ def update_chart(self):
435424
# --------------------------------------------------------------------------
436425

437426
def DAQ_function() -> bool:
438-
# Query the Arduino for its state
439-
success, tmp_state = ard.query_ascii_values("?", delimiter="\t")
440-
if not success:
441-
str_cur_date, str_cur_time = current_date_time_strings()
442-
dprint(
443-
f"'{ard.name}' reports IOError @ "
444-
f"{str_cur_date} {str_cur_time}"
445-
)
446-
return False
447-
448-
# Parse readings into separate state variables
449-
try:
450-
ard.state.time, ard.state.reading_1 = tmp_state
451-
ard.state.time /= 1000
452-
except Exception as err: # pylint: disable=broad-except
453-
pft(err, 3)
454-
str_cur_date, str_cur_time = current_date_time_strings()
455-
dprint(
456-
f"'{ard.name}' reports IOError @ "
457-
f"{str_cur_date} {str_cur_time}"
458-
)
427+
"""Perform a single data acquisition and append this data to the chart
428+
and log.
429+
430+
Returns: True if successful, False otherwise.
431+
"""
432+
# Query the Arduino for new readings, parse them and update the
433+
# corresponding variables of its `state` member.
434+
if not ard.perform_DAQ():
459435
return False
460436

461437
# Use Arduino time or PC time?
@@ -474,7 +450,6 @@ def DAQ_function() -> bool:
474450
# Add readings to the log
475451
log.update()
476452

477-
# Return success
478453
return True
479454

480455
ard_qdev = WaveGeneratorArduino_qdev(
@@ -535,8 +510,10 @@ def notify_connection_lost():
535510
stop_running()
536511

537512
window.qlbl_title.setText("! ! ! LOST CONNECTION ! ! !")
538-
str_cur_date, str_cur_time = current_date_time_strings()
539-
str_msg = f"{str_cur_date} {str_cur_time}\nLost connection to Arduino."
513+
str_msg = (
514+
f"{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
515+
"Lost connection to Arduino."
516+
)
540517
print(f"\nCRITICAL ERROR @ {str_msg}")
541518
reply = QtWid.QMessageBox.warning(
542519
window, "CRITICAL ERROR", str_msg, QtWid.QMessageBox.Ok

demo_B_GUI_minimal.py

Lines changed: 6 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
import psutil
2222
import pyqtgraph as pg
2323

24-
from dvg_debug_functions import dprint, print_fancy_traceback as pft
2524
from dvg_pyqtgraph_threadsafe import HistoryChartCurve
2625

2726
from WaveGeneratorArduino import WaveGeneratorArduino, FakeWaveGeneratorArduino
@@ -69,19 +68,6 @@
6968
# pg.setConfigOptions(leftButtonPan=False)
7069
pg.setConfigOption("foreground", "#EEE")
7170

72-
# ------------------------------------------------------------------------------
73-
# current_date_time_strings
74-
# ------------------------------------------------------------------------------
75-
76-
77-
def current_date_time_strings():
78-
cur_date_time = QtCore.QDateTime.currentDateTime()
79-
return (
80-
cur_date_time.toString("dd-MM-yyyy"), # Date
81-
cur_date_time.toString("HH:mm:ss"), # Time
82-
)
83-
84-
8571
# ------------------------------------------------------------------------------
8672
# MainWindow
8773
# ------------------------------------------------------------------------------
@@ -173,27 +159,13 @@ def __init__(self, parent=None, **kwargs):
173159
# --------------------------------------------------------------------------
174160

175161
def DAQ_function() -> bool:
176-
# Query the Arduino for its state
177-
success, tmp_state = ard.query_ascii_values("?", delimiter="\t")
178-
if not success:
179-
str_cur_date, str_cur_time = current_date_time_strings()
180-
dprint(
181-
f"'{ard.name}' reports IOError @ "
182-
f"{str_cur_date} {str_cur_time}"
183-
)
184-
return False
162+
"""Perform a single data acquisition and append this data to the chart.
185163
186-
# Parse readings into separate state variables
187-
try:
188-
ard.state.time, ard.state.reading_1 = tmp_state
189-
ard.state.time /= 1000
190-
except Exception as err: # pylint: disable=broad-except
191-
pft(err, 3)
192-
str_cur_date, str_cur_time = current_date_time_strings()
193-
dprint(
194-
f"'{ard.name}' reports IOError @ "
195-
f"{str_cur_date} {str_cur_time}"
196-
)
164+
Returns: True if successful, False otherwise.
165+
"""
166+
# Query the Arduino for new readings, parse them and update the
167+
# corresponding variables of its `state` member.
168+
if not ard.perform_DAQ():
197169
return False
198170

199171
# Use Arduino time or PC time?
@@ -209,7 +181,6 @@ def DAQ_function() -> bool:
209181
ard.state.time, ard.state.reading_1
210182
)
211183

212-
# Return success
213184
return True
214185

215186
ard_qdev = WaveGeneratorArduino_qdev(

demo_C_singlethread_for_comparison.py

Lines changed: 20 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import os
2121
import sys
2222
import time
23+
import datetime
2324
from typing import Union
2425

2526
import qtpy
@@ -30,7 +31,7 @@
3031
import numpy as np
3132
import pyqtgraph as pg
3233

33-
from dvg_debug_functions import tprint, dprint, print_fancy_traceback as pft
34+
from dvg_debug_functions import tprint
3435
from dvg_pyqtgraph_threadsafe import HistoryChartCurve, PlotManager
3536
from dvg_pyqt_filelogger import FileLogger
3637
import dvg_pyqt_controls as controls
@@ -91,19 +92,6 @@
9192
QET_rate = QtCore.QElapsedTimer()
9293
rate_accumulator = 0
9394

94-
# ------------------------------------------------------------------------------
95-
# current_date_time_strings
96-
# ------------------------------------------------------------------------------
97-
98-
99-
def current_date_time_strings():
100-
cur_date_time = QtCore.QDateTime.currentDateTime()
101-
return (
102-
cur_date_time.toString("dd-MM-yyyy"), # Date
103-
cur_date_time.toString("HH:mm:ss"), # Time
104-
)
105-
106-
10795
# ------------------------------------------------------------------------------
10896
# MainWindow
10997
# ------------------------------------------------------------------------------
@@ -348,10 +336,11 @@ def process_qpbt_running(self, state: bool):
348336

349337
@Slot()
350338
def update_GUI(self):
351-
str_cur_date, str_cur_time = current_date_time_strings()
352339
state = self.dev.state # Shorthand
353340

354-
self.qlbl_cur_date_time.setText(f"{str_cur_date} {str_cur_time}")
341+
self.qlbl_cur_date_time.setText(
342+
f"{datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S')}"
343+
)
355344
self.qlbl_update_counter.setText(f"{update_counter_DAQ}")
356345
self.qlbl_DAQ_rate.setText(f"DAQ: {obtained_DAQ_rate_Hz:.1f} Hz")
357346
self.qlbl_recording_time.setText(
@@ -370,6 +359,7 @@ def update_GUI(self):
370359
def update_chart(self):
371360
if not self.allow_GUI_update_of_readings:
372361
return
362+
373363
if DEBUG:
374364
tprint("update_curve")
375365

@@ -453,12 +443,14 @@ def write_data_to_log():
453443

454444
@Slot()
455445
def DAQ_function():
446+
"""Perform a single data acquisition and append this data to the chart
447+
and log.
448+
"""
449+
# Keep track of the obtained DAQ rate
456450
global update_counter_DAQ, rate_accumulator, obtained_DAQ_rate_Hz
457451

458-
state = ard.state # Shorthand
459452
update_counter_DAQ += 1
460453

461-
# Keep track of the obtained DAQ rate
462454
if not QET_rate.isValid():
463455
QET_rate.start()
464456
else:
@@ -475,37 +467,23 @@ def DAQ_function():
475467

476468
rate_accumulator = 0
477469

478-
# Query the Arduino for its state
479-
success, tmp_state = ard.query_ascii_values("?", delimiter="\t")
480-
if not success:
481-
str_cur_date, str_cur_time = current_date_time_strings()
482-
dprint(
483-
f"'{ard.name}' reports IOError @ {str_cur_date} {str_cur_time}"
484-
)
485-
sys.exit(0)
486-
487-
# Parse readings into separate state variables
488-
try:
489-
state.time, state.reading_1 = tmp_state
490-
state.time /= 1000
491-
except Exception as err: # pylint: disable=broad-except
492-
pft(err, 3)
493-
str_cur_date, str_cur_time = current_date_time_strings()
494-
dprint(
495-
f"'{ard.name}' reports IOError @ {str_cur_date} {str_cur_time}"
496-
)
470+
# Query the Arduino for new readings, parse them and update the
471+
# corresponding variables of its `state` member.
472+
if not ard.perform_DAQ():
497473
sys.exit(0)
498474

499475
# Use Arduino time or PC time?
500-
now = time.perf_counter() if USE_PC_TIME else state.time
476+
now = time.perf_counter() if USE_PC_TIME else ard.state.time
501477
if update_counter_DAQ == 1:
502-
state.time_0 = now
503-
state.time = 0
478+
ard.state.time_0 = now
479+
ard.state.time = 0
504480
else:
505-
state.time = now - state.time_0
481+
ard.state.time = now - ard.state.time_0
506482

507483
# Add readings to chart history
508-
window.history_chart_curve.appendData(state.time, state.reading_1)
484+
window.history_chart_curve.appendData(
485+
ard.state.time, ard.state.reading_1
486+
)
509487

510488
# Add readings to the log
511489
log.update()

0 commit comments

Comments
 (0)