ReadAll.cs
20.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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Asa.RFID
{
/// <summary>
/// 读取所有RFID
/// </summary>
public class ReadAll
{
private readonly log4net.ILog log;
private readonly ReadMode readMode;
private List<Device> rfidDev;
//client mode
private Socket serverUpper; //上位机的服务端
private bool serverUpperLoop; //上位机服务监控
private Thread listenClientUpper; //上位机监听客户端连接线程
private List<Client> clientListLower; //下位机的客户端列表
private readonly Dictionary<DeviceType, DecodeDelegate> decode; //解码
private const int CLIENT_SLEEP = 10;
private const int DATA_LENGTH = 8;
private delegate void DecodeDelegate(Client client, byte[] buff);
public delegate void ReceivedEvent(string ip, string id);
public event ReceivedEvent Received;
//server mode
private bool serverLowerLoop; //下位机服务监控
private Thread connectServerLower; //连接下位机服务器线程
private List<Client> clientListUpper; //上位机的客户端列表
private const int LOWER_SERVER_PORT = 502;
private readonly byte[] FRAME_HEAD = Encoding.ASCII.GetBytes("1234");
private readonly byte[] FRAME_END = new byte[] { 0x0D, 0x0A };
/// <summary>
/// 读取所有RFID,client模式
/// </summary>
/// <param name="logName">日志名称</param>
public ReadAll(string logName = "RFID.ReadAll.Client")
{
readMode = ReadMode.Client;
rfidDev = new();
decode = new()
{
{ DeviceType.PuYue, DecodePuYue },
{ DeviceType.HaoBin, DecodeHaoBin }
};
log = log4net.LogManager.GetLogger(logName);
log.Debug("ReadAll client initialization");
}
/// <summary>
/// 读取所有RFID,server模式
/// </summary>
/// <param name="ip"></param>
/// <param name="logName"></param>
public ReadAll(string[] ip, string logName = "RFID.ReadAll.Server")
{
readMode = ReadMode.Server;
rfidDev = new();
clientListUpper = new();
for (int i = 0; i < ip.Length; i++)
{
rfidDev.Add(new Device(ip[i]));
clientListUpper.Add(new Client(ip[i]));
}
log = log4net.LogManager.GetLogger(logName);
log.Debug("ReadAll server initialization");
}
/// <summary>
/// 服务端开始,client模式
/// </summary>
/// <param name="port">端口号</param>
public void Start(int port)
{
try
{
IPEndPoint localEP = new(IPAddress.Any, port);
serverUpper = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverUpper.Bind(localEP);
serverUpper.Listen(100);
serverUpperLoop = true;
clientListLower = new();
listenClientUpper = new(new ThreadStart(ListenClientUpper));
listenClientUpper.Start();
log.Info($"Server Start({port}) OK");
}
catch (Exception ex)
{
log.Error("Start", ex);
}
}
/// <summary>
/// 客户端开始,server模式
/// </summary>
public void Start()
{
serverLowerLoop = true;
connectServerLower = new(new ThreadStart(ConnectLower));
connectServerLower.Start();
}
/// <summary>
/// 服务端停止
/// </summary>
public void Stop()
{
try
{
serverUpperLoop = false;
serverLowerLoop = false;
if (clientListLower != null)
{
for (int i = 0; i < clientListLower.Count; i++)
ClientClose(clientListLower[i]);
clientListLower = null;
}
if (clientListUpper != null)
{
for (int i = 0; i < clientListUpper.Count; i++)
ClientClose(clientListUpper[i]);
clientListUpper = null;
}
serverUpper.Close();
serverUpper.Dispose();
rfidDev.Clear();
log.Info("Stop OK");
}
catch (Exception ex)
{
log.Error("Stop", ex);
}
}
/// <summary>
/// 读取
/// </summary>
/// <param name="ip">IP地址</param>
/// <param name="defaultID">没有找到时返回</param>
/// <returns></returns>
public string Read(string ip, string defaultID = "000")
{
string text = $"Read({ip}):";
string result = defaultID;
int index = rfidDev.FindIndex(match => match.IP == ip);
if (index == -1)
{
text += $"default {defaultID}, ip没有找到";
}
else
{
if (string.IsNullOrWhiteSpace(rfidDev[index].Value))
{
text += $"default {defaultID}, value为空";
}
else
{
text += rfidDev[index].Value;
result = rfidDev[index].Value;
}
}
log.Info(text);
return result;
}
/// <summary>
/// 读取所有
/// </summary>
/// <param name="defaultID">没有数据时返回</param>
public Dictionary<string, string> Read(string defaultID = "000")
{
Dictionary<string, string> dic = new();
for (int i = 0; i < rfidDev.Count; i++)
{
string value = string.IsNullOrWhiteSpace(rfidDev[i].Value) ? defaultID : rfidDev[i].Value;
dic.Add(rfidDev[i].IP, value);
}
log.Info($"Read All:Count={dic.Count}");
return dic;
}
/// <summary>
/// 清除缓存
/// </summary>
/// <param name="ip">IP地址</param>
/// <param name="defaultID">设置初始ID</param>
public void Clear(string ip, string defaultID = "000")
{
string text = $"Clear({ip}):";
string result = defaultID;
int index = rfidDev.FindIndex(match => match.IP == ip);
if (index == -1)
{
text += "ip没有找到";
}
else
{
rfidDev[index].Value = defaultID;
text += $"Value={defaultID}";
}
log.Info(text);
}
/// <summary>
/// 清除所有缓存
/// </summary>
/// <param name="defaultID">设置初始ID</param>
public void Clear(string defaultID = "000")
{
for (int i = 0; i < rfidDev.Count; i++)
rfidDev[i].Value = defaultID;
log.Info($"Clear All:Count={rfidDev.Count}");
}
#region server mode
private void ConnectLower()
{
int index = 0;
while (serverLowerLoop)
{
Thread.Sleep(CLIENT_SLEEP);
Client client = clientListUpper[index++];
if (index == clientListUpper.Count)
index = 0;
if (client.IsConn) continue;
if (!CheckIP(client.IP))
{
log.Info($"({client.IP})检查失败");
continue;
}
try
{
client.Socket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 1000);
client.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
client.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
client.Socket.Connect(IPAddress.Parse(client.IP), LOWER_SERVER_PORT);
Thread.Sleep(100); //需要等待一会才能获取连接状态
client.Loop = true;
client.IsConn = true;
client.Buffer = new();
client.ListenNet = new Thread(new ParameterizedThreadStart(ListenServerLower));
client.ListenNet.Start();
}
catch (Exception ex)
{
log.Error("Connect", ex);
}
}
}
private void ListenServerLower(object obj)
{
Client client = clientListUpper[(int)obj];
while (client.Loop)
{
Thread.Sleep(10);
try
{
if (client.Socket.Available > 0)
{
byte[] buff = new byte[client.Socket.Available];
int count = client.Socket.Receive(buff);
client.Buffer.AddRange(buff);
DataProcessLower(client);
}
}
catch (Exception ex)
{
log.Error("ListenServerLower", ex);
client.IsConn = false;
client.Loop = false;
}
}
}
private void DataProcessLower(Client client)
{
bool existHead = true;
try
{
for (int i = 0; i < client.Buffer.Count - 4; i++)
{
if (client.Buffer[i] == FRAME_HEAD[0] && client.Buffer[i + 1] == FRAME_HEAD[1] &&
client.Buffer[i + 2] == FRAME_HEAD[2] && client.Buffer[i + 3] == FRAME_HEAD[3])
{
existHead = true;
if (client.Buffer.Count >= 38 + i) //每帧数据,帧头2*2字节+UID8*2字节+数据8*2字节+回车2字节
{
if (client.Buffer[i + 36] == FRAME_END[0] && client.Buffer[i + 37] == FRAME_END[1])
{
string data = Encoding.ASCII.GetString(client.Buffer.ToArray(), i + 20, 16);
string ID = data;
if (data.Length > 6)
ID = (char)Convert.ToInt32(data.Substring(2, 2), 16) + Convert.ToInt32(data.Substring(4, 2), 16).ToString();
log.Debug($"({client.IP})的数据ID={ID}");
int index = rfidDev.FindIndex(match => match.IP == client.IP);
if (index > -1)
rfidDev[index].Value = ID;
}
else
{
log.Debug($"({client.IP})的数据包解析错误");
}
client.Buffer.RemoveRange(0, i + 38);
i = 0;
}
else
{
break; //包还没有接收完整
}
}
else
{
existHead = false;
}
}
if (!existHead)
client.Buffer.Clear();
}
catch (Exception ex)
{
log.Error("DataProcessLower", ex);
}
}
#endregion
#region client mode
/// <summary>
/// 设备类型
/// </summary>
public DeviceType Type { set; get; } = DeviceType.PuYue;
private void ClientClose(Client client)
{
try
{
client.Loop = false;
client.IsConn = false;
client.Socket.Close();
client.Socket.Dispose();
log.Info($"关闭 ({client.IP})");
}
catch (Exception ex)
{
log.Error("ClientClose", ex);
}
}
private void ListenClientUpper()
{
while (serverUpperLoop)
{
try
{
Socket socket = serverUpper.Accept(); //这边会暂停,不需要sleep
IPEndPoint ep = (IPEndPoint)socket.RemoteEndPoint;
Thread listen = new(new ParameterizedThreadStart(ListenClientUpperNet));
string ip = ep.Address.ToString();
//新的客户端
Client client = new(ip, socket, listen);
int index = rfidDev.FindIndex(match => match.IP == ip);
//重连后删除旧连接
int idx = clientListLower.FindIndex(ls => ls.IP.Equals(ip));
if (idx > -1)
{
if (index > -1) rfidDev[index].Value = "";
clientListLower[idx].IsConn = false;
clientListLower[idx].Loop = false;
clientListLower[idx].Socket.Close();
log.Info($"重连({ip}),删除重复");
clientListLower.RemoveAt(idx);
}
//添加到数组
if (index == -1) rfidDev.Add(new Device(client.IP));
clientListLower.Add(client);
log.Info($"({ip})连接服务端");
listen.Start(clientListLower.Count - 1);
}
catch (SocketException)
{
//关闭连接,退出阻塞Accept
log.Info("Socket Close");
}
catch (Exception ex)
{
log.Error("ListenClient", ex);
}
}
}
private void ListenClientUpperNet(object obj)
{
Client client = clientListLower[(int)obj];
while (client.Loop)
{
Thread.Sleep(CLIENT_SLEEP);
try
{
if (!client.Loop) break;
int count = client.Socket.Available;
if (count > 0)
{
byte[] buff = new byte[count];
client.Socket.Receive(buff);
decode[Type].Invoke(client, buff);
}
}
catch (Exception ex)
{
string s = string.Format("ListenNet: {0}", client.IP);
log.Error(s, ex);
}
}
}
private void DecodeHaoBin(Client client, byte[] buff)
{
client.Buffer.AddRange(buff);
string s = string.Format("Net Receive({0}): {1}", client.IP, HexBuff(buff));
log.Debug(s);
while (client.Loop)
{
if (client.Buffer.Count == 0) break;
//查找包头
int idx = client.Buffer.FindIndex(n => n == 0x5A);
if (idx == -1)
{
s = string.Format("[{0}]没有找到包头5A,清除缓存,{1}", client.IP, HexBuff(client.Buffer));
log.Debug(s);
client.Buffer.Clear();
break;
}
//长度不够,半个包
//该设备会自带0,每块数据之间插入一个0,1块数据为4个字节
//这里只读2块数据,中间插入一个0
int len = idx + DATA_LENGTH + 1;
if (len > client.Buffer.Count) break;
//查找包尾
if (client.Buffer[len - 3] == 0x4A) //最后两个校验位
{
byte[] arr = new byte[DATA_LENGTH];
client.Buffer.CopyTo(idx, arr, 0, 4);
client.Buffer.CopyTo(idx + 5, arr, 4, 4);
client.Buffer.RemoveRange(0, len);
TriggerEvent(client.IP, arr);
}
else
{
s = string.Format("[{0}]没有找到包尾4A,{1}", client.IP, HexBuff(client.Buffer));
log.Debug(s);
client.Buffer.RemoveRange(0, idx + 1);
}
}
}
private void DecodePuYue(Client client, byte[] buff)
{
string s;
string hex = Encoding.ASCII.GetString(buff);
hex = hex.Replace("\r", "");
hex = hex.Replace("\n", "");
buff = new byte[hex.Length / 2];
for (int i = 0; i < buff.Length; i++)
buff[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
client.Buffer.AddRange(buff);
s = string.Format("Net Receive({0}): {1}", client.IP, HexBuff(buff));
log.Debug(s);
while (client.Loop)
{
if (client.Buffer.Count == 0) break;
//查找包头
int idx = client.Buffer.FindIndex(n => n == 0x5A);
if (idx == -1)
{
s = string.Format("[{0}]没有找到包头5A,清除缓存,{1}", client.IP, HexBuff(client.Buffer));
log.Debug(s);
client.Buffer.Clear();
break;
}
//长度不够,半个包
int len = idx + DATA_LENGTH;
if (len > client.Buffer.Count) break;
//查找包尾
if (client.Buffer[len - 3] == 0x4A) //最后两个校验位
{
byte[] arr = new byte[DATA_LENGTH];
client.Buffer.CopyTo(idx, arr, 0, DATA_LENGTH);
client.Buffer.RemoveRange(0, len);
TriggerEvent(client.IP, arr);
}
else
{
s = string.Format("[{0}]没有找到包尾4A,{1}", client.IP, HexBuff(client.Buffer));
log.Debug(s);
client.Buffer.RemoveRange(0, idx + 1);
}
}
}
private void TriggerEvent(string ip, byte[] buff)
{
string s = "";
if (buff[1] >= 65 && buff[1] <= 90) //在A-Z范围
s = (char)buff[1] + buff[2].ToString();
log.Debug($"TriggerEvent({ip}):value={s}");
int index = rfidDev.FindIndex(match => match.IP == ip);
if (index > -1)
{
if (rfidDev[index].Value == s)
{
log.Debug($"TriggerEvent({ip}):value相同不触发");
}
else
{
rfidDev[index].Value = s;
log.Info($"TriggerEvent({ip}):{s},触发事件");
Task.Run(() => Received?.Invoke(ip, s));
}
}
}
#endregion
private string HexBuff(byte[] buff)
{
string s = "";
if (buff == null) return s;
for (int i = 0; i < buff.Length; i++)
s += buff[i].ToString("X2") + " ";
return s;
}
private string HexBuff(List<byte> buff)
{
string s = "";
if (buff == null) return s;
for (int i = 0; i < buff.Count; i++)
s += buff[i].ToString("X2") + " ";
return s;
}
private bool CheckIP(string ip)
{
try
{
string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
bool rtn = System.Text.RegularExpressions.Regex.IsMatch(ip, pattern);
if (rtn)
{
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply result = ping.Send(ip, 1000);
ping.Dispose();
rtn = result.Status == System.Net.NetworkInformation.IPStatus.Success;
}
return rtn;
}
catch (Exception ex)
{
log.Error("CheckIP", ex);
return false;
}
}
}
}