BaseModel.java
2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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 protocol;
protected long flag;
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.setProtocol(firstInt);
model.setFlag(secondInt);
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;
}
public static byte[] toBytes(int n) {
byte[] b = new byte[4];
b[3] = (byte) (n & 0xff);
b[2] = (byte) (n >> 8 & 0xff);
b[1] = (byte) (n >> 16 & 0xff);
b[0] = (byte) (n >> 24 & 0xff);
return b;
}
/**
* 将 model 转换为 byteBuf
*
* @return byteBuf
*/
public void to(ByteBuf byteBuf) {
encodeData();
byteBuf.writeInt(toInt(deviceId));
byteBuf.writeInt(toInt(length));
byteBuf.writeInt(toInt(protocol));
byteBuf.writeInt(toInt(flag));
if (data != null && data.length > 0) {
byteBuf.writeBytes(data);
}
}
/**
* 重写此方法,将相关的字段组装成 byte[] 并赋值给 data
*/
public void encodeData() {
}
/**
* 重写此方法,将 byte[] 解析到子类的字段中
*/
public void decodeData() {
}
}