File size: 11,396 Bytes
985c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: LGPL-2.1-or-later

# ***************************************************************************
# *   Copyright (c) 2014 sliptonic <shopinthewoods@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 datetime
import Path.Post.Utils as PostUtils
import PathScripts.PathUtils as PathUtils
from builtins import open as pyopen


TOOLTIP = """
This is an postprocessor file for the Path workbench. It will output path data
in a format suitable for OpenSBP controllers like shopbot.  This postprocessor,
once placed in the appropriate PathScripts folder, can be used directly from
inside FreeCAD, via the GUI importer or via python scripts with:

import Path
Path.write(object,"/path/to/file.ncc","post_opensbp")
"""

"""
DONE:
    uses native commands
    handles feed and jog moves
    handles XY, Z, and XYZ feed speeds
    handles arcs
    support for inch output
ToDo
    comments may not format correctly
    drilling.  Haven't looked at it.
    many other things

"""

TOOLTIP_ARGS = """
Arguments for opensbp:
    --comments          ... insert comments - mostly for debugging
    --inches            ... convert output to inches
    --no-header         ... suppress header output
    --no-show-editor    ... don't show editor, just save result
"""

now = datetime.datetime.now()

OUTPUT_COMMENTS = False
OUTPUT_HEADER = True
SHOW_EDITOR = True
COMMAND_SPACE = ","

# Preamble text will appear at the beginning of the GCODE output file.
PREAMBLE = """"""
# Postamble text will appear following the last operation.
POSTAMBLE = """"""

# Pre operation text will be inserted before every operation
PRE_OPERATION = """"""

# Post operation text will be inserted after every operation
POST_OPERATION = """"""

# Tool Change commands will be inserted before a tool change
TOOL_CHANGE = """"""


CurrentState = {}


def getMetricValue(val):
    return val


def getImperialValue(val):
    return val / 25.4


GetValue = getMetricValue


def export(objectslist, filename, argstring):
    global OUTPUT_COMMENTS
    global OUTPUT_HEADER
    global SHOW_EDITOR
    global CurrentState
    global GetValue

    for arg in argstring.split():
        if arg == "--comments":
            OUTPUT_COMMENTS = True
        if arg == "--inches":
            GetValue = getImperialValue
        if arg == "--no-header":
            OUTPUT_HEADER = False
        if arg == "--no-show-editor":
            SHOW_EDITOR = False

    for obj in objectslist:
        if not hasattr(obj, "Path"):
            s = "the object " + obj.Name
            s += " is not a path. Please select only path and Compounds."
            print(s)
            return

    CurrentState = {
        "X": 0,
        "Y": 0,
        "Z": 0,
        "F": 0,
        "S": 0,
        "JSXY": 0,
        "JSZ": 0,
        "MSXY": 0,
        "MSZ": 0,
    }
    print("postprocessing...")
    gcode = ""

    # write header
    if OUTPUT_HEADER:
        gcode += linenumber() + "'Exported by FreeCAD\n"
        gcode += linenumber() + "'Post Processor: " + __name__ + "\n"
        gcode += linenumber() + "'Output Time:" + str(now) + "\n"

    # Write the preamble
    if OUTPUT_COMMENTS:
        gcode += linenumber() + "'(begin preamble)\n"
    for line in PREAMBLE.splitlines(True):
        gcode += linenumber() + line

    for obj in objectslist:

        # do the pre_op
        if OUTPUT_COMMENTS:
            gcode += linenumber() + "'(begin operation: " + obj.Label + ")\n"
        for line in PRE_OPERATION.splitlines(True):
            gcode += linenumber() + line

        gcode += parse(obj)

        # do the post_op
        if OUTPUT_COMMENTS:
            gcode += linenumber() + "'(finish operation: " + obj.Label + ")\n"
        for line in POST_OPERATION.splitlines(True):
            gcode += linenumber() + line

    # do the post_amble
    if OUTPUT_COMMENTS:
        gcode += "'(begin postamble)\n"
    for line in POSTAMBLE.splitlines(True):
        gcode += linenumber() + line

    if SHOW_EDITOR:
        dia = PostUtils.GCodeEditorDialog()
        dia.editor.setPlainText(gcode)
        result = dia.exec_()
        if result:
            final = dia.editor.toPlainText()
        else:
            final = gcode
    else:
        final = gcode

    print("done postprocessing.")

    # Write the output
    if not filename == "-":
        gfile = pyopen(filename, "w")
        gfile.write(final)
        gfile.close()

    return final


def move(command):
    txt = ""

    # if 'F' in command.Parameters:
    #     txt += feedrate(command)

    axis = ""
    for p in ["X", "Y", "Z"]:
        if p in command.Parameters:
            if command.Parameters[p] != CurrentState[p]:
                axis += p

    if "F" in command.Parameters:
        speed = command.Parameters["F"]
        if command.Name in ["G1", "G01"]:  # move
            movetype = "MS"
        else:  # jog
            movetype = "JS"
        zspeed = ""
        xyspeed = ""
        if "Z" in axis:
            speedKey = "{}Z".format(movetype)
            speedVal = GetValue(speed)
            if CurrentState[speedKey] != speedVal:
                CurrentState[speedKey] = speedVal
                zspeed = "{:f}".format(speedVal)
        if ("X" in axis) or ("Y" in axis):
            speedKey = "{}XY".format(movetype)
            speedVal = GetValue(speed)
            if CurrentState[speedKey] != speedVal:
                CurrentState[speedKey] = speedVal
                xyspeed = "{:f}".format(speedVal)
        if zspeed or xyspeed:
            txt += "{},{},{}\n".format(movetype, xyspeed, zspeed)

    if command.Name in ["G0", "G00"]:
        pref = "J"
    else:
        pref = "M"

    if axis == "X":
        txt += pref + "X"
        txt += "," + format(GetValue(command.Parameters["X"]), ".4f")
        txt += "\n"
    elif axis == "Y":
        txt += pref + "Y"
        txt += "," + format(GetValue(command.Parameters["Y"]), ".4f")
        txt += "\n"
    elif axis == "Z":
        txt += pref + "Z"
        txt += "," + format(GetValue(command.Parameters["Z"]), ".4f")
        txt += "\n"
    elif axis == "XY":
        txt += pref + "2"
        txt += "," + format(GetValue(command.Parameters["X"]), ".4f")
        txt += "," + format(GetValue(command.Parameters["Y"]), ".4f")
        txt += "\n"
    elif axis == "XZ":
        txt += pref + "3"
        txt += "," + format(GetValue(command.Parameters["X"]), ".4f")
        txt += ","
        txt += "," + format(GetValue(command.Parameters["Z"]), ".4f")
        txt += "\n"
    elif axis == "XYZ":
        txt += pref + "3"
        txt += "," + format(GetValue(command.Parameters["X"]), ".4f")
        txt += "," + format(GetValue(command.Parameters["Y"]), ".4f")
        txt += "," + format(GetValue(command.Parameters["Z"]), ".4f")
        txt += "\n"
    elif axis == "YZ":
        txt += pref + "3"
        txt += ","
        txt += "," + format(GetValue(command.Parameters["Y"]), ".4f")
        txt += "," + format(GetValue(command.Parameters["Z"]), ".4f")
        txt += "\n"
    elif axis == "":
        print("warning: skipping duplicate move.")
    else:
        print(CurrentState)
        print(command)
        print("I don't know how to handle '{}' for a move.".format(axis))

    return txt


def arc(command):
    if command.Name == "G2":  # CW
        dirstring = "1"
    else:  # G3 means CCW
        dirstring = "-1"
    txt = "CG,,"
    txt += format(GetValue(command.Parameters["X"]), ".4f") + ","
    txt += format(GetValue(command.Parameters["Y"]), ".4f") + ","
    txt += format(GetValue(command.Parameters["I"]), ".4f") + ","
    txt += format(GetValue(command.Parameters["J"]), ".4f") + ","
    txt += "T" + ","
    txt += dirstring
    txt += "\n"
    return txt


def tool_change(command):
    txt = ""
    if OUTPUT_COMMENTS:
        txt += "'a tool change happens now\n"
    for line in TOOL_CHANGE.splitlines(True):
        txt += line
    txt += "&ToolName=" + str(int(command.Parameters["T"]))
    txt += "\n"
    txt += "&Tool=" + str(int(command.Parameters["T"]))
    txt += "\n"
    return txt


def comment(command):
    print("a comment", command)
    return


def spindle(command):
    txt = ""
    if command.Name == "M3":  # CW
        pass
    else:
        pass
    txt += "TR," + str(command.Parameters["S"]) + "\n"
    txt += "C6\n"
    txt += "PAUSE 2\n"
    return txt


# Supported Commands
scommands = {
    "G0": move,
    "G1": move,
    "G2": arc,
    "G3": arc,
    "M6": tool_change,
    "M3": spindle,
    "G00": move,
    "G01": move,
    "G02": arc,
    "G03": arc,
    "M06": tool_change,
    "M03": spindle,
    "message": comment,
}


def parse(pathobj):
    output = ""
    # Above list controls the order of parameters

    if hasattr(pathobj, "Group"):  # We have a compound or project.
        if OUTPUT_COMMENTS:
            output += linenumber() + "'(compound: " + pathobj.Label + ")\n"
        for p in pathobj.Group:
            output += parse(p)
    else:  # parsing simple path
        # groups might contain non-path things like stock.
        if not hasattr(pathobj, "Path"):
            return output
        if OUTPUT_COMMENTS:
            output += linenumber() + "'(Path: " + pathobj.Label + ")\n"
        for c in PathUtils.getPathWithPlacement(pathobj).Commands:
            command = c.Name
            if command in scommands:
                output += scommands[command](c)
                if c.Parameters:
                    CurrentState.update(c.Parameters)
            elif command.startswith("("):
                output += "' " + command + "\n"
            else:
                print("I don't know what the hell the command: ", end="")
                print(command + " means.  Maybe I should support it.")
    return output


def linenumber():
    return ""


# print(__name__ + " gcode postprocessor loaded.")