在同一线程内的同一JAVA RXTX串行端口上同时读写

问题描述 投票:0回答:1

在同一线程内的同一JAVA RXTX串行端口上同时读写

是否可以从同一Java线程中的同一串行端口实时读写。实际上,我是从Arduino读取数据,因此我需要实时将相同数据发送到Arduino。我在Runnable内部使用了true条件,这就是为什么无法在EventListner内部获取数据的原因。

代码段

 public void initialize() 
{
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        //First, Find an instance of serial port as set in PORT_NAMES.
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId
                    = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
            System.out.println("Could not find COM port.");
            logText="Could not find COM Port. Please Change your device port to COM3.";
            isconnected=false;
            return;
        } else {
            System.out.println("Port Name: " + portId.getName() + "\n"
                    + "Current Owner: " + portId.getCurrentOwner() + "\n"
                    + "Port Type: " + portId.getPortType());
            logText = portId.getName()+ " Successfully Connected!";
            isconnected=true;
            isRunning=true;
            //Controller.labelStatus.setText(" Successfully Connected!");
        }

        try {
            // open serial port, and use class name for the appName.
            serialPort = (SerialPort) portId.open(this.getClass().getName(),
                    TIMEOUT);

            // set port parameters
            serialPort.setSerialPortParams(DATA_RATE,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            // open the streams
            inputstream = serialPort.getInputStream();
            output = serialPort.getOutputStream();
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
             thread = new Thread(){
                public void run(){
                    while(isRunning) {
                        System.out.println("Thread Running "+bytesToHexString(BtnHexData.getInstance().getSendingPack()));

                        try {
                            output.write(BtnHexData.getInstance().getSendingPack());

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        try {
                            Thread.sleep(200);
                            //System.out.println("\t\t Thread Receiving "+bytesToHexString(input.readAllBytes()));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };

            thread.start();

        } catch (Exception e) {
            serialPort.close();
            System.err.println(e.toString());
            logText="Error: "+e.toString();
        }
    }
java multithreading rxtx real-time-data
1个回答
1
投票
我遇到了同样的问题,但最终我得到了解决方案!

还有另一个JAVA通讯库“ com.fazecast.jSerialComm”,它是同时在串行端口上进行实时读写操作的最终解决方案。如果有人需要有关此问题的帮助,我将发布我的调查结果...

使用jSerialComm的SerialPort类

import com.fazecast.jSerialComm.SerialPort; import com.fazecast.jSerialComm.SerialPortDataListener; import com.fazecast.jSerialComm.SerialPortEvent; public class MySerialPort { public static SerialPort arduinoPort = null; public static InputStream arduinoStream = null; static String logText=""; private static boolean isRunning=false; private byte[] sendingPack; private byte[] receivingPack; public static boolean isRunning() { return isRunning; } public static void setRunning(boolean running) { sendingPack = new byte[6]; receivingPack= new byte[36]; isRunning = running; } public static void connectPort(String port) { devicePortName = port; int len = SerialPort.getCommPorts().length; SerialPort serialPorts[] = new SerialPort[len]; serialPorts = SerialPort.getCommPorts(); for (int i = 0; i < len; i++) { String portName = serialPorts[i].getDescriptivePortName(); System.out.println(serialPorts[i].getSystemPortName() + ": " + portName + ": " + i); if (portName.contains(devicePortName)) { try { arduinoPort = serialPorts[i]; arduinoPort.setBaudRate(115200); arduinoPort.openPort(); setRunning(true); System.out.println("connected to: " + portName + "[" + i + "]"); logText="Connected to: " + portName ; break; } catch (Exception e) { e.printStackTrace(); loogger.stop(); arduinoPort.closePort(); } } } (new Thread(new SerialReader(receivingPack))).start(); (new Thread(new SerialWriter(sendingPack))).start(); } public static class SerialReader implements Runnable { byte[] buffer; public SerialReader ( byte[] buffer ) { this.buffer = buffer; System.out.println("Reader"); } public void run () { readData(buffer,isRunning()); } } public static class SerialWriter implements Runnable { byte[] buffer; public SerialWriter ( byte[] buffer ) { this.buffer = buffer; } public void run () { sendData(buffer); } } public static void sendData(byte[] buffer){ while (isRunning){ arduinoPort.writeBytes(sendingPack,6,0); System.out.println("Sending"+bytesToHexString(sendingPack)); try { Thread.sleep(200); } catch (Exception e) { e.printStackTrace(); } } } public static void readData(byte[] buffer,boolean loopStatus){ while (isRunning()){ arduinoPort.readBytes(receivingPack,36,0); if(receivingPack()[0] & 0xff)==144 ){ String bufferD=bytesToHexString(receivingPack); System.out.println(bufferD); } try { Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); } } public static String bytesToHexString(byte[] bytes){ StringBuilder sb = new StringBuilder(); for (byte b : bytes){ sb.append(String.format("%02x", b&0xff)); } return sb.toString(); } }
主类

public static void main(String[] args) { MySerialPort.setRunning(true); MySerialPort.connectPort("COM3"); }

© www.soinside.com 2019 - 2024. All rights reserved.