合并暂降模块代码

This commit is contained in:
2022-07-14 09:43:29 +08:00
parent 014c766806
commit 638f5b8f93
56 changed files with 3133 additions and 86 deletions

View File

@@ -0,0 +1,31 @@
package com.njcn.event.service;
import com.njcn.device.pojo.param.DeviceInfoParam;
import com.njcn.event.pojo.vo.AreaAnalysisVO;
import com.njcn.event.pojo.vo.VoltageToleranceCurveVO;
/**
* pqs-event
*
* @author cdf
* @date 2022/6/24
*/
public interface AreaAnalysisService {
/**
* 区域暂降原因,类型
*
* @author cdf
* @date 2022/6/24
*/
AreaAnalysisVO getEventReason(DeviceInfoParam.BusinessParam deviceInfoParam);
/**
* 获取电压容忍度曲线兼容性统计
*
* @param deviceInfoParam 查询参数
* @return 电压容忍度曲线兼容性统计
*/
VoltageToleranceCurveVO getVoltageToleranceCurve(DeviceInfoParam.BusinessParam deviceInfoParam);
}

View File

@@ -0,0 +1,39 @@
package com.njcn.event.service;
import com.njcn.device.pojo.param.DeviceInfoParam;
import com.njcn.device.pojo.vo.TerminalBaseVO;
import com.njcn.event.pojo.po.EventDetail;
import com.njcn.event.pojo.vo.AreaSubLineVO;
import java.util.List;
/**
* pqs-event
*
* @author cdf
* @date 2022/6/29
*/
public interface AreaInfoService {
/**
* 获取区域监测点地理信息
* @author cdf
* @date 2022/6/29
*/
List<AreaSubLineVO> getAreaLineInfo(DeviceInfoParam.BusinessParam deviceInfoParam);
/**
* 获取区域监测点地理信息
* @author cdf
* @date 2022/6/29
*/
List<TerminalBaseVO> getAreaOffDev(DeviceInfoParam.BusinessParam deviceInfoParam);
/**
* 获取区域监测点地理信息
* @author cdf
* @date 2022/6/29
*/
List<EventDetail> getNoDealEvents(DeviceInfoParam.BusinessParam deviceInfoParam);
}

View File

@@ -2,9 +2,9 @@ package com.njcn.event.service;
import com.njcn.device.pojo.param.DeviceInfoParam;
import com.njcn.event.pojo.vo.AreaLineVO;
import com.njcn.event.pojo.vo.EventHeatMapVO;
import com.njcn.event.pojo.vo.EventSeverityVO;
import com.njcn.event.pojo.vo.*;
import java.util.List;
/**
* 区域暂降监测点统计
@@ -33,4 +33,13 @@ public interface AreaLineService {
* @return 结果
*/
EventSeverityVO getEventSeverity (DeviceInfoParam.BusinessParam deviceInfoParam);
/**
* 获取终端运行统计
*
* @param deviceInfoParam 参数
* @return 结果
*/
TerminalRunningStatisticsVO getTerminalRunningStatistics(DeviceInfoParam.BusinessParam deviceInfoParam);
}

View File

@@ -0,0 +1,24 @@
package com.njcn.event.service;
import com.njcn.device.pojo.param.DeviceInfoParam;
import com.njcn.event.pojo.vo.AreaStatisticalVO;
/**
* 区域统计
*
* @author : zhaojun
* @version : 1.0.0
* @date : 2022年06月24日 11:02
*/
public interface AreaStatisticalService {
/**
* 获取暂降区域 电压等级 月份统计
*
* @param deviceInfoParam 查询参数
* @return 暂降统计信息
*/
AreaStatisticalVO getAreaCalculation(DeviceInfoParam.BusinessParam deviceInfoParam);
}

View File

@@ -0,0 +1,21 @@
package com.njcn.event.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.event.pojo.param.EventBaseParam;
import com.njcn.event.pojo.po.EventDetail;
/**
* pqs-event
* 暂降 监测点
* @author cdf
* @date 2022/6/23
*/
public interface EventAnalysisService {
/**
* 获取暂降事件分析
* @author cdf
* @date 2022/6/23
*/
Page<EventDetail> getEventAnalyse(EventBaseParam eventBaseParam);
}

View File

@@ -0,0 +1,147 @@
package com.njcn.event.service.Impl;
import cn.hutool.core.collection.CollUtil;
import com.njcn.device.api.GeneralDeviceInfoClient;
import com.njcn.device.api.LineFeignClient;
import com.njcn.device.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pojo.param.DeviceInfoParam;
import com.njcn.device.pojo.vo.AreaLineInfoVO;
import com.njcn.event.influxdb.PqsEventDetailQuery;
import com.njcn.event.pojo.po.EventDetail;
import com.njcn.event.pojo.vo.AreaAnalysisVO;
import com.njcn.event.pojo.vo.VoltageToleranceCurveVO;
import com.njcn.event.pojo.vo.VoltageToleranceCurveVO.VoltageToleranceCurveDataList;
import com.njcn.event.service.AreaAnalysisService;
import com.njcn.system.api.DicDataFeignClient;
import com.njcn.system.enums.DicDataTypeEnum;
import com.njcn.system.pojo.po.DictData;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.njcn.event.influxdb.PqsEventDetailQuery.lineIdOr;
import static com.njcn.event.influxdb.PqsEventDetailQuery.timeAndType;
import static com.njcn.event.influxdb.QueryBuilder.*;
/**
* pqs-event
*
* @author cdf
* @date 2022/6/24
*/
@Service
@RequiredArgsConstructor
public class AreaAnalysisServiceImpl implements AreaAnalysisService {
private final GeneralDeviceInfoClient generalDeviceInfoClient;
private final DicDataFeignClient dicDataFeignClient;
private final LineFeignClient lineFeignClient;
private final PqsEventDetailQuery pqsEventDetailQuery;
@Override
public AreaAnalysisVO getEventReason(DeviceInfoParam.BusinessParam deviceInfoParam) {
AreaAnalysisVO areaAnalysisVO = new AreaAnalysisVO();
List<DictData> dicReasonList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_REASON.getName()).getData();
List<DictData> dicTypeList = dicDataFeignClient.getDicDataByTypeName(DicDataTypeEnum.EVENT_TYPE.getName()).getData();
// 获取指定部门下的监测点集合
List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceInfoClient.getPracticalAllDeviceInfo(deviceInfoParam).getData();
List<String> lineIds = getAllLineIdList(generalDeviceDTOList);
List<AreaAnalysisVO.Children> reasonList = assData(dicReasonList, lineIds, deviceInfoParam.getSearchBeginTime(), deviceInfoParam.getSearchEndTime(), "event_reason");
List<AreaAnalysisVO.Children> typeList = assData(dicTypeList, lineIds, deviceInfoParam.getSearchBeginTime(), deviceInfoParam.getSearchEndTime(), "event_type");
areaAnalysisVO.setReason(reasonList);
areaAnalysisVO.setType(typeList);
return areaAnalysisVO;
}
/**
* 获取电压容忍度曲线兼容性统计
*
* @param deviceInfoParam 查询参数
* @return 电压容忍度曲线兼容性统计
*/
@Override
public VoltageToleranceCurveVO getVoltageToleranceCurve(DeviceInfoParam.BusinessParam deviceInfoParam) {
// 获取指定部门下的监测点集合
List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceInfoClient.getPracticalAllDeviceInfo(deviceInfoParam).getData();
if (CollUtil.isEmpty(generalDeviceDTOList)) {
return VoltageToleranceCurveVO.empty();
}
List<String> lineIds = getAllLineIdList(generalDeviceDTOList);
if (CollUtil.isEmpty(lineIds)) {
return VoltageToleranceCurveVO.empty();
}
List<AreaLineInfoVO> getBaseLineAreaInfo = lineFeignClient.getBaseLineAreaInfo(lineIds).getData();
if (CollUtil.isEmpty(getBaseLineAreaInfo)) {
return VoltageToleranceCurveVO.empty();
}
Map<String, AreaLineInfoVO> areaLineInfoVOMap =
getBaseLineAreaInfo.parallelStream().collect(Collectors.toConcurrentMap(AreaLineInfoVO::getLineId,
Function.identity()));
List<EventDetail> eventDetailList = pqsEventDetailQuery.selectList(Arrays.asList("line_id", "persist_time", "event_value", "create_time"),
lineIdOr(lineIds), timeAnd(beginOfDay(deviceInfoParam.getSearchBeginTime()),
endOfDay(deviceInfoParam.getSearchEndTime())));
if (CollUtil.isEmpty(eventDetailList)) {
return VoltageToleranceCurveVO.empty();
}
List<VoltageToleranceCurveDataList> curveDataList = eventDetailList.parallelStream()
.map(dto -> {
AreaLineInfoVO info = areaLineInfoVOMap.get(dto.getLineId());
VoltageToleranceCurveDataList voltageToleranceCurve = new VoltageToleranceCurveDataList();
voltageToleranceCurve.setLineId(dto.getLineId());
voltageToleranceCurve.setPersistTime(dto.getPersistTime());
voltageToleranceCurve.setEventValue(dto.getEventValue());
voltageToleranceCurve.setTime(dto.getCreateTime());
voltageToleranceCurve.setGdName(info.getGdName());
voltageToleranceCurve.setSubName(info.getSubName());
return voltageToleranceCurve;
})
.sorted(VoltageToleranceCurveDataList.sortAscTime())
.collect(Collectors.toCollection(() -> Collections.synchronizedList(new ArrayList<>())));
return VoltageToleranceCurveVO.buildVO(eventDetailList.size(), curveDataList);
}
/**
* 获取全部的LineID
*
* @param generalDeviceDTOList Device
* @return lineIds
*/
private List<String> getAllLineIdList(List<GeneralDeviceDTO> generalDeviceDTOList) {
return generalDeviceDTOList.stream().flatMap(dto -> dto.getLineIndexes().stream()).collect(Collectors.toList());
}
private List<AreaAnalysisVO.Children> assData(List<DictData> dicList, List<String> lineIds, String startTime, String endTime, String type) {
List<AreaAnalysisVO.Children> reasonList = new ArrayList<>();
Integer allCount = 0;
for (DictData reason : dicList) {
// 暂降原因类型次数
Integer count = pqsEventDetailQuery.selectCount(Collections.singletonList(type),
lineIdOr(lineIds), timeAndType(beginOfDay(startTime),
endOfDay(endTime), type, reason.getId()));
AreaAnalysisVO.Children children = new AreaAnalysisVO.Children();
children.setName(reason.getName());
children.setValue(count);
allCount += count;
reasonList.add(children);
}
AreaAnalysisVO.Children allType = new AreaAnalysisVO.Children();
allType.setName("总计");
allType.setValue(allCount);
reasonList.add(allType);
return reasonList;
}
}

View File

@@ -0,0 +1,142 @@
package com.njcn.event.service.Impl;
import cn.hutool.core.collection.CollectionUtil;
import com.njcn.device.api.GeneralDeviceInfoClient;
import com.njcn.device.api.LineFeignClient;
import com.njcn.device.api.TerminalBaseClient;
import com.njcn.device.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pojo.param.DeviceInfoParam;
import com.njcn.device.pojo.po.Line;
import com.njcn.device.pojo.vo.AreaLineInfoVO;
import com.njcn.device.pojo.vo.TerminalBaseVO;
import com.njcn.event.pojo.constant.Param;
import com.njcn.event.pojo.po.EventDetail;
import com.njcn.event.pojo.vo.AreaSubLineVO;
import com.njcn.event.service.AreaInfoService;
import com.njcn.event.utils.CommUtil;
import com.njcn.influxdb.param.InfluxDBPublicParam;
import com.njcn.influxdb.utils.InfluxDbUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* pqs-event
* 区域地理信息
*
* @author cdf
* @date 2022/6/29
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class AreaInfoServiceImpl implements AreaInfoService {
private final InfluxDbUtils influxDbUtils;
private final GeneralDeviceInfoClient generalDeviceInfoClient;
private final LineFeignClient lineFeignClient;
private final TerminalBaseClient terminalBaseClient;
@Override
public List<AreaSubLineVO> getAreaLineInfo(DeviceInfoParam.BusinessParam deviceInfoParam) {
List<AreaSubLineVO> resultVOList = new ArrayList<>();
List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceInfoClient.getPracticalAllDeviceInfo(deviceInfoParam).getData();
List<String> lineIds = generalDeviceDTOList.stream().flatMap(dto -> dto.getLineIndexes().stream()).collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(lineIds)) {
List<AreaLineInfoVO> resList = lineFeignClient.getBaseLineAreaInfo(lineIds).getData();
//查询监测点未处理暂态事件
StringBuilder lineIdsStr = CommUtil.assToInfluxParam(lineIds);
String stringResult = "SELECT count(eventass_index) FROM " + Param.EVENT_DETAIL + Param.WHERE + "time >= '" + deviceInfoParam.getSearchBeginTime() + InfluxDBPublicParam.START_TIME + "' and " + "time <= '" + deviceInfoParam.getSearchEndTime() + InfluxDBPublicParam.END_TIME + "' and " + lineIdsStr + " and eventass_index = '' group by line_id" + InfluxDBPublicParam.TIME_ZONE;
// 结果集
QueryResult result = influxDbUtils.query(stringResult);
if (!result.hasError()) {
List<QueryResult.Series> list = result.getResults().get(0).getSeries();
for (AreaLineInfoVO areaLineInfoVO : resList) {
boolean flag = false;
for (QueryResult.Series tem : list) {
String lineId = tem.getTags().get("line_id");
if (areaLineInfoVO.getLineId().equals(lineId)) {
areaLineInfoVO.setNoDealCount(Double.valueOf(tem.getValues().get(0).get(1).toString()).intValue());
flag = true;
break;
}
}
if (!flag) {
areaLineInfoVO.setNoDealCount(0);
}
}
}
//组装成变电站
if (CollectionUtil.isNotEmpty(resList)) {
Map<String, List<AreaLineInfoVO>> map = resList.stream().collect(Collectors.groupingBy(AreaLineInfoVO::getSubId));
map.forEach((key, value) -> {
AreaSubLineVO areaSubLineVO = new AreaSubLineVO();
areaSubLineVO.setChildren(value);
areaSubLineVO.setSubId(key);
areaSubLineVO.setLat(value.get(0).getLat());
areaSubLineVO.setLng(value.get(0).getLng());
areaSubLineVO.setSubName(value.get(0).getSubName());
resultVOList.add(areaSubLineVO);
});
}
}
return resultVOList;
}
@Override
public List<TerminalBaseVO> getAreaOffDev(DeviceInfoParam.BusinessParam deviceInfoParam) {
List<TerminalBaseVO> res = new ArrayList<>();
List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceInfoClient.getPracticalAllDeviceInfo(deviceInfoParam).getData();
List<String> devIds = generalDeviceDTOList.stream().flatMap(dto -> dto.getDeviceIndexes().stream()).collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(devIds)) {
res = terminalBaseClient.getDeviceByIdOnOrOff(devIds).getData();
}
return res;
}
@Override
public List<EventDetail> getNoDealEvents(DeviceInfoParam.BusinessParam deviceInfoParam) {
List<EventDetail> resList = new ArrayList<>();
List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceInfoClient.getPracticalAllDeviceInfo(deviceInfoParam).getData();
List<String> lineIds = generalDeviceDTOList.stream().flatMap(dto -> dto.getLineIndexes().stream()).collect(Collectors.toList());
if (CollectionUtil.isNotEmpty(lineIds)) {
List<Line> lineList = lineFeignClient.getBaseLineList(lineIds).getData();
//查询监测点未处理暂态事件
StringBuilder lineIdsStr = CommUtil.assToInfluxParam(lineIds);
String stringResult = "SELECT * FROM " + Param.EVENT_DETAIL + Param.WHERE + "time >= '" + deviceInfoParam.getSearchBeginTime() + Param.BEGIN + "' and " + "time <= '" + deviceInfoParam.getSearchEndTime() + Param.END + "' and " + lineIdsStr + "and eventass_index = '' " + InfluxDBPublicParam.TIME_ZONE;
// 结果集
QueryResult result = influxDbUtils.query(stringResult);
// 结果集映射到对象中
InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
resList = influxDBResultMapper.toPOJO(result, EventDetail.class);
//对未处理暂降事件的监测点替换成中文名称
if (CollectionUtil.isNotEmpty(resList)) {
for (EventDetail eventDetail : resList) {
for (Line tem : lineList) {
if (eventDetail.getLineId().equals(tem.getId())) {
eventDetail.setLineId(tem.getName());
break;
}
}
}
}
}
return resList;
}
}

View File

@@ -1,6 +1,7 @@
package com.njcn.event.service.Impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.njcn.common.pojo.enums.common.ServerEnum;
import com.njcn.device.api.GeneralDeviceInfoClient;
@@ -9,17 +10,32 @@ import com.njcn.device.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pojo.param.DeviceInfoParam;
import com.njcn.device.pojo.vo.LineDetailVO;
import com.njcn.device.pojo.vo.LineDeviceStateVO;
import com.njcn.event.pojo.vo.*;
import com.njcn.device.pojo.vo.SubstationDetailVO;
import com.njcn.event.influxdb.PqsOnlinerateQuery;
import com.njcn.event.mapper.PqDeviceMapper;
import com.njcn.event.pojo.po.PqDevice;
import com.njcn.event.pojo.po.PqsOnlinerate;
import com.njcn.event.pojo.vo.*;
import com.njcn.event.pojo.vo.TerminalRunningStatisticsVO.TerminalRunningInfoVO;
import com.njcn.event.pojo.vo.TerminalRunningStatisticsVO.TerminalRunningVO;
import com.njcn.event.service.AreaLineService;
import com.njcn.influxdb.utils.InfluxDbUtils;
import com.njcn.system.pojo.enums.StatisticsEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.njcn.event.influxdb.PqsOnlinerateQuery.devIdOr;
import static com.njcn.event.influxdb.QueryBuilder.*;
/**
* @author denghuajun
@@ -30,36 +46,39 @@ import java.util.*;
@Service
@RequiredArgsConstructor
public class AreaLineServiceImpl implements AreaLineService {
private final GeneralDeviceInfoClient generalDeviceInfoClient;
private final LineFeignClient lineFeignClient;
private final InfluxDbUtils influxDbUtils;
private final PqsOnlinerateQuery pqsOnlinerateQuery;
private final PqDeviceMapper pqDeviceMapper;
@Override
public AreaLineVO getAreaLineVO(DeviceInfoParam deviceInfoParam) {
AreaLineVO areaLineVO = new AreaLineVO();
deviceInfoParam.setServerName(ServerEnum.EVENT.getName());
List<List<Object>> listObject = new ArrayList<>();
//获取暂降监测点
// 获取暂降监测点
List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceInfoClient.getPracticalAllDeviceInfo(deviceInfoParam).getData();
List<String> lineIndexs;
List<SubstationDetailVO> substationDetailVOList = new ArrayList<>();
//获取所有终端信息
// 获取所有终端信息
for (GeneralDeviceDTO generalDeviceDTO : generalDeviceDTOList) {
List<Object> objectList = new ArrayList<>();
List<String> subIndexs;
subIndexs = generalDeviceDTO.getSubIndexes();
lineIndexs = generalDeviceDTO.getLineIndexes();
//通讯正常个数
// 通讯正常个数
int stateZc = 0;
//通讯中断个数
// 通讯中断个数
int stateZd = 0;
//总次数
// 总次数
int tail = 0;
String color = "";
List<SubstationDetailVO> substationDetailVOS = new ArrayList<>();
if (subIndexs.size() > 0) {
@@ -69,7 +88,7 @@ public class AreaLineServiceImpl implements AreaLineService {
List<LineDeviceStateVO> list = new ArrayList<>();
list.addAll(lineList);
Iterator<LineDeviceStateVO> iterator = list.listIterator();
//获取监测点
// 获取监测点
while (iterator.hasNext()) {
LineDeviceStateVO line = iterator.next();
String[] ids = line.getPids().split(",");
@@ -78,16 +97,16 @@ public class AreaLineServiceImpl implements AreaLineService {
}
}
List<LineDeviceStateVO> lineDataVOList = list;
//通讯正常个数
// 通讯正常个数
int stateTrue;
stateTrue = 0;
//通讯中断个数
// 通讯中断个数
int stateFalse = 0;
//次数
// 次数
double r = 0.0035;
int j = 0;
//总的监测点个数
// 总的监测点个数
int lineTail = lineDataVOList.size();
for (LineDeviceStateVO lineDataVO : lineDataVOList) {
if (lineDataVO.getState() == 1) {
@@ -111,11 +130,11 @@ public class AreaLineServiceImpl implements AreaLineService {
tail += lineTail;
}
}
//获取变电站
// 获取变电站
substationDetailVOList.addAll(substationDetailVOS);
if (lineIndexs.size() > 0) {
areaLineVO.setSubstationDetailVOList(substationDetailVOList);
objectList.add(generalDeviceDTO.getName()+"\n("+tail+")");
objectList.add(generalDeviceDTO.getName() + "\n(" + tail + ")");
objectList.add(tail);
objectList.add(stateZc);
objectList.add(stateZd);
@@ -125,14 +144,14 @@ public class AreaLineServiceImpl implements AreaLineService {
areaLineVO.setAreaValue(listObject);
return areaLineVO;
}
@Override
public EventHeatMapVO getEventHeatMap(DeviceInfoParam.BusinessParam deviceInfoParam) {
EventHeatMapVO eventHeatMapVO = new EventHeatMapVO();
List<EventHeatMapDetailVO> eventHeatMapDetailList = new ArrayList<>();
deviceInfoParam.setServerName(ServerEnum.EVENT.getName());
List<List<Object>> listObject = new ArrayList<>();
//获取暂降监测点
// 获取暂降监测点
List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceInfoClient.getPracticalAllDeviceInfo(deviceInfoParam).getData();
List<String> lineIndexs;
int i = 0, generalDeviceListSize = generalDeviceDTOList.size();
@@ -140,7 +159,7 @@ public class AreaLineServiceImpl implements AreaLineService {
List<Object> objectList = new ArrayList<>();
GeneralDeviceDTO generalDeviceDTO = generalDeviceDTOList.get(i);
lineIndexs = generalDeviceDTO.getLineIndexes();
//获取暂降数据
// 获取暂降数据
if (lineIndexs.size() > 0) {
int tail = 0;
List<EventHeatDeatilVO> eventdetailList = getContion(deviceInfoParam, lineIndexs);
@@ -153,7 +172,7 @@ public class AreaLineServiceImpl implements AreaLineService {
tail += eventdetailList.get(eventNum).getCount();
eventHeatMapDetailList.add(eventHeatMapDetailVO);
}
objectList.add(generalDeviceDTO.getName()+"\n("+lineIndexs.size()+")");
objectList.add(generalDeviceDTO.getName() + "\n(" + lineIndexs.size() + ")");
objectList.add(tail);
listObject.add(objectList);
}
@@ -164,14 +183,14 @@ public class AreaLineServiceImpl implements AreaLineService {
eventHeatMapVO.setEventHeatMapValue(eventHeatMapDetailList);
return eventHeatMapVO;
}
@Override
public EventSeverityVO getEventSeverity(DeviceInfoParam.BusinessParam deviceInfoParam) {
EventSeverityVO eventSeverityVO = new EventSeverityVO();
List<EventSeverityValueVO> eventSeverityValueList = new ArrayList<>();
deviceInfoParam.setServerName(ServerEnum.EVENT.getName());
List<List<Object>> listObject = new ArrayList<>();
//获取暂降监测点
// 获取暂降监测点
List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceInfoClient.getPracticalAllDeviceInfo(deviceInfoParam).getData();
List<String> lineIndexs;
int i = 0, generalDeviceListSize = generalDeviceDTOList.size();
@@ -179,12 +198,12 @@ public class AreaLineServiceImpl implements AreaLineService {
List<Object> objectList = new ArrayList<>();
GeneralDeviceDTO generalDeviceDTO = generalDeviceDTOList.get(i);
lineIndexs = generalDeviceDTO.getLineIndexes();
//获取暂降数据
// 获取暂降数据
if (lineIndexs.size() > 0) {
int tail = 0;
EventSeverityValueVO eventSeverityValueVO = new EventSeverityValueVO();
List<EventHeatDeatilVO> eventdetailList = getContion(deviceInfoParam, lineIndexs);
if (eventdetailList.size()>0){
if (eventdetailList.size() > 0) {
for (int eventNum = 0; eventNum < eventdetailList.size(); eventNum++) {
tail += eventdetailList.get(eventNum).getCount();
}
@@ -192,7 +211,7 @@ public class AreaLineServiceImpl implements AreaLineService {
eventSeverityValueVO.setLineNum(lineIndexs.size());
eventSeverityValueVO.setEventNum(tail);
eventSeverityValueList.add(eventSeverityValueVO);
objectList.add(generalDeviceDTO.getName()+"\n("+lineIndexs.size()+")");
objectList.add(generalDeviceDTO.getName() + "\n(" + lineIndexs.size() + ")");
objectList.add(tail);
listObject.add(objectList);
}
@@ -203,14 +222,116 @@ public class AreaLineServiceImpl implements AreaLineService {
eventSeverityVO.setEventSeverityValue(eventSeverityValueList);
return eventSeverityVO;
}
/**
* 获取终端运行统计
*
* @param deviceInfoParam 参数
* @return 结果
*/
@Override
public TerminalRunningStatisticsVO getTerminalRunningStatistics(DeviceInfoParam.BusinessParam deviceInfoParam) {
// 区域计算
TerminalRunningVO area = analyzeTerminalRun(deviceInfoParam);
// 厂家计算
deviceInfoParam.getStatisticalType().setCode(StatisticsEnum.MANUFACTURER.getCode());
TerminalRunningVO factory = analyzeTerminalRun(deviceInfoParam);
return TerminalRunningStatisticsVO.buildVO(area, factory);
}
private TerminalRunningVO analyzeTerminalRun(DeviceInfoParam.BusinessParam deviceInfoParam) {
List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceInfoClient.getPracticalAllDeviceInfo(deviceInfoParam).getData();
if (CollUtil.isEmpty(generalDeviceDTOList)) {
return TerminalRunningVO.empty();
}
List<String> deviceIndexList =
generalDeviceDTOList.stream().flatMap(dto -> dto.getDeviceIndexes().stream()).collect(Collectors.toList());
if (CollUtil.isEmpty(deviceIndexList)) {
return TerminalRunningVO.empty();
}
List<PqsOnlinerate> pqsOnlinerateList =
pqsOnlinerateQuery.selectList(Arrays.asList("dev_id", "offlinemin", "onlinemin"),
devIdOr(deviceIndexList),
timeAnd(beginOfDay(deviceInfoParam.getSearchBeginTime()), endOfDay(deviceInfoParam.getSearchEndTime())));
List<PqDevice> pqDeviceList = pqDeviceMapper.queryRunFlagByDeviceIndexs(deviceIndexList);
List<TerminalRunningInfoVO> terminalRun = generalDeviceDTOList.parallelStream().map(dto -> {
List<String> deviceIndexes = dto.getDeviceIndexes();
TerminalRunningInfoVO terminalRunningInfoVO = new TerminalRunningInfoVO();
terminalRunningInfoVO.setAreaName(dto.getName());
terminalRunningInfoVO.setNumberOfTerminals(deviceIndexes.size());
terminalRunningInfoVO.setNormal(countDeviceRunStatus(pqDeviceList).apply(0, deviceIndexes));
terminalRunningInfoVO.setBreaks(countDeviceRunStatus(pqDeviceList).apply(1, deviceIndexes));
terminalRunningInfoVO.setShutdown(countDeviceRunStatus(pqDeviceList).apply(2, deviceIndexes));
terminalRunningInfoVO.setOnlineRate(computingDeviceOnlineRate(pqsOnlinerateList).apply(deviceIndexes));
return terminalRunningInfoVO;
}).sorted(TerminalRunningInfoVO.sortAscAreaName())
.collect(Collectors.toCollection(() -> Collections.synchronizedList(new ArrayList<>())));
Integer terminalSum = terminalRun.stream().mapToInt(TerminalRunningInfoVO::getNumberOfTerminals)
.sum();
Long normalSum = terminalRun.stream().mapToLong(TerminalRunningInfoVO::getNormal)
.sum();
Long breaksSum = terminalRun.stream().mapToLong(TerminalRunningInfoVO::getBreaks)
.sum();
Long shutdownSum = terminalRun.stream().mapToLong(TerminalRunningInfoVO::getShutdown)
.sum();
Double onlineRateAvg = computingDeviceOnlineRate(pqsOnlinerateList).apply(deviceIndexList);
return TerminalRunningVO.buildVO(terminalSum, normalSum, breaksSum, shutdownSum,
onlineRateAvg, terminalRun);
}
/**
* 计算装置在线率,在线率计算公式
* OnlineRate = OnLineMin/( OnLineMin+ OffLineMin) * 100%
*
* @param pqsOnlinerateList 装置在线记录
* @return 在线率
*/
private Function<List<String>, Double> computingDeviceOnlineRate(List<PqsOnlinerate> pqsOnlinerateList) {
return deviceIndexes -> {
List<PqsOnlinerate> value = pqsOnlinerateList.stream()
.filter(t -> deviceIndexes.contains(t.getDevId()))
.collect(Collectors.toList());
int onlineSum = value.stream().mapToInt(PqsOnlinerate::getOnlinemin).sum();
int offlineSum = value.stream().mapToInt(PqsOnlinerate::getOfflinemin).sum();
BigDecimal b1 = new BigDecimal(onlineSum);
BigDecimal b2 = new BigDecimal(offlineSum);
BigDecimal c = new BigDecimal(100);
if (b1.compareTo(BigDecimal.ZERO) == 0) {
return 0.00D;
}
return b1.divide(b1.add(b2), 4, RoundingMode.HALF_UP).multiply(c).doubleValue();
};
}
/**
* 根据终端运行状态0投运1热备用2停运查询数据数量
*
* @param pqDeviceList 设备列表
* @return 数据数量
*/
private BiFunction<Integer, List<String>, Long> countDeviceRunStatus(List<PqDevice> pqDeviceList) {
return (runFlag, deviceIndexes) -> pqDeviceList.stream()
.filter(t -> Objects.equals(t.getRunFlag(), runFlag))
.filter(t -> deviceIndexes.contains(t.getId()))
.count();
}
public List<EventHeatDeatilVO> getContion(DeviceInfoParam.BusinessParam deviceInfoParam, List<String> lineIndexs) {
//组装sql语句
// 组装sql语句
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(deviceInfoParam.getSearchBeginTime()))).append("' and ").append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(deviceInfoParam.getSearchEndTime()))).append("' and ");
int j = 0;
//sql语句
// sql语句
for (String line : lineIndexs) {
if (j == 0) {
stringBuilder.append("line_id ='").append(line).append("'");
@@ -220,7 +341,7 @@ public class AreaLineServiceImpl implements AreaLineService {
j++;
}
stringBuilder.append(" group by line_id");
//获取暂降事件
// 获取暂降事件
String sql = "select count(file_flag) from pqs_eventdetail where " + stringBuilder.toString();
QueryResult result = influxDbUtils.query(sql);
InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();

View File

@@ -0,0 +1,198 @@
package com.njcn.event.service.Impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.njcn.device.api.GeneralDeviceInfoClient;
import com.njcn.device.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pojo.param.DeviceInfoParam;
import com.njcn.event.influxdb.PqsEventDetailQuery;
import com.njcn.event.pojo.po.EventDetail;
import com.njcn.event.pojo.vo.AreaCalculationVO;
import com.njcn.event.pojo.vo.AreaStatisticalVO;
import com.njcn.event.pojo.vo.AreaStatisticalVO.AreaStatisticsVO;
import com.njcn.event.pojo.vo.AreaStatisticalVO.MonthlyStatisticsVO;
import com.njcn.event.pojo.vo.AreaStatisticalVO.VoltageStatisticsVO;
import com.njcn.event.pojo.vo.MonthCalculationVO;
import com.njcn.event.pojo.vo.VoltageLevelCalculationVO;
import com.njcn.event.service.AreaStatisticalService;
import com.njcn.system.pojo.enums.StatisticsEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.njcn.event.influxdb.PqsEventDetailQuery.*;
/**
* 区域统计
*
* @author : zhaojun
* @version : 1.0.0
* @date : 2022年06月24日 11:02
*/
@Service
@RequiredArgsConstructor
public class AreaStatisticalServiceImpl implements AreaStatisticalService {
private final GeneralDeviceInfoClient generalDeviceInfoClient;
private final PqsEventDetailQuery pqsEventDetailQuery;
/**
* 获取暂降区域 电压等级 月份统计
*
* @param deviceInfoParam 查询参数
* @return 暂降统计信息
*/
@Override
public AreaStatisticalVO getAreaCalculation(DeviceInfoParam.BusinessParam deviceInfoParam) {
// 获取指定部门下的监测点集合
List<GeneralDeviceDTO> generalDeviceDTOList = generalDeviceInfoClient.getPracticalAllDeviceInfo(deviceInfoParam).getData();
if (CollUtil.isEmpty(generalDeviceDTOList)) {
return AreaStatisticalVO.empty();
}
List<String> lineIds = generalDeviceDTOList.stream().flatMap(dto -> dto.getLineIndexes().stream()).collect(Collectors.toList());
if (CollUtil.isEmpty(lineIds)) {
return AreaStatisticalVO.empty();
}
List<EventDetail> eventDetailList = pqsEventDetailQuery.selectList(Arrays.asList("line_id", "eventass_index"),
lineIdOr(lineIds),
timeAnd(beginOfDay(deviceInfoParam.getSearchBeginTime()), endOfDay(deviceInfoParam.getSearchEndTime())));
if (CollUtil.isEmpty(eventDetailList)) {
return AreaStatisticalVO.empty();
}
AreaStatisticsVO areaStatisticsVO = statisticsAreaInfo(generalDeviceDTOList, eventDetailList);
MonthlyStatisticsVO monthCalculationVOS = statisticsMonthInfo(deviceInfoParam, eventDetailList);
deviceInfoParam.getStatisticalType().setCode(StatisticsEnum.VOLTAGE_LEVEL.getCode());
List<GeneralDeviceDTO> voltageLevelList = generalDeviceInfoClient.getPracticalAllDeviceInfo(deviceInfoParam).getData();
VoltageStatisticsVO voltageStatisticsVO = statisticalVoltageLevelInfo(voltageLevelList, eventDetailList);
return AreaStatisticalVO.buildVO(areaStatisticsVO, voltageStatisticsVO, monthCalculationVOS);
}
/**
* 统计月份信息
*
* @param deviceInfoParam 参数
* @param eventDetailList influxdb数据
* @return 统计月份信息
*/
private MonthlyStatisticsVO statisticsMonthInfo(DeviceInfoParam.BusinessParam deviceInfoParam, List<EventDetail> eventDetailList) {
List<DateTime> timeLimit = calculateTheTimePeriodRange(deviceInfoParam);
List<DateTime> monthStartAndEnd = calculateMonthStartAndEnd(timeLimit);
List<MonthCalculationVO> monthCalculationVOList = new ArrayList<>(monthStartAndEnd.size());
MonthCalculationVO monthCalculationVO;
for (int i = 0; i < monthStartAndEnd.size(); i += 2) {
DateTime beginMon = monthStartAndEnd.get(i);
DateTime endMon = monthStartAndEnd.get(i + 1);
List<EventDetail> eventDetails = getBetweenTimeEventDetailList(eventDetailList).apply(beginMon, endMon);
// 时间段内总记录数
Long count = (long) eventDetails.size();
// 时间段内非空记录数,剔除等于空的
Long linkedCount = countEventassIndexIsNoEmpty().apply(eventDetails);
monthCalculationVO = new MonthCalculationVO();
monthCalculationVO.setMonth(beginMon.toDateStr().substring(0, 7));
monthCalculationVO.setNotAssociated(count - linkedCount);
monthCalculationVO.setLinked(linkedCount);
monthCalculationVOList.add(monthCalculationVO);
}
Long notAssociatedSum = monthCalculationVOList.stream().mapToLong(MonthCalculationVO::getNotAssociated).sum();
return MonthlyStatisticsVO.buildVO(notAssociatedSum, monthCalculationVOList);
}
/**
* 统计电压等级信息
*
* @param generalDeviceDTOList 监测点数据
* @param eventDetailList influxdb数据
* @return 统计电压等级信息
*/
private VoltageStatisticsVO statisticalVoltageLevelInfo(List<GeneralDeviceDTO> generalDeviceDTOList, List<EventDetail> eventDetailList) {
List<VoltageLevelCalculationVO> voltageLevelCalculation = generalDeviceDTOList.parallelStream().map(t -> {
VoltageLevelCalculationVO voltageLevelCalculationVO = new VoltageLevelCalculationVO();
voltageLevelCalculationVO.setVoltageLevel(t.getName());
voltageLevelCalculationVO.setMonitoringPoints(t.getLineIndexes().size());
voltageLevelCalculationVO.setFrequency(countLineIndexes(eventDetailList).apply(t.getLineIndexes()));
return voltageLevelCalculationVO;
}).collect(Collectors.toCollection(() -> Collections.synchronizedList(new ArrayList<>())));
// 求和暂降次数
Long frequencySum = voltageLevelCalculation.stream().mapToLong(VoltageLevelCalculationVO::getFrequency).sum();
// 求装置数量
Integer monitoringPointSum = voltageLevelCalculation.stream().mapToInt(VoltageLevelCalculationVO::getMonitoringPoints).sum();
return VoltageStatisticsVO.buildVO(frequencySum, monitoringPointSum, voltageLevelCalculation);
}
/**
* 统计区域信息
*
* @param generalDeviceDTOList 监测点数据
* @param eventDetailList influxdb数据
* @return 统计区域信息
*/
private AreaStatisticsVO statisticsAreaInfo(List<GeneralDeviceDTO> generalDeviceDTOList, List<EventDetail> eventDetailList) {
List<AreaCalculationVO> areaCalculation = generalDeviceDTOList.parallelStream().map(t -> {
AreaCalculationVO calculationVO = new AreaCalculationVO();
calculationVO.setAreaName(t.getName());
calculationVO.setMonitoringPoints(t.getLineIndexes().size());
calculationVO.setFrequency(countLineIndexes(eventDetailList).apply(t.getLineIndexes()));
calculationVO.computeSarfi90();
return calculationVO;
}).sorted(AreaCalculationVO.sortAscAreaName()).collect(Collectors.toCollection(() -> Collections.synchronizedList(new ArrayList<>())));
// 求和暂降次数
Long frequencySum = areaCalculation.stream().mapToLong(AreaCalculationVO::getFrequency).sum();
// 求装置数量
Integer monitoringPointSum = areaCalculation.stream().mapToInt(AreaCalculationVO::getMonitoringPoints).sum();
return AreaStatisticsVO.buildVO(frequencySum, monitoringPointSum, areaCalculation);
}
/**
* 计算出月的开始时间和结束时间
*
* @param timeLimit 查询参数
* @return 月的开始时间和结束时间
*/
private List<DateTime> calculateMonthStartAndEnd(List<DateTime> timeLimit) {
return timeLimit.stream().flatMap(dateTime -> {
DateTime dateTime1 = DateUtil.beginOfMonth(dateTime);
DateTime dateTime2 = DateUtil.endOfMonth(dateTime);
return Stream.of(dateTime1, dateTime2);
}).collect(Collectors.toList());
}
/**
* 根据开始时间结束时间, 获取时间年月范围
*
* @param deviceInfoParam 查询参数
* @return 获取时间年月范围
*/
private List<DateTime> calculateTheTimePeriodRange(DeviceInfoParam.BusinessParam deviceInfoParam) {
DateTime beginTime = DateUtil.parse(deviceInfoParam.getSearchBeginTime(), DatePattern.NORM_DATE_PATTERN);
DateTime endTime = DateUtil.parse(deviceInfoParam.getSearchEndTime(), DatePattern.NORM_DATE_PATTERN);
return DateUtil.rangeToList(beginTime, endTime, DateField.MONTH);
}
}

View File

@@ -0,0 +1,67 @@
package com.njcn.event.service.Impl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.utils.PubUtils;
import com.njcn.event.pojo.constant.Param;
import com.njcn.event.pojo.param.EventBaseParam;
import com.njcn.event.pojo.po.EventDetail;
import com.njcn.event.service.EventAnalysisService;
import com.njcn.influxdb.utils.InfluxDbUtils;
import lombok.RequiredArgsConstructor;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
/**
* pqs-event
*
* @author cdf
* @date 2022/6/23
*/
@Service
@RequiredArgsConstructor
public class EventAnalysisServiceImpl implements EventAnalysisService {
private final InfluxDbUtils influxDbUtils;
@Override
public Page<EventDetail> getEventAnalyse(EventBaseParam eventBaseParam) {
//查询sql语句
StringBuilder stringResult = new StringBuilder(Param.SELECT).append(Param.EVENT_DETAIL).append(Param.WHERE).
append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(eventBaseParam.getSearchBeginTime()))).append("' and ").append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(eventBaseParam.getSearchEndTime()))).append("' and ")
.append("line_id= '").append(eventBaseParam.getLineId()).append("'");
int i = (eventBaseParam.getPageNum() - 1)*eventBaseParam.getPageSize();
stringResult.append("LIMIT ").append(eventBaseParam.getPageSize()).append(" OFFSET ").append(i).append(" tz('Asia/Shanghai')");
//查询sql语句总条数
StringBuilder stringTotal = new StringBuilder("SELECT COUNT(num) as aa FROM ").append(Param.EVENT_DETAIL).append(" WHERE ") .append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(eventBaseParam.getSearchBeginTime()))).append("' and ")
.append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(eventBaseParam.getSearchEndTime()))).append("' and ");
stringTotal.append("line_id= '").append(eventBaseParam.getLineId()).append("' tz('Asia/Shanghai')");
//结果集
QueryResult result = influxDbUtils.query(stringResult.toString());
//总条数
QueryResult resultTotal = influxDbUtils.query(stringTotal.toString());
//结果集映射到对象中
InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
List<EventDetail> eventDetailList = influxDBResultMapper.toPOJO(result, EventDetail.class);
Page<EventDetail> page = new Page<>();
long total = new BigDecimal(resultTotal.getResults().get(0).getSeries().get(0).getValues().get(0).get(1).toString()).longValue();
page.setTotal(total);
page.setRecords(eventDetailList);
page.setCurrent(eventBaseParam.getPageNum());
page.setSize(eventBaseParam.getPageSize());
return page;
}
}

View File

@@ -1,8 +1,6 @@
package com.njcn.event.service.Impl;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.event.mapper.EventDetailMapper;
import com.njcn.event.pojo.po.EventDetail;
import com.njcn.event.service.EventDetailService;
import com.njcn.influxdb.utils.InfluxDbUtils;
@@ -14,6 +12,7 @@ import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Objects;
/**
* @author denghuajun
@@ -23,7 +22,7 @@ import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class EventDetailServiceImpl extends ServiceImpl<EventDetailMapper, EventDetail> implements EventDetailService {
public class EventDetailServiceImpl implements EventDetailService {
private final InfluxDbUtils influxDbUtils;
@@ -33,10 +32,9 @@ public class EventDetailServiceImpl extends ServiceImpl<EventDetailMapper, Event
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("time >= '").append(DateUtil.beginOfDay(DateUtil.parse(startTime))).append("' and ").append("time <= '").append(DateUtil.endOfDay(DateUtil.parse(endTime))).append("' and ");
//sql语句
stringBuilder.append("line_id ='").append(id).append("'");
stringBuilder.append("line_id ='").append(id).append("'").append(" tz('Asia/Shanghai')");
String sql = "select * from pqs_eventdetail where " + stringBuilder.toString();
System.out.println("sql>>>>>>>>>>>>>>>>>>>>>>>>"+sql);
String sql = "select * from pqs_eventdetail where " + stringBuilder;
//获取暂降事件
QueryResult result = influxDbUtils.query(sql);
InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
@@ -49,16 +47,17 @@ public class EventDetailServiceImpl extends ServiceImpl<EventDetailMapper, Event
EventDetail eventDetail = new EventDetail();
//组装sql语句
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("time >= '").append(time).append("' and ").append("line_id ='").append(id).append("' limit 1 tz('Asia/Shanghai')");
stringBuilder.append("time = '").append(time).append("' and ").append("line_id ='").append(id).append("' limit 1 tz('Asia/Shanghai')");
String sql = "select * from pqs_eventdetail where " + stringBuilder;
System.out.println("sql>>>>>>>>>>>>>>>>>>>>>>>>"+sql);
//获取暂降事件
QueryResult result = influxDbUtils.query(sql);
InfluxDBResultMapper influxDBResultMapper = new InfluxDBResultMapper();
List<EventDetail> detailList = influxDBResultMapper.toPOJO(result, EventDetail.class);
if (!CollectionUtils.isEmpty(detailList)) {
eventDetail = detailList.get(0);
if (!Objects.isNull(result)) {
List<EventDetail> detailList = influxDBResultMapper.toPOJO(result, EventDetail.class);
if (!CollectionUtils.isEmpty(detailList)) {
eventDetail = detailList.get(0);
}
}
return eventDetail;
}
@@ -72,11 +71,12 @@ public class EventDetailServiceImpl extends ServiceImpl<EventDetailMapper, Event
if (lineIndexes.size() - i != 1) {
stringBuilder.append("line_id ='").append(lineIndexes.get(i)).append("' or ");
} else {
stringBuilder.append("line_id ='").append(lineIndexes.get(i)).append("' ");
stringBuilder.append("line_id ='").append(lineIndexes.get(i)).append("' ").append(" tz('Asia/Shanghai')");
}
}
//sql语句
String sql = "SELECT * FROM pqs_eventdetail WHERE " + stringBuilder;
System.out.println("sql------------->>>"+sql);
//结果集
QueryResult result = influxDbUtils.query(sql);
//结果集映射到对象中
@@ -101,7 +101,7 @@ public class EventDetailServiceImpl extends ServiceImpl<EventDetailMapper, Event
}
}
int i = (pageNum - 1)*pageSize;
stringBuilder.append("LIMIT ").append(pageSize).append(" OFFSET ").append(i);
stringBuilder.append("LIMIT ").append(pageSize).append(" OFFSET ").append(i).append(" tz('Asia/Shanghai')");
//sql语句
String sql = "SELECT * FROM pqs_eventdetail WHERE " + stringBuilder;
//结果集

View File

@@ -3,13 +3,18 @@ package com.njcn.event.service.Impl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.dto.wave.WaveDataDTO;
import com.njcn.common.pojo.enums.common.ServerEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.utils.PubUtils;
import com.njcn.common.utils.wave.AnalyWave;
import com.njcn.device.api.GeneralDeviceInfoClient;
import com.njcn.device.api.LineFeignClient;
import com.njcn.device.pojo.dto.GeneralDeviceDTO;
import com.njcn.device.pojo.vo.LineDetailDataVO;
import com.njcn.event.config.EventBaseConfig;
import com.njcn.event.enums.EventResponseEnum;
import com.njcn.event.mapper.TransientMapper;
import com.njcn.event.pojo.param.TransientParam;
import com.njcn.event.pojo.param.WaveFileParam;
import com.njcn.event.pojo.po.EventDetail;
import com.njcn.event.pojo.vo.TransientVO;
import com.njcn.event.service.EventDetailService;
@@ -18,6 +23,8 @@ import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.Instant;
@@ -28,6 +35,8 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author: chenchao
@@ -46,6 +55,8 @@ public class TransientServiceImpl implements TransientService {
private final EventDetailService eventDetailService;
private final EventBaseConfig eventBaseConfig;
@Override
public Page<TransientVO> getTransientData(TransientParam transientParam) {
Page<TransientVO> page = new Page<>();
@@ -76,12 +87,15 @@ public class TransientServiceImpl implements TransientService {
// List<EventDetail> detailList = partition.get(transientParam.getPageNum() - 1);
if (!CollectionUtils.isEmpty(eventDetailData)) {
List<String> collect = eventDetailData.stream().map(EventDetail::getLineId).collect(Collectors.toList());
collect = collect.stream().distinct().collect(Collectors.toList());
List<TransientVO> transientData = transientMapper.getTransientData(collect);
int i = 1;
for (EventDetail eventDetail: eventDetailData) {
if (!Objects.isNull(eventDetail)) {
TransientVO transientVO = new TransientVO();
transientVO.setId(eventDetail.getLineId());
transientVO.setNumber(i++);
transientVO.setWaveName(eventDetail.getWaveName());
Instant timeId = eventDetail.getTimeId();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = LocalDateTime.ofInstant(timeId, zoneId);
@@ -112,14 +126,15 @@ public class TransientServiceImpl implements TransientService {
transientVO.setTrigType("录波");
break;
}
Double value = new BigDecimal(eventDetail.getEventValue()).setScale(3, BigDecimal.ROUND_DOWN).doubleValue();
transientVO.setEventValue(value);
Double values = new BigDecimal(1 - value).setScale(3, BigDecimal.ROUND_DOWN).doubleValue();
transientVO.setEventValues(values);
Double value = new BigDecimal(eventDetail.getEventValue()).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
transientVO.setEventValue(new BigDecimal(value*100).setScale(0,BigDecimal.ROUND_HALF_UP).doubleValue());
transientVO.setEventValues(100-transientVO.getEventValue());
transientVO.setPersistTime((Float.parseFloat(eventDetail.getPersistTime().toString()))/1000);
Float eventValue = Float.parseFloat(eventDetail.getEventValue().toString());
transientVO.setYZD(getYZD(transientVO.getPersistTime(), eventValue));
Float persistTime = Float.parseFloat(eventDetail.getPersistTime().toString());
transientVO.setYZD(getYZD(persistTime, eventValue));
transientVOS.add(transientVO);
}
}
@@ -143,20 +158,306 @@ public class TransientServiceImpl implements TransientService {
@Override
public WaveDataDTO getTransientAnalyseWave(String timeId, String lineId) {
WaveDataDTO waveDataDTO = new WaveDataDTO();
//根据监测点id获取监测点详情
LineDetailDataVO lineDetailData = lineFeignClient.getLineDetailData(lineId).getData();
String ip = lineDetailData.getIp();
EventDetail eventDetailByTime = eventDetailService.getEventDetailByTime(lineId, timeId);
String ip = lineDetailData.getIp();
String waveName = eventDetailByTime.getWaveName();
// TransientVO transientVO = transientMapper.getTransientDataById(lineId);
// String name = transientVO.getName();
// String substation = transientVO.getSubstation();
// Double eventValue = new BigDecimal(eventDetailByTime.getEventValue()).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
// Double v = new BigDecimal(eventValue*100).setScale(0,BigDecimal.ROUND_HALF_UP).doubleValue();
// Double persistTime = eventDetailByTime.getPersistTime()/1000;
// waveDataVO.setName("变电站名称: "+ substation +" 监测点名称: "+ name +" 发生时刻: "+ timeId +" 暂降幅值: "+ v +"% 持续时间: "+ persistTime +"s");
// waveDataVO.setTargetName("相电压有效值");
AnalyWave analyWave = new AnalyWave();
System.out.println("path----------------------"+"C:\\Users\\陈超\\Desktop\\Comtrade\\"+ip+"\\"+waveName);
WaveDataDTO comtrade = analyWave.getComtrade("C:\\Users\\陈超\\Desktop\\Comtrade\\192.168.0.58\\222.CFG", 1);
// WaveDataDTO comtrade = analyWave.getComtrade("C:\\Users\\陈超\\Desktop\\Comtrade\\"+ip+"\\"+waveName, 1);
WaveDataDTO waveDataDTO = analyWave.getValidData(comtrade);
WaveDataDTO comtrade = analyWave.getComtrade(eventBaseConfig.getWavePath()+"\\"+ip+"\\"+waveName+".CFG", 1);
if (Objects.isNull(comtrade.getComtradeCfgDTO())) {
throw new BusinessException(EventResponseEnum.ANALYSEWAVE_NOT_FOUND);
}
// WaveDataDTO comtrade = analyWave.getComtrade("C:\\Users\\陈超\\Desktop\\comtrade\\192.168.0.58\\222.CFG", 1);
waveDataDTO = analyWave.getValidData(comtrade);
waveDataDTO.setPtType(PubUtils.ptTypeName(lineDetailData.getPtType()));
double pt1 = Double.parseDouble(lineDetailData.getPt().split("/")[0]);
double pt2 = Double.parseDouble(lineDetailData.getPt().split("/")[1]);
double ct1 = Double.parseDouble(lineDetailData.getCt().split("/")[0]);
double ct2 = Double.parseDouble(lineDetailData.getCt().split("/")[1]);
waveDataDTO.setPt(pt1/pt2);
waveDataDTO.setCt(ct1/ct2);
return waveDataDTO;
}
@Override
public HttpServletResponse downloadWaveFile(WaveFileParam waveFileParam, HttpServletResponse response) throws Exception {
List<String> lineId = waveFileParam.getLineId();
List<String> timeId = waveFileParam.getTimeId();
copyTempData(timeId,lineId);
zipCompress(new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade"));
String zipPath = "C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade.zip";
try {
// path是指欲下载的文件的路径。
File file = new File(zipPath);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(zipPath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
delFile(zipPath);
deleteDirectoryLegacyIO(new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade"));
return response;
}
/**复制保存文件 */
public void copyTempData(List<String> timeId, List<String> lineId) throws IOException {
for (int i=0; i<timeId.size(); i++) {
//根据监测点id获取监测点详情
LineDetailDataVO lineDetailData = lineFeignClient.getLineDetailData(lineId.get(i)).getData();
EventDetail eventDetailByTime = eventDetailService.getEventDetailByTime(lineId.get(i), timeId.get(i));
if (Objects.isNull(lineDetailData.getIp()) && Objects.isNull(eventDetailByTime.getWaveName())) {
throw new BusinessException(EventResponseEnum.EVENT_NOT_FOUND);
}
String ip = lineDetailData.getIp();
String waveName = eventDetailByTime.getWaveName();
File srcCFGFile = new File(eventBaseConfig.getWavePath()+"\\"+ip+"\\"+waveName+".CFG");
File srcDATFile = new File(eventBaseConfig.getWavePath()+"\\"+ip+"\\"+waveName+".DAT");
if (!srcCFGFile.exists() && !srcDATFile.exists()) {
throw new BusinessException(EventResponseEnum.ANALYSEWAVE_NOT_FOUND);
}
File temp = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\"+ip);
temp.mkdirs();
// File cfg = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\a1234567890\\"+srcCFGFile.getName());
// File dat = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\a1234567890\\"+srcDATFile.getName());
File cfg = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\"+ip+"\\"+srcCFGFile.getName());
File dat = new File("C:\\Users\\陈超\\Desktop\\YSWJ\\comtrade\\"+ip+"\\"+srcDATFile.getName());
writeFile(srcCFGFile,cfg);
writeFile(srcDATFile,dat);
}
}
//读写文件
public static void writeFile(File wave, File temp) throws IOException {
FileInputStream fis=new FileInputStream(wave);
FileOutputStream fos=new FileOutputStream(temp);
int len;
byte[] bys=new byte[1024];
while((len=fis.read(bys))!=-1){
fos.write(bys, 0, len);
fos.flush();
}
fos.close();
fis.close();
}
//==========================================================================================================
/**
* 将文件夹及文件夹包含的内容压缩成zip文件
* (为了解决中文乱码的问题ZipOutputStream用org.apache.tools.zip.*)
* @param inputFile 源文件(夹)
* @return File 压缩后的文件(路径在源文件的文件夹路径下)
*/
public static File zipCompress(File inputFile) throws Exception {
File zipFile = null;
ZipOutputStream zos = null;
if(inputFile != null && inputFile.exists()) {
try {
String path = inputFile.getCanonicalPath();
String zipFileName = path + ".zip";
zipFile = new File(zipFileName);
if(zipFile.exists()) {
zipFile.delete();
}
zipFile.createNewFile();//创建文件
zos = new ZipOutputStream(new FileOutputStream(zipFile));
//压缩文件或文件夹
compressFile(zos, inputFile, inputFile.getName());
}catch(Exception e) {
System.out.println("文件压缩异常:" + e);
throw e;
}finally {
try {
if(zos != null) {
//先调用outputStream的flush()再关闭流;
//流如果未正常关闭,则会在解压的时候出现压缩文件损坏的现象
zos.flush();
zos.close();
}
}catch(Exception ex) {
System.out.println("输出流关闭异常:" + ex);
}
}
}
return zipFile;
}
/**
* 压缩文件或文件夹 (ZipEntry 使用org.apache.tools.zip.*,不要用 java.util.zip.*)
* @param zos zip输出流
* @param sourceFile 源文件
* @param baseName 父路径
* @throws Exception 异常
*/
public static void compressFile(ZipOutputStream zos, File sourceFile, String baseName) throws Exception{
if(!sourceFile.exists()) {
return;
}
//若路径为目录(文件夹)
if(sourceFile.isDirectory()) {
//取出文件夹中的文件(或子文件夹)
File[] fileList = sourceFile.listFiles();
//若文件夹为空,则创建一个目录进入点
if(fileList.length == 0) {
//文件名称后跟File.separator表示这是一个文件夹
zos.putNextEntry(new ZipEntry(baseName + File.separator));
//若文件夹非空则递归调用compressFile,对文件夹中的每个文件或每个文件夹进行压缩
}else {
for(int i = 0; i < fileList.length; i++) {
compressFile(zos, fileList[i],
baseName + File.separator + fileList[i].getName());
}
}
//若为文件,则先创建目录进入点,再将文件写入zip文件中
}else {
ZipEntry ze = new ZipEntry(baseName);
//设置ZipEntry的最后修改时间为源文件的最后修改时间
ze.setTime(sourceFile.lastModified());
zos.putNextEntry(ze);
FileInputStream fis = new FileInputStream(sourceFile);
copyStream(fis, zos);
try {
if(fis != null) {
fis.close();
}
}catch(Exception e) {
System.out.println("输入流关闭异常:" + e);
}
}
}
/**
* 流拷贝
* @param in 输入流
* @param out 输出流
* @throws IOException
*/
public static void copyStream(InputStream in, OutputStream out) throws IOException{
int bufferLength = 1024 * 100;
synchronized(in) {
synchronized(out) {
int count = 0;
byte[] buffer = new byte[bufferLength];
while((count = in.read(buffer, 0, bufferLength)) != -1) {
out.write(buffer, 0, count);
}
out.flush();
}
}
}
//=================================================================================================================
/**处理文件路径和指定压缩包位置 */
public static String downloadWaveMoreFile(List<String> pathList) {
List<File> list = new ArrayList<>();
for (String string: pathList) {
String path = string;
//待压缩的多个源文件
File f1 = new File(path+".CFG");
File f2 = new File(path+".DAT");
list.add(f1);
list.add(f2);
}
File[] srcfile = list.toArray(new File[0]);
String zipPath = "C:\\Users\\陈超\\Desktop\\YSWJ\\新下载的波形文件.zip";
//压缩后的文件存放路径
File zipfile = new File(zipPath);
zipFiles(srcfile, zipfile);
return zipPath;
}
/**
* 压缩多个文件成一个zip文件
* @param srcfile源文件列表
* @param zipfile压缩后的文件
*/
public static void zipFiles(File[] srcfile, File zipfile) {
byte[] buf = new byte[1024];
try {
//ZipOutputStream类完成文件或文件夹的压缩
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
for (int i = 0; i < srcfile.length; i++) {
FileInputStream in = new FileInputStream(srcfile[i]);
out.putNextEntry(new ZipEntry(srcfile[i].getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
System.out.println("压缩完成.");
} catch (Exception e) {
e.printStackTrace();
}
}
/**删除文件(夹)和空文件夹 */
private void deleteDirectoryLegacyIO(File file) {
File[] list = file.listFiles(); //无法做到list多层文件夹数据
if (list != null) {
for (File temp : list) { //先去递归删除子文件夹及子文件
deleteDirectoryLegacyIO(temp); //注意这里是递归调用
}
}
if (file.delete()) { //再删除自己本身的文件夹
System.out.printf("删除成功 : %s%n", file);
} else {
System.err.printf("删除失败 : %s%n", file);
}
}
/**
* 删除文件
* @param filePathAndName 指定得路径
*/
public static void delFile(String filePathAndName) {
try {
String filePath = filePathAndName;
filePath = filePath.toString();
java.io.File myDelFile = new java.io.File(filePath);
myDelFile.delete();
} catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();
}
}
/**
* 获取该事件的严重度
*

View File

@@ -3,8 +3,11 @@ package com.njcn.event.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.dto.wave.WaveDataDTO;
import com.njcn.event.pojo.param.TransientParam;
import com.njcn.event.pojo.param.WaveFileParam;
import com.njcn.event.pojo.vo.TransientVO;
import javax.servlet.http.HttpServletResponse;
/**
* @author: chenchao
* @date: 2022/03/29 10:40
@@ -25,5 +28,11 @@ public interface TransientService {
* @return
*/
WaveDataDTO getTransientAnalyseWave(String timeId, String lineId);
/**
* 功能描述: 暂态事件波形文件下载
* @param waveFileParam
* @return
*/
HttpServletResponse downloadWaveFile(WaveFileParam waveFileParam, HttpServletResponse response) throws Exception;
}