package h.com.serialportapi.comn;

/**
 * Created by hxd on 2018/10/25.
 */

public class Packet {
    byte header = 50;
    private byte len;//data长度
    private byte cmd;
    private byte[] data;
    private byte xor;
    private byte[] buff;//报文
    private int widx;//包长
    private StringBuilder sendData;


    public String getSendData() {
        return this.sendData.toString();
    }


    public Packet(byte[] data, byte header, byte len, byte cmd) {
        this.data = data;
        this.header = header;
        this.len = len;
        this.cmd = cmd;
        sendData = new StringBuilder();
        this.buff = new byte[len + 4];
        setByte(this.header);//包头
        setUint16(this.len);//长度
        setByte(this.cmd);//指令
        setBytes(this.data);//数据
        for (byte b : this.buff) {
            if (String.valueOf(b).length() == 1) {
                sendData.append("0" + String.valueOf(b));
            } else {
                sendData.append(b);
            }
        }
        sendData.append(setXor());
    }


    private void setUint16(int n) {
        this.buff[widx++] = (byte) (n >> 8 & 0xff);
        this.buff[widx++] = (byte) (n & 0xff);
    }

    private void setByte(byte n) {
        this.buff[widx++] = n;
    }

    private void setBytes(byte[] buff) {
        System.arraycopy(buff, 0, this.buff, widx, buff.length);
        widx += buff.length;
    }

    private String setXor() {
        int r = 0;
        for (byte b : this.buff) {
            r = r ^ Integer.parseInt(String.valueOf(b), 16);
        }
        String hex = Integer.toHexString(r & 0xFF);
        return hex;
    }

    /*字节转换成String*/
    public static String Bytes2HexString(byte[] b) {
        String ret = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            ret += " 0x" + hex.toUpperCase();
        }
        return ret;
    }


}

