-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatchbay.py
More file actions
executable file
·2821 lines (2473 loc) · 123 KB
/
patchbay.py
File metadata and controls
executable file
·2821 lines (2473 loc) · 123 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
"""Dante Patch Bay — PyQt6 GUI for managing Dante audio subscriptions."""
import sys
import asyncio
import time
import logging
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QCheckBox, QLabel, QLineEdit, QStatusBar,
QAbstractItemView, QStyledItemDelegate,
QTableWidget, QTableWidgetItem, QTabWidget,
QComboBox, QMessageBox,
)
from PyQt6.QtCore import Qt, QRect, QThread, pyqtSignal, QSize, QTimer
from PyQt6.QtGui import QColor, QFont, QBrush, QPainter, QPen
from netaudio.daemon.client import get_devices_from_daemon, device_request_via_daemon
from netaudio.dante.application import DanteApplication
from netaudio.dante.device_commands import DanteDeviceCommands
from netaudio.dante.protocol import DantePacket, DanteParser
from netaudio.dante.const import SUBSCRIPTION_STATUS_INFO
from netaudio.dante.events import EventType
from netaudio.dante.services.notification import (
NOTIFICATION_TX_CHANNEL_CHANGE,
NOTIFICATION_RX_CHANNEL_CHANGE,
NOTIFICATION_TX_FLOW_CHANGE,
NOTIFICATION_RX_FLOW_CHANGE,
NOTIFICATION_ROUTING_DEVICE_CHANGE,
NOTIFICATION_ROUTING_READY,
)
from netaudio.common.app_config import settings as netaudio_settings
netaudio_settings.mdns_timeout = 3
log = logging.getLogger("patchbay")
# Notification IDs that signal a routing/subscription change on a device.
_ROUTING_NOTIFICATION_IDS = {
NOTIFICATION_TX_CHANNEL_CHANGE, # 257 — TX channel assigned/changed
NOTIFICATION_RX_CHANNEL_CHANGE, # 258 — RX subscription changed
NOTIFICATION_TX_FLOW_CHANGE, # 260 — TX flow changed
NOTIFICATION_RX_FLOW_CHANGE, # 261 — RX flow changed
NOTIFICATION_ROUTING_DEVICE_CHANGE,# 288 — routing-level device change
NOTIFICATION_ROUTING_READY, # 256 — routing table ready (e.g. after reboot)
}
# ── Palette ────────────────────────────────────────────────────────────────────
C_TX_HDR = QColor(40, 80, 130) # TX device header (dark blue)
C_RX_HDR = QColor(90, 40, 110) # RX device header (dark purple)
C_TX_CH = QColor(205, 220, 245) # TX channel label
C_RX_CH = QColor(230, 210, 242) # RX channel label
C_HDR_FG = QColor(255, 255, 255) # white text on coloured headers
C_CH_FG = QColor(25, 25, 25) # near-black text on channel label cells
C_CONN = QColor(50, 175, 70) # connected dot (green)
C_ERROR = QColor(200, 50, 50) # error dot (red — connected but faulted)
C_EMPTY_DOT = QColor(195, 195, 195) # disconnected dot (grey)
C_EMPTY_BG = QColor(252, 252, 252) # connection cell background
C_GRAY_CELL = QColor(218, 220, 224) # separator cell (device×device, etc.)
C_PENDING = QColor(220, 175, 45) # pending dot (amber)
C_CORNER = QColor(50, 50, 55) # top-left corner
# ── Helpers ────────────────────────────────────────────────────────────────────
def _arc_port(device) -> int:
from netaudio.dante.const import SERVICE_ARC
if device.services:
for svc in device.services.values():
if svc.get("type") == SERVICE_ARC:
return svc.get("port", 4440)
return 4440
def _bold_font(size: int | None = None) -> QFont:
f = QFont()
f.setBold(True)
if size:
f.setPointSize(size)
return f
def _small_font() -> QFont:
f = QFont()
f.setPointSize(8)
return f
# ── Delegate: draws dots in connection cells ───────────────────────────────────
class DotDelegate(QStyledItemDelegate):
def paint(self, painter: QPainter, option, index):
# ── Rotated TX header row ──────────────────────────────────────────────
if index.row() == 0 and index.column() > 0:
painter.save()
r = option.rect
bg = index.data(Qt.ItemDataRole.BackgroundRole)
if bg:
painter.fillRect(r, bg)
painter.setClipRect(r)
painter.translate(r.center().x(), r.center().y())
painter.rotate(-90)
# In rotated frame the cell is (original-height wide × original-width tall)
rotated = QRect(-r.height() // 2, -r.width() // 2, r.height(), r.width())
fg = index.data(Qt.ItemDataRole.ForegroundRole)
painter.setPen(fg.color() if fg else option.palette.text().color())
font = index.data(Qt.ItemDataRole.FontRole)
if font:
painter.setFont(font)
painter.setRenderHint(QPainter.RenderHint.TextAntialiasing)
painter.drawText(
rotated,
Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextSingleLine,
index.data(Qt.ItemDataRole.DisplayRole) or "",
)
painter.restore()
return
data = index.data(Qt.ItemDataRole.UserRole)
if isinstance(data, dict) and data.get("kind") == "rx_ch":
super().paint(painter, option, index)
status = data.get("status")
if status is not None:
painter.save()
r = option.rect
size = min(r.width(), r.height()) * 0.28
margin = 4
cx = r.right() - margin - size
cy = r.y() + r.height() / 2
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
if status == "ok":
painter.setBrush(QBrush(C_CONN))
painter.setPen(QPen(QColor(30, 130, 45), 1.5))
else:
painter.setBrush(QBrush(C_ERROR))
painter.setPen(QPen(QColor(150, 20, 20), 1.5))
painter.drawEllipse(
int(cx - size), int(cy - size),
int(size * 2), int(size * 2),
)
painter.restore()
return
if not (isinstance(data, dict) and data.get("kind") == "conn"):
super().paint(painter, option, index)
return
painter.save()
painter.fillRect(option.rect, QBrush(C_EMPTY_BG))
pending = data.get("pending", False)
connected = data.get("connected", False)
r = option.rect
size = min(r.width(), r.height()) * 0.33
cx = r.x() + r.width() / 2
cy = r.y() + r.height() / 2
error = data.get("error", False)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
if pending:
painter.setBrush(QBrush(C_PENDING))
painter.setPen(QPen(QColor(170, 130, 20), 1.5))
elif error:
painter.setBrush(QBrush(C_ERROR))
painter.setPen(QPen(QColor(150, 20, 20), 1.5))
elif connected:
painter.setBrush(QBrush(C_CONN))
painter.setPen(QPen(QColor(30, 130, 45), 1.5))
else:
painter.setBrush(QBrush(C_EMPTY_DOT))
painter.setPen(QPen(QColor(155, 155, 155), 1.0))
painter.drawEllipse(int(cx - size), int(cy - size),
int(size * 2), int(size * 2))
painter.restore()
def sizeHint(self, option, index):
return QSize(32, 26)
# ── Persistent async engine ────────────────────────────────────────────────────
# A single DanteApplication is kept alive for the lifetime of the GUI process.
# It holds the multicast notification listener, so external routing changes
# (e.g. from Dante Controller on another machine) are received immediately
# rather than being discovered only on the next 5-second poll.
#
# All async work runs on a dedicated event loop in its own thread so that
# asyncio never blocks the Qt main thread.
# ──────────────────────────────────────────────────────────────────────────────
import threading
class _AsyncEngine:
"""Owns a persistent DanteApplication and a background asyncio event loop."""
def __init__(self):
self._loop: asyncio.AbstractEventLoop | None = None
self._thread: threading.Thread | None = None
self._app: DanteApplication | None = None
self._ready = threading.Event() # set once the loop + app are up
# ── Lifecycle ──────────────────────────────────────────────────────────────
def start(self):
self._thread = threading.Thread(target=self._run, daemon=True, name="dante-async")
self._thread.start()
self._ready.wait(timeout=10)
def _run(self):
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
self._loop.run_until_complete(self._main())
async def _main(self):
self._app = DanteApplication()
await self._app.startup()
self._ready.set()
# Keep the loop alive indefinitely; tasks submitted via submit() run here.
await asyncio.get_event_loop().create_future() # never resolves
def stop(self):
if self._loop and self._app:
asyncio.run_coroutine_threadsafe(self._app.shutdown(), self._loop)
# ── Submit a coroutine from any thread ────────────────────────────────────
def submit(self, coro) -> "asyncio.Future":
return asyncio.run_coroutine_threadsafe(coro, self._loop)
@property
def app(self) -> DanteApplication:
return self._app
# Module-level singleton — created once when the GUI starts.
_engine = _AsyncEngine()
# ── Discovery worker ───────────────────────────────────────────────────────────
class DiscoveryWorker(QThread):
"""Full device discovery + channel population via the shared async engine.
If *force_full* is True the daemon cache is bypassed and
discover_and_populate() is always called (full ARC re-query of every
device on the network). Use this for the manual Refresh button and the
periodic deep-sync timer.
"""
done = pyqtSignal(dict)
failed = pyqtSignal(str)
partial_update = pyqtSignal(dict) # new devices found before ARC data arrives
def __init__(self, force_full: bool = False):
super().__init__()
self._force_full = force_full
def run(self):
future = _engine.submit(self._discover())
try:
self.done.emit(future.result(timeout=30))
except Exception as exc:
self.failed.emit(str(exc))
async def _discover(self):
import time as _time
_t0 = _time.monotonic()
def _elapsed(): return _time.monotonic() - _t0
print(f"[timing] _discover start force_full={self._force_full}")
app = _engine.app
devices = None if self._force_full else await get_devices_from_daemon()
source = "daemon-cache"
if devices is None:
source = "ARC full-query"
# Snapshot the identity of each device's services dict before
# discovery. discover_and_populate assigns a fresh dict to
# device.services for every device it processes via mDNS, so
# entries whose services object is unchanged afterwards were not
# seen in this run (e.g. stale pre-rename ghost entries).
print(f"[timing] {_elapsed():.2f}s launching discover_and_populate timeout={netaudio_settings.mdns_timeout}s")
task = asyncio.create_task(
app.discover_and_populate(timeout=netaudio_settings.mdns_timeout)
)
last_snapshot: set = set()
while not task.done():
await asyncio.sleep(0.5)
current_sns = set(app.devices.keys())
if current_sns != last_snapshot and current_sns:
last_snapshot = current_sns
print(f"[timing] {_elapsed():.2f}s partial_update: {len(current_sns)} device(s) in app.devices")
self.partial_update.emit(dict(app.devices))
print(f"[timing] {_elapsed():.2f}s discover_and_populate done devices={len(app.devices)}")
devices = task.result()
# Sync device.name from the mDNS service instance name.
# discover_and_populate only fetches the name via ARC when
# device.name is empty, so renames made in Dante Controller are
# never picked up on subsequent runs. The current name is already
# present in the service instance prefix (e.g.
# "NewName._netaudio-arc._udp.local." → "NewName").
for sn, d in app.devices.items():
if not d.services:
continue
for service_key in d.services:
dot = service_key.find('._')
if dot > 0:
mdns_name = service_key[:dot]
if mdns_name != d.name:
print(f"[name-sync] {sn!r}: {d.name!r} → {mdns_name!r}")
d.name = mdns_name
break
else:
print(f"[timing] {_elapsed():.2f}s daemon cache hit devices={len(devices)}")
# Register daemon devices in app.devices so _device_by_ip can
# find them when routing notifications arrive. We intentionally
# do NOT call populate_controls here: doing so on every 5-second
# refresh would race with a running DeviceRefreshWorker on the
# same UDP socket (both use transaction_id=0 for command_receivers,
# corrupting each other's asyncio.Future in _pending).
for sn, d in devices.items():
if not getattr(d, 'online', True):
# Daemon marks devices offline when they disappear from mDNS
# (e.g. after a rename). Drop them from the local cache so
# the stale row disappears from the UI.
app.devices.pop(sn, None)
continue
if sn not in app.devices:
app.devices[sn] = d
else:
# Merge fresh subscription and channel data from the daemon
# into the existing device object. This is safe (no UDP
# traffic) and ensures crosspoint changes made externally
# (e.g. via Dante Controller) are reflected after a device
# restart, when the old app.devices entry would otherwise
# stay stale indefinitely.
existing = app.devices[sn]
if d.name:
existing.name = d.name
existing.online = d.online
existing.subscriptions = d.subscriptions
if d.rx_channels:
existing.rx_channels = d.rx_channels
if d.tx_channels:
existing.tx_channels = d.tx_channels
# Return app.devices so sync() also sees any ARC-fresh data
# already written by a running DeviceRefreshWorker.
devices = app.devices
devices = devices or {}
print(f"[timing] {_elapsed():.2f}s _discover returning source={source} devices={len(devices)}")
log.debug("[discover] source=%s devices=%d", source, len(devices))
for sn, d in devices.items():
tx_chs = list(d.tx_channels.keys()) if d.tx_channels else []
rx_chs = list(d.rx_channels.keys()) if d.rx_channels else []
log.debug(
" device sn=%s name=%r ip=%s tx_channels=%s rx_channels=%s subscriptions=%d",
sn, d.name, getattr(d, 'ipv4', '?'),
tx_chs, rx_chs, len(d.subscriptions),
)
for sub in d.subscriptions:
log.debug(
" sub: rx_dev=%r rx_ch=%r tx_dev=%r tx_ch=%r "
"status=0x%04x rx_ch_status=0x%04x",
sub.rx_device_name, sub.rx_channel_name,
sub.tx_device_name, sub.tx_channel_name,
sub.status_code or 0,
sub.rx_channel_status_code or 0,
)
return devices
# ── Single-device refresh worker ──────────────────────────────────────────────
class DeviceRefreshWorker(QThread):
"""Re-queries rx/tx channels for ONE device after a notification fires."""
done = pyqtSignal(dict) # emits the full (updated) devices dict
def __init__(self, server_name: str):
super().__init__()
self._server_name = server_name
def run(self):
future = _engine.submit(self._refresh())
try:
self.done.emit(future.result(timeout=10))
except Exception:
pass # silent — the 5 s fallback will catch it
async def _refresh(self):
# Dante devices broadcast the notification *before* their ARC state is
# committed. A short pause lets the device finish writing so the ARC
# response is fresh.
await asyncio.sleep(0.35)
app = _engine.app
device = app.devices.get(self._server_name)
if device is None:
log.debug("[device-refresh] server_name=%r not in app.devices — skipping", self._server_name)
return app.devices
arc_port = app.get_arc_port(device)
log.debug("[device-refresh] refreshing %r ip=%s arc_port=%s", self._server_name, getattr(device, 'ipv4', '?'), arc_port)
if arc_port:
try:
await app.arc.get_controls(device, arc_port)
log.debug("[device-refresh] get_controls OK for %r subscriptions=%d", self._server_name, len(device.subscriptions))
for sub in device.subscriptions:
log.debug(
" sub: rx_dev=%r rx_ch=%r tx_dev=%r tx_ch=%r "
"status=0x%04x rx_ch_status=0x%04x",
sub.rx_device_name, sub.rx_channel_name,
sub.tx_device_name, sub.tx_channel_name,
sub.status_code or 0,
sub.rx_channel_status_code or 0,
)
except Exception as exc:
log.warning("[device-refresh] get_controls FAILED for %r: %s", self._server_name, exc)
else:
log.warning("[device-refresh] no ARC port for %r — cannot refresh", self._server_name)
return app.devices
# ── Subscription command worker ────────────────────────────────────────────────
class CmdWorker(QThread):
done = pyqtSignal(bool, str)
def __init__(self, action: str, rx_dev, rx_ch, tx_dev=None, tx_ch=None):
super().__init__()
self._action = action # "add" | "remove"
self._rx_dev = rx_dev
self._rx_ch = rx_ch
self._tx_dev = tx_dev
self._tx_ch = tx_ch
def run(self):
future = _engine.submit(self._send())
try:
future.result(timeout=10)
self.done.emit(True, "")
except Exception as exc:
self.done.emit(False, str(exc))
async def _send(self):
cmds = DanteDeviceCommands()
port = _arc_port(self._rx_dev)
ip = str(self._rx_dev.ipv4)
if self._action == "add":
tx_name = self._tx_ch.friendly_name or self._tx_ch.name
packet, _ = cmds.command_add_subscription(
self._rx_ch.number, tx_name, self._tx_dev.name
)
else:
packet, _ = cmds.command_remove_subscription(self._rx_ch.number)
result = await device_request_via_daemon(packet, ip, port)
if result is None:
await _engine.app.arc.request(
packet, ip, port, logical_command_name="patch_bay"
)
# ── Clock leader command worker ────────────────────────────────────────────────
class ClockSetLeaderWorker(QThread):
"""Sends a preferred-master (clock leader) command to a single device."""
done = pyqtSignal(bool, str)
def __init__(self, device, value: bool):
super().__init__()
self._device = device
self._value = value
def run(self):
future = _engine.submit(self._send())
try:
future.result(timeout=10)
self.done.emit(True, "")
except Exception as exc:
self.done.emit(False, str(exc))
async def _send(self):
cmds = DanteDeviceCommands()
ip = str(self._device.ipv4)
packet, _, port = cmds.command_set_preferred_leader(self._value)
result = await device_request_via_daemon(packet, ip, port)
if result is None:
await _engine.app.settings.request(
packet, ip, port, logical_command_name="clock_leader"
)
# ── Channel rename worker ─────────────────────────────────────────────────────
class ChannelRenameWorker(QThread):
"""Sends a set- or reset-channel-name command to a device."""
done = pyqtSignal(bool, str)
def __init__(self, device, channel_type: str, channel_number: int, new_name: str):
super().__init__()
self._device = device
self._channel_type = channel_type
self._channel_number = channel_number
self._new_name = new_name
def run(self):
future = _engine.submit(self._rename())
try:
future.result(timeout=10)
self.done.emit(True, "")
except Exception as exc:
self.done.emit(False, str(exc))
async def _rename(self):
cmds = DanteDeviceCommands()
ip = str(self._device.ipv4)
port = _arc_port(self._device)
if self._new_name:
packet, _ = cmds.command_set_channel_name(
self._channel_type, self._channel_number, self._new_name)
else:
packet, _ = cmds.command_reset_channel_name(
self._channel_type, self._channel_number)
result = await device_request_via_daemon(packet, ip, port)
if result is None:
await _engine.app.arc.request(
packet, ip, port, logical_command_name="rename_channel")
# ── Clock status fetch worker ─────────────────────────────────────────────────
class ClockRefreshWorker(QThread):
"""Calls get_clocking_status() on every device to populate clock fields.
Operates on the device objects already held by ClockStatusTab (the same
dict reference) so that written fields are immediately visible to the tab.
"""
done = pyqtSignal(dict)
def __init__(self, devices: dict):
super().__init__()
self._devices = devices # same objects the tab holds — no key mismatch
def run(self):
future = _engine.submit(self._fetch())
try:
self.done.emit(future.result(timeout=30))
except Exception as exc:
print(f"[clock-refresh] worker top-level exception: {exc!r}")
async def _fetch(self):
import time as _time
_t0 = _time.monotonic()
def _e(): return _time.monotonic() - _t0
app = _engine.app
async def _probe_one(sn, ip):
_pt = _time.monotonic()
try:
await app.probe_preferred_leader_state(ip, timeout=1.5)
print(f"[clock-refresh] {_e():.2f}s probe_preferred_leader_state {sn!r} done ({_time.monotonic()-_pt:.2f}s)", flush=True)
except Exception as exc:
print(f"[clock-refresh] {_e():.2f}s probe_preferred_leader_state {sn!r} failed ({_time.monotonic()-_pt:.2f}s): {exc}", flush=True)
ips = [(sn, str(device.ipv4))
for sn, device in self._devices.items()
if getattr(device, 'ipv4', None)]
print(f"[clock-refresh] {_e():.2f}s probing preferred_leader for {len(ips)} device(s)", flush=True)
# Probe all devices concurrently so total time ≈ one round-trip, not N×timeout.
await asyncio.gather(*(_probe_one(sn, ip) for sn, ip in ips))
print(f"[clock-refresh] {_e():.2f}s all preferred_leader probes done", flush=True)
# Devices that didn't receive a CONMON multicast (e.g. Dante Via software)
# won't have ptp_v1_role set. Fall back to a unicast get_clocking_status()
# call so their actual clock role is still displayed.
async def _clocking_one(sn, device):
_ct = _time.monotonic()
try:
await device.get_clocking_status()
print(f"[clock-refresh] {_e():.2f}s get_clocking_status {sn!r} done ({_time.monotonic()-_ct:.2f}s)", flush=True)
except Exception as exc:
print(f"[clock-refresh] {_e():.2f}s get_clocking_status {sn!r} failed ({_time.monotonic()-_ct:.2f}s): {exc}", flush=True)
missing = [
(sn, device)
for sn, device in self._devices.items()
if getattr(device, 'ptp_v1_role', None) is None
and getattr(device, 'ipv4', None)
]
if missing:
print(f"[clock-refresh] {_e():.2f}s fetching clocking_status for {len(missing)} device(s) missing ptp_v1_role", flush=True)
await asyncio.gather(*(_clocking_one(sn, d) for sn, d in missing))
print(f"[clock-refresh] {_e():.2f}s fetch complete", flush=True)
return self._devices
# ── Latency read worker ────────────────────────────────────────────────────────
class LatencyReadWorker(QThread):
"""Queries each device's current latency via ARC and stores it in device.latency (ns).
Works on the same device objects held by the routing table, so written
fields are visible immediately when the table refreshes.
"""
done = pyqtSignal(dict)
def __init__(self, devices: dict):
super().__init__()
self._devices = devices
def run(self):
future = _engine.submit(self._fetch())
try:
self.done.emit(future.result(timeout=30))
except Exception as exc:
print(f"[latency-read] worker top-level exception: {exc!r}")
async def _fetch(self):
import time as _time
_t0 = _time.monotonic()
def _e(): return _time.monotonic() - _t0
cmds = DanteDeviceCommands()
async def _probe_one(sn, device):
ip = str(device.ipv4)
port = _arc_port(device)
_pt = _time.monotonic()
try:
packet = cmds.command_device_settings()[0]
response = await _engine.app.arc.request(
packet, ip, port, logical_command_name="get_device_settings"
)
if response:
settings = DanteParser.parse_device_settings(
DantePacket.parse_response(response)
)
if settings.latency_us is not None:
device.latency = settings.latency_us
print(f"[latency-read] {_e():.2f}s {sn!r} latency={settings.latency_us/1_000_000:.3f}ms ({_time.monotonic()-_pt:.2f}s)", flush=True)
else:
print(f"[latency-read] {_e():.2f}s {sn!r} no latency in response ({_time.monotonic()-_pt:.2f}s)", flush=True)
else:
print(f"[latency-read] {_e():.2f}s {sn!r} no response ({_time.monotonic()-_pt:.2f}s)", flush=True)
except Exception as exc:
print(f"[latency-read] {_e():.2f}s {sn!r} error ({_time.monotonic()-_pt:.2f}s): {exc}", flush=True)
devices_with_ip = [
(sn, device)
for sn, device in self._devices.items()
if getattr(device, 'ipv4', None)
]
print(f"[latency-read] {_e():.2f}s probing {len(devices_with_ip)} device(s)", flush=True)
await asyncio.gather(*(_probe_one(sn, d) for sn, d in devices_with_ip))
print(f"[latency-read] {_e():.2f}s fetch complete", flush=True)
return self._devices
# ── Config probe worker ────────────────────────────────────────────────────────
class ConfigProbeWorker(QThread):
"""Runs the slow notification-based probes in parallel after discovery.
discover_and_populate() no longer calls these so the patch tab can appear
immediately after ARC queries finish. This worker runs them concurrently
(total wall time ≈ max of each individual timeout rather than their sum)
and signals done when all have returned.
"""
done = pyqtSignal(dict)
def __init__(self, devices: dict):
super().__init__()
self._devices = devices
def run(self):
future = _engine.submit(self._fetch())
try:
self.done.emit(future.result(timeout=30))
except Exception as exc:
print(f"[config-probe] worker top-level exception: {exc!r}", flush=True)
async def _fetch(self):
import time as _time
_t0 = _time.monotonic()
def _e(): return _time.monotonic() - _t0
app = _engine.app
print(f"[config-probe] {_e():.2f}s start", flush=True)
await asyncio.gather(
app._query_conmon_all(),
app._probe_interface_status(),
app._probe_preferred_leader_all(),
app._probe_aes67_all(),
return_exceptions=True,
)
print(f"[config-probe] {_e():.2f}s all probes done", flush=True)
return self._devices
# ── Interface config worker ────────────────────────────────────────────────────
class InterfaceConfigWorker(QThread):
"""Sends a DHCP or static IP config command to a device's network interface."""
done = pyqtSignal(bool, str)
def __init__(self, device, mode: str, ip: str = "", mask: str = "",
gw: str = "", dns: str = ""):
super().__init__()
self._device = device
self._mode = mode
self._ip = ip
self._mask = mask
self._gw = gw
self._dns = dns
def run(self):
future = _engine.submit(self._send())
try:
future.result(timeout=10)
self.done.emit(True, "")
except Exception as exc:
self.done.emit(False, str(exc))
async def _send(self):
cmds = DanteDeviceCommands()
ip = str(self._device.ipv4)
if self._mode == "dynamic":
packet, _, port = cmds.command_set_interface_dhcp()
else:
# command_set_interface_static signature: (ip, netmask, dns_server, gateway)
# Substitute "0.0.0.0" for any omitted optional fields (gateway, DNS) —
# inet_aton rejects empty strings and the real Dante Controller allows
# leaving these blank when only IP/mask are required.
_or_zero = lambda v: v if v else "0.0.0.0"
packet, _, port = cmds.command_set_interface_static(
self._ip, self._mask, _or_zero(self._dns), _or_zero(self._gw)
)
result = await device_request_via_daemon(packet, ip, port)
if result is None:
await _engine.app.settings.request(
packet, ip, port, logical_command_name="interface_config"
)
# ── Sample rate worker ─────────────────────────────────────────────────────────
_SR_VALID_RATES = [44100, 48000, 88200, 96000, 176400, 192000]
# ── Latency worker ─────────────────────────────────────────────────────────────
# Values in milliseconds — these are the standard Dante Controller options.
_LAT_VALID_MS = [0.25, 0.5, 1.0, 2.0, 5.0, 10.0]
class SampleRateWorker(QThread):
"""Sends a sample-rate change command to a device."""
done = pyqtSignal(bool, str)
def __init__(self, device, sample_rate: int):
super().__init__()
self._device = device
self._sample_rate = sample_rate
def run(self):
future = _engine.submit(self._send())
try:
future.result(timeout=10)
self.done.emit(True, "")
except Exception as exc:
self.done.emit(False, str(exc))
async def _send(self):
cmds = DanteDeviceCommands()
ip = str(self._device.ipv4)
packet, _, port = cmds.command_set_sample_rate(self._sample_rate)
result = await device_request_via_daemon(packet, ip, port)
if result is None:
await _engine.app.settings.request(
packet, ip, port, logical_command_name="set_sample_rate"
)
class LatencyWorker(QThread):
"""Sends a latency change command to a device."""
done = pyqtSignal(bool, str)
def __init__(self, device, latency_ms: float):
super().__init__()
self._device = device
self._latency_ms = latency_ms
def run(self):
future = _engine.submit(self._send())
try:
future.result(timeout=10)
self.done.emit(True, "")
except Exception as exc:
self.done.emit(False, str(exc))
async def _send(self):
cmds = DanteDeviceCommands()
ip = str(self._device.ipv4)
port = _arc_port(self._device)
packet, _ = cmds.command_set_latency(self._latency_ms)
result = await device_request_via_daemon(packet, ip, port)
if result is None:
await _engine.app.arc.request(
packet, ip, port, logical_command_name="set_latency"
)
# ── Reboot worker ──────────────────────────────────────────────────────────────
class RebootWorker(QThread):
"""Sends a reboot command to a device."""
done = pyqtSignal(bool, str)
def __init__(self, device):
super().__init__()
self._device = device
def run(self):
future = _engine.submit(self._send())
try:
future.result(timeout=10)
self.done.emit(True, "")
except Exception as exc:
self.done.emit(False, str(exc))
async def _send(self):
from netaudio.dante.services.cmc import _get_host_mac
cmds = DanteDeviceCommands()
device_ip = str(self._device.ipv4)
host_mac = _get_host_mac()
packet, _, port = cmds.command_reboot(host_mac=host_mac)
# Reboot is fire-and-forget — the device drops off the network immediately
# and never sends a response. Mirror device_operations.reboot(): send 3
# times with short delays so at least one packet gets through.
for attempt in range(3):
_engine.app.settings.send(packet, device_ip, port)
if attempt < 2:
await asyncio.sleep(0.1)
# ── Device rename worker ──────────────────────────────────────────────────────
class DeviceRenameWorker(QThread):
"""Sends a device rename command via the ARC service."""
done = pyqtSignal(bool, str)
def __init__(self, device, new_name: str):
super().__init__()
self._device = device
self._new_name = new_name
def run(self):
future = _engine.submit(self._send())
try:
future.result(timeout=10)
self.done.emit(True, "")
except Exception as exc:
self.done.emit(False, str(exc))
async def _send(self):
cmds = DanteDeviceCommands()
ip = str(self._device.ipv4)
port = _arc_port(self._device)
packet, _ = cmds.command_set_name(self._new_name)
result = await device_request_via_daemon(packet, ip, port)
if result is None:
await _engine.app.arc.request(
packet, ip, port, logical_command_name="set_name"
)
# ── Patch bay table ────────────────────────────────────────────────────────────
#
# Table layout:
#
# row 0, col 0 : corner label
# row 0, col 1..N_tx : TX entries (device header OR channel label)
# row 1..N_rx, col 0 : RX entries (device header OR channel label)
# row 1..N_rx, col 1.. : connection cells (dots) or separator cells
#
# _tx_struct / _rx_struct items:
# {'kind': 'dev', 'name': str, 'device': DanteDevice}
# {'kind': 'chan', 'dname': str, 'device': DanteDevice, 'channel': DanteChannel}
#
# Device entries show a ▼/▶ toggle and are always visible.
# Channel entries are shown/hidden by expanding/collapsing their device.
# ──────────────────────────────────────────────────────────────────────────────
class PatchBayTable(QTableWidget):
status = pyqtSignal(str)
patched = pyqtSignal() # emitted after any successful subscription change
def __init__(self):
super().__init__()
self._tx_struct = []
self._rx_struct = []
self._conns = {} # (rx_dev_name, rx_ch_name) -> (tx_dev_name, tx_ch_name)
self._user_set_conns = {} # same key -> (intended value, expiry_time); takes priority over stale daemon data
self._USER_CONN_TTL = 12 # seconds before an unconfirmed override expires
self._tx_exp = {} # device_name -> bool (True = expanded)
self._rx_exp = {}
self._last_devices = {}
self._last_tx_fp: frozenset = frozenset()
self._last_rx_fp: frozenset = frozenset()
self._workers = [] # keep refs so GC doesn't kill running threads
self.setItemDelegate(DotDelegate())
self.horizontalHeader().setVisible(False)
self.verticalHeader().setVisible(False)
self.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)
self.setShowGrid(True)
self.setGridStyle(Qt.PenStyle.SolidLine)
self.cellClicked.connect(self._cell_clicked)
self.cellDoubleClicked.connect(self._cell_double_clicked)
# ── Public ─────────────────────────────────────────────────────────────────
def load(self, devices: dict):
self._last_devices = devices
self._last_tx_fp = frozenset(
(d.name, ch.number)
for d in devices.values()
for ch in d.tx_channels.values()
)
self._last_rx_fp = frozenset(
(d.name, ch.number)
for d in devices.values()
for ch in d.rx_channels.values()
)
# Build connection map from each device's subscription list
self._conns = {}
for sn, device in devices.items():
for sub in device.subscriptions:
if sub.rx_channel_name:
key = (sub.rx_device_name, sub.rx_channel_name)
if sub.tx_channel_name and sub.tx_device_name:
self._conns[key] = (
sub.tx_device_name, sub.tx_channel_name,
sub.status_code, sub.rx_channel_status_code or 0,
)
else:
log.debug("[load] sub skipped (no tx): rx_dev=%r rx_ch=%r tx_dev=%r tx_ch=%r",
sub.rx_device_name, sub.rx_channel_name,
sub.tx_device_name, sub.tx_channel_name)
log.debug("[load] _conns built: %d connection(s)", len(self._conns))
for k, v in self._conns.items():
log.debug(" conn: rx_dev=%r rx_ch=%r -> tx_dev=%r tx_ch=%r status=0x%04x rx_ch_status=0x%04x",
k[0], k[1], v[0], v[1], v[2] or 0, v[3])
self._rebuild()
# ── Build / rebuild grid ───────────────────────────────────────────────────
def _rebuild(self):
devices = self._last_devices
tx_devs = sorted(
[(sn, d) for sn, d in devices.items() if d.tx_channels],
key=lambda x: (x[1].name or x[0]).lower()
)
rx_devs = sorted(
[(sn, d) for sn, d in devices.items() if d.rx_channels],
key=lambda x: (x[1].name or x[0]).lower()
)
self._tx_struct = []
for sn, dev in tx_devs:
name = dev.name or sn
self._tx_struct.append({'kind': 'dev', 'name': name, 'device': dev})
if self._tx_exp.get(name, False):
for ch in sorted(dev.tx_channels.values(), key=lambda c: c.number):
self._tx_struct.append(
{'kind': 'chan', 'dname': name, 'device': dev, 'channel': ch}
)
self._rx_struct = []
for sn, dev in rx_devs:
name = dev.name or sn
self._rx_struct.append({'kind': 'dev', 'name': name, 'device': dev})
if self._rx_exp.get(name, False):
for ch in sorted(dev.rx_channels.values(), key=lambda c: c.number):
self._rx_struct.append(
{'kind': 'chan', 'dname': name, 'device': dev, 'channel': ch}
)
self.setRowCount(1 + len(self._rx_struct))
self.setColumnCount(1 + len(self._tx_struct))
self._fill_corner()
self._fill_tx_headers()
self._fill_rx_headers()
self._fill_cells()
self._resize_table()
# ── Cell factories ─────────────────────────────────────────────────────────
def _make_item(self, text="", bg=None, fg=None, font=None,
align=Qt.AlignmentFlag.AlignCenter,
flags=Qt.ItemFlag.ItemIsEnabled) -> QTableWidgetItem:
it = QTableWidgetItem(text)
it.setTextAlignment(align)
it.setFlags(flags)
if bg:
it.setBackground(QBrush(bg))
if fg:
it.setForeground(QBrush(fg))
if font:
it.setFont(font)
return it
def _fill_corner(self):
it = self._make_item(
"RX ↓ / TX →",