John Neale
Posts: 10
Nickname: rhino
Registered: Oct, 2003
|
|
Re: Code for privious---serial Port event
|
Posted: Jan 26, 2005 7:16 AM
|
|
Chanda,
A Java program will stop running as soon as the main thread finishes. So your code is running the main method, creating a PhoneListener object and then opening the port in the main method and attaching the listener. The main thread then finishes and so your program finishes.
What you need in the main method is to keep the thread alive. i.e. something to block the thread like a read from input.
Here's a version that should solve your immediate problem.
import javax.comm.*;
import java.io.IOException;
import java.util.TooManyListenersException;
public class PhoneListener implements SerialPortEventListener {
public PhoneListener() {
}
public void setup() {
String portName = "COM3";
try {
CommPortIdentifier cpi = CommPortIdentifier.getPortIdentifier(portName);
if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
SerialPort modem = (SerialPort)cpi.open("Phone Listener", 1000);
modem.notifyOnRingIndicator(true);
modem.notifyOnDataAvailable(true);
modem.addEventListener(this);
}
} catch (NoSuchPortException e) {
System.err.println("Usage: java PhoneListener port_name");
} catch (PortInUseException e) {
System.err.println(e);
} catch (TooManyListenersException e) {
}
}
public static void main(String[] args) throws InterruptedException, IOException {
PhoneListener pl = new PhoneListener();
pl.setup();
System.out.println("Press ENTER to stop");
System.in.read(new byte[10]);
}
public void serialEvent(SerialPortEvent evt) {
System.out.print("Serial port event is fired..");
System.err.println(evt.getEventType());
if (evt.getEventType() == SerialPortEvent.RI) {
System.out.print("Ringing...");
}
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
System.out.print("Data available...");
}
}
}
|
|