The linuxcnc-grpc server runs on your LinuxCNC machine and exposes both LinuxCNCService and HalService over gRPC.

Security warning: the server has no authentication and no TLS. Anyone who can reach the port can command the machine: jog it, start the spindle, run or upload a program.

  • Preferred: bind to localhost with --host 127.0.0.1 and reach it from other machines through an SSH tunnel (ssh -N -L 50051:127.0.0.1:50051 user@cnc-machine).
  • Otherwise: only use --host 0.0.0.0 on a trusted, isolated LAN. Never expose the port to the internet or to a shared network.

The examples below use --host 0.0.0.0 for brevity, and it is the default. See Security Considerations.

Requirements

  • Linux with LinuxCNC 2.9 or newer installed (it does not have to be running when the server starts)
  • Python 3.10+
  • Network access to the machine (for remote clients)

Supported LinuxCNC versions: 2.9 and newer. This is the one place the documentation says why.

  • The HAL service lists pins, signals and parameters with hal.get_info_pins, hal.get_info_signals and hal.get_info_params, which LinuxCNC 2.8’s hal module does not have. On 2.8 the server refuses to start, with LinuxCNC 2.9 or newer is required: this LinuxCNC's hal module has no get_info_pins, get_info_signals or get_info_params (LinuxCNC 2.8 and older). 1.0 needed these functions too.
  • The server tells its commands apart by LinuxCNC’s command serial (linuxcnc.command().serial). A LinuxCNC whose Python module has no such serial is refused when the server connects: LinuxCNC 2.9 or newer is required: this LinuxCNC's Python module has no command.serial. With --require-linuxcnc the server exits at start; otherwise it logs the error and stays NOT_SERVING, and serve() stops the server and raises UnrecoverableConnectionError (linuxcnc-grpc exits with status 1), as for the other conditions that need a restart.

Installation

pip install linuxcnc-grpc
# or with uv
uv pip install linuxcnc-grpc

Basic Usage

Start LinuxCNC first, then start the gRPC server:

linuxcnc-grpc --host 0.0.0.0 --port 50051

Or run as a Python module:

python -m linuxcnc_grpc.server --host 0.0.0.0 --port 50051

Command Line Options

OptionDefaultDescription
--host0.0.0.0Address to bind to. Use 127.0.0.1 for local-only access
--port50051Port number to listen on
--nc-files$LINUXCNC_NC_FILES, else /home/linuxcnc/linuxcnc/nc_filesDirectory for G-code file operations
--error-channelautoWhen to read LinuxCNC’s error channel: auto, on-demand, always or off. auto reads as on-demand when the INI file’s [DISPLAY]DISPLAY is a GUI that reads LinuxCNC’s errors itself, and as always otherwise (also until the INI file has been read, when the server connected while the machine was in cycle). See Error messages and the GUI
--require-linuxcncoffExit with an error if LinuxCNC is not running at startup, as versions up to 1.0 did. See Starting before LinuxCNC
--status-read-timeout SECONDS|off0.1How long a read of LinuxCNC’s status or error buffer waits for the buffer’s lock: 0.01 to 3600 seconds, or off, which uses LinuxCNC’s own NML file unchanged, as 1.0 did. See A task stopped while it holds the status
--in-process-commandsoffSend commands to LinuxCNC from the server’s own process, as versions up to 1.0 did, instead of from its command helper process. See A LinuxCNC task that does not respond
--debugoffEnable debug logging

Auto-Start with LinuxCNC

Method 1: HAL File

Add to your machine’s HAL file (e.g., your_machine.hal):

# Start gRPC server
loadusr linuxcnc-grpc --host 0.0.0.0 --port 50051

Method 2: Dedicated HAL File

Create a separate grpc-server.hal file:

# grpc-server.hal
loadusr linuxcnc-grpc --host 0.0.0.0 --port 50051

Reference it in your INI file:

[HAL]
POSTGUI_HALFILE = grpc-server.hal

Using POSTGUI_HALFILE ensures the server starts after the GUI, which is useful for certain configurations.

Method 3: systemd Service

Create /etc/systemd/system/linuxcnc-grpc.service:

[Unit]
Description=LinuxCNC gRPC Server

[Service]
Type=simple
ExecStart=/usr/local/bin/linuxcnc-grpc --host 0.0.0.0 --port 50051
Restart=always
RestartSec=2
User=your-username

[Install]
WantedBy=multi-user.target

Enable and start:

sudo systemctl daemon-reload
sudo systemctl enable linuxcnc-grpc
sudo systemctl start linuxcnc-grpc

The service can start at boot, before LinuxCNC: the server waits for LinuxCNC and connects when it comes up. Use Restart=always, not on-failure: when LinuxCNC shuts down it stops the server too, with a normal exit, and systemd has to start it again for the next LinuxCNC session (see Starting before LinuxCNC). Run it as the same user that runs LinuxCNC.

Keep RestartSec=2; do not go below about half a second. When LinuxCNC shuts down or is restarted it stops the server, and systemd starts the next one after RestartSec (100 ms if the unit does not set it). A server started that soon comes up while the old LinuxCNC is still shutting down, and can attach to its HAL or its status instead of the next LinuxCNC’s. Measured on the LinuxCNC 2.9 simulator with earlier versions of the server: with a delay of 0, 0.05 or 0.1 seconds, 15 of 19 restarts left a server that answered wrongly (most of them with a status that never worked, see Starting before LinuxCNC). Such a server now notices and exits with status 1 (see When the server finds its LinuxCNC gone), and systemd starts another: with this version, 24 of 24 restarts at 0 to 0.1 seconds ended with a server that works, 6 of them after one such extra round. At 2 seconds 10 of 10 were clean the first time. Each extra round is a restart, and systemd stops restarting a unit that fails 5 times within 10 seconds (its default StartLimitBurst and StartLimitIntervalSec).

The server runs one child process, its command helper (see A LinuxCNC task that does not respond). The unit needs nothing for it. When systemd stops the service it sends SIGTERM to every process of the service; the helper ignores it and ends as soon as the server has closed the pipe to it, or once it has finished a send that was under way.

Starting before LinuxCNC

The server no longer needs LinuxCNC to be running when it starts. If LinuxCNC is not there, the server starts anyway and waits:

  • The gRPC health service reports NOT_SERVING for "" and linuxcnc.LinuxCNCService.
  • RPCs that need LinuxCNC (GetStatus, SendCommand, WaitComplete, StreamStatus, StreamErrors, ResolveFile, GetMachineConfig) fail with UNAVAILABLE. Two of them check something else first: StreamErrors on a server started with --error-channel off fails with FAILED_PRECONDITION, and ResolveFile with an invalid file name fails with INVALID_ARGUMENT.
  • The file RPCs (UploadFile, ListFiles, ReadFile, DeleteFile) work, so programs can be uploaded before LinuxCNC is up.
  • GetServerInfo works and reports linuxcnc_connected = false, so a client can tell a server that is waiting for LinuxCNC from one that is not there.
  • The HAL service answers, with no pins until LinuxCNC has loaded its HAL configuration.

The server looks for LinuxCNC after 1, 2 and 4 seconds and then every 5 seconds, connects as soon as it is there, and health turns to SERVING. “There” means that LinuxCNC’s status can be read twice in a row from a new process: during a LinuxCNC start the first read can succeed while LinuxCNC’s tool table memory does not exist yet, and a process in that state can never read the status again (measured on the 2.9 simulator). On the LinuxCNC 2.9 simulator the server connected within a few seconds of LinuxCNC starting, and the full end-to-end test suite passed against a server that had been started first.

Pass --require-linuxcnc to get the old behaviour: the server exits with status 1 if LinuxCNC is not running. Use it where something else is watching for that exit.

The server exits with an error if it finds it can no longer connect, and also when it finds that the LinuxCNC it was attached to has shut down or been restarted (see When the server finds its LinuxCNC gone). If LinuxCNC goes away in the moment between the server’s check and its connection attempt, the attempt fails, and after that LinuxCNC’s Python module cannot connect again from the same process, even once LinuxCNC is back. The server tries 3 times in all, then logs an error, stops and exits with status 1. A supervisor such as systemd with Restart=always starts a fresh process, which connects normally. Without a supervisor, start the server again by hand.

The server’s command helper process (see A LinuxCNC task that does not respond) makes its own connection check when it starts. If it fails while the server’s check passes (LinuxCNC went away in between), the server process itself has tried nothing and is not affected: it stays disconnected and tries again at the usual intervals, also at startup. After 10 such failures in a row it gives up in the same way as above, with an error that says the command helper could not be started, so the server cannot send commands. For create_server() this is the same on_unrecoverable call, with the same caveat: it can cross with a shutdown.

A program that builds the server with create_server() instead of running linuxcnc-grpc gets the error in the log, and can pass on_unrecoverable=callback to be told: the callback is called once, from a background thread, with a description, for whichever of these conditions comes first. The server stays up and NOT_SERVING until the program stops it; only a new process can connect. The callback is not called once the server is being stopped, but the two can cross: a call can arrive at the moment the program stops the server, or just after. Ignore it once you have decided to stop.

create_server() binds the port as its last step, so if it raises, no port is held. A server it returned keeps its port until it has been started and stopped, or the process exits: stopping a gRPC server that was never started does not release the port.

What happens when LinuxCNC stops

A normal LinuxCNC shutdown stops the server too. The server owns a HAL component (grpc-hal-service), and LinuxCNC unloads every HAL component when it shuts down, which signals the server to exit. That was already the case in 1.0. So a server meant to outlive LinuxCNC sessions needs a supervisor that starts it again, such as systemd with Restart=always. A server started with loadusr from a HAL file simply starts and stops with LinuxCNC.

A crashed LinuxCNC is not detected. Measured on the 2.9 simulator by killing the task processes with kill -9: LinuxCNC’s status memory stays in place, so the server keeps running, keeps returning the last status, and health stays SERVING. A command sent in that state blocks for about 5 seconds and then reports RCS_DONE with acknowledged false (LinuxCNC’s own send timeout does not raise an error; see A LinuxCNC task that does not respond); a WaitComplete on it never completes and returns RCS_EXEC at its timeout. LinuxCNC’s Python interface exposes no heartbeat, so the server has no cheap way to tell a dead task from an idle one. Clients that need to know should watch for a WaitComplete that times out on a command that should be quick. A task that is frozen (stopped in a debugger, say) is not mistaken for a LinuxCNC that is gone either: measured, 30 seconds of a task stopped with SIGSTOP, and 30 seconds after a kill -9 of the task, left the server running. The next start of LinuxCNC after a crash cleans up HAL, which normally stops the server just as a normal shutdown does.

When the server finds its LinuxCNC gone

The server does not reconnect to a LinuxCNC that was restarted: LinuxCNC’s Python module, once connected in a process, cannot be trusted with a new LinuxCNC there, so the server stops instead and a supervisor starts a fresh process. It reconnects in one case only: when a status read in GetStatus or StreamStatus raises LinuxCNC’s own error (linuxcnc.error) other than the status read timeout, which is rare (a read that times out replaces the status object instead, see A task stopped while it holds the status). That reconnect gives up once the server has found its LinuxCNC gone; if none of the checks below has fired, it can reach a LinuxCNC that started again. A server that lives on across a LinuxCNC shutdown or restart (because a supervisor started it too soon, see Method 3: systemd Service, or because a program that embeds it does not end on SIGTERM) used to give wrong answers. It now looks for that and stops. It counts the LinuxCNC as gone when any of these holds:

  • The shared memory it is attached to was removed. LinuxCNC keeps its status, command and error channels and HAL in System V shared memory and removes them when it shuts down. The server knows LinuxCNC’s segments by the keys in the NML file and HAL’s fixed keys; if it cannot read the NML file it logs a warning, and a removed segment that matches only LinuxCNC’s usual keys is then logged but does not stop it. On Linux the server compares the segments it has attached (/proc/self/maps) with the ones that exist (/proc/sysvipc/shm). It looks once after connecting, before every command that is not a stop, and every 2 seconds in the background, also when no client is connected. A stop makes no check of its own, so that nothing delays it: it goes through a newly started command helper once the server has found its LinuxCNC gone. Where /proc cannot be read the check is skipped.
  • The status channel fails for good. Five status reads in a row, over at least 2 seconds, fail with an error other than LinuxCNC’s own linuxcnc.error. Measured, a server that connected while LinuxCNC was starting got SystemError from every status read and never recovered. The server now waits for a status that can be read twice before it connects (see Starting before LinuxCNC), so this is a backstop. The background check reads the status every 2 seconds too, so an idle server notices within about 10 seconds.
  • The status does not belong to the LinuxCNC that took a command. On one LinuxCNC the echo serial read before a send is always behind the serial the send gets (LinuxCNC hands out command serials from one counter for all clients). If it is already at or past it, the status is another LinuxCNC’s.

A crashed or frozen task is none of these: its shared memory stays in place.

The server leaves the restarted LinuxCNC intact. LinuxCNC removes its shared memory when it shuts down, but not the semaphores of its channels, and the next LinuxCNC uses the same ones. A process still attached to the old channels removes those semaphores when its channel objects are destroyed, and then no program can send the new LinuxCNC a command, read its status or its errors until LinuxCNC is restarted again (measured on the simulator with separate Python clients; it applies to any program that uses those channels). The server therefore never destroys a LinuxCNC channel it has created, also when it stops without having noticed anything, and its command helper and its check for a running LinuxCNC end without destroying theirs, so stopping the server is safe (measured: a server holding the old channels that stopped normally, with and without having found its LinuxCNC gone, left the restarted LinuxCNC working for every client). Each kept channel costs a few tens of kilobytes until the process ends. HAL is not affected in this way. A program of your own that uses LinuxCNC’s Python module and lives on across a LinuxCNC restart has the same problem.

Then the server logs an error, turns every health service to NOT_SERVING, and stops. linuxcnc-grpc exits with status 1, so a supervisor starts a fresh process, which connects to the LinuxCNC that is running. Until it has stopped:

  • The RPCs that need LinuxCNC, and every HAL RPC, fail with UNAVAILABLE and the trailing metadata entry linuxcnc-grpc-reason: linuxcnc-gone. Open StreamStatus, StreamErrors and HAL streams end the same way at once, and StreamErrors sends no message read before that. A WaitComplete already waiting answers RCS_ERROR, because the status says nothing about the command any more.
  • A command whose messages were being sent sends no further message (a coolant command whose first message was in flight does not send its second); it answers RCS_ERROR with not_sent false, because part of it went out.
  • A command that only stops something (E-stop, machine off, program abort and pause, jog stop, spindle off) is still sent, through a command helper started for it, which attaches to the LinuxCNC that is running now; it gets RCS_ERROR with not_sent true if there is none. Its acknowledged is unset. A jog stop or spindle off is checked only against the largest joint and spindle numbers LinuxCNC has at all (0 to 15, 0 to 7), since the status may not be readable any more and a restarted LinuxCNC may have more joints or spindles than the old one. With --in-process-commands it is refused like every other command, because the server’s own command channel belongs to the LinuxCNC that is gone.
  • GetServerInfo reports linuxcnc_connected = false. The file RPCs keep working.

A program that uses create_server() gets the on_unrecoverable call described above and should stop the server and start a new process.

While waiting for LinuxCNC, each check starts a short-lived Python process (the LinuxCNC Python module cannot be asked safely from inside the server while LinuxCNC is down). It took 7 ms on the simulator; the cost on a slow controller PC has not been measured. The checks stop once the server has connected.

A LinuxCNC task that does not respond

LinuxCNC’s task process (milltask) takes the commands that clients send. If it stops answering (it hangs, is stopped in a debugger, or does not get the CPU), commands behave as described here. Everything in this section was measured on the LinuxCNC 2.9.4 simulator with the task process frozen by SIGSTOP; the numbers are from that machine.

A command waits up to 5 seconds per LinuxCNC message. LinuxCNC’s Python call that sends a command writes it to LinuxCNC’s command queue and then waits for the task to confirm it, for at most 5 seconds (a fixed value built into LinuxCNC). After that it returns without an error. So SendCommand answers after about 5 seconds (5.01 s measured), or 10 seconds for a command sent as two LinuxCNC messages such as coolant (10.02 s), with RCS_DONE, a linuxcnc_serial and acknowledged false. If the task was stopped while it held the status buffer (see A task stopped while it holds the status), the answer comes after 5.0 to 5.1 s with acknowledged unset, since the status cannot be read to tell.

The command is not withdrawn. It stays in LinuxCNC’s queue and runs when the task runs again, as long as that LinuxCNC is not shut down or restarted meanwhile: a mode change sent to the frozen task took effect within about 35 ms of the task being continued, and so did two commands queued behind each other, in order. A client deadline does not withdraw a command either. A SendCommand that has reached its turn is carried out even if its client has given up meanwhile; only a command still waiting for its turn is dropped when its client goes away (unless it only stops something, see below).

Commands are sent one at a time, stops first. The server sends one command, with all its messages, before it starts the next. When that one is done it sends a waiting stop (E-stop, machine off, program abort and pause, jog stop, spindle off) if there is one, and otherwise the command that has waited longest. A command that arrives while another waits for the task waits for its turn: a feed override sent 0.5 s after a mode change returned after 9.5 s, both with acknowledged false. A command waiting its turn is answered RCS_ERROR with not_sent true, without being sent, if its client goes away, the server stops or a stop arrives; a stop is always sent. What a stop changes for the other commands is described in Stops go first. Every waiting command occupies one of the threads of the server’s SendCommand pool (16 by default, see Thread Pool). Do not make the server the machine’s only way to stop: the E-stop chain of a machine belongs in its hardware and HAL configuration.

The rest of the server keeps answering. LinuxCNC’s send call waits without letting any other Python thread of the process run. A server that made that call itself stalled completely: status, health, file and HAL calls were all answered about 4.5 seconds late. The server therefore sends commands from a separate process, its command helper, and waits for the helper’s answer in a way that lets the other threads run. With a send blocked for 5 seconds, GetStatus, GetServerInfo, the health check, ListFiles and HAL QueryPins answered in 3 to 16 ms, and StreamStatus at 100 ms kept sending an update every 0.10 to 0.11 s. A WaitComplete with a 2-second timeout made meanwhile waited for the command being sent and answered RCS_EXEC after 2.0 s, as for any command still in progress (see WaitComplete). The same scenario without the helper (--in-process-commands): every one of those calls answered when the send returned, 4.5 s late, and the status stream sent nothing for 3 seconds. The helper costs a command a few milliseconds at most: the medians of 100 commands with and without it were 50 and 49 ms for a mode change and 29 and 24 ms for a feed override.

What acknowledged tells. CommandResponse.acknowledged is set on every command that was dispatched:

  • true: a status read made after the send returned showed the command’s serial echoed. The task has taken the command; it may still be executing it.
  • false: the command was written to LinuxCNC’s queue, but the task had not taken it after LinuxCNC’s 5-second wait. The task is not answering. The command runs whenever the task does, as long as that LinuxCNC is not shut down or restarted first; read the status (task.echo_serial_number reaching linuxcnc_serial, then the state you expect) before you rely on it or send it again. The server logs a warning.
  • unset: the server cannot tell (nothing was dispatched; no good status read was made after the send: the read failed; the server reconnected to LinuxCNC between the send and the read; or the server’s status belongs to another LinuxCNC than the one that took the command; see When the server finds its LinuxCNC gone).

RCS_DONE keeps its meaning, “dispatched”, for stops too. For a command sent as several LinuxCNC messages, acknowledged describes the last one.

The command helper process. The server starts it when it connects to LinuxCNC. It shows in ps as a child of the server:

/path/to/python /path/to/site-packages/linuxcnc_grpc/command_helper_process.py --nml-file /tmp/linuxcnc-grpc-nml-XXXXXXXX/linuxcnc.nml

(the same Python interpreter as the server; --nml-file names the server’s copy of LinuxCNC’s NML file, see A task stopped while it holds the status).

It runs in a session of its own, so a Ctrl+C in the server’s terminal does not reach it. It ignores SIGTERM and SIGINT, so that a signal sent to a whole group of processes cannot stop it in the middle of a write to LinuxCNC. It ends when the server closes the pipe to it, which the server does when it stops and which also happens when the server dies. If it is in a send at that moment it finishes the send first, which can take up to 5 seconds per message. It is not left behind.

A command that is under way when the server stops is completed, all its messages, and the server process exits once it is done. Measured with SIGTERM to the server 1 s into a blocked single-message command: the server exited 4 s later, when the send returned, and the helper with it. 1 s into a blocked coolant command (two messages): the client’s call ended with UNAVAILABLE when the server’s 5-second grace period ran out, the server still sent the second message and exited 9 s after the signal, and no helper was left. A supervisor that kills the server sooner than that cuts the command short; systemd’s default stop timeout is 90 seconds.

If the helper dies, or the pipe to it breaks, the server starts another one before the next command. A command the helper had already been given is answered RCS_ERROR with a message that it may have been sent: the helper writes to LinuxCNC before it answers, so the server cannot know. Check the status before sending it again. Health stays SERVING meanwhile, because the server’s connection to LinuxCNC is unchanged; if no helper can be started, commands are answered RCS_ERROR with not_sent true.

The helper reports each request it has read before it calls into LinuxCNC. A helper whose report has not come after a second (stopped, or not reading) is ended, so a stop behind it does not wait for it. If it had written nothing after the request, the command is answered with not_sent true; if it had written anything (its report included), the command may have been sent. In the rare case that the report came just before the helper was ended, the helper may have died inside its call to LinuxCNC. If it died holding LinuxCNC’s command or status buffer, that buffer stays taken until LinuxCNC is restarted (no program can send that LinuxCNC a command, or every send waits out LinuxCNC’s 5-second wait). On Linux the server then logs an error saying that LinuxCNC’s command or status channel may be blocked and that restarting LinuxCNC clears it; it does not stop by itself over this. On the simulator, 3000 helpers killed right after their report left neither buffer taken.

Turning it off. --in-process-commands (or create_server(command_helper=False)) sends commands from the server’s own process, as versions up to 1.0 did. There is no child process then, and a command sent to a task that does not respond stalls every RPC of the server for as long as the send waits. A LinuxCNCServiceServicer built directly in Python sends from its own process unless it is given command_helper=True.

A task stopped while it holds the status

LinuxCNC’s status, command and error channels are shared memory, each guarded by a lock that the programs reading it take too. The task takes the status lock for a moment in every cycle, to write the status. If the task process is stopped in that moment (a debugger, SIGSTOP, Ctrl+Z in the terminal that runs LinuxCNC), the lock stays taken until the task runs again. Measured on the LinuxCNC 2.9.4 simulator: 1.5 to 2.0 % of stops of the task landed there, with the machine idle and during moves. Nothing else ever held the lock for long: 10 minutes of status reads at about 500 a second, also with every CPU core busy, waited at most 36 ms. That was a simulator; on a controller with a loaded real-time kernel it has not been measured.

What a client sees, measured with 20 such stops of 6 and 8 seconds (half of them during a 16-second move), 6 of 15 seconds (half during a 32-second move) and one of 60 seconds:

  • GetStatus, GetMachineConfig and ResolveFile fail with UNAVAILABLE and the trailing metadata entry linuxcnc-grpc-reason: status-unreadable for as long as the task is stopped, each within 0.11 s. The first call after the task runs again succeeds (1 to 55 ms after it continued), so the outage is the stop itself. No status is sent that was not just read: neither the one from before the stop nor an empty one.
  • StreamStatus stays open and sends nothing while the task is stopped (the gap is as long as the stop: 6.0 to 6.1 s, 8.0 to 8.1 s, 15.1 s, 60.1 s), then goes on. A client that treats a silent stream as dead gives up meanwhile: this project’s stream_status examples do after 30 s without an update.
  • WaitComplete keeps waiting on its command, also one started during the stop: it is never answered from a status that cannot be read, and at its timeout it answers RCS_EXEC. Of 134 waits (on moves, and on a command sent during the stop), none answered before its command had finished: the waits on a move answered RCS_DONE when the move ended.
  • SendCommand still sends: a command sent during the stop answered after 5.0 to 5.1 s with RCS_DONE and acknowledged unset, and was carried out when the task ran again. Refused instead, with RCS_ERROR, not_sent true and the message above: a command whose joint or spindle number the server checks against the machine’s counts (jog, home, unhome, spindle, spindle override, brake, set_limit, override_config), since the counts cannot be read, and home and unhome of all joints (-1), which are not stops and should not go out while nobody can see the machine. A jog stop and spindle off are still sent, checked against the largest numbers LinuxCNC has at all (joints 0 to 15, axes 0 to 8, spindles 0 to 7).
  • GetServerInfo (linuxcnc_connected true), health (SERVING), the file RPCs and the HAL service are not affected: at most 0.11 s.
  • StreamErrors: unchanged. A message posted after the stop arrived within 0.06 s.

What the server does. It reads the status with a 0.1-second wait for the lock (see the NML file below). A read that has to give up leaves LinuxCNC’s status object unusable for good, so the server makes a new one and trusts it only after two reads that worked: a new object whose first read gives up holds zeros. Until then the status is “unreadable” as above. It does not reconnect: the commands it has sent, the serials a WaitComplete can name, the command helper and health stay as they are, because LinuxCNC is not gone.

On Linux the server reads the lock’s own state. It tries a new status object as soon as the lock is free, also at once when it notices the stop, so a hold that is already over costs only the read that gave up. While the lock is held it makes a new object no more than once a minute, at first, and then less and less often, down to once every 10 minutes, in case the lock’s state was misread. Where the state cannot be read (not Linux, no permission), it tries after 0.1 s and then at doubling intervals up to 10 minutes: 13 tries in the first 14 minutes, 17 in the first hour, then 6 an hour, and a readable status can be noticed that much later. If the lock reads free but a read still gives up (another process took it again at once), those tries back off the same way.

What a stop costs. Every stop that the server notices makes at least one new status object (an error-channel stop, one error-channel object), and each try made while the lock is still held makes one more. They are kept until the server exits: about 56 KiB per status object and 16 KiB per error-channel object. Nothing limits the total over the life of the server, so a machine whose task often holds the lock longer than the wait (one short hold a second would add about 197 MiB an hour) needs a longer --status-read-timeout. The server logs a warning each time another 100 objects of a kind have been made, with the total and that advice. Each try made while the lock is held also makes LinuxCNC’s library print SHMEM: Can't take semaphore and the buffer name to the server’s standard error (as does the read that noticed the stop); those lines are expected.

A task that dies holding the lock. LinuxCNC’s locks are not released when the process holding one ends. If the task is killed or crashes while it holds the status lock, the lock stays taken until LinuxCNC is restarted, and the status can never be read again. The server checks, while the lock is held, whether the process that took it still exists (a zombie counts as exited). If the same process is found exited on two checks at least a second apart, with the lock held both times, the server treats LinuxCNC as gone (see When the server finds its LinuxCNC gone): measured, GetStatus answered linuxcnc-gone and health turned NOT_SERVING 1.2 s after the stopped task was killed, and the server exited with status 1. A process the server cannot see (one in another PID namespace, for a server in a container that shares LinuxCNC’s IPC but not its processes) cannot be checked and counts as alive.

Only where the holder cannot be checked at all (the lock’s state or its holder cannot be read) is a stop that has made 100 new status objects under the schedule above without one that could be read (about 15 hours) taken as LinuxCNC gone, so the server never keeps trying for good. A supervisor then starts a fresh process, which waits disconnected until LinuxCNC’s status can be read. With a holder that is checked and alive (a task stopped in a debugger) the server never stops on its own: after those 100 tries it stops making objects and keeps answering status-unreadable, and reads the status again as soon as the lock is free.

The error channel is handled the same way, and a read of it that gives up (which LinuxCNC’s Python module returns as a message “unrecognized error -1”) is not passed on.

The server’s copy of the NML file. The 0.1-second wait is set in a copy of LinuxCNC’s NML file. Before it opens anything, the server copies the NML file to a directory of its own (linuxcnc-grpc-nml-XXXXXXXX/linuxcnc.nml in $XDG_RUNTIME_DIR when that is the user’s own private directory, else in the system’s temporary directory; removed when the server exits), with the timeout of process xemc for emcStatus and emcError set to the configured value. Which file it copies: when the server is started by LinuxCNC (loadusr in a HAL file, or [APPLICATIONS]APP), LinuxCNC’s launcher sets INI_FILE_NAME, and the server copies the NML file that INI names ([LINUXCNC] or [EMC] NML_FILE, relative to the INI’s directory), the file LinuxCNC itself uses. Otherwise it copies the file LinuxCNC’s Python module uses (linuxcnc.nmlfile, normally /usr/share/linuxcnc/linuxcnc.nml), and if LinuxCNC’s INI names another file, it logs a warning saying how to make it use that one (start it from LinuxCNC’s environment, or set INI_FILE_NAME for it). The log names the file at startup (“Reading LinuxCNC through …, a copy of …”).

Nothing else in the file changes, so the server attaches to the same buffers as LinuxCNC. If xemc has no line of its own for one of the two buffers and LinuxCNC would use a P xemc default or P default default line, the copy adds an xemc line for that buffer made from it, with the short timeout. A buffer that xemc reads as a REMOTE (or AUTO) process keeps its timeout, which is a network timeout there, and the server logs that it is not protected; if that is the status buffer, no copy is made. The command channel keeps its 10-second timeout: a command written while the task holds the command lock still waits for it that long (in the command helper, not in the server; measured 10.0 s) and then fails with not_sent true.

The server’s command helper and its check for a running LinuxCNC use the same copy. If the copy or its directory disappears (a cleaner of temporary files) or is not exactly what the server made (owner, permissions, a link), the server never reuses the name: it writes a fresh copy in a new directory and uses that from then on. If the file cannot be read or no copy can be written, the server logs a warning and uses LinuxCNC’s own file, with the 10-second waits. A program that builds the servicer in its own process (create_server, LinuxCNCServiceServicer) has linuxcnc.nmlfile pointed at the copy for the whole process, so its own LinuxCNC channels created afterwards use the short wait too: a status read of theirs then returns with old data and the next one raises linuxcnc.error (“emcStatusBuffer invalid err=5”), after which a new linuxcnc.stat() is needed.

Changing the wait. --status-read-timeout SECONDS (create_server( status_read_timeout=...), serve(...)) sets it, from 0.01 to 3600 seconds (LinuxCNC splits the value into whole seconds and a fraction, so values outside that are refused); the default is 0.1. The default was chosen against the 36 ms measured on a simulator: if status-unreadable appears in a client or “could not be read within” in the log while LinuxCNC’s task is running normally, raise it. --status-read-timeout off (status_read_timeout=None) makes no copy and uses LinuxCNC’s own NML file, as 1.0 did: a task stopped while it holds the status lock then stalls the whole server for that file’s timeout, 10 seconds in LinuxCNC’s stock file, on every read while it stays stopped (measured with a 15-second stop: GetStatus 10.0 s and health 9.99 s late). The status object is still replaced rather than the connection renewed.

Stops go first

A stop is a command that can only stop something: state STATE_ESTOP or STATE_OFF, program abort or pause, jog JOG_STOP and spindle SPINDLE_CMD_OFF. Nothing else counts: brake engage does not (braking a turning spindle is not plainly harmless), nor does an override set to zero.

LinuxCNC has one command queue for all its clients. A message written to it waits behind every message written before it, and nothing overtakes it there. LinuxCNC’s send call writes a message and then waits up to 5 seconds for the task to take it, so while the task does not answer, every message ahead of a stop costs that stop up to 5 seconds. A stop that waited for its turn like any other command, with turns given out in no particular order, was written 5 to 8 seconds after it was sent behind three queued commands, at random, and about 30 seconds after behind ten (measured with the task frozen). The server cannot change LinuxCNC’s queue. It decides which of the messages it has not written yet goes next, and it writes them all through the one command helper process, so the order in which it writes them is the order LinuxCNC takes them in.

What the server does

A stop takes the next turn. It goes ahead of every command still waiting. The message being sent when the stop arrives is not interrupted (LinuxCNC’s send call cannot be cut short); the stop is written as soon as that call returns, after at most about 5 seconds while the task does not answer (twice that for program open, which LinuxCNC sends as two messages in one call). Among waiting stops, E-stop and machine off go first, then the others in the order they arrived, with one limit: an E-stop or machine off goes ahead of a stop accepted before it only once. So a stop waits for the stops accepted before it, for at most one E-stop or machine off accepted after it, and for the message being written; a stream of E-stops cannot keep a jog stop waiting. Each stop is written by the SendCommand call that received it, in the server’s SendCommand thread pool like every other command; there is one writer, and the order of the turns is the order of the writes.

A stop is answered like any other command, once its LinuxCNC call has returned: RCS_DONE with linuxcnc_serial, and acknowledged true when the task echoed it, false when LinuxCNC gave up waiting for the echo after about 5 seconds (the stop is in LinuxCNC’s queue and not yet taken), unset when the status could not be read afterwards or belongs to another LinuxCNC. Behind a command the task does not answer, a stop’s call therefore takes that command’s wait and then its own, about 10 seconds. A client whose deadline is shorter gets DEADLINE_EXCEEDED; the stop is written all the same and holds the other commands as below. Once a stop waits for its turn, nothing its client does withdraws it: a stop late is safe, a stop dropped is not. A stop refused before it waits gets RCS_ERROR with not_sent true (an index beyond the fixed arrays, below) or a gRPC status (UNAVAILABLE while the server is not connected to LinuxCNC).

Nothing on a stop’s way to LinuxCNC waits for a status read. The server reads LinuxCNC’s status under a lock, and a read can wait for the status buffer (when the task stopped while it held it). A stop takes no such lock and makes no read of its own before it is handed to the command helper. It only reads whether LinuxCNC has been found gone; finding that out is left to the server’s instance watch and to the commands that are not stops, and a stop’s way declares nothing. Its index is checked only against LinuxCNC’s fixed arrays (joints 0 to 15, axes 0 to 8, spindles 0 to 7), not against the joints and spindles the machine has, so a jog stop or spindle off for one the machine does not have goes to LinuxCNC (measured with the machine on: a jog stop for joint 10 or for axis W is taken and changes nothing; a spindle off for spindle 5 is taken and LinuxCNC posts Attempt to stop non-existent spindle <5> as an error message). A command helper started for a stop does not check the status first (when LinuxCNC is not running its write is not taken, and the stop is answered RCS_ERROR, not_sent true); such a helper is never used by a command that is not a stop and is ended after the stop. A reconnect holds the server’s turn to write only for the moment it takes to switch the channels.

Commands that are not stops do their slow work before they wait for their turn: they start a command helper if theirs has died, make the status read their index check needs, and resolve a program’s file name; and they read the status for acknowledged only after they have given the turn back. A stop waiting behind one therefore waits for none of that, only for the message it is writing. If that work is out of date when the turn comes (the server reconnected, or the helper died meanwhile), the command gives the turn back and does it again, and is refused (not_sent true) after three tries. One thing still delays a stop: while a status read waits for a held buffer, LinuxCNC’s Python module keeps the whole server process from running, every RPC included, for up to the status read timeout (0.1 s by default, see A task stopped while it holds the status). Measured during such reads: with the default timeout an E-stop was handed to the helper 2 to 5 ms after it was sent (about 30 ms when a helper had to be started for it first), also with 40 GetStatus calls made at once; with --status-read-timeout 10 it was handed over 9.5 s after it was sent, when the read ended, and GetServerInfo took as long. Keep the default.

A command a stop overtakes is not sent. Every command that was waiting for its turn when a stop arrived is answered at once with RCS_ERROR, not_sent true and the text A stop was issued; the command was not sent, on a healthy machine too and whichever client sent it. Written after the stop it would undo it: with stops going first and nothing refused, a jog start that was waiting when another client’s jog stop arrived was written after the stop and left the axis moving, in 995 to 1000 of 1000 pairs while a third client kept the server busy (measured). “Waiting” starts when the server’s SendCommand handler starts, so a command and a stop that arrive together are decided by which handler the server ran first, which is close to but not exactly the order the RPCs arrived in. The check is made again at the hand-over to the command helper, the last moment before a message goes out, so a stop accepted after the command’s last look still goes first. The command being sent when the stop arrives is not refused. A command sent as several LinuxCNC messages (coolant, set_limit, override_config, program_options) whose first message is already out is cut short: the stop goes next, and the rest of the command is not sent (RCS_ERROR, A stop was issued; the rest of the command was not sent, not_sent false, since part of it went out; the part that went out is what WaitComplete follows). program open is one LinuxCNC call that sends two messages and cannot be cut.

Commands are held until a status read shows a written stop taken. Once a stop’s call has returned and no good status read has yet shown the task’s echo at or past its serial, the other commands, from every client, are held:

  • A command that arrives then waits, for at most 1 second from its arrival, reading the status itself every 50 ms while it waits (before it waits for its turn, so no stop waits for those reads), and is sent as soon as the stop is shown taken.
  • If it is still not taken when its second is up, the command is answered RCS_ERROR, not_sent true, A stop has not been taken by LinuxCNC yet; the command was not sent.
  • Once the oldest stop that is still not taken was written more than that second ago, every further command is refused at once with the same text, after one status read of its own (so a hold the task ended long ago is seen to have ended even when no client reads the status). Stops that the task takes quickly, however many and however close together, only delay commands.
  • A command held this way is overtaken, and refused, by any further stop. So while stops keep arriving faster than LinuxCNC takes them, every command of every other client that waits is refused in turn: a client that streams stops starves the other clients’ commands.
  • A stop lost with the command helper process (the helper died while it had the stop, so it may be in LinuxCNC’s queue) holds by itself until a stop written after it has been taken: A stop was lost with its helper process and may still be in LinuxCNC's queue; the command was not sent. Sending a stop again clears this. So does a stop whose turn ended in an unexpected failure after its message may have gone out. An untargeted WaitComplete made after a lost stop answers RCS_ERROR saying so (until a later command has been dispatched and recorded).

The hold ends only on evidence: a good status read whose echo_serial_number has reached the newest stop the server wrote (compared as a signed 32-bit difference). It never ends because time has passed. A reconnect to the same LinuxCNC (the server replaces a status channel that failed) keeps it: the stops may still be in its queue. Only a reconnect whose first read shows an echo serial behind the one seen before ends it: that is a LinuxCNC that started again, which the server normally finds gone and stops for instead (see When the server finds its LinuxCNC gone). The echo serial is all the server has to tell the two apart, and it cannot prove that the LinuxCNC is the same: one that started again and whose echo serial is already past the old value is taken for the same one, and the hold then lasts until a stop is taken. After any reconnect the server no longer knows the latest command; an untargeted WaitComplete made while the hold lasts answers RCS_ERROR (The connection to LinuxCNC changed; the latest command's outcome is not known). While the status cannot be read no read can show a stop taken, so the hold stays and commands are refused with its texts; a command held behind a stop gets the hold’s text, not the status-unreadable refusal. A stop the server refused, that LinuxCNC did not take (its command queue was full), or whose serial the server’s status cannot judge (the status belongs to another LinuxCNC) holds nothing. Stops themselves are never held or refused by any of this. Measured: the hold was kept across the reconnect 6 of 6, a feed override was refused with the hold’s text, an untargeted WaitComplete after the reconnect answered RCS_ERROR (“The connection to LinuxCNC changed; the latest command’s outcome is not known”), and the hold cleared 0.12 to 0.19 s after the task was continued.

GetServerInfo shows the stops not taken. ServerInfo.stops_not_taken is the number of stops the server wrote that no good status read has shown taken, plus each stop lost with the command helper process, counted one each. It is computed from the hold on every call and read without any lock a blocked send or a status read can hold. Measured with two clients each sending a stop every 20 ms for 3 s to a frozen task (three runs, 258 to 268 stops): every stop was written once the task ran, each answered with acknowledged true, and the echo reached the last one 6.8 to 7.2 s after the task was continued. stops_not_taken stayed 0 throughout: it counts only stops whose call has returned with the echo behind them, and stops waiting for their turn are not counted (they go ahead of every command by priority instead).

SendCommand has threads of its own. Every RPC in progress holds a worker thread, and one that finds none free waits before it starts, where the server cannot see it. SendCommand therefore runs in a pool of its own: max_workers // 2 threads, at least 4 (16 with the default 32). Commands that are not stops may take all of them but two (14 by default, 3 with 10 workers, 2 with 8 or fewer); one more is answered RCS_ERROR, not_sent true, Too many commands are waiting; the command was not sent. Stops are never counted or refused, and a stop holds a thread of this pool for its whole call, LinuxCNC’s waits included: many stops sent while the task does not answer can fill the pool and its queue. Everything else runs in the general pool of max_workers threads, where the calls that can last are capped so that two threads stay for short calls: health watchers get at most half of max_workers - 2 and never more than 4, and the streams (status, error, HAL) and WaitComplete calls together the rest (26 with 32 workers, 4 with 10). One more stream or WaitComplete is refused with RESOURCE_EXHAUSTED, one more health watcher with UNIMPLEMENTED. So streams, watchers and slow status calls cannot take the threads a stop needs: the server’s tests fill the general pool (every stream and watcher allowed, GetStatus calls blocked and more queued behind them) and every command the limit allows, and require an E-stop’s handler to start within half a second. This does not make a stop’s thread certain; see What the server cannot do. When the server stops, both pools stay in use until the transport has terminated, and are then shut down; a call handed to a pool after that is refused, not raised into gRPC. Measured on the 2.9.4 simulator with the default 32 workers and the task frozen while it held none of LinuxCNC’s buffers:

  • The general pool full (26 status streams and 4 health watchers open, a third stream refused with RESOURCE_EXHAUSTED, 64 threads calling GetStatus back to back) and all 14 commands in progress (one blocked in its send, 13 waiting): the E-stop’s handler started 0.4 to 1.2 ms after it was sent, on a thread of the command pool every time (five runs); its RPC answered after about 8.5 s, after the blocked command’s wait and its own, with acknowledged false.
  • The same 14 commands, and 64 threads sending SendCommand calls that were refused (Too many commands are waiting): 15.6 to 16.5 ms (five runs, about 48,800 refusals each). That is the queue in front of it: the refusals ahead of the stop each took a command thread for a moment.

See Thread Pool.

Measured

On the LinuxCNC 2.9.4 simulator with the task process frozen by SIGSTOP (three runs each, medians; times from the first command of the scenario; “before” is the server without stops first, run the same way).

ScenarioStop written, beforeStop written, nowStop answered, beforeStop answered, now
E-stop at 0.2 s behind a mode change blocked from 0; task continued at 2 s2.06 s2.05-2.07 s, when the mode change returned2.25 s2.17-2.19 s, acknowledged true
The same, task continued at 8 s5.01 s5.02-5.03 s (8.09 s in one run), when the mode change returned8.17 s8.20-8.22 s, acknowledged true
E-stop at 1.0 s behind a blocked mode change and two queued commands; continued at 8 s8.11 s (5.01-8.12)5.02 s, when the mode change returned8.24 s8.19-8.26 s, acknowledged true
E-stop at 0.5 s while coolant waits on its first message; continued at 8 s8.12 s5.01-5.02 s, when mist returned (flood not sent)8.26 s8.13-8.23 s, acknowledged true
Task running, error queue full: E-stop, six jog stops at 0.3 s (5 s each in E-stop), a second E-stop at 1.0 ssecond E-stop 25.35 s (15.33-25.35)1.005 s, at once (the server read the error queue, its default on this headless simulator, so the queue did not stay full)25.48 s1.13-1.15 s, acknowledged true
SIGTERM to the server at 1.2 s, E-stop behind a blocked command; continued at 8 s5.04 sabout 5.03 s, when the mode change returned, during the shutdownUNAVAILABLE at 6.36 sUNAVAILABLE at 6.0-6.3 s; in effect after the task continued, 3 of 3
SIGKILL to the server at 1.2 s, samenot writtennot written (killed while waiting for its turn), 3 of 3UNAVAILABLEUNAVAILABLE

What the other commands got: the commands queued behind the blocked one were refused at the moment the E-stop arrived (A stop was issued; the command was not sent), the coolant command sent its first message and not its second (A stop was issued; the rest of the command was not sent), and every E-stop was written within 2 ms of the call ahead of it returning and took effect after it; in the SIGTERM case the E-stop was still written during the shutdown and took effect when the task was continued (3 of 3); after SIGKILL it was lost (3 of 3), as it was before.

On a healthy simulator: the medians of 100 commands, the previous release and this one run one after the other, twice, were 121 and 118 ms, then 122 and 122 ms for an E-stop (the E-stop median moves between about 110 and 200 ms from run to run with either), 76 and 73, then 74 and 72 ms for an abort, 27 and 31 ms for a jog stop, 51 and 52, then 51 and 53 ms for a mode change and 28 and 29, then 29 and 30 ms for a feed override, measured before stops were written by their own call. Now, 100 of each: E-stop 216 ms, abort 82 ms, jog stop 28.5 ms, mode change 57 ms, feed override 31 ms (medians; a stop’s RPC now answers when its call returns, and the E-stop median moves between about 110 and 230 ms from run to run). The cost of refusing what a stop overtakes, with one client sending feed overrides back to back: while a second client sent an abort or a jog stop every 50 ms, 8 of 198, 13 of 209 and 7 of 198 were refused (3.5 to 6.2 %); while it jogged (jog start, 0.3 s, jog stop, 0.5 s pause), 1 of 1518, 1 of 1475 and 1 of 1489 (0.07 %); every one was overtaken by a stop, none lost without not_sent. A jog start and a jog stop sent by two clients 0 to 2 ms apart: 6000 pairs, never written in the other order and never left moving; the jog start was refused in 300 to 319 pairs of 1000, and in 978 to 993 of 1000 while a third client streamed feed overrides. A burst of 25 commands at once: 11 of each 25 refused (Too many commands are waiting), with the limit of 14.

What the server cannot do

  • A helper that does not start a call is not waited for. The command helper reports each request it has read before it calls into LinuxCNC; if that report does not come within a second, the helper is ended and, when its output shows it never started the call, the command is answered not_sent and a stop waiting behind it is written through a new helper. If it did report, the call may be under way, and what follows is LinuxCNC’s own wait. A stop whose request certainly did not reach its helper is sent once more through a new one. Measured: with the helper stopped before it read a command, an E-stop sent behind it was written 0.83 to 0.85 s after it was sent; with the helper stopped in the middle of a call, only after the helper’s 30-second reply timeout (29.8 to 29.9 s), the command then answered as possibly sent.
  • A stop’s acknowledged can be unset. After its write, a stop’s RPC does not wait for another status read to finish: if one holds the status, the answer comes without acknowledged, and the hold is kept as usual.
  • stops_not_taken falls only on a status read. Under create_server the server reads the status at least every 2 seconds; a servicer used directly reads only for its clients’ status calls and held commands.
  • Shutdown. Stopping the server waits at most 15 seconds for gRPC’s transport to finish, then ends both thread pools whether or not it has; a call that arrives after that is refused without running.
  • Fork support. Importing linuxcnc_grpc sets GRPC_ENABLE_FORK_SUPPORT=false in the process’s environment unless it is set. It has no effect if grpc was imported first; a program that embeds the server and imports grpc earlier must set it itself. The helper start timeout counts from the moment the child process exists, so it does not bound a stall before the child has started.
  • Nothing overtakes LinuxCNC’s queue. A stop is written after the message being sent, and LinuxCNC takes it after every message written before it, by this server or any other program (a GUI, a pendant). The server orders only what it has not written yet.
  • There is one writer. Every command, stops included, goes through the one command helper process one at a time, so a stop waits for the message being written. Two writers would leave the order of the writes unknown, and with it the hold and WaitComplete.
  • A task that does not run acts on nothing. An E-stop sent through the server to a frozen or hung task takes effect only when the task runs again. Use the machine’s physical E-stop; the server is no substitute for it.
  • A stop is not faster than a status read that waits. While the server reads the status of a task that stopped holding the status buffer, the whole server process waits for up to the status read timeout (0.1 s by default; --status-read-timeout up to 3600 s). A stop that arrives then is handed over when the read ends.
  • A stop is not faster than the INI file read either. LinuxCNC’s INI reader keeps the whole server process waiting while it reads, so on a config directory that hangs (a network mount, a failing SD card) every call, stops included, waits for as long as the read does. The server therefore reads the INI file once per connection and does not start a read while the last status it has shows the machine in cycle (see What the server reads from the INI file). That is best effort: a cycle that starts in the moment between that status and the read is not excluded, and any read that runs stops the process for its length. Keep the INI file on local storage.
  • A stop waiting for its turn is lost if the server process is killed outright (SIGKILL, a crash, power). On a normal shutdown (SIGTERM, server.stop()) a stop already waiting for its turn is still written by its own call, through a command helper started for it if the server’s helper has been ended by then; commands that are not stops are refused and start no helper. No bound is given for the shutdown as a whole. With SIGTERM an E-stop waiting behind a blocked command was still written during the shutdown and took effect when the task was continued (3 of 3); with SIGKILL it was lost (3 of 3).
  • A command refused because of a stop is not retried by the server. The client decides: read the status, then send it again if it still makes sense. not_sent true means it was not written, so sending it again cannot run it twice. Confirm a stop with the status (task.task_state for an E-stop or machine off, the velocities for a jog stop) as well as with the count.
  • A command LinuxCNC refuses with an operator message can stall the task for 5 seconds when nobody reads the error channel. Measured: a jog stop sent in E-stop was taken in 22 ms while LinuxCNC’s error queue had room; after 25 such messages that nobody read (a sim without a GUI and the server not reading the error channel), the next one took 5.0 s, and the task took nothing else meanwhile. Such a stop holds the other commands for those 5 seconds. A program that reads the error channel (a GUI, a StreamErrors client, or the server in always mode, which auto chooses on a machine without a GUI) keeps the queue from filling.
  • --in-process-commands applies stops first as well (the order does not depend on the helper), but a send waiting for the task stalls the whole server process.
  • A reconnect (rare, see When the server finds its LinuxCNC gone) to the same LinuxCNC keeps the hold of stops already written; one that reaches a LinuxCNC that started again ends it (their serials mean nothing there). The server tells the two apart by the echo serial alone, which cannot prove identity (see above).
  • A flood of SendCommand calls can delay a stop. gRPC hands a call to the SendCommand pool before the request is read, so the server cannot tell a stop from any other command there; the pool runs calls in the order they came, and a command refused over the limit still takes a thread for the moment its refusal takes. A client that sends commands faster than they are refused (the server has no authentication) queues them ahead of every stop. Bind the server to 127.0.0.1 or a trusted network (see Security Considerations). If the installed gRPC ignored the pool a handler names, SendCommand would share the general pool; the server logs an error the first time it sees that.
  • LinuxCNC 2.9 or newer is required (see Requirements).

Network Configuration

Firewall

Allow incoming connections on the gRPC port:

# UFW (Ubuntu)
sudo ufw allow 50051/tcp

# firewalld (Fedora/CentOS)
sudo firewall-cmd --permanent --add-port=50051/tcp
sudo firewall-cmd --reload

# iptables
sudo iptables -A INPUT -p tcp --dport 50051 -j ACCEPT

Binding to Specific Interface

To bind to a specific network interface:

# Bind to localhost only (no remote access)
linuxcnc-grpc --host 127.0.0.1

# Bind to specific IP
linuxcnc-grpc --host 192.168.1.100

Environment Variables

VariableDefaultDescription
LINUXCNC_NC_FILES/home/linuxcnc/linuxcnc/nc_filesDirectory for G-code file operations (UploadFile, ListFiles, ReadFile, DeleteFile, ResolveFile, program open)

NC Files Directory

All file management RPCs (UploadFile, ListFiles, ReadFile, DeleteFile, ResolveFile) and the program open command operate within a single allowed directory. By default this is /home/linuxcnc/linuxcnc/nc_files.

To change it, use the --nc-files flag:

linuxcnc-grpc --host 0.0.0.0 --nc-files /home/user/nc_programs

Or set the LINUXCNC_NC_FILES environment variable:

export LINUXCNC_NC_FILES=/home/user/nc_programs
linuxcnc-grpc --host 0.0.0.0

Priority: --nc-files flag > LINUXCNC_NC_FILES env var > default.

Or in a systemd service file:

[Service]
Environment=LINUXCNC_NC_FILES=/home/user/nc_programs
ExecStart=/usr/local/bin/linuxcnc-grpc --host 0.0.0.0 --port 50051

Path traversal outside this directory is rejected — filenames like ../../etc/passwd will return INVALID_ARGUMENT. The server resolves symlinks and validates the canonical path stays within the allowed directory. A name that runs into a symbolic link loop is also INVALID_ARGUMENT.

Security Considerations

The server has no authentication and no encryption. Every RPC is open to anyone who can connect to the port, and that includes motion, spindle, program and file-upload commands. The default bind address is 0.0.0.0 (all interfaces), so decide deliberately where it listens.

Bind the server to localhost on the LinuxCNC machine:

linuxcnc-grpc --host 127.0.0.1 --port 50051

Then open a tunnel from each client machine and point the client at localhost:50051:

ssh -N -L 50051:127.0.0.1:50051 user@cnc-machine

SSH supplies the authentication and encryption the server lacks, and no firewall port needs opening.

Trusted LAN only

Binding to 0.0.0.0 or a LAN address is acceptable only on a network where you trust every device, such as an isolated machine network. In that case the insecure connection is suitable for:

  • Local development
  • Trusted private networks
  • Testing and evaluation

Production Security

For production use on untrusted networks:

  1. Use TLS - gRPC supports TLS encryption. Configure your server with certificates.
  2. Use a VPN - Run LinuxCNC on a private network accessible only via VPN.
  3. Firewall rules - Restrict access to known client IPs.
  4. Authentication - Implement gRPC interceptors for authentication.

TLS Configuration (Advanced)

To enable TLS, modify the server code or use a gRPC proxy like Envoy:

# Example TLS configuration (requires code modification)
import grpc

with open('server.key', 'rb') as f:
    private_key = f.read()
with open('server.crt', 'rb') as f:
    certificate_chain = f.read()

server_credentials = grpc.ssl_server_credentials(
    [(private_key, certificate_chain)]
)
server.add_secure_port('[::]:50051', server_credentials)

Command and Error Semantics

A few behaviours that are easy to get wrong from a client.

SendCommand returns when the command is dispatched

SendCommand answers RCS_DONE as soon as LinuxCNC has accepted the command. RCS_DONE here means “dispatched”, not “finished”: an MDI move or a homing sequence is usually still running when the response arrives. To know when it has finished, call WaitComplete or watch the status (task.exec_state, task.interp_state, task.task_mode).

A stop is answered the same way, once its call has returned; it may have waited for its turn behind the message being written first (see Stops go first).

RCS_ERROR from SendCommand

SendCommand answers RCS_ERROR, with the reason in error_message, in these cases:

  • The server rejected the command. It checks some values itself: a joint or spindle index, an MDI command that is empty or too long, the file name of a program to open, an enum value it does not know. A command that fails a check is not sent, and error_message is the server’s own text, for example MDI command must not be empty.
  • A LinuxCNC call failed. error_message is the text of that error.
  • The command helper process was lost with the command. The text says the command may have been sent; check the status before sending it again (see A LinuxCNC task that does not respond).
  • A stop arrived, or has not been taken yet. A command that was waiting for its turn when a stop arrived, one that arrived while a stop has not been taken by LinuxCNC’s task and was still not taken a second later, and every command while a stop lost with the command helper is outstanding, are refused without being sent; so is the rest of a command of several messages that a stop cut short. The texts are in Stops go first.
  • Too many commands are waiting. Too many commands are waiting; the command was not sent (see Thread Pool).
  • LinuxCNC did not take the command. If the write to LinuxCNC’s command channel fails, LinuxCNC’s Python bindings report no error. The server notices because LinuxCNC’s command serial did not change, and answers RCS_ERROR with a message that the command was not accepted by LinuxCNC. Nothing was sent.
  • The server could not get a command helper ready. A command that is not a stop starts a new helper, if its own has died, before it waits for its turn; if that fails, it is refused with the start error (not_sent true). If the connection or the helper changed three times while it waited, it is refused with The command was not sent: the connection to LinuxCNC or its command helper changed 3 times while the command waited for its turn. A helper that dies between two messages of a command of several messages is not replaced for the rest of it: the rest is not sent, and not_sent is false.

Most commands are one LinuxCNC message. Four are sent as several messages, one after the other:

CommandMessages, in order
coolantMist, flood
set_limitMinimum limit, maximum limit
override_configFeed override, spindle override, feed hold, adaptive feed
program_optionsOptional stop, block delete

If one of these messages fails, or a stop arrives between two of them, the ones before it have been sent and stay in effect, and the ones after it are not sent. The answer is RCS_ERROR all the same, and the response does not say how many messages went out.

The server’s own checks all run before the first message (see Values the server rejects), so a rejected command is never partly sent. Only a LinuxCNC call that fails after the first message leaves one that way.

The check for a command LinuxCNC did not take looks at the command as a whole. If LinuxCNC takes none of these messages, the answer is RCS_ERROR and nothing was sent. If it takes some and silently drops another, the answer is RCS_DONE. The same holds for opening a program, which LinuxCNC itself sends as two messages (close the current program, open the new one).

After RCS_ERROR from one of these four commands, read the status before you send the command again: part of it may have taken effect.

not_sent says when a retry is safe. With RCS_ERROR, CommandResponse.not_sent is true when the server is certain that nothing was written to LinuxCNC for the request: the server rejected it, it was dropped while waiting its turn (shutdown, client gone, a stop), it was held behind a stop and refused, too many commands were waiting, no command helper could be started, or LinuxCNC took none of its messages. Sending it again cannot run it twice. False means the server cannot rule out that something was written: a LinuxCNC call that failed during a send, a command of several messages that failed part-way, a helper lost with the command, or a reply from the helper without a usable serial. A 1.0 server never sets it.

The response serial is the server’s, not LinuxCNC’s

CommandResponse.serial is the serial you set on the request or, if you left it at 0, a number from the gRPC server’s own counter. It is not LinuxCNC’s command serial, so don’t compare it with status.task.echo_serial_number. It is only a label for your own bookkeeping: the server does not use it to identify a command later, and WaitComplete ignores it. The server’s counter wraps to 1 after 2147483647 (the field is an int32); the HAL service’s counter does the same.

linuxcnc_serial identifies the command to LinuxCNC

CommandResponse.linuxcnc_serial is LinuxCNC’s own serial number for the command. It is set whenever the command was dispatched:

  • It identifies the command; it does not prove the task received it. LinuxCNC’s send call normally returns once the task has echoed the command, so task.echo_serial_number is normally at or past this value by the time you get the response. But if the task does not answer, the send gives up after about 5 seconds without an error and the serial is returned all the same (see A LinuxCNC task that does not respond). The server looks at the echo once, right after the send, and reports it in acknowledged. To confirm later that the command was received, call WaitComplete with the value or compare it with task.echo_serial_number in the status.
  • It says nothing about the outcome. LinuxCNC can still refuse the command (an MDI line in the wrong mode, for example) or fail part-way. Pass the value to WaitComplete to get RCS_DONE or RCS_ERROR for it, within the limits described below.
  • For a command sent as several LinuxCNC messages (see the table above) it is the serial of the last message LinuxCNC took, so a wait on it covers that message only.
  • It is unset whenever the answer is RCS_ERROR, also when part of the command was sent (see RCS_ERROR from SendCommand).
  • Serials are only meaningful for one run of LinuxCNC. Don’t keep them across a restart of LinuxCNC.
  • It can be set while acknowledged is unset, when the server’s status turned out to belong to another LinuxCNC than the one that took the command (see When the server finds its LinuxCNC gone). The command was sent, to whatever LinuxCNC took it; the server stops, and a WaitComplete on the value is not answered from that status.

WaitComplete

WaitComplete waits until the most recent command sent through this server has finished. The serial in the request is ignored, as it always has been, and is only echoed back in the response. After sending A and then B, WaitComplete reports on B whichever serial you pass.

With several clients on one server, “most recent” means the most recent from any of them, so a plain WaitComplete cannot tell you about your own command if another client has sent one since.

To wait on one command’s serial, set linuxcnc_serial in the request to the value SendCommand returned for it. The wait then applies LinuxCNC’s own serial rule (the one its wait_complete uses) to that serial instead of the latest one:

  • If the task is on that command, the result is RCS_DONE or RCS_ERROR when it stops executing.
  • If LinuxCNC has echoed a later command, the result is RCS_DONE at once, whatever became of the earlier one.
  • If the value is not a serial this server returned from SendCommand on its current connection to LinuxCNC, the result is RCS_ERROR at once with a message saying so. That covers a made-up serial, one from before the server last reconnected (unless the new connection has by chance issued the same number), and one older than the last 4096 commands. An explicit 0 is treated like any other value: it is refused unless this server issued 0. Copy the field only when the response has it set (HasField in Python), because an unset field reads as 0.
  • If the server reconnects to LinuxCNC during the wait, the result is RCS_ERROR with a message saying the outcome is unknown: the new connection may be to a LinuxCNC that started again and counts serials from the start. A reconnect in the instant between the wait’s last look at the status and its answer is not noticed, and the answer can then still be RCS_DONE.

What the answer proves. A wait with linuxcnc_serial is exact as long as nothing else is sent to LinuxCNC meanwhile. Once a later command has been echoed, sent through this server or by any other client of the same LinuxCNC (the GUI, for example, or a feed override sent while a long MDI move runs), the answer is RCS_DONE and the wait does not say how the earlier command ended: it may still be executing, or it may have failed. A client that needs to know a motion has finished should also read the status: task.interp_state back at INTERP_IDLE, trajectory.inpos true and trajectory.current_vel at zero, as fits the command.

The rest of this section describes the wait without linuxcnc_serial.

StatusMeaning
RCS_DONEThe command finished
RCS_ERRORThe command failed (error_message is "Command failed"), or LinuxCNC could not be read
RCS_EXECThe timeout expired and the command is still running
  • A timeout of 0 means the default of 5 seconds.
  • The timeout covers the whole call, including the time it waits for the server’s internal lock (and the connection check at the start). If another RPC holds the lock past the deadline, the answer is RCS_EXEC, as for any timeout.
  • The command it waits on is the latest one dispatched when the call arrives. A command sent while the wait is in progress does not change its target.
  • A command whose messages are still being sent when the call arrives (a SendCommand waiting for a task that does not respond, say) is the latest one. The wait goes on until its send is over and then applies the rules below to it; while the send lasts it answers RCS_EXEC at its timeout, as for any command still in progress. That is also what versions up to 1.0 answered, only later: there the wait could not even start until the send had returned. If the server’s command helper process is lost with that command, what became of it is not known, and the wait answers RCS_ERROR (The latest command sent through this server was lost with the command helper process; its outcome is not known), never RCS_DONE about the command before it. A wait made afterwards answers the same, until the next command has been sent and recorded (a reconnect to the same LinuxCNC does not end it; one that reaches a LinuxCNC that started again does). The same holds for a stop lost that way, and for a command whose helper replied without a usable serial (not a signed 32-bit number). The SendCommand of a lost command itself says it may have been sent (not_sent false).
  • A wait with linuxcnc_serial is not held up by a command being sent. After acknowledged false it waits for the task to take the command, and answers RCS_EXEC at its timeout while the task does not answer.
  • The command counts as finished when LinuxCNC has picked it up and is no longer executing it; the result is then RCS_DONE or RCS_ERROR.
  • If LinuxCNC has already moved on to a later command (one sent during the wait, or from the GUI or anything else), the result is RCS_DONE straight away, even while that later command is running or has failed. The later command’s outcome is not this command’s.
  • If the server has no command to wait for, it returns RCS_DONE immediately, whatever the machine is doing. That is the case when nothing has been sent through this server yet, and after the server has reconnected to LinuxCNC, which makes it forget the command it last sent. The exception: while a stop holds the other commands (see Stops go first), a wait after a reconnect answers RCS_ERROR, The connection to LinuxCNC changed; the latest command's outcome is not known.
  • If the server reconnects to LinuxCNC while a wait is in progress, the wait switches to the most recent command sent since the reconnect, or returns RCS_DONE if there is none. Check the status rather than rely on WaitComplete across a reconnect.
  • The server polls status about every 50 ms while it waits. A wait in progress does not hold the server’s internal lock, so an estop sent from another client or thread is not queued behind it. (Up to 1.0.0 it was: every other RPC waited until the WaitComplete returned.)
  • Each waiting WaitComplete occupies one of the server’s general worker threads (32 by default) until it returns. Streams and WaitComplete calls together may hold 26 of them with the default 32 workers; one more is refused with RESOURCE_EXHAUSTED before it starts (see Thread Pool). SendCommand, stops included, runs in a pool of its own and does not wait for these threads.
  • A stop counts as the latest command like any other. Its SendCommand answers only once its LinuxCNC call has returned, so an untargeted wait made after that answer judges the stop.

Error messages and the GUI

LinuxCNC delivers operator and NML error messages through its NML error channel. That channel is a single queue, and reading a message removes it. The LinuxCNC Python module offers no way to look at a message without taking it. So each message goes to exactly one reader: the machine’s GUI (AXIS, gmoccapy and so on) or this server, never both.

We checked this on the LinuxCNC 2.9 simulator, with a second error-channel reader standing in for the GUI:

  • A second reader in the same process, or in another process, gets nothing once the first has read the message.
  • A reader that connects after the message was posted still finds it, as long as nobody has read it yet.
  • Putting a message back for the GUI is not possible either. The only way to post one is operator_message, which adds a new message to the same queue, where the server would read it again.

The server therefore cannot make its reading invisible to the GUI. What it can do is read in one place, share what it read with every client, and choose whether it reads at all.

Somebody has to read the queue

The queue must not go unread either. Measured on the LinuxCNC 2.9.4 simulator:

  • The queue holds 25 messages. Once it is full, LinuxCNC’s task waits 5.0 seconds for every further message and then drops it. It waits once per message: a refused move beyond a soft limit posts three messages and took 15 seconds.
  • During that wait the task reads no command from anyone, stops included. A jog stop sent 0.7 seconds into a jog stopped the axis 4.61 inches later instead of 0.11; an abort sent 1.5 seconds into an MDI move stopped it 4.65 inches later instead of 0.13. Motion already queued goes on, a program of short segments stood still for 5 seconds, and the status (position, echo serial) does not change until the wait ends. CommandResponse.acknowledged showed such a stalled send as false only sometimes (2 of 13).
  • One reader taking one message ends a stall at once.
  • The GUIs listed below read the queue all the time. Those that ship with LinuxCNC (AXIS, gmoccapy, gscreen, Touchy, QtVCP screens, tklinuxcnc) poll it every 50 to 200 ms. halui never reads it, linuxcncrsh only when its client asks, and mdro, the DRO that ships with LinuxCNC, does not read it.

So on a machine with one of those GUIs the GUI is the reader, and on a machine without one (a dummy or headless display, halui, linuxcncrsh or mdro only, a program of your own) only the server can be. Without a reader such a machine stalls from the 26th error message on: a few dozen refused MDI lines are enough.

The modes

The --error-channel option chooses when the server reads:

ModeThe server reads the channelGUI sees messagesStreamErrorsstatus.errors
auto (default)As on-demand if [DISPLAY]DISPLAY is one of the GUIs below, as always otherwise; decided when the server connects to LinuxCNCAs in the mode chosenWorksAs in the mode chosen
on-demandOnly while at least one StreamErrors client is connectedYes; while a client is streaming, only the ones it polls before the server doesWorksMessages read during streams
alwaysFrom the connect to LinuxCNC onOnly the ones it polls before the server doesWorks, and replay_buffered returns messages from before the client connectedAlways the most recent messages
offNeverYes, alwaysRefused with FAILED_PRECONDITIONAlways empty

How auto decides:

  • When the server connects to LinuxCNC, and again on a reconnect (rare, see Reconnection), it reads [DISPLAY]DISPLAY from the INI file LinuxCNC’s status names, unless the machine is in cycle then (see below). It takes the first word of the value (the program LinuxCNC’s launcher starts; the rest are its arguments), without its directory, in lower case.

  • The displays known to read LinuxCNC’s error messages mean on-demand:

    [DISPLAY]DISPLAY starts withGUI
    axis, profile_axisAXIS (ships with LinuxCNC)
    gmoccapygmoccapy (ships with LinuxCNC)
    gscreengscreen (ships with LinuxCNC)
    touchyTouchy (ships with LinuxCNC)
    qtvcpevery QtVCP screen, for example qtvcp qtdragon and qtvcp qtplasmac (ships with LinuxCNC)
    tklinuxcnc, tkemctklinuxcnc (ships with LinuxCNC)
    qtpyvcpQtPyVCP screens started through QtPyVCP’s launcher
    probe_basic, probe_basic_latheProbe Basic (QtPyVCP)
    tncTurBoNC (QtPyVCP)
    monokrom_mill, monokrom_plasmaMonokrom (QtPyVCP)
    flexguiFlex GUI

    The third-party ones were checked in their published sources: QtPyVCP’s default configuration loads its notifications plugin, which polls the error channel every 200 ms, and Flex GUI polls it in its status update. The list holds displays known to read the errors, not every display that does. A display reads them if it shows LinuxCNC’s error popups (try an MDI line such as M999, which LinuxCNC refuses with an error message).

  • Anything else means always: dummy, linuxcncrsh, halui, a headless stand-in, a program of your own, an empty value, a missing [DISPLAY] section, an INI file the server cannot read, and a status that does not name the INI file.

  • Before the first connect nothing is read (there is nothing to read).

  • The decision is logged at INFO level in one line, for example Error channel auto: [DISPLAY]DISPLAY = 'headless', not a display known to read LinuxCNC's error messages; reading them as always (pass --error-channel on-demand if this display reads LinuxCNC's error messages itself).

  • GetServerInfo reports the mode in use in error_channel_mode (on-demand, always or off; auto until the server has connected).

If the server connects while the machine is in cycle (it was started or restarted in the middle of a program), it does not read the INI file then, and auto reads as always until it has:

  • The log says so in one line at WARNING level: Error channel auto: reading LinuxCNC's error messages as always for now. The machine is in cycle, so the server has not read [DISPLAY]DISPLAY from LinuxCNC's INI file; it decides once the machine is no longer in cycle. ....
  • GetServerInfo reports always meanwhile: that is how the server reads.
  • Once a status read shows the machine out of cycle, the server reads the INI file and decides as usual, with the usual INFO line. It looks every 2 seconds (not a deadline); a paused program counts as in cycle, so this can last as long as the pause.
  • Until then a GUI that reads the error messages itself can miss some of its popups. always is chosen because the other way round is worse: on a machine with nobody reading the queue, the 26th message stalls LinuxCNC’s task and stops sent then take effect seconds late. Start the server with --error-channel on-demand on a machine with a GUI to avoid this.

Measured on the simulator, with the server in its default mode:

MachineWithout a StreamErrors clientResult
DISPLAY = headless60 refused MDI lines at 1 per second, then 60 back to backauto chose always; no stall, every line answered within 0.16 s
DISPLAY = axis, nothing reading30 refused MDI lines back to backauto chose on-demand; lines 26 to 30 each stalled 5 seconds, as with on-demand
DISPLAY = axis, a reader that polls like AXIS60 at 1 per second, then 60 back to backNo stall; the stand-in GUI received all 120 messages

With an always reader on a machine with a GUI, by contrast, the GUI received 19 of 100 messages. Also measured: with a StreamErrors client open, on-demand had no stall in 100 errors, and always had none under a flood of about 300 messages per second (sends waited at most 75 ms).

What the server reads from the INI file

The server reads LinuxCNC’s INI file (the one LinuxCNC’s status names) in one pass per connection to LinuxCNC: [DISPLAY]DISPLAY for auto and the values GetMachineConfig reports (kinematics, coordinates, velocities, accelerations, home sequences and display hints). It keeps them for as long as that connection lasts; LinuxCNC reads its INI file once when it starts, so they do not change while it runs. Once they are read GetMachineConfig opens no file.

  • The read is made when the server connects, unless the status read then shows the machine in cycle. In cycle means: the machine is on (out of E-stop and powered) and busy, which is the interpreter not idle (a program running or paused, an MDI command), or motion not in position, or the trajectory velocity not zero (a jog), or a joint homing. A machine in E-stop or off is not in cycle; a task state the server does not know counts as in cycle.
  • When the machine was in cycle at the connect, the read waits until a status read shows it is not. The server started from the command line (or with create_server) looks every 2 seconds, which is not a deadline, and a GetMachineConfig call checks too and can be what makes the read. A paused program counts as in cycle, so the wait can last as long as the pause. Until the read, GetMachineConfig is refused (see the API reference) and auto reads as always (above).
  • The log line Reading LinuxCNC's INI file <path> (<n> values) marks each read.
  • This is best effort, not a guarantee. The server decides from the last status it has; a cycle that starts in the moment between that status and the read (a jog from the GUI, a command just sent) is not excluded. A read that runs freezes every RPC, stops included, for as long as the file system takes, because LinuxCNC’s reader holds Python’s interpreter lock. Keep the INI file on local storage, not on a network mount.
  • If the joints or axes in the status change under the same INI file name, GetMachineConfig reports ini_readable false (and the server logs it once) rather than report the values it did not read as 0.
  • An INI file the server cannot read is not read again until the next connection: GetMachineConfig reports ini_readable false meanwhile. After fixing its permissions, restart the server.
  • The explicit --error-channel modes do not use [DISPLAY]DISPLAY; the server still reads the other values at the connect, for GetMachineConfig.
  • Separately, the server reads NML_FILE from the INI file with an ordinary file read, when it starts and when it connects, in cycle or not. Such a read holds up only the thread that makes it, not stops.

Which to use

  • A machine with one of the listed GUIs: keep the default. Don’t call StreamErrors unless your client is meant to take over error display, or use off to make sure no client can. Detect trouble from the status instead: task.exec_state, task.task_state (estop), task.interpreter_errcode, limit status and joint faults.
  • A machine with a GUI that is not in the list (a GUI of your own, a vendor’s screen, another QtPyVCP screen started under its own name, or a listed GUI started through a wrapper script under another name): if it shows LinuxCNC’s error popups, it reads the messages; start the server with --error-channel on-demand. Otherwise auto reads as always and the GUI loses most of its error popups to the server. The same applies when the server cannot read the INI file.
  • A headless machine, or one driven entirely over gRPC: keep the default (it reads as always) or say always. Every client then sees every message the server read, status.errors is filled, and replay_buffered returns the newest 256 from before the client connected. Do not use off or on-demand on such a machine unless something else reads the queue: it stalls from the 26th message.

Details:

  • What is observed is not a guarantee: nothing reserves a message for the server, so a GUI that polls the queue first gets that message and the server never sees it.
  • While the server reads the channel and a GUI is running too, both are polling the same queue and each message goes to whichever polls first. The server polls about every 50 ms.
  • In on-demand mode, a message that was waiting in the queue when the first stream starts is read and delivered. When the last stream ends, the server stops reading; a poll already under way at that moment may still take one more message, which then appears in status.errors and in later replays.
  • The server keeps the most recent 256 messages. A StreamErrors client that falls more than 256 messages behind loses the older ones. There is no error; the only sign is a jump in sequence, which clients built against 1.0 cannot see.
  • status.errors carries the newest 20 messages in every GetStatus and StreamStatus message, and they stay there until newer ones push them out. Use ErrorMessage.sequence to tell a new message from one you have already handled. If more than 20 messages arrive between two status reads, the ones in between never appear there, so a gap in sequence between polls is normal; use StreamErrors if you need every message.
  • timestamp is when the server read the message, not when LinuxCNC raised it.

Using with Claude (MCP)

linuxcnc-mcp is an MCP (Model Context Protocol) server built on this API. It lets AI assistants such as Claude monitor and diagnose a machine and, when you opt in, operate it. See Using with Claude (MCP) for what it does and how it uses this server.

Logging

Log Levels

  • INFO (default) - Normal operation, connection events, and one line for each command sent to LinuxCNC with its main values. For an MDI command that line has the full command text, and for an operator message the message text
  • DEBUG - Also one line per RPC with the method name, and for most RPCs a line with its main request fields (command type, file name, query pattern). It adds no other request contents and no responses, with one exception: the full text of every MDI command is logged when it arrives, including one the server then rejects

Enable debug logging:

linuxcnc-grpc --debug

Log Format

2024-01-15 10:30:45 [INFO] linuxcnc_grpc.server: Server configured on 0.0.0.0:50051
2024-01-15 10:30:45 [INFO] linuxcnc_grpc.server: LinuxCNC + HAL gRPC Server

Connection Handling

Reconnection

The server automatically handles LinuxCNC connection issues:

See Starting before LinuxCNC for the details and for what a LinuxCNC shutdown does to the server.

Health service

The server answers the standard gRPC health service (grpc.health.v1.Health) for "" (the server as a whole), linuxcnc.LinuxCNCService and hal.HalService:

  • "" and linuxcnc.LinuxCNCService are NOT_SERVING while the server is waiting for LinuxCNC and SERVING once it has connected. hal.HalService is SERVING from the start.
  • If the server finds that the LinuxCNC it is attached to is gone, all three turn NOT_SERVING (HAL belongs to that LinuxCNC too) and the server stops.
  • When the server stops, every service turns NOT_SERVING before the gRPC shutdown begins, and stays so. Each open Watch then sends NOT_SERVING and ends with status OK, so watchers do not hold up the stop.
  • A service name the server does not know gets NOT_FOUND from Check.

Use Check for probes. It answers at once and holds nothing on the server.

Watch is supported for up to 4 watchers at a time (with the default 32 worker threads; a server built with create_server(max_workers=n) allows half of n - 2, at most 4, so threads are left for the other RPCs (stops run in a pool of their own); with 3 workers or fewer Watch is not available at all; see Thread Pool). Each open Watch occupies one worker thread for as long as it lasts. The first message is the current status (SERVICE_UNKNOWN for a name the server has not set), and after that the status whenever it differs from the last one sent; a status that did not change is not sent again. Changes in quick succession can arrive as one message with the newest status.

A Watch over the limit ends at once with UNIMPLEMENTED and a message saying that the watcher limit is reached (or, with 3 workers or fewer, that Watch is not available) and to use Check. A slot is free again as soon as a watcher’s call ends (cancel, disconnect, deadline), but a refused client is not told. What that means for gRPC’s client-side health checking (a channel configured with a healthCheckConfig): a client whose Watch gets UNIMPLEMENTED treats the server as healthy and stops health checking on that connection; it does not start watching again when a slot frees, so it will not notice the server turning NOT_SERVING. Any other error code would make that client’s channel fail, and it could not use the server at all while the other watchers stay. A client that needs to follow the status should poll Check.

When a Watch ends after NOT_SERVING at shutdown, a client using gRPC’s client-side health checking marks the connection as failed and retries with backoff, which is what it should do with a server that is going away. A watcher sees NOT_SERVING only if the transport still delivers it: serve() stops with a 5-second grace period, which gives it time; a server stopped with stop(0) may close the stream first.

Thread Pool

The server uses two thread pools:

  • The general pool, for every RPC but SendCommand: 32 worker threads by default (create_server(max_workers=n) changes it). Threads are started when needed; 32 instead of 10 made no difference to the server’s idle memory or start-up time (measured).

  • The command pool, for SendCommand alone: max_workers // 2 threads, at least 4 (16 by default). Its threads are named linuxcnc-command.

  • When the server stops, both pools stay in use until the transport has terminated and are then shut down; a call handed to a pool after that is refused, not raised into gRPC.

  • In the command pool, SendCommand calls that are not stops may take every thread but two; the two are kept from them for stops. In the general pool, health Watch calls get at most half of max_workers - 2 and never more than 4 (see Health service), and the streams (StreamStatus, StreamErrors, the HAL streams StreamStatus and WatchValues) and WaitComplete calls together the rest of max_workers - 2; two threads are left for the short calls:

    WorkersHealth watchersStreams and WaitCompleteCommand poolCommands that are not stops
    10042
    41142
    104453
    32 (default)4261614
  • One more stream or WaitComplete is refused with RESOURCE_EXHAUSTED before it starts; one more command is answered RCS_ERROR, not_sent true, Too many commands are waiting; the command was not sent; one more health watcher gets UNIMPLEMENTED. With 2 workers or fewer every stream and WaitComplete is refused. Stops are never counted or refused for this.

  • Not counted: the general pool’s RPCs that end within their own work (GetStatus, GetMachineConfig, ResolveFile, GetServerInfo, the file RPCs, the HAL queries, health Check). They cannot take the command pool’s threads.

  • What the pools do not bound. gRPC gives a call to its pool before the request is read, so the command pool cannot tell a stop from another SendCommand, and it runs calls in the order they came. A command refused over the limit still holds a thread for the moment its refusal takes. A client that sends SendCommand calls faster than they are refused queues them ahead of every stop (the server has no authentication; see Security Considerations). The command pool needs gRPC to honour the thread pool a handler names (grpcio 1.76 does); if it did not, SendCommand would share the general pool, and the server logs an error the first time it sees that.

Every stream that is open occupies one worker thread for as long as it lasts, and so does every WaitComplete while it waits; every stop’s SendCommand occupies a command pool thread until its answer, which comes when its LinuxCNC call has returned (up to about 5 seconds for the message ahead of it and 5 more for its own while the task does not answer). A stream gives its thread back as soon as the client cancels or disconnects, whatever interval it asked for. So does every SendCommand that waits for its turn behind a command the LinuxCNC task is not answering (see A LinuxCNC task that does not respond); a waiting command whose client has gone gives its thread back within about a tenth of a second, unless it only stops something.

Troubleshooting

RPCs return UNAVAILABLE (“LinuxCNC is not running…”)

The server is up but not connected to LinuxCNC. Start LinuxCNC; the server connects within a few seconds:

linuxcnc /path/to/your/machine.ini

If LinuxCNC is running and the server still does not connect, check that both run as the same user and that the server’s Python can import the linuxcnc module (a venv needs --system-site-packages). With --require-linuxcnc the server exits at startup instead of waiting.

The message “The LinuxCNC this server was attached to has shut down or been restarted…” (reason linuxcnc-gone) means the server found its LinuxCNC gone and is stopping; the log says how it found out. A supervisor starts a new server. If it keeps happening after every LinuxCNC restart, raise the supervisor’s restart delay (RestartSec=2, see Method 3: systemd Service).

“Address already in use”

Another process is using the port:

# Find what's using port 50051
sudo lsof -i :50051

# Use a different port
linuxcnc-grpc --port 50052

“Connection refused” from client

  1. Verify the server is running
  2. Check firewall rules
  3. Verify the host/port match
  4. Check network connectivity: nc -zv hostname 50051

Debug Mode

Enable debug logging to see detailed information:

linuxcnc-grpc --debug

This adds, for every RPC, a line with the method name, and for most RPCs a line with the main request fields. Responses are not logged. Commands that were sent to LinuxCNC (including the full text of each MDI command) and connection changes are logged at INFO, so they appear without --debug.

Performance Tuning

Streaming Intervals

Status streaming defaults to 100ms intervals. Adjust based on your needs:

  • 10-50ms - High-frequency updates (UI animation)
  • 100ms - Standard monitoring
  • 500ms-1000ms - Low-bandwidth connections

Clients specify the interval when calling StreamStatus:

request = linuxcnc_pb2.StreamStatusRequest(interval_ms=50)

The longest interval is 60 seconds: a larger interval_ms is treated as 60000. The same default and limit apply to the HAL service’s StreamStatus and WatchValues.

Network Latency

gRPC performs well over high-latency connections. For best results:

  • Use streaming instead of polling for real-time data
  • Batch multiple queries when possible
  • Consider compression for slow connections