Tutorial: a client on another computer Connect to a LinuxCNC machine from your development computer, read and stream its status, and
send one MDI command. Each step has the code in Python, Go, Node.js/TypeScript and Rust.
Before you start A LinuxCNC machine or simulator with the server installed (see
Server setup ). SSH access from your development computer to that machine. LINUXCNC_IP below is its
address. For step 5 only: a machine that is out of E-stop, on and homed. What the MDI step needs LinuxCNC runs an MDI move only on a machine that is out of E-stop, on, homed and in MDI mode.
Take the machine out of E-stop, turn it on and home it at the machine or in its GUI. The
programs in step 5 never do that. Each one does this:
It reads the status and sends nothing unless the machine is on, every joint is homed and
nothing is running. It switches to MDI mode, because the server never switches modes for you (see
Modes and teleop: what to send first ).
It then reads the status again and goes on only if that shows MDI mode and the machine
still on, homed and idle. It sends the move and waits for it with WaitComplete on the command’s linuxcnc_serial. It reads the status again and reports success only when the machine is still on, the
interpreter is idle, trajectory.inpos is true and trajectory.current_vel is zero.
Otherwise it says that the outcome is not confirmed and exits non-zero. The last check is there because RCS_DONE from the wait does not prove that the move finished.
The server also answers it as soon as LinuxCNC has taken a later command from any client, for
example a feed override changed in the GUI during the move (see
WaitComplete ). The status cannot show one thing: an abort
from another client leaves the machine on, idle and in position, like a finished move.
Step 1: start the server and open a tunnel On the LinuxCNC machine, install the server and start it bound to
127.0.0.1. It waits for LinuxCNC if LinuxCNC is not running yet.
~/linuxcnc-grpc-venv/bin/linuxcnc-grpc --host 127.0.0.1 --port 50051 The server has no authentication and no TLS. Keep it bound to 127.0.0.1 and connect through
an SSH tunnel, or use --host 0.0.0.0 only on a trusted LAN. See
Security considerations .
On your development computer, open an SSH tunnel and leave it running. Replace user with your
login on the LinuxCNC machine.
ssh -N -L 127.0.0.1:50051:127.0.0.1:50051 user@LINUXCNC_IP The clients below connect to localhost:50051, which the tunnel forwards to the server. In
another terminal, check that the tunnel is listening:
This succeeds even when the server is not running. The status call in step 3 shows that the
server answers and is connected to LinuxCNC.
Step 2: set up a client project Python mkdir my-cnc-app && cd my-cnc-app
python -m venv venv
source venv/bin/activate
pip install linuxcnc-grpc Go mkdir my-cnc-app && cd my-cnc-app
go mod init my-cnc-app
go get github.com/dougcalobrisi/linuxcnc-grpc
go get google.golang.org/grpc Node.js / TypeScript mkdir my-cnc-app && cd my-cnc-app
npm init -y
npm install linuxcnc-grpc
npm install -D typescript tsx @types/node Create tsconfig.json. Write it yourself: the one that npx tsc --init writes rejects the
import lines of these programs in the CommonJS project that npm init -y makes.
{
"compilerOptions" : {
"target" : "ES2022" ,
"module" : "NodeNext" ,
"moduleResolution" : "NodeNext" ,
"esModuleInterop" : true ,
"strict" : true ,
"skipLibCheck" : true ,
"types" : [ "node" ]
},
"include" : [ "*.ts" ]
} npx tsx runs a program without checking its types. npx tsc --noEmit checks them.
Rust The linuxcnc-grpc crate generates its code at build time, so protoc (the Protocol Buffers compiler) must be on the PATH before you build. Install it with sudo apt install protobuf-compiler on Debian or Ubuntu, or brew install protobuf on macOS.
cargo new my-cnc-app && cd my-cnc-app Add to Cargo.toml:
[ dependencies ]
linuxcnc-grpc = "1.1"
tokio = { version = "1" , features = [ "rt-multi-thread" , "macros" , "signal" , "time" ] }
tonic = "0.12"
futures-util = "0.3" Step 3: read the status The program asks for the status once and prints the position, the mode and the state.
Python Create status.py:
import grpc
from linuxcnc_pb import linuxcnc_pb2 , linuxcnc_pb2_grpc
# Connect to your LinuxCNC machine
channel = grpc . insecure_channel ( "localhost:50051" )
stub = linuxcnc_pb2_grpc . LinuxCNCServiceStub ( channel )
try :
status = stub . GetStatus ( linuxcnc_pb2 . GetStatusRequest (), timeout = 5.0 )
# Print position
pos = status . position . actual_position
print ( f "Position: X= { pos . x : .4f } Y= { pos . y : .4f } Z= { pos . z : .4f } " )
# Print machine state
print ( f "Mode: { linuxcnc_pb2 . TaskMode . Name ( status . task . task_mode ) } " )
print ( f "State: { linuxcnc_pb2 . TaskState . Name ( status . task . task_state ) } " )
except grpc . RpcError as e :
print ( f "Error: { e . code () } : { e . details () } " )
finally :
channel . close () Go Put each Go program in its own directory, because a directory holds only one main function.
Create status/main.go:
package main
import (
"context"
"fmt"
"log"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "github.com/dougcalobrisi/linuxcnc-grpc/packages/go"
)
func main () {
// Connect to your LinuxCNC machine
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 )
ctx , cancel := context . WithTimeout ( context . Background (), 5 * time . Second )
defer cancel ()
status , err := client . GetStatus ( ctx , & pb . GetStatusRequest {})
if err != nil {
log . Fatalf ( "GetStatus failed: %v" , err )
}
// Print position
pos := status . Position . ActualPosition
fmt . Printf ( "Position: X=%.4f Y=%.4f Z=%.4f\n" , pos . X , pos . Y , pos . Z )
// Print machine state
fmt . Printf ( "Mode: %s\n" , status . Task . TaskMode . String ())
fmt . Printf ( "State: %s\n" , status . Task . TaskState . String ())
} Node.js / TypeScript Create status.ts:
import {
LinuxCNCServiceClient ,
GetStatusRequest ,
taskModeToJSON ,
taskStateToJSON ,
credentials ,
Metadata ,
} from "linuxcnc-grpc" ;
// Connect to your LinuxCNC machine
const client = new LinuxCNCServiceClient (
"localhost:50051" ,
credentials . createInsecure ()
);
const deadline = new Date ( Date . now () + 5000 );
client . getStatus ( GetStatusRequest . create (), new Metadata (), { deadline }, ( err , status ) => {
if ( err ) {
console . error ( `Error: ${ err . code } : ${ err . details } ` );
client . close ();
process . exit ( 1 );
}
// Print position
const pos = status ! . position ! . actualPosition ! ;
console . log ( `Position: X= ${ pos . x . toFixed ( 4 ) } Y= ${ pos . y . toFixed ( 4 ) } Z= ${ pos . z . toFixed ( 4 ) } ` );
// Print machine state
console . log ( `Mode: ${ taskModeToJSON ( status ! . task ! . taskMode ) } ` );
console . log ( `State: ${ taskStateToJSON ( status ! . task ! . taskState ) } ` );
client . close ();
}); Rust Replace src/main.rs:
use linuxcnc_grpc ::linuxcnc ::linux_cnc_service_client ::LinuxCncServiceClient ;
use linuxcnc_grpc ::linuxcnc ::{ GetStatusRequest , TaskMode , TaskState };
use std ::time ::Duration ;
#[tokio::main]
async fn main () -> Result < (), Box < dyn std ::error ::Error >> {
// Connect to your LinuxCNC machine
let mut client = LinuxCncServiceClient ::connect ( "http://localhost:50051" ). await ? ;
let mut request = tonic ::Request ::new ( GetStatusRequest {});
request . set_timeout ( Duration ::from_secs ( 5 ));
let status = client . get_status ( request ). await ? . into_inner ();
// Print position
if let Some ( position ) = & status . position {
if let Some ( pos ) = & position . actual_position {
println! ( "Position: X= {:.4} Y= {:.4} Z= {:.4} " , pos . x , pos . y , pos . z );
}
}
// Print machine state
if let Some ( task ) = & status . task {
let mode = match TaskMode ::try_from ( task . task_mode ) {
Ok ( m ) => format! ( " {:?} " , m ),
Err ( _ ) => "UNKNOWN" . to_string (),
};
let state = match TaskState ::try_from ( task . task_state ) {
Ok ( s ) => format! ( " {:?} " , s ),
Err ( _ ) => "UNKNOWN" . to_string (),
};
println! ( "Mode: {mode} " );
println! ( "State: {state} " );
}
Ok (())
} Step 4: stream the position StreamStatus sends a status every interval_ms, here 10 times a second, until the client
cancels. Each program stops on Ctrl+C.
Python Create stream.py and run it with python stream.py:
import grpc
from linuxcnc_pb import linuxcnc_pb2 , linuxcnc_pb2_grpc
channel = grpc . insecure_channel ( "localhost:50051" )
stub = linuxcnc_pb2_grpc . LinuxCNCServiceStub ( channel )
request = linuxcnc_pb2 . StreamStatusRequest ()
request . interval_ms = 100 # 10 updates per second
try :
for status in stub . StreamStatus ( request ):
pos = status . position . actual_position
print ( f " \r X= { pos . x : 8.3f } Y= { pos . y : 8.3f } Z= { pos . z : 8.3f } " , end = "" , flush = True )
except KeyboardInterrupt :
print ( " \n Stopped." )
finally :
channel . close () Go Create stream/main.go and run it with go run ./stream:
package main
import (
"context"
"fmt"
"io"
"log"
"os"
"os/signal"
"syscall"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "github.com/dougcalobrisi/linuxcnc-grpc/packages/go"
)
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 )
// Cancel on Ctrl+C
ctx , cancel := context . WithCancel ( context . Background ())
sigChan := make ( chan os . Signal , 1 )
signal . Notify ( sigChan , syscall . SIGINT , syscall . SIGTERM )
go func () {
<- sigChan
cancel ()
}()
stream , err := client . StreamStatus ( ctx , & pb . StreamStatusRequest {
IntervalMs : 100 , // 10 updates per second
})
if err != nil {
log . Fatalf ( "StreamStatus failed: %v" , err )
}
fmt . Println ( "Streaming status... Press Ctrl+C to stop" )
for {
status , err := stream . Recv ()
if err == io . EOF {
break
}
if err != nil {
if ctx . Err () != nil {
break // Normal cancellation
}
log . Fatalf ( "Stream error: %v" , err )
}
pos := status . Position . ActualPosition
fmt . Printf ( "\rX=%8.3f Y=%8.3f Z=%8.3f " , pos . X , pos . Y , pos . Z )
}
fmt . Println ( "\nStopped." )
} Node.js / TypeScript Create stream.ts and run it with npx tsx stream.ts:
import {
LinuxCNCServiceClient ,
StreamStatusRequest ,
LinuxCNCStatus ,
credentials ,
} from "linuxcnc-grpc" ;
const client = new LinuxCNCServiceClient (
"localhost:50051" ,
credentials . createInsecure ()
);
const request = StreamStatusRequest . create ({ intervalMs : 100 });
const stream = client . streamStatus ( request );
// Set before cancel(): the cancel ends the stream with a CANCELLED error
let cancelling = false ;
stream . on ( "data" , ( status : LinuxCNCStatus ) => {
const pos = status . position ! . actualPosition ! ;
process . stdout . write (
` \ rX= ${ pos . x . toFixed ( 3 ). padStart ( 8 ) } Y= ${ pos . y . toFixed ( 3 ). padStart ( 8 ) } Z= ${ pos . z . toFixed ( 3 ). padStart ( 8 ) } `
);
});
stream . on ( "error" , ( err ) => {
if ( cancelling ) {
return ; // Our own cancel on Ctrl+C
}
console . error ( ` \ nStream error: ${ err } ` );
client . close ();
process . exit ( 1 );
});
// Handle Ctrl+C
process . on ( "SIGINT" , () => {
cancelling = true ;
stream . cancel ();
console . log ( "\nStopped." );
client . close ();
}); Rust Replace src/main.rs and run it with cargo run:
use futures_util ::StreamExt ;
use linuxcnc_grpc ::linuxcnc ::linux_cnc_service_client ::LinuxCncServiceClient ;
use linuxcnc_grpc ::linuxcnc ::StreamStatusRequest ;
use std ::io ::{ self , Write };
#[tokio::main]
async fn main () -> Result < (), Box < dyn std ::error ::Error >> {
let mut client = LinuxCncServiceClient ::connect ( "http://localhost:50051" ). await ? ;
let request = tonic ::Request ::new ( StreamStatusRequest { interval_ms : 100 });
let mut stream = client . stream_status ( request ). await ? . into_inner ();
println! ( "Streaming status... Press Ctrl+C to stop" );
let ctrl_c = tokio ::signal ::ctrl_c ();
tokio ::pin! ( ctrl_c );
loop {
let result = tokio ::select! {
_ = & mut ctrl_c => break ,
next = stream . next () => match next {
Some ( result ) => result ,
None => break ,
},
};
match result {
Ok ( status ) => {
if let Some ( pos ) = status
. position
. as_ref ()
. and_then ( | p | p . actual_position . as_ref ())
{
print! ( " \r X= {:8.3} Y= {:8.3} Z= {:8.3} " , pos . x , pos . y , pos . z );
io ::stdout (). flush () ? ;
}
}
Err ( e ) => {
eprintln! ( " \n Stream error: {e} " );
break ;
}
}
}
println! ( " \n Stopped." );
Ok (())
} Step 5: send an MDI command Read What the MDI step needs first. The program sends G0 X10 Y10, so
make sure that move is safe on your machine or change it. The
mdi_command example is the complete version of this
program.
Python Create mdi.py and run it with python mdi.py:
import sys
import time
import grpc
from linuxcnc_pb import linuxcnc_pb2 , linuxcnc_pb2_grpc
channel = grpc . insecure_channel ( "localhost:50051" )
stub = linuxcnc_pb2_grpc . LinuxCNCServiceStub ( channel )
def get_status ():
return stub . GetStatus ( linuxcnc_pb2 . GetStatusRequest (), timeout = 5.0 )
def machine_is_on ( status ):
return status . task . task_state == linuxcnc_pb2 . STATE_ON
def machine_is_busy ( status ):
"""True while a program, an MDI command or a jog is under way."""
return ( status . task . interp_state != linuxcnc_pb2 . INTERP_IDLE
or not status . trajectory . inpos
or abs ( status . trajectory . current_vel ) >= 1e-6 )
def why_not_ready ( status ):
"""Why nothing may be sent, or None if the machine is on, homed and idle."""
if not machine_is_on ( status ):
state_name = linuxcnc_pb2 . TaskState . Name ( status . task . task_state )
return ( f "the machine is not on (state { state_name } ). Take it out of E-stop "
"and turn it on at the machine or in its GUI" )
if any ( not joint . homed for joint in status . joints [: status . trajectory . joints ]):
return "not every joint is homed. Home the machine at the machine or in its GUI"
if machine_is_busy ( status ):
return "the machine is busy with a program, a command or a jog. Wait for it to finish"
return None
def send ( cmd , serial ):
cmd . serial = serial
cmd . timestamp = int ( time . time () * 1e9 )
return stub . SendCommand ( cmd , timeout = 5.0 )
def wait_for ( sent , step , timeout = 5.0 ):
"""Stop unless `sent` (a SendCommand answer) was dispatched and the wait for it ends with RCS_DONE."""
if sent . status != linuxcnc_pb2 . RCS_DONE :
if sent . not_sent :
sys . exit ( f " { step } was not sent: { sent . error_message } " )
sys . exit ( f " { step } failed and may have been sent: check the machine before retrying. { sent . error_message } " )
request = linuxcnc_pb2 . WaitCompleteRequest ( timeout = timeout )
if sent . HasField ( "linuxcnc_serial" ):
request . linuxcnc_serial = sent . linuxcnc_serial
else :
print ( "Note: no linuxcnc_serial; waiting on the latest command sent by any client" )
result = stub . WaitComplete ( request , timeout = timeout + 5.0 )
if result . status != linuxcnc_pb2 . RCS_DONE :
# RCS_EXEC: the wait timed out. RCS_ERROR: the command failed.
status_name = linuxcnc_pb2 . RcsStatus . Name ( result . status )
sys . exit ( f " { step } did not finish: { status_name } { result . error_message } " )
# Never take the machine out of E-stop or turn it on from here: only check
not_ready = why_not_ready ( get_status ())
if not_ready :
sys . exit ( f "Nothing was sent: { not_ready } , then run this again." )
# Switch to MDI mode
cmd = linuxcnc_pb2 . LinuxCNCCommand ()
cmd . mode . mode = linuxcnc_pb2 . MODE_MDI
wait_for ( send ( cmd , 1 ), "MDI mode" )
# The wait is over, but only the status shows the mode. Check again that the machine is ready
mode_deadline = time . monotonic () + 5.0
while True :
status = get_status ()
if status . task . task_mode == linuxcnc_pb2 . MODE_MDI :
break
if time . monotonic () >= mode_deadline :
sys . exit ( "MDI mode did not show in the status within 5 s. The G-code was not sent." )
time . sleep ( 0.05 )
not_ready = why_not_ready ( status )
if not_ready :
sys . exit ( f "The G-code was not sent: { not_ready } , then run this again." )
# Send a G-code command and wait on its serial
cmd = linuxcnc_pb2 . LinuxCNCCommand ()
cmd . mdi . command = "G0 X10 Y10"
confirm_deadline = time . monotonic () + 30.0
wait_for ( send ( cmd , 2 ), "G0 X10 Y10" , timeout = 30.0 )
# RCS_DONE from the wait is not enough: the status must show the move is over
while True :
status = get_status ()
if not machine_is_on ( status ):
sys . exit ( "The machine is no longer on: the command was stopped and did not finish." )
if not machine_is_busy ( status ):
break
if time . monotonic () >= confirm_deadline :
sys . exit ( "Not confirmed: the wait ended, but the status still shows the machine "
"busy. The command may still be running." )
time . sleep ( 0.05 )
print ( "The machine is on, idle and in position: the command is no longer running" )
channel . close () Go Create mdi/main.go and run it with go run ./mdi:
package main
import (
"context"
"fmt"
"log"
"math"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "github.com/dougcalobrisi/linuxcnc-grpc/packages/go"
)
func machineIsOn ( status * pb . LinuxCNCStatus ) bool {
return status . GetTask (). GetTaskState () == pb . TaskState_STATE_ON
}
// machineIsBusy is true while a program, an MDI command or a jog is under way.
func machineIsBusy ( status * pb . LinuxCNCStatus ) bool {
return status . GetTask (). GetInterpState () != pb . InterpState_INTERP_IDLE ||
! status . GetTrajectory (). GetInpos () ||
math . Abs ( status . GetTrajectory (). GetCurrentVel ()) >= 1e-6
}
// whyNotReady says why nothing may be sent, or "" if the machine is on, homed and idle.
func whyNotReady ( status * pb . LinuxCNCStatus ) string {
if ! machineIsOn ( status ) {
return fmt . Sprintf ( "the machine is not on (state %s). Take it out of E-stop and turn it on at the machine or in its GUI" ,
status . GetTask (). GetTaskState ())
}
for jointIndex , joint := range status . GetJoints () {
if int32 ( jointIndex ) < status . GetTrajectory (). GetJoints () && ! joint . GetHomed () {
return "not every joint is homed. Home the machine at the machine or in its GUI"
}
}
if machineIsBusy ( status ) {
return "the machine is busy with a program, a command or a jog. Wait for it to finish"
}
return ""
}
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 )
ctx , cancel := context . WithTimeout ( context . Background (), 60 * time . Second )
defer cancel ()
getStatus := func () * pb . LinuxCNCStatus {
status , err := client . GetStatus ( ctx , & pb . GetStatusRequest {})
if err != nil {
log . Fatalf ( "GetStatus failed: %v" , err )
}
return status
}
serial := int32 ( 0 )
sendCmd := func ( cmd * pb . LinuxCNCCommand ) * pb . CommandResponse {
serial ++
cmd . Serial = serial
cmd . Timestamp = time . Now (). UnixNano ()
resp , err := client . SendCommand ( ctx , cmd )
if err != nil {
log . Fatalf ( "SendCommand failed: %v" , err )
}
return resp
}
// Stop unless sent (a SendCommand answer) was dispatched and the wait for it ends with RCS_DONE.
waitFor := func ( sent * pb . CommandResponse , step string , timeout float64 ) {
if sent . GetStatus () != pb . RcsStatus_RCS_DONE {
if sent . GetNotSent () {
log . Fatalf ( "%s was not sent: %s" , step , sent . GetErrorMessage ())
}
log . Fatalf ( "%s failed and may have been sent: check the machine before retrying. %s" , step , sent . GetErrorMessage ())
}
if sent . LinuxcncSerial == nil {
fmt . Println ( "Note: no LinuxcncSerial; waiting on the latest command sent by any client" )
}
result , err := client . WaitComplete ( ctx , & pb . WaitCompleteRequest {
Timeout : timeout ,
LinuxcncSerial : sent . LinuxcncSerial ,
})
if err != nil {
log . Fatalf ( "WaitComplete failed: %v" , err )
}
if result . GetStatus () != pb . RcsStatus_RCS_DONE {
// RCS_EXEC: the wait timed out. RCS_ERROR: the command failed.
log . Fatalf ( "%s did not finish: %s %s" , step , result . GetStatus (), result . GetErrorMessage ())
}
}
// Never take the machine out of E-stop or turn it on from here: only check
if notReady := whyNotReady ( getStatus ()); notReady != "" {
log . Fatalf ( "Nothing was sent: %s, then run this again." , notReady )
}
// Switch to MDI mode
waitFor ( sendCmd ( & pb . LinuxCNCCommand { Command : & pb . LinuxCNCCommand_Mode {
Mode : & pb . ModeCommand { Mode : pb . TaskMode_MODE_MDI },
}}), "MDI mode" , 5.0 )
// The wait is over, but only the status shows the mode. Check again that the machine is ready
modeDeadline := time . Now (). Add ( 5 * time . Second )
status := getStatus ()
for status . GetTask (). GetTaskMode () != pb . TaskMode_MODE_MDI {
if ! time . Now (). Before ( modeDeadline ) {
log . Fatal ( "MDI mode did not show in the status within 5 s. The G-code was not sent." )
}
time . Sleep ( 50 * time . Millisecond )
status = getStatus ()
}
if notReady := whyNotReady ( status ); notReady != "" {
log . Fatalf ( "The G-code was not sent: %s, then run this again." , notReady )
}
// Send G-code and wait on its serial
confirmDeadline := time . Now (). Add ( 30 * time . Second )
waitFor ( sendCmd ( & pb . LinuxCNCCommand { Command : & pb . LinuxCNCCommand_Mdi {
Mdi : & pb . MdiCommand { Command : "G0 X10 Y10" },
}}), "G0 X10 Y10" , 30.0 )
// RCS_DONE from the wait is not enough: the status must show the move is over
for {
status := getStatus ()
if ! machineIsOn ( status ) {
log . Fatal ( "The machine is no longer on: the command was stopped and did not finish." )
}
if ! machineIsBusy ( status ) {
break
}
if ! time . Now (). Before ( confirmDeadline ) {
log . Fatal ( "Not confirmed: the wait ended, but the status still shows the machine busy. The command may still be running." )
}
time . Sleep ( 50 * time . Millisecond )
}
fmt . Println ( "The machine is on, idle and in position: the command is no longer running" )
} Node.js / TypeScript Create mdi.ts and run it with npx tsx mdi.ts:
import {
LinuxCNCServiceClient ,
LinuxCNCCommand ,
LinuxCNCStatus ,
CommandResponse ,
GetStatusRequest ,
WaitCompleteRequest ,
InterpState ,
TaskMode ,
TaskState ,
RcsStatus ,
credentials ,
Metadata ,
} from "linuxcnc-grpc" ;
const client = new LinuxCNCServiceClient (
"localhost:50051" ,
credentials . createInsecure ()
);
const RPC_DEADLINE = 5000 ;
function getStatus () : Promise < LinuxCNCStatus > {
return new Promise (( resolve , reject ) => {
client . getStatus ( GetStatusRequest . create (), new Metadata (), { deadline : new Date ( Date . now () + RPC_DEADLINE ) }, ( err , resp ) => {
if ( err ) reject ( err );
else resolve ( resp );
});
});
}
function machineIsOn ( status : LinuxCNCStatus ) : boolean {
return status . task ? . taskState === TaskState . STATE_ON ;
}
// True while a program, an MDI command or a jog is under way.
function machineIsBusy ( status : LinuxCNCStatus ) : boolean {
return (
status . task ? . interpState !== InterpState . INTERP_IDLE ||
status . trajectory ? . inpos !== true ||
Math . abs ( status . trajectory . currentVel ) >= 1 e - 6
);
}
// Why nothing may be sent, or undefined if the machine is on, homed and idle.
function whyNotReady ( status : LinuxCNCStatus ) : string | undefined {
if ( ! machineIsOn ( status )) {
const stateName = status . task ? TaskState [ status . task . taskState ] : "unknown" ;
return `the machine is not on (state ${ stateName } ). Take it out of E-stop and turn it on at the machine or in its GUI` ;
}
const machineJoints = status . joints . slice ( 0 , status . trajectory ? . joints ?? 0 );
if ( machineJoints . some (( joint ) => ! joint . homed )) {
return "not every joint is homed. Home the machine at the machine or in its GUI" ;
}
if ( machineIsBusy ( status )) {
return "the machine is busy with a program, a command or a jog. Wait for it to finish" ;
}
return undefined ;
}
function sendCommand ( cmd : LinuxCNCCommand ) : Promise < CommandResponse > {
cmd . timestamp = Date . now () * 1000000 ;
return new Promise (( resolve , reject ) => {
client . sendCommand ( cmd , new Metadata (), { deadline : new Date ( Date . now () + RPC_DEADLINE ) }, ( err , resp ) => {
if ( err ) reject ( err );
else resolve ( resp );
});
});
}
// Throw unless `sent` (a sendCommand answer) was dispatched and the wait for it ends with RCS_DONE.
async function waitFor ( sent : CommandResponse , step : string , timeout : number ) : Promise < void > {
if ( sent . status !== RcsStatus . RCS_DONE ) {
if ( sent . notSent ) {
throw new Error ( ` ${ step } was not sent: ${ sent . errorMessage } ` );
}
throw new Error ( ` ${ step } failed and may have been sent: check the machine before retrying. ${ sent . errorMessage } ` );
}
if ( sent . linuxcncSerial === undefined ) {
console . log ( "Note: no linuxcncSerial; waiting on the latest command sent by any client" );
}
const request = WaitCompleteRequest . create ({ timeout , linuxcncSerial : sent.linuxcncSerial });
const deadline = new Date ( Date . now () + ( timeout * 1000 ) + 5000 );
const result = await new Promise < CommandResponse >(( resolve , reject ) => {
client . waitComplete ( request , new Metadata (), { deadline }, ( err , resp ) => {
if ( err ) reject ( err );
else resolve ( resp );
});
});
if ( result . status !== RcsStatus . RCS_DONE ) {
// RCS_EXEC: the wait timed out. RCS_ERROR: the command failed.
throw new Error ( ` ${ step } did not finish: ${ RcsStatus [ result . status ] } ${ result . errorMessage } ` );
}
}
async function main() {
// Never take the machine out of E-stop or turn it on from here: only check
const notReady = whyNotReady ( await getStatus ());
if ( notReady !== undefined ) {
throw new Error ( `Nothing was sent: ${ notReady } , then run this again.` );
}
// Switch to MDI mode
let cmd = LinuxCNCCommand . create ({ serial : 1 , mode : { mode : TaskMode.MODE_MDI } });
await waitFor ( await sendCommand ( cmd ), "MDI mode" , 5.0 );
// The wait is over, but only the status shows the mode. Check again that the machine is ready
const modeDeadline = performance . now () + 5000 ;
let modeStatus = await getStatus ();
while ( modeStatus . task ? . taskMode !== TaskMode . MODE_MDI ) {
if ( performance . now () >= modeDeadline ) {
throw new Error ( "MDI mode did not show in the status within 5 s. The G-code was not sent." );
}
await new Promise (( resolve ) => setTimeout ( resolve , 50 ));
modeStatus = await getStatus ();
}
const notReadyInMdiMode = whyNotReady ( modeStatus );
if ( notReadyInMdiMode !== undefined ) {
throw new Error ( `The G-code was not sent: ${ notReadyInMdiMode } , then run this again.` );
}
// Send G-code and wait on its serial
cmd = LinuxCNCCommand . create ({ serial : 2 , mdi : { command : "G0 X10 Y10" } });
const confirmDeadline = performance . now () + 30000 ;
await waitFor ( await sendCommand ( cmd ), "G0 X10 Y10" , 30.0 );
// RCS_DONE from the wait is not enough: the status must show the move is over
for (;;) {
const status = await getStatus ();
if ( ! machineIsOn ( status )) {
throw new Error ( "The machine is no longer on: the command was stopped and did not finish." );
}
if ( ! machineIsBusy ( status )) break ;
if ( performance . now () >= confirmDeadline ) {
throw new Error ( "Not confirmed: the wait ended, but the status still shows the machine busy. The command may still be running." );
}
await new Promise (( resolve ) => setTimeout ( resolve , 50 ));
}
console . log ( "The machine is on, idle and in position: the command is no longer running" );
client . close ();
}
main (). catch (( err ) => {
console . error ( err );
client . close ();
process . exit ( 1 );
}); Rust Replace src/main.rs and run it with cargo run:
use linuxcnc_grpc ::linuxcnc ::linux_cnc_service_client ::LinuxCncServiceClient ;
use linuxcnc_grpc ::linuxcnc ::{
linux_cnc_command ::Command , CommandResponse , GetStatusRequest , InterpState , LinuxCncCommand ,
LinuxCncStatus , MdiCommand , ModeCommand , RcsStatus , TaskMode , TaskState , WaitCompleteRequest ,
};
use std ::time ::{ Duration , Instant , SystemTime , UNIX_EPOCH };
use tonic ::transport ::Channel ;
fn timestamp_ns () -> i64 {
SystemTime ::now ()
. duration_since ( UNIX_EPOCH )
. unwrap ()
. as_nanos () as i64
}
fn machine_is_on ( status : & LinuxCncStatus ) -> bool {
status
. task
. as_ref ()
. is_some_and ( | task | task . task_state () == TaskState ::StateOn )
}
// True while a program, an MDI command or a jog is under way.
fn machine_is_busy ( status : & LinuxCncStatus ) -> bool {
let interpreter_is_idle = status
. task
. as_ref ()
. is_some_and ( | task | task . interp_state () == InterpState ::InterpIdle );
let is_in_position_and_still = status
. trajectory
. as_ref ()
. is_some_and ( | trajectory | trajectory . inpos && trajectory . current_vel . abs () < 1e-6 );
! ( interpreter_is_idle && is_in_position_and_still )
}
// Why nothing may be sent, or None if the machine is on, homed and idle.
fn why_not_ready ( status : & LinuxCncStatus ) -> Option < String > {
if ! machine_is_on ( status ) {
let state_name = status
. task
. as_ref ()
. map_or ( "unknown" , | task | task . task_state (). as_str_name ());
return Some ( format! (
"the machine is not on (state {state_name} ). Take it out of E-stop and turn it on \
at the machine or in its GUI"
));
}
let joint_count = status
. trajectory
. as_ref ()
. map_or ( 0 , | trajectory | trajectory . joints . max ( 0 ) as usize );
if status . joints . iter (). take ( joint_count ). any ( | joint | ! joint . homed ) {
return Some ( "not every joint is homed. Home the machine at the machine or in its GUI" . into ());
}
if machine_is_busy ( status ) {
return Some ( "the machine is busy with a program, a command or a jog. Wait for it to finish" . into ());
}
None
}
// Fail unless `sent` (a send_command answer) was dispatched and the wait for it ends with RCS_DONE.
async fn wait_for (
client : & mut LinuxCncServiceClient < Channel > ,
sent : & CommandResponse ,
step : & str ,
timeout : f64 ,
) -> Result < (), Box < dyn std ::error ::Error >> {
if sent . status () != RcsStatus ::RcsDone {
if sent . not_sent {
return Err ( format! ( " {step} was not sent: {} " , sent . error_message ). into ());
}
return Err ( format! (
" {step} failed and may have been sent: check the machine before retrying. {} " ,
sent . error_message
)
. into ());
}
if sent . linuxcnc_serial . is_none () {
println! ( "Note: no linuxcnc_serial; waiting on the latest command sent by any client" );
}
let request = WaitCompleteRequest {
timeout ,
linuxcnc_serial : sent . linuxcnc_serial ,
.. Default ::default ()
};
let result = client
. wait_complete ( tonic ::Request ::new ( request ))
. await ?
. into_inner ();
if result . status () != RcsStatus ::RcsDone {
// RCS_EXEC: the wait timed out. RCS_ERROR: the command failed.
let status_name = result . status (). as_str_name ();
return Err ( format! ( " {step} did not finish: {status_name} {} " , result . error_message ). into ());
}
Ok (())
}
#[tokio::main]
async fn main () -> Result < (), Box < dyn std ::error ::Error >> {
let mut client = LinuxCncServiceClient ::connect ( "http://localhost:50051" ). await ? ;
// Never take the machine out of E-stop or turn it on from here: only check
let status = client . get_status ( GetStatusRequest {}). await ? . into_inner ();
if let Some ( not_ready ) = why_not_ready ( & status ) {
return Err ( format! ( "Nothing was sent: {not_ready} , then run this again." ). into ());
}
// Switch to MDI mode
let sent = client
. send_command ( tonic ::Request ::new ( LinuxCncCommand {
serial : 1 ,
timestamp : timestamp_ns (),
command : Some ( Command ::Mode ( ModeCommand {
mode : TaskMode ::ModeMdi . into (),
})),
}))
. await ?
. into_inner ();
wait_for ( & mut client , & sent , "MDI mode" , 5.0 ). await ? ;
// The wait is over, but only the status shows the mode. Check again that the machine is ready
let mode_deadline = Instant ::now () + Duration ::from_secs ( 5 );
let status = loop {
let status = client . get_status ( GetStatusRequest {}). await ? . into_inner ();
let is_in_mdi_mode = status
. task
. as_ref ()
. is_some_and ( | task | task . task_mode () == TaskMode ::ModeMdi );
if is_in_mdi_mode {
break status ;
}
if Instant ::now () >= mode_deadline {
return Err ( "MDI mode did not show in the status within 5 s. The G-code was not sent." . into ());
}
tokio ::time ::sleep ( Duration ::from_millis ( 50 )). await ;
};
if let Some ( not_ready ) = why_not_ready ( & status ) {
return Err ( format! ( "The G-code was not sent: {not_ready} , then run this again." ). into ());
}
// Send G-code and wait on its serial
let confirm_deadline = Instant ::now () + Duration ::from_secs ( 30 );
let sent = client
. send_command ( tonic ::Request ::new ( LinuxCncCommand {
serial : 2 ,
timestamp : timestamp_ns (),
command : Some ( Command ::Mdi ( MdiCommand {
command : "G0 X10 Y10" . to_string (),
})),
}))
. await ?
. into_inner ();
wait_for ( & mut client , & sent , "G0 X10 Y10" , 30.0 ). await ? ;
// RCS_DONE from the wait is not enough: the status must show the move is over
loop {
let status = client . get_status ( GetStatusRequest {}). await ? . into_inner ();
if ! machine_is_on ( & status ) {
return Err ( "The machine is no longer on: the command was stopped and did not finish." . into ());
}
if ! machine_is_busy ( & status ) {
break ;
}
if Instant ::now () >= confirm_deadline {
return Err ( "Not confirmed: the wait ended, but the status still shows the machine busy. \
The command may still be running."
. into ());
}
tokio ::time ::sleep ( Duration ::from_millis ( 50 )). await ;
}
println! ( "The machine is on, idle and in position: the command is no longer running" );
Ok (())
} Troubleshooting What you see What to do UNAVAILABLE: failed to connect, or a timeoutCheck that the SSH tunnel is still running and that the server runs on the LinuxCNC machine (nc -zv 127.0.0.1 50051 there). UNAVAILABLE: LinuxCNC is not running…Start LinuxCNC; the server connects within a few seconds. “Nothing was sent” from the step 5 program Take the machine out of E-stop, turn it on and home it at the machine or in its GUI, then run the program again. An MDI command has no effect, or WaitComplete returns RCS_ERROR LinuxCNC refused the command, usually because the machine is not on, homed and in MDI mode. SendCommand returns RCS_ERRORRead error_message, and check the status before you retry (see RCS_ERROR from SendCommand ). INVALID_ARGUMENTA file RPC was given a bad file name or bad content (see Status codes ).
When LinuxCNC refuses a command, SendCommand has already answered RCS_DONE, which only means
that the command was sent. LinuxCNC reports the refusal as an operator error message, in
StreamErrors or status.errors. RCS_ERROR is a normal response, not a gRPC error.
Server troubleshooting covers problems on the server side.
Next