Parcourir la source

报警恢复逻辑优化

zengy il y a 3 jours
Parent
commit
afd0dac70e

+ 30 - 13
environment-service/src/main/java/com/zksy/environment/config/RSServerService.java

@@ -23,8 +23,10 @@ import java.math.BigDecimal;
 import java.text.SimpleDateFormat;
 import java.time.LocalDateTime;
 import java.util.Date;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
@@ -243,6 +245,12 @@ public class RSServerService {
             return;
         }
         String deviceId = String.valueOf(data.getDeviceId());
+        List<String> applicableCodes = thresholdEvaluationService.findApplicableWarningCodes(deviceId);
+        if (applicableCodes == null || applicableCodes.isEmpty()) {
+            log.warn("设备未绑定环境类预警指标,跳过报警状态覆盖: deviceCode={}", deviceId);
+            return;
+        }
+        Set<String> evaluatedCodes = new HashSet<>();
         // 只有包含有效监测值的上报才能刷新在线时间;空节点/无效值不能无限续期。
         boolean receivedValidNode = false;
         boolean hasAlarm = false;
@@ -314,29 +322,38 @@ public class RSServerService {
             try {
                 Integer nodeId = nd.getNodeId();
                 // ====================== 报警/预警处理 ======================
-                BigDecimal actual = new BigDecimal(Float.toString(finalValue));
-                if (nodeId == 1) {
-                    hasAlarm |= evaluateMetric(deviceId, "WARN-SUSPENDED-SOLIDS", actual);
-                } else if (nodeId == 2) {
-                    hasAlarm |= evaluateMetric(deviceId, "WARN-COD", actual);
-                } else if (nodeId == 3) {
-                    hasAlarm |= evaluateMetric(deviceId, "WARN-AMMONIA-NITROGEN", actual);
-                } else if (nodeId == 4) {
-                    hasAlarm |= evaluateMetric(deviceId, "WARN-CONDUCTIVITY", actual);
-                } else if (nodeId == 5) {
-                    hasAlarm |= evaluateMetric(deviceId, "WARN-PH", actual);
+                String warningCode = warningCodeOfNode(nodeId);
+                if (warningCode == null || !applicableCodes.contains(warningCode)) {
+                    continue;
                 }
+                BigDecimal actual = new BigDecimal(Float.toString(finalValue));
+                hasAlarm |= evaluateMetric(deviceId, warningCode, actual);
+                evaluatedCodes.add(warningCode);
             } catch (Exception e) {
                 evaluationCompleted = false;
                 log.error("环境报警评估失败: deviceCode={}, nodeId={}", deviceId, nd.getNodeId(), e);
             }
         }
-        // 同步设备报警状态到 equipment_status 表
-        if (hasAlarm || evaluationCompleted) {
+        // 同步设备报警状态到 equipment_status 表:全部绑定指标均评估完成且正常才清零
+        if (hasAlarm || (evaluationCompleted && evaluatedCodes.containsAll(applicableCodes))) {
             updateDeviceAlarmStatus(deviceId, hasAlarm ? 1 : 0);
         }
     }
 
+    private String warningCodeOfNode(Integer nodeId) {
+        if (nodeId == null) {
+            return null;
+        }
+        switch (nodeId) {
+            case 1: return "WARN-SUSPENDED-SOLIDS";
+            case 2: return "WARN-COD";
+            case 3: return "WARN-AMMONIA-NITROGEN";
+            case 4: return "WARN-CONDUCTIVITY";
+            case 5: return "WARN-PH";
+            default: return null;
+        }
+    }
+
     /** 分级阈值判断与写库统一交给 zk-api-service,服务内只保留一级报警短信。 */
     private boolean evaluateMetric(String deviceCode, String warningCode, BigDecimal actual) {
         ThresholdEvaluationResult result = thresholdEvaluationService.evaluate(

+ 20 - 5
manhole-service/src/main/java/com/zksy/manhole/service/impl/ManholeDataServiceImpl.java

@@ -15,6 +15,8 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
 
 /**
  * 井盖数据Service业务层处理
@@ -59,11 +61,24 @@ public class ManholeDataServiceImpl extends ServiceImpl<ManholeDataMapper, Manho
      */
     private void checkAndSaveAlarm(ManholeData result) {
         String deviceCode = result.getImeiCardNumber();
-        Integer status = alarmStatus(
-                evaluate(deviceCode, WARN_CODE_TILT + ":倾斜阈值评估",
-                        () -> checkTiltAlarmByThreshold(deviceCode, result.getTiltAngle())),
-                handleReportedAlarm(deviceCode, result.getWaterInfiltrationAlarmStatus(), "水浸预警", WARN_CODE_WATER_INFILTRATION, null, "井盖水浸报警"),
-                handleReportedAlarm(deviceCode, result.getWaterLevelAlarmStatus(), "窨井水位预警", WARN_WATER_MANHOLE_LEVEL, null, "井盖水位报警"));
+        List<String> applicableCodes = thresholdEvaluationService.findApplicableWarningCodes(deviceCode);
+        if (applicableCodes == null || applicableCodes.isEmpty()) {
+            return;
+        }
+        List<Boolean> results = new ArrayList<>();
+        if (applicableCodes.contains(WARN_CODE_TILT)) {
+            results.add(evaluate(deviceCode, WARN_CODE_TILT + ":倾斜阈值评估",
+                    () -> checkTiltAlarmByThreshold(deviceCode, result.getTiltAngle())));
+        }
+        if (applicableCodes.contains(WARN_CODE_WATER_INFILTRATION)) {
+            results.add(handleReportedAlarm(deviceCode, result.getWaterInfiltrationAlarmStatus(),
+                    "水浸预警", WARN_CODE_WATER_INFILTRATION, null, "井盖水浸报警"));
+        }
+        if (applicableCodes.contains(WARN_WATER_MANHOLE_LEVEL)) {
+            results.add(handleReportedAlarm(deviceCode, result.getWaterLevelAlarmStatus(),
+                    "窨井水位预警", WARN_WATER_MANHOLE_LEVEL, null, "井盖水位报警"));
+        }
+        Integer status = alarmStatus(results.toArray(new Boolean[0]));
         if (status != null) {
             run(deviceCode, "报警状态同步", () -> alarmUtil.updateDeviceAlarmStatus(deviceCode, status));
         }

+ 16 - 4
radar-service/src/main/java/com/zksy/radar/utils/MessageHandler.java

@@ -26,6 +26,7 @@ import org.springframework.stereotype.Component;
 
 import java.math.BigDecimal;
 import java.time.LocalDateTime;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 
@@ -194,10 +195,21 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
 		 */
     private void handleRadarAlarm(RadarData resultData) {
         String deviceCode = resultData.getDeviceCode();
-        Integer status = alarmStatus(
-                handleAlarm(deviceCode, "WARN-INSTANT-FLOW", resultData.getMeter1InstantFlow()),
-                handleAlarm(deviceCode, "WARN-FLOW-SPEED", resultData.getFlowSpeed()),
-                handleAlarm(deviceCode, "WARN-WATER-LEVEL-OUTLET", resultData.getWaterLevel()));
+        List<String> applicableCodes = thresholdEvaluationService.findApplicableWarningCodes(deviceCode);
+        if (applicableCodes == null || applicableCodes.isEmpty()) {
+            return;
+        }
+        List<Boolean> results = new ArrayList<>();
+        if (applicableCodes.contains("WARN-INSTANT-FLOW")) {
+            results.add(handleAlarm(deviceCode, "WARN-INSTANT-FLOW", resultData.getMeter1InstantFlow()));
+        }
+        if (applicableCodes.contains("WARN-FLOW-SPEED")) {
+            results.add(handleAlarm(deviceCode, "WARN-FLOW-SPEED", resultData.getFlowSpeed()));
+        }
+        if (applicableCodes.contains("WARN-WATER-LEVEL-OUTLET")) {
+            results.add(handleAlarm(deviceCode, "WARN-WATER-LEVEL-OUTLET", resultData.getWaterLevel()));
+        }
+        Integer status = alarmStatus(results.toArray(new Boolean[0]));
         if (status != null) {
             updateDeviceAlarmStatus(deviceCode, status);
         }

+ 16 - 4
telemetry-service/src/main/java/com/zksy/telemetry/utils/MessageHandler.java

@@ -24,6 +24,7 @@ import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
+import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
@@ -138,10 +139,21 @@ public class MessageHandler extends ChannelInboundHandlerAdapter {
      */
     private void evaluateTelemetry(TelemetryData data) {
         String deviceCode = resolveDeviceCode(data);
-        Integer status = alarmStatus(
-                evaluateMetric(deviceCode, "WARN-PRESSURE", "供水压力", data.getPressure()),
-                evaluateMetric(deviceCode, "WARN-INSTANT-FLOW-SUPPLY", "供水瞬时流量", data.getMeter1InstantFlow()),
-                evaluateMetric(deviceCode, "WARN-FLOW-SPEED-SUPPLY", "供水流速", data.getFlowSpeed()));
+        List<String> applicableCodes = thresholdEvaluationService.findApplicableWarningCodes(deviceCode);
+        if (applicableCodes == null || applicableCodes.isEmpty()) {
+            return;
+        }
+        List<Boolean> results = new ArrayList<>();
+        if (applicableCodes.contains("WARN-PRESSURE")) {
+            results.add(evaluateMetric(deviceCode, "WARN-PRESSURE", "供水压力", data.getPressure()));
+        }
+        if (applicableCodes.contains("WARN-INSTANT-FLOW-SUPPLY")) {
+            results.add(evaluateMetric(deviceCode, "WARN-INSTANT-FLOW-SUPPLY", "供水瞬时流量", data.getMeter1InstantFlow()));
+        }
+        if (applicableCodes.contains("WARN-FLOW-SPEED-SUPPLY")) {
+            results.add(evaluateMetric(deviceCode, "WARN-FLOW-SPEED-SUPPLY", "供水流速", data.getFlowSpeed()));
+        }
+        Integer status = alarmStatus(results.toArray(new Boolean[0]));
         if (status != null) {
             run(deviceCode, "报警状态同步", () -> deviceNotifier.updateAlarmStatus(deviceCode, status));
         }

+ 26 - 0
zk-api-service/src/main/java/com/zksy/api/mapper/EquipmentWarningTypeBindingMapper.java

@@ -0,0 +1,26 @@
+package com.zksy.api.mapper;
+
+import org.apache.ibatis.annotations.Mapper;
+import org.apache.ibatis.annotations.Param;
+import org.apache.ibatis.annotations.Select;
+
+import java.util.List;
+
+/**
+ * 设备类型与预警指标绑定关系(equipment_warning_type)。
+ *
+ * <p>采集侧如需组合多个指标,必须以该表为准,不允许在代码里写死。
+ * warning_type.id=4 的历史编码 WARN-WATER-LEVEL 与 WARN-WATER-LEVEL-OUTLET 同时存在时,
+ * 以绑定表实际关联的编码为准。</p>
+ */
+@Mapper
+public interface EquipmentWarningTypeBindingMapper {
+
+    @Select("SELECT DISTINCT wt.warning_code "
+            + "FROM app_user.equipment_warning_type ewt "
+            + "JOIN app_user.warning_type wt ON wt.id = ewt.warning_type_id "
+            + "WHERE ewt.equipment_type_id = #{equipmentTypeId} "
+            + "AND wt.warning_code IS NOT NULL AND wt.warning_code <> '' "
+            + "ORDER BY wt.warning_code")
+    List<String> selectWarningCodesByEquipmentType(@Param("equipmentTypeId") Integer equipmentTypeId);
+}

+ 13 - 1
zk-api-service/src/main/java/com/zksy/api/service/ThresholdEvaluationService.java

@@ -5,6 +5,7 @@ import com.zksy.api.domain.dto.ThresholdLevelValue;
 
 import java.math.BigDecimal;
 import java.time.LocalDateTime;
+import java.util.List;
 
 /**
  * 普通数值型指标的分级阈值评估入口。
@@ -20,11 +21,22 @@ public interface ThresholdEvaluationService {
      * @param warningCode 预警/报警编码
      * @param actualValue 本次采集值
      * @param sampleTime  采样时间;为空时使用当前时间匹配生效时段
-     * @return 评估结果;无配置时状态为 NO_CONFIG且不产生任何写操作
+     * @return 评估结果;无配置时状态为 NO_CONFIG 且不产生任何写操作
      */
     ThresholdEvaluationResult evaluate(String deviceCode, String warningCode,
                                        BigDecimal actualValue, LocalDateTime sampleTime);
 
+    /**
+     * 查询设备类型绑定的预警指标编码。
+     *
+     * <p>采集服务不得写死“一个设备对应哪些指标”,必须按 equipment_warning_type
+     * 关联结果决定本次要评估并组合的指标。</p>
+     *
+     * @param deviceCode 设备编码或设备ID
+     * @return 该设备类型绑定的 warning_code 列表;设备或绑定不存在时返回空列表
+     */
+    List<String> findApplicableWarningCodes(String deviceCode);
+
     /**
      * 只读解析设备的报警阈值级别,不写 alarm_data / early_warning。
      * 复合规则(如音频漏失)据此取得新表中的越限与恢复阈值后自行判定。

+ 22 - 0
zk-api-service/src/main/java/com/zksy/api/service/impl/ThresholdEvaluationServiceImpl.java

@@ -9,6 +9,7 @@ import com.zksy.api.domain.WarningThresholdLevel;
 import com.zksy.api.domain.dto.ThresholdEvaluationResult;
 import com.zksy.api.domain.dto.ThresholdLevelValue;
 import com.zksy.api.mapper.EquipmentBaseApiMapper;
+import com.zksy.api.mapper.EquipmentWarningTypeBindingMapper;
 import com.zksy.api.mapper.WarningThresholdConfigMapper;
 import com.zksy.api.mapper.WarningThresholdLevelMapper;
 import com.zksy.api.mapper.WarningTypeApiMapper;
@@ -24,6 +25,7 @@ import java.math.BigDecimal;
 import java.time.LocalDateTime;
 import java.time.LocalTime;
 import java.time.format.DateTimeFormatter;
+import java.util.Collections;
 import java.util.Comparator;
 import java.util.List;
 import java.util.Map;
@@ -39,6 +41,7 @@ public class ThresholdEvaluationServiceImpl implements ThresholdEvaluationServic
     private final WarningThresholdConfigMapper configMapper;
     private final WarningThresholdLevelMapper levelMapper;
     private final EquipmentBaseApiMapper equipmentBaseMapper;
+    private final EquipmentWarningTypeBindingMapper warningTypeBindingMapper;
     private final WarningTypeApiMapper warningTypeMapper;
     private final AlarmDataService alarmDataService;
     private final EarlyWarningAutoService earlyWarningAutoService;
@@ -47,12 +50,14 @@ public class ThresholdEvaluationServiceImpl implements ThresholdEvaluationServic
     public ThresholdEvaluationServiceImpl(WarningThresholdConfigMapper configMapper,
                                           WarningThresholdLevelMapper levelMapper,
                                           EquipmentBaseApiMapper equipmentBaseMapper,
+                                          EquipmentWarningTypeBindingMapper warningTypeBindingMapper,
                                           WarningTypeApiMapper warningTypeMapper,
                                           AlarmDataService alarmDataService,
                                           EarlyWarningAutoService earlyWarningAutoService) {
         this.configMapper = configMapper;
         this.levelMapper = levelMapper;
         this.equipmentBaseMapper = equipmentBaseMapper;
+        this.warningTypeBindingMapper = warningTypeBindingMapper;
         this.warningTypeMapper = warningTypeMapper;
         this.alarmDataService = alarmDataService;
         this.earlyWarningAutoService = earlyWarningAutoService;
@@ -117,6 +122,23 @@ public class ThresholdEvaluationServiceImpl implements ThresholdEvaluationServic
         return result;
     }
 
+    @Override
+    public List<String> findApplicableWarningCodes(String deviceCode) {
+        if (isBlank(deviceCode)) {
+            return Collections.emptyList();
+        }
+        EquipmentBase device = equipmentBaseMapper.selectOne(
+                Wrappers.lambdaQuery(EquipmentBase.class)
+                        .and(wrapper -> wrapper.eq(EquipmentBase::getEquipmentId, deviceCode)
+                                .or().eq(EquipmentBase::getEquipmentCode, deviceCode))
+                        .last("LIMIT 1"));
+        if (device == null || device.getEquipmentTypeId() == null) {
+            return Collections.emptyList();
+        }
+        List<String> codes = warningTypeBindingMapper.selectWarningCodesByEquipmentType(device.getEquipmentTypeId());
+        return codes == null ? Collections.emptyList() : codes;
+    }
+
     @Override
     public ThresholdLevelValue resolveAlarmThreshold(String deviceCode, String warningCode,
                                                      LocalDateTime sampleTime) {