1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.chabala.brick.controllab;
20
21 import jssc.SerialPortException;
22
23 import java.io.IOException;
24
25
26
27
28
29
30
31 class JsscSerialPort implements SerialPort {
32
33 private final jssc.SerialPort serialPort;
34
35
36
37
38
39 JsscSerialPort(String portName) {
40 this(new jssc.SerialPort(portName));
41 }
42
43
44
45
46 JsscSerialPort(jssc.SerialPort serialPort) {
47 this.serialPort = serialPort;
48 }
49
50
51 @Override
52 public String getPortName() {
53 return serialPort.getPortName();
54 }
55
56
57 @Override
58 public void openPort() throws IOException {
59 try {
60 serialPort.openPort();
61 setParams();
62 setEventsMask();
63 } catch (SerialPortException e) {
64 throw new IOException(e);
65 }
66 }
67
68
69 @Override
70 public boolean isOpen() {
71 return serialPort.isOpened();
72 }
73
74
75 @Override
76 public boolean write(byte b) throws IOException {
77 try {
78 return serialPort.writeByte(b);
79 } catch (SerialPortException e) {
80 throw new IOException(e);
81 }
82 }
83
84
85 @Override
86 public boolean write(byte[] bytes) throws IOException {
87 try {
88 return serialPort.writeBytes(bytes);
89 } catch (SerialPortException e) {
90 throw new IOException(e);
91 }
92 }
93
94
95 @Override
96 public byte[] readBytes(int byteCount) throws IOException {
97 try {
98 return serialPort.readBytes(byteCount);
99 } catch (SerialPortException e) {
100 throw new IOException(e);
101 }
102 }
103
104
105 @Override
106 public void close() throws IOException {
107 if (serialPort.isOpened()) {
108 try {
109 serialPort.closePort();
110 } catch (SerialPortException e) {
111 throw new IOException("Error closing serial port", e);
112 }
113 }
114 }
115
116 private boolean setParams() throws SerialPortException {
117 return serialPort.setParams(
118 jssc.SerialPort.BAUDRATE_9600,
119 jssc.SerialPort.DATABITS_8,
120 jssc.SerialPort.STOPBITS_1,
121 jssc.SerialPort.PARITY_NONE,
122 true,
123 true);
124 }
125
126 private boolean setEventsMask() throws SerialPortException {
127 return serialPort.setEventsMask(
128 jssc.SerialPort.MASK_RXCHAR |
129 jssc.SerialPort.MASK_CTS |
130 jssc.SerialPort.MASK_DSR);
131 }
132
133
134 @Override
135 public void addEventListener(SerialPortEventListener listener) throws IOException {
136 try {
137 serialPort.addEventListener(listener);
138 } catch (SerialPortException e) {
139 throw new IOException(e);
140 }
141 }
142
143
144 @Override
145 public String toString() {
146 return "JsscSerialPort{" +
147 "portName='" + getPortName() + '\'' +
148 ", open=" + isOpen() +
149 '}';
150 }
151 }