using HH.WCS.QingXigongchang.process;
|
using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
|
namespace HH.WCS.QingXigongchang.device
|
{
|
internal class PlcHelper
|
{
|
//public static List<string> ipList = new List<string>();
|
public static Dictionary<string, bool> ipList = new Dictionary<string, bool>();
|
public static object ojbq = new object();
|
internal static void Receive(string ip, string msg)
|
{
|
//处理设备信号
|
try
|
{
|
lock (ojbq)
|
{
|
if (ipList.ContainsKey(ip))
|
{
|
if (ipList.TryGetValue(ip, out bool re))
|
{
|
if (re)
|
return;
|
else
|
ipList[ip] = true;
|
}
|
else return;
|
}
|
else
|
{
|
ipList.Add(ip, true);
|
}
|
}
|
DeviceProcess.Analysis(msg, ip);
|
ipList[ip] = false;
|
}
|
catch (Exception ex)
|
{
|
LogHelper.Error(ex.Message + "{" + $"{ip}-{msg}" + "}", ex);
|
ipList[ip] = false;
|
}
|
}
|
internal static bool SendHex(string ip, string msg)
|
{
|
LogHelper.Info("SendHex:" + ip + "->" + msg);
|
return TcpServer.TcpServerSend(ip, Hex2Bytes(msg));
|
|
}
|
internal static void SendAscii(string ip, string msg)
|
{
|
TcpServer.TcpServerSend(ip, Encoding.ASCII.GetBytes(msg));
|
}
|
|
internal static byte[] Hex2Bytes(string hexString)
|
{
|
hexString = hexString.Replace(" ", "");
|
if ((hexString.Length % 2) != 0)
|
hexString += " ";
|
byte[] returnBytes = new byte[hexString.Length / 2];
|
for (int i = 0; i < returnBytes.Length; i++)
|
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
|
|
return returnBytes;
|
}
|
internal static string Hex2Ascii(string hexString)
|
{
|
hexString = hexString.Replace(" ", "");
|
if ((hexString.Length % 2) != 0)
|
hexString += " ";
|
byte[] returnBytes = new byte[hexString.Length / 2];
|
for (int i = 0; i < returnBytes.Length; i++)
|
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
|
|
return Encoding.ASCII.GetString(returnBytes);
|
}
|
|
#region 进制转换+CRC
|
internal static byte[] CRC16LH(byte[] pDataBytes)
|
{
|
ushort crc = 0xffff;
|
ushort polynom = 0xA001;
|
|
for (int i = 0; i < pDataBytes.Length; i++)
|
{
|
crc ^= pDataBytes[i];
|
for (int j = 0; j < 8; j++)
|
{
|
if ((crc & 0x01) == 0x01)
|
{
|
crc >>= 1;
|
crc ^= polynom;
|
}
|
else
|
{
|
crc >>= 1;
|
}
|
}
|
}
|
|
byte[] result = BitConverter.GetBytes(crc);
|
return result;
|
}
|
internal static byte[] CRC16HL(byte[] pDataBytes)
|
{
|
ushort crc = 0xffff;
|
ushort polynom = 0xA001;
|
|
for (int i = 0; i < pDataBytes.Length; i++)
|
{
|
crc ^= pDataBytes[i];
|
for (int j = 0; j < 8; j++)
|
{
|
if ((crc & 0x01) == 0x01)
|
{
|
crc >>= 1;
|
crc ^= polynom;
|
}
|
else
|
{
|
crc >>= 1;
|
}
|
}
|
}
|
|
byte[] result = BitConverter.GetBytes(crc).Reverse().ToArray();
|
return result;
|
}
|
|
#endregion
|
}
|
}
|