标题:
modbus协议上位机通用接口
[打印本页]
作者:
hopedream
时间:
2018-8-13 08:19
标题:
modbus协议上位机通用接口
public class KModbusUnity
{
static ushort POLYNOMIAL = 0xA001;
/// <summary>
/// 计算CRC校验结果
/// </summary>
/// <param name="data">数据源</param>
/// <returns>校验结果</returns>
public static byte[] CRCCheck(byte[] data )
{
ushort crc = 0xffff;
for(ushort i=0;i<data.Length;i++)
{
crc ^= (ushort)(data[i] & 0x00FF);
for(ushort j = 0;j<8;j++)
{
if ((crc & 0x0001) != 0)
{
crc >>= 1;
crc ^= POLYNOMIAL;
}
else
crc >>= 1;
}
}
return System.BitConverter.GetBytes(crc);
}
/// <summary>
/// 收到的数据有效
/// </summary>
/// <param name="data">数据</param>
/// <returns></returns>
public static bool IsValid(byte[] data)
{
bool bReturn = false;
int n = data.Length;
if (n >= 4)
{
byte[] check = new byte[n - 2];
for (int j = 0; j < n - 2; j++)
{
check[j] = data[j];
}
// 校验结果
byte[] crc = KModbusUnity.CRCCheck(check);
if (crc[0] == data[n - 2] && crc[1] == data[n - 1])
{
bReturn = true;
}
}
return bReturn;
}
/// <summary>
/// 返回带校验码的数据
/// </summary>
/// <param name="data">源数据</param>
/// <returns>带校验码的数据</returns>
public static byte[] CRCData(byte[] data)
{
byte[] crcCheck = CRCCheck(data);
byte[] rdata = new byte[data.Length + 2];
data.CopyTo(rdata, 0);
crcCheck.CopyTo(rdata, data.Length);
return rdata;
}
public static byte[] CRCData(String hex)
{
return CRCData(HexStrToBytes(hex));
}
/// <summary>
/// 16进制字符串转byte数组
/// </summary>
/// <param name="hex">16进制的字符串,可以是空格隔开的方式</param>
/// <returns>byte数组</returns>
public static byte[] HexStrToBytes(String hex)
{
hex = hex.Replace(" ", "");
if ((hex.Length % 2) != 0)
hex += " ";
byte[] returnBytes = new byte[hex.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
{
String sub = hex.Substring(i * 2, 2);
returnBytes[i] = Convert.ToByte(sub, 16);
}
return returnBytes;
}
/// <summary>
/// byte数组转16进制字符串
/// </summary>
/// <param name="bytes">byte数组</param>
/// <returns>16进制字符串</returns>
public static String BytesToHexStr(byte[] bytes)
{
return BitConverter.ToString(bytes).Replace('-', ' ').Trim();
}
/// <summary>
/// byte转float
/// </summary>
/// <param name="data">byte</param>
/// <param name="nStart">开始位置</param>
/// <returns>float</returns>
public static float BytesToFloat(byte[] data ,int nStart = 0)
{
float fResult = 0;
fResult = BitConverter.ToSingle(new byte[] {data[nStart+3],data[nStart+2],data[nStart+1],data[nStart] }, 0);
return fResult;
}
public static bool[] ByteToBitArray(byte data)
{
bool[] bResult = new bool[8];
for(int i =0;i<8;i++)
{
var tmp = 1 << i;
bool b = ((data & tmp) == tmp);
bResult[i] = b;
}
return bResult;
}
public static byte[] StringToBytes(String str)
{
return System.Text.Encoding.ASCII.GetBytes(str);
}
}
复制代码
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1