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

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

/**
 * .
 *
 * @author 谢明辉
 * @date 2020/8/20
 */
@Getter
@Setter
public abstract 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 void decode(ByteBuf byteBuf) {
        this.deviceId = byteBuf.readUnsignedInt();
        this.length = byteBuf.readUnsignedInt();
        this.firstInt = byteBuf.readUnsignedInt();
        this.secondInt = byteBuf.readUnsignedInt();
        this.data = new byte[(int) (length - 16)];
        byteBuf.readBytes(data);

        decodeData();
    }

    ;

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

        byteBuf.writeInt((int) (deviceId & 0xff));
        byteBuf.writeInt((int) (length & 0xff));
        byteBuf.writeInt((int) (firstInt & 0xff));
        byteBuf.writeInt((int) (secondInt & 0xff));
        byteBuf.writeBytes(data);
    }

    ;

    abstract protected void encodeData();

    abstract protected void decodeData();
}