forked from JTrotta/MonoSerialPort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSerialPortInput.cs
367 lines (326 loc) · 11.3 KB
/
SerialPortInput.cs
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
357
358
359
360
361
362
363
364
365
366
367
using SerialPortLib2.Port;
using System;
using System.IO;
using System.Threading;
namespace SerialPortLib2
{
/// <summary>
/// Serial port I/O
/// </summary>
public class SerialPortInput
{
#region Private Fields
//internal static Logger logger = LogManager.GetCurrentClassLogger();
private SerialPort serialPort;
private string _portName = "";
private int _defaultBaudRate = 115200;
private Parity _defaultParity = Parity.None;
private int _defaultDataBits = 8;
private StopBits _defaultStopBits = StopBits.One;
private bool _isVirtualPort = false;
// Read/Write error state variable
private bool gotReadWriteError = true;
// Serial port reader task
private Thread reader;
// Serial port connection watcher
private Thread connectionWatcher;
private object accessLock = new object();
private bool disconnectRequested = false;
#endregion
#region Public Events
/// <summary>
/// Connected state changed event.
/// </summary>
public delegate void ConnectionStatusChangedEventHandler(object sender, ConnectionStatusChangedEventArgs args);
/// <summary>
/// Occurs when connected state changed.
/// </summary>
public event ConnectionStatusChangedEventHandler ConnectionStatusChanged;
/// <summary>
/// Message received event.
/// </summary>
public delegate void MessageReceivedEventHandler(object sender, MessageReceivedEventArgs args);
/// <summary>
/// Occurs when message received.
/// </summary>
public event MessageReceivedEventHandler MessageReceived;
#endregion
#region Public Members
public SerialPortInput():this(false)
{
}
public SerialPortInput(bool isVirtualPort)
{
this._isVirtualPort = isVirtualPort;
}
public SerialPortInput(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, bool isVirtualPort)
{
this._isVirtualPort = isVirtualPort;
this._defaultBaudRate = baudRate;
this._defaultParity = parity;
this._defaultDataBits = dataBits;
this._defaultStopBits = stopBits;
this._portName = portName;
}
/// <summary>
/// Connect to the serial port.
/// </summary>
public bool Connect()
{
if (disconnectRequested)
return false;
lock (accessLock)
{
Disconnect();
Open();
connectionWatcher = new Thread(new ThreadStart(ConnectionWatcherTask));
connectionWatcher.Start();
}
return IsConnected;
}
/// <summary>
/// Disconnect the serial port.
/// </summary>
public void Disconnect()
{
if (disconnectRequested)
return;
disconnectRequested = true;
Close();
lock (accessLock)
{
if (connectionWatcher != null)
{
if (!connectionWatcher.Join(5000))
connectionWatcher.Abort();
connectionWatcher = null;
}
disconnectRequested = false;
}
}
/// <summary>
/// Gets a value indicating whether the serial port is connected.
/// </summary>
/// <value><c>true</c> if connected; otherwise, <c>false</c>.</value>
public bool IsConnected
{
get { return serialPort != null && !gotReadWriteError && !disconnectRequested; }
}
/// <summary>
/// Sets the serial port options.
/// </summary>
/// <param name="portname">Portname.</param>
/// <param name="baudrate">Baudrate.</param>
public void SetPort(string portname, int baudrate = 115200)
{
if (_portName != portname)
{
// set to erro so that the connection watcher will reconnect
// using the new port
gotReadWriteError = true;
}
_portName = portname;
_defaultBaudRate = baudrate;
}
/// <summary>
/// Sends the message.
/// </summary>
/// <returns><c>true</c>, if message was sent, <c>false</c> otherwise.</returns>
/// <param name="message">Message.</param>
public bool SendMessage(byte[] message)
{
bool success = false;
if (IsConnected)
{
try
{
serialPort.Write(message, 0, message.Length);
success = true;
//logger.Debug(BitConverter.ToString(message));
}
catch (Exception e)
{
//logger.Error(e);
}
}
return success;
}
#endregion
#region Private members
#region Serial Port handling
private bool Open()
{
bool success = false;
lock (accessLock)
{
Close();
try
{
bool tryOpen = true;
if (Environment.OSVersion.Platform.ToString().StartsWith("Win") == false)
{
tryOpen = (tryOpen && System.IO.File.Exists(_portName));
}
if (tryOpen)
{
serialPort = new SerialPort();
//JJ
//serialPort.Handshake = Handshake.RequestToSendXOnXOff;
serialPort.IsVirtualPort = this._isVirtualPort;
serialPort.ErrorReceived += HanldeErrorReceived;
serialPort.PortName = _portName;
serialPort.BaudRate = _defaultBaudRate;
serialPort.Parity = _defaultParity;
serialPort.DataBits = _defaultDataBits;
serialPort.StopBits = _defaultStopBits;
// We are not using serialPort.DataReceived event for receiving data since this is not working under Linux/Mono.
// We use the readerTask instead (see below).
serialPort.Open();
success = true;
}
}
catch (Exception e)
{
//logger.Error(e);
Close();
}
if (serialPort != null && serialPort.IsOpen)
{
gotReadWriteError = false;
// Start the Reader task
reader = new Thread(ReaderTask);
reader.Start();
OnConnectionStatusChanged(new ConnectionStatusChangedEventArgs(true));
}
}
return success;
}
private void Close()
{
lock (accessLock)
{
// Stop the Reader task
if (reader != null)
{
if (!reader.Join(5000))
reader.Abort();
reader = null;
}
if (serialPort != null)
{
serialPort.ErrorReceived -= HanldeErrorReceived;
if (serialPort.IsOpen)
{
serialPort.Close();
OnConnectionStatusChanged(new ConnectionStatusChangedEventArgs(false));
}
serialPort.Dispose();
serialPort = null;
}
gotReadWriteError = true;
}
}
private void HanldeErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
//logger.Error(e.EventType);
}
public Stream Stream
{
get { return this.serialPort.BaseStream; }
}
#endregion
#region Background Tasks
private void ReaderTask()
{
while (IsConnected)
{
int msglen = 0;
//
try
{
msglen = serialPort.BytesToRead;
if (msglen > 0)
{
byte[] message = new byte[msglen];
//
int readbytes = 0;
while (serialPort.Read(message, readbytes, msglen - readbytes) <= 0)
; // noop
if (MessageReceived != null)
{
OnMessageReceived(new MessageReceivedEventArgs(message));
}
}
else
{
Thread.Sleep(100);
}
}
catch (Exception e)
{
//logger.Error(e);
gotReadWriteError = true;
Thread.Sleep(1000);
}
}
}
private void ConnectionWatcherTask()
{
// This task takes care of automatically reconnecting the interface
// when the connection is drop or if an I/O error occurs
while (!disconnectRequested)
{
if (gotReadWriteError)
{
try
{
Close();
// wait 1 sec before reconnecting
Thread.Sleep(1000);
if (!disconnectRequested)
{
try
{
Open();
}
catch (Exception e)
{
//logger.Error(e);
}
}
}
catch (Exception e)
{
//logger.Error(e);
}
}
if (!disconnectRequested)
Thread.Sleep(1000);
}
}
#endregion
#region Events Raising
/// <summary>
/// Raises the connected state changed event.
/// </summary>
/// <param name="args">Arguments.</param>
protected virtual void OnConnectionStatusChanged(ConnectionStatusChangedEventArgs args)
{
//logger.Debug(args.Connected);
if (ConnectionStatusChanged != null)
ConnectionStatusChanged(this, args);
}
/// <summary>
/// Raises the message received event.
/// </summary>
/// <param name="args">Arguments.</param>
protected virtual void OnMessageReceived(MessageReceivedEventArgs args)
{
//logger.Debug(BitConverter.ToString(args.Data));
if (MessageReceived != null)
MessageReceived(this, args);
}
#endregion
#endregion
}
}