change - 时间段趋势变化告警逻辑实现

breach-zhy
wenjy 5 months ago
parent 2c5f6886f9
commit 3040987fec

@ -484,8 +484,15 @@ public class HwMonitorPlatformController extends BaseController {
* */ * */
@PostMapping("/selectDeviceByName") @PostMapping("/selectDeviceByName")
public AjaxResult selectDeviceByName(@RequestBody Map map){ public AjaxResult selectDeviceByName(@RequestBody Map map){
List<HwDevice> deviceList = hwDeviceService.selectMonitorUnitAndDeviceByName(map);
return success(deviceList); try {
List<HwDevice> deviceList = hwDeviceService.selectMonitorUnitAndDeviceByName(map);
return success(deviceList);
}catch (Exception ex){
return error(String.format("获取设备信息异常:%e",ex.getMessage()));
}
} }

@ -27,10 +27,12 @@ import com.ruoyi.dataprocess.service.IDataProcessService;
import com.ruoyi.tdengine.api.RemoteTdEngineService; import com.ruoyi.tdengine.api.RemoteTdEngineService;
import com.ruoyi.tdengine.api.domain.TdField; import com.ruoyi.tdengine.api.domain.TdField;
import com.ruoyi.tdengine.api.domain.TdHistorySelectDto; import com.ruoyi.tdengine.api.domain.TdHistorySelectDto;
import com.ruoyi.tdengine.api.domain.TdReturnDataVo;
import com.ruoyi.tdengine.api.domain.TdTableVo; import com.ruoyi.tdengine.api.domain.TdTableVo;
import com.sun.org.apache.xpath.internal.operations.Bool; import com.sun.org.apache.xpath.internal.operations.Bool;
import darabonba.core.client.ClientOverrideConfiguration; import darabonba.core.client.ClientOverrideConfiguration;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -44,13 +46,11 @@ import javax.script.ScriptException;
import java.io.IOException; import java.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
/** /**
* @Description: * @Description:
@ -220,7 +220,7 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
final R<?> insertResult = this.remoteTdEngineService.insertTable(tdTableVo , SecurityConstants.INNER); final R<?> insertResult = this.remoteTdEngineService.insertTable(tdTableVo , SecurityConstants.INNER);
if (insertResult.getCode() == ResultEnums.SUCCESS.getCode()) { if (insertResult.getCode() == ResultEnums.SUCCESS.getCode()) {
logger.info("Insert data result: {}", insertResult.getMsg()); logger.info("Insert data result: {}", insertResult.getCode());
} else { } else {
logger.error("Insert data Exception: {},data:{}", insertResult.getMsg(), jsonData); logger.error("Insert data Exception: {},data:{}", insertResult.getMsg(), jsonData);
} }
@ -242,6 +242,7 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
return paramArr.size(); return paramArr.size();
} }
private static String getImageFileName(String imagePath, String imageDomain, String imagePrefix, String valueStr, Long deviceId, String extension) { private static String getImageFileName(String imagePath, String imageDomain, String imagePrefix, String valueStr, Long deviceId, String extension) {
try { try {
String imageFileName = ImageUtils.convertBase64ToImage(imagePath, String imageFileName = ImageUtils.convertBase64ToImage(imagePath,
@ -363,87 +364,147 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
*/ */
private void checkAlarm(Long deviceId, List<TdField> alarmFields, private void checkAlarm(Long deviceId, List<TdField> alarmFields,
Long tenantId, Long sceneId, Long monitorUnitId, String topic, String subDeviceCode) { Long tenantId, Long sceneId, Long monitorUnitId, String topic, String subDeviceCode) {
HwAlarmRule queryAlarmRule = new HwAlarmRule();
queryAlarmRule.setRuleDeviceId(deviceId);
queryAlarmRule.setRuleType(HwDictConstants.ALARM_RULE_RULE_TYPE_DEVICE);
queryAlarmRule.setAlarmRuleStatus(HwDictConstants.ALARM_RULE_STATUS_ENABLE);
List<HwAlarmRule> alarmRules = hwAlarmRuleMapper.selectHwAlarmRulesWithLink(queryAlarmRule);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
if (alarmRules != null) {
Date currentDate = new Date();
for (HwAlarmRule alarmRule : alarmRules) {
String triggerExpression = alarmRule.getTriggerExpression()
.replaceAll("and", "&&")
.replaceAll("or", "||");
AtomicBoolean isAlarmed = new AtomicBoolean(false);
List<HwAlarmDetail> alarmDetails = new ArrayList<HwAlarmDetail>();
for (TdField alarmField : alarmFields) {
String fieldName = alarmField.getFieldName();
Object filedValue = alarmField.getFieldValue();
if (triggerExpression.contains("{" + fieldName + "}")) {
isAlarmed.set(true);
triggerExpression = triggerExpression.replaceAll("\\{" + fieldName + "\\}", String.valueOf(filedValue));
HwAlarmDetail alarmDetail = new HwAlarmDetail();
alarmDetail.setDeviceId(deviceId);
alarmDetail.setFunctionIdentifier(fieldName);
alarmDetail.setFunctionValue(String.valueOf(filedValue));
alarmDetail.setMonitorTime(currentDate);
alarmDetails.add(alarmDetail);
}
}
if (isAlarmed.get() && !triggerExpression.contains("{") try {
&& RegexUtils.findSymbolInText(triggerExpression).size() > 0 HwAlarmRule queryAlarmRule = new HwAlarmRule();
&& RegexUtils.findNumberInText(triggerExpression).size() > 0) { queryAlarmRule.setRuleDeviceId(deviceId);
queryAlarmRule.setRuleType(HwDictConstants.ALARM_RULE_RULE_TYPE_DEVICE);
queryAlarmRule.setAlarmRuleStatus(HwDictConstants.ALARM_RULE_STATUS_ENABLE);
List<HwAlarmRule> alarmRules = hwAlarmRuleMapper.selectHwAlarmRulesWithLink(queryAlarmRule);
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
if (alarmRules != null) {
Date currentDate = new Date();
for (HwAlarmRule alarmRule : alarmRules) {
String triggerExpression = alarmRule.getTriggerExpression()
.replaceAll("and", "&&")
.replaceAll("or", "||");
AtomicBoolean isAlarmed = new AtomicBoolean(false);
List<HwAlarmDetail> alarmDetails = new ArrayList<HwAlarmDetail>();
for (TdField alarmField : alarmFields) {
String fieldName = alarmField.getFieldName();
Object filedValue = alarmField.getFieldValue();
if (triggerExpression.contains("{" + fieldName + "}")) {
isAlarmed.set(true);
Boolean triggerExpressionBool = null; /**
try { * Add By WenJY 2024-07-03 14:13:21
triggerExpressionBool = (Boolean) engine.eval(triggerExpression); */
} catch (ScriptException e) { if(alarmRule.getTriggerTimeFrame() != null && alarmRule.getTriggerTimeFrame() > 0){
throw new RuntimeException(e); double difValue = FilterDeviceValue(deviceId, fieldName, alarmRule.getTriggerTimeFrame());
} if(difValue > 0){
if (triggerExpressionBool) { filedValue = difValue;
HwAlarmInfo alarmInfo = new HwAlarmInfo(); }
alarmInfo.setAlarmInfoType(HwDictConstants.ALARM_INFO_TYPE_DEVICE);
alarmInfo.setAlarmReleatedId(alarmRule.getAlarmRuleId());
alarmInfo.setDeviceId(deviceId);
alarmInfo.setMonitorUnitId(monitorUnitId);
alarmInfo.setTenantId(tenantId);
alarmInfo.setSceneId(sceneId);
alarmInfo.setAlarmLevelId(alarmRule.getAlarmLevelId());
alarmInfo.setAlarmTypeId(alarmRule.getAlarmTypeId());
alarmInfo.setHwAlarmDetailList(alarmDetails);
alarmInfo.setHandleStatus(HwDictConstants.ALARM_HANDLE_STATUS_NO);
alarmInfo.setCreateTime(currentDate);
alarmInfo.setAlarmTime(currentDate);
hwAlarmInfoMapper.insertHwAlarmInfo(alarmInfo);
this.insertHwAlarmDetail(alarmInfo);
this.handleAlarmLink(alarmRule, topic, subDeviceCode);
try {
HwDevice hwDevice = hwDeviceMapper.GetDeviceById(deviceId);
if(hwDevice != null){
AlarmMsgTemplateParam alarmMsgTemplateParam = new AlarmMsgTemplateParam();
alarmMsgTemplateParam.setWarning(alarmRule.getAlarmRuleName());
alarmMsgTemplateParam.setParentname(hwDevice.getMonitorUnitName());
alarmMsgTemplateParam.setSensorID(deviceId.toString());
SendAlarmInfoToSms(alarmRule.getPhoneNumbers(),alarmMsgTemplateParam);
} }
} catch (ExecutionException | InterruptedException e) { /** End **/
throw new RuntimeException(e.getMessage());
triggerExpression = triggerExpression.replaceAll("\\{" + fieldName + "\\}", String.valueOf(filedValue));
HwAlarmDetail alarmDetail = new HwAlarmDetail();
alarmDetail.setDeviceId(deviceId);
alarmDetail.setFunctionIdentifier(fieldName);
alarmDetail.setFunctionValue(String.valueOf(filedValue));
alarmDetail.setMonitorTime(currentDate);
alarmDetails.add(alarmDetail);
} }
}
break; if (isAlarmed.get() && !triggerExpression.contains("{")
&& RegexUtils.findSymbolInText(triggerExpression).size() > 0
&& RegexUtils.findNumberInText(triggerExpression).size() > 0) {
Boolean triggerExpressionBool = (Boolean) engine.eval(triggerExpression);
if (triggerExpressionBool) {
HwAlarmInfo alarmInfo = new HwAlarmInfo();
alarmInfo.setAlarmInfoType(HwDictConstants.ALARM_INFO_TYPE_DEVICE);
alarmInfo.setAlarmReleatedId(alarmRule.getAlarmRuleId());
alarmInfo.setDeviceId(deviceId);
alarmInfo.setMonitorUnitId(monitorUnitId);
alarmInfo.setTenantId(tenantId);
alarmInfo.setSceneId(sceneId);
alarmInfo.setAlarmLevelId(alarmRule.getAlarmLevelId());
alarmInfo.setAlarmTypeId(alarmRule.getAlarmTypeId());
alarmInfo.setHwAlarmDetailList(alarmDetails);
alarmInfo.setHandleStatus(HwDictConstants.ALARM_HANDLE_STATUS_NO);
alarmInfo.setCreateTime(currentDate);
alarmInfo.setAlarmTime(currentDate);
hwAlarmInfoMapper.insertHwAlarmInfo(alarmInfo);
this.insertHwAlarmDetail(alarmInfo);
this.handleAlarmLink(alarmRule, topic, subDeviceCode);
/**
* Add By WenJY
*/
if(StringUtils.isNotEmpty(alarmRule.getPhoneNumbers())){
SendAlarmInfoBySms(deviceId,alarmRule);
}else {
logger.warn("设备:{};报警信息发送失败,联系方式为空",deviceId);
}
break;
}
} }
} }
} }
}catch (Exception e){
logger.error("设备:{};报警逻辑处理异常:{}",deviceId,e.getMessage());
} }
} }
/**
* 0
* @param deviceId
* @param fieldName
* @param triggerTimeFrame
* @return
*/
private double FilterDeviceValue(Long deviceId,String fieldName,long triggerTimeFrame){
double differenceValue = 0.00;
String databaseName = TdEngineConstants.getDatabaseName();
String tableName = TdEngineConstants.DEFAULT_TABLE_NAME_PREFIX + deviceId;
long currentTimeMillis = System.currentTimeMillis();
long fiveMinutesInMillis = triggerTimeFrame * 60 * 1000;
long beforeTimeMillis = currentTimeMillis - fiveMinutesInMillis;
TdHistorySelectDto tdHistorySelectDto = new TdHistorySelectDto();
tdHistorySelectDto.setDatabaseName(databaseName);
tdHistorySelectDto.setTableName(tableName);
tdHistorySelectDto.setStartTime(beforeTimeMillis);
tdHistorySelectDto.setEndTime(currentTimeMillis);
tdHistorySelectDto.setFirstFieldName("ts");
R<?> result = this.remoteTdEngineService.getHistoryData(tdHistorySelectDto , SecurityConstants.INNER);
if (result.getCode() == ResultEnums.SUCCESS.getCode()) {
logger.info("Get history data result: {}", result.getCode());
TdReturnDataVo data = (TdReturnDataVo) result.getData();
List<Map<String, Object>> dataList = data.getDataList();
List<Double> value = dataList.stream().map(map -> (Double)map.get("value1")).distinct().filter(x -> x > 0).collect(Collectors.toList());
System.out.println(triggerTimeFrame +"分钟内数据:"+JSONArray.toJSON(value) );
OptionalDouble maxOptional = value.stream().mapToDouble(Double::doubleValue).max();
OptionalDouble minOptional = value.stream().mapToDouble(Double::doubleValue).min();
if (maxOptional.isPresent() && minOptional.isPresent()) {
double maxValue = maxOptional.getAsDouble();
double minValue = minOptional.getAsDouble();
differenceValue = maxValue - minValue;
System.out.println("Difference between max and min values: " + differenceValue);
} else {
System.out.println("No values found to calculate difference.");
}
} else {
logger.error("Get history data Exception: {}", result.getMsg());
}
return differenceValue;
}
/** /**
* *
* *
@ -516,6 +577,26 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
} }
} }
/**
*
* @param deviceId
* @param alarmRule
*/
private void SendAlarmInfoBySms(Long deviceId,HwAlarmRule alarmRule){
try {
HwDevice hwDevice = hwDeviceMapper.GetDeviceById(deviceId);
if(hwDevice != null){
AlarmMsgTemplateParam alarmMsgTemplateParam = new AlarmMsgTemplateParam();
alarmMsgTemplateParam.setWarning(alarmRule.getAlarmRuleName());
alarmMsgTemplateParam.setParentname(hwDevice.getMonitorUnitName());
alarmMsgTemplateParam.setSensorID(deviceId.toString());
AliSmsHandle(alarmRule.getPhoneNumbers(),alarmMsgTemplateParam);
}
} catch (ExecutionException | InterruptedException e) {
throw new InvalidOperationException(String.format("报警信息发送异常:%e",e.getMessage()));
}
}
/** /**
* *
* @param phoneNumbers * @param phoneNumbers
@ -523,7 +604,7 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
* @throws ExecutionException * @throws ExecutionException
* @throws InterruptedException * @throws InterruptedException
*/ */
private void SendAlarmInfoToSms(String phoneNumbers,AlarmMsgTemplateParam alarmMsgTemplateParam ) throws ExecutionException, InterruptedException { private void AliSmsHandle(String phoneNumbers,AlarmMsgTemplateParam alarmMsgTemplateParam ) throws ExecutionException, InterruptedException {
StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder() StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
.accessKeyId(AccessKeyId) .accessKeyId(AccessKeyId)
.accessKeySecret(AccessKeySecret) .accessKeySecret(AccessKeySecret)
@ -546,7 +627,7 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
.templateCode("SMS_468740027") .templateCode("SMS_468740027")
.templateParam(jsonString) .templateParam(jsonString)
.build(); .build();
logger.info("向:{};发送报警信息:{}",phoneNumbers,jsonString);
CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest); CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
SendSmsResponse resp = response.get(); SendSmsResponse resp = response.get();

@ -32,6 +32,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="alarmTypeName" column="alarm_type_name" /> <result property="alarmTypeName" column="alarm_type_name" />
<result property="alarmLevelName" column="alarm_level_name" /> <result property="alarmLevelName" column="alarm_level_name" />
<result property="ruleDeviceName" column="device_name" /> <result property="ruleDeviceName" column="device_name" />
<result property="triggerTimeFrame" column="trigger_time_frame" />
<result property="phoneNumbers" column="phone_numbers" />
</resultMap> </resultMap>
<resultMap id="HwAlarmRuleHwAlarmRuleLinkResult" type="HwAlarmRule" extends="HwAlarmRuleResult"> <resultMap id="HwAlarmRuleHwAlarmRuleLinkResult" type="HwAlarmRule" extends="HwAlarmRuleResult">
@ -51,13 +53,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</resultMap> </resultMap>
<sql id="selectHwAlarmRuleVo"> <sql id="selectHwAlarmRuleVo">
select alarm_rule_id, alarm_rule_name, tenant_id, scene_id, language_code, alarm_level_id, alarm_type_id, rule_type, rule_device_id, rule_function_total, trigger_expression, link_flag, alarm_rule_status, alarm_push_flag, alarm_push_content, alarm_recover_content, remark, create_by, create_time, update_by, update_time, alarm_rule_field from hw_alarm_rule select alarm_rule_id, alarm_rule_name, tenant_id, scene_id, language_code, alarm_level_id, alarm_type_id, rule_type, rule_device_id, rule_function_total, trigger_expression, link_flag, alarm_rule_status, alarm_push_flag, alarm_push_content, alarm_recover_content, remark, create_by, create_time, update_by, update_time, alarm_rule_field,trigger_time_frame,phone_numbers from hw_alarm_rule
</sql> </sql>
<select id="selectHwAlarmRulesWithLink" parameterType="HwAlarmRule" resultMap="HwAlarmRuleHwAlarmRuleLinkResult"> <select id="selectHwAlarmRulesWithLink" parameterType="HwAlarmRule" resultMap="HwAlarmRuleHwAlarmRuleLinkResult">
select a.alarm_rule_id, a.alarm_rule_name, a.tenant_id, a.scene_id, a.language_code, a.alarm_level_id, a.alarm_type_id, a.rule_type, a.rule_device_id, a.rule_function_total, a.trigger_expression, a.link_flag, a.alarm_rule_status, a.alarm_push_flag, a.alarm_push_content, a.alarm_recover_content, a.remark, a.create_by, a.create_time, a.update_by, a.update_time, a.alarm_rule_field, select a.alarm_rule_id, a.alarm_rule_name, a.tenant_id, a.scene_id, a.language_code, a.alarm_level_id, a.alarm_type_id, a.rule_type, a.rule_device_id, a.rule_function_total, a.trigger_expression, a.link_flag, a.alarm_rule_status, a.alarm_push_flag, a.alarm_push_content, a.alarm_recover_content, a.remark, a.create_by, a.create_time, a.update_by, a.update_time, a.alarm_rule_field,
b.rule_link_id as sub_rule_link_id, b.alarm_rule_id as sub_alarm_rule_id, b.link_type as sub_link_type, b.link_device_id as sub_link_device_id, b.link_device_function_id as sub_link_device_function_id, b.link_device_function_identifier as sub_link_device_function_identifier, b.link_device_function_data as sub_link_device_function_data b.rule_link_id as sub_rule_link_id, b.alarm_rule_id as sub_alarm_rule_id, b.link_type as sub_link_type, b.link_device_id as sub_link_device_id, b.link_device_function_id as sub_link_device_function_id, b.link_device_function_identifier as sub_link_device_function_identifier, b.link_device_function_data as sub_link_device_function_data,a.trigger_time_frame,a.phone_numbers
from hw_alarm_rule a from hw_alarm_rule a
left join hw_alarm_rule_link b on b.alarm_rule_id = a.alarm_rule_id and b.alarm_rule_type=1 left join hw_alarm_rule_link b on b.alarm_rule_id = a.alarm_rule_id and b.alarm_rule_type=1
<where> <where>

Loading…
Cancel
Save