Working with a COM port from Java using jSSC

A lot of water has flowed since we used mice on coms, modems, played “games” on it for lack of a network, threw files and ... which we didn’t do.

Everything, in the yard of the 21st century, USB 3.0 crushed everything and everything by itself, coms died out and now “newborn” programmers look at this connector with bewilderment and reproach. But, not all died, some still remained ... These brave guys send bytes on three wires and look at the “newborns” with a condescending smile. And about what these guys use when doing their job, I want to tell in this short article. It will be about a small library named jSSC.

Judging by how people on Habré speak about com, apparently many people really think that he is no longer needed and do not understand why someone still uses it, why they write libraries and software, and produce equipment with this port on board. From myself, I can only say one thing, so as not to breed a holivar, as it seems to me, it disappeared only for domestic use, and it is present at production facilities and in various laboratories and feels just fine. There are many reasons for this, but the main one, it seems to me, is simplicity and ease of use.

But the conversation is not about now, so we will not be distracted. So, jSSC is a Java library for easy operation with a COM port (Java Simple Serial Connector). She takes her official, public start in 2010. It was then that it was decided to share it with Java developers (distributed under the LGPL license). A sad fact led to the writing of the library - the lack of adequate tools for working with this port. Many will say, and have already said, they say there is javax.comm, rxtx and there is still giovynet (but it can not be seriously considered under any circumstances), but unfortunately it is not so simple. Our main OS is Windows, and using javax.comm 3.0 will not work, but rxtx did not work because of its instability. As a result, there was nothing to do, I had to write my own library.

Ease of use was put at the forefront during the development, because every day you have to work with equipment, and you want the work to be fun. But do not be fooled by this, simplicity is not a silver bullet or a “make pi * date” button, you need to understand what you want to get from the device, how it works and how the devices interact via com. During development, a greater bias was made towards the Windows development style for the com-port, mainly in the name of constants for setting the event mask, flow control mode, parsing errors, etc.

jSSC can be divided into several main parts:
  • SerialNativeInterface - a class that provides access to all "native" jSSC methods.
  • SerialPort - a class with which we will directly work with the port we need.
  • SerialPortEventListener is an interface that must be implemented if we want to use events.

Now you can sketch a small example. Suppose we have some kind of device that uses hardware flow control, and we want to receive answers from requests from it. Here is an example implementation:

import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
public class Test {
    private static SerialPort serialPort;
    public static void main(String[] args) {
        //Передаём в конструктор имя порта
        serialPort = new SerialPort("COM1");
        try {
            //Открываем порт
            serialPort.openPort();
            //Выставляем параметры
            serialPort.setParams(SerialPort.BAUDRATE_9600,
                                 SerialPort.DATABITS_8,
                                 SerialPort.STOPBITS_1,
                                 SerialPort.PARITY_NONE);
            //Включаем аппаратное управление потоком
            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | 
                                          SerialPort.FLOWCONTROL_RTSCTS_OUT);
            //Устанавливаем ивент лисенер и маску
            serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);
            //Отправляем запрос устройству
            serialPort.writeString("Get data");
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
        }
    }
    private static class PortReader implements SerialPortEventListener {
        public void serialEvent(SerialPortEvent event) {
            if(event.isRXCHAR() && event.getEventValue() > 0){
                try {
                    //Получаем ответ от устройства, обрабатываем данные и т.д.
                    String data = serialPort.readString(event.getEventValue());
                    //И снова отправляем запрос
                    serialPort.writeString("Get data");
                }
                catch (SerialPortException ex) {
                    System.out.println(ex);
                }
            }
        }
    }
}


In my opinion, everything is quite simple. In addition to read / write operations, jSSC provides the following features:
  • RTS, DTR line management
  • Obtaining the status of CTS, DSR, RING, RLSD lines
  • Getting the number of bytes in buffers
  • Flushing Port Buffers
  • Sending Break Signal
  • Flow control
  • Getting a list of com ports in the system

One important point should be noted here: USB-> COM adapters may sometimes behave differently from what you expect, this is understandable depending on their driver, so if you are going to use such adapters, test them thoroughly on Linux and Windows, if Of course you need support for different OS.

A year after the publication of jSSC, there were many letters from developers and firms, and the scope was quite extensive. Here is a short list:
  • Irda management for HTPC (project of one company from the USA)
  • Tuning Mitsubishi Eclipse (hi there too - in the USA)
  • Server software in the center of network technologies (Poland)
  • A parcel weighing system (as far as I understand) for some kind of delivery service (for these guys I wrote a bridge from Java to JavaScript and they rewarded my work by sending 100 USD, by the way, also the USA)
  • Various educational projects (India, Russia and maybe someone else)
  • etc.

Well, a special hello to the guys from India, for whom I made the version of jSSC-CE (Windows CE). If memory serves me right, they ordered some equipment on WinCE without checking if there was a JVM from SUN / Oracle for it, and were very surprised when they found out that it was not there. I used CreMe JVM for development then, well, I hope that everything worked out for them.

Well, let me take my leave, I apologize for the somewhat messy narration, and I hope that one of you jSSC will help in the work. I will be glad to answer your questions.

And here is the link to the project page: http://code.google.com/p/java-simple-serial-connector

Also popular now: