PuYueRFID_C2S.cs
15.1 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class PuYueRFID_C2S
{
byte station = 1;
bool Automode;
public string IP;
TcpClient tcpClient = new TcpClient();
Thread iomonitorThread;
ushort seq = 0;
public event EventHandler<string> ID_Changed_Event;
/// <summary>
/// 连接状态变化, 手动连接不触发
/// </summary>
public event EventHandler<bool> ConnectionState_Event;
public PuYueRFID_C2S(string ip, bool automode = false)
{
this.IP = ip;
Automode = automode;
//DOdata[0] = 0x00;
//DOdata[1] = 0x00;
//if (autoread)
// iomonitorThread = new Thread(new ThreadStart(iomonitor));
}
/// <summary>
/// 销毁
/// </summary>
~PuYueRFID_C2S()
{
iomonitorrun = false;
Close();
}
bool systemrun = false;
/// <summary>
/// 打开IO
/// </summary>
/// <returns></returns>
public bool Open()
{
tcpClient.Dispose();
tcpClient = new TcpClient();
tcpClient.ReceiveTimeout = 1000;
tcpClient.SendTimeout = 100;
lock (tcpClient)
{
try
{
var connectResult = tcpClient.ConnectAsync(IP, 502);
if (connectResult.Wait(1000))
{
Init();
systemrun = true;
if (Automode)
{
iomonitorrun = true;
iomonitorThread = new Thread(new ThreadStart(iomonitor));
iomonitorThread.Start();
}
ConnectionState_Event?.Invoke(this, true);
return true;
}
else
{
tcpClient.EndConnect(connectResult);
tcpClient.Close();
return false;
}
}
catch
{
return false;
}
}
}
void Init()
{
//设备地址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++)
{
WriteDO(address[i], value[i]);
}
}
/// <summary>
/// 设置天线功率dBm
/// </summary>
public short AntennaPower
{
set
{
if (this.IsConn)
WriteDO(0x0100, value);
}
}
/// <summary>
/// 关闭IO
/// </summary>
public void Close()
{
try
{
systemrun = false;
iomonitorrun = false;
if (tcpClient.Connected)
tcpClient.Close();
}
catch { }
}
/// <summary>
/// 连接状态
/// </summary>
public bool IsConn
{
get => iomonitorrun && systemrun && tcpClient.Connected;
}
bool iomonitorrun = false;
/// <summary>
/// 循环读全部IO
/// </summary>
void iomonitor()
{
iomonitorrun = true;
while (iomonitorrun && systemrun)
{
try
{
if (ID_Changed_Event != null)
ReadDO();
else
Thread.Sleep(1000);
}
catch (SocketException)
{
if (tcpClient != null)//&& tcpClient.Connected
tcpClient.Close();
ConnectionState_Event?.Invoke(this, false);
iomonitorrun = false;
}
catch(Exception ex)
{
}
}
if (systemrun)
{
do
{
Thread.Sleep(1000);
} while (systemrun && !Open());
}
}
/// <summary>
/// 写寄存器
/// </summary>
/// <param name="address"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool WriteDO(short address, short value)
{
byte funCode = 0x10;
byte[] startAddress = BitConverter.GetBytes(address); //寄存器起始地址;
byte[] data = BitConverter.GetBytes(value); //寄存器起始地址;
byte startLength = 1;
var seqhead = BitConverter.GetBytes(seq);
byte[] by = new byte[]
{
//事物标识符
seqhead[0],
seqhead[1],
//协议标识符 固定值
0x00,
0x00,
//长度
0x00,
0x06,
//从站地址
station,
//功能码
funCode,
startAddress[1],//起始地址高位
startAddress[0], //起始地址低位
0x00,
startLength, //读个数
0x02,
data[1],
data[0]
};
by[5] = (byte)(by.Length - 6);
bool check = true;
lock (tcpClient)
{
try
{
seqadd();
tcpClient.Client.Send(by);
byte[] result = new byte[100];
var ulength = tcpClient.Client.Receive(result);
var newResult = result.ToList().Take(ulength).ToArray();
if (newResult[0] == seqhead[0] && newResult[1] == seqhead[1])
{
check = true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
/*
var newResult = result.ToList().Take(ulength).ToArray();
//输出报文
var output = string.Join(" ", newResult.Select(x => x.ToString("X2")));
*/
return check;
}
string currentID = "";
bool hasID = false;
DateTime currentIDdate = DateTime.MinValue;
string lastID = "";
public short StartAddr = 0x0255;
public short Length = 2;
/// <summary>
/// 读全部数据
/// </summary>
void ReadDO()
{
byte funCode = 0x03;
byte[] startAddress = BitConverter.GetBytes(StartAddr);
byte[] startLength = BitConverter.GetBytes((short)Math.Ceiling(Length / 2d));//2;
var seqhead = BitConverter.GetBytes(seq);
byte[] by = new byte[]
{
//事物标识符
seqhead[0],
seqhead[1],
//协议标识符 固定值
0x00,
0x00,
//长度
0x00,
0x06,
//从站地址
station,
//功能码
funCode,
startAddress[1],
startAddress[0], //起始地址
startLength[1],
startLength[0], //读个数
};
by[5] = (byte)(by.Length - 6);
byte[] result = new byte[100];
int ulength = 0;
lock (tcpClient)
{
try
{
seqadd();
tcpClient.Client.Send(by);
Thread.Sleep(5);
ulength = tcpClient?.Client?.Receive(result)??0;
}
catch (SocketException se)
{
throw se;
}
finally
{
Thread.Sleep(20);
}
}
var newResult = result;//.ToList().Take(ulength).ToArray();
//aa = BitConverter.ToString(newResult);
//Console.WriteLine(aa);
if (newResult[0] == seqhead[0] && newResult[1] == seqhead[1])
{
if (newResult[7] == 0x03)
{
hasID = true;
currentID = (char)newResult[10] + newResult[11].ToString();
currentIDdate = DateTime.Now;
if (currentID != lastID)
{
ID_Changed_Event?.Invoke(this, currentID);
lastID = currentID;
}
}
else if (newResult[7] == 0x83)
{
hasID = false;
}
}
else
{
Thread.Sleep(20);
if (tcpClient?.Client?.Available > 0)
_ = tcpClient.Client.Receive(result);
}
//输出报文
//var output = string.Join(" ", newResult.Select(x => x.ToString("X2")));
}
/// <summary>
/// 读取rfid
/// </summary>
/// <param name="id">读取到的id</param>
/// <param name="ms">最后读到的时间ms</param>
/// <returns>读取成功状态-1读取失败,0没有读到,1读取成功</returns>
public int TryRead(out string id, out double ms)
{
id = "";
ms = 0;
try
{
ReadDO();
id = lastID;
ms = (DateTime.Now - currentIDdate).TotalMilliseconds;
if (hasID)
return 1;
else
return 0;
}
catch
{
Open();
return -1;
}
}
object locRead = new object();
public bool ReadByte(short address, short length, out byte[] data)
{
data = null;
if (Monitor.TryEnter(locRead))
{
try
{
if (length > 64)
throw new Exception("最大读取64个字节");
data = null;
byte funCode = 0x03;
byte[] startAddress = BitConverter.GetBytes(address);//0x0255
byte[] startLength = BitConverter.GetBytes((short)Math.Ceiling(length / 2d));//2
var seqhead = BitConverter.GetBytes(seq);
byte[] by = new byte[]
{
//事物标识符
seqhead[0],
seqhead[1],
//协议标识符 固定值
0x00,
0x00,
//长度
0x00,
0x06,
//从站地址
station,
//功能码
funCode,
startAddress[1],
startAddress[0], //起始地址
startLength[1],
startLength[0], //读个数
};
by[5] = (byte)(by.Length - 6);
byte[] result = new byte[1000];
int ulength = 0;
lock (tcpClient)
{
try
{
if (tcpClient?.Client?.Available > 0)
tcpClient?.Client?.Receive(result);
seqadd();
tcpClient.Client.Send(by);
Thread.Sleep(5);
ulength = tcpClient?.Client?.Receive(result) ?? 0;
}
catch (SocketException se)
{
return false;
}
}
var newResult = result.ToList().Take(ulength).ToList();
//aa = BitConverter.ToString(newResult);
//Console.WriteLine(aa);
if (newResult.Count > 6 && newResult[0] == seqhead[0] && newResult[1] == seqhead[1])
{
if (newResult[7] == 0x03)
{
var recvlen = BitConverter.ToInt16(new byte[] { newResult[5], newResult[4] }, 0);
if ((recvlen + 6) <= newResult.Count)
{
data = newResult.GetRange(9, recvlen - 3).ToArray();
Console.WriteLine(BitConverter.ToString(newResult.ToArray()));
return true;
}
}
else if (newResult[7] == 0x83)
{
return false;
}
}
else
{
Thread.Sleep(20);
if (tcpClient.Client.Available > 0)
_ = tcpClient.Client.Receive(result);
}
}finally
{
Monitor.Exit(locRead);
}
}
return false;
}
/// <summary>
/// 写入字节最大 64字
/// </summary>
/// <param name="address"></param>
/// <param name="data"></param>
/// <returns></returns>
public bool WriteByte(short address, byte[] data)
{
if (data.Length > 64)
throw new Exception("最大写入64个字节");
byte funCode = 0x10;
byte[] startAddress = BitConverter.GetBytes(address); //寄存器起始地址;
short registerlength = (short)Math.Ceiling(data.Length / 2d);
byte[] registerAddress = BitConverter.GetBytes(registerlength);
var seqhead = BitConverter.GetBytes(seq);
byte[] by = new byte[]
{
//事物标识符
seqhead[0],
seqhead[1],
//协议标识符 固定值
0x00,
0x00,
//长度
0x00,
0x06,
//从站地址
station,
//功能码
funCode,
startAddress[1],//起始地址高位
startAddress[0], //起始地址低位
registerAddress[1],
registerAddress[0], //寄存器数量
(byte)(registerlength * 2)
};
var ab = by.ToList();
ab.AddRange(data);
if (registerlength * 2 > data.Length)
{
ab.Add(0x0);
}
short datalength = (short)(ab.Count() - 6);
var dl = BitConverter.GetBytes(datalength);
ab[4] = dl[1];
ab[5] = dl[0];
by = ab.ToArray();
lock (tcpClient)
{
try
{
byte[] result = new byte[100];
if (tcpClient.Client.Available > 0)
tcpClient.Client.Receive(result);
seqadd();
tcpClient.Client.Send(by);
var ulength = tcpClient.Client.Receive(result);
var newResult = result.ToList().Take(ulength).ToArray();
if (newResult[0] == seqhead[0] && newResult[1] == seqhead[1])
{
Console.WriteLine(BitConverter.ToString(newResult));
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
}
void seqadd()
{
seq++;
if (seq >= ushort.MaxValue - 10)
seq = 0;
}
}