Java中的串口读写

zujrkrfu  于 2022-12-25  发布在  Java
关注(0)|答案(3)|浏览(94)

我有一个应用程序,需要向串行端口写入一些数据并从其获得响应。现在的序列如下:
1.向串行端口发送消息。
1.等待响应
1.一旦收到响应,我必须处理消息,在此之前,应用程序不应发生任何事情。
我应该如何解决这个问题?我不擅长串行编程。我尝试了一个代码,但我的应用程序在我执行发送消息时停止。可能是因为我在发送消息后阅读消息。我真的不知道如何解决这个问题。我必须在应用程序启动时开始侦听端口吗?我必须保持端口打开吗?如果我每次需要的时候都打开端口可以吗?我该如何让程序等待响应直到从端口读取到响应消息?请帮助我解决这个问题。
--编辑--

package testConn;  
import forms_helper.global_variables;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.util.logging.Level;  
import java.util.logging.Logger;  
import javax.comm.*;  
import java.util.*; 

/** Check each port to see if it is open. **/  
public class openPort implements SerialPortEventListener {

    static Enumeration portList;
    static CommPortIdentifier portId;
    static String messageString;
    public static SerialPort serialPort;
    static OutputStream outputStream;
    InputStream inputStream;
    static boolean outputBufferEmptyFlag = false;

    public void open() {
        Enumeration port_list = CommPortIdentifier.getPortIdentifiers();

        while (port_list.hasMoreElements()) {
            // Get the list of ports
            CommPortIdentifier port_id = (CommPortIdentifier) port_list.nextElement();
            if (port_id.getName().equals("/dev/ttyS1")) {

                // Attempt to open it
                try {
                    SerialPort port = (SerialPort) port_id.open("PortListOpen", 20);
                    System.out.println("Opened successfully");
                    try {
                        int baudRate = 9600; //
                        port.setSerialPortParams(
                                baudRate,
                                SerialPort.DATABITS_7,
                                SerialPort.STOPBITS_1,
                                SerialPort.PARITY_EVEN);
                        port.setDTR(true);
                       /*

                        port.setFlowControlMode(
                                SerialPort.FLOWCONTROL_NONE);
                        *
                        */
                        System.out.println("properties are set");
                    } catch (UnsupportedCommOperationException e) {
                        System.out.println(e);
                    }
                    try {
                        //input = new SerialReader(in);
                        port.addEventListener(this);
                        System.out.println("listeners attached" + this);
                    } catch (TooManyListenersException e) {
                        System.out.println("too many listeners");
                    }
                    port.notifyOnDataAvailable(true);
                    //port.notifyOnOutputEmpty(true);
                    //sendMessage(port,"@PL");
                    //port.close ();
                    try {
                        inputStream = port.getInputStream();
                        System.out.println("inputstream" + inputStream.available());
                        outputStream = (OutputStream) port.getOutputStream();

                    } catch (IOException e) {
                        System.out.println(e);
                    }

                    //set the created variables to global variables
                    global_variables.port = port;
                    global_variables.inputStream = inputStream;
                    global_variables.outputStream = outputStream;
                } catch (PortInUseException pe) {
                    System.out.println("Open failed");
                    String owner_name = port_id.getCurrentOwner();
                    if (owner_name == null) {
                        System.out.println("Port Owned by unidentified app");
                    } else // The owner name not returned correctly unless it is
                    // a Java program.
                    {
                        System.out.println("  " + owner_name);
                    }
                }
            }
        }
    } 

    public static void sendMessage(SerialPort port, String msg) {
        if (port != null) {
            try {                
                global_variables.outputStream.write(msg.getBytes());
                global_variables.outputStream.flush();
                try {
                    Thread.sleep(2000);  // Be sure data is xferred before closing
                    System.out.println("read called");
                    //SimpleRead read = new SimpleRead();
                    //int read = global_variables.inputStream.read();
                    //System.out.println("read call ended"+read);
                } catch (Exception e) {
                }
            } catch (IOException ex) {
                Logger.getLogger(openPort.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void serialEvent(SerialPortEvent event) {
        System.out.println(event.getEventType());
        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:
            System.out.println("event.getEventType()");
            break;
             *
             */

            case SerialPortEvent.DATA_AVAILABLE:
                System.out.println("inside event handler data available");
                byte[] readBuffer = new byte[20];
                try {
                    while (inputStream.available() > 0) {
                        int numBytes = inputStream.read(readBuffer);
                    }
                    System.out.print(new String(readBuffer));
                    System.exit(1);
                } catch (IOException e) {
                    System.out.println(e);
                }

                break;
        }
    }
}

这段代码有什么问题?当我发送一个轮询消息时,我看不到连接到串口的终端的响应。我在应用程序启动时打开连接,当我的应用程序中的一个按钮被点击时,我发送消息。我该如何解决这个问题?

imzjd6km

imzjd6km1#

参见this wikibook的“事件驱动串行通信”部分。

ykejflvf

ykejflvf2#

先前回答的问题,此处:How do I get Java to use the serial port in Linux?
根据你的平台(如果你在 *NIX盒子上),你经常可以用stty来设置波特率/端口设置,然后简单地用FileInputStream/FileOutputStream打开/dev/tty*端口。我曾经有一大块代码可以做到这一点,并且工作得相当可靠,但现在我去寻找它,它似乎被放错了地方。可悲。

bqjvbblv

bqjvbblv3#

尝试在超过一次之后再次重试tx,并且当保持Rx处于读取状态以调试来自器械的返回消息时

相关问题