张世豪
13 小时以前 2eea735fd4ddf0ae047687780271ef3962d256cc
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
package Mqttmessage.Util;
 
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import Mqttmessage.Entity.GPSData;
import Mqttmessage.Entity.ResponseData;
 
/**
 * 设备消息解析工具类 - 支持GPS数据、状态数据和响应数据的解析
 */
public class DeviceMessageParser {
 
    private static final ObjectMapper objectMapper = new ObjectMapper();
 
    static {
        // 配置ObjectMapper
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
 
 
    /**
     * 解析为GPS数据对象(支持新协议格式,包含GPS、IMU和状态数据)
     * @param jsonStr JSON字符串
     * @return GPSData对象
     * @throws JsonProcessingException 解析异常
     */
    public static GPSData parseGPSData(String jsonStr) throws JsonProcessingException {
        GPSData gpsData = objectMapper.readValue(jsonStr, GPSData.class);
 
        // 可选:解析GGA数据
       /* if (gpsData.getGps_raw() != null && gpsData.getGps_raw().startsWith("$GNGGA")) {
            GPSData.GGAData ggaData = parseGGA(gpsData.getGps_raw());
            gpsData.setGgaData(ggaData);
        }*/
 
        return gpsData;
    }
 
 
 
    /**
     * 解析为响应数据对象
     * @param jsonStr JSON字符串
     * @return ResponseData对象
     * @throws JsonProcessingException 解析异常
     */
    public static ResponseData parseResponseData(String jsonStr) throws JsonProcessingException {
        return objectMapper.readValue(jsonStr, ResponseData.class);
    }
 
 
 
    /**
     * 将消息对象转换为JSON字符串
     * @param message 消息对象(GPSData、StatusData或ResponseData)
     * @return JSON字符串
     * @throws JsonProcessingException 转换异常
     */
    public static String toJson(Object message) throws JsonProcessingException {
        return objectMapper.writeValueAsString(message);
    }
 
    /**
     * 获取ObjectMapper实例(用于高级操作)
     * @return ObjectMapper实例
     */
    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }
 
    /**
     * 消息类型枚举
     */
    public enum MessageType {
        GPS("gps"),
        STATUS("status"),
        RESPONSE("response");
 
        private final String type;
 
        MessageType(String type) {
            this.type = type;
        }
 
        public String getType() {
            return type;
        }
 
        public static MessageType fromString(String type) {
            for (MessageType mt : MessageType.values()) {
                if (mt.type.equalsIgnoreCase(type)) {
                    return mt;
                }
            }
            throw new IllegalArgumentException("未知的消息类型: " + type);
        }
    }
}