-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUart.cs
334 lines (316 loc) · 10.6 KB
/
Uart.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
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Common
{
public class Uart
{
/// <summary>
/// 解析数据包类
/// </summary>
public class ParseData
{
public enum ParseDataResult
{
Result_None,
Result_OK,
Result_Error,
}
public ParseDataResult Result { set; get; }
public int Data1 { set; get; }
public int Data2 { set; get; }
public int Data3 { set; get; }
public int Data4 { set; get; }
public int Data5 { set; get; }
public int Data6 { set; get; }
public List<byte> Pack { set; get; }
public string PackHexString { set; get; }
public ParseData()
{
Result = ParseDataResult.Result_None;
}
/// <summary>
/// 解析数据包 请在子类重写
/// </summary>
/// <param name="item">解析一个字节</param>
public virtual void ParseDataByByte(byte item)
{
}
}
/// <summary>
/// 设置解析对象
/// </summary>
public ParseData ParseDataObj {set;get;}
public event Action<ParseData> ReceivedDataPack; //声明收到数包事件
public event Action<byte[]> ReceivedBytes;
public event Action<byte[]> SendBytesEvent;
private System.Timers.Timer timer_1s = new System.Timers.Timer(1000);
private System.Timers.Timer timerf_30ms = new System.Timers.Timer();
private SerialPort serialPort1 = new System.IO.Ports.SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
// 接收、发送计数
public int TxCount { set; get; }
public int RxCount { set; get; }
// 错误、好的数据包计数,接收包频率
public int ErrorPackCount { set; get; }
public int GoodPackCount { set; get; }
//获取所有的串口名字
public string[] FindSerialPortName
{
get
{
if(SerialPort.GetPortNames().Length > 0)
{
return SerialPort.GetPortNames();
}
else
{
return new string[] { "port not found" };
}
}
}
public bool SerialPortIsOpen { get { return serialPort1.IsOpen; } } //串口是否打开
// 接收包频率,接收速率
public int PackFrequency { set; get; }
public int ReceivingRate { set; get; }
private int packFreqCount = 0;
private int recRate = 0;
private UartConfig config;
private Form OwnerForm;
private Thread thread1;
public Uart()
{
ParseDataObj = null;
OwnerForm = null;
timer_1s.Interval = 1000;
timer_1s.Elapsed += Timer_1s_Elapsed;
timer_1s.AutoReset = true;
timer_1s.Enabled = true;
//timerf_30ms.Interval = 30;
//timerf_30ms.Elapsed += Timerf_30ms_Tick;
//timerf_30ms.AutoReset = true;
//timerf_30ms.Enabled = true;
}
public Uart(Form OwnerForm)
{
ParseDataObj = null;
this.OwnerForm = OwnerForm;
timer_1s.Interval = 1000;
timer_1s.Elapsed += Timer_1s_Elapsed;
timer_1s.AutoReset = true;
timer_1s.Enabled = true;
//timerf_30ms.Interval = 30;
//timerf_30ms.Elapsed += Timerf_30ms_Tick;
//timerf_30ms.AutoReset = true;
//timerf_30ms.Enabled = true;
}
/// <summary>
/// Uart config form
/// </summary>
public void UartConfigByGUI()
{
if(config == null || config.IsDisposed == true)
{
config = new UartConfig(serialPort1);
if(OwnerForm != null)
{
config.Owner = this.OwnerForm;
}
}
config.ShowDialog();
}
/// <summary>
/// Uart config
/// </summary>
public void UartConfig(string portName = "COM1",Int32 baudRate = 9600,Int32 dataBits = 8,Parity parity = Parity.None,StopBits stopBits = StopBits.One)
{
serialPort1.BaudRate = baudRate;
serialPort1.PortName = portName;
serialPort1.DataBits = dataBits;
serialPort1.Parity = parity;
serialPort1.StopBits = stopBits;
}
/// <summary>
/// 打开或者关闭串口
/// </summary>
/// <param name="portName">COM 号 如果打开出错返回出错消息</param>
/// <returns>true ok false fail</returns>
public bool OpenOrClosePort(ref string portName)
{
if(serialPort1.IsOpen == true)
{
serialPort1.Close();
return false;
}
else
{
if(portName != "") { serialPort1.PortName = portName; }
try {
serialPort1.Open();
SttartReceivedThread();
}
catch(Exception ex)
{
portName = ex.Message;
StopReceivedThread();
return false;// throw;
}
}
return true;
}
/// <summary>
/// 打开串口
/// </summary>
/// <param name="portName">COM 号</param>
/// <returns></returns>
public bool OpenPort(ref string portName)
{
if(serialPort1.IsOpen == true) return true;
serialPort1.PortName = portName;
try {
serialPort1.Open();
SttartReceivedThread();
}
catch(Exception ex)
{
portName = ex.Message;
StopReceivedThread();
return false;// throw;
}
return true;
}
public void SendBytes(byte[] data)
{
if(SerialPortIsOpen)
{
if(data.Length > 0)
{
serialPort1.Write(data, 0, data.Length);
TxCount += data.Length;
if(SendBytesEvent != null)
{
if(this.OwnerForm != null)
{
this.OwnerForm.BeginInvoke(SendBytesEvent,data);
}
else
{
SendBytesEvent(data);
}
}
}
}
}
/// <summary>
/// 关闭串口
/// </summary>
public void Dispose()
{
if(serialPort1.IsOpen == true)
{
serialPort1.Close();
StopReceivedThread();
}
}
/// <summary>
/// 关闭串口
/// </summary>
public void ClosePort()
{
if(serialPort1.IsOpen == true)
{
serialPort1.Close();
StopReceivedThread();
}
}
private void SttartReceivedThread()
{
thread1 = new Thread(new ThreadStart(UsartDataReceivedThead));
thread1.IsBackground = true;
thread1.Name = "UsartDataReceivedThead";
thread1.Start();
}
private void StopReceivedThread()
{
}
/**/
private void Timerf_30ms_Tick(object sender, EventArgs e)
{
// 使用Windows.Forms.Timer 定时器来定时接收数据,更新UI时更流畅
if(serialPort1.IsOpen == true)
SerialPort1DataReceived();
}
private void UsartDataReceivedThead()
{
while(serialPort1.IsOpen)
{
//System.Threading.Thread.Sleep(30);
// 用不着此线程
SerialPort1DataReceived();
}
}
private void Timer_1s_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if(serialPort1.IsOpen == true)
{
PackFrequency = packFreqCount;
packFreqCount = 0;
ReceivingRate = recRate;
recRate = 0;
}
}
private void ReceivingPackets(byte[] buffer)
{
/* 判断是否有解析对象 */
if(ParseDataObj != null)
{
foreach(byte item in buffer)
{
ParseDataObj.ParseDataByByte(item);
if(ParseDataObj.Result != ParseData.ParseDataResult.Result_None)
{
packFreqCount++;
if(ParseDataObj.Result == ParseData.ParseDataResult.Result_OK) GoodPackCount++; /* 数据包校验正确 */
else if(ParseDataObj.Result == ParseData.ParseDataResult.Result_Error) ErrorPackCount++; /* 数据包校验错误 */
if(ReceivedDataPack != null)
{
if(this.OwnerForm != null)
{
this.OwnerForm.BeginInvoke(ReceivedDataPack, ParseDataObj);
}
else
{
ReceivedDataPack(ParseDataObj);
}
}
}
}
}
if(ReceivedBytes != null)
{
if(this.OwnerForm != null)
{
this.OwnerForm.BeginInvoke(ReceivedBytes, buffer);
}
else
{
ReceivedBytes(buffer);
}
}
}
private void SerialPort1DataReceived()
{
SerialPort sp = serialPort1;
int n = sp.BytesToRead; //读取缓存里的字节数
if(n <= 0) return; //没有数据退出 //收到0x1A时 还有数据 但n=0 不知怎么回事
byte[] re_buf = new byte[n];
sp.Read(re_buf, 0, n); //读取缓冲数据
RxCount += n;
recRate += n;
ReceivingPackets(re_buf); // 接收解析数据包
}
}
}