-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSerialPortInfo.cs
More file actions
464 lines (435 loc) · 13.8 KB
/
SerialPortInfo.cs
File metadata and controls
464 lines (435 loc) · 13.8 KB
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
namespace SerialPortForward
{
/// <summary>
/// 串口扩展字段
/// </summary>
public class SerialPortInfo : SerialPort
{
System.Windows.Forms.Timer timerCom;
public const string SERIAL_TCP_SERVER = "TCP Server";
public const string SERIAL_TCP_CLIENT = "TCP Client";
public SerialPortInfo() : base()
{
timerCom = new System.Windows.Forms.Timer();
timerCom.Tick += TimerCom_Tick;
}
private void TimerCom_Tick(object sender, EventArgs e)
{
if (!IsOpen)
{
return;
}
try
{
int length = BytesToRead;
if (length == 0)//没数据,退出去
return;
byte[] rev = new byte[length];
Read(rev, 0, length);//读数据
if (rev.Length == 0)
return;
DataReceived?.Invoke(this, rev);
}
catch (Exception)
{
return;
}//崩了?
}
/// <summary>
/// 轮询查询时间间隔
/// </summary>
public int Timer { get; set; } = 0;
/// <summary>
/// 分包合并
/// </summary>
public int TimeOut { get; set; } = 30;
/// <summary>
/// IP地址
/// </summary>
public IPAddress IP { get; set; } = new IPAddress(0);
/// <summary>
/// 是否是网络串口
/// </summary>
public bool IsNetWork { get { return PortName == SERIAL_TCP_SERVER || PortName == SERIAL_TCP_CLIENT; } }
bool _IsOpen = false;
/// <summary>
/// 串口打开(连接)状态
/// </summary>
new public bool IsOpen
{
get
{
if (IsNetWork)
{
return _IsOpen;
}
return base.IsOpen;
}
}
/// <summary>
/// 端口
/// </summary>
public int Port { get; set; } = 8866;
bool _CloseIng = false;
/// <summary>
/// 串口正在关闭
/// </summary>
public bool CloseIng { get { return _CloseIng; } }
/// <summary>
/// 接收数据中
/// </summary>
public bool Listening { get; set; } = false;
//收到消息的事件
new public event EventHandler<byte[]> DataReceived;
private TcpListener Server = null;
private List<Socket> Clients = new List<Socket>();
//暂存一个对象
SocketObj socketNow = null;
/// <summary>
/// 打开串口
/// </summary>
/// <exception cref="Exception"></exception>
public new void Open()
{
if (PortName == SERIAL_TCP_SERVER)
{
if (Server != null)
{
throw new Exception("已经打开了TCP Server");
}
try
{
Server = new TcpListener(IP, Port);
Server.Start();
}
catch (Exception ex)
{
Server = null;
throw ex;
}
AsyncCallback newConnectionCb = null;
newConnectionCb = new AsyncCallback((ar) =>
{
TcpListener listener = (TcpListener)ar.AsyncState;
try
{
Socket client = listener.EndAcceptSocket(ar);//必须有这一句,不然新的请求没反应
lock (Clients)
Clients.Add(client);//加到列表里
//客户端数据接收回调
StateObject so = new StateObject();
so.workSocket = client;
client.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(Read_Callback), so);
//恢复服务端的回调函数,方便下次接收
Server.BeginAcceptSocket(newConnectionCb, Server);
}
catch { }
});
Server.BeginAcceptSocket(newConnectionCb, Server);
_IsOpen = true;
}
else if (PortName == SERIAL_TCP_CLIENT)
{
IPEndPoint ipe = new IPEndPoint(IP, Port);
Socket s = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
StateObject so = new StateObject();
try
{
s.Connect(ipe);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
so.workSocket = s;
if (!so.isSSL)
{
socketNow = new SocketObj(s);
}
s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(Read_Callback), so);
_IsOpen = true;
//s.BeginConnect(ipe, new AsyncCallback((r) =>
//{
// var state = (Socket)r.AsyncState;
// if (!state.Connected)
// {
// _IsOpen = false;
// return;
// }
// if (!so.isSSL)
// socketNow = new SocketObj(state);
// _IsOpen = true;
// so.workSocket = state;
// state.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(Read_Callback), so);
//}), s);
}
else
{
base.DataReceived -= SerialPortInfo_DataReceived;
if (Timer > 0)
{
timerCom.Interval = Timer;
timerCom.Enabled = true;
}
else
{
base.DataReceived += SerialPortInfo_DataReceived;
}
base.Open();
}
}
/// <summary>
/// 关闭串口,如果正在读取数据,则等待读取完毕后关闭
/// </summary>
public new void Close()
{
if (PortName == SERIAL_TCP_SERVER)
{
lock (Clients)
{
foreach (var c in Clients)
try
{
c.Close();
c.Dispose();
}
catch { }
Clients.Clear();
}
Server?.Stop();
Server = null;
_IsOpen = false;
}
else if (PortName == SERIAL_TCP_CLIENT)
{
if (socketNow != null)
{
socketNow.Close();
socketNow = null;
}
_IsOpen = false;
}
else
{
if (timerCom != null)
{
timerCom.Enabled = false;
}
_CloseIng = true;
while (Listening)
{
Thread.Sleep(10);
Application.DoEvents();
}
//打开时点击,则关闭串口
base.Close();
_CloseIng = false;
}
}
/// <summary>
/// 原生串口收到数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SerialPortInfo_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (CloseIng) { return; }
try
{
Listening = true;
//分包写法
List<byte> result = new List<byte>();
while (true)//循环读
{
if (CloseIng || !IsOpen)//串口被关了,不读了
{
break;
}
try
{
int length = BytesToRead;
if (length == 0)//没数据,退出去
break;
byte[] rev = new byte[length];
Read(rev, 0, length);//读数据
if (rev.Length == 0)
break;
result.AddRange(rev);//加到list末尾
if (result.Count > 1024)
{
break;
}
}
catch (Exception)
{
break;
}//崩了?
if (TimeOut > 0)
{
Thread.Sleep(TimeOut);
}
}
if (result.Count == 0)
{
return;
}
byte[] byteRead = result.ToArray();
DataReceived?.Invoke(this, byteRead);
}
finally
{
Listening = false;
}
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
public new void Write(byte[] buffer, int offset, int count)
{
if (PortName == SERIAL_TCP_SERVER)
{
lock (Clients)
{
foreach (var item in Clients)
{
try
{
item.Send(buffer, offset, count, SocketFlags.None);
}
catch { }
}
}
}
else if (PortName == SERIAL_TCP_CLIENT)
{
if (socketNow != null)
{
socketNow.Send(buffer);
}
}
else
{
base.Write(buffer, offset, count);
}
}
public void Read_Callback(IAsyncResult ar)
{
StateObject so = (StateObject)ar.AsyncState;
if (so.isSSL)//ssl连接
{
var ssl = so.workStream;
try
{
int read = ssl.EndRead(ar);
if (read > 0)
{
var buff = new byte[read];
for (int i = 0; i < buff.Length; i++)
buff[i] = so.buffer[i];
DataReceived?.Invoke(null, buff);
ssl.BeginRead(so.buffer, 0, StateObject.BUFFER_SIZE,
new AsyncCallback(Read_Callback), so);
}
else//断了?
{
try
{
ssl.Close();
ssl.Dispose();
}
catch { }
socketNow = null;
_IsOpen = false;
}
}
catch { }
return;
}
Socket s = so.workSocket;
try
{
int read = s.EndReceive(ar);
if (read > 0)
{
var buff = new byte[read];
for (int i = 0; i < buff.Length; i++)
buff[i] = so.buffer[i];
DataReceived?.Invoke(null, buff);
s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0,
new AsyncCallback(Read_Callback), so);
}
else//断了?
{
try
{
s.Close();
s.Dispose();
}
catch { }
socketNow = null;
_IsOpen = false;
}
}
catch { }
}
}
public class StateObject
{
public Socket workSocket = null;
public SslStream workStream = null;
public const int BUFFER_SIZE = 204800;
public byte[] buffer = new byte[BUFFER_SIZE];
public bool isSSL = false;
}
public class SocketObj
{
Socket socket;
SslStream sslStream;
public SocketObj(Socket s)
{
socket = s;
}
public SocketObj(SslStream ssl)
{
sslStream = ssl;
}
public void Send(byte[] buff)
{
if (socket != null)
socket.Send(buff);
else if (sslStream != null)
{
sslStream.Write(buff);
}
}
public void Close()
{
if (socket != null)
{
socket.Close();
socket.Dispose();
}
else if (sslStream != null)
{
sslStream.Close();
sslStream.Dispose();
}
}
}
}