forked from vlachoudis/bCNC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CNC.py
4141 lines (3682 loc) · 120 KB
/
CNC.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
# -*- coding: ascii -*-
# $Id: CNC.py,v 1.8 2014/10/15 15:03:49 bnv Exp $
#
# Author: [email protected]
# Date: 24-Aug-2014
import os
import re
import pdb
import sys
import math
import types
import random
import string
import undo
import Unicode
from dxf import DXF
from stl import Binary_STL_Writer
from bpath import eq,Path, Segment
from bmath import *
IDPAT = re.compile(r".*\bid:\s*(.*?)\)")
PARENPAT = re.compile(r"(\(.*?\))")
SEMIPAT = re.compile(r"(;.*)")
OPPAT = re.compile(r"(.*)\[(.*)\]")
CMDPAT = re.compile(r"([A-Za-z]+)")
BLOCKPAT = re.compile(r"^\(Block-([A-Za-z]+):\s*(.*)\)")
AUXPAT = re.compile(r"^(%[A-Za-z0-9]+)\b *(.*)$")
STOP = 0
SKIP = 1
ASK = 2
MSG = 3
WAIT = 4
UPDATE = 5
XY = 0
XZ = 1
YZ = 2
CW = 2
CCW = 3
WCS = ["G54", "G55", "G56", "G57", "G58", "G59"]
DISTANCE_MODE = { "G90" : "Absolute",
"G91" : "Incremental" }
FEED_MODE = { "G93" : "1/Time",
"G94" : "unit/min",
"G95" : "unit/rev"}
UNITS = { "G20" : "inch",
"G21" : "mm" }
PLANE = { "G17" : "XY",
"G18" : "ZX",
"G19" : "YZ" }
# Modal Mode from $G and variable set
MODAL_MODES = {
"G0" : "motion",
"G1" : "motion",
"G2" : "motion",
"G3" : "motion",
"G38.2" : "motion",
"G38.3" : "motion",
"G38.4" : "motion",
"G38.5" : "motion",
"G80" : "motion",
"G54" : "WCS",
"G55" : "WCS",
"G56" : "WCS",
"G57" : "WCS",
"G58" : "WCS",
"G59" : "WCS",
"G17" : "plane",
"G18" : "plane",
"G19" : "plane",
"G90" : "distance",
"G91" : "distance",
"G91.1" : "arc",
"G93" : "feedmode",
"G94" : "feedmode",
"G95" : "feedmode",
"G20" : "units",
"G21" : "units",
"G40" : "cutter",
"G43.1" : "tlo",
"G49" : "tlo",
"M0" : "program",
"M1" : "program",
"M2" : "program",
"M30" : "program",
"M3" : "spindle",
"M4" : "spindle",
"M5" : "spindle",
"M7" : "coolant",
"M8" : "coolant",
"M9" : "coolant",
}
ERROR_HANDLING = {}
TOLERANCE = 1e-7
MAXINT = 1000000000 # python3 doesn't have maxint
#------------------------------------------------------------------------------
# Return a value combined from two dictionaries new/old
#------------------------------------------------------------------------------
def getValue(name,new,old,default=0.0):
try:
return new[name]
except:
try:
return old[name]
except:
return default
#===============================================================================
# Probing class and linear interpolation
#===============================================================================
class Probe:
def __init__(self):
self.init()
#----------------------------------------------------------------------
def init(self):
self.filename = ""
self.xmin = 0.0
self.ymin = 0.0
self.zmin = -10.0
self.xmax = 10.0
self.ymax = 10.0
self.zmax = 3.0
self._xstep = 1.0
self._ystep = 1.0
self.xn = 5
self.yn = 5
self.points = [] # probe points
self.matrix = [] # 2D matrix with Z coordinates
self.zeroed = False # if probe was zeroed at any location
self.start = False # start collecting probes
self.saved = False
#----------------------------------------------------------------------
def clear(self):
del self.points[:]
del self.matrix[:]
self.zeroed = False
self.start = False
self.saved = False
#----------------------------------------------------------------------
def isEmpty(self): return len(self.matrix)==0
#----------------------------------------------------------------------
def makeMatrix(self):
del self.matrix[:]
for j in range(self.yn):
self.matrix.append([0.0]*(self.xn))
#----------------------------------------------------------------------
# Load autolevel information from file
#----------------------------------------------------------------------
def load(self, filename=None):
if filename is not None:
self.filename = filename
self.clear()
self.saved = True
def read(f):
while True:
line = f.readline()
if len(line)==0: raise
line = line.strip()
if line: return map(float, line.split())
f = open(self.filename,"r")
self.xmin, self.xmax, self.xn = read(f)
self.ymin, self.ymax, self.yn = read(f)
self.zmin, self.zmax, feed = read(f)
CNC.vars["prbfeed"] = feed
self.xn = max(2,int(self.xn))
self.yn = max(2,int(self.yn))
self.makeMatrix()
self.xstep()
self.ystep()
self.start = True
try:
for j in range(self.yn):
for i in range(self.xn):
self.add(*read(f))
except:
raise
#print "Error reading probe file",self.filename
f.close()
#----------------------------------------------------------------------
# Save level information to file
#----------------------------------------------------------------------
def save(self, filename=None):
if filename is not None:
self.filename = filename
f = open(self.filename,"w")
f.write("%g %g %d\n"%(self.xmin, self.xmax, self.xn))
f.write("%g %g %d\n"%(self.ymin, self.ymax, self.yn))
f.write("%g %g %g\n"%(self.zmin, self.zmax, CNC.vars["prbfeed"]))
f.write("\n\n")
for j in range(self.yn):
y = self.ymin + self._ystep*j
for i in range(self.xn):
x = self.xmin + self._xstep*i
f.write("%g %g %g\n"%(x,y,self.matrix[j][i]))
f.write("\n")
f.close()
self.saved = True
#----------------------------------------------------------------------
# Save level information as STL file
#----------------------------------------------------------------------
def saveAsSTL(self, filename=None):
if filename is not None:
self.filename = filename
with open(self.filename, 'wb') as fp:
writer = Binary_STL_Writer(fp)
for j in range(self.yn -1):
y1 = self.ymin + self._ystep*j
y2 = self.ymin + self._ystep*(j+1)
for i in range(self.xn -1):
x1 = self.xmin + self._xstep*i
x2 = self.xmin + self._xstep*(i+1)
v1=[x1,y1,self.matrix[j][i]]
v2=[x2,y1,self.matrix[j][i+1]]
v3=[x2,y2,self.matrix[j+1][i+1]]
v4=[x1,y2,self.matrix[j+1][i]]
writer.add_face([v1,v2,v3,v4])
writer.close()
#----------------------------------------------------------------------
# Return step
#----------------------------------------------------------------------
def xstep(self):
self._xstep = (self.xmax-self.xmin)/float(self.xn-1)
return self._xstep
#----------------------------------------------------------------------
def ystep(self):
self._ystep = (self.ymax-self.ymin)/float(self.yn-1)
return self._ystep
#----------------------------------------------------------------------
# Return the code needed to scan for autoleveling
#----------------------------------------------------------------------
def scan(self):
self.clear()
self.start = True
self.makeMatrix()
x = self.xmin
xstep = self._xstep
lines = ["F%g"%(CNC.vars["feed"]),
"G0Z%.4f"%(CNC.vars["safe"]),
"G0X%.4fY%.4f"%(self.xmin, self.ymin)]
for j in range(self.yn):
y = self.ymin + self._ystep*j
for i in range(self.xn):
lines.append("F%g"%(CNC.vars["feed"]))
lines.append("G0Z%.4f"%(self.zmax))
lines.append("G0X%.4fY%.4f"%(x,y))
lines.append("%wait")
lines.append("%sZ%.4fF%g"%(CNC.vars["prbcmd"], self.zmin, CNC.vars["prbfeed"]))
lines.append("%wait")
x += xstep
x -= xstep
xstep = -xstep
lines.append("F%g"%(CNC.vars["feed"]))
lines.append("G0Z%.4f"%(self.zmax))
lines.append("G0X%.4fY%.4f"%(self.xmin,self.ymin))
return lines
#----------------------------------------------------------------------
# Add a probed point to the list and the 3D matrix
#----------------------------------------------------------------------
def add(self, x,y,z):
if not self.start: return
i = round((x-self.xmin) / self._xstep)
if i<0.0 or i>self.xn: return
j = round((y-self.ymin) / self._ystep)
if j<0.0 or j>self.yn: return
rem = abs(x - (i*self._xstep + self.xmin))
if rem > self._xstep/10.0: return
rem = abs(y - (j*self._ystep + self.ymin))
if rem > self._ystep/10.0: return
try:
self.matrix[int(j)][int(i)] = z
self.points.append([x,y,z])
except IndexError:
pass
if len(self.points) >= self.xn*self.yn:
self.start = False
#----------------------------------------------------------------------
# Make z-level relative to the location of (x,y,0)
#----------------------------------------------------------------------
def setZero(self, x, y):
del self.points[:]
if self.isEmpty():
self.zeroed = False
return
zero = self.interpolate(x,y)
self.xstep()
self.ystep()
for j,row in enumerate(self.matrix):
y = self.ymin + self._ystep*j
for i in range(len(row)):
x = self.xmin + self._xstep*i
row[i] -= zero
self.points.append([x,y,row[i]])
self.zeroed = True
#----------------------------------------------------------------------
def interpolate(self, x, y):
ix = (x-self.xmin) / self._xstep
jy = (y-self.ymin) / self._ystep
i = int(math.floor(ix))
j = int(math.floor(jy))
if i<0:
i = 0
elif i>=self.xn-1:
i = self.xn-2
if j<0:
j = 0
elif j>=self.yn-1:
j = self.yn-2
a = ix - i
b = jy - j
a1 = 1.0 - a
b1 = 1.0 - b
return a1*b1 * self.matrix[j][i] + \
a1*b * self.matrix[j+1][i] + \
a *b1 * self.matrix[j][i+1] + \
a *b * self.matrix[j+1][i+1]
#----------------------------------------------------------------------
# Split line into multiple segments correcting for Z if needed
# return only end points
#----------------------------------------------------------------------
def splitLine(self, x1, y1, z1, x2, y2, z2):
dx = x2-x1
dy = y2-y1
dz = z2-z1
if abs(dx)<1e-10: dx = 0.0
if abs(dy)<1e-10: dy = 0.0
if abs(dz)<1e-10: dz = 0.0
if dx==0.0 and dy==0.0:
return [(x2,y2,z2+self.interpolate(x2,y2))]
# Length along projection on X-Y plane
rxy = math.sqrt(dx*dx + dy*dy)
dx /= rxy # direction cosines along XY plane
dy /= rxy
dz /= rxy # add correction for the slope in Z, versus the travel in XY
i = int(math.floor((x1-self.xmin) / self._xstep))
j = int(math.floor((y1-self.ymin) / self._ystep))
if dx > 1e-10:
tx = (float(i+1)*self._xstep+self.xmin - x1)/ dx # distance to next cell
tdx = self._xstep / dx
elif dx < -1e-10:
tx = (float(i)*self._xstep+self.xmin - x1)/ dx # distance to next cell
tdx = -self._xstep / dx
else:
tx = 1e10
tdx = 0.0
if dy > 1e-10:
ty = (float(j+1)*self._ystep+self.ymin - y1)/ dy # distance to next cell
tdy = self._ystep / dy
elif dy < -1e-10:
ty = (float(j)*self._ystep+self.ymin - y1)/ dy # distance to next cell
tdy = -self._ystep / dy
else:
ty = 1e10
tdy = 0.0
segments = []
rxy *= 0.999999999 # just reduce a bit to avoid precision errors
while tx<rxy or ty<rxy:
if tx==ty:
t = tx
tx += tdx
ty += tdy
elif tx<ty:
t = tx
tx += tdx
else:
t = ty
ty += tdy
x = x1 + t*dx
y = y1 + t*dy
z = z1 + t*dz
segments.append((x,y,z+self.interpolate(x,y)))
segments.append((x2,y2,z2+self.interpolate(x2,y2)))
return segments
#===============================================================================
# contains a list of machine points vs position in the gcode
# calculates the transformation matrix (rotation + translation) needed
# to adjust the gcode to match the workpiece on the machine
#===============================================================================
class Orient:
#-----------------------------------------------------------------------
def __init__(self):
self.markers = [] # list of points pairs (xm, ym, x, y)
# xm,ym = machine x,y mpos
# x, y = desired or gcode location
self.paths = []
self.errors = []
self.filename = ""
self.clear()
#-----------------------------------------------------------------------
def clear(self, item=None):
if item is None:
self.clearPaths()
del self.markers[:]
else:
del self.paths[item]
del self.markers[item]
self.phi = 0.0
self.xo = 0.0
self.yo = 0.0
self.valid = False
self.saved = False
#-----------------------------------------------------------------------
def clearPaths(self):
del self.paths[:]
#-----------------------------------------------------------------------
def add(self, xm, ym, x, y):
self.markers.append((xm,ym,x,y))
self.valid = False
self.saved = False
#-----------------------------------------------------------------------
def addPath(self, path):
self.paths.append(path)
#-----------------------------------------------------------------------
def __getitem__(self, i):
return self.markers[i]
#-----------------------------------------------------------------------
def __len__(self):
return len(self.markers)
#-----------------------------------------------------------------------
# Return the rotation angle phi in radians and the offset (xo,yo)
# or none on failure
# Transformation equation is the following
#
# Xm = R * X + T
#
# Xm = [xm ym]^t
# X = [x y]^t
#
#
# / cosf -sinf \ / c -s \
# R = | | = | |
# \ sinf cosf / \ s c /
#
# Assuming that the machine is squared. We could even solve it for
# a skewed machine, but then the arcs have to be converted to
# ellipses...
#
# T = [xo yo]^t
#
# The overdetermined system (equations) to solve are the following
# c*x + s*(-y) + xo = xm
# s*x + c*y + yo = ym
# <=> c*y + s*y + yo = ym
#
# We are solving for the unknowns c,s,xo,yo
#
# / x1 -y1 1 0 \ / c \ / xm1 \
# | y1 x1 0 1 | | s | | ym1 |
# | x2 -y2 1 0 | | xo | | xm2 |
# | y2 x2 0 1 | \ yo / = | ym2 |
# ... ..
# | xn -yn 1 0 | | xmn |
# \ yn xn 0 1 / \ ymn /
#
# A X = B
#
# Constraints:
# 1. orthogonal system c^2 + s^2 = 1
# 2. no aspect ratio
#
#-----------------------------------------------------------------------
def solve(self):
self.valid = False
if len(self.markers)< 2: raise Exception("Too few markers")
A = []
B = []
for xm,ym,x,y in self.markers:
A.append([x,-y,1.0,0.0]); B.append([xm])
A.append([y, x,0.0,1.0]); B.append([ym])
# The solution of the overdetermined system A X = B
try:
c,s,self.xo,self.yo = solveOverDetermined(Matrix(A),Matrix(B))
except:
raise Exception("Unable to solve system")
#print "c,s,xo,yo=",c,s,xo,yo
# Normalize the coefficients
r = sqrt(c*c + s*s) # length should be 1.0
if abs(r-1.0) > 0.1:
raise Exception("Resulting system is too skew")
# print "r=",r
#xo /= r
#yo /= r
self.phi = atan2(s, c)
if abs(self.phi)<TOLERANCE: self.phi = 0.0 # rotation
self.valid = True
return self.phi,self.xo,self.yo
#-----------------------------------------------------------------------
# @return minimum, average and maximum error
#-----------------------------------------------------------------------
def error(self):
# Type errors
minerr = 1e9
maxerr = 0.0
sumerr = 0.0
c = cos(self.phi)
s = sin(self.phi)
del self.errors[:]
for i,(xm,ym,x,y) in enumerate(self.markers):
dx = c*x - s*y + self.xo - xm
dy = s*x + c*y + self.yo - ym
err = sqrt(dx**2 + dy**2)
self.errors.append(err)
minerr = min(minerr, err)
maxerr = max(maxerr, err)
sumerr += err
return minerr, sumerr/float(len(self.markers)), maxerr
#-----------------------------------------------------------------------
# Convert gcode to machine coordinates
#-----------------------------------------------------------------------
def gcode2machine(self, x, y):
c = cos(self.phi)
s = sin(self.phi)
return c*x - s*y + self.xo, \
s*x + c*y + self.yo
#-----------------------------------------------------------------------
# Convert machine to gcode coordinates
#-----------------------------------------------------------------------
def machine2gcode(self, x, y):
c = cos(self.phi)
s = sin(self.phi)
x -= self.xo
y -= self.yo
return c*x + s*y, \
-s*x + c*y
#----------------------------------------------------------------------
# Load orient information from file
#----------------------------------------------------------------------
def load(self, filename=None):
if filename is not None:
self.filename = filename
self.clear()
self.saved = True
f = open(self.filename,"r")
for line in f:
self.add(*map(float, line.split()))
f.close()
#----------------------------------------------------------------------
# Save orient information to file
#----------------------------------------------------------------------
def save(self, filename=None):
if filename is not None:
self.filename = filename
f = open(self.filename,"w")
for xm,ym,x,y in self.markers:
f.write("%g %g %g %g\n"%(xm,ym,x,y))
f.close()
self.saved = True
#===============================================================================
# Command operations on a CNC
#===============================================================================
class CNC:
inch = False
lasercutter = False
acceleration_x = 25.0 # mm/s^2
acceleration_y = 25.0 # mm/s^2
acceleration_z = 25.0 # mm/s^2
feedmax_x = 3000
feedmax_y = 3000
feedmax_z = 2000
travel_x = 300
travel_y = 300
travel_z = 60
accuracy = 0.02 # sagitta error during arc conversion
digits = 4
startup = "G90"
stdexpr = False # standard way of defining expressions with []
comment = "" # last parsed comment
developer = False
drozeropad = 0
vars = {
"prbx" : 0.0,
"prby" : 0.0,
"prbz" : 0.0,
"prbcmd" : "G38.2",
"prbfeed" : 10.,
"errline" : "",
"wx" : 0.0,
"wy" : 0.0,
"wz" : 0.0,
"mx" : 0.0,
"my" : 0.0,
"mz" : 0.0,
"wcox" : 0.0,
"wcoy" : 0.0,
"wcoz" : 0.0,
"curfeed" : 0.0,
"curspindle" : 0.0,
"_camwx" : 0.0,
"_camwy" : 0.0,
"G" : [],
"TLO" : 0.0,
"motion" : "G0",
"WCS" : "G54",
"plane" : "G17",
"feedmode" : "G94",
"distance" : "G90",
"arc" : "G91.1",
"units" : "G20",
"cutter" : "",
"tlo" : "",
"program" : "M0",
"spindle" : "M5",
"coolant" : "M9",
"tool" : 0,
"feed" : 0.0,
"rpm" : 0.0,
"planner" : 0,
"rxbytes" : 0,
"OvFeed" : 100, # Override status
"OvRapid" : 100,
"OvSpindle" : 100,
"_OvChanged" : False,
"_OvFeed" : 100, # Override target values
"_OvRapid" : 100,
"_OvSpindle" : 100,
"diameter" : 3.175, # Tool diameter
"cutfeed" : 1000., # Material feed for cutting
"cutfeedz" : 500., # Material feed for cutting
"safe" : 3.,
"state" : "",
"msg" : "",
"stepz" : 1.,
"surface" : 0.,
"thickness" : 5.,
"stepover" : 40.,
"PRB" : None,
"TLO" : 0.,
"version" : "",
"running" : False,
}
drillPolicy = 1 # Expand Canned cycles
toolPolicy = 1 # Should be in sync with ProbePage
# 0 - send to grbl
# 1 - skip those lines
# 2 - manual tool change (WCS)
# 3 - manual tool change (TLO)
# 4 - manual tool change (No Probe)
toolWaitAfterProbe = True # wait at tool change position after probing
appendFeed = False # append feed on every G1/G2/G3 commands to be used
# for feed override testing
# FIXME will not be needed after Grbl v1.0
#----------------------------------------------------------------------
def __init__(self):
self.initPath()
self.resetAllMargins()
#----------------------------------------------------------------------
# Update G variables from "G" string
#----------------------------------------------------------------------
@staticmethod
def updateG():
for g in CNC.vars["G"]:
if g[0] == "F":
CNC.vars["feed"] = float(g[1:])
elif g[0] == "S":
CNC.vars["rpm"] = float(g[1:])
elif g[0] == "T":
CNC.vars["tool"] = int(g[1:])
else:
var = MODAL_MODES.get(g)
if var is not None:
CNC.vars[var] = g
#----------------------------------------------------------------------
def __getitem__(self, name):
return CNC.vars[name]
#----------------------------------------------------------------------
def __setitem__(self, name, value):
CNC.vars[name] = value
#----------------------------------------------------------------------
@staticmethod
def loadConfig(config):
section = "CNC"
try: CNC.inch = bool(int(config.get(section, "units")))
except: pass
try: CNC.lasercutter = bool(int(config.get(section, "lasercutter")))
except: pass
try: CNC.doublesizeicon = bool(int(config.get(section, "doublesizeicon")))
except: pass
try: CNC.acceleration_x = float(config.get(section, "acceleration_x"))
except: pass
try: CNC.acceleration_y = float(config.get(section, "acceleration_y"))
except: pass
try: CNC.acceleration_z = float(config.get(section, "acceleration_z"))
except: pass
try: CNC.feedmax_x = float(config.get(section, "feedmax_x"))
except: pass
try: CNC.feedmax_y = float(config.get(section, "feedmax_y"))
except: pass
try: CNC.feedmax_z = float(config.get(section, "feedmax_z"))
except: pass
try: CNC.travel_x = float(config.get(section, "travel_x"))
except: pass
try: CNC.travel_y = float(config.get(section, "travel_y"))
except: pass
try: CNC.travel_z = float(config.get(section, "travel_z"))
except: pass
try: CNC.travel_z = float(config.get(section, "travel_z"))
except: pass
try: CNC.accuracy = float(config.get(section, "accuracy"))
except: pass
try: CNC.digits = int( config.get(section, "round"))
except: pass
try: CNC.drozeropad = int( config.get(section, "drozeropad"))
except: pass
CNC.startup = config.get(section, "startup")
CNC.header = config.get(section, "header")
CNC.footer = config.get(section, "footer")
if CNC.inch:
CNC.acceleration_x /= 25.4
CNC.acceleration_y /= 25.4
CNC.acceleration_z /= 25.4
CNC.feedmax_x /= 25.4
CNC.feedmax_y /= 25.4
CNC.feedmax_z /= 25.4
CNC.travel_x /= 25.4
CNC.travel_y /= 25.4
CNC.travel_z /= 25.4
section = "Error"
for cmd,value in config.items(section):
try:
ERROR_HANDLING[cmd.upper()] = int(value)
except:
pass
#----------------------------------------------------------------------
@staticmethod
def saveConfig(config):
pass
#----------------------------------------------------------------------
def initPath(self, x=None, y=None, z=None):
if x is None:
self.x = self.xval = 0
else:
self.x = self.xval = x
if y is None:
self.y = self.yval = 0
else:
self.y = self.yval = y
if z is None:
self.z = self.zval = 0
else:
self.z = self.zval = z
self.ival = self.jval = self.kval = 0.0
self.uval = self.vval = self.wval = 0.0
self.dx = self.dy = self.dz = 0.0
self.di = self.dj = self.dk = 0.0
self.rval = 0.0
self.pval = 0.0
self.qval = 0.0
self.unit = 1.0
self.mval = 0
self.lval = 1
self.tool = 0
self._lastTool = None
self.absolute = True # G90/G91 absolute/relative motion
self.arcabsolute = False # G90.1/G91.1 absolute/relative arc
self.retractz = True # G98/G99 retract to Z or R
self.gcode = None
self.plane = XY
self.feed = 0 # Actual gcode feed rate (not to confuse with cutfeed
self.totalLength = 0.0
self.totalTime = 0.0
#----------------------------------------------------------------------
def resetEnableMargins(self):
# Selected blocks margin
CNC.vars["xmin"] = CNC.vars["ymin"] = CNC.vars["zmin"] = 1000000.0
CNC.vars["xmax"] = CNC.vars["ymax"] = CNC.vars["zmax"] = -1000000.0
#----------------------------------------------------------------------
def resetAllMargins(self):
self.resetEnableMargins()
# All blocks margin
CNC.vars["axmin"] = CNC.vars["aymin"] = CNC.vars["azmin"] = 1000000.0
CNC.vars["axmax"] = CNC.vars["aymax"] = CNC.vars["azmax"] = -1000000.0
#----------------------------------------------------------------------
@staticmethod
def isMarginValid():
return CNC.vars["xmin"] <= CNC.vars["xmax"] and \
CNC.vars["ymin"] <= CNC.vars["ymax"] and \
CNC.vars["zmin"] <= CNC.vars["zmax"]
#----------------------------------------------------------------------
@staticmethod
def isAllMarginValid():
return CNC.vars["axmin"] <= CNC.vars["axmax"] and \
CNC.vars["aymin"] <= CNC.vars["aymax"] and \
CNC.vars["azmin"] <= CNC.vars["azmax"]
#----------------------------------------------------------------------
# Number formating
#----------------------------------------------------------------------
@staticmethod
def fmt(c, v, d=None):
if d is None: d = CNC.digits
return ("%s%*f"%(c,d,v)).rstrip("0").rstrip(".")
#----------------------------------------------------------------------
@staticmethod
def gcode(g, pairs):
s = "g%d"%(g)
for c,v in pairs:
s += " %c%g"%(c, round(v,CNC.digits))
return s
#----------------------------------------------------------------------
@staticmethod
def _gcode(g, **args):
s = "g%d"%(g)
for n,v in args.items():
s += ' ' + CNC.fmt(n,v)
return s
#----------------------------------------------------------------------
@staticmethod
def _goto(g, x=None, y=None, z=None, **args):
s = "g%d"%(g)
if x is not None: s += ' '+CNC.fmt('x',x)
if y is not None: s += ' '+CNC.fmt('y',y)
if z is not None: s += ' '+CNC.fmt('z',z)
for n,v in args.items():
s += ' ' + CNC.fmt(n,v)
return s
#----------------------------------------------------------------------
@staticmethod
def grapid(x=None, y=None, z=None, **args):
return CNC._goto(0,x,y,z,**args)
#----------------------------------------------------------------------
@staticmethod
def gline(x=None, y=None, z=None, **args):
return CNC._goto(1,x,y,z,**args)
#----------------------------------------------------------------------
@staticmethod
def glinev(g, v, feed=None):
pairs = zip("xyz",v)
if feed is not None:
pairs.append(("f",feed))
return CNC.gcode(g, pairs)
#----------------------------------------------------------------------
@staticmethod
def garcv(g, v, ijk):
return CNC.gcode(g, zip("xyz",v) + zip("ij",ijk[:2]))
#----------------------------------------------------------------------
@staticmethod
def garc(g, x=None, y=None, z=None, i=None, j=None, k=None, **args):
s = "g%d"%(g)
if x is not None: s += ' '+CNC.fmt('x',x)
if y is not None: s += ' '+CNC.fmt('y',y)
if z is not None: s += ' '+CNC.fmt('z',z)
if i is not None: s += ' '+CNC.fmt('i',i)
if j is not None: s += ' '+CNC.fmt('j',j)
if k is not None: s += ' '+CNC.fmt('k',k)
for n,v in args.items():
s += ' ' + CNC.fmt(n,v)
return s
#----------------------------------------------------------------------
# Enter to material or start the laser
#----------------------------------------------------------------------
@staticmethod
def zenter(z):
if CNC.lasercutter:
return "m3"
else:
return "g1 %s %s"%(CNC.fmt("z",z), CNC.fmt("f",CNC.vars["cutfeedz"]))
#----------------------------------------------------------------------
@staticmethod
def zexit(z):
if CNC.lasercutter:
return "m5"
else:
return "g0 %s"%(CNC.fmt("z",z))
#----------------------------------------------------------------------
# gcode to go to z-safe
# Exit from material or stop the laser
#----------------------------------------------------------------------
@staticmethod
def zsafe():
return CNC.zexit(CNC.vars["safe"])
#----------------------------------------------------------------------
# @return line in broken a list of commands, None if empty or comment
#----------------------------------------------------------------------
@staticmethod
def parseLine(line):
# skip empty lines
if len(line)==0 or line[0] in ("%","(","#",";"):
return None