inputstream.available() 始终为 0

发布于 2024-11-04 04:09:56 字数 7970 浏览 0 评论 0原文

我不知道我的代码发生了什么。我没有收到任何错误,也没有任何回应。我正在将数据写入串行端口并通过激活 port.notifyOnDataAvailable(true); 等待响应,但此事件未触发,且 inputstream.available() 始终返回 0。可能出了什么问题?我在 Linux 中使用 RXTX。

编辑

package testConn;  
import forms_helper.global_variables;  
import java.io.BufferedReader; 
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStream;  
import java.io.PrintStream;  
import java.io.UnsupportedEncodingException;  
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;
    private BufferedReader is;
    private PrintStream os;

    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", 20000);
                    System.out.println("Opened successfully:"+port);
                    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 {
                        is = new BufferedReader(new InputStreamReader(port.getInputStream()));
                    } catch (IOException e) {
                        System.err.println("Can't open input stream: write-only");
                        is = null;
                    }
                    try {
                        os = new PrintStream(port.getOutputStream(), true);
                    } catch (IOException ex) {
                        Logger.getLogger(openPort.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    try {
                        inputStream = port.getInputStream();
                        System.out.println("inputstream" + inputStream.available());
                        outputStream = (OutputStream) port.getOutputStream();
                        os = new PrintStream(port.getOutputStream(), true, "US-ASCII");


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

                    //set the created variables to global variables
                    global_variables.port = port;
                    global_variables.inputStream = inputStream;
                    System.out.println(inputStream);
                    System.out.println(outputStream);
                    global_variables.outputStream = outputStream;
                    global_variables.os = os;
                } 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) {
                System.out.println(msg);
            try {
                byte[] bytes = msg.getBytes("US-ASCII");
                try {
                    global_variables.outputStream.write(bytes);
                    System.out.println(bytes.length);
                    global_variables.outputStream.flush();
                } catch (IOException ex) {
                    Logger.getLogger(openPort.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(openPort.class.getName()).log(Level.SEVERE, null, ex);
            }
                System.out.println("Opened successfully:"+msg.getBytes());
                //global_variables.outputStream.write(msg.getBytes());
                //global_variables.outputStream.flush();
                //global_variables.os.print(msg);
                System.out.println(global_variables.outputStream);
                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) {
                }

        }
    }

    public void serialEvent(SerialPortEvent event) {
        System.out.println(event.getEventType());
        String line;
                try {
                    line = is.readLine();
                    if (line == null) {
                        System.out.println("EOF on serial port.");
                        System.exit(0);
                    }
                    os.println(line);
                } catch (IOException ex) {
                    System.err.println("IO Error " + ex);
                }
        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;
        }
    }
} // PortListOpen

我正在主方法上打开端口,并在应用程序内的按钮单击事件上发送消息。

I have no idea of what is happening to my code. i am getting no errors and no response as well. I am writing the data to the serialport and waiting for the response by activating port.notifyOnDataAvailable(true); but this event is not triggered and inputstream.available() returns 0 always. What might be wrong ? I am using RXTX in linux.

EDIT

package testConn;  
import forms_helper.global_variables;  
import java.io.BufferedReader; 
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStream;  
import java.io.PrintStream;  
import java.io.UnsupportedEncodingException;  
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;
    private BufferedReader is;
    private PrintStream os;

    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", 20000);
                    System.out.println("Opened successfully:"+port);
                    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 {
                        is = new BufferedReader(new InputStreamReader(port.getInputStream()));
                    } catch (IOException e) {
                        System.err.println("Can't open input stream: write-only");
                        is = null;
                    }
                    try {
                        os = new PrintStream(port.getOutputStream(), true);
                    } catch (IOException ex) {
                        Logger.getLogger(openPort.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    try {
                        inputStream = port.getInputStream();
                        System.out.println("inputstream" + inputStream.available());
                        outputStream = (OutputStream) port.getOutputStream();
                        os = new PrintStream(port.getOutputStream(), true, "US-ASCII");


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

                    //set the created variables to global variables
                    global_variables.port = port;
                    global_variables.inputStream = inputStream;
                    System.out.println(inputStream);
                    System.out.println(outputStream);
                    global_variables.outputStream = outputStream;
                    global_variables.os = os;
                } 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) {
                System.out.println(msg);
            try {
                byte[] bytes = msg.getBytes("US-ASCII");
                try {
                    global_variables.outputStream.write(bytes);
                    System.out.println(bytes.length);
                    global_variables.outputStream.flush();
                } catch (IOException ex) {
                    Logger.getLogger(openPort.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(openPort.class.getName()).log(Level.SEVERE, null, ex);
            }
                System.out.println("Opened successfully:"+msg.getBytes());
                //global_variables.outputStream.write(msg.getBytes());
                //global_variables.outputStream.flush();
                //global_variables.os.print(msg);
                System.out.println(global_variables.outputStream);
                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) {
                }

        }
    }

    public void serialEvent(SerialPortEvent event) {
        System.out.println(event.getEventType());
        String line;
                try {
                    line = is.readLine();
                    if (line == null) {
                        System.out.println("EOF on serial port.");
                        System.exit(0);
                    }
                    os.println(line);
                } catch (IOException ex) {
                    System.err.println("IO Error " + ex);
                }
        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;
        }
    }
} // PortListOpen

I am opening the port on main method and sending the message on a button click event inside the application.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

长不大的小祸害 2024-11-11 04:09:56

.available() 不能用于进程间通信(包括串行),因为它仅检查当前进程中是否有可用数据(在输入缓冲区中)。

在串行通信中,当您发送消息然后立即调用 available() 时,您通常会得到 0,因为串行端口尚未回复任何数据。

解决方案是在单独的线程中使用阻塞 read() (使用 interrupt() 结束它):

线程中断未结束输入流读取上的阻塞调用

.available() can not be used in inter-process communication (serial included), since it only checks if there is data available (in input buffers) in current process.

In serial communication, when you send a messaga and then immediately call available() you will mostly get 0 as serial port did not yet reply with any data.

The solution is to use blocking read() in a separate thread (with interrupt() to end it):

Thread interrupt not ending blocking call on input stream read

浪推晚风 2024-11-11 04:09:56

部分回答你的问题。

来自java文档

类的可用方法
InputStream 始终返回 0。

http://download. oracle.com/javase/6/docs/api/java/io/InputStream.html#available()

所以这部分至少是预期的

To partially answer your question.

From the javadocs

The available method for class
InputStream always returns 0.

http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html#available()

So that part at least is as expected

月亮邮递员 2024-11-11 04:09:56

通过使用 PrintStream,您可以抑制任何请求/响应场景中需要了解的异常。

很可能您还没有发送任何东西。

By using a PrintStream you are suppressing exceptions that you need to know about in any request/response scenario.

Most probably you haven't even sent anything yet.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文