simCNC - Python Scripting Guide (3.604)

Created by CS-Lab Support, Modified on Mon, 23 Nov at 8:14 AM by Andrzej Rogozynski

Python scripting in simCNC 3.604: macros, PyActions, the script editor, examples and the complete function reference.

Contents

About this edition This guide replaces the "simCNC - Guide To Python Scripts" from 2020/2022. It is checked against simCNC 3.604. All 43 functions of the old guide still work unchanged. New in this edition: the scripting rules (chapter 3), dialogs, I/O by signal, homing, soft limits, G-code from scripts, tool wear, overrides, parameters, and a complete function reference (appendix A).

1 Introduction

simCNC uses Python as its script language. Scripts automate machine sequences such as tool change, tool length measurement, probing, or anything that reacts to inputs and machine events.

How it works

  • Python 3.13 is installed together with simCNC; nothing has to be installed separately.
  • Every script runs in its own Python process and talks to simCNC through a local network connection. The connection is handled by the library files in the profile's scripts folder (___COMM.py, ___DEVICE.py, ___MSG.py, ...).
  • Two objects are ready in every script, without any import:
    • d – the machine: positions, motion, I/O, spindle, tools, offsets, program control.
    • msg – message boxes and questions for the operator.
  • All enumerations (Axis, CoordMode, SpindleState, ...) are available directly, too. Standard Python modules (time, sys, os, tkinter, ...) are imported as usual.
Do not edit the library files simCNC restores ___*.py in the profile's scripts folder at every start. Changes to these files are lost. Put your own code in your own scripts.

A first script

pos = d.getPosition(CoordMode.Machine)
print("Machine position: X={:.3f} Y={:.3f} Z={:.3f}".format(pos[0], pos[1], pos[2]))
msg.info("Spindle tool: " + str(d.getSpindleToolNumber()), "Hello simCNC")

print() writes to the Python console of the script editor; msg.info() opens a message box for the operator.

2 Where scripts run

M-code macros

An M<n> in G-code or in the MDI line runs the script m<n>.py from the profile's scripts folder. The G-code program waits until the macro has finished. A new profile contains these default macros, which can be changed to suit the machine:

CodeDefault actionCodeDefault action
M0 / M1Stop; Start continues with the next lineM7Mist on
M2Program endM8Flood on
M3 / M4Spindle on CW / CCWM9Mist and flood off
M5Spindle offM30Program end and rewind
M6Tool change (numbers only, no motion)M150 / M151AutoLeveling off / on

New M-codes are added by creating a new script, e.g. m100.py for M100. A macro line takes no parameters (M100 P5 is an error), but T, S and F on the same line are applied before the macro runs (T5 M6). M47, M62, M63, M98 and M99 are built into simCNC and cannot be replaced by scripts.

PyActions

PyActions run a script automatically on an event. They are set up in the configuration window, tab PyActions. Available triggers:

TriggerRuns when
Start / Stop / Finished trajectorya program is started, stopped (STOP, E-stop, limit) or finished
Trajectory pause on / offthe program is paused or resumed
Timer / Fixed timeperiodically, or at a set time
I/O changean input or output changes: up, down, any change, or an analog value reaches a level
Parameter changea machine parameter changes
Controller enable / disablethe controller is enabled or disabled
CSMIO connectedthe connection to the controller is established
Spindle RPM alarm, Torch off alarmthe spindle speed or the plasma torch signal is lost
Screen reload finishedthe screen has been (re)loaded

A PyAction can also be started from a script: d.runPyAction("name").

The script editor

Open it with Macro → Show Script Editor. Macro → Stop all scripts stops every running script.

Script editor
Script editor (screenshot from an earlier version)
  1. Run the script.
  2. Stop the script.
  3. Stop trajectory – the same as STOP on the main screen.
  4. Clear console.
  5. Code editor.
  6. Python console: print() output, errors and exceptions.
  7. Script file name.
  8. Modified since the last save.
  9. Script state.

Ctrl + Space: code completion

Type d. and press Ctrl + Space for the list of functions. Typing the beginning of a name narrows the list. With the cursor in an empty argument, Ctrl + Space lists the possible values (e.g. FloodState.ON). Module functions (chapter 5) are not in the list.

All functions
Matching names
Argument values

External editors

Scripts can also be written and debugged in an external editor such as Visual Studio Code. See the knowledge base article "Running Python Scripts Outside simCNC (e.g., in VS Code)".

3 Rules every script must follow

Calls wait until they are finished

Functions that move the machine or change its state (moveToPosition, executeGCode, executeProbing, executeAxisHoming, setSpindleState, ...) return only when the action is complete. The next line of the script runs afterwards; no extra waiting is needed.

STOP ends the script immediately

A stopped script does not clean up When the operator presses STOP, an E-stop occurs or a hardware limit is hit, simCNC closes the script's Python process at once. The rest of the script does not run – not even a finally: block or an except handler.

Anything the script switched on stays on: d.ignoreAllSoftLimits(True), an output, G91 mode, a changed FRO. Restore such settings from a PyAction triggered by Stop trajectory and/or Controller disable:

# restore_after_stop.py - PyAction on "Stop trajectory" and "Controller disable"
d.ignoreAllSoftLimits(False)

Errors raise SimCncException

When a function cannot do what was asked, it raises SimCncException (for example waitForSpindleSetSpeed when the speed is not reached). A probing without contact is not an error: executeProbing returns False. Catch the exception where the script can react sensibly; an uncaught exception ends the script and is shown in the console.

import sys
try:
    d.moveAxisIncremental(Axis.Z, 50, 1000)
except SimCncException as ex:
    msg.err("Move failed: " + str(ex))
    sys.exit(1)

Units

  • Positions and distances: the display units of each axis (mm or inch, degrees for rotary axes).
  • Velocities: units per minute (mm/min, inch/min, deg/min).
  • Positions are lists of six values in the order X Y Z A B C; index 0 is X. Axis.X.value gives the index of an axis.

Machine coordinates or program coordinates

Most position functions take a CoordMode: CoordMode.Machine (machine coordinates, independent of offsets) or CoordMode.Program (work offset, G92 and tool offset applied).

4 Messages and questions

The msg object shows standard dialogs. The script waits until the operator closes them.

FunctionShowsReturns
msg.info(text, title="Info")information—
msg.wrn(text, title="Warning")warning—
msg.err(text, title="Error")error—
msg.askYesNo(text, title)Yes / No questionTrue for Yes
msg.askOkCancel(text, title)OK / Cancel questionTrue for OK
msg.askRetryCancel(text, title)Retry / Cancel questionTrue for Retry
import sys
if not msg.askYesNo("Is the tool setter in place?", "Tool measurement"):
    sys.exit(0)

d.closeAllMessageBoxes() closes all open message boxes.

Your own windows

tkinter is available for custom windows. This example shows the current XYZ feed rate:

from tkinter import Tk, Label

def update():
    value["text"] = "{:.0f}".format(d.getCurrentXYZVelocity())
    window.after(100, update)

window = Tk()
window.title("Velocity")
Label(window, text="Velocity =", font=("Arial", 12)).pack(side="left", padx=8, pady=20)
value = Label(window, font=("Arial", 12), width=8, anchor="e")
value.pack(side="left", padx=8)
update()
window.mainloop()
Axes stopped
Jogging

5 Inputs and outputs

Inputs and outputs are read in two ways: by signal (the function assigned in the configuration, e.g. "Probe 0") or directly by pin on a module. Reading by signal keeps the script working when the wiring changes.

Reading a signal

DSignalVal d.getDigitalIOSignalValue(IOFunctionId signalFunction, int index)

State of a configured digital signal: DSignalVal.signalActive or DSignalVal.signalInactive. The index selects the signal of that function (e.g. the probe number). Analog, angle, position and velocity signals have matching functions (getAnalogIOSignalValue, ...). The signal functions are listed in appendix B.

if d.getDigitalIOSignalValue(IOFunctionId.iofnProbe, 0) == DSignalVal.signalActive:
    msg.wrn("Probe 0 is already triggered", "Probing")

Modules

Module d.getModule(ModuleType type, int ID)  ·  Module d.getMainModule()  ·  List<Module> d.getModuleList()

A module object gives direct access to the pins of one device.

ModuleTypeDeviceID
IPCSMIO/IP-S, IP-A, IP-M controller (also d.getMainModule())0
IOCSMIO-IO extension module0–15
MPGCSMIO-MPG manual control module0
ENCCSMIO-ENC encoder / threading module0
DRVsimDrive servo drive0–5

Digital pins

DIOPinVal module.getDigitalIO(IOPortDir direction, int pin)  ·  void module.setDigitalIO(int pin, DIOPinVal value)

IOPortDir.InputPort / OutputPort; values DIOPinVal.PinSet (high) and DIOPinVal.PinReset (low). module.getDigitalIOs(direction) returns all pins at once, module.getDigitalIOCount(direction) the number of pins.

import time
ip = d.getMainModule()
if ip.getDigitalIO(IOPortDir.InputPort, 8) == DIOPinVal.PinSet:
    print("Input 8 is high")

io0 = d.getModule(ModuleType.IO, 0)          # first CSMIO-IO module
io0.setDigitalIO(5, DIOPinVal.PinSet)        # output 5 on
time.sleep(1)
io0.setDigitalIO(5, DIOPinVal.PinReset)      # output 5 off

Analog pins

float module.getAnalogIO(IOPortDir direction, int pin)  ·  void module.setAnalogIO(int pin, float volts)

Values in volts. CSMIO/IP analog inputs and outputs: 0–10 V, 12 bit. CSMIO-MPG analog inputs: 0–5 V, 12 bit.

ip = d.getMainModule()
print("Analog input 1 = {:.2f} V".format(ip.getAnalogIO(IOPortDir.InputPort, 1)))
ip.setAnalogIO(0, 5.0)                       # 5 V on analog output 0

Encoder inputs (CSMIO-ENC)

float module.getEncoderIOAngle(int channel)  ·  int module.getEncoderIOPosition(int channel)  ·  float module.getEncoderIORPM(int channel)

Angle (from the index signal), position (counts from the first index) and speed in RPM of an encoder channel.

enc = d.getModule(ModuleType.ENC, 0)
print("Channel 0: {:.1f} RPM, angle {:.1f}".format(enc.getEncoderIORPM(0), enc.getEncoderIOAngle(0)))

6 Positions and work offsets

Reading and setting positions

List<float>(6) d.getPosition(CoordMode coordMode)

Current position of all six axes.

void d.setAxisProgPosition(Axis axis, float value)

Sets the program position of an axis, like "zero axis" on the screen. simCNC does this by changing the current work offset.

pos = d.getPosition(CoordMode.Program)
for axis in (Axis.X, Axis.Y, Axis.Z):
    print("{} = {:.4f}".format(axis.name, pos[axis.value]))

d.setAxisProgPosition(Axis.Z, 0)        # the current point becomes Z0

Work offsets

simCNC has 256 work offsets. Index 1–6 are G54–G59, 7–256 are G59.1–G59.250.

FunctionDescription
d.getWorkOffsetNumber()index of the active work offset
d.setWorkOffsetNumber(index)switches the active work offset (like G54…)
d.getWorkOffset(index) / d.setWorkOffset(index, values)reads / writes the six values of a work offset
d.getCurrentWorkOffset() / d.setCurrentWorkOffset(values)the same for the active work offset
d.setWorkOffsetNumber(2)                # activate G55
offset = d.getWorkOffset(2)
offset[2] -= 0.5                        # move the Z origin of G55 0.5 mm down
d.setWorkOffset(2, offset)
print("G55 =", d.getWorkOffset(2))

7 Moving the machine

Moves

void d.moveAxisIncremental(Axis axis, float distance, float velocity)

Moves one axis by a distance from its current position.

void d.moveToPosition(CoordMode coordMode, List<float>(6) position, float velocity)

Moves all axes to a position; velocity is the resultant feed rate.

void d.parallelMoveToPosition(CoordMode coordMode, Axis axis, float position, float velocity)

Moves a single axis independently (parallel move) to a position.

# a 20 x 20 square from the current position, in program coordinates
pos = d.getPosition(CoordMode.Program)
for dx, dy in ((20, 0), (0, 20), (-20, 0), (0, -20)):
    pos[Axis.X.value] += dx
    pos[Axis.Y.value] += dy
    d.moveToPosition(CoordMode.Program, pos, 1000)

Running G-code from a script

void d.executeGCode(string line)  ·  void d.executeGCodeList(List<string> lines)

Runs G-code like the MDI line and waits until it is finished.

d.executeGCode("G90 G0 Z10")
d.executeGCodeList(["G91", "G1 X10 F500", "G90"])
Tip Prefer the d.move... functions to G91 moves. If a script with G91 is stopped half way, the machine stays in incremental mode (chapter 3).

Homing

d.executeAxisHoming(Axis.Z)             # Z first ...
d.executeAxisHoming(Axis.X)             # ... then X
if not d.isAxisReferenced(Axis.X):
    msg.err("X is not referenced")

d.executeHoming() homes all axes as configured (like "Ref all").

Machine state

FunctionDescription
d.getState()State.EStop, Idle, Homing, Trajectory, JOG, MDI, MPG
d.isConnected()True when simCNC is connected to the controller
d.enableMachine(enable)enables or disables the controller
d.getCurrentXYZVelocity()current resultant XYZ velocity (units/min)
d.getCurrentAxisVelocity(axis)current velocity of one axis (units/min)
d.waitForZeroVelocity(timeout)waits until the axes stand still

Soft limits

d.setSoftLimitsState(Axis.Z, True)
print("Z max:", d.getSoftLimitValue(Direction.Positive, Axis.Z))

d.ignoreAllSoftLimits(True)             # e.g. for a measurement beyond the limits
# ... moves ...
d.ignoreAllSoftLimits(False)
Always switch the soft limits back on If the script is stopped while soft limits are ignored, they stay ignored until switched on again or simCNC is restarted. Use a PyAction on Stop trajectory (chapter 3). Hardware limit switches cannot be switched off from Python.

8 Probing

bool d.executeProbing(CoordMode coordMode, List<float>(6) position, int probeIndex, float velocity)

Moves towards position until the probe triggers. Returns True on contact, False if the end position was reached without contact. probeIndex is the probe number from the special I/O configuration (0–3, like G31…G31.3). The probe input must not also be a hardware limit.

List<float>(6) d.getProbingPosition(CoordMode coordMode)

The contact position of the last probing (or the end position if there was no contact).

Example: measure Z

PROBE = 0
start = d.getPosition(CoordMode.Program)
target = start.copy()
target[Axis.Z.value] -= 20                 # search at most 20 mm down

found = d.executeProbing(CoordMode.Program, target, PROBE, 100)
d.moveToPosition(CoordMode.Program, start, 1000)       # back to the start
if found:
    z = d.getProbingPosition(CoordMode.Program)[Axis.Z.value]
    msg.info("Contact at Z = {:.4f}".format(z), "Probing")
else:
    msg.err("No contact within 20 mm", "Probing")

Example: fast and slow probing of a switch

A fast probe finds the switch, a slow probe measures it precisely.

import sys

AXIS, PROBE, DIRECTION = Axis.X, 1, -1     # switch on probe input 1, in the minus direction
SEARCH, BACKOFF, FAST, SLOW = 5.0, 2.0, 300.0, 30.0
i = AXIS.value

def probe(distance, feed):
    pos = d.getPosition(CoordMode.Machine)
    pos[i] += DIRECTION * distance
    if not d.executeProbing(CoordMode.Machine, pos, PROBE, feed):
        sys.exit("No contact within {:.3f} mm".format(distance))
    return d.getProbingPosition(CoordMode.Machine)[i]

def move_to(value, feed):
    pos = d.getPosition(CoordMode.Machine)
    pos[i] = value
    d.moveToPosition(CoordMode.Machine, pos, feed)

first = probe(SEARCH, FAST)
move_to(first - DIRECTION * BACKOFF, FAST)
contact = probe(2 * BACKOFF, SLOW)
move_to(contact - DIRECTION * BACKOFF, FAST)
print("Switch at {:.4f} (machine coordinates)".format(contact))

Example: digitizing

Saved as a macro (e.g. m40.py) and called from G-code at each grid point, this script probes down and appends the contact point to a text file in the user's home folder.

import os, sys

path = os.path.join(os.path.expanduser("~"), "digitizing.txt")
start = d.getPosition(CoordMode.Program)
target = start.copy()
target[Axis.Z.value] -= 20

found = d.executeProbing(CoordMode.Program, target, 0, 100)
d.moveToPosition(CoordMode.Program, start, 1000)
p = d.getProbingPosition(CoordMode.Program)
line = "{:.4f} {:.4f} {:.4f}\n".format(p[0], p[1], p[2]) if found else "Probing failed\n"
try:
    with open(path, "a") as f:
        f.write(line)
except OSError as ex:
    sys.exit("Cannot write {}: {}".format(path, ex))
G-code calling M40 at each point, and the resulting file
"Probing failed" when there was no contact

9 Tools

Tool numbers

FunctionDescription
d.getSelectedToolNumber() / d.setSelectedToolNumber(n)tool selected for the next change – the same as T<n>
d.getSpindleToolNumber() / d.setSpindleToolNumber(n)tool in the spindle (shown on the screen)
d.getToolOffsetNumber() / d.setToolOffsetNumber(n)tool table entry used for the tool offset

The default M6 macro only takes over the numbers; a real tool change macro adds the machine's own sequence around it:

# m6.py (default)
tool = d.getSelectedToolNumber()
d.setSpindleToolNumber(tool)
d.setToolOffsetNumber(tool)
d.setSelectedToolNumber(10) is the same as T10

Tool table

FunctionDescription
d.getToolLength(n) / d.setToolLength(n, value)length offset
d.getToolOffset(n) / d.setToolOffset(n, values)offset of the tool for all six axes
d.getToolWearOffset(n) / d.setToolWearOffset(n, values)wear offset for all six axes
d.getToolDiameter(n) / d.setToolDiameter(n, value)diameter
d.getToolDiameterWear(n) / d.setToolDiameterWear(n, value)diameter wear

The diameter is used by cutter compensation (G41/G42): the effective diameter is diameter minus diameter wear.

tool = d.getSpindleToolNumber()
d.setToolLength(tool, 52.375)           # e.g. the result of a tool length measurement
d.setToolOffsetNumber(tool)
print("Tool {}: length {:.3f}, diameter {:.3f}".format(tool, d.getToolLength(tool), d.getToolDiameter(tool)))

10 Spindle, flood and mist

Spindle

void d.setSpindleSpeed(float rpm)  ·  float d.getSpindleSpeed()

Spindle speed in RPM, like S in G-code.

void d.setSpindleState(SpindleState state)  ·  SpindleState d.getSpindleState()

SpindleState.CW_ON, CCW_ON or OFF. The call waits during the spindle's acceleration and deceleration ramps.

void d.waitForSpindleSetSpeed(int timeout_sec)

Waits until the measured spindle speed reaches the Spindle Ready Level (percentage of the set speed, in the spindle settings). Raises SimCncException if it is not reached within the timeout. Needs a spindle speed feedback signal.

1000 RPM set, Spindle Ready Level 80 %: the script waits for 800 RPM

An M3 macro that waits for the speed and stops the program if it is not reached:

import sys
d.setSpindleState(SpindleState.CW_ON)
try:
    d.waitForSpindleSetSpeed(5)
except SimCncException as ex:
    d.setSpindleState(SpindleState.OFF)
    d.stopTrajectory()
    msg.err(str(ex), "Spindle")
    sys.exit(0)

Flood and mist

import time
d.setFloodState(FloodState.ON)
d.setMistState(MistState.ON)
time.sleep(10)
d.setFloodState(FloodState.OFF)
d.setMistState(MistState.OFF)
print(d.getFloodState(), d.getMistState())   # FloodState.OFF MistState.OFF

11 Program, overrides and parameters

Program control

FunctionDescription
d.startTrajectory()starts the loaded program
d.stopTrajectory() / d.stopButton()stops the program / the same as the STOP button
d.setTrajectoryPause(True)pauses (False resumes)
d.waitForTrajectoryFinished(timeout)waits until the program has finished
d.openGCodeFile(path), d.isGcodeFileLoaded(), d.getGCodeFilePath()G-code file
d.getGCodeCurrentLineNumber(), d.getGCodeLine(n)current line, text of a line
d.getCalculatedPathTime() / d.getRemainingPathTime()estimated total / remaining time in seconds

Feed rate and overrides

d.setFRO(50)                            # feed rate override 50 %  (integer)
d.setSRO(100)                           # spindle speed override
d.setRRO(25)                            # rapid override
print(d.getFeedrate(), d.getFRO())

Machine parameters

Machine parameters are the # parameters of G-code: d.getMachineParam(100) reads #100. Use them to pass values between G-code and scripts.

count = d.getMachineParam(100)
d.setMachineParam(100, count + 1)       # #100 = #100 + 1
d.setMachineParamName(100, "Part counter")

Information

d.getSimCncVersion(), d.getProfileName() and d.getScreenName() return the simCNC version, the profile and the screen.

A Function reference

All functions of simCNC 3.604. Functions marked module. are called on a module object (chapter 5); all others on d.

Program, positions, offsets, homing

FunctionDescription
bool d.isGcodeFileLoaded()Returns True if GCode file is loaded
void d.executeGCode(string GCodeCommand)Runs a G-code line and waits until it is finished
void d.executeGCodeList(List<string> GCodeList)Runs G-code lines and waits until they are finished
bool d.executeProbing(CoordMode coordMode, List<float>(6) position, int probeIndex, float velocity)Probes towards a position; True on contact, False if the end position was reached
List<float>(6) d.getCurrentWorkOffset()Returns the values of the active work offset
string d.getGCodeFilePath()Returns current GCode File Path
List<float>(6) d.getGCodeMinPosition(CoordMode coordMode)Returns the minimum position of the loaded G-code
List<float>(6) d.getGCodeMaxPosition(CoordMode coordMode)Returns the maximum position of the loaded G-code
float d.getMachineParam(int paramNumber)Returns the value of machine parameter #n
string d.getMachineParamName(int paramNumber)Returns machine parameter name
List<float>(6) d.getProbingPosition(CoordMode coordMode)Returns probe contact position if probe reached, otherwise returns programmed position
List<float>(6) d.getPosition(CoordMode coordMode)Returns the current position in machine or program coordinates
List<float>(6) d.getWorkOffset(int workOffsetIndex)Returns the values of a work offset (1-256)
int d.getWorkOffsetNumber()Returns the index of the active work offset (1 = G54)
void d.openGCodeFile(string filePath)Opens GCode file
void d.closeGCodeFile()Closes GCode file
void d.setGCodeNextLine()Moves the G-code cursor to the next line
int d.getGCodeLinesCount()Returns GCode lines count
string d.getGCodeLine(int number)Returns GCode line text
string d.getGCodeCurrentLine()Returns current GCode line text
int d.getGCodeCurrentLineNumber()Returns current GCode line number
void d.setGCodeCurrentLineNumber(int number)Sets current GCode line number
List<float>(6) d.getPositionForGCodeLine(int number, CoordMode coordMode)Returns the position for the indicated GCode line number
List<float>(6) d.getPositionForGCodeCurrentLine(CoordMode coordMode)Returns the position for the current GCode line
int d.getGCodeLineNumberClosestToPosition(List<float>(6) checkingPosition, List<float>(6) startGCodePosition, CoordMode coordMode)Returns the number of the line, whose position is closest to given position
int d.getGCodeLineNumberClosestToCurrentPosition(List<float>(6) startGCodePosition)Returns the number of the line, whose position is closest to current position
void d.setAxisProgPosition(Axis axis, float value)Sets the program position of an axis (changes the active work offset)
void d.setAxisAbsolutePosition(Axis axis, float value)Sets the machine (absolute) position of an axis
void d.setMachineParam(int paramNumber, float value)Sets the value of machine parameter #n
void d.setMachineParamName(int paramNumber, string name)Changes a machine parameter name
void d.setMachineParamToSave(int paramNumber, bool toSave)Sets a machine parameter as to save
void d.lockMachineParam(int paramNumber, bool lock)Lock machine param value changes
void d.setWorkOffset(int workOffsetIndex, List<float>(6) workOffsetValues)Sets the values of a work offset (1-256)
void d.setCurrentWorkOffset(List<float>(6) workOffsetValues)Sets the values of the active work offset
void d.setWorkOffsetNumber(int workOffsetIndex)Activates a work offset (1 = G54 ... 256 = G59.250)
void d.executeHoming()Execute homing on all axes
void d.executeAxisHoming(Axis axis)Execute homing on one axis
bool d.isAxisEnabled(Axis axis)Returns true if axis is enabled
bool d.isAxisReferenced(Axis axis)Returns true if axis is referenced

Machine state

FunctionDescription
State d.getState()Returns a machine state
void d.enableMachine(bool enable)Enables or disables the controller
bool d.isConnected()Returns true if a program is connected to a CSMIO-IP controller

Configuration

FunctionDescription
void d.setSoftLimitsState(Axis ax, bool state)Switches the soft limits of an axis on or off
bool d.getSoftLimitsState(Axis axis)Returns True if the soft limits of an axis are on
void d.setSoftLimitValue(Direction direction, Axis ax, float value)Sets a soft limit value for a given direction and axis
float d.getSoftLimitValue(Direction direction, Axis ax)Returns a soft limit value for a given direction and axis
void d.ignoreAllSoftLimits(bool ignore)Ignores all soft limits (True) or restores them (False)
bool d.areAllSoftLimitsIgnored()Returns True if ignore all soft limits function is on
string d.getProfileName()Returns current profile name
int d.getSpindleGear()Returns current spindle gear number
void d.setSpindleGear(int gear)Set spindle gear number
void module.setStepsPerUnit(int motionKitIndex, float value)Sets the steps per unit of a motion kit
float module.getStepsPerUnit(int motionKitIndex)Returns the steps per unit of a motion kit
void d.setStartTrajectoryMode(StartTrajectoryMode mode)Sets the start trajectory mode
StartTrajectoryMode d.getStartTrajectoryMode()Returns the start trajectory mode
void d.setStartTrajectoryAccessMode(StartTrajectoryAccessMode mode)Sets the start trajectory access mode
StartTrajectoryAccessMode d.getStartTrajectoryAccessMode()Returns the start trajectory access mode

Inputs and outputs

FunctionDescription
List<Module> d.getModuleList()Returns all available modules
Module d.getModule(ModuleType type, int ID)Returns a module (device) by type and ID
Module d.getMainModule()Returns the main controller module, same as getModule(ModuleType.IP, 0)
float module.getAnalogIO(IOPortDir direction, int analogPin)Returns the voltage of an analog pin
bool module.isAnalogIOAssignedToSignal(IOPortDir direction, int analogPin)Returns true if analog IO is assigned to any signal
string module.getSignalIDAssignedToAnalogIO(IOPortDir direction, int analogPin)Returns signal ID assigned analog IO
DIOPinVal module.getDigitalIO(IOPortDir direction, int digitalPin)Returns the state of a digital pin
bool module.isDigitalIOAssignedToSignal(IOPortDir direction, int digitalPin)Returns true if digital IO is assigned to any signal
string module.getSignalIDAssignedToDigitalIO(IOPortDir direction, int digitalPin)Returns signal ID assigned digital IO
float module.getEncoderIOAngle(int channel)Returns the encoder angle (from the index signal)
int module.getEncoderIOPosition(int channel)Returns the encoder position (counts from the first index)
float module.getEncoderIORPM(int channel)Returns a current encoder speed in revolutions per minute (RPM)
void module.setAnalogIO(int analogPin, float value)Sets the voltage of an analog output pin
void module.setDigitalIO(int digitalPin, DIOPinVal value)Sets a digital output pin
int module.getDigitalIOCount(IOPortDir direction)Return a digital input/output pin count for a module
int module.getAnalogIOCount(IOPortDir direction)Return an analog input/output pin count for a module
int module.getEncoderIOPositionCount()Return a position port count for a module
int module.getEncoderIOVelocityCount()Return a velocity port count for a module
int module.getEncoderIOAngleCount()Return a angle port count for a module
List<DIOPinVal> module.getDigitalIOs(IOPortDir direction)Return a value for all input/output digital pins
List<float> module.getAnalogIOs(IOPortDir direction)Return a value for all input/output analog pins
List<int> module.getEncoderIOPositions()Return a value for all encoder position ports
List<float> module.getEncoderIOVelocities()Return a value for all encoder velocity ports
List<float> module.getEncoderIOAngles()Return a value for all encoder angle ports
float d.getAnalogIOSignalValue(IOFunctionId signalFunction, int index)Returns the value of an analog signal (function and index)
DSignalVal d.getDigitalIOSignalValue(IOFunctionId signalFunction, int index)Returns the state of a digital signal (function and index)
float d.getAngleIOSignalValue(IOFunctionId signalFunction, int index)Returns the value of an angle signal (function and index)
int d.getPositionIOSignalValue(IOFunctionId signalFunction, int index)Returns the value of a position signal (function and index)
float d.getVelocityIOSignalValue(IOFunctionId signalFunction, int index)Returns the value of a velocity signal (function and index)

PyActions

FunctionDescription
void d.runPyAction(string name)Runs a PyAction by name

Trajectory Control

FunctionDescription
float d.getFeedrate()Returns current feedrate
int d.getFRO()Returns current feedrate override value in percent
int d.getSRO()Returns current spindle speed override value in percent
int d.getRRO()Returns current rapid override value in percent
bool d.getTrajectoryPause()Returns true if trajectory is paused, otherwise returns false
void d.rewindTrajectory()Rewind trajectory to its beginning
void d.setFeedrate(float feedrate)Sets a feedrate
void d.setFRO(int FRO)Sets feedrate override value in percent
void d.setSRO(int SRO)Sets spindle speed override value in percent
void d.setRRO(int RRO)Sets rapid override value in percent
void d.setTrajectoryPause(bool pauseON)Sets trajectory pause on or off
void d.startTrajectory()Starts running a currently loaded GCode file
void d.stopTrajectory()Stops running a trajectory
void d.finishTrajectory()Finishes running a trajectory
void d.simpleStopTrajectory()Stops running a trajectory without additional actions
void d.stopButton()Same as click stop button
bool d.waitForTrajectoryFinished(float timeout)Waits until the program has finished
void d.setTangentialAxisEnable(bool enable)Enables tangential axis
bool d.getTangentialAxisEnable()Returns True if the tangential axis is enabled
int d.getCalculatedPathTime()Returns the calculated program time in seconds
int d.getRemainingPathTime()Returns the remaining program time in seconds

Movement

FunctionDescription
bool d.waitForZeroVelocity(float timeout)Waits until the axes stand still
float d.getCurrentXYZVelocity()Returns the current resultant XYZ velocity (units/min)
float d.getCurrentAxisVelocity(Axis axis)Returns the current velocity of an axis (units/min)
void d.moveAxisIncremental(Axis axis, float distance, float velocity)Moves an axis by a distance
void d.moveToPosition(CoordMode coordMode, List<float>(6) position, float velocity)Moves to a position at a resultant velocity
void d.parallelMoveToPosition(CoordMode coordMode, Axis axis, float position, float velocity)Moves a single axis independently to a position

THC

FunctionDescription
void d.setThcState(ThcState state)Sets a THC state
ThcState d.getThcState()Returns a THC state

AutoLeveling

FunctionDescription
void d.setAutoLevelingState(AutoLevelingState state)Sets an auto-leveling state
AutoLevelingState d.getAutoLevelingState()Returns an auto-leveling state
void d.setAutoLevelingGridData(List<List<float>> gridData)Sets an auto-leveling grid data
void d.setAutoLevelingOrigin(List<float>(6) origin)Sets an auto-leveling origin
void d.setAutoLevelingGridStep(float stepX, float stepY)Sets an auto-leveling grid step

Laser

FunctionDescription
void d.setLaserMode(LaserMode mode)Sets a laser mode
LaserMode d.getLaserMode()Returns a laser mode
void d.setLaserRasterOrientation(RasterOrientation orientation)Sets a laser movement orientation
RasterOrientation d.getLaserRasterOrientation()Returns a laser movement orientation
void d.setLaserImgColorMode(ImgColorMode colorMode)Sets a laser image color mode
ImgColorMode d.getLaserImgColorMode()Returns a laser image color mode
void d.setLaserManualOut(float out)Sets a laser out in manual mode
float d.getLaserManualOut()Returns a laser out in manual mode
void d.setLaserImgBrightness(int brightness)Sets a laser image brightness
int d.getLaserImgBrightness()Returns a laser image brightness
void d.setLaserImgContrast(int contrast)Sets a laser image contrast
int d.getLaserImgContrast()Returns a laser image contrast
void d.setLaserImgBWThreshold(int threshold)Sets the laser image black/white threshold
int d.getLaserImgBWThreshold()Returns a laser image black/white threshold
void d.setLaserImgPixelSize(float pixel)Sets a laser image pixel size
float d.getLaserImgPixelSize()Returns a laser image pixel size
void d.setLaserImgWidth(float width)Sets a laser image width
float d.getLaserImgWidth()Returns a laser image width
void d.setLaserImgHeight(float height)Sets a laser image height
float d.getLaserImgHeight()Returns a laser image height
void d.setLaserKeepAspectRatio(bool keepAspectRatio)Sets a laser image aspect ratio keeping
bool d.getLaserKeepAspectRatio()Returns a laser image aspect ratio keeping
void d.setLaserPowerCurve(float grayLevel_1, float voltage_1, float grayLevel_2, float voltage_2)Sets a laser power curve
List<float>(4) d.getLaserPowerCurve()Gets a laser power curve
void d.setLaserDefaultPowerCurve()Sets default laser power curve
void d.setLaserImgDefaultConfig()Sets default laser image configuration
void d.openLaserImage(string filePath)Opens laser image file

Spindle, coolant and tools

FunctionDescription
FloodState d.getFloodState()Returns a current flood state
MistState d.getMistState()Returns a current mist state
int d.getSelectedToolNumber()Returns a selected tool number
float d.getSpindleSpeed()Returns the spindle speed (RPM)
SpindleState d.getSpindleState()Returns a current spindle state
int d.getSpindleToolNumber()Returns a number of a tool currently held by a spindle
float d.getToolDiameter(int toolNumber)Returns a diameter of a tool of a given number
float d.getToolLength(int toolNumber)Returns a length offset of a tool of a given number
List<float>(6) d.getToolOffset(int toolNumber)Returns an offset of a tool of a given number
List<float>(6) d.getToolWearOffset(int toolNumber)Returns a wear offset of a tool of a given number
float d.getToolDiameterWear(int toolNumber)Returns a diameter wear of a tool of a given number
int d.getToolOffsetNumber()Returns the tool table entry used for the tool offset
void d.setFloodState(FloodState state)Sets a flood state
void d.setMistState(MistState state)Sets a mist state
void d.setSelectedToolNumber(int toolNumber)Sets a current chosen tool number, which is about to be changed (equivalent to T command in GCode)
void d.setSpindleSpeed(float spindleSpeed)Sets the spindle speed (RPM), like S
void d.setSpindleState(SpindleState spindleState)Sets the spindle state; waits during the ramps
void d.setSpindleToolNumber(int toolNumber)Sets a number of a tool currently held by a spindle
void d.setToolDiameter(int toolNumber, float toolDiameter)Sets a diameter of a tool of a given number
void d.setToolLength(int toolNumber, float toolLength)Sets a length offset of a tool of a given number
void d.setToolOffset(int toolNumber, List<float>(6) toolOffset)Sets the offset of a tool (six axes)
void d.setToolWearOffset(int toolNumber, List<float>(6) toolOffsetWear)Sets a wear offset of a tool of a given number
void d.setToolDiameterWear(int toolNumber, float toolDiameterWear)Sets a diameter wear of a tool of a given number
void d.setToolOffsetNumber(int toolNumber)Sets the tool table entry used for the tool offset
void d.waitForSpindleSetSpeed(int timeout_sec)Waits until the spindle reaches the Spindle Ready Level; raises SimCncException on timeout

Jog

FunctionDescription
void d.setJogSpeed(float speed)Sets jog speed in percent
float d.getJogSpeed()Gets jog speed in percent
void d.setJogMode(JogMode mode)Sets the JOG mode
JogMode d.getJogMode()Returns a JOG mode
void d.setJogStep(float step)Sets jog step
float d.getJogStep()Gets jog step

Debug

FunctionDescription
void d.clearPythonConsole()Clears python console
dict d.getCurrentScriptInfo()Returns current script info
dict d.getRunningScriptsInfo()Returns running scripts info
dict d.getDeviceInfo()Returns device info
string d.getSimCncVersion()Returns the simCNC version

GUI

FunctionDescription
string d.getScreenName()Returns current screen name
void d.closeAllMessageBoxes()Closes all message boxes

B Enumerations

Axis
X, Y, Z, A, B, C, E0, E1, E2, E3, E4, E5
State
EStop, Idle, Homing, Trajectory, JOG, MDI, MPG
SpindleState
OFF, CW_ON, CCW_ON
FloodState
OFF, ON
MistState
OFF, ON
ModuleType
IP, IO, MPG, ENC, DRV
IOPortDir
InputPort, OutputPort
DIOPinVal
PinReset, PinSet
CoordMode
Machine, Program
IOFunctionId
iofnEStop, iofnHome, iofnIndex, iofnLimitP, iofnLimitN, iofnDriveFault, iofnTrajTrig, iofnProbe, iofnThcUp, iofnThcDown, iofnThcTorchOnDig, iofnThcTorchOnAnalog, iofnThcAnalog, iofnDriveEnable, iofnDriveReset, iofnTrajSyncOut, iofnSpindleCw, iofnSpindleCcw, iofnSpindleAO, iofnFlood, iofnMist, iofnHvEnable, iofnPyFunctionRun, iofnMPGEncPosition, iofnMPGEncSpeed, iofnMPGStatus, iofnSpindleSpeed, iofnExtRateOverrideEnable, iofnExtRateOverrideRegulator, iofnMPGAxisXSelect, iofnMPGAxisYSelect, iofnMPGAxisZSelect, iofnMPGAxisASelect, iofnMPGAxisBSelect, iofnMPGAxisCSelect, iofnMPGIncrementSelect_x1, iofnMPGIncrementSelect_x10, iofnMPGIncrementSelect_x100, iofnLimitsOverride, iofnSpindleFault, iofnPSupplyFault, iofnMPGInhibit, iofnLaserAOut
DSignalVal
signalActive, signalInactive
LaserMode
Off, Image, Manual, Cut
RasterOrientation
Horizontal, Vertical
ImgColorMode
Grayscale, Threshold, Dithering
Direction
Negative, Positive
ThcState
Off, On
AutoLevelingState
Off, On
JogMode
Continous, Step
StartTrajectoryMode
ExactGCode, AddAccessSegments
StartTrajectoryAccessMode
Direct, SafeZPosition

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article