Path: post processor cleanup

This commit is contained in:
brad
2019-06-08 23:10:47 -05:00
parent 361bb6e3c8
commit 5a4c49da28
5 changed files with 118 additions and 119 deletions

View File

@@ -28,7 +28,6 @@ import argparse
import datetime
import shlex
from PathScripts import PostUtils
from PathScripts import PathUtils
TOOLTIP = '''
This is a postprocessor file for the Path workbench. It is used to
@@ -54,7 +53,6 @@ parser.add_argument('--postamble', help='set commands to be issued after the las
parser.add_argument('--inches', action='store_true', help='Convert output for US imperial mode (G20)')
parser.add_argument('--modal', action='store_true', help='Output the Same G-command Name USE NonModal Mode')
parser.add_argument('--axis-modal', action='store_true', help='Output the Same Axis Value Mode')
#parser.add_argument('--power-max', help='set the max value for laser power default=255')
parser.add_argument('--power-on-delay', default='255', help='milliseconds - Add a delay after laser on before moving to pre-heat material. Default=0')
@@ -104,7 +102,6 @@ POST_OPERATION = ''''''
# Tool Change commands will be inserted before a tool change
TOOL_CHANGE = ''''''
#POWER_MAX = 255
POWER_ON_DELAY = 0
# to distinguish python built-in open function from the one declared below
@@ -152,9 +149,9 @@ def processArguments(argstring):
MODAL = True
if args.axis_modal:
OUTPUT_DOUBLES = False
POWER_ON_DELAY = float(args.power_on_delay) / 1000 #milliseconds
POWER_ON_DELAY = float(args.power_on_delay) / 1000 # milliseconds
except:
except Exception:
return False
return True
@@ -290,7 +287,7 @@ def parse(pathobj):
if command == lastcommand:
outstring.pop(0)
if c.Name[0] == '(' and not OUTPUT_COMMENTS: # command is a comment
if c.Name[0] == '(' and not OUTPUT_COMMENTS: # command is a comment
continue
# Now add the remaining parameters in order
@@ -326,10 +323,6 @@ def parse(pathobj):
# Check for Tool Change:
if command == 'M6':
continue
# 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:
@@ -349,4 +342,5 @@ def parse(pathobj):
return out
print(__name__ + " gcode postprocessor loaded.")

View File

@@ -142,7 +142,7 @@ def processArguments(argstring):
print ('here')
OUTPUT_DOUBLES = False
except:
except Exception:
return False
return True

View File

@@ -26,7 +26,7 @@ from PathScripts import PostUtils
# ***************************************************************************/
TOOLTIP='''
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
@@ -50,7 +50,7 @@ ToDo
'''
TOOLTIP_ARGS='''
TOOLTIP_ARGS = '''
Arguments for opensbp:
--comments ... insert comments - mostly for debugging
--inches ... convert output to inches
@@ -80,16 +80,20 @@ POST_OPERATION = ''''''
TOOL_CHANGE = ''''''
# to distinguish python built-in open function from the one declared below
if open.__module__ in ['__builtin__','io']:
if open.__module__ in ['__builtin__', 'io']:
pythonopen = open
CurrentState = {}
def getMetricValue(val):
return val
def getImperialValue(val):
return val / 25.4
GetValue = getMetricValue
@@ -110,7 +114,6 @@ def export(objectslist, filename, argstring):
if arg == '--no-show-editor':
SHOW_EDITOR = False
for obj in objectslist:
if not hasattr(obj, "Path"):
s = "the object " + obj.Name
@@ -333,7 +336,6 @@ 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.
@@ -356,7 +358,7 @@ def parse(pathobj):
elif command[0] == '(':
output += "' " + command + "\n"
else:
print("I don't know what the hell the command: ",end='')
print("I don't know what the hell the command: ", end='')
print(command + " means. Maybe I should support it.")
return output

View File

@@ -49,13 +49,14 @@ Many other OpenSBP commands not handled
from __future__ import print_function
import FreeCAD
import PathScripts.PathUtil as PathUtil
import os, Path
import os
import Path
AXIS = 'X','Y','Z','A','B' #OpenSBP always puts multiaxis move parameters in this order
SPEEDS = 'XY','Z','A','B'
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__ in ['__builtin__','io']:
if open.__module__ in ['__builtin__', 'io']:
pythonopen = open
@@ -63,10 +64,10 @@ 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)
insert(filename, doc.Name)
def insert(filename,docname):
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"
@@ -76,7 +77,7 @@ def insert(filename,docname):
gcode = parse(gcode)
doc = FreeCAD.getDocument(docname)
for subpath in gcode:
obj = doc.addObject("Path::Feature","Path")
obj = doc.addObject("Path::Feature", "Path")
path = Path.Path(subpath)
obj.Path = path
@@ -88,123 +89,121 @@ def parse(inputstring):
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
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:
for line in lines:
# remove any leftover trailing and preceding spaces
l = l.strip()
if not l:
line = line.strip()
if not line:
# discard empty lines
continue
if l[0] in ["'","&"]:
if line[0] in ["'", "&"]:
# discard comment and other non strictly gcode lines
if l[0:9] == "'New Path":
if line[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.
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 = [a.strip() for a in line.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
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
else: # feed move
s = "G1 "
speed = lastfeedspeed["XY"]
for i in range (1, len(words)):
if words [i] == '':
if last[AXIS[i-1]] == None:
for i in range(1, len(words)):
if words[i] == '':
if last[AXIS[i - 1]] is None:
continue
else:
s += AXIS[i-1] + last[AXIS[i-1]]
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'
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
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']:
if words[0][1] in ['X', 'Y']:
speed = lastrapidspeed["XY"]
else:
speed = lastrapidspeed[words[0][1]]
else: #feed move
else: # feed move
s = "G1 "
if words[0][1] in ['X','Y']:
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 PathUtil.keyValueIter(last):
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] == '':
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]
lastrapidspeed[SPEEDS[i - 1]] = words[i]
if words[0] in ["MD"]: #move distance with distance and angle.
#unsupported at this time
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
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] == '':
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
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:
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
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
if words[7] == "1": # CW
s = "G2"
else: #CCW
else: # CCW
s = "G3"
s += " X" + words[2] + " Y" + words[3] + " I" + words[4] + " J" + words[5] + " F" + str(lastfeedspeed["XY"])
output += s + '\n'
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):
# 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.")
print(__name__ + " gcode preprocessor loaded.")

View File

@@ -22,7 +22,14 @@
# ***************************************************************************/
from __future__ import print_function
TOOLTIP='''
import argparse
import datetime
from PathScripts import PostUtils
import FreeCAD
from FreeCAD import Units
import shlex
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
@@ -33,13 +40,6 @@ import smoothie_post
smoothie_post.export(object,"/path/to/file.ncc","")
'''
import argparse
import datetime
from PathScripts import PostUtils
import FreeCAD
from FreeCAD import Units
import shlex
now = datetime.datetime.now()
parser = argparse.ArgumentParser(prog='linuxcnc', add_help=False)
@@ -58,7 +58,7 @@ parser.add_argument('--IP_ADDR', help='IP Address for machine target machine')
parser.add_argument('--verbose', action='store_true', help='verbose output for debugging, default="False"')
parser.add_argument('--inches', action='store_true', help='Convert output for US imperial mode (G20)')
TOOLTIP_ARGS=parser.format_help()
TOOLTIP_ARGS = parser.format_help()
# These globals set common customization preferences
OUTPUT_COMMENTS = True
@@ -108,9 +108,10 @@ TOOL_CHANGE = ''''''
# to distinguish python built-in open function from the one declared below
if open.__module__ in ['__builtin__','io']:
if open.__module__ in ['__builtin__', 'io']:
pythonopen = open
def processArguments(argstring):
global OUTPUT_HEADER
global OUTPUT_COMMENTS
@@ -125,7 +126,6 @@ def processArguments(argstring):
global UNIT_SPEED_FORMAT
global UNIT_FORMAT
try:
args = parser.parse_args(shlex.split(argstring))
@@ -159,11 +159,12 @@ def processArguments(argstring):
IP_ADDR = args.IP_ADDR
VERBOSE = args.verbose
except:
except Exception:
return False
return True
def export(objectslist, filename, argstring):
processArguments(argstring)
global UNITS
@@ -181,13 +182,13 @@ def export(objectslist, filename, argstring):
# sure we're using the current values in the Machine Def.
myMachine = None
for pathobj in objectslist:
if hasattr(pathobj,"MachineName"):
if hasattr(pathobj, "MachineName"):
myMachine = pathobj.MachineName
if hasattr(pathobj, "MachineUnits"):
if pathobj.MachineUnits == "Metric":
UNITS = "G21"
UNITS = "G21"
else:
UNITS = "G20"
UNITS = "G20"
if myMachine is None:
FreeCAD.Console.PrintWarning("No machine found in this selection\n")
@@ -258,68 +259,71 @@ def sendToSmoothie(IP_ADDR, GCODE, fname):
global VERBOSE
fname = os.path.basename(fname)
FreeCAD.Console.PrintMessage ('sending to smoothie: {}\n'.format(fname))
FreeCAD.Console.PrintMessage('sending to smoothie: {}\n'.format(fname))
f = GCODE.rstrip()
filesize= len(f)
filesize = len(f)
# make connection to sftp server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(4.0)
s.connect((IP_ADDR, 115))
tn= s.makefile(mode='rw')
tn = s.makefile(mode='rw')
# read startup prompt
ln= tn.readline()
if not ln.startswith("+") :
ln = tn.readline()
if not ln.startswith("+"):
FreeCAD.Console.PrintMessage("Failed to connect with sftp: {}\n".format(ln))
sys.exit();
sys.exit()
if VERBOSE: print("RSP: " + ln.strip())
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("+") :
ln = tn.readline()
if not ln.startswith("+"):
FreeCAD.Console.PrintError("Failed to create file: {}\n".format(ln))
sys.exit();
sys.exit()
if VERBOSE: print("RSP: " + ln.strip())
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("+") :
ln = tn.readline()
if not ln.startswith("+"):
FreeCAD.Console.PrintError("Failed: {}\n".format(ln))
sys.exit();
sys.exit()
if VERBOSE: print("RSP: " + ln.strip())
if VERBOSE:
print("RSP: " + ln.strip())
cnt= 0
cnt = 0
# now send file
for line in f.splitlines(1):
tn.write(line)
if VERBOSE :
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("+") :
ln = tn.readline()
if not ln.startswith("+"):
FreeCAD.Console.PrintError("Failed to save file: {}\n".format(ln))
sys.exit();
sys.exit()
if VERBOSE: print("RSP: " + ln.strip())
if VERBOSE:
print("RSP: " + ln.strip())
# exit
tn.write("DONE\n")
tn.flush()
ln= tn.readline()
tn.close()
FreeCAD.Console.PrintMessage("Upload complete\n")
@@ -332,12 +336,13 @@ def linenumber():
return "N" + str(LINENR) + " "
return ""
def parse(pathobj):
global PRECISION
out = ""
lastcommand = None
global SPINDLE_SPEED
precision_string = '.' + str(PRECISION) +'f'
precision_string = '.' + str(PRECISION) + 'f'
# params = ['X','Y','Z','A','B','I','J','K','F','S'] #This list control
# the order of parameters
@@ -373,10 +378,10 @@ def parse(pathobj):
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
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_SPEED_FORMAT)), precision_string ) )
param + format(float(speed.getValueAs(UNIT_SPEED_FORMAT)), precision_string))
elif param == 'T':
outstring.append(param + str(c.Parameters['T']))
elif param == 'S':
@@ -385,8 +390,7 @@ def parse(pathobj):
else:
pos = Units.Quantity(c.Parameters[param], FreeCAD.Units.Length)
outstring.append(
param + format(float(pos.getValueAs(UNIT_FORMAT)), precision_string) )
#param + format(c.Parameters[param], precision_string))
param + format(float(pos.getValueAs(UNIT_FORMAT)), precision_string))
if command in ['G1', 'G01', 'G2', 'G02', 'G3', 'G03']:
outstring.append('S' + str(SPINDLE_SPEED))
@@ -413,7 +417,7 @@ def parse(pathobj):
# append the line to the final output
for w in outstring:
out += w + COMMAND_SPACE
out += w + COMMAND_SPACE
out = out.strip() + "\n"
return out