feat(harmonic): 新增移动端线路详情功能并优化波形数据处理

- 添加 AppLineDetailVo 数据传输对象,支持移动端线路详情展示
- 增加 report 服务中的 buildHarmonic 相关方法重构,支持移动端线路详情查询
- 优化波形数据处理逻辑,新增波形数据抽点和裁剪功能,减少移动端数据传输量
- 修改 CommonStatisticalQueryParam 参数类,增加数据模型字段和电度事件类型支持
- 调整统计查询相关接口,支持全量和增量查询模式
- 移除 CredentialReqDTO 类,清理相关依赖
- 优化 CsAppReportServiceImpl 中的越限描述构建逻辑,使用时间转换工具
- 更新数据查询相关 Mapper XML 文件,调整数据过滤条件
- 修改设备用户服务实现,完善当前工程数据显示逻辑
- 优化 CsEquipmentDeliveryServiceImpl 中的数据集添加逻辑,支持电度数据类型
- 重构 CsEventController 和相关服务类,支持移动端波形数据分析
- 添加 Nacos 配置参数控制波形数据抽点和间隔区域处理行为
This commit is contained in:
xy
2026-06-03 10:22:18 +08:00
parent a6f424025a
commit cf691db0a6
39 changed files with 1393 additions and 900 deletions

View File

@@ -1,11 +1,7 @@
package com.njcn.csdevice.api;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.csdevice.api.fallback.CsLineClientFallbackFactory;
import com.njcn.csdevice.pojo.dto.CsLineDTO;
import com.njcn.csdevice.pojo.param.CsLineParam;

View File

@@ -1,23 +0,0 @@
package com.njcn.csdevice.api;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.csdevice.api.fallback.SmsSendClientFallbackFactory;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author xy
*/
@FeignClient(value = ServerInfo.CS_DEVICE_BOOT, path = "/sms", fallbackFactory = SmsSendClientFallbackFactory.class,contextId = "sms")
public interface SmsSendFeignClient {
@PostMapping("/send/simple")
@ApiOperation("发送短信(简化参数)")
HttpResult<String> sendSmsSimple(@RequestParam("receiver") String receiver
, @RequestParam("content") String content
, @RequestParam("messageType") String messageType);
}

View File

@@ -1,34 +0,0 @@
package com.njcn.csdevice.api.fallback;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.csdevice.api.SmsSendFeignClient;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @author xy
*/
@Slf4j
@Component
public class SmsSendClientFallbackFactory implements FallbackFactory<SmsSendFeignClient> {
@Override
public SmsSendFeignClient create(Throwable cause) {
//判断抛出异常是否为解码器抛出的业务异常
Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
if (cause.getCause() instanceof BusinessException) {
BusinessException businessException = (BusinessException) cause.getCause();
}
Enum<?> finalExceptionEnum = exceptionEnum;
return new SmsSendFeignClient() {
@Override
public HttpResult<String> sendSmsSimple(String receiver, String content, String messageType) {
log.error("{}异常,降级处理,异常为:{}","发送短信(简化参数)数据异常",cause.toString());
throw new BusinessException(finalExceptionEnum);
}
};
}
}

View File

@@ -21,4 +21,7 @@ public class IcdBzParam implements Serializable {
@ApiModelProperty("结束时间")
private String endTime;
@ApiModelProperty("补召类型 0:稳态 1:暂态事件 2:波形)")
private Integer bzType;
}

View File

@@ -1,35 +0,0 @@
package com.njcn.csdevice.pojo.dto;
/**
* @author caozehui
* @data 2026-03-31
*/
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
/**
* 系统凭证请求 DTO
*
* @author msgpush
*/
@Data
public class CredentialReqDTO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 上游系统名称
*/
@NotEmpty(message = "上游系统名称不能为空")
private String systemName;
/**
* 密钥(用于生成凭证)
*/
@NotEmpty(message = "密钥不能为空")
private String secretKey;
}

View File

@@ -1,45 +0,0 @@
package com.njcn.csdevice.pojo.po;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* @author xy
*/
@Data
@TableName("cs_sms_send_record")
public class CsSmsSendRecord implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.ASSIGN_ID)
private String id;
private String receiver;
private String content;
private String messageType;
private String credentialToken;
private Integer sendStatus;
@TableField(updateStrategy = FieldStrategy.IGNORED)
private String failReason;
private Integer retryCount;
private Integer maxRetry;
private Long responseTime;
private LocalDateTime sendTime;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}

View File

@@ -71,4 +71,7 @@ public class DevCountVO implements Serializable {
@ApiModelProperty(value = "反馈数")
private Integer feedBackCount = 0;
@ApiModelProperty(value = "当前工程监测点数")
private Integer lineCount = 0;
}

View File

@@ -1,40 +0,0 @@
package com.njcn.csdevice.pojo.vo;
import cn.hutool.core.lang.RegexPool;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
/**
* @author caozehui
* @data 2026-02-27
*/
@Data
@Schema(description = "管理后台 - 消息记录发送 Request VO")
public class MessageRecordReqVO {
private String channel;
@Schema(description = "消息类型", example = "verify_code/order_notify/marketing/system_notify")
@NotBlank(message = "消息类型不能为空")
private String messageType;
@Schema(description = "接收者")
@NotBlank(message = "接收者不能为空")
@Pattern(regexp = RegexPool.EMAIL + "|" + RegexPool.MOBILE, message = "必须是有效的邮箱或手机号格式")
private String receiver;
@Schema(description = "标题")
private String title;
@Schema(description = "消息内容")
private String content;
@Schema(description = "模板编码")
private String templateCode;
@Schema(description = "模板参数")
private String templateParams;
}

View File

@@ -19,7 +19,6 @@ import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.List;
@@ -101,7 +100,6 @@ public class CsDataArrayController extends BaseController {
@PostMapping("/findListByParam")
@ApiOperation("根据条件查询详细数据")
@ApiImplicitParam(name = "param", value = "参数集合", required = true)
@ApiIgnore
public HttpResult<List<CsDataArray>> findListByParam(@RequestBody DataArrayParam param){
String methodDescribe = getMethodDescribe("findListByParam");
List<CsDataArray> list = csDataArrayService.findListByParam(param);

View File

@@ -1,77 +0,0 @@
package com.njcn.csdevice.controller.message;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.csdevice.pojo.vo.MessageRecordReqVO;
import com.njcn.csdevice.service.ISmsSendService;
import com.njcn.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
/**
* @author xy
*/
@Slf4j
@RestController
@RequestMapping("/sms")
@Api(tags = "短信发送管理")
@AllArgsConstructor
public class SmsSendController extends BaseController {
private final ISmsSendService smsSendService;
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/send")
@ApiOperation("发送短信(同步,包含重试)")
public HttpResult<String> sendSms(@RequestBody MessageRecordReqVO vo) {
String methodDescribe = getMethodDescribe("sendSms");
try {
smsSendService.sendSmsWithRetry(vo);
return HttpResultUtil.assembleCommonResponseResult(
CommonResponseEnum.SUCCESS,
"短信发送成功",
methodDescribe
);
} catch (Exception e) {
log.error("短信发送失败", e);
return HttpResultUtil.assembleCommonResponseResult(
CommonResponseEnum.FAIL,
e.getMessage(),
methodDescribe
);
}
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/send/simple")
@ApiOperation("发送短信(简化参数)")
public HttpResult<String> sendSmsSimple(
@RequestParam String receiver,
@RequestParam String content,
@RequestParam(defaultValue = "verify_code") String messageType) {
String methodDescribe = getMethodDescribe("sendSmsSimple");
try {
smsSendService.sendSmsWithRetry(receiver, content, messageType);
return HttpResultUtil.assembleCommonResponseResult(
CommonResponseEnum.SUCCESS,
"短信发送成功",
methodDescribe
);
} catch (Exception e) {
log.error("短信发送失败", e);
return HttpResultUtil.assembleCommonResponseResult(
CommonResponseEnum.FAIL,
e.getMessage(),
methodDescribe
);
}
}
}

View File

@@ -1,7 +0,0 @@
package com.njcn.csdevice.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njcn.csdevice.pojo.po.CsSmsSendRecord;
public interface CsSmsSendRecordMapper extends BaseMapper<CsSmsSendRecord> {
}

View File

@@ -105,7 +105,6 @@
t0.ndid = #{param.id}
and t1.did = #{param.did}
and t3.cl_dev = #{param.cldId}
and (t3.data_type = 'Stat' or t3.data_type is NULL)
and t3.idx = #{param.idx}
and t4.stat_method = #{param.statMethod}
order by t4.sort

View File

@@ -14,7 +14,8 @@
where
pid = #{modelId}
and cl_dev = #{clDev}
and (data_type = 'Stat' or data_type IS NULL)
-- and (data_type = 'Stat' or data_type IS NULL)
and store_flag = 1
order by type,cl_dev
</select>

View File

@@ -1,12 +0,0 @@
package com.njcn.csdevice.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.njcn.csdevice.pojo.po.CsSmsSendRecord;
import com.njcn.csdevice.pojo.vo.MessageRecordReqVO;
public interface ISmsSendService extends IService<CsSmsSendRecord> {
void sendSmsWithRetry(String receiver, String content, String messageType);
void sendSmsWithRetry(MessageRecordReqVO messageRecordReqVO);
}

View File

@@ -35,7 +35,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static java.util.Objects.isNull;
@@ -235,6 +234,7 @@ public class CsDeviceUserPOServiceImpl extends ServiceImpl<CsDeviceUserPOMapper,
}
//note 当前工程数据
vo.setLineCount(0);
//当前工程id
vo.setCurrentId(id);
//设备集合
@@ -287,6 +287,7 @@ public class CsDeviceUserPOServiceImpl extends ServiceImpl<CsDeviceUserPOMapper,
}
//获取未读事件数量
if (CollectionUtil.isNotEmpty(currentLineIds)) {
vo.setLineCount(currentLineIds.size());
CsEventUserQueryParam param1 = new CsEventUserQueryParam();
param1.setUserId(RequestUtil.getUserIndex());
param1.setStartTime(PublicDataUtils.calculateMonthStart(time));

View File

@@ -528,6 +528,8 @@ public class CsEquipmentDeliveryServiceImpl extends ServiceImpl<CsEquipmentDeliv
if (strings.contains(AppRoleEnum.ENGINEERING_USER.getCode()) || strings.contains(AppRoleEnum.OPERATION_MANAGER.getCode()) || strings.contains(AppRoleEnum.ROOT.getCode())) {
addDataSet(dataSetList, item, "模块数据", "moduleData");
}
} else {
addDataSet(dataSetList, item, "电度数据", "kilowattHour");
}
if (isPortableDevice) {
// 便携式设备特有的数据集

View File

@@ -65,11 +65,8 @@ import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
@@ -321,7 +318,7 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
if(CollectionUtil.isNotEmpty(commonStatisticalQueryParam.getList())){
for (CommonStatisticalQueryParam param : commonStatisticalQueryParam.getList()){
List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(param.getStatisticalId()).getData();
List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(param.getStatisticalId())).getData();
eleEpdPqds.forEach(epdPqd->{
List<CommonQueryParam> commonQueryParams = finalCsLinePOList.stream().map(temp -> {
CommonQueryParam commonQueryParam = new CommonQueryParam();
@@ -573,23 +570,165 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
}
});
return csEventVOPage;
} else if ("4".equals(type)) {
formatQueryParamList(commonStatisticalQueryParam);
List<ThdDataVO> result = new ArrayList<>();
List<CsLinePO> finalCsLinePOList = csLineFeignClient.queryLineById(Collections.singletonList(commonStatisticalQueryParam.getLineId())).getData();
CsDataSet csDataSet = csDataSetMapper.selectOne(new LambdaQueryWrapper<CsDataSet>().eq(CsDataSet::getId, finalCsLinePOList.get(0).getDataSetId()));
if (Objects.isNull(csDataSet) || StrUtil.isBlank(csDataSet.getDataLevel())) {
throw new BusinessException("当前测点数据集主要信息缺失,请联系管理员排查(测点表里面数据集id缺失)");
}
Double ct = finalCsLinePOList.get(0).getCtRatio() / (Objects.isNull(finalCsLinePOList.get(0).getCt2Ratio()) ? 1.0 : finalCsLinePOList.get(0).getCt2Ratio());
Double pt = finalCsLinePOList.get(0).getPtRatio() / (Objects.isNull(finalCsLinePOList.get(0).getPt2Ratio()) ? 1.0 : finalCsLinePOList.get(0).getPt2Ratio());
if (CollectionUtil.isNotEmpty(commonStatisticalQueryParam.getList())) {
for (CommonStatisticalQueryParam param : commonStatisticalQueryParam.getList()) {
List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(param.getStatisticalId())).getData();
eleEpdPqds.forEach(epdPqd -> {
List<CommonQueryParam> commonQueryParams = finalCsLinePOList.stream().map(temp -> {
CommonQueryParam commonQueryParam = new CommonQueryParam();
commonQueryParam.setLineId(temp.getLineId());
commonQueryParam.setTableName(influxDbParamUtil.getTableNameByClassId(epdPqd.getClassId()));
if (epdPqd.getName() == null || epdPqd.getName().isEmpty()) {
commonQueryParam.setColumnName(epdPqd.getName() + (StringUtils.isEmpty(param.getFrequency()) ? "" : "_" + param.getFrequency()));
} else {
commonQueryParam.setColumnName(epdPqd.getOtherName() + (StringUtils.isEmpty(param.getFrequency()) ? "" : "_" + param.getFrequency()));
}
commonQueryParam.setPhasic(epdPqd.getPhase());
commonQueryParam.setStartTime(DateUtil.format(DateUtil.parse(commonStatisticalQueryParam.getStartTime(), DatePattern.NORM_DATE_PATTERN), DatePattern.NORM_DATETIME_PATTERN));
commonQueryParam.setEndTime(DateUtil.format(DateUtil.endOfDay(DateUtil.parse(commonStatisticalQueryParam.getEndTime(), DatePattern.NORM_DATE_PATTERN)), DatePattern.NORM_DATETIME_PATTERN));
commonQueryParam.setClDid(influxDbParamUtil.getClDidByLineId(temp.getLineId()));
return commonQueryParam;
}).collect(Collectors.toList());
List<StatisticalDataDTO> deviceRtData;
if (commonStatisticalQueryParam.getDataModel() == 0) {
deviceRtData = commonService.getDeviceRtDataByTime(commonQueryParams);
} else {
deviceRtData = commonService.getDianDuData(commonQueryParams);
}
List<ThdDataVO> collect1 = deviceRtData.stream().map(temp -> {
String unit;
ThdDataVO vo = new ThdDataVO();
vo.setLineId(temp.getLineId());
vo.setPhase(Objects.equals("T", temp.getPhaseType()) ? null : temp.getPhaseType());
String position = finalCsLinePOList.stream().filter(csLinePO -> Objects.equals(csLinePO.getLineId(), vo.getLineId())).collect(Collectors.toList()).get(0).getPosition();
vo.setPosition(position);
vo.setTime(temp.getTime());
vo.setStatMethod(temp.getValueType());
vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
if (temp.getValue() != null) {
double re = 0;
if (Objects.equals("Primary", commonStatisticalQueryParam.getDataLevel())) {
if (Objects.equals("Primary", csDataSet.getDataLevel())) {
if (HarmonicConstant.POWER_LIST.contains(epdPqd.getShowName())) {
re = Objects.isNull(temp.getValue()) ? 3.14159 : Double.parseDouble(df.format(temp.getValue()));
vo.setStatisticalData(re);
unit = epdPqd.getUnit();
} else {
vo.setStatisticalData(Objects.isNull(temp.getValue()) ? 3.14159 : Double.parseDouble(df.format(temp.getValue())));
unit = epdPqd.getUnit();
}
} else {
if (Objects.nonNull(epdPqd.getPrimaryFormula())) {
switch (epdPqd.getPrimaryFormula()) {
case "*PT":
re = temp.getValue() * pt;
unit = epdPqd.getUnit();
break;
case "*CT":
re = temp.getValue() * ct;
unit = epdPqd.getUnit();
break;
case "*PT*CT":
re = temp.getValue() * pt * ct;
unit = epdPqd.getUnit();
break;
default:
re = temp.getValue();
unit = epdPqd.getUnit();
break;
}
vo.setStatisticalData(Double.valueOf(df.format(re)));
} else {
re = temp.getValue();
unit = epdPqd.getUnit();
vo.setStatisticalData(Double.valueOf(df.format(re)));
}
}
} else {
if (Objects.equals("Primary", csDataSet.getDataLevel())) {
if (Objects.nonNull(epdPqd.getPrimaryFormula())) {
switch (epdPqd.getPrimaryFormula()) {
case "*PT":
re = temp.getValue() / pt;
break;
case "*CT":
re = temp.getValue() / ct;
break;
case "*PT*CT":
re = temp.getValue() / pt / ct;
break;
default:
re = temp.getValue();
break;
}
vo.setStatisticalData(Double.valueOf(df.format(re)));
} else {
re = temp.getValue();
vo.setStatisticalData(Double.valueOf(df.format(re)));
}
} else {
vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
}
unit = epdPqd.getUnit();
}
} else {
vo.setStatisticalData(null);
if (Objects.equals("Primary", commonStatisticalQueryParam.getDataLevel())) {
if (Objects.equals("Primary", csDataSet.getDataLevel())) {
unit = epdPqd.getUnit();
} else {
if (Objects.nonNull(epdPqd.getPrimaryFormula())) {
switch (epdPqd.getPrimaryFormula()) {
case "*PT":
unit = epdPqd.getUnit();
break;
case "*CT":
unit = epdPqd.getUnit();
break;
case "*PT*CT":
unit = epdPqd.getUnit();
break;
default:
unit = epdPqd.getUnit();
break;
}
} else {
unit = epdPqd.getUnit();
}
}
} else {
unit = epdPqd.getUnit();
}
}
vo.setUnit(unit);
vo.setStatisticalIndex(epdPqd.getId());
vo.setStatisticalName(epdPqd.getName());
vo.setAnotherName(epdPqd.getShowName());
return vo;
}).collect(Collectors.toList());
result.addAll(collect1);
});
}
}
return result;
}
return null;
}
public static List<Instant> getTimeInstants(String startDateStr, String endDateStr, long interval, ChronoUnit unit, ZoneId zone) {
List<Instant> instants = new ArrayList<>();
LocalDate startDate = LocalDate.parse(startDateStr, DATE_FORMATTER);
LocalDate endDate = LocalDate.parse(endDateStr, DATE_FORMATTER);
ZonedDateTime current = startDate.atStartOfDay(zone);
ZonedDateTime endDateTime = endDate.plusDays(1).atStartOfDay(zone);
while (current.isBefore(endDateTime)) {
instants.add(current.toInstant().plusSeconds(zone.getRules().getOffset(current.toInstant()).getTotalSeconds()));
current = current.plus(interval, unit);
}
return instants;
}
private void formatQueryParamList(CommonStatisticalQueryParam commonStatisticalQueryParam){
List<CommonStatisticalQueryParam> list = new ArrayList<>();
if(commonStatisticalQueryParam.getList() != null && commonStatisticalQueryParam.getList().size() > 0){
@@ -729,7 +868,7 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
List<CsLinePO> finalCsLinePOList = csLineFeignClient.queryLineById(Arrays.asList(commonStatisticalQueryParam.getLineId())).getData();
if(commonStatisticalQueryParam.getList() != null && commonStatisticalQueryParam.getList().size() > 0){
for (CommonStatisticalQueryParam param : commonStatisticalQueryParam.getList()){
List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(param.getStatisticalId()).getData();
List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(param.getStatisticalId())).getData();
ThdDataTdVO.ThdDataSpectrumVOData thdDataSpectrumVOData = new ThdDataTdVO.ThdDataSpectrumVOData();
List<ThdDataVO> result = new ArrayList();
eleEpdPqds.forEach(epdPqd->{
@@ -835,7 +974,7 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
Double pt = finalCsLinePO.getPtRatio() / (Objects.isNull(finalCsLinePO.getPt2Ratio())?1.0:finalCsLinePO.getPt2Ratio());
if(CollectionUtil.isNotEmpty(trendDataQueryParam.getList())) {
for (TrendDataQueryParam param : trendDataQueryParam.getList()) {
List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(param.getStatisticalId()).getData();
List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(param.getStatisticalId())).getData();
for (EleEpdPqd epdPqd : eleEpdPqds) {
CommonQueryParam commonQueryParam = new CommonQueryParam();
commonQueryParam.setLineId(finalCsLinePO.getLineId());
@@ -992,7 +1131,7 @@ public class CsGroupServiceImpl extends ServiceImpl<CsGroupMapper, CsGroup> impl
if(CollectionUtil.isNotEmpty(fittingDataQueryParam.getList())) {
for (FittingDataQueryParam param : fittingDataQueryParam.getList()) {
String dictCode = dictTreeFeignClient.queryById(param.getStatisticalId()).getData().getCode();
List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(param.getStatisticalId()).getData();
List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(param.getStatisticalId())).getData();
List<ThdDataVO> dataList = new ArrayList<>();
for (EleEpdPqd epdPqd : eleEpdPqds) {
CommonQueryParam commonQueryParam = new CommonQueryParam();

View File

@@ -490,8 +490,10 @@ public class CsLinePOServiceImpl extends ServiceImpl<CsLinePOMapper, CsLinePO> i
public List<CsLinePO> getLineList(CsLinePO param) {
List<String> keywordsLineIds = new ArrayList<>();
List<CsLinePO> poList = getSimpleLine();
if (CollUtil.isNotEmpty(poList)) {
if (CollUtil.isNotEmpty(poList) && !poList.isEmpty()) {
keywordsLineIds = poList.stream().map(CsLinePO::getLineId).collect(Collectors.toList());
} else {
return poList;
}
List<CsLinePO> result = this.list(new LambdaQueryWrapper<CsLinePO>()
.eq(CsLinePO::getStatus, 1)

View File

@@ -164,7 +164,7 @@ public class CsTerminalReplyServiceImpl extends ServiceImpl<CsTerminalReplyMappe
@Override
public List<CsTerminalReply> getBzReplyData(String lineId) {
LambdaQueryWrapper<CsTerminalReply> wrapper = new LambdaQueryWrapper<>();
wrapper.in(CsTerminalReply::getCode,Arrays.asList("allFile","allEvent","oneFile"))
wrapper.in(CsTerminalReply::getCode,Arrays.asList("allFile","allEvent","oneFile","harmonic"))
.orderByDesc(CsTerminalReply::getCreateTime);
if (!Objects.isNull(lineId) && StringUtils.isNotBlank(lineId)) {
wrapper.like(CsTerminalReply::getLineId,lineId);
@@ -184,7 +184,7 @@ public class CsTerminalReplyServiceImpl extends ServiceImpl<CsTerminalReplyMappe
, DateUtil.endOfDay(DateUtil.parse(param.getSearchEndTime())));
//排序
queryWrapper.orderBy(true, false, "cs_terminal_reply.create_time");
queryWrapper.in("cs_terminal_reply.code", Arrays.asList("allFile", "allEvent", "oneFile"));
queryWrapper.in("cs_terminal_reply.code", Arrays.asList("allFile", "allEvent", "oneFile","harmonic"));
Page<CsTerminalReply> csTerminalReplyPage = this.baseMapper.page(new Page<>(PageFactory.getPageNum(param), PageFactory.getPageSize(param)), queryWrapper);
List<CsTerminalReply> records = csTerminalReplyPage.getRecords();
@@ -193,6 +193,9 @@ public class CsTerminalReplyServiceImpl extends ServiceImpl<CsTerminalReplyMappe
Map<String, CsLedgerVO> ledgerMap = data.stream().collect(Collectors.toMap(CsLedgerVO::getId, Function.identity()));
List<CldLogsVo> cldLogsVos = new ArrayList<>();
records.forEach(item->{
if (Objects.isNull(ledgerMap.get(item.getDeviceId()))) {
return;
}
String pids = ledgerMap.get(item.getDeviceId()).getPids();
String[] split = pids.split(",");
CldLogsVo cldLogsVo = new CldLogsVo();
@@ -262,6 +265,9 @@ public class CsTerminalReplyServiceImpl extends ServiceImpl<CsTerminalReplyMappe
case "oneFile":
result = "补召单事件波形";
break;
case "harmonic":
result = "稳态数据";
break;
default:
result = "未知";
}

View File

@@ -251,13 +251,13 @@ class IcdServiceImpl implements IcdService {
DatePattern.NORM_DATETIME_PATTERN
);
if (CollectionUtil.isNotEmpty(param.getLineList())) {
processWithLineIds(param.getLineList(), beginDay, endDay);
processWithLineIds(param.getLineList(), beginDay, endDay, param.getBzType());
} else {
processWithoutLineIds(beginDay, endDay);
processWithoutLineIds(beginDay, endDay, param.getBzType());
}
}
private void processWithLineIds(List<String> lineList, String beginDay, String endDay) {
private void processWithLineIds(List<String> lineList, String beginDay, String endDay, Integer bzType) {
List<CsLinePO> csLineList = csLinePOService.listByIds(lineList);
List<String> deviceIdList = csLineList.stream()
.map(CsLinePO::getDeviceId)
@@ -268,10 +268,10 @@ class IcdServiceImpl implements IcdService {
Map<String, List<CsEquipmentDeliveryPO>> devMap = equipmentList.stream()
.collect(Collectors.groupingBy(CsEquipmentDeliveryPO::getNodeId));
handleEventsAndLogs(devMap, csLineList, beginDay, endDay);
handleEventsAndLogs(devMap, csLineList, beginDay, endDay, bzType);
}
private void processWithoutLineIds(String beginDay, String endDay) {
private void processWithoutLineIds(String beginDay, String endDay, Integer bzType) {
List<CsEquipmentDeliveryPO> devList = csEquipmentDeliveryService.getAllOnline();
if (CollectionUtil.isEmpty(devList)) return;
@@ -283,14 +283,15 @@ class IcdServiceImpl implements IcdService {
Map<String, List<CsEquipmentDeliveryPO>> devMap = devList.stream()
.collect(Collectors.groupingBy(CsEquipmentDeliveryPO::getNodeId));
handleEventsAndLogs(devMap, csLineList, beginDay, endDay);
handleEventsAndLogs(devMap, csLineList, beginDay, endDay, bzType);
}
private void handleEventsAndLogs(
Map<String, List<CsEquipmentDeliveryPO>> devMap,
List<CsLinePO> csLineList,
String beginDay,
String endDay
String endDay,
Integer bzType
) {
devMap.forEach((nodeId, devices) -> {
List<BZEventMessage.Event> events = new ArrayList<>();
@@ -300,13 +301,13 @@ class IcdServiceImpl implements IcdService {
for (CsEquipmentDeliveryPO device : devices) {
String uuid = IdUtil.simpleUUID();
BZEventMessage.Event event = buildEvent(uuid, device, csLineList, beginDay, endDay);
BZEventMessage.Event event = buildEvent(uuid, device, csLineList, beginDay, endDay, bzType);
events.add(event);
CsTerminalLogs log = buildTerminalLog(uuid, device, csLineList);
logsToSave.add(log);
List<CsTerminalReply> reply = buildTerminalReply(uuid, device, csLineList);
List<CsTerminalReply> reply = buildTerminalReply(uuid, device, csLineList, bzType);
repliesToSave.addAll(reply);
}
csTerminalLogsService.saveBatch(logsToSave);
@@ -316,7 +317,7 @@ class IcdServiceImpl implements IcdService {
}
private BZEventMessage.Event buildEvent(String guid, CsEquipmentDeliveryPO device,
List<CsLinePO> csLineList, String beginDay, String endDay) {
List<CsLinePO> csLineList, String beginDay, String endDay, Integer bzType) {
BZEventMessage.Event event = new BZEventMessage.Event();
event.setGuid(guid);
event.setTerminalId(device.getId());
@@ -327,7 +328,11 @@ class IcdServiceImpl implements IcdService {
.collect(Collectors.toList());
event.setMonitorIdList(monitorIds);
event.setDataType(1);
if (bzType == 0) {
event.setDataType(0);
} else {
event.setDataType(1);
}
event.setTimeInterval(Collections.singletonList(beginDay + "~" + endDay));
return event;
}
@@ -351,7 +356,7 @@ class IcdServiceImpl implements IcdService {
}
private List<CsTerminalReply> buildTerminalReply(String replyId, CsEquipmentDeliveryPO device,
List<CsLinePO> csLineList) {
List<CsLinePO> csLineList, Integer bzType) {
List<CsTerminalReply> replies = new ArrayList<>();
List<String> lineIds = csLineList.stream()
.filter(line -> Objects.equals(line.getDeviceId(), device.getId()))
@@ -366,7 +371,11 @@ class IcdServiceImpl implements IcdService {
reply.setDeviceId(device.getId());
reply.setLineId(lineId);
reply.setIsReceived(0);
reply.setCode("allEvent");
if (bzType == 0) {
reply.setCode("harmonic");
} else {
reply.setCode("allEvent");
}
replies.add(reply);
});
return replies;

View File

@@ -2,7 +2,6 @@ package com.njcn.csdevice.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.github.jeffreyning.mybatisplus.service.MppServiceImpl;
import com.njcn.csdevice.api.CsLineFeignClient;
@@ -82,14 +81,8 @@ public class RStatIntegrityDServiceImpl extends MppServiceImpl<RStatIntegrityDMa
statisticalDataDTO = commonService.getDataCounts(item.getLineId(),"apf_data","Apf_Freq","value","T","AVG",item.getClDid().toString(),process.toString(),time+" 00:00:00",time+" 23:59:59");
}
else {
//云前置监测点
if (ObjectUtil.isNotNull(item.getLineNo())) {
statisticalDataDTO = commonService.getDataCounts(item.getLineId(),"data_v","freq","value","T","AVG",item.getClDid().toString(),process.toString(),time+" 00:00:00",time+" 23:59:59");
}
//治理、无线监测点
else {
statisticalDataDTO = commonService.getDataCounts(item.getLineId(),"data_v","freq","value","T","AVG",item.getClDid().toString(),process.toString(),time+" 00:00:00",time+" 23:59:59");
}
//云前置监测点 && 治理、无线监测点
statisticalDataDTO = commonService.getDataCounts(item.getLineId(),"data_v","freq","value","T","AVG",item.getClDid().toString(),process.toString(),time+" 00:00:00",time+" 23:59:59");
}
data.setTimeId(LocalDate.parse(time, DatePattern.NORM_DATE_FORMATTER));
data.setLineIndex(item.getLineId());

View File

@@ -1,417 +0,0 @@
package com.njcn.csdevice.service.impl;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.csdevice.mapper.CsSmsSendRecordMapper;
import com.njcn.csdevice.pojo.dto.CredentialReqDTO;
import com.njcn.csdevice.pojo.dto.SendResult;
import com.njcn.csdevice.pojo.po.CsSmsSendRecord;
import com.njcn.csdevice.pojo.vo.MessageRecordReqVO;
import com.njcn.csdevice.service.ISmsSendService;
import com.njcn.redis.utils.RedisUtil;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
/**
* @author xy
*/
@Slf4j
@Service
@AllArgsConstructor
@RequiredArgsConstructor
public class SmsSendServiceImpl extends ServiceImpl<CsSmsSendRecordMapper, CsSmsSendRecord> implements ISmsSendService {
@Value("${msg.credential_url:http://192.168.2.126:48083/admin-api/push/credential/generate}")
private String CREDENTIAL_URL;
@Value("${msg.sms_send_url:http://192.168.2.126:48083/admin-api/push/message/send/sms}")
private String SMS_SEND_URL;
@Value("${msg.connect_timeout:5000}")
private Integer CONNECT_TIMEOUT;
@Value("${msg.read_timeout:30000}")
private Integer READ_TIMEOUT;
@Value("${msg.system_name:NPQS-9500}")
private String SYSTEM_NAME;
@Value("${msg.secret_key:123456}")
private String SECRET_KEY;
private static final int[] RETRY_DELAYS = {1, 2, 3};
private static final int MAX_RETRY = 3;
private static final String CREDENTIAL_CACHE_KEY = "SMS_CREDENTIAL_TOKEN";
private static final Gson GSON = new Gson();
@Resource
private RedisUtil redisUtil;
@Override
public void sendSmsWithRetry(String receiver, String content, String messageType) {
MessageRecordReqVO vo = new MessageRecordReqVO();
vo.setReceiver(receiver);
vo.setContent(content);
vo.setMessageType(messageType);
sendSmsWithRetry(vo);
}
@Override
public void sendSmsWithRetry(MessageRecordReqVO messageRecordReqVO) {
CsSmsSendRecord record = initRecord(messageRecordReqVO);
this.save(record);
try {
String credentialToken = getOrRefreshCredentialWithRetry(record);
if (credentialToken == null) {
record.setSendStatus(0);
record.setFailReason("获取凭证失败已重试3次");
log.error("获取凭证失败,短信未发送,接收者: {}", messageRecordReqVO.getReceiver());
this.updateById(record);
throw new BusinessException("获取凭证失败已重试3次");
}
record.setCredentialToken(credentialToken);
record.setSendTime(LocalDateTime.now());
this.updateById(record);
boolean success = attemptSendWithRetry(messageRecordReqVO, credentialToken, record);
if (success) {
record.setSendStatus(1);
record.setFailReason(null);
log.info("短信发送成功,接收者: {}", messageRecordReqVO.getReceiver());
} else {
record.setSendStatus(0);
if (record.getFailReason() == null) {
record.setFailReason("超过最大重试次数,发送失败");
}
log.error("短信发送失败,接收者: {},已重试{}次,原因: {}",
messageRecordReqVO.getReceiver(), record.getRetryCount(), record.getFailReason());
throw new BusinessException("短信发送失败: " + record.getFailReason());
}
} catch (BusinessException e) {
record.setSendStatus(0);
record.setFailReason(e.getMessage());
log.error("短信发送业务异常,接收者: {}", messageRecordReqVO.getReceiver(), e);
this.updateById(record);
throw e;
} catch (Exception e) {
record.setSendStatus(0);
record.setFailReason("发送异常: " + e.getMessage());
log.error("短信发送异常,接收者: {}", messageRecordReqVO.getReceiver(), e);
this.updateById(record);
throw new BusinessException("短信发送异常: " + e.getMessage());
} finally {
this.updateById(record);
}
}
private CsSmsSendRecord initRecord(MessageRecordReqVO vo) {
CsSmsSendRecord record = new CsSmsSendRecord();
record.setReceiver(vo.getReceiver());
record.setContent(vo.getContent());
record.setMessageType(vo.getMessageType());
record.setSendStatus(-1);
record.setRetryCount(0);
record.setMaxRetry(MAX_RETRY);
record.setCreateTime(LocalDateTime.now());
return record;
}
private String getOrRefreshCredentialWithRetry(CsSmsSendRecord record) {
Object cachedToken = redisUtil.getObjectByKey(CREDENTIAL_CACHE_KEY);
if (cachedToken != null) {
log.info("使用缓存的凭证令牌");
return cachedToken.toString();
}
log.info("缓存中无凭证开始获取新凭证最多重试3次");
for (int i = 1; i <= 3; i++) {
try {
String token = fetchNewCredential();
log.info("第{}次尝试获取凭证成功", i);
return token;
} catch (Exception e) {
log.warn("第{}次获取凭证失败: {}", i, e.getMessage());
record.setFailReason("获取凭证第" + i + "次失败: " + e.getMessage());
this.updateById(record);
try {
int waitSeconds = i * 10;
log.info("等待{}秒后重试...", waitSeconds);
TimeUnit.SECONDS.sleep(waitSeconds);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
log.error("凭证获取重试被中断");
record.setFailReason("获取凭证实例被中断");
this.updateById(record);
return null;
}
}
}
log.error("获取凭证失败已重试3次");
return null;
}
private String fetchNewCredential() {
CredentialReqDTO reqDTO = new CredentialReqDTO();
reqDTO.setSystemName(SYSTEM_NAME);
reqDTO.setSecretKey(SECRET_KEY);
HttpURLConnection connection = null;
try {
URL url = new URL(CREDENTIAL_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(CONNECT_TIMEOUT);
connection.setReadTimeout(READ_TIMEOUT);
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(GSON.toJson(reqDTO).getBytes(StandardCharsets.UTF_8));
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
throw new BusinessException("获取凭证失败HTTP响应码: " + responseCode);
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
JsonObject jsonResponse = GSON.fromJson(response.toString(), JsonObject.class);
int code = jsonResponse.get("code").getAsInt();
if (code != 0) {
String msg = jsonResponse.has("msg") ? jsonResponse.get("msg").getAsString() : "未知错误";
throw new BusinessException("获取凭证失败,错误码: " + code + ",错误信息: " + msg);
}
JsonObject data = jsonResponse.getAsJsonObject("data");
String token = data.get("credentialToken").getAsString();
long expiresTimestamp = data.get("expiresTime").getAsLong();
LocalDateTime expiresTime = LocalDateTime.ofInstant(
Instant.ofEpochMilli(expiresTimestamp),
ZoneId.systemDefault()
);
long expireSeconds = calculateExpireSeconds(expiresTime);
redisUtil.saveByKeyWithExpire(CREDENTIAL_CACHE_KEY, token, expireSeconds);
log.info("获取新凭证成功,过期时间: {},缓存有效期: {}秒", expiresTime, expireSeconds);
return token;
} catch (SocketTimeoutException e) {
throw new BusinessException("获取凭证超时(30秒),请检查网络连接");
} catch (ConnectException e) {
throw new BusinessException("无法连接到凭证服务,请检查服务是否启动和网络是否正常");
} catch (IOException e) {
throw new BusinessException("获取凭证IO异常: " + e.getMessage());
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private long calculateExpireSeconds(LocalDateTime expiresTime) {
long expireSeconds = java.time.Duration.between(
LocalDateTime.now(),
expiresTime
).getSeconds();
expireSeconds = expireSeconds - 60;
return Math.max(expireSeconds, 60);
}
private boolean attemptSendWithRetry(MessageRecordReqVO vo, String token, CsSmsSendRecord record) {
for (int attempt = 0; attempt <= MAX_RETRY; attempt++) {
if (attempt > 0) {
int delayMinutes = RETRY_DELAYS[attempt - 1];
log.info("第{}次重试,等待{}分钟后发送...", attempt, delayMinutes);
try {
TimeUnit.MINUTES.sleep(delayMinutes);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("重试等待被中断", e);
record.setFailReason("重试等待被中断");
return false;
}
record.setRetryCount(attempt);
}
SendResult result = executeSendSms(vo, token, record);
if (result.isSuccess()) {
record.setFailReason(null);
log.info("第{}次尝试发送成功消息ID: {}", attempt, result.getMessageId());
return true;
}
record.setFailReason(result.getFailReason());
if (result.isUnauthorized()) {
log.warn("凭证失效(401),重新获取凭证后重试...");
String newToken = getOrRefreshCredentialWithRetry(record);
if (newToken == null) {
record.setFailReason("凭证刷新失败,无法重新获取凭证");
return false;
}
token = newToken;
record.setCredentialToken(newToken);
this.updateById(record);
continue;
}
if (!result.isTimeOut()) {
log.warn("发送失败且非超时,不再重试,原因: {},响应时间: {}ms",
result.getFailReason(), record.getResponseTime());
return false;
}
log.warn("第{}次发送超时,将重试,响应时间: {}ms",
attempt, record.getResponseTime());
}
record.setFailReason("超过最大重试次数,发送超时");
return false;
}
private SendResult executeSendSms(MessageRecordReqVO vo, String token, CsSmsSendRecord record) {
HttpURLConnection connection = null;
long startTime = System.currentTimeMillis();
try {
URL url = new URL(SMS_SEND_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-Credential-Token", token);
connection.setConnectTimeout(CONNECT_TIMEOUT);
connection.setReadTimeout(READ_TIMEOUT);
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(GSON.toJson(Collections.singletonList(vo)).getBytes(StandardCharsets.UTF_8));
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
long responseTime = System.currentTimeMillis() - startTime;
record.setResponseTime(responseTime);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
responseCode == 200 ? connection.getInputStream() : connection.getErrorStream(),
StandardCharsets.UTF_8
)
);
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
if (responseCode != 200) {
String failReason = "HTTP响应码异常: " + responseCode;
if (response.length() > 0) {
failReason += ",响应: " + response.toString();
}
record.setFailReason(failReason);
return new SendResult(false, null, failReason, false, false);
}
JsonObject jsonResponse = GSON.fromJson(response.toString(), JsonObject.class);
int code = jsonResponse.get("code").getAsInt();
if (code == 401) {
String failReason = "凭证失效(HTTP 401)";
record.setFailReason(failReason);
redisUtil.delete(CREDENTIAL_CACHE_KEY);
return new SendResult(false, null, failReason, false, true);
} else {
if (code != 0) {
String msg = jsonResponse.has("msg") ? jsonResponse.get("msg").getAsString() : "未知错误";
String failReason = "业务错误码: " + code + ",错误信息: " + msg;
record.setFailReason(failReason);
return new SendResult(false, null, failReason, false, false);
}
}
JsonObject firstResult = jsonResponse.getAsJsonArray("data").get(0).getAsJsonObject();
boolean result = firstResult.get("result").getAsBoolean();
String messageId = firstResult.has("messageId") ? firstResult.get("messageId").getAsString() : null;
String detail = firstResult.has("detail") ? firstResult.get("detail").getAsString() : null;
if (result) {
log.info("短信发送成功,接收者: {}消息ID: {},详情: {},耗时: {}ms",
vo.getReceiver(), messageId, detail, responseTime);
return new SendResult(true, messageId, null, false, false);
} else {
String failReason = "发送失败: " + detail;
record.setFailReason(failReason);
return new SendResult(false, messageId, failReason, false, false);
}
} catch (SocketTimeoutException e) {
long responseTime = System.currentTimeMillis() - startTime;
record.setResponseTime(responseTime);
String failReason = "请求超时(30秒)";
record.setFailReason(failReason);
log.warn("短信发送超时,接收者: {},耗时: {}ms", vo.getReceiver(), responseTime);
return new SendResult(false, null, failReason, true, false);
} catch (ConnectException e) {
long responseTime = System.currentTimeMillis() - startTime;
record.setResponseTime(responseTime);
String failReason = "无法连接到短信服务";
record.setFailReason(failReason);
log.error("短信服务连接失败,接收者: {}", vo.getReceiver(), e);
return new SendResult(false, null, failReason, false, false);
} catch (IOException e) {
long responseTime = System.currentTimeMillis() - startTime;
record.setResponseTime(responseTime);
String failReason = "IO异常: " + e.getMessage();
record.setFailReason(failReason);
log.error("短信发送IO异常接收者: {},耗时: {}ms", vo.getReceiver(), responseTime, e);
return new SendResult(false, null, failReason, false, false);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}

View File

@@ -466,7 +466,7 @@ public class WlRecordServiceImpl extends ServiceImpl<WlRecordMapper, WlRecord> i
if(param.getStatisticalId() == null){
continue;
}
List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(param.getStatisticalId()).getData();
List<EleEpdPqd> eleEpdPqds = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(param.getStatisticalId())).getData();
for(WlRecord wl : data){
List<CsLinePO> finalCsLinePOList = csLineFeignClient.queryLineById(Arrays.asList(wl.getLineId())).getData();
CsDataSet csDataSet = csDataSetMapper.selectOne(new LambdaQueryWrapper<CsDataSet>().eq(CsDataSet::getId,finalCsLinePOList.get(0).getDataSetId()));

View File

@@ -1,17 +1,12 @@
package com.njcn.csharmonic.api;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.ServerInfo;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.common.utils.HttpResultUtil;
import com.njcn.csharmonic.api.fallback.EventUserFeignClientFallbackFactory;
import com.njcn.csharmonic.param.CsEventUserQueryParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.po.CsEventUserPO;
import com.njcn.csharmonic.pojo.vo.EventDetailVO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;

View File

@@ -3,7 +3,6 @@ package com.njcn.csharmonic.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.util.List;
/**
@@ -45,9 +44,12 @@ public class CommonStatisticalQueryParam {
private List<String> frequencys;
private int pageNum;
private int pageSize;
@ApiModelProperty(value = "查询分类:传1 则是趋势数据tab页面,传2 则是实时数据tab页面,传3 则是暂态事件tab页面")
@ApiModelProperty(value = "查询分类:传1 则是趋势数据tab页面,传2 则是实时数据tab页面,传3 则是暂态事件tab页面,传4 则是电度事件tab页面")
private String type;
@ApiModelProperty(value = "监测点")
private String lineId;
@ApiModelProperty(value = "数据模型 0:全量查询 1:增量查询")
private Integer dataModel;
}

View File

@@ -0,0 +1,66 @@
package com.njcn.csharmonic.pojo.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.time.Instant;
import java.util.List;
/**
* @author xy
*/
@Data
public class AppLineDetailVo implements Serializable {
private final static long serialVersionUID = 1L;
@ApiModelProperty("项目名称")
private String projectName;
@ApiModelProperty("设备名称")
private String deviceName;
@ApiModelProperty("监测点名称")
private String pointName;
@ApiModelProperty("监测点id")
private String pointId;
@ApiModelProperty("数据时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Instant dataTime;
@ApiModelProperty("监测点类型 0:治理监测点 1:监测监测点")
private Integer lineType;
@ApiModelProperty("指标数据")
private List<targetDetail> children;
@Data
public static class targetDetail implements Serializable {
@ApiModelProperty("指标id")
private String targetId;
@ApiModelProperty("指标名称")
private String name;
@ApiModelProperty("单位")
private String unit;
@ApiModelProperty("相别")
private String phase;
@ApiModelProperty("一二次值转换")
private String primaryFormula;
@ApiModelProperty("排序")
private Integer sort;
@ApiModelProperty("数据")
private Double data;
}
}

View File

@@ -15,7 +15,6 @@ import com.njcn.csharmonic.pojo.param.EventStatisticParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.vo.CsEventVO;
import com.njcn.csharmonic.pojo.vo.EventDetailVO;
import com.njcn.csharmonic.pojo.vo.EventStatisticsVo;
import com.njcn.csharmonic.service.CsEventPOService;
import com.njcn.event.file.pojo.dto.WaveDataDTO;
import com.njcn.web.controller.BaseController;
@@ -78,10 +77,13 @@ public class CsEventController extends BaseController {
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@GetMapping("/analyseWave")
@ApiOperation("暂态事件波形分析")
@ApiImplicitParam(name = "eventId", value = "暂态事件索引", required = true)
public HttpResult<WaveDataDTO> analyseWave(String eventId) {
@ApiImplicitParams({
@ApiImplicitParam(name = "eventId", value = "暂态事件索引"),
@ApiImplicitParam(name = "isApp", value = "是否是移动端查询")
})
public HttpResult<WaveDataDTO> analyseWave(@RequestParam(value = "eventId") String eventId,@RequestParam(value = "isApp", required = false) Boolean isApp) {
String methodDescribe = getMethodDescribe("analyseWave");
WaveDataDTO wave = csEventPOService.analyseWave(eventId,2);
WaveDataDTO wave = csEventPOService.analyseWave(eventId,2,isApp);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, wave, methodDescribe);
}

View File

@@ -9,6 +9,7 @@ import com.njcn.csdevice.pojo.vo.DataGroupEventVO;
import com.njcn.csdevice.pojo.vo.EachModuleVO;
import com.njcn.csdevice.pojo.vo.RecordVo;
import com.njcn.csharmonic.param.DataParam;
import com.njcn.csharmonic.pojo.vo.AppLineDetailVo;
import com.njcn.csharmonic.pojo.vo.RealTimeDataVo;
import com.njcn.csharmonic.service.IDataService;
import com.njcn.web.controller.BaseController;
@@ -83,4 +84,14 @@ public class DataController extends BaseController {
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
@PostMapping("/getLineDataByEngineer")
@ApiOperation("App-》工程下所有监测点数据")
@ApiImplicitParam(name = "id", value = "工程id", required = true)
public HttpResult<List<AppLineDetailVo>> getLineDataByEngineer(@RequestParam("id") String id) {
String methodDescribe = getMethodDescribe("getLineDataByEngineer");
List<AppLineDetailVo> list = dataService.getLineDataByEngineer(id);
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, list, methodDescribe);
}
}

View File

@@ -131,7 +131,7 @@ public class MqttMessageHandler {
List<ThdDataVO> tempList = new ArrayList<>();
//1.查询拓扑图配置的指标:拓扑图扑图配置7677f94c749dedaff30f911949cbd724
List<EleEpdPqd> data = csStatisticalSetFeignClient.queryStatisticalSelect(typeId).getData();
List<EleEpdPqd> data = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(typeId)).getData();
data.forEach(temp -> {
if (Objects.nonNull(temp.getHarmStart()) && Objects.nonNull(temp.getHarmEnd())) {
FrequencyStatisticalQueryParam frequencyStatisticalQueryParam = new FrequencyStatisticalQueryParam();
@@ -180,7 +180,7 @@ public class MqttMessageHandler {
if (item.getTarget() != null && !item.getTarget().isEmpty()) {
List<ThdDataVO> l1 = new ArrayList<>();
//根据指标查询
List<EleEpdPqd> data1 = csStatisticalSetFeignClient.queryStatisticalSelect(item.getTarget()).getData();
List<EleEpdPqd> data1 = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(item.getTarget())).getData();
data1.forEach(temp -> {
CommonStatisticalQueryParam commonStatisticalQueryParam = new CommonStatisticalQueryParam();
commonStatisticalQueryParam.setDevId(devId);
@@ -219,7 +219,7 @@ public class MqttMessageHandler {
//根据指标查询
List<ThdDataVO> l1 = new ArrayList<>();
//根据指标查询
List<EleEpdPqd> data1 = csStatisticalSetFeignClient.queryStatisticalSelect(item.getTarget()).getData();
List<EleEpdPqd> data1 = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(item.getTarget())).getData();
data1.forEach(temp -> {
CommonStatisticalQueryParam commonStatisticalQueryParam = new CommonStatisticalQueryParam();
commonStatisticalQueryParam.setDevId(devId);
@@ -260,7 +260,7 @@ public class MqttMessageHandler {
//根据指标查询
List<ThdDataVO> l1 = new ArrayList<>();
//根据指标查询
List<EleEpdPqd> data1 = csStatisticalSetFeignClient.queryStatisticalSelect(item.getTarget()).getData();
List<EleEpdPqd> data1 = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(item.getTarget())).getData();
data1.forEach(temp -> {
CommonStatisticalQueryParam commonStatisticalQueryParam = new CommonStatisticalQueryParam();
commonStatisticalQueryParam.setDevId(devId);

View File

@@ -12,10 +12,7 @@ import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.vo.CsEventVO;
import com.njcn.csharmonic.pojo.vo.CsWarnDescVO;
import com.njcn.csharmonic.pojo.vo.EventDetailVO;
import com.njcn.csharmonic.pojo.vo.EventStatisticsVo;
import com.njcn.event.file.pojo.dto.WaveDataDTO;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
@@ -40,7 +37,7 @@ public interface CsEventPOService extends IService<CsEventPO>{
* @date 2023/9/20 14:23
* @return WaveDataDTO
*/
WaveDataDTO analyseWave(String eventId, int i);
WaveDataDTO analyseWave(String eventId, int i, Boolean isApp);
/***
* 获取事件波形图信息

View File

@@ -4,6 +4,7 @@ import com.njcn.csdevice.pojo.vo.DataGroupEventVO;
import com.njcn.csdevice.pojo.vo.EachModuleVO;
import com.njcn.csdevice.pojo.vo.RecordVo;
import com.njcn.csharmonic.param.DataParam;
import com.njcn.csharmonic.pojo.vo.AppLineDetailVo;
import com.njcn.csharmonic.pojo.vo.RealTimeDataVo;
import java.util.List;
@@ -38,4 +39,6 @@ public interface IDataService {
List<EachModuleVO> getModuleState(String id);
List<AppLineDetailVo> getLineDataByEngineer(String id);
}

View File

@@ -74,6 +74,7 @@ import org.influxdb.InfluxDB;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@@ -126,6 +127,14 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
private final EventCauseFeignClient eventCauseFeignClient;
private final MsgSendFeignClient msgSendFeignClient;
/** 波形数据抽点窗口大小每N个点为一个窗口进行MinMax抽点可通过Nacos配置wave.sample.interval调整 */
@Value("${wave.sample.interval:0}")
private int waveSampleInterval;
/** 两段数据间隔区域补null点数量可通过Nacos配置wave.gap.null.points调整 */
@Value("${wave.gap.null.points:5}")
private int waveGapNullPoints;
@Override
public List<EventDetailVO> queryEventList(CsEventUserQueryParam csEventUserQueryParam) {
@@ -638,7 +647,7 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
* iType == 3 高级算法原始波形大于32
*/
@Override
public WaveDataDTO analyseWave(String eventId, int iType) {
public WaveDataDTO analyseWave(String eventId, int iType, Boolean isApp) {
WaveDataDTO waveDataDTO;
//获取暂降事件
CsEventPO eventDetail = this.baseMapper.selectById(eventId);
@@ -674,6 +683,10 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
throw new BusinessException(WaveFileResponseEnum.WAVE_DATA_INVALID);
}
waveDataDTO = waveFileComponent.getValidData(waveDataDTO);
if (!Objects.isNull(isApp) && isApp) {
//根据持续时间裁剪波形数据,只保留开始段和结束段的关键数据
filterWaveDataByPersistTime(waveDataDTO, eventDetail.getPersistTime());
}
List<CsLinePO> csLinePOList = csLineFeignClient.queryLineById(Stream.of(eventDetail.getLineId()).collect(Collectors.toList())).getData();
if (CollectionUtil.isEmpty(csLinePOList)) {
throw new BusinessException(AlgorithmResponseEnum.LINE_DATA_MISS);
@@ -690,7 +703,7 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
CsEventPO eventDetail = this.baseMapper.selectById(eventId);
if (StrUtil.isBlank(eventDetail.getInstantPics())) {
//获取波形数据。然后绘图
WaveDataDTO waveDataDTO = this.analyseWave(eventId, iType);
WaveDataDTO waveDataDTO = this.analyseWave(eventId, iType ,true);
//数据筛选,如果是双路电压的话会存在2个波形数据
List<WaveDataDetail> waveDataDetails = WaveUtil.filterWaveData(waveDataDTO);
//单通道处理
@@ -718,4 +731,238 @@ public class CsEventPOServiceImpl extends ServiceImpl<CsEventPOMapper, CsEventPO
return csEventVO;
}
private void filterWaveDataByPersistTime(WaveDataDTO waveDataDTO, Double persistTime) {
if (persistTime == null || persistTime <= 0) {
return;
}
double persistTimeMs = persistTime * 1000;
// 开始段:波形起始前后,-40ms到100ms
double startSegBegin = -100;
double startSegEnd = 100;
// 结束段恢复点前后各40ms
double endSegBegin = persistTimeMs - 40;
double endSegEnd = persistTimeMs + 40;
// 关键时间点(抽点时必须保留,不可被抽掉)
Set<Double> keyTimes = new HashSet<>();
keyTimes.add(startSegBegin); // 开头-100
keyTimes.add(0.0); // 波形开始时间点0
keyTimes.add(persistTimeMs); // 持续时间点
keyTimes.add(endSegBegin); // 持续时间点往前-40
keyTimes.add(endSegEnd); // 持续时间点往后+40
List<List<Float>> originalWaveData = waveDataDTO.getListWaveData();
List<List<Float>> originalRmsData = waveDataDTO.getListRmsData();
if (originalWaveData.isEmpty()) {
return;
}
int waveColumnCount = originalWaveData.get(0).size();
int rmsColumnCount = originalRmsData.get(0).size();
boolean isMerged = endSegBegin <= startSegEnd;
List<List<Float>> filteredWaveData;
List<List<Float>> filteredRmsData;
if (isMerged) {
// 两段重叠或相邻,合并为一段连续数据
double mergedEnd = Math.max(startSegEnd, endSegEnd);
List<List<Float>> segWaveData = filterByTimeRange(originalWaveData, startSegBegin, mergedEnd);
List<List<Float>> segRmsData = filterByTimeRange(originalRmsData, startSegBegin, mergedEnd);
// 合并为1段MinMax抽点 + 保留关键节点
filteredWaveData = downsampleMinMaxWithKeyPoints(segWaveData, keyTimes, waveSampleInterval);
filteredRmsData = downsampleMinMaxWithKeyPoints(segRmsData, keyTimes, waveSampleInterval);
} else {
// 两段分离分别MinMax抽点 + 保留关键节点
List<List<Float>> seg1Wave = filterByTimeRange(originalWaveData, startSegBegin, startSegEnd);
List<List<Float>> seg2Wave = filterByTimeRange(originalWaveData, endSegBegin, endSegEnd);
List<List<Float>> seg1Rms = filterByTimeRange(originalRmsData, startSegBegin, startSegEnd);
List<List<Float>> seg2Rms = filterByTimeRange(originalRmsData, endSegBegin, endSegEnd);
List<List<Float>> ds1Wave = downsampleMinMaxWithKeyPoints(seg1Wave, keyTimes, waveSampleInterval);
List<List<Float>> ds2Wave = downsampleMinMaxWithKeyPoints(seg2Wave, keyTimes, waveSampleInterval);
List<List<Float>> ds1Rms = downsampleMinMaxWithKeyPoints(seg1Rms, keyTimes, waveSampleInterval);
List<List<Float>> ds2Rms = downsampleMinMaxWithKeyPoints(seg2Rms, keyTimes, waveSampleInterval);
// 两段之间补固定数量的null点时间均匀分布
double gapStart = getTimeValue(ds1Wave.get(ds1Wave.size() - 1));
double gapEnd = getTimeValue(ds2Wave.get(0));
List<List<Float>> gapWaveData = createNullGapData(gapStart, gapEnd, waveGapNullPoints, waveColumnCount);
List<List<Float>> gapRmsData = createNullGapData(gapStart, gapEnd, waveGapNullPoints, rmsColumnCount);
// 合并段1 + null间隔 + 段2
filteredWaveData = new ArrayList<>();
filteredWaveData.addAll(ds1Wave);
filteredWaveData.addAll(gapWaveData);
filteredWaveData.addAll(ds2Wave);
filteredRmsData = new ArrayList<>();
filteredRmsData.addAll(ds1Rms);
filteredRmsData.addAll(gapRmsData);
filteredRmsData.addAll(ds2Rms);
}
waveDataDTO.setListWaveData(filteredWaveData);
waveDataDTO.setListRmsData(filteredRmsData);
}
/**
* MinMax抽点每N个点为一个窗口保留窗口内峰值点、谷值点、首点及关键时间点
* 峰值=参考列最大值的数据行,谷值=参考列最小值的数据行
* 这样正弦波的峰谷特征得以保留,波形形状不会被破坏
*
* @param dataList 已按时间范围筛选的数据
* @param keyTimes 关键时间点集合(ms)
* @param sampleInterval 窗口大小(N)
*/
private List<List<Float>> downsampleMinMaxWithKeyPoints(List<List<Float>> dataList, Set<Double> keyTimes, int sampleInterval) {
if (dataList.isEmpty()) {
return dataList;
}
// 找到关键时间点对应的数据索引
Set<Integer> keyIndices = new HashSet<>();
for (Double keyTime : keyTimes) {
int closestIdx = findClosestIndex(dataList, keyTime);
if (closestIdx >= 0) {
keyIndices.add(closestIdx);
}
}
List<List<Float>> result = new ArrayList<>();
int size = dataList.size();
// 使用第1列第一个值列通常是A相电压作为峰谷检测参考列
int refCol = 1;
for (int windowStart = 0; windowStart < size; windowStart += sampleInterval) {
int windowEnd = Math.min(windowStart + sampleInterval, size);
// 在窗口内找参考列的最大值点(峰值)和最小值点(谷值)
int maxIdx = windowStart;
int minIdx = windowStart;
float maxVal = getFloatValue(dataList.get(windowStart), refCol);
float minVal = getFloatValue(dataList.get(windowStart), refCol);
for (int i = windowStart + 1; i < windowEnd; i++) {
float val = getFloatValue(dataList.get(i), refCol);
if (val > maxVal) {
maxVal = val;
maxIdx = i;
}
if (val < minVal) {
minVal = val;
minIdx = i;
}
}
// 保留:窗口首点 + 峰值 + 谷值 + 窗口内的关键时间点
Set<Integer> keepSet = new HashSet<>();
keepSet.add(windowStart);
keepSet.add(maxIdx);
keepSet.add(minIdx);
for (int i = windowStart; i < windowEnd; i++) {
if (keyIndices.contains(i)) {
keepSet.add(i);
}
}
// 按原始顺序输出(索引顺序即时间顺序)
List<Integer> sortedKeep = new ArrayList<>(keepSet);
Collections.sort(sortedKeep);
for (int idx : sortedKeep) {
result.add(dataList.get(idx));
}
}
return result;
}
/**
* 安全获取Float值null时返回0
*/
private float getFloatValue(List<Float> data, int colIdx) {
if (colIdx >= data.size()) {
return 0f;
}
Float val = data.get(colIdx);
return val != null ? val : 0f;
}
/**
* 找到与目标时间最接近的数据点索引
* 仅在容差1.0ms内匹配,超出容差视为该段数据中无此关键点
*/
private int findClosestIndex(List<List<Float>> dataList, double targetTime) {
int closestIdx = -1;
double minDiff = Double.MAX_VALUE;
for (int i = 0; i < dataList.size(); i++) {
double time = getTimeValue(dataList.get(i));
double diff = Math.abs(time - targetTime);
if (diff < minDiff) {
minDiff = diff;
closestIdx = i;
}
}
// 容差1.0ms,超出则认为该段不含此关键点
if (minDiff > 1.0) {
return -1;
}
return closestIdx;
}
private double getTimeValue(List<Float> data) {
return data.get(0).doubleValue();
}
/**
* 在两段数据的间隔区域补固定数量的null数据点
* null点的时间在gapStart和gapEnd之间均匀分布
* 每个null点[时间, null, null, ...]echarts遇到null值会渲染为断线
*
* @param gapStart 段1最后一个点时间(ms)
* @param gapEnd 段2第一个点时间(ms)
* @param nullPointCount 补null点的数量
* @param columnCount 每行数据列数(含时间列)
*/
private List<List<Float>> createNullGapData(double gapStart, double gapEnd, int nullPointCount, int columnCount) {
List<List<Float>> gapData = new ArrayList<>();
if (gapEnd <= gapStart || nullPointCount <= 0) {
return gapData;
}
// 将gapStart到gapEnd之间均匀分成 nullPointCount+1 段
// null点放在中间的 nullPointCount 个位置两端留给段1末点和段2首点
double step = (gapEnd - gapStart) / (nullPointCount + 1);
for (int i = 1; i <= nullPointCount; i++) {
double time = gapStart + step * i;
List<Float> nullPoint = new ArrayList<>();
nullPoint.add((float) (Math.round(time * 100.0) / 100.0));
for (int j = 1; j < columnCount; j++) {
nullPoint.add(null);
}
gapData.add(nullPoint);
}
return gapData;
}
/**
* 按时间范围筛选数据列表
*
* @param dataList 原始数据列表,每行第一个元素为时间坐标(ms)
* @param startTime 起始时间(ms)
* @param endTime 结束时间(ms)
* @return 范围内的数据列表
*/
private List<List<Float>> filterByTimeRange(List<List<Float>> dataList, double startTime, double endTime) {
return dataList.stream()
.filter(data -> {
double time = ((Number) data.get(0)).doubleValue();
return time >= startTime && time <= endTime;
})
.collect(Collectors.toList());
}
}

View File

@@ -8,15 +8,15 @@ import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.tocrhz.mqtt.publisher.MqttPublisher;
import com.google.common.collect.Lists;
import com.njcn.access.api.CsTopicFeignClient;
import com.njcn.access.enums.AccessEnum;
import com.njcn.access.enums.TypeEnum;
import com.njcn.access.pojo.dto.AskDataDto;
import com.njcn.access.pojo.dto.ReqAndResDto;
import com.njcn.csdevice.api.CsLineFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.api.WlRecordFeignClient;
import com.njcn.csdevice.api.*;
import com.njcn.csdevice.pojo.dto.CsEquipmentDeliveryDTO;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csdevice.pojo.param.WlRecordParam;
import com.njcn.csdevice.pojo.po.CsDataSet;
import com.njcn.csdevice.pojo.po.CsEquipmentDeliveryPO;
@@ -25,33 +25,37 @@ import com.njcn.csdevice.pojo.po.WlRecord;
import com.njcn.csdevice.pojo.vo.DataGroupEventVO;
import com.njcn.csdevice.pojo.vo.EachModuleVO;
import com.njcn.csdevice.pojo.vo.RecordVo;
import com.njcn.csdevice.utils.DataChangeUtil;
import com.njcn.csdevice.utils.ReflectUtils;
import com.njcn.csharmonic.constant.HarmonicConstant;
import com.njcn.csharmonic.mapper.CsDataSetMapper;
import com.njcn.csharmonic.param.DataParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.vo.AppLineDetailVo;
import com.njcn.csharmonic.pojo.vo.RealTimeDataVo;
import com.njcn.csharmonic.service.CsEventPOService;
import com.njcn.csharmonic.service.IDataService;
import com.njcn.csharmonic.util.InfluxDbParamUtil;
import com.njcn.influx.constant.InfluxDbSqlConstant;
import com.njcn.influx.imapper.*;
import com.njcn.influx.pojo.bo.CommonQueryParam;
import com.njcn.influx.pojo.dto.EventDataSetDTO;
import com.njcn.influx.pojo.dto.StatisticalDataDTO;
import com.njcn.influx.pojo.po.*;
import com.njcn.influx.pojo.po.cs.ApfData;
import com.njcn.influx.query.InfluxQueryWrapper;
import com.njcn.influx.service.CommonService;
import com.njcn.influx.service.EvtDataService;
import com.njcn.redis.pojo.enums.AppRedisKey;
import com.njcn.redis.utils.RedisUtil;
import com.njcn.system.api.CsStatisticalSetFeignClient;
import com.njcn.system.api.DictTreeFeignClient;
import com.njcn.system.api.EleEvtFeignClient;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.system.pojo.po.EleEpdPqd;
import com.njcn.system.pojo.po.EleEvtParm;
import com.njcn.system.api.*;
import com.njcn.system.pojo.po.*;
import com.njcn.system.pojo.vo.DictTreeVO;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.Duration;
import java.time.Instant;
@@ -91,7 +95,37 @@ public class DataServiceImpl implements IDataService {
private static Integer mid = 1;
private final CsTopicFeignClient csTopicFeignClient;
private final MqttPublisher publisher;
private static final List<String> ONLINE_STATES = Arrays.asList("运行", "停止", "故障");
private final CsLedgerFeignClient csLedgerFeignClient;
private final DicDataFeignClient dicDataFeignClient;
@Resource
private DataVMapper dataVMapper;
@Resource
private DataIMapper dataIMapper;
@Resource
private DataFlickerMapper dataFlickerMapper;
@Resource
private DataFlucMapper dataFlucMapper;
@Resource
private DataHarmPhasicVMapper dataHarmPhasicVMapper;
@Resource
private DataHarmPhasicIMapper dataHarmPhasicIMapper;
@Resource
private DataHarmPowerPMapper dataHarmPowerPMapper;
@Resource
private DataHarmPowerQMapper dataHarmPowerQMapper;
@Resource
private DataHarmPowerSMapper dataHarmPowerSMapper;
@Resource
private DataHarmRateVMapper dataHarmRateVMapper;
@Resource
private DataHarmRateIMapper dataHarmRateIMapper;
@Resource
private DataInHarmVMapper dataInHarmVMapper;
@Resource
private DataPltMapper dataPltMapper;
@Resource
private ApfDataMapper apfDataMapper;
private final DataSetFeignClient dataSetFeignClient;
@Override
public List<RealTimeDataVo> getRealTimeData(DataParam param) {
@@ -108,7 +142,7 @@ public class DataServiceImpl implements IDataService {
//根据分组获取对应指标
List<RealTimeDataVo> finalResult = result;
dictTreeVOList.forEach(item->{
List<EleEpdPqd> epdPqdList = csStatisticalSetFeignClient.queryStatisticalSelect(item.getId()).getData();
List<EleEpdPqd> epdPqdList = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(item.getId())).getData();
epdPqdList.forEach(item2->{
if (Objects.isNull(item2.getHarmStart())) {
RealTimeDataVo vo = getBaseData(item2,param.getLineId(),param.getDataLevel(),csDataSet.getDataLevel(),pt,ct);
@@ -435,6 +469,688 @@ public class DataServiceImpl implements IDataService {
return result;
}
//1、根据监测点集合 100为1个单位进行查询
//2、根据表名来进行查询 指标可以用循环的方式拼接起来 influxQueryWrapper.select("rms","rms")
//3、根据相别来分开查询数据类型统一查询avg
@Override
public List<AppLineDetailVo> getLineDataByEngineer(String id) {
List<AppLineDetailVo> result = new ArrayList<>();
//根据工程获取监测点信息
List<DevDetailDTO> data = csLedgerFeignClient.getDevInfoByEngineerIds(Collections.singletonList(id)).getData();
if (CollectionUtil.isNotEmpty(data)) {
List<DataV> data1 = new ArrayList<>();
List<DataI> data2 = new ArrayList<>();
List<DataFlicker> data3 = new ArrayList<>();
List<DataFluc> data4 = new ArrayList<>();
List<DataHarmPhasicV> data5 = new ArrayList<>();
List<DataHarmPhasicI> data6 = new ArrayList<>();
List<DataHarmPowerP> data7 = new ArrayList<>();
List<DataHarmPowerQ> data8 = new ArrayList<>();
List<DataHarmPowerS> data9 = new ArrayList<>();
List<DataHarmRateV> data10 = new ArrayList<>();
List<DataHarmRateI> data11 = new ArrayList<>();
List<DataInHarmV> data12 = new ArrayList<>();
List<DataPlt> data13 = new ArrayList<>();
List<ApfData> data14 = new ArrayList<>();
//获取监测点集合 针对监测点的类型区分查询数据-治理监测点、监测监测点
List<String> lineList = data.stream().flatMap(v -> v.getLineList().stream()).collect(Collectors.toList());
if (CollectionUtil.isEmpty(lineList)) {
return result;
}
List<CsLinePO> linePo = csLineFeignClient.queryLineById(lineList).getData();
Map<String,CsLinePO> lineMap = linePo.stream().collect(Collectors.toMap(CsLinePO::getLineId, item->item));
//拆分治理监测点 、 监测监测点
List<CsLinePO> line1 = linePo.stream().filter(item->item.getClDid()==0).collect(Collectors.toList());
List<CsLinePO> line2 = linePo.stream().filter(item->item.getClDid()!=0).collect(Collectors.toList());
List<String> lineList2 = line2.stream().map(CsLinePO::getLineId).collect(Collectors.toList());
List<List<String>> partitions = Lists.partition(lineList2, 95);
//表集合
List<DictData> dataList = dicDataFeignClient.getDicDataByTypeCode("Data").getData();
Map<String, DictData> map = dataList.stream().collect(Collectors.toMap(DictData::getId, v -> v));
//获取需要查询的指标
List<SysDicTreePO> list = dictTreeFeignClient.queryByCodeList("Key_Power_Quality").getData();
List<SysDicTreePO> children = list.get(0).getChildren();
children.sort(Comparator.comparing(SysDicTreePO::getSort));
List<String> idList = children.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
List<EleEpdPqd> epdPqdList = csStatisticalSetFeignClient.queryStatisticalSelect(idList).getData();
Map<String,List<EleEpdPqd>> epdPqdMap = epdPqdList.stream().collect(Collectors.groupingBy(EleEpdPqd::getClassId));
Map<String,EleEpdPqd> epdPqdMap2 = epdPqdList.stream().collect(Collectors.toMap(EleEpdPqd::getId, v -> v));
//获取监测点的数据集,转换一二次值
List<String> dataSetIdList = linePo.stream().map(CsLinePO::getDataSetId).distinct().collect(Collectors.toList());
List<CsDataSet> csDataSetList = dataSetFeignClient.getDataSetBySetIds(dataSetIdList).getData();
Map<String,CsDataSet> csDataSetMap = csDataSetList.stream().collect(Collectors.toMap(CsDataSet::getId, v -> v));
//获取指标名称和对应的指标集合
List<CsStatisticalSetPO> csStatisticalSetPOList = csStatisticalSetFeignClient.queryStatisticalById(idList).getData();
Map<String,List<CsStatisticalSetPO>> csStatisticalSetPOMap = csStatisticalSetPOList.stream().collect(Collectors.groupingBy(CsStatisticalSetPO::getStatisicalId));
epdPqdMap.forEach((k,v) ->{
if (Objects.equals(map.get(k).getName(), "data_v")) {
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataV.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataV::getLineId, l)
.eq(DataV::getValueType,"AVG")
.groupBy(DataV::getPhaseType)
.groupBy(DataV::getLineId)
.timeDesc().limit(1);
List<DataV> dataV = dataVMapper.selectByQueryWrapper(influxQueryWrapper);
data1.addAll(dataV);
});
} else if (Objects.equals(map.get(k).getName(), "data_i")){
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataI.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataI::getLineId, l)
.eq(DataI::getValueType,"AVG")
.groupBy(DataI::getPhaseType)
.groupBy(DataI::getLineId)
.timeDesc().limit(1);
List<DataI> dataI = dataIMapper.selectByQueryWrapper(influxQueryWrapper);
data2.addAll(dataI);
});
} else if (Objects.equals(map.get(k).getName(), "data_flicker")){
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataFlicker.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataFlicker::getLineId, l)
.eq(DataFlicker::getValueType,"AVG")
.groupBy(DataFlicker::getPhaseType)
.groupBy(DataFlicker::getLineId)
.timeDesc().limit(1);
List<DataFlicker> dataFlicker = dataFlickerMapper.selectByQueryWrapper(influxQueryWrapper);
data3.addAll(dataFlicker);
});
} else if (Objects.equals(map.get(k).getName(), "data_fluc")){
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataFluc.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataFluc::getLineId, l)
.eq(DataFluc::getValueType,"AVG")
.groupBy(DataFluc::getPhaseType)
.groupBy(DataFluc::getLineId)
.timeDesc().limit(1);
List<DataFluc> dataFluc = dataFlucMapper.selectByQueryWrapper(influxQueryWrapper);
data4.addAll(dataFluc);
});
} else if (Objects.equals(map.get(k).getName(), "data_harmphasic_v")){
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPhasicV.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataHarmPhasicV::getLineId, l)
.eq(DataHarmPhasicV::getValueType,"AVG")
.groupBy(DataHarmPhasicV::getPhaseType)
.groupBy(DataHarmPhasicV::getLineId)
.timeDesc().limit(1);
List<DataHarmPhasicV> dataHarmPhasicV = dataHarmPhasicVMapper.selectByQueryWrapper(influxQueryWrapper);
data5.addAll(dataHarmPhasicV);
});
} else if (Objects.equals(map.get(k).getName(), "data_harmphasic_i")){
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPhasicI.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataHarmPhasicI::getLineId, l)
.eq(DataHarmPhasicI::getValueType,"AVG")
.groupBy(DataHarmPhasicI::getPhaseType)
.groupBy(DataHarmPhasicI::getLineId)
.timeDesc().limit(1);
List<DataHarmPhasicI> dataHarmPhasicI = dataHarmPhasicIMapper.selectByQueryWrapper(influxQueryWrapper);
data6.addAll(dataHarmPhasicI);
});
} else if (Objects.equals(map.get(k).getName(), "data_harmpower_p")){
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPowerP.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataHarmPowerP::getLineId, l)
.eq(DataHarmPowerP::getValueType,"AVG")
.groupBy(DataHarmPowerP::getPhaseType)
.groupBy(DataHarmPowerP::getLineId)
.timeDesc().limit(1);
List<DataHarmPowerP> dataHarmPowerP = dataHarmPowerPMapper.selectByQueryWrapper(influxQueryWrapper);
data7.addAll(dataHarmPowerP);
});
} else if (Objects.equals(map.get(k).getName(), "data_harmpower_q")){
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPowerQ.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataHarmPowerQ::getLineId, l)
.eq(DataHarmPowerQ::getValueType,"AVG")
.groupBy(DataHarmPowerQ::getPhaseType)
.groupBy(DataHarmPowerQ::getLineId)
.timeDesc().limit(1);
List<DataHarmPowerQ> dataHarmPowerQ = dataHarmPowerQMapper.selectByQueryWrapper(influxQueryWrapper);
data8.addAll(dataHarmPowerQ);
});
} else if (Objects.equals(map.get(k).getName(), "data_harmpower_s")){
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmPowerS.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataHarmPowerS::getLineId, l)
.eq(DataHarmPowerS::getValueType,"AVG")
.groupBy(DataHarmPowerS::getPhaseType)
.groupBy(DataHarmPowerS::getLineId)
.timeDesc().limit(1);
List<DataHarmPowerS> dataHarmPowerS = dataHarmPowerSMapper.selectByQueryWrapper(influxQueryWrapper);
data9.addAll(dataHarmPowerS);
});
} else if (Objects.equals(map.get(k).getName(), "data_harmrate_v")){
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmRateV.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataHarmRateV::getLineId, l)
.eq(DataHarmRateV::getValueType,"AVG")
.groupBy(DataHarmRateV::getPhaseType)
.groupBy(DataHarmRateV::getLineId)
.timeDesc().limit(1);
List<DataHarmRateV> dataHarmRateV = dataHarmRateVMapper.selectByQueryWrapper(influxQueryWrapper);
data10.addAll(dataHarmRateV);
});
} else if (Objects.equals(map.get(k).getName(), "data_harmrate_i")){
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataHarmRateI.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataHarmRateI::getLineId, l)
.eq(DataHarmRateI::getValueType,"AVG")
.groupBy(DataHarmRateI::getPhaseType)
.groupBy(DataHarmRateI::getLineId)
.timeDesc().limit(1);
List<DataHarmRateI> DataHarmRateI = dataHarmRateIMapper.selectByQueryWrapper(influxQueryWrapper);
data11.addAll(DataHarmRateI);
});
} else if (Objects.equals(map.get(k).getName(), "data_inharm_v")){
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataInHarmV.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataInHarmV::getLineId, l)
.eq(DataInHarmV::getValueType,"AVG")
.groupBy(DataInHarmV::getPhaseType)
.groupBy(DataInHarmV::getLineId)
.timeDesc().limit(1);
List<DataInHarmV> dataInHarmV = dataInHarmVMapper.selectByQueryWrapper(influxQueryWrapper);
data12.addAll(dataInHarmV);
});
} else if (Objects.equals(map.get(k).getName(), "data_plt")){
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(DataPlt.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(DataPlt::getLineId, l)
.eq(DataPlt::getValueType,"AVG")
.groupBy(DataPlt::getPhaseType)
.groupBy(DataPlt::getLineId)
.timeDesc().limit(1);
List<DataPlt> dataPlt = dataPltMapper.selectByQueryWrapper(influxQueryWrapper);
data13.addAll(dataPlt);
});
}
});
//监测点第一层
line2.forEach(item->{
AppLineDetailVo vo = new AppLineDetailVo();
for (DevDetailDTO item2 : data) {
if (item2.getLineList() != null && item2.getLineList().contains(item.getLineId())) {
vo.setProjectName(item2.getProjectName());
vo.setDeviceName(item2.getEquipmentName());
break;
}
}
vo.setLineType(1);
vo.setPointId(item.getLineId());
vo.setPointName(lineMap.get(item.getLineId()).getName());
List<AppLineDetailVo.targetDetail> children2 = new ArrayList<>();
//指标第二层
List<AppLineDetailVo.targetDetail> finalChildren = children2;
children.forEach(item3->{
List<CsStatisticalSetPO> l1 = csStatisticalSetPOMap.get(item3.getId());
l1.forEach(item1 -> {
EleEpdPqd epdPqd = epdPqdMap2.get(item1.getTargetId());
AppLineDetailVo.targetDetail targetDetail = new AppLineDetailVo.targetDetail();
targetDetail.setTargetId(item3.getId());
targetDetail.setName(item3.getName());
targetDetail.setPhase(epdPqd.getPhase());
targetDetail.setUnit(epdPqd.getUnit());
targetDetail.setSort(item3.getSort());
targetDetail.setPrimaryFormula(epdPqd.getPrimaryFormula());
if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_v")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataV matchedDataV = data1.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
} else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_i")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataI matchedDataV = data2.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
} else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_flicker")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataFlicker matchedDataV = data3.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
} else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_fluc")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataFluc matchedDataV = data4.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
} else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmphasic_v")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataHarmPhasicV matchedDataV = data5.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
} else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmphasic_i")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataHarmPhasicI matchedDataV = data6.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
} else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmpower_p")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataHarmPowerP matchedDataV = data7.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
} else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmpower_q")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataHarmPowerQ matchedDataV = data8.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
} else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmpower_s")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataHarmPowerS matchedDataV = data9.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
} else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmrate_v")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataHarmRateV matchedDataV = data10.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
} else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_harmrate_i")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataHarmRateI matchedDataV = data11.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
} else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_inharm_v")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataInHarmV matchedDataV = data12.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
} else if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "data_plt")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
DataPlt matchedDataV = data13.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
}
//一二次值处理
if (!Objects.isNull(targetDetail.getData())) {
String dataLevel = csDataSetMap.get(lineMap.get(item.getLineId()).getDataSetId()).getDataLevel();
if (Objects.equals(dataLevel, "Primary")) {
if (targetDetail.getPrimaryFormula() != null && ("*PT".equals(targetDetail.getPrimaryFormula()) || "*PT*CT".equals(targetDetail.getPrimaryFormula()))) {
targetDetail.setUnit("k" + targetDetail.getUnit());
targetDetail.setData(Math.round(targetDetail.getData() * 100.0) / 100.0);
}
} else if (Objects.equals(dataLevel, "Secondary")) {
Double ct = item.getCtRatio() / (Objects.isNull(item.getCt2Ratio())?1.0:item.getCt2Ratio());
Double pt = item.getPtRatio() / (Objects.isNull(item.getPt2Ratio())?1.0:item.getPt2Ratio());
String formula = targetDetail.getPrimaryFormula();
if (formula == null) {
targetDetail.setData(Math.round(targetDetail.getData() * 100.0) / 100.0);
}
if ("*PT".equals(formula) || "*PT*CT".equals(formula)) {
targetDetail.setUnit("k" + targetDetail.getUnit());
double finalData = DataChangeUtil.secondaryToPrimary(formula, targetDetail.getData(), pt, ct);
targetDetail.setData(Math.round((finalData/1000) * 100.0) / 100.0);
}
if ("*CT".equals(formula)) {
double finalData = DataChangeUtil.secondaryToPrimary(formula, targetDetail.getData(), pt, ct);
targetDetail.setData(Math.round(finalData * 100.0) / 100.0);
}
}
}
finalChildren.add(targetDetail);
});
});
// 根据接线方式处理相别
chanelPhase(lineMap, item, finalChildren, children2);
if (CollUtil.isNotEmpty(children2)) {
children2.sort(Comparator.comparingInt(AppLineDetailVo.targetDetail::getSort));
}
vo.setChildren(children2);
result.add(vo);
});
if (CollectionUtil.isNotEmpty(line1)) {
List<AppLineDetailVo> zhiLiLineData = getZhiLiLineData(line1,data14, map, data, lineMap, csDataSetMap);
result.addAll(zhiLiLineData);
}
}
if (CollUtil.isNotEmpty(result)) {
result.sort(Comparator.comparing(AppLineDetailVo::getProjectName)
.thenComparing(AppLineDetailVo::getDeviceName)
.thenComparing(AppLineDetailVo::getPointId));
}
return result;
}
public void chanelPhase(Map<String,CsLinePO> lineMap,CsLinePO item,List<AppLineDetailVo.targetDetail> finalChildren, List<AppLineDetailVo.targetDetail> children2) {
// 根据接线方式处理相别
Integer conType = lineMap.get(item.getLineId()).getConType();
if (conType != null && conType == 0) {
// 星型接线: 保留A/B/C/T去除AB/BC/CA
finalChildren.removeIf(d -> "AB".equals(d.getPhase()) || "BC".equals(d.getPhase()) || "CA".equals(d.getPhase()));
} else if (conType != null) {
// 角型/V型接线: A/B/C数据用AB/BC/CA替换然后去除AB/BC/CA
Map<String, List<AppLineDetailVo.targetDetail>> groupByTargetId = finalChildren.stream()
.collect(Collectors.groupingBy(AppLineDetailVo.targetDetail::getTargetId));
List<AppLineDetailVo.targetDetail> newChildren2 = new ArrayList<>();
for (List<AppLineDetailVo.targetDetail> group : groupByTargetId.values()) {
// 提取AB/BC/CA的数据
Map<String, Double> abDataMap = new HashMap<>();
for (AppLineDetailVo.targetDetail d : group) {
if ("AB".equals(d.getPhase()) || "BC".equals(d.getPhase()) || "CA".equals(d.getPhase())) {
abDataMap.put(d.getPhase(), d.getData());
}
}
// 用AB/BC/CA替换A/B/C数据保留T相
for (AppLineDetailVo.targetDetail d : group) {
if ("A".equals(d.getPhase())) {
if (abDataMap.containsKey("AB")) {
d.setData(abDataMap.get("AB"));
}
newChildren2.add(d);
} else if ("B".equals(d.getPhase())) {
if (abDataMap.containsKey("BC")) {
d.setData(abDataMap.get("BC"));
}
newChildren2.add(d);
} else if ("C".equals(d.getPhase())) {
if (abDataMap.containsKey("CA")) {
d.setData(abDataMap.get("CA"));
}
newChildren2.add(d);
} else if ("T".equals(d.getPhase())) {
newChildren2.add(d);
}
}
}
children2 = newChildren2;
}
}
//处理治理监测点
public List<AppLineDetailVo> getZhiLiLineData(List<CsLinePO> poList
,List<ApfData> data14
, Map<String, DictData> map
, List<DevDetailDTO> data
, Map<String,CsLinePO> lineMap
, Map<String,CsDataSet> csDataSetMap) {
List<AppLineDetailVo> result = new ArrayList<>();
if (CollUtil.isEmpty(poList)) {
return result;
}
List<String> lineList = poList.stream().map(CsLinePO::getLineId).collect(Collectors.toList());
List<List<String>> partitions = Lists.partition(lineList, 95);
//获取需要查询的指标
List<SysDicTreePO> list = dictTreeFeignClient.queryByCodeList("Key_Power_Quality_Pq_Com").getData();
List<SysDicTreePO> children = list.get(0).getChildren();
children.sort(Comparator.comparing(SysDicTreePO::getSort));
List<String> idList = children.stream().map(SysDicTreePO::getId).collect(Collectors.toList());
List<EleEpdPqd> epdPqdList = csStatisticalSetFeignClient.queryStatisticalSelect(idList).getData();
Map<String,List<EleEpdPqd>> epdPqdMap = epdPqdList.stream().collect(Collectors.groupingBy(EleEpdPqd::getClassId));
Map<String,EleEpdPqd> epdPqdMap2 = epdPqdList.stream().collect(Collectors.toMap(EleEpdPqd::getId, v -> v));
//获取指标名称和对应的指标集合
List<CsStatisticalSetPO> csStatisticalSetPOList = csStatisticalSetFeignClient.queryStatisticalById(idList).getData();
Map<String,List<CsStatisticalSetPO>> csStatisticalSetPOMap = csStatisticalSetPOList.stream().collect(Collectors.groupingBy(CsStatisticalSetPO::getStatisicalId));
epdPqdMap.forEach((k,v) ->{
if (Objects.equals(map.get(k).getName(), "apf_data")) {
partitions.forEach(l -> {
InfluxQueryWrapper influxQueryWrapper = new InfluxQueryWrapper(ApfData.class);
v.stream().map(EleEpdPqd::getOtherName).distinct().forEach(otherName -> influxQueryWrapper.select(otherName, otherName));
influxQueryWrapper.regular(ApfData::getLineId, l)
.eq(ApfData::getValueType,"AVG")
.groupBy(ApfData::getPhaseType)
.groupBy(ApfData::getLineId)
.timeDesc().limit(1);
List<ApfData> apfData = apfDataMapper.selectByQueryWrapper(influxQueryWrapper);
data14.addAll(apfData);
});
}
});
//监测点第一层
poList.forEach(item->{
AppLineDetailVo vo = new AppLineDetailVo();
for (DevDetailDTO item2 : data) {
if (item2.getLineList() != null && item2.getLineList().contains(item.getLineId())) {
vo.setProjectName(item2.getProjectName());
vo.setDeviceName(item2.getEquipmentName());
break;
}
}
vo.setLineType(0);
vo.setPointId(item.getLineId());
vo.setPointName(lineMap.get(item.getLineId()).getName());
List<AppLineDetailVo.targetDetail> children2 = new ArrayList<>();
//指标第二层
List<AppLineDetailVo.targetDetail> finalChildren = children2;
children.forEach(item3->{
List<CsStatisticalSetPO> l1 = csStatisticalSetPOMap.get(item3.getId());
l1.forEach(item1 -> {
EleEpdPqd epdPqd = epdPqdMap2.get(item1.getTargetId());
AppLineDetailVo.targetDetail targetDetail = new AppLineDetailVo.targetDetail();
targetDetail.setTargetId(item3.getId());
targetDetail.setName(item3.getName());
targetDetail.setPhase(epdPqd.getPhase());
targetDetail.setUnit(epdPqd.getUnit());
targetDetail.setSort(item3.getSort());
targetDetail.setPrimaryFormula(epdPqd.getPrimaryFormula());
if (Objects.equals(map.get(epdPqd.getClassId()).getName(), "apf_data")) {
//根据otherName反射获取DataV中的字段值按lineId和相别匹配
String otherName = epdPqd.getOtherName();
ApfData matchedDataV = data14.stream()
.filter(d -> Objects.equals(d.getLineId(), item.getLineId())
&& Objects.equals(d.getPhaseType(), epdPqd.getPhase()))
.findFirst()
.orElse(null);
if (matchedDataV != null) {
Object value = ReflectUtils.getValue(matchedDataV, toCamelCase(otherName));
if (value instanceof Number) {
targetDetail.setData(((Number) value).doubleValue());
}
vo.setDataTime(matchedDataV.getTime());
}
}
//一二次值处理
if (!Objects.isNull(targetDetail.getData())) {
String dataLevel = csDataSetMap.get(lineMap.get(item.getLineId()).getDataSetId()).getDataLevel();
if (Objects.equals(dataLevel, "Primary")) {
targetDetail.setUnit(targetDetail.getUnit());
targetDetail.setData(Math.round(targetDetail.getData() * 100.0) / 100.0);
} else if (Objects.equals(dataLevel, "Secondary")) {
Double ct = item.getCtRatio() / (Objects.isNull(item.getCt2Ratio())?1.0:item.getCt2Ratio());
Double pt = item.getPtRatio() / (Objects.isNull(item.getPt2Ratio())?1.0:item.getPt2Ratio());
String formula = targetDetail.getPrimaryFormula();
if (formula == null) {
targetDetail.setData(Math.round(targetDetail.getData() * 100.0) / 100.0);
}
if ("*PT".equals(formula) || "*PT*CT".equals(formula)) {
targetDetail.setUnit("k" + targetDetail.getUnit());
double finalData = DataChangeUtil.secondaryToPrimary(formula, targetDetail.getData(), pt, ct);
targetDetail.setData(Math.round((finalData/1000) * 100.0) / 100.0);
}
if ("*CT".equals(formula)) {
double finalData = DataChangeUtil.secondaryToPrimary(formula, targetDetail.getData(), pt, ct);
targetDetail.setData(Math.round(finalData * 100.0) / 100.0);
}
}
}
finalChildren.add(targetDetail);
});
});
// 根据接线方式处理相别
chanelPhase(lineMap, item, finalChildren, children2);
if (CollUtil.isNotEmpty(children2)) {
children2.sort(Comparator.comparingInt(AppLineDetailVo.targetDetail::getSort));
}
vo.setChildren(children2);
result.add(vo);
});
return result;
}
public String toCamelCase(String input) {
if (input == null || input.isEmpty()) {
return input;
}
StringBuilder result = new StringBuilder();
boolean toUpper = false;
for (char c : input.toCharArray()) {
if (c == '_') {
toUpper = true;
} else {
if (toUpper) {
result.append(Character.toUpperCase(c));
toUpper = false;
} else {
result.append(c);
}
}
}
// 确保首字母小写以匹配Java实体字段命名规范
if (result.length() > 0 && Character.isUpperCase(result.charAt(0))) {
result.setCharAt(0, Character.toLowerCase(result.charAt(0)));
}
return result.toString();
}
public int compareWithCurrentTime(String timeString) {
// 定义日期时间格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

View File

@@ -36,10 +36,7 @@ import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -264,7 +261,7 @@ public class StableDataServiceImpl implements StableDataService {
Optional.ofNullable(csLinePOList).orElseThrow(()-> new BusinessException(AlgorithmResponseEnum.LINE_DATA_ERROR));
List<CsLinePO> csLinePOList1 = csLinePOList.stream().filter(temp -> Objects.equals(areaId, temp.getPosition())).collect(Collectors.toList());
List<EleEpdPqd> data = csStatisticalSetFeignClient.queryStatisticalSelect(commonStatisticalQueryParam.getStatisticalId()).getData();
List<EleEpdPqd> data = csStatisticalSetFeignClient.queryStatisticalSelect(Collections.singletonList(commonStatisticalQueryParam.getStatisticalId())).getData();
// EleEpdPqd data = epdFeignClient.selectById(commonStatisticalQueryParam.getStatisticalId()).getData();
// Optional.ofNullable(data).orElseThrow(()-> new BusinessException(AlgorithmResponseEnum.ELEEPDPQD_DATA_ERROR));
@@ -322,80 +319,6 @@ public class StableDataServiceImpl implements StableDataService {
return result;
}
// @Override
// public List<ThdDataVO> queryLineCommonStatistical(CommonStatisticalQueryParam commonStatisticalQueryParam) {
// List<ThdDataVO> result = new ArrayList();
// if(CollectionUtil.isEmpty(commonStatisticalQueryParam.getLineList())){
// throw new BusinessException(AlgorithmResponseEnum.LINE_DATA_ERROR);
// }
// List<CsLinePO> csLinePOList = csLineFeignClient.queryLineById(commonStatisticalQueryParam.getLineList()).getData();
// if(CollectionUtil.isEmpty(csLinePOList)){
// throw new BusinessException(AlgorithmResponseEnum.LINE_DATA_ERROR);
// }
//
// LineParamDTO lineParamDTO = new LineParamDTO();
// lineParamDTO.setLineId(commonStatisticalQueryParam.getLineList().get(0));
// List<CsLedger> csLedgers = csLedgerFeignClient.queryLine(lineParamDTO).getData();
// List<CsEquipmentDeliveryDTO> data1 = equipmentFeignClient.queryDeviceById(Stream.of(csLedgers.get(0).getPid()).collect(Collectors.toList())).getData();
//
//
// List<String> collect = csLinePOList.stream().map(CsLinePO::getLineId).collect(Collectors.toList());
// String areaId = dicDataFeignClient.getDicDataByCode(DicDataEnum.OUTPUT_SIDE.getCode()).getData().getId();
// Optional.ofNullable(csLinePOList).orElseThrow(()-> new BusinessException(AlgorithmResponseEnum.LINE_DATA_ERROR));
//// collect = csLinePOList.stream().filter(temp->Objects.equals(areaId,temp.getPosition())).map(CsLinePO::getLineId).collect(Collectors.toList());
//
// List<EleEpdPqd> data = csStatisticalSetFeignClient.queryStatisticalSelect(commonStatisticalQueryParam.getStatisticalId()).getData();
//
//// EleEpdPqd data = epdFeignClient.selectById(commonStatisticalQueryParam.getStatisticalId()).getData();
// Optional.ofNullable(data).orElseThrow(()-> new BusinessException(AlgorithmResponseEnum.ELEEPDPQD_DATA_ERROR));
//
// String frequency = Optional.ofNullable(commonStatisticalQueryParam.getFrequency()).orElse("");
// if(CollectionUtil.isNotEmpty(data)){
// List<String> finalCollect = collect;
// data.forEach(epdPqd->{
// List<CommonQueryParam> commonQueryParams = finalCsLinePOList.stream().map(temp -> {
// CommonQueryParam commonQueryParam = new CommonQueryParam();
// commonQueryParam.setLineId(temp.getLineId());
// commonQueryParam.setTableName(getTableNameByClassId(epdPqd.getClassId()));
// commonQueryParam.setColumnName(epdPqd.getName()+ finalFrequency1);
// commonQueryParam.setPhasic(epdPqd.getPhase());
// commonQueryParam.setStartTime(commonStatisticalQueryParam.getStartTime());
// commonQueryParam.setEndTime(commonStatisticalQueryParam.getEndTime());
// commonQueryParam.setDataType(commonStatisticalQueryParam.getValueType());
// commonQueryParam.setProcess(data1.get(0).getProcess()+"");
// commonQueryParam.setClDid(getClDidByLineId(temp.getLineId()));
//
// return commonQueryParam;
// }).collect(Collectors.toList());
// List<StatisticalDataDTO> deviceRtData = commonService.getDeviceRtDataByTime(finalCollect, epdPqd.getClassId(), epdPqd.getName()+frequency, epdPqd.getPhase(), commonStatisticalQueryParam.getValueType(),commonStatisticalQueryParam.getStartTime(),commonStatisticalQueryParam.getEndTime(),data1.get(0).getProcess()+"");
//
//
// List<ThdDataVO> collect1 = deviceRtData.stream().map(temp -> {
// ThdDataVO vo = new ThdDataVO();
// vo.setLineId(temp.getLineId());
// vo.setPhase(temp.getPhaseType());
// String position = csLinePOList.stream().filter(csLinePO -> Objects.equals(csLinePO.getLineId(), vo.getLineId())).collect(Collectors.toList()).get(0).getPosition();
// String lineName = csLinePOList.stream().filter(csLinePO -> Objects.equals(csLinePO.getLineId(), vo.getLineId())).collect(Collectors.toList()).get(0).getName();
//
// vo.setLineName(lineName);
// vo.setPosition(position);
// vo.setTime(temp.getTime());
// vo.setStatMethod(temp.getValueType());
// vo.setStatisticalData(Double.valueOf(df.format(temp.getValue())));
// vo.setStatisticalIndex(epdPqd.getId());
// vo.setUnit(epdPqd.getUnit());
// vo.setStatisticalName(epdPqd.getName());
// vo.setAnotherName(epdPqd.getShowName());
// return vo;
// }).collect(Collectors.toList());
// collect1 = collect1.stream().distinct().collect(Collectors.toList());
// result.addAll(collect1);
// });
// }
//
// return result;
// }
private String phaseReflection(String phase){
switch (phase) {
case "AB":

View File

@@ -99,6 +99,12 @@
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.njcn</groupId>
<artifactId>cs-system-api</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.njcn</groupId>

View File

@@ -24,14 +24,13 @@ import com.njcn.csharmonic.api.SysExcelRelationFeignClient;
import com.njcn.csharmonic.enums.CsHarmonicResponseEnum;
import com.njcn.csharmonic.pojo.param.StatSubstationBizBaseParam;
import com.njcn.csharmonic.pojo.po.CsEventPO;
import com.njcn.csharmonic.pojo.po.CsHarmonic;
import com.njcn.csharmonic.pojo.po.RStatLimitRateDPO;
import com.njcn.csharmonic.pojo.vo.HarmonicVO;
import com.njcn.csreport.mapper.CsAppReportMapper;
import com.njcn.csreport.pojo.po.CsAppReport;
import com.njcn.csreport.pojo.vo.ReportEventVO;
import com.njcn.csreport.pojo.vo.ReportHarmonicVO;
import com.njcn.csreport.service.ICsAppReportService;
import com.njcn.cssystem.utils.TimeUtil;
import com.njcn.device.biz.pojo.po.PqsDeviceUnit;
import com.njcn.device.pq.pojo.vo.AreaLineInfoVO;
import com.njcn.event.common.service.CommMonitorEventReportService;
@@ -113,7 +112,7 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
rStatLimitQueryParam.setStartTime(queryStartTime);
rStatLimitQueryParam.setEndTime(queryEndTime);
List<RStatLimitRateDPO> limitRates = rStatLimitRateDClient.getLinesRate(rStatLimitQueryParam).getData();
CsLinePO po = csLineFeignClient.getById(param.getLineId()).getData();
return timeRanges.stream().map(weekRange -> {
List<RStatLimitRateDPO> weekData = limitRates.stream()
.filter(rate -> !rate.getTime().isBefore(weekRange.start) && !rate.getTime().isAfter(weekRange.end))
@@ -121,10 +120,10 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
ReportHarmonicVO vo = new ReportHarmonicVO();
vo.setLineId(param.getLineId());
vo.setLineName(csLineFeignClient.getById(param.getLineId()).getData().getName());
vo.setLineName(po.getName());
vo.setStartTime(weekRange.start.format(DateTimeFormatter.ISO_LOCAL_DATE));
vo.setEndTime(weekRange.end.format(DateTimeFormatter.ISO_LOCAL_DATE));
vo.setOverLimitDesc(buildOverLimitDesc(weekData));
vo.setOverLimitDesc(buildOverLimitDesc(weekData,po.getLineInterval()));
return vo;
}).collect(Collectors.toList());
}
@@ -398,12 +397,15 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
return ranges;
}
private List<TimeRange> splitIntoMonthsForCurrentYear(LocalDate endDate) {
private List<TimeRange> splitIntoMonthsForCurrentYear(LocalDate now) {
List<TimeRange> timeRanges = new ArrayList<>();
LocalDate now = LocalDate.now();
int currentYear = now.getYear();
for (int month = now.getMonthValue(); month >= 1; month--) {
int nowYear = LocalDate.now().getYear();
int num = LocalDate.now().getMonthValue();
if (currentYear < nowYear) {
num = 12;
}
for (int month = num; month >= 1; month--) {
LocalDate monthStart = LocalDate.of(currentYear, month, 1);
LocalDate monthEnd;
@@ -420,8 +422,12 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
//fixme 代码较为冗余,后期可以采用反射的方式进行优化
private String buildOverLimitDesc(List<RStatLimitRateDPO> dataList) {
private String buildOverLimitDesc(List<RStatLimitRateDPO> dataList,Integer lineInterval) {
String tag = "";
if (Objects.isNull(lineInterval)) {
lineInterval = 1;
}
int maxData = dataList.size() * 24 * 60;
RStatLimitRateDPO result = new RStatLimitRateDPO();
if (CollectionUtil.isNotEmpty(dataList)) {
int data1 = 0,data2 = 0,data3 = 0,data4 = 0,data5 = 0,data6 = 0,data7 = 0,data8 = 0,data9 = 0,data10 = 0
@@ -651,42 +657,42 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
// 基础越限项
Integer freqDevOvertime = result.getFreqDevOvertime();
if (freqDevOvertime > 0) {
tag = tag + "频率偏差越限" + freqDevOvertime + "";
tag = tag + "频率偏差越限" + TimeUtil.convertMinutes(Math.min(freqDevOvertime * lineInterval,maxData)) + "";
}
Integer voltageDevOvertime = result.getVoltageDevOvertime();
if (voltageDevOvertime > 0) {
tag = tag + "电压偏差越限" + voltageDevOvertime + "";
tag = tag + "电压偏差越限" + TimeUtil.convertMinutes(Math.min(voltageDevOvertime * lineInterval,maxData)) + "";
}
Integer ubalanceOvertime = result.getUbalanceOvertime();
if (ubalanceOvertime > 0) {
tag = tag + "三相电压不平衡度越限" + ubalanceOvertime + "";
tag = tag + "三相电压不平衡度越限" + TimeUtil.convertMinutes(Math.min(ubalanceOvertime * lineInterval,maxData)) + "";
}
Integer flickerOvertime = result.getFlickerOvertime();
if (flickerOvertime > 0) {
tag = tag + "闪变越限" + flickerOvertime + "";
tag = tag + "闪变越限" + TimeUtil.convertMinutes(Math.min(flickerOvertime * lineInterval,maxData)) + "";
}
Integer uaberranceOvertime = result.getUaberranceOvertime();
if (uaberranceOvertime > 0) {
tag = tag + "电压总谐波畸变率越限" + uaberranceOvertime + "";
tag = tag + "电压总谐波畸变率越限" + TimeUtil.convertMinutes(Math.min(uaberranceOvertime * lineInterval,maxData)) + "";
}
Integer iNegOvertime = result.getINegOvertime();
if (iNegOvertime > 0) {
tag = tag + "负序电流越限" + iNegOvertime + "";
tag = tag + "负序电流越限" + TimeUtil.convertMinutes(Math.min(iNegOvertime * lineInterval,maxData)) + "";
}
// 谐波电压含有率2-25 次)
tag = buildHarmonicVoltageTags(result, tag);
tag = buildHarmonicVoltageTags(result, tag, lineInterval, maxData);
// 谐波电流有效值2-25 次)
tag = buildHarmonicCurrentTags(result, tag);
tag = buildHarmonicCurrentTags(result, tag, lineInterval, maxData);
// 间谐波电压含有率0.5-15.5 次)
tag = buildInterharmonicVoltageTags(result, tag);
tag = buildInterharmonicVoltageTags(result, tag, lineInterval, maxData);
// 去除末尾逗号
return trimTrailingComma(tag);
@@ -709,13 +715,13 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
* @param originalTag 原始 tag
* @return 组装后的 tag
*/
public static String buildHarmonicVoltageTags(Object item, String originalTag) {
public static String buildHarmonicVoltageTags(Object item, String originalTag, Integer lineInterval, Integer maxData) {
String tag = originalTag;
for (int i = 2; i <= 25; i++) {
String fieldName = "uharm" + i + "Overtime";
Integer value = (Integer) ReflectUtil.getFieldValue(item, fieldName);
if (value != null && value > 0) {
tag = tag + i + "次谐波电压含有率越限" + value + "";
tag = tag + i + "次谐波电压含有率越限" + TimeUtil.convertMinutes(Math.min(value*lineInterval,maxData)) + "";
}
}
return tag;
@@ -728,13 +734,13 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
* @param originalTag 原始 tag
* @return 组装后的 tag
*/
public static String buildHarmonicCurrentTags(Object item, String originalTag) {
public static String buildHarmonicCurrentTags(Object item, String originalTag, Integer lineInterval, Integer maxData) {
String tag = originalTag;
for (int i = 2; i <= 25; i++) {
String fieldName = "iharm" + i + "Overtime";
Integer value = (Integer) ReflectUtil.getFieldValue(item, fieldName);
if (value != null && value > 0) {
tag = tag + i + "次谐波电流有效值越限" + value + "";
tag = tag + i + "次谐波电流有效值越限" + TimeUtil.convertMinutes(Math.min(value*lineInterval,maxData)) + "";
}
}
return tag;
@@ -747,14 +753,14 @@ public class CsAppReportServiceImpl extends ServiceImpl<CsAppReportMapper, CsApp
* @param originalTag 原始 tag
* @return 组装后的 tag
*/
public static String buildInterharmonicVoltageTags(Object item, String originalTag) {
public static String buildInterharmonicVoltageTags(Object item, String originalTag, Integer lineInterval, Integer maxData) {
String tag = originalTag;
for (int i = 1; i <= 16; i++) {
String fieldName = "inuharm" + i + "Overtime";
Integer value = (Integer) ReflectUtil.getFieldValue(item, fieldName);
if (value != null && value > 0) {
double harmonicOrder = i * 1.0 - 0.5;
tag = tag + harmonicOrder + "次间谐波电压含有率越限" + value + "";
tag = tag + harmonicOrder + "次间谐波电压含有率越限" + TimeUtil.convertMinutes(Math.min(value*lineInterval,maxData)) + "";
}
}
return tag;

View File

@@ -0,0 +1,52 @@
package com.njcn.cssystem.utils;
public class TimeUtil {
/**
* 将分钟数转换为友好显示格式
* @param totalMinutes 总分钟数
* @return 格式化后的字符串
*/
public static String convertMinutes(int totalMinutes) {
if (totalMinutes < 0) {
return "0分钟";
}
int days = 0;
int hours = 0;
int minutes = totalMinutes;
// 计算天数超过24小时
if (minutes >= 1440) { // 24 * 60 = 1440
days = minutes / 1440;
minutes = minutes % 1440;
}
// 计算小时数剩余分钟超过60分钟
if (minutes >= 60) {
hours = minutes / 60;
minutes = minutes % 60;
}
// 构建返回字符串
StringBuilder result = new StringBuilder();
if (days > 0) {
result.append(days).append("");
}
if (hours > 0) {
result.append(hours).append("小时");
}
if (minutes > 0) {
result.append(minutes).append("分钟");
}
// 如果全部为0
if (result.length() == 0) {
result.append("0分钟");
}
return result.toString();
}
}

View File

@@ -24,6 +24,7 @@ import com.njcn.csharmonic.pojo.po.*;
import com.njcn.cssystem.pojo.po.CsAlarmSet;
import com.njcn.cssystem.service.ICsAlarmSetService;
import com.njcn.cssystem.service.IDataTaskService;
import com.njcn.cssystem.utils.TimeUtil;
import com.njcn.influx.imapper.PqsCommunicateMapper;
import com.njcn.influx.pojo.po.PqsCommunicate;
import com.njcn.influx.query.InfluxQueryWrapper;
@@ -898,32 +899,32 @@ public class DataTaskServiceImpl implements IDataTaskService {
if (targetSet != null) {
Integer freqDevOvertime = item.getFreqDevOvertime();
if (freqDevOvertime != null && freqDevOvertime > 0 && targetSet.contains("频率偏差")) {
tagBuilder.append("频率偏差越限").append(Math.min(freqDevOvertime * lineInterval,1440)).append("分钟");
tagBuilder.append("频率偏差越限").append(TimeUtil.convertMinutes(Math.min(freqDevOvertime * lineInterval,1440))).append("");
}
Integer voltageDevOvertime = item.getVoltageDevOvertime();
if (voltageDevOvertime != null && voltageDevOvertime > 0 && targetSet.contains("电压偏差")) {
tagBuilder.append("电压偏差越限").append(Math.min(voltageDevOvertime * lineInterval,1440)).append("分钟");
tagBuilder.append("电压偏差越限").append(TimeUtil.convertMinutes(Math.min(voltageDevOvertime * lineInterval,1440))).append("");
}
Integer ubalanceOvertime = item.getUbalanceOvertime();
if (ubalanceOvertime != null && ubalanceOvertime > 0 && targetSet.contains("三相电压不平衡度")) {
tagBuilder.append("三相电压不平衡度越限").append(Math.min(ubalanceOvertime * lineInterval,1440)).append("分钟");
tagBuilder.append("三相电压不平衡度越限").append(TimeUtil.convertMinutes(Math.min(ubalanceOvertime * lineInterval,1440))).append("");
}
Integer flickerOvertime = item.getFlickerOvertime();
if (flickerOvertime != null && flickerOvertime > 0 && targetSet.contains("闪变")) {
tagBuilder.append("闪变越限").append(Math.min(flickerOvertime * 120,1440)).append("分钟");
tagBuilder.append("闪变越限").append(TimeUtil.convertMinutes(Math.min(flickerOvertime * 120,1440))).append("");
}
Integer uaberranceOvertime = item.getUaberranceOvertime();
if (uaberranceOvertime != null && uaberranceOvertime > 0 && targetSet.contains("电压总谐波畸变率")) {
tagBuilder.append("电压总谐波畸变率越限").append(Math.min(uaberranceOvertime * lineInterval,1440)).append("分钟");
tagBuilder.append("电压总谐波畸变率越限").append(TimeUtil.convertMinutes(Math.min(uaberranceOvertime * lineInterval,1440))).append("");
}
Integer iNegOvertime = item.getINegOvertime();
if (iNegOvertime != null && iNegOvertime > 0 && targetSet.contains("负序电流")) {
tagBuilder.append("负序电流越限").append(Math.min(iNegOvertime * lineInterval,1440)).append("分钟");
tagBuilder.append("负序电流越限").append(TimeUtil.convertMinutes(Math.min(iNegOvertime * lineInterval,1440))).append("");
}
for (int i = 2; i <= 25; i++) {
@@ -932,7 +933,7 @@ public class DataTaskServiceImpl implements IDataTaskService {
if (value != null && value > 0) {
String targetName = i + "次谐波电压含有率";
if (targetSet.contains(targetName)) {
tagBuilder.append(i).append("次谐波电压含有率越限").append(Math.min(value * lineInterval,1440)).append("分钟");
tagBuilder.append(i).append("次谐波电压含有率越限").append(TimeUtil.convertMinutes(Math.min(value * lineInterval,1440))).append("");
}
}
}
@@ -943,7 +944,7 @@ public class DataTaskServiceImpl implements IDataTaskService {
if (value != null && value > 0) {
String targetName = i + "次谐波电流有效值";
if (targetSet.contains(targetName)) {
tagBuilder.append(i).append("次谐波电流有效值越限").append(Math.min(value * lineInterval,1440)).append("分钟");
tagBuilder.append(i).append("次谐波电流有效值越限").append(TimeUtil.convertMinutes(Math.min(value * lineInterval,1440))).append("");
}
}
}
@@ -955,39 +956,39 @@ public class DataTaskServiceImpl implements IDataTaskService {
double harmonicOrder = i * 1.0 - 0.5;
String targetName = harmonicOrder + "次间谐波电压含有率";
if (targetSet.contains(targetName)) {
tagBuilder.append(harmonicOrder).append("次间谐波电压含有率越限").append(Math.min(value * lineInterval,1440)).append("分钟");
tagBuilder.append(harmonicOrder).append("次间谐波电压含有率越限").append(TimeUtil.convertMinutes(Math.min(value * lineInterval,1440))).append("");
}
}
}
} else {
Integer freqDevOvertime = item.getFreqDevOvertime();
if (freqDevOvertime != null && freqDevOvertime > 0) {
tagBuilder.append("频率偏差越限").append(Math.min(freqDevOvertime * lineInterval,1440)).append("分钟");
tagBuilder.append("频率偏差越限").append(TimeUtil.convertMinutes(Math.min(freqDevOvertime * lineInterval,1440))).append("");
}
Integer voltageDevOvertime = item.getVoltageDevOvertime();
if (voltageDevOvertime != null && voltageDevOvertime > 0) {
tagBuilder.append("电压偏差越限").append(Math.min(voltageDevOvertime * lineInterval,1440)).append("分钟");
tagBuilder.append("电压偏差越限").append(TimeUtil.convertMinutes(Math.min(voltageDevOvertime * lineInterval,1440))).append("");
}
Integer ubalanceOvertime = item.getUbalanceOvertime();
if (ubalanceOvertime != null && ubalanceOvertime > 0) {
tagBuilder.append("三相电压不平衡度越限").append(Math.min(ubalanceOvertime * lineInterval,1440)).append("分钟");
tagBuilder.append("三相电压不平衡度越限").append(TimeUtil.convertMinutes(Math.min(ubalanceOvertime * lineInterval,1440))).append("");
}
Integer flickerOvertime = item.getFlickerOvertime();
if (flickerOvertime != null && flickerOvertime > 0) {
tagBuilder.append("闪变越限").append(Math.min(flickerOvertime * 120,1440)).append("分钟,");
tagBuilder.append("闪变越限").append(TimeUtil.convertMinutes(Math.min(flickerOvertime * 120,1440))).append("分钟,");
}
Integer uaberranceOvertime = item.getUaberranceOvertime();
if (uaberranceOvertime != null && uaberranceOvertime > 0) {
tagBuilder.append("电压总谐波畸变率越限").append(Math.min(uaberranceOvertime * lineInterval,1440)).append("分钟");
tagBuilder.append("电压总谐波畸变率越限").append(TimeUtil.convertMinutes(Math.min(uaberranceOvertime * lineInterval,1440))).append("");
}
Integer iNegOvertime = item.getINegOvertime();
if (iNegOvertime != null && iNegOvertime > 0) {
tagBuilder.append("负序电流越限").append(Math.min(iNegOvertime * lineInterval,1440)).append("分钟");
tagBuilder.append("负序电流越限").append(TimeUtil.convertMinutes(Math.min(iNegOvertime * lineInterval,1440))).append("");
}
String harmonicVoltageTag = buildHarmonicVoltageTags(item, "", lineInterval);
@@ -1022,7 +1023,7 @@ public class DataTaskServiceImpl implements IDataTaskService {
String fieldName = "uharm" + i + "Overtime";
Integer value = (Integer) ReflectUtil.getFieldValue(item, fieldName);
if (value != null && value > 0) {
tag.append(i).append("次谐波电压含有率越限").append(Math.min(value * lineInterval,1440)).append("分钟");
tag.append(i).append("次谐波电压含有率越限").append(TimeUtil.convertMinutes(Math.min(value * lineInterval,1440))).append("");
}
}
return tag.toString();
@@ -1041,7 +1042,7 @@ public class DataTaskServiceImpl implements IDataTaskService {
String fieldName = "iharm" + i + "Overtime";
Integer value = (Integer) ReflectUtil.getFieldValue(item, fieldName);
if (value != null && value > 0) {
tag.append(i).append("次谐波电流有效值越限").append(Math.min(value * lineInterval,1440)).append("分钟");
tag.append(i).append("次谐波电流有效值越限").append(TimeUtil.convertMinutes(Math.min(value * lineInterval,1440))).append("");
}
}
return tag.toString();
@@ -1061,7 +1062,7 @@ public class DataTaskServiceImpl implements IDataTaskService {
Integer value = (Integer) ReflectUtil.getFieldValue(item, fieldName);
if (value != null && value > 0) {
double harmonicOrder = i * 1.0 - 0.5;
tag.append(harmonicOrder).append("次间谐波电压含有率越限").append(Math.min(value * lineInterval,1440)).append("分钟");
tag.append(harmonicOrder).append("次间谐波电压含有率越限").append(TimeUtil.convertMinutes(Math.min(value * lineInterval,1440))).append("");
}
}
return tag.toString();

View File

@@ -5,7 +5,10 @@ import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.njcn.access.pojo.dto.NoticeUserDto;
import com.njcn.access.utils.SendMessageUtil;
import com.njcn.csdevice.api.*;
import com.njcn.csdevice.api.CsLedgerFeignClient;
import com.njcn.csdevice.api.DeviceMessageFeignClient;
import com.njcn.csdevice.api.EquipmentFeignClient;
import com.njcn.csdevice.api.EventLogsFeignClient;
import com.njcn.csdevice.param.DeviceMessageParam;
import com.njcn.csdevice.pojo.dto.DevDetailDTO;
import com.njcn.csdevice.pojo.po.CsEventSendMsg;
@@ -15,6 +18,7 @@ import com.njcn.cssystem.pojo.param.MsgSendParam;
import com.njcn.cssystem.service.ICsEventUserService;
import com.njcn.cssystem.service.IMsgSendService;
import com.njcn.system.api.EpdFeignClient;
import com.njcn.user.api.SmsSendFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.User;
import lombok.RequiredArgsConstructor;