-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction_generator_app.py
More file actions
1951 lines (1715 loc) · 76 KB
/
Copy pathfunction_generator_app.py
File metadata and controls
1951 lines (1715 loc) · 76 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Function Generator Control App
================================
Controls a multi-channel VISA-compatible function generator
for DEP / EROT / EOR experiments.
Requirements:
pip install PyQt5 pyvisa pyvisa-py
Run:
python function_generator_app.py
python function_generator_app.py --test # launch straight into test/virtual mode
"""
import sys
import time
import threading
import random
import math
import pyvisa
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QGridLayout, QLabel, QPushButton, QLineEdit, QComboBox,
QTextEdit, QGroupBox, QTabWidget, QFrame, QDoubleSpinBox,
QSpinBox, QCheckBox, QSizePolicy, QMessageBox, QScrollArea,
QSlider, QSplitter
)
from PyQt5.QtCore import Qt, pyqtSignal, QTimer, QObject
from PyQt5.QtGui import QTextCursor
# ─────────────────────────────────────────────────────────────
# STYLESHEET (dark oscilloscope aesthetic)
# ─────────────────────────────────────────────────────────────
STYLE = """
QMainWindow, QWidget {
background-color: #0d1117;
color: #c9d1d9;
font-family: 'Consolas', 'Courier New', monospace;
font-size: 13px;
}
QTabWidget::pane {
border: 1px solid #30363d;
background: #161b22;
}
QTabBar::tab {
background: #0d1117;
color: #8b949e;
padding: 8px 20px;
border: 1px solid #30363d;
border-bottom: none;
font-weight: bold;
letter-spacing: 1px;
font-size: 11px;
}
QTabBar::tab:selected {
background: #161b22;
color: #58a6ff;
border-top: 2px solid #58a6ff;
}
QTabBar::tab:hover:!selected { color: #c9d1d9; background: #1c2128; }
QGroupBox {
border: 1px solid #30363d;
border-radius: 4px;
margin-top: 12px;
padding-top: 8px;
font-weight: bold;
color: #8b949e;
letter-spacing: 1px;
font-size: 11px;
}
QGroupBox::title {
subcontrol-origin: margin;
left: 10px;
padding: 0 6px;
color: #58a6ff;
}
QPushButton {
background-color: #21262d;
color: #c9d1d9;
border: 1px solid #30363d;
border-radius: 4px;
padding: 7px 16px;
font-weight: bold;
letter-spacing: 0.5px;
}
QPushButton:hover { background-color: #30363d; color: #fff; }
QPushButton:pressed { background-color: #388bfd22; border-color: #58a6ff; }
QPushButton:disabled { color: #484f58; border-color: #21262d; }
QPushButton#btn_connect { background:#1a4a1a; border-color:#238636; color:#3fb950; }
QPushButton#btn_connect:hover { background:#1f6623; }
QPushButton#btn_disconnect { background:#4a1a1a; border-color:#da3633; color:#f85149; }
QPushButton#btn_disconnect:hover { background:#6e2222; }
QPushButton#btn_start {
background:#0d419d; border-color:#388bfd; color:#58a6ff;
font-size:14px; padding:10px 24px;
}
QPushButton#btn_start:hover { background:#1158c7; }
QPushButton#btn_stop {
background:#6e2222; border-color:#da3633; color:#f85149;
font-size:14px; padding:10px 24px;
}
QPushButton#btn_stop:hover { background:#922a2a; }
QPushButton#btn_output_on { background:#1a4a1a; border-color:#238636; color:#3fb950; }
QPushButton#btn_output_off { background:#4a1a1a; border-color:#da3633; color:#f85149; }
QPushButton#btn_testmode {
background:#2a1a4a; border-color:#8957e5; color:#d2a8ff;
font-weight:bold; letter-spacing:1px;
}
QPushButton#btn_testmode:hover { background:#3d2470; }
QPushButton#btn_testmode_active {
background:#3d2470; border-color:#d2a8ff; color:#d2a8ff;
font-weight:bold;
}
QLineEdit, QDoubleSpinBox, QSpinBox, QComboBox {
background:#0d1117; border:1px solid #30363d; border-radius:3px;
color:#c9d1d9; padding:5px 8px; selection-background-color:#388bfd;
}
QLineEdit:focus, QDoubleSpinBox:focus, QSpinBox:focus, QComboBox:focus {
border-color:#58a6ff;
}
QComboBox::drop-down { border:none; }
QComboBox QAbstractItemView {
background:#161b22; border:1px solid #30363d;
selection-background-color:#388bfd;
}
QTextEdit {
background:#0d1117; border:1px solid #30363d; border-radius:3px;
color:#3fb950; font-family:'Consolas',monospace; font-size:12px; padding:6px;
}
QLabel#ch1 { color:#f7c948; }
QLabel#ch2 { color:#58a6ff; }
QLabel#ch3 { color:#3fb950; }
QLabel#ch4 { color:#f85149; }
QLabel#status_ok { color:#3fb950; font-weight:bold; }
QLabel#status_test { color:#d2a8ff; font-weight:bold; }
QLabel#status_err { color:#f85149; font-weight:bold; }
QLabel#status_idle { color:#8b949e; }
QFrame#separator { background:#30363d; max-height:1px; margin:4px 0; }
QSlider::groove:horizontal { height:4px; background:#30363d; border-radius:2px; }
QSlider::handle:horizontal {
background:#58a6ff; width:14px; height:14px; margin:-5px 0; border-radius:7px;
}
QSlider::sub-page:horizontal { background:#388bfd; border-radius:2px; }
QSplitter::handle:horizontal {
background: #30363d;
width: 4px;
}
QSplitter::handle:horizontal:hover { background: #58a6ff; }
QSplitter::handle:vertical {
background: #30363d;
height: 4px;
}
QSplitter::handle:vertical:hover { background: #58a6ff; }
"""
CH_COLORS = {1: '#f7c948', 2: '#58a6ff', 3: '#3fb950', 4: '#f85149'}
# ─────────────────────────────────────────────────────────────
# VIRTUAL INSTRUMENT (test mode — no hardware needed)
# ─────────────────────────────────────────────────────────────
class VirtualChannel:
"""Simulates a single output channel."""
def __init__(self, ch: int):
self.ch = ch
self.freq = 1000.0
self.volt = 1.0
self.phase = 0.0
self.enabled = False
def summary(self):
state = "ON " if self.enabled else "OFF"
return (f"CH{self.ch} [{state}] "
f"{self.freq:>12.3f} Hz "
f"{self.volt:.3f} Vpp "
f"{self.phase:>6.1f}°")
class VirtualInstrument:
"""
Drop-in replacement for a real VISA instrument.
Simulates command parsing, realistic noise on FREQ?, small
latency, and occasional (rare) comms errors to stress-test the UI.
"""
IDN = "VIRTUAL,FG-4CH-SIM,SN00000,FW1.0.0"
def __init__(self, error_rate: float = 0.0):
self._channels = {i: VirtualChannel(i) for i in range(1, 5)}
self._active_ch = 1
self._error_rate = error_rate # 0.0 … 1.0, probability of a fake comms error
self._closed = False
self.timeout = 5000
self.chunk_size = 1024
self.read_termination = '\n'
self.write_termination = '\n'
def _maybe_fail(self):
if self._error_rate > 0 and random.random() < self._error_rate:
raise IOError("VIRTUAL: simulated communications error")
def write(self, cmd: str):
self._maybe_fail()
time.sleep(0.005) # simulate bus latency
cmd = cmd.strip()
if cmd.startswith(':INST:SEL'):
try:
self._active_ch = int(cmd.split()[-1])
except ValueError:
pass
elif cmd.startswith('FREQ '):
self._channels[self._active_ch].freq = float(cmd.split()[1])
elif cmd.startswith('VOLT '):
self._channels[self._active_ch].volt = float(cmd.split()[1])
elif 'PHASe' in cmd:
self._channels[self._active_ch].phase = float(cmd.split()[-1])
elif cmd == 'OUTP ON':
self._channels[self._active_ch].enabled = True
elif cmd == 'OUTP OFF':
self._channels[self._active_ch].enabled = False
def query(self, cmd: str) -> str:
self._maybe_fail()
time.sleep(0.010)
cmd = cmd.strip()
if cmd == '*IDN?':
return self.IDN
if cmd == 'FREQ?':
ch = self._channels[self._active_ch]
# add ±0.01 % noise so queries look realistic
noise = ch.freq * random.uniform(-0.0001, 0.0001)
return f"{ch.freq + noise:.6f}"
return "0"
def close(self):
self._closed = True
def state_snapshot(self) -> list[str]:
"""Returns human-readable channel state lines for the test panel."""
return [ch.summary() for ch in self._channels.values()]
# ─────────────────────────────────────────────────────────────
# INSTRUMENT WORKER
# - Pure Python object (no QThread), all heavy methods called
# from daemon threads via threading.Thread.
# - A threading.Lock serialises every VISA / virtual call so
# connect / disconnect / run_* never race each other.
# ─────────────────────────────────────────────────────────────
class InstrumentWorker(QObject):
log_signal = pyqtSignal(str)
error_signal = pyqtSignal(str)
done_signal = pyqtSignal(str) # carries mode string: 'erot'|'dep'|'eor'|'free'
freq_signal = pyqtSignal(int, float) # (step_index, measured_freq)
def __init__(self):
super().__init__()
self.rm = None
self.inst = None # real Resource OR VirtualInstrument
self._lock = threading.Lock()
self._stop_flag = False
self._test_mode = False
self._ch_state = {} # {ch: {freq, volt, phase, enabled}} — updated by run_*
# ── connection ──────────────────────────────────────────
def connect(self, resource_string: str, buffer_size: int = 1024,
timeout_ms: int = 5000) -> bool:
try:
with self._lock:
self.rm = pyvisa.ResourceManager()
self.inst = self.rm.open_resource(resource_string)
self.inst.read_termination = '\n'
self.inst.write_termination = '\n'
self.inst.timeout = timeout_ms
self.inst.chunk_size = buffer_size
idn = self.inst.query('*IDN?').strip()
self._test_mode = False
self.log_signal.emit(f"[CONNECTED] {idn}")
return True
except Exception as e:
self.error_signal.emit(f"[ERROR] Connection failed: {e}")
return False
def connect_virtual(self, error_rate: float = 0.0) -> bool:
"""Connect to the built-in virtual instrument (no hardware required)."""
with self._lock:
self.inst = VirtualInstrument(error_rate=error_rate)
self.rm = None
self._test_mode = True
self.log_signal.emit(
f"[TEST MODE] Virtual instrument connected "
f"(error_rate={error_rate*100:.0f}%)"
)
return True
def disconnect(self):
self._stop_flag = True # halt any running sweep first
try:
with self._lock:
if self.inst:
try:
self.inst.write('OUTP OFF')
except Exception:
pass
self.inst.close()
if self.rm:
self.rm.close()
self.inst = None
self.rm = None
self._test_mode = False
self.log_signal.emit("[DISCONNECTED]")
except Exception as e:
self.error_signal.emit(f"[ERROR] Disconnect: {e}")
def list_resources(self) -> list:
try:
rm = pyvisa.ResourceManager()
res = rm.list_resources()
rm.close()
return list(res)
except Exception as e:
self.error_signal.emit(f"[ERROR] Listing resources: {e}")
return []
# ── low-level helpers ────────────────────────────────────
def _write(self, cmd: str, verbose: bool = True):
if not self.inst:
self.error_signal.emit("[ERROR] No instrument connected.")
return
with self._lock:
self.inst.write(cmd)
if verbose:
self.log_signal.emit(f" >> {cmd}")
def _query(self, cmd: str, verbose: bool = True) -> str:
if not self.inst:
self.error_signal.emit("[ERROR] No instrument connected.")
return "0"
with self._lock:
resp = self.inst.query(cmd).strip()
if verbose:
self.log_signal.emit(f" >> {cmd} << {resp}")
return resp
def _sel(self, ch: int, verbose: bool = True):
self._write(f':INST:SEL {ch}', verbose=verbose)
def _setup_channel(self, ch: int, freq_hz: float, volt: float, phase_deg: float,
verbose: bool = True):
"""Configure one channel and turn its output on.
volt is in Vpp — SCPI VOLT command on these generators is peak-to-peak by default.
Use VOLT:UNIT VPP to make this explicit if your instrument supports it.
"""
self._sel(ch, verbose=verbose)
self._write(f'FREQ {freq_hz}', verbose=verbose)
self._write(f'VOLT {volt}', verbose=verbose) # Vpp
self._write(f'SINusoid:PHASe {phase_deg}', verbose=verbose)
self._write('OUTP ON', verbose=verbose)
self._update_tracked_state(ch, freq_hz, volt, phase_deg, True)
# ── output master switch ─────────────────────────────────
def all_output(self, state: bool):
if not self.inst:
self.error_signal.emit("[ERROR] No instrument connected.")
return
cmd = 'ON' if state else 'OFF'
for ch in range(1, 5):
self._sel(ch)
self._write(f'OUTP {cmd}')
if ch in self._ch_state:
self._ch_state[ch]['enabled'] = state
self.log_signal.emit(f"[OUTPUT {'ON' if state else 'OFF'}] all channels")
# ── EROT sweep ───────────────────────────────────────────
def run_erot(self, frequencies: list, volt: float, dwell_s: float,
summary_only: bool = False,
ch_order: tuple = (1, 2, 3, 4)):
"""4-channel 90° phase quadrature sweep.
ch_order defines which physical channel receives each successive 90°
phase step (0°, 90°, 180°, 270°). The default (1,2,3,4) is the
standard assignment. To reverse rotation direction pass (1,4,3,2),
which routes 0°→CH1, 90°→CH4, 180°→CH3, 270°→CH2.
summary_only: when True, individual SCPI command lines are suppressed.
"""
self._stop_flag = False
phase_steps = [0, 90, 180, 270]
# Build {channel: phase} mapping from ch_order
ch_phase_map = {ch: phase_steps[i] for i, ch in enumerate(ch_order)}
verbose = not summary_only
measured = []
try:
direction = "CW (1→4→3→2)" if ch_order == (1,4,3,2) else "CCW (1→2→3→4)"
self.log_signal.emit(f"[EROT] Starting sweep — rotation {direction} …")
for idx, freq in enumerate(frequencies):
if self._stop_flag or not self.inst:
self.log_signal.emit("[EROT] Sweep aborted (stop or disconnect).")
self.all_output(False)
break
for ch in sorted(ch_phase_map):
self._setup_channel(ch, freq, volt, ch_phase_map[ch], verbose=verbose)
# query measured freq on CH1
self._sel(1, verbose=verbose)
meas = float(self._query('FREQ?', verbose=verbose))
measured.append(meas)
self.freq_signal.emit(idx, meas)
# one clean summary line regardless of verbosity
self.log_signal.emit(
f"[EROT] Step {idx+1}/{len(frequencies)} "
f"set={freq:.3f} Hz meas={meas:.3f} Hz"
)
# dwell — no countdown, just sleep
elapsed = 0
while elapsed < dwell_s:
if self._stop_flag:
break
time.sleep(min(1.0, dwell_s - elapsed))
elapsed += 1.0
if not self._stop_flag:
self.all_output(False)
if measured:
avg = sum(measured) / len(measured)
self.log_signal.emit(
f"[EROT] Sweep complete — "
f"{len(measured)} steps avg measured={avg:.3f} Hz"
)
else:
self.log_signal.emit("[EROT] Sweep complete.")
except Exception as e:
self.error_signal.emit(f"[EROT ERROR] {e}")
finally:
self.done_signal.emit("erot")
# ── DEP ──────────────────────────────────────────────────
def run_dep(self, freq: float, volt: float):
"""All 4 channels same freq, same phase (0°)."""
self._stop_flag = False
try:
if not self.inst:
self.log_signal.emit("[DEP] Aborted — no instrument connected.")
return
self.log_signal.emit(f"[DEP] f={freq} Hz V={volt} Vpp")
for ch in range(1, 5):
self._setup_channel(ch, freq, volt, 0)
self.log_signal.emit("[DEP] Applied.")
except Exception as e:
self.error_signal.emit(f"[DEP ERROR] {e}")
finally:
self.done_signal.emit("dep")
# ── EOR ──────────────────────────────────────────────────
def run_eor(self, pair: str, freq: float, volt: float):
"""
pair='13': CH1 ON (0°), CH3 ON (180°), CH2/4 OFF
pair='24': CH2 ON (0°), CH4 ON (180°), CH1/3 OFF
"""
self._stop_flag = False
try:
if not self.inst:
self.log_signal.emit("[EOR] Aborted — no instrument connected.")
return
active = (1, 3) if pair == '13' else (2, 4)
inactive = (2, 4) if pair == '13' else (1, 3)
self.log_signal.emit(
f"[EOR] pair={pair} f={freq} Hz V={volt} Vpp"
)
for ch in inactive:
self._sel(ch)
self._write('OUTP OFF')
for ch, ph in zip(active, [0, 180]):
self._setup_channel(ch, freq, volt, ph)
self.log_signal.emit(
f"[EOR] CH{active[0]} (0°) and CH{active[1]} (180°) active."
)
except Exception as e:
self.error_signal.emit(f"[EOR ERROR] {e}")
finally:
self.done_signal.emit("eor")
# ── FREE mode ────────────────────────────────────────────
def run_free(self, channels: list):
"""channels: list of dicts {ch, freq, volt, phase, enabled}"""
self._stop_flag = False
try:
if not self.inst:
self.log_signal.emit("[FREE] Aborted — no instrument connected.")
return
self.log_signal.emit("[FREE] Applying custom channel settings …")
for cfg in channels:
self._sel(cfg['ch'])
if cfg['enabled']:
self._write(f"FREQ {cfg['freq']}")
self._write(f"VOLT {cfg['volt']}")
self._write(f"SINusoid:PHASe {cfg['phase']}")
self._write('OUTP ON')
else:
self._write('OUTP OFF')
self.log_signal.emit("[FREE] Done.")
except Exception as e:
self.error_signal.emit(f"[FREE ERROR] {e}")
finally:
self.done_signal.emit("free")
# ── channel state tracking (for live panel) ─────────────
# Updated after every run_* so LivePanel can poll it
# regardless of whether we are in real or virtual mode.
def _update_tracked_state(self, ch: int, freq: float, volt: float,
phase: float, enabled: bool):
self._ch_state[ch] = {
'freq': freq, 'volt': volt,
'phase': phase, 'enabled': enabled
}
def get_channel_state(self) -> list:
"""Returns a list of VirtualChannel-like objects for LivePanel.
Works in both real and virtual mode."""
with self._lock:
if self._test_mode and isinstance(self.inst, VirtualInstrument):
import copy
return [copy.copy(ch) for ch in self.inst._channels.values()]
# real mode: return from tracked state
result = []
for i in range(1, 5):
s = self._ch_state.get(i)
if s:
vc = VirtualChannel(i)
vc.freq = s['freq']
vc.volt = s['volt']
vc.phase = s['phase']
vc.enabled = s['enabled']
result.append(vc)
return result
def get_channel_state_lines(self) -> list:
"""Returns summary strings for LivePanel labels."""
with self._lock:
if self._test_mode and isinstance(self.inst, VirtualInstrument):
return self.inst.state_snapshot()
lines = []
for i in range(1, 5):
s = self._ch_state.get(i)
if s:
state = "ON " if s['enabled'] else "OFF"
lines.append(
f"CH{i} [{state}] "
f"{s['freq']:>12.3f} Hz "
f"{s['volt']:.3f} Vpp "
f"{s['phase']:>6.1f}°"
)
return lines
def stop(self):
self._stop_flag = True
def reset(self):
"""Clear the stop flag before launching any new command."""
self._stop_flag = False
# ── DC electrophoresis (Tabor WW5064) ────────────────────
def run_dc(self, channels: list):
"""
Apply DC voltage to selected channels on the Tabor WW5064.
The WW5064 is an arbitrary waveform generator; it has no FUNC DC
command. DC is produced by:
1. Selecting SINusoid waveform
2. Setting amplitude to 10 mVpp (minimum) so AC content is negligible
3. Setting VOLT:OFFS to the desired DC level (±5 V into 50 Ohm,
±10 V open circuit)
4. Turning output ON
channels: list of dicts {ch, dc_volts, dc_enabled}
Channels with dc_enabled=False have offset zeroed and output turned OFF.
"""
self._stop_flag = False
try:
if not self.inst:
self.log_signal.emit("[DC] Aborted — no instrument connected.")
return
self.log_signal.emit("[DC] Applying DC voltages …")
for cfg in channels:
self._sel(cfg['ch'])
if cfg['dc_enabled']:
v = cfg['dc_volts']
self._write('FUNCtion:SHAPe SINusoid')
self._write('VOLT 0.010')
self._write(f'VOLT:OFFS {v:.4f}')
self._write('OUTP ON')
self.log_signal.emit(
f" CH{cfg['ch']} DC = {v:+.4f} V ON"
)
self._update_tracked_state(cfg['ch'], 0.0, 0.010, 0.0, True)
else:
self._write('VOLT:OFFS 0')
self._write('OUTP OFF')
self.log_signal.emit(f" CH{cfg['ch']} DC = 0 V OFF")
self._update_tracked_state(cfg['ch'], 0.0, 0.0, 0.0, False)
self.log_signal.emit("[DC] Applied.")
except Exception as e:
self.error_signal.emit(f"[DC ERROR] {e}")
finally:
self.done_signal.emit("dc")
def clear_dc(self, channels: list):
"""Zero offsets and turn off outputs for the given channel list."""
try:
if not self.inst:
return
for ch in channels:
self._sel(ch)
self._write('VOLT:OFFS 0')
self._write('OUTP OFF')
self.log_signal.emit("[DC] Offsets cleared, outputs OFF.")
except Exception as e:
self.error_signal.emit(f"[DC CLEAR ERROR] {e}")
# ── legacy aliases (kept for any external callers) ──────
def get_virtual_state(self) -> list:
return self.get_channel_state_lines()
def get_virtual_channels(self) -> list:
return self.get_channel_state()
# ─────────────────────────────────────────────────────────────
# SHARED UI HELPERS
# ─────────────────────────────────────────────────────────────
def ch_label(n: int, text: str = '') -> QLabel:
lbl = QLabel(text or f'CH{n}')
lbl.setObjectName(f'ch{n}')
lbl.setStyleSheet(f"color:{CH_COLORS[n]}; font-weight:bold;")
return lbl
def hsep() -> QFrame:
f = QFrame()
f.setObjectName("separator")
f.setFrameShape(QFrame.HLine)
return f
# ─────────────────────────────────────────────────────────────
# FREQ LIST EDITOR (EROT) — comma-separated text input
# ─────────────────────────────────────────────────────────────
class FreqListEditor(QWidget):
"""
Simple comma-separated frequency entry.
Type values like: 10000, 7000, 5000, 3000, 2000, 1500
Supports scientific notation: 1e4, 7e3, 5e3
Invalid tokens are highlighted; the parsed count is shown live.
"""
DEFAULT = "10000, 7000, 5000, 3000, 2000, 1500"
def __init__(self, parent=None):
super().__init__(parent)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(4)
# header row
hdr = QHBoxLayout()
hdr.addWidget(QLabel("Frequencies (Hz), comma-separated:"))
self._count_lbl = QLabel("")
self._count_lbl.setStyleSheet("color:#8b949e; font-size:11px;")
hdr.addStretch()
hdr.addWidget(self._count_lbl)
layout.addLayout(hdr)
# text field
self._edit = QLineEdit(self.DEFAULT)
self._edit.setPlaceholderText("e.g. 10000, 7000, 5e3, 1000.5")
self._edit.setToolTip(
"Enter frequency values in Hz separated by commas.\n"
"Scientific notation is supported (e.g. 1e4 = 10 000 Hz)."
)
layout.addWidget(self._edit)
# validation feedback label
self._warn_lbl = QLabel("")
self._warn_lbl.setStyleSheet("color:#f85149; font-size:11px;")
self._warn_lbl.setVisible(False)
layout.addWidget(self._warn_lbl)
self._edit.textChanged.connect(self._on_text_changed)
self._on_text_changed(self.DEFAULT)
def _on_text_changed(self, text: str):
freqs, bad = self._parse(text)
n = len(freqs)
if bad:
self._count_lbl.setText(f"{n} valid | {len(bad)} invalid")
self._count_lbl.setStyleSheet("color:#f85149; font-size:11px;")
self._warn_lbl.setText(f"Ignored tokens: {', '.join(bad)}")
self._warn_lbl.setVisible(True)
self._edit.setStyleSheet("border:1px solid #da3633;")
else:
self._count_lbl.setText(f"{n} step{'s' if n != 1 else ''}")
self._count_lbl.setStyleSheet("color:#3fb950; font-size:11px;")
self._warn_lbl.setVisible(False)
self._edit.setStyleSheet("")
@staticmethod
def _parse(text: str):
good, bad = [], []
for token in text.split(','):
token = token.strip()
if not token:
continue
try:
val = float(token)
if val <= 0:
raise ValueError
good.append(val)
except ValueError:
bad.append(token)
return good, bad
def get_frequencies(self) -> list:
freqs, _ = self._parse(self._edit.text())
return freqs
# ─────────────────────────────────────────────────────────────
# CONSOLE
# ─────────────────────────────────────────────────────────────
class Console(QGroupBox):
def __init__(self):
super().__init__("CONSOLE")
layout = QVBoxLayout(self)
layout.setContentsMargins(6, 4, 6, 6)
self.text = QTextEdit()
self.text.setReadOnly(True)
self.text.setMinimumHeight(60) # can shrink but not disappear
# no setFixedHeight — the splitter controls the size
btn_clear = QPushButton("Clear")
btn_clear.setFixedWidth(70)
btn_clear.clicked.connect(self.text.clear)
top = QHBoxLayout()
top.addStretch()
top.addWidget(btn_clear)
layout.addLayout(top)
layout.addWidget(self.text)
def log(self, msg: str, color: str = '#3fb950'):
ts = time.strftime('%H:%M:%S')
self.text.append(
f'<span style="color:#484f58">[{ts}]</span> '
f'<span style="color:{color}">{msg}</span>'
)
self.text.moveCursor(QTextCursor.End)
def error(self, msg: str):
self.log(msg, color='#f85149')
# ─────────────────────────────────────────────────────────────
# CONNECTION PANEL
# ─────────────────────────────────────────────────────────────
class ConnectionPanel(QGroupBox):
connect_clicked = pyqtSignal(str, int, int)
disconnect_clicked = pyqtSignal()
scan_clicked = pyqtSignal()
test_clicked = pyqtSignal(float) # error_rate
def __init__(self):
super().__init__("INSTRUMENT CONNECTION")
vbox = QVBoxLayout(self)
vbox.setContentsMargins(8, 6, 8, 6)
vbox.setSpacing(5)
# ── ROW 1: adjustable parameters ────────────────────
row1 = QHBoxLayout()
row1.setSpacing(6)
row1.addWidget(QLabel("VISA Resource:"))
self.addr_edit = QLineEdit("ASRL7::INSTR")
self.addr_edit.setPlaceholderText("USB0::… / GPIB0::xx::INSTR / ASRL7::INSTR")
row1.addWidget(self.addr_edit, stretch=1) # takes all remaining space
row1.addSpacing(8)
row1.addWidget(QLabel("Buffer:"))
self.buf_spin = QSpinBox()
self.buf_spin.setRange(256, 65536)
self.buf_spin.setValue(1024)
self.buf_spin.setSingleStep(256)
self.buf_spin.setFixedWidth(82)
row1.addWidget(self.buf_spin)
row1.addSpacing(8)
row1.addWidget(QLabel("Timeout (ms):"))
self.timeout_spin = QSpinBox()
self.timeout_spin.setRange(500, 60000)
self.timeout_spin.setValue(5000)
self.timeout_spin.setSingleStep(500)
self.timeout_spin.setFixedWidth(76)
row1.addWidget(self.timeout_spin)
vbox.addLayout(row1)
# ── ROW 2: connection & test-mode buttons + status ──
row2 = QHBoxLayout()
row2.setSpacing(6)
self.btn_scan = QPushButton("🔍 Scan Ports")
self.btn_conn = QPushButton("⚡ Connect")
self.btn_conn.setObjectName("btn_connect")
self.btn_disc = QPushButton("✕ Disconnect")
self.btn_disc.setObjectName("btn_disconnect")
self.btn_disc.setEnabled(False)
row2.addWidget(self.btn_scan)
row2.addWidget(self.btn_conn)
row2.addWidget(self.btn_disc)
row2.addSpacing(16)
self.btn_test = QPushButton("🧪 Test Mode")
self.btn_test.setObjectName("btn_testmode")
self.err_spin = QDoubleSpinBox()
self.err_spin.setRange(0.0, 0.5)
self.err_spin.setValue(0.0)
self.err_spin.setSingleStep(0.05)
self.err_spin.setDecimals(2)
self.err_spin.setSuffix(" err%")
self.err_spin.setFixedWidth(96)
self.err_spin.setToolTip(
"Probability (0–50 %) that each virtual command raises a fake\n"
"comms error — useful for stress-testing error handling."
)
row2.addWidget(self.btn_test)
row2.addWidget(self.err_spin)
row2.addStretch()
self.status_lbl = QLabel("● Not connected")
self.status_lbl.setObjectName("status_idle")
row2.addWidget(self.status_lbl)
vbox.addLayout(row2)
self.btn_scan.clicked.connect(self.scan_clicked)
self.btn_conn.clicked.connect(self._on_connect)
self.btn_disc.clicked.connect(self.disconnect_clicked)
self.btn_test.clicked.connect(self._on_test)
def _on_connect(self):
self.connect_clicked.emit(
self.addr_edit.text(),
self.buf_spin.value(),
self.timeout_spin.value()
)
def _on_test(self):
self.test_clicked.emit(self.err_spin.value())
def set_connected(self, ok: bool, test_mode: bool = False):
if ok and test_mode:
self.status_lbl.setText("● TEST MODE — Virtual Instrument")
self.status_lbl.setObjectName("status_test")
self.btn_test.setObjectName("btn_testmode_active")
self.btn_test.setEnabled(False)
elif ok:
self.status_lbl.setText("● Connected")
self.status_lbl.setObjectName("status_ok")
self.btn_test.setObjectName("btn_testmode")
self.btn_test.setEnabled(False)
else:
self.status_lbl.setText("● Not connected")
self.status_lbl.setObjectName("status_idle")
self.btn_test.setObjectName("btn_testmode")
self.btn_test.setEnabled(True)
# force style refresh
for w in [self.status_lbl, self.btn_test]:
w.style().unpolish(w)
w.style().polish(w)
self.btn_conn.setEnabled(not ok)
self.btn_disc.setEnabled(ok)
def populate_resources(self, resources: list):
if resources:
self.addr_edit.setText(resources[0])
# ─────────────────────────────────────────────────────────────
# TEST MODE PANEL (virtual instrument state viewer)
# ─────────────────────────────────────────────────────────────
class LivePanel(QGroupBox):
"""
Left-side panel showing live channel state and waveform preview.
Works in both real-hardware mode (polls worker._ch_state) and
virtual/test mode (reads VirtualInstrument directly).
Shown whenever the instrument is connected.
"""
def __init__(self, worker: 'InstrumentWorker'):
super().__init__("📡 CHANNEL LIVE STATE")
self._worker = worker
self._test_mode = False
layout = QVBoxLayout(self)
# mode note (updated when connection type changes)
self._note = QLabel("")
self._note.setWordWrap(True)
self._note.setStyleSheet("font-size:11px;")
layout.addWidget(self._note)
# channel state labels
self._ch_labels: dict[int, QLabel] = {}
ch_grid = QGridLayout()
for ch in range(1, 5):
badge = ch_label(ch)
badge.setFixedWidth(40)
val_lbl = QLabel("—")
val_lbl.setStyleSheet(f"color:{CH_COLORS[ch]}; font-family:Consolas;")
ch_grid.addWidget(badge, ch - 1, 0)
ch_grid.addWidget(val_lbl, ch - 1, 1)
self._ch_labels[ch] = val_lbl
layout.addLayout(ch_grid)
# waveform canvas
self._canvas = WaveformCanvas()
layout.addWidget(self._canvas)
# auto-refresh timer
self._timer = QTimer(self)
self._timer.setInterval(500)
self._timer.timeout.connect(self._refresh)
def set_mode(self, test_mode: bool):
self._test_mode = test_mode
if test_mode:
self._note.setText(
"TEST MODE — commands go to the built-in virtual instrument."
)
self._note.setStyleSheet("color:#d2a8ff; font-size:11px;")
else:
self._note.setText(
"LIVE — channel state updated after each Apply. "
"Waveform is reconstructed from reported parameters."
)
self._note.setStyleSheet("color:#8b949e; font-size:11px;")
def start(self):
self._timer.start()
def stop(self):
self._timer.stop()
# blank out the display when disconnected
for lbl in self._ch_labels.values():
lbl.setText("—")
self._canvas.update_channels([])
def _refresh(self):
lines = self._worker.get_channel_state_lines()
chans = self._worker.get_channel_state()
if lines:
for ch in range(1, 5):
if ch - 1 < len(lines):
self._ch_labels[ch].setText(lines[ch - 1])
self._canvas.update_channels(chans)
# ─────────────────────────────────────────────────────────────
# WAVEFORM CANVAS (pure Qt — no extra dependencies)
# ─────────────────────────────────────────────────────────────
class WaveformCanvas(QWidget):
"""
Time-domain oscilloscope preview for all 4 virtual channels.
Layout
──────
Left margin (Y_MARGIN px) contains:
• a solid Y-axis line
• ±Vpeak tick marks scaled to the highest active channel voltage
• numeric voltage labels (Vpp / 2)
Plot area to the right shows 3 cycles of the fastest active channel.
Disabled channels are drawn as a faint dashed zero line.
"""
Y_MARGIN = 52 # pixels reserved for Y-axis labels
def __init__(self):
super().__init__()
self._channels: list = []
self.setMinimumHeight(140)
self.setStyleSheet(
"background:#0a0e14; border:1px solid #30363d; border-radius:3px;"
)
def update_channels(self, channels):
self._channels = channels
self.update()
# ── helpers ──────────────────────────────────────────────
@staticmethod
def _nice_voltage(v: float) -> str:
"""Format a voltage value concisely: '1.00', '500m', etc."""
if abs(v) >= 1.0: