Moved all post/pre processor into their own directory.

This commit is contained in:
Markus Lampert
2017-06-18 17:45:59 -07:00
parent 03c5168d89
commit 789e79c480
18 changed files with 33 additions and 19 deletions

View File

@@ -0,0 +1,142 @@
# -*- coding: utf-8 -*-
#***************************************************************************
#* *
#* Copyright (c) 2015 Dan Falck <ddfalck@gmail.com> *
#* *
#* 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. *
#* *
#* This program 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 Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#***************************************************************************
from __future__ import print_function
TOOLTIP=''' example post for Centroid CNC mill'''
import FreeCAD
import datetime
now = datetime.datetime.now()
from PathScripts import PostUtils
#***************************************************************************
# user editable stuff here
UNITS = "G20" #old style inch units for this shop
MACHINE_NAME = "BigMill"
CORNER_MIN = {'x':-609.6, 'y':-152.4, 'z':0 } #use metric for internal units
CORNER_MAX = {'x':609.6, 'y':152.4, 'z':304.8 } #use metric for internal units
SHOW_EDITOR = True
MODAL = True
COMMENT= ';' #centroid control comment symbol
HEADER = ""
HEADER += ";Exported by FreeCAD\n"
HEADER += ";Post Processor: " + __name__ +"\n"
HEADER += ";CAM file: %s\n"
HEADER += ";Output Time:"+str(now)+"\n"
TOOLRETURN = '''M5 M25
G49 H0\n''' #spindle off,height offset canceled,spindle retracted (M25 is a centroid command to retract spindle)
ZAXISRETURN = '''G91 G28 X0 Z0
G90\n'''
SAFETYBLOCK = 'G90 G80 G40 G49\n'
AXIS_DECIMALS = 4
FEED_DECIMALS = 1
SPINDLE_DECIMALS = 0
FOOTER = 'M99'+'\n'
# don't edit with the stuff below the next line unless you know what you're doing :)
#***************************************************************************
if open.__module__ == '__builtin__':
pythonopen = open
def export(selection,filename,argstring):
params = ['X','Y','Z','A','B','I','J','F','H','S','T','Q','R','L'] #Using XY plane most of the time so skipping K
for obj in selection:
if not hasattr(obj,"Path"):
print("the object " + obj.Name + " is not a path. Please select only path and Compounds.")
return
myMachine = None
for pathobj in selection:
if hasattr(pathobj,"MachineName"):
myMachine = pathobj.MachineName
if hasattr(pathobj, "MachineUnits"):
if pathobj.MachineUnits == "Metric":
UNITS = "G21"
else:
UNITS = "G20"
if myMachine is None:
print("No machine found in this selection")
gcode =''
gcode+= HEADER % (FreeCAD.ActiveDocument.FileName)
gcode+= SAFETYBLOCK
gcode+= UNITS+'\n'
lastcommand = None
gcode+= COMMENT+ selection[0].Description +'\n'
gobjects = []
for g in selection[0].Group:
gobjects.append(g)
for obj in gobjects:
for c in obj.Path.Commands:
outstring = []
command = c.Name
if command[0]=='(':
command = PostUtils.fcoms(command, COMMENT)
outstring.append(command)
if MODAL == True:
if command == lastcommand:
outstring.pop(0)
if c.Parameters >= 1:
for param in params:
if param in c.Parameters:
if param == 'F':
outstring.append(param + PostUtils.fmt(c.Parameters['F'], FEED_DECIMALS,UNITS))
elif param == 'H':
outstring.append(param + str(int(c.Parameters['H'])))
elif param == 'S':
outstring.append(param + PostUtils.fmt(c.Parameters['S'], SPINDLE_DECIMALS,'G21')) #rpm is unitless-therefore I had to 'fake it out' by using metric units which don't get converted from entered value
elif param == 'T':
outstring.append(param + str(int(c.Parameters['T'])))
else:
outstring.append(param + PostUtils.fmt(c.Parameters[param],AXIS_DECIMALS,UNITS))
outstr = str(outstring)
outstr =outstr.replace('[','')
outstr =outstr.replace(']','')
outstr =outstr.replace("'",'')
outstr =outstr.replace(",",'')
gcode+= outstr + '\n'
lastcommand = c.Name
gcode+= TOOLRETURN
gcode+= SAFETYBLOCK
gcode+= FOOTER
if SHOW_EDITOR:
PostUtils.editor(gcode)
gfile = pythonopen(filename,"wb")
gfile.write(gcode)
gfile.close()

View File

@@ -0,0 +1,110 @@
# -*- coding: utf-8 -*-
#***************************************************************************
#* *
#* Copyright (c) 2015 Dan Falck <ddfalck@gmail.com> *
#* *
#* 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. *
#* *
#* This program 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 Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#***************************************************************************
TOOLTIP=''' Example Post, using Path.Commands instead of Path.toGCode strings for Path gcode output. '''
import FreeCAD
import Path, PathScripts
from PathScripts import PostUtils
SHOW_EDITOR=True
def fmt(num):
fnum = ""
fnum += '%.3f' % (num)
return fnum
def ffmt(num):
fnum = ""
fnum += '%.1f' % (num)
return fnum
class saveVals(object):
''' save command info for modal output'''
def __init__(self, command):
self.com = command.Name
self.params = command.Parameters
def retVals(self):
return self.com, self.params
def lineout(command, oldvals, modal):
line = ""
if modal and (oldvals.com == command.Name):
line +=""
else:
line += str(command.Name)
if command.Name == 'M6':
line+= 'T'+str(int(command.Parameters['T']))
if command.Name == 'M3':
line+= 'S'+str(ffmt(command.Parameters['S']))
if command.Name == 'M4':
line+= 'S'+str(ffmt(command.Parameters['S']))
if 'X' in command.Parameters:
line += "X"+str(fmt(command.Parameters['X']))
if 'Y' in command.Parameters:
line += "Y"+str(fmt(command.Parameters['Y']))
if 'Z' in command.Parameters:
line += "Z"+str(fmt(command.Parameters['Z']))
if 'I' in command.Parameters:
line += "I"+str(fmt(command.Parameters['I']))
if 'J' in command.Parameters:
line += "J"+str(fmt(command.Parameters['J']))
if 'F' in command.Parameters:
line += "F"+str(ffmt(command.Parameters['F']))
return line
def export(obj,filename,argstring):
modal=True
commands = obj[0]
gcode = ''
safetyblock1 = 'G90G40G49\n'
gcode+=safetyblock1
units = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Units")
if units.GetInt('UserSchema') == 0:
firstcommand = Path.Command('G21') #metric mode
else:
firstcommand = Path.Command('G20') #inch mode
oldvals = saveVals(firstcommand) #save first command for modal use
fp = obj[0]
gcode+= firstcommand.Name
if hasattr(fp,"Path"):
for c in fp.Path.Commands:
gcode+= lineout(c, oldvals, modal)+'\n'
oldvals = saveVals(c)
gcode+='M2\n'
gfile = open(filename,"wb")
gfile.write(gcode)
gfile.close()
else:
FreeCAD.Console.PrintError('Select a path object and try again\n')
if SHOW_EDITOR:
FreeCAD.Console.PrintMessage('Editor Activated\n')
dia = PostUtils.GCodeEditorDialog()
dia.editor.setText(gcode)
dia.exec_()

View File

@@ -0,0 +1,94 @@
# ***************************************************************************
# * (c) sliptonic (shopinthewoods@gmail.com) 2014 *
# * *
# * 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 *
# * *
# ***************************************************************************/
from __future__ import print_function
TOOLTIP='''
Dumper is an extremely simple postprocessor file for the Path workbench. It is used
to dump the command list from one or more Path objects for simple inspection. This post
doesn't do any manipulation of the path and doesn't write anything to disk. It just
shows the dialog so you can see it. Useful for debugging, but not much else.
'''
import datetime
from PathScripts import PostUtils
now = datetime.datetime.now()
SHOW_EDITOR = True
# to distinguish python built-in open function from the one declared below
if open.__module__ == '__builtin__':
pythonopen = open
def export(objectslist, filename,argstring):
output = '''(This ouput produced with the dump post processor)
(Dump is useful for inspecting the raw commands in your paths)
(but is not useful for driving machines.)
(Consider setting a default postprocessor in your project or )
(exporting your paths using a specific post that matches your machine)
'''
"called when freecad exports a list of objects"
for obj in objectslist:
if not hasattr(obj, "Path"):
print("the object " + obj.Name + " is not a path. Please select only path and Compounds.")
return
print("postprocessing...")
output += parse(obj)
if SHOW_EDITOR:
dia = PostUtils.GCodeEditorDialog()
dia.editor.setText(output)
result = dia.exec_()
if result:
final = dia.editor.toPlainText()
else:
final = output
else:
final = output
print("done postprocessing.")
return final
def parse(pathobj):
out = ""
if hasattr(pathobj, "Group"): # We have a compound or project.
out += "(Group: " + pathobj.Label + ")\n"
for p in pathobj.Group:
out += parse(p)
return out
else: # parsing simple path
if not hasattr(pathobj, "Path"): # groups might contain non-path things like stock.
return out
out += "(Path: " + pathobj.Label + ")\n"
for c in pathobj.Path.Commands:
out += str(c) + "\n"
return out
print(__name__ + " gcode postprocessor loaded.")

View File

@@ -0,0 +1,263 @@
#***************************************************************************
#* (c) sliptonic (shopinthewoods@gmail.com) 2014 *
#* *
#* 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 file has been modified from Sliptonis original Linux CNC post *
#* for use with a Dynapath 20 controller all changes and Modifications *
#* (c) Linden (Linden@aktfast.net) 2016 *
#* *
#***************************************************************************/
from __future__ import print_function
TOOLTIP='''
This is a postprocessor file for the Path workbench. It is used to
take a pseudo-gcode fragment outputted by a Path object, and output
real GCode suitable for a Tree Journyman 325 3 axis mill with Dynapath 20 controller in MM.
This is a work in progress and very few of the functions available on the Dynapath have been
implemented at this time.
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:
Done
Coordinate Decimal limited to 3 places
Feed limited to hole number no decimal
Speed Limited to hole number no decimal
Machine Travel Limits Set to approximate values
Line numbers start at one and incremental by 1
Set preamble
Set postamble
To Do
Change G20 and G21 to G70 and G71 for metric or imperial units
Convert arcs to absolute
Strip comments and white spaces
Add file name in brackets limited to 8 alpha numeric no spaces all caps as first line in file
Change Q to K For depth of peck on G83
Fix tool change
Limit comments length and characters to Uppercase, alpha numeric and spaces add / prior to coments
import linuxcnc_post
linuxcnc_post.export(object,"/path/to/file.ncc","")
'''
import datetime
now = datetime.datetime.now()
from PathScripts import PostUtils
#These globals set common customization preferences
OUTPUT_COMMENTS = True
OUTPUT_HEADER = False
OUTPUT_LINE_NUMBERS = False
SHOW_EDITOR = True
MODAL = False #if true commands are suppressed if the same as previous line.
COMMAND_SPACE = " "
LINENR = 1 #line number starting value
#These globals will be reflected in the Machine configuration of the project
UNITS = "G21" #G21 for metric, G20 for us standard
MACHINE_NAME = "Tree MM"
CORNER_MIN = {'x':-340, 'y':0, 'z':0 }
CORNER_MAX = {'x':340, 'y':-355, 'z':-150 }
#Preamble text will appear at the beginning of the GCODE output file.
PREAMBLE = '''G17
G90
;G90.1 ;needed for simulation only
G80
G40
'''
#Postamble text will appear following the last operation.
POSTAMBLE = '''M09
M05
G80
G40
G17
G90
M30
'''
#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 = ''''''
# to distinguish python built-in open function from the one declared below
if open.__module__ == '__builtin__':
pythonopen = open
def export(objectslist,filename,argstring):
global UNITS
for obj in objectslist:
if not hasattr(obj,"Path"):
print("the object " + obj.Name + " is not a path. Please select only path and Compounds.")
return
print("postprocessing...")
gcode = ""
#Find the machine.
#The user my have overridden post processor defaults in the GUI. Make sure we're using the current values in the Machine Def.
myMachine = None
for pathobj in objectslist:
if hasattr(pathobj,"MachineName"):
myMachine = pathobj.MachineName
if hasattr(pathobj, "MachineUnits"):
if pathobj.MachineUnits == "Metric":
UNITS = "G21"
else:
UNITS = "G20"
if myMachine is None:
print("No machine found in this selection")
# 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
gcode += linenumber() + UNITS + "\n"
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.setText(gcode)
result = dia.exec_()
if result:
final = dia.editor.toPlainText()
else:
final = gcode
else:
final = gcode
print("done postprocessing.")
gfile = pythonopen(filename,"wb")
gfile.write(final)
gfile.close()
def linenumber():
global LINENR
if OUTPUT_LINE_NUMBERS == True:
LINENR += 1
return "N" + str(LINENR) + " "
return ""
def parse(pathobj):
out = ""
lastcommand = None
#params = ['X','Y','Z','A','B','I','J','K','F','S'] #This list control the order of parameters
params = ['X','Y','Z','A','B','I','J','F','S','T','Q','R','L'] #linuxcnc doesn't want K properties on XY plane Arcs need work.
if hasattr(pathobj,"Group"): #We have a compound or project.
if OUTPUT_COMMENTS: out += linenumber() + "(compound: " + pathobj.Label + ")\n"
for p in pathobj.Group:
out += parse(p)
return out
else: #parsing simple path
if not hasattr(pathobj,"Path"): #groups might contain non-path things like stock.
return out
if OUTPUT_COMMENTS: out += linenumber() + "(Path: " + pathobj.Label + ")\n"
for c in pathobj.Path.Commands:
outstring = []
command = c.Name
outstring.append(command)
# if modal: only print the command if it is not the same as the last one
if MODAL == True:
if command == lastcommand:
outstring.pop(0)
# Now add the remaining parameters in order
for param in params:
if param in c.Parameters:
if param == 'F':
outstring.append(param + format(c.Parameters['F'], '.0f'))
elif param == 'S':
outstring.append(param + format(c.Parameters[param], '.0f'))
elif param == 'T':
outstring.append(param + format(c.Parameters['T'], '.0f'))
else:
outstring.append(param + format(c.Parameters[param], '.3f'))
# store the latest command
lastcommand = command
# Check for Tool Change:
if command == 'M6':
if OUTPUT_COMMENTS: out += linenumber() + "(begin toolchange)\n"
for line in TOOL_CHANGE.splitlines(True):
out += linenumber() + line
if command == "message":
if OUTPUT_COMMENTS == False:
out = []
else:
outstring.pop(0) #remove the command
#prepend a line number and append a newline
if len(outstring) >= 1:
if OUTPUT_LINE_NUMBERS:
outstring.insert(0,(linenumber()))
#append the line to the final output
for w in outstring:
out += w + COMMAND_SPACE
out = out.strip() + "\n"
return out
print(__name__ + " gcode postprocessor loaded.")

View File

@@ -0,0 +1,101 @@
# ***************************************************************************
# * (c) Yorik van Havre (yorik@uncreated.net) 2014 *
# * *
# * 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 *
# * *
# ***************************************************************************/
from __future__ import print_function
TOOLTIP='''
This is an example postprocessor file for the Path workbench. It is used
to save a list of FreeCAD Path objects to a file.
Read the Path Workbench documentation to know how to convert Path objects
to GCode.
'''
import datetime
now = datetime.datetime.now()
# to distinguish python built-in open function from the one declared below
if open.__module__ == '__builtin__':
pythonopen = open
def export(objectslist, filename,argstring):
"called when freecad exports a list of objects"
if len(objectslist) > 1:
print("This script is unable to write more than one Path object")
return
obj = objectslist[0]
if not hasattr(obj, "Path"):
print("the given object is not a path")
gcode = obj.Path.toGCode()
gcode = parse(gcode)
gfile = pythonopen(filename, "wb")
gfile.write(gcode)
gfile.close()
def parse(inputstring):
"parse(inputstring): returns a parsed output string"
print("postprocessing...")
output = ""
# write some stuff first
output += "N10 ;time:"+str(now)+"\n"
output += "N20 G17 G20 G80 G40 G90\n"
output += "N30 (Exported by FreeCAD)\n"
linenr = 100
lastcommand = None
# treat the input line by line
lines = inputstring.split("\n")
for line in lines:
# split the G/M command from the arguments
if " " in line:
command, args = line.split(" ", 1)
else:
# no space found, which means there are no arguments
command = line
args = ""
# add a line number
output += "N" + str(linenr) + " "
# only print the command if it is not the same as the last one
if command != lastcommand:
output += command + " "
output += args + "\n"
# increment the line number
linenr += 10
# store the latest command
lastcommand = command
# write some more stuff at the end
output += "N" + str(linenr) + " M05\n"
output += "N" + str(linenr + 10) + " M25\n"
output += "N" + str(linenr + 20) + " G00 X-1.0 Y1.0\n"
output += "N" + str(linenr + 30) + " G17 G80 G40 G90\n"
output += "N" + str(linenr + 40) + " M99\n"
print("done postprocessing.")
return output
print(__name__ + " gcode postprocessor loaded.")

View File

@@ -0,0 +1,100 @@
# ***************************************************************************
# * (c) Yorik van Havre (yorik@uncreated.net) 2014 *
# * *
# * 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.
Read the Path Workbench documentation to know how to create Path objects
from GCode.
'''
import os
import Path
import FreeCAD
# to distinguish python built-in open function from the one declared below
if open.__module__ == '__builtin__':
pythonopen = open
def open(filename):
"called when freecad opens a file."
docname = os.path.splitext(os.path.basename(filename))[0]
doc = FreeCAD.newDocument(docname)
insert(filename, doc.Name)
def insert(filename, docname):
"called when freecad imports a file"
gfile = pythonopen(filename)
gcode = gfile.read()
gfile.close()
gcode = parse(gcode)
doc = FreeCAD.getDocument(docname)
obj = doc.addObject("Path::Feature", "Path")
path = Path.Path(gcode)
obj.Path = path
def parse(inputstring):
"parse(inputstring): returns a parsed output string"
print("preprocessing...")
# split the input by line
lines = inputstring.split("\n")
output = ""
lastcommand = None
for l in lines:
# remove any leftover trailing and preceding spaces
l = l.strip()
if not l:
# discard empty lines
continue
if l[0].upper() in ["N"]:
# remove line numbers
l = l.split(" ",1)[1]
if l[0] in ["(","%","#"]:
# discard comment and other non strictly gcode lines
continue
if l[0].upper() in ["G","M"]:
# found a G or M command: we store it
output += l + "\n"
last = l[0].upper()
for c in l[1:]:
if not c.isdigit():
break
else:
last += c
lastcommand = last
elif lastcommand:
# no G or M command: we repeat the last one
output += lastcommand + " " + l + "\n"
print("done preprocessing.")
return output
print(__name__ + " gcode preprocessor loaded.")

View File

@@ -0,0 +1,298 @@
# ***************************************************************************
# * (c) sliptonic (shopinthewoods@gmail.com) 2014 *
# * *
# * 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 *
# * *
# ***************************************************************************/
from __future__ import print_function
TOOLTIP='''
This is a postprocessor file for the Path workbench. It is used to
take a pseudo-gcode fragment outputted by a Path object, and output
real GCode suitable for a linuxcnc 3 axis mill. 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 linuxcnc_post
linuxcnc_post.export(object,"/path/to/file.ncc","")
'''
TOOLTIP_ARGS='''
Arguments for linuxcnc:
--header,--no-header ... output headers (--header)
--comments,--no-comments ... output comments (--comments)
--line-numbers,--no-line-numbers ... prefix with line numbers (--no-lin-numbers)
--show-editor, --no-show-editor ... pop up editor before writing output(--show-editor)
--output-precision=4 ... number of digits of precision. Default=4
'''
import FreeCAD
from FreeCAD import Units
import datetime
from PathScripts import PostUtils
from PathScripts import PathUtils
now = datetime.datetime.now()
# These globals set common customization preferences
OUTPUT_COMMENTS = True
OUTPUT_HEADER = True
OUTPUT_LINE_NUMBERS = False
if FreeCAD.GuiUp:
SHOW_EDITOR = True
else:
SHOW_EDITOR = False
MODAL = False # if true commands are suppressed if the same as previous line.
COMMAND_SPACE = " "
LINENR = 100 # line number starting value
# These globals will be reflected in the Machine configuration of the project
UNITS = "G21" # G21 for metric, G20 for us standard
UNIT_FORMAT = 'mm/min'
MACHINE_NAME = "LinuxCNC"
CORNER_MIN = {'x': 0, 'y': 0, 'z': 0}
CORNER_MAX = {'x': 500, 'y': 300, 'z': 300}
PRECISION=4
# Preamble text will appear at the beginning of the GCODE output file.
PREAMBLE = '''G17 G90
'''
# Postamble text will appear following the last operation.
POSTAMBLE = '''M05
G00 X-1.0 Y1.0
G17 G90
M2
'''
# 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 = ''''''
# to distinguish python built-in open function from the one declared below
if open.__module__ == '__builtin__':
pythonopen = open
def processArguments(argstring):
global OUTPUT_HEADER
global OUTPUT_COMMENTS
global OUTPUT_LINE_NUMBERS
global SHOW_EDITOR
global PRECISION
for arg in argstring.split():
if arg == '--header':
OUTPUT_HEADER = True
elif arg == '--no-header':
OUTPUT_HEADER = False
elif arg == '--comments':
OUTPUT_COMMENTS = True
elif arg == '--no-comments':
OUTPUT_COMMENTS = False
elif arg == '--line-numbers':
OUTPUT_LINE_NUMBERS = True
elif arg == '--no-line-numbers':
OUTPUT_LINE_NUMBERS = False
elif arg == '--show-editor':
SHOW_EDITOR = True
elif arg == '--no-show-editor':
SHOW_EDITOR = False
elif arg.split('=')[0] == '--output-precision':
PRECISION = arg.split('=')[1]
def export(objectslist, filename, argstring):
processArguments(argstring)
global UNITS
global UNIT_FORMAT
for obj in objectslist:
if not hasattr(obj, "Path"):
print("the object " + obj.Name + " is not a path. Please select only path and Compounds.")
return
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
gcode += linenumber() + UNITS + "\n"
for obj in objectslist:
# fetch machine details
job = PathUtils.findParentJob(obj)
myMachine = 'not set'
if hasattr(job,"MachineName"):
myMachine = job.MachineName
if hasattr(job, "MachineUnits"):
if job.MachineUnits == "Metric":
UNITS = "G21"
UNIT_FORMAT = 'mm/min'
else:
UNITS = "G20"
UNIT_FORMAT = 'in/min'
# do the pre_op
if OUTPUT_COMMENTS:
gcode += linenumber() + "(begin operation: %s)\n" % obj.Label
gcode += linenumber() + "(machine: %s, %s)\n" % (myMachine, UNIT_FORMAT)
for line in PRE_OPERATION.splitlines(True):
gcode += linenumber() + line
gcode += parse(obj)
# do the post_op
if OUTPUT_COMMENTS:
gcode += linenumber() + "(finish operation: %s)\n" % obj.Label
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.setText(gcode)
result = dia.exec_()
if result:
final = dia.editor.toPlainText()
else:
final = gcode
else:
final = gcode
print("done postprocessing.")
if not filename == '-':
gfile = pythonopen(filename, "wb")
gfile.write(final)
gfile.close()
return final
def linenumber():
global LINENR
if OUTPUT_LINE_NUMBERS is True:
LINENR += 10
return "N" + str(LINENR) + " "
return ""
def parse(pathobj):
global PRECISION
out = ""
lastcommand = None
precision_string = '.' + str(PRECISION) +'f'
# params = ['X','Y','Z','A','B','I','J','K','F','S'] #This list control
# the order of parameters
# linuxcnc doesn't want K properties on XY plane Arcs need work.
params = ['X', 'Y', 'Z', 'A', 'B', 'I', 'J', 'F', 'S', 'T', 'Q', 'R', 'L']
if hasattr(pathobj, "Group"): # We have a compound or project.
# if OUTPUT_COMMENTS:
# out += linenumber() + "(compound: " + pathobj.Label + ")\n"
for p in pathobj.Group:
out += parse(p)
return out
else: # parsing simple path
# groups might contain non-path things like stock.
if not hasattr(pathobj, "Path"):
return out
# if OUTPUT_COMMENTS:
# out += linenumber() + "(" + pathobj.Label + ")\n"
for c in pathobj.Path.Commands:
outstring = []
command = c.Name
outstring.append(command)
# if modal: only print the command if it is not the same as the
# last one
if MODAL is True:
if command == lastcommand:
outstring.pop(0)
# Now add the remaining parameters in order
for param in params:
if param in c.Parameters:
if param == 'F':
if c.Name not in ["G0", "G00"]: #linuxcnc doesn't use rapid speeds
speed = Units.Quantity(c.Parameters['F'], FreeCAD.Units.Velocity)
outstring.append(
param + format(float(speed.getValueAs(UNIT_FORMAT)), precision_string) )
elif param == 'T':
outstring.append(param + str(int(c.Parameters['T'])))
else:
outstring.append(
param + format(c.Parameters[param], precision_string))
# store the latest command
lastcommand = command
# Check for Tool Change:
if command == 'M6':
# if OUTPUT_COMMENTS:
# out += linenumber() + "(begin toolchange)\n"
for line in TOOL_CHANGE.splitlines(True):
out += linenumber() + line
if command == "message":
if OUTPUT_COMMENTS is False:
out = []
else:
outstring.pop(0) # remove the command
# prepend a line number and append a newline
if len(outstring) >= 1:
if OUTPUT_LINE_NUMBERS:
outstring.insert(0, (linenumber()))
# append the line to the final output
for w in outstring:
out += w + COMMAND_SPACE
out = out.strip() + "\n"
return out
print(__name__ + " gcode postprocessor loaded.")

View File

@@ -0,0 +1,327 @@
from __future__ import print_function
import datetime
from PathScripts import PostUtils
# ***************************************************************************
# * (c) sliptonic (shopinthewoods@gmail.com) 2014 *
# * *
# * 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 *
# * *
# ***************************************************************************/
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
ToDo
comments may not format correctly
drilling. Haven't looked at it.
many other things
'''
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 = ''''''
# to distinguish python built-in open function from the one declared below
if open.__module__ == '__builtin__':
pythonopen = open
CurrentState = {}
def export(objectslist, filename, argstring):
global CurrentState
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.setText(gcode)
result = dia.exec_()
if result:
final = dia.editor.toPlainText()
else:
final = gcode
else:
final = gcode
print("done postprocessing.")
# Write the output
gfile = pythonopen(filename, "wb")
gfile.write(final)
gfile.close()
def move(command):
global CurrentState
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 speed != CurrentState['F']:
if command.Name in ['G1', 'G01']: # move
movetype = "MS"
else: # jog
movetype = "JS"
zspeed = ""
xyspeed = ""
if 'Z' in axis:
zspeed = "{:f}".format(speed)
if ('X' in axis) or ('Y' in axis):
xyspeed = "{:f}".format(speed)
txt += "{},{},{}\n".format(movetype, zspeed, xyspeed)
if command.Name in ['G0', 'G00']:
pref = "J"
else:
pref = "M"
if axis == "X":
txt += pref + "X"
txt += "," + format(command.Parameters["X"], '.4f')
txt += "\n"
elif axis == "Y":
txt += pref + "Y"
txt += "," + format(command.Parameters["Y"], '.4f')
txt += "\n"
elif axis == "Z":
txt += pref + "Z"
txt += "," + format(command.Parameters["Z"], '.4f')
txt += "\n"
elif axis == "XY":
txt += pref + "2"
txt += "," + format(command.Parameters["X"], '.4f')
txt += "," + format(command.Parameters["Y"], '.4f')
txt += "\n"
elif axis == "XZ":
txt += pref + "X"
txt += "," + format(command.Parameters["X"], '.4f')
txt += "\n"
txt += pref + "Z"
txt += "," + format(command.Parameters["Z"], '.4f')
txt += "\n"
elif axis == "XYZ":
txt += pref + "3"
txt += "," + format(command.Parameters["X"], '.4f')
txt += "," + format(command.Parameters["Y"], '.4f')
txt += "," + format(command.Parameters["Z"], '.4f')
txt += "\n"
elif axis == "YZ":
txt += pref + "Y"
txt += "," + format(command.Parameters["Y"], '.4f')
txt += "\n"
txt += pref + "Z"
txt += "," + format(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(command.Parameters['X'], '.4f') + ","
txt += format(command.Parameters['Y'], '.4f') + ","
txt += format(command.Parameters['I'], '.4f') + ","
txt += format(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")
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):
global CurrentState
output = ""
params = ['X', 'Y', 'Z', 'A', 'B', 'I', 'J', 'K', 'F', 'S', 'T']
# 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 pathobj.Path.Commands:
command = c.Name
if command in scommands:
output += scommands[command](c)
if c.Parameters:
CurrentState.update(c.Parameters)
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.")

View File

@@ -0,0 +1,209 @@
# ***************************************************************************
# * (c) sliptonic (shopinthewoods<at>gmail.com) 2014 *
# * *
# * 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 a preprocessor file for the Path workbench. Its aim is to
parse the contents of a given OpenSBP file, and transform it to make it
suitable for use in a Path object. This preprocessor, once placed in the
appropriate PathScripts folder, can be used directly from inside FreeCAD,
via the GUI importer or via python scripts with:
import opensbp_pre
opensbp_pre.insert("/path/to/myfile.ngc","DocumentName")
DONE
Correctly imports single axis and multi axis moves.
Stores Jog and Feed speeds
Appends Multiaxis Feed speed to G1 moves
Jog rates don't append to G0 moves
Make single axis feed rates work
Imports CG (non-diameter) arcs.
Handles CW and CCW spindle speeds
if operations are preceded by a comment ('New Path ...) They are split into multiple paths
TODO
Many other OpenSBP commands not handled
'''
from __future__ import print_function
import FreeCAD
import os, Path
AXIS = 'X','Y','Z','A','B' #OpenSBP always puts multiaxis move parameters in this order
SPEEDS = 'XY','Z','A','B'
# to distinguish python built-in open function from the one declared below
if open.__module__ == '__builtin__':
pythonopen = open
def open(filename):
"called when freecad opens a file."
docname = os.path.splitext(os.path.basename(filename))[0]
doc = FreeCAD.newDocument(docname)
insert(filename,doc.Name)
def insert(filename,docname):
"called when freecad imports a file"
"This insert expects parse to return a list of strings"
"each string will become a separate path"
gfile = pythonopen(filename)
gcode = gfile.read()
gfile.close()
gcode = parse(gcode)
doc = FreeCAD.getDocument(docname)
for subpath in gcode:
obj = doc.addObject("Path::Feature","Path")
path = Path.Path(subpath)
obj.Path = path
def parse(inputstring):
"parse(inputstring): returns a list of parsed output string"
print("preprocessing...")
# split the input by line
lines = inputstring.split("\n")
return_output = []
output = ""
last = {'X':None,'Y':None,'Z':None,'A':None,'B':None}
lastrapidspeed = {'XY':"50", 'Z':"50", 'A':"50", 'B':"50" } #set default rapid speeds
lastfeedspeed = {'XY':"50", 'Z':"50", 'A':"50", 'B':"50" } #set default feed speed
movecommand = ['G1', 'G0', 'G02', 'G03']
for l in lines:
# remove any leftover trailing and preceding spaces
l = l.strip()
if not l:
# discard empty lines
continue
if l[0] in ["'","&"]:
# discard comment and other non strictly gcode lines
if l[0:9] == "'New Path":
# starting new path
if any (x in output for x in movecommand): #make sure the path has at least one move command.
return_output.append(output)
output = ""
continue
words = [a.strip() for a in l.split(",")]
words[0] = words[0].upper()
if words[0] in ["J2","J3","J4","J5","M2","M3","M4","M5"]: #multi-axis jogs and moves
if words[0][0] == 'J': #jog move
s = "G0 "
else: #feed move
s = "G1 "
speed = lastfeedspeed["XY"]
for i in range (1, len(words)):
if words [i] == '':
if last[AXIS[i-1]] == None:
continue
else:
s += AXIS[i-1] + last[AXIS[i-1]]
else:
s += AXIS[i-1] + words[i]
last[AXIS[i-1]] = words[i]
output += s +" F" + speed + '\n'
if words[0] in ["JA","JB","JX","JY","JZ","MA","MB","MX","MY","MZ"]: #single axis jogs and moves
if words[0][0] == 'J': #jog move
s = "G0 "
if words[0][1] in ['X','Y']:
speed = lastrapidspeed["XY"]
else:
speed = lastrapidspeed[words[0][1]]
else: #feed move
s = "G1 "
if words[0][1] in ['X','Y']:
speed = lastfeedspeed["XY"]
else:
speed = lastfeedspeed[words[0][1]]
last[words[0][1]] = words[1]
output += s
for key, val in last.iteritems():
if val is not None:
output += key + str(val) + " F" + speed + "\n"
if words[0] in ["JS"]: #set jog speed
for i in range (1, len(words)):
if words [i] == '':
continue
else:
lastrapidspeed[SPEEDS[i-1]] = words[i]
if words[0] in ["MD"]: #move distance with distance and angle.
#unsupported at this time
continue
if words[0] in ["MH"]: #move home
#unsupported at this time
continue
if words[0] in ["MS"]: #set move speed
for i in range (1, len(words)):
if words [i] == '':
continue
else:
lastfeedspeed[SPEEDS[i-1]] = words[i]
if words[0] in ["MO"]: #motors off
#unsupported at this time
continue
if words[0] in ["TR"]: #Setting spindle speed
if float(words[1]) < 0:
s = "M4 S"
else:
s = "M3 S"
s += str(abs(float(words[1])))
output += s + '\n'
if words[0] in ["CG"]: #Gcode circle/arc
if words[1] != "": # diameter mode
print("diameter mode not supported")
continue
else:
if words[7] == "1": #CW
s = "G2"
else: #CCW
s = "G3"
s += " X" + words[2] + " Y" + words[3] + " I" + words[4] + " J" + words[5] + " F" + str(lastfeedspeed["XY"])
output += s + '\n'
last["X"] = words[2]
last["Y"] = words[3]
#Make sure all appended paths have at least one move command.
if any (x in output for x in movecommand):
return_output.append(output)
print("done preprocessing.")
return return_output
print(__name__ + " gcode preprocessor loaded.")

View File

@@ -0,0 +1,469 @@
# -*- coding: utf-8 -*-
#***************************************************************************
#* *
#* Copyright (c) 2016 Christoph Blaue <blaue@fh-westkueste.de> *
#* *
#* 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. *
#* *
#* This program 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 Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#***************************************************************************
TOOLTIP = '''Post processor for Maho M 600E mill
Machines with Philips or Heidenhain control should be very easy to adapt.
The post processor is configurable by changing the values of constants.
No programming experience required. This can make a generated g-code
program more readable and since older machines have very
limited memory it seems sensible to reduce the number of commands and
parameters, like e.g. suppress the units in the header and at every hop.
'''
# reload in python console:
# import generic_post
# reload(generic_post)
''' example post for Maho M 600E mill'''
import FreeCAD
import time
from PathScripts import PostUtils
import math
#***************************************************************************
# user editable stuff here
MACHINE_NAME = 'Maho 600E'
CORNER_MIN = {'x': -51.877, 'y': 0, 'z': 0} # use metric for internal units
# use metric for internal units
CORNER_MAX = {'x': 591.5, 'y': 391.498, 'z': 391.5}
UNITS = 'G21' # use metric units
# possible values:
# 'G20' for inches,
# 'G21' for metric units.
# a mapping to different GCodes is handled in the GCODE MAP below
UNITS_INCLUDED = False # do not include the units in the GCode program
# possible values:
# True if units should be included
# False if units should not be included
# usually the units to be used are defined in the machine constants and almost never change,
# so this can be set to False.
COMMENT = ''
# possible values:
# ';' centroid or sinumerik comment symbol,
# '' leave blank for bracketed comments style "(comment comment comment)"
# '...' any other symbol to start comments
# currently this can be only one symbol, if it should be a sequence of characters
# in PostUtils.py the line
# if len(commentsym)==1:
# should be changed to
# if len(commentsym)>1:
SHOW_EDITOR = True
# possible values:
# True before the file is written it is shown to the user for inspection
# False the file is written directly
LINENUMBERS = True
# possible values:
# True if linenumbers of the form N1 N2 ... should be included
# False linennumbers are suppressed
# if linenumbers are used, header and footer get numbered as well
STARTLINENR = 1 # first linenumber used
# possible values:
# any integer value >= 0
# to have the possibility to change some initial values directly at the CNC machine
# without renumbering the rest it is possible to start the numbering of
# the file with some value > 0
LINENUMBER_INCREMENT = 1
# possible values:
# any integer value > 0
# similar to STARTLINENR it is possible to leave gaps in the linenumbering
# of subsequent lines
MODAL = True
# possible values:
# True repeated GCodes in subsequent lines are suppressed, like in the following snippet
# G1 X10 Y20
# X10 Y30
# False repeated GCodes in subsequent lines are repeated in the GCode file
# G1 X10 Y20
# G1 X10 Y30
# suppress these parameters if they haven't changed
MODALPARAMS = ['X', 'Y', 'Z', 'S', 'F']
# possible values:
# any list of GCode parameters
# if a parameter doesn't change from one line to the next ( or even further) it is suppressed.
# Example:
# G1 X10 Y20
# G1 Y30
# If in addition MODAL is set to True, the generated GCode changes to
# G1 X10 Y20
# Y30
SWAP_G2_G3 = True # some machines have the sign of the X-axis swapped, so they behave like milling from the bottom
# possible values:
# True if left and right turns are to be swapped
# False don't swap
# this might be special with some maho machines or even with mine and
# might be changed in the machine constants as well
SWAP_Y_Z = True # machines with an angle milling head do not switch axes, so we do it here
# possible values:
# True if Y and Z values have to be swapped
# False do not swap
# For vertical milling machines the Z-axis is horizontal (of course).
# If they have an angle milling head, they mill vertical, alas the Z-axis stays horizontal.
# With this parameter we can swap the output values of Y and Z.
# For commands G2 and G3 this means that J and K are swapped as well
ABSOLUTE_CIRCLE_CENTER = True
# possible values:
# True use absolute values for the circle center in commands G2, G3
# False values for I, J, K are given relative to the last point
USE_RADIUS_IF_POSSIBLE = True
# possible values:
# True if in commands G2 and G3 the usage of radius R is preferred
# False if in commands G2 and G3 we use always I and J
# When milling arcs there are two reasons to use the radius instead of the center:
# 1. the GCode program might be easier to understand
# 2. Some machines seem to have a different scheme for calculating / rounding the values of the center
# Thus it is possible that the machine complains, that the endpoint of the arc does not lie on the arc.
# Using the radius instead avoids this problem.
# The post processor takes care of the fact, that only angles <= 180 degrees can be used with R
# for larger angles the center is used independent of the setting of this
# constant
RADIUS_COMMENT = True
# possible values:
# True for better understanding the radius of an arc is included as a comment
# False no additional comment is included
# In case the comments are included they are always included with the bracketing syntax like '(R20.456)'
# and never with the comment symbol, because the radius might appear in
# the middle of a line.
GCODE_MAP = {'M1': 'M0', 'M6': 'M66', 'G20': 'G70',
'G21': 'G71'} # cb: this could be used to swap G2/G3
# possible values:
# Comma separated list of values of the form 'sourceGCode':'targetGCode'
#
# Although the basic movement commands G0, G1, G2 seem to be used uniformly in different GCode dialects,
# this is not the case for all commands.
# E.g the Maho dialect uses G70 and G71 for the units inches vs. metric.
# The map {'M1':'M0', 'G20':'G70', 'G21':'G71'} maps the optional stop command M1 to M0,
# because some Maho machines do not have the optional button on its panel
# in addition it maps inches G20 to G70 and metric G21 to G71
AXIS_DECIMALS = 3
# possible values:
# integer >= 0
FEED_DECIMALS = 2
# possible values:
# integer >= 0
SPINDLE_DECIMALS = 0
# possible values:
# integer >= 0
# The header is divided into two parts, one is dynamic, the other is a static GCode header.
# If the current selection and the current time should be included in the header,
# it has to be generated at execution time, and thus it cannot be held in constant values.
# The last linefeed should be omitted, it is inserted automatically
# linenumbers are inserted automatically if LINENUMBERS is True
# if you don't want to use this header you have to provide a minimal function
# def mkHeader(selection):
# return ''
def mkHeader(selection):
# this is within a function, because otherwise filename and time don't change when changing the FreeCAD project
# now = datetime.datetime.now()
now = time.strftime("%Y-%m-%d %H:%M")
originfile = FreeCAD.ActiveDocument.FileName
headerNoNumber = "%PM\n" # this line gets no linenumber
if hasattr(selection[0], "Description"):
description = selection[0].Description
else:
description = ""
# this line gets no linenumber, it is already a specially numbered
headerNoNumber += "N9XXX (" + description + ", " + now + ")\n"
header = ""
# header += "(Output Time:" + str(now) + ")\n"
header += "(" + originfile + ")\n"
header += "(Exported by FreeCAD)\n"
header += "(Post Processor: " + __name__ + ")\n"
header += "(Target machine: " + MACHINE_NAME + ")"
return headerNoNumber + linenumberify(header)
GCODE_HEADER = "" # do not terminate with a newline, it is inserted by linenumberify
# GCODE_HEADER = "G40 G90" # do not terminate with a newline, it is inserted by linenumberify
# possible values:
# any sequence of GCode, multiple lines are welcome
# this constant header follows the text generated by the function mkheader
# linenumbers are inserted automatically if LINENUMBERS is True
# do not terminate with a newline, it is inserted by linenumberify
GCODE_FOOTER = "M30"
# possible values:
# any sequence of GCode, multiple lines are welcome
# the footer is used to clean things up, reset modal commands and stop the machine
# linenumbers are inserted automatically if LINENUMBERS is True
# don't edit with the stuff below the next line unless you know what you're doing :)
#***************************************************************************
linenr = 0 # variable has to be global because it is used by linenumberify and export
if open.__module__ == '__builtin__':
pythonopen = open
def angleUnder180(command, lastX, lastY, x, y, i, j):
# radius R can be used iff angle is < 180.
# This is the case
# if the previous point is left of the current and the center is below (or on) the connection line
# or if the previous point is right of the current and the center is above
# (or on) the connection line
middleOfLineY = (lastY + y) / 2
centerY = lastY + j
if ((command == 'G2' and ((lastX == x and ((lastY < y and i >= 0) or (lastY > y and i <= 0))) or (lastX < x and centerY <= middleOfLineY) or (lastX > x and centerY >= middleOfLineY)))
or (command == 'G3' and ((lastX == x and ((lastY < y and i <= 0) or (lastY > y and i >= 0))) or (lastX < x and centerY >= middleOfLineY) or (lastX > x and centerY <= middleOfLineY)))):
return True
else:
return False
def mapGCode(command):
if command in GCODE_MAP:
mappedCommand = GCODE_MAP[command]
else:
mappedCommand = command
if SWAP_G2_G3:
if command == 'G2':
mappedCommand = 'G3'
elif command == 'G3':
mappedCommand = 'G2'
return mappedCommand
def linenumberify(GCodeString):
# add a linenumber at every beginning of line
global linenr
if not LINENUMBERS:
result = GCodeString + "\n"
else:
result = ''
strList = GCodeString.split("\n")
for s in strList:
if s:
# only non empty lines get numbered. the special lines "%PM"
# and prognumber "N9XXX" are skipped
result += "N" + str(linenr) + " " + s + "\n"
linenr += LINENUMBER_INCREMENT
else:
result += s + "\n"
return result
def export(selection, filename, argstring):
global linenr
linenr = STARTLINENR
lastX = 0
lastY = 0
lastZ = 0
params = ['X', 'Y', 'Z', 'A', 'B', 'I', 'J', 'F', 'H', 'S', 'T',
'Q', 'R', 'L'] # Using XY plane most of the time so skipping K
modalParamsDict = dict()
for mp in MODALPARAMS:
modalParamsDict[mp] = None
for obj in selection:
if not hasattr(obj, "Path"):
print("the object " + obj.Name + " is not a path. Please select only path and Compounds.")
return
myMachine = None
for pathobj in selection:
if hasattr(pathobj, "MachineName"):
myMachine = pathobj.MachineName
if hasattr(pathobj, "MachineUnits"):
if pathobj.MachineUnits == "Metric":
UNITS = "G21"
else:
UNITS = "G20"
if myMachine is None:
print("No machine found in this selection")
gcode = ''
gcode += mkHeader(selection)
gcode += linenumberify(GCODE_HEADER)
if UNITS_INCLUDED:
gcode += linenumberify(mapGCode(UNITS))
lastcommand = None
gobjects = []
for g in selection[0].Group:
if g.Name != 'Machine': # filtering out gcode home position from Machine object
gobjects.append(g)
for obj in gobjects:
if hasattr(obj, 'Comment'):
gcode += linenumberify('(' + obj.Comment + ')')
for c in obj.Path.Commands:
outstring = []
command = c.Name
if (command != UNITS or UNITS_INCLUDED):
if command[0] == '(':
command = PostUtils.fcoms(command, COMMENT)
# the mapping is done for output only! For internal things we
# still use the old value.
mappedCommand = mapGCode(command)
if not MODAL or command != lastcommand:
outstring.append(mappedCommand)
# if MODAL == True: )
# #\better: append iff MODAL == False )
# if command == lastcommand: )
# outstring.pop(0!#\ )
if c.Parameters >= 1:
for param in params:
if param in c.Parameters:
if (param in MODALPARAMS) and (modalParamsDict[str(param)] == c.Parameters[str(param)]):
# do nothing or append white space
outstring.append(' ')
elif param == 'F':
outstring.append(
param + PostUtils.fmt(c.Parameters['F'], FEED_DECIMALS, UNITS))
elif param == 'H':
outstring.append(
param + str(int(c.Parameters['H'])))
elif param == 'S':
# rpm is unitless-therefore I had to 'fake it
# out' by using metric units which don't get
# converted from entered value
outstring.append(
param + PostUtils.fmt(c.Parameters['S'], SPINDLE_DECIMALS, 'G21'))
elif param == 'T':
outstring.append(
param + str(int(c.Parameters['T'])))
elif param == 'I' and (command == 'G2' or command == 'G3'):
# this is the special case for circular paths,
# where relative coordinates have to be changed
# to absolute
i = c.Parameters['I']
# calculate the radius r
j = c.Parameters['J']
r = math.sqrt(i**2 + j**2)
if USE_RADIUS_IF_POSSIBLE and angleUnder180(command, lastX, lastY, c.Parameters['X'], c.Parameters['Y'], i, j):
outstring.append(
'R' + PostUtils.fmt(r, AXIS_DECIMALS, UNITS))
else:
if RADIUS_COMMENT:
outstring.append(
'(R' + PostUtils.fmt(r, AXIS_DECIMALS, UNITS) + ')')
if ABSOLUTE_CIRCLE_CENTER:
i += lastX
outstring.append(
param + PostUtils.fmt(i, AXIS_DECIMALS, UNITS))
elif param == 'J' and (command == 'G2' or command == 'G3'):
# this is the special case for circular paths,
# where incremental center has to be changed to
# absolute center
i = c.Parameters['I']
j = c.Parameters['J']
if USE_RADIUS_IF_POSSIBLE and angleUnder180(command, lastX, lastY, c.Parameters['X'], c.Parameters['Y'], i, j):
# R is handled with the I parameter, here:
# do nothing at all, keep the structure as
# with I command
pass
else:
if ABSOLUTE_CIRCLE_CENTER:
j += lastY
if SWAP_Y_Z:
# we have to swap j and k as well
outstring.append(
'K' + PostUtils.fmt(j, AXIS_DECIMALS, UNITS))
else:
outstring.append(
param + PostUtils.fmt(j, AXIS_DECIMALS, UNITS))
elif param == 'K' and (command == 'G2' or command == 'G3'):
# this is the special case for circular paths,
# where incremental center has to be changed to
# absolute center
outstring.append(
'(' + param + PostUtils.fmt(c.Parameters[param], AXIS_DECIMALS, UNITS) + ')')
z = c.Parameters['Z']
k = c.Parameters['K']
if USE_RADIUS_IF_POSSIBLE and angleUnder180(command, lastX, lastY, c.Parameters['X'], c.Parameters['Y'], i, j):
# R is handled with the I parameter, here:
# do nothing at all, keep the structure as
# with I command
pass
else:
if ABSOLUTE_CIRCLE_CENTER:
k += lastZ
if SWAP_Y_Z:
# we have to swap j and k as well
outstring.append(
'J' + PostUtils.fmt(j, AXIS_DECIMALS, UNITS))
else:
outstring.append(
param + PostUtils.fmt(j, AXIS_DECIMALS, UNITS))
elif param == 'Y' and SWAP_Y_Z:
outstring.append(
'Z' + PostUtils.fmt(c.Parameters[param], AXIS_DECIMALS, UNITS))
elif param == 'Z' and SWAP_Y_Z:
outstring.append(
'Y' + PostUtils.fmt(c.Parameters[param], AXIS_DECIMALS, UNITS))
else:
outstring.append(
param + PostUtils.fmt(c.Parameters[param], AXIS_DECIMALS, UNITS))
if param in MODALPARAMS:
modalParamsDict[str(param)] = c.Parameters[
param]
# save the last X, Y, Z values
if 'X' in c.Parameters:
lastX = c.Parameters['X']
if 'Y' in c.Parameters:
lastY = c.Parameters['Y']
if 'Z' in c.Parameters:
lastZ = c.Parameters['Z']
outstr = str(outstring)
outstr = outstr.replace(']', '')
outstr = outstr.replace('[', '')
outstr = outstr.replace("'", '')
outstr = outstr.replace(",", '')
if LINENUMBERS:
gcode += "N" + str(linenr) + " "
linenr += LINENUMBER_INCREMENT
gcode += outstr + '\n'
lastcommand = c.Name
gcode += linenumberify(GCODE_FOOTER)
if SHOW_EDITOR:
PostUtils.editor(gcode)
gfile = pythonopen(filename, "wb")
gfile.write(gcode)
gfile.close()

View File

@@ -0,0 +1,256 @@
#***************************************************************************
#* (c) Jon Nordby (jononor@gmail.com) 2015 *
#* *
#* 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 *
#* *
#***************************************************************************/
TOOLTIP='''
FreeCAD Path post-processor to output code for the Roland Modela MDX-## machines.
The machine speaks RML-1, specified in 'Roland RML-1 Programming Guidelines'
https://itp.nyu.edu/classes/cdp-spring2014/files/2014/09/RML1_Manual.pdf
http://altlab.org/d/content/m/pangelo/ideas/rml_command_guide_en_v100.pdf
The format has some overlap with HPGL:
https://en.wikipedia.org/wiki/HPGL
http://paulbourke.net/dataformats/hpgl/
'''
import FreeCAD
import Part
import PostUtils
# to distinguish python built-in open function from the one declared below
if open.__module__ == '__builtin__':
pythonopen = open
# Entrypoint used by FreeCAD
def export(objectslist, filename, argstring):
"Export objects as Roland Modela code."
code = ""
for obj in objectslist:
code += convertobject(obj)
gfile = pythonopen(filename,"wb")
gfile.write(code)
gfile.close()
def convertobject(obj):
gcode = obj.Path.toGCode()
gcode = parse(gcode)
return gcode
def motoron():
return [ "!MC1;" ]
def motoroff():
return [ "!MC0;" ]
def home():
return [ "H;" ]
def setjog():
# "!PZ%d,%d;",iz_down,iz_up); // set z down, jog
return ""
def addheader():
return [ "PA;PA;" ] # absolute positioning
def addfooter():
return []
def mm2cord(mm):
mm = float(mm)
return int(40.0*mm)
def feed(x=None, y=None, z=None, state={}):
c = []
if x is not None:
x = float(x)
state['X'] = x
if y is not None:
y = float(y)
state['Y'] = y
if z is not None:
z = float(z)
state['Z'] = z
if x is not None and y is not None and z is not None:
# 3d motion
c.append("Z%d,%d,%d;" % (mm2cord(x), mm2cord(y), mm2cord(z)))
elif x is not None and y is not None:
# 2d in XY plane
c.append("PD%d,%d;" % (mm2cord(x), mm2cord(y)))
elif z is not None:
pass # XXX: is this used?
return c
def jog(x=None, y=None, z=None, state={}):
c = []
if x is not None and y is not None:
x, y = float(x), float(y)
c.append("PU%d,%d;" % (mm2cord(x), mm2cord(y)))
state['X'] = x
state['Y'] = y
if z is not None:
z = float(z)
c.append("PU;")
# TODO: use !ZZ command
state['Z'] = z
return c
def xyarc(args, state):
# no native support in RML/Modela, convert to linear line segments
c = []
lastPoint = FreeCAD.Vector(state['X'], state['Y'])
newPoint = FreeCAD.Vector(float(args['X']), float(args['Y']))
centerOffset = FreeCAD.Vector(float(args['I']), float(args['J']))
center = lastPoint + centerOffset
radius = (center - lastPoint).Length
xyNormal = FreeCAD.Vector(0, 0, 1)
circle = Part.Circle(center, xyNormal, radius)
p0 = circle.parameter(lastPoint)
p1 = circle.parameter(newPoint)
arc = Part.ArcOfCircle(circle, p0, p1)
steps = 64 # TODO: specify max error instead
points = arc.discretize(steps)
# TODO: consider direction
#print('p = Part.ArcOfCircle(Part.Circle(FreeCAD.Vector(%f, %f), FreeCAD.Vector(0, 0, 1), %f), %f, %f)' % (center.x, center.y, radius, p0, p1))
for p in points:
c += feed(p.x, p.y, state['Z'], state)
return c
def speed(xy=None, z=None, state={}):
c = []
print(xy, z, state)
if xy is not None:
xy = float(xy)
if xy > 0.0 and xy != state['XYspeed']:
c.append("VS%.1f;" % xy)
state['XYspeed'] = xy
if z is not None:
z = float(z)
if z > 0.0 and z != state['Zspeed']:
c.append("!VZ%.1f;" % z)
state['Zspeed'] = z
return c
def convertgcode(cmd, args, state):
"""Convert a single gcode command to equivalent Roland code"""
if cmd == 'G0':
# jog
return jog(args['X'], args['Y'], args['Z'], state)
elif cmd == 'G1':
# linear feed
c = []
# feedrate
c += speed(xy=args['F'], z=args['F'], state=state)
# motion
c += feed(args['X'], args['Y'], args['Z'], state)
return c
elif cmd == 'G2' or cmd == 'G3':
# arc feed
c = []
# feedrate
c += speed(xy=args['F'], state=state)
# motion
if args['X'] and args['Y'] and args['Z']:
# helical motion
pass
elif args['X'] and args['Y']:
# arc in plane
c += xyarc(args, state)
return c
elif cmd == 'G20':
# inches mode
raise ValueError("rml_post: Inches mode not supported")
elif cmd == 'G21':
# millimeter mode
return ""
elif cmd == 'G40':
# tool compensation off
return ""
elif cmd == 'G80':
# cancel all cycles (drill normally)
return "PU;"
elif cmd == 'G81':
c = []
# feedrate
c += speed(z=args['F'], state=state)
# motion
c += jog(args['X'], args['Y'], state=state)
c += feed(args['X'], args['Y'], args['Z'], state)
return c
elif cmd == 'G90':
# absolute mode?
return ""
elif cmd == 'G98':
# feedrate
return ""
else:
raise NotImplementedError("rml_post: GCode command %s not understood" % (cmd,))
raise Exception("should not be reached. cmd=%s" % (cmd,))
def parse(inputstring):
"parse(inputstring): returns a parsed output string"
state = { 'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'XYspeed': -1.0, 'Zspeed': -1.0 }
output = []
# header
output += addheader()
output += motoron()
output += speed(2.0, 1.0, state) # defaults
# TODO: respect clearance height
# treat the input line by line
lines = inputstring.split("\n")
for line in lines:
if not line:
continue
parsed = PostUtils.stringsplit(line)
command = parsed['command']
print('cmd', line)
try:
if command:
code = convertgcode(command, parsed, state)
if not isinstance(code, list):
code = [ code ]
if len(code) and code[0]:
output += code
except NotImplementedError as e:
print(e)
# footer
output += motoroff()
output += home()
output += addfooter()
return '\n'.join(output)
print (__name__ + " gcode postprocessor loaded.")

View File

@@ -0,0 +1,97 @@
# ***************************************************************************
# * (c) Yorik van Havre (yorik@uncreated.net) 2015 *
# * *
# * 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 preprocessor to read gcode files produced from slic3r.
'''
import os
import Path
import FreeCAD
# to distinguish python built-in open function from the one declared below
if open.__module__ == '__builtin__':
pythonopen = open
def open(filename):
"called when freecad opens a file."
docname = os.path.splitext(os.path.basename(filename))[0]
doc = FreeCAD.newDocument(docname)
insert(filename, doc.Name)
def insert(filename, docname):
"called when freecad imports a file"
gfile = pythonopen(filename)
gcode = gfile.read()
gfile.close()
gcode = parse(gcode)
doc = FreeCAD.getDocument(docname)
obj = doc.addObject("Path::Feature", "Path")
path = Path.Path(gcode)
obj.Path = path
def parse(inputstring):
"parse(inputstring): returns a parsed output string"
print("preprocessing...")
# split the input by line
lines = inputstring.split("\n")
output = ""
lastcommand = None
for l in lines:
# remove any leftover trailing and preceding spaces
l = l.strip()
if not l:
# discard empty lines
continue
if l[0].upper() in ["N"]:
# remove line numbers
l = l.split(" ", 1)[1]
if ";" in l:
# replace ; comments with ()
l = l.replace(";", "(")
l = l + ")"
if l[0].upper() in ["G", "M", "("]:
# found a G or M command: we store it
output += l + "\n"
last = l[0].upper()
for c in l[1:]:
if not c.isdigit():
break
else:
last += c
lastcommand = last
elif lastcommand:
# no G or M command: we repeat the last one
output += lastcommand + " " + l + "\n"
print("done preprocessing.")
return output
print (__name__ + " gcode preprocessor loaded.")

View File

@@ -0,0 +1,383 @@
# ***************************************************************************
# * (c) sliptonic (shopinthewoods@gmail.com) 2017 *
# * *
# * 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 *
# * *
# ***************************************************************************/
from __future__ import print_function
TOOLTIP='''
This is a postprocessor file for the Path workbench. It is used to
take a pseudo-gcode fragment outputted by a Path object, and output
real GCode suitable for a smoothieboard. 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 smoothie_post
linuxcnc_post.export(object,"/path/to/file.ncc","")
'''
TOOLTIP_ARGS='''
Arguments for smoothieboard:
--header,--no-header ... output headers (--header)
--comments,--no-comments ... output comments (--comments)
--line-numbers,--no-line-numbers ... prefix with line numbers (--no-lin-numbers)
--show-editor, --no-show-editor ... pop up editor before writing output(--show-editor)
--IP_ADDR ... IP Address for remote sending of gcode
'''
import FreeCAD
from FreeCAD import Units
import datetime
from PathScripts import PostUtils
now = datetime.datetime.now()
# These globals set common customization preferences
OUTPUT_COMMENTS = True
OUTPUT_HEADER = True
OUTPUT_LINE_NUMBERS = False
IP_ADDR = None
VERBOSE = False
SPINDLE_SPEED = 0.0
if FreeCAD.GuiUp:
SHOW_EDITOR = True
else:
SHOW_EDITOR = False
MODAL = False # if true commands are suppressed if the same as previous line.
COMMAND_SPACE = " "
LINENR = 100 # line number starting value
# These globals will be reflected in the Machine configuration of the project
UNITS = "G21" # G21 for metric, G20 for us standard
UNIT_FORMAT = 'mm/min'
MACHINE_NAME = "SmoothieBoard"
CORNER_MIN = {'x': 0, 'y': 0, 'z': 0}
CORNER_MAX = {'x': 500, 'y': 300, 'z': 300}
# Preamble text will appear at the beginning of the GCODE output file.
PREAMBLE = '''G17 G90
'''
# Postamble text will appear following the last operation.
POSTAMBLE = '''M05
G00 X-1.0 Y1.0
G17 G90
M2
'''
# 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 = ''''''
# to distinguish python built-in open function from the one declared below
if open.__module__ == '__builtin__':
pythonopen = open
def processArguments(argstring):
global OUTPUT_HEADER
global OUTPUT_COMMENTS
global OUTPUT_LINE_NUMBERS
global SHOW_EDITOR
global IP_ADDR
global VERBOSE
for arg in argstring.split():
if arg == '--header':
OUTPUT_HEADER = True
elif arg == '--no-header':
OUTPUT_HEADER = False
elif arg == '--comments':
OUTPUT_COMMENTS = True
elif arg == '--no-comments':
OUTPUT_COMMENTS = False
elif arg == '--line-numbers':
OUTPUT_LINE_NUMBERS = True
elif arg == '--no-line-numbers':
OUTPUT_LINE_NUMBERS = False
elif arg == '--show-editor':
SHOW_EDITOR = True
elif arg == '--no-show-editor':
SHOW_EDITOR = False
elif arg.split('=')[0] == '--IP_ADDR':
IP_ADDR = arg.split('=')[1]
elif arg == '--verbose':
VERBOSE = True
def export(objectslist, filename, argstring):
processArguments(argstring)
global UNITS
global IP_ADDR
for obj in objectslist:
if not hasattr(obj, "Path"):
FreeCAD.Console.PrintError("the object " + obj.Name + " is not a path. Please select only path and Compounds.\n")
return
FreeCAD.Console.PrintMessage("postprocessing...\n")
gcode = ""
# Find the machine.
# The user my have overridden post processor defaults in the GUI. Make
# sure we're using the current values in the Machine Def.
myMachine = None
for pathobj in objectslist:
if hasattr(pathobj,"MachineName"):
myMachine = pathobj.MachineName
if hasattr(pathobj, "MachineUnits"):
if pathobj.MachineUnits == "Metric":
UNITS = "G21"
else:
UNITS = "G20"
if myMachine is None:
FreeCAD.Console.PrintWarning("No machine found in this selection\n")
# 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
gcode += linenumber() + UNITS + "\n"
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.setText(gcode)
result = dia.exec_()
if result:
final = dia.editor.toPlainText()
else:
final = gcode
else:
final = gcode
if IP_ADDR is not None:
sendToSmoothie(IP_ADDR, final, filename)
else:
if not filename == '-':
gfile = pythonopen(filename, "wb")
gfile.write(final)
gfile.close()
FreeCAD.Console.PrintMessage("done postprocessing.\n")
return final
def sendToSmoothie(IP_ADDR, GCODE, fname):
import sys
import socket
import os
global VERBOSE
fname = os.path.basename(fname)
FreeCAD.Console.PrintMessage ('sending to smoothie: {}\n'.format(fname))
f = GCODE.rstrip()
filesize= len(f)
# make connection to sftp server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(4.0)
s.connect((IP_ADDR, 115))
tn= s.makefile()
# read startup prompt
ln= tn.readline()
if not ln.startswith("+") :
FreeCAD.Console.PrintMessage("Failed to connect with sftp: {}\n".format(ln))
sys.exit();
if VERBOSE: print("RSP: " + ln.strip())
# Issue initial store command
tn.write("STOR OLD /sd/" + fname + "\n")
tn.flush()
ln= tn.readline()
if not ln.startswith("+") :
FreeCAD.Console.PrintError("Failed to create file: {}\n".format(ln))
sys.exit();
if VERBOSE: print("RSP: " + ln.strip())
# send size of file
tn.write("SIZE " + str(filesize) + "\n")
tn.flush()
ln= tn.readline()
if not ln.startswith("+") :
FreeCAD.Console.PrintError("Failed: {}\n".format(ln))
sys.exit();
if VERBOSE: print("RSP: " + ln.strip())
cnt= 0
# now send file
for line in f.splitlines(1):
tn.write(line)
if VERBOSE :
cnt += len(line)
print("SND: " + line.strip())
print(str(cnt) + "/" + str(filesize) + "\r", end='')
tn.flush()
ln= tn.readline()
if not ln.startswith("+") :
FreeCAD.Console.PrintError("Failed to save file: {}\n".format(ln))
sys.exit();
if VERBOSE: print("RSP: " + ln.strip())
# exit
tn.write("DONE\n")
tn.flush()
ln= tn.readline()
tn.close()
FreeCAD.Console.PrintMessage("Upload complete\n")
def linenumber():
global LINENR
if OUTPUT_LINE_NUMBERS is True:
LINENR += 10
return "N" + str(LINENR) + " "
return ""
def parse(pathobj):
out = ""
lastcommand = None
global SPINDLE_SPEED
# params = ['X','Y','Z','A','B','I','J','K','F','S'] #This list control
# the order of parameters
# linuxcnc doesn't want K properties on XY plane Arcs need work.
params = ['X', 'Y', 'Z', 'A', 'B', 'I', 'J', 'F', 'S', 'T', 'Q', 'R', 'L']
if hasattr(pathobj, "Group"): # We have a compound or project.
# if OUTPUT_COMMENTS:
# out += linenumber() + "(compound: " + pathobj.Label + ")\n"
for p in pathobj.Group:
out += parse(p)
return out
else: # parsing simple path
# groups might contain non-path things like stock.
if not hasattr(pathobj, "Path"):
return out
# if OUTPUT_COMMENTS:
# out += linenumber() + "(" + pathobj.Label + ")\n"
for c in pathobj.Path.Commands:
outstring = []
command = c.Name
outstring.append(command)
# if modal: only print the command if it is not the same as the
# last one
if MODAL is True:
if command == lastcommand:
outstring.pop(0)
# Now add the remaining parameters in order
for param in params:
if param in c.Parameters:
if param == 'F':
if c.Name not in ["G0", "G00"]: #linuxcnc doesn't use rapid speeds
speed = Units.Quantity(c.Parameters['F'], FreeCAD.Units.Velocity)
outstring.append(
param + format(float(speed.getValueAs(UNIT_FORMAT)), '.2f') )
elif param == 'T':
outstring.append(param + str(c.Parameters['T']))
elif param == 'S':
outstring.append(param + str(c.Parameters['S']))
SPINDLE_SPEED = c.Parameters['S']
else:
outstring.append(
param + format(c.Parameters[param], '.4f'))
if command in ['G1', 'G01', 'G2', 'G02', 'G3', 'G03']:
outstring.append('S' + str(SPINDLE_SPEED))
# store the latest command
lastcommand = command
# Check for Tool Change:
if command == 'M6':
# if OUTPUT_COMMENTS:
# out += linenumber() + "(begin toolchange)\n"
for line in TOOL_CHANGE.splitlines(True):
out += linenumber() + line
if command == "message":
if OUTPUT_COMMENTS is False:
out = []
else:
outstring.pop(0) # remove the command
# prepend a line number and append a newline
if len(outstring) >= 1:
if OUTPUT_LINE_NUMBERS:
outstring.insert(0, (linenumber()))
# append the line to the final output
for w in outstring:
out += w + COMMAND_SPACE
out = out.strip() + "\n"
return out
print(__name__ + " gcode postprocessor loaded.")