Commit 53eda596 顾剑亮

修改bug

1 个父辈 c064edb2
正在显示 35 个修改的文件 包含 364 行增加135 行删除
此文件类型无法预览
......@@ -11,6 +11,16 @@ namespace Asa.RFID
public System.Net.Sockets.Socket Socket;
public System.Threading.Thread ListenNet;
public Client(string ip)
{
Loop = false;
IP = ip;
IsConn = false;
Buffer = null;
Socket = null;
ListenNet = null;
}
public Client(string ip, System.Net.Sockets.Socket socket, System.Threading.Thread listenNet)
{
Loop = true;
......
......@@ -2,9 +2,24 @@
namespace Asa.RFID
{
/// <summary>
/// RFID读卡器类型
/// </summary>
public class Device
{
public string IP { set; get; }
public string Value { set; get; }
public Device(string ip, string value)
{
IP = ip;
Value = value;
}
public Device(string ip)
{
IP = ip;
Value = "";
}
}
public enum DeviceType
{
/// <summary>
......@@ -16,4 +31,11 @@ namespace Asa.RFID
/// </summary>
HaoBin
}
public enum ReadMode
{
Client,
Server
}
}
......@@ -21,7 +21,8 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>bin\Debug\Asa.RFID.ReadAll.xml</DocumentationFile>
<DocumentationFile>
</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
......@@ -31,6 +32,9 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<LangVersion>preview</LangVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=2.0.12.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.12\lib\net45\log4net.dll</HintPath>
......@@ -48,9 +52,9 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Client.cs" />
<Compile Include="Device.cs" />
<Compile Include="ReadAll.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Type.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
......
......@@ -14,89 +14,133 @@ namespace Asa.RFID
/// </summary>
public class ReadAll
{
private bool serverLoop;
private Socket server; //服务端
private List<Client> clientList; //所有客户端
private Thread tListenClient; //监听客户端连接
private Dictionary<string, string> rfidID; //RFID编号
private readonly Dictionary<DeviceType, DecodeDelegate> decode; //解码
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
/// 读取所有RFID,client模式
/// </summary>
/// <param name="logName">日志名称</param>
public ReadAll(string logName = "RFID.ReadAll")
public ReadAll(string logName = "RFID.ReadAll.Client")
{
rfidID = new Dictionary<string, string>();
decode = new Dictionary<DeviceType, DecodeDelegate>
readMode = ReadMode.Client;
rfidDev = new();
decode = new()
{
{ DeviceType.PuYue, DecodePuYue },
{ DeviceType.HaoBin, DecodeHaoBin }
};
if (log == null)
log = log4net.LogManager.GetLogger(logName);
log.Debug("ReadAll实例化");
log = log4net.LogManager.GetLogger(logName);
log.Debug("ReadAll client initialization");
}
/// <summary>
/// 设备类型
/// 读取所有RFID,server模式
/// </summary>
public DeviceType Type { set; get; } = DeviceType.PuYue;
/// <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 = 13000)
public void Start(int port)
{
try
{
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(localEP);
server.Listen(100);
serverLoop = true;
clientList = new List<Client>();
tListenClient = new Thread(new ThreadStart(ListenClient));
tListenClient.Start();
string s = string.Format("Server Start({0}) OK", port);
log.Info(s);
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)
{
string s = string.Format("Start({0})", port);
log.Error(s, ex);
log.Error("Start", ex);
}
}
/// <summary>
/// 停止
/// 客户端开始,server模式
/// </summary>
public void Stop()
public void Start()
{
serverLoop = false;
if (clientList == null) return;
for (int i = 0; i < clientList.Count; i++)
ClientClose(i);
serverLowerLoop = true;
connectServerLower = new(new ThreadStart(ConnectLower));
connectServerLower.Start();
}
/// <summary>
/// 服务端停止
/// </summary>
public void Stop()
{
try
{
rfidID.Clear();
server.Close();
server.Dispose();
clientList = null;
log.Info("Server Stop OK");
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)
{
......@@ -112,18 +156,29 @@ namespace Asa.RFID
/// <returns></returns>
public string Read(string ip, string defaultID = "000")
{
if (rfidID.TryGetValue(ip, out string value))
string text = $"Read({ip}):";
string result = defaultID;
int index = rfidDev.FindIndex(match => match.IP == ip);
if (index == -1)
{
string s = string.Format("Read({0}): {1}", ip, value);
log.Info(s);
return value;
text += $"default {defaultID}, ip没有找到";
}
else
{
string s = string.Format("Read: {0}没有连接,返回{1}", ip, defaultID);
log.Info(s);
return defaultID;
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>
......@@ -132,14 +187,14 @@ namespace Asa.RFID
/// <param name="defaultID">没有数据时返回</param>
public Dictionary<string, string> Read(string defaultID = "000")
{
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (string key in rfidID.Keys)
Dictionary<string, string> dic = new();
for (int i = 0; i < rfidDev.Count; i++)
{
if (rfidID[key] == "")
dic.Add(key, defaultID);
else
dic.Add(key, rfidID[key]);
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;
}
......@@ -150,17 +205,21 @@ namespace Asa.RFID
/// <param name="defaultID">设置初始ID</param>
public void Clear(string ip, string defaultID = "000")
{
if (rfidID.ContainsKey(ip))
string text = $"Clear({ip}):";
string result = defaultID;
int index = rfidDev.FindIndex(match => match.IP == ip);
if (index == -1)
{
rfidID[ip] = defaultID;
string s = string.Format("Clear({0}): ID={1}", ip, defaultID);
log.Info(s);
text += "ip没有找到";
}
else
{
string s = string.Format("Clear: {0}没有连接", ip);
log.Info(s);
rfidDev[index].Value = defaultID;
text += $"Value={defaultID}";
}
log.Info(text);
}
/// <summary>
......@@ -169,20 +228,132 @@ namespace Asa.RFID
/// <param name="defaultID">设置初始ID</param>
public void Clear(string defaultID = "000")
{
Dictionary<string, string> temp = new Dictionary<string, string>();
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);
}
foreach (string key in rfidID.Keys)
}
}
private void ListenServerLower(object obj)
{
Client client = clientListUpper[(int)obj];
while (client.Loop)
{
temp.Add(key, defaultID);
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;
}
}
rfidID.Clear();
rfidID = new Dictionary<string, string>(temp);
}
string s = string.Format("Clear All: ID={0}", defaultID);
log.Info(s);
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
......@@ -190,60 +361,60 @@ namespace Asa.RFID
private void ClientClose(int idx)
#region client mode
/// <summary>
/// 设备类型
/// </summary>
public DeviceType Type { set; get; } = DeviceType.PuYue;
private void ClientClose(Client client)
{
try
{
clientList[idx].Loop = false;
clientList[idx].IsConn = false;
clientList[idx].Socket.Close();
clientList[idx].Socket.Dispose();
string s = string.Format("关闭 ({0})", clientList[idx].IP);
log.Info(s);
client.Loop = false;
client.IsConn = false;
client.Socket.Close();
client.Socket.Dispose();
log.Info($"关闭 ({client.IP})");
}
catch (Exception ex)
{
string s = string.Format("ClientClose ({0})", clientList[idx].IP);
log.Error(s, ex);
log.Error("ClientClose", ex);
}
}
private void ListenClient()
private void ListenClientUpper()
{
string s;
while (serverLoop)
while (serverUpperLoop)
{
try
{
Socket socket = server.Accept(); //这边会暂停,不需要sleep
Socket socket = serverUpper.Accept(); //这边会暂停,不需要sleep
IPEndPoint ep = (IPEndPoint)socket.RemoteEndPoint;
Thread listen = new Thread(new ParameterizedThreadStart(ListenNet));
Thread listen = new(new ParameterizedThreadStart(ListenClientUpperNet));
string ip = ep.Address.ToString();
//新的客户端
Client client = new Client(ip, socket, listen);
Client client = new(ip, socket, listen);
int index = rfidDev.FindIndex(match => match.IP == ip);
//重连后关闭旧连接
int idx = clientList.FindIndex(ls => ls.IP.Equals(ip));
//重连后删除旧连接
int idx = clientListLower.FindIndex(ls => ls.IP.Equals(ip));
if (idx > -1)
{
rfidID[clientList[idx].IP] = "";
clientList[idx].IsConn = false;
clientList[idx].Loop = false;
clientList[idx].Socket.Close();
s = string.Format("({0}) 重连,删除重复", clientList[idx].IP);
log.Info(s);
clientList.RemoveAt(idx);
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 (!rfidID.ContainsKey(client.IP))
rfidID.Add(client.IP, "");
clientList.Add(client);
s = string.Format("({0}) 连接服务端", client.IP);
log.Info(s);
listen.Start(clientList.Count - 1);
if (index == -1) rfidDev.Add(new Device(client.IP));
clientListLower.Add(client);
log.Info($"({ip})连接服务端");
listen.Start(clientListLower.Count - 1);
}
catch (SocketException)
{
......@@ -258,9 +429,9 @@ namespace Asa.RFID
}
private void ListenNet(object obj)
private void ListenClientUpperNet(object obj)
{
Client client = clientList[(int)obj];
Client client = clientListLower[(int)obj];
while (client.Loop)
{
Thread.Sleep(CLIENT_SLEEP);
......@@ -381,24 +552,31 @@ namespace Asa.RFID
string s = "";
if (buff[1] >= 65 && buff[1] <= 90) //在A-Z范围
s = (char)buff[1] + buff[2].ToString();
log.Info("TriggerEvent ip=" + ip + " rfid=" + s);
log.Debug($"TriggerEvent({ip}):value={s}");
//添加到缓存
if (rfidID[ip] == s)
{
log.Debug("相同ID[" + ip + "]: " + s);
}
else
int index = rfidDev.FindIndex(match => match.IP == ip);
if (index > -1)
{
rfidID[ip] = s;
if (Received != null)
if (rfidDev[index].Value == s)
{
log.Info("触发事件(" + ip + "): " + s);
Task.Run(() => Received.Invoke(ip, 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)
{
......@@ -420,6 +598,27 @@ namespace Asa.RFID
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;
}
}
}
}
C:\Neotel\Program\RFID\RFID_HaoBin\bin\Debug\Asa.RFID.HaoBin.xml
C:\Neotel\Program\RFID\RFID_HaoBin\bin\Debug\Asa.RFID.HaoBin.dll
C:\Neotel\Program\RFID\RFID_HaoBin\bin\Debug\Asa.RFID.HaoBin.pdb
C:\Neotel\Program\RFID\RFID_HaoBin\obj\Debug\RFID_HaoBin.csprojAssemblyReference.cache
C:\Neotel\Program\RFID\RFID_HaoBin\obj\Debug\RFID_HaoBin.csproj.CoreCompileInputs.cache
C:\Neotel\Program\RFID\RFID_HaoBin\obj\Debug\Asa.RFID.HaoBin.dll
C:\Neotel\Program\RFID\RFID_HaoBin\obj\Debug\Asa.RFID.HaoBin.pdb
C:\Neotel\Program\RFID\RFID_HaoBin\bin\Debug\HFReader9CSharp.dll
C:\Neotel\Program\RFID\RFID_HaoBin\obj\Debug\RFID_HaoBin.csproj.CopyComplete
C:\Neotel\Program\RFID\RFID_HaoBin\obj\Debug\RFID_HaoBin.csproj.AssemblyReference.cache
......@@ -4,7 +4,6 @@ C:\Neotel\Program\RFID\RFID_HaoBin_Debug\bin\Debug\RFID_Debug.pdb
C:\Neotel\Program\RFID\RFID_HaoBin_Debug\bin\Debug\Asa.RFID.HaoBin.dll
C:\Neotel\Program\RFID\RFID_HaoBin_Debug\bin\Debug\Asa.RFID.HaoBin.pdb
C:\Neotel\Program\RFID\RFID_HaoBin_Debug\bin\Debug\Asa.RFID.HaoBin.xml
C:\Neotel\Program\RFID\RFID_HaoBin_Debug\obj\Debug\RFID_HaoBin_Debug.csprojAssemblyReference.cache
C:\Neotel\Program\RFID\RFID_HaoBin_Debug\obj\Debug\Asa.RFID.FrmMain.resources
C:\Neotel\Program\RFID\RFID_HaoBin_Debug\obj\Debug\Asa.RFID.Properties.Resources.resources
C:\Neotel\Program\RFID\RFID_HaoBin_Debug\obj\Debug\RFID_HaoBin_Debug.csproj.GenerateResource.cache
......@@ -13,3 +12,4 @@ C:\Neotel\Program\RFID\RFID_HaoBin_Debug\obj\Debug\RFID_HaoBin_Debug.csproj.Copy
C:\Neotel\Program\RFID\RFID_HaoBin_Debug\obj\Debug\RFID_Debug.exe
C:\Neotel\Program\RFID\RFID_HaoBin_Debug\obj\Debug\RFID_Debug.pdb
C:\Neotel\Program\RFID\RFID_HaoBin_Debug\bin\Debug\HFReader9CSharp.dll
C:\Neotel\Program\RFID\RFID_HaoBin_Debug\obj\Debug\RFID_HaoBin_Debug.csproj.AssemblyReference.cache
......@@ -128,9 +128,9 @@ namespace Asa.RFID
public void Init()
{
_dataMode = false;
//设备地址1,波特率,禁止AFI,盘点超时时间(20*5ms),命令触发,操作模式,寄存器地址,寄存器数量,触发时间(10*5ms),输出格式,数据帧枕头,记录保持时间(9*5ms)
//设备地址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, 20, 1, 1, 0x20, 4, 10, 1, 0x1234, 9 };
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]);
......
......@@ -12,7 +12,7 @@ namespace Test
{
public partial class Form1 : Form
{
private Asa.RFID.ReadAll read;
//private Asa.RFID.ReadAll read;
public Form1()
{
......@@ -21,21 +21,15 @@ namespace Test
private void Form1_Load(object sender, EventArgs e)
{
read = new Asa.RFID.ReadAll("log");
read.Type = Asa.RFID.DeviceType.HaoBin;
read.Received += Read_Received;
read.Start();
}
private void Read_Received(string ip, string id)
{
string s = string.Format("{0}: {1}\r\n", ip, id);
Invoke(new Action(() => { textBox1.AppendText(s); }));
//read = new Asa.RFID.ReadAll("log");
//read.Type = Asa.RFID.DeviceType.HaoBin;
//read.Received += Read_Received;
//read.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
read.Stop();
//read.Stop();
}
}
}
此文件类型无法预览
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!