-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrobotSim.py
1534 lines (1408 loc) · 82.6 KB
/
robotSim.py
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
"""
Author: Konstantinos Angelopoulos
Date: 04/02/2020
All rights reserved.
Feel free to use and modify and if you like it give it a star.
Handles the simulation and communication with the robot.
"""
# Offset of camera center from the origin of the coordinate system of kinect
OFFSET_RGB = 95 # mm
OFFSET_DEPTH = 65 # mm
CLOUD_RESET_RADIUS = 100 # mm
PARTICLE_RADIUS = 30 # mm
# KUKA LWR IV+ Joint angle limits
ORIGINAL_LOWER_LIMITS = [-170, -30, -170, -120, -170, -120, -170]
ORIGINAL_UPPER_LIMITS = [170, 210, 170, 120, 170, 120, 170]
MODIFIED_LOWER_LIMITS = [-170, -30, -170, -170, -170, -170, -170]
MODIFIED_UPPER_LIMITS = [170, 210, 170, 170, 170, 170, 170]
def init(speed, focal_length, field_of_view, fabric_center, fabric_points, fabric_width, fabric_height, world_kalman_points, kinect_distance_from_plane, kinect_tilt, check_col=True):
"""
Reset and initialize RoboDK workspace
:param speed: float robot iso speed
:param focal_length: float kinect focal length
:param field_of_view: float kinect field of view
:param fabric_center: list with fabric center coordinates
:param fabric_points: list with fabric edge point coordinates
:param fabric_width: float fabric width
:param fabric_height: float fabric height
:param world_kalman_points: list with world kalman coordinates
:param kinect_distance_from_plane: float kinect height from floor plane
:param kinect_tilt: float kinect tilt angle from floor plane
:param check_col: boolean to check for collisions
:return: link to the RoboDK instance, Item robot in robodk, Item pose, Item hand, Item kinect, Item gripper, Item bottom right, Item bottom left, Item top left, Item top right
"""
# Import libraries here for optimization
from robolink.robolink import Robolink, ITEM_TYPE_ROBOT
from robodk.robodk import KUKA_2_Pose, Pose_2_KUKA, transl, rotx
import sys
import numpy as np
import os
# Interactions with Robot
RDK = Robolink()
# Turn off automatic rendering (faster simulation)
RDK.Render(False)
# Initialize robot
# Search all items for a valid robot type (assumes only one robot is loaded)
robot = None
for station in RDK.ItemList():
for item in station.Childs():
if item.type == ITEM_TYPE_ROBOT:
robot = item
break
if robot is not None:
break
if not robot.Valid():
print("[ROBODK]: No robot is loaded to the station")
raise Exception("[ROBODK]: No Robot found!!")
# Check Home, Targets and Items Loaded
home = RDK.Item('Home') # Home
pose = RDK.Item('Target') # Target
sheet = RDK.Item('Sheet') # Sheet item
br = RDK.Item('Bottom Right') # Bottom Right Corner of Fabric
bl = RDK.Item('Bottom Left') # Bottom Left Corner of Fabric
tl = RDK.Item('Top Left') # Top Left Corner of Fabric
tr = RDK.Item('Top Right') # Top Right Corner of Fabric
kinect = RDK.Item('Kinect') # Get Kinect
hand = RDK.Item('Hand') # Get Hand model
gripper = RDK.Item('Gripper') # Get Gripper model
light = RDK.Item('Light Source') # Get Light Source
# Check if everything is loaded correctly
if home.type == -1 or pose.type == -1 or sheet.type == -1 or bl.type == -1 or tl.type == -1 or tr.type == -1 or br.type == -1 or kinect.type == -1 or hand.type == -1 or gripper.type == -1 or light.type == -1:
sys.exit('[ROBODK]: Cannot obtain simulation items: Check if everything is loaded')
# Always start from home
try:
# Move to Home
robot.setJoints([0, 90, 0, 0, 0, 0])
except Exception as e:
print(f'[ROBODK]: Cant Move Robot Home\n{e}')
# Initialize Kinect
# Check Kinect Tilt angle
temp_kinect = Pose_2_KUKA(kinect.Pose())
kinect.setPose(KUKA_2_Pose(list((temp_kinect[0], temp_kinect[1], temp_kinect[2], temp_kinect[3], temp_kinect[4], -90 + kinect_tilt))))
# Check kinect height
actual_height = Pose_2_KUKA(kinect.Pose())
if (actual_height[2] - kinect_distance_from_plane) <= 50:
# kinect.setPose(KUKA_2_Pose(list((690, -1770, kinect_distance_from_plane, 0, 0, -90 + kinect_tilt))))
kinect.setPose(KUKA_2_Pose(list((temp_kinect[0], temp_kinect[1], temp_kinect[2], temp_kinect[3], temp_kinect[4], -90 + kinect_tilt))))
else:
# kinect.setPose(KUKA_2_Pose(list((690, -1770, 2150-kinect_distance_from_plane/100, 0, 0, -90 + kinect_tilt))))
kinect.setPose(KUKA_2_Pose(list((temp_kinect[0], temp_kinect[1], temp_kinect[2], temp_kinect[3], temp_kinect[4], -90 + kinect_tilt))))
# Reset Sheet
sheet.Delete()
sheet = RDK.AddFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Models/Sheet.stl'))
sheet.setPose(KUKA_2_Pose(list((635, 0, 770, 90, 0, 0))))
sheet.setColor([255/255, 170/255, 127/255, 1])
# Reset Fabric Points
"""!---------Targets are with respect to the Robot Base Reference so its better to use setPoseAbs() to keep everything in the universal coordinate system---------!"""
br.setPoseAbs(KUKA_2_Pose(list((785, -250, 770, 45, -180, -15))))
bl.setPoseAbs(KUKA_2_Pose(list((485, -250, 770, -45, 180, -15))))
tl.setPoseAbs(KUKA_2_Pose(list((485, 250, 770, 45, 0, 180-15))))
tr.setPoseAbs(KUKA_2_Pose(list((785, 250, 770, -45, 0, 180-15))))
# Reset Hand
hand.setPose(KUKA_2_Pose(list((500, 1000, 1400, -90, 0, 0))))
# Reset Target
pose.setPose(KUKA_2_Pose(list((600, 250, 750, 0, 0, -90))))
# It is important to provide the reference frame and the tool frames when generating programs offline
robot.setPoseFrame(robot.PoseFrame())
robot.setPoseTool(robot.PoseTool())
# Define Light Source
light.setPoseAbs(KUKA_2_Pose(list((1000, 0, 2500, 0, 205, 0))))
# Define Camera
# Close all cameras just in case
RDK.Cam2D_Close()
# Pick which items will act as the camera
# camref = RDK.ItemUserPick('Select the camera')
# Use the GLSL files for more realistic camera view from inside the RoboDK software
file_shader_fragment = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'RoboDK/KUKA/Camera-Shaders/shader_fragment.glsl')
file_shader_vertex = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'RoboDK/KUKA/Camera-Shaders/shader_vertex.glsl')
# Add Camera
"""
# -------------Set parameters in mm and degrees-------------------------
# FOV: Field of view in degrees (atan(0.5*height/distance) of the sensor
# FOCAL_LENGTH: focal length in mm
# FAR_LENGTH: maximum working distance (in mm)
# SIZE: size of the window in pixels (fixed) (width x height)
# SNAPSHOT: size of the snapshot image in pixels (width x height)
# BG_COLOR: background color (rgb color or named color: AARRGGBB)
# LIGHT_AMBIENT: ambient color (rgb color or named color: AARRGGBB)
# LIGHT_SPECULAR: specular color (rgb color or named color: AARRGGBB)
# LIGHT_DIFFUSE: diffuse color (rgb color or named color: AARRGGBB)
# DEPTH: Add this flag to create a 32 bit depth map (white=close, black=far)
# NO_TASKBAR: Don't add the window to the task bar
# MINIMIZED: Show the window minimized
# ALWAYS_VISIBLE: Keep the window on top of all other windows
# SHADER_VERTEX: File to a vertex shader (GLSL file)
# SHADER_FRAGMENT: File to a fragment shader (GLSL file)
"""
# cam_id = RDK.Cam2D_Add(kinect, 'FOCAL_LENGTH=' + str(focal_length) + ' FOV=' + str(field_of_view) + ' FAR_LENGTH=4500 SIZE=548x308 BG_COLOR=black LIGHT_AMBIENT=red LIGHT_DIFFUSE=black LIGHT_SPECULAR=white ALWAYS_VISIBLE')
# RDK.Cam2D_Add(kinect, 'FOCAL_LENGTH=' + str(focal_length) + ' FOV=' + str(field_of_view) + ' FAR_LENGTH=4500 SIZE=548x308 BG_COLOR=black LIGHT_AMBIENT=red LIGHT_DIFFUSE=black LIGHT_SPECULAR=white TASKBAR ALWAYS_VISIBLE')
RDK.Cam2D_Add(kinect, 'FOCAL_LENGTH=' + str(focal_length) + ' FOV=' + str(field_of_view) + ' FAR_LENGTH=4500 SIZE=512x424 BG_COLOR=black SHADER_FRAGMENT=' + file_shader_fragment + ' SHADER_VERTEX=' + file_shader_vertex + ' MINIMIZED')
# Special command to retrieve the window ID:
# win_id = RDK.Command("CamWinID", str(cam_id))
# Take snapshot
# RDK.Cam2D_Snapshot(RDK.getParam('PATH_OPENSTATION') + "/Kinect_snapshot.png", cam_id)
"""
!------------------THE POSE OF AN ITEM/OBJECT/TARGET IS WITH RESPECT TO ITS PARENT------------------!
"""
# Define fabric origins
kinect_pos = Pose_2_KUKA(kinect.Pose())
# Initialise hand origin as detected from kinect camera
# hand.setPose(KUKA_2_Pose(list((kinect_pos[0] - world_kalman_points[0], kinect_pos[1] + world_kalman_points[2], kinect_pos[2] + world_kalman_points[1] + np.sin(kinect_tilt*np.pi/180)*world_kalman_points[2], -90, 0, 0))))
hand_temp = Pose_2_KUKA(kinect.Pose()*transl(-world_kalman_points[0] + OFFSET_DEPTH, -world_kalman_points[1], world_kalman_points[2]))
hand.setPose(KUKA_2_Pose(list((hand_temp[0], hand_temp[1], hand_temp[2], -90, 0, 0))))
# Original Position = (660, 240, 426, 90, 0, 0)
# sheet.setPose(KUKA_2_Pose(list((kinect_pos[0] - fabric_center[0], kinect_pos[1] + fabric_center[2], kinect_pos[2] + fabric_center[1] + np.sin(kinect_tilt*np.pi/180)*fabric_center[2], 90, 0, 0))))
sheet_temp = Pose_2_KUKA(kinect.Pose()*transl(-fabric_center[0] + OFFSET_DEPTH, -fabric_center[1], fabric_center[2]))
sheet.setPose(KUKA_2_Pose(list((sheet_temp[0], sheet_temp[1], sheet_temp[2], 90, 0, 0))))
# sheet.setPose(KUKA_2_Pose(list((kinect_pos[0] - fabric_center[0], kinect_pos[1] + fabric_center[2], kinect_pos[2] + fabric_center[1], 90, 0, 0))))
# Scale to match measurements
# Sheet CAD: thickness (Z axis) = 0.1 mm, Length (Y axis) = 500 mm, Width (X Axis) = 300 mm
# sheet.Scale(scale_uniform)
# Calculate scale
scale_x = fabric_height/500
scale_y = fabric_width/300
scale_z = 1
sheet.Scale([scale_x, scale_y, scale_z]) # Scale with different factor in each direction
# Define Fabric Corners
"""!---------Targets are with respect to the Robot Base Reference so its better to use setPoseAbs() to keep everything in the universal coordinate system---------!"""
"""
br.setPoseAbs(KUKA_2_Pose(list((kinect_pos[0] - fabric_points[0, 0], kinect_pos[1] + fabric_points[0, 2], kinect_pos[2] + fabric_points[0, 1] + np.sin(kinect_tilt*np.pi/180)*fabric_points[0, 2], 0, -180, 0))))
bl.setPoseAbs(KUKA_2_Pose(list((kinect_pos[0] - fabric_points[1, 0], kinect_pos[1] + fabric_points[1, 2], kinect_pos[2] + fabric_points[1, 1] + np.sin(kinect_tilt*np.pi/180)*fabric_points[1, 2], -90, 180, 0))))
tl.setPoseAbs(KUKA_2_Pose(list((kinect_pos[0] - fabric_points[2, 0], kinect_pos[1] + fabric_points[2, 2], kinect_pos[2] + fabric_points[2, 1] + np.sin(kinect_tilt*np.pi/180)*fabric_points[2, 2], 0, 0, 180))))
tr.setPoseAbs(KUKA_2_Pose(list((kinect_pos[0] - fabric_points[3, 0], kinect_pos[1] + fabric_points[3, 2], kinect_pos[2] + fabric_points[3, 1] + np.sin(kinect_tilt*np.pi/180)*fabric_points[3, 2], -90, 0, 180))))
"""
br_temp = Pose_2_KUKA(kinect.Pose()*transl(-fabric_points[0, 0] + OFFSET_DEPTH, -fabric_points[0, 1], fabric_points[0, 2]))
bl_temp = Pose_2_KUKA(kinect.Pose()*transl(-fabric_points[1, 0] + OFFSET_DEPTH, -fabric_points[1, 1], fabric_points[1, 2]))
tl_temp = Pose_2_KUKA(kinect.Pose()*transl(-fabric_points[2, 0] + OFFSET_DEPTH, -fabric_points[2, 1], fabric_points[2, 2]))
tr_temp = Pose_2_KUKA(kinect.Pose()*transl(-fabric_points[3, 0] + OFFSET_DEPTH, -fabric_points[3, 1], fabric_points[3, 2]))
br.setPoseAbs(KUKA_2_Pose(list((br_temp[0], br_temp[1], sheet_temp[2], 45, -180,0))))
bl.setPoseAbs(KUKA_2_Pose(list((bl_temp[0], bl_temp[1], sheet_temp[2], -45, 180, 0))))
tl.setPoseAbs(KUKA_2_Pose(list((tl_temp[0], tl_temp[1], sheet_temp[2], 45, 0, 180))))
tr.setPoseAbs(KUKA_2_Pose(list((tr_temp[0], tr_temp[1], sheet_temp[2], -45, 0, 180))))
# enable render and speed up simulation (big data for neural)
RDK.Render(True)
RDK.setSimulationSpeed(5) # x faster (5 default)
robot.setZoneData(3) # Set the rounding parameter (Also known as: CNT, APO/C_DIS, ZoneData, Blending radius, cornering, ...)
RDK.ShowRoboDK() # Show RoboDK window
RDK.setWindowState(2) # Show RoboDK window
"""
# Script execution types
RUNMODE_SIMULATE = 1 # performs the simulation moving the robot (default)
RUNMODE_QUICKVALIDATE = 2 # performs a quick check to validate the robot movements
RUNMODE_MAKE_ROBOTPROG = 3 # makes the robot program
RUNMODE_MAKE_ROBOTPROG_AND_UPLOAD = 4 # makes the robot program and updates it to the robot
RUNMODE_MAKE_ROBOTPROG_AND_START = 5 # makes the robot program and starts it on the robot (independently from the PC)
RUNMODE_RUN_ROBOT = 6 # moves the real robot from the PC (PC is the client, the robot behaves like a server)
"""
RDK.setRunMode(1) # Simulate only
# robot.setSpeed(speed_linear=speed*1000, speed_joints=110.0, accel_linear=-1, accel_joints=-1) # Set linear speed in mm/s (-1 = no change)
robot.setSpeed(speed_linear=(0.8*speed)*1000, speed_joints=-1, accel_linear=-1, accel_joints=-1) # Set linear speed in mm/s (-1 = no change)
# robot.setSpeedJoints(-1, 110.0, -1, -1) # Set joint speed in deg/s for rotary joints and mm/s for linear joints
# robot.setAcceleration() # Set linear acceleration in mm/s2
# robot.setAccelerationJoints() # Set joint acceleration in deg/s2 for rotary joints and mm/s2 for linear joints
# robot.setParamRobotTool(tool_mass=5, tool_cog=None) # set tool_mass in kg as float, tool_cog = list(x, y, z) tool center of gravity as [x,y,z] with respect to the robot flange
if check_col:
RDK.setCollisionActive(check_state=1) # Enable collision check
RDK.Command('CollisionMethod', value='CUDA')
RDK.Command('DisplayCurves', value='0')
# RDK.Command('SetSize3D', value='650x610')
# RDK.Command('Trace', value='On')
# RDK.setFlagsRoboDK(flags=[FLAG_ROBODK_TREE_ACTIVE])
RDK.setViewPose(KUKA_2_Pose(list((-635, -500, -6000, 0, 0, -40))))
return RDK, robot, pose, hand, kinect, gripper, br, bl, tl, tr
def _init(speed, focal_length, field_of_view, fabric_center, fabric_points, fabric_width, fabric_height, world_kalman_points, kinect_distance_from_plane, kinect_tilt, check_col=True):
"""
Reset and initialize RoboDK workspace
:param speed: float robot speed
:param focal_length: float kinect color focal length
:param field_of_view: float kinect color field of view
:param fabric_center: list with fabric ceter coordinates
:param fabric_points: list with fabric edge points
:param fabric_width: float fabric width
:param fabric_height: float fabric height
:param world_kalman_points: list with world kalman points
:param kinect_distance_from_plane: float kinect height from floor
:param kinect_tilt: float kinect tilt from floor plane
:param check_col: boolean to check collisions
:return: Item robot in RoboDK, Item pose in RoboDK, Item hand in RoboDK, Item kinect in RoboDK, Item gripper in RoboDK, Item bottom right, Item bottom left, Item top left, Item top right
"""
# Import libraries here for optimization
from robolink.robolink import Robolink, ITEM_TYPE_ROBOT
from robodk.robodk import KUKA_2_Pose, Pose_2_KUKA, transl, rotx
import sys
import numpy as np
import os
# Interactions with Robot
RDK = Robolink()
# Turn off automatic rendering (faster simulation)
RDK.Render(False)
# Initialize robot
# Search all items for a valid robot type (assumes only one robot is loaded)
robot = None
for station in RDK.ItemList():
for item in station.Childs():
if item.type == ITEM_TYPE_ROBOT:
robot = item
break
if robot is not None:
break
if not robot.Valid():
print("[ROBODK]: No robot is loaded to the station")
raise Exception("[ROBODK]: No Robot found!!")
# Check Home, Targets and Items Loaded
home = RDK.Item('Home') # Home
pose = RDK.Item('Target') # Target
sheet = RDK.Item('Sheet') # Sheet item
br = RDK.Item('Bottom Right') # Bottom Right Corner of Fabric
bl = RDK.Item('Bottom Left') # Bottom Left Corner of Fabric
tl = RDK.Item('Top Left') # Top Left Corner of Fabric
tr = RDK.Item('Top Right') # Top Right Corner of Fabric
kinect = RDK.Item('Kinect') # Get Kinect
hand = RDK.Item('Hand') # Get Hand model
gripper = RDK.Item('Gripper') # Get Gripper model
light = RDK.Item('Light Source') # Get Light Source
# Check if everything is loaded correctly
if home.type == -1 or pose.type == -1 or sheet.type == -1 or bl.type == -1 or tl.type == -1 or tr.type == -1 or br.type == -1 or kinect.type == -1 or hand.type == -1 or gripper.type == -1 or light.type == -1:
sys.exit('[ROBODK]: Cannot obtain simulation items: Check if everything is loaded')
# Initialize Kinect
# Check Kinect Tilt angle
temp_kinect = Pose_2_KUKA(kinect.Pose())
kinect.setPoseAbs(KUKA_2_Pose(list((temp_kinect[0], temp_kinect[1], temp_kinect[2], temp_kinect[3], temp_kinect[4], -90 + kinect_tilt))))
# Check kinect height
actual_height = Pose_2_KUKA(kinect.Pose())
if (actual_height[2] - kinect_distance_from_plane) <= 50:
# kinect.setPose(KUKA_2_Pose(list((690, -1770, kinect_distance_from_plane, 0, 0, -90 + kinect_tilt))))
kinect.setPoseAbs(KUKA_2_Pose(list((temp_kinect[0], temp_kinect[1], temp_kinect[2], temp_kinect[3], temp_kinect[4], -90 + kinect_tilt))))
else:
# kinect.setPose(KUKA_2_Pose(list((690, -1770, 2150-kinect_distance_from_plane/100, 0, 0, -90 + kinect_tilt))))
kinect.setPoseAbs(KUKA_2_Pose(list((temp_kinect[0], temp_kinect[1], temp_kinect[2], temp_kinect[3], temp_kinect[4], -90 + kinect_tilt))))
# Define Camera
# Use the GLSL files for more realistic camera view from inside the RoboDK software
file_shader_fragment = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'RoboDK/KUKA/Camera-Shaders/shader_fragment.glsl')
file_shader_vertex = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'RoboDK/KUKA/Camera-Shaders/shader_vertex.glsl')
# Add Camera
"""
# -------------Set parameters in mm and degrees-------------------------
# FOV: Field of view in degrees (atan(0.5*height/distance) of the sensor
# FOCAL_LENGTH: focal length in mm
# FAR_LENGTH: maximum working distance (in mm)
# SIZE: size of the window in pixels (fixed) (width x height)
# SNAPSHOT: size of the snapshot image in pixels (width x height)
# BG_COLOR: background color (rgb color or named color: AARRGGBB)
# LIGHT_AMBIENT: ambient color (rgb color or named color: AARRGGBB)
# LIGHT_SPECULAR: specular color (rgb color or named color: AARRGGBB)
# LIGHT_DIFFUSE: diffuse color (rgb color or named color: AARRGGBB)
# DEPTH: Add this flag to create a 32 bit depth map (white=close, black=far)
# NO_TASKBAR: Don't add the window to the task bar
# MINIMIZED: Show the window minimized
# ALWAYS_VISIBLE: Keep the window on top of all other windows
# SHADER_VERTEX: File to a vertex shader (GLSL file)
# SHADER_FRAGMENT: File to a fragment shader (GLSL file)
"""
# cam_id = RDK.Cam2D_Add(kinect, 'FOCAL_LENGTH=' + str(focal_length) + ' FOV=' + str(field_of_view) + ' FAR_LENGTH=4500 SIZE=548x308 BG_COLOR=black LIGHT_AMBIENT=red LIGHT_DIFFUSE=black LIGHT_SPECULAR=white ALWAYS_VISIBLE')
# RDK.Cam2D_Add(kinect, 'FOCAL_LENGTH=' + str(focal_length) + ' FOV=' + str(field_of_view) + ' FAR_LENGTH=4500 SIZE=548x308 BG_COLOR=black LIGHT_AMBIENT=red LIGHT_DIFFUSE=black LIGHT_SPECULAR=white TASKBAR ALWAYS_VISIBLE')
RDK.Cam2D_Add(kinect, 'FOCAL_LENGTH=' + str(focal_length) + ' FOV=' + str(field_of_view) + ' FAR_LENGTH=4500 SIZE=512x424 BG_COLOR=black SHADER_FRAGMENT=' + file_shader_fragment + ' SHADER_VERTEX=' + file_shader_vertex + ' MINIMIZED')
# Special command to retrieve the window ID:
# win_id = RDK.Command("CamWinID", str(cam_id))
# Take snapshot
# RDK.Cam2D_Snapshot(RDK.getParam('PATH_OPENSTATION') + "/Kinect_snapshot.png", cam_id)
"""
!------------------THE POSE OF AN ITEM/OBJECT/TARGET IS WITH RESPECT TO ITS PARENT------------------!
"""
# Define fabric origins
# Initialise hand origin as detected from kinect camera
hand_temp = Pose_2_KUKA(kinect.Pose() * transl(-world_kalman_points[0] + OFFSET_DEPTH, -world_kalman_points[1], world_kalman_points[2]))
hand.setPoseAbs(KUKA_2_Pose(list((hand_temp[0], hand_temp[1], hand_temp[2], -90, 0, 0))))
# Original Position = (660, 240, 426, 90, 0, 0)
sheet_temp = Pose_2_KUKA(kinect.Pose() * transl(-fabric_center[0] + OFFSET_DEPTH, -fabric_center[1], fabric_center[2]))
sheet.setPoseAbs(KUKA_2_Pose(list((sheet_temp[0], sheet_temp[1], sheet_temp[2], 90, 0, 0))))
# Scale to match measurements
# Sheet CAD: thickness (Z axis) = 0.1 mm, Length (Y axis) = 500 mm, Width (X Axis) = 300 mm
# sheet.Scale(scale_uniform)
# Calculate scale
scale_x = fabric_height / 500
scale_y = fabric_width / 300
scale_z = 1
sheet.Scale([scale_x, scale_y, scale_z]) # Scale with different factor in each direction
# Define Fabric Corners
br_temp = Pose_2_KUKA(kinect.Pose() * transl(-fabric_points[0, 0] + OFFSET_DEPTH, -fabric_points[0, 1], fabric_points[0, 2]))
bl_temp = Pose_2_KUKA(kinect.Pose() * transl(-fabric_points[1, 0] + OFFSET_DEPTH, -fabric_points[1, 1], fabric_points[1, 2]))
tl_temp = Pose_2_KUKA(kinect.Pose() * transl(-fabric_points[2, 0] + OFFSET_DEPTH, -fabric_points[2, 1], fabric_points[2, 2]))
tr_temp = Pose_2_KUKA(kinect.Pose() * transl(-fabric_points[3, 0] + OFFSET_DEPTH, -fabric_points[3, 1], fabric_points[3, 2]))
br.setPoseAbs(KUKA_2_Pose(list((br_temp[0], br_temp[1], sheet_temp[2], 45, -180, 0))))
bl.setPoseAbs(KUKA_2_Pose(list((bl_temp[0], bl_temp[1], sheet_temp[2], -45, 180, 0))))
tl.setPoseAbs(KUKA_2_Pose(list((tl_temp[0], tl_temp[1], sheet_temp[2], 45, 0, 180))))
tr.setPoseAbs(KUKA_2_Pose(list((tr_temp[0], tr_temp[1], sheet_temp[2], -45, 0, 180))))
# enable render and speed up simulation (big data for neural)
RDK.Render(True)
"""
# Script execution types
RUNMODE_SIMULATE = 1 # performs the simulation moving the robot (default)
RUNMODE_QUICKVALIDATE = 2 # performs a quick check to validate the robot movements
RUNMODE_MAKE_ROBOTPROG = 3 # makes the robot program
RUNMODE_MAKE_ROBOTPROG_AND_UPLOAD = 4 # makes the robot program and updates it to the robot
RUNMODE_MAKE_ROBOTPROG_AND_START = 5 # makes the robot program and starts it on the robot (independently from the PC)
RUNMODE_RUN_ROBOT = 6 # moves the real robot from the PC (PC is the client, the robot behaves like a server)
"""
# robot.setSpeed(speed_linear=speed*1000, speed_joints=110.0, accel_linear=-1, accel_joints=-1) # Set linear speed in mm/s (-1 = no change)
robot.setSpeed(speed_linear=(0.8 * speed) * 1000, speed_joints=-1, accel_linear=-1, accel_joints=-1) # Set linear speed in mm/s (-1 = no change)
# robot.setSpeedJoints(-1, 110.0, -1, -1) # Set joint speed in deg/s for rotary joints and mm/s for linear joints
# robot.setAcceleration() # Set linear acceleration in mm/s2
# robot.setAccelerationJoints() # Set joint acceleration in deg/s2 for rotary joints and mm/s2 for linear joints
# robot.setParamRobotTool(tool_mass=5, tool_cog=None) # set tool_mass in kg as float, tool_cog = list(x, y, z) tool center of gravity as [x,y,z] with respect to the robot flange
if check_col:
RDK.setCollisionActive(check_state=1) # Enable collision check
RDK.Command('CollisionMethod', value='CUDA')
# RDK.Command('SetSize3D', value='650x610')
# RDK.Command('Trace', value='On')
# RDK.setFlagsRoboDK(flags=[FLAG_ROBODK_TREE_ACTIVE])
return robot, pose, hand, kinect, gripper, br, bl, tl, tr
def reset(robot_ip, port, simulation=True):
"""
Resets the RoboDK's Items position
:param robot_ip: string IP of the robot controller
:param port: integer port of the robot controller
:param simulation: boolean to enable simulation or move the real robot
:return: RDK: Connection to the RoboDK application
"""
# Import libraries here for optimization
from robolink.robolink import ITEM_TYPE_ROBOT, Robolink
from robodk.robodk import KUKA_2_Pose
import sys
import os
RDK = Robolink()
# Turn off automatic rendering (faster simulation)
RDK.Render(False)
# Initialize robot
# Search all items for a valid robot type (assumes only one robot is loaded)
robot = None
for station in RDK.ItemList():
for item in station.Childs():
if item.type == ITEM_TYPE_ROBOT:
robot = item
break
if robot is not None:
break
if not robot.Valid():
print("[ROBODK]: No robot is loaded to the station")
raise Exception("[ROBODK]: No Robot found!!")
# Check Home, Targets and Items Loaded
pose = RDK.Item('Target') # Target
sheet = RDK.Item('Sheet') # Sheet item
br = RDK.Item('Bottom Right') # Bottom Right Corner of Fabric
bl = RDK.Item('Bottom Left') # Bottom Left Corner of Fabric
tl = RDK.Item('Top Left') # Top Left Corner of Fabric
tr = RDK.Item('Top Right') # Top Right Corner of Fabric
hand = RDK.Item('Hand') # Get Hand model
light = RDK.Item('Light Source') # Get Light Source
# Check if everything is loaded correctly
if pose.type == -1 or sheet.type == -1 or bl.type == -1 or tl.type == -1 or tr.type == -1 or br.type == -1 or hand.type == -1 or light.type == -1:
sys.exit('[ROBODK]: Cannot obtain simulation items: Check if everything is loaded')
# Always start from home
try:
# Move to Home
robot.setJoints([0, 90, 0, 0, 0, 0])
except Exception as e:
print(f'[ROBODK]: Cant Move Robot Home\n{e}')
# Reset Sheet
sheet.Delete()
sheet = RDK.AddFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Models/Sheet.stl'))
sheet.setPoseAbs(KUKA_2_Pose(list((635, 0, 770, 90, 0, 0))))
sheet.setColor([255 / 255, 170 / 255, 127 / 255, 1])
# Reset Fabric Points
"""!---------Targets are with respect to the Robot Base Reference so its better to use setPoseAbs() to keep everything in the universal coordinate system---------!"""
br.setPoseAbs(KUKA_2_Pose(list((785, -250, 770, 45, -180, 0))))
bl.setPoseAbs(KUKA_2_Pose(list((485, -250, 770, -45, 180, 0))))
tl.setPoseAbs(KUKA_2_Pose(list((485, 250, 770, 45, 0, 180))))
tr.setPoseAbs(KUKA_2_Pose(list((785, 250, 770, -45, 0, 180))))
# Reset Hand
hand.setPoseAbs(KUKA_2_Pose(list((500, 1000, 1400, -90, 0, 0))))
# Reset Target
pose.setPoseAbs(KUKA_2_Pose(list((600, 250, 770, 0, 0, -90))))
# It is important to provide the reference frame and the tool frames when generating programs offline
robot.setPoseFrame(robot.PoseFrame())
robot.setPoseTool(robot.PoseTool())
# Define Light Source
light.setPoseAbs(KUKA_2_Pose(list((1000, 0, 2500, 0, 205, 0))))
# Close all cameras just in case
RDK.Cam2D_Close()
# enable render and speed up simulation (big data for neural)
RDK.Render(True)
RDK.setSimulationSpeed(5) # x faster (5 default)
robot.setZoneData(3) # Set the rounding parameter (Also known as: CNT, APO/C_DIS, ZoneData, Blending radius, cornering, ...)
RDK.ShowRoboDK() # Show RoboDK window
RDK.setWindowState(2) # Show RoboDK window
"""
# Script execution types
RUNMODE_SIMULATE = 1 # performs the simulation moving the robot (default)
RUNMODE_QUICKVALIDATE = 2 # performs a quick check to validate the robot movements
RUNMODE_MAKE_ROBOTPROG = 3 # makes the robot program
RUNMODE_MAKE_ROBOTPROG_AND_UPLOAD = 4 # makes the robot program and updates it to the robot
RUNMODE_MAKE_ROBOTPROG_AND_START = 5 # makes the robot program and starts it on the robot (independently from the PC)
RUNMODE_RUN_ROBOT = 6 # moves the real robot from the PC (PC is the client, the robot behaves like a server)
"""
if simulation:
RDK.setRunMode(1) # simulate only
else:
RDK.setRunMode(6) # move real robot and simulation
connect(robot_ip, port, robot)
# robot.setSpeed(speed_linear=speed*1000, speed_joints=110.0, accel_linear=-1, accel_joints=-1) # Set linear speed in mm/s (-1 = no change)
# robot.setSpeedJoints(-1, 110.0, -1, -1) # Set joint speed in deg/s for rotary joints and mm/s for linear joints
# robot.setAcceleration() # Set linear acceleration in mm/s2
# robot.setAccelerationJoints() # Set joint acceleration in deg/s2 for rotary joints and mm/s2 for linear joints
# robot.setParamRobotTool(tool_mass=5, tool_cog=None) # set tool_mass in kg as float, tool_cog = list(x, y, z) tool center of gravity as [x,y,z] with respect to the robot flange
RDK.Command('DisplayCurves', value='0')
# RDK.Command('SetSize3D', value='650x610')
# RDK.Command('Trace', value='On')
# RDK.setFlagsRoboDK(flags=[FLAG_ROBODK_TREE_ACTIVE])
RDK.setViewPose(KUKA_2_Pose(list((-635, -500, -6000, 0, 0, -40))))
return RDK
def connect(ip, port, robot):
"""
Make connection with robot
:param ip: string IP of the robot controller
:param port: port of the robot controller
:param robot: Item robot in RoboDK
:return: None
"""
try:
# Set the connection parameters
robot.setConnectionParams(ip, port, '/', 'anonymous', '')
# Connect to the robot, 0 = failed, 1 = success
success = robot.Connect()
# Check connection
if success == 0:
print('[ROBODK]: Failed to Connect to Robot')
robot.Disconnect()
else:
print('[ROBODK]: Connection Successful')
# It is important to provide the reference frame and the tool frames when generating programs offline
robot.setPoseFrame(robot.PoseFrame())
robot.setPoseTool(robot.PoseTool())
status, status_msg = robot.ConnectedState()
# Robot connection status
# ROBOTCOM_PROBLEMS = -3
# ROBOTCOM_DISCONNECTED = -2
# ROBOTCOM_NOT_CONNECTED = -1
# ROBOTCOM_READY = 0
# ROBOTCOM_WORKING = 1
# ROBOTCOM_WAITING = 2
# ROBOTCOM_UNKNOWN = -1000
# Print Robot status
print("[ROBODK]: Robot Status: " + status_msg)
except Exception as e:
print("[ROBODK]: {}".format(e))
def target_joints(RDK, target):
"""
Move robot to a Target and get the joints
:param RDK: link to the RDK instance
:param target: Item target in RoboDk
:return: list with robot angles [J1, J2, J3, J4, J5, J6, J7]
"""
from robolink.robolink import ITEM_TYPE_ROBOT
from robodk.robodk import tr, transl
# Faster Calculations ( Robot not moving )
RDK.Render(False)
RDK.setRunMode(1) # Simulate only
# Initialize robot
# Search all items for a valid robot type (assumes only one robot is loaded)
robot = None
for station in RDK.ItemList():
for item in station.Childs():
if item.type == ITEM_TYPE_ROBOT:
robot = item
break
if robot is not None:
break
if not robot.Valid():
print("[ROBODK]: No robot is loaded to the station")
raise Exception("[ROBODK]: No Robot found!!")
# Calculate pose
pose = robot.Pose()*transl(target[0], target[1], target[2])
# Find angles
angles = robot.SolveIK(pose, robot.Joints(), robot.PoseTool(), robot.PoseFrame())
RDK.Render(True)
return angles
def simulation(RDK, x, y, z, rot_x, rot_y, rot_z, robot, pose, hand_model, hand_state, gripper_model, gripper_state, waitGripper, kinect_model, kinect_tilt, world_kalman_hand_tip_right, human_state, robot_corner, b_right, b_left, t_left, t_right, startSim, check_col=True):
"""
Update robot, hand, gripper, fabric, kinect and cloud skeleton
:param RDK: link to RoboDK instance
:param x: float hand distance in x axis
:param y: float hand distance in y axis
:param z: float hand distance in z axis
:param rot_x: float hand angle in x axis
:param rot_y: float hand angle in y axis
:param rot_z: float hand angle in z axis
:param robot: Item robot in RoboDK
:param pose: Item target in RoboDK
:param hand_model: Item hand in RoboDK
:param hand_state: string hand state
:param gripper_model: Item gripper in RoboDK
:param gripper_state: string gripper state
:param waitGripper: boolean to wait for gripper to grab fabric
:param kinect_model: Item kinect in RoboDK
:param kinect_tilt: float angle of tiltness of Kinect from floor plane
:param world_kalman_hand_tip_right: list with world kalman points of the operator's hand tip
:param human_state: string with human state
:param robot_corner: string with robot's starting corner
:param b_right: Item bottom right in RoboDK
:param b_left: Item bottom left in RoboDK
:param t_left: Item top left in RoboDK
:param t_right: Item top right in RoboDK
:param startSim: boolean to start simulation after fabric is grabbed
:param check_col: boolean to check for collisions
:return: string with robot_state, boolean that simulation started, boolean to wait for gripper to grab the fabric
"""
# Import libraries only for this function to minimize memory usage
from robodk.robodk import transl, rotx, roty, rotz, TxyzRxyz_2_Pose, Pose_2_TxyzRxyz, KUKA_2_Pose, Pose_2_KUKA, tr
import numpy as np
import os
RDK.Render(False) # Faster Calculations
"""
if check_col:
# Check for current collisions
check_collisions = RDK.Collisions()
# if collision then move to home
if check_collisions != 0:
print("Collision detected. Moving to Home Position")
# robot.setJoints([0, 90, 0, 0, 0, 0])
"""
# Move Robot to Target
# joints = robot.SolveIK(x, y, z)
# robot.setJoints([joints[0], joints[1], joints[2], joints[3], joints[4], joints[5]])
# Calculate Robot Pose to move to (x, y, z = mm, rotations = radians
# rot_x, rot_y, rot_z = rot_x * np.pi/180, rot_y * np.pi/180, rot_z * np.pi/18
# pose = robot.Pose()*transl(int(x), int(y), int(z))*rotx(int(rot_x))*roty(int(rot_y))*rotz(int(rot_z))
kinect_pos = Pose_2_KUKA(kinect_model.Pose())
hand_tar = Pose_2_KUKA(hand_model.Pose())
# tar = Pose_2_KUKA(pose.Pose())
# tar = list((tar[0] + int(x), tar[1] + int(z), tar[2] + int(y), int(rot_x), int(rot_z), int(rot_y)))
# tar = list((tar[0] + int(x), tar[1] + int(y), tar[2] + int(z), int(rot_y), int(rot_x), int(rot_z)))
# tar = list((tar[0] - int(x), tar[1] + int(z), tar[2] + int(y), int(rot_z*180/np.pi), int(rot_y*180/np.pi), int(rot_x*180/np.pi)))
# tar = list((tar[0] - int(x), tar[1] + int(z), tar[2] + int(y), rot_x, tar[4], tar[5]))
# tar = list((tar[0] - int(x), tar[1] + int(z), tar[2] + int(y), int(rot_z), tar[4], int(rot_y)))
# tar = list((tar[0] - int(x), tar[1] + int(z), tar[2] + int(y), int(rot_z), int(rot_x), int(rot_y)))
# tar[4] could be the wrist rotation from quaternions
# pose = TxyzRxyz_2_Pose([int(x)/2, int(y)/2, int(z)/2, 0, 0, 0])
# pose = robot.Pose().setPos([int(x), int(y), int(z)])
# Update hand pose in simulation Space
# hand_model.setPose(KUKA_2_Pose(list((kinect_pos[0] - int(world_kalman_hand_tip_right[0]), kinect_pos[1] + int(world_kalman_hand_tip_right[2]), kinect_pos[2] + int(world_kalman_hand_tip_right[1]) + np.sin(kinect_tilt*np.pi/180)*world_kalman_hand_tip_right[2], int(rot_z), 0, int(rot_y)))))
hand_pose = Pose_2_KUKA(kinect_model.Pose()*transl(-world_kalman_hand_tip_right[0], -world_kalman_hand_tip_right[1], world_kalman_hand_tip_right[2]))
# pose.setPose(KUKA_2_Pose(tar))
hand_model.setPose(KUKA_2_Pose(list((hand_pose[0] + OFFSET_DEPTH, hand_pose[1], hand_pose[2], rot_z, 0, rot_y))))
# Update Hand State
# -------------- Color = [r, g, b, a] (from 0 to 1 scale) (a = opacity, 0=transparent, 1=solid)
# GREEN = Closed, RED = UNKNOWN/NOT TRACKED, NUDE = OPEN
if hand_state == 'OPEN':
hand_model.setColor([255/255, 170/255, 127/255, 1])
elif hand_state == 'CLOSED':
hand_model.setColor([85/255, 255/255, 0/255, 1])
else:
hand_model.setColor([255/255, 0/255, 0/255, 1])
# Update Gripper State
# -------------- Color = [r, g, b, a] (from 0 to 1 scale) (a = opacity, 0=transparent, 1=solid)
# GREEN = Closed, BLACK = OPEN
if gripper_state == 'OPEN':
gripper_model.setColor([15/255, 15/255, 15/255, 1])
elif gripper_state == 'CLOSED':
gripper_model.setColor([85/255, 255/255, 0/255, 1])
RDK.Render(True) # Enable simulation again
# RDK.Update()
# Try moving to point if inside reach else stay to previous point
if human_state == 'READY' and not waitGripper:
if startSim:
# Break Loop
startSim = False
# Wait for Gripper to catch the fabric
# Move once and wait for gripper
waitGripper = True
# Calculate robot corner to move to
# Keep the orientation the same and change the xyz coordinates to match the corner
pose_tar = Pose_2_KUKA(pose.Pose())
if robot_corner == 'BR':
"""
br_tar = Pose_2_KUKA(b_right.Pose())
pose.setPose(KUKA_2_Pose(list((br_tar[0], br_tar[1], br_tar[2], br_tar[3], br_tar[4], br_tar[5]))))
"""
pose.setPose(b_right.Pose())
elif robot_corner == 'BL':
"""
bl_tar = Pose_2_KUKA(b_left.Pose())
pose.setPose(KUKA_2_Pose(list((bl_tar[0], bl_tar[1], bl_tar[2], bl_tar[3], bl_tar[4], bl_tar[5]))))
"""
pose.setPose(b_left.Pose())
elif robot_corner == 'TL':
"""
tl_tar = Pose_2_KUKA(t_left.Pose())
pose.setPose(KUKA_2_Pose(list((tl_tar[0], tl_tar[1], tl_tar[2], tl_tar[3], tl_tar[4], tl_tar[5]))))
"""
pose.setPose(t_left.Pose())
elif robot_corner == 'TR':
"""
tr_tar = Pose_2_KUKA(t_right.Pose())
pose.setPose(KUKA_2_Pose(list((tr_tar[0], tr_tar[1], tr_tar[2], tr_tar[3], tr_tar[4], tr_tar[5]))))
"""
pose.setPose(t_right.Pose())
try:
"""
# check if move is free of collisions
issues = robot.MoveJ_Test(robot.Joints(), pose.Joints())
can_move_joints = (issues == 0)
if can_move_joints and len(tr(pose.Joints())) == 7:
# Move Robot
robot.MoveJ(pose)
# Update robot state
robot_state = 'MOVING'
else:
robot_state = 'IDLE'
"""
# Move Robot on Simulation Only
# RDK.setRunMode(1) # Simulate only
# robot.MoveJ(pose)
# Move real robot
RDK.setRunMode(6)
# change robot's joint limits to the original ones to avoid joint limitations
robot.setJointLimits(MODIFIED_LOWER_LIMITS, MODIFIED_UPPER_LIMITS)
tar = tr(pose.Joints())
"""
Change the position of the Joints because KUKA LWR IV+ has declared the third joint as an External Joint.
KUKA LWR IV+ Joints = [A1, A2, E1, A3, A4, A5, A6] and RoboDK sends the joints as [A1, A2, A3, A4, A5, A6, E1]
"""
robot.MoveJ([tar[0, 0], tar[0, 1], tar[0, 3], tar[0, 4], tar[0, 5], tar[0, 6], tar[0, 2]])
# change robot's joint limits to the modified ones to compute the real joint angles
robot.setJointLimits(ORIGINAL_LOWER_LIMITS, ORIGINAL_UPPER_LIMITS)
# Update robot state
robot_state = 'MOVING'
if not waitGripper:
tar = Pose_2_KUKA(pose.Pose())
# tar = list((tar[0] - int(x), tar[1] + int(z), tar[2] + int(y), int(rot_z), tar[4], int(rot_y)))
tar = list((tar[0] - int(x), tar[1] + int(z), tar[2] + int(y), tar[3], tar[4], tar[5]))
pose.setPose(KUKA_2_Pose(tar))
"""
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data.txt'), 'a') as file:
file.write('{}, {}, {}\n'.format(tar[0], tar[1], tar[2]))
"""
if check_col:
# Check for current collisions
check_collisions = RDK.Collisions()
# if collision then move to home
if check_collisions != 0:
print("[ROBODK]: Collision detected. Moving to Home Position")
robot.setJoints([0, 90, 0, 0, 0, 0])
# Update robot state
robot_state = 'IDLE'
waitGripper = False
startSim = True
except Exception as e:
print(f'[ROBODK]: {e}')
# Update robot state
robot_state = 'IDLE'
waitGripper = False
startSim = True
robot.setJointLimits(ORIGINAL_LOWER_LIMITS, ORIGINAL_UPPER_LIMITS)
else:
robot_state = 'IDLE'
return robot_state, startSim, waitGripper
def _simulation(RDK, x, y, z, rot_y, rot_z, robot, pose, hand_model, hand_state, gripper_model, gripper_state, waitGripper, kinect_model, world_kalman_hand_tip_right, human_state, robot_corner, b_right, b_left, t_left, t_right, startSim, robot_path, check_col=True, sim=True):
"""
Update robot, hand, gripper, fabric, kinect and cloud skeleton
:param RDK: link to RoboDK instance
:param x: float hand distance in x axis
:param y: float hand distance in y axis
:param z: float hand distance in z axis
:param rot_y: float hand angle in x axis
:param rot_z: float hand angle in z axis
:param robot: Item robot in RoboDK
:param pose: Item pose in RoboDK
:param hand_model: Item hand in RoboDK
:param hand_state: string with hand state
:param gripper_model: Item gripper in RoboDK
:param gripper_state: string with gripper state
:param waitGripper: boolean to wait for gripper to grab fabric
:param kinect_model: Item kinect in RoboDK
:param world_kalman_hand_tip_right: list with kalman world hand tip coordinates
:param human_state: string with human state
:param robot_corner: string with robot's starting corner
:param b_right: Item bottom right in RoboDK
:param b_left: Item bottom left in RoboDK
:param t_left: Item top left in RoboDk
:param t_right: Item top right in RoboDK
:param startSim: boolean to start updating models and view
:param robot_path: list with robot movement
:param check_col: boolean to check for collisions
:param sim: boolean to simulate
:return: string with robot state, boolean that simmulation stared, boolean to wait for gripper to grab fabric, list with robot movement poits
"""
# Import libraries only for this function to minimize memory usage
from robodk.robodk import transl, KUKA_2_Pose, Pose_2_KUKA, tr
RDK.Render(False) # Faster Calculations
# Update hand pose in simulation Space
hand_pose = Pose_2_KUKA(kinect_model.Pose()*transl(-world_kalman_hand_tip_right[0], -world_kalman_hand_tip_right[1], world_kalman_hand_tip_right[2]))
hand_model.setPoseAbs(KUKA_2_Pose(list((hand_pose[0] + OFFSET_DEPTH, hand_pose[1], hand_pose[2], rot_z, 0, rot_y))))
# Update Hand State
# -------------- Color = [r, g, b, a] (from 0 to 1 scale) (a = opacity, 0=transparent, 1=solid)
# GREEN = Closed, RED = UNKNOWN/NOT TRACKED, NUDE = OPEN
if hand_state == 'OPEN':
hand_model.setColor([255/255, 170/255, 127/255, 1])
elif hand_state == 'CLOSED':
hand_model.setColor([85/255, 255/255, 0/255, 1])
else:
hand_model.setColor([255/255, 0/255, 0/255, 1])
# Update Gripper State
# -------------- Color = [r, g, b, a] (from 0 to 1 scale) (a = opacity, 0=transparent, 1=solid)
# GREEN = Closed, BLACK = OPEN
if gripper_state == 'OPEN':
gripper_model.setColor([15/255, 15/255, 15/255, 1])
elif gripper_state == 'CLOSED':
gripper_model.setColor([85/255, 255/255, 0/255, 1])
RDK.Render(True) # Enable simulation again
# Try moving to point if inside reach else stay to previous point
if human_state == 'READY' and not waitGripper:
if startSim:
# Break Loop
startSim = False
# Wait for Gripper to catch the fabric
# Move once and wait for gripper
waitGripper = True
# Calculate robot corner to move to
# Keep the orientation the same and change the xyz coordinates to match the corner
if robot_corner == 'BR':
pose.setPoseAbs(b_right.PoseAbs())
elif robot_corner == 'BL':
pose.setPoseAbs(b_left.PoseAbs())
elif robot_corner == 'TL':
pose.setPoseAbs(t_left.PoseAbs())
elif robot_corner == 'TR':
pose.setPoseAbs(t_right.PoseAbs())
try:
# change robot's joint limits to the original ones to avoid joint limitations
robot.setJointLimits(MODIFIED_LOWER_LIMITS, MODIFIED_UPPER_LIMITS)
if RDK.RunMode() == 1:
tar = tr(pose.Joints())
# Move Robot on Simulation Only
robot.MoveJ([tar[0, 0], tar[0, 1], tar[0, 2], tar[0, 3], tar[0, 4], tar[0, 5], tar[0, 6]])
elif RDK.RunMode() == 6:
# Move real robot
tar = tr(pose.Joints())
"""
Change the position of the Joints because KUKA LWR IV+ has declared the third joint as an External Joint.
KUKA LWR IV+ Joints = [A1, A2, E1, A3, A4, A5, A6] and RoboDK sends the joints as [A1, A2, A3, A4, A5, A6, E1]
"""
robot.MoveJ([tar[0, 0], tar[0, 1], tar[0, 3], tar[0, 4], tar[0, 5], tar[0, 6], tar[0, 2]])
else:
pass
# change robot's joint limits to the modified ones to compute the real joint angles
robot.setJointLimits(ORIGINAL_LOWER_LIMITS, ORIGINAL_UPPER_LIMITS)
# store robot path
robot_xyz = Pose_2_KUKA(pose.PoseAbs())
robot_path.append([robot_xyz[0], robot_xyz[1], robot_xyz[2]])
# Update robot state
robot_state = 'MOVING'
if not waitGripper:
tar = Pose_2_KUKA(pose.PoseAbs())
tar = list((tar[0] - int(x), tar[1] + int(z), tar[2] + int(y), tar[3], tar[4], tar[5]))
pose.setPoseAbs(KUKA_2_Pose(tar))
if check_col:
# Check for current collisions
check_collisions = RDK.Collisions()
# if collision then move to home
if check_collisions != 0:
print("[ROBODK]: Collision detected. Moving to Home Position")
robot.setJoints([0, 90, 0, 0, 0, 0])
# Update robot state
robot_state = 'IDLE'
waitGripper = False
startSim = True
except Exception as e:
print('[ROBODK]: {}'.format(e))
# Update robot state
robot_state = 'IDLE'
waitGripper = False
startSim = True
robot.setJointLimits(ORIGINAL_LOWER_LIMITS, ORIGINAL_UPPER_LIMITS)
else:
robot_state = 'IDLE'
return robot_state, startSim, waitGripper, robot_path
def move_up(RDK, robot, pose):
"""
Move robot up after the fabric is grabbed
:param RDK: link to RoboDK instance
:param robot: Item robot in RoboDK
:param pose: Item pose in RoboDK
:return: Boolean
"""
from robodk.robodk import KUKA_2_Pose, Pose_2_KUKA, tr
# Move real robot
# change robot's joint limits to the original ones to avoid joint limitations
robot.setJointLimits(MODIFIED_LOWER_LIMITS, MODIFIED_UPPER_LIMITS)
tar = Pose_2_KUKA(pose.PoseAbs())
tar = list((tar[0], tar[1], tar[2] + 60, tar[3], tar[4], tar[5]))
pose.setPoseAbs(KUKA_2_Pose(tar))
RDK.Render(False)
tar = tr(pose.Joints())
""" Change the position of the Joints because KUKA LWR IV+ has declared the third joint as an External Joint.
KUKA LWR IV+ Joints = [A1, A2, E1, A3, A4, A5, A6] and RoboDK sends the joints as [A1, A2, A3, A4, A5, A6, E1] """
robot.MoveJ([tar[0, 0], tar[0, 1], tar[0, 3], tar[0, 4], tar[0, 5], tar[0, 6], tar[0, 2]])
# change robot's joint limits to the modified ones to compute the real joint angles
robot.setJointLimits(ORIGINAL_LOWER_LIMITS, ORIGINAL_UPPER_LIMITS)
return True
def collaborate(RDK, x, y, z, robot, pose, robot_path, kinect_model, hand_model, gripper_model, hand_state, gripper_state, world_kalman_hand_tip_right, rot_y, rot_z):
"""
Human robot collaboration fuction to move robot according to human operator
:param RDK: link to robodk instance
:param x: distance moved in x axis
:param y: distance moved in y axis
:param z: distance moved in z axis
:param robot: Item robot in RoboDK
:param pose: Item pose in RoboDK
:param robot_path: list with robot movement
:param kinect_model: Item kinect in RoboDK
:param hand_model: Item hand in RoboDK
:param gripper_model: Item gripper in RoboDK
:param hand_state: string with operator's hand state
:param gripper_state: string with gripper's state
:param world_kalman_hand_tip_right: list with kalman world coordinates of the operator's hand tip
:param rot_y: float rotation in y axis
:param rot_z: float rotation in z axis
:return: string with robot state, list with robot movements
"""
from robodk.robodk import transl, rotx, roty, rotz, TxyzRxyz_2_Pose, Pose_2_TxyzRxyz, KUKA_2_Pose, Pose_2_KUKA, tr
import numpy as np
RDK.Render(False) # Faster Calculations
# Try moving to point if inside reach else stay to previous point
try:
# Move real robot
# change robot's joint limits to the original ones to avoid joint limitations
robot.setJointLimits(MODIFIED_LOWER_LIMITS, MODIFIED_UPPER_LIMITS)
tar = Pose_2_KUKA(pose.PoseAbs())
tar = list((tar[0] - int(x), tar[1] + int(z), tar[2] + int(y), tar[3], tar[4], tar[5]))
pose.setPoseAbs(KUKA_2_Pose(tar))
# Simulation only
if RDK.RunMode() == 1:
RDK.Render(False) # Faster Calculations
# Update hand pose in simulation Space
hand_pose = Pose_2_KUKA(kinect_model.Pose() * transl(-world_kalman_hand_tip_right[0], -world_kalman_hand_tip_right[1], world_kalman_hand_tip_right[2]))
hand_model.setPoseAbs(KUKA_2_Pose(list((hand_pose[0] + OFFSET_DEPTH, hand_pose[1], hand_pose[2], rot_z, 0, rot_y))))
# Update Hand State
# -------------- Color = [r, g, b, a] (from 0 to 1 scale) (a = opacity, 0=transparent, 1=solid)
# GREEN = Closed, RED = UNKNOWN/NOT TRACKED, NUDE = OPEN
if hand_state == 'OPEN':
hand_model.setColor([255 / 255, 170 / 255, 127 / 255, 1])
elif hand_state == 'CLOSED':
hand_model.setColor([85 / 255, 255 / 255, 0 / 255, 1])
else:
hand_model.setColor([255 / 255, 0 / 255, 0 / 255, 1])
# Update Gripper State
# -------------- Color = [r, g, b, a] (from 0 to 1 scale) (a = opacity, 0=transparent, 1=solid)
# GREEN = Closed, BLACK = OPEN
if gripper_state == 'OPEN':
gripper_model.setColor([15 / 255, 15 / 255, 15 / 255, 1])
elif gripper_state == 'CLOSED':
gripper_model.setColor([85 / 255, 255 / 255, 0 / 255, 1])
tar = tr(pose.Joints())
# Move Robot on Simulation Only
robot.MoveL([tar[0, 0], tar[0, 1], tar[0, 2], tar[0, 3], tar[0, 4], tar[0, 5], tar[0, 6]])
RDK.Render(True) # Enable simulation again
# Real Robot movement
elif RDK.RunMode() == 6:
RDK.Render(False)
tar = tr(pose.Joints())
""" Change the position of the Joints because KUKA LWR IV+ has declared the third joint as an External Joint.
KUKA LWR IV+ Joints = [A1, A2, E1, A3, A4, A5, A6] and RoboDK sends the joints as [A1, A2, A3, A4, A5, A6, E1] """
robot.MoveJ([tar[0, 0], tar[0, 1], tar[0, 3], tar[0, 4], tar[0, 5], tar[0, 6], tar[0, 2]])
else:
pass
# change robot's joint limits to the modified ones to compute the real joint angles
robot.setJointLimits(ORIGINAL_LOWER_LIMITS, ORIGINAL_UPPER_LIMITS)
# store robot path
robot_xyz = Pose_2_KUKA(pose.PoseAbs())
robot_path.append([robot_xyz[0], robot_xyz[1], robot_xyz[2]])
# Update robot state
robot_state = 'MOVING'
except Exception as e:
print('[ROBODK]: {}'.format(e))
# Update robot state
robot_state = 'IDLE'
robot.setJointLimits(ORIGINAL_LOWER_LIMITS, ORIGINAL_UPPER_LIMITS)
return robot_state, robot_path