Sfoglia il codice sorgente

Merge remote-tracking branch 'origin/v2.1.0' into v2.1.0

lixing 3 anni fa
parent
commit
532aed51cf
21 ha cambiato i file con 912 aggiunte e 261 eliminazioni
  1. 3 0
      src/main/java/com/persagy/apm/diagnose/feign/client/CenterMiddlewareClient.java
  2. 9 0
      src/main/java/com/persagy/apm/diagnose/feign/client/SaasWebClient.java
  3. 43 18
      src/main/java/com/persagy/apm/diagnose/indicatorrecord/service/impl/MonitorIndicatorRecordServiceImpl.java
  4. 26 0
      src/main/java/com/persagy/apm/diagnose/maintenance/model/dto/WeatherDTO.java
  5. 3 1
      src/main/java/com/persagy/apm/diagnose/maintenance/service/IProjectDataRecordService.java
  6. 168 106
      src/main/java/com/persagy/apm/diagnose/maintenance/service/impl/ProjectDataRecordServiceImpl.java
  7. 56 0
      src/main/java/com/persagy/apm/diagnose/service/CenterDataService.java
  8. 2 2
      src/main/java/com/persagy/apm/diagnose/service/ComputeIndicatorDataService.java
  9. 4 2
      src/main/java/com/persagy/apm/diagnose/service/MaintenanceDataService.java
  10. 3 7
      src/main/java/com/persagy/apm/diagnose/service/NettyAlarmServiceImpl.java
  11. 28 0
      src/main/java/com/persagy/apm/diagnose/service/SaasWebServiceImpl.java
  12. 89 0
      src/main/java/com/persagy/apm/diagnose/service/WeatherServiceImpl.java
  13. 1 0
      src/main/java/com/persagy/apm/diagnose/service/dto/ProjectDTO.java
  14. 2 2
      src/main/java/com/persagy/apm/diagnose/service/schedule/ComputeIndicatorData.java
  15. 2 1
      src/main/java/com/persagy/apm/diagnose/service/schedule/SendIndicatorData.java
  16. 32 1
      src/main/java/com/persagy/apm/diagnose/utils/CollectDataUtil.java
  17. 205 0
      src/main/java/com/persagy/apm/diagnose/utils/HttpUtils.java
  18. 143 0
      src/main/java/com/persagy/apm/diagnose/utils/JsonUtils.java
  19. 92 0
      src/main/java/com/persagy/apm/diagnose/utils/TwdTempUtil.java
  20. 1 1
      src/main/resources/db/init/table.sql
  21. 0 120
      src/main/resources/logback-diagnose.xml

+ 3 - 0
src/main/java/com/persagy/apm/diagnose/feign/client/CenterMiddlewareClient.java

@@ -25,4 +25,7 @@ public interface CenterMiddlewareClient {
     @PostMapping(value = "/hisdata/queryPeriodData")
     public String queryPeriodData(@RequestBody Map<String, Object> requestMap);
 
+    @PostMapping(value = "/mng/project/query")
+    public String queryProject(@RequestBody Map<String, Object> requestMap);
+
 }

+ 9 - 0
src/main/java/com/persagy/apm/diagnose/feign/client/SaasWebClient.java

@@ -24,4 +24,13 @@ public interface SaasWebClient {
 	@PostMapping("/Spring/MVC/entrance/unifier/queryInUseProjectsByIds")
 	@Headers({ "Content-Type: application/x-www-form-urlencoded" })
 	String queryInUseProjectsByIds(@RequestParam("jsonString") String jsonString);
+
+    /**
+     * 根据项目id查询项目信息
+     * @param jsonString
+     * @return
+     */
+    @PostMapping("/Spring/MVC/entrance/unifier/getProjectByIdService")
+    @Headers({ "Content-Type: application/x-www-form-urlencoded" })
+    String getProjectByIdService(@RequestParam("jsonString") String jsonString);
 }

+ 43 - 18
src/main/java/com/persagy/apm/diagnose/indicatorrecord/service/impl/MonitorIndicatorRecordServiceImpl.java

@@ -20,6 +20,7 @@ import com.persagy.apm.diagnose.timerecord.service.ICalculateTimeRecordService;
 import com.persagy.apm.diagnose.utils.*;
 import com.persagy.apm.energyalarmstarter.alarmdata.service.AlarmConfigServiceImpl;
 import com.persagy.apm.energyalarmstarter.collectdata.websocket.AlarmWebSocketServer;
+import com.persagy.framework.ems.data.core.enumeration.EMSOrder;
 import com.persagy.framework.ems.data.core.enumeration.SpecialOperator;
 import com.persagy.framework.ems.data.mvc.dao.CoreDao;
 import com.persagy.framework.ems.data.pojo.hbase.MonitorIndicatorRecord;
@@ -76,7 +77,7 @@ public class MonitorIndicatorRecordServiceImpl implements IMonitorIndicatorRecor
     public final static String alarmSlipt = "_";
 
 
-    private final static Long SendDataTimeKeyTime = 24 * 60 * 60 * 1000L;
+//    private final static Long SendDataTimeKeyTime = 24 * 60 * 60 * 1000L;
 
 
     @Autowired
@@ -258,7 +259,8 @@ public class MonitorIndicatorRecordServiceImpl implements IMonitorIndicatorRecor
     private Date getDefultStartTime() throws Exception {
         Date lastComputeTime;
         if (StringUtils.isBlank(computePropertiesConfig.getDStartTime())) {
-            lastComputeTime = new Date();
+
+            lastComputeTime = DateUtils.get15MinLite(new Date());
         } else {
             lastComputeTime = DateUtils.str2Date(computePropertiesConfig.getDStartTime(), DateUtils.SDF_SECOND);
         }
@@ -365,28 +367,22 @@ public class MonitorIndicatorRecordServiceImpl implements IMonitorIndicatorRecor
             Date lastSendTime = configItemSendTimeDTO.getLastSendTime();
             Date endTime = getSendEndTime(lastSendTime);
 
-            List<MonitorIndicatorRecord> list = getMonitorIndicatorRecordsGtLte(projectDTO.getProjectId(), objId, lastSendTime, infCodeList, endTime);
-            if (CollectionUtils.isEmpty(list)) {
+            Map<String, List<MonitorIndicatorRecord>> timeKeyAndRecordList = getTimekeyAndRecordListGteLt(projectDTO, objId, infCodeList, lastSendTime, endTime);
+            if (timeKeyAndRecordList == null) {
                 continue;
             }
-            Map<String, List<MonitorIndicatorRecord>> timeKeyAndRecordList = new LinkedHashMap<>();
-            for (MonitorIndicatorRecord record : list) {
-                String timeKey = DateUtils.date2Str(record.getDataTime(), DateUtils.SDF_SECOND);
-                if (!timeKeyAndRecordList.containsKey(timeKey)) {
-                    timeKeyAndRecordList.put(timeKey, new ArrayList<>());
-                }
-                timeKeyAndRecordList.get(timeKey).add(record);
-            }
+           Map<String, List<MonitorIndicatorRecord>> sendTimeKeyAndDataList = new LinkedHashMap<>();
             for (Map.Entry<String, List<MonitorIndicatorRecord>> dateListEntry : timeKeyAndRecordList.entrySet()) {
                 List<MonitorIndicatorRecord> value = dateListEntry.getValue();
                 if (CollectionUtils.isEmpty(value) || value.size() != infCodeList.size()) {
                     continue;
                 }
-                String sentValue = CollectDataUtil.buildSendParam(value,alarmItemCode);
-                AlarmWebSocketServer.sendMsgToClients(projectDTO.getProjectId(), CollectDataUtil.buildSendParam(value,alarmItemCode));
-                log.info("指标发送报表服务数据:" + projectDTO.getProjectId()+";"+ sentValue);
-                endTime = DateUtils.str2Date(dateListEntry.getKey(), DateUtils.SDF_SECOND);
+                sendTimeKeyAndDataList.put(dateListEntry.getKey(),value);
+                endTime = DateUtils.str2Date(dateListEntry.getKey(), DateUtils.SDFSECOND);
             }
+            String sentValue = CollectDataUtil.batchBuildSendParam(sendTimeKeyAndDataList,alarmItemCode);
+            AlarmWebSocketServer.sendMsgToClients(projectDTO.getProjectId(), sentValue);
+            log.error("指标发送报表服务数据:" + projectDTO.getProjectId()+";"+ sentValue);
             configItemSendTimeDTO.setLastSendTime(endTime);
             configItemSendTimeDTO.setUpdateTime(new Date());
             updateRedisConfigItemSendTimeDTO(projectDTO.getProjectId(), objIdAndAlarmItemCode, configItemSendTimeDTO);
@@ -394,6 +390,35 @@ public class MonitorIndicatorRecordServiceImpl implements IMonitorIndicatorRecor
     }
 
     /**
+     * @title getTimekeyAndRecordListGteLt
+     * @description 查询该时间段的需要发送的指标数据,key为时间字符串
+     * @author leifeng
+     * @param: projectDTO
+     * @param: objId
+     * @param: infCodeList
+     * @param: lastSendTime
+     * @param: endTime
+     * @updateTime 2021/11/5 10:59
+     * @return: java.util.Map<java.lang.String,java.util.List<com.persagy.framework.ems.data.pojo.hbase.MonitorIndicatorRecord>>
+     * @throws
+     */
+    private Map<String, List<MonitorIndicatorRecord>> getTimekeyAndRecordListGteLt(ProjectDTO projectDTO, String objId, List<String> infCodeList, Date lastSendTime, Date endTime) throws Exception {
+        List<MonitorIndicatorRecord> list = getMonitorIndicatorRecordsGtLte(projectDTO.getProjectId(), objId, lastSendTime, infCodeList, endTime);
+        if (CollectionUtils.isEmpty(list)) {
+            return null;
+        }
+        Map<String, List<MonitorIndicatorRecord>> timeKeyAndRecordList = new LinkedHashMap<>();
+        for (MonitorIndicatorRecord record : list) {
+            String timeKey = DateUtils.date2Str(record.getDataTime(), DateUtils.SDFSECOND);
+            if (!timeKeyAndRecordList.containsKey(timeKey)) {
+                timeKeyAndRecordList.put(timeKey, new ArrayList<>());
+            }
+            timeKeyAndRecordList.get(timeKey).add(record);
+        }
+        return timeKeyAndRecordList;
+    }
+
+    /**
      * @title getObjIdAlarmItemCodeAndInfoCodes
      * @description 获取对象报警类型及监控指标list,key为objId_itemCode
      * @author leifeng
@@ -449,7 +474,7 @@ public class MonitorIndicatorRecordServiceImpl implements IMonitorIndicatorRecor
         monitorIndicatorRecord.setSpecialOperation("monitorIndicatorId", SpecialOperator.$in, infoCodes);
         monitorIndicatorRecord.setSpecialOperation("dataTime", SpecialOperator.$gt, lastSendTime);
         monitorIndicatorRecord.setSpecialOperation("dataTime", SpecialOperator.$lte, endTime);
-
+        monitorIndicatorRecord.setSort("dataTime", EMSOrder.Asc);
         return coredao.query(monitorIndicatorRecord);
     }
 
@@ -494,7 +519,7 @@ public class MonitorIndicatorRecordServiceImpl implements IMonitorIndicatorRecor
      * @updateTime 2021/9/25 20:05
      */
     private void updateRedisConfigItemSendTimeDTO(String projectId, String objeIdAndAlarmItemCode, ConfigItemDataSendTimeDTO sendTimeDTO) {
-        redisUtil.set(getRedisSendDataKey(projectId, objeIdAndAlarmItemCode), sendTimeDTO, SendDataTimeKeyTime);
+        redisUtil.set(getRedisSendDataKey(projectId, objeIdAndAlarmItemCode), sendTimeDTO);
     }
 
     /**

+ 26 - 0
src/main/java/com/persagy/apm/diagnose/maintenance/model/dto/WeatherDTO.java

@@ -0,0 +1,26 @@
+package com.persagy.apm.diagnose.maintenance.model.dto;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import java.util.Date;
+import java.util.List;
+
+/**
+ * 天气信息
+ */
+@Data
+@Builder(toBuilder = true)
+@NoArgsConstructor
+@AllArgsConstructor
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class WeatherDTO {
+    private Date hourTime;
+
+    private Double temperature;
+
+    private Double humidity;
+}

+ 3 - 1
src/main/java/com/persagy/apm/diagnose/maintenance/service/IProjectDataRecordService.java

@@ -1,5 +1,7 @@
 package com.persagy.apm.diagnose.maintenance.service;
 
+import com.persagy.apm.diagnose.service.dto.ProjectDTO;
+
 import java.util.Date;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Future;
@@ -9,7 +11,7 @@ import java.util.concurrent.Future;
  */
 public interface IProjectDataRecordService {
 
-    Future<String> computeMaintenanceData(Date todayDate,String projectId,CountDownLatch latch) throws Exception;
+    Future<String> computeMaintenanceData(Date todayDate, ProjectDTO projectDTO, CountDownLatch latch) throws Exception;
 
     Future<String> sendMaintenanceData(Date todayDate,String projectId, CountDownLatch latch) throws Exception;
 

+ 168 - 106
src/main/java/com/persagy/apm/diagnose/maintenance/service/impl/ProjectDataRecordServiceImpl.java

@@ -11,10 +11,12 @@ import com.persagy.apm.diagnose.indicatorrecord.model.dto.QueryMonitorIndicatorR
 import com.persagy.apm.diagnose.indicatorrecord.service.IMonitorIndicatorRecordService;
 import com.persagy.apm.diagnose.maintenance.constant.*;
 import com.persagy.apm.diagnose.maintenance.model.dto.CalculateMethodDTO;
+import com.persagy.apm.diagnose.maintenance.model.dto.WeatherDTO;
 import com.persagy.apm.diagnose.maintenance.service.IProjectDataRecordService;
 import com.persagy.apm.diagnose.service.CenterDataService;
 import com.persagy.apm.diagnose.service.EnergyAlarmServiceImpl;
 import com.persagy.apm.diagnose.service.SaasService;
+import com.persagy.apm.diagnose.service.WeatherServiceImpl;
 import com.persagy.apm.diagnose.service.dto.AlarmRuleDTO;
 import com.persagy.apm.diagnose.service.dto.ProjectDTO;
 import com.persagy.apm.diagnose.service.dto.TimeDataDTO;
@@ -27,9 +29,7 @@ import com.persagy.apm.energyalarmstarter.alarmdata.model.dto.alarmrecord.AddAla
 import com.persagy.apm.energyalarmstarter.alarmdata.model.dto.alarmrecord.BatchUpdateAlarmRecordDTO;
 import com.persagy.apm.energyalarmstarter.alarmdata.model.dto.alarmrecord.QueryAlarmRecordDTO;
 import com.persagy.apm.energyalarmstarter.alarmdata.model.dto.alarmrecord.UpdateAlarmRecordDTO;
-import com.persagy.apm.energyalarmstarter.alarmdata.model.vo.AlarmConfigItem;
 import com.persagy.apm.energyalarmstarter.alarmdata.model.vo.AlarmRecordItem;
-import com.persagy.apm.energyalarmstarter.alarmdata.service.AlarmConfigServiceImpl;
 import com.persagy.apm.energyalarmstarter.alarmdata.service.AlarmRecordServiceImpl;
 import com.persagy.apm.energyalarmstarter.collectdata.websocket.AlarmWebSocketServer;
 import com.persagy.framework.ems.data.core.enumeration.SpecialOperator;
@@ -61,10 +61,17 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
 
     @Value(value = "${energy.eq.run.system.code}")
     private String systemCode;
+
+    //测试环境  运行状态 上下限值
+    @Value(value = "${energy.eq.run.state.up.limit}")
+    private Double runStateUpLimit;
+    @Value(value = "${energy.eq.run.state.down.limit}")
+    private Double runStateDownLimit;
+
     //报警分类
     public final static String alarmSplit = "_";
-    private final static Long ConfigItemKeyTime = 60 * 60 * 1000L;
     private final static Long SendDataTimeKeyTime = 24 * 60 * 60 * 1000L;
+    private final static Double TwdTemp_Limit = 0.1;
 
     @Autowired
     private AlarmRecordServiceImpl alarmRecordService;
@@ -84,30 +91,32 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
     private ComputePropertiesConfig computePropertiesConfig;
     @Autowired
     private EnergyAlarmServiceImpl energyAlarmService;
+    @Autowired
+    private WeatherServiceImpl weatherService;
 
     @Resource(name = "ZillionDao")
     private CoreDao coredao;
 
     @Override
     @Async("asyncComputeMaintenanceDataExecutor")
-    public Future<String> computeMaintenanceData(Date todayDate, String projectId, CountDownLatch latch) throws Exception {
+    public Future<String> computeMaintenanceData(Date todayDate,ProjectDTO projectDTO, CountDownLatch latch)throws Exception {
         long time = System.currentTimeMillis() + (20 * 1000);
         try {
-            if (!lockUtil.lock(projectId + "_computeMaintenance", String.valueOf(time))) {
+            if (!lockUtil.lock(projectDTO.getProjectId() + "_computeMaintenance", String.valueOf(time))) {
                 // 获取不到锁,略过
-                return new AsyncResult<>("【监测维保数据计算线程】项目:" + projectId + "被占用");
+                return new AsyncResult<>("【监测维保数据计算线程】项目:" + projectDTO.getProjectId() + "被占用");
             }
 
             long start = System.currentTimeMillis();
-            AsyncResult<String> projectDTOBack = computeProjectMaintenanceData(todayDate, projectId);
+            AsyncResult<String> projectDTOBack = computeProjectMaintenanceData(todayDate, projectDTO);
             if (projectDTOBack != null) {
                 return projectDTOBack;
             }
             long end = System.currentTimeMillis();
-            return new AsyncResult<>("【监测维保数据计算线程】计算项目指标数据用时:" + projectId + ";" + (end - start));
+            return new AsyncResult<>("【监测维保数据计算线程】计算项目指标数据用时:" + projectDTO.getProjectId() + ";" + (end - start));
         } finally {
             // 释放锁
-            lockUtil.unlock(projectId + "_computeMaintenance", String.valueOf(time));
+            lockUtil.unlock(projectDTO.getProjectId() + "_computeMaintenance", String.valueOf(time));
             latch.countDown();
         }
     }
@@ -135,7 +144,7 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
 
     @Override
     @Async("asyncGoingDestroyEquipExecutor")
-    public Future<String> syncGoingDestroyEquip(String projectId, CountDownLatch latch) throws Exception {
+    public Future<String> syncGoingDestroyEquip(String projectId, CountDownLatch latch) {
         long time = System.currentTimeMillis() + (20 * 1000);
         try {
             if (!lockUtil.lock(projectId + "_syncEquip", String.valueOf(time))) {
@@ -170,11 +179,8 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
             List<UpdateAlarmRecordDTO> updateAlarmRecordDTOList = new ArrayList<>();
             if (!CollectionUtils.isEmpty(equipSet)) {
                 for (String equipId : equipSet) {
-                    if (null != alarmRecordItemMap && alarmRecordItemMap.containsKey(equipId)) {
-                        if (null != equipInfoMap && equipInfoMap.containsKey(equipId)) {
-                            //同时存在于 报废记录和报警记录,跳过不处理
-                            continue;
-                        } else {
+                    if (alarmRecordItemMap.containsKey(equipId)) {
+                        if (!equipInfoMap.containsKey(equipId)) {
                             //存在于报警记录和但不在报废记录,将报警状态修改为 已恢复
                             AlarmRecordItem alarmRecordItem = alarmRecordItemMap.get(equipId);
                             if (EnumAlarmState.UN_HANDLE.getCode().equals(alarmRecordItem.getState())) {
@@ -186,9 +192,10 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
                                 updateAlarmRecordDTOList.add(updateAlarmRecordDTO);
                             }
                         }
+                        //同时存在于 报废记录和报警记录,跳过不处理
                     } else {
                         //不存在于报警列表  在即将报废列表   新产生报警信息
-                        if (null != equipInfoMap && equipInfoMap.containsKey(equipId)) {
+                        if (equipInfoMap.containsKey(equipId)) {
                             saveAlarmEquipIdList.add(equipId);
                         }
                     }
@@ -292,22 +299,24 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
             }
             Map<String, List<MonitorIndicatorRecord>> timeKeyAndRecordList = new LinkedHashMap<>();
             for (MonitorIndicatorRecord record : list) {
-                String timeKey = com.persagy.apm.diagnose.utils.DateUtils.date2Str(record.getDataTime(), com.persagy.apm.diagnose.utils.DateUtils.SDF_SECOND);
+                String timeKey = com.persagy.apm.diagnose.utils.DateUtils.date2Str(record.getDataTime(), com.persagy.apm.diagnose.utils.DateUtils.SDFSECOND);
                 if (!timeKeyAndRecordList.containsKey(timeKey)) {
                     timeKeyAndRecordList.put(timeKey, new ArrayList<>());
                 }
                 timeKeyAndRecordList.get(timeKey).add(record);
             }
+            Map<String, List<MonitorIndicatorRecord>> sendTimeKeyAndDataList = new LinkedHashMap<>();
             for (Map.Entry<String, List<MonitorIndicatorRecord>> dateListEntry : timeKeyAndRecordList.entrySet()) {
                 List<MonitorIndicatorRecord> value = dateListEntry.getValue();
                 if (CollectionUtils.isEmpty(value) || value.size() != infCodeList.size()) {
                     continue;
                 }
-                String sentValue = CollectDataUtil.buildSendParam(value,alarmItemCode);
-                AlarmWebSocketServer.sendMsgToClients(projectId, CollectDataUtil.buildSendParam(value,alarmItemCode));
-                log.info("设备维保发送数据服务数据:" + projectId+";"+ sentValue);
-                endTime = com.persagy.apm.diagnose.utils.DateUtils.str2Date(dateListEntry.getKey(), com.persagy.apm.diagnose.utils.DateUtils.SDF_SECOND);
+                sendTimeKeyAndDataList.put(dateListEntry.getKey(),value);
+                endTime = com.persagy.apm.diagnose.utils.DateUtils.str2Date(dateListEntry.getKey(), com.persagy.apm.diagnose.utils.DateUtils.SDFSECOND);
             }
+            String sentValue = CollectDataUtil.batchBuildSendParam(sendTimeKeyAndDataList,alarmItemCode);
+            AlarmWebSocketServer.sendMsgToClients(projectId, sentValue);
+            log.info("设备维保发送数据服务数据:" + projectId+";"+ sentValue);
             configItemSendTimeDTO.setLastSendTime(endTime);
             configItemSendTimeDTO.setUpdateTime(new Date());
             updateRedisConfigItemSendTimeDTO(projectId, objIdAndAlarmItemCode, configItemSendTimeDTO);
@@ -340,7 +349,7 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
                 for (String objId : objIds) {
                     String key = objId + "_" + alarmItemCode;
                     if (!objIdAlarmItemCodeAndInfoCodes.containsKey(key)) {
-                        objIdAlarmItemCodeAndInfoCodes.put(key, new ArrayList<String>());
+                        objIdAlarmItemCodeAndInfoCodes.put(key, new ArrayList<>());
                     }
                     objIdAlarmItemCodeAndInfoCodes.get(key).add(infoCode);
                 }
@@ -374,23 +383,23 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
     /**
      * 计算维保数据
      */
-    private AsyncResult<String> computeProjectMaintenanceData(Date todayDate, String projectId) {
+    private AsyncResult<String> computeProjectMaintenanceData(Date todayDate, ProjectDTO projectDTO) {
         try {
             //通过报警服务查询报警规则
             List<String> itemCodeList = new ArrayList<>();
             itemCodeList.add(EnumAlarmItem.CondAbnormal.getCode());
             itemCodeList.add(EnumAlarmItem.EvapAbnormal.getCode());
             itemCodeList.add(EnumAlarmItem.CoolTowerApproachTempAbnormal.getCode());
-            List<AlarmRuleDTO> projectAlarmRules = energyAlarmService.getProjectAlarmRules(projectId,itemCodeList);
+            List<AlarmRuleDTO> projectAlarmRules = energyAlarmService.getProjectAlarmRules(projectDTO.getProjectId(),itemCodeList);
             if (CollectionUtils.isEmpty(projectAlarmRules)) {
-                return new AsyncResult<>("【监测维保数据计算线程】当前项目:" + projectId + "未设置设备维保报警规则");
+                return new AsyncResult<>("【监测维保数据计算线程】当前项目:" + projectDTO.getProjectId() + "未设置设备维保报警规则");
             }
             Set<String> objIdAndIndicatorId = getObjIdAndInfoCodeFromRules(projectAlarmRules);
             if (CollectionUtils.isEmpty(objIdAndIndicatorId)) {
-                return new AsyncResult<>("【监测维保数据计算线程】当前项目:" + projectId + "报警规则未关联对象");
+                return new AsyncResult<>("【监测维保数据计算线程】当前项目:" + projectDTO.getProjectId() + "报警规则未关联对象");
             }
             //Map<objId_monitorIndicatorId, Date>
-            Map<String, Date> objId_indicatorIdAndComputeTime = getObjId_IndicatorIdAndComputeTIme(projectId);
+            Map<String, Date> objId_indicatorIdAndComputeTime = getObjId_IndicatorIdAndComputeTIme(projectDTO.getProjectId());
             //循环计算
             for (AlarmRuleDTO alarmRuleDTO:projectAlarmRules) {
                 String itemCode = alarmRuleDTO.getAlarmItemCode();
@@ -404,7 +413,7 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
                     continue;
                 }
                 for (String objId:objIdList) {
-                    List<AlarmCondition> alarmConditionList = energyAlarmService.getProjectAlarmCondition(projectId,objId,enumAlarmItem.getCode());
+                    List<AlarmCondition> alarmConditionList = energyAlarmService.getProjectAlarmCondition(projectDTO.getProjectId(),objId,enumAlarmItem.getCode());
                     if (CollectionUtils.isEmpty(alarmConditionList)){
                         continue;
                     }
@@ -445,15 +454,15 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
                         Date computeTime;
                         if (indicatorType == EnumMaintenanceIndicatorType.ACCCOT_DayAvg) {//冷却塔
                             //冷却塔 日均 数据计算
-                            computeTime = computeCoolTowerData(lastComputeTime, todayDate, projectId, objId, indicatorType);
+                            computeTime = computeCoolTowerData(lastComputeTime, todayDate, projectDTO, objId, indicatorType);
                         } else {//冷水机组
                             //冷却水组  日均 数据计算
-                            computeTime = computeCoolWaterData(lastComputeTime, todayDate, projectId, objId, indicatorType);
+                            computeTime = computeCoolWaterData(lastComputeTime, todayDate, projectDTO.getProjectId(), objId, indicatorType);
                         }
                         //计算 运行持续时长
-                        computeAlarmDay(projectId, objId, infoCode, indicatorType, lastComputeTime, todayDate,monitorIndicatorMap);
+                        computeAlarmDay(projectDTO.getProjectId(), objId, infoCode, indicatorType, lastComputeTime, todayDate,monitorIndicatorMap);
                         //更新计算 时间记录
-                        saveOrUpdateComputeTime(projectId, objId, infoCode, computeTime);
+                        saveOrUpdateComputeTime(projectDTO.getProjectId(), objId, infoCode, computeTime);
                     }
                 }
             }
@@ -560,7 +569,7 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
         if (!CollectionUtils.isEmpty(recordList)) {
             //倒序排
             recordList.sort(Comparator.comparing(MonitorIndicatorRecord::getDataTime).reversed());
-
+            Date checkDate = alarmDate;
             if (!StringUtils.isBlank(tempFormula)) {
                 if (!CollectionUtils.isEmpty(recordList)) {
                     for (MonitorIndicatorRecord record : recordList) {
@@ -568,11 +577,12 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
                         if (!isFlag) {
                             return record.getDataTime();
                         }
+                        checkDate = record.getDataTime();
                     }
                 }
             }
             //继续往前找报警开始日期
-            return getStartAlarmDate(checkStartDate, projectId, objId, indicatorId, operator, tempFormula);
+            return getStartAlarmDate(checkDate, projectId, objId, indicatorId, operator, tempFormula);
         }
         return alarmDate;
     }
@@ -613,12 +623,17 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
     /**
      * 冷却塔 日均计算
      */
-    Date computeCoolTowerData(Date startDate, Date endDate, String projectId, String cTObjId, EnumMaintenanceIndicatorType indicatorType) throws Exception {
+    Date computeCoolTowerData(Date startDate, Date endDate, ProjectDTO projectDTO, String cTObjId, EnumMaintenanceIndicatorType indicatorType) throws Exception {
+//        Date runDate = null;
+//        //获取冷却塔下所有风机运行时时间列表(所有风机运行时间合并为一组时间列表)
+//        Map<Date, List<Date>> allDateRunDataMap = getCoolTowerRunDateMap(projectId, startDate, endDate);
+//        //获取持续运行2小时之后的  时间点集合
+//        Map<Date, List<Date>> dateRunDataMap = getCoolTowerContinuedRunDateMap(allDateRunDataMap);
+
         Date runDate = null;
-        //获取冷却塔下所有风机运行时时间列表(所有风机运行时间合并为一组时间列表)
-        Map<Date, List<Date>> allDateRunDataMap = getCoolTowerRunDateMap(projectId, startDate, endDate);
-        //获取持续运行2小时之后的  时间点集合
-        Map<Date, List<Date>> dateRunDataMap = getCoolTowerContinuedRunDateMap(allDateRunDataMap);
+        Map<Date, List<TimeDataDTO>> dayTimeDataMap = getServiceDataFromCenterDataService(projectDTO.getProjectId(), cTObjId, EnumCoolWaterPointNameType.RunStatus.getCode(), startDate, endDate);
+        //获取日 对应运行时间集合
+        Map<Date, List<Date>> dateRunDataMap = getContinuedRunDateMap(dayTimeDataMap);
         //获取冷却水回水干管温度数据集合
         Map<Date, List<TimeDataDTO>> dayCoolWaterMainReturnTempMap = null;
         //获取室外湿球温度数据集合
@@ -626,19 +641,21 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
         //计算日均
         if (dateRunDataMap.size() > 0) {
             //获取中央供冷系统对象
-            List<JSONObject> object2List = getEqObjectList(projectId, "ACCC");
+            List<JSONObject> object2List = getEqObjectList(projectDTO.getProjectId(), "ACCC");
             if (!CollectionUtils.isEmpty(object2List)) {
                 JSONObject object = object2List.get(0);
                 String objId = object.getString("id");
-                dayCoolWaterMainReturnTempMap = getServiceDataFromCenterDataService(projectId, objId, EnumCoolTowerPointNameType.CoolWaterMainReturnTemp.getCode(), startDate, endDate);
+                dayCoolWaterMainReturnTempMap = getServiceDataFromCenterDataService(projectDTO.getProjectId(), objId, EnumCoolTowerPointNameType.CoolWaterMainReturnTemp.getCode(), startDate, endDate);
             }
+            //计算出 湿球温度数据集合
+            dayTwdTempMap = computerWetBallTempMap(projectDTO,startDate,endDate);
             //获取中央供冷系统对象
-            List<JSONObject> object3List = getEqObjectList(projectId, "WEMMMS");
-            if (!CollectionUtils.isEmpty(object3List)) {
-                JSONObject object = object3List.get(0);
-                String objId = object.getString("id");
-                dayTwdTempMap = getServiceDataFromCenterDataService(projectId, objId, EnumCoolTowerPointNameType.Twb.getCode(), startDate, endDate);
-            }
+//            List<JSONObject> object3List = getEqObjectList(projectDTO.getProjectId(), "WEMMMS");
+//            if (!CollectionUtils.isEmpty(object3List)) {
+//                JSONObject object = object3List.get(0);
+//                String objId = object.getString("id");
+//                dayTwdTempMap = getServiceDataFromCenterDataService(projectDTO.getProjectId(), objId, EnumCoolTowerPointNameType.Twb.getCode(), startDate, endDate);
+//            }
         }
         //循环计算日均
         for (Date dayDate = startDate; dayDate.before(endDate); dayDate = DateUtils.addDays(dayDate, 1)) {
@@ -649,7 +666,7 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
             monitorIndicatorRecord.setMonitorIndicatorId(indicatorType.getCode());
             monitorIndicatorRecord.setDataTime(dayDate);
             monitorIndicatorRecord.setObjId(cTObjId);
-            monitorIndicatorRecord.setProject(projectId);
+            monitorIndicatorRecord.setProject(projectDTO.getProjectId());
             monitorIndicatorRecord.setDataValue(dayAvg);
             monitorIndicatorRecordService.saveOrUpdateByPk(monitorIndicatorRecord);
             runDate = dayDate;
@@ -723,7 +740,7 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
                         //冷凝温度、冷凝器出口水温 均不为空
                         if (firstDateDataMap.containsKey(date) && null != firstDateDataMap.get(date)
                                 && secondDateDataMap.containsKey(date) && null != secondDateDataMap.get(date)) {
-                            Double divideTemp = DataUtils.divide(firstDateDataMap.get(date), secondDateDataMap.get(date));
+                            Double divideTemp = DataUtils.subtract(firstDateDataMap.get(date), secondDateDataMap.get(date));
                             totalVal = totalVal == null ? divideTemp : DataUtils.plus(totalVal, divideTemp);
                             num++;
                         }
@@ -789,10 +806,17 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
                     }
                     List<Date> dateList = new ArrayList<>();
                     for (TimeDataDTO dto : dataDTOList) {
+                        if (null == dto.getData()){
+                            continue;
+                        }
                         String time = dto.getTime();
                         Date getDate = com.persagy.apm.diagnose.utils.DateUtils.str2Date(time, com.persagy.apm.diagnose.utils.DateUtils.SDFSECOND);
                         if (getDate.compareTo(twoHourDate) > 0) {
-                            if (Objects.equals(EnumRunStatusType.Open.getCode(), dto.getData())) {
+//                            if (Objects.equals(EnumRunStatusType.Open.getCode(), dto.getData())) {
+//                                dateList.add(getDate);
+//                            }
+                            //TODO 测试 运行状态
+                            if (dto.getData() > runStateDownLimit && dto.getData() < runStateUpLimit) {
                                 dateList.add(getDate);
                             }
                         }
@@ -862,8 +886,14 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
                         dateList = dateRunDataMap.get(dayDate);
                     }
                     for (TimeDataDTO dto : dataDTOList) {
+                        if (null == dto.getData()){
+                            continue;
+                        }
                         Date getDate = com.persagy.apm.diagnose.utils.DateUtils.str2Date(dto.getTime(), com.persagy.apm.diagnose.utils.DateUtils.SDFSECOND);
-                        if (Objects.equals(EnumRunStatusType.Open.getCode(), dto.getData())) {
+//                        if (Objects.equals(EnumRunStatusType.Open.getCode(), dto.getData())) {
+//                            dateList.add(getDate);
+//                        }
+                        if (dto.getData() > runStateDownLimit && dto.getData() < runStateUpLimit) {
                             dateList.add(getDate);
                         }
                     }
@@ -888,9 +918,16 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
                 String time = dto.getTime();
                 Date getDate = com.persagy.apm.diagnose.utils.DateUtils.str2Date(time, com.persagy.apm.diagnose.utils.DateUtils.SDFSECOND);
                 if (getDate.compareTo(firstDate) >= 0 && getDate.compareTo(twoHourDate) <= 0) {
-                    if (Objects.equals(EnumRunStatusType.Close.getCode(), dto.getData())) {
+                    if (null == dto.getData()){
+                        continue;
+                    }
+                    //TODO 测试 运行状态
+                    if (dto.getData() < runStateDownLimit || dto.getData() > runStateUpLimit) {
                         return false;
                     }
+//                    if (Objects.equals(EnumRunStatusType.Close.getCode(), dto.getData())) {
+//                        return false;
+//                    }
                 }
             }
         } catch (Exception e) {
@@ -905,10 +942,14 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
     public String getFirstRunDate(List<TimeDataDTO> dataDTOList) {
         try {
             for (TimeDataDTO dto : dataDTOList) {
-                //
-                if (Objects.equals(EnumRunStatusType.Open.getCode(), dto.getData())) {
+                if (null == dto.getData()){
+                    continue;
+                }
+//                if (Objects.equals(EnumRunStatusType.Open.getCode(), dto.getData())) {
+//                    return dto.getTime();
+//                }
+                if (dto.getData() > runStateDownLimit && dto.getData() < runStateUpLimit) {
                     return dto.getTime();
-                    //return com.persagy.apm.diagnose.utils.DateUtils.str2Date(dto.getTime(), com.persagy.apm.diagnose.utils.DateUtils.SDF_SECOND);
                 }
             }
         } catch (Exception e) {
@@ -952,7 +993,7 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
         List<JSONObject> jsonToList = new ArrayList<>();
         try {
             List<String> classCodeList = new ArrayList<>();
-            classCodeList.add(classCode);//获取冷却塔下所有风机设备
+            classCodeList.add(classCode);
             JSONArray jsonArray = centerDataService.queryObjListByObjType(projectId, classCodeList);
             jsonToList = JSON.parseArray(jsonArray.toJSONString(), JSONObject.class);
         } catch (Exception e) {
@@ -962,55 +1003,6 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
     }
 
     /**
-     * redis中查询报警条件上次发数时间, 如果查询为空, 则初始化当前时间
-     */
-//    private ConfigItemDataSendTimeDTO getConfigItemSendTimeDTO(String projectId, AlarmConfigItem alarmConfigItem, Date defaultDate) {
-//        ConfigItemDataSendTimeDTO sendTimeDTO = (ConfigItemDataSendTimeDTO) redisUtil.hget(RedisUtil.PROJECT_ITEM_SEND_TIME + ":" + projectId, alarmConfigItem.getId());
-////        ConfigItemDataSendTimeDTO sendTimeDTO = null;
-//        if (sendTimeDTO == null) {
-//            sendTimeDTO = ConfigItemDataSendTimeDTO.builder().objId(alarmConfigItem.getObjId()).configItemid(alarmConfigItem.getId()).lastSendTime(defaultDate).build();
-//        }
-//        return sendTimeDTO;
-//    }
-
-    /**
-     * 从缓存中获取报警条件, 如果缓存不存在, 则查询报警服务, 报警条件配置
-     */
-//    private List<AlarmConfigItem> getAlarmConfigItemList(String projectId) throws Exception {
-//        List<AlarmConfigItem> itemList = (List<AlarmConfigItem>) redisUtil.hget(RedisUtil.PROJECT_ALARM_ITEM, projectId);
-//        if (CollectionUtils.isEmpty(itemList)) {
-//            QueryAlarmConfigDTO queryAlarmConfigDTO = new QueryAlarmConfigDTO();
-//            queryAlarmConfigDTO.setProjectId(projectId);
-//            queryAlarmConfigDTO.setGroupCode(systemCode);
-//            queryAlarmConfigDTO.setCategory(Collections.singletonList(EnumAlarmCategory.EQWB.getCode()));
-//            queryAlarmConfigDTO.setOpen(1);
-//            DmpResult<List<AlarmConfigItem>> configItemResult = alarmConfigService.query(queryAlarmConfigDTO);
-//            itemList = DmpResultUtil.getData(configItemResult);
-//            redisUtil.hset(RedisUtil.PROJECT_ALARM_ITEM, projectId, itemList, ConfigItemKeyTime);
-//        } else {
-//            List<AlarmConfigItem> newItemList = new ArrayList<>();
-//            itemList.forEach(alarmConfigItem -> {
-//                if (alarmConfigItem.getCategory().equals(EnumAlarmCategory.EQWB.getCode())) {
-//                    newItemList.add(alarmConfigItem);
-//                }
-//            });
-//            if (CollectionUtils.isEmpty(newItemList)) {
-//                QueryAlarmConfigDTO queryAlarmConfigDTO = new QueryAlarmConfigDTO();
-//                queryAlarmConfigDTO.setProjectId(projectId);
-//                queryAlarmConfigDTO.setGroupCode(systemCode);
-//                queryAlarmConfigDTO.setCategory(Collections.singletonList(EnumAlarmCategory.EQWB.getCode()));
-//                queryAlarmConfigDTO.setOpen(1);
-//                DmpResult<List<AlarmConfigItem>> configItemResult = alarmConfigService.query(queryAlarmConfigDTO);
-//                itemList = DmpResultUtil.getData(configItemResult);
-//                redisUtil.hset(RedisUtil.PROJECT_ALARM_ITEM, projectId, itemList, ConfigItemKeyTime);
-//            } else {
-//                itemList = newItemList;
-//            }
-//        }
-//        return itemList;
-//    }
-
-    /**
      * 获取报警记录
      */
     private Map<String, AlarmRecordItem> getAlarmRecordItemMap(String projectId) throws Exception {
@@ -1023,7 +1015,7 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
         DmpResult<List<AlarmRecordItem>> configItemResultList = alarmRecordService.query(queryAlarmRecordDTO);
         List<AlarmRecordItem> alarmRecordItemList = DmpResultUtil.getData(configItemResultList);
         if (!CollectionUtils.isEmpty(alarmRecordItemList)){
-            alarmRecordItemList.stream().collect(Collectors.toMap(AlarmRecordItem::getObjId, Function.identity(), (a, b) -> b));
+            return alarmRecordItemList.stream().collect(Collectors.toMap(AlarmRecordItem::getObjId, Function.identity(), (a, b) -> b));
         }
         return new HashMap<>();
     }
@@ -1094,4 +1086,74 @@ public class ProjectDataRecordServiceImpl implements IProjectDataRecordService {
         }
         return objIdAndInfoCode;
     }
+
+    public Map<Date, List<TimeDataDTO>> computerWetBallTempMap(ProjectDTO projectDTO,Date startDate,Date endDate){
+        try {
+            //根据室外天气数据计算出湿球温度数据
+            Map<Date, List<WeatherDTO>> dayWeatherDataMap = getWeatherTemp(projectDTO,startDate,endDate);
+            if (null != dayWeatherDataMap && dayWeatherDataMap.size() > 0){
+                Map<Date, List<TimeDataDTO>> dayTwdTempMap = new HashMap<>();
+                for (Date dayDate:dayWeatherDataMap.keySet()) {
+                    List<WeatherDTO> dtoList = dayWeatherDataMap.get(dayDate);
+                    if (CollectionUtils.isEmpty(dtoList)){
+                        continue;
+                    }
+                    List<TimeDataDTO> timeDataDTOList = new ArrayList<>();
+                    for (WeatherDTO dto:dtoList) {
+                        //根据温度和湿度 计算出湿空气焓值
+                        Double hVal = TwdTempUtil.getHVal(dto.getTemperature(),dto.getHumidity());
+                        //根据允许范围推出Tw值
+                        Double Tw = TwdTempUtil.getTw(dto.getTemperature(),hVal,TwdTemp_Limit);
+                        log.info("项目编号为:"+projectDTO.getProjectId()+"日期为:"+dto.getHourTime()+"温度:"+dto.getTemperature()+"湿度:"+dto.getHumidity()+"湿球温度:"+Tw);
+                        //小时时间
+                        Date hour = dto.getHourTime();
+                        Date nextHour = com.persagy.apm.diagnose.utils.DateUtils.addHours(hour,1);
+                        for (Date starthour = hour; starthour.before(nextHour) ; starthour = com.persagy.apm.diagnose.utils.DateUtils.addMinutes(starthour,15)) {
+                            TimeDataDTO timeDataDTO = new TimeDataDTO();
+                            timeDataDTO.setTime(com.persagy.apm.diagnose.utils.DateUtils.date2Str(starthour, com.persagy.apm.diagnose.utils.DateUtils.SDFSECOND));
+                            timeDataDTO.setData(Tw);
+                            timeDataDTOList.add(timeDataDTO);
+                        }
+                    }
+                    dayTwdTempMap.put(dayDate,timeDataDTOList);
+                }
+                return dayTwdTempMap;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+    /**
+     * 获取项目 天气数据
+     */
+    public Map<Date, List<WeatherDTO>> getWeatherTemp(ProjectDTO projectDTO,Date startDate,Date endDate){
+        try {
+            String startTime = com.persagy.apm.diagnose.utils.DateUtils.date2Str(startDate, com.persagy.apm.diagnose.utils.DateUtils.SDF_SECOND);
+            String endTime = com.persagy.apm.diagnose.utils.DateUtils.date2Str(endDate, com.persagy.apm.diagnose.utils.DateUtils.SDF_SECOND);
+            List<WeatherDTO> weatherDTOList = weatherService.hourHistoryData(projectDTO.getCity(),startTime,endTime,true,2);
+            if (!CollectionUtils.isEmpty(weatherDTOList)){
+                Map<Date, List<WeatherDTO>> dayTimeWeatherDataMap = new HashMap<>();
+                for (WeatherDTO dto : weatherDTOList) {
+//                    String time = dto.getHourTime();
+//                    Date timeDate = com.persagy.apm.diagnose.utils.DateUtils.str2Date(time, com.persagy.apm.diagnose.utils.DateUtils.SDF_SECOND);
+                    Date dayDate = DateUtils.truncate(dto.getHourTime(), Calendar.DATE);
+                    if (dayTimeWeatherDataMap.containsKey(dayDate)) {
+                        dayTimeWeatherDataMap.get(dayDate).add(dto);
+                    } else {
+                        List<WeatherDTO> dataDTOS = new ArrayList<>();
+                        dataDTOS.add(dto);
+                        dayTimeWeatherDataMap.put(dayDate, dataDTOS);
+                    }
+                }
+                return dayTimeWeatherDataMap;
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+    }
+
+
 }

+ 56 - 0
src/main/java/com/persagy/apm/diagnose/service/CenterDataService.java

@@ -9,6 +9,7 @@ import com.alibaba.fastjson.JSONObject;
 import com.persagy.apm.diagnose.constant.EnumDataTimeType;
 import com.persagy.apm.diagnose.feign.client.CenterMiddlewareClient;
 import com.persagy.apm.diagnose.service.dto.ObjRelationDataDTO;
+import com.persagy.apm.diagnose.service.dto.ProjectDTO;
 import com.persagy.apm.diagnose.service.dto.TimeDataDTO;
 import com.persagy.apm.diagnose.utils.DataUtils;
 import com.persagy.apm.diagnose.utils.DateUtils;
@@ -33,6 +34,7 @@ public class CenterDataService{
 	private CenterMiddlewareClient centerMiddlewareClient;
 
 
+
 	public JSONArray queryObjListByObjType(String projectId, List<String> classCodeList) throws Exception {
 		JSONArray resultArray = new JSONArray();
 		Map<String, Object> requestMap = new HashMap<>();
@@ -211,4 +213,58 @@ public class CenterDataService{
 		}
 		return resultArray;
 	}
+
+
+    public List<ProjectDTO> queryProjectList() throws Exception {
+        List<ProjectDTO> list = new ArrayList<>();
+        Map<String, Object> requestMap = new HashMap<>();
+        try {
+            Map<String, Object> criteria = new HashMap<>();
+            List<String> typeList = new ArrayList<>();
+            typeList.add("Pj");
+            criteria.put("type",typeList);
+            criteria.put("groupCode", systemCode);
+            requestMap.put("criteria", criteria);
+            String result = centerMiddlewareClient.queryProject(requestMap);
+
+            if (null != result) {
+                JSONObject responseMap = JSONObject.parseObject(result);
+                if (null != responseMap && !responseMap.isEmpty() && SUCCESS.equals(responseMap.get("Result"))) {
+                    List<Map> contentList = (List<Map>) responseMap.get("Content");
+                    if (CollectionUtils.isEmpty(contentList)) {
+                        return list;
+                    }
+                    for (Map map : contentList) {
+                        Map infoMap = (Map)map.get("infos");
+                        if (null == infoMap) {
+                            continue;
+                        }
+                        String projID = (String) infoMap.get("ProjID");
+                        if (StringUtils.isEmpty(projID)) {
+                            continue;
+                        }
+                        String projLocalID = (String) infoMap.get("ProjLocalID");
+                        if (StringUtils.isEmpty(projLocalID)) {
+                            continue;
+                        }
+                        String city = (String) infoMap.get("City");
+                        if (StringUtils.isEmpty(city)) {
+                            continue;
+                        }
+                        ProjectDTO dto = new ProjectDTO();
+                        dto.setProjectId(projID);
+                        dto.setProjectLocalId(projLocalID);
+                        dto.setCity(city);
+                        list.add(dto);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            log.error("获取项目列表错误,错误原因:" + e);
+            log.error("查询数据中台queryObject参数:" + requestMap);
+            throw e;
+        }
+        return list;
+    }
+
 }

+ 2 - 2
src/main/java/com/persagy/apm/diagnose/service/ComputeIndicatorDataService.java

@@ -66,7 +66,7 @@ public class ComputeIndicatorDataService {
         latch.await();
         futureList.forEach(future -> {
             try {
-                log.info(future.get());
+                log.error(future.get());
             } catch (Exception e) {
                 log.error("计算项目指标数据错误:" + CommonUtils.getExceptionStackTrace(e));
             }
@@ -92,7 +92,7 @@ public class ComputeIndicatorDataService {
         latch.await();
         futureList.forEach(future -> {
             try {
-                log.info(future.get());
+                log.error(future.get());
             } catch (Exception e) {
                 log.error("发送指标数据错误:" + CommonUtils.getExceptionStackTrace(e));
             }

+ 4 - 2
src/main/java/com/persagy/apm/diagnose/service/MaintenanceDataService.java

@@ -23,6 +23,8 @@ public class MaintenanceDataService {
     @Autowired
     private SaasWebServiceImpl saasWebServiceImpl;
     @Autowired
+    private CenterDataService centerDataService;
+    @Autowired
     private IProjectDataRecordService projectDataRecordService;
 
     /**
@@ -31,7 +33,7 @@ public class MaintenanceDataService {
     public void computeMaintenanceData() throws Exception {
 
         //查询项目列表
-        List<ProjectDTO> projectDTOList = saasWebServiceImpl.queryProjectDTOList(null);
+        List<ProjectDTO> projectDTOList = centerDataService.queryProjectList();
         if (CollectionUtils.isEmpty(projectDTOList)) {
             return;
         }
@@ -41,7 +43,7 @@ public class MaintenanceDataService {
         List<Future<String>> futureList = new ArrayList<>();
         CountDownLatch latch = new CountDownLatch(projectDTOList.size());
         for (ProjectDTO projectDTO : projectDTOList) {
-            futureList.add(projectDataRecordService.computeMaintenanceData(todayDate,projectDTO.getProjectId(), latch));
+            futureList.add(projectDataRecordService.computeMaintenanceData(todayDate,projectDTO, latch));
         }
         //等待所有任务执行完
         latch.await();

+ 3 - 7
src/main/java/com/persagy/apm/diagnose/service/NettyAlarmServiceImpl.java

@@ -67,13 +67,9 @@ public class NettyAlarmServiceImpl extends NettyAlarmService {
         JSONObject supplement = new JSONObject();
         if (!CollectionUtils.isEmpty(objectList)) {
             supplement.put("alarm_obj_name", objectList.get(0).get("localName"));
-            String itemCode = alarmRecord.getString("itemCode");
-            String category = getAlarmCategory(alarmUrlParam, itemCode);
-            if (EnumAlarmCategory.EQWB.equals(category)){//报警分类   //维保
-                supplement.put("specification",objectList.get(0).getString("specification"));//设备型号
-                supplement.put("equip_local_id",objectList.get(0).getString("localId"));//设备本地编码
-                supplement.put("equip_local_name",objectList.get(0).getString("localName"));//设备本地名称
-            }
+            supplement.put("specification",objectList.get(0).getString("specification"));//设备型号
+            supplement.put("equip_local_id",objectList.get(0).getString("localId"));//设备本地编码
+            supplement.put("equip_local_name",objectList.get(0).getString("localName"));//设备本地名称
         }
         return supplement;
     }

+ 28 - 0
src/main/java/com/persagy/apm/diagnose/service/SaasWebServiceImpl.java

@@ -70,4 +70,32 @@ public class SaasWebServiceImpl {
         return result;
     }
 
+    public List<ProjectDTO> getProjectByIdService(String projectId) throws Exception {
+        JSONObject param = new JSONObject();
+        JSONObject puser = new JSONObject();
+        puser.put("userId", USERID);
+        puser.put("loginDevice", LOGINDEVICE);
+        puser.put("pd", DEFAULT_PD);
+        param.put("puser", puser);
+        param.put("groupCode",systemCode);
+        param.put("projectId", projectId);
+        String resultStr = saasWebClient.getProjectByIdService(param.toJSONString());
+        JSONObject parseObject = JSONObject.parseObject(resultStr);
+        if ("failure".equals(parseObject.getString("result"))) {
+            throw new Exception("查询分区失败:" + parseObject.getString("reson"));
+        }
+        List<ProjectDTO> result = new ArrayList<>();
+        JSONArray jsonArray = parseObject.getJSONArray("content");
+        if (jsonArray == null || jsonArray.isEmpty()) {
+            return result;
+        }
+
+        for (Object object : jsonArray) {
+            JSONObject obj = (JSONObject) object;
+            ProjectDTO projectDTO = ProjectDTO.builder().projectId(obj.getString("projectId")).projectLocalId(obj.getString("projectLocalID")).build();
+            result.add(projectDTO);
+        }
+        return result;
+    }
+
 }

+ 89 - 0
src/main/java/com/persagy/apm/diagnose/service/WeatherServiceImpl.java

@@ -0,0 +1,89 @@
+package com.persagy.apm.diagnose.service;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.persagy.apm.diagnose.maintenance.model.dto.WeatherDTO;
+import com.persagy.apm.diagnose.utils.HttpUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+import org.springframework.util.CollectionUtils;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 天气服务
+ */
+@Service
+@Slf4j
+public class WeatherServiceImpl {
+
+    /**
+     * 天气服务
+     */
+    @Value(value = "${weather.server}")
+    public String emsWeatherServer;
+    private static final String SUCCESS = "success";
+    /**
+     * 天气服务系统-获取历史小时天气 最大支持查询7天的数据。
+     */
+    public static final String HOUR_HISTORY_DATA = "/Spring/MVC/entrance/unifier/HourHistoryData";
+
+    public List<WeatherDTO> hourHistoryData(String cityCode, String startTimeStr, String endTimeStr, Boolean minResponse, int reqCount) throws Exception {
+        String requestUrl = emsWeatherServer + HOUR_HISTORY_DATA;
+        JSONObject param = new JSONObject();
+        param.put("cityCode", cityCode);
+        param.put("startTime", startTimeStr);
+        param.put("endTime", endTimeStr);
+        param.put("minResponse", minResponse);
+
+        Map<String, Object> paramMap = new HashMap<>();
+        paramMap.put("jsonString", param);
+
+        try {
+            String result = HttpUtils.httpPostFormUrlencoded(requestUrl, paramMap);
+
+            JSONObject resultObj = JSONObject.parseObject(result, JSONObject.class);
+
+            if (!resultObj.getString("result").equalsIgnoreCase(SUCCESS)) {
+                log.error("查询室外小时天气历史数据返回结果:{}", result);
+            /*// todo 由于在没有数据情况下接口返回也是失败,但是其实是成功,所以不抛异常
+            if (null != resultObj.get("reason")) {
+                throw new Exception("查询小时天气历史数据请求返回失败");
+            }*/
+                return new ArrayList<>();
+               // throw new Exception("查询小时天气历史数据请求返回失败");
+            }
+            List<JSONObject> jsonObjectList = JSON.parseArray(JSON.toJSONString(resultObj.get("content")), JSONObject.class);
+            if (!CollectionUtils.isEmpty(jsonObjectList)){
+                List<WeatherDTO> weatherDTOList = new ArrayList<>();
+                for (JSONObject obj:jsonObjectList) {
+                    //温湿度 任意为空 跳过
+                    if (null == obj.getDouble("temperature") || null == obj.getDouble("humidity")){
+                        continue;
+                    }
+                    WeatherDTO dto = new WeatherDTO();
+                    dto.setHourTime(obj.getDate("hourTime"));
+                    dto.setTemperature(obj.getDouble("temperature"));
+                    dto.setHumidity(obj.getDouble("humidity"));
+                    weatherDTOList.add(dto);
+                }
+                return weatherDTOList;
+            }
+        } catch (Exception e) {
+            log.error("---------获取室外小时天气历史数据出错了---------");
+            log.error("出错的请求路径是:{}", requestUrl);
+            log.error("出错的请求参数是:{}", JSON.toJSONString(paramMap));
+            // 重试
+            Thread.sleep(100);
+            if (reqCount < 5) {
+                return hourHistoryData(cityCode, startTimeStr, endTimeStr, minResponse, reqCount + 1);
+            }
+           // throw new Exception("查询小时天气历史数据请求出错");
+        }
+        return new ArrayList<>();
+    }
+}

+ 1 - 0
src/main/java/com/persagy/apm/diagnose/service/dto/ProjectDTO.java

@@ -21,4 +21,5 @@ import lombok.NoArgsConstructor;
 public class ProjectDTO {
 	private String projectId;
 	private String projectLocalId;
+	private String city;
 }

+ 2 - 2
src/main/java/com/persagy/apm/diagnose/service/schedule/ComputeIndicatorData.java

@@ -27,8 +27,8 @@ public class ComputeIndicatorData {
     	    //指标计算未开启
     	    return;
 		}
-        log.info("【监测指标数据计算线程】计算指标数据开始.........");
+        log.error("【监测指标数据计算线程】计算指标数据开始.........");
         computeIndicatorDataService.computeIndicatorData();
-        log.info("【监测指标数据计算线程】计算指标数据结束.........");
+        log.error("【监测指标数据计算线程】计算指标数据结束.........");
     }
 }

+ 2 - 1
src/main/java/com/persagy/apm/diagnose/service/schedule/SendIndicatorData.java

@@ -27,7 +27,8 @@ public class SendIndicatorData {
     	    //指标计算未开启
     	    return;
 		}
-        log.info("【发送监测指标数据线程】:发送指标数据开始.......");
+        log.error("【发送监测指标数据线程】:发送指标数据开始.......");
         computeIndicatorDataService.sendIndicatorData();
+        log.error("【发送监测指标数据线程】:发送指标数据结束.......");
     }
 }

+ 32 - 1
src/main/java/com/persagy/apm/diagnose/utils/CollectDataUtil.java

@@ -4,6 +4,7 @@ import com.persagy.framework.ems.data.pojo.hbase.MonitorIndicatorRecord;
 import org.springframework.util.CollectionUtils;
 
 import java.util.List;
+import java.util.Map;
 
 
 /**
@@ -15,7 +16,7 @@ import java.util.List;
  */
 public class CollectDataUtil {
 
-    public static String buildSendParam(List<MonitorIndicatorRecord> recordList,String alarmItemCode) throws Exception {
+    public static String buildSendParam(List<MonitorIndicatorRecord> recordList, String alarmItemCode) throws Exception {
 
         if (CollectionUtils.isEmpty(recordList)) {
             return null;
@@ -48,4 +49,34 @@ public class CollectDataUtil {
     }
 
 
+    public static String batchBuildSendParam(Map<String, List<MonitorIndicatorRecord>> sendTimeKeyAndDataList, String alarmItemCode) {
+        StringBuilder stringBuilder = new StringBuilder();
+
+        for (Map.Entry<String, List<MonitorIndicatorRecord>> entry : sendTimeKeyAndDataList.entrySet()) {
+            String date = entry.getKey();
+            stringBuilder.append(date).append(";");
+            List<MonitorIndicatorRecord> list = entry.getValue();
+            MonitorIndicatorRecord record1 = list.get(0);
+            stringBuilder.append(alarmItemCode).append(";");
+            stringBuilder.append(record1.getObjId()).append(";");
+            for (int i = 0; i < list.size(); i++) {
+                stringBuilder.append(list.get(i).getMonitorIndicatorId());
+                if (i == (list.size() - 1)) {
+                    stringBuilder.append(";");
+                } else {
+                    stringBuilder.append(",");
+                }
+            }
+            for (int i = 0; i < list.size(); i++) {
+                stringBuilder.append(list.get(i).getDataValue());
+                if (i == (list.size() - 1)) {
+                    stringBuilder.append(";");
+                } else {
+                    stringBuilder.append(",");
+                }
+            }
+        }
+        return stringBuilder.toString();
+
+    }
 }

+ 205 - 0
src/main/java/com/persagy/apm/diagnose/utils/HttpUtils.java

@@ -0,0 +1,205 @@
+package com.persagy.apm.diagnose.utils;
+
+import org.apache.http.HttpEntityEnclosingRequest;
+import org.apache.http.HttpRequest;
+import org.apache.http.NameValuePair;
+import org.apache.http.NoHttpResponseException;
+import org.apache.http.client.HttpRequestRetryHandler;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.config.Registry;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.conn.ConnectTimeoutException;
+import org.apache.http.conn.socket.ConnectionSocketFactory;
+import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
+import org.apache.http.conn.socket.PlainConnectionSocketFactory;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.entity.FileEntity;
+import org.apache.http.entity.InputStreamEntity;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLHandshakeException;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.net.UnknownHostException;
+import java.util.*;
+
+/**
+ * http工具
+ */
+public class HttpUtils {
+
+    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
+    private static final CloseableHttpClient HTTP_CLIENT;
+    private static final String UTF8 = "utf-8";
+
+    static {
+        //加载配置文件
+        InputStream inputStream = HttpUtils.class.getResourceAsStream("/config/system.properties");
+        Properties properties = new Properties();
+        if (inputStream != null) {
+            try {
+                properties.load(inputStream);
+            } catch (Exception e) {
+                // TODO Auto-generated catch block
+                e.printStackTrace();
+            }
+        }
+
+        String connectTimeoutString = properties.getProperty("httpclient.connect.timeout", "1000");
+        String connectionRequestTimeoutString = properties.getProperty("httpclient.request.timeout", "1000");
+        String socketTimeoutString = properties.getProperty("httpclient.socket.timeout", "3600000");
+
+        String maxTotalString = properties.getProperty("httpclient.pool.total", "1200");
+        String defaultMaxPerRouteString = properties.getProperty("httpclient.pool.per.route", "200");
+
+        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
+        LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
+        Registry<ConnectionSocketFactory> registry = RegistryBuilder
+                .<ConnectionSocketFactory>create().register("http", plainsf)
+                .register("https", sslsf).build();
+        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
+        // 将最大连接数增加
+        Integer maxTotal = Integer.valueOf(maxTotalString);
+        cm.setMaxTotal(maxTotal);
+        // 将每个路由基础的连接增加
+        Integer defaultMaxPerRoute = Integer.valueOf(defaultMaxPerRouteString);
+        cm.setDefaultMaxPerRoute(defaultMaxPerRoute);
+        //host
+        /*HttpHost httpHost = new HttpHost(hostname, port);
+        // 将目标主机的最大连接数增加
+        cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);*/
+
+        // 请求重试处理
+        HttpRequestRetryHandler httpRequestRetryHandler = (exception, executionCount, context) -> {
+            // 如果已经重试了5次,就放弃
+            if (executionCount >= 5) {
+                return false;
+            }
+            // 如果服务器丢掉了连接,那么就重试
+            if (exception instanceof NoHttpResponseException) {
+                return true;
+            }
+            // 不要重试SSL握手异常
+            if (exception instanceof SSLHandshakeException) {
+                return false;
+            }
+            // 连接被拒绝
+            if (exception instanceof ConnectTimeoutException) {
+                return false;
+            }
+            // 超时
+            if (exception instanceof InterruptedIOException) {
+                return false;
+            }
+            // 目标服务器不可达
+            if (exception instanceof UnknownHostException) {
+                return false;
+            }
+            // SSL握手异常
+            if (exception instanceof SSLException) {
+                return false;
+            }
+
+            HttpClientContext clientContext = HttpClientContext
+                    .adapt(context);
+            HttpRequest request = clientContext.getRequest();
+            // 如果请求是幂等的,就再次尝试
+            if (!(request instanceof HttpEntityEnclosingRequest)) {
+                return true;
+            }
+            return false;
+        };
+
+        //requestConfig
+        Integer connectionTimeout = Integer.valueOf(connectTimeoutString);
+        Integer requestTimeout = Integer.valueOf(connectionRequestTimeoutString);
+        Integer socketTimeout = Integer.valueOf(socketTimeoutString);
+        RequestConfig requestConfig = RequestConfig.custom()
+                // 连接建立时间,三次握手完成时间
+                .setConnectTimeout(connectionTimeout)
+                // 数据传输过程中数据包之间间隔的最大时间
+                .setSocketTimeout(socketTimeout)
+                // httpClient使用连接池来管理连接,这个时间就是从连接池获取连接的超时时间
+                .setConnectionRequestTimeout(requestTimeout).build();
+        HTTP_CLIENT = HttpClients.custom()
+                .setConnectionManager(cm)
+                .setRetryHandler(httpRequestRetryHandler)
+                .setDefaultRequestConfig(requestConfig).build();
+    }
+
+    public static String httpGetRequest(String url) throws Exception {
+        HttpGet httpGet = new HttpGet(url);
+        return sendRequest(httpGet);
+    }
+
+    public static String httpPostRequest(String url) throws Exception {
+        HttpPost httpPost = new HttpPost(url);
+        return sendRequest(httpPost);
+    }
+
+    public static String httpPostRequest(String url, Map<String, Object> params) throws IOException {
+        log.info("请求url:" + url);
+        log.info("参数是:{}", params.toString());
+        HttpPost httpPost = new HttpPost(url);
+        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
+        httpPost.setEntity(new StringEntity(JsonUtils.beanToJson(params), UTF8));
+        String respContent = sendRequest(httpPost);
+        log.info("返回值是:{}", respContent);
+        return respContent;
+    }
+
+    public static String httpPostFormUrlencoded(String url, Map<String, Object> params) throws IOException {
+        log.info("请求url:" + url);
+        log.info("参数是:{}", params.toString());
+        HttpPost httpPost = new HttpPost(url);
+        List<NameValuePair> pairs = new ArrayList<>();
+        Map.Entry entry;
+        for (Iterator var = params.entrySet().iterator(); var.hasNext(); pairs.add(new BasicNameValuePair((String) entry.getKey(), entry.getValue().toString()))) {
+            entry = (Map.Entry) var.next();
+        }
+        httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF8));
+        String respContent = sendRequest(httpPost);
+        log.info("返回值是:{}", respContent);
+        return respContent;
+    }
+
+    private static String sendRequest(HttpUriRequest request) throws IOException {
+        CloseableHttpResponse response = HTTP_CLIENT.execute(request);
+        return EntityUtils.toString(response.getEntity(), UTF8);
+    }
+
+    public static String httpPostRequest(String url, InputStream is) throws Exception {
+        HttpPost httpPost = new HttpPost(url);
+        httpPost.setEntity(new InputStreamEntity(is));
+        return sendRequest(httpPost);
+    }
+
+    public static String httpPostRequest(String url, File file) throws Exception {
+        HttpPost httpPost = new HttpPost(url);
+        httpPost.setEntity(new FileEntity(file));
+        return sendRequest(httpPost);
+    }
+
+    public static byte[] httpGetFile(String url) throws Exception {
+        HttpGet httpGet = new HttpGet(url);
+        CloseableHttpResponse response = HTTP_CLIENT.execute(httpGet);
+        return EntityUtils.toByteArray(response.getEntity());
+    }
+
+}

+ 143 - 0
src/main/java/com/persagy/apm/diagnose/utils/JsonUtils.java

@@ -0,0 +1,143 @@
+package com.persagy.apm.diagnose.utils;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.alibaba.fastjson.TypeReference;
+import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
+import com.alibaba.fastjson.util.TypeUtils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Type;
+import java.util.List;
+
+/**
+ * @Description json工具类
+ * @Author feng
+ * @Date 2018/7/19 12:17
+ * @Version 1.0
+ */
+public class JsonUtils {
+
+    static {
+        TypeUtils.compatibleWithJavaBean = true;
+    }
+
+    /**
+     * 将json字符串转换成java对象
+     *
+     * @param json 需要转化json字符
+     * @param cls  cls  返回实例对象类型
+     * @return T
+     */
+    public static <T> T jsonToBean(String json, Class<T> cls) {
+        return JSON.parseObject(json, cls);
+    }
+
+    public static <T> T getJsonFromInputStream(InputStream inputStream, Class<T> cls) throws IOException {
+
+        return JSON.parseObject(inputStream, cls);
+    }
+
+    /**
+     * 将json字符串转换成java对象
+     *
+     * @param json 需要转化json字符
+     * @param cls  cls  返回实例对象类型
+     * @return T
+     */
+    public static <T> T jsonToBean(String json, Type cls) {
+        return JSON.parseObject(json, cls);
+    }
+
+    /**
+     * 将json字符串转换成java对象
+     *
+     * @param json 需要转化json字符
+     * @return T
+     */
+    public static <T> T jsonToBean(String json) {
+        TypeReference<T> typeReference = new TypeReference<T>() {
+        };
+        return JSON.parseObject(json, typeReference.getType());
+    }
+
+    /**
+     * 将json字符串转换成java对象
+     *
+     * @param json 需要转化json字符
+     * @param cls  cls  返回实例对象类型
+     * @return T
+     */
+    public static <T> T jsonToBean(byte[] json, Class<T> cls) {
+        return JSON.parseObject(json, cls);
+    }
+
+
+    /**
+     * 将json字符串转换成java对象
+     *
+     * @param json 需要转化json字符
+     * @param cls  cls  返回实例对象类型
+     * @return T     TypeReference typeReference = new TypeReference<JsonBean>() {};
+     */
+    public static <T> T jsonToBean(byte[] json, Type cls) {
+        return JSON.parseObject(json, cls);
+    }
+
+
+    /**
+     * 将json字符串转换成java List对象
+     *
+     * @param json 需要转化json字符
+     * @param cls  cls  返回实例对象类型
+     * @return List<T>
+     */
+    public static <T> List<T> jsonToList(String json, Class<T> cls) {
+        return JSON.parseArray(json, cls);
+    }
+
+    /**
+     * 将bean对象转化成json字符串
+     *
+     * @param obj 转化的对象实例
+     * @return String  JSON 字符
+     */
+    public static String beanToJson(Object obj) {
+        String result = JSON.toJSONString(obj);
+        return result;
+    }
+
+    /**
+     * 将bean对象转化成json字符串
+     *
+     * @param obj    转化的对象实例
+     * @param filter 序列化处理
+     * @return String  JSON 字符
+     */
+    public static String beanToJson(Object obj, SimplePropertyPreFilter filter) {
+        return JSON.toJSONString(obj, filter);
+    }
+
+
+    /**
+     * 价格json字符转换JSONObject
+     *
+     * @param jsonString 需要转换的字符
+     * @return JSONObject
+     */
+    public static JSONObject parseJsonObject(String jsonString) {
+        return JSONObject.parseObject(jsonString);
+    }
+
+    /**
+     * 价格json字符转换JSONObject
+     *
+     * @param jsonString 需要转换的字符
+     * @return JSONObject
+     */
+    public static JSONArray parseJsonArray(String jsonString) {
+        return JSONArray.parseArray(jsonString);
+    }
+}

+ 92 - 0
src/main/java/com/persagy/apm/diagnose/utils/TwdTempUtil.java

@@ -0,0 +1,92 @@
+package com.persagy.apm.diagnose.utils;
+
+/**
+ * 湿球温度计算
+ */
+
+public class TwdTempUtil {
+
+    public static void main(String[] args) {
+        try {
+            //Td干球温度 Hr相对湿度 范围 0~100  允许差值 范围
+            Double Td = 30.0,Hr = 75.0,limit = 0.1;
+            //根据温度和湿度 计算出湿空气焓值
+            Double hVal = getHVal(Td,Hr);
+            //根据允许范围推出Tw值
+            Double newTw = getTw(Td,hVal,limit);
+            System.out.println(newTw);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 根据允许范围推出Tw值
+     */
+    public static Double getTw(Double Td, Double hVal, Double limit){
+        Double Tw = Td-3;
+        Double num = 0.0;
+        Boolean isOk = false;
+        Boolean isTrueVal = false;
+        Integer zNum = 0,jNum = 0;
+        while (!isOk){
+            //湿空气焓值
+            Double hwVal = getHwVal(Tw);
+            //两种湿空气焓值  差值
+            Double hc = DataUtils.subtract(hVal,hwVal);
+            //判断范围
+            if (hc<limit && hc > 0.0){
+                isOk = true;
+                isTrueVal = true;
+            }else if (hc > 0){//hw 小于 h  增加湿球温度数据值
+                Tw = Tw + 0.25;
+                zNum++;
+            }else if (hc < 0){//hw 大于 h  减小湿球温度数据值
+                Tw = Tw - 0.25;
+                jNum++;
+            }
+            num++;
+            if (num > 20){
+                isOk = true;
+            }
+        }
+        if (isTrueVal){
+            return Tw;
+        }else {
+            if (zNum > 0 && jNum > 0){
+                return Tw;
+            }else{
+                return getTw(Td,hVal,limit+0.5);
+            }
+        }
+    }
+
+    /**
+     * 根据湿球温度计算出湿空气焓值
+     */
+    public static double getHwVal(Double Tw){
+        Double eVal = (18.678-Tw/234.5)*Tw/(Tw+257.14);
+        Double ev= Math.exp(eVal);
+        Double Pv = 611.2 * ev; //Td时的水蒸汽饱和压力
+        //含湿量
+        Double dw = 0.6219*(Pv/(101326-Pv));
+        //湿空气焓值
+        Double hw = 1.01*Tw + (2500+1.84*Tw)*dw;
+        return hw;
+    }
+
+    /**
+     * 根据温度和湿度 计算出湿空气焓值
+     */
+    public static double getHVal(Double Td,Double Hr){
+        Double eVal = (18.678-Td/234.5)*Td/(Td+257.14);
+        Double ev= Math.exp(eVal);
+        Double Pv = 611.2*ev; //Td时的水蒸汽饱和压力
+        Double hrPv = 0.01*Hr*Pv;
+        //含湿量
+        Double d = 0.6219*(hrPv/(101326-hrPv));
+        //湿空气焓值
+        Double h = 1.01*Td + (2500+1.84*Td)*d;
+        return h;
+    }
+}

File diff suppressed because it is too large
+ 1 - 1
src/main/resources/db/init/table.sql


+ 0 - 120
src/main/resources/logback-diagnose.xml

@@ -1,120 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<configuration>
-    <contextName>${APP_NAME}</contextName>
-    <springProperty name="APP_NAME" scope="context" source="spring.application.name"/>
-    <springProperty name="LOG_FILE" scope="context" source="logging.file" defaultValue="../logs/${APP_NAME}/application"/>
-    <springProperty name="LOG_POINT_FILE" scope="context" source="logging.file" defaultValue="../logs/${APP_NAME}/point"/>
-    <springProperty name="LOG_AUDIT_FILE" scope="context" source="logging.file" defaultValue="../logs/${APP_NAME}/audit"/>
-    <springProperty name="LOG_MAXFILESIZE" scope="context" source="logback.filesize" defaultValue="100MB"/>
-    <springProperty name="LOG_FILEMAXDAY" scope="context" source="logback.filemaxday" defaultValue="7"/>
-    <springProperty name="LOG_TOTALSIZE" scope="context" source="logback.totalsize" defaultValue="1GB"/>
-    <springProperty name="ServerIP" scope="context" source="spring.cloud.client.ip-address" defaultValue="0.0.0.0"/>
-    <springProperty name="ServerPort" scope="context" source="server.port" defaultValue="0000"/>
-
-    <!-- 彩色日志 -->
-    <!-- 彩色日志依赖的渲染类 -->
-    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
-    <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
-    <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
-
-    <!-- 彩色日志格式 -->
-    <property name="CONSOLE_LOG_PATTERN"
-              value="[${APP_NAME}:${ServerIP}:${ServerPort}] %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%level){blue} %clr(${PID}){magenta} %clr([%X{traceId}]){yellow} %clr([%thread]){orange} %clr(%logger){cyan} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}" />
-    <property name="CONSOLE_LOG_PATTERN_NO_COLOR" value="[${APP_NAME}:${ServerIP}:${ServerPort}] %d{yyyy-MM-dd HH:mm:ss.SSS} %level ${PID} [%X{traceId}] [%thread] %logger %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}" />
-
-    <!-- 控制台日志 -->
-    <appender name="StdoutAppender" class="ch.qos.logback.core.ConsoleAppender">
-        <withJansi>true</withJansi>
-        <encoder>
-            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
-            <charset>UTF-8</charset>
-        </encoder>
-    </appender>
-    <!-- 按照每天生成常规日志文件 -->
-    <appender name="FileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
-        <file>${LOG_FILE}/${APP_NAME}.log</file>
-        <encoder>
-            <pattern>${CONSOLE_LOG_PATTERN_NO_COLOR}</pattern>
-            <charset>UTF-8</charset>
-        </encoder>
-        <!-- 基于时间的分包策略 -->
-        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
-			<fileNamePattern>${LOG_FILE}/${APP_NAME}.%d{yyyy-MM-dd}.%i.gz</fileNamePattern>
-			<!--单文件最大限制-->
-			<maxFileSize>${LOG_MAXFILESIZE}</maxFileSize>
-            <!--保留时间,单位:天-->
-            <maxHistory>${LOG_FILEMAXDAY}</maxHistory>
-            <!-- 日志总大小 -->
-            <totalSizeCap>${LOG_TOTALSIZE}</totalSizeCap>
-        </rollingPolicy>
-        <filter class="ch.qos.logback.classic.filter.LevelFilter">
-            <level>INFO</level>
-        </filter>
-    </appender>
-
-    <appender name="point_log" class="ch.qos.logback.core.rolling.RollingFileAppender">
-        <file>${LOG_POINT_FILE}/point.log</file>
-        <encoder>
-            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS}|${APP_NAME}|%msg%n</pattern>
-            <charset>UTF-8</charset>
-        </encoder>
-        <!-- 基于时间的分包策略 -->
-        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
-			<fileNamePattern>${LOG_POINT_FILE}/point.%d{yyyy-MM-dd}.%i.gz</fileNamePattern>
-			<!--单文件最大限制-->
-			<maxFileSize>${LOG_MAXFILESIZE}</maxFileSize>
-            <!--保留时间,单位:天-->
-            <maxHistory>${LOG_FILEMAXDAY}</maxHistory>
-            <!-- 日志总大小 -->
-            <totalSizeCap>${LOG_TOTALSIZE}</totalSizeCap>
-        </rollingPolicy>
-    </appender>
-
-    <appender name="audit_log" class="ch.qos.logback.core.rolling.RollingFileAppender">
-        <file>${LOG_AUDIT_FILE}/audit.log</file>
-        <encoder>
-            <pattern>%msg%n</pattern>
-            <charset>UTF-8</charset>
-        </encoder>
-        <!-- 基于时间的分包策略 -->
-        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
-			<fileNamePattern>${LOG_AUDIT_FILE}/audit.%d{yyyy-MM-dd}.%i.gz</fileNamePattern>
-			<!--单文件最大限制-->
-			<maxFileSize>${LOG_MAXFILESIZE}</maxFileSize>
-            <!--保留时间,单位:天-->
-            <maxHistory>${LOG_FILEMAXDAY}</maxHistory>
-            <!-- 日志总大小 -->
-            <totalSizeCap>${LOG_TOTALSIZE}</totalSizeCap>
-        </rollingPolicy>
-    </appender>
-
-    <appender name="file_async" class="ch.qos.logback.classic.AsyncAppender">
-        <discardingThreshold>0</discardingThreshold>
-        <appender-ref ref="FileAppender"/>
-    </appender>
-    <appender name="point_log_async" class="ch.qos.logback.classic.AsyncAppender">
-        <discardingThreshold>0</discardingThreshold>
-        <appender-ref ref="point_log"/>
-    </appender>
-    <logger name="com.persagy.log.util.PointUtil" level="info" addtivity="false">
-        <appender-ref ref="point_log_async" />
-    </logger>
-    <appender name="audit_log_async" class="ch.qos.logback.classic.AsyncAppender">
-        <discardingThreshold>0</discardingThreshold>
-        <appender-ref ref="audit_log"/>
-    </appender>
-    <logger name="com.persagy.log.service.impl.LoggerAuditServiceImpl" level="debug" addtivity="false">
-        <appender-ref ref="audit_log_async" />
-    </logger>
-	<!-- 剔除eureka client心跳日志 -->
-	<logger name="com.netflix.discovery.shared.resolver.aws.ConfigClusterResolver" level="WARN" />
-	
-<!--    <root level="INFO">-->
-<!--        <appender-ref ref="StdoutAppender"/>-->
-<!--        <appender-ref ref="file_async"/>-->
-<!--    </root>-->
-    <root level="ERROR">
-        <appender-ref ref="StdoutAppender"/>
-        <appender-ref ref="file_async"/>
-    </root>
-</configuration>