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

@@ -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()));