Deepak
Deepak

Reputation: 6802

Serialport read write in java

I have an application where i need to write some data to the serial port and get the response from it. Now the sequence is as follows:

  1. Send a message to the serial port.
  2. wait for the response
  3. Once the response is received i have to process the message and until then nothing should happen to the application.

How should i break this problem and solve it ? I am not good in serial programming. I have tried a code but my application halts when i execute the send message. May be because i am reading the message just after sending a message. I really don't know hot to break this problem down. Do i have to start listen to the port during the application start ? Do i have to keep the port open ? Is it ok if i open the port every time i need that ? and how should i make the program wait to respond until the response message is read form the port ? Please help me solve this problem..

--EDIT--

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;
        }
    }
}

What is wrong with this code ? I cant see the response from the terminal connected to serialport when i send a polling message. I am opening the connection at my application start and i am sending the message when a button inside my application is clicked. How do i solve the problem ??

Upvotes: 2

Views: 38322

Answers (3)

Disabled
Disabled

Reputation: 1

Try to retryger the tx again after than the once and when keep the Rx on read for debugg the came back message from the device

Upvotes: 0

Femi
Femi

Reputation: 64690

Previously answered question, here: How do I get Java to use the serial port in Linux?

Depending on your platform (if you are on a *NIX box) you can often get away with using stty to set the baud rate/port settings, and then simply open the /dev/tty* port with a FileInputStream/FileOutputStream. I used to have a chunk of code that did that and worked quite reliably, but now that I go looking for it it appears to have been misplaced. Sad.

Upvotes: 2

moritz
moritz

Reputation: 5224

See this wikibook, section Event Driven Serial Communication.

Upvotes: 2

Related Questions