Skip to content

Instantly share code, notes, and snippets.

@lava
Last active April 4, 2019 17:42
Show Gist options
  • Select an option

  • Save lava/84a58f84f811fbdab063d7cb5ea5148b to your computer and use it in GitHub Desktop.

Select an option

Save lava/84a58f84f811fbdab063d7cb5ea5148b to your computer and use it in GitHub Desktop.
Postprocessing script to make FreeCAD paths importible by Easel (WIP)
# ***************************************************************************
# * (c) Benno Evers (bennoe@apache.org) 2019 *
# * *
# * 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 post-processor for the Easel WebUI which can control various
models of CNC mills, i.e. Carvey, X-Carve and ShapeOko 1/2.
Note that it has only been tested with the Carvey.
Its main task is to linearize any arcs, since Easel only
supports linear movements.
'''
import datetime
import FreeCAD
import Part
import PathScripts.PostUtils as PostUtils
def export(objectslist, filename, argstring):
"Called when freecad exports a list of objects"
# TODO(bevers): Support multiple paths by concatenating them together.
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")
return
# The `Path.toGCode()` function returns a string formatted in the FreeCAD
# internal GCode dialect
#freecad_gcode = obj.Path.toGCode()
easel_gcode = postprocess(obj.Path.Commands)
dia = PostUtils.GCodeEditorDialog()
dia.editor.setText(easel_gcode)
result = dia.exec_()
gfile = open(filename, "w")
gfile.write(easel_gcode)
gfile.close()
return result
def linearize_arc(start_dict, end_dict, center_dict, clockwise):
result = "; {} arc from {} to {}\n; around center point {}\n".format(
"Clockwise" if clockwise else "Counter-clockwise",
start_dict,
end_dict,
center_dict)
start = FreeCAD.Vector(start_dict['X'], start_dict['Y'], start_dict['Z'])
end = FreeCAD.Vector(end_dict['X'], end_dict['Y'], end_dict['Z'])
center = FreeCAD.Vector(center_dict['X'], center_dict['Y'], center_dict['Z'])
if clockwise:
start, end = end, start
radius = (center - start).Length
normal = (center - start).cross(center - end)
# Special case: If the circle is under-specified (i.e. 180 or 360 degree angles),
# we construct the normal
# This ensures we're getting the z-axis as normal when start and center lie in the same z-plane.
# This will break for circles on the xz or yz planes, but these don't make physical sense on a CNC mill.
# TODO: Warn if we hit this condition.
if (normal.Length == 0.):
to_center = center - start
reference = FreeCAD.Vector(to_center.y, -to_center.x, to_center.z)
normal = to_center.cross(reference)
normal.normalize()
# TODO: Looks like we need to switch to the 3-point form to
# reliably handle semi-circles and such.
circle = Part.Circle(center, normal, radius)
p0 = circle.parameter(start)
p1 = circle.parameter(end)
arc = Part.ArcOfCircle(circle, p0, p1)
steps = 64 # TODO: make number of steps configurable
points = arc.discretize(steps)
c = []
for p in points:
c.append("G1 X{} Y{} Z{}\n".format(p.x, p.y, p.z))
if clockwise:
c.reverse()
return result + "".join(c) + "\n"
# `gcode`: [FreeCAD...Command]
def postprocess(commands):
output = "; Generated by FreeCAD Easel post-processor.\n"
output += "G21 ; Metric units\n" # FreeCAD internal values are always metric.
# Currently supported internal commands:
# G0, G1, G2, G3 (movement commands)
# G81, G82, G83 (drilling commands)
# G90, G91 (absolute/relative coordinates)
# Carvey starts at (20mm, 20mm, 20mm) after smart-clamp calibration.
# TODO: Check if this is different for the other easel-supported machines.
state = {'X': 20., 'Y': 20., 'Z': 20.}
for cmd in commands:
if cmd.Name[0] == "(":
output += "; " + cmd.Name + "\n"
elif cmd.Name == "G0" or cmd.Name == "G1":
argnames = cmd.Parameters.keys()
if 'A' in argnames or 'B' in argnames or 'C' in argnames:
raise RuntimeError("A,B,C rotational axes currently not supported.")
if 'X' in argnames:
state['X'] = float(cmd.Parameters['X'])
if 'Y' in argnames:
state['Y'] = float(cmd.Parameters['Y'])
if 'Z' in argnames:
state['Z'] = float(cmd.Parameters['Z'])
# TODO: Is it important to omit duplicate coordinates?
output += "{} X{} Y{} Z{}\n".format(cmd.Name, state['X'], state['Y'], state['Z'])
elif cmd.Name == "G2" or cmd.Name == "G3":
argnames = cmd.Parameters.keys()
if 'A' in argnames or 'B' in argnames or 'C' in argnames:
raise RuntimeError("A,B,C rotational axes currently not supported.")
center_x = state['X'] + cmd.Parameters['I']
center_y = state['Y'] + cmd.Parameters['J']
center_z = state['Z']
if 'K' in argnames: # 'K' is optional
center_z = state['Z'] + cmd.Parameters['K']
# Update final position
start_position = dict(state)
end_position = dict(state)
if 'X' in argnames:
end_position['X'] = float(cmd.Parameters['X'])
if 'Y' in argnames:
end_position['Y'] = float(cmd.Parameters['Y'])
if 'Z' in argnames:
end_position['Z'] = float(cmd.Parameters['Z'])
clockwise = cmd.Name == "G2"
center = {'X': center_x, 'Y': center_y, 'Z': center_z}
output += linearize_arc(start_position, end_position, center, clockwise)
state = end_position
elif cmd.Name == "G81" or cmd.Name == "G82" or cmd.Name == "G83":
raise RuntimeError("Drilling commands (G8x) currently not supported.")
elif cmd.Name == "G90":
output += "G90 ; Absolute coordinate mode\n"
elif cmd.Name == "G91":
raise RuntimeError("Relative coordinate mode (G91) currently not supported.")
return output
print(__name__ + " gcode postprocessor loaded.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment