Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 681b74c47e907f4a96106a498be6267e42eebd3d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/*******************************************************************************
 * Copyright (c) 2015 QNX Software Systems and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     QNX Software Systems - Initial API and implementation
 *******************************************************************************/
package org.eclipse.cdt.serial;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.eclipse.cdt.serial.internal.Messages;

/**
 * @since 5.8
 */
public class SerialPort {

	private final String portName;
	private boolean isOpen;
	private boolean isPaused;
	private Object pauseMutex = new Object();
	private BaudRate baudRate = BaudRate.B115200;
	private ByteSize byteSize = ByteSize.B8;
	private Parity parity = Parity.None;
	private StopBits stopBits = StopBits.S1;
	private long handle;

	private static final String PORT_OPEN = Messages.getString("SerialPort.PortIsOpen"); //$NON-NLS-1$

	static {
		try {
			System.loadLibrary("serial"); //$NON-NLS-1$
		} catch (UnsatisfiedLinkError e) {
			e.printStackTrace();
		}
	}

	private InputStream inputStream = new InputStream() {
		private byte[] rbuff = new byte[256];
		private int rpos = 0;
		private int rlen = 0;

		@Override
		public int read() throws IOException {
			if (isOpen()) {
				if (rpos >= rlen) {
					while (true) {
						rlen = read1(handle, rbuff, 0, rbuff.length);
						if (rlen < 0) {
							if (isPaused) {
								synchronized (pauseMutex) {
									while (isPaused) {
										try {
											pauseMutex.wait();
										} catch (InterruptedException e) {
											return -1;
										}
									}
								}
							} else {
								return -1;
							}
						} else if (rlen > 0) {
							break;
						}
					}
				}
				return rbuff[rpos++];
			} else {
				return -1;
			}
		}

		@Override
		public int read(byte[] b, int off, int len) throws IOException {
			if (isOpen()) {
				int n = rlen - rpos;
				if (n > 0) {
					if (len < n) {
						n = len;
					}
					System.arraycopy(rbuff, rpos, b, off, n);
					rpos += n;
					return n;
				} else {
					n = read1(handle, b, off, len);
					if (n <= 0 && isPaused) {
						synchronized (pauseMutex) {
							while (isPaused) {
								try {
									pauseMutex.wait();
								} catch (InterruptedException e) {
									return -1;
								}
							}
						}
						return read1(handle, b, off, len);
					} else {
						return n;
					}
				}
			} else {
				return -1;
			}
		}

		@Override
		public void close() throws IOException {
			SerialPort.this.close();
		}
	};

	private OutputStream outputStream = new OutputStream() {
		@Override
		public void write(int b) throws IOException {
			if (isOpen()) {
				try {
					write0(handle, b);
				} catch (IOException e) {
					if (isPaused) {
						synchronized (pauseMutex) {
							while (isPaused) {
								try {
									pauseMutex.wait();
								} catch (InterruptedException e1) {
									throw e;
								}
							}
						}
						write0(handle, b);
					}
				}
			}
		}

		@Override
		public void write(byte[] buff, int off, int len) throws IOException {
			if (isOpen()) {
				try {
					write1(handle, buff, off, len);
				} catch (IOException e) {
					if (isPaused) {
						synchronized (pauseMutex) {
							while (isPaused) {
								try {
									pauseMutex.wait();
								} catch (InterruptedException e1) {
									throw e;
								}
							}
						}
						write1(handle, buff, off, len);
					}
				}
			}
		}

		@Override
		public void close() throws IOException {
			SerialPort.this.close();
		}
	};

	/**
	 * Create a serial port that connect to the given serial device.
	 * 
	 * @param portName
	 *            name for the serial device.
	 */
	public SerialPort(String portName) {
		if (System.getProperty("os.name").startsWith("Windows") && !portName.startsWith("\\\\.\\")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			this.portName = "\\\\.\\" + portName; //$NON-NLS-1$
		} else {
			this.portName = portName;
		}
	}

	private native long open0(String portName, int baudRate, int byteSize, int parity, int stopBits) throws IOException;

	private native void close0(long handle) throws IOException;

	private native int read1(long handle, byte[] b, int off, int len) throws IOException;

	private native void write0(long handle, int b) throws IOException;

	private native void write1(long handle, byte[] b, int off, int len) throws IOException;

	private static native String getPortName(int i) throws IOException;

	private static String[] listDevs(final Pattern pattern) {
		File dev = new File("/dev"); //$NON-NLS-1$
		File[] files = dev.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return pattern.matcher(name).matches();
			}
		});

		if (files == null) {
			return new String[0];
		}

		String[] names = new String[files.length];
		for (int i = 0; i < files.length; i++) {
			names[i] = files[i].getAbsolutePath();
		}
		return names;
	}

	/**
	 * List the available serial ports.
	 * 
	 * @return serial ports
	 */
	public static String[] list() throws IOException {
		String osName = System.getProperty("os.name"); //$NON-NLS-1$
		if (osName.equals("Mac OS X")) { //$NON-NLS-1$
			return listDevs(Pattern.compile("cu\\..*")); //$NON-NLS-1$
		} else if (osName.equals("Linux")) { //$NON-NLS-1$
			return listDevs(Pattern.compile("ttyUSB.*")); //$NON-NLS-1$
		} else if (osName.startsWith("Windows")) { //$NON-NLS-1$
			List<String> ports = new ArrayList<>();
			int i = 0;
			String name = null;
			do {
				try {
					name = getPortName(i++);
					if (name != null) {
						ports.add(name);
					}
				} catch (IOException e) {
					// TODO log the exception
					e.printStackTrace();
				}
			} while (name != null);
			return ports.toArray(new String[ports.size()]);
		} else {
			return new String[0];
		}
	}

	/**
	 * Return the name for this serial port.
	 * 
	 * @return serial port name
	 */
	public String getPortName() {
		return portName;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public OutputStream getOutputStream() {
		return outputStream;
	}

	public void open() throws IOException {
		handle = open0(portName, baudRate.getRate(), byteSize.getSize(), parity.ordinal(), stopBits.ordinal());
		isOpen = true;
	}

	public synchronized void close() throws IOException {
		if (isOpen) {
			isOpen = false;
			close0(handle);
			handle = 0;
			try {
				// Sleep for a second since some serial ports take a while to actually close
				Thread.sleep(500);
			} catch (InterruptedException e) {
				// nothing to do 
			}
		}
	}

	public boolean isOpen() {
		return isOpen;
	}
	
	public void pause() throws IOException {
		isPaused = true;
		close0(handle);
		try {
			// Sleep for a second since some serial ports take a while to actually close
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// nothing to do 
		}
	}

	public void resume() throws IOException {
		synchronized (pauseMutex) {
			isPaused = false;
			open();
			pauseMutex.notifyAll();
		}
	}

	public void setBaudRate(BaudRate rate) throws IOException {
		if (isOpen) {
			throw new IOException(PORT_OPEN);
		}
		this.baudRate = rate;
	}

	public BaudRate getBaudRate() {
		return baudRate;
	}

	public void setByteSize(ByteSize size) throws IOException {
		if (isOpen) {
			throw new IOException(PORT_OPEN);
		}
		this.byteSize = size;
	}

	public ByteSize getByteSize() {
		return byteSize;
	}

	public void setParity(Parity parity) throws IOException {
		if (isOpen) {
			throw new IOException(PORT_OPEN);
		}
		this.parity = parity;
	}

	public Parity getParity() {
		return parity;
	}

	public void setStopBits(StopBits stopBits) throws IOException {
		if (isOpen) {
			throw new IOException(PORT_OPEN);
		}
		this.stopBits = stopBits;
	}

	public StopBits getStopBits() {
		return stopBits;
	}

}

Back to the top