-
Notifications
You must be signed in to change notification settings - Fork 0
/
zabers.py
401 lines (331 loc) · 11.4 KB
/
zabers.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
#!/usr/bin/env python3
import numpy as np
import math
from termios import TCIFLUSH, tcflush
import sys
import os
import threading
import zaber.serial as zs
import keyboard
from failing import errorloc
from grabPorts import grabPorts
default_amount = 10000
default_haxes = {
"colther": ["z", "x", "y"],
"camera": ["x", "z", "y"],
"tactile": ["y", "x", "z"],
}
default_step_sizes = {"colther": 0.49609375, "camera": 0.1905, "tactile": 0.1905}
default_positions = {
"colther": {"x": 235000, "y": 127000, "z": 0},
"camera": {"x": 49507, "y": 535098, "z": 287000},
"tactile": {"x": 336000, "y": 380000, "z": 270000},
}
zaber_models_default = {
"colther": {"x": "end_X-LSQ150B", "y": "end_A-LSQ150B", "z": "end_A-LSQ150B"},
"camera": {"x": "end_LSM100B-T4", "y": "end_LSM100B-T4", "z": "end_LSM100B-T4"},
"tactile": {"x": "end_LSM100B-T4", "y": "end_LSM100B-T4", "z": "end_LSM100B-T4"},
}
zaber_models_end_default = {
"end_X-LSQ150B": 305381,
"end_A-LSQ150B": 305381,
"end_LSM100B-T4": 533333,
"end_LSM200B-T4": 1066667,
}
class Zaber(grabPorts):
"""
Zaber class developed by Ivan Ezquerra-Romano at the Action & Body lab (2018-2023)
"""
def __init__(self, n_device, name, surname, chained_to = None, winPort=None):
self.ports = grabPorts()
self.ports.zaberPort(name, surname, winPort)
self.home = False
if not chained_to: # number 1 device is chosen to lead the Daisy chain
self.port = zs.AsciiSerial(self.ports.zaber_port)
self.device = zs.AsciiDevice(self.port, n_device)
else:
self.port = chained_to.port
self.device = zs.AsciiDevice(self.port, n_device)
def __repr__(self):
return "Device {} at port {}".format(self.device, self.port)
################################################################################################################
################################################################################################################
############################ FUNCTIONS
################################################################################################################
################################################################################################################
def move(zaber, amount, rules):
amount = revDirection(zaber.device_name, zaber.axis, rules, amount)
try:
response = zaber.device.move_rel(amount)
except:
response = zaber.move_rel(amount)
handleOutOfRange(
response,
zaber,
amount,
zaber_models_default,
zaber_models_end_default,
)
def grabPositions(device):
positions = {}
for axis in ["x", "y", "z"]:
try:
pos = device[axis].send("/get pos")
except:
pos = device[axis].device.send("/get pos")
positions[axis] = int(pos.data)
return positions
def setUpBigThree(axes):
### Zabers
colther1 = Zaber(1, name = "serial", surname = "-A104BTL5")
colther2 = Zaber(2, name = "serial", surname = "-A104BTL5", chained_to = colther1)
colther3 = Zaber(3, name = "serial", surname = "-A104BTL5", chained_to = colther1)
print("Colther loaded")
camera12 = Zaber(1, name = "modem", surname = 1424301)
camera1 = camera12.device.axis(1)
camera2 = camera12.device.axis(2)
camera3 = Zaber(1, name = "serial", surname = "-AH0614UB")
print("Camera loaded")
tactile12 = Zaber(1, name = "modem", surname = 759331)
tactile1 = tactile12.device.axis(1)
tactile2 = tactile12.device.axis(2)
tactile3 = Zaber(1, name = "serial", surname = "-AB0NZPLK")
print("Tactile loaded")
colther = {
axes["colther"][0]: colther1,
axes["colther"][1]: colther2,
axes["colther"][2]: colther3,
}
camera = {
axes["camera"][0]: camera1,
axes["camera"][1]: camera2,
axes["camera"][2]: camera3,
}
tactile = {
axes["tactile"][0]: tactile1,
axes["tactile"][1]: tactile2,
axes["tactile"][2]: tactile3,
}
zabers = {"colther": colther, "camera": camera, "tactile": tactile}
for zaber in zabers:
for axis in zabers[zaber]:
zabers[zaber][axis].device_name = zaber
zabers[zaber][axis].axis = axis
return zabers
def gridCalculation(
zaber,
grid_separation,
rules,
positions,
step_size=default_step_sizes,
dim=[3, 3],
):
"""
Function to estimate a grid from a point. The initial point becomes the centre cell.
grid_separation in millimetres
"""
if len(dim) < 2:
raise Exception("dim should be of the form [x, y]")
# print(pos)
# step_size = step_size[zaber]
one_cm_zaber_steps = grid_separation / (step_size[zaber] / 10000)
grid = {}
# Calculate origin
x_origin = positions[zaber]["x"] - revDirection(zaber, "x", rules, one_cm_zaber_steps)
y_origin = positions[zaber]["y"] - revDirection(zaber, "y", rules, one_cm_zaber_steps)
if x_origin < 0 or y_origin < 0:
x_origin = int(max(0, x_origin))
y_origin = int(max(0, y_origin))
print(
f"Either X or Y were found to be negative values.\n They were set to 0, but the grid won't apply properly"
)
# print(x_origin)
# print(y_origin)
cell = 1
for i in np.arange(dim[1]):
for j in np.arange(dim[0]):
# print(pos[zaber]['z'])
grid[str(cell)] = {
"x": math.ceil(
x_origin + revDirection(zaber, "x", rules, one_cm_zaber_steps * j)
),
"y": math.ceil(
y_origin + revDirection(zaber, "y", rules, one_cm_zaber_steps * i)
),
"z": positions[zaber]["z"],
}
# print(j, i)
cell += 1
print(f"\nGrid calculated for {zaber}\n")
return grid
def revDirection(zaber, axis, rule, number):
"""
Function to get the negative value of a number depending on zaber rules
"""
if not rule[zaber][axis]:
number = -number
return number
def moveAxisTo(zabers, zaber, axis, amount, speed = 153600 * 4):
try:
zabers[zaber][axis].device.send("/set maxspeed {}".format(speed))
zabers[zaber][axis].device.move_abs(amount)
except:
zabers[zaber][axis].send("/set maxspeed {}".format(speed))
zabers[zaber][axis].move_abs(amount)
def movetostartZabersConcu(
zabers, zaber, axes, pos = default_positions, speed = 153600 * 4
):
"""
This function is to move one set of Zabers to a defined positions (pos)
"""
def startOneAxis(zaber, d):
if isinstance(pos, dict):
posc = pos[d]
else:
posc = pos
if posc < 0:
posc = 0
print(f"\n Moving axis {d} of {zaber} to {posc}\n")
try:
zabers[zaber][d].device.send("/set maxspeed {}".format(speed))
zabers[zaber][d].device.move_abs(math.ceil(posc))
except:
zabers[zaber][d].send("/set maxspeed {}".format(speed))
zabers[zaber][d].move_abs(math.ceil(posc))
threads_zabers = []
for d in axes:
sz = threading.Thread(target=startOneAxis, args=[zaber, d])
threads_zabers.append(sz)
for x in threads_zabers:
x.start()
for x in threads_zabers:
x.join()
def homingZabersConcu(zabers, axes=None, concurrently = True, speed = 153600 * 4):
"""
This function is to home all zabers in a Zaber object concurrently
"""
def homeOneAxis(kaxes, d, speed):
print(f"\n Homing {d} axis of {kaxes}\n")
try:
zabers[kaxes][d].device.send("/set maxspeed {}".format(speed))
if zabers[kaxes][d].home:
zabers[kaxes][d].device.move_abs(0)
else:
zabers[kaxes][d].device.home()
zabers[kaxes][d].home = True
except:
zabers[kaxes][d].send("/set maxspeed {}".format(speed))
if zabers[kaxes][d].home:
zabers[kaxes][d].move_abs(0)
else:
zabers[kaxes][d].home()
zabers[kaxes][d].home = True
if axes == None:
axes = {}
for kzabers, vzabers in zabers.items():
axes[kzabers] = ["z", "y", "x"]
print("\n Homing to default axes order [z, y, x] \n")
speed = str(speed)
# print(axes)
for kaxes, vaxes in axes.items():
threads_zabers = []
for d in vaxes:
hz = threading.Thread(target=homeOneAxis, args=[kaxes, d, speed])
threads_zabers.append(hz)
for x in threads_zabers:
x.start()
if not concurrently:
x.join()
if concurrently:
for x in threads_zabers:
x.join()
def cmToSteps(z_d, step_size):
"""
Function to translate centimetres into Zaber steps
"""
z_d_microm = z_d * 10000
z_steps = z_d_microm / step_size
return int(round(z_steps))
def stepsToCm(steps, step_size):
"""
Function to translate Zaber steps into centimetres
"""
microms = steps * step_size
d_cm = microms / 10000
return round(d_cm, 2)
def readReply(command):
return [
"Message type: " + command.message_type,
"Device address: " + str(command.device_address),
"Axis number: " + str(command.axis_number),
"Message ID: " + str(command.message_id),
"Reply flag: " + str(command.reply_flag),
"Device status: " + str(command.device_status),
"Warning flag: " + str(command.warning_flag),
"Data: " + str(command.data),
"Checksum: " + str(command.checksum),
]
def changeAmount(key):
while True:
if not keyboard.is_pressed(key):
tcflush(sys.stdin, TCIFLUSH)
new_amount = input("\n\nAmount to move: ")
try:
new_amount = int(new_amount)
break
except Exception as e:
errorloc(e)
return new_amount
def handleOutOfRange(
response,
zaber,
amount,
models,
ends,
):
try:
pos = zaber.send("/get pos")
except:
pos = zaber.device.send("/get pos")
if response.data == "BADDATA":
if int(pos.data) < abs(amount):
try:
zaber.move_abs(0)
except:
zaber.device.move_abs(0)
print("OUT OF START")
else:
model = models[zaber.device_name][zaber.axis]
try:
zaber.move_abs(ends[model])
except:
zaber.device.move_abs(ends[model])
print("OUT OF END")
def reducegrid(dictionary, list_to_remove):
"""
Function to remove a given keys froma dictionary and redefine the keys from '1' upwards
"""
for i in list_to_remove:
del dictionary[i]
reduced_grid = {}
for i, v in enumerate(dictionary.values()):
reduced_grid[f"{i+1}"] = v
return reduced_grid
def findHeight(delta):
time_adjust = 0.8
slope = -2.2589600000000023
intercept = 15.199626666666676
height = (intercept - delta) / slope - time_adjust
if height < 0:
height = abs(height)
elif height > 0:
height = 4
height = round(height, 2)
# clamp within range
low_bound = 4
high_bound = 6.5
if height < low_bound:
height = low_bound
if height > high_bound:
height = high_bound
return height