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

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

@ -484,8 +484,15 @@ public class HwMonitorPlatformController extends BaseController {
* */
@PostMapping("/selectDeviceByName")
public AjaxResult selectDeviceByName(@RequestBody Map map){
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.domain.TdField;
import com.ruoyi.tdengine.api.domain.TdHistorySelectDto;
import com.ruoyi.tdengine.api.domain.TdReturnDataVo;
import com.ruoyi.tdengine.api.domain.TdTableVo;
import com.sun.org.apache.xpath.internal.operations.Bool;
import darabonba.core.client.ClientOverrideConfiguration;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -44,13 +46,11 @@ import javax.script.ScriptException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
/**
* @Description:
@ -220,7 +220,7 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
final R<?> insertResult = this.remoteTdEngineService.insertTable(tdTableVo , SecurityConstants.INNER);
if (insertResult.getCode() == ResultEnums.SUCCESS.getCode()) {
logger.info("Insert data result: {}", insertResult.getMsg());
logger.info("Insert data result: {}", insertResult.getCode());
} else {
logger.error("Insert data Exception: {},data:{}", insertResult.getMsg(), jsonData);
}
@ -242,6 +242,7 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
return paramArr.size();
}
private static String getImageFileName(String imagePath, String imageDomain, String imagePrefix, String valueStr, Long deviceId, String extension) {
try {
String imageFileName = ImageUtils.convertBase64ToImage(imagePath,
@ -363,6 +364,8 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
*/
private void checkAlarm(Long deviceId, List<TdField> alarmFields,
Long tenantId, Long sceneId, Long monitorUnitId, String topic, String subDeviceCode) {
try {
HwAlarmRule queryAlarmRule = new HwAlarmRule();
queryAlarmRule.setRuleDeviceId(deviceId);
queryAlarmRule.setRuleType(HwDictConstants.ALARM_RULE_RULE_TYPE_DEVICE);
@ -386,6 +389,18 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
Object filedValue = alarmField.getFieldValue();
if (triggerExpression.contains("{" + fieldName + "}")) {
isAlarmed.set(true);
/**
* Add By WenJY 2024-07-03 14:13:21
*/
if(alarmRule.getTriggerTimeFrame() != null && alarmRule.getTriggerTimeFrame() > 0){
double difValue = FilterDeviceValue(deviceId, fieldName, alarmRule.getTriggerTimeFrame());
if(difValue > 0){
filedValue = difValue;
}
}
/** End **/
triggerExpression = triggerExpression.replaceAll("\\{" + fieldName + "\\}", String.valueOf(filedValue));
HwAlarmDetail alarmDetail = new HwAlarmDetail();
alarmDetail.setDeviceId(deviceId);
@ -393,6 +408,7 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
alarmDetail.setFunctionValue(String.valueOf(filedValue));
alarmDetail.setMonitorTime(currentDate);
alarmDetails.add(alarmDetail);
}
}
@ -400,12 +416,7 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
&& RegexUtils.findSymbolInText(triggerExpression).size() > 0
&& RegexUtils.findNumberInText(triggerExpression).size() > 0) {
Boolean triggerExpressionBool = null;
try {
triggerExpressionBool = (Boolean) engine.eval(triggerExpression);
} catch (ScriptException e) {
throw new RuntimeException(e);
}
Boolean triggerExpressionBool = (Boolean) engine.eval(triggerExpression);
if (triggerExpressionBool) {
HwAlarmInfo alarmInfo = new HwAlarmInfo();
alarmInfo.setAlarmInfoType(HwDictConstants.ALARM_INFO_TYPE_DEVICE);
@ -423,25 +434,75 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
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) {
throw new RuntimeException(e.getMessage());
/**
* 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
@ -523,7 +604,7 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
* @throws ExecutionException
* @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()
.accessKeyId(AccessKeyId)
.accessKeySecret(AccessKeySecret)
@ -546,7 +627,7 @@ public class DataProcessServiceImpl extends CommanHandleService implements IData
.templateCode("SMS_468740027")
.templateParam(jsonString)
.build();
logger.info("向:{};发送报警信息:{}",phoneNumbers,jsonString);
CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
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="alarmLevelName" column="alarm_level_name" />
<result property="ruleDeviceName" column="device_name" />
<result property="triggerTimeFrame" column="trigger_time_frame" />
<result property="phoneNumbers" column="phone_numbers" />
</resultMap>
<resultMap id="HwAlarmRuleHwAlarmRuleLinkResult" type="HwAlarmRule" extends="HwAlarmRuleResult">
@ -51,13 +53,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</resultMap>
<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>
<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,
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
left join hw_alarm_rule_link b on b.alarm_rule_id = a.alarm_rule_id and b.alarm_rule_type=1
<where>

Loading…
Cancel
Save