How does java communicate with RS232

Posted by Zan on Sat, 18 Dec 2021 12:40:30 +0100

Download virtual serial port software:

Link: https://pan.baidu.com/s/1AXKXdyl9rbm3SSt0y7Q6PQ  
Extraction code: 3aqp

The cracking process of the two versions is roughly the same. Both versions are installed first. Version 6.9 copies the two files in the compressed package crack file to the installation directory to replace the original one exe and dll file; Version 7.1 only needs to compress the data in the package Just copy the dll file to the installation directory and replace it.

Open the software to add virtual serial ports, which are generally added in pairs (add COM7 and COM8), as shown in the figure (add serial ports according to your own needs)

After adding, check in the device manager and find two more virtual serial ports, as shown in the figure:

I don't know why the port I added is not under the port (COM and LPT), because I look at the screenshot of others. The added virtual port is under the port (COM and LPT), but it doesn't affect our experiment.

Download serial port debugging software:

Link: https://pan.baidu.com/s/14e-mflzDx6mBxIt9pejN3Q  
Extraction code: n7bi

You can directly open two debugging windows to represent COM7 and COM8 serial ports respectively. The parameters of the two serial ports must be set the same in order to send and receive data normally. As shown in the figure:

Note that select the corresponding serial port in the serial port debugging tool and open the serial port. How to open the serial port is prompted in the picture on the far right. For example, COM7[9600-N-8-1] indicates that COM7 port is open, and there is nothing in COM17 [] indicates that COM17 port is not open

COM7 sends data to COM8 port, and COM8 sends data to COM7

Description the port is normal

Java code writing and debugging

This part will be our focus. To communicate with the serial port, we must first add rxtxcomm Jar package (put it in the Lib directory of the project and add it to the build Path) (win64 bit download address: https://pan.baidu.com/s/1f6aNfcVNSEmAovTcGlfjNw (extraction code: iec1)); in addition, you also need to put the unzipped rxtxparallel.dll and rxtxserial.dll files in the% JAVA_HOME%/jre/bin directory, so that the package can be loaded and called normally. [the unzipped package contains the installation.txt document, which contains the path description to be put in (Copy RXTXcomm.jar ---> <JAVA_HOME>\jre\lib\ext  ;Copy rxtxSerial.dll ---><JAVA_HOME>\jre\bin;Copy rxtxParallel.dll ---> <JAVA_HOME>\jre\bin)]
 

Note: install to% JAVA_HOME%/jre/bin -- what needs to be installed is the jdk file under tomacat. Remember that it must be under the jdk called by tomcat, including the development environment (because sometimes the jdk developed during development configuration is not the same as the jdk run by tomcat, which means that Tomcat runs the jdk in servers under window preferences of eclipse)

If it is not the jdk under tomacat, an error will be reported: Java lang.UnsatisfiedLinkError: no rxtxSerial in java. library. path thrown while loading gnu. io. RXTXCommDriver

The solution is to import the above files into the correct path.

Relevant codes:

package com.springsecurity.demo.testRxtx;

import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.*;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import gnu.io.*;

/**
 * @version 1.0
 * @author:  hjb
 * @date:  2021-08-31 13:54
 */
public class RxtxUtil extends Thread implements SerialPortEventListener {

    // Listener, my understanding is to independently open up a thread to monitor serial port data
    static CommPortIdentifier portId; // Serial communication management class
    static Enumeration<?> portList; // Enumeration of ports on valid connections
    InputStream inputStream; // Input stream from serial port
    static OutputStream outputStream;// Stream output to serial port
    SerialPort serialPort; // Serial port reference
    // The blocking queue is used to store the read data
    private BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>();
    /**
     * SerialPort EventListene Method to continuously monitor whether there is data flow on the port
     */
    @Override
    public void serialEvent(SerialPortEvent event) {
        switch (event.getEventType()) {
            case SerialPortEvent.BI:
            case SerialPortEvent.OE:
            case SerialPortEvent.FE:
            case SerialPortEvent.PE:
            case SerialPortEvent.CD:
            case SerialPortEvent.CTS:
            case SerialPortEvent.DSR:
            case SerialPortEvent.RI:
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                break;
            case SerialPortEvent.DATA_AVAILABLE:// Read data when available
                byte[] readBuffer = new byte[1024];
                try {
                    int numBytes = -1;
                    while (inputStream.available() > 0) {
                        numBytes = inputStream.read(readBuffer);

                        if (numBytes > 0) {
                            msgQueue.add(new Date() + "The data actually received are:-----"
                                    + new String(readBuffer,"gbk"));
                            readBuffer = new byte[1024];// Reconstruct the buffer object, otherwise it may affect the data received next
                        } else {
                            msgQueue.add("forehead------No data was read");
                        }
                    }
                } catch (IOException e) {
                }
                break;
        }
    } // SerialPortEventListener {


    /**
     *
     * Open the COM4 serial port through the program and set the listener and related parameters
     *
     * @return A return of 1 indicates that the port was opened successfully, and a return of 0 indicates that the port failed to open
     */
    public int startComPort(String portName) {
        // Obtain the list of serial ports on the current connection through the serial port communication management class
        portList = CommPortIdentifier.getPortIdentifiers();

        while (portList.hasMoreElements()) {
            // Get the corresponding serial port object
            portId = (CommPortIdentifier) portList.nextElement();

            System.out.println("Equipment type:--->" + portId.getPortType());
            System.out.println("Equipment name:---->" + portId.getName());
            // Determine whether the port type is serial port
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                // Judge that if the COM7 serial port exists, open the serial port
                if (portId.getName().equals(portName)) {
                    try {
                        // Open the serial port with the name com_ 7 (arbitrary name), with a delay of 2 milliseconds
                        serialPort = (SerialPort) portId.open(portName, 2000);

                    } catch (PortInUseException e) {
                        e.printStackTrace();
                        return 0;
                    }
                    // Sets the input / output stream of the current serial port
                    try {
                        inputStream = serialPort.getInputStream();
                        outputStream = serialPort.getOutputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return 0;
                    }
                    // Add a listener to the current serial port
                    try {
                        serialPort.addEventListener(this);
                    } catch (TooManyListenersException e) {
                        e.printStackTrace();
                        return 0;
                    }
                    // Set the listener to take effect, that is, notify when there is data
                    serialPort.notifyOnDataAvailable(true);

                    // Set some read-write parameters of the serial port
                    try {
                        // Bit rate, data bit, stop bit, parity bit
                        serialPort.setSerialPortParams(9600,
                                SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                                SerialPort.PARITY_NONE);
                    } catch (UnsupportedCommOperationException e) {
                        e.printStackTrace();
                        return 0;
                    }

                    return 1;
                }
            }
        }
        return 0;
    }

    //Processing returned messages
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            System.out.println("--------------The task processing thread is running--------------");
            while (true) {
                // If there is data in the blocked queue, it will be output
                if (msgQueue.size() > 0) {
                    System.out.println(msgQueue.take());
                }
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
package com.springsecurity.demo.testRxtx;

import java.io.IOException;

/**
 * @version 1.0
 * @author:  hjb
 * @date:  2021-08-31 13:53
 */
public class TestRxtxUtil {
    public static void main(String[] args) {
        RxtxUtil cRead = new RxtxUtil();
        int i = cRead.startComPort("COM8");
        if (i == 1) {
            // Start the thread to process the received data
            cRead.start();
            try {
                String st = "ha-ha----Hello";
                System.out.println("Bytes sent:" + st.getBytes("gbk").length);
                cRead.outputStream.write(st.getBytes("gbk"), 0,
                        st.getBytes("gbk").length);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            System.out.println("Port opening failed!");
            return;
        }
    }
}


matters needing attention:

When debugging the port, we use two port debugging tools to connect the port, as shown in the figure

In this state, when testing with Java code, an error will be reported that the port is occupied

gnu.io.PortInUseException: Unknown Application

For example, when I use it in my code, COM8 sends messages to COM7 port, so I need to turn off the debugging tool of COM8

Click to close the serial port, and the running code can run normally

 

Send return message:

 

If you want to receive more message contents at a time, you can write the value of new byte[1024] to a larger value

Topics: Java Web Development