15928045575 2 年之前
父节点
当前提交
ffcf64db3e

+ 6 - 0
slope-common/slope-common-redis/src/main/java/com/sckw/redis/constant/RedisConstant.java

@@ -93,6 +93,12 @@ public class RedisConstant {
     public static final String LOGISTICS_ORDER_SUBCONTRACT_KEY = "order:logistics:no:subcontract:%s";
 
 
+    /**
+     * mqtt-key
+     */
+    public static final String MQ_CONSUMER_ALARM_KEY = "mqtt:consumer:alarm:%s";
+
+
     /**
      * 消费请求有效时间(秒)
      */

+ 7 - 3
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/common/config/mqtt/MqttConfig.java

@@ -1,5 +1,7 @@
 package com.sckw.slope.detection.common.config.mqtt;
 
+import com.sckw.core.model.constant.NumberConstant;
+import com.sckw.core.utils.IdWorker;
 import com.sckw.slope.detection.consumer.MqttCallbackHandler;
 import com.sckw.slope.detection.consumer.mqApi.MqttApiHandler;
 import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
@@ -153,9 +155,10 @@ public class MqttConfig {
     @Bean
     @ServiceActivator(inputChannel = CHANNEL_NAME_OUT)
     public MessageHandler mqttOutbound() {
+        String substring = String.valueOf(new IdWorker(NumberConstant.ONE).nextId()).substring(2, 10);
         //创建消息处理器
         MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
-                clientId + "_pub",
+                clientId + "_pub" + substring,
                 senderMqttClientFactory());
         //设置消息处理类型为异步
         messageHandler.setAsync(true);
@@ -185,9 +188,10 @@ public class MqttConfig {
     public MessageProducer inbound() {
 //        System.out.println("topics:" + msgTopic);
         // 可以同时消费(订阅)多个Topic
+        String substring = String.valueOf(new IdWorker(NumberConstant.ONE).nextId()).substring(2, 10);
         MqttPahoMessageDrivenChannelAdapter adapter =
                 new MqttPahoMessageDrivenChannelAdapter(
-                        clientId + "_sub", senderMqttClientFactory(), msgReceiveTopic.split(","));
+                        clientId + substring + "_sub", senderMqttClientFactory(), msgReceiveTopic.split(","));
         adapter.setCompletionTimeout(5000);
         adapter.setConverter(new DefaultPahoMessageConverter());
         adapter.setQos(0);
@@ -210,7 +214,7 @@ public class MqttConfig {
     public MessageHandler handler() {
         System.out.println("mqtt是否消费:" + isConsume);
         return message -> {
-            if ("false".equals(isConsume)) {
+            if (!"true".equals(isConsume)) {
                 return;
             }
             String topic = message.getHeaders().get("mqtt_receivedTopic").toString();

+ 149 - 132
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/consumer/MqttCallbackHandler.java

@@ -13,8 +13,11 @@ import com.sckw.core.model.enums.DictItemEnum;
 import com.sckw.core.utils.CollectionUtils;
 import com.sckw.core.utils.DateUtils;
 import com.sckw.core.utils.IdWorker;
+import com.sckw.core.utils.PasswordUtils;
 import com.sckw.core.web.response.HttpResult;
 import com.sckw.log.TraceLog.TraceLog;
+import com.sckw.redis.config.RedisLockUtil;
+import com.sckw.redis.constant.RedisConstant;
 import com.sckw.redis.utils.RedissonUtils;
 import com.sckw.slope.detection.common.config.SmsTemplateConfig;
 import com.sckw.slope.detection.dao.mysql.*;
@@ -86,6 +89,9 @@ public class MqttCallbackHandler extends AbstractHandler {
     @Autowired
     SmsTemplateConfig smsTemplateConfig;
 
+    @Autowired
+    RedisLockUtil redisLockUtil;
+
     @TraceLog(description = "处理system/iot/device_data_slope")
     @DSTransactional
     public HttpResult handle(String topic, String payload) {
@@ -101,145 +107,134 @@ public class MqttCallbackHandler extends AbstractHandler {
 //        String deviceMsgId = objects.getString("msg_id");
 //        String deviceRawTs = objects.getString("raw_ts");
 //        JSONArray checkArr = objects.getJSONArray("check_arr");
-        try {
+        String key = PasswordUtils.md5(topic + "alarm" + payload);
+        String alarmKey = String.format(RedisConstant.MQ_CONSUMER_ALARM_KEY, key);
+        boolean flag = redisLockUtil.tryLock(alarmKey, 5);
+        if (flag) {
+            try {
 //            DevicesAlarm devicesAlarm = JSONObject.parseObject(payload, DevicesAlarm.class);
-            String deviceCode = devicesAlarm.getGuid();
-            List<KwsDevice> deviceList = deviceMapper.selectList(new LambdaQueryWrapper<KwsDevice>()
-                    .eq(KwsDevice::getSnCodeFullName, deviceCode)
-                    .eq(KwsDevice::getDelFlag, NumberConstant.ZERO)
-            );
-            KwsDevice device = null;
-            if (!org.springframework.util.CollectionUtils.isEmpty(deviceList)) {
-                device = deviceList.get(0);
-            }
-            if (device == null) {
-                log.error("接收处理数据:{}", payload);
-                log.error("设备数据并未维护+[" + devicesAlarm.getGuid() + "],不做处理");
-                return null;
-            }
-            List<DevicesItem> devicesItemList = devicesAlarm.getDevicesItemList();
-            if (!CollectionUtils.isEmpty(devicesItemList)) {
-                HashMap<Object, Object> devicesItemMap = devicesItemList.stream().collect(HashMap::new,
-                        (m, v) -> m.put(v.getItemName(), v.getItemValue()), HashMap::putAll);
-                String time = "";
-                long timeDate = 0L;
-                //2023-11-30 22:00:00
-                if (devicesItemMap != null) {
-                    if (Objects.nonNull(devicesItemMap.get("time"))) {
-                        time = String.valueOf(devicesItemMap.get("time").toString());
-                        timeDate = DateUtils.formatDate(time).getTime() / 1000L;
-                    }
+                String deviceCode = devicesAlarm.getGuid();
+                List<KwsDevice> deviceList = deviceMapper.selectList(new LambdaQueryWrapper<KwsDevice>()
+                        .eq(KwsDevice::getSnCodeFullName, deviceCode)
+                        .eq(KwsDevice::getDelFlag, NumberConstant.ZERO)
+                );
+                KwsDevice device = null;
+                if (!org.springframework.util.CollectionUtils.isEmpty(deviceList)) {
+                    device = deviceList.get(0);
                 }
-                for (DevicesItem devicesItem : devicesItemList) {
-                    String itemName = devicesItem.getItemName();
-                    String itemValue = devicesItem.getItemValue();
-                    List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
-                            .eq(KwsThreshold::getDeviceId, device.getId())
-                            .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
-                            .eq(KwsThreshold::getItemName, itemName)
-                    );
-                    if (org.springframework.util.CollectionUtils.isEmpty(kwsThresholds)) {
-                        continue;
+                if (device == null) {
+                    log.error("接收处理数据:{}", payload);
+                    log.error("设备数据并未维护+[" + devicesAlarm.getGuid() + "],不做处理");
+                    return null;
+                }
+                List<DevicesItem> devicesItemList = devicesAlarm.getDevicesItemList();
+                if (!CollectionUtils.isEmpty(devicesItemList)) {
+                    HashMap<Object, Object> devicesItemMap = devicesItemList.stream().collect(HashMap::new,
+                            (m, v) -> m.put(v.getItemName(), v.getItemValue()), HashMap::putAll);
+                    String time = "";
+                    long timeDate = 0L;
+                    //2023-11-30 22:00:00
+                    if (devicesItemMap != null) {
+                        if (Objects.nonNull(devicesItemMap.get("time"))) {
+                            time = String.valueOf(devicesItemMap.get("time").toString());
+                            timeDate = DateUtils.formatDate(time).getTime() / 1000L;
+                        }
                     }
-                    Long ts = 0L != timeDate ? timeDate : devicesAlarm.getTs();
-//                    //获取到是 十位 1700970600
-//                    if (Objects.nonNull(ts)) {
-//                        ts = ts * 1000;
-//                    }
-                    //判断是否满足设备超时离线报警
-//                    checkDeviceAlarm(deviceCode, device, itemValue, ts);
-                    //判断是否满足数值超阈值报警
-                    Map<String, String> map = checkThresholdAlarm(devicesItem, kwsThresholds, device);
-                    if ("2".equals(map.get("flag"))) {
-                        Long level = Long.valueOf(map.get("level"));
-                        Long thresholdId = Long.valueOf(map.get("thresholdId"));
-                        String offset = map.get("offset");
-//                        /**x、y、z要进行偏移量计算  其他数值保持源数据进行计算*/
-//                        List<String> checkItemName = new ArrayList<>();
-//                        checkItemName.add(DictItemEnum.ALTITUDE_Z.getValue());
-//                        checkItemName.add(DictItemEnum.LONGITUDE_X.getValue());
-//                        checkItemName.add(DictItemEnum.LATITUDE_Y.getValue());
-//                        String itemValueAndUnit = "";
-//                        String url = "";
-//                        if (checkItemName.contains(itemName)) {
-//
-//                            itemValueAndUnit = StringUtils.isBlank(url) ? itemValue : (itemValue + url);
-//                        } else {
-//                            url = dictByDictCode.get(itemName) == null ? null : dictByDictCode.get(itemName).getRemark();
-//                            itemValueAndUnit = StringUtils.isBlank(url) ? itemValue : (itemValue + url);
-//                        }
-                        //阈值表以及明细表存储
-                        long id = insertAlarmAndDetail(level, device, thresholdId, offset, ts, AlarmTitleEnum.ALARM_TITLE_TWO.getStatus(), AlarmTypeEnum.ALARM_ONE.getCode());
-                        //todo 不适用redis存统计  使用新字段处理
-                        /**阈值次数存redis*/
-//                        redisPutAlarmCount(id);
-                        /*【露天矿山边坡监测系统】尊敬的管理员,2023-10-01 12:23:34监测到一级告警。
-                            设备名称:位移监测设备-gnss一号机,监测数值:55。123456789N,请尽快处理问题。*/
-                        String mountainId = device.getMountainId();
-                        List<KwsAlarmInfo> list = alarmInfoRepository.list(new LambdaQueryWrapper<KwsAlarmInfo>()
-                                .eq(KwsAlarmInfo::getMountainId, mountainId)
-                                .eq(KwsAlarmInfo::getLevel, level.intValue())
-                                .eq(KwsAlarmInfo::getType, NumberConstant.ONE)
-                                .eq(KwsAlarmInfo::getDelFlag, NumberConstant.ZERO)
+                    for (DevicesItem devicesItem : devicesItemList) {
+                        String itemName = devicesItem.getItemName();
+                        String itemValue = devicesItem.getItemValue();
+                        List<KwsThreshold> kwsThresholds = thresholdMapper.selectList(new LambdaQueryWrapper<KwsThreshold>()
+                                .eq(KwsThreshold::getDeviceId, device.getId())
+                                .eq(KwsThreshold::getDelFlag, NumberConstant.ZERO)
+                                .eq(KwsThreshold::getItemName, itemName)
                         );
-                        List<String> pushToPhone = new ArrayList<>();
-                        if (!CollectionUtils.isEmpty(list)) {
-                            pushToPhone = list.stream().map(KwsAlarmInfo::getValueDesc).distinct().collect(Collectors.toList());
+                        if (org.springframework.util.CollectionUtils.isEmpty(kwsThresholds)) {
+                            continue;
                         }
-                        if (!CollectionUtils.isEmpty(pushToPhone)) {
+                        Long ts = 0L != timeDate ? timeDate : devicesAlarm.getTs();
+                        //判断是否满足设备超时离线报警
+//                    checkDeviceAlarm(deviceCode, device, itemValue, ts);
+                        //判断是否满足数值超阈值报警
+                        Map<String, String> map = checkThresholdAlarm(devicesItem, kwsThresholds, device);
+                        if ("2".equals(map.get("flag"))) {
+                            Long level = Long.valueOf(map.get("level"));
+                            Long thresholdId = Long.valueOf(map.get("thresholdId"));
+                            String offset = map.get("offset");
+                            //阈值表以及明细表存储
+                            long id = insertAlarmAndDetail(level, device, thresholdId, offset, ts, AlarmTitleEnum.ALARM_TITLE_TWO.getStatus(), AlarmTypeEnum.ALARM_ONE.getCode());
+                            //todo 不适用redis存统计  使用新字段处理
+                            /**阈值次数存redis*/
+//                        redisPutAlarmCount(id);
+                            String mountainId = device.getMountainId();
+                            List<KwsAlarmInfo> list = alarmInfoRepository.list(new LambdaQueryWrapper<KwsAlarmInfo>()
+                                    .eq(KwsAlarmInfo::getMountainId, mountainId)
+                                    .eq(KwsAlarmInfo::getLevel, level.intValue())
+                                    .eq(KwsAlarmInfo::getType, NumberConstant.ONE)
+                                    .eq(KwsAlarmInfo::getDelFlag, NumberConstant.ZERO)
+                            );
+                            List<String> pushToPhone = new ArrayList<>();
+                            if (!CollectionUtils.isEmpty(list)) {
+                                pushToPhone = list.stream().map(KwsAlarmInfo::getValueDesc).distinct().collect(Collectors.toList());
+                            }
+                            if (!CollectionUtils.isEmpty(pushToPhone) && pushToPhone.size() > 0) {
 //                        KwsThreshold kwsThreshold = thresholdMapper.selectById(thresholdId);
 //                        String phones = kwsThreshold.getPhones();
 //                        List<String> pushToPhone = com.sckw.core.utils.StringUtils.splitStrToList(phones, String.class);
-                            Map<String, String> templateParam = new HashMap<>();
-                            if (StringUtils.isBlank(time)) {
-                                LocalDateTime localDateTime = Instant.ofEpochSecond(ts).atZone(ZoneId.systemDefault()).toLocalDateTime();
-                                time = com.sckw.excel.utils.DateUtil.format(localDateTime);
-                            }
-                            templateParam.put("time", time);
-                            templateParam.put("level", level.toString());
-                            templateParam.put("name", device.getName());
+                                Map<String, String> templateParam = new HashMap<>();
+                                if (StringUtils.isBlank(time)) {
+                                    LocalDateTime localDateTime = Instant.ofEpochSecond(ts).atZone(ZoneId.systemDefault()).toLocalDateTime();
+                                    time = com.sckw.excel.utils.DateUtil.format(localDateTime);
+                                }
+                                templateParam.put("time", time);
+                                templateParam.put("level", level.toString());
+                                templateParam.put("name", device.getName());
 //                            templateParam.put("value", itemValue);
-                            templateParam.put("value", offset);
-                            commonService.pushSmsMessage(pushToPhone
-                                    , smsTemplateConfig.getDataAlarm().getSmsCode()
-                                    , smsTemplateConfig.getDataAlarm().getSignName()
-                                    , templateParam);
-                        }
-                        ProjectVo vo = projectDeviceMapper.selectProjectByDeviceId(device.getId());
-                        /**邮件推送*/
-                        List<KwsAlarmInfo> emailList = alarmInfoRepository.list(new LambdaQueryWrapper<KwsAlarmInfo>()
-                                .eq(KwsAlarmInfo::getMountainId, mountainId)
-                                .eq(KwsAlarmInfo::getLevel, level.intValue())
-                                .eq(KwsAlarmInfo::getType, NumberConstant.TWO)
-                                .eq(KwsAlarmInfo::getDelFlag, NumberConstant.ZERO)
-                        );
-                        List<String> emailAddress = new ArrayList<>();
-                        if (!CollectionUtils.isEmpty(emailList)) {
-                            emailAddress = emailList.stream().map(KwsAlarmInfo::getValueDesc).distinct().collect(Collectors.toList());
-                        }
-                        if (!CollectionUtils.isEmpty(emailAddress)) {
-                            Map<String, Object> templateParam = new HashMap<>();
-                            if (StringUtils.isBlank(time)) {
-                                LocalDateTime localDateTime = Instant.ofEpochSecond(ts).atZone(ZoneId.systemDefault()).toLocalDateTime();
-                                time = com.sckw.excel.utils.DateUtil.format(localDateTime);
+                                templateParam.put("value", offset);
+                                commonService.pushSmsMessage(pushToPhone
+                                        , smsTemplateConfig.getDataAlarm().getSmsCode()
+                                        , smsTemplateConfig.getDataAlarm().getSignName()
+                                        , templateParam);
                             }
-                            templateParam.put("company", smsTemplateConfig.getDataAlarm().getSignName());
-                            templateParam.put("level", level.toString());
-                            templateParam.put("name", device.getName());
-                            templateParam.put("time", time);
-                            templateParam.put("project", vo == null ? null : vo.getProjectName());
+                            ProjectVo vo = projectDeviceMapper.selectProjectByDeviceId(device.getId());
+                            /**邮件推送*/
+                            List<KwsAlarmInfo> emailList = alarmInfoRepository.list(new LambdaQueryWrapper<KwsAlarmInfo>()
+                                    .eq(KwsAlarmInfo::getMountainId, mountainId)
+                                    .eq(KwsAlarmInfo::getLevel, level.intValue())
+                                    .eq(KwsAlarmInfo::getType, NumberConstant.TWO)
+                                    .eq(KwsAlarmInfo::getDelFlag, NumberConstant.ZERO)
+                            );
+                            List<String> emailAddress = new ArrayList<>();
+                            if (!CollectionUtils.isEmpty(emailList) && emailList.size() > 0) {
+                                emailAddress = emailList.stream().map(KwsAlarmInfo::getValueDesc).distinct().collect(Collectors.toList());
+                            }
+                            if (!CollectionUtils.isEmpty(emailAddress)) {
+                                Map<String, Object> templateParam = new HashMap<>();
+                                if (StringUtils.isBlank(time)) {
+                                    LocalDateTime localDateTime = Instant.ofEpochSecond(ts).atZone(ZoneId.systemDefault()).toLocalDateTime();
+                                    time = com.sckw.excel.utils.DateUtil.format(localDateTime);
+                                }
+                                templateParam.put("company", smsTemplateConfig.getDataAlarm().getSignName());
+                                templateParam.put("level", level.toString());
+                                templateParam.put("name", device.getName());
+                                templateParam.put("time", time);
+                                templateParam.put("project", vo == null ? null : vo.getProjectName());
 //                            templateParam.put("value", itemValue);
-                            templateParam.put("value", offset);
-                            commonService.pushEmailMessage(emailAddress
-                                    , templateParam);
+                                templateParam.put("value", offset);
+                                templateParam.put("element", dictByDictCode.get(itemName).getLabel());
+                                templateParam.put("type", AlarmTitleEnum.ALARM_TITLE_TWO.getName() + "告警");
+                                commonService.pushEmailMessage(emailAddress
+                                        , templateParam);
+                            }
                         }
+                        //集成要素阈值告警
+                        deviceIntegrationsAlarm(device, ts, time);
                     }
-                    //集成要素阈值告警
-                    deviceIntegrationsAlarm(device, ts, time);
                 }
+            } catch (Exception e) {
+                log.error("mqtt消费异常:{}", e.getMessage(), e);
+            } finally {
+                redisLockUtil.unlock(alarmKey);
             }
-        } catch (Exception e) {
-            log.error("mqtt消费异常:{}", e.getMessage(), e);
         }
         return HttpResult.ok();
     }
@@ -259,7 +254,15 @@ public class MqttCallbackHandler extends AbstractHandler {
         }
     }
 
+    /**
+     * 集成要素阈值告警
+     *
+     * @param device 设备
+     * @param ts     ts
+     * @param time   时间
+     */
     private void deviceIntegrationsAlarm(KwsDevice device, Long ts, String time) {
+        Map<String, SystemDict> dictByDictCode = commonService.getDictByDictCode(DictEnum.INTEGRATION_UNIT);
 //        List<KwsDeviceIntegration> deviceIntegrations = deviceIntegrationMapper.selectList(
 //                new LambdaQueryWrapper<KwsDeviceIntegration>()
 //                        .eq(KwsDeviceIntegration::getDeviceId, device.getId())
@@ -286,8 +289,9 @@ public class MqttCallbackHandler extends AbstractHandler {
         List<DeviceIntegrationVo> intergData = new ArrayList<>();
         String snCode = device.getSnCode();
         intergData = deviceIntegrationMapper.selectListParamsAndInterNameByDeviceId(device.getId());
-        if (!Objects.isNull(intergData)) {
+        if (!Objects.isNull(intergData) || intergData.size() > 0) {
             for (DeviceIntegrationVo deviceIntegration : intergData) {
+                String unit = "";
                 //获取到当前测量值--现在只有单一值
                 List<SlopeData> slopeData = slopeDataMapper.selectListByTwoLine(snCode, deviceIntegration.getPartNames());
                 if (!Objects.isNull(slopeData) && slopeData.size() == 2) {
@@ -304,7 +308,8 @@ public class MqttCallbackHandler extends AbstractHandler {
 //                        String url = deviceIntegration.getUnit() == null ? null : deviceIntegration.getUnit();
 //                        String itemValueAndUnit = StringUtils.isBlank(url) ? String.valueOf(offset) : (offset + deviceIntegration.getUnit());
 //                        long id = insertAlarmAndDetail(level, device, thresholdId, itemValueAndUnit, ts, AlarmTitleEnum.ALARM_TITLE_TWO.getStatus(), AlarmTypeEnum.ALARM_ONE.getCode());
-                        long id = insertAlarmAndDetail(level, device, thresholdId, offset + deviceIntegration.getUnit(), ts, AlarmTitleEnum.ALARM_TITLE_TWO.getStatus(), AlarmTypeEnum.ALARM_ONE.getCode());
+                        unit = dictByDictCode.get(deviceIntegration.getUnit()) == null ? deviceIntegration.getUnit() : dictByDictCode.get(deviceIntegration.getUnit()).getDescription();
+                        long id = insertAlarmAndDetail(level, device, thresholdId, offset + unit, ts, AlarmTitleEnum.ALARM_TITLE_TWO.getStatus(), AlarmTypeEnum.ALARM_ONE.getCode());
                         /**最初发送短信模式*/
 //                        oldPushSms(device,level,thresholdId);
                         /**目前发送短信模式*/
@@ -331,11 +336,16 @@ public class MqttCallbackHandler extends AbstractHandler {
                             templateParam.put("level", level.toString());
                             templateParam.put("name", device.getName());
 //                            templateParam.put("value", itemValueAndUnit);
-                            templateParam.put("value", String.valueOf(offset) + deviceIntegration.getUnit());
-                            commonService.pushSmsMessage(pushToPhone
-                                    , smsTemplateConfig.getDataAlarm().getSmsCode()
-                                    , smsTemplateConfig.getDataAlarm().getSignName()
-                                    , templateParam);
+                            unit = dictByDictCode.get(deviceIntegration.getUnit()) == null ? deviceIntegration.getUnit() : dictByDictCode.get(deviceIntegration.getUnit()).getDescription();
+                            BigDecimal bd = new BigDecimal(offset);
+                            bd = bd.setScale(2, RoundingMode.HALF_UP);
+                            templateParam.put("value", String.valueOf(bd) + unit);
+                            if (pushToPhone.size() > 0) {
+                                commonService.pushSmsMessage(pushToPhone
+                                        , smsTemplateConfig.getDataAlarm().getSmsCode()
+                                        , smsTemplateConfig.getDataAlarm().getSignName()
+                                        , templateParam);
+                            }
                         }
                         ProjectVo vo = projectDeviceMapper.selectProjectByDeviceId(device.getId());
                         /**邮件推送*/
@@ -361,7 +371,14 @@ public class MqttCallbackHandler extends AbstractHandler {
                             templateParam.put("time", time);
                             templateParam.put("project", vo == null ? null : vo.getProjectName());
 //                            templateParam.put("value", itemValueAndUnit);
-                            templateParam.put("value", String.valueOf(offset) + deviceIntegration.getUnit());
+                            unit = dictByDictCode.get(deviceIntegration.getUnit()) == null ? deviceIntegration.getUnit() : dictByDictCode.get(deviceIntegration.getUnit()).getDescription();
+                            BigDecimal bd = new BigDecimal(offset);
+                            bd = bd.setScale(2, RoundingMode.HALF_UP);
+//                            DecimalFormat df = new DecimalFormat("#.##");
+//                            String formattedNumber = df.format(bd);
+                            templateParam.put("value", String.valueOf(bd) + unit);
+                            templateParam.put("type", AlarmTitleEnum.ALARM_TITLE_TWO.getName());
+                            templateParam.put("element", deviceIntegration.getIntegrationName());
                             commonService.pushEmailMessage(emailAddress
                                     , templateParam);
                         }

+ 20 - 21
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/controller/CommonController.java

@@ -11,11 +11,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RestController;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
 /**
  * @author lfdc
  * @description 公共字典查询
@@ -76,20 +71,24 @@ public class CommonController {
 //                , templateParam);
 //        return  HttpResult.ok();
 //    }
-    @RequestMapping(value = "/pushEmailMessage", method = RequestMethod.GET)
-    public HttpResult pushEmailMessage() {
-        Map<String, Object> templateParam = new HashMap<>();
-        templateParam.put("company", smsTemplateConfig.getDataAlarm().getSignName());
-        templateParam.put("level", "一级");
-        templateParam.put("name", "设备名称");
-        templateParam.put("time", "2023-12-05 15:00:00");
-        templateParam.put("project", "第一个项目");
-        templateParam.put("value", "29.5645E");
-        List<String> emailAddress = new ArrayList<>();
-        emailAddress.add("1573035851@qq.com");
-        emailAddress.add("lengfaqiang96@163.com");
-        commonService.pushEmailMessage(emailAddress
-                , templateParam);
-        return HttpResult.ok();
-    }
+//    @RequestMapping(value = "/pushEmailMessage", method = RequestMethod.GET)
+//    public HttpResult pushEmailMessage() {
+//        String key = PasswordUtils.md5("topic" + "alarm" + "payload");
+//        String alarmKey = String.format(RedisConstant.MQ_CONSUMER_ALARM_KEY, key);
+//        boolean flag = RedissonUtils.tryLock(alarmKey, 3L, 5L);
+//        System.out.println("flag"+flag);
+//        Map<String, Object> templateParam = new HashMap<>();
+//        templateParam.put("company", smsTemplateConfig.getDataAlarm().getSignName());
+//        templateParam.put("level", "一级");
+//        templateParam.put("name", "设备名称");
+//        templateParam.put("time", "2023-12-05 15:00:00");
+//        templateParam.put("project", "第一个项目");
+//        templateParam.put("value", "29.5645E");
+//        List<String> emailAddress = new ArrayList<>();
+////        emailAddress.add("1573035851@qq.com");
+//        emailAddress.add("lengfaqiang96@163.com");
+////        commonService.pushEmailMessage(emailAddress
+////                , templateParam);
+//        return HttpResult.ok();
+//    }
 }

+ 36 - 23
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/CommonService.java

@@ -10,7 +10,6 @@ import com.sckw.core.model.enums.DictItemEnum;
 import com.sckw.core.model.enums.MessageLogEnum;
 import com.sckw.core.model.page.PageRes;
 import com.sckw.core.utils.IdWorker;
-import com.sckw.core.utils.UUIDUtils;
 import com.sckw.core.web.response.PhpResult;
 import com.sckw.slope.detection.common.config.SmsTemplateConfig;
 import com.sckw.slope.detection.dao.mysql.KwsDeviceReferenceMapper;
@@ -29,11 +28,9 @@ import com.sckw.slope.detection.model.vo.QueryDictTypePageReqVo;
 import com.sckw.slope.detection.service.api.DetectionApiService;
 import jakarta.servlet.http.HttpServletRequest;
 import lombok.extern.slf4j.Slf4j;
-import org.apache.dubbo.common.utils.MD5Utils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.cloud.context.config.annotation.RefreshScope;
-import org.springframework.scheduling.annotation.Async;
 import org.springframework.stereotype.Service;
 
 import java.math.BigDecimal;
@@ -181,8 +178,9 @@ public class CommonService {
             if (deviceReference != null) {
                 angleInRadians = deviceReference.getCurrentValue().doubleValue();
             }
-            double cosValue = Math.cos(Math.toRadians(angleInRadians));;
+            double cosValue = Math.cos(Math.toRadians(angleInRadians));
             double doubleValue = subtract.divide(new BigDecimal("360"), 18, BigDecimal.ROUND_HALF_UP).doubleValue();
+
             offsetValue = new BigDecimal(equatorial_circumference).multiply(new BigDecimal(cosValue)).multiply(new BigDecimal(doubleValue));
         }
         double number = offsetValue.doubleValue();
@@ -299,7 +297,7 @@ public class CommonService {
         if (DictItemEnum.LONGITUDE_X.getValue().equals(inter.getPartNames())) {
             List<SlopeData> y = slopeDataMapper.selectListByTwoLine(snCode, DictItemEnum.LATITUDE_Y.getValue());
             double angleInRadians = Double.parseDouble(y.get(1).getVal());
-            double cosValue =Math.cos(Math.toRadians(angleInRadians));
+            double cosValue = Math.cos(Math.toRadians(angleInRadians));
 
             double doubleValue = subtract.divide(new BigDecimal("360"), 18, BigDecimal.ROUND_HALF_UP).doubleValue();
             offsetValue = new BigDecimal(equatorial_circumference).multiply(new BigDecimal(cosValue)).multiply(new BigDecimal(doubleValue));
@@ -410,7 +408,7 @@ public class CommonService {
      * @param signName      签名
      * @param templateParam 请求参数
      */
-    @Async
+//    @Async
     public void pushSmsMessage(List<String> pushToPhone, String templateCode, String signName, Map<String, String> templateParam) {
         SmsMessageParam param = new SmsMessageParam();
         param.setCode("");
@@ -421,10 +419,10 @@ public class CommonService {
         content.setSignName(signName);
         content.setTemplateParam(templateParam);
         param.setContent(content);
-        Map<String, String> headerMap = new HashMap<>();
-        headerMap.put("sign", new MD5Utils().getMd5("sign"));
-        headerMap.put("account", "zhangsan");
-        headerMap.put("msgId", UUIDUtils.get32UUID());
+//        Map<String, String> headerMap = new HashMap<>();
+//        headerMap.put("sign", PasswordUtils.md5("sign"));
+//        headerMap.put("account", "zhangsan");
+//        headerMap.put("msgId", UUIDUtils.get32UUID());
         JSONObject jsonObject = detectionApiService.pushSmsMessage(smsUrl, JSONObject.toJSONString(param));
         log.info("推送短信:请求参数:{},响应结果:{}", JSONObject.toJSONString(param), jsonObject.toString());
     }
@@ -435,27 +433,42 @@ public class CommonService {
      * @param emailAddress
      * @param templateParam
      */
-    @Async
+//    @Async
     public void pushEmailMessage(List<String> emailAddress, Map<String, Object> templateParam) {
         SmsMessageParam param = new SmsMessageParam();
         param.setCode("");
         param.setType(4);
         param.setPushTo(emailAddress);
         SmsMessageParam.Content content = new SmsMessageParam.Content();
-        String templateStr = "尊敬的${company}用户,在北京时间${time}监测到有${level}级告警被触发;\n" +
-                "设备名称:${name};\n" +
-                "所属项目:${project};\n" +
-                "监测数值:${value};\n" +
-                "请在收到邮件后尽快处理,或查阅操作手册文档,确认告警通知相关信息。";
+//        String templateStr = "尊敬的${company}用户,在北京时间${time}监测到有${level}级告警被触发;\n" +
+//                "设备名称:${name};\n" +
+//                "所属项目:${project};\n" +
+//                "监测数值:${value};\n" +
+//                "请在收到邮件后尽快处理,或查阅操作手册文档,确认告警通知相关信息。";
+        /**
+         * company-公司 (如名称、账号、地址等);
+         * time-时间;
+         * level-等级 (如订单号、密码等);
+         * name-设备名称 (如名称、账号、地址等);
+         * project-项目 (如名称、账号、地址等);
+         * value-监测要素值、触发离线时间;
+         * type-数值超阈值告警、设备离线告警;
+         * element-监测要素、离线超24小时*/
+        String templateStr =
+                "标题:设备告警通知邮件\n" +
+                        "发件人:四川开物信息科技有限公司\n" +
+                        "尊敬的${company}用户:\n" +
+                        "    在北京时间的${time},监测到了${level}级告警,告警类型为${type}。\n" +
+                        "    设备名称:${name};\n" +
+                        "    所属项目:${project};\n" +
+                        "    设备告警内容:${element};\n" +
+                        "    触发告警值:${value};\n" +
+                        "    请在收到邮件后尽快处理,或查阅操作手册文档,确认告警通知相关信息,以避免造成相关损失。";
         String text = com.sckw.core.utils.StringUtils.replaceTextVar(templateStr, templateParam);
-        content.setSubject("设备阈值告警");
+        content.setSubject("设备告警通知邮件");
         content.setText(text);
         param.setContent(content);
-        Map<String, String> headerMap = new HashMap<>();
-        headerMap.put("sign", new MD5Utils().getMd5("sign"));
-        headerMap.put("account", "zhangsan");
-        headerMap.put("msgId", UUIDUtils.get32UUID());
-        JSONObject jsonObject = detectionApiService.pushSmsMessage(smsUrl, JSONObject.toJSONString(param));
-        log.info("邮寄发送返回结果:{}",jsonObject.toString());
+        JSONObject jsonObject = detectionApiService.pushEmailMessage(smsUrl, JSONObject.toJSONString(param));
+        log.info("邮件发送 请求参数:{} 返回结果:{}", JSONObject.toJSONString(param), jsonObject.toString());
     }
 }

+ 7 - 2
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/KwsAlarmService.java

@@ -547,6 +547,7 @@ public class KwsAlarmService {
             vo.setDeviceId(deviceId.toString());
             vo.setItemName(itemName);
             String unit = "";
+            String url = "";
             if (devices != null) {
                 String val = devices.getVal();
                 if (list.contains(kwsThreshold.getItemName())) {
@@ -555,12 +556,16 @@ public class KwsAlarmService {
                                 (dictByDictCode == null ?
                                         kwsThreshold.getItemName() : (dictByDictCode.get(kwsThreshold.getItemName()) == null ?
                                         kwsThreshold.getItemName() : dictByDictCode.get(kwsThreshold.getItemName()).getRemark()));
+                        url = kwsThreshold.getItemName() == null ? null :
+                                (dictByDictCode == null ?
+                                        kwsThreshold.getItemName() : (dictByDictCode.get(kwsThreshold.getItemName()) == null ?
+                                        kwsThreshold.getItemName() : dictByDictCode.get(kwsThreshold.getItemName()).getUrl()));
                         BigDecimal computeOffset = commonService.computeOffset(val, kwsThreshold.getItemName(), deviceReference);
                         BigDecimal computeOriginalOffset = commonService.computeOriginalOffset(val, kwsThreshold.getItemName(), deviceReference);
                         vo.setCurrentValue(deviceReference.getCurrentValue() + unit);
-                        vo.setCurrentOffset(computeOffset.setScale(2, RoundingMode.HALF_UP) + unit);
+                        vo.setCurrentOffset(computeOffset.setScale(2, RoundingMode.HALF_UP) + url);
                         vo.setOriginalValue(deviceReference.getOriginalValue() + unit);
-                        vo.setOriginalOffset(computeOriginalOffset.setScale(2, RoundingMode.HALF_UP) + unit);
+                        vo.setOriginalOffset(computeOriginalOffset.setScale(2, RoundingMode.HALF_UP) + url);
                     }
                 } else {
                     vo.setCurrentValue(deviceReference == null ? null : deviceReference.getCurrentValue() + unit);

+ 30 - 0
slope-modules/slope-detection/src/main/java/com/sckw/slope/detection/service/api/DetectionApiService.java

@@ -181,6 +181,36 @@ public class DetectionApiService {
                 .build();
         try {
             Response response = client.newCall(request).execute();
+//            System.out.println(JSONObject.toJSONString(response));
+            System.out.println("请求响应状态码:" + response.code());
+            if (response.isSuccessful()) {
+                String responseBody = response.body().string();
+                log.info("响应信息:{}", responseBody);
+                return JSONObject.parseObject(responseBody);
+            } else {
+                int code = response.code();
+                JSONObject resp = new JSONObject();
+                resp.put("code", code);
+                resp.put("success", false);
+                resp.put("message", "http状态响应异常");
+                return resp;
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public static JSONObject pushEmailMessage(String url, String json) {
+        RequestBody body = RequestBody.create(JSON, json);
+        Request request = new Request.Builder()
+                .url(url)
+                .addHeader("sign", new MD5Utils().getMd5("sign"))
+                .addHeader("account", "zhangsan")
+                .addHeader("msgId", UUIDUtils.get32UUID())
+                .post(body)
+                .build();
+        try {
+            Response response = client.newCall(request).execute();
 //            System.out.println(JSONObject.toJSONString(response));
             System.out.println("请求响应状态码:" + response.code());
             if (response.isSuccessful()) {