2021与蓝度共同重构项目,服务端
liuhaonan
2021-12-09 43fb2ac961d450659a270f1db9053ec545327aa1
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
package com.sandu.ximon.admin.manager.iot.rrpc.util;
 
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import com.sandu.ximon.admin.manager.iot.rrpc.dto.CommonFrame;
 
/**
 * @author chenjiantian
 * @date 2021/12/3 17:36
 */
public class FrameUtils {
 
    /**
     * 把上报的内容 转化成帧实体类
     * @param value 上报内容 {{@link com.sandu.ximon.admin.manager.iot.rrpc.dto.CommonReportMessage.Params}}
     * @return 帧实体类
     */
    public static CommonFrame transformMessageToFrame(String value) {
        String hex = decodeReportMessage(value);
        if (hex == null || hex.length() < 18) {
            return null;
        }
        //  将十六进制数转为大写
        hex = hex.toUpperCase();
        CommonFrame frame = new CommonFrame();
        // MQTT通信方式(1)
        frame.setConnectType(hex.substring(0, 2));
        //  功能码(1)
        frame.setFunctionCode(hex.substring(2, 4));
        //  命令类型(1)
        frame.setOrderType(hex.substring(4, 6));
        //  负荷长度(2)
        frame.setPayloadLength(hex.substring(6, 10));
        //  响应payload
        frame.setPayload(hex.substring(10, hex.length() - 8));
        //  校验码(4)
        frame.setCrc32(hex.substring(hex.length() - 8));
        //  判断校验是否通过
        String content = hex.substring(2, hex.length() - 8);
        frame.setValidate(CRC32Utils.validateFrame(content, frame.getCrc32()));
 
        return frame;
    }
 
    public static void main(String[] args) {
        System.out.println(transformMessageToFrame("/qWEACrwAQAi//8BAQEYAB4CAAAAAAAAAApcAAAAEAAVAAAAAwAQAagAAMPfU3KbHyny").toString());
    }
 
    /**
     * 将设备上报的内容解码
     *
     * @param value 设备上报的内容
     * @return 解码后的内容,16进制
     */
    public static String decodeReportMessage(String value) {
        if (StrUtil.isBlank(value)) {
            return null;
        }
        byte[] decode = Base64.decode(value.getBytes());
        return HexUtil.encodeHexStr(decode);
    }
 
    /**
     * 将准备发送的内容编码
     * @param value 待编码内容
     * @return 编码后的内容 字符串
     */
    public static String encodeReportMessage(String value) {
        if (StrUtil.isBlank(value)) {
            return null;
        }
        byte[] bytes = HexUtil.decodeHex(value);
        String encode = Base64.encode(bytes);
        return encode;
    }
}