Debian Codegraph @

arduino-core/src/processing/app/Serial.java

raw symbols SCIP
1 /*
2 PSerial - class for serial port goodness
3 Part of the Processing project - http://processing.org
4
5 Copyright (c) 2004 Ben Fry & Casey Reas
6
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
11
12 This library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General
18 Public License along with this library; if not, write to the
19 Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20 Boston, MA 02111-1307 USA
21 */
22
23 package processing.app;
24
25 import jssc.SerialPort;
26 import jssc.SerialPortEvent;
27 import jssc.SerialPortEventListener;
28 import jssc.SerialPortException;
29
30 import java.io.IOException;
31 import java.nio.ByteBuffer;
32 import java.nio.CharBuffer;
33 import java.nio.charset.Charset;
34 import java.nio.charset.CharsetDecoder;
35 import java.nio.charset.CodingErrorAction;
36 import java.nio.charset.StandardCharsets;
37 import java.util.Arrays;
38 import java.util.List;
39
40 import static processing.app.I18n.format;
41 import static processing.app.I18n.tr;
42
43 public class Serial implements SerialPortEventListener {
44
45 //PApplet parent;
46
47 // properties can be passed in for default values
48 // otherwise defaults to 9600 N81
49
50 // these could be made static, which might be a solution
51 // for the classloading problem.. because if code ran again,
52 // the static class would have an object that could be closed
53
54 private SerialPort port;
55
56 private CharsetDecoder bytesToStrings;
57 private static final int IN_BUFFER_CAPACITY = 128;
58 private static final int OUT_BUFFER_CAPACITY = 128;
59 private ByteBuffer inFromSerial = ByteBuffer.allocate(IN_BUFFER_CAPACITY);
60 private CharBuffer outToMessage = CharBuffer.allocate(OUT_BUFFER_CAPACITY);
61
62 public Serial() throws SerialException {
63 this(PreferencesData.get("serial.port"),
64 PreferencesData.getInteger("serial.debug_rate", 9600),
65 PreferencesData.getNonEmpty("serial.parity", "N").charAt(0),
66 PreferencesData.getInteger("serial.databits", 8),
67 PreferencesData.getFloat("serial.stopbits", 1),
68 !BaseNoGui.getBoardPreferences().getBoolean("serial.disableRTS"),
69 !BaseNoGui.getBoardPreferences().getBoolean("serial.disableDTR"));
70 }
71
72 public Serial(int irate) throws SerialException {
73 this(PreferencesData.get("serial.port"), irate,
74 PreferencesData.getNonEmpty("serial.parity", "N").charAt(0),
75 PreferencesData.getInteger("serial.databits", 8),
76 PreferencesData.getFloat("serial.stopbits", 1),
77 !BaseNoGui.getBoardPreferences().getBoolean("serial.disableRTS"),
78 !BaseNoGui.getBoardPreferences().getBoolean("serial.disableDTR"));
79 }
80
81 public Serial(String iname, int irate) throws SerialException {
82 this(iname, irate, PreferencesData.getNonEmpty("serial.parity", "N").charAt(0),
83 PreferencesData.getInteger("serial.databits", 8),
84 PreferencesData.getFloat("serial.stopbits", 1),
85 !BaseNoGui.getBoardPreferences().getBoolean("serial.disableRTS"),
86 !BaseNoGui.getBoardPreferences().getBoolean("serial.disableDTR"));
87 }
88
89 public Serial(String iname) throws SerialException {
90 this(iname, PreferencesData.getInteger("serial.debug_rate", 9600),
91 PreferencesData.getNonEmpty("serial.parity", "N").charAt(0),
92 PreferencesData.getInteger("serial.databits", 8),
93 PreferencesData.getFloat("serial.stopbits", 1),
94 !BaseNoGui.getBoardPreferences().getBoolean("serial.disableRTS"),
95 !BaseNoGui.getBoardPreferences().getBoolean("serial.disableDTR"));
96 }
97
98 public static boolean touchForCDCReset(String iname) throws SerialException {
99 SerialPort serialPort = new SerialPort(iname);
100 try {
101 serialPort.openPort();
102 serialPort.setParams(1200, 8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
103 serialPort.setDTR(false);
104 serialPort.closePort();
105 return true;
106 } catch (SerialPortException e) {
107 throw new SerialException(format(tr("Error touching serial port ''{0}''."), iname), e);
108 } finally {
109 if (serialPort.isOpened()) {
110 try {
111 serialPort.closePort();
112 } catch (SerialPortException e) {
113 // noop
114 }
115 }
116 }
117 }
118
119 protected Serial(String iname, int irate, char iparity, int idatabits, float istopbits, boolean setRTS, boolean setDTR) throws SerialException {
120 //if (port != null) port.close();
121 //this.parent = parent;
122 //parent.attach(this);
123
124 resetDecoding(StandardCharsets.UTF_8);
125
126 int parity = SerialPort.PARITY_NONE;
127 if (iparity == 'E') parity = SerialPort.PARITY_EVEN;
128 if (iparity == 'O') parity = SerialPort.PARITY_ODD;
129
130 int stopbits = SerialPort.STOPBITS_1;
131 if (istopbits == 1.5f) stopbits = SerialPort.STOPBITS_1_5;
132 if (istopbits == 2) stopbits = SerialPort.STOPBITS_2;
133
134 // This is required for unit-testing
135 if (iname.equals("none")) {
136 return;
137 }
138
139 try {
140 port = new SerialPort(iname);
141 port.openPort();
142 boolean res = port.setParams(irate, idatabits, stopbits, parity, setRTS, setDTR);
143 if (!res) {
144 System.err.println(format(tr("Error while setting serial port parameters: {0} {1} {2} {3}"),
145 irate, iparity, idatabits, istopbits));
146 }
147 port.addEventListener(this);
148 } catch (SerialPortException e) {
149 if (e.getPortName().startsWith("/dev") && SerialPortException.TYPE_PERMISSION_DENIED.equals(e.getExceptionType())) {
150 throw new SerialException(format(tr("Error opening serial port ''{0}''. Try consulting the documentation at http://playground.arduino.cc/Linux/All#Permission"), iname));
151 }
152 throw new SerialException(format(tr("Error opening serial port ''{0}''."), iname), e);
153 }
154
155 if (port == null) {
156 throw new SerialNotFoundException(format(tr("Serial port ''{0}'' not found. Did you select the right one from the Tools > Serial Port menu?"), iname));
157 }
158 }
159
160 public void setup() {
161 //parent.registerCall(this, DISPOSE);
162 }
163
164 public void dispose() throws IOException {
165 if (port != null) {
166 try {
167 if (port.isOpened()) {
168 port.closePort(); // close the port
169 }
170 } catch (SerialPortException e) {
171 throw new IOException(e);
172 } finally {
173 port = null;
174 }
175 }
176 }
177
178 @Override
179 public synchronized void serialEvent(SerialPortEvent serialEvent) {
180 if (serialEvent.isRXCHAR()) {
181 try {
182 byte[] buf = port.readBytes(serialEvent.getEventValue());
183 processSerialEvent(buf);
184 } catch (SerialPortException e) {
185 errorMessage("serialEvent", e);
186 }
187 }
188 }
189
190 public void processSerialEvent(byte[] buf) {
191 int next = 0;
192 // This uses a CharsetDecoder to convert from bytes to UTF-8 in
193 // a streaming fashion (i.e. where characters might be split
194 // over multiple reads). This needs the data to be in a
195 // ByteBuffer (inFromSerial, which we also use to store leftover
196 // incomplete characters for the nexst run) and produces a
197 // CharBuffer (outToMessage), which we then convert to char[] to
198 // pass onwards.
199 // Note that these buffers switch from input to output mode
200 // using flip/compact/clear
201 while (next < buf.length || inFromSerial.position() > 0) {
202 do {
203 // This might be 0 when all data was already read from buf
204 // (but then there will be data in inFromSerial left to
205 // decode).
206 int copyNow = Math.min(buf.length - next, inFromSerial.remaining());
207 inFromSerial.put(buf, next, copyNow);
208 next += copyNow;
209
210 inFromSerial.flip();
211 bytesToStrings.decode(inFromSerial, outToMessage, false);
212 inFromSerial.compact();
213
214 // When there are multi-byte characters, outToMessage might
215 // still have room, so add more bytes if we have any.
216 } while (next < buf.length && outToMessage.hasRemaining());
217
218 // If no output was produced, the input only contained
219 // incomplete characters, so we're done processing
220 if (outToMessage.position() == 0)
221 break;
222
223 outToMessage.flip();
224 char[] chars = new char[outToMessage.remaining()];
225 outToMessage.get(chars);
226 message(chars, chars.length);
227 outToMessage.clear();
228 }
229 }
230
231 /**
232 * This method is intented to be extended to receive messages
233 * coming from serial port.
234 */
235 protected void message(char[] chars, int length) {
236 // Empty
237 }
238
239
240 /**
241 * This will handle both ints, bytes and chars transparently.
242 */
243 public void write(int what) { // will also cover char
244 try {
245 port.writeInt(what & 0xff);
246 } catch (SerialPortException e) {
247 errorMessage("write", e);
248 }
249 }
250
251
252 public void write(byte bytes[]) {
253 try {
254 port.writeBytes(bytes);
255 } catch (SerialPortException e) {
256 errorMessage("write", e);
257 }
258 }
259
260
261 /**
262 * Write a String to the output. Note that this doesn't account
263 * for Unicode (two bytes per char), nor will it send UTF8
264 * characters.. It assumes that you mean to send a byte buffer
265 * (most often the case for networking and serial i/o) and
266 * will only use the bottom 8 bits of each char in the string.
267 * (Meaning that internally it uses String.getBytes)
268 * <p>
269 * If you want to move Unicode data, you can first convert the
270 * String to a byte stream in the representation of your choice
271 * (i.e. UTF8 or two-byte Unicode data), and send it as a byte array.
272 */
273 public void write(String what) {
274 write(what.getBytes());
275 }
276
277 public void setDTR(boolean state) {
278 try {
279 port.setDTR(state);
280 } catch (SerialPortException e) {
281 errorMessage("setDTR", e);
282 }
283 }
284
285 public void setRTS(boolean state) {
286 try {
287 port.setRTS(state);
288 } catch (SerialPortException e) {
289 errorMessage("setRTS", e);
290 }
291 }
292
293 /**
294 * Reset the encoding used to convert the bytes coming in
295 * before they are handed as Strings to {@Link #message(char[], int)}.
296 */
297 public synchronized void resetDecoding(Charset charset) {
298 bytesToStrings = charset.newDecoder()
299 .onMalformedInput(CodingErrorAction.REPLACE)
300 .onUnmappableCharacter(CodingErrorAction.REPLACE)
301 .replaceWith("\u2e2e");
302 }
303
304 static public List<String> list() {
305 return Arrays.asList(SerialPortList.getPortNames());
306 }
307
308
309 /**
310 * General error reporting, all corraled here just in case
311 * I think of something slightly more intelligent to do.
312 */
313 private static void errorMessage(String where, Throwable e) {
314 System.err.println(format(tr("Error inside Serial.{0}()"), where));
315 e.printStackTrace();
316 }
317 }