forked from FreeCAD/FreeCAD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcode_pre.py
183 lines (141 loc) · 6.3 KB
/
gcode_pre.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
# ***************************************************************************
# * Copyright (c) 2014 Yorik van Havre <yorik@uncreated.net> *
# * *
# * 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 *
# * *
# ***************************************************************************/
'''
This is an example preprocessor file for the Path workbench. Its aim is to
open a gcode file, parse its contents, and create the appropriate objects
in FreeCAD.
This preprocessor will split gcode on tool changes and create one or more
PathCustom objects in the job. Tool Change commands themselves are not
preserved. It is up to the user to create and assign appropriate tool
controllers.
Only gcodes that are supported by Path are imported. Thus things like G43
are suppressed.
Importing gcode is inherently dangerous because context cannot be safely
assumed. The user should carefully examine the resulting gcode!
Read the Path Workbench documentation to know how to create Path objects
from GCode.
'''
import os
import FreeCAD
import PathScripts.PathUtils as PathUtils
import PathScripts.PathLog as PathLog
import re
import PathScripts.PathCustom as PathCustom
import PathScripts.PathCustomGui as PathCustomGui
import PathScripts.PathOpGui as PathOpGui
# LEVEL = PathLog.Level.DEBUG
LEVEL = PathLog.Level.INFO
PathLog.setLevel(LEVEL, PathLog.thisModule())
if LEVEL == PathLog.Level.DEBUG:
PathLog.trackModule(PathLog.thisModule())
# to distinguish python built-in open function from the one declared below
if open.__module__ in ['__builtin__', 'io']:
pythonopen = open
def open(filename):
"called when freecad opens a file."
PathLog.track(filename)
docname = os.path.splitext(os.path.basename(filename))[0]
doc = FreeCAD.newDocument(docname)
insert(filename, doc.Name)
def matchToolController(op, toolnumber):
"""Try to match a tool controller in the job by number"""
toolcontrollers = PathUtils.getToolControllers(op)
for tc in toolcontrollers:
if tc.ToolNumber == toolnumber:
return tc
return toolcontrollers[0]
def insert(filename, docname):
"called when freecad imports a file"
PathLog.track(filename)
gfile = pythonopen(filename)
gcode = gfile.read()
gfile.close()
# Regular expression to match tool changes in the format 'M6 Tn'
p = re.compile('[mM]+?\s?0?6\s?T\d*\s')
# split the gcode on tool changes
paths = re.split('([mM]+?\s?0?6\s?T\d*\s)', gcode)
# iterate the gcode sections and add customs for each
toolnumber = 0
for path in paths:
# if the section is a tool change, extract the tool number
m = p.match(path)
if m:
toolnumber = int(m.group().split('T')[-1])
continue
# Parse the gcode and throw away any empty lists
gcode = parse(path)
if len(gcode) == 0:
continue
# Create a custom and viewobject
obj = PathCustom.Create("Custom")
res = PathOpGui.CommandResources('Custom', PathCustom.Create,
PathCustomGui.TaskPanelOpPage,
'Path_Custom', 'Custom', '', '')
obj.ViewObject.Proxy = PathOpGui.ViewProvider(obj.ViewObject, res)
obj.ViewObject.Proxy.setDeleteObjectsOnReject(False)
# Set the gcode and try to match a tool controller
obj.Gcode = gcode
obj.ToolController = matchToolController(obj, toolnumber)
FreeCAD.ActiveDocument.recompute()
def parse(inputstring):
"parse(inputstring): returns a parsed output string"
supported = ['G0', 'G00',
'G1', 'G01',
'G2', 'G02',
'G3', 'G03',
'G81', 'G82', 'G83',
'G90', 'G91']
axis = ["X", "Y", "Z", "A", "B", "C", "U", "V", "W"]
print("preprocessing...")
PathLog.track(inputstring)
# split the input by line
lines = inputstring.splitlines()
output = []
lastcommand = None
for lin in lines:
# remove any leftover trailing and preceding spaces
lin = lin.strip()
# discard empty lines
if not lin:
continue
# remove line numbers
if lin[0].upper() in ["N"]:
lin = lin.split(" ", 1)
if len(lin) >= 1:
lin = lin[1].strip()
else:
continue
# Anything else not a G/M code or an axis move is ignored.
if lin[0] not in ["G", "M", "X", "Y", "Z", "A", "B", "C", "U", "V", "W"]:
continue
# if the remaining line is supported, store it
currcommand = lin.split()[0]
if currcommand in supported:
output.append(lin)
lastcommand = currcommand
# modal commands have no G or M but have axis moves. append those too.
elif currcommand[0] in axis and lastcommand:
output.append(lastcommand + " " + lin)
print("done preprocessing.")
return output
print(__name__ + " gcode preprocessor loaded.")