:lang: en
:toc:

[[cha:python-interface]]
= Python Interface

:ini: {basebackend@docbook:'':ini}
:hal: {basebackend@docbook:'':hal}
:ngc: {basebackend@docbook:'':ngc}

This documentation describes the `linuxcnc` python module, which provides
a Python API for talking to LinuxCNC.

////
constants are located in src/emc/usr_intf/axis/extensions/emcmodule.cc
////

== The `linuxcnc` Python module

User interfaces control LinuxCNC activity by sending
NML messages to the LinuxCNC task controller, and monitor results by
observing the LinuxCNC status structure, as well as the error reporting channel.

Programmatic access to NML is through a C++ API; however, the most
important parts of the NML interface to LinuxCNC are also available to
Python programs through the `linuxcnc` module.

Beyond the NML interface to the command, status and error channels,
the `linuxcnc` module also contains:

- support for reading values from INI files

////
- support for position logging  (???)
////

== Usage Patterns for the LinuxCNC NML interface

The general pattern for `linuxcnc` usage is roughly like this:

- import the `linuxcnc` module
- establish connections to the command, status and error NML channels as needed
- poll the status channel, either periodically or as needed
- before sending a command, determine from status whether it is in
  fact OK to do so (for instance, there is no point in sending a 'Run'
  command if task is in the ESTOP state, or the interpreter is not idle)
- send the command by using one of the `linuxcnc` command channel methods

To retrieve messages from the error channel, poll the error channel
periodically, and process any messages retrieved.

- poll the status channel, either periodically or as needed
- print any error message and explore the exception code

`linuxcnc` also defines the `error` Python exception type to support error reporting.

== Reading LinuxCNC status

Here is a Python fragment to explore the contents of the
`linuxcnc.stat` object which contains some 80+ values (run while
linuxcnc is running for typical values):

[source,python]
----
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import linuxcnc
try:
    s = linuxcnc.stat() # create a connection to the status channel
    s.poll() # get current values
except linuxcnc.error, detail:
    print("error", detail)
    sys.exit(1)
for x in dir(s):
    if not x.startswith("_"):
        print(x, getattr(s,x))
----

Linuxcnc uses the default compiled-in path to the NML configuration
file unless overridden, see <<python:reading-ini-values,Reading
INI file values>> for an example.

=== linuxcnc.stat attributes

*acceleration*:: '(returns float)' -
  default acceleration, reflects the INI entry [TRAJ]DEFAULT_ACCELERATION.

*active_queue*:: '(returns integer)' -
  number of motions blending.

*actual_position*:: '(returns tuple of floats)' -
  current trajectory position, (x y z a b c u v w) in machine units.

*adaptive_feed_enabled*:: '(returns boolean)' -
  status of adaptive feedrate override (0/1).

*ain*:: '(returns tuple of floats)' -
  current value of the analog input pins.

*angular_units*:: '(returns float)' -
machine angular units per deg, reflects [TRAJ]ANGULAR_UNITS INI value.

*aout*:: '(returns tuple of floats)' -
  current value of the analog output pins.

*axes*:: '(returns integer)' -
  number of axes. Derived from [TRAJ]COORDINATES INI value.

*axis*:: '(returns tuple of dicts)' -
  reflecting current axis values. See
  <<sec:the-axis-dictionary,The axis dictionary>>.

*axis_mask*:: '(returns integer)' -
  mask of axis available as defined by [TRAJ]COORDINATES in the INI
  file. Returns the sum of the axes X=1, Y=2, Z=4, A=8, B=16, C=32, U=64,
  V=128, W=256.

*block_delete*:: '(returns boolean)' -
  block delete current status.

*call_level*:: '(returns integer)'` -
  current subroutine depth. - 0 If not in a subroutine, Depth if not otherwise specified

*command*:: '(returns string)' -
  currently executing command.

*current_line*:: '(returns integer)' -
  currently executing line.

*current_vel*:: '(returns float)' -
  current velocity in user units per second.

*cycle_time*:: '(returns float)' -
  thread period

*debug*:: '(returns integer)' -
  debug flag from the INI file.

*delay_left*:: '(returns float)' -
  remaining time on dwell (G4) command, seconds.

*din*:: '(returns tuple of integers)' -
  current value of the digital input pins.

*distance_to_go*:: '(returns float)' -
  remaining distance of current move, as reported by trajectory planner.

*dout*:: '(returns tuple of integers)' -
  current value of the digital output pins.

*dtg*:: '(returns tuple of floats)' -
  remaining distance of current move for each axis, as reported by trajectory planner.

*echo_serial_number*:: '(returns integer)' -
  The serial number of the last completed command sent by a UI
  to task. All commands carry a serial number. Once the command
  has been executed, its serial number is reflected in
  `echo_serial_number`.

*enabled*:: '(returns boolean)' -
  trajectory planner enabled flag.

*estop*:: '(returns integer)' -
  Returns either STATE_ESTOP or not.

*exec_state*:: '(returns integer)' -
  task execution state. One of EXEC_ERROR, EXEC_DONE,
  EXEC_WAITING_FOR_MOTION, EXEC_WAITING_FOR_MOTION_QUEUE,
  EXEC_WAITING_FOR_IO, EXEC_WAITING_FOR_MOTION_AND_IO,
  EXEC_WAITING_FOR_DELAY, EXEC_WAITING_FOR_SYSTEM_CMD,
  EXEC_WAITING_FOR_SPINDLE_ORIENTED.

*feed_hold_enabled*:: '(returns boolean)' -
  enable flag for feed hold.

*feed_override_enabled*:: '(returns boolean)' -
  enable flag for feed override.

*feedrate*:: '(returns float)' -
  current feedrate override, 1.0 = 100%.

*file*:: '(returns string)' -
  currently loaded G-code filename with path.

*flood*:: '(returns integer)' -
  Flood status, either FLOOD_OFF or FLOOD_ON.

*g5x_index*:: '(returns integer)' -
  currently active coordinate system, G54=1, G55=2 etc.

*g5x_offset*:: '(returns tuple of floats)' -
  offset of the currently active coordinate system.

*g92_offset*:: '(returns tuple of floats)' -
  pose of the current g92 offset.

*gcodes*:: '(returns tuple of integers)' -
  Active G-codes for each modal group.
  G-code constants
  G_0, G_1, G_2, G_3, G_4, G_5, G_5_1, G_5_2, G_5_3, G_7, G_8, G_100, G_17,
  G_17_1, G_18, G_18_1, G_19, G_19_1, G_20, G_21, G_28, G_28_1, G_30, G_30_1,
  G_33, G_33_1, G_38_2, G_38_3, G_38_4, G_38_5, G_40, G_41, G_41_1, G_42, G_42_1,
  G_43, G_43_1, G_43_2, G_49, G_50, G_51, G_53, G_54, G_55, G_56, G_57, G_58,
  G_59, G_59_1, G_59_2, G_59_3, G_61, G_61_1, G_64, G_73, G_76, G_80, G_81, G_82,
  G_83, G_84, G_85, G_86, G_87, G_88, G_89, G_90, G_90_1, G_91, G_91_1, G_92,
  G_92_1, G_92_2, G_92_3, G_93, G_94, G_95, G_96, G_97, G_98, G_99

*homed*:: '(returns tuple of integers)' -
  currently homed joints, 0 = not homed, 1 = homed.

*id*:: '(returns integer)' -
  currently executing motion id.

*ini_filename*:: '(returns string)' -
  path to the INI file passed to linuxcnc.

*inpos*:: '(returns boolean)' -
  machine-in-position flag.

*input_timeout*:: '(returns boolean)' -
  flag for M66 timer in progress.

*interp_state*:: '(returns integer)' -
  current state of RS274NGC interpreter. One of
  INTERP_IDLE, INTERP_READING, INTERP_PAUSED, INTERP_WAITING.

*interpreter_errcode*:: '(returns integer)' -
  current RS274NGC interpreter return code. One of
  INTERP_OK, INTERP_EXIT, INTERP_EXECUTE_FINISH, INTERP_ENDFILE,
  INTERP_FILE_NOT_OPEN, INTERP_ERROR.
  see src/emc/nml_intf/interp_return.hh

*joint*:: '(returns tuple of dicts)' -
  reflecting current joint values. See
  <<sec:the-joint-dictionary,The joint dictionary>>.

*joint_actual_position*:: '(returns tuple of floats)' -
  actual joint positions.

*joint_position*:: '(returns tuple of floats)' -
  Desired joint positions.

*joints*:: '(returns integer)' -
  number of joints. Reflects [KINS]JOINTS INI value.

*kinematics_type*:: '(returns integer)' -
  The type of kinematics. One of:
  * KINEMATICS_IDENTITY
  * KINEMATICS_FORWARD_ONLY
  * KINEMATICS_INVERSE_ONLY
  * KINEMATICS_BOTH

*limit*:: '(returns tuple of integers)' -
  axis limit masks. minHardLimit=1,
  maxHardLimit=2, minSoftLimit=4, maxSoftLimit=8.

*linear_units*:: '(returns float)' -
  machine linear units per mm, reflects [TRAJ]LINEAR_UNITS INI value.

*lube*:: '(returns integer)' -
  'lube on' flag.

*lube_level*:: '(returns integer)' -
  reflects 'iocontrol.0.lube_level'.

*max_acceleration*:: '(returns float)' -
  maximum  acceleration. Reflects [TRAJ]MAX_ACCELERATION.

*max_velocity*:: '(returns float)' -
  maximum  velocity. Reflects the current maximum velocity. If not modified by halui.max-velocity or similar it should reflect [TRAJ]MAX_VELOCITY.

*mcodes*:: '(returns tuple of 10 integers)' -
  currently active M-codes.

*mist*:: '(returns integer)' -
  Mist status, either MIST_OFF or MIST_ON

*motion_line*:: '(returns integer)' -
  source line number motion is currently executing. Relation
  to `id` unclear.

*motion_mode*:: '(returns integer)' -
  This is the mode of the Motion controller.  One of TRAJ_MODE_COORD,
  TRAJ_MODE_FREE, TRAJ_MODE_TELEOP.

*motion_type*:: '(returns integer)' -
  The type of the currently executing motion.  One of:
  * MOTION_TYPE_TRAVERSE
  * MOTION_TYPE_FEED
  * MOTION_TYPE_ARC
  * MOTION_TYPE_TOOLCHANGE
  * MOTION_TYPE_PROBING
  * MOTION_TYPE_INDEXROTARY
  * Or 0 if no motion is currently taking place.

*optional_stop*:: '(returns integer)' -
  option stop flag.

*paused*:: '(returns boolean)' -
  `motion paused` flag.

*pocket_prepped*:: '(returns integer)' -
  A Tx command completed, and this pocket is prepared. -1 if no
  prepared pocket.

*poll()*:: -'(built-in function)'
  method to update current status attributes.

*position*:: '(returns tuple of floats)' -
  trajectory position.

*probe_tripped*:: '(returns boolean)' -
  flag, True if probe has tripped (latch)

*probe_val*:: '(returns integer)' -
  reflects value of the `motion.probe-input` pin.

*probed_position*:: '(returns tuple of floats)' -
  position where probe tripped.

*probing*:: '(returns boolean)' -
  flag, True if a probe operation is in progress.

*program_units*:: '(returns integer)' -
  one of CANON_UNITS_INCHES=1, CANON_UNITS_MM=2, CANON_UNITS_CM=3

*queue*:: '(returns integer)' -
  current size of the trajectory planner queue.

*queue_full*:: '(returns boolean)' -
  the trajectory planner queue is full.

*rapidrate*:: '(returns float)' -
  rapid override scale.

*read_line*:: '(returns integer)' -
  line the RS274NGC interpreter is currently reading.

*rotation_xy*:: '(returns float)' -
  current XY rotation angle around Z axis.

*settings*:: '(returns tuple of floats)' -
  current interpreter settings. settings[0] =
  sequence number, settings[1] = feed rate, settings[2] = speed,
  settings[3] = `G64 P` blend tolerance,
  settings[4] = `G64 Q` naive CAM tolerance.

*spindle*:: ' (returns tuple of dicts) ' -
  returns the current spindle status,
  see <<sec:the-spindle-dictionary, The spindle dictionary>>

*spindles*:: '(returns integer)' -
  number of spindles. Reflects [TRAJ]SPINDLES INI value.

*state*:: '(returns integer)' -
  current command execution status. One of RCS_DONE,
  RCS_EXEC, RCS_ERROR.

*task_mode*:: '(returns integer)' -
  current task mode. one of MODE_MDI, MODE_AUTO,
  MODE_MANUAL.

*task_paused*:: '(returns integer)' -
  task paused flag.

*task_state*:: '(returns integer)' -
  current task state. one of STATE_ESTOP,
  STATE_ESTOP_RESET, STATE_ON, STATE_OFF.

*tool_in_spindle*:: '(returns integer)' -
  current tool number.

*tool_from_pocket*:: '(returns integer)' -
  pocket number for the currently loaded tool (0 if no tool loaded).

*tool_offset*:: '(returns tuple of floats)' -
  offset values of the current tool.

*tool_table*:: '(returns tuple of tool_results)' -
  list of tool entries. Each entry is a sequence of the following fields:
  id, xoffset, yoffset, zoffset, aoffset, boffset, coffset, uoffset, voffset,
  woffset, diameter, frontangle, backangle, orientation. The id and orientation
  are integers and the rest are floats.

[source,python]
----
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import linuxcnc
s = linuxcnc.stat()
s.poll()
# to find the loaded tool information it is in tool table index 0
if s.tool_table[0].id != 0: # a tool is loaded
    print(s.tool_table[0].zoffset)
else:
    print("No tool loaded.")
----

*velocity*:: '(returns float)' -
  This property is defined, but it does not have a useful interpretation.

[[sec:the-axis-dictionary]]
=== The `axis` dictionary

The axis configuration and status values are available through a list
of per-axis dictionaries. Here's an example how to access an attribute
of a particular axis:
Note that many properties that were formerly in the `axis` dictionary are
now in the `joint` dictionary, because on nontrivial kinematics machines
these items (such as backlash) are not the properties of an axis.

*max_position_limit*:: '(returns float)' -
  maximum limit (soft limit) for axis motion, in machine units.configuration
  parameter, reflects [JOINT_n]MAX_LIMIT.

*min_position_limit*:: '(returns float)' -
  minimum limit (soft limit) for axis motion, in machine units.configuration
  parameter, reflects [JOINT_n]MIN_LIMIT.

*velocity*:: '(returns float)' -
  current velocity.

[[sec:the-joint-dictionary]]
=== The `joint` dictionary

[source,python]
----
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import linuxcnc
s = linuxcnc.stat()
s.poll()
print("Joint 1 homed: ", s.joint[1]["homed"])
----

For each joint, the following dictionary keys are available:

*backlash*:: '(returns float)' -
  Backlash in machine units. configuration parameter, reflects [JOINT_n]BACKLASH.

*enabled*:: '(returns integer)' -
  non-zero means enabled.

*fault*:: '(returns integer)' -
  non-zero means axis amp fault.

*ferror_current*:: '(returns float)' -
  current following error.

*ferror_highmark*:: '(returns float)' -
  magnitude of max following error.

*homed*:: '(returns integer)' -
  non-zero means has been homed.

*homing*:: '(returns integer)' -
  non-zero means homing in progress.

*inpos*:: '(returns integer)' -
  non-zero means in position.

*input*:: '(returns float)' -
  current input position.

*jointType*:: '(returns integer)' -
  type of axis configuration parameter, reflects
  [JOINT_n]TYPE. LINEAR=1, ANGULAR=2. See <<sub:ini:sec:axis-letter, Joint
  INI configuration>> for details.

*max_ferror*:: '(returns float)' -
  maximum following error. configuration
  parameter, reflects [JOINT_n]FERROR.

*max_hard_limit*:: '(returns integer)' -
  non-zero means max hard limit exceeded.

*max_position_limit*:: '(returns float)' -
  maximum limit (soft limit) for joint motion, in machine units. configuration
  parameter, reflects [JOINT_n]MAX_LIMIT.

*max_soft_limit*::
  non-zero means `max_position_limit` was exceeded, int

*min_ferror*:: '(returns float)' -
  configuration parameter, reflects [JOINT_n]MIN_FERROR.

*min_hard_limit*:: '(returns integer)' -
  non-zero means min hard limit exceeded.

*min_position_limit*:: '(returns float)' -
  minimum limit (soft limit) for joint motion, in machine units. configuration
  parameter, reflects [JOINT_n]MIN_LIMIT.

*min_soft_limit*:: '(returns integer)' -
  non-zero means `min_position_limit` was exceeded.

*output*:: '(returns float)' -
  commanded output position.

*override_limits*:: '(returns integer)' -
  non-zero means limits are overridden.

*units*:: '(returns float)' -
  joint units per mm, or per degree for angular joints. +
  (joint units are the same as machine units, unless set otherwise
  by the configuration parameter [JOINT_n]UNITS)

*velocity*:: '(returns float)' -
  current velocity.

[[sec:the-spindle-dictionary]]
== The `spindle` dictionary

*brake*:: '(returns integer)' -
  value of the spindle brake flag.

*direction*:: '(returns integer)' -
  rotational direction of the spindle. forward=1, reverse=-1.

*enabled*:: '(returns integer)' -
  value of the spindle enabled flag.

*homed*:: (not currently implemented)

*increasing*:: '(returns integer)' -
  unclear.

*orient_fault*:: '(returns integer)'

*orient_state*:: '(returns integer)'

*override*:: '(returns float)' -
  spindle speed override scale.

*override_enabled*:: '(returns boolean)' -
  value of the spindle override enabled flag.

*speed*:: '(returns float)' -
  spindle speed value, rpm, > 0: clockwise, < 0:
  counterclockwise.

==  Preparing to send commands

Some commands can always be sent, regardless of mode and state; for
instance, the `linuxcnc.command.abort()` method can always be called.

Other commands may be sent only in appropriate state, and those tests
can be a bit tricky. For instance, an MDI command can be sent only if:

- ESTOP has not been triggered, and
- the machine is turned on and
- the axes are homed and
- the interpreter is not running and
- the mode is set to `MDI mode`

so an appropriate test before sending an MDI command through
`linuxcnc.command.mdi()` could be:

[source,python]
----
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import linuxcnc
s = linuxcnc.stat()
c = linuxcnc.command()

def ok_for_mdi():
    s.poll()
    return not s.estop and s.enabled and (s.homed.count(1) == s.joints) and (s.interp_state == linuxcnc.INTERP_IDLE)

if ok_for_mdi():
    c.mode(linuxcnc.MODE_MDI)
    c.wait_complete() # wait until mode switch executed
    c.mdi("G0 X10 Y20 Z30")
----

==  Sending commands through `linuxcnc.command`

Before sending a command, initialize a command channel like so:

[source,python]
----
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import linuxcnc
c = linuxcnc.command()

# Usage examples for some of the commands listed below:
c.abort()

c.auto(linuxcnc.AUTO_RUN, program_start_line)
c.auto(linuxcnc.AUTO_STEP)
c.auto(linuxcnc.AUTO_PAUSE)
c.auto(linuxcnc.AUTO_RESUME)

c.brake(linuxcnc.BRAKE_ENGAGE)
c.brake(linuxcnc.BRAKE_RELEASE)

c.flood(linuxcnc.FLOOD_ON)
c.flood(linuxcnc.FLOOD_OFF)

c.home(2)

c.jog(linuxcnc.JOG_STOP,        jjogmode, joint_num_or_axis_index)
c.jog(linuxcnc.JOG_CONTINUOUS,  jjogmode, joint_num_or_axis_index, velocity)
c.jog(linuxcnc.JOG_INCREMENT,   jjogmode, joint_num_or_axis_index, velocity, increment)

c.load_tool_table()

c.maxvel(200.0)

c.mdi("G0 X10 Y20 Z30")

c.mist(linuxcnc.MIST_ON)
c.mist(linuxcnc.MIST_OFF)

c.mode(linuxcnc.MODE_MDI)
c.mode(linuxcnc.MODE_AUTO)
c.mode(linuxcnc.MODE_MANUAL)

c.override_limits()

c.program_open("foo.ngc")
c.reset_interpreter()

c.tool_offset(toolno, z_offset,  x_offset, diameter, frontangle, backangle, orientation)
----

=== `linuxcnc.command` attributes

`serial`::
  the current command serial number

=== `linuxcnc.command` methods:

`abort()`::
  send EMC_TASK_ABORT message.

`auto(int[, int])`::
  run, step, pause or resume a program.

`brake(int)`::
  engage or release spindle brake.

`debug(int)`::
  set debug level via EMC_SET_DEBUG message.

`display_msg(string)`::
  sends a operator display message to the screen. (max 254 characters)

`error_msg(string)`::
  sends a operator error message to the screen. (max 254 characters)

`feedrate(float)`::
  set the feedrate.

`flood(int)`::
  turn on/off flooding.
  Syntax;;
    flood(command) +
    flood(linuxcnc.FLOOD_ON) +
    flood(linuxcnc.FLOOD_OFF)
  Constants;;
    FLOOD_ON +
    FLOOD_OFF

`home(int)`::
    home a given joint.

`jog(command-constant, bool, int[, float[, float]])`::
    Syntax;;
      jog(command,                 jjogmode, joint_num_or_axis_index, velocity[, distance]) +
      jog(linuxcnc.JOG_STOP,       jjogmode, joint_num_or_axis_index) +
      jog(linuxcnc.JOG_CONTINUOUS, jjogmode, joint_num_or_axis_index, velocity) +
      jog(linuxcnc.JOG_INCREMENT,  jjogmode, joint_num_or_axis_index, velocity, distance)
    Command Constants;;
      linuxcnc.JOG_STOP +
      linuxcnc.JOG_CONTINUOUS +
      linuxcnc.JOG_INCREMENT
    jjogmode;;
      True::: request individual joint jog (requires teleop_enable(0))
      False::: request axis Cartesian coordinate jog (requires teleop_enable(1))
    joint_num_or_axis_index;;
      For joint jog (jjogmode=1)::: joint_number
      For axis Cartesian coordinate jog (jjogmode=0):::
        zero-based index of the axis coordinate with respect to
        the known coordinate letters XYZABCUVW
        (x=>0,y=>1,z=>2,a=>3,b=>4,c=>5,u=>6,v=>7,w=>8)

`load_tool_table()`::
  reload the tool table.

`maxvel(float)`::
  set maximum velocity

`mdi(string)`::
  send an MDI command. Maximum 254 chars.

`mist(int)`:: turn on/off mist. +
    Syntax;;
      mist(command) +
      mist(linuxcnc.MIST_ON) +
      mist(linuxcnc.MIST_OFF) +
    Constants;;
      MIST_ON +
      MIST_OFF

`mode(int)`::
  set mode (MODE_MDI, MODE_MANUAL, MODE_AUTO).

`override_limits()`::
  set the override axis limits flag.

`program_open(string)`::
  open an NGC file.

`rapidrate()`::
  set rapid override factor

`reset_interpreter()`::
  reset the RS274NGC interpreter

`set_adaptive_feed(int)`::
  set adaptive feed flag

`set_analog_output(int, float)`::
  set analog output pin to value

`set_block_delete(int)`::
  set block delete flag

`set_digital_output(int, int)`::
  set digital output pin to value

`set_feed_hold(int)`::
  set feed hold on/off

`set_feed_override(int)`::
  set feed override on/off

`set_max_limit(int, float)`::
  set max position limit for a given axis

`set_min_limit()`::
  set min position limit for a given axis

`set_optional_stop(int)`::
  set optional stop on/off

`set_spindle_override(int [, int])`::
  set spindle override enabled. Defaults to spindle 0.

`spindle(direction: int, speed: float=0, spindle: int=0, wait_for_speed: int=0)`::
    - Direction: [SPINDLE_FORWARD, SPINDLE_REVERSE, SPINDLE_OFF, SPINDLE_INCREASE,
      SPINDLE_DECREASE, or SPINDLE_CONSTANT]
    - Speed: Speed in RPM, defaults to 0.
    - Spindle: Spindle number to command defaults to 0.
    - Wait_for_speed: if 1 motion will wait for speed before continuing, defaults to not.

[WARNING]
MDI commands will ignore this. "S1000" after this will turn the spindle off.

`text_msg(string)`::
  sends a operator text message to the screen. (max 254 characters)

[source,python]
----
#!/usr/bin/env python3
import linuxcnc
c = linuxcnc.command()

# Increase speed of spindle 0 by 100rpm. Spindle must be on first.
c.spindle(linuxcnc.INCREASE)

# Increase speed of spindle 2 by 100rpm. Spindle must be on first.
c.spindle(linuxcnc.SPINDLE_INCREASE, 2)

# Set speed of spindle 0 to 1024 rpm.
c.spindle.(linuxcnc.SPINDLE_FORWARD, 1024)

# Set speed of spindle 1 to -666 rpm.
c.spindle.(linuxcnc.SPINDLE_REVERSE, 666, 1)

# Stop spindle 0.
c.spindle.(linuxcnc.SPINDLE_OFF)

# Stop spindle 0 explicitly.
c.spindle.(linuxcnc.SPINDLE_OFF, 0)
----

`spindleoverride(float [, int])`::
  Set spindle override factor. Defaults to spindle 0.

`state(int)`::
  Set the machine state. Machine state should be STATE_ESTOP, STATE_ESTOP_RESET, STATE_ON, or STATE_OFF.

`task_plan_sync()`::
  On completion of this call, the VAR file on disk is updated with
  live values from the interpreter.

`teleop_enable(int)`::
  Enable/disable teleop mode (disable for joint jogging).

`tool_offset(int, float, float, float, float, float, int)`::
  Set the tool offset. See usage example above.

`traj_mode(int)`::
  Set trajectory mode. Mode is one of MODE_FREE, MODE_COORD, or
  MODE_TELEOP.

`unhome(int)`::
  Unhome a given joint.

`wait_complete([float])`::
  Wait for completion of the last command sent. If timeout in
  seconds not specified, default is 5 seconds. Return -1 if
  timed out, return RCS_DONE or RCS_ERROR according to command
  execution status.

== Reading the error channel

To handle error messages, connect to the error channel and
periodically poll() it.

Note that the NML channel for error messages has a queue (other than
the command and status channels), which means
that the first consumer of an error message deletes that message from
the queue; whether your another error message consumer (e.g. Axis)
will 'see' the message is dependent on timing. It is recommended to have just
one error channel reader task in a setup.

[source,python]
----
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import linuxcnc
e = linuxcnc.error_channel()

error = e.poll()

if error:
    kind, text = error
    if kind in (linuxcnc.NML_ERROR, linuxcnc.OPERATOR_ERROR):
        typus = "error"
    else:
        typus = "info"
    print(typus, text)
----

[[python:reading-ini-values]]
== Reading INI file values

Here's an example for reading values from an INI file through the
`linuxcnc.ini` object:

[source,python]
----
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# run as:
# python3 ini-example.py ~/emc2-dev/configs/sim/axis/axis_mm.ini

import sys
import linuxcnc

inifile = linuxcnc.ini(sys.argv[1])

# inifile.find() returns None if the key wasn't found - the
# following idiom is useful for setting a default value:

machine_name = inifile.find("EMC", "MACHINE") or "unknown"
print("machine name: ", machine_name)

# inifile.findall() returns a list of matches, or an empty list
# if the key wasn't found:

extensions = inifile.findall("FILTER", "PROGRAM_EXTENSION")
print("extensions: ", extensions)

# override default NML file by INI parameter if given
nmlfile = inifile.find("EMC", "NML_FILE")
if nmlfile:
    linuxcnc.nmlfile = os.path.join(os.path.dirname(sys.argv[1]), nmlfile)
----

Or for the same INI file as LinuxCNC:

[source,python]
----
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# run as:
# python3 ini-example2.py

import linuxcnc

stat = linuxcnc.stat()
stat.poll()

inifile = linuxcnc.ini(stat.ini_filename)

# See example above for usage of 'inifile' object
----

== The `linuxcnc.positionlogger` type

Some usage hints can be gleaned from
`src/emc/usr_intf/gremlin/gremlin.py`.

=== members

`npts`::
    number of points.

=== methods

`start(float)`::
  start the position logger and run every ARG seconds

`clear()`::
  clear the position logger

`stop()`::
  stop the position logger

`call()`::
  Plot the backplot now.

`last([int])`::
  Return the most recent point on the plot or None

// vim: set syntax=asciidoc:
