-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDevonics_FR_Controller.py
More file actions
458 lines (411 loc) · 16.1 KB
/
Copy pathDevonics_FR_Controller.py
File metadata and controls
458 lines (411 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
from ast import Try
import time, sys, pygame
from threading import Thread, Lock
from pygame import joystick
import math
import os
import inputs
os.environ["SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS"] = "1"
from fairino import Robot
###############################################################
# CONTROLLER MAPPING #
# X & Y axis movement: Left stick #
# Z movement: right stick (up and down) #
# Rotate robot wrist (up/down): Right Stick (left to right) #
# Rotate robot wrist: left/right trigger #
# A: Opens/Closes gripper (if one exists) #
# X: Move to Home Pose #
# Y: Clears any robot errors #
# B: Stops robot movement #
###############################################################
# CONSTANTS
ROBOT_IP = '192.168.57.2' # CHANGE TO MATCH YOUR DEVICE
SOFT_LIMIT = [-175.0, 175.0, -265.0, 85.0, -160.0
, 160.0, -265.0, 85.0, -175.0, 175.0, -175.0, 175.0]
HOME_POS = [-80, -65, -80, -130, 90, 0]
PACKING_POS = [-125, 10, -158, -122, 0.012, 0] #Specific for FR16
L_LEFT = 'll'
L_RIGHT = 'lr'
L_UP = 'lu'
L_DOWN = 'ld'
R_LEFT = 'rl'
R_RIGHT = 'rr'
R_UP = "ru"
R_DOWN = "rd"
LT = 'lt'
RT = 'rt'
global is_moving
def truncate(number):
factor = 10.0 ** 2
return math.trunc(number * factor) / factor
def checkNeutralPos(joystick):
axes = joystick.get_numaxes()
for m in range(axes - 2):
axis = truncate(float(joystick.get_axis(m) * 1))
if(abs(axis) > 0.1):
return False
for m in range(4, 6):
axis = truncate(float(joystick.get_axis(m) * 1))
if(abs(axis) < 0.9):
return False
return True
def toggleGripper(robot, gripperOpen):
# Opens/closes gripper
if(gripperOpen):
try:
print(robot.MoveGripper(1, 0, 80, 80, 5000,0))
except:
print("Error opening gripper")
else:
try:
print(robot.MoveGripper(1, 100, 80, 80, 5000,0))
except:
print("Error closing gripper")
return not gripperOpen
def moveToSafety(robot, index, joint_pos, lock):
# After joint out of bounds, reset to safe pose
if joint_pos[index] < 0:
joint_pos[index] += 7
else:
joint_pos[index] -= 7
if(lock.locked):
lock.release()
with lock:
time.sleep(0.5)
robot.MoveJ(joint_pos, 0, 0)
time.sleep(0.5)
def checkJointLimits(robot, lock):
try:
err, j_pos = robot.GetActualJointPosDegree()
print(f"Actual Position: msg: {err}, value: {j_pos}")
except:
print("error when getting actual joint positions")
return
for i in range(len(j_pos) - 1):
if (j_pos[i] - 5 <= SOFT_LIMIT[i*2]) or j_pos[i] + 5 >= SOFT_LIMIT[i*2 + 1]:
robot.ImmStopJOG()
print(f"Joint {i}: Too close to soft limit")
time.sleep(.5)
moveToSafety(robot, i, j_pos, lock)
return True
return False
def moveAxisThread(robot, lock, joystick, mv_input):
if lock.locked():
print("Move axis call rejected: mutex populated")
return
# Move according to user input
with lock:
index = -1
print("Move axis called")
if(mv_input == L_LEFT):
err = robot.StartJOG(2, 1, 1, 200)
print(f"Move axis returned: {err}")
if(err == 0):
index = 0
elif(mv_input == L_RIGHT):
try:
err = robot.StartJOG(2, 1, 0, 200)
print(f"Move axis returned: {err}")
if(err == 0):
index = 0
except:
print("Error sending move commands")
elif(mv_input == L_DOWN):
err = robot.StartJOG(2, 2, 1, 200)
print(f"Move axis returned: {err}")
if(err == 0):
index = 1
elif(mv_input == L_UP):
err = robot.StartJOG(2, 2, 0, 200)
print(f"Move axis returned: {err}")
if err == 0:
index = 1
elif(mv_input == R_UP):
try:
err = robot.StartJOG(2, 3, 0, 200)
print(f"Move axis returned: {err}")
if err == 0:
index = 3
except:
print("Error in vertical jog")
elif(mv_input == R_DOWN):
err = robot.StartJOG(2, 3, 1, 200)
print(f"Move axis returned: {err}")
if err == 0:
index = 3
elif(mv_input == R_RIGHT):
try:
err = robot.StartJOG(0, 5, 0, 180)
if err == 0:
index = 2
except:
print("Error rotating end tool")
elif(mv_input == R_LEFT):
try:
err = robot.StartJOG(0, 5, 1, 180)
if err == 0:
index = 2
except:
print("Error rotating end tool")
elif(mv_input == LT):
try:
err = robot.StartJOG(0, 4, 1, 180)
if err == 0:
index = 4
except:
print("Error in rotating joint 4")
elif(mv_input == RT):
try:
err = robot.StartJOG(0, 4, 0, 180)
if err == 0:
index = 5
except:
print("Error in rotating joint 4")
if(index == -1):
return
stop_thread = Thread(target=stopAxis, args=[robot, joystick, index, lock])
# stop_thread.daemon = True
stop_thread.start()
time.sleep(.25)
# robot.ImmStopJOG()
def stopAxis(robot, joystick, JSAxel_index, lock):
if(JSAxel_index == -1):
print("No axis recieved by stopAxis()")
return
print("Stop axis called")
# While the user holds the joystick, let it jog. When stick is released, stop the movement
while True:
axel = float(joystick.get_axis(JSAxel_index))
# print(axel)
if(JSAxel_index < 4):
if abs(axel) < 0.1:
err = robot.ImmStopJOG()
print(f"Stop jog err: {err}")
while(err != 0):
time.sleep(0.1)
print("ERROR in stopping robot!!!")
err = robot.ImmStopJOG()
return
else:
if abs(axel) >= 1:
err = robot.ImmStopJOG()
while(err != 0):
time.sleep(0.1)
print("ERROR in stopping robot!!!")
err = robot.ImmStopJOG()
return
if checkJointLimits(robot, lock):
err = robot.ImmStopJOG()
while(err != 0):
time.sleep(0.1)
print("ERROR in stopping robot!!!")
err = robot.ImmStopJOG()
return
time.sleep(0.1)
def ResetErrors(robot):
print("Error reset activated")
err = robot.ResetAllError()
print(f"ResetAllError() response: {err}")
if(err != 0):
print("Robot broke safety conditions. Please check WebApp for error msg")
def run(robot, robot_speed, gripperConnected):
# Initialization, PyGame window creation, etc
gripperOpen = True
is_moving = False
pygame.init()
screen = pygame.display.set_mode((1280, 720))
screen.fill("purple")
pygame.display.flip()
lock = Lock()
clock = pygame.time.Clock()
joy_stat = 0
running = True
axis = [0, 0, 0, 0, 0, 0]
straxis = "0,0,0,0,"
while running:
pygame.joystick.init()
joystick_count = pygame.joystick.get_count()
# Connects controller
while pygame.joystick.get_count() != 0 and joy_stat == 0:
for i in range(joystick_count):
joystick = pygame.joystick.Joystick(i)
joystick.init()
print("Controller connected")
time.sleep(1)
joy_stat = 1
break
# Inits controller
while pygame.joystick.get_count() == 0:
pygame.joystick.quit()
joy_stat = 0
print("Waiting for controller to connect...")
time.sleep(1)
pygame.joystick.init()
continue
# Refresh reads
pygame.joystick.Joystick(0).init
clock.tick(60)
# Scans each action from the joystick
for event in pygame.event.get():
# If you press one of the four buttons on the right...
if event.type == pygame.JOYBUTTONDOWN:
# Pressing A will open/close the gripper (If one is connected)
if event.button == 0:
print("A Has Been Pressed")
if(gripperConnected):
gripperOpen = toggleGripper(robot, gripperOpen)
else:
print("No gripper connected")
# Pressing the B button is meant to act as an extra way to stop robot motion
elif event.button == 1:
print("B Has Been Pressed")
robot.ImmStopJOG()
time.sleep(1)
# Pressing the Y button will clear any errors that might be in the web app (joint limits etc)
elif event.button == 3:
print("Y Has Been Pressed")
ResetErrors(robot)
# If X is pressed, the robot will return to its "Home position" (neutral, standing pose)
elif event.button == 2:
print("X Has Been Pressed")
robot.MoveJ(HOME_POS, 0, 0)
time.sleep(1)
# These are for functionality when buttons are released. They currently have no use
elif event.type == pygame.JOYBUTTONUP:
if event.button == 0:
print("A Has Been Uped")
elif event.button == 1:
print("B Has Been Uped")
elif event.button == 3:
print("Y Has Been Uped")
elif event.button == 2:
print("X Has Been Uped")
# If you're moving the joysticks...
elif event.type == pygame.JOYAXISMOTION:
# If movement is done and joystick is neutral, make sure that is_moving is False
if(is_moving and checkNeutralPos(joystick)):
is_moving = False
# If is_moving is True following normal behavior, skip over the reads to repvent thread spamming
elif(is_moving):
continue
# Get info on controller axis reads
axes = joystick.get_numaxes()
straxis = ""
fl_axis = []
# Scan each axis
for m in range(axes):
axis[m] = truncate(float(joystick.get_axis(m) * 1))
fl_axis.append(axis[m])
straxis = straxis + str(float(axis[m]) * 1) + ","
print("Controller axices: ", straxis)
# If left stick is pressed right...
if(fl_axis[0] > .7):
print("L-Right")
mv_thread = Thread(target=moveAxisThread, args=[robot, lock, joystick, L_RIGHT])
mv_thread.start()
is_moving = True
# If left stick is pressed Left...
if(fl_axis[0] < -.7):
print("L-Left")
mv_thread = Thread(target=moveAxisThread, args=[robot, lock, joystick, L_LEFT])
mv_thread.start()
is_moving = True
# If left stick is pressed down...
elif(fl_axis[1] > .7):
print('L back')
mv_thread = Thread(target=moveAxisThread, args=[robot, lock, joystick, L_DOWN])
mv_thread.start()
is_moving = True
# If left stick is pressed up...
elif(fl_axis[1] < -.7):
print('L Forward')
mv_thread = Thread(target=moveAxisThread, args=[robot, lock, joystick, L_UP])
mv_thread.start()
is_moving = True
# If right stick is pressed right...
elif(fl_axis[2] > 0.7):
print('R Right')
mv_thread = Thread(target=moveAxisThread, args=[robot, lock, joystick, R_RIGHT])
mv_thread.start()
is_moving = True
# If left stick is pressed left...
elif(fl_axis[2] < -0.7):
print('R left')
mv_thread = Thread(target=moveAxisThread, args=[robot, lock, joystick, R_LEFT])
mv_thread.start()
is_moving = True
# If left stick is pressed up...
elif(fl_axis[3] > 0.7):
print('R Back')
mv_thread = Thread(target=moveAxisThread, args=[robot, lock, joystick, R_UP])
mv_thread.start()
is_moving = True
# If left stick is pressed down...
elif(fl_axis[3] < -0.7):
print('R Forward')
mv_thread = Thread(target=moveAxisThread, args=[robot, lock, joystick, R_DOWN])
mv_thread.start()
is_moving = True
# If left trigger is pressed...
elif(fl_axis[4] > 0):
print('lt')
mv_thread = Thread(target=moveAxisThread, args=[robot, lock, joystick, LT])
mv_thread.start()
is_moving = True
# If right trigger is pressed...
elif(fl_axis[5] > 0):
print('rt')
mv_thread = Thread(target=moveAxisThread, args=[robot, lock, joystick, RT])
mv_thread.start()
is_moving = True
# If no motion...
elif(is_moving and checkNeutralPos(joystick)):
err = robot.ImmStopJOG()
while(err != 0):
time.sleep(0.1)
print("ERROR in stopping robot!!!")
err = robot.ImmStopJOG()
is_moving = False
time.sleep(0.008)
if event.type == pygame.QUIT:
running = False
pygame.quit()
sys.exit()
time.sleep(0.008)
def main():
gripperConnected = False # Change this to True if you wish to connect a gripper to this code
controller_connected = False
robot_connected = False
# Waits for controller to appear on the list of devices
while not controller_connected:
for device in inputs.devices:
if 'X-Box' in device.name:
controller_connected = True
print("Controller Port Connected")
break
if not controller_connected:
print("Please connect controller...")
time.sleep(0.5)
# Waits until robot connection is ebstablished
while not robot_connected:
try:
robot = Robot.RPC(ROBOT_IP)
robot_connected = True
break
except:
time.sleep(0.5)
robot_connected = False
time.sleep(3)
# If gripper is configured, set above value to True and this will connect it (currently configured for DH)
if(gripperConnected):
print(robot.GetGripperConfig())
print(robot.SetGripperConfig(4,0,0,0))
time.sleep(.5)
robot.ActGripper(1,1)
robot_speed = 40 # Set the Point-To-Point speed of your robot
robot.SetSpeed(robot_speed)
run_thread = Thread(target = run, args=[robot, robot_speed])
run_thread.run()
if __name__ == "__main__":
main()
pygame.quit()