LinuxCNCService

Machine status, commands, waits, streams, the machine configuration and server information. The file RPCs of this service are on File management.

GetStatus

Read the current machine status.

rpc GetStatus(GetStatusRequest) returns (LinuxCNCStatus)

Request: GetStatusRequest, empty.

Response: LinuxCNCStatus

FieldTypeDescription
timestampint64Unix time in nanoseconds.
versionstringLinuxCNC’s version.
debugint32LinuxCNC’s debug flags.
taskTaskStatusTask and interpreter state.
trajectoryTrajectoryStatusMotion planner state.
positionPositionStatusCommanded, actual and probed positions and the offsets.
jointsJointStatus[]One entry per joint the machine has (trajectory.joints), in joint order.
axesAxisStatus[]Up to 9 entries, XYZABCUVW.
spindlesSpindleStatus[]One entry per spindle the machine has (trajectory.spindles).
toolToolStatusThe current tool and the tool table without empty slots; see ToolEntry.
ioIOStatusDigital and analog I/O.
gcodeGCodeStatusActive G-codes and M-codes.
limitsLimitStatuslimit_flags and homed have one entry per joint, and misc_error has the length of LinuxCNC’s own array.
errorsErrorMessage[]The newest error-channel messages the server has read (at most 20, oldest first), which depends on its error channel mode; see StreamErrors.
connection_idstringThe server connection the status was read through; see Telling servers and connections apart.

LinuxCNC’s own status always lists 16 joints and 8 spindles. The server sends only the real ones, so joints, spindles, limits.limit_flags and limits.homed can be used as they come. When LinuxCNC’s count is unusable (0, negative or too large), the server sends all 16 and 8. A 1.0 server always sent all 16 and 8; a client that also talks to one should use only the first trajectory.joints joints and trajectory.spindles spindles.

Error codes:

CodeCondition
UNAVAILABLEThe server is not connected, its LinuxCNC is gone, the status cannot be read right now, or the read failed; see Errors and reasons.
INTERNALReading or mapping the status failed in a way the server does not expect, and the message names the error.

Example (Python):

status = stub.GetStatus(linuxcnc_pb2.GetStatusRequest())
print(f"Mode: {linuxcnc_pb2.TaskMode.Name(status.task.task_mode)}")
print(f"X: {status.position.actual_position.x}")

SendCommand

Send one command to LinuxCNC.

rpc SendCommand(LinuxCNCCommand) returns (CommandResponse)

RCS_DONE means the command was dispatched, not that it finished; this holds for stops too. Follow it with WaitComplete or the status. The full rules are in Sending commands and waiting, and how stops go ahead of other commands is in Stops.

Request: LinuxCNCCommand, with one of these fields. Leave serial at 0 to have the server allocate one.

FieldTypeDescription
stateStateCommandSet the machine state: E-stop, E-stop reset, on or off.
modeModeCommandSet the mode: manual, auto or MDI.
mdiMdiCommandRun one line of G-code in MDI mode.
jogJogCommandJog an axis or a joint, or stop a jog.
homeHomeCommandHome one joint, or all with -1.
unhomeUnhomeCommandUnhome one joint, or all with -1.
spindleSpindleControlCommandStart, stop or change a spindle; see Spindle commands.
spindle_overrideSpindleOverrideCommandSet the spindle override.
brakeBrakeCommandEngage or release a spindle brake.
feedrateFeedrateCommandSet the feed override.
rapidrateRapidrateCommandSet the rapid override.
coolantCoolantCommandTurn mist and flood on or off (two LinuxCNC messages).
programProgramCommandOpen, run, pause, resume, step or abort a program.
digital_outputDigitalOutputCommandSet a digital output.
analog_outputAnalogOutputCommandSet an analog output.
override_limitsOverrideLimitsCommandOverride the limit switches.
program_optionsProgramOptionsCommandSet optional stop and block delete (two LinuxCNC messages).
maxvelMaxVelCommandSet the maximum velocity.
tool_offsetToolOffsetCommandSet a tool’s offsets in the tool table.
set_limitSetLimitCommandSet a joint’s soft limits (two LinuxCNC messages).
override_configOverrideConfigCommandEnable or disable feed override, spindle override, feed hold and adaptive feed (four LinuxCNC messages).
teleopTeleopCommandTurn teleop mode on or off.
traj_modeTrajModeCommandSet the trajectory mode: free, coordinated or teleop.
reset_interpreterResetInterpreterCommandReset the interpreter.
load_tool_tableLoadToolTableCommandReload the tool table file.
task_plan_syncTaskPlanSyncCommandSynchronize the task planner.
debugDebugCommandSet LinuxCNC’s debug level.
operator_messageOperatorMessageCommandPost an operator error, text or display message.

AutoCommand is deprecated. The message is in the proto, but LinuxCNCCommand has no field for it, so it cannot be sent. Use ProgramCommand (open, run_from_line, pause, resume, step, abort). AutoCommand and AutoCommandType will be removed in 2.0.

The server does not switch modes or teleop for you; see Modes and teleop.

Response: CommandResponse

FieldTypeDescription
serialint32The request’s serial, or the server’s own counter when it is 0; see The response serial is not LinuxCNC’s.
statusRcsStatusRCS_DONE when the command was dispatched and RCS_ERROR when it was rejected, refused or failed; see RCS_ERROR from SendCommand.
error_messagestringWhy the command got RCS_ERROR.
linuxcnc_serialoptional int32LinuxCNC’s serial for the command (the last message taken, for a multi-message command), unset with RCS_ERROR; see linuxcnc_serial.
acknowledgedoptional boolWhether a status read after the send showed the task had taken the command; see acknowledged.
not_sentboolWith RCS_ERROR, true means nothing was written to LinuxCNC, so sending again cannot run the command twice; see not_sent.
connection_idstringThe server connection that took the command, set only with linuxcnc_serial and only when the server can name it; see Telling servers and connections apart.

A stop’s answer can also have an empty connection_id; then don’t compare its serial.

Error codes:

CodeCondition
UNAVAILABLEThe server is not connected, or its LinuxCNC is gone; see Errors and reasons.

Once LinuxCNC is gone, a stop is still sent when the server uses the command helper. A command the server refuses is answered RCS_ERROR, not with a gRPC error.

Example (Python):

# This sample never takes the machine out of E-stop or turns it on: do that
# at the machine. Send nothing unless it is on and idle.
status = stub.GetStatus(linuxcnc_pb2.GetStatusRequest(), timeout=5)
if status.task.task_state != linuxcnc_pb2.STATE_ON:
    state_name = linuxcnc_pb2.TaskState.Name(status.task.task_state)
    raise SystemExit(f"The machine is not on ({state_name}); turn it on at the machine first")
if not (status.task.interp_state == linuxcnc_pb2.INTERP_IDLE
        and status.trajectory.inpos
        and abs(status.trajectory.current_vel) < 1e-6):
    raise SystemExit("The machine is busy; try again once it is idle")

# Switch to manual mode
cmd = linuxcnc_pb2.LinuxCNCCommand()
cmd.mode.mode = linuxcnc_pb2.MODE_MANUAL
response = stub.SendCommand(cmd, timeout=15)

if response.status == linuxcnc_pb2.RCS_ERROR:
    print(f"Error: {response.error_message}")

If LinuxCNC’s task does not answer, a command takes up to 5 seconds per LinuxCNC message; see A LinuxCNC task that does not respond.

Values the server rejects

The server checks a command before it sends anything. A command that fails a check gets RCS_ERROR with the reason in error_message, no linuxcnc_serial, and nothing is sent. Only the fields the requested operation uses are checked, so a jog stop is never refused over its velocity and a spindle stop never over its speed.

Numbers must be finite (not NaN or infinite): the jog velocity (continuous and incremental jogs) and increment (incremental jogs), the spindle speed (forward and reverse), the feed, rapid and spindle override scale, the maximum velocity, the tool offset values (z_offset, x_offset, diameter, front_angle, back_angle), the analog output value and both set_limit limits.

The spindle speed for forward and reverse, the three override scales and the maximum velocity must also be zero or more. A jog velocity may be negative: its sign is the jog direction, in machine units per second.

set_limit needs min_limit below max_limit, otherwise neither limit is sent. brake takes BRAKE_ENGAGE or BRAKE_RELEASE; any other value is rejected, not taken as a release. A multi-message command (set_limit, override_config) is checked completely before its first message is sent.

An MDI command must not be empty or only whitespace, must not contain a null byte, and may have at most 10000 characters. The name of a program open is checked like a file name: one outside the NC files directory or with a symbolic link loop is rejected.

Joint, axis and spindle numbers in jog, home, unhome, spindle, spindle override, brake, set_limit and override_config commands must exist. A negative number is rejected, except -1 for home and unhome, which means all joints. For a command that is not a stop, joints and spindles are counted as the machine has them (trajectory.joints, trajectory.spindles). A stop is checked against fixed bounds instead (16 joints, 9 axes, 8 spindles), so it is never refused over a status read; see Stops. An axis number is checked against the 9 axis slots (0 = X … 8 = W), not against axis_mask, so LinuxCNC decides what to do with an axis the configuration lacks.

Spindle commands

SpindleControlCommand carries a command, the spindle number (default 0, used by every command), and for forward and reverse a speed and wait_for_at_speed.

commandEffect
SPINDLE_CMD_FORWARD, SPINDLE_CMD_REVERSETurn the spindle on at speed, which must be zero or more because the command gives the direction.
SPINDLE_CMD_OFFStop the spindle.
SPINDLE_CMD_INCREASE, SPINDLE_CMD_DECREASESend LinuxCNC’s SPINDLE_INCREASE or SPINDLE_DECREASE.
SPINDLE_CMD_CONSTANTSend LinuxCNC’s SPINDLE_CONSTANT.

wait_for_at_speed is passed to LinuxCNC when it is true.

WaitComplete

Wait until LinuxCNC has finished a command, or until the timeout.

rpc WaitComplete(WaitCompleteRequest) returns (CommandResponse)

Without linuxcnc_serial it waits on the latest command sent through the server by any client. What each answer proves is in WaitComplete.

Request: WaitCompleteRequest

FieldTypeDescription
serialint32Ignored, and only echoed back in the response.
timeoutdoubleSeconds to wait; 0, negative or NaN means 5, and infinity waits until the command finishes.
linuxcnc_serialoptional int32Wait on this command: a linuxcnc_serial this server issued on its current connection to LinuxCNC.

Response: CommandResponse, with connection_id always empty.

StatusMeaning
RCS_DONELinuxCNC has finished the command or echoed a later one, or nothing was sent through this server; confirm a move from a fresh status.
RCS_ERRORThe command failed, or the server cannot tell (an unknown serial, a reconnect, a lost outcome, LinuxCNC gone or unreadable), and error_message says which; see WaitComplete.
RCS_EXECThe wait ended before the server saw the command finish, which does not prove it is still running.

Error codes:

CodeCondition
UNAVAILABLEThe server is not connected, or its LinuxCNC is gone, when the call starts; see Errors and reasons.
RESOURCE_EXHAUSTEDToo many streams and WaitComplete calls are in progress; see Thread pool.

A wait already in progress when LinuxCNC is found gone answers RCS_ERROR, not UNAVAILABLE.

The example sends nothing unless the machine meets the MDI preconditions, and reports success only when a fresh status shows the move done.

Example (Python):

# This sample only checks: it never takes the machine out of E-stop, turns
# it on, homes it or switches modes. The tutorial shows the full sequence.
status = stub.GetStatus(linuxcnc_pb2.GetStatusRequest(), timeout=5)
if not (status.task.task_state == linuxcnc_pb2.STATE_ON
        and all(joint.homed for joint in status.joints)
        and status.task.interp_state == linuxcnc_pb2.INTERP_IDLE
        and status.trajectory.inpos
        and abs(status.trajectory.current_vel) < 1e-6
        and status.task.task_mode == linuxcnc_pb2.MODE_MDI):
    raise SystemExit("The machine is not on, homed, idle and in MDI mode; nothing sent")

cmd = linuxcnc_pb2.LinuxCNCCommand()
cmd.mdi.command = "G0 X10 Y10"
sent = stub.SendCommand(cmd, timeout=15)
if sent.status != linuxcnc_pb2.RCS_DONE:
    outcome = "not sent" if sent.not_sent else "may have been sent"
    raise SystemExit(f"Refused, {outcome}: {sent.error_message}")

# Wait on this command only, on the connection the status was read through.
if not (sent.HasField("linuxcnc_serial") and sent.connection_id
        and sent.connection_id == status.connection_id):
    raise SystemExit("Sent, but its outcome cannot be waited on; read the status")
request = linuxcnc_pb2.WaitCompleteRequest(
    linuxcnc_serial=sent.linuxcnc_serial, timeout=30.0)
response = stub.WaitComplete(request, timeout=35.0)
if response.status == linuxcnc_pb2.RCS_EXEC:
    raise SystemExit("Wait timed out; the move may still be running")
if response.status != linuxcnc_pb2.RCS_DONE:
    raise SystemExit(f"Wait failed: {response.error_message}")

# RCS_DONE: LinuxCNC has finished the move or taken a later command from
# any client, an abort included. Only a fresh status confirms the move.
status = stub.GetStatus(linuxcnc_pb2.GetStatusRequest(), timeout=5)
position = status.position

# The work position, assuming no XY rotation and a program in machine units
def work_position(axis):
    return (getattr(position.actual_position, axis)
            - getattr(position.g5x_offset, axis)
            - getattr(position.g92_offset, axis)
            - getattr(position.tool_offset, axis))

if not (status.task.task_state == linuxcnc_pb2.STATE_ON
        and status.task.interp_state == linuxcnc_pb2.INTERP_IDLE
        and status.trajectory.inpos
        and abs(status.trajectory.current_vel) < 1e-6
        and abs(work_position("x") - 10) < 0.01
        and abs(work_position("y") - 10) < 0.01):
    raise SystemExit("The move is not confirmed; read the status")
print("Moved to X10 Y10")

StreamStatus

Receive the machine status at a fixed interval.

rpc StreamStatus(StreamStatusRequest) returns (stream LinuxCNCStatus)

Request: StreamStatusRequest

FieldTypeDescription
interval_msint32Milliseconds between updates; 0 or less means 100, and values above 60000 are treated as 60000.

Response: a stream of LinuxCNCStatus, as in GetStatus.

The stream ends as soon as the client cancels. While LinuxCNC’s task is stopped holding the status buffer, the stream stays open and sends nothing; updates resume once the status can be read again (see A task stopped while it holds the status).

Error codes:

CodeCondition
UNAVAILABLEThe server is not connected, its LinuxCNC is gone, or LinuxCNC can no longer be read; see Errors and reasons.
INTERNALReading or mapping the status failed in a way the server does not expect, after the statuses already sent.
RESOURCE_EXHAUSTEDToo many streams and WaitComplete calls are in progress; see Thread pool.

Example (Python):

request = linuxcnc_pb2.StreamStatusRequest(interval_ms=100)

for status in stub.StreamStatus(request):
    pos = status.position.actual_position
    print(f"X={pos.x:.3f} Y={pos.y:.3f} Z={pos.z:.3f}")

StreamErrors

Receive messages from LinuxCNC’s error channel: operator errors, texts and displays, and NML errors.

rpc StreamErrors(StreamErrorsRequest) returns (stream ErrorMessage)

Reading the error channel takes messages away from the machine’s GUI: each message goes to one reader only. With the default --error-channel auto the server reads only while a StreamErrors client is connected when the INI file’s [DISPLAY]DISPLAY names a known GUI that reads errors, and all the time otherwise. It does not detect whether a GUI is running, and it reads all the time while the INI read is deferred. See Error messages and the GUI.

Request: StreamErrorsRequest

FieldTypeDescription
replay_bufferedboolIf true, the stream starts with the messages the server holds (the newest 256), oldest first; if false, only new messages are sent.

Response: a stream of ErrorMessage

FieldTypeDescription
typeErrorTypeOPERATOR_ERROR, NML_ERROR and so on.
messagestringThe message text.
timestampint64When the server read the message, in Unix nanoseconds.
sequenceint64The order the server read messages in, from 1, the same here and in LinuxCNCStatus.errors.
connection_idstringThe server connection whose error channel the message came from; see Telling servers and connections apart.

Every subscriber receives every message. One that falls more than 256 messages behind loses the older ones without an error; a jump in sequence is the only sign. Use sequence to drop duplicates between the stream, status.errors and a replay. The response headers confirm that the subscription is registered. Messages can still be lost after that, to the 256-message buffer or to the stream ending with linuxcnc-gone.

Error codes:

CodeCondition
FAILED_PRECONDITIONThe server runs with --error-channel off.
UNAVAILABLEThe server is not connected, or its LinuxCNC is gone; see Errors and reasons.
INTERNALThe stream failed with an unexpected I/O error (Stream failed: ...).
RESOURCE_EXHAUSTEDToo many streams and WaitComplete calls are in progress; see Thread pool.

Example (Python):

request = linuxcnc_pb2.StreamErrorsRequest(replay_buffered=True)
for error in stub.StreamErrors(request):
    print(f"#{error.sequence} {error.message}")

GetMachineConfig

Read the machine’s configuration: kinematics, which joint drives which axis, limits, velocities and units.

rpc GetMachineConfig(GetMachineConfigRequest) returns (MachineConfig)

Request: GetMachineConfigRequest, empty.

Response: MachineConfig. The Source column says whether a value comes from the live status or the INI file.

FieldTypeSourceDescription
ini_filenamestringstatusThe INI file LinuxCNC was started with.
ini_readableboolFalse if the server could not read that file, or its values no longer cover the status’s joints and axes.
machine_namestringINI[EMC]MACHINE.
kinematicsstringINI[KINS]KINEMATICS in full, such as trivkins coordinates=XYYZ kinstype=BOTH.
kinematics_modulestringINIThe first word of kinematics, such as trivkins.
kinematics_typeKinematicsTypestatusIdentity, forward only, inverse only or both.
coordinatesstringINI[TRAJ]COORDINATES in upper case without spaces.
axis_maskint32statusBit 0 = X … bit 8 = W.
joint_count, spindle_countint32statusThe number of joints and spindles GetStatus lists.
joint_axis_mapping_knownboolTrue if the server could work out which axis each joint drives.
linear_units, angular_unitsdoublestatusMachine units per mm and per degree.
linear_units_namestringstatusmm, inch or cm, and empty for anything else.
angular_units_namestringstatusdegree, radian or grad, and empty for anything else.
max_linear_velocity, default_linear_velocitydoubleINI[TRAJ], in machine units per second.
max_angular_velocity, default_angular_velocitydoubleINI[TRAJ].
lathe, back_tool_latheboolINI[DISPLAY]LATHE and [DISPLAY]BACK_TOOL_LATHE, true only for 1, true or yes in any case.
max_feed_overridedoubleINI[DISPLAY]MAX_FEED_OVERRIDE, where 1.2 means 120%.
min_spindle_override, max_spindle_overridedoubleINI[DISPLAY].
nc_files_directorystringserverThe directory the file RPCs and program open work in.
jointsrepeated JointConfigOne per joint.
axesrepeated AxisConfigOne per axis in axis_mask.

AXIS counts any non-empty LATHE as on, so LATHE = 0 is a lathe in AXIS but lathe is false here.

JointConfig:

FieldTypeSourceDescription
joint_numberint32The joint’s number.
joint_typeJointTypestatusLinear or angular.
axis_letterstringINIThe axis this joint drives, empty if the mapping is not known or the joint drives no axis.
min_limit, max_limitdoublestatusSoft limits in machine units.
max_velocity, max_accelerationdoubleINI[JOINT_n].
home_sequenceoptional int32INI[JOINT_n]HOME_SEQUENCE, unset if the INI has none.
unitsdoublestatusJoint units per mm or per degree.

AxisConfig:

FieldTypeSourceDescription
axis_numberint320 = X … 8 = W.
letterstringX, Y and so on.
min_limit, max_limitdoublestatusSoft limits in machine units.
max_velocity, max_accelerationdoubleINI[AXIS_<letter>].
jointsrepeated int32INIThe joints that drive this axis, empty if the mapping is not known or none does.

With trivkins, joint N drives the Nth letter of the coordinates= parameter, or of XYZABCUVW without one. A lathe with trivkins coordinates=XZ has joint 1 on Z; a gantry with coordinates=XYYZ has joints 1 and 2 on Y. For any other kinematics module joint_axis_mapping_known is false, and axis_letter and joints are empty.

Extra joints (num_extrajoints= on the [EMCMOT]EMCMOT line) are the last joints. They have an empty axis_letter and are in no axis’s joints; trajectory.num_extrajoints gives their number. Jogging an axis never moves one: after homing LinuxCNC drives it from the HAL pin joint.N.posthome-cmd.

The server reads the INI file once per connection, and not while the machine is in cycle; see What the server reads from the INI file. INI values are the configured ones: a limit changed with set_limit shows in the status-based limits, a velocity changed in HAL nowhere here.

A value missing from the INI is 0, empty, or unset for home_sequence, and so is a value the response cannot carry (nan, inf, 1e999, a home_sequence outside int32), with a warning in the log. If the file cannot be read, only the status fields are filled until the server’s next connection, so restart the server after fixing the file. Velocities are per second and accelerations per second squared, in machine units.

Error codes:

CodeCondition
UNAVAILABLEThe server is not connected, its LinuxCNC is gone, or the status cannot be read; see Errors and reasons.
FAILED_PRECONDITIONThe INI file has not been read because the machine has been in cycle since the server connected (reason ini-not-read-in-cycle), so call again once it is idle.
INTERNALThe NC files directory could not be resolved (a symbolic link loop), or the status read failed unexpectedly, and the message names the error.

Example (Python):

config = stub.GetMachineConfig(linuxcnc_pb2.GetMachineConfigRequest())
print(f"{config.machine_name}: {config.kinematics} in {config.linear_units_name}")
for joint in config.joints:
    # No letter: an extra joint if the mapping is known, otherwise unknown
    print(f"joint {joint.joint_number} -> {joint.axis_letter or '-'} "
          f"[{joint.min_limit}, {joint.max_limit}]")

# Find the joints to jog for the Y axis on an unhomed machine
y_joints = [j.joint_number for j in config.joints if j.axis_letter == "Y"]

GetServerInfo

Read the server’s version, whether it is connected to LinuxCNC, and LinuxCNC’s version.

rpc GetServerInfo(GetServerInfoRequest) returns (ServerInfo)

Request: GetServerInfoRequest, empty.

Response: ServerInfo

FieldTypeDescription
server_versionstringThe linuxcnc-grpc package version, such as 1.1.0, which is also the API version.
linuxcnc_connectedboolTrue once the server has connected to LinuxCNC, and false while it waits or once LinuxCNC is gone.
linuxcnc_versionstringThe version the LinuxCNC Python module on the server’s machine reports, such as 2.9.4, or empty.
error_channel_modestringWhen the server reads the error channel now: on-demand, always or off; see Error messages and the GUI.
stops_not_takenint32How many stops the server wrote that no status read has shown taken, plus one for each lost stop; other commands are held while it is above 0, see stops_not_taken.
server_instancestringA random value made when the server starts, so a different value means a different server.
connection_idstringThe server’s current connection to LinuxCNC, empty while not connected and once LinuxCNC is gone; see Telling servers and connections apart.

A server started with --error-channel auto reports auto until it has connected, then the mode it chose (always meanwhile if it connected in cycle). server_instance and connection_id are opaque: compare them, do not parse them. linuxcnc_version is filled while not connected too; while connected it equals LinuxCNCStatus.version, except that an unknown version is empty here and "unknown" there.

GetServerInfo answers while the server waits for LinuxCNC and never waits behind a command, so it is safe to call often. It still needs a thread of the general pool (see Thread pool), and an INI read or a status read with --status-read-timeout off delays it, so a very short deadline can expire on a healthy server.

linuxcnc_connected is the server’s connection state, the same the health service reports. It does not show a crashed LinuxCNC (see What happens when LinuxCNC stops). After LinuxCNC exits it turns false within about 2 seconds, or about 10 seconds when only the status breaks (see When the server finds its LinuxCNC gone).

A 1.0 server answers UNIMPLEMENTED; see Telling servers and connections apart.

Example (Python):

info = stub.GetServerInfo(linuxcnc_pb2.GetServerInfoRequest())
print(f"Server {info.server_version}, LinuxCNC {info.linuxcnc_version or '?'}")
if not info.linuxcnc_connected:
    print("The server is waiting for LinuxCNC")