BaseModel.java 2.18 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 = 1;
    protected long length;
    protected long protocol;
    protected long flag;
    protected byte[] data;


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


        long deviceId = byteBuf.readUnsignedIntLE();
        long length = byteBuf.readUnsignedIntLE();
        long protocol = byteBuf.readUnsignedIntLE();
        long flag = byteBuf.readUnsignedIntLE();

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

        model.setDeviceId(deviceId);
        model.setLength(length);
        model.setProtocol(protocol);
        model.setFlag(flag);
        if (length > 16) {
            model.data = new byte[(int) (length - 16)];
            byteBuf.readBytes(model.data);
            model.decodeData();
        }
        return model;
    }

    public static int toInt(long data) {
        return (int) data;
    }

    /**
     * 将 model 转换为 byteBuf
     */
    public void to(ByteBuf byteBuf) {
        encodeData();
        if (length == 0) {
            length = 16 + (data == null ? 0 : data.length);
        }
        byteBuf.writeIntLE(toInt(deviceId));
        byteBuf.writeIntLE(toInt(length));
        byteBuf.writeIntLE(toInt(protocol));
        byteBuf.writeIntLE(toInt(flag));
        if (data != null && data.length > 0) {
            byteBuf.writeBytes(data);
        }
    }

    /**
     * 重写此方法,将相关的字段组装成 byte[] 并赋值给 data
     */
    public void encodeData() {
    }

    /**
     * 重写此方法,将 byte[] 解析到子类的字段中
     */
    public void decodeData() {
    }
}