-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheadless_commander.py
More file actions
3611 lines (2995 loc) · 154 KB
/
Copy pathheadless_commander.py
File metadata and controls
3611 lines (2995 loc) · 154 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
'''
A full fledged "API" for the PAROL6 robot. To use this, you should pair it with the "robot_api.py" where you can import commands
from said file and use them anywhere within your code. This Python script will handle sending and performing all the commands
to the PAROL6 robot, as well as E-Stop functionality and safety limitations.
To run this program, you must use the "experimental-kinematics" branch of the "PAROL-commander-software" on GitHub
which can be found through this link: https://github.com/PCrnjak/PAROL-commander-software/tree/experimental_kinematics.
You must also save these files into the following folder: "Project Files\PAROL-commander-software\GUI\files".
'''
# * If you press estop robot will stop and you need to enable it by pressing e
from roboticstoolbox import DHRobot, RevoluteDH, ERobot, ELink, ETS, trapezoidal, quintic
import roboticstoolbox as rp
from math import pi, sin, cos
import numpy as np
from oclock import Timer, loop, interactiveloop
import time
import socket
from spatialmath import SE3
import select
import serial
import platform
import os
import re
import logging
import struct
import keyboard
from typing import Optional, Tuple
from spatialmath.base import trinterp
from collections import namedtuple, deque
import GUI.files.PAROL6_ROBOT as PAROL6_ROBOT
from smooth_motion import CircularMotion, SplineMotion, MotionBlender
# Set interval
INTERVAL_S = 0.01
prev_time = 0
logging.basicConfig(level = logging.DEBUG,
format='%(asctime)s.%(msecs)03d %(levelname)s:\t%(message)s',
datefmt='%H:%M:%S'
)
logging.disable(logging.DEBUG)
my_os = platform.system()
if my_os == "Windows":
# Try to read the COM port from a file
try:
with open("com_port.txt", "r") as f:
com_port_str = f.read().strip()
ser = serial.Serial(port=com_port_str, baudrate=3000000, timeout=0)
print(f"Connected to saved COM port: {com_port_str}")
except (FileNotFoundError, serial.SerialException):
# If the file doesn't exist or the port is invalid, ask the user
while True:
try:
com_port = input("Enter the COM port (e.g., COM9): ")
ser = serial.Serial(port=com_port, baudrate=3000000, timeout=0)
print(f"Successfully connected to {com_port}")
# Save the successful port to the file
with open("com_port.txt", "w") as f:
f.write(com_port)
break
except serial.SerialException:
print(f"Could not open port {com_port}. Please try again.")
# in big endian machines, first byte of binary representation of the multibyte data-type is stored first.
int_to_3_bytes = struct.Struct('>I').pack # BIG endian order
# data for output string (data that is being sent to the robot)
#######################################################################################
#######################################################################################
start_bytes = [0xff,0xff,0xff]
start_bytes = bytes(start_bytes)
end_bytes = [0x01,0x02]
end_bytes = bytes(end_bytes)
# data for input string (Data that is being sent by the robot)
#######################################################################################
#######################################################################################
input_byte = 0 # Here save incoming bytes from serial
start_cond1_byte = bytes([0xff])
start_cond2_byte = bytes([0xff])
start_cond3_byte = bytes([0xff])
end_cond1_byte = bytes([0x01])
end_cond2_byte = bytes([0x02])
start_cond1 = 0 #Flag if start_cond1_byte is received
start_cond2 = 0 #Flag if start_cond2_byte is received
start_cond3 = 0 #Flag if start_cond3_byte is received
good_start = 0 #Flag if we got all 3 start condition bytes
data_len = 0 #Length of the data after -3 start condition bytes and length byte, so -4 bytes
data_buffer = [None]*255 #Here save all data after data length byte
data_counter = 0 #Data counter for incoming bytes; compared to data length to see if we have correct length
#######################################################################################
#######################################################################################
prev_positions = [0,0,0,0,0,0]
prev_speed = [0,0,0,0,0,0]
robot_pose = [0,0,0,0,0,0] #np.array([0,0,0,0,0,0])
#######################################################################################
#######################################################################################
# --- Wrapper class to make integers mutable when passed to functions ---
class CommandValue:
def __init__(self, value):
self.value = value
#######################################################################################
#######################################################################################
Position_out = [1,11,111,1111,11111,10]
Speed_out = [2,21,22,23,24,25]
Command_out = CommandValue(255)
Affected_joint_out = [1,1,1,1,1,1,1,1]
InOut_out = [0,0,0,0,0,0,0,0]
Timeout_out = 0
#Positon,speed,current,command,mode,ID
Gripper_data_out = [1,1,1,1,0,0]
#######################################################################################
#######################################################################################
# Data sent from robot to PC
Position_in = [31,32,33,34,35,36]
Speed_in = [41,42,43,44,45,46]
Homed_in = [0,0,0,0,0,0,0,0]
InOut_in = [1,1,1,1,1,1,1,1]
Temperature_error_in = [1,1,1,1,1,1,1,1]
Position_error_in = [1,1,1,1,1,1,1,1]
Timeout_error = 0
# how much time passed between 2 sent commands (2byte value, last 2 digits are decimal so max value is 655.35ms?)
Timing_data_in = [0]
XTR_data = 0
# --- State variables for program execution ---
Robot_mode = "Dummy" # Start in an idle state
Program_step = 0 # Which line of the program to run
Command_step = 0 # The current step within a single command
Command_len = 0 # The total steps for the current command
ik_error = 0 # Flag for inverse kinematics errors
error_state = 0 # General error flag
program_running = False # A flag to start and stop the program
# This will be your "program"
command_list = []
#ID,Position,speed,current,status,obj_detection
Gripper_data_in = [1,1,1,1,1,1]
# Global variable to track previous tolerance for logging changes
_prev_tolerance = None
def normalize_angle(angle):
"""Normalize angle to [-pi, pi] range to handle angle wrapping"""
while angle > np.pi:
angle -= 2 * np.pi
while angle < -np.pi:
angle += 2 * np.pi
return angle
def unwrap_angles(q_solution, q_current):
"""
Unwrap angles in the solution to be closest to current position.
This handles the angle wrapping issue where -179° and 181° are close but appear far.
"""
q_unwrapped = q_solution.copy()
for i in range(len(q_solution)):
# Calculate the difference
diff = q_solution[i] - q_current[i]
# If the difference is more than pi, we need to unwrap
if diff > np.pi:
# Solution is too far in positive direction, subtract 2*pi
q_unwrapped[i] = q_solution[i] - 2 * np.pi
elif diff < -np.pi:
# Solution is too far in negative direction, add 2*pi
q_unwrapped[i] = q_solution[i] + 2 * np.pi
return q_unwrapped
IKResult = namedtuple('IKResult', 'success q iterations residual tolerance_used violations')
def calculate_adaptive_tolerance(robot, q, strict_tol=1e-10, loose_tol=1e-7):
"""
Calculate adaptive tolerance based on proximity to singularities.
Near singularities: looser tolerance for easier convergence.
Away from singularities: stricter tolerance for precise solutions.
Parameters
----------
robot : DHRobot
Robot model
q : array_like
Joint configuration
strict_tol : float
Strict tolerance away from singularities (default: 1e-10)
loose_tol : float
Loose tolerance near singularities (1e-7)
Returns
-------
float
Adaptive tolerance value
"""
global _prev_tolerance
q_array = np.array(q, dtype=float)
# Calculate manipulability measure (closer to 0 = closer to singularity)
manip = robot.manipulability(q_array)
singularity_threshold = 0.001
sing_normalized = np.clip(manip / singularity_threshold, 0.0, 1.0)
adaptive_tol = loose_tol + (strict_tol - loose_tol) * sing_normalized
# Log tolerance changes (only log significant changes to avoid spam)
if _prev_tolerance is None or abs(adaptive_tol - _prev_tolerance) / _prev_tolerance > 0.5:
tol_category = "LOOSE" if adaptive_tol > 1e-7 else "MODERATE" if adaptive_tol > 5e-10 else "STRICT"
print(f"Adaptive IK tolerance: {adaptive_tol:.2e} ({tol_category}) - Manipulability: {manip:.8f} (threshold: {singularity_threshold})")
_prev_tolerance = adaptive_tol
return adaptive_tol
def calculate_configuration_dependent_max_reach(q_seed):
"""
Calculate maximum reach based on joint configuration, particularly joint 5.
When joint 5 is at 90 degrees, the effective reach is reduced by approximately 0.045.
Parameters
----------
q_seed : array_like
Current joint configuration in radians
Returns
-------
float
Configuration-dependent maximum reach threshold
"""
base_max_reach = 0.44 # Base maximum reach from experimentation
j5_angle = q_seed[4] if len(q_seed) > 4 else 0.0
j5_normalized = normalize_angle(j5_angle)
angle_90_deg = np.pi / 2
angle_neg_90_deg = -np.pi / 2
dist_from_90 = abs(j5_normalized - angle_90_deg)
dist_from_neg_90 = abs(j5_normalized - angle_neg_90_deg)
dist_from_90_deg = min(dist_from_90, dist_from_neg_90)
reduction_range = np.pi / 4 # 45 degrees
if dist_from_90_deg <= reduction_range:
# Calculate reduction factor based on proximity to 90°
proximity_factor = 1.0 - (dist_from_90_deg / reduction_range)
reach_reduction = 0.045 * proximity_factor
effective_max_reach = base_max_reach - reach_reduction
return effective_max_reach
else:
return base_max_reach
def solve_ik_with_adaptive_tol_subdivision(
robot: DHRobot,
target_pose: SE3,
current_q,
current_pose: SE3 | None = None,
max_depth: int = 4,
ilimit: int = 100,
jogging: bool = False
):
"""
Uses adaptive tolerance based on proximity to singularities:
- Near singularities: looser tolerance for easier convergence
- Away from singularities: stricter tolerance for precise solutions
If necessary, recursively subdivide the motion until ikine_LM converges
on every segment. Finally check that solution respects joint limits. From experimentation,
jogging with lower tolerances often produces q_paths that do not differ from current_q,
essentially freezing the robot.
Parameters
----------
robot : DHRobot
Robot model
target_pose : SE3
Target pose to reach
current_q : array_like
Current joint configuration
current_pose : SE3, optional
Current pose (computed if None)
max_depth : int, optional
Maximum subdivision depth (default: 8)
ilimit : int, optional
Maximum iterations for IK solver (default: 100)
Returns
-------
IKResult
success - True/False
q_path - (mxn) array of the final joint configuration
iterations, residual - aggregated diagnostics
tolerance_used - which tolerance was used
violations - joint limit violations (if any)
"""
if current_pose is None:
current_pose = robot.fkine(current_q)
# ── inner recursive solver───────────────────
def _solve(Ta: SE3, Tb: SE3, q_seed, depth, tol):
"""Return (path_list, success_flag, iterations, residual)."""
# Calculate current and target reach
current_reach = np.linalg.norm(Ta.t)
target_reach = np.linalg.norm(Tb.t)
# Check if this is an inward movement (recovery)
is_recovery = target_reach < current_reach
# Calculate configuration-dependent maximum reach based on joint 5 position
max_reach_threshold = calculate_configuration_dependent_max_reach(q_seed)
# Determine damping based on reach and movement direction
if is_recovery:
# Recovery mode - always use low damping
damping = 0.0000001
else:
# Check if we're near configuration-dependent max reach
# print(f"current_reach:{current_reach:.3f}, max_reach_threshold:{max_reach_threshold:.3f}")
if not is_recovery and target_reach > max_reach_threshold:
print(f"Target reach limit exceeded: {target_reach:.3f} > {max_reach_threshold:.3f}")
return [], False, depth, 0
else:
damping = 0.0000001 # Normal low damping
res = robot.ikine_LM(Tb, q0=q_seed, ilimit=ilimit, tol=tol)
if res.success:
q_good = unwrap_angles(res.q, q_seed) # << unwrap vs *previous*
return [q_good], True, res.iterations, res.residual
if depth >= max_depth:
return [], False, res.iterations, res.residual
# split the segment and recurse
Tc = SE3(trinterp(Ta.A, Tb.A, 0.5)) # mid-pose (screw interp)
left_path, ok_L, it_L, r_L = _solve(Ta, Tc, q_seed, depth+1, tol)
if not ok_L:
return [], False, it_L, r_L
q_mid = left_path[-1] # last solved joint set
right_path, ok_R, it_R, r_R = _solve(Tc, Tb, q_mid, depth+1, tol)
return (
left_path + right_path,
ok_R,
it_L + it_R,
r_R
)
# ── kick-off with adaptive tolerance ──────────────────────────────────
if jogging:
adaptive_tol = 1e-10
else:
adaptive_tol = calculate_adaptive_tolerance(robot, current_q)
path, ok, its, resid = _solve(current_pose, target_pose, current_q, 0, adaptive_tol)
# Check if solution respects joint limits
target_q = path[-1] if len(path) != 0 else None
solution_valid, violations = PAROL6_ROBOT.check_joint_limits(current_q, target_q)
if ok and solution_valid:
return IKResult(True, path[-1], its, resid, adaptive_tol, violations)
else:
return IKResult(False, None, its, resid, adaptive_tol, violations)
#Setup IP address and Simulator port
ip = "0.0.0.0" #Loopback address
port = 5001
# Create a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((ip, port))
print(f'Start listening to {ip}:{port}')
def Unpack_data(data_buffer_list, Position_in,Speed_in,Homed_in,InOut_in,Temperature_error_in,Position_error_in,Timeout_error,Timing_data_in,
XTR_data,Gripper_data_in):
Joints = []
Speed = []
for i in range(0,18, 3):
variable = data_buffer_list[i:i+3]
Joints.append(variable)
for i in range(18,36, 3):
variable = data_buffer_list[i:i+3]
Speed.append(variable)
for i in range(6):
var = b'\x00' + b''.join(Joints[i])
Position_in[i] = Fuse_3_bytes(var)
var = b'\x00' + b''.join(Speed[i])
Speed_in[i] = Fuse_3_bytes(var)
Homed = data_buffer_list[36]
IO_var = data_buffer_list[37]
temp_error = data_buffer_list[38]
position_error = data_buffer_list[39]
timing_data = data_buffer_list[40:42]
Timeout_error_var = data_buffer_list[42]
xtr2 = data_buffer_list[43]
device_ID = data_buffer_list[44]
Gripper_position = data_buffer_list[45:47]
Gripper_speed = data_buffer_list[47:49]
Gripper_current = data_buffer_list[49:51]
Status = data_buffer_list[51]
# The original object_detection byte at index 52 is ignored as it is not reliable.
CRC_byte = data_buffer_list[53]
endy_byte1 = data_buffer_list[54]
endy_byte2 = data_buffer_list[55]
# ... (Code for Homed, IO_var, temp_error, etc. remains the same) ...
temp = Split_2_bitfield(int.from_bytes(Homed,"big"))
for i in range(8):
Homed_in[i] = temp[i]
temp = Split_2_bitfield(int.from_bytes(IO_var,"big"))
for i in range(8):
InOut_in[i] = temp[i]
temp = Split_2_bitfield(int.from_bytes(temp_error,"big"))
for i in range(8):
Temperature_error_in[i] = temp[i]
temp = Split_2_bitfield(int.from_bytes(position_error,"big"))
for i in range(8):
Position_error_in[i] = temp[i]
var = b'\x00' + b'\x00' + b''.join(timing_data)
Timing_data_in[0] = Fuse_3_bytes(var)
Timeout_error = int.from_bytes(Timeout_error_var,"big")
XTR_data = int.from_bytes(xtr2,"big")
# --- Gripper Data Unpacking ---
Gripper_data_in[0] = int.from_bytes(device_ID,"big")
var = b'\x00'+ b'\x00' + b''.join(Gripper_position)
Gripper_data_in[1] = Fuse_2_bytes(var)
var = b'\x00'+ b'\x00' + b''.join(Gripper_speed)
Gripper_data_in[2] = Fuse_2_bytes(var)
var = b'\x00'+ b'\x00' + b''.join(Gripper_current)
Gripper_data_in[3] = Fuse_2_bytes(var)
# --- Start of Corrected Logic ---
# This section now mirrors the working logic from GUI_PAROL_latest.py
# 1. Store the raw status byte (from index 51)
status_byte = int.from_bytes(Status,"big")
Gripper_data_in[4] = status_byte
# 2. Split the status byte into a list of 8 individual bits
status_bits = Split_2_bitfield(status_byte)
# 3. Combine the 3rd and 4th bits (at indices 2 and 3) to get the true object detection status
# This creates a 2-bit number (0-3) which represents the full state.
object_detection_status = (status_bits[2] << 1) | status_bits[3]
Gripper_data_in[5] = object_detection_status
# --- End of Corrected Logic ---
def Pack_data(Position_out,Speed_out,Command_out,Affected_joint_out,InOut_out,Timeout_out,Gripper_data_out):
# Len is defined by all bytes EXCEPT start bytes and len
# Start bytes = 3
len = 52 #1
Position = [Position_out[0],Position_out[1],Position_out[2],Position_out[3],Position_out[4],Position_out[5]] #18
Speed = [Speed_out[0], Speed_out[1], Speed_out[2], Speed_out[3], Speed_out[4], Speed_out[5],] #18
Command = Command_out#1
Affected_joint = Affected_joint_out
InOut = InOut_out #1
Timeout = Timeout_out #1
Gripper_data = Gripper_data_out #9
CRC_byte = 228 #1
# End bytes = 2
test_list = []
#print(test_list)
#x = bytes(start_bytes)
test_list.append((start_bytes))
test_list.append(bytes([len]))
# Position data
for i in range(6):
position_split = Split_2_3_bytes(Position[i])
test_list.append(position_split[1:4])
# Speed data
for i in range(6):
speed_split = Split_2_3_bytes(Speed[i])
test_list.append(speed_split[1:4])
# Command data
test_list.append(bytes([Command]))
# Affected joint data
Affected_list = Fuse_bitfield_2_bytearray(Affected_joint[:])
test_list.append(Affected_list)
# Inputs outputs data
InOut_list = Fuse_bitfield_2_bytearray(InOut[:])
test_list.append(InOut_list)
# Timeout data
test_list.append(bytes([Timeout]))
# Gripper position
Gripper_position = Split_2_3_bytes(Gripper_data[0])
test_list.append(Gripper_position[2:4])
# Gripper speed
Gripper_speed = Split_2_3_bytes(Gripper_data[1])
test_list.append(Gripper_speed[2:4])
# Gripper current
Gripper_current = Split_2_3_bytes(Gripper_data[2])
test_list.append(Gripper_current[2:4])
# Gripper command
test_list.append(bytes([Gripper_data[3]]))
# Gripper mode
test_list.append(bytes([Gripper_data[4]]))
# ==========================================================
# === FIX: Make sure calibrate is a one-shot command ====
# ==========================================================
# If the mode was set to calibrate (1) or clear_error (2), reset it
# back to normal (0) for the next cycle. This prevents an endless loop.
if Gripper_data_out[4] == 1 or Gripper_data_out[4] == 2:
Gripper_data_out[4] = 0
# ==========================================================
# Gripper ID
test_list.append(bytes([Gripper_data[5]]))
# CRC byte
test_list.append(bytes([CRC_byte]))
# END bytes
test_list.append((end_bytes))
#print(test_list)
return test_list
def Get_data(Position_in,Speed_in,Homed_in,InOut_in,Temperature_error_in,Position_error_in,Timeout_error,Timing_data_in,
XTR_data,Gripper_data_in):
global input_byte
global start_cond1_byte
global start_cond2_byte
global start_cond3_byte
global end_cond1_byte
global end_cond2_byte
global start_cond1
global start_cond2
global start_cond3
global good_start
global data_len
global data_buffer
global data_counter
while (ser.inWaiting() > 0):
input_byte = ser.read()
#UNCOMMENT THIS TO GET ALL DATA FROM THE ROBOT PRINTED
#print(input_byte)
# When data len is received start is good and after that put all data in receive buffer
# Data len is ALL data after it; that includes input buffer, end bytes and CRC
if (good_start != 1):
# All start bytes are good and next byte is data len
if (start_cond1 == 1 and start_cond2 == 1 and start_cond3 == 1):
good_start = 1
data_len = input_byte
data_len = struct.unpack('B', data_len)[0]
logging.debug("data len we got from robot packet= ")
logging.debug(input_byte)
logging.debug("good start for DATA that we received at PC")
# Third start byte is good
if (input_byte == start_cond3_byte and start_cond2 == 1 and start_cond1 == 1):
start_cond3 = 1
#print("good cond 3 PC")
#Third start byte is bad, reset all flags
elif (start_cond2 == 1 and start_cond1 == 1):
#print("bad cond 3 PC")
start_cond1 = 0
start_cond2 = 0
# Second start byte is good
if (input_byte == start_cond2_byte and start_cond1 == 1):
start_cond2 = 1
#print("good cond 2 PC ")
#Second start byte is bad, reset all flags
elif (start_cond1 == 1):
#print("Bad cond 2 PC")
start_cond1 = 0
# First start byte is good
if (input_byte == start_cond1_byte):
start_cond1 = 1
#print("good cond 1 PC")
else:
# Here data goes after good start
data_buffer[data_counter] = input_byte
if (data_counter == data_len - 1):
logging.debug("Data len PC")
logging.debug(data_len)
logging.debug("End bytes are:")
logging.debug(data_buffer[data_len -1])
logging.debug(data_buffer[data_len -2])
# Here if last 2 bytes are end condition bytes we process the data
if (data_buffer[data_len -1] == end_cond2_byte and data_buffer[data_len - 2] == end_cond1_byte):
logging.debug("GOOD END CONDITION PC")
logging.debug("I UNPACKED RAW DATA RECEIVED FROM THE ROBOT")
Unpack_data(data_buffer, Position_in,Speed_in,Homed_in,InOut_in,Temperature_error_in,Position_error_in,Timeout_error,Timing_data_in,
XTR_data,Gripper_data_in)
logging.debug("DATA UNPACK FINISHED")
# ako su dobri izračunaj crc
# if crc dobar raspakiraj podatke
# ako je dobar paket je dobar i spremi ga u nove variable!
# Print every byte
#print("podaci u data bufferu su:")
#for i in range(data_len):
#print(data_buffer[i])
good_start = 0
start_cond1 = 0
start_cond3 = 0
start_cond2 = 0
data_len = 0
data_counter = 0
else:
data_counter = data_counter + 1
# Split data to 3 bytes
def Split_2_3_bytes(var_in):
y = int_to_3_bytes(var_in & 0xFFFFFF) # converts my int value to bytes array
return y
# Splits byte to bitfield list
def Split_2_bitfield(var_in):
#return [var_in >> i & 1 for i in range(7,-1,-1)]
return [(var_in >> i) & 1 for i in range(7, -1, -1)]
# Fuses 3 bytes to 1 signed int
def Fuse_3_bytes(var_in):
value = struct.unpack(">I", bytearray(var_in))[0] # converts bytes array to int
# convert to negative number if it is negative
if value >= 1<<23:
value -= 1<<24
return value
# Fuses 2 bytes to 1 signed int
def Fuse_2_bytes(var_in):
value = struct.unpack(">I", bytearray(var_in))[0] # converts bytes array to int
# convert to negative number if it is negative
if value >= 1<<15:
value -= 1<<16
return value
# Fuse bitfield list to byte
def Fuse_bitfield_2_bytearray(var_in):
number = 0
for b in var_in:
number = (2 * number) + b
return bytes([number])
# Check if there is element 1 in the list.
# If yes return its index, if no element is 1 return -1
def check_elements(lst):
for i, element in enumerate(lst):
if element == 1:
return i
return -1 # Return -1 if no element is 1
def quintic_scaling(s: float) -> float:
"""
Calculates a smooth 0-to-1 scaling factor for progress 's'
using a quintic polynomial, ensuring smooth start/end accelerations.
"""
return 6 * (s**5) - 15 * (s**4) + 10 * (s**3)
#########################################################################
# Robot Commands Start Here
#########################################################################
class HomeCommand:
"""
A non-blocking command that tells the robot to perform its internal homing sequence.
This version uses a state machine to allow re-homing even if the robot is already homed.
"""
def __init__(self):
self.is_valid = True
self.is_finished = False
# State machine: START -> WAIT_FOR_UNHOMED -> WAIT_FOR_HOMED -> FINISHED
self.state = "START"
# Counter to send the home command for multiple cycles
self.start_cmd_counter = 10 # Send command 100 for 10 cycles (0.1s)
# Safety timeout (20 seconds at 0.01s interval)
self.timeout_counter = 2000
print("Initializing Home command...")
def execute_step(self, Position_in, Homed_in, Speed_out, Command_out, **kwargs):
"""
Manages the homing command and monitors for completion using a state machine.
"""
if self.is_finished:
return True
# --- State: START ---
# On the first few executions, continuously send the 'home' (100) command.
if self.state == "START":
print(f" -> Sending home signal (100)... Countdown: {self.start_cmd_counter}")
Command_out.value = 100
self.start_cmd_counter -= 1
if self.start_cmd_counter <= 0:
# Once sent for enough cycles, move to the next state
self.state = "WAITING_FOR_UNHOMED"
return False
# --- State: WAITING_FOR_UNHOMED ---
# The robot's firmware should reset the homed status. We wait to see that happen.
# During this time, we send 'idle' (255) to let the robot's controller take over.
if self.state == "WAITING_FOR_UNHOMED":
Command_out.value = 255
# Check if at least one joint has started homing (is no longer homed)
if any(h == 0 for h in Homed_in[:6]):
print(" -> Homing sequence initiated by robot.")
self.state = "WAITING_FOR_HOMED"
# Check for timeout
self.timeout_counter -= 1
if self.timeout_counter <= 0:
print(" -> ERROR: Timeout waiting for robot to start homing sequence.")
self.is_finished = True
return self.is_finished
# --- State: WAITING_FOR_HOMED ---
# Now we wait for all joints to report that they are homed (all flags are 1).
if self.state == "WAITING_FOR_HOMED":
Command_out.value = 255
# Check if all joints have finished homing
if all(h == 1 for h in Homed_in[:6]):
print("Homing sequence complete. All joints reported home.")
self.is_finished = True
Speed_out[:] = [0] * 6 # Ensure robot is stopped
return self.is_finished
class JogCommand:
"""
A non-blocking command to jog a joint for a specific duration or distance.
It performs all safety and validity checks upon initialization.
"""
def __init__(self, joint, speed_percentage=None, duration=None, distance_deg=None):
"""
Initializes and validates the jog command. This is the SETUP phase.
"""
self.is_valid = False
self.is_finished = False
self.mode = None
self.command_step = 0
# --- 1. Parameter Validation and Mode Selection ---
if duration and distance_deg:
self.mode = 'distance'
print(f"Initializing Jog: Joint {joint}, Distance {distance_deg} deg, Duration {duration}s.")
elif duration:
self.mode = 'time'
print(f"Initializing Jog: Joint {joint}, Speed {speed_percentage}%, Duration {duration}s.")
elif distance_deg:
self.mode = 'distance'
print(f"Initializing Jog: Joint {joint}, Speed {speed_percentage}%, Distance {distance_deg} deg.")
else:
print("Error: JogCommand requires either 'duration', 'distance_deg', or both.")
return
# --- 2. Store parameters for deferred calculation ---
self.joint = joint
self.speed_percentage = speed_percentage
self.duration = duration
self.distance_deg = distance_deg
# --- These will be calculated later ---
self.direction = 1
self.joint_index = 0
self.speed_out = 0
self.command_len = 0
self.target_position = 0
self.is_valid = True # Mark as valid for now; preparation step will confirm.
def prepare_for_execution(self, current_position_in):
"""Pre-computes speeds and target positions using live data."""
print(f" -> Preparing for Jog command...")
# Determine direction and joint index
self.direction = 1 if 0 <= self.joint <= 5 else -1
self.joint_index = self.joint if self.direction == 1 else self.joint - 6
distance_steps = 0
if self.distance_deg:
distance_steps = int(PAROL6_ROBOT.DEG2STEPS(abs(self.distance_deg), self.joint_index))
# --- MOVED LOGIC: Calculate target using the LIVE position ---
self.target_position = current_position_in[self.joint_index] + (distance_steps * self.direction)
min_limit, max_limit = PAROL6_ROBOT.Joint_limits_steps[self.joint_index]
if not (min_limit <= self.target_position <= max_limit):
print(f" -> VALIDATION FAILED: Target position {self.target_position} is out of joint limits ({min_limit}, {max_limit}).")
self.is_valid = False
return
# Calculate speed and duration
speed_steps_per_sec = 0
if self.mode == 'distance' and self.duration:
speed_steps_per_sec = int(distance_steps / self.duration) if self.duration > 0 else 0
max_joint_speed = PAROL6_ROBOT.Joint_max_speed[self.joint_index]
if speed_steps_per_sec > max_joint_speed:
print(f" -> VALIDATION FAILED: Required speed ({speed_steps_per_sec} steps/s) exceeds joint's max speed ({max_joint_speed} steps/s).")
self.is_valid = False
return
else:
if self.speed_percentage is None:
print("Error: 'speed_percentage' must be provided if not calculating automatically.")
self.is_valid = False
return
speed_steps_per_sec = int(np.interp(abs(self.speed_percentage), [0, 100], [0, PAROL6_ROBOT.Joint_max_speed[self.joint_index] * 2]))
self.speed_out = speed_steps_per_sec * self.direction
self.command_len = int(self.duration / INTERVAL_S) if self.duration else float('inf')
print(" -> Jog command is ready.")
def execute_step(self, Position_in, Homed_in, Speed_out, Command_out, **kwargs):
"""This is the EXECUTION phase. It runs on every loop cycle."""
if self.is_finished or not self.is_valid:
return True
stop_reason = None
current_pos = Position_in[self.joint_index]
if self.mode == 'time':
if self.command_step >= self.command_len:
stop_reason = "Timed jog finished."
elif self.mode == 'distance':
if (self.direction == 1 and current_pos >= self.target_position) or \
(self.direction == -1 and current_pos <= self.target_position):
stop_reason = "Distance jog finished."
if not stop_reason:
if (self.direction == 1 and current_pos >= PAROL6_ROBOT.Joint_limits_steps[self.joint_index][1]) or \
(self.direction == -1 and current_pos <= PAROL6_ROBOT.Joint_limits_steps[self.joint_index][0]):
stop_reason = f"Limit reached on joint {self.joint_index + 1}."
if stop_reason:
print(stop_reason)
self.is_finished = True
Speed_out[:] = [0] * 6
Command_out.value = 255
return True
else:
Speed_out[:] = [0] * 6
Speed_out[self.joint_index] = self.speed_out
Command_out.value = 123
self.command_step += 1
return False
class MultiJogCommand:
"""
A non-blocking command to jog multiple joints simultaneously for a specific duration.
It performs all safety and validity checks upon initialization.
"""
def __init__(self, joints, speed_percentages, duration):
"""
Initializes and validates the multi-jog command.
"""
self.is_valid = False
self.is_finished = False
self.command_step = 0
# --- 1. Parameter Validation ---
if not isinstance(joints, list) or not isinstance(speed_percentages, list):
print("Error: MultiJogCommand requires 'joints' and 'speed_percentages' to be lists.")
return
if len(joints) != len(speed_percentages):
print("Error: The number of joints must match the number of speed percentages.")
return
if not duration or duration <= 0:
print("Error: MultiJogCommand requires a positive 'duration'.")
return
# ==========================================================
# === NEW: Check for conflicting joint commands ===
# ==========================================================
base_joints = set()
for joint in joints:
# Normalize the joint index to its base (0-5)
base_joint = joint % 6
# If the base joint is already in our set, it's a conflict.
if base_joint in base_joints:
print(f" -> VALIDATION FAILED: Conflicting commands for Joint {base_joint + 1} (e.g., J1+ and J1-).")
self.is_valid = False
return
base_joints.add(base_joint)
# ==========================================================
print(f"Initializing MultiJog for joints {joints} with speeds {speed_percentages}% for {duration}s.")
# --- 2. Store parameters ---
self.joints = joints
self.speed_percentages = speed_percentages
self.duration = duration
self.command_len = int(self.duration / INTERVAL_S)
# --- This will be calculated in the prepare step ---
self.speeds_out = [0] * 6
self.is_valid = True
def prepare_for_execution(self, current_position_in):
"""Pre-computes the speeds for each joint."""
print(f" -> Preparing for MultiJog command...")
for i, joint in enumerate(self.joints):
# Determine direction and joint index (0-5 for positive, 6-11 for negative)
direction = 1 if 0 <= joint <= 5 else -1
joint_index = joint if direction == 1 else joint - 6
speed_percentage = self.speed_percentages[i]
# Check for joint index validity
if not (0 <= joint_index < 6):
print(f" -> VALIDATION FAILED: Invalid joint index {joint_index}.")
self.is_valid = False
return
# Calculate speed in steps/sec
speed_steps_per_sec = int(np.interp(speed_percentage, [0, 100], [0, PAROL6_ROBOT.Joint_max_speed[joint_index]]))
self.speeds_out[joint_index] = speed_steps_per_sec * direction
print(" -> MultiJog command is ready.")
def execute_step(self, Position_in, Homed_in, Speed_out, Command_out, **kwargs):
"""This is the EXECUTION phase. It runs on every loop cycle."""
if self.is_finished or not self.is_valid:
return True
# Stop if the duration has elapsed
if self.command_step >= self.command_len:
print("Timed multi-jog finished.")
self.is_finished = True
Speed_out[:] = [0] * 6
Command_out.value = 255
return True
else:
# Continuously check for joint limits during the jog
for i in range(6):
if self.speeds_out[i] != 0:
current_pos = Position_in[i]
# Hitting positive limit while moving positively
if self.speeds_out[i] > 0 and current_pos >= PAROL6_ROBOT.Joint_limits_steps[i][1]:
print(f"Limit reached on joint {i + 1}. Stopping jog.")
self.is_finished = True
Speed_out[:] = [0] * 6
Command_out.value = 255
return True
# Hitting negative limit while moving negatively
elif self.speeds_out[i] < 0 and current_pos <= PAROL6_ROBOT.Joint_limits_steps[i][0]:
print(f"Limit reached on joint {i + 1}. Stopping jog.")
self.is_finished = True
Speed_out[:] = [0] * 6
Command_out.value = 255
return True
# If no limits are hit, apply the speeds
Speed_out[:] = self.speeds_out