-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrobot_api.py
More file actions
1477 lines (1246 loc) · 54.3 KB
/
Copy pathrobot_api.py
File metadata and controls
1477 lines (1246 loc) · 54.3 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
"""
Zero-Overhead Robot API with Optional Acknowledgments
======================================================
This version guarantees ZERO resource overhead when tracking is not used.
The tracking system is only initialized when explicitly requested.
"""
import socket
from typing import List, Optional, Literal, Dict, Tuple, Union
import time
import threading
import queue
import uuid
from collections import deque
from datetime import datetime, timedelta
# Global configuration
SERVER_IP = "192.168.1.2"
SERVER_PORT = 5001
# Global tracker - starts as None (no resources)
_command_tracker = None
_tracker_lock = threading.Lock()
# ============================================================================
# ORIGINAL SEND FUNCTION - ZERO OVERHEAD
# ============================================================================
def send_robot_command(command_string: str):
"""
Original send function - NO TRACKING, NO OVERHEAD.
This is what gets called for all backward-compatible operations.
Resource usage:
- No threads
- No extra sockets
- No memory allocation
- Exactly the same as your original implementation
"""
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.sendto(command_string.encode('utf-8'), (SERVER_IP, SERVER_PORT))
return f"Successfully sent command: '{command_string[:50]}...'"
except Exception as e:
return f"Error sending command: {e}"
# ============================================================================
# TRACKING SYSTEM - ONLY LOADED WHEN NEEDED
# ============================================================================
class LazyCommandTracker:
"""
Command tracker with lazy initialization.
Resources are ONLY allocated when tracking is actually used.
"""
def __init__(self, listen_port=5002, history_size=100):
self.listen_port = listen_port
self.history_size = history_size
self.command_history = {}
self.lock = threading.Lock()
# Lazy initialization flags
self._initialized = False
self._thread = None
self._socket = None
self._running = False
def _lazy_init(self):
"""
Initialize resources only when first tracking is requested.
This is called ONLY when someone uses tracking features.
"""
if self._initialized:
return True
try:
print("[Tracker] First tracking request - initializing resources...")
# Create socket
self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._socket.bind(('', self.listen_port))
self._socket.settimeout(0.1)
# Start thread
self._running = True
self._thread = threading.Thread(target=self._listen_loop, daemon=True)
self._thread.start()
self._initialized = True
print(f"[Tracker] Initialized on port {self.listen_port}")
return True
except Exception as e:
print(f"[Tracker] Failed to initialize: {e}")
self._cleanup()
return False
def _cleanup(self):
"""Clean up resources"""
self._running = False
if self._thread:
self._thread.join(timeout=0.5)
self._thread = None
if self._socket:
self._socket.close()
self._socket = None
self._initialized = False
def _listen_loop(self):
"""Listener thread - only runs if tracking is used"""
while self._running:
try:
data, addr = self._socket.recvfrom(2048)
message = data.decode('utf-8')
parts = message.split('|', 3)
if parts[0] == 'ACK' and len(parts) >= 3:
cmd_id = parts[1]
status = parts[2]
details = parts[3] if len(parts) > 3 else ""
with self.lock:
if cmd_id in self.command_history:
self.command_history[cmd_id].update({
'status': status,
'details': details,
'ack_time': datetime.now(),
'completed': status in ['COMPLETED', 'FAILED', 'INVALID', 'CANCELLED']
})
# Clean old entries (only if we have many)
if len(self.command_history) > self.history_size:
self._cleanup_old_entries()
except socket.timeout:
continue
except Exception:
if self._running:
pass # Silently continue
def _cleanup_old_entries(self):
"""Remove old entries to prevent memory growth"""
with self.lock:
now = datetime.now()
expired = [cmd_id for cmd_id, info in self.command_history.items()
if now - info['sent_time'] > timedelta(seconds=30)]
for cmd_id in expired:
del self.command_history[cmd_id]
def track_command(self, command: str) -> Tuple[str, str]:
"""
Track a command - initializes tracker if needed.
Returns (modified_command, cmd_id)
"""
# Initialize on first use
if not self._initialized:
if not self._lazy_init():
# Initialization failed - fall back to non-tracking
return command, None
# Generate ID and modify command
cmd_id = str(uuid.uuid4())[:8]
tracked_command = f"{cmd_id}|{command}"
# Register in history
with self.lock:
self.command_history[cmd_id] = {
'command': command,
'sent_time': datetime.now(),
'status': 'SENT',
'details': '',
'completed': False
}
return tracked_command, cmd_id
def get_status(self, cmd_id: str) -> Optional[Dict]:
"""Get status if tracker is initialized"""
if not self._initialized:
return None
with self.lock:
return self.command_history.get(cmd_id, None)
def wait_for_completion(self, cmd_id: str, timeout: float = 5.0) -> Dict:
"""Wait for completion if tracker is initialized"""
if not self._initialized:
return {'status': 'NO_TRACKING', 'details': 'Tracker not initialized', 'completed': True}
start_time = time.time()
while time.time() - start_time < timeout:
status = self.get_status(cmd_id)
if status and status['completed']:
return status
time.sleep(0.01)
return self.get_status(cmd_id) or {
'status': 'TIMEOUT',
'details': 'No acknowledgment received',
'completed': True
}
def is_active(self) -> bool:
"""Check if tracker is initialized and running"""
return self._initialized and self._running
# ============================================================================
# LAZY TRACKER ACCESS
# ============================================================================
def _get_tracker_if_needed() -> Optional[LazyCommandTracker]:
"""
Get tracker ONLY if tracking is requested.
This ensures zero overhead for non-tracking operations.
"""
global _command_tracker, _tracker_lock
# Fast path - tracker already exists
if _command_tracker is not None:
return _command_tracker
# Slow path - create tracker (only happens once)
with _tracker_lock:
if _command_tracker is None:
_command_tracker = LazyCommandTracker()
return _command_tracker
# ============================================================================
# ENHANCED SEND WITH OPTIONAL TRACKING
# ============================================================================
def send_robot_command_tracked(command_string: str) -> Tuple[str, Optional[str]]:
"""
Send with tracking - initializes tracker on first use.
Resource impact:
- First call: Starts tracker thread
- Subsequent calls: Minimal overhead (UUID generation)
"""
tracker = _get_tracker_if_needed()
if tracker:
tracked_cmd, cmd_id = tracker.track_command(command_string)
if cmd_id:
# Send tracked command
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.sendto(tracked_cmd.encode('utf-8'), (SERVER_IP, SERVER_PORT))
return f"Command sent with tracking (ID: {cmd_id})", cmd_id
except Exception as e:
return f"Error: {e}", None
# Fall back to non-tracked
return send_robot_command(command_string), None
def send_and_wait(
command_string: str,
timeout: float = 2.0,
non_blocking: bool = False
) -> Union[Dict, str, None]:
"""
Send and wait for acknowledgment OR return a command_id immediately.
First use initializes tracker.
"""
result, cmd_id = send_robot_command_tracked(command_string)
if cmd_id:
# If non_blocking is True, return the ID right away
if non_blocking:
return cmd_id
# Otherwise, proceed with the original blocking logic
tracker = _get_tracker_if_needed()
if tracker:
status_dict = tracker.wait_for_completion(cmd_id, timeout)
# Add the command_id to the returned dictionary
status_dict['command_id'] = cmd_id
return status_dict
# Handle cases where a command_id could not be generated
if non_blocking:
return None
else:
return {'status': 'NO_TRACKING', 'details': result, 'completed': True, 'command_id': None}
# ============================================================================
# BACKWARD COMPATIBLE MOVEMENT FUNCTIONS - ZERO OVERHEAD BY DEFAULT
# ============================================================================
def move_robot_joints(
joint_angles: List[float],
duration: Optional[float] = None,
speed_percentage: Optional[int] = None,
wait_for_ack: bool = False, # Default: No tracking, no overhead
timeout: float = 2.0,
non_blocking: bool = False
):
"""
Move robot joints.
Resource usage:
- wait_for_ack=False (default): ZERO overhead, no tracking
- wait_for_ack=True: Initializes tracker on first use
"""
# Validation
if duration is None and speed_percentage is None:
error = "Error: You must provide either a duration or a speed_percentage."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
# Build command
angles_str = "|".join(map(str, joint_angles))
duration_str = str(duration) if duration is not None else "None"
speed_str = str(speed_percentage) if speed_percentage is not None else "None"
command = f"MOVEJOINT|{angles_str}|{duration_str}|{speed_str}"
# Send with or without tracking
if wait_for_ack:
# User explicitly requested tracking - initialize if needed
return send_and_wait(command, timeout, non_blocking)
else:
# Default path - NO TRACKING, NO OVERHEAD
return send_robot_command(command)
def move_robot_pose(
pose: List[float],
duration: Optional[float] = None,
speed_percentage: Optional[int] = None,
wait_for_ack: bool = False, # Default: No tracking
timeout: float = 2.,
non_blocking: bool = False
):
"""
Move to pose - zero overhead by default.
"""
if duration is None and speed_percentage is None:
error = "Error: You must provide either a duration or a speed_percentage."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
pose_str = "|".join(map(str, pose))
duration_str = str(duration) if duration is not None else "None"
speed_str = str(speed_percentage) if speed_percentage is not None else "None"
command = f"MOVEPOSE|{pose_str}|{duration_str}|{speed_str}"
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
def jog_robot_joint(
joint_index: int,
speed_percentage: int,
duration: Optional[float] = None,
distance_deg: Optional[float] = None,
wait_for_ack: bool = False,
timeout: float = 2.0,
non_blocking: bool = False
):
"""
Jogs a single robot joint for a specified time or distance.
Resource usage:
- wait_for_ack=False (default): ZERO overhead, no tracking
- wait_for_ack=True: Initializes tracker on first use
"""
if duration is None and distance_deg is None:
error = "Error: You must provide either a duration or a distance_deg."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
if duration is not None:
try:
duration = float(duration)
except (ValueError, TypeError):
error = "Error: Duration must be a valid number."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
duration_str = str(duration) if duration is not None else "None"
distance_str = str(distance_deg) if distance_deg is not None else "None"
command = f"JOG|{joint_index}|{speed_percentage}|{duration_str}|{distance_str}"
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
def jog_multiple_joints(
joints: List[int],
speeds: List[float],
duration: float,
wait_for_ack: bool = False,
timeout: float = 2.0,
non_blocking: bool = False
) -> str:
"""
Jogs multiple robot joints simultaneously for a specified duration.
Args:
joints: List of joint indices (0-5 for positive, 6-11 for negative)
speeds: List of corresponding speeds (1-100%)
duration: Duration of the jog in seconds
wait_for_ack: Enable command tracking (default False)
timeout: Timeout for acknowledgment
Resource usage:
- wait_for_ack=False (default): ZERO overhead, no tracking
- wait_for_ack=True: Initializes tracker on first use
"""
if len(joints) != len(speeds):
error = "Error: The number of joints must match the number of speeds."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
joints_str = ",".join(map(str, joints))
speeds_str = ",".join(map(str, speeds))
command = f"MULTIJOG|{joints_str}|{speeds_str}|{duration}"
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
def jog_cartesian(
frame: Literal['TRF', 'WRF'],
axis: Literal['X+', 'X-', 'Y+', 'Y-', 'Z+', 'Z-', 'RX+', 'RX-', 'RY+', 'RY-', 'RZ+', 'RZ-'],
speed_percentage: int,
duration: float,
wait_for_ack: bool = False,
timeout: float = 2.0,
non_blocking: bool = False
):
"""
Jogs the robot's end-effector continuously in Cartesian space.
Resource usage:
- wait_for_ack=False (default): ZERO overhead, no tracking
- wait_for_ack=True: Initializes tracker on first use
"""
if duration is not None:
try:
duration = float(duration)
except (ValueError, TypeError):
error = "Error: Duration must be a valid number."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
command = f"CARTJOG|{frame}|{axis}|{speed_percentage}|{duration}"
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
def move_robot_cartesian(
pose: List[float],
duration: Optional[float] = None,
speed_percentage: Optional[float] = None,
wait_for_ack: bool = False,
timeout: float = 2.0,
non_blocking: bool = False
) -> str:
"""
Moves the robot's end-effector to a specific Cartesian pose in a straight line.
Args:
pose: Target pose as [x, y, z, r, p, y] (mm and degrees)
duration: Total time for the movement in seconds
speed_percentage: Movement speed as a percentage (1-100)
wait_for_ack: Enable command tracking (default False)
timeout: Timeout for acknowledgment
Resource usage:
- wait_for_ack=False (default): ZERO overhead, no tracking
- wait_for_ack=True: Initializes tracker on first use
"""
# Validate timing arguments
if (duration is None and speed_percentage is None):
error = "Error: You must provide either 'duration' or 'speed_percentage'."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
if (duration is not None and speed_percentage is not None):
error = "Error: Please provide either 'duration' or 'speed_percentage', not both."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
# Prepare command arguments
duration_arg = 'NONE'
speed_arg = 'NONE'
if duration is not None:
try:
if float(duration) <= 0:
error = "Error: Duration must be a positive number."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
duration_arg = str(duration)
except (ValueError, TypeError):
error = "Error: Duration must be a valid number."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
if speed_percentage is not None:
try:
speed_val = float(speed_percentage)
if not (0 < speed_val <= 100):
error = "Error: Speed percentage must be between 1 and 100."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
speed_arg = str(speed_val)
except (ValueError, TypeError):
error = "Error: Speed percentage must be a valid number."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
# Construct command
pose_str = "|".join(map(str, pose))
command = f"MOVECART|{pose_str}|{duration_arg}|{speed_arg}"
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
def control_pneumatic_gripper(
action: Literal['open', 'close'],
port: Literal[1, 2],
wait_for_ack: bool = False,
timeout: float = 2.0,
non_blocking: bool = False
):
"""
Controls the pneumatic gripper.
Resource usage:
- wait_for_ack=False (default): ZERO overhead, no tracking
- wait_for_ack=True: Initializes tracker on first use
"""
command = f"PNEUMATICGRIPPER|{action}|{port}"
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
def control_electric_gripper(
action: Literal['move', 'calibrate'],
position: Optional[int] = 255,
speed: Optional[int] = 150,
current: Optional[int] = 500,
wait_for_ack: bool = False,
timeout: float = 2.0,
non_blocking: bool = False
):
"""
Controls the electric gripper.
Resource usage:
- wait_for_ack=False (default): ZERO overhead, no tracking
- wait_for_ack=True: Initializes tracker on first use
"""
action_str = "move" if action == 'move' else 'calibrate'
command = f"ELECTRICGRIPPER|{action_str}|{position}|{speed}|{current}"
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
# ============================================================================
# SMOOTH MOTION COMMANDS - WITH START POSITION AND DUAL TIMING SUPPORT
# ============================================================================
def smooth_circle(
center: List[float],
radius: float,
plane: Literal['XY', 'XZ', 'YZ'] = 'XY',
frame: Literal['WRF', 'TRF'] = 'WRF',
start_pose: Optional[List[float]] = None,
duration: Optional[float] = None,
speed_percentage: Optional[float] = None,
clockwise: bool = False,
wait_for_ack: bool = False,
timeout: float = 10.0,
non_blocking: bool = False
):
"""
Execute a smooth circular motion.
Args:
center: [x, y, z] center point in mm
radius: Circle radius in mm
plane: Plane of the circle ('XY', 'XZ', or 'YZ')
frame: Reference frame ('WRF' for World, 'TRF' for Tool)
start_pose: Optional [x, y, z, rx, ry, rz] start pose (mm and degrees).
If None, starts from current position.
duration: Time to complete the circle in seconds
speed_percentage: Speed as percentage (1-100)
clockwise: Direction of motion
wait_for_ack: Enable command tracking (default False)
timeout: Timeout for acknowledgment
non_blocking: Return immediately with command ID
Resource usage:
- wait_for_ack=False (default): ZERO overhead
- wait_for_ack=True: Initializes tracker on first use
"""
if duration is None and speed_percentage is None:
error = "Error: You must provide either duration or speed_percentage."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
center_str = ",".join(map(str, center))
start_str = ",".join(map(str, start_pose)) if start_pose else "CURRENT"
clockwise_str = "1" if clockwise else "0"
# Format timing
if duration is not None:
timing_str = f"DURATION|{duration}"
else:
timing_str = f"SPEED|{speed_percentage}"
command = f"SMOOTH_CIRCLE|{center_str}|{radius}|{plane}|{frame}|{start_str}|{timing_str}|{clockwise_str}"
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
def smooth_arc_center(
end_pose: List[float],
center: List[float],
frame: Literal['WRF', 'TRF'] = 'WRF',
start_pose: Optional[List[float]] = None,
duration: Optional[float] = None,
speed_percentage: Optional[float] = None,
clockwise: bool = False,
wait_for_ack: bool = False,
timeout: float = 10.0,
non_blocking: bool = False
):
"""
Execute a smooth arc motion defined by center point.
Args:
end_pose: [x, y, z, rx, ry, rz] end pose (mm and degrees)
center: [x, y, z] arc center point in mm
frame: Reference frame ('WRF' for World, 'TRF' for Tool)
start_pose: Optional [x, y, z, rx, ry, rz] start pose.
If None, starts from current position.
If specified, adds smooth transition from current position.
duration: Time to complete the arc in seconds
speed_percentage: Speed as percentage (1-100)
clockwise: Direction of motion
wait_for_ack: Enable command tracking
timeout: Timeout for acknowledgment
non_blocking: Return immediately with command ID
"""
if duration is None and speed_percentage is None:
error = "Error: You must provide either duration or speed_percentage."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
end_str = ",".join(map(str, end_pose))
center_str = ",".join(map(str, center))
start_str = ",".join(map(str, start_pose)) if start_pose else "CURRENT"
clockwise_str = "1" if clockwise else "0"
# Format timing
if duration is not None:
timing_str = f"DURATION|{duration}"
else:
timing_str = f"SPEED|{speed_percentage}"
command = f"SMOOTH_ARC_CENTER|{end_str}|{center_str}|{frame}|{start_str}|{timing_str}|{clockwise_str}"
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
def smooth_arc_parametric(
end_pose: List[float],
radius: float,
arc_angle: float,
frame: Literal['WRF', 'TRF'] = 'WRF',
start_pose: Optional[List[float]] = None,
duration: Optional[float] = None,
speed_percentage: Optional[float] = None,
clockwise: bool = False,
wait_for_ack: bool = False,
timeout: float = 10.0,
non_blocking: bool = False
):
"""
Execute a smooth arc motion defined by radius and angle.
Args:
end_pose: [x, y, z, rx, ry, rz] end pose (mm and degrees)
radius: Arc radius in mm
arc_angle: Arc angle in degrees
frame: Reference frame ('WRF' for World, 'TRF' for Tool)
start_pose: Optional [x, y, z, rx, ry, rz] start pose.
If None, starts from current position.
duration: Time to complete the arc in seconds
speed_percentage: Speed as percentage (1-100)
clockwise: Direction of motion
wait_for_ack: Enable command tracking
timeout: Timeout for acknowledgment
non_blocking: Return immediately with command ID
"""
if duration is None and speed_percentage is None:
error = "Error: You must provide either duration or speed_percentage."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
end_str = ",".join(map(str, end_pose))
start_str = ",".join(map(str, start_pose)) if start_pose else "CURRENT"
clockwise_str = "1" if clockwise else "0"
# Format timing
if duration is not None:
timing_str = f"DURATION|{duration}"
else:
timing_str = f"SPEED|{speed_percentage}"
command = f"SMOOTH_ARC_PARAM|{end_str}|{radius}|{arc_angle}|{frame}|{start_str}|{timing_str}|{clockwise_str}"
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
def smooth_spline(
waypoints: List[List[float]],
frame: Literal['WRF', 'TRF'] = 'WRF',
start_pose: Optional[List[float]] = None,
duration: Optional[float] = None,
speed_percentage: Optional[float] = None,
wait_for_ack: bool = False,
timeout: float = 10.0,
non_blocking: bool = False
):
"""
Execute a smooth spline motion through waypoints.
Args:
waypoints: List of [x, y, z, rx, ry, rz] poses (mm and degrees)
frame: Reference frame ('WRF' for World, 'TRF' for Tool)
start_pose: Optional [x, y, z, rx, ry, rz] start pose.
If None, starts from current position.
If specified and different from first waypoint, adds transition.
duration: Total time for the motion in seconds
speed_percentage: Speed as percentage (1-100)
wait_for_ack: Enable command tracking
timeout: Timeout for acknowledgment
non_blocking: Return immediately with command ID
"""
if duration is None and speed_percentage is None:
error = "Error: You must provide either duration or speed_percentage."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
num_waypoints = len(waypoints)
start_str = ",".join(map(str, start_pose)) if start_pose else "CURRENT"
# Format timing
if duration is not None:
timing_str = f"DURATION|{duration}"
else:
timing_str = f"SPEED|{speed_percentage}"
# Format waypoints - flatten each waypoint's 6 values
waypoint_strs = []
for wp in waypoints:
waypoint_strs.extend(map(str, wp))
# Build command
command_parts = [f"SMOOTH_SPLINE", str(num_waypoints), frame, start_str, timing_str]
command_parts.extend(waypoint_strs)
command = "|".join(command_parts)
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
def smooth_helix(
center: List[float],
radius: float,
pitch: float,
height: float,
frame: Literal['WRF', 'TRF'] = 'WRF',
start_pose: Optional[List[float]] = None,
duration: Optional[float] = None,
speed_percentage: Optional[float] = None,
clockwise: bool = False,
wait_for_ack: bool = False,
timeout: float = 10.0,
non_blocking: bool = False
):
"""
Execute a smooth helical motion.
Args:
center: [x, y, z] helix center point in mm
radius: Helix radius in mm
pitch: Vertical distance per revolution in mm
height: Total height of helix in mm
frame: Reference frame ('WRF' for World, 'TRF' for Tool)
start_pose: Optional [x, y, z, rx, ry, rz] start pose.
If None, starts from current position on helix perimeter.
duration: Time to complete the helix in seconds
speed_percentage: Speed as percentage (1-100)
clockwise: Direction of motion
wait_for_ack: Enable command tracking
timeout: Timeout for acknowledgment
non_blocking: Return immediately with command ID
"""
if duration is None and speed_percentage is None:
error = "Error: You must provide either duration or speed_percentage."
return {'status': 'INVALID', 'details': error} if wait_for_ack else error
center_str = ",".join(map(str, center))
start_str = ",".join(map(str, start_pose)) if start_pose else "CURRENT"
clockwise_str = "1" if clockwise else "0"
# Format timing
if duration is not None:
timing_str = f"DURATION|{duration}"
else:
timing_str = f"SPEED|{speed_percentage}"
command = f"SMOOTH_HELIX|{center_str}|{radius}|{pitch}|{height}|{frame}|{start_str}|{timing_str}|{clockwise_str}"
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
def smooth_blend(
segments: List[Dict],
blend_time: float = 0.5,
frame: Literal['WRF', 'TRF'] = 'WRF',
start_pose: Optional[List[float]] = None,
duration: Optional[float] = None,
speed_percentage: Optional[float] = None,
wait_for_ack: bool = False,
timeout: float = 15.0,
non_blocking: bool = False
):
"""
Execute a blended motion through multiple segments.
Args:
segments: List of segment dictionaries, each containing:
- 'type': 'LINE', 'CIRCLE', 'ARC', or 'SPLINE'
- Additional parameters based on type
blend_time: Time to blend between segments in seconds
frame: Reference frame ('WRF' for World, 'TRF' for Tool)
start_pose: Optional [x, y, z, rx, ry, rz] start pose for first segment.
If None, starts from current position.
duration: Total time for entire motion (scales all segments proportionally)
speed_percentage: Speed as percentage (1-100) for entire motion
wait_for_ack: Enable command tracking
timeout: Timeout for acknowledgment
non_blocking: Return immediately with command ID
Example:
segments = [
{'type': 'LINE', 'end': [x,y,z,rx,ry,rz], 'duration': 2.0},
{'type': 'CIRCLE', 'center': [x,y,z], 'radius': 50, 'plane': 'XY',
'duration': 3.0, 'clockwise': False},
{'type': 'ARC', 'end': [x,y,z,rx,ry,rz], 'center': [x,y,z],
'duration': 2.0, 'clockwise': True}
]
"""
num_segments = len(segments)
start_str = ",".join(map(str, start_pose)) if start_pose else "CURRENT"
# Format timing
if duration is None and speed_percentage is None:
# Use individual segment durations
timing_str = "DEFAULT"
elif duration is not None:
timing_str = f"DURATION|{duration}"
else:
timing_str = f"SPEED|{speed_percentage}"
# Format segments
segment_strs = []
for seg in segments:
seg_type = seg['type']
if seg_type == 'LINE':
end_str = ",".join(map(str, seg['end']))
seg_str = f"LINE|{end_str}|{seg.get('duration', 2.0)}"
elif seg_type == 'CIRCLE':
center_str = ",".join(map(str, seg['center']))
clockwise_str = "1" if seg.get('clockwise', False) else "0"
seg_str = f"CIRCLE|{center_str}|{seg['radius']}|{seg['plane']}|{seg.get('duration', 3.0)}|{clockwise_str}"
elif seg_type == 'ARC':
end_str = ",".join(map(str, seg['end']))
center_str = ",".join(map(str, seg['center']))
clockwise_str = "1" if seg.get('clockwise', False) else "0"
seg_str = f"ARC|{end_str}|{center_str}|{seg.get('duration', 2.0)}|{clockwise_str}"
elif seg_type == 'SPLINE':
waypoints_str = ";".join([",".join(map(str, wp)) for wp in seg['waypoints']])
seg_str = f"SPLINE|{len(seg['waypoints'])}|{waypoints_str}|{seg.get('duration', 3.0)}"
else:
continue
segment_strs.append(seg_str)
# Build command with || separators between segments
command = f"SMOOTH_BLEND|{num_segments}|{blend_time}|{frame}|{start_str}|{timing_str}|" + "||".join(segment_strs)
if wait_for_ack:
return send_and_wait(command, timeout, non_blocking)
else:
return send_robot_command(command)
# ============================================================================
# CONVENIENCE FUNCTIONS FOR SMOOTH MOTION CHAINS
# ============================================================================
def chain_smooth_motions(
motions: List[Dict],
ensure_continuity: bool = True,
frame: Literal['WRF', 'TRF'] = 'WRF', # ADD THIS
wait_for_ack: bool = True,
timeout: float = 30.0
):
"""
Chain multiple smooth motions together with automatic continuity.
Args:
motions: List of motion dictionaries, each with 'type' and parameters
ensure_continuity: If True, automatically sets start_pose of each motion
to end of previous motion for perfect continuity
frame: Reference frame for all motions ('WRF' or 'TRF') # ADD THIS
wait_for_ack: Enable command tracking
timeout: Timeout per motion
Example:
chain_smooth_motions([
{'type': 'circle', 'center': [200, 0, 200], 'radius': 50, 'duration': 5},
{'type': 'arc', 'end_pose': [250, 50, 200, 0, 0, 90], 'center': [225, 25, 200], 'duration': 3},
{'type': 'helix', 'center': [250, 50, 150], 'radius': 30, 'pitch': 20, 'height': 100, 'duration': 8}
], frame='TRF') # Can now specify frame
"""
results = []
last_end_pose = None
for i, motion in enumerate(motions):
motion_type = motion.get('type', '').lower()
# Add frame to motion parameters
motion['frame'] = frame
# Add start_pose from previous motion if ensuring continuity
if ensure_continuity and last_end_pose and i > 0:
motion['start_pose'] = last_end_pose
# Execute the appropriate motion (add frame parameter to each call)
if motion_type == 'circle':
result = smooth_circle(**{k: v for k, v in motion.items() if k != 'type'},
wait_for_ack=wait_for_ack, timeout=timeout)
last_end_pose = None # Circles return to start
elif motion_type == 'arc' or motion_type == 'arc_center':
result = smooth_arc_center(**{k: v for k, v in motion.items() if k != 'type'},
wait_for_ack=wait_for_ack, timeout=timeout)
last_end_pose = motion.get('end_pose')
elif motion_type == 'arc_param' or motion_type == 'arc_parametric':
result = smooth_arc_parametric(**{k: v for k, v in motion.items() if k != 'type'},
wait_for_ack=wait_for_ack, timeout=timeout)
last_end_pose = motion.get('end_pose')
elif motion_type == 'spline':
result = smooth_spline(**{k: v for k, v in motion.items() if k != 'type'},
wait_for_ack=wait_for_ack, timeout=timeout)
waypoints = motion.get('waypoints', [])
last_end_pose = waypoints[-1] if waypoints else None
elif motion_type == 'helix':
result = smooth_helix(**{k: v for k, v in motion.items() if k != 'type'},
wait_for_ack=wait_for_ack, timeout=timeout)
last_end_pose = None
else:
result = {'status': 'INVALID', 'details': f'Unknown motion type: {motion_type}'}
results.append(result)
# Check for failures if tracking
if wait_for_ack and isinstance(result, dict) and result.get('status') == 'FAILED':
print(f"Motion {i+1} failed: {result.get('details')}")
break
return results
def execute_trajectory(
trajectory: List[List[float]],
timing_mode: Literal['duration', 'speed'] = 'duration',
timing_value: float = 5.0,
motion_type: Literal['spline', 'linear'] = 'spline',
frame: Literal['WRF', 'TRF'] = 'WRF', # ADD THIS
wait_for_ack: bool = True,
timeout: float = 30.0,