Giao tiếp SerialPort(COM)-PC sử dụng thư viện rxtx trong Java

Ngôn ngữ Java mặc định không hỗ trợ các giao tiếp cụ thể như SerialPort, USB… vì lý do đa nền tảng. Ví dụ PC hầu hết có cổng COM, USB nhưng các thiết bị di động như điện thoại chưa chắc có những cổng này. Tuy nhiên có rất nhiều thư viện mã mở giúp cho công việc giao tiếp trong java được thuận tiện hơn. Ví dụ trong đó là package javax.comm, rxtx. Javax.comm đã thử trên win7 nhưng không hoạt động Winking smile, chuyển sang rxtx thấy cũng hay và đáp ứng được những yêu cầu đặt ra.

Rxtx có thể được download tại http://rxtx.qbang.org/wiki/index.php/Download . Sau khi dowload về máy tính, ta lần lượt coppy các file của thư viện vào thư mục hệ thống của jdk:

  • rxtxSerial.dll tới thư mục <jdk_install>jrebin
  • RXTXcomm.jar tới thư mục <jdk_install>jrelibext

đồng thời không quên add RXTXcomm.jar tới project và thêm import gnu.io.*;.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wheelsspeedgui;

/**
 *
 * @author ThanhBinh
 */
import java.util.*;
import gnu.io.*;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

///
public class SerialCommunication extends Observable {
    private SerialPort serialPort;
    private OutputStream outStream;
    private InputStream inStream;
    private IDataSerial main;
    
    public SerialCommunication(IDataSerial mainFrm){
        main = mainFrm;
    }
    public String[] listSerialPorts() {
        Enumeration ports = CommPortIdentifier.getPortIdentifiers();
        ArrayList portList = new ArrayList();
        String portArray[] = null;
        while (ports.hasMoreElements()) {
            CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
            if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                portList.add(port.getName());
            }
        }
        portArray = (String[]) portList.toArray(new String[0]);
        return portArray;
    }
    public boolean Connect(String portName) throws IOException, TooManyListenersException {
        try {
            // Obtain a CommPortIdentifier object for the port you want to open
            CommPortIdentifier portId =
                    CommPortIdentifier.getPortIdentifier(portName);

            // Get the port's ownership
            serialPort = (SerialPort) portId.open("Demo application", 5000);

            // Set the parameters of the connection.
            setSerialPortParameters();

            // Open the input and output streams for the connection.
            // If they won't open, close the port before throwing an
            // exception.
            outStream = serialPort.getOutputStream();
            inStream = serialPort.getInputStream();
            addDataAvailableListener(new SerialPortEventListener(){
                public void serialEvent(SerialPortEvent spe) {
                    switch (spe.getEventType()) {
                    case SerialPortEvent.DATA_AVAILABLE:
                   // readSerial();
                       // System.out.println("new datan");
                        HasData_Event();
                    }
                    throw new UnsupportedOperationException("Not supported yet.");
                }
                });
            return true;
        } catch (NoSuchPortException e) {
            return false;
           // throw new IOException(e.getMessage());            
        } catch (PortInUseException e) {
            //throw new IOException(e.getMessage());
            return false;
        } catch (IOException e) {
            serialPort.close();
            return false;
            //throw e;
        }
    }
    protected void setSerialPortParameters() throws IOException {

        final int baudRate = 9600; // 9600bps
        try {
            // Set serial port to 57600bps-8N1..my favourite
            serialPort.setSerialPortParams(
                    baudRate,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
        } catch (UnsupportedCommOperationException ex) {
            throw new IOException("Unsupported serial port parameter");
        }
    }
    public void Disconnect() {
        if (serialPort != null) {
            try {
                // close the i/o streams.
                outStream.close();
                inStream.close();
            } catch (IOException ex) {
                // don't care
            }
            // Close the port.
            serialPort.removeEventListener();
            serialPort.close();
            serialPort = null;
        }
    }
    
    public boolean WriteBytes(byte[] data){
        boolean success = false;
        try {
            outStream.write(data);
            success = true;
        } catch (IOException ex) {
            
        }
        return success;
    }

    private void addDataAvailableListener(SerialPortEventListener dataAvailableListener)
            throws TooManyListenersException {
        // Add the serial port event listener
        serialPort.addEventListener(dataAvailableListener);
        serialPort.notifyOnDataAvailable(true);
    }
    private byte[] GetBytes(){
        byte[] empty={};
        try {
            int availableBytes = inStream.available();
            if (availableBytes > 0) {
                    // Read the serial port
              byte[] readBuffer = new byte[availableBytes];
              inStream.read(readBuffer, 0, availableBytes);
              return readBuffer;
            }
         } catch (IOException e) {
             return empty;
         }
        return empty;
    }
    public void HasData_Event(){
           byte[] data = GetBytes();
           main.HasData_Event(data);
    }

}