javajssc从多个com端口读取数据,同时在一个端口上写出所有数据

aij0ehis  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(504)

我有几个com端口每1-2秒带来一次数据。每台设备的每一行,以$开头,以cr和lf结尾。每一行都有不同的长度,长度不超过82字节。
我试图结合四个4800波特输入和一个34800波特输入到一个输出线在192k波特。
你可以在这里看到我的代码:https://github.com/ian5142/nema0183_aggregator
https://github.com/ian5142/nema0183_aggregator/find/master
nema\ U聚合器是主要的
rs232control包含所有jssc内容。
当发送gps数据时,rs232control调用nemadateupdate。更改其中一行中的日期。很好用。
主设备的相关代码:

RS232Control gps = new RS232Control("COM32", 4800, true);
        while (true) {
            String line = gps.testRead2();
            sentences.add(line);
            gps.changePort("COM41", 115200, false);
            gps.testWrite(line);

            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                Logger.getLogger(Nema0183_aggregator.class.getName()).log(Level.SEVERE, null, ex);
            }
            for (int i = 0 ; (i < 8) && (!line.startsWith("$GPGLL")) ; i++ ) {
                gps.changePort("COM32", 4800, true);
                line = gps.testRead2();
                sentences.add(line);
                gps.changePort("COM41", 115200, false);
                gps.testWrite(line);

                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Nema0183_aggregator.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            gps.changePort("COM39", 4800, false);
            line = gps.testRead2();
            sentences.add(line);
            gps.changePort("COM41", 115200, false);
            gps.testWrite(line);

            gps.changePort("COM32", 4800, true);
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                Logger.getLogger(Nema0183_aggregator.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

rs232control在这里:

import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import jssc.*; // Java Simple Serial Connector, the library that contains the serial methods
import static nema0183_aggregator.RS232Control.serialPort;

/**
 *
 * @author Ian Van Schaick
 */
public class RS232Control {

    static SerialPort serialPort;
    String portName;
    static long portOpen;
    StringBuilder message;
    Boolean receivingMessage;
    SerialPortReader reader;
    String readLine;
    Boolean acknowledge;
    int baud;
    boolean gpsData;
    NEMADateUpdate gpsUpdate;
    String lineSep;

    /**
     * 
     * @param portNum
     * @param portbaud
     * @param gps 
     */
    public RS232Control(String portNum, int portbaud, boolean gps) {
        gpsData = gps;
        if (gpsData == true) {
            gpsUpdate = new NEMADateUpdate ();
        }
        portName = portNum;
        baud = portbaud;
        serialPort = new SerialPort(portName);
        message = new StringBuilder();
        receivingMessage = false;
        reader = new SerialPortReader();
        readLine = "";
        acknowledge = false;
        lineSep = System.getProperty("line.separator");
        openP();
    }

 protected void changePort (String portNum, int portbaud, boolean gps) {
        close();
        gpsData = gps;
        if (gpsData == true) {
            gpsUpdate = new NEMADateUpdate ();
        }
        portName = portNum;
        baud = portbaud;
        serialPort = new SerialPort(portName);
        message = new StringBuilder();
        receivingMessage = false;
        reader = new SerialPortReader();
        readLine = "";
        acknowledge = false;
        lineSep = System.getProperty("line.separator");
        openP();
    }

    /**
     * Opens a COM port at the specified settings (baudrate 8N1)
     * Can throw an error opening the port
     */
    private void openP() {
        try {
            serialPort.openPort();
            serialPort.setParams(baud,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
            int mask = SerialPort.MASK_RXCHAR;
            serialPort.setEventsMask(mask);
            serialPort.addEventListener(reader);
            serialPort.setRTS(false);
            serialPort.setDTR(false);
            acknowledge = true;
        } catch (SerialPortException ex) {
            Logger.getLogger(RS232Control.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("There is an error opening port т: " + ex);
        }
    }

    /**
     * Closes the serial port, can throw a SerialPortException error.
     *
     * @return
     */
    private boolean close() {
        boolean success = false;
        try {
            serialPort.closePort();
            success = true;
        } catch (SerialPortException ex) {
            Logger.getLogger(RS232Control.class.getName()).log(Level.SEVERE, null, ex);
        }
        return success;
    }
/**
     * Opens the serial port. Tries to read a string from the serial port.
     * Closes the serial port.
     *
     * @return Returns the byte array read from the serial port.
     */
    protected String testRead2() {
        String line = "";
        ArrayList <String> readList = new ArrayList <String> ();
        boolean lineFin = false;
        for (int i = 0; i < 100 && (!lineFin); i++) {
            try {
                line =  line + serialPort.readString(1);
            } catch (SerialPortException ex) {
                Logger.getLogger(RS232Control.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (line.endsWith(lineSep)) {
                lineFin = true;
            }
        if (gpsData == true) {
            line = gpsUpdate.dateUpdate(line);
        }
    }
        return line;
    }

    /**
     * Writes the String message to the serial port
     *
     * @param message The string to write to the serial port
     * @return Returns true if the write was successful
     */
    protected boolean testWrite(String message) {
        boolean success = false;

        try {
            if ( (!message.isBlank() ) && message.startsWith("$") ) {
                success = serialPort.writeString(message);
            }
        } catch (SerialPortException ex) {
            Logger.getLogger(RS232Control.class.getName()).log(Level.SEVERE, null, ex);
        }
        return success;
    }
}

/**
 * In this class must implement the method serialEvent, through it we learn
 * about events that happened to our port. But we will not report on all events
 * but only those that we put in the mask. In this case the arrival of the data
 * and change the status lines CTS and DSR
 */
class SerialPortReader implements SerialPortEventListener {

    /**
     * Reads the data bit by bit from the serial port Can throw a
     * SerialPortException error
     *
     * @param event
     */
    @Override
    public void serialEvent(SerialPortEvent event) {
        if (event.isRXCHAR() && event.getEventValue() == 10) {
            try {
                byte buffer[] = serialPort.readBytes(10);
            } catch (SerialPortException ex) {
                System.out.println("Error in receiving string from COM-port: " + ex);
            }
        }
    }

    /**
     * Prints out the message read from the serial port
     *
     * @param message
     */
    protected void processMessage(String message) {
//        System.out.println(message);
    }
}

我试图使用for/while循环来迭代com端口,但这意味着我错过了从其他端口传入的数据。
有什么办法吗?

cs7cruho

cs7cruho1#

听起来像是条形码扫描。但这并不重要。
保留单独的示例 RS232Control 对于每个端口。重复轮询它们,并将任何数据放入队列。
在另一个线程take from queue中,合并并向前发送。
有时多线程解决方案更容易。这是值得的。

ulmd4ohb

ulmd4ohb2#

我建议使用一个全局列表变量来标识每个com端口,可能使用一个类来创建两个成员:一个布尔值表示从com端口读取数据的时间,另一个布尔值表示当您在while循环中遍历com端口时,该com端口的数据已经被您检查过的时间。如果它们都在不同的线程上,那么它们都可以同时接收数据,while循环将继续迭代所有的com端口,直到它们的alreadychecked(数据已经接收并发送到主端口)布尔值变为true。这可以通过在while循环中执行for循环来完成,以计算还有多少类示例已经将boolean检查为false,我希望这会有所帮助。

相关问题