耀华仪表A9数据解析(C#)

耀华仪表A9 数据解析,磨蹭一中午,终于把他解析出来了,测试了一下午感觉很完美,在这里分享给大家;废话不说,直接贴代码;顺便给大家推荐一个开源称重软件,git 码云地址:https://gitee.com/jinhengliuyafei/2022.git , 谢谢大家支持;

///

/// 缓存

///

List buffData = new List();

///

/// 缓存

///

List buffData = new List();

///

/// 仪表数据解析

///

/// 串口数据

///

public string DataConvert(byte[] data)

{

string weightVal = string.Empty;

buffData.AddRange(data);

if (buffData.Count < 12) return weightVal;

int startFlag = buffData.LastIndexOf(2);

int endFlag = buffData.LastIndexOf(3);

if (startFlag >= 0 && 0 < endFlag && startFlag < endFlag)

{

//截取一帧数据

var tmpData = buffData.GetRange(startFlag, endFlag - startFlag + 1);

if (tmpData.Count < 12 || tmpData.Count >12) return weightVal;

buffData.Clear();

//判断符号

string flag = string.Empty;

if (tmpData[1] == 45) //45的ascii符号是 -;

{

flag = "-";

}

//读取中间6个字节的数据

string value = string.Empty;

byte[] arr = new byte[6];

int j = 0;

for (int i = 2; i < 8; i++)

{

arr[j] = tmpData[i];

j++;

}

string num = Encoding.ASCII.GetString(arr);

//读取小数位

byte[] arrDot = new byte[1];

arrDot[0] = tmpData[8];

int dot = 0;

int.TryParse(Encoding.ASCII.GetString(arrDot), out dot);

int len = num.Length - dot;

if (len <= 0) return string.Empty;

string num1 = num.Substring(0, len);

string num2 = num.Substring(num.Length - dot, dot);

string result = flag + num1 + "." + num2;

//校验

byte[] checkData = new byte[12];

for (int i = 0; i < tmpData.Count && i < 12; i++)

{

checkData[i] = tmpData[i];

}

var heightResult = HeightBitValidate(checkData);

var lowResult = LowBitValidate(checkData);

if (heightResult == tmpData[9] && lowResult == tmpData[10])

{

weightVal = result;

}

}

return weightVal;

}

///

/// 高位验证

///

///

///

public static int HeightBitValidate(byte[] data)

{

byte[] height = new byte[8];

if (data.Length == 12 && data[0] == 2)

{

int i = 0;

for (int index = 1; index < 9; index++)

{

height[i] = (byte)((data[index]) >> 4);

i++;

}

}

int tmp = 0;

for (int i = 0; i < height.Length; i++)

{

tmp = tmp ^ height[i];

}

if (tmp <= 9)

{

tmp += 48;

}

else

{

tmp += 55;

}

return tmp;

}

///

/// 低位验证

///

///

///

public static int LowBitValidate(byte[] data)

{

byte[] height = new byte[8];

if (data.Length == 12 && data[0] == 2)

{

int i = 0;

for (int index = 1; index < 9; index++)

{

height[i] = (byte)((data[index]) << 4);

i++;

}

}

int tmp = 0;

for (int i = 0; i < height.Length; i++)

{

tmp = tmp ^ height[i];

}

tmp = tmp >> 4;

if (tmp <= 9)

{

tmp += 48;

}

else

{

tmp += 55;

}

return tmp;

}

你可能感兴趣的:(称重软件,汽车衡,c#,java,开发语言,仪表对接)