Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Control a CNC Machine Using Java or Groovy

DZone's Guide to

Control a CNC Machine Using Java or Groovy

Feel like doing your own woodworking, or other, similar work? Take a look at how you can give commands to your own computer numeric control machine.

· IoT Zone
Free Resource

Address your IoT software testing needs – improve quality, security, safety, and compliance across the development lifecycle.

Let’s discuss some topics ranging from work and occupations to machine tools, Java/Groovy automation, and estimating the future of humanity.

You will find in this article information about personal, computer-aided manufacturing in the in-home workshop, moving from the creator’s idea to the finished item. Let’s consider the following approach for G-code instruction from the JVM and Groovy/Java to the NC machine tool to automate features that do not exist in an out-of-the-box system.

Image title

I hope this article will be useful for the programmers who work with JVM, for those interested in IoT, for those who are familiar with DIY work, for those who have a 3D printer or who are planning to buy one, and for those who made prototypes of any system and run the software at the Raspberry Pi/Beagleboard Black level. And what we cover, you could retry using open source software and open hardware.

This post was written based on my conference report from the Central and Eastern European Software Engineering Conference in Russia 2016 and my personal experience with hardware and software.

Introduction

Good morning, ladies and gentlemen. Let me start by saying thanks to all of you for waking up this early in the weekend day and coming to the conference here. I'm happy to see you in the meeting room! We don't have much time for the report, so there won't be a question-answer section. But feel free to come and ask questions after the report.

Your opinion on the report is very important to me. I would like to hold a meetup where we can use, in practice, the theory that I will describe today — operating a computer numeric control (CNC) machine. That will be open/free, and everyone in Moscow at that time will be able to join up. I hope I will find a place to meet up soon and will publish the information at the Meetup.com. Those who are interested in it could write an email to me and I will send you the event notification. I will surely publish results of this Meetup for the Habrahabr readers, and you could be involved in it, too.

Here is a report: "How to prevent the NC machine tool in your home workshop from becoming the cartoon characters 'two twins from the box.'" Who has watched the cartoon and remembers the plot?

Meeting room voice: «Everyone has (watched it) »

Great, so you are more or less familiar with the problem I will talk about. At the end of the report, we'll try to control the machine using Java and Groovy.

One more question for you. Who is using NC machine tools, or works as an engineer, a designer, or technologist at a manufacturer? Fortunately, I don't hear a response. It makes the things easier for me and you will not troll me on this point. Those who use these technologies every day in production could find the price of the tools, the depth of subject immersion, and my style of explanation hilarious.

NC Machine Tools

What do we know about work? The occupation of the man and his work always were settled/organized in two ways:

Image title


Either you control workers, or you get to work yourself and sweat it out together. Now new, more easy-to-use tools were developed, which brings a third possibility.

Image title

They created technologies that make the work easier, life more pleasant, and give people the opportunity to be occupied with more intellectual things while letting the machines do the hard work.

There is an old cartoon, «Vovka in the Far Away Kingdom». There was a boy in this story who wanted his wishes to come true, but he didn’t want to make something himself and he didn’t want to learn anything.

Image title

In the Far Away Kingdom, he has found two helpers, twins from the box. They were diligent and made literally everything for him, but not the way he wanted.

Here is another cartoon "Wings, Feet, and Tails."

Image title


A pheasant called an Ostrich to the place filled with tasty things. When the Ostrich started to run, the pheasant stopped him with the phrase “It's better to lose a day, then to fly in five minutes.” When you have to do routine tasks, you should think whether it is more effective to lose a day for its automation.

Now we’ll talk about technologies of 1970s. These are machine tools controlled by stored programs. Previously, there were punch cards; currently, flash drives are being used. The automatic machines could be of different sizes and kinematic diagrams and equipped with different tools, all of which carry out material processing at the plant.

Image title


Things are simpler in the in-home workshop. Basically, those machine tools are either AliExpress products or products of Russian import merchants, which rebrand the Celestial Empire's products. You can get whatever you want in the assembled condition, or you can assemble the machine yourself from the parts.

Image title

If you're not worried about time and money, you have no experience, or any other similar reason, it will be easier for you to buy the ready-to-work machine. Also, there are several projects: Shapeoko, MechMate CNC Router, Zenbot CNC etc.

From the software point of view, there is not much difference between NC machine tool and the 3D printer or plotter. The operating tool differs, but a lot of 3D printers are controlled the same way as big industrial machines with the same instruction language.

There was a moment in the cartoon when the ostrich was running around, but he could not fly up. The pheasant keeps telling that wings are the best, but the ostrich insists that legs are. In the end, a lizard appears and says that most important thing is the tail. Its tail saved her life in the beginning of the cartoon.

Image title

While working with NC machine tool, please be mindful of the danger for your life and safety and observe the safety procedures! An NC machine tool includes acutting tool, solid shifting, and rotating elements.

Image title

The contact with the frame of the electric drive is dangerous, especially if the insulation is damaged. If there's a fire in that area, cut the power before extinguishing anything.

From the Model to G-code

Almost every NC machine tool is operated with G-code. This is a text command and data format that is a worldwide standard now. But some of its implementations for machines of different manufacturers have extensions that could make it impossible to port control software to the other machine.

Image title

This example is really easy, but as a matter of fact, G-code is rarely handwritten. Usually, any kind of model is made with the control software created at its base.

The path could be made in the drawing program, Inkskape for example, and GCodeTools turns it into a G-code program for a machine tool. This approach is good for designers.

Image title

Those who used to work with Blender can convert the 3D object to the 2.5D object using the open source BlenderCAM.

Image title

Industrial CAD systems, with their prices over a gazillion dollars, are not accessible for a hobbyist. But the open source software FreeCAD can be used.

Image title

It cannot be compared in ease and functionality with expensive CAD/CAM software suites, but it is sufficient for simple tasks. HeeksCAD fork is established much better in its CAM part and allows creating the control software on the base of the model/drawing.

Image title

Numerical Control

What exactly controls the motion axis of the machine tool, mill, or other tools?

Image title

The Dedicated DSP controller of the NC machine tool comes with a USB port for a flash drive and a machine. These are either accessory boards for the single-board computer (Raspberry Pi, BeagleBoard, etc.) to control electric drive and spindle, or an ordinary PC with an LPT port or PCI/PCIe accessory board to interface with the machine electronics.

The hero of the day is a PC. You can control the machine and interpret the G-code using the open source software LinuxCNC.

Image title

The software is based on the Linux kernel real-time. Its fork, Machinekit, (for an ARM ready-to-use ISO image) is used for the Raspberry Pi, BeagleBoard Black single-board computers. There is a Machinekit build for the single-board C.H.I.P. at the price of $9.

LinuxCNC is a constructor, and you can build almost any configuration on its base. This software controls both hobby-use machines and huge industrial NC machine tools. It is used not only for upgrading industrial NC machine tools, but also for the newly developed machine tool.

Image title

Part of its components work in a real-time process, while less critical parts work in the environment with unscheduled delays. It is possible to extend the internal logic of the response to events in the LinuxCNC using LD diagrams, and even shell scripts or command line programs.

Control the Machine Using Java and Groovy

Instead of its GUI component, we’ll try to control the NC machine tool through the external API using software technologies more usable to us. Those who are interested in this idea could find my PoC Apache Camel component and JVM library on GitHub.

There is a set of solutions for IoT based on Java — frequently, they are servers for IoT gateways. Now it is possible to integrate LinuxCNC control of the machine into the complex cloud-based automation scripts with Internet access. It is no trouble to build the working solution using thousands of ready-made components in this constructor with Eclipse Kura or Apache Camel. You can integrate computer vision libraries and add matching components or camera/network image capture tools. 

Let’s start with a little Java example. We’ll use the API to send commands to control the machine. The library sends telnet commands to the linuxcncrsh process from the LinuxCNC/Machinekit.

//maven dependency com.github.igor-suhorukov:camel-gcode:0.1
import com.github.igorsuhorukov.gcode.GCodeClient;
public class Gcode {
    public static void main(String[] args) throws Exception {
        String hostname = "beaglebone.local";
        int port = 5007;
        try (GCodeClient gCodeClient = new GCodeClient(hostname, port)) {
            System.out.println(gCodeClient.login("EMC", "JVM", "1.0"));
            gCodeClient.sendCommand("set mode manual");
            gCodeClient.sendCommand("set estop off");
            gCodeClient.sendCommand("set machine on");
            for (int axis = 0; axis < 4; axis++)
                gCodeClient.sendCommand("set home " + axis);
            System.out.println(gCodeClient.sendCommand("get abs_act_pos"));
            gCodeClient.sendCommand("set mode mdi");
            gCodeClient.sendCommand("set mdi g0 x3 y4");
            gCodeClient.sendCommand("set mdi g0 x5 y2");
        }
    }
}


This example moves the gantry/portal at the idle full speed first to the (3; 4) position, then to the (5; 2) position.

The next example is a Groovy program based on the Apache Camel framework and com.github.igor-suhorukov:camel-gcode component for sending commands.

@Grab('com.github.igor-suhorukov:camel-gcode:0.1')
@Grab('org.apache.camel:camel-groovy:2.18.0')
@Grab('org.apache.camel:camel-core:2.18.0')
@Grab('org.apache.camel:camel-jetty:2.18.0')
@Grab('org.slf4j:slf4j-simple:1.6.6')
import org.apache.camel.builder.RouteBuilder
import org.apache.camel.impl.DefaultCamelContext
import com.github.igorsuhorukov.smreed.dropship.MavenClassLoader

def camelContext = new DefaultCamelContext()
camelContext.setName("I'll be back")
camelContext.addRoutes(new RouteBuilder() {
    def void configure() {
        from('jetty:http://0.0.0.0:9090/moveTo').routeId('CamelCNC')
                .process{ it.in.body =
                  ("set mdi g0 x${Math.round(Math.random()*10)} y${Math.round(Math.random()*10)} z1") }
                .to('gcode:?host=beaglebone.local&port=5007&autoHomeAxisCount=4')
    }
})
addShutdownHook{ camelContext.stop() }
camelContext.start()

def HawtIo = MavenClassLoader.usingCentralRepo()
        .forMavenCoordinates('io.hawt:hawtio-app:2.0.0').loadClass('io.hawt.app.App')
Thread.currentThread().setContextClassLoader(HawtIo.getClassLoader())
HawtIo.main('--port','10090')

To run it, use: java -jar groovy-grape-aether-2.4.5.4.jar CamelCNC.groovy

Image title

Image title

In this example, the Groovy application links the Jetty and G-Code components, builds a route to the Groovy DSL camel, and loads and runs the web console for HawtIo monitoring. At each HTTP request at HOST:9090/moveTo, the new command to move at the random positions along the X and Y axis is created and sent to the LinuxCNC and machine to be complete. Then, the generated command returns to the client as an HTTP response. The web console listens at the :10090/hawtio address.

The Apache Camel, Groovy, and HawtIo magic will help you to make complex things quite easily.

The Perfect Future...

We can try to predict the future. We can distinguish a trend: all things that could be automated when it makes economic sense to do are being automated. Recently, there has been news about Foxconn in China: 40,000 machines at the manufacturer caused a mass layoff. 

I’m not Nostradamus, but automation might destroy workplaces in times to come. It is also quite clear that demand for automation will increase with time. And people who are familiar with these technologies will be still more sought-after at the labor market, but only up to a point… And individual production at the NC machine tool level will be in every workshop.

What will be the future like?

Will the robots enslave or destroy humanity?

Image title


Or people will still control robots.

Image title


It depends on us and our skills and decisions today!

Conclusion

A lot of things that we make with our hands and routine tasks usually could be automated. In this case, we should start with the design of the model. The next step is to turn the model into the control program for the machine. These commands will be executed by some kind of NC machine, and all elements in the production process that are reasonable to automate should be automated. The computer vision technologies and feedback sensors should be used, too. Surely it is unacceptable to run between a computer and a machine with a flash drive — the commands will be transmitted through the network. Let the machine make all the work. But to prevent the tool from becoming the twins from the box, you have to learn the technology and have a good handle in the process details. Or you’ll have to share financial resources with those who understand these technologies and get a different result from the one you wanted.

Accelerate the delivery of high-quality software in the connected IoT era through an integrated analysis, testing, security, and analytics platform

Topics:
java ,groovy ,cnc prototyping ,apache camel ,iot

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}