Repository navigation
Expand file tree
/
Copy pathnicegui_test.py
More file actions
4319 lines (3898 loc) · 235 KB
/
Copy pathnicegui_test.py
File metadata and controls
4319 lines (3898 loc) · 235 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
"""NiceGUI robot dashboard — Source Robotics."""
from nicegui import ui, app
from data import shared_data
import math
import asyncio
import time
import psutil
import os
import queue
import json
import gc
import sys # Firmware tab: spawns the flasher CLI with this interpreter
import signal # Firmware tab: SIGINT to cancel a running flash
# ── GC tuning: smooth out the periodic ~1 ms plot freezes ──────────────────
# The live-plot loop rebuilds the whole windowed series each frame (~5k short-
# lived list objects at 20 Hz). That high allocation rate makes CPython's
# generational GC fire a full gen2 collection every few seconds → a brief stall.
# Raising the thresholds (esp. gen2) makes those full collections far rarer; the
# objects are tiny and short-lived, so the small memory trade-off is worth the
# smoothness. Reference counting still frees everything promptly regardless.
gc.set_threshold(50_000, 500, 1000) # default is (700, 10, 10)
from gui_command_sender import ExecCommandSender
from config.xml_parser import load_system_config, load_full_robot_config
from config.system_config import publish_static_system_info, publish_memory_info, publish_disk_info
from project_paths import SYSTEM_XML, ROBOTS_DIR, GRIPPERS_DIR, ACTIVITY_RTI_LOG, ACTIVITY_EXEC_LOG, CONFIG_DIR
from utility.signal_filters import FILTER_KINDS
# Pure constants — importing rti_handler pulls no hardware, it is the RT-side motion
# generator module. Used so the RTI panel shows the real budget rather than a copy of it
# that can drift (TODO/RTI_mode_plan.md §9.1 is what happens when numbers get retyped).
from motion.rti_handler import COMMAND_TIMEOUT_S, SUCCESS_WINDOW_TICKS, SUCCESS_WARN, SUCCESS_BAD
from utility.filter_config import ALL_SIGNALS, default_filter_config
from utility.process_utils import process_info
from data.shared_memory_index import ESTOP_1 as _ESTOP_1 # for plot event markers
shared_data.setup(joints=6)
# Populate the System Info shared strings. Nothing else in the stack ever wrote them, so the
# System Info tab read them back empty and showed "---" for every field. The GUI is the natural
# producer: it runs on the box at normal priority and already uses psutil, so this stays well
# clear of RTI's RT loop. Platform/CPU cannot change without a reboot -> publish once, here.
# Memory is refreshed on a slow timer further down (it moves, but not fast).
publish_static_system_info(shared_data)
publish_memory_info(shared_data)
publish_disk_info(shared_data)
JOINTS = 6
_sys_cfg = load_system_config(SYSTEM_XML, ROBOTS_DIR)
_xml_cfg = load_full_robot_config(
str(_sys_cfg['robot_xml_path']),
grippers_dir=GRIPPERS_DIR,
active_gripper=_sys_cfg['active_gripper'],
)
from utility.process_utils import setup_process
setup_process(core=1, rt=False) # GUI: own core, normal scheduling (only RTI is RT)
# RTI process liveness tracking — compared each GUI refresh tick
_prev_rti_tick = -1
_rti_stale_cnt = 0 # consecutive refreshes with no tick change
# Refresh rates — tables and plots run on SEPARATE timers so each can be tuned
# without affecting the other. Tables only need ~10 Hz to be readable (faster
# just makes the numbers jitter); plots benefit from a higher rate for smooth
# scrolling. Plot buffer sizing + rebuild cadence derive from PLOT_REFRESH_HZ.
TABLE_REFRESH_HZ = 10
TABLE_REFRESH_S = 1.0 / TABLE_REFRESH_HZ
PLOT_REFRESH_HZ = 20
PLOT_REFRESH_S = 1.0 / PLOT_REFRESH_HZ
# GUI loop timing
_gui_last_t = 0.0
_gui_exec_last = 0.0 # exec time of the previous iteration (ms)
_gui_period_ema = 0.0
_gui_exec_ema = 0.0
_gui_period_peak = 0.0
_gui_exec_peak = 0.0
_GUI_EMA_ALPHA = 0.1 # smoothing factor for EMA
# rti['rti_substate'] -> (badge text, quasar colour). Codes are owned by
# motion/rti_handler.py::SUBSTATE_CODE; keep the two in step.
_RTI_SUBSTATE_UI = {
0: ("NO PC PAIRED", "grey"),
1: ("CONNECTED", "blue"), # streaming state, control not claimed
2: ("CONTROL ACTIVE", "positive"), # PC is driving; timing rules enforced
3: ("STOPPING", "warning"), # clean release, holding position
4: ("STOPPED: ERROR", "negative"), # timeout / packet loss, error latched
}
# Plot-loop timing (separate timer) — used for the FPS readout on the Plots tab.
_plot_last_t = 0.0
_plot_period_ema = 0.0
# ─── Activity Log tailer state ──────────────────────────────────────────────
# Read position is `None` until first tailed. On first tail, seek near the end
# instead of from byte 0 — bounds GUI startup cost against a long-running,
# multi-MB rotated log instead of re-parsing its entire history. On rotation
# (RotatingFileHandler renames the current file away and starts a fresh one at
# the same path — file size drops below our tracked position), reset to 0.
_ACTIVITY_LOG_SOURCES = {"RTI": str(ACTIVITY_RTI_LOG), "EXEC": str(ACTIVITY_EXEC_LOG)}
_ACTIVITY_INITIAL_TAIL_BYTES = 256_000
_ACTIVITY_MAX_ROWS = 500
_activity_tail_pos = {name: None for name in _ACTIVITY_LOG_SOURCES}
_activity_entries = [] # bounded, sorted newest-first; rebuilt each refresh
def _tail_activity_log(name, path):
"""Read whatever's new in one activity log file since the last call."""
try:
size = os.path.getsize(path)
except OSError:
return []
pos = _activity_tail_pos[name]
# Only the initial fuzzy seek (size - N bytes) can land mid-line — every
# later `pos` came from a previous f.tell() and is already an exact line
# boundary, so the partial-line discard below must not fire for those.
first_open = pos is None
if first_open:
pos = max(0, size - _ACTIVITY_INITIAL_TAIL_BYTES)
elif size < pos:
pos = 0 # rotation — file was replaced, start over from the fresh one
entries = []
try:
with open(path, "r") as f:
f.seek(pos)
if first_open and pos > 0:
f.readline() # discard a possibly-partial line from the fuzzy seek
for line in f:
line = line.strip()
if not line:
continue
try:
entries.append(json.loads(line))
except json.JSONDecodeError:
continue
_activity_tail_pos[name] = f.tell()
except OSError:
pass
return entries
def _fmt_activity_row(e, idx):
ts = e.get("timestamp")
if isinstance(ts, (int, float)):
t_struct = time.localtime(ts)
time_str = f"{time.strftime('%H:%M:%S', t_struct)}.{int((ts % 1) * 1000):03d}"
else:
time_str = "?"
detail = e.get("message") or ""
if not detail:
detail = " → ".join(x for x in (e.get("cause"), e.get("fix")) if x)
return {
"key": f"{ts}_{idx}",
"time": time_str,
"source": e.get("source", ""),
"level": e.get("level", "info"),
"code": e.get("code", ""),
"id": e.get("id") or "",
"command": e.get("command") or "",
"detail": detail,
}
def fmt(x, decimals=3):
"""Format a float; returns '---' for non-finite values."""
if not math.isfinite(x):
return "---"
return f"{x:.{decimals}f}"
# ─────────────────────────────────────────────────────────────
# Command channel to command_executor
# ─────────────────────────────────────────────────────────────
# Commands go through command_executor's validated TCP JSON protocol (via a
# RobotClient), not a raw ZMQ push to RTI — so RTI has ONE arbitrated command
# source, not two. See TODO/gui_executor_migration_plan.md.
#
# RobotClient calls block on the executor ack and raise on rejection/timeout,
# which a UI handler must not do. So handlers just _exec(fn) and return: one
# background worker owns the client, runs submissions in order, reconnects if
# the executor restarts, and never lets an error escape. Failures are logged by
# the sender and surfaced to the user as a toast, drained by a ui.timer below.
_gui_toasts = queue.Queue() # (message, type) pending toasts → drained in the UI context
def _on_exec_error(label, exc):
_gui_toasts.put((f"{label or 'command'}: {exc}", "negative"))
_exec_sender = ExecCommandSender(on_error=_on_exec_error)
def _exec(fn, label=""):
"""Submit a RobotClient call to the executor. Non-blocking; never raises into the UI."""
_exec_sender.submit(fn, label=label)
def handle_enable(): _exec(lambda r: r.enable(), "enable")
def handle_disable(): _exec(lambda r: r.disable(), "disable")
def handle_home(): _exec(lambda r: r.home(), "home")
def handle_enter_exec(): _exec(lambda r: r.enter_exec_mode(), "enter_exec_mode")
def handle_exit_exec(): _exec(lambda r: r.enter_idle_mode(), "enter_idle_mode")
def handle_clear_errors():
"""Signal RTI to wipe the error latch. Any still-active errors re-latch next tick."""
shared_data.clear_error_signal.set("1")
def handle_reset_loop_stats():
"""Signal RTI to zero the since-start loop-timing peaks (max period/exec/jitter,
overrun count) and the rolling p95/p99 window. The p95/p99 values themselves
don't need this to stay meaningful (they're always a rolling last-500-tick
window) — this is for the "since start" peaks, which otherwise persist across
RTI restarts (same shared-memory segment, re-attached not recreated)."""
shared_data.loop_stats_reset_signal.set("1")
def handle_reload_filters():
"""Signal RTI to rebuild the signal filters from config/filters.xml — hot reload, no
restart, no re-home. Edit the tau/type in the XML, click this, see it live. RTI rebuilds
the filter banks on its next tick; each filter's internal state resets, so a brief
(~one filter window) transient is expected right after."""
shared_data.filter_reload_signal.set("1")
ui.notify("Reloading signal filters from config/filters.xml", type="info")
_sw_estop_btn = None # set after UI is built
async def handle_limp_toggle():
"""SAFETY_STOP: drive every motor with NOTHING (Position=None, Speed=None,
Current=0), or release back to IDLE.
Distinct from SW E-STOP and from disable(): both of those leave a velocity-0
hold that still resists motion. This removes all authority, so the arm hangs
on its own mechanics and WILL fall. Hence the dialog — a button this
destructive must not be a single click.
Its purpose is diagnostic: with every motor commanded by nothing, anything
still moving or buzzing is the driver's own firmware rather than the runtime.
"""
mode = shared_data.robot_mode.get()
if mode == "SAFETY_STOP":
_exec(lambda r: r.release_safety_stop(), "release_safety_stop")
return
with ui.dialog() as dlg, ui.card().classes("max-w-xl"):
ui.label("Cut all motor authority?").classes("text-lg font-bold text-red-700")
ui.markdown(
"Every joint will be commanded with **Position=None, Speed=None, "
"Current=0** — no position loop, no velocity loop, no holding torque.\n\n"
"**THE ARM WILL GO LIMP AND FALL UNDER ITS OWN WEIGHT.**\n\n"
"This is not the E-Stop and not Disable — both of those keep a "
"velocity-0 hold that resists motion. This removes it entirely.\n\n"
"Support the arm, or make sure it is resting somewhere it can drop "
"safely, before continuing."
).classes("text-sm")
with ui.row().classes("gap-2 justify-end w-full mt-2"):
ui.button("Cancel", on_click=lambda: dlg.submit(False)).props("outline")
ui.button("THE ARM IS SUPPORTED — CUT POWER",
on_click=lambda: dlg.submit(True)).props("color=red")
if not await dlg:
return
_exec(lambda r: r.safety_stop(), "safety_stop")
def handle_sw_estop_toggle():
"""Toggle software e-stop. Assert if inactive, release if active."""
current = int(shared_data.rti["software_estop"][0])
shared_data.rti["software_estop"][0] = 0 if current else 1
if _sw_estop_btn is not None:
active = bool(shared_data.rti["software_estop"][0])
_sw_estop_btn.props("color=orange" if active else "color=red size=sm")
_sw_estop_btn.text = "Release E-Stop" if active else "SW E-STOP"
# ─────────────────────────────────────────────────────────────
# Column definitions
# ─────────────────────────────────────────────────────────────
motor_columns = [
{'name': 'joint', 'label': 'Joint', 'field': 'joint'},
{'name': 'pos', 'label': 'Position', 'field': 'pos'},
{'name': 'spd', 'label': 'Speed', 'field': 'spd'},
{'name': 'cur', 'label': 'Current', 'field': 'cur'},
{'name': 'err', 'label': 'Error', 'field': 'err'},
{'name': 'HW', 'label': 'HW Ver', 'field': 'HW'},
{'name': 'SW', 'label': 'SW Ver', 'field': 'SW'},
{'name': 'SN', 'label': 'Serial', 'field': 'SN'},
]
# What RTI actually PUT ON THE WIRE this tick, in motor space — the literal ints handed to
# Send_data_pack_1 / Send_data_pack_PD. Distinct from motor_columns above, which is what the
# driver reports BACK. "—" means the channel was not commanded (data_pack_1 omits it), which
# is not the same as a commanded 0.
sent_columns = [
{'name': 'joint', 'label': 'Joint', 'field': 'joint'},
{'name': 'spos', 'label': 'Position (ticks)', 'field': 'spos'},
{'name': 'sspd', 'label': 'Speed (ticks/s)', 'field': 'sspd'},
{'name': 'scur', 'label': 'Current (mA)', 'field': 'scur'},
]
info_columns = [
{'name': 'joint', 'label': 'Joint', 'field': 'joint'},
{'name': 'temp', 'label': 'Temp (°C)', 'field': 'temp'},
{'name': 'volt', 'label': 'Voltage', 'field': 'volt'},
{'name': 'kt', 'label': 'Kt (Nm/A)', 'field': 'kt'},
{'name': 'kt_src', 'label': 'Kt from', 'field': 'kt_src'},
]
def _fmt_kt_src(value):
"""Where a Kt value actually came from: read off the motor over CAN, or the XML fallback
(motor didn't answer, or kt_source=xml). Resolved once at startup by utility/kt_init.py."""
return "CAN" if float(value) else "XML"
error_columns = [
{'name': 'joint', 'label': 'Joint', 'field': 'joint'},
{'name': 'temp', 'label': 'Temp', 'field': 'temp'},
{'name': 'enc', 'label': 'Encoder', 'field': 'enc'},
{'name': 'vbus', 'label': 'VBUS', 'field': 'vbus'},
{'name': 'drv', 'label': 'Driver', 'field': 'drv'},
{'name': 'vel', 'label': 'Velocity', 'field': 'vel'},
{'name': 'cur', 'label': 'Current', 'field': 'cur'},
{'name': 'estop', 'label': 'EStop', 'field': 'estop'},
{'name': 'wd', 'label': 'Watchdog', 'field': 'wd'},
{'name': 'cal', 'label': 'Calibrated', 'field': 'cal'},
]
gripper_columns = [
{'name': 'pos', 'label': 'Position', 'field': 'pos'},
{'name': 'cur', 'label': 'Current', 'field': 'cur'},
{'name': 'act', 'label': 'Active', 'field': 'act'},
{'name': 'action', 'label': 'Action', 'field': 'action'},
{'name': 'obj', 'label': 'Object', 'field': 'obj'},
# The GRIPPER MECHANISM's calibration (stroke/endstop sweep — what the Calibrate button runs).
# Distinct from the motor driver's own 'Motor Calibrated' flag in the gripper motor table.
{'name': 'cal', 'label': 'Gripper Calibrated', 'field': 'cal'},
{'name': 'temp_err', 'label': 'Temp Err', 'field': 'temp_err'},
{'name': 'timeout', 'label': 'Timeout', 'field': 'timeout'},
{'name': 'err', 'label': 'Error', 'field': 'err'},
{'name': 'estop', 'label': 'EStop', 'field': 'estop'},
]
joint_columns = [
{'name': 'j', 'label': 'Joint', 'field': 'j'},
{'name': 'homed', 'label': 'Homed', 'field': 'homed'},
{'name': 'pos', 'label': 'Position (rad)', 'field': 'pos'},
{'name': 'spd', 'label': 'Speed (rad/s)', 'field': 'spd'},
{'name': 'trq', 'label': 'Torque (Nm)', 'field': 'trq'},
{'name': 'acc', 'label': 'Accel (rad/s²)', 'field': 'acc'},
{'name': 'jrk', 'label': 'Jerk', 'field': 'jrk'},
{'name': 'pos_cmd', 'label': 'Pos Cmd', 'field': 'pos_cmd'},
{'name': 'spd_cmd', 'label': 'Spd Cmd', 'field': 'spd_cmd'},
{'name': 'trq_cmd', 'label': 'Trq Cmd', 'field': 'trq_cmd'},
{'name': 'trq_ext', 'label': 'Ext Torque', 'field': 'trq_ext'},
]
tcp_columns = [
{'name': 'axis', 'label': 'Axis', 'field': 'axis'},
{'name': 'pose', 'label': 'Pose', 'field': 'pose'},
{'name': 'spd', 'label': 'Speed', 'field': 'spd'},
{'name': 'force_ext', 'label': 'F External', 'field': 'force_ext'},
{'name': 'pose_cmd', 'label': 'Pose Cmd', 'field': 'pose_cmd'},
{'name': 'spd_cmd', 'label': 'Spd Cmd', 'field': 'spd_cmd'},
]
rti_columns = [
{'name': 'node', 'label': 'Node', 'field': 'node'},
{'name': 'scan', 'label': 'Scan', 'field': 'scan'},
{'name': 'err_cnt', 'label': 'Errors', 'field': 'err_cnt'},
{'name': 'old_data', 'label': 'Old Data', 'field': 'old_data'},
{'name': 'conn_err', 'label': 'Conn Err', 'field': 'conn_err'},
]
# Processes panel (System Info tab). Pattern = the script's command-line basename.
process_columns = [
{'name': 'name', 'label': 'Name', 'field': 'name', 'align': 'left'},
{'name': 'pid', 'label': 'PID', 'field': 'pid'},
{'name': 'cores', 'label': 'Core', 'field': 'cores'},
{'name': 'sched', 'label': 'Sched', 'field': 'sched'},
{'name': 'prio', 'label': 'Prio', 'field': 'prio'},
{'name': 'cpu', 'label': 'CPU%', 'field': 'cpu'},
{'name': 'mem', 'label': 'Mem', 'field': 'mem'},
]
PROCESS_PATTERNS = {
"RTI": "RTI.py",
"GUI": "nicegui_test.py",
"HIGH_LEVEL": "command_executor.py",
"SUPERVISOR": "supervisor.py",
}
activity_columns = [
{'name': 'time', 'label': 'Time', 'field': 'time', 'align': 'left'},
{'name': 'source', 'label': 'Source', 'field': 'source', 'align': 'left'},
{'name': 'level', 'label': 'Level', 'field': 'level', 'align': 'left'},
{'name': 'code', 'label': 'Code', 'field': 'code', 'align': 'left'},
{'name': 'id', 'label': 'ID', 'field': 'id', 'align': 'left'},
{'name': 'command', 'label': 'Command', 'field': 'command', 'align': 'left'},
{'name': 'detail', 'label': 'Detail', 'field': 'detail', 'align': 'left'},
]
pid_columns = [
{'name': 'joint', 'label': 'Joint', 'field': 'joint'},
{'name': 'KPP', 'label': 'KPP (Pos P)', 'field': 'KPP'},
{'name': 'KPV', 'label': 'KPV (Vel P)', 'field': 'KPV'},
{'name': 'KIV', 'label': 'KIV (Vel I)', 'field': 'KIV'},
{'name': 'KPIQ', 'label': 'KPIQ (Cur P)', 'field': 'KPIQ'},
{'name': 'KIIQ', 'label': 'KIIQ (Cur I)', 'field': 'KIIQ'},
{'name': 'KP', 'label': 'KP (Imp P)', 'field': 'KP'},
{'name': 'KD', 'label': 'KD (Imp D)', 'field': 'KD'},
{'name': 'Ilim', 'label': 'Iq Limit (mA)', 'field': 'Ilim'},
{'name': 'vel_lim', 'label': 'Vel Limit (t/s)','field': 'vel_lim'},
{'name': 'vlim', 'label': 'V Limit (mV)', 'field': 'vlim'},
]
def _fmt_vlim(value):
"""Voltage limit for the config tables. 0 is the driver's "use VBUS" mode, not a 0 mV limit —
show it as such rather than a bare zero."""
return "VBUS" if float(value) == 0.0 else f"{float(value):.0f}"
# ─────────────────────────────────────────────────────────────
# STATUS BAR (always visible, top of page)
# ─────────────────────────────────────────────────────────────
with ui.card().classes("w-full mb-2"):
with ui.row().classes("items-center gap-3 flex-wrap px-3 py-2"):
ui.label("Status").classes("font-bold text-sm text-gray-500 uppercase tracking-wide")
robot_mode_badge = ui.badge("MODE: ---")
robot_state_badge = ui.badge("STATE: ---").props("color=blue outline")
homed_badge = ui.badge("NOT HOMED").props("color=orange outline")
sim_badge = ui.badge("SIM: ---").props("color=purple outline")
error_badge = ui.badge("ERR: 0").props("color=grey outline")
safety_badge = ui.badge("SAFETY: OK").props("color=positive outline")
rti_process_badge = ui.badge("RTI: ---").props("color=grey outline")
robot_can_badge = ui.badge("ROBOT: ---").props("color=grey outline")
ui.separator().props("vertical")
robot_cmd_label = ui.label("CMD: ---").classes("font-mono text-sm text-gray-500")
recipe_label = ui.label("Recipe: ---").classes("font-mono text-sm text-gray-500")
ui.separator().props("vertical")
_sw_estop_btn = ui.button("SW E-STOP", icon="emergency", on_click=handle_sw_estop_toggle).props("color=red size=sm")
ui.separator().props("vertical")
_limp_btn = ui.button("MOTORS OFF", icon="power_settings_new",
on_click=lambda: handle_limp_toggle()).props("color=deep-orange size=sm")
ui.separator().props("vertical")
_grav_comp_state = [True]
def _handle_grav_comp_toggle():
_grav_comp_state[0] = not _grav_comp_state[0]
enabled = _grav_comp_state[0]
_exec(lambda r: r.set_gravity_comp(enabled), "gravity_comp")
_grav_comp_btn.props(f"color={'positive' if enabled else 'grey'}")
_grav_comp_btn.set_text("Grav Comp ON" if enabled else "Grav Comp OFF")
_grav_comp_btn = ui.button("Grav Comp ON", icon="downhill_skiing",
on_click=_handle_grav_comp_toggle).props("color=positive outline size=sm")
ui.separator().props("vertical")
ui.button("Enable", icon="power", on_click=handle_enable).props("color=positive outline size=sm")
ui.button("Disable", icon="power_off", on_click=handle_disable).props("color=grey outline size=sm")
ui.button("Home", icon="home", on_click=handle_home).props("color=primary outline size=sm")
ui.button("Enter EXEC", icon="play_circle", on_click=handle_enter_exec).props("color=secondary outline size=sm")
ui.button("Exit EXEC", icon="stop_circle", on_click=handle_exit_exec).props("color=grey outline size=sm")
ui.button("Clear Errors", icon="cancel", on_click=handle_clear_errors).props("color=negative outline size=sm")
# ─────────────────────────────────────────────────────────────
# JOG CONTROLS
# ─────────────────────────────────────────────────────────────
# Read live jog config from shared memory so a fresh GUI tab reflects whatever
# RTI currently has — XML defaults at boot, or whatever the user last set.
# RTI writes these via JogHandler._mirror_all_to_shared_memory + set_* methods.
_PROFILE_IDX_TO_NAME = {0: 'trapezoidal', 1: 'scurve'}
_CONTROL_IDX_TO_NAME = {0: 'pid', 1: 'pd'}
_initial_speed_pct = float(shared_data.rti['jog_speed_pct'][0])
_initial_accel_time = float(shared_data.rti['jog_accel_time'][0])
_initial_jerk_factor = float(shared_data.rti['jog_jerk_factor'][0])
_initial_profile = _PROFILE_IDX_TO_NAME.get(int(shared_data.rti['jog_profile_idx'][0]), 'scurve')
_initial_control_mode = _CONTROL_IDX_TO_NAME.get(int(shared_data.rti['jog_control_mode'][0]), 'pid')
# Safety fallback: if RTI hasn't started yet, shared memory reads as 0 — use
# the XML-equivalent defaults so the GUI is usable in isolation.
if _initial_speed_pct <= 0.0: _initial_speed_pct = 0.20
if _initial_accel_time <= 0.0: _initial_accel_time = 0.55
if _initial_jerk_factor <= 0.0: _initial_jerk_factor = 3.0
_jog_state = {
'speed_pct': _initial_speed_pct,
'accel_time': _initial_accel_time,
'profile': _initial_profile,
'jerk_factor': _initial_jerk_factor,
'control_mode': _initial_control_mode,
}
def _jog_start(joint_idx, direction):
speed = _jog_state['speed_pct']
_exec(lambda r: r.jog(joint_idx, direction, speed), "jog_set")
def _jog_stop():
_exec(lambda r: r.jog_stop(), "jog_stop")
with ui.card().classes("w-full mb-2"):
with ui.row().classes("items-center gap-3 flex-wrap px-3 py-2"):
ui.label("Jog").classes("font-bold text-sm text-gray-500 uppercase tracking-wide")
ui.button("Enter JOG", icon="open_with",
on_click=lambda: _exec(lambda r: r.enter_jog_mode(), "enter_jog_mode")
).props("color=primary outline size=sm")
ui.button("Exit JOG", icon="close",
on_click=lambda: _exec(lambda r: r.enter_idle_mode(), "enter_idle_mode")
).props("color=grey outline size=sm")
ui.separator().props("vertical")
ui.label("Speed:").classes("text-sm text-gray-500")
_speed_init = int(round(_initial_speed_pct * 100))
_jog_speed_slider = ui.slider(min=1, max=100, value=_speed_init).classes("w-36")
_jog_speed_label = ui.label(f"{_speed_init}%").classes("text-sm font-mono w-8")
def _on_jog_speed(e):
_jog_state['speed_pct'] = e.args / 100.0
_jog_speed_label.set_text(f"{e.args}%")
_refresh_jog_speed_labels()
_jog_speed_slider.on('update:model-value', _on_jog_speed)
ui.separator().props("vertical")
ui.label("Accel:").classes("text-sm text-gray-500")
_accel_init = int(round(_initial_accel_time * 100))
_jog_accel_slider = ui.slider(min=5, max=400, value=_accel_init).classes("w-36")
_jog_accel_label = ui.label(f"{_initial_accel_time:.2f}s").classes("text-sm font-mono w-12")
def _on_jog_accel(e):
t = e.args / 100.0
_jog_state['accel_time'] = t
_jog_accel_label.set_text(f"{t:.2f}s")
_exec(lambda r: r.set_jog_accel(t), "jog_accel")
_jog_accel_slider.on('update:model-value', _on_jog_accel)
ui.separator().props("vertical")
ui.label("Profile:").classes("text-sm text-gray-500")
def _on_jog_profile(e):
_jog_state['profile'] = e.value
_exec(lambda r: r.set_jog_profile(e.value), "jog_profile")
_jog_profile_toggle = ui.toggle({'trapezoidal': 'TRAPEZOIDAL', 'scurve': 'S-CURVE'},
value=_initial_profile, on_change=_on_jog_profile)
with ui.row().classes("items-center gap-2") as _jog_jerk_row:
ui.separator().props("vertical")
ui.label("Jerk:").classes("text-sm text-gray-500")
_jerk_init = int(round(_initial_jerk_factor * 10))
_jog_jerk_slider = ui.slider(min=5, max=200, value=_jerk_init).classes("w-28")
_jog_jerk_label = ui.label(f"{_initial_jerk_factor:.1f}×").classes("text-sm font-mono w-8")
_jog_jerk_row.bind_visibility_from(_jog_profile_toggle, 'value', value='scurve')
def _on_jog_jerk(e):
factor = e.args / 10.0
_jog_state['jerk_factor'] = factor
_jog_jerk_label.set_text(f"{factor:.1f}×")
_exec(lambda r: r.set_jog_jerk_factor(factor), "jog_jerk_factor")
_jog_jerk_slider.on('update:model-value', _on_jog_jerk)
ui.separator().props("vertical")
ui.label("Control:").classes("text-sm text-gray-500")
def _on_jog_control_mode(e):
_jog_state['control_mode'] = e.value
_exec(lambda r: r.set_jog_control_mode(e.value), "jog_control_mode")
ui.toggle(['pid', 'pd'], value=_initial_control_mode, on_change=_on_jog_control_mode)
_jog_buttons = [] # list of {'neg': btn, 'pos': btn} — used by update_tables() for block indicators
# Tracks whether a jog button is currently held. Lets mouseleave act as a
# drag-off safety only when a button was actually pressed, instead of
# firing jog_stop every time the cursor passes over a button.
_jog_btn_pressed = {'active': False}
def _jog_button_down(joint_idx, direction):
_jog_btn_pressed['active'] = True
_jog_start(joint_idx, direction)
def _jog_button_up():
if _jog_btn_pressed['active']:
_jog_btn_pressed['active'] = False
_jog_stop()
_jog_max_vel_rad = [float(v) for v in _xml_cfg['joint_velocity_limit']]
_jog_ticks_per_rad = [
(2 ** int(_xml_cfg['motor_encoder'][i])) * float(_xml_cfg['gear_ratio'][i]) / (2.0 * math.pi)
for i in range(JOINTS)
]
_jog_speed_labels = []
def _refresh_jog_speed_labels():
pct = _jog_state['speed_pct']
for i, lbl in enumerate(_jog_speed_labels):
rad_s = pct * _jog_max_vel_rad[i]
tick_s = rad_s * _jog_ticks_per_rad[i]
lbl.set_text(f"{rad_s:.2f} rad/s · {tick_s:.0f} t/s")
with ui.row().classes("gap-6 px-3 pb-3 flex-wrap"):
for _ji in range(6):
with ui.column().classes("items-start gap-0"):
with ui.row().classes("items-center gap-1"):
ui.label(f"J{_ji + 1}").classes("text-sm font-mono text-gray-500 w-5")
_neg = ui.button("◄").props("size=sm flat dense")
_pos = ui.button("►").props("size=sm flat dense")
_neg.on('mousedown', lambda e, j=_ji: _jog_button_down(j, -1))
_neg.on('mouseup', lambda e: _jog_button_up())
_neg.on('mouseleave', lambda e: _jog_button_up())
_pos.on('mousedown', lambda e, j=_ji: _jog_button_down(j, +1))
_pos.on('mouseup', lambda e: _jog_button_up())
_pos.on('mouseleave', lambda e: _jog_button_up())
_jog_buttons.append({'neg': _neg, 'pos': _pos})
_jog_speed_labels.append(
ui.label("").classes("text-xs font-mono text-gray-400 pl-6")
)
_refresh_jog_speed_labels()
_JOYSTICK_DEADZONE = 0.04 # ignore x within this fraction of full range
def _on_joystick_move(e, joint_idx):
x = e.x # nipplejs vector component: -1.0 (full left) … +1.0 (full right)
if abs(x) < _JOYSTICK_DEADZONE:
_exec(lambda r: r.jog_stop(), "jog_stop")
return
direction = 1 if x > 0 else -1
speed_pct = min(abs(x), 1.0)
_exec(lambda r: r.jog(joint_idx, direction, speed_pct), "jog_set")
ui.separator()
with ui.row().classes("gap-5 px-3 pt-1 pb-3 flex-wrap"):
for _ji in range(6):
with ui.column().classes("items-center gap-1"):
ui.label(f"J{_ji + 1}").classes("text-xs font-mono text-gray-500")
ui.joystick(
color='#1976D2',
size=46,
mode='static',
lockX=True,
on_move=lambda e, j=_ji: _on_joystick_move(e, j),
on_end=lambda e: _exec(lambda r: r.jog_stop(), "jog_stop"),
throttle=0.05,
).style("width:90px; height:90px;")
ui.label("← speed →").classes("text-xs text-gray-400")
# ─────────────────────────────────────────────────────────────
# TABS
# ─────────────────────────────────────────────────────────────
with ui.tabs().classes("w-full") as tabs:
tab_joints = ui.tab('Joints & TCP', icon='timeline')
tab_motor = ui.tab('Motor', icon='electric_bolt')
tab_gripper = ui.tab('Gripper', icon='back_hand')
tab_diag = ui.tab('RT Diagnostics', icon='speed')
tab_power = ui.tab('Power & CB', icon='bolt')
tab_io = ui.tab('I/O', icon='device_hub')
tab_sysinfo = ui.tab('System Info', icon='computer')
tab_errors = ui.tab('Errors', icon='error')
tab_activity = ui.tab('Activity Log', icon='history')
tab_pid = ui.tab('PID Config', icon='tune')
tab_filters = ui.tab('Tune Filters', icon='graphic_eq')
tab_preview = ui.tab('Plan Preview', icon='play_circle')
tab_plots = ui.tab('Plots', icon='show_chart')
tab_firmware = ui.tab('Firmware', icon='memory')
tabs.set_value('Joints & TCP')
with ui.tab_panels(tabs, value=tab_joints).classes("w-full"):
# ─── Joints & TCP ───────────────────────────────────────
with ui.tab_panel(tab_joints):
ui.label("Joint Data").classes("text-sm font-semibold mt-2 mb-1 text-gray-600 uppercase tracking-wide")
joint_table = ui.table(columns=joint_columns, rows=[]).classes("w-full")
ui.separator().classes("my-3")
ui.label("TCP Pose & Forces").classes("text-sm font-semibold mb-1 text-gray-600 uppercase tracking-wide")
tcp_table = ui.table(columns=tcp_columns, rows=[]).classes("w-full")
# ─── Motor ──────────────────────────────────────────────
with ui.tab_panel(tab_motor):
with ui.row().classes("gap-4 mb-3 flex-wrap"):
motor_conn_badges = []
motor_err_badges = []
for _i in range(JOINTS):
with ui.column().classes("items-center gap-1"):
ui.label(f"J{_i+1}").classes("text-xs font-bold text-gray-500")
_cb = ui.badge("CONNECTED").props("color=positive")
_eb = ui.badge("NO ERRORS").props("color=positive outline")
motor_conn_badges.append(_cb)
motor_err_badges.append(_eb)
ui.label("Motor Telemetry").classes("text-sm font-semibold mt-2 mb-1 text-gray-600 uppercase tracking-wide")
motor_table = ui.table(columns=motor_columns, rows=[]).classes("w-full")
ui.separator().classes("my-3")
with ui.row().classes("items-center gap-3 mb-1"):
ui.label("CAN Commands Sent").classes("text-sm font-semibold text-gray-600 uppercase tracking-wide")
sent_mode_badge = ui.badge("—").props("color=grey outline")
ui.label("Exactly what RTI put on the wire this tick, in motor space (after rad→ticks / "
"Nm→mA and int truncation). '—' = channel not commanded, which is different "
"from a commanded 0. Arm joints on the dispatch path only — homing does its "
"own sends and the gripper has its own path.").classes("text-xs text-gray-400 mb-1")
sent_table = ui.table(columns=sent_columns, rows=[]).classes("w-full")
ui.separator().classes("my-3")
ui.label("Temperature / Voltage / Kt").classes("text-sm font-semibold mb-1 text-gray-600 uppercase tracking-wide")
info_table = ui.table(columns=info_columns, rows=[]).classes("w-full")
ui.separator().classes("my-3")
ui.label("Error Flags").classes("text-sm font-semibold mb-1 text-gray-600 uppercase tracking-wide")
error_table = ui.table(columns=error_columns, rows=[]).classes("w-full")
# ─── Gripper ────────────────────────────────────────────
with ui.tab_panel(tab_gripper):
with ui.row().classes("items-center gap-3 mb-3"):
gripper_conn_badge = ui.badge("GRIPPER: UNKNOWN").props("color=grey")
gripper_mode_badge = ui.badge("MODE: ---").props("color=grey outline")
gripper_err_badge = ui.badge("NO ERRORS").props("color=positive outline")
gripper_err_badge.set_visibility(False)
# ─── Gripper Command (firmware mode) ────────────────────
# In firmware mode, RTI sends Send_gripper_data_pack every tick with
# activate forced to 1. To take the firmware path offline, flip the
# mode toggle to MOTOR. The action flag below toggles movement vs hold.
_gripper_cmd_state = {'position': 0, 'speed': 100, 'current': 200,
'action': 0,
'last_dir': 0} # +1 closing, -1 opening (set on each move)
def _send_gripper_cmd(position):
s = _gripper_cmd_state
# Snapshot the fields NOW — the worker runs the call later and the shared state
# dict is mutated by _gr_move/_gr_stop, so a captured dict could send stale values.
pos, spd, cur, act = int(position), s['speed'], s['current'], s['action']
_exec(lambda r: r.set_gripper(pos, spd, cur, act), "gripper_set")
def _gr_move(pos):
# Open/Close pass 1/254; Goto passes the slider's tracked value.
# We do NOT write `position` into _gripper_cmd_state — that field is
# owned by the slider so Goto always reflects the slider, not the
# last hard-coded button target.
target = int(pos)
current = int(shared_data.gripper['gripper_position'][0])
_gripper_cmd_state['last_dir'] = 1 if target > current else (-1 if target < current else 0)
_gripper_cmd_state['action'] = 1
_send_gripper_cmd(target)
def _gr_idle():
# RELEASE. action=0 drops the firmware into its "Idle or disabled" branch:
# velocity setpoint 0, and on a Spectral BLDC board the output stage is
# switched off as well (SLEEP/RESET LOW), so the jaws go limp and can be
# moved by hand. A STEPFOC board has no such lines and settles into a
# velocity-0 hold instead — no active command either way, but only the
# Spectral one is genuinely draggable. RTI announces this to the firmware
# and then holds the bus quiet with empty polls.
_gripper_cmd_state['last_dir'] = 0
_gripper_cmd_state['action'] = 0
_send_gripper_cmd(_gripper_cmd_state['position'])
def _gr_stop():
# HALT IN PLACE — hold the jaws exactly where they are.
#
# The firmware has no graceful stop primitive. Its only stop is the ESTOP
# bit, and that LATCHES A FAULT (motor_control.cpp sets estop_error = 1 and
# controller.Error = 1), which would then need clearing before the gripper
# worked again. Not what a Stop button should do.
#
# So stop is done host-side: re-target the position the jaws are at RIGHT
# NOW, keeping action=1. The firmware is already within tolerance of that
# target, so it holds there instead of continuing to the old one.
here = int(shared_data.gripper['gripper_position'][0])
if not 1 <= here <= 254:
# No trustworthy reading (an uncalibrated gripper reports 0). Releasing
# is the safe fallback — commanding 0 would be read as FULLY OPEN and
# drive the jaws instead of stopping them.
_gr_idle()
return
_gripper_cmd_state['last_dir'] = 0
_gripper_cmd_state['action'] = 1
_send_gripper_cmd(here)
def _on_gripper_ctrl_mode(e):
mode = 2 if e.value == 'firmware' else 1
_exec(lambda r: r.set_gripper_ctrl_mode(mode), "gripper_ctrl_mode")
with ui.card().classes("w-full mb-3"):
with ui.row().classes("items-center gap-3 flex-wrap px-3 py-2"):
ui.label("Gripper Command").classes("font-bold text-sm text-gray-500 uppercase tracking-wide")
ui.label("Mode:").classes("text-sm text-gray-500")
gripper_ctrl_mode_toggle = ui.toggle(['motor', 'firmware'], value='motor',
on_change=_on_gripper_ctrl_mode)
ui.separator().props("vertical")
ui.button("Open", icon="open_in_full", on_click=lambda: _gr_move(1) ).props("color=primary outline size=sm")
ui.button("Close", icon="close_fullscreen",on_click=lambda: _gr_move(254)).props("color=primary outline size=sm")
ui.button("Goto", icon="play_arrow", on_click=lambda: _gr_move(_gripper_cmd_state['position'])).props("color=primary outline size=sm")
ui.button("Stop", icon="stop", on_click=_gr_stop ).props("color=warning outline size=sm") \
.tooltip("Halt in place — holds the jaws where they are (still gripping)")
ui.button("Idle", icon="power_settings_new", on_click=_gr_idle ).props("color=warning outline size=sm") \
.tooltip("Release — no active command. Limp on SSG48, velocity-0 hold on MSG")
ui.separator().props("vertical")
ui.button("Calibrate", icon="straighten", on_click=lambda: _exec(lambda r: r.gripper_calibrate(), "gripper_calibrate")).props("color=secondary outline size=sm")
with ui.row().classes("items-center gap-3 flex-wrap px-3 pb-1"):
ui.label("Status:").classes("text-sm text-gray-500")
gripper_status_label = ui.label("---").classes("text-sm font-mono font-bold")
with ui.row().classes("items-center gap-3 flex-wrap px-3 pb-3"):
ui.label("Pos:").classes("text-sm text-gray-500")
_gr_pos_slider = ui.slider(min=0, max=255, value=0).classes("w-40")
_gr_pos_label = ui.label("0").classes("text-sm font-mono w-10")
def _on_gr_pos(e):
_gripper_cmd_state['position'] = int(e.args)
_gr_pos_label.set_text(str(int(e.args)))
_gr_pos_slider.on('update:model-value', _on_gr_pos)
ui.separator().props("vertical")
ui.label("Spd:").classes("text-sm text-gray-500")
_gr_spd_slider = ui.slider(min=0, max=255, value=100).classes("w-40")
_gr_spd_label = ui.label("100").classes("text-sm font-mono w-10")
def _on_gr_spd(e):
_gripper_cmd_state['speed'] = int(e.args)
_gr_spd_label.set_text(str(int(e.args)))
_gr_spd_slider.on('update:model-value', _on_gr_spd)
ui.separator().props("vertical")
ui.label("Cur (mA):").classes("text-sm text-gray-500")
_gr_cur_slider = ui.slider(min=0, max=1500, value=200).classes("w-40")
_gr_cur_label = ui.label("200").classes("text-sm font-mono w-12")
def _on_gr_cur(e):
_gripper_cmd_state['current'] = int(e.args)
_gr_cur_label.set_text(str(int(e.args)))
_gr_cur_slider.on('update:model-value', _on_gr_cur)
ui.label("Gripper Status").classes("text-sm font-semibold mt-2 mb-1 text-gray-600 uppercase tracking-wide")
gripper_table = ui.table(columns=gripper_columns, rows=[]).classes("w-full")
ui.separator().classes("my-3")
ui.label("Gripper Motor Health").classes("text-sm font-semibold mb-1 text-gray-600 uppercase tracking-wide")
with ui.grid(columns=2).classes("gap-x-8 gap-y-1 font-mono text-sm mt-1 mb-2"):
ui.label("Position (ticks)"); grp_motor_pos_lbl = ui.label("---")
ui.label("Speed (ticks/s)"); grp_motor_spd_lbl = ui.label("---")
ui.label("Current (mA)"); grp_motor_cur_lbl = ui.label("---")
ui.label("Temperature (°C)"); grp_motor_temp_lbl = ui.label("---")
ui.label("Voltage"); grp_motor_volt_lbl = ui.label("---")
ui.label("Kt (Nm/A)"); grp_motor_kt_lbl = ui.label("---")
ui.label("HW Version"); grp_motor_hw_lbl = ui.label("---")
ui.label("SW Version"); grp_motor_sw_lbl = ui.label("---")
ui.label("Serial"); grp_motor_sn_lbl = ui.label("---")
ui.label("Gripper Motor Error Flags").classes("text-sm font-semibold mb-1 text-gray-600 uppercase tracking-wide")
grp_motor_err_columns = [
{'name': 'temp', 'label': 'Temp', 'field': 'temp'},
{'name': 'enc', 'label': 'Encoder', 'field': 'enc'},
{'name': 'vbus', 'label': 'VBUS', 'field': 'vbus'},
{'name': 'drv', 'label': 'Driver', 'field': 'drv'},
{'name': 'vel', 'label': 'Velocity', 'field': 'vel'},
{'name': 'cur', 'label': 'Current', 'field': 'cur'},
{'name': 'estop', 'label': 'EStop', 'field': 'estop'},
{'name': 'wd', 'label': 'Watchdog', 'field': 'wd'},
# The MOTOR DRIVER's own calibration (commutation/encoder, factory-level) — not the
# gripper mechanism's stroke calibration shown as 'Gripper Calibrated' in the status table.
{'name': 'cal', 'label': 'Motor Calibrated','field': 'cal'},
]
grp_motor_err_table = ui.table(columns=grp_motor_err_columns, rows=[]).classes("w-full mb-3")
ui.separator().classes("my-3")
ui.label("Gripper Joint (SI units)").classes("text-sm font-semibold mb-1 text-gray-600 uppercase tracking-wide")
with ui.grid(columns=4).classes("gap-3 font-mono text-sm mt-1"):
ui.label("").classes("font-bold")
ui.label("Position (m)").classes("font-bold")
ui.label("Speed (m/s)").classes("font-bold")
ui.label("Force (N)").classes("font-bold")
ui.label("Actual")
grp_pos_actual_lbl = ui.label("---")
grp_spd_actual_lbl = ui.label("---")
grp_frc_actual_lbl = ui.label("---")
ui.label("Target")
grp_pos_target_lbl = ui.label("---")
grp_spd_target_lbl = ui.label("---")
grp_frc_target_lbl = ui.label("---")
ui.label("Commanded")
grp_pos_cmd_lbl = ui.label("---")
grp_spd_cmd_lbl = ui.label("---")
grp_frc_cmd_lbl = ui.label("---")
# ─── RT Diagnostics ─────────────────────────────────────
with ui.tab_panel(tab_diag):
with ui.card().classes("w-full mb-3"):
ui.label("Loop Health").classes("text-sm font-semibold mb-2 text-gray-600 uppercase tracking-wide")
with ui.row().classes("gap-6 font-mono text-sm flex-wrap"):
ts_label = ui.label("Timestamp: ---")
tick_label = ui.label("Tick: ---")
gripper_connected_label = ui.label("Gripper: ---")
hall_index_label = ui.label("Hall: ---")
additional_pin2_label = ui.label("Pin2: ---")
edge_detect_label = ui.label("Edge: ---")
with ui.row().classes("gap-6 font-mono text-sm flex-wrap mt-1"):
safety_violation_label = ui.label("Safety violation: NO")
error_active_label = ui.label("Error active: 0")
can_error_nodes_label = ui.label("CAN nodes in error: 0")
can_old_data_label = ui.label("CAN old-data flags: 0")
ui.separator().classes("my-2")
ui.label("Timing").classes("text-sm font-semibold text-gray-600 uppercase tracking-wide")
# p95/p99 are a rolling window over the last ~500 ticks (always fresh,
# never need a manual reset). "Peak" is since-start and can be zeroed
# with the button below — see handle_reset_loop_stats.
with ui.grid(columns=6).classes("gap-x-6 gap-y-1 font-mono text-sm mt-1"):
ui.label("").classes("font-bold")
ui.label("Current").classes("font-bold")
ui.label("EMA avg").classes("font-bold")
ui.label("p95").classes("font-bold")
ui.label("p99").classes("font-bold")
ui.label("Peak").classes("font-bold")
ui.label("Period (ms)")
period_cur_label = ui.label("—")
period_avg_label = ui.label("—")
period_p95_label = ui.label("—")
period_p99_label = ui.label("—")
period_peak_label = ui.label("—")
# Informational mirror of the Period row above — the ms figures stay the
# authority. Only Current/EMA are inverted: 1/period flips a percentile's
# tail (p99 period is the SLOW tail, so its Hz is the 1st percentile), and
# 1/peak-period is the LOWEST rate, not a peak. Showing those under p95/p99/
# Peak headers would read backwards, so they stay blank — same choice the
# GUI Loop panel below already makes.
ui.label("Rate (Hz)")
rate_cur_label = ui.label("—")
rate_avg_label = ui.label("—")
ui.label("")
ui.label("")
ui.label("")
ui.label("Exec (ms)")
exec_cur_label = ui.label("—")
exec_avg_label = ui.label("—")
exec_p95_label = ui.label("—")
exec_p99_label = ui.label("—")
exec_peak_label = ui.label("—")
ui.label("Jitter (µs)")
jitter_cur_label = ui.label("—")
jitter_avg_label = ui.label("—")
ui.label("")
ui.label("")
jitter_peak_label = ui.label("—")
ui.label("Overruns")
overrun_label = ui.label("0")
ui.label("")
ui.label("")
ui.label("")
ui.label("")
# How far behind the CAN bus this loop is running. Healthy = a few ms; 100 ms+
# means RTI is controlling on stale measurements (no PID tuning fixes that).
with ui.row().classes("items-center gap-1 no-wrap"):
ui.label("CAN age (ms)")
with ui.icon("help_outline").classes("text-gray-400 cursor-help text-sm"):
# Plain labels rather than ui.html/ui.markdown: their signatures have
# changed across NiceGUI versions (3.3 made ui.html's `sanitize` a
# required kwarg), and a tooltip is not worth a version dependency.
with ui.tooltip().classes("max-w-sm"), ui.column().classes("gap-1 py-1"):
ui.label("How old the measurements RTI is controlling on are.") \
.classes("font-semibold")
ui.label(
"Each tick RTI drains the CAN socket. Every frame carries a "
"kernel arrival timestamp, so this is how long the oldest frame "
"sat in the buffer before RTI read it — how far behind the bus "
"the loop is running.")
ui.label("Current = worst frame this tick · min = best this tick · "
"Peak = worst since reset").classes("italic")
ui.label("HEALTHY: under one tick (<4 ms).").classes("font-semibold")
ui.label(
"Draining once per tick means a frame arriving just after a "
"drain waits for the next one, so 0–4 ms is the floor, not a "
"fault. A spread between min and Current is normal and good.")
ui.label("BAD: min ≈ Current, both tens of ms.").classes("font-semibold")
ui.label(
"That is uniform staleness = a receive backlog. RTI is acting "
"on the past: commanded-vs-actual looks phase-shifted, errors "
"latch on stale state, and no amount of PID tuning fixes it.")
ui.label(
"Reads 0 on a silent bus (no frames to age) — CAN_LOST and "
"CAN_STALE cover that case instead.").classes("italic")
# 6 cells to match the grid: name | Current | (min in the EMA col) | p95 | p99 | Peak
can_age_label = ui.label("—")
can_age_min_label = ui.label("—")
ui.label("")
ui.label("")
can_age_peak_label = ui.label("—")
with ui.row().classes("mt-2 gap-2"):
ui.button("Reset Loop Stats (peaks)", icon="restart_alt",
on_click=handle_reset_loop_stats).props("color=grey outline size=sm")
ui.button("Reload Filters", icon="tune",
on_click=handle_reload_filters).props("color=grey outline size=sm")