Client quickstart

Install a client library and make the first calls. You need a running server; the programs below reach it at localhost:50051, on the LinuxCNC machine itself or through an SSH tunnel.

Install a client

python3 -m venv venv && . venv/bin/activate   # Debian refuses a plain pip install
pip install linuxcnc-grpc
go get github.com/dougcalobrisi/linuxcnc-grpc

Requires Go 1.25 or later.

npm install linuxcnc-grpc

Add to Cargo.toml:

[dependencies]
linuxcnc-grpc = "1.1"
tokio = { version = "1", features = ["full"] }
tonic = "0.12"

The crate generates its code at build time, so protoc must be on the PATH: sudo apt install protobuf-compiler on Debian or Ubuntu, brew install protobuf on macOS.

Status, a stream and HAL

Each program reads the status once, takes three updates from a status stream and lists the HAL pins that match a pattern. None of them sends a command.

import grpc
from linuxcnc_pb import hal_pb2, hal_pb2_grpc, linuxcnc_pb2, linuxcnc_pb2_grpc

channel = grpc.insecure_channel("localhost:50051")
stub = linuxcnc_pb2_grpc.LinuxCNCServiceStub(channel)
hal_stub = hal_pb2_grpc.HalServiceStub(channel)

# Read the status once
status = stub.GetStatus(linuxcnc_pb2.GetStatusRequest(), timeout=5.0)
pos = status.position.actual_position
print(f"Position: X={pos.x:.3f} Y={pos.y:.3f} Z={pos.z:.3f}")
print(f"Mode:  {linuxcnc_pb2.TaskMode.Name(status.task.task_mode)}")
print(f"State: {linuxcnc_pb2.TaskState.Name(status.task.task_state)}")

# Stream it, one update every 100 ms, and stop after three
stream = stub.StreamStatus(linuxcnc_pb2.StreamStatusRequest(interval_ms=100))
for update_number, update in enumerate(stream, start=1):
    print(f"Update {update_number}: X={update.position.actual_position.x:.3f}")
    if update_number == 3:
        stream.cancel()
        break

# List the HAL pins that match a glob pattern
response = hal_stub.QueryPins(hal_pb2.QueryPinsCommand(pattern="axis.x.*"), timeout=5.0)
if not response.success:
    print(f"QueryPins failed: {response.error}")
for pin in response.pins:
    print(pin.name)

channel.close()
package main

import (
    "context"
    "fmt"
    "log"
    "time"

    pb "github.com/dougcalobrisi/linuxcnc-grpc/packages/go"
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials/insecure"
)

func main() {
    conn, err := grpc.NewClient("localhost:50051",
        grpc.WithTransportCredentials(insecure.NewCredentials()))
    if err != nil {
        log.Fatalf("Failed to connect: %v", err)
    }
    defer conn.Close()

    client := pb.NewLinuxCNCServiceClient(conn)
    halClient := pb.NewHalServiceClient(conn)
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    // Read the status once
    status, err := client.GetStatus(ctx, &pb.GetStatusRequest{})
    if err != nil {
        log.Fatalf("GetStatus failed: %v", err)
    }
    pos := status.GetPosition().GetActualPosition()
    fmt.Printf("Position: X=%.3f Y=%.3f Z=%.3f\n", pos.GetX(), pos.GetY(), pos.GetZ())
    fmt.Printf("Mode:  %s\n", status.GetTask().GetTaskMode())
    fmt.Printf("State: %s\n", status.GetTask().GetTaskState())

    // Stream it, one update every 100 ms, and stop after three
    streamCtx, stopStream := context.WithCancel(ctx)
    stream, err := client.StreamStatus(streamCtx, &pb.StreamStatusRequest{IntervalMs: 100})
    if err != nil {
        log.Fatalf("StreamStatus failed: %v", err)
    }
    for updateNumber := 1; updateNumber <= 3; updateNumber++ {
        update, err := stream.Recv()
        if err != nil {
            log.Fatalf("Stream error: %v", err)
        }
        fmt.Printf("Update %d: X=%.3f\n", updateNumber, update.GetPosition().GetActualPosition().GetX())
    }
    stopStream()

    // List the HAL pins that match a glob pattern
    response, err := halClient.QueryPins(ctx, &pb.QueryPinsCommand{Pattern: "axis.x.*"})
    if err != nil {
        log.Fatalf("QueryPins failed: %v", err)
    }
    if !response.GetSuccess() {
        log.Fatalf("QueryPins failed: %s", response.GetError())
    }
    for _, pin := range response.GetPins() {
        fmt.Println(pin.GetName())
    }
}
import {
  LinuxCNCServiceClient,
  HalServiceClient,
  GetStatusRequest,
  StreamStatusRequest,
  QueryPinsCommand,
  LinuxCNCStatus,
  TaskMode,
  TaskState,
  credentials,
} from "linuxcnc-grpc";

const client = new LinuxCNCServiceClient("localhost:50051", credentials.createInsecure());
const halClient = new HalServiceClient("localhost:50051", credentials.createInsecure());

// Read the status once
client.getStatus(GetStatusRequest.create(), (err, status) => {
  if (err) throw err;
  const pos = status!.position!.actualPosition!;
  console.log(`Position: X=${pos.x.toFixed(3)} Y=${pos.y.toFixed(3)} Z=${pos.z.toFixed(3)}`);
  console.log(`Mode:  ${TaskMode[status!.task!.taskMode]}`);
  console.log(`State: ${TaskState[status!.task!.taskState]}`);
  streamThreeUpdates();
});

// Stream it, one update every 100 ms, and stop after three
function streamThreeUpdates(): void {
  const stream = client.streamStatus(StreamStatusRequest.create({ intervalMs: 100 }));
  let updateCount = 0;
  stream.on("data", (update: LinuxCNCStatus) => {
    if (updateCount === 3) return; // Already cancelled
    updateCount += 1;
    console.log(`Update ${updateCount}: X=${update.position!.actualPosition!.x.toFixed(3)}`);
    if (updateCount === 3) {
      stream.cancel();
      listPins();
    }
  });
  stream.on("error", (err) => {
    // Our own cancel ends the stream with a CANCELLED error
    if (updateCount < 3) throw err;
  });
}

// List the HAL pins that match a glob pattern
function listPins(): void {
  halClient.queryPins(QueryPinsCommand.create({ pattern: "axis.x.*" }), (err, response) => {
    if (err) throw err;
    if (!response!.success) throw new Error(`QueryPins failed: ${response!.error}`);
    for (const pin of response!.pins) {
      console.log(pin.name);
    }
    client.close();
    halClient.close();
  });
}
use linuxcnc_grpc::hal::hal_service_client::HalServiceClient;
use linuxcnc_grpc::hal::QueryPinsCommand;
use linuxcnc_grpc::linuxcnc::linux_cnc_service_client::LinuxCncServiceClient;
use linuxcnc_grpc::linuxcnc::{GetStatusRequest, StreamStatusRequest};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = LinuxCncServiceClient::connect("http://localhost:50051").await?;
    let mut hal_client = HalServiceClient::connect("http://localhost:50051").await?;

    // Read the status once
    let status = client.get_status(GetStatusRequest {}).await?.into_inner();
    if let Some(pos) = status.position.as_ref().and_then(|position| position.actual_position.as_ref()) {
        println!("Position: X={:.3} Y={:.3} Z={:.3}", pos.x, pos.y, pos.z);
    }
    if let Some(task) = &status.task {
        println!("Mode:  {}", task.task_mode().as_str_name());
        println!("State: {}", task.task_state().as_str_name());
    }

    // Stream it, one update every 100 ms, and stop after three
    let mut stream = client
        .stream_status(StreamStatusRequest { interval_ms: 100 })
        .await?
        .into_inner();
    for update_number in 1..=3 {
        let Some(update) = stream.message().await? else { break };
        let x = update
            .position
            .and_then(|position| position.actual_position)
            .map_or(0.0, |pos| pos.x);
        println!("Update {update_number}: X={x:.3}");
    }
    drop(stream); // Dropping the stream cancels it

    // List the HAL pins that match a glob pattern
    let response = hal_client
        .query_pins(QueryPinsCommand { pattern: "axis.x.*".to_string() })
        .await?
        .into_inner();
    if !response.success {
        return Err(format!("QueryPins failed: {}", response.error).into());
    }
    for pin in &response.pins {
        println!("{}", pin.name);
    }
    Ok(())
}

A real client gives every call a deadline, as the Python and Go programs do. A stream that runs until Ctrl+C is in step 4 of the tutorial.

More to read from the server

The same stub has the other read-only calls. In Python:

import grpc
from linuxcnc_pb import linuxcnc_pb2, linuxcnc_pb2_grpc

with grpc.insecure_channel("localhost:50051") as channel:
    stub = linuxcnc_pb2_grpc.LinuxCNCServiceStub(channel)

    # What kind of machine this is: units, limits, which joint drives which axis
    config = stub.GetMachineConfig(linuxcnc_pb2.GetMachineConfigRequest(), timeout=5.0)
    print(config.machine_name, config.linear_units_name)
    for joint in config.joints:
        print(joint.joint_number, joint.axis_letter, joint.min_limit, joint.max_limit)

    # The server's version and whether it is connected to LinuxCNC
    server_info = stub.GetServerInfo(linuxcnc_pb2.GetServerInfoRequest(), timeout=5.0)
    print(server_info.server_version, server_info.linuxcnc_connected)

GetServerInfo works while LinuxCNC is not running, when most other RPCs answer UNAVAILABLE. A 1.0 server does not have it and answers UNIMPLEMENTED. See GetMachineConfig, GetServerInfo and, for uploading and listing G-code files, File management.

Send a command

A command is a LinuxCNCCommand message with one command field set (state, mode, mdi, jog and so on), sent with SendCommand. Four rules apply to every client:

  • RCS_DONE from SendCommand means the command was dispatched, not that it finished.
  • To wait for a command, pass the linuxcnc_serial from its response to WaitComplete, then read the status to confirm that a motion is over (see WaitComplete).
  • The server never switches modes for you (see Modes and teleop: what to send first).
  • A refused command is not a gRPC error. SendCommand returns a normal response with RCS_ERROR and the reason in error_message, so check response.status as well as catching the RPC error (see RCS_ERROR from SendCommand).

Client code should check that the machine is out of E-stop, on and homed before it sends motion, and never take the machine out of E-stop, turn it on or home it itself. Step 5 of the tutorial is a complete MDI program in each language that makes these checks, and the jog_axis example does the same for jogging.

Errors

Every call can fail with a gRPC status. In Python that is a grpc.RpcError:

try:
    status = stub.GetStatus(linuxcnc_pb2.GetStatusRequest(), timeout=5.0)
except grpc.RpcError as error:
    print(f"Error: {error.code()}: {error.details()}")

The codes a client meets most often:

  • UNAVAILABLE: the server cannot be reached, or it cannot reach or read LinuxCNC right now. GetServerInfo tells the two apart, and the server’s own answers usually carry a linuxcnc-grpc-reason in the trailing metadata.
  • INVALID_ARGUMENT, NOT_FOUND, ALREADY_EXISTS and ABORTED: a file RPC or WatchValues was given something it cannot use.
  • RESOURCE_EXHAUSTED: too many streams and WaitComplete calls are open; try again when one has ended.
  • FAILED_PRECONDITION: StreamErrors on a server started with --error-channel off, or GetMachineConfig while the machine has been in cycle ever since the server connected; call again once it is idle.
  • UNIMPLEMENTED: the server is older than the RPC.

Status codes has the full list, and Reasons lists the metadata values.

Next