RFIDReader.cs
11.5 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
using log4net;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Asa.RFID.RFIDAuto;
namespace Asa.RFID
{
public class RFID
{
public static readonly ILog LOGGER = LogManager.GetLogger("TheRFID");
// private System.Threading.Thread tScan;
private bool loop;
private string IP = "";
private byte addr;
private int portIndex;
private bool IsConnect = false;
private byte[] lastData = new byte[8];
internal byte[] _buff; //8字节缓存
private byte[] _uid; //卡片ID
public bool IsExist = false;
public int ErrCode = 0;
/// <summary>
/// 接收事件
/// </summary>
/// <param name="ip"></param>
/// <param name="buff"></param>
public delegate void Received_Event(string ip, byte[] buff);
/// <summary>
/// 接收数据
/// </summary>
public event Received_Event Received;
public RFID(string ip)
{
this.IP = ip;
}
public int Close()
{
try
{
loop = false;
IsConnect = false;
try
{
// tScan.Abort();
}catch(Exception ex)
{
LOGGER.Info("Close tScan[" + IP + "] error :" + ex.ToString());
}
int ErrCode = ReaderA.StaticClassReaderA.CloseNetPort(portIndex);
LOGGER.Info("Close RFID [" + IP + "]:" + ErrCode);
return ErrCode;
}
catch (Exception e)
{
LOGGER.Error("Close RFID[" + IP + "] has error", e);
}
return -1;
}
public int Open()
{
if (IsConnect)
{
LOGGER.Warn(" RFID [" + IP + "] is already connected, no need to start again");
return 0;
}
//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)
{
LOGGER.Error(IP + " is error");
return -1;
}
string[] arr = IP.Split('.');
if (arr.Length != 4)
{
LOGGER.Error(IP + " length is not 4");
return -1;
}
addr = Convert.ToByte(arr[3]);
int port = 6000 + Convert.ToInt32(arr[3]);
portIndex = 0;
int ErrCode = ReaderA.StaticClassReaderA.OpenNetPort(port, IP, ref addr, ref portIndex);
LOGGER.Info("Connect [" + IP + "] :" + ErrCode);
// 在 OpenNetPort 后面使用
System.Threading.Thread.Sleep(100);
OpenCloseRF(false);
System.Threading.Thread.Sleep(100);
OpenCloseRF(true);
return ErrCode;
}
public void FindMode()
{
loop = true;
//tScan = new System.Threading.Thread(new System.Threading.ThreadStart(Scan));
//tScan.Start();
Task.Factory.StartNew(Scan);
}
private void Scan()
{
while (loop)
{
bool rtn = FindRFID();
if (rtn)
{
int result = ReadRFID();
if (result.Equals(0))
{
byte[] bb = new byte[] { _buff[0], _buff[1], _buff[2] };
string dataStr = byteToStr(bb, bb.Length);
LOGGER.Info(IP + " Scan Data:" + dataStr);
Received?.Invoke(IP, bb);
}
else if (result.Equals(14))
{
LOGGER.Error(IP + " ReadRFID 返回 " + result + ", 需要重连,调用close ,等待100后重连");
Close();
System.Threading.Thread.Sleep(100);
Open();
FindMode();
break;
}
}
System.Threading.Thread.Sleep(100);
}
}
private void OpenCloseRF(bool rtn)
{
if (rtn)
ErrCode = ReaderA.StaticClassReaderA.OpenRf(ref addr, portIndex);
else
ErrCode = ReaderA.StaticClassReaderA.CloseRf(ref addr, portIndex);
}
/// <summary>
/// 查找电子标签,扫描模式不能使用
/// </summary>
/// <returns></returns>
public bool FindRFID()
{
try
{
//0 不带AFI
//1 带AFI
//2 不带AFI,继续查询
//3 带AFI,继续查询
//6 不带AFI,新的查询
//7 带AFI,新的查询
byte state = 0;
//Select模式需要AFI
byte AFI = 0;
//输出,1字节DSFID,8字节UID
byte[] DSFIDAndUID = new byte[9];
//输出,标签数量
byte cardNumber = 0;
if (_uid == null)
{
_uid = new byte[8];
}
ErrCode = ReaderA.StaticClassReaderA.Inventory(ref addr, ref state, ref AFI, DSFIDAndUID, ref cardNumber, portIndex);
if (ErrCode == 0)
{
//查询时间
//fCmdRet = StaticClassReaderA.GetInventoryTime(ref n_time, portIndex);
Array.Copy(DSFIDAndUID, 1, _uid, 0, 8);
IsExist = true;
return true;
}
else
{
for (int i = 0; i < _uid.Length; i++)
_uid[i] = 0;
IsExist = false;
}
}catch(Exception ex)
{
LOGGER.Error(IP + "FindRFID Error:" + ex.ToString());
}
return false;
}
//public byte[] Read(bool isNeedFind = false)
//{
// if (isNeedFind)
// {
// FindRFID();
// }
// if (IsExist)
// {
// ReadRFID();
// return _buff;
// }
// else
// {
// LOGGER.Info(IP + " Read: IsExist=false ");
// }
// return null;
//}
private int ReadRFID()
{
try
{
//0 不带AFI
//1 带AFI
//2 不带AFI,继续查询
//3 带AFI,继续查询
//6 不带AFI,新的查询
//7 带AFI,新的查询
byte state = 0;
//起始块号
byte blockNum = 0;
//块数量
byte blockCount = 2;
//输出,块内安全信息,长度为BlockCount个字节
byte[] blockSecStatus = new byte[blockCount];
//输出,块内数据信息,长度为块的大小(4或8字节)乘以BlockCount个字节
byte[] data = new byte[4 * blockCount];
//错误代码
byte errorCode = 0;
if (_buff == null)
{
_buff = new byte[8];
}
ErrCode = ReaderA.StaticClassReaderA.ReadMultipleBlock(ref addr, ref state, _uid, blockNum, blockCount, blockSecStatus, data, ref errorCode, portIndex);
if (ErrCode == 0)
{
Array.Copy(data, 0, _buff, 0, data.Length);
string dataStr = byteToStr(data, data.Length);
LOGGER.Info(IP + " ReadMultipleBlock: Length: " + data.Length + " Data:" + dataStr);
}else if (ErrCode == 14)
{
LOGGER.Error(IP + " ReadMultipleBlock: ErrCode: " + ErrCode+",需要重连");
}
else
{
LOGGER.Info(IP + " ReadMultipleBlock: ErrCode: " + ErrCode);
}
return ErrCode;
}
catch (Exception ex)
{
LOGGER.Error(IP + "ReadRFID Error:" + ex.ToString());
}
return -1;
}
private string byteToStr(byte[] data, int len)
{
string s = "";
for (int i = 0; i < len; i++)
{
s += data[i].ToString("X2") + " ";
}
return s;
}
}
public class RFIDReader
{
public static readonly ILog LOGGER = LogManager.GetLogger("TheRFID");
private static Dictionary<string, RFID> rfidMap = new Dictionary<string, RFID>();
private static Dictionary<string, byte[]> LastRfidData = new Dictionary<string, byte[]>();
public static void Open(params string[] ipArr)
{
try
{
foreach (var ip in ipArr)
{
if (rfidMap.ContainsKey(ip))
{
rfidMap[ip].Open();
rfidMap[ip].FindMode();
}
else
{
RFID rfid = new RFID(ip);
rfid.Received += Rfid_Received;
rfid.Open();
rfid.FindMode();
rfidMap.Add(ip, rfid);
}
}
}
catch (Exception ex)
{
LOGGER.Error ("RFIDReader Open Error:" + ex.ToString());
}
}
private static void Rfid_Received(string ip, byte[] buff)
{
if (buff == null)
{
return;
}
string dataStr = byteToStr(buff, buff.Length);
LOGGER.Info(ip + " Rfid_Received 保存数据:" + dataStr);
if (LastRfidData.ContainsKey(ip))
{
LastRfidData[ip] = buff;
}
else
{
LastRfidData.Add(ip, buff);
}
}
//public static bool FindRFID(string ip)
//{
// if (rfidMap.ContainsKey(ip))
// {
// return rfidMap[ip].FindRFID();
// }
// return false;
//}
public static byte[] Read(string ip, bool isClear = false)
{
if (rfidMap.ContainsKey(ip))
{
if (LastRfidData.ContainsKey(ip))
{
byte[] data= LastRfidData[ip];
if (isClear)
{
LastRfidData.Remove(ip);
}
return data;
}
// return rfidMap[ip].Read(isNeedFind);
}
return null;
}
public static void CloseAll()
{
foreach (RFID rfid in rfidMap.Values)
{
rfid.Close();
}
}
private static string byteToStr(byte[] data, int len)
{
string s = "";
for (int i = 0; i < len; i++)
{
s += data[i].ToString("X2") + " ";
}
return s;
}
}
}