#
whycq
2024-08-12 2583078fdf32b87da154b1594f3e616a77824175
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
package com.example.agvcontroller.protocol;
 
import java.util.logging.Logger;
 
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
 
/**
 * 编码器
 * 此解码器将会生成校验码
 * 处理方式: 异或和
 * Created by vincent on 2019-04-02
 */
//@Component
@ChannelHandler.Sharable
public class ProtocolEncoder extends MessageToByteEncoder<Object> {
 
    //private static final Logger log = LoggerFactory.getLogger(ProtocolEncoder.class);
 
    //@Autowired
    private SystemProperties systemProperties;
 
    @Override
    protected void encode(ChannelHandlerContext ctx, Object obj, ByteBuf out) {
 
        if (obj instanceof ByteBuf){
            out.writeBytes((ByteBuf) obj);
 
        } else if (obj instanceof byte[]){
            out.writeBytes((byte[]) obj);
 
        } else if (obj instanceof AgvPackage){
 
            AgvPackage pac = (AgvPackage)obj;
 
 
 
            byte[] bodyBytes = pac.getBody().getMessageBody().writeToBytes();   // body
 
            //String uniqueNo = pac.getHeader().getUniqueNo();
 
                //byte[] uniquenoBytes = RadixTools.intToBytes(Integer.parseInt(pac.getHeader().getUniqueNo()));   // uniqueno
 
 
            int len = PackagePart.UNIQUENO.getLen()     // len
                    + PackagePart.TIMESTAMP.getLen()
                    + PackagePart.COMMAND_MARK.getLen()
                    + bodyBytes.length;
 
            //out.writeByte(pac.getHeader().getStartSymbol())         // symbol
            //        .writeShortLE(len)
            //        .writeBytes(Utils.reverse(uniquenoBytes))       // uniqueno
            //        .writeIntLE((int) (System.currentTimeMillis() / 1000))   // timestamp
            //        .writeByte(pac.getHeader().getProtocolType().getCode()) // type
            //        .writeBytes(bodyBytes)                          // body
            //        .writeShort(pac.getValidCode())                 // valid
            //;
 
            pac.setValidCode(ValidUtil.calculateValidByteFromBuff(out));
            out.resetReaderIndex();
 
            out.writerIndex(out.readableBytes() - 2);
            out.writeShortLE(pac.getValidCode());
 
 
            if (systemProperties.isPrintPacLog()){
                //log.info("Agv [{}] 下行 [{}] >>> {}", uniqueNo, pac.getHeader().getProtocolType().getDes(), ByteBufUtil.hexDump(out).toUpperCase());
            }
 
        }
 
 
    }
 
// EE | 11 00 | 01 00 00 00 | 0C AB 12 64 | F0  | 01 00 | 01 01 | 00 00 00 00 | 4C F7
// #  | len   | uniqueno    | timestamp   | cmd | content                     | crc
 
}