Monitor a job and send alerts
job_monitor.py is a Python program that watches one machine and reports what its jobs do. It
prints a line for each event, and can POST each one as JSON to a webhook, for a chat channel or
a phone notification. It sends no commands. It needs a server of version 1.1 or newer.
Before you start
Start the server on the LinuxCNC machine,
bound to 127.0.0.1. On the computer that runs the monitor, install the Python client and
open an SSH tunnel, which runs until you stop it:
python3 -m venv venv && . venv/bin/activate # Debian refuses a plain pip install
pip install linuxcnc-grpc
ssh -N -L 127.0.0.1:50051:127.0.0.1:50051 user@cnc-machineThe tunnel makes the server reachable at localhost:50051 on this computer only. It supplies
the encryption and the login the server lacks, but anyone with a login on either computer can
reach the forwarded port, and with it send any command. See
Security.
Run it
The program is examples/guides/job_monitor.py in the repository. Download it and run it:
curl -O https://raw.githubusercontent.com/dougcalobrisi/linuxcnc-grpc/main/examples/guides/job_monitor.py
python job_monitor.py --server localhost:50051 --webhook https://hooks.example.com/cnc--interval-ms sets the status interval, 250 ms by default. Leave out --webhook to only
print. Ctrl+C or SIGTERM stops the monitor with exit status 0. A run looks like this:
2026-12-04T18:32:19-05:00 connected: Connected to localhost:50051: STATE_ON, no program running
2026-12-04T18:32:19-05:00 program-started: Started /home/cnc/nc_files/part.ngc
2026-12-04T18:32:20-05:00 program-paused: Paused at line 42
2026-12-04T18:32:21-05:00 program-resumed: Resumed
2026-12-04T18:44:25-05:00 program-finished: /home/cnc/nc_files/part.ngc finished after 12 min 6 s
2026-12-04T18:51:02-05:00 estop: E-stop is activeEach webhook POST has a JSON body like this one, for the program-finished line above:
{"event": "program-finished", "message": "/home/cnc/nc_files/part.ngc finished after 12 min 6 s", "time": "2026-12-04T18:44:25-05:00"}The monitor refuses a --webhook value that is not an http or https URL. A separate thread
sends the POSTs, so a slow webhook does not delay the events on the terminal. A POST that fails
or takes longer than 5 seconds prints a warning on standard error and is not sent again. With
100 events waiting, further ones are printed but not sent.
The events
| Event | When |
|---|---|
connected | The first status arrives, at start or after a lost connection. |
connection-lost | A session ended; reported once per outage, with the reason. |
server-restarted | GetServerInfo.server_instance changed, so this is a new server process. |
program-started | A program started running. |
program-paused, program-resumed | The interpreter paused or went on. |
program-finished | A run ended with no error and the machine still on. |
program-stopped | A run ended after an error, or with the machine no longer on. |
program-unknown | A run was in progress when the run history broke, so its outcome is unknown. |
estop, machine-off, machine-on | task.task_state changed. |
error, message | An error-channel message arrived, only where the server reads errors anyway. |
How it tells what happened
The monitor compares each status with what it knew before. The first status is only a baseline: a monitor started during a job reports no start for it, and gives no elapsed time at its end.
Running and paused
def is_running(status):
"""True while a program runs or is paused, False when none does, None if unknown."""
task = status.task
if (task.interp_state == linuxcnc_pb2.INTERP_STATE_UNSPECIFIED
or task.task_mode == linuxcnc_pb2.TASK_MODE_UNSPECIFIED):
return None # the status says nothing: neither a start nor an end
return (task.task_mode == linuxcnc_pb2.MODE_AUTO
and task.interp_state != linuxcnc_pb2.INTERP_IDLE)A program is running when task.task_mode is MODE_AUTO and task.interp_state is not
INTERP_IDLE, so MDI commands are not counted as jobs. A status whose mode or interpreter
state is unspecified says nothing, and neither starts nor ends a run. The enums are in
Types.
A run is paused while interp_state is INTERP_PAUSED. The GUI’s pause button, an M0, and
an M1 with optional stop on all show this way, as program-paused. The line in the message
is task.motion_line, the line of the last move, so for an M0 it is the move before it.
Start and end
def _compare(self, status, running):
"""What changed since the last status that said whether a program runs."""
events = []
if running and not self.running:
events += self._due_end(force=True) # an earlier end still held back
self._start_run(status, start_seen=True)
events.append(("program-started", f"Started {self.run_file}"))
elif self.running and not running:
self._end_of_run() # reported END_GRACE later, as finished or stopped
elif running and is_paused(status) != self.paused:
if is_paused(status):
events.append(("program-paused", f"Paused at line {status.task.motion_line}"))
else:
events.append(("program-resumed", "Resumed"))
return eventsA finished program and one aborted without an error look the same in the status: the
interpreter goes back to INTERP_IDLE with the machine on. Both are reported as
program-finished. The GUI’s stop button gives that result, for example. The monitor reports
program-stopped when the machine is no longer STATE_ON, or when an OPERATOR_ERROR or
NML_ERROR arrived during the run.
The error that ends a run can arrive just after the status that shows the end. So the monitor
holds the end back for 0.5 seconds, and an error within that time still makes it
program-stopped.
A break in the run history
Two things break the history of a run: a changed connection_id, which means the server
connected to LinuxCNC again, and an outage of the status stream. See
Telling servers and connections apart.
After a break the monitor takes a new baseline and carries neither the timer nor the error
flag across. A run in progress at the break is reported as program-unknown, with one
exception: after an outage on the same connection, the same file still running is taken as the
same run, with no event and no elapsed time at its end. The machine state is compared across
the break as usual, so an E-stop during an outage is still reported as estop. Error messages
from an older connection are ignored.
Lost connections
Each session calls GetServerInfo with a
5-second deadline, then opens StreamStatus.
A 1.0 server answers GetServerInfo with UNIMPLEMENTED, and the monitor then exits with
status 1 and a message that says so. When a call ends with another error, this function words
the connection-lost event:
def describe_failure(error):
"""Turns the error that ended a call into a sentence for the operator."""
reason = dict(error.trailing_metadata() or ()).get(REASON_KEY)
if error.code() == grpc.StatusCode.UNAVAILABLE and reason == "not-connected":
return "The server is waiting for LinuxCNC to start"
if error.code() == grpc.StatusCode.UNAVAILABLE and reason == "linuxcnc-gone":
return "LinuxCNC shut down or restarted; the server is stopping"
if error.code() == grpc.StatusCode.UNAVAILABLE and reason is None:
return f"Cannot reach the server, or no reason given ({error.details()})"
return f"{error.code().name}: {error.details()}"It reads the linuxcnc-grpc-reason entry. not-connected means the
server is waiting for LinuxCNC. linuxcnc-gone means the server found its LinuxCNC gone and
is stopping. No entry usually means the server could
not be reached, so the monitor prints gRPC’s message too.
A normal LinuxCNC shutdown gives neither reason. LinuxCNC signals the server, which ends its streams without an error, and the monitor reports “The server ended the status stream”. The attempts after that fail with no reason until the server runs again.
The monitor retries after 1 second, then doubles the wait up to 30 seconds. A connection can also die without an error, for example when a link under the SSH tunnel drops. So a stream that sends nothing for 30 seconds counts as lost, or for twice the interval plus 5 seconds if that is longer. The monitor cancels it and reconnects.
Errors and the GUI
LinuxCNC’s error channel is a single queue, and reading a message removes it. On a machine whose GUI shows errors, the server reads the queue only while a StreamErrors client is connected. A monitor that kept a
StreamErrorsstream open would take error popups away from the operator. See Error messages and the GUI.
So the monitor opens StreamErrors only when GetServerInfo says the server reads the queue
all the time:
# Only read errors when the server reads them anyway; see the guide.
error_stream = None
if info.error_channel_mode == "always":
error_stream = stub.StreamErrors(linuxcnc_pb2.StreamErrorsRequest())
threading.Thread(target=self.read_errors, args=(error_stream,), daemon=True).start()
threading.Thread(target=self.recheck_error_mode, args=(stub, error_stream, session_over),
daemon=True).start()That answer can change. A server that connected to LinuxCNC during a program reports always
until the program ends and it has read the INI file (see
Connected while in cycle). On a machine with a
GUI the mode then becomes on-demand, and a stream still open would take messages from the
GUI. So while the stream is open, a second thread asks again every 2 seconds and cancels
the stream when the mode is no longer always:
while not session_over.wait(MODE_CHECK_INTERVAL):
try:
info = stub.GetServerInfo(linuxcnc_pb2.GetServerInfoRequest(), timeout=RPC_TIMEOUT)
except grpc.RpcError:
continue # the status stream reports a lost connection
except ValueError:
return # the channel was closed: the session is over
if info.error_channel_mode != "always":
error_stream.cancel() # the GUI reads errors now: leave them to it
returnOPERATOR_ERROR and NML_ERROR are reported as error and mark the run as stopped. The
*_TEXT and *_DISPLAY types, such as a tool change prompt, are reported as message. On a
machine with a GUI the monitor reports no errors, and an aborted run ends as program-finished
unless the machine also left STATE_ON.
Other languages
The program exists in Python only. In Go, Node.js or Rust, start from the
stream_status example of that language, in
examples/go,
examples/node
or
examples/rust.
It already opens the stream and handles its end. Copy two things from this page: the running
test above, with a baseline from the first status, and the linuxcnc-grpc-reason entry, which
is in the trailing metadata of the error that ends the stream (see
Errors and reasons).
Run it as a service
On a Linux monitoring computer, run the tunnel and the monitor as systemd user services. The
tunnel needs key-based SSH login. ServerAliveInterval makes a dead link end ssh, and
systemd starts it again. Save this as ~/.config/systemd/user/cnc-tunnel.service:
[Unit]
Description=SSH tunnel to the LinuxCNC gRPC server
[Service]
ExecStart=/usr/bin/ssh -N -o ExitOnForwardFailure=yes -o ServerAliveInterval=15 -L 127.0.0.1:50051:127.0.0.1:50051 user@cnc-machine
Restart=always
RestartSec=5
[Install]
WantedBy=default.targetSave this as ~/.config/systemd/user/job-monitor.service, with your paths:
[Unit]
Description=LinuxCNC job monitor
Wants=cnc-tunnel.service
After=cnc-tunnel.service
[Service]
ExecStart=/home/me/venv/bin/python /home/me/job_monitor.py --server localhost:50051 --webhook https://hooks.example.com/cnc
Restart=on-failure
RestartSec=5
[Install]
WantedBy=default.targetEnable both and follow the events in the journal. loginctl enable-linger keeps them running
after you log out.
systemctl --user daemon-reload
systemctl --user enable --now cnc-tunnel.service job-monitor.service
journalctl --user -u job-monitor.service -fLimits
- The monitor sees the status once per interval. A state that starts and ends between two
updates, such as a short pause, is missed. Use a shorter
--interval-msif that matters. - A finished program and one aborted without an error are both
program-finished. - A hardware E-stop shows only as a change of
task.task_state, the same as one pressed in the GUI. - A feed hold from a HAL input and a feed override at 0% stop motion without changing
task.interp_state, so they are not reported as pauses. - Errors raised while the monitor is disconnected are not reported after it reconnects.
- A crashed LinuxCNC is often not detected: the server keeps returning the last status, so the monitor shows the machine as it was. See When LinuxCNC stops.
- While LinuxCNC’s task is stopped holding the status, the stream sends nothing, and the monitor
reports
connection-lost(“No status for 30 s”) and keeps retrying. See A task stopped while it holds the status.