package com.unibuy.smartdevice.devices;
public class DevDigitalDisplay {
    private static byte[] bufferTmp = new byte[]{0x10, 0x00, (byte) 0xE8, 0x00, 0x08, 0x10};

    public static byte[] getBuffer(int slot, int h, int m, int min) {
        byte[] buffer = PortTools.concatByteArrays(PortTools.intToByte8(slot, 1), bufferTmp);
        buffer = PortTools.concatByteArrays(buffer, PortTools.charToByte8(String.format("%02d", min), 2));
        buffer = PortTools.concatByteArrays(buffer, new byte[] {0x00, 0x2D});
        buffer = PortTools.concatByteArrays(buffer, PortTools.charToByte8(String.format("%02d", m), 2));
        buffer = PortTools.concatByteArrays(buffer, new byte[] {0x00, 0x2D});
        buffer = PortTools.concatByteArrays(buffer, PortTools.charToByte8(String.format("%02d", h), 2));
        buffer = PortTools.concatByteArrays(buffer, calculateCRC16(buffer));
        return buffer;
    }

    public static byte[] calculateCRC16(byte[] data) {
        int crc = 0xFFFF; // 初始值

        for (byte b : data) {
            crc ^= (b & 0xFF); // 將 byte 擴展到無符號整數進行異或

            for (int i = 0; i < 8; i++) {
                if ((crc & 0x0001) != 0) {
                    crc >>>= 1;
                    crc ^= 0xA001;
                } else {
                    crc >>>= 1;
                }
            }
        }

        // 回傳低位與高位的 byte 值
        return new byte[]{(byte) (crc & 0xFF), (byte) ((crc >> 8) & 0xFF)};
    }
}
