-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRun_Dynamic_Robot
632 lines (512 loc) · 23.5 KB
/
Run_Dynamic_Robot
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
#!/usr/bin/env python3
# -- BEGIN LICENSE BLOCK ----------------------------------------------
# Copyright 2021 FZI Forschungszentrum Informatik
# Created on behalf of Universal Robots A/S
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -- END LICENSE BLOCK ------------------------------------------------
#
# ---------------------------------------------------------------------
# !\file
#
# \author Felix Exner mauch@fzi.de
# \date 2021-08-05
#
#
# ---------------------------------------------------------------------
import sys
import time
import rospy
import actionlib
from control_msgs.msg import FollowJointTrajectoryAction, FollowJointTrajectoryGoal
from trajectory_msgs.msg import JointTrajectoryPoint
from controller_manager_msgs.srv import SwitchControllerRequest, SwitchController
from controller_manager_msgs.srv import LoadControllerRequest, LoadController
from controller_manager_msgs.srv import ListControllers, ListControllersRequest
import geometry_msgs.msg as geometry_msgs
from cartesian_control_msgs.msg import (
FollowCartesianTrajectoryAction,
FollowCartesianTrajectoryGoal,
CartesianTrajectoryPoint,
)
# Compatibility for python2 and python3
if sys.version_info[0] < 3:
input = raw_input
# If your robot description is created with a tf_prefix, those would have to be adapted
JOINT_NAMES = [
"shoulder_pan_joint",
"shoulder_lift_joint",
"elbow_joint",
"wrist_1_joint",
"wrist_2_joint",
"wrist_3_joint",
]
# All of those controllers can be used to execute joint-based trajectories.
# The scaled versions should be preferred over the non-scaled versions.
JOINT_TRAJECTORY_CONTROLLERS = [
"scaled_pos_joint_traj_controller",
"scaled_vel_joint_traj_controller",
"pos_joint_traj_controller",
"vel_joint_traj_controller",
"forward_joint_traj_controller",
]
# All of those controllers can be used to execute Cartesian trajectories.
# The scaled versions should be preferred over the non-scaled versions.
CARTESIAN_TRAJECTORY_CONTROLLERS = [
"pose_based_cartesian_traj_controller",
"joint_based_cartesian_traj_controller",
"forward_cartesian_traj_controller",
]
# We'll have to make sure that none of these controllers are running, as they will
# be conflicting with the joint trajectory controllers
CONFLICTING_CONTROLLERS = ["joint_group_vel_controller", "twist_controller"]
class TrajectoryClient:
"""Small trajectory client to test a joint trajectory"""
def __init__(self):
rospy.init_node("test_move")
timeout = rospy.Duration(5)
self.switch_srv = rospy.ServiceProxy(
"controller_manager/switch_controller", SwitchController
)
self.load_srv = rospy.ServiceProxy("controller_manager/load_controller", LoadController)
self.list_srv = rospy.ServiceProxy("controller_manager/list_controllers", ListControllers)
try:
self.switch_srv.wait_for_service(timeout.to_sec())
except rospy.exceptions.ROSException as err:
rospy.logerr("Could not reach controller switch service. Msg: {}".format(err))
sys.exit(-1)
self.joint_trajectory_controller = JOINT_TRAJECTORY_CONTROLLERS[0]
self.cartesian_trajectory_controller = CARTESIAN_TRAJECTORY_CONTROLLERS[0]
def send_joint_trajectory(self):
"""Creates a trajectory and sends it using the selected action server"""
# make sure the correct controller is loaded and activated
self.switch_controller(self.joint_trajectory_controller)
trajectory_client = actionlib.SimpleActionClient(
"{}/follow_joint_trajectory".format(self.joint_trajectory_controller),
FollowJointTrajectoryAction,
)
# Wait for action server to be ready
timeout = rospy.Duration(5)
if not trajectory_client.wait_for_server(timeout):
rospy.logerr("Could not reach controller action server.")
sys.exit(-1)
# Create and fill trajectory goal
goal = FollowJointTrajectoryGoal()
goal.trajectory.joint_names = JOINT_NAMES
# The following list are arbitrary positions
position_list = [[0, -1.57, -1.57, 0, 0, 0]]
duration_list = [3.0, 7.0, 10.0]
for i, position in enumerate(position_list):
point = JointTrajectoryPoint()
point.positions = position
point.time_from_start = rospy.Duration(duration_list[i])
goal.trajectory.points.append(point)
self.ask_confirmation(position_list)
rospy.loginfo("Executing trajectory using the {}".format(self.joint_trajectory_controller))
trajectory_client.send_goal(goal)
trajectory_client.wait_for_result()
result = trajectory_client.get_result()
rospy.loginfo("Trajectory execution finished in state {}".format(result.error_code))
def send_cartesian_trajectory(self):
"""Creates a Cartesian trajectory and sends it using the selected action server"""
self.switch_controller(self.cartesian_trajectory_controller)
#----------------------Pickup offset input from user---------------------------
offset_bool = 0
while True:
ask = input("Is there an offset in pickup? Enter y or n: ")
if ask!="y" and ask!="n":
print("Please enter y or n: ")
elif ask=="y":
offset_bool = 1
break
else:
break
offset_dir = "None"
if offset_bool == 1:
while True:
inp = input("Enter pickup offset Direction, L for left, R for right: ")
if inp.lower() == "l":
offset_dir = "l"
break
elif inp.lower() == "r":
offset_dir = "r"
break
else:
print("Please enter either L or R")
offset_skip = 0
if offset_bool == 1:
while True:
inp = input("Enter offset number: ")
try:
a = int(inp)
if a < 1:
print("Skip cannot be less than 1, please enter again")
elif a>=1:
offset_skip = a
break
except:
print("Please enter a number")
off_mov = -1
if offset_dir == "l":
off_mov = 1
print(f"The offset direction selected is: {offset_dir.upper()}")
print(f"The offset skips entered is: {offset_skip}")
#-----------------------Drop Input from user------------------------------
dir = ""
while True:
inp = input("Enter Direction relative to pickup point, L for left, R for right: ")
if inp.lower() == "l":
dir = "l"
break
elif inp.lower() == "r":
dir = "r"
break
else:
print("Please enter either L or R")
skip = 0
while True:
inp = input("Enter skips: ")
try:
a = int(inp)
if a < 1:
print("Skip cannot be less than 1, please enter again")
elif a>=1:
skip = a
break
except:
print("Please enter a number")
print(f"The direction selected is: {dir.upper()}")
print(f"The skips entered is: {skip}")
mov = -1
if dir == "l":
mov = 1
# Gripper
from std_msgs.msg import Int32
from robotiq_hande_ros_driver.srv import gripper_service
gripper_srv = rospy.ServiceProxy('gripper_service', gripper_service)
# Reset Gripper position
response = gripper_srv(position=0, speed=255, force=255)
# make this dynamic
coord = ""
with open(r"/home/ise.ros/Shyam/current_pos.txt") as f:
coord = f.readline()
coord = coord[3:-2]
cur_x = 0
cur_y = 0
try:
cur_x = coord.split(" ")[0]
except:
cur_x = coord.split(" ")[0]
try:
cur_y = coord.split(" ")[1]
except:
cur_y = coord.split(" ")[1]
current_pos = []
print("cur x = ", cur_x)
print("cur y = ", cur_y)
current_pos.append(float(cur_x))
current_pos.append(float(cur_y))
#current_pos = [float(cur_x), float(cur_y)]
diff_x = -0.208 - current_pos[0]
diff_y = -0.3 - current_pos[1]
inital_car_coord = current_pos[0] + diff_x + 0.033*offset_bool*off_mov*offset_skip
pick_up_cart_coord = inital_car_coord - 0.019
pick_up_y = current_pos[1] + diff_y #equate it to -0.3
###### 1) ------------------------Go to Hangers and Close Gripper-----------------------------------
# make sure the correct controller is loaded and activated
goal = FollowCartesianTrajectoryGoal()
trajectory_client = actionlib.SimpleActionClient(
"{}/follow_cartesian_trajectory".format(self.cartesian_trajectory_controller),
FollowCartesianTrajectoryAction,
)
# Wait for action server to be ready
timeout = rospy.Duration(5)
if not trajectory_client.wait_for_server(timeout):
rospy.logerr("Could not reach controller action server.")
sys.exit(-1)
# The following list are arbitrary positions
# Change to your own needs if desired
pose_list = [
geometry_msgs.Pose(
geometry_msgs.Vector3(pick_up_cart_coord, pick_up_y, 0.645), geometry_msgs.Quaternion(1, 0, 0, 1)
),
geometry_msgs.Pose(
geometry_msgs.Vector3(pick_up_cart_coord, pick_up_y - 0.15, 0.645), geometry_msgs.Quaternion(1, 0, 0, 1)
)
]
#duration_list = [2, 4, 6]
duration_list = [0.4, 0.8]
for i, pose in enumerate(pose_list):
point = CartesianTrajectoryPoint()
point.pose = pose
point.time_from_start = rospy.Duration(duration_list[i])
goal.trajectory.points.append(point)
self.ask_confirmation(pose_list)
#time.sleep(7)
rospy.loginfo(
"Executing trajectory using the {}".format(self.cartesian_trajectory_controller)
)
trajectory_client.send_goal(goal)
trajectory_client.wait_for_result()
result = trajectory_client.get_result()
rospy.loginfo("Trajectory execution finished in state {}".format(result.error_code))
response = gripper_srv(position=180, speed=255, force=255)
###### 2) ------------------------Pick-up Hangers-----------------------------------
# make sure the correct controller is loaded and activated
goal = FollowCartesianTrajectoryGoal()
trajectory_client = actionlib.SimpleActionClient(
"{}/follow_cartesian_trajectory".format(self.cartesian_trajectory_controller),
FollowCartesianTrajectoryAction,
)
# Wait for action server to be ready
timeout = rospy.Duration(5)
if not trajectory_client.wait_for_server(timeout):
rospy.logerr("Could not reach controller action server.")
sys.exit(-1)
pose_list = [
geometry_msgs.Pose(
geometry_msgs.Vector3(inital_car_coord, pick_up_y - 0.15 + 0.02, 0.645), geometry_msgs.Quaternion(1, 0, 0, 1)
),
geometry_msgs.Pose(
geometry_msgs.Vector3(inital_car_coord, pick_up_y - 0.15 + 0.02, 0.735), geometry_msgs.Quaternion(1, 0, 0, 1)
)
]
#duration_list = [2, 4, 6, 8, 10, 12 ,14]
duration_list = [0.4, 0.8]
for i, pose in enumerate(pose_list):
point = CartesianTrajectoryPoint()
point.pose = pose
point.time_from_start = rospy.Duration(duration_list[i])
goal.trajectory.points.append(point)
#self.ask_confirmation(pose_list)
rospy.loginfo(
"Executing trajectory using the {}".format(self.cartesian_trajectory_controller)
)
trajectory_client.send_goal(goal)
trajectory_client.wait_for_result()
result = trajectory_client.get_result()
rospy.loginfo("Trajectory execution finished in state {}".format(result.error_code))
response = gripper_srv(position=255, speed=255, force=255)
mov_pos_cartesian_coord = inital_car_coord + mov*skip*0.033
###### 3) ------------------------Move to a drop position-----------------------------------
# make sure the correct controller is loaded and activated
goal = FollowCartesianTrajectoryGoal()
trajectory_client = actionlib.SimpleActionClient(
"{}/follow_cartesian_trajectory".format(self.cartesian_trajectory_controller),
FollowCartesianTrajectoryAction,
)
# Wait for action server to be ready
timeout = rospy.Duration(5)
if not trajectory_client.wait_for_server(timeout):
rospy.logerr("Could not reach controller action server.")
sys.exit(-1)
# The following list are arbitrary positions
# Change to your own needs if desired
pose_list = [
geometry_msgs.Pose(
geometry_msgs.Vector3(inital_car_coord, pick_up_y - 0.15 + 0.02 + 0.06, 0.735), geometry_msgs.Quaternion(1, 0, 0, 1)
),
geometry_msgs.Pose(
geometry_msgs.Vector3(mov_pos_cartesian_coord, pick_up_y - 0.15 + 0.02 + 0.06, 0.735), geometry_msgs.Quaternion(1, 0, 0, 1)
),
geometry_msgs.Pose(
geometry_msgs.Vector3(mov_pos_cartesian_coord, pick_up_y - 0.15 + 0.02, 0.732), geometry_msgs.Quaternion(1, 0, 0, 1)
)
]
#duration_list = [2]
duration_list = [0.4, 0.8, 1.2]
for i, pose in enumerate(pose_list):
point = CartesianTrajectoryPoint()
point.pose = pose
point.time_from_start = rospy.Duration(duration_list[i])
goal.trajectory.points.append(point)
#self.ask_confirmation(pose_list)
#time.sleep(15)
rospy.loginfo(
"Executing trajectory using the {}".format(self.cartesian_trajectory_controller)
)
trajectory_client.send_goal(goal)
trajectory_client.wait_for_result()
result = trajectory_client.get_result()
rospy.loginfo("Trajectory execution finished in state {}".format(result.error_code))
response = gripper_srv(position=180, speed=255, force=255)
###### 4) ------------------------Drop Hangers-----------------------------------
# make sure the correct controller is loaded and activated
goal = FollowCartesianTrajectoryGoal()
trajectory_client = actionlib.SimpleActionClient(
"{}/follow_cartesian_trajectory".format(self.cartesian_trajectory_controller),
FollowCartesianTrajectoryAction,
)
# Wait for action server to be ready
timeout = rospy.Duration(5)
if not trajectory_client.wait_for_server(timeout):
rospy.logerr("Could not reach controller action server.")
sys.exit(-1)
# The following list are arbitrary positions
# Change to your own needs if desired
pose_list = [
geometry_msgs.Pose(
geometry_msgs.Vector3(mov_pos_cartesian_coord, pick_up_y - 0.15 + 0.02, 0.64), geometry_msgs.Quaternion(1, 0, 0, 1)
)
]
#duration_list = [2]
duration_list = [0.5]
for i, pose in enumerate(pose_list):
point = CartesianTrajectoryPoint()
point.pose = pose
point.time_from_start = rospy.Duration(duration_list[i])
goal.trajectory.points.append(point)
#self.ask_confirmation(pose_list)
#time.sleep(15)
rospy.loginfo(
"Executing trajectory using the {}".format(self.cartesian_trajectory_controller)
)
trajectory_client.send_goal(goal)
trajectory_client.wait_for_result()
result = trajectory_client.get_result()
rospy.loginfo("Trajectory execution finished in state {}".format(result.error_code))
response = gripper_srv(position=0, speed=255, force=255)
safe_move_car_coord = mov_pos_cartesian_coord - 0.024
###### 5) ------------------------Move to a safe position-----------------------------------
# make sure the correct controller is loaded and activated
goal = FollowCartesianTrajectoryGoal()
trajectory_client = actionlib.SimpleActionClient(
"{}/follow_cartesian_trajectory".format(self.cartesian_trajectory_controller),
FollowCartesianTrajectoryAction,
)
# Wait for action server to be ready
timeout = rospy.Duration(5)
if not trajectory_client.wait_for_server(timeout):
rospy.logerr("Could not reach controller action server.")
sys.exit(-1)
# The following list are arbitrary positions
# Change to your own needs if desired
pose_list = [
geometry_msgs.Pose(
geometry_msgs.Vector3(safe_move_car_coord, pick_up_y - 0.15 + 0.02, 0.64), geometry_msgs.Quaternion(1, 0, 0, 1)
),
geometry_msgs.Pose(
geometry_msgs.Vector3(safe_move_car_coord, pick_up_y, 0.64), geometry_msgs.Quaternion(1, 0, 0, 1)
)
]
#duration_list = [2]
duration_list = [0.4, 0.8]
for i, pose in enumerate(pose_list):
point = CartesianTrajectoryPoint()
point.pose = pose
point.time_from_start = rospy.Duration(duration_list[i])
goal.trajectory.points.append(point)
#self.ask_confirmation(pose_list)
#time.sleep(15)
rospy.loginfo(
"Executing trajectory using the {}".format(self.cartesian_trajectory_controller)
)
trajectory_client.send_goal(goal)
trajectory_client.wait_for_result()
result = trajectory_client.get_result()
rospy.loginfo("Trajectory execution finished in state {}".format(result.error_code))
###############################################################################################
# #
# Methods defined below are for the sake of safety / flexibility of this demo script only. #
# If you just want to copy the relevant parts to make your own motion script you don't have #
# to use / copy all the functions below. #
# #
###############################################################################################
def ask_confirmation(self, waypoint_list):
"""Ask the user for confirmation. This function is obviously not necessary, but makes sense
in a testing script when you know nothing about the user's setup."""
rospy.logwarn("The robot will move to the following waypoints: \n{}".format(waypoint_list))
confirmed = False
valid = False
while not valid:
input_str = input(
"Please confirm that the robot path is clear of obstacles.\n"
"Keep the EM-Stop available at all times. You are executing\n"
"the motion at your own risk. Please type 'y' to proceed or 'n' to abort: "
)
valid = input_str in ["y", "n"]
if not valid:
rospy.loginfo("Please confirm by entering 'y' or abort by entering 'n'")
else:
confirmed = input_str == "y"
if not confirmed:
rospy.loginfo("Exiting as requested by user.")
sys.exit(0)
def choose_controller(self):
"""Ask the user to select the desired controller from the available list."""
rospy.loginfo("Available trajectory controllers:")
for (index, name) in enumerate(JOINT_TRAJECTORY_CONTROLLERS):
rospy.loginfo("{} (joint-based): {}".format(index, name))
for (index, name) in enumerate(CARTESIAN_TRAJECTORY_CONTROLLERS):
rospy.loginfo("{} (Cartesian): {}".format(index + len(JOINT_TRAJECTORY_CONTROLLERS), name))
choice = -1
while choice < 0:
input_str = input(
"Please choose a controller by entering its number (Enter '0' if "
"you are unsure / don't care): "
)
try:
choice = int(input_str)
if choice < 0 or choice >= len(JOINT_TRAJECTORY_CONTROLLERS) + len(
CARTESIAN_TRAJECTORY_CONTROLLERS
):
rospy.loginfo(
"{} not inside the list of options. "
"Please enter a valid index from the list above.".format(choice)
)
choice = -1
except ValueError:
rospy.loginfo("Input is not a valid number. Please try again.")
if choice < len(JOINT_TRAJECTORY_CONTROLLERS):
self.joint_trajectory_controller = JOINT_TRAJECTORY_CONTROLLERS[choice]
return "joint_based"
self.cartesian_trajectory_controller = CARTESIAN_TRAJECTORY_CONTROLLERS[
choice - len(JOINT_TRAJECTORY_CONTROLLERS)
]
return "cartesian"
def switch_controller(self, target_controller):
"""Activates the desired controller and stops all others from the predefined list above"""
other_controllers = (
JOINT_TRAJECTORY_CONTROLLERS
+ CARTESIAN_TRAJECTORY_CONTROLLERS
+ CONFLICTING_CONTROLLERS
)
other_controllers.remove(target_controller)
srv = ListControllersRequest()
response = self.list_srv(srv)
for controller in response.controller:
if controller.name == target_controller and controller.state == "running":
return
srv = LoadControllerRequest()
srv.name = target_controller
self.load_srv(srv)
srv = SwitchControllerRequest()
srv.stop_controllers = other_controllers
srv.start_controllers = [target_controller]
srv.strictness = SwitchControllerRequest.BEST_EFFORT
self.switch_srv(srv)
if __name__ == "__main__":
client = TrajectoryClient()
# The controller choice is obviously not required to move the robot. It is a part of this demo
# script in order to show all available trajectory controllers.
trajectory_type = client.choose_controller()
if trajectory_type == "joint_based":
client.send_joint_trajectory()
elif trajectory_type == "cartesian":
client.send_cartesian_trajectory()
else:
raise ValueError(
"I only understand types 'joint_based' and 'cartesian', but got '{}'".format(
trajectory_type
)
)