1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876 |
- package com.tofly.scada.service.impl;
- import cn.hutool.core.date.DateUtil;
- import com.alibaba.fastjson.JSON;
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.tofly.common.core.util.StringUtil;
- import com.tofly.common.oauth.exception.ToflyDeniedException;
- import com.tofly.scada.common.FlowConstant;
- import com.tofly.scada.common.MessageTopicEnum;
- import com.tofly.scada.entity.*;
- import com.tofly.scada.entity.dto.DeviceQuery;
- import com.tofly.scada.entity.dto.ScadaQuery;
- import com.tofly.scada.entity.vo.*;
- import com.tofly.scada.mapper.AllocationMapper;
- import com.tofly.scada.mapper.DeviceArchiveManageMapper;
- import com.tofly.scada.mapper.ScadaMapper;
- import com.tofly.scada.mapper.ScadaReportMapper;
- import com.tofly.scada.service.*;
- import com.tofly.scada.util.SendTidingsUtil;
- import com.tofly.scada.util.TimeUtils;
- import lombok.SneakyThrows;
- import lombok.extern.slf4j.Slf4j;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.BeanUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.scheduling.annotation.Async;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import org.springframework.util.CollectionUtils;
- import org.springframework.util.ObjectUtils;
- import org.springframework.util.StringUtils;
- import javax.annotation.PostConstruct;
- import java.math.BigDecimal;
- import java.math.RoundingMode;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.time.LocalDate;
- import java.time.LocalDateTime;
- import java.util.*;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.atomic.AtomicReference;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import java.util.stream.Collectors;
- @Service
- @Slf4j
- public class ScadaServiceImpl extends ServiceImpl<ScadaMapper, Scada> implements ScadaService {
-
- private List<String> llj = new ArrayList<>();
- private final Logger logger = LoggerFactory.getLogger(ScadaServiceImpl.class);
- private static final Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]*");
- public static final String SCADA_HISTORY = "SCADA_HISTORY";
- @Autowired
- private ScadaMapper scadaMapper;
- @Autowired
- private StatisticsScadaService statisticsScadaService;
- @Autowired
- private AllocationMapper allocationMapper;
- @Autowired
- private DeviceArchiveManageMapper deviceArchiveManageMapper;
- @Autowired
- private ScadaReportMapper reportMapper;
- @Autowired
- private SendTidingsUtil sendTidingsUtil;
- @Autowired
- private ScadaReportServiceImpl scadaReportService;
- @Autowired
- private TfScadaReportListService tfScadaReportListService;
- @Autowired
- private AllocationService allocationService;
- @Autowired
- private DmatableService dmatableService;
- @Autowired
- private ScadaMonitorService scadaMonitorService;
-
-
- @Scheduled(cron = "0 0 2 28 * ? ")
- public void createMonths() {
- Calendar cal = Calendar.getInstance();
- cal.setTime(new Date());
- cal.add(Calendar.MONTH, 1);
- SimpleDateFormat format = new SimpleDateFormat("yyyy_MM");
- String date = format.format(cal.getTime());
- String tableName = "SCADA_MONTH_" + date;
- logger.info("开始检测Scada月份表状态");
- if (scadaMapper.verifyTableMonthsIsExits(tableName) <= 0) {
- logger.info("Scada月份表状态:不存在,开始创建");
- scadaMapper.createTableMonths(tableName);
- logger.info("Scada月份表状态:创建完成");
- }
- logger.info("结束检测Scada月份表状态");
- }
- public String createMonths(Date time) {
- Calendar cal = Calendar.getInstance();
- cal.setTime(time == null ? new Date() : time);
- SimpleDateFormat format = new SimpleDateFormat("yyyy_MM");
- String date = format.format(cal.getTime());
- String tableName = "SCADA_MONTH_" + date;
- logger.info("开始检测Scada月份表状态");
- if (scadaMapper.verifyTableMonthsIsExits(tableName) <= 0) {
- logger.info("Scada月份表状态:不存在,开始创建");
- scadaMapper.createTableMonths(tableName);
- logger.info("Scada月份表状态:创建完成");
- }
- logger.info("结束检测Scada月份表状态");
- return tableName;
- }
-
-
- @Scheduled(cron = "0 0 * * * ? ")
- public void insert24H() {
- logger.info("同步scada历史数据到24小时表:正在进行时间调整");
-
- Calendar calendar = Calendar.getInstance();
- Date date = new Date();
- calendar.setTime(date);
-
- calendar.add(Calendar.HOUR_OF_DAY, -1);
- calendar.set(Calendar.MINUTE, 0);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MILLISECOND, 0);
- Date startTime = calendar.getTime();
- String start = DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
-
- calendar.set(Calendar.MINUTE, 59);
- calendar.set(Calendar.SECOND, 59);
- calendar.set(Calendar.MILLISECOND, 999);
- Date endTime = calendar.getTime();
- String end = DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
- logger.info("同步scada历史数据到24小时表:正在进行查询历史数据");
-
- List<String> codes = getCodes(null);
-
- List<StatisticsScadaCalVo> scadaLists = scadaMapper.selectHistoryMaxAndMinByScadaTime(codes, startTime, endTime, 0);
-
- statisticsScadaService.delete(0, codes, startTime, endTime);
-
- saveStatisticsCode(scadaLists, FlowConstant.INTEGER_ZERO, true);
- logger.info("同步scada历史数据到24小时表结束");
- }
- public void insert24H(String code, Date startTime, Date endTime, Integer type) {
- logger.info("同步scada历史数据到24小时表:正在进行时间调整");
- List<String> codes = getCodes(code);
-
- List<StatisticsScadaCalVo> scadaLists = scadaMapper.selectHistoryMaxAndMinByScadaTime(codes, startTime, endTime, type);
-
- statisticsScadaService.delete(0, codes, startTime, endTime);
-
- saveStatisticsCode(scadaLists, FlowConstant.INTEGER_ZERO, false);
- }
- private Date getDateType(String timeStr, Integer type) {
- if (0 == type) {
- String s = timeStr + ":00:00";
- LocalDateTime localDateTime = TimeUtils.fromString2LocalDateTime(s, "yyyy-MM-dd HH:mm:ss");
- return TimeUtils.convertLDTToDate(localDateTime);
- } else if (1 == type) {
- return TimeUtils.localDateToDate(TimeUtils.fromString2LocalDate(timeStr, "yyyy-MM-dd"));
- } else {
- String s = timeStr + "-01";
- return TimeUtils.localDateToDate(TimeUtils.fromString2LocalDate(s, "yyyy-MM-dd"));
- }
- }
-
- @Scheduled(cron = "0 30 1 * * ? ")
- public void syncDaysData() {
- logger.info("同步scada历史数据到表:正在进行时间调整");
-
- Calendar calendar = Calendar.getInstance();
- Date date = new Date();
- calendar.setTime(date);
-
- calendar.add(Calendar.DAY_OF_MONTH, -1);
- calendar.set(Calendar.HOUR_OF_DAY, 0);
- calendar.set(Calendar.MINUTE, 0);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MILLISECOND, 0);
- Date startTime = calendar.getTime();
- String start = DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
-
- calendar.set(Calendar.HOUR_OF_DAY, 23);
- calendar.set(Calendar.MINUTE, 59);
- calendar.set(Calendar.SECOND, 59);
- calendar.set(Calendar.MILLISECOND, 999);
- Date endTime = calendar.getTime();
- String end = DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
- logger.info("同步scada历史数据到24小时表:正在进行查询历史数据");
-
- List<String> codes = getCodes(null);
-
- List<StatisticsScadaCalVo> scadaLists = scadaMapper.selectHistoryMaxAndMinByScadaTime(codes, startTime, endTime, 1);
-
- statisticsScadaService.delete(1, codes, startTime, endTime);
- saveStatisticsCode(scadaLists, FlowConstant.INTEGER_ONE, true);
- }
- @Async
- public void syncDaysData(String code, Date startTime, Date endTime, Integer type) {
- logger.info("同步scada历史数据到表:正在进行时间调整");
- List<String> codes = getCodes(code);
-
- List<StatisticsScadaCalVo> scadaLists = scadaMapper.selectHistoryMaxAndMinByScadaTime(codes, startTime, endTime, type);
-
- statisticsScadaService.delete(1, codes, startTime, endTime);
- saveStatisticsCode(scadaLists, FlowConstant.INTEGER_ONE, true);
- }
-
- @Scheduled(cron = "0 0 1 1 * ? ")
- public void syncDataIntoMonths() {
- logger.info("同步scada历史数据到月份表:正在进行时间调整");
-
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(new Date());
-
- calendar.add(Calendar.MONTH, -1);
- calendar.set(Calendar.DATE, 1);
- calendar.set(Calendar.HOUR_OF_DAY, 0);
- calendar.set(Calendar.MINUTE, 0);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MILLISECOND, 0);
- Date startTime = calendar.getTime();
- String start = DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
-
- calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
- calendar.set(Calendar.HOUR_OF_DAY, 23);
- calendar.set(Calendar.MINUTE, 59);
- calendar.set(Calendar.SECOND, 59);
- calendar.set(Calendar.MILLISECOND, 999);
- Date endTime = calendar.getTime();
- String end = DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
- logger.info("同步scada历史数据到月份表:正在进行历史数据查询....");
-
- List<String> codes = getCodes(null);
-
- List<StatisticsScadaCalVo> scadaLists = scadaMapper.selectHistoryMaxAndMinByScadaTime(codes, startTime, endTime, 2);
-
- statisticsScadaService.delete(2, codes, startTime, endTime);
- saveStatisticsCode(scadaLists, FlowConstant.INTEGER_TWO, true);
- }
- @Async
- public void syncDataIntoMonths(String code, Date startTime, Date endTime, Integer type) {
- logger.info("同步scada历史数据到月份表:正在进行时间调整");
- List<String> codes = getCodes(code);
-
- List<StatisticsScadaCalVo> scadaLists = scadaMapper.selectHistoryMaxAndMinByScadaTime(codes, startTime, endTime, 2);
-
- statisticsScadaService.delete(2, codes, startTime, endTime);
- saveStatisticsCode(scadaLists, FlowConstant.INTEGER_TWO, true);
- }
-
- public void saveStatisticsByCode(Date startTime, Date endTime, List<String> codes, Integer DateType) {
- }
-
- @Async
- public void saveStatisticsData(Date startTime, Date endTime, List<Scada> scadas, Integer DateType) {
- }
-
- public int insertMouthBatch(List<Scada> scadas, String tableName) {
- int size = scadas.size();
- int limit = 1000;
- int startIndex = 0;
- int endIndex;
- if (size <= limit) {
-
- int insertMouth = scadaMapper.insertMouth(scadas, tableName);
- log.info("新增数据:{}条", insertMouth);
- } else {
- while (startIndex < size) {
-
- endIndex = startIndex + limit;
-
- endIndex = endIndex > size ? size : endIndex;
-
- List<Scada> scadaList = scadas.subList(startIndex, endIndex);
-
- startIndex = endIndex;
-
- int insertMouth = scadaMapper.insertMouth(scadaList, tableName);
- log.info("新增数据:{}条", insertMouth);
- }
- }
- return size;
- }
-
- @Transactional(rollbackFor = Exception.class)
- public void saveStatisticsCode(List<StatisticsScadaCalVo> scadaLists, Integer dateType, boolean isAuto) {
- if (!CollectionUtils.isEmpty(scadaLists)) {
- logger.info("计算scada统计数据:正在进行数据大小{}", scadaLists.size());
-
- List<StatisticsScada> saveList = new ArrayList<>();
- if (CollectionUtils.isEmpty(scadaLists)) {
- return;
- }
- scadaLists.forEach(k -> {
- StatisticsScada statisticsScada = new StatisticsScada();
- statisticsScada.setCode(k.getCode());
- String maxValue = k.getMaxValue() == null ? "0" : k.getMaxValue();
- statisticsScada.setValue(maxValue);
- statisticsScada.setAve(k.getAvgValue());
- statisticsScada.setMin(k.getMinValue() == null ? "0" : k.getMinValue());
- statisticsScada.setMax(maxValue);
- statisticsScada.setFold(k.getDifferenceValue());
- List<Date> dates = getDateListByType(getDateType(k.getDateTimeStr(), dateType), dateType);
- if (!CollectionUtils.isEmpty(dates) && dates.size() == 2) {
- statisticsScada.setStartTime(dates.get(0));
- statisticsScada.setEndTime(dates.get(1));
- }
- statisticsScada.setStatisticsType(dateType);
- statisticsScada.setDataType(k.getAllocationType());
-
- saveList.add(statisticsScada);
- });
-
- logger.info("新增scada数据大小{}", saveList.size());
- statisticsScadaService.saveBatch(saveList);
- } else {
- logger.info("获取历史数据为空");
- }
- }
-
- public List<Date> getDateListByType(Date time, Integer type) {
-
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(time == null ? new Date() : time);
- List<Date> dates = new ArrayList<>();
- if (type.equals(FlowConstant.INTEGER_ZERO)) {
-
- calendar.set(Calendar.MINUTE, 0);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MILLISECOND, 0);
- Date startTime = calendar.getTime();
- String start = DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
-
- calendar.set(Calendar.MINUTE, 59);
- calendar.set(Calendar.SECOND, 59);
- calendar.set(Calendar.MILLISECOND, 999);
- Date endTime = calendar.getTime();
- String end = DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
- dates.add(startTime);
- dates.add(endTime);
- } else if (type.equals(FlowConstant.INTEGER_ONE)) {
-
- calendar.set(Calendar.HOUR_OF_DAY, 0);
- calendar.set(Calendar.MINUTE, 0);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MILLISECOND, 0);
- Date startTime = calendar.getTime();
- String start = DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
-
- calendar.set(Calendar.HOUR_OF_DAY, 23);
- calendar.set(Calendar.MINUTE, 59);
- calendar.set(Calendar.SECOND, 59);
- calendar.set(Calendar.MILLISECOND, 999);
- Date endTime = calendar.getTime();
- String end = DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
- dates.add(startTime);
- dates.add(endTime);
- } else if (type.equals(FlowConstant.INTEGER_TWO)) {
-
- calendar.set(Calendar.DATE, 1);
- calendar.set(Calendar.HOUR_OF_DAY, 0);
- calendar.set(Calendar.MINUTE, 0);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MILLISECOND, 0);
- Date startTime = calendar.getTime();
- String start = DateUtil.format(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
-
- calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
- calendar.set(Calendar.HOUR_OF_DAY, 23);
- calendar.set(Calendar.MINUTE, 59);
- calendar.set(Calendar.SECOND, 59);
- calendar.set(Calendar.MILLISECOND, 999);
- Date endTime = calendar.getTime();
- dates.add(startTime);
- dates.add(endTime);
- }
- return dates;
- }
-
- public List<Scada> getScadasDatas(String code, Date start, Date end) {
- List<Allocation> allocations = allocationMapper.selectList(Wrappers.<Allocation>lambdaQuery()
- .eq(StringUtils.hasText(code), Allocation::getVariableCode, code));
- List<String> codes = allocations.stream().filter(allocation -> allocation.getVariableCode() != null)
- .map(Allocation::getVariableCode).collect(Collectors.toList());
- List<Scada> scadas = new ArrayList<>();
- if (!CollectionUtils.isEmpty(codes)) {
- QueryWrapper<Scada> scadaQueryWrapper = new QueryWrapper<>();
- scadaQueryWrapper.between("SCADA_TIME", start, end)
- .in("CODE", codes);
- scadas = scadaMapper.selectList(scadaQueryWrapper);
- }
- return scadas;
- }
- public List<String> getCodes(String code) {
- if (StringUtils.hasText(code) && code.contains(",")) {
- String[] codeList = code.split(",");
- List<Allocation> allocations = allocationMapper.selectList(Wrappers.<Allocation>lambdaQuery()
- .in(!CollectionUtils.isEmpty(Arrays.asList(codeList)), Allocation::getVariableCode, codeList));
- List<String> codes = allocations.stream().filter(allocation -> allocation.getVariableCode() != null)
- .map(Allocation::getVariableCode).collect(Collectors.toList());
- if (!CollectionUtils.isEmpty(codes)) {
- return codes;
- }
- }
- List<Allocation> allocations = allocationMapper.selectList(Wrappers.<Allocation>lambdaQuery()
- .eq(StringUtils.hasText(code), Allocation::getVariableCode, code));
- List<String> codes = allocations.stream().filter(allocation -> allocation.getVariableCode() != null)
- .map(Allocation::getVariableCode).collect(Collectors.toList());
- if (!CollectionUtils.isEmpty(codes)) {
- return codes;
- }
- return null;
- }
- @Async
- public void insertMouth(List<Scada> scadas, String tableName) {
- int size = scadas.size();
- int i = 0;
- while (size > 600) {
- scadaMapper.insertMouth(scadas.subList(i, i + 600), tableName);
- i = i + 600;
- size = size - 600;
- }
- if (size > 0) {
- scadaMapper.insertMouth(scadas.subList(i, i + size), tableName);
- }
- }
- @Override
- public List<Scada> getListData() {
- List<Scada> scadaList = scadaMapper.selectMonitoring("SCADA_MONITOR");
- for (Scada scada : scadaList) {
- if (StringUtils.hasText(scada.getValue()) && scada.getValue().startsWith(".")) {
- scada.setValue("0" + scada.getValue());
- }
- }
- return scadaList;
- }
- @Override
- public boolean fetch24HoursData(String syncTime) {
- Date date = null;
- if (StringUtils.isEmpty(syncTime)) {
- date = new Date();
- Calendar cal = Calendar.getInstance();
- cal.setTime(date);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- } else {
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
- try {
- Date parse = format.parse(syncTime);
- Date now = new Date();
- Calendar cal = Calendar.getInstance();
- cal.setTime(now);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- if (parse.getTime() >= now.getTime()) {
- throw new RuntimeException("时间参数不允许大于等于当前时间:" + format.format(now));
- }
- date = parse;
- } catch (ParseException e) {
- throw new RuntimeException("时间参数格式传入错误:" + e);
- }
- }
- return true;
- }
- @Override
- public void fetchMonthsData(String syncTime) {
- }
- @Override
- public void fetchDaysData(String syncTime) {
- }
- @Override
- public Page<ScadaVo> get24HoursData(Page page, ScadaQuery scadaQuery) {
- QueryWrapper<ScadaQuery> queryWrapper = new QueryWrapper<>();
- if (StringUtils.hasText(scadaQuery.getCode())) {
- queryWrapper.like("hours.CODE", scadaQuery.getCode());
- }
- if (StringUtils.hasText(scadaQuery.getValue())) {
- queryWrapper.like("hours.VALUE", scadaQuery.getValue());
- }
- if (scadaQuery.getStart() != null && scadaQuery.getEnd() != null) {
- queryWrapper.between("hours.SCADA_TIME", scadaQuery.getStart(), scadaQuery.getEnd());
- }
- queryWrapper.orderByDesc("hours.SCADA_TIME");
- return scadaMapper.pageList(page, queryWrapper, "SCADA_HOURS");
- }
- @Override
- public Page getMonthsData(Page page, ScadaQuery scadaQuery) {
- QueryWrapper<ScadaQuery> queryWrapper = new QueryWrapper<>();
- queryWrapper.orderByDesc("hours.SCADA_TIME");
- if (StringUtils.hasText(scadaQuery.getCode())) {
- queryWrapper.like("hours.CODE", scadaQuery.getCode());
- }
- if (StringUtils.hasText(scadaQuery.getValue())) {
- queryWrapper.like("hours.VALUE", scadaQuery.getValue());
- }
- if (scadaQuery.getStart() != null && scadaQuery.getEnd() != null) {
- if (scadaQuery.getStart().getYear() == scadaQuery.getEnd().getYear() &&
- scadaQuery.getStart().getMonth() == scadaQuery.getEnd().getMonth()) {
- List<Date> startAndEndByDate = TimeUtils.getMonthsToStartAndEndByDate(scadaQuery.getStart());
- queryWrapper.between("hours.SCADA_TIME", scadaQuery.getStart(), scadaQuery.getEnd());
- Calendar cal = Calendar.getInstance();
- cal.setTime(startAndEndByDate.get(0));
- SimpleDateFormat format = new SimpleDateFormat("yyyy_MM");
- String date = format.format(cal.getTime());
- String tableName = "SCADA_MONTH_" + date;
- return scadaMapper.pageList(page, queryWrapper, tableName);
- }
- }
- return scadaMapper.pageList(page, queryWrapper, SCADA_HISTORY);
- }
- @Override
- public List<DeviceArchiveManageVo> getAppData(DeviceQuery deviceQuery) {
- QueryWrapper<DeviceArchiveManage> queryWrapper = getQueryWrapper(deviceQuery);
- List<DeviceArchiveManage> deviceArchiveManages = deviceArchiveManageMapper.pageList(queryWrapper);
- if (CollectionUtils.isEmpty(deviceArchiveManages)) {
- return null;
- }
-
- List<Allocation> allocations = allocationMapper.selectList(new QueryWrapper<Allocation>().lambda().eq(StringUtil.isNotNull(deviceQuery.getIsDisplay()),Allocation::getIsDisplay,deviceQuery.getIsDisplay()));
-
- List<ScadaReport> scadaReports = reportMapper.selectList(null);
-
- List<Scada> scadas = getListData();
- List<DeviceArchiveManageVo> manageVos = deviceArchiveManages.stream().map(deviceArchiveManage -> {
- DeviceArchiveManageVo vo = new DeviceArchiveManageVo();
- BeanUtils.copyProperties(deviceArchiveManage, vo);
-
- if (!CollectionUtils.isEmpty(allocations)) {
-
- List<AllocationVo> allocationVos = new HashSet<>(allocations).stream().filter(allocation -> allocation.getDeviceId() != null &&
- allocation.getDeviceId().equals(vo.getId())).map(allocation -> {
- AllocationVo allocationVo = new AllocationVo();
- BeanUtils.copyProperties(allocation, allocationVo);
- Scada scadaBelong = null;
-
- if (!CollectionUtils.isEmpty(scadas)) {
- List<Scada> scadaList = scadas.stream()
- .filter(scada -> scada.getCode() != null && scada.getCode().equals(allocation.getVariableCode()))
- .collect(Collectors.toList());
- if (!CollectionUtils.isEmpty(scadaList)) {
- scadaBelong = scadaList.get(0);
- allocationVo.setScada(scadaList.get(0));
- }
- }
-
- Set<Long> reportIdSets = getReportIdSets(Collections.singletonList(allocation));
- if (!CollectionUtils.isEmpty(scadaReports) && !CollectionUtils.isEmpty(reportIdSets)) {
-
- List<ScadaReport> reports = scadaReports.stream().filter(scadaReport -> scadaReport.getId() != null
- && reportIdSets.contains(scadaReport.getId())).collect(Collectors.toList());
-
- allocationVo.setIsAlarm("0");
-
- if(scadaBelong != null && scadaBelong.getValue() != null){
- for (ScadaReport scadaReport : reports) {
- if(scadaReport.getReportLower() == null || scadaReport.getReportUpper() == null){
- continue;
- }
- if(!isNumber(scadaReport.getReportLower())
- || !isNumber(scadaReport.getReportUpper())
- || !isNumber(scadaBelong.getValue())){
- continue;
- }
- Double lower = Double.parseDouble(scadaReport.getReportLower());
- Double upper = Double.parseDouble(scadaReport.getReportUpper());
- Double value = Double.parseDouble(scadaBelong.getValue());
- if(value.compareTo(lower) >= 0 && value.compareTo(upper) <= 0){
- allocationVo.setIsAlarm("1");
- break;
- }
- }
- }
- allocationVo.setScadaReports(reports);
- }
- return allocationVo;
- }).collect(Collectors.toList());
- vo.setAllocations(allocationVos);
- }
- if (org.apache.commons.lang3.StringUtils.isNotBlank(deviceQuery.getDeviceTypeIds())) {
- List<String> deviceTypeList = Arrays.stream(deviceQuery.getDeviceTypeIds().split(",")).map(String::trim)
- .collect(Collectors.toList());
- for (String s : deviceTypeList) {
- if (vo.getDeviceType().equals(s)) {
- return vo;
- }
- }
- return null;
- }
- return vo;
- }).filter(Objects::nonNull).collect(Collectors.toList());
- return manageVos;
- }
-
- private void getAllocation(DeviceArchiveManageVo vo) {
- QueryWrapper<Allocation> allocationQueryWrapper = new QueryWrapper<>();
- allocationQueryWrapper.eq("DEVICE_ID", vo.getId());
- List<Allocation> allocations = allocationMapper.selectList(allocationQueryWrapper);
- if (!CollectionUtils.isEmpty(allocations)) {
- List<AllocationVo> allocationVos = allocations.stream().map(allocation -> {
- AllocationVo allocationVo = new AllocationVo();
- BeanUtils.copyProperties(allocation, allocationVo);
-
- List<Scada> dataByCode = scadaMapper.getListDataByCode(allocation.getVariableCode());
- if (!CollectionUtils.isEmpty(dataByCode)) {
- allocationVo.setScada(dataByCode.get(0));
- }
-
- Set<Long> reportIdSets = getReportIdSets(Collections.singletonList(allocation));
- if (!CollectionUtils.isEmpty(reportIdSets)) {
- logger.info("获取指标报警相关....");
- QueryWrapper<ScadaReport> scadaReportQueryWrapper = new QueryWrapper<>();
- scadaReportQueryWrapper.in("ID", reportIdSets);
- List<ScadaReport> scadaReports = reportMapper.selectList(scadaReportQueryWrapper);
- if (!CollectionUtils.isEmpty(scadaReports)) {
- allocationVo.setScadaReports(scadaReports);
- }
- }
-
- return allocationVo;
- }).collect(Collectors.toList());
- vo.setAllocations(allocationVos);
- }
- }
-
- private QueryWrapper<DeviceArchiveManage> getQueryWrapper(DeviceQuery deviceQuery) {
- QueryWrapper<DeviceArchiveManage> queryWrapper = new QueryWrapper<>();
- if (!ObjectUtils.isEmpty(deviceQuery)) {
- if (StringUtils.hasText(deviceQuery.getType())) {
- queryWrapper.eq("manage.TYPE", deviceQuery.getType());
- }
- if (StringUtils.hasText(deviceQuery.getDeviceType())) {
- queryWrapper.eq("manage.DEVICE_TYPE", deviceQuery.getDeviceType());
- }
- if (StringUtils.hasText(deviceQuery.getStatus())) {
- queryWrapper.eq("manage.STATUS", deviceQuery.getStatus());
- }
- if (StringUtils.hasText(deviceQuery.getQuery())) {
- queryWrapper.and(q -> {
- q.like("manage.ADDRESS", deviceQuery.getQuery())
- .or().like("manage.NAME", deviceQuery.getQuery())
- .or().like("manage.DESCRIBE", deviceQuery.getQuery());
- });
- }
- if (StringUtils.hasText(deviceQuery.getName())) {
- queryWrapper.like("manage.NAME", deviceQuery.getName());
- }
- if (StringUtils.hasText(deviceQuery.getCode())) {
- queryWrapper.like("allocation.VARIABLE_CODE", deviceQuery.getCode());
- }
- if (deviceQuery.getDeviceId() != null) {
- queryWrapper.eq("manage.ID", deviceQuery.getDeviceId());
- }
- if (deviceQuery.getLatitude() != null && deviceQuery.getLongitude() != null) {
- queryWrapper.eq("manage.LATITUDE", deviceQuery.getLatitude())
- .eq("manage.LONGITUDE", deviceQuery.getLongitude());
- }
- }
- return queryWrapper;
- }
- @Override
- @Async
- public void insertData(Scada scada) {
- if (ObjectUtils.isEmpty(scada)) {
- throw new ToflyDeniedException("数据为空");
- }
- if (!ObjectUtils.isEmpty(scada)) {
-
-
- sendNotice(scada);
- }
- }
-
- private Scada getScada(Scada scada) {
- if (scada != null && scada.getId() != null && StringUtils.isEmpty(scada.getValue()) && scada.getScadaTime() == null) {
- List<Scada> scadas = baseMapper.selectScadaMonitoringRealtimeById("SCADA_MONITORING_REALTIME", scada.getId());
- if (!CollectionUtils.isEmpty(scadas)) {
- scada = scadas.get(0);
- }
- }
- return scada;
- }
-
- @Scheduled(cron = "0 0/1 * * * ?")
- @Async
- public void timingInsertData() {
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(new Date());
- Date end = calendar.getTime();
- calendar.add(Calendar.MINUTE, -5);
- Date start = calendar.getTime();
- List<Scada> scadas = scadaMapper.selectList(new QueryWrapper<Scada>().lambda()
- .between(Scada::getUpdateTime, start, end));
- log.info("时间{}-----{}----->查询每分钟定时任务实时数据{}", start, end, scadas);
- if (!CollectionUtils.isEmpty(scadas)) {
-
-
- for (Scada scada : scadas) {
-
-
- sendNotice(scada, DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
- }
- }
- }
-
- public int insertMouthDataBatch(List<Scada> scadas, String tableName) {
- int size = scadas.size();
- int limit = 1000;
- int startIndex = 0;
- int endIndex;
- if (size <= limit) {
-
- int insertMouth = scadaMapper.insertMouth(scadas, tableName);
- log.info("新增数据:{}条", insertMouth);
- } else {
- while (startIndex < size) {
-
- endIndex = startIndex + limit;
-
- endIndex = endIndex > size ? size : endIndex;
-
- List<Scada> scadaList = scadas.subList(startIndex, endIndex);
-
- startIndex = endIndex;
-
- int insertMouth = scadaMapper.insertMouth(scadaList, tableName);
- log.info("{}新增数据:{}条", tableName, insertMouth);
- }
- }
- return size;
- }
- @Override
- @Transactional(rollbackFor = Exception.class)
- public void fetchData(String code, String start, String end, Integer type) {
- Date startTime;
- Date endTime;
- try {
- SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
- startTime = format.parse(start);
- endTime = format.parse(end);
- } catch (Exception e) {
- throw new RuntimeException("时间格式有误");
- }
- long s = System.currentTimeMillis();
-
- logger.info("同步scada历史数据开始");
- switch (type) {
- case 0: {
- log.info("开始进行统计计算-----{}", type);
- insert24H(code, startTime, endTime, type);
- long e = System.currentTimeMillis();
- logger.info("统计计算小时结束,用时{}", e - s);
- break;
- }
- case 1: {
- log.info("开始进行统计计算-----{}", type);
- syncDaysData(code, startTime, endTime, type);
- long e = System.currentTimeMillis();
- logger.info("统计计算天结束,用时{}", e - s);
- break;
- }
- case 2: {
- log.info("开始进行统计计算-----{}", type);
- syncDataIntoMonths(code, startTime, endTime, type);
- long e = System.currentTimeMillis();
- logger.info("统计计算月结束,用时{}", e - s);
- break;
- }
- case 3: {
-
- break;
- }
- }
- }
- @Override
- public Page<StatisticsScadaVo> selectHistoryByMouthsTables(String mouthTable, Page page,
- ScadaQuery scadaQuery, boolean isPage) {
- if (isPage) {
-
- return baseMapper.selectHistoryByMouthsTablePage(mouthTable, page, scadaQuery);
- } else {
- Page<StatisticsScadaVo> pageDb = new Page<>();
- List<StatisticsScadaVo> statisticsScadaVoPage = baseMapper.selectHistoryByMouthsTableList(mouthTable, scadaQuery);
- pageDb.setRecords(statisticsScadaVoPage);
-
- return pageDb;
- }
- }
-
- private void defaultValHandle(Page<StatisticsScadaVo> statisticsScadaVoPage) {
- for (StatisticsScadaVo scadaVo : statisticsScadaVoPage.getRecords()) {
- if (!StringUtils.hasText(scadaVo.getValue())) {
- scadaVo.setValue("0");
- } else if (StringUtils.hasText(scadaVo.getValue()) && scadaVo.getValue().startsWith(".")) {
- String value = scadaVo.getValue();
- scadaVo.setValue("0" + value);
- }
- }
- }
- @Override
- public void fetchDataMouth(String code, String startStr, String endStr) {
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(new Date());
- Date end = DateUtil.parseDateTime(endStr);
- calendar.add(Calendar.MINUTE, -1);
- Date start = DateUtil.parseDateTime(startStr);
- List<String> codes = getCodes(code);
- if (CollectionUtils.isEmpty(codes)) {
- return;
- }
- List<Scada> scadas = scadaMapper.selectList(new QueryWrapper<Scada>().lambda()
- .between(Scada::getScadaTime, start, end)
- .in(Scada::getCode, codes));
- log.info("查询每分钟定时任务实时数据{}", scadas);
- if (!CollectionUtils.isEmpty(scadas)) {
- for (Scada scada : scadas) {
-
- if (scada.getValue().startsWith(".")) {
- scada.setValue("0" + scada.getValue());
- }
- Scada monitoring = scadaMapper.selectDataByMonitoring(scada.getCode());
- log.info("查询存在的实时数据{}", monitoring);
- if (ObjectUtils.isEmpty(monitoring)) {
- scadaMapper.insertMonitoring(scada);
- log.info("无实时数据,进行新增{}", scada);
- } else {
- scadaMapper.updateMonitoring(scada);
- log.info("有实时数据,进行更新{}", scada);
- }
-
- insertData(scada);
- }
- }
- }
-
- public static List<Date> findDates(Date start, Date end, Integer type) {
- Calendar s = Calendar.getInstance();
- s.setTime(start);
-
- List<Date> dates = new ArrayList<>();
- dates.add(start);
- dates.add(end);
- while (end.getTime() > s.getTime().getTime()) {
- if (type == 1) {
- s.add(Calendar.DAY_OF_MONTH, 1);
- } else if (type == 2) {
- s.add(Calendar.MONTH, 1);
- } else if (type == 3) {
- s.add(Calendar.DAY_OF_YEAR, 1);
- } else if (type == 0) {
- s.add(Calendar.HOUR_OF_DAY, 1);
- } else if (type == 4) {
- s.add(Calendar.MINUTE, 5);
- }
- dates.add(s.getTime());
- }
- return dates;
- }
-
- public void syncSave(Scada data) {
- if (ObjectUtils.isEmpty(data)) {
- throw new RuntimeException("参数为空");
- }
- System.out.println("主线程 =====> 开始 =====> " + System.currentTimeMillis());
- ExecutorService executorService = Executors.newSingleThreadExecutor();
- executorService.submit(() -> {
- System.out.println("异步线程 =====> 开始 =====> " + System.currentTimeMillis());
- try {
- Thread.sleep(5000);
- syncScadaData(data);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("异步线程 =====> 结束 =====> " + System.currentTimeMillis());
- });
- executorService.shutdown();
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- System.out.println("主线程 =====> 结束 =====> " + System.currentTimeMillis());
- }
- private void syncScadaData(Scada scada) {
- log.info("获取到同步scada信息数据:-----{}-----", scada.toString());
- if (!ObjectUtils.isEmpty(scada)) {
-
- log.info("检测是否为系统创建的指标");
- Integer selectCount = allocationMapper.selectCount(new QueryWrapper<Allocation>()
- .eq("VARIABLE_CODE", scada.getCode()));
- if (selectCount == 0) {
- log.info("数据不存在指标绑定配置,无法进行同步更新存储");
- throw new RuntimeException("数据不存在指标绑定配置,无法进行同步更新存储");
- }
-
- scadaMapper.insert(scada);
-
- String tableName = createMonths(scada.getScadaTime() == null ? new Date() : scada.getScadaTime());
- log.info("创建月份表成功:-----{}-----", tableName);
-
- if (CollectionUtils.isEmpty(scadaMapper.selectHistoryById(tableName, scada.getId()))) {
- log.info("scada数据不存在月份表中,正在执行新增数据");
- scadaMapper.insertByOne(scada, tableName);
- log.info("新增数据成功:-----{}-----", scada);
- }
-
- sendNotice(scada);
- }
- }
-
- @SneakyThrows
- @Async
- void sendNotice(Scada scada) {
- Thread.sleep(5000);
- scada = getScada(scada);
- log.info("获取到同步scada信息数据:-----{}-----", scada.toString());
- if (!StringUtils.hasText(scada.getValue())) {
- logger.info("数据:{},存在value值为空,报警流程结束", scada);
- return;
- }
- QueryWrapper<Allocation> allocationQueryWrapper = new QueryWrapper<>();
- allocationQueryWrapper.eq("VARIABLE_CODE", scada.getCode())
- .eq("IS_ALARM", "1");
- List<Allocation> allocations = allocationMapper.selectList(allocationQueryWrapper);
- if (!CollectionUtils.isEmpty(allocations)) {
- for (Allocation allocation : allocations) {
- if (!StringUtils.hasText(allocation.getIsAlarm()) || allocation.getIsAlarm().equals("0")) {
- logger.info("未设置报警开关,正在退出这次匹配");
- break;
- }
- List<Long> reports = getReportIds(Collections.singletonList(allocation));
- QueryWrapper<ScadaReport> scadaReportQueryWrapper = new QueryWrapper<>();
- scadaReportQueryWrapper.eq("IS_DEL", FlowConstant.SHORT_ZERO)
- .in("ID", reports);
- List<ScadaReport> scadaReports = reportMapper.selectList(scadaReportQueryWrapper);
- if (!CollectionUtils.isEmpty(scadaReports)) {
- logger.info("匹配到告警模版...");
-
- BigDecimal scadaVal = new BigDecimal(scada.getValue());
- for (ScadaReport scadaReport : scadaReports) {
- BigDecimal upVal = new BigDecimal(scadaReport.getReportUpper());
- BigDecimal downVal = new BigDecimal(scadaReport.getReportLower());
-
- if (scadaVal.compareTo(upVal) > 0 || scadaVal.compareTo(downVal) < 0) {
- MessagepushW messagepush = new MessagepushW();
-
- messagepush.setTopic(MessageTopicEnum.REPORT_MSG.getTopic());
- messagepush.setMessage(createMsg(scadaReport.getMsgTemplate(), scadaReport));
- messagepush.setType("8");
- messagepush.setTableName(MessageTopicEnum.REPORT_MSG.getTableName());
- messagepush.setCreateTime(scada.getScadaTime());
- sendTidingsUtil.sendMsg(messagepush, scadaReport.getLiaisonPeople());
- logger.info("发送报警消息:{}", messagepush);
-
- saveReportListData(scada, scadaReports, allocations);
- logger.info("记录到报警列表:{}", scada);
- }
- }
- log.info("--------报警处理结束----------");
- } else {
- log.info("--------未匹配到报警模版---报警处理结束-------");
- }
- }
- }
- }
-
- @SneakyThrows
- @Async
- void sendNotice(Scada scada, String date) {
- if (!StringUtils.hasText(scada.getValue())) {
- logger.info("数据:{},存在value值为空,报警流程结束", scada);
- return;
- }
- QueryWrapper<Allocation> allocationQueryWrapper = new QueryWrapper<>();
- allocationQueryWrapper.eq("VARIABLE_CODE", scada.getCode())
- .eq("IS_ALARM", "1");
- List<Allocation> allocations = allocationMapper.selectList(allocationQueryWrapper);
- if (!CollectionUtils.isEmpty(allocations)) {
- for (Allocation allocation : allocations) {
- if (!StringUtils.hasText(allocation.getIsAlarm()) || allocation.getIsAlarm().equals("0")) {
- logger.info("未设置报警开关,正在退出这次匹配");
- break;
- }
- List<Long> reports = getReportIds(Collections.singletonList(allocation));
- QueryWrapper<ScadaReport> scadaReportQueryWrapper = new QueryWrapper<>();
- scadaReportQueryWrapper.eq("IS_DEL", FlowConstant.SHORT_ZERO)
- .in("ID", reports);
- List<ScadaReport> scadaReports = reportMapper.selectList(scadaReportQueryWrapper);
- if (!CollectionUtils.isEmpty(scadaReports)) {
-
- BigDecimal scadaVal = new BigDecimal(scada.getValue());
- for (ScadaReport scadaReport : scadaReports) {
- BigDecimal upVal = new BigDecimal(scadaReport.getReportUpper());
- BigDecimal downVal = new BigDecimal(scadaReport.getReportLower());
-
- if (scadaVal.compareTo(upVal) > 0 || scadaVal.compareTo(downVal) < 0) {
- MessagepushW messagepush = new MessagepushW();
-
- messagepush.setTopic(MessageTopicEnum.REPORT_MSG.getTopic());
- messagepush.setMessage(createMsg(scadaReport.getMsgTemplate(), scadaReport));
- messagepush.setType("8");
- messagepush.setTableName(MessageTopicEnum.REPORT_MSG.getTableName());
- messagepush.setCreateTime(scada.getScadaTime());
- sendTidingsUtil.sendMsg(messagepush, scadaReport.getLiaisonPeople());
- logger.info("发送报警消息:{}", messagepush);
-
- saveReportListData(scada, scadaReports, allocations);
- }
- }
- log.info("--------报警处理结束----------");
- } else {
- log.info("--------未匹配到报警模版---报警处理结束-------");
- }
- }
- }
- }
- private void saveReportListData(Scada scada, List<ScadaReport> scadaReports, List<Allocation> allocations) {
- TfScadaReportList tfScadaReportList = new TfScadaReportList();
- BeanUtils.copyProperties(scada, tfScadaReportList);
- List<String> levelTitles = scadaReports.stream().filter(scadaReport -> StringUtils.hasText(scadaReport.getReportLevel()))
- .map(ScadaReport::getReportLevel).collect(Collectors.toList());
- if (!CollectionUtils.isEmpty(levelTitles)) {
- String join = org.apache.commons.lang3.StringUtils.join(levelTitles);
- tfScadaReportList.setReportLevel(join);
- }
- List<String> reportUppers = scadaReports.stream().filter(scadaReport -> StringUtils.hasText(scadaReport.getReportUpper()))
- .map(ScadaReport::getReportUpper).collect(Collectors.toList());
- if (!CollectionUtils.isEmpty(reportUppers)) {
- String join = org.apache.commons.lang3.StringUtils.join(reportUppers);
- tfScadaReportList.setReportUpper(join);
- }
- List<String> reportLowers = scadaReports.stream().filter(scadaReport -> StringUtils.hasText(scadaReport.getReportLower()))
- .map(ScadaReport::getReportLower).collect(Collectors.toList());
- if (!CollectionUtils.isEmpty(reportLowers)) {
- String join = org.apache.commons.lang3.StringUtils.join(reportLowers);
- tfScadaReportList.setReportLower(join);
- }
- List<String> displayNames = allocations.stream().filter(scadaReport -> StringUtils.hasText(scadaReport.getDisplayName()))
- .map(Allocation::getDisplayName).collect(Collectors.toList());
- if (!CollectionUtils.isEmpty(displayNames)) {
- String join = org.apache.commons.lang3.StringUtils.join(displayNames);
- tfScadaReportList.setDisplayName(join);
- }
- tfScadaReportList.setStatus("0");
- tfScadaReportListService.insert(tfScadaReportList);
- log.info("添加列表报警数据成功:{}", tfScadaReportList);
- }
-
- public String createMsg(String template, ScadaReport scadaReport) {
- if (template.contains("#TIME#")) {
- String date = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
- template = template.replaceAll("#TIME#", date);
- }
- if (template.contains("#YHXM#")) {
- String user = scadaReportService.getUser(scadaReport.getLiaisonPeople());
- template = template.replace(user, "#YHXM#");
- }
- if (template.contains("#LXDH#")) {
- template = template.replace(scadaReport.getLiaisonPhone(), "#LXDH#");
- }
- return template;
- }
-
- private List<Long> getReportIds(List<Allocation> allocations) {
- List<Long> reports = allocations.stream().filter(allocation -> StringUtils.hasText(allocation.getReportId()))
- .map(allocation -> {
- if (allocation.getReportId().contains(",")) {
- String[] reportIds = allocation.getReportId().split(",");
- for (String reportId : reportIds) {
- return Long.parseLong(reportId);
- }
- } else {
- return Long.parseLong(allocation.getReportId());
- }
- return null;
- }).collect(Collectors.toList());
- return reports;
- }
-
- public static Set<Long> getReportIdSets(List<Allocation> allocations) {
- Set<Long> reports = allocations.stream().filter(allocation -> StringUtils.hasText(allocation.getReportId()))
- .map(allocation -> {
- if (allocation.getReportId().contains(",")) {
- String[] reportIds = allocation.getReportId().split(",");
- for (String reportId : reportIds) {
- return Long.parseLong(reportId);
- }
- } else {
- return Long.parseLong(allocation.getReportId());
- }
- return null;
- }).collect(Collectors.toSet());
- return reports;
- }
- @Scheduled(cron = "0 0/5 * * * ? ")
- @Transactional(rollbackFor = Exception.class)
- public void automaticSendNetCumulativeFlow() {
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(new Date());
- Date endTime = calendar.getTime();
- calendar.add(Calendar.MINUTE, -5);
- Date startTime = calendar.getTime();
- sendNetCumulativeFlow(startTime, endTime);
- }
- @Override
- @Transactional(rollbackFor = Exception.class)
- public void manualSendNetCumulativeFlow(Date sDate, Date eDate) {
- log.info("手动同步scada正反数据");
- sendNetCumulativeFlow(sDate, eDate);
- }
- private void sendNetCumulativeFlow(Date sDate, Date eDate) {
- long l = System.currentTimeMillis();
- List<Scada> scadaList = new ArrayList<>();
-
- logger.info("同步scada正反数据时间区间: {}", DateUtil.format(sDate, "yyyy-MM-dd HH:mm:ss") + "-" + DateUtil.format(eDate, "yyyy-MM-dd HH:mm:ss"));
- List<NetCumulativeFlow> netCumulativeFlow = scadaMapper.getNetCumulativeFlow(sDate, eDate);
- logger.info("同步scada正反数据获取大小: {}", netCumulativeFlow.size());
-
- Map<Long, List<NetCumulativeFlow>> longListMap = netCumulativeFlow.stream().collect(Collectors.groupingBy(NetCumulativeFlow::getDeviceId));
-
- Map<Long, Allocation> newAllocation = newAllocation(longListMap.keySet());
- logger.info("同步scada虚拟指标: {}", JSON.toJSONString(newAllocation));
-
- longListMap.forEach((k, v) -> {
- Allocation allocation = newAllocation.get(k);
-
- Map<Date, List<NetCumulativeFlow>> dateListMap = v.stream().collect(Collectors.groupingBy(NetCumulativeFlow::getScadaTime));
- dateListMap.forEach((n, m) -> {
- AtomicReference<BigDecimal> value = new AtomicReference<>(BigDecimal.ZERO);
- m.forEach(i -> {
- BigDecimal bigDecimal = BigDecimal.valueOf(Double.parseDouble(i.getValue() == null ? "0" : i.getValue()));
- value.set(value.get().subtract(bigDecimal).abs());
- });
- Scada scada = new Scada();
- BigDecimal bigDecimal = value.get();
- scada.setCode(allocation.getVariableCode());
- scada.setScadaTime(n);
- scada.setValue(value.get().toString());
-
- if (null != bigDecimal && bigDecimal.compareTo(BigDecimal.ZERO) != 0) {
- scadaList.add(scada);
- }
- });
- });
- logger.info("同步scada新增scada历史数据大小: {}", scadaList.size());
-
- if (scadaList.size() > 0) {
-
- this.remove(new QueryWrapper<Scada>().lambda().like(Scada::getCode, ".JLJ").ge(Scada::getScadaTime, sDate).le(Scada::getScadaTime,eDate));
- scadaMonitorService.remove(new QueryWrapper<ScadaMonitor>().lambda().like(ScadaMonitor::getCode, ".JLJ"));
- this.saveBatch(scadaList,2000);
-
- Map<String, List<Scada>> collect = scadaList.stream().collect(Collectors.groupingBy(Scada::getCode));
- List<ScadaMonitor> scadaMonitorList = new ArrayList<>();
- collect.forEach((k,v)->{
- Optional<Scada> max = v.stream().max(Comparator.comparingDouble(d->d.getScadaTime().getTime()));
- Scada scada = max.get();
- ScadaMonitor scadaMonitor = new ScadaMonitor(scada.getCode(),scada.getValue(),scada.getScadaTime());
- scadaMonitorList.add(scadaMonitor);
- });
- logger.info("同步scada新增scada实时数据: {}", JSON.toJSONString(scadaMonitorList));
- scadaMonitorService.saveBatch(scadaMonitorList);
- }
- long l1 = System.currentTimeMillis();
- log.info("同步scada正反数据,用时{}mm", l1 - l);
- }
-
- private Map<Long, Allocation> newAllocation(Set<Long> deviceIdList) {
-
- Set<Long> xnDeviceIdSet = new HashSet<>();
-
- List<Allocation> allocations = allocationMapper.selectList(new QueryWrapper<Allocation>().lambda().eq(Allocation::getType, "19"));
- if (null != allocations && allocations.size() > 0) {
-
- Map<Long, List<Allocation>> xnCodeMap = allocations.stream().collect(Collectors.groupingBy(Allocation::getDeviceId));
- Set<Long> collect = deviceIdList.stream().filter(deviceId -> !xnCodeMap.containsKey(deviceId)).collect(Collectors.toSet());
- xnDeviceIdSet.addAll(collect);
- } else {
-
- xnDeviceIdSet.addAll(deviceIdList);
- }
-
- List<Allocation> newAllocationList = new ArrayList<>();
- if (xnDeviceIdSet.size() > 0) {
-
- List<Allocation> oldAllocationList = allocationMapper.selectList(new QueryWrapper<Allocation>().lambda().in(Allocation::getDeviceId, xnDeviceIdSet));
-
- Map<Long, List<Allocation>> mapAllocation = oldAllocationList.stream().collect(Collectors.groupingBy(Allocation::getDeviceId));
- mapAllocation.forEach((k, v) -> {
-
- Map<String, Allocation> allocationMap = v.stream().collect(Collectors.toMap(Allocation::getType, t -> t, (key1, key2) -> key2));
- Allocation allocation;
- if (allocationMap.containsKey("17")) {
- allocation = allocationMap.get("17");
- } else {
- allocation = allocationMap.get("18");
- }
- allocation.setId(null);
- allocation.setVariableCode(allocation.getVariableCode() + ".JLJ");
- allocation.setVariableName(allocation.getVariableName() + ".净累计");
- allocation.setDisplayName(allocation.getDisplayName() + ".净累计");
- allocation.setType("19");
- newAllocationList.add(allocation);
- });
-
-
- if (newAllocationList.size() > 0) {
- allocationService.saveBatch(newAllocationList);
- List<Dmatable> dmaTableList = newAllocationList.stream().map(v -> new Dmatable(v.getDeviceId(), Double.parseDouble("0"))).collect(Collectors.toList());
- dmatableService.saveBatch(dmaTableList);
- }
- }
-
- if (null != allocations && allocations.size() > 0) {
- newAllocationList.addAll(allocations);
- }
- return newAllocationList.stream().collect(Collectors.toMap(Allocation::getDeviceId, t -> t, (key1, key2) -> key2));
- }
-
- public static boolean isNumber(String str) {
- Matcher m = pattern.matcher(str);
- return m.matches();
- }
- }
|