串口通信,需要用到异或算法进行加密处理,
package comtest.example.admin.lib;
/**
* Created by wrs on 2019/6/14,10:13
* projectName: Testz
* packageName: comtest.example.admin.lib
*/
public class CheckCode {
public static void main(String[] args) {
byte[] c;
// generateCommand((byte) 0x03, new byte[]{0x55,0x45});
// generateCommand((byte) 0x03, new byte[]{0x55});
generateCommand((byte) 0x01, new byte[]{});
int a=0x03,b=0x00,d=0x01,e=0x55,f=0x02,g=0x54,m=0x45;
// 0x69 0x03 0x00 0x01 0x55 校验码 0x16
// System.out.println("test: "+ (g ^= m));
/* c = int2Bytes(0);
for (int i = 0; i < c.length; i++) {
System.out.println("test: "+c[i]);
}*/
}
//控制码 和发送指令 长度0或者1 内容0x55或者0xAA
public static byte[] generateCommand(byte controlCode, byte[] data) {
int dataLen = 0;
if (null != data) {
dataLen = data.length;
}
// dataLen = 1
byte[] command = new byte[6 + dataLen];
command[0] = 0x69;
command[1] = controlCode;
byte[] len = int2Bytes(dataLen);
command[2] = len[len.length - 2];
command[3] = len[len.length - 1];
// 0x69 0x03 0x00 0x01 0x55 校验码 0x16
for (int i = 0; i < dataLen; i++) {
command[i + 4] = data[i];
}
command[command.length - 2] = generateBCC(command);
command[command.length - 1] = 0x16;
for (int i = 0; i < command.length; i++) {
System.out.println("test: " + command[i] + " size: " + command.length);
}
return command;
}
//控制码 和发送指令 长度0或者1 内容0x55或者0xAA
public static byte[] generatesCommand(byte controlCode, byte[] data) {
int dataLen = 0;
if (null != data) {
dataLen = data.length;
}
byte[] command = new byte[6 + dataLen];
command[0] = 0x69;
command[1] = controlCode;
byte[] len = int2Bytes(dataLen);
command[2] = len[0];
command[3] = len[1];
for (int i = 0; i < dataLen; i++) {
command[i + 4] = data[i];
}
command[dataLen - 2] = generateBCC(command);
command[dataLen - 1] = 0x16;
System.out.println("test: " + command[0] + " size: " + command.length);
return command;
}
public static byte[] int2Bytes(int num) {
byte[] result = new byte[4];
result[0] = (byte) (num >>> 24);//取最高8位放到0下标
result[1] = (byte) (num >>> 16);//取次高8为放到1下标
result[2] = (byte) (num >>> 8); //取次低8位放到2下标
result[3] = (byte) (num); //取最低8位放到3下标
return result;
}
//异或校验码new
private static byte generateBCC(byte[] data) {
// 105 3 0 1 85 0 0
byte bcc = 0x00;
for (int i = 1; i < data.length-2; ++i) {
bcc ^= data[i]; // 异或操作
}
return bcc;
}
}