-
Notifications
You must be signed in to change notification settings - Fork 8
/
MachineMotion.py
2259 lines (1905 loc) · 94.5 KB
/
MachineMotion.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
# File name: MachineMotion.py #
# Note: Information about all the g-Code #
# commands supported are available at #
# the following location of the SDK: #
# ./documentation #
# Import standard libraries
import json, time, threading, sys
import traceback
import urllib
if sys.version_info.major < 3:
from httplib import HTTPConnection
from urllib import urlencode
else:
from http.client import HTTPConnection
from urllib.parse import urlencode
# Import package dependent libraries
import paho.mqtt.client as mqtt
import paho.mqtt.subscribe as MQTTsubscribe
class MACHINEMOTION_HW_VERSIONS:
MMv1 = 1
MMv2 = 2
MMv2OneDrive = 3
class DIRECTION:
POSITIVE = "positive"
NEGATIVE = "negative"
NORMAL = POSITIVE
REVERSE = NEGATIVE
CLOCKWISE = POSITIVE
COUNTERCLOCKWISE = NEGATIVE
class AXIS_NUMBER:
DRIVE1 = 1
DRIVE2 = 2
DRIVE3 = 3
DRIVE4 = 4
class UNITS_SPEED:
mm_per_min = "mm per minute"
mm_per_sec = "mm per second"
class UNITS_ACCEL:
mm_per_min_sqr = "mm per minute"
mm_per_sec_sqr = "mm per second"
class DEFAULT_IP_ADDRESS:
usb_windows = "192.168.7.2"
usb_mac_linux = "192.168.7.2"
ethernet = "192.168.0.2"
localhost = "127.0.0.1"
DEFAULT_IP = DEFAULT_IP_ADDRESS.usb_windows
class MICRO_STEPS:
ustep_full = 1
ustep_2 = 2
ustep_4 = 4
ustep_8 = 8
ustep_16 = 16
ustep_32 = 32
class MECH_GAIN:
timing_belt_150mm_turn = 150
legacy_timing_belt_200_mm_turn = 200
enclosed_timing_belt_mm_turn = 208
ballscrew_10mm_turn = 10
enclosed_ballscrew_16mm_turn = 16
legacy_ballscrew_5_mm_turn = 5
indexer_deg_turn = 85
indexer_v2_deg_turn = 36
roller_conveyor_mm_turn = 157.7
belt_conveyor_mm_turn = 73.563
rack_pinion_mm_turn = 157.08
rack_pinion_v2_mm_turn = 141.37
electric_cylinder_mm_turn = 6
class STEPPER_MOTOR:
steps_per_turn = 200
class AUX_PORTS:
aux_1 = 0
aux_2 = 1
aux_3 = 2
aux_4 = 3
class ENCODER_TYPE:
real_time = "realtime-position"
stable = "stable-position"
class BRAKE_STATES:
locked = "locked"
unlocked = "unlocked"
unknown = "unknown"
class TUNING_PROFILES:
DEFAULT = "default"
class CONTROL_LOOPS:
OPEN_LOOP = "open"
CLOSED_LOOP = "closed"
class POWER_SWITCH:
ON = "on"
OFF = "off"
class PUSH_BUTTON:
class COLOR:
BLACK = 0
WHITE = 1
class STATE:
PUSHED = "pushed"
RELEASED = "released"
HARDWARE_MIN_HOMING_FEEDRATE = 500
HARDWARE_MAX_HOMING_FEEDRATE = 8000
MIN_MOTOR_CURRENT = 1.5 # Amps
MAX_MOTOR_CURRENT = 10.0 # Amps
class MQTT :
class PATH :
ESTOP = "estop"
ESTOP_STATUS = ESTOP + "/status"
ESTOP_TRIGGER_REQUEST = ESTOP + "/trigger/request"
ESTOP_TRIGGER_RESPONSE = ESTOP + "/trigger/response"
ESTOP_RELEASE_REQUEST = ESTOP + "/release/request"
ESTOP_RELEASE_RESPONSE = ESTOP + "/release/response"
ESTOP_SYSTEMRESET_REQUEST = ESTOP + "/systemreset/request"
ESTOP_SYSTEMRESET_RESPONSE = ESTOP + "/systemreset/response"
AUX_PORT_POWER = "aux_power"
AUX_PORT_SAFETY = "aux_safety_power"
SMARTDRIVES_READY = "smartDrives/areReady"
TIMEOUT = 10.0 # Number of seconds while we wait for MQTT response
DEFAULT_TIMEOUT = 65
def stderr(*args):
# print(*args, file=sys.stderr, flush=True) only works in python3
sys.stderr.write(" ".join(map(lambda x : str(x), list(args))) + "\n")
sys.stderr.flush()
def HTTPSend(host, path, data=None, JsonResponse=False, JsonRequest=False, timeout=DEFAULT_TIMEOUT):
timeout = DEFAULT_TIMEOUT if timeout <= 0 else timeout
timeouts = [
DEFAULT_TIMEOUT for i in range(int(timeout/DEFAULT_TIMEOUT))
]
if timeout % DEFAULT_TIMEOUT > 0:
timeouts.append(timeout % DEFAULT_TIMEOUT)
for i, current_timeout in enumerate(timeouts):
try:
lConn = HTTPConnection(host, timeout=current_timeout)
if None == data:
lConn.request("GET", path)
else:
contentType = "application/json" if JsonRequest else "application/octet-stream"
headers = { "Content-type": contentType}
lConn.request("POST", path, data, headers)
lResponse = lConn.getresponse()
status = lResponse.status
lResponse = lResponse.read()
if status != 200:
raise Exception("request http://%s%s failed with status %d: %s"
% (host, path, status, str(lResponse)))
if not JsonResponse:
# Casting as a string is necessary for python3
return str(lResponse)
return lResponse
except Exception as e:
stderr("ERROR - Could not GET %s: %s (%s)" % (path, traceback.format_exc(), e))
if lConn:
lConn.close()
lConn = None
if i + 1 == len(timeouts):
raise e
#
# Class that handles all gCode related communications
# @status
#
class GCode:
#
# Class constructor
# PRIVATE
# @param socket --- Description: The GCode class requires a socket object to communicate with the controller. The socket object is passed at contruction time.
# @status
#
def __init__(self, ip, isMMv2=False, isMMv2OneDrive=False):
# Passing in the socket instance at construction
self.myIp = ip
self.libPort = ":8000"
self.isMMv2 = isMMv2
self.isMMv2OneDrive = isMMv2OneDrive
return
#
# Function to map API axis labels to motion controller axis labels
# PRIVATE
# @param axis --- Description: The API axis label.
# @status
#
def __getTrueAxis__(self, axis):
if self.isMMv2OneDrive:
strs = "X"
elif self.isMMv2:
strs = "XYZW"
else:
strs = "XYZ"
if axis < 1 or axis > len(strs):
rng = ", ".join([str(i + 1) for i in range(len(strs))])
raise Exception("Invalid axis index %d ! (must be in range %s)" % (axis, rng))
return strs[axis - 1]
#
# Function that packages the data in a JSON object and sends to the MachineMotion server over a socket connection.
# PRIVATE
#
def __send__(self, cmd, data=None, JsonResponse=False, JsonRequest=False, timeout=DEFAULT_TIMEOUT):
return HTTPSend(self.myIp + self.libPort, cmd, data, JsonResponse, JsonRequest, timeout)
#
# Function to send a raw G-Code ASCII command
# @param gCode --- Description: gCode is string representing the G-Code command to send to the controller. Type: string.
# @status
#
def __emit__(self, gCode, timeout=DEFAULT_TIMEOUT):
try:
path = "/gcode?%s" % urlencode({"gcode": "%s" % gCode})
rep = self.__send__(path, timeout=timeout)
# Call user callback only if relevant
if self.__userCallback__ is not None:
self.__userCallback__(rep)
return rep
except Exception as e:
raise e
def __emitEchoOk__(self, gCode, timeout=DEFAULT_TIMEOUT):
reply = self.__emit__(gCode, timeout=timeout)
if ("echo" in reply and "ok" in reply):
return reply
else:
raise Exception('Error in gCode execution: %s' % str(reply))
#
# Function to send commands specifically to the smartDrives
# @status
#
def __sendToSmartDrives__(self, url, payload=None, JsonResponse=False, JsonRequest=False) :
rep = self.__send__(url, payload, JsonResponse, JsonRequest)
# Call user callback only if relevant
if self.__userCallback__ is None : pass
else :
self.__userCallback__(str(rep)) # Casting as a string is necessary for python3
return rep
#
# Function to send the config to the smartDrives
# @param config --- Description: config is an object representing the config payload to send to the controller. Type: object.
# @status
#
def __sendConfigToSmartDrives__(self, drive, payload, JsonResponse=False) :
url = "/smartDrives/configuration?%s" % urlencode({"drive": "%s" % drive})
return self.__sendToSmartDrives__(url, payload, JsonResponse, JsonRequest=True)
#
# Function to ask the configuration to the smartDrives
# @status
#
def __askConfigToSmartDrives__(self, drive) :
return self.__sendConfigToSmartDrives__(drive, None, JsonResponse=True)
#
# Function to ask the position to the smartDrives
# @status
#
def __askPositionToSmartDrives__(self) :
# Expecting a json encoded response
return self.__sendToSmartDrives__("/smartDrives/position", JsonResponse=True)
@staticmethod
def __userCallback__(data): return
def __keepSocketAlive__(self) : pass
# Private function
def __setUserCallback__(self, userCallback) :
# Save the user function to call on incoming messages locally
self.__userCallback__ = userCallback
# Start the periodic process that fetches the sockets that were received by the OS
self.__keepSocketAlive__()
return
#
# Class used to encapsulate the MachineMotion controller
# @status
#
class MachineMotion(object):
# Version independent MQTT parser
def __parseMessage(self, message, jsonLoads=True):
# Decode the payload according to the Python version
if sys.version_info.major < 3:
payload = message
else:
payload = message.decode('utf-8')
# Json decode the payload or not
if jsonLoads:
try:
return json.loads(payload)
except Exception as e:
stderr("WARNING - Invalid JSON payload: " + e)
return None
return payload
# Version independent numerical checker
def _isNumber(self, number):
# Python 2 has two integer types - int and long. There is no 'long integer' in Python 3 anymore : integers in Python 3 are of unlimited size.
if sys.version_info.major < 3:
return isinstance(number, (int, long, float))
else:
return isinstance(number, (int, float))
# Class constructor
def __init__(self, machineIp=DEFAULT_IP_ADDRESS.usb_windows, gCodeCallback=(lambda *args: None), machineMotionHwVersion=MACHINEMOTION_HW_VERSIONS.MMv1) :
'''
desc: Constructor of MachineMotion class
params:
machineIp:
desc: IP address of the Machine Motion
type: string of the DEFAULT_IP_ADDRESS class, or other valid IP address
default: DEFAULT_IP_ADDRESS.usb_windows
gCodeCallback:
desc: Allows to define a custom behaviour for the MachineMotion object
when a response is received from the motion controller.
type: function
default: None
machineMotionHwVersion:
desc: The hardware version of the MachineMotion being used
type: string of the MACHINEMOTION_HW_VERSIONS class
default: MACHINEMOTION_HW_VERSIONS.MMv1
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: moveRelative.py, oneDriveControl.py
'''
self.IP = machineIp
self.machineMotionHwVersion = machineMotionHwVersion
self.isMMv2 = self.machineMotionHwVersion >= MACHINEMOTION_HW_VERSIONS.MMv2
self.isMMv2OneDrive = self.machineMotionHwVersion == MACHINEMOTION_HW_VERSIONS.MMv2OneDrive
self.myConfiguration = {"machineIp": self.IP, "machineGateway": "notInitialized", "machineNetmask": "notInitialized"}
self.myGCode = GCode(self.IP, self.isMMv2, self.isMMv2OneDrive)
self.myGCode.__setUserCallback__(gCodeCallback)
self.maxIo = 8 if self.isMMv2 else 3
self.myIoExpanderAvailabilityState = [ False ] * self.maxIo
self.myEncoderRealtimePositions = [ 0, 0, 0 ] # MMv1 only
self.myEncoderStablePositions = [ 0, 0, 0 ] # MMv1 only
self.digitalInputs = {}
self.pushButtonStates = {}
dev_count = 4 if self.isMMv2 else 3
self.brakeStatus_control = [None for i in range(dev_count)] # MMv2 does not support control power
self.brakeStatus_safety = [None for i in range(dev_count)]
self.estopStatus = None
self.areSmartDrivesReady = None
# MQTT
self.myMqttClient = None
self.myMqttClient = mqtt.Client()
self.myMqttClient.on_connect = self.__onConnect
self.myMqttClient.on_message = self.__onMessage
self.myMqttClient.on_disconnect = self.__onDisconnect
self.myMqttClient.connect(machineIp)
self.myMqttClient.loop_start()
#Set callback to default until user initialize it
self.eStopCallback = (lambda *args: None)
# Initialize all of the possible push button callbacks
# The callbacks are stored in a dict of dicts of functions. The dict is first built with
# the total amount of possible push button addresses, then with the total amount buttons
# available per module.
# The callback associated with pressing the black button of module 1 can be accessed as follows:
# address = 1
# function = self.pushButtonCallbacks[str(address)][str(PUSH_BUTTON.COLOR.BLACK)]
self.pushButtonCallbacks = {}
for address in range(1,self.maxIo+1):
self.pushButtonCallbacks.update({str(address):{}})
validParams = [i for i in PUSH_BUTTON.COLOR.__dict__.keys() if i[:1] != '_']
validValues = [str(PUSH_BUTTON.COLOR.__dict__[i]) for i in validParams]
for button in validValues:
self.pushButtonCallbacks[str(address)].update({button: (lambda *args: None)})
# Initializing axis parameters
self.steps_mm = ["Axis 0 does not exist", "notInitialized", "notInitialized", "notInitialized", "notInitialized"]
self.u_step = ["Axis 0 does not exist", "notInitialized", "notInitialized", "notInitialized", "notInitialized"]
self.mech_gain = ["Axis 0 does not exist", "notInitialized", "notInitialized", "notInitialized", "notInitialized"]
self.direction = ["Axis 0 does not exist", "notInitialized", "notInitialized", "notInitialized", "notInitialized"]
return
#Takes tuples of parameter variables and the class they belong to.
#If the parameter does not belong to the class, it raises a descriptive error.
def _restrictInputValue(self, argName, argValue, argClass):
validParams = [i for i in argClass.__dict__.keys() if i[:1] != '_']
validValues = [argClass.__dict__[i] for i in validParams]
if argValue in validValues:
return
errorMessage = "An invalid selection was made. Given parameter '" + str(argName) + "' must be one of the following values:"
for param in validParams:
errorMessage += "\n" + argClass.__name__ + "." + param + " (" + str(argClass.__dict__[param]) +")"
raise Exception(errorMessage)
def moveContinuous(self, axis, speed, accel) :
'''
desc: Starts an axis using speed mode.
params:
axis:
desc: Axis to move
type: Number
speed:
desc: Speed to move the axis at in mm / sec
type: Number
accel:
desc: Acceleration used to reach the desired speed, in mm / sec^2
type: Number
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: moveContinuous.py
'''
# Verify argument type to avoid sending garbage in the GCODE
self._restrictAxisValue(axis)
if not self._isNumber(speed) : raise Exception('Error in speed variable type')
if not self._isNumber(accel) : raise Exception('Error in accel variable type')
# Check if steps_per_mm are defined locally. If not, query them.
if not self._isNumber(self.steps_mm[axis]) :
self.populateStepsPerMm()
# Send speed command with accel
gCode = "V4 S" + str(speed * self.steps_mm[axis]) + " A" + str(abs(accel * self.steps_mm[axis])) + " " + self.myGCode.__getTrueAxis__(axis)
self.myGCode.__emitEchoOk__(gCode)
return
def stopMoveContinuous(self, axis, accel) :
'''
desc: Stops an axis using speed mode.
params:
axis:
desc: Axis to move
type: Number
accel:
desc: Acceleration used to reach a null speed, in mm / sec^2
type: Number
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: moveContinuous.py
'''
return self.moveContinuous(axis, 0, accel)
# ------------------------------------------------------------------------
# Determines if the given id is valid for a drive.
def _restrictAxisValue(self, axis) :
# MMv1 has drives 1,2,3
# MMv2 has drives 1,2,3,4
# MMv2OneDrive has drive 1
self.myGCode.__getTrueAxis__(axis)
return True
# ------------------------------------------------------------------------
# Determines if the given id is valid for a Brake.
# @param {int} port - Port identifier
def _restrictBrakePort(self, port):
# Brakes are connected to AUX port on MMv1
# Brakes are connected to JunctionBox brake port on MMv2
if self.isMMv2OneDrive:
maxId = 1
elif self.isMMv2:
maxId = 4
else:
maxId = 3
if (port < 1 or port > maxId):
rng = ", ".join([str(i + 1) for i in range(maxId)])
raise Exception("Invalid brake port %d ! (must be in range %s)" % (port, rng))
return True
# ------------------------------------------------------------------------
# Determines if the given id is valid for an IO Exapnder.
# @param {int} id - Device identifier
def isIoExpanderIdValid(self, id):
# IO-Expander IDs range between 1 and maxIo.
if id < 1 or id > self.maxIo:
rng = ", ".join([str(i) for i in range(self.maxIo)])
raise Exception("Invalid Digital IO Module device ID %d (must be in range %s)" % (id, rng))
return True
# ------------------------------------------------------------------------
# Determines if the given input pin identifier is valid for an IO Exapnder.
# @param {int} deviceId - Device identifier
# @param {int} pinId - Pin identifier
def isIoExpanderInputIdValid(self, deviceId, pinId):
self.isIoExpanderIdValid(deviceId)
# IO-Expander pins range between 0 and 3.
if (pinId < 0 or pinId > 3):
rng = ", ".join([str(i) for i in range(4)])
raise Exception("Invalid Digital IO Module pin id %d (must be in range %s)" % (pinId, rng))
return True
# ------------------------------------------------------------------------
# Determines if the given output pin identifier is valid for an IO Exapnder.
# @param {int} deviceId - Device identifier
# @param {int} pinId - Pin identifier
def isIoExpanderOutputIdValid(self, deviceId, pinId) :
return self.isIoExpanderInputIdValid(deviceId, pinId)
# ------------------------------------------------------------------------
# Determines if the given push button address is valid for a given push button module.
# @param {int} deviceId - Device identifier
# @param {str} buttonId - Button identifier
def isPushButtonInputIdValid(self, deviceId, buttonId):
self.isIoExpanderIdValid(deviceId)
self._restrictInputValue("buttonId", buttonId, PUSH_BUTTON.COLOR)
return True
# ------------------------------------------------------------------------
# Determines if the given id is valid for an encoder.
def isEncoderIdValid(self, id) :
# For MMv1 only, encoder IDs range 0, 1, 2.
if id < 0 or id > 2:
rng = ", ".join([str(i) for i in range(3)])
raise Exception("invalid encoder id %d (must be in range %s)" % (id, rng))
return True
def populateStepsPerMm(self,onlyMarlin=False):
# For axes 1,2,3 ask directly from Marlin
reply_M503 = self.myGCode.__emitEchoOk__("M503")
beginning = reply_M503.find('M92')
self.steps_mm[1] = float(reply_M503[reply_M503.find('X',beginning)+1:(reply_M503.find('Y',beginning)-1)])
self.steps_mm[2] = float(reply_M503[reply_M503.find('Y',beginning)+1:(reply_M503.find('Z',beginning)-1)])
self.steps_mm[3] = float(reply_M503[reply_M503.find('Z',beginning)+1:(reply_M503.find('E',beginning)-1)])
self.direction[1] = DIRECTION.NORMAL if self.steps_mm[1]>0 else DIRECTION.REVERSE
self.direction[2] = DIRECTION.NORMAL if self.steps_mm[2]>0 else DIRECTION.REVERSE
self.direction[3] = DIRECTION.NORMAL if self.steps_mm[3]>0 else DIRECTION.REVERSE
# Ask the 4th one (if relevant) to the smartDrives
if self.isMMv2 and not onlyMarlin and not self.isMMv2OneDrive:
reply = self.myGCode.__askConfigToSmartDrives__(4)
if ( "Error" in str(reply) ) : # str() encoding is necessary for Python3
raise Exception('Error in gCode execution')
else :
parsedReply = self.__parseMessage(reply)
self.mech_gain[4] = parsedReply['gain']
self.u_step[4] = parsedReply['microSteps']
self.direction[4] = parsedReply['direction']
self.steps_mm[4] = self.deduce_steps_per_mm(self.mech_gain[4], self.u_step[4], self.direction[4])
return
def deduce_steps_per_mm(self, mech_gain, u_step, direction) :
steps_per_mm = abs(float(STEPPER_MOTOR.steps_per_turn) * float(u_step) / float(mech_gain))
return -steps_per_mm if direction == DIRECTION.REVERSE else steps_per_mm
def getDesiredPositions(self, axis=None):
'''
desc: Returns the desired position of the axes.
params:
axis (optional):
desc: The axis to get the desired position of.
type: Number
returnValue: The position of the axis if that parameter was specified, or a dictionary containing the desired position of every axis.
returnValueType: Number or Dictionary of numbers
note: This function returns the 'open loop' position of each axis.
compatibility: Recommended for MachineMotion v1.
exampleCodePath: getPositions.py
'''
desiredPositions = self.getCurrentPositions()
if isinstance(axis, int) : # Axis is a single number, return a number
self._restrictAxisValue(axis)
if axis == 4:
raise Exception("The desired position of the 4th axis is not supported.")
return desiredPositions[axis]
else : # Return the whole dictionary
return desiredPositions
def getCurrentPositions(self):
# Note : Deprecated this function, as it does not do what its name suggests...
# It returns the desired position, and not the current one.
reply = self.myGCode.__emitEchoOk__("M114")
positions = {
1 : float(reply[reply.find('X')+2:(reply.find('Y')-1)]),
2 : float(reply[reply.find('Y')+2:(reply.find('Z')-1)]),
3 : float(reply[reply.find('Z')+2:(reply.find('E')-1)])
}
# Note : The desired position of the 4th drive is unobtainable from the smartDrives.
return positions
def getActualPositions(self, axis=None):
'''
desc: Returns the current position of the axes.
params:
axis (optional):
desc: The axis to get the current position of.
type: Number
returnValue: The position of the axis if that parameter was specified, or a dictionary containing the current position of every axis.
returnValueType: Number or Dictionary of numbers
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: getPositions.py
'''
axes = [1, 2, 3]
if axis != None : # Restrict argument if we were given some
self._restrictAxisValue(axis)
axes = [axis]
# If MM v1, use M114, and read step counts.
if not self.isMMv2 :
# Find out step counts
reply_M114 = self.myGCode.__emitEchoOk__("M114")
beginning = reply_M114.find('Count')
step_count = {
1 : int(reply_M114[reply_M114.find('X',beginning)+3:(reply_M114.find('Y',beginning)-1)]),
2 : int(reply_M114[reply_M114.find('Y',beginning)+2:(reply_M114.find('Z',beginning)-1)]),
3 : int(reply_M114[reply_M114.find('Z',beginning)+2:(reply_M114.find(' ', reply_M114.find('Z',beginning)+2 ))])
}
# Find out step per mm and then calculate position
positions = {}
for drive in axes :
# If the steps_per_mm are not defined locally, retrieve them from Marlin
if not self._isNumber(self.steps_mm[drive]) :
self.populateStepsPerMm()
# Deduce position
positions[drive] = int( step_count[drive] / self.steps_mm[drive] )
# If MM v2, use smartDrive server route
else :
reply = self.myGCode.__askPositionToSmartDrives__()
if ( "Error" in str(reply) ) : # str() encoding is necessary for Python3
raise Exception('Error in gCode execution')
else:
parsedReply = self.__parseMessage(reply)
if not self.isMMv2OneDrive :
positions = {
1 : parsedReply['X'],
2 : parsedReply['Y'],
3 : parsedReply['Z'],
4 : parsedReply['W']
}
else:
positions = {1 : parsedReply['X']}
if isinstance(axis, int) : # Axis is a single number, return a number
return positions[axis]
else : # Return the whole dictionary
return positions
def getEndStopState(self):
'''
desc: Returns the current state of all home and end sensors.
returnValue: The states of all end stop sensors {x_min, x_max, y_min, y_max, z_min, z_max} "TRIGGERED" or "open"
returnValueType: Dictionary
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: getEndStopState.py
'''
if self.isMMv2OneDrive:
states = {
'x_min' : None,
'x_max' : None
}
else:
states = {
'x_min' : None,
'x_max' : None,
'y_min' : None,
'y_max' : None,
'z_min' : None,
'z_max' : None,
'w_min' : None,
'w_max' : None
}
def trimUntil(S, key) :
return S[S.find(key) + len(key) :]
reply = self.myGCode.__emitEchoOk__("M119")
#If Python 2.7
if sys.version_info.major < 3:
keyE = "\n"
#If Python 3
else:
keyE = "\\n"
#Remove first line (echo line)
reply = trimUntil(reply, keyE)
if "x_min" in reply :
keyB = "x_min: "
states['x_min'] = reply[(reply.find(keyB) + len(keyB)) : (reply.find(keyE))]
#Remove x_min line
reply = trimUntil(reply, keyE)
else : raise Exception('Error in gCode')
if "x_max" in reply :
keyB = "x_max: "
states['x_max'] = reply[(reply.find(keyB) + len(keyB)) : (reply.find(keyE))]
#Remove x_max line
reply = trimUntil(reply, keyE)
else : raise Exception('Error in gCode')
if not self.isMMv2OneDrive:
if "y_min" in reply :
keyB = "y_min: "
states['y_min'] = reply[(reply.find(keyB) + len(keyB)) : (reply.find(keyE))]
#Remove y_min line
reply = trimUntil(reply, keyE)
else : raise Exception('Error in gCode')
if "y_max" in reply :
keyB = "y_max: "
states['y_max'] = reply[(reply.find(keyB) + len(keyB)) : (reply.find(keyE))]
#Remove y_max line
reply = trimUntil(reply, keyE)
else : raise Exception('Error in gCode')
if "z_min" in reply :
keyB = "z_min: "
states['z_min'] = reply[(reply.find(keyB) + len(keyB)) : (reply.find(keyE))]
#Remove z_min line
reply = trimUntil(reply, keyE)
else : raise Exception('Error in gCode')
if "z_max" in reply :
keyB = "z_max: "
states['z_max'] = reply[(reply.find(keyB) + len(keyB)) : (reply.find(keyE))]
#Remove z_max line
reply = trimUntil(reply, keyE)
else : raise Exception('Error in gCode')
if "w_min" in reply :
keyB = "w_min: "
states['w_min'] = reply[(reply.find(keyB) + len(keyB)) : (reply.find(keyE))]
#Remove w_min line
reply = trimUntil(reply, keyE)
elif self.isMMv2 : raise Exception('Error in gCode')
if "w_max" in reply :
keyB = "w_max: "
states['w_max'] = reply[(reply.find(keyB) + len(keyB)) : (reply.find(keyE))]
#Remove w_max line
reply = trimUntil(reply, keyE)
elif self.isMMv2 : raise Exception('Error in gCode')
return states
def stopAllMotion(self):
'''
desc: Immediately stops all motion of all axes.
note: This function is a hard stop. It is not a controlled stop and consequently does not decelerate smoothly to a stop. Additionally, this function is not intended to serve as an emergency stop since this stop mechanism does not have safety ratings.
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: stopAllMotion.py
'''
return self.myGCode.__emitEchoOk__("M410")
def moveToHomeAll(self):
'''
desc: Initiates the homing sequence of all axes. All axes will move home sequentially.
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: moveToHomeAll.py
'''
try:
return self.myGCode.__emitEchoOk__("G28", timeout=DEFAULT_TIMEOUT * 5)
except Exception as e:
self.stopAllMotion()
raise e
def moveToHome(self, axis):
'''
desc: Initiates the homing sequence for the specified axis.
params:
axis:
desc: The axis to be homed.
type: Number
note: If configAxisDirection is set to "normal" on axis 1, axis 1 will home itself towards sensor 1A. If configAxisDirection is set to "reverse" on axis 1, axis 1 will home itself towards sensor 1B.
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: moveToHome.py
'''
self._restrictAxisValue(axis)
gCode = "G28 " + self.myGCode.__getTrueAxis__(axis)
try:
return self.myGCode.__emitEchoOk__(gCode, timeout=DEFAULT_TIMEOUT * 5)
except Exception as e:
self.stopAllMotion()
raise e
def setSpeed(self, speed, units = UNITS_SPEED.mm_per_sec):
'''
desc: Sets the global speed for all movement commands on all axes.
params:
speed:
desc: The global max speed in mm/sec, or mm/min according to the units parameter.
type: Number
units:
desc: Units for speed. Can be switched to UNITS_SPEED.mm_per_min
defaultValue: UNITS_SPEED.mm_per_sec
type: String
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: setSpeed.py
'''
self._restrictInputValue("units", units, UNITS_SPEED)
if units == UNITS_SPEED.mm_per_min:
speed_mm_per_min = speed
elif units == UNITS_SPEED.mm_per_sec:
speed_mm_per_min = 60*speed
self.myGCode.__emitEchoOk__("G0 F" +str(speed_mm_per_min))
return
def setAcceleration(self, acceleration, units=UNITS_ACCEL.mm_per_sec_sqr):
'''
desc: Sets the global acceleration for all movement commands on all axes.
params:
mm_per_sec_sqr:
desc: The global acceleration in mm/s^2.
type: Number
units:
desc: Units for speed. Can be switched to UNITS_ACCEL.mm_per_min_sqr
defaultValue: UNITS_ACCEL.mm_per_sec_sqr
type: String
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: setAcceleration.py
'''
self._restrictInputValue("units", units, UNITS_ACCEL)
if units == UNITS_ACCEL.mm_per_sec_sqr:
accel_mm_per_sec_sqr = acceleration
elif units == UNITS_ACCEL.mm_per_min_sqr:
accel_mm_per_sec_sqr = acceleration/3600
# Note : Set travel and print acceleration, to impact G0 and G1 commands.
self.myGCode.__emitEchoOk__("M204 T" + str(accel_mm_per_sec_sqr) + " P" + str(accel_mm_per_sec_sqr))
return
def moveToPosition(self, axis, position):
'''
desc: Moves the specified axis to a desired end location.
params:
axis:
desc: The axis which will perform the absolute move command.
type: Number
position:
desc: The desired end position of the axis movement.
type: Number
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: moveToPosition.py
'''
self._restrictAxisValue(axis)
# Set to absolute motion mode
self.myGCode.__emitEchoOk__("G90")
# Transmit move command
self.myGCode.__emitEchoOk__("G0 " + self.myGCode.__getTrueAxis__(axis) + str(position))
return
def moveToPositionCombined(self, axes, positions):
'''
desc: Moves multiple specified axes to their desired end locations synchronously.
params:
axes:
desc: The axes which will perform the move commands. Ex - [1 ,3]
type: List
positions:
desc: The desired end position of all axess movement. Ex - [50, 10]
type: List
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: moveToPositionCombined.py
note: The current speed and acceleration settings are applied to the combined motion of the axes.
'''
if (not isinstance(axes, list) or not isinstance(positions, list)):
raise TypeError("Axes and Positions must be lists")
for axis in axes:
self._restrictAxisValue(axis)
# Set to absolute motion mode
self.myGCode.__emitEchoOk__("G90")
# Transmit move command
command = "G0"
for axis, position in zip(axes, positions):
command += " " + self.myGCode.__getTrueAxis__(axis) + str(position)
self.myGCode.__emitEchoOk__(command)
return
def moveRelative(self, axis, distance):
'''
desc: Moves the specified axis the specified distance.
params:
axis:
desc: The axis to move.
type: Integer
distance:
desc: The travel distance in mm.
type: Number
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: moveRelative.py
'''
self._restrictAxisValue(axis)
# Set to relative motion mode
self.myGCode.__emitEchoOk__("G91")
# Transmit move command
self.myGCode.__emitEchoOk__("G0 " + self.myGCode.__getTrueAxis__(axis) + str(distance))
return
def moveRelativeCombined(self, axes, distances):
'''
desc: Moves the multiple specified axes the specified distances.
params:
axes:
desc: The axes to move. Ex-[1,3]
type: List of Integers
distances:
desc: The travel distances in mm. Ex - [10, 40]
type: List of Numbers
compatibility: MachineMotion v1 and MachineMotion v2.
exampleCodePath: moveRelativeCombined.py
note: The current speed and acceleration settings are applied to the combined motion of the axes.
'''
if (not isinstance(axes, list) or not isinstance(distances, list)):
raise TypeError("Axes and Distances must be lists")
for axis in axes:
self._restrictAxisValue(axis)
# Set to relative motion mode
self.myGCode.__emitEchoOk__("G91")
# Transmit move command
command = "G0"
for axis, distance in zip(axes, distances):
command += " " + self.myGCode.__getTrueAxis__(axis) + str(distance)
self.myGCode.__emitEchoOk__(command)
return