-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindicator.py
More file actions
805 lines (663 loc) · 28.8 KB
/
indicator.py
File metadata and controls
805 lines (663 loc) · 28.8 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
#!/usr/bin/env python3
"""
Digital Indicator Panel
Professional seven-segment display panel for real-time dataset monitoring.
Inspired by industrial panel meters (Omega, Laurel, Red Lion).
Features:
- Master window to browse datasets and spawn indicator windows
- Canvas-rendered seven-segment digits with authentic segment geometry
- Per-display color themes: green, amber, red, cyan, white
- Hold (freeze), Tare (zero offset), Peak hold, and Min/Max tracking
- Configurable decimal places and display label
- Alert flash when value exceeds user-set threshold
- Auto-reconnect to Serial Studio API
Requirements: Serial Studio API server on port 7777, Python 3.6+, tkinter.
"""
import math, signal, sys, threading, time
from collections import deque
from grpc_client import GRPCClient
try:
import tkinter as tk
from tkinter import ttk
except ImportError:
sys.exit("[Indicator] tkinter required")
# ── Theme ────────────────────────────────────────────────────────────────────
BG = "#0d1117"
SURFACE = "#161b22"
HEADER = "#1c2633"
BORDER = "#30363d"
TEXT = "#e6edf3"
DIM = "#8b949e"
ACCENT = "#58a6ff"
GREEN = "#3fb950"
RED = "#f85149"
# Platform-aware font families
MONO_FONT = "Menlo" if sys.platform == "darwin" else "Consolas" if sys.platform == "win32" else "Monospace"
SANS_FONT = "Helvetica Neue" if sys.platform == "darwin" else "Segoe UI" if sys.platform == "win32" else "Sans"
IDLE_SEC = 3
# Color presets for indicator displays
PRESETS = {
"blue": {"digit": "#58a6ff", "dim": "#0a1a2e", "bg": "#060c14", "label": "#4090e0"},
"green": {"digit": "#39ff14", "dim": "#0a2e06", "bg": "#050d04", "label": "#2ecc40"},
"amber": {"digit": "#ffbf00", "dim": "#2e2400", "bg": "#0d0b04", "label": "#f0a000"},
"red": {"digit": "#ff3030", "dim": "#2e0808", "bg": "#0d0404", "label": "#e04040"},
"cyan": {"digit": "#00e5ff", "dim": "#002a2e", "bg": "#040d0d", "label": "#00c0d0"},
"white": {"digit": "#e0e0e0", "dim": "#1a1a1a", "bg": "#080808", "label": "#c0c0c0"},
}
DEFAULT_PRESET = "blue"
# ── Seven-segment geometry ───────────────────────────────────────────────────
# _aa_
# | |
# f b
# |_gg_|
# | |
# e c
# |_dd_| .dp
SEGMENTS = {
"0": "abcdef", "1": "bc", "2": "abdeg", "3": "abcdg",
"4": "bcfg", "5": "acdfg", "6": "acdefg", "7": "abc",
"8": "abcdefg","9": "abcdfg", "-": "g", " ": "", ".": "dp",
"E": "adefg", "e": "adefg", "r": "eg", "o": "cdeg",
"L": "def", "H": "bcefg", "d": "bcdeg", "P": "abefg",
"F": "aefg", "n": "ceg", "t": "defg",
}
def _h_seg(canvas, x1, y_mid, x2, sw, fill):
"""Draw a horizontal segment as a tapered hexagon (pointed ends)."""
hs = sw // 2
canvas.create_polygon(
x1, y_mid,
x1 + hs, y_mid - hs,
x2 - hs, y_mid - hs,
x2, y_mid,
x2 - hs, y_mid + hs,
x1 + hs, y_mid + hs,
fill=fill, outline="", tags="seg", smooth=False)
def _v_seg(canvas, x_mid, y1, y2, sw, fill):
"""Draw a vertical segment as a tapered hexagon (pointed ends)."""
hs = sw // 2
canvas.create_polygon(
x_mid, y1,
x_mid + hs, y1 + hs,
x_mid + hs, y2 - hs,
x_mid, y2,
x_mid - hs, y2 - hs,
x_mid - hs, y1 + hs,
fill=fill, outline="", tags="seg", smooth=False)
def draw_segments(canvas, x, y, w, h, chars, color_on, color_off, spacing=10):
"""Draw seven-segment characters on a Canvas.
Each segment is a tapered hexagonal polygon, wider in the middle,
pointed at the ends, matching real LED/LCD panel displays.
Decimal points are zero-width (drawn in the gap between digits).
"""
canvas.delete("seg")
sw = max(3, int(w * 0.13))
step = w + spacing
half_h = h // 2
gap = max(1, sw // 3)
col = 0
i = 0
while i < len(chars):
ch_val = chars[i]
# Decimal point is zero-width
if ch_val == ".":
dp_x = x + col * step - spacing // 2
dp_y = y + h - sw // 2
dp_r = max(2, sw // 2)
canvas.create_oval(dp_x - dp_r, dp_y - dp_r,
dp_x + dp_r, dp_y + dp_r,
fill=color_on, outline="", tags="seg")
i += 1
continue
cx = x + col * step
active = SEGMENTS.get(ch_val, "")
# Segment center positions
hs = sw // 2
left = cx + hs
right = cx + w - hs
top = y + hs
bot = y + h - hs
mid = y + half_h
# Horizontal segments: a (top), g (middle), d (bottom)
_h_seg(canvas, left, top, right, sw,
color_on if "a" in active else color_off)
_h_seg(canvas, left, mid, right, sw,
color_on if "g" in active else color_off)
_h_seg(canvas, left, bot, right, sw,
color_on if "d" in active else color_off)
# Vertical segments: f (top-left), b (top-right)
_v_seg(canvas, cx + hs, top + gap, mid - gap, sw,
color_on if "f" in active else color_off)
_v_seg(canvas, cx + w - hs, top + gap, mid - gap, sw,
color_on if "b" in active else color_off)
# Vertical segments: e (bottom-left), c (bottom-right)
_v_seg(canvas, cx + hs, mid + gap, bot - gap, sw,
color_on if "e" in active else color_off)
_v_seg(canvas, cx + w - hs, mid + gap, bot - gap, sw,
color_on if "c" in active else color_off)
# Check if next char is a decimal point
if i + 1 < len(chars) and chars[i + 1] == ".":
dp_x = cx + w + spacing // 2
dp_y = y + h - sw // 2
dp_r = max(2, sw // 2)
canvas.create_oval(dp_x - dp_r, dp_y - dp_r,
dp_x + dp_r, dp_y + dp_r,
fill=color_on, outline="", tags="seg")
i += 1
col += 1
i += 1
def format_7seg(value, width=8, decimals=None):
"""Format a float for seven-segment display.
Returns a string where non-dot characters == width exactly.
Dots are zero-width (drawn attached to the preceding digit).
No scientific notation. Real panel meters don't use it.
"""
if value is None or math.isnan(value):
return (" " * (width - 3) + "---")[:width]
if math.isinf(value):
s = "oFL" if value > 0 else "-FL"
return (" " * (width - len(s)) + s)[:width]
def digit_count(s):
return sum(1 for c in s if c != ".")
if decimals is not None:
text = f"{value:.{decimals}f}"
else:
# Auto-select decimals to fill the display width
sign_chars = 1 if value < 0 else 0
int_part = int(abs(value))
int_chars = max(1, len(str(int_part))) + sign_chars
if int_chars >= width:
text = str(int(value))
else:
avail = width - int_chars - 1 # -1 for the dot
avail = max(0, min(avail, 6))
text = f"{value:.{avail}f}"
# Truncate trailing decimals if too wide
while digit_count(text) > width:
if "." in text and not text.endswith("."):
text = text[:-1]
elif text.endswith("."):
text = text[:-1]
else:
# Integer overflow, show "oFL"
text = "-oFL" if value < 0 else " oFL"
break
# Pad with leading spaces
pad = width - digit_count(text)
if pad > 0:
text = " " * pad + text
return text
# ── Data store ───────────────────────────────────────────────────────────────
class DataStore:
def __init__(self):
self.lock = threading.Lock()
self.fields = [] # [(key, group, title, units)]
self.field_keys = set()
self.current = {}
self.frame_count = 0
self.last_frame_time = None
@property
def is_active(self):
return self.last_frame_time is not None and (time.time() - self.last_frame_time) < IDLE_SEC
def ingest(self, frame):
now = time.time()
with self.lock:
self.frame_count += 1
self.last_frame_time = now
idx = 0
for group in frame.get("groups", []):
gt = group.get("title", "")
for ds in group.get("datasets", []):
title = ds.get("title", f"Field {idx}")
units = ds.get("units", "")
try:
val = float(ds.get("value", ""))
except (ValueError, TypeError):
idx += 1
continue
key = f"f{idx}"
self.current[key] = val
if key not in self.field_keys:
self.field_keys.add(key)
self.fields.append((key, gt, title, units))
idx += 1
# ── Indicator Display Window ─────────────────────────────────────────────────
class IndicatorWindow:
"""Single seven-segment indicator display."""
DIGIT_W = 36
DIGIT_H = 64
NUM_DIGITS = 8
DISPLAY_PAD = 20
DIGIT_GAP = 10
def __init__(self, master, store, key, group, title, units, preset=None):
self.store = store
self.key = key
self.preset_name = preset or DEFAULT_PRESET
self.colors = PRESETS[self.preset_name]
self.units = units
self.label = f"{group} / {title}" if group else title
self.held = False
self.held_value = None
self.tare_offset = 0.0
self.peak_max = None
self.peak_min = None
self.decimals = None
self.alert_hi = None
self.alert_lo = None
self.flash_state = False
step = self.DIGIT_W + self.DIGIT_GAP
disp_w = self.NUM_DIGITS * step + self.DISPLAY_PAD * 2
total_w = max(disp_w + 24, 420)
self.win = tk.Toplevel(master)
self.win.title(title)
self.win.geometry(f"{total_w}x310")
self.win.configure(bg=self.colors["bg"])
self.win.resizable(False, False)
self.win.protocol("WM_DELETE_WINDOW", self._close)
# ── Display area ─────────────────────────────────────────────────
self.canvas = tk.Canvas(
self.win, width=disp_w, height=self.DIGIT_H + self.DISPLAY_PAD * 2,
bg=self.colors["bg"], highlightthickness=1,
highlightbackground=self.colors["dim"],
)
self.canvas.pack(padx=10, pady=(10, 4))
# ── Label + units ────────────────────────────────────────────────
info_frame = tk.Frame(self.win, bg=self.colors["bg"])
info_frame.pack(fill="x", padx=12)
tk.Label(
info_frame, text=self.label, bg=self.colors["bg"],
fg=self.colors["label"], font=(SANS_FONT, 11, "bold"),
anchor="w",
).pack(side="left")
self.units_lbl = tk.Label(
info_frame, text=units, bg=self.colors["bg"],
fg=self.colors["label"], font=(SANS_FONT, 11),
anchor="e",
)
self.units_lbl.pack(side="right")
# ── Min/Max/Peak bar ─────────────────────────────────────────────
stats_frame = tk.Frame(self.win, bg=self.colors["bg"])
stats_frame.pack(fill="x", padx=12, pady=(2, 4))
self.min_lbl = tk.Label(
stats_frame, text="MIN: -", bg=self.colors["bg"],
fg=DIM, font=(MONO_FONT, 9), anchor="w",
)
self.min_lbl.pack(side="left")
self.max_lbl = tk.Label(
stats_frame, text="MAX: -", bg=self.colors["bg"],
fg=DIM, font=(MONO_FONT, 9), anchor="e",
)
self.max_lbl.pack(side="right")
self.peak_lbl = tk.Label(
stats_frame, text="", bg=self.colors["bg"],
fg=DIM, font=(MONO_FONT, 9),
)
self.peak_lbl.pack()
# ── Buttons ──────────────────────────────────────────────────────
btn_frame = tk.Frame(self.win, bg=self.colors["bg"])
btn_frame.pack(fill="x", padx=10, pady=(4, 8))
self.btn_frame = btn_frame
self.buttons = []
self.hold_btn = self._make_btn(btn_frame, "HOLD", self._toggle_hold)
self.hold_btn.pack(side="left", padx=(0, 3))
self._make_btn(btn_frame, "TARE", self._tare).pack(side="left", padx=3)
self._make_btn(btn_frame, "PEAK", self._toggle_peak).pack(side="left", padx=3)
self._make_btn(btn_frame, "RESET", self._reset).pack(side="left", padx=3)
# Color cycle button
self._make_btn(btn_frame, "COLOR", self._cycle_color).pack(side="right", padx=(3, 0))
# Decimals cycle button
self.dec_btn = self._make_btn(btn_frame, "DEC:A", self._cycle_decimals)
self.dec_btn.pack(side="right", padx=3)
self._dec_options = ["Auto", "0", "1", "2", "3", "4", "5"]
self._dec_idx = 0
self._color_names = list(PRESETS.keys())
self._color_idx = self._color_names.index(preset)
self.peak_mode = False
self.alive = True
self._tick()
def _make_btn(self, parent, text, command):
"""Create a styled label-button matching the indicator theme."""
lbl = tk.Label(
parent, text=f" {text} ", cursor="hand2",
bg=self.colors["dim"], fg=self.colors["label"],
font=(MONO_FONT, 9, "bold"), padx=6, pady=4,
)
lbl.bind("<Button-1>", lambda _: command())
lbl.bind("<Enter>", lambda _: lbl.config(bg=self.colors["digit"], fg=self.colors["bg"]))
lbl.bind("<Leave>", lambda _: lbl.config(
bg=self.colors["dim"] if not getattr(lbl, "_active", False) else self.colors["digit"],
fg=self.colors["label"] if not getattr(lbl, "_active", False) else self.colors["bg"],
))
self.buttons.append(lbl)
return lbl
def _restyle_buttons(self):
"""Update all button colors to match current theme."""
for lbl in self.buttons:
try:
if not getattr(lbl, "_active", False):
lbl.config(bg=self.colors["dim"], fg=self.colors["label"])
else:
lbl.config(bg=self.colors["digit"], fg=self.colors["bg"])
except tk.TclError:
pass
def _toggle_hold(self):
self.held = not self.held
if self.held:
with self.store.lock:
self.held_value = self.store.current.get(self.key, 0) - self.tare_offset
self.hold_btn._active = True
self.hold_btn.config(bg=self.colors["digit"], fg=self.colors["bg"])
else:
self.held_value = None
self.hold_btn._active = False
self.hold_btn.config(bg=self.colors["dim"], fg=self.colors["label"])
def _tare(self):
with self.store.lock:
self.tare_offset = self.store.current.get(self.key, 0)
self.peak_max = None
self.peak_min = None
def _toggle_peak(self):
self.peak_mode = not self.peak_mode
if not self.peak_mode:
self.peak_max = None
self.peak_min = None
def _reset(self):
self.tare_offset = 0.0
self.peak_max = None
self.peak_min = None
self.held = False
self.held_value = None
self.hold_btn._active = False
self.hold_btn.config(bg=self.colors["dim"], fg=self.colors["label"])
def _cycle_color(self):
self._color_idx = (self._color_idx + 1) % len(self._color_names)
name = self._color_names[self._color_idx]
self.preset_name = name
self.colors = PRESETS[name]
self.win.configure(bg=self.colors["bg"])
self.canvas.configure(bg=self.colors["bg"],
highlightbackground=self.colors["dim"])
# Update all child backgrounds
def update_bg(widget):
try:
if isinstance(widget, (tk.Frame, tk.Label)):
widget.configure(bg=self.colors["bg"])
if isinstance(widget, tk.Label):
if widget.cget("fg") != DIM:
widget.configure(fg=self.colors["label"])
except tk.TclError:
pass
for child in widget.winfo_children():
update_bg(child)
update_bg(self.win)
self._restyle_buttons()
self.btn_frame.configure(bg=self.colors["bg"])
def _cycle_decimals(self):
self._dec_idx = (self._dec_idx + 1) % len(self._dec_options)
val = self._dec_options[self._dec_idx]
self.decimals = None if val == "Auto" else int(val)
label = "DEC:A" if val == "Auto" else f"DEC:{val}"
self.dec_btn.config(text=label)
def to_dict(self):
return {
"key": self.key,
"label": self.label,
"units": self.units,
"preset": self.preset_name,
"decimals": self.decimals,
"tare": self.tare_offset,
}
def _close(self):
self.alive = False
self.win.destroy()
def _tick(self):
if not self.alive:
return
try:
self._update_display()
self.win.after(100, self._tick)
except (tk.TclError, RuntimeError):
self.alive = False
def _update_display(self):
with self.store.lock:
raw = self.store.current.get(self.key, 0)
val = raw - self.tare_offset
# Peak tracking
if self.peak_mode:
if self.peak_max is None:
self.peak_max = val
self.peak_min = val
else:
self.peak_max = max(self.peak_max, val)
self.peak_min = min(self.peak_min, val)
# Min/Max labels
if self.peak_min is not None:
self.min_lbl.config(text=f"MIN: {self.peak_min:.4f}")
self.max_lbl.config(text=f"MAX: {self.peak_max:.4f}")
else:
self.min_lbl.config(text="MIN: -")
self.max_lbl.config(text="MAX: -")
if self.peak_mode:
self.peak_lbl.config(text="PEAK", fg=self.colors["digit"])
else:
self.peak_lbl.config(text="")
# Display value
display_val = self.held_value if self.held else val
text = format_7seg(display_val, self.NUM_DIGITS, self.decimals)
# Draw segments
draw_segments(
self.canvas,
self.DISPLAY_PAD, self.DISPLAY_PAD,
self.DIGIT_W, self.DIGIT_H,
text, self.colors["digit"], self.colors["dim"],
spacing=self.DIGIT_GAP,
)
# ── Master Window ────────────────────────────────────────────────────────────
class MasterApp:
def __init__(self, store, client):
self.store = store
self.client = client
self.indicators = []
self.root = tk.Tk()
self.root.title("Digital Indicator Panel")
self.root.geometry("480x500")
self.root.minsize(380, 320)
self.root.configure(bg=BG)
self.root.protocol("WM_DELETE_WINDOW", self._quit)
# ── Header ───────────────────────────────────────────────────────
hdr = tk.Frame(self.root, bg=HEADER, height=44)
hdr.pack(fill="x")
hdr.pack_propagate(False)
tk.Label(hdr, text="Digital Indicator Panel", bg=HEADER, fg=TEXT,
font=(SANS_FONT, 13, "bold")).pack(side="left", padx=14)
self.status = tk.Label(hdr, text="● Connecting", bg=HEADER, fg=DIM,
font=(SANS_FONT, 11))
self.status.pack(side="right", padx=14)
tk.Frame(self.root, bg=BORDER, height=1).pack(fill="x")
# ── Instructions ─────────────────────────────────────────────────
tk.Label(
self.root, text="Double-click a dataset to open an indicator display",
bg=BG, fg=DIM, font=(SANS_FONT, 10), anchor="w",
).pack(fill="x", padx=14, pady=(8, 4))
# ── Dataset list ─────────────────────────────────────────────────
style = ttk.Style()
style.theme_use("default")
style.configure("DI.Treeview",
background=SURFACE, foreground=TEXT,
fieldbackground=SURFACE, rowheight=28,
borderwidth=0, font=(MONO_FONT, 11))
style.configure("DI.Treeview.Heading",
background=HEADER, foreground=DIM,
borderwidth=0, relief="flat",
font=(SANS_FONT, 10, "bold"))
style.map("DI.Treeview",
background=[("selected", "#1f3a5f")],
foreground=[("selected", ACCENT)])
style.layout("DI.Treeview", [("Treeview.treearea", {"sticky": "nswe"})])
tf = tk.Frame(self.root, bg=BG)
tf.pack(fill="both", expand=True, padx=12, pady=(0, 4))
cols = ("GROUP", "DATASET", "VALUE", "UNITS")
self.tree = ttk.Treeview(tf, columns=cols, show="headings", style="DI.Treeview")
ws = (120, 140, 100, 60)
for col, w in zip(cols, ws):
self.tree.heading(col, text=col)
self.tree.column(col, width=w, anchor="w" if col in ("GROUP", "DATASET") else "e",
minwidth=40)
self.tree.pack(side="left", fill="both", expand=True)
self.tree.tag_configure("even", background=SURFACE)
self.tree.tag_configure("odd", background="#111820")
self.tree.bind("<Double-1>", self._on_double_click)
# ── Footer ───────────────────────────────────────────────────────
tk.Frame(self.root, bg=BORDER, height=1).pack(fill="x")
ftr = tk.Frame(self.root, bg=BG, height=28)
ftr.pack(fill="x")
ftr.pack_propagate(False)
self.lbl_fc = tk.Label(ftr, text="0 frames", bg=BG, fg=DIM, font=(MONO_FONT, 10))
self.lbl_fc.pack(side="left", padx=14)
self.lbl_indicators = tk.Label(ftr, text="0 displays", bg=BG, fg=DIM,
font=(MONO_FONT, 10))
self.lbl_indicators.pack(side="right", padx=14)
self.iid_map = {}
self._tick()
def _on_double_click(self, event):
sel = self.tree.selection()
if not sel:
return
item = self.tree.item(sel[0])
vals = item["values"]
group, title, _, units = vals
# Find the key (release lock before creating the window)
found = None
with self.store.lock:
for key, g, t, u in self.store.fields:
if g == group and t == title:
found = (key, g, t, u)
break
if found:
key, g, t, u = found
ind = IndicatorWindow(
self.root, self.store, key, g, t, u,
preset=DEFAULT_PRESET,
)
self.indicators.append(ind)
def _fmt(self, v):
a = abs(v)
if a == 0: return "0"
if a >= 1e6: return f"{v/1e6:.2f}M"
if a >= 100: return f"{v:.1f}"
if a >= 1: return f"{v:.3f}"
if a >= 0.01:return f"{v:.4f}"
return f"{v:.2e}"
def _tick(self):
if not self.client.running:
self.root.destroy()
return
# Status
with self.store.lock:
fc = self.store.frame_count
active = self.store.is_active
if not self.client.connected:
self.status.config(text="● Reconnecting…", fg=RED)
elif active:
self.status.config(text="● Live", fg=GREEN)
elif fc > 0:
self.status.config(text="● Idle", fg=DIM)
else:
self.status.config(text="● Connected", fg=ACCENT)
self.lbl_fc.config(text=f"{fc:,} frames")
# Clean dead indicators
self.indicators = [i for i in self.indicators if i.alive]
self.lbl_indicators.config(text=f"{len(self.indicators)} displays")
# Update dataset list
with self.store.lock:
for i, (key, group, title, units) in enumerate(self.store.fields):
val = self.store.current.get(key, 0)
tag = "even" if i % 2 == 0 else "odd"
values = (group, title, self._fmt(val), units)
if key in self.iid_map:
self.tree.item(self.iid_map[key], values=values, tags=(tag,))
else:
iid = self.tree.insert("", "end", values=values, tags=(tag,))
self.iid_map[key] = iid
self.root.after(150, self._tick)
def _save_state(self):
displays = [ind.to_dict() for ind in self.indicators if ind.alive]
if self.client.connected:
self.client.execute("extensions.saveState",
{"pluginId": "digital-indicator",
"state": {"displays": displays}})
def _restore_state(self):
if not self.client.connected:
return
def _load():
ok, result = self.client.execute(
"extensions.loadState", {"pluginId": "digital-indicator"})
if ok and isinstance(result, dict):
state = result.get("state", result)
if state:
self.root.after(0, lambda: self._on_state_loaded(state))
threading.Thread(target=_load, daemon=True).start()
def _on_state_loaded(self, state):
if not state or "displays" not in state:
return
def try_restore():
with self.store.lock:
has_fields = len(self.store.fields) > 0
if not has_fields:
self.root.after(500, try_restore)
return
for dc in state["displays"]:
key = dc.get("key", "")
if not key:
continue
found = None
with self.store.lock:
for k, g, t, u in self.store.fields:
if k == key:
found = (k, g, t, u)
break
if found:
k, g, t, u = found
ind = IndicatorWindow(
self.root, self.store, k, g, t, u,
preset=dc.get("preset", DEFAULT_PRESET))
ind.decimals = dc.get("decimals")
ind.tare_offset = dc.get("tare", 0.0)
self.indicators.append(ind)
self.root.after(100, try_restore)
def _on_event(self, event_name):
if event_name == "disconnected":
self._save_state()
elif event_name == "connected":
self._restore_state()
def _quit(self):
self._save_state()
for ind in self.indicators:
ind.alive = False
try:
ind.win.destroy()
except tk.TclError:
pass
self.client.running = False
self.root.destroy()
def run(self):
self.root.mainloop()
# ── Main ─────────────────────────────────────────────────────────────────────
def main():
store = DataStore()
client = GRPCClient()
client.on_frame = store.ingest
signal.signal(signal.SIGTERM, lambda *_: setattr(client, "running", False))
signal.signal(signal.SIGINT, lambda *_: setattr(client, "running", False))
if not client.connect():
print("[Indicator] Waiting for API server…", file=sys.stderr)
threading.Thread(target=client.run_loop, daemon=True).start()
try:
app = MasterApp(store, client)
client.on_event = app._on_event
app._restore_state()
app.run()
except Exception as e:
print(f"[Indicator] {e}", file=sys.stderr)
client.stop()
if __name__ == "__main__":
main()