BaseModel.java 2 KB
package com.viontech.model;

import io.netty.buffer.ByteBuf;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * .
 *
 * @author 谢明辉
 * @date 2020/8/20
 */
@Getter
@Setter
@Accessors(chain = true)
public class BaseModel {
    protected Long deviceId;
    protected Long length;
    protected Long firstInt;
    protected Long secondInt;
    protected byte[] data;


    /**
     * 将byteBuf 转换为 model
     *
     * @param byteBuf byteBuf
     *
     * @return model
     */
    public static BaseModel from(ByteBuf byteBuf) {


        long deviceId = byteBuf.readUnsignedInt();
        long length = byteBuf.readUnsignedInt();
        long firstInt = byteBuf.readUnsignedInt();
        long secondInt = byteBuf.readUnsignedInt();

        BaseModel model;
        switch ((int) firstInt) {
            case 0x00010100:
                model = new LoginData();
                break;
            case 0x0001FFFF:
                model = new KeepAlive();
                break;
            default:
                return null;
        }

        model.setDeviceId(deviceId);
        model.setLength(length);
        model.setFirstInt(firstInt);
        model.setSecondInt(secondInt);
        if (length > 16) {
            model.data = new byte[(int) (length - 16)];
            byteBuf.readBytes(model.data);
            model.decodeData();
        }
        return model;
    }

    public static int castLong2Int(long data) {
        return (int) (data & 0xFF);
    }

    /**
     * 将 model 转换为 byteBuf
     *
     * @return byteBuf
     */
    public void to(ByteBuf byteBuf) {
        encodeData();

        byteBuf.writeInt(castLong2Int(deviceId));
        byteBuf.writeInt(castLong2Int(length));
        byteBuf.writeInt(castLong2Int(firstInt));
        byteBuf.writeInt(castLong2Int(secondInt));
        if (data != null && data.length > 0) {
            byteBuf.writeBytes(data);
        }
    }

    protected void encodeData() {
    }

    protected void decodeData() {
    }
}