Examples guide

The repository has six example programs, each in Python, Go, Node.js and Rust. This page shows what each one does, how to run it, the few lines that matter and what it prints. The full programs are in examples/.

ExampleWhat it doesSource
get_statusReads the machine status once and prints itPython, Go, Node.js, Rust
stream_statusStreams live status updates for a displayPython, Go, Node.js, Rust
jog_axisJogs X by a fixed increment, then jogs Y continuously for half a secondPython, Go, Node.js, Rust
mdi_commandRuns MDI G-code, one command or an interactive sessionPython, Go, Node.js, Rust
hal_queryQueries HAL pins, signals, parameters and components, or watches valuesPython, Go, Node.js, Rust
upload_fileUploads a sample G-code file and lists the files; deletes it only with --cleanupPython, Go, Node.js, Rust

jog_axis and mdi_command move the machine. They never take it out of E-stop, power it on or home it, but they do change its mode and move axes. Never run untested code on a machine with a workpiece or near people. The complete rules the motion examples follow are in the examples README.

Running the examples

Start the server on the LinuxCNC machine with ~/linuxcnc-grpc-venv/bin/linuxcnc-grpc --host 127.0.0.1 --port 50051 (see Start the server), and run the examples there or through an SSH tunnel (ssh -N -L 127.0.0.1:50051:127.0.0.1:50051 user@cnc-machine). The server has no authentication or TLS; see Security considerations.

Each language runs the same programs with the same arguments, from its directory under examples/. Python needs linuxcnc-grpc installed in a virtual environment (python3 -m venv venv && venv/bin/pip install linuxcnc-grpc). Node.js uses the package from the checkout, so build it first: cd packages/node && npm ci && npm run build, then npm install in examples/node.

PythonGoNode.jsRust
python get_status.py --port 50051go run ./cmd/get_status --port 50051npx tsx get_status.ts --port 50051cargo run --bin get_status -- --port 50051

The rest of this page uses Python. In Go, flags come before any other argument: go run ./cmd/mdi_command --no-wait "M5" works, and go run ./cmd/mdi_command "M5" --no-wait is refused.

get_status

Reads the status once with GetStatus and prints the task state, position, trajectory, joints (flags: homed, enabled, fault), spindles, I/O and active G-codes.

# Request current status
request = linuxcnc_pb2.GetStatusRequest()
status = stub.GetStatus(request, timeout=RPC_TIMEOUT)
============================================================
LinuxCNC Status
============================================================

[Task]
  Mode:       MODE_MANUAL
  State:      STATE_ON
  Exec State: EXEC_DONE
  Interp:     INTERP_IDLE

[Position]
  X:     0.0000  Y:     0.0000  Z:     0.0000

[Trajectory]
  Enabled:    True
  Feed Rate:  100.0%
  Rapid Rate: 100.0%
  Velocity:   0.00

[Joints]
  Joint 0: [HE-] pos=    0.0000
  Joint 1: [HE-] pos=    0.0000
  Joint 2: [HE-] pos=    0.0000

[Spindles]
  Spindle 0: OFF @ 0 RPM

[I/O]
  E-stop: OK
  Mist:   COOLANT_OFF
  Flood:  COOLANT_OFF

[Active G-codes]
  G17 G21 G40 G49 G54 G64 G80 G90 G91.1 G94
  G97 G99

stream_status

Opens a StreamStatus stream with the requested interval_ms and rewrites one line in place for every update.

python stream_status.py                  # one update every 100 ms (the default)
python stream_status.py --interval 2000  # one update every 2 seconds
Streaming status from localhost:50051 (interval: 100ms)
Press Ctrl+C to stop

--------------------------------------------------------------------------------
[    42] X:   0.000 Y:   0.000 Z:   0.000 | MANUAL/ON/IDLE       | V:   0.00 F:100.0%

--interval is in milliseconds, a whole number from 1 to 60000; anything else is refused before the stream opens. After Ctrl+C the example prints how many updates it received and the rate, and exits 0. It exits non-zero when the stream fails, when the server cancels it, and when no update arrives in time (see Streaming timeouts).

jog_axis

Jogs X by +1 unit with JOG_INCREMENT, then jogs Y with JOG_CONTINUOUS for half a second and sends JOG_STOP. It runs the two moves and exits; it is not a keyboard jog pendant.

python jog_axis.py              # run both jogs (moves the machine!)
python jog_axis.py --skip-demo  # only show the current position

It never resets E-stop, powers the machine on or homes it, and it switches to manual mode with teleop on itself (see Modes and teleop); what it checks before each jog is in Before they move anything.

“Idle” takes three fields, because the interpreter state alone can read INTERP_IDLE during an MDI move. mdi_command uses the same test:

return (status.task.interp_state != linuxcnc_pb2.INTERP_IDLE
        or not status.trajectory.inpos
        or abs(status.trajectory.current_vel) >= STOPPED_VELOCITY)

The continuous jog sends its stop on the failure path and on the normal path. The interrupt handlers are installed before anything moves, so Ctrl+C leaves through the same code:

try:
    # From here on a stop is always sent: after the sleep, on Ctrl+C and
    # on any error, including a start whose answer never came. Nothing is
    # printed until the stop has been sent: a failed print must not come
    # before it.
    sent = client.jog_continuous(CONTINUOUS_AXIS, JOG_VELOCITY)
    if sent.status != linuxcnc_pb2.RCS_DONE:
        raise ExampleError(f"Continuous jog was refused: {sent.error_message}")
    pause(CONTINUOUS_JOG_SECONDS)
except BaseException as jog_error:
    stop_response = stop_jog(client, CONTINUOUS_AXIS)
    # Dispatched is not stopped: confirm it on fresh status.
    raise_unless_stop_confirmed(client, CONTINUOUS_AXIS, stop_response, jog_error)
    raise
stop_response = stop_jog(client, CONTINUOUS_AXIS)
report("Jog stop sent.")

Jog velocity is in machine units per second. The example uses 1 unit per second and a 1 unit increment; change the constants at the top of the file to suit the machine.

Current position: X=0.0000 Y=0.0000 Z=0.0000
Turning teleop on...

--- Incremental Jog Demo ---
Jogging X by +1 at 1 units/s...
X moved from 0.0000 to 1.0000

--- Continuous Jog Demo ---
Jogging Y at +1 units/s for 0.5 seconds...
Jog stop sent.
Y moved from 0.0000 to 0.5300

Jog demo complete!

How it confirms the stop, and its exit codes, are in How jog_axis stops.

mdi_command

Sends MDI G-code and waits for it with WaitComplete on the command’s linuxcnc_serial, then confirms in the status that it is no longer running.

python mdi_command.py "G0 X10 Y10"
python mdi_command.py --wait-timeout 300 "G1 X200 F50"  # wait up to 5 minutes (default 60 s)
python mdi_command.py --no-wait "M5"                    # send without waiting
python mdi_command.py --interactive

Before every command it checks that the machine is on, homed and idle, and switches to MDI mode if needed. It never resets E-stop, powers the machine on or homes it.

RCS_DONE from the wait does not prove the command finished, so the example confirms it in the status before it prints Done.; what Done. does and does not show is in When mdi_command says Done..

With the machine already in MDI mode, python mdi_command.py "G0 X10 Y10" prints:

Executing: G0 X10 Y10
  Waiting for completion...
  Done.
Position: X=10.0000 Y=10.0000 Z=0.0000

hal_query

Queries HAL through HalService, with glob patterns.

python hal_query.py pins "axis.*"     # also: signals, params, components, status
python hal_query.py watch spindle.0.speed-out axis.x.pos-cmd  # print changes, every 500 ms
python hal_query.py watch spindle.0.speed-out --interval 2000

A query can fail while the RPC succeeds, so the example checks success and exits non-zero when it is false:

request = hal_pb2.QueryPinsCommand()
request.pattern = pattern

response = stub.QueryPins(request, timeout=RPC_TIMEOUT)
if not response.success:
    print(f"Error: {response.error}", file=sys.stderr)
    sys.exit(1)

Against the mock server, python hal_query.py pins "axis.*" prints:

Found 1 pins matching 'axis.*':

Name                                               Type   Dir  Value           Signal
------------------------------------------------------------------------------------------
axis.x.pos-cmd                                     FLOAT  OUT  123.456         x-pos-cmd

The mock fills in a signal name; a real server always leaves it empty, shown as -.

In Node.js, s64 and u64 values are exact only up to Number.MAX_SAFE_INTEGER (2^53 - 1); a larger value arrives as the nearest number.

upload_file

Uploads a sample G-code file with UploadFile and lists the NC files directory with ListFiles.

python upload_file.py                         # upload as grpc_example.ngc
python upload_file.py --filename my_test.ngc  # upload under another name
python upload_file.py --cleanup               # upload, then delete by name

fail_if_exists makes the server refuse to replace an existing file (ALREADY_EXISTS), and the example then stops:

upload_request = linuxcnc_pb2.UploadFileRequest(
    filename=filename,
    content=SAMPLE_GCODE,
    fail_if_exists=True,
)

Without --cleanup the file stays on the machine, and a second run stops with “already exists”. With --cleanup the example deletes the file by name with DeleteFile: if another client replaced it under that name after the upload, that client’s file is the one deleted, and the example warns about this first.

Uploading 'grpc_example.ngc'...
  Written to: /home/linuxcnc/linuxcnc/nc_files/grpc_example.ngc
  Size: 141 bytes

Listing files...
  Directory: /home/linuxcnc/linuxcnc/nc_files
  Name                               Size  Type
  ------------------------------ --------  ----
  grpc_example.ngc                    141  FILE
  projects                           4096  DIR

'grpc_example.ngc' was left on the machine. Delete it in the LinuxCNC GUI or the nc_files directory, or with the DeleteFile RPC, when you no longer need it.

The examples do not use ReadFile (download a file) or ResolveFile (is this name the loaded program?); see ReadFile and ResolveFile.

Testing with the mock server

For development without LinuxCNC, start python tests/mock_server.py --port 50051 from the repository root and point the examples at it. The mock’s status is fixed: a command it accepts changes nothing, and one the real server would refuse before sending it is refused. So jog_axis and mdi_command stop with “did not show in the status” at their mode change, which is the check doing its job. The mock does not implement UploadFile, ListFiles or DeleteFile, so upload_file gets UNIMPLEMENTED. For those, use the LinuxCNC simulator (see E2E testing).

Common patterns

Streaming timeouts

A stream that runs until Ctrl+C cannot have an overall deadline. stream_status instead gives up, and exits non-zero, when no update has arrived for 30 seconds, or for twice the interval plus 5 seconds if that is longer (stream_idle_timeout).

In Rust the call that opens the stream needs the timeout too, because a server may send its response headers only with the first update. A stream that ends with CANCELLED is a clean end only when the example cancelled it itself, so each example records that it cancelled instead of going by the status code; a cancel from the server is an error. hal_query watch has no idle timeout, because the server sends only when a watched value changes.

Stopping motion on Ctrl+C

A program that starts motion must stop it on every way out. In jog_axis the signal handler only sets a flag, and the waits check it and raise, so the stop code runs:

def pause(seconds: float) -> None:
    """Sleep in short slices; raise Interrupted soon after an interrupt arrives."""
    wake_time = time.monotonic() + seconds
    while True:
        if interrupt_was_requested:
            raise Interrupted()
        remaining = wake_time - time.monotonic()
        if remaining <= 0:
            return
        time.sleep(min(remaining, INTERRUPT_CHECK_INTERVAL))

Do not exit from inside the handler (os._exit, process.exit, os.Exit, log.Fatal): that skips the stop. In Python, do not take a lock there either: Event.set() and Event.wait() share one, so the flag is a plain boolean. Print nothing between the start of a jog and its stop, because a closed pipe makes a write fail. A panic in Go or Rust also sends the stop before it goes on. A signal the example does not handle (SIGHUP when the terminal closes, SIGKILL) still ends it without a stop, as does losing the network. Keep the E-stop in reach.