Details | Last modification | View Log | RSS feed
Rev | Author | Line No. | Line |
---|---|---|---|
1563 | - | 1 | package dongfang.mkt.comm.serial; |
2 | |||
3 | import gnu.io.CommPort; |
||
4 | import gnu.io.CommPortIdentifier; |
||
5 | import gnu.io.NoSuchPortException; |
||
6 | import gnu.io.SerialPort; |
||
7 | |||
8 | import java.io.IOException; |
||
9 | import java.io.InputStream; |
||
10 | import java.io.OutputStream; |
||
11 | |||
12 | import dongfang.mkt.comm.MKConnection; |
||
13 | |||
14 | |||
15 | public class RXTXSerialPort implements MKConnection { |
||
16 | private SerialPort serialPort; |
||
17 | |||
18 | public void init(String id) throws IOException { |
||
19 | // CommPortIdentifier.getPortIdentifier("COM1"); |
||
20 | // Just take the 1st available port. |
||
21 | CommPortIdentifier portIdentifier = null; |
||
22 | |||
23 | try { |
||
24 | if (id == null) { |
||
25 | portIdentifier = (CommPortIdentifier) CommPortIdentifier |
||
26 | .getPortIdentifiers().nextElement(); |
||
27 | if (portIdentifier == null) { |
||
28 | throw new IOException( |
||
29 | "No serial port found (in search for any serial port)."); |
||
30 | } |
||
31 | } else |
||
32 | portIdentifier = CommPortIdentifier.getPortIdentifier(id); |
||
33 | } catch (NoSuchPortException ex) { |
||
34 | throw new IOException(ex.getMessage()); |
||
35 | } |
||
36 | |||
37 | System.out.println("Using " + portIdentifier.getName()); |
||
38 | |||
39 | if (portIdentifier.isCurrentlyOwned()) { |
||
40 | System.out.println("Error: Port is currently in use"); |
||
41 | return; |
||
42 | } else { |
||
43 | try { |
||
44 | CommPort commPort = portIdentifier.open(this.getClass() |
||
45 | .getName(), 2001); |
||
46 | if (commPort instanceof SerialPort) { |
||
47 | serialPort = (SerialPort) commPort; |
||
48 | serialPort.setSerialPortParams(57600, |
||
49 | SerialPort.DATABITS_8, SerialPort.STOPBITS_1, |
||
50 | SerialPort.PARITY_NONE); |
||
51 | } |
||
52 | } catch (Exception ex) { |
||
53 | throw new IOException(ex.getMessage()); |
||
54 | } |
||
55 | } |
||
56 | } |
||
57 | |||
58 | public InputStream getInputStream() throws IOException { |
||
59 | return serialPort.getInputStream(); |
||
60 | } |
||
61 | |||
62 | public OutputStream getOutputStream() throws IOException { |
||
63 | return serialPort.getOutputStream(); |
||
64 | } |
||
65 | } |