MessageHandler.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. package com.zksy.radar.utils;
  2. import static com.zksy.common.utils.CollectionSideEffects.*;
  3. import com.zksy.api.domain.AlarmData;
  4. import com.zksy.api.domain.WarningThreshold;
  5. import com.zksy.api.scheduling.RefreshableOfflineCheckTask;
  6. import com.zksy.api.service.AlarmDataService;
  7. import com.zksy.api.service.EarlyWarningAutoService;
  8. import com.zksy.api.service.EquipmentStatusApiService;
  9. import com.zksy.api.service.WarningThresholdService;
  10. import com.zksy.api.utils.AlarmLevelUtil;
  11. import com.zksy.api.utils.SmsUtil;
  12. import com.zksy.common.exception.InvalidMessageException;
  13. import com.zksy.radar.domain.RadarData;
  14. import com.zksy.radar.service.RadarDataService;
  15. import com.zksy.api.service.DeviceContactService;
  16. import io.netty.buffer.ByteBuf;
  17. import io.netty.util.ReferenceCountUtil;
  18. import io.netty.buffer.Unpooled;
  19. import io.netty.channel.ChannelHandler;
  20. import io.netty.channel.ChannelHandlerContext;
  21. import io.netty.channel.ChannelInboundHandlerAdapter;
  22. import io.netty.handler.timeout.ReadTimeoutException;
  23. import lombok.extern.slf4j.Slf4j;
  24. import org.slf4j.Logger;
  25. import org.slf4j.LoggerFactory;
  26. import org.springframework.beans.factory.annotation.Autowired;
  27. import org.springframework.stereotype.Component;
  28. import java.math.BigDecimal;
  29. import java.time.LocalDateTime;
  30. import java.util.List;
  31. import java.util.Map;
  32. @ChannelHandler.Sharable
  33. @Slf4j
  34. @Component
  35. public class MessageHandler extends ChannelInboundHandlerAdapter {
  36. private static Logger logger = LoggerFactory.getLogger(MessageHandler.class);
  37. private final RadarDataService service;
  38. private final WarningThresholdService warningThresholdService;
  39. private final AlarmDataService alarmDataService;
  40. private final EarlyWarningAutoService earlyWarningAutoService;
  41. private final SmsUtil smsUtil;
  42. private final DeviceContactService devicePhoneFetchUtil;
  43. @Autowired
  44. private DeviceOfflineCheckTask deviceOfflineCheckTask;
  45. @Autowired
  46. private EquipmentStatusApiService equipmentStatusApiService;
  47. @Autowired
  48. public MessageHandler(RadarDataService RadarDataService, WarningThresholdService warningThresholdService,
  49. AlarmDataService alarmDataService, EarlyWarningAutoService earlyWarningAutoService,
  50. SmsUtil smsUtil, DeviceContactService devicePhoneFetchUtil) {
  51. this.service = RadarDataService;
  52. this.warningThresholdService = warningThresholdService;
  53. this.alarmDataService = alarmDataService;
  54. this.earlyWarningAutoService = earlyWarningAutoService;
  55. this.smsUtil = smsUtil;
  56. this.devicePhoneFetchUtil = devicePhoneFetchUtil;
  57. }
  58. @Override
  59. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  60. super.channelActive(ctx);
  61. //sendDataToDevice(ctx);
  62. }
  63. @Override
  64. public void channelRead(ChannelHandlerContext ctx, Object msg) {
  65. try {
  66. ByteBuf in = (ByteBuf) msg;
  67. byte[] msgBytes = new byte[in.readableBytes()];
  68. in.readBytes(msgBytes);
  69. logger.debug("接收到的原始数据帧: {}", printHexBinary(msgBytes));
  70. // 提取帧类型
  71. byte frameType = msgBytes[6];
  72. logger.debug("帧类型: 0x{}", String.format("%02X", frameType));
  73. // 1. 完整协议校验
  74. DataParser.validateMessage(msgBytes);
  75. logger.info("数据帧校验通过");
  76. // 2. 数据解析
  77. RadarData resultData = DataParser.parseMessage(msgBytes);
  78. if (resultData.getSystemIdentifier() == null) {
  79. resultData.setSystemIdentifier("123456");
  80. }
  81. // 3. 根据帧类型处理
  82. if (frameType == 0x31) {
  83. if (msgBytes.length > 34) {
  84. byte flagByte = msgBytes[34];
  85. String binary = String.format("%8s", Integer.toBinaryString(flagByte & 0xFF)).replace(' ', '0');
  86. boolean isEnd = (flagByte & 0x08) != 0;
  87. logger.debug("结束位检测: 字节=0x{}, 二进制={}, 第5位(结束标识)={}",
  88. String.format("%02X", flagByte), binary, isEnd ? "1(结束)" : "0(未结束)");
  89. } else {
  90. logger.warn("数据长度不足,无法检测结束位");
  91. }
  92. // 入库
  93. requireSaved(service.save(resultData));
  94. String deviceCode = resultData.getDeviceCode();
  95. run(deviceCode, "接收时间更新", () ->
  96. RefreshableOfflineCheckTask.deviceLastReceiveTimeMap.put(deviceCode, new java.util.Date()));
  97. run(deviceCode, "采集应答", () -> {
  98. byte[] response = ProtocolUtils.buildCustomReplyFrame(msgBytes);
  99. ctx.writeAndFlush(Unpooled.copiedBuffer(response));
  100. if (Boolean.TRUE.equals(resultData.getIsLastPacket())) {
  101. byte[] endResponse = ProtocolUtils.buildEndReplyFrame(msgBytes);
  102. ctx.executor().schedule(() -> run(deviceCode, "结束应答", () -> {
  103. if (ctx.channel().isActive()) {
  104. ctx.writeAndFlush(Unpooled.copiedBuffer(endResponse));
  105. }
  106. }), 1, java.util.concurrent.TimeUnit.SECONDS);
  107. }
  108. });
  109. run(deviceCode, "在线状态同步", () -> deviceOfflineCheckTask.markDeviceOnline(deviceCode));
  110. run(deviceCode, "报警预警评估", () -> handleRadarAlarm(resultData));
  111. } else if (frameType == 0x34) {
  112. /*logger.info("收到结束通讯帧,准备发送回应包");
  113. byte[] response = ProtocolUtils.buildShutdownAckPacket(msgBytes);
  114. ctx.writeAndFlush(Unpooled.copiedBuffer(response));
  115. logger.debug("已发送结束通讯回应包");*/
  116. } else {
  117. logger.warn("收到未知帧类型: 0x{}", String.format("%02X", frameType));
  118. }
  119. } catch (InvalidMessageException e) {
  120. logger.error("数据校验失败,不入库: {}", e.getMessage());
  121. sendErrorResponse(ctx, "数据校验失败");
  122. } catch (Exception e) {
  123. logger.error("数据解析或入库异常", e);
  124. sendErrorResponse(ctx, "数据处理异常");
  125. } finally {
  126. ReferenceCountUtil.release(msg);
  127. }
  128. }
  129. // 工具方法:发送错误响应
  130. private void sendErrorResponse(ChannelHandlerContext ctx, String msg) {
  131. ctx.writeAndFlush(Unpooled.copiedBuffer(("数据处理失败: " + msg).getBytes()));
  132. }
  133. private String printHexBinary(byte[] bytes) {
  134. StringBuilder sb = new StringBuilder();
  135. for (byte b : bytes) {
  136. sb.append(String.format("%02X ", b));
  137. }
  138. logger.info("Received raw data: " + sb.toString());
  139. return sb.toString();
  140. }
  141. @Override
  142. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  143. if (cause instanceof ReadTimeoutException) {
  144. logger.info("来自" + ctx.channel().remoteAddress() + "的连接超时断开");
  145. } else {
  146. logger.error("设备连接异常", cause);
  147. logger.info("来自" + ctx.channel().remoteAddress() + "的连接异常断开");
  148. ctx.close();
  149. }
  150. }
  151. @Override
  152. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  153. ctx.flush();
  154. }
  155. @Override
  156. public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
  157. logger.info("来自" + ctx.channel().remoteAddress() + "的连接主动断开");
  158. ctx.fireChannelUnregistered();
  159. }
  160. // 主动向设备发送数据
  161. public void sendDataToDevice(ChannelHandlerContext ctx) {
  162. try {
  163. // 将字符串形式的十六进制数据转换为字节数组
  164. String hexData = "01 03 00 00 00 01 84 0A ";
  165. String[] hexArray = hexData.split(" ");
  166. byte[] dataBytes = new byte[hexArray.length];
  167. for (int i = 0; i < hexArray.length; i++) {
  168. dataBytes[i] = (byte) Integer.parseInt(hexArray[i], 16);
  169. }
  170. ByteBuf byteBuf = Unpooled.copiedBuffer(dataBytes);
  171. ctx.writeAndFlush(byteBuf);
  172. logger.info("已向设备发送数据: {}", printHexBinary(dataBytes));
  173. } catch (Exception e) {
  174. logger.error("发送数据失败: {}", e.getMessage());
  175. }
  176. }
  177. /**
  178. * 处理雷达设备告警
  179. */
  180. private void handleRadarAlarm(RadarData resultData) {
  181. String deviceCode = resultData.getDeviceCode();
  182. Integer status = alarmStatus(
  183. handleAlarm(deviceCode, "WARN-INSTANT-FLOW", "瞬时流量", resultData.getMeter1InstantFlow()),
  184. handleAlarm(deviceCode, "WARN-FLOW-SPEED", "流速", resultData.getFlowSpeed()),
  185. handleAlarm(deviceCode, "WARN-WATER-LEVEL", "水位", resultData.getWaterLevel()));
  186. if (status != null) {
  187. updateDeviceAlarmStatus(deviceCode, status);
  188. }
  189. }
  190. /**
  191. * 处理单个告警
  192. * @return 是否触发告警
  193. */
  194. private Boolean handleAlarm(String deviceCode, String warningCode, String defaultType, String valueStr) {
  195. if (valueStr == null) {
  196. return null;
  197. }
  198. return evaluate(deviceCode, warningCode, () -> {
  199. BigDecimal actual = new BigDecimal(valueStr);
  200. WarningThreshold threshold = warningThresholdService.getWarningThresholdByDeviceAndCode(deviceCode, warningCode);
  201. if (threshold == null || (threshold.getMinValue() == null && threshold.getMaxValue() == null)) {
  202. throw new IllegalStateException("阈值缺失,不能判断设备已恢复正常");
  203. }
  204. String type = defaultType;
  205. BigDecimal min = threshold.getMinValue() == null ? null : BigDecimal.valueOf(threshold.getMinValue());
  206. BigDecimal max = threshold.getMaxValue() == null ? null : BigDecimal.valueOf(threshold.getMaxValue());
  207. boolean over = (min != null && actual.compareTo(min) <= 0) || (max != null && actual.compareTo(max) >= 0);
  208. if (over) {
  209. run(deviceCode, warningCode + ":报警入库及通知", () -> saveAlarmData(deviceCode, type, warningCode, min, max, actual, null));
  210. run(deviceCode, warningCode + ":关闭预警", () -> earlyWarningAutoService.closeAutoWarning(deviceCode, warningCode, "已达报警阈值,转报警处理"));
  211. } else {
  212. run(deviceCode, warningCode + ":告警恢复", () -> alarmDataService.recoverThresholdAlarm(deviceCode, warningCode, min, max, actual));
  213. run(deviceCode, warningCode + ":生成预警", () -> earlyWarningAutoService.checkAndGenerate(deviceCode, type, warningCode, min, max, actual, null));
  214. }
  215. return over;
  216. });
  217. }
  218. /**
  219. * 保存告警数据到 alarm_data 表
  220. */
  221. private void saveAlarmData(String deviceCode, String warningType, String warningCode,
  222. BigDecimal minValue, BigDecimal maxValue, BigDecimal actualValue, String remark) {
  223. try {
  224. AlarmData alarmData = new AlarmData();
  225. alarmData.setDeviceCode(deviceCode);
  226. alarmData.setWarningCode(warningCode);
  227. alarmData.setMinValue(minValue);
  228. alarmData.setMaxValue(maxValue);
  229. alarmData.setActualValue(actualValue);
  230. int alarmLevel = AlarmLevelUtil.calculateLevel(actualValue, minValue, maxValue);
  231. BigDecimal deviationRatio = AlarmLevelUtil.calculateDeviationRatio(actualValue, minValue, maxValue);
  232. alarmData.setAlarmLevel(alarmLevel);
  233. alarmData.setDeviationRatio(deviationRatio);
  234. alarmData.setAlarmStatus(0);
  235. alarmData.setCreateTime(LocalDateTime.now());
  236. alarmData.setCreateTime(LocalDateTime.now());
  237. boolean saved = run(deviceCode, warningCode + ":报警入库", () -> requireSaved(alarmDataService.saveAlarmData(alarmData)));
  238. if (saved) { logger.info("告警数据入库成功: deviceCode={}, warningCode={}, level={}级", deviceCode, warningCode, alarmLevel); }
  239. if (alarmLevel == 1) {
  240. logger.warn("【1级紧急告警】deviceCode={}, warningCode={}, deviationRatio={}%",
  241. deviceCode, warningCode, deviationRatio);
  242. sendAlarmSms(deviceCode, warningType, actualValue, minValue, maxValue);
  243. }
  244. } catch (Exception e) {
  245. logger.error("保存告警数据失败", e);
  246. }
  247. }
  248. private void sendAlarmSms(String deviceCode, String warningType, BigDecimal actualValue,
  249. BigDecimal minValue, BigDecimal maxValue) {
  250. try {
  251. List<String> phoneList = devicePhoneFetchUtil.getPhoneListByDeviceCode(deviceCode);
  252. if (phoneList == null || phoneList.isEmpty()) {
  253. logger.warn("报警短信发送失败:未找到设备{}的维护人员手机号", deviceCode);
  254. return;
  255. }
  256. com.alibaba.fastjson.JSONObject params = new com.alibaba.fastjson.JSONObject();
  257. params.put("deviceNo", deviceCode);
  258. params.put("alarmType", warningType);
  259. params.put("location", "当前值:" + actualValue + ",正常范围:" + minValue + "~" + maxValue);
  260. Map<String, Boolean> result = smsUtil.sendBatchSms(phoneList, params.toJSONString());
  261. long successCount = result.values().stream().filter(Boolean::booleanValue).count();
  262. logger.info("1级告警短信发送完成,成功{}条,失败{}条", successCount, phoneList.size() - successCount);
  263. } catch (Exception e) {
  264. logger.error("发送报警短信异常: {}", e.getMessage());
  265. }
  266. }
  267. /**
  268. * 更新设备报警状态
  269. * @param deviceCode 设备编码
  270. * @param alarmStatus 报警状态:0-正常,1-报警
  271. */
  272. private void updateDeviceAlarmStatus(String deviceCode, int alarmStatus) {
  273. try {
  274. if (equipmentStatusApiService.updateAlarmStatus(deviceCode, alarmStatus)) {
  275. logger.info("设备报警状态更新成功: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus);
  276. } else {
  277. logger.warn("设备报警状态更新未成功: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus);
  278. }
  279. } catch (Exception e) {
  280. logger.error("更新设备报警状态失败: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus, e);
  281. }
  282. }
  283. }