为什么我的程序在Main方法完成后没有完成?

时间:2015-01-08 20:40:56

标签: java serial-port arduino event-listener

我最近得到了arduino并开始玩它。我已经编写了一个java程序来监听来自arduino的串口输入(或者我稍微修改了一些示例代码。

这是代码:

public class SerialListener implements SerialPortEventListener {
SerialPort serialPort;

/**
 * A BufferedReader which will be fed by a InputStreamReader 
 * converting the bytes into characters 
 * making the displayed results codepage independent
 */
private BufferedReader input;
/** The output stream to the port */
private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;

public void initialize() {
    // the next line is for Raspberry Pi and 
    // gets us into the while loop and was suggested here was suggested http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186
    // System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");

    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
    while (portEnum.hasMoreElements()) {
        CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
        if (currPortId.getName().equals("COM3")) {
            portId = currPortId;
            break;
        }
    }


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

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

        // open the streams
        input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
        output = serialPort.getOutputStream();

        // add event listeners
        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);
    } catch (Exception e) {
        System.err.println(e.toString());
    }
}

/**
 * This should be called when you stop using the port.
 * This will prevent port locking on platforms like Linux.
 */
public synchronized void close() {
    if (serialPort != null) {
        serialPort.removeEventListener();
        serialPort.close();
    }
}

/**
 * Handle an event on the serial port. Read the data and print it.
 */
public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            String inputLine=input.readLine();
            System.out.println(inputLine);
            FileWriter fWriter = new FileWriter("C:\\Apache24\\htdocs\\temp.txt");
            BufferedWriter writer = new BufferedWriter (fWriter);
            writer.write(inputLine);
            writer.close();
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
}

public static void main(String[] args) throws Exception {
    SerialListener tempListener = new SerialListener();
    tempListener.initialize();

}
}

我理解SerialListener类实现了处理SerialPort Events的方法,而我在initiate方法中设置SerialListner类的对象来监听事件。

我不明白为什么这个程序不会立即退出,因为在运行initialize方法后它在main方法中什么都不做。

事件监听器是否在不同的线程上运行,或者为什么这样做? (因为这可以按照我想要的方式工作)

我基本上复制的代码可以在这里找到: http://playground.arduino.cc/Interfacing/Java 在“Java示例代码”下但是你可以看到我没有启动一个让它保持活动1000秒的类,正如他们在示例中所说的那样

2 个答案:

答案 0 :(得分:0)

如果在主方法的末尾添加以下内容,该怎么办:

tempListener.close();

答案 1 :(得分:0)

来自SerialPort.addEventListener()上的docs

  

此侦听器接收的所有事件都由属于SerialPort对象的一个​​专用线程生成。

所以我猜SerialPort有一个线程正在运行。之后尝试拨打tempListener.close();