You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.9 KiB

1 year ago
using System.Text;
namespace JiLinApp.Docking.VibrateAlarm;
public class DataMessage
{
private byte headA = 0xAA;
private byte headB = 0xAA; //(1)帧头
public int deviceID { get; set; } //(2)设备ID
public string sendIP { get; set; } //(3)原地址
public int sendPort { get; set; }//(3)原地址
public string receiveIP { get; set; }//(4)目标地址
public int receivePort { get; set; }//(4)目标地址
public byte frameNum { get; set; }//(5)帧编号
public byte functionNum { get; set; }//(6)功能码
public byte dataLen { get; set; }//(7)传输数据长度
public byte[] data { get; set; }//(8)传输数据
public byte CRC { get; set; }//(9)CRC8
public void decode(byte[] bytes)
{
deviceID = bytes[2];
sendIP = bytes[3].ToString() + "." + bytes[4].ToString() + "." + bytes[5].ToString() + "." + bytes[6].ToString();
sendPort = bytes[8] * 256 + bytes[7];
receiveIP = bytes[9].ToString() + "." + bytes[10].ToString() + "." + bytes[11].ToString() + "." + bytes[12].ToString();
receivePort = bytes[13] * 256 + bytes[14];
frameNum = bytes[15];
functionNum = bytes[16];
dataLen = bytes[17];
data = new byte[dataLen];
for (int i = 0; i < dataLen; i++)
{
data[i] = bytes[18 + i];
}
CRC = bytes[18 + dataLen];
}
public byte[] encode()
{
byte[] bytes = new byte[19 + dataLen];
bytes[0] = bytes[1] = 0xAA;
bytes[2] = (byte)deviceID;
string[] strs = sendIP.Split('.');
bytes[3] = byte.Parse(strs[0]);
bytes[4] = byte.Parse(strs[1]);
bytes[5] = byte.Parse(strs[2]);
bytes[6] = byte.Parse(strs[3]);
bytes[7] = (byte)(sendPort % 256);
bytes[8] = (byte)(sendPort / 256);
string[] strs2 = receiveIP.Split('.');
bytes[9] = byte.Parse(strs2[0]);
bytes[10] = byte.Parse(strs2[1]);
bytes[11] = byte.Parse(strs2[2]);
bytes[12] = byte.Parse(strs2[3]);
bytes[13] = (byte)(receivePort % 256);
bytes[14] = (byte)(receivePort / 256);
bytes[15] = frameNum;
bytes[16] = functionNum;
bytes[17] = dataLen;
for (int i = 0; i < dataLen; i++)
{
bytes[18 + i] = data[i];
}
bytes[bytes.Length - 1] = CRC8.CRC(bytes, 0, bytes.Length - 1);
Console.WriteLine("发送指令:" + ToHexString(bytes));
return bytes;
}
private string ToHexString(byte[] bytes)
{
string hexString = string.Empty;
if (bytes != null)
{
StringBuilder strB = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
strB.Append(bytes[i].ToString("X2") + " ");
}
hexString = strB.ToString();
}
return hexString;
}
}