-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSerialUI.py
More file actions
2100 lines (1821 loc) · 91.3 KB
/
SerialUI.py
File metadata and controls
2100 lines (1821 loc) · 91.3 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
#!/usr/bin/env python3
############################################################################################################################################
# Serial Communication App
# ************************
#
# - Provides serial interface to send and receive data to/from
# - serial port (USB, RS232)
# - serial BLE (Nordic UART Service)
# - Displays received data in a scrollable text window with option to record to file.
# - can handle data at high rates comparable with other terminal programs
# - Plots data in chart with zoom, save and clear.
# - extracts numbers from data in simple or structured manner efficiently
# - can use pyqtgraph or fastplotlib for plotting
# - Handles connection upon insertion and removal of USB devices.
# - Attempts handling of BLE devices in comprehensive manner.
#
# Configurations can be changed in config.py
#
# This code is maintained by Urs Utzinger
############################################################################################################################################
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# ==============================================================================
# pyinstaller resource path handling
# crash logging and reporting for executable
# ==============================================================================
import sys
import os
import traceback
import threading
from datetime import datetime
from pathlib import Path
def _serialui_log_dir() -> Path:
"""Return writable log directory for crash diagnostics."""
if os.name == "nt":
base = os.environ.get("LOCALAPPDATA")
if base:
root = Path(base)
else:
root = Path.home() / "AppData" / "Local"
else:
root = Path.home() / ".local" / "state"
out = root / "SerialUI" / "logs"
out.mkdir(parents=True, exist_ok=True)
return out
def _write_crash_report(exc_type, exc_value, exc_tb, source: str = "main") -> Path | None:
try:
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_dir = _serialui_log_dir()
report_path = log_dir / "last_crash.log"
with report_path.open("a", encoding="utf-8") as fh:
fh.write("\n" + "=" * 80 + "\n")
fh.write(f"Timestamp: {ts}\n")
fh.write(f"Source: {source}\n")
fh.write(f"Executable: {sys.executable}\n")
fh.write(f"Frozen: {bool(getattr(sys, 'frozen', False))}\n")
fh.write("Traceback:\n")
traceback.print_exception(exc_type, exc_value, exc_tb, file=fh)
return report_path
except Exception:
return None
def _show_windows_crash_dialog(path: Path | None) -> None:
if os.name != "nt":
return
try:
import ctypes
msg = "SerialUI crashed during startup.\n"
if path is not None:
msg += f"Crash report: {path}"
ctypes.windll.user32.MessageBoxW(0, msg, "SerialUI Error", 0x10)
except Exception:
pass
def _serialui_excepthook(exc_type, exc_value, exc_tb):
report = _write_crash_report(exc_type, exc_value, exc_tb, source="main")
if getattr(sys, "frozen", False):
_show_windows_crash_dialog(report)
try:
sys.__excepthook__(exc_type, exc_value, exc_tb)
except Exception:
pass
def _threading_excepthook(args):
report = _write_crash_report(args.exc_type, args.exc_value, args.exc_traceback, source=f"thread:{args.thread.name}")
if getattr(sys, "frozen", False):
_show_windows_crash_dialog(report)
sys.excepthook = _serialui_excepthook
if hasattr(threading, "excepthook"):
threading.excepthook = _threading_excepthook
def resource_path(relative_path: str) -> str:
"""
Get absolute path to resource, works in dev and in PyInstaller bundle.
"""
if hasattr(sys, "_MEIPASS"):
# In a PyInstaller bundle, this is the temp / _internal dir
base_path = sys._MEIPASS
else:
# When running from source
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
# ==============================================================================
def _run_c_parser_selftest_mode() -> int:
"""
Lightweight self-test mode for parser probing.
Runs before importing the full app stack.
"""
if "--selftest-c-parser" not in sys.argv:
return -1
errors = []
try:
from helpers.line_parsers import simple_parser # noqa: F401
from helpers.line_parsers import header_parser # noqa: F401
print("C parser self-test passed (backend=helpers.line_parsers)")
return 0
except Exception as exc:
errors.append(f"helpers.line_parsers: {exc}")
try:
from line_parsers import simple_parser # noqa: F401
from line_parsers import header_parser # noqa: F401
print("C parser self-test passed (backend=line_parsers)")
return 0
except Exception as exc:
errors.append(f"line_parsers: {exc}")
print(
"C parser self-test failed: " + " | ".join(errors),
file=sys.stderr,
)
return 1
_selftest_rc = _run_c_parser_selftest_mode()
if _selftest_rc >= 0:
raise SystemExit(_selftest_rc)
def _run_numba_selftest_mode() -> int:
"""
Lightweight self-test mode for numba probing.
Runs before importing the full app stack.
"""
if "--selftest-numba" not in sys.argv:
return -1
errors = []
try:
import numba
from numba import njit
except Exception as exc:
errors.append(f"numba import failed: {exc}")
else:
try:
@njit(cache=False)
def _numba_probe(x):
return x + 1
value = _numba_probe(1)
if int(value) != 2:
raise RuntimeError(f"unexpected JIT result {value!r}")
except Exception as exc:
errors.append(f"numba JIT failed: {exc}")
try:
from helpers.Circular_Buffer import hasNUMBA, NUMBA_IMPORT_ERROR
if not hasNUMBA:
raise RuntimeError(NUMBA_IMPORT_ERROR or "hasNUMBA=False")
except Exception as exc:
errors.append(f"helpers.Circular_Buffer numba path failed: {exc}")
if errors:
print(
"Numba self-test failed: " + " | ".join(errors),
file=sys.stderr,
)
return 1
print(f"Numba self-test passed (numba={numba.__version__})")
return 0
_selftest_rc = _run_numba_selftest_mode()
if _selftest_rc >= 0:
raise SystemExit(_selftest_rc)
# ==============================================================================
# Config
# ==============================================================================
# This will steer imports
from config import (
USE_BLE, USE_3DPLOT, USE_FASTPLOTLIB, USE_BLUETOOTHCTL,
VERSION, AUTHOR, DATE,
DEFAULT_TEXT_LINES, MAX_TEXT_LINES, MAX_ROWS,
DEBUGKEYINPUT, DEBUG_LEVEL, DEBUGRECEIVER, DEBUGCHART,
ENCODING, BACKGROUNDCOLOR, BACKGROUNDCOLOR_LOG, BACKGROUNDCOLOR_TABS,
BLESCAN_SHORT,
EOL_DICT, EOL_DICT_INV, EOL_DEFAULT_LABEL, EOL_DEFAULT_BYTES, DEFAULT_LINETERMINATOR,
PARSE_OPTIONS, PARSE_OPTIONS_INV, PARSE_DEFAULT_LABEL, PARSE_DEFAULT_NAME,
LOG_OPTIONS, LOG_OPTIONS_INV, LOG_DEFAULT_LABEL, LOG_DEFAULT_NAME,
DISCRETE_GPU
)
# ==============================================================================
# Graphics Environment Setup
# ==============================================================================
# This needs to run before importing any QT, wgpu, pygfx, fastplotlib, pyqtgraph modules
from helpers.General_helper import setup_graphics_env
if DEBUGCHART:
setup_graphics_env(
prefer_discrete_gpu=DISCRETE_GPU, # use False to bias to iGPU
force_backend=None, # None->auto per OS; or "vulkan"/"dx12"/"metal"/"gl"
wayland_ok=True, # set False to force X11 on Linux even if Wayland session
verbose_logs=True, # True to enable RUST_LOG for wgpu
)
else:
setup_graphics_env(
prefer_discrete_gpu=DISCRETE_GPU, # use False to bias to iGPU
force_backend=None, # None->auto per OS; or "vulkan"/"dx12"/"metal"/"gl"
wayland_ok=True, # set False to force X11 on Linux even if Wayland session
verbose_logs=False, # True to enable RUST_LOG for wgpu
)
# ==============================================================================
# Imports
# ==============================================================================
#
# Basic libraries
# ----------------------------------------
import sys
import os
import time
import textwrap
from markdown import markdown
import logging
#
# QT imports, QT5 or QT6
# ----------------------------------------
try:
from PyQt6 import uic
from PyQt6.QtCore import (
QTimer, Qt, pyqtSlot, pyqtSignal, QStandardPaths, QCoreApplication
)
from PyQt6.QtWidgets import (
QMainWindow, QLineEdit, QSlider,
QMessageBox, QDialog, QVBoxLayout,
QTextEdit, QTabWidget, QWidget,
QPlainTextEdit, QApplication,
)
from PyQt6.QtGui import QIcon, QShortcut, QTextCursor, QTextOption, QKeySequence, QGuiApplication, QPixmap, QFontDatabase
WindowType = Qt.WindowType
ConnectionType= Qt.ConnectionType
NO_WRAP = QPlainTextEdit.LineWrapMode.NoWrap
NO_WORDWRAP = QTextOption.WrapMode.NoWrap
MOVE_END = QTextCursor.MoveOperation.End
KEY_UP = QKeySequence(Qt.Key.Key_Up)
KEY_DOWN = QKeySequence(Qt.Key.Key_Down)
DOCUMENTS = QStandardPaths.StandardLocation.DocumentsLocation
hasQt6 = True
except Exception:
from PyQt5 import uic
from PyQt5.QtCore import (
QTimer, Qt, pyqtSlot, pyqtSignal, QStandardPaths, QCoreApplication
)
from PyQt5.QtWidgets import (
QMainWindow, QLineEdit, QSlider,
QMessageBox, QDialog, QVBoxLayout,
QTextEdit, QTabWidget, QWidget, QShortcut,
QPlainTextEdit, QApplication,
)
from PyQt5.QtGui import (
QIcon, QTextCursor, QTextOption, QKeySequence, QGuiApplication, QPixmap, QFontDatabase
)
WindowType = Qt
ConnectionType= Qt
NO_WRAP = QPlainTextEdit.NoWrap
NO_WORDWRAP = QTextOption.NoWrap
MOVE_END = QTextCursor.End
KEY_UP = QKeySequence(Qt.Key_Up)
KEY_DOWN = QKeySequence(Qt.Key_Down)
DOCUMENTS = QStandardPaths.DocumentsLocation
hasQt6 = False
#
# # Set HiDPI rounding policy early (before creating QApplication). Safe for Qt5/Qt6.
# NOT enabled as environment variables should take care of this
# try:
# if hasattr(QGuiApplication, "setHighDpiScaleFactorRoundingPolicy"):
# # Only set if no instance exists yet
# if QGuiApplication.instance() is None:
# # Prefer PassThrough; fall back to RoundPreferFloor if not available
# policy = getattr(Qt.HighDpiScaleFactorRoundingPolicy, "PassThrough",
# getattr(Qt.HighDpiScaleFactorRoundingPolicy, "RoundPreferFloor"))
# QGuiApplication.setHighDpiScaleFactorRoundingPolicy(policy)
# except Exception:
# pass
#
# Enable High DPI scaling and use high DPI pixmaps (should be before creating QApplication)
try:
if hasattr(Qt.ApplicationAttribute, "AA_EnableHighDpiScaling"):
QApplication.setAttribute(
Qt.ApplicationAttribute.AA_EnableHighDpiScaling, True
)
if hasattr(Qt.ApplicationAttribute, "AA_UseHighDpiPixmaps"):
QApplication.setAttribute(
Qt.ApplicationAttribute.AA_UseHighDpiPixmaps, True
)
except Exception:
pass
#
# Program's local class imports
# ----------------------------------------
#
from helpers.Qgraph_helper import QChart
from helpers.Qserial_helper import QSerial
from helpers.USB_SerialPortMonitor import QUSBMonitor
from helpers.General_helper import (clip_value, connect, disconnect, select_file,
confirm_overwrite_append)
if USE_BLE:
from helpers.QBLE_helper import QBLESerial
#
# Profiling
# ----------------------------------------
# To profile this application run the program with:
# kernprof -l -v SerialUI.py
# Then create a readable report with:
# python -m line_profiler SerialUI.py.lprof > SerialUI_profile.txt
# This will shows which statements in tagged functions take the most time.
try:
profile # provided by kernprof at runtime
except NameError:
def profile(func): # no-op when not profiling
return func
############################################################################################################################################
#
# Main Window
#
# This is the Viewer of the Model - View - Controller (MVC) architecture.
#
############################################################################################################################################
class mainWindow(QMainWindow):
"""
Main program that ties the classes, threads and widgets together.
Serial:
Create serial interface. The initialization sets a custom serial worker in a separate qt thread.
BLE:
Create BLE interface. The initialization sets a custom worker using a custom task scheduler.
Text and Log Display:
Create text and log display windows with scrollbar, history, save and record.
Plotter:
Create chart interface using pyqtgraph or fastplotlib.
The chart can be zoomed in time and saved/exported.
Fastplotlib utilizes GPU if present. pyqtgraph uses multiple cores for rendering.
Indicator:
Display values and vectors (not yet implemented).
USB Monitor:
Detect insertion and removal of USB devices. It triggers reconnection attempt.
"""
# Signals of the main window
# ==========================================================================
mtocRequest = pyqtSignal() # request to receive function profiling information
sendFileRequest = pyqtSignal(Path) # request to open file and send over serial port
sendTextRequest = pyqtSignal(bytes) # request to transmit text to TX
sendLineRequest = pyqtSignal(bytes) # request to transmit one line of text to TX
sendLinesRequest = pyqtSignal(list) # request to transmit lines of text to TX
runMonitoringRequest = pyqtSignal(bool) # request monitor on/off
rxStartRequest = pyqtSignal() # start transceivers (whoever is wired)
rxStopRequest = pyqtSignal() # stop transceivers (whoever is wired)
throughputStartRequest = pyqtSignal() # start throughput (whoever is wired)
throughputStopRequest = pyqtSignal() # stop throughput (whoever is wired)
# ==========================================================================
# Initialize
# ==========================================================================
def __init__(self, parent=None, logger=None):
"""
Initialize the components of the main window.
This will create the connections between slots and signals in both directions.
Serial, BLE, Chart and USB monitoring is setup in their initialization threads.
Display and logging is handled here in the main thread.
"""
super().__init__(parent) # parent constructor
if logger is None:
self.logger = logging.getLogger("SerialUI")
self.logger.setLevel(DEBUG_LEVEL)
sh = logging.StreamHandler()
fmt = "[%(levelname)-8s] [%(name)-10s] %(message)s"
sh.setFormatter(logging.Formatter(fmt))
self.logger.addHandler(sh)
self.logger.propagate = False
else:
self.logger = logger
self.encoding = ENCODING
self.maxlines = DEFAULT_TEXT_LINES
self.main_dir = os.path.dirname(os.path.abspath(__file__))
self.instance_name = self.objectName() if self.objectName() else self.__class__.__name__
self.isMonitoring = False
self.isPlotting = False # chart receiver status request
self.startup_work_scheduled = False
self.lineSendHistory = [] # previously sent text (e.g. commands)
self.lineSendHistoryIndx = -1
self.textLineTerminator = DEFAULT_LINETERMINATOR
# User Interface
# ----------------------------------------
ui_file = resource_path(os.path.join("assets", "serialUI.ui"))
self.ui = uic.loadUi(ui_file, self)
self.setWindowTitle("Serial GUI")
# Log Display
# ----------------------------------------
# Needs to be setup first, otherwise logging is not available
self.log_widget = self.ui.plainTextEdit_Log
self.log_widget.setStyleSheet(f"background-color: {BACKGROUNDCOLOR_LOG};")
if hasQt6:
log_font = QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont)
else:
log_font = QFontDatabase.systemFont(QFontDatabase.FixedFont)
self.log_widget.setFont(log_font)
# Modify LOG display window on serial text display
self.log_widget.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
self.log_widget.setLineWrapMode(NO_WRAP) # no wrapping for better performance
self.log_widget.setReadOnly(True) # prevent user edits
self.log_widget.setWordWrapMode(NO_WORDWRAP) # no wrapping for better performance
self.log_widget.setUndoRedoEnabled(False)
self.log_widget.setMaximumBlockCount(DEFAULT_TEXT_LINES) #
self.log_widget.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
self.log_scroll_bar = self.log_widget.verticalScrollBar()
self.log_scroll_bar.setSingleStep(1) # highest resolution for scrolling
self.log_scroll_bar.setPageStep(10) # defines how much a full page scroll moves
self.log_scroll_bar.setValue(self.log_scroll_bar.maximum()) # scroll to bottom
# Set cursor to end of LOG display for auto scrolling
# one should obtain a copy of the text cursor each time one modifies it
textCursor = self.log_widget.textCursor()
textCursor.movePosition(MOVE_END)
self.log_widget.setTextCursor(textCursor)
self.log_widget.ensureCursorVisible()
# Icons
# ----------------------------------------
icon_path = os.path.join(self.main_dir, "assets", "icon_48.png")
window_icon = QIcon(icon_path)
self.setWindowIcon(window_icon)
QApplication.setWindowIcon(window_icon)
ble_icon_path = os.path.join(self.main_dir, "assets", "BLE_48.png")
ble_icon = QIcon(ble_icon_path)
usb_icon_path = os.path.join(self.main_dir, "assets", "USB_48.png")
usb_icon = QIcon(usb_icon_path)
# pix = QPixmap(icon_path)
# self.logger.log(logging.INFO, f"Icon Pixmap isNull: {pix.isNull()}, Size: {pix.size()}")
# pix = QPixmap(usb_icon_path)
# self.logger.log(logging.INFO, f"USB Icon Pixmap isNull: {pix.isNull()}, Size: {pix.size()}")
# pix = QPixmap(ble_icon_path)
# self.logger.log(logging.INFO, f"BLE Icon Pixmap isNull: {pix.isNull()}, Size: {pix.size()}")
# Find the tabs and connect to tab change
# ----------------------------------------
self.tabs: QTabWidget = self.findChild(QTabWidget, "tabWidget_MainWindow")
self.tabs.currentChanged.connect(self.on_tab_change)
self.tabs.setStyleSheet(f"QWidget {{ background-color: {BACKGROUNDCOLOR_TABS}; }}")
# Configure Drop Down Menus
# ----------------------------------------
# Line Termination Serial
cb = self.ui.comboBoxDropDown_LineTermination
cb.blockSignals(True)
cb.clear()
cb.addItems(list(EOL_DICT.keys()))
# Set current index based on the current bytes value (if you already have one)
current_bytes = getattr(self, "textLineTerminator", EOL_DEFAULT_BYTES)
label = EOL_DICT_INV.get(current_bytes, EOL_DEFAULT_LABEL)
idx = cb.findText(label)
if idx >= 0:
cb.setCurrentIndex(idx)
else:
cb.setCurrentIndex(cb.findText(EOL_DEFAULT_LABEL))
cb.blockSignals(False)
# Line Termination BLE
cb = self.ui.comboBoxDropDown_LineTermination_BLE
cb.blockSignals(True)
cb.clear()
cb.addItems(list(EOL_DICT.keys()))
# Set current index based on the current bytes value (if you already have one)
# current_bytes = getattr(self, "textLineTerminator", EOL_DEFAULT_BYTES)
# label = EOL_DICT_INV.get(current_bytes, EOL_DEFAULT_LABEL)
idx = cb.findText(label)
if idx >= 0:
cb.setCurrentIndex(idx)
else:
cb.setCurrentIndex(cb.findText(EOL_DEFAULT_LABEL))
cb.blockSignals(False)
# Plotting Data Separator
cb = self.ui.comboBoxDropDown_DataSeparator
cb.blockSignals(True)
cb.clear()
cb.addItems(list(PARSE_OPTIONS.keys()))
current_name = getattr(self, "textDataSeparator", PARSE_DEFAULT_NAME)
label = PARSE_OPTIONS_INV.get(current_name, PARSE_DEFAULT_LABEL)
idx = cb.findText(label)
if idx >= 0:
cb.setCurrentIndex(idx)
else:
cb.setCurrentIndex(cb.findText(PARSE_DEFAULT_LABEL))
cb.blockSignals(False)
# LOG level
cb = self.ui.comboBoxDropDown_LogLevel
cb.blockSignals(True)
cb.clear()
cb.addItems(list(LOG_OPTIONS.keys()))
current_name = getattr(self, "textLogLevel", LOG_DEFAULT_NAME)
label = LOG_OPTIONS_INV.get(current_name, LOG_DEFAULT_LABEL)
idx = cb.findText(label)
if idx >= 0:
cb.setCurrentIndex(idx)
else:
cb.setCurrentIndex(cb.findText(LOG_DEFAULT_LABEL))
cb.blockSignals(False)
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: User Interface drop downs initialized."
)
# Configure the Buttons (enabled/disabled)
# ----------------------------------------
# Text display buttons
self.ui.pushButton_ReceiverStartStop.setText("Start")
self.ui.pushButton_ReceiverStartStop.setEnabled(True)
self.ui.pushButton_SendFile.setEnabled(False)
self.ui.pushButton_ReceiverClearOutput.setEnabled(True)
self.ui.pushButton_ReceiverSave.setEnabled(True)
# Serial Buttons
self.ui.pushButton_SerialOpenClose.setText("Open")
self.ui.pushButton_SerialScan.setEnabled(True)
self.ui.pushButton_SerialOpenClose.setEnabled(False)
self.ui.pushButton_ToggleDTR.setEnabled(False)
self.ui.pushButton_ResetESP.setEnabled(False)
if USE_BLE:
self.ui.pushButton_toBLE.setEnabled(True)
else:
self.ui.pushButton_toBLE.setEnabled(False)
# BLE Buttons
if USE_BLE:
self.ui.pushButton_BLEScan.setEnabled(True)
self.ui.pushButton_BLEConnect.setEnabled(False)
self.ui.pushButton_toSerial.setEnabled(True)
else:
self.ui.pushButton_BLEScan.setEnabled(False)
self.ui.pushButton_BLEConnect.setEnabled(False)
self.ui.pushButton_toSerial.setEnabled(True)
if USE_BLUETOOTHCTL:
self.ui.pushButton_BLEPair.setEnabled(True)
self.ui.pushButton_BLETrust.setEnabled(True)
self.ui.pushButton_BLEStatus.setEnabled(True)
else:
self.ui.pushButton_BLEPair.setEnabled(False)
self.ui.pushButton_BLETrust.setEnabled(False)
self.ui.pushButton_BLEStatus.setEnabled(False)
# Chart Buttons
self.ui.pushButton_ChartStartStop.setText("Start")
self.ui.pushButton_ChartStartStop.setEnabled(True)
self.ui.pushButton_ChartClear.setEnabled(True)
self.ui.pushButton_ChartSave.setEnabled(True)
self.ui.pushButton_ChartSaveFigure.setEnabled(True)
# Indicator Buttons
self.ui.pushButton_IndicatorStartStop.setEnabled(True)
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: User Interface buttons initialized."
)
# Plotter
# ----------------------------------------
# Create user interface hook for chart plotting
self.chart = QChart(parent=self, ui=self.ui) # create chart user interface object
# Signals from Main to Chart-UI
self.mtocRequest.connect( self.chart.on_mtocRequest) # connect mtoc request to worker
self.ui.pushButton_ChartStartStop.clicked.connect( self.chart.on_pushButton_ChartStartStop)
self.ui.pushButton_ChartPause.clicked.connect( self.chart.on_pushButton_ChartPause)
self.ui.pushButton_ChartClear.clicked.connect( self.chart.on_pushButton_ChartClear)
self.ui.pushButton_ChartSave.clicked.connect( self.chart.on_pushButton_ChartSave)
self.ui.pushButton_ChartSaveFigure.clicked.connect( self.chart.on_pushButton_ChartSaveFigure)
self.ui.comboBoxDropDown_DataSeparator.currentIndexChanged.connect(self.chart.on_comboBox_DataSeparator)
# Signals from Chart-UI to Main
self.chart.plottingRunning.connect( self.handle_ReceiverRunning)
self.chart.logSignal.connect( self.handle_log) # connect log messages to Serial UI
# Done with Plotter
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: Plotter initialized."
)
# Serial
# ----------------------------------------
# Create user interface hook for Serial
self.serial = QSerial(parent=self, ui=self.ui) # create serial user interface object
# Signals from mainWindow to Serial (UI
self.mtocRequest.connect( self.serial.on_mtocRequest) # connect mtoc request to worker
# Signals handled elsewhere:
# sendFileRequest
# sendTextRequest
# sendLineRequest
# sendLinesRequest
# runMonitoringRequest
# Signals from Serial-UI to Main
self.serial.logSignal.connect( self.handle_log) # connect log messages to Serial UI
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: Serial initialized."
)
# BLE
# ----------------------------------------
if USE_BLE:
# Create user interface hook for BLE
self.ble = QBLESerial(parent=self, ui=self.ui) # create BLE UI object
# Signals from mainWindow to QBLE (UI)
self.mtocRequest.connect( self.ble.on_mtocRequest) # connect mtoc request
# Signals handled elsewhere:
# sendFileRequest
# sendTextRequest
# sendLineRequest
# sendLinesRequest
# runMonitoringRequest
# Signals from QBLE (UI) to Main
self.ble.logSignal.connect( self.handle_log) # connect log messages to Serial UI
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: BLE initialized."
)
# Chart Zoom
# ----------------------------------------
self.horizontalSlider_Zoom = self.ui.findChild(QSlider, "horizontalSlider_Zoom")
self.horizontalSlider_Zoom.setMinimum(8)
self.horizontalSlider_Zoom.setMaximum(MAX_ROWS)
self.lineEdit_Zoom = self.ui.findChild(QLineEdit, "lineEdit_Horizontal_Zoom")
# Monitoring
# ----------------------------------------
self.ui.pushButton_ReceiverStartStop.clicked.connect( self.on_pushButton_ReceiverStartStop) # start/stop serial receive
self.ui.pushButton_ReceiverSave.clicked.connect( self.on_pushButton_ReceiverSave) # save text from serial receive window
self.ui.pushButton_ReceiverClearOutput.clicked.connect(self.on_pushButton_ReceiverClearOutput) # clear serial receive window
self.ui.pushButton_SendFile.clicked.connect( self.on_pushButton_SendFile) # send text from a file to serial port
# Text Input
# ----------------------------------------
self.ui.lineEdit_Text.setEnabled(False)
self.ui.pushButton_SendFile.setEnabled(False)
# Text Display
# ----------------------------------------
self.horizontalSlider = self.ui.findChild(QSlider, "horizontalSlider_History")
self.horizontalSlider.setMinimum(50)
self.horizontalSlider.setMaximum(MAX_TEXT_LINES)
self.horizontalSlider.setValue(int(self.maxlines))
# Debounce apply of history limit
self.historySliderTimer = QTimer(self)
self.historySliderTimer.setSingleShot(True)
self.historySliderTimer.setInterval(250) # ms
self.historySliderTimer.timeout.connect(self.applyHistoryLimit)
self.lineEdit_History = self.ui.findChild(QLineEdit, "lineEdit_Vertical_History")
self.lineEdit_History.setText(str(self.maxlines))
self.text_widget = self.ui.plainTextEdit_Text
self.text_widget.setStyleSheet(f"background-color: {BACKGROUNDCOLOR};")
# Modify text display window on serial text display
self.text_widget.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
self.text_widget.setLineWrapMode(NO_WRAP) # no wrapping for better performance
self.text_widget.setReadOnly(True) # prevent user edits
self.text_widget.setWordWrapMode(NO_WORDWRAP) # no wrapping for better performance
self.text_widget.setUndoRedoEnabled(False)
self.text_widget.setMaximumBlockCount(self.maxlines)
# Modify TEXT display scrollbar behavior
self.text_widget.setVerticalScrollBarPolicy(
Qt.ScrollBarPolicy.ScrollBarAlwaysOn
)
self.text_scroll_bar = self.text_widget.verticalScrollBar()
self.text_scroll_bar.setSingleStep(1) # highest resolution for scrolling
self.text_scroll_bar.setPageStep(20) # defines how much a full page scroll moves
self.text_scroll_bar.setValue(self.text_scroll_bar.maximum()) # scroll to bottom
# Set cursor to end of text display for auto scrolling
textCursor = self.text_widget.textCursor()
textCursor.movePosition(MOVE_END)
self.text_widget.setTextCursor(textCursor)
self.text_widget.ensureCursorVisible()
self.recordingFileName = ""
self.recordingFile = None
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: Text display initialized."
)
# end/RX wiring follows transport readiness
# ----------------------------------------
self.txrxReady_wired_to_ble = False
self.txrxReady_wired_to_serial = False
# combined throughput stats
self.rx_serial = 0.0
self.tx_serial = 0.0
self.rx_ble = 0.0
self.tx_ble = 0.0
self.pps = 0.01
# React to connection state changes
self.serial.txrxReadyChanged.connect(self.update_sendreceive_targets_serial)
if USE_BLE:
self.ble.txrxReadyChanged.connect(self.update_sendreceive_targets_ble)
# Receive per-transport throughput and aggregate in main
try:
self.serial.throughputUpdate.connect(self.on_throughputUpdate)
except Exception:
pass
if USE_BLE:
try:
self.ble.throughputUpdate.connect(self.on_throughputUpdate)
except Exception:
pass
try:
self.chart.throughputUpdate.connect(self.on_throughputUpdate)
except Exception:
pass
self.ui.stackedWidget_BLE_Serial.setCurrentIndex(0) # start with serial tab visible
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: Receiver connected."
)
# USB device connect/disconnect
# ----------------------------------------
self.usbmonitor = QUSBMonitor(parent=self, ui=self.ui) # create USB monitor user interface object
self.usbmonitor.usb_event_detected.connect( self.serial.on_usb_event_detected)
self.usbmonitor.logSignal.connect( self.handle_log)
self.mtocRequest.connect( self.usbmonitor.on_mtocRequest)
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: USB monitor initialized."
)
# Indicator
# ----------------------------------------
# for now disable the indicator page
indicator_page: QWidget = self.tabs.findChild(QWidget, 'Indicator')
if indicator_page is not None:
idx = self.tabs.indexOf(indicator_page)
if idx != -1:
self.tabs.setTabVisible(idx, False)
if USE_3DPLOT:
self.ui.ThreeD.setEnabled(True)
else:
self.ui.ThreeD.setEnabled(False)
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: Indicator initialized."
)
# Main Program
# ----------------------------------------
# Signals from mainWindow to itself
# ----------------------------------------
self.runMonitoringRequest.connect( self.handle_ReceiverRunning)
# Interface Elements Connections
# ----------------------------------------
# Serial Buttons
self.ui.pushButton_SerialScan.clicked.connect( self.serial.on_pushButton_SerialScan) # scan for ports
self.ui.pushButton_SerialOpenClose.clicked.connect( self.serial.on_pushButton_SerialOpenClose) # open/close serial port
self.ui.pushButton_ToggleDTR.clicked.connect( lambda:self.serial.toggleDTRRequest.emit()) # toggle DTR
self.ui.pushButton_ResetESP.clicked.connect( lambda:self.serial.espResetRequest.emit()) # reset ESP32
# BLE Buttons
if USE_BLE:
# Switch from Serial to BLE
self.ui.pushButton_toBLE.clicked.connect( self.on_pushButton_toBLE) # switch to BLE tab
self.ui.pushButton_toBLE.setIcon(ble_icon)
# BLE action buttons
self.ui.pushButton_BLEScan.clicked.connect( self.ble.on_pushButton_BLEScan)
self.ui.pushButton_BLEConnect.clicked.connect( self.ble.on_pushButton_BLEConnect)
# BLUETOOTHCTL buttons
if USE_BLUETOOTHCTL:
self.ui.pushButton_BLEPair.clicked.connect( self.ble.on_pushButton_BLEPair)
self.ui.pushButton_BLETrust.clicked.connect(self.ble.on_pushButton_BLETrust)
self.ui.pushButton_BLEStatus.clicked.connect(self.ble.on_pushButton_BLEStatus)
# Switch from BLE to Serial
self.ui.pushButton_toSerial.clicked.connect( self.on_pushButton_toSerial) # switch to Serial tab
self.ui.pushButton_toSerial.setIcon(usb_icon)
# Radio Button Record
self.ui.checkBox_ReceiverRecord.toggled.connect( self.on_receiverRecord) # record incoming data to file
self.ui.checkBox_DisplayBLE.toggled.connect( self.on_displayBLE) # record incoming data to file
self.ui.checkBox_DisplaySerial.toggled.connect( self.on_displaySerial) # record incoming data to file
self.ui.checkBox_PlotSerial.toggled.connect( self.on_plotSerial)
self.ui.checkBox_PlotBLE.toggled.connect( self.on_plotBLE)
# Serial ComboBoxes
self.ui.comboBoxDropDown_SerialPorts.currentIndexChanged.connect( self.serial.on_comboBoxDropDown_SerialPorts) # user changed serial port
self.ui.comboBoxDropDown_BaudRates.currentIndexChanged.connect( self.serial.on_comboBoxDropDown_BaudRates) # user changed baud rate
self.ui.comboBoxDropDown_LineTermination.currentIndexChanged.connect(self.serial.on_comboBoxDropDown_LineTermination) # User changed line termination
# BLE ComboBoxes
if USE_BLE:
self.ui.comboBoxDropDown_Device.currentIndexChanged.connect( self.ble.on_comboBoxDropDown_BLEDevices)
self.ui.comboBoxDropDown_LineTermination_BLE.currentIndexChanged.connect(self.ble.on_comboBoxDropDown_LineTermination)
# Log ComboBoxes
self.ui.comboBoxDropDown_LogLevel.currentIndexChanged.connect(self.on_changeLoglevel)
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: Serial and BLE signals connected."
)
# Text History Length
self.horizontalSlider.valueChanged.connect( self.on_HistorySliderValueChanged)
self.horizontalSlider.sliderReleased.connect( self.on_HistorySliderReleased) # add
self.lineEdit_History.returnPressed.connect( self.on_HistoryLineEditChanged)
# Chart Zoom Slider
self.horizontalSlider_Zoom.valueChanged.connect( self.chart.on_ZoomSliderChanged)
self.horizontalSlider_Zoom.sliderReleased.connect( self.chart.on_ZoomSliderReleased)
self.lineEdit_Zoom.returnPressed.connect( self.chart.on_ZoomLineEditChanged)
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: Slider signals connected."
)
# Plot source selectors
self.ui.checkBox_PlotSerial.setChecked(self.serial.plot)
if USE_BLE:
self.ui.checkBox_PlotBLE.setChecked(self.ble.plot)
self.ui.checkBox_PlotBLE.setEnabled(True)
else:
self.ui.checkBox_PlotBLE.setChecked(False)
self.ui.checkBox_PlotBLE.setEnabled(False)
# Text Input
# ----------------------------------------
# User hits up/down arrow in send lineEdit
self.shortcutUpArrow = QShortcut(KEY_UP, self.ui.lineEdit_Text, self.on_upArrowPressed)
self.shortcutDownArrow = QShortcut(KEY_DOWN, self.ui.lineEdit_Text, self.on_downArrowPressed)
# Return key pressed in send lineEdit
self.ui.lineEdit_Text.returnPressed.connect( self.on_carriageReturnPressed) # send text as soon as enter key is pressed
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: Text entry signals connected."
)
# Menu Bar
# ----------------------------------------
# Connect the action_about action to the show_about_dialog slot
self.ui.action_About.triggered.connect( self.show_about_dialog)
self.ui.action_Help.triggered.connect( self.show_help_dialog)
self.ui.action_Profile.triggered.connect( self.on_mtocRequest)
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: Menu initialized."
)
# Status Bar
# ----------------------------------------
self.statusTimer = QTimer(self)
self.statusTimer.timeout.connect( self.on_resetStatusBar)
self.statusTimer.start(10000) # trigger every 10 seconds
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: Status Bar initialized."
)
# Display UI
# ----------------------------------------
self.show()
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: Displaying User Interface."
)
# ==========================================================================
# User Interface Functions General
# ==========================================================================
@pyqtSlot()
def on_mtocRequest(self):
"""
Produce profiling log message.
For selected functions, during runtime we measure their execution time.
If PROFILEME is False, this will report 0.
"""
self.handle_log(logging.INFO,
f"[{self.instance_name[:15]:<15}]: Obtaining profiling info."
)
if USE_BLE:
ble_status = "running" if self.ble.receiverIsRunning else "off"
else:
ble_status = "off"
log_message = textwrap.dedent(f"""
main Window
=============================================================
monitoring is {"on" if self.isMonitoring else "off"}.
plotting is {"on" if self.isPlotting else "off"}.
serial worker is {"running" if self.serial.receiverIsRunning else "off"}.
ble worker is {ble_status}.
""")
self.handle_log(-1, log_message)
# Emit the mtocRequest signal for other components to respond
self.mtocRequest.emit()
@pyqtSlot()
def on_logSignal(self, level: int, message: str) -> None:
"""Handle log messages from the logger."""
self.handle_log(level, message)
@profile
def handle_log(self, level: int, message: str) -> None:
"""
Handle log messages from the logger.
We log to console and to the dedicated log window.
level: -2 = forced display, disregarding log level
-1 = mtoc request
0..50 = logging levels
message: the log message to display
"""
# Console
# ----------------------------------------
if level > -1:
self.logger.log(level, message)
# Logwindow
# ----------------------------------------
if level == -1:
# mtoc request
#