-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverdig_ui.py
More file actions
1056 lines (905 loc) · 43.5 KB
/
Copy pathverdig_ui.py
File metadata and controls
1056 lines (905 loc) · 43.5 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
"""Coherent Verdi-G laser control GUI.
A small myTk front-end for the Coherent Verdi-G CW laser on a HOPS supply,
driven through PyHardwareLibrary's ``VerdiGDevice``. It offers:
* an emission On/Off button (the laser enable line),
* a shutter Open/Close button,
* a power monitor (live output power) with a settable power setpoint,
* a diagnostics panel: interlock, main temperature, remote-control state, faults.
The Verdi-G is not a serial-ASCII device: its FT2232 is driven as bit-banged
I2C, abstracted behind a ``HOPSInterface`` with a native (pyftdi) and a
CohrHOPS.dll transport. VerdiGDevice picks one with ``--interface auto`` (native
first, then the DLL); pass ``--interface native|dll`` to force one, or ``--url``
to pin a specific pyftdi device.
All device I/O runs on a single background worker thread owned by
PyHardwareLibrary's ``DeviceController`` (poll, connect, and user commands all
flow through it), so a blocking I2C exchange never freezes the UI. The controller
reports connect/disconnect/status/failure through the ``NotificationCenter``;
this app observes those and marshals each onto the Tk main thread via
``App.schedule_on_main_thread``, where they are assigned to Bindable properties
that update the widgets automatically.
Use ``--simulate`` to drive a DebugVerdiGDevice when no hardware is reachable.
Run:
python verdig_ui.py # discover the Verdi-G (native, then DLL)
python verdig_ui.py --interface dll # force the CohrHOPS.dll transport
python verdig_ui.py --url ftdi://ftdi:2232/1
python verdig_ui.py --simulate # no hardware needed
The same executable is also a command-line remote for a *running* app (it talks
to the RPC server RemoteControllable exposes):
python verdig_ui.py ctl status # on/off/open/close/set/status
python verdig_ui.py install-cli # add a `verdig-ctl` command to PATH
verdig-ctl on # once installed
"""
import argparse
import os
import sys
from contextlib import suppress
# matplotlib is pulled in transitively (via PyHardwareLibrary), even though this
# app never plots. Pin its cache to a stable per-user dir so the font cache is
# built once and reused. A frozen PyInstaller app otherwise points MPLCONFIGDIR
# at a fresh temp dir (deleted at exit), so matplotlib rebuilt the font cache on
# *every* verdig-ctl call. Must run before matplotlib is first imported — i.e.
# before the mytk / hardwarelibrary imports below.
try:
_mpl_cache = os.path.join(os.path.expanduser("~"), ".verdig", "matplotlib")
os.makedirs(_mpl_cache, exist_ok=True)
os.environ["MPLCONFIGDIR"] = _mpl_cache
except OSError:
pass
from tkinter import TclError
from mytk import (
App,
BooleanIndicator,
Box,
Button,
Dialog,
FormattedEntry,
Label,
Level,
RemoteControllable,
remote_command,
)
from hardwarelibrary.sources.verdig import (
VerdiGDevice,
DebugVerdiGDevice,
HOPSInterface,
)
from hardwarelibrary.devicecontroller import (
DeviceController,
DeviceControllerNotification as N,
connectionErrorReason,
)
from hardwarelibrary.notificationcenter import NotificationCenter
# Version is injected at build time by packaging/make_version.py (from the git
# tag); falls back to a dev marker when running from a checkout.
try:
from _version import __version__
except Exception:
__version__ = "0.0.0+dev"
# The app's identity: the window/menu name, the mDNS service name the app
# advertises (advertise_remote), and the name verdig-ctl discovers.
APP_NAME = "Verdi-G Control"
# Interface selection (auto/native/dll) and any pyftdi URL are the app's only
# transport knobs: VerdiGDevice discovers the HOPS FT2232 itself. There is no
# serial "port" to pin (the HOPS bus is I2C, not a COM port).
class VerdiGGuiDevice(VerdiGDevice):
"""VerdiGDevice whose status poll never raises when a value is unavailable.
On the native pyftdi transport ``getPower()`` raises ``NotCalibrated`` (a
``HOPSInterface.NotSupported``) as soon as the laser emits but no power
calibration has been set. The stock ``doGetStatusUserInfo`` only guards
interlock/faults, so that exception would reach ``DeviceController.poll`` and
be mistaken for a dropped connection — the laser would appear to disconnect
the instant it lased. Here power and setpoint degrade to ``None`` the same
way interlock/faults already do, so the poll always returns a dict and the
UI shows "—" for the unknown value.
"""
def doGetStatusUserInfo(self) -> dict:
try:
power = self.doGetPower()
except HOPSInterface.NotSupported:
power = None
try:
setpoint = self.powerSetpoint()
except HOPSInterface.NotSupported:
setpoint = None
info = {
"power": power,
"setpoint": setpoint,
"isLaserOn": self.doGetOnOffState(),
"isShutterOpen": self.doGetShutterState(),
"remoteControl": self.remoteControlIsOn(),
"mainTemperature": self.mainTemperature(),
}
try:
info["interlockOk"] = self.doGetInterlockState()
info["faults"] = self.faults()
except HOPSInterface.NotSupported:
info["interlockOk"] = None
info["faults"] = None
return info
class VerdiGApp(App, RemoteControllable):
"""A myTk App that builds the window and wires the widgets to the controller.
Mixes in `RemoteControllable`, so the laser commands (turn_on, turn_off,
open_shutter, close_shutter, set_power) and a status query are reachable over
RPC from another process via ``mytk.connect(...)`` (localhost only, see
:meth:`_register_remote_api`).
"""
HELP_URL = "https://github.com/DCC-Lab/VerdiG"
MAX_POWER = 8.0 # full-scale of the power Level bar (W); head max is 7.344 W
STATUS_COLORS = {
"ok": "#1a7f37",
"info": "#57606a",
"warn": "#9a6700",
"error": "#cf222e",
}
def __init__(self, simulate=False, interface="auto", url=None,
remote=True, remote_port=0):
self.simulate_arg = simulate
self.interface_arg = interface
self.url_arg = url
self.remote_enabled = remote
self.remote_port = remote_port
# Last known truth, so a button click can send the *opposite* action.
# These drive *derived* UI (button labels/enablement, status colour) and
# are observed rather than value-bound (see _bind_state_to_ui).
self.connected = False
self.monitoring = False # disconnected but auto-reconnecting
self.busy = False
# Whether each laser state is currently known (False before the first
# poll and after a drop); drives the "—" text and disables the buttons.
self.emission_known = False
self.shutter_known = False
self.power_known = False
self.setpoint_known = False
self.temp_known = False
self.remote_known = False
self.interlock_known = False
# Displayed state value-bound 1:1 to widgets via the Bindable mixin.
# The boolean indicators need plain bools (never None — a BooleanVar
# cannot hold None); the "known" flags above say whether the bool is
# meaningful yet.
self.emission_on = False
self.shutter_open = False
self.interlock_ok = False
self.remote_control = False
self.power = 0.0 # W, live reading (0.0 when unknown)
self.power_setpoint = 0.0 # W, commanded setpoint
self.main_temperature = 0.0 # °C
self.faults_text = "—"
self.identity = ""
self.status = "Starting…"
self.status_kind = "info"
super().__init__(
geometry="640x560",
name=APP_NAME,
help_url=self.HELP_URL,
)
# App titles the window from `name`; use a richer title with the version.
self.root.title(
"Verdi-G — Laser Control (v{0})".format(__version__))
# PyHardwareLibrary's DeviceController owns the worker thread and reports
# through the NotificationCenter; it is created in _start_controller once
# the UI exists to observe it.
self.device = None
self.controller = None
self._build_ui()
self._bind_state_to_ui()
# Clicking the window's close box routes through quit() so the worker
# thread and device are released cleanly.
self.root.protocol("WM_DELETE_WINDOW", self.quit)
self._refresh_ui()
# Build the device + DeviceController and auto-connect. Done before the
# RPC server starts so a remote call can never see a None controller.
self._start_controller()
# Expose the laser commands over RPC (localhost) if enabled.
self._register_remote_api()
# -- UI construction --
def _build_ui(self):
window = self.window
# --- Emission (On/Off) -----------------------------------------
emission_box = Box(label="Emission")
emission_box.grid_into(window, column=0, row=0, padx=8, pady=6, sticky="nsew")
self.emission_indicator = BooleanIndicator(diameter=18)
self.emission_indicator.grid_into(emission_box, column=0, row=0, padx=8, pady=8)
self.emission_state_label = Label(text="—")
self.emission_state_label.grid_into(emission_box, column=1, row=0,
padx=4, pady=8, sticky="w")
self.emission_button = Button(
"Turn On", width=12, user_event_callback=self._on_emission_clicked
)
self.emission_button.grid_into(emission_box, column=0, row=1, columnspan=2,
padx=8, pady=(0, 8))
# --- Shutter (Open/Close) --------------------------------------
shutter_box = Box(label="Shutter")
shutter_box.grid_into(window, column=1, row=0, padx=8, pady=6, sticky="nsew")
self.shutter_indicator = BooleanIndicator(diameter=18)
self.shutter_indicator.grid_into(shutter_box, column=0, row=0, padx=8, pady=8)
self.shutter_state_label = Label(text="—")
self.shutter_state_label.grid_into(shutter_box, column=1, row=0,
padx=4, pady=8, sticky="w")
self.shutter_button = Button(
"Open Shutter", width=12, user_event_callback=self._on_shutter_clicked
)
self.shutter_button.grid_into(shutter_box, column=0, row=1, columnspan=2,
padx=8, pady=(0, 8))
# --- Power monitor + setpoint ----------------------------------
power_box = Box(label="Power Monitor")
power_box.grid_into(window, column=0, row=1, columnspan=2,
padx=8, pady=6, sticky="nsew")
self.power_value_label = Label(text="—")
self.power_value_label.grid_into(power_box, column=0, row=0,
padx=8, pady=(8, 2), sticky="w")
self.setpoint_label = Label(text="setpoint —")
self.setpoint_label.grid_into(power_box, column=1, row=0,
padx=8, pady=(8, 2), sticky="e")
# A wide fixed-size bar that spans the box. (We deliberately do NOT
# stretch it via a weighted cell + <Configure> handler: mytk's
# CanvasView.on_resize calls update_idletasks(), so resizing the canvas
# from within a resize callback recurses until RecursionError.)
self.power_level = Level(maximum=self.MAX_POWER, width=600, height=22)
self.power_level.grid_into(power_box, column=0, row=1, columnspan=2,
padx=8, pady=(2, 8), sticky="w")
# Setpoint entry + explicit Set button (no live drag, so no accidental
# power change). Validation against the head's max power is the driver's
# job; an out-of-range value surfaces as a commandFailed status.
Label(text="Setpoint:").grid_into(power_box, column=0, row=2,
padx=(8, 2), pady=(0, 10), sticky="e")
self.power_entry = FormattedEntry(
value=0.0, character_width=7, format_string="{0:.2f}"
)
self.power_entry.grid_into(power_box, column=1, row=2,
padx=2, pady=(0, 10), sticky="w")
self.power_set_button = Button(
"Set", width=8, user_event_callback=self._on_set_power_clicked
)
self.power_set_button.grid_into(power_box, column=2, row=2,
padx=8, pady=(0, 10), sticky="w")
# --- Diagnostics -----------------------------------------------
diag_box = Box(label="Diagnostics")
diag_box.grid_into(window, column=0, row=2, columnspan=2,
padx=8, pady=6, sticky="nsew")
Label(text="Interlock:").grid_into(diag_box, column=0, row=0,
padx=(8, 2), pady=6, sticky="e")
self.interlock_indicator = BooleanIndicator(diameter=16)
self.interlock_indicator.grid_into(diag_box, column=1, row=0, padx=4, pady=6)
self.interlock_state_label = Label(text="—")
self.interlock_state_label.grid_into(diag_box, column=2, row=0,
padx=4, pady=6, sticky="w")
Label(text="Remote:").grid_into(diag_box, column=3, row=0,
padx=(16, 2), pady=6, sticky="e")
self.remote_indicator = BooleanIndicator(diameter=16)
self.remote_indicator.grid_into(diag_box, column=4, row=0, padx=4, pady=6)
self.remote_state_label = Label(text="—")
self.remote_state_label.grid_into(diag_box, column=5, row=0,
padx=4, pady=6, sticky="w")
Label(text="Main temp:").grid_into(diag_box, column=0, row=1,
padx=(8, 2), pady=6, sticky="e")
self.temp_label = Label(text="—")
self.temp_label.grid_into(diag_box, column=1, row=1, columnspan=2,
padx=4, pady=6, sticky="w")
Label(text="Faults:").grid_into(diag_box, column=3, row=1,
padx=(16, 2), pady=6, sticky="e")
self.faults_label = Label(text="—")
self.faults_label.grid_into(diag_box, column=4, row=1, columnspan=2,
padx=4, pady=6, sticky="w")
# --- Connection (kept at the bottom: normally untouched) --------
conn_box = Box(label="Connection")
conn_box.grid_into(window, column=0, row=3, columnspan=2,
padx=8, pady=6, sticky="nsew")
self.status_label = Label(text="Starting…")
self.status_label.grid_into(conn_box, column=0, row=0, columnspan=2,
padx=8, pady=(6, 2), sticky="w")
self.identity_label = Label(text="")
self.identity_label.grid_into(conn_box, column=0, row=1, columnspan=2,
padx=8, pady=(0, 4), sticky="w")
self.connect_button = Button(
"Connect", user_event_callback=self._on_connect_clicked
)
self.connect_button.grid_into(conn_box, column=0, row=2,
padx=8, pady=6, sticky="w")
window.all_resize_weight(1)
# -- state <-> UI binding (Bindable mixin) --
# State that drives *derived* UI (ON/OFF text, button labels/enablement,
# status colour, "—" placeholders) which cannot be value-bound 1:1, so we
# observe it and recompute in observed_property_changed. The boolean/value
# fields appear here too: besides driving their (value-bound) widgets, they
# change labels and button enablement.
DERIVED_TRIGGERS = frozenset(
{"connected", "monitoring", "busy", "status_kind",
"emission_on", "emission_known", "shutter_open", "shutter_known",
"power", "power_known", "power_setpoint", "setpoint_known",
"main_temperature", "temp_known", "remote_control", "remote_known",
"interlock_ok", "interlock_known"}
)
def _bind_state_to_ui(self):
"""Connect model state to widgets with the Bindable mixin.
Two-way value bindings keep a property and a widget's ``value_variable``
synchronised automatically. State that first needs a transformation
before it can be shown (the "—" placeholders, the formatted power/temp
text) is handled by observing it and recomputing in
:meth:`observed_property_changed`.
Must run after :meth:`_build_ui`: a widget's ``value_variable`` only
exists once the widget has been placed on screen.
"""
# Direct value bindings — one property, one (or more) widgets.
self.bind_property_to_widget_value("emission_on", self.emission_indicator)
self.bind_property_to_widget_value("shutter_open", self.shutter_indicator)
self.bind_property_to_widget_value("interlock_ok", self.interlock_indicator)
self.bind_property_to_widget_value("remote_control", self.remote_indicator)
self.bind_property_to_widget_value("power", self.power_level)
self.bind_property_to_widget_value("faults_text", self.faults_label)
self.bind_property_to_widget_value("identity", self.identity_label)
self.bind_property_to_widget_value("status", self.status_label)
# Derived UI — observe the raw state; recompute in the callback.
for name in self.DERIVED_TRIGGERS:
self.add_observer(self, name)
def observed_property_changed(self, observed, name, value, context):
# Let Bindable service the two-way value bindings first...
super().observed_property_changed(observed, name, value, context)
# ...then recompute anything that is a *function* of the raw state.
if name in self.DERIVED_TRIGGERS:
self._refresh_ui()
def _refresh_ui(self):
"""Recompute the derived UI from the current state.
The value-bound widgets (indicators, level bar, faults line) update
themselves; only the tri-state text, the formatted power/temperature
readouts, the status colour, and the buttons are computed here.
"""
self.emission_state_label.value_variable.set(
self._state_text(self.emission_known, self.emission_on, "ON", "OFF"))
self.shutter_state_label.value_variable.set(
self._state_text(self.shutter_known, self.shutter_open, "OPEN", "CLOSED"))
self.interlock_state_label.value_variable.set(
self._state_text(self.interlock_known, self.interlock_ok, "OK", "FAULT"))
self.remote_state_label.value_variable.set(
self._state_text(self.remote_known, self.remote_control, "ON", "OFF"))
self.power_value_label.value_variable.set(
"—" if not self.power_known else "{0:.2f} W".format(self.power))
self.setpoint_label.value_variable.set(
"setpoint —" if not self.setpoint_known
else "setpoint {0:.2f} W".format(self.power_setpoint))
self.temp_label.value_variable.set(
"—" if not self.temp_known else "{0:.1f} °C".format(self.main_temperature))
color = self.STATUS_COLORS.get(self.status_kind, "#000000")
with suppress(Exception):
self.status_label.widget.configure(foreground=color)
self._update_controls_enabled()
# -- DeviceController lifecycle --
def _make_device(self, simulate, interface, url):
"""Build the PhysicalDevice the controller will drive.
DebugVerdiGDevice is used in --simulate. Otherwise VerdiGGuiDevice picks
a HOPS transport (native pyftdi / CohrHOPS.dll) per ``interface``; ``url``
pins a specific pyftdi device when given.
"""
if simulate:
return DebugVerdiGDevice()
return VerdiGGuiDevice(interface=interface, url=url)
def _start_controller(self):
"""Create the DeviceController for the current device and connect.
The controller owns the single worker thread; we observe its
notifications and marshal each onto the Tk main thread.
"""
self.device = self._make_device(
self.simulate_arg, self.interface_arg, self.url_arg)
self.controller = DeviceController(self.device)
self._observe_controller()
self.controller.start()
self.controller.connect()
def _stop_controller(self):
"""Stop the worker and drop our observers (safe if never started)."""
NotificationCenter().removeObserver(self)
if self.controller is not None:
self.controller.stop()
self.controller = None
def _observe_controller(self):
nc = NotificationCenter()
for name in (N.didConnect, N.didDisconnect, N.connectionLost,
N.connectionFailed, N.status, N.commandFailed):
nc.addObserver(self, self._controller_did_post, name, self.controller)
# -- controller notifications -> main thread -> bound state --
def _controller_did_post(self, notification):
# Runs on the controller's worker thread; bounce onto the Tk main thread
# before touching state (bindings/observers then update the widgets).
self.schedule_on_main_thread(
self._apply_notification,
args=(notification.name, notification.userInfo))
def _apply_notification(self, name, user_info):
"""Translate one controller notification into bound state assignments.
The Bindable bindings/observers do the rest; each poll value may be
``None`` (not yet known, or unavailable on this transport), in which case
the matching "known" flag stays False and the UI shows "—".
"""
if name is N.didConnect:
self.identity = self._identity(user_info)
self.connected = True
self.monitoring = False
self.busy = False
self.status = "Connected"
self.status_kind = "ok"
elif name is N.status:
self._apply_status(user_info)
elif name is N.connectionLost:
self._enter_monitoring(
"Connection lost ({0}). Watching for the Verdi-G — will "
"reconnect automatically.".format(user_info))
elif name is N.connectionFailed:
self._enter_monitoring(self._connection_message(user_info))
elif name is N.didDisconnect:
self.connected = False
self.monitoring = False
self.busy = False
self.identity = ""
self._clear_laser_state()
self.status = "Disconnected"
self.status_kind = "info"
elif name is N.commandFailed:
self.busy = False
self.status = "Command failed: {0}".format(user_info)
self.status_kind = "error"
def _apply_status(self, info):
"""Fan one status-poll dict out to the bound state (see doGetStatusUserInfo)."""
emission = info.get("isLaserOn")
self.emission_on = bool(emission)
self.emission_known = emission is not None
shutter = info.get("isShutterOpen")
self.shutter_open = bool(shutter)
self.shutter_known = shutter is not None
power = info.get("power")
self.power = power if power is not None else 0.0
self.power_known = power is not None
setpoint = info.get("setpoint")
self.power_setpoint = setpoint if setpoint is not None else 0.0
self.setpoint_known = setpoint is not None
temperature = info.get("mainTemperature")
self.main_temperature = temperature if temperature is not None else 0.0
self.temp_known = temperature is not None
remote = info.get("remoteControl")
self.remote_control = bool(remote)
self.remote_known = remote is not None
interlock = info.get("interlockOk")
self.interlock_ok = bool(interlock)
self.interlock_known = interlock is not None
self.faults_text = self._faults_text(info.get("faults"))
self.busy = False
def _clear_laser_state(self):
"""Mark every laser value unknown (indicators off, "—" text, bar at 0)."""
self.emission_on = False
self.emission_known = False
self.shutter_open = False
self.shutter_known = False
self.interlock_ok = False
self.interlock_known = False
self.remote_control = False
self.remote_known = False
self.power = 0.0
self.power_known = False
self.power_setpoint = 0.0
self.setpoint_known = False
self.main_temperature = 0.0
self.temp_known = False
self.faults_text = "—"
def _enter_monitoring(self, message):
"""Common state for a lost/failed connection that will be retried."""
self.connected = False
self.monitoring = self.controller.autoReconnect
self.busy = False
self._clear_laser_state()
self.status = message
self.status_kind = "warn"
@staticmethod
def _identity(device):
model = getattr(device, "laserModel", None)
head = getattr(device, "headType", None)
label = model or "Verdi-G"
if head and head != model:
label += " ({0})".format(head)
serial_number = getattr(device, "headSerialNumber", None)
if serial_number:
label += " S/N {0}".format(serial_number)
max_power = getattr(device, "maxPower", None)
if max_power:
label += " max {0:.3g} W".format(max_power)
return label
@staticmethod
def _faults_text(faults):
"""Format the faults list: "—" unknown, "none" empty, else joined."""
if faults is None:
return "—"
if not faults:
return "none"
return ", ".join(str(fault) for fault in faults)
@staticmethod
def _connection_message(error):
"""Turn a connect failure into a user-facing line via the driver's
preserved error chain (connectionErrorReason from PyHardwareLibrary)."""
reason = connectionErrorReason(error)
if reason == "busy":
return ("The Verdi-G's FT2232 is busy — another program is using it "
"(e.g. Coherent's app, or a stale process). Close it and it "
"will reconnect automatically.")
if reason == "permission":
return "Permission denied opening the Verdi-G's USB interface."
if reason == "missing":
return ("No Verdi-G found (HOPS FT2232 not present). Waiting for it "
"to reappear…")
return "Could not connect: {0}".format(error or type(error).__name__)
@staticmethod
def _state_text(known, value, true_text, false_text):
"""The tri-state label text: "—" when unknown, else true/false text."""
return "—" if not known else (true_text if value else false_text)
# -- control enable/disable + button labels --
def _update_controls_enabled(self):
connected = self.connected
idle = connected and not self.busy
# While monitoring (disconnected but auto-reconnecting), the button
# reads "Disconnect" so a click cancels the auto-retry.
self.connect_button.label = (
"Disconnect" if (connected or self.monitoring) else "Connect"
)
self.emission_button.is_disabled = not idle or not self.emission_known
self.shutter_button.is_disabled = not idle or not self.shutter_known
self.power_set_button.is_disabled = not idle
self.emission_button.label = (
"Turn Off" if self.emission_on else "Turn On"
)
self.shutter_button.label = (
"Close Shutter" if self.shutter_open else "Open Shutter"
)
# -- callbacks (main thread) --
def _on_connect_clicked(self, event, button):
# "Disconnect" while connected OR while auto-reconnecting (cancels the
# monitoring); otherwise start connecting.
if self.connected or self.monitoring:
self.controller.disconnect()
else:
self.controller.connect()
def _on_emission_clicked(self, event, button):
if not self.emission_known:
return
self.turn_off() if self.emission_on else self.turn_on()
def _on_shutter_clicked(self, event, button):
if not self.shutter_known:
return
self.close_shutter() if self.shutter_open else self.open_shutter()
def _on_set_power_clicked(self, event, button):
self.set_power(self.power_entry.value)
# -- laser commands (invoked by the buttons; the surface exposed over RPC
# via RemoteControllable). Each submits a device action onto the
# controller's worker thread; DeviceController rejects it (commandFailed)
# when not connected, so they are safe to call any time. --
def _submit(self, action):
# Mark busy immediately (the observer disables the controls); the next
# status/commandFailed notification clears it.
self.busy = True
self.controller.submit(action)
@remote_command
def turn_on(self):
"""Turn laser emission on."""
self._submit(lambda device: device.turnOn())
@remote_command
def turn_off(self):
"""Turn laser emission off."""
self._submit(lambda device: device.turnOff())
@remote_command
def open_shutter(self):
"""Open the shutter."""
self._submit(lambda device: device.openShutter())
@remote_command
def close_shutter(self):
"""Close the shutter."""
self._submit(lambda device: device.closeShutter())
@remote_command
def set_power(self, watts):
"""Set the output-power setpoint (watts). Out-of-range values are
rejected by the driver and surface as a commandFailed status."""
target = float(watts)
self._submit(lambda device: device.setPower(target))
# -- remote control (RemoteControllable) --
def _register_remote_api(self):
"""Expose every ``@remote_command`` method over RPC and advertise it.
RemoteControllable marshals each remote call onto the Tk main thread, so
the exposed functions are exactly the ones the buttons call. Clients find
the app with ``mytk.discover(app_name=...)`` (or ``verdig-ctl``) and may
call turn_on/turn_off/open_shutter/close_shutter/set_power or ``status()``.
"""
if not self.remote_enabled:
return
# advertise_remote() = start_remote() (which auto-registers every
# @remote_command method, mytk >= 1.8) plus an mDNS/Zeroconf
# announcement, so clients discover us by name instead of a fixed port.
# remote_port=0 lets the OS pick a free port (it is advertised).
try:
bound_port = self.advertise_remote(port=self.remote_port)
print("Remote control advertised as '{0}' on port {1} — find it "
"with mytk.discover / verdig-ctl.".format(
self.name, bound_port))
except Exception as err:
# mDNS needs zeroconf + a usable network; if that fails, still serve
# so verdig-ctl --port works. Bind a known port (not 0) so the
# client has something to target without discovery.
bound_port = self.start_remote(
port=self.remote_port or 8778, app_name=self.name)
print("Remote control on port {0} (not advertised: {1}). "
"Use: verdig-ctl --port {0}.".format(bound_port, err))
@remote_command(name="status")
def remote_status(self):
"""Return a snapshot of the laser state for remote clients.
All values are XML-RPC serializable. Fields that are not yet known (not
polled, disconnected, or unavailable on this transport) are None.
"""
return {
"connected": self.connected,
"monitoring": self.monitoring,
"busy": self.busy,
"emission_on": self.emission_on if self.emission_known else None,
"shutter_open": self.shutter_open if self.shutter_known else None,
"power": self.power if self.power_known else None,
"setpoint": self.power_setpoint if self.setpoint_known else None,
"main_temperature": self.main_temperature if self.temp_known else None,
"remote_control": self.remote_control if self.remote_known else None,
"interlock_ok": self.interlock_ok if self.interlock_known else None,
"faults": self.faults_text,
"status": self.status,
"identity": self.identity,
}
# -- App lifecycle / menu overrides --
def quit(self):
"""Release the worker thread and device, then tear the window down."""
try:
self._stop_controller()
finally:
super().quit()
def save(self):
"""No document model to save; the File ▸ Save… menu item is inert here."""
Dialog.showinfo(
title="Nothing to save",
message="This application controls the laser live; there is no "
"document to save.",
)
def preferences(self):
"""No preferences UI yet."""
Dialog.showinfo(
title="Preferences",
message="There are no preferences for this application.",
)
def create_menu(self):
"""Add an "Install verdig-ctl" item to the File menu (above Quit)."""
super().create_menu()
menubar = self.root.nametowidget(self.root["menu"])
file_menu = self.root.nametowidget(menubar.entrycget("File", "menu"))
label = "Install “verdig-ctl” Command…"
try:
quit_index = file_menu.index("Quit")
file_menu.insert_separator(quit_index)
file_menu.insert_command(quit_index + 1, label=label,
command=self._install_cli_from_menu)
except TclError:
# No "Quit" entry to anchor to; just append.
file_menu.add_separator()
file_menu.add_command(label=label,
command=self._install_cli_from_menu)
def _install_cli_from_menu(self):
"""Menu action: install the verdig-ctl command and report via a dialog."""
try:
link, note = install_verdig_ctl()
except RuntimeError as err:
Dialog.showerror(
title="Could not install verdig-ctl", message=str(err))
return
message = ("Installed the command:\n\n {0}\n\nUse it from a terminal "
"while this app is running, e.g.\n verdig-ctl status"
.format(link))
if note:
message += "\n\n" + note
Dialog.showinfo(title="verdig-ctl installed", message=message)
# -- verdig-ctl : command-line remote control --------------------------------
CTL_ACTIONS = {
"on": "turn_on",
"off": "turn_off",
"open": "open_shutter",
"close": "close_shutter",
}
def cli_main(argv):
"""``verdig-ctl`` — drive a *running* VerdiG app over its RPC server.
This is the same executable as the GUI, invoked either through the
``verdig-ctl`` wrapper (see :func:`install_cli`) or as ``… ctl <cmd>``.
By default it finds the app on the local network with ``mytk.discover``
(mDNS); pass ``--port`` to connect directly to a known host/port instead.
"""
parser = argparse.ArgumentParser(
prog="verdig-ctl",
description="Control a running VerdiG laser application over its "
"remote-control (RPC) server.",
)
parser.add_argument(
"command", choices=["status", "on", "off", "open", "close", "set"],
help="status; on/off (emission); open/close (shutter); set <watts>.",
)
parser.add_argument("value", nargs="?", default=None,
help="Power in watts, required by 'set'.")
parser.add_argument("--port", type=int, default=None,
help="Connect directly to this port instead of "
"discovering the app over the network (mDNS).")
parser.add_argument("--host", default="127.0.0.1",
help="Host to use with --port (default 127.0.0.1).")
parser.add_argument("--timeout", type=float, default=3.0,
help="Seconds to wait for discovery (default 3).")
args = parser.parse_args(argv)
if args.command == "set" and args.value is None:
print("The 'set' command needs a power value, e.g. verdig-ctl set 2.0",
file=sys.stderr)
return 2
import mytk
try:
if args.port is not None:
remote = mytk.connect(host=args.host, port=args.port,
app_name=APP_NAME)
else:
remote = mytk.discover(app_name=APP_NAME, timeout=args.timeout)
except mytk.RemoteAppMismatch as err:
print("Reached a server, but it is not VerdiG: {0}".format(err),
file=sys.stderr)
return 2
except TimeoutError:
print("No VerdiG found on the network within {0:g}s. Is the app "
"running (and not launched with --no-remote)? You can also "
"connect directly with --port.".format(args.timeout),
file=sys.stderr)
return 2
except ImportError as err:
print("Network discovery needs the 'zeroconf' package: {0}".format(err),
file=sys.stderr)
return 2
except Exception as err: # connection refused, etc.
print("Cannot reach VerdiG: {0}".format(err), file=sys.stderr)
return 2
try:
if args.command == "status":
status = remote.status()
width = max((len(k) for k in status), default=0)
for key, value in status.items():
print("{0:<{1}} {2}".format(key, width, value))
elif args.command == "set":
remote.set_power(float(args.value))
print("Sent: set_power({0})".format(float(args.value)))
else:
method = CTL_ACTIONS[args.command]
getattr(remote, method)()
print("Sent: {0}".format(method))
except Exception as err:
print("Remote call failed: {0}".format(err), file=sys.stderr)
return 1
return 0
def install_verdig_ctl():
"""Install a ``verdig-ctl`` command on PATH; return ``(path, note)``.
Writes a small wrapper (not a bare symlink) that runs this program in CLI
mode with the *same* interpreter/binary it was installed from, so the
command always has the right dependencies (mytk >= 1.8): from the packaged
app it points at the self-contained bundle binary; from a source checkout it
points at the venv's python + this script. A plain symlink to the source
script would instead be run by ``/usr/bin/env python3`` (often the system
Python, which lacks the deps).
Tries ``/usr/local/bin`` first, then ``~/.local/bin``, then ``~/bin`` — the
first directory it can write to wins.
Returns:
tuple[pathlib.Path, str]: the created command, and a note (empty unless
the chosen directory is not on PATH).
Raises:
RuntimeError: if none of the candidate directories are writable.
"""
from pathlib import Path
name = "verdig-ctl"
# Use sys.executable verbatim — do NOT resolve() it: a venv's python is a
# symlink to the base interpreter, and following it would drop the venv's
# site-packages (i.e. lose mytk >= 1.8).
if getattr(sys, "frozen", False):
# Packaged app: the bundle binary is self-contained; it dispatches to
# CLI mode when its first argument is "ctl".
command = '"{0}"'.format(sys.executable)
else:
# Source checkout: run this script with the interpreter running us now
# (the venv python), not whatever a shebang would resolve to.
command = '"{0}" "{1}"'.format(sys.executable, Path(__file__).resolve())
wrapper = '#!/bin/sh\nexec {0} ctl "$@"\n'.format(command)
candidates = [
Path("/usr/local/bin"),
Path.home() / ".local" / "bin",
Path.home() / "bin",
]
problems = []
for directory in candidates:
entry = directory / name
try:
directory.mkdir(parents=True, exist_ok=True)
if entry.is_symlink() or entry.exists():
entry.unlink()
entry.write_text(wrapper)
entry.chmod(0o755)
except OSError as err:
problems.append("{0} ({1})".format(directory, err))
continue
note = ""
if str(directory) not in os.environ.get("PATH", "").split(os.pathsep):
note = ("{0} is not on your PATH — add it to your shell profile:\n"
" export PATH=\"{0}:$PATH\"".format(directory))
return entry, note
raise RuntimeError(
"Could not write verdig-ctl to any of:\n " + "\n ".join(problems))
def install_cli():
"""CLI wrapper around :func:`install_verdig_ctl` (prints, returns a code)."""
try:
link, note = install_verdig_ctl()
except RuntimeError as err:
print(err, file=sys.stderr)
return 1
print("Installed {0}".format(link))
if note:
print("\nNote: " + note)
print("\nThen, with the app running:\n verdig-ctl status")
return 0
def main():
"""Entry point: dispatch to the CLI, the installer, or the GUI."""
invoked = os.path.basename(sys.argv[0]).lower()
if invoked.startswith("verdig-ctl"):
return cli_main(sys.argv[1:])
if len(sys.argv) > 1:
if sys.argv[1] == "ctl":
return cli_main(sys.argv[2:])
if sys.argv[1] == "install-cli":
return install_cli()
return gui_main()
def gui_main():
parser = argparse.ArgumentParser(description="Coherent Verdi-G laser control GUI")
parser.add_argument(