Controlling LinuxCNCrsh from a Java program

More
07 Jul 2012 18:04 #21678 by billooms
This might be heresy, but I would rather program in Java than in C or C++. If there are others out there who want to control LinuxCNC from a Java program, it's quite easy. In my case, I'm running on a separate computer, so I had to enable telnet:

sudo apt-get install telnetd
sudo /etc/init.d/openbsd-inetd restart

Telnet is not secure, but I don't care because my shop network is not connected to the outside world.

Find your computer's IP address by right-clicking on the network symbol at the top right of the screen and select "Connection Information". Substitute your IP address in the code below, or use "localhost" if you are running the Java program on the same machine. Add the following line to your .hal file:

loadusr linuxcncrsh

This is just a simple example. Once you see how it's done you can elaborate to suit your needs.


package testtelnet3;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Scanner;

public class TestTelnet3 {
private final static String IP = "192.168.1.146"; // IP address of my LinuxCNC machine
private final static int PORT = 5007; // Port for LinuxCNCrsh
private final static int CONNECT_TIMOUT = 5; // 5 second time-out for connection

private static Scanner in;
private static PrintWriter out;

public static void main(String[] args) {
try {
SocketAddress sa = new InetSocketAddress(IP, PORT);
Socket socket = new Socket();
socket.connect(sa, CONNECT_TIMOUT * 1000);
InputStream instream = socket.getInputStream();
OutputStream outstream = socket.getOutputStream();
in = new Scanner(instream);
out = new PrintWriter(outstream, true);

System.out.println(sendCommand("hello EMC x 1"));
System.out.println(sendCommand("set echo off"));
System.out.println(sendCommand("get program_status"));
System.out.println(sendCommand("get abs_act_pos"));
System.out.println(sendCommand("get rel_act_pos"));
System.out.println(sendCommand("get joint_pos"));
System.out.println(sendCommand("get pos_offset"));
out.println("quit");

instream.close();
out.close();
outstream.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* Send a command to LinuxCNCrsh and return the response.
* Don't use this for commands that have no response (like "quit").
* @param s command for LinuxCNCrsh
* @return response
*/
private static String sendCommand(String s) {
out.println(s);
return in.nextLine();
}
}

Please Log in or Create an account to join the conversation.

Time to create page: 0.075 seconds
Powered by Kunena Forum