[Rxtx] closing a serial port connection (hanging & exception access error)

Julian Bui julianbui at gmail.com
Mon Feb 23 18:33:12 MST 2009


Here is the full code that produces the error:



/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SC.java
 *
 * Created on Feb 3, 2009, 11:11:10 AM
 */
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

/**
 *
 * @author julian.bui
 */
public class SC extends javax.swing.JFrame {

    static InputStream in;
    static OutputStream out;
    static SerialPort serialPort;
    static CommPort commPort;
    static Object lock = new Object();
    static Thread readerThread;
    static boolean running = true;

    public SC() {
        initComponents();
    }

    void connect(String portName) throws Exception {
        System.out.println("COM ports on server:");
        for (Enumeration ports = CommPortIdentifier.getPortIdentifiers();
ports.hasMoreElements();) {
            System.out.println(((CommPortIdentifier)
ports.nextElement()).getName());
        }
        System.out.println("Connecting to COM port: " + portName);

        CommPortIdentifier portIdentifier =
CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()) {
            System.out.println("Error: Port is currently in use");
        } else {
            commPort = portIdentifier.open(this.getClass().getName(), 2000);

            if (commPort instanceof SerialPort) {
                serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);


serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
                serialPort.disableReceiveFraming();

                in = serialPort.getInputStream();
                out = serialPort.getOutputStream();

                //serialPort.addEventListener(new SerialReadera(in));
                //serialPort.notifyOnDataAvailable(true);

                readerThread = new Thread(new SerialReader(in));
                readerThread.start();
            } else {
                System.out.println("Error: Only serial ports are handled by
this example.");
            }
        }
    }

    /** */
    public static class SerialReader implements Runnable {

        InputStream in;

        public SerialReader(InputStream in) {
            this.in = in;
        }

        public void run() {
            byte[] buffer = new byte[1024];
            int len = -1;
            try {
                while ((len = this.in.read(buffer)) > -1) {
                    System.out.print(new String(buffer, 0, len));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Handles the input coming from the serial port. A new line character
     * is treated as the end of a block in this example.
     */
    public static class SerialReadera implements SerialPortEventListener {

        private InputStream in;
        private byte[] buffer = new byte[1024];

        public SerialReadera(InputStream in) {
            this.in = in;
        }

        public void serialEvent(SerialPortEvent arg0) {
            //synchronized (lock) {
            int data;

            try {
                int len = 0;

                while (running && (data = in.read()) > -1) {
                    buffer[len++] = (byte) data;
                }

                System.err.print(new String(buffer, 0, len));
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(-1);
            }
        //}
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated
Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton1.setText("Send Text");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Multi-Message Surprise");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("close");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(110, 110, 110)
                        .addComponent(jScrollPane1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(148, 148, 148)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(119, 119, 119)
                        .addComponent(jButton2)))
                .addContainerGap(63, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(96, 96, 96)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton3)
                    .addComponent(jScrollPane1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45,
Short.MAX_VALUE)
                .addComponent(jButton2)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
        write(jTextArea1.getText());
        jTextArea1.setText("");
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
        write("STATUS");
        //write("STATUS"); //UNCOMMENT THIS LINE TO MAKE THE "MULTI MESSAGE
SURPRISE" BUTTON SEND TWO COMMANDS AT ONCE
    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
{
        running = false;
        close();
    }

    private static void close() {
        if (serialPort != null) {
            try {
                // close the i/o streams.
                out.flush();

                System.out.println("about to close");

                out.close();
                in.close();
            } catch (IOException ex) {
                // don't care
            }
            // Close the port.

            System.out.println("about to remove event listener");
            serialPort.removeEventListener();
            System.out.println("about to close serial");
            serialPort.close();
            System.out.println("finished closing");
        }
    }

    private static void printBytes(byte[] x) {
        StringBuffer sb = new StringBuffer();
        sb.append("Bytes you're sending: ");
        for (int i = 0; i < x.length; i++) {
            sb.append(x[i]);
            sb.append("-");
        }
        System.err.println(sb.toString());
    }

    synchronized static void write(String outString) {
        //synchronized (lock) {
        try {

            if (outString != null && out != null) {
                byte[] outStringBytes = outString.getBytes();

                for (int i = 0; i < outString.length(); i++) {
                    out.write(outStringBytes[i]);
                    out.flush();
                }

                out.write(13);
                out.flush();
            }
        } catch (IOException ex) {
            System.out.println("exception");
        }
    //}
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    SC x = new SC();
                    x.connect("COM3");
                    x.setVisible(true);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.qbang.org/pipermail/rxtx/attachments/20090223/7d3abebc/attachment-1154.htm>


More information about the Rxtx mailing list