jiazx0107@163.com
2023-12-29 5fc84fec1dd242571328bbd9321a47a7adcfcb1f
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
package com.fzzy.protocol.bhzn.v0.server;
 
 
import com.fzzy.api.utils.BytesUtil;
import com.fzzy.protocol.bhzn.server.BhznGrainV2ServerUtils;
import com.ld.io.api.IoSession;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * 工具类
 *
 * @author vince
 */
public class BhznGrainV0ServerUtils {
 
 
    /**
     * 记录每个连接的最后一次信息时间 key = 连接的KYE,data =当前时间戳
     */
    public static Map<String, Long> contextMapHeart = new HashMap<>();
 
 
    public static int HEART_BEAT_TIME = 30;//心跳间隔时间
 
 
    public static String MSG_START = "3C42485A4E3E";//<BHZN>
    public static String MSG_START2 = "AA";
    public static String MSG_END = "<END>";//<END>
    public static String MSG_END_16 = "3C454E443E";//<END>
    public static final String CHARSET = "UTF-8";
 
 
    /**
     * 针对无线粮情主机的默认ID配置
     */
    public static String DEFAULT_MAC_ID = "53681";
 
    public static String FUNCTION_ID_00 = "00";
    public static String FUNCTION_ID_F1 = "F1";
    public static String FUNCTION_ID_F2 = "F2";
    public static String FUNCTION_ID_83 = "83";
    public static String FUNCTION_ID_93 = "93";
    public static String FUNCTION_ID_92 = "92";
 
 
    /**
     * 生成TCP连接的KEY
     *
     * @param ip
     * @param port
     * @return
     */
    public static String getServerKey(String ip, Integer port) {
        return ip + ":" + port;
    }
 
 
    /**
     * 添加最新心跳时间戳
     *
     * @param session
     */
    public static void addHeartBeat(IoSession session) {
        contextMapHeart.put(getServerKey(session.getAddress(), session.getPort()), System.currentTimeMillis());
    }
 
    public static Long getHearBeat(IoSession session) {
        return contextMapHeart.get(getServerKey(session.getAddress(), session.getPort()));
    }
 
 
    /**
     * 计算校验
     *
     * @param content
     * @return
     */
    public static String getCheck(String content) {
        int start = BhznGrainV2ServerUtils.MSG_START.length() + BhznGrainV2ServerUtils.MSG_START2.length();
        content = content.substring(start);
        int sum = 0;
        String hex;
        for (int i = 0; i < content.length() / 2; i++) {
            hex = content.substring(i * 2, i * 2 + 2);
            sum += BytesUtil.hexToInt(hex);
        }
        String hexSum = BytesUtil.intToHexStr(sum);
        int check = BytesUtil.hexToInt(hexSum.substring(hexSum.length() - 2));
 
        return BytesUtil.intToHexStr(256 - check).substring(2);
    }
}