Browse Source

fix(manhole): 修复井盖倾斜告警判定逻辑及帧解析问题

- 修正 DeviceFrameDecoder 中 0x4520 标签字节数从 4 改为 3,避免正常上报帧被误判为坏帧丢弃
- 将倾斜角度告警从设备上报状态判定改为基于阈值表的数值型判定
- 新增 checkTiltAlarmByThreshold 方法,支持越限报警、告警恢复和自动预警生成
- 引入 WarningThresholdService 和 EarlyWarningAutoService 依赖实现阈值配置与预警联动
- 按偏差率计算告警等级,单侧阈值配置时补齐计算基线
- 倾斜角度值缺失或阈值未配置时抛异常保留上次报警状态,避免误判恢复
林仔 2 weeks ago
parent
commit
07c4560895

+ 60 - 8
manhole-service/src/main/java/com/zksy/manhole/service/impl/ManholeDataServiceImpl.java

@@ -3,7 +3,11 @@ package com.zksy.manhole.service.impl;
 import static com.zksy.common.utils.CollectionSideEffects.*;
 
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.zksy.api.domain.WarningThreshold;
 import com.zksy.api.service.AlarmDataService;
+import com.zksy.api.service.EarlyWarningAutoService;
+import com.zksy.api.service.WarningThresholdService;
+import com.zksy.api.utils.EarlyWarningLevelUtil;
 import com.zksy.manhole.domain.ManholeData;
 import com.zksy.manhole.mapper.ManholeDataMapper;
 import com.zksy.manhole.service.ManholeDataService;
@@ -29,9 +33,15 @@ public class ManholeDataServiceImpl extends ServiceImpl<ManholeDataMapper, Manho
     private AlarmUtil alarmUtil;
     @Autowired
     private AlarmDataService alarmDataService;
+    @Autowired
+    private WarningThresholdService warningThresholdService;
+    @Autowired
+    private EarlyWarningAutoService earlyWarningAutoService;
 
-    /** 倾斜角度告警编码 */
+    /** 倾斜角度告警编码,同时作为阈值表的预警编码 */
     private static final String WARN_CODE_TILT = "WARN-TILT";
+    /** 倾斜预警类型名称(写入 early_warning 展示用) */
+    private static final String TILT_WARNING_TYPE = "倾斜预警";
     /** 水浸告警编码 */
     private static final String WARN_CODE_WATER_INFILTRATION = "WARN-WATER-INFILTRATION";
     /** 水位告警编码 */
@@ -50,16 +60,14 @@ public class ManholeDataServiceImpl extends ServiceImpl<ManholeDataMapper, Manho
 
     /**
      * 检查并保存告警数据
-     * 井盖的报警全部由采集过来的数据字段直接判断,无需查询阈值表:
-     * - alarmStatus:倾斜角度报警状态(0正常,1报警)
-     * - waterInfiltrationAlarmStatus:水浸报警状态(0正常,1报警)
-     * - waterLevelAlarmStatus:水位报警状态(0正常,1报警)
-     * 均为状态型告警,告警即为1级
+     * - 倾斜角度:按阈值表 WARN-TILT 配置的阈值判定,超过阈值即报警(数值型,等级按偏差率计算);
+     * - 水浸、水位:仍由设备上报的状态字段直接判断(0正常,1报警),状态型告警即为1级。
      */
     private void checkAndSaveAlarm(ManholeData result) {
         String deviceCode = result.getImeiCardNumber();
         Integer status = alarmStatus(
-                handleReportedAlarm(deviceCode, result.getAlarmStatus(), "倾斜预警", WARN_CODE_TILT, parseTiltAngle(result.getTiltAngle()), "井盖倾斜报警"),
+                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, "井盖水位报警"));
         if (status != null) {
@@ -67,6 +75,50 @@ public class ManholeDataServiceImpl extends ServiceImpl<ManholeDataMapper, Manho
         }
     }
 
+    /**
+     * 按阈值表判定本次倾斜角度:越限写报警并关闭自动预警;未越限则处理告警恢复,
+     * 并在接近阈值时生成/更新自动预警、回到安全区时由 checkAndGenerate 关闭。
+     *
+     * @return true 越限报警,false 正常/恢复;阈值未配置或角度值缺失时抛异常,
+     *         由 evaluate 返回 null 以保留设备上一次报警状态,避免误判恢复/预警。
+     */
+    private boolean checkTiltAlarmByThreshold(String deviceCode, String tiltAngle) {
+        if (warningThresholdService == null || earlyWarningAutoService == null) {
+            throw new IllegalStateException("倾斜阈值预警依赖未注入");
+        }
+        BigDecimal actual = parseTiltAngle(tiltAngle);
+        if (actual == null) {
+            throw new IllegalArgumentException("采集报文缺少有效倾斜角度,无法判定报警状态: tiltAngle=" + tiltAngle);
+        }
+        WarningThreshold threshold = warningThresholdService
+                .getWarningThresholdByDeviceAndCode(deviceCode, WARN_CODE_TILT);
+        if (threshold == null || (threshold.getMinValue() == null && threshold.getMaxValue() == null)) {
+            throw new IllegalStateException("井盖倾斜角度阈值未配置,无法判定报警状态: deviceCode=" + deviceCode);
+        }
+
+        BigDecimal min = threshold.getMinValue() == null ? null : BigDecimal.valueOf(threshold.getMinValue());
+        BigDecimal max = threshold.getMaxValue() == null ? null : BigDecimal.valueOf(threshold.getMaxValue());
+        // 单侧阈值补齐等级计算基线:倾斜角度非负,仅配上限时下限取 0;仅配下限时上限取两倍下限,
+        // 保证只配一侧时按偏差率定级仍有可比区间(与消防压力/可燃气体处理一致)。
+        BigDecimal levelMin = min != null ? min : BigDecimal.ZERO;
+        BigDecimal levelMax = max != null ? max : (min == null ? null : min.multiply(BigDecimal.valueOf(2)));
+
+        if (EarlyWarningLevelUtil.isOverThreshold(actual, min, max)) {
+            run(deviceCode, WARN_CODE_TILT + ":报警入库", () -> alarmUtil.saveAlarm(
+                    deviceCode, TILT_WARNING_TYPE, WARN_CODE_TILT, levelMin, levelMax, actual, "井盖倾斜角度超阈值报警"));
+            run(deviceCode, WARN_CODE_TILT + ":关闭预警",
+                    () -> earlyWarningAutoService.closeAutoWarning(deviceCode, WARN_CODE_TILT, "已达报警阈值,转报警处理"));
+            return true;
+        }
+
+        run(deviceCode, WARN_CODE_TILT + ":告警恢复",
+                () -> alarmDataService.recoverThresholdAlarm(deviceCode, WARN_CODE_TILT, levelMin, levelMax, actual));
+        run(deviceCode, WARN_CODE_TILT + ":生成预警",
+                () -> earlyWarningAutoService.checkAndGenerate(deviceCode, TILT_WARNING_TYPE, WARN_CODE_TILT,
+                        levelMin, levelMax, actual, null));
+        return false;
+    }
+
     private Boolean handleReportedAlarm(String deviceCode, String flag, String type, String code,
                                         BigDecimal actualValue, String remark) {
         if (!"0".equals(flag) && !"1".equals(flag)) {
@@ -87,7 +139,7 @@ public class ManholeDataServiceImpl extends ServiceImpl<ManholeDataMapper, Manho
         try {
             return new BigDecimal(tiltAngle.trim());
         } catch (NumberFormatException e) {
-            log.warn("井盖倾斜角度不是有效数值,告警仍保留但实际值为空: tiltAngle={}", tiltAngle);
+            log.warn("井盖倾斜角度不是有效数值,跳过本次阈值评估: tiltAngle={}", tiltAngle);
             return null;
         }
     }

+ 152 - 149
zk-common/src/main/java/com/zksy/common/netty/DeviceFrameDecoder.java

@@ -1,149 +1,152 @@
-package com.zksy.common.netty;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.ByteToMessageDecoder;
-import java.util.List;
-
-/** 每条连接独立累积报文;校验失败只丢弃坏帧,不关闭设备连接。 */
-public final class DeviceFrameDecoder extends ByteToMessageDecoder {
-    public enum Protocol { PINGSHENG, MANHOLE, GAS, FIRE_PRESSURE }
-    private static final int MAX_FRAME = 8192;
-    private final Protocol protocol;
-
-    public DeviceFrameDecoder(Protocol protocol) { this.protocol = protocol; }
-
-    @Override
-    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
-        int minimum = protocol == Protocol.MANHOLE ? 72 : 5;
-        while (in.readableBytes() >= minimum) {
-            int start = in.readerIndex();
-            int length;
-            if (protocol == Protocol.PINGSHENG) {
-                if (in.getUnsignedMedium(start) != 0x123456) { in.skipBytes(1); continue; }
-                length = in.getUnsignedShort(start + 3);
-                if (length < 10 || length > MAX_FRAME) { in.skipBytes(1); continue; }
-                if (in.readableBytes() < length) {
-                    // 长度字段损坏时,寻找后续完整且两层校验通过的上报帧。
-                    int next = nextPingshengFrame(in, start + 3);
-                    if (next < 0) return;
-                    in.readerIndex(next);
-                    continue;
-                }
-                int xor = 0;
-                for (int i = 0; i < length; i++) xor ^= in.getUnsignedByte(start + i);
-                if (xor != 0) { in.skipBytes(1); continue; }
-            } else if (protocol == Protocol.MANHOLE) {
-                // 井盖帧:前72字节参与CRC16,最后2字节为小端CRC,整帧74字节。
-                length = 74;
-                if (crc(in, start, 72) != in.getUnsignedShortLE(start + 72)) { in.skipBytes(1); continue; }
-            } else if (protocol == Protocol.GAS) {
-                // 协议:7E + 2 字节长度(帧类型→校验07)+ 数据 + 校验07 + 校验16,总长 = 长度字段 + 4。
-                // 数据项数量随设备上报内容变化(5 项无经纬度、7 项含经纬度),帧长不能写死。
-                if (in.getUnsignedByte(start) != 0x7E) { in.skipBytes(1); continue; }
-                length = in.getUnsignedShort(start + 1) + 4;
-                if (length < 20 || length > MAX_FRAME) { in.skipBytes(1); continue; }
-                if (in.readableBytes() < length) {
-                    if (in.readableBytes() >= MAX_FRAME) { in.skipBytes(1); continue; }
-                    return;
-                }
-                if (in.getUnsignedByte(start + 15) != 0xAA || !gasChecksum(in, start, length)) {
-                    in.skipBytes(1);
-                    continue;
-                }
-            } else {
-                if (in.getUnsignedShort(start) != 0x7E7E) { in.skipBytes(1); continue; }
-                // 现有消防设备长度字段不作为可信边界,使用结束符 + 完整CRC确认边界。
-                // 不能单靠03分隔:日期、TLV和压力数据中也可能出现03。
-                length = fireLength(in, start);
-                if (length == 0) {
-                    // 坏帧后可能紧接新报文,不能让坏CRC永久阻塞下一条有效数据。
-                    boolean recovered = false;
-                    for (int next = start + 2; next + 16 < in.writerIndex(); next++) {
-                        if (in.getUnsignedShort(next) == 0x7E7E && fireLength(in, next) > 0) {
-                            in.readerIndex(next);
-                            recovered = true;
-                            break;
-                        }
-                    }
-                    if (recovered) continue;
-                    if (in.readableBytes() >= MAX_FRAME) { in.skipBytes(1); continue; }
-                    return;
-                }
-            }
-            out.add(in.readRetainedSlice(length));
-        }
-    }
-
-    private static boolean gasChecksum(ByteBuf in, int start, int frameLen) {
-        int body = 0, full = 0;
-        for (int i = 16; i < frameLen - 2; i++) body += in.getUnsignedByte(start + i);
-        for (int i = 3; i < frameLen - 1; i++) full += in.getUnsignedByte(start + i);
-        return (body & 255) == in.getUnsignedByte(start + frameLen - 2)
-                && ((255 - full) & 255) == in.getUnsignedByte(start + frameLen - 1);
-    }
-
-    private static int nextPingshengFrame(ByteBuf in, int from) {
-        for (int start = from; start + 10 <= in.writerIndex(); start++) {
-            if (in.getUnsignedMedium(start) != 0x123456) continue;
-            int length = in.getUnsignedShort(start + 3);
-            if (length < 14 || length > MAX_FRAME || start + length > in.writerIndex()
-                    || in.getUnsignedByte(start + 6) != 0x31) continue;
-            int xor = 0;
-            for (int i = 0; i < length; i++) xor ^= in.getUnsignedByte(start + i);
-            if (xor != 0) continue;
-            int src = (in.getUnsignedByte(start + 7) + 1) / 2;
-            int destIndex = start + 8 + src;
-            if (src == 0 || src > 10 || destIndex >= start + length - 3) continue;
-            int dest = (in.getUnsignedByte(destIndex) + 1) / 2;
-            int body = destIndex + 1 + dest;
-            if (dest > 10 || body + 2 >= start + length - 3) continue;
-            if (crc(in, body, start + length - 3 - body) == in.getUnsignedShortLE(start + length - 3)) return start;
-        }
-        return -1;
-    }
-
-    private static int fireLength(ByteBuf in, int start) {
-        if (in.writerIndex() - start < 14) return 0;
-        if (in.getUnsignedByte(start + 10) != 0xEF) {
-            // 上报数据固定头之后按TLV跨过值区,值中偶然的03+CRC不能作为帧尾。
-            int cursor = start + 37;
-            int limit = Math.min(in.writerIndex(), start + MAX_FRAME);
-            while (cursor + 3 <= limit) {
-                int marker = in.getUnsignedByte(cursor);
-                if (marker == 0x03 || marker == 0x17) {
-                    return crc(in, start, cursor - start + 1) == in.getUnsignedShort(cursor + 1)
-                            ? cursor - start + 3 : 0;
-                }
-                int tag = in.getUnsignedShort(cursor);
-                int bytes = (in.getUnsignedByte(cursor + 2) >>> 3) & 31;
-                if (bytes == 0 && tag == 0x581A) bytes = 2;
-                if (bytes == 0 && tag == 0x4520) bytes = 4;
-                cursor += 3 + bytes;
-            }
-            return 0;
-        }
-        int value = 0xFFFF;
-        int end = Math.min(in.writerIndex() - 2, start + MAX_FRAME - 2);
-        for (int i = start; i < end; i++) {
-            value = crcByte(value, in.getUnsignedByte(i));
-            int marker = in.getUnsignedByte(i);
-            // 消防现有crc16Tall以高字节在前追加CRC。
-            if (i >= start + 14 && (marker == 0x03 || marker == 0x17)
-                    && value == in.getUnsignedShort(i + 1)) return i - start + 3;
-        }
-        return 0;
-    }
-
-    private static int crc(ByteBuf in, int start, int length) {
-        int value = 0xFFFF;
-        for (int i = 0; i < length; i++) value = crcByte(value, in.getUnsignedByte(start + i));
-        return value;
-    }
-
-    private static int crcByte(int value, int b) {
-        value ^= b;
-        for (int i = 0; i < 8; i++) value = (value & 1) == 1 ? (value >>> 1) ^ 0xA001 : value >>> 1;
-        return value;
-    }
-}
+package com.zksy.common.netty;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.ByteToMessageDecoder;
+import java.util.List;
+
+/** 每条连接独立累积报文;校验失败只丢弃坏帧,不关闭设备连接。 */
+public final class DeviceFrameDecoder extends ByteToMessageDecoder {
+    public enum Protocol { PINGSHENG, MANHOLE, GAS, FIRE_PRESSURE }
+    private static final int MAX_FRAME = 8192;
+    private final Protocol protocol;
+
+    public DeviceFrameDecoder(Protocol protocol) { this.protocol = protocol; }
+
+    @Override
+    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
+        int minimum = protocol == Protocol.MANHOLE ? 72 : 5;
+        while (in.readableBytes() >= minimum) {
+            int start = in.readerIndex();
+            int length;
+            if (protocol == Protocol.PINGSHENG) {
+                if (in.getUnsignedMedium(start) != 0x123456) { in.skipBytes(1); continue; }
+                length = in.getUnsignedShort(start + 3);
+                if (length < 10 || length > MAX_FRAME) { in.skipBytes(1); continue; }
+                if (in.readableBytes() < length) {
+                    // 长度字段损坏时,寻找后续完整且两层校验通过的上报帧。
+                    int next = nextPingshengFrame(in, start + 3);
+                    if (next < 0) return;
+                    in.readerIndex(next);
+                    continue;
+                }
+                int xor = 0;
+                for (int i = 0; i < length; i++) xor ^= in.getUnsignedByte(start + i);
+                if (xor != 0) { in.skipBytes(1); continue; }
+            } else if (protocol == Protocol.MANHOLE) {
+                // 井盖帧:前72字节参与CRC16,最后2字节为小端CRC,整帧74字节。
+                length = 74;
+                if (crc(in, start, 72) != in.getUnsignedShortLE(start + 72)) { in.skipBytes(1); continue; }
+            } else if (protocol == Protocol.GAS) {
+                // 协议:7E + 2 字节长度(帧类型→校验07)+ 数据 + 校验07 + 校验16,总长 = 长度字段 + 4。
+                // 数据项数量随设备上报内容变化(5 项无经纬度、7 项含经纬度),帧长不能写死。
+                if (in.getUnsignedByte(start) != 0x7E) { in.skipBytes(1); continue; }
+                length = in.getUnsignedShort(start + 1) + 4;
+                if (length < 20 || length > MAX_FRAME) { in.skipBytes(1); continue; }
+                if (in.readableBytes() < length) {
+                    if (in.readableBytes() >= MAX_FRAME) { in.skipBytes(1); continue; }
+                    return;
+                }
+                if (in.getUnsignedByte(start + 15) != 0xAA || !gasChecksum(in, start, length)) {
+                    in.skipBytes(1);
+                    continue;
+                }
+            } else {
+                if (in.getUnsignedShort(start) != 0x7E7E) { in.skipBytes(1); continue; }
+                // 现有消防设备长度字段不作为可信边界,使用结束符 + 完整CRC确认边界。
+                // 不能单靠03分隔:日期、TLV和压力数据中也可能出现03。
+                length = fireLength(in, start);
+                if (length == 0) {
+                    // 坏帧后可能紧接新报文,不能让坏CRC永久阻塞下一条有效数据。
+                    boolean recovered = false;
+                    for (int next = start + 2; next + 16 < in.writerIndex(); next++) {
+                        if (in.getUnsignedShort(next) == 0x7E7E && fireLength(in, next) > 0) {
+                            in.readerIndex(next);
+                            recovered = true;
+                            break;
+                        }
+                    }
+                    if (recovered) continue;
+                    if (in.readableBytes() >= MAX_FRAME) { in.skipBytes(1); continue; }
+                    return;
+                }
+            }
+            out.add(in.readRetainedSlice(length));
+        }
+    }
+
+    private static boolean gasChecksum(ByteBuf in, int start, int frameLen) {
+        int body = 0, full = 0;
+        for (int i = 16; i < frameLen - 2; i++) body += in.getUnsignedByte(start + i);
+        for (int i = 3; i < frameLen - 1; i++) full += in.getUnsignedByte(start + i);
+        return (body & 255) == in.getUnsignedByte(start + frameLen - 2)
+                && ((255 - full) & 255) == in.getUnsignedByte(start + frameLen - 1);
+    }
+
+    private static int nextPingshengFrame(ByteBuf in, int from) {
+        for (int start = from; start + 10 <= in.writerIndex(); start++) {
+            if (in.getUnsignedMedium(start) != 0x123456) continue;
+            int length = in.getUnsignedShort(start + 3);
+            if (length < 14 || length > MAX_FRAME || start + length > in.writerIndex()
+                    || in.getUnsignedByte(start + 6) != 0x31) continue;
+            int xor = 0;
+            for (int i = 0; i < length; i++) xor ^= in.getUnsignedByte(start + i);
+            if (xor != 0) continue;
+            int src = (in.getUnsignedByte(start + 7) + 1) / 2;
+            int destIndex = start + 8 + src;
+            if (src == 0 || src > 10 || destIndex >= start + length - 3) continue;
+            int dest = (in.getUnsignedByte(destIndex) + 1) / 2;
+            int body = destIndex + 1 + dest;
+            if (dest > 10 || body + 2 >= start + length - 3) continue;
+            if (crc(in, body, start + length - 3 - body) == in.getUnsignedShortLE(start + length - 3)) return start;
+        }
+        return -1;
+    }
+
+    private static int fireLength(ByteBuf in, int start) {
+        if (in.writerIndex() - start < 14) return 0;
+        if (in.getUnsignedByte(start + 10) != 0xEF) {
+            // 上报数据固定头之后按TLV跨过值区,值中偶然的03+CRC不能作为帧尾。
+            int cursor = start + 37;
+            int limit = Math.min(in.writerIndex(), start + MAX_FRAME);
+            while (cursor + 3 <= limit) {
+                int marker = in.getUnsignedByte(cursor);
+                if (marker == 0x03 || marker == 0x17) {
+                    return crc(in, start, cursor - start + 1) == in.getUnsignedShort(cursor + 1)
+                            ? cursor - start + 3 : 0;
+                }
+                int tag = in.getUnsignedShort(cursor);
+                int bytes = (in.getUnsignedByte(cursor + 2) >>> 3) & 31;
+                if (bytes == 0 && tag == 0x581A) bytes = 2;
+                // 开关量 4520 的值区固定为 3 字节(结束符 03/17 紧随其后)。
+                // 此前按 4 字节跨步会越过结束符,导致正常上报帧被判为坏帧丢弃,
+                // 与 DataParser 中 4520 取值的协议约定保持一致。
+                if (bytes == 0 && tag == 0x4520) bytes = 3;
+                cursor += 3 + bytes;
+            }
+            return 0;
+        }
+        int value = 0xFFFF;
+        int end = Math.min(in.writerIndex() - 2, start + MAX_FRAME - 2);
+        for (int i = start; i < end; i++) {
+            value = crcByte(value, in.getUnsignedByte(i));
+            int marker = in.getUnsignedByte(i);
+            // 消防现有crc16Tall以高字节在前追加CRC。
+            if (i >= start + 14 && (marker == 0x03 || marker == 0x17)
+                    && value == in.getUnsignedShort(i + 1)) return i - start + 3;
+        }
+        return 0;
+    }
+
+    private static int crc(ByteBuf in, int start, int length) {
+        int value = 0xFFFF;
+        for (int i = 0; i < length; i++) value = crcByte(value, in.getUnsignedByte(start + i));
+        return value;
+    }
+
+    private static int crcByte(int value, int b) {
+        value ^= b;
+        for (int i = 0; i < 8; i++) value = (value & 1) == 1 ? (value >>> 1) ^ 0xA001 : value >>> 1;
+        return value;
+    }
+}