-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate_post.py
More file actions
646 lines (516 loc) · 23.6 KB
/
template_post.py
File metadata and controls
646 lines (516 loc) · 23.6 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
# ***************************************************************************
# * Copyright (c) 2014 sliptonic <shopinthewoods@gmail.com> *
# * Copyright (c) 2026 Mark Riem <mriem667@gmail.com> *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
import FreeCAD
from FreeCAD import Units
import Path
import argparse
import datetime
import shlex
import Path.Post.Utils as PostUtils
import PathScripts.PathUtils as PathUtils
from builtins import open as pyopen
import re
import copy
TOOLTIP = """
This is a postprocessor file for the CAM workbench. It is used to
take a pseudo-G-code fragment outputted by a Path object, and output
real G-code suitable for gcode laser cutter. This postprocessor, once placed
in the Macro folder, can be used directly from inside
FreeCAD, via the GUI importer or via python scripts with:
import laser_post
laser_post.export(object,"/path/to/file.ncc","")
"""
now = datetime.datetime.now()
arg_parser = argparse.ArgumentParser(prog="laser", add_help=False)
arg_parser.add_argument(
"--no-show-editor",
action="store_true",
help="don't pop up editor before writing output"
)
arg_parser.add_argument(
"--precision", default="4",
help="number of digits of precision, default=4"
)
arg_parser.add_argument(
"--inches", action="store_true",
help="Convert output for US imperial mode (G20)"
)
arg_parser.add_argument(
"--preamble",
help='set commands to be issued before the first command, default="G17\nG90"'
)
arg_parser.add_argument(
"--postamble",
help='set commands to be issued after the last command, default="G17 G90\nM2"'
)
arg_parser.add_argument(
"--laser-on",
help="Command to turn laser on, use \\n for newline.Default is M3"
)
arg_parser.add_argument(
"--laser-off",
help="Command to turn laser on, use \\n for newline.Default is M5"
)
arg_parser.add_argument(
"--laser-power",
help='"Laser power command, use \\n for newline.Default is spindle speed "S####"Use "NONE" or "" to suppress any power commands.'
)
arg_parser.add_argument(
"--laser-3d",
action="store_true",
help="Format gcode for 3d laser"
)
TOOLTIP_ARGS = arg_parser.format_help()
def processArguments(argstring, parser):
try:
args = arg_parser.parse_args(shlex.split(argstring))
if args.no_show_editor:
parser.variables.SHOW_EDITOR = False
print("Show editor = %d" % parser.variables.SHOW_EDITOR)
parser.variables.PRECISION = args.precision
if args.inches:
parser.variables.UNITS = "G20"
parser.variables.UNIT_SPEED_FORMAT = "in/min"
parser.variables.UNIT_FORMAT = "in"
parser.variables.PRECISION = 4
if args.preamble is not None:
parser.variables.PREAMBLE = args.preamble.replace("\\n", '\n')
if args.postamble is not None:
parser.variables.POSTAMBLE = args.postamble.replace("\\n", '\n')
if args.laser_on is not None:
parser.variables.LASER_ON = args.laser_on.replace("\\n", '\n')
if args.laser_off is not None:
parser.variables.LASER_OFF = args.laser_off.replace("\\n", '\n')
if args.laser_power is not None:
parser.variables.LASER_POWER = args.laser_power.replace("NONE", "")
parser.variables.LASER_POWER = args.laser_power.replace("\\n", '\n')
if args.laser_3d:
parser.variables.LASER_3D = True
except Exception:
return False
return True
class Variables:
def __init__(self):
self.SHOW_EDITOR = True
self.UNITS = "G21"
self.UNIT_SPEED_FORMAT = "mm/min"
self.UNIT_FORMAT = "mm"
self.PRECISION = 4
self.PREAMBLE = "G17 G90"
self.POSTAMBLE = "G17 G90\nM2"
self.LASER_ON = "M3"
self.LASER_OFF = "M5"
self.LASER_POWER = "S0"
self.LASER_3D = False
class ParserState:
def __init__(self):
self.COMMENT = False
self.LASER = "OFF"
self.X_Y_MOTION = False
self.ONLY_Z = False
self.M = ""
self.S = ""
self.T = ""
self.Q = ""
self.R = ""
self.L = ""
self.H = ""
self.D = ""
self.G = ""
self.X = "0"
self.Y = "0"
self.Z = "0"
self.A = "0"
self.B = "0"
self.C = "0"
self.I = ""
self.J = ""
self.K = ""
self.F = ""
class PathParser:
def __init__(self):
self.variables = Variables()
self.current = ParserState()
self.last = ParserState()
self.comment = ""
self.mm_word = "" ; self.pm_word = "" # Words(parameters) prefixed with
self.ms_word = "" ; self.ps_word = "" # p reflect the value on the
self.mt_word = "" ; self.pt_word = "" # current line being parsed.
self.mq_word = "" ; self.pq_word = "" # The m prefix reflects the machine
self.mr_word = "" ; self.pr_word = "" # state.
self.ml_word = "" ; self.pl_word = "" # Example:
self.mh_word = "" ; self.ph_word = "" # If you want X and Y on every line
self.md_word = "" ; self.pd_word = "" # in your gcode file use mx_word and
self.mg_word = "" ; self.pg_word = "" # my_word. This will print X and Y
self.mx_word = "" ; self.px_word = "" # even if they are not in the command line
self.my_word = "" ; self.py_word = "" # currently being parsed.
self.mz_word = "" ; self.pz_word = ""
self.ma_word = "" ; self.pa_word = ""
self.mb_word = "" ; self.pb_word = ""
self.mc_word = "" ; self.pc_word = ""
self.mi_word = "" ; self.pi_word = ""
self.mj_word = "" ; self.pj_word = ""
self.mk_word = "" ; self.pk_word = ""
self.mf_word = "" ; self.pf_word = ""
def parse_command(self, command):
precision_string = "." + str(self.variables.PRECISION) + "f"
if "(" in command.Name and ")" in command.Name:
self.current.COMMENT = True
self.comment = (re.search(r"\(.*?(?<=\))", command.Name)).group()
else:
self.current.COMMENT = False
self.comment = ""
if "M" in command.Name:
self.current.M = (re.search(r"M.*?(?=\s|$)", command.Name)).group()
self.pm_word = self.current.M + " "
self.mm_word = self.pm_word
else:
self.pm_word = ""
if "S" in command.Parameters:
self.current.S = command.Parameters["S"]
self.current.S = "S" + str(int(command.Parameters["S"]))
self.ps_word = self.current.S + " "
self.ms_word = self.ps_word
else:
self.ps_word = ""
if "T" in command.Parameters:
self.current.T = command.Parameters["T"]
self.current.T = "T" + str(int(command.Parameters["T"]))
self.pt_word = self.current.T + " "
self.mt_word = self.pt_word
else:
self.pt_word = ""
if "Q" in command.Parameters:
self.current.Q = command.Parameters["Q"]
position = Units.Quantity(self.current.Q, FreeCAD.Units.Length)
self.current.Q = "Q" + format(float(position.getValueAs(self.variables.UNIT_FORMAT)), precision_string)
self.pq_word = self.current.Q + " "
self.mq_word = self.pq_word
else:
self.pq_word = ""
if "R" in command.Parameters:
self.current.R = command.Parameters["R"]
position = Units.Quantity(self.current.Y, FreeCAD.Units.Length)
self.current.R = "R" + format(float(position.getValueAs(self.variables.UNIT_FORMAT)), precision_string)
self.pr_word = self.current.R + " "
self.mr_word = self.pr_word
else:
self.pr_word = ""
if "L" in command.Parameters:
self.current.L = command.Parameters["L"]
position = Units.Quantity(self.current.L, FreeCAD.Units.Length)
self.current.L = "L" + format(float(position.getValueAs(self.variables.UNIT_FORMAT)), precision_string)
self.pl_word = self.current.L + " "
self.ml_word = self.pl_word
else:
self.pl_word = ""
if "H" in command.Parameters:
self.current.H = command.Parameters["H"]
self.current.H = "H" + str(int(command.Parameters["H"]))
self.ph_word = self.current.H + " "
self.mh_word = self.ph_word
else:
self.ph_word = ""
if "D" in command.Parameters:
self.current.D = command.Parameters["D"]
self.current.D = "D" + str(int(command.Parameters["D"]))
self.pd_word = self.current.D + " "
self.md_word = self.pd_word
else:
self.pd_word = ""
if "G" in command.Name:
self.current.G = (re.search(r"G.*?(?=\s|$)", command.Name)).group()
self.pg_word = self.current.G + " "
self.mg_word = self.pg_word
else:
self.pg_word = ""
if "X" in command.Parameters:
self.current.X = command.Parameters["X"]
position = Units.Quantity(self.current.X, FreeCAD.Units.Length)
self.current.X = "X" + format(float(position.getValueAs(self.variables.UNIT_FORMAT)), precision_string)
self.px_word = self.current.X + " "
self.mx_word = self.px_word
else:
self.px_word = ""
if "Y" in command.Parameters:
self.current.Y = command.Parameters["Y"]
position = Units.Quantity(self.current.Y, FreeCAD.Units.Length)
self.current.Y = "Y" + format(float(position.getValueAs(self.variables.UNIT_FORMAT)), precision_string)
self.py_word = self.current.Y + " "
self.my_word = self.py_word
else:
self.py_word = ""
if "Z" in command.Parameters:
self.current.Z = command.Parameters["Z"]
position = Units.Quantity(self.current.Z, FreeCAD.Units.Length)
self.current.Z = "Z" + format(float(position.getValueAs(self.variables.UNIT_FORMAT)), precision_string)
self.pz_word = self.current.Z + " "
self.mz_word = self.pz_word
else:
self.pz_word = ""
if "A" in command.Parameters:
self.current.A = command.Parameters["A"]
self.current.A = "A" + format(float(self.current.A), precision_string)
self.pa_word = self.current.A + " "
self.ma_word = self.pa_word
else:
self.pa_word = ""
if "B" in command.Parameters:
self.current.B = command.Parameters["B"]
self.current.B = "B" + format(float(self.current.B), precision_string)
self.pb_word = self.current.B + " "
self.mb_word = self.pb_word
else:
self.pb_word = ""
if "C" in command.Parameters:
self.current.C = command.Parameters["C"]
self.current.C = "C" + format(float(self.current.C), precision_string)
self.pc_word = self.current.C + " "
self.mc_word = self.pc_word
else:
self.pc_word = ""
if "I" in command.Parameters:
self.current.I = command.Parameters["I"]
position = Units.Quantity(self.current.I, FreeCAD.Units.Length)
self.current.I = "I" + format(float(position.getValueAs(self.variables.UNIT_FORMAT)), precision_string)
self.pi_word = self.current.I + " "
self.mi_word = self.pi_word
else:
self.pi_word = ""
if "J" in command.Parameters:
self.current.J = command.Parameters["J"]
position = Units.Quantity(self.current.J, FreeCAD.Units.Length)
self.current.J = "J" + format(float(position.getValueAs(self.variables.UNIT_FORMAT)), precision_string)
self.pj_word = self.current.J + " "
self.mj_word = self.pj_word
else:
self.pj_word = ""
if "K" in command.Parameters:
self.current.K = command.Parameters["K"]
position = Units.Quantity(self.current.K, FreeCAD.Units.Length)
self.current.K = "K" + format(float(position.getValueAs(self.variables.UNIT_FORMAT)), precision_string)
self.pk_word = self.current.K + " "
self.mk_word = self.pk_word
else:
self.pk_word = ""
if "F" in command.Parameters:
self.current.F = command.Parameters["F"]
speed = Units.Quantity(self.current.F, FreeCAD.Units.Velocity)
feed_float = float(speed.getValueAs(self.variables.UNIT_SPEED_FORMAT))
if feed_float > 0.0:
self.current.F = "F" + format(float(speed.getValueAs(self.variables.UNIT_SPEED_FORMAT)), precision_string)
self.pf_word = self.current.F + " "
self.mf_word = self.pf_word
else:
self.current.F = ""
self.pf_word = ""
if self.current.G == "G0":
self.pf_word = ""
if self.current.X != self.last.X or self.current.Y != self.last.Y:
self.current.X_Y_MOTION = True
else:
self.current.X_Y_MOTION = False
if self.pz_word != "" and self.px_word == "" and self.py_word == "":
self.current.ONLY_Z = True
else:
self.current.ONLY_Z = False
def update(self):
self.last = copy.deepcopy(self.current)
def export(objects_list, file_name, arg_string):
parser = PathParser()
if not processArguments(arg_string, parser):
return None
for obj in objects_list:
if not hasattr(obj, "Path"):
print("the object " + obj.Name + " is not a path. Please select only path and Compounds.")
return None
print("postprocessing...")
print("Laser gcode postprocessor loaded.")
gcode = ""
gcode += "(Exported by FreeCAD)\n"
gcode += "(Post Processor: Laser)\n"
gcode += "(Output Time: " + (now.strftime("%Y-%m-%d %H:%M:%S")) + ")\n"
gcode += "(begin preamble)\n"
gcode += parser.variables.PREAMBLE + "\n"
gcode += parser.variables.UNITS + "\n"
for obj in objects_list:
# Skip inactive operations
if hasattr(obj, "Active"):
if not obj.Active:
continue
if hasattr(obj, "Base") and hasattr(obj.Base, "Active"):
if not obj.Base.Active:
continue
gcode += "(begin operation: %s)\n" % obj.Label
gcode += "(machine units: %s)\n" % (parser.variables.UNIT_SPEED_FORMAT)
# Laser formatted gcode.
gcode += parser.variables.LASER_OFF + "\n"
if parser.variables.LASER_3D:
gcode += laser_3d(obj, parser)
else:
gcode += laser_2d(obj, parser)
gcode += parser.variables.LASER_OFF + "\n"
##########################
gcode += "(begin postamble)\n"
gcode += parser.variables.POSTAMBLE + "\n"
if FreeCAD.GuiUp and parser.variables.SHOW_EDITOR:
final = gcode
if len(gcode) > 100000:
print("Skipping editor since output is greater than 100kb")
else:
dia = PostUtils.GCodeEditorDialog()
dia.editor.setText(gcode)
result = dia.exec_()
if result:
final = dia.editor.toPlainText()
else:
final = gcode
print("done postprocessing.")
if not file_name == "-":
gfile = pyopen(file_name, "w")
gfile.write(final)
gfile.close()
return final
def write_2d_line(parser):
nl = "\n"
line = f"{parser.pm_word}{parser.ps_word}"\
f"{parser.pg_word}"\
f"{parser.mx_word}{parser.my_word}"\
f"{parser.pi_word}{parser.pj_word}"\
f"{parser.pf_word}{nl}"
if line == "\n":
line = line.replace("\n", "")
return line
def laser_2d(path_object, parser):
out = ""
nl = "\n"
temp_gcode = ""
temp_line = ""
if hasattr(path_object, "Group"): # We have a compound or project.
for p in path_object.Group:
out += laser_2d(p)
return out
else: # parsing simple path
# groups might contain non-path things like stock.
if not hasattr(path_object, "Path"):
return out
for command in path_object.Path.Commands:
temp_line = ""
parser.parse_command(command)
# Feedrate semi-modal. Freedrate is printed at the beginning of each motion controlled group.
if parser.current.F == parser.last.F and parser.last.G != "G0":
parser.pf_word = ""
if parser.current.COMMENT:
temp_line += f"{parser.comment}{nl}"
if parser.current.S != "":
parser.variables.LASER_POWER = parser.ms_word
# Remove redundant moves created when ignoring the Z axis.
if parser.current.G in ["G0", "G1"] and parser.last.G in ["G0", "G1", "G2", "G3"]\
and not parser.current.X_Y_MOTION:
continue
# Remove G0 moves that only include the Z axis.
elif parser.current.G == "G0" and parser.current.ONLY_Z:
continue
# Turn the laser on for feed controlled moves and off for rapid moves.
elif parser.current.G == "G0" and parser.current.LASER == "OFF":
temp_line += write_2d_line(parser)
elif parser.current.G == "G0" and parser.current.LASER == "ON":
parser.current.LASER = "OFF" # turn laser off
temp_line += f"{parser.variables.LASER_OFF}{nl}" # write laser off command
temp_line += write_2d_line(parser) # write gcode line
elif parser.current.G == "G1" and parser.current.LASER == "ON":
temp_line += write_2d_line(parser)
elif parser.current.G == "G1" and parser.current.LASER == "OFF":
parser.current.LASER = "ON"
temp_line += f"{parser.variables.LASER_ON} {parser.variables.LASER_POWER}{nl}"
temp_line += write_2d_line(parser)
elif parser.current.G in ["G2", "G3"] and parser.current.LASER == "ON":
temp_line += write_2d_line(parser)
elif parser.current.G in ["G2", "G3"] and parser.current.LASER == "OFF":
parser.current.LASER = "ON"
temp_line += f"{parser.variables.LASER_ON} {parser.variables.LASER_POWER}{nl}"
temp_line += write_2d_line(parser)
else:
#temp_line = line
pass
temp_gcode += temp_line
parser.update()
return temp_gcode
def write_3d_line(parser):
nl = "\n"
line = f"{parser.pm_word}{parser.ps_word}"\
f"{parser.pg_word}"\
f"{parser.px_word}{parser.py_word}{parser.pz_word}"\
f"{parser.pi_word}{parser.pj_word}{parser.pk_word}"\
f"{parser.pf_word}{nl}"
if line == "\n":
line = line.replace("\n", "")
return line
def laser_3d(path_object, parser):
out = ""
nl = "\n"
temp_gcode = ""
temp_line = ""
if hasattr(path_object, "Group"): # We have a compound or project.
for p in path_object.Group:
out += laser_3d(p)
return out
else: # parsing simple path
# groups might contain non-path things like stock.
if not hasattr(path_object, "Path"):
return out
for command in path_object.Path.Commands:
temp_line = ""
parser.parse_command(command)
if parser.current.COMMENT:
temp_line += f"{parser.comment}{nl}"
if parser.current.S != "":
parser.variables.LASER_POWER = parser.ms_word
# Feedrate semi-modal. Freedrate is printed at the beginning of each motion controlled group.
if parser.current.F == parser.last.F and parser.last.G != "G0":
parser.pf_word = ""
if parser.current.G == "G0" and parser.last.LASER == "OFF":
temp_line += write_3d_line(parser)
elif parser.current.LASER == "ON" and parser.last.LASER == "OFF":
temp_line += f"{nl}{parser.variables.LASER_OFF}{nl}"
elif parser.current.LASER == "OFF" and parser.last.LASER == "ON":
temp_line += f"{parser.variables.LASER_ON}{nl}"
elif parser.current.G in ["G0", "G1", "G2", "G3"] and not parser.current.X_Y_MOTION and parser.current.LASER == "ON":
temp_line += f'{parser.variables.LASER_OFF}{nl}'
temp_line += write_3d_line(parser)
parser.current.LASER = "OFF"
elif parser.current.G in ["G0", "G1", "G2", "G3"] and not parser.current.X_Y_MOTION and parser.current.LASER == "OFF":
temp_line += write_3d_line(parser)
elif parser.current.G in ["G1", "G2", "G3"] and parser.current.X_Y_MOTION and parser.current.LASER == "OFF":
temp_line += f"{parser.variables.LASER_ON} {parser.variables.LASER_POWER}{nl}"
temp_line += write_3d_line(parser)
parser.current.LASER = "ON"
elif parser.current.G in ["G1", "G2", "G3"] and parser.current.X_Y_MOTION and parser.current.LASER == "ON":
temp_line += write_3d_line(parser)
else:
#temp_line = line
pass
temp_gcode += temp_line
parser.update()
return temp_gcode