0,0 → 1,62 |
package dongfang.mkt.io; |
|
import gnu.io.CommPort; |
import gnu.io.CommPortIdentifier; |
import gnu.io.NoSuchPortException; |
import gnu.io.SerialPort; |
|
import java.io.IOException; |
import java.io.InputStream; |
import java.io.OutputStream; |
|
public class RXTXSerialPort implements MKCommPort { |
private SerialPort serialPort; |
|
public void init(String id) throws IOException { |
// CommPortIdentifier.getPortIdentifier("COM1"); |
// Just take the 1st available port. |
CommPortIdentifier portIdentifier = null; |
|
try { |
if (id == null) { |
portIdentifier = (CommPortIdentifier) CommPortIdentifier |
.getPortIdentifiers().nextElement(); |
if (portIdentifier == null) { |
throw new IOException( |
"No serial port found (in search for any serial port)."); |
} |
} else |
portIdentifier = CommPortIdentifier.getPortIdentifier(id); |
} catch (NoSuchPortException ex) { |
throw new IOException(ex.getMessage()); |
} |
|
System.out.println("Using " + portIdentifier.getName()); |
|
if (portIdentifier.isCurrentlyOwned()) { |
System.out.println("Error: Port is currently in use"); |
return; |
} else { |
try { |
CommPort commPort = portIdentifier.open(this.getClass() |
.getName(), 2001); |
if (commPort instanceof SerialPort) { |
serialPort = (SerialPort) commPort; |
serialPort.setSerialPortParams(57600, |
SerialPort.DATABITS_8, SerialPort.STOPBITS_1, |
SerialPort.PARITY_NONE); |
} |
} catch (Exception ex) { |
throw new IOException(ex.getMessage()); |
} |
} |
} |
|
public InputStream getInputStream() throws IOException { |
return serialPort.getInputStream(); |
} |
|
public OutputStream getOutputStream() throws IOException { |
return serialPort.getOutputStream(); |
} |
} |