Dock-MultiCtrl/admin/src/main/java/com/multictrl/common/utils/HmsUtils.java

106 lines
3.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.multictrl.common.utils;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* HMS健康告警工具类
*
* @author Sdy
* @since 1.0.0 2026/5/10
*/
@Slf4j
@Component
public class HmsUtils {
private static final String HMS_CONFIG_PATH = "dji/hms.json";
private static final String ZH_FIELD = "zh";
private static final String KEY_DELIMITER = "_";
/**
* 转换后的 HMS 映射key = 第三段(如 0x1BA10004), value = 中文文本
*/
private static Map<String, String> hmsMap;
@PostConstruct
private void init() {
hmsMap = loadAndTransformHms();
}
//加载并转换 HMS 配置
private Map<String, String> loadAndTransformHms() {
JSONObject rawJson = loadRawJson();
if (rawJson == null || rawJson.isEmpty()) {
log.warn("大疆 hms.json 为空或加载失败,返回空映射");
return Collections.emptyMap();
}
log.info("大疆 hms.json 加载成功,原始条目数:{}", rawJson.size());
Map<String, String> result = new HashMap<>();
for (String key : rawJson.keySet()) {
String[] parts = key.split(KEY_DELIMITER);
// 格式要求:至少三段,如 "fpv_tip_0x1BA10004"
if (parts.length < 3) {
log.debug("跳过格式不正确的key: {}", key);
continue;
}
String code = parts[2]; // 取第三段作为映射的key
JSONObject data = rawJson.getJSONObject(key);
if (data != null && data.containsKey(ZH_FIELD)) {
String zhText = data.getStr(ZH_FIELD);
if (zhText != null && !zhText.isEmpty()) {
result.put(code, zhText);
} else {
log.debug("key: {} 的中文文本为空", key);
}
} else {
log.debug("key: {} 缺少'zh'字段", key);
}
}
log.info("转换完成,有效条目数:{}", result.size());
return Collections.unmodifiableMap(result); // 返回只读视图,防止后续意外修改
}
//仅负责从 classpath 读取并解析 JSON返回原始 JSONObject
private JSONObject loadRawJson() {
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(HMS_CONFIG_PATH)) {
if (inputStream == null) {
log.error("资源文件不存在: {}", HMS_CONFIG_PATH);
return null;
}
try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
JSONObject json = JSONUtil.parseObj(reader);
if (json == null) {
log.error("解析 hms.json 结果为 null");
}
return json;
}
} catch (IOException e) {
log.error("读取或解析 hms.json 失败", e);
return null;
}
}
/**
* 根据 HMS 代码查找对应的中文文本
*/
public static String getHmsText(String code) {
if (hmsMap.containsKey(code)) {
return hmsMap.get(code);
}
return "未知错误";
}
}