-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRTI.py
More file actions
1876 lines (1667 loc) · 91.1 KB
/
Copy pathRTI.py
File metadata and controls
1876 lines (1667 loc) · 91.1 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
# -*- coding: utf-8 -*-
"""
Filename: RTI.py
Author: Petar Crnjak
Company: Source Robotics
Date: 13.5.2025
Version: 1.0
Description:
This script demonstrates a detailed
header format with additional metadata.
License: GNU General Public License v3.0
Contact: petar@source-robotics.com
Dependencies: os, sys
"""
import time
import signal
import atexit
from collections import deque
from utility.RTI_utils import *
from project_paths import RTI_LOG, SYSTEM_XML, ROBOTS_DIR, JOBLIB_DATA, TEMP_DATA_DIR, DATA_RECIPE_DIR, GRIPPERS_DIR, CRITICAL_LOG, CONFIG_DIR, FLASH_PERFORMED_MARKER
import logging
import sys
import numpy as np
from utility.robot_factory import create_robot
import threading
import zmq
from queue import Queue, Empty
from spatialmath import *
from gpiozero import pi_info
from utility.logger_setup import setup_logging
import config.xml_parser as read_XML2
from utility.selfcheck import run_selfcheck
from utility.state_machine import RobotMode, request_mode_change, request_enable, MAINTENANCE_MODES
from utility.error_checks import (
process_errors_tick, clear_errors, send_clear_errors, ExecLinkWatchdog,
LoopDegradationMonitor,
CLEAR_ERROR_SETTLE_TICKS, CLEAR_ERROR_SEND_REPEATS, _WARNING_SUFFIXES,
)
from utility.activity_log import get_rti_activity_logger, log_activity
from robotics.homing import HomingController
from motion.rti_handler import RTIModeHandler
from communication.rti_protocol import CLOCK_ROBOT, CLOCK_PC
# ==========================================================================
# System and Configuration
# ==========================================================================
from config.system_config import setup_realtime_process
from hardware.can_hardware import start_can_interface
#from config.network_config import initialize_all_sockets
# ==========================================================================
# Hardware
# ==========================================================================
from hardware.gpio_handler import (
initialize_gpio, update_gpio, check_estop_active, write_all_outputs, read_all_inputs,
set_output, set_output_high, set_output_low, toggle_output, HIGH, LOW,
ISOLATED_OUTPUT_1, ISOLATED_OUTPUT_2, ISOLATED_OUTPUT_3
)
from hardware.motor_setup import setup_motor_system
from hardware.can_hardware import scan_can_bus, initialize_can_communication
# init_rti_receive_socket is now an alias inside config/networking.py
# ==========================================================================
# Networking
# ==========================================================================
from config.networking import zmq_listener, zmq_sender_setup, UDP_socket_receive_setup, UDP_socket_send_setup, broadcast_UDP_telemetry, init_rti_receive_socket, drain_rti_udp, RTI_PORT_SENDER
from communication.can_message_handlers import receive_and_process_can_messages, handle_polling_and_overrides, update_can_connection_status, drain_can_discard
from communication.can_message_handlers import send_gripper_commands, send_motor_commands, secondary_data_send, load_motor_configs, load_gripper_configs, handle_motor_reconnect, write_motor_config_to_shared, write_gripper_config_to_shared, GRIPPER_IDLE_PACK_REPEATS
from utility.kt_init import resolve_and_preload_kt
from utility.tick_types import TickContext, TickResult
from utility.mode_dispatch import build_mode_dispatch, dispatch_step
from utility.kinematics_backend import set_kinematics_backend
from utility.pinocchio_attach import attach_pinocchio
# ==========================================================================
# Shared data setup — joint count driven by active robot in config/system.xml
# NOTE: load_system_config is a lightweight parse (two small XMLs only).
# It runs before shared_data.setup() so the joint count is always correct.
# ==========================================================================
_sys = read_XML2.load_system_config(SYSTEM_XML, ROBOTS_DIR)
from data import shared_data
shared_data.setup(joints=_sys['joint_num'])
from data.update_shared_data import update_motor_and_gripper_data, update_joint_and_tcp_data
from utility.filter_config import load_filter_banks
from utility.signal_filters import describe_bank
from data.data_recipe import RecipeManager, build_payload
# ==========================================================================
# System configuration (RT scheduling, CPU affinity, system info)
#
# NOTE: setup_realtime_process used to run here, BEFORE setup_logging()
# attached the file handler — so its info/warning messages disappeared.
# It's been moved to right after setup_logging() (just below this block);
# keeping the section header so the call site is easy to find by greppers
# accustomed to the old layout.
# ==========================================================================
# ==========================================================================
# Heartbeat terminal debug output
# Enable: RTI_HEARTBEAT=1 python RTI.py
# Interval: RTI_HEARTBEAT_INTERVAL=200 (ticks between prints, default 100)
# ==========================================================================
_HB_ENABLED = os.environ.get("RTI_HEARTBEAT", "0") == "1" # TRUE
_HB_INTERVAL = int(os.environ.get("RTI_HEARTBEAT_INTERVAL", "100"))
# ==========================================================================
# Optional RTI section profiler
# Enable: RTI_PROFILE=1 python3 RTI.py
# Interval: RTI_PROFILE_INTERVAL=500 (ticks per report, default 500)
# ==========================================================================
_PROFILE_ENABLED = os.environ.get("RTI_PROFILE", "0") == "1"
_PROFILE_INTERVAL = int(os.environ.get("RTI_PROFILE_INTERVAL", "500"))
_PROFILE_TOP = int(os.environ.get("RTI_PROFILE_TOP", "12"))
_profile_sum = {}
_profile_max = {}
_profile_count = 0
_profile_loop_sum = 0.0
# ==========================================================================
# Overrun tracer — names the section responsible for a slow tick.
# Enable: RTI_OVERRUN_TRACE=1 python3 RTI.py
# Threshold: RTI_OVERRUN_TRACE_MS=4.0 (default: the tick budget, delta_t)
#
# RTI_PROFILE answers "where does the AVERAGE tick go" — it averages over 500
# ticks, so a single 7 ms spike is smeared away and invisible. This answers the
# other question: "what blew up on THAT tick". It keeps the current tick's
# per-section times and dumps them, sorted, only when the tick exceeds the
# threshold. Rare by construction, so the log stays readable.
#
# Overhead when enabled: the same ~22 perf_counter calls RTI_PROFILE already
# does — 3.06 us/tick, 0.077% of a 4 ms tick. Zero when disabled (the mark
# function returns immediately). Writes into a preallocated dict, so no
# allocation once the section names are known.
# ==========================================================================
_OVERRUN_TRACE_ENABLED = os.environ.get("RTI_OVERRUN_TRACE", "0") == "1"
_OVERRUN_TRACE_MS = float(os.environ.get("RTI_OVERRUN_TRACE_MS", "0")) / 1e3 # 0 => use delta_t
_OVERRUN_TRACE_TOP = int(os.environ.get("RTI_OVERRUN_TRACE_TOP", "6"))
_tick_sections = {} # section -> seconds spent THIS tick (overwritten each tick)
_overrun_trace_count = 0
# Marks must run if EITHER consumer is on.
_MARKS_ON = _PROFILE_ENABLED or _OVERRUN_TRACE_ENABLED
def _profile_mark(last_time, name):
if not _MARKS_ON:
return last_time
now = time.perf_counter()
dt = now - last_time
if _PROFILE_ENABLED:
_profile_sum[name] = _profile_sum.get(name, 0.0) + dt
if dt > _profile_max.get(name, 0.0):
_profile_max[name] = dt
if _OVERRUN_TRACE_ENABLED:
_tick_sections[name] = dt
return now
def _overrun_trace(loop_total, tick, mode):
"""Log the per-section breakdown of a tick that blew its budget.
Reports the UNACCOUNTED remainder too: if the sections sum to far less than the
tick took, the cost is in an unprofiled gap between marks, which is itself the
finding (it says "add a mark here", not "this section is slow").
"""
global _overrun_trace_count
if not _OVERRUN_TRACE_ENABLED or not _tick_sections:
return
limit = _OVERRUN_TRACE_MS if _OVERRUN_TRACE_MS > 0 else delta_t
if loop_total <= limit:
return
_overrun_trace_count += 1
ranked = sorted(_tick_sections.items(), key=lambda kv: kv[1], reverse=True)
accounted = sum(_tick_sections.values())
top = " ".join(f"{n}={v * 1e3:.2f}ms" for n, v in ranked[:_OVERRUN_TRACE_TOP] if v > 0)
logger.warning(
f"[OVERRUN #{_overrun_trace_count}] tick={int(tick)} mode={mode} "
f"exec={loop_total * 1e3:.3f}ms (limit {limit * 1e3:.2f}ms) | "
f"worst: {top} | unaccounted={(loop_total - accounted) * 1e3:.2f}ms"
)
def _profile_report(loop_total):
global _profile_count, _profile_loop_sum
if not _PROFILE_ENABLED:
return
_profile_count += 1
_profile_loop_sum += loop_total
if _profile_count < _PROFILE_INTERVAL:
return
rows = []
for name, total in _profile_sum.items():
avg_ms = (total / _profile_count) * 1e3
max_ms = _profile_max.get(name, 0.0) * 1e3
pct = (total / _profile_loop_sum * 100.0) if _profile_loop_sum > 0.0 else 0.0
rows.append((total, name, avg_ms, max_ms, pct))
rows.sort(reverse=True)
sys.stdout.write(
f"\n[RTI_PROFILE] last {_profile_count} ticks "
f"(avg exec {(_profile_loop_sum / _profile_count) * 1e3:.3f} ms)\n"
)
for _total, name, avg_ms, max_ms, pct in rows[:_PROFILE_TOP]:
sys.stdout.write(
f" {name:<24s} avg={avg_ms:8.3f} ms "
f"max={max_ms:8.3f} ms share={pct:5.1f}%\n"
)
sys.stdout.flush()
_profile_sum.clear()
_profile_max.clear()
_profile_count = 0
_profile_loop_sum = 0.0
# ==========================================================================
# Init gpio
# ==========================================================================
initialize_gpio()
# ==========================================================================
# Setup logging
# ==========================================================================
# Logging if TRUE print to terminal and save to log file, If FALSE save to log file - only for this file
setup_logging(str(RTI_LOG), log_to_console=True, critical_log_file=str(CRITICAL_LOG))
# Activity log — separate mechanism from the above (see TODO/activity_log_design.md).
_rti_activity_logger = get_rti_activity_logger()
# RT scheduling + CPU affinity. Runs AFTER setup_logging so the verified
# RT-state line lands in RTI.log instead of disappearing.
setup_realtime_process(cpu_core=3, priority=99)
# When a script crashes with exception we write the error to log file
def handle_exception(exc_type, exc_value, exc_traceback):
# Ignore keyboard interrupt
# if issubclass(exc_type, KeyboardInterrupt):
# sys.__excepthook__(exc_type, exc_value, exc_traceback)
# return
logging.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
sys.excepthook = handle_exception
# ==========================================================================
# Setup print format
# ==========================================================================
np.set_printoptions(suppress=True, precision=7, floatmode='fixed')
# ==========================================================================
# Setup networking
# ==========================================================================
# NOTE: Do NOT use ephemeral ports: 49152 to 65535
# u sudo ss -tunap to check all ports currently in use
robot_IP = get_local_ip()
# --- Create and start the thread
command_queue = Queue()
threading.Thread(target=zmq_listener, args=(command_queue,), daemon=True).start()
# --- Setup ZMQ response sender
status_socket = zmq_sender_setup()
# --- RTI socket receive ---
RTI_socket_receive = UDP_socket_receive_setup()
# --- RTI socket sender: RTI and telemetry---
RTI_socket_sender, telemetry_socket = UDP_socket_send_setup()
# ==========================================================================
# Get robot data from XML
# ==========================================================================
xml_path = str(_sys['robot_xml_path'])
output_path = str(_sys['robot_xml_path'].parent / f"{_sys['active_robot']}_modified.xml")
joblib_path = str(JOBLIB_DATA)
# Load all robot/gripper parameters in one call
cfg = read_XML2.load_full_robot_config(xml_path, grippers_dir=GRIPPERS_DIR, active_gripper=_sys['active_gripper'])
# Validate XML config — abort immediately if any required field is broken
_cfg_ok, _cfg_issues = read_XML2.validate_robot_config(cfg)
if not _cfg_ok:
for _msg in _cfg_issues:
logging.critical(f"[Startup] {_msg}")
raise SystemExit("RTI.py cannot start: robot XML has errors (see log above).")
robot_name = cfg['robot_name']
joint_num = cfg['joint_num']
motor_kt = cfg['motor_kt']
motor_Ilim = cfg['motor_Ilim']
motor_voltage_limit = cfg['motor_voltage_limit'] # mV, per joint (0 = use VBUS)
motor_velocity_limit = cfg['motor_velocity_limit']
motor_KPP = cfg['motor_KPP']
motor_KPV = cfg['motor_KPV']
motor_KIV = cfg['motor_KIV']
motor_KIIQ = cfg['motor_KIIQ']
motor_KPIQ = cfg['motor_KPIQ']
motor_KP = cfg['motor_KP']
motor_KD = cfg['motor_KD']
motor_encoder = cfg['motor_encoder']
joint_limit_negative = cfg['joint_limit_negative']
joint_limit_positive = cfg['joint_limit_positive']
master_position = cfg['master_position']
gear_ratio = cfg['gear_ratio']
gear_efficiency = cfg['gear_efficiency']
motor_offset = cfg['motor_offset']
motor_dir = cfg['motor_dir']
motor_signs = 1 - 2 * motor_dir # 0→1, 1→−1
gripper_name = cfg['gripper_name']
gripper_stroke = cfg['gripper_stroke']
gripper_kt = cfg['gripper_kt']
gripper_gear_r = cfg['gripper_gear_r']
gripper_Ilim = cfg['gripper_Ilim']
gripper_voltage_limit = cfg['gripper_voltage_limit'] # mV (0 = use VBUS)
gripper_velocity_limit = cfg['gripper_velocity_limit']
gripper_KPP = cfg['gripper_KPP']
gripper_KPV = cfg['gripper_KPV']
gripper_KIV = cfg['gripper_KIV']
gripper_KIIQ = cfg['gripper_KIIQ']
gripper_KPIQ = cfg['gripper_KPIQ']
gripper_KP = cfg['gripper_KP']
gripper_KD = cfg['gripper_KD']
delta_t = cfg['delta_t']
delta_t_RTI_joint = cfg['delta_t_RTI_joint']
safety_cfg = cfg['safety']
# Build homing controller from XML config
homing_ctrl = HomingController.from_config(cfg, joint_num)
# Raw XML objects kept for set_single_value / save_robot_config calls
_root_xml = cfg['_root']
_joints_xml = cfg['_joints']
_gripper_xml = cfg['_gripper_elem']
# ==========================================================================
# Setup Gripper
# ==========================================================================
name_of_the_gripper = cfg['gripper_name'] # read from system.xml -> grippers/<name>.xml
_can_raw = cfg['gripper_CAN_gripper']
active_CAN_gripper = 0 if (isinstance(_can_raw, float) and np.isnan(_can_raw)) else int(_can_raw)
# Write gripper control mode to shared memory (0=no gripper, 1=motor, 2=firmware)
_gripper_ctrl_mode = 0
if active_CAN_gripper == 1:
_gripper_ctrl_mode = 1 # default: motor mode
for _step in cfg.get('homing_sequence', []):
if _step.get('gripper_mode') is not None:
_gripper_ctrl_mode = 2 if _step['gripper_mode'] == 'firmware' else 1
break
shared_data.rti['gripper_ctrl_mode'][0] = _gripper_ctrl_mode
if active_CAN_gripper:
shared_data.gripper['gripper_gear_r'][0] = gripper_gear_r
# Firmware-mode gripper command state — updated by ZMQ "gripper_set:" commands
# from the GUI. Sent every tick by send_gripper_commands when
# gripper_ctrl_mode == 2 (activate is forced to 1 inside the sender).
# position/speed are 0–255, current is mA, action is 0/1.
_gripper_fw_state = {
'position': 0, 'speed': 100, 'current': 200,
'action': 0,
}
# Calibrate state machine. After Send_gripper_calibrate fires, the bus must be
# held with *empty* Send_gripper_data_pack() polls — resuming the full data
# pack mid-calibration cancels it. We don't try to auto-detect completion
# The user interrupts the state by clicking Open/Close/Goto/Stop, which aborts the calibration via the
# gripper_set handler. The hard timeout is a safety backstop only.
_gripper_calibrate_pending = False
_gripper_calibrate_running = False
_gripper_calibrate_ticks = 0
# Tracks the gripper CAN slot changing hands, so RTI can tell the firmware to release
# when homing gives it back. See the handover block in the superloop.
_gripper_was_owned = False
_GRIPPER_CALIBRATE_MAX_TICKS = max(1, round(30.0 / delta_t)) # safety timeout
# ==========================================================================
# Setup robot
# ==========================================================================
robot = create_robot(robot_name, gripper_name=name_of_the_gripper)
_kinematics_backend = os.environ.get("RTI_KINEMATICS_BACKEND", "auto").strip().lower()
set_kinematics_backend(_kinematics_backend)
if _kinematics_backend == "rtb":
logging.info("[Startup] Kinematics backend: robotics-toolbox")
else:
try:
attach_pinocchio(robot)
logging.info(f"[Startup] Kinematics backend: {_kinematics_backend} (Pinocchio attached)")
except Exception:
if _kinematics_backend == "pinocchio":
raise
logging.exception(
"[Startup] Pinocchio attach failed; falling back to robotics-toolbox kinematics"
)
# ==========================================================================
# ==========================================================================
# Start / Restart CAN interface when starting this script
# ==========================================================================
start_can_interface()
communication1 = initialize_can_communication(bustype='socketcan', channel='can0', bitrate=1000000)
# ==========================================================================
# Motor objects, joint objects, filters, housekeeping — via motor_setup.py
# ==========================================================================
xml_config = {
'motor_encoder': motor_encoder,
'master_position': master_position,
'gear_ratio': gear_ratio,
'motor_offset': motor_offset,
'motor_dir': motor_dir,
}
motor_system = setup_motor_system(joint_num, communication1, xml_config)
Motor = motor_system['Motor']
Joint = motor_system['Joint']
dummy_device = motor_system['dummy_device']
# Selectable per-signal, per-joint filters (config/filters.xml, hot-reloadable). Replaces the
# old hardcoded EMAs (joint_speed_filtered/alpha_Speed AND the TCP-accel EMA): joint_speed is now
# RAW with joint_speed_filtered from filter_banks['speed'], and Cartesian acceleration is filtered
# by filter_banks['tcp_accel']. The old motor_system['filters'] EMA-state arrays are left unused.
FILTER_CONFIG_PATH = CONFIG_DIR / "filters.xml"
filter_banks, _filter_src = load_filter_banks(FILTER_CONFIG_PATH, joint_num, delta_t)
logger.info(f"[filters] loaded from {_filter_src}: " +
", ".join(f"{s}={describe_bank(b)}" for s, b in filter_banks.items()))
received_ids = motor_system['housekeeping']['received_ids']
latest_commands_id = motor_system['housekeeping']['latest_commands_id']
node_error_bits = motor_system['housekeeping']['node_error_bits']
motor_error_bytes = motor_system['control']['motor_error_bytes']
startup_selfcheck = motor_system['housekeeping']['startup_selfcheck']
loop_execution_time = motor_system['housekeeping']['loop_execution_time']
command_success_rate = motor_system['housekeeping']['command_success_rate']
# Zero out shared memory housekeeping arrays
shared_data.rti["scan_received_ids"][:] = np.zeros(16, dtype=int)
shared_data.rti["CAN_node_connection_error"][:] = np.zeros(16, dtype=int)
shared_data.rti["old_data_warning"][:] = np.zeros(16, dtype=int)
shared_data.rti["homing_status"][:] = 0
shared_data.rti["joint_homed"][:] = 0
shared_data.rti["gravity_comp_enabled"][0] = 1.0
# ==========================================================================
# Data queue. Allows us to save previous x points of data for safety, filtering,
# ==========================================================================
# -1 index in deque is LATEST item and 0 is the OLDEST stored
# range(16) because our CAN bus can handle 16 unique CAN nodes (0 - 15)
# This one is critical data array that if not filled properly will cause errors
# Initialize all structures at once
robot_init_data = initialize_robot_data(joint_num)
Motor_data = robot_init_data["Motor_data"]
Gripper_data = robot_init_data["Gripper_data"]
Motor_temperature_data = robot_init_data["Motor_temperature_data"]
Motor_voltage_data = robot_init_data["Motor_voltage_data"]
Motor_errors_data = robot_init_data["Motor_errors_data"]
Motor_info_data = robot_init_data["Motor_info_data"]
Motor_Kt_data = robot_init_data["Motor_Kt_data"]
Joint_data = robot_init_data["Joint_data"]
System_data = robot_init_data["System_data"]
scheduled_state = {"step": 0,"joint_index": 0,"device_info_counter": 0}
# Optional override function (set externally when needed)
scheduled_override_queue = deque() # Each item is a tuple: (function, repeat_count)
current_override = {"fn": None,"count": 0}
# ==========================================================================
# Preload motor driver configs. NOTE this needs to be preloaded after
# Every fatal error or disconnect because motor drivers might lose this data
# Same goes for gripper configs if we have CAN gripper
# ==========================================================================
motor_watchdog_rate = cfg['motor_watchdog_rate']
gripper_watchdog_rate = int(cfg['gripper_watchdog_rate']) if active_CAN_gripper else 5000
# ==========================================================================
# Helpers that bundle load + write_to_shared for arm and gripper configs.
# Called at startup, at the tick-50/150/300 reconfig, and from the
# clear_errors / set_pid_gains command handlers.
# num_repeats DEFAULT stays 4 solely for the tick-50/150/300 reconfig block,
# which calls with no arguments and must not change (dirty fix for the
# exec-time-doubling bug). Every other caller passes num_repeats=2 explicitly.
# ==========================================================================
def _reload_motor_config(num_repeats=4, motor_index=None, pace_s=0.0):
load_motor_configs(Motor,
joint_num=joint_num, watchdog_rate=motor_watchdog_rate,
velocity_limit=motor_velocity_limit, current_limit=motor_Ilim,
KP=motor_KP, KD=motor_KD, KPIQ=motor_KPIQ, KIIQ=motor_KIIQ,
KPV=motor_KPV, KIV=motor_KIV, KPP=motor_KPP,
watchdog_action="Idle", num_repeats=num_repeats, motor_index=motor_index,
voltage_limit=motor_voltage_limit, pace_s=pace_s)
write_motor_config_to_shared(
shared_data, joint_num,
KPP=motor_KPP, KPV=motor_KPV, KIV=motor_KIV,
KPIQ=motor_KPIQ, KIIQ=motor_KIIQ, KP=motor_KP, KD=motor_KD,
Ilim=motor_Ilim, velocity_limit=motor_velocity_limit,
voltage_limit=motor_voltage_limit)
def _reload_gripper_config(num_repeats=4, pace_s=0.0):
if not active_CAN_gripper:
return
load_gripper_configs(Motor,
joint_num=joint_num, watchdog_rate=gripper_watchdog_rate,
velocity_limit=gripper_velocity_limit, current_limit=gripper_Ilim,
KP=gripper_KP, KD=gripper_KD, KPIQ=gripper_KPIQ, KIIQ=gripper_KIIQ,
KPV=gripper_KPV, KIV=gripper_KIV, KPP=gripper_KPP,
watchdog_action="Idle", num_repeats=num_repeats,
voltage_limit=gripper_voltage_limit, pace_s=pace_s)
write_gripper_config_to_shared(
shared_data,
KPP=gripper_KPP, KPV=gripper_KPV, KIV=gripper_KIV,
KPIQ=gripper_KPIQ, KIIQ=gripper_KIIQ, KP=gripper_KP, KD=gripper_KD,
Ilim=gripper_Ilim, velocity_limit=gripper_velocity_limit,
voltage_limit=gripper_voltage_limit)
# Boot-only TX pacing. The CAN library swallows send failures, so overflowing
# the socketcan TX queue (~270 frames of skb budget) silently DROPS frames.
# The boot blast is ~196 back-to-back frames — arm (168) then gripper (28) —
# enqueued in microseconds against a bus that drains ~10 frames/ms, and the
# gripper's watchdog arming rides the tail: exactly the frames that die when
# the queue tips over. 0.5 ms per message-type loop bounds the queue at ~a
# dozen frames for ~16 ms of one-time pre-loop boot cost. The in-loop reloads
# (reconnect, tick-50/150/300, PID apply) stay at pace_s=0 on purpose: a sleep
# there blows the 4 ms tick, their bursts are ≤28 frames (cannot overflow),
# and the full re-send passes are idempotent — a dropped tail cannot
# un-configure an already-armed node.
BOOT_CONFIG_PACE_S = 0.0005
_reload_motor_config(num_repeats=2, pace_s=BOOT_CONFIG_PACE_S)
# ==========================================================================
# Preload gripper data (If CAN gripper is active)
# ==========================================================================
_reload_gripper_config(num_repeats=2, pace_s=BOOT_CONFIG_PACE_S)
# ==========================================================================
# Kt fetch from CAN bus (or fall back to XML values)
# ==========================================================================
motor_kt, gripper_kt = resolve_and_preload_kt(
_sys, Motor, communication1, joint_num,
motor_kt, gripper_kt, active_CAN_gripper,
Motor_Kt_data, shared_data,
)
# ==========================================================================
# Initialize the timer before the loop starts
# ==========================================================================
prev_time = time.perf_counter()
shared_data.rti["loop_tick"][0] = 0
current_mode = RobotMode.BOOTING
pending_mode_request = None
# Set alongside pending_mode_request by "set_mode:<MODE>:PARKED|FORCE". Only
# maintenance modes (FLASHING) read these. There is no automatic test for "can
# this pose survive losing torque", so entry requires an explicit operator
# assertion; the assertion string is kept only so the log says which was made.
pending_mode_force = False
pending_mode_assertion = ""
shared_data.robot_mode.set(current_mode)
shared_data.robot_state.set("DISABLED")
shared_data.homed_state.set("NOT HOMED")
# Consume any flash marker left by a RUNTIME-DOWN flash. Starting RTI already
# clears homing (the line above), so the marker has done its job — leaving it on
# disk would fire on the next FLASHING exit and cost a re-home that nothing
# earned. Best-effort: a marker we cannot delete is a spurious re-home later,
# never a missed one.
try:
FLASH_PERFORMED_MARKER.unlink(missing_ok=True)
except OSError:
pass
shared_data.error_state.set_json("NONE")
shared_data.rti["error_active"][0] = 0
shared_data.rti["safety_violation"][0] = 0
shared_data.rti["software_estop"][0] = 0
# RTI-mode telemetry. These are only written while RobotMode.RTI is active, and shared
# memory survives an RTI.py restart — so without this, whatever the last session (or a
# test harness) left behind would sit in the GUI looking live, forever. Zeroed here so a
# fresh process always starts from "no PC paired".
shared_data.rti["rti_substate"][0] = 0
shared_data.rti["control_success_rate"][0] = 0
shared_data.rti["rti_consecutive_misses"][0] = 0
shared_data.rti["rti_worst_consecutive_misses"][0] = 0
shared_data.rti["rti_tx_bytes_per_s"][0] = 0
shared_data.rti["rti_rx_bytes_per_s"][0] = 0
shared_data.rti["rti_seq_rx_last"][0] = 0
shared_data.rti["rti_discard_pct"][0] = 0
startup_selfcheck = 0 # Flag to run startup selfcheck only once at startup
startup_motor_reconfig = 0 # Counts reconfiguration passes (0→1→2→3 = done)
# ==========================================================================
# Graceful shutdown — cleanup shared memory on exit / SIGTERM
# ==========================================================================
atexit.register(shared_data.cleanup)
def _handle_sigterm(_signum, _frame):
logging.info("[RTI] SIGTERM received — shutting down gracefully.")
shared_data.cleanup()
sys.exit(0)
signal.signal(signal.SIGTERM, _handle_sigterm)
# ==========================================================================
# Error tracking state — latched faults, metadata, clear countdown
# ==========================================================================
# Holds all errors that have appeared since the last user-requested clear.
# Errors only leave this set when the user calls "Clear Errors" from the GUI
# or sends the "clear_errors" ZMQ command.
latched_errors: set = set()
error_metadata: dict = {} # key → {"timestamp": float, "tick": int, "description": str, "level": str}
clear_error_countdown: int = 0 # counts down to 0 each time a clear is requested
# EXEC control-link watchdog (gui_executor_migration_plan.md Phase 5): trip if
# command_executor's heartbeat stops advancing while EXEC motion is in flight.
# Timeout must clear the ~20 ms heartbeat period plus scheduling jitter by a wide
# margin (a false trip disables a working arm), yet stay well under operator-
# confusion time. 0.5 s ≈ 25 missed heartbeats = unambiguously dead.
EXEC_LINK_TIMEOUT_S = 0.5
_exec_link_watchdog = ExecLinkWatchdog(max(1, int(round(EXEC_LINK_TIMEOUT_S / delta_t))))
# Rolling p95/p99 loop-timing window (see utility/signal_processing.py
# update_rolling_percentiles) — preallocated once, mutated in place every tick,
# so this stays a zero-allocation hot-path structure like everything else here.
LOOP_STATS_BUFFER_SIZE = 500 # ~2s of history at 250Hz (PAR6), ~5s at 100Hz
LOOP_STATS_INTERVAL = 50 # recompute p95/p99 every 50 ticks (~10us when it fires)
# Tick at which the "since start" peaks are auto-wiped a second time, so they
# describe STEADY STATE rather than boot. Must land after the last boot
# transient: startup_selfcheck (tick 8) and the multi-shot reconfig at ticks
# 50/150/300, whose 4 passes x 168 frames are the biggest bursts RTI ever sends.
# 350 clears tick 300 with ~50 ticks of slack. The discarded peaks are logged
# once before the wipe, so a pathological boot is still recorded in RTI.log.
LOOP_STATS_WARMUP_TICKS = 350
# [0]=worst, [1]=best CAN frame age this tick. Preallocated: the RX loop writes into it every
# tick, so it must not allocate.
_can_age_buf = np.zeros(2, dtype=np.float64)
_loop_period_buf = np.zeros(LOOP_STATS_BUFFER_SIZE, dtype=np.float64)
_loop_exec_buf = np.zeros(LOOP_STATS_BUFFER_SIZE, dtype=np.float64)
_loop_stats_buf_pos = 0
_loop_stats_buf_count = 0
# RT loop health monitor. Warmup is derived, not guessed: the peaks are wiped at
# LOOP_STATS_WARMUP_TICKS, and the rolling window then needs LOOP_STATS_BUFFER_SIZE
# more ticks to refill with post-boot samples before p99 describes anything real.
# Arming any earlier would trip on the boot transients the wipe exists to discard.
_loop_monitor = LoopDegradationMonitor(
delta_t=delta_t,
warmup_ticks=LOOP_STATS_WARMUP_TICKS + LOOP_STATS_BUFFER_SIZE,
)
# Per-node old_data_warning state from the previous tick — used to detect reconnect edges.
# Initialized to 0 so the first real stale→fresh transition fires correctly later.
_prev_old_data_warning = np.zeros(joint_num + 1, dtype=int)
# ==========================================================================
# Data recipe setup
# ==========================================================================
recipe_mgr = RecipeManager(DATA_RECIPE_DIR)
# Hoisted out of the RT loop — build once, references are stable.
# Passed to build_payload() every tick to route motor / motor-temp / motor-volt
# tags to the right per-node deque dict.
motor_buffers = {
"data": Motor_data,
"temperature": Motor_temperature_data,
"voltage": Motor_voltage_data,
"errors": Motor_errors_data,
"config": shared_data.motor_config,
}
# ==========================================================================
# Mode dispatch — build TickContext and MODE_HANDLERS once before the loop.
# TickContext fields point to existing objects (no copies). Only
# rti_udp_data and current_tick are reassigned per tick.
# ==========================================================================
ctx = TickContext(
Motor=Motor,
Joint=Joint,
joint_num=joint_num,
active_CAN_gripper=active_CAN_gripper,
shared_data=shared_data,
robot=robot,
delta_t=delta_t,
rti_udp_data=None,
socket_sender=RTI_socket_sender,
recipe=None,
Joint_data=Joint_data,
Gripper_data=Gripper_data,
current_tick=0,
motor_buffers=motor_buffers,
)
MODE_HANDLERS = build_mode_dispatch(
joint_num=joint_num,
homing_ctrl=homing_ctrl,
load_motor_configs_fn=load_motor_configs,
motor_config={
'velocity_limit': motor_velocity_limit,
'Ilim': motor_Ilim,
'KPP': motor_KPP, 'KP': motor_KP, 'KD': motor_KD,
'KPIQ': motor_KPIQ, 'KIIQ': motor_KIIQ,
'KPV': motor_KPV, 'KIV': motor_KIV,
},
jog_config={
'max_vel_rad': cfg['joint_velocity_limit'],
'delta_t': delta_t,
'limit_neg': cfg['software_joint_limit_negative'],
'limit_pos': cfg['software_joint_limit_positive'],
# XML defaults from config/system.xml::<jog_defaults>
'accel_time': _sys['jog_defaults']['accel_time'],
# Physical ceiling from the robot XML — jog's accel_time slider is a
# preference and must not be able to exceed it.
'accel_limit': cfg['joint_acceleration_limit'],
'profile': _sys['jog_defaults']['profile'],
'jerk_factor': _sys['jog_defaults']['jerk_factor'],
'control_mode': _sys['jog_defaults']['control_mode'],
'speed_pct': _sys['jog_defaults']['speed_pct'],
},
motor_dynamics={
'gear_ratio': gear_ratio,
'gear_efficiency': gear_efficiency,
'motor_kt': motor_kt,
'motor_signs': motor_signs,
},
shared_data=shared_data,
)
# RTI mode handler. Replaces the handle_idle placeholder build_mode_dispatch()
# installs for RobotMode.RTI. Module-level so the TCP command handlers below can
# drive its pairing lifecycle (connect_pc / claim_control / ...), which is separate
# from the enter(ctx)/exit(ctx) hooks dispatch calls on mode transitions.
rti_handler = RTIModeHandler(
joint_num=joint_num,
clock_mode=CLOCK_ROBOT,
delta_t=delta_t,
# Phase 2 rate-limiter budgets, from <rti_limits> per joint — RTI's own share of the
# hardware ceiling in <joint_*_limit>. Separate from EXEC's <exec_limits> so that opening
# a limit up to tune this limiter does not silently make every queued EXEC move punchier
# (which is exactly what happened on 2026-08-06).
# All four are optional in the robot XML at every level: a missing <rti_limits> falls back
# to the ceiling, and a missing ceiling gets a documented derivation from
# config/xml_parser.py — so these are never NaN. A NaN would silently disable clamping for
# that joint, since every comparison against it is False.
vel_limit=cfg['rti_velocity_limit'],
accel_limit=cfg['rti_acceleration_limit'],
jerk_limit=cfg['rti_jerk_limit'],
torque_rate_limit=cfg['rti_torque_rate_limit'],
# The soft joint limits. Already loaded and already handed to JogHandler — RTI simply
# never asked for them, so nothing bounded an RTI command to the workspace.
limit_neg=cfg['software_joint_limit_negative'],
limit_pos=cfg['software_joint_limit_positive'],
# RTI policy from <rti_defaults> in config/system.xml — see _parse_rti_defaults.
# Robot-INDEPENDENT tuning; the per-joint physical limits above come from the robot XML.
**{k: _sys['rti_defaults'][k] for k in (
'command_timeout_s', 'stopping_hold_s', 'start_pose_tol_rad',
'lowpass_cutoff_hz', 'success_window_ticks', 'success_warn', 'success_bad')},
)
MODE_HANDLERS[RobotMode.RTI] = rti_handler
# Maintenance policy from <maintenance_defaults> in config/system.xml.
flash_park_max_gravity_nm = _sys['maintenance_defaults']['flash_park_max_gravity_nm']
# IP of the PC currently paired over TCP. drain_rti_udp() filters on it so a
# stray sender cannot inject setpoints. None until rti_connect arrives, and the
# UDP read is skipped entirely while unpaired.
rti_pc_ip = None
# ==========================================================================
# RTI command dispatch — handlers for ZMQ commands (from command_executor,
# GUI, or Supervisor). Keyed by the first colon-delimited segment of the
# command string, e.g. "jog_set:2:1:0.5" dispatches on "jog_set". Handlers
# live here (not a separate module) because they mutate this file's own
# module-level state directly via `global` — the RT loop is a flat script,
# not a class, so this keeps the exact same data flow as before, just
# organized as one lookup table instead of a 130-line inline elif chain.
# Extracted 2026-07-03 — pure reorganization, identical logic per command,
# see TODO/exec_mode_implementation_checklist.md for the equivalence notes.
# ==========================================================================
def _handle_enable(cmd_msg, cmd_dict):
_errors_active = bool(shared_data.rti['error_active'][0])
_safety_active = bool(shared_data.rti['safety_violation'][0])
success, reason = request_enable(_errors_active, _safety_active)
if success:
shared_data.robot_state.set("ENABLED")
else:
shared_data.robot_state.set(f"ENABLE_REJECTED:{reason}")
def _handle_disable(cmd_msg, cmd_dict):
global pending_mode_request
shared_data.robot_state.set("DISABLED")
pending_mode_request = RobotMode.IDLE
def _handle_home(cmd_msg, cmd_dict):
global pending_mode_request
pending_mode_request = RobotMode.HOMING
def _handle_clear_errors(cmd_msg, cmd_dict):
global clear_error_countdown
send_clear_errors(shared_data, Motor, Motor_errors_data, joint_num, CLEAR_ERROR_SEND_REPEATS,
Gripper_data=Gripper_data, active_CAN_gripper=active_CAN_gripper)
clear_error_countdown = CLEAR_ERROR_SETTLE_TICKS
def _handle_gravity_comp(cmd_msg, cmd_dict):
# Guard added by the 2026-07-03 dispatch-table extraction: the old
# `elif cmd_msg.startswith("gravity_comp:")` guaranteed a colon before
# this branch was ever entered. A plain-string dispatch key doesn't, so
# this checks explicitly instead of indexing straight into parts[1].
parts = cmd_msg.split(":", 1)
if len(parts) != 2:
return
val = parts[1].strip()
new_val = 1.0 if val == "1" else 0.0
old_val = shared_data.rti['gravity_comp_enabled'][0]
shared_data.rti['gravity_comp_enabled'][0] = new_val
if new_val != old_val:
log_activity(_rti_activity_logger, "RTI", "info", "COMPENSATION_CHANGED",
message=f"gravity comp: {'ON' if new_val else 'OFF'}")
def _handle_set_mode(cmd_msg, cmd_dict):
global pending_mode_request, pending_mode_force, pending_mode_assertion
parts = cmd_msg.split(":") # see _handle_gravity_comp for why this is guarded
if len(parts) < 2:
return
pending_mode_request = parts[1].strip().upper()
# Maintenance modes need an EXPLICIT operator assertion — there is no
# automatic way to know the arm can survive going limp:
#
# set_mode:FLASHING -> refused, no assertion given
# set_mode:FLASHING:PARKED -> operator moved it to the park pose and confirmed
# set_mode:FLASHING:FORCE -> operator asserts it is supported WITHOUT parking
#
# PARKED and FORCE are equivalent to the gate; they are distinguished so the
# log records which claim was made. Replaces a gravity-torque threshold that
# could not do this job: PAR6's own standby pose measures 1.80 Nm against a
# shipped 1.0 Nm limit, so the correct answer failed the check (2026-08-05).
_assertion = parts[2].strip().upper() if len(parts) > 2 else ""
pending_mode_force = _assertion in ("PARKED", "FORCE")
pending_mode_assertion = _assertion
def _handle_jog_set(cmd_msg, cmd_dict):
parts = cmd_msg.split(":")
if len(parts) == 4 and current_mode == RobotMode.JOG:
_jog = MODE_HANDLERS.get(RobotMode.JOG)
if _jog is not None:
_jog.set_jog(int(parts[1]), int(parts[2]), float(parts[3]))
def _handle_jog_stop(cmd_msg, cmd_dict):
_jog = MODE_HANDLERS.get(RobotMode.JOG)
if _jog is not None:
_jog.stop_jog()
def _handle_jog_accel(cmd_msg, cmd_dict):
parts = cmd_msg.split(":")
if len(parts) == 2:
_jog = MODE_HANDLERS.get(RobotMode.JOG)
if _jog is not None:
_jog.set_accel_time(float(parts[1]))
def _handle_jog_profile(cmd_msg, cmd_dict):
parts = cmd_msg.split(":", 1)
if len(parts) == 2:
_jog = MODE_HANDLERS.get(RobotMode.JOG)
if _jog is not None:
try:
_jog.set_profile(parts[1].strip())
except ValueError as exc:
logger.warning("jog_profile: %s", exc)
def _handle_jog_jerk_factor(cmd_msg, cmd_dict):
parts = cmd_msg.split(":", 1)
if len(parts) == 2:
_jog = MODE_HANDLERS.get(RobotMode.JOG)
if _jog is not None:
_jog.set_jerk_factor(float(parts[1]))
def _handle_jog_control_mode(cmd_msg, cmd_dict):
parts = cmd_msg.split(":", 1)
if len(parts) == 2:
_jog = MODE_HANDLERS.get(RobotMode.JOG)
if _jog is not None:
try:
_jog.set_control_mode(parts[1].strip())
except ValueError as exc:
logger.warning("jog_control_mode: %s", exc)
def _handle_exec_pause(cmd_msg, cmd_dict):
_exec = MODE_HANDLERS.get(RobotMode.EXEC)
if _exec is not None:
_exec.pause()
def _handle_exec_resume(cmd_msg, cmd_dict):
_exec = MODE_HANDLERS.get(RobotMode.EXEC)
if _exec is not None:
_exec.resume()
def _handle_exec_completion_policy(cmd_msg, cmd_dict):
parts = cmd_msg.split(":", 1)
if len(parts) != 2:
return
_exec = MODE_HANDLERS.get(RobotMode.EXEC)
if _exec is not None:
try:
_exec.set_completion_policy(parts[1].strip())
except ValueError as exc:
logger.warning("exec_completion_policy: %s", exc)
def _handle_gripper_set(cmd_msg, cmd_dict):
# gripper_set:<position>:<speed>:<current>:<action>
# position/speed: 0–255, current: mA, action: 0/1.
# activate is always 1 in firmware mode (forced in send_gripper_commands).
# A new gripper_set also aborts any in-progress calibration —
# the user can see when the sweep is done, so an explicit
# Open/Close/Goto/Stop is the cancel signal.
global _gripper_calibrate_running, _gripper_calibrate_pending
parts = cmd_msg.split(":")
if len(parts) == 5 and active_CAN_gripper:
try:
_gripper_fw_state['position'] = int(parts[1])
_gripper_fw_state['speed'] = int(parts[2])
_gripper_fw_state['current'] = int(parts[3])
_gripper_fw_state['action'] = int(parts[4])
if _gripper_calibrate_running or _gripper_calibrate_pending:
logger.info("[Gripper] calibrate aborted by gripper_set")
_gripper_calibrate_running = False
_gripper_calibrate_pending = False
except ValueError as exc:
logger.warning("gripper_set: bad payload %s", exc)
def _handle_gripper_calibrate(cmd_msg, cmd_dict):
global _gripper_calibrate_pending
if active_CAN_gripper:
_gripper_calibrate_pending = True
def _handle_gripper_ctrl_mode(cmd_msg, cmd_dict):
# 1 = motor mode, 2 = firmware mode
parts = cmd_msg.split(":", 1) # see _handle_gravity_comp for why this is guarded
if len(parts) != 2 or not active_CAN_gripper:
return
try:
_new_mode = int(parts[1].strip())
if _new_mode in (1, 2):
shared_data.rti['gripper_ctrl_mode'][0] = _new_mode
# Stop any pending move when leaving firmware mode so the
# gripper sits still on the next firmware re-entry.
if _new_mode == 1:
_gripper_fw_state['action'] = 0
except ValueError as exc:
logger.warning("gripper_ctrl_mode: bad payload %s", exc)
def _handle_set_pid_gains(cmd_msg, cmd_dict):
global gripper_KPP, gripper_KPV, gripper_KIV, gripper_KPIQ, gripper_KIIQ
global gripper_KP, gripper_KD, gripper_Ilim, gripper_velocity_limit
global gripper_voltage_limit
_joint = int(cmd_dict.get("joint", -1))
if 0 <= _joint < joint_num:
if "KPP" in cmd_dict: motor_KPP[_joint] = float(cmd_dict["KPP"])
if "KPV" in cmd_dict: motor_KPV[_joint] = float(cmd_dict["KPV"])
if "KIV" in cmd_dict: motor_KIV[_joint] = float(cmd_dict["KIV"])
if "KPIQ" in cmd_dict: motor_KPIQ[_joint] = float(cmd_dict["KPIQ"])
if "KIIQ" in cmd_dict: motor_KIIQ[_joint] = float(cmd_dict["KIIQ"])
if "KP" in cmd_dict: motor_KP[_joint] = float(cmd_dict["KP"])
if "KD" in cmd_dict: motor_KD[_joint] = float(cmd_dict["KD"])
if "Ilim" in cmd_dict: motor_Ilim[_joint] = float(cmd_dict["Ilim"])
if "vel_lim" in cmd_dict: motor_velocity_limit[_joint] = float(cmd_dict["vel_lim"])
if "vlim" in cmd_dict: motor_voltage_limit[_joint] = read_XML2.clamp_voltage_limit(
cmd_dict["vlim"])
_reload_motor_config(num_repeats=2, motor_index=_joint)
elif _joint == joint_num and active_CAN_gripper:
if "KPP" in cmd_dict: gripper_KPP = float(cmd_dict["KPP"])
if "KPV" in cmd_dict: gripper_KPV = float(cmd_dict["KPV"])
if "KIV" in cmd_dict: gripper_KIV = float(cmd_dict["KIV"])
if "KPIQ" in cmd_dict: gripper_KPIQ = float(cmd_dict["KPIQ"])
if "KIIQ" in cmd_dict: gripper_KIIQ = float(cmd_dict["KIIQ"])
if "KP" in cmd_dict: gripper_KP = float(cmd_dict["KP"])