-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmotor.py
More file actions
1423 lines (1238 loc) · 56.8 KB
/
motor.py
File metadata and controls
1423 lines (1238 loc) · 56.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import time
import json
gTIMEOUT = 100 # seconds to wait for a response from the ESP32
class Motor(object):
# indicate if there is any motion happening
isRunning = False
def __init__(self, parent=None):
self._parent = parent
# do we have a coreXY setup?
self.isCoreXY = False
self.nMotors = 4
self.lastDirection = np.zeros((self.nMotors))
self.backlash = np.zeros((self.nMotors))
self.stepSize = np.ones((self.nMotors))
self.maxStep = np.ones((self.nMotors))*np.inf
self.minStep = np.ones((self.nMotors))*(-np.inf)
self.currentDirection = np.zeros((self.nMotors))
self.currentPosition = np.zeros((self.nMotors))
# Per-axis hardware-direction sign (+1 or -1), indexed as [A, X, Y, Z]
# Applied internally at the firmware boundary: outbound commands are
# multiplied by this sign before being sent, and inbound positions are
# multiplied by this sign before being reported. This lets callers keep
# a consistent physical/user coordinate frame while motor.py absorbs
# any wiring polarity flips. Configured via setup_motor() (either via
# an explicit `direction` argument or by passing a negative stepSize).
self.direction = np.ones((self.nMotors), dtype=np.int8)
self.minPosX = -np.inf
self.minPosY = -np.inf
self.minPosZ = -np.inf
self.minPosA = -np.inf
self.maxPosX = np.inf
self.maxPosY = np.inf
self.maxPosZ = np.inf
self.maxPosA = np.inf
self.stepSizeX = 1
self.stepSizeY = 1
self.stepSizeZ = 1
self.stepSizeA = 1
self.DEFAULT_ACCELERATION = 1000000
self.motorAxisOrder = [0,1,2,3] # motor axis is 1,2,3,0 => X,Y,Z,T # FIXME: Hardcoded
# register a callback function for the motor status on the serial loop
if hasattr(self._parent, "serial"):
self._parent.serial.register_callback(self._callback_motor_status, pattern="steppers")
# Register callback for stagescan completion signal: {"stagescan":{},"qid":0,"success":1}
self._parent.serial.register_callback(self._callback_stagescan_complete, pattern="stagescan")
# announce a function that is called when we receive a position update through the callback
self._callbackPerKey = {}
self.nCallbacks = 10
self._callbackPerKey = self.init_callback_functions(nCallbacks=self.nCallbacks) # only one is used for now
print(self._callbackPerKey)
# Stage scan completion state
self._stagescan_complete = False
self._stagescan_callbacks = [] # List of callbacks to call when stagescan completes
# move motor to wake them up #FIXME: Should not be necessary!
#self.move_stepper(steps=(1,1,1,1), speed=(1000,1000,1000,1000), is_absolute=(False,False,False,False))
#self.move_stepper(steps=(-1,-1,-1,-1), speed=(1000,1000,1000,1000), is_absolute=(False,False,False,False))
def init_callback_functions(self, nCallbacks=10):
''' initialize the callback functions '''
_callbackPerKey = {}
self.nCallbacks = nCallbacks
for i in range(nCallbacks):
_callbackPerKey[i] = []
return _callbackPerKey
def _callback_motor_status(self, data):
''' cast the json in the form:
{
"qid": 0,
"steppers": [{
"stepperid": 1,
"position": 1000,
"isDone": 1
}]
}
into the position array of the motors '''
try:
nSteppers = len(data["steppers"])
stepSizes = np.array((self.stepSizeA, self.stepSizeX, self.stepSizeY, self.stepSizeZ))
for iMotor in range(nSteppers):
stepperID = data["steppers"][iMotor]["stepperid"]
# Hardware returns raw steps in firmware frame; convert to physical units
# in user frame: phys = hw_steps * stepSize * direction. The direction sign
# hides any wiring polarity flip from the caller.
self.currentPosition[stepperID] = (
data["steppers"][iMotor]["position"]
* stepSizes[stepperID]
* self.direction[stepperID]
)
if callable(self._callbackPerKey[0]):
self._callbackPerKey[0](self.currentPosition) # we call the function with the value
except Exception as e:
print("Error in _callback_motor_status: ", e)
def _callback_stagescan_complete(self, data):
"""
Callback for stagescan completion signal from firmware.
Expected JSON format:
{
"stagescan": {},
"qid": 0,
"success": 1
}
Args:
data: JSON data dictionary from firmware
"""
try:
# Check if this is a completion signal (success key present)
if "success" in data:
self._stagescan_complete = True
success = data.get("success", 0)
self._parent.logger.debug(f"Stage scan complete signal received: success={success}")
# Call all registered completion callbacks
for callback in self._stagescan_callbacks:
try:
callback(data)
except Exception as e:
self._parent.logger.error(f"Error in stagescan completion callback: {e}")
else:
self._parent.logger.debug("Received stagescan data without completion signal.")
except Exception as e:
print(f"Error in _callback_stagescan_complete: {e}")
def register_stagescan_callback(self, callback):
"""
Register a callback function to be called when stagescan completes.
Args:
callback: Function to call with completion data
"""
if callback not in self._stagescan_callbacks:
self._stagescan_callbacks.append(callback)
def unregister_stagescan_callback(self, callback):
"""
Unregister a stagescan completion callback.
Args:
callback: Function to unregister
"""
if callback in self._stagescan_callbacks:
self._stagescan_callbacks.remove(callback)
def reset_stagescan_complete(self):
"""Reset the stagescan completion flag."""
self._stagescan_complete = False
def is_stagescan_complete(self):
"""Check if stagescan has completed."""
return self._stagescan_complete
def wait_for_stagescan_complete(self, timeout=300):
"""
Wait for stagescan to complete with timeout.
Args:
timeout: Maximum time to wait in seconds
Returns:
True if completed, False if timeout
"""
start_time = time.time()
while not self._stagescan_complete:
if time.time() - start_time > timeout:
return False
time.sleep(0.1)
return True
def register_callback(self, key, callbackfct):
''' register a callback function for a specific key '''
self._callbackPerKey[key] = callbackfct
def setTrigger(self, axis="X", pin=1, offset=0, period=1):
# {"task": "/motor_act", "setTrig": {"steppers": [{"stepperid": 1, "trigPin": 1, "trigOff":0, "trigPer":1}]}}
if type(axis) is not int:
axis = self.xyztTo1230(axis)
path = "/motor_act"
payload = {
"task": path,
"setTrig":{
"steppers": [
{
"stepperid": axis,
"trigPin": pin,
"trigOff": offset,
"trigPer": period
}]
}}
r = self._parent.post_json(path, payload)
return r
# {"task": "/motor_act", "stagescan": {"nStepsLine": 50, "dStepsLine": 1, "nTriggerLine": 1, "nStepsPixel": 50, "dStepsPixel": 1, "nTriggerPixel": 1, "delayTimeStep": 10, "stopped": 0, "nFrames": 50}}"}}
def startStageScanning(self, nStepsLine=100, dStepsLine=1, nTriggerLine=1, nStepsPixel=100, dStepsPixel=1, nTriggerPixel=1, delayTimeStep=10, nFrames=5, isBlocking = False):
path = "/motor_act"
payload = {
"task": path,
"stagescan":{
"nStepsLine": nStepsLine,
"dStepsLine": dStepsLine,
"nTriggerLine": nTriggerLine,
"nStepsPixel": nStepsPixel,
"dStepsPixel": dStepsPixel,
"nTriggerPixel": nTriggerPixel,
"delayTimeStep": delayTimeStep,
"stopped": 0,
"nFrames": nFrames
}}
r = self._parent.post_json(path, payload, getReturn=isBlocking)
return r
def stopStageScanning(self):
self.startStageScanning(stopped=1)
def setIsCoreXY(self, isCoreXY = False):
self.isCoreXY = isCoreXY
def setMotorAxisOrder(self, order=[0,1,2,3]):
self.motorAxisOrder = order
# { "task": "/motor_act", "focusscan": { "zStart": 0, "zStep": 50, "nZ": 20, "tPre": 80, "tTrig": 20, "tPost": 0, "led": 0, "illumination": [0, 255, 0, 0], "speed": 20000, "acceleration": 1000000, "qid": 42 }}
def startFocusScanning(self, zStart=0, zStep=50, nZ=20, tPre=80, tTrig=20, tPost=0, led=0, illumination=[0, 255, 0, 0], speed=20000, acceleration=1000000, qid=42):
path = "/motor_act"
payload = {
"task": path,
"focusscan": {
"zStart": zStart,
"zStep": zStep,
"nZ": nZ,
"tPre": tPre,
"tTrig": tTrig,
"tPost": tPost,
"led": led,
"illumination": illumination,
"speed": speed,
"acceleration": acceleration,
"qid": qid
}
}
r = self._parent.post_json(path, payload)
return r
def stopFocusScanning(self):
path = "/motor_act"
payload = {
"task": path,
"focusscan": {
"stopped": 1
}
}
r = self._parent.post_json(path, payload)
return r
'''################################################################################################################################################
HIGH-LEVEL Functions that rely on basic REST-API functions
################################################################################################################################################'''
def setup_motor(self, axis, minPos, maxPos, stepSize, backlash, direction=None):
"""Configure one motor axis.
The ``stepSize`` is stored internally as a positive magnitude (physical
units per step). The wiring polarity is tracked separately in
``self.direction[axis]`` so the user/physical coordinate frame stays
consistent in both directions of communication.
Parameters
----------
axis : str
One of "X", "Y", "Z", "A".
minPos, maxPos : float
Soft limits in physical (user-frame) units.
stepSize : float
Physical units per step. A negative value is interpreted as a
request to flip the hardware direction for this axis (equivalent
to passing ``direction=-1``) and is split into magnitude + sign.
backlash : float
Backlash in hardware steps (sign handled internally).
direction : int or None, optional
Explicit hardware-direction sign (+1 or -1). If ``None`` it is
derived from the sign of ``stepSize`` (default +1).
"""
# Split sign from magnitude. An explicit `direction` always wins;
# otherwise the sign of stepSize is consumed and stepSize becomes
# a positive scale factor.
if direction is None:
sign = -1 if stepSize < 0 else 1
else:
sign = -1 if direction < 0 else 1
stepSize = abs(stepSize)
axisIdx = self.xyztTo1230(axis)
self.direction[axisIdx] = sign
if axis == "X":
self.minPosX = minPos
self.maxPosX = maxPos
self.stepSizeX = stepSize
elif axis == "Y":
self.minPosY = minPos
self.maxPosY = maxPos
self.stepSizeY = stepSize
elif axis == "Z":
self.minPosZ = minPos
self.maxPosZ = maxPos
self.stepSizeZ = stepSize
elif axis == "A":
self.minPosA = minPos
self.maxPosA = maxPos
self.stepSizeA = stepSize
self.backlash[axisIdx] = backlash
def xyztTo1230(self, axis):
axis = axis.upper()
if axis == "X":
axis = 1
if axis == "Y":
axis = 2
if axis == "Z":
axis = 3
if axis == "A":
axis = 0
return axis
def cartesian2corexy(self, x, y):
# convert cartesian coordinates to coreXY coordinates
# https://www.corexy.com/theory.html
x1 = (x+y)/np.sqrt(2)
y1 = (x-y)/np.sqrt(2)
return x1, y1
def move_x(self, steps=0, speed=1000, acceleration=None, is_blocking=False, is_absolute=False, is_enabled=True, timeout=gTIMEOUT, is_reduced=False):
if self.isCoreXY:
# have to turn two motors to move in X direction
xTemp, yTemp = self.cartesian2corexy(steps, 0)
return self.move_xy(steps=(xTemp, yTemp), speed=(speed,speed), is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, timeout=timeout, is_reduced=is_reduced)
else:
return self.move_axis_by_name(axis="X", steps=steps, speed=speed, acceleration=acceleration, is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, timeout=timeout, is_reduced=is_reduced)
def move_y(self, steps=0, speed=1000, acceleration=None, is_blocking=False, is_absolute=False, is_enabled=True, timeout=gTIMEOUT, is_reduced=False):
if self.isCoreXY:
# have to turn two motors to move in Y direction
xTemp, yTemp = self.cartesian2corexy(0,steps)
return self.move_xy(steps=(xTemp, yTemp), speed=(speed,speed), is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, timeout=timeout, is_reduced=is_reduced)
else:
return self.move_axis_by_name(axis="Y", steps=steps, speed=speed, acceleration=acceleration, is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, timeout=timeout, is_reduced=is_reduced)
def move_z(self, steps=0, speed=1000, acceleration=None, is_blocking=False, is_absolute=False, is_dualaxis = False, is_enabled=True, timeout=gTIMEOUT, is_reduced=False):
if is_dualaxis:
self.move_az(steps=(steps, steps), speed=(speed,speed), acceleration=acceleration, is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, timeout=gTIMEOUT, is_reduced=is_reduced)
else:
return self.move_axis_by_name(axis="Z", steps=steps, speed=speed, acceleration=acceleration, is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, timeout=timeout, is_reduced=is_reduced)
def move_a(self, steps=0, speed=1000, acceleration=None, is_blocking=False, is_absolute=False, is_enabled=True, timeout=gTIMEOUT, is_reduced=False):
return self.move_axis_by_name(axis="A", steps=steps, speed=speed, acceleration=acceleration, is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, timeout=timeout, is_reduced=is_reduced)
def move_xyz(self, steps=(0,0,0), speed=(1000,1000,1000), acceleration=None, is_blocking=False, is_absolute=False, is_enabled=True, timeout=gTIMEOUT, is_reduced=False):
if len(speed)!= 3:
speed = (speed,speed,speed)
# motor axis is 1,2,3,0 => X,Y,Z,T # FIXME: Hardcoded
r = self.move_xyza(steps=(0,steps[0],steps[1],steps[2]), acceleration=(0,acceleration[0],acceleration[1],acceleration[2]), speed=(0,speed[0],speed[1],speed[2]), is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, timeout=timeout, is_reduced=is_reduced)
return r
def move_xy(self, steps=(0,0), speed=(1000,1000), acceleration=None, is_blocking=False, is_absolute=False, is_enabled=True, timeout=gTIMEOUT, is_reduced=False):
if self.isCoreXY:
# have to move only one motor to move in XY direction
return self.move_xyza(steps=(0,steps[0], steps[1], 0), speed=(0,speed[0],speed[1],0), is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, timeout=timeout, is_reduced=is_reduced)
else:
if type(speed)==int or len(speed)!= 2:
speed = (speed,speed)
if acceleration is None:
acceleration = 100000
if type(acceleration)==int or len(acceleration)!= 2:
acceleration = (acceleration,acceleration)
# motor axis is 1,2,3,0 => X,Y,Z,T # FIXME: Hardcoded
r = self.move_xyza(steps=(0, steps[0],steps[1],0), speed=(0,speed[0],speed[1],0), acceleration=(0,acceleration[0],acceleration[1],0), is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, timeout=timeout, is_reduced=is_reduced)
return r
def move_az(self, steps=(0,0), speed=(1000,1000), acceleration=None, is_blocking=False, is_absolute=False, is_enabled=True, timeout=gTIMEOUT, is_reduced=False):
if (type(speed)!=list and type(speed)!=tuple) or len(speed)!= 2:
speed = (speed,speed)
if (type(acceleration)!=list and type(acceleration)!=tuple) or len(acceleration)!= 2:
acceleration = (acceleration,acceleration)
# motor axis is 1,2,3,0 => X,Y,Z,T # FIXME: Hardcoded
r = self.move_xyza(steps=(steps[0],0,0,steps[1]), speed=(speed[0],0,0,speed[1]), acceleration=(acceleration[0],0,0,acceleration[1]), is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, timeout=timeout, is_reduced=is_reduced)
return r
def move_xyza(self, steps=(0,0,0,0), speed=(1000,1000,1000,1000), acceleration=None, is_blocking=False, is_absolute=False, is_enabled=True, timeout=gTIMEOUT, is_reduced=False):
# everywhere, where relative steps are zero, speed should be zero, too
if type(speed)==int:
speed = [speed,speed,speed,speed]
if type(speed)==tuple:
speed = list(speed)
for iMotor in range(len(steps)):
if steps[iMotor]==0 and not is_absolute:
speed[iMotor] = 0
r = self.move_stepper(steps=steps, speed=speed, acceleration=acceleration, is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, timeout=timeout, is_reduced=is_reduced)
return r
def move_axis_by_name(self, axis="X", steps=100, speed=1000, acceleration=None, is_blocking=False, is_absolute=False, is_enabled=True, timeout=gTIMEOUT, is_reduced=False):
axis = self.xyztTo1230(axis)
_speed=np.zeros(4)
_speed[axis] = speed
_steps=np.array((0,0,0,0))
_steps[axis] = steps
_acceleration=acceleration
r = self.move_stepper(_steps, speed=_speed, acceleration=_acceleration, timeout=timeout, is_blocking=is_blocking, is_absolute=is_absolute, is_enabled=is_enabled, is_reduced=is_reduced)
return r
def move_forever(self, speed=(0,0,0,0), is_stop=False, is_blocking=False):
if type(speed)==int:
speed=(speed, speed, speed, speed)
if len(speed)==3:
speed = (*speed,0)
'''
{"task":"/motor_act",
"motor":
{
"steppers": [
{ "stepperid": 3, "isforever": 1, "speed": 2000}
]
}
}
'''
# only consider those actions that are necessary
motorPropList = []
for iMotor in range(4):
if abs(speed[iMotor])>=0:
motorProp = { "stepperid": iMotor,
"isforever": int(not is_stop),
"speed": speed[iMotor]}
motorPropList.append(motorProp)
path = "/motor_act"
payload = {
"task":path,
"motor":
{
"steppers": motorPropList
}
}
r = self._parent.post_json(path, payload, timeout=0, getReturn=is_blocking)
return r
def stop(self, axis=None):
axisNumberList = []
if axis is None:
for iMotor in range(self.nMotors):
axisNumberList.append(iMotor)
else:
axisNumberList.append(self.xyztTo1230(axis))
motorPropList = []
for iMotor in axisNumberList:
motorProp = { "stepperid": self.motorAxisOrder[iMotor],
"isstop": True}
motorPropList.append(motorProp)
path = "/motor_act"
payload = {
"task":path,
"motor":
{
"steppers": motorPropList
}
}
# ensure that nothing blocks this command!
if self.isRunning:
self._parent.serial.breakCurrentCommunication()
r = self._parent.post_json(path, payload, getReturn=False, timeout=0)
return r
def compute_travel_time(self, steps, max_speed, acceleration):
import math
"""
Calculate approximate travel time for a stepper motor
with trapezoidal velocity profile.
steps : total distance in steps
max_speed : maximum speed in steps/second
acceleration: acceleration in steps/second^2
"""
# Distance to accelerate from 0 to max_speed:
dist_accel = (max_speed ** 2) / (2.0 * acceleration)
# If distance is too short to reach max speed -> triangular profile
if steps < 2 * dist_accel:
# T = 2 * sqrt( distance / acceleration )
return 2.0 * math.sqrt(steps / acceleration)
else:
# Time to accelerate to max_speed
t_accel = max_speed / acceleration
# Distance spent accelerating
d_accel = dist_accel
# Distance spent decelerating (same as accelerating)
d_decel = dist_accel
# Remaining distance at constant speed
d_const = steps - d_accel - d_decel
# Time at constant speed
t_const = d_const / max_speed
# Total time
return t_accel + t_const + t_accel
def move_stepper(self, steps=(0,0,0,0), speed=(1000,1000,1000,1000), is_absolute=(False,False,False,False), timeout=gTIMEOUT, acceleration=(None, None, None, None), is_blocking=True, is_enabled=True, is_reduced=False):
'''
This tells the motor to run at a given speed for a specific number of steps; Multiple motors can run simultaneously
XYZT => 1,2,3,0
'''
# determine the axis to operate
axisToMove = np.where(np.abs(speed)>0)[0]
if axisToMove.shape[0]==0:
return "{'return':-1}"
if type(is_absolute)==bool:
isAbsoluteArray = np.zeros((4))
isAbsoluteArray[axisToMove] = is_absolute
else:
isAbsoluteArray = is_absolute
# convert single elements to array
if type(speed)!=list and type(speed)!=tuple and type(speed)!=np.ndarray:
speed = np.array((speed,speed,speed,speed))
# convert single elements to array
if type(acceleration)!=list and type(acceleration)!=tuple and type(acceleration)!=np.ndarray:
acceleration = np.array((acceleration,acceleration,acceleration,acceleration))
# make sure value is an array
if type(steps)==tuple:
steps = np.array(steps)
# Store the target position in physical units BEFORE conversion to hardware steps
targetPositionPhysical = steps.copy()
# Convert from physical (user-frame) units to firmware (hardware-frame) steps.
# Apply the per-axis direction sign so wiring polarity is hidden from callers:
# hw_steps = phys / |stepSize| * direction
# (For relative moves this flips the requested delta; for absolute targets it
# flips the absolute position the firmware should drive to.)
steps[0] = steps[0] * self.direction[0] / self.stepSizeA
steps[1] = steps[1] * self.direction[1] / self.stepSizeX
steps[2] = steps[2] * self.direction[2] / self.stepSizeY
steps[3] = steps[3] * self.direction[3] / self.stepSizeZ
# detect change in direction and compute distances in HARDWARE STEPS for travel time calculation
absoluteDistances_steps = np.zeros((4)) # Distance in hardware steps
stepSizes = np.array((self.stepSizeA, self.stepSizeX, self.stepSizeY, self.stepSizeZ))
for iMotor in range(4):
# for absolute motion:
if isAbsoluteArray[iMotor]:
# Compare current position (physical) with target (physical, already includes offset)
self.currentDirection[iMotor] = 1 if (self.currentPosition[iMotor] > targetPositionPhysical[iMotor]) else -1
# Calculate distance to travel in HARDWARE STEPS:
# Current position (physical) -> convert to steps, then subtract target (already in steps)
currentPosition_steps = self.currentPosition[iMotor] / stepSizes[iMotor]
absoluteDistances_steps[iMotor] = abs(currentPosition_steps - steps[iMotor])
else:
self.currentDirection[iMotor] = np.sign(steps[iMotor])
# For relative motion, steps[iMotor] is already the distance in hardware steps
absoluteDistances_steps[iMotor] = abs(steps[iMotor])
if self.lastDirection[iMotor] != self.currentDirection[iMotor]:
# we want to overshoot a bit (backlash is in steps, so apply AFTER conversion to steps)
steps[iMotor] = steps[iMotor] + self.currentDirection[iMotor]*self.backlash[iMotor]
# Update distance calculation if backlash was applied
if not isAbsoluteArray[iMotor]:
absoluteDistances_steps[iMotor] = abs(steps[iMotor])
# Convert speed and acceleration from physical units to steps/second
speed_steps = np.zeros(4)
acceleration_steps = np.zeros(4)
for iMotor in range(4):
if speed[iMotor] != 0:
# Speed: µm/s -> steps/s => divide by stepSize (µm/step)
speed_steps[iMotor] = abs(speed[iMotor]) # TODO: This is actually given in steps/s / stepSizes[iMotor]
if acceleration[iMotor] is not None and acceleration[iMotor] != 0:
# Acceleration: µm/s² -> steps/s² => divide by stepSize
acceleration_steps[iMotor] = abs(acceleration[iMotor]) # TODO: This is actually given in steps/s / stepSizes[iMotor]
else:
# Default acceleration in steps/s²
acceleration_steps[iMotor] = 20000 # This should also be converted, but we use a safe default
# Calculate travel time using HARDWARE STEPS and converted speed/acceleration
# Find the axis that will take the longest (limits overall movement time)
max_travel_time = 0
for iMotor in range(4):
if absoluteDistances_steps[iMotor] > 0 and speed_steps[iMotor] > 0:
axis_time = self.compute_travel_time(
absoluteDistances_steps[iMotor],
speed_steps[iMotor],
acceleration_steps[iMotor]
)
max_travel_time = max(max_travel_time, axis_time)
# Set timeout based on calculated travel time (add 2 seconds safety margin)
if max_travel_time > 0:
timeout = np.uint8(abs(timeout) > 0) * (max_travel_time + 2)
else:
timeout = np.uint8(abs(timeout) > 0) * 3 # Minimum 3 seconds if no movement detected
# get current position
#_positions = self.get_position() # x,y,z,t = 1,2,3,0
#pos_3, pos_0, pos_1, pos_2 = _positions[0],_positions[1],_positions[2],_positions[3]
'''
# check if within limits
if pos_0+steps_0 > self.maxPosX or pos_0+steps_0 < self.minPosX:
steps_0=0
if pos_1+steps_1 > self.maxPosY or pos_1+steps_1 < self.minPosY:
steps_1=0
if pos_2+steps_2 > self.maxPosZ or pos_2+steps_2 < self.minPosZ:
steps_2 = 0
if pos_3+steps_3 > self.maxPosA or pos_3+steps_3 < self.minPosA:
steps_3 = 0
'''
# only consider those actions that are necessary
motorPropList = []
for iMotor in range(4):
if isAbsoluteArray[iMotor] or abs(steps[iMotor])>0:
# if we are absolute and the last target position is the same as the current one, we don't need to move
# Compare in physical units: targetPositionPhysical vs currentPosition
if isAbsoluteArray[iMotor] and abs(targetPositionPhysical[iMotor] - self.currentPosition[iMotor])<1:
if self._parent.serial.DEBUG: self._parent.logger.debug(f"Motor {iMotor} is already at target position {targetPositionPhysical[iMotor]}")
continue
motorProp = { "stepperid": int(self.motorAxisOrder[iMotor]),
"position": int(steps[iMotor]),
"speed": int(speed[iMotor]),
"isabs": int(isAbsoluteArray[iMotor]),
"isaccel": int(1),
"isen": int(is_enabled),
"redu": int(is_reduced)}
if acceleration[iMotor] is not None:
motorProp["accel"] = int(acceleration[iMotor])
else:
motorProp["accel"] = self.DEFAULT_ACCELERATION
motorPropList.append(motorProp)
if len(motorPropList)==0:
return "{'return':-1}"
path = "/motor_act"
payload = {
"task":path,
"motor":
{
"steppers": motorPropList
}
}
# Update currentPosition to track expected position in physical (user-frame) units.
# ``steps`` is in hardware/firmware frame at this point, so we convert back with
# phys = hw_steps * stepSize * direction
stepSizes = np.array((self.stepSizeA, self.stepSizeX, self.stepSizeY, self.stepSizeZ))
for iMotor in range(self.nMotors):
if isAbsoluteArray[iMotor]:
# For absolute: convert hardware steps back to physical (user) units.
self.currentPosition[iMotor] = steps[iMotor] * stepSizes[iMotor] * self.direction[iMotor]
else:
# For relative: convert hw step delta to physical delta and accumulate.
self.currentPosition[iMotor] = self.currentPosition[iMotor] + (
steps[iMotor] * stepSizes[iMotor] * self.direction[iMotor]
)
# drive motor
self.isRunning = True
is_blocking = is_blocking and self._parent.serial.is_connected
timeout = timeout if is_blocking else 0
if self._parent.serial.use_qid_done:
nResponses = 1 # QID mode: firmware handles completion tracking
else:
nResponses = len(payload["motor"]["steppers"]) + 1
# if we get a return, we will receive the latest position feedback from the driver by means of the axis that moves the longest
r = self._parent.post_json(path, payload, getReturn=is_blocking, timeout=timeout, nResponses=nResponses)
# save direction for last iteration
self.lastDirection = self.currentDirection.copy()
# Reset busy flag
self.isRunning = False
return r
def isBusy(self, steps, timeout=1):
path = "/motor_get"
payload = {
"task":path,
"isbusy": 1
}
r = self._parent.post_json(path, payload, timeout=timeout)
try:
isbusy = 0
for iMotor in range(self.nMotors):
isbusy += r["motor"]["steppers"][iMotor]["isbusy"]
if isbusy:
return True
else :
return False
except Exception as e:
return False
def set_motor(self, stepperid = 0, position = None, stepPin=None, dirPin=None, enablePin=None, maxPos=None, minPos=None, acceleration=None, isEnable=None, isBlocking=True, timeout=2):
path = "/motor_set"
payload = {"task":path,
"motor":{
"steppers": [
{ "stepperid": self.motorAxisOrder[stepperid]}]
}}
if stepPin is not None: payload['motor']["steppers"][0]["step"] = stepPin
if dirPin is not None: payload['motor']["steppers"][0]["dir"] = dirPin
if enablePin is not None: payload['motor']["steppers"][0]["enable"] = enablePin
if maxPos is not None: payload['motor']["steppers"][0]["max_pos"] = maxPos
if minPos is not None: payload['motor']["steppers"][0]["min_pos"] = minPos
if position is not None: payload['motor']["steppers"][0]["position"] = position
if acceleration is not None: payload['motor']["steppers"][0]["acceleration"] = acceleration
if isEnable is not None: payload['motor']["steppers"][0]["isen"] = isEnable
# send command
r = self._parent.post_json(path, payload, timeout=1)
# wait until job has been done
time0=time.time()
if isBlocking:
while self.isBusy((0,0,0,0)):
time.sleep(0.1)
if time.time()-time0>timeout:
break
return r
def set_motor_currentPosition(self, axis=0, currentPosition=10000):
if type(axis)==str:
axis = self.xyztTo1230(axis)
r = self.set_motor(stepperid = axis, position = currentPosition)
return r
def set_motor_acceleration(self, axis=0, acceleration=40000):
if type(axis)==str:
axis = self.xyztTo1230(axis)
path = "/motor_act"
payload = {
"task": path,
"motor":
{
"steppers": [
{ "stepperid":axis, "isaccel":1, "accel":acceleration}
]
}
}
r = self._parent.post_json(path, payload)
return r
def set_motor_enable(self, enable=None, enableauto=None):
"""
turns on/off enable pin overrides motor settings - god for cooling puproses
eanbaleauto turns on/off timer of the accelstepper library
"""
path = "/motor_act"
payload = {
"task": path
}
if enable is not None:
payload["isen"] = enable
if enableauto is not None:
payload["isenauto"] = enableauto
if not enableauto:
enable = True
r = self._parent.post_json(path, payload)
return r
def get_position(self, axis=None, timeout=1):
# pulls all current positions from the stepper controller
path = "/motor_get"
payload = {
"task":path,
"position":True,
}
_position = np.array((0.,0.,0.,0.)) # T,X,Y,Z
_physicalStepSizes = np.array((self.stepSizeA, self.stepSizeX, self.stepSizeY, self.stepSizeZ))
# this may be an asynchronous call.. #FIXME!
r = self._parent.post_json(path, payload, getReturn = True, nResponses=1, timeout=timeout)[0]
# returns {"motor": }
if "motor" in r :
for index, istepper in enumerate(r["motor"]["steppers"]):
if index >3: break # TODO: We would need to handle other values too soon
stepperID = istepper["stepperid"]
# phys = hw_steps * stepSize * direction (apply wiring sign at boundary)
_position[stepperID] = (
istepper["position"]
* _physicalStepSizes[self.motorAxisOrder[index]]
* self.direction[stepperID]
)
return _position
def set_position(self, axis=1, position=0, timeout=1):
'''
{"task":"/motor_act", "setpos": {"steppers": [{"stepperid":1, "posval": 0}]}}
'''
path = "/motor_act"
if type(axis) !=int:
axis = self.xyztTo1230(axis)
payload = {
"task": path,
"setpos":{
"steppers": [
{
"stepperid": axis,
"posval": int(position)
}]
}}
r = self._parent.post_json(path, payload, timeout=timeout)
return r
def set_soft_limits(self, axis=1, min_pos=None, max_pos=None, is_enabled=None, timeout=1):
'''
Set soft limits for a motor axis. Soft limits prevent motor movement beyond specified boundaries.
Parameters:
-----------
axis : int or str
Motor axis (0/"A", 1/"X", 2/"Y", 3/"Z")
min_pos : int, optional
Minimum position limit in steps
max_pos : int, optional
Maximum position limit in steps
is_enabled : bool or int, optional
Enable (1/True) or disable (0/False) soft limits for this axis
timeout : int
Command timeout in seconds
Returns:
--------
Response from ESP32
Example:
--------
# Set limits for X-axis
motor.set_soft_limits(axis="X", min_pos=-10000, max_pos=10000, is_enabled=True)
# Disable limits for Z-axis
motor.set_soft_limits(axis="Z", is_enabled=False)
Note:
-----
Soft limits are automatically ignored during homing operations.
'''
if type(axis) != int:
axis = self.xyztTo1230(axis)
path = "/motor_act"
payload = {
"task": path,
"softlimits": {
"steppers": [{
"stepperid": axis
}]
}
}
if min_pos is not None:
payload["softlimits"]["steppers"][0]["min"] = int(min_pos)
if max_pos is not None:
payload["softlimits"]["steppers"][0]["max"] = int(max_pos)
if is_enabled is not None:
payload["softlimits"]["steppers"][0]["isen"] = int(is_enabled)
r = self._parent.post_json(path, payload, timeout=timeout)
return r
def get_soft_limits(self, axis=None, timeout=1):
'''
Get current soft limits configuration for all axes or a specific axis.
Parameters:
-----------
axis : int or str, optional
Motor axis (0/"A", 1/"X", 2/"Y", 3/"Z"). If None, returns all axes.
timeout : int
Command timeout in seconds
Returns:
--------
dict : Soft limits configuration
Contains min, max, and isen (enabled) for each axis
Example:
--------
# Get limits for all axes
limits = motor.get_soft_limits()
# Get limits for X-axis only
x_limits = motor.get_soft_limits(axis="X")
'''
motors = self.get_motors(timeout=timeout)
if motors and "steppers" in motors:
if axis is not None:
if type(axis) != int:
axis = self.xyztTo1230(axis)
# Find the specific axis
for stepper in motors["steppers"]:
if stepper.get("stepperid") == axis:
return {
"axis": axis,
"min": stepper.get("min", 0),
"max": stepper.get("max", 0),
"enabled": stepper.get("isen", 0)
}
else:
# Return all axes
result = []
for stepper in motors["steppers"]:
result.append({
"axis": stepper.get("stepperid"),
"min": stepper.get("min", 0),
"max": stepper.get("max", 0),
"enabled": stepper.get("isen", 0)
})
return result
return None
def enable_soft_limits(self, axis, timeout=1):
'''
Enable soft limits for a specific axis.
Parameters:
-----------
axis : int or str
Motor axis (0/"A", 1/"X", 2/"Y", 3/"Z")
timeout : int
Command timeout in seconds
'''
return self.set_soft_limits(axis=axis, is_enabled=True, timeout=timeout)
def disable_soft_limits(self, axis, timeout=1):
'''
Disable soft limits for a specific axis.
Parameters:
-----------
axis : int or str
Motor axis (0/"A", 1/"X", 2/"Y", 3/"Z")
timeout : int
Command timeout in seconds
'''
return self.set_soft_limits(axis=axis, is_enabled=False, timeout=timeout)
def set_joystick_direction(self, axis, inverted=False, timeout=1):
'''
Set joystick direction inversion for a specific motor axis.
When inverted is True, joystick movements for this axis will be reversed.
Parameters:
-----------
axis : int or str
Motor axis (0/"A", 1/"X", 2/"Y", 3/"Z")
inverted : bool or int
True/1 to invert joystick direction, False/0 for normal direction
timeout : int
Command timeout in seconds
Returns:
--------
Response from ESP32
Example: