cam - CAM/GCode package¶
cam.gcode¶
A G-code generator that is suitable for a four axis (or 3.5 axis) machine with X, Y, and Z axes along with an angular A axis that rotates about the Z axis. It is more general but that’s the machine I have and the code might reflect that.
The generated G code is currently intended for a LinuxCNC interpreter, but probably works fine for others as well.
-
class
cam.gcode.PreviewPlotter[source]¶ Base interface that can be implemented by users of the GCode class to provide a graphical preview of the G-code output.
See
cam.gcodesvgfor an example of an SVG implemention.-
plot_move(endp)[source]¶ Plot G00 - rapid move from current tool location to to
endp.Parameters: endp – Endpoint of move as a 4-tuple (x, y, z, a).
-
plot_feed(endp)[source]¶ Plot G01 - linear feed from current tool location to
endp.Parameters: endp – Endpoint of feed as a 4-tuple (x, y, z, a).
-
-
class
cam.gcode.GCodeGenerator(xyfeed, zsafe, zfeed=None, afeed=None, output=None, plotter=None)[source]¶ GCode generator class that describes a basic two axis (XY), three axis (XYZ), or four axis (XYZA) machine. The G code output is compatible with LinuxCNC.
Angles are always specified in radians but output as degrees.
Axis values are always specified in user/world coordinates and output as machine units (ie inches or millimeters) using
GCode.unit_scaleas the scaling factor.Parameters: - xyfeed – Default feed rate along X and Y axes, in machine units per minute.
- zsafe – The safe height of the Z axis for rapid XY moves.
- zfeed – Feed rate along Z axis in machine units per minute. (Defaults to xyfeed.)
- afeed – Feed rate along A axis in degrees per minute. (Defaults to xyfeed.)
- output – Output stream for generated G code.
Must implement
write()method. Defaults to a StringIO if None (default). - plotter – Preview plotter. Should be a subclass of
gcode.PreviewPlotter.
-
TARGET= u'linuxcnc'¶ Current machine target
-
xyfeed= None¶ Feed rate along X and Y axes
-
zsafe= None¶ Z axis safe height for rapid moves
-
line_number= None¶ Current line number
-
unit_scale= None¶ User to machine unit scale
-
tolerance= None¶ Tolerance for float comparisons
-
angle_tolerance= None¶ Tolerance for angle comparisons
-
tool_wait_down= None¶ Delay time in millis for tool-down
-
tool_wait_up= None¶ Delay time in millis for tool-up
-
alt_tool_up= None¶ Alternate G code for Tool Up
-
alt_tool_down= None¶ Alternate G code for Too Down
-
spindle_wait_on= None¶ Default delay time in milliseconds after spindle is turned on.
-
spindle_wait_off= None¶ Default delay time in milliseconds after spindle is shut off.
-
spindle_clockwise= None¶ Spindle direction flag
-
spindle_speed= None¶ Default spindle speed
-
spindle_auto= None¶ Turn spindle on/off automatically on tool_up/tool_down
-
wrap_angles= None¶ Angles < 360 ?
-
show_comments= None¶ Show comments if True
-
show_line_numbers= None¶ Show line numbers if True
-
header_comments= None¶ Extra header comments
-
blend_mode= None¶ Blend mode. Can be None, ‘blend’, or ‘exact’.
-
blend_tolerance= None¶ Blend tolerance. P value for G64 blend directive.
-
blend_qtolerance= None¶ Naive cam detector tolerance value. Q value for G64 blend directive.
-
verbose= None¶ Output code comments
-
zfeed= None¶ Z axis feed rate
-
afeed= None¶ Angular axis feed rate
-
output= None¶ The G code output stream
-
preview_plotter= None¶ The current preview plotter
-
units¶ GCode output units. Can be ‘in’ or ‘mm’.
-
X¶ The current X axis value or none if unknown.
-
Y¶ The current Y axis value or none if unknown.
-
Z¶ The current Z axis value or none if unknown.
-
A¶ The current A axis value or none if unknown.
-
set_tolerance(tolerance, angle_tolerance=None)[source]¶ Set tolerance (epsilon) for floating point comparisons.
Parameters: - tolerance – The tolerance for scalar floating point comparisons except angular values.
- angle_tolerance – The tolerance for comparing angle values. Set to
toleranceif None (default).
-
set_output_precision(precision)[source]¶ Set numeric output precision. This determines the number of digits after the decimal point.
This can be different from the precision implied by the tolerance value. The default is derived from the tolerance value.
Parameters: precision – The number of digits after the decimal point.
-
set_units(units, unit_scale=1.0)[source]¶ Set G code units and unit scale factor.
Note
Linear axis values are specified in user/world coordinates and output as machine units (ie inches or millimeters) using
unit_scaleas the scaling factor to scale from user/world units to G-code units.Parameters: - units – Unit specifier. Must be ‘in’ or ‘mm’.
- unit_scale – Scale factor to apply to linear axis values. Default is 1.0.
-
set_spindle_defaults(speed, clockwise=True, wait_on=0, wait_off=0, auto=False)[source]¶ Set spindle parameter defaults.
Parameters: - speed – Spindle speed in RPM
- clockwise – Spindle direction. True if clockwise (default).
- wait_on – Number of milliseconds to wait for the spindle to reach full speed.
- wait_off – the number of milliseconds to wait for the spindle to stop.
- auto – Turn on/off spindle automatically on
tool_up()/tool_down(). Default is False.
-
set_path_blending(mode, tolerance=None, qtolerance=None)[source]¶ Set path trajectory blending mode and optional tolerance.
Parameters: - mode – Path blending mode. Can be ‘exact’ or ‘blend’. Uses G64 in ‘blend’ mode and G61 in ‘exact’ mode.
- tolerance – Blending tolerance. Only used in ‘blend’ mode. This is the value for the G64 P parameter. Default is None.
- qtolerance – Naive cam detector tolerance value. This is the value for the G64 Q parameter. Default is None.
-
set_axis_offset(**kwargs)[source]¶ Set the offset for the specified axes.
Axis offsets are always specified in machine units. Angular offsets are always in degrees.
This is a ‘soft’ offset, not a G92 offset. The offset value will be added to the current axis value when a move is performed.
Example:
gcode_gen = gcode.GCodeGenerator(...) gcode_gen.set_axis_offset(x=10, y=10)
Parameters: - x – X axis offset value (optional)
- y – Y axis offset value (optional)
- z – Z axis offset value (optional)
- a – A axis offset value (optional)
-
set_axis_scale(**kwargs)[source]¶ Set the scaling factors for the specified axes. The scaling is applied before the world/machine unit scaling.
Example:
gcode_gen = gcode.GCodeGenerator(...) gcode_gen.set_axis_scale(x=10, y=10)
Parameters: - x – X axis scale value (optional)
- y – Y axis scale value (optional)
- z – Z axis scale value (optional)
- a – A axis scale value (optional)
-
map_axis(canonical_name, output_name)[source]¶ Map canonical axis names to G code output names.
Mapping can be used to accommodate machines that expect different axis names (ie. using C instead of A or UVW instead of XYZ).
Parameters: - canonical_name – Canonical axis name. (ie ‘X’, ‘Y’, ‘Z’, or ‘A’)
- output_name – Output name. (ie ‘U’, ‘V’, ‘W’, or ‘C’)
-
add_header_comment(comment)[source]¶ Append a comment to the header section.
Parameters: comment – A comment or list of comments.
-
comment(comment=None, use_semi=True)[source]¶ Write a G code comment line.
Outputs a newline if the comment string is None (default).
Parameters: - comment – A comment string or a list (or tuple) of comment strings. In the case of multiple comments, each one will be on a separate line.
- use_semi – Use the semicolon as a comment start character if True. Otherwise enclose the comment in parentheses.
-
header(comment=None)[source]¶ Output a pretty standard G code file header.
Parameters: comment – A header comment or a list of comments (optional).
Output a generic G code file footer.
-
feed_rate(feed_rate)[source]¶ Set the specified feed rate. Outputs the F G code directive if the feed rate has changed since the last feed value.
Parameters: feed_rate – The feed rate in machine units per minute.
-
pause(conditional=False, comment=u'Pause')[source]¶ Pause the G code interpreter.
Outputs M1 or M0 G code.
Note
Normally, pressing the start button in LinuxCNC/Axis will restart the interpreter after a pause.
Parameters: - conditional – use conditional stop if True.
- comment – Optional comment string.
-
dwell(milliseconds, comment=None)[source]¶ Output a dwell command which pauses the tool for the specified number of milliseconds.
Parameters: - milliseconds – Number of milliseconds to pause.
- comment – Optional comment string.
-
tool_up(rapid=True, wait=None, comment=None)[source]¶ Moves tool to a safe Z axis height. This should be called before performing a rapid move.
The spindle will also be automatically shut off if
Gcode.spindle_autois True.Parameters: - rapid – Use G0 to move Z axis, otherwise G1 at current feed rate. Default is True.
- wait – the number of milliseconds to wait for the tool to retract. Uses GCode.tool_wait_up value by default if None specified. This parameter is mainly useful for pneumatically controlled up/down axes where the actuator may take a few milliseconds to extend/retract.
- comment – Optional comment string.
-
tool_down(z, feed=None, wait=None, comment=None)[source]¶ Moves tool on Z axis down to specified height. Outputs a G1 move command using the current feed rate for the Z axis.
The spindle will be automatically turned on first if
Gcode.spindle_autois True.Parameters: - z – Height of Z axis to move to.
- feed – Feed rate (optional - default Z axis feed rate used if None.)
- wait – the number of milliseconds to wait for the tool to actually get to the specified depth. Uses GCode.tool_wait_down value by default if None specified. This parameter is mainly useful for pneumatically controlled up/down axes where the actuator may take a few milliseconds to extend/retract.
- comment – Optional comment string.
-
spindle_on(speed=None, clockwise=None, wait=None, comment=None)[source]¶ Turn on the spindle.
Parameters: - speed – Spindle speed in RPM. If None use default speed.
- clockwise – Spindle turns clockwise if True. If None use default value.
- wait – Number of milliseconds to wait for the spindle to reach
full speed. Uses
GCode.spindle_wait_onvalue by default. - comment – Optional comment string.
-
spindle_off(wait=None, comment=None)[source]¶ Turn off the spindle.
Parameters: - wait – the number of milliseconds to wait for the spindle
to stop. Uses
GCode.spindle_wait_offvalue by default. - comment – Optional comment string.
- wait – the number of milliseconds to wait for the spindle
to stop. Uses
-
normalize_axis_angle(axis=u'A')[source]¶ Unwrap (normalize) a rotational axis. If the current angular position of the axis is > 360 this will reset the rotary axis origin so that 0 < angle < 360.
Useful when cutting large spirals with a tangent knife to minimize long unwinding moves between paths.
Parameters: axis – Name of axis to unwrap. Default is ‘A’.
-
rapid_move(x=None, y=None, z=None, a=None, comment=None)[source]¶ Perform a rapid G0 move to the specified location.
At least one axis should be specified. If the tool is below the safe ‘Z’ height it will be raised before the rapid move is performed.
Parameters: - x – X axis value (optional)
- y – Y axis value (optional)
- z – Z axis value (optional)
- a – A axis value (optional)
- comment – Optional comment string.
-
feed(x=None, y=None, z=None, a=None, feed=None, comment=None)[source]¶ Perform a G1 linear tool feed to the specified location.
At least one axis should be specified.
Parameters: - x – X axis value (optional)
- y – Y axis value (optional)
- z – Z axis value (optional)
- a – A axis value (optional)
- feed – Feed rate (optional - default feed rate used if None)
- comment – Optional comment string.
-
feed_arc(clockwise, x, y, arc_x, arc_y, a=None, z=None, feed=None, comment=None)[source]¶ Perform a G2/G3 arc feed.
This will raise a GCodeException if the beginning and ending arc radii do not match, ie if one of the end points does not lie on the arc.
Parameters: - clockwise – True if the arc moves in a clockwise direction.
- x – X value of arc end point
- y – Y value of arc end point
- arc_x – Center of arc relative to
x - arc_y – Center of arc relative to
y - a – A axis value at endpoint (in radians)
- feed – Feed rate (optional - default feed rate used if None)
- comment – Optional comment string.
-
get_current_position_xy()[source]¶ The last known tool position on the XY plane.
Returns: A 2-tuple containing coordinates of X and Y axes of the form (X, Y). An axis value will be None if the position is unknown.
-
get_current_position()[source]¶ The last known tool position.
Returns: A 4-tuple containing coordinates of all four axes of the form (X, Y, Z, A). An axis value will be None if the position is unknown.
-
position(axis)[source]¶ The current position of the specified axis.
Parameters: axis – The axis name - i.e. ‘X’, ‘Y’, ‘Z’, ‘A’, etc. Returns: The current position of the named axis as a float value.
-
gcode_command(command, **kwargs)[source]¶ Output a line of gcode.
This is mainly for internal use and should be used with extreme caution. Use the higher level methods if at all possible.
Parameters: - command – G code command. Required.
- params – Parameter string that will be output as is. This must not be used with commands that that may change the position of the machine. Optional.
- X – The X axis value. Optional.
- Y – The Y axis value. Optional.
- Z – The Z axis value. Optional.
- I – Center (x) of arc relative to X,Y. Optional.
- J – Center (y) of arc relative to X,Y. Optional.
- R – Arc radius. Optional.
- A – The A axis value in radians. Optional.
- force_value – A string containing the modal parameter names whose values will be output regardless of whether their values have changed. By default if the specified value of a modal parameter has not changed since its last value then it will not be output.
- comment – Optional inline comment string.
Raises:
cam.simplecam¶
Simple G code generation from basic 2D geometry.
-
class
cam.simplecam.SimpleCAM(gcode_gen)[source]¶ Simple 2D CAM library that converts line/arc path geometry into G code suitable for a straightforward 2.5 axis machine with an optional fourth angular axis (A) that rotates about the Z axis. The fourth axis position is always tangential to the movement along the X and Y axes. This is usually called a tangential tool (ie a knife or a brush).
Since the path geometry is two dimensional the Z and A axes are calculated automatically. By default the Z axis value is determined by the current plunge depth and the A axis value is the tangent normal of the current segment.
These defaults can be overridden by assigning extra attributes to the segment.
Segment attributes:
- inline_end_z: The Z axis value at the end of the segment.
- inline_start_a: The A axis value at the start of the segment.
- inline_end_a: The A axis value at the start of the segment.
- inline_ignore_a: Boolean. True if the A axis is not to be
- rotated for the length of the segment.
Parameters: gcode_gen – a cam.gcode.GCodeGeneratorinstance-
generate_gcode(path_list)[source]¶ Generate G code from tool paths.
Parameters: path_list – A list of drawing paths. Where a drawing path is a sequential collection of bezier.CubicBezier, geom.Line, or geom.Arc segments. Other shape types will be silently ignored…
-
preprocess_paths(path_list)[source]¶ Preprocess paths. Sort order will be maintained.
Parameters: path_list – A list of drawing paths. Where a drawing path is a sequential collection of bezier.CubicBezier, geom.Line, or geom.Arc objects. Returns: A new list of tool paths.
-
path_biarc_approximation(path)[source]¶ Convert all cubic bezier curves in the drawing path to biarcs (tangentially connected circular arcs).
Parameters: - path – A drawing path; an iterable collection of
- geom.Line, or geom.Arc objects. (bezier.CubicBezier,) –
Returns: A new drawing path containing only geom.Line and geom.Arc objects.
Raises: CAMException– If the path contains anything other than CubicBezier, Line, or Arc segments.
-
plunge(depth, path)[source]¶ Bring the tool down to the current working depth.
This can be subclassed to generate custom plunge profiles.
-
generate_rapid_move(path)[source]¶ Generate G code for a rapid move to the beginning of the tool path.
-
sort_paths(path_list, sort_method=u'optimize')[source]¶ Sort the tool paths to minimize tool movements. This will try to sort the tool paths to minimize tool travel between the end of one path and the start of the next path.
Parameters: - path_list – A list of tool paths.
- sort_method – Sorting strategy.
Returns: A sorted list of paths.
cam.toolpath¶
-
class
cam.toolpath.Toolpath[source]¶ A Toolpath is an ordered list of Line and Arc segments.
-
biarc_approximation(path, tolerance, max_depth, line_flatness)[source]¶ Append the path while converting all cubic bezier curves to biarcs (tangentially connected circular arcs).
Parameters: - path – An iterable collection of bezier.CubicBezier, geom.Line, or geom.Arc objects.
- tolerance – Approximation tolerance. A lower value increases accuracy at the cost of time and number of generated biarc segments.
- max_depth – Maximum recursion depth. This limits how many times the Bezier curve can be subdivided.
- line_flatness – Segments flatter than this value will be converted to straight line segments instead of arcs with huge radii. Generally this should be a small value (say <= 0.01) to avoid path distortions.
Raises: ToolpathException– If the path contains anything other than CubicBezier, Line, or Arc segments.
-
cam.util¶
-
cam.util.split_path_g1(path)[source]¶ Split the path at path vertices that connect non-tangential segments.
Parameters: path – The path to split. Returns: A list of one or more paths.
-
cam.util.copy_segment_attrs(seg1, seg2)[source]¶ Copy inline GCode rendering hints from seg1 to seg2.
cam.fillet¶
Connect Line/Arc segments with a fillet arc.
-
cam.fillet.fillet_path(path, radius, fillet_close=True, adjust_rotation=False, mark_fillet=False)[source]¶ Attempt to insert a circular arc of the specified radius to blend adjacent path segments that have C0 or G0 continuity.
Parameters: - path – a list of geom.Line or geom.Arc segments.
- fillet_close – If True and the path is closed then add a terminating fillet. Default is False.
- adjust_rotation – If True adjust the A axis rotation hints to compensate for the offset caused by the fillet.
- mark_fillets – If True add an attribute to the fillet arc to mark it to ignore G1. Default is False.
Returns: A new path with fillet arcs. If no fillets are created then the original path will be returned.
-
cam.fillet.create_adjusted_fillet(seg1, seg2, radius, adjust_rotation=False, mark_fillet=False)[source]¶ Try to create a fillet between two segments. Any GCode rendering hints attached to the segments will be preserved.
Parameters: - seg1 – First segment, an Arc or a Line.
- seg2 – Second segment, an Arc or a Line.
- radius – Fillet radius.
- adjust_rotation – If True adjust the A axis rotation hints to compensate for the offset caused by the fillet.
- mark_fillets – If True add an attribute to the fillet arc to mark it to ignore G1. Default is False.
Returns: A tuple containing the adjusted segments and fillet arc (seg1, fillet_arc, seg2), or an empty tuple if the segments cannot be connected with a fillet arc (either they are too small, already G1 continuous, or are somehow degenerate.)
cam.offset¶
Offset Line/Arc segments in a tool path to compensate for tool trail offset.
-
cam.offset.offset_path(path, offset, min_arc_dist, g1_tolerance=None)[source]¶ Recalculate path to compensate for a trailing tangential offset. This will shift all of the segments by offset amount. Arcs will be recalculated to correct for the shift offset.
Parameters: - path – The path to recalculate.
- offset – The amount of tangential tool trail.
- min_arc_dist – The minimum distance between two connected segment end points that can be bridged with an arc. A line will be used if the distance is less than this.
- g1_tolerance – The angle tolerance to determine if two segments are g1 continuous.
Returns: A new path
Raises: cam.toolpath.ToolpathException– if the path contains segment types other than Line or Arc.
-
cam.offset.smoothing_arcs(seg1, seg2, cp1=None, tolerance=0.0001, line_flatness=0.0001, max_depth=1, match_arcs=True)[source]¶ Create circular smoothing biarcs between two segments that are not currently G1 continuous.
Parameters: - seg1 – First path segment containing first and second points. Can be a geom.Line or geom.Arc.
- seg2 – Second path segment containing second and third points. Can be a geom.Line or geom.Arc.
- cp1 – Control point computed from previous invocation.
- tolerance – Biarc matching tolerance.
- line_flatness – Curve to line tolerance.
- max_depth – Max Bezier subdivision recursion depth.
- match_arcs – Attempt to more closely match existing arc segments. Default is True.
Returns: A tuple containing a list of biarc segments and the control point for the next curve.