PuYue.cs
19.0 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Asa.RFID
{
/// <summary>
/// HiStation RFID
/// </summary>
public class PuYue
{
private Thread tListen; //监听网络
private Socket _client; //客户端
private bool _loop; //循环
private short _mark; //事务处理标识
private bool _dataMode = true; //自动发送数据模式
private bool _conOnce;
private bool _total; //完整的
private List<byte> _fullCmd;
private List<byte> _receive;
private readonly byte[] FRAME_HEAD = Encoding.ASCII.GetBytes("1234");
private readonly byte[] FRAME_END = new byte[] { 0x0D, 0x0A };
/// <summary>
/// 连接事件
/// </summary>
public delegate void Connected_Event(string ip);
/// <summary>
/// 已连接时触发
/// </summary>
public event Connected_Event Connected;
/// <summary>
/// 接收事件
/// </summary>
/// <param name="ip"></param>
/// <param name="uid"></param>
/// <param name="data"></param>
public delegate void Received_Event(string ip, string uid, string data);
/// <summary>
/// 接收到数据事件
/// </summary>
public event Received_Event Received;
/// <summary>
/// HiStation RFID
/// </summary>
/// <param name="logName">日志名称</param>
public PuYue(string logName = "HiStation")
{
_mark = 0;
_conOnce = true;
_receive = new List<byte>();
//if (Common.log == null)
// Common.log = log4net.LogManager.GetLogger(logName);
//Common.log.Info("=====Init=====");
}
/// <summary>
/// IP地址
/// </summary>
public string IP { set; get; } = "192.168.1.7";
/// <summary>
/// 是否连接
/// </summary>
public bool IsConn { get; private set; } = false;
/// <summary>
/// 打开设备
/// </summary>
public void Open()
{
//_loop = true;
//IsConn = false;
//tRecon = new Thread(new ThreadStart(Reconn)) { Name = "Reconnect" };
//tListen = new Thread(new ThreadStart(Listen)) { Name = "Listen" };
//tRecon.Start();
//tListen.Start();
//Common.log.Info(string.Format("Open[{0}] OK", IP));
IsConn = Connect();
if (IsConn)
{
_loop = true;
tListen = new Thread(new ThreadStart(Listen)) { Name = "Listen" };
tListen.Start();
}
//Common.log.Info(string.Format("Open[{0}] {1}", IP, IsConn));
}
/// <summary>
/// 关闭设备
/// </summary>
public void Close()
{
_loop = false;
IsConn = false;
try
{
if (_client != null)
{
//TriggerMode(false);
//Thread.Sleep(50);
_client.Shutdown(SocketShutdown.Both);
_client.Close();
}
//Common.log.Info(string.Format("Close[{0}] OK", IP));
}
catch (Exception ex)
{
//Common.log.Error(string.Format("Close[{0}] ERROR", IP), ex);
}
finally
{
_client = null;
}
}
/// <summary>
/// 初始化(用于修改硬件参数,不用每次调用)
/// </summary>
public void Init()
{
_dataMode = false;
//设备地址1,波特率,禁止AFI,盘点超时时间(100*5ms),命令触发,操作模式,寄存器地址,寄存器数量,触发时间(10*5ms),输出格式,数据帧枕头,记录保持时间(9*5ms)
short[] address = new short[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
short[] value = new short[] { 1, 2, 0, 100, 1, 1, 0x20, 4, 20, 1, 0x1234, 19 };
for (int i = 0; i < address.Length; i++)
{
Write(address[i], value[i]);
bool rtn = Wait();
if (!rtn) break;
}
}
/// <summary>
/// 触发模式
/// </summary>
/// <param name="auto"></param>
public void TriggerMode(bool auto)
{
_dataMode = false;
Write(4, (short)(auto ? 0 : 1));
if (Wait())
_dataMode = auto;
}
public bool GetAutoMode()
{
_dataMode = false;
bool rtn = false;
Read(4, 1);
if (Wait())
{
byte n = _fullCmd[_fullCmd.Count - 1];
rtn = n == 0;
_dataMode = rtn;
}
return rtn;
}
public bool ReadData(out string value)
{
_dataMode = false;
bool rtn = false;
value = "";
Read(0x20, 4);
if (Wait())
{
if (_fullCmd[7] == 0x03)
{
value = (char)_fullCmd[10] + _fullCmd[11].ToString();
rtn = true;
}
else
{
//Common.log.Info("0x03功能码不匹配");
}
}
return rtn;
}
public bool WriteData(string id)
{
_dataMode = false;
bool rtn = false;
Write(id);
if (Wait())
{
if (_fullCmd[7] == 0x10)
rtn = true;
//else
// Common.log.Info("0x10功能码不匹配");
}
return rtn;
}
/// <summary>
/// 监听网络
/// </summary>
private void Listen()
{
while (_loop)
{
Thread.Sleep(10);
if (!IsConn) continue;
if (_client == null) continue;
try
{
if (_client.Available > 0)
{
byte[] buff = new byte[_client.ReceiveBufferSize];
int count = _client.Receive(buff);
byte[] temp = new byte[count];
Array.Copy(buff, 0, temp, 0, count);
//Common.log.Debug("Receive[" + IP + "]: " + HexBuff(temp));
_receive.AddRange(temp);
while (_receive.Count > 6)
{
if (!IsConn) break;
if (_dataMode)
DataProcess();
else
CmdProcess();
}
}
}
catch (Exception ex)
{
//Common.log.Error(string.Format("Listen[{0}] ERROR", IP), ex);
IsConn = false;
}
}
}
/// <summary>
/// 数据处理
/// </summary>
private void DataProcess()
{
try
{
for (int i = 0; i < _receive.Count - 4; i++)
{
if (_receive[i] == FRAME_HEAD[0] && _receive[i + 1] == FRAME_HEAD[1] &&
_receive[i + 2] == FRAME_HEAD[2] && _receive[i + 3] == FRAME_HEAD[3])
{
if (_receive.Count >= 38 + i) //每帧数据,帧头2*2字节+UID8*2字节+数据8*2字节+回车2字节
{
if (_receive[i + 36] == FRAME_END[0] && _receive[i + 37] == FRAME_END[1])
{
string uid = Encoding.ASCII.GetString(_receive.ToArray(), i + 4, 16);
string data = Encoding.ASCII.GetString(_receive.ToArray(), i + 20, 16);
//Common.log.Debug(string.Format("解析完成[{0}] uid={1} data={2}", IP, uid, data));
string ID;
if (data.Length > 6)
ID = (char)Convert.ToInt32(data.Substring(2, 2), 16) + Convert.ToInt32(data.Substring(4, 2), 16).ToString();
else
ID = data;
Received?.Invoke(IP, uid, ID);
}
else
{
//Common.log.Error(string.Format("解析错误[{0}]", IP));
}
_receive.RemoveRange(0, i + 38);
}
else
{
break;
}
}
}
}
catch (Exception ex)
{
//Common.log.Error(string.Format("DataProcess[{0}] ERROR", IP), ex);
}
}
/// <summary>
/// 命令处理
/// </summary>
private void CmdProcess()
{
try
{
int len = 0;
byte[] temp = BitConverter.GetBytes(_mark); //事务处理标识
for (int i = 0; i < _receive.Count - 2; i++)
{
if (_receive[i] == temp[1] && _receive[i + 1] == temp[0])
{
len = 6 + i;
if (_receive.Count >= len)
{
len += _receive[i + 5];
if (_receive.Count >= len)
{
_fullCmd = _receive.GetRange(0, len);
_receive.RemoveRange(0, len);
_total = true;
}
else
{
break;
}
}
else
{
break;
}
}
}
}
catch (Exception ex)
{
//Common.log.Error(string.Format("CmdProcess[{0}] ERROR", IP), ex);
}
}
/// <summary>
/// 重连
/// </summary>
private void Reconn()
{
while (_loop)
{
if (IsConn)
{
if (!_conOnce)
{
Connected?.Invoke(IP);
_conOnce = true;
}
}
else
{
if (_conOnce)
{
Connected?.Invoke(IP);
_conOnce = false;
}
Thread.Sleep(500);
if (!_loop) break;
IsConn = Connect();
}
Thread.Sleep(1000);
}
}
/// <summary>
/// 建立Socket连接
/// </summary>
/// <returns></returns>
private bool Connect()
{
bool rtn;
try
{
rtn = CheckIP(IP);
if (rtn)
{
//建立连接
_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 1000);
_client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
_client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
_client.Connect(System.Net.IPAddress.Parse(IP), 502);
Thread.Sleep(100); //需要等待一会才能获取连接状态
//Common.log.Info("Socket[" + IP + "] Connected");
}
}
catch (Exception ex)
{
rtn = false;
//Common.log.Error(string.Format("Connect[{0}] ERROR", IP), ex);
}
return rtn;
}
/// <summary>
/// 检查IP
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
private bool CheckIP(string ip)
{
//IP合法
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)
{
//Common.log.Info(string.Format("非法的IP地址[{0}]", IP));
return false;
}
//Ping服务端
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply result = ping.Send(ip, 1000);
ping.Dispose();
if (result.Status != System.Net.NetworkInformation.IPStatus.Success)
{
//Common.log.Info(string.Format("Ping[{0}]请求没有响应", IP));
return false;
}
return true;
}
/// <summary>
/// 16进制转换
/// </summary>
/// <param name="buff"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 读取保持寄存器,0x03功能码
/// </summary>
/// <param name="address"></param>
/// <param name="count"></param>
private void Read(short address, short count)
{
if (!IsConn) return;
byte[] temp;
byte[] buffer = new byte[12];
GetMark();
temp = BitConverter.GetBytes(_mark); //事务处理标识
buffer[0] = temp[1]; //高位
buffer[1] = temp[0]; //低位
buffer[2] = 0;
buffer[3] = 0; //协议标识
buffer[4] = 0;
buffer[5] = 0x06; //后面字节数
buffer[6] = 0xFF; //主设备
buffer[7] = 0x03; //功能码
temp = BitConverter.GetBytes(address); //寄存器起始地址
buffer[8] = temp[1]; //高位
buffer[9] = temp[0]; //低位
temp = BitConverter.GetBytes(count); //寄存器个数
buffer[10] = temp[1]; //高位
buffer[11] = temp[0]; //低位
try
{
_total = false;
//Common.log.Debug("Read[" + IP + "] " + HexBuff(buffer));
if (_client != null)
_client.Send(buffer);
}
catch (Exception ex)
{
IsConn = false;
//Common.log.Error(string.Format("Read[{0}] ERROR", IP), ex);
}
}
/// <summary>
/// 写入保持寄存器,0x10功能码
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
private void Write(short address, short value)
{
if (!IsConn) return;
byte[] temp;
byte[] buffer = new byte[15];
GetMark();
temp = BitConverter.GetBytes(_mark); //事务处理标识
buffer[0] = temp[1]; //高位
buffer[1] = temp[0]; //低位
buffer[2] = 0;
buffer[3] = 0; //协议标识
buffer[4] = 0;
buffer[5] = 0x09; //后面字节数
buffer[6] = 0xFF; //主设备
buffer[7] = 0x10; //功能码
temp = BitConverter.GetBytes(address); //寄存器起始地址
buffer[8] = temp[1]; //高位
buffer[9] = temp[0]; //低位
buffer[10] = 0;
buffer[11] = 1; //寄存器个数
buffer[12] = 2; //数据长度
temp = BitConverter.GetBytes(value); //寄存器个数
buffer[13] = temp[1]; //高位
buffer[14] = temp[0]; //低位
try
{
_total = false;
//Common.log.Debug("Write[" + IP + "] " + HexBuff(buffer));
if (_client != null)
_client.Send(buffer);
}
catch (Exception ex)
{
IsConn = false;
//Common.log.Error(string.Format("Write[{0}] ERROR", IP), ex);
}
}
private void Write(string value)
{
if (!IsConn) return;
byte[] temp;
byte[] buffer = new byte[21];
GetMark();
temp = BitConverter.GetBytes(_mark); //事务处理标识
buffer[0] = temp[1]; //高位
buffer[1] = temp[0]; //低位
buffer[2] = 0;
buffer[3] = 0; //协议标识
buffer[4] = 0;
buffer[5] = 15; //后面字节数
buffer[6] = 0xFF; //主设备
buffer[7] = 0x10; //功能码
buffer[8] = 0;
buffer[9] = 0x20; //地址
buffer[10] = 0;
buffer[11] = 4; //寄存器个数
buffer[12] = 8; //数据长度
buffer[13] = 0x5A;
buffer[14] = (byte)value[0];
buffer[15] = Convert.ToByte(value.Substring(1));
buffer[16] = 0;
buffer[17] = 0;
buffer[18] = 0x4A;
buffer[19] = 0;
buffer[20] = 0;
try
{
_total = false;
//Common.log.Debug("Write[" + IP + "] " + HexBuff(buffer));
if (_client != null)
_client.Send(buffer);
}
catch (Exception ex)
{
IsConn = false;
//Common.log.Error(string.Format("Write[{0}] ERROR", IP), ex);
}
}
private void GetMark()
{
if (_mark == short.MaxValue)
_mark = 1;
else
_mark++;
}
private bool Wait()
{
bool result = true;
int count = 0;
do
{
Thread.Sleep(5);
count += 5;
if (count == 2000)
{
result = false;
break;
}
}
while (!_total);
return result;
}
}
}